<commit_before>cordova.define("cordova-plugin-bcplayer.player", function(require, exports, module) {
var exec = require('cordova/exec');

    var BrightcovePlayerPlugin = function() {
    };

    BrightcovePlayerPlugin.init = function(token) {
        exec(
            successHandler,
            errorHandler,
            "BCPlayerPlugin",
            "init",
            [token || null]
        );
    };

    BrightcovePlayerPlugin.load = function(id) {
      exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "load",
        [id ? id.toString() : null]
      );
    };

    BrightcovePlayerPlugin.enable = function() {
        exec(
            successHandler,
            errorHandler,
            "BCPlayerPlugin",
            "enable",
            []
        );
    };

    BrightcovePlayerPlugin.disable = function() {
        exec(
            successHandler,
            errorHandler,
            "BCPlayerPlugin",
            "disable",
            []
        );
    };

    BrightcovePlayerPlugin.hide = function() {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "hide",
        []
        );
    };

    BrightcovePlayerPlugin.show = function() {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "show",
        []
        );
    };

    BrightcovePlayerPlugin.rate = function(rate) {
        exec(
            successHandler,
            errorHandler,
            "BCPlayerPlugin",
            "rate",
            [rate ? rate.toString() : null]
        );
    };

    BrightcovePlayerPlugin.seek = function(position) {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "seek",
        [position ? position.toString() : null]
        );
    };

    BrightcovePlayerPlugin.pause = function() {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "pause",
        []
        );
    };

    BrightcovePlayerPlugin.play = function() {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "play",
        []
        );
    };

    BrightcovePlayerPlugin.reposition = function(x, y, width, height) {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "reposition",
        [x ? x.toString() : null, y ? y.toString() : null, width ? width.toString() : null, height ? height.toString() : null]
        );
    };

    function successHandler(success) {
      //console.log("[BrightcovePlayerPlugin] OK: " + success);
    }

    function errorHandler(error) {
      //console.error("[BrightcovePlayerPlugin] Error: " + error);
    }

module.exports = BrightcovePlayerPlugin;

});
<commit_msg>Not necessary to define the plugin<commit_after>var exec = require('cordova/exec');

    var BrightcovePlayerPlugin = function() {
    };

    BrightcovePlayerPlugin.init = function(token) {
        exec(
            successHandler,
            errorHandler,
            "BCPlayerPlugin",
            "init",
            [token || null]
        );
    };

    BrightcovePlayerPlugin.load = function(id) {
      exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "load",
        [id ? id.toString() : null]
      );
    };

    BrightcovePlayerPlugin.enable = function() {
        exec(
            successHandler,
            errorHandler,
            "BCPlayerPlugin",
            "enable",
            []
        );
    };

    BrightcovePlayerPlugin.disable = function() {
        exec(
            successHandler,
            errorHandler,
            "BCPlayerPlugin",
            "disable",
            []
        );
    };

    BrightcovePlayerPlugin.hide = function() {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "hide",
        []
        );
    };

    BrightcovePlayerPlugin.show = function() {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "show",
        []
        );
    };

    BrightcovePlayerPlugin.rate = function(rate) {
        exec(
            successHandler,
            errorHandler,
            "BCPlayerPlugin",
            "rate",
            [rate ? rate.toString() : null]
        );
    };

    BrightcovePlayerPlugin.seek = function(position) {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "seek",
        [position ? position.toString() : null]
        );
    };

    BrightcovePlayerPlugin.pause = function() {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "pause",
        []
        );
    };

    BrightcovePlayerPlugin.play = function() {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "play",
        []
        );
    };

    BrightcovePlayerPlugin.reposition = function(x, y, width, height) {
    exec(
        successHandler,
        errorHandler,
        "BCPlayerPlugin",
        "reposition",
        [x ? x.toString() : null, y ? y.toString() : null, width ? width.toString() : null, height ? height.toString() : null]
        );
    };

    function successHandler(success) {
      //console.log("[BrightcovePlayerPlugin] OK: " + success);
    }

    function errorHandler(error) {
      //console.error("[BrightcovePlayerPlugin] Error: " + error);
    }

module.exports = BrightcovePlayerPlugin;

<|endoftext|>


<commit_before>//=============================================================================
// main.js
//=============================================================================

PluginManager.setup($plugins);

window.onload = function() {
    SceneManager.run(Scene_Boot);
    Graphics._switchStretchMode();

};

var sidecarversion = "REPLACEVERSION";
var links = {};
buildLinks();

function buildLinks(){
  var wt = "https://console.cloud.google.com?walkthrough_tutorial_id";
  links.tut_dev1 = wt + "=cloudjourney_intro_cf";
  links.tut_sys1 = wt + "=cloudjourney_intro_ce";
  links.tut_dsc1 = wt + "=cloudjourney_intro_bq";
  links.tut_pro1 = wt + "=cloudjourney_intro_project";
  links.tut_sys2 = wt + "=cloudjourney_02_sys";
}

function setRemoteStatus(label, id){
    var project = $gameActors.actor(5).name().trim();
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://"+project+".appspot.com/status", false);
    xhr.send();

    var results = JSON.parse(xhr.responseText);

    for (var i = 0; i < results.length; i++){
        var r = results[i];
        if (r.quest == label && r.complete){
            setProject(id, r.complete);
        }
    }
    return results;
}

function setProject(id, value){
    $gameSwitches.setValue(id, value);
}

function checkHealth(){
    var project = "NOTAVALIDPROJECTNAME";
    if (typeof $gameActors.actor(5).name() != 'undefined'){
      project = $gameActors.actor(5).name().trim();
    }
    var response = {};
    response.works = false;

    var xhr = new XMLHttpRequest();
    try{
      xhr.open("GET", "https://"+project+".appspot.com/health", false);
      xhr.send();
    } catch(exception) {
        console.log('Bad project.');
        return response;
    }

    if (xhr.status == 404){
        return response;
    }

    var results = JSON.parse(xhr.responseText);

    if (results.msg == "ok"){
        response.works = true;
    }

    return response;
}

function checkVersion(){
  var project = "NOTAVALIDPROJECTNAME";
  if (typeof $gameActors.actor(5).name() != 'undefined'){
    project = $gameActors.actor(5).name().trim();
  }

  var xhr = new XMLHttpRequest();
  try{
    var endpoint = "https://"+project+".appspot.com/version";
    console.log('Endpoint:', endpoint);
    xhr.open("GET", endpoint, false);
    xhr.send();
  } catch(exception) {
      console.log(exception);
      console.log('Bad project');
      return false;
  }

  if (xhr.status == 404){
      console.log('Version isn\'t set, update.');
      return false;
  }

  var results = JSON.parse(xhr.responseText);

  if (results.update){
      console.log('Backend says update.');
      return false;
  }

  if (results.version == sidecarversion){
    console.log('Version set and matches, no update.');
    return true;
  }

  console.log('For some reason, update.');
  return false;
}

function popUp(url){
    var div = document.createElement("div");
    var ok = document.createElement("button");
    var p = document.createElement("p");

    ok.innerHTML = "Ok";
    ok.id="okbtn";
    ok.style.backgroundColor=  "#0000FF"; /* Blue */
    ok.style.border=  "none";
    ok.style.color=  "white";
    ok.style.padding=  "10px 32px";
    ok.style.textAlign=  "center";
    ok.style.textDecoration=  "none";
    ok.style.display=  "inline-block";
    ok.style.fontSize=  "16px";

    div.id = "alert_box";
    div.style.top = "10%";
    div.style.left = "40%";
    div.style.height = "100px";
    div.style.width = "300px";
    div.style.position = "absolute";
    div.style.zIndex = 10;
    div.style.backgroundColor = "#dddddd";
    div.style.padding = "5px 10px";
    div.style.border = "1px solid #999";
    div.style.fontFamily = "'Google Sans', Roboto, Helvetica, Arial, sans-serif";

    p.innerHTML = "Click Ok to launch Cloud Console";

    div.appendChild(p);
    div.appendChild(ok);
    document.getElementsByTagName("body")[0].appendChild(div);
    ok.addEventListener("click", function(){
                                        window.open(url,'_blank');
                                        document.querySelector("#alert_box").remove();
                                    } );
}

function populateProject(){
    var projectid = getAllUrlParams().projectid;

    if (typeof projectid !== "undefined"){
      $gameActors.actor(5).setName(projectid);

    }

    console.log(projectid);

}

function getAllUrlParams(url) {

    // get query string from url (optional) or window
    var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

    // we'll store the parameters here
    var obj = {};

    // if query string exists
    if (queryString) {

      // stuff after # is not part of query string, so get rid of it
      queryString = queryString.split('#')[0];

      // split our query string into its component parts
      var arr = queryString.split('&');

      for (var i = 0; i < arr.length; i++) {
        // separate the keys and the values
        var a = arr[i].split('=');

        // set parameter name and value (use 'true' if empty)
        var paramName = a[0];
        var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];

        // (optional) keep case consistent
        paramName = paramName.toLowerCase();
        if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();

        // if the paramName ends with square brackets, e.g. colors[] or colors[2]
        if (paramName.match(/\[(\d+)?\]$/)) {

          // create key if it doesn't exist
          var key = paramName.replace(/\[(\d+)?\]/, '');
          if (!obj[key]) obj[key] = [];

          // if it's an indexed array e.g. colors[2]
          if (paramName.match(/\[\d+\]$/)) {
            // get the index value and add the entry at the appropriate position
            var index = /\[(\d+)\]/.exec(paramName)[1];
            obj[key][index] = paramValue;
          } else {
            // otherwise add the value to the end of the array
            obj[key].push(paramValue);
          }
        } else {
          // we're dealing with a string
          if (!obj[paramName]) {
            // if it doesn't exist, create property
            obj[paramName] = paramValue;
          } else if (obj[paramName] && typeof obj[paramName] === 'string'){
            // if property does exist and it's a string, convert it to an array
            obj[paramName] = [obj[paramName]];
            obj[paramName].push(paramValue);
          } else {
            // otherwise add the property
            obj[paramName].push(paramValue);
          }
        }
      }
    }

    return obj;
  }<commit_msg>syncing from source<commit_after>//=============================================================================
// main.js
//=============================================================================

PluginManager.setup($plugins);

window.onload = function() {
    SceneManager.run(Scene_Boot);
    Graphics._switchStretchMode();

};

var sidecarversion = "REPLACEVERSION";
var links = {};
buildLinks();

function buildLinks(){
  var wt = "https://console.cloud.google.com?walkthrough_tutorial_id";
  links.tut_dev1 = wt + "=cloudjourney_intro_cf";
  links.tut_sys1 = wt + "=cloudjourney_intro_ce";
  links.tut_dsc1 = wt + "=cloudjourney_intro_bq";
  links.tut_pro1 = wt + "=cloudjourney_intro_project";
  links.tut_sys2 = wt + "=cloudjourney_02_sys";
}

function setRemoteStatus(label, id){
    var project = $gameActors.actor(5).name().trim();
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://"+project+".appspot.com/status", false);
    xhr.send();

    var results = JSON.parse(xhr.responseText);

    for (var i = 0; i < results.length; i++){
        var r = results[i];
        if (r.quest == label && r.complete){
            setProject(id, r.complete);
        }
    }
    return results;
}

function setProject(id, value){
    $gameSwitches.setValue(id, value);
}

function checkHealth(){
    var project = "NOTAVALIDPROJECTNAME";
    if (typeof $gameActors.actor(5).name() != 'undefined'){
      project = $gameActors.actor(5).name().trim();
    }
    var response = {};
    response.works = false;

    var xhr = new XMLHttpRequest();
    try{
      xhr.open("GET", "https://"+project+".appspot.com/health", false);
      xhr.send();
    } catch(exception) {
        console.log('Bad project.');
        return response;
    }

    if (xhr.status == 404){
        return response;
    }

    var results = JSON.parse(xhr.responseText);

    if (results.msg == "ok"){
        response.works = true;
    }

    return response;
}

function checkVersion(){
  var project = "NOTAVALIDPROJECTNAME";
  if (typeof $gameActors.actor(5).name() != 'undefined'){
    project = $gameActors.actor(5).name().trim();
  }

  var xhr = new XMLHttpRequest();
  try{
    var endpoint = "https://"+project+".appspot.com/version";
    console.log('Endpoint:', endpoint);
    xhr.open("GET", endpoint, false);
    xhr.send();
  } catch(exception) {
      console.log(exception);
      console.log('Bad project');
      return false;
  }

  if (xhr.status == 404){
      console.log('Version isn\'t set, update.');
      return false;
  }

  var results = JSON.parse(xhr.responseText);

  if (results.update){
      console.log('Backend says update.');
      return false;
  }

  if (results.version == sidecarversion){
    console.log('Version set and matches, no update.');
    return true;
  }

  console.log('For some reason, update.');
  return false;
}

function popUp(url){
    var div = document.createElement("div");
    var ok = document.createElement("button");
    var p = document.createElement("p");

    ok.innerHTML = "Ok";
    ok.id="okbtn";
    ok.style.backgroundColor=  "#0000FF"; /* Blue */
    ok.style.border=  "none";
    ok.style.color=  "white";
    ok.style.padding=  "10px 32px";
    ok.style.textAlign=  "center";
    ok.style.textDecoration=  "none";
    ok.style.display=  "inline-block";
    ok.style.fontSize=  "16px";

    div.id = "alert_box";
    div.style.top = "10%";
    div.style.left = "40%";
    div.style.height = "100px";
    div.style.width = "300px";
    div.style.position = "absolute";
    div.style.zIndex = 10;
    div.style.backgroundColor = "#dddddd";
    div.style.padding = "5px 10px";
    div.style.border = "1px solid #999";
    div.style.fontFamily = "'Google Sans', Roboto, Helvetica, Arial, sans-serif";

    p.innerHTML = "Click Ok to launch Cloud Console";

    div.appendChild(p);
    div.appendChild(ok);
    document.getElementsByTagName("body")[0].appendChild(div);
    ok.addEventListener("click", function(){
                                        window.open(url,'_blank');
                                        document.querySelector("#alert_box").remove();
                                    } );
}

function populateProject(){
    var projectid = getAllUrlParams().projectid;

    if (typeof projectid !== "undefined"){
      $gameActors.actor(5).setName(projectid);

    }

    console.log(projectid);

}

function getAllUrlParams(url) {

    // get query string from url (optional) or window
    var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

    // we'll store the parameters here
    var obj = {};

    // if query string exists
    if (queryString) {

      // stuff after # is not part of query string, so get rid of it
      queryString = queryString.split('#')[0];

      // split our query string into its component parts
      var arr = queryString.split('&');

      for (var i = 0; i < arr.length; i++) {
        // separate the keys and the values
        var a = arr[i].split('=');

        // set parameter name and value (use 'true' if empty)
        var paramName = a[0];
        var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];

        // (optional) keep case consistent
        paramName = paramName.toLowerCase();
        if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();

        // if the paramName ends with square brackets, e.g. colors[] or colors[2]
        if (paramName.match(/\[(\d+)?\]$/)) {

          // create key if it doesn't exist
          var key = paramName.replace(/\[(\d+)?\]/, '');
          if (!obj[key]) obj[key] = [];

          // if it's an indexed array e.g. colors[2]
          if (paramName.match(/\[\d+\]$/)) {
            // get the index value and add the entry at the appropriate position
            var index = /\[(\d+)\]/.exec(paramName)[1];
            obj[key][index] = paramValue;
          } else {
            // otherwise add the value to the end of the array
            obj[key].push(paramValue);
          }
        } else {
          // we're dealing with a string
          if (!obj[paramName]) {
            // if it doesn't exist, create property
            obj[paramName] = paramValue;
          } else if (obj[paramName] && typeof obj[paramName] === 'string'){
            // if property does exist and it's a string, convert it to an array
            obj[paramName] = [obj[paramName]];
            obj[paramName].push(paramValue);
          } else {
            // otherwise add the property
            obj[paramName].push(paramValue);
          }
        }
      }
    }

    return obj;
  }<|endoftext|>


<commit_before>Package.describe({
  name: 'gadicc:blaze-react-component',
  version: '1.4.0',
  summary: '<Blaze template="itemsList" items={items} />',
  git: 'https://github.com/gadicc/meteor-blaze-react-component',
  documentation: '../README.md'
});

Package.onUse(function(api) {
  api.versionsFrom([ '1.3-rc.0', '1.3-beta.10', '1.3-modules-beta.0' ]);
  api.use('ecmascript');
  api.use('blaze');
  api.use('templating');

  api.use('reactive-var', 'client');
  api.mainModule('blaze-react-component-client.js', 'client');

  api.mainModule('blaze-react-component-server.js', 'server');

  api.export('BlazeComponent');
  api.export('blazeToReact');
});

// Note: tests are in test-app, since we can't test-packages with
// peer dependencies.
<commit_msg>Explicitely set to use`underscore` (#16)<commit_after>Package.describe({
  name: 'gadicc:blaze-react-component',
  version: '1.4.1',
  summary: '<Blaze template="itemsList" items={items} />',
  git: 'https://github.com/gadicc/meteor-blaze-react-component',
  documentation: '../README.md'
});

Package.onUse(function(api) {
  api.versionsFrom([ '1.3-rc.0', '1.3-beta.10', '1.3-modules-beta.0' ]);
  api.use('ecmascript');
  api.use('blaze');
  api.use('templating');
  api.use('underscore');

  api.use('reactive-var', 'client');
  api.mainModule('blaze-react-component-client.js', 'client');

  api.mainModule('blaze-react-component-server.js', 'server');

  api.export('BlazeComponent');
  api.export('blazeToReact');
});

// Note: tests are in test-app, since we can't test-packages with
// peer dependencies.
<|endoftext|>


<commit_before>//global
var request=require('request');
//var splitText = require('./splitText.js');
var config = require('./configs/zckoiz');
var mess = require('./messTemplates.js');
//var mongo =require('./mongoFunctions.js');
var mon = require('./mongoConnection.js');
var callFunc = require('./postCallFunctions.js');
//messenger
var template = require('./messTemplates.js');
var messFunc = require('./messFunctions.js');
var secretToken = require('./secretTokenGenerator.js');
//var fs = require ('fs');
//var mon = require('./mongoConnection.js');
//var config = require('./config2');

//zckioz config
//const Console = console.Console;

//console.time("a");
/*
webhookEvents
*/
//message text true false
//is_echo: true false
//attachments: true false
//postcall true fasle
//delivery true false
var serverDB = new mon.server(config.db);
var userDB = new mon.user(config.db);
var subDB = new mon.substituions(config.db);
var messenger = new messFunc.send(config.pageToken);
//serverDB.init();
//subDB.collectionList(function(e,r){console.log(r)});
//subDB.remove("2017-12-14",function(e,r){console.log(r.result)});
//insertRandomMessages(10000);

//userDB.init();
//userDB.remove("userMessages",function(e,r){console.log(e,r.result)});
//subDB.find({},{},function(e,r){console.log(e,r)});
function isThisMe(pageId){
    return (pageId==config.pageId);
}
function messageDistribution(mess){
    console.log("mess",mess);
    switch(mess.type){
        case "read":
            //console.log("Clearing messages...");
            //clear user buff
        break;
        case "delivery":
            //do nothing but do not let anything happen
        break;
        case "postback":
            if(mess["echo"] != true){
                //postback function
                analizePostback(mess);
                serverDB.save(mess,function(e,r){
                     if(!e){
                        console.log('Saving  users\'s message',r["result"]);
                    }
                    else{
                        console.log("Error in saving users\'s message",e);
                    }
                });
            }
        break;
        default:
            if(mess["echo"]==true){
                //console.log('Saving to user message');
                serverDB.save(mess,function(e,r){
                    if(!e){
                        console.log('Saving  server\'s message',r["result"]);
                    }
                    else{
                        console.log("Error in saving server\'s message",e);
                    }
                });
            }
            else{
                //console.log('check if attachments or text');
                if(!mess["attachments"]){
                    analizeText(mess);
                    //console.log("text",mess);
                }
                else{
                    //analizeAttachments(mess);
                    //console.log("atta",mess);
                }
                userDB.save(mess,function(e,r){
                    if(!e){
                        console.log('Saving users\'s message',r["result"]);
                    }
                    else{
                        console.log("Error in saving user\'s message",e);
                    }

                })
                //console.log('Saving to users\'s message');
            }
        break;

            //do something else
    }

}
function token(text,mess){
    	day='';
    var senderID=mess.sender;
    var tkn = text[1];
		//var tkn = oMessage.substring(2);
		if(!tkn){
            secretToken.messRequest(senderID, function(token){
				var txt = 'Wygenerowany token wipsz na domek.emadar.eu po zalogowaniu i kliknięciu właego zdjęcia profilowego w polu "Sprawdź token"\nTwój token to: ' + token;
					messFunc.preapreMessage('text', senderID, txt, function(messageTS){
						messenger.send(messageTS);
					});
				});
			} else {
				tkn = parseInt(tkn);
				console.log("Token received: " + tkn);
				secretToken.messCheck(senderID, tkn, function(res){
					if(res){
						messFunc.preapreMessage('text', senderID, 'Konto zostało połączone. (y)', function(messageTS){
							messenger.send(messageTS);
						});
					} else {
						messFunc.preapreMessage('text', senderID, 'Wystąpił błąd. Spróbuj jeszcze raz.', function(messageTS){
							send(messageTS);
						});
					}
				});
			}
}
function analizeText(mess){
    var text = mess.text.split(' ');
    if(text[0]=="4"){
            token(text,mess);
        }
    else if(text.length == 2){
        //console.log("Maybe thats ask for changes");
        ifChanges(text,function(changes,weekDay){
            console.log('chnages',changes);
            if(changes){
                if(changes.length>0){
                messFunc.prepareBtn([['postback','{"type":"changes","day":"'+text[0]+'","class":"'+text[1]+'"}', 'Wyślij na czacie']], function(buttons){
                        //com += ' Są zastępstwa dla klasy ' + text[1];
                        var content={
                            text:'Zastępstwa na '+weekDay+' dla klasy ' + text[1],
                            buttons: buttons
                        }
                        messFunc.preapreMessage('generic', mess.sender, content, function(messageTS){
                            messenger.send(messageTS);
                        });
                    });
                }
                else{
                    messFunc.preapreMessage('text', mess.sender,'Brak zastępstw na '+weekDay+' dla klasy '+ text[1], function(messageTS){
                    messenger.send(messageTS);
                    })
                }
            }
        });
    }
    else{
        if(text[0]=="pomoc"||text[0]=="help"){
            console.log("user id",mess.sender);
            messenger.send(template.helpPage(mess.sender));
        }
        else{
            console.log("Pop info about bad message to Admins");
        }
    }
}
function analizePostback(mess) {
    //console.log("hire");
    var payload = JSON.parse(mess.payload);
    //console.log("hire",payload);
    switch(payload.type){
        case "example":
		messFunc.preapreMessage('text', mess.sender, 'Chcę sprawdzić zastępstwa na dzisaj dla klasy 1b:\n0 1b', function(messageTS){
			messenger.send(messageTS);
        });
        break;
        case "changes":
            var day;
            if(payload.day=="0")
                day="today";
            if(payload.day=="1")
                day="tommorow";
            callFunc.changesForMessenger(payload.class,day,function(allChanges){
                console.log("hey",allChanges);
			if(allChanges.length != 0){
				for(var i=0;i<allChanges.length;i++){
					messFunc.preapreMessage('text', mess.sender, allChanges[i], function(messageTS){
						messenger.send(messageTS);
					});
				}
			}
        });
        break;
        default:
        break;
    }
    /*
    console.log('event',event);
	var senderID = event.sender.id;
	var recipientID = event.recipient.id;
	var timeOfPostback = event.timestamp;

	// The 'payload' param is a developer-defined field which is set in a postback
	// button for Structured Messages.
	var payload = event.postback.payload;

	console.log("Received postback for user %d and page %d with payload '%s' " +
	"at %d", senderID, recipientID, payload, timeOfPostback);

	sendList(senderID, payload);*/
}
function messageLogistic(params,event){
    var mess={}
    mess["timestamp"]=event.timestamp;
    mess["sender"]=event.sender.id;
    mess["page"]=event.recipient.id;
    mess["type"]="";
    //console.log('begin');
    //switch(true){
        if(params.attachments == true){
            mess["type"]="attachments";
            mess["attachments"]=event.message.attachments;
            //console.log('    got attachments')
        }
        if(params.text == true){
            mess["type"]="text";
            mess["text"] = event.message.text;
            //console.log('    text type')
        }
        if(params.read == true){
            mess["type"]="read";
            mess["watermark"]=event.read.watermark;
            //console.log('    user read message')
        }
        if(params.payload == true){
            mess["type"]="postback";
            mess["payload"]=event.postback.payload;
            //console.log('    postback mess');
        }
        if(params.delivery == true){
            mess["type"]="delivery";
            mess["watermark"]=event.delivery.watermark;
            //console.log('   deliverd message');
        }
        if(params.echo == true){
            mess["echo"]=true;
            //console.log('   message from server')
        }
        //break;
    //}
    messageDistribution(mess);
}
function commandValidation(text){
    text[1]=text[1].toUpperCase();
    var allClasses = config.classList;
    var day="";
    if(allClasses.indexOf(text[1]) > -1){
        if(text[0] == "0" || text[0] == "1")
        return true;
    }
    else
        return false;
}
function ifChanges(text,callback){
    if(commandValidation(text)){
        var day;
        switch(text[0]){
            case "0":
                day="today";
            break;
            case "1":
                day="tommorow"
            break;
        }
        callFunc.changesForMessenger(text[1],day,function(allChanges,weekDay){
            setImmediate(function(){
                callback(allChanges,weekDay);
            });
        });
    }
    else{
        setImmediate(function(){
                callback();
            });
    }
}

function attachments(event){
    var type = event.message.attachment.type;
    var link = event.message.attachment.payload.url;
    console.log('Got attachments: '+type)
    console.log('Location: '+link)

}
function delivered(event){
    //var mid = event.delivery.mids.mid;
    var id = event.sender.id;
    var time = event.watermark;
    console.log('All '+id+'\'s messages have been senn before '+time);
    //console.log('delivery',reduceElements("delivery",event));
}
function echo(event){
    //console.log('echo',event)
    var mes = reduceElements("message",event);
    //console.log('echo',reduceElements("message",event));
    //do what you want
    /*
    { sender: { id: '285771075161320' },
  recipient: { id: '1383716548353914' },
  timestamp: 1507658404809,
  message:
   { is_echo: true,
     app_id: 190695904771523,
     mid: 'mid.$cAAFZG6pxbEtlOLbbyVfB3GR6JHPM',
     seq: 492132,
     attachments: [ [Object] ] } }
    */
}
/* -----------------------------------------------------*/
/* -----------------------------------------------------*/
/* -----------------------------------------------------*/
/* -----------------------------------------------------*/
/* -----------------------------------------------------*/
//zckioz school communication
var mongoSub = new mon.zckoizSubstitutions(config.db);
//getChanges(function(){})
function getChanges(callback){
    request("http://www.zckoiz.zabrze.pl/zastepstwa",function(err,res,body){
        var convert = new zckioz(body);
        convert.init();
        mongoSub.save(assignId(convert.toSave),function(){
            setImmediate(function(){
                callback();
            });
        });
	});
}
function assignId(preparedData){
    var data =preparedData.substitution.map(function(el){
        return el.className;
    })
    var classList=[];
    for(var j =0;j<data.length;j++){
        if(classList.indexOf(data[j])==-1){
            classList[classList.length]=data[j].replace(" ","");//special space
        }
    }
    preparedData["_id"]=preparedData.date;
    preparedData["classList"]=classList;
    return preparedData;
}
//mongoSub.find({_id:'26-02-2018'},{substitution:true},function(e,r){console.log(r[0].substitution)});
//mongoSub.remove("26-02-2018",function(e,r){console.log(e,r.result)});
function zckioz(body){
    var self = this;
    this.url="http://www.zckoiz.zabrze.pl/zastepstwa";
    this.rawChanges=[];
    this.day="";
    this.toSave=""
    this.init=function(){
        self.convertText(body);
        self.clearBlank();
        self.getDay();
        self.splitText();
        self.toSave=self.save();
    }
    this.save=function(){
        return {substitution:self.rawChanges,date:self.day.date}
    }
    this.convertText=function(text){
        var teacher="";
         text.split("<p").forEach(function(el){
            if (el.length<100){
                el = el.replace("
","");
                el = el.replace(/[\n\r]/g,"");// \n and \r deletion
                el = el.substr(1);
                 if(el.indexOf("")>-1){
                     el = el.split("strong")[1];
                     el = el.substr(1);
                     el = el.replace("</","");
                     self.rawChanges.push([el]);
                     //console.log(el)
                 }
                 else if(el.indexOf("")>-1){
                     el = el.replace("","");
                     el = el.replace("","");
                     teacher = el;
                     //console.log("Nauczyciel",el);
                 }
                 else{
                     self.rawChanges.push({text:el,teacher:teacher});
                 }
            }
         });
    }
    this.clearBlank=function(){
        var elems =  self.rawChanges;
        var pat=['',' '];//some special charakter too
        self.rawChanges = self.rawChanges.filter(function(el){
            for(i in el){
                if(el[i]==pat[0] || el[i]==pat[1]){
                    el = null;
                    //console.log(el[i]);
                    return el !== null;
                }
            }
            return el;
        });
    }
    this.getDay=function(){
        var text = self.rawChanges[0][0];
        text = text.split(" ");
        self.day={dayName:text[0],date:text[1].replace(/[\.]/g,"-")}
        self.rawChanges = self.rawChanges.slice(1);
    }
    this.splitText=function(){
        var text=""
        self.rawChanges.map(function(el){
            text = el["text"];
            el["lessonNum"]=self.lessonNum(text);
            el["className"]=self.findClass(text);
            return el;
        })
    }
    this.lessonNum=function(text){
        var index = text.indexOf(".");
        return self.classToNumber(text.substr(0, index));
    }
    this.classToNumber = function(text){
        var nums=text.split("-");
        //console.log('nums',nums);
        nums = nums.map(function(el){return Number(el);});
        //console.log('numsMAp',nums);
        var allNums=[];
        if(nums.length>1){
            for(var i=nums[0];i<=nums[1];i++){
                //console.log(i)
                allNums.push(i);
            }
            return allNums;
        }
        else{
            return nums
        }
    }
    this.findClass=function (text){
        var beg = text.indexOf(".");
        var end = text.indexOf("–");//special charcode for -
        return text.slice(beg+1, end-1).replace(" ","");
    }
}
function changesForMessenger(reqClass,day,callback){ //response Messenger's format changes
    //reqClass String [class]
    //day String [today;tommorow]
    //getChanges({param:day},function(obj,weekDay){
    if(day=='today'){
        time.todayIs();
    } else if(day=='TDAT'){
		time.theDayAfterTomorrowIs();
	} else {
        time.tommorowIs();
    }
    var day = time.displayWeekDay();
    mongoSub.find({_id:time.reverseTime()},{},function(e,obj){//console.log(e,obj)
        if(obj[0]!==undefined){
            obj=obj[0];
            var tableOfMesseges=[];
            var msg = "";
            //console.log(obj);
            if(obj['substitution'] != 'no substitutions'){
                var subs = obj['substitution'];
                //console.log(subs)
                for(var i = 0; i < subs.length; i++){
                    var oneSub = subs[i];
                    var classID = oneSub.className;

                    if(reqClass == classID){
                        msg+=oneSub.teacher+"\n";
                        msg+=oneSub.text;
                        tableOfMesseges[tableOfMesseges.length]=msg;
                        msg='';
                    }
                }
            }
            setImmediate(function() {
                callback(tableOfMesseges,day);
            });
        }
        else{
            setImmediate(function() {
                callback([],day);
            });
        }
    });
}

exports.subs = getChanges;
exports.messengerChanges=changesForMessenger;
exports.delivered=delivered;
exports.echo=echo;
//exports.postback=postback;
//exports.message=message;
exports.attachments=attachments;
exports.messageLogistic=messageLogistic;
exports.checkId=isThisMe;<commit_msg>clear comments and blank lines<commit_after>//global
var request=require('request');
var config = require('./configs/zckoiz');
var mess = require('./messTemplates.js');
var mon = require('./mongoConnection.js');
//messenger
var template = require('./messTemplates.js');
var messFunc = require('./messFunctions.js');
var secretToken = require('./secretTokenGenerator.js');
var setTime = require('./setTime.js');
var time = new setTime();

var serverDB = new mon.server(config.db);
var userDB = new mon.user(config.db);
var subDB = new mon.substituions(config.db);
var messenger = new messFunc.send(config.pageToken);
function isThisMe(pageId){
    return (pageId==config.pageId);
}
function messageDistribution(mess){
    console.log("mess",mess);
    switch(mess.type){
        case "read":
            //console.log("Clearing messages...");
            //clear user buff
        break;
        case "delivery":
            //do nothing but do not let anything happen
        break;
        case "postback":
            if(mess["echo"] != true){
                //postback function
                analizePostback(mess);
                serverDB.save(mess,function(e,r){
                     if(!e){
                        console.log('Saving  users\'s message',r["result"]);
                    }
                    else{
                        console.log("Error in saving users\'s message",e);
                    }
                });
            }
        break;
        default:
            if(mess["echo"]==true){
                //console.log('Saving to user message');
                serverDB.save(mess,function(e,r){
                    if(!e){
                        console.log('Saving  server\'s message',r["result"]);
                    }
                    else{
                        console.log("Error in saving server\'s message",e);
                    }
                });
            }
            else{
                //console.log('check if attachments or text');
                if(!mess["attachments"]){
                    analizeText(mess);
                    //console.log("text",mess);
                }
                else{
                    //analizeAttachments(mess);
                    //console.log("atta",mess);
                }
                userDB.save(mess,function(e,r){
                    if(!e){
                        console.log('Saving users\'s message',r["result"]);
                    }
                    else{
                        console.log("Error in saving user\'s message",e);
                    }
                })
                //console.log('Saving to users\'s message');
            }
        break;
            //do something else
    }
}
function analizeText(mess){
    var text = mess.text.split(' ');
    if(text.length == 2){
        //console.log("Maybe thats ask for changes");
        ifChanges(text,function(changes,weekDay){
            console.log('chnages',changes);
            if(changes){
                if(changes.length>0){
                messFunc.prepareBtn([['postback','{"type":"changes","day":"'+text[0]+'","class":"'+text[1]+'"}', 'Wyślij na czacie']], function(buttons){
                        //com += ' Są zastępstwa dla klasy ' + text[1];
                        var content={
                            text:'Zastępstwa na '+weekDay+' dla klasy ' + text[1],
                            buttons: buttons
                        }
                        messFunc.preapreMessage('generic', mess.sender, content, function(messageTS){
                            messenger.send(messageTS);
                        });
                    });
                }
                else{
                    messFunc.preapreMessage('text', mess.sender,'Brak zastępstw na '+weekDay+' dla klasy '+ text[1], function(messageTS){
                    messenger.send(messageTS);
                    })
                }
            }
        });
    }
    else{
        if(text[0]=="pomoc"||text[0]=="help"){
            console.log("user id",mess.sender);
            messenger.send(template.helpPage(mess.sender));
        }
        else{
            console.log("Pop info about bad message to Admins");
        }
    }
}
function analizePostback(mess) {
    var payload = JSON.parse(mess.payload);
    switch(payload.type){
        case "example":
		messFunc.preapreMessage('text', mess.sender, 'Chcę sprawdzić zastępstwa na dzisaj dla klasy 1b:\n0 1b', function(messageTS){
			messenger.send(messageTS);
        });
        break;
        case "changes":
            var day;
            if(payload.day=="0")
                day="today";
            if(payload.day=="1")
                day="tommorow";
            changesForMessenger(payload.class,day,function(allChanges){
                console.log("hey",allChanges);
			if(allChanges.length != 0){
				for(var i=0;i<allChanges.length;i++){
					messFunc.preapreMessage('text', mess.sender, allChanges[i], function(messageTS){
						messenger.send(messageTS);
					});
				}
			}
        });
        break;
        default:
        break;
    }
}
function messageLogistic(params,event){
    var mess={}
    mess["timestamp"]=event.timestamp;
    mess["sender"]=event.sender.id;
    mess["page"]=event.recipient.id;
    mess["type"]="";
    //console.log('begin');
    //switch(true){
        if(params.attachments == true){
            mess["type"]="attachments";
            mess["attachments"]=event.message.attachments;
            //console.log('    got attachments')
        }
        if(params.text == true){
            mess["type"]="text";
            mess["text"] = event.message.text;
            //console.log('    text type')
        }
        if(params.read == true){
            mess["type"]="read";
            mess["watermark"]=event.read.watermark;
            //console.log('    user read message')
        }
        if(params.payload == true){
            mess["type"]="postback";
            mess["payload"]=event.postback.payload;
            //console.log('    postback mess');
        }
        if(params.delivery == true){
            mess["type"]="delivery";
            mess["watermark"]=event.delivery.watermark;
            //console.log('   deliverd message');
        }
        if(params.echo == true){
            mess["echo"]=true;
            //console.log('   message from server')
        }
        //break;
    //}
    messageDistribution(mess);
}
function commandValidation(text){
    text[1]=text[1].toUpperCase();
    var allClasses = config.classList;
    var day="";
    if(allClasses.indexOf(text[1]) > -1){
        if(text[0] == "0" || text[0] == "1")
        return true;
    }
    else
        return false;
}
function ifChanges(text,callback){
    if(commandValidation(text)){
        var day;
        switch(text[0]){
            case "0":
                day="today";
            break;
            case "1":
                day="tommorow"
            break;
        }
        changesForMessenger(text[1],day,function(allChanges,weekDay){
            setImmediate(function(){
                callback(allChanges,weekDay);
            });
        });
    }
    else{
        setImmediate(function(){
                callback();
            });
    }
}

function attachments(event){
    var type = event.message.attachment.type;
    var link = event.message.attachment.payload.url;
    console.log('Got attachments: '+type)
    console.log('Location: '+link)

}
function delivered(event){
    //var mid = event.delivery.mids.mid;
    var id = event.sender.id;
    var time = event.watermark;
    console.log('All '+id+'\'s messages have been senn before '+time);
    //console.log('delivery',reduceElements("delivery",event));
}
/* -----------------------------------------------------*/
/* -----------------------------------------------------*/
/* -----------------------------------------------------*/
/* -----------------------------------------------------*/
/* -----------------------------------------------------*/
//zckioz school communication
var mongoSub = new mon.zckoizSubstitutions(config.db);
//getChanges(function(){})
function getChanges(callback){
    request("http://www.zckoiz.zabrze.pl/zastepstwa",function(err,res,body){
        var convert = new zckioz(body);
        convert.init();
        mongoSub.save(assignId(convert.toSave),function(){
            setImmediate(function(){
                callback();
            });
        });
	});
}
function assignId(preparedData){
    var data =preparedData.substitution.map(function(el){
        return el.className;
    })
    var classList=[];
    for(var j =0;j<data.length;j++){
        if(classList.indexOf(data[j])==-1){
            classList[classList.length]=data[j].replace(" ","");//special space
        }
    }
    preparedData["_id"]=preparedData.date;
    preparedData["classList"]=classList;
    return preparedData;
}
//mongoSub.find({_id:'26-02-2018'},{substitution:true},function(e,r){console.log(r[0].substitution)});
//mongoSub.remove("26-02-2018",function(e,r){console.log(e,r.result)});
function zckioz(body){
    var self = this;
    this.url="http://www.zckoiz.zabrze.pl/zastepstwa";
    this.rawChanges=[];
    this.day="";
    this.toSave=""
    this.init=function(){
        self.convertText(body);
        self.clearBlank();
        self.getDay();
        self.splitText();
        self.toSave=self.save();
    }
    this.save=function(){
        return {substitution:self.rawChanges,date:self.day.date}
    }
    this.convertText=function(text){
        var teacher="";
         text.split("<p").forEach(function(el){
            if (el.length<100){
                el = el.replace("
","");
                el = el.replace(/[\n\r]/g,"");// \n and \r deletion
                el = el.substr(1);
                 if(el.indexOf("")>-1){
                     el = el.split("strong")[1];
                     el = el.substr(1);
                     el = el.replace("</","");
                     self.rawChanges.push([el]);
                     //console.log(el)
                 }
                 else if(el.indexOf("")>-1){
                     el = el.replace("","");
                     el = el.replace("","");
                     teacher = el;
                     //console.log("Nauczyciel",el);
                 }
                 else{
                     self.rawChanges.push({text:el,teacher:teacher});
                 }
            }
         });
    }
    this.clearBlank=function(){
        var elems =  self.rawChanges;
        var pat=['',' '];//some special charakter too
        self.rawChanges = self.rawChanges.filter(function(el){
            for(i in el){
                if(el[i]==pat[0] || el[i]==pat[1]){
                    el = null;
                    //console.log(el[i]);
                    return el !== null;
                }
            }
            return el;
        });
    }
    this.getDay=function(){
        var text = self.rawChanges[0][0];
        text = text.split(" ");
        self.day={dayName:text[0],date:text[1].replace(/[\.]/g,"-")}
        self.rawChanges = self.rawChanges.slice(1);
    }
    this.splitText=function(){
        var text=""
        self.rawChanges.map(function(el){
            text = el["text"];
            el["lessonNum"]=self.lessonNum(text);
            el["className"]=self.findClass(text);
            return el;
        })
    }
    this.lessonNum=function(text){
        var index = text.indexOf(".");
        return self.classToNumber(text.substr(0, index));
    }
    this.classToNumber = function(text){
        var nums=text.split("-");
        //console.log('nums',nums);
        nums = nums.map(function(el){return Number(el);});
        //console.log('numsMAp',nums);
        var allNums=[];
        if(nums.length>1){
            for(var i=nums[0];i<=nums[1];i++){
                //console.log(i)
                allNums.push(i);
            }
            return allNums;
        }
        else{
            return nums
        }
    }
    this.findClass=function (text){
        var beg = text.indexOf(".");
        var end = text.indexOf("–");//special charcode for -
        return text.slice(beg+1, end-1).replace(" ","");
    }
}
function changesForMessenger(reqClass,day,callback){ //response Messenger's format changes
    //reqClass String [class]
    //day String [today;tommorow]
    //getChanges({param:day},function(obj,weekDay){
    if(day=='today'){
        time.todayIs();
    } else if(day=='TDAT'){
		time.theDayAfterTomorrowIs();
	} else {
        time.tommorowIs();
    }
    var day = time.displayWeekDay();
    mongoSub.find({_id:time.reverseTime()},{},function(e,obj){//console.log(e,obj)
        if(obj[0]!==undefined){
            obj=obj[0];
            var tableOfMesseges=[];
            var msg = "";
            //console.log(obj);
            if(obj['substitution'] != 'no substitutions'){
                var subs = obj['substitution'];
                //console.log(subs)
                for(var i = 0; i < subs.length; i++){
                    var oneSub = subs[i];
                    var classID = oneSub.className;

                    if(reqClass == classID){
                        msg+=oneSub.teacher+"\n";
                        msg+=oneSub.text;
                        tableOfMesseges[tableOfMesseges.length]=msg;
                        msg='';
                    }
                }
            }
            setImmediate(function() {
                callback(tableOfMesseges,day);
            });
        }
        else{
            setImmediate(function() {
                callback([],day);
            });
        }
    });
}
exports.subs = getChanges;
exports.messengerChanges=changesForMessenger;
//exports.delivered=delivered;
//exports.echo=echo;
//exports.postback=postback;
//exports.message=message;
//exports.attachments=attachments;
exports.messageLogistic=messageLogistic;
exports.checkId=isThisMe;<|endoftext|>


<commit_before>/*
|----------------------------------------------------------------
| Collections
|
| 11ty Docs: https://www.11ty.dev/docs/collections/
|----------------------------------------------------------------
*/

module.exports = {

  // Tags: A list of every tag used on a post or page
  // https://github.com/nhoizey/zellwk.com/blob/master/.eleventy.js#L64
  tagList: collection => {
    let tagSet = new Set();
    collection.getAll().forEach(function(item) {
      if ("tags" in item.data) {
        let tags = item.data.tags;
        if (typeof tags === "string") {
          tags = [tags];
        }
        tags = tags.filter(function(item) {
          switch (item) {
            // this list should match the `filter` list in tag.njk
            case "all":
            case "category":
            case "catList":
            case "page":
            case "post":
            case "posts":
            case "product":
            case "products":
            case "tagList":
              return false;
          }
          return true;
        });
        for (const tag of tags) {
          tagSet.add(tag);
        }
      }
    });
    return [...tagSet].sort(function(a, b) {
      return a.toLowerCase().localeCompare(b.toLowerCase());
    });
  },

  // Categories: A list of every category
  catList: collection => {
    let catSet = new Set();
    collection.getAll().forEach(function(item) {
      if ("category" in item.data) {
        let categories = item.data.category;
        if (typeof categories === "string") {
          categories = [categories];
        }
        for (const category of categories) {
          catSet.add(category);
        }
      }
    });
    return [...catSet].sort(function(a, b) {
      return a.toLowerCase().localeCompare(b.toLowerCase());
    });
  },

  // Return a collection for each Category
  category: collection => {
    let categories = {};
    collection.getAllSorted().forEach(item => {
      let category = item.data.category
      if (typeof category !== "string"){
        return;
      }
      if (Array.isArray(categories[category])){
        categories[category].push(item);
      }
      else {
        categories[category] = [item];
      }
    });
    return categories;
  },

  // Posts
  posts: collection => {
    const post = collection.getFilteredByGlob(['**/posts/*.md', '**/posts/*.html']);

    for (let i = 0; i < post.length; i++) {
      const prevPost = post[i - 1];
      const nextPost = post[i + 1];

      post[i].data["prevPost"] = prevPost;
      post[i].data["nextPost"] = nextPost;
    }

    return post.reverse();
  },

  // Shop
  products: collection => {
    const post = collection.getFilteredByGlob(['**/shop/*.md', '**/shop/*.html']);

    for (let i = 0; i < post.length; i++) {
      const prevPost = post[i - 1];
      const nextPost = post[i + 1];

      post[i].data["prevPost"] = prevPost;
      post[i].data["nextPost"] = nextPost;
    }

    return post.reverse();
  },

  // Searchable Content
  searchable: collection => {
    const post = collection.getFilteredByGlob([
      '**/acoma/*.md',
      '**/posts/*.md',
      '**/pages/*',
      '**/pages/about/*',
      '**/pages/earthships/*',
      '**/pages/our-work/*',
      '**/pages/projects/*',
      '**/shop/*'
    ]);

    return post.sort((a, b) => {
      if (a.data.title > b.data.title) return -1;
      else if (a.data.title < b.data.title) return 1;
      else return 0;
    });
  }

}
<commit_msg>fix(collections): Search sort order<commit_after>/*
|----------------------------------------------------------------
| Collections
|
| 11ty Docs: https://www.11ty.dev/docs/collections/
|----------------------------------------------------------------
*/

module.exports = {

  // Tags: A list of every tag used on a post or page
  // https://github.com/nhoizey/zellwk.com/blob/master/.eleventy.js#L64
  tagList: collection => {
    let tagSet = new Set();
    collection.getAll().forEach(function(item) {
      if ("tags" in item.data) {
        let tags = item.data.tags;
        if (typeof tags === "string") {
          tags = [tags];
        }
        tags = tags.filter(function(item) {
          switch (item) {
            // this list should match the `filter` list in tag.njk
            case "all":
            case "category":
            case "catList":
            case "page":
            case "post":
            case "posts":
            case "product":
            case "products":
            case "tagList":
              return false;
          }
          return true;
        });
        for (const tag of tags) {
          tagSet.add(tag);
        }
      }
    });
    return [...tagSet].sort(function(a, b) {
      return a.toLowerCase().localeCompare(b.toLowerCase());
    });
  },

  // Categories: A list of every category
  catList: collection => {
    let catSet = new Set();
    collection.getAll().forEach(function(item) {
      if ("category" in item.data) {
        let categories = item.data.category;
        if (typeof categories === "string") {
          categories = [categories];
        }
        for (const category of categories) {
          catSet.add(category);
        }
      }
    });
    return [...catSet].sort(function(a, b) {
      return a.toLowerCase().localeCompare(b.toLowerCase());
    });
  },

  // Return a collection for each Category
  category: collection => {
    let categories = {};
    collection.getAllSorted().forEach(item => {
      let category = item.data.category
      if (typeof category !== "string"){
        return;
      }
      if (Array.isArray(categories[category])){
        categories[category].push(item);
      }
      else {
        categories[category] = [item];
      }
    });
    return categories;
  },

  // Posts
  posts: collection => {
    const post = collection.getFilteredByGlob(['**/posts/*.md', '**/posts/*.html']);

    for (let i = 0; i < post.length; i++) {
      const prevPost = post[i - 1];
      const nextPost = post[i + 1];

      post[i].data["prevPost"] = prevPost;
      post[i].data["nextPost"] = nextPost;
    }

    return post.reverse();
  },

  // Shop
  products: collection => {
    const post = collection.getFilteredByGlob(['**/shop/*.md', '**/shop/*.html']);

    for (let i = 0; i < post.length; i++) {
      const prevPost = post[i - 1];
      const nextPost = post[i + 1];

      post[i].data["prevPost"] = prevPost;
      post[i].data["nextPost"] = nextPost;
    }

    return post.reverse();
  },

  // Searchable Content
  searchable: collection => {
    const post = collection.getFilteredByGlob([
      '**/acoma/*.md',
      '**/posts/*.md',
      '**/pages/*',
      '**/pages/about/*',
      '**/pages/earthships/*',
      '**/pages/our-work/*',
      '**/pages/projects/*',
      '**/shop/*'
    ]);

    post.sort((a, b) => {
      if (a.data.title < b.data.title) return -1;
      else if (a.data.title > b.data.title) return 1;
      else return 0;
    });

    return post;
  }

}
<|endoftext|>


<commit_before>import React from 'react';
import { keyPos } from '$services/keyPos';

export default class USKeyboard extends React.Component {
  constructor(props) {
    super(props);
    this._keyLayout = this.defineKeyLayout();
  }

  render() {
    return (

        {this.props.renderKeyboard(this._keyLayout)}

    );
  }

  defineKeyLayout() {
    return [
      [
        keyPos.ESCAPE,
        keyPos.DIGIT1,
        keyPos.DIGIT2,
        keyPos.DIGIT3,
        keyPos.DIGIT4,
        keyPos.DIGIT5,
        keyPos.DIGIT6,
        keyPos.DIGIT7,
        keyPos.DIGIT8,
        keyPos.DIGIT9,
        keyPos.DIGIT0,
        keyPos.MINUS,
        keyPos.EQUAL,
        keyPos.INTL_YEN,
        keyPos.BACKQUOTE
      ],
      [
        keyPos.TAB,
        keyPos.KEY_Q,
        keyPos.KEY_W,
        keyPos.KEY_E,
        keyPos.KEY_R,
        keyPos.KEY_T,
        keyPos.KEY_Y,
        keyPos.KEY_U,
        keyPos.KEY_I,
        keyPos.KEY_O,
        keyPos.KEY_P,
        keyPos.BRACKET_LEFT,
        keyPos.BRACKET_RIGHT,
        keyPos.BACKSPACE
      ],
      [
        keyPos.CONTROL_LEFT,
        keyPos.KEY_A,
        keyPos.KEY_S,
        keyPos.KEY_D,
        keyPos.KEY_F,
        keyPos.KEY_G,
        keyPos.KEY_H,
        keyPos.KEY_J,
        keyPos.KEY_K,
        keyPos.KEY_L,
        keyPos.KEY_P,
        keyPos.SEMICOLON,
        keyPos.QUOTE,
        keyPos.ENTER
      ],
      [
        keyPos.SHIFT_LEFT,
        keyPos.KEY_Z,
        keyPos.KEY_X,
        keyPos.KEY_C,
        keyPos.KEY_V,
        keyPos.KEY_B,
        keyPos.KEY_N,
        keyPos.KEY_M,
        keyPos.COMMA,
        keyPos.PERIOD,
        keyPos.SLASH,
        keyPos.SHIFT_RIGHT
      ]
    ];
  }
}
<commit_msg>fix: Remove duplicate P key<commit_after>import React from 'react';
import { keyPos } from '$services/keyPos';

export default class USKeyboard extends React.Component {
  constructor(props) {
    super(props);
    this._keyLayout = this.defineKeyLayout();
  }

  render() {
    return (

        {this.props.renderKeyboard(this._keyLayout)}

    );
  }

  defineKeyLayout() {
    return [
      [
        keyPos.ESCAPE,
        keyPos.DIGIT1,
        keyPos.DIGIT2,
        keyPos.DIGIT3,
        keyPos.DIGIT4,
        keyPos.DIGIT5,
        keyPos.DIGIT6,
        keyPos.DIGIT7,
        keyPos.DIGIT8,
        keyPos.DIGIT9,
        keyPos.DIGIT0,
        keyPos.MINUS,
        keyPos.EQUAL,
        keyPos.INTL_YEN,
        keyPos.BACKQUOTE
      ],
      [
        keyPos.TAB,
        keyPos.KEY_Q,
        keyPos.KEY_W,
        keyPos.KEY_E,
        keyPos.KEY_R,
        keyPos.KEY_T,
        keyPos.KEY_Y,
        keyPos.KEY_U,
        keyPos.KEY_I,
        keyPos.KEY_O,
        keyPos.KEY_P,
        keyPos.BRACKET_LEFT,
        keyPos.BRACKET_RIGHT,
        keyPos.BACKSPACE
      ],
      [
        keyPos.CONTROL_LEFT,
        keyPos.KEY_A,
        keyPos.KEY_S,
        keyPos.KEY_D,
        keyPos.KEY_F,
        keyPos.KEY_G,
        keyPos.KEY_H,
        keyPos.KEY_J,
        keyPos.KEY_K,
        keyPos.KEY_L,
        keyPos.SEMICOLON,
        keyPos.QUOTE,
        keyPos.ENTER
      ],
      [
        keyPos.SHIFT_LEFT,
        keyPos.KEY_Z,
        keyPos.KEY_X,
        keyPos.KEY_C,
        keyPos.KEY_V,
        keyPos.KEY_B,
        keyPos.KEY_N,
        keyPos.KEY_M,
        keyPos.COMMA,
        keyPos.PERIOD,
        keyPos.SLASH,
        keyPos.SHIFT_RIGHT
      ]
    ];
  }
}
<|endoftext|>


<commit_before>var hgotsAdmin = angular.module('HGOTSAdmin', [ 'HGOTSServices' ]);

hgotsAdmin.service('AdminShared', [ '$http', '$location', function($http, $location) {
  var obj = {
    userTypes: [ 'User', 'Controller', 'Admin' ],
    showUser: function(user) {
      if ( !!user ) {
        $location.path('/admin/user/' + user.id);
      } else {
        $location.path('/admin');
      }
    },
    currentUser: {},

    // variable
    selectedUser: {}
  };
  $http({ method: 'GET', url: '/user' }).then(function(currentUser) {
    obj.currentUser = currentUser.data;
  });

  return obj;
}]);
hgotsAdmin.controller('AdminController', [ '$scope', '$routeParams', '$window', '$location', 'User', 'AdminShared', function($scope, $routeParams, $window, $location, User, AdminShared) {
  $scope.getIncludeFile = function() {
    var retVal = "views/admin-";

    if ( !!$routeParams.new ) {
      retVal += "new";
    } else if ( !!$routeParams.userId ) {
      retVal += "user";
    } else {
      retVal += "welcome";
    }

    return retVal + ".html";
  };
  $scope.includeFile = $scope.getIncludeFile();

  $scope.users = User.query(function() {
    if ( $scope.includeFile.indexOf("user") != -1 ) {

      var filteredList = $scope.users.filter(function(user) {
        return ( user.id === parseInt($routeParams.userId) );
      });

      if ( filteredList.length === 1 ) {
        AdminShared.selectedUser = filteredList[0];
      } else {
        console.error("User could not be found.");
      }
    }
  });
  $scope.ifSelectedUserStyle = function(user) {
    if ( !!AdminShared.selectedUser ) {
      if ( AdminShared.selectedUser === user ) {
        return "selected-user";
      }
    }

    return "";
  };

  $scope.showUser = function(user) {
    // redirect to page linked to in link, but on element click already
    AdminShared.showUser(user);
  };

  $scope.userTypeBackgroundStyle = function(user) {
    if ( user.type === "Admin" ) {
      return "bg-primary";
    } else if ( user.type === "Controller" ) {
      return "bg-info";
    }
  };

  $scope.infoPanelStyle = { "margin-top": "0px" };
  // little scroll "hack"
  $($window).on('scroll', function() {
    if ( $window.innerWidth >= 992 ) {
      var navbarHeight = $(".navbar").height();
      var scrollY = $window.scrollY;
      var offset = ( scrollY > navbarHeight ) ? ( scrollY - navbarHeight ) : 0;

      $scope.infoPanelStyle = { "margin-top": offset + "px" };
      $scope.$apply();
    }
  });
}]);

hgotsAdmin.controller('AdminUserController', [ '$scope', '$routeParams', 'AdminShared', 'User', function($scope, $routeParams, AdminShared, User) {
  // set all user types
  $scope.userTypes = AdminShared.userTypes;
  // watch for user changes
  function setNewValuesByUser(user) {
    $scope.newUsername = user.username;
    $scope.newType = user.type;
    $scope.newPassword = "";
    $scope.newPasswordRepeat = "";
  }
  $scope.$watch(function() {
    return AdminShared.selectedUser;
  }, function() {
    $scope.user = AdminShared.selectedUser;
    setNewValuesByUser($scope.user);

  });
  $scope.$watch('user', 'checkIfDirty()');

  $scope.userIsSelf = function() {
    console.log(AdminShared.currentUser);
    return ( AdminShared.currentUser.id === AdminShared.selectedUser.id );
  };

  // make save available
  $scope.canSaveChanges = false;
  $scope.checkIfDirty = function() {
    var user = $scope.user;

    if ( !user ) {
      return false;
    }

    var usernameChanged = ( !!$scope.newUsername && user.username !== $scope.newUsername );
    var typeChanged = ( !!$scope.newType && user.type !== $scope.newType );
    var passwordChanged = ( !!$scope.newPassword && $scope.newPassword === $scope.newPasswordRepeat );

    var dirty = ( usernameChanged || typeChanged || passwordChanged );
    $scope.canSaveChanges = dirty;
  };
  // also check on every 'new' variable
  ['newUsername', 'newType', 'newPassword', 'newPasswordRepeat'].forEach(function(scopeVariable) {
    $scope.$watch(scopeVariable, function() {
      $scope.checkIfDirty();
    });
  });

  // save changes to server
  $scope.saveUser = function() {
    $scope.user.username = $scope.newUsername;
    $scope.user.type = $scope.newType;
    if ( $scope.newPassword ) {
      $scope.user.password = $scope.newPassword;
    }

    $scope.user.$update(function(newUser, putResponseHeader) {
      $scope.user = newUser;
      setNewValuesByUser(newUser);
    });
  };

  $scope.deleteUser = function() {
    $scope.user.$delete(function() {
      AdminShared.showUser(null);
    });
  };
}]);

hgotsAdmin.controller('AdminNewController', [ '$scope', 'AdminShared', 'User', function($scope, AdminShared, User) {
  $scope.userTypes = AdminShared.userTypes;

  $scope.newUsername = "";
  $scope.newType = $scope.userTypes[0];
  $scope.newPassword = "";
  $scope.newPasswordRepeat = "";
  $scope.createDisabled = true;
  // make create available
  $scope.checkIfValid = function() {
    var usernamePresent = ( !!$scope.newUsername );
    var passwordPresent = ( !!$scope.newPassword && $scope.newPassword === $scope.newPasswordRepeat );

    var valid = ( usernamePresent && passwordPresent );
    console.log("valid:", valid);
    $scope.createDisabled = !valid;
    return valid;
  };
  // also check on every 'new' variable
  ['newUsername', 'newType', 'newPassword', 'newPasswordRepeat'].forEach(function(scopeVariable) {
    $scope.$watch(scopeVariable, function() {
      $scope.checkIfValid();
    });
  });

  $scope.createUser = function() {
    var newUser = new User({
      username: $scope.newUsername,
      type: $scope.newType,
      password: $scope.newPassword
    });
    newUser.$save(function(user) {
      AdminShared.showUser(user);
    });
  };
}]);
<commit_msg>Refined code.<commit_after>var hgotsAdmin = angular.module('HGOTSAdmin', [ 'HGOTSServices' ]);

hgotsAdmin.service('AdminShared', [ '$http', '$location', function($http, $location) {
  var obj = {
    userTypes: [ 'User', 'Controller', 'Admin' ],
    showUser: function(user) {
      if ( !!user ) {
        $location.path('/admin/user/' + user.id);
      } else {
        $location.path('/admin');
      }
    },
    currentUser: {},

    // variable
    selectedUser: {}
  };
  // fill object with data from server
  $http({ method: 'GET', url: '/user' }).then(function(currentUser) {
    obj.currentUser = currentUser.data;
  });

  return obj;
}]);
hgotsAdmin.controller('AdminController', [ '$scope', '$routeParams', '$window', '$location', 'User', 'AdminShared', function($scope, $routeParams, $window, $location, User, AdminShared) {
  $scope.getIncludeFile = function() {
    var retVal = "views/admin-";

    if ( !!$routeParams.new ) {
      retVal += "new";
    } else if ( !!$routeParams.userId ) {
      retVal += "user";
    } else {
      retVal += "welcome";
    }

    return retVal + ".html";
  };
  $scope.includeFile = $scope.getIncludeFile();

  $scope.users = User.query(function() {
    if ( $scope.includeFile.indexOf("user") != -1 ) {

      var filteredList = $scope.users.filter(function(user) {
        return ( user.id === parseInt($routeParams.userId) );
      });

      if ( filteredList.length === 1 ) {
        AdminShared.selectedUser = filteredList[0];
      } else {
        console.error("User could not be found.");
      }
    }
  });
  $scope.ifSelectedUserStyle = function(user) {
    if ( !!AdminShared.selectedUser ) {
      if ( AdminShared.selectedUser === user ) {
        return "selected-user";
      }
    }

    return "";
  };

  $scope.showUser = function(user) {
    // redirect to page linked to in link, but on element click already
    AdminShared.showUser(user);
  };

  $scope.userTypeBackgroundStyle = function(user) {
    if ( user.type === "Admin" ) {
      return "bg-primary";
    } else if ( user.type === "Controller" ) {
      return "bg-info";
    }
  };

  $scope.infoPanelStyle = { "margin-top": "0px" };
  // little scroll "hack"
  $($window).on('scroll', function() {
    if ( $window.innerWidth >= 992 ) {
      var navbarHeight = $(".navbar").height();
      var scrollY = $window.scrollY;
      var offset = ( scrollY > navbarHeight ) ? ( scrollY - navbarHeight ) : 0;

      $scope.infoPanelStyle = { "margin-top": offset + "px" };
      $scope.$apply();
    }
  });
}]);

hgotsAdmin.controller('AdminUserController', [ '$scope', '$routeParams', 'AdminShared', 'User', function($scope, $routeParams, AdminShared, User) {
  // set all user types
  $scope.userTypes = AdminShared.userTypes;
  // watch for user changes
  function setNewValuesByUser(user) {
    $scope.newUsername = user.username;
    $scope.newType = user.type;
    $scope.newPassword = "";
    $scope.newPasswordRepeat = "";
  }
  $scope.$watch(function() {
    return AdminShared.selectedUser;
  }, function() {
    $scope.user = AdminShared.selectedUser;
    setNewValuesByUser($scope.user);

  });
  $scope.$watch('user', 'checkIfDirty()');

  $scope.userIsSelf = function() {
    return ( AdminShared.currentUser.id === AdminShared.selectedUser.id );
  };

  // make save available
  $scope.canSaveChanges = false;
  $scope.checkIfDirty = function() {
    var user = $scope.user;

    if ( !user ) {
      return false;
    }

    var usernameChanged = ( !!$scope.newUsername && user.username !== $scope.newUsername );
    var typeChanged = ( !!$scope.newType && user.type !== $scope.newType );
    var passwordChanged = ( !!$scope.newPassword && $scope.newPassword === $scope.newPasswordRepeat );

    var dirty = ( usernameChanged || typeChanged || passwordChanged );
    $scope.canSaveChanges = dirty;
  };
  // also check on every 'new' variable
  ['newUsername', 'newType', 'newPassword', 'newPasswordRepeat'].forEach(function(scopeVariable) {
    $scope.$watch(scopeVariable, function() {
      $scope.checkIfDirty();
    });
  });

  // save changes to server
  $scope.saveUser = function() {
    $scope.user.username = $scope.newUsername;
    $scope.user.type = $scope.newType;
    if ( $scope.newPassword ) {
      $scope.user.password = $scope.newPassword;
    }

    $scope.user.$update(function(newUser, putResponseHeader) {
      $scope.user = newUser;
      setNewValuesByUser(newUser);
    });
  };

  $scope.deleteUser = function() {
    $scope.user.$delete(function() {
      AdminShared.showUser(null);
    });
  };
}]);

hgotsAdmin.controller('AdminNewController', [ '$scope', 'AdminShared', 'User', function($scope, AdminShared, User) {
  $scope.userTypes = AdminShared.userTypes;

  $scope.newUsername = "";
  $scope.newType = $scope.userTypes[0];
  $scope.newPassword = "";
  $scope.newPasswordRepeat = "";
  $scope.createDisabled = true;
  // make create available
  $scope.checkIfValid = function() {
    var usernamePresent = ( !!$scope.newUsername );
    var passwordPresent = ( !!$scope.newPassword && $scope.newPassword === $scope.newPasswordRepeat );

    var valid = ( usernamePresent && passwordPresent );
    console.log("valid:", valid);
    $scope.createDisabled = !valid;
    return valid;
  };
  // also check on every 'new' variable
  ['newUsername', 'newType', 'newPassword', 'newPasswordRepeat'].forEach(function(scopeVariable) {
    $scope.$watch(scopeVariable, function() {
      $scope.checkIfValid();
    });
  });

  $scope.createUser = function() {
    var newUser = new User({
      username: $scope.newUsername,
      type: $scope.newType,
      password: $scope.newPassword
    });
    newUser.$save(function(user) {
      AdminShared.showUser(user);
    });
  };
}]);
<|endoftext|>


<commit_before>import { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { isElloAndroid } from '../lib/jello'
import { selectIsLoggedIn } from '../selectors/authentication'
import {
  selectAllowsAnalytics,
  selectAnalyticsId,
  selectCreatedAt,
  selectCreatorTypes,
  selectIsNabaroo,
  selectProfileIsFeatured,
} from '../selectors/profile'
import * as ENV from '../../env'

const agent = isElloAndroid() ? 'android' : 'webapp'

export function addSegment({ createdAt, creatorTypes, hasAccount, isFeatured, isNabaroo, uid }) {
  /* eslint-disable */
  !function(){const analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){const e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(let t=0;t<analytics.methods.length;t++){const e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){const e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};
    /* eslint-enable */
    analytics.SNIPPET_VERSION = '3.1.0'
    analytics.load(ENV.SEGMENT_WRITE_KEY)
    if (uid) {
      analytics.identify(uid, {
        agent,
        createdAt,
        creatorTypes,
        hasAccount,
        isFeatured,
        isNabaroo,
      })
    }
  }
  }();
}

export function doesAllowTracking() {
  return !(
    window.navigator.doNotTrack === '1' ||
    window.navigator.msDoNotTrack === '1' ||
    window.doNotTrack === '1' ||
    window.msDoNotTrack === '1'
  )
}

function mapStateToProps(state) {
  const creatorTypes = selectCreatorTypes(state)
  return {
    allowsAnalytics: selectAllowsAnalytics(state),
    analyticsId: selectAnalyticsId(state),
    createdAt: selectCreatedAt(state),
    creatorTypes: creatorTypes.toArray(),
    isFeatured: selectProfileIsFeatured(state),
    isLoggedIn: selectIsLoggedIn(state),
    isNabaroo: selectIsNabaroo(state),
  }
}

class AnalyticsContainer extends Component {

  static propTypes = {
    allowsAnalytics: PropTypes.bool,
    analyticsId: PropTypes.string,
    createdAt: PropTypes.string,
    creatorTypes: PropTypes.array.isRequired,
    isFeatured: PropTypes.bool.isRequired,
    isLoggedIn: PropTypes.bool.isRequired,
    isNabaroo: PropTypes.bool.isRequired,
  }

  static defaultProps = {
    allowsAnalytics: null,
    analyticsId: null,
    createdAt: null,
  }

  componentWillMount() {
    this.hasLoadedTracking = false
  }

  componentDidMount() {
    const { analyticsId, allowsAnalytics, createdAt,
      isFeatured, isLoggedIn, creatorTypes, isNabaroo } = this.props
    if (this.hasLoadedTracking) { return }
    if (!isLoggedIn && doesAllowTracking()) {
      this.hasLoadedTracking = true
      addSegment({})
    } else if (analyticsId && allowsAnalytics) {
      this.hasLoadedTracking = true
      addSegment({ createdAt,
        hasAccount: isLoggedIn,
        isFeatured,
        creatorTypes,
        isNabaroo,
        uid: analyticsId })
    }
  }

  componentWillReceiveProps(nextProps) {
    const { allowsAnalytics, analyticsId, createdAt,
      isFeatured, isLoggedIn, creatorTypes, isNabaroo } = nextProps
    if (this.hasLoadedTracking) {
      // identify the user if they didn't previously have an id to identify with
      if (!this.props.analyticsId && analyticsId) {
        const props = { agent,
          createdAt,
          hasAccount: isLoggedIn,
          isFeatured,
          creatorTypes,
          isNabaroo }
        window.analytics.identify(analyticsId, props)
      }
    } else if (this.props.analyticsId && analyticsId && allowsAnalytics) {
      this.hasLoadedTracking = true
      addSegment({ createdAt,
        hasAccount: isLoggedIn,
        isFeatured,
        isNabaroo,
        creatorTypes,
        uid: analyticsId })
    }
  }

  shouldComponentUpdate() {
    return false
  }

  render() {
    return null
  }
}

export default connect(mapStateToProps)(AnalyticsContainer)

<commit_msg>Fix DNT for logged in users.<commit_after>import { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { isElloAndroid } from '../lib/jello'
import { selectIsLoggedIn } from '../selectors/authentication'
import {
  selectAllowsAnalytics,
  selectAnalyticsId,
  selectCreatedAt,
  selectCreatorTypes,
  selectIsNabaroo,
  selectProfileIsFeatured,
} from '../selectors/profile'
import * as ENV from '../../env'

const agent = isElloAndroid() ? 'android' : 'webapp'

export function addSegment({ createdAt, creatorTypes, hasAccount, isFeatured, isNabaroo, uid }) {
  /* eslint-disable */
  !function(){const analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){const e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(let t=0;t<analytics.methods.length;t++){const e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){const e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};
    /* eslint-enable */
    analytics.SNIPPET_VERSION = '3.1.0'
    analytics.load(ENV.SEGMENT_WRITE_KEY)
    if (uid) {
      analytics.identify(uid, {
        agent,
        createdAt,
        creatorTypes,
        hasAccount,
        isFeatured,
        isNabaroo,
      })
    }
  }
  }();
}

export function doesAllowTracking() {
  return !(
    window.navigator.doNotTrack === '1' ||
    window.navigator.msDoNotTrack === '1' ||
    window.doNotTrack === '1' ||
    window.msDoNotTrack === '1'
  )
}

function mapStateToProps(state) {
  const creatorTypes = selectCreatorTypes(state)
  return {
    allowsAnalytics: doesAllowTracking() && selectAllowsAnalytics(state),
    analyticsId: selectAnalyticsId(state),
    createdAt: selectCreatedAt(state),
    creatorTypes: creatorTypes.toArray(),
    isFeatured: selectProfileIsFeatured(state),
    isLoggedIn: selectIsLoggedIn(state),
    isNabaroo: selectIsNabaroo(state),
  }
}

class AnalyticsContainer extends Component {

  static propTypes = {
    allowsAnalytics: PropTypes.bool,
    analyticsId: PropTypes.string,
    createdAt: PropTypes.string,
    creatorTypes: PropTypes.array.isRequired,
    isFeatured: PropTypes.bool.isRequired,
    isLoggedIn: PropTypes.bool.isRequired,
    isNabaroo: PropTypes.bool.isRequired,
  }

  static defaultProps = {
    allowsAnalytics: null,
    analyticsId: null,
    createdAt: null,
  }

  componentWillMount() {
    this.hasLoadedTracking = false
  }

  componentDidMount() {
    const { analyticsId, allowsAnalytics, createdAt,
      isFeatured, isLoggedIn, creatorTypes, isNabaroo } = this.props
    if (this.hasLoadedTracking) { return }
    if (!isLoggedIn && doesAllowTracking()) {
      this.hasLoadedTracking = true
      addSegment({})
    } else if (analyticsId && allowsAnalytics) {
      this.hasLoadedTracking = true
      addSegment({ createdAt,
        hasAccount: isLoggedIn,
        isFeatured,
        creatorTypes,
        isNabaroo,
        uid: analyticsId })
    }
  }

  componentWillReceiveProps(nextProps) {
    const { allowsAnalytics, analyticsId, createdAt,
      isFeatured, isLoggedIn, creatorTypes, isNabaroo } = nextProps
    if (this.hasLoadedTracking) {
      // identify the user if they didn't previously have an id to identify with
      if (!this.props.analyticsId && analyticsId) {
        const props = { agent,
          createdAt,
          hasAccount: isLoggedIn,
          isFeatured,
          creatorTypes,
          isNabaroo }
        window.analytics.identify(analyticsId, props)
      }
    } else if (this.props.analyticsId && analyticsId && allowsAnalytics) {
      this.hasLoadedTracking = true
      addSegment({ createdAt,
        hasAccount: isLoggedIn,
        isFeatured,
        isNabaroo,
        creatorTypes,
        uid: analyticsId })
    }
  }

  shouldComponentUpdate() {
    return false
  }

  render() {
    return null
  }
}

export default connect(mapStateToProps)(AnalyticsContainer)

<|endoftext|>


<commit_before>import React from 'react';
import cx from 'classnames';

const DATABASE_SVG = (
  <svg xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 50 50">
    <path d="M24.985,0C37.556,0,46,4.576,46,8.849c0,4.274-8.444,8.85-21.015,8.85c-12.572,0-21.017-4.576-21.017-8.85 C3.968,4.576,12.413,0,24.985,0z M46,39.151C46,43.424,37.556,48,24.985,48c-12.572,0-21.017-4.576-21.017-8.849v-5.195 c3.676,3.753,11.597,6.302,21.017,6.302c9.418,0,17.34-2.549,21.015-6.302V39.151z M46,29.196c0,4.272-8.444,8.849-21.015,8.849 c-12.572,0-21.017-4.576-21.017-8.849v-5.286c3.676,3.752,11.597,6.301,21.017,6.301c9.418,0,17.34-2.549,21.015-6.301V29.196z M46,19.15C46,23.424,37.556,28,24.985,28c-12.572,0-21.017-4.576-21.017-8.85v-5.541c3.676,3.753,11.597,6.301,21.017,6.301 c9.418,0,17.34-2.547,21.015-6.301V19.15z"></path>
  </svg>
);

const Database = (props) => {
  let description;

  switch (props.database) {
    case 'mongodb':
      description = (

          MongoDB — Document-oriented, general purpose NoSQL database.

      );
      break;
    case 'sqlite':
      description = (

          SQLite — A self-contained, serverless, zero-configuration, transactional SQL database engine.

      );
      break;
    case 'mysql':
      description = (

          MySQL — The world's most popular open source database.

      );
      break;
    case 'postgresql':
      description = (

          PostgreSQL  — The world's most advanced open source database.

      );
      break;
    case 'rethinkdb':
      description = (

          RethinkDB — The open source database
          for the realtime web.

      );
      break;
    default:
      description =

;
  }

  const recommended = props.beginner ? (

  ) : null;

  return (

{DATABASE_SVG}{!props.database || props.database === 'none' ? 'Database' : props.database}

        {description}

            <input type="radio" name="databaseRadios" value="none" onChange={props.handleChange} checked={props.database === 'none'} />
            None

            <input type="radio" name="databaseRadios" value="mongodb" onChange={props.handleChange} checked={props.database === 'mongodb'} />
            MongoDB
            {recommended}

            <input type="radio" name="databaseRadios" value="sqlite" onChange={props.handleChange} checked={props.database === 'sqlite'} />
            SQLite3

            <input type="radio" name="databaseRadios" value="mysql" onChange={props.handleChange} checked={props.database === 'mysql'} />
            MySQL

            <input type="radio" name="databaseRadios" value="postgresql" onChange={props.handleChange} checked={props.database === 'postgresql'} />
            PostgreSQL

            <input type="radio" name="databaseRadios" value="rethinkdb" onChange={props.handleChange} checked={props.database === 'rethinkdb'} />
            RethinkDB

  );
};

export default Database;
<commit_msg>Updated database order<commit_after>import React from 'react';
import cx from 'classnames';

const DATABASE_SVG = (
  <svg xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 50 50">
    <path d="M24.985,0C37.556,0,46,4.576,46,8.849c0,4.274-8.444,8.85-21.015,8.85c-12.572,0-21.017-4.576-21.017-8.85 C3.968,4.576,12.413,0,24.985,0z M46,39.151C46,43.424,37.556,48,24.985,48c-12.572,0-21.017-4.576-21.017-8.849v-5.195 c3.676,3.753,11.597,6.302,21.017,6.302c9.418,0,17.34-2.549,21.015-6.302V39.151z M46,29.196c0,4.272-8.444,8.849-21.015,8.849 c-12.572,0-21.017-4.576-21.017-8.849v-5.286c3.676,3.752,11.597,6.301,21.017,6.301c9.418,0,17.34-2.549,21.015-6.301V29.196z M46,19.15C46,23.424,37.556,28,24.985,28c-12.572,0-21.017-4.576-21.017-8.85v-5.541c3.676,3.753,11.597,6.301,21.017,6.301 c9.418,0,17.34-2.547,21.015-6.301V19.15z"></path>
  </svg>
);

const Database = (props) => {
  let description;

  switch (props.database) {
    case 'mongodb':
      description = (

          MongoDB — Document-oriented, general purpose NoSQL database.

      );
      break;
    case 'sqlite':
      description = (

          SQLite — A self-contained, serverless, zero-configuration, transactional SQL database engine.

      );
      break;
    case 'mysql':
      description = (

          MySQL — The world's most popular open source database.

      );
      break;
    case 'postgresql':
      description = (

          PostgreSQL  — The world's most advanced open source database.

      );
      break;
    case 'rethinkdb':
      description = (

          RethinkDB — The open source database
          for the realtime web.

      );
      break;
    default:
      description =

;
  }

  const recommended = props.beginner ? (

  ) : null;

  return (

{DATABASE_SVG}{!props.database || props.database === 'none' ? 'Database' : props.database}

        {description}

            <input type="radio" name="databaseRadios" value="none" onChange={props.handleChange} checked={props.database === 'none'} />
            None

            <input type="radio" name="databaseRadios" value="mongodb" onChange={props.handleChange} checked={props.database === 'mongodb'} />
            MongoDB
            {recommended}

            <input type="radio" name="databaseRadios" value="mysql" onChange={props.handleChange} checked={props.database === 'mysql'} />
            MySQL

            <input type="radio" name="databaseRadios" value="postgresql" onChange={props.handleChange} checked={props.database === 'postgresql'} />
            PostgreSQL

            <input type="radio" name="databaseRadios" value="sqlite" onChange={props.handleChange} checked={props.database === 'sqlite'} />
            SQLite3

            <input type="radio" name="databaseRadios" value="rethinkdb" onChange={props.handleChange} checked={props.database === 'rethinkdb'} />
            RethinkDB

  );
};

export default Database;
<|endoftext|>