<commit_before>/********************************************************************************
*   Ledger Node JS API
*   (c) 2016-2017 Ledger
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
********************************************************************************/

'use strict';

var Q = require('q');
// Default to global u2f in order to support Firefox u2f plugin that injects it into
// the browser window object, but fallback to Chrome u2f-api to support modern
// build systems.
var chromeU2FApi = require('./chrome-u2f-api');
var u2f = global.u2f ? global.u2f : chromeU2FApi;

var Ledger3 = function(timeoutSeconds) {
	this.timeoutSeconds = timeoutSeconds;
}

Ledger3.wrapApdu = function(apdu, key) {
	var result = Buffer.alloc(apdu.length);
	for (var i=0; i<apdu.length; i++) {
		result[i] = apdu[i] ^ key[i % key.length];
	}
	return result;
}

// Convert from normal to web-safe, strip trailing "="s
Ledger3.webSafe64 = function(base64) {
    return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

// Convert from web-safe to normal, add trailing "="s
Ledger3.normal64 = function(base64) {
    return base64.replace(/\-/g, '+').replace(/_/g, '/') + '=='.substring(0, (3*base64.length)%4);
}

Ledger3.prototype.u2fCallback = function(response, deferred, statusList) {
	if (typeof response['signatureData'] != "undefined") {
		var data = Buffer.from((Ledger3.normal64(response['signatureData'])), 'base64');
		if (typeof statusList != "undefined") {
			var statusFound = false;
			var sw = data.readUInt16BE(data.length - 2);
			for (var index in statusList) {
				if (statusList[index] == sw) {
					statusFound = true;
					break;
				}
			}
			if (!statusFound) {
				deferred.reject("Invalid status " + sw.toString(16));
			}
		}
		deferred.resolve(data.toString('hex', 5));
	}
	else {
		deferred.reject(response);
	}
}

Ledger3.prototype.exchange = function(apduHex, statusList) {
	var apdu = Buffer.from(apduHex, 'hex');
	var keyHandle = Ledger3.wrapApdu(apdu, this.scrambleKey);
	var challenge = Buffer.from("0000000000000000000000000000000000000000000000000000000000000000", 'hex');
	var key = {};
	key['version'] = 'U2F_V2';
	key['keyHandle'] = Ledger3.webSafe64(keyHandle.toString('base64'));
	var self = this;
	var deferred = Q.defer();
	var localCallback = function(result) {
		self.u2fCallback(result, deferred, statusList);
	}
	u2f.sign(location.origin, Ledger3.webSafe64(challenge.toString('base64')), [key], localCallback, this.timeoutSeconds);
	return deferred.promise;
}

Ledger3.prototype.setScrambleKey = function(scrambleKey) {
	this.scrambleKey = Buffer.from(scrambleKey, 'ascii');
}

Ledger3.prototype.close_async = function() {
		return Q.fcall(function() {
		});
}

Ledger3.create_async = function() {
	return Q.fcall(function() {
		return new Ledger3(20);
	});
}

module.exports = Ledger3
<commit_msg>Improve comment<commit_after>/********************************************************************************
*   Ledger Node JS API
*   (c) 2016-2017 Ledger
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
********************************************************************************/

'use strict';

var Q = require('q');
// Default to global u2f in order to support Firefox u2f plugin that injects it into
// the browser window object, but fallback to Chrome's u2f-api to support modern
// build systems.
var chromeU2FApi = require('./chrome-u2f-api');
var u2f = global.u2f ? global.u2f : chromeU2FApi;

var Ledger3 = function(timeoutSeconds) {
	this.timeoutSeconds = timeoutSeconds;
}

Ledger3.wrapApdu = function(apdu, key) {
	var result = Buffer.alloc(apdu.length);
	for (var i=0; i<apdu.length; i++) {
		result[i] = apdu[i] ^ key[i % key.length];
	}
	return result;
}

// Convert from normal to web-safe, strip trailing "="s
Ledger3.webSafe64 = function(base64) {
    return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

// Convert from web-safe to normal, add trailing "="s
Ledger3.normal64 = function(base64) {
    return base64.replace(/\-/g, '+').replace(/_/g, '/') + '=='.substring(0, (3*base64.length)%4);
}

Ledger3.prototype.u2fCallback = function(response, deferred, statusList) {
	if (typeof response['signatureData'] != "undefined") {
		var data = Buffer.from((Ledger3.normal64(response['signatureData'])), 'base64');
		if (typeof statusList != "undefined") {
			var statusFound = false;
			var sw = data.readUInt16BE(data.length - 2);
			for (var index in statusList) {
				if (statusList[index] == sw) {
					statusFound = true;
					break;
				}
			}
			if (!statusFound) {
				deferred.reject("Invalid status " + sw.toString(16));
			}
		}
		deferred.resolve(data.toString('hex', 5));
	}
	else {
		deferred.reject(response);
	}
}

Ledger3.prototype.exchange = function(apduHex, statusList) {
	var apdu = Buffer.from(apduHex, 'hex');
	var keyHandle = Ledger3.wrapApdu(apdu, this.scrambleKey);
	var challenge = Buffer.from("0000000000000000000000000000000000000000000000000000000000000000", 'hex');
	var key = {};
	key['version'] = 'U2F_V2';
	key['keyHandle'] = Ledger3.webSafe64(keyHandle.toString('base64'));
	var self = this;
	var deferred = Q.defer();
	var localCallback = function(result) {
		self.u2fCallback(result, deferred, statusList);
	}
	u2f.sign(location.origin, Ledger3.webSafe64(challenge.toString('base64')), [key], localCallback, this.timeoutSeconds);
	return deferred.promise;
}

Ledger3.prototype.setScrambleKey = function(scrambleKey) {
	this.scrambleKey = Buffer.from(scrambleKey, 'ascii');
}

Ledger3.prototype.close_async = function() {
		return Q.fcall(function() {
		});
}

Ledger3.create_async = function() {
	return Q.fcall(function() {
		return new Ledger3(20);
	});
}

module.exports = Ledger3
<|endoftext|>


<commit_before>//         __	   ______              __           __        _
//     .--() '.'  / __/ /___ ___ ___  / / ___ ____ / /_      (_)___
//    '|, . ,' 	 / _// // -_) -_) _ \/ _ | _ `/ _ | __/_    / /(_-<
//     !_-(_\	/___/_/ \__/\__/ .__/_//_|_,_/_//_|__/(_)__/ //___/
//	   		 	              /_/                       |___/
//
// elephant.js 0.0.1 (c) 2011 [Jeff Remer](http://jeffremer.com).
//
// [Source](http://github.com/jeffremer/elephant.js) available on GitHub.
// [MIT License](https://github.com/jeffremer/elephant.js/blob/master/LICENSE).

(function(){
	var Elephant;
	typeof exports != 'undefined' ? Elephant = exports : Elephant = this.Elephant = {};

	if(window.debug) console.log("There's an Elephant in the room.")

	// Local Helpers
	// -------

	// `each` and `map`
	// Taken from [underscore.js](http://documentcloud.github.com/underscore)
	// Rather than make underscore a dependency, here are standalone versions
	// of Jeremy Ashkenas wonderful each and map functions.
	function each(obj, iterator, context) {
		if (obj == null) return;
		if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
			obj.forEach(iterator, context);
		} else if (!!(obj.length === 0 || (obj.length && obj.length.toExponential && obj.length.toFixed))) {
			for (var i = 0, l = obj.length; i < l; i++) {
				if (iterator.call(context, obj[i], i, obj) === {}) return;
			}
		} else {
			for (var key in obj) {
				if (hasOwnProperty.call(obj, key)) {
					if (iterator.call(context, obj[key], key, obj) === {}) return;
				}
			}
		}
	}

	function map(obj, iterator, context) {
		var results = [];
		if (obj == null) return results;
		if (Array.prototype.map && obj.map === Array.prototype.map) return obj.map(iterator, context);
		each(obj, function(value, index, list) {
			results[results.length] = iterator.call(context, value, index, list);
		});
		return results;
	}

	// Elephant.has
	// ------------
	Elephant.has = {
		// Determines if window.localStorage is available
		localStorage : function() {
			try { return !!localStorage.getItem; } catch (e) {return false};
		}(),
		// Tests to make sure cookies are available
		cookies: function() {
			if(navigator.cookieEnabled) return true;
			document.cookie = 'elephantcookie=1';
			var ret = document.cookie.indexOf("cookietest=") != -1;
			document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
			return ret;
		}()
	};

	// Elephant.Trunk
	// --------------

	// The main store class.
	Elephant.Trunk = function(name) {
		// `name` is a namespace for the localStorage object
		this.name = name;
		var store = localStorage.getItem(this.name);
		// `Elephant.Trunk.data` is JSON hash of guid to object
		this.data = (store && JSON.parse(store)) || {};
	};

	// `guid` generates a random 32-bit unique ID
	Elephant.Trunk.prototype.guid = function() {
	    return 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
		    return v.toString(16);
		});
	};

	Elephant.Trunk.prototype.sync = function() {
		localStorage.setItem(this.name, JSON.stringify(this.data));
	};

	// CRUD
	// ====

	// Create
	// ------

	// `save` creates a new guid for the object, assigns
	// the guid, updates the memory store, then syncs the
	// local store.

	// `guid` a very low chance of colliding, even so the `save` method
	// checks to see if the `guid` is in use and generates a new one before
	// clobbering any existing objects.
	// TODO If the object has a guid update instead of save.
	//		store.save({...}) // -> {..., guid: '53b425a6-47cb-462c-9498-ba236becee06'}
	Elephant.Trunk.prototype.save = function(object) {
		var uuid = this.guid();
		while(uuid in this.data) uuid = guid();
		object.guid = uuid;
		this.data[object.guid] = object;
		this.sync();
		return object;
	};

	// Read
	// ------

	// `find` retrieves an object by guid.
	//		store.find('53b425a6-47cb-462c-9498-ba236becee06') // -> {...}
	Elephant.Trunk.prototype.find = function(guid) {
		return this.data[guid]
	};

	// `findAll` retrieves all of the objects as an array.
    //		store.findAll() // -> [{...}, {...}, {...}]
	Elephant.Trunk.prototype.findAll = function() {
		return map(this.data, function(obj){return obj;})
	};

	// Update
	// ------

	// `update` saves if the object has no guid, or
	// it replaces the object in memory store and syncs.
	// 		store.update({..., guid: '53b425a6-47cb-462c-9498-ba236becee06'}) // -> {..., guid: '53b425a6-47cb-462c-9498-ba236becee06'}
	Elephant.Trunk.prototype.update = function(object) {
		if(!object.guid) {
			object = this.save(object);
		} else {
			this.data[object.guid] = object;
			this.sync()
		}
		return object;
	};

	// Destroy
	// ------

	// `destroy` removes the object from the store and deletes
	// the guid off the object before returning it.
	//		store.destroy({..., guid: '53b425a6-47cb-462c-9498-ba236becee06'}) // -> {...}
	Elephant.Trunk.prototype.destroy = function(object) {
		if(object.guid && object.guid in this.data) {
			delete this.data[object.guid];
			delete object.guid;
			this.sync();
		}
		return object;
	};

	// `destroyAll` clears the internal data store then saves the blank object.
	//		store.destroyAll() // -> undefined
	Elephant.Trunk.prototype.destroyAll = function() {
		this.data = {};
		this.sync();
	};
})()
<commit_msg>ASCII elephant, because.<commit_after>//         __	   ______              __           __        _
//     .--() '.'  / __/ /___ ___ ___  / / ___ ____ / /_      (_)___
//    '|, . ,' 	 / _// // -_) -_) _ \/ _ | _ `/ _ | __/_    / /(_-<
//     !_-(_\	/___/_/ \__/\__/ .__/_//_|_,_/_//_|__/(_)__/ //___/
//  	   	 	              /_/                       |___/
//
// elephant.js 0.0.1 (c) 2011 [Jeff Remer](http://jeffremer.com).
//
// [Source](http://github.com/jeffremer/elephant.js) available on GitHub.
// [MIT License](https://github.com/jeffremer/elephant.js/blob/master/LICENSE).

(function(){
	var Elephant;
	typeof exports != 'undefined' ? Elephant = exports : Elephant = this.Elephant = {};

	if(window.debug) console.log("There's an Elephant in the room.")

	// Local Helpers
	// -------

	// `each` and `map`
	// Taken from [underscore.js](http://documentcloud.github.com/underscore)
	// Rather than make underscore a dependency, here are standalone versions
	// of Jeremy Ashkenas wonderful each and map functions.
	function each(obj, iterator, context) {
		if (obj == null) return;
		if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
			obj.forEach(iterator, context);
		} else if (!!(obj.length === 0 || (obj.length && obj.length.toExponential && obj.length.toFixed))) {
			for (var i = 0, l = obj.length; i < l; i++) {
				if (iterator.call(context, obj[i], i, obj) === {}) return;
			}
		} else {
			for (var key in obj) {
				if (hasOwnProperty.call(obj, key)) {
					if (iterator.call(context, obj[key], key, obj) === {}) return;
				}
			}
		}
	}

	function map(obj, iterator, context) {
		var results = [];
		if (obj == null) return results;
		if (Array.prototype.map && obj.map === Array.prototype.map) return obj.map(iterator, context);
		each(obj, function(value, index, list) {
			results[results.length] = iterator.call(context, value, index, list);
		});
		return results;
	}

	// Elephant.has
	// ------------
	Elephant.has = {
		// Determines if window.localStorage is available
		localStorage : function() {
			try { return !!localStorage.getItem; } catch (e) {return false};
		}(),
		// Tests to make sure cookies are available
		cookies: function() {
			if(navigator.cookieEnabled) return true;
			document.cookie = 'elephantcookie=1';
			var ret = document.cookie.indexOf("cookietest=") != -1;
			document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
			return ret;
		}()
	};

	// Elephant.Trunk
	// --------------

	// The main store class.
	Elephant.Trunk = function(name) {
		// `name` is a namespace for the localStorage object
		this.name = name;
		var store = localStorage.getItem(this.name);
		// `Elephant.Trunk.data` is JSON hash of guid to object
		this.data = (store && JSON.parse(store)) || {};
	};

	// `guid` generates a random 32-bit unique ID
	Elephant.Trunk.prototype.guid = function() {
	    return 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
		    return v.toString(16);
		});
	};

	Elephant.Trunk.prototype.sync = function() {
		localStorage.setItem(this.name, JSON.stringify(this.data));
	};

	// CRUD
	// ====

	// Create
	// ------

	// `save` creates a new guid for the object, assigns
	// the guid, updates the memory store, then syncs the
	// local store.

	// `guid` a very low chance of colliding, even so the `save` method
	// checks to see if the `guid` is in use and generates a new one before
	// clobbering any existing objects.
	// TODO If the object has a guid update instead of save.
	//		store.save({...}) // -> {..., guid: '53b425a6-47cb-462c-9498-ba236becee06'}
	Elephant.Trunk.prototype.save = function(object) {
		var uuid = this.guid();
		while(uuid in this.data) uuid = guid();
		object.guid = uuid;
		this.data[object.guid] = object;
		this.sync();
		return object;
	};

	// Read
	// ------

	// `find` retrieves an object by guid.
	//		store.find('53b425a6-47cb-462c-9498-ba236becee06') // -> {...}
	Elephant.Trunk.prototype.find = function(guid) {
		return this.data[guid]
	};

	// `findAll` retrieves all of the objects as an array.
    //		store.findAll() // -> [{...}, {...}, {...}]
	Elephant.Trunk.prototype.findAll = function() {
		return map(this.data, function(obj){return obj;})
	};

	// Update
	// ------

	// `update` saves if the object has no guid, or
	// it replaces the object in memory store and syncs.
	// 		store.update({..., guid: '53b425a6-47cb-462c-9498-ba236becee06'}) // -> {..., guid: '53b425a6-47cb-462c-9498-ba236becee06'}
	Elephant.Trunk.prototype.update = function(object) {
		if(!object.guid) {
			object = this.save(object);
		} else {
			this.data[object.guid] = object;
			this.sync()
		}
		return object;
	};

	// Destroy
	// ------

	// `destroy` removes the object from the store and deletes
	// the guid off the object before returning it.
	//		store.destroy({..., guid: '53b425a6-47cb-462c-9498-ba236becee06'}) // -> {...}
	Elephant.Trunk.prototype.destroy = function(object) {
		if(object.guid && object.guid in this.data) {
			delete this.data[object.guid];
			delete object.guid;
			this.sync();
		}
		return object;
	};

	// `destroyAll` clears the internal data store then saves the blank object.
	//		store.destroyAll() // -> undefined
	Elephant.Trunk.prototype.destroyAll = function() {
		this.data = {};
		this.sync();
	};
})()
<|endoftext|>


<commit_before>angular.module('rifiuti.services.utili', [])

.factory('Conf', function() {

    return {
        showNews: function() {
            return SHOW_NEWS;
        }
    };
})

.factory('ConnectionErrorService', function($ionicPopup,$filter) {
  return {
    show : function() {
        var popup = $ionicPopup.show({
            title: ''+$filter("translate")("dev_mode")+'',
            template: $filter("translate")("connection_error"),
            buttons: [
                {
                    text: 'OK'
                }
            ]
        });
     }
   }
})

.factory('LoaderService', function($rootScope, $ionicLoading) {
  return {
        show : function() {

            $rootScope.loading = $ionicLoading.show({

              // The text to display in the loading indicator
              content: ' Loading',

              // The animation to use
              animation: 'fade-in',

              // Will a dark overlay or backdrop cover the entire view
              showBackdrop: true,

              // The maximum width of the loading indicator
              // Text will be wrapped if longer than maxWidth
              maxWidth: 200,

              // The delay in showing the indicator
              showDelay: 10
            });
        },

        hide : function(){
            if ($rootScope.loading) {
                $rootScope.loading.hide();
            }
        }
    }
})

.factory('Utili', function () {
  var mesi = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
  var giorni = ["DOM", "LUN", "MAR", "MER", "GIO", "VEN", "SAB"];
  var giorniC = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
  var giorniShort = ["dom", "lun", "mar", "mer", "gio", "ven", "sab"];

  var DOW = {"DOM":6, "LUN":0, "MAR":1, "MER":2, "GIO":3, "VEN":4, "SAB":5};

  var daysInMonth = function(month, year) {
      return new Date(year, month + 1, 0).getDate();
  };
  var dayIndex = function(day) {
          return DOW[day];
  };

  var format = function(date) {
    return date.getFullYear()+'-'+(date.getMonth() < 9 ? '0'+(date.getMonth()+1):(date.getMonth()+1))+'-'+(date.getDate() < 10 ? '0'+date.getDate():date.getDate());
  };

  var generateDOWDates = function(da, a, dow, ecc) {
      var res = [];
      var currFrom = new Date(da.getTime());
      currFrom.setDate(currFrom.getDate()-dayIndex(giorni[currFrom.getDay()])+dow);
      while (currFrom.getTime()  da.getTime()) {
          var dStr = format(currFrom);
          if (!ecc || ecc.indexOf(dStr) < 0) res.push(dStr);
        }
        // move to next week
        currFrom.setDate(currFrom.getDate()+7);
      }
      return res;
  };

  /**
   * generate a list of date string for the specified period, date, definition, and list of exceptions (format dd/MM[/yyyy])
   * definition is space-separated elements, where element is either DOW (e.g., lunedi) or date (format dd/MM[/yyyy])
   */
  var calToDates = function(da, a, il, ecc) {
    if (!il) return [];

    var arr = il.trim().split(' ');
    var dates = [];
    var eccDates = calToDates(da, a, ecc, null);
    for (var i = 0; i < arr.length; i++) {
      var elem = arr[i];
      var idx = giorniC.indexOf(elem);
      // DOW case
      if (idx >= 0) {
        dates = dates.concat(generateDOWDates(da, a, DOW[giorni[idx]], eccDates));
      // date case
      } else {
        var dElems = elem.split('/');
        if (dElems.length < 2 || dElems.length > 3) return;
        if (dElems.length == 2) dElems.push(''+da.getFullYear());
        var dStr = format(new Date(dElems[2], dElems[1]-1, dElems[0]));
        if (!ecc || ecc.indexOf(dStr) < 0) dates.push(dStr);
      }
    }
    dates.sort();
    return dates;
  };

  var iconType = function(tipologia) {
    if (tipologia in ICON_POINT_MAP) return ICON_POINT_MAP[tipologia];
    return null;
  };

  var rgbColor = function(colore) {
      if (colore in ICON_COLOR_MAP) return ICON_COLOR_MAP[colore];
      return 'grey';
  }

  return {
    jsDOWToShortText: function(dow) {
      return giorni[dow];
    },
    jsDOWToDOW: function(dow) {
      return DOW[giorni[dow]];
    },
    DOWTextToDOW: function(dow) {
      return DOW[dow];
    },
    dayIndex: dayIndex,
    textToDOW: function(txt) {
      return DOW[giorni[giorniC.indexOf(txt)]];
    },
    dayToDOW: function(day) {
      return dayIndex(giorni[day]);
    },
    monthYear: function(a, b) {
        return mesi[a] + " " + b
    },
    isLastDayInMonth : function(dt) {
        return new Date(dt.getTime() + 86400000).getDate() === 1;
    },
    lastDateOfMonth: function(date) {
        return new Date(date.getFullYear(), date.getMonth() + 1, 0);
    },
    calToDates: calToDates,
    expandOrarioApertura: function(cal) {
      if (!cal.il || cal.dates) return;
      var max = new Date(Date.parse(cal.dataA));
      var min = new Date(Date.parse(cal.dataDa));
      cal.dates = calToDates(min,max, cal.il, cal.eccezione);
    },

    getRGBColor: function(rgbColor) {
        var c = rgbColor;
        if (c == 'white') {
            return 'grey';
        }
        return c;
    },
    iconFromRegola: function(regola) {
      return this.icon(regola.tipologiaPuntoRaccolta, regola.colore);
    },
//    icon: function(tipologia, colore) {
//      var icona = iconType(tipologia);
//      return (!!icona?'img/ic_'+icona+'_'+this.getRGBColor(colore)+'.png':null);
//    },
    icon: function(icona,colorById) {
      //var icona = iconType(tipologia);
      if (colorById=='white') {
        return icona + '-outline';
      }
      return icona;
    },
    poiIcon: function(icona, colore) {
      //var icona = iconType(tipologia);
      return (!!icona?'img/ic_poi_'+icona+'.png':null);
    },
    belongsTo: function(pr, area, profile) {
      return profile.aree.indexOf(area) != -1
          //&& (pr.tipologiaPuntiRaccolta=='CRM' || pr.tipologiaPuntiRaccolta=='CRZ' || !pr.zona || profile.comuni.indexOf(pr.zona)!=-1)
        ;
    },
    isPaP: function(tipoPuntoRaccolta) {
      return !!tipoPuntoRaccolta && !!tipoPuntoRaccolta.type && (tipoPuntoRaccolta.type == 'PP' || !!CUSTOM_PAP && CUSTOM_PAP.indexOf(tipoPuntoRaccolta.type) >= 0);
    },
      //return !!tipologia && (tipologia.toLowerCase().indexOf('porta a porta') == 0 || !!CUSTOM_PAP && CUSTOM_PAP.indexOf(tipologia) >= 0);
	fullDateFormat: function(d,transf) {
		return transf(giorniShort[d.getDay()])+ ' ' +d.getDate()+' '+transf(mesi[d.getMonth()])+' '+d.getFullYear();
	},
//    filterCharacteristics: function(pdr) {
//        if (!ISOLA_MAPPING) return false;
//        if (!pdr.caratteristiche) return false;
//        for (var key in pdr.caratteristiche) {
//            if (pdr.caratteristiche[key]) return true;
//        }
//        return false;
//    },
    pdrCharacteristicApplies: function(pdr, tipo) {
        var mapping = null;
        try {
            mapping = ISOLA_MAPPING;
        }catch(e) {
        }
        if (mapping != null && pdr.caratteristiche && !pdr.caratteristiche[mapping[tipo]]) return false;
        return true;
    }
  }
})
<commit_msg>fix for deprecate warning<commit_after>angular.module('rifiuti.services.utili', [])

.factory('Conf', function() {

    return {
        showNews: function() {
            return SHOW_NEWS;
        }
    };
})

.factory('ConnectionErrorService', function($ionicPopup,$filter) {
  return {
    show : function() {
        var popup = $ionicPopup.show({
            title: ''+$filter("translate")("dev_mode")+'',
            template: $filter("translate")("connection_error"),
            buttons: [
                {
                    text: 'OK'
                }
            ]
        });
     }
   }
})

.factory('LoaderService', function($rootScope, $ionicLoading) {
  return {
        show : function() {

            $rootScope.loading = $ionicLoading.show({

              // The text to display in the loading indicator
              content: ' Loading',

              // The animation to use
              animation: 'fade-in',

              // Will a dark overlay or backdrop cover the entire view
              showBackdrop: true,

              // The maximum width of the loading indicator
              // Text will be wrapped if longer than maxWidth
              maxWidth: 200,

              // The delay in showing the indicator
              showDelay: 10
            });
        },

        hide : function(){
            if ($rootScope.loading) {
                $ionicLoading.hide();
            }
        }
    }
})

.factory('Utili', function () {
  var mesi = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
  var giorni = ["DOM", "LUN", "MAR", "MER", "GIO", "VEN", "SAB"];
  var giorniC = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
  var giorniShort = ["dom", "lun", "mar", "mer", "gio", "ven", "sab"];

  var DOW = {"DOM":6, "LUN":0, "MAR":1, "MER":2, "GIO":3, "VEN":4, "SAB":5};

  var daysInMonth = function(month, year) {
      return new Date(year, month + 1, 0).getDate();
  };
  var dayIndex = function(day) {
          return DOW[day];
  };

  var format = function(date) {
    return date.getFullYear()+'-'+(date.getMonth() < 9 ? '0'+(date.getMonth()+1):(date.getMonth()+1))+'-'+(date.getDate() < 10 ? '0'+date.getDate():date.getDate());
  };

  var generateDOWDates = function(da, a, dow, ecc) {
      var res = [];
      var currFrom = new Date(da.getTime());
      currFrom.setDate(currFrom.getDate()-dayIndex(giorni[currFrom.getDay()])+dow);
      while (currFrom.getTime()  da.getTime()) {
          var dStr = format(currFrom);
          if (!ecc || ecc.indexOf(dStr) < 0) res.push(dStr);
        }
        // move to next week
        currFrom.setDate(currFrom.getDate()+7);
      }
      return res;
  };

  /**
   * generate a list of date string for the specified period, date, definition, and list of exceptions (format dd/MM[/yyyy])
   * definition is space-separated elements, where element is either DOW (e.g., lunedi) or date (format dd/MM[/yyyy])
   */
  var calToDates = function(da, a, il, ecc) {
    if (!il) return [];

    var arr = il.trim().split(' ');
    var dates = [];
    var eccDates = calToDates(da, a, ecc, null);
    for (var i = 0; i < arr.length; i++) {
      var elem = arr[i];
      var idx = giorniC.indexOf(elem);
      // DOW case
      if (idx >= 0) {
        dates = dates.concat(generateDOWDates(da, a, DOW[giorni[idx]], eccDates));
      // date case
      } else {
        var dElems = elem.split('/');
        if (dElems.length < 2 || dElems.length > 3) return;
        if (dElems.length == 2) dElems.push(''+da.getFullYear());
        var dStr = format(new Date(dElems[2], dElems[1]-1, dElems[0]));
        if (!ecc || ecc.indexOf(dStr) < 0) dates.push(dStr);
      }
    }
    dates.sort();
    return dates;
  };

  var iconType = function(tipologia) {
    if (tipologia in ICON_POINT_MAP) return ICON_POINT_MAP[tipologia];
    return null;
  };

  var rgbColor = function(colore) {
      if (colore in ICON_COLOR_MAP) return ICON_COLOR_MAP[colore];
      return 'grey';
  }

  return {
    jsDOWToShortText: function(dow) {
      return giorni[dow];
    },
    jsDOWToDOW: function(dow) {
      return DOW[giorni[dow]];
    },
    DOWTextToDOW: function(dow) {
      return DOW[dow];
    },
    dayIndex: dayIndex,
    textToDOW: function(txt) {
      return DOW[giorni[giorniC.indexOf(txt)]];
    },
    dayToDOW: function(day) {
      return dayIndex(giorni[day]);
    },
    monthYear: function(a, b) {
        return mesi[a] + " " + b
    },
    isLastDayInMonth : function(dt) {
        return new Date(dt.getTime() + 86400000).getDate() === 1;
    },
    lastDateOfMonth: function(date) {
        return new Date(date.getFullYear(), date.getMonth() + 1, 0);
    },
    calToDates: calToDates,
    expandOrarioApertura: function(cal) {
      if (!cal.il || cal.dates) return;
      var max = new Date(Date.parse(cal.dataA));
      var min = new Date(Date.parse(cal.dataDa));
      cal.dates = calToDates(min,max, cal.il, cal.eccezione);
    },

    getRGBColor: function(rgbColor) {
        var c = rgbColor;
        if (c == 'white') {
            return 'grey';
        }
        return c;
    },
    iconFromRegola: function(regola) {
      return this.icon(regola.tipologiaPuntoRaccolta, regola.colore);
    },
//    icon: function(tipologia, colore) {
//      var icona = iconType(tipologia);
//      return (!!icona?'img/ic_'+icona+'_'+this.getRGBColor(colore)+'.png':null);
//    },
    icon: function(icona,colorById) {
      //var icona = iconType(tipologia);
      if (colorById=='white') {
        return icona + '-outline';
      }
      return icona;
    },
    poiIcon: function(icona, colore) {
      //var icona = iconType(tipologia);
      return (!!icona?'img/ic_poi_'+icona+'.png':null);
    },
    belongsTo: function(pr, area, profile) {
      return profile.aree.indexOf(area) != -1
          //&& (pr.tipologiaPuntiRaccolta=='CRM' || pr.tipologiaPuntiRaccolta=='CRZ' || !pr.zona || profile.comuni.indexOf(pr.zona)!=-1)
        ;
    },
    isPaP: function(tipoPuntoRaccolta) {
      return !!tipoPuntoRaccolta && !!tipoPuntoRaccolta.type && (tipoPuntoRaccolta.type == 'PP' || !!CUSTOM_PAP && CUSTOM_PAP.indexOf(tipoPuntoRaccolta.type) >= 0);
    },
      //return !!tipologia && (tipologia.toLowerCase().indexOf('porta a porta') == 0 || !!CUSTOM_PAP && CUSTOM_PAP.indexOf(tipologia) >= 0);
	fullDateFormat: function(d,transf) {
		return transf(giorniShort[d.getDay()])+ ' ' +d.getDate()+' '+transf(mesi[d.getMonth()])+' '+d.getFullYear();
	},
//    filterCharacteristics: function(pdr) {
//        if (!ISOLA_MAPPING) return false;
//        if (!pdr.caratteristiche) return false;
//        for (var key in pdr.caratteristiche) {
//            if (pdr.caratteristiche[key]) return true;
//        }
//        return false;
//    },
    pdrCharacteristicApplies: function(pdr, tipo) {
        var mapping = null;
        try {
            mapping = ISOLA_MAPPING;
        }catch(e) {
        }
        if (mapping != null && pdr.caratteristiche && !pdr.caratteristiche[mapping[tipo]]) return false;
        return true;
    }
  }
})
<|endoftext|>


<commit_before>import { css } from 'styled-components';
import {
  miscNormalStyle, miscActiveStyle, miscCheckedStyle,
  miscDisabledStyle, inputNormalStyle, inputActiveStyle,
  inputDisabledStyle,
} from './formHelpers';
import { rem } from '../../helpers/utils';

export const commonInputStyles = css`
  margin: 0;
  -webkit-appearance: none;
  touch-action: manipulation;
  max-width: 100%;
  width: 100%;
  border-width: 1px;
  border-style: solid;
  transition: .2s ease-in-out;
  transition-property: color, background-color, border;
  border-radius: ${rem(6)};
  ${inputNormalStyle}
  &:focus {
    outline: none;
    ${inputActiveStyle}
  }
  &:disabled {
    ${inputDisabledStyle}
  }
`;

export const miscInputStyles = css`
  touch-action: manipulation;
  -webkit-appearance: none;
  overflow: hidden;
  padding: 0;
  display: inline-block;
  height: ${rem(16)};
  width: ${rem(16)};
  margin-top: ${rem(-4)};
  vertical-align: middle;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  border-width: 1px;
  border-style: solid;
  transition: .2s ease-in-out;
  transition-property: background-color, border;
  cursor: pointer;
  ${miscNormalStyle}
  &:focus {
    outline: none;
    ${miscActiveStyle}
  }
  &:checked {
    ${miscCheckedStyle}
  }
  &:disabled {
    ${miscDisabledStyle}
    cursor: default;
  }
`;
<commit_msg>Make Radio and Checkbox bigger<commit_after>import { css } from 'styled-components';
import {
  miscNormalStyle, miscActiveStyle, miscCheckedStyle,
  miscDisabledStyle, inputNormalStyle, inputActiveStyle,
  inputDisabledStyle,
} from './formHelpers';
import { rem } from '../../helpers/utils';

export const commonInputStyles = css`
  margin: 0;
  -webkit-appearance: none;
  touch-action: manipulation;
  max-width: 100%;
  width: 100%;
  border-width: 1px;
  border-style: solid;
  transition: .2s ease-in-out;
  transition-property: color, background-color, border;
  border-radius: ${rem(6)};
  ${inputNormalStyle}
  &:focus {
    outline: none;
    ${inputActiveStyle}
  }
  &:disabled {
    ${inputDisabledStyle}
  }
`;

export const miscInputStyles = css`
  touch-action: manipulation;
  -webkit-appearance: none;
  overflow: hidden;
  padding: 0;
  display: inline-block;
  height: ${rem(24)};
  width: ${rem(24)};
  margin-top: ${rem(-4)};
  vertical-align: middle;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  border-width: 1px;
  border-style: solid;
  transition: .2s ease-in-out;
  transition-property: background-color, border;
  cursor: pointer;
  ${miscNormalStyle}
  &:focus {
    outline: none;
    ${miscActiveStyle}
  }
  &:checked {
    ${miscCheckedStyle}
  }
  &:disabled {
    ${miscDisabledStyle}
    cursor: default;
  }
`;
<|endoftext|>


<commit_before>/**
 * Created by Obscurity on 2017/1/21.
 */

(function ($) {

    'use strict';

    var platforms = {
        qzone: {
            name: "qzone",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/qzone.png",
            text: "QQ空间"
        },
        qq: {
            name: "qq",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/qq.png",
            text: "QQ好友"
        },
        wechat: {
            name: "wechat",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/wechat.png",
            text: "微信"
        },
        sinaweibo: {
            name: "sinaweibo",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/sinaweibo.png",
            text: "新浪微博"
        },
        douban: {
            name: "douban",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/douban.png",
            text: "豆瓣"
        },
        renren: {
            name: "renren",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/renren.png",
            text: "人人网"
        },
        kaixin: {
            name: "kaixin",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/kaixin.png",
            text: "开心网"
        },
        pengyou: {
            name: "pengyou",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/pengyou.png",
            text: "朋友网"
        },
        tieba: {
            name: "tieba",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/tieba.png",
            text: "百度贴吧"
        },
        renminweibo: {
            name: "renminweibo",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/renminweibo.png",
            text: "人民微博"
        },
        hexunweibo: {
            name: "hexunweibo",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/hexunweibo.png",
            text: "和讯微博"
        },
        tianya: {
            name: "tianya",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/tianya.png",
            text: "天涯网"
        },
        reddit: {
            name: "reddit",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/reddit.png",
            text: "Reddit"
        },
        copyLink: {
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/copylink.png"
        }
    };

    var defaults = {
        size: "small",
        copyLink: true,
        platforms: []
    };

    var sizes = ["small", "medium", "large"];

    var hShare = function (options) {

        var _render = function (name, icon, customize, html) {
            if (customize) {
                return html;
            }
            else {
                switch(name) {
                    case "qzone":
                        return _renderQzone(icon);
                    case "qq":
                        return __renderQQ(icon);
                    case "wechat":
                        return _renderWechat(icon);
                    case "sinaweibo":
                        return _renderSinaWeibo(icon);
                    case "renren":
                        return _renderRenren(icon);
                    case "douban":
                        return _renderDouban(icon);
                    case "kaixin":
                        return _renderKaixin(icon);
                    case "pengyou":
                        return _renderPengyou(icon);
                    case "tieba":
                        return _renderTieba(icon);
                    case "renminweibo":
                        return _renderRenminWeibo(icon);
                    case "hexunweibo":
                        return _renderHexunWeibo(icon);
                    case "tianya":
                        return _renderTianya(icon);
                    case "reddit":
                        return _renderReddit(icon);
                    default:
                        throw Error("invalid name");
                        break;
                }
            }
        };

        var __renderQQ = function (icon) {
            return ""
        };

        var _renderWechat = function (icon) {
            return "<\/a>";
        };

        var _renderQzone = function (icon) {
            return "<\/a>";
        };

        var _renderDouban = function (icon) {
            return "";
        };

        var _renderRenren = function (icon) {
            return "";
        };

        var _renderSinaWeibo = function (icon) {
            return "";
        };

        var _renderKaixin = function (icon) {
            return "";
        };

        var _renderPengyou = function (icon) {
            return "<\/a>";
        };

        var _renderTieba = function (icon) {
            return "";
        };

        var _renderRenminWeibo = function (icon) {
            return "";
        };

        var _renderHexunWeibo = function (icon) {
            return "";
        };

        var _renderTianya = function (icon) {
            return "";
        };

        var _renderReddit = function (icon) {
            return "";
        };

        var _renderCopyLink = function (icon) {
            return "";
        };

        var _loadScript = function (url, callback)
        {
            // Adding the script tag to the head as suggested before
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = url;

            // Then bind the event to the callback function.
            // There are several events for cross browser compatibility.
            script.onreadystatechange = callback;
            script.onload = callback;

            // Fire the loading
            head.appendChild(script);
        };

        var url = encodeURIComponent(location.href);
        var title = encodeURIComponent(document.title);

        var opts = options ? $.extend(true, {}, options) : $.extend(true, {}, defaults);
        var size = sizes.includes(opts.size) ? opts.size : "medium";

        opts.platforms = [];
        if (options && (options.platforms instanceof Array)) {
            options.platforms.forEach(function (platform) {
                opts.platforms.push($.extend({}, (platform.name && platforms[platform.name]) ? platforms[platform.name] : {}, platform));
            });
        }
        else {
            for(var key in platforms) {
                if (platforms[key].default) {
                    opts.platforms.push(platforms[key]);
                }
            }
        }

        return this.each(function () {
            var $this = $(this);

            var _platforms = opts.platforms;

            _platforms.forEach(function (plt) {
                var name = plt.name || "";
                var icon = plt.icon || "";
                var isCustomized = !!plt.customize;
                var customize = plt.customize || "";
                $this.append($(_render(name, icon, isCustomized, customize)));
            });

            if(opts.copyLink) {
                var copyEntry = $(_renderCopyLink(platforms.copyLink.icon));
                _loadScript("https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.16/clipboard.min.js", function () {
                    new Clipboard(copyEntry[0], {
                        text: function(trigger) {
                            return location.href;
                        }
                    });
                });
                $this.append(copyEntry);
            }

        });
    };

    $.fn.extend({
        hshare: hShare
    });

})(jQuery);<commit_msg>增加了一个demo<commit_after>/**
 * Created by Obscurity on 2017/1/21.
 */

(function ($) {

    'use strict';

    var platforms = {
        qzone: {
            name: "qzone",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/qzone.png",
            text: "QQ空间"
        },
        qq: {
            name: "qq",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/qq.png",
            text: "QQ好友"
        },
        wechat: {
            name: "wechat",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/wechat.png",
            text: "微信"
        },
        sinaweibo: {
            name: "sinaweibo",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/sinaweibo.png",
            text: "新浪微博"
        },
        douban: {
            name: "douban",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/douban.png",
            text: "豆瓣"
        },
        renren: {
            name: "renren",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/renren.png",
            text: "人人网"
        },
        kaixin: {
            name: "kaixin",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/kaixin.png",
            text: "开心网"
        },
        pengyou: {
            name: "pengyou",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/pengyou.png",
            text: "朋友网"
        },
        tieba: {
            name: "tieba",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/tieba.png",
            text: "百度贴吧"
        },
        renminweibo: {
            name: "renminweibo",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/renminweibo.png",
            text: "人民微博"
        },
        hexunweibo: {
            name: "hexunweibo",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/hexunweibo.png",
            text: "和讯微博"
        },
        tianya: {
            name: "tianya",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/tianya.png",
            text: "天涯网"
        },
        reddit: {
            name: "reddit",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/reddit.png",
            text: "Reddit"
        },
        copyLink: {
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/copylink.png"
        }
    };

    var defaults = {
        size: "small",
        copyLink: true,
        platforms: []
    };

    var sizes = ["small", "medium", "large"];

    var hShare = function (options) {

        var _render = function (name, icon, customize, html) {
            if (customize) {
                return html;
            }
            else {
                switch(name) {
                    case "qzone":
                        return _renderQzone(icon);
                    case "qq":
                        return __renderQQ(icon);
                    case "wechat":
                        return _renderWechat(icon);
                    case "sinaweibo":
                        return _renderSinaWeibo(icon);
                    case "renren":
                        return _renderRenren(icon);
                    case "douban":
                        return _renderDouban(icon);
                    case "kaixin":
                        return _renderKaixin(icon);
                    case "pengyou":
                        return _renderPengyou(icon);
                    case "tieba":
                        return _renderTieba(icon);
                    case "renminweibo":
                        return _renderRenminWeibo(icon);
                    case "hexunweibo":
                        return _renderHexunWeibo(icon);
                    case "tianya":
                        return _renderTianya(icon);
                    case "reddit":
                        return _renderReddit(icon);
                    default:
                        throw Error("invalid name");
                        break;
                }
            }
        };

        var __renderQQ = function (icon) {
            return ""
        };

        var _renderWechat = function (icon) {
            return "<\/a>";
        };

        var _renderQzone = function (icon) {
            return "<\/a>";
        };

        var _renderDouban = function (icon) {
            return "";
        };

        var _renderRenren = function (icon) {
            return "";
        };

        var _renderSinaWeibo = function (icon) {
            return "";
        };

        var _renderKaixin = function (icon) {
            return "";
        };

        var _renderPengyou = function (icon) {
            return "<\/a>";
        };

        var _renderTieba = function (icon) {
            return "";
        };

        var _renderRenminWeibo = function (icon) {
            return "";
        };

        var _renderHexunWeibo = function (icon) {
            return "";
        };

        var _renderTianya = function (icon) {
            return "";
        };

        var _renderReddit = function (icon) {
            return "";
        };

        var _renderCopyLink = function (icon) {
            return "";
        };

        var _loadScript = function (url, callback)
        {
            // Adding the script tag to the head as suggested before
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = url;

            // Then bind the event to the callback function.
            // There are several events for cross browser compatibility.
            script.onreadystatechange = callback;
            script.onload = callback;

            // Fire the loading
            head.appendChild(script);
        };

        var url = encodeURIComponent(location.href);
        var title = encodeURIComponent(document.title);

        var opts = options ? $.extend(true, {}, options) : $.extend(true, {}, defaults);
        var size = sizes.includes(opts.size) ? opts.size : "medium";

        opts.platforms = [];
        if (options && (options.platforms instanceof Array)) {
            options.platforms.forEach(function (platform) {
                opts.platforms.push($.extend({}, (platform.name && platforms[platform.name]) ? platforms[platform.name] : {}, platform));
            });
        }
        else {
            for(var key in platforms) {
                if (platforms[key].default) {
                    opts.platforms.push(platforms[key]);
                }
            }
        }

        return this.each(function () {
            var $this = $(this);

            var _platforms = opts.platforms;

            _platforms.forEach(function (plt) {
                var name = plt.name || "";
                var icon = plt.icon || "";
                var isCustomized = !!plt.customize;
                var customize = plt.customize || "";
                $this.append($(_render(name, icon, isCustomized, customize)));
            });

            if(opts.copyLink) {
                var copyEntry = $(_renderCopyLink(platforms.copyLink.icon));
                _loadScript("https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.16/clipboard.min.js", function () {
                    var clipboard = new Clipboard(copyEntry[0], {
                        text: function(trigger) {
                            return location.href;
                        }
                    });

                    clipboard.on('success', function(e) {
                        alert("已复制链接到剪贴板");
                    });
                });
                $this.append(copyEntry);
            }

        });
    };

    $.fn.extend({
        hshare: hShare
    });

})(jQuery);<|endoftext|>


<commit_before>import React from 'react'
import { api } from '../../data'
import { Container } from '@hackclub/design-system'
import {
  FormWrapper,
  Aside,
  ConfirmClose,
  Fieldset,
  Field,
  Submit,
  Form
} from '../components/Forms'
import { withFormik } from 'formik'
import { Link, Prompt } from 'react-static'

const InnerForm = props => {
  const {
    values,
    errors,
    touched,
    handleChange,
    handleBlur,
    handleSubmit,
    isSubmitting,
    params
  } = props
  return (
    <FormWrapper>
      {values != params ? <ConfirmClose /> : null}
      <Form onSubmit={handleSubmit}>
        <Fieldset section="leader">
          <Field
            name="leader_name"
            label="Full Name"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_name}
            error={touched.leader_name && errors.leader_name}
          />
          <Field
            name="leader_email"
            label="Email"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_email}
            error={touched.leader_email && errors.leader_email}
          />
          <Field
            name="leader_birthday"
            label="Birthday"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_birthday}
            error={touched.leader_birthday && errors.leader_birthday}
            type="date"
          />
          <Field
            name="leader_year_in_school"
            label="Year in school"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_year_in_school || 'select'}
            error={
              touched.leader_year_in_school && errors.leader_year_in_school
            }
            type="select"
          >
            <option value="select">Select One</option>
            <option value="freshman">Freshman</option>
            <option value="sophomore">Sophomore</option>
            <option value="junior">Junior</option>
            <option value="senior">Senior</option>
            <option value="other_year">Other year</option>
          </Field>
          <Field
            name="leader_gender"
            label="Gender"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_gender || 'select'}
            error={touched.leader_gender && errors.leader_gender}
            type="select"
          >
            <option value="select">Select One</option>
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="genderqueer">Genderqueer</option>
            <option value="agender">Agender</option>
            <option value="other">Other</option>
          </Field>
          <Field
            name="leader_ethnicity"
            label="Ethnicity"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_ethnicity || 'select'}
            error={touched.leader_ethnicity && errors.leader_ethnicity}
            type="select"
          >
            <option value="select">Select One</option>
            <option value="hispanic_or_latino">Hispanic or Latino</option>
            <option value="white">White</option>
            <option value="black">Black</option>
            <option value="native_american_or_indian">
              Native American or American Indian
            </option>
            <option value="asian_or_pacific_islander">
              Asian or Pacific Islander
            </option>
            <option value="other_ethnicity">Other ethnicity</option>
          </Field>
          <Field
            name="leader_phone_number"
            label="Phone number"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_phone_number}
            error={touched.leader_phone_number && errors.leader_phone_number}
          />
          <Field
            name="leader_address"
            label="Your full address (include city, state/province, country)"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_address}
            error={touched.leader_address && errors.leader_address}
            type="textarea"
          />
        </Fieldset>
        <Fieldset section="presence">
          <Field
            name="presence_personal_website"
            label="Personal website URL"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_personal_website}
            error={
              touched.presence_personal_website &&
              errors.presence_personal_website
            }
            optional
          />
          <Field
            name="presence_github_url"
            label="GitHub URL"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_github_url}
            error={touched.presence_github_url && errors.presence_github_url}
            optional
          />
          <Field
            name="presence_linkedin_url"
            label="LinkedIn URL"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_linkedin_url}
            error={
              touched.presence_linkedin_url && errors.presence_linkedin_url
            }
            optional
          />
          <Field
            name="presence_facebook_url"
            label="Facebook URL"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_facebook_url}
            error={
              touched.presence_facebook_url && errors.presence_facebook_url
            }
            optional
          />
          <Field
            name="presence_twitter_url"
            label="Twitter URL"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_twitter_url}
            error={touched.presence_twitter_url && errors.presence_twitter_url}
            optional
          />
        </Fieldset>
        <Fieldset section="skills">
          <Field
            name="skills_system_hacked"
            label="Please tell us about the time you most successfully hacked some (non-computer) system to your advantage."
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.skills_system_hacked}
            error={touched.skills_system_hacked && errors.skills_system_hacked}
            type="textarea"
          />
          <Field
            name="skills_impressive_achievement"
            label="Please tell us in one or two sentences about the most impressive thing you have built or achieved."
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.skills_impressive_achievement}
            error={
              touched.skills_impressive_achievement &&
              errors.skills_impressive_achievement
            }
            type="textarea"
          />
          <Field
            name="skills_is_technical"
            label="Are you a technical leader? (You are a programmer who can teach without outside assistance)"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.skills_is_technical || 'select'}
            error={touched.skills_is_technical && errors.skills_is_technical}
            type="select"
          >
            <option value="select" disabled>
              Select One
            </option>
            <option value="true">Yes</option>
            <option value="false">No</option>
          </Field>
        </Fieldset>
        <Container maxWidth={24}>
          <Submit value="Save Draft" disabled={isSubmitting} w={1} my={2} lg />
        </Container>
      </Form>
    </FormWrapper>
  )
}

const LeaderApplicationForm = withFormik({
  mapPropsToValues: props => props.params,
  enableReinitialize: true,
  handleSubmit: (data, { setSubmitting, setStatus, props, resetForm }) => {
    fetch(`${api}/v1/applicant_profiles/${props.id}`, {
      method: 'PATCH',
      headers: {
        Authorization: `Bearer ${props.authToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
      .then(res => {
        if (res.ok) {
          return res.json()
        } else {
          throw res
        }
      })
      .then(json => {
        alert('Saved!')
        setSubmitting(false)
        resetForm()
      })
      .catch(e => {
        console.error(e)
        alert(e)
        setSubmitting(false)
      })
  },
  displayName: 'LeaderApplicationForm'
})(InnerForm)

export default LeaderApplicationForm
<commit_msg>Clarify personal links in application<commit_after>import React from 'react'
import { api } from '../../data'
import { Container } from '@hackclub/design-system'
import {
  FormWrapper,
  Aside,
  ConfirmClose,
  Fieldset,
  Field,
  Submit,
  Form
} from '../components/Forms'
import { withFormik } from 'formik'
import { Link, Prompt } from 'react-static'

const InnerForm = props => {
  const {
    values,
    errors,
    touched,
    handleChange,
    handleBlur,
    handleSubmit,
    isSubmitting,
    params
  } = props
  return (
    <FormWrapper>
      {values != params ? <ConfirmClose /> : null}
      <Form onSubmit={handleSubmit}>
        <Fieldset section="leader">
          <Field
            name="leader_name"
            label="Full Name"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_name}
            error={touched.leader_name && errors.leader_name}
          />
          <Field
            name="leader_email"
            label="Email"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_email}
            error={touched.leader_email && errors.leader_email}
          />
          <Field
            name="leader_birthday"
            label="Birthday"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_birthday}
            error={touched.leader_birthday && errors.leader_birthday}
            type="date"
          />
          <Field
            name="leader_year_in_school"
            label="Year in school"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_year_in_school || 'select'}
            error={
              touched.leader_year_in_school && errors.leader_year_in_school
            }
            type="select"
          >
            <option value="select">Select One</option>
            <option value="freshman">Freshman</option>
            <option value="sophomore">Sophomore</option>
            <option value="junior">Junior</option>
            <option value="senior">Senior</option>
            <option value="other_year">Other year</option>
          </Field>
          <Field
            name="leader_gender"
            label="Gender"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_gender || 'select'}
            error={touched.leader_gender && errors.leader_gender}
            type="select"
          >
            <option value="select">Select One</option>
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="genderqueer">Genderqueer</option>
            <option value="agender">Agender</option>
            <option value="other">Other</option>
          </Field>
          <Field
            name="leader_ethnicity"
            label="Ethnicity"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_ethnicity || 'select'}
            error={touched.leader_ethnicity && errors.leader_ethnicity}
            type="select"
          >
            <option value="select">Select One</option>
            <option value="hispanic_or_latino">Hispanic or Latino</option>
            <option value="white">White</option>
            <option value="black">Black</option>
            <option value="native_american_or_indian">
              Native American or American Indian
            </option>
            <option value="asian_or_pacific_islander">
              Asian or Pacific Islander
            </option>
            <option value="other_ethnicity">Other ethnicity</option>
          </Field>
          <Field
            name="leader_phone_number"
            label="Phone number"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_phone_number}
            error={touched.leader_phone_number && errors.leader_phone_number}
          />
          <Field
            name="leader_address"
            label="Your full address (include city, state/province, country)"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leader_address}
            error={touched.leader_address && errors.leader_address}
            type="textarea"
          />
        </Fieldset>
        <Fieldset section="presence">
          <Field
            name="presence_personal_website"
            label="Personal website link"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_personal_website}
            error={
              touched.presence_personal_website &&
              errors.presence_personal_website
            }
            optional
          />
          <Field
            name="presence_github_url"
            label="GitHub link"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_github_url}
            error={touched.presence_github_url && errors.presence_github_url}
            optional
          />
          <Field
            name="presence_linkedin_url"
            label="LinkedIn link"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_linkedin_url}
            error={
              touched.presence_linkedin_url && errors.presence_linkedin_url
            }
            optional
          />
          <Field
            name="presence_facebook_url"
            label="Facebook link"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_facebook_url}
            error={
              touched.presence_facebook_url && errors.presence_facebook_url
            }
            optional
          />
          <Field
            name="presence_twitter_url"
            label="Twitter link"
            placeholder="https://"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.presence_twitter_url}
            error={touched.presence_twitter_url && errors.presence_twitter_url}
            optional
          />
        </Fieldset>
        <Fieldset section="skills">
          <Field
            name="skills_system_hacked"
            label="Please tell us about the time you most successfully hacked some (non-computer) system to your advantage."
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.skills_system_hacked}
            error={touched.skills_system_hacked && errors.skills_system_hacked}
            type="textarea"
          />
          <Field
            name="skills_impressive_achievement"
            label="Please tell us in one or two sentences about the most impressive thing you have built or achieved."
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.skills_impressive_achievement}
            error={
              touched.skills_impressive_achievement &&
              errors.skills_impressive_achievement
            }
            type="textarea"
          />
          <Field
            name="skills_is_technical"
            label="Are you a technical leader? (You are a programmer who can teach without outside assistance)"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.skills_is_technical || 'select'}
            error={touched.skills_is_technical && errors.skills_is_technical}
            type="select"
          >
            <option value="select" disabled>
              Select One
            </option>
            <option value="true">Yes</option>
            <option value="false">No</option>
          </Field>
        </Fieldset>
        <Container maxWidth={24}>
          <Submit value="Save Draft" disabled={isSubmitting} w={1} my={2} lg />
        </Container>
      </Form>
    </FormWrapper>
  )
}

const LeaderApplicationForm = withFormik({
  mapPropsToValues: props => props.params,
  enableReinitialize: true,
  handleSubmit: (data, { setSubmitting, setStatus, props, resetForm }) => {
    fetch(`${api}/v1/applicant_profiles/${props.id}`, {
      method: 'PATCH',
      headers: {
        Authorization: `Bearer ${props.authToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
      .then(res => {
        if (res.ok) {
          return res.json()
        } else {
          throw res
        }
      })
      .then(json => {
        alert('Saved!')
        setSubmitting(false)
        resetForm()
      })
      .catch(e => {
        console.error(e)
        alert(e)
        setSubmitting(false)
      })
  },
  displayName: 'LeaderApplicationForm'
})(InnerForm)

export default LeaderApplicationForm
<|endoftext|>


<commit_before>/**
 * Engine2D game engine.
 */

/**
 * Engine2D namespace
 */
var Engine2D = {
    TYPE: {
        RECT: 1,
        CIRCLE: 2
    },
    /**
     * Engine2D game scene constructor.
     */
    GameScene: function() {
        var self = this;
        self.objects = {};
        /**
         * Adds game object to scene.
         */
        var isValidID = function(objectId) {
            var pass;
            for (var i in self.objects) {
                if (self.objects[i].id == objectId) pass = true;
            }
            if (!!pass)
                return true;
            else
                return false;
        };
        self.addObject = function(gameObject) {
            var pass;
            for (var i in Engine2D.TYPE) {
                if (gameObject.type == Engine2D.TYPE[i]) pass = true;
            }
            if (!!pass)
                self.objects[gameObject.id] = gameObject;
            else
                throw new TypeError("\"" + gameObject.type + "\" is not a valid Engine2D game object type.");
        };
        /**
         * Disables a game object.
         */
        self.disableObject = function(objectId) {
            if (isValidID(objectId))
                self.objects[objectId].alive = false;
            else
                throw new ReferenceError("Object \"" + objectId + "\" either doesn't exist, or hasn't been added to the scene.");
        };
        /**
         * Enables a game object.
         */
        self.enableObject = function(objectId) {
            if (isValidID(objectId))
                self.objects[objectId].alive = true;
            else
                throw new ReferenceError("Object \"" + objectId + "\" either doesn't exist, or hasn't been added to the scene.");
        };
        /**
         * Permanently destroys a game object.
         */
        self.destroyObject = function(objectId) {
            if (isValidID(objectId))
                delete self.objects[objectId];
            else
                throw new ReferenceError("Object \"" + objectId + "\" either doesn't exist, or hasn't been added to the scene.");
        };
    },
    /**
     * Engine2D rectangle constructor.
     */
    Rect: function(options) {
        var self = this;
        self.id = options.id || Engine2D.randomID();
        self.type = Engine2D.TYPE.RECT;
        self.alive = options.alive || true;
        self.size = {}, self.position = {};
        self.size.width = options.width || 0;
        self.size.height = options.height || 0;
        self.position.x = options.x || 0;
        self.position.y = options.y || 0;
    },
    /**
     * Engine2D circle constructor.
     */
    Circle: function(options) {
        var self = this;
        self.id = options.id || Engine2D.randomID();
        self.type = Engine2D.TYPE.CIRCLE;
        self.alive = options.alive || true;
        self.size = {}, self.position = {};
        self.size.radius = options.radius || 0;
        self.position.x = options.x || 0;
        self.position.y = options.y || 0;
    },
    /**
     * Used to generate random object IDs for Engine2D game objects.
     */
    randomID: function() {
        var opts = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", out = "";
        var i = 0;
        while (i < 5) {
            i++;
            out += opts[Math.floor(Math.random() * opts.length)];
        }
        return out;
    }
};<commit_msg>Fixed documentation error<commit_after>/**
 * Engine2D game engine.
 */

/**
 * Engine2D namespace
 */
var Engine2D = {
    TYPE: {
        RECT: 1,
        CIRCLE: 2
    },
    /**
     * Engine2D game scene constructor.
     */
    GameScene: function() {
        var self = this;
        self.objects = {};
        /**
         * Checks whether a game object ID is valid or not.
         * Private.
         */
        var isValidID = function(objectId) {
            var pass;
            for (var i in self.objects) {
                if (self.objects[i].id == objectId) pass = true;
            }
            if (!!pass)
                return true;
            else
                return false;
        };
        /**
         * Adds game object to scene.
         */
        self.addObject = function(gameObject) {
            var pass;
            for (var i in Engine2D.TYPE) {
                if (gameObject.type == Engine2D.TYPE[i]) pass = true;
            }
            if (!!pass)
                self.objects[gameObject.id] = gameObject;
            else
                throw new TypeError("\"" + gameObject.type + "\" is not a valid Engine2D game object type.");
        };
        /**
         * Disables a game object.
         */
        self.disableObject = function(objectId) {
            if (isValidID(objectId))
                self.objects[objectId].alive = false;
            else
                throw new ReferenceError("Object \"" + objectId + "\" either doesn't exist, or hasn't been added to the scene.");
        };
        /**
         * Enables a game object.
         */
        self.enableObject = function(objectId) {
            if (isValidID(objectId))
                self.objects[objectId].alive = true;
            else
                throw new ReferenceError("Object \"" + objectId + "\" either doesn't exist, or hasn't been added to the scene.");
        };
        /**
         * Permanently destroys a game object.
         */
        self.destroyObject = function(objectId) {
            if (isValidID(objectId))
                delete self.objects[objectId];
            else
                throw new ReferenceError("Object \"" + objectId + "\" either doesn't exist, or hasn't been added to the scene.");
        };
    },
    /**
     * Engine2D rectangle constructor.
     */
    Rect: function(options) {
        var self = this;
        self.id = options.id || Engine2D.randomID();
        self.type = Engine2D.TYPE.RECT;
        self.alive = options.alive || true;
        self.size = {}, self.position = {};
        self.size.width = options.width || 0;
        self.size.height = options.height || 0;
        self.position.x = options.x || 0;
        self.position.y = options.y || 0;
    },
    /**
     * Engine2D circle constructor.
     */
    Circle: function(options) {
        var self = this;
        self.id = options.id || Engine2D.randomID();
        self.type = Engine2D.TYPE.CIRCLE;
        self.alive = options.alive || true;
        self.size = {}, self.position = {};
        self.size.radius = options.radius || 0;
        self.position.x = options.x || 0;
        self.position.y = options.y || 0;
    },
    /**
     * Used to generate random object IDs for Engine2D game objects.
     */
    randomID: function() {
        var opts = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", out = "";
        var i = 0;
        while (i < 5) {
            i++;
            out += opts[Math.floor(Math.random() * opts.length)];
        }
        return out;
    }
};<|endoftext|>


<commit_before>import map from 'lodash.map'
import SQLiteResult from './SQLiteResult'
import zipObject from 'lodash.zipobject'
import {NativeModules, Platform} from 'react-native'
const {RNSqlite2} = NativeModules

function massageError(err) {
  return typeof err === 'string' ? new Error(err) : err
}

function SQLiteDatabase(name) {
  this._name = name
}

function dearrayifyRow(res) {
  // use a compressed array format to send minimal data between
  // native and web layers
  var rawError = res[0]
  if (rawError) {
    return new SQLiteResult(massageError(res[0]))
  }
  var insertId = res[1]
  if (insertId === null) {
    insertId = void 0 // per the spec, should be undefined
  }
  var rowsAffected = res[2]
  var columns = res[3]
  var rows = unescapeForIOSAndAndroid(res[4] || [])
  var zippedRows = []
  for (var i = 0, len = rows.length; i < len; i++) {
    zippedRows.push(zipObject(columns, rows[i]))
  }

  // v8 likes predictable objects
  return new SQLiteResult(null, insertId, rowsAffected, zippedRows)
}

// send less data over the wire, use an array
function arrayifyQuery(query) {
  return [query.sql, escapeForIOSAndAndroid(query.args || [])]
}

// for avoiding strings truncated with '\u0000'
function escapeForIOSAndAndroid(args) {
  if (
    Platform.OS === 'android' ||
    Platform.OS === 'ios' ||
    Platform.OS === 'macos'
  ) {
    return map(args, escapeBlob)
  } else {
    return args
  }
}

function escapeBlob(data) {
  if (typeof data === 'string') {
    return data
      .replace(/\u0002/g, '\u0002\u0002')
      .replace(/\u0001/g, '\u0001\u0002')
      .replace(/\u0000/g, '\u0001\u0001')
  } else {
    return data
  }
}

function unescapeForIOSAndAndroid(rows) {
  if (Platform.OS === 'android' || Platform.OS === 'ios') {
    return map(rows, function (row) {
      return map(row, unescapeBlob)
    })
  } else {
    return rows
  }
}

function unescapeBlob(data) {
  if (typeof data === 'string') {
    return data
      .replace(/\u0001\u0001/g, '\u0000')
      .replace(/\u0001\u0002/g, '\u0001')
      .replace(/\u0002\u0002/g, '\u0002')
  } else {
    return data
  }
}

SQLiteDatabase.prototype.exec = function exec(queries, readOnly, callback) {
  function onSuccess(rawResults) {
    var results = map(rawResults, dearrayifyRow)
    callback(null, results)
  }

  function onError(err) {
    callback(massageError(err))
  }

  RNSqlite2.exec(this._name, map(queries, arrayifyQuery), readOnly).then(
    onSuccess,
    onError
  )
}

export default SQLiteDatabase
<commit_msg>chore(prettier): format<commit_after>import map from 'lodash.map'
import SQLiteResult from './SQLiteResult'
import zipObject from 'lodash.zipobject'
import { NativeModules, Platform } from 'react-native'
const { RNSqlite2 } = NativeModules

function massageError(err) {
  return typeof err === 'string' ? new Error(err) : err
}

function SQLiteDatabase(name) {
  this._name = name
}

function dearrayifyRow(res) {
  // use a compressed array format to send minimal data between
  // native and web layers
  var rawError = res[0]
  if (rawError) {
    return new SQLiteResult(massageError(res[0]))
  }
  var insertId = res[1]
  if (insertId === null) {
    insertId = void 0 // per the spec, should be undefined
  }
  var rowsAffected = res[2]
  var columns = res[3]
  var rows = unescapeForIOSAndAndroid(res[4] || [])
  var zippedRows = []
  for (var i = 0, len = rows.length; i < len; i++) {
    zippedRows.push(zipObject(columns, rows[i]))
  }

  // v8 likes predictable objects
  return new SQLiteResult(null, insertId, rowsAffected, zippedRows)
}

// send less data over the wire, use an array
function arrayifyQuery(query) {
  return [query.sql, escapeForIOSAndAndroid(query.args || [])]
}

// for avoiding strings truncated with '\u0000'
function escapeForIOSAndAndroid(args) {
  if (
    Platform.OS === 'android' ||
    Platform.OS === 'ios' ||
    Platform.OS === 'macos'
  ) {
    return map(args, escapeBlob)
  } else {
    return args
  }
}

function escapeBlob(data) {
  if (typeof data === 'string') {
    return data
      .replace(/\u0002/g, '\u0002\u0002')
      .replace(/\u0001/g, '\u0001\u0002')
      .replace(/\u0000/g, '\u0001\u0001')
  } else {
    return data
  }
}

function unescapeForIOSAndAndroid(rows) {
  if (Platform.OS === 'android' || Platform.OS === 'ios') {
    return map(rows, function (row) {
      return map(row, unescapeBlob)
    })
  } else {
    return rows
  }
}

function unescapeBlob(data) {
  if (typeof data === 'string') {
    return data
      .replace(/\u0001\u0001/g, '\u0000')
      .replace(/\u0001\u0002/g, '\u0001')
      .replace(/\u0002\u0002/g, '\u0002')
  } else {
    return data
  }
}

SQLiteDatabase.prototype.exec = function exec(queries, readOnly, callback) {
  function onSuccess(rawResults) {
    var results = map(rawResults, dearrayifyRow)
    callback(null, results)
  }

  function onError(err) {
    callback(massageError(err))
  }

  RNSqlite2.exec(this._name, map(queries, arrayifyQuery), readOnly).then(
    onSuccess,
    onError
  )
}

export default SQLiteDatabase
<|endoftext|>


<commit_before>var FontWatchRunnerTest = TestCase('FontWatchRunnerTest');

FontWatchRunnerTest.prototype.setUp = function() {
  var self = this;

  this.fontFamily_ = 'fontFamily1';
  this.fontDescription_ = 'n4';

  this.fontActiveCalled_ = 0;
  this.fontActive_ = {};
  this.fontInactiveCalled_ = 0;
  this.fontInactive_ = {};
  this.activeCallback_ = function(fontFamily, fontDescription) {
    self.fontActiveCalled_++;
    self.fontActive_[fontFamily + ' ' + fontDescription] = true;
  };
  this.inactiveCallback_ = function(fontFamily, fontDescription) {
    self.fontInactiveCalled_++;
    self.fontInactive_[fontFamily + ' ' + fontDescription] = true;
  };

  this.createElementCalled_ = 0;
  this.createdElements_ = [];
  this.insertIntoCalled_ = 0;
  this.removeElementCalled_ = 0;
  this.fakeDomHelper_ = {
    createElement: function(name, attrs, innerHtml) {
      self.createElementCalled_++;
      self.createdElements_.push({
        'name': name,
        'attrs': attrs,
        'innerHtml': innerHtml
      });

      var element = document.createElement(name);

      for (var attr in attrs) {
        element.setAttribute(attr, attrs[attr]);
      }
      element.innerHTML = innerHtml;
      return element;
    },
    insertInto: function(name, el) {
      self.insertIntoCalled_++;
    },
    removeElement: function(el) {
      self.removeElementCalled_++;
    }
  };

  this.timesToCheckWidthsBeforeChange_ = 0;
  this.fakeFontSizer_ = {
    getWidth: function(el) {
      if (el.style.fontFamily.indexOf(self.fontFamily_) != -1) {
        // This is a font stack with fontFamily included (not just fallbacks)
        if (self.timesToCheckWidthsBeforeChange_ <= 0) {
          // Decrement by 0.5 because we're checking two separate font stacks each iteration
          self.timesToCheckWidthsBeforeChange_ -= 0.5;
          return 2;
        } else {
          // Decrement by 0.5 because we're checking two separate font stacks each iteration
          self.timesToCheckWidthsBeforeChange_ -= 0.5;
          return 1;
        }
      } else {
        return 1;
      }
    }
  };

  this.timesToGetTimeBeforeTimeout_ = 10;
  this.fakeGetTime_ = function() {
    if (self.timesToGetTimeBeforeTimeout_ <= 0) {
      return 6000;
    } else {
      self.timesToGetTimeBeforeTimeout_--;
      return 1;
    }
  };

  this.asyncCount_ = 0;
  this.fakeAsyncCall_ = function(func, timeout) {
    self.asyncCount_++;
    func();
  };

};

FontWatchRunnerTest.prototype.testWatchFontAlreadyLoaded = function() {
  this.timesToCheckWidthsBeforeChange_ = 0;
  this.timesToGetTimeBeforeTimeout_ = 10;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_);

  fontWatchRunner.start();

  assertEquals(1, this.asyncCount_);

  assertEquals(1, this.fontActiveCalled_);
  assertEquals(true, this.fontActive_['fontFamily1 n4']);
  assertEquals(0, this.fontInactiveCalled_);
};

FontWatchRunnerTest.prototype.testWatchFontWaitForLoadActive = function() {
  this.timesToCheckWidthsBeforeChange_ = 3;
  this.timesToGetTimeBeforeTimeout_ = 10;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_);

  fontWatchRunner.start();

  assertEquals(4, this.asyncCount_);

  assertEquals(1, this.fontActiveCalled_);
  assertEquals(true, this.fontActive_['fontFamily1 n4']);
  assertEquals(0, this.fontInactiveCalled_);
};

FontWatchRunnerTest.prototype.testWatchFontWaitForLoadInactive = function() {
  this.timesToCheckWidthsBeforeChange_ = 10;
  this.timesToGetTimeBeforeTimeout_ = 5;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_);

  fontWatchRunner.start();

  assertEquals(4, this.asyncCount_);

  assertEquals(0, this.fontActiveCalled_);
  assertEquals(1, this.fontInactiveCalled_);
  assertEquals(true, this.fontInactive_['fontFamily1 n4']);
};

FontWatchRunnerTest.prototype.testDomWithDefaultTestString = function() {
  this.timesToCheckWidthsBeforeChange_ = 3;
  this.timesToGetTimeBeforeTimeout_ = 10;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_);

  fontWatchRunner.start();

  assertEquals(4, this.createElementCalled_);
  assertEquals('span', this.createdElements_[0]['name']);
  assertEquals(-1, this.createdElements_[0]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[0]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_A));
  assertEquals('BESbswy', this.createdElements_[0]['innerHtml']);
  assertEquals('span', this.createdElements_[1]['name']);
  assertEquals(-1, this.createdElements_[1]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[1]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_B));
  assertEquals('BESbswy', this.createdElements_[1]['innerHtml']);
  assertEquals('span', this.createdElements_[2]['name']);
  assertNotEquals(-1, this.createdElements_[2]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[2]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_A));
  assertEquals('BESbswy', this.createdElements_[2]['innerHtml']);
  assertEquals('span', this.createdElements_[3]['name']);
  assertNotEquals(-1, this.createdElements_[3]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[3]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_B));
  assertEquals('BESbswy', this.createdElements_[3]['innerHtml']);
  assertEquals(4, this.insertIntoCalled_);
  assertEquals(4, this.removeElementCalled_);
};

FontWatchRunnerTest.prototype.testDomWithNotDefaultTestString = function() {
  this.timesToCheckWidthsBeforeChange_ = 3;
  this.timesToGetTimeBeforeTimeout_ = 10;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_, 'testString');

  fontWatchRunner.start();

  assertEquals(4, this.createElementCalled_);
  assertEquals('span', this.createdElements_[0]['name']);
  assertEquals(-1, this.createdElements_[0]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[0]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_A));
  assertEquals('testString', this.createdElements_[0]['innerHtml']);
  assertEquals('span', this.createdElements_[1]['name']);
  assertEquals(-1, this.createdElements_[1]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[1]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_B));
  assertEquals('testString', this.createdElements_[1]['innerHtml']);
  assertEquals('span', this.createdElements_[2]['name']);
  assertNotEquals(-1, this.createdElements_[2]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[2]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_A));
  assertEquals('testString', this.createdElements_[2]['innerHtml']);
  assertEquals('span', this.createdElements_[3]['name']);
  assertNotEquals(-1, this.createdElements_[3]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[3]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_B));
  assertEquals('testString', this.createdElements_[3]['innerHtml']);
  assertEquals(4, this.insertIntoCalled_);
  assertEquals(4, this.removeElementCalled_);

};
<commit_msg>Added an accurate model of the broken way webkit used to handle fallback fonts while loading webfonts. Also added two new tests that test for the case where a font is parsed and applied quickly and slowly (where the slow one currently fails.)<commit_after>var FontWatchRunnerTest = TestCase('FontWatchRunnerTest');

FontWatchRunnerTest.prototype.setUp = function() {
  var self = this;

  this.fontFamily_ = 'fontFamily1';
  this.fontDescription_ = 'n4';

  this.fontActiveCalled_ = 0;
  this.fontActive_ = {};
  this.fontInactiveCalled_ = 0;
  this.fontInactive_ = {};
  this.activeCallback_ = function(fontFamily, fontDescription) {
    self.fontActiveCalled_++;
    self.fontActive_[fontFamily + ' ' + fontDescription] = true;
  };
  this.inactiveCallback_ = function(fontFamily, fontDescription) {
    self.fontInactiveCalled_++;
    self.fontInactive_[fontFamily + ' ' + fontDescription] = true;
  };

  this.createElementCalled_ = 0;
  this.createdElements_ = [];
  this.insertIntoCalled_ = 0;
  this.removeElementCalled_ = 0;
  this.fakeDomHelper_ = {
    createElement: function(name, attrs, innerHtml) {
      self.createElementCalled_++;
      self.createdElements_.push({
        'name': name,
        'attrs': attrs,
        'innerHtml': innerHtml
      });

      var element = document.createElement(name);

      for (var attr in attrs) {
        element.setAttribute(attr, attrs[attr]);
      }
      element.innerHTML = innerHtml;
      return element;
    },
    insertInto: function(name, el) {
      self.insertIntoCalled_++;
    },
    removeElement: function(el) {
      self.removeElementCalled_++;
    }
  };

  this.timesToCheckWidthsBeforeChange_ = 0;
  this.fakeFontSizer_ = {
    getWidth: function(el) {
      if (el.style.fontFamily.indexOf(self.fontFamily_) != -1) {
        // This is a font stack with fontFamily included (not just fallbacks)
        if (self.timesToCheckWidthsBeforeChange_ <= 0) {
          // Decrement by 0.5 because we're checking two separate font stacks each iteration
          self.timesToCheckWidthsBeforeChange_ -= 0.5;
          return 2;
        } else {
          // Decrement by 0.5 because we're checking two separate font stacks each iteration
          self.timesToCheckWidthsBeforeChange_ -= 0.5;
          return 1;
        }
      } else {
        return 1;
      }
    }
  };

  /**
   * This accurately models the way webkit used to handle
   * fallback fonts while loading web fonts. Even though
   * this Webkit bug is now patched, we still have a large
   * portion of our users using old webkit builds.
   *
   * See: https://bugs.webkit.org/show_bug.cgi?id=76684
   */
  this.timesToDelayChangedWidthWebkit_ = 1;
  this.fakeWebkitFontSizer_ = {
    getWidth: function(el) {
      if (el.style.fontFamily.indexOf(self.fontFamily_) !== -1) {
        if (self.timesToDelayChangedWidthWebkit_ > 0) {
            self.timesToDelayChangedWidthWebkit_ -= 0.5;
            // Return the incorrect width for a certain number of cycles.
            // The actual number depends on how fast or how slow the font
            // is parsed and applied.
            return 2;
        } else {
            // Return the correct width
            return 1;
        }
      } else {
        // Return the default width
        return 1;
      }
    }
  };

  this.timesToGetTimeBeforeTimeout_ = 10;
  this.fakeGetTime_ = function() {
    if (self.timesToGetTimeBeforeTimeout_ <= 0) {
      return 6000;
    } else {
      self.timesToGetTimeBeforeTimeout_--;
      return 1;
    }
  };

  this.asyncCount_ = 0;
  this.fakeAsyncCall_ = function(func, timeout) {
    self.asyncCount_++;
    func();
  };

};

FontWatchRunnerTest.prototype.testWatchFontAlreadyLoaded = function() {
  this.timesToCheckWidthsBeforeChange_ = 0;
  this.timesToGetTimeBeforeTimeout_ = 10;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_);

  fontWatchRunner.start();

  assertEquals(1, this.asyncCount_);

  assertEquals(1, this.fontActiveCalled_);
  assertEquals(true, this.fontActive_['fontFamily1 n4']);
  assertEquals(0, this.fontInactiveCalled_);
};

FontWatchRunnerTest.prototype.testWatchFontWaitForLoadActive = function() {
  this.timesToCheckWidthsBeforeChange_ = 3;
  this.timesToGetTimeBeforeTimeout_ = 10;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_);

  fontWatchRunner.start();

  assertEquals(4, this.asyncCount_);

  assertEquals(1, this.fontActiveCalled_);
  assertEquals(true, this.fontActive_['fontFamily1 n4']);
  assertEquals(0, this.fontInactiveCalled_);
};

FontWatchRunnerTest.prototype.testWatchFontWaitForLoadInactive = function() {
  this.timesToCheckWidthsBeforeChange_ = 10;
  this.timesToGetTimeBeforeTimeout_ = 5;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_);

  fontWatchRunner.start();

  assertEquals(4, this.asyncCount_);

  assertEquals(0, this.fontActiveCalled_);
  assertEquals(1, this.fontInactiveCalled_);
  assertEquals(true, this.fontInactive_['fontFamily1 n4']);
};

FontWatchRunnerTest.prototype.testWatchFontWebkitWithFastFont = function() {
    this.timesToGetTimeBeforeTimeout_ = 10;
    this.timesToDelayChangedWidthWebkit_ = 1;

    var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
        this.inactiveCallback_, this.fakeDomHelper_, this.fakeWebkitFontSizer_,
        this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
        this.fontDescription_);

    fontWatchRunner.start();

    assertEquals(9, this.asyncCount_);
    assertEquals(1, this.fontInactiveCalled_);
    assertEquals(true, this.fontInactive_['fontFamily1 n4']);
};

FontWatchRunnerTest.prototype.testWatchFontWebkitWithSlowFont = function() {
  this.timesToGetTimeBeforeTimeout_ = 10;
  this.timesToDelayChangedWidthWebkit_ = 2;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeWebkitFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_);

  fontWatchRunner.start();

  assertEquals(9, this.asyncCount_);
  assertEquals(1, this.fontInactiveCalled_);
  assertEquals(true, this.fontInactive_['fontFamily1 n4']);
};

FontWatchRunnerTest.prototype.testDomWithDefaultTestString = function() {
  this.timesToCheckWidthsBeforeChange_ = 3;
  this.timesToGetTimeBeforeTimeout_ = 10;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_);

  fontWatchRunner.start();

  assertEquals(4, this.createElementCalled_);
  assertEquals('span', this.createdElements_[0]['name']);
  assertEquals(-1, this.createdElements_[0]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[0]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_A));
  assertEquals('BESbswy', this.createdElements_[0]['innerHtml']);
  assertEquals('span', this.createdElements_[1]['name']);
  assertEquals(-1, this.createdElements_[1]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[1]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_B));
  assertEquals('BESbswy', this.createdElements_[1]['innerHtml']);
  assertEquals('span', this.createdElements_[2]['name']);
  assertNotEquals(-1, this.createdElements_[2]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[2]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_A));
  assertEquals('BESbswy', this.createdElements_[2]['innerHtml']);
  assertEquals('span', this.createdElements_[3]['name']);
  assertNotEquals(-1, this.createdElements_[3]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[3]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_B));
  assertEquals('BESbswy', this.createdElements_[3]['innerHtml']);
  assertEquals(4, this.insertIntoCalled_);
  assertEquals(4, this.removeElementCalled_);
};

FontWatchRunnerTest.prototype.testDomWithNotDefaultTestString = function() {
  this.timesToCheckWidthsBeforeChange_ = 3;
  this.timesToGetTimeBeforeTimeout_ = 10;

  var fontWatchRunner = new webfont.FontWatchRunner(this.activeCallback_,
      this.inactiveCallback_, this.fakeDomHelper_, this.fakeFontSizer_,
      this.fakeAsyncCall_, this.fakeGetTime_, this.fontFamily_,
      this.fontDescription_, 'testString');

  fontWatchRunner.start();

  assertEquals(4, this.createElementCalled_);
  assertEquals('span', this.createdElements_[0]['name']);
  assertEquals(-1, this.createdElements_[0]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[0]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_A));
  assertEquals('testString', this.createdElements_[0]['innerHtml']);
  assertEquals('span', this.createdElements_[1]['name']);
  assertEquals(-1, this.createdElements_[1]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[1]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_B));
  assertEquals('testString', this.createdElements_[1]['innerHtml']);
  assertEquals('span', this.createdElements_[2]['name']);
  assertNotEquals(-1, this.createdElements_[2]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[2]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_A));
  assertEquals('testString', this.createdElements_[2]['innerHtml']);
  assertEquals('span', this.createdElements_[3]['name']);
  assertNotEquals(-1, this.createdElements_[3]['attrs']['style'].indexOf('fontFamily1'));
  assertNotEquals(-1, this.createdElements_[3]['attrs']['style'].indexOf(webfont.FontWatchRunner.DEFAULT_FONTS_B));
  assertEquals('testString', this.createdElements_[3]['innerHtml']);
  assertEquals(4, this.insertIntoCalled_);
  assertEquals(4, this.removeElementCalled_);

};
<|endoftext|>