<commit_before>'use strict';

var config = {
  formId: 'tkf-skoleskyss',
  formName: 'Skoleskyss',
  initialState: {
    page: 1,
    formId:'',
    formVersion:'',
    personnummer: '',
    navn: '',
    folkeregistrert_adresse_bosted: '',
    folkeregistrert_adresse_adresse:'',
    folkeregistrert_adresse_gnr: '',
    folkeregistrert_adresse_bnr: '',
    folkeregistrert_adresse_kommunenr:'',
    alternativ_adresse: '',
    alternativ_adresse_bosted: '',
    alternativ_adresse_adresse:'',
    alternativ_adresse_gnr: '',
    alternativ_adresse_bnr: '',
    alternativ_adresse_kommunenr:'',
    telefon: '',
    epost: '',
    skole: '',
    klassetrinn: '',
    sokegrunnlag: '',
    busskortstatus: '',
    busskortnummer: '',
    eksternSkoleNavn: '',
    eksternSkoleAdresse: '',
    beregnetStatus:'',
    utregnetAvstandFolkeregistrert: '',
    utregnetAvstandAdresseFolkeregistrert: '',
    utregnetAvstandSkoleFolkeregistrert: '',
    utregnetAvstandKartFolkeregistrert: '',
    holdeplassHjemFolkeregistrert: '',
    overgangFolkeregistrert: '',
    utregnetAvstandAlternativt: '',
    utregnetAvstandAdresseAlternativt: '',
    utregnetAvstandSkoleAlternativt: '',
    utregnetAvstandKartAlternativt: '',
    holdeplassHjemAlternativt: '',
    overgangAlternativt: '',
    holdeplassSkole:'',
    utmFolkeregistrert:'',
    utmAlternativt:'',
    utmSkole:'',
    fullReiseFolkeregistrert:'',
    fullReiseAlternativt:''
  },
  kommuneListe : [
    {value:'', text:'Velg kommune', id:'007'},
    {value:'0814', text:'Bamble', id:'0814'},
    {value:'0821', text:'Bø', id:'0821'},
    {value:'0817', text:'Drangedal', id:'0817'},
    {value:'0831', text:'Fyresdal', id:'0831'},
    {value:'0827', text:'Hjartdal', id:'0827'},
    {value:'0815', text:'Kragerø', id:'0815'},
    {value:'0829', text:'Kviteseid', id:'0829'},
    {value:'0830', text:'Nissedal', id:'0830'},
    {value:'0819', text:'Nome', id:'0819'},
    {value:'0807', text:'Notodden', id:'0807'},
    {value:'0805', text:'Porsgrunn', id:'0805'},
    {value:'0822', text:'Sauherad', id:'0822'},
    {value:'0828', text:'Seljord', id:'0828'},
    {value:'0811', text:'Siljan', id:'0811'},
    {value:'0806', text:'Skien', id:'0806'},
    {value:'0826', text:'Tinn', id:'0826'},
    {value:'0833', text:'Tokke', id:'0833'},
    {value:'0834', text:'Vinje', id:'0834'}
  ],
  skoleListe: [
    {value:'', text:'Velg skole', id:'007'},
    {value:'Bamble videregående skole, Tønderveien 6, 3960 Stathelle', text:'Bamble videregående skole, avdeling Grasmyr', id:'39601'},
    {value:'Bamble videregående skole, Tostrupsvei 7, 3960 Stathelle', text:'Bamble videregående skole, avdeling Croftholmen', id:'39602'},
    {value:'Bø videregåande skule, Gymnasbakken 23, 3802 Bø', text:'Bø videregåande skule', id:'3802'},
    {value:'Hjalmar Johansen videregående skole, Moflatvegen 38, 3733 Skien',
      text:'Hjalmar Johansen videregående skole, avdeling Fritidsparken', id:'3733'},
    {value:'Hjalmar Johansen videregående skole, Olai Skulleruds veg 20, 3730 Skien',
      text:'Hjalmar Johansen videregående skole, avdeling Klosterskogen', id:'3730'},
    {value:'Kragerø videregående skole, Frydensborgveien 9-11, 3770 Kragerø',
      text:'Kragerø videregående skole', id:'3770'},
    {value:'Kvitsund gymnas, Jakob Naadlandsveg 2, 3850 Kviteseid',
      text:'Kvitsund gymnas', id:'3850'},
    {value:'Nome videregående skole, Olav Strannas vei 25, 3825 Lunde',
      text:'Nome videregående skole, avdeling Lunde', id:'3825'},
    {value:'Nome videregående skole, Søveveien 8, 3830 Ulefoss',
      text:'Nome videregående skole, avdeling Søve', id:'3830'},
    {value:'Notodden videregående skole, Heddalsveien 4, 3674 Notodden',
      text:'Notodden videregående skole', id:'3674'},
    {value:'Porsgrunn videregående skole, Kjølnes Ring 58, 3918 Porsgrunn',
      text:'Porsgrunn videregående skole, avdeling Nord', id:'39181'},
    {value:'Porsgrunn videregående skole, Kjølnes Ring 20, 3918 Porsgrunn',
      text:'Porsgrunn videregående skole, avdeling Sør', id:'39182'},
    {value:'Rjukan videregående skole, Såheimveien 22, 3660 Rjukan',
      text:'Rjukan videregående skole', id:'3660'},
    {value:'Skien videregående skole, Rektor Ørns gate 2, 3717 Skien',
      text:'Skien videregående skole, avdeling Brekkeby', id:'3717'},
    {value:'Skien videregående skole, Einar Østvedts gate 12, 3724 Skien',
      text:'Skien videregående skole, avdeling Prestegjordet', id:'3724'},
    {value:'Skogmo videregående skole, Kjørbekkdalen 11, 3735 Skien',
      text:'Skogmo videregående skole', id:'3735'},
    {value:'Toppidrettsgymnaset i Telemark, Fritjof Nansens gate 19C, 3722 Skien',
      text:'Toppidrettsgymnaset i Telemark', id:'3722'},
    {value:'Vest-Telemark vidaregåande skule, Storvegen 195, 3880 Dalen',
      text:'Vest-Telemark vidaregåande skule, avdeling Dalen', id:'3880'},
    {value:'Vest-Telemark vidaregåande skule, Brøløsvegen 2, 3840 Seljord',
      text:'Vest-Telemark vidaregåande skule, avdeling Seljord', id:'3840'},
    {value:'Skole utenfor Telemark',
      text:'Skole utenfor Telemark', id:'0666'}
  ],
  SERVER_PORT: 3000,
  API_POST_HOST: 'api.t-fk.no',
  API_POST_PATH: '/forms',
  TRAVEL_API: 'https://api.t-fk.no/stages/travel'
};

module.exports = config;<commit_msg>Changes address<commit_after>'use strict';

var config = {
  formId: 'tkf-skoleskyss',
  formName: 'Skoleskyss',
  initialState: {
    page: 1,
    formId:'',
    formVersion:'',
    personnummer: '',
    navn: '',
    folkeregistrert_adresse_bosted: '',
    folkeregistrert_adresse_adresse:'',
    folkeregistrert_adresse_gnr: '',
    folkeregistrert_adresse_bnr: '',
    folkeregistrert_adresse_kommunenr:'',
    alternativ_adresse: '',
    alternativ_adresse_bosted: '',
    alternativ_adresse_adresse:'',
    alternativ_adresse_gnr: '',
    alternativ_adresse_bnr: '',
    alternativ_adresse_kommunenr:'',
    telefon: '',
    epost: '',
    skole: '',
    klassetrinn: '',
    sokegrunnlag: '',
    busskortstatus: '',
    busskortnummer: '',
    eksternSkoleNavn: '',
    eksternSkoleAdresse: '',
    beregnetStatus:'',
    utregnetAvstandFolkeregistrert: '',
    utregnetAvstandAdresseFolkeregistrert: '',
    utregnetAvstandSkoleFolkeregistrert: '',
    utregnetAvstandKartFolkeregistrert: '',
    holdeplassHjemFolkeregistrert: '',
    overgangFolkeregistrert: '',
    utregnetAvstandAlternativt: '',
    utregnetAvstandAdresseAlternativt: '',
    utregnetAvstandSkoleAlternativt: '',
    utregnetAvstandKartAlternativt: '',
    holdeplassHjemAlternativt: '',
    overgangAlternativt: '',
    holdeplassSkole:'',
    utmFolkeregistrert:'',
    utmAlternativt:'',
    utmSkole:'',
    fullReiseFolkeregistrert:'',
    fullReiseAlternativt:''
  },
  kommuneListe : [
    {value:'', text:'Velg kommune', id:'007'},
    {value:'0814', text:'Bamble', id:'0814'},
    {value:'0821', text:'Bø', id:'0821'},
    {value:'0817', text:'Drangedal', id:'0817'},
    {value:'0831', text:'Fyresdal', id:'0831'},
    {value:'0827', text:'Hjartdal', id:'0827'},
    {value:'0815', text:'Kragerø', id:'0815'},
    {value:'0829', text:'Kviteseid', id:'0829'},
    {value:'0830', text:'Nissedal', id:'0830'},
    {value:'0819', text:'Nome', id:'0819'},
    {value:'0807', text:'Notodden', id:'0807'},
    {value:'0805', text:'Porsgrunn', id:'0805'},
    {value:'0822', text:'Sauherad', id:'0822'},
    {value:'0828', text:'Seljord', id:'0828'},
    {value:'0811', text:'Siljan', id:'0811'},
    {value:'0806', text:'Skien', id:'0806'},
    {value:'0826', text:'Tinn', id:'0826'},
    {value:'0833', text:'Tokke', id:'0833'},
    {value:'0834', text:'Vinje', id:'0834'}
  ],
  skoleListe: [
    {value:'', text:'Velg skole', id:'007'},
    {value:'Bamble videregående skole, Tønderveien 6, 3960 Stathelle', text:'Bamble videregående skole, avdeling Grasmyr', id:'39601'},
    {value:'Bamble videregående skole, Tostrupsvei 7, 3960 Stathelle', text:'Bamble videregående skole, avdeling Croftholmen', id:'39602'},
    {value:'Bø videregåande skule, Gymnasbakken 23, 3802 Bø', text:'Bø videregåande skule', id:'3802'},
    {value:'Hjalmar Johansen videregående skole, Moflatvegen 38, 3733 Skien',
      text:'Hjalmar Johansen videregående skole, avdeling Fritidsparken', id:'3733'},
    {value:'Hjalmar Johansen videregående skole, Olai Skulleruds veg 20, 3730 Skien',
      text:'Hjalmar Johansen videregående skole, avdeling Klosterskogen', id:'3730'},
    {value:'Kragerø videregående skole, Frydensborgveien 9-11, 3770 Kragerø',
      text:'Kragerø videregående skole', id:'3770'},
    {value:'Kvitsund gymnas, Jakob Naadlands veg 2, 3850 Kviteseid',
      text:'Kvitsund gymnas', id:'3850'},
    {value:'Nome videregående skole, Olav Strannas vei 25, 3825 Lunde',
      text:'Nome videregående skole, avdeling Lunde', id:'3825'},
    {value:'Nome videregående skole, Søveveien 8, 3830 Ulefoss',
      text:'Nome videregående skole, avdeling Søve', id:'3830'},
    {value:'Notodden videregående skole, Heddalsveien 4, 3674 Notodden',
      text:'Notodden videregående skole', id:'3674'},
    {value:'Porsgrunn videregående skole, Kjølnes Ring 58, 3918 Porsgrunn',
      text:'Porsgrunn videregående skole, avdeling Nord', id:'39181'},
    {value:'Porsgrunn videregående skole, Kjølnes Ring 20, 3918 Porsgrunn',
      text:'Porsgrunn videregående skole, avdeling Sør', id:'39182'},
    {value:'Rjukan videregående skole, Såheimveien 22, 3660 Rjukan',
      text:'Rjukan videregående skole', id:'3660'},
    {value:'Skien videregående skole, Rektor Ørns gate 2, 3717 Skien',
      text:'Skien videregående skole, avdeling Brekkeby', id:'3717'},
    {value:'Skien videregående skole, Einar Østvedts gate 12, 3724 Skien',
      text:'Skien videregående skole, avdeling Prestegjordet', id:'3724'},
    {value:'Skogmo videregående skole, Kjørbekkdalen 11, 3735 Skien',
      text:'Skogmo videregående skole', id:'3735'},
    {value:'Toppidrettsgymnaset i Telemark, Fritjof Nansens gate 19C, 3722 Skien',
      text:'Toppidrettsgymnaset i Telemark', id:'3722'},
    {value:'Vest-Telemark vidaregåande skule, Storvegen 195, 3880 Dalen',
      text:'Vest-Telemark vidaregåande skule, avdeling Dalen', id:'3880'},
    {value:'Vest-Telemark vidaregåande skule, Brøløsvegen 2, 3840 Seljord',
      text:'Vest-Telemark vidaregåande skule, avdeling Seljord', id:'3840'},
    {value:'Skole utenfor Telemark',
      text:'Skole utenfor Telemark', id:'0666'}
  ],
  SERVER_PORT: 3000,
  API_POST_HOST: 'api.t-fk.no',
  API_POST_PATH: '/forms',
  TRAVEL_API: 'https://api.t-fk.no/stages/travel'
};

module.exports = config;<|endoftext|>


<commit_before>//Changing the win to = Ti.Ui.currentWindow, just allowed me to declare anytime I wanted to modify something to appear in this window to just
//add "win." whatever else instead of having to write "Titanium.UI.currentWindow." then "add." over and over.
var win = Titanium.UI.currentWindow;

var isAndroid = false;
if (Titanium.Platform.name == 'android'){
	isAndroid = true;
}
		/*  NAV BAR - Looking at making a "Re-center" button and a "Zoom-in" and "Zoom-out" button for easier navigation
			For this to work I had to delete all the files already complied in the "build/iphone" folder within the project
			folder. I don't know why, but it made a clean rebuild and it started adding the bars and acknowledging the
			"Titanium.UI.iPhone" part of the code instead of declaring it "unknown".  */

		//I believe that these declare the variables without having them set to anything.
		var zoomin = null;
		var zoomout = null;

		/*I have no idea what the "wireClickHandlers" function is suppose to do; I copied this code from the Maps example
		  from the Titanium Appcelerator KitchenSink. I think these just make the "zoom" variables become functions that
		  affect the mapview - and that the "mapview.zoom" part actually details how it changes the map itself.*/

		var wireClickHandlers = function() {
			zoomin.addEventListener('click',function() {
				mapview.zoom(1);
			})
			zoomout.addEventListener('click',function() {
				mapview.zoom(-1);
			})
		}
	  /* This statement is just in place because the "remove all" button (from the Maps example in the Kitchen Sink) won't work on the Android
		 phone as is and needs to be adjusted. So (!isAndroid) = if it isn't the Android OS do the following. It was important to place anyways
		because below, the zoom-in and zoom-out buttons need to have a different method. It is "menu.add" with a title. */
if (!isAndroid) {
		var flexSpace = Titanium.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
		});

		zoomin = Titanium.UI.createButton({
			title:'Zoom +',
			style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
		});

		zoomout = Titanium.UI.createButton({
			title:'Zoom -',
			style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
		});

		wireClickHandlers();
		/* The usage of "flexspace" below fills in the gaps. Since I placed a "flexspace" before the other identified buttons, it pushed those
		   buttons all the way to the right. If I wanted to add another button for any reason, just make sure to identify it and then determine
		   how much spacing is wanted. */
		win.setToolbar([flexSpace,zoomin,zoomout]);

} else {
	var activity = Titanium.Android.currentActivity;
	activity.onCreateOptionsMenu = function() {
		var menu = e.menu;
		zoomin = menu.add({title : "Zoom In"});
		zoomout = menu.add({title : "Zoom Out"});
		wireClickHandlers();
	}
}

//
// Begin Geo Location
//

Titanium.Geolocation.purpose = "Recieve User Location";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;

// Set Distance filter. This dictates how often an event fires based on the distance the device moves. This value is in meters.
Titanium.Geolocation.distanceFilter = 10;

//This fires only ONCE.
var longitude = Titanium.Geolocation.getCurrentPosition(function(e) {
        if (e.error) {
            Ti.API.log('error: ' + JSON.stringify(e.error) );
            return;
        }
		//This gets the current coordinates
		e.coords.longitude;
/*		var latitude = e.coords.latitude;
		var altitude = e.coords.altitude;
		var heading = e.coords.heading;
		var accuracy = e.coords.accuracy;
		var speed = e.coords.speed;
		var timestamp = e.coords.timestamp;
		var altitudeAccuracy = e.coords.altitudeAccuracy; */

});

var latitude = Titanium.Geolocation.getCurrentPosition(function(e) {
        if (e.error) {
            Ti.API.log('error: ' + JSON.stringify(e.error) );
            return;
        }
		e.coords.latitude;
})

//
// Begin drawing map
//
var mapview = Titanium.Map.createView({
	mapType: Titanium.Map.STANDARD_TYPE,
	// Latitude and Longitude Delta values are set for default zoom. They are in meters.
	//The following are booleans
	animate:true,
	regionFit:true,
	userLocation:true,
	region: {latitude: latitude, longitude: longitude, latitudeDelta:.01, longitudeDelta:.01},
});

/*mapview.addEventListener('regionChanged',function() {
	region:{latitude, longitude}
	});*/

win.add(mapview);<commit_msg>Revert back to mapview in Geolocation<commit_after>//Changing the win to = Ti.Ui.currentWindow, just allowed me to declare anytime I wanted to modify something to appear in this window to just
//add "win." whatever else instead of having to write "Titanium.UI.currentWindow." then "add." over and over.
var win = Titanium.UI.currentWindow;

var isAndroid = false;
if (Titanium.Platform.name == 'android'){
	isAndroid = true;
}
		/*  NAV BAR - Looking at making a "Re-center" button and a "Zoom-in" and "Zoom-out" button for easier navigation
			For this to work I had to delete all the files already complied in the "build/iphone" folder within the project
			folder. I don't know why, but it made a clean rebuild and it started adding the bars and acknowledging the
			"Titanium.UI.iPhone" part of the code instead of declaring it "unknown".  */

		//I believe that these declare the variables without having them set to anything.
		var zoomin = null;
		var zoomout = null;

		/*I have no idea what the "wireClickHandlers" function is suppose to do; I copied this code from the Maps example
		  from the Titanium Appcelerator KitchenSink. I think these just make the "zoom" variables become functions that
		  affect the mapview - and that the "mapview.zoom" part actually details how it changes the map itself.*/

		var wireClickHandlers = function() {
			zoomin.addEventListener('click',function() {
				mapview.zoom(1);
			})
			zoomout.addEventListener('click',function() {
				mapview.zoom(-1);
			})
		}
	  /* This statement is just in place because the "remove all" button (from the Maps example in the Kitchen Sink) won't work on the Android
		 phone as is and needs to be adjusted. So (!isAndroid) = if it isn't the Android OS do the following. It was important to place anyways
		because below, the zoom-in and zoom-out buttons need to have a different method. It is "menu.add" with a title. */
if (!isAndroid) {
		var flexSpace = Titanium.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
		});

		zoomin = Titanium.UI.createButton({
			title:'Zoom +',
			style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
		});

		zoomout = Titanium.UI.createButton({
			title:'Zoom -',
			style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
		});

		wireClickHandlers();
		/* The usage of "flexspace" below fills in the gaps. Since I placed a "flexspace" before the other identified buttons, it pushed those
		   buttons all the way to the right. If I wanted to add another button for any reason, just make sure to identify it and then determine
		   how much spacing is wanted. */
		win.setToolbar([flexSpace,zoomin,zoomout]);

} else {
	var activity = Titanium.Android.currentActivity;
	activity.onCreateOptionsMenu = function() {
		var menu = e.menu;
		zoomin = menu.add({title : "Zoom In"});
		zoomout = menu.add({title : "Zoom Out"});
		wireClickHandlers();
	}
}

//
// Begin Geo Location
//

Titanium.Geolocation.purpose = "Recieve User Location";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;

// Set Distance filter. This dictates how often an event fires based on the distance the device moves. This value is in meters.
Titanium.Geolocation.distanceFilter = 10;

//This fires only ONCE.
var my_location = Titanium.Geolocation.getCurrentPosition(function(e) {
        if (e.error) {
            Ti.API.log('error: ' + JSON.stringify(e.error) );
            return;
        }
		//This gets the current coordinates
		var current_longitude = e.coords.longitude;
		var current_latitude = e.coords.latitude;
		var current_altitude = e.coords.altitude;
		var current_heading = e.coords.heading;
		var current_accuracy = e.coords.accuracy;
		var current_speed = e.coords.speed;
		var current_timestamp = e.coords.timestamp;
		var current_altitudeAccuracy = e.coords.altitudeAccuracy;
		//
		// Begin drawing map
		//
		var mapview = Titanium.Map.createView({
			mapType: Titanium.Map.STANDARD_TYPE,
			//The following are booleans
			animate:true,
			regionFit:true,
			userLocation:true,
			// Latitude and Longitude Delta values are set for default zoom. They are in meters.
			region: {latitude: current_latitude, longitude: current_longitude, latitudeDelta:.01, longitudeDelta:.01},
		});
		mapview.addEventListener('regionChanged', function(){

		});
	    win.add(mapview);

});<|endoftext|>


<commit_before>// -*- Mode: JavaScript; tab-width: 4 -*- vim:tabstop=4 syntax=javascript:
/* 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/. */
// Module: Transform text.

module.version = 1.3;
module.alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
module.alphaLC = "abcdefghijklmnopqrstuvwxyz";

module.cmd_tr =
function cmd_tr(dest, msg, nick, host, at, serv, relay)
{	const args = /^"(\"?[^"]+(?:\"[^"]*)*)" "(\"?[^"]+(?:\"[^"]*)*)" "(\"?[^"]+(?:\"[^"]*)*)"$/.exec(msg);
	if (!args)
		aucgbot.msg(dest, at + 'Invalid usage. Usage: tr "<text>" "<trFromTable>" "<trToTable>"');
	else
		aucgbot.msg(dest, at + tr.apply(null, args));
	return true;
}
module.cmd_rot13 =
function cmd_rot13(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + tr(msg, this.alphabet + this.alphaLC, "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"));
	return true;
}
module.cmd_rot47 =
function cmd_rot47(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + tr(msg, "!\"#$%&\'()*+,-./0123456789:;<=>?@" + this.alphabet + "[\\]^_`" + this.alphaLC + "{|}~", "PQRSTUVWXYZ[\\]^_`" + this.alphaLC + "{|}~!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO"));
module.cmd_revtr =
function cmd_revtr(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + tr(msg, this.alphabet + this.alphaLC, this.reverseABC + this.reverseABC.toLowerCase()));
	return true;
}
module.cmd_rev =
function cmd_rev(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + msg.reverse());
	return true;
}

// from http://www.svendtofte.com/code/usefull_prototypes/
// and https://developer.mozilla.org/en/A_re-introduction_to_JavaScript
String.prototype.reverse =
function reverse()
{	var s = "";
	for (var i = this.length - 1; i >= 0; i--)
	    s += this[i];
	return s;
}
module.reverseABC = module.alphabet.reverse();

function tr(str, fromTable, toTable)
{	var s = "";
	for (var i = 0, j = 0, k = ""; i < str.length; i++)
	{	if ((j = fromTable.indexOf(str[i])) == -1)
			k = str[i];
		else if (!(k = toTable[j]))
			k = "";
		s += k;
	}
	return s;
}<commit_msg>fix a derp and add HTML/URL/Base64 commands<commit_after>// -*- Mode: JavaScript; tab-width: 4 -*- vim:tabstop=4 syntax=javascript:
/* 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/. */
// Module: Transform text.

module.version = 1.4;
module.alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
module.alphaLC = "abcdefghijklmnopqrstuvwxyz";

module.cmd_tr =
function cmd_tr(dest, msg, nick, host, at, serv, relay)
{	const args = /^"(\"?[^"]+(?:\"[^"]*)*)" "(\"?[^"]+(?:\"[^"]*)*)" "(\"?[^"]+(?:\"[^"]*)*)"$/.exec(msg);
	if (!args)
		aucgbot.msg(dest, at + 'Invalid usage. Usage: tr "<text>" "<trFromTable>" "<trToTable>"');
	else
		aucgbot.msg(dest, at + tr.apply(null, args));
	return true;
}
module.cmd_rot13 =
function cmd_rot13(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + tr(msg, this.alphabet + this.alphaLC, "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"));
	return true;
}
module.cmd_rot47 =
function cmd_rot47(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + tr(msg, "!\"#$%&\'()*+,-./0123456789:;<=>?@" + this.alphabet + "[\\]^_`" + this.alphaLC + "{|}~", "PQRSTUVWXYZ[\\]^_`" + this.alphaLC + "{|}~!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO"));
	return true;
}
module.cmd_revtr =
function cmd_revtr(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + tr(msg, this.alphabet + this.alphaLC, this.reverseABC + this.reverseABC.toLowerCase()));
	return true;
}
module.cmd_rev =
function cmd_rev(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + msg.reverse());
	return true;
}
module.cmd_b64encode =
function cmd_b64encode(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + encodeB64(msg));
	return true;
}
module.cmd_b64decode =
function cmd_b64decode(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + decodeB64(msg));
	return true;
}
module.cmd_htmlencode =
function cmd_htmlencode(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + encodeHTML(msg));
	return true;
}
module.cmd_htmldecode =
function cmd_htmldecode(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + decodeHTML(msg));
	return true;
}
module.cmd_urlencode =
function cmd_urlencode(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + encodeURL(msg));
	return true;
}
module.cmd_urldecode =
function cmd_urldecode(dest, msg, nick, host, at, serv, relay)
{	aucgbot.msg(dest, at + decodeURL(msg));
	return true;
}

// from http://www.svendtofte.com/code/usefull_prototypes/
// and https://developer.mozilla.org/en/A_re-introduction_to_JavaScript
String.prototype.reverse =
function reverse()
{	var s = "";
	for (var i = this.length - 1; i >= 0; i--)
	    s += this[i];
	return s;
}
module.reverseABC = module.alphabet.reverse();

function tr(str, fromTable, toTable)
{	var s = "";
	for (var i = 0, j = 0, k = ""; i < str.length; i++)
	{	if ((j = fromTable.indexOf(str[i])) == -1)
			k = str[i];
		else if (!(k = toTable[j]))
			k = "";
		s += k;
	}
	return s;
}<|endoftext|>


<commit_before>function mapQuery(lat, lon, longdelt, callback){
	var Cloud = require('ti.cloud');
	var radians = 180*longdelt/3.14;
	Cloud.debug = true;
	jobs = Cloud.Objects.query({
		classname : 'jobs',
		limit : 100,
		where : {
			"coordinates":{"$nearSphere":[lon, lat], "$maxDistance" : radians }
			}
	}, function(e) {
		if(e.success){
			alert('Success:\n' + 'Count: ' + e.jobs.length + e.jobs[0].description);
			return e.jobs;
		}else {
        alert('Error:\n' +
            ((e.error && e.message) || JSON.stringify(e)));
   		}
	});

}

exports.createMapWindow = function(){
	var win = Ti.UI.createWindow({
	backgroundColor : "white",
	layout : 'vertical',
	navBarHidden : true
	});

	var osname = Ti.Platform.osname;

	var lat;
	var lon;
	var	latitudeDelta = 0.1;
	var	longitudeDelta = 0.1;

	var loc = Ti.Geolocation.getCurrentPosition(function(e) {
		if (e.error) {
			alert('Cannot get your current location, using default..');
			latitude = 0;
			longitude = 0;
			return;
		} else {
			alert('Success getting location');
			lat = e.coords.latitude;
			lon = e.coords.longitude;
			return;
		}
	});

var jobs = mapQuery(lat, lon, longitudeDelta );
alert(JSON.stringify(jobs));
var annot = new Array();

if (osname == 'android') {

	var MapModule = require('ti.map');

	for(var i = 0 ; i < jobs.jobs.length ; i++ ){
		var job = jobs.jobs[i];
		annot[i] = MapModule.createAnnotation({
			latitude : job.coordinates[1],
			longitude : job.coordinates[0],
			title : job.description,
			subtitle : job.time_estimate + " hours \n$" + job.wage +"\nexpires " + job.expiration,
			animate : true,
			leftView: Ti.UI.createButton({title :'contactPoster'})
		});
	}

	var osu = MapModule.createAnnotation({
		latitude : 44.5646,
		longitude : -123.2757,
		title : "Oregon State University",
		subtitle : 'Corvallis, OR',
		pincolor : MapModule.ANNOTATION_RED,
		animate : true,
		//leftButton : '../images/appcelerator_small.png',
		leftView: Ti.UI.createButton({title: 'Detail'}),
		myid : 1 // Custom property to uniquely identify this annotation.
	});

	var map = MapModule.createView({
		height : '90%',
		userLocation : true,
		mapType : MapModule.NORMAL_TYPE,
		animate : true,
		region : {
			latitude : lat,
			longitude : lon,
			latitudeDelta : 0.1,
			longitudeDelta : 0.1
		},
		// height : Titanium.UI.Fill,
		width : Titanium.UI.Fill,
		top : 0,
		left : 0,
		annotations : annot
	});
} else {

	var osu = Titanium.Map.createAnnotation({
		latitude : 44.5646,
		longitude : -123.2757,
		title : "Oregon State University",
		subtitle : 'Corvallis, OR',
		pincolor : Titanium.Map.ANNOTATION_RED,
		animate : true,
		// leftView: Ti.UI.createButton({title: 'Detail'}),
		// leftView: Ti.UI.createButton({title: 'Detail'}),
		leftButton : Titanium.UI.iPhone.SystemButton.INFO_LIGHT,
		myid : 1 // Custom property to uniquely identify this annotation.
	});

	var map = Titanium.Map.createView({
		height : '95%',
		userLocation : true,
		mapType : Titanium.Map.STANDARD_TYPE,
		animate : true,
		region : {
			latitude : lat,
			longitude : lon,
			latitudeDelta : 0.1,
			longitudeDelta : 0.1
		},
		top : 0,
		left : 0,
		annotations : [osu]
	});
}
win.add(map);
var backBtn = Ti.UI.createButton({
	title : 'Back',
	width : Ti.UI.FILL,
	 height : Ti.UI.FILL
});
backBtn.addEventListener('click', function(){
	win.close();
});
win.add(backBtn);
	win.open();
}

<commit_msg>callback first attempt<commit_after>function mapQuery(lat, lon, longdelt, callback, win){
	var Cloud = require('ti.cloud');
	var radians = 180*longdelt/3.14;
	Cloud.debug = true;
	jobs = Cloud.Objects.query({
		classname : 'jobs',
		limit : 100,
		where : {
			"coordinates":{"$nearSphere":[lon, lat], "$maxDistance" : radians }
			}
	}, function(e) {
		if(e.success){
			alert('Success:\n' + 'Count: ' + e.jobs.length + e.jobs[0].description);
			callback(e.jobs, win);
		}else {
        alert('Error:\n' +
            ((e.error && e.message) || JSON.stringify(e)));
   		}
	});

}

var callback = function(jobs, win){

		for(var i = 0 ; i < jobs.length ; i++ ){
		var job = jobs[i];
		annot[i] = MapModule.createAnnotation({
			latitude : job.coordinates[1],
			longitude : job.coordinates[0],
			title : job.description,
			subtitle : job.time_estimate + " hours \n$" + job.wage +"\nexpires " + job.expiration,
			animate : true,
			leftView: Ti.UI.createButton({title :'contactPoster'})
		});
		win.add(annot[i]);
	}
};

exports.createMapWindow = function(){
	var win = Ti.UI.createWindow({
	backgroundColor : "white",
	layout : 'vertical',
	navBarHidden : true
	});

	var osname = Ti.Platform.osname;

	var lat;
	var lon;
	var	latitudeDelta = 0.1;
	var	longitudeDelta = 0.1;

	var loc = Ti.Geolocation.getCurrentPosition(function(e) {
		if (e.error) {
			alert('Cannot get your current location, using default..');
			latitude = 0;
			longitude = 0;
			return;
		} else {
			alert('Success getting location');
			lat = e.coords.latitude;
			lon = e.coords.longitude;
			return;
		}
	});

mapQuery(lat, lon, longitudeDelta, callback, win );
alert(JSON.stringify(jobs));
var annot = new Array();

if (osname == 'android') {

	var MapModule = require('ti.map');

	var osu = MapModule.createAnnotation({
		latitude : 44.5646,
		longitude : -123.2757,
		title : "Oregon State University",
		subtitle : 'Corvallis, OR',
		pincolor : MapModule.ANNOTATION_RED,
		animate : true,
		//leftButton : '../images/appcelerator_small.png',
		leftView: Ti.UI.createButton({title: 'Detail'}),
		myid : 1 // Custom property to uniquely identify this annotation.
	});

	var map = MapModule.createView({
		height : '90%',
		userLocation : true,
		mapType : MapModule.NORMAL_TYPE,
		animate : true,
		region : {
			latitude : lat,
			longitude : lon,
			latitudeDelta : 0.1,
			longitudeDelta : 0.1
		},
		// height : Titanium.UI.Fill,
		width : Titanium.UI.Fill,
		top : 0,
		left : 0,
		annotations : annot
	});
} else {

	var osu = Titanium.Map.createAnnotation({
		latitude : 44.5646,
		longitude : -123.2757,
		title : "Oregon State University",
		subtitle : 'Corvallis, OR',
		pincolor : Titanium.Map.ANNOTATION_RED,
		animate : true,
		// leftView: Ti.UI.createButton({title: 'Detail'}),
		// leftView: Ti.UI.createButton({title: 'Detail'}),
		leftButton : Titanium.UI.iPhone.SystemButton.INFO_LIGHT,
		myid : 1 // Custom property to uniquely identify this annotation.
	});

	var map = Titanium.Map.createView({
		height : '95%',
		userLocation : true,
		mapType : Titanium.Map.STANDARD_TYPE,
		animate : true,
		region : {
			latitude : lat,
			longitude : lon,
			latitudeDelta : 0.1,
			longitudeDelta : 0.1
		},
		top : 0,
		left : 0,
		annotations : [osu]
	});
}
win.add(map);
var backBtn = Ti.UI.createButton({
	title : 'Back',
	width : Ti.UI.FILL,
	 height : Ti.UI.FILL
});
backBtn.addEventListener('click', function(){
	win.close();
});
win.add(backBtn);
	win.open();
}

<|endoftext|>


<commit_before>(function() {
var app = angular.module('Crypto', []);
app.controller('CryptoCtrl', ['$scope', function($scope) {

  $scope.sentence = "";
  $scope.lettersString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $scope.letters = [];
  $scope.lettersToNumbers = {};

  $scope.setLetters = function(lettersArray) {
    for(var i = 0; i < lettersArray.length; i++) {
      $scope.lettersToNumbers[lettersArray[i]] = i + 1;
      $scope.letters = lettersArray;
    }
  };

  $scope.resetLetters = function() {
    $scope.setLetters($scope.lettersString.split(""));
  };

  $scope.resetLetters(); // calling to init

  $scope.shuffleLetters = function() {
    var array = $scope.lettersString.split("");
    var currentIndex = array.length;
    var temporaryValue;
    var randomIndex;

    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    $scope.setLetters(array);
  };

  $scope.clearSentence = function() {
    $scope.sentence = "";
  };

  $scope.dash = function(character) {
    if($scope.letters.indexOf(character.toUpperCase()) >= 0) {
      return "_____";
    } else {
      return character;
    }
  };

  $scope.clue = function(character) {
    var num = $scope.lettersToNumbers[character.toUpperCase()];
    if(num !== undefined) {
      return num;
    } else {
      return " ";
    }
  };

  $scope.lines = function() {
    var lineList = [];
    var curLine = "";

    var wordList = $scope.sentence.split(/\s+/);
    for(var i = 0; i < wordList.length; i++) {
      var word = wordList[i];
      if(curLine.length !== 0 && curLine.length + word.length > 12) {
        lineList.push(curLine);
        curLine = "";
      }

      if(curLine.length !== 0) {
        curLine += " ";
      }
      curLine += word;
    }

    if(curLine.length > 0) {
      lineList.push(curLine);
    }

    return lineList;
  };

}]);

})();
<commit_msg>flip while statement<commit_after>(function() {
var app = angular.module('Crypto', []);
app.controller('CryptoCtrl', ['$scope', function($scope) {

  $scope.sentence = "";
  $scope.lettersString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $scope.letters = [];
  $scope.lettersToNumbers = {};

  $scope.setLetters = function(lettersArray) {
    for(var i = 0; i < lettersArray.length; i++) {
      $scope.lettersToNumbers[lettersArray[i]] = i + 1;
      $scope.letters = lettersArray;
    }
  };

  $scope.resetLetters = function() {
    $scope.setLetters($scope.lettersString.split(""));
  };

  $scope.resetLetters(); // calling to init

  $scope.shuffleLetters = function() {
    var array = $scope.lettersString.split("");
    var currentIndex = array.length;
    var temporaryValue;
    var randomIndex;

    while (currentIndex !== 0) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    $scope.setLetters(array);
  };

  $scope.clearSentence = function() {
    $scope.sentence = "";
  };

  $scope.dash = function(character) {
    if($scope.letters.indexOf(character.toUpperCase()) >= 0) {
      return "_____";
    } else {
      return character;
    }
  };

  $scope.clue = function(character) {
    var num = $scope.lettersToNumbers[character.toUpperCase()];
    if(num !== undefined) {
      return num;
    } else {
      return " ";
    }
  };

  $scope.lines = function() {
    var lineList = [];
    var curLine = "";

    var wordList = $scope.sentence.split(/\s+/);
    for(var i = 0; i < wordList.length; i++) {
      var word = wordList[i];
      if(curLine.length !== 0 && curLine.length + word.length > 12) {
        lineList.push(curLine);
        curLine = "";
      }

      if(curLine.length !== 0) {
        curLine += " ";
      }
      curLine += word;
    }

    if(curLine.length > 0) {
      lineList.push(curLine);
    }

    return lineList;
  };

}]);

})();
<|endoftext|>


<commit_before>import PartyBot from 'partybot-http-client';
import React, { PropTypes, Component } from 'react';
import cssModules from 'react-css-modules';
import styles from './index.module.scss';
import Heading from 'grommet/components/Heading';
import Box from 'grommet/components/Box';
import Footer from 'grommet/components/Footer';
import Button from 'grommet/components/Button';
import Form from 'grommet/components/Form';
import FormField from 'grommet/components/FormField';
import FormFields from 'grommet/components/FormFields';
import NumberInput from 'grommet/components/NumberInput';
import CloseIcon from 'grommet/components/icons/base/Close';
import Dropzone from 'react-dropzone';
import Layer from 'grommet/components/Layer';
import Header from 'grommet/components/Header';
import Section from 'grommet/components/Section';
import Paragraph from 'grommet/components/Paragraph';
import request from 'superagent';
import { CLOUDINARY_UPLOAD_PRESET, CLOUDINARY_NAME, CLOUDINARY_KEY, CLOUDINARY_SECRET, CLOUDINARY_UPLOAD_URL } from '../../constants';
import Immutable from 'immutable';
class ManageTablesPage extends Component {
  constructor(props) {
    super(props);
    this.handleMobile = this.handleMobile.bind(this);
    this.getTableVariants = this.getTableVariants.bind(this);
    this.closeSetup = this.closeSetup.bind(this);
    this.onDrop = this.onDrop.bind(this);
    this.onRemoveImage = this.onRemoveImage.bind(this);
    this.addVariant = this.addVariant.bind(this);
    this.submitSave = this.submitSave.bind(this);
    this.submitDelete = this.submitDelete.bind(this);
    this.state = {
      isMobile: false,
      tableId: props.params.table_id || null,
      confirm: false,
      name: '',
      variants: [],
      organisationId: '5800471acb97300011c68cf7',
      venues: [],
      venueId: '',
      events: [],
      eventId: '',
      tableTypes: [],
      tableTypeId: undefined,
      tags: 'table',
      image: null,
      prevImage: null,
      isNewImage: null,
      prices: []
    };
  }

  componentWillMount() {
    if (this.state.tableId) {
      this.setState({variants: []});
    }
  }

  componentDidMount() {
    if (typeof window !== 'undefined') {
      window.addEventListener('resize', this.handleMobile);
    }

    let options = {
      organisationId: this.state.organisationId
    };
    this.getVenues(options);
    // IF TABLE ID EXISTS
    if(this.props.params.table_id) {
      let tOptions = {
        organisationId: this.state.organisationId,
        productId: this.props.params.table_id
      }
      this.getTable(tOptions);
    }
  }
  componentWillUnmount() {
    if (typeof window !== 'undefined') {
      window.removeEventListener('resize', this.handleMobile);
    }
  }
  handleMobile() {
    const isMobile = window.innerWidth <= 768;
    this.setState({
      isMobile,
    });
  };

  getVenues = (options) => {
    PartyBot.venues.getAllInOrganisation(options, (errors, response, body) => {
      if(response.statusCode == 200) {
        if(body.length > 0) {
          this.setState({venueId: body[0]._id});
          let ttOptions = {
            organisationId: this.state.organisationId,
            venue_id: this.state.venueId
          }
          this.getEvents(ttOptions);
          this.getTableTypes(ttOptions);
        }
        this.setState({venues: body, events: []});
      }
    });
  }

  getEvents = (options) => {
    PartyBot.events.getEventsInOrganisation(options, (err, response, body) => {
      if(!err && response.statusCode == 200) {
        if(body.length > 0) {
          this.setState({eventId: body[0]._id});
        }
        body.map((value, index) =>{
          this.setState({events: this.state.events.concat({ _event: value._id, name: value.name, selected: false })});
        });
      }
    });
  }

  getTableTypes = (options) => {
    PartyBot.tableTypes.getTableTypesInOrganisation(options, (errors, response, body) => {
      if(response.statusCode == 200) {
        if(body.length > 0) {
          this.setState({tableTypeId: body[0]._id});
        }
        this.setState({tableTypes: body});
      }
    });
  }

  getTable = (options) => {
    PartyBot.products.getProductsInOrganisation(options, (error, response, body) => {
      if(response.statusCode == 200) {
        this.setState({
          name: body.name,
          image: {
            preview: body.image
          },
          prevImage: {
            preview: body.image
          },
          variants: body.prices.map((value, index) => {
            return {  _event: value._event, price: value.price }
          })
        });

      }
    });
  }

  onVenueChange = (event) => {
    let id = event.target.value;
    this.setState({ venueId: id, events: [], variants: []});
    let options = {
      organisationId: this.state.organisationId,
      venue_id: id
    };
    this.getTableTypes(options);
    this.getEvents(options);
  }

  onEventChange = (item, index, event) => {
    // var id = event.nativeEvent.target.selectedIndex;
    console.log(event.target.value);
    let variants = Immutable.List(this.state.variants);
    let mutated = variants.set(index, { _event: event.target.value, price: item.price});
    this.setState( { variants: mutated.toArray() } );
  }

  onPriceChange = (item, index, event) => {
    let variants = Immutable.List(this.state.variants);
    let mutated = variants.set(index, { _event: item._event, price: event.target.value});
    this.setState( { variants: mutated.toArray() } );
  }

  closeSetup(){
    this.setState({
     confirm: false
   });
    this.context.router.push('/tables');
  }

  addVariant() { // will create then get?
    var newArray = this.state.variants.slice();
    newArray.push({
        _event: '', // default value
        price: 0 // default value
      });
    this.setState({variants:newArray})
  }

  removeVariant(index, event){ // delete variant ID
    let variants = Immutable.List(this.state.variants);
    let mutated = variants.remove(index);
    console.log(mutated.toArray());
  }

  onTypeChange = (event) => {
    var id = event.target.value;

    this.setState({tableTypeId: id});
    //this.setState
  }

  setName = (event) => {
    this.setState({name: event.target.value});
  }

  getTypeOptions = () => {
    return this.state.tableTypes.map((value, index) => {
      return <option key={index} value={value._id}>{value.name}</option>;
    });
  }

  getTableVariants(){
    return this.state.variants.map( (item, index) => {
      return

                <FormField label="Event" htmlFor="tableName">
                  <select id="tableVenue" onChange={this.onEventChange.bind(this, item, index)} value={item._event}>
                  {
                    this.state.events.map(function(value, index) {
                      return (<option key={index} value={value._event}>{value.name}</option>)
                    })
                  }
                  </select>
                </FormField>
                <FormField label="Price(Php)" htmlFor="tablePrice">
                  <input type="number" onChange={this.onPriceChange.bind(this, item, index)} value={item.price}/>
                </FormField>

                   <Heading align="center">
                    <Button className={styles.eventButton} label="Update" primary={true} onClick={() => {}} />
                    <Button className={styles.eventButton} label="Remove" onClick={this.removeVariant.bind(this, index)} />
                   </Heading>

;
    });
  }

  onDrop(file) {
    this.setState({
       image: file[0],
       isNewImage: true
     });
  }
  onRemoveImage() {
    this.setState({
      image: this.state.prevImage,
      isNewImage: false
    });
  }

  handleImageUpload(file, callback) {
    if(this.state.isNewImage) {
      let options = {
        url: CLOUDINARY_UPLOAD_URL,
        formData: {
          file: file
        }
      };
      let upload = request.post(CLOUDINARY_UPLOAD_URL)
      .field('upload_preset', CLOUDINARY_UPLOAD_PRESET)
      .field('file', file);

      upload.end((err, response) => {
        if (err) {
          console.error(err);
        }

        if (response.body.secure_url !== '') {
          callback(null, response.body.secure_url)
        } else {
          callback(err, '');
        }
      });
    } else {
      callback(null, null);
    }
  }

  submitDelete (event) {
    event.preventDefault();
    let delParams = {
      organisationId: this.state.organisationId,
      productId: this.state.tableId
    };
    PartyBot.products.deleteProduct(delParams, (error, response, body) => {
      if(!error && response.statusCode == 200) {
        this.setState({
          confirm: true
        });
      } else {

      }
    });
  }

  submitSave() {
    event.preventDefault();
    this.handleImageUpload(this.state.image, (err, imageLink) => {
      if(err) {
        console.log(err);
      } else {
        let updateParams = {
          name: this.state.name,
          organisationId: this.state.organisationId,
          productId: this.state.tableId,
          // venueId: this.state.venueId,
          // tags: this.state.tags,
          // table_type: this.state.tableTypeId,
          image: imageLink || this.state.prevImage.preview
        };

        PartyBot.products.update(updateParams, (errors, response, body) => {
          if(response.statusCode == 200) {
            this.setState({
              confirm: true
            });
          }
        });
      }
    });
  }

  submitCreate = () => {
    event.preventDefault();
    this.handleImageUpload(this.state.image, (err, imageLink) => {
      if(err) {
        console.log(err);
      } else {
        let createParams = {
          name: this.state.name,
          organisationId: this.state.organisationId,
          venueId: this.state.venueId,
          tags: this.state.tags,
          table_type: this.state.tableTypeId,
          image: imageLink,
          prices: this.state.variants
        };
        // console.log(createParams);
        PartyBot.products.create(createParams, (errors, response, body) => {
          console.log(errors);
          console.log(response.statusCode);
          console.log(body);
          if(response.statusCode == 200) {
            // this.setState({
            //   confirm: true
            // });
          }
        });
      }
    });
  }

  render() {
    const {
      router,
    } = this.context;
    const {
      isMobile,
    } = this.state;
    const {
      files,
      variants,
    } = this.state;
    return (

      {this.state.confirm !== false ?
      <Layer align="center">

            Table successfully created.

          <Button label="Close" onClick={this.closeSetup} plain={true} icon={<CloseIcon />}/>

      </Layer>
      :
      null
      }
      <Box>
        {this.state.tableId !== null ?
    	<Heading align="center">
            Edit Table
        </Heading>
        :
    	<Heading align="center">
            Add Table
        </Heading>
    	}
          </Box>
			<Box direction="row" justify="center" align="center" wrap={true} margin="small">
				<Form>
				<FormFields>
					<fieldset>
					  <FormField label="Venue" htmlFor="tableVenue">
					    <select id="tableVenue" onChange={this.onVenueChange} value={this.state.venueId}>
              {this.state.venues.map((value, index) => {
                return <option key={index} value={value._id}>{value.name}</option>;
              })}
						  </select>
					  </FormField>
					  <FormField label="Table Type" htmlFor="tableType">
					    <select id="tableType" onChange={this.onTypeChange} value={this.state.tableTypeId}>
              {this.state.tableTypes.map((value, index) => {
                return <option key={index} value={value._id}>{value.name}</option>;
              })}
						  </select>
					  </FormField>
					  <FormField label=" Name" htmlFor="tableName">
					    <input id="tableName" type="text" onChange={this.setName} value={this.state.name}/>
					  </FormField>
          <FormField label="Image">
          {this.state.image ?
            <Box align="center" justify="center">

              <Box>
                <Button label="Cancel" onClick={this.onRemoveImage.bind(this)} plain={true} icon={<CloseIcon />}/>
              </Box>
            </Box> :
            <Box align="center" justify="center">
              <Dropzone multiple={false} ref={(node) => { this.dropzone = node; }} onDrop={this.onDrop} accept='image/*'>
                Drop image here or click to select image to upload.
              </Dropzone>
            </Box>
          }
           </FormField>
           </fieldset>
           </FormFields>

            <Box>
            Pricing:
            </Box>
            <Button label="Add Event" primary={true} onClick={this.addVariant} />

            {
            //Dynamic Price/Event Component
            this.getTableVariants()
            }

            {
              this.state.tableId !== null ?
              <Heading align="center">
                <Button label="Save Changes" primary={true} onClick={this.submitSave} />
                <Button label="Delete" primary={true} onClick={this.submitDelete} />
              </Heading>
              :
              <Heading align="center">
                <Button label="Create Table" primary={true} onClick={this.submitCreate} />
              </Heading>
            }

            </Form>
            </Box>

            );
  }
}

ManageTablesPage.contextTypes = {
  router: PropTypes.object.isRequired,
};

export default cssModules(ManageTablesPage, styles);
<commit_msg>Updating Prices<commit_after>import PartyBot from 'partybot-http-client';
import React, { PropTypes, Component } from 'react';
import cssModules from 'react-css-modules';
import styles from './index.module.scss';
import Heading from 'grommet/components/Heading';
import Box from 'grommet/components/Box';
import Footer from 'grommet/components/Footer';
import Button from 'grommet/components/Button';
import Form from 'grommet/components/Form';
import FormField from 'grommet/components/FormField';
import FormFields from 'grommet/components/FormFields';
import NumberInput from 'grommet/components/NumberInput';
import CloseIcon from 'grommet/components/icons/base/Close';
import Dropzone from 'react-dropzone';
import Layer from 'grommet/components/Layer';
import Header from 'grommet/components/Header';
import Section from 'grommet/components/Section';
import Paragraph from 'grommet/components/Paragraph';
import request from 'superagent';
import { CLOUDINARY_UPLOAD_PRESET, CLOUDINARY_NAME, CLOUDINARY_KEY, CLOUDINARY_SECRET, CLOUDINARY_UPLOAD_URL } from '../../constants';
import Immutable from 'immutable';
class ManageTablesPage extends Component {
  constructor(props) {
    super(props);
    this.handleMobile = this.handleMobile.bind(this);
    this.getTableVariants = this.getTableVariants.bind(this);
    this.closeSetup = this.closeSetup.bind(this);
    this.onDrop = this.onDrop.bind(this);
    this.addVariant = this.addVariant.bind(this);
    this.submitSave = this.submitSave.bind(this);
    this.submitDelete = this.submitDelete.bind(this);
    this.state = {
      isMobile: false,
      tableId: props.params.table_id || null,
      confirm: false,
      name: '',
      variants: [],
      organisationId: '5800471acb97300011c68cf7',
      venues: [],
      venueId: '',
      events: [],
      eventId: '',
      tableTypes: [],
      tableTypeId: undefined,
      tags: 'table',
      image: null,
      prevImage: null,
      isNewImage: null,
      prices: []
    };
  }

  componentWillMount() {
    if (this.state.tableId) {
      this.setState({variants: []});
    }
  }

  componentDidMount() {
    if (typeof window !== 'undefined') {
      window.addEventListener('resize', this.handleMobile);
    }

    let options = {
      organisationId: this.state.organisationId
    };
    this.getVenues(options);
    // IF TABLE ID EXISTS
    if(this.props.params.table_id) {
      let tOptions = {
        organisationId: this.state.organisationId,
        productId: this.props.params.table_id
      }
      this.getTable(tOptions);
    }
  }
  componentWillUnmount() {
    if (typeof window !== 'undefined') {
      window.removeEventListener('resize', this.handleMobile);
    }
  }
  handleMobile() {
    const isMobile = window.innerWidth <= 768;
    this.setState({
      isMobile,
    });
  };

  getVenues = (options) => {
    PartyBot.venues.getAllInOrganisation(options, (errors, response, body) => {
      if(response.statusCode == 200) {
        if(body.length > 0) {
          this.setState({venueId: body[0]._id});
          let ttOptions = {
            organisationId: this.state.organisationId,
            venue_id: this.state.venueId
          }
          this.getEvents(ttOptions);
          this.getTableTypes(ttOptions);
        }
        this.setState({venues: body, events: []});
      }
    });
  }

  getEvents = (options) => {
    PartyBot.events.getEventsInOrganisation(options, (err, response, body) => {
      if(!err && response.statusCode == 200) {
        if(body.length > 0) {
          this.setState({eventId: body[0]._id});
        }
        body.map((value, index) =>{
          this.setState({events: this.state.events.concat({ _event: value._id, name: value.name, selected: false })});
        });
      }
    });
  }

  getTableTypes = (options) => {
    PartyBot.tableTypes.getTableTypesInOrganisation(options, (errors, response, body) => {
      if(response.statusCode == 200) {
        if(body.length > 0) {
          this.setState({tableTypeId: body[0]._id});
        }
        this.setState({tableTypes: body});
      }
    });
  }

  getTable = (options) => {
    PartyBot.products.getProductsInOrganisation(options, (error, response, body) => {
      if(response.statusCode == 200) {
        this.setState({
          name: body.name,
          image: {
            preview: body.image
          },
          prevImage: {
            preview: body.image
          },
          variants: body.prices.map((value, index) => {
            return {  _event: value._event, price: value.price }
          })
        });

      }
    });
  }

  onVenueChange = (event) => {
    let id = event.target.value;
    this.setState({ venueId: id, events: [], variants: []});
    let options = {
      organisationId: this.state.organisationId,
      venue_id: id
    };
    this.getTableTypes(options);
    this.getEvents(options);
  }

  onEventChange = (item, index, event) => {
    // var id = event.nativeEvent.target.selectedIndex;
    console.log(event.target.value);
    let variants = Immutable.List(this.state.variants);
    let mutated = variants.set(index, { _event: event.target.value, price: item.price});
    this.setState( { variants: mutated.toArray() } );
  }

  onPriceChange = (item, index, event) => {
    let variants = Immutable.List(this.state.variants);
    let mutated = variants.set(index, { _event: item._event, price: event.target.value});
    this.setState( { variants: mutated.toArray() } );
  }

  closeSetup(){
    this.setState({
     confirm: false
   });
    this.context.router.push('/tables');
  }

  addVariant() { // will create then get?
    var newArray = this.state.variants.slice();
    newArray.push({
        _event: '', // default value
        price: 0 // default value
      });
    this.setState({variants:newArray})
  }

  removeVariant(index, event){ // delete variant ID
    let variants = Immutable.List(this.state.variants);
    let mutated = variants.remove(index);
    console.log(mutated.toArray());
  }

  onTypeChange = (event) => {
    var id = event.target.value;

    this.setState({tableTypeId: id});
    //this.setState
  }

  setName = (event) => {
    this.setState({name: event.target.value});
  }

  getTypeOptions = () => {
    return this.state.tableTypes.map((value, index) => {
      return <option key={index} value={value._id}>{value.name}</option>;
    });
  }

  getTableVariants(){
    return this.state.variants.map( (item, index) => {
      return

                <FormField label="Event" htmlFor="tableName">
                  <select id="tableVenue" onChange={this.onEventChange.bind(this, item, index)} value={item._event}>
                  {
                    this.state.events.map(function(value, index) {
                      return (<option key={index} value={value._event}>{value.name}</option>)
                    })
                  }
                  </select>
                </FormField>
                <FormField label="Price(Php)" htmlFor="tablePrice">
                  <input type="number" onChange={this.onPriceChange.bind(this, item, index)} value={item.price}/>
                </FormField>

                   <Heading align="center">
                    <Button className={styles.eventButton} label="Update" primary={true} onClick={() => {}} />
                    <Button className={styles.eventButton} label="Remove" onClick={this.removeVariant.bind(this, index)} />
                   </Heading>

;
    });
  }

  onDrop(file) {
    this.setState({
       image: file[0],
       isNewImage: true
     });
  }
  onRemoveImage = () => {
    this.setState({
      image: null,
      isNewImage: false
    });
  }

  handleImageUpload(file, callback) {
    if(this.state.isNewImage) {
      let options = {
        url: CLOUDINARY_UPLOAD_URL,
        formData: {
          file: file
        }
      };
      let upload = request.post(CLOUDINARY_UPLOAD_URL)
      .field('upload_preset', CLOUDINARY_UPLOAD_PRESET)
      .field('file', file);

      upload.end((err, response) => {
        if (err) {
          console.error(err);
        }

        if (response.body.secure_url !== '') {
          callback(null, response.body.secure_url)
        } else {
          callback(err, '');
        }
      });
    } else {
      callback(null, null);
    }
  }

  submitDelete (event) {
    event.preventDefault();
    let delParams = {
      organisationId: this.state.organisationId,
      productId: this.state.tableId
    };
    PartyBot.products.deleteProduct(delParams, (error, response, body) => {
      if(!error && response.statusCode == 200) {
        this.setState({
          confirm: true
        });
      } else {

      }
    });
  }

  submitSave() {
    console.log("Sending Save");
    event.preventDefault();
    this.handleImageUpload(this.state.image, (err, imageLink) => {
      if(err) {
        console.log(err);
      } else {
        let updateParams = {
          name: this.state.name,
          organisationId: this.state.organisationId,
          productId: this.state.tableId,
          venueId: this.state.venueId,
          table_type: this.state.tableTypeId,
          image: imageLink || this.state.prevImage.preview,
          prices: this.state.variants

        };
        PartyBot.products.update(updateParams, (errors, response, body) => {
          if(response.statusCode == 200) {
            this.setState({
              confirm: true
            });
          }
        });
      }
    });
  }

  submitCreate = () => {
    event.preventDefault();
    this.handleImageUpload(this.state.image, (err, imageLink) => {
      if(err) {
        console.log(err);
      } else {
        let createParams = {
          name: this.state.name,
          organisationId: this.state.organisationId,
          venueId: this.state.venueId,
          tags: this.state.tags,
          table_type: this.state.tableTypeId,
          image: imageLink,
          prices: this.state.variants
        };
        // console.log(createParams);
        PartyBot.products.create(createParams, (errors, response, body) => {
          console.log(errors);
          console.log(response.statusCode);
          console.log(body);
          if(response.statusCode == 200) {
            // this.setState({
            //   confirm: true
            // });
          }
        });
      }
    });
  }

  render() {
    const {
      router,
    } = this.context;
    const {
      isMobile,
    } = this.state;
    const {
      files,
      variants,
    } = this.state;
    return (

      {this.state.confirm !== false ?
      <Layer align="center">

            Table successfully created.

          <Button label="Close" onClick={this.closeSetup} plain={true} icon={<CloseIcon />}/>

      </Layer>
      :
      null
      }
      <Box>
        {this.state.tableId !== null ?
    	<Heading align="center">
            Edit Table
        </Heading>
        :
    	<Heading align="center">
            Add Table
        </Heading>
    	}
          </Box>
			<Box direction="row" justify="center" align="center" wrap={true} margin="small">
				<Form>
				<FormFields>
					<fieldset>
					  <FormField label="Venue" htmlFor="tableVenue">
					    <select id="tableVenue" onChange={this.onVenueChange} value={this.state.venueId}>
              {this.state.venues.map((value, index) => {
                return <option key={index} value={value._id}>{value.name}</option>;
              })}
						  </select>
					  </FormField>
					  <FormField label="Table Type" htmlFor="tableType">
					    <select id="tableType" onChange={this.onTypeChange} value={this.state.tableTypeId}>
              {this.state.tableTypes.map((value, index) => {
                return <option key={index} value={value._id}>{value.name}</option>;
              })}
						  </select>
					  </FormField>
					  <FormField label=" Name" htmlFor="tableName">
					    <input id="tableName" type="text" onChange={this.setName} value={this.state.name}/>
					  </FormField>
          <FormField label="Image">
          {this.state.image ?
            <Box align="center" justify="center">

              <Box>
                <Button label="Cancel" onClick={this.onRemoveImage.bind(this)} plain={true} icon={<CloseIcon />}/>
              </Box>
            </Box> :
            <Box align="center" justify="center">
              <Dropzone multiple={false} ref={(node) => { this.dropzone = node; }} onDrop={this.onDrop} accept='image/*'>
                Drop image here or click to select image to upload.
              </Dropzone>
            </Box>
          }
           </FormField>
           </fieldset>
           </FormFields>

            <Box>
            Pricing:
            </Box>
            <Button label="Add Event" primary={true} onClick={this.addVariant} />

            {
            //Dynamic Price/Event Component
            this.getTableVariants()
            }

            {
              this.state.tableId !== null ?
              <Heading align="center">
                <Button label="Save Changes" primary={true} onClick={this.submitSave} />
                <Button label="Delete" primary={true} onClick={this.submitDelete} />
              </Heading>
              :
              <Heading align="center">
                <Button label="Create Table" primary={true} onClick={this.submitCreate} />
              </Heading>
            }

            </Form>
            </Box>

            );
  }
}

ManageTablesPage.contextTypes = {
  router: PropTypes.object.isRequired,
};

export default cssModules(ManageTablesPage, styles);
<|endoftext|>


<commit_before>import { Map } from 'immutable';

const getStockObj = (stocks) =>
  stocks.reduce((acc, stock) =>
    acc.set(stock.get('productCode'), stock.get('storeStock')),
    Map());

export default function normalizeRealTimeData(data) {
  return data.reduce((acc, store) =>
    acc.set(store.get('storeCode'), getStockObj(store.get('stock'))),
    Map()
  );
}
<commit_msg>new end point stock label<commit_after>import { Map } from 'immutable';

const getStockObj = (stocks) =>
  stocks.reduce((acc, stock) =>
    acc.set(stock.get('productCode'), stock.get('digitalStock')),
    Map());

export default function normalizeRealTimeData(data) {
  return data.reduce((acc, store) =>
    acc.set(store.get('storeCode'), getStockObj(store.get('stock'))),
    Map()
  );
}
<|endoftext|>


<commit_before>/*
 * Package: linker.js
 *
 * Namespace: amigo.linker
 *
 * Generic AmiGO link generator, fed by <amigo.data.server> for local
 * links and <amigo.data.xrefs> for non-local links.
 *
 * TODO: maybe this should actually be under bbop.html so we could
 * make use of the anchor tag stuff?
 *
 * NOTE: A lot of this is lifted from the (defunct) amigo.js
 * package. However, the future should be here.
 *
 * NOTE: This should pull data from something like amigo.data.xrefs
 * instead.
 */

// Setup the internal requirements.
bbop.core.require('bbop', 'core');
//bbop.core.require('amigo', 'data', 'server');
//bbop.core.require('amigo', 'data', 'xrefs');
bbop.core.namespace('amigo', 'linker');

/*
 * Constructor: linker
 *
 * Create an object that can make URLs and/or anchors.
 *
 * These functions have a well defined interface so that other
 * packages can use it.
 *
 * Arguments:
 *  n/a
 *
 * Returns:
 *  self
 */
amigo.linker = function (){
    this._is_a = 'amigo.linker';

    // With the new dispatcher, relative URLs no longer work, so we
    // have to bring in server data--first let's ensure it.
    if( ! amigo.data.server ){
	throw new Error('we are missing access to amigo.data.server!');
    }
    var sd = new amigo.data.server();
    this.app_base = sd.app_base();

    // Categories for different special cases (internal links).
    this.ont_category = {
	'term': true,
	'ontology_class': true,
	'annotation_class': true,
	'annotation_class_closure': true,
	'annotation_class_list': true
    };
    this.bio_category = {
        'gp': true,
	'gene_product': true,
	'bioentity': true
    };
    this.search_category = {
        'search': true,
	'live_search': true
    };
};

/*
 * Function: url
 *
 * Return a url string.
 *
 * Arguments:
 *  args - id
 *  xid - *[optional]* an internal transformation id
 *
 * Returns:
 *  string (url); null if it couldn't create anything
 */
amigo.linker.prototype.url = function (id, xid){

    var retval = null;

    // AmiGO hard-coded link types.
    if( xid ){
	if( this.ont_category[xid] ){
	    //retval = 'amigo?mode=term&term=' + id;
	    retval = this.app_base + '/amigo/term/' + id;
        }else if( this.bio_category[xid] ){
	    //retval = 'amigo?mode=gene_product&gp=' + id;
	    retval = this.app_base + '/amigo/gene_product/' + id;
        }else if( this.search_category[xid] ){
	    if( id ){
		//retval = 'amigo?mode=search&bookmark=' + id;
		retval = this.app_base +'/amigo/search?bookmark='+ id;
	    }else{
		//retval = 'amigo?mode=search';
		retval = this.app_base + '/amigo/search';
	    }
	}
    }

    // Since we couldn't find anything with our explicit
    // transformation set, drop into the great abyss of the xref data.
    if( ! retval){
	if( ! amigo.data.xrefs ){
	    throw new Error('amigo.data.xrefs is missing!');
	}

	// First, extract the probable source and break it into parts.
	var full_id_parts = bbop.core.first_split(':', id);
	if( full_id_parts && full_id_parts[0] && full_id_parts[1] ){
	    var src = full_id_parts[0];
	    var sid = full_id_parts[1];

	    // Now, check to see if it is indeed in our store.
	    var lc_src = src.toLowerCase();
	    var xref = amigo.data.xrefs[lc_src];
	    if( xref && xref['url_syntax'] ){
		retval = xref['url_syntax'].replace('[example_id]', sid, 'g');
	    }
	}
    }

    return retval;
};

/*
 * Function: anchor
 *
 * Return a link as a chunk of HTML, all ready to consume in a
 * display.
 *
 * Arguments:
 *  args - hash--'id' required; 'label' and 'hilite' are inferred if not extant
 *  xid - *[optional]* an internal transformation id
 *
 * Returns:
 *  string (link); null if it couldn't create anything
 */
amigo.linker.prototype.anchor = function(args, xid){

    var anchor = this;
    var retval = null;

    // Get what fundamental arguments we can.
    var id = args['id'];
    if( ! id ){
	throw new Error('"id" is a required argument');
    }

    // Infer label from id if not present.
    var label = args['label'];
    if( ! label ){ label = id; }

    // Infer label from id if not present.
    var hilite = args['hilite'];
    if( ! hilite ){ hilite = label; }

    // See if the URL is legit. If it is, make something for it.
    var url = this.url(id, xid);
    if( url ){

	// First, see if it is one of the internal ones we know about
	// and make something special for it.
	if( xid ){
	    if( this.ont_category[xid] ){
		retval = '' + hilite + '';
            }else if( this.bio_category[xid] ){
		retval = '' + hilite + '';
            }else if( this.search_category[xid] ){
		retval = '' + hilite + '';
	    }
	}

	// If it wasn't in the special transformations, just make
	// something generic.
	if( ! retval ){
	    retval = '' + hilite + '';
	}
    }

    return retval;
};
<commit_msg>better tooltip<commit_after>/*
 * Package: linker.js
 *
 * Namespace: amigo.linker
 *
 * Generic AmiGO link generator, fed by <amigo.data.server> for local
 * links and <amigo.data.xrefs> for non-local links.
 *
 * TODO: maybe this should actually be under bbop.html so we could
 * make use of the anchor tag stuff?
 *
 * NOTE: A lot of this is lifted from the (defunct) amigo.js
 * package. However, the future should be here.
 *
 * NOTE: This should pull data from something like amigo.data.xrefs
 * instead.
 */

// Setup the internal requirements.
bbop.core.require('bbop', 'core');
//bbop.core.require('amigo', 'data', 'server');
//bbop.core.require('amigo', 'data', 'xrefs');
bbop.core.namespace('amigo', 'linker');

/*
 * Constructor: linker
 *
 * Create an object that can make URLs and/or anchors.
 *
 * These functions have a well defined interface so that other
 * packages can use it.
 *
 * Arguments:
 *  n/a
 *
 * Returns:
 *  self
 */
amigo.linker = function (){
    this._is_a = 'amigo.linker';

    // With the new dispatcher, relative URLs no longer work, so we
    // have to bring in server data--first let's ensure it.
    if( ! amigo.data.server ){
	throw new Error('we are missing access to amigo.data.server!');
    }
    var sd = new amigo.data.server();
    this.app_base = sd.app_base();

    // Categories for different special cases (internal links).
    this.ont_category = {
	'term': true,
	'ontology_class': true,
	'annotation_class': true,
	'annotation_class_closure': true,
	'annotation_class_list': true
    };
    this.bio_category = {
        'gp': true,
	'gene_product': true,
	'bioentity': true
    };
    this.search_category = {
        'search': true,
	'live_search': true
    };
};

/*
 * Function: url
 *
 * Return a url string.
 *
 * Arguments:
 *  args - id
 *  xid - *[optional]* an internal transformation id
 *
 * Returns:
 *  string (url); null if it couldn't create anything
 */
amigo.linker.prototype.url = function (id, xid){

    var retval = null;

    // AmiGO hard-coded link types.
    if( xid ){
	if( this.ont_category[xid] ){
	    //retval = 'amigo?mode=term&term=' + id;
	    retval = this.app_base + '/amigo/term/' + id;
        }else if( this.bio_category[xid] ){
	    //retval = 'amigo?mode=gene_product&gp=' + id;
	    retval = this.app_base + '/amigo/gene_product/' + id;
        }else if( this.search_category[xid] ){
	    if( id ){
		//retval = 'amigo?mode=search&bookmark=' + id;
		retval = this.app_base +'/amigo/search?bookmark='+ id;
	    }else{
		//retval = 'amigo?mode=search';
		retval = this.app_base + '/amigo/search';
	    }
	}
    }

    // Since we couldn't find anything with our explicit
    // transformation set, drop into the great abyss of the xref data.
    if( ! retval){
	if( ! amigo.data.xrefs ){
	    throw new Error('amigo.data.xrefs is missing!');
	}

	// First, extract the probable source and break it into parts.
	var full_id_parts = bbop.core.first_split(':', id);
	if( full_id_parts && full_id_parts[0] && full_id_parts[1] ){
	    var src = full_id_parts[0];
	    var sid = full_id_parts[1];

	    // Now, check to see if it is indeed in our store.
	    var lc_src = src.toLowerCase();
	    var xref = amigo.data.xrefs[lc_src];
	    if( xref && xref['url_syntax'] ){
		retval = xref['url_syntax'].replace('[example_id]', sid, 'g');
	    }
	}
    }

    return retval;
};

/*
 * Function: anchor
 *
 * Return a link as a chunk of HTML, all ready to consume in a
 * display.
 *
 * Arguments:
 *  args - hash--'id' required; 'label' and 'hilite' are inferred if not extant
 *  xid - *[optional]* an internal transformation id
 *
 * Returns:
 *  string (link); null if it couldn't create anything
 */
amigo.linker.prototype.anchor = function(args, xid){

    var anchor = this;
    var retval = null;

    // Get what fundamental arguments we can.
    var id = args['id'];
    if( ! id ){
	throw new Error('"id" is a required argument');
    }

    // Infer label from id if not present.
    var label = args['label'];
    if( ! label ){ label = id; }

    // Infer label from id if not present.
    var hilite = args['hilite'];
    if( ! hilite ){ hilite = label; }

    // See if the URL is legit. If it is, make something for it.
    var url = this.url(id, xid);
    if( url ){

	// First, see if it is one of the internal ones we know about
	// and make something special for it.
	if( xid ){
	    if( this.ont_category[xid] ){
		//retval = '<a title="Go to the term details page for ' +
 		retval = '' + hilite + '';
            }else if( this.bio_category[xid] ){
 		retval = '' + hilite + '';
            }else if( this.search_category[xid] ){
		retval = '' + hilite + '';
	    }
	}

	// If it wasn't in the special transformations, just make
	// something generic.
	if( ! retval ){
	    retval = '' + hilite + '';
	}
    }

    return retval;
};
<|endoftext|>


<commit_before>import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import  { Breakpoint, BreakpointProvider } from 'react-socks';
import './App.css';
import AddWordsPage from './addWords/AddWordsPage';
import { TranslationsPageWithRouter } from './translations/TranslationsPage';
import ContributionsPage from './contributions/ContributionsPage';
import ThemePage from './theme/ThemePage';
import AuthUtils from './utils/AuthUtils';
import SharingPage from './sharing/SharingPage';
import ManagementPage from './management/ManagementPage';
import Header from './header/Header';
import NavMenu from './navmenu/NavMenu';

const ROUTES = {
  ADD_WORDS: '/add-words',
  TRANSLATIONS: '/',
  CONTRIBUTIONS: '/user-contributions',
  THEME: '/theme',
  SHARING: '/sharing',
  MANAGEMENT: '/management',
};

const LANDING_IMG = "../logo2200.png";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.authUtils_ = new AuthUtils();

    this.state = {
      email: null,
      authInitializing: true,
    };
  }

  componentDidMount() {
    this.authUtils_.getFirebaseAuth().onAuthStateChanged(async (user) => {
      if (!user) {
        this.setState({email: null, authInitializing: false});
        return;
      }

      const idTokenResult = await user.getIdTokenResult();
      if (idTokenResult.claims.admin || idTokenResult.claims.moderator) {
        AuthUtils.setUser(user);
        this.setState({email: user.email, authInitializing: false});
      } else {
        this.logOut_();
      }
    });
  }

  async logIn_() {
    try {
      await this.authUtils_.signInWithPopup();
    } catch(err) {
      console.error(err);
    }
  }

  async logOut_() {
    try {
      await AuthUtils.signOut();
    } catch(err) {
      console.error(err);
    }
  }

  async authAction_() {
    if (this.state.email) {
      this.logOut_();
    } else {
      this.logIn_();
    }
  }

  renderBody() {
    if (this.state.authInitializing) {
      return null;
    } else if (!this.state.email) {
      return (

      );
    }

    return (

        {/* Only renders the permanent side menu in desktop widths. */}
        <Breakpoint large up>
          {!!this.state.email ? <NavMenu /> : null}
        </Breakpoint>

          <Route path={ROUTES.ADD_WORDS} component={AddWordsPage} />
          <Route exact path={[ROUTES.TRANSLATIONS, "/translations/:pageNum"]} component={TranslationsPageWithRouter} />
          <Route path={ROUTES.CONTRIBUTIONS} component={ContributionsPage} />
          <Route path={ROUTES.THEME} component={ThemePage} />
          <Route path={ROUTES.SHARING} component={SharingPage} />
          <Route path={ROUTES.MANAGEMENT} component={ManagementPage} />

    );
  }

  render() {
    return (
      <Router>
        <BreakpointProvider>

             this.authAction_()}
            />
            {this.renderBody()}

        </BreakpointProvider>
      </Router>
    );
  }
}

export {
  App,
  ROUTES
};
<commit_msg>Use woolaroo logo from static storage<commit_after>import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import  { Breakpoint, BreakpointProvider } from 'react-socks';
import './App.css';
import AddWordsPage from './addWords/AddWordsPage';
import { TranslationsPageWithRouter } from './translations/TranslationsPage';
import ContributionsPage from './contributions/ContributionsPage';
import ThemePage from './theme/ThemePage';
import AuthUtils from './utils/AuthUtils';
import SharingPage from './sharing/SharingPage';
import ManagementPage from './management/ManagementPage';
import Header from './header/Header';
import NavMenu from './navmenu/NavMenu';

const ROUTES = {
  ADD_WORDS: '/add-words',
  TRANSLATIONS: '/',
  CONTRIBUTIONS: '/user-contributions',
  THEME: '/theme',
  SHARING: '/sharing',
  MANAGEMENT: '/management',
};

const LANDING_IMG = "https://storage.googleapis.com/barnard-public-assets/woolaroo_logo.png";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.authUtils_ = new AuthUtils();

    this.state = {
      email: null,
      authInitializing: true,
    };
  }

  componentDidMount() {
    this.authUtils_.getFirebaseAuth().onAuthStateChanged(async (user) => {
      if (!user) {
        this.setState({email: null, authInitializing: false});
        return;
      }

      const idTokenResult = await user.getIdTokenResult();
      if (idTokenResult.claims.admin || idTokenResult.claims.moderator) {
        AuthUtils.setUser(user);
        this.setState({email: user.email, authInitializing: false});
      } else {
        this.logOut_();
      }
    });
  }

  async logIn_() {
    try {
      await this.authUtils_.signInWithPopup();
    } catch(err) {
      console.error(err);
    }
  }

  async logOut_() {
    try {
      await AuthUtils.signOut();
    } catch(err) {
      console.error(err);
    }
  }

  async authAction_() {
    if (this.state.email) {
      this.logOut_();
    } else {
      this.logIn_();
    }
  }

  renderBody() {
    if (this.state.authInitializing) {
      return null;
    } else if (!this.state.email) {
      return (

      );
    }

    return (

        {/* Only renders the permanent side menu in desktop widths. */}
        <Breakpoint large up>
          {!!this.state.email ? <NavMenu /> : null}
        </Breakpoint>

          <Route path={ROUTES.ADD_WORDS} component={AddWordsPage} />
          <Route exact path={[ROUTES.TRANSLATIONS, "/translations/:pageNum"]} component={TranslationsPageWithRouter} />
          <Route path={ROUTES.CONTRIBUTIONS} component={ContributionsPage} />
          <Route path={ROUTES.THEME} component={ThemePage} />
          <Route path={ROUTES.SHARING} component={SharingPage} />
          <Route path={ROUTES.MANAGEMENT} component={ManagementPage} />

    );
  }

  render() {
    return (
      <Router>
        <BreakpointProvider>

             this.authAction_()}
            />
            {this.renderBody()}

        </BreakpointProvider>
      </Router>
    );
  }
}

export {
  App,
  ROUTES
};
<|endoftext|>


<commit_before>/**
 * Created by ryancornillie on 1/21/17.
 */

angular.module('myApp.officeService', ['ngWebSocket'])

    .factory("OfficeService", function ($http, $q, API, $websocket) {

        var service = {};

        service.dataLoaded = false;

        var dataStream = $websocket('ws://localhost:3333/test');

        service.getOffices = function () {
            var deferred = $q.defer();

            $http.get(API + '/offices').then(function success(response) {

                console.log(response);

                service.offices = response.data;

                service.dataLoaded = true;

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;
        };

        service.createOffice = function (office) {
            var deferred = $q.defer();

            $http.post(API + '/offices', office).then(function success(response) {

                console.log(response);

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;
        };

        service.createSession = function (session) {

            var deferred = $q.defer();

            console.log(session);

            $http.post(API + '/sessions', session).then(function success(response) {

                console.log(response);

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;
        };

        service.deleteOffice = function (id) {

            var deferred = $q.defer();

            var data = {
                officeId: id
            };

            console.log(data);

            $http.delete(API + '/offices/' + id, data).then(function success(response) {

                console.log(response);

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;
        };

        service.activateOffice = function (office) {

            var deferred = $q.defer();

            var data = {
                officeId: office._id,
                active: office.active
            };

            console.log("activate", data);

            $http.patch(API + '/offices/active', data).then(function success(response) {

                console.log(response);

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;

        };

        dataStream.onMessage(function (message) {
            console.dir(message);
            if (service.dataLoaded) {
                var data = JSON.parse(message);
                data.forEach(function (elm) {
                    service.offices.forEach(function (office) {
                        if (elm.officeId == office._id) {
                            office.queue.push(elm);
                        }
                    });
                });
            }
        });

        service.selectedOffice = null;

        service.adding = 0;

        service.offices = [];

        return service;
    });<commit_msg>web sokets<commit_after>/**
 * Created by ryancornillie on 1/21/17.
 */

angular.module('myApp.officeService', ['ngWebSocket'])

    .factory("OfficeService", function ($http, $q, API, $websocket) {

        var service = {};

        service.dataLoaded = false;

        var dataStream = $websocket('ws://localhost:3333/test');

        service.getOffices = function () {
            var deferred = $q.defer();

            $http.get(API + '/offices').then(function success(response) {

                console.log(response);

                service.offices = response.data;

                service.dataLoaded = true;

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;
        };

        service.createOffice = function (office) {
            var deferred = $q.defer();

            $http.post(API + '/offices', office).then(function success(response) {

                console.log(response);

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;
        };

        service.createSession = function (session) {

            var deferred = $q.defer();

            console.log(session);

            $http.post(API + '/sessions', session).then(function success(response) {

                console.log(response);

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;
        };

        service.deleteOffice = function (id) {

            var deferred = $q.defer();

            var data = {
                officeId: id
            };

            console.log(data);

            $http.delete(API + '/offices/' + id, data).then(function success(response) {

                console.log(response);

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;
        };

        service.activateOffice = function (office) {

            var deferred = $q.defer();

            var data = {
                officeId: office._id,
                active: office.active
            };

            console.log("activate", data);

            $http.patch(API + '/offices/active', data).then(function success(response) {

                console.log(response);

                deferred.resolve(response.data);

            }, function error(error) {
                deferred.reject(error);
            });

            return deferred.promise;

        };

        dataStream.onMessage(function (message) {
            console.dir(message);
            if (service.dataLoaded) {
                var elm = JSON.parse(message.data);

                service.offices.forEach(function (office) {
                    if (elm.officeId == office._id) {
                        if (elm.delete) {
                            // take out of queue
                            var index = 0;
                            while (office.queue[index]._id != elm._id) {
                                index++;
                            }
                            office.queue.splice(index,1);
                        } else {
                            office.queue.push(elm);
                        }
                    }
                });
            }
        });

        service.selectedOffice = null;

        service.adding = 0;

        service.offices = [];

        return service;
    });<|endoftext|>


<commit_before>import * as historyActions from './history';
import * as dialogActions from './dialog';
import * as notificationActions from './notifications';

export default {
  ...historyActions,
  ...dialogActions,
  ...notificationActions
}
<commit_msg>create documents actions<commit_after>import * as historyActions from './history';
import * as dialogActions from './dialog';
import * as notificationActions from './notifications';
import createDocumentsActions from './createDocumentsActions';

export default config => {
  ...createDocumentsActions(config),
  ...historyActions,
  ...dialogActions,
  ...notificationActions
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';

class Header extends Component {
  render() {
    return (

          {this.props.name}

          {this.props.about}
          {this.props.contact}
          {this.props.subscription}

    );
  }
}

class Featured extends Component {
  render() {
    return (

{this.props.duration}

{this.props.title}

{this.props.desc}

          <button id="featured-button">{this.props.button}</button>

    );
  }
}

class PlaylistContainer extends Component {
  render() {
    return (

    );
  }
}

class Playlist extends Component {
  render() {
    return (

{this.props.duration}

{this.props.title}

{this.props.description}

    );
  }
}

export class App extends Component {
  render() {
    const featuredProps = {
      img: "https://pbs.twimg.com/profile_images/378800000822867536/3f5a00acf72df93528b6bb7cd0a4fd0c.jpeg",
      duration: "1h 30m",
      title: "Featured Podcast Playlist Title",
      desc: "Austin viral whatever, mlkshk Odd Future 3 wolf moon squid aesthetic ugh beard butcher. Crucifix master cleanse viral jean shorts Banksy PBR selfies. Dreamcatcher scenester pickled chambray kitsch. Next level distillery you probably haven't heard of them tattooed. IPhone tofu occupy next level.",
      button: "Check it out"
    };
    const playlistProps = {
      img: "http://i3.kym-cdn.com/photos/images/original/000/581/251/5af.jpg",
      duration: "1h 24m",
      title: "Podcast Playlist Title",
      description: "Rub face on owner shove bum in owner's face like camera lens. Why must they do that. Sits on keyboard, spit up on light gray carpet instead of adjacent linoleum destroy couch as revenge for chew iPad power cord chew iPad power cord chase dog then run away. Hide from vacuum cleaner chew on cable, and intently sniff hand, or see owner, run in terror, chase dog then run away for cough furball but hiss at vacuum cleaner."
    }
    return (

        <Featured {...featuredProps} />
        <PlaylistContainer />
        <Playlist {...playlistProps} />

    );
  }
}

<commit_msg>fix playlist component<commit_after>import React, { Component } from 'react';

class Header extends Component {
  render() {
    return (

          {this.props.name}

          {this.props.about}
          {this.props.contact}
          {this.props.subscription}

    );
  }
}

class Featured extends Component {
  render() {
    return (

{this.props.duration}

{this.props.title}

{this.props.desc}

          <button id="featured-button">{this.props.button}</button>

    );
  }
}

class PlaylistContainer extends Component {
  render() {
    // const podcastPlaylists = this.props.data.map(function(data){
    //   return <Playlist {...data} />
    // })
    const podcastPlaylists = this.props.data.map(data =>
      <Playlist {...data} />)
    return (

        {podcastPlaylists}

    );
  }
}

class Playlist extends Component {
  render() {
    return (

{this.props.duration}

{this.props.title}

{this.props.description}

    );
  }
}

export class App extends Component {
  render() {
    const featuredProps = {
      img: "https://pbs.twimg.com/profile_images/378800000822867536/3f5a00acf72df93528b6bb7cd0a4fd0c.jpeg",
      duration: "1h 30m",
      title: "Featured Podcast Playlist Title",
      desc: "Austin viral whatever, mlkshk Odd Future 3 wolf moon squid aesthetic ugh beard butcher. Crucifix master cleanse viral jean shorts Banksy PBR selfies. Dreamcatcher scenester pickled chambray kitsch. Next level distillery you probably haven't heard of them tattooed. IPhone tofu occupy next level.",
      button: "Check it out"
    };
    const playlistProps = [{
      img: "http://i3.kym-cdn.com/photos/images/original/000/581/251/5af.jpg",
      duration: "1h 24m",
      title: "Podcast Playlist Title",
      description: "Rub face on owner shove bum in owner's face like camera lens. Why must they do that. Sits on keyboard, spit up on light gray carpet instead of adjacent linoleum destroy couch as revenge for chew iPad power cord chew iPad power cord chase dog then run away. Hide from vacuum cleaner chew on cable, and intently sniff hand, or see owner, run in terror, chase dog then run away for cough furball but hiss at vacuum cleaner."
    }, {
      img: "http://img.ifcdn.com/images/5aa617f17978baf23e992f1e86c038627c11d9a6300fabc7b939d09508a273e0_1.jpg",
      duration: "1h 24m",
      title: "Podcast Playlist Title",
      description: "Rub face on owner shove bum in owner's face like camera lens run in terror, chase dog then run away for cough furball but hiss at vacuum cleaner."
    }, {
      img: "http://i0.kym-cdn.com/photos/images/facebook/000/733/489/6c3.jpg",
      duration: "1h 24m",
      title: "Podcast Playlist Title",
      description: "Rub face on owner shove bum in owner's face like camera lens. Why must they do that. Hide from vacuum cleaner chew on cable, and intently sniff hand, or see owner, run in terror, chase dog then run away for cough furball but hiss at vacuum cleaner."
    }]
    return (

        <Featured {...featuredProps} />
        <PlaylistContainer data={playlistProps} />

    );
  }
}

<|endoftext|>