<commit_before>/* jslint node: true, esnext: true */
var Config = require('./config'),
  log = require('./log');

/**
 * @object Core
 */
var Core = {

  /**
   * @method getHostname
   * @param {Object} ConfigEntry
   */
  getHostname(ConfigEntry) {
    var hostname = ConfigEntry.name;

    if (typeof ConfigEntry.project !== 'undefined') {
      hostname += '.' + ConfigEntry.project;
    } else if (typeof ConfigEntry.site !== 'undefined') {
      hostname += '.' + ConfigEntry.domain;
    }

    return hostname;
  },

  /**
   * @method getJumpHost
   * @return {String}
   */
  getJumpHost() {
    return Config.jumphost.name + '.' + Config.jumphost.domain;
  },

  /**
   * @method getEntry
   * @param {String} host
   * @return {String}
   */
  getEntry(host) {

    var data = null;
    for (var i = 0; i < Config.hosts.length; i++) {
      var entry = Config.hosts[i];
      if (entry.name === host) {
        data = entry;
        break;
      }
    }

    return data;
  },

  /**
   * @param {String} hostname
   * @param {Boolean} jump
   * @return {String}
   * @method getCommand
   */
  getCommand(hostname, jump) {

    if (typeof jump === 'undefined') {
      jump = false;
    }

    var shellSyntaxCommand = 'ssh -A -t ' + Config.username + '@' + hostname;

    if (jump) {
      shellSyntaxCommand = 'ssh -A -t ' + Config.username + '@' + this.getJumpHost() + ' ' + shellSyntaxCommand;
    }

    return shellSyntaxCommand;
  },

  /**
   * @method run
   * @param {String} command
   * @param {String} jump
   * @public
   */
  run(command, jump) {

    if (typeof jump === 'undefined') {
      jump = false;
    }

    var host = command;
    var data = this.getEntry(host);

    if (data !== null) {
      var spawn = require('child_process').spawn;
      var hostname = this.getHostname(data);
      var shellSyntaxCommand = this.getCommand(hostname, jump);
      log(shellSyntaxCommand);
      spawn('sh', ['-c', shellSyntaxCommand], { stdio: 'inherit' });
    }
  }

};

module.exports = Core;
<commit_msg>Removing unused code.<commit_after>/* jslint node: true, esnext: true */
var Config = require('./config'),
  log = require('./log');

/**
 * @object Core
 */
var Core = {

  /**
   * @method getHostname
   * @param {Object} ConfigEntry
   */
  getHostname(ConfigEntry) {
    var hostname = ConfigEntry.name;

    if (typeof ConfigEntry.project !== 'undefined') {
      hostname += '.' + ConfigEntry.project;
    } else if (typeof ConfigEntry.site !== 'undefined') {
      hostname += '.' + ConfigEntry.domain;
    }

    return hostname;
  },

  /**
   * @method getJumpHost
   * @return {String}
   */
  getJumpHost() {
    return Config.jumphost.name + '.' + Config.jumphost.domain;
  },

  /**
   * @method getEntry
   * @param {String} host
   * @return {String}
   */
  getEntry(host) {

    var data = null;
    for (var i = 0; i < Config.hosts.length; i++) {
      var entry = Config.hosts[i];
      if (entry.name === host) {
        data = entry;
        break;
      }
    }

    return data;
  },

  /**
   * @param {String} hostname
   * @param {Boolean} jump
   * @return {String}
   * @method getCommand
   */
  getCommand(hostname, jump) {

    if (typeof jump === 'undefined') {
      jump = false;
    }

    var shellSyntaxCommand = 'ssh -A -t ' + Config.username + '@' + hostname;

    if (jump) {
      shellSyntaxCommand = 'ssh -A -t ' + Config.username + '@' + this.getJumpHost() + ' ' + shellSyntaxCommand;
    }

    return shellSyntaxCommand;
  }

};

module.exports = Core;
<|endoftext|>


<commit_before>mini.Module(
	"editor/editorgame"
)
.requires(
	"editor/script/editor",
	"engine/main",
	"engine/game",
	"editor/editorscene",
	"basic/utils",
	"editor/action",
	"engine/map/map",
	"assets/loader",
	"editor/server"
)
.defines(function(
	_Editor,
	main,
	Game,
	EditorScene,
	Utils,
	Action,
	Map,
	Loader,
	Server
) {

	Editor = true;

	main(_Editor, "canvas");

	return {};
});
<commit_msg>removed unnecessary includes in editorgame.js<commit_after>mini.Module(
	"editor/editorgame"
)
.requires(
	"editor/script/editor",
	"engine/main"
)
.defines(function(
	_Editor,
	main
) {

	Editor = true;

	main(_Editor, "canvas");

	return {};
});
<|endoftext|>


<commit_before>'use strict';
var config = require('../../configs');

var http = require('http');

/**
 *The AlexaSkill Module that has the AlexaSkill prototype and helper functions
 */

var apiKey=config.getAPIKey();
var i=0,j=0;
/**
 * This function will return the train status as a string.
 * Sample output : Train departed from KARUKKUTTY(KUC) and late by 24 minutes.
 */
exports.getJsonLiveStatus= function (train_no,doj,eventCallback){

    var url =config.getBaseUrl()+"live/train/"+train_no+"/doj/"+doj+"/apikey/"+apiKey+"/";
    var state="";
    var status= "";
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var status=stringResult.position;
            if(stringResult.response_code!='200')
                    status="There was an error processing your request.";
            var result={speech:status,status:stringResult.position,heading:'Train Number: '+train_no};
            eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        status= "Sorry, we could not process your request.";

        var result={speech:status,status:status,heading:null};
        eventCallback(result);
    });
   return status;
}

/**
 * This function will return the stations in a route as a string.
 * Sample output : KANYAKUMARI,Source,14:10,1,  NAGARCOIL JN,14:30,14:35,1,  KULITTHURAI,15:14,15:15,1,  TRIVANDRUM CNTL,15:55,16:00,1,  KOLLAM JN,17:00,17:05,1,  KAYANKULAM,17:34,17:36,1 (Station     **name,Arriavl time,Departure time,Day of arrival.)
 */
exports.getJsonTrainRoute=function (train_no,eventCallback){

    var url =config.getBaseUrl()+'route/train/'+train_no+'/apikey/'+ apiKey+'/';
       var station_string="";
    var state = "";
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var station_names=[];
            var station_arrival=[];
            var station_dep=[];
            var day=[];
            for (i=0; i<stringResult.route.length; i++){
                station_names[i]=stringResult.route[i].fullname;
                station_arrival[i]=stringResult.route[i].scharr;
                station_dep[i]=stringResult.route[i].schdep;
                day[i]=stringResult.route[i].day;
                }
             var m=0;
             var update=Math.ceil(((stringResult.route.length-2)/5));
             var source_=station_names[0];
             var dest_=station_names[i-1];

             station_string=station_string+"The train starts from "+source_+" at "+station_dep[0]+" and arrives  "+dest_+" at "+station_arrival[i-1]+" on day "+day[i-1]+" passing through ";
            for (j=0; j<i-1; j=j+update){
               m=j+1;
              if((j+update)<(i-1))
                 station_string=station_string+station_names[j]+",";
                else
                 station_string=station_string+" and "+station_names[j]+".";
               }
               if(stringResult.response_code!='200')
                    station_string="There was an error processing your request.";
            var result={speech:station_string,status:station_string,heading:"Route of Train Number: "+train_no};
            eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        status= "Sorry, we could not process your request.";
        var result={speech:status,status:status,heading:null};
        eventCallback(result);
    });
}

/**
 * This function will return the seat availability as string.
 * Sample output : AVAILABLE 11

*/
exports.getJsonSeatAvailability = function (train_no, source, dest, date, _class, quota,eventCallback){
    var url =config.getBaseUrl() +'/check_seat/train/'+train_no+'/source/'+ source +'/dest/'+dest+'/date/'+ date+'/class/'+_class+'/quota/'+quota+'/apikey/'+ apiKey+'/';
    var status = "";
      http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var index3=0;
            var index4=0;
            var status=stringResult.availability[0].status;
            if(status.indexOf('AVAILABLE')>-1)
            {
                var index_=status.indexOf('AVAILABLE');
                var available=status.substring(index_+10);
            }
            status=available+" seats are available.";
            if(status.charAt(0)=='G'&&status.charAt(1)=='N'&&status.charAt(2)=='W')
               {
                 index3=status.indexOf("/WL");
                 index4=status.indexOf("\n",index3);
                 var waiting=status.substring(index3+3,index3+8);
                 var status=waiting+" seats are in waiting list.";
                }
                if(stringResult.response_code!='200')
                    status="There was an error processing your request.";
             var result={speech:status,status:status,heading:"Seat availability of Train: "+train_no};
             eventCallback(result);
        });
    }).on('error', function (e) {
             var result={speech:"Sorry, we could not process your request.",status:"Sorry, we could not process your request.",heading:null};
             eventCallback(result);
    });
}

/**
 * This function will return the train numbers of trains between stations as a string.
 * Sample output : 12617  16382  16346  19577  16334

*/
exports.getJsonTrainBtw =function (source, dest, date, eventCallback){
         var mon= date.substring(5,7);
         var day= date.substring(8);
         date=day+"-"+mon;
         var url=config.getBaseUrl()+"between/source/"+source+"/dest/"+dest+"/date/"+date+"/apikey/"+apiKey+"/";
         var stat="";
         var train_string="";
        http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var train_no=[];
            var src_departure_time=[];
            var dest_arrival_time=[];
            var days=[];
            var index=0;
            for(i=0; i<stringResult["train"].length; i++){
                days[i]="";
                train_no[i]=stringResult["train"][i].number;
                src_departure_time[i]=stringResult["train"][i].src_departure_time;
                dest_arrival_time[i]=stringResult["train"][i].dest_arrival_time;
                for  (j=0; j<stringResult["train"][i]["days"].length; j++){
                        if(stringResult["train"][i]["days"][j].runs==="Y")
                          {
                            switch(j){
                               case 0: days[i]=days[i]+"monday, ";
                                       break;
                               case 1: days[i]=days[i]+"tuesday, ";
                                       break;
                               case 2: days[i]=days[i]+"wednesday, ";
                                       break;
                               case 3: days[i]=days[i]+"thursday, ";
                                       break;
                               case 4: days[i]=days[i]+"friday, ";
                                       break;
                               case 5: days[i]=days[i]+"saturday, ";
                                       break;
                               case 6: days[i]=days[i]+"sunday, ";
                                       break;
                              }
                            }
                     }
              }
             stat= stat+ "Total "+i+" trains are there.";
             var m=0;
            for (j=0; j<i; j++){
               m=j+1;
               if(m<=3)
                 {
                  stat = stat + "Train "+m+ '.';
                   stat = stat+" Source departure time :"+src_departure_time[j]+", Destination arrival time "+dest_arrival_time[j]+", Days of run "+days[j]+".";
                   }
               train_string = train_string + "Train "+m+ '\n';
               train_string =train_string+" Source departure time :"+src_departure_time[j]+"\n Destination arrival time "+dest_arrival_time[j]+"\n Days of run "+days[j]+"\n";

               }

               if(stringResult.response_code!='200'){
                    train_string="There was an error processing your request.";
                     stat=train_string;
                   }
             stat=stat+ "For details of all other trains see the result card."
             var result={speech:stat,status:train_string,heading:"Trains running between "+source+" and "+dest};
             eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        train_string = "sorry, we could not process your request.";
        var result={speech:train_string,status:train_string,heading:null};
        eventCallback(result);
    });
}

exports.getJsonPNRstatus=function (pnr_no, eventCallback){
    var result="";
    var stat="";
      var train_name="Hi";
     var url =config.getBaseUrl() +'pnr_status/pnr/'+pnr_no+'/apikey/'+ apiKey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
           var train_no;
            var doj="";
            var Class="";
            var chart_prepared="";
            var total_passengers;
            var booking_status=[];
            var current_status=[];
            var coach_position =[];
            var stringResult = JSON.parse(body);
             var c="";
            train_no= stringResult.train_no;
            doj= stringResult.doj;
            Class= stringResult.class;
            chart_prepared= stringResult.chart_prepared;
            total_passengers= stringResult.total_passengers;
           result= result+"Starting date is "+doj+"\n Class is "+Class+"\n Chart prepared "+chart_prepared+"\n Total number of passengers "+total_passengers+"\n Details of each passengers\n";
           result= result+"Starting date is "+doj+". Class is "+Class+". Chart prepared "+chart_prepared+". Total number of passengers "+total_passengers+". Details of each passengers.";

            for ( i=0; i<stringResult["passengers"].length; i++){
               booking_status[i]=stringResult["passengers"][i].booking_status;
               current_status[i]=stringResult["passengers"][i].current_status;
               coach_position[i]=stringResult["passengers"][i].coach_position;

              }
             var m=0;
            for (j=0; j<i; j++){
               m=j+1;
               result = result + "passenger "+m+ '\n';
               result=result+" Booking status "+booking_status[j]+"\n Current status "+current_status[j]+"\n Coach position "+coach_position[j]+"\n";
               if(current_status[j]==="CAN/MOD")
                  current_status[j]="cancelled or modified.";
              if(current_status[j]==="CNF/Confirmed")
                  {
                    current_status[j]="confirmed, Coach/Berth number will be available after chart preparation.";
                  }
                else if(chart_prepared==="Y"){
                    c=current_status[j];
                    current_status[j]= "confirmed, coach and berth position is "+ c+".";
                }

               stat=stat+" passenger "+m+", current status is "+current_status[j]+".";
               }

               stat=stat+" For further details see the result card.";
                if(stringResult.response_code=='410'){
                    result="PNR does not exist.";
                    stat=result;
                   }
            var result1={speech:stat,status:result,heading:"PNR status of: "+pnr_no};

            eventCallback(result1);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
         result = "sorry, we could not process your request.";
        var result1={speech:result,status:result,heading:null};
        eventCallback(result1);
    });
}

exports.getJsonTrainArrivals=function (station_code,hrs, eventCallback){
    var result="";
    var url =config.getBaseUrl() +'arrivals/station/'+station_code+'/hours/'+hrs+'/apikey/'+ apiKey+'/';

    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
           var train_no=[];
            var actdep=[];
            var delaydep=[];
            var scharr=[];
            var delayarr=[];
            var schdep =[];
            var stringResult = JSON.parse(body);
             for (i=0; i<stringResult["train"].length; i++){
                train_no[i]=stringResult["train"][i].number;
                scharr[i]=stringResult["train"][i].scharr;
                delayarr[i]=stringResult["train"][i].delayarr;
                schdep[i]=stringResult["train"][i].schdep;
                actdep[i]=stringResult["train"][i].actdep;
                delaydep[i]=stringResult["train"][i].delaydep;

              }
             var m=0;
            for ( j=0; j<i; j++){
               m=j+1;
               result = result + "Train "+train_no[j]+ '.';
               result=result+", Scheduled arrival "+scharr[j]+", Delayed arrival "+delayarr[j]+", Scheduled departure "+schdep[j]+", actual departure "+actdep[j]+", delayed departure "+delaydep[j]+".";

               }
               if(stringResult.response_code!='200')
                    result="There was an error processing your request.";
            var result1={speech:result,status:result,heading:"Train arrivals at station: "+station_code};
            eventCallback(result1);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
         result = "sorry, we could not process your request.";
         var result1={speech:result,status:result,heading:null};
         eventCallback(result1);
    });
}

/*exports.getJsonTrainName = function (train_no){
    var state="";
    var result="";
    var url =baseUrl +'/name_number/train/'+train_no+'/apikey/'+ apikey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.stringify(body);
            var index=0;
            var index2=0
            var train_numbers=[];
            var train_string="";
            var index=stringResult.indexOf("name")
            var index1=stringResult.indexOf("}",index)
            var name =stringResult.substring(index+10,index1-8);
            result=name;
            if(stringResult.indexOf("error") > -1) {
                 state = "error";
                }
            else
                 state = "success";

        });
    }).on('error', function (e) {
        state = "error";
    });
}

function numberToName(train_no,eventCallback){
    var baseURL="http://api.railwayapi.com";
    var apiKey="bkxel1825";
    var state="";
    var result="";
    var url =baseURL +'/name_number/train/'+train_no+'/apikey/'+ apiKey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            eventCallback(stringResult.train.name);

        });
    }).on('error', function (e) {
        state = "error";
    });
}
*/

<commit_msg>Minor bugfix. -Snippy<commit_after>'use strict';
var config = require('../../configs');

var http = require('http');

/**
 *The AlexaSkill Module that has the AlexaSkill prototype and helper functions
 */

var apiKey=config.getAPIKey();
var i=0,j=0;
/**
 * This function will return the train status as a string.
 * Sample output : Train departed from KARUKKUTTY(KUC) and late by 24 minutes.
 */
exports.getJsonLiveStatus= function (train_no,doj,eventCallback){

    var url =config.getBaseUrl()+"live/train/"+train_no+"/doj/"+doj+"/apikey/"+apiKey+"/";
    var state="";
    var status= "";
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var status=stringResult.position;
            if(stringResult.response_code!='200')
                    status="There was an error processing your request.";
            var result={speech:status,status:stringResult.position,heading:'Train Number: '+train_no};
            eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        status= "Sorry, we could not process your request.";

        var result={speech:status,status:status,heading:null};
        eventCallback(result);
    });
   return status;
}

/**
 * This function will return the stations in a route as a string.
 * Sample output : KANYAKUMARI,Source,14:10,1,  NAGARCOIL JN,14:30,14:35,1,  KULITTHURAI,15:14,15:15,1,  TRIVANDRUM CNTL,15:55,16:00,1,  KOLLAM JN,17:00,17:05,1,  KAYANKULAM,17:34,17:36,1 (Station     **name,Arriavl time,Departure time,Day of arrival.)
 */
exports.getJsonTrainRoute=function (train_no,eventCallback){

    var url =config.getBaseUrl()+'route/train/'+train_no+'/apikey/'+ apiKey+'/';
       var station_string="";
    var state = "";
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var station_names=[];
            var station_arrival=[];
            var station_dep=[];
            var day=[];
            for (i=0; i<stringResult.route.length; i++){
                station_names[i]=stringResult.route[i].fullname;
                station_arrival[i]=stringResult.route[i].scharr;
                station_dep[i]=stringResult.route[i].schdep;
                day[i]=stringResult.route[i].day;
                }
             var m=0;
             var update=Math.ceil(((stringResult.route.length-2)/5));
             var source_=station_names[0];
             var dest_=station_names[i-1];

             station_string=station_string+"The train starts from "+source_+" at "+station_dep[0]+" and arrives  "+dest_+" at "+station_arrival[i-1]+" on day "+day[i-1]+" passing through ";
            for (j=0; j<i-1; j=j+update){
               m=j+1;
              if((j+update)<(i-1))
                 station_string=station_string+station_names[j]+",";
                else
                 station_string=station_string+" and "+station_names[j]+".";
               }
               if(stringResult.response_code!='200')
                    station_string="There was an error processing your request.";
            var result={speech:station_string,status:station_string,heading:"Route of Train Number: "+train_no};
            eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        status= "Sorry, we could not process your request.";
        var result={speech:status,status:status,heading:null};
        eventCallback(result);
    });
}

/**
 * This function will return the seat availability as string.
 * Sample output : AVAILABLE 11

*/
exports.getJsonSeatAvailability = function (train_no, source, dest, date, _class, quota,eventCallback){
    var url =config.getBaseUrl() +'/check_seat/train/'+train_no+'/source/'+ source +'/dest/'+dest+'/date/'+ date+'/class/'+_class+'/quota/'+quota+'/apikey/'+ apiKey+'/';
    var status = "";
      http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var index3=0;
            var index4=0;
            var status=stringResult.availability[0].status;
            if(status.indexOf('AVAILABLE')>-1)
            {
                var index_=status.indexOf('AVAILABLE');
                var available=status.substring(index_+10);
            }
            status=available+" seats are available.";
            if(status.charAt(0)=='G'&&status.charAt(1)=='N'&&status.charAt(2)=='W')
               {
                 index3=status.indexOf("/WL");
                 index4=status.indexOf("\n",index3);
                 var waiting=status.substring(index3+3,index3+8);
                 var status=waiting+" seats are in waiting list.";
                }
                if(stringResult.response_code!='200')
                    status="There was an error processing your request.";
             var result={speech:status,status:status,heading:"Seat availability of Train: "+train_no};
             eventCallback(result);
        });
    }).on('error', function (e) {
             var result={speech:"Sorry, we could not process your request.",status:"Sorry, we could not process your request.",heading:null};
             eventCallback(result);
    });
}

/**
 * This function will return the train numbers of trains between stations as a string.
 * Sample output : 12617  16382  16346  19577  16334

*/
exports.getJsonTrainBtw =function (source, dest, date, eventCallback){
         var mon= date.substring(5,7);
         var day= date.substring(8);
         date=day+"-"+mon;
         var url=config.getBaseUrl()+"between/source/"+source+"/dest/"+dest+"/date/"+date+"/apikey/"+apiKey+"/";
         var stat="";
         var train_string="";
        http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var train_no=[];
            var src_departure_time=[];
            var dest_arrival_time=[];
            var days=[];
            var index=0;
            for(i=0; i<stringResult["train"].length; i++){
                days[i]="";
                train_no[i]=stringResult["train"][i].number;
                src_departure_time[i]=stringResult["train"][i].src_departure_time;
                dest_arrival_time[i]=stringResult["train"][i].dest_arrival_time;
                for  (j=0; j<stringResult["train"][i]["days"].length; j++){
                        if(stringResult["train"][i]["days"][j].runs==="Y")
                          {
                            switch(j){
                               case 0: days[i]=days[i]+"monday, ";
                                       break;
                               case 1: days[i]=days[i]+"tuesday, ";
                                       break;
                               case 2: days[i]=days[i]+"wednesday, ";
                                       break;
                               case 3: days[i]=days[i]+"thursday, ";
                                       break;
                               case 4: days[i]=days[i]+"friday, ";
                                       break;
                               case 5: days[i]=days[i]+"saturday, ";
                                       break;
                               case 6: days[i]=days[i]+"sunday, ";
                                       break;
                              }
                            }
                     }
              }
             stat= stat+ "Total "+train_no[j]+" trains are there.";
             var m=0;
            for (j=0; j<i; j++){
               m=j+1;
               if(m<=3)
                 {
                  stat = stat + "Train "+m+ '.';
                   stat = stat+" Source departure time :"+src_departure_time[j]+", Destination arrival time "+dest_arrival_time[j]+", Days of run "+days[j]+".";
                   }
               train_string = train_string + "Train "+m+ '\n';
               train_string =train_string+" Source departure time :"+src_departure_time[j]+"\n Destination arrival time "+dest_arrival_time[j]+"\n Days of run "+days[j]+"\n";

               }

               if(stringResult.response_code!='200'){
                    train_string="There was an error processing your request.";
                     stat=train_string;
                   }
             stat=stat+ "For details of all other trains see the result card."
             var result={speech:stat,status:train_string,heading:"Trains running between "+source+" and "+dest};
             eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        train_string = "sorry, we could not process your request.";
        var result={speech:train_string,status:train_string,heading:null};
        eventCallback(result);
    });
}

exports.getJsonPNRstatus=function (pnr_no, eventCallback){
    var result="";
    var stat="";
      var train_name="Hi";
     var url =config.getBaseUrl() +'pnr_status/pnr/'+pnr_no+'/apikey/'+ apiKey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
           var train_no;
            var doj="";
            var Class="";
            var chart_prepared="";
            var total_passengers;
            var booking_status=[];
            var current_status=[];
            var coach_position =[];
            var stringResult = JSON.parse(body);
             var c="";
            train_no= stringResult.train_no;
            doj= stringResult.doj;
            Class= stringResult.class;
            chart_prepared= stringResult.chart_prepared;
            total_passengers= stringResult.total_passengers;
           result= result+"Starting date is "+doj+"\n Class is "+Class+"\n Chart prepared "+chart_prepared+"\n Total number of passengers "+total_passengers+"\n Details of each passengers\n";
           result= result+"Starting date is "+doj+". Class is "+Class+". Chart prepared "+chart_prepared+". Total number of passengers "+total_passengers+". Details of each passengers.";

            for ( i=0; i<stringResult["passengers"].length; i++){
               booking_status[i]=stringResult["passengers"][i].booking_status;
               current_status[i]=stringResult["passengers"][i].current_status;
               coach_position[i]=stringResult["passengers"][i].coach_position;

              }
             var m=0;
            for (j=0; j<i; j++){
               m=j+1;
               result = result + "passenger "+m+ '\n';
               result=result+" Booking status "+booking_status[j]+"\n Current status "+current_status[j]+"\n Coach position "+coach_position[j]+"\n";
               if(current_status[j]==="CAN/MOD")
                  current_status[j]="cancelled or modified.";
              if(current_status[j]==="CNF/Confirmed")
                  {
                    current_status[j]="confirmed, Coach/Berth number will be available after chart preparation.";
                  }
                else if(chart_prepared==="Y"){
                    c=current_status[j];
                    current_status[j]= "confirmed, coach and berth position is "+ c+".";
                }

               stat=stat+" passenger "+m+", current status is "+current_status[j]+".";
               }

               stat=stat+" For further details see the result card.";
                if(stringResult.response_code=='410'){
                    result="PNR does not exist.";
                    stat=result;
                   }
            var result1={speech:stat,status:result,heading:"PNR status of: "+pnr_no};

            eventCallback(result1);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
         result = "sorry, we could not process your request.";
        var result1={speech:result,status:result,heading:null};
        eventCallback(result1);
    });
}

exports.getJsonTrainArrivals=function (station_code,hrs, eventCallback){
    var result="";
    var url =config.getBaseUrl() +'arrivals/station/'+station_code+'/hours/'+hrs+'/apikey/'+ apiKey+'/';

    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
           var train_no=[];
            var actdep=[];
            var delaydep=[];
            var scharr=[];
            var delayarr=[];
            var schdep =[];
            var stringResult = JSON.parse(body);
             for (i=0; i<stringResult["train"].length; i++){
                train_no[i]=stringResult["train"][i].number;
                scharr[i]=stringResult["train"][i].scharr;
                delayarr[i]=stringResult["train"][i].delayarr;
                schdep[i]=stringResult["train"][i].schdep;
                actdep[i]=stringResult["train"][i].actdep;
                delaydep[i]=stringResult["train"][i].delaydep;

              }
             var m=0;
            for ( j=0; j<i; j++){
               m=j+1;
               result = result + "Train "+train_no[j]+ '.';
               result=result+", Scheduled arrival "+scharr[j]+", Delayed arrival "+delayarr[j]+", Scheduled departure "+schdep[j]+", actual departure "+actdep[j]+", delayed departure "+delaydep[j]+".";

               }
               if(stringResult.response_code!='200')
                    result="There was an error processing your request.";
            var result1={speech:result,status:result,heading:"Train arrivals at station: "+station_code};
            eventCallback(result1);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
         result = "sorry, we could not process your request.";
         var result1={speech:result,status:result,heading:null};
         eventCallback(result1);
    });
}

/*exports.getJsonTrainName = function (train_no){
    var state="";
    var result="";
    var url =baseUrl +'/name_number/train/'+train_no+'/apikey/'+ apikey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.stringify(body);
            var index=0;
            var index2=0
            var train_numbers=[];
            var train_string="";
            var index=stringResult.indexOf("name")
            var index1=stringResult.indexOf("}",index)
            var name =stringResult.substring(index+10,index1-8);
            result=name;
            if(stringResult.indexOf("error") > -1) {
                 state = "error";
                }
            else
                 state = "success";

        });
    }).on('error', function (e) {
        state = "error";
    });
}

function numberToName(train_no,eventCallback){
    var baseURL="http://api.railwayapi.com";
    var apiKey="bkxel1825";
    var state="";
    var result="";
    var url =baseURL +'/name_number/train/'+train_no+'/apikey/'+ apiKey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            eventCallback(stringResult.train.name);

        });
    }).on('error', function (e) {
        state = "error";
    });
}
*/

<|endoftext|>


<commit_before>//adjectival forms of place names, as adjectives.
module.exports = [
  'afghan',
  'albanian',
  'algerian',
  'angolan',
  'argentine',
  'armenian',
  'australian',
  'aussie',
  'austrian',
  'bangladeshi',
  'belarusian',
  'belgian',
  'bolivian',
  'bosnian',
  'brazilian',
  'bulgarian',
  'cambodian',
  'cameroonian',
  'canadian',
  'chadian',
  'chilean',
  'chinese',
  'colombian',
  'congolese',
  'croatian',
  'cuban',
  'czech',
  'dominican',
  'danish',
  'egyptian',
  'british',
  'estonian',
  'ethiopian',
  'ecuadorian',
  'finnish',
  'french',
  'gambian',
  'georgian',
  'german',
  'greek',
  'ghanaian',
  'guatemalan',
  'haitian',
  'hungarian',
  'honduran',
  'icelandic',
  'indian',
  'indonesian',
  'iranian',
  'iraqi',
  'irish',
  'israeli',
  'italian',
  'ivorian',  // of Ivory Coast
  'jamaican',
  'japanese',
  'jordanian',
  'kazakh',
  'kenyan',
  'korean',
  'kuwaiti',
  'lao',    // of Laos
  'latvian',
  'lebanese',
  'liberian',
  'libyan',
  'lithuanian',
  'namibian',
  'malagasy', // of Madagascar
  'macedonian',
  'malaysian',
  'mexican',
  'mongolian',
  'moroccan',
  'dutch',
  'nicaraguan',
  'nigerian', // of Nigeria
  'nigerien', // of Niger
  'norwegian',
  'omani',
  'panamanian',
  'paraguayan',
  'pakistani',
  'palestinian',
  'peruvian',
  'philippine',
  'filipino',
  'polish',
  'portuguese',
  'qatari',
  'romanian',
  'russian',
  'rwandan',
  'samoan',
  'saudi',
  'scottish',
  'senegalese',
  'serbian',
  'singaporean',
  'slovak',
  'somalian',
  'sudanese',
  'swedish',
  'swiss',
  'syrian',
  'taiwanese',
  'trinidadian',
  'thai',
  'tunisian',
  'turkmen',
  'ugandan',
  'ukrainian',
  'american',
  'hindi',
  'spanish',
  'venezuelan',
  'vietnamese',
  'welsh',
  'zambian',
  'zimbabwean',
  'english',
  'african',
  'european',
  'asian',
  'californian',
];
<commit_msg>Added basque people :)<commit_after>//adjectival forms of place names, as adjectives.
module.exports = [
  'afghan',
  'albanian',
  'algerian',
  'angolan',
  'argentine',
  'armenian',
  'australian',
  'aussie',
  'austrian',
  'bangladeshi',
  'basque', // of Basque Country
  'belarusian',
  'belgian',
  'bolivian',
  'bosnian',
  'brazilian',
  'bulgarian',
  'cambodian',
  'cameroonian',
  'canadian',
  'chadian',
  'chilean',
  'chinese',
  'colombian',
  'congolese',
  'croatian',
  'cuban',
  'czech',
  'dominican',
  'danish',
  'egyptian',
  'british',
  'estonian',
  'ethiopian',
  'ecuadorian',
  'finnish',
  'french',
  'gambian',
  'georgian',
  'german',
  'greek',
  'ghanaian',
  'guatemalan',
  'haitian',
  'hungarian',
  'honduran',
  'icelandic',
  'indian',
  'indonesian',
  'iranian',
  'iraqi',
  'irish',
  'israeli',
  'italian',
  'ivorian',  // of Ivory Coast
  'jamaican',
  'japanese',
  'jordanian',
  'kazakh',
  'kenyan',
  'korean',
  'kuwaiti',
  'lao',    // of Laos
  'latvian',
  'lebanese',
  'liberian',
  'libyan',
  'lithuanian',
  'namibian',
  'malagasy', // of Madagascar
  'macedonian',
  'malaysian',
  'mexican',
  'mongolian',
  'moroccan',
  'dutch',
  'nicaraguan',
  'nigerian', // of Nigeria
  'nigerien', // of Niger
  'norwegian',
  'omani',
  'panamanian',
  'paraguayan',
  'pakistani',
  'palestinian',
  'peruvian',
  'philippine',
  'filipino',
  'polish',
  'portuguese',
  'qatari',
  'romanian',
  'russian',
  'rwandan',
  'samoan',
  'saudi',
  'scottish',
  'senegalese',
  'serbian',
  'singaporean',
  'slovak',
  'somalian',
  'sudanese',
  'swedish',
  'swiss',
  'syrian',
  'taiwanese',
  'trinidadian',
  'thai',
  'tunisian',
  'turkmen',
  'ugandan',
  'ukrainian',
  'american',
  'hindi',
  'spanish',
  'venezuelan',
  'vietnamese',
  'welsh',
  'zambian',
  'zimbabwean',
  'english',
  'african',
  'european',
  'asian',
  'californian',
];
<|endoftext|>


<commit_before>'use strict';

let _        = require('lodash');
let bluebird = require('bluebird');
let readFile = bluebird.promisify(require('fs').readFile);
let path     = require('path');

let registry = require('./tasks');
let utility  = require('./utility');

let directory;

function templateAllFunc(blobs) {
  let name = path.join('demo', 'index.html');

  blobs = _.compact(blobs);

  return bluebird.join(
    readFile(name),
    utility.getStyleNames(),
    (template, styles) => ({ template, path, blobs, styles })
  );
}

function copyDocs() {
  let input  = path.join(directory.root, 'docs', '*.rst'),
      output = path.join(directory.build, 'docs');

  return {
    startLog: { task: ['log', 'Copying documentation.'] },
    read: { requires: 'startLog', task: ['glob', utility.glob(input)] },
    writeLog: { requires: 'read', task: ['log', 'Writing documentation.'] },
    write: { requires: 'writeLog', task: ['dest', output] }
  };
}

function generateDemo(filterCB, readArgs) {
  let staticArgs   = utility.glob(path.join('demo', '*.{js,css}')),
      stylesArgs   = utility.glob(path.join('src', 'styles', '*'), 'binary'),
      demoRoot     = path.join(directory.build, 'demo'),
      templateArgs = { callback: templateAllFunc },
      destArgs     = {
        dir: path.join(demoRoot, 'styles'),
        encoding: 'binary'
      };

  return {
    logStart: { task: ['log', 'Generating demo.'] },
    readLanguages: { requires: 'logStart', task: ['glob', readArgs] },
    filterSnippets: { requires: 'readLanguages', task: ['filter', filterCB] },
    readSnippet: { requires: 'filterSnippets', task: 'readSnippet' },
    template: {
      requires: 'readSnippet',
      task: ['templateAll', templateArgs]
    },
    write: {
      requires: 'template',
      task: ['write', path.join(demoRoot, 'index.html')]
    },
    readStatic: { requires: 'logStart', task: ['glob', staticArgs] },
    writeStatic: { requires: 'readStatic', task: ['dest', demoRoot] },
    readStyles: { requires: 'logStart', task: ['glob', stylesArgs] },
    writeStyles: { requires: 'readStyles', task: ['dest', destArgs] }
  };
}

module.exports = function(commander, dir) {
  directory = dir;

  let hljsExt, output, requiresTask, tasks,
      replace           = utility.replace,
      regex             = utility.regex,
      replaceClassNames = utility.replaceClassNames,

      coreFile     = path.join('src', 'highlight.js'),
      languages    = utility.glob(path.join('src', 'languages', '*.js')),
      filterCB     = utility.buildFilterCallback(commander.args),
      replaceArgs  = replace(regex.header, ''),
      templateArgs =
        'hljs.registerLanguage(\'<%= name %>\', <%= content %>);\n';

  tasks = {
    startLog: { task: ['log', 'Building highlight.js pack file.'] },
    readCore: { requires: 'startLog', task: ['read', coreFile] },
    read: { requires: 'startLog', task: ['glob', languages] },
    filter: { requires: 'read', task: ['filter', filterCB] },
    reorder: { requires: 'filter', task: 'reorderDeps' },
    replace: { requires: 'reorder', task: ['replace', replaceArgs] },
    template: { requires: 'replace', task: ['template', templateArgs] },
    packageFiles: {
      requires: ['readCore', 'template'],
      task: 'packageFiles'
    }
  };
  requiresTask = 'packageFiles';

  if(commander.compress || commander.target === 'cdn') {
    tasks.compresslog = {
      requires: requiresTask,
      task: ['log', 'Compressing highlight.js pack file.']
    };

    tasks.replace2 = {
      requires: 'compresslog',
      task: [ 'replaceSkippingStrings'
            , replace(regex.replaces, replaceClassNames)
            ]
    };

    tasks.replace3 = {
      requires: 'replace2',
      task: ['replace', replace(regex.classname, '$1.className')]
    };

    tasks.minify  = { requires: 'replace3', task: 'jsminify' };
    requiresTask  = 'minify';
  }

  tasks.insertLicenseTag = {
    requires: requiresTask,
    task: 'insertLicenseTag'
  };

  tasks.writelog = {
    requires: 'insertLicenseTag',
    task: ['log', 'Writing highlight.js pack file.']
  };

  hljsExt = commander.target === 'cdn' ? 'min' : 'pack';
  output  = path.join(directory.build, `highlight.${hljsExt}.js`);

  tasks.write = {
    requires: 'writelog',
    task: ['write', output]
  };

  tasks = (commander.target === 'browser')
        ? [copyDocs(), generateDemo(filterCB, languages), tasks]
        : [tasks];

  return utility.toQueue(tasks, registry);
};
<commit_msg>Use const when it makes sense in `browser` target<commit_after>'use strict';

let _        = require('lodash');
let bluebird = require('bluebird');
let readFile = bluebird.promisify(require('fs').readFile);
let path     = require('path');

let registry = require('./tasks');
let utility  = require('./utility');

let directory;

function templateAllFunc(blobs) {
  const name = path.join('demo', 'index.html');

  blobs = _.compact(blobs);

  return bluebird.join(
    readFile(name),
    utility.getStyleNames(),
    (template, styles) => ({ template, path, blobs, styles })
  );
}

function copyDocs() {
  const input  = path.join(directory.root, 'docs', '*.rst'),
        output = path.join(directory.build, 'docs');

  return {
    startLog: { task: ['log', 'Copying documentation.'] },
    read: { requires: 'startLog', task: ['glob', utility.glob(input)] },
    writeLog: { requires: 'read', task: ['log', 'Writing documentation.'] },
    write: { requires: 'writeLog', task: ['dest', output] }
  };
}

function generateDemo(filterCB, readArgs) {
  let staticArgs   = utility.glob(path.join('demo', '*.{js,css}')),
      stylesArgs   = utility.glob(path.join('src', 'styles', '*'), 'binary'),
      demoRoot     = path.join(directory.build, 'demo'),
      templateArgs = { callback: templateAllFunc },
      destArgs     = {
        dir: path.join(demoRoot, 'styles'),
        encoding: 'binary'
      };

  return {
    logStart: { task: ['log', 'Generating demo.'] },
    readLanguages: { requires: 'logStart', task: ['glob', readArgs] },
    filterSnippets: { requires: 'readLanguages', task: ['filter', filterCB] },
    readSnippet: { requires: 'filterSnippets', task: 'readSnippet' },
    template: {
      requires: 'readSnippet',
      task: ['templateAll', templateArgs]
    },
    write: {
      requires: 'template',
      task: ['write', path.join(demoRoot, 'index.html')]
    },
    readStatic: { requires: 'logStart', task: ['glob', staticArgs] },
    writeStatic: { requires: 'readStatic', task: ['dest', demoRoot] },
    readStyles: { requires: 'logStart', task: ['glob', stylesArgs] },
    writeStyles: { requires: 'readStyles', task: ['dest', destArgs] }
  };
}

module.exports = function(commander, dir) {
  directory = dir;

  let hljsExt, output, requiresTask, tasks,
      replace           = utility.replace,
      regex             = utility.regex,
      replaceClassNames = utility.replaceClassNames,

      coreFile     = path.join('src', 'highlight.js'),
      languages    = utility.glob(path.join('src', 'languages', '*.js')),
      filterCB     = utility.buildFilterCallback(commander.args),
      replaceArgs  = replace(regex.header, ''),
      templateArgs =
        'hljs.registerLanguage(\'<%= name %>\', <%= content %>);\n';

  tasks = {
    startLog: { task: ['log', 'Building highlight.js pack file.'] },
    readCore: { requires: 'startLog', task: ['read', coreFile] },
    read: { requires: 'startLog', task: ['glob', languages] },
    filter: { requires: 'read', task: ['filter', filterCB] },
    reorder: { requires: 'filter', task: 'reorderDeps' },
    replace: { requires: 'reorder', task: ['replace', replaceArgs] },
    template: { requires: 'replace', task: ['template', templateArgs] },
    packageFiles: {
      requires: ['readCore', 'template'],
      task: 'packageFiles'
    }
  };
  requiresTask = 'packageFiles';

  if(commander.compress || commander.target === 'cdn') {
    tasks.compresslog = {
      requires: requiresTask,
      task: ['log', 'Compressing highlight.js pack file.']
    };

    tasks.replace2 = {
      requires: 'compresslog',
      task: [ 'replaceSkippingStrings'
            , replace(regex.replaces, replaceClassNames)
            ]
    };

    tasks.replace3 = {
      requires: 'replace2',
      task: ['replace', replace(regex.classname, '$1.className')]
    };

    tasks.minify  = { requires: 'replace3', task: 'jsminify' };
    requiresTask  = 'minify';
  }

  tasks.insertLicenseTag = {
    requires: requiresTask,
    task: 'insertLicenseTag'
  };

  tasks.writelog = {
    requires: 'insertLicenseTag',
    task: ['log', 'Writing highlight.js pack file.']
  };

  hljsExt = commander.target === 'cdn' ? 'min' : 'pack';
  output  = path.join(directory.build, `highlight.${hljsExt}.js`);

  tasks.write = {
    requires: 'writelog',
    task: ['write', output]
  };

  tasks = (commander.target === 'browser')
        ? [copyDocs(), generateDemo(filterCB, languages), tasks]
        : [tasks];

  return utility.toQueue(tasks, registry);
};
<|endoftext|>


<commit_before>// Load modules

var Any = require('./any');
var Errors = require('./errors');
var Hoek = require('hoek');

// Declare internals

var internals = {};

internals.Date = function () {

    Any.call(this);
    this._type = 'date';
};

Hoek.inherits(internals.Date, Any);

internals.Date.prototype._base = function (value, state, options) {

    var result = {
        value: (options.convert && internals.toDate(value)) || value
    };

    result.errors = (result.value instanceof Date && !isNaN(result.value.getTime())) ? null : Errors.create('date.base', null, state, options);
    return result;
};

internals.toDate = function (value) {

    if (value instanceof Date) {
        return value;
    }

    if (typeof value === 'string' ||
        Hoek.isInteger(value)) {

        var date = new Date(value);
        if (!isNaN(date.getTime())) {
            return date;
        }
    }

    if (typeof value === 'string') {

        var parsed = parseInt(value, 10);
        if (!isNaN(parsed)) {
            return new Date(parsed);
        }
    }

    return null;
};

internals.Date.prototype.min = function (date) {

    date = internals.toDate(date);
    Hoek.assert(date, 'Invalid date format');

    return this._test('min', date, function (value, state, options) {

        if (value.getTime() >= date.getTime()) {
            return null;
        }

        return Errors.create('date.min', { limit: date }, state, options);
    });
};

internals.Date.prototype.max = function (date) {

    date = internals.toDate(date);
    Hoek.assert(date, 'Invalid date format');

    return this._test('max', date, function (value, state, options) {

        if (value.getTime() <= date.getTime()) {
            return null;
        }

        return Errors.create('date.max', { limit: date }, state, options);
    });
};

module.exports = new internals.Date();
<commit_msg>Clean for #357<commit_after>// Load modules

var Any = require('./any');
var Errors = require('./errors');
var Hoek = require('hoek');

// Declare internals

var internals = {};

internals.Date = function () {

    Any.call(this);
    this._type = 'date';
};

Hoek.inherits(internals.Date, Any);

internals.Date.prototype._base = function (value, state, options) {

    var result = {
        value: (options.convert && internals.toDate(value)) || value
    };

    result.errors = (result.value instanceof Date && !isNaN(result.value.getTime())) ? null : Errors.create('date.base', null, state, options);
    return result;
};

internals.toDate = function (value) {

    if (value instanceof Date) {
        return value;
    }

    if (typeof value === 'string' ||
        Hoek.isInteger(value)) {

        if (typeof value === 'string' &&
            /^\d+$/.test(value)) {

            value = parseInt(value, 10);
        }

        var date = new Date(value);
        if (!isNaN(date.getTime())) {
            return date;
        }
    }

    return null;
};

internals.Date.prototype.min = function (date) {

    date = internals.toDate(date);
    Hoek.assert(date, 'Invalid date format');

    return this._test('min', date, function (value, state, options) {

        if (value.getTime() >= date.getTime()) {
            return null;
        }

        return Errors.create('date.min', { limit: date }, state, options);
    });
};

internals.Date.prototype.max = function (date) {

    date = internals.toDate(date);
    Hoek.assert(date, 'Invalid date format');

    return this._test('max', date, function (value, state, options) {

        if (value.getTime() <= date.getTime()) {
            return null;
        }

        return Errors.create('date.max', { limit: date }, state, options);
    });
};

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


<commit_before>import fs from 'fs'
import babelPreset from '../../../../babel-preset'

// we check which babel config file exists in the project root
const readBabelConfig = root => {
  const babelFiles = [
    `${root}/.babelrc`,
    `${root}/.babelrc.js`,
    `${root}/babel.config.js`,
  ]

  let extendsFile = {}

  babelFiles.forEach(file => {
    try {
      fs.statSync(file)
      extendsFile = { extends: file }
    } catch (err) {
      // dont do anything
    }
  })

  return extendsFile
}

export default function({ config, stage }) {
  let babelFile = {}

  const isRelativePath = config.paths.DIST.startsWith(config.paths.ROOT)

  if (!isRelativePath) {
    babelFile = readBabelConfig(config.paths.ROOT)
  }

  return {
    test: /\.(js|jsx|mjs)$/,
    include: [
      config.paths.SRC,
      `${config.paths.DIST}/react-static-routes.js`,
      `${config.paths.DIST}/react-static-browser-plugins.js`,
    ],
    use: [
      // 'thread-loader',
      {
        loader: 'babel-loader',
        options: {
          ...babelFile,
          root: config.paths.ROOT,
          presets: [[babelPreset, { modules: false }]],
          cacheDirectory: isRelativePath ? stage !== 'prod' : config.paths.TEMP,
          compact: stage === 'prod',
          highlightCode: true,
        },
      },
    ],
  }
}
<commit_msg>make the static files location more flexible (#794)<commit_after>import fs from 'fs'
import babelPreset from '../../../../babel-preset'

// we check which babel config file exists in the project root
const readBabelConfig = root => {
  const babelFiles = [
    `${root}/.babelrc`,
    `${root}/.babelrc.js`,
    `${root}/babel.config.js`,
  ]

  let extendsFile = {}

  babelFiles.forEach(file => {
    try {
      fs.statSync(file)
      extendsFile = { extends: file }
    } catch (err) {
      // dont do anything
    }
  })

  return extendsFile
}

export default function({ config, stage }) {
  let babelFile = {}

  const isRelativePath = config.paths.DIST.startsWith(config.paths.ROOT)

  if (!isRelativePath) {
    babelFile = readBabelConfig(config.paths.ROOT)
  }

  return {
    test: /\.(js|jsx|mjs)$/,
    include: [
      config.paths.SRC,
      /react-static-routes\.js/,
      /react-static-browser-plugins\.js/,
    ],
    use: [
      // 'thread-loader',
      {
        loader: 'babel-loader',
        options: {
          ...babelFile,
          root: config.paths.ROOT,
          presets: [[babelPreset, { modules: false }]],
          cacheDirectory: isRelativePath ? stage !== 'prod' : config.paths.TEMP,
          compact: stage === 'prod',
          highlightCode: true,
        },
      },
    ],
  }
}
<|endoftext|>


<commit_before>'use strict';

const date = {
    timezone: 'local',
    setTimezone: function (timezone) {
        if (timezone) {
            if (timezone == "GMT") date.timezone = "GMT";
            else date.timezone = 'local';
        }
    },
    /**
     * Turn a dateString (YYYY-MM-DD) to an age
     * @param dateString
     * @param date - Optional date to compare with
     * @return int age
     */
    calculateAge:function (dateString, date=new Date()) {
        const dateSplitted = dateString.split('-');
        let birthDate = new Date(dateSplitted[0], +dateSplitted[1] - 1, dateSplitted[2]);
        let age = date.getFullYear() - birthDate.getFullYear();
        let monthsDiff = date.getMonth() - birthDate.getMonth();
        if (monthsDiff < 0 || (monthsDiff === 0 && date.getDate() < birthDate.getDate())) {
            age--;
        }
        return age;
    },
    time: function () {
        let d = new Date();
        return (timezone == "local") ? d.toLocaleTimeString('en-US', {hour12: false}) : d.toISOString().substr(11, 8);
    },
    date: function () {
        let d = new Date();
        return (date.timezone == "local") ? d.toLocaleDateString() : d.toISOString().substr(0, 10);
    },
    datetime: function () {
        let d = new Date();
        return (date.timezone == "local") ? d.toLocaleString() : toISOString().substr(0, 10) + ' ' + d.toISOString().substr(11, 8);
    },
    UTCEpochMS: function () {
        return new Date().getTime();
    },
    UTCEpoch: function () {
        let d = new Date();
        return (d.timezone == "local") ? d.floor(d.getTime() / 1000) : Math.floor(d.getTime() / 1000);
    },
    localEpochMS: function () {
        let d = new Date();
        return (date.timezone == "local") ? d.getTime() + (d.getTimezoneOffset() * 60000) : d.getTime();
    },
    localEpoch: function () {
        let d = new Date();
        return (date.timezone == "local") ? Math.floor((d.getTime() + (d.getTimezoneOffset() * 60)) / 1000) : Math.floor(d.getTime() / 1000);
    }
};
module.exports = date;<commit_msg>Feat: Added YYYYMMDDhhmmss formatted date<commit_after>'use strict';

const date = {
    timezone: 'local',
    setTimezone: function (timezone) {
        if (timezone) {
            if (timezone == "GMT") date.timezone = "GMT";
            else date.timezone = 'local';
        }
    },
    /**
     * Turn a dateString (YYYY-MM-DD) to an age
     * @param dateString
     * @param date - Optional date to compare with
     * @return int age
     */
    calculateAge:function (dateString, date=new Date()) {
        const dateSplitted = dateString.split('-');
        let birthDate = new Date(dateSplitted[0], +dateSplitted[1] - 1, dateSplitted[2]);
        let age = date.getFullYear() - birthDate.getFullYear();
        let monthsDiff = date.getMonth() - birthDate.getMonth();
        if (monthsDiff < 0 || (monthsDiff === 0 && date.getDate() < birthDate.getDate())) {
            age--;
        }
        return age;
    },
    YYYYMMDDhhmmss:function(separatorDate="-", separatorTime=":", separatorBetween=" "){
        const d = new Date;
        return [
                d.getFullYear(),
                string.pad.left(d.getDate(),2,0),
                string.pad.left((d.getMonth()+1),2,0),
            ].join(separatorDate) +separatorBetween +
            [
                string.pad.left(d.getHours(),2,0),
                string.pad.left(d.getMinutes(),2,0),
                string.pad.left(d.getSeconds(),2,0)
            ].join(separatorTime);
    },
    time: function () {
        let d = new Date();
        return (timezone == "local") ? d.toLocaleTimeString('en-US', {hour12: false}) : d.toISOString().substr(11, 8);
    },
    date: function () {
        let d = new Date();
        return (date.timezone == "local") ? d.toLocaleDateString() : d.toISOString().substr(0, 10);
    },
    datetime: function () {
        let d = new Date();
        return (date.timezone == "local") ? d.toLocaleString() : toISOString().substr(0, 10) + ' ' + d.toISOString().substr(11, 8);
    },
    UTCEpochMS: function () {
        return new Date().getTime();
    },
    UTCEpoch: function () {
        let d = new Date();
        return (d.timezone == "local") ? d.floor(d.getTime() / 1000) : Math.floor(d.getTime() / 1000);
    },
    localEpochMS: function () {
        let d = new Date();
        return (date.timezone == "local") ? d.getTime() + (d.getTimezoneOffset() * 60000) : d.getTime();
    },
    localEpoch: function () {
        let d = new Date();
        return (date.timezone == "local") ? Math.floor((d.getTime() + (d.getTimezoneOffset() * 60)) / 1000) : Math.floor(d.getTime() / 1000);
    }
};
module.exports = date;<|endoftext|>


<commit_before>var Filesystem = require('./filesystem');
var fs = require('fs');
var pickle = require('chromium-pickle');

var writeFileListToStream = function(out, list) {
  if (list.length == 0) {
    out.end();
    return;
  }

  var src = fs.createReadStream(list[0]);
  src.on('end', writeFileListToStream.bind(this, out, list.slice(1)));
  src.pipe(out, { end: false });
};

module.exports.writeFilesystem = function(dest, filesystem, files) {
  var headerPickle = pickle.createEmpty();
  headerPickle.writeString(JSON.stringify(filesystem.header));
  headerBuf = headerPickle.toBuffer();

  var sizePickle = pickle.createEmpty();
  sizePickle.writeUInt32(headerBuf.length);
  sizeBuf = sizePickle.toBuffer();

  var out = fs.createWriteStream(dest);
  out.write(sizeBuf);
  out.write(headerBuf, writeFileListToStream.bind(this, out, files));
};

module.exports.readArchiveHeader = function(archive) {
  var fd = fs.openSync(archive, 'r');
  var sizeBuf = new Buffer(8);
  if (fs.readSync(fd, sizeBuf, 0, 8, null) != 8)
    throw new Error('Unable to read header size');

  var sizePickle = pickle.createFromBuffer(sizeBuf);
  var size = sizePickle.createIterator().readUInt32();
  var headerBuf = new Buffer(size);
  if (fs.readSync(fd, headerBuf, 0, size, null) != size)
    throw new Error('Unable to read header');
  fs.closeSync(fd);

  var headerPickle = pickle.createFromBuffer(headerBuf);
  var header = headerPickle.createIterator().readString();
  return { header: JSON.parse(header), headerSize: size };
};

module.exports.readFilesystem = function(archive) {
  var header = this.readArchiveHeader(archive);
  var filesystem = new Filesystem(archive);
  filesystem.header = header.header;
  filesystem.headerSize = header.headerSize;
  return filesystem;
};

module.exports.readFile = function(filesystem, info) {
  var fd = fs.openSync(filesystem.src, 'r');
  var buffer = new Buffer(info.size);
  fs.readSync(fd, buffer, 0, info.size,
              8 + filesystem.headerSize + parseInt(info.offset));
  fs.closeSync(fd);
  return buffer;
}
<commit_msg>Add callback to disk.writeFilesystem<commit_after>var Filesystem = require('./filesystem');
var fs = require('fs');
var pickle = require('chromium-pickle');

var writeFileListToStream = function(out, list, cb) {
  if (list.length == 0) {
    out.end();
    if (cb) {
      cb(null);
    }
    return;
  }

  var src = fs.createReadStream(list[0]);
  src.on('end', writeFileListToStream.bind(this, out, list.slice(1), cb));
  src.pipe(out, { end: false });
};

module.exports.writeFilesystem = function(dest, filesystem, files, cb) {
  var headerPickle = pickle.createEmpty();
  headerPickle.writeString(JSON.stringify(filesystem.header));
  headerBuf = headerPickle.toBuffer();

  var sizePickle = pickle.createEmpty();
  sizePickle.writeUInt32(headerBuf.length);
  sizeBuf = sizePickle.toBuffer();

  var out = fs.createWriteStream(dest);
  out.write(sizeBuf);
  out.write(headerBuf, writeFileListToStream.bind(this, out, files, cb));
};

module.exports.readArchiveHeader = function(archive) {
  var fd = fs.openSync(archive, 'r');
  var sizeBuf = new Buffer(8);
  if (fs.readSync(fd, sizeBuf, 0, 8, null) != 8)
    throw new Error('Unable to read header size');

  var sizePickle = pickle.createFromBuffer(sizeBuf);
  var size = sizePickle.createIterator().readUInt32();
  var headerBuf = new Buffer(size);
  if (fs.readSync(fd, headerBuf, 0, size, null) != size)
    throw new Error('Unable to read header');
  fs.closeSync(fd);

  var headerPickle = pickle.createFromBuffer(headerBuf);
  var header = headerPickle.createIterator().readString();
  return { header: JSON.parse(header), headerSize: size };
};

module.exports.readFilesystem = function(archive) {
  var header = this.readArchiveHeader(archive);
  var filesystem = new Filesystem(archive);
  filesystem.header = header.header;
  filesystem.headerSize = header.headerSize;
  return filesystem;
};

module.exports.readFile = function(filesystem, info) {
  var fd = fs.openSync(filesystem.src, 'r');
  var buffer = new Buffer(info.size);
  fs.readSync(fd, buffer, 0, info.size,
              8 + filesystem.headerSize + parseInt(info.offset));
  fs.closeSync(fd);
  return buffer;
}
<|endoftext|>


<commit_before>mini.Module(
	"engine/map/entity"
)
.requires(
	"engine/map/entityrepository",
	"engine/rendering/animation",
	"engine/rendering/texture",
	"behaviour/trait",
	"basic/mouse"
)
.defines(function(
	EntityRepository,
	Animation,
	Texture,
	Trait,
	Mouse
) {
	var Entity = mini.Class.subclass({
		initialize: function(name, settings) {
			this.name = name;
			this.zIndex = 0;
			this.stateAnimations = {};

			this.pos = Vector2.Zero.copy();
			this.offset = Vector2.Zero.copy();

			// Process/copy given settings.
			this.settings = {};
			settings = settings || {};
			for( var s in settings ) {
				if(!settings.hasOwnProperty(s)) continue;

				this.settings[s] = settings[s];
			}

			this.setState("idle");
			this.tags = [];

			// Draw callbacks
			this.drawCallbacks = [];
		},

		addToLayer: function (layer) {
			layer.addEntity(this);

			return this;
		},

		/*
		 *  State
		 */
		state: function(name) {
			// as getter
			if(typeof name === "undefined") return this.__state__;

			// as setter
			if(typeof name === "string") {
				this.__state__ = name;
			} else if(typeof name === "function") {
				this.__state__ = name(this);
			} else {
				throw "incompatible state data type";
			};

			if(this.hasAnimationForState(name)) this.setAnimationForState(name);
		},

		setState: function(name) {
			this.state(name);
		},

		getState: function() {
			return this.state();
		},

		/*
		 * Tags
		 */
		addTag: function(tag) {
			// check for already existing.
			var exists = false;
			for(var i = 0; i < this.tags.length; i++)
				if(this.tags[i] == tag) {
					exists = true;
					break;
				};

			// do not add an already existing tag
			if (!exists) {
				this.tags.push(tag);
			}
		},

		removeTag: function(tag) {
			var index = this.tags.indexOf(tag);
			if (index !== - 1) {
				this.tags.splice( index, 1 );
			}
		},

		hasTag: function(tag) {
			return this.tags.indexOf(tag) !== -1;
		},

		getTags: function() {
			return this.tags;
		},

		/*
		 * Rendering/Animation
		 */

		// body.aabb AnimationSheet for StateAnimation
		addStateAnimation: function(name, sheet, frameTime, order) {
			this.stateAnimations[name] = new Animation(sheet, frameTime, order);

			// Use newly created Animation if set for current state.
			if(name == this.getState())
				this.setAnimationForState(name);
		},

		hasAnimationForState: function(name) {
			return typeof this.stateAnimations[name] !== "undefined";
		},

		getAnimationForState: function(name) {
			if(!this.hasAnimationForState(name)) throw "Entity has no StateAnimation for state \"" + name + "\".";
			return this.stateAnimations[name];
		},

		setAnimationForState: function(name) {
			this.setAnimation(this.getAnimationForState(name));
		},

		setAnimation: function(animation) {
			this.animation = animation;
		},

		// Texturing
		setTexture: function(texture) {
			this.texture = texture;
		},

		getTexture: function() {
			return this.texture;
		},

		drawTexture: function(renderer) {
			this.getTexture().drawOn(this.getBody(), renderer);
		},

		// DrawCallbacks
		addDrawCallback: function(callback) {
			this.drawCallbacks.push(callback);
		},

		clearDrawCallbacks: function() {
			this.drawCallbacks.length = 0;
		},

		applyDrawCallbacks: function(renderer) {
			for(var drawCallbackIndex in this.drawCallbacks) {
				this.drawCallbacks[drawCallbackIndex].call(this, renderer);
			}
		},

		/*
		 * Physics
		 */
		setBody: function(body) {
			this.body = body;
		},

		getBody: function() {
			return this.body;
		},

		// Checks, whether a point given in world coordinates is contained in the Body.
		contains: function(point) {
			// does not contains any point without a body
			var body = this.getBody();
			if(typeof body === "undefined") return false;
			// check first for aabb
			if(!(body.getAABB().contains(point))) return false;
			return body.contains(point);
		},

		/*
		 * Behavior
		 */
		setTrait: function(trait) {
			this.trait = trait;
		},

		getTrait: function() {
			return this.trait;
		},

		isHovered: function() {
			var worldMouse = env.camera.screenToWorldCoordinates(env.input.mouse);
			return this.contains(worldMouse);
		},

		isClicked: function() {
			if(!env.input.state(Mouse.LeftButton)) return false;
			return this.isHovered();
		},

		/*
		 *  Updating
		 */
		update: function() {
			var trait = this.getTrait();
			if(typeof trait !== "undefined")
				trait.update(this);

			if(typeof this.animation !== "undefined")
				this.animation.update();
		},

		// draw in order:
		// 1. AnimationSheet on bodies bounding box
		// 2. Texture
		// 3. drawCallbacks
		draw: function(renderer) {
			if(typeof this.animation !== "undefined")
				this.animation.draw(this.getBody().getAABB());
			if(typeof this.getTexture() !== "undefined")
				this.drawTexture(renderer);
			this.applyDrawCallbacks(renderer);
		},

		debugDraw: function(debugDraw) {
		}

	});

	Entity.prototype.toJson = function() {
		var json = {
			name: this.name,
			zIndex: this.zIndex,
			state: this.getState(),
			tags: this.tags
		};

		json.stateAnimations = {};
		for(var state in this.stateAnimations)
			json.stateAnimations[state] = this.stateAnimations[state].toJson();

		return json;
	};

	Entity.fromJson = function(json) {

	};

	EntityRepository.addClass("Entity", Entity);

	return Entity;
});
<commit_msg>stub definition of fromJson in Entity<commit_after>mini.Module(
	"engine/map/entity"
)
.requires(
	"engine/map/entityrepository",
	"engine/rendering/animation",
	"engine/rendering/texture",
	"behaviour/trait",
	"basic/mouse"
)
.defines(function(
	EntityRepository,
	Animation,
	Texture,
	Trait,
	Mouse
) {
	var Entity = mini.Class.subclass({
		initialize: function(name, settings) {
			this.name = name;
			this.zIndex = 0;
			this.stateAnimations = {};

			this.pos = Vector2.Zero.copy();
			this.offset = Vector2.Zero.copy();

			// Process/copy given settings.
			this.settings = {};
			settings = settings || {};
			for( var s in settings ) {
				if(!settings.hasOwnProperty(s)) continue;

				this.settings[s] = settings[s];
			}

			this.setState("idle");
			this.tags = [];

			// Draw callbacks
			this.drawCallbacks = [];
		},

		addToLayer: function (layer) {
			layer.addEntity(this);

			return this;
		},

		/*
		 *  State
		 */
		state: function(name) {
			// as getter
			if(typeof name === "undefined") return this.__state__;

			// as setter
			if(typeof name === "string") {
				this.__state__ = name;
			} else if(typeof name === "function") {
				this.__state__ = name(this);
			} else {
				throw "incompatible state data type";
			};

			if(this.hasAnimationForState(name)) this.setAnimationForState(name);
		},

		setState: function(name) {
			this.state(name);
		},

		getState: function() {
			return this.state();
		},

		/*
		 * Tags
		 */
		addTag: function(tag) {
			// check for already existing.
			var exists = false;
			for(var i = 0; i < this.tags.length; i++)
				if(this.tags[i] == tag) {
					exists = true;
					break;
				};

			// do not add an already existing tag
			if (!exists) {
				this.tags.push(tag);
			}
		},

		removeTag: function(tag) {
			var index = this.tags.indexOf(tag);
			if (index !== - 1) {
				this.tags.splice( index, 1 );
			}
		},

		hasTag: function(tag) {
			return this.tags.indexOf(tag) !== -1;
		},

		getTags: function() {
			return this.tags;
		},

		/*
		 * Rendering/Animation
		 */

		// body.aabb AnimationSheet for StateAnimation
		addStateAnimation: function(name, sheet, frameTime, order) {
			this.stateAnimations[name] = new Animation(sheet, frameTime, order);

			// Use newly created Animation if set for current state.
			if(name == this.getState())
				this.setAnimationForState(name);
		},

		hasAnimationForState: function(name) {
			return typeof this.stateAnimations[name] !== "undefined";
		},

		getAnimationForState: function(name) {
			if(!this.hasAnimationForState(name)) throw "Entity has no StateAnimation for state \"" + name + "\".";
			return this.stateAnimations[name];
		},

		setAnimationForState: function(name) {
			this.setAnimation(this.getAnimationForState(name));
		},

		setAnimation: function(animation) {
			this.animation = animation;
		},

		// Texturing
		setTexture: function(texture) {
			this.texture = texture;
		},

		getTexture: function() {
			return this.texture;
		},

		drawTexture: function(renderer) {
			this.getTexture().drawOn(this.getBody(), renderer);
		},

		// DrawCallbacks
		addDrawCallback: function(callback) {
			this.drawCallbacks.push(callback);
		},

		clearDrawCallbacks: function() {
			this.drawCallbacks.length = 0;
		},

		applyDrawCallbacks: function(renderer) {
			for(var drawCallbackIndex in this.drawCallbacks) {
				this.drawCallbacks[drawCallbackIndex].call(this, renderer);
			}
		},

		/*
		 * Physics
		 */
		setBody: function(body) {
			this.body = body;
		},

		getBody: function() {
			return this.body;
		},

		// Checks, whether a point given in world coordinates is contained in the Body.
		contains: function(point) {
			// does not contains any point without a body
			var body = this.getBody();
			if(typeof body === "undefined") return false;
			// check first for aabb
			if(!(body.getAABB().contains(point))) return false;
			return body.contains(point);
		},

		/*
		 * Behavior
		 */
		setTrait: function(trait) {
			this.trait = trait;
		},

		getTrait: function() {
			return this.trait;
		},

		isHovered: function() {
			var worldMouse = env.camera.screenToWorldCoordinates(env.input.mouse);
			return this.contains(worldMouse);
		},

		isClicked: function() {
			if(!env.input.state(Mouse.LeftButton)) return false;
			return this.isHovered();
		},

		/*
		 *  Updating
		 */
		update: function() {
			var trait = this.getTrait();
			if(typeof trait !== "undefined")
				trait.update(this);

			if(typeof this.animation !== "undefined")
				this.animation.update();
		},

		// draw in order:
		// 1. AnimationSheet on bodies bounding box
		// 2. Texture
		// 3. drawCallbacks
		draw: function(renderer) {
			if(typeof this.animation !== "undefined")
				this.animation.draw(this.getBody().getAABB());
			if(typeof this.getTexture() !== "undefined")
				this.drawTexture(renderer);
			this.applyDrawCallbacks(renderer);
		},

		debugDraw: function(debugDraw) {
		}

	});

	Entity.prototype.toJson = function() {
		var json = {
			name: this.name,
			zIndex: this.zIndex,
			state: this.getState(),
			tags: this.tags
		};

		json.stateAnimations = {};
		for(var state in this.stateAnimations)
			json.stateAnimations[state] = this.stateAnimations[state].toJson();

		return json;
	};

	Entity.fromJson = function(json, world) {
		var entity = new Entity(json.name);

		return entity;
	};

	EntityRepository.addClass("Entity", Entity);

	return Entity;
});
<|endoftext|>


<commit_before>'use strict';

var SMTPServer = require('smtp-server').SMTPServer
  , ehlo = {}
;

ehlo.options = {
  port: 10025
  , api: ''
};

ehlo.start = function() {
  console.log('Starting ehlo');
  var smtp = new SMTPServer({
    banner: 'Welcome to Ehlo SMTP Server'
    , disabledCommands: ['STARTTLS', 'AUTH']
    , onData: function(stream, session, callback) {
      stream.pipe(process.stdout);
      stream.on('end', callback);
    }
    , onMailFrom: function(address, session, callback) {
      callback();
    }
    , onRcptTo: function(address, session, callback) {
      callback();
    }
  });

  smtp.listen(
    this.options.port
    , function() {
      console.log('Listening on port [' + ehlo.options.port + ']');
    }
  );
};

ehlo.stop = function() {
  console.log('Stopping ehlo');
};

ehlo.buildShortId = function() {
  return Math.floor(
    Math.random() * 10
  ) + parseInt(
    (new Date()).getTime()
  ).toString(36);
};

module.exports = ehlo;
<commit_msg>Dump parsed email<commit_after>'use strict';

var SMTPServer = require('smtp-server').SMTPServer
  , MailParser = require("mailparser").MailParser
  , ehlo = {}
;

ehlo.options = {
  port: 10025
  , api: ''
};

ehlo.start = function() {
  console.log('Starting ehlo');
  var smtp = new SMTPServer({
    banner: 'Welcome to Ehlo SMTP Server'
    , disabledCommands: ['STARTTLS', 'AUTH']
    , onData: function(stream, session, callback) {
      var mailParser = new MailParser();
      mailParser.on('end', function(mail) {
        console.log(mail);
      });
      stream.pipe(mailParser);
      stream.on('end', callback);
    }
    , onMailFrom: function(address, session, callback) {
      callback();
    }
    , onRcptTo: function(address, session, callback) {
      callback();
    }
  });

  smtp.listen(
    this.options.port
    , function() {
      console.log('Listening on port [' + ehlo.options.port + ']');
    }
  );
};

ehlo.stop = function() {
  console.log('Stopping ehlo');
};

ehlo.buildShortId = function() {
  return Math.floor(
    Math.random() * 10
  ) + parseInt(
    (new Date()).getTime()
  ).toString(36);
};

module.exports = ehlo;
<|endoftext|>


<commit_before>'use strict';
const symbol = require('../utilities/symbol');
const getCallerFile = require('get-caller-file');
const deprecate = require('../utilities/deprecate');

let experiments = {
  MODULE_UNIFICATION: symbol('module-unification'),
  get INSTRUMENTATION() {
    deprecate(`\`experiments.INSTRUMENTATION\` is deprecated now that the feature has landed, use \`instrumentation\` method on your addon instead. Required from: \n${getCallerFile()}`, true);

    return 'instrumentation';
  },
};

Object.freeze(experiments);

module.exports = experiments;
<commit_msg>Enable CONFIG_CACHING experiment<commit_after>'use strict';
const symbol = require('../utilities/symbol');
const getCallerFile = require('get-caller-file');
const deprecate = require('../utilities/deprecate');

let experiments = {
  CONFIG_CACHING: symbol('config-caching'),
  MODULE_UNIFICATION: symbol('module-unification'),
  get INSTRUMENTATION() {
    deprecate(`\`experiments.INSTRUMENTATION\` is deprecated now that the feature has landed, use \`instrumentation\` method on your addon instead. Required from: \n${getCallerFile()}`, true);

    return 'instrumentation';
  },
};

Object.freeze(experiments);

module.exports = experiments;
<|endoftext|>


<commit_before>import createGraph from '../query/lib/createGraph.js';
import recursiveCompose from '../query/lib/recursiveCompose.js';
import hypernova from '../query/hypernova/hypernova.js';
import ExposureConfigSchema from './exposure.config.schema.js';
import enforceMaxDepth from './lib/enforceMaxDepth.js';
import enforceMaxLimit from './lib/enforceMaxLimit.js';
import cleanBody from './lib/cleanBody.js';
import deepClone from '../query/lib/deepClone';
import restrictFieldsFn from './lib/restrictFields.js';
import restrictLinks from './lib/restrictLinks.js';

let globalConfig = {};

export default class Exposure {
    static setConfig(config) {
        ExposureConfigSchema.clean(config);
        ExposureConfigSchema.validate(config);

        _.extend(globalConfig, config);
    }

    static getConfig() {
        return globalConfig;
    }

    static restrictFields(...args) {
        return restrictFieldsFn(...args);
    }

    constructor(collection, config = {}) {
        collection.__isExposedForGrapher = true;
        collection.__exposure = this;

        this.collection = collection;
        this.name = `exposure_${collection._name}`;

        this.config = config;
        this._validateAndClean();

        this.initSecurity();

        if (config.publication) {
            this.initPublication();
        }

        if (config.method) {
            this.initMethod();
        }

        if (!config.method && !config.publication) {
            throw new Meteor.Error('weird', 'If you want to expose your collection you need to specify at least one of ["method", "publication"] options to true')
        }

        this.initCountMethod();
    }

    _validateAndClean() {
        if (typeof(this.config) === 'function') {
            const firewall = this.config;
            this.config = {firewall};
        }

        ExposureConfigSchema.clean(this.config);
        ExposureConfigSchema.validate(this.config);

        if (this.config.body) {
            ExposureConfigSchema.validateBody(this.collection, this.config.body);
        }

        this.config = _.extend({}, Exposure.getConfig(), this.config);
    }

    /**
     * Takes the body and intersects it with the exposure body, if it exists.
     *
     * @param body
     * @param userId
     * @returns {*}
     */
    getTransformedBody(body, userId) {
        if (!this.config.body) {
            return body;
        }

        return cleanBody(this.getBody(userId), body);
    }

    /**
     * Gets the exposure body
     */
    getBody(userId) {
        if (!this.config.body) {
            throw new Meteor.Error('missing-body', 'Cannot get exposure body because it was not defined.');
        }

        if (_.isFunction(this.config.body)) {
            return deepClone(
                this.config.body.call(this, userId),
                userId
            );
        } else {
            return deepClone(this.config.body, userId);
        }
    }

    /**
     * Initializing the publication for reactive query fetching
     */
    initPublication() {
        const collection = this.collection;
        const config = this.config;
        const getTransformedBody = this.getTransformedBody.bind(this);

        Meteor.publishComposite(this.name, function (body) {
            let transformedBody = getTransformedBody(body);

            const rootNode = createGraph(collection, transformedBody);

            enforceMaxDepth(rootNode, config.maxDepth);
            restrictLinks(rootNode, this.userId);

            return recursiveCompose(rootNode, this.userId, {
                bypassFirewalls: !!config.body
            });
        });
    }

    /**
     * Initializez the method to retrieve the data via Meteor.call
     */
    initMethod() {
        const collection = this.collection;
        const config = this.config;
        const getTransformedBody = this.getTransformedBody.bind(this);

        const methodBody = function(body) {
            if (!config.blocking) {
                this.unblock();
            }

            let transformedBody = getTransformedBody(body);

            const rootNode = createGraph(collection, transformedBody);

            enforceMaxDepth(rootNode, config.maxDepth);
            restrictLinks(rootNode, this.userId);

            // if there is no exposure body defined, then we need to apply firewalls
            return hypernova(rootNode, this.userId, {
                bypassFirewalls: !!config.body
            });
        };

        Meteor.methods({
            [this.name]: methodBody
        });
    }

    /**
     * Initializez the method to retrieve the count of the data via Meteor.call
     * @returns {*}
     */
    initCountMethod() {
        const collection = this.collection;

        Meteor.methods({
            [this.name + '.count'](body) {
                this.unblock();

                return collection.find(body.$filters || {}, {}, this.userId).count();
            }
        })
    }

    /**
     * Initializes security enforcement
     * THINK: Maybe instead of overriding .find, I could store this data of security inside the collection object.
     */
    initSecurity() {
        const collection = this.collection;
        const {firewall, maxLimit, restrictedFields} = this.config;
        const find = collection.find.bind(collection);
        const findOne = collection.findOne.bind(collection);

        collection.firewall = (filters, options, userId) => {
            if (userId !== undefined) {
                if (firewall) {
                    firewall.call({collection: collection}, filters, options, userId);
                }

                enforceMaxLimit(options, maxLimit);

                if (restrictedFields) {
                    Exposure.restrictFields(filters, options, restrictedFields);
                }
            }
        };

        collection.find = (filters = {}, options = {}, userId = undefined) => {
            collection.firewall(filters, options, userId);

            return find(filters, options);
        };

        collection.findOne = (filters = {}, options = {}, userId = undefined) => {
            collection.firewall(filters, options, userId);

            return findOne(filters, options);
        }
    }
};<commit_msg>more functional approach for _validateAndClean to match simpl-schema<commit_after>import createGraph from '../query/lib/createGraph.js';
import recursiveCompose from '../query/lib/recursiveCompose.js';
import hypernova from '../query/hypernova/hypernova.js';
import ExposureConfigSchema from './exposure.config.schema.js';
import enforceMaxDepth from './lib/enforceMaxDepth.js';
import enforceMaxLimit from './lib/enforceMaxLimit.js';
import cleanBody from './lib/cleanBody.js';
import deepClone from '../query/lib/deepClone';
import restrictFieldsFn from './lib/restrictFields.js';
import restrictLinks from './lib/restrictLinks.js';

let globalConfig = {};

export default class Exposure {
    static setConfig(config) {
        ExposureConfigSchema.clean(config);
        ExposureConfigSchema.validate(config);

        _.extend(globalConfig, config);
    }

    static getConfig() {
        return globalConfig;
    }

    static restrictFields(...args) {
        return restrictFieldsFn(...args);
    }

    constructor(collection, config = {}) {
        collection.__isExposedForGrapher = true;
        collection.__exposure = this;

        this.collection = collection;
        this.name = `exposure_${collection._name}`;

        this.config = this._validateAndClean(config);

        this.initSecurity();

        if (this.config.publication) {
            this.initPublication();
        }

        if (this.config.method) {
            this.initMethod();
        }

        if (!this.config.method && !this.config.publication) {
            throw new Meteor.Error('weird', 'If you want to expose your collection you need to specify at least one of ["method", "publication"] options to true')
        }

        this.initCountMethod();
    }

    _validateAndClean() {
        if (typeof(this.config) === 'function') {
            const firewall = this.config;
            this.config = {firewall};
        }

        this.config = ExposureConfigSchema.clean(this.config);
        ExposureConfigSchema.validate(this.config);

        if (this.config && this.config.body) {
            ExposureConfigSchema.validateBody(this.collection, this.config.body);
        }

        return _.extend({}, Exposure.getConfig(), this.config);
    }

    /**
     * Takes the body and intersects it with the exposure body, if it exists.
     *
     * @param body
     * @param userId
     * @returns {*}
     */
    getTransformedBody(body, userId) {
        if (!this.config.body) {
            return body;
        }

        return cleanBody(this.getBody(userId), body);
    }

    /**
     * Gets the exposure body
     */
    getBody(userId) {
        if (!this.config.body) {
            throw new Meteor.Error('missing-body', 'Cannot get exposure body because it was not defined.');
        }

        if (_.isFunction(this.config.body)) {
            return deepClone(
                this.config.body.call(this, userId),
                userId
            );
        } else {
            return deepClone(this.config.body, userId);
        }
    }

    /**
     * Initializing the publication for reactive query fetching
     */
    initPublication() {
        const collection = this.collection;
        const config = this.config;
        const getTransformedBody = this.getTransformedBody.bind(this);

        Meteor.publishComposite(this.name, function (body) {
            let transformedBody = getTransformedBody(body);

            const rootNode = createGraph(collection, transformedBody);

            enforceMaxDepth(rootNode, config.maxDepth);
            restrictLinks(rootNode, this.userId);

            return recursiveCompose(rootNode, this.userId, {
                bypassFirewalls: !!config.body
            });
        });
    }

    /**
     * Initializez the method to retrieve the data via Meteor.call
     */
    initMethod() {
        const collection = this.collection;
        const config = this.config;
        const getTransformedBody = this.getTransformedBody.bind(this);

        const methodBody = function(body) {
            if (!config.blocking) {
                this.unblock();
            }

            let transformedBody = getTransformedBody(body);

            const rootNode = createGraph(collection, transformedBody);

            enforceMaxDepth(rootNode, config.maxDepth);
            restrictLinks(rootNode, this.userId);

            // if there is no exposure body defined, then we need to apply firewalls
            return hypernova(rootNode, this.userId, {
                bypassFirewalls: !!config.body
            });
        };

        Meteor.methods({
            [this.name]: methodBody
        });
    }

    /**
     * Initializez the method to retrieve the count of the data via Meteor.call
     * @returns {*}
     */
    initCountMethod() {
        const collection = this.collection;

        Meteor.methods({
            [this.name + '.count'](body) {
                this.unblock();

                return collection.find(body.$filters || {}, {}, this.userId).count();
            }
        })
    }

    /**
     * Initializes security enforcement
     * THINK: Maybe instead of overriding .find, I could store this data of security inside the collection object.
     */
    initSecurity() {
        const collection = this.collection;
        const {firewall, maxLimit, restrictedFields} = this.config;
        const find = collection.find.bind(collection);
        const findOne = collection.findOne.bind(collection);

        collection.firewall = (filters, options, userId) => {
            if (userId !== undefined) {
                if (firewall) {
                    firewall.call({collection: collection}, filters, options, userId);
                }

                enforceMaxLimit(options, maxLimit);

                if (restrictedFields) {
                    Exposure.restrictFields(filters, options, restrictedFields);
                }
            }
        };

        collection.find = (filters = {}, options = {}, userId = undefined) => {
            collection.firewall(filters, options, userId);

            return find(filters, options);
        };

        collection.findOne = (filters = {}, options = {}, userId = undefined) => {
            collection.firewall(filters, options, userId);

            return findOne(filters, options);
        }
    }
};<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @flow

import * as React from 'react';
import { render } from '@testing-library/react';
import fs from 'fs';
import { LocalizationProvider, ReactLocalization } from '@fluent/react';
import { lazilyParsedBundles } from '../../app-logic/l10n';

function customRender(children: React$Element<any>, ...args: any) {
  const messages = fs.readFileSync('./locales/en-US/app.ftl', 'UTF-8');
  const bundles = lazilyParsedBundles([['en-US', messages]]);
  const localization = new ReactLocalization(bundles);

  return render(
    <LocalizationProvider l10n={localization}>{children}</LocalizationProvider>,
    ...args
  );
}

// Reexport everything
export * from '@testing-library/react';

// override render method
export { customRender as render };
<commit_msg>Update rerender() in  customRender()<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @flow

import * as React from 'react';
import { render } from '@testing-library/react';
import fs from 'fs';
import { LocalizationProvider, ReactLocalization } from '@fluent/react';
import { lazilyParsedBundles } from '../../app-logic/l10n';

function customRender(children: React$Element<any>, ...args: any) {
  const messages = fs.readFileSync('./locales/en-US/app.ftl', 'UTF-8');
  const bundles = lazilyParsedBundles([['en-US', messages]]);
  const localization = new ReactLocalization(bundles);

  const renderResult = render(
    <LocalizationProvider l10n={localization}>{children}</LocalizationProvider>,
    ...args
  );

  // Rerender function should also wrap the children with the LocalizationProvider.
  const rerender = (children: React$Element<any>, ...args: any) =>
    renderResult.rerender(
      <LocalizationProvider l10n={localization}>
        {children}
      </LocalizationProvider>,
      ...args
    );

  return ({
    ...renderResult,
    rerender,
  }: typeof renderResult);
}

// Reexport everything
export * from '@testing-library/react';

// override render method
export { customRender as render };
<|endoftext|>