<commit_before>// @flow

import type {LoggerType} from './types.js';

const debug = require('debug');
const path = require('path');
const createColoredLogPrefix = require('./_lib/createColoredLogPrefix.js');

function logger(namespace: string, type: string, ...args: Array<any>): void {
	const prefix = createColoredLogPrefix(namespace, type);

	return debug(prefix)(...args);
}

function resolvePkgJsonName(): string {
	const pkgJsonPath = path.resolve('package.json');
	const pkg: {name?: string} = require(pkgJsonPath);

	if (!pkg.name) {
		throw new Error(`No "name" property found in "${pkgJsonPath}", either set a name or provide a namespace to the createLogger() function.`);
	}

	return pkg.name;
}

function createLogger(arg?: string): LoggerType {
	const namespace = arg || resolvePkgJsonName();
	const log = logger.bind(null, namespace);
	const api = {
		enforceLogging() {
			debug.enable(`*${namespace}*`);

			return api;
		},
		fatal(...args: Array<any>) {
			const stack = new Error().stack.split('\n').splice(2);

			console.error(
				createColoredLogPrefix(namespace, 'fatal'),
				...args,
				'\n',
				stack.join('\n')
			);

			try {
				process.exit(1);
			} catch (e) {}
		},
		error: log.bind(null, 'error'),
		success: log.bind(null, 'success'),
		warn: log.bind(null, 'warn'),
		info: log.bind(null, 'info'),
		debug: log.bind(null, 'debug'),
		log: log.bind(null, 'log')
	};

	return api;
}

module.exports = createLogger;
<commit_msg>BUGFIX: Fix a typo annotation during the automatic resolving of the loggers name in node<commit_after>// @flow

import type {LoggerType} from './types.js';

const debug = require('debug');
const path = require('path');
const createColoredLogPrefix = require('./_lib/createColoredLogPrefix.js');

function logger(namespace: string, type: string, ...args: Array<any>): void {
	const prefix = createColoredLogPrefix(namespace, type);

	return debug(prefix)(...args);
}

function resolvePkgJsonName(): string {
	const pkgJsonPath = path.resolve('package.json');
	const pkg: {name: string} = require(pkgJsonPath);

	if (!pkg.name) {
		throw new Error(`No "name" property found in "${pkgJsonPath}", either set a name or provide a namespace to the createLogger() function.`);
	}

	return pkg.name;
}

function createLogger(arg?: string): LoggerType {
	const namespace = arg || resolvePkgJsonName();
	const log = logger.bind(null, namespace);
	const api = {
		enforceLogging() {
			debug.enable(`*${namespace}*`);

			return api;
		},
		fatal(...args: Array<any>) {
			const stack = new Error().stack.split('\n').splice(2);

			console.error(
				createColoredLogPrefix(namespace, 'fatal'),
				...args,
				'\n',
				stack.join('\n')
			);

			try {
				process.exit(1);
			} catch (e) {}
		},
		error: log.bind(null, 'error'),
		success: log.bind(null, 'success'),
		warn: log.bind(null, 'warn'),
		info: log.bind(null, 'info'),
		debug: log.bind(null, 'debug'),
		log: log.bind(null, 'log')
	};

	return api;
}

module.exports = createLogger;
<|endoftext|>


<commit_before>define(['app', 'lodash'], function(app, _) {

    app.factory("mongoStorage", ['$http','$rootScope', function($http,$rootScope) {

        var clientOrg = 0; // means cbd

        //============================================================
        //
        //============================================================
        function saveRes(res) {
            var url = '/api/v2016/reservations';
            var doc = _.cloneDeep(res);
            if (doc.sideEvent) delete(doc.sideEvent);
            var params = {};
            if (!doc.clientOrg) doc.clientOrg = clientOrg;

            if(!doc.start || !doc.end || !location) throw "Error missing start or end time or location.";

                      if (doc._id) {
                          params.id = doc._id;
                          url = url + '/' + doc._id;

                          return $http.patch(url, doc, {
                              'params': params
                          });
                      } else {
                          return $http.post(url, doc, params);
                      } //create

        }

        //============================================================
        //
        //============================================================
        function save(schema, doc) {
            var url = '/api/v2016/' + schema;

            var params = {};
            if (!doc.clientOrg) doc.clientOrg = clientOrg;
            if (doc._id) {
                params.id = doc._id;
                url = url + '/' + doc._id;

                return $http.put(url, doc, params);
            } else {
                return $http.post(url, doc, params);
            } //create
        }

        //============================================================
        //
        //============================================================
        function getReservations(start, end, location, type) {

            var params = {};

            params = {
                q: {
                    'location.venue': location.venue,
                    'location.room': location.room,
                    '$and': [{
                        'start': {
                            '$gt': {
                                '$date': (start * 1000)
                            }
                        }
                    }, {
                        'end': {
                            '$lt': {
                                '$date': end * 1000
                            }
                        }
                    }],
                    'meta.status': {
                        $nin: ['archived', 'deleted']
                    },
                    'sideEvent.meta.status': {
                        $nin: ['archived', 'deleted']
                    }
                }
            };

            //TODO search if parent and if yes search for parent or children
            if (type && _.isString(type)) {
                return getChildrenTypes(type).then(function(typeArr) {
                    params.q.$and.push({
                        'type': {
                            '$in': typeArr
                        }
                    });
                    return $http.get('/api/v2016/reservations', {
                        'params': params
                    });
                });
            } else
                return $http.get('/api/v2016/reservations', {
                    'params': params
                });
        } // getDocs

        //============================================================
        //
        //============================================================
        function getReservation(id) {

            var params = {};

            return $http.get('/api/v2016/reservations/' + id, {
                'params': params
            });
        } // getDocs
        //============================================================
        //
        //============================================================
        function getRecurrences(parent) {

            var params = {};
            if(!parent) throw "Error: no parent id passed to getReccurences.";
            params ={ q: {
                'meta.status': {
                    $nin: ['archived', 'deleted']
                },
                'sideEvent.meta.status': {
                    $nin: ['archived', 'deleted']
                }
            }};

            params.q.parent=parent;

            return   $http.get('/api/v2016/reservations/', {
                  'params': params
              });
        } // getReccurences

        //============================================================
        //
        //============================================================
        function getDocs(schema, status, cache) {
            if (!cache) cache = false;
            var params = {};
            if (!schema) throw "Error: failed to indicate schema loadOwnerDocs";
            if (!status) {
                params = {
                    q: {
                        'meta.status': {
                            $nin: ['archived', 'deleted']
                        }
                    },

                };
                return $http.get('/api/v2016/' + schema, {
                    'params': params,
                    'cache': cache
                });
            }
            if (!_.isArray(status)) {
                params = {
                    q: {
                        'meta.status': status
                    }
                };
                return $http.get('/api/v2016/' + schema, {
                    'params': params,
                    'cache': cache
                });
            } else {
                params = {
                    q: {
                        'meta.status': {
                            $in: status
                        }
                    }
                };
                return $http.get('/api/v2016/' + schema, {
                    'params': params,
                    'cache': cache
                });
            }
        } // getDocs

        //============================================================
        //
        //============================================================
        function getAllOrgs() {

            var params = {
                q: {
                    'meta.status': 'published'
                }
            };
            return $http.get('/api/v2016/inde-orgs', {
                'params': params,
                'cache': true
            });

        } // getDocs

        //=======================================================================
        //
        //=======================================================================
        function deleteDoc(schema, docObj, _id) {
            if (!docObj.meta) docObj.meta = {};
            docObj.meta.status = 'deleted';
            return save(schema, docObj, _id);
        }

        //============================================================
        //
        //============================================================
        function getConferenceRooms(id) {

            return $http.get('/api/v2016/conferences/' + id + '/rooms', {});
        } // getConferenceRooms

        //============================================================
        //
        //============================================================
        function getConferences() {

            var params = {};

            params = {
                q: {
                    'meta.status': {
                        $nin: ['archived', 'deleted']
                    }
                },
                s: {
                    'start': -1
                }
            };
            return $http.get('/api/v2016/conferences', {
                'params': params,
                'cache': true
            });
        }

        //============================================================
        //
        //============================================================
        function getUnscheduledSideEvents(meeting) {
            var params = {};
            params = {
                q: {
                    'link.meeting': meeting,
                    'sideEvent.meta.status': 'published',
                    'start': {
                        '$exists': 0
                    }
                }

            };
            return $http.get('/api/v2016/reservations', {
                'params': params
            });
        }

        //============================================================
        //
        //============================================================
        function getChildrenTypes(type) {
            var types = [];
            types.push(type);
            var params = {
                q: {
                    'parent': type
                }
            };
            return $http.get('/api/v2016/reservation-types', {
                'params': params
            }).then(function(responce) {
                _.each(responce.data, function(t) {
                    types.push(t._id);
                });
                return types;
            });

        } //loadSideEventTypes

        //============================================================
        //
        //============================================================
        function syncSideEvents(conferenceId) {
            if (!conferenceId) throw "Error no confrence selected to sync";
            return $http.get('/api/v2016/reservations/sync/side-events/' + conferenceId);
        }

        return {
            getRecurrences:getRecurrences,
            getReservation: getReservation,
            getConferences: getConferences,
            getAllOrgs: getAllOrgs,
            saveRes: saveRes,
            syncSideEvents: syncSideEvents,
            deleteDoc: deleteDoc,
            save: save,
            getConferenceRooms: getConferenceRooms,
            getUnscheduledSideEvents: getUnscheduledSideEvents,
            getReservations: getReservations,
            getDocs: getDocs,
        }; //return
    }]); //factory
}); //require<commit_msg>fix save function<commit_after>define(['app', 'lodash'], function(app, _) {

    app.factory("mongoStorage", ['$http','$rootScope', function($http,$rootScope) {

        var clientOrg = 0; // means cbd

        //============================================================
        //
        //============================================================
        function saveRes(res) {
            var url = '/api/v2016/reservations';
            var doc = _.cloneDeep(res);
            if (doc.sideEvent) delete(doc.sideEvent);
            var params = {};
            if (!doc.clientOrg) doc.clientOrg = clientOrg;

            if(!doc.start || !doc.end || !location) throw "Error missing start or end time or location.";

                      if (doc._id) {
                          params.id = doc._id;
                          url = url + '/' + doc._id;

                          return $http.patch(url, doc, {
                              'params': params
                          });
                      } else {
                          return $http.post(url, doc, params);
                      } //create
        }

        //============================================================
        //
        //============================================================
        function save(schema, doc) {
            var url = '/api/v2016/' + schema;

            var params = {};
            if (!doc.clientOrg) doc.clientOrg = clientOrg;
            if (doc._id) {
                params.id = doc._id;
                url = url + '/' + doc._id;

                return $http.patch(url, doc, params);
            } else {
                return $http.post(url, doc, params);
            } //create
        }

        //============================================================
        //
        //============================================================
        function getReservations(start, end, location, type) {

            var params = {};

            params = {
                q: {
                    'location.venue': location.venue,
                    'location.room': location.room,
                    '$and': [{
                        'start': {
                            '$gt': {
                                '$date': (start * 1000)
                            }
                        }
                    }, {
                        'end': {
                            '$lt': {
                                '$date': end * 1000
                            }
                        }
                    }],
                    'meta.status': {
                        $nin: ['archived', 'deleted']
                    },
                    'sideEvent.meta.status': {
                        $nin: ['archived', 'deleted']
                    }
                }
            };

            //TODO search if parent and if yes search for parent or children
            if (type && _.isString(type)) {
                return getChildrenTypes(type).then(function(typeArr) {
                    params.q.$and.push({
                        'type': {
                            '$in': typeArr
                        }
                    });
                    return $http.get('/api/v2016/reservations', {
                        'params': params
                    });
                });
            } else
                return $http.get('/api/v2016/reservations', {
                    'params': params
                });
        } // getDocs

        //============================================================
        //
        //============================================================
        function getReservation(id) {

            var params = {};

            return $http.get('/api/v2016/reservations/' + id, {
                'params': params
            });
        } // getDocs
        //============================================================
        //
        //============================================================
        function getRecurrences(parent) {

            var params = {};
            if(!parent) throw "Error: no parent id passed to getReccurences.";
            params ={ q: {
                'meta.status': {
                    $nin: ['archived', 'deleted']
                },
                'sideEvent.meta.status': {
                    $nin: ['archived', 'deleted']
                }
            }};

            params.q.parent=parent;

            return   $http.get('/api/v2016/reservations/', {
                  'params': params
              });
        } // getReccurences

        //============================================================
        //
        //============================================================
        function getDocs(schema, status, cache) {
            if (!cache) cache = false;
            var params = {};
            if (!schema) throw "Error: failed to indicate schema loadOwnerDocs";
            if (!status) {
                params = {
                    q: {
                        'meta.status': {
                            $nin: ['archived', 'deleted']
                        }
                    },

                };
                return $http.get('/api/v2016/' + schema, {
                    'params': params,
                    'cache': cache
                });
            }
            if (!_.isArray(status)) {
                params = {
                    q: {
                        'meta.status': status
                    }
                };
                return $http.get('/api/v2016/' + schema, {
                    'params': params,
                    'cache': cache
                });
            } else {
                params = {
                    q: {
                        'meta.status': {
                            $in: status
                        }
                    }
                };
                return $http.get('/api/v2016/' + schema, {
                    'params': params,
                    'cache': cache
                });
            }
        } // getDocs

        //============================================================
        //
        //============================================================
        function getAllOrgs() {

            var params = {
                q: {
                    'meta.status': 'published'
                }
            };
            return $http.get('/api/v2016/inde-orgs', {
                'params': params,
                'cache': true
            });

        } // getDocs

        //=======================================================================
        //
        //=======================================================================
        function deleteDoc(schema, docObj, _id) {
            if (!docObj.meta) docObj.meta = {};
            docObj.meta.status = 'deleted';
            return save(schema, docObj, _id);
        }

        //============================================================
        //
        //============================================================
        function getConferenceRooms(id) {

            return $http.get('/api/v2016/conferences/' + id + '/rooms', {});
        } // getConferenceRooms

        //============================================================
        //
        //============================================================
        function getConferences() {

            var params = {};

            params = {
                q: {
                    'meta.status': {
                        $nin: ['archived', 'deleted']
                    }
                },
                s: {
                    'start': -1
                }
            };
            return $http.get('/api/v2016/conferences', {
                'params': params,
                'cache': true
            });
        }

        //============================================================
        //
        //============================================================
        function getUnscheduledSideEvents(meeting) {
            var params = {};
            params = {
                q: {
                    'link.meeting': meeting,
                    'sideEvent.meta.status': 'published',
                    'start': {
                        '$exists': 0
                    }
                }

            };
            return $http.get('/api/v2016/reservations', {
                'params': params
            });
        }

        //============================================================
        //
        //============================================================
        function getChildrenTypes(type) {
            var types = [];
            types.push(type);
            var params = {
                q: {
                    'parent': type
                }
            };
            return $http.get('/api/v2016/reservation-types', {
                'params': params
            }).then(function(responce) {
                _.each(responce.data, function(t) {
                    types.push(t._id);
                });
                return types;
            });

        } //loadSideEventTypes

        //============================================================
        //
        //============================================================
        function syncSideEvents(conferenceId) {
            if (!conferenceId) throw "Error no confrence selected to sync";
            return $http.get('/api/v2016/reservations/sync/side-events/' + conferenceId);
        }

        return {
            getRecurrences:getRecurrences,
            getReservation: getReservation,
            getConferences: getConferences,
            getAllOrgs: getAllOrgs,
            saveRes: saveRes,
            syncSideEvents: syncSideEvents,
            deleteDoc: deleteDoc,
            save: save,
            getConferenceRooms: getConferenceRooms,
            getUnscheduledSideEvents: getUnscheduledSideEvents,
            getReservations: getReservations,
            getDocs: getDocs,
        }; //return
    }]); //factory
}); //require<|endoftext|>


<commit_before>/**
 * Created by dani on 18/05/16.
 *
 */

var seasons=new Array(), seasonsLengths=[];
var defend_ev=[], defend_ev_season=[];
var attack_ev=[], attack_ev_season=[];

function extractEverything(JsonObj){

    getSnapshots(JsonObj.data.snapshots, seasons.length);
    getDefendEvents(JsonObj.data.defend_events, defend_ev.length);
    getAttackEvents(JsonObj.data.attack_events, attack_ev.length);
}

function getSnapshots(snapObject, currentSeasonLength){
    var globalSeason=null;
    for(var counter=0;counter<snapObject.length;counter++){
        var seasonTmp=snapObject[counter].season;
        var timeTmp= snapObject[counter].time;
        globalSeason=seasonTmp;

        var extract=JSON.parse(snapObject[counter].data);
        seasons[counter+currentSeasonLength]=new Array(extract.length);
        for(var extractCount=0;extractCount<extract.length;extractCount++){ // antal data
            seasons[counter+currentSeasonLength][extractCount]={
                time: timeTmp,
                season: seasonTmp,
                points: extract[extractCount].points,
                points_taken: extract[extractCount].points_taken,
                status: extract[extractCount].status
            };
        }
    }
    seasonsLengths[globalSeason]={
        start: currentSeasonLength,
        end: seasons.length
    };
}

/*
1. sparar alla defend events i en 1 dimensionell array
 */
function getDefendEvents(defendObject, currentDefenseLength){
    var globalSeason=defendObject[0].season;
    for(var counter=0;counter<defendObject.length;counter++){
        defend_ev [counter+currentDefenseLength]={
            season: defendObject[counter].season,
            event_id: defendObject[counter].event_id,
            start_time: defendObject[counter].start_time,
            end_time: defendObject[counter].end_time,
            region: defendObject[counter].region,
            enemy: defendObject[counter].enemy,
            points_max: defendObject[counter].points_max,
            points: defendObject[counter].points,
            status: defendObject[counter].status,
            players_at_start: defendObject[counter].players_at_start
        };
    }
    defend_ev_season[globalSeason]={
        start:currentDefenseLength,
        end: defend_ev.length
    }
}

/*
 1. sparar alla attackevents i en 1 dimensionell array
 */
function getAttackEvents(attackObject, currentAttackLength){
    var globalSeason=attackObject[0].season;
    for(var counter=0;counter<attackObject.length;counter++){
        attack_ev [counter+currentAttackLength]={
            season: attackObject[counter].season,
            event_id: attackObject[counter].event_id,
            start_time: attackObject[counter].start_time,
            end_time: attackObject[counter].end_time,
            region: attackObject[counter].region,
            enemy: attackObject[counter].enemy,
            points_max: attackObject[counter].points_max,
            points: attackObject[counter].points,
            status: attackObject[counter].status,
            players_at_start: attackObject[counter].players_at_start
        };
    }
    attack_ev_season[globalSeason]={
        start:currentAttackLength,
        end: attack_ev.length
    }
}

// returnerar samtliga säsonger
function getSeasonsArray(){
    return seasons;
}

// returnerar samtliga defend_events
function getDefend_evArray(){
    return defend_ev;
}

// returnerar samtliga attack_ events
function getAttack_evArray(){
    return attack_ev;
}

/*
1. Returnerar en hel säsong med objekt och möjligheten att välja enemytyper för varje dag
2. resultatet som returneras: möjligheten att välja dag och enemytyp [dag (beroende av hur lång en säsong är 0 -x )] [enemytyp (0-2 max)]
 */
function getSeasonInfo(season){
    var start= seasonsLengths[season].start;
    var end = seasonsLengths[season].end;
    var result=[];

    var startTmp=start;
    var endTmp=end;

    for(var xCount=0;xCount<end;xCount++){
        result[xCount]=new Array(3);

       for(var yCount=0;yCount<3;yCount++){
           result[xCount][yCount]=seasons[startTmp][yCount];
       }
       startTmp++;
   }
    return result;
}

/*
1. returnerar information för en specifik dag bara
2. innehåller de tre olika enemytyperna bara, alltså kan man välja endas från 0-2
3.  resultatet som returneras: [möjlighet att välja enemy 0-2 (max 3 enemies) ]
 */
function getSeasonDay(season,day){
    var start= seasonsLengths[season].start;
    var end = seasonsLengths[season].end;
    var result=[];
    // start dagen + inskickade dagen för att få den specifika dagen
    for(var count=0; count<3;count++){
        result[count] = seasons[start+day][count];
    }

    return result;
}

/*
1. returnerar alla defend_events för en specifik säsong
 */
function getSeasonDefendEvents(season){
    var start = defend_ev_season[season].start;
    var end= defend_ev_season[season].end;
    var result=[], resultCounter=0;

    for(var counter=start;counter<end;counter++){
        result[resultCounter++]=defend_ev[counter];
    }
    return result;
}

/*
1. returnerar alla attack_events för en specifik säsong
 */
function getSeasonAttackEvents(season){
    var start = attack_ev_season[season].start;
    var end= attack_ev_season[season].end;
    var result=[], resultCounter=0;

    for(var counter=start;counter<end;counter++){
        result[resultCounter++]=attack_ev[counter];
    }

    return result;
}<commit_msg>allting borde funkar nu.<commit_after>/**
 * Created by dani on 18/05/16.
 *
 */

// nödvändiga arrayer
var seasons=new Array(), seasonsLengths=[];
var defend_ev=[], defend_ev_season=[];
var attack_ev=[], attack_ev_season=[];

function extractEverything(JsonObj){

    getSnapshots(JsonObj.data.snapshots, seasons.length);
    getDefendEvents(JsonObj.data.defend_events, defend_ev.length);
    getAttackEvents(JsonObj.data.attack_events, attack_ev.length);
}

function getSnapshots(snapObject, currentSeasonLength){
    var globalSeason=null;
    for(var counter=0;counter<snapObject.length;counter++){
        var seasonTmp=snapObject[counter].season;
        var timeTmp= snapObject[counter].time;
        globalSeason=seasonTmp;

        var extract=JSON.parse(snapObject[counter].data);
        seasons[counter+currentSeasonLength]=new Array(extract.length);
        for(var extractCount=0;extractCount<extract.length;extractCount++){ // antal data
            seasons[counter+currentSeasonLength][extractCount]={
                time: timeTmp,
                season: seasonTmp,
                points: extract[extractCount].points,
                points_taken: extract[extractCount].points_taken,
                status: extract[extractCount].status
            };
        }
    }
    seasonsLengths[globalSeason]={
        start: currentSeasonLength,
        end: seasons.length
    };
}

/*
1. sparar alla defend events i en 1 dimensionell array
 */
function getDefendEvents(defendObject, currentDefenseLength){
    var globalSeason=defendObject[0].season;
    for(var counter=0;counter<defendObject.length;counter++){
        defend_ev [counter+currentDefenseLength]={
            season: defendObject[counter].season,
            event_id: defendObject[counter].event_id,
            start_time: defendObject[counter].start_time,
            end_time: defendObject[counter].end_time,
            region: defendObject[counter].region,
            enemy: defendObject[counter].enemy,
            points_max: defendObject[counter].points_max,
            points: defendObject[counter].points,
            status: defendObject[counter].status,
            players_at_start: defendObject[counter].players_at_start
        };
    }
    defend_ev_season[globalSeason]={
        start:currentDefenseLength,
        end: defend_ev.length
    }
}

/*
 1. sparar alla attackevents i en 1 dimensionell array
 */
function getAttackEvents(attackObject, currentAttackLength){
    var globalSeason=attackObject[0].season;
    for(var counter=0;counter<attackObject.length;counter++){
        attack_ev [counter+currentAttackLength]={
            season: attackObject[counter].season,
            event_id: attackObject[counter].event_id,
            start_time: attackObject[counter].start_time,
            end_time: attackObject[counter].end_time,
            region: attackObject[counter].region,
            enemy: attackObject[counter].enemy,
            points_max: attackObject[counter].points_max,
            points: attackObject[counter].points,
            status: attackObject[counter].status,
            players_at_start: attackObject[counter].players_at_start
        };
    }
    attack_ev_season[globalSeason]={
        start:currentAttackLength,
        end: attack_ev.length
    }
}

// returnerar samtliga säsonger
function getSeasonsArray(){
    return seasons;
}

// returnerar samtliga defend_events
function getDefend_evArray(){
    return defend_ev;
}

// returnerar samtliga attack_ events
function getAttack_evArray(){
    return attack_ev;
}

/*
1. Returnerar en hel säsong med objekt och möjligheten att välja enemytyper för varje dag
2. resultatet som returneras: möjligheten att välja dag och enemytyp [dag (beroende av hur lång en säsong är 0 -x )] [enemytyp (0-2 max)]
 */
function getSeasonInfo(season){
    var start= seasonsLengths[season].start;
    var end = seasonsLengths[season].end;
    var result=[];

    var startTmp=start;
    var endTmp=end;

    for(var xCount=0;xCount<end;xCount++){
        result[xCount]=new Array(3);

       for(var yCount=0;yCount<3;yCount++){
           result[xCount][yCount]=seasons[startTmp][yCount];
       }
       startTmp++;
   }
    return result;
}

/*
1. returnerar information för en specifik dag bara
2. innehåller de tre olika enemytyperna bara, alltså kan man välja endas från 0-2
3.  resultatet som returneras: [möjlighet att välja enemy 0-2 (max 3 enemies) ]
 */
function getSeasonDay(season,day){
    var start= seasonsLengths[season].start;
    var end = seasonsLengths[season].end;
    var result=[];
    // start dagen + inskickade dagen för att få den specifika dagen
    for(var count=0; count<3;count++){
        result[count] = seasons[start+day][count];
    }

    return result;
}

/*
1. returnerar alla defend_events för en specifik säsong
 */
function getSeasonDefendEvents(season){
    var start = defend_ev_season[season].start;
    var end= defend_ev_season[season].end;
    var result=[], resultCounter=0;

    for(var counter=start;counter<end;counter++){
        result[resultCounter++]=defend_ev[counter];
    }
    return result;
}

/*
1. returnerar alla attack_events för en specifik säsong
 */
function getSeasonAttackEvents(season){
    var start = attack_ev_season[season].start;
    var end= attack_ev_season[season].end;
    var result=[], resultCounter=0;

    for(var counter=start;counter<end;counter++){
        result[resultCounter++]=attack_ev[counter];
    }

    return result;
}<|endoftext|>


<commit_before>(function() {

  if (typeof document !== 'undefined' && typeof window !== 'undefined') {
    return;
  }

  var DOMParser = new require('xmldom').DOMParser,
      URL = require('url'),
      HTTP = require('http'),

      Canvas = require('canvas'),
      Image = require('canvas').Image;

  /** @private */
  function request(url, encoding, callback) {
    var oURL = URL.parse(url),
        client = HTTP.createClient(oURL.port, oURL.hostname),
        req = client.request('GET', oURL.pathname, { 'host': oURL.hostname });

    client.addListener('error', function(err) {
      if (err.errno === process.ECONNREFUSED) {
        fabric.log('ECONNREFUSED: connection refused to ' + client.host + ':' + client.port);
      }
      else {
        fabric.log(err.message);
      }
    });

    req.end();
    req.on('response', function (response) {
      var body = "";
      if (encoding) {
        response.setEncoding(encoding);
      }
      response.on('end', function () {
        callback(body);
      });
      response.on('data', function (chunk) {
        if (response.statusCode === 200) {
          body += chunk;
        }
      });
    });
  }

  fabric.util.loadImage = function(url, callback, context) {
    var img = new Image();
    if (url && url.indexOf('data') === 0) {
      img.src = img._src = url;
      callback && callback.call(context, img);
    }
    else if (url) {
      request(url, 'binary', function(body) {
        img.src = new Buffer(body, 'binary');
        // preserving original url, which seems to be lost in node-canvas
        img._src = url;
        callback && callback.call(context, img);
      });
    }
  };

  fabric.loadSVGFromURL = function(url, callback) {
    url = url.replace(/^\n\s*/, '').replace(/\?.*$/, '').trim();
    request(url, '', function(body) {
      fabric.loadSVGFromString(body, callback);
    });
  };

  fabric.loadSVGFromString = function(string, callback) {
    var doc = new DOMParser().parseFromString(string);
    fabric.parseSVGDocument(doc.documentElement, function(results, options) {
      callback(results, options);
    });
  };

  fabric.util.getScript = function(url, callback) {
    request(url, '', function(body) {
      eval(body);
      callback && callback();
    });
  };

  fabric.Image.fromObject = function(object, callback) {
    fabric.util.loadImage(object.src, function(img) {
      var oImg = new fabric.Image(img);

      oImg._initConfig(object);
      oImg._initFilters(object);
      callback(oImg);
    });
  };

  /**
   * Only available when running fabric on node.js
   * @method createCanvasForNode
   * @param width Canvas width
   * @param height Canvas height
   * @return {Object} wrapped canvas instance
   */
  fabric.createCanvasForNode = function(width, height) {

    var canvasEl = fabric.document.createElement('canvas'),
        nodeCanvas = new Canvas(width || 600, height || 600);

    // jsdom doesn't create style on canvas element, so here be temp. workaround
    canvasEl.style = { };

    canvasEl.width = nodeCanvas.width;
    canvasEl.height = nodeCanvas.height;

    var FabricCanvas = fabric.Canvas || fabric.StaticCanvas;
    var fabricCanvas = new FabricCanvas(canvasEl);
    fabricCanvas.contextContainer = nodeCanvas.getContext('2d');
    fabricCanvas.nodeCanvas = nodeCanvas;

    return fabricCanvas;
  };

  /** @ignore */
  fabric.StaticCanvas.prototype.createPNGStream = function() {
    return this.nodeCanvas.createPNGStream();
  };

  var origSetWidth = fabric.StaticCanvas.prototype.setWidth;
  fabric.StaticCanvas.prototype.setWidth = function(width) {
    origSetWidth.call(this);
    this.nodeCanvas.width = width;
    return this;
  };
  if (fabric.Canvas) {
    fabric.Canvas.prototype.setWidth = fabric.StaticCanvas.prototype.setWidth;
  }

  var origSetHeight = fabric.StaticCanvas.prototype.setHeight;
  fabric.StaticCanvas.prototype.setHeight = function(height) {
    origSetHeight.call(this);
    this.nodeCanvas.height = height;
    return this;
  };
  if (fabric.Canvas) {
    fabric.Canvas.prototype.setHeight = fabric.StaticCanvas.prototype.setHeight;
  }

})();<commit_msg>Add createJPEGStream support for fabric canvas<commit_after>(function() {

  if (typeof document !== 'undefined' && typeof window !== 'undefined') {
    return;
  }

  var DOMParser = new require('xmldom').DOMParser,
      URL = require('url'),
      HTTP = require('http'),

      Canvas = require('canvas'),
      Image = require('canvas').Image;

  /** @private */
  function request(url, encoding, callback) {
    var oURL = URL.parse(url),
        client = HTTP.createClient(oURL.port, oURL.hostname),
        req = client.request('GET', oURL.pathname, { 'host': oURL.hostname });

    client.addListener('error', function(err) {
      if (err.errno === process.ECONNREFUSED) {
        fabric.log('ECONNREFUSED: connection refused to ' + client.host + ':' + client.port);
      }
      else {
        fabric.log(err.message);
      }
    });

    req.end();
    req.on('response', function (response) {
      var body = "";
      if (encoding) {
        response.setEncoding(encoding);
      }
      response.on('end', function () {
        callback(body);
      });
      response.on('data', function (chunk) {
        if (response.statusCode === 200) {
          body += chunk;
        }
      });
    });
  }

  fabric.util.loadImage = function(url, callback, context) {
    var img = new Image();
    if (url && url.indexOf('data') === 0) {
      img.src = img._src = url;
      callback && callback.call(context, img);
    }
    else if (url) {
      request(url, 'binary', function(body) {
        img.src = new Buffer(body, 'binary');
        // preserving original url, which seems to be lost in node-canvas
        img._src = url;
        callback && callback.call(context, img);
      });
    }
  };

  fabric.loadSVGFromURL = function(url, callback) {
    url = url.replace(/^\n\s*/, '').replace(/\?.*$/, '').trim();
    request(url, '', function(body) {
      fabric.loadSVGFromString(body, callback);
    });
  };

  fabric.loadSVGFromString = function(string, callback) {
    var doc = new DOMParser().parseFromString(string);
    fabric.parseSVGDocument(doc.documentElement, function(results, options) {
      callback(results, options);
    });
  };

  fabric.util.getScript = function(url, callback) {
    request(url, '', function(body) {
      eval(body);
      callback && callback();
    });
  };

  fabric.Image.fromObject = function(object, callback) {
    fabric.util.loadImage(object.src, function(img) {
      var oImg = new fabric.Image(img);

      oImg._initConfig(object);
      oImg._initFilters(object);
      callback(oImg);
    });
  };

  /**
   * Only available when running fabric on node.js
   * @method createCanvasForNode
   * @param width Canvas width
   * @param height Canvas height
   * @return {Object} wrapped canvas instance
   */
  fabric.createCanvasForNode = function(width, height) {

    var canvasEl = fabric.document.createElement('canvas'),
        nodeCanvas = new Canvas(width || 600, height || 600);

    // jsdom doesn't create style on canvas element, so here be temp. workaround
    canvasEl.style = { };

    canvasEl.width = nodeCanvas.width;
    canvasEl.height = nodeCanvas.height;

    var FabricCanvas = fabric.Canvas || fabric.StaticCanvas;
    var fabricCanvas = new FabricCanvas(canvasEl);
    fabricCanvas.contextContainer = nodeCanvas.getContext('2d');
    fabricCanvas.nodeCanvas = nodeCanvas;

    return fabricCanvas;
  };

  /** @ignore */
  fabric.StaticCanvas.prototype.createPNGStream = function() {
    return this.nodeCanvas.createPNGStream();
  };

  fabric.StaticCanvas.prototype.createJPEGStream = function(opts) {
    return this.nodeCanvas.createJPEGStream(opts);
  };

  var origSetWidth = fabric.StaticCanvas.prototype.setWidth;
  fabric.StaticCanvas.prototype.setWidth = function(width) {
    origSetWidth.call(this);
    this.nodeCanvas.width = width;
    return this;
  };
  if (fabric.Canvas) {
    fabric.Canvas.prototype.setWidth = fabric.StaticCanvas.prototype.setWidth;
  }

  var origSetHeight = fabric.StaticCanvas.prototype.setHeight;
  fabric.StaticCanvas.prototype.setHeight = function(height) {
    origSetHeight.call(this);
    this.nodeCanvas.height = height;
    return this;
  };
  if (fabric.Canvas) {
    fabric.Canvas.prototype.setHeight = fabric.StaticCanvas.prototype.setHeight;
  }

})();
<|endoftext|>


<commit_before>import Ember from 'ember';
import ENV from '../config/environment';

export default Ember.Service.extend({
  socketService: Ember.inject.service('socket-io'),
  session: Ember.inject.service(),

  getSocket() {
    return this.get('socketService').socketFor(ENV.host);
  },

  setNotificationCookie(orderId) {
    const isCookieExists = this.getIfNotificationCookieSet(orderId);
    if (!isCookieExists) {
      const oneDay = 1 * 24 * 60 * 60 * 1000;
      const date = new Date();
      date.setTime(date.getTime() + oneDay);
      document.cookie =
        `ROOMS_JOINED_${orderId}=${orderId}; expires=${date.toGMTString()}; path=/`;
    }
  },

  removeNotificationCookie(orderId) {
    const isCookieExists = this.getIfNotificationCookieSet(orderId);
    if (isCookieExists) {
      const oneDay = 1 * 24 * 60 * 60 * 1000;
      const date = new Date();
      date.setTime(date.getTime() - oneDay);
      document.cookie = `ROOMS_JOINED_${orderId}=; expires=${date.toGMTString()}`;
    }
  },

  getIfNotificationCookieSet(orderId) {
    const name = `ROOMS_JOINED_${orderId}=`;
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      let cookie = cookies[i];
      while (cookie.charAt(0) === ' ') {
        cookie = cookie.substring(1);
      }
      if (cookie.indexOf(name) === 0) {
        return true;
      }
    }
    return false;
  },

  getOrdersFromCookies() {
    const connectedOrders = [];
    const name = 'ROOMS_JOINED_';
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      let cookie = cookies[i];
      while (cookie.charAt(0) === ' ') {
        cookie = cookie.substring(1);
      }
      if (cookie.indexOf(name) === 0) {
        cookie = cookie.substring(name.length, cookie.length);
        const divider = '=';
        if (cookie.indexOf(divider) > 0) {
          const order = cookie.substring(cookie.indexOf(divider) + 1, cookie.length);
          connectedOrders.push(order);
        }
      }
    }
    return connectedOrders;
  },

  requestUserOrders(email) {
    const socketIO = this.getSocket();
    socketIO.emit('getOrders', { email });
  },

  joinToPrivateSession(email) {
    const socketIO = this.getSocket();
    socketIO.emit('join', { room: email });
  },

  sendOrderNotification(message, order) {
    const socketIO = this.getSocket();
    socketIO.emit('sendMessage', { message, order });
  },

  subscribeOrderNotification(orderId) {
    this.setNotificationCookie(orderId);
    const socketIO = this.getSocket();
    socketIO.emit('join', { room: orderId });
  },

  subscribeNotifications() {
    const notification = this;
    const orders = notification.getOrdersFromCookies();
    orders.forEach(item => {
      notification.subscribeOrderNotification(item);
    });
  },

  subscribeNotificationsOnLogin(email) {
    this.joinToPrivateSession(email);
    this.requestUserOrders(email);
  },

  unsubscribeFromOrderNotifications() {
    const socketIO = this.getSocket();
    const notification = this;
    const orders = notification.getOrdersFromCookies();
    orders.forEach(item => {
      socketIO.emit('leave', { room: item });
      notification.removeNotificationCookie(item);
    });
  },

  createNotification(options) {
    const notification = new Notification('Yummy Time', options);
    notification.onclick = function(event) {
      event.preventDefault();
      notification.close();
    };
  },

  init(email) {
    this._super.apply(this);
    const socketIO = this.getSocket();

    socketIO.on('message', data => {
      const options = {
        body: data.msg,
        icon: 'assets/img/notify-icon.jpg'
      };

      if ('Notification' in window) {
        if (Notification.permission === 'granted') {
          this.createNotification(options);
        } else if (Notification.permission !== 'denied') {
          Notification.requestPermission(permission => {
            if (permission === 'granted') {
              this.createNotification(options);
            }
          });
        }
      }
    }, this);

    socketIO.on('orders', function(data) {
      const notification = this;
      data.orders.forEach(orderId => {
        notification.subscribeOrderNotification(orderId);
      });
      socketIO.emit('leave', { room: email });
    }, this);
  }
});
<commit_msg>set io transport<commit_after>import Ember from 'ember';
import ENV from '../config/environment';

export default Ember.Service.extend({
  socketService: Ember.inject.service('socket-io'),
  session: Ember.inject.service(),

  getSocket() {
    const io = this.get('socketService').socketFor(ENV.host);
    io.set('transports', ['xhr-polling']);
    io.set('polling duration', 10);
    return
  },

  setNotificationCookie(orderId) {
    const isCookieExists = this.getIfNotificationCookieSet(orderId);
    if (!isCookieExists) {
      const oneDay = 1 * 24 * 60 * 60 * 1000;
      const date = new Date();
      date.setTime(date.getTime() + oneDay);
      document.cookie =
        `ROOMS_JOINED_${orderId}=${orderId}; expires=${date.toGMTString()}; path=/`;
    }
  },

  removeNotificationCookie(orderId) {
    const isCookieExists = this.getIfNotificationCookieSet(orderId);
    if (isCookieExists) {
      const oneDay = 1 * 24 * 60 * 60 * 1000;
      const date = new Date();
      date.setTime(date.getTime() - oneDay);
      document.cookie = `ROOMS_JOINED_${orderId}=; expires=${date.toGMTString()}`;
    }
  },

  getIfNotificationCookieSet(orderId) {
    const name = `ROOMS_JOINED_${orderId}=`;
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      let cookie = cookies[i];
      while (cookie.charAt(0) === ' ') {
        cookie = cookie.substring(1);
      }
      if (cookie.indexOf(name) === 0) {
        return true;
      }
    }
    return false;
  },

  getOrdersFromCookies() {
    const connectedOrders = [];
    const name = 'ROOMS_JOINED_';
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      let cookie = cookies[i];
      while (cookie.charAt(0) === ' ') {
        cookie = cookie.substring(1);
      }
      if (cookie.indexOf(name) === 0) {
        cookie = cookie.substring(name.length, cookie.length);
        const divider = '=';
        if (cookie.indexOf(divider) > 0) {
          const order = cookie.substring(cookie.indexOf(divider) + 1, cookie.length);
          connectedOrders.push(order);
        }
      }
    }
    return connectedOrders;
  },

  requestUserOrders(email) {
    const socketIO = this.getSocket();
    socketIO.emit('getOrders', { email });
  },

  joinToPrivateSession(email) {
    const socketIO = this.getSocket();
    socketIO.emit('join', { room: email });
  },

  sendOrderNotification(message, order) {
    const socketIO = this.getSocket();
    socketIO.emit('sendMessage', { message, order });
  },

  subscribeOrderNotification(orderId) {
    this.setNotificationCookie(orderId);
    const socketIO = this.getSocket();
    socketIO.emit('join', { room: orderId });
  },

  subscribeNotifications() {
    const notification = this;
    const orders = notification.getOrdersFromCookies();
    orders.forEach(item => {
      notification.subscribeOrderNotification(item);
    });
  },

  subscribeNotificationsOnLogin(email) {
    this.joinToPrivateSession(email);
    this.requestUserOrders(email);
  },

  unsubscribeFromOrderNotifications() {
    const socketIO = this.getSocket();
    const notification = this;
    const orders = notification.getOrdersFromCookies();
    orders.forEach(item => {
      socketIO.emit('leave', { room: item });
      notification.removeNotificationCookie(item);
    });
  },

  createNotification(options) {
    const notification = new Notification('Yummy Time', options);
    notification.onclick = function(event) {
      event.preventDefault();
      notification.close();
    };
  },

  init(email) {
    this._super.apply(this);
    const socketIO = this.getSocket();

    socketIO.on('message', data => {
      const options = {
        body: data.msg,
        icon: 'assets/img/notify-icon.jpg'
      };

      if ('Notification' in window) {
        if (Notification.permission === 'granted') {
          this.createNotification(options);
        } else if (Notification.permission !== 'denied') {
          Notification.requestPermission(permission => {
            if (permission === 'granted') {
              this.createNotification(options);
            }
          });
        }
      }
    }, this);

    socketIO.on('orders', function(data) {
      const notification = this;
      data.orders.forEach(orderId => {
        notification.subscribeOrderNotification(orderId);
      });
      socketIO.emit('leave', { room: email });
    }, this);
  }
});
<|endoftext|>


<commit_before>var moment = require('moment');
var todos = Alloy.Collections.todo;
var id;

// $model represents the current model accessible to this
// controller from the markup's model-view binding. $model
// will be null if there is no binding in place.

if ($model) {
	id = $model.get('id');
	if ($model.get('done')) {
		$.row.backgroundColor = '#eee';
		$.check.backgroundColor = '#eee';
		$.task.color = '#ccc';
		$.check.image = '/tick_64.png';
	} else {
		$.row.backgroundColor = '#fff';
		$.check.backgroundColor = '#fff';
		$.task.color = '#000';
		$.check.image = '/tick_gray_64.png';
	}
}

// toggle the "done" status of the IDed todo
function toggleStatus(e) {
	// finc the todo task by id
	var todo = todos.get(id);

	// set the current done and date_completed fields for the model
	todo.set({
    		"done": todo.get('done') ? 0 : 1,
    		"date_completed": moment().unix()
  	}).save(); // save to presistence

  	// update views from sql storage
  	todos.fetch();
}

// delete the IDed todo from the collection
function deleteTask(e) {
	// find the todo task by id
	var todo = todos.get(id);

	// destroy the model from persistence, which will in turn remove
	// it from the collection, and model-view binding will automatically
	// reflect this in the tableview
	todo.destroy();
}<commit_msg>removed another superfluous fetch(), better comments<commit_after>var moment = require('moment');
var todos = Alloy.Collections.todo;
var id;

// $model represents the current model accessible to this
// controller from the markup's model-view binding. $model
// will be null if there is no binding in place.

if ($model) {
	id = $model.get('id');
	if ($model.get('done')) {
		$.row.backgroundColor = '#eee';
		$.check.backgroundColor = '#eee';
		$.task.color = '#ccc';
		$.check.image = '/tick_64.png';
	} else {
		$.row.backgroundColor = '#fff';
		$.check.backgroundColor = '#fff';
		$.task.color = '#000';
		$.check.image = '/tick_gray_64.png';
	}
}

// toggle the "done" status of the IDed todo
function toggleStatus(e) {
	// finc the todo task by id
	var todo = todos.get(id);

	// set the current "done" and "date_completed" fields for the model,
	// then save to presistence, and model-view binding will automatically
	// reflect this in the tableview
	todo.set({
    		"done": todo.get('done') ? 0 : 1,
    		"date_completed": moment().unix()
  	}).save(); // save to presistence
}

// delete the IDed todo from the collection
function deleteTask(e) {
	// find the todo task by id
	var todo = todos.get(id);

	// destroy the model from persistence, which will in turn remove
	// it from the collection, and model-view binding will automatically
	// reflect this in the tableview
	todo.destroy();
}<|endoftext|>


<commit_before>var binary = require('node-pre-gyp');
var fs = require('fs');
var path = require('path');
var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json')));
var binding = require(binding_path);
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var extend = require('util')._extend;

var NODE_NEXT = require('./tools/NODE_NEXT');

// Don't cache debugger module
delete require.cache[module.id];

function InjectedScriptDir(link) {
  return require.resolve(__dirname + '/InjectedScript/' + link);
};
var DebuggerScriptLink = InjectedScriptDir('DebuggerScript.js');
var InjectedScriptLink = InjectedScriptDir('InjectedScriptSource.js');
var InjectedScriptHostLink = InjectedScriptDir('InjectedScriptHost.js');

var overrides = {
  extendedProcessDebugJSONRequestHandles_: {},
  extendedProcessDebugJSONRequestAsyncHandles_: {},
  extendedProcessDebugJSONRequest_: function(json_request) {
    var request;  // Current request.
    var response;  // Generated response.
    try {
      try {
        // Convert the JSON string to an object.
        request = JSON.parse(json_request);

        var handle = this.extendedProcessDebugJSONRequestHandles_[request.command];
        var asyncHandle = this.extendedProcessDebugJSONRequestAsyncHandles_[request.command];
        var asyncResponse;

        if (!handle && !asyncHandle) return;

        // Create an initial response.
        response = this.createResponse(request);

        if (request.arguments) {
          var args = request.arguments;
          if (args.maxStringLength !== undefined) {
            response.setOption('maxStringLength', args.maxStringLength);
          }
          if (args.asyncResponse) {
            asyncResponse = args.asyncResponse;
          }
        }

        if (asyncHandle) {
          if (asyncResponse) return JSON.stringify(asyncResponse);

          asyncHandle.call(this, request, response, function(error) {
            sendCommand(request.command, {
              asyncResponse: error || response
            });
          }.bind(this));

          return '{"seq":0,"type":"response","success":true}';
        }

        handle.call(this, request, response);
      } catch (e) {
        // If there is no response object created one (without command).
        if (!response) {
          response = this.createResponse();
        }
        response.success = false;
        response.message = e.toString();
      }

      // Return the response as a JSON encoded string.
      try {
        if (response.running !== undefined) {
          // Response controls running state.
          this.running_ = response.running;
        }
        response.running = this.running_;
        return JSON.stringify(response);
      } catch (e) {
        // Failed to generate response - return generic error.
        return '{"seq":' + response.seq + ',' +
                '"request_seq":' + request.seq + ',' +
                '"type":"response",' +
                '"success":false,' +
                '"message":"Internal error: ' + e.toString() + '"}';
      }
    } catch (e) {
      // Failed in one of the catch blocks above - most generic error.
      return '{"seq":0,"type":"response","success":false,"message":"Internal error"}';
    }
  },
  processDebugRequest: function WRAPPED_BY_NODE_INSPECTOR(request) {
    return this.extendedProcessDebugJSONRequest_(request)
      || this.processDebugJSONRequest(request);
  }
};

inherits(V8Debug, EventEmitter);
function V8Debug() {
  this._webkitProtocolEnabled = false;

  // NOTE: Call `_setDebugEventListener` before all other changes in Debug Context.
  // After node 0.12.0 this function serves to allocate Debug Context
  // like a persistent value, that saves all our changes.
  this._setDebugEventListener();
  this._wrapDebugCommandProcessor();

  this.once('close', function() {
    this._unwrapDebugCommandProcessor();
    this._unsetDebugEventListener();
    process.nextTick(function() {
      this.removeAllListeners();
    }.bind(this));
  });
}

V8Debug.prototype._setDebugEventListener = function() {
  var Debug = this.get('Debug');
  Debug.setListener(function(_, execState, event) {
    // TODO(3y3): Handle events here
  });
};

V8Debug.prototype._unsetDebugEventListener = function() {
  var Debug = this.get('Debug');
  Debug.setListener(null);
};

V8Debug.prototype._wrapDebugCommandProcessor = function() {
  var proto = this.get('DebugCommandProcessor.prototype');
  overrides.processDebugRequest_ = proto.processDebugRequest;
  extend(proto, overrides);
  overrides.extendedProcessDebugJSONRequestHandles_['disconnect'] = function(request, response) {
    this.emit('close');
    this.processDebugJSONRequest(request);
  }.bind(this);
};

V8Debug.prototype._unwrapDebugCommandProcessor = function() {
  var proto = this.get('DebugCommandProcessor.prototype');
  proto.processDebugRequest = proto.processDebugRequest_;
  delete proto.processDebugRequest_;
  delete proto.extendedProcessDebugJSONRequest_;
  delete proto.extendedProcessDebugJSONRequestHandles_;
  delete proto.extendedProcessDebugJSONRequestAsyncHandles_;
};

V8Debug.prototype.register =
V8Debug.prototype.registerCommand = function(name, func) {
  overrides.extendedProcessDebugJSONRequestHandles_[name] = func;
};

V8Debug.prototype.registerAsync =
V8Debug.prototype.registerAsyncCommand = function(name, func) {
  overrides.extendedProcessDebugJSONRequestAsyncHandles_[name] = func;
};

V8Debug.prototype.command =
V8Debug.prototype.sendCommand =
V8Debug.prototype.emitEvent = sendCommand;
function sendCommand(name, attributes, userdata) {
  var message = {
    seq: 0,
    type: 'request',
    command: name,
    arguments: attributes || {}
  };
  binding.sendCommand(JSON.stringify(message));
};

V8Debug.prototype.commandToEvent = function(request, response) {
  response.type = 'event';
  response.event = response.command;
  response.body = request.arguments || {};
  delete response.command;
  delete response.request_seq;
};

V8Debug.prototype.registerEvent = function(name) {
  overrides.extendedProcessDebugJSONRequestHandles_[name] = this.commandToEvent;
};

V8Debug.prototype.get =
V8Debug.prototype.runInDebugContext = function(script) {
  if (typeof script == 'function') script = script.toString() + '()';

  script = /\);$/.test(script) ? script : '(' + script + ');';

  return binding.runScript(script);
};

V8Debug.prototype.getFromFrame = function(index, value) {
  var result;

  binding.call(function(execState) {
    var _index = index + 1;
    var _count = execState.frameCount();
    if (_count > _index + 1 ) {
      var frame = execState.frame(_index + 1);
      _count = frame.scopeCount();
      _index = 0;
      while (_count --> 0) {
        var scope = frame.scope(_index).scopeObject().value();
        if (scope[value]) {
          result = scope[value];
          return;
        }
      }
    }
  });

  return result;
};

V8Debug.prototype.enableWebkitProtocol = function() {
  if (!NODE_NEXT) {
    throw new Error('WebKit protocol is not supported on target node version (' + process.version + ')');
  }

  if (this._webkitProtocolEnabled) return;

  var DebuggerScriptSource,
      DebuggerScript,
      InjectedScriptSource,
      InjectedScript,
      InjectedScriptHostSource,
      InjectedScriptHost;

  function prepareSource(source) {
    return 'var ToggleMirrorCache = ToggleMirrorCache || function() {};\n' +
    '(function() {' +
      ('' + source).replace(/^.*?"use strict";(\r?\n.*?)*\(/m, '\r\n"use strict";\nreturn (') +
    '}());';
  }

  DebuggerScriptSource = prepareSource(fs.readFileSync(DebuggerScriptLink, 'utf8'));
  DebuggerScript = this.runInDebugContext(DebuggerScriptSource);

  InjectedScriptSource = prepareSource(fs.readFileSync(InjectedScriptLink, 'utf8'));
  InjectedScript = this.runInDebugContext(InjectedScriptSource);

  InjectedScriptHostSource = prepareSource(fs.readFileSync(InjectedScriptHostLink, 'utf8'));
  InjectedScriptHost = this.runInDebugContext(InjectedScriptHostSource)(binding, DebuggerScript);

  var injectedScript = InjectedScript(InjectedScriptHost, global, 1);

  this.registerAgentCommand = function(command, parameters, callback) {
    this.registerCommand(command, new WebkitProtocolCallback(parameters, callback));
  };

  this._webkitProtocolEnabled = true;

  function WebkitProtocolCallback(argsList, callback) {
    return function(request, response) {
      InjectedScriptHost.execState = this.exec_state_;

      var args = argsList.map(function(name) {
        return request.arguments[name];
      });

      callback.call(this, args, response, injectedScript, DebuggerScript);

      InjectedScriptHost.execState = null;
    }
  }
};

V8Debug.prototype.registerAgentCommand = function(command, parameters, callback) {
  throw new Error('Use "enableWebkitProtocol" before using this method');
};

module.exports = new V8Debug();
<commit_msg>Fix #21: this.extendedProcessDebugJSONRequest_ is not a function<commit_after>var binary = require('node-pre-gyp');
var fs = require('fs');
var path = require('path');
var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json')));
var binding = require(binding_path);
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var extend = require('util')._extend;

var NODE_NEXT = require('./tools/NODE_NEXT');

// Don't cache debugger module
delete require.cache[module.id];

function InjectedScriptDir(link) {
  return require.resolve(__dirname + '/InjectedScript/' + link);
};
var DebuggerScriptLink = InjectedScriptDir('DebuggerScript.js');
var InjectedScriptLink = InjectedScriptDir('InjectedScriptSource.js');
var InjectedScriptHostLink = InjectedScriptDir('InjectedScriptHost.js');

var overrides = {
  extendedProcessDebugJSONRequestHandles_: {},
  extendedProcessDebugJSONRequestAsyncHandles_: {},
  extendedProcessDebugJSONRequest_: function(json_request) {
    var request;  // Current request.
    var response;  // Generated response.
    try {
      try {
        // Convert the JSON string to an object.
        request = JSON.parse(json_request);

        var handle = this.extendedProcessDebugJSONRequestHandles_[request.command];
        var asyncHandle = this.extendedProcessDebugJSONRequestAsyncHandles_[request.command];
        var asyncResponse;

        if (!handle && !asyncHandle) return;

        // Create an initial response.
        response = this.createResponse(request);

        if (request.arguments) {
          var args = request.arguments;
          if (args.maxStringLength !== undefined) {
            response.setOption('maxStringLength', args.maxStringLength);
          }
          if (args.asyncResponse) {
            asyncResponse = args.asyncResponse;
          }
        }

        if (asyncHandle) {
          if (asyncResponse) return JSON.stringify(asyncResponse);

          asyncHandle.call(this, request, response, function(error) {
            sendCommand(request.command, {
              asyncResponse: error || response
            });
          }.bind(this));

          return '{"seq":0,"type":"response","success":true}';
        }

        handle.call(this, request, response);
      } catch (e) {
        // If there is no response object created one (without command).
        if (!response) {
          response = this.createResponse();
        }
        response.success = false;
        response.message = e.toString();
      }

      // Return the response as a JSON encoded string.
      try {
        if (response.running !== undefined) {
          // Response controls running state.
          this.running_ = response.running;
        }
        response.running = this.running_;
        return JSON.stringify(response);
      } catch (e) {
        // Failed to generate response - return generic error.
        return '{"seq":' + response.seq + ',' +
                '"request_seq":' + request.seq + ',' +
                '"type":"response",' +
                '"success":false,' +
                '"message":"Internal error: ' + e.toString() + '"}';
      }
    } catch (e) {
      // Failed in one of the catch blocks above - most generic error.
      return '{"seq":0,"type":"response","success":false,"message":"Internal error"}';
    }
  },
  processDebugRequest: function WRAPPED_BY_NODE_INSPECTOR(request) {
    return (this.extendedProcessDebugJSONRequest_
      && this.extendedProcessDebugJSONRequest_(request))
      || this.processDebugJSONRequest(request);
  }
};

inherits(V8Debug, EventEmitter);
function V8Debug() {
  this._webkitProtocolEnabled = false;

  // NOTE: Call `_setDebugEventListener` before all other changes in Debug Context.
  // After node 0.12.0 this function serves to allocate Debug Context
  // like a persistent value, that saves all our changes.
  this._setDebugEventListener();
  this._wrapDebugCommandProcessor();

  this.once('close', function() {
    this._unwrapDebugCommandProcessor();
    this._unsetDebugEventListener();
    process.nextTick(function() {
      this.removeAllListeners();
    }.bind(this));
  });
}

V8Debug.prototype._setDebugEventListener = function() {
  var Debug = this.get('Debug');
  Debug.setListener(function(_, execState, event) {
    // TODO(3y3): Handle events here
  });
};

V8Debug.prototype._unsetDebugEventListener = function() {
  var Debug = this.get('Debug');
  Debug.setListener(null);
};

V8Debug.prototype._wrapDebugCommandProcessor = function() {
  var proto = this.get('DebugCommandProcessor.prototype');
  overrides.processDebugRequest_ = proto.processDebugRequest;
  extend(proto, overrides);
  overrides.extendedProcessDebugJSONRequestHandles_['disconnect'] = function(request, response) {
    this.emit('close');
    this.processDebugJSONRequest(request);
  }.bind(this);
};

V8Debug.prototype._unwrapDebugCommandProcessor = function() {
  var proto = this.get('DebugCommandProcessor.prototype');
  proto.processDebugRequest = proto.processDebugRequest_;
  delete proto.processDebugRequest_;
  delete proto.extendedProcessDebugJSONRequest_;
  delete proto.extendedProcessDebugJSONRequestHandles_;
  delete proto.extendedProcessDebugJSONRequestAsyncHandles_;
};

V8Debug.prototype.register =
V8Debug.prototype.registerCommand = function(name, func) {
  overrides.extendedProcessDebugJSONRequestHandles_[name] = func;
};

V8Debug.prototype.registerAsync =
V8Debug.prototype.registerAsyncCommand = function(name, func) {
  overrides.extendedProcessDebugJSONRequestAsyncHandles_[name] = func;
};

V8Debug.prototype.command =
V8Debug.prototype.sendCommand =
V8Debug.prototype.emitEvent = sendCommand;
function sendCommand(name, attributes, userdata) {
  var message = {
    seq: 0,
    type: 'request',
    command: name,
    arguments: attributes || {}
  };
  binding.sendCommand(JSON.stringify(message));
};

V8Debug.prototype.commandToEvent = function(request, response) {
  response.type = 'event';
  response.event = response.command;
  response.body = request.arguments || {};
  delete response.command;
  delete response.request_seq;
};

V8Debug.prototype.registerEvent = function(name) {
  overrides.extendedProcessDebugJSONRequestHandles_[name] = this.commandToEvent;
};

V8Debug.prototype.get =
V8Debug.prototype.runInDebugContext = function(script) {
  if (typeof script == 'function') script = script.toString() + '()';

  script = /\);$/.test(script) ? script : '(' + script + ');';

  return binding.runScript(script);
};

V8Debug.prototype.getFromFrame = function(index, value) {
  var result;

  binding.call(function(execState) {
    var _index = index + 1;
    var _count = execState.frameCount();
    if (_count > _index + 1 ) {
      var frame = execState.frame(_index + 1);
      _count = frame.scopeCount();
      _index = 0;
      while (_count --> 0) {
        var scope = frame.scope(_index).scopeObject().value();
        if (scope[value]) {
          result = scope[value];
          return;
        }
      }
    }
  });

  return result;
};

V8Debug.prototype.enableWebkitProtocol = function() {
  if (!NODE_NEXT) {
    throw new Error('WebKit protocol is not supported on target node version (' + process.version + ')');
  }

  if (this._webkitProtocolEnabled) return;

  var DebuggerScriptSource,
      DebuggerScript,
      InjectedScriptSource,
      InjectedScript,
      InjectedScriptHostSource,
      InjectedScriptHost;

  function prepareSource(source) {
    return 'var ToggleMirrorCache = ToggleMirrorCache || function() {};\n' +
    '(function() {' +
      ('' + source).replace(/^.*?"use strict";(\r?\n.*?)*\(/m, '\r\n"use strict";\nreturn (') +
    '}());';
  }

  DebuggerScriptSource = prepareSource(fs.readFileSync(DebuggerScriptLink, 'utf8'));
  DebuggerScript = this.runInDebugContext(DebuggerScriptSource);

  InjectedScriptSource = prepareSource(fs.readFileSync(InjectedScriptLink, 'utf8'));
  InjectedScript = this.runInDebugContext(InjectedScriptSource);

  InjectedScriptHostSource = prepareSource(fs.readFileSync(InjectedScriptHostLink, 'utf8'));
  InjectedScriptHost = this.runInDebugContext(InjectedScriptHostSource)(binding, DebuggerScript);

  var injectedScript = InjectedScript(InjectedScriptHost, global, 1);

  this.registerAgentCommand = function(command, parameters, callback) {
    this.registerCommand(command, new WebkitProtocolCallback(parameters, callback));
  };

  this._webkitProtocolEnabled = true;

  function WebkitProtocolCallback(argsList, callback) {
    return function(request, response) {
      InjectedScriptHost.execState = this.exec_state_;

      var args = argsList.map(function(name) {
        return request.arguments[name];
      });

      callback.call(this, args, response, injectedScript, DebuggerScript);

      InjectedScriptHost.execState = null;
    }
  }
};

V8Debug.prototype.registerAgentCommand = function(command, parameters, callback) {
  throw new Error('Use "enableWebkitProtocol" before using this method');
};

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