text
stringlengths 3
1.05M
|
---|
const computeWeeklyDays = (data, rruleObj) => {
let weekdays = [];
if (rruleObj.freq !== 2) {
return data.repeat.weekly.days;
}
if (rruleObj.byweekday) {
weekdays = rruleObj.byweekday.map((weekday) => weekday.weekday);
}
return {
mon: weekdays.includes(0),
tue: weekdays.includes(1),
wed: weekdays.includes(2),
thu: weekdays.includes(3),
fri: weekdays.includes(4),
sat: weekdays.includes(5),
sun: weekdays.includes(6),
};
};
export default computeWeeklyDays;
|
import GameService from './game.service';
describe('Game Service', function(){
let service;
let API_URL = 'api-url',
resource = jasmine.createSpy('resource').and.callFake(function() {
return {
save: jasmine.createSpy('save')
}
}),
state = {
go: jasmine.createSpy('go')
};
beforeEach(function(){
service = new GameService(API_URL, resource, state);
});
it('should init game', function() {
//given
service.finalScore.result = 1200;
service.seconds.value = 123;
service.mistakes.value = 2;
//when
service.initGame();
//then
expect(service.finalScore.result).toBe(1500);
expect(service.seconds.value).toBe(0);
expect(service.mistakes.value).toBe(0);
});
it('should get final score value', function() {
//given
service.seconds.value = 35;
service.mistakes.value = 2;
let expected = 1000;
//when
service.calcScore();
//then
expect(service.finalScore.result).toBe(expected);
});
it('should save result', function() {
//given
let userName = {value: 'test'};
let score = 1000;
let url = '/scores'
//when
service.saveScore(userName, score);
//then
expect(resource).toHaveBeenCalled();
expect(resource).toHaveBeenCalledWith(API_URL+url);
});
});
|
from __future__ import absolute_import
import unittest
from .util import extract_numerical_value
from .model import Missing
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
class TestSelector(unittest.TestCase):
def test_extract_numerical_value(self):
test_dict = {
None: 0.0,
'': 0.0,
'i': 0,
'M': 0.0,
'Mi': 0.0,
'0': 0.0,
'0i': 0.0,
'0n': 0.0,
'0ni': 0.0,
'1e2': 100.0,
'1e2Mi': 104857600.0,
'1e2i': 100.0,
'1e2M': 100000000.0,
'.314ni': 2.9243528842926026e-10,
'3.14n': 3.1400000000000003e-09,
'3.14u': 3.14e-06,
'3.14m': 0.00314,
'3.14': 3.14,
'3.14i': 3.14,
'3.14K': 3140.0,
'3.14k': 3140.0,
'3.14M': 3140000.0,
'3.14G': 3140000000.0,
'3.14T': 3140000000000.0,
'3.14P': 3140000000000000.0,
'3.14E': 3.14e+18,
'314.Ei': 3.6201735244654995e+20
}
for i in test_dict.keys():
self.assertTrue(isclose(test_dict[i], extract_numerical_value(i)))
# test oc.Missing
self.assertTrue(isclose(extract_numerical_value(Missing), 0.0))
if __name__ == '__main__':
unittest.main()
|
/**
* Suitelet that changes the PO Form Type
*/
function crearFacturaCo(request, response)
{
/*var id = request.getParameter('paramInCo');
nlapiLogExecution('ERROR', 'crearFacturaCo: ', 'SL| Value request id parameter: ' + id);*/
var valT = "POCD_HD000041";
var myvar = '<?xml version="1.0" encoding="UTF-8"?>'+
'<?xml-stylesheet type="text/xsl" href="https://3559763.app.netsuite.com/core/media/media.nl?id=2586311&c=3559763&h=762f5d4d5c88ffde5e39&_xt=.xml"?>'+
'<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:hl7-org:v3 cda/CDA.xsd" xmlns:mif="urn:hl7-org:v3/mif" xmlns="urn:hl7-org:v3">'+
' <!-- '+
' Referirse a la "Guía de Intercambio de Información en Salud para Documentos Clínicos Electrónicos GIIS-A001-CDAMX-01-01" para las definiciones de variables y normatividad a cumplir.'+
' '+
' Para conocer más detalle y los derechos de autor de los estándares favor de revisar dicha referencia en www.hl7.org'+
' -->'+
' '+
' <!-- Código para realm de México-->'+
' <realmCode code="MX"/>'+
' '+
' <!-- OID para documentos estándar "HL7 Registered RMIMs"-->'+
' <typeId root="2.16.840.1.113883.1.3" extension="'+
valT+'"/>'+
' '+
' <!-- Template para Documentos Clínicos en México [*]-->'+
' <templateId root="2.16.840.1.113883.3.215.11.1.1"/>'+
' '+
' <!-- ******************************************************** ENCABEZADO DEL DOCUMENTO ******************************************************** -->'+
''+
' <!-- Identificador único de este documento generado'+
' - root: OID del sistema que genera el documento, o bien, del mecanismo de identificación de documentos que ocupe.'+
' - extension: UUID o identificador único del documento generado por el sistema emisor.'+
' - assigningAuthorityName: Nombre (corto) del sistema que está generado el documento (para mayor detalle ver <author>)'+
' -->'+
' <id root="--OID del identificador o sistema generador del documento--" extension="-- Valor del identificador único del documento --" assigningAuthorityName="--Nombre del Sistema--"/>'+
' '+
' <!-- Tipo de documento (tomar de valores seleccionados para México de LOINC) -->'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="34133-9" displayName="Nota Resumen de Episodio"/>'+
' '+
' <!-- Título de acuerdo al tipo de CDA que se está generando -->'+
' <title>Resumen Clínico</title>'+
' '+
' <!-- Momento de generación del CDA en formato aaaammddhhiiss-->'+
' <effectiveTime value="--aaaammddhhiiss--"/>'+
' '+
' <!-- Nivel de confidencialidad de acuerdo al catálogo de HL7. Posibles códigos y valores: '+
' L - Bajo'+
' M - Moderado'+
' N - Normal'+
' R - Restringido'+
' U - Irrestricto'+
' V - Muy restringido'+
' -->'+
' <confidentialityCode codeSystem="2.16.840.1.113883.5.25" codeSystemName="Confidentiality" code="--Valor del Nivel de confidencialidad de acuerdo al catálogo--" displayName="--Nombre del Nivel de confidencialidad de acuerdo al catálogo--"/>'+
' '+
' <!-- Código del lenguaje en el que se genera el contenido del documento -->'+
' <languageCode code="es-MX"/>'+
' '+
' <!-- Identificador del documento base (igual al id del documento en caso de la primera versión del mismo) -->'+
' <setId root="--OID de identificación del documento base del sistema--" extension="--Identificador único del documento base--" assigningAuthorityName="--Nombre del sistema generador del documento base--"/>'+
' '+
' <!-- Versión del documento -->'+
' <versionNumber value="--Número de versión del documento--"/>'+
' '+
' <!-- Datos del paciente -->'+
' <recordTarget>'+
' <patientRole>'+
' <!-- Identificador ÚNICO del paciente en el sistema que genera el documento.'+
' - root: OID del sistema de identificación.'+
' - extension: identificador del paciente.'+
' - assigningAuthorityName: descripción legible del identificador-->'+
' <id root="---OID del Identificador único de paciente--" extension="--Valor único del identificador de paciente--" assigningAuthorityName="--Nombre del identificador usado por el sistema--"/>'+
' '+
' <!-- extension: CURP del paciente -->'+
' <id root="2.16.840.1.113883.4.629" extension="--Clave Unica de Registro de Población (CURP) del paciente--" assigningAuthorityName="CURP"/>'+
' '+
' <!-- Otros identificadores relevantes-->'+
' <id root="--OID Identificador adicional de paciente--" extension="--Identificador adicional de paciente--" assigningAuthorityName="--Nombre del identificador adicional de paciente--"/>'+
' '+
' <!-- Nacionalidad del paciente de acuerdo al catálogo de RENAPO-->'+
' <id root="2.16.840.1.113883.3.215.12.15" extension="--Valor de nacionalidad de acuerdo a catálogo--" assigningAuthorityName="Nacionalidad" />'+
' '+
' <!-- Edad del paciente en años en el momento de la atención -->'+
' <id root="2.16.840.1.113883.3.215.12.501" extension="--Edad del paciente--" assigningAuthorityName="Edad"/>'+
' '+
' <!-- Domicilio de residencia del paciente. En caso de definirse más de un domicilio para el paciente, el de residencia debe ser el primero y con @use="HP"-->'+
' <addr>'+
' <!-- El texto del elemento tiene la dirección en formato legible-->'+
' -- Domicilio completo en texto libre--'+
' '+
' <!--Tipo de vialidad de acuerdo al catálogo de INEGI-->'+
' <streetNameType>--Valor de tipo de vialidad de acuerdo al catálogo--</streetNameType>'+
' <!--Nombre de la vialidad -->'+
' <streetName>--Nombre de la vialidad--</streetName>'+
' <!--Número exterior (parte numérica)-->'+
' <houseNumberNumeric>--Número exterior (Numérico)--</houseNumberNumeric>'+
' <!--Número exterior (parte alfanumérica) -->'+
' <houseNumber>--Número exterior parte alfanumérica--</houseNumber>'+
' <!--Número interior (parte numérica) -->'+
' <unitID>--Número interior (numérico)--</unitID>'+
' <!--Número interior (parte alfanumérica) -->'+
' <unitType>--Número interior (alfanumérico)--</unitType>'+
' <!--Tipo de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationType>--Valor de Tipo de asentamiento de acuerdo al catálogo--</deliveryInstallationType>'+
' <!--Nombre de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationArea>--Nombre del asentamiento--</deliveryInstallationArea>'+
' <!--Localidad de acuerdo al catálogo de INEGI-->'+
' <precinct>--Valor de Localidad de acuerdo al catálogo--</precinct>'+
' <!--Muncipio de acuerdo al catálogo de INEGI -->'+
' <county>--Valor de Municipio de acuerdo al catálogo--</county>'+
' <!--Entidad de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de Entidad de acuerdo al catálogo--</state>'+
' <!--Código Postal de acuerdo al catálogo de SEPOMEX-->'+
' <postalCode>--Valor de Código Postal de acuerdo al catálogo--</postalCode>'+
' <!--Clave del país de acuerdo al catálogo de nacionalidades-->'+
' <country>--País--</country>'+
' </addr>'+
' '+
' <!--Medios de contacto del paciente, esto es, teléfonos, correos electrónicos.'+
' - value: utilizar el prefijo "tel:" para indicar que es un teléfono, "mailto:" para indicar e-mail.'+
' -->'+
' <telecom value="tel:--Número telefónico--"/>'+
' <telecom value="mailto:[email protected]"/>'+
' '+
' <patient>'+
' <!-- Nombre completo del paciente (nombre y primer apellido)-->'+
' <name>'+
' <!--Nombre(s) del paciente-->'+
' <given>--Nombre(s)--</given>'+
' <!--Primer apellido del paciente-->'+
' <family>--Primer apellido--</family>'+
' <!--Segundo apellido del paciente-->'+
' <family>--Segundo apellido--</family>'+
' </name>'+
' '+
' <!-- Sexo del paciente de acuerdo a catálogo de HL7 referido en el OID. Posibles valores: (F, M, U) o UNK si se desconce)-->'+
' <administrativeGenderCode codeSystem="2.16.840.1.113883.5.1" codeSystemName="Administrative Gender" code="--Valor del Sexo de acuerdo a catálogo--" displayName="--Nombre del Sexo de acuerdo a catálogo--"/>'+
' '+
' <!-- Fecha o fecha-hora de nacimiento del paciente en formato aaaammddhhiiss-->'+
' <birthTime value="--aaaammddhhiiss--"/>'+
' '+
' <!-- Estado civil de acuerdo al catálogo estándar de HL7 '+
' D - Divorciado(a)'+
' M - Casado(a)'+
' U - Soltero(a)'+
' W - Viudo(a)'+
' T- Unión Libre'+
' L - Separado(a)'+
' -->'+
' <maritalStatusCode codeSystem="2.16.840.1.113883.5.2" codeSystemName="MaritalStatus" code="--Valor del Estado civil de acuerdo a catálogo--" displayName="--Nombre del Estado civil de acuerdo a catálogo--"/>'+
' '+
' <!-- Religión de acuerdo al catálogo de INEGI-->'+
' <religiousAffiliationCode codeSystem="2.16.840.1.113883.3.215.12.11" codeSystemName="Religiones INEGI" code="--Valor de la Religión de acuerdo a catálogo--" displayName="--Nombre de la Religión de acuerdo a catálogo--"/>'+
' '+
' <!-- Grupo étnico / lengua indígena de acuerdo al catálogo de INEGI-->'+
' <ethnicGroupCode codeSystem="2.16.840.1.113883.3.215.12.10" codeSystemName="Lenguas Indígenas INEGI" code="--Valor de Lengua indígena de acuerdo a catálogo--" displayName="--Nombre de Lengua indígena de acuerdo a catálogo--"/>'+
' <birthplace>'+
' <place>'+
' <addr>'+
' <!-- Clave de la Entidad federativa de nacimiento de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de la Entidad de acuerdo al catálogo--</state>'+
' </addr>'+
' </place>'+
' </birthplace>'+
' '+
' <!-- Datos del responsable legal del paciente (Padre, Tutor, Representante legal, etc.)-->'+
' <guardian>'+
' <!-- Parentesco o relación con el paciente ver catálogo HL7: http://wiki.hl7.de/index.php/2.16.840.1.113883.5.111 -->'+
' <code codeSystem="2.16.840.1.113883.5.111" codeSystemName="Role Code" code="--Valor del Parentesco de acuerdo al catálogo--" displayName="--Nombre del Parentesco de acuerdo al catálogo--"/>'+
' '+
' <!-- Domicilio del responsable del paciente -->'+
' <addr>'+
' <!-- El texto del elemento tiene la dirección en formato legible-->'+
' -- Domicilio completo en texto libre--'+
' '+
' <!--Tipo de vialidad de acuerdo al catálogo de INEGI-->'+
' <streetNameType>--Valor de tipo de vialidad de acuerdo al catálogo--</streetNameType>'+
' <!--Nombre de la vialidad -->'+
' <streetName>--Nombre de la vialidad--</streetName>'+
' <!--Número exterior (parte numérica)-->'+
' <houseNumberNumeric>--Número exterior (Numérico)--</houseNumberNumeric>'+
' <!--Número exterior (parte alfanumérica) -->'+
' <houseNumber>--Número exterior parte alfanumérica--</houseNumber>'+
' <!--Número interior (parte numérica) -->'+
' <unitID>--Número interior (numérico)--</unitID>'+
' <!--Número interior (parte alfanumérica) -->'+
' <unitType>--Número interior (alfanumérico)--</unitType>'+
' <!--Tipo de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationType>--Valor de Tipo de asentamiento de acuerdo al catálogo--</deliveryInstallationType>'+
' <!--Nombre de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationArea>--Nombre del asentamiento--</deliveryInstallationArea>'+
' <!--Localidad de acuerdo al catálogo de INEGI-->'+
' <precinct>--Valor de Localidad de acuerdo al catálogo--</precinct>'+
' <!--Muncipio de acuerdo al catálogo de INEGI -->'+
' <county>--Valor de Municipio de acuerdo al catálogo--</county>'+
' <!--Entidad de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de Entidad de acuerdo al catálogo--</state>'+
' <!--Código Postal de acuerdo al catálogo de SEPOMEX-->'+
' <postalCode>--Valor de Código Postal de acuerdo al catálogo--</postalCode>'+
' <!--Clave del país de acuerdo al catálogo de nacionalidades-->'+
' <country>--País--</country>'+
' </addr>'+
' '+
' <!-- Medios de contacto del responsable del paciente (1:N): teléfono, correo, etc. -->'+
' <telecom value="tel:--Número telefónico--"/>'+
' <telecom value="mailto:--Correo electrónico--"/>'+
' '+
' <guardianPerson>'+
' <!-- Nombre completo del responsable legal del paciente -->'+
' <name>'+
' <!--Nombre(s) del responsable del paciente-->'+
' <given>--Nombre(s)--</given>'+
' <!--Primer apellido del responsable del paciente-->'+
' <family>--Primer apellido--</family>'+
' <!--Segundo apellido del responsable del paciente-->'+
' <family>--Segundo apellido--</family>'+
' </name>'+
' </guardianPerson>'+
' </guardian>'+
' </patient>'+
' '+
' <!-- Datos de la unidad a la que pertenece el paciente-->'+
' <providerOrganization>'+
' <!-- Clave Única de Establecimiento de Salud de atención de acuerdo al catálogo de CLUES de la SS/DGIS-->'+
' <id root="2.16.840.1.113883.4.631" extension="--Valor de la CLUES de acuerdo al catálogo--" assigningAuthorityName="CLUES"/>'+
' <!-- Nombre del establecimiento de atención-->'+
' <name>--Nombre del Establecimiento de salud de acuerdo al catálogo de CLUES--</name>'+
' '+
' <!-- Medios de contacto del establecimiento -->'+
' <telecom value="tel:--Número telefónico--"/>'+
' <telecom value="mailto:--Correo electrónico--"/>'+
' '+
' <!-- Domicilio del establecimiento -->'+
' <addr>'+
' <!-- El texto del elemento tiene la dirección en formato legible-->'+
' -- Domicilio completo en texto libre--'+
' '+
' <!--Tipo de vialidad de acuerdo al catálogo de INEGI-->'+
' <streetNameType>--Valor de tipo de vialidad de acuerdo al catálogo--</streetNameType>'+
' <!--Nombre de la vialidad -->'+
' <streetName>--Nombre de la vialidad--</streetName>'+
' <!--Número exterior (parte numérica)-->'+
' <houseNumberNumeric>--Número exterior (Numérico)--</houseNumberNumeric>'+
' <!--Número exterior (parte alfanumérica) -->'+
' <houseNumber>--Número exterior parte alfanumérica--</houseNumber>'+
' <!--Número interior (parte numérica) -->'+
' <unitID>--Número interior (numérico)--</unitID>'+
' <!--Número interior (parte alfanumérica) -->'+
' <unitType>--Número interior (alfanumérico)--</unitType>'+
' <!--Tipo de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationType>--Valor de Tipo de asentamiento de acuerdo al catálogo--</deliveryInstallationType>'+
' <!--Nombre de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationArea>--Nombre del asentamiento--</deliveryInstallationArea>'+
' <!--Localidad de acuerdo al catálogo de INEGI-->'+
' <precinct>--Valor de Localidad de acuerdo al catálogo--</precinct>'+
' <!--Muncipio de acuerdo al catálogo de INEGI -->'+
' <county>--Valor de Municipio de acuerdo al catálogo--</county>'+
' <!--Entidad de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de Entidad de acuerdo al catálogo--</state>'+
' <!--Código Postal de acuerdo al catálogo de SEPOMEX-->'+
' <postalCode>--Valor de Código Postal de acuerdo al catálogo--</postalCode>'+
' <!--Clave del país de acuerdo al catálogo de nacionalidades-->'+
' <country>--País--</country>'+
' </addr>'+
' '+
' </providerOrganization>'+
' </patientRole>'+
' </recordTarget>'+
' '+
' <!-- Datos del destinatario del documento-->'+
' <informationRecipient>'+
' <intendedRecipient>'+
' <!--extension: Cédula profesional del médico destinatario-->'+
' <id root=\'2.16.840.1.113883.3.215.12.18\' extension="--Número de cédula profesional--"/>'+
' <!-- Medios de contacto del destinatario del documento -->'+
' <telecom value="tel:--Número telefónico--"/>'+
' <telecom value="mailto:--Correo Electrónico--"/>'+
' <!-- Ubicación del destinatario del documento -->'+
' <addr>'+
' <!-- El texto del elemento tiene la dirección en formato legible-->'+
' -- Domicilio completo en texto libre--'+
' '+
' <!--Tipo de vialidad de acuerdo al catálogo de INEGI-->'+
' <streetNameType>--Valor de tipo de vialidad de acuerdo al catálogo--</streetNameType>'+
' <!--Nombre de la vialidad -->'+
' <streetName>--Nombre de la vialidad--</streetName>'+
' <!--Número exterior (parte numérica)-->'+
' <houseNumberNumeric>--Número exterior (Numérico)--</houseNumberNumeric>'+
' <!--Número exterior (parte alfanumérica) -->'+
' <houseNumber>--Número exterior parte alfanumérica--</houseNumber>'+
' <!--Número interior (parte numérica) -->'+
' <unitID>--Número interior (numérico)--</unitID>'+
' <!--Número interior (parte alfanumérica) -->'+
' <unitType>--Número interior (alfanumérico)--</unitType>'+
' <!--Tipo de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationType>--Valor de Tipo de asentamiento de acuerdo al catálogo--</deliveryInstallationType>'+
' <!--Nombre de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationArea>--Nombre del asentamiento--</deliveryInstallationArea>'+
' <!--Localidad de acuerdo al catálogo de INEGI-->'+
' <precinct>--Valor de Localidad de acuerdo al catálogo--</precinct>'+
' <!--Muncipio de acuerdo al catálogo de INEGI -->'+
' <county>--Valor de Municipio de acuerdo al catálogo--</county>'+
' <!--Entidad de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de Entidad de acuerdo al catálogo--</state>'+
' <!--Código Postal de acuerdo al catálogo de SEPOMEX-->'+
' <postalCode>--Valor de Código Postal de acuerdo al catálogo--</postalCode>'+
' <!--Clave del país de acuerdo al catálogo de nacionalidades-->'+
' <country>--País--</country>'+
' </addr>'+
' <informationRecipient>'+
' <!-- Nombre completo del destinatario (i.e. médico consultado) al que se dirige este CDA -->'+
' <name>'+
' <!--Nombre(s) del destinatario del documento-->'+
' <given>--Nombre(s)--</given>'+
' <!--Primer apellido del destinatario del documento-->'+
' <family>--Primer apellido--</family>'+
' <!--Segundo apellido del destinatario del documento-->'+
' <family>--Segundo apellido--</family>'+
' </name>'+
' </informationRecipient>'+
' <receivedOrganization>'+
' <!-- OID de la institución a la que pertenece el destinatario -->'+
' <id root="--OID de la institución/organización/dependencia a la que pertenece el destinatario"/>'+
' <!-- Clave Única de Establecimiento de Salud donde se encuentra el destinatario de acuerdo al catálogo de CLUES de la SS/DGIS-->'+
' <id root="2.16.840.1.113883.4.631" extension="--Valor de la CLUES de acuerdo al catálogo--" assigningAuthorityName="CLUES"/>'+
' <!-- Nombre de la institución a la que pertenece el destinatario -->'+
' <name>--Nombre de la institución/organización/dependencia a la que pertenece el destinatario--</name>'+
' </receivedOrganization>'+
' </intendedRecipient>'+
' </informationRecipient>'+
' '+
' <!-- Autor (Sistema que genera el CDA e institución) -->'+
' <author>'+
' <!-- Momento de generación del CDA, o bien, momento en el que se obtienen los datos para generarlo -->'+
' <time value="aaaammddhhiiss"/>'+
' <assignedAuthor>'+
' <!-- OID del sistema que genera el CDA -->'+
' <id root="---OID del sistema que genera el CDA--"/>'+
' <assignedAuthoringDevice>'+
' <!-- Nombre del sistema (Fabricante, Producto, Versión) que genera el documento electrónico -->'+
' <softwareName>--Software, Dispositivo,Producto--</softwareName>'+
' <!-- Descripción (fabricante, modelo) del dispositivo que genera el documento electrónico -->'+
' <manufacturerModelName>--Versión del software, modelo del dispositivo o producto--</manufacturerModelName> '+
' </assignedAuthoringDevice>'+
' <!-- Medios de contacto de la institución responsable de la autoría del documento electrónico -->'+
' <telecom value="tel:--Número telefónico--"/>'+
' <telecom value="mailto:--Correo Electrónico--"/>'+
' <!-- Domicilio "legible" de la institución responsable de la autoría del documento electrónico -->'+
' <addr>'+
' <!-- El texto del elemento tiene la dirección en formato legible-->'+
' -- Domicilio completo en texto libre--'+
' '+
' <!--Tipo de vialidad de acuerdo al catálogo de INEGI-->'+
' <streetNameType>--Valor de tipo de vialidad de acuerdo al catálogo--</streetNameType>'+
' <!--Nombre de la vialidad -->'+
' <streetName>--Nombre de la vialidad--</streetName>'+
' <!--Número exterior (parte numérica)-->'+
' <houseNumberNumeric>--Número exterior (Numérico)--</houseNumberNumeric>'+
' <!--Número exterior (parte alfanumérica) -->'+
' <houseNumber>--Número exterior parte alfanumérica--</houseNumber>'+
' <!--Número interior (parte numérica) -->'+
' <unitID>--Número interior (numérico)--</unitID>'+
' <!--Número interior (parte alfanumérica) -->'+
' <unitType>--Número interior (alfanumérico)--</unitType>'+
' <!--Tipo de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationType>--Valor de Tipo de asentamiento de acuerdo al catálogo--</deliveryInstallationType>'+
' <!--Nombre de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationArea>--Nombre del asentamiento--</deliveryInstallationArea>'+
' <!--Localidad de acuerdo al catálogo de INEGI-->'+
' <precinct>--Valor de Localidad de acuerdo al catálogo--</precinct>'+
' <!--Muncipio de acuerdo al catálogo de INEGI -->'+
' <county>--Valor de Municipio de acuerdo al catálogo--</county>'+
' <!--Entidad de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de Entidad de acuerdo al catálogo--</state>'+
' <!--Código Postal de acuerdo al catálogo de SEPOMEX-->'+
' <postalCode>--Valor de Código Postal de acuerdo al catálogo--</postalCode>'+
' <!--Clave del país de acuerdo al catálogo de nacionalidades-->'+
' <country>--País--</country>'+
' </addr>'+
' <representedOrganization>'+
' <!-- OID de la institución responsable de la autoría del documento electrónico -->'+
' <id root="-- OID de la Institución responsable de la autoría del documento electrónico --"/>'+
' <!-- Nombre de la institución responsable de la autoría del documento -->'+
' <name>-- Nombre de la Institución responsable de la autoría del documento electrónico --</name>'+
' </representedOrganization>'+
' </assignedAuthor>'+
' </author>'+
' '+
' <!-- Datos de identificación del Capturista de los datos del documento electrónico -->'+
' <dataEnterer>'+
' <!-- Momento en que el usuario introdujo los datos del documento en el software. Formato de fecha aaaammddhhiiss-->'+
' <time value="--aaaammddhhiiss--"/>'+
' <assignedEntity>'+
' <!-- Identificador único del usuario que introduce los datos en el software'+
' - root: OID del sistema de identificación de usuarios, puede ser uno propio o uno estándar como la cédula profesional'+
' - extension: Valor del dentificador del usuario-->'+
' <id root="--OID del sistema de identificador único del usuario capturista--" extension="--Valor del identificador único del usuario capturista--"/>'+
' <assignedPerson>'+
' <!-- Nombre completo del usuario capturista de este documento -->'+
' <name>'+
' <!--Nombre(s) del Capturista del documento-->'+
' <given>--Nombre(s)--</given>'+
' <!--Primer apellido del Capturista del documento-->'+
' <family>--Primer apellido--</family>'+
' <!--Segundo apellido del Capturista del documento-->'+
' <family>--Segundo apellido--</family>'+
' </name>'+
' </assignedPerson>'+
' </assignedEntity>'+
' </dataEnterer>'+
' '+
' <!-- Responsable del archivamiento, esto es, resguardo del CDA y su documentación original -->'+
' <custodian>'+
' <assignedCustodian>'+
' <representedCustodianOrganization>'+
' <!-- Clave Única del Establecimiento de Salud de acuerdo al catálogo CLUES de la SS/DGIS donde se encuentra la documentación física respaldo de este documento electrónico -->'+
' <id root="2.16.840.1.113883.4.631" extension="--Valor de la CLUES de acuerdo al catálogo--" assigningAuthorityName="CLUES"/>'+
' <!-- Nombre del establecimiento donde se encuentra la documentación física respaldo de este documento electrónico -->'+
' <name>--Nombre del Establecimiento de salud de acuerdo al catálogo de CLUES--</name>'+
' <!-- Medios de contacto del establecimiento donde se encuentra la documentación física respaldo de este documento electrónico -->'+
' <telecom value="tel:--Número telefónico--"/>'+
' <telecom value="mailto:--Correo Electrónico--"/>'+
' '+
' <!-- Domicilio del establecimiento que resguarda la información -->'+
' <addr>'+
' <!-- El texto del elemento tiene la dirección en formato legible-->'+
' -- Domicilio completo en texto libre--'+
' '+
' <!--Tipo de vialidad de acuerdo al catálogo de INEGI-->'+
' <streetNameType>--Valor de tipo de vialidad de acuerdo al catálogo--</streetNameType>'+
' <!--Nombre de la vialidad -->'+
' <streetName>--Nombre de la vialidad--</streetName>'+
' <!--Número exterior (parte numérica)-->'+
' <houseNumberNumeric>--Número exterior (Numérico)--</houseNumberNumeric>'+
' <!--Número exterior (parte alfanumérica) -->'+
' <houseNumber>--Número exterior parte alfanumérica--</houseNumber>'+
' <!--Número interior (parte numérica) -->'+
' <unitID>--Número interior (numérico)--</unitID>'+
' <!--Número interior (parte alfanumérica) -->'+
' <unitType>--Número interior (alfanumérico)--</unitType>'+
' <!--Tipo de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationType>--Valor de Tipo de asentamiento de acuerdo al catálogo--</deliveryInstallationType>'+
' <!--Nombre de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationArea>--Nombre del asentamiento--</deliveryInstallationArea>'+
' <!--Localidad de acuerdo al catálogo de INEGI-->'+
' <precinct>--Valor de Localidad de acuerdo al catálogo--</precinct>'+
' <!--Muncipio de acuerdo al catálogo de INEGI -->'+
' <county>--Valor de Municipio de acuerdo al catálogo--</county>'+
' <!--Entidad de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de Entidad de acuerdo al catálogo--</state>'+
' <!--Código Postal de acuerdo al catálogo de SEPOMEX-->'+
' <postalCode>--Valor de Código Postal de acuerdo al catálogo--</postalCode>'+
' <!--Clave del país de acuerdo al catálogo de nacionalidades-->'+
' <country>--País--</country>'+
' </addr>'+
' </representedCustodianOrganization>'+
' </assignedCustodian>'+
' </custodian>'+
' '+
' <!-- Responsable legal "firmante" de este documento -->'+
' <legalAuthenticator>'+
' <!-- Momento de firma del documento en formato "aaaammddhhiiss"-->'+
' <time value="--aaaammddhhiiss--"/>'+
' <!--Código para determinar si el documento fué firmado y puede terner los siguientes valores:'+
' S = Firmado.'+
' X = Se requiere la firma'+
' -->'+
' <signatureCode code="--Valor del código para determinar si la firma fue plasmada en el documento--"/>'+
' <assignedEntity>'+
' <!-- extension: Cédula profesional del médico responsable legal del documento -->'+
' <id root="2.16.840.1.113883.3.215.12.18" extension="--Número de cédula profesional--"/>'+
' <!-- Domicilio del responsable legal del documento -->'+
' <addr>'+
' <!-- El texto del elemento tiene la dirección en formato legible-->'+
' -- Domicilio completo en texto libre--'+
' '+
' <!--Tipo de vialidad de acuerdo al catálogo de INEGI-->'+
' <streetNameType>--Valor de tipo de vialidad de acuerdo al catálogo--</streetNameType>'+
' <!--Nombre de la vialidad -->'+
' <streetName>--Nombre de la vialidad--</streetName>'+
' <!--Número exterior (parte numérica)-->'+
' <houseNumberNumeric>--Número exterior (Numérico)--</houseNumberNumeric>'+
' <!--Número exterior (parte alfanumérica) -->'+
' <houseNumber>--Número exterior parte alfanumérica--</houseNumber>'+
' <!--Número interior (parte numérica) -->'+
' <unitID>--Número interior (numérico)--</unitID>'+
' <!--Número interior (parte alfanumérica) -->'+
' <unitType>--Número interior (alfanumérico)--</unitType>'+
' <!--Tipo de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationType>--Valor de Tipo de asentamiento de acuerdo al catálogo--</deliveryInstallationType>'+
' <!--Nombre de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationArea>--Nombre del asentamiento--</deliveryInstallationArea>'+
' <!--Localidad de acuerdo al catálogo de INEGI-->'+
' <precinct>--Valor de Localidad de acuerdo al catálogo--</precinct>'+
' <!--Muncipio de acuerdo al catálogo de INEGI -->'+
' <county>--Valor de Municipio de acuerdo al catálogo--</county>'+
' <!--Entidad de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de Entidad de acuerdo al catálogo--</state>'+
' <!--Código Postal de acuerdo al catálogo de SEPOMEX-->'+
' <postalCode>--Valor de Código Postal de acuerdo al catálogo--</postalCode>'+
' <!--Clave del país de acuerdo al catálogo de nacionalidades-->'+
' <country>--País--</country>'+
' </addr>'+
' <!-- Medios de contacto del responsable legal del documento -->'+
' <telecom value="tel:--Número telefónico--"/>'+
' <telecom value="mailto:--Correo Electrónico--"/>'+
' <assignedPerson>'+
' <!-- Nombre completo del responsable legal que firma el documento -->'+
' <name>'+
' <!--Nombre(s) del Responsable legal del documento-->'+
' <given>--Nombre(s)--</given>'+
' <!--Primer apellido del Responsable legal del documento-->'+
' <family>--Primer apellido--</family>'+
' <!--Segundo apellido del Responsable legal del documento-->'+
' <family>--Segundo apellido--</family>'+
' </name>'+
' </assignedPerson>'+
' </assignedEntity>'+
' </legalAuthenticator>'+
' '+
' <!-- Datos del "episodio" (periodo de tiempo con una o más atenciones relacionadas con un problema) que documenta este CDA -->'+
' <documentationOf typeCode="DOC">'+
' <serviceEvent classCode="PCPR">'+
' <!-- Identificador único del "episodio" dentro del sistema que genera este documento'+
' - root: OID del identificador de episodios que se esté ocupando'+
' - extension: Valor del identificador -->'+
' <id root="-- OID del identificador de episodios que se esté ocupando --" extension="--Valor del Identificador único del episodio--"/>'+
' <!-- Tipo de episodio que está documentando este CDA de acuerdo al catálogo de HL7'+
' - Clave - Descripción del tipo de episodio:'+
' EMER - Emergencias'+
' IMP - Hospitalización'+
' AMB - Ambulatorio'+
' HH - Cuidados caseros'+
' ACUTE - Cuidados intensivos / Hospitalización aguda'+
' -->'+
' <code codeSystem="2.16.840.1.113883.5.4" codeSystemName="actCode" code="--Valor del Tipo de episodio de acuerdo al catálogo--" displayName="Nombre del Tipo de episodio de acuerdo al catálogo"/>'+
' <!-- Periodo de tiempo que comprende el episodio -->'+
' <effectiveTime>'+
' <!-- Fecha (hora) en el formato "aaaammddhhiiss" de inicio del episodio copmrendido por este documento -->'+
' <low value="--aaaammddhhiiss--"/>'+
' <!-- Fecha (hora) en el formato "aaaammddhhiiss" de fin del episodio comprendido por este documento -->'+
' <high value="--aaaammddhhiiss--"/>'+
' </effectiveTime>'+
' <!-- Datos del médico responsable'+
' (En caso de que se deseen incluir responsables adicionales al principal, modificar functionCode =\'PP\')'+
' Solo se tienen 3 valores permitidos:'+
' PP - Médico Responsable'+
' CP - Médico Consultado'+
' RP - Médico Referido.'+
' -->'+
' <performer typeCode="PRF">'+
' <functionCode codeSystem="2.16.840.1.113883.12.443" codeSystemName="Provider Role" code="PP" displayName="Primary Care Provider"/>'+
' <assignedEntity>'+
' <!-- extension: Cédula profesional del médico responsable -->'+
' <id root="2.16.840.1.113883.3.215.12.18" extension="--Valor de la Cédula profesional del médico responsable--"/>'+
' <assignedPerson>'+
' <name>'+
' <!-- Nombre completo del médico responsable-->'+
' <given>--Nombre(s)--</given>'+
' <!--Primer apellido del médico responsable-->'+
' <family>--Primer apellido--</family>'+
' <!--Segundo apellido del médico responsable-->'+
' <family>--Segundo apellido--</family>'+
' </name>'+
' </assignedPerson>'+
' <representedOrganization>'+
' <!-- extension: Clave Única del Establecimiento de Salud responsable del episodio, de acuerdo al catálogo de CLUES de la SS/DGIS -->'+
' <id root="2.16.840.1.113883.4.631" extension="--Clave CLUES de acuerdo al catálogo--" assigningAuthorityName="CLUES"/>'+
' <!-- extension: Licencia sanitaria del establecimiento responsable del episodio -->'+
' <id root="2.16.840.1.113883.3.215.1.1" extension="--Valor de la Licencia Sanitaria--" assigningAuthorityName="Licencia Sanitaria"/>'+
' <!-- Nombre del establecimiento de salud responsable del episodio de acuerdo al catálogo de CLUES -->'+
' <name>--Nombre del establecimiento de salud responsable del episodio--</name>'+
' <!-- Medios de contacto del establecimiento responsable del episodio -->'+
' <telecom value="tel:--Número telefónico--"/>'+
' <telecom value="mailto:--Correo electrónico--"/>'+
' <!-- Dirección legible del establecimiento responsable del episodio -->'+
' <addr>'+
' <!-- El texto del elemento tiene la dirección en formato legible-->'+
' -- Domicilio completo en texto libre--'+
' '+
' <!--Tipo de vialidad de acuerdo al catálogo de INEGI-->'+
' <streetNameType>--Valor de tipo de vialidad de acuerdo al catálogo--</streetNameType>'+
' <!--Nombre de la vialidad -->'+
' <streetName>--Nombre de la vialidad--</streetName>'+
' <!--Número exterior (parte numérica)-->'+
' <houseNumberNumeric>--Número exterior (Numérico)--</houseNumberNumeric>'+
' <!--Número exterior (parte alfanumérica) -->'+
' <houseNumber>--Número exterior parte alfanumérica--</houseNumber>'+
' <!--Número interior (parte numérica) -->'+
' <unitID>--Número interior (numérico)--</unitID>'+
' <!--Número interior (parte alfanumérica) -->'+
' <unitType>--Número interior (alfanumérico)--</unitType>'+
' <!--Tipo de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationType>--Valor de Tipo de asentamiento de acuerdo al catálogo--</deliveryInstallationType>'+
' <!--Nombre de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationArea>--Nombre del asentamiento--</deliveryInstallationArea>'+
' <!--Localidad de acuerdo al catálogo de INEGI-->'+
' <precinct>--Valor de Localidad de acuerdo al catálogo--</precinct>'+
' <!--Muncipio de acuerdo al catálogo de INEGI -->'+
' <county>--Valor de Municipio de acuerdo al catálogo--</county>'+
' <!--Entidad de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de Entidad de acuerdo al catálogo--</state>'+
' <!--Código Postal de acuerdo al catálogo de SEPOMEX-->'+
' <postalCode>--Valor de Código Postal de acuerdo al catálogo--</postalCode>'+
' <!--Clave del país de acuerdo al catálogo de nacionalidades-->'+
' <country>--País--</country>'+
' </addr>'+
' </representedOrganization>'+
' </assignedEntity>'+
' </performer>'+
' </serviceEvent>'+
' </documentationOf>'+
' '+
' <!-- Documentación del "encuentro".'+
' Incluir si este CDA documenta únicamente una atención o parte de ella y los datos son diferentes a los del episodio completo.'+
' Por ejemplo si esta es la nota RESULTANTE de una interconsulta o contrarreferencia. -->'+
' <componentOf>'+
' <encompassingEncounter>'+
' <!-- Identificador único del "encuentro" dentro del sistema que genera este documento: '+
' - root OID del identificador de encuentros que se esté ocupando'+
' - extension Valor del identificador -->'+
' <id root="--OID del identificador de encuentros que se esté ocupando--" extension="--Valor del identificador de encuentros que se esté ocupando--"/>'+
' <!-- Tipo de encuentro que está documentando este CDA (ActEncounterCode):'+
' AMB - Ambulatorio'+
' EMER - Emergencia'+
' IMP - Hospitalización'+
' SS - Corta Estancia'+
' HH - Casero'+
' FLD - Fuera del establecimiento de salud'+
' VR - Virtual (Telesalud)'+
' -->'+
' <code codeSystem="2.16.840.1.113883.5.4" codeSystemName="actCode" code="--Valor del Tipo de encuentro--" displayName="--Nombre del Tipo de encuentro--"/>'+
' <!--Periodo de tiempo en el cual ocurrio el encuentro clínico registrado en el documento-->'+
' <effectiveTime>'+
' <!-- Fecha (hora) de inicio del encuentro registrado en el documento en formato "aaaammddhhiiss"-->'+
' <low value="--aaaammddhhiiss--"/>'+
' <!-- Fecha (hora) de fin del encuentro registrado en el documento en formato "aaaammddhhiiss"-->'+
' <high value="--aaaammddhhiiss--"/>'+
' </effectiveTime>'+
' '+
' <!-- Datos del responsable del "encuentro", que pueden ser diferentes a los del episodio completo.-->'+
' <responsibleParty>'+
' <assignedEntity>'+
' <!-- extension: Cédula profesional del médico consultado -->'+
' <id root="2.16.840.1.113883.3.215.12.18" extension="--Valor de la cédula profesional del médico consultado--"/>'+
' <assignedPerson>'+
' <!-- Nombre completo del médico consutlado (Requerido, si se incluye la sección de "encuentro") -->'+
' <name>'+
' <!-- Nombre completo del médico responsable del encuentro-->'+
' <given>--Nombre(s)--</given>'+
' <!--Primer apellido del médico responsable del encuentro-->'+
' <family>--Primer apellido--</family>'+
' <!--Segundo apellido del médico responsable del encuentro-->'+
' <family>--Segundo apellido--</family>'+
' </name>'+
' </assignedPerson>'+
' <representedOrganization>'+
' <!-- root: OID de la organización consultada -->'+
' <id root="--OID de la organización consultada"/>'+
' <!-- Nombre de la organización consultada -->'+
' <name>--Nombre de la organización consultada--</name>'+
' </representedOrganization>'+
' </assignedEntity>'+
' </responsibleParty>'+
' '+
' <!-- Motivo del egreso del paciente para el encuentro en turno:'+
' 1 - Curación'+
' 2 - Mejoría'+
' 3 - Voluntario'+
' 4 - Pase a otro hospital'+
' 5 - Defunción'+
' 6 - Otro motivo'+
' -->'+
' <dischargeDispositionCode codeSystem="2.16.840.1.113883.12.112" codeSystemName="HL7 Discharge Disposition" code="--Código del motivo de egreso--" displayName="--Descripción del motivo del egreso--"/>'+
' '+
' <location>'+
' <healthCareFacility>'+
' <!-- extension: Clave Única del Establecimiento de Salud donde se llevó a cabo el encuentro, de acuerdo al catálogo de CLUES -->'+
' <id root="2.16.840.1.113883.4.631" extension="--Clave CLUES de acuerdo al catálogo--" assigningAuthorityName="CLUES"/>'+
' <!-- extension: Licencia sanitaria del establecimiento consultado -->'+
' <id root="2.16.840.1.113883.3.215.1.1" extension="--Valor de la Licencia Sanitaria--" assigningAuthorityName="Licencia Sanitaria"/>'+
' <!-- Área en la que se realizó el encuentro:'+
' ACC - Lugar del accidente'+
' AMB - Ambulancia'+
' ER - Sala de emergencias'+
' HOSP - Hospitalización'+
' MOBL - Unidad Móvil'+
' OF - Servicios Ambulatorios'+
' PROFF - Consultorio médico'+
' PTRES - Hogar del paciente'+
' -->'+
' <code codeSystem=\'2.16.840.1.113883.5.111\' codeSystemName=\'RoleCode\' code=\'--Código del área del encuentro--\' displayName="--Nombre del área del encuentro--"/>'+
' <location>'+
' <!-- Nombre del establecimiento consultado -->'+
' <name>--Nombre del establecimiento de salud consultado--</name>'+
' <!-- Dirección legible del establecimiento responsable del episodio -->'+
' <addr>'+
' <!-- El texto del elemento tiene la dirección en formato legible-->'+
' -- Domicilio completo en texto libre--'+
' '+
' <!--Tipo de vialidad de acuerdo al catálogo de INEGI-->'+
' <streetNameType>--Valor de tipo de vialidad de acuerdo al catálogo--</streetNameType>'+
' <!--Nombre de la vialidad -->'+
' <streetName>--Nombre de la vialidad--</streetName>'+
' <!--Número exterior (parte numérica)-->'+
' <houseNumberNumeric>--Número exterior (Numérico)--</houseNumberNumeric>'+
' <!--Número exterior (parte alfanumérica) -->'+
' <houseNumber>--Número exterior parte alfanumérica--</houseNumber>'+
' <!--Número interior (parte numérica) -->'+
' <unitID>--Número interior (numérico)--</unitID>'+
' <!--Número interior (parte alfanumérica) -->'+
' <unitType>--Número interior (alfanumérico)--</unitType>'+
' <!--Tipo de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationType>--Valor de Tipo de asentamiento de acuerdo al catálogo--</deliveryInstallationType>'+
' <!--Nombre de asentamiento de acuerdo al catálogo de INEGI-->'+
' <deliveryInstallationArea>--Nombre del asentamiento--</deliveryInstallationArea>'+
' <!--Localidad de acuerdo al catálogo de INEGI-->'+
' <precinct>--Valor de Localidad de acuerdo al catálogo--</precinct>'+
' <!--Muncipio de acuerdo al catálogo de INEGI -->'+
' <county>--Valor de Municipio de acuerdo al catálogo--</county>'+
' <!--Entidad de acuerdo al catálogo de INEGI-->'+
' <state>--Valor de Entidad de acuerdo al catálogo--</state>'+
' <!--Código Postal de acuerdo al catálogo de SEPOMEX-->'+
' <postalCode>--Valor de Código Postal de acuerdo al catálogo--</postalCode>'+
' <!--Clave del país de acuerdo al catálogo de nacionalidades-->'+
' <country>--País--</country>'+
' </addr>'+
' </location>'+
' </healthCareFacility>'+
' </location>'+
' </encompassingEncounter>'+
' </componentOf>'+
''+
' <!-- ******************************************* CUERPO DEL DOCUMENTO, ESTRUCTURADO EN SECCIONES ******************************************************** -->'+
' <component>'+
' <structuredBody>'+
' '+
' <!-- ************************ MOTIVO DEL ENVÍO ************************************** -->'+
' <component>'+
' <section> '+
' <templateId root="1.3.6.1.4.1.19376.1.5.3.1.3.1"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="42349-1" displayName="Motivo de Referencia"/>'+
' <title>Motivo de la referencia</title>'+
' <!--Descripción del motivo de la referencia del paciente a otro prestador de servicios-->'+
' <text>--Detalle del motivo de la referencia--</text>'+
' </section>'+
' </component>'+
' '+
' <!-- ************************************** AFILIACIONES / PLANES DE ASEGURAMIENTO ************************************************* -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.18"/>'+
' <!--Identificador único de Planes de aseguramiento de acuerdo al catálogo LOINC-->'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="48768-6" displayName="Pagador"/>'+
' <title>Afiliaciones / Planes de aseguramiento</title>'+
' <text>'+
' <table border="1" width="100%">'+
' <thead>'+
' <tr>'+
' <th>Inicio</th>'+
' <th>Fin</th>'+
' <th>Programa</th>'+
' <th>Póliza</th>'+
' <th>Folio</th>'+
' <th>Tipo de beneficiario</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Inicio de vigencia N--</td>'+
' <td>--Fin de vigencia N--</td>'+
' <td>--Nombre del programa N--</td>'+
' <td>--Valor del identificador de la póliza N--</td>'+
' <td>--Valor del identificador del beneficiario N--</td>'+
' <td>--Valor del identificador del tipo de beneficiario N--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' </text>'+
' <!-- Datos para cada afiliación / plan de aseguramiento del paciente -->'+
' <entry>'+
' <act classCode="ACT" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="48768-6" displayName="Fuentes de financiamiento"/>'+
' <statusCode code="completed"/>'+
' <entryRelationship typeCode="COMP">'+
' <act classCode="ACT" moodCode="EVN">'+
' <!-- Programa / Plan de seguro'+
' code: clave del programa'+
' displayName: nombre del programa'+
' -->'+
' <code codeSystem="2.16.840.1.113883.5.110" codeSystemName="RoleClass" code="--Identificador/clave del programa--" displayName="--Nombre del programa--"/>'+
' <statusCode code="completed"/>'+
' <!-- Datos de la aseguradora -->'+
' <performer typeCode="PRF">'+
' <time nullFlavor="NA"/>'+
' <assignedEntity>'+
' <!-- Identificador de la dependencia / aseguradora pública o privada-->'+
' <id root="--OID de la dependencia--"/>'+
' <code code="PAYOR" codeSystem="2.16.840.1.113883.5.110" codeSystemName="HL7 RoleCode" />'+
' <representedOrganization>'+
' <name>-- Nombre de la dependencia u organización aseguradora --</name>'+
' </representedOrganization>'+
' </assignedEntity>'+
' </performer>'+
' <participant typeCode="COV"> '+
' <time>'+
' <!-- Inicio de vigencia de cobertura en el formato "aaaammddhhiiss"-->'+
' <low value="--aaaammddhhiiss--"/>'+
' <!-- Fin de vigencia de cobertura en el formato "aaaammddhhiiss"-->'+
' <high value="--aaaammddhhiiss--"/>'+
' </time>'+
' <participantRole classCode="PAT">'+
' <!-- Folio o identificador único del beneficiario en el programa-->'+
' <id root="--OID del identificador de personas del programa dentro de la dependencia--" extension="--Identificador único de la persona dentro del programa--"/>'+
' <!-- Tipo de beneficiario de acuerdo al catálogo de la DGIS -->'+
' <code codeSystem="2.16.840.1.113883.3.215.12.16" codeSystemName="Tipos de beneficario" code="--Valor del identificador de tipo de beneficiario de acuerdo a catálogo--" displayName="--Tipo de beneficiario de acuerdo a catálogo--"/>'+
' </participantRole>'+
' </participant>'+
' <participant typeCode="HLD">'+
' <participantRole>'+
' <!-- Identificador de la póliza de aseguramiento dentro de la organización aseguradora-->'+
' <id root="2.16.840.1.113883.3.215.1.2" extension="--Identificador único de la persona dentro de la póliza--"/>'+
' </participantRole>'+
' </participant>'+
' </act>'+
' </entryRelationship>'+
' </act>'+
' </entry>'+
' </section>'+
' </component>'+
' '+
' <!-- ******************************************************** ALERGIAS (REQUERIDA) ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.22"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="48765-2" displayName="Alergias"/>'+
' <title>Alergias y reacciones adversas</title>'+
' <text>'+
' <table width="100%">'+
' <thead>'+
' <tr>'+
' <th>Alergeno</th>'+
' <th>Fecha inicial</th>'+
' <th>Médico</th>'+
' <th>Reacción</th>'+
' <th>Estado actual</th>'+
' <th>Observaciones</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Nombre del alergeno al que tiene reacción el paciente--</td> '+
' <td>--Fecha y hora en el cuál se realizó la detección en formato "aaaammddhhiiss"--</td>'+
' <td>--Nombre del médico que realizó la detección--</td>'+
' <td>--Descripción de la reacción producida por el alergeno en el paciente--</td>'+
' <td>--Situación actual de la alergia--</td>'+
' <td>--Otros comentarios acerca de la reacción que presenta el paciente--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' </text>'+
' </section>'+
' </component>'+
' '+
' <!-- ******************************************************** ANTECEDENTES HEREDO-FAMILIARES *********************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.1.4"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="10157-6" displayName="Antecedentes Familiares"/>'+
' <title>Antecedentes Heredo-Familiares</title>'+
' <text>'+
' <table width="100%">'+
' <thead>'+
' <tr>'+
' <th>Hipertensión</th>'+
' <th>Dislipidemias</th>'+
' <th>Diabetes</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Sí/No/Sin información--</td>'+
' <td>--Sí/No/Sin información--</td>'+
' <td>--Sí/No/Sin información--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' </text>'+
' <!-- Plantilla para registrar información mínima sobre padecimientos obligatorios -->'+
' <entry typeCode="DRIV">'+
' <organizer moodCode="EVN" classCode="CLUSTER">'+
' <statusCode code="completed" />'+
' <subject>'+
' <relatedSubject classCode="PRS">'+
' <code codeSystem="2.16.840.1.113883.5.111" codeSystemName="HL7 FamilyMember" code="FAMMEMB" displayName="Familiar"/>'+
' </relatedSubject>'+
' </subject>'+
' <component>'+
' <!-- Debe haber una entrada para cada uno de los tres padecimientos -->'+
' '+
' <!-- PRESENCIA DE HIPERTENSIÓN: Incluir si algún familiar del paciente ha tenido el padecimiento.-->'+
' <observation classCode="OBS" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' <statusCode code="completed" />'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="I10X" displayName="Hipertensión"/>'+
' </observation>'+
' '+
' <!-- AUSENCIA DE HIPERTENSIÓN: Incluir si se sabe que ningún familiar del paciente ha tenido el padecimiento.-->'+
' <observation classCode="OBS" moodCode="EVN" negationInd="true">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' <statusCode code="completed" />'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="I10X" displayName="Hipertensión"/>'+
' </observation>'+
' '+
' <!-- SIN INFORMACIÓN DE HIPERTENSIÓN: Incluir si no se cuenta con información sobre si algún familiar del paciente ha tenido el padecimiento.-->'+
' <observation classCode="OBS" moodCode="EVN" nullFlavor="NI">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' <statusCode code="completed" />'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="I10X" displayName="Hipertensión"/>'+
' </observation>'+
' '+
' '+
' '+
' '+
' <!-- PRESENCIA DE DISLIPIDEMIAS: Incluir si algún familiar del paciente ha tenido el padecimiento.-->'+
' <observation classCode="OBS" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' <statusCode code="completed" />'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="E78" displayName="Dislipidemias"/>'+
' </observation>'+
' '+
' <!-- AUSENCIA DE DISLIPIDEMIAS: Incluir si se sabe que ningún familiar del paciente ha tenido el padecimiento.-->'+
' <observation classCode="OBS" moodCode="EVN" negationInd="true">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' <statusCode code="completed" />'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="E78" displayName="Dislipidemias"/>'+
' </observation>'+
' '+
' <!-- SIN INFORMACIÓN DE DISLIPIDEMIAS: Incluir si no se cuenta con información sobre si algún familiar del paciente ha tenido el padecimiento.-->'+
' <observation classCode="OBS" moodCode="EVN" nullFlavor="NI">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' <statusCode code="completed" />'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="E78" displayName="Dislipidemias"/>'+
' </observation>'+
' '+
' '+
' '+
' '+
' <!-- PRESENCIA DE DIABETES: Incluir si algún familiar del paciente ha tenido el padecimiento.-->'+
' <observation classCode="OBS" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' <statusCode code="completed" />'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="E14" displayName="Diabetes"/>'+
' </observation>'+
' '+
' <!-- AUSENCIA DE DIABETES: Incluir si se sabe que ningún familiar del paciente ha tenido el padecimiento.-->'+
' <observation classCode="OBS" moodCode="EVN" negationInd="true">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' <statusCode code="completed" />'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="E14" displayName="Diabetes"/>'+
' </observation>'+
' '+
' <!-- SIN INFORMACIÓN DE DIABETES: Incluir si no se cuenta con información sobre si algún familiar del paciente ha tenido el padecimiento.-->'+
' <observation classCode="OBS" moodCode="EVN" nullFlavor="NI">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' <statusCode code="completed" />'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="E14" displayName="Diabetes"/>'+
' </observation>'+
''+
' <!-- PLANTILLA PARA AGREGAR OTROS ANTECEDENTES HEREDO-FAMILIARES (opcional 0:N) -->'+
' <!-- Repetir el elemento organizer para cada miembro familiar con el que se tenga antecedente patológico-->'+
' <organizer moodCode="EVN" classCode="CLUSTER">'+
' <templateId root="2.16.840.1.113883.10.20.22.4.45" />'+
' <statusCode code="completed" />'+
' <subject>'+
' <relatedSubject classCode="PRS">'+
' <!--'+
' Relación familiar'+
' code: clave de la relación. Si no se conoce "FAMMEMB" (ver 2.16.840.1.113883.1.11.19579 HL7V3 RoleCode dentro de FAMMEMB)'+
' displayName: descripción de la relación'+
' -->'+
' <code codeSystem="2.16.840.1.113883.5.111" codeSystemName="HL7 FamilyMember" code="--Valor del identificador de la relación familiar con el paciente--" displayName="--Nombre de la relación familiar con el paciente--"/>'+
' </relatedSubject>'+
' </subject>'+
' <component>'+
' <!-- Agregar una observación para cada antecedente observado con ese familiar (1:N) -->'+
' <observation classCode="OBS" moodCode="EVN">'+
' <!-- Grado de juicio médico sobre el antecedente.'+
' Es posible sustituir code y displayName por el ValueSet 2.16.840.1.113883.3.88.12.3221.7.2'+
' -->'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="64572001" displayName="Condition"/>'+
' '+
' <!-- Enfermedad a la que se refiere este antecedente -->'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="--Valor del identificador de diagnóstico de acuerdo a catálogo, codificado a 4 dígitos--" displayName="--Nombre de diagnóstico de acuerdo a catálogo--" />'+
' '+
' <!-- Especificación de que fue causa de muerte, omitir elemento completo si no causó muerte -->'+
' <entryRelationship typeCode="CAUS">'+
' <observation classCode="OBS" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.5.4" codeSystemName="HL7ActCode" code="ASSERTION"/>'+
' <statusCode code="completed"/>'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="419099009" displayName="Muerte"/>'+
' </observation>'+
' </entryRelationship>'+
' '+
' <!-- Especificación de edad en que el familiar presentó el padecimiento -->'+
' <entryRelationship typeCode="SUBJ" inversionInd="true">'+
' <observation classCode="OBS" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="397659008" displayName="Edad"/>'+
' <statusCode code="completed"/>'+
' <!-- value: Edad en años-->'+
' <value xsi:type="PQ" value="--Edad en años--" unit="a"/>'+
' </observation>'+
' </entryRelationship>'+
' </observation>'+
' </component>'+
' </organizer>'+
' '+
' </component>'+
' </organizer>'+
' </entry>'+
' </section>'+
' </component>'+
' '+
' <!-- ***************************** ANTECEDENTES PERSONALES NO PATOLÓGICOS ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.4.38"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="29762-2" displayName="Antecedentes no patológicos"/>'+
' <title>Antecedentes personales no patológicos</title>'+
' <text>'+
' <paragraph>Tipo de Sangre: --Tipo de sangre--</paragraph>'+
' <paragraph/>'+
' '+
' <table width="100%">'+
' <thead>'+
' <tr>'+
' <th colspan="6">Tabaquismo</th>'+
' </tr>'+
' <tr>'+
' <th>Fecha de inicio</th>'+
' <th>Fecha de fin</th>'+
' <th>Cigarros por día</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Fecha de inicio del hábito en formato "aaaammddhhiiss"--</td>'+
' <td>--Fecha de termino del hábito en formato "aaaammddhhiiss"--</td>'+
' <td>--Cantidad de cigarros consumido por día--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' <paragraph/>'+
' <table width="100%">'+
' <thead>'+
' <tr>'+
' <th colspan="6">Alcoholismo</th>'+
' </tr>'+
' <tr>'+
' <th>Fecha de inicio</th>'+
' <th>Fecha de fin</th>'+
' <th>Consumo</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Fecha de inicio del hábito en formato "aaaammddhhiiss"--</td>'+
' <td>--Fecha de termino del hábito en formato "aaaammddhhiiss"--</td>'+
' <td>--Cantidad de alcohol consumido por día--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' <paragraph/>'+
' <table width="100%">'+
' <thead>'+
' <tr>'+
' <th colspan="6">Consumo de otras sustancias</th>'+
' </tr>'+
' <tr>'+
' <th>Fecha de inicio</th>'+
' <th>Fecha de fin</th>'+
' <th>Consumo</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Fecha de inicio del hábito en formato "aaaammddhhiiss"--</td>'+
' <td>--Fecha de termino del hábito en formato "aaaammddhhiiss"--</td>'+
' <td>--Sustancia y cantidad de consumo por día--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
''+
' <paragraph>--Otros antecedentes personales no patológicos en texto libre--</paragraph>'+
' <paragraph/>'+
' </text>'+
' '+
' <!-- Tipo de sangre (una entrada)-->'+
' <entry>'+
' <observation classCode="OBS" moodCode="EVN"> '+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="882-1" displayName="GRUPO ABO+RH"/>'+
' <!-- Fecha-hora en que se conoció el tipo de sangre en formato "aaaammddhhiiss" -->'+
' <effectiveTime value="--aaaammddhhiiss--"/>'+
' <!-- code: clave del tipo de sangre -->'+
' <value xsi:type="CS" code="--Tipo de sangre y factor RH--"/>'+
' </observation>'+
' </entry>'+
' '+
' <!-- Fumador (0:N)'+
' Incluir al menos una entrada si es o ha sido fumador. Es posible repetir para cada periodo de consumo.-->'+
' <entry typeCode="DRIV">'+
' <observation classCode="OBS" moodCode="EVN">'+
' <!-- Identificador único por cada periodo -->'+
' <id root="--identificador único por cada periodo de consumo de tabaco--" />'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="229819007" displayName="Uso y exposición al tabaco"/>'+
' <statusCode code="completed" />'+
' <effectiveTime>'+
' <!-- Año/fecha de inicio como fumador -->'+
' <low value="--Año de inicio como fumador--"/>'+
' <!-- Año/fecha de término como fumador-->'+
' <high value="--Año de término como fumador--"/>'+
' </effectiveTime>'+
' <!-- Descripción del Consumo -->'+
' <value xsi:type="ST">--Cantidad de cajetillas por día--</value>'+
' </observation>'+
' </entry>'+
' '+
' <!-- Alcohol (0:N)'+
' Incluir al menos una entrada si es o ha sido alochólico. Es posible repetir para cada periodo de consumo.-->'+
' <entry typeCode="DRIV">'+
' <observation classCode="OBS" moodCode="EVN">'+
' <!-- Identificador único por cada periodo -->'+
' <id root="--identificador único por cada periodo de consumo de alcohol--" />'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="160573003" displayName="Ingesta de Alcohol"/>'+
' <statusCode code="completed" />'+
' <effectiveTime>'+
' <!-- Año/fecha de inicio en el consumo de alcohol -->'+
' <low value="--Año de inicio en el consumo de alcohol--"/>'+
' <!-- Año/fecha de término/cambio en el consumo de alcohol -->'+
' <high value="--Año de término/cambio en el consumo de alcohol--"/>'+
' </effectiveTime>'+
' <!-- Descripción del Consumo -->'+
' <value xsi:type="ST">--Cantidad de consumo de alcohol por día--</value>'+
' </observation>'+
' </entry>'+
' '+
' <!-- Otras sustancias (0:N)'+
' Incluir al menos una entrada si es o ha consumido otras sustancias (e.g. drogas). Es posible repetir para cada periodo de consumo y sustancia.-->'+
' <entry typeCode="DRIV">'+
' <observation classCode="OBS" moodCode="EVN">'+
' <!-- Identificador único por cada periodo -->'+
' <id root="--identificador único por cada periodo de consumo de drogas--" />'+
' <code codeSystem="2.16.840.1.113883.6.96" code="363908000" displayName="Uso indebido de drogas"/>'+
' <statusCode code="completed" />'+
' <effectiveTime>'+
' <!-- Año/fecha de inicio en el consumo de drogas-->'+
' <low value="--Año de inicio en el consumo de drogas--"/>'+
' <!-- Año/fecha de término/cambio en el consumo de drogas-->'+
' <high value="--Año de término/cambio en el consumo de drogas--"/>'+
' </effectiveTime>'+
' <!-- Descripción del consumo de drogas-->'+
' <value xsi:type="ST">--Descripción del consumo de la sustancia--</value>'+
' </observation>'+
' </entry>'+
' </section>'+
' </component>'+
' '+
' <!-- ********************************** ANTECEDENTES PERSONALES PATOLÓGICOS ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.20"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="11348-0" displayName="Antecedentes patológicos"/>'+
' <title>Antecedentes personales patológicos</title>'+
' <text>'+
' <paragraph> --Relación de antecedentes personales patológicos del paciente --</paragraph>'+
' <table>'+
' <tbody>'+
' <tr>'+
' <th>Diabetes</th>'+
' <td>Hipertensión</td>'+
' <td>Hipertiroidismo</td>'+
' </tr> '+
' <tr>'+
' <td>--Tiempo que el paciente lleva con Diabetes--</td>'+
' <td>--Tiempo que el paciente lleva con Hipertensión--</td>'+
' <td>--Tiempo que el paciente lleva con Hipertiroidismo--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' '+
' </text>'+
' '+
' <!-- PRESENCIA DE DIABETES: Incluir al menos esta entrada, si el paciente ha presentado el padecimiento.-->'+
' <entry>'+
' <observation classCode="OBS" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="282291009" displayName="Diagnóstico"/>'+
' <statusCode code="completed"/>'+
' <effectiveTime>'+
' <!-- Año en que fue diagnosticado-->'+
' <low value="--aaaa--"/>'+
' </effectiveTime>'+
' <value xsi:type="CE" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="E14" displayName="Diabetes"/>'+
' </observation>'+
' </entry>'+
' '+
' <!-- PRESENCIA DE HIPERTENSIÓN: Incluir al menos esta entrada, si el paciente ha presentado el padecimiento.-->'+
' <entry>'+
' <observation classCode="OBS" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="282291009" displayName="Diagnóstico"/>'+
' <statusCode code="completed"/>'+
' <effectiveTime>'+
' <!-- Año en que fue diagnosticado-->'+
' <low value="aaaa"/>'+
' </effectiveTime>'+
' <value xsi:type="CE" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="I10X" displayName="Hipertensión"/>'+
' </observation>'+
' </entry>'+
' '+
' '+
' <!-- PRESENCIA DE HIPERTIROIDISMO: Incluir al menos esta entrada, si el paciente ha presentado el padecimiento.-->'+
' <entry>'+
' <observation classCode="OBS" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="282291009" displayName="Diagnóstico"/>'+
' <statusCode code="completed"/>'+
' <effectiveTime>'+
' <!-- Año en que fue diagnosticado-->'+
' <low value="aaaa"/>'+
' </effectiveTime>'+
' <value xsi:type="CE" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="E05" displayName="Hipertiroidismo"/>'+
' </observation>'+
' </entry>'+
' '+
' <!-- Repetir para cada padecimiento en la historia clínica del paciente previo al episodio actual (opcional, 0:N)-->'+
' <entry>'+
' <observation classCode="OBS" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="282291009" displayName="Diagnóstico"/>'+
' <!-- Diagnóstico (texto libre introducido) -->'+
' <text>--Registro de diagnóstico en texto libre--</text>'+
' <statusCode code="completed"/>'+
' <effectiveTime>'+
' <!-- Fecha de diagnóstico del antecedente patológico en formato "aaaammddhhiiss" -->'+
' <low value="aaaammddhhiiss"/> '+
' </effectiveTime>'+
' <!-- Enfermedad'+
' code: código cie-10 de la enfermedad de acuerdo al catálogo del CEMECE'+
' displayName: descripción de acuerdoa CIE-10 de la enfermedad'+
' -->'+
' <value xsi:type="CE" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="--Valor del identificador del diagnóstico de acuerdo a catálogo--" displayName="--Nombre del diagnóstico de acuerdo a catálogo--"/>'+
' </observation>'+
' </entry>'+
' '+
' </section>'+
' </component>'+
''+
''+
' <!-- **************************************** DISCAPACIDADES ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root=\'2.16.840.1.113883.10.20.22.2.14\'/>'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="21134002" displayName="Discapacidades"/>'+
' <title>Discapacidades</title>'+
' <text>'+
' --Descripción de discapacidades y estado del funcionamiento--'+
' </text>'+
' '+
' <!-- Repetir para cada discapacidad que presente el paciente (0:n)-->'+
' <entry typeCode="DRIV">'+
' <observation classCode="OBS" moodCode="EVN">'+
' <id root="--Identificador único de la discapacidad del paciente--"/>'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="248536006" displayName="Discapacidades"/> '+
' <statusCode code="completed"/>'+
' <!-- Discapacidad '+
' code: clave de la discapacidad de acuerdo a CIF'+
' displayName: descripción de la discapacidad correspondiente a code'+
' -->'+
' <value xsi:type="CD" codeSystem="2.16.840.1.113883.6.254" codeSystemName="CIF" code="--Valor del identificador de discapacidad de acuerdo a catálogo--" displayName="--Nombre de discapacidad de acuerdo a catálogo--"/>'+
' </observation>'+
' </entry>'+
' </section>'+
' </component>'+
' '+
' '+
' <!-- **************************************** MEDICAMENTOS PREVIOS Y ACTUALES******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.1"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="10160-0" displayName="Antecedentes de medicamentos"/>'+
' <title>Historial farmacológico</title>'+
' <text>'+
' <table >'+
' <thead>'+
' <tr>'+
' <th>Medicamento</th>'+
' <th>Via de administración</th>'+
' <th>Dosis</th>'+
' <th>Fecha de inicio</th>'+
' <th>Fecha de fin</th>'+
' <th>Obs. prescripción</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Nombre del medicamento/substancia activa--</td>'+
' <td>--Vía de administración--</td>'+
' <td>--Dosis por administrar--</td>'+
' <td>--Fecha y hora de inicio de administración de medicamento--</td>'+
' <td>--Fecha y hora de término de administración de medicamento--</td>'+
' <td>--Observaciones adicionales acerca de la prescripción--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' </text>'+
' '+
' <!-- Para cada medicamento relevante al episodio actual que el paciente consuma o haya consumido anteriormente (0:n)-->'+
' <entry>'+
' <substanceAdministration classCode="SBADM" moodCode="EVN" negationInd="false">'+
' <!-- Observaciones generales sobre la medicación *debe aparecer textual en el texto de la sección o referenciarlo* -->'+
' <text>--Observaciones generales del medicamento relevante al episodio--</text>'+
' <statusCode code="completed"/> '+
' <!-- Vía de administración de acuerdo con el catálogo del Cuadro Básico de Medicamentos -->'+
' <routeCode codeSystem="2.16.840.1.113883.3.215.12.12" codeSystemName="Vía de Administración CBM" code="--Valor del identificador de Vía de administración--" displayName="--Nombre de Vía de administración--"/>'+
' <!-- Dosis y frecuencia-->'+
' <doseQuantity>'+
' <center value="--Cantidad administrada y frecuencia--"/>'+
' </doseQuantity>'+
' <effectiveTime>'+
' <!-- Fecha de inicio de administración de medicamento en formato "aaaammddhhiiss"-->'+
' <low value="--aaaammddhhiiss--"/>'+
' <!-- Fecha de término de administración de medicamento en formato "aaaammddhhiiss"-->'+
' <high value="--aaaammddhhiiss--"/>'+
' </effectiveTime> '+
' <consumable>'+
' <manufacturedProduct classCode="MANU">'+
' <manufacturedMaterial>'+
' <!-- Medicamento de acuerdo con catálogo del Cuadro Básico de Medicamentos'+
' code: clave en el Cuadro Básico'+
' displayName: descripción del medicamento-->'+
' <code codeSystem="2.16.840.1.113883.3.215.12.8" codeSystemName="Cuadro Básico de Medicamentos" code="--Valor del identificador del Medicamento de acuerdo a catálogo--" displayName="--Nombre del medicamento de acuerdo a catálogo--"/>'+
' </manufacturedMaterial>'+
' </manufacturedProduct>'+
' </consumable>'+
' </substanceAdministration>'+
' </entry>'+
' </section>'+
' </component>'+
' '+
' <!-- ******************************************************** Manifestaciones iniciales ****************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="1.3.6.1.4.1.19376.1.5.3.1.1.13.2.1"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="10154-3" displayName="Manifestaciones Iniciales"/>'+
' <title>Manifestaciones iniciales</title>'+
' <!-- Sintomatología descrita por el paciente desde su aparición, por lo que se origina este episodio.-->'+
' <text>--Sintomatología que origina el episodio descrita por el paciente--</text>'+
' </section>'+
' </component>'+
' '+
' '+
' <!-- ******************************************************** Impresión diagnóstica ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.8"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="51848-0" displayName="Impresión diagnóstica"/>'+
' <title>Impresión diagnóstica</title>'+
' <text>--Estado del paciente en evaluación inicial descrito por profesionale de la salud que lo recibió--</text>'+
' </section>'+
' </component>'+
' '+
' <!-- ******************************************************** DIAGNÓSTICOS ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.5"/>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.5.1"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="11450-4" displayName="Lista de Problemas"/>'+
' <title>Diagnósticos y problemas de salud</title>'+
' <text>'+
' <table width="100%">'+
' <thead>'+
' <tr>'+
' <th>Tipo</th>'+
' <th>Fecha</th>'+
' <th>CIE</th>'+
' <th>Diagnóstico</th>'+
' <th>Observaciones</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Tipo de diagnóstico--</td>'+
' <td>--Fecha y hora en el cual se presentó el problema diagnosticado--</td>'+
' <td>--Clave CIE 10 del diagnóstico de acuerdo a catálogo--</td>'+
' <td>--Descripción de la diagnóstico escrito por el médico--</td>'+
' <td>--Observaciones adicionales acerca del diagnóstico--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' </text>'+
' '+
' <!-- Repetir para cada problema de salud registrado en el episodio que documenta este CDA (0:n) -->'+
' <entry typeCode="DRIV">'+
' <act classCode="ACT" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.5.6" code="CONC" displayName="Concern"/>'+
' <statusCode code="completed"/>'+
' <effectiveTime>'+
' <low value="--Fecha y hora de inicio de la afección / problema--"/>'+
' <high value="--Fecha y hora de término de la afección / problema--"/>'+
' </effectiveTime>'+
' <entryRelationship typeCode="SUBJ">'+
' <observation classCode="OBS" moodCode="EVN">'+
' <!-- root: Identificador único '+
' extension: Número de afección-->'+
' <id root="--Identificador único de la afección--" extension="--Número de la afección--"/>'+
' <!-- Tipo de diagnóstico. Indicar si se trata de la afección principal, comorbilidad, causa externa, etc. o diagnóstico en general.-->'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="282291009" displayName="Diagnóstico"/>'+
' <!-- Enfermedad (texto libre introducido) -->'+
' <text>--Descripción en texto libre del diagnóstico introducido por el médico--</text>'+
' <statusCode code="completed"/>'+
' <!-- La codificación debe realizarse a 4 dígitos de acuerdo al catálogo CIE-10 del CEMECE -->'+
' <value xsi:type="CE" codeSystem="2.16.840.1.113883.6.3" codeSystemName="ICD-10" code="--Valor del identificador del diagnóstico de acuerdo a catálogo--" displayName="--Nombre del diagnóstico de acuerdo a catálogo--"/>'+
' </observation>'+
' </entryRelationship>'+
' </act>'+
' </entry>'+
' '+
' </section>'+
' </component>'+
' '+
' <!-- ******************************************************** PROCEDIMIENTOS ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.1.12"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="47519-4" displayName="Historial de procedimientos"/>'+
' <title>Procedimientos quirúrgicos y terapéuticos</title>'+
' <text>'+
' <table width="100%">'+
' <thead>'+
' <tr>'+
' <th>CIE9-MC</th>'+
' <th>Procedimiento</th>'+
' <th>Estado</th>'+
' <th>Activo</th>'+
' <th>Observaciones</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Valor del identificador del procedimiento de acuerdo a catálogo CIE9-MC --</td>'+
' <td>--Nombre del procedimiento de acuerdo a catálogo CIE9-MC --</td>'+
' <td>--Situación actual en la que se encuentra el procedimiento--</td>'+
' <td>--Señalamiento si el procedimiento se encuentra activo (Si / No) --</td>'+
' <td>--Observaciones adicionales acerca del procedimiento--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' </text>'+
' '+
' <!-- Repetir para cada procedimiento realizado durante el episodio que documenta este CDA (0:n) -->'+
' <entry typeCode="DRIV">'+
' <procedure classCode="PROC" moodCode="EVN">'+
' <!-- Procedimiento'+
' code= Código CIE-9MC'+
' displayName= descripción de acuerdo al catálogo -->'+
' <code codeSystem="2.16.840.1.113883.6.2" codeSystemName="ICD-9CM" code="--Valor del identificador del procedimiento de acuerdo a catálogo--" displayName="--Nombre del procedimiento de acuerdo a catálogo--">'+
' <!-- Procedimiento en texto libre introducido por el médico -->'+
' <originalText>-- Procedimiento en texto libre introducido por el médico --</originalText>'+
' </code>'+
' <statusCode code="completed"/>'+
' <!-- Fecha o fecha-hora de la realización del procedimiento en formato "aaaammddhhiiss"-->'+
' <effectiveTime value="--aaaammddhhiiss--"/>'+
' <performer>'+
' <assignedEntity>'+
' <!-- Cédula del médico responsable del procedimiento-->'+
' <id root="2.16.840.1.113883.3.215.12.18" extension="--Número de cédula profesional del médico responsable del procedimiento--"/>'+
' <assignedPerson>'+
' <!-- Nombre completo del médico responsable del procedimiento -->'+
' <name>'+
' <given>--Nombre(s) del médico responsable del procedimiento--</given>'+
' <family>--Primer apellido del médico responsable del procedimiento--</family>'+
' <family>--Segundo apellido del médico responsable del procedimiento--</family>'+
' </name>'+
' </assignedPerson>'+
' </assignedEntity>'+
' </performer>'+
' <participant typeCode="LOC">'+
' <participantRole classCode="SDLOC">'+
' <!-- Ubicación/Servicio donde se realizó el procedimiento -->'+
' <code codeSystem="2.16.840.1.113883.6.259" codeSystemName="HealthcareServiceLocation" code="--Clave de la ubicación (serivicio) donde se realizó el procedimiento--" displayName="--ubicación (serivicio) donde se realizó el procedimiento--"/>'+
' </participantRole>'+
' </participant>'+
' </procedure>'+
' </entry>'+
' </section>'+
' </component>'+
' '+
' <!-- ******************************************************** MEDICAMENTOS ADMINISTRADOS DURANTE LA ATENCIÓN ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.38"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="29549-3" displayName="Medicamentos administrados"/>'+
' <title>Terapéutica empleada</title>'+
' <text>'+
' <table>'+
' <thead>'+
' <tr>'+
' <th>Medicamento</th>'+
' <th>Via de administración</th>'+
' <th>Dosis</th>'+
' <th>Fecha de inicio</th>'+
' <th>Fecha de fin</th>'+
' <th>Obs. prescripción</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Nombre del medicamento/substancia activa--</td>'+
' <td>--Vía de administración--</td>'+
' <td>--Dosis por administrar--</td>'+
' <td>--Fecha y hora de inicio de administración de medicamento"--</td>'+
' <td>--Fecha y hora de término de administración de medicamento"--</td>'+
' <td>--Observaciones adicionales acerca de la prescripción--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' </text>'+
' '+
' <!-- Para cada medicamento administrado durante el epsidoio documentado en este CDA (0:n)-->'+
' <entry>'+
' <substanceAdministration classCode="SBADM" moodCode="EVN" negationInd="false">'+
' <!-- Observaciones generales sobre la medicación *debe aparecer textual en el texto de la sección o referenciarlo* -->'+
' <text>--Observaciones generales del medicamento administrado--</text>'+
' <statusCode code="completed"/>'+
' <!-- Vía de administración de acuerdo con el catálogo del Cuadro Básico de Medicamentos -->'+
' <routeCode codeSystem="2.16.840.1.113883.3.215.12.12" codeSystemName="Vía de Administración CBM" code="--Valor del identificador de Vía de administración--" displayName="--Nombre de Vía de administración--"/>'+
' <!-- Dosis y frecuencia-->'+
' <doseQuantity>'+
' <center value="--Cantidad administrada y frecuencia--"/>'+
' </doseQuantity>'+
' <effectiveTime>'+
' <!-- Fecha de inicio de administración de medicamento en formato "aaaammddhhiiss"-->'+
' <low value="--aaaammddhhiiss--"/>'+
' <!-- Fecha de término de administración de medicamento en formato "aaaammddhhiiss"-->'+
' <high value="--aaaammddhhiiss--"/>'+
' </effectiveTime>'+
' <consumable>'+
' <manufacturedProduct classCode="MANU">'+
' <manufacturedMaterial>'+
' <!-- Medicamento de acuerdo con catálogo del Cuadro Básico de Medicamentos'+
' code: clave en el Cuadro Básico'+
' displayName: descripción del medicamento-->'+
' <code codeSystem="2.16.840.1.113883.3.215.12.8" codeSystemName="Cuadro Básico de Medicamentos" code="--Valor del identificador del Medicamento de acuerdo a catálogo--" displayName="--Nombre del medicamento de acuerdo a catálogo--"/>'+
' </manufacturedMaterial>'+
' </manufacturedProduct>'+
' </consumable>'+
' </substanceAdministration>'+
' </entry>'+
''+
' </section>'+
' </component>'+
' '+
' <!-- *************************************** Evolución durante la atención ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="1.3.6.1.4.1.19376.1.5.3.1.3.5"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="8648-8" displayName="Evolución"/>'+
' <title>Evolución durante la atención</title>'+
' <text>'+
' --Narrativa describiendo brevemente la evolución que el paciente ha tenido durante esta atención médica--'+
' </text>'+
' </section>'+
' </component>'+
' '+
' <!-- *************************************** Signos vitales ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.4"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="8716-3" displayName="Signos Vitales"/>'+
' <title>Signos vitales</title>'+
' <text>'+
' <table width="100%">'+
' <thead>'+
' <tr>'+
' <th>Fecha</th>'+
' <th>Signo</th>'+
' <th>Valor</th>'+
' <th>Observaciones</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <tr>'+
' <td>--Fecha y hora de la toma del signo vital en formato "aaaammddhhiiss"--</td>'+
' <td>--Nombre / descripción del signo vital--</td>'+
' <td>--Valor / resultado del signo vital--</td>'+
' <td>--Observaciones generales acerca del resultado del signo vital--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' </text>'+
' '+
' <entry>'+
' <organizer classCode="CLUSTER" moodCode="EVN">'+
' <code codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" code="46680005" displayName="Signos vitales"/>'+
' <statusCode code="completed"/>'+
' '+
' <!-- Repetir para cada signo/medición -->'+
' <component>'+
' <observation classCode="OBS" moodCode="EVN">'+
' <!-- Signo vital'+
' code: clave del signo vital'+
' displayName: nombre del signo vital'+
' -->'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="--Valor del identificador del signo vital a medir--" displayName="--Nombre del signo vital a medir--"/>'+
' <statusCode code="completed"/>'+
' <!-- Fecha-hora de la toma del signo vital -->'+
' <effectiveTime value="--aaaammddhhiiss--"/>'+
' <!-- Valor'+
' value: medición física'+
' unit: unidades'+
' -->'+
' <value xsi:type="PQ" value="--Resultado de la medición--" unit="--Unidad de expresión del resultado--"/>'+
' </observation>'+
' </component>'+
' </organizer>'+
' </entry>'+
' '+
' </section>'+
' </component>'+
' '+
' <!-- ************************************************** Resultados de laboratorio ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.3.1"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="30954-2" displayName="Estudios de Laboratorio"/>'+
' <title>Estudios de laboratorio</title>'+
' <text>'+
' <!-- Repetir para cada batería realizada en el episodio -->'+
' <paragraph>--Identificación de la batería de pruebas o estudios de laboratorio realizados--</paragraph>'+
' <table width="100%">'+
' <thead>'+
' <tr>'+
' <th>Prueba</th>'+
' <th>Fecha de resultado</th>'+
' <th>Resultado</th>'+
' <th>Rango</th>'+
' </tr>'+
' </thead>'+
' <tbody>'+
' <!-- Agregar tantos renglones como sea necesario, de acuerdo a la totalidad de resultados -->'+
' <tr>'+
' <td>--Nombre de la prueba o analito--</td>'+
' <td>--Fecha y hora del resultado--</td>'+
' <td>--Valor y unidad del resultado--</td>'+
' <td>--Rango de referencia para el resultado de acuerdo al perfil del paciente--</td>'+
' </tr>'+
' </tbody>'+
' </table>'+
' <!-- (fin de repetición de cada batería) -->'+
' </text>'+
' <entry>'+
' '+
' <!-- Repetir para cada batería realizada en el episodio (0:N) -->'+
' <organizer classCode="BATTERY" moodCode="EVN">'+
' <!-- Tipo de batería realizada -->'+
' <code codeSystem="--OID del sistema de codificación--" codeSystemName="--Nombre del sistema de codificación--" code="--Clave de la batería realizada--" displayName="--Nombre de la batería"/>'+
' <statusCode code="completed"/>'+
' '+
' <!-- Repetir para cada resultado obtenido de las pruebas o estudios de laboratorio de la batería (0:N) -->'+
' <component>'+
' <observation classCode="OBS" moodCode="EVN">'+
' <!-- Tipo de prueba realizada -->'+
' <code codeSystem="--OID del sistema de codificación--" codeSystemName="--Nombre del sistema de codificación--" code="--Clave de la prueba realizada--" displayName="--Nombre de la prueba realizada--"/>'+
' <statusCode code="completed"/>'+
' <!-- Fecha-hora del resultado -->'+
' <effectiveTime value="--aaaammddhhiiss--"/>'+
' <!-- Valor del resultado -->'+
' <value xsi:type="PQ" value="--Resultado de la medición--" unit="--Unidad de expresión del resultado--"/>'+
' <referenceRange>'+
' <observationRange>'+
' <text>--Rango de referencia para el resultado--</text>'+
' </observationRange>'+
' </referenceRange>'+
' </observation>'+
' </component>'+
' '+
' </organizer>'+
' '+
' </entry>'+
' </section>'+
' </component>'+
' '+
' <!-- ************************************************** Plan de tratamiento ******************************************************** -->'+
' <component>'+
' <section>'+
' <templateId root="2.16.840.1.113883.10.20.22.2.10"/>'+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="18776-5" displayName="Plan de tratamiento"/>'+
' <title>Plan de tratamiento y recomendaciones terapéuticas</title>'+
' <text>'+
' -- Indicaciones generales que deben seguir el paciente y/o equipo de atención, así como un listado de los medicamentos prescritos al alta del paciente. --'+
' </text>'+
' </section>'+
' </component>'+
' '+
' <!-- *************************************** Pronóstico de salud ******************************************************** -->'+
' <component>'+
' <section> '+
' <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="47420-5" displayName="Evaluación del Estado Funcional"/>'+
' <title>Pronóstico de salud del paciente</title>'+
' <text>--Pronóstico de la salud del paciente en texto libre--</text>'+
' </section>'+
' </component>'+
' </structuredBody>'+
' </component>'+
'</ClinicalDocument>';
// Create File
var file = nlapiCreateFile('searchresults123.xml', 'XMLDOC', myvar);
file.setFolder(-4); // 1139356
file.setEncoding('UTF-8');
var fileId = nlapiSubmitFile(file);
// You can either write result on the same page
response.setContentType(file.getType());
response.write(file.getValue());
/*nlapiLogExecution('AUDIT', 'SL| invoke_ws(xml) response:', bodyResp);
// create file
if (valtranid != null && valtranid !== '' && valentity != null && valentity !== '' && respp == 'Archivo TXT cargado Correctamente') {
var mesfolder = getMesFolder(month);
var newFile = nlapiCreateFile(fileName, 'PLAINTEXT', valTXT);
newFile.setFolder(mesfolder); // 1139356
newFile.setEncoding('UTF-8');
var fileId = nlapiSubmitFile(newFile);
inRecord.setFieldValue('custbody45', respp);
inRecord.setFieldValue('custbody33', 'Si');
inRecord.setFieldValue('custbody46', fileName + ' | ' + detalleFac);
nlapiLogExecution('AUDIT', 'SL| PROCESADO (INVOICECO): ', 'Value PROCESADO (INVOICECO): Si');
nlapiSubmitRecord(inRecord, false, true);
nlapiLogExecution('AUDIT', 'SL| crearFacturaCo(): ', 'Invoice redirecting...');
nlapiSetRedirectURL('RECORD', 'invoice', idparam, false);
}
else if(respp !== 'Archivo TXT cargado Correctamente'){
inRecord.setFieldValue('custbody45', respp);
inRecord.setFieldValue('custbody33', 'No');
nlapiLogExecution('AUDIT', 'SL| PROCESADO (INVOICECO): ', 'Value PROCESADO (INVOICECO): No');
nlapiSubmitRecord(inRecord, false, true);
nlapiLogExecution('AUDIT', 'SL| crearFacturaCo(): ', 'Invoice redirecting...');
nlapiSetRedirectURL('RECORD', 'invoice', idparam, false);
}*/
}
function invoke_ws(xml){
//Set up Headers
var headers = new Array();
headers['User-Agent-x'] = 'SuiteScript-Call';
headers['Content-Type'] = 'text/xml; charset=utf-8';
headers['Content-Length']= 'length';
headers['SOAPAction'] = 'http://tempuri.org/CargarTxt';
var url = 'http://api.stupendo.co/ServicioCargaTxtColombia/WebServiceReceptaProceso.asmx'; // http://184.106.39.67/ServicioCargaTxtColombia/WebServiceReceptaProceso.asmx
var resp = null;
if (xml) {
// blindly re-try upon error
try{
resp = nlapiRequestURL(url, xml, headers);
}catch(e){
resp = nlapiRequestURL(url, xml, headers);
}
}
else{
resp = nlapiRequestURL(url, null , headers);
}
return resp.getBody();
} |
//take 2 objects that have string arrays and alternately print them out to the console
function AlternatingStrings(obj1, obj2) {
//find the smaller arrays
let smallerArray = Math.min(obj1.stringArray.length, obj2.stringArray1.length);
let fullString = '';
for (let i = 0; i < smallerArray; i++) {
fullString = `${obj1.stringArray[i]} ${obj2.stringArray1[i]}`;
}
return fullString;
}
let myObj1 = { stringArray: ["This", "a", "cool", "demo"], bigNumber: 12345678965412362n, currentDate: new Date() };
let myObj2 = { stringArray1: ["is", "really", "TypeScript", "."], isTrueOrFalse: true, integer: 100 };
let resultStirng = AlternatingStrings(myObj1, myObj2);
console.log(resultStirng +"abvc");
|
from __future__ import print_function # In python 2.7
import os, sys
sys.path.append('/home/ubuntu/sebastian')
from flask import Flask, request, redirect, url_for, json, make_response, request
from flask import send_from_directory
from flask import render_template
from werkzeug import secure_filename
import random, string
import Generator
UPLOAD_FOLDER_PREFIX = 'static/files/{}'
ALLOWED_EXTENSIONS = set(['mid'])
app = Flask(__name__)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
folder_name = request.cookies.get('foldername')
if not folder_name:
print("no foldername")
folder_name = get_foldername()
folder_path = os.makedirs(UPLOAD_FOLDER_PREFIX.format(folder_name))
print(folder_path)
# folder_name = request.cookies.get('foldername')
upload_folder = UPLOAD_FOLDER_PREFIX.format(folder_name)
if request.method == 'POST':
upload_files = request.files.getlist("file[]")
ticks = int(request.form['ticks'])
nsize = int(request.form['nsize'])
policy = request.form['policy']
for f in upload_files:
if f and allowed_file(f.filename):
filename = secure_filename(f.filename)
destination = os.path.join(upload_folder, filename)
f.save(destination)
Generator.generate(filename, ticks, folder=upload_folder, nsize=nsize, policy=policy)
return redirect(url_for('upload_file'))
songs = os.listdir(upload_folder)
resp = make_response(render_template("index.html",
title='Sebastian Music', songs=songs, upload_folder=upload_folder))
resp.set_cookie('foldername', folder_name)
return resp
def get_foldername():
STRING_LENGTH = 20
folder_name = ''.join(random.choice(string.lowercase) for i in range(STRING_LENGTH))
while os.path.exists(folder_name):
folder_name = ''.join(random.choice(string.lowercase) for i in range(STRING_LENGTH))
return folder_name
@app.route('/delete_song', methods=['POST'])
def delete_song():
song = request.form['song']
os.remove(song)
return redirect(url_for('upload_file'))
# @app.route('/songs')
# def index():
# music_files = [f for f in os.listdir(UPLOAD_FOLDER) if f.endswith('mid')]
# music_files_number = len(music_files)
# return render_template("songs.html",
# title = 'Songs Available',
# music_files_number = music_files_number,
# music_files = music_files)
@app.route('/songs/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
if __name__ == '__main__':
# app.run(debug=True)
app.run(port=5001)
|
/**
* Riode Main Javascript File
*/
"use strict";
var $ = jQuery.noConflict();
/* jQuery easing */
$.extend($.easing, {
def: 'easeOutQuad',
swing: function (x, t, b, c, d) {
return $.easing[$.easing.def](x, t, b, c, d);
},
easeOutQuad: function (x, t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
}
});
/**
* Riode Object
*/
window.Riode = {};
(function () {
// Riode Properties
Riode.$window = $(window);
Riode.$body = $(document.body);
Riode.status = ''; // Riode Status
Riode.minDesktopWidth = 992; // Detect desktop screen
Riode.isIE = navigator.userAgent.indexOf("Trident") >= 0; // Detect Internet Explorer
Riode.isEdge = navigator.userAgent.indexOf("Edge") >= 0; // Detect Edge
Riode.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); // Detect Mobile
Riode.resizeChanged = false;
Riode.canvasWidth = window.innerWidth;
Riode.resizeTimeStamp = 0;
Riode.defaults = {
animation: {
name: 'fadeIn',
duration: '1.2s',
delay: '.2s'
},
isotope: {
itemsSelector: '.grid-item',
layoutMode: 'masonry',
percentPosition: true,
masonry: {
columnWidth: '.grid-space'
},
sortBy: 'original-order'
},
minipopup: {
// info
message: '',
productClass: '', // ' product-cart', ' product-list-sm'
imageSrc: '',
imageLink: '#',
name: '',
nameLink: '#', // 'product.html',
price: '',
count: null,
rating: null,
actionTemplate: '',
isPurchased: false,
// option
delay: 4000, // milliseconds
space: 20,
// template
priceTemplate: '<span class="product-price">{{price}}</span>',
ratingTemplate: '<div App="ratings-container"><div App="ratings-full"><span App="ratings" style="width:{{rating}}"></span><span App="tooltiptext tooltip-top"></span></div></div>',
priceQuantityTemplate: '<div App="price-box"><span App="product-quantity">{{count}}</span><span App="product-price">{{price}}</span></div>',
purchasedTemplate: '<span class="purchased-time">12 MINUTES AGO</span>',
template: '<div App="minipopup-box"><p App="minipopup-title">{{message}}</p>' +
'<div class="product product-purchased {{productClass}} mb-0">' +
'<figure class="product-media"><a href="{{imageLink}}"><img src="{{imageSrc}}" alt="product" width="90" height="90"></a></figure>' +
'<div class="product-detail">' +
'<a href="{{nameLink}}" class="product-name">{{name}}</a>' +
'{{detailTemplate}}' +
'</div>' +
'</div>' +
'{{actionTemplate}}' +
'</div>',
},
popup: {
removalDelay: 350,
callbacks: {
open: function () {
$('html').css('overflow-y', 'hidden');
$('body').css('overflow-x', 'visible');
$('.mfp-wrap').css('overflow', 'hidden auto');
$('.sticky-header.fixed').css('padding-right', window.innerWidth - document.body.clientWidth);
},
close: function () {
$('html').css('overflow-y', '');
$('body').css('overflow-x', 'hidden');
$('.mfp-wrap').css('overflow', '');
$('.sticky-header.fixed').css('padding-right', '');
}
}
},
popupPresets: {
login: {
type: 'ajax',
mainClass: "mfp-login mfp-fade",
tLoading: '',
preloader: false
},
video: {
type: 'iframe',
mainClass: "mfp-fade",
preloader: false,
closeBtnInside: false
},
img: {
type: 'iframe',
mainClass: "mfp-fade",
preloader: false,
closeBtnInside: false
},
quickview: {
type: 'ajax',
mainClass: "mfp-product mfp-fade",
tLoading: '',
preloader: false
}
},
slider: {
responsiveClass: true,
navText: ['<i class="d-icon-angle-left">', '<i class="d-icon-angle-right">'],
checkVisible: false,
items: 1,
smartSpeed: Riode.isEdge ? 200 : 500,
autoplaySpeed: Riode.isEdge ? 200 : 1000,
autoplayTimeout: 10000
},
sliderPresets: {
'intro-slider': {
animateIn: 'fadeIn',
animateOut: 'fadeOut'
},
'product-single-carousel': {
dots: false,
nav: true,
},
'product-gallery-carousel': {
dots: false,
nav: true,
margin: 20,
items: 1,
responsive: {
576: {
items: 2
},
768: {
items: 3
}
},
},
'rotate-slider': {
dots: false,
nav: true,
margin: 0,
items: 1,
animateIn: '',
animateOut: ''
}
},
sliderThumbs: {
margin: 0,
items: 4,
dots: false,
nav: true,
navText: ['<i class="fas fa-chevron-left">', '<i class="fas fa-chevron-right">']
},
stickyContent: {
minWidth: Riode.minDesktopWidth,
maxWidth: 20000,
top: 300,
hide: false, // hide when it is not sticky.
max_index: 1060, // maximum z-index of sticky contents
scrollMode: false
},
stickyHeader: {
// activeScreenWidth: Riode.minDesktopWidth
activeScreenWidth: 768
},
stickyFooter: {
minWidth: 0,
maxWidth: 767,
top: 150,
hide: true,
scrollMode: true
},
stickyToolbox: {
minWidth: 0,
maxWidth: 767,
top: false,
scrollMode: true
},
stickySidebar: {
autoInit: true,
minWidth: 991,
containerSelector: '.sticky-sidebar-wrapper',
autoFit: true,
activeClass: 'sticky-sidebar-fixed',
paddingOffsetTop: 67,
paddingOffsetBottom: 0,
},
templateCartAddedAlert: '<div class="alert alert-simple alert-btn cart-added-alert">' +
'<a href="cart.html" class="btn btn-success btn-md">View Cart</a>' +
'<span>"{{name}}" has been added to your cart.</span>' +
'<button type="button" App="btn btn-link btn-close"><i App="d-icon-times"></i></button>' +
'</div>',
zoomImage: {
responsive: true,
zoomWindowFadeIn: 750,
zoomWindowFadeOut: 500,
borderSize: 0,
zoomType: 'inner',
cursor: 'crosshair'
}
}
/**
* Get jQuery object
* @param {string|jQuery} selector
*/
Riode.$ = function (selector) {
return selector instanceof jQuery ? selector : $(selector);
}
/**
* Make a macro task
* @param {function} fn
* @param {number} delay
*/
Riode.call = function (fn, delay) {
setTimeout(fn, delay);
}
/**
* Get dom element by id
* @param {string} id
*/
Riode.byId = function (id) {
return document.getElementById(id);
}
/**
* Get dom elements by tagName
* @param {string} tagName
* @param {HTMLElement} element this can be omitted.
*/
Riode.byTag = function (tagName, element) {
return element ?
element.getElementsByTagName(tagName) :
document.getElementsByTagName(tagName);
}
/**
* Get dom elements by className
* @param {string} className
* @param {HTMLElement} element this can be omitted.
*/
Riode.byClass = function (className, element) {
return element ?
element.getElementsByClassName(className) :
document.getElementsByClassName(className);
}
/**
* Set cookie
* @param {string} name Cookie name
* @param {string} value Cookie value
* @param {number} exdays Expire period
*/
Riode.setCookie = function (name, value, exdays) {
var date = new Date();
date.setTime(date.getTime() + (exdays * 24 * 60 * 60 * 1000));
document.cookie = name + "=" + value + ";expires=" + date.toUTCString() + ";path=/";
}
/**
* Get cookie
* @param {string} name Cookie name
*/
Riode.getCookie = function (name) {
var n = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; ++i) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(n) == 0) {
return c.substring(n.length, c.length);
}
}
return "";
}
/**
* Parse options string to object
* @param {string} options
*/
Riode.parseOptions = function (options) {
return 'string' == typeof options ?
JSON.parse(options.replace(/'/g, '"').replace(';', '')) :
{};
}
/**
* Parse html template with variables.
* @param {string} template
* @param {object} vars
*/
Riode.parseTemplate = function (template, vars) {
return template.replace(/\{\{(\w+)\}\}/g, function () {
return vars[arguments[1]];
});
}
/**
* @function isOnScreen
* @param {HTMLElement} el
* @param {number} dx
* @param {number} dy
*/
Riode.isOnScreen = function (el, dx, dy) {
var a = window.pageXOffset,
b = window.pageYOffset,
o = el.getBoundingClientRect(),
x = o.left + a,
y = o.top + b,
ax = typeof dx == 'undefined' ? 0 : dx,
ay = typeof dy == 'undefined' ? 0 : dy;
return y + o.height + ay >= b &&
y <= b + window.innerHeight + ay &&
x + o.width + ax >= a &&
x <= a + window.innerWidth + ax;
}
/**
* @function windowResized
* @param {number} timeStamp
* @returns
* @since 1.2.1
*/
Riode.windowResized = function (timeStamp) {
if (timeStamp == Riode.resizeTimeStamp) {
return Riode.resizeChanged;
}
if (Riode.canvasWidth != window.innerWidth) {
Riode.resizeChanged = true;
} else {
Riode.resizeChanged = false;
}
Riode.canvasWidth = window.innerWidth;
Riode.resizeTimeStamp = timeStamp;
return Riode.resizeChanged;
}
/**
* @function doLoading
* Show loading overlay
* @param {string|jQuery} selector
* @param {string} type This can be omitted.
*/
Riode.doLoading = function (selector, type) {
var $selector = Riode.$(selector);
if (typeof type == 'undefined') {
$selector.append('<div class="d-loading"><i></i></div>');
} else if (type == 'small') {
$selector.append('<div class="d-loading small"><i></i></div>');
} else if (type == 'simple') {
$selector.append('<div class="d-loading small"></div>');
}
if ('static' == $selector.css('position')) {
Riode.$(selector).css('position', 'relative');
}
}
/**
* @function endLoading
* Hide loading overlay
* @param {string|jQuery} selector
*/
Riode.endLoading = function (selector) {
Riode.$(selector).find('.d-loading').remove();
Riode.$(selector).css('position', '');
}
/**
* @function appear
*
* @param {HTMLElement} el
* @param {function} fn
* @param {object} options
*/
Riode.appear = (function () {
var checks = [],
timerId = false,
one;
var checkAll = function () {
for (var i = checks.length; i--;) {
one = checks[i];
if (Riode.isOnScreen(one.el, one.options.accX, one.options.accY)) {
typeof $(one.el).data('appear-callback') == 'function' && $(one.el).data('appear-callback').call(one.el, one.data);
one.fn && one.fn.call(one.el, one.data);
checks.splice(i, 1);
}
}
};
window.addEventListener('scroll', checkAll, { passive: true });
window.addEventListener('resize', checkAll, { passive: true });
$(window).on('appear.check', checkAll);
return function (el, fn, options) {
var settings = {
data: undefined,
accX: 0,
accY: 0
};
if (options) {
options.data && (settings.data = options.data);
options.accX && (settings.accX = options.accX);
options.accY && (settings.accY = options.accY);
}
checks.push({ el: el, fn: fn, options: settings });
if (!timerId) {
timerId = Riode.requestTimeout(checkAll, 100);
}
}
})();
Riode.zoomImageObjects = [];
/**
* @function zoomImage
*
* @requires elevateZoom
* @param {string|jQuery} selector
*/
Riode.zoomImage = function (selector) {
if ($.fn.elevateZoom && selector) {
Riode.$(selector).find('img').each(function () {
var $this = $(this);
Riode.defaults.zoomImage.zoomContainer = $this.parent();
$this.elevateZoom(Riode.defaults.zoomImage);
Riode.zoomImageObjects.push($this);
});
}
}
/**
* @function initZoom
*/
Riode.initZoom = function () {
window.addEventListener('resize', function () {
Riode.zoomImageObjects.forEach(function ($img) {
$img.each(function () {
var $this = $(this);
var elevateZoom = $this.data('elevateZoom');
if ($this.closest('.rotate-slider').length > 0 && elevateZoom) {
// Refresh elevateZoom plugin after finished resize transition.
setTimeout(function () {
elevateZoom.refresh();
}, 1200);
} else {
elevateZoom && elevateZoom.refresh();
}
});
});
}, { passive: true });
}
/**
* @function countTo
*
* @requires jQuery.countTo
* @param {string} selector
*/
Riode.countTo = function (selector) {
if ($.fn.numerator) {
Riode.$(selector).each(function () {
var $this = $(this),
options = {
fromValue: $this.data('fromvalue'),
toValue: $this.data('tovalue'),
duration: $this.data('duration'),
delimiter: $this.data('delimiter'),
rounding: $this.data('round')
};
Riode.appear(this, function () {
setTimeout(function () {
$this.numerator(options);
}, 300);
})
});
}
}
/**
* @function countdown
*
* @requires jquery-countdown
* @param {string} selector
*/
Riode.countdown = function (selector) {
if ($.fn.countdown) {
Riode.$(selector).each(function () {
var $this = $(this),
untilDate = $this.data('until'),
compact = $this.data('compact'),
dateFormat = (!$this.data('format')) ? 'DHMS' : $this.data('format'),
newLabels = (!$this.data('labels-short')) ?
['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'] :
['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Mins', 'Secs'],
newLabels1 = (!$this.data('labels-short')) ?
['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'] :
['Year', 'Month', 'Week', 'Day', 'Hour', 'Min', 'Sec'];
var newDate;
// Split and created again for ie and edge
if (!$this.data('relative')) {
var untilDateArr = untilDate.split(", "), // data-until 2019, 10, 8 - yy,mm,dd
newDate = new Date(untilDateArr[0], untilDateArr[1] - 1, untilDateArr[2]);
} else {
newDate = untilDate;
}
$this.countdown({
until: newDate,
format: dateFormat,
padZeroes: true,
compact: compact,
compactLabels: [' y', ' m', ' w', ' days, '],
timeSeparator: ' : ',
labels: newLabels,
labels1: newLabels1
});
});
// Pause
// $('.countdown').countdown('pause');
}
}
/**
* @function priceSlider
*
* @requires noUiSlider
* @param {string} selector
* @param {object} option
*/
Riode.priceSlider = function (selector, option) {
if (typeof noUiSlider === 'object') {
Riode.$(selector).each(function () {
var self = this;
noUiSlider.create(self, $.extend(true, {
start: [18, 35],
connect: true,
step: 1,
range: {
min: 18,
max: 35
}
}, option));
// Update Price Range
self.noUiSlider.on('update', function (values, handle) {
var values = values.map(function (value) {
return '$' + parseInt(value);
})
$(self).parent().find('.filter-price-range').text(values.join(' - '));
});
});
}
}
Riode.lazyload = function (selector, force) {
function load() {
this.setAttribute('src', this.getAttribute('data-src'));
this.addEventListener('load', function () {
this.style['padding-top'] = '';
this.classList.remove('lazy-img');
});
}
// Lazyload images
Riode.$(selector).find('.lazy-img').each(function () {
if ('undefined' != typeof force && force) {
load.call(this);
} else {
Riode.appear(this, load);
}
})
}
/**
* @function isotopes
*
* @requires isotope,imagesLoaded
* @param {string} selector
* @param {object} options
*/
Riode.isotopes = function (selector, options) {
if (typeof imagesLoaded === 'function' && $.fn.isotope) {
var self = this;
Riode.$(selector).each(function () {
var $this = $(this),
settings = $.extend(true, {},
Riode.defaults.isotope,
Riode.parseOptions($this.attr('data-grid-options')),
options ? options : {}
);
Riode.lazyload($this);
$this.imagesLoaded(function () {
settings.customInitHeight && $this.height($this.height());
settings.customDelay && Riode.call(function () {
$this.isotope(settings);
}, parseInt(settings.customDelay));
$this.isotope(settings);
})
});
}
}
/**
* @function initNavFilter
*
* @requires isotope
* @param {string} selector
*/
Riode.initNavFilter = function (selector) {
if ($.fn.isotope) {
Riode.$(selector).on('click', function (e) {
var $this = $(this),
filterValue = $this.attr('data-filter'),
filterTarget = $this.parent().parent().attr('data-target');
(filterTarget ? $(filterTarget) : $('.grid'))
.isotope({ filter: filterValue })
.isotope('on', 'arrangeComplete', function () {
Riode.$window.trigger('appear.check');
});
$this.parent().siblings().children().removeClass('active');
$this.addClass('active');
e.preventDefault();
});
}
}
/**
* @function initShowVendorSearch
*
* @param {string} selector
*/
Riode.initShowVendorSearch = function (selector) {
Riode.$body.on('click', selector, function (e) {
var $this = $(this),
$formWrapper = $this.closest('.toolbox').next('.form-wrapper');
if (!$formWrapper.hasClass('open')) {
$formWrapper.slideDown().addClass('open');
} else {
$formWrapper.slideUp().removeClass('open');
}
e.preventDefault();
});
}
/**
* @function parallax
* Initialize Parallax Background
* @requires themePluginParallax
* @param {string} selector
*/
Riode.parallax = function (selector, options) {
if ($.fn.themePluginParallax) {
Riode.$(selector).each(function () {
var $this = $(this);
$this.themePluginParallax(
$.extend(true, Riode.parseOptions($this.attr('data-parallax-options')), options)
);
});
}
}
/**
* Initialize floating elements
* @since 1.1
* @param {string|jQuery} selector
* @return {void}
*/
Riode.initFloatingElements = function (selector) {
if ($.fn.parallax) {
var $selectors = Riode.$(selector);
$selectors.each(function () {
var $this = $(this);
if ($this.attr('data-floating-depth'))
$this.children('.layer').attr('data-depth', $this.attr('data-floating-depth'));
else
$this.children('.layer').attr('data-depth', '.3');
$this.parallax($this.data('options'));
});
}
}
/**
* Initialize advanced motions
* @param {string} selector
* @return {void}
*/
Riode.initAdvancedMotions = function (selector) {
if (Riode.isMobile) {
return;
}
if (typeof skrollr == 'undefined') {
return;
}
var $selectors = Riode.$(selector);
$selectors.each(function () {
var $this = $(this),
options = {
'data-bottom-top': 'transform: translate(10%, 0);',
'data-center': 'transform: translate(-10%, 0);'
},
keys = [];
if ($this.data('options')) {
options = $this.data('options');
keys = Object.keys(options);
}
if ('object' == typeof options && (keys = Object.keys(options)).length) {
keys.forEach(function (key) {
$this.attr(key, options[key]);
})
}
});
if ($selectors.length) {
skrollr.init({ forceHeight: false, smoothScrolling: true });
}
}
/**
* @function degree360
* Register events for 360 degree
* @param {string} selector
*/
Riode.degree360 = function (selector) {
if (!$.fn.ThreeSixty) {
return;
}
Riode.$(selector).ThreeSixty({
imagePath: 'images/demos/demo-single-product/degree/',
filePrefix: '360-',
ext: '.png',
totalFrames: 32,
endFrame: 32,
currentFrame: 1,
imgList: Riode.$body.find('.product-degree-images'),
progress: '.d-loading',
height: 500,
width: 830,
navigation: true
});
// if ( !$.fn.ThreeSixty ) {
// return;
// }
// if ( typeof selector == 'undefined' ) {
// selector = '.product-gallery-degree';
// }
// Riode.$body.find( selector ).each( function() {
// var images = $( this ).find( '.riode-360-gallery-wrap' ).attr( 'data-srcs' ).split( ',' ),
// $degree_viewport = $( this );
// $degree_viewport.addClass( 'not_loaded' );
// $degree_viewport.ThreeSixty(
// {
// totalFrames: images.length, // Total no. of image you have for 360 slider
// endFrame: images.length, // end frame for the auto spin animation
// currentFrame: images.length - 1, // This the start frame for auto spin
// imgList: $degree_viewport.find( '.riode-360-gallery-wrap' ), // selector for image list
// progress: '.riode-degree-progress-bar', // selector to show the loading progress
// imgArray: images, // path of the image assets
// height: $degree_viewport.children( '.post-div' ).length ? '' : 500,
// width: $degree_viewport.outerWidth(),
// navigation: true
// }
// );
// $degree_viewport.find( '.riode-360-gallery-wrap' ).imagesLoaded(
// function() {
// console.log( 'image loaded' );
// setTimeout( function() {
// $degree_viewport.removeClass( 'not_loaded' ).addClass( 'loaded' );
// $degree_viewport.find( '.nav_bar' ).removeClass( 'hide' );
// }, 200 );
// }
// );
// } );
}
/**
* @function headerToggleSearch
* Init header toggle search.
* @param {string} selector
*/
Riode.headerToggleSearch = function (selector) {
var $search = Riode.$(selector);
$search.find('.form-control')
.on('focusin', function (e) {
$search.addClass('show');
})
.on('focusout', function (e) {
$search.removeClass('show');
});
// Initialize sticky footer's search toggle.
Riode.$body.on('click', '.sticky-footer .search-toggle', function (e) {
$(this).parent().toggleClass('show');
e.preventDefault();
});
}
/**
* @function closeTopNotice
* Init header toggle search.
* @param {string} selector
*/
Riode.closeTopNotice = function (selector) {
var $closeBtn = Riode.$(selector);
$closeBtn.on('click', function (e) {
e.preventDefault();
$closeBtn.closest('.top-notice').css('display', 'none');
});
}
/**
* @function stickyHeader
* Init sticky header
* @param {string} selector
*/
Riode.stickyHeader = function (selector) {
var $stickyHeader = Riode.$(selector);
if ($stickyHeader.length == 0) return;
var height, top, isWrapped = false;
// define wrap function
var stickyHeaderWrap = function () {
height = $stickyHeader[0].offsetHeight;
top = $stickyHeader.offset().top + height;
// if sticky header has category dropdown, increase top
if ($stickyHeader.hasClass('has-dropdown')) {
var $box = $stickyHeader.find('.category-dropdown .dropdown-box');
if ($box.length) {
top += $stickyHeader.find('.category-dropdown .dropdown-box')[0].offsetHeight;
}
}
// wrap sticky header
if (!isWrapped && window.innerWidth >= Riode.defaults.stickyHeader.activeScreenWidth) {
isWrapped = true;
$stickyHeader.wrap('<div class="sticky-wrapper" style="height:' + height + 'px"></div>');
}
Riode.$window.off('resize', stickyHeaderWrap);
};
// define refresh function
var stickyHeaderRefresh = function () {
var isFixed = window.innerWidth >= Riode.defaults.stickyHeader.activeScreenWidth && window.pageYOffset >= top;
// fix or unfix
if (isFixed) {
$stickyHeader[0].classList.add('fixed');
document.body.classList.add('sticky-header-active');
} else {
$stickyHeader[0].classList.remove('fixed');
document.body.classList.remove('sticky-header-active');
}
};
// register events
window.addEventListener('scroll', stickyHeaderRefresh, { passive: true });
Riode.$window.on('resize', stickyHeaderWrap);
Riode.$window.on('resize', stickyHeaderRefresh);
// init
Riode.call(stickyHeaderWrap, 500);
Riode.call(stickyHeaderRefresh, 500);
}
/**
* @function stickyContent
* Init Sticky Content
* @param {string, Object} selector
* @param {Object} settings
*/
Riode.stickyContent = function (selector, settings) {
var $stickyContents = Riode.$(selector),
options = $.extend({}, Riode.defaults.stickyContent, settings),
scrollPos = window.pageYOffset;
if (0 == $stickyContents.length) return;
var setTopOffset = function ($item) {
var offset = 0,
index = 0;
$('.sticky-content.fixed.fix-top').each(function () {
offset += $(this)[0].offsetHeight;
index++;
});
$item.data('offset-top', offset);
$item.data('z-index', options.max_index - index);
}
var setBottomOffset = function ($item) {
var offset = 0,
index = 0;
$('.sticky-content.fixed.fix-bottom').each(function () {
offset += $(this)[0].offsetHeight;
index++;
});
$item.data('offset-bottom', offset);
$item.data('z-index', options.max_index - index);
}
var wrapStickyContent = function ($item, height) {
if (window.innerWidth >= options.minWidth && window.innerWidth <= options.maxWidth) {
$item.wrap('<div class="sticky-content-wrapper"></div>');
$item.parent().css('height', height + 'px');
$item.data('is-wrap', true);
}
}
var initStickyContent = function () {
$stickyContents.each(function (index) {
var $item = $(this);
if (!$item.data('is-wrap')) {
var height = $item.removeClass('fixed').outerHeight(true), top;
top = $item.offset().top + height;
// if sticky header has category dropdown, increase top
if ($item.hasClass('has-dropdown')) {
var $box = $item.find('.category-dropdown .dropdown-box');
if ($box.length) {
top += $box[0].offsetHeight;
}
}
$item.data('top', top);
wrapStickyContent($item, height);
} else {
if (window.innerWidth < options.minWidth || window.innerWidth >= options.maxWidth) {
$item.unwrap('.sticky-content-wrapper');
$item.data('is-wrap', false);
}
}
});
}
var refreshStickyContent = function (e) {
if (e && !e.isTrusted) return;
$stickyContents.each(function (index) {
var $item = $(this),
showContent = true;
if (options.scrollMode) {
showContent = scrollPos > window.pageYOffset;
scrollPos = window.pageYOffset;
}
if (window.pageYOffset > (false == options.top ? $item.data('top') : options.top) && window.innerWidth >= options.minWidth && window.innerWidth <= options.maxWidth) {
if ($item.hasClass('fix-top')) {
if (undefined === $item.data('offset-top')) {
setTopOffset($item);
}
$item.css('margin-top', $item.data('offset-top') + 'px');
} else if ($item.hasClass('fix-bottom')) {
if (undefined === $item.data('offset-bottom')) {
setBottomOffset($item);
}
$item.css('margin-bottom', $item.data('offset-bottom') + 'px');
}
$item.css('z-index', $item.data('z-index'));
if (options.scrollMode) {
if ((showContent && $item.hasClass('fix-top')) || (!showContent && $item.hasClass('fix-bottom'))) {
$item.addClass('fixed');
if ($item.closest('.page-wrapper').find('.header').hasClass('.header-transparent')) {
if (!Riode.$body.hasClass('sidebar-active') && !Riode.$body.hasClass('top-sidebar-active')
&& !Riode.$body.hasClass('right-sidebar-active')) {
$item.closest('.main').css('z-index', '19');
} else {
$item.closest('.main').css('z-index', 'unset');
}
}
} else {
$item.removeClass('fixed');
$item.css('margin', '');
if ($item.closest('.page-wrapper').find('.header').hasClass('.header-transparent')) {
if (!Riode.$body.hasClass('sidebar-active') && !Riode.$body.hasClass('top-sidebar-active')
&& !Riode.$body.hasClass('right-sidebar-active')) {
$item.closest('.main').css('z-index', '19');
} else {
$item.closest('.main').css('z-index', 'unset');
}
}
}
} else {
$item.addClass('fixed');
}
options.hide && $item.parent('.sticky-content-wrapper').css('display', '');
} else {
$item.removeClass('fixed');
$item.css('margin-top', '');
$item.css('margin-bottom', '');
options.hide && $item.parent('.sticky-content-wrapper').css('display', 'none');
}
});
}
var resizeStickyContent = function (e) {
$stickyContents.removeData('offset-top')
.removeData('offset-bottom')
.removeClass('fixed')
.css('margin', '')
.css('z-index', '');
Riode.call(function () {
initStickyContent();
refreshStickyContent();
});
}
setTimeout(initStickyContent, 550);
setTimeout(refreshStickyContent, 600);
Riode.call(function () {
window.addEventListener('scroll', refreshStickyContent, { passive: true });
Riode.$window.on('resize', resizeStickyContent);
}, 700);
}
/**
* @function alert
* Register events for alert
* @param {string} selector
*/
Riode.initAlert = function (selector) {
Riode.$body.on('click', selector + ' .btn-close', function (e) {
$(this).closest(selector).fadeOut(function () {
$(this).remove();
});
});
}
/**
* @function accordion
* Register events for accordion
* @param {string} selector
*/
Riode.initAccordion = function (selector) {
Riode.$body.on('click', selector, function (e) {
var $this = $(this),
$header = $this,
$body = $this.closest('.card').find($this.attr('href')),
$parent = $this.closest('.accordion');
e.preventDefault();
if (0 === $parent.find(".collapsing").length &&
0 === $parent.find(".expanding").length) {
if ($body.hasClass('expanded')) {
if (!$parent.hasClass('radio-type'))
slideToggle($body);
} else if ($body.hasClass('collapsed')) {
if ($parent.find('.expanded').length > 0) {
if (Riode.isIE) {
slideToggle($parent.find('.expanded'), function () {
slideToggle($body);
});
} else {
slideToggle($parent.find('.expanded'));
slideToggle($body);
}
} else {
slideToggle($body);
}
}
}
});
// define slideToggle method
var slideToggle = function ($wrap, callback) {
var $header = $wrap.closest('.card').find(selector);
if ($wrap.hasClass("expanded")) {
$header
.removeClass("collapse")
.addClass("expand");
$wrap
.addClass("collapsing")
.slideUp(300, function () {
$wrap.removeClass("expanded collapsing").addClass("collapsed");
callback && callback();
})
} else if ($wrap.hasClass("collapsed")) {
$header
.removeClass("expand")
.addClass("collapse");
$wrap
.addClass("expanding")
.slideDown(300, function () {
$wrap.removeClass("collapsed expanding").addClass("expanded");
callback && callback();
})
}
};
}
/**
* @function tab
* Register events for tab
* @param {string} selector
*/
Riode.initTab = function (selector) {
Riode.$body
// tab nav link
.on('click', '.tab .nav-link', function (e) {
var $this = $(this);
e.preventDefault();
if (!$this.hasClass("active")) {
var $panel = $($this.attr('href'));
$panel.siblings().removeClass('in active');
$panel.addClass('active in');
// owl-carousel init
Riode.slider($panel.find('.owl-carousel'));
$this.parent().parent().find('.active').removeClass('active');
$this.addClass('active');
}
})
// link to tab
.on('click', '.single-product:not(.element-single-product) .link-to-tab', function (e) {
var selector = $(e.currentTarget).attr('href'),
$tab = $(selector),
$nav = $tab.parent().siblings('.nav');
e.preventDefault();
$tab.siblings().removeClass('active in');
$tab.addClass('active in');
$nav.find('.nav-link').removeClass('active');
$nav.find('[href="' + selector + '"]').addClass('active');
$('html').animate({
scrollTop: $tab.offset().top - 150
});
});
}
/**
* @function playableVideo
*
* @param {string} selector
*/
Riode.playableVideo = function (selector) {
$(selector + ' .video-play').on('click', function (e) {
var $video = $(this).closest(selector);
if ($video.hasClass('playing')) {
$video.removeClass('playing')
.addClass('paused')
.find('video')[0].pause();
} else {
$video.removeClass('paused')
.addClass('playing')
.find('video')[0].play();
}
e.preventDefault();
});
$(selector + ' video').on('ended', function () {
$(this).closest(selector).removeClass('playing');
});
}
/**
* @function appearAnimate
*
* @param {string} selector
*/
Riode.appearAnimate = function (selector) {
Riode.$(selector).each(function () {
var el = this;
Riode.appear(el, function () {
if (el.classList.contains('appear-animate')) {
var settings = $.extend({}, Riode.defaults.animation, Riode.parseOptions(el.getAttribute('data-animation-options')));
Riode.call(function () {
setTimeout(
function () {
el.style['animation-duration'] = settings.duration;
el.classList.add(settings.name);
el.classList.add('appear-animation-visible');
},
settings.delay ? Number(settings.delay.slice(0, -1)) * 1000 : 0
);
});
}
});
});
}
/**
* @function stickySidebar
*
* @requires themeSticky
* @param {string} selector
*/
Riode.stickySidebar = function (selector) {
if ($.fn.themeSticky) {
Riode.$(selector).each(function () {
var $this = $(this);
$this.themeSticky($.extend(Riode.defaults.stickySidebar, Riode.parseOptions($this.attr('data-sticky-options'))));
$this.trigger('recalc.pin');
});
}
}
/**
* @function refreshSidebar
*
* @param {string} selector
*/
Riode.refreshSidebar = function (selector) {
if ($.fn.themeSticky) {
Riode.$(selector).each(function () {
$(this).trigger('recalc.pin');
});
}
}
/**
* @function ratingTooltip
* Find all .ratings-full from root, and initialize tooltip.
*
* @param {HTMLElement} root
*/
Riode.ratingTooltip = function (root) {
var els = Riode.byClass('ratings-full', root ? root : document.body),
len = els.length;
var ratingHandler = function () {
var res = parseInt(this.firstElementChild.style.width.slice(0, -1)) / 20;
this.lastElementChild.innerText = res ? res.toFixed(2) : res;
}
for (var i = 0; i < len; ++i) {
els[i].addEventListener('mouseover', ratingHandler, { passive: true });
els[i].addEventListener('touchstart', ratingHandler, { passive: true });
}
}
/**
* @function popup
* @requires magnificPopup
* @params {object} options
* @params {string|undefined} preset
*/
Riode.popup = function (options, preset) {
var mpInstance = $.magnificPopup.instance,
opt = $.extend(true, {},
Riode.defaults.popup,
('undefined' != typeof preset) ? Riode.defaults.popupPresets[preset] : {},
options
);
// if something is already opened ( except login popup )
if (mpInstance.isOpen && mpInstance.content) {
mpInstance.close(); // close current
setTimeout(function () { // and open new after a moment
$.magnificPopup.open(opt);
}, 500);
} else {
$.magnificPopup.open(opt); // if nothing is opened, open new
}
}
/**
* @function initPopups
*/
Riode.initPopups = function () {
Riode.$body
// Register Login Popup
.on('click', 'a.login, .login-link', function (e) {
e.preventDefault();
Riode.popup({
items: {
src: $(e.currentTarget).attr('href')
}
}, 'login');
})
// Register "Register" Popup
.on('click', '.register-link', function (e) {
e.preventDefault();
Riode.popup({
items: {
src: $(e.currentTarget).attr('href')
},
callbacks: {
ajaxContentAdded: function () {
this.wrap.find('[href="#register"]').click();
}
}
}, 'login');
})
// Register "Image" Popup
// .on( 'click', '.btn-img', function ( e ) {
// e.preventDefault();
// Riode.popup( {
// items: {
// src: '<img src="' + $( e.currentTarget ).attr( 'href' ) + '" alt="popup"> ',
// type: "inline"
// },
// mainClass: "mfp-img-popup"
// }, "img" )
// } )
// Register "Play Video" Popup
.on('click', '.btn-iframe', function (e) {
e.preventDefault();
Riode.popup({
items: {
src: '<video src="' + $(e.currentTarget).attr('href') + '" autoplay loop controls>',
type: "inline"
},
mainClass: "mfp-video-popup"
}, "video")
});
// Open newsletter Popup after 7.5s in home pages
if ($('.home > #newsletter-popup').length > 0 && Riode.getCookie('hideNewsletterPopup') !== 'true') {
setTimeout(function () {
Riode.popup({
items: {
src: '#newsletter-popup'
},
type: 'inline',
tLoading: '',
mainClass: 'mfp-newsletter mfp-flip-popup',
callbacks: {
beforeClose: function () {
// if "do not show" is checked
$('#hide-newsletter-popup')[0].checked && Riode.setCookie('hideNewsletterPopup', true, 7);
}
},
});
}, 7500);
}
}
/**
* @function initPurchasedMinipopup
*/
Riode.initPurchasedMinipopup = function () {
setInterval(function () {
Riode.Minipopup.open({
message: 'Someone Purchased',
productClass: 'product-cart',
name: 'Daisy Shoes Sonia by Sonia-Blue',
nameLink: 'product.html',
imageSrc: 'images/cart/product-1.jpg',
isPurchased: true
}, function ($box) {
Riode.ratingTooltip($box[0]);
});
}, 60000);
}
/**
* @function initScrollTopButton
*/
Riode.initScrollTopButton = function () {
// register scroll top button
var domScrollTop = Riode.byId('scroll-top');
if (domScrollTop) {
domScrollTop.addEventListener('click', function (e) {
$('html, body').animate({ scrollTop: 0 }, 600);
e.preventDefault();
});
var refreshScrollTop = function () {
if (window.pageYOffset > 400) {
domScrollTop.classList.add('show');
} else {
domScrollTop.classList.remove('show');
}
}
Riode.call(refreshScrollTop, 500);
window.addEventListener('scroll', refreshScrollTop, { passive: true });
}
}
/**
* Scroll To
*
* @param {string} arg
* @param {number} duration
*/
Riode.scrollTo = function (arg, duration) {
var offset = 0;
var _duration = typeof duration == 'undefined' ? 600 : duration;
if (typeof arg == 'number') {
offset = arg;
} else {
offset = Riode.$(arg).offset().top;
}
$('html,body').stop().animate({ scrollTop: offset }, _duration);
}
/**
* @function scrollSet
*/
Riode.scrollSet = function (selector) {
var $selector = $(selector);
Riode.$window.on('scroll', function (e) {
var $this = $(this),
pos = $this.scrollTop(),
height = $this.outerHeight();
$('.section').each(function (index) {
var $item = $(this),
itemPos = $(this).offset().top;
if (pos <= itemPos && itemPos <= pos + height / 2) {
$selector.filter('[href="#' + $item.attr('id') + '"]').parent().addClass('active').siblings().removeClass('active');
return;
}
});
});
Riode.$body.on('click', selector, function (e) {
var $this = $(this), link = e.currentTarget, hash = link.hash ? link.hash : link.slice(link.lastIndexOf('#'));
if (hash.startsWith('#')) {
$('.mobile-menu-overlay').click();
Riode.scrollTo(hash);
e.preventDefault();
}
$this.closest('li').addClass('active').siblings().removeClass('active');
})
}
/**
* @function requestTimeout
* @param {function} fn
* @param {number} delay
*/
Riode.requestTimeout = function (fn, delay) {
var handler = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
if (!handler) {
return setTimeout(fn, delay);
}
var start, rt = new Object();
function loop(timestamp) {
if (!start) {
start = timestamp;
}
var progress = timestamp - start;
progress >= delay ? fn() : rt.val = handler(loop);
};
rt.val = handler(loop);
return rt;
}
/**
* @function requestInterval
* @param {function} fn
* @param {number} step
* @param {number} timeOut
*/
Riode.requestInterval = function (fn, step, timeOut) {
var handler = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
if (!handler) {
if (!timeOut)
return setTimeout(fn, timeOut);
else
return setInterval(fn, step);
}
var start, last, rt = new Object();
function loop(timestamp) {
if (!start) {
start = last = timestamp;
}
var progress = timestamp - start;
var delta = timestamp - last;
if (!timeOut || progress < timeOut) {
if (delta > step) {
rt.val = handler(loop);
fn();
last = timestamp;
} else {
rt.val = handler(loop);
}
} else {
fn();
}
};
rt.val = handler(loop);
return rt;
}
/**
* @function deleteTimeout
* @param {number} timerID
*/
Riode.deleteTimeout = function (timerID) {
if (!timerID) {
return;
}
var handler = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame;
if (!handler) {
return clearTimeout(timerID);
}
if (timerID.val) {
return handler(timerID.val);
}
}
/**
* @function sidebar
*/
Riode.sidebar = (function () {
var is_mobile = window.innerWidth < Riode.minDesktopWidth;
var onResizeNavigationStyle = function () {
if (window.innerWidth < Riode.minDesktopWidth && !is_mobile) {
this.$sidebar.find('.sidebar-content, .filter-clean').removeAttr('style');
this.$sidebar.find('.sidebar-content').attr('style', '');
this.$sidebar.siblings('.toolbox').children(':not(:first-child)').removeAttr('style');
} else if (window.innerWidth >= Riode.minDesktopWidth) {
if (!this.$sidebar.hasClass('closed') && is_mobile) {
this.$sidebar.addClass('closed')
this.$sidebar.find('.sidebar-content').css('display', 'none');
}
}
is_mobile = window.innerWidth < Riode.minDesktopWidth;
}
/**
* @App Sidebar
* Sidebar active App will be added to body tag : "sidebar App" + "-active"
*/
function Sidebar(name) {
return this.init(name);
}
Sidebar.prototype.init = function (name) {
var self = this;
self.name = name;
self.$sidebar = $('.' + name);
self.isNavigation = false;
// If sidebar exists
if (self.$sidebar.length) {
// check if navigation style
self.isNavigation = self.$sidebar.hasClass('sidebar-fixed') &&
self.$sidebar.parent().hasClass('toolbox-wrap');
if (self.isNavigation) {
onResizeNavigationStyle = onResizeNavigationStyle.bind(this);
Riode.$window.on('resize', onResizeNavigationStyle);
}
if (Riode.$body.find('.header').hasClass('header-transparent')) {
Riode.$body.find('.main').css('z-index', '19');
}
Riode.$window.on('resize', function () {
Riode.$body.removeClass(name + '-active');
if (Riode.$body.find('.header').hasClass('header-transparent')) {
setTimeout(function () {
Riode.$body.find('.main').css('z-index', '19');
}, 400);
}
});
// Register toggle event
self.$sidebar.find('.sidebar-toggle, .sidebar-toggle-btn')
.add(name === 'sidebar' ? '.left-sidebar-toggle' : ('.' + name + '-toggle'))
.on('click', function (e) {
self.toggle();
$(this).blur();
$('.sticky-sidebar').trigger('recalc.pin.left', [400]);
if (Riode.$body.find('.header').hasClass('header-transparent') && $(window).innerWidth() < 992) {
Riode.$body.find('.main').css('z-index', 'unset');
}
e.preventDefault();
});
// Register close event
self.$sidebar.find('.sidebar-overlay, .sidebar-close')
.on('click', function (e) {
Riode.$body.removeClass(name + '-active');
if (Riode.$body.find('.header').hasClass('header-transparent')) {
setTimeout(function () {
Riode.$body.find('.main').css('z-index', '19');
}, 400);
}
$('.sticky-sidebar').trigger('recalc.pin.left', [400]);
e.preventDefault();
});
setTimeout(function () {
$('.sticky-sidebar').trigger('recalc.pin', [400]);
})
}
return false;
}
Sidebar.prototype.toggle = function () {
var self = this;
// if fixed sidebar
if (window.innerWidth >= Riode.minDesktopWidth && self.$sidebar.hasClass('sidebar-fixed')) {
// is closed ?
var isClosed = self.$sidebar.hasClass('closed');
// if navigation style's sidebar
if (self.isNavigation) {
isClosed || self.$sidebar.find('.filter-clean').hide();
self.$sidebar.siblings('.toolbox').children(':not(:first-child)').fadeToggle('fast');
self.$sidebar
.find('.sidebar-content')
.stop()
.animate(
{
'height': 'toggle',
'margin-bottom': isClosed ? 'toggle' : -6
}, function () {
$(this).css('margin-bottom', '');
isClosed && self.$sidebar.find('.filter-clean').fadeIn('fast');
}
);
}
// if shop sidebar
if (self.$sidebar.hasClass('shop-sidebar')) {
// change columns
var $wrapper = $('.main-content .product-wrapper');
if ($wrapper.length) {
if ($wrapper.hasClass('product-lists')) {
// if list type, toggle 2 cols or 1 col
$wrapper.toggleClass('row cols-xl-2', !isClosed);
} else {
// if grid type
var colData = $wrapper.data('toggle-cols'),
colsClasses = $wrapper.attr('class').match(/cols-\w*-*\d/g),
// get max cols count
maxColsCount = colsClasses ?
Math.max.apply(null, colsClasses.map(function (cls) {
return cls.match(/\d/)[0];
})) :
0;
if (isClosed) { // when open
4 === maxColsCount &&
3 == colData &&
$wrapper.removeClass('cols-md-4');
} else { // when close
if (3 === maxColsCount) {
$wrapper.addClass('cols-md-4');
if (!colData) {
$wrapper.data('toggle-cols', 3);
}
}
}
}
}
}
// finally, toggle fixed sidebar
self.$sidebar.toggleClass('closed');
} else {
self.$sidebar.find('.sidebar-overlay .sidebar-close').css('margin-left', - (window.innerWidth - document.body.clientWidth));
// activate sidebar
Riode.$body
.toggleClass(self.name + '-active')
.removeClass('closed');
// issue
if (window.innerWidth >= 1200 && Riode.$body.hasClass('with-flex-container')) {
$('.owl-carousel').trigger('refresh.owl.carousel');
}
}
}
return function (name) {
return new Sidebar(name);
}
})();
/**
* @function initProductSingle
*
* @param {jQuery} $el
* @param {object} options
*
* @requires OwlCarousel
* @requires ImagesLoaded (only quickview needs)
* @requires elevateZoom
* @instance multiple
*/
Riode.initProductSingle = (function () {
/**
* @App ProductSingle
*/
function ProductSingle($el) {
return this.init($el);
}
var thumbsInit = function (self) {
// members for thumbnails
self.$thumbs = self.$wrapper.find('.product-thumbs');
self.$thumbsWrap = self.$thumbs.closest('.product-thumbs-wrap');
self.$thumbUp = self.$thumbsWrap.find('.thumb-up');
self.$thumbDown = self.$thumbsWrap.find('.thumb-down');
self.$thumbsDots = self.$thumbs.children();
self.thumbsCount = self.$thumbsDots.length;
self.$productThumb = self.$thumbsDots.eq(0);
self._isPgvertical = self.$thumbsWrap.parent().hasClass('pg-vertical');
self.thumbsIsVertical = self._isPgvertical && window.innerWidth >= Riode.minDesktopWidth;
// register events
self.$thumbDown.on('click', function (e) {
self.thumbsIsVertical && thumbsDown(self);
});
self.$thumbUp.on('click', function (e) {
self.thumbsIsVertical && thumbsUp(self);
});
self.$thumbsDots.on('click', function () {
var $this = $(this),
index = ($this.parent().filter(self.$thumbs).length ? $this : $this.parent()).index();
self.$wrapper.find('.product-single-carousel').trigger('to.owl.carousel', index);
});
// refresh thumbs
thumbsRefresh(self);
Riode.$window.on('resize', function () {
thumbsRefresh(self);
});
}
var thumbsDown = function (self) {
var maxBottom = self.$thumbsWrap.offset().top + self.$thumbsWrap[0].offsetHeight,
curBottom = self.$thumbs.offset().top + self.thumbsHeight;
if (curBottom >= maxBottom + self.$productThumb[0].offsetHeight) {
self.$thumbs.css('top', parseInt(self.$thumbs.css('top')) - self.$productThumb[0].offsetHeight);
self.$thumbUp.removeClass('disabled');
} else if (curBottom > maxBottom) {
self.$thumbs.css('top', parseInt(self.$thumbs.css('top')) - Math.ceil(curBottom - maxBottom));
self.$thumbUp.removeClass('disabled');
self.$thumbDown.addClass('disabled');
} else {
self.$thumbDown.addClass('disabled');
}
}
var thumbsUp = function (self) {
var maxTop = self.$thumbsWrap.offset().top,
curTop = self.$thumbs.offset().top;
if (curTop <= maxTop - self.$productThumb[0].offsetHeight) {
self.$thumbs.css('top', parseInt(self.$thumbs.css('top')) + self.$productThumb[0].offsetHeight);
self.$thumbDown.removeClass('disabled');
} else if (curTop < maxTop) {
self.$thumbs.css('top', parseInt(self.$thumbs.css('top')) - Math.ceil(curTop - maxTop));
self.$thumbDown.removeClass('disabled');
self.$thumbUp.addClass('disabled');
} else {
self.$thumbUp.addClass('disabled');
}
}
var thumbsRefresh = function (self) {
if (typeof self.$thumbs == 'undefined') {
return;
}
var oldIsVertical = 'undefined' == typeof self.thumbsIsVertical ? false : self.thumbsIsVertical; // is vertical?
self.thumbsIsVertical = self._isPgvertical && window.innerWidth >= Riode.minDesktopWidth;
if (self.thumbsIsVertical) { // enable vertical product gallery thumbs.
// disable thumbs carousel
self.$thumbs.hasClass('owl-carousel') &&
self.$thumbs
.trigger('destroy.owl.carousel')
.removeClass('owl-carousel');
// enable thumbs vertical nav
self.thumbsHeight = self.$productThumb[0].offsetHeight * self.thumbsCount + parseInt(self.$productThumb.css('margin-bottom')) * (self.thumbsCount - 1);
self.$thumbUp.addClass('disabled');
self.$thumbDown.toggleClass('disabled', self.thumbsHeight <= self.$thumbsWrap[0].offsetHeight);
self.isQuickview && recalcDetailsHeight();
} else {
// if not vertical, remove top property
oldIsVertical && self.$thumbs.css('top', '');
// enable thumbs carousel
self.$thumbs.hasClass('owl-carousel') || self.$thumbs.addClass('owl-carousel').owlCarousel(
$.extend(
true,
self.isQuickview ? {
onInitialized: recalcDetailsHeight,
onResized: recalcDetailsHeight
} : {},
Riode.defaults.sliderThumbs
));
}
}
var initVariation = function (self) {
self.$selects = self.$wrapper.find('.product-variations select');
self.$items = self.$wrapper.find('.product-variations');
self.$priceWrap = self.$wrapper.find('.product-variation-price');
self.$clean = self.$wrapper.find('.product-variation-clean'),
self.$btnCart = self.$wrapper.find('.btn-cart');
// check
self.variationCheck();
self.$selects.on('change', function (e) {
self.variationCheck();
});
self.$items.children('a').on('click', function (e) {
$(this).toggleClass('active').siblings().removeClass('active');
e.preventDefault();
self.variationCheck();
});
// clean
self.$clean.on('click', function (e) {
e.preventDefault();
self.variationClean(true);
});
}
var initCartAction = function (self) {
// Product Single's Add To Cart Button
self.$wrapper.on('click', '.btn-cart', function (e) {
e.preventDefault();
var $product = self.$wrapper,
name = $product.find('.product-name').text();
// minipopup if only quickview or home pages
if (
$product.closest('.product-popup').length ||
document.body.classList.contains('home')
) {
Riode.Minipopup.open({
message: 'Successfully Added',
productClass: 'product-cart',
name: name,
nameLink: $product.find('.product-name > a').attr('href'),
imageSrc: $product.find('.product-image img').eq(0).attr('src'),
imageLink: $product.find('.product-name > a').attr('href'),
price: $product.find('.product-variation-price').length > 0 ? $product.find('.product-variation-price').children('span').html() : $product.find('.product-price .price').html(),
count: $product.find('.quantity').val(),
actionTemplate: '<div App="action-group d-flex mt-3"><a href="cart.html" App="btn btn-sm btn-outline btn-primary btn-rounded mr-2">View Cart</a><a href="checkout.html" App="btn btn-sm btn-primary btn-rounded">Check Out</a></div>'
});
}
});
}
var initCompareAction = function (self) {
// Product Single's Add To Cart Button
self.$wrapper.on('click', '.btn-compare', function (e) {
e.preventDefault();
var $product = self.$wrapper,
name = $product.find('.product-name').text();
// minipopup if only quickview or home pages
if (
(($product.closest('.product-popup').length ||
document.body.classList.contains('home'))) & ($product.find('.btn-product.btn-cart').attr('disabled') != 'disabled')
) {
Riode.Minipopup.open({
message: 'Successfully Added',
productClass: 'product-compare',
name: name,
nameLink: $product.find('.product-name > a').attr('href'),
imageSrc: $product.find('.product-image img').eq(0).attr('src'),
imageLink: $product.find('.product-name > a').attr('href'),
price: $product.find('.product-variation-price').length > 0 ? $product.find('.product-variation-price').children('span').html() : $product.find('.product-price .price').html(),
count: $product.find('.quantity').val(),
actionTemplate: '<div App="action-group d-flex mt-3"><a href="compare.html" App="btn btn-sm btn-outline btn-primary btn-rounded mr-2">Compare</a><a href="checkout.html" App="btn btn-sm btn-primary btn-rounded">Check Out</a></div>'
});
}
});
}
// For only Quickview
var recalcDetailsHeight = function () {
var self = this;
self.$wrapper.find('.product-details').css(
'height',
window.innerWidth > 767 ? self.$wrapper.find('.product-gallery')[0].clientHeight : ''
);
}
// Public Properties
ProductSingle.prototype.init = function ($el) {
var self = this,
$slider = $el.find('.product-single-carousel');
// members
self.$wrapper = $el;
self.isQuickview = !!$el.closest('.mfp-content').length;
self._isPgvertical = false;
// bind
if (self.isQuickview) {
recalcDetailsHeight = recalcDetailsHeight.bind(this);
Riode.ratingTooltip();
}
// init thumbs
$slider.on('initialized.owl.carousel', function (e) {
//run on only single product
if (!document.body.classList.contains('home')) {
// if not quickview, make full image toggle
self.isQuickview || $slider.append('<a href="#" App="product-image-full"><i App="d-icon-zoom"></i></a>');
}
if ($slider.parent().hasClass('product-gallery-degree')) {
self.isQuickView || $slider.append('<a href="#" App="product-gallery-btn product-degree-viewer" title="Product 360 Degree Gallery"><i App="w-icon-rotate-3d"></i></a>');
}
// init thumbnails
thumbsInit(self);
}).on('translate.owl.carousel', function (e) {
var currentIndex = (e.item.index - $(e.currentTarget).find('.cloned').length / 2 + e.item.count) % e.item.count;
self.thumbsSetActive(currentIndex);
});
// if this is created after document ready, init plugins
if ('complete' === Riode.status) {
Riode.slider($slider);
Riode.quantityInput($el.find('.quantity'));
}
// if ( $slider.length == 0 ) {
// Riode.zoomImage( this.$wrapper );
// }
initVariation(this);
initCartAction(this);
initCompareAction(this);
}
ProductSingle.prototype.thumbsSetActive = function (index) {
var self = this,
$curThumb = self.$thumbsDots.eq(index);
self.$thumbsDots.filter('.active').removeClass('active');
$curThumb.addClass('active');
// show current thumb
if (self.thumbsIsVertical) { // if vertical
var offset = parseInt(self.$thumbs.css('top')) + index * self.thumbsHeight;
if (offset < 0) {
// if above
self.$thumbs.css('top', parseInt(self.$thumbs.css('top')) - offset);
} else {
offset = self.$thumbs.offset().top + self.$thumbs[0].offsetHeight - $curThumb.offset().top - $curThumb[0].offsetHeight;
if (offset < 0) {
// if below
self.$thumbs.css('top', parseInt(self.$thumbs.css('top')) + offset);
}
}
} else { // if thumb carousel
self.$thumbs.trigger('to.owl.carousel', index, 100);
}
}
ProductSingle.prototype.variationCheck = function () {
var self = this,
isAllSelected = true;
// check all select variations are selected
self.$selects.each(function () {
return this.value || (isAllSelected = false);
});
// check all item variations are selected
self.$items.each(function () {
var $this = $(this);
if ($this.children('a:not(.size-guide)').length) {
return $this.children('.active').length || (isAllSelected = false);
}
});
isAllSelected ?
self.variationMatch() :
self.variationClean();
}
ProductSingle.prototype.variationMatch = function () {
var self = this;
self.$priceWrap.find('span').text('$' + (Math.round(Math.random() * 50) + 200) + '.00');
self.$priceWrap.slideDown();
self.$clean.slideDown();
self.$btnCart.removeAttr('disabled');
}
ProductSingle.prototype.variationClean = function (reset) {
reset && this.$selects.val('');
reset && this.$items.children('.active').removeClass('active');
this.$priceWrap.slideUp();
this.$clean.css('display', 'none');
this.$btnCart.attr('disabled', 'disabled');
}
return function ($el, options) {
if ($el) {
return new ProductSingle($el.eq(0), options);
}
return null;
}
})();
/**
* @function initProductSinglePage
*
* @requires Slider
* @requires ProductSingle
* @requires PhotoSwipe
* @instance single
*/
Riode.initProductSinglePage = (function () {
function alertCartAdded(e) {
var $product = $(e.currentTarget).closest('.product-single');
$('.cart-added-alert').remove();
$(Riode.parseTemplate(Riode.defaults.templateCartAddedAlert, {
name: $product.find('h1.product-name').text()
}))
.insertBefore($product).fadeIn();
$('.sticky-sidebar').trigger('recalc.pin');
}
function compareAdded(e) {
var $product = $(e.currentTarget).closest('.product-single');
if ($product.find('.btn-product.btn-cart').attr('disabled') != 'disabled') {
Riode.Minipopup.open({
message: 'Successfully Added',
productClass: 'product-compare',
name: $product.find('h1.product-name').text(),
nameLink: $product.find('.product-name > a').attr('href'),
imageSrc: $product.find('.product-image img').eq(0).attr('src'),
imageLink: $product.find('.product-name > a').attr('href'),
price: $product.find('.product-variation-price').length > 0 ? $product.find('.product-variation-price').children('span').html() : $product.find('.product-price').html(),
count: $product.find('.quantity').val(),
actionTemplate: '<div App="action-group d-flex mt-3"><a href="compare.html" App="btn btn-sm btn-outline btn-primary btn-rounded mr-2">Compare</a><a href="checkout.html" App="btn btn-sm btn-primary btn-rounded">Check Out</a></div>'
});
}
}
function openFullImage(e) {
e.preventDefault();
var $this = $(e.currentTarget),
$product = $this.closest('.product-single'),
$images,
images;
if ($product.find('.product-single-carousel').length) {
// single carousel
$images = $product.find('.product-single-carousel .owl-item:not(.cloned) img');
} else if ($product.find('.product-gallery-carousel').length) {
// gallery carousel
$images = $product.find('.product-gallery-carousel .owl-item:not(.cloned) img');
} else {
// simple gallery
$images = $product.find('.product-gallery img');
}
// if images exist
if ($images.length) {
var images = $images.map(function () {
var $this = $(this);
return {
src: $this.attr('data-zoom-image'),
w: 800,
h: 899,
title: $this.attr('alt')
};
}).get(),
carousel = $product.find('.product-single-carousel, .product-gallery-carousel').data('owl.carousel'),
currentIndex = carousel ?
// Carousel Type
((carousel.current() - carousel.clones().length / 2 + images.length) % images.length) :
// Gallery Type
($product.find('.product-gallery > *').index());
if (typeof PhotoSwipe !== 'undefined') {
var pswpElement = $('.pswp')[0];
//if( ! pswpElement ) return;
var photoswipe = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, images, {
index: currentIndex,
closeOnScroll: false,
});
photoswipe.init();
Riode.photoswipe = photoswipe;
}
}
}
// Open 360 Degree
function open360DegreeView(e) {
e.preventDefault();
Riode.popup({
type: 'inline',
mainClass: "product-popupbox wm-fade product-360-popup",
preloader: false,
items: {
src: '<div App="product-gallery-degree">\
<div App="w-loading"><i></i></div>\
<ul App="product-degree-images"></ul>\
</div>'
},
callbacks: {
open: function () {
this.container.find('.product-gallery-degree').ThreeSixty({
imagePath: 'images/product/shoes/',
filePrefix: 'filename_',
ext: '.jpg',
totalFrames: 36,
endFrame: 36,
currentFrame: 1,
imgList: this.container.find('.product-degree-images'),
progress: '.w-loading',
height: 500,
width: 830,
navigation: true
});
},
beforeClose: function () {
this.container.empty();
}
}
});
}
function ratingForm() {
Riode.$body.on('click', '.rating-form .rating-stars > a', function (e) {
var $star = $(this);
$star.addClass('active').siblings().removeClass('active');
$star.parent().addClass('selected');
$star.closest('.rating-form').find('select').val($star.text());
e.preventDefault();
});
}
function initWishlistAction(e) {
var $this = $(e.currentTarget);
if ($this.hasClass('added')) {
return;
}
e.preventDefault();
$this.addClass('load-more-overlay loading');
setTimeout(function () {
$this
.removeClass('load-more-overlay loading')
.html('<i class="d-icon-heart-full"></i> Browse wishlist')
.addClass('added')
.attr('title', 'Browse wishlist')
.attr('href', 'wishlist.html');
}, 500);
}
function reviewOpenToggler() {
Riode.$body.on('click', '.submit-review-toggle', function (e) {
$('.review-form-section').toggleClass('opened');
e.stopPropagation();
e.preventDefault();
});
Riode.$body.on('click', '.review-overlay', function (e) {
$('.review-form-section').removeClass('opened');
e.stopPropagation();
});
Riode.$body.on('click', '.btn.like', function (e) {
var $this = $(this), val = $this.find('.count').text();
$this.toggleClass('active');
$this.find('.count').text(1 - val);
$this.closest('.feeling').find('.btn.unlike').removeClass('active');
$this.closest('.feeling').find('.btn.unlike .count').text('0');
});
Riode.$body.on('click', '.btn.unlike', function (e) {
var $this = $(this), val = $this.find('.count').text();
$this.toggleClass('active');
$this.find('.count').text(1 - val);
$this.closest('.feeling').find('.btn.like').removeClass('active');
$this.closest('.feeling').find('.btn.like .count').text('0');
});
}
function openLightBox(e) {
e.preventDefault();
var $img = $(e.currentTarget);
var images = $img.parent().children('img').map(function () {
return {
src: this.getAttribute('src'),
w: this.getAttribute('width'),
h: this.getAttribute('height'),
title: this.getAttribute('alt') || ''
};
}).get();
if (typeof PhotoSwipe !== 'undefined') {
var pswpElement = $('.pswp')[0];
var photoSwipe = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, images, {
index: $img.index(),
closeOnScroll: false
});
// show image at first.
photoSwipe.listen('afterInit', function () {
photoSwipe.shout('initialZoomInEnd');
});
photoSwipe.init();
}
}
// Public Properties
return function () {
var $product = $('.product-single');
// Wishlist button
Riode.$body.on('click', '.product-single .btn-wishlist', initWishlistAction);
if ($product.length) {
// if home page, init single products
if (document.body.classList.contains('home')) {
$product.each(function () {
Riode.initProductSingle($(this));
});
// image zoom for grid type
Riode.zoomImage('.product-gallery.row');
return null;
// else, init single product page
} else {
if (Riode.initProductSingle($product) === null) {
return null;
}
}
} else {
// if no single product exists, return
return null;
}
// image full
Riode.$body.on('click', '.product-single .product-image-full', openFullImage);
// cart added alert and compare popup
{
Riode.$body.on('click', '.single-product .btn-cart:not(.disabled)', alertCartAdded);
Riode.$body.on('click', '.single-product .btn-compare', compareAdded);
}
// image zoom for grid type
Riode.zoomImage('.product-gallery.row');
// 360 degree
Riode.$body.on('click', '.product-degree-viewer', open360DegreeView);
// image pswp
Riode.$body.on('click', '.btn-img', openLightBox);
// init rating from.(new)
ratingForm();
reviewOpenToggler();
}
})();
/**
* @App CommentWithMedia
*/
Riode.CommentWithMedia = {
/**
* Initialize
* @since 1.0
*/
init: function () {
// Register events.
Riode.$body
.on('change', '.review-medias input[type="file"]', this.uploadMedia)
.on('click', '.review-medias .btn-remove', this.removeMedia);
},
uploadMedia: function (e) {
if (!$(this)[0].files.length) {
return;
}
var $this = $(this),
file = $(this)[0].files[0],
reader = new FileReader(),
$control = $this.closest('.file-input');
var URL = window.URL || window.webkitURL;
var src = URL.createObjectURL(file);
if (src) {
if ($control.hasClass('image-input')) {
$control.find('.file-input-wrapper').css('background-image', 'url(' + src + ')');
} else if ($control.hasClass('video-input')) {
$control.find('video').attr('src', src);
}
}
},
removeMedia: function (e) {
var $this = $(this),
$fileInput = $this.closest('.file-input');
$fileInput.find('input[type="file"]').val('');
$fileInput.find('.file-input-wrapper').css('background-image', '');
$fileInput.find('video').attr('src', '');
}
}
/**
* @function slider
*
* @requires OwlCarousel
*/
Riode.slider = (function () {
/**
* @App Slider
*/
function Slider($el, options) {
return this.init($el, options);
}
var onInitialize = function (e) {
var i, j, breaks = ['', '-xs', '-sm', '-md', '-lg', '-xl', '-xxl'];
this.classList.remove('row');
for (i = 0; i < 7; ++i) {
for (j = 1; j <= 12; ++j) {
this.classList.remove('cols' + breaks[i] + '-' + j);
}
}
this.classList.remove('gutter-no');
this.classList.remove('gutter-sm');
this.classList.remove('gutter-lg');
if (this.classList.contains("animation-slider")) {
var els = this.children,
len = els.length;
for (var i = 0; i < len; ++i) {
els[i].setAttribute('data-index', i + 1);
}
}
}
var onInitialized = function (e) {
var els = this.firstElementChild.firstElementChild.children,
i,
len = els.length;
for (i = 0; i < len; ++i) {
if (!els[i].classList.contains('active')) {
var animates = Riode.byClass('appear-animate', els[i]),
j;
for (j = animates.length - 1; j >= 0; --j) {
animates[j].classList.remove('appear-animate');
}
}
}
// Video
var $el = $(e.currentTarget);
$el.find('video').on('ended', function () {
var $this = $(this);
if ($this.closest('.owl-item').hasClass('active')) {
if (true === $el.data('owl.carousel').options.autoplay) {
if (false === $el.data('owl.carousel').options.loop && ($el.data().children - 1) === $el.find('.owl-item.active').index()) {
this.loop = true;
this.play();
}
$el.trigger('next.owl.carousel');
$el.trigger('play.owl.autoplay');
} else {
this.loop = true;
this.play();
}
}
});
}
var onTranslated = function (e) {
$(window).trigger('appear.check');
// Video Play
var $el = $(e.currentTarget),
$activeVideos = $el.find('.owl-item.active video');
$el.find('.owl-item:not(.active) video').each(function () {
if (!this.paused) {
$el.trigger('play.owl.autoplay');
}
this.pause();
this.currentTime = 0;
});
if ($activeVideos.length) {
if (true === $el.data('owl.carousel').options.autoplay) {
$el.trigger('stop.owl.autoplay');
}
$activeVideos.each(function () {
this.paused && this.play();
});
}
}
var onSliderInitialized = function (e) {
var self = this,
$el = $(e.currentTarget);
// carousel content animation
$el.find('.owl-item.active .slide-animate').each(function () {
var $animation_item = $(this),
settings = $.extend(true, {},
Riode.defaults.animation,
Riode.parseOptions($animation_item.data('animation-options'))
),
duration = settings.duration,
delay = settings.delay,
aniName = settings.name;
$animation_item.css('animation-duration', duration);
var temp = Riode.requestTimeout(function () {
$animation_item.addClass(aniName);
$animation_item.addClass('show-content');
}, (delay ? Number((delay).slice(0, -1)) * 1000 : 0));
self.timers.push(temp);
});
}
var onSliderResized = function (e) {
$(e.currentTarget).find('.owl-item.active .slide-animate').each(function () {
var $animation_item = $(this);
$animation_item.addClass('show-content');
$animation_item.attr('style', '');
});
}
var onSliderTranslate = function (e) {
var self = this,
$el = $(e.currentTarget);
self.translateFlag = 1;
self.prev = self.next;
$el.find('.owl-item .slide-animate').each(function () {
var $animation_item = $(this),
settings = $.extend(true, {}, Riode.defaults.animation, Riode.parseOptions($animation_item.data('animation-options')));
$animation_item.removeClass(settings.name);
});
}
var onSliderTranslated = function (e) {
var self = this,
$el = $(e.currentTarget);
if (1 == self.translateFlag) {
self.next = $el.find('.owl-item').eq(e.item.index).children().attr('data-index');
$el.find('.show-content').removeClass('show-content');
if (self.prev != self.next) {
$el.find('.show-content').removeClass('show-content');
/* clear all animations that are running. */
if ($el.hasClass("animation-slider")) {
for (var i = 0; i < self.timers.length; i++) {
Riode.deleteTimeout(self.timers[i]);
}
self.timers = [];
}
$el.find('.owl-item.active .slide-animate').each(function () {
var $animation_item = $(this),
settings = $.extend(true, {}, Riode.defaults.animation, Riode.parseOptions($animation_item.data('animation-options'))),
duration = settings.duration,
delay = settings.delay,
aniName = settings.name;
$animation_item.css('animation-duration', duration);
$animation_item.css('animation-delay', delay);
$animation_item.css('transition-property', 'visibility, opacity');
$animation_item.css('transition-delay', delay);
$animation_item.css('transition-duration', duration);
$animation_item.addClass(aniName);
duration = duration ? duration : '0.75s';
$animation_item.addClass('show-content');
var temp = Riode.requestTimeout(function () {
$animation_item.css('transition-property', '');
$animation_item.css('transition-delay', '');
$animation_item.css('transition-duration', '');
self.timers.splice(self.timers.indexOf(temp), 1)
}, (delay ? Number((delay).slice(0, -1)) * 1000 + Number((duration).slice(0, -1)) * 500 : Number((duration).slice(0, -1)) * 500));
self.timers.push(temp);
});
} else {
$el.find('.owl-item').eq(e.item.index).find('.slide-animate').addClass('show-content');
}
self.translateFlag = 0;
}
}
// Public Properties
Slider.zoomImage = function () {
Riode.zoomImage(this.$element);
}
Slider.zoomImageRefresh = function () {
this.$element.find('img').each(function () {
var $this = $(this);
if ($.fn.elevateZoom) {
var elevateZoom = $this.data('elevateZoom');
if (typeof elevateZoom !== 'undefined') {
elevateZoom && elevateZoom.refresh();
} else {
Riode.defaults.zoomImage.zoomContainer = $this.parent();
$this.elevateZoom($this.elevateZoom);
}
}
});
}
Riode.defaults.sliderPresets['product-single-carousel'].onInitialized = Riode.defaults.sliderPresets['product-gallery-carousel'].onInitialized = Slider.zoomImage;
Riode.defaults.sliderPresets['product-single-carousel'].onRefreshed = Riode.defaults.sliderPresets['product-gallery-carousel'].onRefreshed = Slider.zoomImageRefresh;
Slider.prototype.init = function ($el, options) {
this.timers = [];
this.translateFlag = 0;
this.prev = 1;
this.next = 1;
Riode.lazyload($el, true);
var classes = $el.attr('class').split(' '),
settings = $.extend(true, {}, Riode.defaults.slider);
// extend preset options
classes.forEach(function (className) {
var preset = Riode.defaults.sliderPresets[className];
preset && $.extend(true, settings, preset);
});
var $videos = $el.find('video');
$videos.each(function () {
this.loop = false;
});
// extend user options
$.extend(true, settings, Riode.parseOptions($el.attr('data-owl-options')), options);
onSliderInitialized = onSliderInitialized.bind(this);
onSliderTranslate = onSliderTranslate.bind(this);
onSliderTranslated = onSliderTranslated.bind(this);
// init
$el.on('initialize.owl.carousel', onInitialize)
.on('initialized.owl.carousel', onInitialized)
.on('translated.owl.carousel', onTranslated);
// if animation slider
$el.hasClass('animation-slider') &&
$el.on('initialized.owl.carousel', onSliderInitialized)
.on('resized.owl.carousel', onSliderResized)
.on('translate.owl.carousel', onSliderTranslate)
.on('translated.owl.carousel', onSliderTranslated);
$el.owlCarousel(settings);
}
return function (selector, options) {
Riode.$(selector).each(function () {
var $this = $(this);
Riode.call(function () {
new Slider($this, options);
});
});
}
})();
/**
* @function quantityInput
*/
Riode.quantityInput = (function () {
/**
* @App QuantityInput
*/
function QuantityInput($el) {
return this.init($el);
}
QuantityInput.min = 1;
QuantityInput.max = 1000000;
QuantityInput.value = 1;
QuantityInput.prototype.init = function ($el) {
var self = this;
self.$minus = false;
self.$plus = false;
self.$value = false;
self.value = false;
// Bind Events
self.startIncrease = self.startIncrease.bind(self);
self.startDecrease = self.startDecrease.bind(self);
self.stop = self.stop.bind(self);
// Variables
self.min = parseInt($el.attr('min')),
self.max = parseInt($el.attr('max'));
self.min || ($el.attr('min', self.min = QuantityInput.min))
self.max || ($el.attr('max', self.max = QuantityInput.max))
// Add DOM elements and event listeners
self.$value = $el.val(self.value = QuantityInput.value);
self.$minus = $el.prev()
.on('mousedown', function (e) {
e.preventDefault();
self.startDecrease();
})
.on('touchstart', function (e) {
if (e.cancelable) {
e.preventDefault();
}
self.startDecrease();
})
.on('mouseup', self.stop);
self.$plus = $el.next()
.on('mousedown', function (e) {
e.preventDefault();
self.startIncrease();
})
.on('touchstart', function (e) {
if (e.cancelable) {
e.preventDefault();
}
self.startIncrease();
})
.on('mouseup', self.stop);
Riode.$body.on('mouseup', self.stop)
.on('touchend', self.stop)
.on('touchcancel', self.stop);
}
QuantityInput.prototype.startIncrease = function (e) {
e && e.preventDefault();
var self = this;
self.value = self.$value.val();
self.value < self.max && self.$value.val(++self.value);
self.increaseTimer = Riode.requestTimeout(function () {
self.speed = 1;
self.increaseTimer = Riode.requestInterval(function () {
self.$value.val(self.value = Math.min(self.value + Math.floor(self.speed *= 1.05), self.max));
}, 50);
}, 400);
}
QuantityInput.prototype.stop = function (e) {
Riode.deleteTimeout(this.increaseTimer);
Riode.deleteTimeout(this.decreaseTimer);
}
QuantityInput.prototype.startDecrease = function () {
var self = this;
self.value = self.$value.val();
self.value > self.min && self.$value.val(--self.value);
self.decreaseTimer = Riode.requestTimeout(function () {
self.speed = 1;
self.decreaseTimer = Riode.requestInterval(function () {
self.$value.val(self.value = Math.max(self.value - Math.floor(self.speed *= 1.05), self.min));
}, 50);
}, 400);
}
return function (selector) {
Riode.$(selector).each(function () {
var $this = $(this);
// if not initialized
$this.data('quantityInput') ||
$this.data('quantityInput', new QuantityInput($this));
});
}
})();
/**
* @App Menu
*/
Riode.Menu = {
init: function () {
this.initMenu();
this.initMobileMenu();
this.initFilterMenu();
this.initCategoryMenu();
this.initCollapsibleWidget();
},
initMenu: function () {
// setup menu
$('.menu li').each(function () {
if (this.lastElementChild && (
this.lastElementChild.tagName === 'UL' ||
this.lastElementChild.classList.contains('megamenu'))
) {
this.classList.add('submenu');
}
});
$('.menu > li > a').each(function () {
var $this = $(this);
if ($this.text() == "Elements") {
var $parent = $this.closest('li');
$parent.addClass('submenu-container');
}
});
$('.main-nav .megamenu, .main-nav .submenu > ul').each(function () {
var $this = $(this),
left = $this.offset().left,
outerWidth = $this.outerWidth(),
offset = (left + outerWidth) - (window.innerWidth - 20);
if ($this.closest('li').hasClass('submenu-container')) {
var winWidth = $(window).innerWidth();
if (winWidth <= 1200) {
$this.css('width', winWidth - 40);
}
$this.css('margin-left', ((winWidth - outerWidth) / 2 - left));
}
else {
if (offset >= 0 && left > 20) {
$this.css('margin-left', '-=' + offset);
}
}
});
// calc megamenu position
Riode.$window.on('resize', function () {
$('.main-nav .megamenu, .main-nav .submenu > ul').each(function () {
var $this = $(this),
left = $this.offset().left,
outerWidth = $this.outerWidth(),
offset = (left + outerWidth) - (window.innerWidth - 20);
if ($this.closest('li').hasClass('submenu-container')) {
var winWidth = $(window).innerWidth();
if (winWidth <= 1200) {
$this.css('width', winWidth - 40);
outerWidth = $this.innerWidth();
}
$this.css('margin-left', 0);
left = $this.offset().left;
$this.css('margin-left', ((winWidth - outerWidth) / 2 - left));
} else {
if (offset >= 0 && left > 20) {
$this.css('margin-left', '-=' + offset);
}
}
});
});
},
initMobileMenu: function () {
function showMobileMenu() {
Riode.$body.addClass('mmenu-active');
};
function hideMobileMenu(e) {
if (e && e.type && 'resize' == e.type && !Riode.windowResized(e.timeStamp)) {
return;
}
e.preventDefault();
Riode.$body.removeClass('mmenu-active');
};
$('.mobile-menu li, .toggle-menu li').each(function () {
if (this.lastElementChild && (
this.lastElementChild.tagName === 'UL' ||
this.lastElementChild.classList.contains('megamenu'))
) {
var span = document.createElement('span');
span.className = "toggle-btn";
this.firstElementChild.appendChild(span);
}
});
$('.mobile-menu-toggle').on('click', showMobileMenu);
$('.mobile-menu-overlay').on('click', hideMobileMenu);
$('.mobile-menu-close').on('click', hideMobileMenu);
Riode.$window.on('resize', hideMobileMenu);
},
initFilterMenu: function () {
$('.search-ul li').each(function () {
if (this.lastElementChild && this.lastElementChild.tagName === 'UL') {
var i = document.createElement('i');
i.className = "fas fa-chevron-down";
this.classList.add('with-ul');
this.firstElementChild.appendChild(i);
}
});
$('.with-ul > a i, .toggle-btn').on('click', function (e) {
$(this).parent().next().slideToggle(300).parent().toggleClass("show");
setTimeout(function () {
$('.sticky-sidebar').trigger('recalc.pin');
}, 320);
e.preventDefault();
});
},
initCategoryMenu: function () {
// cat dropdown
var $menu = $('.category-dropdown');
if ($menu.length) {
var $box = $menu.find('.dropdown-box');
if ($box.length) {
var top = $('.main').offset().top + $box[0].offsetHeight;
if (window.pageYOffset > top || window.innerWidth < Riode.minDesktopWidth) {
$menu.removeClass('show');
}
window.addEventListener('scroll', function () {
if (window.pageYOffset <= top && window.innerWidth >= Riode.minDesktopWidth) {
$menu.removeClass('show');
}
}, { passive: true });
$('.category-toggle').on("click", function (e) {
e.preventDefault();
})
$menu.on("mouseover", function (e) {
if (window.pageYOffset > top && window.innerWidth >= Riode.minDesktopWidth) {
$menu.addClass('show');
}
})
$menu.on("mouseleave", function (e) {
if (window.pageYOffset > top && window.innerWidth >= Riode.minDesktopWidth) {
$menu.removeClass('show');
}
})
}
if ($menu.hasClass('with-sidebar')) {
var sidebar = Riode.byClass('sidebar');
if (sidebar.length) {
$menu.find('.dropdown-box').css('width', sidebar[0].offsetWidth - 20);
// set category menu's width same as sidebar.
Riode.$window.on('resize', function () {
$menu.find('.dropdown-box').css('width', (sidebar[0].offsetWidth - 20));
});
}
}
}
},
initCollapsibleWidget: function () {
// generate toggle icon
$('.widget-collapsible .widget-title').each(function () {
var span = document.createElement('span');
span.className = 'toggle-btn';
this.appendChild(span);
});
// slideToggle
$('.widget-collapsible .widget-title').on('click', function (e) {
var $this = $(this);
if (!$this.hasClass('sliding')) {
var $body = $this.siblings('.widget-body');
$this.hasClass("collapsed") || $body.css('display', 'block');
$this.addClass("sliding");
$body.slideToggle(300, function () {
$this.removeClass("sliding");
});
$this.toggleClass("collapsed");
setTimeout(function () {
$('.sticky-sidebar').trigger('recalc.pin');
}, 320);
}
});
}
};
/**
* @App StickyLink
*/
Riode.StickyLink = {
init: function () {
this.initShowDemos();
},
initShowDemos: function () {
function showStickyLinks() {
$('.demos-list').addClass('show');
var $demos = $('.demos-list .demos'),
$content = $('.demos-list .demos-content');
//call demos list
if (0 == $demos.children().length) {
Riode.doLoading($content);
$.ajax({
url: "ajax/demos-list.html",
method: 'post',
data: {
action: "riode_demos_list",
},
success: function (data) {
if (data) {
Riode.endLoading($content);
$demos.html(data);
}
}
})
}
};
function hideStickyLinks() {
$('.demos-list').removeClass('show');
};
$('.demo-toggle').on('click', function (e) {
e.preventDefault();
showStickyLinks();
});
$('.demos-overlay').on('click', function (e) {
e.preventDefault();
hideStickyLinks();
});
$('.demos-close').on('click', function (e) {
e.preventDefault();
hideStickyLinks();
});
},
};
/**
* @App MiniPopup
*/
Riode.Minipopup = (function () {
var $area,
offset = 0,
boxes = [],
isPaused = false,
timers = [],
timerId = false,
timerInterval = 200,
timerClock = function () {
if (isPaused) {
return;
}
for (var i = 0; i < timers.length; ++i) {
(timers[i] -= timerInterval) <= 0 && this.close(i--);
}
}
return {
init: function () {
// init area
var area = document.createElement('div');
area.className = "minipopup-area";
Riode.byClass('page-wrapper')[0].appendChild(area);
$area = $(area);
$area.on('click', '.btn-close', function (e) {
self.close($(this).closest('.minipopup-box').index());
});
// bind methods
this.close = this.close.bind(this);
timerClock = timerClock.bind(this);
},
open: function (options, callback) {
var self = this,
settings = $.extend(true, {}, Riode.defaults.minipopup, options),
$box;
if (!settings.isPurchased) {
settings.detailTemplate = Riode.parseTemplate(
(null != settings.count ? settings.priceQuantityTemplate : settings.priceTemplate),
settings
)
} else {
settings.detailTemplate = Riode.parseTemplate(
settings.purchasedTemplate,
settings
)
}
if (null != settings.rating) {
settings.detailTemplate += Riode.parseTemplate(settings.ratingTemplate, settings);
}
$box = $(Riode.parseTemplate(settings.template, settings));
self.space = settings.space;
// open
$box
.appendTo($area)
.css('top', - offset)
.find("img")[0]
.onload = function () {
offset += $box[0].offsetHeight + self.space;
$box.addClass('show');
if ($box.offset().top - window.pageYOffset < 0) {
self.close();
$box.css('top', - offset + $box[0].offsetHeight + self.space);
}
$box.on('mouseenter', function () { self.pause() })
.on('mouseleave', function () { self.resume() })
.on('touchstart', function (e) { self.pause(); e.stopPropagation(); })
.on('mousedown', function () {
$(this).addClass('focus');
})
.on('mouseup', function () {
self.close($(this).index());
});
Riode.$body.on('touchstart', function () {
self.resume();
});
boxes.push($box);
timers.push(settings.delay);
(timers.length > 1) || (
timerId = setInterval(timerClock, timerInterval)
)
callback && callback($box);
};
},
close: function (indexToClose) {
var self = this,
index = ('undefined' === typeof indexToClose) ? 0 : indexToClose,
$box = boxes.splice(index, 1)[0];
// remove timer
timers.splice(index, 1)[0];
// remove box
offset -= $box[0].offsetHeight + self.space;
$box.removeClass('show');
setTimeout(function () {
$box.remove();
}, 300);
// slide down other boxes
boxes.forEach(function ($box, i) {
if (i >= index && $box.hasClass('show')) {
$box.stop(true, true).animate({
top: parseInt($box.css('top')) + $box[0].offsetHeight + 20
}, 600, 'easeOutQuint');
}
});
// clear timer
boxes.length || clearTimeout(timerId);
},
pause: function () {
isPaused = true;
},
resume: function () {
isPaused = false;
}
}
})();
/**
* @function floatSVG
* @param {string|jQuery} selector
* @param {object} options
*/
Riode.floatSVG = (function () {
function FloatSVG(svg, options) {
this.$el = $(svg);
this.set(options);
this.start();
}
FloatSVG.prototype.set = function (options) {
this.options = $.extend({
delta: 15,
speed: 10,
size: 1,
}, typeof options == 'string' ? Riode.parseOptions(options) : options);
}
FloatSVG.prototype.getDeltaY = function (dx) {
return Math.sin(2 * Math.PI * dx / this.width * this.options.size) * this.options.delta;
}
FloatSVG.prototype.start = function () {
this.update = this.update.bind(this);
this.timeStart = Date.now() - parseInt(Math.random() * 100);
this.$el.find('path').each(function () {
$(this).data('original', this.getAttribute('d').replace(/([\d])\s*\-/g, '$1,-'));
});
window.addEventListener('resize', this.update, { passive: true });
window.addEventListener('scroll', this.update, { passive: true });
Riode.$window.on('check_float_svg', this.update);
this.update();
}
FloatSVG.prototype.update = function () {
var self = this;
if (this.$el.length && Riode.isOnScreen(this.$el[0])) { // && $.contains(this.$el, document.body)) {
Riode.requestTimeout(function () {
self.draw();
}, 16);
}
}
FloatSVG.prototype.draw = function () {
var self = this,
_dx = (Date.now() - this.timeStart) * this.options.speed / 200;
this.width = this.$el.width();
if (!this.width) {
return;
}
this.$el.find('path').each(function () {
var dx = _dx, dy = 0;
this.setAttribute('d', $(this).data('original')
.replace(/M([\d|\.]*),([\d|\.]*)/, function (match, p1, p2) {
if (p1 && p2) {
return 'M' + p1 + ',' + (parseFloat(p2) + (dy = self.getDeltaY(dx += parseFloat(p1)))).toFixed(3);
}
return match;
})
.replace(/([c|C])[^A-Za-z]*/g, function (match, p1) {
if (p1) {
var v = match.slice(1).split(',').map(parseFloat);
if (v.length == 6) {
if ('C' == p1) {
v[1] += self.getDeltaY(_dx + v[0]);
v[3] += self.getDeltaY(_dx + v[2]);
v[5] += self.getDeltaY(dx = _dx + v[4]);
} else {
v[1] += self.getDeltaY(dx + v[0]) - dy;
v[3] += self.getDeltaY(dx + v[2]) - dy;
v[5] += self.getDeltaY(dx += v[4]) - dy;
}
dy = self.getDeltaY(dx);
return p1 + v.map(function (v) {
return v.toFixed(3);
}).join(',');
}
}
return match;
})
);
});
this.update();
}
return function (selector) {
Riode.$(selector).each(function () {
var $this = $(this), float;
if (this.tagName == 'svg') {
float = $this.data('float-svg');
if (float) {
float.set($this.attr('data-float-options'));
} else {
$this.data('float-svg', new FloatSVG(this, $this.attr('data-float-options')));
}
}
})
};
})();
/**
* @App Shop
*
* @requires Minipopup
* @requires noUiSlider
* @instance single
*/
Riode.Shop = {
init: function () {
// Functions for products
this.initProductsQuickview();
this.initProductsCartAction();
this.initProductsCompareAction();
this.initProductsWishlistAction();
this.initProductsLoginAction();
this.initProductsLoad();
this.initProductsScrollLoad('.scroll-load');
this.initProductType('slideup');
this.initVariation();
this.initWishlistButton('.product:not(.product-single) .btn-wishlist');
Riode.call(Riode.ratingTooltip, 500);
// Functions for shop page
this.initSelectMenu('.select-menu');
Riode.priceSlider('.filter-price-slider');
this.topCategoryOpener();
},
topCategoryOpener: function () {
Riode.$body.find('.toolbox-horizontal .widget-title').on('click', function (e) {
$(this).parent().siblings().removeClass('opened');
$(this).parent().toggleClass('opened');
e.stopPropagation();
});
},
initVariation: function (type) {
$('.product:not(.product-single) .product-variations > a').on('click', function (e) {
var $this = $(this),
$image = $this.closest('.product').find('.product-media img');
if (!$image.data('image-src'))
$image.data('image-src', $image.attr('src'));
$this.toggleClass('active').siblings().removeClass('active');
if ($this.hasClass('active')) {
$image.attr('src', $this.data('src'))
} else {
$image.attr('src', $image.data('image-src'));
$this.blur();
}
e.preventDefault();
})
},
initProductType: function (type) {
// "slideup" type
if (type === 'slideup') {
$('.product-slideup-content .product-details').each(function (e) {
var $this = $(this),
hidden_height = $this.find('.product-hide-details').outerHeight(true);
$this.height($this.height() - hidden_height);
});
$(Riode.byClass('product-slideup-content'))
.on('mouseenter touchstart', function (e) {
var $this = $(this),
hidden_height = $this.find('.product-hide-details').outerHeight(true);
$this.find('.product-details').css('transform', 'translateY(' + (-hidden_height) + 'px)');
$this.find('.product-hide-details').css('transform', 'translateY(' + (-hidden_height) + 'px)');
})
.on('mouseleave touchleave', function (e) {
var $this = $(this),
hidden_height = $this.find('.product-hide-details').outerHeight(true);
$this.find('.product-details').css('transform', 'translateY(0)');
$this.find('.product-hide-details').css('transform', 'translateY(0)');
});
}
},
initSelectMenu: function () {
Riode.$body
// open select menu
.on('click', '.select-menu', function (e) {
var $this = $(this);
if (!$this.hasClass('toolbox-sort')) {
var $selectMenu = $(e.currentTarget),
$target = $(e.target),
isOpened = $selectMenu.hasClass('opened');
if ($selectMenu.hasClass('fixed')) {
e.stopPropagation()
} else {
// close all select menu
if ($this.closest('.sidebar-content').length != 0) {
$('.select-menu').removeClass('opened');
}
}
if ($selectMenu.is($target.parent())) {
// if toggle is clicked
isOpened || $selectMenu.addClass('opened');
e.stopPropagation();
} else {
// if item is clicked
$target.parent().toggleClass('active');
if ($target.parent().hasClass('active')) { // add select-item, and show
$('.select-items').show();
$('<a href="#" class="select-item">' + $target.text() + '<i class="d-icon-times"></i></a>')
.insertBefore('.select-items .filter-clean')
.hide().fadeIn()
.data('link', $target.parent()); // link to anchor's parent - li tag
} else { // remove select-item
$('.select-items > .select-item').filter(function (i, el) {
return el.innerText == $target.text();
}).fadeOut(function () {
$(this).remove();
// if only clean all button remains, // then hide select-items
if ($('.select-items').children().length < 2) {
$('.select-items').hide();
}
});
}
}
}
e.preventDefault();
})
// Close select menu
.on('click', function (e) {
if ($(e.target).closest('.filter-items').length == 0 || $(e.target).hasClass('select-menu')) {
$('.select-menu').removeClass('opened');
}
})
// Remove all filters in navigation
.on('click', '.select-items .filter-clean', function (e) {
var $clean = $(this);
$clean.siblings().each(function () {
var $link = $(this).data('link');
$link && $link.removeClass('active');
});
$clean.parent().fadeOut(function () {
$clean.siblings().remove();
});
e.preventDefault();
})
// Remove one filter in navigation
.on('click', '.select-item i', function (e) {
$(e.currentTarget).parent().fadeOut(function () {
var $this = $(this),
$link = $this.data('link');
$link && $link.toggleClass('active');
$this.remove();
// if only clean all button remains, then hide select-items
if ($('.select-items').children().length < 2) {
$('.select-items').hide();
}
});
e.preventDefault();
})
// Remove all filters
.on('click', '.filter-clean', function (e) {
$('.shop-sidebar .filter-items .active').removeClass('active');
e.preventDefault();
})
// Toggle filter
.on('click', '.filter-items a', function (e) {
var $ul = $(this).closest('.filter-items');
if (!$ul.hasClass('search-ul') && !$ul.parent().hasClass('select-menu')) {
if ($ul.hasClass('filter-price')) {
$(this).parent().siblings().removeClass('active');
$(this).parent().toggleClass('active');
e.preventDefault();
} else {
$(this).parent().toggleClass('active');
e.preventDefault();
}
}
})
},
initProductsQuickview: function () {
Riode.$body.on('click', '.btn-quickview', function (e) {
e.preventDefault();
if ($(this).closest('.dark-theme').length > 0) {
//dark theme
Riode.popup({
items: {
src: "ajax/quickview-dark.html"
},
callbacks: {
ajaxContentAdded: function () {
this.wrap.imagesLoaded(function () {
Riode.initProductSingle($('.mfp-product .product-single'));
});
}
}
}, 'quickview');
} else {
//light theme
Riode.popup({
items: {
src: "ajax/quickview.html"
},
callbacks: {
ajaxContentAdded: function () {
this.wrap.imagesLoaded(function () {
Riode.initProductSingle($('.mfp-product .product-single'));
});
}
}
}, 'quickview');
}
});
},
initProductsCartAction: function () {
Riode.$body
// Cart dropdown is offcanvas type
.on('click', '.off-canvas .cart-toggle', function (e) {
e.preventDefault();
$('.cart-dropdown').addClass('opened');
})
.on('click', '.off-canvas .canvas-header .btn-close', function (e) {
$('.cart-dropdown').removeClass('opened');
e.preventDefault();
})
.on('click', '.off-canvas .canvas-overlay', function (e) {
$('.cart-dropdown').removeClass('opened');
e.preventDefault();
})
// Add to cart in products
.on('click', '.product:not(.product-variable) .btn-product-icon.btn-cart, .product:not(.product-variable) .btn-product.btn-cart', function (e) {
e.preventDefault();
var $product = $(this).closest('.product'),
$compareCol = $(this).closest('.compare-col'),
$compareRow = $(this).closest('.compare-row'),
productPrice,
$productName;
if ($compareCol.length > 0) {
productPrice = $('.riode-compare-table > .compare-row').eq(2).children().eq($compareCol.index()).find('.product-price .new-price, .product-price .price').html();
$productName = $('.riode-compare-table > .compare-row').eq(1).children().eq($compareCol.index());
// if not product single, then open minipopup
$product.hasClass('product-single') ||
Riode.Minipopup.open({
message: 'Successfully Added',
productClass: 'product-cart',
name: $productName.find('a').text(),
nameLink: $productName.find(' a ').attr('href'),
imageSrc: $product.find('.product-media img').attr('src'),
imageLink: $productName.find(' a ').attr('href'),
price: productPrice,
count: $product.find('.quantity').length > 0 ? $product.find('.quantity').val() : 1,
actionTemplate: '<div App="action-group d-flex"><a href="cart.html" App="btn btn-sm btn-outline btn-primary btn-rounded">View Cart</a><a href="checkout.html" App="btn btn-sm btn-primary btn-rounded">Check Out</a></div>'
});
} else {
// if not product single, then open minipopup
$product.hasClass('product-single') ||
Riode.Minipopup.open({
message: 'Successfully Added',
productClass: 'product-cart',
name: $product.find('.product-name').text(),
nameLink: $product.find('.product-name > a').attr('href'),
imageSrc: $product.find('.product-media img').attr('src'),
imageLink: $product.find('.product-name > a').attr('href'),
price: $product.find('.product-price .new-price, .product-price .price').html(),
count: $product.find('.quantity').length > 0 ? $product.find('.quantity').val() : 1,
actionTemplate: '<div App="action-group d-flex"><a href="cart.html" App="btn btn-sm btn-outline btn-primary btn-rounded">View Cart</a><a href="checkout.html" App="btn btn-sm btn-primary btn-rounded">Check Out</a></div>'
});
}
})
// Add to cart in hotspot
.on('click', '.hotspot .btn-cart', function (e) {
e.preventDefault();
var $tooltip = $(this).closest('.tooltip');
Riode.Minipopup.open({
message: 'Successfully Added To Cart',
productClass: 'product-cart',
name: $tooltip.find('.tooltip-name').text(),
nameLink: $tooltip.find('.tooltip-name > a').attr('href'),
imageSrc: $tooltip.find('.tooltip-media img').attr('src'),
imageLink: $tooltip.find('.tooltip-name > a').attr('href'),
price: $tooltip.find('.tooltip-price .new-price, .tooltip-price .price').html(),
count: $tooltip.find('.quantity').length > 0 ? $tooltip.find('.quantity').val() : 1,
actionTemplate: '<div App="action-group d-flex"><a href="cart.html" App="btn btn-sm btn-outline btn-primary btn-rounded">View Cart</a><a href="checkout.html" App="btn btn-sm btn-primary btn-rounded">Check Out</a></div>'
});
});
},
initProductsCompareAction: function () {
Riode.$body
// Compare dropdown is offcanvas type
.on('click', '.off-canvas .compare-toggle', function (e) {
e.preventDefault();
$('.compare-dropdown').addClass('opened');
})
.on('click', '.off-canvas .canvas-header .btn-close', function (e) {
$('.compare-dropdown').removeClass('opened');
e.preventDefault();
})
.on('click', '.off-canvas .canvas-overlay', function (e) {
$('.compare-dropdown').removeClass('opened');
e.preventDefault();
})
// Add to compare in products
.on('click', '.product .btn-product-icon.btn-compare', function (e) {
e.preventDefault();
var $product = $(this).closest('.product');
// if not product single, then open minipopup
$product.hasClass('product-single') ||
Riode.Minipopup.open({
message: 'Added To Compare List',
productClass: ' product-compare',
name: $product.find('.product-name').text(),
nameLink: $product.find('.product-name > a').attr('href'),
imageSrc: $product.find('.product-media img').attr('src'),
imageLink: $product.find('.product-name > a').attr('href'),
price: $product.find('.product-price .new-price, .product-price .price').html(),
count: $product.find('.quantity').length > 0 ? $product.find('.quantity').val() : 1,
actionTemplate: '<div App="action-group d-flex"><a href="compare.html" App="btn btn-sm btn-outline btn-primary btn-rounded">Compare</a><a href="checkout.html" App="btn btn-sm btn-primary btn-rounded">Check Out</a></div>'
});
});
},
initProductsWishlistAction: function () {
Riode.$body
// Compare dropdown is offcanvas type
.on('click', '.off-canvas .wishlist-toggle', function (e) {
e.preventDefault();
$('.wishlist-dropdown').addClass('opened');
})
.on('click', '.off-canvas .canvas-header .btn-close', function (e) {
$('.wishlist-dropdown').removeClass('opened');
e.preventDefault();
})
.on('click', '.off-canvas .canvas-overlay', function (e) {
$('.wishlist-dropdown').removeClass('opened');
e.preventDefault();
})
},
initProductsLoginAction: function () {
Riode.$body
// Compare dropdown is offcanvas type
.on('click', '.login-toggle, .register-toggle', function (e) {
e.preventDefault();
$('.login-dropdown').addClass('opened');
})
.on('click', '.off-canvas .canvas-header .btn-close', function (e) {
$('.login-dropdown').removeClass('opened');
e.preventDefault();
})
.on('click', '.off-canvas .canvas-overlay', function (e) {
$('.login-dropdown').removeClass('opened');
e.preventDefault();
})
},
initProductsLoad: function () {
$('.btn-load').on('click', function (e) {
var $this = $(this),
$wrapper = $($this.data('load-to')),
loadText = $this.html();
$this.text('Loading ...');
$this.addClass('btn-loading');
$('.d-loading').css('display', 'block');
e.preventDefault();
$.ajax({
url: $this.attr('href'),
success: function (result) {
var $newItems = $(result);
setTimeout(function () {
if ($.fn.isotope) {
$wrapper.isotope('insert', $newItems);
} else {
$wrapper.append($newItems);
}
$this.html(loadText);
var loadCount = parseInt($this.data('load-count') ? $this.data('load-count') : 0);
$this.data('load-count', ++loadCount);
//remove loading App
$this.removeClass('btn-loading');
$('.d-loading').css('display', 'none');
// do not load more than 2 times
loadCount >= 2 && $this.hide();
}, 350);
},
failure: function () {
$this.text("Sorry something went wrong.");
}
});
});
},
initProductsScrollLoad: function ($obj) {
var $wrapper = Riode.$($obj)
, top;
var url = $($obj).data('url');
if (!url) {
url = 'ajax/ajax-products.html';
}
var loadProducts = function (e) {
if (window.pageYOffset > top + $wrapper.outerHeight() - window.innerHeight - 150 && 'loading' != $wrapper.data('load-state')) {
$.ajax({
url: url,
success: function (result) {
var $newItems = $(result);
$wrapper.data('load-state', 'loading');
if (!$wrapper.next().hasClass('load-more-overlay')) {
$('<div class="mt-4 mb-4 load-more-overlay loading"></div>').insertAfter($wrapper);
} else {
$wrapper.next().addClass('loading');
}
setTimeout(function () {
$wrapper.next().removeClass('loading');
$wrapper.append($newItems);
setTimeout(function () {
$wrapper.find('.product-wrap.fade:not(.in)').addClass('in');
}, 200);
$wrapper.data('load-state', 'loaded');
}, 500);
var loadCount = parseInt($wrapper.data('load-count') ? $wrapper.data('load-count') : 0);
$wrapper.data('load-count', ++loadCount);
loadCount > 2 && window.removeEventListener('scroll', loadProducts, { passive: true });
},
failure: function () {
$this.text("Sorry something went wrong.");
}
});
}
}
if ($wrapper.length > 0) {
top = $wrapper.offset().top;
window.addEventListener('scroll', loadProducts, { passive: true });
}
},
initWishlistButton: function (selector) {
Riode.$body.on('click', selector, function (e) {
var $this = $(this);
$this.toggleClass('added').addClass('load-more-overlay loading');
setTimeout(function () {
$this.removeClass('load-more-overlay loading').find('i').toggleClass('d-icon-heart')
.toggleClass('d-icon-heart-full');
if ($this.hasClass('added')) {
$this.attr('title', 'Remove from wishlist');
} else {
$this.attr('title', 'Add to wishlist');
}
}, 500);
e.preventDefault();
})
}
}
/**
* Riode Initializer
*/
// Initialize Method while document is being loaded.
Riode.prepare = function () {
if (Riode.$body.hasClass('with-flex-container') && window.innerWidth >= 1200) {
Riode.$body.addClass('sidebar-active');
}
};
// Initialize Method while document is interactive
Riode.initLayout = function () {
Riode.isotopes('.grid:not(.grid-float)');
Riode.stickySidebar('.sticky-sidebar');
}
// Initialize Method after document has been loaded
Riode.init = function () {
Riode.appearAnimate('.appear-animate'); // Runs appear animations
Riode.Minipopup.init(); // Initialize minipopup
Riode.Shop.init(); // Initialize shop
Riode.initProductSinglePage(); // Initialize single product page
Riode.slider('.owl-carousel'); // Initialize slider
Riode.headerToggleSearch('.hs-toggle'); // Initialize header toggle search
Riode.closeTopNotice('.btn-notice-close'); // Initialize header toggle search
Riode.stickyContent('.product-sticky-content, .sticky-header', { top: false }); // Initialize sticky content
Riode.stickyContent('.sticky-footer', Riode.defaults.stickyFooter); // Initialize sticky footer
Riode.stickyContent('.sticky-toolbox', Riode.defaults.stickyToolbox); // Initialize sticky toolbox
Riode.sidebar('sidebar'); // Initialize left sidebar
Riode.sidebar('right-sidebar'); // Initialize right sidebar
Riode.sidebar('top-sidebar'); // Initialize top sidebar
Riode.quantityInput('.quantity'); // Initialize quantity input
Riode.playableVideo('.inner-video'); // Initialize playable video
Riode.initAccordion('.card-header > a'); // Initialize accordion
Riode.initTab('.nav-tabs'); // Initialize tab
Riode.initAlert('.alert'); // Initialize alert
Riode.parallax('.parallax'); // Initialize parallax
Riode.countTo('.count-to'); // Initialize countTo
Riode.countdown('.product-countdown, .countdown'); // Initialize countdown
Riode.Menu.init(); // Initialize menus
Riode.StickyLink.init(); // Initialize StickyLink
Riode.initZoom(); // Initialize zoom
Riode.initNavFilter('.nav-filters .nav-filter'); // Initialize navigation filters for blog, products
Riode.initPopups(); // Initialize popups: login, register, play video, newsletter popup
Riode.initPurchasedMinipopup(); // Initialize minipopup for purchased event
Riode.initScrollTopButton(); // Initialize scroll top button.
Riode.floatSVG('.float-svg'); // Floating SVG
Riode.initShowVendorSearch('.toolbox .form-toggle-btn'); // Initialize show vendor search form
Riode.initFloatingElements('.floating'); // Initialize floating widgets
Riode.initAdvancedMotions('.skrollr'); // Initialize scrolling widgets
Riode.degree360('.product-gallery-degree'); // Initialize 360 degree
Riode.scrollSet('.scroll-menu a'); // Initialize Scroll Menu
Riode.CommentWithMedia.init(); // Initialize Comment with Media
Riode.status = 'complete';
}
/**
* Setup Riode
*/
// Prepare Riode Theme
Riode.prepare();
// Initialize Riode Theme
window.onload = function () {
Riode.status = 'loaded';
Riode.$body.addClass('loaded');
Riode.$window.trigger('riode_load');
Riode.call(Riode.initLayout);
Riode.call(Riode.init);
Riode.$window.trigger('riode_complete');
Riode.refreshSidebar();
}
})();
|
import {useContext} from 'react';
import {useApiClient} from './useApiClient';
import {DoneTaskContext} from '../_context/DoneTaskContext';
import {PendingTaskContext} from '../_context/PendingTaskContext';
export const useTaskApi = () => {
const {client} = useApiClient();
const [, setDoneTasks] = useContext(DoneTaskContext);
const [, setPendingTasks] = useContext(PendingTaskContext);
const getTasks = (type, date) => client.get('/api/task/' + type + (date ? '?date=' + date : '')).catch(console.log);
const getPreviousDayTasks = () => client.get('/api/task/previous_day').catch(console.log);
const getExportTask = (date) =>
client
.get('/api/task/export?date=' + date)
.then((res) => {
const hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + escape(res.data);
hiddenElement.target = '_blank';
hiddenElement.download = date + '.csv';
hiddenElement.click();
})
.catch(console.log);
const getExportTaskForRange = (start, end) =>
client
.get(`/api/task/export/range?start=${start}&end=${end}`)
.then((res) => {
const hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + escape(res.data);
hiddenElement.target = '_blank';
hiddenElement.download = `${start}_${end}.csv`.replaceAll('-', '');
hiddenElement.click();
})
.catch(console.log);
const deleteTask = (task) => client.delete('/api/task/delete/' + task.id);
const updateTask = (task) =>
client.patch('/api/task/' + task.id, {
description: task.description,
start: task.start,
end: task.end,
date: task.date,
deadline: task.deadline,
});
const addTask = (data) =>
client.post('/api/task/add', {
description: data.description,
start: data.start,
end: data.end,
date: data.date,
deadline: data.deadline,
});
const getTasksForDate = (date) => Promise.all([getTasks('pending', null), getTasks('done', date)]);
const getTasksForDashboard = (currentDate) =>
Promise.all([getTasks('pending', null), getTasks('done', currentDate), getPreviousDayTasks()]);
const getTasksForDateAndSave = (date) =>
getTasksForDate(date).then(([pending, done]) => {
setPendingTasks(pending.data);
setDoneTasks(done.data);
});
const getTasksForSearch = ({search, page, elements}) =>
client.get('/api/task/search', {
params: {
s: search,
page: page || 1,
elements: elements || 20,
},
});
const getTasksForRange = ({start, end}) =>
client.get('/api/task/range', {
params: {
start: start,
end: end,
},
});
return {
getTasks,
deleteTask,
updateTask,
addTask,
getTasksForDate,
getTasksForDateAndSave,
getExportTask,
getTasksForSearch,
getTasksForRange,
getTasksForDashboard,
getExportTaskForRange,
};
};
|
# Programa que realice cualquiera de las figuras anteriores
print("Selecciona la figura que quieres crear,")
print("Puedes elegir entre las siguientes figuras:")
carlos=input("Triángulo,Cuadrado,Pentágono,Hexágono,Octógono y Decágono: ")
import turtle
turtle.Turtle
l=100
turtle.bgcolor("blue")
turtle.color("pink")
turtle.width(10)
turtle.speed(0)
if carlos=="Triángulo":
for _ in range(3):
turtle.forward(l)
turtle.left(120)
elif carlos=="Cuadrado":
for _ in range (4):
turtle.forward(l)
turtle.left(90)
elif carlos=="Pentágono":
for _ in range(5):
turtle.forward(l)
turtle.left(72)
elif carlos=="Hexágono":
for _ in range (6):
turtle.forward(l)
turtle.left(60)
elif carlos=="Octógono":
for _ in range (8):
turtle.forward(l)
turtle.left(45)
elif carlos=="Decágono":
for _ in range (10):
turtle.forward(l)
turtle.left(36)
else:
print("Has escrito mal el nombre del polígono, o no esta entre las opciones a seleccionar")
turtle.done()
|
import $axios, { api } from '@/js/api'
export default {
namespaced: true,
state: {
authenticated: false,
user: null,
},
getters: {
authenticated(state) {
return state.authenticated
},
user(state) {
return state.user
},
},
mutations: {
setAuthenticated(state, value) {
state.authenticated = value
},
setUser(state, value) {
state.user = value
},
},
actions: {
async logIn({ dispatch }, credentials) {
await $axios.get('/sanctum/csrf-cookie')
await $axios.post('/login', credentials)
return dispatch('me')
},
async logOut({ dispatch }) {
await $axios.get('/sanctum/csrf-cookie')
await $axios.post('/logout')
return dispatch('me')
},
me({ commit }) {
return api
.get('/account/me')
.then(({ data: { data } }) => {
commit('setAuthenticated', true)
commit('setUser', data)
})
.catch(() => {
commit('setAuthenticated', false)
commit('setUser', null)
})
},
},
}
|
"use strict";
window.globals = require('./can-globals');
|
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db_name');
// map function
var map = function(){
emit(this.field_to_group_by, {
other_fields: this.other_fields
// list other fields like above to select them
})
}
// reduce function
var reduce = function(key, values){
return {
other_fields: values[0].other_fields,
// list other fields like above to select them
// here i am returning values[0] because the fields are already sorted
// write your reduce logic here
};
}
// condition
var query = {
'field_1' : req.body.field_1,
'field_2' : req.body.field_2,
'date_field' : new Date(req.body.date_field),
'field_3' : { $lte : req.body.field_3 },
'bool_field': true
}
// map-reduce command
var command = {
mapreduce: "collection_name", // the name of the collection we are map-reducing
map: map.toString(), // a function for mapping
reduce: reduce.toString(), // a function for reducing
query: query, // filter conditions
sort: {field_3: 1}, // sorting on field_3 (also makes the reducing process faster)
out: {inline: 1} // doesn't create a new collection, includes the result in the output obtained
};
// execute map-reduce command
mongoose.connection.db.executeDbCommand(command, function(err, dbres) {
if(err) throw err;
// restrict the results to 15 (you can restrict to any number you want)
dbres.documents[0].results.splice(14, dbres.documents[0].results.length-15)
// sort the map-reduced results on field_3
var sortedResults = dbres.documents[0].results.sort(function(current, next){
return current.value.field_3 - next.value.field_3
})
var finalGroupedResult = [];
// clean up the results returned by mapreduce
sortedResults.forEach(function(obj, index){
finalGroupedResult.push(obj.value)
});
// render results page
res.render('view/path/to/render', {
title: 'Title of the page',
results: finalGroupedResult
});
});
|
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as orgApi from 'actions/api/organisation';
import * as userApi from 'actions/api/user';
import RegisterPanel from '../index';
function mapStateToProps(state, ownProps) {
const { app, home } = state;
return {
orgs: app.orgs,
value: ownProps.value,
userId: home.userId,
orgId: home.orgId,
};
}
function mapDispatchToProps(dispatch) {
return {
orgApi: bindActionCreators(orgApi, dispatch),
userApi: bindActionCreators(userApi, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(RegisterPanel);
|
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('api/user/', include('user.urls')),
path('api/recipe/', include('recipe.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
module.exports = {
siteMetadata: {
title: `Praktik`,
description: `Vodoinštalačný material PRAKTIK Nové Mesto nad Váhom. Vodovodné Batérie, ...`,
author: `@coderkin`
},
plugins: [
// {
// resolve: 'gatsby-source-googlemaps-geocoding',
// options: {
// key: 'AIzaSyAWJm6cxzq48liRWhS45Otn0DnfncMvc_k',
// address: 'Slovakia'
// }
// },
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
include: /assets/ // See below to configure properly
}
}
},
`gatsby-plugin-sass`,
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`
}
},
{
resolve: `gatsby-plugin-google-analytics`,
options: {
// The property ID; the tracking code won't be generated without it
trackingId: 'UA-150072420-1'
// Defines where to place the tracking script - `true` in the head and `false` in the body
// head: false,
// // Setting this parameter is optional
// anonymize: true,
// // Setting this parameter is also optional
// respectDNT: true,
// // Avoids sending pageview hits from custom paths
// exclude: ["/preview/**", "/do-not-track/me/too/"],
// // Delays sending pageview hits on route update (in milliseconds)
// pageTransitionDelay: 0,
// // Enables Google Optimize using your container Id
// optimizeId: "YOUR_GOOGLE_OPTIMIZE_TRACKING_ID",
// // Enables Google Optimize Experiment ID
// experimentId: "YOUR_GOOGLE_EXPERIMENT_ID",
// // Set Variation ID. 0 for original 1,2,3....
// variationId: "YOUR_GOOGLE_OPTIMIZE_VARIATION_ID",
// // Any additional optional fields
// sampleRate: 5,
// siteSpeedSampleRate: 10,
// cookieDomain: "example.com",
}
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `praktik`,
short_name: `prkt`,
start_url: `/`,
background_color: `#c7d8f0`,
theme_color: `#c7d8f0`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png` // This path is relative to the root of the site.
}
}
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
]
};
|
define(function (require) {
var exports = require('./exports');
var q = require('quack');
var Matrix = require('./matrix');
return exports.Vector = q.createAbstractClass(Matrix, {
toVectorN: new q.AbstractMethod(),
reversed: new q.AbstractMethod(),
toMatrixNM: function() {
var column = this.toVectorN();
var rows = [];
column.forEachArgument(function (v) {
rows.push([v]);
});
return new exports.MatrixNM(rows);
},
/*
* Get or set element. Index is a Vector2
*/
element: function(index, value) {
if (index.y().value() !== 0) {
console.error("Vector has only one column");
}
return this.argument(index.x().value(), value);
},
/**
* Access.
*/
access: function (index) {
return this.argument(index);
},
/**
* Accept.
*/
accept: function (visitor) {
return visitor.visitVector(this);
}
});
});
|
""" networkx interface
"""
import operator
import networkx
from automol.graph._graph_base import atom_keys
from automol.graph._graph_base import bond_keys
from automol.graph._graph_base import atom_symbols
from automol.graph._graph_base import atom_implicit_hydrogen_valences
from automol.graph._graph_base import atom_stereo_parities
from automol.graph._graph_base import bond_orders
from automol.graph._graph_base import bond_stereo_parities
def from_graph(gra):
""" networkx graph object from a molecular graph
"""
nxg = networkx.Graph()
nxg.add_nodes_from(atom_keys(gra))
nxg.add_edges_from(bond_keys(gra))
networkx.set_node_attributes(nxg, atom_symbols(gra), 'symbol')
networkx.set_node_attributes(nxg, atom_implicit_hydrogen_valences(gra),
'implicit_hydrogen_valence')
networkx.set_node_attributes(nxg, atom_stereo_parities(gra),
'stereo_parity')
networkx.set_edge_attributes(nxg, bond_orders(gra),
'order')
networkx.set_edge_attributes(nxg, bond_stereo_parities(gra),
'stereo_parity')
return nxg
def minimum_cycle_basis(nxg):
""" minimum cycle basis for the graph
"""
rng_atm_keys_lst = networkx.algorithms.cycles.minimum_cycle_basis(nxg)
return frozenset(map(frozenset, rng_atm_keys_lst))
def connected_component_atom_keys(nxg):
""" atom keys for the connected components in this graph
"""
return tuple(map(frozenset, networkx.algorithms.connected_components(nxg)))
def isomorphism(nxg1, nxg2):
""" graph isomorphism
"""
matcher = networkx.algorithms.isomorphism.GraphMatcher(
nxg1, nxg2, node_match=operator.eq, edge_match=operator.eq)
iso_dct = None
if matcher.is_isomorphic():
iso_dct = dict(matcher.mapping)
return iso_dct
def subgraph_isomorphism(nxg1, nxg2):
""" subgraph isomorphism -- a subgraph of G1 is isomorphic to G2
"""
matcher = networkx.algorithms.isomorphism.GraphMatcher(
nxg1, nxg2, node_match=operator.eq, edge_match=operator.eq)
iso_dct = None
if matcher.subgraph_is_isomorphic():
iso_dct = dict(matcher.mapping)
return iso_dct
if __name__ == '__main__':
GRA = (
{0: ('C', 3, None), 1: ('C', 2, None), 2: ('C', 3, None),
3: ('C', 1, None), 4: ('C', 1, None), 5: ('C', 1, None),
6: ('C', 1, False), 7: ('C', 1, False), 8: ('O', 0, None)},
{frozenset({1, 4}): (1, None), frozenset({4, 6}): (1, None),
frozenset({0, 3}): (1, None), frozenset({2, 6}): (1, None),
frozenset({6, 7}): (1, None), frozenset({8, 7}): (1, None),
frozenset({3, 5}): (1, False), frozenset({5, 7}): (1, None)})
GRA2 = (
{0: ('C', 3, None), 1: ('C', 2, None), 2: ('C', 3, None),
3: ('C', 1, None), 4: ('C', 1, None), 5: ('C', 1, None),
6: ('C', 1, False), 7: ('C', 1, False), 8: ('O', 0, None)},
{frozenset({1, 4}): (1, None), frozenset({4, 6}): (1, None),
frozenset({0, 3}): (1, None), frozenset({2, 6}): (1, None),
frozenset({6, 7}): (1, None), frozenset({8, 7}): (1, None),
frozenset({3, 5}): (1, False), frozenset({5, 7}): (1, None)})
NXG = from_graph(GRA)
NXG2 = from_graph(GRA2)
print(isomorphism(NXG, NXG2))
networkx.write_yaml(NXG, 'test.g.yaml')
|
import { POSICION_USER, NO_DEVICE, SIN_PERMISOS, LOADING_LOCATION } from './types';
import { Platform } from 'react-native';
import { Constants, Location, Permissions } from 'expo';
export const treaUbicacion = () => {
return async (dispatch) => {
dispatch({type: LOADING_LOCATION})
if (await (Platform.OS === 'android' && !Constants.isDevice)) {
dispatch({type: NO_DEVICE, payload: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!' })
} else {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
dispatch({type: SIN_PERMISOS, payload: 'Permission to access location was denied'})
} else {
let location = await Location.getCurrentPositionAsync({});
dispatch({ type: POSICION_USER, payload: location });
};
}
}
}
|
import argparse
import os
from actions import all_modes
from actions import help_dict
from actions import resampling_filters
from actions import supported_formats
import util
def resize(im, width, height, resample):
if width < 1: width = 1
if height < 1: height = 1
# In case the user hasn't given a resample filter, use NEAREST
if resample is None:
resample_filter = 0
else:
resample_filter = resampling_filters.index(resample)
return im.resize((width, height), resample_filter)
# def run(path, width, height, save_folder, save_as, mode, resample, optimize,
# background):
def run(path, namespace):
im = util.open_image(path)
if im is not None:
resized_image = resize(im, namespace.width, namespace.height,
namespace.resample)
util.save_image(resized_image, path, namespace.save_folder,
namespace.save_as, namespace.mode, "resized",
namespace.optimize, namespace.background)
def subparser(subparser):
my_help = help_dict["modules"]["resize"]
resize_parser = subparser.add_parser("resize", help=my_help["general"])
## This is used to identify which command is being run
resize_parser.set_defaults(command="resize")
resize_parser.add_argument('path', help=my_help["path"])
resize_parser.add_argument('width', type=int, help=my_help["width"])
resize_parser.add_argument('height', type=int, help=my_help["width"])
resize_parser.add_argument('--save_folder', type=str, default=None,
help=my_help["--save_folder"])
resize_parser.add_argument('--save_as', type=str, choices=supported_formats,
default=None, help=my_help["--save_as"])
resize_parser.add_argument('--mode', type=str, choices=all_modes,
default=None, help=my_help["--mode"])
resize_parser.add_argument('--background', type=util.rgb_color_type,
default="#fff", help=my_help["--background"])
resize_parser.add_argument('-optimize', action="store_true",
help=my_help["-optimize"])
resize_parser.add_argument('--resample', type=str, choices=resampling_filters,
default=None, help=my_help["--resample"])
|
import { AsyncStorage } from 'react-native'
export default class Storage {
static async get(key, defaultValue) {
let stored
try {
stored = await AsyncStorage.getItem(key)
stored = JSON.parse(stored)
} catch (err) {
stored = null
}
if (defaultValue && stored === null) {
stored = defaultValue
}
return stored
}
static set(key, value) {
if (value) {
AsyncStorage.setItem(key, JSON.stringify(value))
}
}
static remove(key) {
AsyncStorage.removeItem(key)
}
static clear() {
AsyncStorage.clear()
}
}
|
$(document).ready(function(){
$(".navbar a, footer a[href='#myPage']").on('click', function(event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function(){
window.location.hash = hash;
});
});
});
function toggleSlider(name) {
if ($("#hiddenPanel").is(":visible")) {
if ($(name).is(":visible")) {
$(name).animate(
{
opacity: "0"
},
600,
function(){
$("#hiddenPanel").slideUp(
function() {
$(name).hide();
$(name+"Button").removeClass("selected");
}
);
}
);
} else {
$("#panelButtons .selected").removeClass("selected");
$("#hiddenPanel").slideUp(600, function(){
$("#hiddenPanel").children().hide();
$(name+"Button").addClass("selected");
$(name).show();
$("#hiddenPanel").slideDown(600, function(){
$(name).animate(
{
opacity: "1"
},
600
);
});
});
}
}
else {
$(name+"Button").addClass("selected");
$(name).show();
$("#hiddenPanel").slideDown(600, function(){
$(name).animate(
{
opacity: "1"
},
600
);
});
}
} |
import { Link as RouterLink } from 'react-router-dom';
// material
import { styled } from '@mui/material/styles';
import { Box, Card, Link, Container, Typography } from '@mui/material';
// layouts
import AuthLayout from '../layouts/AuthLayout';
// components
import Page from '../components/Page';
import { MHidden } from '../components/@material-extend';
import { RegisterForm } from '../components/authentication/register';
import AuthSocial from '../components/authentication/AuthSocial';
// ----------------------------------------------------------------------
const RootStyle = styled(Page)(({ theme }) => ({
[theme.breakpoints.up('md')]: {
display: 'flex'
}
}));
const SectionStyle = styled(Card)(({ theme }) => ({
width: '100%',
maxWidth: 464,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
margin: theme.spacing(2, 0, 2, 2)
}));
const ContentStyle = styled('div')(({ theme }) => ({
maxWidth: 480,
margin: 'auto',
display: 'flex',
minHeight: '100vh',
flexDirection: 'column',
justifyContent: 'center',
padding: theme.spacing(12, 0)
}));
// ----------------------------------------------------------------------
export default function Register() {
return (
<RootStyle title="Register">
<AuthLayout>
Đã có tài khoản?
<Link underline="none" variant="subtitle2" component={RouterLink} to="/login">
Đăng nhập
</Link>
</AuthLayout>
{/* <MHidden width="mdDown">
<SectionStyle>
<Typography variant="h3" sx={{ px: 5, mt: 10, mb: 5 }}>
Manage the job more effectively with Minimal
</Typography>
<img alt="register" src="/static/illustrations/illustration_register.png" />
</SectionStyle>
</MHidden> */}
<Container>
<ContentStyle>
<Box sx={{ mb: 5 }}>
<Typography variant="h4" gutterBottom>
Đăng ký.
</Typography>
<Typography sx={{ color: 'text.secondary' }}>Miễn phí và sẽ luôn như vậy.</Typography>
</Box>
<AuthSocial />
<RegisterForm />
<Typography variant="body2" align="center" sx={{ color: 'text.secondary', mt: 3 }}>
Bằng cách bấm Đăng ký, tôi đồng ý với
<Link underline="always" sx={{ color: 'text.primary' }}>
Điều khoản dịch vụ
</Link>
và
<Link underline="always" sx={{ color: 'text.primary' }}>
Chính sách dữ liệu
</Link>
.
</Typography>
<MHidden width="smUp">
<Typography variant="subtitle2" sx={{ mt: 3, textAlign: 'center' }}>
Đã có tài khoản?
<Link to="/login" component={RouterLink}>
Đăng nhập
</Link>
</Typography>
</MHidden>
</ContentStyle>
</Container>
</RootStyle>
);
}
|
"""save the data into db"""
import os
from typing import List, Dict
import pickle
from copy import deepcopy
from type import DataNodeStatus
import json
import dataclasses
class DB:
"""abstract class for save and search data"""
def save(self, key: str, value: DataNodeStatus):
raise NotImplementedError
def get(self, key: str) -> List[DataNodeStatus]:
raise NotImplementedError
def get_all(self) -> Dict[str, List[DataNodeStatus]]:
raise NotImplementedError
class MemoryDB(DB):
"""save data to the memory"""
def get_all(self) -> Dict[str, List[DataNodeStatus]]:
return deepcopy(self.memory_cache)
def __init__(self):
self.memory_cache: Dict[str, List[DataNodeStatus]] = {}
def save(self, key: str, value: DataNodeStatus):
"""save data to the memory"""
if key not in self.memory_cache:
self.memory_cache[key] = []
self.memory_cache[key].append(value)
def get(self, key: str) -> List[DataNodeStatus]:
if key not in self.memory_cache:
return []
return self.memory_cache[key]
class FileDB(DB):
"""save data to be json file"""
def get_all(self) -> Dict[str, List[DataNodeStatus]]:
"""read data from the json file"""
with open(self.file, 'rb') as f:
data: Dict[str, List[DataNodeStatus]] = pickle.load(f)
return data
def __init__(self, file: str):
self.file: str = file
# init the json file
if not os.path.exists(file):
with open(file, 'wb') as f:
pickle.dump({}, f)
def save(self, key: str, value: DataNodeStatus):
"""read data from the json file"""
with open(self.file, 'rb') as f:
data: Dict[str, List[DataNodeStatus]] = pickle.load(f)
if key not in data:
data[key] = []
data[key].append(value)
# save data into the json file
with open(self.file, 'wb') as f:
pickle.dump(data, f)
def get(self, key: str) -> List[DataNodeStatus]:
"""read data from the json file"""
with open(self.file, 'rb') as f:
data: Dict[str, List[DataNodeStatus]] = pickle.load(f)
if key not in data:
data[key] = []
return data[key]
class JsonDB:
def __init__(self):
self.file = "./db.json"
def save(self, value: str):
with open(self.file, 'a+', encoding='utf-8') as f:
# 读取文件最后n行数据即可
f.write(value + '\n')
def get(self, latest: int = 10) -> List[str]:
""""""
with open(self.file, 'r', encoding='utf-8') as f:
lines = f.readlines()
status = lines[-latest:]
status = [json.loads(item) for item in status]
return status
|
#!/usr/bin/python3
from __future__ import print_function
import argparse
import errno
import glob
import json
import logging
import os
import os.path
import re
import shutil
import subprocess
import sys
import time
from subprocess import check_output
from textwrap import wrap
class FoundBugException(Exception):
pass
script_path = os.path.dirname(os.path.realpath(__file__))
cpachecker_root = os.path.join(script_path, os.pardir, os.pardir, os.pardir)
# Not thread safe
temp_dir = os.path.join(script_path, 'temp_dir_coverage')
def print_command(command, logger):
for c in command[:-1]:
logger.debug(c + " \\")
logger.debug(command[-1])
def create_temp_dir(temp_dir):
try:
shutil.rmtree(temp_dir)
except:
pass
os.makedirs(temp_dir)
coverage_test_case_message = 'Found covering test case'
#
# def found_coverage_test_case(output):
# return coverage_test_case_message.encode('utf-8') in output
def gen_reach_exit_spec(f):
print('CONTROL AUTOMATON CoverageAutomaton', file=f)
print('', file=f)
print('INITIAL STATE WaitForExit;', file=f)
print('', file=f)
print('STATE USEFIRST WaitForExit:', file=f)
print(
' MATCH EXIT -> ERROR("' + coverage_test_case_message + '");',
file=f)
print('', file=f)
print('END AUTOMATON', file=f)
def gen_covers_any_line_in_set_then_reach_exit_spec(lines_to_cover, f):
print('CONTROL AUTOMATON CoverageAutomaton', file=f)
print('', file=f)
print('INITIAL STATE LookingForLine;', file=f)
print('', file=f)
print('STATE USEFIRST LookingForLine:', file=f)
print(' CHECK(' +
'AutomatonAnalysis_AssumptionAutomaton, "state == __FALSE") ' +
'-> STOP;', file=f)
lines = map(str, lines_to_cover)
print(
' COVERS_LINES(' + ' '.join(lines) + ') -> GOTO WaitForExit;',
file=f)
print('', file=f)
print('STATE USEFIRST WaitForExit:', file=f)
print(
' MATCH EXIT -> ERROR("' + coverage_test_case_message + '");',
file=f)
print('', file=f)
print('END AUTOMATON', file=f)
def create_spec(spec_folder):
reach_exit_spec_file = os.path.join(spec_folder, 'spec' + spec_extension)
with open(reach_exit_spec_file, 'w') as f:
gen_reach_exit_spec(f)
return reach_exit_spec_file
def create_spec_for_lines(spec_folder, lines_to_cover):
reach_exit_spec_file = os.path.join(spec_folder, 'spec' + spec_extension)
with open(reach_exit_spec_file, 'w') as f:
gen_covers_any_line_in_set_then_reach_exit_spec(lines_to_cover, f)
return reach_exit_spec_file
spec_extension = '.spc'
def counterexample_spec_files(cex_dir):
pattern = r'.*Counterexample.([^.]*)' + spec_extension
all_files = sorted(os.listdir(cex_dir))
return [os.path.join(cex_dir, cex)
for cex in all_files if re.match(pattern, cex)]
cov_extension = '.aa-prefix.coverage-info'
def counterexample_coverage_files(cex_dir):
pattern = r'.*Counterexample.([^.]*)' + cov_extension
all_files = sorted(os.listdir(cex_dir))
return [os.path.join(cex_dir, cex)
for cex in all_files if re.match(pattern, cex)]
def move_execution_spec_files(temp_dir, output_dir):
if os.path.exists(output_dir):
msg = 'Output directory (' + output_dir + ') should not exist.'
raise ValueError(msg)
os.makedirs(output_dir)
all_cex_specs = counterexample_spec_files(temp_dir)
for spec in all_cex_specs:
bn = os.path.basename(spec)
shutil.copyfile(src=spec, dst=os.path.join(output_dir, bn))
def move_execution_spec_and_cex_coverage_files(temp_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
all_cex_specs = counterexample_spec_files(temp_dir)
all_cex_cov = counterexample_coverage_files(temp_dir)
# sanity check, should have a coverage file for each .spc file:
no_extension_cov = list(map(
lambda s : s.replace(cov_extension, ''), all_cex_cov))
no_extension_spc = list(map(
lambda s : s.replace(spec_extension, ''), all_cex_specs))
assert no_extension_cov == no_extension_spc
def counterexample_filename(path, i, ext):
return os.path.join(path, 'Counterexample.' + str(i) + ext)
i = 1
new_specs = []
for cex in no_extension_spc:
while True:
if not os.path.exists(
counterexample_filename(
path=output_dir, i=i, ext=spec_extension)):
break
i = i + 1
new_spec = counterexample_filename(
path=output_dir, i=i, ext=spec_extension)
shutil.copyfile(
src=cex+spec_extension,
dst=new_spec)
new_specs.append(new_spec)
# sanity check
# if spec file didn't exist, coverage file shouldn't exist either
assert not os.path.exists(
counterexample_filename(
path=output_dir, i=i, ext=cov_extension))
shutil.copyfile(
src=cex+cov_extension,
dst=counterexample_filename(
path=output_dir, i=i, ext=cov_extension))
return new_specs
def run_command(command, logger):
logger.debug("Executing:")
print_command(command, logger)
try:
output = check_output(command, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
logger.error(e.output)
raise e
logger.debug("Finished Executing")
logger.debug(output)
return output
class FoundUserDefinedPropertyViolation():
def found_property_violation(self):
return True
def found_bug(self):
return True
class OnlyGeneratedSuccessfulExecutions():
def found_property_violation(self):
return True
def found_bug(self):
return False
class NoPropertyViolationFound():
def found_property_violation(self):
return False
def found_bug(self):
raise Exception('This method should not have been called')
def parse_result(output, logger):
pattern = r'Verification result: [^(]*\((?P<message>[^)]*)\).*'
result_pattern = r'Verification result: (?P<result>.*)'
m_result = re.search(pattern=result_pattern, string=str(output))
m = re.search(pattern=pattern, string=str(output))
if not m_result:
logger.error("Failed to parse CPAchecker output.")
return NoPropertyViolationFound()
if (m_result.group('result').startswith('TRUE') or
m_result.group('result').startswith('UNKNOWN')):
return NoPropertyViolationFound()
else:
if not m:
logger.error("Failed to parse CPAchecker output.")
return NoPropertyViolationFound()
if m.group('message') == coverage_test_case_message:
return OnlyGeneratedSuccessfulExecutions()
else:
return FoundUserDefinedPropertyViolation()
class ComputeCoverage():
def __init__(
self,
instance,
output_dir,
cex_count,
spec,
heap_size,
timelimit,
logger,
aa_file,
start_time):
self.instance = instance
self.output_dir = output_dir
self.cex_count = cex_count
self.spec = spec
self.heap_size = heap_size
self.timelimit = timelimit
self.logger = logger
check_aa(aa_file, logger)
self.aa_file = aa_file
self.lines_covered = set()
self.lines_to_cover = self.compute_lines_to_cover(
self.instance, self.logger)
self.start_time = start_time
@staticmethod
def compute_lines_to_cover(instance, logger):
create_temp_dir(temp_dir)
command = [
os.path.join(cpachecker_root, 'scripts', 'cpa.sh'),
# Using this configuration because it seems lightweight
'-detectRecursion',
'-outputpath', temp_dir,
instance]
try:
run_command(command, logger)
lines_to_cover = get_lines_to_cover(temp_dir)
finally:
shutil.rmtree(temp_dir)
return lines_to_cover
@staticmethod
def cpachecker_command(
temp_dir,
specs,
heap_size,
timelimit,
instance,
export_coverage=False,
stop_after_error=False,
cex_count=0):
conf = os.path.join(
cpachecker_root, 'config', 'valueAnalysis.properties')
coverage_options = [
'-setprop',
'counterexample.export.exportCounterexampleCoverage=true',
'-setprop',
'cpa.composite.aggregateBasicBlocks=false']
stop_after_error_opts = \
[] if stop_after_error else \
['-setprop', 'analysis.stopAfterError=false']
timelimit_prop = []
if timelimit is None:
# No time limit (see doc/ConfigurationOptions.txt)
timelimit_prop = ['-setprop', 'limits.time.cpu=-1ns']
else:
timelimit_prop = ['-setprop', 'limits.time.cpu='+str(timelimit)+'s']
return [
os.path.join(cpachecker_root, 'scripts', 'cpa.sh'),
'-config' , conf,
'-outputpath', temp_dir,
'-setprop', 'specification=' + ','.join(specs)] + (
['-heap', heap_size] if heap_size else []) + (
stop_after_error_opts) + [
'-setprop', 'analysis.counterexampleLimit='+str(cex_count),
'-setprop', 'analysis.traversal.usePostorder=true'] + (
timelimit_prop) + [
'-setprop', 'analysis.traversal.order=DFS',
'-setprop', 'analysis.traversal.useReversePostorder=false',
'-setprop', 'analysis.traversal.useCallstack=false' ] + (
coverage_options if export_coverage else []) + [
instance]
def generate_executions(self):
raise NotImplementedError("Instantiate one of the sub-classes.")
def get_coverage(self, cex_spec_file, instance, aa_file, heap_size, logger):
cex_prefix_coverage_file = \
os.path.splitext(cex_spec_file)[0] + cov_extension
assert os.path.isfile(cex_prefix_coverage_file)
lines_covered, _ = parse_coverage_file(cex_prefix_coverage_file)
return lines_covered
def collect_coverage(self):
for num, cex in enumerate(self.generate_executions(), start=1):
new_covered = self.get_coverage(
cex, self.instance, self.aa_file, self.heap_size, self.logger)
self.lines_covered.update(new_covered)
self.logger.info(
'Coverage after collecting ' + str(num) + ' executions:' )
self.logger.info('Lines covered: ' + str(len(self.lines_covered)))
self.logger.info(
'Total lines to cover: ' + str(len(self.lines_to_cover)))
self.logger.info('')
self.logger.info(
'Total lines covered: ' + str(len(self.lines_covered)))
self.logger.info(
'Total lines to cover: ' + str(len(self.lines_to_cover)))
return self.lines_covered, self.lines_to_cover
def gen_specs_from_dir(cex_dir):
for spec in counterexample_spec_files(cex_dir):
yield spec
# When adding additional generators also update argparse documentation.
available_generators = ['fixpoint', 'blind']
# It will be necessary to refactor this code to support custom configuration
# of the generators.
def create_generator(
name,
instance,
output_dir,
cex_count,
spec,
heap_size,
timelimit,
logger,
aa_file,
start_time):
if name not in available_generators:
raise Exception('Invalid generator name.')
if name == 'fixpoint':
return FixPointOnCoveredLines(
instance=instance,
output_dir=output_dir,
cex_count=cex_count,
spec=spec,
heap_size=heap_size,
timelimit=timelimit,
logger=logger,
aa_file=aa_file,
start_time=start_time)
if name == 'blind':
if not cex_count:
logger.error((
"Invalid option: when using '-generator_type blind', "
'a limit to the number of counterexamples has to be provided '
'using -cex_count.'))
sys.exit(0)
return GenerateFirstThenCollect(
instance=instance,
output_dir=output_dir,
cex_count=cex_count,
spec=spec,
heap_size=heap_size,
timelimit=timelimit,
logger=logger,
aa_file=aa_file,
start_time=start_time)
raise Exception('Missing generator constructor.')
def define_iteration_timelimit_from_global_timelimit(
start_time, global_timelimit):
if global_timelimit:
assert start_time and global_timelimit
elapsed_time = time.time() - start_time
return str(int(float(global_timelimit) - elapsed_time))
else:
return None
class FixPointOnCoveredLines(ComputeCoverage):
def __init__(
self,
instance,
output_dir,
cex_count,
spec,
heap_size,
timelimit,
logger,
aa_file,
start_time):
super().__init__(
instance=instance,
output_dir=output_dir,
cex_count=cex_count,
spec=spec,
heap_size=heap_size,
timelimit=timelimit,
logger=logger,
aa_file=aa_file,
start_time=start_time)
def generate_executions(self):
last_difference_size = None
cex_created = 0
while True:
remaining_lines = \
self.lines_to_cover.difference(self.lines_covered)
difference_size = len(remaining_lines)
# sanity check
assert (last_difference_size is None or
last_difference_size > difference_size)
if not difference_size:
break
create_temp_dir(temp_dir)
cover_line_then_reach_exit_spec_file = create_spec_for_lines(
spec_folder=temp_dir,
lines_to_cover=remaining_lines)
specs = [cover_line_then_reach_exit_spec_file,
self.spec,
self.aa_file]
timelimit = define_iteration_timelimit_from_global_timelimit(
start_time=self.start_time,
global_timelimit=self.timelimit)
if timelimit and float(timelimit) < 5:
self.logger.debug("Preemptively quitting. Less than 10 seconds left.")
break
command = self.cpachecker_command(
temp_dir=temp_dir,
specs=specs,
heap_size=self.heap_size,
timelimit=timelimit,
instance=self.instance,
export_coverage=True,
stop_after_error=True)
try:
output = run_command(command, self.logger)
specs_generated = move_execution_spec_and_cex_coverage_files(
temp_dir=temp_dir, output_dir=self.output_dir)
finally:
shutil.rmtree(temp_dir)
msg = 'Generated ' + str(len(specs_generated)) + ' executions.'
self.logger.info(msg)
cpachecker_result = parse_result(output, self.logger)
# sanity check
assert (cpachecker_result.found_property_violation() or
len(specs_generated) == 0)
if not cpachecker_result.found_property_violation():
self.logger.debug('CPAchecker did not generate an execution.')
break
if cpachecker_result.found_bug():
self.logger.error(
'Found an assertion violation. Inspect counterexamples '
'before collecting a coverage measure.')
raise FoundBugException()
for spec in specs_generated:
yield spec
# we might be ignoring already produced counterexamples
# if we generate more than once at a time (this is not
# the case yet)
cex_created += 1
if self.cex_count and cex_created >= self.cex_count:
break
# Also need to leave the main loop
if self.cex_count and cex_created >= self.cex_count:
break
class GenerateFirstThenCollect(ComputeCoverage):
def __init__(
self,
instance,
output_dir,
cex_count,
spec,
heap_size,
timelimit,
logger,
aa_file,
start_time):
super().__init__(
instance=instance,
output_dir=output_dir,
cex_count=cex_count,
spec=spec,
heap_size=heap_size,
timelimit=timelimit,
logger=logger,
aa_file=aa_file,
start_time=start_time)
def get_coverage(self, cex_spec_file, instance, aa_file, heap_size, logger):
create_temp_dir(temp_dir)
specs = [aa_file, cex_spec_file]
lines_covered = set()
lines_to_cover = set()
command = self.cpachecker_command(
temp_dir=temp_dir,
specs=specs,
heap_size=heap_size,
timelimit=900,
instance=instance,
export_coverage=True,
stop_after_error=True)
try:
run_command(command, logger)
lines_covered = get_covered_lines(temp_dir)
lines_to_cover = get_lines_to_cover(temp_dir)
finally:
shutil.rmtree(temp_dir)
return lines_covered
def generate_executions(self):
create_temp_dir(temp_dir)
reach_exit_spec_file = create_spec(spec_folder=temp_dir)
specs = [reach_exit_spec_file, self.spec]
timelimit = define_iteration_timelimit_from_global_timelimit(
start_time=self.start_time,
global_timelimit=self.timelimit)
if timelimit and float(timelimit) < 0:
# using alternative time limit of 10s, this should not be used
# under normal circumstances
timelimit = 10
command = self.cpachecker_command(
temp_dir=temp_dir,
specs=specs,
heap_size=self.heap_size,
cex_count=self.cex_count,
timelimit=timelimit,
instance=self.instance)
try:
output = run_command(command, self.logger)
move_execution_spec_files(
temp_dir=temp_dir, output_dir=self.output_dir)
finally:
shutil.rmtree(temp_dir)
cex_generated = len(os.listdir(self.output_dir))
msg = 'Generated ' + str(cex_generated) + ' executions.'
self.logger.info(msg)
cpachecker_result = parse_result(output, self.logger)
# sanity check
assert (cpachecker_result.found_property_violation() or
cex_generated == 0)
if (cpachecker_result.found_property_violation() and
cpachecker_result.found_bug()):
self.logger.error(
'Found an assertion violation. Inspect counterexamples '
'before collecting a coverage measure.')
raise FoundBugException()
return gen_specs_from_dir(self.output_dir)
class CollectFromExistingExecutions(GenerateFirstThenCollect):
def __init__(
self,
instance,
cex_dir,
heap_size,
timelimit,
logger,
aa_file,
start_time):
super().__init__(
instance=instance, output_dir=cex_dir, cex_count=None, spec=None, heap_size=heap_size, timelimit=timelimit, logger=logger, aa_file=aa_file, start_time=start_time)
def generate_executions(self):
return gen_specs_from_dir(self.output_dir)
def parse_coverage_file(coverage_file):
lines_covered = set()
# Some lines, such as comments and blank lines, cannot be covered.
# These lines never show up in coverage files produced by CPAchecker.
lines_to_cover = set()
# This script only supports a single source file right now.
# For the current use case we don't need more than that but the file
# format does not seem to complex.
sf_lines = []
with open(coverage_file) as f:
for line in f:
m_sf = re.match(
r'^SF:(?P<sourcefile>.*)$', line)
if m_sf:
sf_lines.append(m_sf.group('sourcefile'))
m = re.match(
r'^DA:(?P<line_number>[^,]*),(?P<visits>.*)$', line)
if not m:
continue
line_number = int(m.group('line_number'))
lines_to_cover.add(line_number)
n_visits = int(m.group('visits'))
if n_visits != 0:
lines_covered.add(line_number)
assert len(sf_lines) == 1
# The coverage files produced for counterexample do not contain
# all the existing lines. Should not output this information.
if coverage_file.endswith(cov_extension):
lines_to_cover = None
return lines_covered, lines_to_cover
def get_covered_lines(output_dir):
coverage_files = counterexample_coverage_files(output_dir)
assert len(coverage_files) == 1
lines_covered, _ = parse_coverage_file(coverage_files[0])
return lines_covered
def get_lines_to_cover(output_dir):
coverage_file = os.path.join(output_dir, 'coverage.info')
assert os.path.isfile(coverage_file)
_, lines_to_cover = parse_coverage_file(coverage_file)
return lines_to_cover
def check_aa(aa_file, logger):
assert os.path.isfile(aa_file)
with open(aa_file) as f:
for line in f:
if 'ASSUME' in line:
logger.error(
'There are known bugs in ASSUME statements that can '
'result in misleading output. '
'To generate the Assumption Automaton without ASSUME '
'statements, use the following option:\n'
'assumptions.automatonIgnoreAssumptions=true')
raise ValueError(
'Assumption Automaton contains ASSUME statement.')
def create_arg_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
"-assumption_automaton_file",
required=True,
help="""some_path/assumption_automaton
File containing an assumption automaton.""")
parser.add_argument(
"-cex_dir",
required=True,
help=("Directory where traces sampling the execution space are "
"located. If the option -only_collect_coverage is not "
"present, then this directory must not exist, since it will "
"be created and used to store the executions."))
parser.add_argument(
"-cex_count",
type=int,
help="Only applicable when -only_collect_coverage "
"is not present. Indicates the number of traces to be generated.""")
parser.add_argument(
"-only_collect_coverage",
action='store_true',
help="Do not generate traces before collecting coverage.")
parser.add_argument(
"-debug",
action='store_true',
help="Verbose output.")
parser.add_argument(
"-timelimit",
type=int,
help=("Only applicable when -only_collect_coverage is not present.\n"
"Time limit in seconds: We sample the execution space by "
"repeatedly calling CPAchecker, this would be a global time limit "
"across several calls."))
parser.add_argument(
"-spec",
required=True,
help=("Only applicable when -only_collect_coverage is not present.\n"
"CPAchecker specification file: We sample the execution space by "
"repeatedly calling CPAchecker, if a specification violation was "
"found, we will produce an error message for the executions "
"generated to be manually inspected."))
parser.add_argument(
"-heap", help="Heap size limit to be used by CPAchecker.")
parser.add_argument(
"-generator_type",
choices=available_generators,
default='fixpoint',
help=("Type of generator to be used. 'fixpoint' incrementally "
"creates executions that cover statements not covered by "
"previously generated executions. The generator stops producing "
"executions when the number of generated executions reaches "
"-cex_count or when CPAchecker returns TRUE or UNKNOWN."))
parser.add_argument(
"instance_filename", help="Instance filename.")
return parser
def check_args(args, logger):
check_aa(args.assumption_automaton_file, logger)
if (args.cex_count or args.timelimit) and (args.only_collect_coverage):
logger.error((
'Invalid options: Options -cex_count can only be '
'present when -only_collect_coverage is not present.'))
sys.exit(0)
if not args.only_collect_coverage:
if os.path.exists(args.cex_dir):
logger.error((
'Invalid option: when not using -only_collect_coverage, the '
'directory -cex_dir (' + args.cex_dir + ') must not '
'exist. The directory will be created by this script '
'and will contain the generated executions.'))
sys.exit(0)
if not os.path.isfile(args.spec):
logger.error(
'Invalid option: Specification file does not exist: ' +
args.spec)
sys.exit(0)
elif (args.cex_count or args.timelimit):
logger.error(
('Invalid options: Options -cex_count and -timelimit can only '
'be present when -only_collect_coverage is not present.'))
sys.exit(0)
def main(argv, logger):
parser = create_arg_parser()
if len(argv)==0:
parser.print_help()
sys.exit(1)
args = parser.parse_args(argv)
if args.debug:
logger.setLevel(logging.DEBUG)
check_args(args, logger)
start_time = time.time()
if args.only_collect_coverage:
compute_coverage = CollectFromExistingExecutions(
instance=args.instance_filename,
cex_dir=args.cex_dir,
heap_size=args.heap,
timelimit=args.timelimit,
logger=logger,
aa_file=args.assumption_automaton_file,
start_time=start_time)
else:
compute_coverage = create_generator(
name=args.generator_type,
instance=args.instance_filename,
output_dir=args.cex_dir,
cex_count=args.cex_count,
spec=args.spec,
heap_size=args.heap,
timelimit=args.timelimit,
logger=logger,
aa_file=args.assumption_automaton_file,
start_time=start_time)
compute_coverage.collect_coverage()
|
import React from 'react';
import RightContent from '../GlobalHeader/RightContent';
import BaseMenu from '../SiderMenu/BaseMenu';
import styles from './index.less';
import LogoImg from '../LogoImg';
export default class TopNavHeader extends React.PureComponent {
render() {
const { theme, contentWidth } = this.props;
return (
<div className={`${styles.head} ${theme === 'light' ? styles.light : ''}`}>
<div
ref={ref => {
this.maim = ref;
}}
className={`${styles.main} ${contentWidth === 'Fixed' ? styles.wide : ''}`}
>
<div className={styles.left}>
<div className={styles.logo} key="logo" id="logo">
<LogoImg />
</div>
<div
style={{
marginLeft: 55,
}}
>
<BaseMenu {...this.props} style={{ border: 'none', height: 64 }} />
</div>
</div>
<RightContent {...this.props} />
</div>
</div>
);
}
}
|
"""empty message
Revision ID: ac483cfeb230
Revises: b29e2c4bf8c9
Create Date: 2017-10-11 10:16:39.682591
"""
# revision identifiers, used by Alembic.
revision = 'ac483cfeb230'
down_revision = 'b29e2c4bf8c9'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.alter_column('certificates', 'name',
existing_type=sa.VARCHAR(length=128),
type_=sa.String(length=256))
def downgrade():
op.alter_column('certificates', 'name',
existing_type=sa.VARCHAR(length=256),
type_=sa.String(length=128))
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[119],{172:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return i})),n.d(t,"metadata",(function(){return o})),n.d(t,"rightToc",(function(){return p})),n.d(t,"default",(function(){return s}));var r=n(2),a=n(6),c=(n(0),n(299)),i={title:"Form / Checklist"},o={unversionedId:"examples/checklist",id:"examples/checklist",isDocsHomePage:!1,title:"Form / Checklist",description:"Use a checklist to group a set of related checkboxes.",source:"@site/docs/examples/checklist.md",slug:"/examples/checklist",permalink:"/wave/docs/examples/checklist",editUrl:"https://github.com/h2oai/wave/edit/master/website/docs/examples/checklist.md",version:"current",sidebar:"someSidebar",previous:{title:"Form / Checkbox",permalink:"/wave/docs/examples/checkbox"},next:{title:"Form / Picker",permalink:"/wave/docs/examples/picker"}},p=[],l={rightToc:p};function s(e){var t=e.components,i=Object(a.a)(e,["components"]);return Object(c.b)("wrapper",Object(r.a)({},l,i,{components:t,mdxType:"MDXLayout"}),Object(c.b)("p",null,"Use a checklist to group a set of related checkboxes."),Object(c.b)("div",{className:"cover",style:{backgroundImage:"url("+n(393).default+")"}}),Object(c.b)("pre",null,Object(c.b)("code",Object(r.a)({parentName:"pre"},{className:"language-py"}),"from h2o_wave import main, app, Q, ui\n\n\n@app('/demo')\nasync def serve(q: Q):\n if q.args.show_inputs:\n q.page['example'].items = [\n ui.text(f'selected={q.args.checklist}'),\n ui.button(name='show_form', label='Back', primary=True),\n ]\n else:\n q.page['example'] = ui.form_card(box='1 1 4 10', items=[\n ui.checklist(name='checklist', label='Choices',\n choices=[ui.choice(name=x, label=x) for x in ['Egg', 'Bacon', 'Spam']]),\n ui.button(name='show_inputs', label='Submit', primary=True),\n ])\n await q.page.save()\n")))}s.isMDXComponent=!0},299:function(e,t,n){"use strict";n.d(t,"a",(function(){return m})),n.d(t,"b",(function(){return f}));var r=n(0),a=n.n(r);function c(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function o(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?i(Object(n),!0).forEach((function(t){c(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function p(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n,r,a={},c=Object.keys(e);for(r=0;r<c.length;r++)n=c[r],t.indexOf(n)>=0||(a[n]=e[n]);return a}(e,t);if(Object.getOwnPropertySymbols){var c=Object.getOwnPropertySymbols(e);for(r=0;r<c.length;r++)n=c[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}var l=a.a.createContext({}),s=function(e){var t=a.a.useContext(l),n=t;return e&&(n="function"==typeof e?e(t):o(o({},t),e)),n},m=function(e){var t=s(e.components);return a.a.createElement(l.Provider,{value:t},e.children)},u={inlineCode:"code",wrapper:function(e){var t=e.children;return a.a.createElement(a.a.Fragment,{},t)}},d=a.a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,c=e.originalType,i=e.parentName,l=p(e,["components","mdxType","originalType","parentName"]),m=s(n),d=r,f=m["".concat(i,".").concat(d)]||m[d]||u[d]||c;return n?a.a.createElement(f,o(o({ref:t},l),{},{components:n})):a.a.createElement(f,o({ref:t},l))}));function f(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var c=n.length,i=new Array(c);i[0]=d;var o={};for(var p in t)hasOwnProperty.call(t,p)&&(o[p]=t[p]);o.originalType=e,o.mdxType="string"==typeof e?e:r,i[1]=o;for(var l=2;l<c;l++)i[l]=n[l];return a.a.createElement.apply(null,i)}return a.a.createElement.apply(null,n)}d.displayName="MDXCreateElement"},393:function(e,t,n){"use strict";n.r(t),t.default="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJoAAACWCAYAAAAmPZFsAAAABHNCSVQICAgIfAhkiAAAABl0RVh0U29mdHdhcmUAZ25vbWUtc2NyZWVuc2hvdO8Dvz4AAAAtdEVYdENyZWF0aW9uIFRpbWUATW9uIDI4IFNlcCAyMDIwIDEyOjUzOjA0IFBNIFBEVHzOnogAABjOSURBVHic7d15XBX1/sfxF0uCQOAROeKWK25gqSUgmYq4oKnlkgoJ4o6hppSiKS0uXZdEUcGwrkiKoZJaZmluN5fsuiSmCAoJXWUTRGTVI/L9/aGcX0fNOIhDx77Px8PHgzPzne98Z3gzM+ecmY9GQgiBJD1hxtU9AOmfQQZNUoQMmqQIGTRJETJokiJk0CRFyKBJivjbB+331FRiYmLQaDTVPRTpMVQ6aAUFBSwPCaH/q/142a0zw4a9QVTUep1ALF60iBc7duDChQuVHmD4mnCWLlnM0aNHKt2HVP1MK7NQQUEBfqN8SU1NpW7duji1a0dyUhIrQ0OJOx1HyPLlGBkZVckAJ4yfQNu2bXFze7lK+pOqR6WCFha2mtTUVF4fNIj33puDiYkJJSUlBE6fxqFDP7Lr22/pP2BAlQyweYsWNG/Rokr6kqqP3qfO27dv8/1332FjY8PMmUGYmJgAULNmTd6eNg1nZ2dycnJ0lsnIyGDMmNF0dnVlxPBhxMfHa+dpNBpCli2jd6+euHV2ZbTfKE6dPKmdX376PXv2rHbaV1/FMnjwIDq7ujB48CB2bN+us75t275i8KDXcet8d327v/9eO6+0tJTQ0BX09exDZ1cXhr0xlL17f9B3N0h60jtoaWlpFBYW0qFDB8zMzHTmtW7dhjWfRuA3erTO9KVLFmNb2xZHR0eSkpKYPWsW5d/lz53zHtHRG2nb1pE3R47kypUrTJrkz/nz5x+6/piYGD5euBBjIyO8vLwxNTFh/vx52rBs3bKFhQsWYGNjg5/faMzMzJkz5z2+/fZbACLXreOLqCgcWrYkYPJkTExMeG/27Me6jpT+mt6nzhs3bgBgY1Orwsu8MWwYfn53w/emtzeJiQlkZGSg0WjYv38/Tk7tCFm+HGNjYzp27MjkgADWR65jydJPdPopKytj3b8/x8LCgnXrIrG2sWGkjw+TJwcQFxeHh0dP1n62Fjs7O1auWo2ZmRkjR45k4MABbI75kv79+3Pp0iUARo8eTYcOHenTx5PExATs6tTRd1dIetA7aNbW1gDcyL9R4WU6tO+g/blFi+YkJiZQUlzMxYsXAXB72Q1j47sHVxcXV2rUqEFCQsID/eTk5HDt2jU6duyItY0NALVr12bTpi8BuHr1KrnXrgHQvVtXnWVLS0sB6NOnD/v27cV/4kQcnZzo2LEjfT37UtvWtsLbI+lP76A1aNAAC0tL4k6fRqPRUKNGDe285OQk1kZE4OzswtA33tBON753HQfAH96NCh5+K5wQ4qHvWv/q1rny+fXq1eNfixbrzCsPcnd3d76MieGHPT8QdyaOjRs2ELV+PaErV+Hm5vbI/qXK0/sarUaNGnj28SQvL49lnyylrKwMgJKSEkKWLWP//v3UqlWx02qbNm0BOHrkiLafY8eOcfv2bVq1av1Aezs7O2xtbUm8cIHs7GwArl27hre3F0uXLsHOzg6VSoUQAgcHB9q1a4ejoyO//HKKrKzMe/3/RHx8PG8FBLB27Wd8NG8+ZWVlHD50SN9dIemhUh9vTJkyhRMnjhMbG8vhw0d47rnnSEq6SF5eHt26dcOjZ88K9dO0aVPc3Xtw8OABpk6ZQvMWzfl2505MTEzw8/N7oL2xsTFjxoxl6dIlTJw4gS4vd+Ho0SOkpqbi6zsKY2NjRo3yY8WK5YwdM4Yur3Th1zNnOH78OOPGjadHDw/27d3Ljh07OHHiBI5tHfl+9913pM8//3xldoVUQZUKmrWNDVFfbGBtxKccPPgf4uJOo1bXxc9vNF7e3np9WLvw449ZvWoVe/bs5pdfTtGyZUsmT56Co5PTQ9uP8PLC1NSUTZui2bJlM/b29sx+bw6enp4A+Pj6UsOsBptjYohav57atW2ZONGfcePHA/DujJk8U6MGBw8cYN/evTRo0IDZs9+jb79+ldkVUgUZyWcGJCX87b9Ul54OMmiSImTQJEXIoEmKkEGTFCGDJilCBk1ShAyapAgZNEkRMmiSImTQJEXIoEmKkEGTFCGDJilCBk1ShAyapAgZtIdYHxn5wEPJ0uORQZMUIYMmKaJSQbt06RIDBgzAysqK2rVrM2bMGAoLC/9yudjYWIYOHVqZVWr98ssv7Nix4y/bDRs2DBcXF51pOTk51Ln3RHplx7JixQqMjY0xNTXF3NycNm3asHz58r985vRxODk5ce7cucfqIyQkhLy8vEe2SUhIwMjIiO//UKsEdPfV5MmTWb16td7rr1TQXn31Vdzc3EhPTycxMZHi4mKmTZtWma70VpGg5efn89NPP5GXl0dycnKVj2HMmDGUlpZSWFjIhg0biImJYdasWVW+nqpUkaBt3LgRV1dXoqOjq3z9egetpKSEpKQk3nnnHaytrVGr1YSFhTF8+HBtm+3bt9OqVStUKhVDhgwhKyvrgX6EEMyfPx97e3vs7e2ZOXOmtmzBH+epVCpmzJjBnTt32Lx5M+PHjycqKgp7e3vu3Lnz0DFu27YNT09PvLy8nshOK2dqaspLL73Ezp07iYiI4Nq9cgznz5+nS5cu2NjY4OLiwokTJ7TLfPnll7Rt2xa1Ws2QIUMoKioC7v5xeHt7o1KpaN68ORs2bHjoOh/Vrny9zz77LC+88AKnT58GoFOnTqSlpdG0aVMWL1780H6FEMTExBAZGcnevXu146oqegetZs2aeHp6Mnr0aO3h3NbWll69egF3N9bf35+YmBhycnJo1qwZY8eOfaCfzz77jJ07d3L27FkuXrzI8ePHWbFihXberl27+PXXX7l8+TJnz54lNDSU4cOH89lnnzFq1CgyMzO1JbPuFx0dzfDhwxk+fPgTDVo5tVpN586dOXLkCBqNhgEDBjBu3Djy8vIICgpi4MCBFBcXc/XqVQICAti9ezeZmZk0btyYgwcPAuDv74+1tTWZmZl89913BAUF6QS03J+102g09O/fnwkTJpCfn8+SJUvo27cvt27d4sSJEzRo0ICUlBSCgoIeug0//fQT9vb2tG7dmu7du/P1119X6T6q1Klz+/btuLm5MX78eJo0acLcuXMpLi4G7v7F+vv706FDB0xMTJg/fz4HDhygpKREp48NGzawePFi7OzssLa2Jjg4mO33PlL44osvmDNnDmq1GisrK2JjY/H19a3Q2DIyMjh79izu7u60adMGc3Pzh/7CqpparSY3N5fDhw/TsGFD/Pz8MDIyYvDgwbRo0YKjR49iamqKEILz588jhCAkJIT+/ftTUlLCzp07WbFiBWZmZrRq1YqxY8c+cInwqHaHDh1CpVLh6+uLkZERffr04eTJk3/6x3i/6Ohohg0bBvBE/kAr9aT6M888Q0BAAAEBAWRkZDBnzhzGjRvHpk2bSEtLIzIykoiIiP9fiamp9rRS7siRI/To0YO6desCdw/darUagPT0dJo1a6Zta2VlhZWVVYXGNnfuXLKysnjmmWe007y8vJ7ItdofZWRkYGtrS1paGocOHcLe3l4779atW+Tk5NyrfLSJjz/+GB8fH/r160dISAhFRUUUFhbSpEkT7TKlpaXaX3y57OzsP213/z4DaNiwYYXGfvv2bdasWQOgc62dnZ2NnZ1dRXfBI+l9RLt8+TIbN27Uvq5Xrx7z5s1j79692tezZs0iMzNT+y8/P/+BjXZzc9OeQjIzM8nKytJWdaxfv75OMAoLCx+oIvlnzpw5w759+xBCIITg4sWLFBYW/un1XFVIT0/n559/pkuXLtSrVw9XV1ed7b9+/TpeXl4A9O3bl0OHDvHbb79RUlLC/PnzqVOnDmZmZly6dEm7TE5ODuHh4TrreVS7+/cZwJUrV7TXvY+yZ88eunTpot1nQgi8vb3ZsmVLle0jvYNmbm7OpEmT+Pzzz8nPz+d///sfM2fOxNnZGYARI0awbt06Tp06hRCC2NhYXn/99Qf6GTlyJMHBwVy9ehWNRkNQUBBLly4FwNfXl+DgYLKzs7lx4waDBg1i69atAFhaWpKYmEh+fv4DfV64cIHLly/TvXt37TQHBwfq16/P/v379d3Uv6TRaDh27Bj9+/fn7bffpnbt2nTt2pXMzEwiIyO1p0kXFxeuX79OXFwcL774Irm5uVhYWGBtbY2xsTEWFha89tprBAYGcvPmTa5du8bAgQP58ccfddb3qHZdu3YlLy+PiIgIhBDs2rULV1dXbR0US0tLTp8+ze3btx/Yjj+eNstV+elTVMKPP/4oOnXqJMzMzIRKpRLe3t7i6tWr2vnbtm0TrVu3FtbW1sLV1VWcOnVKCCHE1q1bxZAhQ4QQQpSVlYl58+aJevXqidq1a4uhQ4dq+ygrKxMffPCBUKvVwtraWkydOlXcvn1bCCFEQUGB6Nevn7CwsBAFBQU64woODhb+/v4PjHfRokXCx8dHZGdnC1tb2wfGcr/IdevE9m3bHjpv+fLlwsjISJiYmAhzc3Ph5OQkwsLCdNrEx8eLV155RTz77LPCwcFBREdHa+d9+OGHwt7eXtjb24vBgweLnJwcIYQQeXl54s033xS1atUS9evXFzNnzhSlpaVCCCEcHR3F2bNn/7LduXPnhJubm7CwsBBt2rQRx48f1643NjZWqNVqMXv2bJ2xFhQUCCsrK5Genq4z/ebNm6JWrVoiOTlZZ18FBASIVatWPXTfPIos8vIQ6yMjqVWrFq8PGlTdQ3lqyK+gJEXIoEmKkKdOSRHyiCYpQgZNUoQMmqQIGTRJETJokiJk0CRFyKBJipBBkxQhgyYpQgZNUoTed9h+8803rAxdwfXr1x9rxSqViqlvT2PgwIGP1Y9kIPS9r8ijh7uIP3dO7/uR7hd/7pzw6OH+2P1IhkHvU+f169dp6+j42AFv6+j42EdFyXDIazRJEZV6CkppY8aM5kxc3APTP/zwIwbIazyDYBBBAxg1yk/n/2kHKvxfakvVz2CCZm1tTf369at7GFIlGUzQ/sqWLZuJWr+e3Nzr9O7dCweHlpw4eYLQ0JXA3UfjQkKWsWf3bgDGjhvHr2fO0K7d8/hU8Cl4qfKeijcD3323i/CwMN6dMYPYr2Jp9NxzRH0RpdNm8aJ/cSYujtCVq1gXuZ5fz5zRFkGRnjyDOaKFh4cREfGpzrS9+/ZjZWVF9MZoJkyciLt7DwDGjRvP8f/+V9suPz+fnTt3smFjNK1atQLgo3nz6dXTQ7kN+IczmKB5eXkzaPBgnWkWFhYAJCcn4eTUTmdeW0dHUlJSAEi5dAkTE1McHBy082vWrEnTpk2f8KilcgYTNJVKpVPcpJwQgrKyMoyNjXSm/7GKzp1788vLAzysjfRkGfw1mpGREU2aNOH8+fM60y8kXtD+3KRxYzQaDZcuXdJOu/+19GQZzBEtPz+f9PR0nWk2NjZYWloyfPgIPv10DfXr1adZ8+YcPHiAhITzOLW7ezqtbWuLh0dP5n30EUGzZmFpacm6f3+OianBbL7BM5g9HRW1nqio9TrTpk2bjo+vL0PfeIOi4iIWLlxAXt4NevXqyYgRXpyL//8Cw+9/8AGfLF3KJP+JGBkZMX7CBK5dy1V4K/7B9P0WvmOH9lX2jX5V9lVeUafcihXLxexZQdrXd+7ceWAZn5FvitjYrVU2BunPGcwR7VG2bNnMrm93ERgYSIOGDYmPj2fH9u3MmDlT22ZW0EwsLC3x8fHFysqKH/bsISkpCVdX12oc+T/HUxG0gQNfIyMjg+DguVy9ehV7e3smTJhIv36vattMD3yHlaGhTPKfSEFBAQ4tW7JiRSgNGlSs/Kb0mPQ9BMobH6XK0PuINvXtaUydOqXKbuWW/hlk2SpJEQb/ga1kGGTQJEXIoEmKkEGTFCGDJilCBk1ShAyapAgZNEkRMmiSImQ1IUkZ+n45Kr9UlypDVhOSFCGv0SRFGMSNj/dXE1KpVPTx9OTtt6dRo0aNahyZVFEGETTQrSZ0+fJlFi5YgLm5OVOmTK3mkUkVYTCnzvJqQvXr18fFxYWJ/hPZv29fdQ9LqiCDOaLdz8TEVOe0mZaWxupVq/jvf3/mzp07dO3ajaBZs7CysgLgzp07hIeHsfObbygsLKRz587MDX4flUoFwLVr11iyeBHHjh3D1NSUXr17M316IObm5gDMnPEuzZo357fk3zh69Ai1aqmYPGWyznMJ0p8zmCPaH6WkpLB2bQT9+w8A7pZFCJw+HYD1UV/wxYaNXL78P9aEh2mXCVn2CYcPH2bJ0qV8GbOZmhYWTJw4ASEEpaWlBLw1CSMjY6K+2EBY+BqSk5KZM+c9nfVu3bKFfq/2Y9++/YwZO5aPPvyQrKws5TbckOn7eUh1PNc5erSfcHHuJF526yzcOruKjh3ai7femiSKCgu1bQoKCoRGo9G+3rJ5s3jT20sIIUR+fr5w7vSSuHDhgnZ+SUmJiI7eKIqKisSPP/5HePRwF7du3dLOz8rKEi927CBSU1KEEELMePcdMWfOezrj6v9qP7F37169t/ufyGBOnSO8vBgyZChw97O8laGhTJo0icj16zE2NsbYyIjvv/+O+HPnuHzlCufj41Gr1QD89lsyFhYWtGzZUtufubk53t5vAnDx4kVatW6tcypWq9XUq1ePCxcv0PhecZlGjRrpjMnGxoaS4uInudlPDYMJWi2bWtpfdKNGjQhduZLevXoSHx9P82bNGOkzkrpqNR49e9GrV29SUlLYunUL8P8Vh/6UACOM/ny+9NgM8hoN7tY3q2FmRnFREQkJCVzNymJ1WDhDhw7lpU6dyMvL07Zt3rwFJSUlJCQkaKeVlJSweXMMxcXFtGzVksTEBIqLirTz09LSyMjIoFXLVopu19PKYIJWXk0oPT2dxMQEFi5cgBHQ7vnnadioIRqNhu927SIjI4N9+/axZctm7bLW1tYMGjSID94PJi7uNKmpqSyYP4+vYmOpWbMmbm4vU6dOHYLfDyYlJYXExARmzwqie3d37WlTejwGc+r8YzUhC0tLHNs6Er5mDRYWFlhYWLD0k2Us+2QpixcvouOLL+Lj48u33+7ULj9jZhBhYauZMWMGRYWFvNSpE59+GoGRkRGmpqaEha9hyeJF+Pr68IypKb169WJ64DvVtLVPH70fIH6xYwdO/VI1RYarsi/p781gTp2SYZNBkxShd9BUKhXn4+Mfe8Xn4+O1X/9ITz9ZTUhShKwmJClCXqNJipBBkxQhgyYpQgZNUoQMmqQIGTRJETJokiJk0CRFyKBJipDVhCRl6Ps0i6wmJFWGrCYkKUJeo0mKMJhnBr7ctImtsVtJT0tDrVYz8LXXGDNmLMbG8m/FEBhE0NavjyR640amBwbSunUbfv89lZBly7iRd4N33n23uocnVYBBBO3rHTsIDHyHvv36AdCsWTMsLa1Y9+9/V/PIpIoyiKCZmppyNfuqzjRnZ2ecnZ21r3u4d2ducDAbN2wgISGBxo0b8/a0aXTu7KZts33bNjZtiubKlTQaPdeIiRP98fDwAO5WC2rSpCkJCec5efIUTZs2YeHH/+Kbb75mx/btmJqaMnbceEaMGKHEJj999H2bWh1FXnZ+841wce4kFi5YIE4cP65TzKWce/du4vXXBorTp38RN2/eFHv27BYvu3UWyUlJQggh9u3bJ7p1fUUcOLBfZGdnix07tgtXF2eRnZ0thLhbxKVXTw/x87Fj4saNG+KdwEDR9ZUu4rO1a0VRUZE4cGC/cO70krhy5XKVbf8/iUFcSfcfMIBPIyLIzc1lypQp9O7Vk9WrV3Hz5k2ddgMGDKR9+w6YmZnRu3cfPDw82HKv/oaHhwfbd3yNu3sP6tSpw2uvvY6lpSUJCee1y7/yyiu4uLrefbJ98GBu3brFmLFjsbCwwN29B/b29iQlJSu67U8Lgzh1ArRv34H27TtQUlLCfw4eJDw8jN9Tf2fpJ59o2zi0dNBZpk2btvyw9wft68zMTDZvjiElJYXUlFSuX7/OrVsa7Xx13bran01NTTEzM9N5V2tmZsatW7eexOY99QziiPZHNWvWpG+/fqxctZoDB/aTm5urnafR3NZpq9FotFWCtm37ikn+EyktLaV37z78a9EiGjZsqOjY/8n+9kHLzs6me7euXLx4UWd6SUkJxsbGOjXN7n/e9OzZs7RwaAHA7u+/Z9QoPyZPnoKHhwcNGzYkOzv7yW+ABBjAqdPOzo7nX3iBoJkzeCsggIYNG/FbcjKrV6/C07OvtkYtwJ49u2nZqhVOTk4cPHiAI0cOszF6EwDPNW7M0aNH6dq1K8YmJny6JhwhnzRUzN8+aACLFi1mTXg4IcuWkZubi52dHQMGDmT8+Ak67SZPmcpXsVv54P1gGjduwvLlK2jevDkAgdMDWbBgPr6+PqhUKsaOHUdiYmJ1bM4/k75vU6vj442KcO/eTZw8caLK+pOq1t/+Gk16OsigSYrQ+xqtvJrQ496TVtXVhA4c/E+V9SVVPVlNSFKErCYkKUJeo0mKkEGTFCGDJilCBk1ShAyapAgZNEkR/wej4dE2Y0zQGgAAAABJRU5ErkJggg=="}}]); |
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
const Watergirl = props => {
const data = useStaticQuery(graphql`
query {
placeholderImage: file(relativePath: { eq: "watergirl.jpg" }) {
childImageSharp {
fluid(maxWidth: 700, quality: 100) {
...GatsbyImageSharpFluid
}
}
}
}
`)
if (!data?.placeholderImage?.childImageSharp?.fluid) {
return <div>Picture not found</div>
}
return (
<div {...props}>
<Img fluid={data.placeholderImage.childImageSharp.fluid} />
</div>
)
}
export default Watergirl
|
const visit = require("unist-util-visit");
const toString = require("mdast-util-to-string");
const { breakLiquidTag } = require("./utils");
const getCodepen = require("./embeds/codepen");
const getYoutube = require("./embeds/youtube");
const getCodesandbox = require("./embeds/codesandbox");
const getGoogleslides = require("./embeds/google-slides");
const getJsfiddle = require("./embeds/jsfiddle");
const getSlides = require("./embeds/slides");
const getSoundcloud = require("./embeds/soundcloud");
const serviceMap = {
codepen: getCodepen,
youtube: getYoutube,
codesandbox: getCodesandbox,
'google-slides': getGoogleslides,
'jsfiddle': getJsfiddle,
'slides': getSlides,
'soundcloud': getSoundcloud,
}
// twitter is a work in progress, having issues because it returns a promise
// const getTwitter = require("./embeds/twitter");
const LIQUID_BLOCK_EXP = /{\%.*\%}/g;
module.exports = ({ markdownAST }, { customServiceMap = {}}) => {
visit(markdownAST, "paragraph", (node) => {
// Grab the innerText of the paragraph node
let text = toString(node);
// Test paragraph if it includes a liquid tag format
const matches = text.match(LIQUID_BLOCK_EXP);
// Only show embeds for liquid tags
if (matches !== null) {
let tagDetails = breakLiquidTag(matches[0]); // only interested in the first match
let { tagName, tagOptions } = tagDetails;
let embed;
// check the tagname to know which embed is to be used
const serviceFn = serviceMap[tagName] || customServiceMap[tagName]
if (serviceFn) {
embed = serviceFn(tagOptions);
}
if (embed === undefined) return;
node.type = "html";
node.children = undefined;
node.value = text.replace(LIQUID_BLOCK_EXP, embed);
}
});
return markdownAST;
};
|
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
.BundleAnalyzerPlugin;
module.exports = {
// Disable eslint for now
chainWebpack: config => {
config.module.rules.delete('eslint');
},
// compile templates on runtime
runtimeCompiler: true,
configureWebpack: {
// plugins: [new BundleAnalyzerPlugin()]
optimization: {
splitChunks: {
chunks: 'all'
}
}
},
css: {
loaderOptions: {
sass: {
prependData: `
@import "@/styles/setup/_mixins.scss";
`
}
}
},
devServer: {
watchOptions: {
poll: true
}
},
}
|
from pypy.jit.metainterp.optimizeopt.intutils import IntBound, IntUpperBound, \
IntLowerBound, IntUnbounded
from copy import copy
import sys
from pypy.rlib.rarithmetic import LONG_BIT
def bound(a,b):
if a is None and b is None:
return IntUnbounded()
elif a is None:
return IntUpperBound(b)
elif b is None:
return IntLowerBound(a)
else:
return IntBound(a,b)
def const(a):
return bound(a,a)
def some_bounds():
brd = [None] + range(-2, 3)
for lower in brd:
for upper in brd:
if lower is not None and upper is not None and lower > upper:
continue
yield (lower, upper, bound(lower, upper))
nbr = range(-5, 6)
def test_known():
for lower, upper, b in some_bounds():
inside = []
border = []
for n in nbr:
if (lower is None or n >= lower) and \
(upper is None or n <= upper):
if n == lower or n ==upper:
border.append(n)
else:
inside.append(n)
for n in nbr:
c = const(n)
if n in inside:
assert b.contains(n)
assert not b.known_lt(c)
assert not b.known_gt(c)
assert not b.known_le(c)
assert not b.known_ge(c)
elif n in border:
assert b.contains(n)
if n == upper:
assert b.known_le(const(upper))
else:
assert b.known_ge(const(lower))
else:
assert not b.contains(n)
some = (border + inside)[0]
if n < some:
assert b.known_gt(c)
else:
assert b.known_lt(c)
def test_make():
for _, _, b1 in some_bounds():
for _, _, b2 in some_bounds():
lt = IntUnbounded()
lt.make_lt(b1)
lt.make_lt(b2)
for n in nbr:
c = const(n)
if b1.known_le(c) or b2.known_le(c):
assert lt.known_lt(c)
else:
assert not lt.known_lt(c)
assert not lt.known_gt(c)
assert not lt.known_ge(c)
gt = IntUnbounded()
gt.make_gt(b1)
gt.make_gt(b2)
for n in nbr:
c = const(n)
if b1.known_ge(c) or b2.known_ge(c):
assert gt.known_gt(c)
else:
assert not gt.known_gt(c)
assert not gt.known_lt(c)
assert not gt.known_le(c)
le = IntUnbounded()
le.make_le(b1)
le.make_le(b2)
for n in nbr:
c = const(n)
if b1.known_le(c) or b2.known_le(c):
assert le.known_le(c)
else:
assert not le.known_le(c)
assert not le.known_gt(c)
assert not le.known_ge(c)
ge = IntUnbounded()
ge.make_ge(b1)
ge.make_ge(b2)
for n in nbr:
c = const(n)
if b1.known_ge(c) or b2.known_ge(c):
assert ge.known_ge(c)
else:
assert not ge.known_ge(c)
assert not ge.known_lt(c)
assert not ge.known_le(c)
gl = IntUnbounded()
gl.make_ge(b1)
gl.make_le(b2)
for n in nbr:
c = const(n)
if b1.known_ge(c):
assert gl.known_ge(c)
else:
assert not gl.known_ge(c)
assert not gl.known_gt(c)
if b2.known_le(c):
assert gl.known_le(c)
else:
assert not gl.known_le(c)
assert not gl.known_lt(c)
def test_intersect():
for _, _, b1 in some_bounds():
for _, _, b2 in some_bounds():
b = copy(b1)
b.intersect(b2)
for n in nbr:
if b1.contains(n) and b2.contains(n):
assert b.contains(n)
else:
assert not b.contains(n)
def test_add():
for _, _, b1 in some_bounds():
for n1 in nbr:
b2 = b1.add(n1)
for n2 in nbr:
c1 = const(n2)
c2 = const(n2 + n1)
if b1.known_le(c1):
assert b2.known_le(c2)
else:
assert not b2.known_le(c2)
if b1.known_ge(c1):
assert b2.known_ge(c2)
else:
assert not b2.known_ge(c2)
if b1.known_le(c1):
assert b2.known_le(c2)
else:
assert not b2.known_lt(c2)
if b1.known_lt(c1):
assert b2.known_lt(c2)
else:
assert not b2.known_lt(c2)
if b1.known_gt(c1):
assert b2.known_gt(c2)
else:
assert not b2.known_gt(c2)
def test_add_bound():
for _, _, b1 in some_bounds():
for _, _, b2 in some_bounds():
b3 = b1.add_bound(b2)
for n1 in nbr:
for n2 in nbr:
if b1.contains(n1) and b2.contains(n2):
assert b3.contains(n1 + n2)
a=bound(2, 4).add_bound(bound(1, 2))
assert not a.contains(2)
assert not a.contains(7)
def test_mul_bound():
for _, _, b1 in some_bounds():
for _, _, b2 in some_bounds():
b3 = b1.mul_bound(b2)
for n1 in nbr:
for n2 in nbr:
if b1.contains(n1) and b2.contains(n2):
assert b3.contains(n1 * n2)
a=bound(2, 4).mul_bound(bound(1, 2))
assert not a.contains(1)
assert not a.contains(9)
a=bound(-3, 2).mul_bound(bound(1, 2))
assert not a.contains(-7)
assert not a.contains(5)
assert a.contains(-6)
assert a.contains(4)
a=bound(-3, 2).mul(-1)
for i in range(-2,4):
assert a.contains(i)
assert not a.contains(4)
assert not a.contains(-3)
def test_shift_bound():
for _, _, b1 in some_bounds():
for _, _, b2 in some_bounds():
bleft = b1.lshift_bound(b2)
bright = b1.rshift_bound(b2)
for n1 in nbr:
for n2 in range(10):
if b1.contains(n1) and b2.contains(n2):
assert bleft.contains(n1 << n2)
assert bright.contains(n1 >> n2)
def test_shift_overflow():
b10 = IntBound(0, 10)
b100 = IntBound(0, 100)
bmax = IntBound(0, sys.maxint/2)
assert not b10.lshift_bound(b100).has_upper
assert not bmax.lshift_bound(b10).has_upper
assert b10.lshift_bound(b10).has_upper
for b in (b10, b100, bmax, IntBound(0, 0)):
for shift_count_bound in (IntBound(7, LONG_BIT), IntBound(-7, 7)):
#assert not b.lshift_bound(shift_count_bound).has_upper
assert not b.rshift_bound(shift_count_bound).has_upper
def test_div_bound():
for _, _, b1 in some_bounds():
for _, _, b2 in some_bounds():
b3 = b1.div_bound(b2)
for n1 in nbr:
for n2 in nbr:
if b1.contains(n1) and b2.contains(n2):
if n2 != 0:
assert b3.contains(n1 / n2)
a=bound(2, 4).div_bound(bound(1, 2))
assert not a.contains(0)
assert not a.contains(5)
a=bound(-3, 2).div_bound(bound(1, 2))
assert not a.contains(-4)
assert not a.contains(3)
assert a.contains(-3)
assert a.contains(0)
def test_sub_bound():
for _, _, b1 in some_bounds():
for _, _, b2 in some_bounds():
b3 = b1.sub_bound(b2)
for n1 in nbr:
for n2 in nbr:
if b1.contains(n1) and b2.contains(n2):
assert b3.contains(n1 - n2)
a=bound(2, 4).sub_bound(bound(1, 2))
assert not a.contains(-1)
assert not a.contains(4)
|
# vim:ts=4:sts=4:sw=4:expandtab
import logging
import threading
import time
class X(threading.local):
def __init__(self):
self._total = {}
self._begin = {}
self._count = {}
x = X()
def begin(name):
x._begin[name] = time.time()
def end(name):
if not name in x._begin:
raise Exception("Name not in _begin")
diff = time.time() - x._begin[name]
del x._begin[name]
x._total[name] = x._total.get(name, 0) + diff
x._count[name] = x._count.get(name, 0) + 1
logging.debug('End:\t%s\t%s\t%s\t%s', name, '{0:.3f}'.format(diff), '{0:.3f}'.format(x._total[name]), x._count[name])
def clear(name):
x._total = {}
self._count = {}
|
const Career = require('../models/careers'),
mongoose = require('mongoose'),
base_URL = "http://localhost:3000/api/careers/";
module.exports = {
read: async (req, res, next) => {
const careers = await Career.find({});
res.status(200).json({
success: true,
count: careers.length,
message: 'Listado completo de carreras',
carrersList: careers.map(carrer => {
return {
_id: carrer._id,
carrerName: career.careerName,
description: career.description,
dischargeProfile: career.dischargeProfile,
admissionProfile: career.admissionProfile,
workArea: career.workArea,
info: {
cycles: career.cycles,
years: career.years,
collegeDegree: career.collegeDegree
},
request: {
type: 'GET',
url: base_URL + career._id
}
};
})
});
},
create: async (req, res, next) => {
const newCareer = new Career(req.value.body);
newCareer._id = new mongoose.Types.ObjectId();
const career = await newCareer.save();
res.status(200).json({
succes: true,
message: 'Carrera creada satisfactoriamente',
career,
request: {
type: 'POST',
url: base_URL + career._id
}
});
},
getCareer: async (req, res, next) => {
const { careerId } = req.params;
const career = await Career.findById(careerId);
res.status(200).json({
success: true,
message: 'Recuperando información de la carrera',
career: career,
request: {
type: 'GET',
url: base_URL + careerId
}
});
},
edit: async (req, res, next) => {
const { careerId } = req.params;
const newCareer = req.body;
const result = await Career.findByIdAndUpdate(careerId, newCareer);
res.status(200).json({
success: true,
message: 'Carrera editada satisfactoriamente'
});
},
update: async (req, res, next) => {
const { careerId } = req.params;
const newCareer = req.body;
const result = await Career.findByIdAndUpdate(careerId, newCareer);
res.status(200).json({
success: true,
message: 'Carrera editada satisfactoriamente'
});
},
delete: async (req, res, next) => {
const { careerId } = req.params;
const result = await Career.findByIdAndRemove(careerId);
res.status(200).json({
success: true,
message: "Carrera borrada satisfactoriamente."
});
}
} |
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import app from './app.vue'
import routerObj from './router.js'
var vm = new Vue({
el: '#app',
render: c =>c(app),
router: routerObj
})
|
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Xception."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
from six.moves import xrange # pylint: disable=redefined-builtin
from tensor2tensor.models import common_hparams
from tensor2tensor.models import common_layers
from tensor2tensor.utils import registry
from tensor2tensor.utils import t2t_model
import tensorflow as tf
def residual_block(x, hparams):
"""A stack of convolution blocks with residual connection."""
k = (hparams.kernel_height, hparams.kernel_width)
dilations_and_kernels = [((1, 1), k) for _ in xrange(3)]
y = common_layers.subseparable_conv_block(
x,
hparams.hidden_size,
dilations_and_kernels,
padding="SAME",
separability=0,
name="residual_block")
x = common_layers.layer_norm(x + y, hparams.hidden_size, name="lnorm")
return tf.nn.dropout(x, 1.0 - hparams.dropout)
def xception_internal(inputs, hparams):
"""Xception body."""
with tf.variable_scope("xception"):
cur = inputs
for i in xrange(hparams.num_hidden_layers):
with tf.variable_scope("layer_%d" % i):
cur = residual_block(cur, hparams)
return cur
@registry.register_model
class Xception(t2t_model.T2TModel):
def model_fn_body(self, features):
return xception_internal(features["inputs"], self._hparams)
@registry.register_hparams
def xception_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 4096
hparams.hidden_size = 768
hparams.dropout = 0.2
hparams.symbol_dropout = 0.2
hparams.label_smoothing = 0.1
hparams.clip_grad_norm = 2.0
hparams.num_hidden_layers = 8
hparams.kernel_height = 3
hparams.kernel_width = 3
hparams.learning_rate_decay_scheme = "exp50k"
hparams.learning_rate = 0.05
hparams.learning_rate_warmup_steps = 3000
hparams.initializer_gain = 1.0
hparams.weight_decay = 3.0
hparams.num_sampled_classes = 0
hparams.sampling_method = "argmax"
hparams.optimizer_adam_epsilon = 1e-6
hparams.optimizer_adam_beta1 = 0.85
hparams.optimizer_adam_beta2 = 0.997
hparams.add_hparam("imagenet_use_2d", True)
return hparams
@registry.register_hparams
def xception_tiny():
hparams = xception_base()
hparams.batch_size = 1024
hparams.hidden_size = 128
hparams.num_hidden_layers = 4
hparams.learning_rate_decay_scheme = "none"
return hparams
|
import React from "react"
import { graphql, Link } from 'gatsby';
import Img from "gatsby-image"
import { DiscussionEmbed } from "disqus-react"
import Layout from "../components/layout"
import SEO from "../components/seo"
class PostTemplate extends React.Component {
render() {
const frontmatter = this.props.data.markdownRemark.frontmatter;
const { title, description, date, featuredImage } = frontmatter;
const post = this.props.data.markdownRemark;
const { previous, next, slug } = this.props.pageContext;
const disqusConfig = {
shortname: process.env.GATSBY_DISQUS_NAME,
config: { identifier: slug, title },
}
return (
<Layout title={title}>
<SEO title={title} description={description || post.excerpt} slug={slug}/>
<div className="container">
<div className="row">
<div className="col">
<div className="card border-light">
<div className="row">
<div className="col">
<Img fluid={featuredImage.childImageSharp.fluid} className="card-img-top"/>
<div className="card-img-overlay text-center d-flex flex-column justify-content-center">
<h1 className="d-none d-sm-block">
{post.frontmatter.title}
</h1>
<p><i className={`fab ${post.frontmatter.topicIcon} fa-3x`}></i></p>
</div>
</div>
</div>
<div className="card-body">
<h2 className="card-title d-block d-sm-none">{post.frontmatter.title}</h2>
<div className="card-subtitle mb-2 post-subtitle">
<h5>Luis Manuel Ramirez Vargas</h5>
<span>{date}</span>
{post.frontmatter.codeLink && (
<a href={post.frontmatter.codeLink} target="_blank" rel="noreferrer"><i className="fas fa-code"></i> Get the Code</a>
)}
</div>
<br/>
<div className="card-text" dangerouslySetInnerHTML={{ __html: post.html }} />
<div className="">
{previous && (
<Link to={previous.fields.slug} rel="prev" className="btn btn-primary">
← {previous.frontmatter.title}
</Link>
)}
{next && (
<Link to={next.fields.slug} rel="next" className="btn btn-primary float-right">
{next.frontmatter.title} →
</Link>
)}
</div>
<DiscussionEmbed {...disqusConfig} />
</div>
</div>
<br/>
</div>
</div>
</div>
</Layout>
)
}
}
export default PostTemplate
export const pageQuery = graphql`
query Posts($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
id
excerpt(pruneLength: 160)
html
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
description
topicIcon
codeLink
featuredImage {
childImageSharp {
fluid(maxWidth: 800, quality: 100) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
` |
# -*- coding: utf-8 -*-
"""The environment controller for MapWorld.
"""
from transitions import Machine
from IPython.display import display, Image
LIST_DIRECTIONS = ["n", "s", "e", "w"]
class MapWorld(object):
"""The MapWorld environment. State machine for one agent.
Tries to be general in what it returns when entering a new state.
This is specified by the list of node_descriptors, which are fields
in the dictionaries describing the nodes / states / rooms.
"""
def __init__(self, map_graph, node_descriptors):
self.machine = Machine(model=self,
states=[str(this_node['id']) for this_node in map_graph['nodes']],
transitions=map_graph['transitions'],
ignore_invalid_triggers=True,
initial=map_graph['initial'])
"""
Nodes is a list of dicts
{'base_type': 'indoor',
'type': 'v/veranda',
'target': False,
'instance': 'v/veranda/ADE_train_00019501.jpg',
'id': (2, 1)}
"""
self.nodes = map_graph['nodes']
self.node_descriptors = node_descriptors
def __get_node(self, node_id):
for node in self.nodes:
if str(node['id']) == node_id:
return node
def get_directions(self, node_id):
return [t for t in self.machine.get_triggers(node_id) if t in LIST_DIRECTIONS]
def describe_node(self, node_id):
"""
:return: tuple of (descriptors, directions)
"""
node = self.__get_node(node_id)
descriptors = dict([(descriptor, node[descriptor]) for descriptor in self.node_descriptors])
return descriptors, self.get_directions(node_id)
def try_transition(self, direction):
if direction not in self.machine.get_triggers(self.state):
return None, self.get_directions(self.state)
self.trigger(direction)
return self.describe_node(self.state)
class MapWorldWrapper(object):
"""A convenience wrapper around MapWorld, for use in notebook.
Can show images realising the instances, in which case the URL
is expected to be in "instance" in the node / state / room
dictionaries (via the node_descriptors mechanism of MapWorld).
"""
def __init__(self, map_, node_descriptor=['instance'], show_image=False,
image_prefix=None):
self.map = map_
self.mw = MapWorld(map_.to_fsa_def(), node_descriptor)
self.show_image = show_image
self.image_prefix = image_prefix
# need to describe the initial state as well
self.describe_state(self.mw.state, show_image=show_image)
def describe_state(self, state, show_image=False):
description, avail_dirs = self.mw.describe_node(state)
if show_image:
image_path = self.image_prefix + '/' + description['instance']
display(Image(filename=image_path, width=400, height=400))
else:
print(description)
self.print_dirs(avail_dirs)
def print_dirs(self, avail_dirs):
out_string = 'You can go: {}'.format(' '.join(avail_dirs))
print(out_string)
def upd(self, command):
if command == 'l': # look: repeat directions, but don't
# show image again
self.describe_state(self.mw.state, show_image=False)
elif command in 'n s e w'.split():
description, avail_dirs = self.mw.try_transition(command)
if description is None: # transition failed
print('Nothing happened.')
self.describe_state(self.mw.state, show_image=False)
else:
self.describe_state(self.mw.state, show_image=self.show_image)
def plt(self):
self.map.plot_graph(state=eval(self.mw.state))
|
/*! For license information please see 725e64e8.js.LICENSE.txt */
"use strict";(self.webpackChunkhome_assistant_frontend=self.webpackChunkhome_assistant_frontend||[]).push([[6992,2240],{67810:function(t,e,n){n.d(e,{o:function(){return l}});n(94604);var r=n(87156);function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o(t)}var l={properties:{scrollTarget:{type:HTMLElement,value:function(){return this._defaultScrollTarget}}},observers:["_scrollTargetChanged(scrollTarget, isAttached)"],_shouldHaveListener:!0,_scrollTargetChanged:function(t,e){if(this._oldScrollTarget&&(this._toggleScrollListener(!1,this._oldScrollTarget),this._oldScrollTarget=null),e)if("document"===t)this.scrollTarget=this._doc;else if("string"==typeof t){var n=this.domHost;this.scrollTarget=n&&n.$?n.$[t]:(0,r.vz)(this.ownerDocument).querySelector("#"+t)}else this._isValidScrollTarget()&&(this._oldScrollTarget=t,this._toggleScrollListener(this._shouldHaveListener,t))},_scrollHandler:function(){},get _defaultScrollTarget(){return this._doc},get _doc(){return this.ownerDocument.documentElement},get _scrollTop(){return this._isValidScrollTarget()?this.scrollTarget===this._doc?window.pageYOffset:this.scrollTarget.scrollTop:0},get _scrollLeft(){return this._isValidScrollTarget()?this.scrollTarget===this._doc?window.pageXOffset:this.scrollTarget.scrollLeft:0},set _scrollTop(t){this.scrollTarget===this._doc?window.scrollTo(window.pageXOffset,t):this._isValidScrollTarget()&&(this.scrollTarget.scrollTop=t)},set _scrollLeft(t){this.scrollTarget===this._doc?window.scrollTo(t,window.pageYOffset):this._isValidScrollTarget()&&(this.scrollTarget.scrollLeft=t)},scroll:function(t,e){var n;"object"===o(t)?(n=t.left,e=t.top):n=t,n=n||0,e=e||0,this.scrollTarget===this._doc?window.scrollTo(n,e):this._isValidScrollTarget()&&(this.scrollTarget.scrollLeft=n,this.scrollTarget.scrollTop=e)},get _scrollTargetWidth(){return this._isValidScrollTarget()?this.scrollTarget===this._doc?window.innerWidth:this.scrollTarget.offsetWidth:0},get _scrollTargetHeight(){return this._isValidScrollTarget()?this.scrollTarget===this._doc?window.innerHeight:this.scrollTarget.offsetHeight:0},_isValidScrollTarget:function(){return this.scrollTarget instanceof HTMLElement},_toggleScrollListener:function(t,e){var n=e===this._doc?window:e;t?this._boundScrollHandler||(this._boundScrollHandler=this._scrollHandler.bind(this),n.addEventListener("scroll",this._boundScrollHandler)):this._boundScrollHandler&&(n.removeEventListener("scroll",this._boundScrollHandler),this._boundScrollHandler=null)},toggleScrollListener:function(t){this._shouldHaveListener=t,this._toggleScrollListener(t,this.scrollTarget)}}},25782:function(t,e,n){n(94604),n(65660),n(47686),n(97968);var r,o,l,i=n(9672),s=n(50856),a=n(33760);(0,i.k)({_template:(0,s.d)(r||(o=['\n <style include="paper-item-shared-styles"></style>\n <style>\n :host {\n @apply --layout-horizontal;\n @apply --layout-center;\n @apply --paper-font-subhead;\n\n @apply --paper-item;\n @apply --paper-icon-item;\n }\n\n .content-icon {\n @apply --layout-horizontal;\n @apply --layout-center;\n\n width: var(--paper-item-icon-width, 56px);\n @apply --paper-item-icon;\n }\n </style>\n\n <div id="contentIcon" class="content-icon">\n <slot name="item-icon"></slot>\n </div>\n <slot></slot>\n'],l||(l=o.slice(0)),r=Object.freeze(Object.defineProperties(o,{raw:{value:Object.freeze(l)}})))),is:"paper-icon-item",behaviors:[a.U]})},33760:function(t,e,n){n.d(e,{U:function(){return l}});n(94604);var r=n(51644),o=n(26110),l=[r.P,o.a,{hostAttributes:{role:"option",tabindex:"0"}}]},89194:function(t,e,n){n(94604),n(65660),n(1656),n(47686);var r,o,l,i=n(9672),s=n(50856);(0,i.k)({_template:(0,s.d)(r||(o=["\n <style>\n :host {\n overflow: hidden; /* needed for text-overflow: ellipsis to work on ff */\n @apply --layout-vertical;\n @apply --layout-center-justified;\n @apply --layout-flex;\n }\n\n :host([two-line]) {\n min-height: var(--paper-item-body-two-line-min-height, 72px);\n }\n\n :host([three-line]) {\n min-height: var(--paper-item-body-three-line-min-height, 88px);\n }\n\n :host > ::slotted(*) {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n :host > ::slotted([secondary]) {\n @apply --paper-font-body1;\n\n color: var(--paper-item-body-secondary-color, var(--secondary-text-color));\n\n @apply --paper-item-body-secondary;\n }\n </style>\n\n <slot></slot>\n"],l||(l=o.slice(0)),r=Object.freeze(Object.defineProperties(o,{raw:{value:Object.freeze(l)}})))),is:"paper-item-body"})},97968:function(t,e,n){n(65660),n(15495),n(1656),n(47686);var r=document.createElement("template");r.setAttribute("style","display: none;"),r.innerHTML="<dom-module id=\"paper-item-shared-styles\">\n <template>\n <style>\n :host, .paper-item {\n display: block;\n position: relative;\n min-height: var(--paper-item-min-height, 48px);\n padding: 0px 16px;\n }\n\n .paper-item {\n @apply --paper-font-subhead;\n border:none;\n outline: none;\n background: white;\n width: 100%;\n text-align: left;\n }\n\n :host([hidden]), .paper-item[hidden] {\n display: none !important;\n }\n\n :host(.iron-selected), .paper-item.iron-selected {\n font-weight: var(--paper-item-selected-weight, bold);\n\n @apply --paper-item-selected;\n }\n\n :host([disabled]), .paper-item[disabled] {\n color: var(--paper-item-disabled-color, var(--disabled-text-color));\n\n @apply --paper-item-disabled;\n }\n\n :host(:focus), .paper-item:focus {\n position: relative;\n outline: 0;\n\n @apply --paper-item-focused;\n }\n\n :host(:focus):before, .paper-item:focus:before {\n @apply --layout-fit;\n\n background: currentColor;\n content: '';\n opacity: var(--dark-divider-opacity);\n pointer-events: none;\n\n @apply --paper-item-focused-before;\n }\n </style>\n </template>\n</dom-module>",document.head.appendChild(r.content)},1460:function(t,e,n){n.d(e,{l:function(){return y}});var r=n(15304),o=n(38941);function l(t){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l(t)}function i(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null==n)return;var r,o,l=[],i=!0,s=!1;try{for(n=n.call(t);!(i=(r=n.next()).done)&&(l.push(r.value),!e||l.length!==e);i=!0);}catch(a){s=!0,o=a}finally{try{i||null==n.return||n.return()}finally{if(s)throw o}}return l}(t,e)||function(t,e){if(!t)return;if("string"==typeof t)return s(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return s(t,e)}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function c(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function u(t,e){return u=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},u(t,e)}function p(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(h){return!1}}();return function(){var n,r=d(t);if(e){var o=d(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return f(this,n)}}function f(t,e){if(e&&("object"===l(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function d(t){return d=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},d(t)}var h={},y=(0,o.XM)(function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&u(t,e)}(s,t);var e,n,o,l=p(s);function s(){var t;return a(this,s),(t=l.apply(this,arguments)).ot=h,t}return e=s,n=[{key:"render",value:function(t,e){return e()}},{key:"update",value:function(t,e){var n=this,o=i(e,2),l=o[0],s=o[1];if(Array.isArray(l)){if(Array.isArray(this.ot)&&this.ot.length===l.length&&l.every((function(t,e){return t===n.ot[e]})))return r.Jb}else if(this.ot===l)return r.Jb;return this.ot=Array.isArray(l)?Array.from(l):l,this.render(l,s)}}],n&&c(e.prototype,n),o&&c(e,o),s}(o.Xe))}}]); |
window.addEventListener('load', () => {
svgIcons = document.querySelectorAll(".skills__data-img");
const storage = localStorage.getItem("selected-theme")
svgIcons.forEach(svgIcon => {
if (storage.toString() == "dark") {
svgIcon.classList.add("skills__data-img-dark")
}
else {
svgIcon.classList.remove("skills__data-img-dark")
}
})
})
const navMenu = document.getElementById('nav__menu'),
navToggle = document.getElementById('nav__toggle'),
navClose = document.getElementById('nav__close');
// Toggle Navbar
if (navToggle) {
navToggle.addEventListener('click', () => {
navMenu.classList.add('show-menu');
});
}
if (navClose) {
navClose.addEventListener('click', () => {
navMenu.classList.remove('show-menu');
});
}
// Close Navbar After Clicking On A Link
const navLink = document.querySelectorAll('.nav__link');
navLink.forEach(n => n.addEventListener('click', () => {
const navMenu = document.getElementById('nav__menu');
navMenu.classList.remove('show-menu');
}));
// Accordion Skills
const skillsContent = document.getElementsByClassName('skills__content'),
skillsHeader = document.querySelectorAll('.skills__header');
function toggleSkills() {
let itemClass = this.parentNode.className;
for (i = 0; i < skillsContent.length; i++) {
skillsContent[i].className = 'skills__content skills__close';
}
if (itemClass === 'skills__content skills__close') {
this.parentNode.className = 'skills__content skills__open'
}
}
skillsHeader.forEach((el) => {
el.addEventListener('click', toggleSkills)
});
// Qualification Tabs
const tabs = document.querySelectorAll('[data-target]'),
tabContents = document.querySelectorAll('[data-content]');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const target = document.querySelector(tab.dataset.target);
tabContents.forEach(tabContent => {
tabContent.classList.remove('qualification__active');
});
target.classList.add('qualification__active');
tabs.forEach(tab => {
tab.classList.remove('qualification__active');
});
tab.classList.add('qualification__active')
});
});
// Services Modal
const modalViews = document.querySelectorAll('.services__modal'),
modalBtns = document.querySelectorAll('.services__button'),
modalCloses = document.querySelectorAll('.services__modal-close');
let modal = function (modalClick) {
modalViews[modalClick].classList.add('active-modal')
}
modalBtns.forEach((modalBtn, i) => {
modalBtn.addEventListener('click', () => {
modal(i)
});
});
modalCloses.forEach((modalClose) => {
modalClose.addEventListener('click', () => {
modalViews.forEach(modalView => {
modalView.classList.remove('active-modal')
});
});
});
// Scroll Sections Active Link
const sections = document.querySelectorAll('section[id]')
function scrollActive() {
const scrollY = window.pageYOffset
sections.forEach(current => {
const sectionHeight = current.offsetHeight
const sectionTop = current.offsetTop - 50;
sectionId = current.getAttribute('id')
if (scrollY > sectionTop && scrollY <= sectionTop + sectionHeight) {
document.querySelector('.nav__menu a[href*=' + sectionId + ']').classList.add('active-link')
} else {
document.querySelector('.nav__menu a[href*=' + sectionId + ']').classList.remove('active-link')
}
})
}
window.addEventListener('scroll', scrollActive)
// Change Background Header
function scrollHeader() {
const nav = document.getElementById('header')
if (this.scrollY >= 80) nav.classList.add('scroll-header');
else nav.classList.remove('scroll-header')
}
window.addEventListener('scroll', scrollHeader)
// Show Scroll Top
function scrollTop() {
const scrollTop = document.getElementById('scroll-top');
if (this.scrollY >= 560) {
if (scrollTop) {
scrollTop.classList.add('show-scroll');
}
} else {
if (scrollTop) {
scrollTop.classList.remove('show-scroll')
}
}
}
window.addEventListener('scroll', scrollTop)
// Dark Theme
const themeButton = document.getElementById('theme-button')
const darkTheme = 'dark-theme'
const iconTheme = 'uil-sun'
const selectedTheme = localStorage.getItem('selected-theme')
const selectedIcon = localStorage.getItem('selected-icon')
const getCurrentTheme = () => document.body.classList.contains(darkTheme) ? 'dark' : 'light'
const getCurrentIcon = () => themeButton.classList.contains(iconTheme) ? 'uil-moon' : 'uil-sun'
if (selectedTheme) {
document.body.classList[selectedTheme === 'dark' ? 'add' : 'remove'](darkTheme)
themeButton.classList[selectedIcon === 'uil-moon' ? 'add' : 'remove'](iconTheme)
}
themeButton.addEventListener('click', () => {
svgIcons = document.querySelectorAll(".skills__data-img");
svgIcons.forEach(svgIcon => {
svgIcon.classList.toggle("skills__data-img-dark")
});
document.body.classList.toggle(darkTheme)
themeButton.classList.toggle(iconTheme)
localStorage.setItem('selected-theme', getCurrentTheme())
localStorage.setItem('selected-icon', getCurrentIcon())
}) |
//---------------------------------------------------------------------
// Favorites panel
//---------------------------------------------------------------------
// Copyright (C) 2007-2011 The NOC Project
// See LICENSE for details
//---------------------------------------------------------------------
console.debug("Defining NOC.main.desktop.Favorites");
Ext.define("NOC.main.desktop.Favorites", {
extend: "Ext.Panel",
title: __("Favorites"),
iconCls: "icon_star",
initComponent: function() {
var me = this;
me.store = Ext.create("Ext.data.Store", {
fields: ["app", "title", "launch_info"],
data: []
});
me.grid = Ext.create("Ext.grid.Panel", {
columns: [
{
xtype: "actioncolumn",
width: 20,
items: [
{
iconCls: "icon_star",
scope: me
}
]
},
{
dataIndex: "title",
flex: 1
}
],
hideHeaders: true,
store: me.store,
listeners: {
scope: me,
itemclick: me.onClick
}
});
Ext.apply(me, {
items: [me.grid]
});
me.callParent();
},
//
afterRender: function() {
var me = this;
me.callParent();
me.loadStore();
},
// Load data to store
loadStore: function() {
var me = this;
Ext.Ajax.request({
url: "/main/desktop/favapps/",
scope: me,
success: function(result) {
var me = this,
data = Ext.decode(result.responseText);
me.store.loadData(data);
}
});
},
// Favorite app clicked
onClick: function(grid, record, item) {
var me = this,
li = record.get("launch_info");
NOC.run(li.class, li.title, li.params);
}
});
|
////////////////////
// if key and value are identical we condense to single word
////////////////////
const color = 'red';
// const car = {
// color: color
// };
const car = {
color
};
console.log(car);
////////////////////
// default function arguments
////////////////////
function makeCake (recipe, type = 'Strawberry') {
return `Using ${recipe} for ${type} cake`;
}
console.log(makeCake('My Recipe', 'Chocolate'));
// Using My Recipe for Chocolate cake
console.log(makeCake('My Recipe'));
// Using My Recipe for Strawberry cake |
module.exports = {
// 'primary-color': '#1DA57A',
};
|
from runtime_data.heap.class_member import ClassMember
from runtime_data.heap.utils import get_default_value, is_primitive
class ClassField(ClassMember):
def __init__(self, clazz, class_file_member):
super().__init__(clazz, class_file_member)
self.val = class_file_member.get_value()
if self.val is None:
self.val = get_default_value(self.descriptor)
def is_primitive(self) -> bool:
return is_primitive(self.descriptor)
@staticmethod
def new_fields(clazz, class_file_members):
fields = []
for member in class_file_members:
fields.append(ClassField(clazz, member))
return fields
|
/*
* Copyright 2018 dialog LLC <[email protected]>
* @flow
*/
export type AttachmentFile = Blob | File;
export type Attachment = {
file: AttachmentFile,
isDocument: boolean
};
export type AttachmentModalProps = {
className?: string,
current: number,
sendAsFile: boolean,
attachments: Attachment[],
onClose: () => mixed,
onSend: (attachments: Attachment[]) => mixed,
onSendAll: (attachments: Attachment[]) => mixed,
onCurrentChange: (current: number) => mixed,
onSendAsFileChange: (sendAsFIle: boolean) => mixed
};
export type AttachmentPreviewProps = {
className?: string,
fileClassName?: string,
imageClassName?: string,
file: AttachmentFile
};
export type AttachmentMetaProps = {
className?: string,
attachment: Attachment,
sendAsFile: boolean,
onSendAsFileChange: (sendAsFIle: boolean) => mixed
};
|
document.addEventListener('DOMContentLoaded', (event) => {
// Toggle mobile menu
const jlbestblog_toggleMobileMenu = () => {
const mobileMenuIcon = document.getElementById("mobile-menu-icon");
const navigation = document.getElementById("navigation");
if (mobileMenuIcon) {
mobileMenuIcon.addEventListener("mousedown", function() {
navigation.classList.toggle("isVisible");
}, true);
mobileMenuIcon.addEventListener("keydown", function(e) {
const code = e.which;
if ( code === 13 ) {
navigation.classList.toggle("isVisible");
}
}, true);
}
}
jlbestblog_toggleMobileMenu();
// Toggle mobile top menu
const jlbestblog_toggleMobileTopMenu = () => {
const mobileMenuIcon = document.getElementById("mobile-top-menu-container");
const navigation = document.querySelector(".mobile-top-menu-class");
if (mobileMenuIcon) {
mobileMenuIcon.addEventListener("mousedown", function() {
navigation.classList.toggle("isVisible");
}, true);
mobileMenuIcon.addEventListener("keydown", function(e) {
const code = e.which;
if ( code === 13 ) {
navigation.classList.toggle("isVisible");
}
}, true);
}
}
jlbestblog_toggleMobileTopMenu();
// Actions made when tabbing content
function jlbestblog_tab_mobile_menu() {
const navigation = document.getElementById("navigation");
const all_mobile_menu_tabs = jlbestblog_get_mobile_menu_tabs( navigation, document.getElementById('mobile-menu-icon') );
jlbestblog_set_tab_mobile( all_mobile_menu_tabs );
}
jlbestblog_tab_mobile_menu();
function jlbestblog_tab_mobile_top_menu() {
const navigation = document.querySelector(".mobile-top-menu-class");
if (navigation !== null) {
const all_mobile_menu_tabs = jlbestblog_get_mobile_menu_tabs( navigation, document.getElementById("mobile-top-menu-container") );
jlbestblog_set_tab_mobile( all_mobile_menu_tabs );
}
}
jlbestblog_tab_mobile_top_menu();
function jlbestblog_get_mobile_menu_tabs( navigation, menu_button ) {
const mobile_navigation_tabs = navigation.querySelectorAll('button, [href], input, select, textarea');
const mobile_navigation_tabs_array = Array.from(mobile_navigation_tabs);
const all_mobile_menu_tabs = [menu_button, ...mobile_navigation_tabs_array];
return all_mobile_menu_tabs;
}
function jlbestblog_set_tab_mobile( all_mobile_menu_tabs ) {
const content = document.querySelector(".main-container");
let is_tab_key_pressed = false;
let is_shift_key_pressed = false;
content.addEventListener("keydown", function(e) {
const code = e.which;
if (code === 9) {
is_tab_key_pressed = true;
}
if (code === 16) {
is_shift_key_pressed = true;
}
}, true);
content.addEventListener("keyup", function(e) {
const code = e.which;
if (code === 9) {
is_tab_key_pressed = false;
}
if (code === 16) {
is_shift_key_pressed = false;
}
}, true);
all_mobile_menu_tabs[0].addEventListener('blur', function() {
if ( is_tab_key_pressed && is_shift_key_pressed ) {
all_mobile_menu_tabs[all_mobile_menu_tabs.length-1].focus();
}
});
all_mobile_menu_tabs[all_mobile_menu_tabs.length-1].addEventListener('blur', function() {
if ( is_tab_key_pressed && !is_shift_key_pressed ) {
all_mobile_menu_tabs[0].focus();
}
});
}
});
|
// All the options
const OPTIONS = {
name : "",
icon : "",
message : "",
isVCE : false,
isVE : false,
isCED : false,
isCE : false,
isView : false,
isAdd : false,
isCreate : false,
isCopy : false,
isEdit : false,
isDelete : false,
isImport : false,
isExport : false,
isTab : false,
isCollapse : false,
isFilter : false,
isEmail : false,
isCampaign : false,
isLogin : false,
isSelect : false,
isUpload : false,
isManage : false,
};
// All the Actions
const ACTIONS = {
"NULL" : { ...OPTIONS },
"VIEW" : {
...OPTIONS,
icon : "view",
message : "GENERAL_VIEW",
isView : true,
isVCE : true,
isVE : true,
},
"ADD" : {
...OPTIONS,
icon : "create",
message : "GENERAL_ADD",
isAdd : true,
isVCE : true,
isCED : true,
isCE : true,
},
"CREATE" : {
...OPTIONS,
icon : "create",
message : "GENERAL_CREATE",
isCreate : true,
isVCE : true,
isCED : true,
isCE : true,
},
"COPY" : {
...OPTIONS,
icon : "copy",
message : "GENERAL_COPY",
isCopy : true,
},
"EDIT" : {
...OPTIONS,
icon : "edit",
message : "GENERAL_EDIT",
isEdit : true,
isVCE : true,
isVE : true,
isCED : true,
isCE : true,
},
"DELETE" : {
...OPTIONS,
icon : "delete",
message : "GENERAL_DELETE",
isDelete : true,
isCED : true,
},
"IMPORT" : {
...OPTIONS,
icon : "import",
message : "GENERAL_IMPORT",
isImport : true,
},
"EXPORT" : {
...OPTIONS,
icon : "export",
message : "GENERAL_EXPORT",
isExport : true,
},
"TAB" : {
...OPTIONS,
icon : "tab",
isTab : true,
},
"COLLAPSE" : {
...OPTIONS,
icon : "open",
isCollapse : true,
},
"FILTER" : {
...OPTIONS,
icon : "filter",
message : "GENERAL_FILTER",
isFilter : true,
},
"EMAIL" : {
...OPTIONS,
icon : "email",
message : "GENERAL_SEND_EMAIL",
isEmail : true,
},
"CAMPAIGN" : {
...OPTIONS,
icon : "add",
message : "GENERAL_SEND_CAMPAIGN",
isCampaign : true,
},
"LOGIN" : {
...OPTIONS,
icon : "login",
message : "GENERAL_LOGIN_AS",
isLogin : true,
},
"SELECT" : {
...OPTIONS,
icon : "select",
message : "GENERAL_SELECT",
isSelect : true,
},
"UPLOAD" : {
...OPTIONS,
icon : "create",
message : "GENERAL_UPLOAD",
isUpload : true,
},
"MANAGE" : {
...OPTIONS,
icon : "settings",
message : "GENERAL_MANAGE",
isManage : true,
},
};
/**
* Initializes the Actions
* @param {Object[]} actions
* @returns {Void}
*/
function init(actions) {
for (const { name, icon, message } of actions) {
const isName = `is${name[0]}${name.toLocaleLowerCase().substr(1)}`;
for (const action of Object.values(ACTIONS)) {
action[isName] = false;
}
ACTIONS[name] = create(name, icon, message);
OPTIONS[isName] = false;
}
}
/**
* Creates a New Action
* @param {String} name
* @param {String=} icon
* @param {String=} message
* @returns {Object}
*/
function create(name, icon = "", message = "") {
const isName = `is${name[0]}${name.toLocaleLowerCase().substr(1)}`;
return {
...OPTIONS,
name, icon, message,
[isName] : true,
};
}
/**
* Returns the Action with the given name
* @param {String=} name
* @returns {Object}
*/
function get(name) {
if (!name) {
return ACTIONS.NULL;
}
if (ACTIONS[name]) {
return ACTIONS[name];
}
return create(name);
}
// The public API
export default {
init,
create,
get,
};
|
const assert = require('assert')
const ListRepository = require('./listRepository')
describe.skip('List Repository', () => {
it('Should save a new list', async () => {
// Given
const repository = new ListRepository()
// When
const ret = await repository.save({ id: 1, name: 'List 1' })
// Then
assert.deepStrictEqual("List 1", ret.ok.name)
assert.deepStrictEqual(1, ret.ok.id)
})
it('Should get all lists', async () => {
// Given
const repository = new ListRepository()
await repository.save({ id: 1, name: 'List 1' })
await repository.save({ id: 2, name: 'List 2' })
// When
const ret = await repository.getAll()
// Then
assert.deepStrictEqual(2, ret.ok.length)
})
it('Should get lists by id', async () => {
// Given
const repository = new ListRepository()
await repository.save({ id: 1, name: 'List 1' })
await repository.save({ id: 2, name: 'List 2' })
// When
const ret = await repository.getByIDs([1])
// Then
assert.deepStrictEqual(1, ret.ok.length)
assert.deepStrictEqual("List 1", ret.ok[0].name)
assert.deepStrictEqual(1, ret.ok[0].id)
})
it('Should delete a list by id', async () => {
// Given
const repository = new ListRepository()
await repository.save({ id: 1, name: 'List 1' })
await repository.save({ id: 2, name: 'List 2' })
// When
const ret = await repository.deleteByIDs([1])
// Then
assert.deepStrictEqual(1, ret.ok.length)
})
})
|
;(function(){
// Initialize Firebase
var config = {
apiKey: "AIzaSyBk3x6pvOi8sfsfCYTc9JHU_6oC-RW7Q9U",
authDomain: "chat-1-1-cf-25112016.firebaseapp.com",
databaseURL: "https://chat-1-1-cf-25112016.firebaseio.com",
storageBucket: "chat-1-1-cf-25112016.appspot.com",
messagingSenderId: "83532153713"
};
firebase.initializeApp(config);
var database = firebase.database();//Crear bd no sql
var loginBtn = document.getElementById('start-login') //obtiene el llamado de el boton
var user = null;
var usuariosConectado = null
var conectadoKey = ""
var rooms
loginBtn.addEventListener("click", googleLogin)
window.addEventListener("unload", unlogin)
function googleLogin(){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider)
.then(function(result){
user = result.user
console.log(user)
$("#login").fadeOut()
initApp()
})
}
function initApp(){
usuariosConectado = database.ref("/connected")
rooms = database.ref("/rooms")
login(user.uid, user.displayName || user.email)
usuariosConectado.on("child_added", addUser)
usuariosConectado.on("child_removed", removeUser)
rooms.on("child_added", newRoom)
}
function login(uid,name){
var conectado = usuariosConectado.push({
uid: uid,
name: name
})
conectadokey = conectado.key
}
function unlogin(){
database.ref("/connected/"+conectadokey).remove()
}
function addUser(data){
if(data.val().uid == user.uid) return
var friend_id = data.val().uid
var $li = $("<li>").addClass("collection-item")
.html(data.val().name)
.attr("id",friend_id )
.appendTo("#users")
$li.on("click", function(){
var room = rooms.push({
creator: user.uid,
friend: friend_id
})
//new Chat(room.key, user, "chats", database)
});
}
function removeUser(data){
$("#"+data.val().uid).slideUp('fast', function(){
$(this).remove()
})
}
function newRoom(data){
if(data.val().friend == user.uid){
new Chat(data.key, user, "chats", database)
}
if(data.val().creator == user.uid){
new Chat(data.key, user, "chats", database)
}
}
})() |
/**
* index.js
* @author @shawngettler
*
* Main.
*/
import Project from "./Project.js";
import JNSEBinaryData from "./io/JNSEBinaryData.js";
import ZipArchive from "./io/ZipArchive.js";
import Editor from "./ui/Editor.js";
import Toolbar from "./ui/Toolbar.js";
/*
* Run app.
*/
(function() {
let project = new Project();
// editor interface
let editor = new Editor(project.course, project.refData);
editor.canvas.addEventListener("courseupdate", (e) => { updateToolbar(); });
// side bar
let toolbar = new Toolbar("JNSE Course Designer");
let projectGroup = toolbar.addControlGroup("PROJECT");
let projectButtons = toolbar.addButtonGroup(projectGroup);
let projectOpen = toolbar.addButton(projectButtons, "Open Project", (e) => { openProject(); });
let projectSave = toolbar.addButton(projectButtons, "Save Project", (e) => { saveProject(); });
let projectButtonBreak = toolbar.addButtonBreak(projectButtons);
let projectImport = toolbar.addButton(projectButtons, "Import Game Data", importGameData);
let projectExport = toolbar.addButton(projectButtons, "Export Game Data", exportGameData);
let projectImage = toolbar.addButton(projectButtons, "Add Image Reference", (e) => { openRef(); });
let projectDEM = toolbar.addButton(projectButtons, "Add Height Reference", null);
projectDEM.disabled = true;
let projectFilenameInput = toolbar.addTextField(projectGroup, "Game Data Name", 8, (e) => { project.name = e.target.value; });
let courseGroup = toolbar.addControlGroup("COURSE");
let courseNameInput = toolbar.addTextField(courseGroup, "Course Name", 21, (e) => { project.course.name = e.target.value; });
let courseQuoteInput = toolbar.addTextArea(courseGroup, "Course Quote", 120, (e) => { project.course.plot.quote = e.target.value; });
let courseBoundsInput = toolbar.addDropdown(courseGroup, "Out of Bounds", ["Out of Bounds", "Heavy Rough"], (e) => { project.course.outOfBounds = parseInt(e.target.value); });
let courseWindSpeedInput = toolbar.addDropdown(courseGroup, "Wind Speed", ["None", "Gentle", "Medium", "Strong"], (e) => { project.course.plot.windSpeed = parseInt(e.target.value); });
let courseWindDirInput = toolbar.addDropdown(courseGroup, "Wind Direction", ["n/a", "North", "Northeast", "East", "Southeast", "South", "Southwest", "West", "Northwest"], (e) => { project.course.plot.windDir = parseInt(e.target.value); });
let coursePlot = toolbar.addPlot(courseGroup, editor.plotImages[18], (e) => { editor.plotAlpha[18] = e.target.value/100; editor.update(); });
let coursePlotButtons = toolbar.addButtonGroup(courseGroup);
let courseShowPlot = toolbar.addButton(coursePlotButtons, "Show Plot", (e) => { editor.showPlot(18); });
let courseEditPlot = toolbar.addButton(coursePlotButtons, "Edit Plot", (e) => { editor.editPlot(18); });
let courseMovePlot = toolbar.addButton(coursePlotButtons, "Move Plot", (e) => { editor.movePlot(18); });
let holeGroup = [];
let holeParInput = [];
let holeLengthInput = [];
let holeRoutingButtons = [];
let holeCreateRouting = [];
let holeEditRouting = [];
let holeDeleteRouting = [];
let holeQuoteInput = [];
let holeWallInput = [];
let holePlot = [];
let holePlotButtons = [];
let holeShowPlot = [];
let holeEditPlot = [];
let holeMovePlot = [];
for(let i = 0; i < 18; i++) {
holeGroup[i] = toolbar.addControlGroup("HOLE "+(i+1));
holeParInput[i] = toolbar.addDropdown(holeGroup[i], "Par", ["3", "4", "5"], (e) => { project.course.holeData[i].par = e.target.value + 3; });
holeLengthInput[i] = toolbar.addText(holeGroup[i], "Length");
holeRoutingButtons[i] = toolbar.addButtonGroup(holeGroup[i]);
holeCreateRouting[i] = toolbar.addButton(holeRoutingButtons[i], "Create Routing", (e) => { editor.createRouting(i); });
holeEditRouting[i] = toolbar.addButton(holeRoutingButtons[i], "Edit Routing", (e) => { editor.editRouting(i); });
holeDeleteRouting[i] = toolbar.addButton(holeRoutingButtons[i], "Delete Routing", (e) => { editor.deleteRouting(i); });
holeQuoteInput[i] = toolbar.addTextArea(holeGroup[i], "Hole Quote", 120, (e) => { project.course.holes[i].quote = e.target.value; });
holeWallInput[i] = toolbar.addDropdown(holeGroup[i], "Wall Style", ["No Walls", "Railroad Ties", "Stone Walls"], (e) => { project.course.outofbounds = parseInt(e.target.value); });
holePlot[i] = toolbar.addPlot(holeGroup[i], editor.plotImages[i], (e) => { editor.plotAlpha[i] = e.target.value/100; editor.update(); });
holePlotButtons[i] = toolbar.addButtonGroup(holeGroup[i]);
holeShowPlot[i] = toolbar.addButton(holePlotButtons[i], "Show Plot", (e) => { editor.showPlot(i); });
holeEditPlot[i] = toolbar.addButton(holePlotButtons[i], "Edit Plot", (e) => { editor.editPlot(i); });
holeMovePlot[i] = toolbar.addButton(holePlotButtons[i], "Move Plot", (e) => { editor.movePlot(i); });
}
let refGroup = [];
let refScaleInput = [];
let refImageButtons = [];
let refShowImage = [];
let refMoveImage = [];
updateToolbar();
// update fields
function updateToolbar() {
projectFilenameInput.value = project.name;
courseNameInput.value = project.course.name;
courseQuoteInput.value = project.course.plot.quote;
courseBoundsInput.value = project.course.outOfBounds;
courseWindSpeedInput.value = project.course.plot.windSpeed;
courseWindDirInput.value = project.course.plot.windDir;
for(let i = 0; i < 18; i++) {
holeParInput[i].value = project.course.holeData[i].par - 3;
holeLengthInput[i].value = Math.round(project.course.getHoleLength(i));
holeQuoteInput[i].value = project.course.holes[i].quote;
holeWallInput[i].value = project.course.holes[i].wallStyle;
if(project.course.holeData[i].v.length) {
holeCreateRouting[i].disabled = true;
holeEditRouting[i].disabled = false;
holeDeleteRouting[i].disabled = false;
holeShowPlot[i].disabled = false;
holeEditPlot[i].disabled = false;
holeMovePlot[i].disabled = false;
} else {
holeCreateRouting[i].disabled = false;
holeEditRouting[i].disabled = true;
holeDeleteRouting[i].disabled = true;
holeShowPlot[i].disabled = true;
holeEditPlot[i].disabled = true;
holeMovePlot[i].disabled = true;
}
}
}
function updateReferences() {
for(let g of refGroup) {
toolbar.removeControlGroup(g);
}
refGroup = [];
for(let i = 0; i < project.refData.images.length; i++) {
let r = project.refData.images[i];
refGroup[i] = toolbar.addControlGroup("IMAGE "+r.title);
refScaleInput[i] = toolbar.addTextField(refGroup[i], "Image Scale (ft/px)", 21, (e) => { r.s = e.target.value; editor.update(); });
refScaleInput[i].value = r.s;
refImageButtons[i] = toolbar.addButtonGroup(refGroup[i]);
refShowImage[i] = toolbar.addButton(refImageButtons[i], "Show Ref Image", (e) => { editor.showRef(r); });
refMoveImage[i] = toolbar.addButton(refImageButtons[i], "Move Ref Image", (e) => { editor.moveRef(r); });
}
}
// file operations
function openProject() {
let inputElement = document.createElement("input");
inputElement.type = "file";
inputElement.addEventListener("change", (e) => {
const reader = new FileReader();
reader.addEventListener("load", (e) => {
project.restoreJSON(e.target.result);
for(let i = 0; i < 19; i++) {
editor.renderPlot(i);
}
editor.update();
updateToolbar();
updateReferences();
});
reader.readAsText(inputElement.files[0]);
});
inputElement.click();
}
function saveProject() {
let anchorElement = document.createElement("a");
anchorElement.href = project.saveJSON();
anchorElement.download = project.name+".json";
anchorElement.click();
}
function importGameData() {
let inputElement = document.createElement("input");
inputElement.type = "file";
inputElement.multiple = "true";
inputElement.addEventListener("change", (e) => {
for(let f of inputElement.files) {
let name = f.name.slice(0, f.name.lastIndexOf(".")).toUpperCase();
let ext = f.name.slice(f.name.lastIndexOf(".") + 1).toUpperCase();
const reader = new FileReader();
reader.addEventListener("load", (e) => {
project.name = name;
let bytes = new Uint8Array(e.target.result);
if(ext === "PRC") {
project.course.loadData(bytes);
for(let i = 0; i < 19; i++) {
editor.renderPlot(i);
}
editor.update();
}
if(ext === "LDM") {
project.course.plot.loadData(JNSEBinaryData.expandFile(bytes));
editor.renderPlot(18);
editor.update();
}
for(let i = 0; i < 18; i++) {
if(ext === "H" + (i+1)) {
project.course.holes[i].loadData(JNSEBinaryData.expandFile(bytes));
editor.renderPlot(i);
editor.update();
}
}
if(ext === "DZV") {
project.course.panorama.loadData(JNSEBinaryData.expandFile(bytes));
}
// if(ext === "OMM") {
// }
// if(ext === "MIN") {
// }
updateToolbar();
});
reader.readAsArrayBuffer(f);
}
});
inputElement.click();
}
function exportGameData() {
let files = [];
files.push({ name: project.name+".PRC", data: project.course.saveData(), date: new Date() });
files.push({ name: project.name+".LDM", data: JNSEBinaryData.compressFile(project.course.plot.saveData()), date: new Date() });
for(let i = 0; i < 18; i++) {
files.push({ name: project.name+".H"+(i+1), data: JNSEBinaryData.compressFile(project.course.holes[i].saveData()), date: new Date() });
}
files.push({ name: project.name+".DZV", data: JNSEBinaryData.compressFile(project.course.panorama.saveData()), date: new Date() });
// files.push({ name: project.name+".OMM", data: null, date: new Date() });
// files.push({ name: project.name+".MIN", data: null, date: new Date() });
let zip = new Blob([ZipArchive.createArchive(files)], { type: "application/octet-stream" });
let anchorElement = document.createElement("a");
anchorElement.href = window.URL.createObjectURL(zip);
anchorElement.download = project.name+".zip";
anchorElement.click();
}
function openRef() {
let inputElement = document.createElement("input");
inputElement.type = "file";
inputElement.addEventListener("change", (e) => {
const reader = new FileReader();
reader.addEventListener("load", (e) => {
let img = new Image();
img.src = e.target.result;
project.addImageReference(img, inputElement.files[0].name);
editor.update();
updateToolbar();
updateReferences();
});
reader.readAsDataURL(inputElement.files[0]);
});
inputElement.click();
}
})();
|
#!/usr/bin/env python3
# Copyright (c) 2014-2021 Daniel Kraft
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# RPC tests for the handling of names in the wallet.
from test_framework.names import NameTestFramework, val
from test_framework.util import *
from decimal import Decimal
nameFee = Decimal ("0.01")
txFee = Decimal ("0.001")
initialBalance = Decimal ("2500")
zero = Decimal ("0")
class NameWalletTest (NameTestFramework):
spentA = zero
spentB = zero
def set_test_params (self):
self.setup_clean_chain = True
self.setup_name_test ([["-paytxfee=%s" % txFee]] * 2)
def generateToOther (self, ind, n):
"""
Generates n new blocks with test node ind, paying to an address in neither
test wallet. This ensures that we do not mess up the balances.
"""
addr = "cmUcickA9iRQpTTnwoXrrxCpb73ggpQiAn"
self.generatetoaddress (self.nodes[ind], n, addr)
def getFee (self, ind, txid, extra=zero):
"""
Returns and checks the fee of a transaction. There may be an additional
fee for the locked coin, and the paytxfee times the tx size.
The tx size is queried from the node with the given index by the txid.
"""
info = self.nodes[ind].gettransaction (txid)
totalFee = -info['fee']
assert totalFee >= extra
absFee = totalFee - extra
size = count_bytes (info['hex'])
assert_fee_amount (absFee, size, txFee)
return totalFee
def checkBalance (self, ind, spent):
"""
Checks the balance of the node with index ind. It should be
the initial balance minus "spent".
"""
bal = self.nodes[ind].getbalance ()
assert_equal (bal, initialBalance - spent)
assert_equal (self.nodes[ind].getbalance (), bal)
def checkBalances (self, spentA=zero, spentB=zero):
"""
Checks balances of the two test nodes. The expected spent amounts
for them are stored in self.spentA and self.spentB, and increased
prior to the check by the arguments passed in.
"""
self.spentA += spentA
self.spentB += spentB
self.checkBalance (0, self.spentA)
self.checkBalance (1, self.spentB)
def checkTx (self, ind, txid, amount, fee, details):
"""
Calls 'gettransaction' and compares the result to the
expected data given in the arguments. "details" is an array
containing all the tx sent/received entries expected.
Each array element is an array itself with the fields:
[category, nameop, amount, fee]
nameop can be None if no "name" key is expected.
"""
data = self.nodes[ind].gettransaction (txid)
assert_equal (data['amount'], amount)
if fee is None:
assert 'fee' not in data
else:
assert_equal (data['fee'], fee)
# Bring the details returned in the same format as our expected
# argument. Furthermore, check that each entry has an address
# set (but don't compare the address, since we don't know it).
detailsGot = []
for d in data['details']:
assert 'address' in d
if 'name' in d:
nameOp = d['name']
if nameOp[:3] == 'new':
nameOp = 'new'
else:
# None is not sortable in Python3, so use "none" instead.
nameOp = "none"
if 'fee' in d:
fee = d['fee']
else:
fee = None
detailsGot.append ([d['category'], nameOp, d['amount'], fee])
# Compare. Sort to get rid of differences in the order.
detailsGot.sort ()
details.sort ()
assert_equal (detailsGot, details)
def run_test (self):
self.generate (self.nodes[0], 50)
self.sync_blocks ()
self.generate (self.nodes[1], 50)
self.generateToOther (1, 150)
self.sync_blocks ()
self.checkBalances ()
# Check that we use legacy addresses.
# FIXME: Remove once we have segwit.
addr = self.nodes[0].getnewaddress ()
info = self.nodes[0].getaddressinfo (addr)
assert not info['isscript']
assert not info['iswitness']
# Register and update a name. Check changes to the balance.
regA = self.nodes[0].name_register ("x/name-a", val ("value"))
regFee = self.getFee (0, regA, nameFee)
self.generateToOther (0, 1)
self.checkBalances (regFee)
updA = self.nodes[0].name_update ("x/name-a", val ("new value"))
updFee = self.getFee (0, updA)
self.generateToOther (0, 1)
self.checkBalances (updFee)
# Check the transactions.
self.checkTx (0, regA, zero, -regFee,
[['send', "update: 'x/name-a'", zero, -regFee]])
self.checkTx (0, updA, zero, -updFee,
[['send', "update: 'x/name-a'", zero, -updFee]])
# Send a name from 0 to 1 by registration and update.
addr = self.nodes[1].getnewaddress ()
regB = self.nodes[0].name_register ("x/name-b", val ("value"),
{"destAddress": addr})
fee = self.getFee (0, regB, nameFee)
regC = self.nodes[0].name_register ("x/name-c", val ("value"))
fee += self.getFee (0, regC, nameFee)
self.generateToOther (0, 1)
self.checkBalances (fee)
updC = self.nodes[0].name_update ("x/name-c", val ("new value"),
{"destAddress": addr})
fee = self.getFee (0, updC)
self.generateToOther (0, 1)
self.checkBalances (fee)
# Check the receiving transactions on node 1.
self.sync_blocks ()
self.checkTx (1, regB, zero, None,
[['receive', "update: 'x/name-b'", zero, None]])
self.checkTx (1, updC, zero, None,
[['receive', "update: 'x/name-c'", zero, None]])
# Use the rawtx API to build a simultaneous name update and currency send.
# This is done as an atomic name trade. Note, though, that the
# logic is a bit confused by "coin join" transactions and thus
# possibly not exactly what one would expect.
price = Decimal ("1.0")
fee = Decimal ("0.01")
txid = self.atomicTrade ("x/name-a", val ("enjoy"), price, fee, 0, 1)
self.generateToOther (0, 1)
self.sync_blocks ()
self.checkBalances (-price, price + fee)
self.checkTx (0, txid, price, None,
[['receive', "none", price, None]])
self.checkTx (1, txid, -price, -fee,
[['send', "none", -price, -fee],
['send', "update: 'x/name-a'", zero, -fee]])
# Test sendtoname RPC command.
addr = self.nodes[0].getnewaddress ()
txid = self.nodes[0].name_register ("x/destination", val ("value"),
{"destAddress": addr})
self.generateToOther (0, 1)
self.checkName (0, "x/destination", val ("value"))
self.checkBalances (self.getFee (0, txid, nameFee))
self.sync_blocks ()
assert_raises_rpc_error (-5, 'name not found',
self.nodes[1].sendtoname, "x/non-existant", 10)
txid = self.nodes[1].sendtoname ("x/destination", 10)
fee = self.getFee (1, txid)
self.generateToOther (1, 1)
self.sync_blocks ()
self.checkBalances (-10, 10 + fee)
txid = self.nodes[1].sendtoname ("x/destination", 10, "foo", "bar", True)
fee = self.getFee (1, txid)
self.generateToOther (1, 1)
self.sync_blocks ()
self.checkBalances (-10 + fee, 10)
if __name__ == '__main__':
NameWalletTest ().main ()
|
"use strict";
let datafire = require('datafire');
let fantasydata_nascar_v2 = require('@datafire/fantasydata_nascar_v2').actions;
module.exports = new datafire.Action({
handler: async (input, context) => {
let driver = await Promise.all([].map(item => fantasydata_nascar_v2.DriverDetails({
format: "json",
driverid: "",
}, context)));
return driver;
},
});
|
/*************************************************************
*
* MathJax/localization/en/MathMenu.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("en","MathMenu",{
version: "2.7.5",
isLoaded: true,
strings: {
Show: "Show math as",
MathMLcode: "MathML code",
OriginalMathML: "Original MathML",
TeXCommands: "TeX commands",
AsciiMathInput: "AsciiMathML input",
Original: "Original form",
ErrorMessage: "Error message",
Annotation: "Annotation",
TeX: "TeX",
StarMath: "StarMath",
Maple: "Maple",
ContentMathML: "Content MathML",
OpenMath: "OpenMath",
texHints: "Show TeX hints in MathML",
Settings: "Math settings",
ZoomTrigger: "Zoom trigger",
Hover: "Hover",
Click: "Click",
DoubleClick: "Double-click",
NoZoom: "No zoom",
TriggerRequires: "Trigger requires:",
Option: "Option",
Alt: "Alt",
Command: "Command",
Control: "Control",
Shift: "Shift",
ZoomFactor: "Zoom factor",
Renderer: "Math renderer",
MPHandles: "Let MathPlayer handle:",
MenuEvents: "Menu events",
MouseEvents: "Mouse events",
MenuAndMouse: "Mouse and menu events",
FontPrefs: "Font preferences",
ForHTMLCSS: "For HTML-CSS:",
Auto: "Auto",
TeXLocal: "TeX (local)",
TeXWeb: "TeX (web)",
TeXImage: "TeX (image)",
STIXLocal: "STIX (local)",
STIXWeb: "STIX (web)",
AsanaMathWeb: "Asana Math (web)",
GyrePagellaWeb: "Gyre Pagella (web)",
GyreTermesWeb: "Gyre Termes (web)",
LatinModernWeb: "Latin Modern (web)",
NeoEulerWeb: "Neo Euler (web)",
ContextMenu: "Contextual menu",
Browser: "Browser",
Scale: "Scale all math ...",
Discoverable: "Highlight on hover",
Locale: "Language",
LoadLocale: "Load from URL ...",
About: "About MathJax",
Help: "MathJax help",
localTeXfonts: "using local TeX fonts",
webTeXfonts: "using web TeX font",
imagefonts: "using Image fonts",
localSTIXfonts: "using local STIX fonts",
webSVGfonts: "using web SVG fonts",
genericfonts: "using generic Unicode fonts",
wofforotffonts: "WOFF or OTF fonts",
eotffonts: "EOT fonts",
svgfonts: "SVG fonts",
WebkitNativeMMLWarning: "Your browser does not seem to support MathML natively, so switching to MathML output may cause the mathematics on the page to become unreadable",
MSIENativeMMLWarning: "Internet Explorer requires the MathPlayer plugin in order to process MathML output.",
OperaNativeMMLWarning: "Opera's support for MathML is limited, so switching to MathML output may cause some expressions to render poorly.",
SafariNativeMMLWarning: "Your browser's native MathML does not implement all the features used by MathJax, so some expressions may not render properly.",
FirefoxNativeMMLWarning: "Your browser's native MathML does not implement all the features used by MathJax, so some expressions may not render properly.",
MSIESVGWarning: "SVG is not implemented in Internet Explorer prior to IE9 or when it is emulating IE8 or below. Switching to SVG output will cause the mathematics to not display properly.",
LoadURL: "Load translation data from this URL:",
BadURL: "The URL should be for a JavaScript file that defines MathJax translation data. JavaScript file names should end with '.js'",
BadData: "Failed to load translation data from %1",
SwitchAnyway: "Switch the renderer anyway?\n\n(Press OK to switch, CANCEL to continue with the current renderer)",
ScaleMath: "Scale all mathematics (compared to surrounding text) by",
NonZeroScale: "The scale should not be zero",
PercentScale: "The scale should be a percentage (for example 120%%)",
IE8warning: "This will disable the MathJax menu and zoom features, but you can Alt-Click on an expression to obtain the MathJax menu instead.\n\nReally change the MathPlayer settings?",
IE9warning: "The MathJax contextual menu will be disabled, but you can Alt-Click on an expression to obtain the MathJax menu instead.",
NoOriginalForm: "No original form available",
Close: "Close",
EqSource: "MathJax Equation Source",
CloseAboutDialog: "Close about MathJax dialog",
FastPreview: "Fast Preview",
AssistiveMML: "Assistive MathML",
InTabOrder: "Include in Tab Order"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/en/MathMenu.js");
|
import React from "react";
import Auth from "../utils/auth";
import { useParams } from "react-router-dom";
import { useQuery } from "@apollo/react-hooks";
import { QUERY_THERAPIST } from "../utils/queries";
import ReachOutForm from "../components/ReachOutForm";
const SingleTherapist = (props) => {
const { id: therapistId } = useParams();
const { loading, data } = useQuery(QUERY_THERAPIST, {
variables: { id: therapistId },
});
const therapist = data?.therapist || {};
const loggedIn = Auth.loggedIn();
if (loading) {
return <h3>Loading data...</h3>;
}
return (
<>
<div className="container">
<div className="row justify-content-center mt-5">
<div className="col col-sm-5 col-xl-4 align-middle">
<img
src={therapist.photo}
className="site-footer3--with-clipmask mb-3"
alt={therapist.first_name + " " + therapist.last_name}
loading="lazy"
width="200"
/>
<h1>
{therapist.first_name} {therapist.last_name}
</h1>
<p>{therapist.bio}</p>
</div>
<div className="col col-sm-5 col-xl-4">
<div
className="p-5 mt-3 rounded shadow"
style={{ background: "#c8c6c1" }}
>
<h2>Specialties</h2>
<ul>
{therapist.specialties.map((specialty, key) => (
<li key={therapist._id+'specialty'+key}>{specialty}</li>
))}
</ul>
</div>
<div
className="p-5 mt-3 rounded shadow"
style={{ background: "#d1ced8" }}
>
<h2>Skills</h2>
<ul>
{therapist.skills.map((skill, key) => (
<li key={therapist._id+'skill'+key}>{skill}</li>
))}
</ul>
</div>
</div>
</div>
<div className="row">
<div className="col mt-5">
{loggedIn ? (
<>
<ReachOutForm therapist={therapist}/>
</>
) : (
<>
Login to establish care with {therapist.first_name} {therapist.last_name}.
</>
)}
</div>
</div>
</div>
</>
);
};
export default SingleTherapist;
|
import { DesktopController } from "../controllers/DesktopController.js";
import { MobileController } from "../controllers/MobileController.js";
export class ArenaPlayer extends Phaser.Physics.Matter.Sprite
{
/* scene: Scene (Level)
x: X position of player in level (pixel unit)
y: Y position of player in level (pixel unit)
*/
constructor(scene, x, y, connection)
{
super(scene.matter.world, x, y, 'player');
this.scene = scene;
this.connection = connection;
scene.add.existing(this);
//Status
this.status = {
health: 20,
maxVelocityX: 3,
maxVelocityY: 9,
moveForce: 0.01,
nodamage: false,
isTouching: { left: false, right: false, down: false },
canJump: true,
fireRate: .3, // 1 bullet every [fireRate] seconds
isFireReloaded: true,
jumpCooldownTimer: null,
allowHorizontal: true,
allowMove: true,
};
//Creating Collision Body and Sensors using Phaser.Matter engine
let { Body, Bodies} = scene.PhaserGame.MatterPhysics;
//Bodies.rectangle(centerX position IN the sprite, centerY position IN the sprite,
// width of the collision body, height of the collision body, {options});
let mainBody = Bodies.rectangle(0, 0, this.width * 0.7, this.height, {chamfer: 1});
//Sensors: only for detecting, not for collision
this.sensors = {
bottom: Bodies.rectangle(0, this.height * 0.5, this.width * 0.4, 2, { isSensor: true }),
left: Bodies.rectangle(-this.width * 0.35, 0, 2, this.height * 0.5, { isSensor: true }),
right: Bodies.rectangle(this.width * 0.35, 0, 2, this.height * 0.5, { isSensor: true })
};
let compoundBody = Body.create({
parts: [mainBody, this.sensors.bottom, this.sensors.left, this.sensors.right],
frictionStatic: 0,
frictionAir: 0.03,
friction: .012
});
//Set collision category
this.category = 16;
//Add Collision Events
scene.matter.world.on("beforeupdate", this.resetTouching, this);
scene.matterCollision.addOnCollideStart({
objectA: [this.sensors.bottom, this.sensors.left, this.sensors.right],
callback: this.onSensorCollide,
context: this
});
scene.matterCollision.addOnCollideActive({
objectA: [this.sensors.bottom, this.sensors.left, this.sensors.right],
callback: this.onSensorCollide,
context: this
});
//Setting Sprite
this.setExistingBody(compoundBody)
.setPosition(x, y)
.setMass(2)
.setScale(1.5)
.setFixedRotation()
.setCollisionCategory(this.category)
.setDepth(1);
// Creating Controls/Cursors
this.controller = scene.PhaserGame.isMobile ? new MobileController(scene, this) : new DesktopController(scene, this);
//Creating Health Display
this.healthSprite = scene.add.sprite(20, 20, 'hearts');
scene.add.existing(this.healthSprite);
this.healthSprite.setFrame(0).setScrollFactor(0, 0);
this.displayHealth = scene.add.text(30, 12, this.status.health, {color:'#DC143C'});
this.displayHealth.setScrollFactor(0, 0);
this.gun = scene.add.image(this.x, this.y, 'gun');
this.gun.setDepth(1).setScale(2);
}
update()
{
if (this.status.allowMove)
{
//Update Controls/Cursors
this.controller.update();
}
this.controller.updateGun();
if (this.y > 600)
{
this.death();
}
}
//Sensor Update: ({bodyA: this collision body, bodyB: that collision body, pair: both collision body})
onSensorCollide({ bodyA, bodyB, pair }) {
if (bodyB.isSensor) return;
if (bodyA === this.sensors.left)
{
this.status.isTouching.left = true;
if (pair.separation > 0.5) this.x += pair.separation - 0.5;
}
else if (bodyA === this.sensors.right)
{
this.status.isTouching.right = true;
if (pair.separation > 0.5) this.x -= pair.separation - 0.5;
}
else if (bodyA === this.sensors.bottom)
{
this.status.isTouching.down = true;
}
}
resetTouching() {
this.status.isTouching.left = false;
this.status.isTouching.right = false;
this.status.isTouching.down = false;
}
//Important for entities
changeHealth(changeHealthBy)
{
this.status.health += changeHealthBy;
if (changeHealthBy < 0 && this.status.nodamage)
{
this.status.health -= changeHealthBy;
}
if (changeHealthBy < 0 && !this.status.nodamage)
{
this.damagedEffects();
}
if (this.status.health < 0)
{
this.status.health = 0;
//death() // game over
}
if (this.status.health < 10)
{
this.healthSprite.setFrame(2);
}
this.displayHealth.setText(this.status.health);
if (this.status.health <= 0)
{
this.death();
}
}
damagedEffects()
{
this.alpha = .5;
this.status.nodamage = true;
let timer = this.scene.time.addEvent({
delay: 1000,
callback: () =>
{
this.alpha = 1;
this.status.nodamage = false;
},
callbackScope: this,
loop: false
});
}
reloadGun()
{
this.status.isFireReloaded = false;
let timer = this.scene.time.addEvent({
delay: this.status.fireRate * 1000,
callback: () => this.status.isFireReloaded = true,
callbackScope: this,
loop: false
});
}
shoot(x, y)
{
if (this.status.isFireReloaded)
{
this.scene.connection.shootBullet(this.x, this.y, x, y, this)
//new Bullet(this.scene, this, this.x, this.y, x, y);
this.reloadGun();
}
}
disableHorizontalMovement()
{
this.status.allowHorizontal = false;
}
enableHorizontalMovement()
{
this.status.allowHorizontal = true;
}
disableAllMovement()
{
this.status.allowMove = false;
}
enableAllMovement()
{
this.status.allowMove = true;
}
stageMode()
{
this.scene.cameras.main.stopFollow();
this.disableAllMovement();
this.healthSprite.setVisible(false);
this.displayHealth.setVisible(false);
if (this.scene.PhaserGame.isMobile)
{
this.controller.disable();
}
else
{
this.controller.disableShoot();
}
}
playMode()
{
this.scene.cameras.main.startFollow(this, false, 0.5, 0.5);
this.enableAllMovement();
this.healthSprite.setVisible(true);
this.displayHealth.setVisible(true);
if (this.scene.PhaserGame.isMobile)
{
this.controller.enable();
}
else
{
this.controller.enableShoot();
}
}
//Initializing death sequence
death() {
//Freeze our character and delete nametag
this.stageMode();
this.name.destroy();
this.connection.destroyTimer();
this.connection.death();
// Event listeners
// if (this.scene.matter.world) {
// this.scene.matter.world.off("beforeupdate", this.resetTouching, this);
// }
// Matter collision plugin
// const sensors = [this.sensors.bottom, this.sensors.left, this.sensors.right];
// this.scene.matterCollision.removeOnCollideStart({ objectA: sensors });
// this.scene.matterCollision.removeOnCollideActive({ objectA: sensors });
// if (this.jumpCooldownTimer) this.jumpCooldownTimer.destroy();
this.scene.scene.start('death-scene', {
scene: this.scene.scene.key,
player: this,
sceneObject: this.scene
});
//this.destroy();
}
}
|
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// Respect "browser" field in package.json when resolving modules
// browser: false,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/0d/1_rhdzs91ns43n_6_23fsj_h0000gn/T/jest_dx",
// Automatically clear mock calls and instances between every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: null,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: null,
// A path to a custom dependency extractor
// dependencyExtractor: null,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: null,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: null,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],
// A map from regular expressions to module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: null,
// Run tests from one or more projects
// projects: null,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: null,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: null,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
testTimeout: 15000,
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: null,
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: null,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: null,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
|
import { NEW_LINE_CHARACTER } from 'containers/App/constants';
import uniq from 'lodash/uniq';
export function mapSearchParticipantAssociatedOrg(participant) {
const organizations = participant.practitionerRoles && participant.practitionerRoles
.map((role) => role.organization)
.map((organization) => organization.display);
return uniq(organizations)
.join(NEW_LINE_CHARACTER);
}
|
var searchData=
[
['idlenotificationdeadline',['IdleNotificationDeadline',['../classv8_1_1_isolate.html#aba794ed25d4fa8780b3a07c66a5e5d4a',1,'v8::Isolate']]],
['idletask',['IdleTask',['../classv8_1_1_idle_task.html',1,'v8']]],
['idletasksenabled',['IdleTasksEnabled',['../classv8_1_1_platform.html#ad229642bf16a066d2e8d866dc128141e',1,'v8::Platform']]],
['incontext',['InContext',['../classv8_1_1_isolate.html#afb6bbd31a87d0999dbbe5402447690a9',1,'v8::Isolate']]],
['increaseheaplimitfordebugging',['IncreaseHeapLimitForDebugging',['../classv8_1_1_isolate.html#a72cccea72b0a24af320542bbd5919043',1,'v8::Isolate']]],
['indexedpropertydefinercallback',['IndexedPropertyDefinerCallback',['../namespacev8.html#a967435db933fa9798caac467948499df',1,'v8']]],
['indexedpropertydeletercallback',['IndexedPropertyDeleterCallback',['../namespacev8.html#a53863728de14cde48dd6543207b2f2da',1,'v8']]],
['indexedpropertydescriptorcallback',['IndexedPropertyDescriptorCallback',['../namespacev8.html#a7506e91d70d885b5cbeabdf870ac0e88',1,'v8']]],
['indexedpropertyenumeratorcallback',['IndexedPropertyEnumeratorCallback',['../namespacev8.html#adbb0a6d5537371953f9ba807d4f6275e',1,'v8']]],
['indexedpropertygettercallback',['IndexedPropertyGetterCallback',['../namespacev8.html#a48e7816ba64447bf32a25d194588daaf',1,'v8']]],
['indexedpropertyhandlerconfiguration',['IndexedPropertyHandlerConfiguration',['../structv8_1_1_indexed_property_handler_configuration.html',1,'v8']]],
['indexedpropertyhandlerconfiguration',['IndexedPropertyHandlerConfiguration',['../structv8_1_1_indexed_property_handler_configuration.html#a1e474ac223c5b502e6eab8b0336f9fe7',1,'v8::IndexedPropertyHandlerConfiguration']]],
['indexedpropertyquerycallback',['IndexedPropertyQueryCallback',['../namespacev8.html#a980b62c33eb664783e61e25c3b27f9ee',1,'v8']]],
['indexedpropertysettercallback',['IndexedPropertySetterCallback',['../namespacev8.html#a4ac7cc6185ebc8b6a199f9fa8e6bf5c3',1,'v8']]],
['indexfilter',['IndexFilter',['../namespacev8.html#a46fd71fef702b35b34ed7495e7a63323',1,'v8']]],
['inherit',['Inherit',['../classv8_1_1_function_template.html#abc11c462facf11bafd541892815c5425',1,'v8::FunctionTemplate']]],
['init',['Init',['../structv8_1_1_tick_sample.html#a5e763b4b249b3fba53241b82d4ef6eeb',1,'v8::TickSample']]],
['initialize',['Initialize',['../classv8_1_1_v8.html#a40daec93ce44bdd922567fc121be9db8',1,'v8::V8']]],
['initializeexternalstartupdata',['InitializeExternalStartupData',['../classv8_1_1_v8.html#ad662ec37263887b7fd31c6b498e9466c',1,'v8::V8']]],
['initializeicudefaultlocation',['InitializeICUDefaultLocation',['../classv8_1_1_v8.html#a133e338f42ab109a51f75b929f7c1500',1,'v8::V8']]],
['initializeplatform',['InitializePlatform',['../classv8_1_1_v8.html#a095eb8064458588a579c2b904e02dbbf',1,'v8::V8']]],
['inspectable',['Inspectable',['../classv8__inspector_1_1_v8_inspector_session_1_1_inspectable.html',1,'v8_inspector::V8InspectorSession']]],
['instancetemplate',['InstanceTemplate',['../classv8_1_1_function_template.html#a00dd9725566908e8fd14064542f5a781',1,'v8::FunctionTemplate']]],
['instantiate',['Instantiate',['../classv8_1_1_module.html#aa432ad852dd5b1b8c309528a9bd1aa5c',1,'v8::Module']]],
['int16array',['Int16Array',['../classv8_1_1_int16_array.html',1,'v8']]],
['int32',['Int32',['../classv8_1_1_int32.html',1,'v8']]],
['int32array',['Int32Array',['../classv8_1_1_int32_array.html',1,'v8']]],
['int8array',['Int8Array',['../classv8_1_1_int8_array.html',1,'v8']]],
['integer',['Integer',['../classv8_1_1_integer.html',1,'v8']]],
['integritylevel',['IntegrityLevel',['../namespacev8.html#a02642d03ff1eecc2fd358626499c2e30',1,'v8']]],
['internalfieldcount',['InternalFieldCount',['../classv8_1_1_object.html#aaec28576353eebe6fee113bce2718ecc',1,'v8::Object::InternalFieldCount()'],['../classv8_1_1_object.html#a324a71142f621a32bfe5738648718370',1,'v8::Object::InternalFieldCount(const PersistentBase< Object > &object)'],['../classv8_1_1_object_template.html#a43de785d594d8c01b18230b1aa79e31c',1,'v8::ObjectTemplate::InternalFieldCount()']]],
['internals',['Internals',['../classv8_1_1internal_1_1_internals.html',1,'v8::internal']]],
['isactive',['IsActive',['../classv8_1_1_locker.html#a19d2b640f2f9b3dd0ec3a6c09a0442ed',1,'v8::Locker']]],
['isargumentsobject',['IsArgumentsObject',['../classv8_1_1_value.html#addd71e0247ca7e8055dafdf196542b0b',1,'v8::Value']]],
['isarray',['IsArray',['../classv8_1_1_value.html#a4908fac2c2888ade5d05a8dd312e1fd7',1,'v8::Value']]],
['isarraybuffer',['IsArrayBuffer',['../classv8_1_1_value.html#a62c732277023d09f5e5a54eaa2846853',1,'v8::Value']]],
['isarraybufferview',['IsArrayBufferView',['../classv8_1_1_value.html#ab1ba4b263da3630cf8efd0c6b6e26293',1,'v8::Value']]],
['isasyncfunction',['IsAsyncFunction',['../classv8_1_1_value.html#ade5685814ab387c1772e2d5dbd000735',1,'v8::Value']]],
['isboolean',['IsBoolean',['../classv8_1_1_value.html#a7ab7130b87a1fbcced76268353fae00b',1,'v8::Value']]],
['isbooleanobject',['IsBooleanObject',['../classv8_1_1_value.html#a4cc64a2761fa8ed852007a2c35ecde8a',1,'v8::Value']]],
['iscallable',['IsCallable',['../classv8_1_1_object.html#a23c2c1f23b50fab4a02e2f819641b865',1,'v8::Object']]],
['iscodegenerationfromstringsallowed',['IsCodeGenerationFromStringsAllowed',['../classv8_1_1_context.html#aa7a960a232d232d1a2a904c2e6c18831',1,'v8::Context']]],
['isconstructor',['IsConstructor',['../classv8_1_1_stack_frame.html#a8f37df38214b6dc10655fc50f0341eb8',1,'v8::StackFrame::IsConstructor()'],['../classv8_1_1_object.html#a257233cb6b11dc7bb5a0e8df8695e889',1,'v8::Object::IsConstructor()']]],
['isdataview',['IsDataView',['../classv8_1_1_value.html#ad854ff95b445e924a4d78b1b1dc8054b',1,'v8::Value']]],
['isdate',['IsDate',['../classv8_1_1_value.html#aa94f94744aed4d5e731eacf52c8b4801',1,'v8::Value']]],
['isdead',['IsDead',['../classv8_1_1_isolate.html#a603a9bc7860d7936bce2dd45829869c3',1,'v8::Isolate']]],
['isempty',['IsEmpty',['../classv8_1_1_persistent_value_vector.html#aa45dd4d1ee94a2c199a28a0bb2e432f1',1,'v8::PersistentValueVector::IsEmpty()'],['../classv8_1_1_local.html#aeec81dfca98e0d5b2f26ae13c2d141f4',1,'v8::Local::IsEmpty()']]],
['isequivalent',['IsEquivalent',['../classv8_1_1_retained_object_info.html#a286103bb076c85415919c86b1838c990',1,'v8::RetainedObjectInfo']]],
['iseval',['IsEval',['../classv8_1_1_stack_frame.html#aa07e67a6a00adcd0f5c8c4ba7a82e54a',1,'v8::StackFrame']]],
['isevent',['IsEvent',['../classv8_1_1_debug_1_1_message.html#a36ade83a9c960ce581b1a4051f763785',1,'v8::Debug::Message']]],
['isexecutionterminating',['IsExecutionTerminating',['../classv8_1_1_isolate.html#aee57283198c192e83afe5e7d12d42e85',1,'v8::Isolate']]],
['isexternal',['IsExternal',['../classv8_1_1_value.html#a908070323b8cd593127141a22b79e39d',1,'v8::Value::IsExternal()'],['../classv8_1_1_string.html#a1d24faa97c6168221ec362c395d41ce1',1,'v8::String::IsExternal()'],['../classv8_1_1_array_buffer.html#a22ecea76af2257b12bdb69b40d9bec8f',1,'v8::ArrayBuffer::IsExternal()'],['../classv8_1_1_shared_array_buffer.html#adcbceac6432955c7d54fceea27c92b73',1,'v8::SharedArrayBuffer::IsExternal()']]],
['isexternalonebyte',['IsExternalOneByte',['../classv8_1_1_string.html#a29b5d1786d906b84e10a5cab9451f976',1,'v8::String']]],
['isfalse',['IsFalse',['../classv8_1_1_value.html#a84b6682c5582e0ae14d85bd9b6f25522',1,'v8::Value']]],
['isfloat32array',['IsFloat32Array',['../classv8_1_1_value.html#aafedbffb06cdd267149f241ad7926d9d',1,'v8::Value']]],
['isfloat32x4',['IsFloat32x4',['../classv8_1_1_value.html#a126b9e4fc197bdb5c780df2ddfb75293',1,'v8::Value']]],
['isfloat64array',['IsFloat64Array',['../classv8_1_1_value.html#a7ed4de7b1d4467cdd69eb128b3ecfdf2',1,'v8::Value']]],
['isfunction',['IsFunction',['../classv8_1_1_value.html#ac7a649d482c41cfc6281a4215a091a6d',1,'v8::Value']]],
['isgeneratorfunction',['IsGeneratorFunction',['../classv8_1_1_value.html#ac0a7fcb3b244a921e5574e6f34fa9b07',1,'v8::Value']]],
['isgeneratorobject',['IsGeneratorObject',['../classv8_1_1_value.html#af6f2d3199fe8b5eee219ef42574293ac',1,'v8::Value']]],
['isimmutableproto',['IsImmutableProto',['../classv8_1_1_object_template.html#a76c12ee7be283bd3b007d062686dc0ed',1,'v8::ObjectTemplate']]],
['isint16array',['IsInt16Array',['../classv8_1_1_value.html#a8db779f4ac104540e63d78e73d424195',1,'v8::Value']]],
['isint32',['IsInt32',['../classv8_1_1_value.html#ad5d58df1d978b4d9875eb97b3bebfc29',1,'v8::Value']]],
['isint32array',['IsInt32Array',['../classv8_1_1_value.html#afd14729579f9768a7d3f8bc3db6c1d28',1,'v8::Value']]],
['isint8array',['IsInt8Array',['../classv8_1_1_value.html#ad9c2858387a0cafe3628f0533a9bbf6a',1,'v8::Value']]],
['isinuse',['IsInUse',['../classv8_1_1_isolate.html#a961a5591bb2a3febda9e2974f21c4d15',1,'v8::Isolate']]],
['islocked',['IsLocked',['../classv8_1_1_locker.html#a3ae563ffdd9e8b5a0100f0ae756b3a6a',1,'v8::Locker']]],
['ismap',['IsMap',['../classv8_1_1_value.html#a85e4e8455cbd60c9b0a1dc91030383e6',1,'v8::Value']]],
['ismapiterator',['IsMapIterator',['../classv8_1_1_value.html#a761b2fd0aa8c2f59c879741336eb2f66',1,'v8::Value']]],
['isname',['IsName',['../classv8_1_1_value.html#a1ae3d5f5823705d2b6c26378201b772b',1,'v8::Value']]],
['isnativeerror',['IsNativeError',['../classv8_1_1_value.html#a7dc01ab1db65640f774366e8ecab91df',1,'v8::Value']]],
['isneardeath',['IsNearDeath',['../classv8_1_1_persistent_base.html#a6587b66b7d4c0397129c51d0507b4094',1,'v8::PersistentBase']]],
['isneuterable',['IsNeuterable',['../classv8_1_1_array_buffer.html#a5de3f4c29744bd89204462f987ecb626',1,'v8::ArrayBuffer']]],
['isnull',['IsNull',['../classv8_1_1_value.html#a7710cf2aca870e961f1df65ef6057eb4',1,'v8::Value']]],
['isnumber',['IsNumber',['../classv8_1_1_value.html#a6ef42a28c0bc70022acb7e308bda4e19',1,'v8::Value']]],
['isnumberobject',['IsNumberObject',['../classv8_1_1_value.html#a497018ef8c5ed946e1c0c30554bad3f8',1,'v8::Value']]],
['isobject',['IsObject',['../classv8_1_1_value.html#a72a01e06e897a8fedbb430cdd7fc3ffe',1,'v8::Value']]],
['isolate',['Isolate',['../classv8_1_1_isolate.html',1,'v8']]],
['isolateinbackgroundnotification',['IsolateInBackgroundNotification',['../classv8_1_1_isolate.html#a15c1ba9cdb3526a6439e7fddb292ee93',1,'v8::Isolate']]],
['isolateinforegroundnotification',['IsolateInForegroundNotification',['../classv8_1_1_isolate.html#afaa09b3cb3a20f53bdcdce4b154d928f',1,'v8::Isolate']]],
['isonebyte',['IsOneByte',['../classv8_1_1_string.html#a8f14ab3aff52295d2d3245081a1b29eb',1,'v8::String']]],
['ispromise',['IsPromise',['../classv8_1_1_value.html#a4b0be5d9dc3a857fee9ba7dac07123e3',1,'v8::Value']]],
['isproxy',['IsProxy',['../classv8_1_1_value.html#a3c0ad01f2ca4ac050ef8214785848918',1,'v8::Value']]],
['isregexp',['IsRegExp',['../classv8_1_1_value.html#a010aa78e7cc8e1dbb878479e534992b3',1,'v8::Value']]],
['isrunningmicrotasks',['IsRunningMicrotasks',['../classv8_1_1_microtasks_scope.html#add7bcfed084afcd0d2729c3ac382145c',1,'v8::MicrotasksScope']]],
['isset',['IsSet',['../classv8_1_1_value.html#a131fc14572f31efd8e2969963564abbb',1,'v8::Value']]],
['issetiterator',['IsSetIterator',['../classv8_1_1_value.html#a908403b5e09eb5dc0087b562b01618a4',1,'v8::Value']]],
['issharedarraybuffer',['IsSharedArrayBuffer',['../classv8_1_1_value.html#a1d7d90fe704feab89dcbdc383ab298b2',1,'v8::Value']]],
['issharedcrossorigin',['IsSharedCrossOrigin',['../classv8_1_1_message.html#a60e48ec814c324c443043dfaf366590a',1,'v8::Message']]],
['isstring',['IsString',['../classv8_1_1_value.html#a6c7582919eec6f30e865b3300eff9a8e',1,'v8::Value']]],
['isstringobject',['IsStringObject',['../classv8_1_1_value.html#a32054145eadf3b1a3f900dcd52110e2b',1,'v8::Value']]],
['issymbol',['IsSymbol',['../classv8_1_1_value.html#a0fee90dc2589b156d277a74b0b225a71',1,'v8::Value']]],
['issymbolobject',['IsSymbolObject',['../classv8_1_1_value.html#a1d5507f09734f8062a0d0a9a78496b2a',1,'v8::Value']]],
['istailcalleliminationenabled',['IsTailCallEliminationEnabled',['../classv8_1_1_debug.html#a79ce7b9e4e09be64ca1c3494ec6130ab',1,'v8::Debug']]],
['istrue',['IsTrue',['../classv8_1_1_value.html#a48c300598bad0155eb59965c9e6b86b6',1,'v8::Value']]],
['istypedarray',['IsTypedArray',['../classv8_1_1_value.html#a01183cf30ba5e6383cdca82daee630d8',1,'v8::Value']]],
['isuint16array',['IsUint16Array',['../classv8_1_1_value.html#af3e8da420ddc0f92aac5dbfe61ac9699',1,'v8::Value']]],
['isuint32',['IsUint32',['../classv8_1_1_value.html#ae30d50fb96b03239bc90ceb07b6e46fc',1,'v8::Value']]],
['isuint32array',['IsUint32Array',['../classv8_1_1_value.html#a52fe549df18b0c77a875d7aa61f87317',1,'v8::Value']]],
['isuint8array',['IsUint8Array',['../classv8_1_1_value.html#af11d828f1a78df0de696e210571b7860',1,'v8::Value']]],
['isuint8clampedarray',['IsUint8ClampedArray',['../classv8_1_1_value.html#a655a46fa71c8a33d138756d8a6c515ac',1,'v8::Value']]],
['isundefined',['IsUndefined',['../classv8_1_1_value.html#ad3a7686feef02fbe0317570b9640b078',1,'v8::Value']]],
['isweak',['IsWeak',['../classv8_1_1_persistent_value_map_base.html#a9f824b13dd30605589508db2740dd678',1,'v8::PersistentValueMapBase::IsWeak()'],['../classv8_1_1_persistent_base.html#a479c7b146da083aa608e133a7dec79f9',1,'v8::PersistentBase::IsWeak()']]],
['isweakmap',['IsWeakMap',['../classv8_1_1_value.html#a3be1c8f103d9aa9b31b3b1c56905337d',1,'v8::Value']]],
['isweakset',['IsWeakSet',['../classv8_1_1_value.html#a66c2dbb0ed13325f0f9e6b38e5e1992c',1,'v8::Value']]]
];
|
const express = require('express')
const PatientController = require('../controllers/patient')
const router = express.Router()
router.get('/list', PatientController.getPatients)
router.post('/add', PatientController.addPatient)
router.put('/update', PatientController.updatePatient)
router.put('/associer', PatientController.associerPatient)
router.put('/dissocier', PatientController.dissocierPatient)
router.delete('/delete/:id', PatientController.deletePatient)
module.exports = router
|
define(['mmirf/jscc','mmirf/constants','mmirf/configurationManager','mmirf/grammarConverter','mmirf/util/deferred','mmirf/util/extend','mmirf/util/toArray','mmirf/util/loadFile','mmirf/logger', 'module'],
/**
* Generator for executable language-grammars (i.e. converted JSON grammars).
*
* <p>
* This generator uses JS/CC for compiling the JSON grammar.
*
* <p>
* The generator for compiling the JSON grammar definitions in <code>www/config/languages/<language code>/grammar.json</code>
* can be configured in <code>www/config/configuration.json</code>:<br>
* <pre>
* {
* ...
* "grammarCompiler": "jscc",
* ...
* }</pre>
*
* <em>NOTE: this is the default grammar engine (if there is no setting in
* <code>configuration.json</code>, then this engine will be used)
* </em>
*
* <p>
* JS/CC supports grammar generation for:
* LALR(1)
*
* (in difference to jison, JS/CC supports backtracking to certain extend)
*
* @see <a href="http://jscc.phorward-software.com/">http://jscc.phorward-software.com/</a>
*
* @class
* @constant
* @public
* @name JsccGenerator
* @memberOf mmir.env.grammar
*
* @requires JS/CC
*/
function(jscc, constants, configManager, GrammarConverter, deferred, extend, toArray, loadFile, Logger, module){
////////////////////////////////////// template loading / setup for JS/CC generator ////////////////////////////////
/**
* Deferred object that will be returned - for async-initialization:
* the deferred object will be resolved, when this module has been initialized.
*
* @private
* @type Deferred
* @memberOf JsccGenerator#
*
* @see #_loadTemplate
*/
var deferred = deferred();
/**
* The Logger for the JS/CC generator.
*
* @private
* @type Logger
* @memberOf JsccGenerator#
*
* @see mmir.Logging
*/
var logger = Logger.create(module);
//setup logger for compile-messages
/**
* HELPER for creating default logging / error-print functions
*
* @function
* @private
* @memberOf JsccGenerator#
*
* @see mmir.Logging
*/
function _createCompileLogFunc(log /*Logger*/, level /*String: log-function-name*/, toArray/*helper-lib: provides function makeArray(obj); e.g. jquery*/){
return function(){
var args = toArray(arguments);
//prepend "location-information" to logger-call:
args.unshift('JS/CC', 'compile');
//output log-message:
log[level].apply(log, args);
};
}
/**
* The URL to the JS/CC template file (generated code-text will be "embedded" in this template)
*
* @private
* @type String
* @memberOf JsccGenerator#
*/
var templatePath = constants.getGrammarPluginPath() + 'grammarTemplate_reduced.tpl';
/**
* The argument name when generating the grammar function:
* the argument holds the raw text that will be parsed by the generated grammar.
*
* NOTE: this argument/variable name must not collide with any code that is generated for the grammar.
*
* @constant
* @private
* @memberOf JsccGenerator#
*/
var INPUT_FIELD_NAME = 'asr_recognized_text';
/**
* The default options for the JS/CC compiler.
*
* To overwrite the default options, configure the following property in <code>www/config/configuration.json</code>:<br>
* <pre>
* {
* ...
* "grammar": {
* ...
* "jscc": {
* "execMode": "your configuration setting!"
* }
* ...
* },
* ...
* }</pre>
*
* Valid settings are:
* <code>execMode = 'sync' | 'async'</code>
* <code>genSourceUrl = true | STRING | FALSY'</code>
*
*
* genSourceUrl: if TRUTHY, the sourceUrl for eval'ed parser-module is set
* (i.e. eval'ed code will appear at the URL in debugger, if browser supports sourceURL setting)
* if true: the sourceUrl will be generated using the grammar's ID
* if STRING: the string will be used as sourceUrl; if "<id>" is contained, it will be replaced by the grammar's ID
*
* @constant
* @private
* @default targetType := jscc.MODE_GEN_JS, execMode := sync, genSourceUrl := FALSY
* @memberOf JsccGenerator#
*/
var DEFAULT_OPTIONS = {
targetType: jscc.MODE_GEN_JS,
execMode: 'sync',//'sync' | 'async' | default: sync
genSourceUrl: '',// true | STRING: the sourceURL for eval'ed parser-module | default: FALSY
};
/**
* Name for this plugin/grammar-generator (e.g. used for looking up configuration values in configuration.json).
* @constant
* @private
* @memberOf JsccGenerator#
*/
var pluginName = 'grammar.jison';
/**
* Exported (public) functions for the JS/CC grammar-engine.
* @public
* @type GrammarGenerator
* @memberOf JsccGenerator#
*/
var jsccGen = {
/** @scope JsccGenerator.prototype */
/**
* The name/ID for the compile engine for the JS/CC compiler
*
* @memberOf mmir.env.grammar.JsccGenerator.prototype
*/
engineId: 'jscc',
/**
* @param {Function} [callback] OPTIONAL
* the callback that is triggered, when the engine is initialized
* @returns {Deferred}
* a promise that is resolved, when the engine is initialized
* (NOTE: if you use the same function for the <code>callback</code> AND the promise,
* then the function will be invoked twice!)
*
* @memberOf mmir.env.grammar.JsccGenerator.prototype
*/
init: function(callback){
if(callback){
deferred.then(callback, callback);
}
return deferred;
},
/** @returns {Boolean} if this engine compilation works asynchronously. The current implementation works synchronously (returns FALSE) */
isAsyncCompilation: function(){ return false; },
/**
* The function for compiling a JSON grammar:
*
*
* @param {GrammarConverter} theConverterInstance
* @param {String} instanceId
* the ID for the compiled grammar (usually this is a language code)
* @param {Number} fileFormatVersion
* the version of the file format (this is a constant within {@link mmir.SemanticInterpreter}
* @param callback
* @returns {GrammarConverter}
* the grammar instance with attached with the compiled function for executing the
* grammar to the instance's {@link GrammarConvert#executeGrammar} property/function.
*/
compileGrammar: function(theConverterInstance, instanceId, fileFormatVersion, callback){
//attach functions for JS/CC conversion/generation to the converter-instance:
extend(theConverterInstance, JsccGrammarConverterExt);
//attach the JS/CC template to the converter instance
theConverterInstance.TEMPLATE = this.template;
//start conversion: create grammar in JS/CC syntax (from the JSON definition):
theConverterInstance.init();
this._preparePrintError();
theConverterInstance.convertJSONGrammar();
var grammarDefinition = theConverterInstance.getGrammarDef();
//load options from configuration:
var config = configManager.get(pluginName, {});
//combine with default default options:
var options = extend({id: instanceId}, DEFAULT_OPTIONS, config);
var compileParserModule = function(grammarParserStr, hasError){
var addGrammarParserExec = theConverterInstance.getCodeWrapPrefix(fileFormatVersion, JSON.stringify(options.execMode))
+ 'var grammarFunc = function('+INPUT_FIELD_NAME+'){' + grammarParserStr + '\n};\n'
+ theConverterInstance.getCodeWrapSuffix(theConverterInstance.getEncodedStopwords(), 'grammarFunc', instanceId);
if(options.genSourceUrl){
var sourceUrlStr;
if(options.genSourceUrl === true){
sourceUrlStr = 'gen/grammar/_compiled_grammar_'+instanceId;
} else {
sourceUrlStr = options.genSourceUrl.toString().replace(/<id>/g,instanceId);
}
//for Chrome / FireFox debugging: provide an URL for eval'ed code
addGrammarParserExec += '//@ sourceURL='+sourceUrlStr+'\n'
+'//# sourceURL='+sourceUrlStr+'\n';
}
theConverterInstance.setGrammarSource(addGrammarParserExec);
try{
eval(addGrammarParserExec);
} catch (err) {
//TODO russa: generate meaningful error message with details about error location
// eg. use esprima (http://esprima.org) ...?
// ... as optional dependency (see deferred initialization above?)
var evalMsg = 'Error during eval() for "'+ instanceId +'": ' + err + ', source code:\n'+addGrammarParserExec+'\n\ntemplate code:\n'+theConverterInstance.TEMPLATE;
if(jscc.get_printError()){
jscc.get_printError()(evalMsg);
}
else {
logger.error('JS/CC', 'evalCompiled', evalMsg, err);
}
if(! hasError){
evalMsg = '[INVALID GRAMMAR JavaScript CODE] ' + evalMsg;
var parseDummyFunc = (function(msg, error){
return function(){ console.error(msg); console.error(error); throw msg;};
})(evalMsg, err);
parseDummyFunc.hasErrors = true;
theConverterInstance.setGrammarFunction(parseDummyFunc);
}
}
//invoke callback if present:
if(callback){
callback(theConverterInstance);
}
};
var isPreventDefault = this._afterCompileParser(compileParserModule, callback);
var result = this._compileParser(grammarDefinition, options, isPreventDefault);
if(!isPreventDefault){
var hasError = result.hasError;
compileParserModule(result.def, hasError);
}
return theConverterInstance;
},
/**
* @protected
*/
_compileParser: function(grammarDefinition, options, afterCompileParserResult){
//set up the JS/CC compiler:
var dfa_table = '';
jscc.reset_all( jscc.EXEC_WEB );
var isParsingFailed = false;
var grammarParserStr;
try {
jscc.parse_grammar(grammarDefinition);
} catch (err){
var msg = 'Error while compiling grammar: ' + (err.stack?err.stack:err);
isParsingFailed = msg;
msg = '[INVALID GRAMMAR] ' + msg + (error && error.stack? error.stack : '');
grammarParserStr = 'var msg = '+JSON.stringify(msg)+'; console.error(msg); throw msg;';//FIXME
}
if (jscc.getErrors() == 0) {
jscc.undef();
jscc.unreachable();
if (jscc.getErrors() == 0) {
jscc.first();
jscc.print_symbols();
dfa_table = jscc.create_subset(jscc.get_nfa_states());
dfa_table = jscc.minimize_dfa(dfa_table);
jscc.set_dfa_table(dfa_table);//FIXME: check, if this is really necessary
jscc.lalr1_parse_table(false);
jscc.resetErrors();
}
}
if (jscc.getErrors() > 0 || jscc.getWarnings() > 0){
logger.error(
'JSCC', 'compile', 'there occured'
+ (jscc.getWarnings() > 0? jscc.getWarnings() + ' warning(s)' : '')
+ (jscc.getErrors() > 0? jscc.getErrors() + ' error(s)' : '')
+ ' during compilation.'
);
}
jscc.resetErrors();
jscc.resetWarnings();
// console.debug("before replace " + theConverterInstance.PARSER_TEMPLATE);//debug
if( ! isParsingFailed){
var genData = this._getGenerated(options.targetType, dfa_table);
grammarParserStr = this._applyGenerated(genData, this.template);
}
return {def: grammarParserStr, hasError: isParsingFailed};
},
/**
* @protected
*/
_preparePrintError: function(){
//only set print-message function, if it is not already set
// (i.e. if JS/CC still has its default print function set)
if(jscc.is_printError_default()){
/**
* The default logging function for printing compilation errors.
* @private
* @name set_printError
* @function
* @memberOf JsccGenerator.jscc#
*/
jscc.set_printError( _createCompileLogFunc(logger, 'error', toArray));
}
if(jscc.is_printWarning_default()){
/**
* The default logging function for printing compilation warnings.
* @private
* @name set_printWarning
* @function
* @memberOf JsccGenerator.jscc#
*/
jscc.set_printWarning( _createCompileLogFunc(logger, 'warn', toArray));
}
if(jscc.is_printInfo_default()){
/**
* The default logging function for printing compilation information.
* @private
* @name set_printInfo
* @function
* @memberOf JsccGenerator.jscc#
*/
jscc.set_printInfo( _createCompileLogFunc(logger, 'info', toArray));
}
},
/**
* The default logging / error-print function for JS/CC.
*
* @protected
*
* @see mmir.Logging
*/
printError: function(){
var errorFunc = jscc.get_printError();
if(errorFunc){
errorFunc.apply(jscc, arguments);
} else {
var args = toArray(arguments);
//prepend "location-information" to logger-call:
args.unshift('JS/CC', 'compile');
//output log-message:
logger.error.apply(logger, args);
}
},
/**
* Optional hook for pre-processing the generated parser, after the parser is generated.
*
* By default, this function returns VOID, in which case the parser-module is created by default.
*
* If a function is returned instead, then it must invoke <code>compileParserModuleFunc</code>:
* <code>compileParserModuleFunc(compiledParser : STRING, hasErrors : BOOLEAN)</code>
*
*
* @param {Function} compileParserModuleFunc
* the function that generates the parser-module:
* <code>compileParserModuleFunc(compiledParser : STRING, hasErrors : BOOLEAN)</code>
*
* @param {Function} compileCallbackFunc
* the callback function which will be invoked by compileParserModuleFunc, after it has finished.
* If compileParserModuleFunc() is prevented from exectution then the callback MUST be invoked manually
* <code>compileCallbackFunc(theConverterInstance: GrammarConverter)</code>
*
* @returns {TRUTHY|VOID}
* FALSY for the default behavior.
* IF a TRUTHY value is returned, then the default action after compiling the parser
* is not executed:
* i.e. compileParserModuleFunc is not automatically called and in consequence the callback is not invoked
*
*
* NOTE: if not FALSY, then either compileParserModuleFunc() must be invoked, or the callback() must be invoked!
*
* @protected
*/
_afterCompileParser: function(compileParserModuleFunc, compileCallbackFunc){
//default: return VOID
return;
},
/**
* @protected
*/
_getGenerated: function(genMode, dfaTable){
return {
head: jscc.get_code_head(),
tables: jscc.print_parse_tables(genMode),//jscc.MODE_GEN_JS
dfa: jscc.print_dfa_table(dfaTable),//dfa_table
terminals: jscc.print_term_actions(),
labels: jscc.print_symbol_labels(),
actions: jscc.print_actions(),
error: jscc.get_error_symbol_id(),
eof: jscc.get_eof_symbol_id(),
whitespace: jscc.get_whitespace_symbol_id()
};
},
/**
* @protected
*/
_applyGenerated: function(genData, template){
var grammarParserStr = template;
grammarParserStr = grammarParserStr.replace(/##PREFIX##/g, "");
grammarParserStr = grammarParserStr.replace(/##HEADER##/g, genData.head);
grammarParserStr = grammarParserStr.replace(/##TABLES##/g, genData.tables);
grammarParserStr = grammarParserStr.replace(/##DFA##/g, genData.dfa);
grammarParserStr = grammarParserStr.replace(/##TERMINAL_ACTIONS##/g, genData.terminals);
grammarParserStr = grammarParserStr.replace(/##LABELS##/g, genData.labels);
grammarParserStr = grammarParserStr.replace(/##ACTIONS##/g, genData.actions);
grammarParserStr = grammarParserStr.replace(/##FOOTER##/g, "\nvar _semanticAnnotationResult = { result: {}};\n"
+"__parse( "+INPUT_FIELD_NAME+", new Array(), new Array(), _semanticAnnotationResult);\n"
+"return _semanticAnnotationResult.result;"
);
grammarParserStr = grammarParserStr.replace(/##ERROR##/g, genData.error);
grammarParserStr = grammarParserStr.replace(/##EOF##/g, genData.eof);
grammarParserStr = grammarParserStr.replace(/##WHITESPACE##/g, genData.whitespace);
return grammarParserStr;
}
};
/**
* Initializes the grammar-engine:
*
* loads the template and resolves the engine as initialzed.
*
* @param {String} url
* URL to the template file
* @param {GrammarGenerator} jsccGenerator
* the JS/CC grammar generator instance
* @param {Deferred} promise
* the {@link #deferred} for resolving the generator
* as initialized.
*
*
* @private
* @function
* @memberOf JsccGenerator#
*/
function _loadTemplate(url, jsccGenerator, promise){
loadFile({//$.ajax({
url: url,
dataType: 'text',
async: true,
success: function(data){
jsccGenerator.template = data;
promise.resolve();
},
error: function(xhr, status, err){
var msg = 'Failed to load grammar template file from "'+templatePath+'": '+status+', ERROR '+err;
console.error(msg);
promise.reject(msg);
}
});
}
//load the JS/CC template and resolve this module as "initialzed":
_loadTemplate(templatePath, jsccGen, deferred);
////////////////////////////////////// JS/CC specific extensions to GrammarConverter ////////////////////////////////
/**
* JS/CC specific extension / implementation for {@link GrammarConverter} instances
*
* @type GrammarConverter
* @memberOf JsccGenerator#
*/
var JsccGrammarConverterExt = {
/** @memberOf JsccGrammarConverterExt */
init: function(){
this.THE_INTERNAL_GRAMMAR_CONVERTER_INSTANCE_NAME = "theGrammarConverterInstance";
this._PARTIAL_MATCH_PREFIX = "%";
this._PARTIAL_LOCATION_PREFIX = '@';
this.grammar_tokens = "/~ --- Token definitions --- ~/\n\n/~ Characters to be ignored ~/\n! ' |\\t' ;\n\n/~ Non-associative tokens ~/\n";
this.grammar_utterances = "";
this.grammar_phrases = "phrases:";
this.token_variables = "[*\n"
//some helper functions
+ " var _tokenList = function(match, list) {if(!list){list = [];}var size = match.length, t;for (var i = 0; i < size; ++i) {t = match[i];if (!t) {continue;}if (t."+this.entry_token_field+".join) {_tokenList(t."+this.entry_token_field+", list);} else {list.push(t."+this.entry_token_field+");}}return list;};\n"
+ " var _getTok = function(phrases, type, index) {var count = 0, p;for(var i=0, size = phrases.length; i < size; ++i){p = phrases[i];if(p."+this.entry_type_field+" === type){if(index === count++){return typeof p."+this.entry_token_field+" === 'string'? p."+this.entry_token_field+" : p;}}}};\n"
//global variable for storing the result:
+ " var " + this.variable_prefix + "result = '';\n"
;
this.tokens_array = [];
},
convertJSONGrammar: function(){
this.json_grammar_definition = this.maskJSON(this.json_grammar_definition);
this.parseTokens();
this.parseUtterances();
this.parseStopWords();
this.jscc_grammar_definition = this.token_variables
+ "*]\n\n"
+ this.grammar_tokens
+ "\n\n ##\n\n/~ --- Grammar specification --- ~/\n\nutterance: phrases [* "
//TODO use LOG LEVEL for activating / deactivating this:
+ "console.log("
+ this.variable_prefix + "result); "
+ "semanticAnnotationResult.result = "
+ this.variable_prefix + "result; *] ;\n\n" + this.grammar_utterances
+ "\n" + this.grammar_phrases + ";";
this.json_grammar_definition = this.unmaskJSON(this.json_grammar_definition);
},
parseTokens: function(){
var self = this;
var json_tokens = this.json_grammar_definition.tokens;
var pref = self.variable_prefix;
for(var token_name in json_tokens){
var words = json_tokens[token_name];
self.token_variables += " var " + pref
+ token_name.toLowerCase() + " = [];\n";
var grammar_token =" '";
for(var i=0, size = words.length; i < size ; ++i){
if(i > 0){
grammar_token += "|";
}
grammar_token += this._prepareToken(words[i]);
}
grammar_token += "' " + token_name + " [* " +
pref + token_name.toLowerCase() + ".push(%match);"
+ "%match = {"
+ this.entry_index_field + ": %offset,"
+ this.entry_type_field + ": '" + token_name.toLowerCase() + "',"
+ this.entry_token_field + ": %match"
+ "}; *];\n";
self.grammar_tokens += grammar_token;
}
},
parseUtterances: function(){
var self = this;
var utt_index = 0;
var json_utterances = this.json_grammar_definition.utterances;
for(var utterance_name in json_utterances){
var utterance_def = json_utterances[utterance_name];
if(utt_index > 0){
self.grammar_phrases += "\n\t|";
}
utt_index++;
self.doParseUtterance(utterance_name, utterance_def);
}
},
doParseUtterance: function(utterance_name, utterance_def){
var grammar_utterance = utterance_name + ":";
var self = this;
self.token_variables += " var " + self.variable_prefix
+ utterance_name.toLowerCase() + " = [];\n";
self.grammar_phrases += utterance_name + " " ;
var phrases = utterance_def.phrases;
var semantic = self.doCreateSemanticInterpretationForUtterance(utterance_name, utterance_def);
for(var index=0,size=phrases.length; index < size; ++index){
if(index > 0){
grammar_utterance += "\n|";
}
var phrase = phrases[index];
var semantic_interpretation = self.doCreateSemanticInterpretationForPhrase(
utterance_name.toLowerCase(), utterance_def, phrase, semantic
);
grammar_utterance += phrase + semantic_interpretation;
}
self.grammar_utterances += grammar_utterance + ";\n\n";
},
doCreateSemanticInterpretationForUtterance: function(utterance_name, utterance_def){
var semantic = utterance_def.semantic,
variable_index, variable_name;
if(logger.isDebug()) logger.debug('doCreateSemanticInterpretationForUtterance: '+semantic);//debug
var semantic_as_string = JSON.stringify(semantic);
if( semantic_as_string != null){
this.variable_regexp.lastIndex = 0;
var variables = this.variable_regexp.exec(semantic_as_string);
while (variables != null) {
var variable = variables[1],
remapped_variable_name = "";
if(logger.isDebug()) logger.debug("variables " + variable, semantic_as_string);//debug
variable_index = /\[(\d+)\]/.exec(variable);
variable_name = new RegExp('_\\$([a-zA-Z_][a-zA-Z0-9_\\-]*)').exec(variable)[1];
// variableObj = /_\$([a-zA-Z_][a-zA-Z0-9_\-]*)(\[(\d+)\])?(\["semantic"\]|\['semantic'\]|\.semantic)?/.exec(variable);
// variableObj = /_\$([a-zA-Z_][a-zA-Z0-9_\-]*)(\[(\d+)\])?((\[(("(.*?[^\\])")|('(.*?[^\\])'))\])|(\.(\w+)))?/.exec(variable);
//"_$NAME[INDEX]['FIELD']": _$NAME [ INDEX ] [" FIELD "] | [' FIELD '] | .FIELD
if (variable_index == null) {
remapped_variable_name = "return " + variable;
} else {
//TODO replace try/catch with safe_acc function
// PROBLEM: currently, the format for variable-access is not well defined
// -> in case of accessing the "semantic" field for a variable reference of another Utterance
// we would need another safe_acc call
// ... i.e. need to parse expression for this, but since the format is not well defined
// we cannot say, for what exactly we should parse...
// NORMAL VAR EXPR: _$a_normal_token[0]
// ACCESS TO SEMANTICS: _$other_utterance[0]['semantic']
// but this could also be expressed e.g. as _$other_utterance[0].semantic
// ...
// remapped_variable_name = variable.replace(
// '[' + variable_index[1] + ']'
// , "[safe_acc("
// + utterance_name.toLowerCase() + "_temp, 'phrases', '"
// + variable_name.toLowerCase() + "', "
// + variable_index[1]
// + ")]"
// );
remapped_variable_name = "var res = _getTok("+utterance_name.toLowerCase() + "_temp['phrases'],'"
+ variable_name.toLowerCase() + "', "
+ variable_index[1]+");"
+ " return typeof res === 'string'? res : (typeof res === 'object' && res? "+variable+" : void(0))";
}
semantic_as_string = semantic_as_string.replace(
variables[0],
//TODO replace try/catch with safe_acc function
" function(){try{ " + remapped_variable_name
+ ";} catch(e){return void(0);}}() "
);
variables = this.variable_regexp.exec(semantic_as_string);
}
}
return semantic_as_string;
},
doCreateSemanticInterpretationForPhrase: function(utterance_name, utterance_def, phrase, semantic_as_string){
var phraseList = phrase.split(/\s+/),
length = phraseList.length,
phrase_name;
// var phraseStr = "";
var i = 0;
var pharseMatchResult = "%% = {"
+ this.entry_index_field + ": "+ this._PARTIAL_MATCH_PREFIX +"1." + this.entry_index_field + ","
+ this.entry_type_field + ": '" + utterance_name + "',"
+ this.entry_token_field + ": null";
var semanticProcResult = "var "+utterance_name+"_temp = {}, tempMatch; "+utterance_name+"_temp['phrases'] = [];";
var num;
for (i = 0; i < length; ++i) {
num = i + 1;
//create STR for semantic processing of phrase
semanticProcResult += "tempMatch = " + this._PARTIAL_MATCH_PREFIX + num + ";"
+ utterance_name + "_temp['phrases'].push(tempMatch);\n\t\t";
}
pharseMatchResult += "}";
semanticProcResult += "%%.tok = " + utterance_name + "_temp['phrases'];"
+ utterance_name + "_temp['phrase']=_tokenList("+utterance_name + "_temp['phrases']).join(' ');\n "
+ utterance_name + "_temp['utterance']='" + utterance_name + "'; "
+ utterance_name + "_temp['engine']='jscc'; "
+ utterance_name + "_temp['semantic'] = " + semantic_as_string
+ "; " + this.variable_prefix + utterance_name + ".push(" + utterance_name + "_temp); "
+ this.variable_prefix + "result = " + utterance_name + "_temp;";
return " [* " + pharseMatchResult + "; " + semanticProcResult + " *]";
},
_prepareToken: function(token){
//need to mask delimiting quotes, i.e. '
return token.replace(/'/g, "\\'");
}
};
return jsccGen;
}); |
import { FeatureService } from '../../../src/openlayers/services/FeatureService';
import { GetFeaturesBySQLParameters } from '../../../src/common/iServer/GetFeaturesBySQLParameters';
import { FetchRequest } from '../../../src/common/util/FetchRequest';
var featureServiceURL = GlobeParameter.dataServiceURL;
var options = {
serverType: 'iServer'
};
describe('openlayers_FeatureService_getFeaturesBySQL', () => {
var serviceResult;
var originalTimeout;
beforeEach(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;
serviceResult = null;
});
afterEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
it('headers', () => {
let myHeaders = new Headers();
var getFeaturesBySQLService = new FeatureService(featureServiceURL, { headers: myHeaders });
expect(getFeaturesBySQLService).not.toBeNull();
expect(getFeaturesBySQLService.options).not.toBeNull();
expect(getFeaturesBySQLService.options.headers).not.toBeNull();
});
//数据集SQL查询服务
it('getFeaturesBySQL', (done) => {
var sqlParam = new GetFeaturesBySQLParameters({
queryParameter: {
name: "Countries@World",
attributeFilter: "SMID = 247"
},
datasetNames: ["World:Countries"]
});
var getFeaturesBySQLService = new FeatureService(featureServiceURL, options);
spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => {
expect(method).toBe("POST");
expect(testUrl).toBe(featureServiceURL + "/featureResults.json?returnContent=true&fromIndex=0&toIndex=19");
var paramsObj = JSON.parse(params.replace(/'/g, "\""));
expect(paramsObj.datasetNames[0]).toBe("World:Countries");
expect(paramsObj.getFeatureMode).toBe("SQL");
expect(paramsObj.queryParameter.attributeFilter).toBe("SMID = 247");
expect(options).not.toBeNull();
return Promise.resolve(new Response(JSON.stringify(getFeaturesResultJson)));
});
getFeaturesBySQLService.getFeaturesBySQL(sqlParam, (result) => {
serviceResult = result;
try {
expect(getFeaturesBySQLService).not.toBeNull();
expect(serviceResult).not.toBeNull();
expect(serviceResult.type).toBe("processCompleted");
expect(serviceResult.result.succeed).toBe(true);
expect(serviceResult.result.featureCount).toEqual(1);
expect(serviceResult.result.totalCount).toEqual(serviceResult.result.featureCount);
expect(serviceResult.result.features.type).toEqual("FeatureCollection");
var features = serviceResult.result.features.features;
expect(features.length).not.toBeNull();
expect(features[0].id).not.toBeNull();
expect(features[0].type).toEqual("Feature");
expect(features[0].properties.CAPITAL).toEqual("利伯维尔");
expect(features[0].geometry.type).toEqual("MultiPolygon");
expect(features[0].geometry.coordinates.length).toBeGreaterThan(0);
expect(features[0].geometry.coordinates[0][0].length).toBeGreaterThan(0);
for (var i = 0; i < features[0].geometry.coordinates[0][0].length; i++) {
expect(features[0].geometry.coordinates[0][0][i].length).toEqual(2);
}
done();
} catch (exception) {
console.log("'getFeaturesBySQL'案例失败" + exception.name + ":" + exception.message);
expect(false).toBeTruthy();
done();
}
});
});
it('GetFeaturesBySQLParameters:targetEpsgCode', done => {
var sqlParam = new GetFeaturesBySQLParameters({
queryParameter: {
name: "Countries@World",
attributeFilter: "SMID = 247"
},
datasetNames: ["World:Countries"],
targetEpsgCode: 4326
});
var getFeaturesBySQLService = new FeatureService(featureServiceURL, options);
spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => {
var paramsObj = JSON.parse(params.replace(/'/g, '"'));
expect(paramsObj.targetEpsgCode).toEqual(4326);
return Promise.resolve(new Response(JSON.stringify(getFeaturesResultJson)));
});
getFeaturesBySQLService.getFeaturesBySQL(sqlParam, (result) => {
serviceResult = result;
done();
});
});
it('GetFeaturesBySQLParameters:targetPrj', done => {
var sqlParam = new GetFeaturesBySQLParameters({
queryParameter: {
name: "Countries@World",
attributeFilter: "SMID = 247"
},
datasetNames: ["World:Countries"],
targetPrj: { "epsgCode": 4326 }
});
var getFeaturesBySQLService = new FeatureService(featureServiceURL, options);
spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => {
var paramsObj = JSON.parse(params.replace(/'/g, '"'));
expect(paramsObj.targetPrj.epsgCode).toEqual(4326);
return Promise.resolve(new Response(JSON.stringify(getFeaturesResultJson)));
});
getFeaturesBySQLService.getFeaturesBySQL(sqlParam, (result) => {
serviceResult = result;
done();
});
});
}); |
# -*- coding: utf-8 -*-
"""This is a generated class and is not intended for modification!
"""
from datetime import datetime
from infobip.util.models import DefaultObject, serializable
from infobip.api.model.Error import Error
from infobip.api.model.Status import Status
from infobip.api.model.Price import Price
class SMSReport(DefaultObject):
@property
@serializable(name="bulkId", type='basestring')
def bulk_id(self):
"""
Property is of type: 'basestring'
"""
return self.get_field_value("bulk_id")
@bulk_id.setter
def bulk_id(self, bulk_id):
"""
Property is of type: 'basestring'
"""
self.set_field_value("bulk_id", bulk_id)
def set_bulk_id(self, bulk_id):
self.bulk_id = bulk_id
return self
@property
@serializable(name="messageId", type='basestring')
def message_id(self):
"""
Property is of type: 'basestring'
"""
return self.get_field_value("message_id")
@message_id.setter
def message_id(self, message_id):
"""
Property is of type: 'basestring'
"""
self.set_field_value("message_id", message_id)
def set_message_id(self, message_id):
self.message_id = message_id
return self
@property
@serializable(name="to", type='basestring')
def to(self):
"""
Property is of type: 'basestring'
"""
return self.get_field_value("to")
@to.setter
def to(self, to):
"""
Property is of type: 'basestring'
"""
self.set_field_value("to", to)
def set_to(self, to):
self.to = to
return self
@property
@serializable(name="from", type='basestring')
def from_(self):
"""
Property is of type: 'basestring'
"""
return self.get_field_value("from_")
@from_.setter
def from_(self, from_):
"""
Property is of type: 'basestring'
"""
self.set_field_value("from_", from_)
def set_from_(self, from_):
self.from_ = from_
return self
@property
@serializable(name="text", type='basestring')
def text(self):
"""
Property is of type: 'basestring'
"""
return self.get_field_value("text")
@text.setter
def text(self, text):
"""
Property is of type: 'basestring'
"""
self.set_field_value("text", text)
def set_text(self, text):
self.text = text
return self
@property
@serializable(name="sentAt", type=datetime)
def sent_at(self):
"""
Property is of type: datetime
"""
return self.get_field_value("sent_at")
@sent_at.setter
def sent_at(self, sent_at):
"""
Property is of type: datetime
"""
self.set_field_value("sent_at", sent_at)
def set_sent_at(self, sent_at):
self.sent_at = sent_at
return self
@property
@serializable(name="doneAt", type=datetime)
def done_at(self):
"""
Property is of type: datetime
"""
return self.get_field_value("done_at")
@done_at.setter
def done_at(self, done_at):
"""
Property is of type: datetime
"""
self.set_field_value("done_at", done_at)
def set_done_at(self, done_at):
self.done_at = done_at
return self
@property
@serializable(name="smsCount", type=int)
def sms_count(self):
"""
Property is of type: int
"""
return self.get_field_value("sms_count")
@sms_count.setter
def sms_count(self, sms_count):
"""
Property is of type: int
"""
self.set_field_value("sms_count", sms_count)
def set_sms_count(self, sms_count):
self.sms_count = sms_count
return self
@property
@serializable(name="mccMnc", type='basestring')
def mcc_mnc(self):
"""
Property is of type: 'basestring'
"""
return self.get_field_value("mcc_mnc")
@mcc_mnc.setter
def mcc_mnc(self, mcc_mnc):
"""
Property is of type: 'basestring'
"""
self.set_field_value("mcc_mnc", mcc_mnc)
def set_mcc_mnc(self, mcc_mnc):
self.mcc_mnc = mcc_mnc
return self
@property
@serializable(name="price", type=Price)
def price(self):
"""
Property is of type: Price
"""
return self.get_field_value("price")
@price.setter
def price(self, price):
"""
Property is of type: Price
"""
self.set_field_value("price", price)
def set_price(self, price):
self.price = price
return self
@property
@serializable(name="status", type=Status)
def status(self):
"""
Property is of type: Status
"""
return self.get_field_value("status")
@status.setter
def status(self, status):
"""
Property is of type: Status
"""
self.set_field_value("status", status)
def set_status(self, status):
self.status = status
return self
@property
@serializable(name="error", type=Error)
def error(self):
"""
Property is of type: Error
"""
return self.get_field_value("error")
@error.setter
def error(self, error):
"""
Property is of type: Error
"""
self.set_field_value("error", error)
def set_error(self, error):
self.error = error
return self
@property
@serializable(name="callbackData", type='basestring')
def callback_data(self):
"""
Property is of type: 'basestring'
"""
return self.get_field_value("callback_data")
@callback_data.setter
def callback_data(self, callback_data):
"""
Property is of type: 'basestring'
"""
self.set_field_value("callback_data", callback_data)
def set_callback_data(self, callback_data):
self.callback_data = callback_data
return self |
/*
Language: Pine
Description: Pine (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions.
Category: common, scripting
*/
export default function (hljs) {
var KEYWORDS = {
keyword:
'var if else for to by return break continue and or not =>',
literal:
'true false na open close high low',
built_in:
'bool int float string color'
};
var NUMBER = {
className: 'number',
variants: [
{ begin: hljs.C_NUMBER_RE }
],
relevance: 0
};
var HEXCOLOR = {
className: 'number', begin: '#[0-9A-Fa-f]+'
};
var PARAMS = {
className: 'params',
begin: /\(/, end: /\)/,
contains: [
NUMBER,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
HEXCOLOR
]
};
return {
name: 'Pine',
aliases: ['pine'],
keywords: KEYWORDS,
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_LINE_COMMENT_MODE,
NUMBER,
HEXCOLOR,
{
className: 'function',
begin: '\\b(?=([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(.+?\\)\\s*=>)',
end: '(?==>)',
illegal: /[${=;\n,]/,
keywords: KEYWORDS,
contains: [
// FUNC_KEYWORD,
hljs.UNDERSCORE_TITLE_MODE,
PARAMS,
]
},
]
};
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i");
this.$outdent = new MatchingBraceOutdent();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.foldingRules = "cStyle";
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
// ignore braces in comments
var tokens = this.$tokenizer.getLineTokens(line, state).tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
var match = line.match(/^.*\{\s*$/);
if (match) {
indent += tab;
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker");
worker.attachToDocument(session.getDocument());
worker.on("csslint", function(e) {
var errors = [];
e.data.forEach(function(message) {
errors.push({
row: message.line - 1,
column: message.col - 1,
text: message.message,
type: message.type,
lint: message
});
});
session.setAnnotations(errors);
});
return worker;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var CssHighlightRules = function() {
var keywordMapper = this.createKeywordMapper({
"support.type": "animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index",
"support.function": "rgb|rgba|url|attr|counter|counters",
"support.constant": "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero",
"support.constant.color": "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow",
"support.constant.fonts": "arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"
}, "text", true);
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))";
var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b";
var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b";
var base_ruleset = [
{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "ruleset_comment"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : ["constant.numeric", "keyword"],
regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"
}, {
token : ["constant.numeric"],
regex : "([0-9]+)"
}, {
token : "constant.numeric", // hex6 color
regex : "#[a-f0-9]{6}"
}, {
token : "constant.numeric", // hex3 color
regex : "#[a-f0-9]{3}"
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"],
regex : pseudoElements
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"],
regex : pseudoClasses
}, {
token : keywordMapper,
regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"
}
];
var ruleset = lang.copyArray(base_ruleset);
ruleset.unshift({
token : "paren.rparen",
regex : "\\}",
next: "start"
});
var media_ruleset = lang.copyArray( base_ruleset );
media_ruleset.unshift({
token : "paren.rparen",
regex : "\\}",
next: "media"
});
var base_comment = [{
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}];
var comment = lang.copyArray(base_comment);
comment.unshift({
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
});
var media_comment = lang.copyArray(base_comment);
media_comment.unshift({
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "media"
});
var ruleset_comment = lang.copyArray(base_comment);
ruleset_comment.unshift({
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "ruleset"
});
this.$rules = {
"start" : [{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "comment"
}, {
token: "paren.lparen",
regex: "\\{",
next: "ruleset"
}, {
token: "string",
regex: "@.*?{",
next: "media"
},{
token: "keyword",
regex: "#[a-z0-9-_]+"
},{
token: "variable",
regex: "\\.[a-z0-9-_]+"
},{
token: "string",
regex: ":[a-z0-9-_]+"
},{
token: "constant",
regex: "[a-z0-9-_]+"
}],
"media" : [ {
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "media_comment"
}, {
token: "paren.lparen",
regex: "\\{",
next: "media_ruleset"
},{
token: "string",
regex: "\\}",
next: "start"
},{
token: "keyword",
regex: "#[a-z0-9-_]+"
},{
token: "variable",
regex: "\\.[a-z0-9-_]+"
},{
token: "string",
regex: ":[a-z0-9-_]+"
},{
token: "constant",
regex: "[a-z0-9-_]+"
}],
"comment" : comment,
"ruleset" : ruleset,
"ruleset_comment" : ruleset_comment,
"media_ruleset" : media_ruleset,
"media_comment" : media_comment
};
};
oop.inherits(CssHighlightRules, TextHighlightRules);
exports.CssHighlightRules = CssHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[2]) {
var range = session.getCommentFoldRange(row, i);
range.end.column -= 2;
return range;
}
var end = {row: row, column: i};
var start = session.$findOpeningBracket(match[1], end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /\S/;
var line = session.getLine(row);
var startLevel = line.search(re);
if (startLevel == -1)
return;
var startColumn = column || line.length;
var maxRow = session.getLength();
var startRow = row;
var endRow = row;
while (++row < maxRow) {
var level = session.getLine(row).search(re);
if (level == -1)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start" && end.row > start.row) {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
|
(function(a,b){if("function"==typeof define&&define.amd)define([],b);else if("undefined"!=typeof exports)b();else{b(),a.FileSaver={exports:{}}.exports}})(this,function(){"use strict";(function(a,b){if("function"==typeof define&&define.amd)define([],b);else if("undefined"!=typeof exports)b();else{b(),a.FileSaver={exports:{}}.exports}})(void 0,function(){function a(a,b){return"undefined"==typeof b?b={autoBom:!1}:"object"!=typeof b&&(console.warn("Deprecated: Expected third argument to be a object"),b={autoBom:!b}),b.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}function b(a,b,c){var d=new XMLHttpRequest;d.open("GET",a),d.responseType="blob",d.onload=function(){f(d.response,b,c)},d.onerror=function(){console.error("could not download file")},d.send()}function c(a,b,c){var d=new XMLHttpRequest;d.open("GET",a,!0),d.onload=function(){var a=200<=d.status&&299>=d.status;a?b():c()};try{d.send()}catch(a){}return 200<=d.status&&299>=d.status}function d(a){try{a.dispatchEvent(new MouseEvent("click"))}catch(c){var b=document.createEvent("MouseEvents");b.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),a.dispatchEvent(b)}}var e="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof global&&global.global===global?global:void 0,f=e.saveAs||("object"!=typeof window||window!==e?function(){}:"download"in HTMLAnchorElement.prototype?function(f,g,h){var i=e.URL||e.webkitURL,j=document.createElement("a");g=g||f.name||"download",j.download=g,j.rel="noopener","string"==typeof f?(j.href=f,j.origin===location.origin?d(j):c(j.href,function(){b(f,g,h)},function(){d(j,j.target="_blank")})):(j.href=i.createObjectURL(f),setTimeout(function(){i.revokeObjectURL(j.href)},4e4),setTimeout(function(){d(j)},0))}:"msSaveOrOpenBlob"in navigator?function(e,f,g){f=f||e.name||"download","string"==typeof e?c(e,function(){b(e,f,g)},function(){var b=document.createElement("a");b.href=e,b.target="_blank",setTimeout(function(){d(b)})}):navigator.msSaveOrOpenBlob(a(e,g),f)}:function(a,c,d,f){if(f=f||open("","_blank"),f&&(f.document.title=f.document.body.innerText="downloading..."),"string"==typeof a)return b(a,c,d);var g="application/octet-stream"===a.type,h=/constructor/i.test(e.HTMLElement)||e.safari,i=/CriOS\/[\d]+/.test(navigator.userAgent);if((i||g&&h)&&"undefined"!=typeof FileReader){var j=new FileReader;j.onloadend=function(){var a=j.result;a=i?a:a.replace(/^data:[^;]*;/,"data:attachment/file;"),f?f.location.href=a:location=a,f=null},j.readAsDataURL(a)}else{var k=e.URL||e.webkitURL,l=k.createObjectURL(a);f?f.location=l:location.href=l,f=null,setTimeout(function(){k.revokeObjectURL(l)},4e4)}});e.saveAs=f.saveAs=f,"undefined"!=typeof module&&(module.exports=f)})});
//# sourceMappingURL=FileSaver.min.js.map |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import division, unicode_literals
from datetime import date, datetime, time
from dateutil.relativedelta import relativedelta
from indico.core.db import db
from indico.modules.rb.models.reservation_occurrences import ReservationOccurrence
from indico.modules.rb.models.reservations import Reservation
from indico.util.date_time import iterdays
WORKING_TIME_PERIODS = ((time(8, 30), time(12, 30)), (time(13, 30), time(17, 30)))
def calculate_rooms_bookable_time(rooms, start_date=None, end_date=None):
if end_date is None:
end_date = date.today() - relativedelta(days=1)
if start_date is None:
start_date = end_date - relativedelta(days=29)
working_time_per_day = sum((datetime.combine(date.today(), end) - datetime.combine(date.today(), start)).seconds
for start, end in WORKING_TIME_PERIODS)
working_days = sum(1 for __ in iterdays(start_date, end_date, skip_weekends=True))
return working_days * working_time_per_day * len(rooms)
def calculate_rooms_booked_time(rooms, start_date=None, end_date=None):
if end_date is None:
end_date = date.today() - relativedelta(days=1)
if start_date is None:
start_date = end_date - relativedelta(days=29)
# Reservations on working days
reservations = Reservation.find(Reservation.room_id.in_(r.id for r in rooms),
db.extract('dow', ReservationOccurrence.start_dt).between(1, 5),
db.cast(ReservationOccurrence.start_dt, db.Date) >= start_date,
db.cast(ReservationOccurrence.end_dt, db.Date) <= end_date,
ReservationOccurrence.is_valid,
_join=ReservationOccurrence)
rsv_start = db.cast(ReservationOccurrence.start_dt, db.TIME)
rsv_end = db.cast(ReservationOccurrence.end_dt, db.TIME)
slots = ((db.cast(start, db.TIME), db.cast(end, db.TIME)) for start, end in WORKING_TIME_PERIODS)
# this basically handles all possible ways an occurrence overlaps with each one of the working time slots
overlaps = sum(db.case([
((rsv_start < start) & (rsv_end > end), db.extract('epoch', end - start)),
((rsv_start < start) & (rsv_end > start) & (rsv_end <= end), db.extract('epoch', rsv_end - start)),
((rsv_start >= start) & (rsv_start < end) & (rsv_end > end), db.extract('epoch', end - rsv_start)),
((rsv_start >= start) & (rsv_end <= end), db.extract('epoch', rsv_end - rsv_start))
], else_=0) for start, end in slots)
return reservations.with_entities(db.func.sum(overlaps)).scalar() or 0
def calculate_rooms_occupancy(rooms, start=None, end=None):
bookable_time = calculate_rooms_bookable_time(rooms, start, end)
booked_time = calculate_rooms_booked_time(rooms, start, end)
return booked_time / bookable_time if bookable_time else 0
|
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
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.
****************************************************************************/
if(cc.sys.isNative)(function(){
var Particle3DTestIdx = -1;
var PARTICLE_SYSTEM_TAG = 0x0001;
jsb.fileUtils.addSearchPath("res/Sprite3DTest");
jsb.fileUtils.addSearchPath("res/Particle3D/materials");
jsb.fileUtils.addSearchPath("res/Particle3D/scripts");
var Particle3DTestDemo = cc.Layer.extend({
_title:"Particle3D Test",
_subtitle:"",
_camera:null,
_particleLabel:null,
_angle:0,
ctor:function () {
this._super();
},
//
// Menu
//
onEnter:function () {
this._super();
var label = new cc.LabelTTF(this._title, "Arial", 28);
this.addChild(label, 100, BASE_TEST_TITLE_TAG);
label.x = winSize.width / 2;
label.y = winSize.height - 50;
var label2 = new cc.LabelTTF(this._subtitle, "Thonburi", 16);
this.addChild(label2, 101, BASE_TEST_SUBTITLE_TAG);
label2.x = winSize.width / 2;
label2.y = winSize.height - 80;
var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.onBackCallback, this);
var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.onRestartCallback, this);
var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.onNextCallback, this);
item1.tag = BASE_TEST_MENUITEM_PREV_TAG;
item2.tag = BASE_TEST_MENUITEM_RESET_TAG;
item3.tag = BASE_TEST_MENUITEM_NEXT_TAG;
var menu = new cc.Menu(item1, item2, item3);
menu.x = 0;
menu.y = 0;
var width = item2.width, height = item2.height;
item1.x = winSize.width/2 - width*2;
item1.y = height/2 ;
item2.x = winSize.width/2;
item2.y = height/2 ;
item3.x = winSize.width/2 + width*2;
item3.y = height/2 ;
this.addChild(menu, 102, BASE_TEST_MENU_TAG);
var size = cc.winSize;
this._camera = new cc.Camera(cc.Camera.Mode.PERSPECTIVE, 30.0, size.width / size.height, 1.0, 1000.0);
this._camera.setPosition3D(cc.math.vec3(0, 0, 100));
this._camera.lookAt(cc.math.vec3(0, 0, 0), cc.math.vec3(0, 1, 0));
this._camera.setCameraFlag(cc.CameraFlag.USER1);
this.addChild(this._camera);
var ttfconfig = {outlineSize:0, fontSize:15, glyphs:0, customGlyphs:"", fontFilePath:"fonts/tahoma.ttf"};
this._particleLabel = cc.Label.createWithTTF(ttfconfig, "Particle count: 0");
this._particleLabel.setPosition(0, size.height/6);
this._particleLabel.setAnchorPoint(cc.p(0, 0));
this.addChild(this._particleLabel);
cc.eventManager.addListener({
event:cc.EventListener.TOUCH_ALL_AT_ONCE,
onTouchesMoved:this.onTouchesMoved.bind(this)
}, this);
this.scheduleUpdate();
},
onTouchesMoved:function(touches, event){
var touch = touches[0];
var delta = touch.getDelta();
this._angle -= cc.degreesToRadians(delta.x);
this._camera.setPosition3D(cc.math.vec3(100*Math.sin(this._angle), 0, 100*Math.cos(this._angle)));
this._camera.lookAt(cc.math.vec3(0, 0, 0), cc.math.vec3(0, 1, 0));
},
update:function(dt){
var ps = this.getChildByTag(PARTICLE_SYSTEM_TAG);
if(ps){
var count = 0;
var children = ps.children;
for(var i = 0; i < children.length; ++i){
var child = children[i];
if(child && child.getAliveParticleCount)
count += child.getAliveParticleCount();
}
this._particleLabel.setString("Particle Count: "+count);
}
},
onRestartCallback:function (sender) {
var s = new Particle3DTestScene();
s.addChild(restartParticle3DTest());
director.runScene(s);
},
onNextCallback:function (sender) {
var s = new Particle3DTestScene();
s.addChild(nextParticle3DTest());
director.runScene(s);
},
onBackCallback:function (sender) {
var s = new Particle3DTestScene();
s.addChild(previousParticle3DTest());
director.runScene(s);
}
});
Particle3DTestScene = cc.Scene.extend({
ctor:function () {
this._super();
var label = new cc.LabelTTF("Main Menu", "Arial", 20);
var menuItem = new cc.MenuItemLabel(label, this.onMainMenuCallback, this);
var menu = new cc.Menu(menuItem);
menu.x = 0;
menu.y = 0;
menuItem.x = winSize.width - 50;
menuItem.y = 25;
this.addChild(menu);
},
onMainMenuCallback:function () {
var scene = new cc.Scene();
var layer = new TestController();
scene.addChild(layer);
director.runScene(scene);
},
runThisTest:function (num) {
Particle3DTestIdx = (num || num == 0) ? (num - 1) : -1;
var layer = nextParticle3DTest();
this.addChild(layer);
director.runScene(this);
}
});
var Particle3DExplosionSystemDemo = Particle3DTestDemo.extend({
_subtitle:"ExplosionSystem",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("explosionSystem.pu");
rootps.setCameraMask(cc.CameraFlag.USER1);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DLineStreakDemo = Particle3DTestDemo.extend({
_subtitle:"LineStreak",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("lineStreak.pu", "pu_mediapack_01.material");
rootps.setCameraMask(2);
rootps.setScale(5);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DBlackHoleDemo = Particle3DTestDemo.extend({
_subtitle:"BlackHole",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("blackHole.pu", "pu_mediapack_01.material");
rootps.setCameraMask(2);
rootps.runAction(cc.sequence(
cc.moveBy(2, cc.p(50, 0)),
cc.moveBy(2, cc.p(-50, 0))
).repeatForever());
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DHypnoDemo = Particle3DTestDemo.extend({
_subtitle:"Hypno",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("hypno.pu", "pu_mediapack_01.material");
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DAdvancedLodSystemDemo = Particle3DTestDemo.extend({
_subtitle:"AdvancedSystem",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("advancedLodSystem.pu");
rootps.setCameraMask(2);
rootps.runAction(cc.rotateBy(1, cc.math.vec3(0, 0, 100)).repeatForever());
var scale = cc.scaleBy(1, 2, 2, 2);
rootps.runAction(cc.sequence(scale, scale.reverse()).repeatForever());
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DTimeShiftDemo = Particle3DTestDemo.extend({
_subtitle:"TimeShift",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("timeShift.pu", "pu_mediapack_01.material");
rootps.setScale(2);
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DUVAnimDemo = Particle3DTestDemo.extend({
_subtitle:"UVAnim",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("UVAnimation.pu", "pu_mediapack_01.material");
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DFirePlaceDemo = Particle3DTestDemo.extend({
_subtitle:"Fire",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("mp_torch.pu", "pu_mediapack_01.material");
rootps.setScale(5);
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DElectricBeamSystemDemo = Particle3DTestDemo.extend({
_subtitle:"ElectricBeamSystem",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("electricBeamSystem.pu");
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DFlareShieldDemo = Particle3DTestDemo.extend({
_subtitle:"flareShield",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("flareShield.pu");
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DLightningBoltDemo = Particle3DTestDemo.extend({
_subtitle:"LightningBolt",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("lightningBolt.pu");
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DCanOfWormsDemo = Particle3DTestDemo.extend({
_subtitle:"CanOfWorms",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("canOfWorms.pu");
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DRibbonTrailDemo = Particle3DTestDemo.extend({
_subtitle:"RibbonTrailTest",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("ribbonTrailTest.pu");
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DWeaponTrailDemo = Particle3DTestDemo.extend({
_subtitle:"WeaponTrail",
ctor:function(){
this._super();
var rootps = jsb.PUParticleSystem3D.create("weaponTrail.pu");
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
});
var Particle3DWithSprite3DDemo = Particle3DTestDemo.extend({
_subtitle:"Particle with Sprite3D",
ctor:function(){
this._super();
var c3bfileName = "Sprite3DTest/orc.c3b";
var sprite = new jsb.Sprite3D(c3bfileName);
this.addChild(sprite);
sprite.setPosition3D(cc.math.vec3(-20, 0, 0));
sprite.setRotation3D(cc.math.vec3(0, 180, 0));
sprite.setCameraMask(2);
var animation = new jsb.Animation3D(c3bfileName);
if(animation){
var animate = new jsb.Animate3D(animation);
sprite.runAction(cc.repeatForever(animate));
}
var billboard = new jsb.BillBoard("Images/Icon.png");
billboard.setPosition3D(cc.math.vec3(20, 0, 0));
billboard.setScale(0.2);
billboard.setCameraMask(2);
this.addChild(billboard);
var rootps = jsb.PUParticleSystem3D.create("lineStreak.pu");
rootps.setCameraMask(2);
rootps.startParticleSystem();
this.addChild(rootps, 0, PARTICLE_SYSTEM_TAG);
}
})
//
// Flow control
//
var arrayOfParticle3DTest = [
Particle3DExplosionSystemDemo,
Particle3DLineStreakDemo,
Particle3DBlackHoleDemo,
Particle3DHypnoDemo,
Particle3DAdvancedLodSystemDemo,
Particle3DTimeShiftDemo,
Particle3DUVAnimDemo,
Particle3DFirePlaceDemo,
Particle3DElectricBeamSystemDemo,
Particle3DFlareShieldDemo,
Particle3DLightningBoltDemo,
Particle3DCanOfWormsDemo,
Particle3DRibbonTrailDemo,
Particle3DWeaponTrailDemo,
Particle3DWithSprite3DDemo
];
var nextParticle3DTest = function () {
Particle3DTestIdx++;
Particle3DTestIdx = Particle3DTestIdx % arrayOfParticle3DTest.length;
return new arrayOfParticle3DTest[Particle3DTestIdx ]();
};
var previousParticle3DTest = function () {
Particle3DTestIdx--;
if (Particle3DTestIdx < 0)
Particle3DTestIdx += arrayOfParticle3DTest.length;
return new arrayOfParticle3DTest[Particle3DTestIdx ]();
};
var restartParticle3DTest = function () {
return new arrayOfParticle3DTest[Particle3DTestIdx ]();
};
})();
|
'use strict'
var mongoosePaginate = require('mongoose-pagination');
var UsersFB = require('../models/usersfb');
var FanPages = require('../models/fanpages');
var Responds = require('../models/responds');
var responseInboxC = require('./responseInbox');
var InboxSend = require('../models/inboxsends');
var graph = require('fbgraph');
function xlog(x){
console.log(x);
}
function responseInbox(id_fanpage , id_user , mid , msj){
xlog("responseInbox");
var dataOr = { $or:[ {uuid_1:id_user}, {uuid_2:id_user}, {uuid_3:id_user}, {uuid_4:id_user}, {uuid_5:id_user} ] };
UsersFB.findOne(dataOr , (err , regFind) => {
if(!err){
if(regFind){
if(regFind.first_name != '' && regFind.first_name != '' && regFind.status_answer == true){
FanPages.findOne({uuid:id_fanpage} , (err , regFindFP) => {
if(!err){
if(regFindFP){
var token = regFindFP.token;
var idUser = regFind._id;
var idFanPage = regFindFP._id;
actionResponseInbox(id_fanpage , id_user , mid , msj , token , idUser , idFanPage);
}
}
});
} else {
FanPages.findOne({uuid:id_fanpage} , (err , regFindFP) => {
if(!err){
if(regFindFP){
var token = regFindFP.token;
var idUser = regFind._id;
var idFanPage = regFindFP._id;
var url = id_user+'?fields=id,first_name,last_name,name,gender,profile_pic,locale,timezone';
graph.get(url, {access_token: token}, function(err, resFB){
if(err){
UsersFB.update(dataOr, {uuid_1:id_user , status_answer:true , status:true}, { multi: true }, (err , regUpdate) => {});
} else {
var dataUpdate = {
first_name: resFB.first_name,
last_name: resFB.last_name,
gender: resFB.gender,
profile_pic: resFB.profile_pic,
locale: resFB.locale,
timezone: resFB.timezone,
status_answer: true,
status: true
};
UsersFB.update(dataOr, dataUpdate, { multi: true }, (err , regUpdate) => {});
}
actionResponseInbox(id_fanpage , id_user , mid , msj , token , idUser , idFanPage);
});
}
}
});
}
} else {
// No existe el user
FanPages.findOne({uuid:id_fanpage} , (err , regFindFP) => {
if(!err){
if(regFindFP){
var token = regFindFP.token;
var idUser = 0;
var idFanPage = regFindFP._id;
var usersfb = new UsersFB();
usersfb.id_fanpage = regFindFP._id;
var url = id_user+'?fields=id,first_name,last_name,name,gender,profile_pic,locale,timezone';
graph.get(url, {access_token: token}, function(err, resFB){
if(err){
usersfb.uuid_1 = id_user;
usersfb.status_answer = true;
usersfb.status = true;
} else {
usersfb.uuid_1 = id_user;
usersfb.first_name = resFB.first_name;
usersfb.last_name = resFB.last_name;
usersfb.gender = resFB.gender;
usersfb.profile_pic = resFB.profile_pic;
usersfb.locale = resFB.locale;
usersfb.timezone = resFB.timezone;
usersfb.status_answer = true;
usersfb.status = true;
}
usersfb.save((err , regStored) => {
if(!err){
if(regStored){
actionResponseInbox(id_fanpage , id_user , mid , msj , token , regStored._id , idFanPage);
}
}
});
});
}
}
});
}
}
});
}
function actionResponseInbox(id_fanpage , id_user , mid , msj , token , idUser , idFanPage){
xlog("actionResponseInbox");
var responds = new Responds();
responds.id_fanpage = idFanPage;
responds.id_user = idUser;
responds.mid = mid;
responds.msg = msj;
responds.save((err , regStored) => {
if(!err){
if(regStored){
respondedInbox(id_fanpage , id_user)
responseInboxC.Init(idFanPage , idUser , regStored._id , mid , msj , token , id_fanpage , id_user);
}
}
});
}
function readInbox(id_fanpage , id_user){
xlog("readInbox");
var dataOr = { $or:[ {uuid_1:id_user}, {uuid_2:id_user}, {uuid_3:id_user}, {uuid_4:id_user}, {uuid_5:id_user} ] };
UsersFB.findOne(dataOr , (err , regFind) => {
if(!err){
if(regFind){
var id_user = regFind._id;
var id_fanpage = regFind.id_fanpage;
InboxSend.findOne({id_user:id_user , id_fanpage:id_fanpage , status_read: false}).sort({ field: 'desc', date: -1 }).paginate(1 , 1 , function(err , regs , total){
if(!err){
if(total > 0){
InboxSend.findByIdAndUpdate(regs._id , {status_read:true} , (err , regUpdate) => {});
}
}
});
}
}
});
}
function respondedInbox(id_fanpage , id_user){
xlog("respondedInbox");
var dataOr = { $or:[ {uuid_1:id_user}, {uuid_2:id_user}, {uuid_3:id_user}, {uuid_4:id_user}, {uuid_5:id_user} ] };
UsersFB.findOne(dataOr , (err , regFind) => {
if(!err){
if(regFind){
var id_user = regFind._id;
var id_fanpage = regFind.id_fanpage;
InboxSend.findOne({id_user:id_user , id_fanpage:id_fanpage , status_response: false}).sort({ field: 'desc', date: -1 }).paginate(1 , 1 , function(err , regs , total){
if(!err){
if(total > 0){
InboxSend.findByIdAndUpdate(regs._id , {status_response:true} , (err , regUpdate) => {});
}
}
});
}
}
});
}
module.exports = {
responseInbox,
actionResponseInbox,
readInbox
}; |
import Client from "shopify-buy";
import {
INITIAL_CLIENT,
ADD_TO_CHECKOUT,
} from "../actions/shopifyCheckoutAction";
const initState = {
client: {},
checkout: {},
checkoutId: "",
};
const shopifyCheckoutReducer = (state = initState, action) => {
switch (action.type) {
case INITIAL_CLIENT:
return {
...state,
client: action.payload,
};
case ADD_TO_CHECKOUT:
const checkout = addToCheckout(state, action.payload);
return {
...state,
checkout: checkout,
checkoutId: checkout.id,
};
default:
return state;
}
};
const addToCheckout = async (state, item) => {
// const client = state.client;
const client = Client.buildClient({
storefrontAccessToken: process.env.GATSBY_ACCESS_TOKEN,
domain: `${process.env.GATSBY_SHOP_NAME}.myshopify.com`,
});
let checkoutId = state.checkoutId || "";
let checkout;
console.log(checkoutId);
if (checkoutId === "") {
checkout = await client.checkout
.create()
.then(checkout => updateCheckout(client, checkout, item));
} else {
checkout = await client.checkout
.fetch(checkoutId)
.then(checkout => updateCheckout(client, checkout, item));
}
console.log(checkout);
return checkout;
};
const updateCheckout = async (client, checkout, item) => {
// const client = state.client;
const variantId = item.variants[0].shopifyId;
const lineItemsToAdd = [
{
variantId,
quantity: 1,
},
];
return client.checkout
.addLineItems(checkout.id, lineItemsToAdd)
.then(checkout => {
console.log(checkout.lineItems);
return checkout;
});
};
export default shopifyCheckoutReducer;
|
import numpy as np
def init(mdlParams_):
mdlParams = {}
# Save summaries and model here
mdlParams['saveDir'] = './models/model_ham_effb2_aug0_drop'
mdlParams['model_load_path'] = ''
# Data is loaded from here
mdlParams['dataDir'] = './Data'
mdlParams['with_meta'] = False
mdlParams['meta_path'] = './ham_meta.pkl'
### Model Selection ###
mdlParams['model_type'] = 'efficientnet-b2'
mdlParams['numClasses'] = 7
mdlParams['balance_classes'] = 7
mdlParams['numOut'] = mdlParams['numClasses']
# Scale up for b1-b7
mdlParams['crop_size'] = [300, 300]
mdlParams['input_size'] = [260, 260, 3]
mdlParams['focal_loss'] = True
### Training Parameters ###
# Batch size
mdlParams['batchSize'] = 20 # *len(mdlParams['numGPUs'])
# Initial learning rate
mdlParams['learning_rate'] = 0.000015 # *len(mdlParams['numGPUs'])
# Lower learning rate after no improvement over 100 epochs
mdlParams['lowerLRAfter'] = 25
# If there is no validation set, start lowering the LR after X steps
mdlParams['lowerLRat'] = 50
# Divide learning rate by this value
mdlParams['LRstep'] = 5
# Maximum number of training iterations
mdlParams['training_steps'] = 60
# Display error every X steps
mdlParams['display_step'] = 2
# Scale?
mdlParams['scale_targets'] = False
# Peak at test error during training? (generally, dont do this!)
mdlParams['peak_at_testerr'] = False
# Print trainerr
mdlParams['print_trainerr'] = False
# Subtract trainset mean?
mdlParams['subtract_set_mean'] = False
mdlParams['setMean'] = np.array([0.0, 0.0, 0.0])
mdlParams['setStd'] = np.array([1.0, 1.0, 1.0])
# Cross validation
mdlParams['fold'] = 5
# Data AUG
# mdlParams['full_color_distort'] = True
mdlParams['autoaugment'] = False
#mdlParams['flip_lr_ud'] = True
#mdlParams['full_rot'] = 180
#mdlParams['scale'] = (0.8, 1.2)
#mdlParams['shear'] = 10
#mdlParams['cutout'] = 16
mdlParams['only_downsmaple'] = True
# Meta settings
mdlParams['meta_features'] = ['age_0.0', 'age_5.0',
'age_10.0', 'age_15.0', 'age_20.0', 'age_25.0', 'age_30.0', 'age_35.0',
'age_40.0', 'age_45.0', 'age_50.0', 'age_55.0', 'age_60.0', 'age_65.0',
'age_70.0', 'age_75.0', 'age_80.0', 'age_85.0', 'sex_female',
'sex_male', 'sex_unknown', 'localization_abdomen', 'localization_acral',
'localization_back', 'localization_chest', 'localization_ear',
'localization_face', 'localization_foot', 'localization_genital',
'localization_hand', 'localization_lower extremity',
'localization_neck', 'localization_scalp', 'localization_trunk',
'localization_unknown', 'localization_upper extremity']
mdlParams['fc_layers_before'] = [256, 256]
# Factor for scaling up the FC layer
scale_up_with_larger_b = 1.0
mdlParams['fc_layers_after'] = [int(1024 * scale_up_with_larger_b)]
mdlParams['freeze_cnn'] = False
mdlParams['learning_rate_meta'] = 0.00001
# Normal dropout in fc layers
mdlParams['dropout_meta'] = 0.4
return mdlParams
|
module.exports = () => require("./webpack.all.config");
|
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import {
GraphQLEnumType,
GraphQLInterfaceType,
GraphQLObjectType,
GraphQLList,
GraphQLNonNull,
GraphQLSchema,
GraphQLString,
} from '../type';
import { getFriends, getHero, getHuman, getDroid } from './starWarsData.js';
/**
* This is designed to be an end-to-end test, demonstrating
* the full GraphQL stack.
*
* We will create a GraphQL schema that describes the major
* characters in the original Star Wars trilogy.
*
* NOTE: This may contain spoilers for the original Star
* Wars trilogy.
*/
/**
* Using our shorthand to describe type systems, the type system for our
* Star Wars example is:
*
* enum Episode { NEWHOPE, EMPIRE, JEDI }
*
* interface Character {
* id: String!
* name: String
* friends: [Character]
* appearsIn: [Episode]
* }
*
* type Human : Character {
* id: String!
* name: String
* friends: [Character]
* appearsIn: [Episode]
* homePlanet: String
* }
*
* type Droid : Character {
* id: String!
* name: String
* friends: [Character]
* appearsIn: [Episode]
* primaryFunction: String
* }
*
* type Query {
* hero(episode: Episode): Character
* human(id: String!): Human
* droid(id: String!): Droid
* }
*
* We begin by setting up our schema.
*/
/**
* The original trilogy consists of three movies.
*
* This implements the following type system shorthand:
* enum Episode { NEWHOPE, EMPIRE, JEDI }
*/
const episodeEnum = new GraphQLEnumType({
name: 'Episode',
description: 'One of the films in the Star Wars Trilogy',
values: {
NEWHOPE: {
value: 4,
description: 'Released in 1977.',
},
EMPIRE: {
value: 5,
description: 'Released in 1980.',
},
JEDI: {
value: 6,
description: 'Released in 1983.',
},
}
});
/**
* Characters in the Star Wars trilogy are either humans or droids.
*
* This implements the following type system shorthand:
* interface Character {
* id: String!
* name: String
* friends: [Character]
* appearsIn: [Episode]
* }
*/
const characterInterface = new GraphQLInterfaceType({
name: 'Character',
description: 'A character in the Star Wars Trilogy',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLString),
description: 'The id of the character.',
},
name: {
type: GraphQLString,
description: 'The name of the character.',
},
friends: {
type: new GraphQLList(characterInterface),
description: 'The friends of the character, or an empty list if they ' +
'have none.',
},
appearsIn: {
type: new GraphQLList(episodeEnum),
description: 'Which movies they appear in.',
},
}),
resolveType: character => {
return getHuman(character.id) ? humanType : droidType;
}
});
/**
* We define our human type, which implements the character interface.
*
* This implements the following type system shorthand:
* type Human : Character {
* id: String!
* name: String
* friends: [Character]
* appearsIn: [Episode]
* }
*/
const humanType = new GraphQLObjectType({
name: 'Human',
description: 'A humanoid creature in the Star Wars universe.',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLString),
description: 'The id of the human.',
},
name: {
type: GraphQLString,
description: 'The name of the human.',
},
friends: {
type: new GraphQLList(characterInterface),
description: 'The friends of the human, or an empty list if they ' +
'have none.',
resolve: human => getFriends(human),
},
appearsIn: {
type: new GraphQLList(episodeEnum),
description: 'Which movies they appear in.',
},
homePlanet: {
type: GraphQLString,
description: 'The home planet of the human, or null if unknown.',
},
}),
interfaces: [ characterInterface ]
});
/**
* The other type of character in Star Wars is a droid.
*
* This implements the following type system shorthand:
* type Droid : Character {
* id: String!
* name: String
* friends: [Character]
* appearsIn: [Episode]
* primaryFunction: String
* }
*/
const droidType = new GraphQLObjectType({
name: 'Droid',
description: 'A mechanical creature in the Star Wars universe.',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLString),
description: 'The id of the droid.',
},
name: {
type: GraphQLString,
description: 'The name of the droid.',
},
friends: {
type: new GraphQLList(characterInterface),
description: 'The friends of the droid, or an empty list if they ' +
'have none.',
resolve: droid => getFriends(droid),
},
appearsIn: {
type: new GraphQLList(episodeEnum),
description: 'Which movies they appear in.',
},
primaryFunction: {
type: GraphQLString,
description: 'The primary function of the droid.',
},
}),
interfaces: [ characterInterface ]
});
/**
* This is the type that will be the root of our query, and the
* entry point into our schema. It gives us the ability to fetch
* objects by their IDs, as well as to fetch the undisputed hero
* of the Star Wars trilogy, R2-D2, directly.
*
* This implements the following type system shorthand:
* type Query {
* hero(episode: Episode): Character
* human(id: String!): Human
* droid(id: String!): Droid
* }
*
*/
const queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
hero: {
type: characterInterface,
args: {
episode: {
description: 'If omitted, returns the hero of the whole saga. If ' +
'provided, returns the hero of that particular episode.',
type: episodeEnum
}
},
resolve: (root, { episode }) => getHero(episode),
},
human: {
type: humanType,
args: {
id: {
description: 'id of the human',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }) => getHuman(id),
},
droid: {
type: droidType,
args: {
id: {
description: 'id of the droid',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }) => getDroid(id),
},
})
});
/**
* Finally, we construct our schema (whose starting query type is the query
* type we defined above) and export it.
*/
export const StarWarsSchema = new GraphQLSchema({
query: queryType,
types: [ humanType, droidType ]
});
|
export default {
intersectionObserverThreshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1],
} |
(function () {
'use strict';
/**
* Chain to fetch module
* https://github.com/johnpapa/angular-styleguide#style-y022
*/
angular
.module('app.providers')
.service('myService', MyService);
/**
* Avoid anonymous functions as callbacks
* https://github.com/johnpapa/angular-styleguide#style-y024
*/
/* @ngInject */
function MyService() {
/**
* Accessible members at top
* https://github.com/johnpapa/angular-styleguide#style-y052
*/
this.publicMethod = _publicMethod;
_initialize();
////////////
/**
* startup logic goes here
* https://github.com/johnpapa/angular-styleguide#style-y080
*/
function _initialize() {
}
function _publicMethod() {
return true;
}
}
})();
|
const { resolve } = require('url');
const cheerio = require('cheerio');
const axios = require('@/utils/axios');
const iconv = require('iconv-lite');
const load = ($, baseUrl) => {
const num = $.next('font').text();
const pages = Number.parseInt(/\d+/.exec(num)[0], 10);
let description = '';
for (let page = 1; page <= pages; page++) {
description += `<img referrerpolicy="no-referrer" src="${baseUrl}/${String(page).padStart(3, '0')}.jpg" /></br>`;
}
return {
description,
};
};
const getChapters = async (id, $, caches) => {
const chapters = $('#info')
.eq(1)
.find('a');
return await Promise.all(
chapters
.slice(chapters.length - 10, chapters.length)
.map(async (_, ele) => {
const a = $(ele);
const link = resolve('https://www.cartoonmad.com/', a.attr('href'));
const title = a.text();
const single = {
link,
title,
};
const other = await caches.tryGet(link, async () => await load(a, `https://www.cartoonmad.com/home75458/${id}/${title.split(' ')[1]}`));
return Promise.resolve(Object.assign({}, single, other));
})
.toArray()
.reverse()
);
};
module.exports = async (ctx) => {
const { id } = ctx.params;
const { data } = await axios.get(`https://www.cartoonmad.com/comic/${id}`, {
responseType: 'arraybuffer',
headers: {
Host: 'www.cartoonmad.com',
Referer: 'https://www.cartoonmad.com/',
},
});
const content = iconv.decode(new Buffer.from(data), 'big5');
const $ = cheerio.load(content);
const bookTitle = $('title')
.text()
.match(/\S+/)[0];
const bookIntro = $('#info')
.eq(0)
.find('td')
.text()
.trim();
// const coverImgSrc = $('.cover')
// .parent()
// .find('img')
// .attr('src');
const chapters = await getChapters(id, $, ctx.cache);
ctx.state.data = {
title: `動漫狂 - ${bookTitle}`,
link: `https://www.cartoonmad.com/comic/${id}`,
description: bookIntro,
item: chapters,
};
};
|
import { expect } from 'chai';
import addDays from 'date-fns/addDays';
import addMonths from 'date-fns/addMonths';
import addYears from 'date-fns/addYears';
import isBeforeDay from '../../src/utils/isBeforeDay';
const today = new Date();
const tomorrow = addDays(new Date(), 1);
describe('isBeforeDay', () => {
it('returns true if first arg is before the second but have same month and year', () => {
expect(isBeforeDay(today, tomorrow)).to.equal(true);
});
it('returns true if first arg is before the second but have same day and year', () => {
expect(isBeforeDay(today, addYears(new Date(), 1))).to.equal(true);
});
it('returns true if first arg is before the second but have same day and month', () => {
expect(isBeforeDay(today, addMonths(new Date(), 1))).to.equal(true);
});
it('returns false if args are the same day', () => {
expect(isBeforeDay(today, today)).to.equal(false);
});
it('returns false if first arg is after the second', () => {
expect(isBeforeDay(tomorrow, today)).to.equal(false);
});
describe('non-Date object arguments', () => {
it('is false if first argument is not a Date object', () => {
expect(isBeforeDay(null, today)).to.equal(false);
});
it('is false if second argument is not a Date object', () => {
expect(isBeforeDay(today, 'foo')).to.equal(false);
});
});
});
|
sweetApp.directive("sidebar", function() {
return {
restrict: 'E',
replace: true,
templateUrl : "js/directives/sidebar.html"
};
}); |
from __future__ import division
from collections import defaultdict
import random
import numpy as np
from albumentations.augmentations.keypoints_utils import KeypointsProcessor
from albumentations.core.serialization import SerializableMeta, get_shortest_class_fullname
from albumentations.core.six import add_metaclass
from albumentations.core.transforms_interface import DualTransform
from albumentations.core.utils import format_args, Params
from albumentations.augmentations.bbox_utils import BboxProcessor
from albumentations.core.serialization import SERIALIZABLE_REGISTRY, instantiate_lambda
__all__ = ["Compose", "OneOf", "OneOrOther", "BboxParams", "KeypointParams", "ReplayCompose", "Sequential"]
REPR_INDENT_STEP = 2
class Transforms:
def __init__(self, transforms):
self.transforms = transforms
self.start_end = self._find_dual_start_end(transforms)
def _find_dual_start_end(self, transforms):
dual_start_end = None
last_dual = None
for idx, transform in enumerate(transforms):
if isinstance(transform, DualTransform):
last_dual = idx
if dual_start_end is None:
dual_start_end = [idx]
if isinstance(transform, BaseCompose):
inside = self._find_dual_start_end(transform)
if inside is not None:
last_dual = idx
if dual_start_end is None:
dual_start_end = [idx]
if dual_start_end is not None:
dual_start_end.append(last_dual)
return dual_start_end
def get_always_apply(self, transforms):
new_transforms = []
for transform in transforms:
if isinstance(transform, BaseCompose):
new_transforms.extend(self.get_always_apply(transform))
elif transform.always_apply:
new_transforms.append(transform)
return Transforms(new_transforms)
def __getitem__(self, item):
return self.transforms[item]
def set_always_apply(transforms):
for t in transforms:
t.always_apply = True
@add_metaclass(SerializableMeta)
class BaseCompose:
def __init__(self, transforms, p):
self.transforms = Transforms(transforms)
self.p = p
self.replay_mode = False
self.applied_in_replay = False
def __getitem__(self, item):
return self.transforms[item]
def __repr__(self):
return self.indented_repr()
def indented_repr(self, indent=REPR_INDENT_STEP):
args = {k: v for k, v in self._to_dict().items() if not (k.startswith("__") or k == "transforms")}
repr_string = self.__class__.__name__ + "(["
for t in self.transforms:
repr_string += "\n"
if hasattr(t, "indented_repr"):
t_repr = t.indented_repr(indent + REPR_INDENT_STEP)
else:
t_repr = repr(t)
repr_string += " " * indent + t_repr + ","
repr_string += "\n" + " " * (indent - REPR_INDENT_STEP) + "], {args})".format(args=format_args(args))
return repr_string
@classmethod
def get_class_fullname(cls):
return get_shortest_class_fullname(cls)
def _to_dict(self):
return {
"__class_fullname__": self.get_class_fullname(),
"p": self.p,
"transforms": [t._to_dict() for t in self.transforms], # skipcq: PYL-W0212
}
def get_dict_with_id(self):
return {
"__class_fullname__": self.get_class_fullname(),
"id": id(self),
"params": None,
"transforms": [t.get_dict_with_id() for t in self.transforms],
}
def add_targets(self, additional_targets):
if additional_targets:
for t in self.transforms:
t.add_targets(additional_targets)
def set_deterministic(self, flag, save_key="replay"):
for t in self.transforms:
t.set_deterministic(flag, save_key)
class Compose(BaseCompose):
"""Compose transforms and handle all transformations regarding bounding boxes
Args:
transforms (list): list of transformations to compose.
bbox_params (BboxParams): Parameters for bounding boxes transforms
keypoint_params (KeypointParams): Parameters for keypoints transforms
additional_targets (dict): Dict with keys - new target name, values - old target name. ex: {'image2': 'image'}
p (float): probability of applying all list of transforms. Default: 1.0.
"""
def __init__(self, transforms, bbox_params=None, keypoint_params=None, additional_targets=None, p=1.0):
super(Compose, self).__init__([t for t in transforms if t is not None], p)
self.processors = {}
if bbox_params:
if isinstance(bbox_params, dict):
params = BboxParams(**bbox_params)
elif isinstance(bbox_params, BboxParams):
params = bbox_params
else:
raise ValueError("unknown format of bbox_params, please use `dict` or `BboxParams`")
self.processors["bboxes"] = BboxProcessor(params, additional_targets)
if keypoint_params:
if isinstance(keypoint_params, dict):
params = KeypointParams(**keypoint_params)
elif isinstance(keypoint_params, KeypointParams):
params = keypoint_params
else:
raise ValueError("unknown format of keypoint_params, please use `dict` or `KeypointParams`")
self.processors["keypoints"] = KeypointsProcessor(params, additional_targets)
if additional_targets is None:
additional_targets = {}
self.additional_targets = additional_targets
for proc in self.processors.values():
proc.ensure_transforms_valid(self.transforms)
self.add_targets(additional_targets)
def __call__(self, *args, force_apply=False, **data):
if args:
raise KeyError("You have to pass data to augmentations as named arguments, for example: aug(image=image)")
self._check_args(**data)
assert isinstance(force_apply, (bool, int)), "force_apply must have bool or int type"
need_to_run = force_apply or random.random() < self.p
for p in self.processors.values():
p.ensure_data_valid(data)
transforms = self.transforms if need_to_run else self.transforms.get_always_apply(self.transforms)
dual_start_end = transforms.start_end if self.processors else None
check_each_transform = any(
getattr(item.params, "check_each_transform", False) for item in self.processors.values()
)
for idx, t in enumerate(transforms):
if dual_start_end is not None and idx == dual_start_end[0]:
for p in self.processors.values():
p.preprocess(data)
data = t(force_apply=force_apply, **data)
if dual_start_end is not None and idx == dual_start_end[1]:
for p in self.processors.values():
p.postprocess(data)
elif check_each_transform and isinstance(t, DualTransform):
rows, cols = data["image"].shape[:2]
for p in self.processors.values():
if not getattr(p.params, "check_each_transform", False):
continue
for data_name in p.data_fields:
data[data_name] = p.filter(data[data_name], rows, cols)
return data
def _to_dict(self):
dictionary = super(Compose, self)._to_dict()
bbox_processor = self.processors.get("bboxes")
keypoints_processor = self.processors.get("keypoints")
dictionary.update(
{
"bbox_params": bbox_processor.params._to_dict() if bbox_processor else None, # skipcq: PYL-W0212
"keypoint_params": keypoints_processor.params._to_dict() # skipcq: PYL-W0212
if keypoints_processor
else None,
"additional_targets": self.additional_targets,
}
)
return dictionary
def get_dict_with_id(self):
dictionary = super().get_dict_with_id()
bbox_processor = self.processors.get("bboxes")
keypoints_processor = self.processors.get("keypoints")
dictionary.update(
{
"bbox_params": bbox_processor.params._to_dict() if bbox_processor else None, # skipcq: PYL-W0212
"keypoint_params": keypoints_processor.params._to_dict() # skipcq: PYL-W0212
if keypoints_processor
else None,
"additional_targets": self.additional_targets,
"params": None,
}
)
return dictionary
def _check_args(self, **kwargs):
checked_single = ["image", "mask"]
checked_multi = ["masks"]
# ["bboxes", "keypoints"] could be almost any type, no need to check them
for data_name, data in kwargs.items():
internal_data_name = self.additional_targets.get(data_name, data_name)
if internal_data_name in checked_single:
if not isinstance(data, np.ndarray):
raise TypeError("{} must be numpy array type".format(data_name))
if internal_data_name in checked_multi:
if data:
if not isinstance(data[0], np.ndarray):
raise TypeError("{} must be list of numpy arrays".format(data_name))
class OneOf(BaseCompose):
"""Select one of transforms to apply. Selected transform will be called with `force_apply=True`.
Transforms probabilities will be normalized to one 1, so in this case transforms probabilities works as weights.
Args:
transforms (list): list of transformations to compose.
p (float): probability of applying selected transform. Default: 0.5.
"""
def __init__(self, transforms, p=0.5):
super(OneOf, self).__init__(transforms, p)
transforms_ps = [t.p for t in transforms]
s = sum(transforms_ps)
self.transforms_ps = [t / s for t in transforms_ps]
def __call__(self, force_apply=False, **data):
if self.replay_mode:
for t in self.transforms:
data = t(**data)
return data
if self.transforms_ps and (force_apply or random.random() < self.p):
random_state = np.random.RandomState(random.randint(0, 2 ** 32 - 1))
t = random_state.choice(self.transforms.transforms, p=self.transforms_ps)
data = t(force_apply=True, **data)
return data
class OneOrOther(BaseCompose):
"""Select one or another transform to apply. Selected transform will be called with `force_apply=True`."""
def __init__(self, first=None, second=None, transforms=None, p=0.5):
if transforms is None:
transforms = [first, second]
super(OneOrOther, self).__init__(transforms, p)
def __call__(self, force_apply=False, **data):
if self.replay_mode:
for t in self.transforms:
data = t(**data)
return data
if random.random() < self.p:
return self.transforms[0](force_apply=True, **data)
return self.transforms[-1](force_apply=True, **data)
class PerChannel(BaseCompose):
"""Apply transformations per-channel
Args:
transforms (list): list of transformations to compose.
channels (list): channels to apply the transform to. Pass None to apply to all.
Default: None (apply to all)
p (float): probability of applying the transform. Default: 0.5.
"""
def __init__(self, transforms, channels=None, p=0.5):
super(PerChannel, self).__init__(transforms, p)
self.channels = channels
def __call__(self, force_apply=False, **data):
if force_apply or random.random() < self.p:
image = data["image"]
# Expand mono images to have a single channel
if len(image.shape) == 2:
image = np.expand_dims(image, -1)
if self.channels is None:
self.channels = range(image.shape[2])
for c in self.channels:
for t in self.transforms:
image[:, :, c] = t(image=image[:, :, c])["image"]
data["image"] = image
return data
class ReplayCompose(Compose):
def __init__(
self, transforms, bbox_params=None, keypoint_params=None, additional_targets=None, p=1.0, save_key="replay"
):
super(ReplayCompose, self).__init__(transforms, bbox_params, keypoint_params, additional_targets, p)
self.set_deterministic(True, save_key=save_key)
self.save_key = save_key
def __call__(self, force_apply=False, **kwargs):
kwargs[self.save_key] = defaultdict(dict)
result = super(ReplayCompose, self).__call__(force_apply=force_apply, **kwargs)
serialized = self.get_dict_with_id()
self.fill_with_params(serialized, result[self.save_key])
self.fill_applied(serialized)
result[self.save_key] = serialized
return result
@staticmethod
def replay(saved_augmentations, **kwargs):
augs = ReplayCompose._restore_for_replay(saved_augmentations)
return augs(force_apply=True, **kwargs)
@staticmethod
def _restore_for_replay(transform_dict, lambda_transforms=None):
"""
Args:
transform (dict): A dictionary with serialized transform pipeline.
lambda_transforms (dict): A dictionary that contains lambda transforms, that
is instances of the Lambda class.
This dictionary is required when you are restoring a pipeline that contains lambda transforms. Keys
in that dictionary should be named same as `name` arguments in respective lambda transforms from
a serialized pipeline.
"""
transform = transform_dict
applied = transform["applied"]
params = transform["params"]
lmbd = instantiate_lambda(transform, lambda_transforms)
if lmbd:
transform = lmbd
else:
name = transform["__class_fullname__"]
args = {k: v for k, v in transform.items() if k not in ["__class_fullname__", "applied", "params"]}
cls = SERIALIZABLE_REGISTRY[name]
if "transforms" in args:
args["transforms"] = [
ReplayCompose._restore_for_replay(t, lambda_transforms=lambda_transforms)
for t in args["transforms"]
]
transform = cls(**args)
transform.params = params
transform.replay_mode = True
transform.applied_in_replay = applied
return transform
def fill_with_params(self, serialized, all_params):
params = all_params.get(serialized.get("id"))
serialized["params"] = params
del serialized["id"]
for transform in serialized.get("transforms", []):
self.fill_with_params(transform, all_params)
def fill_applied(self, serialized):
if "transforms" in serialized:
applied = [self.fill_applied(t) for t in serialized["transforms"]]
serialized["applied"] = any(applied)
else:
serialized["applied"] = serialized.get("params") is not None
return serialized["applied"]
def _to_dict(self):
dictionary = super(ReplayCompose, self)._to_dict()
dictionary.update({"save_key": self.save_key})
return dictionary
class BboxParams(Params):
"""
Parameters of bounding boxes
Args:
format (str): format of bounding boxes. Should be 'coco', 'pascal_voc', 'albumentations' or 'yolo'.
The `coco` format
`[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200].
The `pascal_voc` format
`[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212].
The `albumentations` format
is like `pascal_voc`, but normalized,
in other words: [x_min, y_min, x_max, y_max]`, e.g. [0.2, 0.3, 0.4, 0.5].
The `yolo` format
`[x, y, width, height]`, e.g. [0.1, 0.2, 0.3, 0.4];
`x`, `y` - normalized bbox center; `width`, `height` - normalized bbox width and height.
label_fields (list): list of fields that are joined with boxes, e.g labels.
Should be same type as boxes.
min_area (float): minimum area of a bounding box. All bounding boxes whose
visible area in pixels is less than this value will be removed. Default: 0.0.
min_visibility (float): minimum fraction of area for a bounding box
to remain this box in list. Default: 0.0.
check_each_transform (bool): if `True`, then bboxes will be checked after each dual transform.
Default: `True`
"""
def __init__(self, format, label_fields=None, min_area=0.0, min_visibility=0.0, check_each_transform=True):
super(BboxParams, self).__init__(format, label_fields)
self.min_area = min_area
self.min_visibility = min_visibility
self.check_each_transform = check_each_transform
def _to_dict(self):
data = super(BboxParams, self)._to_dict()
data.update(
{
"min_area": self.min_area,
"min_visibility": self.min_visibility,
"check_each_transform": self.check_each_transform,
}
)
return data
class KeypointParams(Params):
"""
Parameters of keypoints
Args:
format (str): format of keypoints. Should be 'xy', 'yx', 'xya', 'xys', 'xyas', 'xysa'.
x - X coordinate,
y - Y coordinate
s - Keypoint scale
a - Keypoint orientation in radians or degrees (depending on KeypointParams.angle_in_degrees)
label_fields (list): list of fields that are joined with keypoints, e.g labels.
Should be same type as keypoints.
remove_invisible (bool): to remove invisible points after transform or not
angle_in_degrees (bool): angle in degrees or radians in 'xya', 'xyas', 'xysa' keypoints
check_each_transform (bool): if `True`, then keypoints will be checked after each dual transform.
Default: `True`
"""
def __init__(
self,
format, # skipcq: PYL-W0622
label_fields=None,
remove_invisible=True,
angle_in_degrees=True,
check_each_transform=True,
):
super(KeypointParams, self).__init__(format, label_fields)
self.remove_invisible = remove_invisible
self.angle_in_degrees = angle_in_degrees
self.check_each_transform = check_each_transform
def _to_dict(self):
data = super(KeypointParams, self)._to_dict()
data.update(
{
"remove_invisible": self.remove_invisible,
"angle_in_degrees": self.angle_in_degrees,
"check_each_transform": self.check_each_transform,
}
)
return data
class Sequential(BaseCompose):
"""Sequentially applies all transforms to targets.
Note:
This transform is not intended to be a replacement for `Compose`. Instead, it should be used inside `Compose`
the same way `OneOf` or `OneOrOther` are used. For instance, you can combine `OneOf` with `Sequential` to
create an augmentation pipeline that contains multiple sequences of augmentations and applies one randomly
chose sequence to input data (see the `Example` section for an example definition of such pipeline).
Example:
>>> import albumentations as A
>>> transform = A.Compose([
>>> A.OneOf([
>>> A.Sequential([
>>> A.HorizontalFlip(p=0.5),
>>> A.ShiftScaleRotate(p=0.5),
>>> ]),
>>> A.Sequential([
>>> A.VerticalFlip(p=0.5),
>>> A.RandomBrightnessContrast(p=0.5),
>>> ]),
>>> ], p=1)
>>> ])
"""
def __init__(self, transforms, p=0.5):
super().__init__(transforms, p)
def __call__(self, **data):
for t in self.transforms:
data = t(**data)
return data
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');
var useIsomorphicLayoutEffect = require('@reach/utils/use-isomorphic-layout-effect');
/*
* Welcome to @reach/auto-id!
* Let's see if we can make sense of why this hook exists and its
* implementation.
*
* Some background:
* 1. Accessibility APIs rely heavily on element IDs
* 2. Requiring developers to put IDs on every element in Reach UI is both
* cumbersome and error-prone
* 3. With a component model, we can generate IDs for them!
*
* Solution 1: Generate random IDs.
*
* This works great as long as you don't server render your app. When React (in
* the client) tries to reuse the markup from the server, the IDs won't match
* and React will then recreate the entire DOM tree.
*
* Solution 2: Increment an integer
*
* This sounds great. Since we're rendering the exact same tree on the server
* and client, we can increment a counter and get a deterministic result between
* client and server. Also, JS integers can go up to nine-quadrillion. I'm
* pretty sure the tab will be closed before an app never needs
* 10 quadrillion IDs!
*
* Problem solved, right?
*
* Ah, but there's a catch! React's concurrent rendering makes this approach
* non-deterministic. While the client and server will end up with the same
* elements in the end, depending on suspense boundaries (and possibly some user
* input during the initial render) the incrementing integers won't always match
* up.
*
* Solution 3: Don't use IDs at all on the server; patch after first render.
*
* What we've done here is solution 2 with some tricks. With this approach, the
* ID returned is an empty string on the first render. This way the server and
* client have the same markup no matter how wild the concurrent rendering may
* have gotten.
*
* After the render, we patch up the components with an incremented ID. This
* causes a double render on any components with `useId`. Shouldn't be a problem
* since the components using this hook should be small, and we're only updating
* the ID attribute on the DOM, nothing big is happening.
*
* It doesn't have to be an incremented number, though--we could do generate
* random strings instead, but incrementing a number is probably the cheapest
* thing we can do.
*
* Additionally, we only do this patchup on the very first client render ever.
* Any calls to `useId` that happen dynamically in the client will be
* populated immediately with a value. So, we only get the double render after
* server hydration and never again, SO BACK OFF ALRIGHT?
*/
var serverHandoffComplete = false;
var id = 0;
var genId = function genId() {
return ++id;
};
/**
* useId
*
* Autogenerate IDs to facilitate WAI-ARIA and server rendering.
*
* Note: The returned ID will initially be `null` and will update after a
* component mounts. Users may need to supply their own ID if they need
* consistent values for SSR.
*
* @see Docs https://reach.tech/auto-id
*/
function useId(idFromProps) {
/*
* If this instance isn't part of the initial render, we don't have to do the
* double render/patch-up dance. We can just generate the ID and return it.
*/
var initialId = idFromProps || (serverHandoffComplete ? genId() : null);
var _React$useState = React.useState(initialId),
id = _React$useState[0],
setId = _React$useState[1];
useIsomorphicLayoutEffect.useIsomorphicLayoutEffect(function () {
if (id === null) {
/*
* Patch the ID after render. We do this in `useLayoutEffect` to avoid any
* rendering flicker, though it'll make the first render slower (unlikely
* to matter, but you're welcome to measure your app and let us know if
* it's a problem).
*/
setId(genId());
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
React.useEffect(function () {
if (serverHandoffComplete === false) {
/*
* Flag all future uses of `useId` to skip the update dance. This is in
* `useEffect` because it goes after `useLayoutEffect`, ensuring we don't
* accidentally bail out of the patch-up dance prematurely.
*/
serverHandoffComplete = true;
}
}, []);
return id != null ? String(id) : undefined;
}
exports.useId = useId;
|
/**
* three.js extensions for KIMCHI.
* @external THREE
*/
/**
* @constructor Object3D
* @memberOf external:THREE
*/
/**
* @constructor PerspectiveCamera
* @memberOf external:THREE
*/
/**
* @constructor Vector3
* @memberOf external:THREE
*/
/**
* @constructor Matrix3
* @memberOf external:THREE
*/
/**
* @constructor Curve
* @memberOf external:THREE
*/
(function (_, THREE) {
'use strict';
/**
* @param {THREE.Object3D} object1
* @param {THREE.Object3D} object2
* @return {Number} The distance between the two objects.
* @alias distance
* @memberOf external:THREE.Object3D
*/
THREE.Object3D.getDistance = function (object1, object2) {
return object1.position.distanceTo(object2.position);
};
/**
* "Overload" the original function of THREE.Object3D.prototype.add to
* accept arrays as well.
* @param {THREE.Object3D|Array} param
* Either an Object3D or an array of Object3Ds to be added.
* @alias add
* @instance
* @function
* @memberOf external:THREE.Object3D
*/
THREE.Object3D.prototype.add = (function () {
var addSingle = THREE.Object3D.prototype.add;
return function (param) {
var self = this;
if (Object.prototype.toString.call(param) === '[object Array]') { // add multiple Object3Ds
_.each(param, function (object) {
self.add(object);
});
} else { // add a single Object3D
addSingle.call(self, param);
}
};
}());
/**
* Revolve around the given world axis. TODO provide a translation
* vector for cases where the world axis doesn't pass through the origin
* @param {THREE.Vector3} worldAxis Not local based on the object, but
* but global in the world.
* @param {Number} angle In Radians.
* @returns {THREE.Vector3} this
* @alias orbit
* @instance
* @function
* @memberOf external:THREE.Matrix3
*/
THREE.Vector3.prototype.orbit = (function () {
var sin, cos, x, y, z, rotationMatrix, scalingMatrix;
rotationMatrix = new THREE.Matrix3();
scalingMatrix = new THREE.Matrix3();
return function (worldAxis, angle) {
sin = Math.sin(angle);
cos = Math.cos(angle);
worldAxis = worldAxis.normalize();
x = worldAxis.x;
y = worldAxis.y;
z = worldAxis.z;
scalingMatrix.set(
1, 0, 0,
0, 1, 0,
0, 0, 1
);
rotationMatrix.set( // http://en.wikipedia.org/wiki/Rotation_matrix
cos + x * x * (1 - cos),
x * y * (1 - cos) - z * sin,
x * z * (1 - cos) + y * sin,
y * x * (1 - cos) + z * sin,
cos + y * y * (1 - cos),
y * z * (1 - cos) - x * sin,
z * x * (1 - cos) - y * sin,
z * y * (1 - cos) + x * sin,
cos + z * z * (1 - cos)
);
return this.applyMatrix3(scalingMatrix)
.applyMatrix3(rotationMatrix)
.applyMatrix3(scalingMatrix.inverse());
};
}());
/**
* Update the camera with the given options. The aspect ratio is calculated
* from the given width and height. See {@link
* http://threejs.org/docs/#Reference/Cameras/PerspectiveCamera} for the
* other properties.
* @param {Object} options
* @param {Number} [options.width] If given, height must also be given
* @param {Number} [options.height] If given, width must also be given.
* @param {Number} [options.fov]
* @param {Number} [options.near]
* @param {Number} [options.far]
* @alias update
* @instance
* @memberOf external:THREE.PerspectiveCamera
*/
THREE.PerspectiveCamera.prototype.update = function (options) {
if (typeof options.width === 'number' && options.height > 0) {
this.aspect = options.width / options.height;
// the camera doesn't have width and height properties; no need to assign
_.omit(options, ['width', 'height']);
}
_.assign(this, options);
// must be called after changing options
this.updateProjectionMatrix();
};
/**
* Set the x, y, and z values of this vector to all be the given value.
* @param {Number} value
* @alias setXYZ
* @instance
* @memberOf external:THREE.Vector3
*/
THREE.Vector3.prototype.setXYZ = function (value) {
return this.set(value, value, value);
};
/**
* The original function getInverse() also sets this and requires a Matrix4,
* so we write our own function to only return the inverse.
* @returns {Matrix3} The inverse matrix.
* @alias inverse
* @instance
* @function
* @memberOf external:THREE.Matrix3
*/
THREE.Matrix3.prototype.inverse = (function () {
var determinant, e, inverse = new THREE.Matrix3();
return function () {
determinant = this.determinant();
e = this.elements;
if (determinant === 0) {
throw new Error('Matrix3.inverse(): Matrix not invertible.');
}
inverse.set(
e[4] * e[8] - e[5] * e[7],
e[2] * e[7] - e[1] * e[8],
e[1] * e[5] - e[2] * e[4],
e[5] * e[6] - e[3] * e[8],
e[0] * e[8] - e[2] * e[6],
e[2] * e[3] - e[0] * e[5],
e[3] * e[7] - e[4] * e[6],
e[1] * e[6] - e[0] * e[7],
e[0] * e[4] - e[1] * e[3]
);
return inverse.multiplyScalar(1 / determinant);
};
}());
/**
* For this Curve, create a Line which can be added to a scene.
* Based on {@link
* http://mrdoob.github.io/three.js/examples/webgl_geometry_shapes.html}
* @param {Object} options
* <br> position: THREE.Vector3.
* <br> rotation: THREE.Euler.
* <br> color: Hexadecimal.
* <br> opacity: Number.
* <br> lineSegments: Number of line segments to make up the Line.
* <br> scale: THREE.Vector3.
* @returns {THREE.Line}
* @alias createLine
* @instance
* @memberOf external:THREE.Curve
*/
THREE.Curve.prototype.createLine = function (options) {
var curvePath, geometry, line;
options = _.assign({
'position': new THREE.Vector3(),
'rotation': new THREE.Euler(),
'color': 0x888888,
'opacity': 1,
'lineSegments': 360,
'scale': new THREE.Vector3(1, 1, 1)
}, options);
// a CurvePath is needed since it has the createGeometry() functions
curvePath = new THREE.CurvePath();
curvePath.add(this);
geometry = curvePath.createSpacedPointsGeometry(options.lineSegments);
// create Line
line = new THREE.Line(geometry, new THREE.LineBasicMaterial({
'color': options.color,
'transparent': options.opacity < 1,
'opacity': options.opacity,
'linewidth': 1
}));
line.position.copy(options.position);
line.rotation.copy(options.rotation);
line.scale.copy(options.scale);
return line;
};
}(_, THREE)); |
var _curry2 = require('./internal/_curry2');
var _pickBy = require('./internal/_pickBy');
/**
* Returns a new object that does not contain a `prop` property.
*
* @func
* @memberOf R
* @category Object
* @sig String -> {k: v} -> {k: v}
* @param {String} prop the name of the property to dissociate
* @param {Object} obj the object to clone
* @return {Object} a new object similar to the original but without the specified property
* @example
*
* R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3}
*/
module.exports = _curry2(function dissoc(prop, obj) {
return _pickBy(function(val, key) { return key !== prop; }, obj);
});
|
from builtins import object
from typing import Dict, Optional, Tuple
from empire.server.common.module_models import PydanticModule
class Module(object):
@staticmethod
def generate(
main_menu,
module: PydanticModule,
params: Dict,
obfuscate: bool = False,
obfuscation_command: str = "",
) -> Tuple[Optional[str], Optional[str]]:
listApps = params["ListApps"]
appName = params["AppName"]
sandboxMode = params["SandboxMode"]
if listApps != "":
script = """
import os
apps = [ app.split('.app')[0] for app in os.listdir('/Applications/') if not app.split('.app')[0].startswith('.')]
choices = []
for x in xrange(len(apps)):
choices.append("[%s] %s " %(x+1, apps[x]) )
print("\\nAvailable applications:\\n")
print('\\n'.join(choices))
"""
else:
if sandboxMode != "":
# osascript prompt for the current application with System Preferences icon
script = """
import os
print(os.popen('osascript -e \\\'display dialog "Software Update requires that you type your password to apply changes." & return & return default answer "" with hidden answer with title "Software Update"\\\'').read())
"""
else:
# osascript prompt for the specific application
script = """
import os
print(os.popen('osascript -e \\\'tell app "%s" to activate\\\' -e \\\'tell app "%s" to display dialog "%s requires your password to continue." & return default answer "" with icon 1 with hidden answer with title "%s Alert"\\\'').read())
""" % (
appName,
appName,
appName,
appName,
)
return script
|
/* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.*/
(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx.binding","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(a,b){return Array.isArray(a)?e.call(b,a):i(a)?A(a.call(b)):j(a)?A(a):h(a)?f(a):isPromise(a)?g(a):typeof a===x?a:z(a)||Array.isArray(a)?e.call(b,a):a}function e(a){var b=this;return function(c){function e(a,e){if(!f)try{if(a=d(a,b),typeof a!==x)return i[e]=a,--h||c(null,i);a.call(b,function(a,b){if(!f){if(a)return f=!0,c(a);i[e]=b,--h||c(null,i)}})}catch(g){f=!0,c(g)}}var f,g=Object.keys(a),h=g.length,i=new a.constructor;if(!h)return void u.schedule(function(){c(null,i)});for(var j=0,k=g.length;k>j;j++)e(a[g[j]],g[j])}}function f(a){return function(b){var c,d=!1;a.subscribe(function(a){c=a,d=!0},b,function(){d&&b(null,c)})}}function g(a){return function(b){a.then(function(a){b(null,a)},b)}}function h(a){return a&&typeof a.subscribe===x}function i(a){return a&&a.constructor&&"GeneratorFunction"===a.constructor.name}function j(a){return a&&typeof a.next===x&&typeof a[y]===x}function k(a){a&&u.schedule(function(){throw a})}function l(a,b,c){if(a.addEventListener)return a.addEventListener(b,c,!1),s(function(){a.removeEventListener(b,c,!1)});throw new Error("No listener found")}function m(a,b,c){var d=new t;if("[object NodeList]"===Object.prototype.toString.call(a))for(var e=0,f=a.length;f>e;e++)d.add(m(a.item(e),b,c));else a&&d.add(l(a,b,c));return d}var n=c.Observable,o=(n.prototype,n.fromPromise),p=n.throwException,q=c.AnonymousObservable,r=c.AsyncSubject,s=c.Disposable.create,t=c.CompositeDisposable,u=(c.Scheduler.immediate,c.Scheduler.timeout),v=c.helpers.isScheduler,w=Array.prototype.slice,x="function",y="throw",z=c.internals.isObject,A=c.spawn=function(a){var b=i(a);return function(c){function e(a,b){u.schedule(c.bind(g,a,b))}function f(a,b){var c;if(arguments.length>2&&(b=w.call(arguments,1)),a)try{c=h[y](a)}catch(i){return e(i)}if(!a)try{c=h.next(b)}catch(i){return e(i)}if(c.done)return e(null,c.value);if(c.value=d(c.value,g),typeof c.value!==x)f(new TypeError("Rx.spawn only supports a function, Promise, Observable, Object or Array."));else{var j=!1;try{c.value.call(g,function(){j||(j=!0,f.apply(g,arguments))})}catch(i){u.schedule(function(){j||(j=!0,f.call(g,i))})}}}var g=this,h=a;if(b){var i=w.call(arguments),j=i.length,l=j&&typeof i[j-1]===x;c=l?i.pop():k,h=a.apply(this,i)}else c=c||k;f()}};n.start=function(a,b,c){return B(a,b,c)()};var B=n.toAsync=function(a,b,c){return v(c)||(c=u),function(){var d=arguments,e=new r;return c.schedule(function(){var c;try{c=a.apply(b,d)}catch(f){return void e.onError(f)}e.onNext(c),e.onCompleted()}),e.asObservable()}};n.fromCallback=function(a,b,c){return function(){var d=w.call(arguments,0);return new q(function(e){function f(){var a=arguments;if(c){try{a=c(a)}catch(b){return void e.onError(b)}e.onNext(a)}else a.length<=1?e.onNext.apply(e,a):e.onNext(a);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},n.fromNodeCallback=function(a,b,c){return function(){var d=w.call(arguments,0);return new q(function(e){function f(a){if(a)return void e.onError(a);var b=w.call(arguments,1);if(c){try{b=c(b)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},c.config.useNativeEvents=!1,n.fromEvent=function(b,d,e){if(b.addListener)return C(function(a){b.addListener(d,a)},function(a){b.removeListener(d,a)},e);if(!c.config.useNativeEvents){if("function"==typeof b.on&&"function"==typeof b.off)return C(function(a){b.on(d,a)},function(a){b.off(d,a)},e);if(a.Ember&&"function"==typeof a.Ember.addListener)return C(function(a){Ember.addListener(b,d,a)},function(a){Ember.removeListener(b,d,a)},e)}return new q(function(a){return m(b,d,function(b){var c=b;if(e)try{c=e(arguments)}catch(d){return void a.onError(d)}a.onNext(c)})}).publish().refCount()};var C=n.fromEventPattern=function(a,b,c){return new q(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)}var f=a(e);return s(function(){b&&b(e,f)})}).publish().refCount()};return n.startAsync=function(a){var b;try{b=a()}catch(c){return p(c)}return o(b)},c});
//# sourceMappingURL=rx.async.map |
# -*- coding: utf-8 -*-
# Visigoth: A lightweight Python3 library for rendering data visualizations in SVG
# Copyright (C) 2020 Visigoth Developers
#
# 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.
import unittest
import random
import math
from visigoth import Diagram
from visigoth.internal.utils.test_utils import TestUtils
from visigoth.containers.map import Map
from visigoth.containers.box import Box
from visigoth.map_layers.voronoi import Voronoi
from visigoth.utils import DiscreteHueManager, MarkerManager
class TestVoronoi(unittest.TestCase):
def test_basic(self):
d = Diagram()
m1 = Map(512)
rng = random.Random(1)
data1 = [(rng.random(), rng.random(), str(x), "p"+str(x)) for x in range(0, 100)]
p = DiscreteHueManager()
mm = MarkerManager()
mm.setDefaultRadius(5)
m1.add(Voronoi(data1,hue_manager=p,lon=0,lat=1,hue=2,marker_manager=mm))
d.add(Box(m1))
m2 = Map(512)
rng = random.Random(1)
angles2 = [math.pi * rng.random() * 2 for r in range(15)]
data2 = [(0.5 + (0.4+0.1*rng.random())*math.sin(a), 0.5 + (0.4 + 0.1*rng.random())*math.cos(a)) for a in angles2]
data2v = [(x,y,random.choice(["A","B","C"])) for (x,y) in data2]
m2.add(Voronoi(data2v,lon=0,lat=1,hue=2,label=2))
d.add(Box(m2))
TestUtils.draw_output(d,"test_voronoi")
def test_square(self):
d = Diagram()
m1 = Map(512)
p = DiscreteHueManager()
p.addHue("A","red").addHue("B","blue").addHue("C","green").addHue("D","orange")
data1 = [(0.25,0.25,"A"),
(0.75,0.75,"B"),
(0.25,0.75,"C"),
(0.75,0.25,"D")]
m1.add(Voronoi(data1))
d.add(Box(m1))
TestUtils.draw_output(d,"test_voronoi_square")
if __name__ == "__main__":
unittest.main()
|
# Copyright (c) ZenML GmbH 2020. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing
# permissions and limitations under the License.
"""File utilities"""
import fnmatch
import os
import tarfile
from pathlib import Path
from typing import Text, Callable
from tfx.utils.io_utils import _REMOTE_FS_PREFIX, load_csv_column_names, fileio
# TODO: [TFX] [LOW] Unnecessary dependency here
def walk(dir_path):
"""Walks down the dir_path"""
return fileio.walk(dir_path)
def is_root(path: Text):
"""
Returns true if path has no parent in local filesystem.
Args:
path (str): Local path in filesystem.
"""
return Path(path).parent == Path(path)
def is_dir(dir_path: Text):
"""
Returns true if dir_path points to a dir.
Args:
dir_path (str): Local path in filesystem.
"""
return fileio.isdir(dir_path)
def find_files(dir_path, pattern):
"""
Find files in a directory that match pattern.
Args:
dir_path: Path to directory.
pattern: pattern like *.png.
"""
for root, dirs, files in walk(dir_path):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
def is_remote(path: Text):
"""
Returns True if path exists remotely.
Args:
path (str): Any path.
"""
return any([path.startswith(prefix) for prefix in
_REMOTE_FS_PREFIX])
def is_gcs_path(path: Text):
"""
Returns True if path is on Google Cloud Storage.
Args:
path (str): Any path.
"""
return path.startswith('gs://')
def list_dir(dir_path: Text, only_file_names: bool = False):
"""
Returns a list of files under dir.
Args:
dir_path (str): Path in filesystem.
only_file_names (bool): Returns only file names if True.
"""
return [os.path.join(dir_path, f) if not only_file_names else f
for f in fileio.listdir(dir_path)]
def create_file_if_not_exists(file_path: Text, file_contents: Text):
"""
Creates directory if it does not exist.
Args:
file_path (str): Local path in filesystem.
file_contents (str): Contents of file.
"""
# if not fileio.exists(file_path):
# fileio.(file_path, file_contents)
raise NotImplementedError
def append_file(file_path: Text, file_contents: Text):
"""
Appends file_contents to file.
Args:
file_path (str): Local path in filesystem.
file_contents (str): Contents of file.
"""
# with file_io.FileIO(file_path, mode='a') as f:
# f.write(file_contents)
raise NotImplementedError
def create_dir_if_not_exists(dir_path: Text):
"""
Creates directory if it does not exist.
Args:
dir_path (str): Local path in filesystem.
"""
if not fileio.isdir(dir_path):
fileio.mkdir(dir_path)
def create_dir_recursive_if_not_exists(dir_path: Text):
"""
Creates directory recursively if it does not exist.
Args:
dir_path (str): Local path in filesystem.
"""
if not fileio.isdir(dir_path):
fileio.mkdir(dir_path) # TODO: check if working recursively
def resolve_relative_path(path: Text):
"""
Takes relative path and resolves it absolutely.
Args:
path (str): Local path in filesystem.
"""
if is_remote(path):
return path
return str(Path(path).resolve())
def file_exists(path: Text):
"""
Returns true if file exists at path.
Args:
path (str): Local path in filesystem.
"""
return fileio.exists(path)
def copy(source: Text, destination: Text, overwrite: bool = False):
"""
Copies dir from source to destination.
Args:
source (str): Path to copy from.
destination (str): Path to copy to.
overwrite: boolean, if false, then throws an error before overwrite.
"""
return fileio.copy(source, destination, overwrite)
def copy_dir(source_dir: Text, destination_dir: Text, overwrite: bool = False):
"""
Copies dir from source to destination.
Args:
source_dir (str): Path to copy from.
destination_dir (str): Path to copy to.
overwrite: boolean, if false, then throws an error before overwrite.
"""
for f in list_dir(source_dir):
p = Path(f)
destination_name = os.path.join(destination_dir, p.name)
if is_dir(f):
copy_dir(f, destination_name, overwrite)
else:
create_dir_recursive_if_not_exists(
str(Path(destination_name).parent))
copy(f, destination_name, overwrite)
def move(source: Text, destination: Text, overwrite: bool = False):
"""
Moves dir from source to destination. Can be used to rename.
Args:
source (str): Local path to copy from.
destination (str): Local path to copy to.
overwrite: boolean, if false, then throws an error before overwrite.
"""
return fileio.rename(source, destination, overwrite)
def rm_dir(dir_path: Text):
"""
Deletes dir recursively. Dangerous operation.
Args:
dir_path (str): Dir to delete.
"""
fileio.rmtree(dir_path)
def rm_file(file_path: Text):
"""
Deletes file. Dangerous operation.
Args:
file_path (str): Path of file to delete.
"""
if not file_exists(file_path):
raise Exception(f'{file_path} does not exist!')
return fileio.remove(file_path)
def read_file_contents(file_path: Text):
"""
Reads contents of file.
Args:
file_path (str): Path to file.
"""
# if not file_exists(file_path):
# raise Exception(f'{file_path} does not exist!')
# return file_io.read_file_to_string(file_path)
# tODO: Check for proper implementation
raise NotImplementedError
def write_file_contents(file_path: Text, content: Text):
"""
Writes contents of file.
Args:
file_path (str): Path to file.
content (str): Contents of file.
"""
# return file_io.write_string_to_file(file_path, content)
# TODO: Check for prpoer implementation
raise NotImplementedError
def get_grandparent(dir_path: Text):
"""
Get grandparent of dir.
Args:
dir_path (str): Path to directory.
"""
return Path(dir_path).parent.stem
def get_parent(dir_path: Text):
"""
Get parent of dir.
Args:
dir_path (str): Path to directory.
"""
return Path(dir_path).stem
def load_csv_header(csv_path: Text):
"""
Gets header column of csv and returns list.
Args:
csv_path (str): Path to csv file.
"""
return load_csv_column_names(csv_path)
def create_tarfile(source_dir: Text, output_filename: Text = 'zipped.tar.gz',
exclude_function: Callable = None):
"""
Create a compressed representation of source_dir.
Args:
source_dir: path to source dir
output_filename: name of outputted gz
exclude_function: function that determines whether to exclude file
"""
if exclude_function is None:
# default is to exclude the .zenml directory
def exclude_function(tarinfo):
filename = tarinfo.name
if '.zenml/' in filename:
return None
elif 'venv/' in filename:
return None
else:
return tarinfo
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname='', filter=exclude_function)
def extract_tarfile(source_tar: Text, output_dir: Text):
"""
Untars a compressed tar file to output_dir.
Args:
source_tar: path to a tar compressed file
output_dir: directory where to uncompress
"""
if is_remote(source_tar):
raise NotImplementedError('Use local tars for now.')
with tarfile.open(source_tar, "r:gz") as tar:
tar.extractall(output_dir)
|
const ClientConfiguration = require('../Auth/ClientConfiguration');
const RuntimeInformationProvider = require('../RuntimeInformationProvider');
const ApiClient = require('../ApiClient');
const AuthService = require('../Auth/AuthService');
const OAuth2ApiClient = require('../OAuth2ApiClient');
const CacheService = require('../Auth/CacheService');
class BaseApi {
constructor(authBaseUrl, clientId, clientSecret, accountId, scope){
this.clientConfiguration = new ClientConfiguration(authBaseUrl, clientId, clientSecret, accountId, scope);
this.runtimeInformationProvider = new RuntimeInformationProvider();
let apiClient = new ApiClient(this.runtimeInformationProvider);
let cacheService = new CacheService();
this.authService = new AuthService(this.clientConfiguration, apiClient, cacheService);
this.apiClient = new OAuth2ApiClient(this.authService, this.runtimeInformationProvider);
}
}
module.exports = BaseApi; |
import logging
try:
from .version import __version__
except ImportError:
pass
from autogluon.core.dataset import TabularDataset # noqa: F401
# TODO: make ForecastingPredictor available
logging.basicConfig(format="%(message)s") # just print message in logs
|
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.2.2 (2020-04-23)
*/
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
var getPreviewDialogWidth = function (editor) {
return parseInt(editor.getParam('plugin_preview_width', '650'), 10);
};
var getPreviewDialogHeight = function (editor) {
return parseInt(editor.getParam('plugin_preview_height', '500'), 10);
};
var getContentStyle = function (editor) {
return editor.getParam('content_style', '');
};
var shouldUseContentCssCors = function (editor) {
return editor.getParam('content_css_cors', false, 'boolean');
};
var Settings = {
getPreviewDialogWidth: getPreviewDialogWidth,
getPreviewDialogHeight: getPreviewDialogHeight,
getContentStyle: getContentStyle,
shouldUseContentCssCors: shouldUseContentCssCors
};
var global$2 = tinymce.util.Tools.resolve('tinymce.Env');
var getPreviewHtml = function (editor) {
var headHtml = '';
var encode = editor.dom.encode;
var contentStyle = Settings.getContentStyle(editor);
headHtml += '<base href="' + encode(editor.documentBaseURI.getURI()) + '">';
if (contentStyle) {
headHtml += '<style type="text/css">' + contentStyle + '</style>';
}
var cors = Settings.shouldUseContentCssCors(editor) ? ' crossorigin="anonymous"' : '';
global$1.each(editor.contentCSS, function (url) {
headHtml += '<link type="text/css" rel="stylesheet" href="' + encode(editor.documentBaseURI.toAbsolute(url)) + '"' + cors + '>';
});
var bodyId = editor.settings.body_id || 'tinymce';
if (bodyId.indexOf('=') !== -1) {
bodyId = editor.getParam('body_id', '', 'hash');
bodyId = bodyId[editor.id] || bodyId;
}
var bodyClass = editor.settings.body_class || '';
if (bodyClass.indexOf('=') !== -1) {
bodyClass = editor.getParam('body_class', '', 'hash');
bodyClass = bodyClass[editor.id] || '';
}
var isMetaKeyPressed = global$2.mac ? 'e.metaKey' : 'e.ctrlKey && !e.altKey';
var preventClicksOnLinksScript = '<script>' + 'document.addEventListener && document.addEventListener("click", function(e) {' + 'for (var elm = e.target; elm; elm = elm.parentNode) {' + 'if (elm.nodeName === "A" && !(' + isMetaKeyPressed + ')) {' + 'e.preventDefault();' + '}' + '}' + '}, false);' + '</script> ';
var directionality = editor.getBody().dir;
var dirAttr = directionality ? ' dir="' + encode(directionality) + '"' : '';
var previewHtml = '<!DOCTYPE html>' + '<html>' + '<head>' + headHtml + '</head>' + '<body id="' + encode(bodyId) + '" class="mce-content-body ' + encode(bodyClass) + '"' + dirAttr + '>' + editor.getContent() + preventClicksOnLinksScript + '</body>' + '</html>';
return previewHtml;
};
var IframeContent = {getPreviewHtml: getPreviewHtml};
var open = function (editor) {
var content = IframeContent.getPreviewHtml(editor);
var dataApi = editor.windowManager.open({
title: 'Preview',
size: 'large',
body: {
type: 'panel',
items: [{
name: 'preview',
type: 'iframe',
sandboxed: true
}]
},
buttons: [{
type: 'cancel',
name: 'close',
text: 'Close',
primary: true
}],
initialData: {preview: content}
});
dataApi.focus('close');
};
var register = function (editor) {
editor.addCommand('mcePreview', function () {
open(editor);
});
};
var Commands = {register: register};
var register$1 = function (editor) {
editor.ui.registry.addButton('preview', {
icon: 'preview',
tooltip: 'Preview',
onAction: function () {
return editor.execCommand('mcePreview');
}
});
editor.ui.registry.addMenuItem('preview', {
icon: 'preview',
text: 'Preview',
onAction: function () {
return editor.execCommand('mcePreview');
}
});
};
var Buttons = {register: register$1};
function Plugin() {
global.add('preview', function (editor) {
Commands.register(editor);
Buttons.register(editor);
});
}
Plugin();
}());
|
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { subCategoryGet } from "../../actions/subCategoryActions";
import ProductCard from "../../components/cards/ProductCard";
const SubCategoryHome = ({ match }) => {
const { slug } = match.params;
const dispatch = useDispatch();
const { loading, subCategory, products } = useSelector(
(state) => state.subCategory
);
useEffect(() => {
dispatch(subCategoryGet(slug));
}, [slug, dispatch]);
return (
<div className="container-fluid">
<div className="row">
<div className="col">
{loading ? (
<h4 className="text-center mt-5 mb-5 display-4 jumbotron">
Loading...
</h4>
) : (
<h4 className="text-center p-3 mt-5 mb-5 display-4 jumbotron">
{products.length} Products in "{subCategory.name}" Sub-Category
</h4>
)}
</div>
</div>
<div className="row">
{products &&
products.map((product) => (
<div key={product._id} className="col-md-4">
<ProductCard product={product} />
</div>
))}
</div>
</div>
);
};
export default SubCategoryHome;
|
import http from 'http';
import pify from 'pify';
export const host = 'localhost';
export const port = 6765;
export function createServer(givenPort = port) {
const server = http.createServer((request, response) => {
server.emit(request.url, request, response);
});
server.host = host;
server.port = givenPort;
server.url = `http://${host}:${givenPort}`;
server.protocol = 'http';
server.listen = pify(server.listen);
server.close = pify(server.close);
return server;
}
|
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh';
dayjs.extend(relativeTime);
export default dayjs;
|
window.alert("Welcome!")
document.getElementById("ctcb").addEventListener("click", function() {
document.getElementById("loremgid").select()
document.execCommand("copy")
})
function copied() {
window.alert("Copied!")
}
|
var http = require("http");
http.get({host: "vitorbritto.com.br"}, function(res) {
if (res.statusCode === 200) {
console.log("This site is up and runnning!");
} else {
console.log("This site might be down!");
}
});
|
'use strict'
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
TextInput,
Alert,
ScrollView,
AsyncStorage,
findNodeHandle
} from 'react-native';
import getData from './getData';
import base64 from 'base-64';
import SignInButton from './/button';
import styles from './styleSheet';
var api = require('../library/api.js');
//Sign in page, first screen to render when app is opened
//Once correct login details are entered app will render the Applist component
class Signin extends Component{
constructor(){
super();
this.state = {
username: '',
password: '',
clientId: ''
}
};
//Checks to see if there is already an access token in local storage so user does not have to log in each time
componentWillMount(){
AsyncStorage.getItem('AccessToken')
.then((value) =>{
if(value){
provideAccessToken(value, () => {
this.props.navigator.push({
name: 'appList'
})
})
}
})
}
render(){
return (
<ScrollView ref='scrollView'>
<View style={styles.loginContainer}>
<Text style={styles.header}>Login to Apteligent account</Text>
<Text style={styles.label}>Email</Text>
<TextInput ref='username' onFocus={this._inputFocused.bind(this, 'username')} style={styles.input} onChangeText={(text) => this.setState({username: text})} value={this.state.username}/>{/*By default TextInput has no default styling*/}
<Text style={styles.label}>Password</Text>
<TextInput ref='password' onFocus={this._inputFocused.bind(this, 'password')}secureTextEntry={true} style={styles.input} onChangeText={(text) => this.setState({password: text})} value={this.state.password}/>
<Text style={styles.label}>Client ID</Text>
<TextInput ref='clientId' onFocus={this._inputFocused.bind(this, 'clientId')}secureTextEntry={true} style={styles.input} onChangeText={(text) => this.setState({clientId: text})} value={this.state.clientId}/>
<SignInButton text={'LOGIN'} onPress={this._onPress.bind(this)} />
</View>
</ScrollView>
)
};
_forgotPassword(){
this.props.navigator.push({
name: 'forgotPassword'
})
}
_inputFocused(refName) {
setTimeout(() => {
let scrollResponder = this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
findNodeHandle(this.refs[refName]),
110, //additionalOffset
true
);
}, 100);
}
_onPress(){
const nav = this.props.navigator;
const username = this.state.username;
const password = this.state.password;
//Client ID must be Base64 encoded, cURL does this automatically but http requests need to be done manually
//Client ID is found at apteligent app user settings
const clientId = base64.encode(this.state.clientId);
//Apteligent APi currently only accepts grant_type 'password'
const grantType = 'password';
if(!this.state.username || !this.state.password){
Alert.alert('Incorrect Details', 'Please enter a valid email and password',
[{text: 'OK'},
{text: 'Forgot Password', onPress: () => this.props.navigator.push({name: 'forgotPassword'})}]
);
}else{
//Call the API to get the access token and render AppList component
getAccessToken(password, username, clientId, grantType, (error, data) => {
if(error){
console.log(error);
Alert.alert('Incorrect Details', 'Incorrect email or password entered',
[{text: 'OK'},
{text: 'Forgot Password', onPress: () => this.props.navigator.push({name: 'forgotPassword'})}]
);
}else{
AsyncStorage.setItem('AccessToken', data);
nav.push({
name: 'appList'
});
}
});
}
};
};
module.exports = Signin |
import { useCookies } from "react-cookie"
import {useState} from "react"
const cookieOPtions = { path: "/", maxAge: 3600 *24 * 30 *13}
export function useGdpr(initialPreferences) {
const [cookies, setCookie, removeCookie] = useCookies()
const [storedPreferences, setStoredPreferences] = useState( () => {
return {
rememberPreferences : cookies["ga-pref-set"] !== undefined,
gaEnabled: cookies["ga-pref-set"] === "allow-ga"
}
})
const setPreferences = pref => {
try {
if (!pref.rememberPreferences) {
removeCookie("_ga");
removeCookie("test-opt-in");
removeCookie('ga-pref-set');
setStoredPreferences({
rememberPreferences: false
})
}
else
{
if (pref.gaEnabled) {
setCookie("test-opt-in", true, cookieOPtions);
setCookie("ga-pref-set", "allow-ga", cookieOPtions);
setStoredPreferences({
gaEnabled: true,
rememberPreferences: true
})
} else {
removeCookie("test-opt-in");
removeCookie("_ga");
setCookie("ga-pref-set", "forbid-ga", cookieOPtions);
setStoredPreferences({
gaEnabled: false,
rememberPreferences: true
})
}
}
} catch (error) {
console.log('error while setting preferences', error)
}
}
return [storedPreferences, setPreferences];
} |
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@6thquake/react-material/styles';
import Grid from '@6thquake/react-material/Grid';
import Paper from '@6thquake/react-material/Paper';
import Typography from '@6thquake/react-material/Typography';
import ButtonBase from '@6thquake/react-material/ButtonBase';
const styles = theme => ({
root: {
flexGrow: 1,
maxWidth: 600,
padding: theme.spacing.unit * 2,
},
image: {
width: 128,
height: 128,
},
img: {
margin: 'auto',
display: 'block',
maxWidth: '100%',
maxHeight: '100%',
},
});
function ComplexGrid(props) {
const { classes } = props;
return (
<Paper className={classes.root}>
<Grid container spacing={16}>
<Grid item>
<ButtonBase className={classes.image}>
<img className={classes.img} alt="complex" src="/static/images/grid/complex.jpg" />
</ButtonBase>
</Grid>
<Grid item xs={12} sm container>
<Grid item xs container direction="column" spacing={16}>
<Grid item xs>
<Typography gutterBottom variant="subheading">
Standard license
</Typography>
<Typography gutterBottom>Full resolution 1920x1080 • JPEG</Typography>
<Typography color="textSecondary">ID: 1030114</Typography>
</Grid>
<Grid item>
<Typography style={{ cursor: 'pointer' }}>Remove</Typography>
</Grid>
</Grid>
<Grid item>
<Typography variant="subheading">$19.00</Typography>
</Grid>
</Grid>
</Grid>
</Paper>
);
}
ComplexGrid.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ComplexGrid);
|
"""Merry Xmas ported from https://twitter.com/Frozax/status/1342463299909275651
"""
from pypico8 import *
printh(
pico8_to_python(
r"""
pal({129,1,140,12,7},1)
::_::
cls(1)
function e(x,y,r,d)
local d,x,y,r,s,a=d-1,x,y,r,r\2,t()/6
if(d%2==0)a=-a
v=(r+s)*1.2
local f,g=cos(a)*v,sin(a)*v
if(d>0)e(x+f,y+g,s,d)e(x-f,y-g,s,d)e(x-g,y+f,s,d)e(x+g,y-f,s,d)
circfill(x,y,r,5-d)
end
e(64,64,25,5)
?"merry xmas",45,62,7
flip()goto _
"""
)
)
def _init():
pal(Table([129, 1, 140, 12, 7]), 1)
def _update():
pass
def _draw():
cls(1)
def e(x, y, r, d):
d, x, y, r, s, a = d - 1, x, y, r, r // 2, t() / 6
if d % 2 == 0:
a = -a
v = (r + s) * 1.2
f, g = cos(a) * v, sin(a) * v
if d > 0:
e(x + f, y + g, s, d)
e(x - f, y - g, s, d)
e(x - g, y + f, s, d)
e(x + g, y - f, s, d)
circfill(x, y, r, 5 - d)
e(64, 64, 25, 5)
print("MERRY XMAS", 45, 62, 7)
run(_init, _update, _draw) |
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{
/***/ "../pkg/wasm_pie.js":
/*!**************************!*\
!*** ../pkg/wasm_pie.js ***!
\**************************/
/*! exports provided: compute, __wbindgen_object_drop_ref, __wbg_getRandomValues_57e4008f45f0e105, __wbg_randomFillSync_d90848a552cbd666, __wbg_static_accessor_MODULE_39947eb3fe77895f, __wbg_self_f865985e662246aa, __wbg_require_c59851dfa0dc7e78, __wbg_crypto_bfb05100db79193b, __wbg_msCrypto_f6dddc6ae048b7e2, __wbindgen_is_undefined, __wbindgen_string_new, __wbg_new_5c43423e355e07f2, __wbg_set_5e4e19d05134472c, __wbg_buffer_e35e010c3ba9f945, __wbg_newwithbyteoffsetandlength_0c7ac30665ee26f8, __wbg_new_c77df81d6c892c35, __wbg_set_4a7e26c164c39e3d, __wbg_length_e0e70640cea5ee8c, __wbg_new_139e70222494b1ff, __wbg_set_d771848e3c7935bb, __wbg_length_2cfa674c2a529bc1, __wbg_newwithbyteoffsetandlength_12e0f22f7215a535, __wbg_new_865d1422d0493dbb, __wbg_set_3735cb2b5a062242, __wbg_length_77800d12ae1a0d8a, __wbg_newwithlength_e0c461e90217842c, __wbg_subarray_8a52f1c1a11c02a8, __wbindgen_throw, __wbindgen_memory */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _wasm_pie_bg_wasm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./wasm_pie_bg.wasm */ \"../pkg/wasm_pie_bg.wasm\");\n/* harmony import */ var _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./wasm_pie_bg.js */ \"../pkg/wasm_pie_bg.js\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"compute\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"compute\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_object_drop_ref\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbindgen_object_drop_ref\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_getRandomValues_57e4008f45f0e105\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_getRandomValues_57e4008f45f0e105\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_randomFillSync_d90848a552cbd666\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_randomFillSync_d90848a552cbd666\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_static_accessor_MODULE_39947eb3fe77895f\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_static_accessor_MODULE_39947eb3fe77895f\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_self_f865985e662246aa\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_self_f865985e662246aa\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_require_c59851dfa0dc7e78\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_require_c59851dfa0dc7e78\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_crypto_bfb05100db79193b\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_crypto_bfb05100db79193b\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_msCrypto_f6dddc6ae048b7e2\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_msCrypto_f6dddc6ae048b7e2\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_is_undefined\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbindgen_is_undefined\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_string_new\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbindgen_string_new\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_new_5c43423e355e07f2\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_new_5c43423e355e07f2\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_set_5e4e19d05134472c\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_set_5e4e19d05134472c\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_buffer_e35e010c3ba9f945\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_buffer_e35e010c3ba9f945\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_newwithbyteoffsetandlength_0c7ac30665ee26f8\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_newwithbyteoffsetandlength_0c7ac30665ee26f8\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_new_c77df81d6c892c35\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_new_c77df81d6c892c35\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_set_4a7e26c164c39e3d\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_set_4a7e26c164c39e3d\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_length_e0e70640cea5ee8c\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_length_e0e70640cea5ee8c\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_new_139e70222494b1ff\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_new_139e70222494b1ff\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_set_d771848e3c7935bb\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_set_d771848e3c7935bb\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_length_2cfa674c2a529bc1\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_length_2cfa674c2a529bc1\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_newwithbyteoffsetandlength_12e0f22f7215a535\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_newwithbyteoffsetandlength_12e0f22f7215a535\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_new_865d1422d0493dbb\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_new_865d1422d0493dbb\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_set_3735cb2b5a062242\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_set_3735cb2b5a062242\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_length_77800d12ae1a0d8a\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_length_77800d12ae1a0d8a\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_newwithlength_e0c461e90217842c\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_newwithlength_e0c461e90217842c\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbg_subarray_8a52f1c1a11c02a8\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbg_subarray_8a52f1c1a11c02a8\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_throw\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbindgen_throw\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_memory\", function() { return _wasm_pie_bg_js__WEBPACK_IMPORTED_MODULE_1__[\"__wbindgen_memory\"]; });\n\n\n\n\n//# sourceURL=webpack:///../pkg/wasm_pie.js?");
/***/ }),
/***/ "../pkg/wasm_pie_bg.js":
/*!*****************************!*\
!*** ../pkg/wasm_pie_bg.js ***!
\*****************************/
/*! exports provided: compute, __wbindgen_object_drop_ref, __wbg_getRandomValues_57e4008f45f0e105, __wbg_randomFillSync_d90848a552cbd666, __wbg_static_accessor_MODULE_39947eb3fe77895f, __wbg_self_f865985e662246aa, __wbg_require_c59851dfa0dc7e78, __wbg_crypto_bfb05100db79193b, __wbg_msCrypto_f6dddc6ae048b7e2, __wbindgen_is_undefined, __wbindgen_string_new, __wbg_new_5c43423e355e07f2, __wbg_set_5e4e19d05134472c, __wbg_buffer_e35e010c3ba9f945, __wbg_newwithbyteoffsetandlength_0c7ac30665ee26f8, __wbg_new_c77df81d6c892c35, __wbg_set_4a7e26c164c39e3d, __wbg_length_e0e70640cea5ee8c, __wbg_new_139e70222494b1ff, __wbg_set_d771848e3c7935bb, __wbg_length_2cfa674c2a529bc1, __wbg_newwithbyteoffsetandlength_12e0f22f7215a535, __wbg_new_865d1422d0493dbb, __wbg_set_3735cb2b5a062242, __wbg_length_77800d12ae1a0d8a, __wbg_newwithlength_e0c461e90217842c, __wbg_subarray_8a52f1c1a11c02a8, __wbindgen_throw, __wbindgen_memory */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* WEBPACK VAR INJECTION */(function(module) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"compute\", function() { return compute; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_object_drop_ref\", function() { return __wbindgen_object_drop_ref; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_getRandomValues_57e4008f45f0e105\", function() { return __wbg_getRandomValues_57e4008f45f0e105; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_randomFillSync_d90848a552cbd666\", function() { return __wbg_randomFillSync_d90848a552cbd666; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_static_accessor_MODULE_39947eb3fe77895f\", function() { return __wbg_static_accessor_MODULE_39947eb3fe77895f; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_self_f865985e662246aa\", function() { return __wbg_self_f865985e662246aa; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_require_c59851dfa0dc7e78\", function() { return __wbg_require_c59851dfa0dc7e78; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_crypto_bfb05100db79193b\", function() { return __wbg_crypto_bfb05100db79193b; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_msCrypto_f6dddc6ae048b7e2\", function() { return __wbg_msCrypto_f6dddc6ae048b7e2; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_is_undefined\", function() { return __wbindgen_is_undefined; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_string_new\", function() { return __wbindgen_string_new; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_new_5c43423e355e07f2\", function() { return __wbg_new_5c43423e355e07f2; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_set_5e4e19d05134472c\", function() { return __wbg_set_5e4e19d05134472c; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_buffer_e35e010c3ba9f945\", function() { return __wbg_buffer_e35e010c3ba9f945; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_newwithbyteoffsetandlength_0c7ac30665ee26f8\", function() { return __wbg_newwithbyteoffsetandlength_0c7ac30665ee26f8; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_new_c77df81d6c892c35\", function() { return __wbg_new_c77df81d6c892c35; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_set_4a7e26c164c39e3d\", function() { return __wbg_set_4a7e26c164c39e3d; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_length_e0e70640cea5ee8c\", function() { return __wbg_length_e0e70640cea5ee8c; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_new_139e70222494b1ff\", function() { return __wbg_new_139e70222494b1ff; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_set_d771848e3c7935bb\", function() { return __wbg_set_d771848e3c7935bb; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_length_2cfa674c2a529bc1\", function() { return __wbg_length_2cfa674c2a529bc1; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_newwithbyteoffsetandlength_12e0f22f7215a535\", function() { return __wbg_newwithbyteoffsetandlength_12e0f22f7215a535; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_new_865d1422d0493dbb\", function() { return __wbg_new_865d1422d0493dbb; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_set_3735cb2b5a062242\", function() { return __wbg_set_3735cb2b5a062242; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_length_77800d12ae1a0d8a\", function() { return __wbg_length_77800d12ae1a0d8a; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_newwithlength_e0c461e90217842c\", function() { return __wbg_newwithlength_e0c461e90217842c; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbg_subarray_8a52f1c1a11c02a8\", function() { return __wbg_subarray_8a52f1c1a11c02a8; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_throw\", function() { return __wbindgen_throw; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__wbindgen_memory\", function() { return __wbindgen_memory; });\n/* harmony import */ var _wasm_pie_bg_wasm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./wasm_pie_bg.wasm */ \"../pkg/wasm_pie_bg.wasm\");\n\n\nconst heap = new Array(32).fill(undefined);\n\nheap.push(undefined, null, true, false);\n\nfunction getObject(idx) { return heap[idx]; }\n\nlet heap_next = heap.length;\n\nfunction dropObject(idx) {\n if (idx < 36) return;\n heap[idx] = heap_next;\n heap_next = idx;\n}\n\nfunction takeObject(idx) {\n const ret = getObject(idx);\n dropObject(idx);\n return ret;\n}\n\nconst lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder;\n\nlet cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n\ncachedTextDecoder.decode();\n\nlet cachegetUint8Memory0 = null;\nfunction getUint8Memory0() {\n if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== _wasm_pie_bg_wasm__WEBPACK_IMPORTED_MODULE_0__[\"memory\"].buffer) {\n cachegetUint8Memory0 = new Uint8Array(_wasm_pie_bg_wasm__WEBPACK_IMPORTED_MODULE_0__[\"memory\"].buffer);\n }\n return cachegetUint8Memory0;\n}\n\nfunction getStringFromWasm0(ptr, len) {\n return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));\n}\n\nfunction addHeapObject(obj) {\n if (heap_next === heap.length) heap.push(heap.length + 1);\n const idx = heap_next;\n heap_next = heap[idx];\n\n heap[idx] = obj;\n return idx;\n}\n\nlet stack_pointer = 32;\n\nfunction addBorrowedObject(obj) {\n if (stack_pointer == 1) throw new Error('out of js stack');\n heap[--stack_pointer] = obj;\n return stack_pointer;\n}\n/**\n* @param {Int32Array} pre\n* @param {Int32Array} post\n* @param {Int32Array} inits\n* @param {Float64Array} hazards\n* @returns {Map<any, any>}\n*/\nfunction compute(pre, post, inits, hazards) {\n try {\n var ret = _wasm_pie_bg_wasm__WEBPACK_IMPORTED_MODULE_0__[\"compute\"](addBorrowedObject(pre), addBorrowedObject(post), addBorrowedObject(inits), addBorrowedObject(hazards));\n return takeObject(ret);\n } finally {\n heap[stack_pointer++] = undefined;\n heap[stack_pointer++] = undefined;\n heap[stack_pointer++] = undefined;\n heap[stack_pointer++] = undefined;\n }\n}\n\nfunction handleError(f) {\n return function () {\n try {\n return f.apply(this, arguments);\n\n } catch (e) {\n _wasm_pie_bg_wasm__WEBPACK_IMPORTED_MODULE_0__[\"__wbindgen_exn_store\"](addHeapObject(e));\n }\n };\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nconst __wbindgen_object_drop_ref = function(arg0) {\n takeObject(arg0);\n};\n\nconst __wbg_getRandomValues_57e4008f45f0e105 = handleError(function(arg0, arg1) {\n getObject(arg0).getRandomValues(getObject(arg1));\n});\n\nconst __wbg_randomFillSync_d90848a552cbd666 = handleError(function(arg0, arg1, arg2) {\n getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2));\n});\n\nconst __wbg_static_accessor_MODULE_39947eb3fe77895f = function() {\n var ret = module;\n return addHeapObject(ret);\n};\n\nconst __wbg_self_f865985e662246aa = handleError(function() {\n var ret = self.self;\n return addHeapObject(ret);\n});\n\nconst __wbg_require_c59851dfa0dc7e78 = handleError(function(arg0, arg1, arg2) {\n var ret = getObject(arg0).require(getStringFromWasm0(arg1, arg2));\n return addHeapObject(ret);\n});\n\nconst __wbg_crypto_bfb05100db79193b = function(arg0) {\n var ret = getObject(arg0).crypto;\n return addHeapObject(ret);\n};\n\nconst __wbg_msCrypto_f6dddc6ae048b7e2 = function(arg0) {\n var ret = getObject(arg0).msCrypto;\n return addHeapObject(ret);\n};\n\nconst __wbindgen_is_undefined = function(arg0) {\n var ret = getObject(arg0) === undefined;\n return ret;\n};\n\nconst __wbindgen_string_new = function(arg0, arg1) {\n var ret = getStringFromWasm0(arg0, arg1);\n return addHeapObject(ret);\n};\n\nconst __wbg_new_5c43423e355e07f2 = function() {\n var ret = new Map();\n return addHeapObject(ret);\n};\n\nconst __wbg_set_5e4e19d05134472c = function(arg0, arg1, arg2) {\n var ret = getObject(arg0).set(getObject(arg1), getObject(arg2));\n return addHeapObject(ret);\n};\n\nconst __wbg_buffer_e35e010c3ba9f945 = function(arg0) {\n var ret = getObject(arg0).buffer;\n return addHeapObject(ret);\n};\n\nconst __wbg_newwithbyteoffsetandlength_0c7ac30665ee26f8 = function(arg0, arg1, arg2) {\n var ret = new Int32Array(getObject(arg0), arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n};\n\nconst __wbg_new_c77df81d6c892c35 = function(arg0) {\n var ret = new Int32Array(getObject(arg0));\n return addHeapObject(ret);\n};\n\nconst __wbg_set_4a7e26c164c39e3d = function(arg0, arg1, arg2) {\n getObject(arg0).set(getObject(arg1), arg2 >>> 0);\n};\n\nconst __wbg_length_e0e70640cea5ee8c = function(arg0) {\n var ret = getObject(arg0).length;\n return ret;\n};\n\nconst __wbg_new_139e70222494b1ff = function(arg0) {\n var ret = new Uint8Array(getObject(arg0));\n return addHeapObject(ret);\n};\n\nconst __wbg_set_d771848e3c7935bb = function(arg0, arg1, arg2) {\n getObject(arg0).set(getObject(arg1), arg2 >>> 0);\n};\n\nconst __wbg_length_2cfa674c2a529bc1 = function(arg0) {\n var ret = getObject(arg0).length;\n return ret;\n};\n\nconst __wbg_newwithbyteoffsetandlength_12e0f22f7215a535 = function(arg0, arg1, arg2) {\n var ret = new Float64Array(getObject(arg0), arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n};\n\nconst __wbg_new_865d1422d0493dbb = function(arg0) {\n var ret = new Float64Array(getObject(arg0));\n return addHeapObject(ret);\n};\n\nconst __wbg_set_3735cb2b5a062242 = function(arg0, arg1, arg2) {\n getObject(arg0).set(getObject(arg1), arg2 >>> 0);\n};\n\nconst __wbg_length_77800d12ae1a0d8a = function(arg0) {\n var ret = getObject(arg0).length;\n return ret;\n};\n\nconst __wbg_newwithlength_e0c461e90217842c = function(arg0) {\n var ret = new Uint8Array(arg0 >>> 0);\n return addHeapObject(ret);\n};\n\nconst __wbg_subarray_8a52f1c1a11c02a8 = function(arg0, arg1, arg2) {\n var ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n};\n\nconst __wbindgen_throw = function(arg0, arg1) {\n throw new Error(getStringFromWasm0(arg0, arg1));\n};\n\nconst __wbindgen_memory = function() {\n var ret = _wasm_pie_bg_wasm__WEBPACK_IMPORTED_MODULE_0__[\"memory\"];\n return addHeapObject(ret);\n};\n\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../www/node_modules/webpack/buildin/harmony-module.js */ \"./node_modules/webpack/buildin/harmony-module.js\")(module)))\n\n//# sourceURL=webpack:///../pkg/wasm_pie_bg.js?");
/***/ }),
/***/ "../pkg/wasm_pie_bg.wasm":
/*!*******************************!*\
!*** ../pkg/wasm_pie_bg.wasm ***!
\*******************************/
/*! exports provided: memory, compute, __wbindgen_exn_store */
/***/ (function(module, exports, __webpack_require__) {
eval("\"use strict\";\n// Instantiate WebAssembly module\nvar wasmExports = __webpack_require__.w[module.i];\n__webpack_require__.r(exports);\n// export exports from WebAssembly module\nfor(var name in wasmExports) if(name != \"__webpack_init__\") exports[name] = wasmExports[name];\n// exec imports from WebAssembly module (for esm order)\n/* harmony import */ var m0 = __webpack_require__(/*! ./wasm_pie_bg.js */ \"../pkg/wasm_pie_bg.js\");\n\n\n// exec wasm module\nwasmExports[\"__webpack_init__\"]()\n\n//# sourceURL=webpack:///../pkg/wasm_pie_bg.wasm?");
/***/ }),
/***/ "./node_modules/webpack/buildin/harmony-module.js":
/*!*******************************************!*\
!*** (webpack)/buildin/harmony-module.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("module.exports = function(originalModule) {\n\tif (!originalModule.webpackPolyfill) {\n\t\tvar module = Object.create(originalModule);\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"exports\", {\n\t\t\tenumerable: true\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n\n\n//# sourceURL=webpack:///(webpack)/buildin/harmony-module.js?");
/***/ })
}]); |
#!/usr/bin/env python
#-*-coding:utf-8-*-
"""
A client for webkv
"""
from __future__ import print_function
import json
import sys
if sys.version_info[0]==2:
from urllib import urlencode, urlopen
elif sys.version_info[0]==3:
from urllib.parse import urlencode
from urllib.request import urlopen
else:
raise Exception('Unsupported version of Python')
def webkv_query(host, id, **kv):
params=urlencode(kv)
url=host.format(id=id)+'?'+urlencode(kv)
return json.loads(urlopen(url).read())
if __name__ == '__main__':
from timeit import timeit
webkvserv='http://127.0.0.1:8080/{id}'
number=10
dt=timeit('webkv_query(webkvserv, "test", x=1231)',
setup='from __main__ import webkv_query, webkvserv',
number=number)
print('timings:', dt/number)
|
"""
This command implements requirements 1
"""
from django.core.management.base import BaseCommand
from ...functions import current_rent
class Command(BaseCommand):
"Django Command; `lease_rent`."
help = """
Returns a list of current rent sorted in ascending order of rent.
"""
def add_arguments(self, parser):
help_text = """
Specify the max amount of items, by default this
is: '%(default)s'."""
parser.add_argument(
"--max", type=int, default=current_rent.DEFAULT, help=help_text
)
def handle(self, *args, **options):
current_rent.current_rent(options["max"])
|
function saveItem(key,value){
localStorage.setItem(key, value);
}
function getItem(key){
return localStorage.getItem(key);
}
function removeItem(key){
localStorage.removeItem(key);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.