text:
'use strict';
angular
	.module('softvApp')
	.factory('reportesFactory', function($http, $q, globalService, $localStorage) {
		var factory = {};
		var paths = {
			getOpcionsMenu: '/OpcionesCortesFacturas/GetOpcionesCortesFacturasList',
			getOptionsSubMenu: '/CatalogoReportesFac/GetCatalogoReportesFacList',
			getDistribuidores: '/DistribuidorReporte/GetDistribuidorReporteList',
			getPlazasByDistribuidor: '/PlazaReporte/GetPlazaDList',
			getCajas: '/Muestra_CajasCortes/GetMuestra_CajasCortesList',
			getSucursales: '/Muestra_SucursalesCortes/GetMuestra_SucursalesCortesList',
			getUsuarios: '/Muestra_UsuariosCortes/GetMuestra_UsuariosCortesList',
			getVendedores: '/Muestra_VendedoresCortes/GetMuestra_VendedoresCortesList',
			reporteGeneralCajas: '/ReporteCortesFac/GetReporteCortesFList',
			reportesPorCajero: '/ReporteCortesFac/GetReporteCortesCajeroList',
			reportesPorCaja: '/ReporteCortesFac/GetReporteCortesCajaList',
			reportesPorSucursal: '/ReporteCortesFac/GetReporteCortesSucursalList',
			reporteGeneralCajasFiscales: '/ReporteFacFis/GetReporteCortesGralFacFisList',
			reportesPorCajeroPuntos: '/ReporteCortesFac/GetReporteCortesCajeroConPuntosList',
			reportePorPlaza: '/ReportesCortesPlaza/GetReporteCortesPlazaCajasList',
			reportesPorSucursalFiscales: '/ReporteFacFis/GetReporteCortesSucFacFisList',
			reportesGeneralVentas: '/ReporteCortesFac/GetReporteCortesGralVentasList',
			reportesCajasVentas: '/ReporteCortesFac/GetReporteCortesCajasVentasList',
			reportesSucursalesVentas: '/ReporteCortesFac/GetReporteCortesSucursalVentasList',
			reportesCajeroVentas: '/ReporteCortesFac/GetReporteCortesCajeroVentasList',
			reportesPlazasVentas: '/ReportesCortesPlaza/GetReporteCortesPlazaVentasList',
			reportesCajeroPuntos: '/ReporteCortesFac/GetReporteCortesCajeroConPuntosVentasList',
			reportesGeneralFiscalesVentas: '/ReporteFacFis/GetReporteCortesGralFacFisVentasList',
			reportesPorSucursalFiscalesVentas: '/ReporteFacFis/GetReporteCortesSucFacFisVentasList',
			reportesPorVendedor: '/ReporteCortesFac/GetReporteCortesPorVendedorList',
			reportesGeneralResumen: '/ReporteCortesFac/GetReporteCortesGralResumenList',
			reportesCajeroResumen: '/ReporteCortesFac/GetReporteCortesCajeroResumenList',
			reporteSucursalesResumen: '/ReporteCortesFac/GetReporteCortesSucursalResumenList',
			reportesSucursalFisResumen: '/ReporteFacFis/GetReporteCortesSucFacFisResumenList',
			reportesCajeroPuntosResumen: '/ReporteCortesFac/GetReporteCortesCajeroConPuntosResumenList',
			reportesPlazaResumen: '/ReportesCortesPlaza/GetReporteCortesPlazaResumenList',
			//sucursales especiales
			muestraSucursalesEspeciales: '/SucursalesEspeciales/GetSucursalesEspecialesList',
			getOptionsEspeciales: '/OpcionesCortesFacturas/GetOpcionesCortesEspecialesFacList',
			getCatalogoOptionsEspeciales: '/CatalogoReportesFac/GetCatalogoRepCorteEspecialFacList',
			reporteGeneralEspeciales: '/ReporteCortesEspeciales/GetReporteCortesEspGralList',
			reporteSucursalEspeciales: '/ReporteCortesEspeciales/GetReporteCortesEspSucList',
			reporteFacturasFiscales: '/RepFacFisEspeciales/GetRepFacFisEspecialesGralList'
		};

		factory.getOpcionsMenu = function() {
			var deferred = $q.defer();
			var Parametros = {};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getOpcionsMenu, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.getOptionsSubMenu = function(option) {
			var deferred = $q.defer();
			var Parametros = {
				'Op': option
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getOptionsSubMenu, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.getDistribuidores = function() {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'IdUsuario': user
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getDistribuidores, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.getVendedores = function() {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'IdUsuario': user
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getVendedores, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.getPlazasByDistribuidor = function(objDist) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objDis': {
					'IdUsuario': user
				},
				'LstDis': objDist
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getPlazasByDistribuidor, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.getCajas = function() {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'IdUsuario': user
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getCajas, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.getSucursales = function() {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'IdUsuario': user
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getSucursales, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.getUsuarios = function() {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'IdUsuario': user
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getUsuarios, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reporteGeneralCajas = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reporteGeneralCajas, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesPorCajero = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Cajera': obj.cajera
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesPorCajero, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesPorCaja = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Caja': obj.caja
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesPorCaja, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesPorSucursal = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Sucursal': obj.sucursal
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesPorSucursal, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reporteGeneralCajasFiscales = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reporteGeneralCajasFiscales, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesPorCajeroPuntos = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Cajera': obj.cajera
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesPorCajeroPuntos, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportePorPlaza = function(obj) {
			var deferred = $q.defer();
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportePorPlaza, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesPorSucursalFiscales = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'Sucursal': obj.sucursal,
					'Resumen': obj.resumen,
					'IdUsuario': user
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesPorSucursalFiscales, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesGeneralVentas = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesGeneralVentas, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesCajasVentas = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Caja': obj.caja
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesCajasVentas, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesSucursalesVentas = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Sucursal': obj.sucursal
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesSucursalesVentas, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesCajeroVentas = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Cajera': obj.cajera
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesCajeroVentas, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesPlazasVentas = function(obj) {
			var deferred = $q.defer();
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesPlazasVentas, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesCajeroPuntos = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Cajera': obj.cajera
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesCajeroPuntos, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesGeneralFiscalesVentas = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesGeneralFiscalesVentas, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesPorSucursalFiscalesVentas = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'Sucursal': obj.sucursal,
					'Resumen': obj.resumen,
					'IdUsuario': user
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesPorSucursalFiscalesVentas, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesPorVendedor = function(obj) {
			var deferred = $q.defer();
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'Resumen': obj.resumen,
					'Vendedor': obj.vendedor
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesPorVendedor, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesGeneralResumen = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesGeneralResumen, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesCajeroResumen = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Cajera': obj.cajera
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesCajeroResumen, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reporteSucursalesResumen = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Sucursal': obj.sucursal
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			console.log(Parametros);
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reporteSucursalesResumen, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesSucursalFisResumen = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Sucursal': obj.sucursal,
					'IdUsuario': user,
					'Resumen': obj.resumen
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesSucursalFisResumen, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesCajeroPuntosResumen = function(obj) {
			var deferred = $q.defer();
			var user = $localStorage.currentUser.idUsuario;
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen,
					'Cajera': obj.cajera
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesCajeroPuntosResumen, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		factory.reportesPlazaResumen = function(obj) {
			var deferred = $q.defer();
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
				},
				'lstPlaza': obj.objPlaza,
				'lstDis': obj.objdistribuidores
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reportesPlazaResumen, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});
			return deferred.promise;
		};

		//Sucursales especiales

		factory.muestraSucursalesEspeciales = function() {
			var deferred = $q.defer();
			var Parametros = {

			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.muestraSucursalesEspeciales, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.getOptionsEspeciales = function() {
			var deferred = $q.defer();
			var Parametros = {};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getOptionsEspeciales, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.getCatalogoOptionsEspeciales = function(op) {
			var deferred = $q.defer();
			var Parametros = {
				'Op': op
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.getCatalogoOptionsEspeciales, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.reporteGeneralEspeciales = function(obj) {
			var user = $localStorage.currentUser.idUsuario;
			var deferred = $q.defer();
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user
				},
				'lstSuc': obj.objsucursales
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reporteGeneralEspeciales, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.reporteSucursalEspeciales = function(obj) {
			var user = $localStorage.currentUser.idUsuario;
			var deferred = $q.defer();
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'Ordenar': obj.status,
					'IdUsuario': user,
					'Resumen': obj.resumen
				},
				'lstSuc': obj.objsucursales
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reporteSucursalEspeciales, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		factory.reporteFacturasFiscales = function(obj) {
			var user = $localStorage.currentUser.idUsuario;
			var deferred = $q.defer();
			var Parametros = {
				'objRep': {
					'Fi': obj.fechaInicial,
					'Ff': obj.fechaFinal,
					'IdUsuario': user
				},

				'lstSuc': obj.objsucursales
			};
			var config = {
				headers: {
					'Authorization': $localStorage.currentUser.token
				}
			};
			$http.post(globalService.getUrl() + paths.reporteFacturasFiscales, JSON.stringify(Parametros), config).then(function(response) {
				deferred.resolve(response.data);
			}).catch(function(response) {
				deferred.reject(response.data);
			});

			return deferred.promise;
		};

		return factory;
	});


text:
package com.google.common.hash;

import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.truth.Truth.assertThat;

import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableSet;
import com.google.common.hash.BloomFilterStrategies.LockFreeBitArray;
import com.google.common.math.LongMath;
import com.google.common.primitives.Ints;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
import com.google.common.util.concurrent.Uninterruptibles;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import junit.framework.TestCase;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Tests for SimpleGenericBloomFilter and derived BloomFilter views.
 *
 * @author Dimitris Andreou
 */
public class BloomFilterTest extends TestCase {
  private static final int NUM_PUTS = 100_000;
  private static final ThreadLocal<Random> random =
      new ThreadLocal<Random>() {
        @Override
        protected Random initialValue() {
          return new Random();
        }
      };

  private static final int GOLDEN_PRESENT_KEY = random.get().nextInt();

  @AndroidIncompatible // OutOfMemoryError
  public void testLargeBloomFilterDoesntOverflow() {
    long numBits = Integer.MAX_VALUE;
    numBits++;

    LockFreeBitArray bitArray = new LockFreeBitArray(numBits);
    assertTrue(
        "BitArray.bitSize() must return a positive number, but was " + bitArray.bitSize(),
        bitArray.bitSize() > 0);

    // Ideally we would also test the bitSize() overflow of this BF, but it runs out of heap space
    // BloomFilter.create(Funnels.unencodedCharsFunnel(), 244412641, 1e-11);
  }

  /**
   * Asserts that {@link BloomFilter#approximateElementCount} is within 1 percent of the expected
   * value.
   */
  private static void assertApproximateElementCountGuess(BloomFilter<?> bf, int sizeGuess) {
    assertThat(bf.approximateElementCount()).isAtLeast((long) (sizeGuess * 0.99));
    assertThat(bf.approximateElementCount()).isAtMost((long) (sizeGuess * 1.01));
  }

  public void testCreateAndCheckMitz32BloomFilterWithKnownFalsePositives() {
    int numInsertions = 1000000;
    BloomFilter<String> bf =
        BloomFilter.create(
            Funnels.unencodedCharsFunnel(),
            numInsertions,
            0.03,
            BloomFilterStrategies.MURMUR128_MITZ_32);

    // Insert "numInsertions" even numbers into the BF.
    for (int i = 0; i < numInsertions * 2; i += 2) {
      bf.put(Integer.toString(i));
    }
    assertApproximateElementCountGuess(bf, numInsertions);

    // Assert that the BF "might" have all of the even numbers.
    for (int i = 0; i < numInsertions * 2; i += 2) {
      assertTrue(bf.mightContain(Integer.toString(i)));
    }

    // Now we check for known false positives using a set of known false positives.
    // (These are all of the false positives under 900.)
    ImmutableSet<Integer> falsePositives =
        ImmutableSet.of(
            49, 51, 59, 163, 199, 321, 325, 363, 367, 469, 545, 561, 727, 769, 773, 781);
    for (int i = 1; i < 900; i += 2) {
      if (!falsePositives.contains(i)) {
        assertFalse("BF should not contain " + i, bf.mightContain(Integer.toString(i)));
      }
    }

    // Check that there are exactly 29824 false positives for this BF.
    int knownNumberOfFalsePositives = 29824;
    int numFpp = 0;
    for (int i = 1; i < numInsertions * 2; i += 2) {
      if (bf.mightContain(Integer.toString(i))) {
        numFpp++;
      }
    }
    assertEquals(knownNumberOfFalsePositives, numFpp);
    double expectedReportedFpp = (double) knownNumberOfFalsePositives / numInsertions;
    double actualReportedFpp = bf.expectedFpp();
    assertEquals(expectedReportedFpp, actualReportedFpp, 0.00015);
  }

  public void testCreateAndCheckBloomFilterWithKnownFalsePositives64() {
    int numInsertions = 1000000;
    BloomFilter<String> bf =
        BloomFilter.create(
            Funnels.unencodedCharsFunnel(),
            numInsertions,
            0.03,
            BloomFilterStrategies.MURMUR128_MITZ_64);

    // Insert "numInsertions" even numbers into the BF.
    for (int i = 0; i < numInsertions * 2; i += 2) {
      bf.put(Integer.toString(i));
    }
    assertApproximateElementCountGuess(bf, numInsertions);

    // Assert that the BF "might" have all of the even numbers.
    for (int i = 0; i < numInsertions * 2; i += 2) {
      assertTrue(bf.mightContain(Integer.toString(i)));
    }

    // Now we check for known false positives using a set of known false positives.
    // (These are all of the false positives under 900.)
    ImmutableSet<Integer> falsePositives =
        ImmutableSet.of(15, 25, 287, 319, 381, 399, 421, 465, 529, 697, 767, 857);
    for (int i = 1; i < 900; i += 2) {
      if (!falsePositives.contains(i)) {
        assertFalse("BF should not contain " + i, bf.mightContain(Integer.toString(i)));
      }
    }

    // Check that there are exactly 30104 false positives for this BF.
    int knownNumberOfFalsePositives = 30104;
    int numFpp = 0;
    for (int i = 1; i < numInsertions * 2; i += 2) {
      if (bf.mightContain(Integer.toString(i))) {
        numFpp++;
      }
    }
    assertEquals(knownNumberOfFalsePositives, numFpp);
    double expectedReportedFpp = (double) knownNumberOfFalsePositives / numInsertions;
    double actualReportedFpp = bf.expectedFpp();
    assertEquals(expectedReportedFpp, actualReportedFpp, 0.00033);
  }

  public void testCreateAndCheckBloomFilterWithKnownUtf8FalsePositives64() {
    int numInsertions = 1000000;
    BloomFilter<String> bf =
        BloomFilter.create(
            Funnels.stringFunnel(UTF_8),
            numInsertions,
            0.03,
            BloomFilterStrategies.MURMUR128_MITZ_64);

    // Insert "numInsertions" even numbers into the BF.
    for (int i = 0; i < numInsertions * 2; i += 2) {
      bf.put(Integer.toString(i));
    }
    assertApproximateElementCountGuess(bf, numInsertions);

    // Assert that the BF "might" have all of the even numbers.
    for (int i = 0; i < numInsertions * 2; i += 2) {
      assertTrue(bf.mightContain(Integer.toString(i)));
    }

    // Now we check for known false positives using a set of known false positives.
    // (These are all of the false positives under 900.)
    ImmutableSet<Integer> falsePositives = ImmutableSet.of(129, 471, 723, 89, 751, 835, 871);
    for (int i = 1; i < 900; i += 2) {
      if (!falsePositives.contains(i)) {
        assertFalse("BF should not contain " + i, bf.mightContain(Integer.toString(i)));
      }
    }

    // Check that there are exactly 29763 false positives for this BF.
    int knownNumberOfFalsePositives = 29763;
    int numFpp = 0;
    for (int i = 1; i < numInsertions * 2; i += 2) {
      if (bf.mightContain(Integer.toString(i))) {
        numFpp++;
      }
    }
    assertEquals(knownNumberOfFalsePositives, numFpp);
    double expectedReportedFpp = (double) knownNumberOfFalsePositives / numInsertions;
    double actualReportedFpp = bf.expectedFpp();
    assertEquals(expectedReportedFpp, actualReportedFpp, 0.00033);
  }

  /** Sanity checking with many combinations of false positive rates and expected insertions */
  public void testBasic() {
    for (double fpr = 0.0000001; fpr < 0.1; fpr *= 10) {
      for (int expectedInsertions = 1; expectedInsertions <= 10000; expectedInsertions *= 10) {
        checkSanity(BloomFilter.create(HashTestUtils.BAD_FUNNEL, expectedInsertions, fpr));
      }
    }
  }

  public void testPreconditions() {
    try {
      BloomFilter.create(Funnels.unencodedCharsFunnel(), -1);
      fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
      BloomFilter.create(Funnels.unencodedCharsFunnel(), -1, 0.03);
      fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
      BloomFilter.create(Funnels.unencodedCharsFunnel(), 1, 0.0);
      fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
      BloomFilter.create(Funnels.unencodedCharsFunnel(), 1, 1.0);
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }

  public void testFailureWhenMoreThan255HashFunctionsAreNeeded() {
    try {
      int n = 1000;
      double p = 0.00000000000000000000000000000000000000000000000000000000000000000000000000000001;
      BloomFilter.create(Funnels.unencodedCharsFunnel(), n, p);
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }

  public void testNullPointers() {
    NullPointerTester tester = new NullPointerTester();
    tester.testAllPublicInstanceMethods(BloomFilter.create(Funnels.unencodedCharsFunnel(), 100));
    tester.testAllPublicStaticMethods(BloomFilter.class);
  }

  /** Tests that we never get an optimal hashes number of zero. */
  public void testOptimalHashes() {
    for (int n = 1; n < 1000; n++) {
      for (int m = 0; m < 1000; m++) {
        assertTrue(BloomFilter.optimalNumOfHashFunctions(n, m) > 0);
      }
    }
  }

  // https://code.google.com/p/guava-libraries/issues/detail?id=1781
  public void testOptimalNumOfHashFunctionsRounding() {
    assertEquals(7, BloomFilter.optimalNumOfHashFunctions(319, 3072));
  }

  /** Tests that we always get a non-negative optimal size. */
  public void testOptimalSize() {
    for (int n = 1; n < 1000; n++) {
      for (double fpp = Double.MIN_VALUE; fpp < 1.0; fpp += 0.001) {
        assertTrue(BloomFilter.optimalNumOfBits(n, fpp) >= 0);
      }
    }

    // some random values
    Random random = new Random(0);
    for (int repeats = 0; repeats < 10000; repeats++) {
      assertTrue(BloomFilter.optimalNumOfBits(random.nextInt(1 << 16), random.nextDouble()) >= 0);
    }

    // and some crazy values (this used to be capped to Integer.MAX_VALUE, now it can go bigger
    assertEquals(3327428144502L, BloomFilter.optimalNumOfBits(Integer.MAX_VALUE, Double.MIN_VALUE));
    try {
      BloomFilter<String> unused =
          BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);
      fail("we can't represent such a large BF!");
    } catch (IllegalArgumentException expected) {
      assertThat(expected).hasMessage("Could not create BloomFilter of 3327428144502 bits");
    }
  }

  @AndroidIncompatible // OutOfMemoryError
  public void testLargeNumberOfInsertions() {
    // We use horrible FPPs here to keep Java from OOM'ing
    BloomFilter<String> unused =
        BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.29);
    unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);
  }

  private static void checkSanity(BloomFilter<Object> bf) {
    assertFalse(bf.mightContain(new Object()));
    assertFalse(bf.apply(new Object()));
    for (int i = 0; i < 100; i++) {
      Object o = new Object();
      bf.put(o);
      assertTrue(bf.mightContain(o));
      assertTrue(bf.apply(o));
    }
  }

  public void testCopy() {
    BloomFilter<String> original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);
    BloomFilter<String> copy = original.copy();
    assertNotSame(original, copy);
    assertEquals(original, copy);
  }

  public void testExpectedFpp() {
    BloomFilter<Object> bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);
    double fpp = bf.expectedFpp();
    assertEquals(0.0, fpp);
    // usually completed in less than 200 iterations
    while (fpp != 1.0) {
      boolean changed = bf.put(new Object());
      double newFpp = bf.expectedFpp();
      // if changed, the new fpp is strictly higher, otherwise it is the same
      assertTrue(changed ? newFpp > fpp : newFpp == fpp);
      fpp = newFpp;
    }
  }

  @AndroidIncompatible // slow
  public void testBitSize() {
    double fpp = 0.03;
    for (int i = 1; i < 10000; i++) {
      long numBits = BloomFilter.optimalNumOfBits(i, fpp);
      int arraySize = Ints.checkedCast(LongMath.divide(numBits, 64, RoundingMode.CEILING));
      assertEquals(
          arraySize * Long.SIZE,
          BloomFilter.create(Funnels.unencodedCharsFunnel(), i, fpp).bitSize());
    }
  }

  public void testApproximateElementCount() {
    int numInsertions = 1000;
    BloomFilter<Integer> bf = BloomFilter.create(Funnels.integerFunnel(), numInsertions);
    bf.put(-1);
    for (int i = 0; i < numInsertions; i++) {
      bf.put(i);
    }
    assertApproximateElementCountGuess(bf, numInsertions);
  }

  public void testEquals_empty() {
    new EqualsTester()
        .addEqualityGroup(BloomFilter.create(Funnels.byteArrayFunnel(), 100, 0.01))
        .addEqualityGroup(BloomFilter.create(Funnels.byteArrayFunnel(), 100, 0.02))
        .addEqualityGroup(BloomFilter.create(Funnels.byteArrayFunnel(), 200, 0.01))
        .addEqualityGroup(BloomFilter.create(Funnels.byteArrayFunnel(), 200, 0.02))
        .addEqualityGroup(BloomFilter.create(Funnels.unencodedCharsFunnel(), 100, 0.01))
        .addEqualityGroup(BloomFilter.create(Funnels.unencodedCharsFunnel(), 100, 0.02))
        .addEqualityGroup(BloomFilter.create(Funnels.unencodedCharsFunnel(), 200, 0.01))
        .addEqualityGroup(BloomFilter.create(Funnels.unencodedCharsFunnel(), 200, 0.02))
        .testEquals();
  }

  public void testCollector() {
    BloomFilter<String> bf1 = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);
    bf1.put("1");
    bf1.put("2");

    assertEquals(
        bf1,
        Stream.of("1", "2")
            .collect(BloomFilter.toBloomFilter(Funnels.unencodedCharsFunnel(), 100)));
    assertEquals(
        bf1,
        Stream.of("2", "1")
            .collect(BloomFilter.toBloomFilter(Funnels.unencodedCharsFunnel(), 100)));
  }

  public void testEquals() {
    BloomFilter<String> bf1 = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);
    bf1.put("1");
    bf1.put("2");

    BloomFilter<String> bf2 = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);
    bf2.put("1");
    bf2.put("2");

    new EqualsTester().addEqualityGroup(bf1, bf2).testEquals();

    bf2.put("3");

    new EqualsTester().addEqualityGroup(bf1).addEqualityGroup(bf2).testEquals();
  }

  public void testEqualsWithCustomFunnel() {
    BloomFilter<Long> bf1 = BloomFilter.create(new CustomFunnel(), 100);
    BloomFilter<Long> bf2 = BloomFilter.create(new CustomFunnel(), 100);
    assertEquals(bf1, bf2);
  }

  public void testSerializationWithCustomFunnel() {
    SerializableTester.reserializeAndAssert(BloomFilter.create(new CustomFunnel(), 100));
  }

  private static final class CustomFunnel implements Funnel<Long> {
    @Override
    public void funnel(Long value, PrimitiveSink into) {
      into.putLong(value);
    }

    @Override
    public boolean equals(@NullableDecl Object object) {
      return (object instanceof CustomFunnel);
    }

    @Override
    public int hashCode() {
      return 42;
    }
  }

  public void testPutReturnValue() {
    for (int i = 0; i < 10; i++) {
      BloomFilter<String> bf = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);
      for (int j = 0; j < 10; j++) {
        String value = new Object().toString();
        boolean mightContain = bf.mightContain(value);
        boolean put = bf.put(value);
        assertTrue(mightContain != put);
      }
    }
  }

  public void testPutAll() {
    int element1 = 1;
    int element2 = 2;

    BloomFilter<Integer> bf1 = BloomFilter.create(Funnels.integerFunnel(), 100);
    bf1.put(element1);
    assertTrue(bf1.mightContain(element1));
    assertFalse(bf1.mightContain(element2));

    BloomFilter<Integer> bf2 = BloomFilter.create(Funnels.integerFunnel(), 100);
    bf2.put(element2);
    assertFalse(bf2.mightContain(element1));
    assertTrue(bf2.mightContain(element2));

    assertTrue(bf1.isCompatible(bf2));
    bf1.putAll(bf2);
    assertTrue(bf1.mightContain(element1));
    assertTrue(bf1.mightContain(element2));
    assertFalse(bf2.mightContain(element1));
    assertTrue(bf2.mightContain(element2));
  }

  public void testPutAllDifferentSizes() {
    BloomFilter<Integer> bf1 = BloomFilter.create(Funnels.integerFunnel(), 1);
    BloomFilter<Integer> bf2 = BloomFilter.create(Funnels.integerFunnel(), 10);

    try {
      assertFalse(bf1.isCompatible(bf2));
      bf1.putAll(bf2);
      fail();
    } catch (IllegalArgumentException expected) {
    }

    try {
      assertFalse(bf2.isCompatible(bf1));
      bf2.putAll(bf1);
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }

  public void testPutAllWithSelf() {
    BloomFilter<Integer> bf1 = BloomFilter.create(Funnels.integerFunnel(), 1);
    try {
      assertFalse(bf1.isCompatible(bf1));
      bf1.putAll(bf1);
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }

  public void testJavaSerialization() {
    BloomFilter<byte[]> bf = BloomFilter.create(Funnels.byteArrayFunnel(), 100);
    for (int i = 0; i < 10; i++) {
      bf.put(Ints.toByteArray(i));
    }

    BloomFilter<byte[]> copy = SerializableTester.reserialize(bf);
    for (int i = 0; i < 10; i++) {
      assertTrue(copy.mightContain(Ints.toByteArray(i)));
    }
    assertEquals(bf.expectedFpp(), copy.expectedFpp());

    SerializableTester.reserializeAndAssert(bf);
  }

  public void testCustomSerialization() throws Exception {
    Funnel<byte[]> funnel = Funnels.byteArrayFunnel();
    BloomFilter<byte[]> bf = BloomFilter.create(funnel, 100);
    for (int i = 0; i < 100; i++) {
      bf.put(Ints.toByteArray(i));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bf.writeTo(out);

    assertEquals(bf, BloomFilter.readFrom(new ByteArrayInputStream(out.toByteArray()), funnel));
  }

  /**
   * This test will fail whenever someone updates/reorders the BloomFilterStrategies constants. Only
   * appending a new constant is allowed.
   */
  public void testBloomFilterStrategies() {
    assertThat(BloomFilterStrategies.values()).hasLength(2);
    assertEquals(BloomFilterStrategies.MURMUR128_MITZ_32, BloomFilterStrategies.values()[0]);
    assertEquals(BloomFilterStrategies.MURMUR128_MITZ_64, BloomFilterStrategies.values()[1]);
  }

  public void testNoRaceConditions() throws Exception {
    final BloomFilter<Integer> bloomFilter =
        BloomFilter.create(Funnels.integerFunnel(), 15_000_000, 0.01);

    // This check has to be BEFORE the loop because the random insertions can
    // flip GOLDEN_PRESENT_KEY to true even if it wasn't explicitly inserted
    // (false positive).
    assertThat(bloomFilter.mightContain(GOLDEN_PRESENT_KEY)).isFalse();
    for (int i = 0; i < NUM_PUTS; i++) {
      bloomFilter.put(getNonGoldenRandomKey());
    }
    bloomFilter.put(GOLDEN_PRESENT_KEY);

    int numThreads = 12;
    final double safetyFalsePositiveRate = 0.1;
    final Stopwatch stopwatch = Stopwatch.createStarted();

    Runnable task =
        new Runnable() {
          @Override
          public void run() {
            do {
              // We can't have a GOLDEN_NOT_PRESENT_KEY because false positives are
              // possible! It's false negatives that can't happen.
              assertThat(bloomFilter.mightContain(GOLDEN_PRESENT_KEY)).isTrue();

              int key = getNonGoldenRandomKey();
              // We can't check that the key is mightContain() == false before the
              // put() because the key could have already been generated *or* the
              // bloom filter might say true even when it's not there (false
              // positive).
              bloomFilter.put(key);
              // False negative should *never* happen.
              assertThat(bloomFilter.mightContain(key)).isTrue();

              // If this check ever fails, that means we need to either bump the
              // number of expected insertions or don't run the test for so long.
              // Don't forget, the bloom filter slowly saturates over time and the
              // expected false positive probability goes up!
              assertThat(bloomFilter.expectedFpp()).isLessThan(safetyFalsePositiveRate);
            } while (stopwatch.elapsed(TimeUnit.SECONDS) < 1);
          }
        };

    List<Throwable> exceptions = runThreadsAndReturnExceptions(numThreads, task);

    assertThat(exceptions).isEmpty();
  }

  private static List<Throwable> runThreadsAndReturnExceptions(int numThreads, Runnable task) {
    List<Thread> threads = new ArrayList<>(numThreads);
    final List<Throwable> exceptions = new ArrayList<>(numThreads);
    for (int i = 0; i < numThreads; i++) {
      Thread thread = new Thread(task);
      thread.setUncaughtExceptionHandler(
          new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
              exceptions.add(e);
            }
          });
      threads.add(thread);
    }
    for (Thread t : threads) {
      t.start();
    }
    for (Thread t : threads) {
      Uninterruptibles.joinUninterruptibly(t);
    }
    return exceptions;
  }

  private static int getNonGoldenRandomKey() {
    int key;
    do {
      key = random.get().nextInt();
    } while (key == GOLDEN_PRESENT_KEY);
    return key;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.chinamobile.bcbsp.comm;

import com.chinamobile.bcbsp.api.Vertex;
import com.chinamobile.bcbsp.comm.io.util.WritableBSPMessages;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * The interface for Message Queues, which manages the message queues.
 */
public interface MessageManagerInterface {

  /**
   * Load message bucket.
   *
   * @param bucket
   *        int
   * @param superStep
   *        int
   */
  void loadBucketMessage(int bucket, int superStep);

  /**
   * Add a message into the incoming message queue with the destination vertexID
   * for index.
   *
   * @param srcPartitionDstBucket
   *        int
   * @param msg
   *        IMessage
   * @param superstep
   *        int
   */
  void incomeAMessage(int srcPartitionDstBucket, IMessage msg, int superstep);

  /**
   * Add a message into the incoming message queue with the destination vertexID
   * for index.
   *
   * @param srcPartitionDstBucket
   *        int
   * @param msg
   *        WritableBSPMessages
   * @param superstep
   *        int
   */
  void incomeAMessage(int srcPartitionDstBucket, WritableBSPMessages msg,
      int superstep);

  /**
   * Add a message into the outgoing message queue with the destination
   * "WorkerManagerName:Port" for index.
   *
   * @param dstPartitionBucket
   *        int
   * @param msg
   *        IMessage
   * @return int
   */
  int outgoAMessage(int dstPartitionBucket, IMessage msg);

  /**
   * Remove and return the incomed message queue for dstVertexID as the
   * destination.
   *
   * @param dstVertexID
   *        String
   * @return ConcurrentLinkedQueue<BSPMessage>
   */
  ArrayList<IMessage> removeIncomedQueue(String dstVertexID);

  /**
   * Get the current longest outgoing queue's index. If the outgoing queues are
   * all empty, return null.
   *
   * @return String
   */
  String getMaxOutgoingQueueIndex();

  /**
   * Get the next outgoing queue's index. This method will be used for traversal
   * of the outgoing queues' map looply. If the outgoing queues are all empty,
   * return null.
   *
   * @return String
   * @throws Exception
   *         e
   */
  String getNextOutgoingQueueIndex() throws Exception;

  /**
   * Remove and return the outgoing message queue for index as the queue's
   * index.
   *
   * @param destPartitionBucket
   *        int
   * @return ConcurrentLinkedQueue<BSPMessage>
   */
  WritableBSPMessages removeOutgoingQueue(int destPartitionBucket);

  /**
   * Get the current longest incoming queue's index. If the incoming queues are
   * all empty, return -1.
   *
   * @return int
   */
  String getMaxIncomingQueueIndex();

  /**
   * Remove and return the incoming message queue for dstVertexID as the queue's
   * index.
   *
   * @param dstVertexID
   *        String
   * @return ConcurrentLinkedQueue<BSPMessage>
   */
  ConcurrentLinkedQueue<IMessage> removeIncomingQueue(String dstVertexID);

  /**
   * Get the incoming queue's size.
   *
   * @param dstVertexID
   *        String
   * @return int
   */
  int getIncomingQueueSize(String dstVertexID);

  /**
   * Get the outgoing queue's size.
   *
   * @param dstPartitionBucket
   *        int
   * @return int
   */
  int getOutgoingQueueSize(int dstPartitionBucket);

  /**
   * Get the outgoing queue's size.
   */
  void exchangeIncomeQueues();

  /** Clear all message queues. */
  void clearAllQueues();

  /** Clear outgoing message queues. */
  void clearOutgoingQueues();

  /** Clear incoming message queues. */
  void clearIncomingQueues();

  /** Clear incomed message queues. */
  void clearIncomedQueues();

  /**
   * Get the outgoing queue's size.
   *
   * @return int
   */
  int getOutgoingQueuesSize();

  /**
   * Get the incoming queue's size.
   *
   * @return int
   */
  int getIncomingQueuesSize();

  /**
   * Get the incomed queue's size.
   *
   * @return int
   */
  int getIncomedQueuesSize();

  /** Show the information of memeory. */
  void showMemoryInfo();

  ArrayList<IMessage> getMessageQueue(String vertexID) throws IOException;

  /*
   * For SGA-Graph
   */
  int outgoVertex(int targetPartition, Vertex migrateVertex);

  WritableBSPMessages removeMirrorQueue(int targetPartition);

  void incomeMigrateVertex(WritableBSPMessages packedMessages);

  ArrayList<Vertex> getMigrateVertexQueue();

  int getMigrateQueueSize(int dstPartitionId);
}


text:
package org.apache.sling.models.factory;

/**
 * Exception which is triggered, whenever the post-construct method has thrown an exception.
 * The cause (accessible via {@link #getCause()}) is always the original exception being thrown from the post-construct method.
 */
public class PostConstructException extends ModelClassException {

    /**
     *
     */
    private static final long serialVersionUID = -2527043835215727726L;

    /**
     *
     * @param message some message
     * @param cause the original exception being thrown in the post-construct
     */
    public PostConstructException(String message, Throwable cause) {
        super(message, cause);
    }

}


text:
export interface Manifest {
  cache: Array<string>,
  fallback: {
    [key: string]: string;
  },
  network: Array<string>,
  settings: Array<string>,
  unknown: Array<string>,
  [key: string]: any;
}

export interface ManifestURLToHashes {
  [key: string]: HashToManifest,
}

export type HashToManifest = Map<string, Manifest>

export interface PageURLToManifestURL {
  [key: string]: string,
}

export interface ClientIdToHash {
  [key: string]: string,
}

export interface CachePopulatedCallback {
  (urlsCached: Array<string>): void;
}


text:
Imports System
Imports Microsoft.VisualStudio.TestTools.UnitTesting

Namespace Tests
  <TestClass()>
  Public Class TupleEnumertatorTests
    <TestMethod()>
    Public Sub Test1TupleIteration()
      Dim t As New Tuple(Of Integer)(- 1)
      Const expected As Integer = - 1
      Dim actual As Integer = 0
      For Each v As Integer In t
        actual += v
      Next
      Assert.AreEqual(expected, actual)
    End Sub

    <TestMethod()>
    Public Sub Test2TupleIteration()
      Dim t As New Tuple(Of Integer, Integer)(- 1, - 2)
      Const expected As Integer = - 3
      Dim actual As Integer = 0
      For Each v As Integer In t
        actual += v
      Next
      Assert.AreEqual(expected, actual)
    End Sub

    <TestMethod()>
    Public Sub Test3TupleIteration()
      Dim t As New Tuple(Of Integer, Integer, Integer)(- 1, - 2, - 3)
      Const expected As Integer = - 6
      Dim actual As Integer = 0
      For Each v As Integer In t
        actual += v
      Next
      Assert.AreEqual(expected, actual)
    End Sub

    <TestMethod()>
    Public Sub Test4TupleIteration()
      Dim t As New Tuple(Of Integer, Integer, Integer, Integer)(- 1, - 2, - 3, - 4)
      Const expected As Integer = - 10
      Dim actual As Integer = 0
      For Each v As Integer In t
        actual += v
      Next
      Assert.AreEqual(expected, actual)
    End Sub

    <TestMethod()>
    Public Sub Test5TupleIteration()
      Dim t As New Tuple(Of Integer, Integer, Integer, Integer, Integer)(- 1, - 2, - 3, - 4, - 5)
      Const expected As Integer = - 15
      Dim actual As Integer = 0
      For Each v As Integer In t
        actual += v
      Next
      Assert.AreEqual(expected, actual)
    End Sub

    <TestMethod()>
    Public Sub Test6TupleIteration()
      Dim t As New Tuple(Of Integer, Integer, Integer, Integer, Integer, Integer)(- 1, - 2, - 3, - 4, - 5, - 6)
      Const expected As Integer = - 21
      Dim actual As Integer = 0
      For Each v As Integer In t
        actual += v
      Next
      Assert.AreEqual(expected, actual)
    End Sub

    <TestMethod()>
    Public Sub Test7TupleIteration()
      Dim _
        t As _
          New Tuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer)(- 1, - 2, - 3, - 4, - 5, - 6, - 7)
      Const expected As Integer = - 28
      Dim actual As Integer = 0
      For Each v As Integer In t
        actual += v
      Next
      Assert.AreEqual(expected, actual)
    End Sub
  End Class
End Namespace


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace DnDPlayerCompanion.Characters
{
    public class ThreeFiveCharacter : BaseCharacter
    {

    }
}


text:
```
git clone -b news.academical.io git@github.com:LaxWorks/news.git news && cd $_

git submodule init && git submodule update

mkdir vendor && pushd $_
curl -L -O https://mirror.racket-lang.org/installers/6.7/racket-6.7-x86_64-linux.sh
chmod +x racket-6.7-x86_64-linux.sh
sudo ./racket-6.7-x86_64-linux.sh --unix-style --dest /usr/ --create-dir
rm -f racket-6.7-x86_64-linux.sh
popd

sudo yum install rlwrap -y -q

./run-news
```


text:
import sys
import tty
import termios
import logging.config

from contextlib import contextmanager

from . import __name__ as __root_logger__

COLORS = {
    '_red': '\x1b[38;5;1m',
    '_green': '\x1b[38;5;2m',
    '_yellow': '\x1b[38;5;3m',
    '_magenta': '\x1b[38;5;5m',
    '_cyan': '\x1b[38;5;6m',
    '_darkgray': '\x1b[38;5;8m',
    '_r': '\x1b[0m',
}

NO_COLORS = {k: '' for k in COLORS}

AUTO_COLORS = COLORS if sys.stdout.isatty() else NO_COLORS

LOG_FORMAT = '{asctime} {levelname} {name}: {message}'

LOG_STYLE = '{'

DATE_FORMAT = '%H:%M:%S'

@contextmanager
def config_tty():
    if sys.stdin.isatty() and sys.stdout.isatty():
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            # fixes new-lines in raw mode
            fixed_mode = termios.tcgetattr(fd)
            fixed_mode[tty.OFLAG] |= tty.OPOST
            termios.tcsetattr(fd, termios.TCSAFLUSH, fixed_mode)
            yield True
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old)
    else:
        yield False

def configure_logging(debug):
    log = logging.getLogger(__root_logger__)
    if debug:
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)
        handler.setFormatter(logging.Formatter(LOG_FORMAT, DATE_FORMAT,
                                               LOG_STYLE))
        log.setLevel(logging.DEBUG)
        log.addHandler(handler)
    else:
        log.disabled = True

def pretty(string, *args, **kwargs):
    kwargs.update(AUTO_COLORS)
    return string.format(*args, **kwargs) + AUTO_COLORS['_r']


text:
package org.hl7.fhir.dstu3.hapi.validation;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.Test;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.util.TestUtil;

public class DefaultProfileValidationSupportTest {

	private DefaultProfileValidationSupport mySvc = new DefaultProfileValidationSupport();
	private static FhirContext ourCtx = FhirContext.forDstu3();

	@Test
	public void testGetStructureDefinitionsWithRelativeUrls() {
		assertNotNull(mySvc.fetchStructureDefinition(ourCtx, "http://hl7.org/fhir/StructureDefinition/Extension"));
		assertNotNull(mySvc.fetchStructureDefinition(ourCtx, "StructureDefinition/Extension"));
		assertNotNull(mySvc.fetchStructureDefinition(ourCtx, "Extension"));

		assertNull(mySvc.fetchStructureDefinition(ourCtx, "http://hl7.org/fhir/StructureDefinition/Extension2"));
		assertNull(mySvc.fetchStructureDefinition(ourCtx, "StructureDefinition/Extension2"));
		assertNull(mySvc.fetchStructureDefinition(ourCtx, "Extension2"));

	}

	@AfterClass
	public static void afterClassClearContext() {
		TestUtil.clearAllStaticFieldsForUnitTest();
	}

}


text:
import React, { Component } from 'react';
import config from './config';
import { Progress, Button } from 'semantic-ui-react'
import LoginMenuContainer from './containers/LoginMenuContainer'
import SignupContainer from './containers/SignupContainer'
import MainMenuContainer from './containers/MainMenuContainer'
import LevelSelectionContainer from './containers/LevelSelectionContainer'
import InGameMenuContainer from './containers/InGameMenuContainer'
import CreateRoomMenuContainer from './containers/CreateRoomMenuContainer'

const style = {
    width: config.gameWidth,
    height: config.gameHeight
}

class MainUI extends Component {

    constructor(props) {
      super(props)

      this.state = {
          display: 'play',
          user: null,
      }

      this.setDisplay = this.setDisplay.bind(this)
    }

    setDisplay(display) {
      this.setState({
        display
      })
    }

    render() {
        const isMainMenu = this.state.displayMainMenu;
        const isLevelSelection = this.state.displayLevelSelection;
        const display = this.state.display;
        let menu = null;
        // TODO: refactor this into a switch statement or something better
        if (display === 'login') {
          menu = <LoginMenuContainer game={this.props.game} mainUI={this} />
        } else if (display === 'signup') {
          menu = <SignupContainer game={this.props.game} mainUI={this}/>
        } else if (display === 'main') {
          menu = <MainMenuContainer game={this.props.game} mainUI={this}/>
        } else if (display === 'levels') {
          menu = <LevelSelectionContainer game={this.props.game} mainUI={this}/>
        } else if (display === 'play') {
          menu = <InGameMenuContainer game={this.props.game} mainUI={this}/>
        } else if (display === 'create room') {
          menu = <CreateRoomMenuContainer game={this.props.game} mainUI={this}/>
        } else {
          // TODO: add more ui
          menu =
hello

        }
        return (

                { menu }

      );
    }
}

export default MainUI;


text:
			Sample Code @path will be replaced with the actual file path.

				JavaScript
				HTML

			Run
			<form id="chart_form" action="generate.map.php" method="post" target="chart_frame" enctype="multipart/form-data" style="display:none">
				<input type="hidden" name="component_code" value="" />
				<input type="hidden" name="sample_code" value="" />
				<input type="hidden" name="html_code" value="" />
				<input type="hidden" name="name" value="" />
				<input type="hidden" name="type" value="map" />
			</form>

	<textarea id="sample_code">jui.ready([ "chart.builder" ], function(builder) {
	var chart = builder("#result", {
		height : 400,
		padding : 0,
		axis : [{
			map : {
				path : @path
			}
		}]
	});
});
</textarea>

		<textarea id="html_code">

</textarea>


text:
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using SharpDX;

namespace CustomLayout
{
    /// <summary>
    /// Tells a flow layout where text is allowed to flow.
    /// </summary>
    internal class FlowLayoutSource
    {
        public FlowShape FlowShape;
        public float Width, Height;

        private float currentY;

        public FlowLayoutSource()
        {
            FlowShape = FlowShape.Circle;
            Width = 300;
            Height = 300;
            Reset();
        }

        public void Reset()
        {
            currentY = 0;
        }
        public void SetSize(int width, int height)
        {
            Width = width;
            Height = height;
        }
        public bool GetNextRect(float fontHeight, out RectangleF rect)
        {
            // Set defaults.
            rect = new RectangleF(0, 0, Width, Height);

            if (Width < 0 || Height < 0)
                return false;

            float halfHeight = Height / 2;
            float halfWidth = Width / 2;

            // Simple, hard-coded shape formulas.
            // You can add more shapes by adding a new enum in the header and extending
            // the switch statement.

            switch (FlowShape)
            {
                case FlowShape.Funnel:
                    float xShift = (float)(Math.Sin(currentY / Height * Math.PI * 3)) * 30;
                    // Calculate slope to determine edges.
                    rect.Top = currentY;
                    rect.Bottom = currentY + fontHeight;
                    rect.Left = xShift + (currentY / Height) * Width / 2;
                    rect.Right = Width - rect.Left;
                    break;
                case FlowShape.Circle:
                    float adjustedY = (currentY + fontHeight / 2) - halfHeight;
                    // Determine x from y using circle formula d^2 = (x^2 + y^2).
                    float x = (float)Math.Sqrt((halfHeight * halfHeight) - (adjustedY * adjustedY));
                    rect.Top = currentY;
                    rect.Bottom = currentY + fontHeight;
                    rect.Left = halfWidth - x;
                    rect.Right = halfWidth + x;
                    break;
            }

            // Advance down one line, based on font height.
            currentY += fontHeight;
            if (currentY >= Height)
            {
                // Crop any further lines.
                rect.Left = rect.Right = 0;
            }
            return true;
        }
    }

    public enum FlowShape { Circle, Funnel };

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
    xmlns:rim="http://www.blackberry.com/ns/widgets"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="org.apache.cordova.test"
    version="0.1">
    <name>Test</name>
    <description>Cordova Test Plugin</description>
    <license>Apache 2.0</license>
    <keywords>cordova,test</keywords>

    <js-module src="www/test.js" name="test" />

</plugin>


text:
layout: post
title: "Regeneration branded 'miserable failure' at CPO Public Inquiry"
date: 2013-07-18
image: img/larryandjanetleave.png
---
Southwark's Elephant & Castle regeneration plans were branded _"a miserable
failure"_ by former Heygate residents at a public inquiry into the Heygate
Compulsory Purchase Order.

![](https://betterelephant.github.io/images/IMG_3290.JPG)

The Order was confirmed today after a six month wait following the four day
inquiry, which took place during 5th - 8th Feb. The inquiry was triggered when
remaining leaseholders on the Heygate estate objected to the Order, which will
see them dispossessed of their homes to make way for the £1.5bn regeneration
scheme being undertaken by the council and its development partner [Lend
Lease](https://lendlease.com).

There were a total of [10 objectors to the
Order](https://www.southwark.gov.uk/download/8118/core_document_6-objection_table),
including the Crossway church located on the estate plus a number of local
residents and community groups. The objections broached a number of themes
including lack of truly affordable housing, loss of trees and claims that the
[plans had been altered](https://35percent.org/affordable-housing/) from the
[original regeneration
objectives](https://betterelephant.github.io/images/2004SPG.pdf) to the extent
that they were no longer in the public interest.

The objectors lead by the Heygate Leaseholders Group, pointed out that tenants
on the estate had not been given the opportunity to object, as those who
objected had simply been subjected to eviction proceedings under the 1985
Landlord & Tenant Act. They also pointed out that the scheme amounts to forced
displacement - as the council had [denied Heygate residents a
ballot](https://heygate.github.io/displacement.html) on whether their homes
should be demolished. Several former Heygate residents [gave
evidence](https://heygate.github.io/img/CPOWitnessStatements.zip) at the inquiry
objecting to Southwark's heavy-handed approach when the [decant was brought
forward in 2007](https://betterelephant.github.io/images/HAPtenantsletter.pdf)
- 1 in 3 secure tenants were subjected to eviction proceedings[^1], and its
  failure to honour promises to residents that they would be able to move to
new homes on the estate footprint: the new 'affordable' units will be at the
new '[affordable
rent](https://www.guardian.co.uk/society/2013/mar/05/social-rents-increases-break-up-communities)',
which will be at least double the level of council rents. Just 1 in 5 secure
tenants on the estate have managed to stay living in the SE17 postcode, the
rest have been
[scattered](https://35percent.org/2013-06-08-the-heygate-diaspora/) across the
four corners of the borough and beyond:

![](https://heygate.github.io/img/DisplacedTenants.png)

The objectors were also supported by academic expert witnesses who gave evidence showing the negative effects of displacement on the community, and produced [data](https://heygate.github.io/img/tenurechangeanalysis.pdf) showing how the development plans - if passed - would create a far less mixed community at the Elephant & Castle (just 8% social housing in total).

![](https://betterelephant.github.io/images/IMG_3284.JPG)

Among the expert witnesses giving evidence were:

__Lorretta Lees__ - King's College London

__Michael Edwards__ - Bartlett School of Planning (UCL)

__Mara Ferreri__ - Queen Mary University of London

Other witnesses giving evidence in support of the objectors included members of
local groups [Better Elephant](https://betterelephant.github.io/) and the [Elephant
Amenity Network](https://elephantamenity.wordpress.com/), Catherine Croft from
the Twentieth Century Society and Tim Tinker the original Heygate architect.

In his submission, Tinker who spent 7 years drawing up the Heygate scheme in
the 1960s said the following: _"The Heygate and its design has been stigmatised
and I thought it was time to set the record straight. Its notorious reputation
is a farrago of half-truths and lies put together by people who should have
known better."_[^2] Tinker also pointed out that the original 1970s Heygate
redevelopment had been based on providing homes for those displaced from a
specific [neighbouring slum clearance
area](https://heygate.github.io/img/NewingtonEstateSlumClearanceArea.png) (what
is now the Newington estate). The original scheme he claimed, had kept the
community together whereas the current scheme he said, had seen residents
_"scattered to the four winds"_.

Michael Edwards who is a senior lecturer in the economics of planning at UCL's
Bartlett School of Planning said _"What is called 'regeneration' typically has
perverse, unintended, negative effects of displacing precisely those people
whose deprivation was taken as the justification for regeneration."_[^3]

Lorretta Lees, who is Professor of Human Geography at King's College London and
an international expert on gentrification and urban regeneration policy said
_"The development plans do not acknowledge the social mix already present on
the estate, nor do they address issues of social sustainability. They deploy a
language of social balance in the service of social exclusion. The rhetoric is
about social sustainability, but confirmation of the CPO will lead to social
segregation."_[^4]

![](https://heygate.github.io/img/examples/helen.jpg)

In her [witness
statement](https://heygate.github.io/img/examples/HelenObrien.pdf), former chair
of the Heyate Tenants and Residents Association Helen O'Brien described the
redevelopment plans as a miserable failure - _"What was once a thriving
community has now been scattered all over Southwark. Southwark's regeneration
plans are a miserable failure. Everyone who has worked on the regeneration at
the Elephant should be thoroughly ashamed of themselves."_

During the inquiry objectors produced detailed statistics including a [1998
Stock Condition
Survey](https://betterelephant.github.io/blog/2012/12/23/1998-southwark-housing-stock-survey/)
and a council-commissioned [Options Appraisal
Study](https://heygate.herokuapp.com/monthly-roundup/1998-allot-and-max-survey.html),
which had made recommendations for large parts of the estate to be refurbished
as part of the redevelopment. They also produced a [detailed
analysis](https://heygateestate.wordpress.com/) by global architects
[Gensler](https://gensler.com/), showing how the estate could be refurbished and
modernised at the current cost of just £14k per home.

[Crime
statistics](https://betterelephant.github.io/images/HeygateCrimeStats.pdf) were
also tabled by objectors in response to the [council's
claim](https://www.youtube.com/watch?v=87Yg_SJoPjw) that the bad design of the
estate led to it becoming a _"by-word for social failure, crime and anti-social
behaviour"_. The figures showed that the crime rate on the estate was a
staggering 45% below the borough average.

![](https://heygate.github.io/img/TerryRedpath.jpg)

Former Heygate Leaseholder Terry Redpath travelled in from Sidcup to give
evidence at the inquiry. His submission highlighted the plight of leaseholders,
many of which had been forced to relocate outside London with the low
compensation paid for their homes - _"I could no longer afford to stay in the
area - the compensation I was offered plus £45,000 of life savings bought me a
terraced property 15 miles out of London. I have been forced to give up my home
to accommodate the building of homes for overseas investors."_[^5]

Redpath, who lived on the estate for 35 years and whose family have lived in
the area for generations, went on to highlight the shortcomings of the
consultation process: _"Consultation was a farce - the council kept insisting
that 94% of local residents supported the redevelopment plans, but we later
learned that this was 94% of just 6% that had responded to the survey.  They
had originally promised us a ballot on whether the estate should be demolished
but we never got it - it has been completely undemocratic."_

The [google overlay map](https://maps.google.co.uk/maps/ms?msid=206540700955382422085.0004ddeb74e646a7276ee&msa=0) below shows the extent of displacement suffered by Heygate leaseholders as a result of the regeneration scheme:

![](https://betterelephant.github.io/images/LeaseholderDisplacement1.png)

![](https://betterelephant.github.io/images/IMG_3286.JPG)

Remaining leaseholder and statutory objector Adrian Glasspool said _"We have
simply exercised our right to say no. This is a privilege that tenants on the
estate didn't have - 198 of whom were forced to leave their homes under the
shadow of [eviction
proceedings](https://betterelephant.github.io/images/jonabbottCPOinquiry8Feb2013.pdf)."_

![](https://2.bp.blogspot.com/-2ZJgFmnm42M/URLp52OPDEI/AAAAAAAAA9w/03rzKuUo-Js/s400/2013-02-06+10.18.46+HDR+copy.jpg)

Remaining leaseholder and statutory objector Mojisola Ojeikere (left in the
photograph accompanying inspector Wenda Fabian during the site tour) said _"We
were [originally promised](https://heygate.github.io/img/Appendix8.pdf) a range
of options in assisting us to buy one of the new-build Heygate homes[^6], but
this promise was never honoured - now we are being shortchanged and priced out
of the area: I am being offered just £150,000 for my 2 bed flat, when the
new-build 2 bed Heygate flats are currently being marketed overseas for upwards
of £455,000 - [www.trafalgarplace.com](https://www.trafalgarplace.com).
How am I supposed to buy one of these with the miserable amount they are
offering me for my home?"_

When objectors asked at the inquiry why they didn't get the new homes
originally promised, the council's lead officer replied _"I don't know, I
wasn't employed by the council at the time the promises were made. But I am
sure Lend Lease would be willing to sell to anyone"_:

Analysis of [information](https://heygate.github.io/img/LBSHeygateacquisitionsOct2012.xls) received through FOI requests, shows that the average compensation received by leaseholders for a 1 bed flat on the estate was just £95,480.

Southwark Council is estimated to have spent around £3m obtaining the Compulsory Purchase Order.

The council's case documents submitted for the CPO can be downloaded
[here](https://www.southwark.gov.uk/downloads/download/3287/heygate_compulsory_purchase-core_documents_and_proofs_of_evidence_list),
and a copy of the Objectors' Statement of Case is available
[here](https://betterelephant.github.io/images/HeygateCPOStatementOfCaseFinal.pdf).
A short audio recording of objectors giving evidence at the inquiry can be
downloaded from [here](https://heygate.github.io/img/CPORichardLee.mp3).

__Footnotes:__

[^1]: Inquiry
Document 32 tabled by Project Director Jon Abbott during Public Inquiry on 8 Feb 2013.
[^2]: Mr Tinker's written statement, Objectors' Statement of Case - page 45.
[^3]: Mr Edwards' written statement, Inquiry Document 21.
[^4]: Professor Lees' written statement, Inquiry Document 26.
[^5]: Mr Redpath's written statement, Objectors' Statement of Case - page 43.
[^6]: See also paragraph 26 of the 2005 Leaseholder Policy and paragraphs 4 & 33 of the Executive Report - 'Heygate Estate Decant Arrangements', 18 May 2004: "Council Executive agrees to develop housing options for leaseholders whose interests will be acquired as part of the main scheme, including shared and retained equity arrangements. The negotiation of shared ownership retained equity schemes for people to buy a
share in a higher valued property will form part of the procurement exercise to select housing association and developer partners."


text:
import pyspeckit
import pylab as pl
import astropy.units as u

# Load the spectrum & properly identify the units
# The data is from http://adsabs.harvard.edu/abs/1999A%26A...348..600P
sp = pyspeckit.Spectrum('02232_plus_6138.txt')
sp.xarr.set_unit(u.km/u.s)
sp.xarr.refX = 88.63184666e9 * u.Hz
sp.xarr.velocity_convention = 'radio'
sp.xarr.xtype='velocity'
sp.unit='$T_A^*$'

# set the error array based on a signal-free part of the spectrum
sp.error[:] = sp.stats((-35,-25))['std']
# Register the fitter
# The HCN fitter is 'built-in' but is not registered by default; this example
# shows how to register a fitting procedure
# 'multi' indicates that it is possible to fit multiple components and a
# background will not automatically be fit
# 5 is the number of parameters in the model (line center,
# line width, and amplitude for the 0-1, 2-1, and 1-1 lines)
sp.Registry.add_fitter('hcn_varyhf',pyspeckit.models.hcn.hcn_varyhf_amp_fitter,5)

# This one is the same, but with fixed relative ampltidue hyperfine components
sp.Registry.add_fitter('hcn_fixedhf',pyspeckit.models.hcn.hcn_amp,3)

# Plot the results
sp.plotter()
# Run the fixed-ampltiude fitter and show the individual fit components
sp.specfit(fittype='hcn_fixedhf',
           multifit=None,
           guesses=[1,-48,0.6],
           show_hyperfine_components=True)
# Now plot the residuals offset below the original
sp.specfit.plotresiduals(axis=sp.plotter.axis,clear=False,yoffset=-1,color='g',label=False)
sp.plotter.reset_limits(ymin=-2)

# Save the figure (this step is just so that an image can be included on the web page)
sp.plotter.savefig('hcn_fixedhf_fit.png')

# Run the variable-ampltiude fitter and show the individual fit components
# Note the different order of the arguments (velocity, width, then three amplitudes)
sp.specfit(fittype='hcn_varyhf',
           multifit=None,
           guesses=[-48,1,0.2,0.6,0.3],
           show_hyperfine_components=True,
           clear=True)

# Again plot the residuals
sp.specfit.plotresiduals(axis=sp.plotter.axis,clear=False,yoffset=-1,color='g',label=False)
sp.plotter.reset_limits(ymin=-2)

# Save the figure
sp.plotter.savefig('hcn_freehf_fit.png')

# now do the same thing, but allow the widths to vary too
# there are 7 parameters:
# 1. the centroid
# 2,3,4 - the amplitudes of the 0-1, 2-1, and 1-1 lines
# 5,6,7 - the widths of the 0-1, 2-1, and 1-1 lines
sp.Registry.add_fitter('hcn_varyhf_width',pyspeckit.models.hcn.hcn_varyhf_amp_width_fitter,7)

# Run the fitter
sp.specfit(fittype='hcn_varyhf_width',
           multifit=None,
           guesses=[-48,0.2,0.6,0.3,1,1,1],
           show_hyperfine_components=True,
           clear=True)

# print the fitted parameters:
print sp.specfit.parinfo
# Param #0      CENTER0 =      -51.865 +/-       0.0525058
# Param #1    AMP10-010 =      1.83238 +/-       0.0773993   Range:   [0,inf)
# Param #2    AMP12-010 =      5.26566 +/-       0.0835981   Range:   [0,inf)
# Param #3    AMP11-010 =      3.02621 +/-       0.0909095   Range:   [0,inf)
# Param #4  WIDTH10-010 =      2.16711 +/-        0.118651   Range:   [0,inf)
# Param #5  WIDTH12-010 =      1.90987 +/-       0.0476163   Range:   [0,inf)
# Param #6  WIDTH11-010 =      1.64409 +/-        0.076998   Range:   [0,inf)

sp.specfit.plotresiduals(axis=sp.plotter.axis,clear=False,yoffset=-1,color='g',label=False)
sp.plotter.reset_limits(ymin=-2)

# Save the figure (this step is just so that an image can be included on the web page)
sp.plotter.savefig('hcn_freehf_ampandwidth_fit.png')

# Finally, how well does a 2-component fit work?
sp.specfit(fittype='hcn_fixedhf',
           multifit=None,
           guesses=[1,-48,0.6,0.1,-46,0.6],
           show_hyperfine_components=True,
           clear=True)
sp.specfit.plotresiduals(axis=sp.plotter.axis,clear=False,yoffset=-1,color='g',label=False)
sp.plotter.reset_limits(ymin=-2)

# Save the figure (this step is just so that an image can be included on the web page)
sp.plotter.savefig('hcn_fixedhf_fit_2components.png')


text:
using namespace Ilwis;
using namespace RasterOperations;

Ilwis::OperationImplementation *AggregateRaster::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new AggregateRaster(metaid, expr);
}

AggregateRaster::AggregateRaster()
{
}

AggregateRaster::AggregateRaster(quint64 metaid, const Ilwis::OperationExpression &expr) :
    OperationImplementation(metaid, expr),
    _method(NumericStatistics::pSUM)
{
}

bool AggregateRaster::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx,symTable)) != sPREPARED)
            return false;

    IRasterCoverage outputRaster = _outputObj.as<RasterCoverage>();

    quint64 currentCount = 0;
    BoxedAsyncFunc aggregateFun = [&](const BoundingBox& box) -> bool {
        //Size sz = outputRaster->size();
        PixelIterator iterOut(outputRaster, box);
        BoundingBox inpBox(Pixel(box.min_corner().x,
                                             box.min_corner().y * groupSize(1),
                                             box.min_corner().z * groupSize(2)),
                             Pixel((box.max_corner().x+1) * groupSize(0) - 1,
                                             (box.max_corner().y + 1) * groupSize(1) - 1,
                                             (box.max_corner().z + 1) * groupSize(2) - 1) );

        // TODO blockiterator is too slow.
        BlockIterator blockIter(_inputObj.as<RasterCoverage>(),Size<>(groupSize(0),groupSize(1), groupSize(2)), inpBox);
        NumericStatistics stats;
        PixelIterator iterEnd = iterOut.end();
        while(iterOut != iterEnd) {
            GridBlock& block = *blockIter;
            // TODO using the big statistics class maybe a bit overdone here as this has some overhead (for each pixel)
            stats.calculate(block.begin(), block.end(), _method);
            double v = stats[_method];
           *iterOut = v;
            ++iterOut;
            ++blockIter;
            updateTranquilizer(currentCount++, 1000);
        }
        return true;
    };
    bool res = OperationHelperRaster::execute(ctx, aggregateFun, outputRaster);

    if ( res && ctx != 0) {
        QVariant value;
        value.setValue<IRasterCoverage>(outputRaster);
        ctx->setOutput(symTable,value,outputRaster->name(), itRASTER, outputRaster->source() );
    }
    return res;
}

NumericStatistics::PropertySets AggregateRaster::toMethod(const QString& nm) {
    QString mname = nm.toLower();
    if ( mname == "avg")
        return NumericStatistics::pMEAN;
    else if ( mname == "min")
        return NumericStatistics::pMIN;
    else if ( mname == "max")
        return NumericStatistics::pMAX;
    else if ( mname == "med")
        return NumericStatistics::pMEDIAN;
    else if ( mname == "pred")
        return NumericStatistics::pPREDOMINANT;
    else if ( mname == "std")
        return NumericStatistics::pSTDEV;
    else if ( mname == "sum")
        return NumericStatistics::pSUM;

    return NumericStatistics::pLAST    ;
}

Ilwis::OperationImplementation::State AggregateRaster::prepare(ExecutionContext *, const SymbolTable & )
{
    QString raster = _expression.parm(0).value();
    QString outputName = _expression.parm(0,false).value();
    int copylist = itDOMAIN | itCOORDSYSTEM;

    if (!_inputObj.prepare(raster, itRASTER)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,raster,"");
        return sPREPAREFAILED;
    }
    _method = toMethod(_expression.parm(1).value());
    if ( _method == NumericStatistics::pLAST) {
        ERROR2(ERR_ILLEGAL_VALUE_2, "parameter value", " aggregation method");
        return sPREPAREFAILED;
    }
    bool ok;
    quint32 groupSz = _expression.parm(2).value().toInt(&ok);
    if (!ok) {
        QString blist = _expression.parm(2).value();
        blist.remove("{");
        blist.remove("}");
        QStringList dims = blist.split(" ");
        if ( dims.size() > 0) {
            for(int i=0; i < dims.size(); ++i)     {
                quint32 val = dims[i].toInt(&ok);
                if ( ok) {
                    _groupSize[i] = val;
                }else
                    break;
            }
        }

    }else {
        _groupSize[0] = groupSz;
        _groupSize[1] = groupSz;

    }
    if ( !ok || groupSize() < 2) {
        ERROR2(ERR_ILLEGAL_VALUE_2, "aggregation group size", QString::number(groupSize()));
        return sPREPAREFAILED;
    }

    _grouped = _expression.parm(3).value().toLower() == "true";
    if ( !_grouped)
        copylist |= itGEOREF;

    _outputObj = OperationHelperRaster::initialize(_inputObj,itRASTER, copylist);
    if ( !_outputObj.isValid()) {
        ERROR1(ERR_NO_INITIALIZED_1, "output rastercoverage");
        return sPREPAREFAILED;
    }
    QString outputBaseName = outputName;
    int index = 0;
    if ( (index = outputName.lastIndexOf(".")) != -1) {
        outputBaseName = outputName.left(index);
    }
    IRasterCoverage inputRaster = _inputObj.as<RasterCoverage>();
    IRasterCoverage outputRaster = _outputObj.as<RasterCoverage>();
    if ( outputName != sUNDEF)
        _outputObj->name(outputName);
    outputRaster->coordinateSystem(inputRaster->coordinateSystem());

    BoundingBox box(inputRaster->size());
    if ( _grouped) {
        int xs = box.xlength();
        int ys = box.ylength();
        int zs = box.zlength();
        int newxs = xs / groupSize(0);
        int newys = ys / groupSize(1);
        int newzs = zs / groupSize(2);
        box = BoundingBox(Size<>(newxs, newys, newzs));

    }
    if ( _grouped) {
        Envelope envlope = inputRaster->envelope();
        Resource resource(QUrl("ilwis://internalcatalog/georeference" + _outputObj->name()),itGEOREF);
        resource.addProperty("size", IVARIANT(box.size()));
        resource.addProperty("envelope", IVARIANT(envlope));
        resource.addProperty("coordinatesystem", inputRaster->coordinateSystem()->id());
        resource.addProperty("name", outputBaseName);
        resource.addProperty("centerofpixel",inputRaster->georeference()->centerOfPixel());
        IGeoReference  grf;
        if (grf.prepare(resource)) {
            mastercatalog()->addItems({resource});
            outputRaster->georeference(grf);
        }
        outputRaster->envelope(envlope);
        outputRaster->size(box.size());
    }

    initialize(outputRaster->size().linearSize());

    return sPREPARED;
}

quint64 AggregateRaster::createMetadata()
{

    OperationResource operation({"ilwis://operations/aggregateraster"});
    operation.setLongName("Spatial Aggregation of Raster coverage");
    operation.setSyntax("aggregateraster(inputgridcoverage,!Avg|Max|Med|Min|Prd|Std|Sum, groupsize,changegeometry)");
    operation.setDescription(TR("generates a rastercoverage according to a aggregation method. The aggregation method determines how pixel values are used in the aggregation"));
    operation.setInParameterCount({4});
    operation.addInParameter(0,itRASTER , TR("input rastercoverage"),TR("input rastercoverage with any domain"));
    operation.addInParameter(1,itSTRING , TR("Aggregation Method"),TR("the method how pixels inside a group will be accumulated"));
    operation.addInParameter(2,itINTEGER | itSTRING , TR("Groupsize"),TR("The size of the block used to aggregate. In the case of integer it is a square 2D block; in the case of string it is of the list format (2 or 3 dimensions). eg {3 4}"));
    operation.addInParameter(3,itBOOL , TR("change geometry"),TR("The aggregation can either create a map with a reduced size proportional to de block size or use the same geometry size but fill all pixels in the block with the aggregate"));
    operation.setOutParameterCount({1});
    operation.addOutParameter(0,itRASTER, TR("Aggregated raster"), TR("output rastercoverage with the domain of the input map"));
    operation.setKeywords("aggregate,raster,geometry");

    mastercatalog()->addItems({operation});
    return operation.id();
}

quint32 AggregateRaster::groupSize(int dim)
{
    return _groupSize[dim];
}