text
stringlengths
3
1.05M
/*eslint no-var:0, max-len:0 */ 'use strict'; const { expect } = require('chai'); const Knex = require('../../../knex'); const _ = require('lodash'); const delay = require('../../../lib/execution/internal/delay'); const { isPostgreSQL, isOracle, isRedshift, isOneOfDbs, isSQLite, isMysql, } = require('../../util/db-helpers'); module.exports = function (knex) { describe('Additional', function () { describe('Custom response processing', () => { before('setup custom response handler', () => { knex.client.config.postProcessResponse = (response, queryContext) => { response.callCount = response.callCount ? response.callCount + 1 : 1; response.queryContext = queryContext; return response; }; }); after('restore client configuration', () => { knex.client.config.postProcessResponse = null; }); it('should process normal response', () => { return knex('accounts') .limit(1) .then((res) => { expect(res.callCount).to.equal(1); }); }); it('should pass query context to the custom handler', () => { return knex('accounts') .queryContext('the context') .limit(1) .then((res) => { expect(res.queryContext).to.equal('the context'); }); }); it('should process raw response', () => { return knex.raw('select * from ??', ['accounts']).then((res) => { expect(res.callCount).to.equal(1); }); }); it('should pass query context for raw responses', () => { return knex .raw('select * from ??', ['accounts']) .queryContext('the context') .then((res) => { expect(res.queryContext).to.equal('the context'); }); }); it('should process response done in transaction', () => { return knex .transaction((trx) => { return trx('accounts') .limit(1) .then((res) => { expect(res.callCount).to.equal(1); return res; }); }) .then((res) => { expect(res.callCount).to.equal(1); }); }); it('should pass query context for responses from transactions', () => { return knex .transaction((trx) => { return trx('accounts') .queryContext('the context') .limit(1) .then((res) => { expect(res.queryContext).to.equal('the context'); return res; }); }) .then((res) => { expect(res.queryContext).to.equal('the context'); }); }); it('should handle error correctly in a stream', (done) => { const stream = knex('wrongtable').limit(1).stream(); stream.on('error', () => { done(); }); }); it('should process response done through a stream', (done) => { let response; const stream = knex('accounts').limit(1).stream(); stream.on('data', (res) => { response = res; }); stream.on('finish', () => { expect(response.callCount).to.equal(1); done(); }); }); it('should pass query context for responses through a stream', (done) => { let response; const stream = knex('accounts') .queryContext('the context') .limit(1) .stream(); stream.on('data', (res) => { response = res; }); stream.on('finish', () => { expect(response.queryContext).to.equal('the context'); done(); }); }); it('should process response for each row done through a stream', (done) => { const stream = knex('accounts').limit(5).stream(); let count = 0; stream.on('data', () => count++); stream.on('finish', () => { expect(count).to.equal(5); done(); }); }); }); describe('columnInfo with wrapIdentifier and postProcessResponse', () => { before('setup hooks', () => { knex.client.config.postProcessResponse = (response) => { return _.mapKeys(response, (val, key) => { return _.camelCase(key); }); }; knex.client.config.wrapIdentifier = (id, origImpl) => { return origImpl(_.snakeCase(id)); }; }); after('restore client configuration', () => { knex.client.config.postProcessResponse = null; knex.client.config.wrapIdentifier = null; }); it('should work using camelCased table name', () => { return knex('testTableTwo') .columnInfo() .then((res) => { expect(Object.keys(res)).to.have.all.members([ 'id', 'accountId', 'details', 'status', 'jsonData', ]); }); }); it('should work using snake_cased table name', () => { return knex('test_table_two') .columnInfo() .then((res) => { expect(Object.keys(res)).to.have.all.members([ 'id', 'accountId', 'details', 'status', 'jsonData', ]); }); }); }); describe('returning with wrapIdentifier and postProcessResponse` (TODO: fix to work on all possible dialects)', function () { const origHooks = {}; if (!isOneOfDbs(knex, ['pg', 'mssql'])) { return; } before('setup custom hooks', () => { origHooks.postProcessResponse = knex.client.config.postProcessResponse; origHooks.wrapIdentifier = knex.client.config.wrapIdentifier; // Add `_foo` to each identifier. knex.client.config.postProcessResponse = (res) => { if (Array.isArray(res)) { return res.map((it) => { if (typeof it === 'object') { return _.mapKeys(it, (value, key) => { return key + '_foo'; }); } else { return it; } }); } else { return res; } }; // Remove `_foo` from the end of each identifier. knex.client.config.wrapIdentifier = (id) => { return id.substring(0, id.length - 4); }; }); after('restore hooks', () => { knex.client.config.postProcessResponse = origHooks.postProcessResponse; knex.client.config.wrapIdentifier = origHooks.wrapIdentifier; }); it('should return the correct column when a single property is given to returning', () => { return knex('accounts_foo') .insert({ balance_foo: 123 }) .returning('balance_foo') .then((res) => { expect(res).to.eql([123]); }); }); it('should return the correct columns when multiple properties are given to returning', () => { return knex('accounts_foo') .insert({ balance_foo: 123, email_foo: '[email protected]' }) .returning(['balance_foo', 'email_foo']) .then((res) => { expect(res).to.eql([ { balance_foo: 123, email_foo: '[email protected]' }, ]); }); }); }); it('should truncate a table with truncate', function () { return knex('test_table_two') .truncate() .testSql(function (tester) { tester('mysql', 'truncate `test_table_two`'); tester('pg', 'truncate "test_table_two" restart identity'); tester('pg-redshift', 'truncate "test_table_two"'); tester('sqlite3', 'delete from `test_table_two`'); tester('oracledb', 'truncate table "test_table_two"'); tester('mssql', 'truncate table [test_table_two]'); }) .then(() => { return knex('test_table_two') .select('*') .then((resp) => { expect(resp).to.have.length(0); }); }) .then(() => { // Insert new data after truncate and make sure ids restart at 1. // This doesn't currently work on oracle, where the created sequence // needs to be manually reset. // On redshift, one would need to create an entirely new table and do // `insert into ... (select ...); alter table rename...` if (isOracle(knex) || isRedshift(knex)) { return; } return knex('test_table_two') .insert({ status: 1 }) .then((res) => { return knex('test_table_two') .select('id') .first() .then((res) => { expect(res).to.be.an('object'); expect(res.id).to.equal(1); }); }); }); }); it('should allow raw queries directly with `knex.raw`', function () { const tables = { mysql: 'SHOW TABLES', mysql2: 'SHOW TABLES', pg: "SELECT table_name FROM information_schema.tables WHERE table_schema='public'", 'pg-redshift': "SELECT table_name FROM information_schema.tables WHERE table_schema='public'", sqlite3: "SELECT name FROM sqlite_master WHERE type='table';", oracledb: 'select TABLE_NAME from USER_TABLES', mssql: "SELECT table_name FROM information_schema.tables WHERE table_schema='dbo'", }; return knex .raw(tables[knex.client.driverName]) .testSql(function (tester) { tester(knex.client.driverName, tables[knex.client.driverName]); }); }); it('should allow using the primary table as a raw statement', function () { expect(knex(knex.raw('raw_table_name')).toQuery()).to.equal( 'select * from raw_table_name' ); }); it('should allow using .fn-methods to create raw statements', function () { expect(knex.fn.now().prototype === knex.raw().prototype); expect(knex.fn.now().toQuery()).to.equal('CURRENT_TIMESTAMP'); expect(knex.fn.now(6).toQuery()).to.equal('CURRENT_TIMESTAMP(6)'); }); it('gets the columnInfo', function () { return knex('datatype_test') .columnInfo() .testSql(function (tester) { tester( 'mysql', 'select * from information_schema.columns where table_name = ? and table_schema = ?', null, { enum_value: { defaultValue: null, maxLength: 1, nullable: true, type: 'enum', }, uuid: { defaultValue: null, maxLength: 36, nullable: false, type: 'char', }, } ); tester( 'pg', 'select * from information_schema.columns where table_name = ? and table_catalog = ? and table_schema = current_schema()', null, { enum_value: { defaultValue: null, maxLength: null, nullable: true, type: 'text', }, uuid: { defaultValue: null, maxLength: null, nullable: false, type: 'uuid', }, } ); tester( 'pg-redshift', 'select * from information_schema.columns where table_name = ? and table_catalog = ? and table_schema = current_schema()', null, { enum_value: { defaultValue: null, maxLength: 255, nullable: true, type: 'character varying', }, uuid: { defaultValue: null, maxLength: 36, nullable: false, type: 'character', }, } ); tester('sqlite3', 'PRAGMA table_info(`datatype_test`)', [], { enum_value: { defaultValue: null, maxLength: null, nullable: true, type: 'text', }, uuid: { defaultValue: null, maxLength: '36', nullable: false, type: 'char', }, }); tester( 'oracledb', "select * from xmltable( '/ROWSET/ROW'\n passing dbms_xmlgen.getXMLType('\n select char_col_decl_length, column_name, data_type, data_default, nullable\n from all_tab_columns where table_name = ''datatype_test'' ')\n columns\n CHAR_COL_DECL_LENGTH number, COLUMN_NAME varchar2(200), DATA_TYPE varchar2(106),\n DATA_DEFAULT clob, NULLABLE varchar2(1))", [], { enum_value: { defaultValue: null, nullable: true, maxLength: 1, type: 'VARCHAR2', }, uuid: { defaultValue: null, nullable: false, maxLength: 36, type: 'CHAR', }, } ); tester( 'mssql', "select [COLUMN_NAME], [COLUMN_DEFAULT], [DATA_TYPE], [CHARACTER_MAXIMUM_LENGTH], [IS_NULLABLE] from information_schema.columns where table_name = ? and table_catalog = ? and table_schema = 'dbo'", ['datatype_test', 'knex_test'], { enum_value: { defaultValue: null, maxLength: 100, nullable: true, type: 'nvarchar', }, uuid: { defaultValue: null, maxLength: null, nullable: false, type: 'uniqueidentifier', }, } ); }); }); it('gets the columnInfo with columntype', function () { return knex('datatype_test') .columnInfo('uuid') .testSql(function (tester) { tester( 'mysql', 'select * from information_schema.columns where table_name = ? and table_schema = ?', null, { defaultValue: null, maxLength: 36, nullable: false, type: 'char', } ); tester( 'pg', 'select * from information_schema.columns where table_name = ? and table_catalog = ? and table_schema = current_schema()', null, { defaultValue: null, maxLength: null, nullable: false, type: 'uuid', } ); tester( 'pg-redshift', 'select * from information_schema.columns where table_name = ? and table_catalog = ? and table_schema = current_schema()', null, { defaultValue: null, maxLength: 36, nullable: false, type: 'character', } ); tester('sqlite3', 'PRAGMA table_info(`datatype_test`)', [], { defaultValue: null, maxLength: '36', nullable: false, type: 'char', }); tester( 'oracledb', "select * from xmltable( '/ROWSET/ROW'\n passing dbms_xmlgen.getXMLType('\n select char_col_decl_length, column_name, data_type, data_default, nullable\n from all_tab_columns where table_name = ''datatype_test'' ')\n columns\n CHAR_COL_DECL_LENGTH number, COLUMN_NAME varchar2(200), DATA_TYPE varchar2(106),\n DATA_DEFAULT clob, NULLABLE varchar2(1))", [], { defaultValue: null, maxLength: 36, nullable: false, type: 'CHAR', } ); tester( 'mssql', "select [COLUMN_NAME], [COLUMN_DEFAULT], [DATA_TYPE], [CHARACTER_MAXIMUM_LENGTH], [IS_NULLABLE] from information_schema.columns where table_name = ? and table_catalog = ? and table_schema = 'dbo'", null, { defaultValue: null, maxLength: null, nullable: false, type: 'uniqueidentifier', } ); }); }); it('#2184 - should properly escape table name for SQLite columnInfo', function () { if (!isSQLite(knex)) { return this.skip(); } return knex.schema .dropTableIfExists('group') .then(function () { return knex.schema.createTable('group', function (table) { table.integer('foo'); }); }) .then(function () { return knex('group').columnInfo(); }) .then(function (columnInfo) { expect(columnInfo).to.deep.equal({ foo: { type: 'integer', maxLength: null, nullable: true, defaultValue: null, }, }); }); }); if (knex.client.driverName === 'oracledb') { const oracledb = require('oracledb'); describe('test oracle stored procedures', function () { it('create stored procedure', function () { return knex .raw( ` CREATE OR REPLACE PROCEDURE SYSTEM.multiply (X IN NUMBER, Y IN NUMBER, OUTPUT OUT NUMBER) IS BEGIN OUTPUT := X * Y; END;` ) .then(function (result) { expect(result).to.be.an('array'); }); }); it('get outbound values from stored procedure', function () { const bindVars = { x: 6, y: 7, output: { dir: oracledb.BIND_OUT, }, }; return knex .raw('BEGIN SYSTEM.MULTIPLY(:x, :y, :output); END;', bindVars) .then(function (result) { expect(result[0]).to.be.ok; expect(result[0]).to.equal('42'); }); }); it('drop stored procedure', function () { const bindVars = { x: 6, y: 7 }; return knex .raw('drop procedure SYSTEM.MULTIPLY', bindVars) .then(function (result) { expect(result).to.be.ok; expect(result).to.be.an('array'); }); }); }); } it('should allow renaming a column', function () { let countColumn; switch (knex.client.driverName) { case 'oracledb': countColumn = 'COUNT(*)'; break; case 'mssql': countColumn = ''; break; default: countColumn = 'count(*)'; break; } let count; const inserts = []; _.times(40, function (i) { inserts.push({ email: 'email' + i, first_name: 'Test', last_name: 'Data', }); }); return knex('accounts') .insert(inserts) .then(function () { return knex.count('*').from('accounts'); }) .then(function (resp) { count = resp[0][countColumn]; return knex.schema .table('accounts', function (t) { t.renameColumn('about', 'about_col'); }) .testSql(function (tester) { tester('mysql', ['show fields from `accounts` where field = ?']); tester('pg', [ 'alter table "accounts" rename "about" to "about_col"', ]); tester('pg-redshift', [ 'alter table "accounts" rename "about" to "about_col"', ]); tester('sqlite3', [ 'alter table `accounts` rename `about` to `about_col`', ]); tester('oracledb', [ 'DECLARE PK_NAME VARCHAR(200); IS_AUTOINC NUMBER := 0; BEGIN EXECUTE IMMEDIATE (\'ALTER TABLE "accounts" RENAME COLUMN "about" TO "about_col"\'); SELECT COUNT(*) INTO IS_AUTOINC from "USER_TRIGGERS" where trigger_name = \'accounts_autoinc_trg\'; IF (IS_AUTOINC > 0) THEN SELECT cols.column_name INTO PK_NAME FROM all_constraints cons, all_cons_columns cols WHERE cons.constraint_type = \'P\' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner AND cols.table_name = \'accounts\'; IF (\'about_col\' = PK_NAME) THEN EXECUTE IMMEDIATE (\'DROP TRIGGER "accounts_autoinc_trg"\'); EXECUTE IMMEDIATE (\'create or replace trigger "accounts_autoinc_trg" BEFORE INSERT on "accounts" for each row declare checking number := 1; begin if (:new."about_col" is null) then while checking >= 1 loop select "accounts_seq".nextval into :new."about_col" from dual; select count("about_col") into checking from "accounts" where "about_col" = :new."about_col"; end loop; end if; end;\'); end if; end if;END;', ]); tester('mssql', ["exec sp_rename ?, ?, 'COLUMN'"]); }); }) .then(function () { return knex.count('*').from('accounts'); }) .then(function (resp) { expect(resp[0][countColumn]).to.equal(count); }) .then(function () { return knex('accounts').select('about_col'); }) .then(function () { return knex.schema.table('accounts', function (t) { t.renameColumn('about_col', 'about'); }); }) .then(function () { return knex.count('*').from('accounts'); }) .then(function (resp) { expect(resp[0][countColumn]).to.equal(count); }); }); it('should allow dropping a column', function () { let countColumn; switch (knex.client.driverName) { case 'oracledb': countColumn = 'COUNT(*)'; break; case 'mssql': countColumn = ''; break; default: countColumn = 'count(*)'; break; } let count; return knex .count('*') .from('accounts') .then(function (resp) { count = resp[0][countColumn]; }) .then(function () { return knex.schema .table('accounts', function (t) { t.dropColumn('first_name'); }) .testSql(function (tester) { tester('mysql', ['alter table `accounts` drop `first_name`']); tester('pg', ['alter table "accounts" drop column "first_name"']); tester('pg-redshift', [ 'alter table "accounts" drop column "first_name"', ]); tester('sqlite3', ['PRAGMA table_info(`accounts`)']); tester('oracledb', [ 'alter table "accounts" drop ("first_name")', ]); //tester('oracledb', ['alter table "accounts" drop ("first_name")']); tester('mssql', [ "\n DECLARE @constraint varchar(100) = (SELECT default_constraints.name\n FROM sys.all_columns\n INNER JOIN sys.tables\n ON all_columns.object_id = tables.object_id\n INNER JOIN sys.schemas\n ON tables.schema_id = schemas.schema_id\n INNER JOIN sys.default_constraints\n ON all_columns.default_object_id = default_constraints.object_id\n WHERE schemas.name = 'dbo'\n AND tables.name = 'accounts'\n AND all_columns.name = 'first_name')\n\n IF @constraint IS NOT NULL EXEC('ALTER TABLE accounts DROP CONSTRAINT ' + @constraint)", 'ALTER TABLE [accounts] DROP COLUMN [first_name]', ]); }); }) .then(function () { return knex.select('*').from('accounts').first(); }) .then(function (resp) { expect(_.keys(resp).sort()).to.eql([ 'about', 'balance', 'created_at', 'email', 'id', 'last_name', 'logins', 'phone', 'updated_at', ]); }) .then(function () { return knex.count('*').from('accounts'); }) .then(function (resp) { expect(resp[0][countColumn]).to.equal(count); }); }); it('.timeout() should throw TimeoutError', function () { const driverName = knex.client.driverName; if (driverName === 'sqlite3') { return this.skip(); } //TODO -- No built-in support for sleeps if (/redshift/.test(driverName)) { return this.skip(); } const testQueries = { pg: function () { return knex.raw('SELECT pg_sleep(1)'); }, mysql: function () { return knex.raw('SELECT SLEEP(1)'); }, mysql2: function () { return knex.raw('SELECT SLEEP(1)'); }, mssql: function () { return knex.raw("WAITFOR DELAY '00:00:01'"); }, oracledb: function () { return knex.raw('begin dbms_lock.sleep(1); end;'); }, }; if (!Object.prototype.hasOwnProperty.call(testQueries, driverName)) { throw new Error('Missing test query for driver: ' + driverName); } const query = testQueries[driverName](); return query .timeout(200) .then(function () { expect(true).to.equal(false); }) .catch(function (error) { expect(_.pick(error, 'timeout', 'name', 'message')).to.deep.equal({ timeout: 200, name: 'KnexTimeoutError', message: 'Defined query timeout of 200ms exceeded when running query.', }); }); }); it('.timeout(ms, {cancel: true}) should throw TimeoutError and cancel slow query', function () { if (isSQLite(knex)) { return this.skip(); } //TODO -- No built-in support for sleeps if (isRedshift(knex)) { return this.skip(); } // There's unexpected behavior caused by knex releasing a connection back // to the pool because of a timeout when a long query is still running. // A subsequent query will acquire the connection (still in-use) and hang // until the first query finishes. Setting a sleep time longer than the // mocha timeout exposes this behavior. const testQueries = { pg: function () { return knex.raw('SELECT pg_sleep(10)'); }, mysql: function () { return knex.raw('SELECT SLEEP(10)'); }, mysql2: function () { return knex.raw('SELECT SLEEP(10)'); }, mssql: function () { return knex.raw("WAITFOR DELAY '00:00:10'"); }, oracledb: function () { return knex.raw('begin dbms_lock.sleep(10); end;'); }, }; const driverName = knex.client.driverName; if (!Object.prototype.hasOwnProperty.call(testQueries, driverName)) { throw new Error('Missing test query for driverName: ' + driverName); } const query = testQueries[driverName](); function addTimeout() { return query.timeout(200, { cancel: true }); } // Only mysql/postgres query cancelling supported for now if (!isMysql(knex) && !isPostgreSQL(knex)) { expect(addTimeout).to.throw( 'Query cancelling not supported for this dialect' ); return; // TODO: Use `this.skip()` here? } const getProcessesQueries = { pg: function () { return knex.raw('SELECT * from pg_stat_activity'); }, mysql: function () { return knex.raw('SHOW PROCESSLIST'); }, mysql2: function () { return knex.raw('SHOW PROCESSLIST'); }, }; if ( !Object.prototype.hasOwnProperty.call(getProcessesQueries, driverName) ) { throw new Error('Missing test query for driverName: ' + driverName); } const getProcessesQuery = getProcessesQueries[driverName](); return addTimeout() .then(function () { expect(true).to.equal(false); }) .catch(function (error) { expect(_.pick(error, 'timeout', 'name', 'message')).to.deep.equal({ timeout: 200, name: 'KnexTimeoutError', message: 'Defined query timeout of 200ms exceeded when running query.', }); // Ensure sleep command is removed. // This query will hang if a connection gets released back to the pool // too early. // 50ms delay since killing query doesn't seem to have immediate effect to the process listing return delay(50) .then(function () { return getProcessesQuery; }) .then(function (results) { let processes; let sleepProcess; if (_.startsWith(driverName, 'pg')) { processes = results.rows; sleepProcess = _.find(processes, { query: query.toString() }); } else { processes = results[0]; sleepProcess = _.find(processes, { Info: 'SELECT SLEEP(10)', }); } expect(sleepProcess).to.equal(undefined); }); }); }); it('.timeout(ms, {cancel: true}) should throw error if cancellation cannot acquire connection', async function () { // Only mysql/postgres query cancelling supported for now if (!isMysql(knex) && !isPostgreSQL(knex)) { return this.skip(); } // To make this test easier, I'm changing the pool settings to max 1. // Also setting acquireTimeoutMillis to lower as not to wait the default time const knexConfig = _.cloneDeep(knex.client.config); knexConfig.pool.min = 0; knexConfig.pool.max = 1; knexConfig.pool.acquireTimeoutMillis = 100; const knexDb = new Knex(knexConfig); const testQueries = { pg: function () { return knexDb.raw('SELECT pg_sleep(10)'); }, mysql: function () { return knexDb.raw('SELECT SLEEP(10)'); }, mysql2: function () { return knexDb.raw('SELECT SLEEP(10)'); }, mssql: function () { return knexDb.raw("WAITFOR DELAY '00:00:10'"); }, oracle: function () { return knexDb.raw('begin dbms_lock.sleep(10); end;'); }, }; const driverName = knex.client.driverName; if (!Object.prototype.hasOwnProperty.call(testQueries, driverName)) { throw new Error('Missing test query for dialect: ' + driverName); } const query = testQueries[driverName](); try { await expect( query.timeout(1, { cancel: true }) ).to.eventually.be.rejected.and.to.deep.include({ timeout: 1, name: 'KnexTimeoutError', message: 'After query timeout of 1ms exceeded, cancelling of query failed.', }); } finally { await knexDb.destroy(); } }); it('.timeout(ms, {cancel: true}) should release connections after failing if connection cancellation throws an error', async function () { // Only mysql/postgres query cancelling supported for now if (!isPostgreSQL(knex)) { return this.skip(); } // To make this test easier, I'm changing the pool settings to max 1. // Also setting acquireTimeoutMillis to lower as not to wait the default time const knexConfig = _.cloneDeep(knex.client.config); knexConfig.pool.min = 0; knexConfig.pool.max = 2; knexConfig.pool.acquireTimeoutMillis = 100; const rawTestQueries = { pg: (sleepSeconds) => `SELECT pg_sleep(${sleepSeconds})`, }; const driverName = knex.client.driverName; if (!Object.prototype.hasOwnProperty.call(rawTestQueries, driverName)) { throw new Error('Missing test query for driverName: ' + driverName); } const knexDb = new Knex(knexConfig); const getTestQuery = (sleepSeconds = 10) => { const rawTestQuery = rawTestQueries[driverName](sleepSeconds); return knexDb.raw(rawTestQuery); }; const knexPrototype = Object.getPrototypeOf(knexDb.client); const originalWrappedCancelQueryCall = knexPrototype._wrappedCancelQueryCall; knexPrototype._wrappedCancelQueryCall = (conn) => { return knexPrototype.query(conn, { method: 'raw', sql: 'TestError', }); }; const queryTimeout = 10; const secondQueryTimeout = 11; try { await expect( getTestQuery().timeout(queryTimeout, { cancel: true }) ).to.be.eventually.rejected.and.deep.include({ timeout: queryTimeout, name: 'error', message: `After query timeout of ${queryTimeout}ms exceeded, cancelling of query failed.`, }); knexPrototype._wrappedCancelQueryCall = originalWrappedCancelQueryCall; await expect( getTestQuery().timeout(secondQueryTimeout, { cancel: true }) ).to.be.eventually.rejected.and.deep.include({ timeout: secondQueryTimeout, name: 'KnexTimeoutError', message: `Defined query timeout of ${secondQueryTimeout}ms exceeded when running query.`, }); } finally { await knexDb.destroy(); } }); it('Event: query-response', function () { let queryCount = 0; const onQueryResponse = function (response, obj, builder) { queryCount++; expect(response).to.be.an('array'); expect(obj).to.be.an('object'); expect(obj.__knexUid).to.be.a('string'); expect(obj.__knexQueryUid).to.be.a('string'); expect(builder).to.be.an('object'); }; knex.on('query-response', onQueryResponse); return knex('accounts') .select() .on('query-response', onQueryResponse) .then(function () { return knex.transaction(function (tr) { return tr('accounts') .select() .on('query-response', onQueryResponse); //Transactions should emit the event as well }); }) .then(function () { knex.removeListener('query-response', onQueryResponse); expect(queryCount).to.equal(4); }); }); it('Event: preserves listeners on a copy with user params', function () { let queryCount = 0; const onQueryResponse = function (response, obj, builder) { queryCount++; expect(response).to.be.an('array'); expect(obj).to.be.an('object'); expect(obj.__knexUid).to.be.a('string'); expect(obj.__knexQueryUid).to.be.a('string'); expect(builder).to.be.an('object'); }; knex.on('query-response', onQueryResponse); const knexCopy = knex.withUserParams({}); return knexCopy('accounts') .select() .on('query-response', onQueryResponse) .then(function () { return knexCopy.transaction(function (tr) { return tr('accounts') .select() .on('query-response', onQueryResponse); //Transactions should emit the event as well }); }) .then(function () { expect(Object.keys(knex._events).length).to.equal(1); expect(Object.keys(knexCopy._events).length).to.equal(1); knex.removeListener('query-response', onQueryResponse); expect(Object.keys(knex._events).length).to.equal(0); expect(queryCount).to.equal(4); }); }); it('Event: query-error', function () { let queryCountKnex = 0; let queryCountBuilder = 0; const onQueryErrorKnex = function (error, obj) { queryCountKnex++; expect(obj).to.be.an('object'); expect(obj.__knexUid).to.be.a('string'); expect(obj.__knexQueryUid).to.be.a('string'); expect(error).to.be.an('error'); }; const onQueryErrorBuilder = function (error, obj) { queryCountBuilder++; expect(obj).to.be.an('object'); expect(obj.__knexUid).to.be.a('string'); expect(obj.__knexQueryUid).to.be.a('string'); expect(error).to.be.an('error'); }; knex.on('query-error', onQueryErrorKnex); return knex .raw('Broken query') .on('query-error', onQueryErrorBuilder) .then(function () { expect(true).to.equal(false); //Should not be resolved }) .catch(function () { knex.removeListener('query-error', onQueryErrorKnex); knex.removeListener('query-error', onQueryErrorBuilder); expect(queryCountBuilder).to.equal(1); expect(queryCountKnex).to.equal(1); }); }); it('Event: start', function () { return knex('accounts') .insert({ last_name: 'Start event test' }) .then(function () { const queryBuilder = knex('accounts').select(); queryBuilder.on('start', function (builder) { //Alter builder prior to compilation //Select only one row builder.where('last_name', 'Start event test').first(); }); return queryBuilder; }) .then(function (row) { expect(row).to.exist; expect(row.last_name).to.equal('Start event test'); }); }); it("Event 'query' should not emit native sql string", function () { const builder = knex('accounts').where('id', 1).select(); builder.on('query', function (obj) { const native = builder.toSQL().toNative().sql; const sql = builder.toSQL().sql; //Only assert if they diff to begin with. //IE Maria does not diff if (native !== sql) { expect(obj.sql).to.not.equal(builder.toSQL().toNative().sql); expect(obj.sql).to.equal(builder.toSQL().sql); } }); return builder; }); describe('async stack traces', function () { before(() => { knex.client.config.asyncStackTraces = true; }); after(() => { delete knex.client.config.asyncStackTraces; }); it('should capture stack trace on raw query', () => { return knex.raw('select * from some_nonexisten_table').catch((err) => { expect(err.stack.split('\n')[2]).to.match(/at Object\.raw \(/); // the index 2 might need adjustment if the code is refactored expect(typeof err.originalStack).to.equal('string'); }); }); it('should capture stack trace on schema builder', () => { return knex.schema .renameTable('some_nonexisten_table', 'whatever') .catch((err) => { expect(err.stack.split('\n')[1]).to.match(/client\.schemaBuilder/); // the index 1 might need adjustment if the code is refactored expect(typeof err.originalStack).to.equal('string'); }); }); }); it('Overwrite knex.logger functions using config', () => { const knexConfig = _.clone(knex.client.config); let callCount = 0; const assertCall = function (expectedMessage, message) { expect(message).to.equal(expectedMessage); callCount++; }; knexConfig.log = { warn: assertCall.bind(null, 'test'), error: assertCall.bind(null, 'test'), debug: assertCall.bind(null, 'test'), deprecate: assertCall.bind( null, 'test is deprecated, please use test2' ), }; //Sqlite warning message knexConfig.useNullAsDefault = true; const knexDb = new Knex(knexConfig); knexDb.client.logger.warn('test'); knexDb.client.logger.error('test'); knexDb.client.logger.debug('test'); knexDb.client.logger.deprecate('test', 'test2'); expect(callCount).to.equal(4); }); }); };
import botocore import datetime import re import logging import boto3 logger = logging.getLogger() logger.setLevel(logging.INFO) class RDSBackup: def __init__(self): self.my_rds = boto3.client('rds') def get_rds_instance(self,instances): try: result = False for instance in instances: logger.info("Checking if RDS instance: " + instance + " exists") response = self.my_rds.describe_db_instances( DBInstanceIdentifier=instance ) if 'DBInstances' in response: logger.info("RDS Instance exists") result = True else: logger.info("RDS Instance does not exist") return result except botocore.exceptions.ClientError as error: if error.response['Error']['Code'] == 'ResourceNotFound': logger.info("RDS instance does not exist. Returning false") return False except Exception as e: logger.error('Class RDSBackup. Method get_rds_instance failed with error: ' + str(e)) def create_rds_snapshot(self, instances): try: for instance in instances: logger.info("Creating RDS instance snapshot for instance " + instance) date = str(datetime.datetime.now().strftime('%Y-%m-%d')) snapshot = "{0}-{1}-{2}".format("lambda-dr-snapshot", instance, date) response = self.my_rds.create_db_snapshot(DBSnapshotIdentifier=snapshot, DBInstanceIdentifier=instance,) logger.info(response) return response except Exception as e: logger.error('Class RDSBackup Method create_rds_snapshot failed with error: ' + str(e))
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be found # in the LICENSE file. """ Analyze recent SkPicture bench data, and output suggested ranges. The outputs can be edited and pasted to bench_expectations.txt to trigger buildbot alerts if the actual benches are out of range. Details are documented in the .txt file. Currently the easiest way to update bench_expectations.txt is to delete all skp bench lines, run this script, and redirect outputs (">>") to be added to the .txt file. TODO(bensong): find a better way for updating the bench lines in place. Note: since input data are stored in Google Storage, you will need to set up the corresponding library. See http://developers.google.com/storage/docs/gspythonlibrary for details. """ __author__ = '[email protected] (Ben Chen)' import bench_util import boto import cStringIO import optparse import re import shutil from oauth2_plugin import oauth2_plugin # Ratios for calculating suggested picture bench upper and lower bounds. BENCH_UB = 1.1 # Allow for 10% room for normal variance on the up side. BENCH_LB = 0.85 # Further allow for a fixed amount of noise. This is especially useful for # benches of smaller absolute value. Keeping this value small will not affect # performance tunings. BENCH_ALLOWED_NOISE = 10 # List of platforms to track. PLATFORMS = ['Mac_Float_Bench_32', 'Nexus10_4-1_Float_Bench_32', 'Shuttle_Ubuntu12_ATI5770_Float_Bench_32', ] # Filter for configs of no interest. They are old config names replaced by more # specific ones. CONFIGS_TO_FILTER = ['gpu', 'raster'] # Template for gsutil uri. GOOGLE_STORAGE_URI_SCHEME = 'gs' URI_BUCKET = 'chromium-skia-gm' # Constants for optparse. USAGE_STRING = 'USAGE: %s [options]' HOWTO_STRING = """ Feel free to revise PLATFORMS for your own needs. The default is the most common combination that we care most about. Platforms that did not run bench_pictures in the given revision range will not have corresponding outputs. Please check http://go/skpbench to choose a range that fits your needs. BENCH_UB, BENCH_LB and BENCH_ALLOWED_NOISE can be changed to expand or narrow the permitted bench ranges without triggering buidbot alerts. """ HELP_STRING = """ Outputs expectation picture bench ranges for the latest revisions for the given revision range. For instance, --rev_range=6000:6000 will return only bench ranges for the bots that ran bench_pictures at rev 6000; --rev-range=6000:7000 may have multiple bench data points for each bench configuration, and the code returns bench data for the latest revision of all available (closer to 7000). """ + HOWTO_STRING OPTION_REVISION_RANGE = '--rev-range' OPTION_REVISION_RANGE_SHORT = '-r' # Bench bench representation algorithm flag. OPTION_REPRESENTATION_ALG = '--algorithm' OPTION_REPRESENTATION_ALG_SHORT = '-a' # List of valid representation algorithms. REPRESENTATION_ALGS = ['avg', 'min', 'med', '25th'] def OutputSkpBenchExpectations(rev_min, rev_max, representation_alg): """Reads skp bench data from google storage, and outputs expectations. Ignores data with revisions outside [rev_min, rev_max] integer range. For bench data with multiple revisions, we use higher revisions to calculate expected bench values. Uses the provided representation_alg for calculating bench representations. """ expectation_dic = {} uri = boto.storage_uri(URI_BUCKET, GOOGLE_STORAGE_URI_SCHEME) for obj in uri.get_bucket(): # Filters out non-skp-bench files. if (not obj.name.startswith('perfdata/Skia_') or obj.name.find('_data_skp_') < 0): continue # Ignores uninterested platforms. platform = obj.name.split('/')[1][5:] # Removes "Skia_" prefix. if platform not in PLATFORMS: continue # Filters by revision. for rev in range(rev_min, rev_max + 1): if '_r%s_' % rev not in obj.name: continue contents = cStringIO.StringIO() obj.get_file(contents) for point in bench_util.parse('', contents.getvalue().split('\n'), representation_alg): if point.config in CONFIGS_TO_FILTER: continue # TODO(bensong): the filtering below is only needed during skp generation # system transitioning. Change it once the new system (bench name starts # with http) is stable for the switch-over, and delete it once we # deprecate the old ones. if point.bench.startswith('http'): continue key = '%s_%s_%s,%s-%s' % (point.bench, point.config, point.time_type, platform, representation_alg) # It is fine to have later revisions overwrite earlier benches, since we # only use the latest bench within revision range to set expectations. expectation_dic[key] = point.time keys = expectation_dic.keys() keys.sort() for key in keys: bench_val = expectation_dic[key] # Prints out expectation lines. print '%s,%.3f,%.3f,%.3f' % (key, bench_val, bench_val * BENCH_LB - BENCH_ALLOWED_NOISE, bench_val * BENCH_UB + BENCH_ALLOWED_NOISE) def main(): """Parses flags and outputs expected Skia picture bench results.""" parser = optparse.OptionParser(USAGE_STRING % '%prog' + HELP_STRING) parser.add_option(OPTION_REVISION_RANGE_SHORT, OPTION_REVISION_RANGE, dest='rev_range', help='(Mandatory) revision range separated by ":", e.g., 6000:6005') parser.add_option(OPTION_REPRESENTATION_ALG_SHORT, OPTION_REPRESENTATION_ALG, dest='alg', default='25th', help=('Bench representation algorithm. One of ' '%s. Default to "25th".' % str(REPRESENTATION_ALGS))) (options, args) = parser.parse_args() if options.rev_range: range_match = re.search('(\d+)\:(\d+)', options.rev_range) if not range_match: parser.error('Wrong format for rev-range [%s]' % options.rev_range) else: rev_min = int(range_match.group(1)) rev_max = int(range_match.group(2)) OutputSkpBenchExpectations(rev_min, rev_max, options.alg) else: parser.error('Please provide mandatory flag %s' % OPTION_REVISION_RANGE) if '__main__' == __name__: main()
from sqlalchemy import ( MetaData, Table, Column, NVARCHAR, Integer, DateTime, ForeignKey, UniqueConstraint, ) meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine u = Table("user", meta, autoload=True) t = Table( "participant_import_definition", meta, Column("id", Integer, primary_key=True), Column("name", NVARCHAR(200), nullable=False), Column("recruitment_date_column_name", NVARCHAR(100)), Column("first_name_column_name", NVARCHAR(100)), Column("last_name_column_name", NVARCHAR(100)), Column("postcode_column_name", NVARCHAR(100)), Column("birth_date_column_name", NVARCHAR(100)), Column("non_completion_reason_column_name", NVARCHAR(100)), Column("withdrawal_date_column_name", NVARCHAR(100)), Column("withdrawn_from_study_column_name", NVARCHAR(100)), Column("withdrawn_from_study_values", NVARCHAR(500)), Column("sex_column_name", NVARCHAR(100)), Column("sex_column_map", NVARCHAR(500)), Column("complete_or_expected_column_name", NVARCHAR(100)), Column("complete_or_expected_values", NVARCHAR(500)), Column("post_withdrawal_keep_samples_column_name", NVARCHAR(100)), Column("post_withdrawal_keep_samples_values", NVARCHAR(500)), Column("post_withdrawal_keep_data_column_name", NVARCHAR(100)), Column("post_withdrawal_keep_data_values", NVARCHAR(500)), Column("brc_opt_out_column_name", NVARCHAR(100)), Column("brc_opt_out_values", NVARCHAR(500)), Column("excluded_from_analysis_column_name", NVARCHAR(100)), Column("excluded_from_analysis_values", NVARCHAR(500)), Column("excluded_from_study_column_name", NVARCHAR(100)), Column("excluded_from_study_values", NVARCHAR(500)), Column("identities_map", NVARCHAR(500)), Column("last_updated_datetime", DateTime, nullable=False), Column("last_updated_by_user_id", Integer, ForeignKey(u.c.id), index=True, nullable=False), ) t.create() def downgrade(migrate_engine): meta.bind = migrate_engine t = Table("participant_import_definition", meta, autoload=True) t.drop()
import os from mindware.components.feature_engineering.transformations.base_transformer import Transformer from mindware.components.utils.class_loader import find_components, ThirdPartyComponents """ Load the buildin classifiers. """ rescaler_directory = os.path.split(__file__)[0] _rescaler = find_components(__package__, rescaler_directory, Transformer) """ Load third-party classifiers. """ _addons = ThirdPartyComponents(Transformer) def add_rescaler(rescaler): _addons.add_component(rescaler)
const Discord = require('discord.js'); const client = new Discord.Client(); const ly = require('wio.db'); const moment = require('moment'); const config = require("../config.json") exports.run = (client, message, args) => { try { let user = message.author const embed = new Discord.MessageEmbed() .setAuthor(client.user.username, client.user.displayAvatarURL()) .setColor("#0067f4") .setTitle(`Help Menu`) .setDescription(`Bot Prefix: **${config.prefix}** \nExample: **${config.prefix}dashboard** \nWebsite: [**Click**](${config.website_url})`) .addField(`Commands`, "`dashboard`, `monitors`, `account`, `new-monitor`, `invite`") message.channel.send(embed) } catch (e) { console.log(e) } } exports.conf = { enabled: true, guildOnly: false, aliases: [], permLevel: 0 }; exports.help = { name: 'help' };
""" Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'whh^^+z91kk(ib#*clq%f8*j^ffeuio&o15jbf(-wpq08g8om$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ecommerce.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR,'static/images')
TSim.Train = function(name, station) { var root_ = this var tmp = [] this.name = name this.ret = false this.currentLink = 0 this.percent = 0 this.state = 1 /* ** 0 - Arret ** 1 - Lent (1 px/s) ** 2 - Rapide (2 px/s) */ this.update = function() { if (root_.state == 0) return; if (root_.currentLink.to.reserve == root_.name || !root_.currentLink.to.reserve) root_.percent += 0.01 * root_.state; if (root_.percent >= 1) { root_.currentLink.to.reserve = false root_.reachCheckPoint(root_.currentLink.to) }else if(root_.percent >= 0.80) { root_.currentLink.to.reserve = root_.name; } } this.setStartStation = function(station) { console.log("start", station); root_.currentLink = station.link[0]; root_.state = 2; root_.currentLink.train[root_.name] = root_; } this.reachCheckPoint = function(checkPoint) { console.log(checkPoint); if (checkPoint.link.length < 1) { root_.state = 0; root_.percent = 1; return; } delete root_.currentLink.train[this.name] root_.currentLink = checkPoint.link[Math.floor((Math.random()*checkPoint.link.length - 1)+1)]; root_.currentLink.train[this.name] = this; root_.state = 1; root_.percent = 0; } this.setStartStation(station) return (this) }
'use strict'; module.exports = require('./lib'); module.exports.Node = require('./lib/node'); module.exports.Service = require('./lib/service'); module.exports.errors = require('./lib/errors'); module.exports.services = {}; module.exports.services.Bitcoin = require('./lib/services/bitcoind'); module.exports.services.Web = require('./lib/services/web'); module.exports.scaffold = {}; module.exports.scaffold.create = require('./lib/scaffold/create'); module.exports.scaffold.add = require('./lib/scaffold/add'); module.exports.scaffold.remove = require('./lib/scaffold/remove'); module.exports.scaffold.start = require('./lib/scaffold/start'); module.exports.scaffold.callMethod = require('./lib/scaffold/call-method'); module.exports.scaffold.findConfig = require('./lib/scaffold/find-config'); module.exports.scaffold.defaultConfig = require('./lib/scaffold/default-config'); module.exports.cli = {}; module.exports.cli.main = require('./lib/cli/main'); module.exports.cli.daemon = require('./lib/cli/daemon'); module.exports.cli.bitcore = require('./lib/cli/bitcore'); module.exports.cli.bitcored = require('./lib/cli/bitcored'); module.exports.lib = require('denariicore-lib');
import React from "react"; import styles from "./styles.module.scss" import PropTypes from "prop-types"; import LoginForm from "components/LoginForm"; import SignupForm from "components/SignupForm"; const Auth = (props, context) => <main className={styles.auth}> <div className={styles.column}> <img src={require("images/androidandiphone.png")} alt="Checkout our app. Is cool" /> </div> <div className={styles.column}> <div className={ `${styles.whiteBox} ${styles.formBox}`}> <img className={styles.logo} src={require("images/logo.png")} alt="Logo" /> {props.action === "login" && <LoginForm/>} {props.action === "signup" && <SignupForm/>} </div> <div className={styles.whiteBox}> {/* state 액션이 로그인일때 혹은 회원가입일때 / 즉시 실행 */} {props.action === "login" && ( <p className={styles.text} > {context.t("Don't have an account?")}{" "} <span onClick={props.changeAction} className={styles.changeLink}> {context.t("Sign up")} </span> </p>)} {props.action === "signup" && ( <p className={styles.text} > {context.t("Have an account?")}{" "} <span onClick={props.changeAction} className={styles.changeLink}> {context.t("Log in")} </span> </p> ) } </div> <div className={styles.appBox}> <span>{context.t("Get the app")}</span> <div className={styles.appstores}> <img src={require("images/ios.png")} alt="Download it on the Apple Appstore" /> <img src={require("images/android.png")} alt="Download it on the Apple Appstore" /> </div> </div> </div> </main> Auth.contextTypes = { t: PropTypes.func.isRequired }; export default Auth;
#!/usr/bin/env node /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. // const {spawn, execSync, exec} = require('child_process'); // const path = require('path'); // const rootDir = path.resolve(__dirname, '../'); console.log('1-------------', process.execPath); // console.log('1-------------', process.argv); // const reactScriptsPath = path // .resolve(__dirname, '../node_modules/.bin/react-scripts') // .replace(/ /g, '\\ '); // const child = spawn(reactScriptsPath, ['start'], { stdio: 'inherit' }); // child.stdout.on('data', (data)=>{ // console.log('data from child: ', data.toString()); // }) // const execFn = (command, extraEnv) =>{ // execSync(command, // { // stdio: 'inherit', // env: Object.assign({}, process.env, extraEnv), // } // ); // } // execFn(`${reactScriptsPath} start` // , { // NODE_ENV: 'production', // } // ); process.on('unhandledRejection', err => { console.log('unhandledRejection------------'); throw err; }); console.log('2------------------'); const spawn = require('react-dev-utils/crossSpawn'); const args = process.argv.slice(2); const scriptIndex = args.findIndex( x => x === 'build' || x === 'eject' || x === 'start' || x === 'test' ); const script = scriptIndex === -1 ? args[0] : args[scriptIndex]; const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : []; console.log(scriptIndex, args, script, nodeArgs) // console.log(require.resolve('react-scripts' + '../scripts/' + script), args.slice(scriptIndex + 1)) console.log('3-------------') switch (script) { case 'build': case 'eject': case 'start': case 'test': { const result = spawn.sync( 'node', nodeArgs .concat(require.resolve('react-scripts' + '/scripts/' + script)) .concat(args.slice(scriptIndex + 1)), { stdio: 'inherit' } ); if (result.signal) { console.log('result.sginal-----------', result.signal); if (result.signal === 'SIGKILL') { console.log( 'The build failed because the process exited too early. ' + 'This probably means the system ran out of memory or someone called ' + '`kill -9` on the process.' ); } else if (result.signal === 'SIGTERM') { console.log( 'The build failed because the process exited too early. ' + 'Someone might have called `kill` or `killall`, or the system could ' + 'be shutting down.' ); } process.exit(1); } process.exit(result.status); break; } default: console.log('Unknown script "' + script + '".'); console.log('Perhaps you need to update react-scripts?'); console.log( 'See: https://facebook.github.io/create-react-app/docs/updating-to-new-releases' ); break; }
module.exports = {"0":{"0":"W","1":null,"2":null,"3":"G","4":"O","5":null},"1":{"0":null,"1":null,"2":null,"3":"G","4":"O","5":null},"2":{"0":null,"1":"Y","2":null,"3":"G","4":"O","5":null},"3":{"0":"W","1":null,"2":null,"3":null,"4":"O","5":null},"4":{"0":null,"1":null,"2":null,"3":null,"4":"O","5":null},"5":{"0":null,"1":"Y","2":null,"3":null,"4":"O","5":null},"6":{"0":"W","1":null,"2":"B","3":null,"4":"O","5":null},"7":{"0":null,"1":null,"2":"B","3":null,"4":"O","5":null},"8":{"0":null,"1":"Y","2":"B","3":null,"4":"O","5":null},"9":{"0":"W","1":null,"2":null,"3":"G","4":null,"5":null},"10":{"0":null,"1":null,"2":null,"3":"G","4":null,"5":null},"11":{"0":null,"1":"Y","2":null,"3":"G","4":null,"5":null},"12":{"0":"W","1":null,"2":null,"3":null,"4":null,"5":null},"13":{"0":"W","1":"Y","2":"W","3":"W","4":"W","5":"W"},"14":{"0":null,"1":"Y","2":null,"3":null,"4":null,"5":null},"15":{"0":"W","1":null,"2":"B","3":null,"4":null,"5":null},"16":{"0":null,"1":null,"2":"B","3":null,"4":null,"5":null},"17":{"0":null,"1":"Y","2":"B","3":null,"4":null,"5":null},"18":{"0":"W","1":null,"2":null,"3":"G","4":null,"5":"R"},"19":{"0":null,"1":null,"2":null,"3":"G","4":null,"5":"R"},"20":{"0":null,"1":"Y","2":null,"3":"G","4":null,"5":"R"},"21":{"0":"W","1":null,"2":null,"3":null,"4":null,"5":"R"},"22":{"0":null,"1":null,"2":null,"3":null,"4":null,"5":"R"},"23":{"0":null,"1":"Y","2":null,"3":null,"4":null,"5":"R"},"24":{"0":"W","1":null,"2":"B","3":null,"4":null,"5":"R"},"25":{"0":null,"1":null,"2":"B","3":null,"4":null,"5":"R"},"26":{"0":null,"1":"Y","2":"B","3":null,"4":null,"5":"R"}};
module.exports = { parser: "@typescript-eslint/parser", env: { es6: true, node: true }, plugins: ["@typescript-eslint"], extends: ["plugin:@typescript-eslint/recommended", "standard"], globals: { Atomics: "readonly", SharedArrayBuffer: "readonly" }, parserOptions: { ecmaVersion: 2018, sourceType: "module" }, rules: { semi: ["error", "always"], indent: "off", "@typescript-eslint/indent": ["error", 2], "space-before-function-paren": ["error", "never"], quotes: [2, "double", { avoidEscape: true }], "no-use-before-define": ["error", "nofunc"] } };
/** * Copyright 2020 Adobe. All rights reserved. * This file is licensed to you 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 REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ import { withPrefix } from "gatsby" // TODO: efficiency 🥴 export const pathDir = (path) => (path.split("/").slice(0, -1).join("/")) export const pageInSameDir = (page, dir) => (page && pathDir(page.path).indexOf(dir) !== -1) export const pageTitles = (pages) => pages.map((p) => p.title) export const findSelectedPageNextPrev = (pathname, pages, type = "", defaultHomePage = "/") => { const flat = flattenPages(pages) const selectedPage = flat.find((page) => { return withPrefix(page.path) === pathname }) const previous = flat[flat.indexOf(selectedPage) - 1] let next = flat[flat.indexOf(selectedPage) + 1] if (!next) { next = { path: defaultHomePage, title: `Complete ${type}` } } return { nextPage: next, previousPage: previous, } } export const flattenPages = (pages) => { if (pages === null) { return [] } let flat = [] const find = (page) => { flat.push(page) if (page.pages) { page.pages.forEach(find) } } pages.forEach(find) flat = flat.flat() return flat.filter( (page, index) => page.path && page.path !== flat[index + 1]?.path ) }
import path from 'path'; import test from 'ava'; import del from 'del'; import pathExists from 'path-exists'; import fn from '.'; const imgUrl = 'http://i3.pixiv.net/img-original/img/2016/03/31/00/31/46/56100246_p0.jpg'; const fakeUrl = 'http://i3.pixiv.net/img-original/img/2016/03/31/00/31/46/fake.jpg'; test.after('cleanup', async t => { await del(['*.jpg', 'fixtures/*.jpg']); t.pass(); }); test('download image', async t => { t.is(await fn(imgUrl), path.basename(imgUrl)); }); test('output path', async t => { await fn(imgUrl, 'fixtures/output.jpg'); t.true(await pathExists('fixtures/output.jpg')); }); test('throw type error', async t => { try { await fn(); t.fail('Exception was not thrown'); } catch (error) { t.regex(error.message, /string/); } }); test('throw http error', async t => { try { await fn(fakeUrl); t.fail('Exception was not thrown'); } catch (error) { t.truthy(error); t.is(error.message, 'Response code 404 (Not Found)'); } });
angular.module('myAppControllers') .controller('startPageController', ['$scope', '$http', function ($scope, $http) { $scope.woot = 'This is Start Page'; }]);
/* eslint-disable max-lines-per-function */ /* eslint-disable no-undef */ const { stringify, safeStringify } = require('../index'); describe('Make an array', () => { it('Input object will be stringified', () => { const result = stringify({ test: true }); expect(result).toStrictEqual(JSON.stringify({ test: true })); }); it('Stringified object will also stay stringified object', () => { const result = stringify(JSON.stringify({ test: true })); expect(result).toStrictEqual(JSON.stringify({ test: true })); }); it('Null will return null', () => { const result = stringify(null); expect(result).toStrictEqual(null); }); it('Undefined will return undefined', () => { const result = stringify(undefined); expect(result).toStrictEqual(undefined); }); it('Input string will return as is', () => { const result = stringify('test'); expect(result).toStrictEqual('test'); }); it('Input array will return a stringified array', () => { const result = stringify([true, true]); expect(result).toStrictEqual(JSON.stringify([true, true])); }); it('Input object will be stringified on safeStringify', () => { const result = safeStringify({ test: true }); expect(result).toStrictEqual(JSON.stringify({ test: true })); }); it('Default value will be returned when fails to stringify', () => { const foo = { }; foo.bar = foo; const result = safeStringify(foo, 'default'); expect(result).toStrictEqual('default'); }); });
# This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # spec/fixtures/responses/whois.srs.net.nz/status_invalid # # and regenerate the tests with the following script # # $ scripts/generate_tests.py # from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisSrsNetNzStatusInvalid(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.srs.net.nz/status_invalid.txt" host = "whois.srs.net.nz" part = yawhois.record.Part(open(fixture_path, "r").read(), host) self.record = yawhois.record.Record(None, [part]) def test_status(self): eq_(self.record.status, 'invalid') def test_available(self): eq_(self.record.available, False) def test_nameservers(self): eq_(self.record.nameservers.__class__.__name__, 'list') eq_(self.record.nameservers, []) def test_registered(self): eq_(self.record.registered, False) def test_response_throttled(self): eq_(self.record.response_throttled, False) def test_invalid(self): eq_(self.record.invalid, True) def test_created_on(self): eq_(self.record.created_on, None) def test_valid(self): eq_(self.record.valid, False) def test_updated_on(self): eq_(self.record.updated_on, None) def test_expires_on(self): eq_(self.record.expires_on, None)
import pytest import re from proknow import Exceptions def test_create(app, workspace_generator): pk = app.pk # Verify returned WorkspaceItem params, created = workspace_generator() assert created.slug == params["slug"] assert created.name == params["name"] assert created.protected == params["protected"] # Assert item can be found in query workspaces = pk.workspaces.query() for workspace in workspaces: if workspace.slug == params["slug"]: workspace_match = workspace break else: workspace_match = None assert workspace_match is not None assert workspace_match.slug == params["slug"] assert workspace_match.name == params["name"] assert workspace_match.protected == params["protected"] def test_create_failure(app, workspace_generator): pk = app.pk params, _ = workspace_generator() # Assert error is raised for duplicate workspace with pytest.raises(Exceptions.HttpError) as err_wrapper: pk.workspaces.create(**params) assert err_wrapper.value.status_code == 409 assert err_wrapper.value.body == 'Workspace already exists with slug "' + params["slug"] + '"' def test_delete(app, workspace_generator): pk = app.pk params, workspace = workspace_generator(do_not_mark=True) # Verify workspace was deleted successfully workspace.delete() for workspace in pk.workspaces.query(): if workspace.slug == params["slug"]: match = workspace break else: match = None assert match is None def test_delete_failure(app, workspace_generator): pk = app.pk _, workspace = workspace_generator(do_not_mark=True) workspace.delete() # Assert error is raised when attempting to delete protected workspace with pytest.raises(Exceptions.HttpError) as err_wrapper: workspace.delete() assert err_wrapper.value.status_code == 404 assert err_wrapper.value.body == ('Workspace "' + workspace.id + '" not found') def test_find(app, workspace_generator): pk = app.pk params, _ = workspace_generator(slug="findme", name="Find Me") expr = re.compile(r"indm") # Find with no args found = pk.workspaces.find() assert found is None # Find using predicate found = pk.workspaces.find(lambda ws: expr.search(ws.data["slug"]) is not None) assert found is not None assert found.slug == params["slug"] assert found.name == params["name"] assert found.protected == params["protected"] # Find using props found = pk.workspaces.find(slug=params["slug"], name=params["name"]) assert found is not None assert found.slug == params["slug"] assert found.name == params["name"] assert found.protected == params["protected"] # Find using both found = pk.workspaces.find(lambda ws: expr.search(ws.data["slug"]) is not None, slug=params["slug"], name=params["name"]) assert found is not None assert found.slug == params["slug"] assert found.name == params["name"] assert found.protected == params["protected"] # Find failure found = pk.workspaces.find(lambda ws: expr.search(ws.data["name"]) is not None) assert found is None found = pk.workspaces.find(slug="findme", name="Find me") assert found is None def test_query(app, workspace_generator): pk = app.pk params1, _ = workspace_generator() params2, _ = workspace_generator() # Verify test 1 for workspace in pk.workspaces.query(): if workspace.slug == params1["slug"]: match = workspace break else: match = None assert match is not None assert match.slug == params1["slug"] assert match.name == params1["name"] assert match.protected == params1["protected"] # Verify test 2 for workspace in pk.workspaces.query(): if workspace.slug == params2["slug"]: match = workspace break else: match = None assert match is not None assert match.slug == params2["slug"] assert match.name == params2["name"] assert match.protected == params2["protected"] def test_resolve(app, workspace_generator): pk = app.pk params, workspace = workspace_generator() # Test resolve by id resolved = pk.workspaces.resolve(workspace.id) assert resolved is not None assert resolved.slug == params["slug"] assert resolved.name == params["name"] assert resolved.protected == params["protected"] # Test resolve by name resolved = pk.workspaces.resolve(params["name"]) assert resolved is not None assert resolved.slug == params["slug"] assert resolved.name == params["name"] assert resolved.protected == params["protected"] def test_resolve_failure(app): pk = app.pk # Test resolve by id with pytest.raises(Exceptions.WorkspaceLookupError) as err_wrapper: pk.workspaces.resolve("00000000000000000000000000000000") assert err_wrapper.value.message == "Workspace with id `00000000000000000000000000000000` not found." # Test resolve by name with pytest.raises(Exceptions.WorkspaceLookupError) as err_wrapper: pk.workspaces.resolve("My Workspace") assert err_wrapper.value.message == "Workspace with name `My Workspace` not found." def test_resolve_by_id(app, workspace_generator): pk = app.pk params, workspace = workspace_generator() resolved = pk.workspaces.resolve_by_id(workspace.id) assert resolved is not None assert resolved.slug == params["slug"] assert resolved.name == params["name"] assert resolved.protected == params["protected"] def test_resolve_by_id_failure(app): pk = app.pk with pytest.raises(Exceptions.WorkspaceLookupError) as err_wrapper: pk.workspaces.resolve_by_id("00000000000000000000000000000000") assert err_wrapper.value.message == "Workspace with id `00000000000000000000000000000000` not found." def test_resolve_by_name(app, workspace_generator): pk = app.pk params, workspace = workspace_generator(name="workspace-lower1") resolved = pk.workspaces.resolve_by_name(params["name"]) assert resolved is not None assert resolved.slug == params["slug"] assert resolved.name == params["name"] assert resolved.protected == params["protected"] resolved = pk.workspaces.resolve_by_name(params["name"].upper()) assert resolved is not None assert resolved.slug == params["slug"] assert resolved.name == params["name"] assert resolved.protected == params["protected"] def test_resolve_by_name_failure(app): pk = app.pk with pytest.raises(Exceptions.WorkspaceLookupError) as err_wrapper: pk.workspaces.resolve("My Workspace") assert err_wrapper.value.message == "Workspace with name `My Workspace` not found." def test_update(app, workspace_generator): pk = app.pk resource_prefix = app.resource_prefix params, workspace = workspace_generator() # Verify workspace was updated successfully workspace.slug = resource_prefix + "updated" workspace.name = "Updated Workspace Name" workspace.protected = True workspace.save() workspaces = pk.workspaces.query() for workspace in workspaces: if workspace.slug == resource_prefix + "updated": workspace_match = workspace break else: workspace_match = None assert workspace_match is not None assert workspace_match.slug == resource_prefix + "updated" assert workspace_match.name == "Updated Workspace Name" assert workspace_match.protected == True def test_update_failure(app, workspace_generator): pk = app.pk params, _ = workspace_generator() _, workspace = workspace_generator() # Assert error is raised for duplicate workspace with pytest.raises(Exceptions.HttpError) as err_wrapper: workspace.slug = params["slug"] workspace.save() assert err_wrapper.value.status_code == 409 assert err_wrapper.value.body == 'Workspace already exists with slug "' + params["slug"] + '"' def test_update_entities(app, workspace_generator): pk = app.pk _, workspace = workspace_generator() patient = pk.patients.create(workspace.id, "1000", "Last^First", "2018-01-01", "M") patient.upload([ "./data/Jensen^Myrtle/HNC0522c0013_CT1_image00000.dcm", "./data/Becker^Matthew/HNC0522c0009_CT1_image00000.dcm", ]) patient.refresh() image_sets = [entity.get() for entity in patient.find_entities(type="image_set")] assert len(image_sets) == 2 assert image_sets[0].data["frame_of_reference"] != image_sets[1].data["frame_of_reference"] workspace.update_entities({ "frame_of_reference": image_sets[0].data["frame_of_reference"] }, [image_sets[0], image_sets[1].id]) for image_set in image_sets: image_set.refresh() assert image_sets[0].data["frame_of_reference"] == image_sets[1].data["frame_of_reference"] def test_update_entities_failure(app, workspace_generator): pk = app.pk _, workspace = workspace_generator() patient = pk.patients.create(workspace.id, "1000", "Last^First", "2018-01-01", "M") # Assert error is raised for invalid entity ids with pytest.raises(Exceptions.HttpError) as err_wrapper: workspace.update_entities({ "frame_of_reference": "1.3.6.1.4.1.22213.2.26558.1" }, ["00000000000000000000000000000000"]) assert err_wrapper.value.status_code == 404 assert err_wrapper.value.body == 'One or more entities not found'
import sys import pandas as pd import numpy as np import re import chardet from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): ''' Function that takes two CSV files from the given paths, creates two dataframes, merges the two dataframes on their common ID and returns the joint dataframe Arguments: messages_filepath - pathname categories_filepath - pathname Returns: df - dataframe object ''' # load messages dataset messages = pd.read_csv(messages_filepath, sep=',', encoding='utf-8', dtype='str') # load categories dataset categories = pd.read_csv(categories_filepath, sep=',', dtype=str) # merge datasets df = messages.merge(categories, left_on='id', right_on='id').sort_values(by='id') return df def clean_data(df): ''' Function that transforms the catagorical data into a new dataframe of binary values (0,1) for the n categries, then drops the 'categories' column from the original dataframe and concats the 2 dataframes to a new one showing the categorical value for each message in binary values Arguments: df - dataframe object Returns: df - cleaned dataframe object ''' # create a dataframe of the 36 individual category columns categories = df['categories'].str.split(pat=';', expand=True) # select the first row of the categories dataframe row = categories.iloc[0,] # use this row to extract a list of new column names for categories. # one way is to apply a lambda function that takes everything # up to the second to last character of each string with slicing row = row.apply(lambda x: x[:len(x)-2]) category_colnames = list(row) # rename the columns of `categories` categories.columns = category_colnames for column in categories: # set each value to be the last character of the string categories[column] = categories[column].apply(lambda x: x[len(x)-1]) # only once # convert column from string to numeric categories[column] = pd.to_numeric(categories[column]) # drop the original categories column from `df` df.drop(['categories'], inplace=True, axis=1) # drop the original column from `df` df.drop(['original'], inplace=True, axis=1) # concatenate the original dataframe with the new `categories` dataframe df = pd.concat([df, categories], axis=1) df.related.replace(2, 1, inplace=True) # remove dublicates df.drop_duplicates(inplace=True) return df def save_data(df, database_filename): ''' Save the clean dataset into an sqlite database ''' engine = create_engine('sqlite:///{}'.format(database_filename)) df.to_sql('Disaster_messages_categories', engine, index=False, if_exists='replace') def main(): if len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df = load_data(messages_filepath, categories_filepath) print('Cleaning data...') df = clean_data(df) print('Saving data...\n DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned data saved to database!') else: print('Please provide the filepaths of the messages and categories '\ 'datasets as the first and second argument respectively, as '\ 'well as the filepath of the database to save the cleaned data '\ 'to as the third argument. \n\nExample: python process_data.py '\ 'disaster_messages.csv disaster_categories.csv '\ 'DisasterResponse.db') if __name__ == '__main__': main()
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * @summary This sample demonstrates querying methods related to metric. */ // Load the .env file if it exists const dotenv = require("dotenv"); dotenv.config(); const { MetricsAdvisorKeyCredential, MetricsAdvisorClient } = require("@azure/ai-metrics-advisor"); async function main() { // You will need to set these environment variables or edit the following values const endpoint = process.env["METRICS_ADVISOR_ENDPOINT"] || "<service endpoint>"; const subscriptionKey = process.env["METRICS_ADVISOR_SUBSCRIPTION_KEY"] || "<subscription key>"; const apiKey = process.env["METRICS_ADVISOR_API_KEY"] || "<api key>"; const metricId = process.env["METRICS_ADVISOR_METRIC_ID"] || "<metric id>"; const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey); const client = new MetricsAdvisorClient(endpoint, credential); await listMetricSeriesDefinitions(client, metricId); await listMetricDimensionValues(client, metricId); await listEnrichmentStatus(client, metricId); } async function listMetricSeriesDefinitions(client, metricId) { console.log("Listing metric series definitions..."); console.log(" with for-await-of loop"); const listIterator = client.listMetricSeriesDefinitions(metricId, new Date("08/05/2020")); for await (const definition of listIterator) { console.log(definition); } console.log(" first two pages using byPage()"); const iterator = client .listMetricSeriesDefinitions(metricId, new Date("08/05/2020")) .byPage({ maxPageSize: 2 }); let result = await iterator.next(); if (!result.done) { console.log(" -- Page --"); for (const definition of result.value) { console.log(definition); } result = await iterator.next(); if (!result.done) { console.log(" -- Page --"); for (const definition of result.value) { console.log(definition); } } } } async function listEnrichmentStatus(client, metricId) { console.log("Listing metric enrichment status..."); const listIterator = client.listMetricEnrichmentStatus( metricId, new Date("10/22/2020"), new Date("10/24/2020") ); for await (const status of listIterator) { console.log(" Enrichment status"); console.log(status.timestamp); console.log(status.status); console.log(status.message); } } async function listMetricDimensionValues(client, metricId) { console.log("Listing metric dimension values..."); const listIterator = client.listMetricDimensionValues(metricId, "city"); for await (const dv of listIterator) { console.log(` ${dv}`); } } main() .then((_) => { console.log("Succeeded"); }) .catch((err) => { console.log("Error occurred:"); console.log(err); });
import ruamel.yaml import pprint # Tokens mnemonic: # directive: % # document_start: --- # document_end: ... # alias: * # anchor: & # tag: ! # scalar _ # block_sequence_start: [[ # block_mapping_start: {{ # block_end: ]} # flow_sequence_start: [ # flow_sequence_end: ] # flow_mapping_start: { # flow_mapping_end: } # entry: , # key: ? # value: : _replaces = { ruamel.yaml.DirectiveToken: '%', ruamel.yaml.DocumentStartToken: '---', ruamel.yaml.DocumentEndToken: '...', ruamel.yaml.AliasToken: '*', ruamel.yaml.AnchorToken: '&', ruamel.yaml.TagToken: '!', ruamel.yaml.ScalarToken: '_', ruamel.yaml.BlockSequenceStartToken: '[[', ruamel.yaml.BlockMappingStartToken: '{{', ruamel.yaml.BlockEndToken: ']}', ruamel.yaml.FlowSequenceStartToken: '[', ruamel.yaml.FlowSequenceEndToken: ']', ruamel.yaml.FlowMappingStartToken: '{', ruamel.yaml.FlowMappingEndToken: '}', ruamel.yaml.BlockEntryToken: ',', ruamel.yaml.FlowEntryToken: ',', ruamel.yaml.KeyToken: '?', ruamel.yaml.ValueToken: ':', } def test_tokens(data_filename, tokens_filename, verbose=False): tokens1 = [] with open(tokens_filename, 'r') as fp: tokens2 = fp.read().split() try: yaml = ruamel.yaml.YAML(typ='unsafe', pure=True) with open(data_filename, 'rb') as fp1: for token in yaml.scan(fp1): if not isinstance(token, (ruamel.yaml.StreamStartToken, ruamel.yaml.StreamEndToken)): tokens1.append(_replaces[token.__class__]) finally: if verbose: print('TOKENS1:', ' '.join(tokens1)) print('TOKENS2:', ' '.join(tokens2)) assert len(tokens1) == len(tokens2), (tokens1, tokens2) for token1, token2 in zip(tokens1, tokens2): assert token1 == token2, (token1, token2) test_tokens.unittest = ['.data', '.tokens'] def test_scanner(data_filename, canonical_filename, verbose=False): for filename in [data_filename, canonical_filename]: tokens = [] try: yaml = ruamel.yaml.YAML(typ='unsafe', pure=False) with open(filename, 'rb') as fp: for token in yaml.scan(fp): tokens.append(token.__class__.__name__) finally: if verbose: pprint.pprint(tokens) test_scanner.unittest = ['.data', '.canonical'] if __name__ == '__main__': import test_appliance test_appliance.run(globals())
""" Code modified from PyTorch DCGAN examples: https://github.com/pytorch/examples/tree/master/dcgan Example Usage: # For MNIST zeros and ones # Improved GAN CUDA_VISIBLE_DEVICES=1 python main.py --outf=/scratch0/ilya/locDoc/ACGAN/experiments/julytest13 --train_batch_size=32 --cuda --dataset mnist_subset --num_classes 2 --imageSize=32 --data_root=/scratch0/ilya/locDoc/data/mnist --eval_period 50 --nc 1 --ndf 32 --ngf 32 --GAN_lrD 0.0001 --g_loss feature_matching # Mary GAN CUDA_VISIBLE_DEVICES=1 python main.py --outf=/scratch0/ilya/locDoc/ACGAN/experiments/julytest13 --train_batch_size=32 --cuda --dataset mnist_subset --num_classes 2 --imageSize=32 --data_root=/scratch0/ilya/locDoc/data/mnist --eval_period 50 --nc 1 --ndf 32 --ngf 32 --GAN_lrD 0.0001 # activation maximization gan CUDA_VISIBLE_DEVICES=1 python main.py --outf=/scratch0/ilya/locDoc/ACGAN/experiments/julytest7 --train_batch_size=32 --cuda --dataset=mnist_subset --imageSize=32 --data_root=/scratch0/ilya/locDoc/data/mnist --eval_period 50 --nc 1 --num_classes 2 --ndf 32 --ngf 32 --GAN_lrD 0.0001 --g_loss activation_maximization # complement GAN CUDA_VISIBLE_DEVICES=1 python main.py --outf=/scratch0/ilya/locDoc/ACGAN/experiments/julytest9 --train_batch_size=32 --cuda --dataset=mnist_subset --imageSize=32 --data_root=/scratch0/ilya/locDoc/data/mnist --eval_period 50 --nc 1 --num_classes 2 --ndf 32 --ngf 32 --GAN_lrD 0.0001 --g_loss crammer_singer_complement --g_loss_aux confuse --g_loss_aux_weight 0.33 --confuse_margin 1.0 # Full MNIST CUDA_VISIBLE_DEVICES=1 python main.py --outf=/scratch0/ilya/locDoc/ACGAN/experiments/julytest10 --train_batch_size=32 --cuda --dataset=mnist --imageSize=32 --data_root=/scratch0/ilya/locDoc/data/mnist --eval_period 50 --nc 1 --num_classes 10 --ndf 32 --ngf 32 --GAN_lrD 0.0001 --g_loss crammer_singer_complement --g_loss_aux confuse --g_loss_aux_weight 0.33 --confuse_margin 1.0 """ from __future__ import print_function import argparse import glob import os import numpy as np import random import re from tqdm import tqdm import time import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import torchvision.utils as vutils from torch.autograd import Variable import data from utils import weights_init, compute_acc, decimate, RunningAcc, MovingAverage from network import _netG, _netD, _netD_CIFAR10_SNGAN, _netG_CIFAR10_SNGAN from folder import ImageFolder from GAN_training.models import DCGAN, DCGAN_spectralnorm, resnet, resnet_extra, resnet_48_flat, resnet_48, resnet_128, wideresnet import visdom import imageio import pdb parser = argparse.ArgumentParser() parser.add_argument('--dataset', required=True, help='cifar | cifar100') parser.add_argument('--data_root', required=True, help='path to dataset') parser.add_argument('--workers', type=int, help='number of data loading workers', default=2) parser.add_argument('--train_batch_size', type=int, default=1, help='input batch size') parser.add_argument('--imageSize', type=int, default=32, help='the height / width of the input image to network') parser.add_argument('--nc', type=int, default=3) parser.add_argument('--nz', type=int, default=110, help='size of the latent z vector') parser.add_argument('--ngf', type=int, default=128) parser.add_argument('--ndf', type=int, default=128) # parser.add_argument('--lr', type=float, default=0.0002, help='learning rate, ACGAN default=0.0002') parser.add_argument('--beta1', type=float, default=0.0, help='beta1 for adam. ACGAN default=0.5') parser.add_argument('--beta2', type=float, default=0.999, help='beta2 for adam. ACGAN default=0.999') parser.add_argument('--ndis', type=int, default=1, help='Num discriminator steps. ACGAN default=1') parser.add_argument('--cuda', action='store_true', help='enables cuda') parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use') parser.add_argument('--netG', default='', help="path to netG (to continue training)") parser.add_argument('--netD', default='', help="path to netD (to continue training)") parser.add_argument('--outf', default='.', help='folder to output images and model checkpoints') parser.add_argument('--random_seed', type=int, help='manual seed') parser.add_argument('--num_classes', type=int, default=10, help='Number of classes in dataset.') parser.add_argument('--net_type', default='flat', help='Only relevant for image size 48') parser.add_argument('--host', default='http://ramawks69', type=str, help="hostname/server visdom listener is on.") parser.add_argument('--port', default=8097, type=int, help="which port visdom should use.") parser.add_argument('--visdom_board', default='main', type=str, help="name of visdom board to use.") parser.add_argument('--eval_period', type=int, default=1000) parser.add_argument('--gantype', default='main', type=str, help="modegan | acgan | mhgan") parser.add_argument('--scoring_period', type=int, default=1e9) parser.add_argument('--run_scoring_now', type=bool, default=False) parser.add_argument('--projection_discriminator', action='store_true', help="Set to true to use Miyator Koyama ICLR 2018 projection discriminator") parser.add_argument('--conditional_bn', action='store_true', help="Set to true to use conditional batch norm in generator") parser.add_argument('--noise_class_concat', action='store_true', help="Set to true to have class labels writen to the noise") parser.add_argument('--plot_sorted_outputs', action='store_true', help="Display sorted fakes/real images in visdom") # for data loader parser.add_argument('--size_labeled_data', type=int, default=4000) parser.add_argument('--dev_batch_size', type=int, default=None) parser.add_argument('--train_batch_size_2', type=int, default=None) # for GAN_training folder parser.add_argument('--GAN_lrG', type=float, default=0.0001, help='learning rate, default=0.0002') parser.add_argument('--GAN_lrD', type=float, default=0.0004, help='learning rate, default=0.0002') parser.add_argument('--GAN_disc_loss_type', default='hinge', help='which disc loss to use| hinge, wasserstein, ns') parser.add_argument('--aux_scale_G', type=float, default=0.1, help='WGAN default=0.1') parser.add_argument('--aux_scale_D', type=float, default=1.0, help='WGAN default=1.0') parser.add_argument('--max_itr', type=int, default=1e10) parser.add_argument('--save_period', type=int, default=10000) parser.add_argument("--d_loss", help="nll | activation_maximization | activation_minimization", default="nll") parser.add_argument("--g_loss", help="see d_loss", default="positive_log_likelihood") parser.add_argument("--g_loss_aux", help="see d_loss", default=None) parser.add_argument('--g_loss_aux_weight', default=0.0, type=float) parser.add_argument('--confuse_margin', default=1.0, type=float) parser.add_argument("--d_network", help="resnet | wideresnet", default="resnet") opt = parser.parse_args() print(opt) # for GAN_training folder opt.GAN_nz = opt.nz opt.GAN_ngf = opt.ngf opt.GAN_ndf = opt.ndf opt.GAN_disc_iters = opt.ndis opt.GAN_beta1 = opt.beta1 opt.batchSize = opt.train_batch_size # setup visdom vis = visdom.Visdom(env=opt.visdom_board, port=opt.port, server=opt.host) visdom_visuals_ids = [] if opt.imageSize == 32: empty_img = np.moveaxis(imageio.imread('404_32.png')[:,:,:opt.nc],-1,0) / 255.0 elif opt.imageSize == 64: empty_img = np.moveaxis(imageio.imread('404_64.png')[:,:,:3],-1,0) / 255.0 elif opt.imageSize == 48: empty_img = np.moveaxis(imageio.imread('404_48.png')[:,:,:3],-1,0) / 255.0 elif opt.imageSize == 128: empty_img = np.moveaxis(imageio.imread('404_128.png')[:,:,:3],-1,0) / 255.0 def winid(): """ Pops first item on visdom_visuals_ids or returns none if it is empty """ visid = None # acceptable id to make a new plot if visdom_visuals_ids: visid = visdom_visuals_ids.pop(0) return visid try: os.makedirs(opt.outf) except OSError: pass if opt.random_seed is None: opt.random_seed = random.randint(1, 10000) print("Random Seed: ", opt.random_seed) random.seed(opt.random_seed) torch.manual_seed(opt.random_seed) if opt.cuda: torch.cuda.manual_seed_all(opt.random_seed) cudnn.benchmark = True if torch.cuda.is_available() and not opt.cuda: print("WARNING: You have a CUDA device, so you should probably run with --cuda") device = torch.device("cuda:0" if opt.cuda else "cpu") # some hyper parameters ngpu = int(opt.ngpu) nz = int(opt.nz) ngf = int(opt.ngf) ndf = int(opt.ndf) opt.num_classes = int(opt.num_classes) num_classes = int(opt.num_classes) # if (opt.gantype == 'marygan') or (opt.gantype == 'mhgan'): # opt.num_classes = opt.num_classes - 1 nc = opt.nc if not opt.dev_batch_size: opt.dev_batch_size = opt.train_batch_size if not opt.train_batch_size_2: opt.train_batch_size_2 = opt.train_batch_size # dataset if opt.dataset == 'cifar': metaloader = data.get_cifar_loaders elif opt.dataset == 'mnist_subset': metaloader = data.get_mnist_subset_loaders elif opt.dataset == 'mnist': metaloader = data.get_mnist_loaders elif opt.dataset == 'cifar100': metaloader = data.get_cifar100_loaders elif opt.dataset == 'cifar20': metaloader = data.get_cifar20_loaders elif opt.dataset == 'stl': metaloader = data.get_stl_loaders elif opt.dataset == 'celeba': metaloader = data.get_celeba_loaders elif opt.dataset == 'flower': metaloader = data.get_flower102_loaders elif opt.dataset == 'imagenet': metaloader = data.get_imagenet_loaders else: raise NotImplementedError("No such dataset {}".format(opt.dataset)) labeled_loader, unlabeled_loader, unlabeled_loader2, dev_loader, special_set = metaloader(opt) # check outf for files netGfiles = glob.glob(os.path.join(opt.outf, 'netG_iter_*.pth')) netGfiles.sort(key = lambda s: int(s.split('_')[-1].split('.')[0])) if opt.netG == '' and netGfiles: opt.netG = netGfiles[-1] netDfiles = glob.glob(os.path.join(opt.outf, 'netD_iter_*.pth')) netDfiles.sort(key = lambda s: int(s.split('_')[-1].split('.')[0])) if opt.netD == '' and netDfiles: opt.netD = netDfiles[-1] # Define the generator and initialize the weights if opt.imageSize == 32: netG = resnet.Generator(opt) # elif opt.imageSize == 64: # if opt.projection_discriminator: # netG = resnet_128.Generator64SpecNorm(num_classes=opt.num_classes) # else: # NotImplementedError() # elif opt.imageSize == 48: # netG = resnet_48.Generator(opt) # elif opt.imageSize == 128: # if opt.projection_discriminator: # netG = resnet_128.GeneratorSpecNorm(num_classes=opt.num_classes) # else: # NotImplementedError() else: raise NotImplementedError('A network for imageSize %i is not implemented!' % opt.imageSize) # netG.apply(weights_init) # TODO: explain why this is commented out if opt.netG != '': print('Loading %s...' % opt.netG) netG.load_state_dict(torch.load(opt.netG)) curr_iter = int(re.findall('\d+', opt.netG)[-1]) else: curr_iter = 0 print(netG) # Define the discriminator and initialize the weights if opt.d_network == 'resnet': netD = resnet.Classifier(opt) elif opt.d_network == 'wideresnet': netD = wideresnet.WideResNet(num_classes=opt.num_classes+1) # if (opt.gantype == 'marygan'): # netD = resnet.Classifier(opt) # elif opt.gantype == 'acgan': # netD = resnet.Discriminator(opt) # elif opt.gantype == 'mhgan': # netD = resnet.ClassifierMultiHinge(opt) # elif opt.gantype == 'projection': # netD = resnet.ProjectionDiscriminator(opt) # elif opt.imageSize == 64: # if opt.gantype == 'mhgan' and opt.projection_discriminator: # netD = resnet_128.ClassifierMultiHinge64(num_classes=opt.num_classes) # elif opt.projection_discriminator: # netD = resnet_128.Discriminator64(num_classes=opt.num_classes) # else: # NotImplementedError() # elif opt.imageSize == 48: # if opt.gantype == 'mhgan': # netD = resnet_48.ClassifierMultiHinge(opt) # else: # NotImplementedError() # elif opt.imageSize == 128: # if opt.gantype == 'mhgan' and opt.projection_discriminator: # netD = resnet_128.ClassifierMultiHinge(num_classes=opt.num_classes) # elif opt.projection_discriminator: # netD = resnet_128.Discriminator(num_classes=opt.num_classes) # else: # NotImplementedError() else: raise NotImplementedError('A network for imageSize %i is not implemented!' % opt.imageSize) # netD.apply(weights_init) if opt.netD != '': print('Loading %s...' % opt.netD) netD.load_state_dict(torch.load(opt.netD)) print(netD) # loss functions # nll = nn.NLLLoss() # def dis_criterion_old(inputs, labels): # # hinge loss # # from Yogesh, probably from: https://github.com/wronnyhuang/gan_loss/blob/master/trainer.py # return torch.mean(F.relu(1 + inputs*labels)) + torch.mean(F.relu(1 - inputs*(1-labels))) # def dis_criterion(inputs, labels): # # hinge loss, flipped from Yogesh # # from cGAN projection: https://github.com/crcrpar/pytorch.sngan_projection/blob/master/losses.py # return torch.mean(F.relu(1 - inputs)*labels) + torch.mean(F.relu(1 + inputs)*(1-labels)) # # dis_criterion = nn.BCELoss() # acgan_aux_criterion = nll # def marygan_criterion(inputs, labels): # return nll(torch.log(inputs),labels) # def crammer_singer_criterion(X, Ylabel): # mask = torch.ones_like(X) # mask.scatter_(1, Ylabel.unsqueeze(-1), 0) # wrongs = torch.masked_select(X,mask.byte()).reshape(X.shape[0],opt.num_classes-1) # max_wrong, _ = wrongs.max(1) # max_wrong = max_wrong.unsqueeze(-1) # target = X.gather(1,Ylabel.unsqueeze(-1)) # return torch.mean(F.relu(1 + max_wrong - target)) # def crammer_singer_complement_criterion(X, Ylabel): # mask = torch.ones_like(X) # mask.scatter_(1, Ylabel.unsqueeze(-1), 0) # wrongs = torch.masked_select(X,mask.byte()).reshape(X.shape[0],opt.num_classes-1) # max_wrong, _ = wrongs.max(1) # max_wrong = max_wrong.unsqueeze(-1) # target = X.gather(1,Ylabel.unsqueeze(-1)) # return torch.mean(F.relu(1 - max_wrong + target)) # def hinge_antifake(X, Ylabel): # target = X.gather(1,Ylabel.unsqueeze(-1)) # label_for_fake = (opt.num_classes - 1) * np.ones(Ylabel.shape[0]) # Ylabel.data.copy_(torch.from_numpy(label_for_fake)) # pred_for_fake = X.gather(1,Ylabel.unsqueeze(-1)) # return torch.mean(F.relu(1 + pred_for_fake - target)) losses_on_logits = ['crammer_singer', 'crammer_singer_complement', 'confuse'] losses_on_features = ['feature_matching', 'feature_matching_l1'] nll = nn.NLLLoss() # cross entropy but assumes log was already taken K = opt.num_classes def myloss(X=None, Ylabel=None, Xfeat=None, Yfeat=None, loss_type='nll'): """For trying multiple losses. Args: X: preds, could be probabilities or logits Ylabel: scalar labels Y1hot: target_1hot, target_lab wgan should take raw ouput of network, no softmax """ # NLL case takes indices if loss_type == 'nll_builtin': return nll(torch.log(X), Ylabel) elif loss_type == 'nll': target = X.gather(1,Ylabel.unsqueeze(-1)) return torch.mean(-torch.log(target)) elif loss_type == 'feature_matching': return torch.mean((torch.mean(Xfeat, dim=0) - torch.mean(Yfeat, dim=0))**2) elif loss_type == 'feature_matching_l1': return torch.mean(torch.abs(torch.mean(Xfeat, dim=0) - torch.mean(Yfeat, dim=0))) elif loss_type == 'positive_log_likelihood': # go away from Ylabel target = X.gather(1,Ylabel.unsqueeze(-1)) return torch.mean(torch.log(target)) elif loss_type == 'activation_maximization': # Ylabel acts as 'target' to avoid mask = torch.ones_like(X) mask.scatter_(1, Ylabel.unsqueeze(-1), 0) wrongs = torch.masked_select(X,mask.byte()).reshape(X.shape[0],K) max_wrong, _ = wrongs.max(1) return torch.mean(-torch.log(max_wrong)) elif loss_type == 'activation_minimization': # Ylabel acts as 'target' to avoid mask = torch.ones_like(X) mask.scatter_(1, Ylabel.unsqueeze(-1), 0) wrongs = torch.masked_select(X,mask.byte()).reshape(X.shape[0],K) min_wrong, _ = wrongs.min(1) return torch.mean(-torch.log(min_wrong)) elif loss_type == 'confuse': confuse_margin = opt.confuse_margin # 0.1 # 0.01 mask = torch.ones_like(X) mask.scatter_(1, Ylabel.unsqueeze(-1), 0) wrongs = torch.masked_select(X,mask.byte()).reshape(X.shape[0],K) max_wrong, max_Ylabel = wrongs.max(1) mask.scatter_(1, max_Ylabel.unsqueeze(-1), 0) wrongs2 = torch.masked_select(X,mask.byte()).reshape(X.shape[0],K-1) runnerup_wrong, _ = wrongs2.max(1) # make a step towards the margin if it is outside of confuse_margin return torch.mean(F.relu(-confuse_margin + max_wrong - runnerup_wrong)) # elif loss_type == 'wasserstein': # inputs = X.gather(1,Ylabel.unsqueeze(-1)) # labels = Y1hot.gather(1,Ylabel.unsqueeze(-1)) # return torch.mean(inputs*labels) - torch.mean(inputs*(1-labels)) # elif loss_type == 'hinge': # inputs = X.gather(1,Ylabel.unsqueeze(-1)) # labels = Y1hot.gather(1,Ylabel.unsqueeze(-1)) # return torch.mean(F.relu(1 + inputs*labels)) + torch.mean(F.relu(1 - inputs*(1-labels))) elif loss_type == 'crammer_singer': mask = torch.ones_like(X) mask.scatter_(1, Ylabel.unsqueeze(-1), 0) wrongs = torch.masked_select(X,mask.byte()).reshape(X.shape[0],K) max_wrong, _ = wrongs.max(1) max_wrong = max_wrong.unsqueeze(-1) target = X.gather(1,Ylabel.unsqueeze(-1)) return torch.mean(F.relu(1 + max_wrong - target)) elif loss_type == 'crammer_singer_complement': mask = torch.ones_like(X) mask.scatter_(1, Ylabel.unsqueeze(-1), 0) wrongs = torch.masked_select(X,mask.byte()).reshape(X.shape[0],K) max_wrong, _ = wrongs.max(1) max_wrong = max_wrong.unsqueeze(-1) target = X.gather(1,Ylabel.unsqueeze(-1)) return torch.mean(F.relu(1 - max_wrong + target)) else: raise NotImplementedError('Loss type: %s' % loss_type) # if (opt.gantype == 'marygan'): # aux_criterion = marygan_criterion # elif opt.gantype == 'acgan': # aux_criterion = acgan_aux_criterion # elif opt.gantype == 'mhgan': # aux_criterion = crammer_singer_criterion # tensor placeholders input = torch.FloatTensor(opt.train_batch_size, 3, opt.imageSize, opt.imageSize) noise = torch.FloatTensor(opt.train_batch_size, nz) eval_noise = torch.FloatTensor(opt.train_batch_size, nz).normal_(0, 1) dis_label = torch.FloatTensor(opt.train_batch_size) aux_label = torch.LongTensor(opt.train_batch_size) # use in criterion conditioning_label = torch.LongTensor(opt.train_batch_size) # use as network input eval_conditioning_label = torch.LongTensor(opt.train_batch_size) real_label = 1 fake_label = 0 # if using cuda if opt.cuda: netG = netG.to(device) netD = netD.to(device) # dis_criterion.cuda() # aux_criterion.cuda() input, dis_label, aux_label = input.cuda(), dis_label.cuda(), aux_label.cuda() noise, eval_noise = noise.cuda(), eval_noise.cuda() conditioning_label = conditioning_label.cuda() eval_conditioning_label = eval_conditioning_label.cuda() # define variables input = Variable(input) noise = Variable(noise) eval_noise = Variable(eval_noise) dis_label = Variable(dis_label) aux_label = Variable(aux_label) conditioning_label = Variable(conditioning_label) eval_conditioning_label = Variable(eval_conditioning_label) # noise for evaluation eval_noise_ = np.random.normal(0, 1, (opt.train_batch_size, nz)) eval_label_ = np.random.randint(0, opt.num_classes, opt.train_batch_size) if opt.noise_class_concat: eval_onehot = np.zeros((opt.train_batch_size, num_classes)) eval_onehot[np.arange(opt.train_batch_size), eval_label_] = 1 eval_noise_[np.arange(opt.train_batch_size), :num_classes] = eval_onehot[np.arange(opt.train_batch_size)] eval_noise_ = (torch.from_numpy(eval_noise_)) eval_noise.data.copy_(eval_noise_.view(opt.train_batch_size, nz)) eval_conditioning_label.data.copy_(torch.from_numpy(eval_label_)) # setup optimizer optimizerD = optim.Adam(netD.parameters(), lr=opt.GAN_lrD, betas=(opt.beta1, opt.beta2)) optimizerG = optim.Adam(netG.parameters(), lr=opt.GAN_lrG, betas=(opt.beta1, opt.beta2)) avg_loss_D = 0.0 avg_loss_G = 0.0 avg_loss_A = 0.0 history = [] history_times = [] score_history = [] score_history_times = [] latest_save = None this_run_iters = 0 this_run_seconds = 0 running_accuracy = RunningAcc(100) running_train_accuracy = RunningAcc(100) D_x_MA, D_G_z1_MA, D_G_z2_MA = MovingAverage(100), MovingAverage(100), MovingAverage(100) while curr_iter <= opt.max_itr: netD.train() netG.train() curr_iter += 1 this_run_iters +=1 this_iter_start = time.time() for dis_step in range(opt.ndis): ############################ # (1) Update D network ########################### d_kwargs = {'logits': False, 'features': False} if opt.d_loss in losses_on_logits: d_kwargs = {'logits': True, 'features': False} # train with real netD.zero_grad() real_cpu, label = labeled_loader.next() batch_size = real_cpu.size(0) if opt.cuda: real_cpu = real_cpu.cuda() input.data.resize_as_(real_cpu).copy_(real_cpu) dis_label.data.resize_(batch_size).fill_(real_label) aux_label.data.resize_(batch_size).copy_(label) conditioning_label.data.resize_(batch_size).copy_(label) dis_output = netD(input, **d_kwargs) errD_real = myloss(dis_output, aux_label, loss_type=opt.d_loss) # if opt.projection_discriminator: # dis_output, aux_output = netD(input, conditioning_label) # else: # if (opt.gantype == 'marygan'): # aux_errD_real = aux_criterion(aux_output, aux_label) # errD_real = aux_errD_real # elif opt.gantype == 'acgan': # aux_errD_real = aux_criterion(aux_output, aux_label) # dis_errD_real = dis_criterion(dis_output, dis_label) # errD_real = dis_errD_real + opt.aux_scale_D * aux_errD_real # elif opt.gantype == 'mhgan': # aux_errD_real = aux_criterion(aux_output, aux_label) # errD_real = aux_errD_real # elif opt.gantype == 'projection': # dis_errD_real = dis_criterion(dis_output, dis_label) # errD_real = dis_errD_real errD_real.backward() D_x = dis_output[:,opt.num_classes].data.mean() # compute the current classification accuracy on train if dis_step == 0: train_accuracy, train_acc_dev = running_train_accuracy.compute_acc(dis_output[:,:opt.num_classes], aux_label) # if opt.gantype == 'mhgan': # else: # accuracy = compute_acc(aux_output, aux_label) # train with fake label = np.random.randint(0, opt.num_classes, batch_size) aux_label.data.resize_(batch_size).copy_(torch.from_numpy(label)) conditioning_label.data.resize_(batch_size).copy_(torch.from_numpy(label)) noise.data.resize_(batch_size, nz).normal_(0, 1) noise_ = np.random.normal(0, 1, (batch_size, nz)) if opt.noise_class_concat: class_onehot = np.zeros((batch_size, opt.num_classes)) class_onehot[np.arange(batch_size), label] = 1 noise_[np.arange(batch_size), :opt.num_classes] = class_onehot if True: #opt.gantype == 'mhgan': # overwrite aux_label to signify fake label_for_fake = (opt.num_classes) * np.ones(batch_size) aux_label.data.resize_(batch_size).copy_(torch.from_numpy(label_for_fake)) noise_ = (torch.from_numpy(noise_)) noise.data.copy_(noise_.view(batch_size, nz)) dis_label.data.fill_(fake_label) fake = netG(noise) dis_output = netD(fake.detach(), **d_kwargs) errD_fake = myloss(dis_output, aux_label, loss_type=opt.d_loss) # if opt.conditional_bn: # fake = netG(noise, conditioning_label) # else: # fake = netG(noise) # if opt.projection_discriminator: # dis_output, aux_output = netD(fake.detach(), conditioning_label) # else: # dis_output, aux_output = netD(fake.detach()) # if (opt.gantype == 'marygan'): # errD_fake = -torch.mean(torch.log(dis_output)) # elif opt.gantype == 'acgan': # dis_errD_fake = dis_criterion(dis_output, dis_label) # aux_errD_fake = aux_criterion(aux_output, aux_label) # errD_fake = dis_errD_fake + opt.aux_scale_D * aux_errD_fake # elif opt.gantype == 'mhgan': # errD_fake = aux_criterion(aux_output, aux_label) # elif opt.gantype == 'projection': # errD_fake = dis_criterion(dis_output, dis_label) errD_fake.backward() D_G_z1 = dis_output[:,opt.num_classes].data.mean() errD = errD_real + errD_fake # train with unlabeled if False and unlabeled_loader: # and opt.gantype == 'mhgan': unl_images, _ = unlabeled_loader.next() if opt.cuda: unl_images = unl_images.cuda() input.data.copy_(unl_images) dis_label.data.fill_(real_label) if opt.projection_discriminator: dis_output, aux_output = netD(input, conditioning_label) else: dis_output, aux_output = netD(input) # dis_errD_unl = dis_criterion(dis_output, dis_label) dis_errD_unl = crammer_singer_complement_criterion(aux_output, aux_label) dis_errD_unl.backward() errD += dis_errD_unl optimizerD.step() ############################ # (2) Update G network ########################### gd_kwargs = {'logits': False, 'features': False} if opt.g_loss in losses_on_features: gd_kwargs = {'logits': False, 'features': True} if opt.g_loss in losses_on_logits: gd_kwargs = {'logits': True, 'features': False} real_features = None fake_features = None output = None netG.zero_grad() dis_label.data.fill_(real_label) # fake labels are real for generator cost if gd_kwargs['features']: fake_features = netD(fake,**gd_kwargs).squeeze() real_features = netD(real_cpu,**gd_kwargs).detach().squeeze() else: output = netD(fake,**gd_kwargs).squeeze() # if opt.projection_discriminator: # dis_output, aux_output = netD(fake, conditioning_label) # else: # dis_output, aux_output = netD(fake) # if (opt.gantype == 'marygan'): # errG = -torch.mean(torch.log(aux_output).max(1)[0]) # elif opt.gantype == 'acgan': # dis_errG = dis_criterion(dis_output, dis_label) # aux_errG = aux_criterion(aux_output, aux_label) # errG = dis_errG + opt.aux_scale_G * aux_errG # elif opt.gantype == 'mhgan': # errG = crammer_singer_complement_criterion(aux_output, aux_label) # # aux_label.data.resize_(batch_size).copy_(torch.from_numpy(label)) # # errG = aux_criterion(aux_output, aux_label) # # errG = hinge_antifake(aux_output, aux_label) # elif opt.gantype == 'projection': # errG = -torch.mean(dis_output) errG_main = myloss(X=output, Ylabel=aux_label, Xfeat=fake_features, Yfeat=real_features, loss_type=opt.g_loss) if opt.g_loss_aux is not None: errG_aux = myloss(X=output, Ylabel=aux_label, Xfeat=fake_features, Yfeat=real_features, loss_type=opt.g_loss_aux) else: errG_aux = 0.0 errG = (1 - opt.g_loss_aux_weight) * errG_main + opt.g_loss_aux_weight * errG_aux errG.backward() D_G_z2 = dis_output[:,opt.num_classes].data.mean() optimizerG.step() ############################ # A little running eval accuracy ########################### with torch.no_grad(): netD.eval() netG.eval() if dev_loader: real_cpu, label = dev_loader.next() if opt.cuda: real_cpu = real_cpu.cuda() input.data.resize_as_(real_cpu).copy_(real_cpu) dis_label.data.resize_(batch_size).fill_(real_label) aux_label.data.resize_(batch_size).copy_(label) conditioning_label.data.resize_(batch_size).copy_(label) # if opt.projection_discriminator: # dis_output, aux_output = netD(input.detach(), conditioning_label) # else: # dis_output, aux_output = netD(input.detach()) # if opt.gantype == 'mhgan': # aux_output = aux_output[:,:(opt.num_classes-1)] aux_output = netD(input.detach(), logits=False, features=False) aux_output = aux_output[:,:opt.num_classes] test_accuracy, test_acc_dev = running_accuracy.compute_acc(aux_output, aux_label) else: test_accuracy, test_acc_dev = -1, -1 # Print statistics D_x_mean, D_x_sigma = D_x_MA.update(D_x.item()) D_G_z1_mean, D_G_z1_sigma = D_G_z1_MA.update(D_G_z1.item()) D_G_z2_mean, D_G_z2_sigma = D_G_z2_MA.update(D_G_z2.item()) # same as D_G_z1 this_run_seconds += (time.time() - this_iter_start) basic_msg = '[%06d][%.2f itr/s] L_D: %.3f L_G: %.3f' \ % (curr_iter, this_run_iters / this_run_seconds, errD.item(), errG.item()) msg = ' D(x): %.2f +/-%.2f D(G(z)): %.2f +/-%.2f Train: %.1f +/-%.1f Test: %.1f +/-%.1f' \ % (D_x_mean, D_x_sigma, D_G_z1_mean, D_G_z1_sigma, train_accuracy, train_acc_dev, test_accuracy, test_acc_dev) msg = re.sub(r"[\s-]0+\.", " .", msg) # get rid of leading zeros print(basic_msg + msg) ### Save GAN Images to interface with IS and FID scores if opt.run_scoring_now or curr_iter % opt.scoring_period == 0: opt.run_scoring_now = False n_used_imgs = 50000 all_fakes = np.empty((n_used_imgs,opt.imageSize,opt.imageSize,3), dtype=np.uint8) if not os.path.exists('%s/GAN_OUTPUTS' % (opt.outf)): os.makedirs('%s/GAN_OUTPUTS' % (opt.outf)) # save a bunch of GAN images for i in tqdm(range(n_used_imgs // opt.train_batch_size),desc='Saving'): start = i * opt.train_batch_size end = start + opt.train_batch_size # fake noise.data.resize_(batch_size, nz).normal_(0, 1) label = np.random.randint(0, opt.num_classes, batch_size) conditioning_label.data.resize_(batch_size).copy_(torch.from_numpy(label)) noise_ = np.random.normal(0, 1, (batch_size, nz)) if opt.noise_class_concat: class_onehot = np.zeros((batch_size, opt.num_classes)) class_onehot[np.arange(batch_size), label] = 1 noise_[np.arange(batch_size), :opt.num_classes] = class_onehot noise_ = (torch.from_numpy(noise_)) noise.data.copy_(noise_.view(batch_size, nz)) if opt.conditional_bn: fake = netG(noise, conditioning_label).data.cpu().numpy() else: fake = netG(noise).data.cpu().numpy() fake = np.floor((fake + 1) * 255/2.0).astype(np.uint8) all_fakes[start:end] = np.moveaxis(fake,1,-1) np.save('%s/GAN_OUTPUTS/out.npy' % (opt.outf), all_fakes) with open('%s/scoring.info' % opt.outf,'w') as f: f.write(str(curr_iter)) if (curr_iter - 1) % opt.eval_period == 0: history.append([errD.item(), errG.item()]) history_times.append(curr_iter) # setup nphist = np.array(history) max_line_samples = 200 ds = max(1,nphist.shape[0] // (max_line_samples+1)) dts = decimate(history_times,ds) new_ids = [] # figure of real images real_grid = vutils.make_grid(real_cpu, nrow=10, padding=2, normalize=True) new_ids.append(vis.image(real_grid, win=winid(), opts={'title': 'Real Images' })) # figure of sorted real images if opt.plot_sorted_outputs: aux_output = netD(real_cpu) real_data = real_cpu.data.cpu() preds = torch.max(aux_output.detach()[:,:(opt.num_classes)],1)[1].data.cpu().numpy() # if opt.gantype == 'mhgan': # else: # preds = torch.max(aux_output.detach(),1)[1].data.cpu().numpy() sorted_i = np.argsort(preds) sorted_preds = preds[sorted_i] sorted_real_imgs = np.zeros(real_data.shape) plab = 0 for i in range(real_data.shape[0]): now_lab = i // 10 # if we have too many images from earlier labels: fast forward while (plab < len(sorted_preds)) and (sorted_preds[plab] < now_lab): plab += 1 if (plab == len(sorted_preds)) or (sorted_preds[plab] > now_lab): # ran out of images for this label # put in a blank image sorted_real_imgs[i,:,:,:] = empty_img elif sorted_preds[plab] == now_lab: # have an image # use the image sorted_real_imgs[i,:,:,:] = real_data[sorted_i[plab],:,:,:] plab += 1 # plot sorted reals real_grid_sorted = vutils.make_grid(torch.Tensor(sorted_real_imgs), nrow=10, padding=2, normalize=True) new_ids.append(vis.image(real_grid_sorted, win=winid(), opts={'title': 'Sorted Real Images ' })) # figure of fake images if opt.conditional_bn: fake = netG(eval_noise, eval_conditioning_label) else: fake = netG(eval_noise) fake_grid = vutils.make_grid(fake.data, nrow=10, padding=2, normalize=True) new_ids.append(vis.image(fake_grid, win=winid(), opts={'title': 'Fixed Fakes' })) # figure of fake images, but sorted if opt.plot_sorted_outputs: n_display_per_class = 10 n_fakes_to_sort = n_display_per_class * opt.num_classes n_batches_to_generate = (n_fakes_to_sort // batch_size) + 1 sorted_fakes_shape = (n_batches_to_generate * batch_size, nc, opt.imageSize, opt.imageSize) all_fake_imgs = np.zeros(sorted_fakes_shape) all_preds = np.zeros((sorted_fakes_shape[0],)) # generate these images for i in range(n_batches_to_generate): # set noise label = np.random.randint(0, opt.num_classes, batch_size) aux_label.data.resize_(batch_size).copy_(torch.from_numpy(label)) noise_ = np.random.normal(0, 1, (batch_size, nz)) conditioning_label.data.resize_(batch_size).copy_(torch.from_numpy(label)) if opt.noise_class_concat: class_onehot = np.zeros((batch_size, opt.num_classes)) class_onehot[np.arange(batch_size), label] = 1 noise_[np.arange(batch_size), :opt.num_classes] = class_onehot noise_ = (torch.from_numpy(noise_)) noise.data.copy_(noise_.view(batch_size, nz)) # generate # if opt.projection_discriminator: # fake = netG(noise, conditioning_label) # dis_output, aux_output = netD(fake, conditioning_label) # else: fake = netG(noise) aux_output = netD(fake) preds = torch.max(aux_output.detach()[:,:opt.num_classes],1)[1].data.cpu().numpy() # if opt.gantype == 'mhgan': # else: # preds = torch.max(aux_output.detach(),1)[1].data.cpu().numpy() # save all_fake_imgs[(i*batch_size):((i+1)*batch_size)] = fake.data.cpu() all_preds[(i*batch_size):((i+1)*batch_size)] = preds sorted_i = np.argsort(all_preds) sorted_preds = all_preds[sorted_i] sorted_imgs = np.zeros(sorted_fakes_shape) plab = 0 # pointer in sorted arrays for i in range(sorted_fakes_shape[0]): # iterate through unfilled sorted_imgs now_lab = i // n_display_per_class # if we have too many images from earlier labels: fast forward while (plab < sorted_fakes_shape[0]) and (sorted_preds[plab] < now_lab): plab += 1 if (plab == sorted_fakes_shape[0]) or (sorted_preds[plab] > now_lab): # ran out of images for this label # put in a blank image sorted_imgs[i,:,:,:] = empty_img elif sorted_preds[plab] == now_lab: # have an image # use the image sorted_imgs[i,:,:,:] = all_fake_imgs[sorted_i[plab],:,:,:] plab += 1 # plot sorted fakes in groups of classes n_classes_display_per_group = 10 for i in range(opt.num_classes // n_classes_display_per_group): group = sorted_imgs[(i*n_display_per_class*n_classes_display_per_group):((i+1)*n_display_per_class*n_classes_display_per_group)] fake_grid_sorted = vutils.make_grid(torch.Tensor(group), nrow=10, padding=2, normalize=True) new_ids.append(vis.image(fake_grid_sorted, win=winid(), opts={'title': 'Sorted Fakes Class %i-%i' % (i*n_classes_display_per_group,(i+1)*n_classes_display_per_group) })) # figure of losses new_ids.append(vis.line(decimate(nphist[:,:2],ds), dts, win=winid(), opts={'legend': ['D', 'G'], 'title': 'Loss'})) # done plotting, update ids visdom_visuals_ids = new_ids # save and overwrite latest checkpoint if latest_save: os.remove('%s/netG_iter_%06d.pth' % (opt.outf, latest_save)) os.remove('%s/netD_iter_%06d.pth' % (opt.outf, latest_save)) torch.save(netG.state_dict(), '%s/netG_iter_%06d.pth' % (opt.outf, curr_iter)) torch.save(netD.state_dict(), '%s/netD_iter_%06d.pth' % (opt.outf, curr_iter)) latest_save = curr_iter # do historical checkpointing (these are not overwritten) if curr_iter % opt.save_period == (opt.save_period - 1): torch.save(netG.state_dict(), '%s/netG_iter_%06d.pth' % (opt.outf, curr_iter)) torch.save(netD.state_dict(), '%s/netD_iter_%06d.pth' % (opt.outf, curr_iter)) vutils.save_image(fake.data,'%s/fake_samples_iter_%06d.png' % (opt.outf, curr_iter), normalize=True) print("Max iteration of %i reached. Quiting..." % opt.max_itr)
import child from 'child_process' import LocalRunner from '../src' jest.mock('child_process', () => { const childProcessMock = { on: jest.fn(), send: jest.fn(), kill: jest.fn() } return { fork: jest.fn().mockReturnValue(childProcessMock) } }) test('should fork a new process', () => { const runner = new LocalRunner('/path/to/wdio.conf.js', { outputDir: '/foo/bar', runnerEnv: { FORCE_COLOR: 1 } }) const worker = runner.run({ cid: '0-5', command: 'run', configFile: '/path/to/wdio.conf.js', args: {}, caps: {}, processNumber: 123, specs: ['/foo/bar.test.js'] }) const childProcess = worker.childProcess worker.emit = jest.fn() expect(worker.isBusy).toBe(true) expect(child.fork.mock.calls[0][0].endsWith('run.js')).toBe(true) const { env } = child.fork.mock.calls[0][2] expect(env.WDIO_LOG_PATH).toMatch(/(\\|\/)foo(\\|\/)bar(\\|\/)wdio-0-5\.log/) expect(env.FORCE_COLOR).toBe(1) expect(childProcess.on).toBeCalled() expect(childProcess.send).toBeCalledWith({ args: {}, caps: {}, cid: '0-5', command: 'run', configFile: '/path/to/wdio.conf.js', specs: ['/foo/bar.test.js'] }) worker.postMessage('runAgain', { foo: 'bar' }) }) test('should shut down worker processes', async () => { const runner = new LocalRunner('/path/to/wdio.conf.js', { outputDir: '/foo/bar', runnerEnv: { FORCE_COLOR: 1 } }) const worker1 = runner.run({ cid: '0-4', command: 'run', configFile: '/path/to/wdio.conf.js', args: {}, caps: {}, processNumber: 124, specs: ['/foo/bar2.test.js'] }) const worker2 = runner.run({ cid: '0-5', command: 'run', configFile: '/path/to/wdio.conf.js', args: {}, caps: {}, processNumber: 123, specs: ['/foo/bar.test.js'] }) setTimeout(() => { worker1.isBusy = false setTimeout(() => { worker2.isBusy = false }, 260) }, 260) const before = Date.now() await runner.shutdown() const after = Date.now() expect(after - before).toBeGreaterThanOrEqual(750) const call1 = worker1.childProcess.send.mock.calls.pop()[0] expect(call1.cid).toBe('0-5') expect(call1.command).toBe('endSession') const call2 = worker1.childProcess.send.mock.calls.pop()[0] expect(call2.cid).toBe('0-4') expect(call2.command).toBe('endSession') }) test('should avoid shutting down if worker is not busy', async () => { const runner = new LocalRunner('/path/to/wdio.conf.js', { outputDir: '/foo/bar', runnerEnv: { FORCE_COLOR: 1 } }) runner.run({ cid: '0-8', command: 'run', configFile: '/path/to/wdio.conf.js', args: { sessionId: 'abc' }, caps: {}, processNumber: 231, specs: ['/foo/bar2.test.js'], }) runner.workerPool['0-8'].isBusy = false await runner.shutdown() expect(runner.workerPool['0-8']).toBeFalsy() }) test('should shut down worker processes in watch mode - regular', async () => { const runner = new LocalRunner('/path/to/wdio.conf.js', { outputDir: '/foo/bar', runnerEnv: { FORCE_COLOR: 1 }, watch: true, }) const worker = runner.run({ cid: '0-6', command: 'run', configFile: '/path/to/wdio.conf.js', args: { sessionId: 'abc' }, caps: {}, processNumber: 231, specs: ['/foo/bar2.test.js'], }) runner.workerPool['0-6'].sessionId = 'abc' runner.workerPool['0-6'].server = { host: 'foo' } runner.workerPool['0-6'].caps = { browser: 'chrome' } setTimeout(() => { worker.isBusy = false }, 260) const before = Date.now() await runner.shutdown() const after = Date.now() expect(after - before).toBeGreaterThanOrEqual(300) const call2 = worker.childProcess.send.mock.calls.pop()[0] expect(call2.cid).toBe('0-6') expect(call2.command).toBe('endSession') expect(call2.args.watch).toBe(true) expect(call2.args.isMultiremote).toBeFalsy() expect(call2.args.config.sessionId).toBe('abc') expect(call2.args.config.host).toEqual('foo') expect(call2.args.caps).toEqual({ browser: 'chrome' }) }) test('should shut down worker processes in watch mode - mutliremote', async () => { const runner = new LocalRunner('/path/to/wdio.conf.js', { outputDir: '/foo/bar', runnerEnv: { FORCE_COLOR: 1 }, watch: true, }) const worker = runner.run({ cid: '0-7', command: 'run', configFile: '/path/to/wdio.conf.js', args: {}, caps: {}, processNumber: 232, specs: ['/foo/bar.test.js'], }) runner.workerPool['0-7'].isMultiremote = true runner.workerPool['0-7'].instances = { foo: {} } runner.workerPool['0-7'].caps = { foo: { capabilities: { browser: 'chrome' } } } setTimeout(() => { worker.isBusy = false }, 260) const before = Date.now() await runner.shutdown() const after = Date.now() expect(after - before).toBeGreaterThanOrEqual(300) const call1 = worker.childProcess.send.mock.calls.pop()[0] expect(call1.cid).toBe('0-7') expect(call1.command).toBe('endSession') expect(call1.args.watch).toBe(true) expect(call1.args.isMultiremote).toBe(true) expect(call1.args.instances).toEqual({ foo: {} }) expect(call1.args.caps).toEqual({ foo: { capabilities: { browser: 'chrome' } } }) }) test('should avoid shutting down if worker is not busy', async () => { const runner = new LocalRunner('/path/to/wdio.conf.js', {}) expect(runner.initialise()).toBe(undefined) })
'use strict'; module.exports = { shared: { apiVersion: '1' }, local: { db: 'mongodb://localhost/bookStore' }, testing: { db: 'mongodb://localhost/bookStore-testing' }, staging: { db: 'mongodb://localhost/bookStore' }, production: { db: 'mongodb://localhost/bookStore' } };
from astropy import units as u from numpy.linalg import norm class LithobrakeEvent: """Terminal event that detects impact with the attractor surface. Parameters ---------- R : float Radius of the attractor. """ def __init__(self, R): self._R = R self._last_t = None @property def terminal(self): # Tell SciPy to stop the integration at H = R (impact) return True @property def last_t(self): return self._last_t * u.s def __call__(self, t, u, k): self._last_t = t H = norm(u[:3]) # SciPy will search for H - R = 0 return H - self._R
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ "use strict"; const { dirname, join, parse } = require("path"); module.exports = class HasteFS { constructor(files) { this.directories = buildDirectorySet(files); this.directoryEntries = buildDirectoryEntries(files.map(parse)); this.files = new Set(files); } closest(path, fileName) { const parsedPath = parse(path); const root = parsedPath.root; let dir = parsedPath.dir; do { const candidate = join(dir, fileName); if (this.files.has(candidate)) { return candidate; } dir = dirname(dir); } while (dir !== "." && dir !== root); return null; } dirExists(path) { return this.directories.has(path); } exists(path) { return this.files.has(path); } getAllFiles() { return Array.from(this.files.keys()); } matchFiles() { throw new Error("HasteFS.matchFiles is not implemented yet."); } matches(directory, pattern) { const entries = this.directoryEntries.get(directory); // $FlowFixMe[method-unbinding] added when improving typing for this parameters // $FlowFixMe[incompatible-call] return entries ? entries.filter(pattern.test, pattern) : []; } }; function buildDirectorySet(files) { const directories = new Set(); files.forEach(path => { const parsedPath = parse(path); const root = parsedPath.root; let dir = parsedPath.dir; while (dir !== "." && dir !== root && !directories.has(dir)) { directories.add(dir); dir = dirname(dir); } }); return directories; } function buildDirectoryEntries(files) { const directoryEntries = new Map(); files.forEach(({ base, dir }) => { const entries = directoryEntries.get(dir); if (entries) { entries.push(base); } else { directoryEntries.set(dir, [base]); } }); return directoryEntries; }
import request from '@/utils/request' const baseUrl = require('@/api/config.js'); import axios from "axios"; import { getToken } from '@/utils/auth' // 新增采购订单 export function addPurchaseOrder(option) { return request.post(`/backend-order/purchaseOrder/save`, option); } // 更新采购订单 export function updatePurchaseOrder(option) { return request.post(`/backend-order/purchaseOrder/update`, option); } // 采购订单详情 export function purchaseOrderDetail(option) { return request.get(`/backend-order/purchaseOrder/getDetailById`, { params: option }); } // 采购订单详情(含流程控制塔) export function getDetailPOFlowById(option) { return request.get(`/backend-order/purchaseOrder/getDetailPOFlowById`, { params: option }); } export function selectSupplierCompanyList(option) { return request.get(`/backend-order/purchaseOrder/selectSupplierCompanyList`, { params: option }); } // 采购订单分页列表 export function getPurchaseOrderList(option) { return request.post(`/backend-order/purchaseOrder/pageph`, option); } // 删除采购订单 export function deletePurchaseOrder(option) { return request.delete(`/backend-order/purchaseOrder/deleteBatchByIds`, { params: option }); } // 确认作废操作 export function confirmObsoleteById(option) { return request.post(`/backend-order/purchaseOrder/confirmObsoleteById`, option); } // 付款详情 export function payTermsByBid(option) { return request.get(`/backend-supplier/supplierPaymentTerms/detailByBid`, { params: option }); } // 获取待采购的销售订单 export function getWaitSaleOrder(option) { return request.post(`/backend-order/salesOrder/getSalesOrderByOrderNo`, option); } // 销售订单通过bid查询商品 export function getSaleOrderSkuByBId(option) { return request.get(`/backend-order/salesOrder/getProductBySalesOrderBid`, { params: option }); } // 采购订单批量新增 export function addBatchPurchase(option) { return request.post(`/backend-order/purchaseOrder/saveBatch`, option); } // 采购订单流程节点 export function getNodePurchase(option) { return request.get(`/backend-order/purchaseOrder/selectWFProcessByBid`, { params: option }); } // 采购订单新增上传记录 export function addPurchaseRecord(option) { return request.post(`/backend-order/purchaseOrderAttachments/save`, option); } // 采购订单新增上传记录 export function getPurchaseRecord(option) { return request.get(`/backend-order/purchaseOrderAttachments/list`, { params: option }); } // 采购订单删除上传记录 export function deleteOrderRecord(option) { return request.post(`/backend-order/purchaseOrderAttachments/delete`, option); } // 采购订单验收 export function purchaseOrderCheck(option) { return request.post(`/backend-order/purchaseOrderAttachments/updatePoaByBId`, option); } // 采购订单文件上传凭证列表 export function getPurchaseRecordList(option) { return request.get(`/backend-order/purchaseOrderAttachments/selectPurchaseData`, { params: option }); } // 采购订单相关的销售订单 export function getPurchaseRelateOrder(option) { return request.get(`/backend-order/purchaseOrderAttachments/selectSaleOrderDataList`, { params: option }); } /** * * 导出采购订单列表-导出 */ export function exportPurchaseOrderExcel(option) { return axios({ method: 'post', data: option, url: `${baseUrl.baseUrl}/backend-order/purchaseOrder/exportPurchaseOrderExcel`, headers: { token: getToken() }, responseType: 'blob' }) }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'tb'; var iconName = 'manual-gearbox'; var width = 512; var height = 512; var ligatures = []; var unicode = null; var svgPathData = 'M 106.65039 63.990234 C 71.56234 63.990236 42.66016 92.892416 42.660156 127.98047 C 42.660156 155.60397 60.578206 179.38218 85.320312 188.25391 L 85.320312 255.85547 A 21.33 21.33 0 0 0 85.320312 255.96094 L 85.320312 323.66602 C 60.578206 332.53774 42.660156 356.31596 42.660156 383.93945 C 42.660156 419.02751 71.562338 447.92969 106.65039 447.92969 C 141.73845 447.92969 170.64062 419.02751 170.64062 383.93945 C 170.64063 356.31596 152.72258 332.53774 127.98047 323.66602 L 127.98047 277.28906 L 234.63086 277.28906 L 234.63086 323.66602 C 209.88875 332.53774 191.9707 356.31596 191.9707 383.93945 C 191.9707 419.02751 220.87288 447.92969 255.96094 447.92969 C 291.04899 447.92969 319.94922 419.02751 319.94922 383.93945 C 319.94922 356.31531 302.03155 332.53725 277.28906 323.66602 L 277.28906 277.28906 L 362.60938 277.28906 C 397.69743 277.28906 426.59961 248.38884 426.59961 213.30078 L 426.59961 188.25391 C 451.34172 179.38218 469.25977 155.60397 469.25977 127.98047 C 469.25976 92.892415 440.35758 63.990234 405.26953 63.990234 C 370.18148 63.990234 341.2793 92.892415 341.2793 127.98047 C 341.2793 155.60397 359.19735 179.38218 383.93945 188.25391 L 383.93945 213.30078 C 383.93945 225.33366 374.64225 234.63086 362.60938 234.63086 L 277.28906 234.63086 L 277.28906 188.25391 C 302.03155 179.38267 319.94922 155.60461 319.94922 127.98047 C 319.94922 92.892415 291.04899 63.990234 255.96094 63.990234 C 220.87288 63.990234 191.97071 92.892415 191.9707 127.98047 C 191.9707 155.60397 209.88875 179.38218 234.63086 188.25391 L 234.63086 234.63086 L 127.98047 234.63086 L 127.98047 188.25391 C 152.72258 179.38218 170.64062 155.60397 170.64062 127.98047 C 170.64062 92.892415 141.73844 63.990234 106.65039 63.990234 z M 106.65039 106.65039 C 118.68327 106.65039 127.98047 115.94759 127.98047 127.98047 C 127.98047 140.01335 118.68327 149.31055 106.65039 149.31055 C 94.617512 149.31055 85.320312 140.01335 85.320312 127.98047 C 85.320314 115.94759 94.617513 106.65039 106.65039 106.65039 z M 255.96094 106.65039 C 267.99382 106.65039 277.28906 115.94759 277.28906 127.98047 C 277.28906 140.01335 267.99382 149.31055 255.96094 149.31055 C 243.92806 149.31055 234.63086 140.01335 234.63086 127.98047 C 234.63086 115.94759 243.92806 106.65039 255.96094 106.65039 z M 405.26953 106.65039 C 417.30241 106.65039 426.59961 115.94759 426.59961 127.98047 C 426.59961 140.01335 417.30241 149.31055 405.26953 149.31055 C 393.23665 149.31055 383.93945 140.01335 383.93945 127.98047 C 383.93945 115.94759 393.23665 106.65039 405.26953 106.65039 z M 106.65039 362.60938 C 118.68327 362.60938 127.98047 371.90657 127.98047 383.93945 C 127.98047 395.97233 118.68327 405.26953 106.65039 405.26953 C 94.617512 405.26953 85.320312 395.97233 85.320312 383.93945 C 85.320312 371.90657 94.617512 362.60938 106.65039 362.60938 z M 255.96094 362.60938 C 267.99382 362.60938 277.28906 371.90657 277.28906 383.93945 C 277.28906 395.97233 267.99382 405.26953 255.96094 405.26953 C 243.92806 405.26953 234.63086 395.97233 234.63086 383.93945 C 234.63086 371.90657 243.92806 362.60938 255.96094 362.60938 z '; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.tbManualGearbox = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
/** * RepoListItem * * リポジトリの名前と、発行件数をリストします */ import React from 'react'; import PropTypes from 'prop-types'; import ListItem from 'components/ListItem'; import { IssueIcon } from 'components/Icons'; import './style.scss'; export default class RepoListItem extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { const { item, currentUser } = this.props; let nameprefix = ''; // リポジトリが所有しているデータが、 // (フォークであるために)別の人が所有している場合、 // 所有者の名前を表示する必要があります。 if (item.owner.login !== currentUser) { nameprefix = `${item.owner.login}/`; } // リポジトリのコンテンツをまとめます。 const content = ( <div className="repo-list-item"> <a className="repo-list-item__repo-link" href={item.html_url} target="_blank" rel="noopener noreferrer"> {nameprefix + item.name} </a> <a className="repo-list-item__issue-link" href={`${item.html_url}/issues`} target="_blank" rel="noopener noreferrer"> <IssueIcon className="repo-list-item__issue-icon" /> {item.open_issues_count} </a> </div> ); // コンテンツを、リストアイテムに描画します。 return ( <ListItem key={`repo-list-item-${item.full_name}`} item={content} /> ); } } RepoListItem.propTypes = { item: PropTypes.object, currentUser: PropTypes.string, };
/*! * morgan * Copyright(c) 2010 Sencha Inc. * Copyright(c) 2011 TJ Holowaychuk * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var auth = require('basic-auth') var debug = require('debug')('morgan') var deprecate = require('depd')('morgan') var onFinished = require('on-finished') /** * Array of CLF month names. * @private */ var clfmonth = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] /** * Default log buffer duration. * @private */ var defaultBufferDuration = 1000; /** * Create a logger middleware. * * @public * @param {String|Function} format * @param {Object} [options] * @return {Function} middleware */ exports = module.exports = function morgan(format, options) { if (typeof format === 'object') { options = format format = options.format || 'default' // smart deprecation message deprecate('morgan(options): use morgan(' + (typeof format === 'string' ? JSON.stringify(format) : 'format') + ', options) instead') } if (format === undefined) { deprecate('undefined format: specify a format') } options = options || {} // output on request instead of response var immediate = options.immediate; // check if log entry should be skipped var skip = options.skip || function () { return false; }; // format function var fmt = compile(exports[format] || format || exports.default) // steam var buffer = options.buffer var stream = options.stream || process.stdout // logger var logger = options.logger // buffering support if (buffer) { deprecate('buffer option') var realStream = stream var buf = [] var timer = null var interval = 'number' == typeof buffer ? buffer : defaultBufferDuration // flush function var flush = function(){ timer = null if (buf.length) { realStream.write(buf.join('')); buf.length = 0; } } // swap the stream stream = { write: function(str){ if (timer === null) { timer = setTimeout(flush, interval) } buf.push(str); } }; } return function(req, res, next) { req._startAt = process.hrtime(); req._startTime = new Date; req._remoteAddress = getip(req); function logRequest(){ if (skip(req, res)) { debug('skip request') return } var formatted = fmt(exports, req, res); var line; var tokenPairs; if (typeof formatted === 'object') { line = formatted.line; tokenPairs = formatted.tokenPairs; } else { line = formatted; } if (null == line) { debug('skip line') return } debug('log request'); if (logger) { logger(line, tokenPairs); } else { stream.write(line + '\n'); } }; // immediate if (immediate) { logRequest(); } else { onFinished(res, logRequest) } next(); }; }; /** * Compile `format` into a function. * * @private * @param {Function|String} format * @return {Function} */ function compile(format) { if (typeof format === 'function') { // already compiled return format } if (typeof format !== 'string') { throw new TypeError('argument format must be a function or string') } var fmt = format.replace(/"/g, '\\"'); var tokens = []; var line = '"' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg){ tokens.push([name, arg]); return '"\n + values["' + name + '"] + "'; }) + '"'; var values = ("var values = {" + tokens.map(function(token, i) { var name = token[0]; var arg = String(JSON.stringify(token[1])); return '"' + name + '": (tokens["' + name + '"](req, res, ' + arg + ') || "-")' + (i < tokens.length - 1 ? ',' : ''); }).join('') + "};"); var js = (values + "\n" + "return {" + "tokenPairs: values," + "line: " + line + "};" ); return new Function('tokens, req, res', js); }; /** * Define a token function with the given `name`, * and callback `fn(req, res)`. * * @public * @param {String} name * @param {Function} fn * @return {Object} exports for chaining */ exports.token = function(name, fn) { exports[name] = fn; return this; }; /** * Define a `fmt` with the given `name`. * * @public * @param {String} name * @param {String|Function} fmt * @return {Object} exports for chaining */ exports.format = function(name, fmt){ exports[name] = fmt; return this; }; /** * Apache combined log format. */ exports.format('combined', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"') /** * Apache common log format. */ exports.format('common', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]') /** * Default format. */ exports.format('default', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'); deprecate.property(exports, 'default', 'default format: use combined format') /** * Short format. */ exports.format('short', ':remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'); /** * Tiny format. */ exports.format('tiny', ':method :url :status :res[content-length] - :response-time ms'); /** * dev (colored) */ exports.format('dev', function(tokens, req, res){ var color = 32; // green var status = res.statusCode; if (status >= 500) color = 31; // red else if (status >= 400) color = 33; // yellow else if (status >= 300) color = 36; // cyan var fn = compile('\x1b[0m:method :url \x1b[' + color + 'm:status \x1b[0m:response-time ms - :res[content-length]\x1b[0m'); return fn(tokens, req, res); }); /** * request url */ exports.token('url', function(req){ return req.originalUrl || req.url; }); /** * request method */ exports.token('method', function(req){ return req.method; }); /** * response time in milliseconds */ exports.token('response-time', function(req, res){ if (!res._header || !req._startAt) return ''; var diff = process.hrtime(req._startAt); var ms = diff[0] * 1e3 + diff[1] * 1e-6; return ms.toFixed(3); }); /** * current date */ exports.token('date', function(req, res, format){ format = format || 'web' var date = new Date() switch (format) { case 'clf': return clfdate(date) case 'iso': return date.toISOString() case 'web': return date.toUTCString() } }); /** * response status code */ exports.token('status', function(req, res){ return res._header ? res.statusCode : null; }); /** * normalized referrer */ exports.token('referrer', function(req){ return req.headers['referer'] || req.headers['referrer']; }); /** * remote address */ exports.token('remote-addr', getip); /** * remote user */ exports.token('remote-user', function (req) { var creds = auth(req) var user = (creds && creds.name) || '-' return user; }) /** * HTTP version */ exports.token('http-version', function(req){ return req.httpVersionMajor + '.' + req.httpVersionMinor; }); /** * UA string */ exports.token('user-agent', function(req){ return req.headers['user-agent']; }); /** * request header */ exports.token('req', function(req, res, field){ return req.headers[field.toLowerCase()]; }); /** * response header */ exports.token('res', function(req, res, field){ return (res._headers || {})[field.toLowerCase()]; }); /** * Format a Date in the common log format. * * @private * @param {Date} dateTime * @return {string} */ function clfdate(dateTime) { var date = dateTime.getUTCDate() var hour = dateTime.getUTCHours() var mins = dateTime.getUTCMinutes() var secs = dateTime.getUTCSeconds() var year = dateTime.getUTCFullYear() var month = clfmonth[dateTime.getUTCMonth()] return pad2(date) + '/' + month + '/' + year + ':' + pad2(hour) + ':' + pad2(mins) + ':' + pad2(secs) + ' +0000' } /** * Get request IP address. * * @private * @param {IncomingMessage} req * @return {string} */ function getip(req) { return req.ip || req._remoteAddress || (req.connection && req.connection.remoteAddress) || undefined; } /** * Pad number to two digits. * * @private * @param {number} num * @return {string} */ function pad2(num) { var str = String(num) return (str.length === 1 ? '0' : '') + str }
var searchData= [ ['full_5fmatch_1949',['full_match',['../block_8c.html#a1ec5cbfe5f4d8b25e30d7ff67ac69eb5',1,'block.c']]] ];
const express = require('express'); const SocketServer = require('ws'); const uuidv4 = require('uuid/v4'); // Set the port to 3001 const PORT = 3001; let counter = 0; // Create a new express server const server = express() // Make the express server serve static assets (html, javascript, css) from the /public folder .use(express.static('public')) .listen(PORT, '0.0.0.0', 'localhost', () => console.log(`Listening on ${ PORT }`)); // Create the WebSockets server const wss = new SocketServer.Server({ server }); //Function that will send data to all clients connected to server wss.broadcast = function broadcast(data) { wss.clients.forEach(function each(client) { if (client.readyState === SocketServer.OPEN) { client.send(data); } }); }; // Set up a callback that will run when a client connects to the server // When a client connects they are assigned a socket, represented by // the ws parameter in the callback. wss.on('connection', (ws) => { console.log('Client connected'); counter += 1; console.log(counter); wss.broadcast(JSON.stringify({type: "Client connected", count: counter})); //Server side handling of incoming messages and user-change notifications //server also creates unique keys using UUID ws.on('message', function incoming(message) { let mess = JSON.parse(message); console.log(mess); if(mess.type === "postMessage"){ const answer = {id: uuidv4(), username: mess.username, color: mess.color, content: mess.content, type: "incomingMessage"}; wss.broadcast(JSON.stringify(answer)); } else if(mess.type === "postNotification"){ const answer = {id: uuidv4(), content: `${mess.username} changed their name to ${mess.content}`, type: "incomingNotification"}; wss.broadcast(JSON.stringify(answer)); } }); // Set up a callback for when a client closes the socket. This usually means they closed their browser. ws.on('close', () => { console.log('Client disconnected'); counter -= 1; console.log(counter); wss.broadcast(JSON.stringify({type: "Client disconnected", count: counter})); }); });
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import moox from 'moox'; import PropTypes from 'prop-types'; import { devToolsEnhancer } from 'redux-devtools-extension'; import App from './App'; import utils from './utils'; import schema from './models/schema'; module.exports = (config = {}) => { if (config.lang) utils.lang = config.lang; const Model = moox({ schema, }, // { // enhancer: devToolsEnhancer() // } ); if (config.format) { Model.__jsonSchemaFormat = config.format; } else { Model.__jsonSchemaFormat = utils.format; } const store = Model.getStore(); const DefaultComponent = props => { return ( <div>{props.children}</div> ) } class Component extends React.Component { constructor(props) { super(props); } WrapComponent = this.props.WrapComponent || DefaultComponent; render() { return ( <Provider store={store} className="wrapper"> <App Model={Model} {...this.props} WrapComponent={this.WrapComponent} /> </Provider> ); } } Component.propTypes = { data: PropTypes.string, onChange: PropTypes.func, showEditor: PropTypes.bool, refSchemas: PropTypes.array, refFunc: PropTypes.func, WrapComponent: PropTypes.func, }; return Component; };
// moment.js locale configuration // locale : Morocco Central Atlas Tamaziɣt (tzm) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory((typeof global !== 'undefined' ? global : this).moment); // node or other global } }(function (moment) { return moment.defineLocale('tzm', { months : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), monthsShort : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), weekdays : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), weekdaysShort : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), weekdaysMin : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), longDateFormat : { LT : 'HH:mm', LTS: 'LT:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY LT', LLLL : 'dddd D MMMM YYYY LT' }, calendar : { sameDay: '[ⴰⵙⴷⵅ ⴴ] LT', nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', nextWeek: 'dddd [ⴴ] LT', lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', lastWeek: 'dddd [ⴴ] LT', sameElse: 'L' }, relativeTime : { future : 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s', past : 'ⵢⴰⵏ %s', s : 'ⵉⵎⵉⴽ', m : 'ⵎⵉⵏⵓⴺ', mm : '%d ⵎⵉⵏⵓⴺ', h : 'ⵙⴰⵄⴰ', hh : '%d ⵜⴰⵙⵙⴰⵄⵉⵏ', d : 'ⴰⵙⵙ', dd : '%d oⵙⵙⴰⵏ', M : 'ⴰⵢoⵓⵔ', MM : '%d ⵉⵢⵢⵉⵔⵏ', y : 'ⴰⵙⴳⴰⵙ', yy : '%d ⵉⵙⴳⴰⵙⵏ' }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); }));
# Beispielprogramm für das Buch "Python Challenge" # # Copyright 2020 by Michael Inden import pytest from ch05_datastructures.solutions.ex04_remove_duplicates import remove_duplicates, remove_duplicates_with_dict def inputs_and_expected(): return [([1, 1, 2, 3, 4, 1, 2, 3], [1, 2, 3, 4]), ([7, 5, 3, 5, 1], [7, 5, 3, 1]), ([1, 1, 1, 1], [1])] @pytest.mark.parametrize("inputs, expected", inputs_and_expected()) def test_remove_duplicates(inputs, expected): result = remove_duplicates(inputs) assert expected == result @pytest.mark.parametrize("inputs, expected", inputs_and_expected()) def test_remove_duplicates_with_dict(inputs, expected): result = remove_duplicates_with_dict(inputs) assert expected == result
import render from './render' export default { render }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var MentionsContextKey = Symbol('MentionsContextKey'); var _default = MentionsContextKey; exports.default = _default;
'use strict'; var Tester = require('../../src/tester'); var assert = require('assert'); new Tester() .addPackage('add', function(a, b) { return a + b; }, '0.1.0') .addPackage('sub', function(a, b) { return a - b; }) .addPackage('mul', function(a, b) { return a * b; }, '') .addPackage('div', function(a, b) { return a / b; }, '1.2.0') .addTest('add', function(add, data) { return add(data[0], data[1]); }) .addTest('sub', function(sub, data) { return sub(data[0], data[1]); }) .addTest('mul', function(mul, data) { return mul(data[0], data[1]); }) .addTest('div', function(div, data) { return div(data[0], data[1]); }) .verifyTest('add', [123, 456], 579) .verifyTest('sub', [123, 456], -334, assert.notEqual) .verifyTest('mul', function(testFn, mul) { assert.strictEqual(testFn(mul, [123, 456]), 56088); }) .verifyTest('div', function(testFn, div) { var value = testFn(div, [123, 456]); assert.ok(0.26 < value && value < 0.27); }) .runTest('Zeros', [0, 0]) .runTest('Integers', [123, 456]) .runTest('Decimals', [0.123, 4.56]) .addTest('add', function(add, data) { return add(add(data[0], data[1]), data[2]); }) .addTest('sub', function(sub, data) { return sub(sub(data[0], data[1]), data[2]); }) .addTest('mul', function(mul, data) { return mul(mul(data[0], data[1]), data[2]); }) .addTest('div', function(div, data) { return div(div(data[0], data[1]), data[2]); }) .runTest('Zeros (3 num)', [0, 0, 0]) .runTest('Integers (3 num)', [123, 456, 789]) .runTest('Decimals (3 num)', [0.123, 4.56, -0.0789]) .print();
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } import * as React from "react"; function SvgSignalWifiStatusbarConnectedNoInternet4(props) { return /*#__PURE__*/React.createElement("svg", _extends({ xmlns: "http://www.w3.org/2000/svg", width: 24, height: 24, viewBox: "0 0 24 24" }, props), /*#__PURE__*/React.createElement("path", { d: "M19 18h2v2h-2zm0-8h2v6h-2z" }), /*#__PURE__*/React.createElement("path", { d: "M12 4C7.31 4 3.07 5.9 0 8.98L12 21l5-5.01V8h5.92C19.97 5.51 16.16 4 12 4z" })); } export default SvgSignalWifiStatusbarConnectedNoInternet4;
import bisect import Tkinter as tk class NumberModel(object): def __init__(self, val=0): self.value = val def increment(self): self.value += 1 def decrement(self): self.value -= 1 class GraphModel(object): def __init__(self): self.points = [] def add_point(self, point): bisect.insort(self.points, point) def __len__(self): return len(self.points) class Controller(object): def __init__(self, number_model, graph_model): self.number_model = number_model self.graph_model = graph_model def increment(self): self.number_model.increment() self._update_graph() def decrement(self): self.number_model.decrement() self._update_graph() def _update_graph(self): x_value = len(self.graph_model) y_value = self.number_model.value self.graph_model.add_point((x_value, y_value)) class Window(tk.Frame): def __init__(self, model, controller, *args): tk.Frame.__init__(self, *args) self.entry = tk.Label(self) self.quit_button = tk.Button(self, text='Quit', command=root.destroy) self.inc_button = tk.Button(self, text='+', command=self.increment) self.dec_button = tk.Button(self, text='-', command=self.decrement) self.entry.grid(row=0, columnspan=2) self.inc_button.grid(row=1, column=0) self.dec_button.grid(row=1, column=1) self.quit_button.grid(row=2) self.pack() self.model = model self.controller = controller self.update() def update(self): self.entry.configure(text=str(self.model.value)) def increment(self): self.controller.increment() self.update() def decrement(self): self.controller.decrement() self.update() if __name__ == '__main__': root = tk.Tk() number_model = NumberModel() graph_model = GraphModel() controller = Controller(number_model, graph_model) w = Window(number_model, controller, root) root.mainloop()
import React from 'react'; import { Link, graphql, navigate } from 'gatsby'; import { window } from 'browser-monads'; import Layout from '../components/layout'; import Nav from '../components/nav'; import SEO from '../components/seo'; import '../components/home/home.css'; import './archive.css'; import headerImg from '../images/mario-azzi-DY2miYwMchk-unsplash.jpg'; const ContemporaryBlock = (props) => { const blogContent = props.data.allContentfulBlog; const { currentPage, numOfPages } = props.pageContext; // this comes from gatsby-node! const isFirstPage = currentPage === 1; const isLastPage = currentPage === numOfPages; const previousPage = currentPage - 1 === 1 ? '/category/contemporary-block' : `/category/contemporary-block${currentPage - 1}`; // does the current page - 1 equal 1? if so, direct to blog, otherwise, direct to blog/2 etc. const nextPage = `/category/contemporary-block/${currentPage + 1}`; return ( <Layout> <SEO title='Contemporary Block' keywords={['halloween', 'horror blog', 'horror movies']} /> <Nav /> <header> <div className='archive_section'> <div className='archive_hero' style={{ backgroundImage: `url(${headerImg})` }}> </div> <div className="archive_nav"> <Link to='/blog' className={window.location.href.indexOf('/blog') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> All </Link> <Link to='/category/contemporary-block' className={window.location.href.indexOf('category/contemporary-block') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> Contemporary Block </Link> <Link to='/category/un-block' className={window.location.href.indexOf('category/un-block') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> Un Block </Link> <Link to='/category/vampire-block' className={window.location.href.indexOf('category/vampire-block') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> Vampire Block </Link> <Link to='/category/awful-block' className={window.location.href.indexOf('category/awful-block') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> Awful Block </Link> <Link to='/category/slasher-block' className={window.location.href.indexOf('category/slasher-block') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> Slasher Block </Link> <Link to='/category/japanese-block' className={window.location.href.indexOf('category/japanese-block') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> Japanese Block </Link> <Link to='/category/stephen-king-block' className={window.location.href.indexOf('category/stephen-king-block') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> Stephen King Block </Link> <Link to='/category/john-carpenter-block' className={window.location.href.indexOf('category/john-carpenter-block') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> John Carpenter Block </Link> <Link to='/category/other' className={window.location.href.indexOf('category/other') > 0 ? 'archive_nav_link selected' : 'archive_nav_link'}> Other </Link> </div> </div> </header> <div className='feed'> {blogContent.edges.map(edge => ( <div key={edge.node.id} className='card' style={{ backgroundImage: `linear-gradient( to bottom, rgba(10, 10, 10, 0) 0%, rgba(10, 10, 10, 0) 50%, rgba(10, 10, 10, 0.7) 100%), url(${edge.node.featuredImage.fluid.src})` }} onClick={() => navigate(`/blog/${edge.node.slug}`)} > {edge.node.category.map(category => ( <p className='card_category'>{category.title}</p> ))} <p className="card_title"> {edge.node.title} </p> </div> ))} </div> <div className='pagination'> <div className='pagination_item'> {!isFirstPage && ( <Link to={previousPage} rel="previous"> <div className="arrow_back"> </div> </Link> )} {/* if this is not the first page and true, we display an arrow back */} </div> <div className='pagination_item'> {!isLastPage && ( <Link to={nextPage} rel="next"> <div className="arrow_next"> </div> </Link> )} {/* if this is not the last page and true, we display an arrow forward */} </div> </div> </Layout> ) } export default ContemporaryBlock; export const pageQuery = graphql` query ContemporaryBlockQuery ($skip: Int!, $limit: Int!) { allContentfulBlog( sort: { fields: [createdAt], order: DESC } filter: { node_locale: {eq: "en-US"} category: {elemMatch: {title: {eq: "Contemporary Block"}}} } skip: $skip limit: $limit ) { edges { node { id slug title createdAt category { title id } featuredImage { fluid(maxWidth: 1200, quality: 85) { src ...GatsbyContentfulFluid } } } } } } `
import urllib.request # 构建一个HTTPHandler处理器对象,支持处理HTTP请求 http_handler = urllib.request.HTTPHandler() # 加上debuglever参数,还可以启动debug模式,默认值为0 #http_handler = urllib.request.HTTPHandler(debuglevel=1) # 构建一个HTTPHandler处理器对象,支持处理HTTPS请求 #http_handler = urllib.request.HTTPSHandler() # 调用urllib.request.build_opener()方法,创建支持处理HTTP请求的opener对象 opener = urllib.request.build_opener(http_handler) #构建request请求 request = urllib.request.Request("http://www.baidu.com/") #调用自定义opener对象的open()方法,发送request请求 response = opener.open(request) html = response.read().decode("utf-8") print(html)
"use strict"; var Models = require("../models"); const getUsers = (res) => { Models.Users.find({}, {}, {}, (err,data) => { if (err) throw err; res.send({result: 200 , data: data}) }); } const createUsers = (data, res) => { new Models.Users(data).save((err,data) => { if(err) throw err res.send({ result: 200 , data: data}) }); } module.exports = { getUsers, createUsers }
#!/usr/local/bin/python3 def fibonacci(quantidade, sequencia=(0, 1)): # Importante: Condição de parada if len(sequencia) == quantidade: return sequencia return fibonacci(quantidade, sequencia + (sum(sequencia[-2:]),)) if __name__ == '__main__': # Listar os 20 primeiros números da sequência for fib in fibonacci(20): print(fib)
let homeController = require('./home-controller') let usersController = require('./users-controller') let articlesController = require('./articles-controller') let profileController = require('./profile-controller') let eventController = require('./event-controller') module.exports = { home: homeController, users: usersController, articles: articlesController, profile: profileController, event: eventController }
import { fetch } from "./fetch"; export function getLatestBlock(num) { return fetch({ method: "post", url: "LatestBlock", data: { num } }); } export function getLatestMessage(num) { return fetch({ method: "post", url: "LatestMsg", data: { num } }); } export function getBoardInfo() { return fetch({ method: "post", url: "BaseInformation" }); } /* param:{ start_time timestamp end_time timestamp } */ export function getBlockTimeData(data) { return fetch({ method: "post", url: "BlocktimeGraphical", data }); } /* param:{ start_time timestamp end_time timestamp } */ export function getBlocSizeData(data) { return fetch({ method: "post", url: "AvgBlockheaderSizeGraphical", data }); } /* param:{ start_time timestamp end_time timestamp } */ export function getGetFil() { return fetch({ method: "post", url: "GetFil", }); } // param:{ // key number // } export function getPowerIn(data){ return fetch({ method: "post", url: "GetPowerIn", data }); } // param:{ // key number // } export function getFee(data) { return fetch({ method: "post", url: "GetFee", data }); } /* param:{ time timestamp } */ export function getTotalPowerData(data) { return fetch({ method: "post", url: "/TotalPowerGraphical", data }); } /* param:{ key string filter number } */ export function search(data) { return fetch({ method: "post", url: "SearchIndex", data }); } export function getActivePeerCount() { return fetch({ method: "post", url: "/peer/ActivePeerCount" }); }
import React from 'react'; import { Form, Row, Col, Input, Button, Select, Checkbox } from 'antd'; import { camelize } from '../../utils'; import './style.css'; const FormItem = Form.Item; const Option = Select.Option; const formItemDefaultLayout = { labelCol: { span: 2 }, wrapperCol: { span: 8 }, }; const DataEntitySelectFields = (placeholder, selectValues = []) => { return (<Select showSearch placeholder={placeholder} optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} > { selectValues.map((itm, i) => <Option key={i} value={itm}>{camelize(itm)}</Option>) } </Select>) } class DataEntitiesSearchForm extends React.PureComponent { getFields() { const { entityFields } = this.props; const { getFieldDecorator } = this.props.form; const children = entityFields.map((itm, i) => { const { fieldName, type, displayName, rules, onCustomRender, initialValue } = itm; const placeHolder = itm.placeHolder || fieldName; const layoutItem = { ...formItemDefaultLayout, wrapperCol: { span: itm.layoutColSpan || 8 } } let displayComp = null; let extraConfig = {} if (onCustomRender) displayComp = onCustomRender(itm); else { switch (type) { case 'text': displayComp = (<Input placeholder={`${placeHolder}...`} />); break; case 'select': displayComp = DataEntitySelectFields(placeHolder, itm.selectValues); break; case 'checkbox': extraConfig.valuePropName = "checked"; // checkbox using checked insted of value fields! displayComp = (<Checkbox />) break; default: throw new Error("DataEntitiesSearchForm. Unknown type " + type); break; } } return ( <FormItem key={i} label={`${displayName}`} {...layoutItem} > {getFieldDecorator(`${fieldName}`, { rules: rules || [], initialValue: initialValue, ...extraConfig })( displayComp )} </FormItem> ) }); return children; } _handleSearch = (e) => { const { onSearchHandler } = this.props; e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { console.log('Received values of form: ', values); onSearchHandler && onSearchHandler(values) } }); } __handleReset = (e) => { this.props.form.resetFields(); } render() { return ( <Form className="ant-advanced-search-form" onSubmit={this._handleSearch} layout="horizontal" > <Row gutter={24}>{this.getFields()}</Row> <Row> <Col span={24} style={{ textAlign: 'right' }}> <Button type="primary" htmlType="submit">Search</Button> <Button style={{ marginLeft: 8 }} onClick={this._handleReset}> Clear </Button> </Col> </Row> </Form> ); } } export default Form.create()(DataEntitiesSearchForm);;
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@syncfusion/ej2-base"),require("@syncfusion/ej2-popups"),require("@syncfusion/ej2-inputs"),require("@syncfusion/ej2-buttons"),require("@syncfusion/ej2-lists")):"function"==typeof define&&define.amd?define(["exports","@syncfusion/ej2-base","@syncfusion/ej2-popups","@syncfusion/ej2-inputs","@syncfusion/ej2-buttons","@syncfusion/ej2-lists"],t):t(e.ej={},e.ej2Base,e.ej2Popups,e.ej2Inputs,e.ej2Buttons,e.ej2Lists)}(this,function(e,t,i,s,a,n){"use strict";var r=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(t,i)};return function(t,i){function s(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(s.prototype=i.prototype,new s)}}(),l=function(e,t,i,s){var a,n=arguments.length,r=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,i,s);else for(var l=e.length-1;l>=0;l--)(a=e[l])&&(r=(n<3?a(r):n>3?a(t,i,r):a(t,i))||r);return n>3&&r&&Object.defineProperty(t,i,r),r},o="e-other-month",h="e-other-year",u="e-calendar",d="e-year",p="e-month",c="e-disabled",m="e-overlay",v="e-week-number",f="e-selected",y="e-focused-date",g="e-month-hide",b="e-zoomin",D="e-calendar-day-header-lg",E=function(e){function i(t,i){var s=e.call(this,t,i)||this;return s.effect="",s.isPopupClicked=!1,s.isDateSelected=!0,s.defaultKeyConfigs={controlUp:"ctrl+38",controlDown:"ctrl+40",moveDown:"downarrow",moveUp:"uparrow",moveLeft:"leftarrow",moveRight:"rightarrow",select:"enter",home:"home",end:"end",pageUp:"pageup",pageDown:"pagedown",shiftPageUp:"shift+pageup",shiftPageDown:"shift+pagedown",controlHome:"ctrl+home",controlEnd:"ctrl+end",altUpArrow:"alt+uparrow",spacebar:"space",altRightArrow:"alt+rightarrow",altLeftArrow:"alt+leftarrow"},s}return r(i,e),i.prototype.render=function(){this.rangeValidation(this.min,this.max),this.calendarEleCopy=this.element.cloneNode(!0),"Islamic"===this.calendarMode&&(+this.min.setSeconds(0)==+new Date(1900,0,1,0,0,0)&&(this.min=new Date(1944,2,18)),+this.max==+new Date(2099,11,31)&&(this.max=new Date(2069,10,16))),this.globalize=new t.Internationalization(this.locale),(t.isNullOrUndefined(this.firstDayOfWeek)||this.firstDayOfWeek>6||this.firstDayOfWeek<0)&&this.setProperties({firstDayOfWeek:this.globalize.getFirstDayOfWeek()},!0),this.todayDisabled=!1,this.todayDate=new Date((new Date).setHours(0,0,0,0)),"calendar"===this.getModuleName()?(this.element.classList.add(u),this.enableRtl&&this.element.classList.add("e-rtl"),t.Browser.isDevice&&this.element.classList.add("e-device"),t.attributes(this.element,{"data-role":"calendar"}),this.tabIndex=this.element.hasAttribute("tabindex")?this.element.getAttribute("tabindex"):"0",this.element.setAttribute("tabindex",this.tabIndex)):(this.calendarElement=this.createElement("div"),this.calendarElement.classList.add(u),this.enableRtl&&this.calendarElement.classList.add("e-rtl"),t.Browser.isDevice&&this.calendarElement.classList.add("e-device"),t.attributes(this.calendarElement,{role:"calendar"})),this.createHeader(),this.createContent(),this.wireEvents()},i.prototype.rangeValidation=function(e,i){t.isNullOrUndefined(e)&&this.setProperties({min:new Date(1900,0,1)},!0),t.isNullOrUndefined(i)&&this.setProperties({max:new Date(2099,11,31)},!0)},i.prototype.validateDate=function(e){this.setProperties({min:this.checkDateValue(new Date(this.checkValue(this.min)))},!0),this.setProperties({max:this.checkDateValue(new Date(this.checkValue(this.max)))},!0),this.currentDate=this.currentDate?this.currentDate:new Date((new Date).setHours(0,0,0,0)),!t.isNullOrUndefined(e)&&this.min<=this.max&&e>=this.min&&e<=this.max&&(this.currentDate=new Date(this.checkValue(e)))},i.prototype.setOverlayIndex=function(e,i,s,a){if(a&&!t.isNullOrUndefined(i)&&!t.isNullOrUndefined(s)&&!t.isNullOrUndefined(e)){var n=parseInt(i.style.zIndex,10)?parseInt(i.style.zIndex,10):1e3;s.style.zIndex=(n-1).toString(),e.style.zIndex=n.toString()}},i.prototype.minMaxUpdate=function(e){+this.min<=+this.max?t.removeClass([this.element],m):(this.setProperties({min:this.min},!0),t.addClass([this.element],m)),this.min=t.isNullOrUndefined(this.min)||!+this.min?this.min=new Date(1900,0,1):this.min,this.max=t.isNullOrUndefined(this.max)||!+this.max?this.max=new Date(2099,11,31):this.max,+this.min<=+this.max&&e&&+e<=+this.max&&+e>=+this.min?this.currentDate=new Date(this.checkValue(e)):+this.min<=+this.max&&!e&&+this.currentDate>+this.max?this.currentDate=new Date(this.checkValue(this.max)):+this.currentDate<+this.min&&(this.currentDate=new Date(this.checkValue(this.min)))},i.prototype.createHeader=function(){this.headerElement=this.createElement("div",{className:"e-header"});var e=this.createElement("div",{className:"e-icon-container"});this.previousIcon=this.createElement("button",{className:"e-prev",attrs:{type:"button"}}),t.rippleEffect(this.previousIcon,{duration:400,selector:".e-prev",isCenterRipple:!0}),t.attributes(this.previousIcon,{"aria-disabled":"false","aria-label":"previous month"}),this.nextIcon=this.createElement("button",{className:"e-next",attrs:{type:"button"}}),t.rippleEffect(this.nextIcon,{selector:".e-next",duration:400,isCenterRipple:!0}),t.attributes(this.nextIcon,{"aria-disabled":"false","aria-label":"next month"}),this.headerTitleElement=this.createElement("div",{className:"e-day e-title"}),t.attributes(this.headerTitleElement,{"aria-atomic":"true","aria-live":"assertive","aria-label":"title"}),this.headerElement.appendChild(this.headerTitleElement),this.previousIcon.appendChild(this.createElement("span",{className:"e-date-icon-prev e-icons"})),this.nextIcon.appendChild(this.createElement("span",{className:"e-date-icon-next e-icons"})),e.appendChild(this.previousIcon),e.appendChild(this.nextIcon),this.headerElement.appendChild(e),"calendar"===this.getModuleName()?this.element.appendChild(this.headerElement):this.calendarElement.appendChild(this.headerElement),this.adjustLongHeaderSize()},i.prototype.createContent=function(){this.contentElement=this.createElement("div",{className:"e-content"}),this.table=this.createElement("table",{attrs:{tabIndex:"0",role:"grid","aria-activedescendant":""}}),"calendar"===this.getModuleName()?this.element.appendChild(this.contentElement):this.calendarElement.appendChild(this.contentElement),this.contentElement.appendChild(this.table),this.createContentHeader(),this.createContentBody(),this.showTodayButton&&this.createContentFooter()},i.prototype.getCultureValues=function(){var e,i=[],s="days.stand-alone."+this.dayHeaderFormat.toLowerCase();e="en"===this.locale||"en-US"===this.locale?t.getValue(s,t.getDefaultDateObject()):this.getCultureObjects(t.cldrData,""+this.locale);for(var a=0,n=Object.keys(e);a<n.length;a++){var r=n[a];i.push(t.getValue(r,e))}return i},i.prototype.createContentHeader=function(){"calendar"===this.getModuleName()?t.isNullOrUndefined(this.element.querySelectorAll(".e-content .e-week-header")[0])||t.detach(this.element.querySelectorAll(".e-content .e-week-header")[0]):t.isNullOrUndefined(this.calendarElement.querySelectorAll(".e-content .e-week-header")[0])||t.detach(this.calendarElement.querySelectorAll(".e-content .e-week-header")[0]);var e,i="";(this.firstDayOfWeek>6||this.firstDayOfWeek<0)&&this.setProperties({firstDayOfWeek:0},!0),this.tableHeadElement=this.createElement("thead",{className:"e-week-header"}),this.weekNumber&&(i+='<th class="e-week-number"></th>',"calendar"===this.getModuleName()?t.addClass([this.element],""+v):t.addClass([this.calendarElement],""+v)),e=this.shiftArray(this.getCultureValues().length>0&&this.getCultureValues(),this.firstDayOfWeek);for(var s=0;s<=6;s++)i+='<th class="">'+e[s]+"</th>";i="<tr>"+i+"</tr>",this.tableHeadElement.innerHTML=i,this.table.appendChild(this.tableHeadElement)},i.prototype.createContentBody=function(){switch("calendar"===this.getModuleName()?t.isNullOrUndefined(this.element.querySelectorAll(".e-content tbody")[0])||t.detach(this.element.querySelectorAll(".e-content tbody")[0]):t.isNullOrUndefined(this.calendarElement.querySelectorAll(".e-content tbody")[0])||t.detach(this.calendarElement.querySelectorAll(".e-content tbody")[0]),this.start){case"Year":this.renderYears();break;case"Decade":this.renderDecades();break;default:this.renderMonths()}},i.prototype.updateFooter=function(){this.todayElement.textContent=this.l10.getConstant("today"),this.todayElement.setAttribute("aria-label",this.l10.getConstant("today"))},i.prototype.createContentFooter=function(){if(this.showTodayButton){var e=new Date(+this.min),i=new Date(+this.max);this.globalize=new t.Internationalization(this.locale),this.l10=new t.L10n(this.getModuleName(),{today:"Today"},this.locale),this.todayElement=this.createElement("button",{attrs:{role:"button"}}),t.rippleEffect(this.todayElement),this.updateFooter(),t.addClass([this.todayElement],["e-btn","e-today","e-flat","e-primary","e-css"]),+new Date(e.setHours(0,0,0,0))<=+this.todayDate&&+this.todayDate<=+new Date(i.setHours(0,0,0,0))&&!this.todayDisabled||t.addClass([this.todayElement],c),this.footer=this.createElement("div",{className:"e-footer-container"}),this.footer.appendChild(this.todayElement),"calendar"===this.getModuleName()&&this.element.appendChild(this.footer),"datepicker"===this.getModuleName()&&this.calendarElement.appendChild(this.footer),"datetimepicker"===this.getModuleName()&&this.calendarElement.appendChild(this.footer),this.todayElement.classList.contains(c)||t.EventHandler.add(this.todayElement,"click",this.todayButtonClick,this)}},i.prototype.wireEvents=function(){t.EventHandler.add(this.headerTitleElement,"click",this.navigateTitle,this),this.defaultKeyConfigs=t.extend(this.defaultKeyConfigs,this.keyConfigs),"calendar"===this.getModuleName()?this.keyboardModule=new t.KeyboardEvents(this.element,{eventName:"keydown",keyAction:this.keyActionHandle.bind(this),keyConfigs:this.defaultKeyConfigs}):this.keyboardModule=new t.KeyboardEvents(this.calendarElement,{eventName:"keydown",keyAction:this.keyActionHandle.bind(this),keyConfigs:this.defaultKeyConfigs})},i.prototype.todayButtonClick=function(e){this.showTodayButton&&(this.currentView()===this.depth?this.effect="":this.effect="e-zoomin",this.getViewNumber(this.start)>=this.getViewNumber(this.depth)?this.navigateTo(this.depth,new Date(this.checkValue(e))):this.navigateTo("Month",new Date(this.checkValue(e))))},i.prototype.keyActionHandle=function(e,i,s){var a,n=this.getViewNumber(this.currentView()),r=this.tableBodyElement.querySelector("tr td.e-focused-date");a=s?t.isNullOrUndefined(r)||+i!==parseInt(r.getAttribute("id").split("_")[0],10)?this.tableBodyElement.querySelector("tr td.e-selected"):r:this.tableBodyElement.querySelector("tr td.e-selected");var l=this.getViewNumber(this.depth),o=n===l&&this.getViewNumber(this.start)>=l;switch(this.effect="",e.action){case"moveLeft":this.KeyboardNavigate(-1,n,e,this.max,this.min),e.preventDefault();break;case"moveRight":this.KeyboardNavigate(1,n,e,this.max,this.min),e.preventDefault();break;case"moveUp":0===n?this.KeyboardNavigate(-7,n,e,this.max,this.min):this.KeyboardNavigate(-4,n,e,this.max,this.min),e.preventDefault();break;case"moveDown":0===n?this.KeyboardNavigate(7,n,e,this.max,this.min):this.KeyboardNavigate(4,n,e,this.max,this.min),e.preventDefault();break;case"select":if(e.target===this.todayElement)this.todayButtonClick(i);else{var h=t.isNullOrUndefined(r)?a:r;if(!t.isNullOrUndefined(h)&&!h.classList.contains(c))if(o){var u=new Date(parseInt(""+h.id,0));this.selectDate(e,u,h)}else this.contentClick(null,--n,h,i)}break;case"controlUp":this.title(),e.preventDefault();break;case"controlDown":t.isNullOrUndefined(r)&&(t.isNullOrUndefined(a)||o)||this.contentClick(null,--n,r||a,i),e.preventDefault();break;case"home":this.currentDate=this.firstDay(this.currentDate),t.detach(this.tableBodyElement),0===n?this.renderMonths(e):1===n?this.renderYears(e):this.renderDecades(e),e.preventDefault();break;case"end":this.currentDate=this.lastDay(this.currentDate,n),t.detach(this.tableBodyElement),0===n?this.renderMonths(e):1===n?this.renderYears(e):this.renderDecades(e),e.preventDefault();break;case"pageUp":this.addMonths(this.currentDate,-1),this.navigateTo("Month",this.currentDate),e.preventDefault();break;case"pageDown":this.addMonths(this.currentDate,1),this.navigateTo("Month",this.currentDate),e.preventDefault();break;case"shiftPageUp":this.addYears(this.currentDate,-1),this.navigateTo("Month",this.currentDate),e.preventDefault();break;case"shiftPageDown":this.addYears(this.currentDate,1),this.navigateTo("Month",this.currentDate),e.preventDefault();break;case"controlHome":this.navigateTo("Month",new Date(this.currentDate.getFullYear(),0,1)),e.preventDefault();break;case"controlEnd":this.navigateTo("Month",new Date(this.currentDate.getFullYear(),11,31)),e.preventDefault()}"calendar"===this.getModuleName()&&this.table.focus()},i.prototype.KeyboardNavigate=function(e,i,s,a,n){var r=new Date(this.checkValue(this.currentDate));switch(i){case 2:this.addYears(this.currentDate,e),this.isMonthYearRange(this.currentDate)?(t.detach(this.tableBodyElement),this.renderDecades(s)):this.currentDate=r;break;case 1:this.addMonths(this.currentDate,e),this.calendarMode,this.isMonthYearRange(this.currentDate)?(t.detach(this.tableBodyElement),this.renderYears(s)):this.currentDate=r;break;case 0:this.addDay(this.currentDate,e,s,a,n),this.isMinMaxRange(this.currentDate)?(t.detach(this.tableBodyElement),this.renderMonths(s)):this.currentDate=r}},i.prototype.preRender=function(e){var t=this;this.navigatePreviousHandler=this.navigatePrevious.bind(this),this.navigateNextHandler=this.navigateNext.bind(this),this.navigateHandler=function(e){t.triggerNavigate(e)}},i.prototype.minMaxDate=function(e){var t=new Date(new Date(+e).setHours(0,0,0,0)),i=new Date(new Date(+this.min).setHours(0,0,0,0)),s=new Date(new Date(+this.max).setHours(0,0,0,0));return+t!=+i&&+t!=+s||(+e<+this.min&&(e=new Date(+this.min)),+e>+this.max&&(e=new Date(+this.max))),e},i.prototype.renderMonths=function(e,t){var i,s=this.weekNumber?8:7;i="Gregorian"===this.calendarMode?this.renderDays(this.currentDate,e,t):this.islamicModule.islamicRenderDays(this.currentDate,t),this.createContentHeader(),"Gregorian"===this.calendarMode?this.renderTemplate(i,s,p,e,t):this.islamicModule.islamicRenderTemplate(i,s,p,e,t)},i.prototype.renderDays=function(e,i,s,a,n){var r,l=[],h=new Date(this.checkValue(e)),u=(this.weekNumber,h.getMonth());this.titleUpdate(e,"days");var d=h;for(h=new Date(d.getFullYear(),d.getMonth(),0,d.getHours(),d.getMinutes(),d.getSeconds(),d.getMilliseconds());h.getDay()!==this.firstDayOfWeek;)this.setStartDate(h,-864e5);for(var p=0;p<42;++p){var y=this.createElement("td",{className:"e-cell"}),g=this.createElement("span");p%7==0&&this.weekNumber&&(g.textContent=""+this.getWeek(h),y.appendChild(g),t.addClass([y],""+v),l.push(y)),r=new Date(+h),h=this.minMaxDate(h);var b={type:"dateTime",skeleton:"full"},D=this.globalize.parseDate(this.globalize.formatDate(h,b),b),E=this.dayCell(h),C=this.globalize.formatDate(h,{type:"date",skeleton:"full"}),w=this.createElement("span");w.textContent=this.globalize.formatDate(h,{format:"d",type:"date",skeleton:"yMd"});var V=this.min>h||this.max<h;V?(t.addClass([E],c),t.addClass([E],m)):w.setAttribute("title",""+C),u!==h.getMonth()&&t.addClass([E],o),0!==h.getDay()&&6!==h.getDay()||t.addClass([E],"e-weekend"),E.appendChild(w),this.renderDayCellArgs={date:h,isDisabled:!1,element:E,isOutOfRange:V};var k=this.renderDayCellArgs;if(this.renderDayCellEvent(k),k.isDisabled)if(a){if(!t.isNullOrUndefined(n)&&n.length>0)for(var O=0;O<n.length;O++){+new Date(this.globalize.formatDate(k.date,{type:"date",skeleton:"yMd"}))===+new Date(this.globalize.formatDate(n[O],{type:"date",skeleton:"yMd"}))&&(n.splice(O,1),O=-1)}}else s&&+s==+k.date&&this.setProperties({value:null},!0);this.renderDayCellArgs.isDisabled&&!E.classList.contains(f)&&(t.addClass([E],c),t.addClass([E],m),+this.renderDayCellArgs.date==+this.todayDate&&(this.todayDisabled=!0));var N=E.classList.contains(o),M=E.classList.contains(c);if(M||t.EventHandler.add(E,"click",this.clickHandler,this),!a||t.isNullOrUndefined(n)||N||M)N||M||!this.getDateVal(h,s)?this.updateFocus(N,M,h,E,e):t.addClass([E],f);else{for(var I=0;I<n.length;I++){var x={type:"date",skeleton:"short",calendar:"Gregorian"===this.calendarMode?"gregorian":"islamic"};this.globalize.formatDate(h,x)===this.globalize.formatDate(n[I],x)&&this.getDateVal(h,n[I])||this.getDateVal(h,s)?t.addClass([E],f):this.updateFocus(N,M,h,E,e)}n.length<=0&&this.updateFocus(N,M,h,E,e)}D.getMonth()===(new Date).getMonth()&&D.getDate()===(new Date).getDate()&&D.getFullYear()===(new Date).getFullYear()&&t.addClass([E],"e-today"),l.push(this.renderDayCellArgs.element),h=new Date(+r),this.addDay(h,1,null,this.max,this.min)}return l},i.prototype.updateFocus=function(e,i,s,a,n){n.getDate()!==s.getDate()||e||i?(n>=this.max&&parseInt(a.id,0)===+this.max&&!e&&!i&&t.addClass([a],y),n<=this.min&&parseInt(a.id,0)===+this.min&&!e&&!i&&t.addClass([a],y)):t.addClass([a],y)},i.prototype.renderYears=function(e,i){this.removeTableHeadElement();var s=[],a=t.isNullOrUndefined(i),n=new Date(this.checkValue(this.currentDate)),r=n.getMonth(),l=n.getFullYear(),o=n,h=o.getFullYear(),u=new Date(this.checkValue(this.min)).getFullYear(),p=new Date(this.checkValue(this.min)).getMonth(),m=new Date(this.checkValue(this.max)).getFullYear(),v=new Date(this.checkValue(this.max)).getMonth();o.setMonth(0),this.titleUpdate(this.currentDate,"months");this.min>o||this.max;o.setDate(1);for(var g=0;g<12;++g){var b=this.dayCell(o),D=this.createElement("span"),E=i&&i.getMonth()===o.getMonth(),C=i&&i.getFullYear()===l&&E;D.textContent=this.globalize.formatDate(o,{type:"dateTime",skeleton:"MMM"}),this.min&&(h<u||g<p&&h===u)||this.max&&(h>m||g>v&&h>=m)?t.addClass([b],c):!a&&C?t.addClass([b],f):o.getMonth()===r&&this.currentDate.getMonth()===r&&t.addClass([b],y),o.setDate(1),o.setMonth(o.getMonth()+1),b.classList.contains(c)||t.EventHandler.add(b,"click",this.clickHandler,this),b.appendChild(D),s.push(b)}this.renderTemplate(s,4,d,e,i)},i.prototype.renderDecades=function(e,i){this.removeTableHeadElement();var s=[],a=new Date(this.checkValue(this.currentDate));a.setMonth(0),a.setDate(1);var n=a.getFullYear(),r=new Date(a.setFullYear(n-n%10)),l=new Date(a.setFullYear(n-n%10+9)),o=r.getFullYear(),u=l.getFullYear(),d=this.globalize.formatDate(r,{type:"dateTime",skeleton:"y"}),p=this.globalize.formatDate(l,{type:"dateTime",skeleton:"y"});this.headerTitleElement.textContent=d+" - "+p;for(var m=new Date(n-n%10-1,0,1).getFullYear(),v=0;v<12;++v){var g=m+v;a.setFullYear(g);var b=this.dayCell(a);t.attributes(b,{role:"gridcell"});var D=this.createElement("span");D.textContent=this.globalize.formatDate(a,{type:"dateTime",skeleton:"y"}),g<o||g>u?(t.addClass([b],h),(g<new Date(this.checkValue(this.min)).getFullYear()||g>new Date(this.checkValue(this.max)).getFullYear())&&t.addClass([b],c)):g<new Date(this.checkValue(this.min)).getFullYear()||g>new Date(this.checkValue(this.max)).getFullYear()?t.addClass([b],c):t.isNullOrUndefined(i)||a.getFullYear()!==i.getFullYear()?a.getFullYear()!==this.currentDate.getFullYear()||b.classList.contains(c)||t.addClass([b],y):t.addClass([b],f),b.classList.contains(c)||t.EventHandler.add(b,"click",this.clickHandler,this),b.appendChild(D),s.push(b)}this.renderTemplate(s,4,"e-decade",e,i)},i.prototype.dayCell=function(e){var i={skeleton:"full",type:"dateTime",calendar:"Gregorian"===this.calendarMode?"gregorian":"islamic"},s=this.globalize.parseDate(this.globalize.formatDate(e,i),i).valueOf(),a={className:"e-cell",attrs:{id:""+t.getUniqueID(""+s),"aria-selected":"false",role:"gridcell"}};return this.createElement("td",a)},i.prototype.firstDay=function(e){var t="Decade"!==this.currentView()?this.tableBodyElement.querySelectorAll("td:not(."+o):this.tableBodyElement.querySelectorAll("td:not(."+h);if(t.length)for(var i=0;i<t.length;i++)if(!t[i].classList.contains(c)){e=new Date(parseInt(t[i].id,0));break}return e},i.prototype.lastDay=function(e,t){var i=new Date(e.getFullYear(),e.getMonth()+1,0);if(2!==t){var s=Math.abs(i.getTimezoneOffset()-this.firstDay(e).getTimezoneOffset());return s&&i.setHours(this.firstDay(e).getHours()+s/60),this.findLastDay(i)}return this.findLastDay(this.firstDay(i))},i.prototype.checkDateValue=function(e){return!t.isNullOrUndefined(e)&&e instanceof Date&&!isNaN(+e)?e:null},i.prototype.findLastDay=function(e){var t="Decade"===this.currentView()?this.tableBodyElement.querySelectorAll("td:not(."+h):this.tableBodyElement.querySelectorAll("td:not(."+o);if(t.length)for(var i=t.length-1;i>=0;i--)if(!t[i].classList.contains(c)){e=new Date(parseInt(t[i].id,0));break}return e},i.prototype.removeTableHeadElement=function(){"calendar"===this.getModuleName()?t.isNullOrUndefined(this.element.querySelectorAll(".e-content table thead")[0])||t.detach(this.tableHeadElement):t.isNullOrUndefined(this.calendarElement.querySelectorAll(".e-content table thead")[0])||t.detach(this.tableHeadElement)},i.prototype.renderTemplate=function(e,i,s,a,n){var r,l=this.getViewNumber(this.currentView());this.tableBodyElement=this.createElement("tbody"),this.table.appendChild(this.tableBodyElement),t.removeClass([this.contentElement,this.headerElement],[p,"e-decade",d]),t.addClass([this.contentElement,this.headerElement],[s]);for(var h=i,u=0,c=0;c<e.length/i;++c){for(r=this.createElement("tr",{attrs:{role:"row"}}),u=0+u;u<h;u++)e[u].classList.contains("e-week-number")||t.isNullOrUndefined(e[u].children[0])||(t.addClass([e[u].children[0]],["e-day"]),t.rippleEffect(e[u].children[0],{duration:600,isCenterRipple:!0})),r.appendChild(e[u]),this.weekNumber&&7===u&&e[7].classList.contains(o)&&t.addClass([r],g),!this.weekNumber&&6===u&&e[6].classList.contains(o)&&t.addClass([r],g),this.weekNumber?41===u&&e[41].classList.contains(o)&&t.addClass([r],g):35===u&&e[35].classList.contains(o)&&t.addClass([r],g);h+=i,u+=0,this.tableBodyElement.appendChild(r)}this.table.querySelector("tbody").className=this.effect,"Gregorian"===this.calendarMode?this.iconHandler():this.islamicModule.islamicIconHandler(),(l!==this.getViewNumber(this.currentView())||0===l&&l!==this.getViewNumber(this.currentView()))&&this.navigateHandler(a),this.setAriaActiveDescendant()},i.prototype.clickHandler=function(e,t){this.clickEventEmitter(e);var i=e.currentTarget,s=this.getViewNumber(this.currentView());i.classList.contains(o)?this.contentClick(e,0,null,t):s===this.getViewNumber(this.depth)&&this.getViewNumber(this.start)>=this.getViewNumber(this.depth)?this.contentClick(e,1,null,t):2===s?this.contentClick(e,1,null,t):i.classList.contains(o)||0!==s?this.contentClick(e,0,i,t):this.selectDate(e,this.getIdValue(e,null),null),"calendar"===this.getModuleName()&&this.table.focus()},i.prototype.clickEventEmitter=function(e){e.preventDefault()},i.prototype.contentClick=function(e,i,s,a){var n=this.getViewNumber(this.currentView()),r=this.getIdValue(e,s);switch(i){case 0:n===this.getViewNumber(this.depth)&&this.getViewNumber(this.start)>=this.getViewNumber(this.depth)?(t.detach(this.tableBodyElement),this.currentDate=r,this.effect=b,this.renderMonths(e)):("Gregorian"===this.calendarMode?(this.currentDate.setMonth(r.getMonth()),r.getMonth()>0&&this.currentDate.getMonth()!==r.getMonth()&&this.currentDate.setDate(0),this.currentDate.setFullYear(r.getFullYear())):this.currentDate=r,this.effect=b,t.detach(this.tableBodyElement),this.renderMonths(e));break;case 1:if(n===this.getViewNumber(this.depth)&&this.getViewNumber(this.start)>=this.getViewNumber(this.depth))this.selectDate(e,r,null);else{if("Gregorian"===this.calendarMode)this.currentDate.setFullYear(r.getFullYear());else{var l=this.islamicModule.getIslamicDate(r);this.currentDate=this.islamicModule.toGregorian(l.year,l.month,1)}this.effect=b,t.detach(this.tableBodyElement),this.renderYears(e)}}},i.prototype.switchView=function(e,i,s){switch(e){case 0:t.detach(this.tableBodyElement),this.renderMonths(i),s&&!t.isNullOrUndefined(this.tableBodyElement.querySelectorAll("."+y)[0])&&this.tableBodyElement.querySelectorAll("."+y)[0].classList.remove(y);break;case 1:t.detach(this.tableBodyElement),this.renderYears(i);break;case 2:t.detach(this.tableBodyElement),this.renderDecades(i)}},i.prototype.getModuleName=function(){return"calendar"},i.prototype.requiredModules=function(){var e=[];return this&&e.push({args:[this],member:"islamic"}),e},i.prototype.getPersistData=function(){return this.addOnPersist(["value"])},i.prototype.onPropertyChanged=function(e,i,s,a){this.effect="";for(var n=0,r=Object.keys(e);n<r.length;n++){var l=r[n];switch(l){case"enableRtl":e.enableRtl?"calendar"===this.getModuleName()?this.element.classList.add("e-rtl"):this.calendarElement.classList.add("e-rtl"):"calendar"===this.getModuleName()?this.element.classList.remove("e-rtl"):this.calendarElement.classList.remove("e-rtl");break;case"dayHeaderFormat":this.getCultureValues(),this.createContentHeader(),this.adjustLongHeaderSize();break;case"min":case"max":this.rangeValidation(this.min,this.max),"min"===l?this.setProperties({min:this.checkDateValue(new Date(this.checkValue(e.min)))},!0):this.setProperties({max:this.checkDateValue(new Date(this.checkValue(e.max)))},!0),this.setProperties({start:this.currentView()},!0),t.detach(this.tableBodyElement),this.minMaxUpdate(),s&&this.validateValues(s,a),this.createContentBody(),(this.todayDate<this.min||this.max<this.todayDate)&&this.footer&&this.todayElement?(t.detach(this.todayElement),t.detach(this.footer),this.todayElement=this.footer=null,this.createContentFooter()):this.footer&&this.todayElement&&this.todayElement.classList.contains("e-disabled")&&(t.removeClass([this.todayElement],c),t.detach(this.todayElement),t.detach(this.footer),this.todayElement=this.footer=null,this.createContentFooter());break;case"start":case"depth":case"weekNumber":case"firstDayOfWeek":this.checkView(),this.createContentHeader(),this.createContentBody();break;case"locale":this.globalize=new t.Internationalization(this.locale),this.createContentHeader(),this.createContentBody(),this.l10.setLocale(this.locale),this.updateFooter();break;case"showTodayButton":e.showTodayButton?this.createContentFooter():t.isNullOrUndefined(this.todayElement)||t.isNullOrUndefined(this.footer)||(t.detach(this.todayElement),t.detach(this.footer),this.todayElement=this.footer=void 0),this.setProperties({showTodayButton:e.showTodayButton},!0)}}},i.prototype.validateValues=function(e,i){if(e&&!t.isNullOrUndefined(i)&&i.length>0){for(var s=this.copyValues(i),a=0;a<s.length;a++){var n=s[a],r="Gregorian"===this.calendarMode?"gregorian":"islamic",l=void 0;l="Gregorian"===this.calendarMode?this.globalize.formatDate(n,{type:"date",skeleton:"yMd"}):this.globalize.formatDate(n,{type:"dateTime",skeleton:"full",calendar:"islamic"});var o={type:"date",skeleton:"yMd",calendar:r},h=this.globalize.formatDate(this.min,o),u={type:"date",skeleton:"yMd",calendar:r},d=this.globalize.formatDate(this.max,u);(+new Date(l)<+new Date(h)||+new Date(l)>+new Date(d))&&(s.splice(a,1),a=-1)}this.setProperties({values:s},!0)}},i.prototype.setValueUpdate=function(){t.isNullOrUndefined(this.tableBodyElement)||(t.detach(this.tableBodyElement),this.setProperties({start:this.currentView()},!0),this.createContentBody())},i.prototype.copyValues=function(e){var i=[];if(!t.isNullOrUndefined(e)&&e.length>0)for(var s=0;s<e.length;s++)i.push(new Date(+e[s]));return i},i.prototype.titleUpdate=function(e,i){var s,a,n=new t.Internationalization(this.locale),r="Gregorian"===this.calendarMode?"gregorian":"islamic";switch("Gregorian"===this.calendarMode?(s=n.formatDate(e,{type:"dateTime",skeleton:"yMMMM",calendar:r}),a=n.formatDate(e,{type:"dateTime",skeleton:"y",calendar:r})):(s=n.formatDate(e,{type:"dateTime",format:"MMMM y",calendar:r}),a=n.formatDate(e,{type:"dateTime",format:"y",calendar:r})),i){case"days":this.headerTitleElement.textContent=s;break;case"months":this.headerTitleElement.textContent=a}},i.prototype.setActiveDescendant=function(){var e,i,s=this.tableBodyElement.querySelector("tr td.e-focused-date"),a=this.tableBodyElement.querySelector("tr td.e-selected"),n="Gregorian"===this.calendarMode?"gregorian":"islamic",r=this.currentView();return i="Month"===r?this.globalize.formatDate(this.currentDate,{type:"date",skeleton:"full",calendar:n}):"Year"===r?"islamic"!==n?this.globalize.formatDate(this.currentDate,{type:"date",skeleton:"yMMMM",calendar:n}):this.globalize.formatDate(this.currentDate,{type:"date",skeleton:"GyMMM",calendar:n}):this.globalize.formatDate(this.currentDate,{type:"date",skeleton:"y",calendar:n}),(a||s)&&(t.isNullOrUndefined(a)||a.setAttribute("aria-selected","true"),(s||a).setAttribute("aria-label",i),e=(s||a).getAttribute("id")),e},i.prototype.iconHandler=function(){switch(new Date(this.checkValue(this.currentDate)).setDate(1),this.currentView()){case"Month":this.previousIconHandler(this.compareMonth(new Date(this.checkValue(this.currentDate)),this.min)<1),this.nextIconHandler(this.compareMonth(new Date(this.checkValue(this.currentDate)),this.max)>-1);break;case"Year":this.previousIconHandler(this.compareYear(new Date(this.checkValue(this.currentDate)),this.min)<1),this.nextIconHandler(this.compareYear(new Date(this.checkValue(this.currentDate)),this.max)>-1);break;case"Decade":this.previousIconHandler(this.compareDecade(new Date(this.checkValue(this.currentDate)),this.min)<1),this.nextIconHandler(this.compareDecade(new Date(this.checkValue(this.currentDate)),this.max)>-1)}},i.prototype.destroy=function(){"calendar"===this.getModuleName()?t.removeClass([this.element],[u]):this.calendarElement&&t.removeClass([this.element],[u]),"calendar"===this.getModuleName()&&(t.EventHandler.remove(this.headerTitleElement,"click",this.navigateTitle),this.todayElement&&t.EventHandler.remove(this.todayElement,"click",this.todayButtonClick),this.previousIconHandler(!0),this.nextIconHandler(!0),this.keyboardModule.destroy(),this.element.removeAttribute("data-role"),t.isNullOrUndefined(this.calendarEleCopy.getAttribute("tabindex"))?this.element.removeAttribute("tabindex"):this.element.setAttribute("tabindex",this.tabIndex)),this.element.innerHTML="",e.prototype.destroy.call(this)},i.prototype.title=function(e){var t=this.getViewNumber(this.currentView());this.effect=b,this.switchView(++t,e)},i.prototype.getViewNumber=function(e){return"Month"===e?0:"Year"===e?1:2},i.prototype.navigateTitle=function(e){e.preventDefault(),this.title(e),"calendar"===this.getModuleName()&&this.table.focus()},i.prototype.previous=function(){this.effect="";var e=this.getViewNumber(this.currentView());switch(this.currentView()){case"Month":this.addMonths(this.currentDate,-1),this.switchView(e);break;case"Year":this.addYears(this.currentDate,-1),this.switchView(e);break;case"Decade":this.addYears(this.currentDate,-10),this.switchView(e)}},i.prototype.navigatePrevious=function(e){e.preventDefault(),"Gregorian"===this.calendarMode?this.previous():this.islamicModule.islamicPrevious(),this.triggerNavigate(e),"calendar"===this.getModuleName()&&this.table.focus()},i.prototype.next=function(){this.effect="";var e=this.getViewNumber(this.currentView());switch(this.currentView()){case"Month":this.addMonths(this.currentDate,1),this.switchView(e);break;case"Year":this.addYears(this.currentDate,1),this.switchView(e);break;case"Decade":this.addYears(this.currentDate,10),this.switchView(e)}},i.prototype.navigateNext=function(e){e.preventDefault(),"Gregorian"===this.calendarMode?this.next():this.islamicModule.islamicNext(),this.triggerNavigate(e),"calendar"===this.getModuleName()&&this.table.focus()},i.prototype.navigateTo=function(e,t){+t>=+this.min&&+t<=+this.max&&(this.currentDate=t),+t<=+this.min&&(this.currentDate=new Date(this.checkValue(this.min))),+t>=+this.max&&(this.currentDate=new Date(this.checkValue(this.max))),this.getViewNumber(this.depth)>=this.getViewNumber(e)&&(this.getViewNumber(this.depth)<=this.getViewNumber(this.start)||this.getViewNumber(this.depth)===this.getViewNumber(e))&&(e=this.depth),this.switchView(this.getViewNumber(e))},i.prototype.currentView=function(){return this.contentElement.classList.contains(d)?"Year":this.contentElement.classList.contains("e-decade")?"Decade":"Month"},i.prototype.getDateVal=function(e,i){return!t.isNullOrUndefined(i)&&e.getDate()===i.getDate()&&e.getMonth()===i.getMonth()&&e.getFullYear()===i.getFullYear()},i.prototype.getCultureObjects=function(e,i){var s=".dates.calendars.gregorian.days.format."+this.dayHeaderFormat.toLowerCase(),a=".dates.calendars.islamic.days.format."+this.dayHeaderFormat.toLowerCase();return"Gregorian"===this.calendarMode?t.getValue("main."+this.locale+s,e):t.getValue("main."+this.locale+a,e)},i.prototype.getWeek=function(e){var t=new Date(this.checkValue(e)).valueOf(),i=new Date(e.getFullYear(),0,1).valueOf(),s=t-i;return Math.ceil((s/864e5+new Date(i).getDay()+1)/7)},i.prototype.setStartDate=function(e,t){var i=e.getTimezoneOffset(),s=new Date(e.getTime()+t),a=s.getTimezoneOffset()-i;e.setTime(s.getTime()+6e4*a)},i.prototype.addMonths=function(e,t){if("Gregorian"===this.calendarMode){var i=e.getDate();e.setDate(1),e.setMonth(e.getMonth()+t),e.setDate(Math.min(i,this.getMaxDays(e)))}else{var s=this.islamicModule.getIslamicDate(e);this.currentDate=this.islamicModule.toGregorian(s.year,s.month+t,1)}},i.prototype.addYears=function(e,t){if("Gregorian"===this.calendarMode){var i=e.getDate();e.setDate(1),e.setFullYear(e.getFullYear()+t),e.setDate(Math.min(i,this.getMaxDays(e)))}else{var s=this.islamicModule.getIslamicDate(e);this.currentDate=this.islamicModule.toGregorian(s.year+t,s.month,1)}},i.prototype.getIdValue=function(e,t){var i;i=e?e.currentTarget:t;var s={type:"dateTime",skeleton:"full",calendar:"Gregorian"===this.calendarMode?"gregorian":"islamic"},a=this.globalize.formatDate(new Date(parseInt(""+i.getAttribute("id"),0)),s),n=this.globalize.parseDate(a,s),r=n.valueOf()-n.valueOf()%1e3;return new Date(r)},i.prototype.adjustLongHeaderSize=function(){t.removeClass([this.element],D),"Wide"===this.dayHeaderFormat&&t.addClass(["calendar"===this.getModuleName()?this.element:this.calendarElement],D)},i.prototype.selectDate=function(e,i,s,a,n){var r=s||e.currentTarget;if(this.isDateSelected=!1,"Decade"===this.currentView())this.setDateDecade(this.currentDate,i.getFullYear());else if("Year"===this.currentView())this.setDateYear(this.currentDate,i);else{if(a&&!this.checkPresentDate(i,n)){var l=this.copyValues(n);!t.isNullOrUndefined(n)&&l.length>0?(l.push(new Date(this.checkValue(i))),this.setProperties({values:l},!0),this.setProperties({value:n[n.length-1]},!0)):this.setProperties({values:[new Date(this.checkValue(i))]},!0)}else this.setProperties({value:new Date(this.checkValue(i))},!0);this.currentDate=new Date(this.checkValue(i))}var o=t.closest(r,"."+u);if(t.isNullOrUndefined(o)&&(o=this.tableBodyElement),a||t.isNullOrUndefined(o.querySelector("."+f))||t.removeClass([o.querySelector("."+f)],f),a||t.isNullOrUndefined(o.querySelector("."+y))||t.removeClass([o.querySelector("."+y)],y),a){l=this.copyValues(n);for(var h=Array.prototype.slice.call(this.tableBodyElement.querySelectorAll("td")),d=0;d<h.length;d++){var p=o.querySelectorAll("td."+y)[0],c=o.querySelectorAll("td."+f)[0];h[d]===p&&t.removeClass([h[d]],y),h[d]!==c||this.checkPresentDate(new Date(parseInt(c.getAttribute("id").split("_")[0],10)),n)||t.removeClass([h[d]],f)}if(r.classList.contains(f)){t.removeClass([r],f);for(var m=0;m<l.length;m++){var v={type:"date",skeleton:"short",calendar:"Gregorian"===this.calendarMode?"gregorian":"islamic"};if(this.globalize.formatDate(i,v)===this.globalize.formatDate(l[m],v)){d=l.indexOf(l[m]);l.splice(d,1),t.addClass([r],y)}}this.setProperties({values:l},!0)}else t.addClass([r],f)}else t.addClass([r],f);this.isDateSelected=!0},i.prototype.checkPresentDate=function(e,i){var s=!1;if(!t.isNullOrUndefined(i))for(var a=0;a<i.length;a++){var n="Gregorian"===this.calendarMode?"gregorian":"islamic";this.globalize.formatDate(e,{type:"date",skeleton:"short",calendar:n})===this.globalize.formatDate(i[a],{type:"date",skeleton:"short",calendar:n})&&(s=!0)}return s},i.prototype.setAriaActiveDescendant=function(){t.attributes(this.table,{"aria-activedescendant":""+this.setActiveDescendant()})},i.prototype.previousIconHandler=function(e){e?(t.EventHandler.remove(this.previousIcon,"click",this.navigatePreviousHandler),t.addClass([this.previousIcon],""+c),t.addClass([this.previousIcon],""+m),this.previousIcon.setAttribute("aria-disabled","true")):(t.EventHandler.add(this.previousIcon,"click",this.navigatePreviousHandler),t.removeClass([this.previousIcon],""+c),t.removeClass([this.previousIcon],""+m),this.previousIcon.setAttribute("aria-disabled","false"))},i.prototype.renderDayCellEvent=function(e){t.extend(this.renderDayCellArgs,{name:"renderDayCell"}),this.trigger("renderDayCell",e)},i.prototype.navigatedEvent=function(e){t.extend(this.navigatedArgs,{name:"navigated",event:e}),this.trigger("navigated",this.navigatedArgs)},i.prototype.triggerNavigate=function(e){this.navigatedArgs={view:this.currentView(),date:this.currentDate},this.navigatedEvent(e)},i.prototype.nextIconHandler=function(e){e?(t.EventHandler.remove(this.nextIcon,"click",this.navigateNextHandler),t.addClass([this.nextIcon],c),t.addClass([this.nextIcon],m),this.nextIcon.setAttribute("aria-disabled","true")):(t.EventHandler.add(this.nextIcon,"click",this.navigateNextHandler),t.removeClass([this.nextIcon],c),t.removeClass([this.nextIcon],m),this.nextIcon.setAttribute("aria-disabled","false"))},i.prototype.compare=function(e,t,i){var s,a,n=t.getFullYear();return s=n,a=0,i&&(s=(n-=n%i)-n%i+i-1),e.getFullYear()>s?a=1:e.getFullYear()<n&&(a=-1),a},i.prototype.isMinMaxRange=function(e){return+e>=+this.min&&+e<=+this.max},i.prototype.isMonthYearRange=function(e){if("Gregorian"===this.calendarMode)return e.getMonth()>=this.min.getMonth()&&e.getFullYear()>=this.min.getFullYear()&&e.getMonth()<=this.max.getMonth()&&e.getFullYear()<=this.max.getFullYear();var t=this.islamicModule.getIslamicDate(e);return t.month>=this.islamicModule.getIslamicDate(new Date(1944,1,18)).month&&t.year>=this.islamicModule.getIslamicDate(new Date(1944,1,18)).year&&t.month<=this.islamicModule.getIslamicDate(new Date(2069,1,16)).month&&t.year<=this.islamicModule.getIslamicDate(new Date(2069,1,16)).year},i.prototype.compareYear=function(e,t){return this.compare(e,t,0)},i.prototype.compareDecade=function(e,t){return this.compare(e,t,10)},i.prototype.shiftArray=function(e,t){return e.slice(t).concat(e.slice(0,t))},i.prototype.addDay=function(e,i,s,a,n){var r=i,l=new Date(+e);if(!t.isNullOrUndefined(this.tableBodyElement)&&!t.isNullOrUndefined(s)){for(;this.findNextTD(new Date(+e),r,a,n);)r+=i;var o=new Date(l.setDate(l.getDate()+r));r=+o>+a||+o<+n?r===i?i-i:i:r}e.setDate(e.getDate()+r)},i.prototype.findNextTD=function(e,i,s,a){var n=new Date(e.setDate(e.getDate()+i)),r=[],l=!1;if((!t.isNullOrUndefined(n)&&n.getMonth())===(!t.isNullOrUndefined(this.currentDate)&&this.currentDate.getMonth())){r=("Gregorian"===this.calendarMode?this.renderDays(n,null):this.islamicModule.islamicRenderDays(this.currentDate,n)).filter(function(e){return e.classList.contains(c)})}else r=this.tableBodyElement.querySelectorAll("td."+c);if(+n<=+s&&+n>=+a&&r.length)for(var o=0;o<r.length&&!(l=+n==+new Date(parseInt(r[o].id,0)));o++);return l},i.prototype.getMaxDays=function(e){var t,i,s=new Date(this.checkValue(e));for(t=28,i=s.getMonth();s.getMonth()===i;)++t,s.setDate(t);return t-1},i.prototype.setDateDecade=function(e,t){e.setFullYear(t),this.setProperties({value:new Date(this.checkValue(e))},!0)},i.prototype.setDateYear=function(e,t){e.setFullYear(t.getFullYear(),t.getMonth(),e.getDate()),t.getMonth()!==e.getMonth()&&e.setDate(0),this.setProperties({value:new Date(this.checkValue(e))},!0),this.currentDate=new Date(this.checkValue(t))},i.prototype.compareMonth=function(e,t){return e.getFullYear()>t.getFullYear()?1:e.getFullYear()<t.getFullYear()?-1:e.getMonth()===t.getMonth()?0:e.getMonth()>t.getMonth()?1:-1},i.prototype.checkValue=function(e){return e instanceof Date?e.toUTCString():""+e},i.prototype.checkView=function(){"Decade"!==this.start&&"Year"!==this.start&&this.setProperties({start:"Month"},!0),"Decade"!==this.depth&&"Year"!==this.depth&&this.setProperties({depth:"Month"},!0),this.getViewNumber(this.depth)>this.getViewNumber(this.start)&&this.setProperties({depth:"Month"},!0)},l([t.Property(new Date(1900,0,1))],i.prototype,"min",void 0),l([t.Property(new Date(2099,11,31))],i.prototype,"max",void 0),l([t.Property(null)],i.prototype,"firstDayOfWeek",void 0),l([t.Property("Gregorian")],i.prototype,"calendarMode",void 0),l([t.Property("Month")],i.prototype,"start",void 0),l([t.Property("Month")],i.prototype,"depth",void 0),l([t.Property(!1)],i.prototype,"weekNumber",void 0),l([t.Property(!0)],i.prototype,"showTodayButton",void 0),l([t.Property("Short")],i.prototype,"dayHeaderFormat",void 0),l([t.Property(!1)],i.prototype,"enablePersistence",void 0),l([t.Property(null)],i.prototype,"keyConfigs",void 0),l([t.Event()],i.prototype,"created",void 0),l([t.Event()],i.prototype,"destroyed",void 0),l([t.Event()],i.prototype,"navigated",void 0),l([t.Event()],i.prototype,"renderDayCell",void 0),i=l([t.NotifyPropertyChanges],i)}(t.Component),C=function(e){function i(t,i){return e.call(this,t,i)||this}return r(i,e),i.prototype.render=function(){if("Islamic"===this.calendarMode&&void 0===this.islamicModule&&t.throwError("Requires the injectable Islamic modules to render Calendar in Islamic mode"),this.isMultiSelection&&"object"==typeof this.values&&!t.isNullOrUndefined(this.values)&&this.values.length>0){for(var i=[],s=[],a=0;a<this.values.length;a++)-1===i.indexOf(+this.values[a])&&(i.push(+this.values[a]),s.push(this.values[a]));this.setProperties({values:s},!0);for(var n=0;n<this.values.length;n++)if(!this.checkDateValue(this.values[n]))if("string"==typeof this.values[n]&&this.checkDateValue(new Date(this.checkValue(this.values[n])))){var r=new Date(this.checkValue(this.values[n]));this.values.splice(n,1),this.values.splice(n,0,r)}else this.values.splice(n,1);this.setProperties({value:this.values[this.values.length-1]},!0),this.previousValues=this.values.length}if(this.validateDate(),this.minMaxUpdate(),e.prototype.render.call(this),"calendar"===this.getModuleName()){var l=t.closest(this.element,"form");l&&t.EventHandler.add(l,"reset",this.formResetHandler.bind(this))}this.renderComplete()},i.prototype.formResetHandler=function(){this.setProperties({value:null},!0)},i.prototype.validateDate=function(){"string"==typeof this.value&&this.setProperties({value:this.checkDateValue(new Date(this.checkValue(this.value)))},!0),e.prototype.validateDate.call(this,this.value),!t.isNullOrUndefined(this.value)&&this.min<=this.max&&this.value>=this.min&&this.value<=this.max&&(this.currentDate=new Date(this.checkValue(this.value))),isNaN(+this.value)&&this.setProperties({value:null},!0)},i.prototype.minMaxUpdate=function(){"calendar"===this.getModuleName()&&(!t.isNullOrUndefined(this.value)&&this.value<=this.min&&this.min<=this.max?(this.setProperties({value:this.min},!0),this.changedArgs={value:this.value}):!t.isNullOrUndefined(this.value)&&this.value>=this.max&&this.min<=this.max&&(this.setProperties({value:this.max},!0),this.changedArgs={value:this.value})),"calendar"===this.getModuleName()||t.isNullOrUndefined(this.value)?e.prototype.minMaxUpdate.call(this,this.value):!t.isNullOrUndefined(this.value)&&this.value<this.min&&this.min<=this.max?e.prototype.minMaxUpdate.call(this,this.min):!t.isNullOrUndefined(this.value)&&this.value>this.max&&this.min<=this.max&&e.prototype.minMaxUpdate.call(this,this.max)},i.prototype.generateTodayVal=function(e){var t=new Date;return e?(t.setHours(e.getHours()),t.setMinutes(e.getMinutes()),t.setSeconds(e.getSeconds()),t.setMilliseconds(e.getMilliseconds())):t=new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,0,0),t},i.prototype.todayButtonClick=function(){if(this.showTodayButton){var t=this.generateTodayVal(this.value);if(this.setProperties({value:t},!0),this.isMultiSelection){var i=this.copyValues(this.values);e.prototype.checkPresentDate.call(this,t,this.values)||(i.push(t),this.setProperties({values:i}))}e.prototype.todayButtonClick.call(this,new Date(+this.value))}},i.prototype.keyActionHandle=function(t){e.prototype.keyActionHandle.call(this,t,this.value,this.isMultiSelection)},i.prototype.preRender=function(){var t=this;this.changeHandler=function(e){t.triggerChange(e)},this.checkView(),e.prototype.preRender.call(this,this.value)},i.prototype.createContent=function(){this.previousDate=this.value,e.prototype.createContent.call(this)},i.prototype.minMaxDate=function(t){return e.prototype.minMaxDate.call(this,t)},i.prototype.renderMonths=function(t){e.prototype.renderMonths.call(this,t,this.value)},i.prototype.renderDays=function(t,i){var s=e.prototype.renderDays.call(this,t,i,this.value,this.isMultiSelection,this.values);return this.isMultiSelection&&e.prototype.validateValues.call(this,this.isMultiSelection,this.values),s},i.prototype.renderYears=function(t){"Gregorian"===this.calendarMode?e.prototype.renderYears.call(this,t,this.value):this.islamicModule.islamicRenderYears(t,this.value)},i.prototype.renderDecades=function(t){"Gregorian"===this.calendarMode?e.prototype.renderDecades.call(this,t,this.value):this.islamicModule.islamicRenderDecade(t,this.value)},i.prototype.renderTemplate=function(t,i,s,a){"Gregorian"===this.calendarMode?e.prototype.renderTemplate.call(this,t,i,s,a,this.value):this.islamicModule.islamicRenderTemplate(t,i,s,a,this.value),this.changedArgs={value:this.value,values:this.values},this.changeHandler()},i.prototype.clickHandler=function(i){var s=i.currentTarget;if(this.isPopupClicked=!0,s.classList.contains(o))if(this.isMultiSelection){var a=this.copyValues(this.values);a.push(this.getIdValue(i,null)),this.setProperties({values:a},!0),this.setProperties({value:this.values[this.values.length-1]},!0)}else this.setProperties({value:this.getIdValue(i,null)},!0);var n=this.currentView();e.prototype.clickHandler.call(this,i,this.value),this.isMultiSelection&&this.currentDate!==this.value&&!t.isNullOrUndefined(this.tableBodyElement.querySelectorAll("."+y)[0])&&"Year"===n&&this.tableBodyElement.querySelectorAll("."+y)[0].classList.remove(y)},i.prototype.switchView=function(t,i){e.prototype.switchView.call(this,t,i,this.isMultiSelection)},i.prototype.getModuleName=function(){return e.prototype.getModuleName.call(this),"calendar"},i.prototype.getPersistData=function(){e.prototype.getPersistData.call(this);return this.addOnPersist(["value","values"])},i.prototype.onPropertyChanged=function(t,i){this.effect="";for(var s=0,a=Object.keys(t);s<a.length;s++){switch(a[s]){case"value":this.isDateSelected&&("string"==typeof t.value?this.setProperties({value:new Date(this.checkValue(t.value))},!0):t.value=new Date(this.checkValue(t.value)),isNaN(+this.value)&&this.setProperties({value:i.value},!0),this.update());break;case"values":if(this.isDateSelected){if("string"==typeof t.values||"number"==typeof t.values)this.setProperties({values:null},!0);else{for(var n=this.copyValues(this.values),r=0;r<n.length;r++){var l=n[r];this.checkDateValue(l)&&!e.prototype.checkPresentDate.call(this,l,n)&&n.push(l)}this.setProperties({values:n},!0),this.values.length>0&&this.setProperties({value:t.values[t.values.length-1]},!0)}this.validateValues(this.isMultiSelection,this.values),this.update()}break;case"isMultiSelection":this.isDateSelected&&(this.setProperties({isMultiSelection:t.isMultiSelection},!0),this.update());break;default:e.prototype.onPropertyChanged.call(this,t,i,this.isMultiSelection,this.values)}}},i.prototype.destroy=function(){if(e.prototype.destroy.call(this),"calendar"===this.getModuleName()){var i=t.closest(this.element,"form");i&&t.EventHandler.remove(i,"reset",this.formResetHandler.bind(this))}},i.prototype.navigateTo=function(t,i){this.minMaxUpdate(),e.prototype.navigateTo.call(this,t,i)},i.prototype.currentView=function(){return e.prototype.currentView.call(this)},i.prototype.addDate=function(i){if("string"!=typeof i&&"number"!=typeof i){var s=this.copyValues(this.values);if("object"==typeof i&&i.length>0)for(var a=i,n=0;n<a.length;n++)this.checkDateValue(a[n])&&!e.prototype.checkPresentDate.call(this,a[n],s)&&(!t.isNullOrUndefined(s)&&s.length>0?s.push(a[n]):s=[new Date(+a[n])]);else this.checkDateValue(i)&&!e.prototype.checkPresentDate.call(this,i,s)&&(!t.isNullOrUndefined(s)&&s.length>0?s.push(i):s=[new Date(+i)]);this.setProperties({values:s},!0),this.isMultiSelection&&this.setProperties({value:this.values[this.values.length-1]},!0),this.validateValues(this.isMultiSelection,s),this.update(),this.changedArgs={value:this.value,values:this.values},this.changeHandler()}},i.prototype.removeDate=function(e){if("string"!=typeof e&&"number"!=typeof e&&!t.isNullOrUndefined(this.values)&&this.values.length>0){var i=this.copyValues(this.values);if("object"==typeof e&&e.length>0)for(var s=e,a=0;a<s.length;a++)for(var n=0;n<i.length;n++)+i[n]==+s[a]&&i.splice(n,1);else for(n=0;n<i.length;n++)+i[n]==+e&&i.splice(n,1);this.setProperties({values:i},!1),this.update(),this.isMultiSelection&&this.setProperties({value:this.values[this.values.length-1]},!0),this.changedArgs={value:this.value,values:this.values},this.changeHandler()}},i.prototype.update=function(){this.validateDate(),this.minMaxUpdate(),e.prototype.setValueUpdate.call(this)},i.prototype.selectDate=function(i,s,a){e.prototype.selectDate.call(this,i,s,a,this.isMultiSelection,this.values),this.isMultiSelection&&!t.isNullOrUndefined(this.values)&&this.values.length>0&&this.setProperties({value:this.values[this.values.length-1]},!0),this.changedArgs={value:this.value,values:this.values},this.changeHandler(i)},i.prototype.changeEvent=function(e){this.trigger("change",this.changedArgs),this.previousDate=new Date(+this.value)},i.prototype.triggerChange=function(e){this.changedArgs.event=e||null,this.changedArgs.isInteracted=!t.isNullOrUndefined(e),t.isNullOrUndefined(this.value)||this.setProperties({value:this.value},!0),this.isMultiSelection||+this.value===Number.NaN||+this.value==+this.previousDate?t.isNullOrUndefined(this.values)||this.previousValues===this.values.length||(this.changeEvent(e),this.previousValues=this.values.length):this.changeEvent(e)},l([t.Property(null)],i.prototype,"value",void 0),l([t.Property(null)],i.prototype,"values",void 0),l([t.Property(!1)],i.prototype,"isMultiSelection",void 0),l([t.Event()],i.prototype,"change",void 0),i=l([t.NotifyPropertyChanges],i)}(E),w="e-other-month",V="e-disabled",k="e-selected",O="e-focused-date",N="e-month-hide",M=function(){function e(e){this.calendarInstance=e}return e.prototype.getModuleName=function(){return"islamic"},e.prototype.islamicTitleUpdate=function(e,i){var s=new t.Internationalization(this.calendarInstance.locale);switch(i){case"days":this.calendarInstance.headerTitleElement.textContent=s.formatDate(e,{type:"dateTime",format:"MMMMyyyy",calendar:"islamic"});break;case"months":this.calendarInstance.headerTitleElement.textContent=s.formatDate(e,{type:"dateTime",format:"yyyy",calendar:"islamic"})}},e.prototype.islamicRenderDays=function(e,i,s,a){var n,r=[],l=new Date(this.islamicInValue(e));this.calendarInstance.weekNumber;this.islamicTitleUpdate(e,"days");var o=this.getIslamicDate(l),h=this.toGregorian(o.year,o.month,1),u=o.month;for(l=h;l.getDay()!==this.calendarInstance.firstDayOfWeek;)this.calendarInstance.setStartDate(l,-864e5);for(var d=0;d<42;++d){var p=this.calendarInstance.createElement("td",{className:"e-cell"}),c=this.calendarInstance.createElement("span");d%7==0&&this.calendarInstance.weekNumber&&(c.textContent=""+this.calendarInstance.getWeek(l),p.appendChild(c),t.addClass([p],"e-week-number"),r.push(p)),n=new Date(+l),l=this.calendarInstance.minMaxDate(l);var m={type:"dateTime",skeleton:"full",calendar:"islamic"},v=this.calendarInstance.globalize.parseDate(this.calendarInstance.globalize.formatDate(l,m),m),f=this.islamicDayCell(l),y=this.calendarInstance.globalize.formatDate(l,{type:"date",skeleton:"full",calendar:"islamic"}),g=this.calendarInstance.createElement("span");g.textContent=this.calendarInstance.globalize.formatDate(l,{type:"date",skeleton:"d",calendar:"islamic"});var b=this.calendarInstance.min>l||this.calendarInstance.max<l;b?(t.addClass([f],V),t.addClass([f],"e-overlay")):g.setAttribute("title",""+y);u!==this.getIslamicDate(l).month&&t.addClass([f],w),0!==l.getDay()&&6!==l.getDay()||t.addClass([f],"e-weekend"),f.appendChild(g),this.calendarInstance.renderDayCellArgs={date:l,isDisabled:!1,element:f,isOutOfRange:b};var D=this.calendarInstance.renderDayCellArgs;if(this.calendarInstance.renderDayCellEvent(D),D.isDisabled)if(this.calendarInstance.isMultiSelection){if(!t.isNullOrUndefined(this.calendarInstance.values)&&this.calendarInstance.values.length>0)for(var E=0;E<a.length;E++){+new Date(this.calendarInstance.globalize.formatDate(D.date,{type:"date",skeleton:"yMd",calendar:"islamic"}))===+new Date(this.calendarInstance.globalize.formatDate(this.calendarInstance.values[E],{type:"date",skeleton:"yMd",calendar:"islamic"}))&&(this.calendarInstance.values.splice(E,1),E=-1)}}else i&&+i==+D.date&&this.calendarInstance.setProperties({value:null},!0);this.calendarInstance.renderDayCellArgs.isDisabled&&!f.classList.contains(k)&&(t.addClass([f],V),t.addClass([f],"e-overlay"),+this.calendarInstance.renderDayCellArgs.date==+this.calendarInstance.todayDate&&(this.calendarInstance.todayDisabled=!0));var C=f.classList.contains(w),O=f.classList.contains(V);if(O||t.EventHandler.add(f,"click",this.calendarInstance.clickHandler,this.calendarInstance),!this.calendarInstance.isMultiSelection||t.isNullOrUndefined(this.calendarInstance.values)||C||O)C||O||!this.calendarInstance.getDateVal(l,i)?this.calendarInstance.updateFocus(C,O,l,f,e):t.addClass([f],k);else{for(var N=0;N<this.calendarInstance.values.length;N++){this.calendarInstance.globalize.formatDate(l,{type:"date",skeleton:"short",calendar:"islamic"})===this.calendarInstance.globalize.formatDate(this.calendarInstance.values[N],{type:"date",skeleton:"short",calendar:"islamic"})&&this.calendarInstance.getDateVal(l,this.calendarInstance.values[N])?t.addClass([f],k):this.calendarInstance.updateFocus(C,O,l,f,e)}this.calendarInstance.values.length<=0&&this.calendarInstance.updateFocus(C,O,l,f,e)}v.getDate()===(new Date).getDate()&&v.getMonth()===(new Date).getMonth()&&v.getFullYear()===(new Date).getFullYear()&&t.addClass([f],"e-today"),l=new Date(+n),r.push(this.calendarInstance.renderDayCellArgs.element),this.calendarInstance.addDay(l,1,null,this.calendarInstance.max,this.calendarInstance.min)}return r},e.prototype.islamicIconHandler=function(){new Date(this.islamicInValue(this.calendarInstance.currentDate)).setDate(1);var e=new Date(this.islamicInValue(this.calendarInstance.currentDate));switch(this.calendarInstance.currentView()){case"Month":var t=this.islamicCompareMonth(e,this.calendarInstance.min)<1,i=this.islamicCompareMonth(e,this.calendarInstance.max)>-1;this.calendarInstance.previousIconHandler(t),this.calendarInstance.nextIconHandler(i);break;case"Year":var s=this.hijriCompareYear(e,this.calendarInstance.min)<1,a=this.hijriCompareYear(e,this.calendarInstance.max)>-1;this.calendarInstance.previousIconHandler(s),this.calendarInstance.nextIconHandler(a);break;case"Decade":var n=this.hijriCompareDecade(e,this.calendarInstance.min)<1,r=this.hijriCompareDecade(e,this.calendarInstance.max)>-1;this.calendarInstance.previousIconHandler(n),this.calendarInstance.nextIconHandler(r)}},e.prototype.islamicNext=function(){this.calendarInstance.effect="";var e=this.calendarInstance.getViewNumber(this.calendarInstance.currentView()),t=this.getIslamicDate(this.calendarInstance.currentDate);switch(this.calendarInstance.currentView()){case"Year":this.calendarInstance.currentDate=this.toGregorian(t.year+1,t.month,1),this.calendarInstance.switchView(e);break;case"Month":this.calendarInstance.currentDate=this.toGregorian(t.year,t.month+1,1),this.calendarInstance.switchView(e);break;case"Decade":this.calendarInstance.currentDate=this.toGregorian(t.year+10,t.month,1),this.calendarInstance.switchView(e)}},e.prototype.islamicPrevious=function(){var e=this.calendarInstance.getViewNumber(this.calendarInstance.currentView());this.calendarInstance.effect="";var t=this.getIslamicDate(this.calendarInstance.currentDate);switch(this.calendarInstance.currentView()){case"Month":this.calendarInstance.currentDate=this.toGregorian(t.year,t.month-1,1),this.calendarInstance.switchView(e);break;case"Year":this.calendarInstance.currentDate=this.toGregorian(t.year-1,t.month,1),this.calendarInstance.switchView(e);break;case"Decade":this.calendarInstance.currentDate=this.toGregorian(t.year-10,t.month-1,1),this.calendarInstance.switchView(e)}},e.prototype.islamicRenderYears=function(e,i){this.calendarInstance.removeTableHeadElement();var s=[],a=t.isNullOrUndefined(i),n=new Date(this.islamicInValue(this.calendarInstance.currentDate)),r=this.getIslamicDate(n);n=t.HijriParser.toGregorian(r.year,1,1);var l=r.month,o=r.year,h=r.year,u=this.getIslamicDate(this.calendarInstance.min).year,d=this.getIslamicDate(this.calendarInstance.min).month,p=this.getIslamicDate(this.calendarInstance.max).year,c=this.getIslamicDate(this.calendarInstance.max).month;this.islamicTitleUpdate(this.calendarInstance.currentDate,"months");this.calendarInstance.min>n||this.calendarInstance.max;for(var m=1;m<=12;++m){var v=this.getIslamicDate(n);n=t.HijriParser.toGregorian(v.year,m,1);var f=this.islamicDayCell(n),y=this.calendarInstance.createElement("span"),g=i&&this.getIslamicDate(i).month===this.getIslamicDate(n).month,b=i&&this.getIslamicDate(i).year===o&&g;y.textContent=this.calendarInstance.globalize.formatDate(n,{type:"dateTime",format:"MMM",calendar:"islamic"}),this.calendarInstance.min&&(h<u||m<d&&h===u)||this.calendarInstance.max&&(h>p||m>c&&h>=p)?t.addClass([f],V):!a&&b?t.addClass([f],k):this.getIslamicDate(n).month===l&&this.getIslamicDate(this.calendarInstance.currentDate).month===l&&t.addClass([f],O),f.classList.contains(V)||t.EventHandler.add(f,"click",this.calendarInstance.clickHandler,this.calendarInstance),f.appendChild(y),s.push(f)}this.islamicRenderTemplate(s,4,"e-year",e,i)},e.prototype.islamicRenderDecade=function(e,i){this.calendarInstance.removeTableHeadElement();var s=[],a=new Date(this.islamicInValue(this.calendarInstance.currentDate)),n=this.getIslamicDate(a),r=(a=t.HijriParser.toGregorian(n.year,1,1)).getFullYear(),l=new Date(this.islamicInValue(r-r%10)),o=new Date(this.islamicInValue(r-r%10+9)),h=l.getFullYear(),u=o.getFullYear(),d=this.calendarInstance.globalize.formatDate(l,{type:"dateTime",format:"y",calendar:"islamic"}),p=this.calendarInstance.globalize.formatDate(o,{type:"dateTime",format:"y",calendar:"islamic"});this.calendarInstance.headerTitleElement.textContent=d+" - "+p;for(var c=new Date(r-r%10-2,0,1).getFullYear(),m=1;m<=12;++m){var v=c+m;a.setFullYear(v),a.setDate(1),a.setMonth(0);var f=this.getIslamicDate(a);a=t.HijriParser.toGregorian(f.year,1,1);var y=this.islamicDayCell(a);t.attributes(y,{role:"gridcell"});var g=this.calendarInstance.createElement("span");g.textContent=this.calendarInstance.globalize.formatDate(a,{type:"dateTime",format:"y",calendar:"islamic"}),v<h||v>u?t.addClass([y],w):v<new Date(this.islamicInValue(this.calendarInstance.min)).getFullYear()||v>new Date(this.islamicInValue(this.calendarInstance.max)).getFullYear()?t.addClass([y],V):t.isNullOrUndefined(i)||this.getIslamicDate(a).year!==this.getIslamicDate(i).year?a.getFullYear()!==this.calendarInstance.currentDate.getFullYear()||y.classList.contains(V)||t.addClass([y],O):t.addClass([y],k),y.classList.contains(V)||t.EventHandler.add(y,"click",this.calendarInstance.clickHandler,this.calendarInstance),y.appendChild(g),s.push(y)}this.islamicRenderTemplate(s,4,"e-decade",e,i)},e.prototype.islamicDayCell=function(e){var i={skeleton:"full",type:"dateTime",calendar:"islamic"},s=this.calendarInstance.globalize.formatDate(e,i),a=this.calendarInstance.globalize.parseDate(s,i).valueOf(),n={className:"e-cell",attrs:{id:""+t.getUniqueID(""+a),"aria-selected":"false",role:"gridcell"}};return this.calendarInstance.createElement("td",n)},e.prototype.islamicRenderTemplate=function(e,i,s,a,n){var r,l=this.calendarInstance.getViewNumber(this.calendarInstance.currentView());this.calendarInstance.tableBodyElement=this.calendarInstance.createElement("tbody"),this.calendarInstance.table.appendChild(this.calendarInstance.tableBodyElement),t.removeClass([this.calendarInstance.contentElement,this.calendarInstance.headerElement],["e-month","e-decade","e-year"]),t.addClass([this.calendarInstance.contentElement,this.calendarInstance.headerElement],[s]);for(var o=i,h=0,u=0;u<e.length/i;++u){for(r=this.calendarInstance.createElement("tr",{attrs:{role:"row"}}),h=0+h;h<o;h++)e[h].classList.contains("e-week-number")||t.isNullOrUndefined(e[h].children[0])||(t.addClass([e[h].children[0]],["e-day"]),t.rippleEffect(e[h].children[0],{duration:600,isCenterRipple:!0})),r.appendChild(e[h]),this.calendarInstance.weekNumber&&7===h&&e[7].classList.contains(w)&&t.addClass([r],N),!this.calendarInstance.weekNumber&&6===h&&e[6].classList.contains(w)&&t.addClass([r],N),this.calendarInstance.weekNumber?41===h&&e[41].classList.contains(w)&&t.addClass([r],N):35===h&&e[35].classList.contains(w)&&t.addClass([r],N);o+=i,h+=0,this.calendarInstance.tableBodyElement.appendChild(r)}this.calendarInstance.table.querySelector("tbody").className=this.calendarInstance.effect,this.islamicIconHandler(),(l!==this.calendarInstance.getViewNumber(this.calendarInstance.currentView())||0===l&&l!==this.calendarInstance.getViewNumber(this.calendarInstance.currentView()))&&this.calendarInstance.navigateHandler(a),this.calendarInstance.setAriaActiveDescendant(),this.calendarInstance.changedArgs={value:this.calendarInstance.value,values:this.calendarInstance.values},this.calendarInstance.changeHandler()},e.prototype.islamicCompareMonth=function(e,t){var i=this.getIslamicDate(e),s=this.getIslamicDate(t);return i.year>s.year?1:i.year<s.year?-1:i.month===s.month?0:i.month>s.month?1:-1},e.prototype.islamicCompare=function(e,t,i){var s,a,n=this.getIslamicDate(e),r=this.getIslamicDate(t).year;return s=r,a=0,i&&(s=(r-=r%i)-r%i+i-1),n.year>s?a=1:"Decade"===this.calendarInstance.currentView()&&n.year<r&&!(e.getFullYear()>=2060&&e.getFullYear()<=2069)?a=-1:n.year<r&&"Year"===this.calendarInstance.currentView()&&(a=-1),a},e.prototype.getIslamicDate=function(e){return t.HijriParser.getHijriDate(e)},e.prototype.toGregorian=function(e,i,s){return t.HijriParser.toGregorian(e,i,s)},e.prototype.hijriCompareYear=function(e,t){return this.islamicCompare(e,t,0)},e.prototype.hijriCompareDecade=function(e,t){return this.islamicCompare(e,t,10)},e.prototype.destroy=function(){this.calendarInstance=null},e.prototype.islamicInValue=function(e){return e instanceof Date?e.toUTCString():""+e},e}(),I=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(t,i)};return function(t,i){function s(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(s.prototype=i.prototype,new s)}}(),x=function(e,t,i,s){var a,n=arguments.length,r=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,i,s);else for(var l=e.length-1;l>=0;l--)(a=e[l])&&(r=(n<3?a(r):n>3?a(t,i,r):a(t,i))||r);return n>3&&r&&Object.defineProperty(t,i,r),r},A="e-datepicker",T="e-popup-wrapper",U="e-input-focus",P="e-active",S="e-date-overflow",H="e-selected",W="e-non-edit",L=["title","class","style"],F=function(e){function a(t,i){var s=e.call(this,t,i)||this;return s.previousElementValue="",s.isDateIconClicked=!1,s.isAltKeyPressed=!1,s.isInteracted=!0,s.invalidValueString=null,s.checkPreviousValue=null,s.defaultKeyConfigs={altUpArrow:"alt+uparrow",altDownArrow:"alt+downarrow",escape:"escape",enter:"enter",controlUp:"ctrl+38",controlDown:"ctrl+40",moveDown:"downarrow",moveUp:"uparrow",moveLeft:"leftarrow",moveRight:"rightarrow",select:"enter",home:"home",end:"end",pageUp:"pageup",pageDown:"pagedown",shiftPageUp:"shift+pageup",shiftPageDown:"shift+pagedown",controlHome:"ctrl+home",controlEnd:"ctrl+end",tab:"tab"},s.datepickerOptions=t,s}return I(a,e),a.prototype.render=function(){this.initialize(),this.bindEvents(),this.renderComplete()},a.prototype.setAllowEdit=function(){this.allowEdit?this.readonly||this.inputElement.removeAttribute("readonly"):t.attributes(this.inputElement,{readonly:""}),this.updateIconState()},a.prototype.updateIconState=function(){this.allowEdit||!this.inputWrapper||this.readonly?this.inputWrapper&&t.removeClass([this.inputWrapper.container],[W]):""===this.inputElement.value?t.removeClass([this.inputWrapper.container],[W]):t.addClass([this.inputWrapper.container],[W])},a.prototype.initialize=function(){this.checkInvalidValue(this.value),this.createInput(),this.updateHtmlAttributeToWrapper(),this.setAllowEdit(),this.updateInput(),this.previousElementValue=this.inputElement.value,this.previousDate=new Date(+this.value),this.inputElement.setAttribute("value",this.inputElement.value),this.inputValueCopy=this.value},a.prototype.createInput=function(){var e={"aria-live":"assertive","aria-atomic":"true","aria-haspopup":"true","aria-activedescendant":"null","aria-owns":this.element.id+"_options","aria-expanded":"false",role:"combobox",autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false","aria-invalid":"false"};if("datepicker"===this.getModuleName()){var i={placeholder:this.placeholder};this.globalize=new t.Internationalization(this.locale),this.l10n=new t.L10n("datepicker",i,this.locale),this.setProperties({placeholder:this.placeholder||this.l10n.getConstant("placeholder")},!0)}this.inputWrapper=s.Input.createInput({element:this.inputElement,floatLabelType:this.floatLabelType,properties:{readonly:this.readonly,placeholder:this.placeholder,cssClass:this.cssClass,enabled:this.enabled,enableRtl:this.enableRtl,showClearButton:this.showClearButton},buttons:["e-input-group-icon e-date-icon e-icons"]},this.createElement),this.setWidth(this.width),""!==this.inputElement.name?this.inputElement.setAttribute("name",""+this.inputElement.getAttribute("name")):this.inputElement.setAttribute("name",""+this.element.id),t.attributes(this.inputElement,e),this.enabled?(this.inputElement.setAttribute("aria-disabled","false"),this.inputElement.setAttribute("tabindex",this.tabIndex)):(this.inputElement.setAttribute("aria-disabled","true"),this.inputElement.tabIndex=-1),s.Input.addAttributes({"aria-label":"select"},this.inputWrapper.buttons[0]),t.addClass([this.inputWrapper.container],"e-date-wrapper")},a.prototype.updateInput=function(){var i;if(this.value&&!this.isCalendar()&&this.disabledDates(),+new Date(this.checkValue(this.value))||this.setProperties({value:null},!0),this.strictMode&&(e.prototype.validateDate.call(this),this.minMaxUpdates(),e.prototype.minMaxUpdate.call(this)),!t.isNullOrUndefined(this.value)){var a=this.value,n=void 0,r=t.isNullOrUndefined(this.formatString)?this.dateTimeFormat:this.formatString;if("datetimepicker"===this.getModuleName()?n="Gregorian"===this.calendarMode?this.globalize.formatDate(this.value,{format:r,type:"dateTime",skeleton:"yMd"}):this.globalize.formatDate(this.value,{format:r,type:"dateTime",skeleton:"yMd",calendar:"islamic"}):(i="Gregorian"===this.calendarMode?{format:this.formatString,type:"dateTime",skeleton:"yMd"}:{format:this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"},n=this.globalize.formatDate(this.value,i)),+a<=+this.max&&+a>=+this.min)s.Input.setValue(n,this.inputElement,this.floatLabelType,this.showClearButton);else{var l=+a>=+this.max||!+this.value||!+this.value||+a<=+this.min;!this.strictMode&&l&&s.Input.setValue(n,this.inputElement,this.floatLabelType,this.showClearButton)}}t.isNullOrUndefined(this.value)&&this.strictMode&&s.Input.setValue("",this.inputElement,this.floatLabelType,this.showClearButton),!this.strictMode&&t.isNullOrUndefined(this.value)&&this.invalidValueString&&s.Input.setValue(this.invalidValueString,this.inputElement,this.floatLabelType,this.showClearButton),this.changedArgs={value:this.value},this.errorClass(),this.updateIconState()},a.prototype.minMaxUpdates=function(){!t.isNullOrUndefined(this.value)&&this.value<this.min&&this.min<=this.max&&this.strictMode?(this.setProperties({value:this.min},!0),this.changedArgs={value:this.value}):!t.isNullOrUndefined(this.value)&&this.value>this.max&&this.min<=this.max&&this.strictMode&&(this.setProperties({value:this.max},!0),this.changedArgs={value:this.value})},a.prototype.checkStringValue=function(e){var i=null,s=null,a=null;if("datetimepicker"===this.getModuleName()){var n=new t.Internationalization(this.locale);"Gregorian"===this.calendarMode?(s={format:this.dateTimeFormat,type:"dateTime",skeleton:"yMd"},a={format:n.getDatePattern({skeleton:"yMd"}),type:"dateTime"}):(s={format:this.dateTimeFormat,type:"dateTime",skeleton:"yMd",calendar:"islamic"},a={format:n.getDatePattern({skeleton:"yMd"}),type:"dateTime",calendar:"islamic"})}else s="Gregorian"===this.calendarMode?{format:this.formatString,type:"dateTime",skeleton:"yMd"}:{format:this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"};return i=this.checkDateValue(this.globalize.parseDate(e,s)),t.isNullOrUndefined(i)&&"datetimepicker"===this.getModuleName()&&(i=this.checkDateValue(this.globalize.parseDate(e,a))),i},a.prototype.checkInvalidValue=function(e){if(!(e instanceof Date||t.isNullOrUndefined(e))){var i=null,s=e;"number"==typeof e&&(s=e.toString());if("datetimepicker"===this.getModuleName()){var a=new t.Internationalization(this.locale);"Gregorian"===this.calendarMode?({format:this.dateTimeFormat,type:"dateTime",skeleton:"yMd"},{format:a.getDatePattern({skeleton:"yMd"}),type:"dateTime"}):({format:this.dateTimeFormat,type:"dateTime",skeleton:"yMd",calendar:"islamic"},{format:a.getDatePattern({skeleton:"yMd"}),type:"dateTime",calendar:"islamic"})}else"Gregorian"===this.calendarMode?{format:this.formatString,type:"dateTime",skeleton:"yMd"}:{format:this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"};var n=!1;if("string"!=typeof s)s=null,n=!0;else if("string"==typeof s&&(s=s.trim()),!(i=this.checkStringValue(s))){var r=null;r=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,!/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/.test(s)&&!r.test(s)||/^[a-zA-Z0-9- ]*$/.test(s)||isNaN(+new Date(this.checkValue(s)))?n=!0:i=new Date(s)}n?(this.strictMode||(this.invalidValueString=s),this.setProperties({value:null},!0)):this.setProperties({value:i},!0)}},a.prototype.bindInputEvent=function(){t.isNullOrUndefined(this.formatString)||(-1===this.formatString.indexOf("y")?t.EventHandler.add(this.inputElement,"input",this.inputHandler,this):t.EventHandler.remove(this.inputElement,"input",this.inputHandler))},a.prototype.bindEvents=function(){this.enabled?(t.EventHandler.add(this.inputWrapper.buttons[0],"mousedown touchstart",this.dateIconHandler,this),t.EventHandler.add(this.inputElement,"focus",this.inputFocusHandler,this),t.EventHandler.add(this.inputElement,"blur",this.inputBlurHandler,this),this.bindInputEvent(),t.EventHandler.add(this.inputElement,"change",this.inputChangeHandler,this),this.showClearButton&&this.inputWrapper.clearButton&&t.EventHandler.add(this.inputWrapper.clearButton,"mousedown touchstart",this.resetHandler,this),this.formElement&&t.EventHandler.add(this.formElement,"reset",this.resetFormHandler,this)):(t.EventHandler.remove(this.inputWrapper.buttons[0],"mousedown touchstart",this.dateIconHandler),t.EventHandler.remove(this.inputElement,"focus",this.inputFocusHandler),t.EventHandler.remove(this.inputElement,"blur",this.inputBlurHandler),t.EventHandler.remove(this.inputElement,"change",this.inputChangeHandler),this.showClearButton&&this.inputWrapper.clearButton&&t.EventHandler.remove(this.inputWrapper.clearButton,"mousedown touchstart",this.resetHandler),this.formElement&&t.EventHandler.remove(this.formElement,"reset",this.resetFormHandler)),this.defaultKeyConfigs=t.extend(this.defaultKeyConfigs,this.keyConfigs),this.keyboardModules=new t.KeyboardEvents(this.inputElement,{eventName:"keydown",keyAction:this.inputKeyActionHandle.bind(this),keyConfigs:this.defaultKeyConfigs})},a.prototype.resetFormHandler=function(){if(!this.inputElement.disabled){var e=this.inputElement.getAttribute("value");"EJS-DATEPICKER"!==this.element.tagName&&"EJS-DATETIMEPICKER"!==this.element.tagName||(e="",this.inputValueCopy=null,this.inputElement.setAttribute("value","")),this.setProperties({value:this.inputValueCopy},!0),this.restoreValue(),this.inputElement&&(s.Input.setValue(e,this.inputElement,this.floatLabelType,this.showClearButton),this.errorClass())}},a.prototype.restoreValue=function(){this.currentDate=this.value?this.value:new Date,this.previousDate=this.value,this.previousElementValue=t.isNullOrUndefined(this.inputValueCopy)?"":this.globalize.formatDate(this.inputValueCopy,{format:this.formatString,type:"dateTime",skeleton:"yMd"})},a.prototype.inputChangeHandler=function(e){e.stopPropagation()},a.prototype.bindClearEvent=function(){this.showClearButton&&this.inputWrapper.clearButton&&t.EventHandler.add(this.inputWrapper.clearButton,"mousedown touchstart",this.resetHandler,this)},a.prototype.resetHandler=function(e){e.preventDefault(),this.clear(e)},a.prototype.clear=function(e){this.setProperties({value:null},!0),s.Input.setValue("",this.inputElement,this.floatLabelType,this.showClearButton),this.invalidValueString="",this.updateInput(),this.popupUpdate(),this.changeEvent(e)},a.prototype.dateIconHandler=function(e){t.Browser.isDevice&&(this.inputElement.setAttribute("readonly",""),this.inputElement.blur()),e.preventDefault(),this.readonly||(this.isCalendar()?this.hide(e):(this.isDateIconClicked=!0,this.show(null,e),"datetimepicker"===this.getModuleName()&&this.inputElement.focus(),this.inputElement.focus(),t.addClass([this.inputWrapper.container],[U]),t.addClass(this.inputWrapper.buttons,P)))},a.prototype.updateHtmlAttributeToWrapper=function(){if(!t.isNullOrUndefined(this.htmlAttributes))for(var e=0,i=Object.keys(this.htmlAttributes);e<i.length;e++){var s=i[e];if(L.indexOf(s)>-1)if("class"===s)t.addClass([this.inputWrapper.container],this.htmlAttributes[s].split(" "));else if("style"===s){var a=this.inputWrapper.container.getAttribute(s);a=t.isNullOrUndefined(a)?this.htmlAttributes[s]:a+this.htmlAttributes[s],this.inputWrapper.container.setAttribute(s,a)}else this.inputWrapper.container.setAttribute(s,this.htmlAttributes[s])}},a.prototype.updateHtmlAttributeToElement=function(){if(!t.isNullOrUndefined(this.htmlAttributes))for(var e=0,i=Object.keys(this.htmlAttributes);e<i.length;e++){var s=i[e];L.indexOf(s)<0&&this.inputElement.setAttribute(s,this.htmlAttributes[s])}},a.prototype.CalendarKeyActionHandle=function(e){switch(e.action){case"escape":this.isCalendar()?this.hide(e):this.inputWrapper.container.children[this.index].blur();break;case"enter":this.isCalendar()?+this.value==+this.currentDate||this.isCalendar()||this.inputWrapper.container.children[this.index].focus():this.show(null,e),"datetimepicker"===this.getModuleName()&&this.inputElement.focus();break;case"tab":this.hide(e)}},a.prototype.inputFocusHandler=function(){var e={model:this};this.isDateIconClicked=!1,this.trigger("focus",e),this.updateIconState()},a.prototype.inputHandler=function(e){this.isPopupClicked=!1},a.prototype.inputBlurHandler=function(e){if(this.strictModeUpdate(),""===this.inputElement.value&&t.isNullOrUndefined(this.value)&&(this.invalidValueString=null,s.Input.setValue("",this.inputElement,this.floatLabelType,this.showClearButton)),this.updateInput(),this.popupUpdate(),this.changeTrigger(e),this.errorClass(),this.isCalendar()&&document.activeElement===this.inputElement&&this.hide(e),"datepicker"===this.getModuleName()){var i={model:this};this.trigger("blur",i)}this.isCalendar()&&(this.defaultKeyConfigs=t.extend(this.defaultKeyConfigs,this.keyConfigs),this.calendarKeyboardModules=new t.KeyboardEvents(this.calendarElement.children[1].firstElementChild,{eventName:"keydown",keyAction:this.CalendarKeyActionHandle.bind(this),keyConfigs:this.defaultKeyConfigs})),this.isPopupClicked=!1},a.prototype.documentHandler=function(i){"touchstart"!==i.type&&i.preventDefault();var s=i.target;t.closest(s,".e-datepicker.e-popup-wrapper")||t.closest(s,".e-input-group")===this.inputWrapper.container||s.classList.contains("e-day")?t.closest(s,".e-datepicker.e-popup-wrapper")&&(s.classList.contains("e-day")&&!t.isNullOrUndefined(i.target.parentElement)&&i.target.parentElement.classList.contains("e-selected")&&t.closest(s,".e-content")&&t.closest(s,".e-content").classList.contains("e-"+this.depth.toLowerCase())?this.hide(i):t.closest(s,".e-footer-container")&&s.classList.contains("e-today")&&s.classList.contains("e-btn")&&+new Date(+this.value)==+e.prototype.generateTodayVal.call(this,this.value)&&this.hide(i)):(this.hide(i),this.focusOut())},a.prototype.inputKeyActionHandle=function(e){var t=this.currentView();switch(e.action){case"altUpArrow":this.isAltKeyPressed=!1,this.hide(e),this.inputElement.focus();break;case"altDownArrow":this.isAltKeyPressed=!0,this.strictModeUpdate(),this.updateInput(),this.changeTrigger(e),"datepicker"===this.getModuleName()&&this.show(null,e);break;case"escape":this.hide(e);break;case"enter":this.strictModeUpdate(),this.updateInput(),this.popupUpdate(),this.changeTrigger(e),this.errorClass(),this.isCalendar()||document.activeElement!==this.inputElement||this.hide(e),this.isCalendar()&&(e.preventDefault(),e.stopPropagation());break;case"tab":this.strictModeUpdate(),this.updateInput(),this.popupUpdate(),this.changeTrigger(e),this.errorClass(),this.hide(e);break;default:this.defaultAction(e),"select"===e.action&&t===this.depth&&this.hide(e)}},a.prototype.defaultAction=function(i){this.previousDate=!t.isNullOrUndefined(this.value)&&new Date(+this.value)||null,this.isCalendar()&&(e.prototype.keyActionHandle.call(this,i),t.attributes(this.inputElement,{"aria-activedescendant":""+this.setActiveDescendant()}))},a.prototype.popupUpdate=function(){if((t.isNullOrUndefined(this.value)&&!t.isNullOrUndefined(this.previousDate)||+this.value!=+this.previousDate)&&(this.popupObj&&this.popupObj.element.querySelectorAll("."+H).length>0&&t.removeClass(this.popupObj.element.querySelectorAll("."+H),[H]),!t.isNullOrUndefined(this.value)&&+this.value>=+this.min&&+this.value<=+this.max)){var i=new Date(this.checkValue(this.value));e.prototype.navigateTo.call(this,"Month",i)}},a.prototype.strictModeUpdate=function(){var e,i;if(e="datetimepicker"===this.getModuleName()?t.isNullOrUndefined(this.formatString)?this.dateTimeFormat:this.formatString:t.isNullOrUndefined(this.formatString)?this.formatString:this.formatString.replace("dd","d"),!t.isNullOrUndefined(e)){e.split("M").length-1<3&&(e=e.replace("MM","M"))}var a;a="datetimepicker"===this.getModuleName()?"Gregorian"===this.calendarMode?{format:t.isNullOrUndefined(this.formatString)?this.dateTimeFormat:this.formatString,type:"dateTime",skeleton:"yMd"}:{format:t.isNullOrUndefined(this.formatString)?this.dateTimeFormat:this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"}:i="Gregorian"===this.calendarMode?{format:e,type:"dateTime",skeleton:"yMd"}:{format:e,type:"dateTime",skeleton:"yMd",calendar:"islamic"};var n;"string"==typeof this.inputElement.value&&(this.inputElement.value=this.inputElement.value.trim()),"datetimepicker"===this.getModuleName()?this.checkDateValue(this.globalize.parseDate(this.inputElement.value,a))?n=this.globalize.parseDate(this.inputElement.value,a):(i="Gregorian"===this.calendarMode?{type:"dateTime",skeleton:"yMd"}:{type:"dateTime",skeleton:"yMd",calendar:"islamic"},n=this.globalize.parseDate(this.inputElement.value,i)):(n=this.globalize.parseDate(this.inputElement.value,a),!t.isNullOrUndefined(this.formatString)&&""!==this.inputElement.value&&this.strictMode&&(this.isPopupClicked||!this.isPopupClicked&&this.inputElement.value===this.previousElementValue)&&-1===this.formatString.indexOf("y")&&n.setFullYear(this.value.getFullYear())),this.strictMode&&n?(s.Input.setValue(this.globalize.formatDate(n,a),this.inputElement,this.floatLabelType,this.showClearButton),this.inputElement.value!==this.previousElementValue&&this.setProperties({value:n},!0)):this.strictMode||this.inputElement.value!==this.previousElementValue&&this.setProperties({value:n},!0),this.strictMode&&!n&&""===this.inputElement.value&&this.setProperties({value:null},!0),isNaN(+this.value)&&this.setProperties({value:null},!0),t.isNullOrUndefined(this.value)&&(this.currentDate=new Date((new Date).setHours(0,0,0,0)))},a.prototype.createCalendar=function(){var e=this;this.popupWrapper=this.createElement("div",{className:A+" "+T}),t.isNullOrUndefined(this.cssClass)||(this.popupWrapper.className+=" "+this.cssClass),t.Browser.isDevice&&(this.modelHeader(),this.modal=this.createElement("div"),this.modal.className=A+" e-date-modal",document.body.className+=" "+S,this.modal.style.display="block",document.body.appendChild(this.modal)),this.calendarElement.querySelector("table tbody").className="",this.popupObj=new i.Popup(this.popupWrapper,{content:this.calendarElement,relateTo:t.Browser.isDevice?document.body:this.inputWrapper.container,position:t.Browser.isDevice?{X:"center",Y:"center"}:{X:"left",Y:"bottom"},offsetY:4,targetType:"container",enableRtl:this.enableRtl,zIndex:this.zIndex,collision:t.Browser.isDevice?{X:"fit",Y:"fit"}:{X:"flip",Y:"flip"},open:function(){"datetimepicker"!==e.getModuleName()&&document.activeElement!==e.inputElement&&(e.defaultKeyConfigs=t.extend(e.defaultKeyConfigs,e.keyConfigs),e.calendarElement.children[1].firstElementChild.focus(),e.calendarKeyboardModules=new t.KeyboardEvents(e.calendarElement.children[1].firstElementChild,{eventName:"keydown",keyAction:e.CalendarKeyActionHandle.bind(e),keyConfigs:e.defaultKeyConfigs}),e.calendarKeyboardModules=new t.KeyboardEvents(e.inputWrapper.container.children[e.index],{eventName:"keydown",keyAction:e.CalendarKeyActionHandle.bind(e),keyConfigs:e.defaultKeyConfigs}))},close:function(){e.isDateIconClicked&&e.inputWrapper.container.children[e.index].focus(),e.value&&e.disabledDates(),e.popupObj&&e.popupObj.destroy(),t.detach(e.popupWrapper),e.popupObj=e.popupWrapper=null,e.setAriaAttributes()}}),this.popupObj.element.className+=" "+this.cssClass,this.setAriaAttributes()},a.prototype.setAriaDisabled=function(){this.enabled?(this.inputElement.setAttribute("aria-disabled","false"),this.inputElement.setAttribute("tabindex",this.tabIndex)):(this.inputElement.setAttribute("aria-disabled","true"),this.inputElement.tabIndex=-1)},a.prototype.modelHeader=function(){var e,t=this.createElement("div",{className:"e-model-header"}),i=this.createElement("h1",{className:"e-model-year"}),s=this.createElement("div"),a=this.createElement("span",{className:"e-model-day"}),n=this.createElement("span",{className:"e-model-month"});e="Gregorian"===this.calendarMode?{format:"y",skeleton:"dateTime"}:{format:"y",skeleton:"dateTime",calendar:"islamic"},i.textContent=""+this.globalize.formatDate(this.value||new Date,e),e="Gregorian"===this.calendarMode?{format:"E",skeleton:"dateTime"}:{format:"E",skeleton:"dateTime",calendar:"islamic"},a.textContent=this.globalize.formatDate(this.value||new Date,e)+", ",e="Gregorian"===this.calendarMode?{format:"MMM d",skeleton:"dateTime"}:{format:"MMM d",skeleton:"dateTime",calendar:"islamic"},n.textContent=""+this.globalize.formatDate(this.value||new Date,e),t.appendChild(i),s.appendChild(a),s.appendChild(n),t.appendChild(s),this.calendarElement.insertBefore(t,this.calendarElement.firstElementChild)},a.prototype.changeTrigger=function(e){this.inputElement.value!==this.previousElementValue&&(this.previousDate&&this.previousDate.valueOf())!==(this.value&&this.value.valueOf())&&(this.changedArgs.value=this.value,this.changedArgs.event=e||null,this.changedArgs.element=this.element,this.changedArgs.isInteracted=!t.isNullOrUndefined(e),this.trigger("change",this.changedArgs),this.previousElementValue=this.inputElement.value,this.previousDate=isNaN(+new Date(this.checkValue(this.value)))?null:new Date(this.checkValue(this.value)),this.isInteracted=!0)},a.prototype.navigatedEvent=function(){this.trigger("navigated",this.navigatedArgs)},a.prototype.changeEvent=function(e){(this.previousDate&&this.previousDate.valueOf())!==(this.value&&this.value.valueOf())&&(this.selectCalendar(e),this.changedArgs.event=e||null,this.changedArgs.element=this.element,this.changedArgs.isInteracted=this.isInteracted,this.trigger("change",this.changedArgs),this.previousDate=this.value&&new Date(+this.value),this.hide(e),this.previousElementValue=this.inputElement.value,this.errorClass())},a.prototype.requiredModules=function(){var e=[];return this&&e.push({args:[this],member:"islamic"}),e},a.prototype.selectCalendar=function(e){var i,a,n;a="datetimepicker"===this.getModuleName()&&t.isNullOrUndefined(this.formatString)?this.dateTimeFormat:this.formatString,this.value&&("datetimepicker"===this.getModuleName()?(n="Gregorian"===this.calendarMode?{format:a,type:"dateTime",skeleton:"yMd"}:{format:a,type:"dateTime",skeleton:"yMd",calendar:"islamic"},i=this.globalize.formatDate(this.changedArgs.value,n)):(n="Gregorian"===this.calendarMode?{format:this.formatString,type:"dateTime",skeleton:"yMd"}:{format:this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"},i=this.globalize.formatDate(this.changedArgs.value,n))),t.isNullOrUndefined(i)||s.Input.setValue(i,this.inputElement,this.floatLabelType,this.showClearButton)},a.prototype.isCalendar=function(){return!(!this.popupWrapper||!this.popupWrapper.classList.contains(""+T))},a.prototype.setWidth=function(e){this.inputWrapper.container.style.width="number"==typeof e?t.formatUnit(this.width):"string"==typeof e?e.match(/px|%|em/)?this.width:t.formatUnit(this.width):"100%"},a.prototype.show=function(i,s){var a=this;if(!(this.enabled&&this.readonly||!this.enabled||this.popupObj)){var n=!0,r=void 0;t.isNullOrUndefined(this.value)||+this.value>=+this.min&&+this.value<=+this.max?r=this.value||null:(r=new Date(this.checkValue(this.value)),this.setProperties({value:null},!0)),this.isCalendar()||(e.prototype.render.call(this),this.setProperties({value:r||null},!0),this.previousDate=r,this.createCalendar()),t.Browser.isDevice&&(this.mobilePopupWrapper=this.createElement("div",{className:"e-datepick-mob-popup-wrap"}),document.body.appendChild(this.mobilePopupWrapper)),this.preventArgs={preventDefault:function(){n=!1},popup:this.popupObj,event:s||null,cancel:!1,appendTo:t.Browser.isDevice?this.mobilePopupWrapper:document.body};var l=this.preventArgs;this.trigger("open",l,function(i){if(a.preventArgs=i,n&&!a.preventArgs.cancel){t.addClass(a.inputWrapper.buttons,P),a.preventArgs.appendTo.appendChild(a.popupWrapper),a.popupObj.refreshPosition(a.inputElement);var s={name:"FadeIn",duration:t.Browser.isDevice?0:300};1e3===a.zIndex?a.popupObj.show(new t.Animation(s),a.element):a.popupObj.show(new t.Animation(s),null),e.prototype.setOverlayIndex.call(a,a.mobilePopupWrapper,a.popupObj.element,a.modal,t.Browser.isDevice),a.setAriaAttributes()}else a.popupObj.destroy(),a.popupWrapper=a.popupObj=null;t.EventHandler.add(document,"mousedown touchstart",a.documentHandler,a)})}},a.prototype.hide=function(e){var i=this;if(t.isNullOrUndefined(this.popupWrapper))t.Browser.isDevice&&this.allowEdit&&!this.readonly&&this.inputElement.removeAttribute("readonly"),this.setAllowEdit();else{var s=!0;this.preventArgs={preventDefault:function(){s=!1},popup:this.popupObj,event:e||null,cancel:!1},t.removeClass(this.inputWrapper.buttons,P),t.removeClass([document.body],S);var a=this.preventArgs;this.isCalendar()?this.trigger("close",a,function(e){i.closeEventCallback(s,e)}):this.closeEventCallback(s,a)}},a.prototype.closeEventCallback=function(e,i){this.preventArgs=i,this.isCalendar()&&e&&!this.preventArgs.cancel&&(this.popupObj.hide(),this.isAltKeyPressed=!1,this.keyboardModule.destroy(),t.removeClass(this.inputWrapper.buttons,P)),this.setAriaAttributes(),t.Browser.isDevice&&this.modal&&(this.modal.style.display="none",this.modal.outerHTML="",this.modal=null),t.Browser.isDevice&&(t.isNullOrUndefined(this.mobilePopupWrapper)||(this.mobilePopupWrapper.remove(),this.mobilePopupWrapper=null)),t.EventHandler.remove(document,"mousedown touchstart",this.documentHandler),t.Browser.isDevice&&this.allowEdit&&!this.readonly&&this.inputElement.removeAttribute("readonly"),this.setAllowEdit()},a.prototype.focusIn=function(e){document.activeElement!==this.inputElement&&this.enabled&&(this.inputElement.focus(),t.addClass([this.inputWrapper.container],[U]))},a.prototype.focusOut=function(){document.activeElement===this.inputElement&&(t.removeClass([this.inputWrapper.container],[U]),this.inputElement.blur())},a.prototype.currentView=function(){var t;return this.calendarElement&&(t=e.prototype.currentView.call(this)),t},a.prototype.navigateTo=function(t,i){this.calendarElement&&e.prototype.navigateTo.call(this,t,i)},a.prototype.destroy=function(){e.prototype.destroy.call(this),this.keyboardModules.destroy(),this.popupObj&&this.popupObj.element.classList.contains("e-popup")&&e.prototype.destroy.call(this);var i={"aria-live":"assertive","aria-atomic":"true","aria-disabled":"true","aria-haspopup":"true","aria-activedescendant":"null","aria-owns":this.element.id+"_options","aria-expanded":"false",role:"combobox",autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false"};this.inputElement&&(s.Input.removeAttributes(i,this.inputElement),t.isNullOrUndefined(this.inputElementCopy.getAttribute("tabindex"))?this.inputElement.removeAttribute("tabindex"):this.inputElement.setAttribute("tabindex",this.tabIndex),t.EventHandler.remove(this.inputElement,"blur",this.inputBlurHandler),t.EventHandler.remove(this.inputElement,"focus",this.inputFocusHandler),this.ensureInputAttribute()),this.isCalendar()&&(this.popupWrapper&&t.detach(this.popupWrapper),this.popupObj=this.popupWrapper=null,this.keyboardModule.destroy()),null===this.ngTag&&(this.inputElement&&(this.inputWrapper.container.insertAdjacentElement("afterend",this.inputElement),t.removeClass([this.inputElement],["e-input"])),t.removeClass([this.element],[A]),t.detach(this.inputWrapper.container)),this.formElement&&t.EventHandler.remove(this.formElement,"reset",this.resetFormHandler)},a.prototype.ensureInputAttribute=function(){for(var e=[],i=0;i<this.inputElement.attributes.length;i++)e[i]=this.inputElement.attributes[i].name;for(i=0;i<e.length;i++)t.isNullOrUndefined(this.inputElementCopy.getAttribute(e[i]))?("value"===e[i].toLowerCase()&&(this.inputElement.value=""),this.inputElement.removeAttribute(e[i])):("value"===e[i].toLowerCase()&&(this.inputElement.value=this.inputElementCopy.getAttribute(e[i])),this.inputElement.setAttribute(e[i],this.inputElementCopy.getAttribute(e[i])))},a.prototype.preRender=function(){this.inputElementCopy=this.element.cloneNode(!0),t.removeClass([this.inputElementCopy],[A,"e-control","e-lib"]),this.inputElement=this.element,this.formElement=t.closest(this.inputElement,"form"),this.index=this.showClearButton?2:1,this.ngTag=null,"EJS-DATEPICKER"!==this.element.tagName&&"EJS-DATETIMEPICKER"!==this.element.tagName||(this.ngTag=this.element.tagName,this.inputElement=this.createElement("input"),this.element.appendChild(this.inputElement)),this.element.getAttribute("id")?null!==this.ngTag&&(this.inputElement.id=this.element.getAttribute("id")+"_input"):"datetimepicker"===this.getModuleName()?(this.element.id=t.getUniqueID("ej2-datetimepicker"),null!==this.ngTag&&t.attributes(this.inputElement,{id:this.element.id+"_input"})):(this.element.id=t.getUniqueID("ej2-datepicker"),null!==this.ngTag&&t.attributes(this.inputElement,{id:this.element.id+"_input"})),null!==this.ngTag&&this.validationAttribute(this.element,this.inputElement),this.updateHtmlAttributeToElement(),this.checkHtmlAttributes(!1),this.tabIndex=this.element.hasAttribute("tabindex")?this.element.getAttribute("tabindex"):"0",this.element.removeAttribute("tabindex"),e.prototype.preRender.call(this)},a.prototype.validationAttribute=function(e,i){var s=e.getAttribute("name")?e.getAttribute("name"):e.getAttribute("id");i.setAttribute("name",s),e.removeAttribute("name");for(var a=["required","aria-required","form"],n=0;n<a.length;n++)if(!t.isNullOrUndefined(e.getAttribute(a[n]))){var r=e.getAttribute(a[n]);i.setAttribute(a[n],r),e.removeAttribute(a[n])}},a.prototype.checkFormat=function(){var e=new t.Internationalization(this.locale);if(this.format)if("string"==typeof this.format)this.formatString=this.format;else if(""===this.format.skeleton||t.isNullOrUndefined(this.format.skeleton))"datetimepicker"===this.getModuleName()?this.formatString=this.dateTimeFormat:this.formatString=null;else{var i=this.format.skeleton;"datetimepicker"===this.getModuleName()?this.formatString=e.getDatePattern({skeleton:i,type:"dateTime"}):this.formatString=e.getDatePattern({skeleton:i,type:"date"})}else this.formatString=null},a.prototype.checkHtmlAttributes=function(e){this.globalize=new t.Internationalization(this.locale),this.checkFormat(),this.checkView();var i,s=e?t.isNullOrUndefined(this.htmlAttributes)?[]:Object.keys(this.htmlAttributes):["value","min","max","disabled","readonly","style","name","placeholder","type"];i="datetimepicker"===this.getModuleName()?"Gregorian"===this.calendarMode?{format:t.isNullOrUndefined(this.formatString)?this.dateTimeFormat:this.formatString,type:"dateTime",skeleton:"yMd"}:{format:t.isNullOrUndefined(this.formatString)?this.dateTimeFormat:this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"}:"Gregorian"===this.calendarMode?{format:this.formatString,type:"dateTime",skeleton:"yMd"}:{format:this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"};for(var a=0,n=s;a<n.length;a++){var r=n[a];if(!t.isNullOrUndefined(this.inputElement.getAttribute(r)))switch(r){case"disabled":if(t.isNullOrUndefined(this.datepickerOptions)||void 0===this.datepickerOptions.enabled||e){var l="disabled"!==this.inputElement.getAttribute(r)&&""!==this.inputElement.getAttribute(r)&&"true"!==this.inputElement.getAttribute(r);this.setProperties({enabled:l},!e)}break;case"readonly":if(t.isNullOrUndefined(this.datepickerOptions)||void 0===this.datepickerOptions.readonly||e){var o="readonly"===this.inputElement.getAttribute(r)||""===this.inputElement.getAttribute(r)||"true"===this.inputElement.getAttribute(r);this.setProperties({readonly:o},!e)}break;case"placeholder":if(t.isNullOrUndefined(this.datepickerOptions)||void 0===this.datepickerOptions.placeholder||e){this.inputElement.getAttribute(r);this.setProperties({placeholder:this.inputElement.getAttribute(r)},!e)}break;case"style":this.inputElement.setAttribute("style",""+this.inputElement.getAttribute(r));break;case"name":this.inputElement.setAttribute("name",""+this.inputElement.getAttribute(r));break;case"value":if(t.isNullOrUndefined(this.datepickerOptions)||void 0===this.datepickerOptions.value||e){var h=this.inputElement.getAttribute(r);this.setProperties(t.setValue(r,this.globalize.parseDate(h,i),{}),!e)}break;case"min":if(+this.min==+new Date(1900,0,1)||e){var u=this.inputElement.getAttribute(r);this.setProperties(t.setValue(r,this.globalize.parseDate(u),{}),!e)}break;case"max":if(+this.max==+new Date(2099,11,31)||e){var d=this.inputElement.getAttribute(r);this.setProperties(t.setValue(r,this.globalize.parseDate(d),{}),!e)}break;case"type":"text"!==this.inputElement.getAttribute(r)&&this.inputElement.setAttribute("type","text")}}},a.prototype.getModuleName=function(){return"datepicker"},a.prototype.disabledDates=function(){var i,a;i=this.checkDateValue(this.value)?new Date(+this.value):new Date(this.checkValue(this.value));var n=this.previousDate;this.minMaxUpdates(),e.prototype.render.call(this),this.previousDate=n;var r='*[id^="/id"]'.replace("/id",""+(i&&+i));this.strictMode||("string"==typeof this.value||"object"==typeof this.value&&+this.value!=+i)&&this.setProperties({value:i},!0),t.isNullOrUndefined(this.calendarElement.querySelectorAll(r)[0])||this.calendarElement.querySelectorAll(r)[0].classList.contains("e-disabled")&&(this.strictMode||(this.currentDate=new Date((new Date).setHours(0,0,0,0))));var l;"datetimepicker"===this.getModuleName()?l="Gregorian"===this.calendarMode?this.globalize.formatDate(i,{format:t.isNullOrUndefined(this.formatString)?this.dateTimeFormat:this.formatString,type:"dateTime",skeleton:"yMd"}):this.globalize.formatDate(i,{format:t.isNullOrUndefined(this.formatString)?this.dateTimeFormat:this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"}):(a="Gregorian"===this.calendarMode?{format:this.formatString,type:"dateTime",skeleton:"yMd"}:{format:this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"},l=this.globalize.formatDate(i,a)),this.popupObj||s.Input.setValue(l,this.inputElement,this.floatLabelType,this.showClearButton)},a.prototype.setAriaAttributes=function(){this.isCalendar()?(s.Input.addAttributes({"aria-expanded":"true"},this.inputElement),t.attributes(this.inputElement,{"aria-activedescendant":""+this.setActiveDescendant()})):(s.Input.addAttributes({"aria-expanded":"false"},this.inputElement),t.attributes(this.inputElement,{"aria-activedescendant":"null"}))},a.prototype.errorClass=function(){var e='*[id^="/id"]'.replace("/id",""+ +this.value),i=this.calendarElement&&this.calendarElement.querySelectorAll(e)[0]&&this.calendarElement.querySelectorAll(e)[0].classList.contains("e-disabled");!t.isNullOrUndefined(this.value)&&!(+new Date(+this.value).setMilliseconds(0)>=+this.min&&+new Date(+this.value).setMilliseconds(0)<=+this.max)||!this.strictMode&&""!==this.inputElement.value&&t.isNullOrUndefined(this.value)||i?(t.addClass([this.inputWrapper.container],"e-error"),t.attributes(this.inputElement,{"aria-invalid":"true"})):(t.removeClass([this.inputWrapper.container],"e-error"),t.attributes(this.inputElement,{"aria-invalid":"false"}))},a.prototype.onPropertyChanged=function(i,a){"Gregorian"===this.calendarMode?this.formatString:this.formatString;for(var n=0,r=Object.keys(i);n<r.length;n++){switch(r[n]){case"value":this.isInteracted=!1,this.invalidValueString=null,this.checkInvalidValue(i.value),i.value=this.value,this.previousElementValue=this.inputElement.value,t.isNullOrUndefined(this.value)&&(s.Input.setValue("",this.inputElement,this.floatLabelType,this.showClearButton),this.currentDate=new Date((new Date).setHours(0,0,0,0))),this.updateInput(),+this.previousDate!=+this.value&&this.changeTrigger(null);break;case"format":this.checkFormat(),this.bindInputEvent(),this.updateInput();break;case"allowEdit":this.setAllowEdit();break;case"placeholder":s.Input.setPlaceholder(this.placeholder,this.inputElement);break;case"readonly":s.Input.setReadonly(this.readonly,this.inputElement);break;case"enabled":s.Input.setEnabled(this.enabled,this.inputElement),this.setAriaDisabled(),this.bindEvents();break;case"htmlAttributes":this.updateHtmlAttributeToElement(),this.updateHtmlAttributeToWrapper(),this.checkHtmlAttributes(!0);break;case"locale":this.globalize=new t.Internationalization(this.locale),this.l10n.setLocale(this.locale),this.setProperties({placeholder:this.l10n.getConstant("placeholder")},!0),s.Input.setPlaceholder(this.placeholder,this.inputElement),this.updateInput();break;case"enableRtl":s.Input.setEnableRtl(this.enableRtl,[this.inputWrapper.container]);break;case"start":case"depth":this.checkView(),this.calendarElement&&e.prototype.onPropertyChanged.call(this,i,a);break;case"zIndex":this.setProperties({zIndex:i.zIndex},!0);break;case"cssClass":s.Input.setCssClass(i.cssClass,[this.inputWrapper.container],a.cssClass),this.popupWrapper&&s.Input.setCssClass(i.cssClass,[this.popupWrapper],a.cssClass);break;case"showClearButton":s.Input.setClearButton(this.showClearButton,this.inputElement,this.inputWrapper),this.bindClearEvent();break;case"strictMode":this.invalidValueString=null,this.updateInput();break;case"width":this.setWidth(i.width);break;case"floatLabelType":this.floatLabelType=i.floatLabelType,s.Input.removeFloating(this.inputWrapper),s.Input.addFloating(this.inputElement,this.floatLabelType,this.placeholder);break;default:this.calendarElement&&e.prototype.onPropertyChanged.call(this,i,a)}this.hide(null)}},x([t.Property(null)],a.prototype,"width",void 0),x([t.Property(null)],a.prototype,"cssClass",void 0),x([t.Property(!1)],a.prototype,"strictMode",void 0),x([t.Property(null)],a.prototype,"format",void 0),x([t.Property(!0)],a.prototype,"enabled",void 0),x([t.Property({})],a.prototype,"htmlAttributes",void 0),x([t.Property(null)],a.prototype,"values",void 0),x([t.Property(!1)],a.prototype,"isMultiSelection",void 0),x([t.Property(!0)],a.prototype,"showClearButton",void 0),x([t.Property(!0)],a.prototype,"allowEdit",void 0),x([t.Property(null)],a.prototype,"keyConfigs",void 0),x([t.Property(!1)],a.prototype,"enablePersistence",void 0),x([t.Property(1e3)],a.prototype,"zIndex",void 0),x([t.Property(!1)],a.prototype,"readonly",void 0),x([t.Property(null)],a.prototype,"placeholder",void 0),x([t.Property("Never")],a.prototype,"floatLabelType",void 0),x([t.Event()],a.prototype,"open",void 0),x([t.Event()],a.prototype,"close",void 0),x([t.Event()],a.prototype,"blur",void 0),x([t.Event()],a.prototype,"focus",void 0),x([t.Event()],a.prototype,"created",void 0),x([t.Event()],a.prototype,"destroyed",void 0),a=x([t.NotifyPropertyChanges],a)}(C),B=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(t,i)};return function(t,i){function s(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(s.prototype=i.prototype,new s)}}(),j=function(e,t,i,s){var a,n=arguments.length,r=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,i,s);else for(var l=e.length-1;l>=0;l--)(a=e[l])&&(r=(n<3?a(r):n>3?a(t,i,r):a(t,i))||r);return n>3&&r&&Object.defineProperty(t,i,r),r},Y="e-left-calendar",R="e-right-calendar",z="e-daterangepicker",q="e-active",K="e-start-date",_="e-end-date",G="e-input-focus",X="e-range-hover",Z="e-other-month",J="e-start-label",$="e-end-label",Q="e-disabled",ee="e-selected",te="e-calendar",ie="e-header",se="e-title",ae="e-icon-container",ne="e-date-range-container",re="e-presets",le="e-focused-date",oe="e-content",he="e-day-span",ue="e-week-number",de="e-date-disabled",pe="e-icon-disabled",ce="e-overlay",me=n.cssClass.li,ve="e-hover",fe="e-range-overflow",ye="e-non-edit",ge=["title","class","style"],be=function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return B(i,e),j([t.Property()],i.prototype,"label",void 0),j([t.Property()],i.prototype,"start",void 0),j([t.Property()],i.prototype,"end",void 0),i}(t.ChildProperty),De=function(e){function r(t,i){var s=e.call(this,t,i)||this;return s.isCustomRange=!1,s.isCustomWindow=!1,s.presetsItem=[],s.liCollections=[],s.previousEleValue="",s.isKeyPopup=!1,s.dateDisabled=!1,s.isRangeIconClicked=!1,s.isMaxDaysClicked=!1,s.disabledDays=[],s.preventBlur=!1,s.preventFocus=!1,s.invalidValueString=null,s.dateRangeOptions=t,s}return B(r,e),r.prototype.render=function(){this.initialize(),this.setProperties({startDate:this.startValue},!0),this.setProperties({endDate:this.endValue},!0),this.setModelValue(),this.renderComplete()},r.prototype.preRender=function(){if(this.keyInputConfigs={altDownArrow:"alt+downarrow",escape:"escape",enter:"enter",tab:"tab",altRightArrow:"alt+rightarrow",altLeftArrow:"alt+leftarrow",moveUp:"uparrow",moveDown:"downarrow",spacebar:"space"},this.defaultConstant={placeholder:this.placeholder,startLabel:"Start Date",endLabel:"End Date",customRange:"Custom Range",applyText:"Apply",cancelText:"Cancel",selectedDays:"Selected Days",days:"days"},this.isMobile=window.matchMedia("(max-width:550px)").matches,this.inputElement=this.element,this.angularTag=null,"EJS-DATERANGEPICKER"===this.element.tagName&&(this.angularTag=this.element.tagName,this.inputElement=this.createElement("input"),this.element.appendChild(this.inputElement)),this.cloneElement=this.element.cloneNode(!0),t.removeClass([this.cloneElement],[z,"e-control","e-lib"]),this.updateHtmlAttributeToElement(),this.element.getAttribute("id")?null!==this.angularTag&&(this.inputElement.id=this.element.getAttribute("id")+"_input"):(this.element.id=t.getUniqueID("ej2-datetimepicker"),null!==this.angularTag&&t.attributes(this.inputElement,{id:this.element.id+"_input"})),this.checkInvalidRange(this.value),!this.invalidValueString&&"string"==typeof this.value){var i=this.value.split(" "+this.separator+" ");this.value=[new Date(i[0]),new Date(i[1])]}this.initProperty(),this.tabIndex=this.element.hasAttribute("tabindex")?this.element.getAttribute("tabindex"):"0",this.element.removeAttribute("tabindex"),e.prototype.preRender.call(this),this.navNextFunction=this.navNextMonth.bind(this),this.navPrevFunction=this.navPrevMonth.bind(this),this.deviceNavNextFunction=this.deviceNavNext.bind(this),this.deviceNavPrevFunction=this.deviceNavPrevious.bind(this),this.initStartDate=this.checkDateValue(this.startValue),this.initEndDate=this.checkDateValue(this.endValue),this.formElement=t.closest(this.element,"form")},r.prototype.updateValue=function(){this.formatString;this.value&&this.value.length>0?(this.value[0]instanceof Date&&!isNaN(+this.value[0])?(this.setProperties({startDate:this.value[0]},!0),this.startValue=this.value[0]):"string"==typeof this.value[0]?0==+this.value[0]||isNaN(+new Date(this.checkValue(this.value[0])))?(this.startValue=null,this.setValue()):(this.setProperties({startDate:new Date(this.checkValue(this.value[0]))},!0),this.startValue=new Date(this.checkValue(this.value[0]))):(this.startValue=null,this.setValue()),this.value[1]instanceof Date&&!isNaN(+this.value[1])?(this.setProperties({endDate:this.value[1]},!0),this.endValue=this.value[1]):"string"==typeof this.value[1]?0==+this.value[0]||isNaN(+new Date(this.checkValue(this.value[0])))?(this.setProperties({endDate:null},!0),this.endValue=null,this.setValue()):(this.setProperties({endDate:new Date(this.checkValue(this.value[1]))},!0),this.endValue=new Date(this.checkValue(this.value[1])),this.setValue()):(this.setProperties({endDate:null},!0),this.endValue=null,this.setValue())):this.value&&this.value.start?(this.value.start instanceof Date&&!isNaN(+this.value.start)?(this.setProperties({startDate:this.value.start},!0),this.startValue=this.value.start):"string"==typeof this.value.start?(this.setProperties({startDate:new Date(this.checkValue(this.value.start))},!0),this.startValue=new Date(this.checkValue(this.value.start))):(this.startValue=null,this.setValue()),this.value.end instanceof Date&&!isNaN(+this.value.end)?(this.setProperties({endDate:this.value.end},!0),this.endValue=this.value.end):"string"==typeof this.value.end?(this.setProperties({endDate:new Date(this.checkValue(this.value.end))},!0),this.endValue=new Date(this.checkValue(this.value.end)),this.setValue()):(this.setProperties({endDate:null},!0),this.endValue=null,this.setValue())):t.isNullOrUndefined(this.value)&&(this.endValue=this.checkDateValue(new Date(this.checkValue(this.endDate))),this.startValue=this.checkDateValue(new Date(this.checkValue(this.startDate))),this.setValue())},r.prototype.initProperty=function(){this.globalize=new t.Internationalization(this.locale),this.checkFormat(),this.checkView(),(t.isNullOrUndefined(this.firstDayOfWeek)||this.firstDayOfWeek>6||this.firstDayOfWeek<0)&&this.setProperties({firstDayOfWeek:this.globalize.getFirstDayOfWeek()},!0),this.updateValue()},r.prototype.checkFormat=function(){if(this.format)if("string"==typeof this.format)this.formatString=this.format;else if(""===this.format.skeleton||t.isNullOrUndefined(this.format.skeleton))this.formatString=null;else{var e=this.format.skeleton;this.formatString=this.globalize.getDatePattern({skeleton:e,type:"date"})}else this.formatString=null},r.prototype.initialize=function(){null!==this.angularTag&&this.validationAttribute(this.element,this.inputElement),this.checkHtmlAttributes(!1),t.merge(this.defaultKeyConfigs,{shiftTab:"shift+tab"});var e=this.checkDateValue(new Date(this.checkValue(this.startValue)));this.setProperties({startDate:e},!0),this.setProperties({endValue:this.checkDateValue(new Date(this.checkValue(this.endValue)))},!0),this.setValue(),this.setProperties({min:this.checkDateValue(new Date(this.checkValue(this.min)))},!0),this.setProperties({max:this.checkDateValue(new Date(this.checkValue(this.max)))},!0),this.l10n=new t.L10n("daterangepicker",this.defaultConstant,this.locale),this.l10n.setLocale(this.locale),this.setProperties({placeholder:this.placeholder||this.l10n.getConstant("placeholder")},!0),this.processPresets(),this.createInput(),this.updateHtmlAttributeToWrapper(),this.setRangeAllowEdit(),this.bindEvents()},r.prototype.setRangeAllowEdit=function(){this.allowEdit?this.readonly||this.inputElement.removeAttribute("readonly"):t.attributes(this.inputElement,{readonly:""}),this.updateClearIconState()},r.prototype.updateClearIconState=function(){this.allowEdit||!this.inputWrapper||this.readonly?this.inputWrapper&&t.removeClass([this.inputWrapper.container],[ye]):""===this.inputElement.value?t.removeClass([this.inputWrapper.container],[ye]):t.addClass([this.inputWrapper.container],[ye])},r.prototype.validationAttribute=function(e,i){var s=e.getAttribute("name")?e.getAttribute("name"):e.getAttribute("id");i.setAttribute("name",s),e.removeAttribute("name");for(var a=["required","aria-required","form"],n=0;n<a.length;n++)if(!t.isNullOrUndefined(e.getAttribute(a[n]))){var r=e.getAttribute(a[n]);i.setAttribute(a[n],r),e.removeAttribute(a[n])}},r.prototype.updateHtmlAttributeToWrapper=function(){if(!t.isNullOrUndefined(this.htmlAttributes))for(var e=0,i=Object.keys(this.htmlAttributes);e<i.length;e++){var s=i[e];if(ge.indexOf(s)>-1)if("class"===s)t.addClass([this.inputWrapper.container],this.htmlAttributes[s].split(" "));else if("style"===s){var a=this.inputWrapper.container.getAttribute(s);a=t.isNullOrUndefined(a)?this.htmlAttributes[s]:a+this.htmlAttributes[s],this.inputWrapper.container.setAttribute(s,a)}else this.inputWrapper.container.setAttribute(s,this.htmlAttributes[s])}},r.prototype.updateHtmlAttributeToElement=function(){if(!t.isNullOrUndefined(this.htmlAttributes))for(var e=0,i=Object.keys(this.htmlAttributes);e<i.length;e++){var s=i[e];ge.indexOf(s)<0&&this.inputElement.setAttribute(s,this.htmlAttributes[s])}},r.prototype.processPresets=function(){this.presetsItem=[];var e=0;if(!t.isUndefined(this.presets[0].start&&this.presets[0].end&&this.presets[0].label)){for(var i=0,s=this.presets;i<s.length;i++){var a=s[i],n=a.label.replace(/\s+/g,"")+"_"+ ++e;"string"==typeof a.end?this.presetsItem.push({id:n,text:a.label,end:new Date(this.checkValue(a.end)),start:new Date(this.checkValue(a.start))}):this.presetsItem.push({id:n,text:a.label,start:a.start,end:a.end})}var r=t.isNullOrUndefined(this.startValue)?null:new Date(+this.startValue),l=t.isNullOrUndefined(this.endValue)?null:new Date(+this.endValue);this.presetsItem.push({id:"custom_range",text:this.l10n.getConstant("customRange"),start:r,end:l}),t.isNullOrUndefined(this.startValue)||t.isNullOrUndefined(this.endValue)||(this.isCustomRange=!0,this.activeIndex=this.presetsItem.length-1)}},r.prototype.bindEvents=function(){this.enabled?(t.EventHandler.add(this.inputWrapper.buttons[0],"mousedown",this.rangeIconHandler,this),t.EventHandler.add(this.inputElement,"focus",this.inputFocusHandler,this),t.EventHandler.add(this.inputElement,"blur",this.inputBlurHandler,this),t.EventHandler.add(this.inputElement,"change",this.inputChangeHandler,this),this.showClearButton&&this.inputWrapper.clearButton&&t.EventHandler.add(this.inputWrapper.clearButton,"mousedown",this.resetHandler,this),this.isMobile||(this.keyInputConfigs=t.extend(this.keyInputConfigs,this.keyConfigs),this.inputKeyboardModule=new t.KeyboardEvents(this.inputElement,{eventName:"keydown",keyAction:this.inputHandler.bind(this),keyConfigs:this.keyInputConfigs})),this.formElement&&t.EventHandler.add(this.formElement,"reset",this.formResetHandler,this),this.inputElement.setAttribute("tabindex",this.tabIndex)):(t.EventHandler.remove(this.inputWrapper.buttons[0],"mousedown",this.rangeIconHandler),t.EventHandler.remove(this.inputElement,"blur",this.inputBlurHandler),t.EventHandler.remove(this.inputElement,"focus",this.inputFocusHandler),t.EventHandler.remove(this.inputElement,"change",this.inputChangeHandler),this.showClearButton&&this.inputWrapper.clearButton&&t.EventHandler.remove(this.inputWrapper.clearButton,"mousedown touchstart",this.resetHandler),this.isMobile||t.isNullOrUndefined(this.inputKeyboardModule)||this.inputKeyboardModule.destroy(),this.formElement&&t.EventHandler.remove(this.formElement,"reset",this.formResetHandler),this.inputElement.tabIndex=-1)},r.prototype.updateHiddenInput=function(){if(this.firstHiddenChild&&this.secondHiddenChild){var e={type:"datetime",skeleton:"yMd"};"string"==typeof this.startDate&&(this.startDate=this.globalize.parseDate(this.startDate,e)),"string"==typeof this.endDate&&(this.endDate=this.globalize.parseDate(this.endDate,e)),this.firstHiddenChild.value=this.startDate&&this.globalize.formatDate(this.startDate,e)||this.inputElement.value,this.secondHiddenChild.value=this.endDate&&this.globalize.formatDate(this.endDate,e)||this.inputElement.value,this.dispatchEvent(this.firstHiddenChild,"focusout"),this.dispatchEvent(this.firstHiddenChild,"change")}},r.prototype.inputChangeHandler=function(e){e.stopPropagation(),this.updateHiddenInput()},r.prototype.bindClearEvent=function(){this.showClearButton&&this.inputWrapper.clearButton&&t.EventHandler.add(this.inputWrapper.clearButton,"mousedown",this.resetHandler,this)},r.prototype.resetHandler=function(e){this.valueType=this.value,e.preventDefault(),this.clear(),this.changeTrigger(e),this.clearRange(),this.hide(e)},r.prototype.restoreValue=function(){this.previousEleValue=this.inputElement.value,this.previousStartValue=this.startValue,this.previousEndValue=this.endValue,this.valueType=null,this.initStartDate=this.checkDateValue(this.startValue),this.initEndDate=this.checkDateValue(this.endValue),this.setValue(),this.setModelValue()},r.prototype.formResetHandler=function(e){if(this.formElement&&e.target===this.formElement&&!this.inputElement.disabled){var i=this.inputElement.getAttribute("value");t.isNullOrUndefined(this.startCopy)?(this.setProperties({value:null,startDate:null,endDate:null},!0),this.startValue=this.endValue=null):(t.isNullOrUndefined(this.value)||t.isNullOrUndefined(this.value.start)?(this.setProperties({value:[this.startCopy,this.endCopy]},!0),this.startValue=this.value[0],this.endValue=this.value[1]):(this.setProperties({value:{start:this.startCopy,end:this.endCopy}},!0),this.startValue=this.value.start,this.endValue=this.value.end),this.setProperties({startDate:this.startValue,endDate:this.endValue},!0)),"EJS-DATERANGEPICKER"===this.element.tagName&&(this.setProperties({value:null,startDate:null,endDate:null},!0),i="",this.startValue=this.endValue=null,this.inputElement.setAttribute("value","")),this.restoreValue(),this.inputElement&&(s.Input.setValue(i,this.inputElement,this.floatLabelType,this.showClearButton),this.errorClass())}},r.prototype.clear=function(){null!==this.startValue&&(this.startValue=null),null!==this.endValue&&(this.endValue=null),this.value&&this.value.start&&this.setProperties({value:{start:null,end:null}},!0),null!==this.value&&this.value.length>0&&this.setProperties({value:null},!0),s.Input.setValue("",this.inputElement,this.floatLabelType,this.showClearButton),t.isNullOrUndefined(this.applyButton)||(this.applyButton.disabled=this.applyButton.element.disabled=!0),this.removeSelection()},r.prototype.rangeIconHandler=function(e){this.isMobile&&this.inputElement.setAttribute("readonly",""),e.preventDefault(),this.targetElement=null,this.isPopupOpen()?this.applyFunction(e):(this.isRangeIconClicked=!0,this.inputWrapper.container.children[0].focus(),this.show(null,e),this.isMobile||t.isNullOrUndefined(this.leftCalendar)||(this.isRangeIconClicked=!1,this.calendarFocus(),this.isRangeIconClicked=!0),t.addClass([this.inputWrapper.container],[G]))},r.prototype.checkHtmlAttributes=function(e){this.globalize=new t.Internationalization(this.locale);for(var i=e?t.isNullOrUndefined(this.htmlAttributes)?[]:Object.keys(this.htmlAttributes):["startDate","endDate","minDays","maxDays","min","max","disabled","readonly","style","name","placeholder","type","value"],s={format:this.formatString,type:"date",skeleton:"yMd"},a=0,n=i;a<n.length;a++){var r=n[a];if(!t.isNullOrUndefined(this.inputElement.getAttribute(r)))switch(r){case"disabled":if(t.isNullOrUndefined(this.dateRangeOptions)||void 0===this.dateRangeOptions.enabled||e){var l="disabled"===this.inputElement.getAttribute(r)||""===this.inputElement.getAttribute(r)||"true"===this.inputElement.getAttribute(r);this.setProperties({enabled:!l},!e)}break;case"readonly":if(t.isNullOrUndefined(this.dateRangeOptions)||void 0===this.dateRangeOptions.readonly||e){var o="readonly"===this.inputElement.getAttribute(r)||"true"===this.inputElement.getAttribute(r)||""===this.inputElement.getAttribute(r);this.setProperties({readonly:o},!e)}break;case"placeholder":(t.isNullOrUndefined(this.dateRangeOptions)||void 0===this.dateRangeOptions.placeholder||e)&&this.setProperties({placeholder:this.inputElement.getAttribute(r)},!e);break;case"value":if(t.isNullOrUndefined(this.dateRangeOptions)||void 0===this.dateRangeOptions.value||e){var h=this.inputElement.getAttribute(r);this.setProperties(t.setValue(r,h,{}),!e)}break;case"style":this.inputElement.setAttribute("style",""+this.inputElement.getAttribute(r));break;case"min":if(t.isNullOrUndefined(this.min)||+this.min==+new Date(1900,0,1)||e){var u=this.globalize.parseDate(this.inputElement.getAttribute(r),s);this.setProperties(t.setValue(r,u,{}),!e)}break;case"name":this.inputElement.setAttribute("name",""+this.inputElement.getAttribute(r));break;case"max":if(t.isNullOrUndefined(this.max)||+this.max==+new Date(2099,11,31)||e){u=this.globalize.parseDate(this.inputElement.getAttribute(r),s);this.setProperties(t.setValue(r,u,{}),!e)}break;case"startDate":if(t.isNullOrUndefined(this.startDate)){u=this.globalize.parseDate(this.inputElement.getAttribute(r),s);this.startValue=u,this.setValue()}break;case"endDate":if(t.isNullOrUndefined(this.endDate)){u=this.globalize.parseDate(this.inputElement.getAttribute(r),s);this.endValue=u,this.setValue()}break;case"minDays":t.isNullOrUndefined(this.minDays)&&this.setProperties(t.setValue(r,parseInt(this.inputElement.getAttribute(r),10),{}),!0);break;case"maxDays":t.isNullOrUndefined(this.maxDays)&&this.setProperties(t.setValue(r,parseInt(this.inputElement.getAttribute(r),10),{}),!0);break;case"type":"text"!==this.inputElement.getAttribute(r)&&this.inputElement.setAttribute("type","text")}}},r.prototype.createPopup=function(){for(var e=0;e<this.presetsItem.length;e++)e!==this.presetsItem.length-1&&"custom_range"===this.presetsItem[e].id&&this.presetsItem.splice(e,1);this.activeIndex=this.presetsItem.length-1,this.isCustomRange=!0;for(e=0;e<=this.presetsItem.length-2;e++){var i=this.presetsItem[e].start,s=this.presetsItem[e].end;this.startValue&&this.endValue&&+i.setMilliseconds(0)==+this.startValue.setMilliseconds(0)&&+s.setMilliseconds(0)==+this.endValue.setMilliseconds(0)&&(this.activeIndex=e,this.isCustomRange=!1)}this.popupWrapper=t.createElement("div",{id:this.element.id+"_popup",className:z+" e-popup"}),this.adjustLongHeaderWidth();var a=!this.isCustomRange||this.isMobile;!t.isUndefined(this.presets[0].start&&this.presets[0].end&&this.presets[0].label)&&a?(this.isCustomWindow=!1,this.createPresets(),this.listRippleEffect(),this.renderPopup()):(this.isCustomWindow=!0,this.renderControl())},r.prototype.renderControl=function(){this.createControl(),this.bindCalendarEvents(),this.updateRange(this.isMobile?[this.calendarElement]:[this.leftCalendar,this.rightCalendar]),t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)||this.disabledDateRender(),this.updateHeader()},r.prototype.clearCalendarEvents=function(){t.EventHandler.clearEvents(this.leftCalPrevIcon),t.EventHandler.clearEvents(this.leftCalNextIcon),t.EventHandler.clearEvents(this.rightCalPrevIcon),t.EventHandler.clearEvents(this.rightCalNextIcon)},r.prototype.updateNavIcons=function(){if(this.isPopupOpen()&&this.depth===this.currentView()){var e=new Date(this.checkValue(this.leftCalCurrentDate)),t=!1;"Year"===this.currentView()?t=this.compareYears(e,this.rightCalCurrentDate)<1:"Decade"===this.currentView()?t=this.compareDecades(e,this.rightCalCurrentDate)<1:"Month"===this.currentView()&&(t=this.compareMonths(e,this.rightCalCurrentDate)<1),this.previousIcon=this.rightCalPrevIcon,this.nextIcon=this.leftCalNextIcon,this.nextIconHandler(t),this.previousIconHandler(t)}},r.prototype.calendarIconEvent=function(){this.clearCalendarEvents(),this.leftCalPrevIcon&&!this.leftCalPrevIcon.classList.contains(Q)&&t.EventHandler.add(this.leftCalPrevIcon,"mousedown",this.navPrevFunction),this.leftCalNextIcon&&!this.leftCalNextIcon.classList.contains(Q)&&t.EventHandler.add(this.leftCalNextIcon,"mousedown",this.navNextFunction),this.rightCalPrevIcon&&!this.rightCalPrevIcon.classList.contains(Q)&&t.EventHandler.add(this.rightCalPrevIcon,"mousedown",this.navPrevFunction),this.rightCalNextIcon&&!this.rightCalNextIcon.classList.contains(Q)&&t.EventHandler.add(this.rightCalNextIcon,"mousedown",this.navNextFunction)},r.prototype.bindCalendarEvents=function(){this.isMobile?(this.deviceCalendarEvent(),t.EventHandler.add(this.startButton.element,"click",this.deviceHeaderClick,this),t.EventHandler.add(this.endButton.element,"click",this.deviceHeaderClick,this)):(this.updateNavIcons(),this.calendarIconEvent(),this.calendarIconRipple(),this.headerTitleElement=this.popupObj.element.querySelector("."+R+" ."+ie+" ."+se),this.headerTitleElement=this.popupObj.element.querySelector("."+Y+" ."+ie+" ."+se),this.defaultKeyConfigs=t.extend(this.defaultKeyConfigs,this.keyConfigs),this.leftKeyboardModule=new t.KeyboardEvents(this.leftCalendar,{eventName:"keydown",keyAction:this.keyInputHandler.bind(this),keyConfigs:this.defaultKeyConfigs}),this.rightKeyboardModule=new t.KeyboardEvents(this.rightCalendar,{eventName:"keydown",keyAction:this.keyInputHandler.bind(this),keyConfigs:this.defaultKeyConfigs})),this.start===this.depth&&this.bindCalendarCellEvents(),this.removeFocusedDate()},r.prototype.calendarIconRipple=function(){t.rippleEffect(this.leftCalPrevIcon,{selector:".e-prev",duration:400,isCenterRipple:!0}),t.rippleEffect(this.leftCalNextIcon,{selector:".e-next",duration:400,isCenterRipple:!0}),t.rippleEffect(this.rightCalPrevIcon,{selector:".e-prev",duration:400,isCenterRipple:!0}),t.rippleEffect(this.rightCalNextIcon,{selector:".e-next",duration:400,isCenterRipple:!0})},r.prototype.deviceCalendarEvent=function(){t.EventHandler.clearEvents(this.nextIcon),t.EventHandler.clearEvents(this.previousIcon),t.rippleEffect(this.nextIcon,{selector:".e-prev",duration:400,isCenterRipple:!0}),t.rippleEffect(this.previousIcon,{selector:".e-next",duration:400,isCenterRipple:!0}),this.nextIcon&&!this.nextIcon.classList.contains(Q)&&t.EventHandler.add(this.nextIcon,"mousedown",this.deviceNavNextFunction),this.previousIcon&&!this.previousIcon.classList.contains(Q)&&t.EventHandler.add(this.previousIcon,"mousedown",this.deviceNavPrevFunction)},r.prototype.deviceNavNext=function(e){var i=t.closest(e.target,"."+te);this.updateDeviceCalendar(i),this.navigateNext(e),this.deviceNavigation()},r.prototype.deviceNavPrevious=function(e){var i=t.closest(e.target,"."+te);this.updateDeviceCalendar(i),this.navigatePrevious(e),this.deviceNavigation()},r.prototype.updateDeviceCalendar=function(e){e&&(this.previousIcon=e.querySelector(".e-prev"),this.nextIcon=e.querySelector(".e-next"),this.calendarElement=e,this.deviceCalendar=e,this.contentElement=e.querySelector("."+oe),this.tableBodyElement=t.select(".e-content tbody",e),this.table=e.querySelector("."+oe).getElementsByTagName("table")[0],this.headerTitleElement=e.querySelector(".e-header ."+se),this.headerElement=e.querySelector("."+ie))},r.prototype.deviceHeaderClick=function(e){if(e.currentTarget.classList.contains("e-start-btn")&&!t.isNullOrUndefined(this.startValue)){this.endButton.element.classList.remove(q),this.startButton.element.classList.add(q);var i=this.popupObj.element.querySelector("."+te);this.updateDeviceCalendar(i),t.isNullOrUndefined(this.calendarElement.querySelector("."+K+":not(.e-other-month)"))&&(this.currentDate=new Date(+this.startValue),t.remove(this.tableBodyElement),this.createContentBody(),this.deviceNavigation()),this.removeClassDisabled()}else if(!t.isNullOrUndefined(this.startValue)&&!t.isNullOrUndefined(this.endValue)){this.startButton.element.classList.remove(q),this.endButton.element.classList.add(q);i=this.popupObj.element.querySelector("."+te);this.updateDeviceCalendar(i),t.isNullOrUndefined(this.calendarElement.querySelector("."+_+":not(.e-other-month)"))&&(this.currentDate=new Date(+this.endValue),t.remove(this.tableBodyElement),this.createContentBody(),this.deviceNavigation()),this.updateMinMaxDays(this.popupObj.element.querySelector("."+te)),this.selectableDates()}},r.prototype.inputFocusHandler=function(){this.preventBlur=!1;var e={model:this};this.preventFocus||(this.preventFocus=!0,this.trigger("focus",e)),this.updateClearIconState(),this.updateHiddenInput()},r.prototype.inputBlurHandler=function(e){if(!this.preventBlur){var i=this.inputElement.value;if(t.isNullOrUndefined(this.presetsItem)||this.presetsItem.length>0&&this.previousEleValue!==this.inputElement.value&&(this.activeIndex=this.presetsItem.length-1,this.isCustomRange=!0),!t.isNullOrUndefined(i)&&""!==i.trim()){var a=i.split(" "+this.separator+" ");if(a.length>1){this.invalidValueString=null;var n={format:this.formatString,type:"date",skeleton:"yMd"},r=this.globalize.parseDate(a[0].trim(),n),l=this.globalize.parseDate(a[1].trim(),n);if(!(t.isNullOrUndefined(r)||isNaN(+r)||t.isNullOrUndefined(l)||isNaN(+l))){if(this.startValue=r,this.endValue=l,this.setValue(),this.refreshControl(),i!==this.previousEleValue&&this.changeTrigger(e),!this.preventBlur&&document.activeElement!==this.inputElement){this.preventFocus=!1;var o={model:this};this.trigger("blur",o)}return void this.updateHiddenInput()}this.strictMode||(this.startValue=null,this.endValue=null,this.setValue())}else this.strictMode||(this.startValue=null,this.endValue=null,this.setValue())}if(this.strictMode?(t.isNullOrUndefined(i)||""!==i.trim()||(this.startValue=null,this.endValue=null),s.Input.setValue("",this.inputElement,this.floatLabelType,this.showClearButton),this.updateInput()):(this.clearRange(),this.startValue=null,this.endValue=null,this.setValue()),this.errorClass(),this.changeTrigger(e),!this.preventBlur&&document.activeElement!==this.inputElement){this.preventFocus=!1;o={model:this};this.trigger("blur",o)}}this.updateHiddenInput()},r.prototype.clearRange=function(){this.previousStartValue=this.previousEndValue=null,this.currentDate=null},r.prototype.errorClass=function(){var e=this.inputElement.value.trim();(t.isNullOrUndefined(this.endValue)&&t.isNullOrUndefined(this.startValue)&&""!==e||!t.isNullOrUndefined(this.startValue)&&+this.startValue<+this.min||!t.isNullOrUndefined(this.startValue)&&!t.isNullOrUndefined(this.endValue)&&+this.startValue>+this.endValue||!t.isNullOrUndefined(this.endValue)&&+this.endValue>+this.max||this.startValue&&this.isDateDisabled(this.startValue)||this.endValue&&this.isDateDisabled(this.endValue))&&""!==e?(t.addClass([this.inputWrapper.container],"e-error"),t.attributes(this.inputElement,{"aria-invalid":"true"})):this.inputWrapper&&(t.removeClass([this.inputWrapper.container],"e-error"),t.attributes(this.inputElement,{"aria-invalid":"false"}))},r.prototype.keyCalendarUpdate=function(e,t){return this.removeFocusedDate(),e?(this.leftCalCurrentDate=new Date(+this.currentDate),t=this.leftCalendar):(this.rightCalCurrentDate=new Date(+this.currentDate),t=this.rightCalendar),this.updateCalendarElement(t),this.table.focus(),t},r.prototype.navInCalendar=function(e,i,s,a,n){var r,l,o=this.getViewNumber(this.currentView()),h=this.min;switch(l=t.isNullOrUndefined(this.maxDays)||!this.isMaxDaysClicked||t.isNullOrUndefined(this.startValue)?this.max:new Date(new Date(+this.startValue).setDate(this.startValue.getDate()+(this.maxDays-1))),e.action){case"moveRight":r=new Date(+this.currentDate),this.addDay(r,1,e,l,h),i&&+r==+a&&(n=this.keyCalendarUpdate(!1,n)),this.KeyboardNavigate(1,o,e,l,h),this.keyNavigation(n,e);break;case"moveLeft":r=new Date(+this.currentDate),this.addDay(r,-1,e,l,h),i||+r==+s&&(n=this.keyCalendarUpdate(!0,n)),this.KeyboardNavigate(-1,o,e,l,h),this.keyNavigation(n,e);break;case"moveUp":0===o?(r=new Date(+this.currentDate),this.addDay(r,-7,e,l,h),+r<=+s&&!i&&(n=this.keyCalendarUpdate(!0,n)),this.KeyboardNavigate(-7,o,e,l,h)):this.KeyboardNavigate(-4,o,e,this.max,this.min),this.keyNavigation(n,e);break;case"moveDown":0===o?(r=new Date(+this.currentDate),this.addDay(r,7,e,l,h),i&&+r>=+a&&(n=this.keyCalendarUpdate(!1,n)),this.KeyboardNavigate(7,o,e,l,h)):this.KeyboardNavigate(4,o,e,this.max,this.min),this.keyNavigation(n,e);break;case"home":this.currentDate=this.firstDay(this.currentDate),t.remove(this.tableBodyElement),0===o?this.renderMonths(e):1===o?this.renderYears(e):this.renderDecades(e),this.keyNavigation(n,e);break;case"end":this.currentDate=this.lastDay(this.currentDate,o),t.remove(this.tableBodyElement),0===o?this.renderMonths(e):1===o?this.renderYears(e):this.renderDecades(e),this.keyNavigation(n,e)}},r.prototype.keyInputHandler=function(i,s){var a,n=this.getViewNumber(this.currentView()),r=new Date(this.rightCalCurrentDate.getFullYear(),this.rightCalCurrentDate.getMonth(),1),l=new Date(this.leftCalCurrentDate.getFullYear(),this.leftCalCurrentDate.getMonth()+1,0),o=t.closest(i.target,"."+R),h=(o=t.isNullOrUndefined(o)?this.leftCalendar:o).classList.contains(Y);this.updateCalendarElement(o);var u=this.tableBodyElement.querySelector("tr td.e-selected"),d=o.querySelector("tr td."+le),p=o.querySelector("tr td."+K),c=o.querySelector("tr td."+_),m=this.getViewNumber(this.depth),v=n===m&&this.getViewNumber(this.start)>=m,f=t.closest(i.target,"."+Y),y=t.closest(i.target,"."+R),g=t.closest(i.target,"."+re);switch(t.isNullOrUndefined(d)?t.isNullOrUndefined(c)||this.dateDisabled?t.isNullOrUndefined(p)||this.dateDisabled?this.dateDisabled||this.currentDate.setDate(1):this.currentDate=new Date(+this.startValue):this.currentDate=new Date(+this.endValue):this.currentDate=this.currentDate,this.effect="",i.action){case"altUpArrow":this.isPopupOpen()&&(this.hide(i),this.preventFocus=!0,this.inputElement.focus(),t.addClass([this.inputWrapper.container],[G]));break;case"select":if(v){var b=t.isNullOrUndefined(d)?p:d;t.isNullOrUndefined(b)||b.classList.contains(Q)||this.selectRange(null,b)}else(t.isNullOrUndefined(u)||v)&&t.isNullOrUndefined(d)||(t.isNullOrUndefined(this.value)||(s=this.calendarElement.classList.contains(Y)?this.startDate:this.endDate),this.controlDown=i,this.contentClick(null,--n,d||u,s));i.preventDefault();break;case"controlHome":var D=new Date(this.currentDate.getFullYear(),0,1);!h&&+D<+l&&(o=this.keyCalendarUpdate(!0,o)),e.prototype.navigateTo.call(this,"Month",new Date(this.currentDate.getFullYear(),0,1)),this.keyNavigation(o,i);break;case"altRightArrow":t.isNullOrUndefined(f)?t.isNullOrUndefined(y)?t.isNullOrUndefined(g)||this.cancelButton.element.focus():t.isNullOrUndefined(this.presetElement)?this.cancelButton.element.focus():(this.presetElement.focus(),this.removeFocusedDate()):this.rightCalendar.children[1].firstElementChild.focus(),i.preventDefault();break;case"altLeftArrow":t.isNullOrUndefined(f)?t.isNullOrUndefined(y)||this.leftCalendar.children[1].firstElementChild.focus():!0!==this.applyButton.element.disabled?this.applyButton.element.focus():this.cancelButton.element.focus(),i.preventDefault();break;case"controlUp":this.calendarElement.classList.contains(Y),this.calendarNavigation(i,this.calendarElement),i.preventDefault();break;case"controlDown":t.isNullOrUndefined(u)&&t.isNullOrUndefined(d)||v||(t.isNullOrUndefined(this.value)||(s=this.calendarElement.classList.contains(Y)?this.startDate:this.endDate),this.controlDown=i,this.contentClick(null,--n,u||d,s)),i.preventDefault();break;case"controlEnd":D=new Date(this.currentDate.getFullYear(),11,31),h&&+D>+r&&(o=this.keyCalendarUpdate(!1,o)),e.prototype.navigateTo.call(this,"Month",new Date(this.currentDate.getFullYear(),11,31)),this.keyNavigation(o,i);break;case"pageUp":a=new Date(+this.currentDate),this.addMonths(a,-1),!h&&+a<=+l&&(o=this.keyCalendarUpdate(!0,o)),this.addMonths(this.currentDate,-1),e.prototype.navigateTo.call(this,"Month",this.currentDate),this.keyNavigation(o,i);break;case"pageDown":a=new Date(+this.currentDate),this.addMonths(a,1),h&&+a>=+r&&(o=this.keyCalendarUpdate(!1,o)),this.addMonths(this.currentDate,1),e.prototype.navigateTo.call(this,"Month",this.currentDate),this.keyNavigation(o,i);break;case"shiftPageUp":a=new Date(+this.currentDate),this.addYears(a,-1),!h&&+a<=+l&&(o=this.keyCalendarUpdate(!0,o)),this.addYears(this.currentDate,-1),e.prototype.navigateTo.call(this,"Month",this.currentDate),this.keyNavigation(o,i);break;case"shiftPageDown":a=new Date(+this.currentDate),this.addYears(a,1),h&&+a>=+r&&(o=this.keyCalendarUpdate(!1,o)),this.addYears(this.currentDate,1),e.prototype.navigateTo.call(this,"Month",this.currentDate),this.keyNavigation(o,i);break;case"shiftTab":t.isNullOrUndefined(this.presetElement)||(this.presetElement.setAttribute("tabindex","0"),this.presetElement.focus(),this.removeFocusedDate()),i.preventDefault();break;case"spacebar":this.applyButton&&!this.applyButton.disabled&&this.applyFunction(i);break;default:this.navInCalendar(i,h,l,r,o),this.checkMinMaxDays()}this.presetHeight()},r.prototype.keyNavigation=function(e,t){this.bindCalendarCellEvents(e),e.classList.contains(Y)?this.leftCalCurrentDate=new Date(+this.currentDate):this.rightCalCurrentDate=new Date(+this.currentDate),this.updateNavIcons(),this.calendarIconEvent(),this.updateRange([e]),this.dateDisabled=this.isDateDisabled(this.currentDate),t.preventDefault()},r.prototype.inputHandler=function(e){switch(e.action){case"altDownArrow":this.isPopupOpen()||(""===this.inputElement.value&&(this.clear(),this.changeTrigger(e),this.clearRange()),this.show(null,e),this.isRangeIconClicked=!1,this.isMobile||t.isNullOrUndefined(this.leftCalendar)||this.calendarFocus(),this.isKeyPopup=!0);break;case"escape":this.isPopupOpen()&&this.hide(e);break;case"enter":document.activeElement===this.inputElement&&(this.inputBlurHandler(e),this.hide(e));break;case"tab":document.activeElement===this.inputElement&&this.isPopupOpen()&&(this.hide(e),e.preventDefault())}},r.prototype.bindCalendarCellEvents=function(e){for(var i=0,s=e?e.querySelectorAll("."+te+" td"):this.popupObj.element.querySelectorAll("."+te+" td");i<s.length;i++){var a=s[i];t.EventHandler.clearEvents(a);a.classList.contains(Q)||a.classList.contains(de)||a.classList.contains(ue)||(this.isMobile||t.EventHandler.add(a,"mouseover",this.hoverSelection,this),t.EventHandler.add(a,"mousedown",this.selectRange,this))}},r.prototype.removeFocusedDate=function(){for(var e=!t.isNullOrUndefined(this.startValue)||!t.isNullOrUndefined(this.endValue),i=0,s=this.popupObj.element.querySelectorAll("."+te+" ."+le);i<s.length;i++){var a=s[i],n=new Date,r=this.getIdValue(null,a);("Month"===this.depth&&"Month"===this.currentView()&&(!a.classList.contains("e-today")||a.classList.contains("e-today")&&e)||"Year"===this.depth&&"Year"===this.currentView()&&(!this.isSameMonth(n,r)&&!this.isSameYear(n,r)||e)||"Decade"===this.depth&&"Decade"===this.currentView()&&(!this.isSameYear(n,r)||e))&&(a.classList.remove(le),a.classList.contains(K)||a.classList.contains(_)||a.removeAttribute("aria-label"))}},r.prototype.hoverSelection=function(e,i){var s=i||e.currentTarget,a=this.getIdValue(null,s);if(!t.isNullOrUndefined(this.startValue)&&+this.startValue>=+this.min&&+this.startValue<=+this.max&&(!this.isDateDisabled(this.endValue)&&!this.isDateDisabled(this.startValue)&&t.isNullOrUndefined(this.endValue)&&t.isNullOrUndefined(this.startValue)||!t.isNullOrUndefined(this.startValue)&&t.isNullOrUndefined(this.endValue)))for(var n=0,r=this.popupObj.element.querySelectorAll("."+te+" td");n<r.length;n++){var l=r[n],o=!l.classList.contains(Q)||l.classList.contains(de);if(!l.classList.contains(ue)&&o){var h=this.getIdValue(null,l),u=new Date(+this.startValue);new Date(+h).setHours(0,0,0,0)>=u.setHours(0,0,0,0)&&+h<=+a?t.addClass([l],X):t.removeClass([l],[X])}}},r.prototype.isSameStartEnd=function(e,t){var i=!1;return"Month"===this.depth?e.setHours(0,0,0,0)===t.setHours(0,0,0,0)&&(i=!0):"Year"===this.depth?e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&(i=!0):"Decade"===this.depth&&e.getFullYear()===t.getFullYear()&&(i=!0),i},r.prototype.updateRange=function(e){if(!t.isNullOrUndefined(this.startValue))for(var i=0,s=e;i<s.length;i++)for(var a=0,n=s[i].querySelectorAll("."+te+" td");a<n.length;a++){var r=n[a];if(!r.classList.contains(ue)&&!r.classList.contains(Q)){var l=this.getIdValue(null,r),o=this.getIdValue(null,r);if(t.isNullOrUndefined(this.endValue)?t.removeClass([r],[X]):this.currentView()===this.depth&&+o.setHours(0,0,0,0)>=+new Date(+this.startValue).setHours(0,0,0,0)&&+o.setHours(0,0,0,0)<=+new Date(+this.endValue).setHours(0,0,0,0)&&!this.isSameStartEnd(new Date(+this.startValue),new Date(+this.endValue))&&+new Date(+this.startValue).setHours(0,0,0,0)>=+this.min&&+new Date(+this.endValue).setHours(0,0,0,0)<=+this.max&&!this.isDateDisabled(this.startValue)&&!this.isDateDisabled(this.endValue)&&t.addClass([r],X),!r.classList.contains(Z)){var h=new Date(+this.startValue),u=new Date(+l);this.currentView()===this.depth&&+u.setHours(0,0,0,0)==+h.setHours(0,0,0,0)&&+u.setHours(0,0,0,0)>=+h.setHours(0,0,0,0)&&+this.startValue>=+this.min&&!this.inputWrapper.container.classList.contains("e-error")&&!this.isDateDisabled(this.startValue)&&!this.isDateDisabled(this.endValue)&&(t.addClass([r],[K,ee]),this.addSelectedAttributes(r,this.startValue,!0));var d=new Date(+this.endValue);"Year"===this.currentView()?u=new Date(u.getFullYear(),u.getMonth()+1,0):"Decade"===this.currentView()&&(u=new Date(u.getFullYear(),11,31)),this.currentView()===this.depth&&!t.isNullOrUndefined(this.endValue)&&+u.setHours(0,0,0,0)==+d.setHours(0,0,0,0)&&+u.setHours(0,0,0,0)<=+d.setHours(0,0,0,0)&&+this.startValue>=+this.min&&!this.inputWrapper.container.classList.contains("e-error")&&!this.isDateDisabled(this.startValue)&&!this.isDateDisabled(this.endValue)&&(t.addClass([r],[_,ee]),this.addSelectedAttributes(r,this.startValue,!1)),+l!=+this.startValue||t.isNullOrUndefined(this.endValue)||+l!=+this.endValue||this.addSelectedAttributes(r,this.endValue,!1,!0)}}}},r.prototype.checkMinMaxDays=function(){(!t.isNullOrUndefined(this.minDays)&&this.minDays>0||!t.isNullOrUndefined(this.maxDays)&&this.maxDays>0)&&(this.isMobile?this.updateMinMaxDays(this.popupObj.element.querySelector("."+te)):(this.updateMinMaxDays(this.popupObj.element.querySelector("."+Y)),this.updateMinMaxDays(this.popupObj.element.querySelector("."+R))))},r.prototype.rangeArgs=function(e){var i,s,a=t.isNullOrUndefined(this.startValue)?null:this.globalize.formatDate(this.startValue,{format:this.formatString,type:"date",skeleton:"yMd"}),n=t.isNullOrUndefined(this.endValue)?null:this.globalize.formatDate(this.endValue,{format:this.formatString,type:"date",skeleton:"yMd"});t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)?(i="",s=0):(i=a+" "+this.separator+" "+n,s=Math.round(Math.abs((this.startValue.getTime()-this.endValue.getTime())/864e5))+1);return{value:this.value,startDate:this.startValue,endDate:this.endValue,daySpan:s,event:e||null,element:this.element,isInteracted:!t.isNullOrUndefined(e),text:i}},r.prototype.otherMonthSelect=function(e,i,s){var a=+this.getIdValue(null,e),n='*[id^="/id"]:not(.e-other-month)'.replace("/id",""+a),r=this.popupObj&&this.popupObj.element.querySelector(n);t.isNullOrUndefined(r)||(i?(t.addClass([r],[K,ee]),this.addSelectedAttributes(r,this.startValue,!0)):(t.addClass([r],[_,ee]),this.addSelectedAttributes(r,this.endValue,!0)),s&&this.addSelectedAttributes(e,this.endValue,!1,!0))},r.prototype.selectRange=function(e,i){var s,a;e&&e.preventDefault();var n,r=(n=t.isNullOrUndefined(e)?this.getIdValue(null,i):this.getIdValue(e,null)).getFullYear(),l=n.getMonth(),o=new Date(r,l,1),h=new Date(r,l+1,0),u=new Date(r,0,1),d=new Date(r,11,31);t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)?this.isMobile&&this.startButton.element.classList.contains(q)&&this.removeSelection():(!this.isMobile||this.isMobile&&!this.endButton.element.classList.contains(q))&&this.removeSelection();var p=i||e.currentTarget;if(t.isNullOrUndefined(this.startValue))t.isNullOrUndefined(this.previousStartValue)||(n.setHours(this.previousStartValue.getHours()),n.setMinutes(this.previousStartValue.getMinutes()),n.setSeconds(this.previousStartValue.getSeconds())),this.startValue="Month"===this.depth?new Date(this.checkValue(n)):"Year"===this.depth?o:u,this.endValue=null,this.setValue(),t.addClass([p],K),this.addSelectedAttributes(p,this.startValue,!0),p.classList.contains(Z)&&this.otherMonthSelect(p,!0),this.checkMinMaxDays(),this.applyButton.disabled=!0,this.applyButton.element.disabled=!0,this.isMobile&&(this.endButton.element.classList.add(q),this.startButton.element.classList.remove(q),this.endButton.element.removeAttribute("disabled"),this.selectableDates()),this.trigger("select",this.rangeArgs(e));else if(+n==+this.startValue||+n>+this.startValue){if(+n==+this.startValue&&!t.isNullOrUndefined(this.minDays)&&this.minDays>1)return;this.endValue=null,this.setValue(),(this.isMobile||i)&&this.hoverSelection(e,i),t.isNullOrUndefined(this.previousEndValue)||(n.setHours(this.previousEndValue.getHours()),n.setMinutes(this.previousEndValue.getMinutes()),n.setSeconds(this.previousEndValue.getSeconds())),this.endValue="Month"===this.depth?new Date(this.checkValue(n)):"Year"===this.depth?h:d,this.setValue();var c=this.popupObj.element.querySelectorAll("."+_);if(this.isMobile){this.startButton.element.classList.remove(q),this.endButton.element.classList.add(q);for(var m=0,v=c;m<v.length;m++){var f=v[m];f.removeAttribute("aria-label"),f.classList.contains(K)?(this.addSelectedAttributes(f,this.startValue,!0),t.removeClass([f],[_])):(f.setAttribute("aria-selected","false"),t.removeClass([f],[_,ee]))}}t.addClass([p],_),+this.endValue==+this.startValue?this.addSelectedAttributes(p,this.endValue,!1,!0):this.addSelectedAttributes(p,this.endValue,!1),p.classList.contains(Z)&&(+this.endValue==+this.startValue?this.otherMonthSelect(p,!1,!0):this.otherMonthSelect(p,!1));for(var y=0,g=c=this.popupObj.element.querySelectorAll("."+_);y<g.length;y++){var b=g[y];b.classList.contains(K)&&t.removeClass([b],[X])}this.applyButton.disabled=!1,this.applyButton.element.disabled=!1,this.isMobile||this.removeClassDisabled(),this.disabledDateRender(),this.trigger("select",this.rangeArgs(e))}else+n<+this.startValue&&(this.removeClassDisabled(),this.startValue="Month"===this.depth?new Date(this.checkValue(n)):"Year"===this.depth?o:u,this.setValue(),this.removeSelectedAttributes(),t.removeClass(this.popupObj.element.querySelectorAll("."+K),[K,ee]),t.addClass([p],K),this.addSelectedAttributes(p,this.startValue,!0),p.classList.contains(Z)&&this.otherMonthSelect(p,!0),this.checkMinMaxDays());e&&(s=t.closest(e.target,"."+Y)),t.isNullOrUndefined(s)?(e&&(a=e&&t.closest(e.target,"."+R)),t.isNullOrUndefined(a)||this.rightCalendar.children[1].firstElementChild.focus()):this.leftCalendar.children[1].firstElementChild.focus(),t.addClass([p],ee),this.updateHeader(),this.removeFocusedDate()},r.prototype.selectableDates=function(){if(!t.isNullOrUndefined(this.startValue)){var e=this.calendarElement.querySelectorAll("."+te+" td"),i=!1;if(this.currentView()===this.depth){for(var s=0,a=e;s<a.length;s++){if(!(l=a[s]).classList.contains(K)&&!l.classList.contains(ue)&&!l.classList.contains(Q)){if(+this.getIdValue(null,l)<+this.startValue){t.addClass([l],[de,Q,ce]),t.EventHandler.clearEvents(l);continue}break}if(l.classList.contains(K)&&!l.classList.contains(Z)){i=!0;break}}i&&(this.previousIcon.classList.contains(Q)||t.addClass([this.previousIcon],[pe,Q,ce]))}else{for(var n=0,r=e;n<r.length;n++){var l=r[n],o=this.startValue.getMonth(),h=this.startValue.getFullYear(),u=this.getIdValue(null,l);if(this.startButton.element.classList.contains(q)||!("Year"===this.currentView()&&u.getMonth()<o&&u.getFullYear()<=h||"Decade"===this.currentView()&&u.getMonth()<=o&&u.getFullYear()<h))break;t.addClass([l],[Q])}e[0].classList.contains(Q)?this.previousIconHandler(!0):e[e.length-1].classList.contains(Q)&&this.nextIconHandler(!0)}}},r.prototype.updateMinMaxDays=function(e){if(!t.isNullOrUndefined(this.startValue)&&t.isNullOrUndefined(this.endValue)||this.isMobile&&this.endButton.element.classList.contains(q)){if(!t.isNullOrUndefined(this.minDays)&&this.minDays>0||!t.isNullOrUndefined(this.maxDays)&&this.maxDays>0){var i=new Date(new Date(+this.startValue).setDate(this.startValue.getDate()+(this.minDays-1))),s=new Date(new Date(+this.startValue).setDate(this.startValue.getDate()+(this.maxDays-1)));i=!t.isNullOrUndefined(this.minDays)&&this.minDays>0?i:null,s=!t.isNullOrUndefined(this.maxDays)&&this.maxDays>0?s:null,"Year"===this.currentView()?(i=t.isNullOrUndefined(i)?null:new Date(i.getFullYear(),i.getMonth(),0),s=t.isNullOrUndefined(s)?null:new Date(s.getFullYear(),s.getMonth(),1)):"Decade"===this.currentView()&&(i=t.isNullOrUndefined(i)?null:new Date(i.getFullYear()-1,11,1),s=t.isNullOrUndefined(s)?null:new Date(s.getFullYear(),0,1));for(var a=void 0,n=0,r=e.querySelectorAll("."+te+" td");n<r.length;n++){var l=r[n];if(!l.classList.contains(K)&&!l.classList.contains(ue)){var o=this.getIdValue(null,l);if(!t.isNullOrUndefined(i)&&+o==+i&&l.classList.contains(Q)&&i.setDate(i.getDate()+1),!l.classList.contains(Q)){if(+o<=+this.startValue)continue;!t.isNullOrUndefined(i)&&+o<+i&&(t.addClass([l],[de,Q,ce]),t.EventHandler.clearEvents(l)),!t.isNullOrUndefined(s)&&+o>+s&&(t.addClass([l],[de,Q,ce]),this.isMaxDaysClicked=!0,t.EventHandler.clearEvents(l),t.isNullOrUndefined(a)&&!l.classList.contains(Z)&&(a=l))}}}if(!t.isNullOrUndefined(a))if(this.isMobile)this.nextIcon.classList.contains(Q)||t.addClass([this.nextIcon],[pe,Q,ce]);else{var h=t.closest(a,"."+R);(h=t.isNullOrUndefined(h)?this.leftCalendar:h).classList.contains(Y)?(this.rightCalNextIcon.classList.contains(Q)||t.addClass([this.rightCalNextIcon],[pe,Q,ce]),this.leftCalNextIcon.classList.contains(Q)||t.addClass([this.leftCalNextIcon],[pe,Q,ce]),this.rightCalPrevIcon.classList.contains(Q)||t.addClass([this.rightCalPrevIcon],[pe,Q,ce])):this.rightCalNextIcon.classList.contains(Q)||t.addClass([this.rightCalNextIcon],[pe,Q,ce])}}}else this.isMaxDaysClicked=!1},r.prototype.removeClassDisabled=function(){for(var e=0,i=this.popupObj.element.querySelectorAll("."+te+" td."+de);e<i.length;e++){var s=i[e];s.classList.contains(de)&&(t.removeClass([s],[de,Q,ce]),t.EventHandler.add(s,"click",this.selectRange,this),this.isMobile||t.EventHandler.add(s,"mouseover",this.hoverSelection,this))}this.isMobile?(this.nextIcon.classList.contains(pe)&&t.removeClass([this.nextIcon],[pe,Q,ce]),this.previousIcon.classList.contains(pe)&&t.removeClass([this.previousIcon],[pe,Q,ce])):(this.rightCalNextIcon.classList.contains(pe)&&t.removeClass([this.rightCalNextIcon],[pe,Q,ce]),this.rightCalPrevIcon.classList.contains(pe)&&t.removeClass([this.rightCalPrevIcon],[pe,Q,ce]),this.leftCalNextIcon.classList.contains(pe)&&t.removeClass([this.leftCalNextIcon],[pe,Q,ce]))},r.prototype.updateHeader=function(){var e={type:"date",skeleton:"yMMMd"};if(t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue))this.popupObj.element.querySelector("."+he).textContent=this.l10n.getConstant("selectedDays");else{var i=Math.round(Math.abs((this.startValue.getTime()-this.endValue.getTime())/864e5))+1;t.isNullOrUndefined(this.disabledDayCnt)||(i-=this.disabledDayCnt,this.disabledDayCnt=null),this.popupObj.element.querySelector("."+he).textContent=i.toString()+" "+this.l10n.getConstant("days")}this.isMobile?(t.isNullOrUndefined(this.startValue)?this.startButton.element.textContent=this.l10n.getConstant("startLabel"):this.startButton.element.textContent=this.globalize.formatDate(this.startValue,e),t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)?this.endButton.element.textContent=this.l10n.getConstant("endLabel"):this.endButton.element.textContent=this.globalize.formatDate(this.endValue,e)):(t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)?this.popupObj.element.querySelector("."+$).textContent=this.l10n.getConstant("endLabel"):this.popupObj.element.querySelector("."+$).textContent=this.globalize.formatDate(this.endValue,e),t.isNullOrUndefined(this.startValue)?this.popupObj.element.querySelector("."+J).textContent=this.l10n.getConstant("startLabel"):this.popupObj.element.querySelector("."+J).textContent=this.globalize.formatDate(this.startValue,e)),(this.isDateDisabled(this.startValue)||this.isDateDisabled(this.endValue)||!t.isNullOrUndefined(this.startValue)&&+this.startValue<+this.min||!t.isNullOrUndefined(this.endValue)&&+this.endValue>+this.max||!t.isNullOrUndefined(this.startValue)&&!t.isNullOrUndefined(this.endValue)&&+this.startValue>+this.endValue)&&(this.isMobile?(this.startButton.element.textContent=this.l10n.getConstant("startLabel"),this.endButton.element.textContent=this.l10n.getConstant("endLabel"),this.popupObj.element.querySelector("."+he).textContent=this.l10n.getConstant("selectedDays")):(this.popupObj.element.querySelector("."+he).textContent=this.l10n.getConstant("selectedDays"),this.popupObj.element.querySelector("."+J).textContent=this.l10n.getConstant("startLabel"),this.popupObj.element.querySelector("."+$).textContent=this.l10n.getConstant("endLabel"))),this.popupObj.element.querySelector("#custom_range")&&(this.popupObj.element.querySelector("#custom_range").textContent=""!==this.l10n.getConstant("customRange")?this.l10n.getConstant("customRange"):"Custom Range")},r.prototype.removeSelection=function(){this.startValue=null,this.endValue=null,this.setValue(),this.removeSelectedAttributes(),this.popupObj&&(this.popupObj.element.querySelectorAll("."+ee).length>0&&t.removeClass(this.popupObj.element.querySelectorAll("."+ee),[K,_,ee]),this.popupObj.element.querySelectorAll("."+le).length>0&&t.removeClass(this.popupObj.element.querySelectorAll("."+le),le),this.popupObj.element.querySelectorAll("."+X).length>0&&t.removeClass(this.popupObj.element.querySelectorAll("."+X),[X]))},r.prototype.addSelectedAttributes=function(e,i,s,a){if(e){var n=this.globalize.formatDate(i,{type:"date",skeleton:"full"});!t.isNullOrUndefined(a)&&a?e.setAttribute("aria-label","The current start and end date is "+n):e.setAttribute("aria-label","The current "+(s?"start":"end")+" date is "+n),e.setAttribute("aria-selected","true")}},r.prototype.removeSelectedAttributes=function(){if(this.popupObj){for(var e=0,t=this.popupObj.element.querySelectorAll("."+K);e<t.length;e++){(a=t[e]).setAttribute("aria-selected","false"),a.removeAttribute("aria-label")}for(var i=0,s=this.popupObj.element.querySelectorAll("."+_);i<s.length;i++){var a;(a=s[i]).setAttribute("aria-selected","false"),a.removeAttribute("aria-label")}}},r.prototype.updateCalendarElement=function(e){e.classList.contains(Y)?(this.calendarElement=this.leftCalendar,this.currentDate=this.leftCalCurrentDate,this.previousIcon=this.leftCalPrevIcon,this.nextIcon=this.leftCalNextIcon):(this.calendarElement=this.rightCalendar,this.currentDate=this.rightCalCurrentDate,this.previousIcon=this.rightCalPrevIcon,this.nextIcon=this.rightCalNextIcon),this.contentElement=e.querySelector("."+oe),this.tableBodyElement=t.select(".e-content tbody",e),this.table=e.querySelector("."+oe).getElementsByTagName("table")[0],this.headerTitleElement=e.querySelector(".e-header ."+se),this.headerElement=e.querySelector("."+ie)},r.prototype.navPrevMonth=function(e){e.preventDefault();var i=t.closest(e.target,"."+Y);i=t.isNullOrUndefined(i)?t.closest(e.target,"."+R):i,this.updateCalendarElement(i),this.navigatePrevious(e),!t.isNullOrUndefined(this.startValue)&&t.isNullOrUndefined(this.endValue)&&this.updateMinMaxDays(i),this.updateControl(i)},r.prototype.deviceNavigation=function(e){this.deviceCalendarEvent(),this.updateRange([this.popupObj.element.querySelector("."+te)]),this.endButton.element.classList.contains(q)&&this.updateMinMaxDays(this.popupObj.element.querySelector("."+te)),this.endButton.element.classList.contains(q)&&this.selectableDates(),this.currentView()===this.depth&&this.bindCalendarCellEvents(),this.removeFocusedDate()},r.prototype.updateControl=function(e){e.classList.contains(R)?this.rightCalCurrentDate=new Date(+this.currentDate):this.leftCalCurrentDate=new Date(+this.currentDate),this.updateNavIcons(),this.calendarIconEvent(),("Month"===this.depth&&this.leftCalendar.querySelector(".e-content").classList.contains("e-month")&&this.rightCalendar.querySelector(".e-content").classList.contains("e-month")||"Year"===this.depth&&this.leftCalendar.querySelector(".e-content").classList.contains("e-year")&&this.rightCalendar.querySelector(".e-content").classList.contains("e-year")||"Decade"===this.depth&&this.leftCalendar.querySelector(".e-content").classList.contains("e-decade")&&this.rightCalendar.querySelector(".e-content").classList.contains("e-decade")||this.isMobile)&&this.bindCalendarCellEvents(),this.removeFocusedDate(),this.updateRange([e])},r.prototype.navNextMonth=function(e){e.preventDefault();var i=t.closest(e.target,"."+Y);i=t.isNullOrUndefined(i)?t.closest(e.target,"."+R):i,this.updateCalendarElement(i),this.navigateNext(e),!t.isNullOrUndefined(this.startValue)&&t.isNullOrUndefined(this.endValue)&&this.updateMinMaxDays(i),this.updateControl(i)},r.prototype.compareMonths=function(e,t){return e.getFullYear()!==t.getFullYear()||"Year"!==this.currentView()&&"Decade"!==this.currentView()?e.getFullYear()>t.getFullYear()?-1:e.getFullYear()<t.getFullYear()?e.getFullYear()+1===t.getFullYear()&&11===e.getMonth()&&0===t.getMonth()?-1:1:e.getMonth()===t.getMonth()?0:e.getMonth()+1===t.getMonth()?-1:1:-1},r.prototype.compareYears=function(e,t){return e.getFullYear()===t.getFullYear()?-1:e.getFullYear()>t.getFullYear()?-1:e.getFullYear()+1===t.getFullYear()?-1:1},r.prototype.compareDecades=function(e,t){var i;if(e.getFullYear()===t.getFullYear())i=-1;else if(e.getFullYear()>t.getFullYear())i=-1;else{var s=e.getFullYear(),a=t.getFullYear();i=s-s%10+10==a-a%10?-1:1}return i},r.prototype.isPopupOpen=function(){return!(t.isNullOrUndefined(this.popupObj)||!this.popupObj.element.classList.contains("e-popup"))},r.prototype.createRangeHeader=function(){var e=this.createElement("div",{className:"e-start-end"});if(this.isMobile){var i=this.createElement("button",{className:"e-end-btn"}),s=this.createElement("button",{className:"e-start-btn"});this.startButton=new a.Button({content:this.l10n.getConstant("startLabel")},s),this.endButton=new a.Button({content:this.l10n.getConstant("endLabel")},i),e.appendChild(s),e.appendChild(i)}else{var n=this.createElement("a",{className:J}),r=this.createElement("a",{className:$}),l=this.createElement("span",{className:"e-change-icon e-icons"});t.attributes(n,{"aria-atomic":"true","aria-live":"assertive","aria-label":"Start Date",role:"button"}),t.attributes(r,{"aria-atomic":"true","aria-live":"assertive","aria-label":"End Date",role:"button"}),e.appendChild(n),e.appendChild(l),e.appendChild(r),n.textContent=this.l10n.getConstant("startLabel"),r.textContent=this.l10n.getConstant("endLabel")}return e},r.prototype.disableInput=function(){this.strictMode?t.isNullOrUndefined(this.previousStartValue)||t.isNullOrUndefined(this.previousEndValue)||(this.startValue=this.previousStartValue,this.endValue=this.previousEndValue,this.setValue(),this.updateInput()):(this.updateInput(),this.clearRange(),this.setProperties({startDate:null},!0),this.setProperties({endDate:null},!0),this.startValue=null,this.endValue=null,this.setValue(),this.errorClass()),this.setProperties({enabled:!1},!0),s.Input.setEnabled(this.enabled,this.inputElement),this.bindEvents()},r.prototype.validateMinMax=function(){this.min=t.isNullOrUndefined(this.min)||!+this.min?this.min=new Date(1900,0,1):this.min,this.max=t.isNullOrUndefined(this.max)||!+this.max?this.max=new Date(2099,11,31):this.max,this.min<=this.max?(t.isNullOrUndefined(this.minDays)||t.isNullOrUndefined(this.maxDays)||this.maxDays>0&&this.minDays>0&&this.minDays>this.maxDays&&(this.maxDays=null),!t.isNullOrUndefined(this.minDays)&&this.minDays<0&&(this.minDays=null),!t.isNullOrUndefined(this.maxDays)&&this.maxDays<0&&(this.maxDays=null)):this.disableInput()},r.prototype.validateRangeStrict=function(){t.isNullOrUndefined(this.startValue)||(+this.startValue<=+this.min?(this.startValue=this.min,this.setValue()):+this.startValue>=+this.min&&+this.startValue>=+this.max&&(this.startValue=this.max)),t.isNullOrUndefined(this.endValue)||(+this.endValue>+this.max?(this.endValue=this.max,this.setValue()):+this.endValue<+this.min&&(this.endValue=this.min,this.setValue())),this.validateMinMaxDays()},r.prototype.validateRange=function(){this.validateMinMaxDays()},r.prototype.validateMinMaxDays=function(){if(!t.isNullOrUndefined(this.startValue)&&!t.isNullOrUndefined(this.endValue)){var e=Math.round(Math.abs((this.startValue.getTime()-this.endValue.getTime())/864e5))+1;if(!t.isNullOrUndefined(this.minDays)&&this.minDays>0&&!(e>=this.minDays))if(this.strictMode){var i=new Date(+this.startValue);i.setDate(i.getDate()+(this.minDays-1)),+i>+this.max?(this.endValue=this.max,this.setValue()):(this.endValue=i,this.setValue())}else this.startValue=null,this.endValue=null,this.setValue();t.isNullOrUndefined(this.maxDays)||!(this.maxDays>0)||e<=this.maxDays||(this.strictMode?(this.endValue=new Date(+this.startValue),this.endValue.setDate(this.endValue.getDate()+(this.maxDays-1)),this.setValue()):(this.startValue=null,this.endValue=null,this.setValue()))}},r.prototype.renderCalendar=function(){this.calendarElement=this.createElement("div"),this.calendarElement.classList.add(te),this.enableRtl&&this.calendarElement.classList.add("e-rtl"),t.attributes(this.calendarElement,{role:"calendar"}),e.prototype.createHeader.call(this),e.prototype.createContent.call(this)},r.prototype.isSameMonth=function(e,t){return e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear()},r.prototype.isSameYear=function(e,t){return e.getFullYear()===t.getFullYear()},r.prototype.isSameDecade=function(e,t){var i=e.getFullYear(),s=t.getFullYear();return i-i%10==s-s%10},r.prototype.startMonthCurrentDate=function(){this.isSameMonth(this.min,this.max)||+this.currentDate>+this.max||this.isSameMonth(this.currentDate,this.max)?(this.currentDate=new Date(+this.max),this.currentDate.setDate(1),this.currentDate.setMonth(this.currentDate.getMonth()-1)):this.currentDate<this.min&&(this.currentDate=new Date(this.checkValue(this.min)))},r.prototype.selectNextMonth=function(){if(t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)||this.isSameMonth(this.endValue,this.currentDate)||this.isDateDisabled(this.endValue)||this.isDateDisabled(this.startValue))return this.currentDate.setDate(1),void this.currentDate.setMonth(this.currentDate.getMonth()+1);if(this.currentDate=new Date(+this.endValue),!t.isNullOrUndefined(this.startValue)&&+this.startValue<+this.min||!t.isNullOrUndefined(this.endValue)&&+this.endValue>+this.max||!t.isNullOrUndefined(this.startValue)&&!t.isNullOrUndefined(this.endValue)&&+this.startValue>+this.endValue){this.currentDate=new Date((new Date).setHours(0,0,0,0)),this.currentDate.setDate(1);var e=this.currentDate.getMonth()+1;this.currentDate.setMonth(e)}},r.prototype.selectNextYear=function(){if(t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)||this.isSameYear(this.endValue,this.currentDate)||this.isDateDisabled(this.endValue)||this.isDateDisabled(this.startValue)){this.currentDate.setMonth(0);var e=this.currentDate.getFullYear()+1;this.currentDate.setFullYear(e)}else this.currentDate=new Date(+this.endValue),(!t.isNullOrUndefined(this.endValue)&&+this.endValue>+this.max||!t.isNullOrUndefined(this.startValue)&&!t.isNullOrUndefined(this.endValue)&&+this.startValue>+this.endValue||!t.isNullOrUndefined(this.startValue)&&+this.startValue<+this.min)&&(this.currentDate=new Date((new Date).setHours(0,0,0,0)),this.currentDate.setMonth(0),this.currentDate.setFullYear(this.currentDate.getFullYear()+1))},r.prototype.selectNextDecade=function(){if(t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)||this.isSameDecade(this.endValue,this.currentDate)||this.isDateDisabled(this.endValue)||this.isDateDisabled(this.startValue)){var e=this.currentDate.getFullYear()+10;this.currentDate.setFullYear(e)}else this.currentDate=new Date(+this.endValue),(!t.isNullOrUndefined(this.startValue)&&!t.isNullOrUndefined(this.endValue)&&+this.startValue>+this.endValue||!t.isNullOrUndefined(this.endValue)&&+this.endValue>+this.max||!t.isNullOrUndefined(this.startValue)&&+this.startValue<+this.min)&&(this.currentDate=new Date((new Date).setHours(0,0,0,0)),this.currentDate.setFullYear(this.currentDate.getFullYear()+10))},r.prototype.selectStartMonth=function(){t.isNullOrUndefined(this.startValue)?(this.currentDate=new Date((new Date).setHours(0,0,0,0)),this.startMonthCurrentDate()):!t.isNullOrUndefined(this.max)&&this.isSameMonth(this.startValue,this.max)?(this.currentDate=new Date(+this.max),this.currentDate.setDate(1),this.currentDate.setMonth(this.currentDate.getMonth()-1)):this.startValue>=this.min&&this.startValue<=this.max&&!this.isDateDisabled(this.startValue)?this.currentDate=new Date(+this.startValue):this.currentDate=new Date((new Date).setHours(0,0,0,0)),(!t.isNullOrUndefined(this.endValue)&&+this.endValue>+this.max||!t.isNullOrUndefined(this.startValue)&&+this.startValue<+this.min||!t.isNullOrUndefined(this.startValue)&&!t.isNullOrUndefined(this.endValue)&&+this.startValue>+this.endValue)&&(this.currentDate=new Date((new Date).setHours(0,0,0,0))),this.startMonthCurrentDate()},r.prototype.createCalendar=function(){var i=this.createElement("div",{className:"e-calendar-container"});if(this.isMobile){t.isNullOrUndefined(this.startValue)||(this.currentDate=new Date(+this.startValue)),e.prototype.validateDate.call(this),e.prototype.minMaxUpdate.call(this),e.prototype.render.call(this);var s=this.calendarElement.querySelector("."+te+" .e-prev"),a=this.calendarElement.querySelector("."+te+" .e-next");t.remove(this.calendarElement.querySelector("."+te+" ."+ae)),this.calendarElement.querySelector("."+te+" ."+ie).appendChild(a),this.calendarElement.querySelector("."+te+" ."+ie).appendChild(s),t.prepend([s],this.calendarElement.querySelector("."+te+" ."+ie)),this.deviceCalendar=this.calendarElement,i.appendChild(this.calendarElement),this.headerTitleElement=this.calendarElement.querySelector(".e-calendar .e-header ."+se)}else{this.selectStartMonth(),this.renderCalendar(),this.leftCalCurrentDate=new Date(+this.currentDate),this.calendarElement.classList.add(Y),this.leftCalPrevIcon=this.calendarElement.querySelector("."+Y+" .e-prev"),this.leftCalNextIcon=this.calendarElement.querySelector("."+Y+" .e-next"),this.leftTitle=this.calendarElement.querySelector("."+Y+" ."+se),t.remove(this.calendarElement.querySelector("."+Y+" ."+ae)),this.calendarElement.querySelector("."+Y+" ."+ie).appendChild(this.leftCalNextIcon),this.calendarElement.querySelector("."+Y+" ."+ie).appendChild(this.leftCalPrevIcon),t.prepend([this.leftCalPrevIcon],this.calendarElement.querySelector("."+Y+" ."+ie)),this.leftCalendar=this.calendarElement;var n=this.createElement("div",{className:"e-left-container"}),r=this.createElement("div",{className:"e-right-container"});n.appendChild(this.leftCalendar),i.appendChild(n),this.isMobile||t.EventHandler.add(this.leftTitle,"click",this.leftNavTitle,this),"Month"===this.start&&this.selectNextMonth(),"Year"===this.start&&this.selectNextYear(),"Decade"===this.start&&this.selectNextDecade(),this.renderCalendar(),this.rightCalCurrentDate=new Date(+this.currentDate),t.addClass([this.calendarElement],R),this.rightCalendar=this.calendarElement,t.removeClass([this.leftCalendar&&this.leftCalendar.querySelector(".e-content tbody")],"e-zoomin"),t.removeClass([this.rightCalendar&&this.rightCalendar.querySelector(".e-content tbody")],"e-zoomin"),this.rightCalPrevIcon=this.calendarElement.querySelector("."+R+" .e-prev"),this.rightCalNextIcon=this.calendarElement.querySelector("."+R+" .e-next"),this.rightTitle=this.calendarElement.querySelector("."+R+" ."+se),t.remove(this.calendarElement.querySelector("."+R+" ."+ae)),this.calendarElement.querySelector("table").setAttribute("tabindex","-1"),this.calendarElement.querySelector("."+R+" ."+ie).appendChild(this.rightCalNextIcon),this.calendarElement.querySelector("."+R+" ."+ie).appendChild(this.rightCalPrevIcon),t.prepend([this.rightCalPrevIcon],this.calendarElement.querySelector("."+R+" ."+ie)),r.appendChild(this.rightCalendar),i.appendChild(r),this.isMobile||t.EventHandler.add(this.rightTitle,"click",this.rightNavTitle,this)}return i},r.prototype.leftNavTitle=function(e){this.isPopupOpen()&&(this.calendarElement=this.leftCalendar,this.calendarNavigation(e,this.calendarElement))},r.prototype.calendarNavigation=function(t,i){this.table=i.querySelector("table"),this.headerTitleElement=i.querySelector(".e-title"),this.tableBodyElement=i.querySelector("tbody"),this.tableHeadElement=i.querySelector("thead"),this.contentElement=i.querySelector(".e-content"),this.updateCalendarElement(i),e.prototype.navigateTitle.call(this,t),this.updateNavIcons()},r.prototype.rightNavTitle=function(e){this.isPopupOpen()&&(this.calendarElement=this.rightCalendar,this.calendarNavigation(e,this.calendarElement))},r.prototype.clickEventEmitter=function(e){this.isMobile||(t.closest(e.target,".e-calendar.e-left-calendar")?(this.calendarElement=this.leftCalendar,this.updateCalendarElement(this.leftCalendar)):(this.calendarElement=this.rightCalendar,this.updateCalendarElement(this.rightCalendar)))},r.prototype.currentView=function(){return e.prototype.currentView.call(this)},r.prototype.getCalendarView=function(e){return"Year"===e?"Year":"Decade"===e?"Decade":"Month"},r.prototype.navigatedEvent=function(i){if(this.trigger("navigated",this.navigatedArgs),!t.isNullOrUndefined(this.popupObj)){var s=this.getCalendarView(this.currentView());if(this.isMobile)s===this.depth?(this.bindCalendarCellEvents(),this.deviceNavigation(),this.removeFocusedDate(),this.checkMinMaxDays()):this.selectableDates();else if(this.isMobile||s!==this.depth)this.updateNavIcons(),this.calendarIconEvent();else{if((this.calendarElement.classList.contains("e-left-calendar")?this.leftCalendar:this.rightCalendar)!==this.leftCalendar||(!i||i.currentTarget.children[0].classList.contains("e-icons"))&&t.isNullOrUndefined(this.controlDown)){if(i&&!i.currentTarget.children[0].classList.contains("e-icons")||!t.isNullOrUndefined(this.controlDown)){if(this.rightCalCurrentDate=new Date(+this.currentDate),"Year"===s){var a=this.currentDate.getFullYear()-1;this.leftCalCurrentDate=new Date(new Date(+this.currentDate).setFullYear(a))}else if("Decade"===s){var n=this.currentDate.getFullYear()-10;this.leftCalCurrentDate=new Date(new Date(+this.currentDate).setFullYear(n))}else this.leftCalCurrentDate=new Date(new Date(+this.currentDate).setMonth(this.currentDate.getMonth()-1));this.currentDate=this.rightCalCurrentDate,this.updateCalendarElement(this.rightCalendar),this.updateControl(this.rightCalendar),this.updateCalendarElement(this.leftCalendar),this.startValue&&t.isNullOrUndefined(this.endValue)?"Month"===s&&this.startValue.getMonth()<this.rightCalCurrentDate.getMonth()&&this.startValue.getFullYear()<=this.rightCalCurrentDate.getFullYear()?e.prototype.navigateTo.call(this,s,new Date(+this.startValue)):"Year"===s&&this.startValue.getFullYear()<this.rightCalCurrentDate.getFullYear()?e.prototype.navigateTo.call(this,s,new Date(+this.startValue)):e.prototype.navigateTo.call(this,s,this.leftCalCurrentDate):e.prototype.navigateTo.call(this,s,this.leftCalCurrentDate),this.updateControl(this.leftCalendar),this.updateNavIcons(),this.calendarIconEvent(),this.calendarIconRipple(),this.controlDown=null}}else{if(this.leftCalCurrentDate=new Date(+this.currentDate),"Year"===s){var r=this.currentDate.getFullYear()+1;this.rightCalCurrentDate=new Date(new Date(+this.currentDate).setFullYear(r))}else if("Decade"===s){var l=this.currentDate.getFullYear()+10;this.rightCalCurrentDate=new Date(new Date(+this.currentDate).setFullYear(l))}else this.rightCalCurrentDate=new Date(new Date(+this.currentDate).setMonth(this.currentDate.getMonth()+1));this.currentDate=this.leftCalCurrentDate,this.updateCalendarElement(this.leftCalendar),this.updateControl(this.leftCalendar),this.updateCalendarElement(this.rightCalendar),e.prototype.navigateTo.call(this,s,this.rightCalCurrentDate),this.updateControl(this.rightCalendar),this.updateNavIcons(),this.calendarIconEvent(),this.calendarIconRipple(),this.controlDown=null}this.checkMinMaxDays()}}},r.prototype.createControl=function(){var e=this.createElement("div",{className:ne}),i=this.createElement("div",{className:"e-range-header"}),s=this.createRangeHeader();i.appendChild(s);var n=this.createElement("div",{className:he});t.attributes(n,{"aria-label":"Selected Days"}),n.textContent=this.l10n.getConstant("selectedDays"),i.appendChild(n);var r=this.createElement("div",{className:"e-separator"}),l=this.createCalendar();e.appendChild(i),e.appendChild(r),e.appendChild(l);var o=this.createElement("div",{className:"e-footer"}),h=this.createElement("button",{className:"e-cancel e-flat e-css"}),u=this.createElement("button");t.addClass([u],["e-apply","e-flat","e-primary","e-css"]),o.appendChild(u),o.appendChild(h);var d=!t.isNullOrUndefined(this.startValue)&&!t.isNullOrUndefined(this.endValue);if(this.cancelButton=new a.Button({content:this.l10n.getConstant("cancelText")},h),this.applyButton=new a.Button({content:this.l10n.getConstant("applyText"),disabled:!d},u),t.EventHandler.add(u,"click",this.applyFunction,this),t.EventHandler.add(h,"click",this.cancelFunction,this),this.popupWrapper.appendChild(e),!this.isMobile&&!t.isUndefined(this.presets[0].start&&this.presets[0].end&&this.presets[0].label)){this.createPresets(),this.listRippleEffect(),t.addClass([e],"e-range-border"),t.addClass([this.popupWrapper],"e-preset-wrapper");this.popupWrapper.querySelector("."+re).style.height=this.popupWrapper.querySelector("."+ne).getBoundingClientRect().height+"px"}this.popupWrapper.appendChild(o),this.isMobile&&this.deviceHeaderUpdate(),this.renderPopup()},r.prototype.cancelFunction=function(e){document.activeElement!==this.inputElement&&(this.preventFocus=!0,this.inputElement.focus(),t.addClass([this.inputWrapper.container],[G])),e.preventDefault(),this.isKeyPopup&&(this.inputElement.focus(),this.isKeyPopup=!1),this.startValue=null,this.endValue=null,this.removeSelection(),this.hide(e)},r.prototype.deviceHeaderUpdate=function(){t.isNullOrUndefined(this.startValue)&&t.isNullOrUndefined(this.endValue)?(this.endButton.element.setAttribute("disabled",""),this.startButton.element.classList.add(q)):t.isNullOrUndefined(this.startValue)||this.startButton.element.classList.add(q)},r.prototype.applyFunction=function(e){var i=!1;e.preventDefault(),this.closeEventArgs&&this.closeEventArgs.cancel&&(this.startValue=this.popupWrapper.querySelector(".e-start-date")&&this.getIdValue(null,this.popupWrapper.querySelector(".e-start-date")),this.endValue=this.popupWrapper.querySelector(".e-end-date")&&this.getIdValue(null,this.popupWrapper.querySelector(".e-end-date")),this.setValue()),document.activeElement!==this.inputElement&&(this.preventFocus=!0,this.inputElement.focus(),t.addClass([this.inputWrapper.container],[G])),"touchstart"!==e.type&&this.closeEventArgs&&!this.closeEventArgs.cancel&&e.preventDefault(),t.isNullOrUndefined(this.startValue)||t.isNullOrUndefined(this.endValue)?this.hide(e||null):(this.previousStartValue=new Date(+this.startValue),this.previousEndValue=new Date(+this.endValue),this.previousEleValue=this.inputElement.value,s.Input.setValue(this.rangeArgs(e).text,this.inputElement,this.floatLabelType,this.showClearButton),+this.initStartDate==+this.startValue&&+this.initEndDate==+this.endValue||(i=!0),this.changeTrigger(e),this.hide(e||null),this.errorClass(),i=!0),t.closest(e.target,".e-input-group")||i||this.focusOut(),this.isMobile||(this.isKeyPopup=!1,this.isRangeIconClicked&&(this.inputWrapper.container.children[1].focus(),this.keyInputConfigs=t.extend(this.keyInputConfigs,this.keyConfigs),this.popupKeyboardModule=new t.KeyboardEvents(this.inputWrapper.container.children[1],{eventName:"keydown",keyConfigs:this.keyInputConfigs,keyAction:this.popupKeyActionHandle.bind(this)})))},r.prototype.onMouseClick=function(e,i){if("touchstart"!==e.type){var s=i||e.target,a=t.closest(s,"."+me),n=a&&a.classList.contains(q);a&&a.classList.contains(me)&&this.setListSelection(a,e),this.inputElement.focus(),this.isMobile||(this.preventFocus=!0,a&&a.classList.contains(me)&&"custom_range"===a.getAttribute("id")?this.leftCalendar.children[1].firstElementChild.focus():n||"keydown"!==e.type||this.inputElement.focus())}},r.prototype.onMouseOver=function(e){var i=t.closest(e.target,"."+me);i&&i.classList.contains(me)&&!i.classList.contains(ve)&&t.addClass([i],ve)},r.prototype.onMouseLeave=function(e){var i=t.closest(e.target,"."+ve);t.isNullOrUndefined(i)||t.removeClass([i],ve)},r.prototype.setListSelection=function(e,i){if(e&&(!e.classList.contains(q)||this.isMobile&&e.classList.contains(q))){if(this.isMobile&&e.classList.contains(q)){this.activeIndex=Array.prototype.slice.call(this.liCollections).indexOf(e);if("custom_range"===this.presetsItem[this.activeIndex].id)return void this.renderCustomPopup();return}this.removeListSelection(),this.activeIndex=Array.prototype.slice.call(this.liCollections).indexOf(e),t.addClass([e],q),e.setAttribute("aria-selected","true");var s=this.presetsItem[this.activeIndex];"custom_range"===s.id?this.renderCustomPopup():this.applyPresetRange(s)}},r.prototype.removeListSelection=function(){var e=this.presetElement.querySelector("."+q);t.isNullOrUndefined(e)||(t.removeClass([e],q),e.removeAttribute("aria-selected"))},r.prototype.setValue=function(){this.modelValue=[this.startValue,this.endValue]},r.prototype.applyPresetRange=function(e){this.hide(null),this.presetsItem[this.presetsItem.length-1].start=null,this.presetsItem[this.presetsItem.length-1].end=null,this.startValue=e.start,this.endValue=e.end,this.setValue(),this.refreshControl(),this.trigger("select",this.rangeArgs(null)),this.changeTrigger(),this.previousEleValue=this.inputElement.value,this.isCustomRange=!1,this.leftCalendar=this.rightCalendar=null,this.isKeyPopup&&(this.isRangeIconClicked=!1,this.inputElement.focus())},r.prototype.showPopup=function(e,t){this.presetHeight(),1e3===this.zIndex?this.popupObj.show(null,this.element):this.popupObj.show(null,null),this.isMobile&&this.popupObj.refreshPosition()},r.prototype.renderCustomPopup=function(){this.isCustomWindow=!0,this.popupObj.hide(),this.popupWrapper=this.createElement("div",{id:this.element.id+"_popup",className:z+" e-popup"}),this.renderControl(),this.openEventArgs.appendTo.appendChild(this.popupWrapper),this.showPopup(),this.isCustomRange=!0,this.isMobile||this.calendarFocus()},r.prototype.listRippleEffect=function(){for(var e=0,i=this.liCollections;e<i.length;e++){var s=i[e];t.rippleEffect(s)}},r.prototype.createPresets=function(){if(!t.isUndefined(this.presets[0].start&&this.presets[0].end&&this.presets[0].label)){this.presetElement=this.createElement("div",{className:re,attrs:{tabindex:"0"}});var e=n.ListBase.createList(this.createElement,this.presetsItem,null,!0);t.attributes(e,{role:"listbox","aria-hidden":"false",id:this.element.id+"_options"}),this.presetElement.appendChild(e),this.popupWrapper.appendChild(this.presetElement);var i=this.presetElement.querySelector("#custom_range");t.isNullOrUndefined(i)||(i.textContent=""!==this.l10n.getConstant("customRange")?this.l10n.getConstant("customRange"):"Custom Range"),this.liCollections=this.presetElement.querySelectorAll("."+me),this.wireListEvents(),this.isMobile&&(this.presetElement.style.width=this.inputWrapper.container.getBoundingClientRect().width+"px"),!t.isNullOrUndefined(this.activeIndex)&&this.activeIndex>-1&&t.addClass([this.liCollections[this.activeIndex]],q)}},r.prototype.wireListEvents=function(){t.EventHandler.add(this.presetElement,"click",this.onMouseClick,this),this.isMobile||(t.EventHandler.add(this.presetElement,"mouseover",this.onMouseOver,this),t.EventHandler.add(this.presetElement,"mouseout",this.onMouseLeave,this))},r.prototype.unWireListEvents=function(){t.isNullOrUndefined(this.presetElement)||(t.EventHandler.remove(this.presetElement,"click touchstart",this.onMouseClick),this.isMobile||(t.EventHandler.remove(this.presetElement,"mouseover",this.onMouseOver),t.EventHandler.remove(this.presetElement,"mouseout",this.onMouseLeave)))},r.prototype.renderPopup=function(){var e=this;this.popupWrapper.classList.add("e-control");var s=this.popupWrapper.getBoundingClientRect().width;t.isNullOrUndefined(this.cssClass)||""===this.cssClass.trim()||(this.popupWrapper.className+=" "+this.cssClass),this.isMobile&&this.isCustomWindow&&(this.modal=this.createElement("div"),document.body.appendChild(this.modal)),this.popupObj=new i.Popup(this.popupWrapper,{relateTo:this.isMobile&&this.isCustomWindow?document.body:t.isNullOrUndefined(this.targetElement)?this.inputWrapper.container:this.targetElement,position:this.isMobile?t.isUndefined(this.presets[0].start&&this.presets[0].end&&this.presets[0].label)||this.isCustomWindow?{X:"center",Y:"center"}:{X:"left",Y:"bottom"}:this.enableRtl?{X:"left",Y:"bottom"}:{X:"right",Y:"bottom"},offsetX:this.isMobile||this.enableRtl?0:-s,offsetY:4,collision:this.isMobile?t.isUndefined(this.presets[0].start&&this.presets[0].end&&this.presets[0].label)||this.isCustomWindow?{X:"fit",Y:"fit"}:{X:"fit"}:{X:"fit",Y:"flip"},targetType:this.isMobile&&this.isCustomWindow?"container":"relative",enableRtl:this.enableRtl,zIndex:this.zIndex,open:function(){t.attributes(e.inputElement,{"aria-expanded":"true"}),t.addClass([e.inputWrapper.buttons[0]],q),e.isMobile||(e.cancelButton&&(e.btnKeyboardModule=new t.KeyboardEvents(e.cancelButton.element,{eventName:"keydown",keyAction:e.popupKeyActionHandle.bind(e),keyConfigs:{tab:"tab",altRightArrow:"alt+rightarrow",altLeftArrow:"alt+leftarrow"}}),e.btnKeyboardModule=new t.KeyboardEvents(e.applyButton.element,{eventName:"keydown",keyAction:e.popupKeyActionHandle.bind(e),keyConfigs:{altRightArrow:"alt+rightarrow",altLeftArrow:"alt+leftarrow"}})),t.isNullOrUndefined(e.leftCalendar)||e.isRangeIconClicked||e.calendarFocus(),t.isNullOrUndefined(e.presetElement)||(e.keyInputConfigs=t.extend(e.keyInputConfigs,e.keyConfigs),e.presetKeyboardModule=new t.KeyboardEvents(e.presetElement,{eventName:"keydown",keyAction:e.presetKeyActionHandler.bind(e),keyConfigs:e.keyInputConfigs}),e.presetKeyboardModule=new t.KeyboardEvents(e.presetElement,{eventName:"keydown",keyAction:e.popupKeyActionHandle.bind(e),keyConfigs:{altRightArrow:"alt+rightarrow",altLeftArrow:"alt+leftarrow"}}),t.isNullOrUndefined(e.leftCalendar)?(e.preventBlur=!0,e.presetElement.focus()):e.presetElement.setAttribute("tabindex","-1")),e.popupKeyBoardHandler()),e.isMobile&&!t.Browser.isDevice&&t.EventHandler.add(document,"keydown",e.popupCloseHandler,e)},close:function(){t.attributes(e.inputElement,{"aria-expanded":"false"}),t.removeClass([e.inputWrapper.buttons[0]],q),e.isRangeIconClicked&&e.inputWrapper.container.children[1].focus(),t.isUndefined(e.presets[0].start&&e.presets[0].end&&e.presets[0].label)||e.unWireListEvents(),t.isNullOrUndefined(e.popupObj)||(t.isNullOrUndefined(e.popupObj.element.parentElement)||t.detach(e.popupObj.element),e.popupObj.destroy(),e.popupObj=null),e.isMobile&&!t.Browser.isDevice&&t.EventHandler.remove(document,"keydown",e.popupCloseHandler)}}),this.isMobile&&(this.popupObj.element.classList.add("e-device"),this.isMobile||this.popupObj.element.classList.add("e-bigger")),this.isMobile&&this.isCustomWindow&&(t.addClass([this.modal],["e-device",z,"e-range-modal"]),document.body.className+=" "+fe,this.modal.style.display="block"),t.EventHandler.add(document,"mousedown touchstart",this.documentHandler,this)},r.prototype.popupCloseHandler=function(e){switch(e.keyCode){case 27:this.hide(e)}},r.prototype.calendarFocus=function(){var e=this.popupObj&&this.popupObj.element.querySelector("."+K);if(e){var i=t.closest(e,"."+R);i=t.isNullOrUndefined(i)?this.leftCalendar:i,this.isRangeIconClicked?this.inputWrapper.container.focus():(this.preventBlur=!0,i.children[1].firstElementChild.focus()),t.addClass([e],le)}else this.isRangeIconClicked?this.inputWrapper.container.focus():(this.preventBlur=!0,this.leftCalendar.children[1].firstElementChild.focus())},r.prototype.presetHeight=function(){var e=this.popupObj&&this.popupObj.element.querySelector("."+re),i=this.popupObj&&this.popupObj.element.querySelector("."+ne);t.isNullOrUndefined(e)||t.isNullOrUndefined(i)||(e.style.height=i.getBoundingClientRect().height+"px")},r.prototype.presetKeyActionHandler=function(e){switch(e.action){case"moveDown":this.listMoveDown(e),this.setScrollPosition(),e.preventDefault();break;case"moveUp":this.listMoveUp(e),this.setScrollPosition(),e.preventDefault();break;case"enter":var i=this.getHoverLI(),s=this.getActiveLI();if(!t.isNullOrUndefined(this.leftCalendar)&&!t.isNullOrUndefined(s)&&(t.isNullOrUndefined(i)||!t.isNullOrUndefined(s)&&s===i)){this.activeIndex=Array.prototype.slice.call(this.liCollections).indexOf(s);if("custom_range"===this.presetsItem[this.activeIndex].id)return this.calendarFocus(),s.classList.remove(ve),void e.preventDefault()}t.isNullOrUndefined(i)&&t.isNullOrUndefined(s)||this.onMouseClick(e,i||s),e.preventDefault();break;case"tab":if(this.leftCalendar){var a=this.getHoverLI();t.isNullOrUndefined(a)||a.classList.remove(ve)}else this.hide(e),e.preventDefault()}},r.prototype.listMoveDown=function(e){var i=this.getHoverLI(),s=this.getActiveLI();if(t.isNullOrUndefined(i))if(t.isNullOrUndefined(s))t.addClass([this.liCollections[0]],ve);else{a=s.nextElementSibling;!t.isNullOrUndefined(a)&&a.classList.contains(me)&&t.addClass([a],ve)}else{var a=i.nextElementSibling;!t.isNullOrUndefined(a)&&a.classList.contains(me)&&(t.removeClass([i],ve),t.addClass([a],ve))}},r.prototype.listMoveUp=function(e){var i=this.getHoverLI(),s=this.getActiveLI();if(t.isNullOrUndefined(i)){if(!t.isNullOrUndefined(s)){a=s.previousElementSibling;!t.isNullOrUndefined(a)&&a.classList.contains(me)&&t.addClass([a],ve)}}else{var a=i.previousElementSibling;!t.isNullOrUndefined(a)&&a.classList.contains(me)&&(t.removeClass([i],ve),t.addClass([a],ve))}},r.prototype.getHoverLI=function(){return this.presetElement.querySelector("."+ve)},r.prototype.getActiveLI=function(){return this.presetElement.querySelector("."+q)},r.prototype.popupKeyBoardHandler=function(){this.popupKeyboardModule=new t.KeyboardEvents(this.popupWrapper,{eventName:"keydown",keyAction:this.popupKeyActionHandle.bind(this),keyConfigs:{escape:"escape"}}),this.keyInputConfigs=t.extend(this.keyInputConfigs,this.keyConfigs),this.popupKeyboardModule=new t.KeyboardEvents(this.inputWrapper.container.children[1],{eventName:"keydown",keyAction:this.popupKeyActionHandle.bind(this),keyConfigs:this.keyInputConfigs})},r.prototype.setScrollPosition=function(){var e=this.presetElement.getBoundingClientRect().height,i=this.presetElement.querySelector("."+ve),s=this.presetElement.querySelector("."+q),a=t.isNullOrUndefined(i)?s:i;if(!t.isNullOrUndefined(a)){var n=a.nextElementSibling,r=n?n.offsetTop:a.offsetTop,l=a.getBoundingClientRect().height;r+a.offsetTop>e?this.presetElement.scrollTop=n?r-(e/2+l/2):r:this.presetElement.scrollTop=0}},r.prototype.popupKeyActionHandle=function(e){var i=t.closest(e.target,"."+re);switch(e.action){case"escape":this.isPopupOpen()?(this.isKeyPopup&&(this.inputElement.focus(),this.isKeyPopup=!1),this.hide(e)):this.inputWrapper.container.children[1].blur();break;case"enter":this.isPopupOpen()?this.inputWrapper.container.children[1].focus():this.show(null,e);break;case"tab":this.hide(e);break;case"altRightArrow":t.isNullOrUndefined(i)?document.activeElement===this.cancelButton.element&&!0!==this.applyButton.element.disabled?this.applyButton.element.focus():this.leftCalendar.children[1].firstElementChild.focus():this.cancelButton.element.focus(),e.preventDefault();break;case"altLeftArrow":t.isNullOrUndefined(i)?document.activeElement===this.applyButton.element&&!0!==this.applyButton.element.disabled?this.cancelButton.element.focus():t.isNullOrUndefined(this.presetElement)||document.activeElement!==this.cancelButton.element?this.rightCalendar.children[1].firstElementChild.focus():this.presetElement.focus():this.rightCalendar.children[1].firstElementChild.focus(),e.preventDefault()}},r.prototype.documentHandler=function(e){if(!t.isNullOrUndefined(this.popupObj)){var i=e.target;this.inputWrapper.container.contains(i)&&(t.isNullOrUndefined(this.popupObj)||t.closest(i,this.popupWrapper.id))||("touchstart"===e.type||"mousedown"===e.type||this.closeEventArgs&&!this.closeEventArgs.cancel)&&e.preventDefault(),!t.isNullOrUndefined(this.targetElement)&&(t.isNullOrUndefined(this.targetElement)||i===this.targetElement)||t.closest(i,"#"+this.popupObj.element.id)||t.closest(i,".e-input-group")===this.inputWrapper.container||t.closest(i,".e-daterangepicker.e-popup")&&!i.classList.contains("e-day")||(this.preventBlur=!1,this.isPopupOpen()&&(this.applyFunction(e),this.isMobile||(this.isRangeIconClicked=!1)))}},r.prototype.createInput=function(){this.inputWrapper=s.Input.createInput({floatLabelType:this.floatLabelType,element:this.inputElement,properties:{readonly:this.readonly,placeholder:this.placeholder,cssClass:this.cssClass,enabled:this.enabled,enableRtl:this.enableRtl,showClearButton:this.showClearButton},buttons:["e-input-group-icon e-range-icon e-icons"]},this.createElement),t.attributes(this.inputElement,{"aria-readonly":this.readonly?"true":"false",tabindex:"0","aria-haspopup":"true","aria-activedescendant":"null","aria-owns":this.element.id+"_popup","aria-expanded":"false",role:"daterangepicker",autocomplete:"off","aria-disabled":this.enabled?"false":"true",autocorrect:"off",autocapitalize:"off",spellcheck:"false"}),s.Input.addAttributes({"aria-label":"select"},this.inputWrapper.buttons[0]),t.isNullOrUndefined(this.placeholder)||""===this.placeholder.trim()||s.Input.addAttributes({"aria-placeholder":this.placeholder},this.inputElement),this.setEleWidth(this.width),t.addClass([this.inputWrapper.container],"e-date-range-wrapper"),t.isNullOrUndefined(this.inputElement.getAttribute("name"))&&t.attributes(this.inputElement,{name:this.element.id}),"hidden"===this.inputElement.type&&(this.inputWrapper.container.style.display="none"),this.refreshControl(),this.previousEleValue=this.inputElement.value,this.inputElement.setAttribute("value",this.inputElement.value),this.startCopy=this.startDate,this.endCopy=this.endDate},r.prototype.setEleWidth=function(e){this.inputWrapper.container.style.width="string"==typeof e?this.width:"number"==typeof e?t.formatUnit(this.width):"100%"},r.prototype.adjustLongHeaderWidth=function(){"Wide"===this.dayHeaderFormat&&t.addClass([this.popupWrapper],"e-daterange-day-header-lg")},r.prototype.refreshControl=function(){this.validateMinMax(),this.strictMode&&this.validateRangeStrict();var e=this.disabledDates();this.strictMode&&e&&(this.startValue=this.previousStartValue,this.setProperties({startDate:this.startValue},!0),this.endValue=this.previousEndValue,this.setProperties({endDate:this.endValue},!0),this.setValue()),this.updateInput(),this.strictMode||this.validateRange(),!this.strictMode&&e&&this.clearRange(),t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)||e||this.disabledDateRender(),this.errorClass(),this.previousStartValue=t.isNullOrUndefined(this.startValue)||isNaN(+this.startValue)?null:new Date(+this.startValue),this.previousEndValue=t.isNullOrUndefined(this.endValue)||isNaN(+this.endValue)?null:new Date(+this.endValue)},r.prototype.updateInput=function(){if(!t.isNullOrUndefined(this.endValue)&&!t.isNullOrUndefined(this.startValue)){var e={format:this.formatString,type:"date",skeleton:"yMd"},i=this.globalize.formatDate(this.startValue,e),a=this.globalize.formatDate(this.endValue,e);s.Input.setValue(i+" "+this.separator+" "+a,this.inputElement,this.floatLabelType,this.showClearButton),this.previousStartValue=new Date(+this.startValue),this.previousEndValue=new Date(+this.endValue)}!this.strictMode&&t.isNullOrUndefined(this.value)&&this.invalidValueString&&s.Input.setValue(this.invalidValueString,this.inputElement,this.floatLabelType,this.showClearButton)},r.prototype.checkInvalidRange=function(e){if(!t.isNullOrUndefined(e)){var i=!1,s=void 0,a=void 0,n=null,r=null,l=null,o=!1,h=!1,u=!1;if("string"==typeof e){var d=e.split(" "+this.separator+" ");2===d.length?(n=d[0],r=d[1]):(i=!0,l=e)}else e.length>0?(s=e[0],a=e[1]):(s=e.start,a=e.end),s instanceof Date||"object"==typeof s?s instanceof Date?o=!0:t.isNullOrUndefined(s)||(u=!0):n=this.getstringvalue(s),a instanceof Date||"object"==typeof a?a instanceof Date?h=!0:t.isNullOrUndefined(a)||(u=!0):r=this.getstringvalue(a);(t.isNullOrUndefined(n)&&!o&&!t.isNullOrUndefined(r)||!t.isNullOrUndefined(n)&&!h&&t.isNullOrUndefined(r))&&(i=!0),u&&(n=r=l=null,i=!0),n&&(i=i||this.checkInvalidValue(n)),r&&(i=i||this.checkInvalidValue(r)),i&&(o&&!u&&(n=s.toLocaleDateString()),h&&!u&&(r=a.toLocaleDateString()),t.isNullOrUndefined(n)||t.isNullOrUndefined(r)?t.isNullOrUndefined(n)?t.isNullOrUndefined(r)||(l=r):l=n:l=n+" "+this.separator+" "+r,this.invalidValueString=l,this.setProperties({value:null},!0),this.setProperties({startValue:null},!0),this.setProperties({endValue:null},!0),this.startDate=null,this.endDate=null)}},r.prototype.getstringvalue=function(e){var i=null;return t.isNullOrUndefined(e)||"number"!=typeof e?t.isNullOrUndefined(e)||"string"!=typeof e||(i=""+e):i=e.toString(),i},r.prototype.checkInvalidValue=function(e){var i=e,s=!1,a=null;if(a={format:this.formatString,type:"date",skeleton:"yMd"},"string"!=typeof i)s=!0;else{var n=new t.Internationalization(this.locale);if(!this.checkDateValue(n.parseDate(i,a))){var r=null;r=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,(!/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/.test(i)&&!r.test(i)||/^[a-zA-Z0-9- ]*$/.test(i)||isNaN(+new Date(this.checkValue(i))))&&(s=!0)}}return s},r.prototype.isDateDisabled=function(e){if(t.isNullOrUndefined(e))return!1;var i=new Date(+e);if(+i<+this.min||+i>+this.max)return!0;this.virtualRenderCellArgs={date:i,isDisabled:!1};var s=this.virtualRenderCellArgs;return this.virtualRenderCellEvent(s),!!s.isDisabled},r.prototype.disabledDateRender=function(){this.disabledDays=[],this.disabledDayCnt=null;for(var e=new Date(+this.startValue),t=0;+e<=+this.endValue;){this.virtualRenderCellArgs={date:e,isDisabled:!1};var i=this.virtualRenderCellArgs;this.virtualRenderCellEvent(i),i.isDisabled&&(this.disabledDays.push(new Date(+i.date)),+e>+this.startValue&&+e<+this.endValue&&t++),this.addDay(e,1,null,this.max,this.min)}this.disabledDayCnt=t},r.prototype.virtualRenderCellEvent=function(e){t.extend(this.virtualRenderCellArgs,{name:"renderDayCell"}),this.trigger("renderDayCell",e)},r.prototype.disabledDates=function(){var e=!1,i=!1;return t.isNullOrUndefined(this.endValue)||t.isNullOrUndefined(this.startValue)||(e=this.isDateDisabled(this.startValue),i=this.isDateDisabled(this.endValue),this.currentDate=null,this.setValue()),e||i},r.prototype.setModelValue=function(){this.value||null!==this.startDate||null!==this.endDate?null===this.value||null===this.value.start?null===this.value?this.setProperties({value:[this.startDate,this.endDate]},!0):null===this.value.start&&this.setProperties({value:{start:this.startDate,end:this.endDate}},!0):this.value&&this.value.length>0||this.valueType&&this.valueType.length>0?(+this.startDate==+this.value[0]&&+this.endDate==+this.value[1]||this.setProperties({value:[this.startDate,this.endDate]},!0),this.value&&null==this.value[0]&&null==this.value[1]&&this.setProperties({value:null},!0)):this.value&&this.value.start&&this.setProperties({value:{start:this.startDate,end:this.endDate}},!0):this.setProperties({value:null},!0),this.createHiddenInput()},r.prototype.dispatchEvent=function(e,t){var i=document.createEvent("HTMLEvents");i.initEvent(t,!1,!0),e.dispatchEvent(i),this.firstHiddenChild.dispatchEvent(i)},r.prototype.changeTrigger=function(e){+this.initStartDate==+this.startValue&&+this.initEndDate==+this.endValue||(this.setProperties({endDate:this.checkDateValue(this.endValue)},!0),this.setProperties({startDate:this.checkDateValue(this.startValue)},!0),this.setModelValue(),this.trigger("change",this.rangeArgs(e))),this.previousEleValue=this.inputElement.value,this.initStartDate=this.checkDateValue(this.startValue),this.initEndDate=this.checkDateValue(this.endValue)},r.prototype.navigateTo=function(t,i){if(this.isPopupOpen()){if("month"===t.toLowerCase())t="Month";else if("year"===t.toLowerCase())t="Year";else{if("decade"!==t.toLowerCase())return;t="Decade"}this.getViewNumber(t)<this.getViewNumber(this.depth)&&(t=this.depth),this.isMobile?e.prototype.navigateTo.call(this,t,i):(i<this.min?i=new Date(+this.min):i>=this.max&&(i=new Date(+this.max)),"Month"===t&&this.isSameMonth(i,this.max)?i=new Date(this.max.getFullYear(),this.max.getMonth()-1,this.min.getDate()):"Year"===t&&this.isSameYear(i,this.max)?i=new Date(this.max.getFullYear()-1,this.max.getMonth(),this.max.getDate()):"Decade"===t&&this.isSameDecade(i,this.max)&&(i=new Date(this.max.getFullYear()-10,this.max.getMonth(),this.max.getDate())),this.leftCalCurrentDate=i,this.navigate(this.leftCalendar,this.leftCalCurrentDate,t),i="Month"===t?new Date(this.currentDate.setMonth(this.currentDate.getMonth()+1)):"Year"===t?new Date(this.currentDate.setFullYear(this.currentDate.getFullYear()+1)):new Date(this.currentDate.setFullYear(this.currentDate.getFullYear()+10)),this.rightCalCurrentDate=i,this.navigate(this.rightCalendar,this.rightCalCurrentDate,t),this.leftKeyboardModule=this.rightKeyboardModule=null,this.updateNavIcons()),this.currentView()===this.depth&&this.bindCalendarCellEvents(),this.removeFocusedDate(),this.updateRange(this.isMobile?[this.calendarElement]:[this.leftCalendar,this.rightCalendar])}},r.prototype.navigate=function(t,i,s){this.calendarElement=t,this.table=t.querySelector("table"),this.tableBodyElement=t.querySelector("tbody"),this.headerTitleElement=t.querySelector(".e-title"),this.tableHeadElement=t.querySelector("thead"),this.contentElement=t.querySelector(".e-content"),this.previousIcon=t.querySelector(".e-prev"),this.nextIcon=t.querySelector(".e-next"),this.effect="e-zoomin",e.prototype.navigateTo.call(this,s,i)},r.prototype.focusIn=function(){document.activeElement!==this.inputElement&&this.enabled&&(t.addClass([this.inputWrapper.container],[G]),this.inputElement.focus())},r.prototype.focusOut=function(){var e=this.preventBlur;document.activeElement===this.inputElement&&(t.removeClass([this.inputWrapper.container],[G]),this.preventBlur=!1,this.inputElement.blur(),this.preventBlur=e)},r.prototype.destroy=function(){this.hide(null);var i={"aria-readonly":this.readonly?"true":"false",tabindex:"0","aria-haspopup":"true","aria-activedescendant":"null","aria-owns":this.element.id+"_popup","aria-expanded":"false",role:"daterangepicker",autocomplete:"off","aria-disabled":this.enabled?"false":"true",autocorrect:"off",autocapitalize:"off","aria-invalid":"false",spellcheck:"false"};this.inputElement&&(t.removeClass([this.inputElement],[z]),t.EventHandler.remove(this.inputElement,"blur",this.inputBlurHandler),s.Input.removeAttributes(i,this.inputElement),t.isNullOrUndefined(this.cloneElement.getAttribute("tabindex"))?this.inputElement.removeAttribute("tabindex"):this.inputElement.setAttribute("tabindex",this.tabIndex),this.ensureInputAttribute(),this.inputElement.classList.remove("e-input"),t.isNullOrUndefined(this.inputWrapper)||(t.EventHandler.remove(this.inputWrapper.buttons[0],"mousedown",this.rangeIconHandler),null===this.angularTag&&this.inputWrapper.container.parentElement.appendChild(this.inputElement),t.detach(this.inputWrapper.container))),t.isNullOrUndefined(this.inputKeyboardModule)||this.isMobile||this.inputKeyboardModule.destroy(),this.popupObj&&(this.isMobile||this.clearCalendarEvents()),e.prototype.destroy.call(this),this.inputWrapper=this.popupWrapper=this.popupObj=this.cloneElement=this.presetElement=null,this.formElement&&t.EventHandler.remove(this.formElement,"reset",this.formResetHandler),t.isNullOrUndefined(this.firstHiddenChild)||t.isNullOrUndefined(this.secondHiddenChild)||(t.detach(this.firstHiddenChild),t.detach(this.secondHiddenChild),this.firstHiddenChild=this.secondHiddenChild=null,this.inputElement.setAttribute("name",this.element.getAttribute("data-name")),this.inputElement.removeAttribute("data-name"))},r.prototype.ensureInputAttribute=function(){for(var e=[],i=0;i<this.inputElement.attributes.length;i++)e[i]=this.inputElement.attributes[i].name;for(i=0;i<e.length;i++)t.isNullOrUndefined(this.cloneElement.getAttribute(e[i]))?("value"===e[i].toLowerCase()&&(this.inputElement.value=""),this.inputElement.removeAttribute(e[i])):("value"===e[i].toLowerCase()&&(this.inputElement.value=this.cloneElement.getAttribute(e[i])),this.inputElement.setAttribute(e[i],this.cloneElement.getAttribute(e[i])))},r.prototype.getModuleName=function(){return"daterangepicker"},r.prototype.getPersistData=function(){return this.addOnPersist(["startDate","endDate","value"])},r.prototype.getSelectedRange=function(){var e;return t.isNullOrUndefined(this.startValue)||t.isNullOrUndefined(this.endValue)?e=0:(e=Math.round(Math.abs((this.startValue.getTime()-this.endValue.getTime())/864e5))+1,this.disabledDateRender(),t.isNullOrUndefined(this.disabledDayCnt)||(e-=this.disabledDayCnt,this.disabledDayCnt=null)),{startDate:this.startValue,endDate:this.endValue,daySpan:e}},r.prototype.show=function(i,s){var a=this;if(this.isMobile&&this.popupObj&&this.popupObj.refreshPosition(),!(this.enabled&&this.readonly||!this.enabled||this.popupObj||this.isPopupOpen())){i&&(this.targetElement=i),this.createPopup(),(this.isMobile||t.Browser.isDevice)&&(this.mobileRangePopupWrap=this.createElement("div",{className:"e-daterangepick-mob-popup-wrap"}),document.body.appendChild(this.mobileRangePopupWrap)),this.openEventArgs={popup:this.popupObj||null,cancel:!1,date:this.inputElement.value,model:this,event:s||null,appendTo:this.isMobile||t.Browser.isDevice?this.mobileRangePopupWrap:document.body};var n=this.openEventArgs;this.trigger("open",n,function(n){if(a.openEventArgs=n,!a.openEventArgs.cancel){a.openEventArgs.appendTo.appendChild(a.popupWrapper),a.showPopup(i,s);var r=!a.isCustomRange||a.isMobile&&a.isCustomRange;!t.isUndefined(a.presets[0].start&&a.presets[0].end&&a.presets[0].label)&&r&&a.setScrollPosition(),a.checkMinMaxDays(),a.isMobile&&!t.isNullOrUndefined(a.startDate)&&t.isNullOrUndefined(a.endDate)&&(a.endButton.element.classList.add(q),a.startButton.element.classList.remove(q),a.endButton.element.removeAttribute("disabled"),a.selectableDates()),e.prototype.setOverlayIndex.call(a,a.mobileRangePopupWrap,a.popupObj.element,a.modal,a.isMobile||t.Browser.isDevice)}})}},r.prototype.hide=function(e){var i=this;if(this.popupObj){if(t.isNullOrUndefined(this.previousEndValue)&&t.isNullOrUndefined(this.previousStartValue)?this.clearRange():(t.isNullOrUndefined(this.previousStartValue)?(this.startValue=null,this.setValue()):(this.startValue=new Date(this.checkValue(this.previousStartValue)),this.setValue(),this.currentDate=new Date(this.checkValue(this.startValue))),t.isNullOrUndefined(this.previousEndValue)?(this.endValue=null,this.setValue()):(this.endValue=new Date(this.checkValue(this.previousEndValue)),this.setValue())),this.isPopupOpen()){this.closeEventArgs={cancel:!1,popup:this.popupObj,date:this.inputElement.value,model:this,event:e||null};var s=this.closeEventArgs;this.trigger("close",s,function(e){i.closeEventArgs=e,i.closeEventArgs.cancel?t.removeClass([i.inputWrapper.buttons[0]],q):(i.isMobile&&(t.isNullOrUndefined(i.startButton)||t.isNullOrUndefined(i.endButton)||(t.EventHandler.remove(i.startButton.element,"click touchstart",i.deviceHeaderClick),t.EventHandler.remove(i.endButton.element,"click touchstart",i.deviceHeaderClick))),i.popupObj&&(i.popupObj.hide(),i.preventBlur&&(i.inputElement.focus(),t.addClass([i.inputWrapper.container],[G]))),i.isMobile||(t.isNullOrUndefined(i.leftKeyboardModule)||t.isNullOrUndefined(i.rightKeyboardModule)||(i.leftKeyboardModule.destroy(),i.rightKeyboardModule.destroy()),t.isNullOrUndefined(i.presetElement)||i.presetKeyboardModule.destroy(),t.isNullOrUndefined(i.cancelButton)||i.btnKeyboardModule.destroy()),i.targetElement=null,t.removeClass([document.body],fe),t.EventHandler.remove(document,"mousedown touchstart",i.documentHandler),i.isMobile&&i.modal&&(i.modal.style.display="none",i.modal.outerHTML="",i.modal=null),(i.isMobile||t.Browser.isDevice)&&(t.isNullOrUndefined(i.mobileRangePopupWrap)||(i.mobileRangePopupWrap.remove(),i.mobileRangePopupWrap=null)),i.isKeyPopup=i.dateDisabled=!1),i.updateClearIconState(),i.updateHiddenInput(),i.isMobile&&i.allowEdit&&!i.readonly&&i.inputElement.removeAttribute("readonly")})}}else this.updateClearIconState(),this.updateHiddenInput(),this.isMobile&&this.allowEdit&&!this.readonly&&this.inputElement.removeAttribute("readonly")},r.prototype.setLocale=function(){this.globalize=new t.Internationalization(this.locale),this.l10n.setLocale(this.locale),this.setProperties({placeholder:this.l10n.getConstant("placeholder")},!0),s.Input.setPlaceholder(this.placeholder,this.inputElement),this.updateInput(),this.changeTrigger()},r.prototype.refreshChange=function(){this.checkView(),this.refreshControl(),this.changeTrigger()},r.prototype.setDate=function(){s.Input.setValue("",this.inputElement,this.floatLabelType,this.showClearButton),this.refreshChange()},r.prototype.enableInput=function(){+this.min<=+this.max&&(this.setProperties({enabled:!0},!0),s.Input.setEnabled(this.enabled,this.inputElement),this.element.hasAttribute("disabled")&&this.bindEvents())},r.prototype.clearModelvalue=function(e,t){this.setProperties({startDate:null},!0),this.setProperties({endDate:null},!0),t.value&&t.value.length>0?this.setProperties({value:null},!0):t.value&&t.value.start?this.setProperties({value:{start:null,end:null}},!0):t.value&&!t.value.start&&this.setProperties({value:{start:null,end:null}},!0),this.updateValue(),this.setDate()},r.prototype.createHiddenInput=function(){t.isNullOrUndefined(this.firstHiddenChild)&&t.isNullOrUndefined(this.secondHiddenChild)&&(this.firstHiddenChild=this.createElement("input"),this.secondHiddenChild=this.createElement("input")),t.isNullOrUndefined(this.inputElement.getAttribute("name"))||(this.inputElement.setAttribute("data-name",this.inputElement.getAttribute("name")),this.inputElement.removeAttribute("name")),t.attributes(this.firstHiddenChild,{type:"text",name:this.inputElement.getAttribute("data-name")}),t.attributes(this.secondHiddenChild,{type:"text",name:this.inputElement.getAttribute("data-name")});var e={type:"datetime",skeleton:"yMd"};this.firstHiddenChild.value=this.startDate&&this.globalize.formatDate(this.startDate,e),this.secondHiddenChild.value=this.endDate&&this.globalize.formatDate(this.endDate,e),this.inputElement.parentElement.appendChild(this.firstHiddenChild),this.inputElement.parentElement.appendChild(this.secondHiddenChild),this.firstHiddenChild.style.display="none",this.secondHiddenChild.style.display="none"},r.prototype.onPropertyChanged=function(e,i){for(var a={format:this.formatString,type:"date",skeleton:"yMd"},n=0,r=Object.keys(e);n<r.length;n++){var l=r[n];switch(this.hide(null),l){case"width":this.setEleWidth(this.width);break;case"separator":this.previousEleValue=this.inputElement.value,this.setProperties({separator:e.separator},!0),this.updateInput(),this.changeTrigger();break;case"placeholder":s.Input.setPlaceholder(e.placeholder,this.inputElement),this.setProperties({placeholder:e.placeholder},!0);break;case"readonly":s.Input.setReadonly(this.readonly,this.inputElement),this.inputElement.setAttribute("aria-readonly",""+this.readonly),this.setRangeAllowEdit();break;case"cssClass":s.Input.setCssClass(e.cssClass,[this.inputWrapper.container],i.cssClass),this.popupWrapper&&s.Input.setCssClass(e.cssClass,[this.popupWrapper],i.cssClass);break;case"enabled":this.setProperties({enabled:e.enabled},!0),s.Input.setEnabled(this.enabled,this.inputElement),this.bindEvents();break;case"allowEdit":this.setRangeAllowEdit();break;case"enableRtl":this.setProperties({enableRtl:e.enableRtl},!0),s.Input.setEnableRtl(this.enableRtl,[this.inputWrapper.container]);break;case"zIndex":this.setProperties({zIndex:e.zIndex},!0);break;case"format":this.setProperties({format:e.format},!0),this.checkFormat(),this.updateInput(),this.changeTrigger();break;case"locale":this.globalize=new t.Internationalization(this.locale),this.l10n.setLocale(this.locale),this.setProperties({placeholder:this.l10n.getConstant("placeholder")},!0),s.Input.setPlaceholder(this.placeholder,this.inputElement),this.setLocale();break;case"htmlAttributes":this.updateHtmlAttributeToElement(),this.updateHtmlAttributeToWrapper(),this.checkHtmlAttributes(!0);break;case"showClearButton":s.Input.setClearButton(this.showClearButton,this.inputElement,this.inputWrapper),this.bindClearEvent();break;case"startDate":"string"==typeof e.startDate&&(e.startDate=this.globalize.parseDate(e.startDate,a)),+this.initStartDate!=+e.startDate&&(this.startValue=this.checkDateValue(new Date(this.checkValue(e.startDate))),this.setDate(),this.setValue());break;case"endDate":"string"==typeof e.endDate&&(e.endDate=this.globalize.parseDate(e.endDate,a)),+this.initEndDate!=+e.endDate&&(this.endValue=this.checkDateValue(new Date(this.checkValue(e.endDate))),this.setDate(),this.setValue());break;case"value":if(this.invalidValueString=null,this.checkInvalidRange(e.value),"string"==typeof e.value)if(this.invalidValueString)this.clearModelvalue(e,i);else{var o=e.value.split(" "+this.separator+" ");this.value=[new Date(o[0]),new Date(o[1])],this.updateValue(),this.setDate()}else!t.isNullOrUndefined(e.value)&&e.value.length>0||!t.isNullOrUndefined(e.value)&&e.value.start?(this.valueType=e.value,null===e.value[0]||null===e.value.start?1===e.value.length||e.value.start?this.clearModelvalue(e,i):null!==e.value[1]&&null!==e.value.start||this.clearModelvalue(e,i):+this.initStartDate==+e.value[0]&&+this.initEndDate==+e.value[1]&&+this.initStartDate==+(e.value.start||+this.initEndDate!=+e.value.start)||(1===e.value.length?this.modelValue=e.value:e.value.start&&(this.modelValue=e.value),this.updateValue(),this.setDate())):(t.isNullOrUndefined(this.value)||null==e.value.start)&&(this.valueType=e.value,this.startValue=null,this.endValue=null,this.clearModelvalue(e,i));break;case"minDays":this.setProperties({minDays:e.minDays},!0),this.refreshChange();break;case"maxDays":this.setProperties({maxDays:e.maxDays},!0),this.refreshChange();break;case"min":this.setProperties({min:this.checkDateValue(new Date(this.checkValue(e.min)))},!0),this.previousEleValue=this.inputElement.value,this.enableInput(),this.refreshChange();break;case"max":this.setProperties({max:this.checkDateValue(new Date(this.checkValue(e.max)))},!0),this.enableInput(),this.refreshChange();break;case"strictMode":this.invalidValueString=null,this.setProperties({strictMode:e.strictMode},!0),this.refreshChange();break;case"presets":this.setProperties({presets:e.presets},!0),this.processPresets();break;case"floatLabelType":this.floatLabelType=e.floatLabelType,s.Input.removeFloating(this.inputWrapper),s.Input.addFloating(this.inputElement,this.floatLabelType,this.placeholder);break;case"start":this.setProperties({start:e.start},!0),this.refreshChange();break;case"depth":this.setProperties({depth:e.depth},!0),this.refreshChange()}}},j([t.Property(null)],r.prototype,"value",void 0),j([t.Property(!1)],r.prototype,"enablePersistence",void 0),j([t.Property(new Date(1900,0,1))],r.prototype,"min",void 0),j([t.Property(new Date(2099,11,31))],r.prototype,"max",void 0),j([t.Property(null)],r.prototype,"locale",void 0),j([t.Property(null)],r.prototype,"firstDayOfWeek",void 0),j([t.Property(!1)],r.prototype,"weekNumber",void 0),j([t.Property("Gregorian")],r.prototype,"calendarMode",void 0),j([t.Event()],r.prototype,"created",void 0),j([t.Event()],r.prototype,"destroyed",void 0),j([t.Event()],r.prototype,"change",void 0),j([t.Event()],r.prototype,"navigated",void 0),j([t.Event()],r.prototype,"renderDayCell",void 0),j([t.Property(null)],r.prototype,"startDate",void 0),j([t.Property(null)],r.prototype,"endDate",void 0),j([t.Collection([{}],be)],r.prototype,"presets",void 0),j([t.Property("")],r.prototype,"width",void 0),j([t.Property(1e3)],r.prototype,"zIndex",void 0),j([t.Property(!0)],r.prototype,"showClearButton",void 0),j([t.Property(!0)],r.prototype,"showTodayButton",void 0),j([t.Property("Month")],r.prototype,"start",void 0),j([t.Property("Month")],r.prototype,"depth",void 0),j([t.Property("")],r.prototype,"cssClass",void 0),j([t.Property("-")],r.prototype,"separator",void 0),j([t.Property(null)],r.prototype,"minDays",void 0),j([t.Property(null)],r.prototype,"maxDays",void 0),j([t.Property(!1)],r.prototype,"strictMode",void 0),j([t.Property(null)],r.prototype,"keyConfigs",void 0),j([t.Property(null)],r.prototype,"format",void 0),j([t.Property(!0)],r.prototype,"enabled",void 0),j([t.Property(!1)],r.prototype,"readonly",void 0),j([t.Property(!0)],r.prototype,"allowEdit",void 0),j([t.Property("Never")],r.prototype,"floatLabelType",void 0),j([t.Property(null)],r.prototype,"placeholder",void 0),j([t.Property({})],r.prototype,"htmlAttributes",void 0),j([t.Event()],r.prototype,"open",void 0),j([t.Event()],r.prototype,"close",void 0),j([t.Event()],r.prototype,"select",void 0),j([t.Event()],r.prototype,"focus",void 0),j([t.Event()],r.prototype,"blur",void 0),r=j([t.NotifyPropertyChanges],r)}(E),Ee=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(t,i)};return function(t,i){function s(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(s.prototype=i.prototype,new s)}}(),Ce=function(e,t,i,s){var a,n=arguments.length,r=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,i,s);else for(var l=e.length-1;l>=0;l--)(a=e[l])&&(r=(n<3?a(r):n>3?a(t,i,r):a(t,i))||r);return n>3&&r&&Object.defineProperty(t,i,r),r},we=(new Date).getDate(),Ve=(new Date).getMonth(),ke=(new Date).getFullYear(),Oe="e-timepicker",Ne="e-active",Me="e-navigation",Ie="e-disabled",xe="e-input-focus",Ae=n.cssClass.li,Te="e-non-edit",Ue=["title","class","style"];!function(t){(e.TimePickerBase||(e.TimePickerBase={})).createListItems=function(e,t,i,s,a,r){this.calendarMode;var l,o,h=6e4*r,u=[],d=[];for(l=+t.setMilliseconds(0),o=+i.setMilliseconds(0);o>=l;)d.push(l),u.push(s.formatDate(new Date(l),{format:a,type:"time"})),l+=h;return{collection:d,list:n.ListBase.createList(e,u,null,!0)}}}();var Pe=function(e){function a(t,i){var s=e.call(this,t,i)||this;return s.liCollections=[],s.timeCollections=[],s.disableItemCollection=[],s.invalidValueString=null,s.timeOptions=t,s}return Ee(a,e),a.prototype.preRender=function(){this.keyConfigure={enter:"enter",escape:"escape",end:"end",tab:"tab",home:"home",down:"downarrow",up:"uparrow",left:"leftarrow",right:"rightarrow",open:"alt+downarrow",close:"alt+uparrow"},this.cloneElement=this.element.cloneNode(!0),t.removeClass([this.cloneElement],[Oe,"e-control","e-lib"]),this.inputElement=this.element,this.angularTag=null,this.formElement=t.closest(this.element,"form"),"EJS-TIMEPICKER"===this.element.tagName&&(this.angularTag=this.element.tagName,this.inputElement=this.createElement("input"),this.element.appendChild(this.inputElement)),this.tabIndex=this.element.hasAttribute("tabindex")?this.element.getAttribute("tabindex"):"0",this.element.removeAttribute("tabindex"),this.openPopupEventArgs={appendTo:document.body}},a.prototype.render=function(){this.initialize(),this.createInputElement(),this.updateHtmlAttributeToWrapper(),this.setTimeAllowEdit(),this.setEnable(),this.validateInterval(),this.bindEvents(),this.validateDisable(),this.setValue(this.getFormattedValue(this.value)),this.anchor=this.inputElement,this.inputElement.setAttribute("value",this.inputElement.value),this.inputEleValue=this.getDateObject(this.inputElement.value),this.renderComplete()},a.prototype.setTimeAllowEdit=function(){this.allowEdit?this.readonly||this.inputElement.removeAttribute("readonly"):t.attributes(this.inputElement,{readonly:""}),this.clearIconState()},a.prototype.clearIconState=function(){this.allowEdit||!this.inputWrapper||this.readonly?this.inputWrapper&&t.removeClass([this.inputWrapper.container],[Te]):""===this.inputElement.value?t.removeClass([this.inputWrapper.container],[Te]):t.addClass([this.inputWrapper.container],[Te])},a.prototype.validateDisable=function(){this.setMinMax(this.initMin,this.initMax),this.popupCreation(),this.popupObj.destroy(),this.popupWrapper=this.popupObj=null,isNaN(+this.value)||null===this.value||this.valueIsDisable(this.value)||(this.strictMode&&this.resetState(),this.initValue=null,this.initMax=this.getDateObject(this.initMax),this.initMin=this.getDateObject(this.initMin),this.timeCollections=this.liCollections=[],this.setMinMax(this.initMin,this.initMax))},a.prototype.validationAttribute=function(e,i){var s=e.getAttribute("name")?e.getAttribute("name"):e.getAttribute("id");i.setAttribute("name",s),e.removeAttribute("name");for(var a=["required","aria-required","form"],n=0;n<a.length;n++)if(!t.isNullOrUndefined(e.getAttribute(a[n]))){var r=e.getAttribute(a[n]);i.setAttribute(a[n],r),e.removeAttribute(a[n])}},a.prototype.initialize=function(){this.globalize=new t.Internationalization(this.locale),this.defaultCulture=new t.Internationalization("en"),this.checkTimeFormat(),this.checkInvalidValue(this.value),this.setProperties({value:this.checkDateValue(new Date(this.checkInValue(this.value)))},!0),this.setProperties({min:this.checkDateValue(new Date(this.checkInValue(this.min)))},!0),this.setProperties({max:this.checkDateValue(new Date(this.checkInValue(this.max)))},!0),null!==this.angularTag&&this.validationAttribute(this.element,this.inputElement),this.updateHtmlAttributeToElement(),this.checkAttributes(!1);var e={placeholder:this.placeholder};this.l10n=new t.L10n("timepicker",e,this.locale),this.setProperties({placeholder:this.placeholder||this.l10n.getConstant("placeholder")},!0),this.initValue=this.checkDateValue(this.value),this.initMin=this.checkDateValue(this.min),this.initMax=this.checkDateValue(this.max),this.isNavigate=this.isPreventBlur=this.isTextSelected=!1,this.activeIndex=this.valueWithMinutes=this.prevDate=null,t.isNullOrUndefined(this.element.getAttribute("id"))?(this.element.id=t.getUniqueID("ej2_timepicker"),null!==this.angularTag&&t.attributes(this.inputElement,{id:this.element.id+"_input"})):null!==this.angularTag&&(this.inputElement.id=this.element.getAttribute("id")+"_input"),t.isNullOrUndefined(this.inputElement.getAttribute("name"))&&t.attributes(this.inputElement,{name:this.element.id})},a.prototype.checkTimeFormat=function(){if(this.format)if("string"==typeof this.format)this.formatString=this.format;else if(t.isNullOrUndefined(this.format.skeleton)||""===this.format.skeleton)this.formatString=this.globalize.getDatePattern({type:"time",skeleton:"short"});else{var e=this.format.skeleton;this.formatString=this.globalize.getDatePattern({type:"time",skeleton:e})}else this.formatString=null},a.prototype.checkDateValue=function(e){return!t.isNullOrUndefined(e)&&e instanceof Date&&!isNaN(+e)?e:null},a.prototype.createInputElement=function(){this.inputWrapper=s.Input.createInput({element:this.inputElement,floatLabelType:this.floatLabelType,properties:{readonly:this.readonly,placeholder:this.placeholder,cssClass:this.cssClass,enabled:this.enabled,enableRtl:this.enableRtl,showClearButton:this.showClearButton},buttons:[" e-input-group-icon e-time-icon e-icons"]},this.createElement),this.inputWrapper.container.style.width=this.setWidth(this.width),t.attributes(this.inputElement,{"aria-haspopup":"true","aria-autocomplete":"list",tabindex:"0","aria-activedescendant":"null","aria-owns":this.element.id+"_options","aria-expanded":"false",role:"combobox",autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false","aria-disabled":"false","aria-invalid":"false"}),this.isNullOrEmpty(this.inputStyle)||s.Input.addAttributes({style:this.inputStyle},this.inputElement),t.addClass([this.inputWrapper.container],"e-time-wrapper")},a.prototype.getCldrDateTimeFormat=function(){var e=new t.Internationalization(this.locale).getDatePattern({skeleton:"yMd"});return this.isNullOrEmpty(this.formatString)?e+" "+this.CldrFormat("time"):this.formatString},a.prototype.checkInvalidValue=function(e){var i=!1;if("object"!=typeof e&&!t.isNullOrUndefined(e)){var s=e;"string"==typeof s&&(s=s.trim());var a=null,n=null;if("number"==typeof e?s=e.toString():"string"==typeof e&&(/^[a-zA-Z0-9- ]*$/.test(e)||(a=this.setCurrentDate(this.getDateObject(e)),t.isNullOrUndefined(a)&&(a=this.checkDateValue(this.globalize.parseDate(s,{format:this.getCldrDateTimeFormat(),type:"datetime"})),t.isNullOrUndefined(a)&&(a=this.checkDateValue(this.globalize.parseDate(s,{format:this.formatString,type:"dateTime",skeleton:"yMd"})))))),n=this.globalize.parseDate(s,{format:this.getCldrDateTimeFormat(),type:"datetime"}),a=!t.isNullOrUndefined(n)&&n instanceof Date&&!isNaN(+n)?n:null,t.isNullOrUndefined(a)&&s.replace(/\s/g,"").length){var r=null;r=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,!/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/.test(s)&&!r.test(s)||/^[a-zA-Z0-9- ]*$/.test(e)||isNaN(+new Date(""+s))?i=!0:a=new Date(""+s)}i?(this.strictMode||(this.invalidValueString=s),this.setProperties({value:null},!0),this.initValue=null):(this.setProperties({value:a},!0),this.initValue=this.value)}},a.prototype.CldrFormat=function(e){return"en"===this.locale||"en-US"===this.locale?t.getValue("timeFormats.short",t.getDefaultDateObject()):this.getCultureTimeObject(t.cldrData,""+this.locale)},a.prototype.destroy=function(){this.hide(),this.unBindEvents();var i={"aria-haspopup":"true","aria-autocomplete":"list",tabindex:"0","aria-activedescendant":"null","aria-owns":this.element.id+"_options","aria-expanded":"false",role:"combobox",autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false","aria-disabled":"true","aria-invalid":"false"};this.inputElement&&(s.Input.removeAttributes(i,this.inputElement),null===this.angularTag&&this.inputWrapper.container.parentElement.appendChild(this.inputElement),t.isNullOrUndefined(this.cloneElement.getAttribute("tabindex"))?this.inputElement.removeAttribute("tabindex"):this.inputElement.setAttribute("tabindex",this.tabIndex),this.ensureInputAttribute(),this.enableElement([this.inputElement]),this.inputElement.classList.remove("e-input"),t.isNullOrUndefined(this.cloneElement.getAttribute("disabled"))&&s.Input.setEnabled(!0,this.inputElement,this.floatLabelType)),this.inputWrapper.container&&t.detach(this.inputWrapper.container),this.inputWrapper=this.popupWrapper=this.cloneElement=void 0,this.liCollections=this.timeCollections=this.disableItemCollection=[],t.isNullOrUndefined(this.rippleFn)||this.rippleFn(),e.prototype.destroy.call(this),this.formElement&&t.EventHandler.remove(this.formElement,"reset",this.formResetHandler)},a.prototype.ensureInputAttribute=function(){for(var e=[],i=0;i<this.inputElement.attributes.length;i++)e[i]=this.inputElement.attributes[i].name;for(i=0;i<e.length;i++)t.isNullOrUndefined(this.cloneElement.getAttribute(e[i]))?(this.inputElement.removeAttribute(e[i]),"value"===e[i].toLowerCase()&&(this.inputElement.value="")):(this.inputElement.setAttribute(e[i],this.cloneElement.getAttribute(e[i])),"value"===e[i].toLowerCase()&&(this.inputElement.value=this.cloneElement.getAttribute(e[i])))},a.prototype.popupCreation=function(){this.popupWrapper=this.createElement("div",{className:Oe+" e-popup",attrs:{id:this.element.id+"_popup",style:"visibility:hidden"}}),t.isNullOrUndefined(this.cssClass)||(this.popupWrapper.className+=" "+this.cssClass),!t.isNullOrUndefined(this.step)&&this.step>0&&(this.generateList(),t.append([this.listWrapper],this.popupWrapper)),this.openPopupEventArgs.appendTo.appendChild(this.popupWrapper),this.addSelection(),this.renderPopup(),t.detach(this.popupWrapper)},a.prototype.getPopupHeight=function(){var e=parseInt("240px",10),t=this.popupWrapper.getBoundingClientRect().height;return t>e?e:t},a.prototype.generateList=function(){this.createListItems(),this.wireListEvents();var e={duration:300,selector:"."+Ae};this.rippleFn=t.rippleEffect(this.listWrapper,e),this.liCollections=this.listWrapper.querySelectorAll("."+Ae)},a.prototype.renderPopup=function(){var e=this;this.containerStyle=this.inputWrapper.container.getBoundingClientRect(),this.popupObj=new i.Popup(this.popupWrapper,{width:this.setPopupWidth(this.width),zIndex:this.zIndex,targetType:"relative",position:t.Browser.isDevice?{X:"center",Y:"center"}:{X:"left",Y:"bottom"},collision:t.Browser.isDevice?{X:"fit",Y:"fit"}:{X:"flip",Y:"flip"},enableRtl:this.enableRtl,relateTo:t.Browser.isDevice?document.body:this.inputWrapper.container,offsetY:4,open:function(){e.popupWrapper.style.visibility="visible",t.addClass([e.inputWrapper.buttons[0]],Ne)},close:function(){t.removeClass([e.inputWrapper.buttons[0]],Ne),e.unWireListEvents(),e.inputElement.setAttribute("aria-activedescendant","null"),t.remove(e.popupObj.element),e.popupObj.destroy(),e.popupWrapper.innerHTML="",e.listWrapper=e.popupWrapper=e.listTag=void 0}}),t.Browser.isDevice||(this.popupObj.collision={X:"none",Y:"flip"}),this.popupObj.element.style.maxHeight="240px"},a.prototype.getFormattedValue=function(e){return t.isNullOrUndefined(this.checkDateValue(e))?null:this.globalize.formatDate(e,{skeleton:"medium",type:"time"})},a.prototype.getDateObject=function(e){if(!this.isNullOrEmpty(e)){var t=this.createDateObj(e),i=!this.isNullOrEmpty(this.initValue);if(this.checkDateValue(t)){var s=i?this.initValue.getDate():we,a=i?this.initValue.getMonth():Ve,n=i?this.initValue.getFullYear():ke;return new Date(n,a,s,t.getHours(),t.getMinutes(),t.getSeconds())}}return null},a.prototype.updateHtmlAttributeToWrapper=function(){if(!t.isNullOrUndefined(this.htmlAttributes))for(var e=0,i=Object.keys(this.htmlAttributes);e<i.length;e++){var s=i[e];if(Ue.indexOf(s)>-1)if("class"===s)t.addClass([this.inputWrapper.container],this.htmlAttributes[s].split(" "));else if("style"===s){var a=this.inputWrapper.container.getAttribute(s);a=t.isNullOrUndefined(a)?this.htmlAttributes[s]:a+this.htmlAttributes[s],this.inputWrapper.container.setAttribute(s,a)}else this.inputWrapper.container.setAttribute(s,this.htmlAttributes[s])}},a.prototype.updateHtmlAttributeToElement=function(){if(!t.isNullOrUndefined(this.htmlAttributes))for(var e=0,i=Object.keys(this.htmlAttributes);e<i.length;e++){var s=i[e];Ue.indexOf(s)<0&&this.inputElement.setAttribute(s,this.htmlAttributes[s])}},a.prototype.removeErrorClass=function(){t.removeClass([this.inputWrapper.container],"e-error"),t.attributes(this.inputElement,{"aria-invalid":"false"})},a.prototype.checkErrorState=function(e){var i=this.getDateObject(e);this.validateState(i)&&!this.invalidValueString?this.removeErrorClass():(t.addClass([this.inputWrapper.container],"e-error"),t.attributes(this.inputElement,{"aria-invalid":"true"}))},a.prototype.validateInterval=function(){!t.isNullOrUndefined(this.step)&&this.step>0?this.enableElement([this.inputWrapper.buttons[0]]):this.disableTimeIcon()},a.prototype.disableTimeIcon=function(){this.disableElement([this.inputWrapper.buttons[0]]),this.hide()},a.prototype.disableElement=function(e){t.addClass(e,Ie)},a.prototype.enableElement=function(e){t.removeClass(e,Ie)},a.prototype.selectInputText=function(){this.inputElement.setSelectionRange(0,this.inputElement.value.length)},a.prototype.getMeridianText=function(){return"en"===this.locale||"en-US"===this.locale?t.getValue("dayPeriods.format.wide",t.getDefaultDateObject()):t.getValue("main."+this.locale+".dates.calendars.gregorian.dayPeriods.format.abbreviated",t.cldrData)},a.prototype.getCursorSelection=function(){var e=this.inputElement,t=0,i=0;return isNaN(e.selectionStart)||(t=e.selectionStart,i=e.selectionEnd),{start:Math.abs(t),end:Math.abs(i)}},a.prototype.getActiveElement=function(){return t.isNullOrUndefined(this.popupWrapper)?null:this.popupWrapper.querySelectorAll("."+Ne)},a.prototype.isNullOrEmpty=function(e){return!!(t.isNullOrUndefined(e)||"string"==typeof e&&""===e.trim())},a.prototype.setWidth=function(e){return e="number"==typeof e?t.formatUnit(e):"string"==typeof e?e.match(/px|%|em/)?e:t.formatUnit(e):"100%"},a.prototype.setPopupWidth=function(e){if((e=this.setWidth(e)).indexOf("%")>-1){e=(this.containerStyle.width*parseFloat(e)/100).toString()+"px"}return e},a.prototype.setScrollPosition=function(){var e;this.getPopupHeight();e=this.selectedElement,t.isNullOrUndefined(e)?this.popupWrapper&&this.checkDateValue(this.scrollTo)&&this.setScrollTo():this.findScrollTop(e)},a.prototype.findScrollTop=function(e){var t=this.getPopupHeight(),i=e.nextElementSibling,s=i?i.offsetTop:e.offsetTop,a=e.getBoundingClientRect().height;s+e.offsetTop>t?this.popupWrapper.scrollTop=i?s-(t/2+a/2):s:this.popupWrapper.scrollTop=0},a.prototype.setScrollTo=function(){var e;if(t.isNullOrUndefined(this.popupWrapper))this.popupWrapper.scrollTop=0;else{var i=this.popupWrapper.querySelectorAll("."+Ae);if(i.length){var s=this.timeCollections[0],a=this.getDateObject(this.checkDateValue(this.scrollTo)).getTime();e=i[Math.round((a-s)/(6e4*this.step))]}}t.isNullOrUndefined(e)?this.popupWrapper.scrollTop=0:this.findScrollTop(e)},a.prototype.getText=function(){return t.isNullOrUndefined(this.checkDateValue(this.value))?"":this.getValue(this.value)},a.prototype.getValue=function(e){return t.isNullOrUndefined(this.checkDateValue(e))?null:this.globalize.formatDate(e,{format:this.cldrTimeFormat(),type:"time"})},a.prototype.cldrDateFormat=function(){return"en"===this.locale||"en-US"===this.locale?t.getValue("dateFormats.short",t.getDefaultDateObject()):this.getCultureDateObject(t.cldrData,""+this.locale)},a.prototype.cldrTimeFormat=function(){return this.isNullOrEmpty(this.formatString)?"en"===this.locale||"en-US"===this.locale?t.getValue("timeFormats.short",t.getDefaultDateObject()):this.getCultureTimeObject(t.cldrData,""+this.locale):this.formatString},a.prototype.dateToNumeric=function(){return"en"===this.locale||"en-US"===this.locale?t.getValue("timeFormats.medium",t.getDefaultDateObject()):t.getValue("main."+this.locale+".dates.calendars.gregorian.timeFormats.medium",t.cldrData)},a.prototype.getExactDateTime=function(e){return t.isNullOrUndefined(this.checkDateValue(e))?null:this.globalize.formatDate(e,{format:this.dateToNumeric(),type:"time"})},a.prototype.setValue=function(e){var t=this.checkValue(e);this.strictMode||this.validateState(t)?this.isNullOrEmpty(t)?(this.initValue=null,this.validateMinMax(this.value,this.min,this.max)):this.initValue=this.compareFormatChange(t):(null===this.checkDateValue(this.valueWithMinutes)&&(this.initValue=this.valueWithMinutes=null),this.validateMinMax(this.value,this.min,this.max)),this.updateInput(!0,this.initValue)},a.prototype.compareFormatChange=function(e){return t.isNullOrUndefined(e)?null:e!==this.getText()?this.getDateObject(e):this.getDateObject(this.value)},a.prototype.updatePlaceHolder=function(){s.Input.setPlaceholder(this.l10n.getConstant("placeholder"),this.inputElement)},a.prototype.popupHandler=function(e){t.Browser.isDevice&&this.inputElement.setAttribute("readonly",""),e.preventDefault(),this.isPopupOpen()?this.closePopup(0,e):(this.inputElement.focus(),this.show(e))},a.prototype.mouseDownHandler=function(){if(!this.readonly){this.getCursorSelection();this.inputElement.setSelectionRange(0,0),t.EventHandler.add(this.inputElement,"mouseup",this.mouseUpHandler,this)}},a.prototype.mouseUpHandler=function(e){if(!this.readonly){e.preventDefault(),t.EventHandler.remove(this.inputElement,"mouseup",this.mouseUpHandler);var i=this.getCursorSelection();0===i.start&&i.end===this.inputElement.value.length||(this.inputElement.value.length>0&&(this.cursorDetails=this.focusSelection()),this.inputElement.setSelectionRange(this.cursorDetails.start,this.cursorDetails.end))}},a.prototype.focusSelection=function(){var e=new RegExp("^[a-zA-Z0-9]+$"),t=this.inputElement.value.split("");t.push(" ");var i=this.getCursorSelection(),s=0,a=0,n=!1;if(this.isTextSelected)s=i.start,a=i.end,this.isTextSelected=!1;else for(var r=0;r<t.length;r++)if(e.test(t[r])||(a=r,n=!0),n){if(i.start>=s&&i.end<=a){a=a,this.isTextSelected=!0;break}s=r+1,n=!1}return{start:s,end:a}},a.prototype.inputHandler=function(e){if(!this.readonly&&this.enabled)switch("right"!==e.action&&"left"!==e.action&&"tab"!==e.action&&e.preventDefault(),e.action){case"home":case"end":case"up":case"down":this.keyHandler(e);break;case"enter":this.isNavigate?(this.selectedElement=this.liCollections[this.activeIndex],this.valueWithMinutes=new Date(this.timeCollections[this.activeIndex]),this.updateValue(this.valueWithMinutes,e)):this.updateValue(this.inputElement.value,e),this.hide(),t.addClass([this.inputWrapper.container],xe),this.isNavigate=!1,this.isPopupOpen()&&e.stopPropagation();break;case"open":this.show(e);break;case"escape":s.Input.setValue(this.objToString(this.value),this.inputElement,this.floatLabelType,this.showClearButton),this.previousState(this.value),this.hide();break;case"close":this.hide();break;default:this.isNavigate=!1}},a.prototype.onMouseClick=function(e){var i=e.target,s=this.selectedElement=t.closest(i,"."+Ae);this.setSelection(s,e),s&&s.classList.contains(Ae)&&(this.hide(),t.addClass([this.inputWrapper.container],xe))},a.prototype.closePopup=function(e,i){var s=this;if(this.isPopupOpen()&&this.popupWrapper){var a={popup:this.popupObj,event:i||null,cancel:!1,name:"open"};t.removeClass([document.body],"e-time-overflow"),this.trigger("close",a,function(i){if(!i.cancel){var a={name:"FadeOut",duration:50,delay:e||0};s.popupObj.hide(new t.Animation(a)),t.removeClass([s.inputWrapper.container],["e-icon-anim"]),t.attributes(s.inputElement,{"aria-expanded":"false"}),t.EventHandler.remove(document,"mousedown touchstart",s.documentClickHandler)}t.Browser.isDevice&&s.modal&&(s.modal.style.display="none",s.modal.outerHTML="",s.modal=null),t.Browser.isDevice&&s.allowEdit&&!s.readonly&&s.inputElement.removeAttribute("readonly")})}else t.Browser.isDevice&&this.allowEdit&&!this.readonly&&this.inputElement.removeAttribute("readonly")},a.prototype.checkValueChange=function(e,i){if(this.strictMode||this.validateState(this.valueWithMinutes))if(i){var s=this.getDateObject(new Date(this.timeCollections[this.activeIndex]));+this.prevDate!=+s&&this.valueProcess(e,s)}else(this.prevValue!==this.inputElement.value||t.isNullOrUndefined(this.checkDateValue(this.value)))&&this.valueProcess(e,this.compareFormatChange(this.inputElement.value));else null===this.checkDateValue(this.valueWithMinutes)&&(this.initValue=this.valueWithMinutes=null),this.setProperties({value:this.compareFormatChange(this.inputElement.value)},!0),this.initValue=this.valueWithMinutes=this.compareFormatChange(this.inputElement.value),this.prevValue=this.inputElement.value,+this.prevDate!=+this.value&&this.changeEvent(e)},a.prototype.onMouseOver=function(e){var i=t.closest(e.target,"."+Ae);this.setHover(i,"e-hover")},a.prototype.setHover=function(e,i){this.enabled&&this.isValidLI(e)&&!e.classList.contains(i)&&(this.removeHover(i),t.addClass([e],i),i===Me&&e.setAttribute("aria-selected","true"))},a.prototype.setSelection=function(e,i){this.isValidLI(e)&&!e.classList.contains(Ne)&&(this.checkValue(e.getAttribute("data-value")),this.selectedElement=e,this.activeIndex=Array.prototype.slice.call(this.liCollections).indexOf(e),this.valueWithMinutes=new Date(this.timeCollections[this.activeIndex]),t.addClass([this.selectedElement],Ne),this.selectedElement.setAttribute("aria-selected","true"),this.checkValueChange(i,!0))},a.prototype.onMouseLeave=function(){this.removeHover("e-hover")},a.prototype.scrollHandler=function(){"timepicker"===this.getModuleName()&&t.Browser.isDevice||this.hide()},a.prototype.setMinMax=function(e,i){t.isNullOrUndefined(this.checkDateValue(e))&&(this.initMin=this.getDateObject("12:00:00 AM")),t.isNullOrUndefined(this.checkDateValue(i))&&(this.initMax=this.getDateObject("11:59:59 PM"))},a.prototype.validateMinMax=function(e,i,s){var a=e instanceof Date?e:this.getDateObject(e);return t.isNullOrUndefined(this.checkDateValue(a))?+this.createDateObj(this.getFormattedValue(this.initMin))>+this.createDateObj(this.getFormattedValue(this.initMax))&&this.disableTimeIcon():e=this.strictOperation(this.initMin,this.initMax,e,a),this.strictMode&&(e=this.valueIsDisable(e)?e:null),this.checkErrorState(e),e},a.prototype.valueIsDisable=function(e){if(this.disableItemCollection.length>0){if(this.disableItemCollection.length===this.timeCollections.length)return!1;for(var t=e instanceof Date?this.objToString(e):e,i=0;i<this.disableItemCollection.length;i++)if(t===this.disableItemCollection[i])return!1}return!0},a.prototype.validateState=function(e){if(!this.strictMode){if(!this.valueIsDisable(e))return!1;var i=this.setCurrentDate(this.getDateObject(e)),s=this.setCurrentDate(this.getDateObject(this.initMax)),a=this.setCurrentDate(this.getDateObject(this.initMin));if(t.isNullOrUndefined(this.checkDateValue(i))){if(+s<+a||""!==this.inputElement.value)return!1}else if(+i>+s||+i<+a)return!1}return!0},a.prototype.strictOperation=function(e,t,i,a){var n=this.createDateObj(this.getFormattedValue(t)),r=this.createDateObj(this.getFormattedValue(e)),l=this.createDateObj(this.getFormattedValue(a));if(this.strictMode){if(+r>+n)return this.disableTimeIcon(),this.initValue=this.getDateObject(n),s.Input.setValue(this.getValue(this.initValue),this.inputElement,this.floatLabelType,this.showClearButton),this.inputElement.value;if(+r>=+l)return this.getDateObject(r);if(+l>=+n||+r==+n)return this.getDateObject(n)}else if(+r>+n&&(this.disableTimeIcon(),!isNaN(+this.createDateObj(i))))return i;return i},a.prototype.bindEvents=function(){t.EventHandler.add(this.inputWrapper.buttons[0],"mousedown",this.popupHandler,this),t.EventHandler.add(this.inputElement,"blur",this.inputBlurHandler,this),t.EventHandler.add(this.inputElement,"focus",this.inputFocusHandler,this),t.EventHandler.add(this.inputElement,"change",this.inputChangeHandler,this),this.showClearButton&&this.inputWrapper.clearButton&&t.EventHandler.add(this.inputWrapper.clearButton,"mousedown",this.clearHandler,this),this.formElement&&t.EventHandler.add(this.formElement,"reset",this.formResetHandler,this),t.Browser.isDevice||(this.keyConfigure=t.extend(this.keyConfigure,this.keyConfigs),this.inputEvent=new t.KeyboardEvents(this.inputWrapper.container,{keyAction:this.inputHandler.bind(this),keyConfigs:this.keyConfigure,eventName:"keydown"}),this.showClearButton&&this.inputElement&&t.EventHandler.add(this.inputElement,"mousedown",this.mouseDownHandler,this))},a.prototype.formResetHandler=function(){if(!this.inputElement.disabled){var e=this.inputElement.getAttribute("value"),t=this.checkDateValue(this.inputEleValue);"EJS-TIMEPICKER"===this.element.tagName&&(t=null,e="",this.inputElement.setAttribute("value","")),this.setProperties({value:t},!0),this.prevDate=this.value,this.valueWithMinutes=this.value,this.initValue=this.value,this.inputElement&&(s.Input.setValue(e,this.inputElement,this.floatLabelType,this.showClearButton),this.checkErrorState(e),this.prevValue=this.inputElement.value)}},a.prototype.inputChangeHandler=function(e){e.stopPropagation()},a.prototype.unBindEvents=function(){this.inputWrapper&&t.EventHandler.remove(this.inputWrapper.buttons[0],"mousedown touchstart",this.popupHandler),t.EventHandler.remove(this.inputElement,"blur",this.inputBlurHandler),t.EventHandler.remove(this.inputElement,"focus",this.inputFocusHandler),t.EventHandler.remove(this.inputElement,"change",this.inputChangeHandler),this.inputEvent&&this.inputEvent.destroy(),t.EventHandler.remove(this.inputElement,"mousedown touchstart",this.mouseDownHandler),this.showClearButton&&!t.isNullOrUndefined(this.inputWrapper.clearButton)&&t.EventHandler.remove(this.inputWrapper.clearButton,"mousedown touchstart",this.clearHandler),this.formElement&&t.EventHandler.remove(this.formElement,"reset",this.formResetHandler)},a.prototype.bindClearEvent=function(){this.showClearButton&&this.inputWrapper.clearButton&&t.EventHandler.add(this.inputWrapper.clearButton,"mousedown",this.clearHandler,this)},a.prototype.clearHandler=function(e){e.preventDefault(),t.isNullOrUndefined(this.value)||this.clear(e),this.popupWrapper&&(this.popupWrapper.scrollTop=0)},a.prototype.clear=function(e){this.setProperties({value:null},!0),this.initValue=null,this.resetState(),this.changeEvent(e)},a.prototype.setZIndex=function(){this.popupObj&&(this.popupObj.zIndex=this.zIndex,this.popupObj.dataBind())},a.prototype.checkAttributes=function(e){for(var i,s=0,a=e?t.isNullOrUndefined(this.htmlAttributes)?[]:Object.keys(this.htmlAttributes):["step","disabled","readonly","style","name","value","min","max","placeholder"];s<a.length;s++){var n=a[s];if(!t.isNullOrUndefined(this.inputElement.getAttribute(n)))switch(n){case"disabled":if(t.isNullOrUndefined(this.timeOptions)||void 0===this.timeOptions.enabled||e){var r="disabled"!==this.inputElement.getAttribute(n)&&""!==this.inputElement.getAttribute(n)&&"true"!==this.inputElement.getAttribute(n);this.setProperties({enabled:r},!e)}break;case"style":this.inputStyle=this.inputElement.getAttribute(n);break;case"readonly":if(t.isNullOrUndefined(this.timeOptions)||void 0===this.timeOptions.readonly||e){var l="readonly"===this.inputElement.getAttribute(n)||""===this.inputElement.getAttribute(n)||"true"===this.inputElement.getAttribute(n);this.setProperties({readonly:l},!e)}break;case"name":this.inputElement.setAttribute("name",this.inputElement.getAttribute(n));break;case"step":this.step=parseInt(this.inputElement.getAttribute(n),10);break;case"placeholder":(t.isNullOrUndefined(this.timeOptions)||void 0===this.timeOptions.placeholder||e)&&this.setProperties({placeholder:this.inputElement.getAttribute(n)},!e);break;case"min":(t.isNullOrUndefined(this.timeOptions)||void 0===this.timeOptions.min||e)&&(i=new Date(this.inputElement.getAttribute(n)),t.isNullOrUndefined(this.checkDateValue(i))||this.setProperties({min:i},!e));break;case"max":(t.isNullOrUndefined(this.timeOptions)||void 0===this.timeOptions.max||e)&&(i=new Date(this.inputElement.getAttribute(n)),t.isNullOrUndefined(this.checkDateValue(i))||this.setProperties({max:i},!e));break;case"value":(t.isNullOrUndefined(this.timeOptions)||void 0===this.timeOptions.value||e)&&(i=new Date(this.inputElement.getAttribute(n)),t.isNullOrUndefined(this.checkDateValue(i))||(this.initValue=i,this.updateInput(!1,this.initValue),this.setProperties({value:i},!e)))}}},a.prototype.setCurrentDate=function(e){return t.isNullOrUndefined(this.checkDateValue(e))?null:new Date(ke,Ve,we,e.getHours(),e.getMinutes(),e.getSeconds())},a.prototype.getTextFormat=function(){var e=0;if("a"===this.cldrTimeFormat().split(" ")[0]||0===this.cldrTimeFormat().indexOf("a"))e=1;else if(this.cldrTimeFormat().indexOf("a")<0)for(var t=this.cldrTimeFormat().split(" "),i=0;i<t.length;i++)if(t[i].toLowerCase().indexOf("h")>=0){e=i;break}return e},a.prototype.updateValue=function(e,t){var i;if(this.isNullOrEmpty(e))this.resetState();else if(i=this.checkValue(e),this.strictMode){var a=null===i&&e.trim().length>0?this.previousState(this.prevDate):this.inputElement.value;s.Input.setValue(a,this.inputElement,this.floatLabelType,this.showClearButton)}this.checkValueChange(t,"string"!=typeof e)},a.prototype.previousState=function(e){for(var t=this.getDateObject(e),i=0;i<this.timeCollections.length;i++)if(+t===this.timeCollections[i]){this.activeIndex=i,this.selectedElement=this.liCollections[i],this.valueWithMinutes=new Date(this.timeCollections[i]);break}return this.prevValue},a.prototype.resetState=function(){this.removeSelection(),s.Input.setValue("",this.inputElement,this.floatLabelType,!1),this.valueWithMinutes=this.activeIndex=null,this.strictMode||this.checkErrorState(null)},a.prototype.objToString=function(e){return t.isNullOrUndefined(this.checkDateValue(e))?null:this.globalize.formatDate(e,{format:this.cldrTimeFormat(),type:"time"})},a.prototype.checkValue=function(e){if(!this.isNullOrEmpty(e)){var t=e instanceof Date?e:this.getDateObject(e);return this.validateValue(t,e)}return this.resetState(),this.valueWithMinutes=null},a.prototype.validateValue=function(e,i){var a,n=this.validateMinMax(i,this.min,this.max),r=this.createDateObj(n);if(this.getFormattedValue(r)!==this.getFormattedValue(this.value)?(this.valueWithMinutes=t.isNullOrUndefined(r)?null:r,a=this.objToString(this.valueWithMinutes)):(this.strictMode&&(e=r),this.valueWithMinutes=this.checkDateValue(e),a=this.objToString(this.valueWithMinutes)),!this.strictMode&&t.isNullOrUndefined(a)){var l=n.trim().length>0?n:"";s.Input.setValue(l,this.inputElement,this.floatLabelType,this.showClearButton)}else s.Input.setValue(a,this.inputElement,this.floatLabelType,this.showClearButton);return a},a.prototype.findNextElement=function(e){var i=this.inputElement.value,s=t.isNullOrUndefined(this.valueWithMinutes)?this.createDateObj(i):this.getDateObject(this.valueWithMinutes),a=null,n=this.liCollections.length;if(t.isNullOrUndefined(this.checkDateValue(s))&&t.isNullOrUndefined(this.activeIndex)){r=this.validLiElement(0,"down"!==e.action);this.activeIndex=r,this.selectedElement=this.liCollections[r],this.elementValue(new Date(this.timeCollections[r]))}else{if("home"===e.action){var r=this.validLiElement(0);a=+this.createDateObj(new Date(this.timeCollections[r])),this.activeIndex=r}else if("end"===e.action){var r=this.validLiElement(this.timeCollections.length-1,!0);a=+this.createDateObj(new Date(this.timeCollections[r])),this.activeIndex=r}else if("down"===e.action)for(var l=0;l<n;l++){if(+s<this.timeCollections[l]){r=this.validLiElement(l);a=+this.createDateObj(new Date(this.timeCollections[r])),this.activeIndex=r;break}if(l===n-1){r=this.validLiElement(0);a=+this.createDateObj(new Date(this.timeCollections[r])),this.activeIndex=r;break}}else for(l=n-1;l>=0;l--){if(+s>this.timeCollections[l]){r=this.validLiElement(l,!0);a=+this.createDateObj(new Date(this.timeCollections[r])),this.activeIndex=r;break}if(0===l){r=this.validLiElement(n-1);a=+this.createDateObj(new Date(this.timeCollections[r])),this.activeIndex=r;break}}this.selectedElement=this.liCollections[this.activeIndex],this.elementValue(t.isNullOrUndefined(a)?null:new Date(a))}},a.prototype.elementValue=function(e){t.isNullOrUndefined(this.checkDateValue(e))||this.checkValue(e)},a.prototype.validLiElement=function(e,i){var s=null,a=t.isNullOrUndefined(this.popupWrapper)?this.liCollections:this.popupWrapper.querySelectorAll("."+Ae),n=!0;if(a.length)if(i)for(var r=e;r>=0;r--){if(!a[r].classList.contains(Ie)){s=r;break}0===r&&n&&(e=r=a.length,n=!1)}else for(r=e;r<=a.length-1;r++){if(!a[r].classList.contains(Ie)){s=r;break}r===a.length-1&&n&&(e=r=-1,n=!1)}return s},a.prototype.keyHandler=function(e){if(!(t.isNullOrUndefined(this.step)||this.step<=0||this.inputWrapper.buttons[0].classList.contains(Ie))){var i=this.timeCollections.length;if(t.isNullOrUndefined(this.getActiveElement())||0===this.getActiveElement().length)if(this.liCollections.length>0)if(t.isNullOrUndefined(this.value)&&t.isNullOrUndefined(this.activeIndex)){var s=this.validLiElement(0,"down"!==e.action);this.activeIndex=s,this.selectedElement=this.liCollections[s],this.elementValue(new Date(this.timeCollections[s]))}else this.findNextElement(e);else this.findNextElement(e);else{var a=void 0;if(e.keyCode>=37&&e.keyCode<=40){s=40===e.keyCode||39===e.keyCode?++this.activeIndex:--this.activeIndex;this.activeIndex=s=this.activeIndex===i?0:this.activeIndex,this.activeIndex=s=this.activeIndex<0?i-1:this.activeIndex,this.activeIndex=s=this.validLiElement(this.activeIndex,40!==e.keyCode&&39!==e.keyCode),a=t.isNullOrUndefined(this.timeCollections[s])?this.timeCollections[0]:this.timeCollections[s]}else if("home"===e.action){s=this.validLiElement(0);this.activeIndex=s,a=this.timeCollections[s]}else if("end"===e.action){s=this.validLiElement(i-1,!0);this.activeIndex=s,a=this.timeCollections[s]}this.selectedElement=this.liCollections[this.activeIndex],this.elementValue(new Date(a))}this.isNavigate=!0,this.setHover(this.selectedElement,Me),this.setActiveDescendant(),this.selectInputText(),!this.isPopupOpen()||null===this.selectedElement||e&&"click"===e.type||this.setScrollPosition()}},a.prototype.getCultureTimeObject=function(e,i){return t.getValue("main."+i+".dates.calendars.gregorian.timeFormats.short",e)},a.prototype.getCultureDateObject=function(e,i){return t.getValue("main."+i+".dates.calendars.gregorian.dateFormats.short",e)},a.prototype.wireListEvents=function(){t.EventHandler.add(this.listWrapper,"click",this.onMouseClick,this),t.Browser.isDevice||(t.EventHandler.add(this.listWrapper,"mouseover",this.onMouseOver,this),t.EventHandler.add(this.listWrapper,"mouseout",this.onMouseLeave,this))},a.prototype.unWireListEvents=function(){this.listWrapper&&(t.EventHandler.remove(this.listWrapper,"click",this.onMouseClick),t.Browser.isDevice||(t.EventHandler.remove(this.listWrapper,"mouseover",this.onMouseOver),t.EventHandler.remove(this.listWrapper,"mouseout",this.onMouseLeave)))},a.prototype.valueProcess=function(e,i){var s=t.isNullOrUndefined(this.checkDateValue(i))?null:i;+this.prevDate!=+s&&(this.initValue=s,this.changeEvent(e))},a.prototype.changeEvent=function(e){this.addSelection(),this.updateInput(!0,this.initValue);var i={event:e||null,value:this.value,text:this.inputElement.value,isInteracted:!t.isNullOrUndefined(e),element:this.element};i.value=this.valueWithMinutes||this.getDateObject(this.inputElement.value),this.prevDate=this.valueWithMinutes||this.getDateObject(this.inputElement.value),this.trigger("change",i),this.invalidValueString=null,this.checkErrorState(this.value)},a.prototype.updateInput=function(e,i){e&&(this.prevValue=this.getValue(i)),this.prevDate=this.valueWithMinutes=i,"number"==typeof i&&(this.value&&+new Date(+this.value).setMilliseconds(0))===+i||this.setProperties({value:i},!0),!this.strictMode&&t.isNullOrUndefined(this.value)&&this.invalidValueString&&(this.checkErrorState(this.invalidValueString),s.Input.setValue(this.invalidValueString,this.inputElement,this.floatLabelType,this.showClearButton)),this.clearIconState()},a.prototype.setActiveDescendant=function(){t.isNullOrUndefined(this.selectedElement)?t.attributes(this.inputElement,{"aria-activedescendant":"null"}):t.attributes(this.inputElement,{"aria-activedescendant":this.selectedElement.getAttribute("id")})},a.prototype.removeSelection=function(){if(this.removeHover("e-hover"),!t.isNullOrUndefined(this.popupWrapper)){var e=this.popupWrapper.querySelectorAll("."+Ne);e.length&&(t.removeClass(e,Ne),e[0].removeAttribute("aria-selected"))}},a.prototype.removeHover=function(e){var i=this.getHoverItem(e);i&&i.length&&(t.removeClass(i,e),e===Me&&i[0].removeAttribute("aria-selected"))},a.prototype.getHoverItem=function(e){var i;return t.isNullOrUndefined(this.popupWrapper)||(i=this.popupWrapper.querySelectorAll("."+e)),i},a.prototype.setActiveClass=function(){if(!t.isNullOrUndefined(this.popupWrapper)){var e=this.popupWrapper.querySelectorAll("."+Ae);if(e.length)for(var i=0;i<e.length;i++)if(this.timeCollections[i]===+this.getDateObject(this.valueWithMinutes)){e[i].setAttribute("aria-selected","true"),this.selectedElement=e[i],this.activeIndex=i;break}}},a.prototype.addSelection=function(){this.selectedElement=null,this.removeSelection(),this.setActiveClass(),t.isNullOrUndefined(this.selectedElement)||(t.addClass([this.selectedElement],Ne),this.selectedElement.setAttribute("aria-selected","true"))},a.prototype.isValidLI=function(e){return e&&e.classList.contains(Ae)&&!e.classList.contains(Ie)},a.prototype.createDateObj=function(e){var i=this.globalize.formatDate(new Date,{skeleton:"short",type:"date"}),s=null;return"string"==typeof e?e.toUpperCase().indexOf("AM")>-1||e.toUpperCase().indexOf("PM")>-1?(i=this.defaultCulture.formatDate(new Date,{skeleton:"short",type:"date"}),s=isNaN(+new Date(i+" "+e))?null:new Date(new Date(i+" "+e).setMilliseconds(0)),t.isNullOrUndefined(s)&&(s=this.TimeParse(i,e))):s=this.TimeParse(i,e):e instanceof Date&&(s=e),s},a.prototype.TimeParse=function(e,i){var s;return s=this.globalize.parseDate(e+" "+i,{format:this.cldrDateFormat()+" "+this.cldrTimeFormat(),type:"datetime"}),s=t.isNullOrUndefined(s)?this.globalize.parseDate(e+" "+i,{format:this.cldrDateFormat()+" "+this.dateToNumeric(),type:"datetime"}):s,s=t.isNullOrUndefined(s)?s:new Date(s.setMilliseconds(0))},a.prototype.createListItems=function(){var e=this;this.listWrapper=this.createElement("div",{className:"e-content",attrs:{tabindex:"0"}});var i,s,a=6e4*this.step,r=[];for(this.timeCollections=[],this.disableItemCollection=[],i=+this.getDateObject(this.initMin).setMilliseconds(0),s=+this.getDateObject(this.initMax).setMilliseconds(0);s>=i;)this.timeCollections.push(i),r.push(this.globalize.formatDate(new Date(i),{format:this.cldrTimeFormat(),type:"time"})),i+=a;var l={itemCreated:function(t){var i={element:t.item,text:t.text,value:e.getDateObject(t.text),isDisabled:!1};e.trigger("itemRender",i,function(t){t.isDisabled&&t.element.classList.add(Ie),t.element.classList.contains(Ie)&&e.disableItemCollection.push(t.element.getAttribute("data-value"))})}};this.listTag=n.ListBase.createList(this.createElement,r,l,!0),t.attributes(this.listTag,{role:"listbox","aria-hidden":"false",id:this.element.id+"_options"}),t.append([this.listTag],this.listWrapper)},a.prototype.documentClickHandler=function(e){"touchstart"!==e.type&&e.preventDefault();var i=e.target;t.closest(i,"#"+this.popupObj.element.id)||i===this.inputElement||i===(this.inputWrapper&&this.inputWrapper.buttons[0])||i===(this.inputWrapper&&this.inputWrapper.clearButton)||i===(this.inputWrapper&&this.inputWrapper.container)?i!==this.inputElement&&(t.Browser.isDevice||(this.isPreventBlur=(t.Browser.isIE||"edge"===t.Browser.info.name)&&document.activeElement===this.inputElement,e.preventDefault())):this.isPopupOpen()&&(this.hide(),this.focusOut())},a.prototype.setEnableRtl=function(){s.Input.setEnableRtl(this.enableRtl,[this.inputWrapper.container]),this.popupObj&&(this.popupObj.enableRtl=this.enableRtl,this.popupObj.dataBind())},a.prototype.setEnable=function(){s.Input.setEnabled(this.enabled,this.inputElement,this.floatLabelType),this.enabled?(t.removeClass([this.inputWrapper.container],Ie),t.attributes(this.inputElement,{"aria-disabled":"false"}),this.inputElement.setAttribute("tabindex",this.tabIndex)):(this.hide(),t.addClass([this.inputWrapper.container],Ie),t.attributes(this.inputElement,{"aria-disabled":"true"}),this.inputElement.tabIndex=-1)},a.prototype.getProperty=function(e,t){"min"===t?(this.initMin=this.checkDateValue(new Date(this.checkInValue(e.min))),this.setProperties({min:this.initMin},!0)):(this.initMax=this.checkDateValue(new Date(this.checkInValue(e.max))),this.setProperties({max:this.initMax},!0)),""===this.inputElement.value?this.validateMinMax(this.value,this.min,this.max):this.checkValue(this.inputElement.value),this.checkValueChange(null,!1)},a.prototype.inputBlurHandler=function(e){if(this.isPreventBlur&&this.isPopupOpen())this.inputElement.focus();else{this.closePopup(0,e),t.removeClass([this.inputWrapper.container],[xe]);var i={model:this};this.trigger("blur",i),this.getText()!==this.inputElement.value?this.updateValue(this.inputElement.value,e):0===this.inputElement.value.trim().length&&this.resetState(),this.cursorDetails=null,this.isNavigate=!1,""===this.inputElement.value&&(this.invalidValueString=null)}},a.prototype.focusOut=function(){if(document.activeElement===this.inputElement){this.inputElement.blur();var e={model:this};this.trigger("blur",e)}},a.prototype.isPopupOpen=function(){return!(!this.popupWrapper||!this.popupWrapper.classList.contains(""+Oe))},a.prototype.inputFocusHandler=function(){var e={model:this};this.readonly||t.Browser.isDevice||this.selectInputText(),this.trigger("focus",e),this.clearIconState()},a.prototype.focusIn=function(){document.activeElement!==this.inputElement&&this.enabled&&this.inputElement.focus()},a.prototype.hide=function(){this.closePopup(100,null),this.clearIconState()},a.prototype.show=function(e){var i=this;if(!(this.enabled&&this.readonly||!this.enabled||this.popupWrapper)){this.popupCreation(),t.Browser.isDevice&&this.listWrapper&&(this.modal=this.createElement("div"),this.modal.className=Oe+" e-time-modal",document.body.className+=" e-time-overflow",document.body.appendChild(this.modal)),this.openPopupEventArgs={popup:this.popupObj||null,cancel:!1,event:e||null,name:"open",appendTo:document.body};var s=this.openPopupEventArgs;this.trigger("open",s,function(e){if(i.openPopupEventArgs=e,i.openPopupEventArgs.cancel||i.inputWrapper.buttons[0].classList.contains(Ie))i.popupObj.destroy(),i.popupWrapper=i.listTag=void 0,i.liCollections=i.timeCollections=i.disableItemCollection=[],i.popupObj=null;else{i.openPopupEventArgs.appendTo.appendChild(i.popupWrapper),i.popupAlignment(i.openPopupEventArgs),i.setScrollPosition(),t.Browser.isDevice||i.inputElement.focus();var s={name:"FadeIn",duration:50};i.popupObj.refreshPosition(i.anchor),1e3===i.zIndex?i.popupObj.show(new t.Animation(s),i.element):i.popupObj.show(new t.Animation(s),null),i.setActiveDescendant(),t.attributes(i.inputElement,{"aria-expanded":"true"}),t.addClass([i.inputWrapper.container],xe),t.EventHandler.add(document,"mousedown touchstart",i.documentClickHandler,i)}})}},a.prototype.formatValues=function(e){var i;return"number"==typeof e?i=t.formatUnit(e):"string"==typeof e&&(i=e.match(/px|%|em/)?e:isNaN(parseInt(e,10))?e:t.formatUnit(e)),i},a.prototype.popupAlignment=function(e){if(e.popup.position.X=this.formatValues(e.popup.position.X),e.popup.position.Y=this.formatValues(e.popup.position.Y),isNaN(parseFloat(e.popup.position.X))&&isNaN(parseFloat(e.popup.position.Y))||(this.popupObj.relateTo=this.anchor=document.body,this.popupObj.targetType="container"),isNaN(parseFloat(e.popup.position.X))||(this.popupObj.offsetX=parseFloat(e.popup.position.X)),isNaN(parseFloat(e.popup.position.Y))||(this.popupObj.offsetY=parseFloat(e.popup.position.Y)),t.Browser.isDevice)"center"===e.popup.position.X&&"center"===e.popup.position.Y&&(this.popupObj.relateTo=this.anchor=document.body,this.popupObj.offsetY=0,this.popupObj.targetType="container",this.popupObj.collision={X:"fit",Y:"fit"});else{switch(e.popup.position.X){case"left":break;case"right":e.popup.offsetX=this.containerStyle.width;break;case"center":e.popup.offsetX=-this.containerStyle.width/2}switch(e.popup.position.Y){case"top":case"bottom":break;case"center":e.popup.offsetY=-this.containerStyle.height/2}"center"===e.popup.position.X&&"center"===e.popup.position.Y&&(this.popupObj.relateTo=this.inputWrapper.container,this.anchor=this.inputElement,this.popupObj.targetType="relative")}},a.prototype.getPersistData=function(){return this.addOnPersist(["value"])},a.prototype.getModuleName=function(){return"timepicker"},a.prototype.onPropertyChanged=function(e,i){for(var a=0,n=Object.keys(e);a<n.length;a++){var r=n[a];switch(r){case"placeholder":s.Input.setPlaceholder(e.placeholder,this.inputElement),this.inputElement.setAttribute("aria-placeholder",e.placeholder);break;case"readonly":s.Input.setReadonly(this.readonly,this.inputElement,this.floatLabelType),this.readonly&&this.hide(),this.setTimeAllowEdit();break;case"enabled":this.setProperties({enabled:e.enabled},!0),this.setEnable();break;case"allowEdit":this.setTimeAllowEdit();break;case"enableRtl":this.setProperties({enableRtl:e.enableRtl},!0),this.setEnableRtl();break;case"cssClass":s.Input.setCssClass(e.cssClass,[this.inputWrapper.container],i.cssClass),this.popupWrapper&&s.Input.setCssClass(e.cssClass,[this.popupWrapper],i.cssClass);break;case"zIndex":this.setProperties({zIndex:e.zIndex},!0),this.setZIndex();break;case"htmlAttributes":this.updateHtmlAttributeToElement(),this.updateHtmlAttributeToWrapper(),this.checkAttributes(!0);break;case"min":case"max":this.getProperty(e,r);break;case"showClearButton":s.Input.setClearButton(this.showClearButton,this.inputElement,this.inputWrapper),this.bindClearEvent();break;case"locale":this.setProperties({locale:e.locale},!0),this.globalize=new t.Internationalization(this.locale),this.l10n.setLocale(this.locale),this.updatePlaceHolder(),this.setValue(this.value);break;case"width":t.setStyleAttribute(this.inputWrapper.container,{width:this.setWidth(e.width)}),this.containerStyle=this.inputWrapper.container.getBoundingClientRect();break;case"format":this.setProperties({format:e.format},!0),this.checkTimeFormat(),this.setValue(this.value);break;case"value":this.invalidValueString=null,this.checkInvalidValue(e.value),e.value=this.value,this.invalidValueString?(s.Input.setValue(this.invalidValueString,this.inputElement,this.floatLabelType,this.showClearButton),this.checkErrorState(this.invalidValueString)):("string"==typeof e.value?(this.setProperties({value:this.checkDateValue(new Date(e.value))},!0),e.value=this.value):(e.value&&+new Date(+e.value).setMilliseconds(0))!==+this.value&&(e.value=this.checkDateValue(new Date(""+e.value))),this.initValue=e.value,e.value=this.compareFormatChange(this.checkValue(e.value))),this.checkValueChange(null,!1);break;case"floatLabelType":this.floatLabelType=e.floatLabelType,s.Input.removeFloating(this.inputWrapper),s.Input.addFloating(this.inputElement,this.floatLabelType,this.placeholder);break;case"strictMode":this.invalidValueString=null,e.strictMode&&this.checkErrorState(null),this.setProperties({strictMode:e.strictMode},!0),this.checkValue(this.inputElement.value),this.checkValueChange(null,!1);break;case"scrollTo":this.checkDateValue(new Date(this.checkInValue(e.scrollTo)))?(this.popupWrapper&&this.setScrollTo(),this.setProperties({scrollTo:e.scrollTo},!0)):this.setProperties({scrollTo:null},!0)}}},a.prototype.checkInValue=function(e){return e instanceof Date?e.toUTCString():""+e},Ce([t.Property(null)],a.prototype,"width",void 0),Ce([t.Property(null)],a.prototype,"cssClass",void 0),Ce([t.Property(!1)],a.prototype,"strictMode",void 0),Ce([t.Property(null)],a.prototype,"keyConfigs",void 0),Ce([t.Property(null)],a.prototype,"format",void 0),Ce([t.Property(!0)],a.prototype,"enabled",void 0),Ce([t.Property(!1)],a.prototype,"readonly",void 0),Ce([t.Property({})],a.prototype,"htmlAttributes",void 0),Ce([t.Property("Never")],a.prototype,"floatLabelType",void 0),Ce([t.Property(null)],a.prototype,"placeholder",void 0),Ce([t.Property(1e3)],a.prototype,"zIndex",void 0),Ce([t.Property(!1)],a.prototype,"enablePersistence",void 0),Ce([t.Property(!0)],a.prototype,"showClearButton",void 0),Ce([t.Property(30)],a.prototype,"step",void 0),Ce([t.Property(null)],a.prototype,"scrollTo",void 0),Ce([t.Property(null)],a.prototype,"value",void 0),Ce([t.Property(null)],a.prototype,"min",void 0),Ce([t.Property(null)],a.prototype,"max",void 0),Ce([t.Property(!0)],a.prototype,"allowEdit",void 0),Ce([t.Event()],a.prototype,"change",void 0),Ce([t.Event()],a.prototype,"created",void 0),Ce([t.Event()],a.prototype,"destroyed",void 0),Ce([t.Event()],a.prototype,"open",void 0),Ce([t.Event()],a.prototype,"itemRender",void 0),Ce([t.Event()],a.prototype,"close",void 0),Ce([t.Event()],a.prototype,"blur",void 0),Ce([t.Event()],a.prototype,"focus",void 0),a=Ce([t.NotifyPropertyChanges],a)}(t.Component),Se=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(t,i)};return function(t,i){function s(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(s.prototype=i.prototype,new s)}}(),He=function(e,t,i,s){var a,n=arguments.length,r=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,i,s);else for(var l=e.length-1;l>=0;l--)(a=e[l])&&(r=(n<3?a(r):n>3?a(t,i,r):a(t,i))||r);return n>3&&r&&Object.defineProperty(t,i,r),r},We=(new Date).getDate(),Le=(new Date).getMonth(),Fe=(new Date).getFullYear(),Be=(new Date).getHours(),je=(new Date).getMinutes(),Ye=(new Date).getSeconds(),Re=(new Date).getMilliseconds(),ze="e-datetimepicker",qe="e-datetimepopup-wrapper",Ke="e-input-focus",_e="e-disabled",Ge="e-active",Xe=n.cssClass.li,Ze=function(a){function n(e,t){var i=a.call(this,e,t)||this;return i.valueWithMinutes=null,i.previousDateTime=null,i.dateTimeOptions=e,i}return Se(n,a),n.prototype.focusHandler=function(){t.addClass([this.inputWrapper.container],Ke)},n.prototype.focusIn=function(){a.prototype.focusIn.call(this)},n.prototype.focusOut=function(){document.activeElement===this.inputElement&&(this.inputElement.blur(),t.removeClass([this.inputWrapper.container],[Ke]))},n.prototype.blurHandler=function(e){if(this.isTimePopupOpen()&&this.isPreventBlur)this.inputElement.focus();else{t.removeClass([this.inputWrapper.container],Ke);var i={model:this};this.isTimePopupOpen()&&this.hide(e),this.trigger("blur",i)}},n.prototype.destroy=function(){this.popupObject&&this.popupObject.element.classList.contains("e-popup")&&(this.dateTimeWrapper=void 0,this.liCollections=this.timeCollections=[],t.isNullOrUndefined(this.rippleFn)||this.rippleFn());var e={"aria-live":"assertive","aria-atomic":"true","aria-invalid":"false","aria-haspopup":"true","aria-activedescendant":"null",autocorrect:"off",autocapitalize:"off",spellcheck:"false","aria-owns":this.element.id+"_options","aria-expanded":"false",role:"combobox",autocomplete:"off"};this.inputElement&&(s.Input.removeAttributes(e,this.inputElement),this.inputElement.removeAttribute("aria-placeholder")),this.isCalendar()&&(this.popupWrapper&&t.detach(this.popupWrapper),this.popupObject=this.popupWrapper=null,this.keyboardHandler.destroy()),this.unBindInputEvents(),a.prototype.destroy.call(this)},n.prototype.render=function(){this.timekeyConfigure={enter:"enter",escape:"escape",end:"end",tab:"tab",home:"home",down:"downarrow",up:"uparrow",left:"leftarrow",right:"rightarrow",open:"alt+downarrow",close:"alt+uparrow"},this.valueWithMinutes=null,this.previousDateTime=null,this.isPreventBlur=!1,this.cloneElement=this.element.cloneNode(!0),this.dateTimeFormat=this.cldrDateTimeFormat(),this.initValue=this.value,a.prototype.updateHtmlAttributeToElement.call(this),this.checkAttributes(!1);var e={placeholder:this.placeholder};this.l10n=new t.L10n("datetimepicker",e,this.locale),this.setProperties({placeholder:this.placeholder||this.l10n.getConstant("placeholder")},!0),a.prototype.render.call(this),this.createInputElement(),a.prototype.updateHtmlAttributeToWrapper.call(this),this.bindInputEvents(),this.setValue(),this.previousDateTime=this.value&&new Date(+this.value),"EJS-DATETIMEPICKER"===this.element.tagName&&(this.tabIndex=this.element.hasAttribute("tabindex")?this.element.getAttribute("tabindex"):"0",this.element.removeAttribute("tabindex"),this.enabled||(this.inputElement.tabIndex=-1)),this.renderComplete()},n.prototype.setValue=function(){if(this.initValue=this.validateMinMaxRange(this.value),!this.strictMode&&this.isDateObject(this.initValue)){var e=this.validateMinMaxRange(this.initValue);s.Input.setValue(this.getFormattedValue(e),this.inputElement,this.floatLabelType,this.showClearButton),this.setProperties({value:e},!0)}else t.isNullOrUndefined(this.value)&&(this.initValue=null,this.setProperties({value:null},!0));this.valueWithMinutes=this.value,a.prototype.updateInput.call(this)},n.prototype.validateMinMaxRange=function(e){var t=e;return this.isDateObject(e)?t=this.validateValue(e):+this.min>+this.max&&this.disablePopupButton(!0),this.checkValidState(t),t},n.prototype.checkValidState=function(e){this.isValidState=!0,this.strictMode||(+e>+this.max||+e<+this.min)&&(this.isValidState=!1),this.checkErrorState()},n.prototype.checkErrorState=function(){this.isValidState?t.removeClass([this.inputWrapper.container],"e-error"):t.addClass([this.inputWrapper.container],"e-error"),t.attributes(this.inputElement,{"aria-invalid":this.isValidState?"false":"true"})},n.prototype.validateValue=function(e){var t=e;return this.strictMode?+this.min>+this.max?(this.disablePopupButton(!0),t=this.max):+e<+this.min?t=this.min:+e>+this.max&&(t=this.max):+this.min>+this.max&&(this.disablePopupButton(!0),t=e),t},n.prototype.disablePopupButton=function(e){e?(t.addClass([this.inputWrapper.buttons[0],this.timeIcon],_e),this.hide()):t.removeClass([this.inputWrapper.buttons[0],this.timeIcon],_e)},n.prototype.getFormattedValue=function(e){var i;return t.isNullOrUndefined(e)?null:(i="Gregorian"===this.calendarMode?{format:this.cldrDateTimeFormat(),type:"dateTime",skeleton:"yMd"}:{format:this.cldrDateTimeFormat(),type:"dateTime",skeleton:"yMd",calendar:"islamic"},this.globalize.formatDate(e,i))},n.prototype.isDateObject=function(e){return!t.isNullOrUndefined(e)&&!isNaN(+e)},n.prototype.createInputElement=function(){t.removeClass([this.inputElement],"e-datepicker"),t.removeClass([this.inputWrapper.container],"e-date-wrapper"),t.addClass([this.inputWrapper.container],"e-datetime-wrapper"),t.addClass([this.inputElement],ze),this.renderTimeIcon()},n.prototype.renderTimeIcon=function(){this.timeIcon=s.Input.appendSpan("e-input-group-icon e-time-icon e-icons",this.inputWrapper.container)},n.prototype.bindInputEvents=function(){t.EventHandler.add(this.timeIcon,"mousedown",this.timeHandler,this),t.EventHandler.add(this.inputWrapper.buttons[0],"mousedown",this.dateHandler,this),t.EventHandler.add(this.inputElement,"blur",this.blurHandler,this),t.EventHandler.add(this.inputElement,"focus",this.focusHandler,this),this.defaultKeyConfigs=t.extend(this.defaultKeyConfigs,this.keyConfigs),this.keyboardHandler=new t.KeyboardEvents(this.inputElement,{eventName:"keydown",keyAction:this.inputKeyAction.bind(this),keyConfigs:this.defaultKeyConfigs})},n.prototype.unBindInputEvents=function(){t.EventHandler.remove(this.timeIcon,"mousedown touchstart",this.timeHandler),t.EventHandler.remove(this.inputWrapper.buttons[0],"mousedown touchstart",this.dateHandler),this.inputElement&&(t.EventHandler.remove(this.inputElement,"blur",this.blurHandler),t.EventHandler.remove(this.inputElement,"focus",this.focusHandler)),this.keyboardHandler&&this.keyboardHandler.destroy()},n.prototype.cldrTimeFormat=function(){return this.isNullOrEmpty(this.timeFormat)?"en"===this.locale||"en-US"===this.locale?t.getValue("timeFormats.short",t.getDefaultDateObject()):this.getCultureTimeObject(t.cldrData,""+this.locale):this.timeFormat},n.prototype.cldrDateTimeFormat=function(){var e=new t.Internationalization(this.locale).getDatePattern({skeleton:"yMd"});return this.isNullOrEmpty(this.formatString)?e+" "+this.getCldrFormat("time"):this.formatString},n.prototype.getCldrFormat=function(e){return"en"===this.locale||"en-US"===this.locale?t.getValue("timeFormats.short",t.getDefaultDateObject()):this.getCultureTimeObject(t.cldrData,""+this.locale)},n.prototype.isNullOrEmpty=function(e){return!!(t.isNullOrUndefined(e)||"string"==typeof e&&""===e.trim())},n.prototype.getCultureTimeObject=function(e,i){return"Gregorian"===this.calendarMode?t.getValue("main."+this.locale+".dates.calendars.gregorian.timeFormats.short",e):t.getValue("main."+this.locale+".dates.calendars.islamic.timeFormats.short",e)},n.prototype.timeHandler=function(e){t.Browser.isDevice&&this.inputElement.setAttribute("readonly",""),e.currentTarget===this.timeIcon&&e.preventDefault(),this.enabled&&!this.readonly&&(this.isDatePopupOpen()&&a.prototype.hide.call(this,e),this.isTimePopupOpen()?this.closePopup(e):(this.inputElement.focus(),this.popupCreation("time",e),t.addClass([this.inputWrapper.container],[Ke])))},n.prototype.dateHandler=function(e){e.currentTarget===this.inputWrapper.buttons[0]&&e.preventDefault(),this.enabled&&!this.readonly&&(this.isTimePopupOpen()&&this.closePopup(e),t.isNullOrUndefined(this.popupWrapper)||this.popupCreation("date",e))},n.prototype.show=function(e,t){this.enabled&&this.readonly||!this.enabled||("time"!==e||this.dateTimeWrapper?this.popupObj||(this.isTimePopupOpen()&&this.hide(t),a.prototype.show.call(this),this.popupCreation("date",t)):(this.isDatePopupOpen()&&this.hide(t),this.popupCreation("time",t)))},n.prototype.toggle=function(e){this.isDatePopupOpen()?(a.prototype.hide.call(this,e),this.show("time",null)):this.isTimePopupOpen()?(this.hide(e),a.prototype.show.call(this,null,e),this.popupCreation("date",null)):this.show(null,e)},n.prototype.listCreation=function(){var i;i="Gregorian"===this.calendarMode?this.globalize.parseDate(this.inputElement.value,{format:this.cldrDateTimeFormat(),type:"datetime"}):this.globalize.parseDate(this.inputElement.value,{format:this.cldrDateTimeFormat(),type:"datetime",calendar:"islamic"});var s=t.isNullOrUndefined(this.value)?""!==this.inputElement.value?i:new Date:this.value;this.valueWithMinutes=s,this.listWrapper=t.createElement("div",{className:"e-content",attrs:{tabindex:"0"}});var a=this.startTime(s),n=this.endTime(s),r=e.TimePickerBase.createListItems(this.createElement,a,n,this.globalize,this.cldrTimeFormat(),this.step);this.timeCollections=r.collection,this.listTag=r.list,t.attributes(this.listTag,{role:"listbox","aria-hidden":"false",id:this.element.id+"_options"}),t.append([r.list],this.listWrapper),this.wireTimeListEvents();var l={duration:300,selector:"."+Xe};this.rippleFn=t.rippleEffect(this.listWrapper,l),this.liCollections=this.listWrapper.querySelectorAll("."+Xe)},n.prototype.popupCreation=function(e,i){t.Browser.isDevice&&this.element.setAttribute("readonly","readonly"),"date"===e?!this.readonly&&this.popupWrapper&&(t.addClass([this.popupWrapper],qe),t.attributes(this.popupWrapper,{id:this.element.id+"_datepopup"})):this.readonly||(this.dateTimeWrapper=t.createElement("div",{className:ze+" e-popup",attrs:{id:this.element.id+"_timepopup",style:"visibility:hidden ; display:block"}}),t.isNullOrUndefined(this.cssClass)||(this.dateTimeWrapper.className+=" "+this.cssClass),!t.isNullOrUndefined(this.step)&&this.step>0&&(this.listCreation(),t.append([this.listWrapper],this.dateTimeWrapper)),document.body.appendChild(this.dateTimeWrapper),this.addTimeSelection(),this.renderPopup(),this.setTimeScrollPosition(),this.openPopup(i),this.popupObject.refreshPosition(this.inputElement))},n.prototype.openPopup=function(e){var i=this;this.preventArgs={cancel:!1,popup:this.popupObject,event:e||null};var s=this.preventArgs;this.trigger("open",s,function(e){if(i.preventArgs=e,!i.preventArgs.cancel&&!i.readonly){var s={name:"FadeIn",duration:100};1e3===i.zIndex?i.popupObject.show(new t.Animation(s),i.element):i.popupObject.show(new t.Animation(s),null),t.addClass([i.inputWrapper.container],["e-icon-anim"]),t.attributes(i.inputElement,{"aria-expanded":"true"}),t.EventHandler.add(document,"mousedown touchstart",i.documentClickHandler,i)}})},n.prototype.documentClickHandler=function(e){"touchstart"!==e.type&&e.preventDefault();var i=e.target;t.closest(i,"#"+(this.popupObject&&this.popupObject.element.id))||i===this.inputElement||i===this.timeIcon||i===this.inputWrapper.container?i!==this.inputElement&&(t.Browser.isDevice||(this.isPreventBlur=document.activeElement===this.inputElement&&(t.Browser.isIE||"edge"===t.Browser.info.name)&&i===this.popupObject.element,e.preventDefault())):this.isTimePopupOpen()&&(this.hide(e),this.focusOut())},n.prototype.isTimePopupOpen=function(){return!(!this.dateTimeWrapper||!this.dateTimeWrapper.classList.contains(""+ze))},n.prototype.isDatePopupOpen=function(){return!(!this.popupWrapper||!this.popupWrapper.classList.contains(""+qe))},n.prototype.renderPopup=function(){var e=this;this.containerStyle=this.inputWrapper.container.getBoundingClientRect(),t.Browser.isDevice&&(this.timeModal=t.createElement("div"),this.timeModal.className=ze+" e-time-modal",document.body.className+=" e-time-overflow",this.timeModal.style.display="block",document.body.appendChild(this.timeModal));this.popupObject=new i.Popup(this.dateTimeWrapper,{width:this.setPopupWidth(),zIndex:this.zIndex,targetType:"container",collision:t.Browser.isDevice?{X:"fit",Y:"fit"}:{X:"flip",Y:"flip"},relateTo:t.Browser.isDevice?document.body:this.inputWrapper.container,position:t.Browser.isDevice?{X:"center",Y:"center"}:{X:"left",Y:"bottom"},enableRtl:this.enableRtl,offsetY:4,open:function(){e.dateTimeWrapper.style.visibility="visible",t.addClass([e.timeIcon],Ge),t.Browser.isDevice||(e.timekeyConfigure=t.extend(e.timekeyConfigure,e.keyConfigs),e.inputEvent=new t.KeyboardEvents(e.inputWrapper.container,{keyAction:e.TimeKeyActionHandle.bind(e),keyConfigs:e.timekeyConfigure,eventName:"keydown"}))},close:function(){t.removeClass([e.timeIcon],Ge),e.unWireTimeListEvents(),e.inputElement.setAttribute("aria-activedescendant","null"),t.remove(e.popupObject.element),e.popupObject.destroy(),e.dateTimeWrapper.innerHTML="",e.listWrapper=e.dateTimeWrapper=void 0,e.inputEvent&&e.inputEvent.destroy()}}),this.popupObject.element.style.maxHeight="250px"},n.prototype.setDimension=function(e){return e="number"==typeof e?t.formatUnit(e):"string"==typeof e?e:"100%"},n.prototype.setPopupWidth=function(){var e=this.setDimension(this.width);if(e.indexOf("%")>-1){e=(this.containerStyle.width*parseFloat(e)/100).toString()+"px"}return e},n.prototype.wireTimeListEvents=function(){t.EventHandler.add(this.listWrapper,"click",this.onMouseClick,this),t.Browser.isDevice||(t.EventHandler.add(this.listWrapper,"mouseover",this.onMouseOver,this),t.EventHandler.add(this.listWrapper,"mouseout",this.onMouseLeave,this))},n.prototype.unWireTimeListEvents=function(){this.listWrapper&&(t.EventHandler.remove(this.listWrapper,"click",this.onMouseClick),t.EventHandler.remove(document,"mousedown touchstart",this.documentClickHandler),t.Browser.isDevice||(t.EventHandler.add(this.listWrapper,"mouseover",this.onMouseOver,this),t.EventHandler.add(this.listWrapper,"mouseout",this.onMouseLeave,this)))},n.prototype.onMouseOver=function(e){var i=t.closest(e.target,"."+Xe);this.setTimeHover(i,"e-hover")},n.prototype.onMouseLeave=function(){this.removeTimeHover("e-hover")},n.prototype.setTimeHover=function(e,i){this.enabled&&this.isValidLI(e)&&!e.classList.contains(i)&&(this.removeTimeHover(i),t.addClass([e],i))},n.prototype.getPopupHeight=function(){var e=parseInt("250px",10),t=this.dateTimeWrapper.getBoundingClientRect().height;return t>e?e:t},n.prototype.changeEvent=function(e){+this.previousDateTime!=+this.value&&(a.prototype.changeEvent.call(this,e),this.inputElement.focus(),this.valueWithMinutes=this.value,this.setInputValue("date"),this.previousDateTime=this.value&&new Date(+this.value))},n.prototype.updateValue=function(e){this.setInputValue("time"),+this.previousDateTime!=+this.value&&(this.changedArgs={value:this.value,event:e||null,isInteracted:!t.isNullOrUndefined(e),element:this.element},this.addTimeSelection(),this.trigger("change",this.changedArgs),this.previousDateTime=this.value)},n.prototype.setTimeScrollPosition=function(){var e;e=this.selectedElement,t.isNullOrUndefined(e)?this.dateTimeWrapper&&this.checkDateValue(this.scrollTo)&&this.setScrollTo():this.findScrollTop(e)},n.prototype.findScrollTop=function(e){var t=this.getPopupHeight(),i=e.nextElementSibling,s=i?i.offsetTop:e.offsetTop,a=e.getBoundingClientRect().height;s+e.offsetTop>t?this.dateTimeWrapper.scrollTop=i?s-(t/2+a/2):s:this.dateTimeWrapper.scrollTop=0},n.prototype.setScrollTo=function(){var e,i=this.dateTimeWrapper.querySelectorAll("."+Xe);if(i.length>=0){var s=this.timeCollections[0],a=this.getDateObject(this.checkDateValue(this.scrollTo)).getTime();e=i[Math.round((a-s)/(6e4*this.step))]}else this.dateTimeWrapper.scrollTop=0;t.isNullOrUndefined(e)?this.dateTimeWrapper.scrollTop=0:this.findScrollTop(e)},n.prototype.setInputValue=function(e){if("date"===e)this.inputElement.value=this.previousElementValue=this.getFormattedValue(this.getFullDateTime()),this.setProperties({value:this.getFullDateTime()},!0);else{var t=this.getFormattedValue(new Date(this.timeCollections[this.activeIndex]));s.Input.setValue(t,this.inputElement,this.floatLabelType,this.showClearButton),this.previousElementValue=this.inputElement.value,this.setProperties({value:new Date(this.timeCollections[this.activeIndex])},!0)}this.updateIconState()},n.prototype.getFullDateTime=function(){var e=null;return e=this.isDateObject(this.valueWithMinutes)?this.combineDateTime(this.valueWithMinutes):this.previousDate,this.validateMinMaxRange(e)},n.prototype.combineDateTime=function(e){if(this.isDateObject(e)){var t=this.previousDate.getDate(),i=this.previousDate.getMonth(),s=this.previousDate.getFullYear(),a=e.getHours(),n=e.getMinutes(),r=e.getSeconds();return new Date(s,i,t,a,n,r)}return this.previousDate},n.prototype.onMouseClick=function(e){var i=e.target,s=this.selectedElement=t.closest(i,"."+Xe);s&&s.classList.contains(Xe)&&(this.timeValue=s.getAttribute("data-value"),this.hide(e)),this.setSelection(s,e)},n.prototype.setSelection=function(e,i){if(this.isValidLI(e)&&!e.classList.contains(Ge)){e.getAttribute("data-value");this.selectedElement=e;var s=Array.prototype.slice.call(this.liCollections).indexOf(e);this.activeIndex=s,this.valueWithMinutes=new Date(this.timeCollections[this.activeIndex]),t.addClass([this.selectedElement],Ge),this.selectedElement.setAttribute("aria-selected","true"),this.updateValue(i)}},n.prototype.setTimeActiveClass=function(){var e=t.isNullOrUndefined(this.dateTimeWrapper)?this.listWrapper:this.dateTimeWrapper;if(!t.isNullOrUndefined(e)){var i=e.querySelectorAll("."+Xe);if(i.length)for(var s=0;s<i.length;s++)if(this.timeCollections[s]===+this.valueWithMinutes){i[s].setAttribute("aria-selected","true"),this.selectedElement=i[s],this.activeIndex=s,this.setTimeActiveDescendant();break}}},n.prototype.setTimeActiveDescendant=function(){t.isNullOrUndefined(this.selectedElement)?t.attributes(this.inputElement,{"aria-activedescendant":"null"}):t.attributes(this.inputElement,{"aria-activedescendant":this.selectedElement.getAttribute("id")})},n.prototype.addTimeSelection=function(){this.selectedElement=null,this.removeTimeSelection(),this.setTimeActiveClass(),t.isNullOrUndefined(this.selectedElement)||(t.addClass([this.selectedElement],Ge),this.selectedElement.setAttribute("aria-selected","true"))},n.prototype.removeTimeSelection=function(){if(this.removeTimeHover("e-hover"),!t.isNullOrUndefined(this.dateTimeWrapper)){var e=this.dateTimeWrapper.querySelectorAll("."+Ge);e.length&&(t.removeClass(e,Ge),e[0].removeAttribute("aria-selected"))}},n.prototype.removeTimeHover=function(e){var i=this.getTimeHoverItem(e);i&&i.length&&t.removeClass(i,e)},n.prototype.getTimeHoverItem=function(e){var i,s=t.isNullOrUndefined(this.dateTimeWrapper)?this.listWrapper:this.dateTimeWrapper;return t.isNullOrUndefined(s)||(i=s.querySelectorAll("."+e)),i},n.prototype.isValidLI=function(e){return e&&e.classList.contains(Xe)&&!e.classList.contains(_e)},n.prototype.calculateStartEnd=function(e,t,i){var s=e.getDate(),a=e.getMonth(),n=e.getFullYear(),r=e.getHours(),l=e.getMinutes(),o=e.getSeconds(),h=e.getMilliseconds();return t?"starttime"===i?new Date(n,a,s,0,0,0):new Date(n,a,s,23,59,59):new Date(n,a,s,r,l,o,h)},n.prototype.startTime=function(e){var t,i,s,a=this.min;return+(s=null===e?new Date:e).getDate()==+a.getDate()&&+s.getMonth()==+a.getMonth()&&+s.getFullYear()==+a.getFullYear()||+new Date(s.getFullYear(),s.getMonth(),s.getDate())<=+new Date(a.getFullYear(),a.getMonth(),a.getDate())?(i=!1,t=this.min):+s<+this.max&&+s>+this.min?(i=!0,t=s):+s>=+this.max&&(i=!0,t=this.max),this.calculateStartEnd(t,i,"starttime")},n.prototype.endTime=function(e){var t,i,s,a=this.max;return+(s=null===e?new Date:e).getDate()==+a.getDate()&&+s.getMonth()==+a.getMonth()&&+s.getFullYear()==+a.getFullYear()||+new Date(s.getUTCFullYear(),s.getMonth(),s.getDate())>=+new Date(a.getFullYear(),a.getMonth(),a.getDate())?(i=!1,t=this.max):+s<+this.max&&+s>+this.min?(i=!0,t=s):+s<=+this.min&&(i=!0,t=this.min),this.calculateStartEnd(t,i,"endtime")},n.prototype.hide=function(e){var i=this;if(this.popupObj||this.dateTimeWrapper){this.preventArgs={cancel:!1,popup:this.popupObj||this.popupObject,event:e||null};var s=this.preventArgs;t.isNullOrUndefined(this.popupObj)?this.trigger("close",s,function(t){i.dateTimeCloseEventCallback(e,t)}):this.dateTimeCloseEventCallback(e,s)}else t.Browser.isDevice&&this.allowEdit&&!this.readonly&&this.inputElement.removeAttribute("readonly"),this.setAllowEdit()},n.prototype.dateTimeCloseEventCallback=function(e,i){this.preventArgs=i,this.preventArgs.cancel||(this.isDatePopupOpen()?a.prototype.hide.call(this,e):this.isTimePopupOpen()&&(this.closePopup(e),t.removeClass([document.body],"e-time-overflow"),t.Browser.isDevice&&this.timeModal&&(this.timeModal.style.display="none",this.timeModal.outerHTML="",this.timeModal=null),this.setTimeActiveDescendant())),t.Browser.isDevice&&this.allowEdit&&!this.readonly&&this.inputElement.removeAttribute("readonly"),this.setAllowEdit()},n.prototype.closePopup=function(e){if(this.isTimePopupOpen()&&this.popupObject){var i={name:"FadeOut",duration:100,delay:0};this.popupObject.hide(new t.Animation(i)),this.inputWrapper.container.classList.remove("e-icon-anim"),t.attributes(this.inputElement,{"aria-expanded":"false"}),t.EventHandler.remove(document,"mousedown touchstart",this.documentClickHandler)}},n.prototype.preRender=function(){this.checkFormat(),this.dateTimeFormat=this.cldrDateTimeFormat(),a.prototype.preRender.call(this),t.removeClass([this.inputElementCopy],[ze])},n.prototype.getProperty=function(e,t){"min"===t?this.setProperties({min:this.validateValue(e.min)},!0):this.setProperties({max:this.validateValue(e.max)},!0)},n.prototype.checkAttributes=function(e){for(var i,s=0,a=e?t.isNullOrUndefined(this.htmlAttributes)?[]:Object.keys(this.htmlAttributes):["style","name","step","disabled","readonly","value","min","max","placeholder","type"];s<a.length;s++){var n=a[s];if(!t.isNullOrUndefined(this.inputElement.getAttribute(n)))switch(n){case"name":this.inputElement.setAttribute("name",this.inputElement.getAttribute(n));break;case"step":this.step=parseInt(this.inputElement.getAttribute(n),10);break;case"readonly":if(t.isNullOrUndefined(this.dateTimeOptions)||void 0===this.dateTimeOptions.readonly||e){var r="disabled"===this.inputElement.getAttribute(n)||""===this.inputElement.getAttribute(n)||"true"===this.inputElement.getAttribute(n);this.setProperties({readonly:r},!e)}break;case"placeholder":(t.isNullOrUndefined(this.dateTimeOptions)||void 0===this.dateTimeOptions.placeholder||e)&&this.setProperties({placeholder:this.inputElement.getAttribute(n)},!e);break;case"min":(t.isNullOrUndefined(this.dateTimeOptions)||void 0===this.dateTimeOptions.min||e)&&(i=new Date(this.inputElement.getAttribute(n)),this.isNullOrEmpty(i)||isNaN(+i)||this.setProperties({min:i},!e));break;case"disabled":if(t.isNullOrUndefined(this.dateTimeOptions)||void 0===this.dateTimeOptions.enabled||e){var l="disabled"!==this.inputElement.getAttribute(n)&&"true"!==this.inputElement.getAttribute(n)&&""!==this.inputElement.getAttribute(n);this.setProperties({enabled:l},!e)}break;case"value":(t.isNullOrUndefined(this.dateTimeOptions)||void 0===this.dateTimeOptions.value||e)&&(i=new Date(this.inputElement.getAttribute(n)),this.isNullOrEmpty(i)||isNaN(+i)||this.setProperties({value:i},!e));break;case"max":(t.isNullOrUndefined(this.dateTimeOptions)||void 0===this.dateTimeOptions.max||e)&&(i=new Date(this.inputElement.getAttribute(n)),this.isNullOrEmpty(i)||isNaN(+i)||this.setProperties({max:i},!e))}}},n.prototype.requiredModules=function(){var e=[];return this&&e.push({args:[this],member:"islamic"}),e},n.prototype.getTimeActiveElement=function(){return t.isNullOrUndefined(this.dateTimeWrapper)?null:this.dateTimeWrapper.querySelectorAll("."+Ge)},n.prototype.createDateObj=function(e){return e instanceof Date?e:null},n.prototype.getDateObject=function(e){if(!this.isNullOrEmpty(e)){var i=this.createDateObj(e),s=this.valueWithMinutes,a=!t.isNullOrUndefined(s);if(this.checkDateValue(i)){var n=a?s.getDate():We,r=a?s.getMonth():Le,l=a?s.getFullYear():Fe,o=a?s.getHours():Be,h=a?s.getMinutes():je,u=a?s.getSeconds():Ye,d=a?s.getMilliseconds():Re;return new Date(l,r,n,o,h,u,d)}}return null},n.prototype.findNextTimeElement=function(e){var i=this.inputElement.value,s=t.isNullOrUndefined(this.valueWithMinutes)?this.createDateObj(i):this.getDateObject(this.valueWithMinutes),a=null,n=this.liCollections.length;if(!t.isNullOrUndefined(this.activeIndex)||!t.isNullOrUndefined(this.checkDateValue(s))){if("home"===e.action)a=+this.createDateObj(new Date(this.timeCollections[0])),this.activeIndex=0;else if("end"===e.action)a=+this.createDateObj(new Date(this.timeCollections[this.timeCollections.length-1])),this.activeIndex=this.timeCollections.length-1;else if("down"===e.action){for(var r=0;r<n;r++)if(+s<this.timeCollections[r]){a=+this.createDateObj(new Date(this.timeCollections[r])),this.activeIndex=r;break}}else for(r=n-1;r>=0;r--)if(+s>this.timeCollections[r]){a=+this.createDateObj(new Date(this.timeCollections[r])),this.activeIndex=r;break}this.selectedElement=this.liCollections[this.activeIndex],this.timeElementValue(t.isNullOrUndefined(a)?null:new Date(a))}},n.prototype.setTimeValue=function(e,i){var a,n,r=this.validateMinMaxRange(i),l=this.createDateObj(r);return this.getFormattedValue(l)!==(t.isNullOrUndefined(this.value)?null:this.getFormattedValue(this.value))?(this.valueWithMinutes=t.isNullOrUndefined(l)?null:l,n=new Date(+this.valueWithMinutes)):(this.strictMode&&(e=l),this.valueWithMinutes=this.checkDateValue(e),n=new Date(+this.valueWithMinutes)),a="Gregorian"===this.calendarMode?this.globalize.formatDate(n,{format:t.isNullOrUndefined(this.formatString)?this.cldrDateTimeFormat():this.formatString,type:"dateTime",skeleton:"yMd"}):this.globalize.formatDate(n,{format:t.isNullOrUndefined(this.formatString)?this.cldrDateTimeFormat():this.formatString,type:"dateTime",skeleton:"yMd",calendar:"islamic"}),!this.strictMode&&t.isNullOrUndefined(n),s.Input.setValue(a,this.inputElement,this.floatLabelType,this.showClearButton),n},n.prototype.timeElementValue=function(e){if(!t.isNullOrUndefined(this.checkDateValue(e))&&!this.isNullOrEmpty(e)){var i=e instanceof Date?e:this.getDateObject(e);return this.setTimeValue(i,e)}return null},n.prototype.timeKeyHandler=function(e){if(!(t.isNullOrUndefined(this.step)||this.step<=0)){var i=this.timeCollections.length;if(t.isNullOrUndefined(this.getTimeActiveElement())||0===this.getTimeActiveElement().length)this.liCollections.length>0&&(t.isNullOrUndefined(this.value)&&t.isNullOrUndefined(this.activeIndex)?(this.activeIndex=0,this.selectedElement=this.liCollections[0],this.timeElementValue(new Date(this.timeCollections[0]))):this.findNextTimeElement(e));else{var s=void 0;if(e.keyCode>=37&&e.keyCode<=40){var a=40===e.keyCode||39===e.keyCode?++this.activeIndex:--this.activeIndex;this.activeIndex=a=this.activeIndex===i?0:this.activeIndex,this.activeIndex=a=this.activeIndex<0?i-1:this.activeIndex,s=t.isNullOrUndefined(this.timeCollections[a])?this.timeCollections[0]:this.timeCollections[a]}else"home"===e.action?(this.activeIndex=0,s=this.timeCollections[0]):"end"===e.action&&(this.activeIndex=i-1,s=this.timeCollections[i-1]);this.selectedElement=this.liCollections[this.activeIndex],this.timeElementValue(new Date(s))}this.isNavigate=!0,this.setTimeHover(this.selectedElement,"e-navigation"),this.setTimeActiveDescendant(),!this.isTimePopupOpen()||null===this.selectedElement||e&&"click"===e.type||this.setTimeScrollPosition()}},n.prototype.TimeKeyActionHandle=function(e){if(this.enabled)switch("right"!==e.action&&"left"!==e.action&&"tab"!==e.action&&e.preventDefault(),e.action){case"up":case"down":case"home":case"end":this.timeKeyHandler(e);break;case"enter":this.isNavigate?(this.selectedElement=this.liCollections[this.activeIndex],this.valueWithMinutes=new Date(this.timeCollections[this.activeIndex]),this.setInputValue("time"),+this.previousDateTime!=+this.value&&(this.changedArgs.value=this.value,this.addTimeSelection(),this.previousDateTime=this.value)):this.updateValue(e),this.hide(e),t.addClass([this.inputWrapper.container],Ke),this.isNavigate=!1,e.stopPropagation();break;case"escape":this.hide(e);break;default:this.isNavigate=!1}},n.prototype.inputKeyAction=function(e){switch(e.action){case"altDownArrow":this.strictModeUpdate(),this.updateInput(),this.toggle(e)}},n.prototype.onPropertyChanged=function(e,i){for(var n=0,r=Object.keys(e);n<r.length;n++){var l=r[n];switch(l){case"value":this.cldrDateTimeFormat();this.invalidValueString=null,this.checkInvalidValue(e.value),e.value=this.value,e.value=this.validateValue(e.value),s.Input.setValue(this.getFormattedValue(e.value),this.inputElement,this.floatLabelType,this.showClearButton),this.valueWithMinutes=e.value,this.setProperties({value:e.value},!0),this.previousDateTime=new Date(this.inputElement.value),this.updateInput(),this.changeTrigger(null);break;case"min":case"max":this.getProperty(e,l),this.updateInput();break;case"enableRtl":s.Input.setEnableRtl(this.enableRtl,[this.inputWrapper.container]);break;case"cssClass":s.Input.setCssClass(e.cssClass,[this.inputWrapper.container],i.cssClass),this.dateTimeWrapper&&s.Input.setCssClass(e.cssClass,[this.dateTimeWrapper],i.cssClass);break;case"locale":this.globalize=new t.Internationalization(this.locale),this.l10n.setLocale(this.locale),this.setProperties({placeholder:this.l10n.getConstant("placeholder")},!0),s.Input.setPlaceholder(this.l10n.getConstant("placeholder"),this.inputElement),this.dateTimeFormat=this.cldrDateTimeFormat(),a.prototype.updateInput.call(this);break;case"htmlAttributes":this.updateHtmlAttributeToElement(),this.updateHtmlAttributeToWrapper(),this.checkAttributes(!0);break;case"format":this.setProperties({format:e.format},!0),this.checkFormat(),this.dateTimeFormat=this.formatString,this.setValue();break;case"placeholder":s.Input.setPlaceholder(e.placeholder,this.inputElement),this.inputElement.setAttribute("aria-placeholder",e.placeholder);break;case"enabled":s.Input.setEnabled(this.enabled,this.inputElement),this.enabled||(this.inputElement.tabIndex=-1),this.bindEvents();break;case"strictMode":this.invalidValueString=null,this.updateInput();break;case"width":this.setWidth(e.width);break;case"readonly":s.Input.setReadonly(this.readonly,this.inputElement);break;case"floatLabelType":this.floatLabelType=e.floatLabelType,s.Input.removeFloating(this.inputWrapper),s.Input.addFloating(this.inputElement,this.floatLabelType,this.placeholder);break;case"scrollTo":this.checkDateValue(new Date(this.checkValue(e.scrollTo)))?(this.dateTimeWrapper&&this.setScrollTo(),this.setProperties({scrollTo:e.scrollTo},!0)):this.setProperties({scrollTo:null},!0);break;default:a.prototype.onPropertyChanged.call(this,e,i)}this.hide(null)}},n.prototype.getModuleName=function(){return"datetimepicker"},n.prototype.restoreValue=function(){this.previousDateTime=this.previousDate,this.currentDate=this.value?this.value:new Date,this.valueWithMinutes=this.value,this.previousDate=this.value,this.previousElementValue=this.previousElementValue=t.isNullOrUndefined(this.inputValueCopy)?"":this.getFormattedValue(this.inputValueCopy)},He([t.Property(null)],n.prototype,"timeFormat",void 0),He([t.Property(30)],n.prototype,"step",void 0),He([t.Property(null)],n.prototype,"scrollTo",void 0),He([t.Property(1e3)],n.prototype,"zIndex",void 0),He([t.Property(null)],n.prototype,"keyConfigs",void 0),He([t.Property({})],n.prototype,"htmlAttributes",void 0),He([t.Property(!1)],n.prototype,"enablePersistence",void 0),He([t.Property(!0)],n.prototype,"allowEdit",void 0),He([t.Property(!1)],n.prototype,"isMultiSelection",void 0),He([t.Property(null)],n.prototype,"values",void 0),He([t.Property(!0)],n.prototype,"showClearButton",void 0),He([t.Property(null)],n.prototype,"placeholder",void 0),He([t.Property(!1)],n.prototype,"strictMode",void 0),He([t.Event()],n.prototype,"open",void 0),He([t.Event()],n.prototype,"close",void 0),He([t.Event()],n.prototype,"blur",void 0),He([t.Event()],n.prototype,"focus",void 0),He([t.Event()],n.prototype,"created",void 0),He([t.Event()],n.prototype,"destroyed",void 0),n=He([t.NotifyPropertyChanges],n)}(F);e.CalendarBase=E,e.Calendar=C,e.Islamic=M,e.DatePicker=F,e.Presets=be,e.DateRangePicker=De,e.TimePicker=Pe,e.DateTimePicker=Ze,Object.defineProperty(e,"__esModule",{value:!0})}); //# sourceMappingURL=ej2-calendars.umd.min.js.map
/** * Copyright IBM Corp. 2016, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * Code generated by @carbon/icon-build-helpers. DO NOT EDIT. */ 'use strict'; var _32 = { "elem": "svg", "attrs": { "xmlns": "http://www.w3.org/2000/svg", "viewBox": "0 0 32 32", "fill": "currentColor", "width": 32, "height": 32 }, "content": [{ "elem": "path", "attrs": { "d": "M27,3H5A2,2,0,0,0,3,5V27a2,2,0,0,0,2,2H27a2,2,0,0,0,2-2V5A2,2,0,0,0,27,3Zm0,2V9H5V5ZM17,11H27v7H17Zm-2,7H5V11H15ZM5,20H15v7H5Zm12,7V20H27v7Z" } }], "name": "table--split", "size": 32 }; module.exports = _32;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils_tests_helpers_1 = require("@hint/utils-tests-helpers"); const utils_types_1 = require("@hint/utils-types"); const hintPath = utils_tests_helpers_1.getHintPath(__filename); const ssllabsMock = (response) => { return { './api': { analyze: async (options) => { if (response === null) { throw new Error('Error'); } return response; } } }; }; const results = { aplussite: { endpoints: [{ grade: 'A+' }] }, asite: { endpoints: [{ grade: 'A' }, { grade: 'A', serverName: 'a-site.net' }] }, nohttps: { endpoints: [{ details: { protocols: [] } }] } }; const testsForDefaults = [ { name: `Site with with A+ grade passes`, overrides: ssllabsMock(results.aplussite), serverUrl: 'https://example.com' }, { name: `Site A grade passes`, overrides: ssllabsMock(results.asite), serverUrl: 'https://example.com' }, { name: `Domain without HTTPS fails with default configuration`, overrides: ssllabsMock(results.nohttps), reports: [{ message: `'http://example.com/' does not support HTTPS.`, severity: utils_types_1.Severity.error }], serverUrl: 'http://example.com' }, { name: `Resource is not an HTML document`, serverConfig: { '/': { headers: { 'Content-Type': 'image/png' } } } } ]; const testsForConfigs = [ { name: `Site with A+ grade passes with A+ minimum`, overrides: ssllabsMock(results.aplussite), serverUrl: 'https://example.com' }, { name: `Site with A grade doesn't pass with A+ minimum`, overrides: ssllabsMock(results.asite), reports: [ { message: `https://example.com/'s grade A does not meet the minimum A+ required.`, severity: utils_types_1.Severity.error }, { message: `a-site.net's grade A does not meet the minimum A+ required.`, severity: utils_types_1.Severity.error } ], serverUrl: 'https://example.com' }, { name: `Domain without HTTPS fails with a custom configuration`, overrides: ssllabsMock(results.nohttps), reports: [{ message: `'http://example.com/' does not support HTTPS.`, severity: utils_types_1.Severity.error }], serverUrl: 'http://example.com' } ]; const testsForErrors = [ { name: 'Issue gettings results from SSL Labs reports error', overrides: ssllabsMock(null), reports: [{ message: `Could not get results from SSL Labs for 'https://example.com/'.`, severity: utils_types_1.Severity.warning }], serverUrl: 'https://example.com' }, { name: 'Missing endpoints reports an error', overrides: ssllabsMock({}), reports: [{ message: `Didn't get any result for https://example.com/. There might be something wrong with SSL Labs servers.`, severity: utils_types_1.Severity.warning }], serverUrl: 'https://example.com' }, { name: 'Empty endpoints array reports an error', overrides: ssllabsMock({ endpoints: [] }), reports: [{ message: `Didn't get any result for https://example.com/. There might be something wrong with SSL Labs servers.`, severity: utils_types_1.Severity.warning }], serverUrl: 'https://example.com' }, { name: 'Response with right status code but nothing inside reports an error', overrides: ssllabsMock(undefined), reports: [{ message: `Didn't get any result for https://example.com/. There might be something wrong with SSL Labs servers.`, severity: utils_types_1.Severity.warning }], serverUrl: 'https://example.com' } ]; utils_tests_helpers_1.testHint(hintPath, testsForDefaults, { serial: true }); utils_tests_helpers_1.testHint(hintPath, testsForConfigs, { hintOptions: { grade: 'A+' }, serial: true }); utils_tests_helpers_1.testHint(hintPath, testsForErrors, { serial: true });
import React from "react"; import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown'; import "../MusicPlayerPanel.css"; export const DropDownButton = (props) => { return ( <React.Fragment> <div className={"MusicPlayerPanel__open__dropDown"}> <ArrowDropDownIcon onClick={props.toggleMusicPanel} /> </div> </React.Fragment> ); };
import React from 'react'; import PropTypes from 'prop-types'; const UitWebSection = (props) => { const { color, size, ...otherProps } = props return React.createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: color, ...otherProps }, React.createElement('path', { d: 'M21.5,2H2.4993896C2.2234497,2.0001831,1.9998169,2.223999,2,2.5v19.0005493C2.0001831,21.7765503,2.223999,22.0001831,2.5,22h19.0006104C21.7765503,21.9998169,22.0001831,21.776001,22,21.5V2.4993896C21.9998169,2.2234497,21.776001,1.9998169,21.5,2z M14.5,21H3V3h11.5V21z M21,21h-5.5V3H21V21z' })); }; UitWebSection.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; UitWebSection.defaultProps = { color: 'currentColor', size: '24', }; export default UitWebSection;
/* * * 给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。 * * 示例 1: * * 输入: [0,1,2,4,5,7] * 输出: [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;] * 解释: 0,1,2 可组成一个连续的区间;&nbsp;4,5 可组成一个连续的区间。 * * 示例 2: * * 输入: [0,2,3,4,6,8,9] * 输出: [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;] * 解释: 2,3,4 可组成一个连续的区间;&nbsp;8,9 可组成一个连续的区间。 * * */
export const texts = { days: [ 'Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado' ], howLongYear: 'Hace más de un año', howLongMonth: 'Hace unos meses', howLongWeek: 'Hace unas semanas', howLongDay: 'Hace unos días', howLongHour: 'Hace unas horas', howLongMinut: 'Hace unos minutos', howLongSecond: 'Hace unos segundos' }
# Copyright 2019 Google LLC # # 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. """Credentials management.""" from oauth2client.client import Credentials from oauth2client.client import Storage from clusterfuzz._internal.config import db_config class CredentialStorage(Storage): """Instead of reading a file, just parse a config entry.""" def locked_get(self): """Return Credentials.""" content = db_config.get_value('client_credentials') if not content: return None try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: return None return credentials def locked_put(self, credentials): # pylint: disable=unused-argument pass def locked_delete(self): pass
import pytest from django.contrib.contenttypes.models import ContentType from constants import user_system from event_manager.event import Attribute, Event from event_manager.events import ( bookmark, build_job, chart_view, cluster, experiment, experiment_group, experiment_job, job, notebook, permission, project, repo, search, superuser, tensorboard, user ) from event_manager.events.experiment import ExperimentSucceededEvent from factories.factory_experiments import ExperimentFactory from libs.json_utils import loads from tests.utils import BaseTest @pytest.mark.events_mark class TestEvents(BaseTest): DISABLE_RUNNER = True def test_events_subjects(self): # pylint:disable=too-many-statements # Cluster assert cluster.ClusterCreatedEvent.get_event_subject() == 'cluster' assert cluster.ClusterUpdatedEvent.get_event_subject() == 'cluster' assert cluster.ClusterNodeCreatedEvent.get_event_subject() == 'cluster_node' assert cluster.ClusterNodeUpdatedEvent.get_event_subject() == 'cluster_node' assert cluster.ClusterNodeDeletedEvent.get_event_subject() == 'cluster_node' assert cluster.ClusterNodeGPU.get_event_subject() == 'cluster_node' # Experiment assert experiment.ExperimentCreatedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentUpdatedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentDeletedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentViewedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentBookmarkedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentUnBookmarkedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentStoppedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentResumedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentRestartedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentCopiedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentNewStatusEvent.get_event_subject() == 'experiment' assert experiment.ExperimentNewMetricEvent.get_event_subject() == 'experiment' assert experiment.ExperimentSucceededEvent.get_event_subject() == 'experiment' assert experiment.ExperimentFailedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentDoneEvent.get_event_subject() == 'experiment' assert experiment.ExperimentResourcesViewedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentLogsViewedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentOutputsDownloadedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentStatusesViewedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentJobsViewedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentMetricsViewedEvent.get_event_subject() == 'experiment' assert experiment.ExperimentDeletedTriggeredEvent.get_event_subject() == 'experiment' assert experiment.ExperimentStoppedTriggeredEvent.get_event_subject() == 'experiment' assert experiment.ExperimentResumedTriggeredEvent.get_event_subject() == 'experiment' assert experiment.ExperimentRestartedTriggeredEvent.get_event_subject() == 'experiment' assert experiment.ExperimentCopiedTriggeredEvent.get_event_subject() == 'experiment' # Experiment group assert (experiment_group.ExperimentGroupCreatedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupUpdatedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupDeletedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupViewedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupBookmarkedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupUnBookmarkedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupStoppedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupResumedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupDoneEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupNewStatusEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupExperimentsViewedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupStatusesViewedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupMetricsViewedEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupIterationEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupRandomEvent.get_event_subject() == 'experiment_group') assert experiment_group.ExperimentGroupGridEvent.get_event_subject() == 'experiment_group' assert (experiment_group.ExperimentGroupHyperbandEvent.get_event_subject() == 'experiment_group') assert experiment_group.ExperimentGroupBOEvent.get_event_subject() == 'experiment_group' assert (experiment_group.ExperimentGroupDeletedTriggeredEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupStoppedTriggeredEvent.get_event_subject() == 'experiment_group') assert (experiment_group.ExperimentGroupResumedTriggeredEvent.get_event_subject() == 'experiment_group') # Experiment job assert experiment_job.ExperimentJobViewedEvent.get_event_subject() == 'experiment_job' assert (experiment_job.ExperimentJobResourcesViewedEvent.get_event_subject() == 'experiment_job') assert experiment_job.ExperimentJobLogsViewedEvent.get_event_subject() == 'experiment_job' assert (experiment_job.ExperimentJobStatusesViewedEvent.get_event_subject() == 'experiment_job') # Notebook assert notebook.NotebookStartedEvent.get_event_subject() == 'notebook' assert notebook.NotebookStartedTriggeredEvent.get_event_subject() == 'notebook' assert notebook.NotebookSoppedEvent.get_event_subject() == 'notebook' assert notebook.NotebookSoppedTriggeredEvent.get_event_subject() == 'notebook' assert notebook.NotebookViewedEvent.get_event_subject() == 'notebook' assert notebook.NotebookNewStatusEvent.get_event_subject() == 'notebook' assert notebook.NotebookFailedEvent.get_event_subject() == 'notebook' assert notebook.NotebookSucceededEvent.get_event_subject() == 'notebook' # Job assert job.JobCreatedEvent.get_event_subject() == 'job' assert job.JobUpdatedEvent.get_event_subject() == 'job' assert job.JobStartedEvent.get_event_subject() == 'job' assert job.JobStartedTriggeredEvent.get_event_subject() == 'job' assert job.JobSoppedEvent.get_event_subject() == 'job' assert job.JobSoppedTriggeredEvent.get_event_subject() == 'job' assert job.JobViewedEvent.get_event_subject() == 'job' assert job.JobBookmarkedEvent.get_event_subject() == 'job' assert job.JobUnBookmarkedEvent.get_event_subject() == 'job' assert job.JobNewStatusEvent.get_event_subject() == 'job' assert job.JobFailedEvent.get_event_subject() == 'job' assert job.JobSucceededEvent.get_event_subject() == 'job' assert job.JobDoneEvent.get_event_subject() == 'job' assert job.JobDeletedEvent.get_event_subject() == 'job' assert job.JobDeletedTriggeredEvent.get_event_subject() == 'job' assert job.JobLogsViewedEvent.get_event_subject() == 'job' assert job.JobRestartedEvent.get_event_subject() == 'job' assert job.JobRestartedTriggeredEvent.get_event_subject() == 'job' assert job.JobStatusesViewedEvent.get_event_subject() == 'job' assert job.JobOutputsDownloadedEvent.get_event_subject() == 'job' # BuildJob assert build_job.BuildJobCreatedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobUpdatedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobStartedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobStartedTriggeredEvent.get_event_subject() == 'build_job' assert build_job.BuildJobSoppedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobSoppedTriggeredEvent.get_event_subject() == 'build_job' assert build_job.BuildJobViewedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobBookmarkedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobUnBookmarkedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobNewStatusEvent.get_event_subject() == 'build_job' assert build_job.BuildJobFailedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobSucceededEvent.get_event_subject() == 'build_job' assert build_job.BuildJobDoneEvent.get_event_subject() == 'build_job' assert build_job.BuildJobDeletedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobDeletedTriggeredEvent.get_event_subject() == 'build_job' assert build_job.BuildJobLogsViewedEvent.get_event_subject() == 'build_job' assert build_job.BuildJobStatusesViewedEvent.get_event_subject() == 'build_job' # Bookmarks assert bookmark.BookmarkBuildJobsViewedEvent.get_event_subject() == 'bookmark' assert bookmark.BookmarkJobsViewedEvent.get_event_subject() == 'bookmark' assert bookmark.BookmarkExperimentsViewedEvent.get_event_subject() == 'bookmark' assert bookmark.BookmarkExperimentGroupsViewedEvent.get_event_subject() == 'bookmark' assert bookmark.BookmarkProjectsViewedEvent.get_event_subject() == 'bookmark' # Searches assert search.SearchCreatedEvent.get_event_subject() == 'search' assert search.SearchDeletedEvent.get_event_subject() == 'search' # Chart view assert chart_view.ChartViewCreatedEvent.get_event_subject() == 'chart_view' assert chart_view.ChartViewDeletedEvent.get_event_subject() == 'chart_view' # Permission assert permission.PermissionProjectDeniedEvent.get_event_subject() == 'project' assert permission.PermissionRepoDeniedEvent.get_event_subject() == 'repo' assert (permission.PermissionExperimentGroupDeniedEvent.get_event_subject() == 'experiment_group') assert permission.PermissionExperimentDeniedEvent.get_event_subject() == 'experiment' assert permission.PermissionTensorboardDeniedEvent.get_event_subject() == 'tensorboard' assert permission.PermissionNotebookDeniedEvent.get_event_subject() == 'notebook' assert permission.PermissionBuildJobDeniedEvent.get_event_subject() == 'build_job' assert permission.PermissionExperimentJobDeniedEvent.get_event_subject() == 'experiment_job' assert permission.PermissionClusterDeniedEvent.get_event_subject() == 'cluster' assert permission.PermissionUserRoleEvent.get_event_subject() == 'superuser' # Project assert project.ProjectCreatedEvent.get_event_subject() == 'project' assert project.ProjectUpdatedEvent.get_event_subject() == 'project' assert project.ProjectDeletedEvent.get_event_subject() == 'project' assert project.ProjectDeletedTriggeredEvent.get_event_subject() == 'project' assert project.ProjectViewedEvent.get_event_subject() == 'project' assert project.ProjectBookmarkedEvent.get_event_subject() == 'project' assert project.ProjectUnBookmarkedEvent.get_event_subject() == 'project' assert project.ProjectSetPublicEvent.get_event_subject() == 'project' assert project.ProjectSetPrivateEvent.get_event_subject() == 'project' assert project.ProjectExperimentsViewedEvent.get_event_subject() == 'project' assert project.ProjectExperimentGroupsViewedEvent.get_event_subject() == 'project' assert project.ProjectJobsViewedEvent.get_event_subject() == 'project' assert project.ProjectBuildsViewedEvent.get_event_subject() == 'project' assert project.ProjectTensorboardsViewedEvent.get_event_subject() == 'project' # Repo assert repo.RepoCreatedEvent.get_event_subject() == 'repo' assert repo.RepoNewCommitEvent.get_event_subject() == 'repo' # Superuser assert superuser.SuperUserRoleGrantedEvent.get_event_subject() == 'superuser' assert superuser.SuperUserRoleRevokedEvent.get_event_subject() == 'superuser' # Tensorboard assert tensorboard.TensorboardStartedEvent.get_event_subject() == 'tensorboard' assert tensorboard.TensorboardStartedTriggeredEvent.get_event_subject() == 'tensorboard' assert tensorboard.TensorboardSoppedEvent.get_event_subject() == 'tensorboard' assert tensorboard.TensorboardSoppedTriggeredEvent.get_event_subject() == 'tensorboard' assert tensorboard.TensorboardViewedEvent.get_event_subject() == 'tensorboard' assert tensorboard.TensorboardBookmarkedEvent.get_event_subject() == 'tensorboard' assert tensorboard.TensorboardUnBookmarkedEvent.get_event_subject() == 'tensorboard' assert tensorboard.TensorboardNewStatusEvent.get_event_subject() == 'tensorboard' assert tensorboard.TensorboardFailedEvent.get_event_subject() == 'tensorboard' assert tensorboard.TensorboardSucceededEvent.get_event_subject() == 'tensorboard' # User assert user.UserRegisteredEvent.get_event_subject() == 'user' assert user.UserUpdatedEvent.get_event_subject() == 'user' assert user.UserActivatedEvent.get_event_subject() == 'user' assert user.UserDeletedEvent.get_event_subject() == 'user' assert user.UserLDAPEvent.get_event_subject() == 'user' assert user.UserGITHUBEvent.get_event_subject() == 'user' assert user.UserGITLABEvent.get_event_subject() == 'user' assert user.UserBITBUCKETEvent.get_event_subject() == 'user' assert user.UserAZUREEvent.get_event_subject() == 'user' def test_events_actions(self): # pylint:disable=too-many-statements # Cluster assert cluster.ClusterCreatedEvent.get_event_action() is None assert cluster.ClusterUpdatedEvent.get_event_action() is None assert cluster.ClusterNodeCreatedEvent.get_event_action() is None assert cluster.ClusterNodeUpdatedEvent.get_event_action() is None assert cluster.ClusterNodeDeletedEvent.get_event_action() is None assert cluster.ClusterNodeGPU.get_event_action() is None # Experiment assert experiment.ExperimentCreatedEvent.get_event_action() == 'created' assert experiment.ExperimentUpdatedEvent.get_event_action() == 'updated' assert experiment.ExperimentDeletedEvent.get_event_action() is None assert experiment.ExperimentViewedEvent.get_event_action() == 'viewed' assert experiment.ExperimentBookmarkedEvent.get_event_action() == 'bookmarked' assert experiment.ExperimentUnBookmarkedEvent.get_event_action() == 'unbookmarked' assert experiment.ExperimentStoppedEvent.get_event_action() is None assert experiment.ExperimentResumedEvent.get_event_action() is None assert experiment.ExperimentRestartedEvent.get_event_action() is None assert experiment.ExperimentCopiedEvent.get_event_action() is None assert experiment.ExperimentNewStatusEvent.get_event_action() is None assert experiment.ExperimentNewMetricEvent.get_event_action() is None assert experiment.ExperimentSucceededEvent.get_event_action() is None assert experiment.ExperimentFailedEvent.get_event_action() is None assert experiment.ExperimentDoneEvent.get_event_action() is None assert experiment.ExperimentResourcesViewedEvent.get_event_action() == 'resources_viewed' assert experiment.ExperimentLogsViewedEvent.get_event_action() == 'logs_viewed' assert (experiment.ExperimentOutputsDownloadedEvent.get_event_action() == 'outputs_downloaded') assert experiment.ExperimentStatusesViewedEvent.get_event_action() == 'statuses_viewed' assert experiment.ExperimentJobsViewedEvent.get_event_action() == 'jobs_viewed' assert experiment.ExperimentMetricsViewedEvent.get_event_action() == 'metrics_viewed' assert experiment.ExperimentDeletedTriggeredEvent.get_event_action() == 'deleted' assert experiment.ExperimentStoppedTriggeredEvent.get_event_action() == 'stopped' assert experiment.ExperimentResumedTriggeredEvent.get_event_action() == 'resumed' assert experiment.ExperimentRestartedTriggeredEvent.get_event_action() == 'restarted' assert experiment.ExperimentCopiedTriggeredEvent.get_event_action() == 'copied' # Experiment group assert experiment_group.ExperimentGroupCreatedEvent.get_event_action() == 'created' assert experiment_group.ExperimentGroupUpdatedEvent.get_event_action() == 'updated' assert experiment_group.ExperimentGroupDeletedEvent.get_event_action() is None assert experiment_group.ExperimentGroupViewedEvent.get_event_action() == 'viewed' assert experiment_group.ExperimentGroupBookmarkedEvent.get_event_action() == 'bookmarked' assert (experiment_group.ExperimentGroupUnBookmarkedEvent.get_event_action() == 'unbookmarked') assert experiment_group.ExperimentGroupStoppedEvent.get_event_action() is None assert experiment_group.ExperimentGroupResumedEvent.get_event_action() is None assert experiment_group.ExperimentGroupDoneEvent.get_event_action() is None assert experiment_group.ExperimentGroupNewStatusEvent.get_event_action() is None assert (experiment_group.ExperimentGroupExperimentsViewedEvent.get_event_action() == 'experiments_viewed') assert (experiment_group.ExperimentGroupStatusesViewedEvent.get_event_action() == 'statuses_viewed') assert (experiment_group.ExperimentGroupMetricsViewedEvent.get_event_action() == 'metrics_viewed') assert experiment_group.ExperimentGroupIterationEvent.get_event_action() is None assert experiment_group.ExperimentGroupRandomEvent.get_event_action() is None assert experiment_group.ExperimentGroupGridEvent.get_event_action() is None assert experiment_group.ExperimentGroupHyperbandEvent.get_event_action() is None assert experiment_group.ExperimentGroupBOEvent.get_event_action() is None assert experiment_group.ExperimentGroupDeletedTriggeredEvent.get_event_action() == 'deleted' assert experiment_group.ExperimentGroupStoppedTriggeredEvent.get_event_action() == 'stopped' assert experiment_group.ExperimentGroupResumedTriggeredEvent.get_event_action() == 'resumed' # Experiment job assert experiment_job.ExperimentJobViewedEvent.get_event_action() == 'viewed' assert (experiment_job.ExperimentJobResourcesViewedEvent.get_event_action() == 'resources_viewed') assert experiment_job.ExperimentJobLogsViewedEvent.get_event_action() == 'logs_viewed' assert (experiment_job.ExperimentJobStatusesViewedEvent.get_event_action() == 'statuses_viewed') # Notebook assert notebook.NotebookStartedEvent.get_event_action() is None assert notebook.NotebookStartedTriggeredEvent.get_event_action() == 'started' assert notebook.NotebookSoppedEvent.get_event_action() is None assert notebook.NotebookSoppedTriggeredEvent.get_event_action() == 'stopped' assert notebook.NotebookViewedEvent.get_event_action() == 'viewed' assert notebook.NotebookNewStatusEvent.get_event_action() is None assert notebook.NotebookFailedEvent.get_event_action() is None assert notebook.NotebookSucceededEvent.get_event_action() is None # Job assert job.JobCreatedEvent.get_event_action() == 'created' assert job.JobUpdatedEvent.get_event_action() == 'updated' assert job.JobStartedEvent.get_event_action() is None assert job.JobStartedTriggeredEvent.get_event_action() == 'started' assert job.JobSoppedEvent.get_event_action() is None assert job.JobSoppedTriggeredEvent.get_event_action() == 'stopped' assert job.JobViewedEvent.get_event_action() == 'viewed' assert job.JobBookmarkedEvent.get_event_action() == 'bookmarked' assert job.JobUnBookmarkedEvent.get_event_action() == 'unbookmarked' assert job.JobNewStatusEvent.get_event_action() is None assert job.JobFailedEvent.get_event_action() is None assert job.JobSucceededEvent.get_event_action() is None assert job.JobDoneEvent.get_event_action() is None assert job.JobDeletedEvent.get_event_action() is None assert job.JobDeletedTriggeredEvent.get_event_action() == 'deleted' assert job.JobLogsViewedEvent.get_event_action() == 'logs_viewed' assert job.JobRestartedEvent.get_event_action() is None assert job.JobRestartedTriggeredEvent.get_event_action() == 'restarted' assert job.JobStatusesViewedEvent.get_event_action() == 'statuses_viewed' assert job.JobOutputsDownloadedEvent.get_event_action() == 'outputs_downloaded' # Build job assert build_job.BuildJobCreatedEvent.get_event_action() == 'created' assert build_job.BuildJobUpdatedEvent.get_event_action() == 'updated' assert build_job.BuildJobStartedEvent.get_event_action() is None assert build_job.BuildJobStartedTriggeredEvent.get_event_action() == 'started' assert build_job.BuildJobSoppedEvent.get_event_action() is None assert build_job.BuildJobSoppedTriggeredEvent.get_event_action() == 'stopped' assert build_job.BuildJobViewedEvent.get_event_action() == 'viewed' assert build_job.BuildJobBookmarkedEvent.get_event_action() == 'bookmarked' assert build_job.BuildJobUnBookmarkedEvent.get_event_action() == 'unbookmarked' assert build_job.BuildJobNewStatusEvent.get_event_action() is None assert build_job.BuildJobFailedEvent.get_event_action() is None assert build_job.BuildJobSucceededEvent.get_event_action() is None assert build_job.BuildJobDoneEvent.get_event_action() is None assert build_job.BuildJobDeletedEvent.get_event_action() is None assert build_job.BuildJobDeletedTriggeredEvent.get_event_action() == 'deleted' assert build_job.BuildJobLogsViewedEvent.get_event_action() == 'logs_viewed' assert build_job.BuildJobStatusesViewedEvent.get_event_action() == 'statuses_viewed' # Bookmarks assert bookmark.BookmarkBuildJobsViewedEvent.get_event_action() == 'builds_viewed' assert bookmark.BookmarkJobsViewedEvent.get_event_action() == 'jobs_viewed' assert bookmark.BookmarkExperimentsViewedEvent.get_event_action() == 'experiments_viewed' assert (bookmark.BookmarkExperimentGroupsViewedEvent.get_event_action() == 'experiment_groups_viewed') assert bookmark.BookmarkProjectsViewedEvent.get_event_action() == 'projects_viewed' # Searches assert search.SearchCreatedEvent.get_event_action() == 'created' assert search.SearchDeletedEvent.get_event_action() == 'deleted' # Chart views assert chart_view.ChartViewCreatedEvent.get_event_action() == 'created' assert chart_view.ChartViewDeletedEvent.get_event_action() == 'deleted' # Permission assert permission.PermissionProjectDeniedEvent.get_event_action() == 'denied' assert permission.PermissionRepoDeniedEvent.get_event_action() == 'denied' assert permission.PermissionExperimentGroupDeniedEvent.get_event_action() == 'denied' assert permission.PermissionExperimentDeniedEvent.get_event_action() == 'denied' assert permission.PermissionTensorboardDeniedEvent.get_event_action() == 'denied' assert permission.PermissionNotebookDeniedEvent.get_event_action() == 'denied' assert permission.PermissionBuildJobDeniedEvent.get_event_action() == 'denied' assert permission.PermissionExperimentJobDeniedEvent.get_event_action() == 'denied' assert permission.PermissionClusterDeniedEvent.get_event_action() == 'denied' assert permission.PermissionUserRoleEvent.get_event_action() == 'denied' # Project assert project.ProjectCreatedEvent.get_event_action() == 'created' assert project.ProjectUpdatedEvent.get_event_action() == 'updated' assert project.ProjectDeletedEvent.get_event_action() is None assert project.ProjectDeletedTriggeredEvent.get_event_action() == 'deleted' assert project.ProjectViewedEvent.get_event_action() == 'viewed' assert project.ProjectBookmarkedEvent.get_event_action() == 'bookmarked' assert project.ProjectUnBookmarkedEvent.get_event_action() == 'unbookmarked' assert project.ProjectSetPublicEvent.get_event_action() is None assert project.ProjectSetPrivateEvent.get_event_action() is None assert project.ProjectExperimentsViewedEvent.get_event_action() == 'experiments_viewed' assert (project.ProjectExperimentGroupsViewedEvent.get_event_action() == 'experiment_groups_viewed') assert project.ProjectJobsViewedEvent.get_event_action() == 'jobs_viewed' assert project.ProjectBuildsViewedEvent.get_event_action() == 'builds_viewed' assert project.ProjectTensorboardsViewedEvent.get_event_action() == 'tensorboards_viewed' # Repo assert repo.RepoCreatedEvent.get_event_action() == 'created' assert repo.RepoNewCommitEvent.get_event_action() == 'new_commit' # Superuser assert superuser.SuperUserRoleGrantedEvent.get_event_action() == 'granted' assert superuser.SuperUserRoleRevokedEvent.get_event_action() == 'revoked' # Tensorboard assert tensorboard.TensorboardStartedEvent.get_event_action() is None assert tensorboard.TensorboardStartedTriggeredEvent.get_event_action() == 'started' assert tensorboard.TensorboardSoppedEvent.get_event_action() is None assert tensorboard.TensorboardSoppedTriggeredEvent.get_event_action() == 'stopped' assert tensorboard.TensorboardViewedEvent.get_event_action() == 'viewed' assert tensorboard.TensorboardBookmarkedEvent.get_event_action() == 'bookmarked' assert tensorboard.TensorboardUnBookmarkedEvent.get_event_action() == 'unbookmarked' assert tensorboard.TensorboardNewStatusEvent.get_event_action() is None assert tensorboard.TensorboardFailedEvent.get_event_action() is None assert tensorboard.TensorboardSucceededEvent.get_event_action() is None # User assert user.UserRegisteredEvent.get_event_action() == 'registered' assert user.UserUpdatedEvent.get_event_action() == 'updated' assert user.UserActivatedEvent.get_event_action() == 'activated' assert user.UserDeletedEvent.get_event_action() == 'deleted' assert user.UserLDAPEvent.get_event_action() is None assert user.UserGITHUBEvent.get_event_action() == 'auth' assert user.UserGITLABEvent.get_event_action() == 'auth' assert user.UserBITBUCKETEvent.get_event_action() == 'auth' assert user.UserAZUREEvent.get_event_action() == 'auth' def test_serialize(self): class DummyEvent(Event): event_type = 'dummy.event' attributes = ( Attribute('attr1'), ) event = DummyEvent(attr1='test') event_serialized = event.serialize(dumps=False) assert event_serialized['type'] == 'dummy.event' assert event_serialized['uuid'] is not None assert event_serialized['timestamp'] is not None assert event_serialized['data']['attr1'] == 'test' event_serialized_dump = event.serialize(dumps=True) assert event_serialized == loads(event_serialized_dump) def test_serialize_with_instance(self): instance = ExperimentFactory() event = ExperimentSucceededEvent.from_instance(instance=instance, actor_id=1, actor_name='user') event_serialized = event.serialize(dumps=False, include_instance_info=True) instance_contenttype = ContentType.objects.get_for_model(instance).id assert event_serialized['instance_id'] == instance.id assert event_serialized['instance_contenttype'] == instance_contenttype def test_from_event_data(self): instance = ExperimentFactory() event = ExperimentSucceededEvent.from_instance(instance=instance, actor_id=1, actor_name='user') event_serialized = event.serialize(dumps=False, include_instance_info=True) new_event = ExperimentSucceededEvent.from_event_data(event_data=event_serialized) assert new_event.serialize(include_instance_info=True) == event_serialized def test_get_value_from_instance(self): class DummyEvent(Event): event_type = 'dummy.event' class SimpleObject(object): attr1 = 'test' class ComposedObject(object): attr2 = SimpleObject() value = DummyEvent.get_value_from_instance(attr='attr1', instance=SimpleObject()) assert value == 'test' value = DummyEvent.get_value_from_instance(attr='attr2', instance=SimpleObject()) assert value is None value = DummyEvent.get_value_from_instance(attr='attr2.attr1', instance=ComposedObject()) assert value == 'test' value = DummyEvent.get_value_from_instance(attr='attr2.attr3', instance=ComposedObject()) assert value is None value = DummyEvent.get_value_from_instance(attr='attr2.attr1.attr3', instance=ComposedObject()) assert value is None value = DummyEvent.get_value_from_instance(attr='attr2.attr4.attr3', instance=SimpleObject()) assert value is None def test_from_instance_simple_event(self): class DummyEvent(Event): event_type = 'dummy.event' attributes = ( Attribute('attr1'), ) class DummyObject(object): attr1 = 'test' obj = DummyObject() event = DummyEvent.from_instance(obj) event_serialized = event.serialize(dumps=False) assert event_serialized['type'] == 'dummy.event' assert event_serialized['uuid'] is not None assert event_serialized['timestamp'] is not None assert event_serialized['data']['attr1'] == 'test' def test_from_instance_nested_event(self): class DummyEvent(Event): event_type = 'dummy.event' attributes = ( Attribute('attr1'), Attribute('attr2.attr3'), Attribute('attr2.attr4', is_required=False), ) class DummyObject(object): class NestedObject(object): attr3 = 'test2' attr1 = 'test' attr2 = NestedObject() obj = DummyObject() event = DummyEvent.from_instance(obj) event_serialized = event.serialize(dumps=False) assert event_serialized['type'] == 'dummy.event' assert event_serialized['uuid'] is not None assert event_serialized['timestamp'] is not None assert event_serialized['data']['attr1'] == 'test' assert event_serialized['data']['attr2.attr3'] == 'test2' assert event_serialized['data']['attr2.attr4'] is None def test_actor(self): class DummyEvent1(Event): event_type = 'dummy.event' actor = True attributes = ( Attribute('attr1'), ) class DummyEvent2(Event): event_type = 'dummy.event' actor = True actor_id = 'some_actor_id' actor_name = 'some_actor_name' attributes = ( Attribute('attr1'), ) class DummyObject1(object): attr1 = 'test' class DummyObject2(object): attr1 = 'test' some_actor_id = 1 some_actor_name = 'foo' # Not providing actor_id raises obj = DummyObject1() with self.assertRaises(ValueError): DummyEvent1.from_instance(obj) # Providing actor_id and not actor_name raises with self.assertRaises(ValueError): DummyEvent1.from_instance(obj, actor_id=1) # Providing system actor id without actor_name does not raise event = DummyEvent1.from_instance(obj, actor_id=user_system.USER_SYSTEM_ID) assert event.data['actor_id'] == user_system.USER_SYSTEM_ID assert event.data['actor_name'] == user_system.USER_SYSTEM_NAME # Providing actor_id and actor_name does not raise event = DummyEvent1.from_instance(obj, actor_id=1, actor_name='foo') assert event.data['actor_id'] == 1 assert event.data['actor_name'] == 'foo' # Using an instance that has the actor properties obj2 = DummyObject2() event = DummyEvent2.from_instance(obj2) assert event.data['some_actor_id'] == 1 assert event.data['some_actor_name'] == 'foo' # Using an instance that has the actor properties and overriding the actor event = DummyEvent2.from_instance(obj2, some_actor_id=user_system.USER_SYSTEM_ID, some_actor_name=user_system.USER_SYSTEM_NAME) assert event.data['some_actor_id'] == user_system.USER_SYSTEM_ID assert event.data['some_actor_name'] == user_system.USER_SYSTEM_NAME
import argparse import warnings import matplotlib.pyplot as plt import numpy as np from libs.svm import SVM from dataset.utils import DatasetLoader, DatasetUtils from libs.plot import Plotter ### warnings.filterwarnings("ignore") np.random.seed(666) datasets = [ DatasetLoader.linear(), DatasetLoader.non_linear1(), DatasetLoader.non_linear2(), DatasetLoader.non_linear3(), DatasetLoader.non_linear4(), DatasetLoader.random() ] ### def __accuracy(Y, Y_predicted): return Y[Y == Y_predicted].shape[0] / Y.shape[0] def __analyze_svm(fig, axs, config, dataset): ### Dataset X, Y = dataset X_train, X_test, Y_train, Y_test = DatasetUtils.split(X, Y) ### Training svm = SVM(kernel=config['kernel'], deg=config['deg'], C=config['C']) svm.fit(X_train, Y_train) Y_train_predicted = svm.predict(X_train) train_accuracy = __accuracy(Y_train, Y_train_predicted) ### Testing Y_test_predicted = svm.predict(X_test) test_accuracy = __accuracy(Y_test, Y_test_predicted) ### Stats print() print(" > {}: correct predictions".format(config['title'])) print(" > - training-set = {:.1%}".format(train_accuracy)) print(" > - testing-set = {:.1%}".format(test_accuracy)) ### Plot Plotter.advanced(fig, axs, X_train, Y_train, X_test, Y_test, svm) def main(dataset_index=None): if dataset_index is None: dataset_index = 1 dataset = datasets[dataset_index] fig, axs = plt.subplots(2, 2) ### Linear (hard) title = 'Linear (hard)' axs[0, 0].set_title(title) __analyze_svm( fig, axs[0, 0], { 'title': title, 'kernel': 'linear', 'C': None, 'deg': None }, dataset ) ### Linear (soft) title = 'Linear (soft, C=.5)' axs[0, 1].set_title(title) __analyze_svm( fig, axs[0, 1], { 'title': title, 'kernel': 'linear', 'C': .5, 'deg': None }, dataset ) ### Poly (soft) title = 'Poly-3 (soft, C=.5)' axs[1, 0].set_title(title) __analyze_svm(fig, axs[1, 0], {'title': title, 'kernel': 'poly', 'C': .5, 'deg': 3}, dataset) ### Poly (soft) title = 'Poly-5 (hard)' axs[1, 1].set_title(title) __analyze_svm(fig, axs[1, 1], {'title': title, 'kernel': 'poly', 'C': None, 'deg': 5}, dataset) ### plt.axis("tight") plt.show() ### if __name__ == "__main__": parser = argparse.ArgumentParser(description="Matteo Conti - SVM") parser.add_argument( "--dataset", help="dataset index to use.", choices=['1', '2', '3', '4', '5', '6'], # default=1, required=True ) args = parser.parse_args() print() print(args) main(dataset_index=int(args.dataset) - 1) print()
/* home.js文件专门用于处理 home首页的数据请求。 */ import { request } from './request' // 首页的某一个请求 export function getHomeMultidata() { return request({ url: '/home/multidata' }) } export function getHomeGoods(type, page,) { return request({ url: '/home/data', params: { type, page } }) }
//! moment.js ; (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.moment = factory() }(this, (function () { 'use strict'; var hookCallback; function hooks() { return hookCallback.apply(null, arguments); } // This is done to register the method called with moment() // without creating circular dependencies. function setHookCallback(callback) { hookCallback = callback; } function isArray(input) { return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; } function isObject(input) { // IE8 will treat undefined and null as object if it wasn't for // input != null return input != null && Object.prototype.toString.call(input) === '[object Object]'; } function isObjectEmpty(obj) { if (Object.getOwnPropertyNames) { return (Object.getOwnPropertyNames(obj).length === 0); } else { var k; for (k in obj) { if (obj.hasOwnProperty(k)) { return false; } } return true; } } function isUndefined(input) { return input === void 0; } function isNumber(input) { return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]'; } function isDate(input) { return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function hasOwnProp(a, b) { return Object.prototype.hasOwnProperty.call(a, b); } function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function createUTC(input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, true).utc(); } function defaultParsingFlags() { // We need to deep clone this object. return { empty: false, unusedTokens: [], unusedInput: [], overflow: -2, charsLeftOver: 0, nullInput: false, invalidMonth: null, invalidFormat: false, userInvalidated: false, iso: false, parsedDateParts: [], meridiem: null, rfc2822: false, weekdayMismatch: false }; } function getParsingFlags(m) { if (m._pf == null) { m._pf = defaultParsingFlags(); } return m._pf; } var some; if (Array.prototype.some) { some = Array.prototype.some; } else { some = function (fun) { var t = Object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(this, t[i], i, t)) { return true; } } return false; }; } function isValid(m) { if (m._isValid == null) { var flags = getParsingFlags(m); var parsedParts = some.call(flags.parsedDateParts, function (i) { return i != null; }); var isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || (flags.meridiem && parsedParts)); if (m._strict) { isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined; } if (Object.isFrozen == null || !Object.isFrozen(m)) { m._isValid = isNowValid; } else { return isNowValid; } } return m._isValid; } function createInvalid(flags) { var m = createUTC(NaN); if (flags != null) { extend(getParsingFlags(m), flags); } else { getParsingFlags(m).userInvalidated = true; } return m; } // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. var momentProperties = hooks.momentProperties = []; function copyConfig(to, from) { var i, prop, val; if (!isUndefined(from._isAMomentObject)) { to._isAMomentObject = from._isAMomentObject; } if (!isUndefined(from._i)) { to._i = from._i; } if (!isUndefined(from._f)) { to._f = from._f; } if (!isUndefined(from._l)) { to._l = from._l; } if (!isUndefined(from._strict)) { to._strict = from._strict; } if (!isUndefined(from._tzm)) { to._tzm = from._tzm; } if (!isUndefined(from._isUTC)) { to._isUTC = from._isUTC; } if (!isUndefined(from._offset)) { to._offset = from._offset; } if (!isUndefined(from._pf)) { to._pf = getParsingFlags(from); } if (!isUndefined(from._locale)) { to._locale = from._locale; } if (momentProperties.length > 0) { for (i = 0; i < momentProperties.length; i++) { prop = momentProperties[i]; val = from[prop]; if (!isUndefined(val)) { to[prop] = val; } } } return to; } var updateInProgress = false; // Moment prototype object function Moment(config) { copyConfig(this, config); this._d = new Date(config._d != null ? config._d.getTime() : NaN); if (!this.isValid()) { this._d = new Date(NaN); } // Prevent infinite loop in case updateOffset creates new moment // objects. if (updateInProgress === false) { updateInProgress = true; hooks.updateOffset(this); updateInProgress = false; } } function isMoment(obj) { return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); } function absFloor(number) { if (number < 0) { // -0 -> 0 return Math.ceil(number) || 0; } else { return Math.floor(number); } } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { value = absFloor(coercedNumber); } return value; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function warn(msg) { if (hooks.suppressDeprecationWarnings === false && (typeof console !== 'undefined') && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(null, msg); } if (firstTime) { var args = []; var arg; for (var i = 0; i < arguments.length; i++) { arg = ''; if (typeof arguments[i] === 'object') { arg += '\n[' + i + '] '; for (var key in arguments[0]) { arg += key + ': ' + arguments[0][key] + ', '; } arg = arg.slice(0, -2); // Remove trailing comma and space } else { arg = arguments[i]; } args.push(arg); } warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); firstTime = false; } return fn.apply(this, arguments); }, fn); } var deprecations = {}; function deprecateSimple(name, msg) { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(name, msg); } if (!deprecations[name]) { warn(msg); deprecations[name] = true; } } hooks.suppressDeprecationWarnings = false; hooks.deprecationHandler = null; function isFunction(input) { return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; } function set(config) { var prop, i; for (i in config) { prop = config[i]; if (isFunction(prop)) { this[i] = prop; } else { this['_' + i] = prop; } } this._config = config; // Lenient ordinal parsing accepts just a number in addition to // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. // TODO: Remove "ordinalParse" fallback in next major release. this._dayOfMonthOrdinalParseLenient = new RegExp( (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + (/\d{1,2}/).source); } function mergeConfigs(parentConfig, childConfig) { var res = extend({}, parentConfig), prop; for (prop in childConfig) { if (hasOwnProp(childConfig, prop)) { if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { res[prop] = {}; extend(res[prop], parentConfig[prop]); extend(res[prop], childConfig[prop]); } else if (childConfig[prop] != null) { res[prop] = childConfig[prop]; } else { delete res[prop]; } } } for (prop in parentConfig) { if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) { // make sure changes to properties don't modify parent config res[prop] = extend({}, res[prop]); } } return res; } function Locale(config) { if (config != null) { this.set(config); } } var keys; if (Object.keys) { keys = Object.keys; } else { keys = function (obj) { var i, res = []; for (i in obj) { if (hasOwnProp(obj, i)) { res.push(i); } } return res; }; } var defaultCalendar = { sameDay: '[Today at] LT', nextDay: '[Tomorrow at] LT', nextWeek: 'dddd [at] LT', lastDay: '[Yesterday at] LT', lastWeek: '[Last] dddd [at] LT', sameElse: 'L' }; function calendar(key, mom, now) { var output = this._calendar[key] || this._calendar['sameElse']; return isFunction(output) ? output.call(mom, now) : output; } var defaultLongDateFormat = { LTS: 'h:mm:ss A', LT: 'h:mm A', L: 'MM/DD/YYYY', LL: 'MMMM D, YYYY', LLL: 'MMMM D, YYYY h:mm A', LLLL: 'dddd, MMMM D, YYYY h:mm A' }; function longDateFormat(key) { var format = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; if (format || !formatUpper) { return format; } this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); return this._longDateFormat[key]; } var defaultInvalidDate = 'Invalid date'; function invalidDate() { return this._invalidDate; } var defaultOrdinal = '%d'; var defaultDayOfMonthOrdinalParse = /\d{1,2}/; function ordinal(number) { return this._ordinal.replace('%d', number); } var defaultRelativeTime = { future: 'in %s', past: '%s ago', s: 'a few seconds', ss: '%d seconds', m: 'a minute', mm: '%d minutes', h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days', M: 'a month', MM: '%d months', y: 'a year', yy: '%d years' }; function relativeTime(number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (isFunction(output)) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); } function pastFuture(diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return isFunction(format) ? format(output) : format.replace(/%s/i, output); } var aliases = {}; function addUnitAlias(unit, shorthand) { var lowerCase = unit.toLowerCase(); aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; } function normalizeUnits(units) { return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } var priorities = {}; function addUnitPriority(unit, priority) { priorities[unit] = priority; } function getPrioritizedUnits(unitsObj) { var units = []; for (var u in unitsObj) { units.push({ unit: u, priority: priorities[u] }); } units.sort(function (a, b) { return a.priority - b.priority; }); return units; } function zeroFill(number, targetLength, forceSign) { var absNumber = '' + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign = number >= 0; return (sign ? (forceSign ? '+' : '') : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; } var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; var formatFunctions = {}; var formatTokenFunctions = {}; // token: 'M' // padded: ['MM', 2] // ordinal: 'Mo' // callback: function () { this.month() + 1 } function addFormatToken(token, padded, ordinal, callback) { var func = callback; if (typeof callback === 'string') { func = function () { return this[callback](); }; } if (token) { formatTokenFunctions[token] = func; } if (padded) { formatTokenFunctions[padded[0]] = function () { return zeroFill(func.apply(this, arguments), padded[1], padded[2]); }; } if (ordinal) { formatTokenFunctions[ordinal] = function () { return this.localeData().ordinal(func.apply(this, arguments), token); }; } } function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = '', i; for (i = 0; i < length; i++) { output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } var match1 = /\d/; // 0 - 9 var match2 = /\d\d/; // 00 - 99 var match3 = /\d{3}/; // 000 - 999 var match4 = /\d{4}/; // 0000 - 9999 var match6 = /[+-]?\d{6}/; // -999999 - 999999 var match1to2 = /\d\d?/; // 0 - 99 var match3to4 = /\d\d\d\d?/; // 999 - 9999 var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 var match1to3 = /\d{1,3}/; // 0 - 999 var match1to4 = /\d{1,4}/; // 0 - 9999 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 var matchUnsigned = /\d+/; // 0 - inf var matchSigned = /[+-]?\d+/; // -inf - inf var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 // any word (or two) characters or numbers including two/three word month in arabic. // includes scottish gaelic two word and hyphenated months var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i; var regexes = {}; function addRegexToken(token, regex, strictRegex) { regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { return (isStrict && strictRegex) ? strictRegex : regex; }; } function getParseRegexForToken(token, config) { if (!hasOwnProp(regexes, token)) { return new RegExp(unescapeFormat(token)); } return regexes[token](config._strict, config._locale); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function unescapeFormat(s) { return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; })); } function regexEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } var tokens = {}; function addParseToken(token, callback) { var i, func = callback; if (typeof token === 'string') { token = [token]; } if (isNumber(callback)) { func = function (input, array) { array[callback] = toInt(input); }; } for (i = 0; i < token.length; i++) { tokens[token[i]] = func; } } function addWeekParseToken(token, callback) { addParseToken(token, function (input, array, config, token) { config._w = config._w || {}; callback(input, config._w, config, token); }); } function addTimeToArrayFromToken(token, input, config) { if (input != null && hasOwnProp(tokens, token)) { tokens[token](input, config._a, config, token); } } var YEAR = 0; var MONTH = 1; var DATE = 2; var HOUR = 3; var MINUTE = 4; var SECOND = 5; var MILLISECOND = 6; var WEEK = 7; var WEEKDAY = 8; // FORMATTING addFormatToken('Y', 0, 0, function () { var y = this.year(); return y <= 9999 ? '' + y : '+' + y; }); addFormatToken(0, ['YY', 2], 0, function () { return this.year() % 100; }); addFormatToken(0, ['YYYY', 4], 0, 'year'); addFormatToken(0, ['YYYYY', 5], 0, 'year'); addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES addUnitAlias('year', 'y'); // PRIORITIES addUnitPriority('year', 1); // PARSING addRegexToken('Y', matchSigned); addRegexToken('YY', match1to2, match2); addRegexToken('YYYY', match1to4, match4); addRegexToken('YYYYY', match1to6, match6); addRegexToken('YYYYYY', match1to6, match6); addParseToken(['YYYYY', 'YYYYYY'], YEAR); addParseToken('YYYY', function (input, array) { array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); }); addParseToken('YY', function (input, array) { array[YEAR] = hooks.parseTwoDigitYear(input); }); addParseToken('Y', function (input, array) { array[YEAR] = parseInt(input, 10); }); // HELPERS function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } // HOOKS hooks.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; // MOMENTS var getSetYear = makeGetSet('FullYear', true); function getIsLeapYear() { return isLeapYear(this.year()); } function makeGetSet(unit, keepTime) { return function (value) { if (value != null) { set$1(this, unit, value); hooks.updateOffset(this, keepTime); return this; } else { return get(this, unit); } }; } function get(mom, unit) { return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; } function set$1(mom, unit, value) { if (mom.isValid() && !isNaN(value)) { if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) { mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month())); } else { mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } } // MOMENTS function stringGet(units) { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](); } return this; } function stringSet(units, value) { if (typeof units === 'object') { units = normalizeObjectUnits(units); var prioritized = getPrioritizedUnits(units); for (var i = 0; i < prioritized.length; i++) { this[prioritized[i].unit](units[prioritized[i].unit]); } } else { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](value); } } return this; } function mod(n, x) { return ((n % x) + x) % x; } var indexOf; if (Array.prototype.indexOf) { indexOf = Array.prototype.indexOf; } else { indexOf = function (o) { // I know var i; for (i = 0; i < this.length; ++i) { if (this[i] === o) { return i; } } return -1; }; } function daysInMonth(year, month) { if (isNaN(year) || isNaN(month)) { return NaN; } var modMonth = mod(month, 12); year += (month - modMonth) / 12; return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2); } // FORMATTING addFormatToken('M', ['MM', 2], 'Mo', function () { return this.month() + 1; }); addFormatToken('MMM', 0, 0, function (format) { return this.localeData().monthsShort(this, format); }); addFormatToken('MMMM', 0, 0, function (format) { return this.localeData().months(this, format); }); // ALIASES addUnitAlias('month', 'M'); // PRIORITY addUnitPriority('month', 8); // PARSING addRegexToken('M', match1to2); addRegexToken('MM', match1to2, match2); addRegexToken('MMM', function (isStrict, locale) { return locale.monthsShortRegex(isStrict); }); addRegexToken('MMMM', function (isStrict, locale) { return locale.monthsRegex(isStrict); }); addParseToken(['M', 'MM'], function (input, array) { array[MONTH] = toInt(input) - 1; }); addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid. if (month != null) { array[MONTH] = month; } else { getParsingFlags(config).invalidMonth = input; } }); // LOCALES var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); function localeMonths(m, format) { if (!m) { return isArray(this._months) ? this._months : this._months['standalone']; } return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; } var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); function localeMonthsShort(m, format) { if (!m) { return isArray(this._monthsShort) ? this._monthsShort : this._monthsShort['standalone']; } return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; } function handleStrictParse(monthName, format, strict) { var i, ii, mom, llc = monthName.toLocaleLowerCase(); if (!this._monthsParse) { // this is not used this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; for (i = 0; i < 12; ++i) { mom = createUTC([2000, i]); this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } } } function localeMonthsParse(monthName, format, strict) { var i, mom, regex; if (this._monthsParseExact) { return handleStrictParse.call(this, monthName, format, strict); } if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } // TODO: add sorting // Sorting makes sure if one month (or abbr) is a prefix of another // see sorting in computeMonthsParse for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = createUTC([2000, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); } if (!strict && !this._monthsParse[i]) { regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { return i; } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } } // MOMENTS function setMonth(mom, value) { var dayOfMonth; if (!mom.isValid()) { // No op return mom; } if (typeof value === 'string') { if (/^\d+$/.test(value)) { value = toInt(value); } else { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (!isNumber(value)) { return mom; } } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function getSetMonth(value) { if (value != null) { setMonth(this, value); hooks.updateOffset(this, true); return this; } else { return get(this, 'Month'); } } function getDaysInMonth() { return daysInMonth(this.year(), this.month()); } var defaultMonthsShortRegex = matchWord; function monthsShortRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsShortStrictRegex; } else { return this._monthsShortRegex; } } else { if (!hasOwnProp(this, '_monthsShortRegex')) { this._monthsShortRegex = defaultMonthsShortRegex; } return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; } } var defaultMonthsRegex = matchWord; function monthsRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsStrictRegex; } else { return this._monthsRegex; } } else { if (!hasOwnProp(this, '_monthsRegex')) { this._monthsRegex = defaultMonthsRegex; } return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; } } function computeMonthsParse() { function cmpLenRev(a, b) { return b.length - a.length; } var shortPieces = [], longPieces = [], mixedPieces = [], i, mom; for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = createUTC([2000, i]); shortPieces.push(this.monthsShort(mom, '')); longPieces.push(this.months(mom, '')); mixedPieces.push(this.months(mom, '')); mixedPieces.push(this.monthsShort(mom, '')); } // Sorting makes sure if one month (or abbr) is a prefix of another it // will match the longer piece. shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 12; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); } for (i = 0; i < 24; i++) { mixedPieces[i] = regexEscape(mixedPieces[i]); } this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._monthsShortRegex = this._monthsRegex; this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); } function createDate(y, m, d, h, M, s, ms) { // can't just apply() to create a date: // https://stackoverflow.com/q/181348 var date; // the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { // preserve leap years using a full 400 year cycle, then reset date = new Date(y + 400, m, d, h, M, s, ms); if (isFinite(date.getFullYear())) { date.setFullYear(y); } } else { date = new Date(y, m, d, h, M, s, ms); } return date; } function createUTCDate(y) { var date; // the Date.UTC function remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { var args = Array.prototype.slice.call(arguments); // preserve leap years using a full 400 year cycle, then reset args[0] = y + 400; date = new Date(Date.UTC.apply(null, args)); if (isFinite(date.getUTCFullYear())) { date.setUTCFullYear(y); } } else { date = new Date(Date.UTC.apply(null, arguments)); } return date; } // start-of-first-week - start-of-year function firstWeekOffset(year, dow, doy) { var // first-week day -- which january is always in the first week (4 for iso, 1 for other) fwd = 7 + dow - doy, // first-week day local weekday -- which local weekday is fwd fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; return -fwdlw + fwd - 1; } // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, dow, doy) { var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; if (dayOfYear <= 0) { resYear = year - 1; resDayOfYear = daysInYear(resYear) + dayOfYear; } else if (dayOfYear > daysInYear(year)) { resYear = year + 1; resDayOfYear = dayOfYear - daysInYear(year); } else { resYear = year; resDayOfYear = dayOfYear; } return { year: resYear, dayOfYear: resDayOfYear }; } function weekOfYear(mom, dow, doy) { var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; if (week < 1) { resYear = mom.year() - 1; resWeek = week + weeksInYear(resYear, dow, doy); } else if (week > weeksInYear(mom.year(), dow, doy)) { resWeek = week - weeksInYear(mom.year(), dow, doy); resYear = mom.year() + 1; } else { resYear = mom.year(); resWeek = week; } return { week: resWeek, year: resYear }; } function weeksInYear(year, dow, doy) { var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; } // FORMATTING addFormatToken('w', ['ww', 2], 'wo', 'week'); addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES addUnitAlias('week', 'w'); addUnitAlias('isoWeek', 'W'); // PRIORITIES addUnitPriority('week', 5); addUnitPriority('isoWeek', 5); // PARSING addRegexToken('w', match1to2); addRegexToken('ww', match1to2, match2); addRegexToken('W', match1to2); addRegexToken('WW', match1to2, match2); addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { week[token.substr(0, 1)] = toInt(input); }); // HELPERS // LOCALES function localeWeek(mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; } var defaultLocaleWeek = { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 6th is the first week of the year. }; function localeFirstDayOfWeek() { return this._week.dow; } function localeFirstDayOfYear() { return this._week.doy; } // MOMENTS function getSetWeek(input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); } function getSetISOWeek(input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); } // FORMATTING addFormatToken('d', 0, 'do', 'day'); addFormatToken('dd', 0, 0, function (format) { return this.localeData().weekdaysMin(this, format); }); addFormatToken('ddd', 0, 0, function (format) { return this.localeData().weekdaysShort(this, format); }); addFormatToken('dddd', 0, 0, function (format) { return this.localeData().weekdays(this, format); }); addFormatToken('e', 0, 0, 'weekday'); addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES addUnitAlias('day', 'd'); addUnitAlias('weekday', 'e'); addUnitAlias('isoWeekday', 'E'); // PRIORITY addUnitPriority('day', 11); addUnitPriority('weekday', 11); addUnitPriority('isoWeekday', 11); // PARSING addRegexToken('d', match1to2); addRegexToken('e', match1to2); addRegexToken('E', match1to2); addRegexToken('dd', function (isStrict, locale) { return locale.weekdaysMinRegex(isStrict); }); addRegexToken('ddd', function (isStrict, locale) { return locale.weekdaysShortRegex(isStrict); }); addRegexToken('dddd', function (isStrict, locale) { return locale.weekdaysRegex(isStrict); }); addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { week.d = weekday; } else { getParsingFlags(config).invalidWeekday = input; } }); addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { if (typeof input !== 'string') { return input; } if (!isNaN(input)) { return parseInt(input, 10); } input = locale.weekdaysParse(input); if (typeof input === 'number') { return input; } return null; } function parseIsoWeekday(input, locale) { if (typeof input === 'string') { return locale.weekdaysParse(input) % 7 || 7; } return isNaN(input) ? null : input; } // LOCALES function shiftWeekdays(ws, n) { return ws.slice(n, 7).concat(ws.slice(0, n)); } var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); function localeWeekdays(m, format) { var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone']; return (m === true) ? shiftWeekdays(weekdays, this._week.dow) : (m) ? weekdays[m.day()] : weekdays; } var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); function localeWeekdaysShort(m) { return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow) : (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; } var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); function localeWeekdaysMin(m) { return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow) : (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; } function handleStrictParse$1(weekdayName, format, strict) { var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); if (!this._weekdaysParse) { this._weekdaysParse = []; this._shortWeekdaysParse = []; this._minWeekdaysParse = []; for (i = 0; i < 7; ++i) { mom = createUTC([2000, 1]).day(i); this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } } } function localeWeekdaysParse(weekdayName, format, strict) { var i, mom, regex; if (this._weekdaysParseExact) { return handleStrictParse$1.call(this, weekdayName, format, strict); } if (!this._weekdaysParse) { this._weekdaysParse = []; this._minWeekdaysParse = []; this._shortWeekdaysParse = []; this._fullWeekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); if (strict && !this._fullWeekdaysParse[i]) { this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i'); this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i'); this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i'); } if (!this._weekdaysParse[i]) { regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { return i; } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { return i; } } } // MOMENTS function getSetDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } } function getSetLocaleDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); } function getSetISODayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. if (input != null) { var weekday = parseIsoWeekday(input, this.localeData()); return this.day(this.day() % 7 ? weekday : weekday - 7); } else { return this.day() || 7; } } var defaultWeekdaysRegex = matchWord; function weekdaysRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysStrictRegex; } else { return this._weekdaysRegex; } } else { if (!hasOwnProp(this, '_weekdaysRegex')) { this._weekdaysRegex = defaultWeekdaysRegex; } return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } } var defaultWeekdaysShortRegex = matchWord; function weekdaysShortRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysShortStrictRegex; } else { return this._weekdaysShortRegex; } } else { if (!hasOwnProp(this, '_weekdaysShortRegex')) { this._weekdaysShortRegex = defaultWeekdaysShortRegex; } return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } } var defaultWeekdaysMinRegex = matchWord; function weekdaysMinRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysMinStrictRegex; } else { return this._weekdaysMinRegex; } } else { if (!hasOwnProp(this, '_weekdaysMinRegex')) { this._weekdaysMinRegex = defaultWeekdaysMinRegex; } return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } } function computeWeekdaysParse() { function cmpLenRev(a, b) { return b.length - a.length; } var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); minp = this.weekdaysMin(mom, ''); shortp = this.weekdaysShort(mom, ''); longp = this.weekdays(mom, ''); minPieces.push(minp); shortPieces.push(shortp); longPieces.push(longp); mixedPieces.push(minp); mixedPieces.push(shortp); mixedPieces.push(longp); } // Sorting makes sure if one weekday (or abbr) is a prefix of another it // will match the longer piece. minPieces.sort(cmpLenRev); shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 7; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); mixedPieces[i] = regexEscape(mixedPieces[i]); } this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._weekdaysShortRegex = this._weekdaysRegex; this._weekdaysMinRegex = this._weekdaysRegex; this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); } // FORMATTING function hFormat() { return this.hours() % 12 || 12; } function kFormat() { return this.hours() || 24; } addFormatToken('H', ['HH', 2], 0, 'hour'); addFormatToken('h', ['hh', 2], 0, hFormat); addFormatToken('k', ['kk', 2], 0, kFormat); addFormatToken('hmm', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); }); addFormatToken('hmmss', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); addFormatToken('Hmm', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2); }); addFormatToken('Hmmss', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); function meridiem(token, lowercase) { addFormatToken(token, 0, 0, function () { return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); }); } meridiem('a', true); meridiem('A', false); // ALIASES addUnitAlias('hour', 'h'); // PRIORITY addUnitPriority('hour', 13); // PARSING function matchMeridiem(isStrict, locale) { return locale._meridiemParse; } addRegexToken('a', matchMeridiem); addRegexToken('A', matchMeridiem); addRegexToken('H', match1to2); addRegexToken('h', match1to2); addRegexToken('k', match1to2); addRegexToken('HH', match1to2, match2); addRegexToken('hh', match1to2, match2); addRegexToken('kk', match1to2, match2); addRegexToken('hmm', match3to4); addRegexToken('hmmss', match5to6); addRegexToken('Hmm', match3to4); addRegexToken('Hmmss', match5to6); addParseToken(['H', 'HH'], HOUR); addParseToken(['k', 'kk'], function (input, array, config) { var kInput = toInt(input); array[HOUR] = kInput === 24 ? 0 : kInput; }); addParseToken(['a', 'A'], function (input, array, config) { config._isPm = config._locale.isPM(input); config._meridiem = input; }); addParseToken(['h', 'hh'], function (input, array, config) { array[HOUR] = toInt(input); getParsingFlags(config).bigHour = true; }); addParseToken('hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); getParsingFlags(config).bigHour = true; }); addParseToken('hmmss', function (input, array, config) { var pos1 = input.length - 4; var pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); getParsingFlags(config).bigHour = true; }); addParseToken('Hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); }); addParseToken('Hmmss', function (input, array, config) { var pos1 = input.length - 4; var pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); }); // LOCALES function localeIsPM(input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); } var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; function localeMeridiem(hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } } // MOMENTS // Setting the hour should keep the time, because the user explicitly // specified which hour they want. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. var getSetHour = makeGetSet('Hours', true); var baseConfig = { calendar: defaultCalendar, longDateFormat: defaultLongDateFormat, invalidDate: defaultInvalidDate, ordinal: defaultOrdinal, dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, relativeTime: defaultRelativeTime, months: defaultLocaleMonths, monthsShort: defaultLocaleMonthsShort, week: defaultLocaleWeek, weekdays: defaultLocaleWeekdays, weekdaysMin: defaultLocaleWeekdaysMin, weekdaysShort: defaultLocaleWeekdaysShort, meridiemParse: defaultLocaleMeridiemParse }; // internal storage for locale config files var locales = {}; var localeFamilies = {}; var globalLocale; function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return globalLocale; } function loadLocale(name) { var oldLocale = null; // TODO: Find a better way to register and load all the locales in Node if (!locales[name] && (typeof module !== 'undefined') && module && module.exports) { try { oldLocale = globalLocale._abbr; var aliasedRequire = require; aliasedRequire('./locale/' + name); getSetGlobalLocale(oldLocale); } catch (e) {} } return locales[name]; } // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. function getSetGlobalLocale(key, values) { var data; if (key) { if (isUndefined(values)) { data = getLocale(key); } else { data = defineLocale(key, values); } if (data) { // moment.duration._locale = moment._locale = data; globalLocale = data; } else { if ((typeof console !== 'undefined') && console.warn) { //warn user if arguments are passed but the locale could not be set console.warn('Locale ' + key + ' not found. Did you forget to load it?'); } } } return globalLocale._abbr; } function defineLocale(name, config) { if (config !== null) { var locale, parentConfig = baseConfig; config.abbr = name; if (locales[name] != null) { deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); parentConfig = locales[name]._config; } else if (config.parentLocale != null) { if (locales[config.parentLocale] != null) { parentConfig = locales[config.parentLocale]._config; } else { locale = loadLocale(config.parentLocale); if (locale != null) { parentConfig = locale._config; } else { if (!localeFamilies[config.parentLocale]) { localeFamilies[config.parentLocale] = []; } localeFamilies[config.parentLocale].push({ name: name, config: config }); return null; } } } locales[name] = new Locale(mergeConfigs(parentConfig, config)); if (localeFamilies[name]) { localeFamilies[name].forEach(function (x) { defineLocale(x.name, x.config); }); } // backwards compat for now: also set the locale // make sure we set the locale AFTER all child locales have been // created, so we won't end up with the child locale set. getSetGlobalLocale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } } function updateLocale(name, config) { if (config != null) { var locale, tmpLocale, parentConfig = baseConfig; // MERGE tmpLocale = loadLocale(name); if (tmpLocale != null) { parentConfig = tmpLocale._config; } config = mergeConfigs(parentConfig, config); locale = new Locale(config); locale.parentLocale = locales[name]; locales[name] = locale; // backwards compat for now: also set the locale getSetGlobalLocale(name); } else { // pass null for config to unupdate, useful for tests if (locales[name] != null) { if (locales[name].parentLocale != null) { locales[name] = locales[name].parentLocale; } else if (locales[name] != null) { delete locales[name]; } } } return locales[name]; } // returns locale data function getLocale(key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); } function listLocales() { return keys(locales); } function checkOverflow(m) { var overflow; var a = m._a; if (a && getParsingFlags(m).overflow === -2) { overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } if (getParsingFlags(m)._overflowWeeks && overflow === -1) { overflow = WEEK; } if (getParsingFlags(m)._overflowWeekday && overflow === -1) { overflow = WEEKDAY; } getParsingFlags(m).overflow = overflow; } return m; } // Pick the first defined of two or three arguments. function defaults(a, b, c) { if (a != null) { return a; } if (b != null) { return b; } return c; } function currentDateArray(config) { // hooks is actually the exported moment object var nowValue = new Date(hooks.now()); if (config._useUTC) { return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; } return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function configFromArray(config) { var i, date, input = [], currentDate, expectedWeekday, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear != null) { yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { getParsingFlags(config)._overflowDayOfYear = true; } date = createUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // Check for 24:00:00.000 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); // Apply timezone offset from input. The actual utcOffset can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } // check for mismatching day of week if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) { getParsingFlags(config).weekdayMismatch = true; } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); week = defaults(w.W, 1); weekday = defaults(w.E, 1); if (weekday < 1 || weekday > 7) { weekdayOverflow = true; } } else { dow = config._locale._week.dow; doy = config._locale._week.doy; var curWeek = weekOfYear(createLocal(), dow, doy); weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); // Default to current week. week = defaults(w.w, curWeek.week); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < 0 || weekday > 6) { weekdayOverflow = true; } } else if (w.e != null) { // local weekday -- counting starts from beginning of week weekday = w.e + dow; if (w.e < 0 || w.e > 6) { weekdayOverflow = true; } } else { // default to beginning of week weekday = dow; } } if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { getParsingFlags(config)._overflowWeeks = true; } else if (weekdayOverflow != null) { getParsingFlags(config)._overflowWeekday = true; } else { temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } } // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; var isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], // YYYYMM is NOT allowed by the standard ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/] ]; // iso time formats and regexes var isoTimes = [ ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/] ]; var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; // date from iso format function configFromISO(config) { var i, l, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat; if (match) { getParsingFlags(config).iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(match[1])) { dateFormat = isoDates[i][0]; allowTime = isoDates[i][2] !== false; break; } } if (dateFormat == null) { config._isValid = false; return; } if (match[3]) { for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(match[3])) { // match[2] should be 'T' or space timeFormat = (match[2] || ' ') + isoTimes[i][0]; break; } } if (timeFormat == null) { config._isValid = false; return; } } if (!allowTime && timeFormat != null) { config._isValid = false; return; } if (match[4]) { if (tzRegex.exec(match[4])) { tzFormat = 'Z'; } else { config._isValid = false; return; } } config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); configFromStringAndFormat(config); } else { config._isValid = false; } } // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { var result = [ untruncateYear(yearStr), defaultLocaleMonthsShort.indexOf(monthStr), parseInt(dayStr, 10), parseInt(hourStr, 10), parseInt(minuteStr, 10) ]; if (secondStr) { result.push(parseInt(secondStr, 10)); } return result; } function untruncateYear(yearStr) { var year = parseInt(yearStr, 10); if (year <= 49) { return 2000 + year; } else if (year <= 999) { return 1900 + year; } return year; } function preprocessRFC2822(s) { // Remove comments and folding whitespace and replace multiple-spaces with a single space return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } function checkWeekday(weekdayStr, parsedInput, config) { if (weekdayStr) { // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay(); if (weekdayProvided !== weekdayActual) { getParsingFlags(config).weekdayMismatch = true; config._isValid = false; return false; } } return true; } var obsOffsets = { UT: 0, GMT: 0, EDT: -4 * 60, EST: -5 * 60, CDT: -5 * 60, CST: -6 * 60, MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, PST: -8 * 60 }; function calculateOffset(obsOffset, militaryOffset, numOffset) { if (obsOffset) { return obsOffsets[obsOffset]; } else if (militaryOffset) { // the only allowed military tz is Z return 0; } else { var hm = parseInt(numOffset, 10); var m = hm % 100, h = (hm - m) / 100; return h * 60 + m; } } // date and time from ref 2822 format function configFromRFC2822(config) { var match = rfc2822.exec(preprocessRFC2822(config._i)); if (match) { var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]); if (!checkWeekday(match[1], parsedArray, config)) { return; } config._a = parsedArray; config._tzm = calculateOffset(match[8], match[9], match[10]); config._d = createUTCDate.apply(null, config._a); config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); getParsingFlags(config).rfc2822 = true; } else { config._isValid = false; } } // date from iso format or fallback function configFromString(config) { var matched = aspNetJsonRegex.exec(config._i); if (matched !== null) { config._d = new Date(+matched[1]); return; } configFromISO(config); if (config._isValid === false) { delete config._isValid; } else { return; } configFromRFC2822(config); if (config._isValid === false) { delete config._isValid; } else { return; } // Final attempt, use Input Fallback hooks.createFromInputFallback(config); } hooks.createFromInputFallback = deprecate( 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + 'discouraged and will be removed in an upcoming major release. Please refer to ' + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) { config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); } ); // constant that refers to the ISO standard hooks.ISO_8601 = function () {}; // constant that refers to the RFC 2822 form hooks.RFC_2822 = function () {}; // date from string and format string function configFromStringAndFormat(config) { // TODO: Move this to another part of the creation flow to prevent circular deps if (config._f === hooks.ISO_8601) { configFromISO(config); return; } if (config._f === hooks.RFC_2822) { configFromRFC2822(config); return; } config._a = []; getParsingFlags(config).empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; // console.log('token', token, 'parsedInput', parsedInput, // 'regex', getParseRegexForToken(token, config)); if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { getParsingFlags(config).unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { getParsingFlags(config).empty = false; } else { getParsingFlags(config).unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { getParsingFlags(config).unusedTokens.push(token); } } // add remaining unparsed input length to the string getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { getParsingFlags(config).unusedInput.push(string); } // clear _12h flag if hour is <= 12 if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) { getParsingFlags(config).bigHour = undefined; } getParsingFlags(config).parsedDateParts = config._a.slice(0); getParsingFlags(config).meridiem = config._meridiem; // handle meridiem config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); configFromArray(config); checkOverflow(config); } function meridiemFixWrap(locale, hour, meridiem) { var isPm; if (meridiem == null) { // nothing to do return hour; } if (locale.meridiemHour != null) { return locale.meridiemHour(hour, meridiem); } else if (locale.isPM != null) { // Fallback isPm = locale.isPM(meridiem); if (isPm && hour < 12) { hour += 12; } if (!isPm && hour === 12) { hour = 0; } return hour; } else { // this is not supposed to happen return hour; } } // date from string and array of format strings function configFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { getParsingFlags(config).invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._f = config._f[i]; configFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += getParsingFlags(tempConfig).charsLeftOver; //or tokens currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; getParsingFlags(tempConfig).score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } function configFromObject(config) { if (config._d) { return; } var i = normalizeObjectUnits(config._i); config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { return obj && parseInt(obj, 10); }); configFromArray(config); } function createFromConfig(config) { var res = new Moment(checkOverflow(prepareConfig(config))); if (res._nextDay) { // Adding is smart enough around DST res.add(1, 'd'); res._nextDay = undefined; } return res; } function prepareConfig(config) { var input = config._i, format = config._f; config._locale = config._locale || getLocale(config._l); if (input === null || (format === undefined && input === '')) { return createInvalid({ nullInput: true }); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (isMoment(input)) { return new Moment(checkOverflow(input)); } else if (isDate(input)) { config._d = input; } else if (isArray(format)) { configFromStringAndArray(config); } else if (format) { configFromStringAndFormat(config); } else { configFromInput(config); } if (!isValid(config)) { config._d = null; } return config; } function configFromInput(config) { var input = config._i; if (isUndefined(input)) { config._d = new Date(hooks.now()); } else if (isDate(input)) { config._d = new Date(input.valueOf()); } else if (typeof input === 'string') { configFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); configFromArray(config); } else if (isObject(input)) { configFromObject(config); } else if (isNumber(input)) { // from milliseconds config._d = new Date(input); } else { hooks.createFromInputFallback(config); } } function createLocalOrUTC(input, format, locale, strict, isUTC) { var c = {}; if (locale === true || locale === false) { strict = locale; locale = undefined; } if ((isObject(input) && isObjectEmpty(input)) || (isArray(input) && input.length === 0)) { input = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c._isAMomentObject = true; c._useUTC = c._isUTC = isUTC; c._l = locale; c._i = input; c._f = format; c._strict = strict; return createFromConfig(c); } function createLocal(input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, false); } var prototypeMin = deprecate( 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other < this ? this : other; } else { return createInvalid(); } } ); var prototypeMax = deprecate( 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other > this ? this : other; } else { return createInvalid(); } } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return createLocal(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (!moments[i].isValid() || moments[i][fn](res)) { res = moments[i]; } } return res; } // TODO: Use [].sort instead? function min() { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); } function max() { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); } var now = function () { return Date.now ? Date.now() : +(new Date()); }; var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; function isDurationValid(m) { for (var key in m) { if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { return false; } } var unitHasDecimal = false; for (var i = 0; i < ordering.length; ++i) { if (m[ordering[i]]) { if (unitHasDecimal) { return false; // only allow non-integers for smallest unit } if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { unitHasDecimal = true; } } } return true; } function isValid$1() { return this._isValid; } function createInvalid$1() { return createDuration(NaN); } function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || normalizedInput.isoWeek || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; this._isValid = isDurationValid(normalizedInput); // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible to translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = getLocale(); this._bubble(); } function isDuration(obj) { return obj instanceof Duration; } function absRound(number) { if (number < 0) { return Math.round(-1 * number) * -1; } else { return Math.round(number); } } // FORMATTING function offset(token, separator) { addFormatToken(token, 0, 0, function () { var offset = this.utcOffset(); var sign = '+'; if (offset < 0) { offset = -offset; sign = '-'; } return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); }); } offset('Z', ':'); offset('ZZ', ''); // PARSING addRegexToken('Z', matchShortOffset); addRegexToken('ZZ', matchShortOffset); addParseToken(['Z', 'ZZ'], function (input, array, config) { config._useUTC = true; config._tzm = offsetFromString(matchShortOffset, input); }); // HELPERS // timezone chunker // '+10:00' > ['10', '00'] // '-1530' > ['-15', '30'] var chunkOffset = /([\+\-]|\d\d)/gi; function offsetFromString(matcher, string) { var matches = (string || '').match(matcher); if (matches === null) { return null; } var chunk = matches[matches.length - 1] || []; var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; var minutes = +(parts[1] * 60) + toInt(parts[2]); return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes; } // Return a moment from input, that is local/utc/zone equivalent to model. function cloneWithOffset(input, model) { var res, diff; if (model._isUTC) { res = model.clone(); diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); // Use low-level api, because this fn is low-level api. res._d.setTime(res._d.valueOf() + diff); hooks.updateOffset(res, false); return res; } else { return createLocal(input).local(); } } function getDateOffset(m) { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return -Math.round(m._d.getTimezoneOffset() / 15) * 15; } // HOOKS // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. hooks.updateOffset = function () {}; // MOMENTS // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. function getSetOffset(input, keepLocalTime, keepMinutes) { var offset = this._offset || 0, localAdjust; if (!this.isValid()) { return input != null ? this : NaN; } if (input != null) { if (typeof input === 'string') { input = offsetFromString(matchShortOffset, input); if (input === null) { return this; } } else if (Math.abs(input) < 16 && !keepMinutes) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = getDateOffset(this); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.add(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addSubtract(this, createDuration(input - offset, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; hooks.updateOffset(this, true); this._changeInProgress = null; } } return this; } else { return this._isUTC ? offset : getDateOffset(this); } } function getSetZone(input, keepLocalTime) { if (input != null) { if (typeof input !== 'string') { input = -input; } this.utcOffset(input, keepLocalTime); return this; } else { return -this.utcOffset(); } } function setOffsetToUTC(keepLocalTime) { return this.utcOffset(0, keepLocalTime); } function setOffsetToLocal(keepLocalTime) { if (this._isUTC) { this.utcOffset(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.subtract(getDateOffset(this), 'm'); } } return this; } function setOffsetToParsedOffset() { if (this._tzm != null) { this.utcOffset(this._tzm, false, true); } else if (typeof this._i === 'string') { var tZone = offsetFromString(matchOffset, this._i); if (tZone != null) { this.utcOffset(tZone); } else { this.utcOffset(0, true); } } return this; } function hasAlignedHourOffset(input) { if (!this.isValid()) { return false; } input = input ? createLocal(input).utcOffset() : 0; return (this.utcOffset() - input) % 60 === 0; } function isDaylightSavingTime() { return ( this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset() ); } function isDaylightSavingTimeShifted() { if (!isUndefined(this._isDSTShifted)) { return this._isDSTShifted; } var c = {}; copyConfig(c, this); c = prepareConfig(c); if (c._a) { var other = c._isUTC ? createUTC(c._a) : createLocal(c._a); this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; } else { this._isDSTShifted = false; } return this._isDSTShifted; } function isLocal() { return this.isValid() ? !this._isUTC : false; } function isUtcOffset() { return this.isValid() ? this._isUTC : false; } function isUtc() { return this.isValid() ? this._isUTC && this._offset === 0 : false; } // ASP.NET json date format regex var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere // and further modified to allow for strings containing both week and day var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; function createDuration(input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, diffRes; if (isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (isNumber(input)) { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match }; } else if (!!(match = isoRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: parseIso(match[2], sign), M: parseIso(match[3], sign), w: parseIso(match[4], sign), d: parseIso(match[5], sign), h: parseIso(match[6], sign), m: parseIso(match[7], sign), s: parseIso(match[8], sign) }; } else if (duration == null) { // checks for null or undefined duration = {}; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; } createDuration.fn = Duration.prototype; createDuration.invalid = createInvalid$1; function parseIso(inp, sign) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { var res = {}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; if (!(base.isValid() && other.isValid())) { return { milliseconds: 0, months: 0 }; } other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = createDuration(val, period); addSubtract(this, dur, direction); return this; }; } function addSubtract(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = absRound(duration._days), months = absRound(duration._months); if (!mom.isValid()) { // No op return; } updateOffset = updateOffset == null ? true : updateOffset; if (months) { setMonth(mom, get(mom, 'Month') + months * isAdding); } if (days) { set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); } if (milliseconds) { mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); } if (updateOffset) { hooks.updateOffset(mom, days || months); } } var add = createAdder(1, 'add'); var subtract = createAdder(-1, 'subtract'); function getCalendarFormat(myMoment, now) { var diff = myMoment.diff(now, 'days', true); return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; } function calendar$1(time, formats) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're local/utc/offset or not. var now = time || createLocal(), sod = cloneWithOffset(now, this).startOf('day'), format = hooks.calendarFormat(this, sod) || 'sameElse'; var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); return this.format(output || this.localeData().calendar(format, this, createLocal(now))); } function clone() { return new Moment(this); } function isAfter(input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() > localInput.valueOf(); } else { return localInput.valueOf() < this.clone().startOf(units).valueOf(); } } function isBefore(input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() < localInput.valueOf(); } else { return this.clone().endOf(units).valueOf() < localInput.valueOf(); } } function isBetween(from, to, units, inclusivity) { var localFrom = isMoment(from) ? from : createLocal(from), localTo = isMoment(to) ? to : createLocal(to); if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { return false; } inclusivity = inclusivity || '()'; return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)); } function isSame(input, units) { var localInput = isMoment(input) ? input : createLocal(input), inputMs; if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() === localInput.valueOf(); } else { inputMs = localInput.valueOf(); return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); } } function isSameOrAfter(input, units) { return this.isSame(input, units) || this.isAfter(input, units); } function isSameOrBefore(input, units) { return this.isSame(input, units) || this.isBefore(input, units); } function diff(input, units, asFloat) { var that, zoneDelta, output; if (!this.isValid()) { return NaN; } that = cloneWithOffset(input, this); if (!that.isValid()) { return NaN; } zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; units = normalizeUnits(units); switch (units) { case 'year': output = monthDiff(this, that) / 12; break; case 'month': output = monthDiff(this, that); break; case 'quarter': output = monthDiff(this, that) / 3; break; case 'second': output = (this - that) / 1e3; break; // 1000 case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst default: output = this - that; } return asFloat ? output : absFloor(output); } function monthDiff(a, b) { // difference in months var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month) anchor = a.clone().add(wholeMonthDiff, 'months'), anchor2, adjust; if (b - anchor < 0) { anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor - anchor2); } else { anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor2 - anchor); } //check for negative zero, return zero if negative zero return -(wholeMonthDiff + adjust) || 0; } hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; function toString() { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } function toISOString(keepOffset) { if (!this.isValid()) { return null; } var utc = keepOffset !== true; var m = utc ? this.clone().utc() : this; if (m.year() < 0 || m.year() > 9999) { return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'); } if (isFunction(Date.prototype.toISOString)) { // native implementation is ~50x faster, use it when we can if (utc) { return this.toDate().toISOString(); } else { return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z')); } } return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'); } /** * Return a human readable representation of a moment that can * also be evaluated to get a new moment which is the same * * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects */ function inspect() { if (!this.isValid()) { return 'moment.invalid(/* ' + this._i + ' */)'; } var func = 'moment'; var zone = ''; if (!this.isLocal()) { func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; zone = 'Z'; } var prefix = '[' + func + '("]'; var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; var datetime = '-MM-DD[T]HH:mm:ss.SSS'; var suffix = zone + '[")]'; return this.format(prefix + year + datetime + suffix); } function format(inputString) { if (!inputString) { inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; } var output = formatMoment(this, inputString); return this.localeData().postformat(output); } function from(time, withoutSuffix) { if (this.isValid() && ((isMoment(time) && time.isValid()) || createLocal(time).isValid())) { return createDuration({ to: this, from: time }).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function fromNow(withoutSuffix) { return this.from(createLocal(), withoutSuffix); } function to(time, withoutSuffix) { if (this.isValid() && ((isMoment(time) && time.isValid()) || createLocal(time).isValid())) { return createDuration({ from: this, to: time }).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function toNow(withoutSuffix) { return this.to(createLocal(), withoutSuffix); } // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. function locale(key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = getLocale(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } } var lang = deprecate( 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ); function localeData() { return this._locale; } var MS_PER_SECOND = 1000; var MS_PER_MINUTE = 60 * MS_PER_SECOND; var MS_PER_HOUR = 60 * MS_PER_MINUTE; var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; // actual modulo - handles negative numbers (for dates before 1970): function mod$1(dividend, divisor) { return (dividend % divisor + divisor) % divisor; } function localStartOfDate(y, m, d) { // the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { // preserve leap years using a full 400 year cycle, then reset return new Date(y + 400, m, d) - MS_PER_400_YEARS; } else { return new Date(y, m, d).valueOf(); } } function utcStartOfDate(y, m, d) { // Date.UTC remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { // preserve leap years using a full 400 year cycle, then reset return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; } else { return Date.UTC(y, m, d); } } function startOf(units) { var time; units = normalizeUnits(units); if (units === undefined || units === 'millisecond' || !this.isValid()) { return this; } var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; switch (units) { case 'year': time = startOfDate(this.year(), 0, 1); break; case 'quarter': time = startOfDate(this.year(), this.month() - this.month() % 3, 1); break; case 'month': time = startOfDate(this.year(), this.month(), 1); break; case 'week': time = startOfDate(this.year(), this.month(), this.date() - this.weekday()); break; case 'isoWeek': time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1)); break; case 'day': case 'date': time = startOfDate(this.year(), this.month(), this.date()); break; case 'hour': time = this._d.valueOf(); time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR); break; case 'minute': time = this._d.valueOf(); time -= mod$1(time, MS_PER_MINUTE); break; case 'second': time = this._d.valueOf(); time -= mod$1(time, MS_PER_SECOND); break; } this._d.setTime(time); hooks.updateOffset(this, true); return this; } function endOf(units) { var time; units = normalizeUnits(units); if (units === undefined || units === 'millisecond' || !this.isValid()) { return this; } var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; switch (units) { case 'year': time = startOfDate(this.year() + 1, 0, 1) - 1; break; case 'quarter': time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1; break; case 'month': time = startOfDate(this.year(), this.month() + 1, 1) - 1; break; case 'week': time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1; break; case 'isoWeek': time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1; break; case 'day': case 'date': time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; break; case 'hour': time = this._d.valueOf(); time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1; break; case 'minute': time = this._d.valueOf(); time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; break; case 'second': time = this._d.valueOf(); time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; break; } this._d.setTime(time); hooks.updateOffset(this, true); return this; } function valueOf() { return this._d.valueOf() - ((this._offset || 0) * 60000); } function unix() { return Math.floor(this.valueOf() / 1000); } function toDate() { return new Date(this.valueOf()); } function toArray() { var m = this; return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; } function toObject() { var m = this; return { years: m.year(), months: m.month(), date: m.date(), hours: m.hours(), minutes: m.minutes(), seconds: m.seconds(), milliseconds: m.milliseconds() }; } function toJSON() { // new Date(NaN).toJSON() === null return this.isValid() ? this.toISOString() : null; } function isValid$2() { return isValid(this); } function parsingFlags() { return extend({}, getParsingFlags(this)); } function invalidAt() { return getParsingFlags(this).overflow; } function creationData() { return { input: this._i, format: this._f, locale: this._locale, isUTC: this._isUTC, strict: this._strict }; } // FORMATTING addFormatToken(0, ['gg', 2], 0, function () { return this.weekYear() % 100; }); addFormatToken(0, ['GG', 2], 0, function () { return this.isoWeekYear() % 100; }); function addWeekYearFormatToken(token, getter) { addFormatToken(0, [token, token.length], 0, getter); } addWeekYearFormatToken('gggg', 'weekYear'); addWeekYearFormatToken('ggggg', 'weekYear'); addWeekYearFormatToken('GGGG', 'isoWeekYear'); addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES addUnitAlias('weekYear', 'gg'); addUnitAlias('isoWeekYear', 'GG'); // PRIORITY addUnitPriority('weekYear', 1); addUnitPriority('isoWeekYear', 1); // PARSING addRegexToken('G', matchSigned); addRegexToken('g', matchSigned); addRegexToken('GG', match1to2, match2); addRegexToken('gg', match1to2, match2); addRegexToken('GGGG', match1to4, match4); addRegexToken('gggg', match1to4, match4); addRegexToken('GGGGG', match1to6, match6); addRegexToken('ggggg', match1to6, match6); addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { week[token.substr(0, 2)] = toInt(input); }); addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { week[token] = hooks.parseTwoDigitYear(input); }); // MOMENTS function getSetWeekYear(input) { return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy); } function getSetISOWeekYear(input) { return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4); } function getISOWeeksInYear() { return weeksInYear(this.year(), 1, 4); } function getWeeksInYear() { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } function getSetWeekYearHelper(input, week, weekday, dow, doy) { var weeksTarget; if (input == null) { return weekOfYear(this, dow, doy).year; } else { weeksTarget = weeksInYear(input, dow, doy); if (week > weeksTarget) { week = weeksTarget; } return setWeekAll.call(this, input, week, weekday, dow, doy); } } function setWeekAll(weekYear, week, weekday, dow, doy) { var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); this.year(date.getUTCFullYear()); this.month(date.getUTCMonth()); this.date(date.getUTCDate()); return this; } // FORMATTING addFormatToken('Q', 0, 'Qo', 'quarter'); // ALIASES addUnitAlias('quarter', 'Q'); // PRIORITY addUnitPriority('quarter', 7); // PARSING addRegexToken('Q', match1); addParseToken('Q', function (input, array) { array[MONTH] = (toInt(input) - 1) * 3; }); // MOMENTS function getSetQuarter(input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); } // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIORITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { // TODO: Remove "ordinalParse" fallback in next major release. return isStrict ? (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : locale._dayOfMonthOrdinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0]); }); // MOMENTS var getSetDayOfMonth = makeGetSet('Date', true); // FORMATTING addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES addUnitAlias('dayOfYear', 'DDD'); // PRIORITY addUnitPriority('dayOfYear', 4); // PARSING addRegexToken('DDD', match1to3); addRegexToken('DDDD', match3); addParseToken(['DDD', 'DDDD'], function (input, array, config) { config._dayOfYear = toInt(input); }); // HELPERS // MOMENTS function getSetDayOfYear(input) { var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); } // FORMATTING addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES addUnitAlias('minute', 'm'); // PRIORITY addUnitPriority('minute', 14); // PARSING addRegexToken('m', match1to2); addRegexToken('mm', match1to2, match2); addParseToken(['m', 'mm'], MINUTE); // MOMENTS var getSetMinute = makeGetSet('Minutes', false); // FORMATTING addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES addUnitAlias('second', 's'); // PRIORITY addUnitPriority('second', 15); // PARSING addRegexToken('s', match1to2); addRegexToken('ss', match1to2, match2); addParseToken(['s', 'ss'], SECOND); // MOMENTS var getSetSecond = makeGetSet('Seconds', false); // FORMATTING addFormatToken('S', 0, 0, function () { return ~~(this.millisecond() / 100); }); addFormatToken(0, ['SS', 2], 0, function () { return ~~(this.millisecond() / 10); }); addFormatToken(0, ['SSS', 3], 0, 'millisecond'); addFormatToken(0, ['SSSS', 4], 0, function () { return this.millisecond() * 10; }); addFormatToken(0, ['SSSSS', 5], 0, function () { return this.millisecond() * 100; }); addFormatToken(0, ['SSSSSS', 6], 0, function () { return this.millisecond() * 1000; }); addFormatToken(0, ['SSSSSSS', 7], 0, function () { return this.millisecond() * 10000; }); addFormatToken(0, ['SSSSSSSS', 8], 0, function () { return this.millisecond() * 100000; }); addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { return this.millisecond() * 1000000; }); // ALIASES addUnitAlias('millisecond', 'ms'); // PRIORITY addUnitPriority('millisecond', 16); // PARSING addRegexToken('S', match1to3, match1); addRegexToken('SS', match1to3, match2); addRegexToken('SSS', match1to3, match3); var token; for (token = 'SSSS'; token.length <= 9; token += 'S') { addRegexToken(token, matchUnsigned); } function parseMs(input, array) { array[MILLISECOND] = toInt(('0.' + input) * 1000); } for (token = 'S'; token.length <= 9; token += 'S') { addParseToken(token, parseMs); } // MOMENTS var getSetMillisecond = makeGetSet('Milliseconds', false); // FORMATTING addFormatToken('z', 0, 0, 'zoneAbbr'); addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS function getZoneAbbr() { return this._isUTC ? 'UTC' : ''; } function getZoneName() { return this._isUTC ? 'Coordinated Universal Time' : ''; } var proto = Moment.prototype; proto.add = add; proto.calendar = calendar$1; proto.clone = clone; proto.diff = diff; proto.endOf = endOf; proto.format = format; proto.from = from; proto.fromNow = fromNow; proto.to = to; proto.toNow = toNow; proto.get = stringGet; proto.invalidAt = invalidAt; proto.isAfter = isAfter; proto.isBefore = isBefore; proto.isBetween = isBetween; proto.isSame = isSame; proto.isSameOrAfter = isSameOrAfter; proto.isSameOrBefore = isSameOrBefore; proto.isValid = isValid$2; proto.lang = lang; proto.locale = locale; proto.localeData = localeData; proto.max = prototypeMax; proto.min = prototypeMin; proto.parsingFlags = parsingFlags; proto.set = stringSet; proto.startOf = startOf; proto.subtract = subtract; proto.toArray = toArray; proto.toObject = toObject; proto.toDate = toDate; proto.toISOString = toISOString; proto.inspect = inspect; proto.toJSON = toJSON; proto.toString = toString; proto.unix = unix; proto.valueOf = valueOf; proto.creationData = creationData; proto.year = getSetYear; proto.isLeapYear = getIsLeapYear; proto.weekYear = getSetWeekYear; proto.isoWeekYear = getSetISOWeekYear; proto.quarter = proto.quarters = getSetQuarter; proto.month = getSetMonth; proto.daysInMonth = getDaysInMonth; proto.week = proto.weeks = getSetWeek; proto.isoWeek = proto.isoWeeks = getSetISOWeek; proto.weeksInYear = getWeeksInYear; proto.isoWeeksInYear = getISOWeeksInYear; proto.date = getSetDayOfMonth; proto.day = proto.days = getSetDayOfWeek; proto.weekday = getSetLocaleDayOfWeek; proto.isoWeekday = getSetISODayOfWeek; proto.dayOfYear = getSetDayOfYear; proto.hour = proto.hours = getSetHour; proto.minute = proto.minutes = getSetMinute; proto.second = proto.seconds = getSetSecond; proto.millisecond = proto.milliseconds = getSetMillisecond; proto.utcOffset = getSetOffset; proto.utc = setOffsetToUTC; proto.local = setOffsetToLocal; proto.parseZone = setOffsetToParsedOffset; proto.hasAlignedHourOffset = hasAlignedHourOffset; proto.isDST = isDaylightSavingTime; proto.isLocal = isLocal; proto.isUtcOffset = isUtcOffset; proto.isUtc = isUtc; proto.isUTC = isUtc; proto.zoneAbbr = getZoneAbbr; proto.zoneName = getZoneName; proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); function createUnix(input) { return createLocal(input * 1000); } function createInZone() { return createLocal.apply(null, arguments).parseZone(); } function preParsePostFormat(string) { return string; } var proto$1 = Locale.prototype; proto$1.calendar = calendar; proto$1.longDateFormat = longDateFormat; proto$1.invalidDate = invalidDate; proto$1.ordinal = ordinal; proto$1.preparse = preParsePostFormat; proto$1.postformat = preParsePostFormat; proto$1.relativeTime = relativeTime; proto$1.pastFuture = pastFuture; proto$1.set = set; proto$1.months = localeMonths; proto$1.monthsShort = localeMonthsShort; proto$1.monthsParse = localeMonthsParse; proto$1.monthsRegex = monthsRegex; proto$1.monthsShortRegex = monthsShortRegex; proto$1.week = localeWeek; proto$1.firstDayOfYear = localeFirstDayOfYear; proto$1.firstDayOfWeek = localeFirstDayOfWeek; proto$1.weekdays = localeWeekdays; proto$1.weekdaysMin = localeWeekdaysMin; proto$1.weekdaysShort = localeWeekdaysShort; proto$1.weekdaysParse = localeWeekdaysParse; proto$1.weekdaysRegex = weekdaysRegex; proto$1.weekdaysShortRegex = weekdaysShortRegex; proto$1.weekdaysMinRegex = weekdaysMinRegex; proto$1.isPM = localeIsPM; proto$1.meridiem = localeMeridiem; function get$1(format, index, field, setter) { var locale = getLocale(); var utc = createUTC().set(setter, index); return locale[field](utc, format); } function listMonthsImpl(format, index, field) { if (isNumber(format)) { index = format; format = undefined; } format = format || ''; if (index != null) { return get$1(format, index, field, 'month'); } var i; var out = []; for (i = 0; i < 12; i++) { out[i] = get$1(format, i, field, 'month'); } return out; } // () // (5) // (fmt, 5) // (fmt) // (true) // (true, 5) // (true, fmt, 5) // (true, fmt) function listWeekdaysImpl(localeSorted, format, index, field) { if (typeof localeSorted === 'boolean') { if (isNumber(format)) { index = format; format = undefined; } format = format || ''; } else { format = localeSorted; index = format; localeSorted = false; if (isNumber(format)) { index = format; format = undefined; } format = format || ''; } var locale = getLocale(), shift = localeSorted ? locale._week.dow : 0; if (index != null) { return get$1(format, (index + shift) % 7, field, 'day'); } var i; var out = []; for (i = 0; i < 7; i++) { out[i] = get$1(format, (i + shift) % 7, field, 'day'); } return out; } function listMonths(format, index) { return listMonthsImpl(format, index, 'months'); } function listMonthsShort(format, index) { return listMonthsImpl(format, index, 'monthsShort'); } function listWeekdays(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); } function listWeekdaysShort(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); } function listWeekdaysMin(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); } getSetGlobalLocale('en', { dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); // Side effect imports hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); var mathAbs = Math.abs; function abs() { var data = this._data; this._milliseconds = mathAbs(this._milliseconds); this._days = mathAbs(this._days); this._months = mathAbs(this._months); data.milliseconds = mathAbs(data.milliseconds); data.seconds = mathAbs(data.seconds); data.minutes = mathAbs(data.minutes); data.hours = mathAbs(data.hours); data.months = mathAbs(data.months); data.years = mathAbs(data.years); return this; } function addSubtract$1(duration, input, value, direction) { var other = createDuration(input, value); duration._milliseconds += direction * other._milliseconds; duration._days += direction * other._days; duration._months += direction * other._months; return duration._bubble(); } // supports only 2.0-style add(1, 's') or add(duration) function add$1(input, value) { return addSubtract$1(this, input, value, 1); } // supports only 2.0-style subtract(1, 's') or subtract(duration) function subtract$1(input, value) { return addSubtract$1(this, input, value, -1); } function absCeil(number) { if (number < 0) { return Math.floor(number); } else { return Math.ceil(number); } } function bubble() { var milliseconds = this._milliseconds; var days = this._days; var months = this._months; var data = this._data; var seconds, minutes, hours, years, monthsFromDays; // if we have a mix of positive and negative values, bubble down first // check: https://github.com/moment/moment/issues/2166 if (!((milliseconds >= 0 && days >= 0 && months >= 0) || (milliseconds <= 0 && days <= 0 && months <= 0))) { milliseconds += absCeil(monthsToDays(months) + days) * 864e5; days = 0; months = 0; } // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absFloor(milliseconds / 1000); data.seconds = seconds % 60; minutes = absFloor(seconds / 60); data.minutes = minutes % 60; hours = absFloor(minutes / 60); data.hours = hours % 24; days += absFloor(hours / 24); // convert days to months monthsFromDays = absFloor(daysToMonths(days)); months += monthsFromDays; days -= absCeil(monthsToDays(monthsFromDays)); // 12 months -> 1 year years = absFloor(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; return this; } function daysToMonths(days) { // 400 years have 146097 days (taking into account leap year rules) // 400 years have 12 months === 4800 return days * 4800 / 146097; } function monthsToDays(months) { // the reverse of daysToMonths return months * 146097 / 4800; } function as(units) { if (!this.isValid()) { return NaN; } var days; var months; var milliseconds = this._milliseconds; units = normalizeUnits(units); if (units === 'month' || units === 'quarter' || units === 'year') { days = this._days + milliseconds / 864e5; months = this._months + daysToMonths(days); switch (units) { case 'month': return months; case 'quarter': return months / 3; case 'year': return months / 12; } } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + Math.round(monthsToDays(this._months)); switch (units) { case 'week': return days / 7 + milliseconds / 6048e5; case 'day': return days + milliseconds / 864e5; case 'hour': return days * 24 + milliseconds / 36e5; case 'minute': return days * 1440 + milliseconds / 6e4; case 'second': return days * 86400 + milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 864e5) + milliseconds; default: throw new Error('Unknown unit ' + units); } } } // TODO: Use this.as('ms')? function valueOf$1() { if (!this.isValid()) { return NaN; } return ( this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6 ); } function makeAs(alias) { return function () { return this.as(alias); }; } var asMilliseconds = makeAs('ms'); var asSeconds = makeAs('s'); var asMinutes = makeAs('m'); var asHours = makeAs('h'); var asDays = makeAs('d'); var asWeeks = makeAs('w'); var asMonths = makeAs('M'); var asQuarters = makeAs('Q'); var asYears = makeAs('y'); function clone$1() { return createDuration(this); } function get$2(units) { units = normalizeUnits(units); return this.isValid() ? this[units + 's']() : NaN; } function makeGetter(name) { return function () { return this.isValid() ? this._data[name] : NaN; }; } var milliseconds = makeGetter('milliseconds'); var seconds = makeGetter('seconds'); var minutes = makeGetter('minutes'); var hours = makeGetter('hours'); var days = makeGetter('days'); var months = makeGetter('months'); var years = makeGetter('years'); function weeks() { return absFloor(this.days() / 7); } var round = Math.round; var thresholds = { ss: 44, // a few seconds to seconds s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime$1(posNegDuration, withoutSuffix, locale) { var duration = createDuration(posNegDuration).abs(); var seconds = round(duration.as('s')); var minutes = round(duration.as('m')); var hours = round(duration.as('h')); var days = round(duration.as('d')); var months = round(duration.as('M')); var years = round(duration.as('y')); var a = seconds <= thresholds.ss && ['s', seconds] || seconds < thresholds.s && ['ss', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days] || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years]; a[2] = withoutSuffix; a[3] = +posNegDuration > 0; a[4] = locale; return substituteTimeAgo.apply(null, a); } // This function allows you to set the rounding function for relative time strings function getSetRelativeTimeRounding(roundingFunction) { if (roundingFunction === undefined) { return round; } if (typeof (roundingFunction) === 'function') { round = roundingFunction; return true; } return false; } // This function allows you to set a threshold for relative time strings function getSetRelativeTimeThreshold(threshold, limit) { if (thresholds[threshold] === undefined) { return false; } if (limit === undefined) { return thresholds[threshold]; } thresholds[threshold] = limit; if (threshold === 's') { thresholds.ss = limit - 1; } return true; } function humanize(withSuffix) { if (!this.isValid()) { return this.localeData().invalidDate(); } var locale = this.localeData(); var output = relativeTime$1(this, !withSuffix, locale); if (withSuffix) { output = locale.pastFuture(+this, output); } return locale.postformat(output); } var abs$1 = Math.abs; function sign(x) { return ((x > 0) - (x < 0)) || +x; } function toISOString$1() { // for ISO strings we do not use the normal bubbling rules: // * milliseconds bubble up until they become hours // * days do not bubble at all // * months bubble up until they become years // This is because there is no context-free conversion between hours and days // (think of clock changes) // and also not between days and months (28-31 days per month) if (!this.isValid()) { return this.localeData().invalidDate(); } var seconds = abs$1(this._milliseconds) / 1000; var days = abs$1(this._days); var months = abs$1(this._months); var minutes, hours, years; // 3600 seconds -> 60 minutes -> 1 hour minutes = absFloor(seconds / 60); hours = absFloor(minutes / 60); seconds %= 60; minutes %= 60; // 12 months -> 1 year years = absFloor(months / 12); months %= 12; // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var Y = years; var M = months; var D = days; var h = hours; var m = minutes; var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; var total = this.asSeconds(); if (!total) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } var totalSign = total < 0 ? '-' : ''; var ymSign = sign(this._months) !== sign(total) ? '-' : ''; var daysSign = sign(this._days) !== sign(total) ? '-' : ''; var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; return totalSign + 'P' + (Y ? ymSign + Y + 'Y' : '') + (M ? ymSign + M + 'M' : '') + (D ? daysSign + D + 'D' : '') + ((h || m || s) ? 'T' : '') + (h ? hmsSign + h + 'H' : '') + (m ? hmsSign + m + 'M' : '') + (s ? hmsSign + s + 'S' : ''); } var proto$2 = Duration.prototype; proto$2.isValid = isValid$1; proto$2.abs = abs; proto$2.add = add$1; proto$2.subtract = subtract$1; proto$2.as = as; proto$2.asMilliseconds = asMilliseconds; proto$2.asSeconds = asSeconds; proto$2.asMinutes = asMinutes; proto$2.asHours = asHours; proto$2.asDays = asDays; proto$2.asWeeks = asWeeks; proto$2.asMonths = asMonths; proto$2.asQuarters = asQuarters; proto$2.asYears = asYears; proto$2.valueOf = valueOf$1; proto$2._bubble = bubble; proto$2.clone = clone$1; proto$2.get = get$2; proto$2.milliseconds = milliseconds; proto$2.seconds = seconds; proto$2.minutes = minutes; proto$2.hours = hours; proto$2.days = days; proto$2.weeks = weeks; proto$2.months = months; proto$2.years = years; proto$2.humanize = humanize; proto$2.toISOString = toISOString$1; proto$2.toString = toISOString$1; proto$2.toJSON = toISOString$1; proto$2.locale = locale; proto$2.localeData = localeData; proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1); proto$2.lang = lang; // Side effect imports // FORMATTING addFormatToken('X', 0, 0, 'unix'); addFormatToken('x', 0, 0, 'valueOf'); // PARSING addRegexToken('x', matchSigned); addRegexToken('X', matchTimestamp); addParseToken('X', function (input, array, config) { config._d = new Date(parseFloat(input, 10) * 1000); }); addParseToken('x', function (input, array, config) { config._d = new Date(toInt(input)); }); // Side effect imports hooks.version = '2.24.0'; setHookCallback(createLocal); hooks.fn = proto; hooks.min = min; hooks.max = max; hooks.now = now; hooks.utc = createUTC; hooks.unix = createUnix; hooks.months = listMonths; hooks.isDate = isDate; hooks.locale = getSetGlobalLocale; hooks.invalid = createInvalid; hooks.duration = createDuration; hooks.isMoment = isMoment; hooks.weekdays = listWeekdays; hooks.parseZone = createInZone; hooks.localeData = getLocale; hooks.isDuration = isDuration; hooks.monthsShort = listMonthsShort; hooks.weekdaysMin = listWeekdaysMin; hooks.defineLocale = defineLocale; hooks.updateLocale = updateLocale; hooks.locales = listLocales; hooks.weekdaysShort = listWeekdaysShort; hooks.normalizeUnits = normalizeUnits; hooks.relativeTimeRounding = getSetRelativeTimeRounding; hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; hooks.calendarFormat = getCalendarFormat; hooks.prototype = proto; // currently HTML5 input type only supports 24-hour formats hooks.HTML5_FMT = { DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" /> DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" /> DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" /> DATE: 'YYYY-MM-DD', // <input type="date" /> TIME: 'HH:mm', // <input type="time" /> TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" /> TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" /> WEEK: 'GGGG-[W]WW', // <input type="week" /> MONTH: 'YYYY-MM' // <input type="month" /> }; return hooks; })));
import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; import sveltePreprocess from 'svelte-preprocess'; import WindiCSS from 'vite-plugin-windicss'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [ WindiCSS(), svelte({ preprocess: [sveltePreprocess({ typescript: true })], }), ], });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _createIcon = _interopRequireDefault(require("./util/createIcon")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _default = (0, _createIcon["default"])('M7,5H21V7H7V5M7,13V11H21V13H7M4,4.5A1.5,1.5 0 0,1 5.5,6A1.5,1.5 0 0,1 4,7.5A1.5,1.5 0 0,1 2.5,6A1.5,1.5 0 0,1 4,4.5M4,10.5A1.5,1.5 0 0,1 5.5,12A1.5,1.5 0 0,1 4,13.5A1.5,1.5 0 0,1 2.5,12A1.5,1.5 0 0,1 4,10.5M7,19V17H21V19H7M4,16.5A1.5,1.5 0 0,1 5.5,18A1.5,1.5 0 0,1 4,19.5A1.5,1.5 0 0,1 2.5,18A1.5,1.5 0 0,1 4,16.5Z'); exports["default"] = _default;
import * as React from 'react'; import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils'; import { arrayIncludes } from '../utils'; function getOrientation() { if (typeof window === 'undefined') { return 'portrait'; } if (window.screen && window.screen.orientation && window.screen.orientation.angle) { return Math.abs(window.screen.orientation.angle) === 90 ? 'landscape' : 'portrait'; } // Support IOS safari if (window.orientation) { return Math.abs(Number(window.orientation)) === 90 ? 'landscape' : 'portrait'; } return 'portrait'; } export function useIsLandscape(views, customOrientation) { var _React$useState = React.useState(getOrientation), orientation = _React$useState[0], setOrientation = _React$useState[1]; useEnhancedEffect(function () { var eventHandler = function eventHandler() { setOrientation(getOrientation()); }; window.addEventListener('orientationchange', eventHandler); return function () { window.removeEventListener('orientationchange', eventHandler); }; }, []); if (arrayIncludes(views, ['hours', 'minutes', 'seconds'])) { // could not display 13:34:44 in landscape mode return false; } var orientationToUse = customOrientation || orientation; return orientationToUse === 'landscape'; } export default useIsLandscape;
'use strict'; angular.module('MapBiomas.services') .factory('ClassesService', ['$resource', function ($resource) { var Classes = $resource('mapbiomas/services/classes/:id', { id: '@id' }, { paginate: { url: "mapbiomas/services/classes", isArray: false, method: 'GET' } }); return Classes; } ]);
import * as React from "react" import { graphql } from "gatsby" //import parse from "react-html-parser" // import parse from "html-react-parser" // import { GatsbyImage, getImage } from 'gatsby-plugin-image' // import { render } from "react-dom" import Img from "gatsby-image" const acfPost=({data})=>{ return( <div> {data.allWpPost.edges[0].node.acfDemo.justATextField} <h1> {data.allWpPost.edges[0].node.acfDemo.textarea}</h1> <img src={data.allWpPost.edges[0].node.acfDemo.kaliimg.sourceUrl}/> </div> ) } export const query=graphql `query{ allWpPost(filter: {title: {eq: "Freetech"}}) { edges { node { excerpt acfDemo { fieldGroupName justATextField textarea kaliimg{ sourceUrl } } } } } } ` export default acfPost
var ufs__extern_8h = [ [ "BA_CLRBUF", "d6/dc6/ufs__extern_8h.html#acb5c2c558e6b9726f11b864282e0e228", null ], [ "BA_METAONLY", "d6/dc6/ufs__extern_8h.html#ad8b107c1878c2604e4a31eca22eae6ec", null ], [ "BA_SEQMASK", "d6/dc6/ufs__extern_8h.html#a46407f9fa3f9faac8f2970acda55c324", null ], [ "BA_SEQMAX", "d6/dc6/ufs__extern_8h.html#a7e184ed5e3dd93f457d2a7fbae718ae5", null ], [ "BA_SEQSHIFT", "d6/dc6/ufs__extern_8h.html#a83f42879372ac90810c95bf95c91fee8", null ], [ "BA_UNMAPPED", "d6/dc6/ufs__extern_8h.html#ad55d9dc7ac4e9e3a33b00a4799be06fe", null ], [ "ffs_snapgone", "d6/dc6/ufs__extern_8h.html#a41964469cbcd8acac3e5a0121a1ccb5e", null ], [ "softdep_change_directoryentry_offset", "d6/dc6/ufs__extern_8h.html#a2f3cd6cdffb6a232cd77e98a311aef32", null ], [ "softdep_change_linkcnt", "d6/dc6/ufs__extern_8h.html#a4742973311bcb9daca5274f5dd306e50", null ], [ "softdep_revert_create", "d6/dc6/ufs__extern_8h.html#adaecbda6cc810556733ff172a60f6405", null ], [ "softdep_revert_link", "d6/dc6/ufs__extern_8h.html#a43f9f06a80a3722d45015e2dcc5bc8a9", null ], [ "softdep_revert_mkdir", "d6/dc6/ufs__extern_8h.html#a83a23cb06f03e161d09322c011f3c5aa", null ], [ "softdep_revert_rmdir", "d6/dc6/ufs__extern_8h.html#a0cd7874944e64470a06d2b784b509b1a", null ], [ "softdep_setup_create", "d6/dc6/ufs__extern_8h.html#a8b6d6e729792086cb9acc5d0279765ba", null ], [ "softdep_setup_directory_add", "d6/dc6/ufs__extern_8h.html#aabc74d5cf3e943b0c8e91a5f5eb18a20", null ], [ "softdep_setup_directory_change", "d6/dc6/ufs__extern_8h.html#a586b46d62771cce6ebd8432a04131397", null ], [ "softdep_setup_dotdot_link", "d6/dc6/ufs__extern_8h.html#afa98828d9acf3bb6303d3a29169b2583", null ], [ "softdep_setup_link", "d6/dc6/ufs__extern_8h.html#a9c358ab17f78073c17a799fc435a558e", null ], [ "softdep_setup_mkdir", "d6/dc6/ufs__extern_8h.html#a50903c064f35363ad5aecdcc1fd2a0a7", null ], [ "softdep_setup_remove", "d6/dc6/ufs__extern_8h.html#a85ba2a72fe731a3eb30f5c4055910588", null ], [ "softdep_setup_rmdir", "d6/dc6/ufs__extern_8h.html#aa1216d604b04db68fc21d2ec5306518f", null ], [ "softdep_setup_unlink", "d6/dc6/ufs__extern_8h.html#a8902459658def3b44546b6af7f339fc7", null ], [ "softdep_slowdown", "d6/dc6/ufs__extern_8h.html#a04c54c6e3d41452bd504db7f71c5ce5d", null ], [ "SYSCTL_DECL", "d6/dc6/ufs__extern_8h.html#adf9cf4ddc429907c08ce5f493be121bc", null ], [ "ufs_bmap", "d6/dc6/ufs__extern_8h.html#aa6134edeb119bc732a52d30ea42b941d", null ], [ "ufs_bmaparray", "d6/dc6/ufs__extern_8h.html#a0e54c9e03e97c7e8b213b5ec8da0e128", null ], [ "ufs_checkpath", "d6/dc6/ufs__extern_8h.html#ae8f553d277277ac36e459692723929d1", null ], [ "ufs_dirbad", "d6/dc6/ufs__extern_8h.html#ad469bc74734c793b983315fcd979afb1", null ], [ "ufs_dirbadentry", "d6/dc6/ufs__extern_8h.html#a383d263ad713c972f7477a7480aaf98d", null ], [ "ufs_dirempty", "d6/dc6/ufs__extern_8h.html#a232d0968a90f448aa8df95a43264894b", null ], [ "ufs_direnter", "d6/dc6/ufs__extern_8h.html#af941bbd2aea865b368bbeff8a9a04c45", null ], [ "ufs_dirremove", "d6/dc6/ufs__extern_8h.html#a1198dbf9c299234038eddec957ad84b5", null ], [ "ufs_dirrewrite", "d6/dc6/ufs__extern_8h.html#a2943c1d770190a938e4b8977b214e161", null ], [ "ufs_extread", "d6/dc6/ufs__extern_8h.html#a7ec5a463bd2e6e3d0a297dbebc7b6281", null ], [ "ufs_extwrite", "d6/dc6/ufs__extern_8h.html#a3f2d027df56801514f98f5e192ad0633", null ], [ "ufs_fhtovp", "d6/dc6/ufs__extern_8h.html#a10c4958ba78d63b9ea34959b7537afbe", null ], [ "ufs_getlbns", "d6/dc6/ufs__extern_8h.html#a14bf920afb956f16f2ed495841372330", null ], [ "ufs_inactive", "d6/dc6/ufs__extern_8h.html#adafbdf2b515ef29fb47ee4472408283a", null ], [ "ufs_init", "d6/dc6/ufs__extern_8h.html#a0e742cb6b351c7a1b01a320a9be9d99b", null ], [ "ufs_itimes", "d6/dc6/ufs__extern_8h.html#ab814a762ce14ba119ab5fc19a1fc1832", null ], [ "ufs_lookup", "d6/dc6/ufs__extern_8h.html#afdad4485752ca95c8806480ea1149c60", null ], [ "ufs_lookup_ino", "d6/dc6/ufs__extern_8h.html#a05a6baefbdf838cf01229d798e709461", null ], [ "ufs_makedirentry", "d6/dc6/ufs__extern_8h.html#a94c226f114e08c0402cfdb4d6b510e5c", null ], [ "ufs_prepare_reclaim", "d6/dc6/ufs__extern_8h.html#abd571327abfb9241aca1a04087fe29ed", null ], [ "ufs_readdir", "d6/dc6/ufs__extern_8h.html#aa6b3412cc5811c83d153e812d7f9c736", null ], [ "ufs_reclaim", "d6/dc6/ufs__extern_8h.html#a66064d210c47a4a4089c01fe0172430d", null ], [ "ufs_uninit", "d6/dc6/ufs__extern_8h.html#a56b1bacd39bfd673938f86892ca6c8e1", null ], [ "ufs_vinit", "d6/dc6/ufs__extern_8h.html#af12d21231632f9a911bc9e2442c539c1", null ], [ "ufs_fifoops", "d6/dc6/ufs__extern_8h.html#ada47a443e617eb4e6fedfcbc21d1c3dc", null ], [ "ufs_root", "d6/dc6/ufs__extern_8h.html#a56dcdd05473bfd1fe5b87cfe70c193d4", null ], [ "ufs_vnodeops", "d6/dc6/ufs__extern_8h.html#a8155356d23e070448aea5e991152b118", null ] ];
import json class TestApi: # UserList tests def test_user_list_200(self, testapp, users): resp = testapp.get('/v1/users') data = json.loads(resp.get_data(as_text=True)) assert len(data) == 50 assert data[0].get('username') == "user0" assert data[0].get('email') == "[email protected]" def test_user_list_post_201(self, testapp, users): data = { 'username': 'valid', 'email': '[email protected]' } resp = testapp.post( '/v1/users', data=json.dumps(data), content_type='application/json' ) assert resp.status_code == 201 user_id = json.loads(resp.get_data(as_text=True))['id'] resp = testapp.get('/v1/users/{}'.format(user_id)) assert resp.status_code == 200 assert json.loads(resp.get_data(as_text=True))['username'] == 'valid' def test_user_post_500(self, testapp, users): data = { 'username': 'user0', 'email': '[email protected]' } resp = testapp.post( '/v1/users', data=json.dumps(data), content_type='application/json' ) assert resp.status_code == 500 # UserDetail tests def test_user_put_200(self, testapp, users): resp = testapp.put('/v1/users/1', data=json.dumps({ 'username': 'new_name', 'email': '[email protected]' }), content_type='application/json') assert resp.status_code == 200 resp = testapp.get('/v1/users/1') assert resp.status_code == 200 data = json.loads(resp.get_data(as_text=True)) assert data['username'] == "new_name" def test_user_put_404(self, testapp, users): resp = testapp.put('/v1/users/10000', data=json.dumps({ 'username': 'new_name', 'email': '[email protected]' }), content_type='application/json') assert resp.status_code == 404 def test_user_get_200(self, testapp, users): resp = testapp.get('/v1/users/1') assert resp.status_code == 200 data = json.loads(resp.get_data(as_text=True)) assert data["id"] == 1 assert data['username'] == 'user0' assert data['email'] == '[email protected]' def test_user_get_404(self, testapp, users): resp = testapp.get('/v1/users/10000') assert resp.status_code == 404 def test_user_delete_202(self, testapp, users): resp = testapp.delete('/v1/users/1') assert resp.status_code == 202 def test_user_delete_404(self, testapp, users): resp = testapp.delete('/v1/users/10000') assert resp.status_code == 404
'use strict' // Template version: 1.2.5 // see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') const devEnv = require('./dev.env') module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', // 代理列表, 是否开启代理通过[./dev.env.js]配置 proxyTable: devEnv.OPEN_PROXY === false ? {} : { '/proxyApi': { target: 'http://localhost:8020/highway-calculator-fast/', changeOrigin: true, pathRewrite: { '^/proxyApi': '/' } } }, // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 8019, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined autoOpenBrowser: true, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- // Use Eslint Loader? // If true, your code will be linted during bundling and // linting errors and warnings will be shown in the console. useEslint: true, // If true, eslint errors and warnings will also be shown in the error overlay // in the browser. showEslintErrorsInOverlay: false, /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'eval-source-map', // If you have problems debugging vue-files in devtools, // set this to false - it *may* help // https://vue-loader.vuejs.org/en/options.html#cachebusting cacheBusting: true, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false, }, build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: './', /** * Source Maps */ productionSourceMap: false, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report } }
/************************************************************* * * MathJax/jax/output/CommonHTML/fonts/TeX/SansSerif-Regular.js * * Copyright (c) 2015-2016 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. * */ (function (CHTML) { var font = 'MathJax_SansSerif'; CHTML.FONTDATA.FONTS[font] = { className: CHTML.FONTDATA.familyName(font), centerline: 250, ascent: 750, descent: 250, 0x20: [0, 0, 250, 0, 0], // SPACE 0x21: [694, 0, 319, 110, 208], // EXCLAMATION MARK 0x22: [694, -471, 500, 32, 325], // QUOTATION MARK 0x23: [694, 194, 833, 56, 777], // NUMBER SIGN 0x24: [750, 56, 500, 44, 444], // DOLLAR SIGN 0x25: [750, 56, 833, 56, 776], // PERCENT SIGN 0x26: [716, 22, 758, 42, 702], // AMPERSAND 0x27: [694, -471, 278, 89, 188], // APOSTROPHE 0x28: [750, 250, 389, 74, 333], // LEFT PARENTHESIS 0x29: [750, 250, 389, 55, 314], // RIGHT PARENTHESIS 0x2A: [750, -306, 500, 63, 436], // ASTERISK 0x2B: [583, 82, 778, 56, 722], // PLUS SIGN 0x2C: [98, 125, 278, 89, 188], // COMMA 0x2D: [259, -186, 333, 11, 277], // HYPHEN-MINUS 0x2E: [98, 0, 278, 90, 188], // FULL STOP 0x2F: [750, 250, 500, 56, 445], // SOLIDUS 0x30: [678, 22, 500, 39, 460], // DIGIT ZERO 0x31: [678, 0, 500, 83, 430], // DIGIT ONE 0x32: [677, 0, 500, 42, 449], // DIGIT TWO 0x33: [678, 22, 500, 42, 457], // DIGIT THREE 0x34: [656, 0, 500, 28, 471], // DIGIT FOUR 0x35: [656, 21, 500, 33, 449], // DIGIT FIVE 0x36: [677, 22, 500, 42, 457], // DIGIT SIX 0x37: [656, 11, 500, 42, 457], // DIGIT SEVEN 0x38: [678, 22, 500, 43, 456], // DIGIT EIGHT 0x39: [677, 22, 500, 42, 457], // DIGIT NINE 0x3A: [444, 0, 278, 90, 188], // COLON 0x3B: [444, 125, 278, 89, 188], // SEMICOLON 0x3D: [370, -130, 778, 56, 722], // EQUALS SIGN 0x3F: [704, 0, 472, 55, 416], // QUESTION MARK 0x40: [704, 11, 667, 56, 612], // COMMERCIAL AT 0x41: [694, 0, 667, 28, 638], // LATIN CAPITAL LETTER A 0x42: [694, 0, 667, 90, 610], // LATIN CAPITAL LETTER B 0x43: [705, 11, 639, 59, 587], // LATIN CAPITAL LETTER C 0x44: [694, 0, 722, 88, 666], // LATIN CAPITAL LETTER D 0x45: [691, 0, 597, 86, 554], // LATIN CAPITAL LETTER E 0x46: [691, 0, 569, 86, 526], // LATIN CAPITAL LETTER F 0x47: [704, 11, 667, 59, 599], // LATIN CAPITAL LETTER G 0x48: [694, 0, 708, 86, 621], // LATIN CAPITAL LETTER H 0x49: [694, 0, 278, 87, 191], // LATIN CAPITAL LETTER I 0x4A: [694, 22, 472, 42, 388], // LATIN CAPITAL LETTER J 0x4B: [694, 0, 694, 88, 651], // LATIN CAPITAL LETTER K 0x4C: [694, 0, 542, 87, 499], // LATIN CAPITAL LETTER L 0x4D: [694, 0, 875, 92, 782], // LATIN CAPITAL LETTER M 0x4E: [694, 0, 708, 88, 619], // LATIN CAPITAL LETTER N 0x4F: [715, 22, 736, 55, 680], // LATIN CAPITAL LETTER O 0x50: [694, 0, 639, 88, 583], // LATIN CAPITAL LETTER P 0x51: [715, 125, 736, 55, 680], // LATIN CAPITAL LETTER Q 0x52: [694, 0, 646, 88, 617], // LATIN CAPITAL LETTER R 0x53: [716, 22, 556, 44, 500], // LATIN CAPITAL LETTER S 0x54: [688, 0, 681, 36, 644], // LATIN CAPITAL LETTER T 0x55: [694, 22, 688, 87, 600], // LATIN CAPITAL LETTER U 0x56: [694, 0, 667, 14, 652], // LATIN CAPITAL LETTER V 0x57: [694, 0, 944, 14, 929], // LATIN CAPITAL LETTER W 0x58: [694, 0, 667, 14, 652], // LATIN CAPITAL LETTER X 0x59: [694, 0, 667, 3, 663], // LATIN CAPITAL LETTER Y 0x5A: [694, 0, 611, 55, 560], // LATIN CAPITAL LETTER Z 0x5B: [750, 250, 289, 94, 266], // LEFT SQUARE BRACKET 0x5D: [750, 250, 289, 22, 194], // RIGHT SQUARE BRACKET 0x5E: [694, -527, 500, 78, 421], // CIRCUMFLEX ACCENT 0x5F: [-38, 114, 500, 0, 499], // LOW LINE 0x61: [460, 10, 481, 38, 407], // LATIN SMALL LETTER A 0x62: [694, 11, 517, 75, 482], // LATIN SMALL LETTER B 0x63: [460, 10, 444, 34, 415], // LATIN SMALL LETTER C 0x64: [694, 10, 517, 33, 441], // LATIN SMALL LETTER D 0x65: [461, 10, 444, 28, 415], // LATIN SMALL LETTER E 0x66: [705, 0, 306, 27, 347], // LATIN SMALL LETTER F 0x67: [455, 206, 500, 28, 485], // LATIN SMALL LETTER G 0x68: [694, 0, 517, 73, 443], // LATIN SMALL LETTER H 0x69: [680, 0, 239, 67, 171], // LATIN SMALL LETTER I 0x6A: [680, 205, 267, -59, 192], // LATIN SMALL LETTER J 0x6B: [694, 0, 489, 76, 471], // LATIN SMALL LETTER K 0x6C: [694, 0, 239, 74, 164], // LATIN SMALL LETTER L 0x6D: [455, 0, 794, 73, 720], // LATIN SMALL LETTER M 0x6E: [455, 0, 517, 73, 443], // LATIN SMALL LETTER N 0x6F: [460, 10, 500, 28, 471], // LATIN SMALL LETTER O 0x70: [455, 194, 517, 75, 483], // LATIN SMALL LETTER P 0x71: [455, 194, 517, 33, 441], // LATIN SMALL LETTER Q 0x72: [455, 0, 342, 74, 327], // LATIN SMALL LETTER R 0x73: [460, 10, 383, 28, 360], // LATIN SMALL LETTER S 0x74: [571, 10, 361, 18, 333], // LATIN SMALL LETTER T 0x75: [444, 10, 517, 73, 443], // LATIN SMALL LETTER U 0x76: [444, 0, 461, 14, 446], // LATIN SMALL LETTER V 0x77: [444, 0, 683, 14, 668], // LATIN SMALL LETTER W 0x78: [444, 0, 461, 0, 460], // LATIN SMALL LETTER X 0x79: [444, 204, 461, 14, 446], // LATIN SMALL LETTER Y 0x7A: [444, 0, 435, 28, 402], // LATIN SMALL LETTER Z 0x7E: [327, -193, 500, 83, 416], // TILDE 0xA0: [0, 0, 250, 0, 0], // NO-BREAK SPACE 0x131: [444, 0, 239, 74, 164], // LATIN SMALL LETTER DOTLESS I 0x237: [444, 205, 267, -59, 192], // LATIN SMALL LETTER DOTLESS J 0x300: [694, -527, 0, -417, -199], // COMBINING GRAVE ACCENT 0x301: [694, -527, 0, -302, -84], // COMBINING ACUTE ACCENT 0x302: [694, -527, 0, -422, -79], // COMBINING CIRCUMFLEX ACCENT 0x303: [677, -543, 0, -417, -84], // COMBINING TILDE 0x304: [631, -552, 0, -431, -70], // COMBINING MACRON 0x306: [694, -508, 0, -427, -74], // COMBINING BREVE 0x307: [680, -576, 0, -302, -198], // COMBINING DOT ABOVE 0x308: [680, -582, 0, -397, -104], // COMBINING DIAERESIS 0x30A: [694, -527, 0, -319, -99], // COMBINING RING ABOVE 0x30B: [694, -527, 0, -399, -84], // COMBINING DOUBLE ACUTE ACCENT 0x30C: [654, -487, 0, -422, -79], // COMBINING CARON 0x393: [691, 0, 542, 87, 499], // GREEK CAPITAL LETTER GAMMA 0x394: [694, 0, 833, 42, 790], // GREEK CAPITAL LETTER DELTA 0x398: [716, 21, 778, 56, 722], // GREEK CAPITAL LETTER THETA 0x39B: [694, 0, 611, 28, 582], // GREEK CAPITAL LETTER LAMDA 0x39E: [688, 0, 667, 42, 624], // GREEK CAPITAL LETTER XI 0x3A0: [691, 0, 708, 86, 621], // GREEK CAPITAL LETTER PI 0x3A3: [694, 0, 722, 55, 666], // GREEK CAPITAL LETTER SIGMA 0x3A5: [716, 0, 778, 55, 722], // GREEK CAPITAL LETTER UPSILON 0x3A6: [694, 0, 722, 55, 666], // GREEK CAPITAL LETTER PHI 0x3A8: [694, 0, 778, 55, 722], // GREEK CAPITAL LETTER PSI 0x3A9: [716, 0, 722, 44, 677], // GREEK CAPITAL LETTER OMEGA 0x2013: [312, -236, 500, 0, 499], // EN DASH 0x2014: [312, -236, 1000, 0, 999], // EM DASH 0x2018: [694, -471, 278, 90, 189], // LEFT SINGLE QUOTATION MARK 0x2019: [694, -471, 278, 89, 188], // RIGHT SINGLE QUOTATION MARK 0x201C: [694, -471, 500, 174, 467], // LEFT DOUBLE QUOTATION MARK 0x201D: [694, -471, 500, 32, 325] // RIGHT DOUBLE QUOTATION MARK }; CHTML.fontLoaded("TeX/" + font.substr(8)); })(MathJax.OutputJax.CommonHTML);
import React, { useState } from "react"; import Avatar from "@material-ui/core/Avatar"; import Button from "@material-ui/core/Button"; import CssBaseline from "@material-ui/core/CssBaseline"; import TextField from "@material-ui/core/TextField"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Checkbox from "@material-ui/core/Checkbox"; import Link from "@material-ui/core/Link"; import Grid from "@material-ui/core/Grid"; import Box from "@material-ui/core/Box"; import LockOutlinedIcon from "@material-ui/icons/LockOutlined"; import Typography from "@material-ui/core/Typography"; import { makeStyles } from "@material-ui/core/styles"; import Container from "@material-ui/core/Container"; import axios from "axios"; import { setUserSession, setAppCache } from "../utils/Common.js"; import { config } from "../variables/general.js"; import Lang from "../variables/lang.json"; import Snackbar from "components/Snackbar/Snackbar.js"; import AddAlert from "@material-ui/icons/AddAlert"; import api from "../variables/api.json"; // import api from '../' function Copyright() { return ( <Typography variant="body2" color="textSecondary" align="center"> {"Copyright © "} <Link color="inherit" href="#"> {Lang.appName} </Link>{" "} {new Date().getFullYear()} {"."} </Typography> ); } const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: "flex", flexDirection: "column", alignItems: "center", }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: "100%", // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, })); export default function Login(props) { const classes = useStyles(); const [loading, setLoading] = useState(false); const username = useFormInput(""); const password = useFormInput(""); //notification hooks const [open, setOpen] = useState(false); const [place, setPlace] = useState("tr"); const [color, setColor] = useState("info"); const [error, setError] = useState(null); // handle button click of login form const handleLogin = (ev) => { debugger; ev.preventDefault(); //validations if (!username.value || !password.value) { showNotification(Lang.loginPage.keyRequiredField); return false; } else if (/(.+)@(.+){2,}\.(.+){2,}/.test(username.value) !== true) { showNotification(Lang.loginPage.keyInvalidEmail); return false; } else if (password.value.length < 6) { showNotification(Lang.loginPage.keyPasswordErrorMessage); return false; } setLoading(true); config.params = {}; config.params.userName = username.value; config.params.password = password.value; axios .post(api.login, null, config) .then((response) => { setLoading(false); setUserSession(true, response.data); setAppCache("orgId", response.data.orgId); setAppCache("adminUserId", response.data.adminUserId); props.history.push("/dashboard"); }) .catch((error) => { setLoading(false); if (error && error.response) showNotification(error.response.data.value); else showNotification(Lang.loginPage.keySomethingWentWrong); }); }; //notification handler const showNotification = (message) => { setError(message); setOpen(true); setTimeout(() => { setOpen(false); }, 3000); }; return ( <Container component="main" maxWidth="xs"> <CssBaseline /> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign in </Typography> <form className={classes.form} noValidate> <TextField margin="normal" required fullWidth id="email" label="Email Address" name="email" autoComplete="email" autoFocus {...username} /> <TextField margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" {...password} /> <Button type="button" fullWidth variant="contained" color="primary" className={classes.submit} onClick={handleLogin} > Sign In </Button> {/* <Grid container> <Grid item xs> <Link href="#" variant="body2"> Forgot password? </Link> </Grid> <Grid item> <Link href="#" variant="body2"> {"Don't have an account? Sign Up"} </Link> </Grid> </Grid> */} </form> </div> <Box mt={8}> <Copyright /> </Box> <Snackbar place={place} color={color} icon={AddAlert} message={error} open={open} closeNotification={() => setOpen(false)} close /> </Container> ); } const useFormInput = (initialValue) => { const [value, setValue] = useState(initialValue); const handleChange = (e) => { setValue(e.target.value); }; return { value, onChange: handleChange, }; };
import _class_call_check from "@swc/helpers/src/_class_call_check.mjs"; import _inherits from "@swc/helpers/src/_inherits.mjs"; import _create_super from "@swc/helpers/src/_create_super.mjs"; // @noEmit: true // @allowJs: true // @checkJs: true // @noImplicitAny: true // @strictNullChecks: true // @Filename: a.js var Base = function Base() { "use strict"; _class_call_check(this, Base); this.p = 1; }; var Derived = /*#__PURE__*/ function(Base) { "use strict"; _inherits(Derived, Base); var _super = _create_super(Derived); function Derived() { _class_call_check(this, Derived); return _super.apply(this, arguments); } var _proto = Derived.prototype; _proto.m = function m() { this.p = 1; }; return Derived; }(Base);
var path = require('path'); var ManifestPlugin = require('webpack-manifest-plugin'); module.exports = { entry: path.resolve(__dirname, '../src/index.jsx'), mode: 'development', node: { fs: "empty" }, devtool: 'source-map', output: { path: path.resolve(__dirname, '../../public/assets'), filename: '[name].js', chunkFilename: 'chunk.[name].js' }, module: { rules: [ { loader: 'babel-loader', test: /\.jsx?$/, exclude: /node_modules/, options: { presets: [['@babel/preset-env', {useBuiltIns: 'usage', corejs:3}], '@babel/preset-react'], babelrc: false } } ] }, plugins: [ new ManifestPlugin({ fileName: 'webpack.manifest.json' }) ] };
/** * Message processing logic that deals with message representations at a higher * level than just text/plain processing (`quotechew.js`) or text/html * (`htmlchew.js`) parsing. We are particularly concerned with replying to * messages and forwarding messages, and use the aforementioned libs to do the * gruntwork. * * For replying and forwarding, we synthesize messages so that there is always * a text part that is the area where the user can enter text which may be * followed by a read-only editable HTML block. If replying to a text/plain * message, the quoted text is placed in the text area. If replying to a * message with any text/html parts, we generate an HTML block for all parts. **/ define( [ 'exports', 'logic', './util', './mailchew-strings', './quotechew', './htmlchew' ], function( exports, logic, $util, $mailchewStrings, $quotechew, $htmlchew ) { var DESIRED_SNIPPET_LENGTH = 100; var scope = logic.scope('MailChew'); /** * Generate the default compose body for a new e-mail * @param {MailSenderIdentity} identity The current composer identity * @return {String} The text to be inserted into the body */ exports.generateBaseComposeBody = function generateBaseComposeBody(identity) { if (identity.signatureEnabled && identity.signature && identity.signature.length > 0) { var body = '\n\n--\n' + identity.signature; return body; } else { return ''; } }; var RE_RE = /^[Rr][Ee]:/; /** * Generate the reply subject for a message given the prior subject. This is * simply prepending "Re: " to the message if it does not already have an * "Re:" equivalent. * * Note, some clients/gateways (ex: I think the google groups web client? at * least whatever has a user-agent of G2/1.0) will structure mailing list * replies so they look like "[list] Re: blah" rather than the "Re: [list] blah" * that Thunderbird would produce. Thunderbird (and other clients) pretend like * that inner "Re:" does not exist, and so do we. * * We _always_ use the exact string "Re: " when prepending and do not localize. * This is done primarily for consistency with Thunderbird, but it also is * friendly to other e-mail applications out there. * * Thunderbird does support recognizing a * mail/chrome/messenger-region/region.properties property, * "mailnews.localizedRe" for letting locales specify other strings used by * clients that do attempt to localize "Re:". Thunderbird also supports a * weird "Re(###):" or "Re[###]:" idiom; see * http://mxr.mozilla.org/comm-central/ident?i=NS_MsgStripRE for more details. */ exports.generateReplySubject = function generateReplySubject(origSubject) { var re = 'Re: '; if (origSubject) { if (RE_RE.test(origSubject)) return origSubject; return re + origSubject; } return re; }; var FWD_FWD = /^[Ff][Ww][Dd]:/; /** * Generate the forward subject for a message given the prior subject. This is * simply prepending "Fwd: " to the message if it does not already have an * "Fwd:" equivalent. */ exports.generateForwardSubject = function generateForwardSubject(origSubject) { var fwd = 'Fwd: '; if (origSubject) { if (FWD_FWD.test(origSubject)) return origSubject; return fwd + origSubject; } return fwd; }; var l10n_wroteString = '{name} wrote', l10n_originalMessageString = 'Original Message'; /* * L10n strings for forward headers. In Thunderbird, these come from * mime.properties: * http://mxr.mozilla.org/comm-central/source/mail/locales/en-US/chrome/messenger/mime.properties * * The libmime logic that injects them is mime_insert_normal_headers: * http://mxr.mozilla.org/comm-central/source/mailnews/mime/src/mimedrft.cpp#791 * * Our dictionary maps from the lowercased header name to the human-readable * string. * * XXX actually do the l10n hookup for this */ var l10n_forward_header_labels = { subject: 'Subject', date: 'Date', from: 'From', replyTo: 'Reply-To', to: 'To', cc: 'CC' }; exports.setLocalizedStrings = function(strings) { l10n_wroteString = strings.wrote; l10n_originalMessageString = strings.originalMessage; l10n_forward_header_labels = strings.forwardHeaderLabels; }; // Grab the localized strings, if not available, listen for the event that // sets them. if ($mailchewStrings.strings) { exports.setLocalizedStrings($mailchewStrings.strings); } $mailchewStrings.events.on('strings', function(strings) { exports.setLocalizedStrings(strings); }); /** * Generate the reply body representation given info about the message we are * replying to. * * This does not include potentially required work such as propagating embedded * attachments or de-sanitizing links/embedded images/external images. */ exports.generateReplyBody = function generateReplyMessage(reps, authorPair, msgDate, identity, refGuid) { var useName = authorPair.name ? authorPair.name.trim() : authorPair.address; var textMsg = '\n\n' + l10n_wroteString.replace('{name}', useName) + ':\n', htmlMsg = null; for (var i = 0; i < reps.length; i++) { var repType = reps[i].type, rep = reps[i].content; if (repType === 'plain') { var replyText = $quotechew.generateReplyText(rep); // If we've gone HTML, this needs to get concatenated onto the HTML. if (htmlMsg) { htmlMsg += $htmlchew.wrapTextIntoSafeHTMLString(replyText) + '\n'; } // We haven't gone HTML yet, so this can all still be text. else { textMsg += replyText; } } else if (repType === 'html') { if (!htmlMsg) { htmlMsg = ''; // slice off the trailing newline of textMsg if (textMsg.slice(-1) === '\n') { textMsg = textMsg.slice(0, -1); } } // rep has already been sanitized and therefore all HTML tags are balanced // and so there should be no rude surprises from this simplistic looking // HTML creation. The message-id of the message never got sanitized, // however, so it needs to be escaped. Also, in some cases (Activesync), // we won't have the message-id so we can't cite it. htmlMsg += '<blockquote '; if (refGuid) { htmlMsg += 'cite="mid:' + $htmlchew.escapeAttrValue(refGuid) + '" '; } htmlMsg += 'type="cite">' + rep + '</blockquote>'; } } // Thunderbird's default is to put the signature after the quote, so us too. // (It also has complete control over all of this, but not us too.) if (identity.signature && identity.signatureEnabled) { // Thunderbird wraps its signature in a: // <pre class="moz-signature" cols="72"> construct and so we do too. if (htmlMsg) htmlMsg += $htmlchew.wrapTextIntoSafeHTMLString( identity.signature, 'pre', false, ['class', 'moz-signature', 'cols', '72']); else textMsg += '\n\n-- \n' + identity.signature; } return { text: textMsg, html: htmlMsg }; }; /** * Generate the body of an inline forward message. XXX we need to generate * the header summary which needs some localized strings. */ exports.generateForwardMessage = function(author, date, subject, headerInfo, bodyInfo, identity) { var textMsg = '\n\n', htmlMsg = null; if (identity.signature && identity.signatureEnabled) textMsg += '-- \n' + identity.signature + '\n\n'; textMsg += '-------- ' + l10n_originalMessageString + ' --------\n'; // XXX l10n! l10n! l10n! // Add the headers in the same order libmime adds them in // mime_insert_normal_headers so that any automated attempt to re-derive // the headers has a little bit of a chance (since the strings are // localized.) // : subject textMsg += l10n_forward_header_labels['subject'] + ': ' + subject + '\n'; // We do not track or remotely care about the 'resent' headers // : resent-comments // : resent-date // : resent-from // : resent-to // : resent-cc // : date textMsg += l10n_forward_header_labels['date'] + ': ' + new Date(date) + '\n'; // : from textMsg += l10n_forward_header_labels['from'] + ': ' + $util.formatAddresses([author]) + '\n'; // : reply-to if (headerInfo.replyTo) textMsg += l10n_forward_header_labels['replyTo'] + ': ' + $util.formatAddresses([headerInfo.replyTo]) + '\n'; // : organization // : to if (headerInfo.to) textMsg += l10n_forward_header_labels['to'] + ': ' + $util.formatAddresses(headerInfo.to) + '\n'; // : cc if (headerInfo.cc) textMsg += l10n_forward_header_labels['cc'] + ': ' + $util.formatAddresses(headerInfo.cc) + '\n'; // (bcc should never be forwarded) // : newsgroups // : followup-to // : references (only for newsgroups) textMsg += '\n'; var reps = bodyInfo.bodyReps; for (var i = 0; i < reps.length; i++) { var repType = reps[i].type, rep = reps[i].content; if (repType === 'plain') { var forwardText = $quotechew.generateForwardBodyText(rep); // If we've gone HTML, this needs to get concatenated onto the HTML. if (htmlMsg) { htmlMsg += $htmlchew.wrapTextIntoSafeHTMLString(forwardText) + '\n'; } // We haven't gone HTML yet, so this can all still be text. else { textMsg += forwardText; } } else if (repType === 'html') { if (!htmlMsg) { htmlMsg = ''; // slice off the trailing newline of textMsg if (textMsg.slice(-1) === '\n') { textMsg = textMsg.slice(0, -1); } } htmlMsg += rep; } } return { text: textMsg, html: htmlMsg }; }; var HTML_WRAP_TOP = '<html><body><body bgcolor="#FFFFFF" text="#000000">'; var HTML_WRAP_BOTTOM = '</body></html>'; /** * Combine the user's plaintext composition with the read-only HTML we provided * them into a final HTML representation. */ exports.mergeUserTextWithHTML = function mergeReplyTextWithHTML(text, html) { return HTML_WRAP_TOP + $htmlchew.wrapTextIntoSafeHTMLString(text, 'div') + html + HTML_WRAP_BOTTOM; }; /** * Generate the snippet and parsed body from the message body's content. */ exports.processMessageContent = function processMessageContent( content, type, isDownloaded, generateSnippet) { // Strip any trailing newline. if (content.slice(-1) === '\n') { content = content.slice(0, -1); } var parsedContent, snippet; switch (type) { case 'plain': try { parsedContent = $quotechew.quoteProcessTextBody(content); } catch (ex) { logic(scope, 'textChewError', { ex: ex }); // An empty content rep is better than nothing. parsedContent = []; } if (generateSnippet) { try { snippet = $quotechew.generateSnippet( parsedContent, DESIRED_SNIPPET_LENGTH ); } catch (ex) { logic(scope, 'textSnippetError', { ex: ex }); snippet = ''; } } break; case 'html': if (generateSnippet) { try { snippet = $htmlchew.generateSnippet(content); } catch (ex) { logic(scope, 'htmlSnippetError', { ex: ex }); snippet = ''; } } if (isDownloaded) { try { parsedContent = $htmlchew.sanitizeAndNormalizeHtml(content); } catch (ex) { logic(scope, 'htmlParseError', { ex: ex }); parsedContent = ''; } } break; } return { content: parsedContent, snippet: snippet }; }; }); // end define
import aspose.words as aw from docs_examples_base import DocsExamplesBase, MY_DIR, ARTIFACTS_DIR class WorkingWithPdfLoadOptions(DocsExamplesBase): def test_load_encrypted_pdf(self): #ExStart:LoadEncryptedPdf doc = aw.Document(MY_DIR + "Pdf Document.pdf") save_options = aw.saving.PdfSaveOptions() save_options.encryption_details = aw.saving.PdfEncryptionDetails("Aspose", None) doc.save(ARTIFACTS_DIR + "WorkingWithPdfLoadOptions.load_encrypted_pdf.pdf", save_options) load_options = aw.loading.PdfLoadOptions() load_options.password = "Aspose" load_options.load_format = aw.LoadFormat.PDF doc = aw.Document(ARTIFACTS_DIR + "WorkingWithPdfLoadOptions.load_encrypted_pdf.pdf", load_options) #ExEnd:LoadEncryptedPdf def test_load_page_range_of_pdf(self): #ExStart:LoadPageRangeOfPdf load_options = aw.loading.PdfLoadOptions() load_options.page_index = 0 load_options.page_count = 1 #ExStart:LoadPDF doc = aw.Document(MY_DIR + "Pdf Document.pdf", load_options) doc.save(ARTIFACTS_DIR + "WorkingWithPdfLoadOptions.load_page_range_of_pdf.pdf") #ExEnd:LoadPDF #ExEnd:LoadPageRangeOfPdf
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HPP5_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HPP5_ConnectedLHS. """ # Flag this instance as compiled now self.is_compiled = True super(HPP5_ConnectedLHS, self).__init__(name='HPP5_ConnectedLHS', num_nodes=0, edges=[]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """#=============================================================================== # This code is executed after the nodes in the LHS have been matched. # You can access a matched node labelled n by: PreNode('n'). # To access attribute x of node n, use: PreNode('n')['x']. # The given constraint must evaluate to a boolean expression: # returning True enables the rule to be applied, # returning False forbids the rule from being applied. #=============================================================================== return True """ self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'PP5') # Set the node attributes # match class State() node self.add_node() self.vs[0]["MT_pre__attr1"] = """ #=============================================================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access any attribute x of this node by: this['x']. # If the constraint relies on attribute values from other nodes, # use the LHS/NAC constraint instead. # The given constraint must evaluate to a boolean expression. #=============================================================================== return True """ self.vs[0]["MT_label__"] = """1""" self.vs[0]["MT_dirty__"] = False self.vs[0]["mm__"] = """MT_pre__State""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'') # match class State() node self.add_node() self.vs[1]["MT_pre__attr1"] = """ #=============================================================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access any attribute x of this node by: this['x']. # If the constraint relies on attribute values from other nodes, # use the LHS/NAC constraint instead. # The given constraint must evaluate to a boolean expression. #=============================================================================== return True """ self.vs[1]["MT_label__"] = """2""" self.vs[1]["MT_dirty__"] = False self.vs[1]["mm__"] = """MT_pre__State""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'') # Nodes that represent the edges of the property. # match association State--states-->State node self.add_node() self.vs[2]["MT_pre__attr1"] = """ #=============================================================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access any attribute x of this node by: this['x']. # If the constraint relies on attribute values from other nodes, # use the LHS/NAC constraint instead. # The given constraint must evaluate to a boolean expression. #=============================================================================== return attr_value == "states" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["MT_subtypes__"] = [] self.vs[2]["MT_dirty__"] = False self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'assoc2') # Add the edges self.add_edges([ (0,2), # match_class State() -> association states (2,1) # association states -> match_class State() ]) # Add the attribute equations self["equations"] = [((0,'isComposite'),('constant','true')), ] def eval_attr11(self, attr_value, this): #=============================================================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access any attribute x of this node by: this['x']. # If the constraint relies on attribute values from other nodes, # use the LHS/NAC constraint instead. # The given constraint must evaluate to a boolean expression. #=============================================================================== return True def eval_attr12(self, attr_value, this): #=============================================================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access any attribute x of this node by: this['x']. # If the constraint relies on attribute values from other nodes, # use the LHS/NAC constraint instead. # The given constraint must evaluate to a boolean expression. #=============================================================================== return True def eval_attr13(self, attr_value, this): #=============================================================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access any attribute x of this node by: this['x']. # If the constraint relies on attribute values from other nodes, # use the LHS/NAC constraint instead. # The given constraint must evaluate to a boolean expression. #=============================================================================== return attr_value == "states" def constraint(self, PreNode, graph): """ Executable constraint code. @param PreNode: Function taking an integer as parameter and returns the node corresponding to that label. """ #=============================================================================== # This code is executed after the nodes in the LHS have been matched. # You can access a matched node labelled n by: PreNode('n'). # To access attribute x of node n, use: PreNode('n')['x']. # The given constraint must evaluate to a boolean expression: # returning True enables the rule to be applied, # returning False forbids the rule from being applied. #=============================================================================== return True
from copy import deepcopy from typing import Dict, Any import torch.nn as nn from torch.nn.modules.batchnorm import BatchNorm2d from torch.nn.modules.normalization import LayerNorm class Norm_fn: def __init__(self, norm_cfg: Dict[str, Any]): self.norm_name = norm_cfg["name"] self.norm_cfg = norm_cfg def _bn_call(self, **runtime_kwargs) -> nn.Module: cfg = deepcopy(self.norm_cfg) cfg.update(runtime_kwargs) return BatchNorm2d( num_features=cfg["num_features"], eps=cfg.pop("eps", 1e-5), momentum=cfg.pop("momentum", 0.1), affine=cfg.pop("affine", True) ) def _ln_call(self, **runtime_kwargs) -> nn.Module: cfg = deepcopy(self.norm_cfg) cfg.update(runtime_kwargs) return LayerNorm( normalized_shape=cfg["normalized_shape"], eps=cfg.pop("eps", 1e-5), elementwise_affine=cfg.pop("momentum", True), ) def __call__(self, **runtime_kwargs) -> nn.Module: fn = { "bn": self._bn_call, "ln": self._ln_call } return fn[self.norm_name](**runtime_kwargs)
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Length, EqualTo, Email class RegisterForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=254)]) password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=254)]) confirm = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password')]) class LoginForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)]) password = PasswordField('Password', validators=[DataRequired()]) class EmailForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=254)]) class PasswordForm(FlaskForm): password = PasswordField('Password', validators=[DataRequired()])
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=jobs-options.js.map
const { Command } = require('discord.js-commando'); const { botname, botimage } = require('../../config'); const { MessageEmbed } = require('discord.js') module.exports = class piCommand extends Command { constructor(client) { super(client, { name: 'pi', group: 'divers', memberName: 'pi', description: 'give pi' }); } async run(message, args) { const embed = new MessageEmbed() .setColor('BLUE') .setTitle('Valeur de PI') .addField('Liste des 15 premiers nombres:', `\`\`\`css\n${Math.PI}\`\`\``) .setFooter(botname, botimage) .setTimestamp(); message.say(embed) } }
const util = require("../../utils/ll.js"); var app = getApp(); var page = 1; Page({ data:{ dataList: [], }, zaima: function (e) { var id = e.currentTarget.id; var list = this.data.dataList; var name = list[e.target.dataset.id].name; console.log(7894156, name) wx.navigateTo ({ url: "../../pages/index/index?iid="+id+"&name="+name }) }, zaima1: function (e) { var id = e.currentTarget.id; var name = e.target.dataset.name; console.log(7894156, name) wx.navigateTo({ url: "../../pages/index/index?iid=" + id + "&name=" + name }) }, getList: function(){ var that = this; util.req('fav/myFav', { sk: app.globalData.sk, page: page }, function (data) { console.log('kkkk123', data); that.setData({ pp: data.data }); }) }, getList1: function () { var that = this; wx.getStorage({ key: 'sk', success: function (res) { var sk = res.data; util.req('fav/myFav', { sk:sk, page: page }, function (data) { console.log('kkkk222', data); that.setData({ pp: data.data }); }) } }) }, getList2: function () { var that = this; util.req('FeiLei/zanzan', { }, function (data) { console.log('***',data) var list = data.data; that.setData({ dataList: list }); })}, quanbu:function(e){ wx.navigateTo({ url: "quanbu" }) }, // onLoad: function (options) { // var that = this // wx.request({ // url: 'http://localhost/pinche/index.php/Api/FeiLei/fenlei', // data: { // }, // method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT // header: { 'content-type': 'application/json' }, // 设置请求的 header // success: function (res) { // that.setData({ // dataList: res.data.square_list // }); // console.log(64351354, res.data.square_list) // setTimeout(function () { // wx.stopPullDownRefresh(); // }, 1000); // }, // fail: function (res) { // // fail // pageNo--; // }, // complete: function (res) { // // complete // wx.stopPullDownRefresh() // } // }) // }, onLoad: function (options) { this.getList2(); }, onShow: function () { page = 1; var that=this this.getList1(); setTimeout(function () { that.getList(); wx.stopPullDownRefresh(); },1500); }, onPullDownRefresh: function () { page = 1; this.getList(); this.getList2(); wx.stopPullDownRefresh(); } });
import os from typing import Callable, Dict, List import config from jobs.base.job import Job from .gdoc import push_gdoc # Functions for pushing individual source types PUSH_FUNCS: Dict[str, Callable[[List[str], str, dict], None]] = { "googledocs": push_gdoc, } class Push(Job): """ A job that pushes files from a project back to their source. """ name = "push" def do(self, paths: List[str], project: int, source: dict): # type: ignore """ Push `paths` within `project` to `source`. :param paths: A list of paths, within the project, to be pushed. :param project: The id of the project to push the paths from :param source: A dictionary with `type` and any other keys required to push the source (e.g. urls, authentication tokens). """ assert isinstance(source, dict), "source must be a dictionary" assert "type" in source, "source must have a type" assert ( isinstance(project, int) and project > 0 ), "project must be a positive integer" assert isinstance(paths, list) and len(paths) > 0, "paths must be non-empty" # Resolve the push function based on the source type typ = source["type"].lower() if typ not in PUSH_FUNCS: raise ValueError("Unknown source type: {}".format(typ)) push_func = PUSH_FUNCS[typ] return push_func(paths, os.getcwd(), source)
# Standard library imports import csv import json import os from typing import List, TextIO # Third-party imports import holidays # Third party imports import pandas as pd # First-party imports from gluonts.dataset.artificial._base import ( ArtificialDataset, ComplexSeasonalTimeSeries, ConstantDataset, ) def write_csv_row( time_series: List, freq: str, csv_file: TextIO, is_missing: bool, num_missing: int, ) -> None: csv_writer = csv.writer(csv_file) # convert to right date where MON == 0, ..., SUN == 6 week_dict = { 0: "MON", 1: "TUE", 2: "WED", 3: "THU", 4: "FRI", 5: "SAT", 6: "SUN", } for i in range(len(time_series)): data = time_series[i] timestamp = pd.Timestamp(data["start"]) freq_week_start = freq if freq_week_start == "W": freq_week_start = f"W-{week_dict[timestamp.weekday()]}" timestamp = pd.Timestamp(data["start"], freq=freq_week_start) item_id = int(data["item"]) for j, target in enumerate(data["target"]): # Using convention that there are no missing values before the start date if is_missing and j != 0 and j % num_missing == 0: timestamp += 1 continue # Skip every 4th entry else: timestamp_row = timestamp if freq in ["W", "D", "M"]: timestamp_row = timestamp.date() row = [item_id, timestamp_row, target] # Check if related time series is present if "feat_dynamic_real" in data.keys(): for feat_dynamic_real in data["feat_dynamic_real"]: row.append(feat_dynamic_real[j]) csv_writer.writerow(row) timestamp += 1 def generate_sf2( filename: str, time_series: List, is_missing: bool, num_missing: int ) -> None: # This function generates the test and train json files which will be converted to csv format if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) with open(filename, "w") as json_file: for ts in time_series: if is_missing: target = [] # type: List # For Forecast don't output feat_static_cat and feat_static_real for j, val in enumerate(ts["target"]): # only add ones that are not missing if j != 0 and j % num_missing == 0: target.append(None) else: target.append(val) ts["target"] = target ts.pop("feat_static_cat", None) ts.pop("feat_static_real", None) # Chop features in training set if "feat_dynamic_real" in ts.keys() and "train" in filename: # TODO: Fix for missing values for i, feat_dynamic_real in enumerate(ts["feat_dynamic_real"]): ts["feat_dynamic_real"][i] = feat_dynamic_real[ : len(ts["target"]) ] json.dump(ts, json_file) json_file.write("\n") def generate_sf2s_and_csv( file_path: str, folder_name: str, artificial_dataset: ArtificialDataset, is_missing: bool = False, num_missing: int = 4, ) -> None: file_path += f"{folder_name}" if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) freq = artificial_dataset.metadata.freq train_set = artificial_dataset.train generate_sf2(file_path + "train.json", train_set, is_missing, num_missing) test_set = artificial_dataset.test generate_sf2(file_path + "test.json", test_set, is_missing, num_missing) with open(file_path + "input_to_forecast.csv", "w") as csv_file: # Test set has training set with the additional values to predict write_csv_row(test_set, freq, csv_file, is_missing, num_missing) if __name__ == "__main__": num_timeseries = 1 file_path = "../../../datasets/synthetic/" generate_sf2s_and_csv(file_path, "constant/", ConstantDataset()) generate_sf2s_and_csv( file_path, "constant_missing/", ConstantDataset(), is_missing=True ) generate_sf2s_and_csv( file_path, "constant_random/", ConstantDataset(is_random_constant=True) ) generate_sf2s_and_csv( file_path, "constant_one_ts/", ConstantDataset( num_timeseries=num_timeseries, is_random_constant=True ), ) generate_sf2s_and_csv( file_path, "constant_diff_scales/", ConstantDataset(is_different_scales=True), ) generate_sf2s_and_csv( file_path, "constant_noise/", ConstantDataset(is_noise=True) ) generate_sf2s_and_csv( file_path, "constant_linear_trend/", ConstantDataset(is_trend=True) ) generate_sf2s_and_csv( file_path, "constant_linear_trend_noise/", ConstantDataset(is_noise=True, is_trend=True), ) generate_sf2s_and_csv( file_path, "constant_noise_long/", ConstantDataset(is_noise=True, is_long=True), ) generate_sf2s_and_csv( file_path, "constant_noise_short/", ConstantDataset(is_noise=True, is_short=True), ) generate_sf2s_and_csv( file_path, "constant_diff_scales_noise/", ConstantDataset(is_noise=True, is_different_scales=True), ) generate_sf2s_and_csv( file_path, "constant_zeros_and_nans/", ConstantDataset(is_nan=True) ) generate_sf2s_and_csv( # Requires is_random_constant to be set to True file_path, "constant_piecewise/", ConstantDataset(is_piecewise=True, is_random_constant=True), ) generate_sf2s_and_csv( file_path, "complex_seasonal_noise_scale/", ComplexSeasonalTimeSeries() ) generate_sf2s_and_csv( file_path, "complex_seasonal_noise/", ComplexSeasonalTimeSeries(is_scale=False), ) generate_sf2s_and_csv( file_path, "complex_seasonal/", ComplexSeasonalTimeSeries(is_scale=False, is_noise=False), ) generate_sf2s_and_csv( file_path, "complex_seasonal_missing/", ComplexSeasonalTimeSeries(proportion_missing_values=0.8), ) generate_sf2s_and_csv( file_path, "constant_missing_middle/", ConstantDataset(num_steps=500, num_missing_middle=100), ) generate_sf2s_and_csv( file_path, "complex_seasonal_random_start_dates_weekly/", ComplexSeasonalTimeSeries( freq_str="W", percentage_unique_timestamps=1, is_out_of_bounds_date=True, ), ) generate_sf2s_and_csv( file_path, "constant_promotions/", ConstantDataset( is_promotions=True, freq="M", start="2015-11-30", num_timeseries=100, num_steps=50, ), ) generate_sf2s_and_csv( file_path, "constant_holidays/", ConstantDataset( start="2017-07-01", freq="D", holidays=list(holidays.UnitedStates(years=[2017, 2018]).keys()), num_steps=365, ), )
# -*- coding: utf-8 -*- #test on python 3.4 ,python of lower version has different module organization. import http.server from http.server import HTTPServer, BaseHTTPRequestHandler import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler Handler.extensions_map={ '.manifest': 'text/cache-manifest', '.html': 'text/html', '.png': 'image/png', '.jpg': 'image/jpg', '.svg': 'image/svg+xml', '.css': 'text/css', '.js': 'application/x-javascript', '.wasm': 'application/wasm', '': 'application/octet-stream', # Default } httpd = socketserver.TCPServer(("", PORT), Handler) print("serving at port", PORT) httpd.serve_forever()
#!/usr/bin/python # # Copyright 2012 Google Inc. 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. """This example displays available placement strategies for a given search string. Results are limited to 10. Tags: strategy.getPlacementStrategiesByCriteria """ __author__ = '[email protected] (Joseph DiLallo)' import os import sys sys.path.insert(0, os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle import DfaClient def main(client): # Initialize appropriate service. placement_strategy_service = client.GetStrategyService( 'https://advertisersapitest.doubleclick.net', 'v1.19') # Create placement strategy search criteria structure. placement_strategy_search_criteria = { 'pageSize': '10' } # Get placement strategy record set. results = placement_strategy_service.GetPlacementStrategiesByCriteria( placement_strategy_search_criteria)[0] # Display placement strategy names, IDs and descriptions. if results['records']: for placement in results['records']: print ('Placement strategy with name \'%s\' and ID \'%s\' was found.' % (placement['name'], placement['id'])) else: print 'No placement strategies found for your criteria.' if __name__ == '__main__': # Initialize client object. client = DfaClient(path=os.path.join('..', '..', '..', '..')) main(client)
import React from "react" import Header from "../components/header" import Layout from "../components/layout" export default function PageNotFound() { return ( <Layout> <Header headerText="404" style={{ fontSize: `72px`, textAling: `center` }} /> <p>Ooops page not found</p> </Layout> ) }
// Copyright 2019 Google LLC // // 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 // // https://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. goog.module('proto.im.integration.MessageDefaultInstanceTest'); goog.setTestOnly(); const MessageA = goog.require('improto.protobuf.contrib.immutablejs.protos.MessageA'); const testSuite = goog.require('goog.testing.testSuite'); class MessageDefaultInstanceTest { testGetDefaultInstance() { assertTrue(MessageA.getDefaultInstance() instanceof MessageA); assertEquals( 'getDefaultInstance should always return the same instance.', MessageA.getDefaultInstance(), MessageA.getDefaultInstance()); } } testSuite(new MessageDefaultInstanceTest());
'use strict' const Joi = require('joi') const { isSemver } = require('../test-validators') const { ServiceTester } = require('../tester') const t = (module.exports = new ServiceTester({ id: 'GithubTag', title: 'Github Tag', pathPrefix: '/github', })) t.create('Tag') .get('/v/tag/expressjs/express.json') .expectBadge({ label: 'tag', message: isSemver, color: 'blue' }) t.create('Tag (inc pre-release)') .get('/v/tag/expressjs/express.json?include_prereleases') .expectBadge({ label: 'tag', message: isSemver, color: Joi.string().allow('blue', 'orange').required(), }) t.create('Tag (no tags)') .get('/v/tag/badges/daily-tests.json') .expectBadge({ label: 'tag', message: 'no tags found' }) t.create('Tag (repo not found)') .get('/v/tag/badges/helmets.json') .expectBadge({ label: 'tag', message: 'repo not found' }) // redirects t.create('Tag (legacy route: tag)') .get('/tag/photonstorm/phaser.svg') .expectRedirect('/github/v/tag/photonstorm/phaser.svg?sort=semver') t.create('Tag (legacy route: tag-pre)') .get('/tag-pre/photonstorm/phaser.svg') .expectRedirect( '/github/v/tag/photonstorm/phaser.svg?include_prereleases&sort=semver' ) t.create('Tag (legacy route: tag-date)') .get('/tag-date/photonstorm/phaser.svg') .expectRedirect('/github/v/tag/photonstorm/phaser.svg')
import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import PropTypes from 'prop-types'; import isEqual from 'lodash/isEqual'; import isUndefined from 'lodash/isUndefined'; import { FormGroup } from 'reactstrap'; import classNames from 'classnames'; import AvFeedback from './AvFeedback'; const htmlValidationAttrs = ['required']; const noop = () => {}; export default class AvCheckboxGroup extends Component { static propTypes = Object.assign({}, FormGroup.propTypes, { name: PropTypes.string.isRequired, }); static contextTypes = { FormCtrl: PropTypes.object.isRequired, }; static childContextTypes = { Group: PropTypes.object.isRequired, FormCtrl: PropTypes.object.isRequired, }; state = { invalidInputs: {}, dirtyInputs: {}, touchedInputs: {}, badInputs: {}, validate: {}, value: [], }; getChildContext() { if (!this.FormCtrl) { this.FormCtrl = { ...this.context.FormCtrl }; this.FormCtrl.register = this.registerInput.bind(this); this.FormCtrl.unregister = this.unregisterInput.bind(this); this.FormCtrl.validate = noop; } const updateGroup = async(e, value) => { if (e.target.checked) { this.value.push(value); } else { this.value = this.value.filter(item => item !== value); } this.setState({value: this.value}); await this.validate(); !this.context.FormCtrl.isTouched(this.props.name) && this.context.FormCtrl.setTouched(this.props.name); !this.context.FormCtrl.isDirty(this.props.name) && this.context.FormCtrl.setDirty(this.props.name); this.props.onChange && this.props.onChange(e, this.value); }; return { Group: { getProps: () => ({ name: this.props.name, inline: this.props.inline, required: this.props.required || !!(this.validations.required && this.validations.required.value), value: this.value, }), update: updateGroup, getValue: () => this.value, getInputState: this.getInputState.bind(this), }, FormCtrl: this.FormCtrl, }; } componentWillMount() { this.value = this.props.value || this.getDefaultValue().value; this.setState({ value: this.value }); this.updateValidations(); } componentWillReceiveProps(nextProps) { if (nextProps.name !== this.props.name) { this.context.FormCtrl.unregister(this); } if (nextProps.value !== this.props.value) { this.value = nextProps.value; this.setState({ value: nextProps.value }); } if (!isEqual(nextProps, this.props)) { this.updateValidations(nextProps); } } componentWillUnmount() { this.context.FormCtrl.unregister(this); } getValue() { return this.value; } getInputState() { return this.context.FormCtrl.getInputState(this.props.name); } getDefaultValue() { const key = 'defaultValue'; let value = []; if (!isUndefined(this.props[key])) { value = this.props[key]; } else if (!isUndefined(this.context.FormCtrl.getDefaultValue(this.props.name))) { value = this.context.FormCtrl.getDefaultValue(this.props.name); } return { key, value }; } async validate() { await this.context.FormCtrl.validate(this.props.name); this.updateInputs(); } update() { this.setState({}); this.updateInputs(); } _inputs = []; value = []; updateValidations(props = this.props) { this.validations = Object.assign({}, props.validate); Object.keys(props) .filter(val => htmlValidationAttrs.indexOf(val) > -1) .forEach(attr => { if (props[attr]) { this.validations[attr] = this.validations[attr] || { value: props[attr], }; } else { delete this.validations[attr]; } }); this.context.FormCtrl.register(this, this.update.bind(this)); this.validate(); } updateInputs() { this._inputs.forEach(input => findDOMNode(input).firstChild.setCustomValidity('Invalid.') && input.setState.call(input, {}) ); this.setState({}); } reset() { this.value = this.getDefaultValue().value; this.context.FormCtrl.setDirty(this.props.name, false); this.context.FormCtrl.setTouched(this.props.name, false); this.context.FormCtrl.setBad(this.props.name, false); this.setState({ value: this.value }); this.validate(); this.props.onReset && this.props.onReset(this.value); } registerInput(input) { if (this._inputs.indexOf(input) < 0) { this._inputs.push(input); } } unregisterInput(input) { this._inputs = this._inputs.filter(ipt => { return ipt !== input; }); } render() { const legend = this.props.label ? <legend>{this.props.label}</legend> : ''; const validation = this.getInputState(); const { errorMessage: omit1, validate: omit2, validationEvent: omit3, state: omit4, label: omit5, required: omit6, inline: omit7, children, ...attributes } = this.props; const touched = this.context.FormCtrl.isTouched(this.props.name); const hasError = this.context.FormCtrl.hasError(this.props.name); const classes = classNames( 'form-control border-0 p-0 h-auto', touched ? 'is-touched' : 'is-untouched', this.context.FormCtrl.isDirty(this.props.name) ? 'is-dirty' : 'is-pristine', this.context.FormCtrl.isBad(this.props.name) ? 'is-bad-input' : null, hasError ? 'av-invalid' : 'av-valid', touched && hasError && 'is-invalid' ); const groupClass = classNames( attributes.className, touched && hasError && 'was-validated' ); return ( <FormGroup tag="fieldset" {...attributes} className={groupClass}> {legend} <div className={classes}>{children}</div> <AvFeedback>{validation.errorMessage}</AvFeedback> </FormGroup> ); } }
/*! * bip70/index.js - bip70 for fcoin * Copyright (c) 2016-2017, Christopher Jeffrey (MIT License). * https://github.com/folm/fcoin */ 'use strict'; /** * @module bip70 */ exports.certs = require('./certs'); exports.PaymentACK = require('./paymentack'); exports.PaymentDetails = require('./paymentdetails'); exports.Payment = require('./payment'); exports.PaymentRequest = require('./paymentrequest'); exports.pk = require('./pk'); exports.x509 = require('./x509');
import React from "react"; import { connect } from "react-redux"; import {createOrder, createOrderItem, editOrderItem} from '../store' import ProductCardSingle from "./ProductCardSingle"; const SingleProduct = ({products, match}) => { const product = products.find(product => product.id === match.params.productId) if (!product) return '...loading' return ( <ProductCardSingle product={product} style={{maxWidth: 500, margin: '2rem'}}/> ) }; const mapDispatchToProps = (dispatch) => { return { createOrder: (user) => { dispatch(createOrder(user)) }, createOrderItem: (product) => { dispatch(createOrderItem(product)) }, editOrderItem: (orderItem) => { dispatch(editOrderItem(orderItem)) } } } export default connect((state) => state, mapDispatchToProps)(SingleProduct);
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import serialize from 'serialize-javascript'; import { allLanguages as languagesList } from 'shared/languagesList.js'; const determineHotAssets = query => ({ JS: [ 'http://localhost:8080/pdfjs-dist.js', 'http://localhost:8080/nprogress.js', 'http://localhost:8080/main.js', 'http://localhost:8080/vendor.js', ], CSS: [ `http://localhost:8080/CSS/vendor.css${query}`, `http://localhost:8080/CSS/main.css${query}`, 'http://localhost:8080/pdfjs-dist.css', ] }); const determineAssets = (assets, languageData) => ({ JS: [ assets['pdfjs-dist'].js, assets.nprogress.js, assets.vendor.js, assets.main.js, ], CSS: [ assets.vendor.css[languageData.rtl ? 1 : 0], assets.main.css[languageData.rtl ? 1 : 0], assets['pdfjs-dist'].css[0], ] }); const googelFonts = ( <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Mono:100,300,400,500,700|Roboto+Slab:100,300,400,700|Roboto:100,300,400,500,700,900" /> ); const headTag = (head, CSS, reduxData) => ( <head> {head.title.toComponent()} {head.meta.toComponent()} {head.link.toComponent()} <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {CSS.map((style, key) => <link key={key} href={style} rel="stylesheet" type="text/css" />)} <style type="text/css" dangerouslySetInnerHTML={{ __html: reduxData.settings.collection.get('customCSS') }} /> {googelFonts} <link rel="shortcut icon" href="/public/favicon.ico"/> </head> ); class Root extends Component { renderInitialData() { let innerHtml = ''; if (this.props.reduxData) { innerHtml += `window.__reduxData__ = ${serialize(this.props.reduxData, { isJSON: true })};`; } if (this.props.user) { innerHtml += `window.__user__ = ${serialize(this.props.user, { isJSON: true })};`; } return ( <script dangerouslySetInnerHTML={{ __html: innerHtml }} /> //eslint-disable-line ); } render() { const isHotReload = process.env.HOT; const { head, language, assets, reduxData, content } = this.props; const languageData = languagesList.find(l => l.key === language); const query = (languageData && languageData.rtl) ? '?rtl=true' : ''; const { JS, CSS } = isHotReload ? determineHotAssets(query) : determineAssets(assets, languageData); return ( <html lang={language}> {headTag(head, CSS, reduxData)} <body> <div id="root" dangerouslySetInnerHTML={{ __html: content }} /> {this.renderInitialData()} {head.script.toComponent()} {JS.map((file, index) => <script key={index} src={file} />)} </body> </html> ); } } Root.propTypes = { user: PropTypes.object, children: PropTypes.object, reduxData: PropTypes.object, head: PropTypes.object, content: PropTypes.string, language: PropTypes.string, assets: PropTypes.object }; export default Root;
// jspredict.js makes `jspredict` global on the window (or global) object, while Meteor expects a file-scoped global variable jspredict = this.jspredict; try { delete this.jspredict; } catch (e) { }
import React from 'react'; import {View} from 'react-native'; import PropTypes from 'prop-types'; import ScreenWrapper from '../components/ScreenWrapper'; import withLocalize, {withLocalizePropTypes} from '../components/withLocalize'; import KeyboardAvoidingView from '../components/KeyboardAvoidingView'; import HeaderWithCloseButton from '../components/HeaderWithCloseButton'; import Section from '../components/Section'; import Navigation from '../libs/Navigation/Navigation'; import styles from '../styles/styles'; import Text from '../components/Text'; import * as Expensicons from '../components/Icon/Expensicons'; import * as Illustrations from '../components/Icon/Illustrations'; import * as Report from '../libs/actions/Report'; import ROUTES from '../ROUTES'; const propTypes = { /** Route object from navigation */ route: PropTypes.shape({ params: PropTypes.shape({ /** The task ID to request the call for */ taskID: PropTypes.string, }), }).isRequired, ...withLocalizePropTypes, }; const GetAssistancePage = props => ( <ScreenWrapper> <KeyboardAvoidingView> <HeaderWithCloseButton title={props.translate('getAssistancePage.title')} onCloseButtonPress={() => Navigation.dismissModal(true)} shouldShowBackButton onBackButtonPress={() => Navigation.goBack()} /> <Section title={props.translate('getAssistancePage.subtitle')} icon={Illustrations.ConciergeExclamation} menuItems={[ { title: props.translate('getAssistancePage.chatWithConcierge'), onPress: () => Report.navigateToConciergeChat(), icon: Expensicons.ChatBubble, shouldShowRightIcon: true, }, { title: props.translate('getAssistancePage.requestSetupCall'), onPress: () => Navigation.navigate(ROUTES.getRequestCallRoute(props.route.params.taskID)), icon: Expensicons.Phone, shouldShowRightIcon: true, }, ]} > <View style={styles.mv4}> <Text>{props.translate('getAssistancePage.description')}</Text> </View> </Section> </KeyboardAvoidingView> </ScreenWrapper> ); GetAssistancePage.propTypes = propTypes; GetAssistancePage.displayName = 'GetAssistancePage'; export default withLocalize(GetAssistancePage);
let nock = require('nock'); module.exports.testInfo = {"container":"container156776197897508123"} nock('https://fakestorageaccount.blob.core.windows.net:443', {"encodedQueryParams":true}) .put('/container156776197897508123') .query(true) .reply(201, "", [ 'Content-Length', '0', 'Last-Modified', 'Fri, 06 Sep 2019 09:26:19 GMT', 'ETag', '"0x8D732AC465FC898"', 'Server', 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0', 'x-ms-request-id', '5a701609-e01e-0022-6295-64329c000000', 'x-ms-client-request-id', 'f12f3f34-453f-46b5-96d9-6c55ac91b450', 'x-ms-version', '2019-02-02', 'Date', 'Fri, 06 Sep 2019 09:26:19 GMT', 'Connection', 'close' ]); nock('https://fakestorageaccount.blob.core.windows.net:443', {"encodedQueryParams":true}) .put('/container156776197897508123') .query(true) .reply(201, "", [ 'Content-Length', '0', 'Last-Modified', 'Fri, 06 Sep 2019 09:26:19 GMT', 'ETag', '"0x8D732AC465FC898"', 'Server', 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0', 'x-ms-request-id', 'b4044a41-601e-011c-4c95-645bee000000', 'x-ms-client-request-id', 'c25d282b-d4e5-4526-8e6a-a408f400a0a1', 'x-ms-version', '2019-02-02', 'x-ms-lease-id', 'ca761232-ed42-11ce-bacd-00aa0057b223', 'Date', 'Fri, 06 Sep 2019 09:26:18 GMT', 'Connection', 'close' ]); nock('https://fakestorageaccount.blob.core.windows.net:443', {"encodedQueryParams":true}) .get('/container156776197897508123') .query(true) .reply(200, "", [ 'Content-Length', '0', 'Last-Modified', 'Fri, 06 Sep 2019 09:26:19 GMT', 'ETag', '"0x8D732AC465FC898"', 'Server', 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0', 'x-ms-request-id', 'e5a23ce7-101e-0009-5c95-64b250000000', 'x-ms-client-request-id', '6195f436-07d5-4e89-b227-e79ad137839d', 'x-ms-version', '2019-02-02', 'x-ms-lease-status', 'locked', 'x-ms-lease-state', 'leased', 'x-ms-lease-duration', 'fixed', 'x-ms-has-immutability-policy', 'false', 'x-ms-has-legal-hold', 'false', 'x-ms-default-encryption-scope', '$account-encryption-key', 'x-ms-deny-encryption-scope-override', 'false', 'Access-Control-Expose-Headers', 'x-ms-request-id,x-ms-client-request-id,Server,x-ms-version,Last-Modified,ETag,x-ms-lease-status,x-ms-lease-state,x-ms-lease-duration,x-ms-has-immutability-policy,x-ms-has-legal-hold,x-ms-default-encryption-scope,x-ms-deny-encryption-scope-override,Content-Length,Date,Transfer-Encoding,content-md5,x-ms-content-crc64', 'Access-Control-Allow-Origin', '*', 'Date', 'Fri, 06 Sep 2019 09:26:19 GMT', 'Connection', 'close' ]); nock('https://fakestorageaccount.blob.core.windows.net:443', {"encodedQueryParams":true}) .put('/container156776197897508123') .query(true) .reply(200, "", [ 'Content-Length', '0', 'Last-Modified', 'Fri, 06 Sep 2019 09:26:19 GMT', 'ETag', '"0x8D732AC465FC898"', 'Server', 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0', 'x-ms-request-id', '0a8f34f0-d01e-00dd-3795-640201000000', 'x-ms-client-request-id', '5322a70f-e4b4-4ff6-892c-399c9d133e1e', 'x-ms-version', '2019-02-02', 'Date', 'Fri, 06 Sep 2019 09:26:20 GMT', 'Connection', 'close' ]); nock('https://fakestorageaccount.blob.core.windows.net:443', {"encodedQueryParams":true}) .delete('/container156776197897508123') .query(true) .reply(202, "", [ 'Content-Length', '0', 'Server', 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0', 'x-ms-request-id', '54c2097a-401e-0004-4695-647a84000000', 'x-ms-client-request-id', '262e867c-44b6-4ff0-9076-9218c26bbc1b', 'x-ms-version', '2019-02-02', 'Date', 'Fri, 06 Sep 2019 09:26:20 GMT', 'Connection', 'close' ]);
city = str(input('Em que cidade você nasceu?')).strip().capitalize() print('Santo' in city) # cid = str(input('Cidade de Nascimento:')).strip() # print(cid[:5].upper() == 'SANTO')
# global import tensorflow as tf from typing import Union, Tuple, Optional, List # local # noinspection PyShadowingBuiltins def all( x: Union[tf.Tensor, tf.Variable], axis: Optional[Union[int, Tuple[int], List[int]]] = None, keepdims: bool = False, ) -> Union[tf.Tensor, tf.Variable]: if axis is None: num_dims = len(x.shape) axis = tuple(range(num_dims)) elif isinstance(axis, list): axis = tuple(axis) ret = tf.reduce_all(tf.cast(x, tf.bool), axis=axis, keepdims=keepdims) return ret # noinspection PyShadowingBuiltins def any( x: Union[tf.Tensor, tf.Variable], axis: Optional[Union[int, Tuple[int], List[int]]] = None, keepdims: bool = False, ) -> Union[tf.Tensor, tf.Variable]: if axis is None: num_dims = len(x.shape) axis = tuple(range(num_dims)) elif isinstance(axis, list): axis = tuple(axis) ret = tf.reduce_any(tf.cast(x, tf.bool), axis=axis, keepdims=keepdims) return ret
from copy import deepcopy from typing import Optional, Callable, List from dataclasses import dataclass import io from chess import pgn from chess import engine as computer from chess.pgn import Game from blunder_wunder.types import MoveClassification, Color from blunder_wunder.game import AnalysedMove, AnalysedGame MOVE_CLASSIFIER = Callable[[int], MoveClassification] @dataclass class EngineInfo: white_score: computer.Score suggested_line: List pov: computer.PovScore def color_from_board(board): return Color.WHITE if board.turn else Color.BLACK def evaluate_for_white( engine: computer.SimpleEngine, board, depth: computer.Limit ) -> EngineInfo: raw = engine.analyse(board, depth) return EngineInfo(raw["score"].white(), raw.get("pv", list()), raw["score"]) def classify_move(difference: int) -> MoveClassification: if difference == 0: return MoveClassification.TOP_ENGINE_MOVE elif difference < 25: return MoveClassification.EXCELLENT_MOVE elif difference < 50: return MoveClassification.GOOD_MOVE elif difference < 150: return MoveClassification.INACCURACY elif difference < 250: return MoveClassification.MISTAKE else: return MoveClassification.BLUNDER def determine_move_strength( color, human_move, engine_move, classifier: MOVE_CLASSIFIER ): if color == color.BLACK: difference = human_move - engine_move return classify_move(difference) difference = engine_move - human_move return classifier(difference) class GameAnalysis: def __init__( self, engine_path: str, depth: int = 20, time_limit: Optional[int] = None, move_classifier: Optional[MOVE_CLASSIFIER] = None, ): self.engine_path = engine_path self.config = None self.depth = ( computer.Limit(depth=depth) if time_limit is None else computer.Limit(time=time_limit) ) self._best_line = None self._move_classifier = ( classify_move if move_classifier is None else move_classifier ) def _is_mate(self, first_eval, second_eval) -> bool: return first_eval.is_mate() or second_eval.is_mate() def evaluate_mate(self, post_move, post_engine_move): if post_move.is_mate() and not post_engine_move.is_mate(): return MoveClassification.BLUNDER return MoveClassification.GOOD_MOVE def _analyse_move(self, engine: computer.SimpleEngine, board, move) -> AnalysedMove: current_color = color_from_board(board) pre_move_fen = board.fen() copied_board = deepcopy(board) board.push(move) post_move_fen = board.fen() human_eval: EngineInfo = evaluate_for_white(engine, board, self.depth) best_engine_move = engine.play(copied_board, self.depth) copied_board.push(best_engine_move.move) computer_eval: EngineInfo = evaluate_for_white(engine, copied_board, self.depth) if self._is_mate(human_eval.white_score, computer_eval.white_score): classification = self.evaluate_mate( human_eval.white_score, computer_eval.white_score ) else: classification = determine_move_strength( current_color, human_eval.white_score.score(), computer_eval.white_score.score(), self._move_classifier, ) analyzed_move = AnalysedMove( pre_move_fen, post_move_fen, current_color, str(move), str(best_engine_move.move), classification, human_eval.pov, self._best_line, ) self._best_line = human_eval.suggested_line return analyzed_move def analyse_game(self, game: Game, color: Optional[Color] = None): analysed_game = AnalysedGame(game.headers) board = game.board() engine: computer.SimpleEngine = computer.SimpleEngine.popen_uci( self.engine_path ) for move in game.mainline_moves(): current_player = color_from_board(board) if color and current_player != color: board.push(move) continue analysed_move = self._analyse_move(engine, board, move) analysed_game.moves.append(analysed_move) print(analysed_move) engine.close() return analysed_game def analyse_game_from_pgn( self, pgn_file_path: str, color: Optional[Color] = None ) -> AnalysedGame: with open(pgn_file_path, "r") as pgn_file: game = pgn.read_game(pgn_file) return self.analyse_game(game, color) def analyse_game_from_pgn_str(self, pgn_content: str) -> AnalysedGame: return self.analyse_game(pgn.read_game(io.StringIO(pgn_content)))
'use strict'; // Consumables controller angular.module('consumables').controller('ConsumablesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Consumables', function($scope, $stateParams, $location, Authentication, Consumables) { $scope.authentication = Authentication; // Create new Consumable $scope.create = function() { // Create new Consumable object var consumable = new Consumables ({ name: this.name }); // Redirect after save consumable.$save(function(response) { $location.path('consumables/' + response._id); // Clear form fields $scope.name = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Consumable $scope.remove = function(consumable) { if ( consumable ) { consumable.$remove(); for (var i in $scope.consumables) { if ($scope.consumables [i] === consumable) { $scope.consumables.splice(i, 1); } } } else { $scope.consumable.$remove(function() { $location.path('consumables'); }); } }; // Update existing Consumable $scope.update = function() { var consumable = $scope.consumable; consumable.$update(function() { $location.path('consumables/' + consumable._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Consumables $scope.find = function() { $scope.consumables = Consumables.query(); }; // Find existing Consumable $scope.findOne = function() { $scope.consumable = Consumables.get({ consumableId: $stateParams.consumableId }); }; } ]);
'use strict'; /** * "Moteur" de template minimaliste le but est de simplifié la créatoin * de "composant" pour par exemple coller à des données récupéré en ajax * Pas fait pour gérer des gros templates, * pas de compilation, pas de fonction. * Dans un premier temps les variables et ensuite du code libre, gestion d'une * valeur en cas d'abscence */ /** * Minimalistic "template engine". * The goal is to simplify "composant" creation, for exemple when use * ajax data to create DOM Element. * Not for big templates * No compilation, no functions. * Only access to passed variables and not found value. */ function Template() { } Template.config = { notFoundReplacment: null, htmlTrim: true }; Template.config.templatesSelector = function() { return document.querySelectorAll('.template'); }; Template.variableRegex = /{{\s*([a-zA-Z][\w-\.]*)\s*}}/g; Template.render = function (template, datas) { // Accept a Node or a Node Id if (typeof template === 'string') { template = document.getElementById(template); } if (template === null) { return null; } var result = template.innerHTML; // Remove useless withespace who can make style issues if (Template.config.htmlTrim) { result = result.trim().replace(/>(\s+)</g, '><'); result = result.trim().replace(/>(\s+){/g, '>{'); result = result.trim().replace(/}(\s+)</g, '}<'); } var variable; while ((variable = Template.variableRegex.exec(template.innerHTML)) !== null) { var property = ''; // Eval make eaysier the access to sub property eval('property = datas.' + variable[1]); if ( property === undefined && Template.config.notFoundReplacment !== null) { result = result.replace(variable[0], Template.config.notFoundReplacment); } else { result = result.replace(variable[0], property); } } return Template.strToDOM(result); }; // Not the worst way to turn a string in DOM Element Template.strToDOM = function (s){ var d=document ,i ,a=d.createElement("div") ,b=d.createElement('div'); a.innerHTML=s; while(i=a.firstChild)b.appendChild(i); return b.firstChild; }; document.addEventListener('DOMContentLoaded', function() { // Hide know templates for (var template of Template.config.templatesSelector()) { template.setAttribute('hidden', ''); } });
function Downloader() { this.isActive = false; this.realtime = false; this.chunkStart = 0; this.chunkSize = 0; this.totalLength = 0; this.chunkTimeout = 1000; this.url = null; this.callback = null; this.eof = false; this.setDownloadTimeoutCallback = null; } Downloader.prototype.setDownloadTimeoutCallback = function(callback) { this.setDownloadTimeoutCallback = callback; return this; } Downloader.prototype.reset = function() { this.chunkStart = 0; this.totalLength = 0; this.eof = false; return this; } Downloader.prototype.setRealTime = function(_realtime) { this.realtime = _realtime; return this; } Downloader.prototype.setChunkSize = function(_size) { this.chunkSize = _size; return this; } Downloader.prototype.setChunkStart = function(_start) { this.chunkStart = _start; this.eof = false; return this; } Downloader.prototype.setInterval = function(_timeout) { this.chunkTimeout = _timeout; return this; } Downloader.prototype.setUrl = function(_url) { this.url = _url; return this; } Downloader.prototype.setCallback = function(_callback) { this.callback = _callback; return this; } Downloader.prototype.isStopped = function () { return !this.isActive; } Downloader.prototype.getFileLength = function () { return this.totalLength; } Downloader.prototype.getFile = function() { var dl = this; if (dl.totalLength && this.chunkStart>= dl.totalLength) { dl.eof = true; } if (dl.eof === true) { Log.info("Downloader", "File download done."); this.callback(null, true); return; } var xhr = new XMLHttpRequest(); xhr.open("GET", this.url, true); xhr.responseType = "arraybuffer"; var range = null; xhr.start = this.chunkStart; var maxRange; if (this.chunkStart+this.chunkSize < Infinity) { range = 'bytes=' + this.chunkStart + '-'; maxRange = this.chunkStart+this.chunkSize-1; /* if the file length is known we limit the max range to that length */ /*if (dl.totalLength !== 0) { maxRange = Math.min(maxRange, dl.totalLength); }*/ range += maxRange; xhr.setRequestHeader('Range', range); } xhr.onerror = function(e) { dl.callback(null, false, true); } xhr.onreadystatechange = function (e) { if (xhr.status == 404) { dl.callback(null, false, true); } if ((xhr.status == 200 || xhr.status == 206 || xhr.status == 304 || xhr.status == 416) && xhr.readyState == this.DONE) { var rangeReceived = xhr.getResponseHeader("Content-Range"); Log.info("Downloader", "Received data range: "+rangeReceived); /* if the length of the file is not known, we get it from the response header */ if (!dl.totalLength && rangeReceived) { var sizeIndex; sizeIndex = rangeReceived.indexOf("/"); if (sizeIndex > -1) { dl.totalLength = +rangeReceived.slice(sizeIndex+1); } } dl.eof = (xhr.response.byteLength !== dl.chunkSize) || (xhr.response.byteLength === dl.totalLength); var buffer = xhr.response; buffer.fileStart = xhr.start; if (!buffer.fileStart) { // IE does not support adding properties to an ArrayBuffer generated by XHR buffer = buffer.slice(0); buffer.fileStart = xhr.start; } dl.callback(buffer, dl.eof); if (dl.isActive === true && dl.eof === false) { var timeoutDuration = 0; if (!dl.realtime) { timeoutDuration = dl.chunkTimeout; } else { timeoutDuration = computeWaitingTimeFromBuffer(video); } if (dl.setDownloadTimeoutCallback) dl.setDownloadTimeoutCallback(timeoutDuration); Log.info("Downloader", "Next download scheduled in "+Math.floor(timeoutDuration)+ ' ms.'); dl.timeoutID = window.setTimeout(dl.getFile.bind(dl), timeoutDuration); } else { /* end of file */ dl.isActive = false; } } }; if (dl.isActive) { Log.info("Downloader", "Fetching "+this.url+(range ? (" with range: "+range): "")); xhr.send(); } } Downloader.prototype.start = function() { Log.info("Downloader", "Starting file download"); this.chunkStart = 0; this.resume(); return this; } Downloader.prototype.resume = function() { Log.info("Downloader", "Resuming file download"); this.isActive = true; if (this.chunkSize === 0) { this.chunkSize = Infinity; } this.getFile(); return this; } Downloader.prototype.stop = function() { Log.info("Downloader", "Stopping file download"); this.isActive = false; if (this.timeoutID) { window.clearTimeout(this.timeoutID); delete this.timeoutID; } return this; }