How to use times method in Testcafe

Best JavaScript code snippet using testcafe

praytimes.js

Source:praytimes.js Github

copy

Full Screen

1//--------------------- Copyright Block ----------------------2/* 3PrayTimes.js: Prayer Times Calculator (ver 2.3)4Copyright (C) 2007-2011 PrayTimes.org5Developer: Hamid Zarrabi-Zadeh6License: GNU LGPL v3.07TERMS OF USE:8 Permission is granted to use this code, with or 9 without modification, in any website or application 10 provided that credit is given to the original work 11 with a link back to PrayTimes.org.12This program is distributed in the hope that it will 13be useful, but WITHOUT ANY WARRANTY. 14PLEASE DO NOT REMOVE THIS COPYRIGHT BLOCK.15 16*/ 17//--------------------- Help and Manual ----------------------18/*19User's Manual: 20http://praytimes.org/manual21Calculation Formulas: 22http://praytimes.org/calculation23//------------------------ User Interface -------------------------24 getTimes (date, coordinates [, timeZone [, dst [, timeFormat]]]) 25 26 setMethod (method) // set calculation method 27 adjust (parameters) // adjust calculation parameters 28 tune (offsets) // tune times by given offsets 29 getMethod () // get calculation method 30 getSetting () // get current calculation parameters31 getOffsets () // get current time offsets32//------------------------- Sample Usage --------------------------33 var PT = new PrayTimes('ISNA');34 var times = PT.getTimes(new Date(), [43, -80], -5);35 document.write('Sunrise = '+ times.sunrise)36*/37 38//----------------------- PrayTimes Class ------------------------39function PrayTimes(method) {40 //------------------------ Constants --------------------------41 var42 43 // Time Names44 timeNames = {45 tahajjud : 'Tahajjud',46 imsak : 'Imsak',47 fajr : 'Fajr',48 sunrise : 'Sunrise',49 dhuhr : 'Dhuhr',50 asr : 'Asr',51 sunset : 'Sunset',52 maghrib : 'Maghrib',53 isha : 'Isha',54 midnight : 'Midnight'55 },56 // Calculation Methods57 methods = {58 MWL: {59 name: 'Muslim World League',60 params: { fajr: 18, isha: 17 } },61 ISNA: {62 name: 'Islamic Society of North America (ISNA)',63 params: { fajr: 15, isha: 15 } },64 Egypt: {65 name: 'Egyptian General Authority of Survey',66 params: { fajr: 19.5, isha: 17.5 } },67 Makkah: {68 name: 'Umm Al-Qura University, Makkah',69 params: { fajr: 18.5, isha: '90 min' } }, // fajr was 19 degrees before 1430 hijri70 Karachi: {71 name: 'University of Islamic Sciences, Karachi',72 params: { fajr: 18, isha: 18 } },73 Tehran: {74 name: 'Institute of Geophysics, University of Tehran',75 params: { fajr: 17.7, isha: 14, maghrib: 4.5, midnight: 'Jafari' } }, // isha is not explicitly specified in this method76 Jafari: {77 name: 'Shia Ithna-Ashari, Leva Institute, Qum',78 params: { fajr: 16, isha: 14, maghrib: 4, midnight: 'Jafari' } },79 Algeria: {80 name: 'Algerian Minister of Religious Affairs and Wakfs',81 params: { fajr: 18, isha: 17 } },82 Diyanet: {83 name: 'Diyanet İşleri Başkanlığı',84 params: { fajr: 18, isha: 17 } },85 EgyptBis: {86 name: 'Egyptian General Authority (Bis)',87 params: { fajr: 20, isha: 18 } },88 FixedIsha: {89 name: 'Fixed Isha Angle Interval',90 params: { fajr: 19.5, isha: '90 min' } },91 FranceUOIF: {92 name: 'France UOIF - Angle 12°',93 params: { fajr: 12, isha: 12 } },94 France15: {95 name: 'France - Angle 15°',96 params: { fajr: 15, isha: 15 } },97 France18: {98 name: 'France - Angle 18°',99 params: { fajr: 18, isha: 18 } },100 JAKIM: {101 name: 'JAKIM (Jabatan Kemajuan Islam Malaysia)',102 params: { fajr: 20, isha: 18 } },103 MUIS: {104 name: 'MUIS (Majlis Ugama Islam Singapura)',105 params: { fajr: 20, isha: 18 } },106 Kemenag: {107 name: 'SIHAT/KEMENAG (Kementerian Agama RI)',108 params: { fajr: 20, isha: 18 } },109 Tunisia: {110 name: 'Tunisian Ministry of Religious Affairs',111 params: { fajr: 18, isha: 18 } },112 AwqafUAE: {113 name: 'UAE General Authority of Islamic Affairs And Endowments',114 params: { fajr: 19.5, isha: '90 min' } },115 LondonUIPT: {116 name: 'London Unified Islamic Prayer Timetable',117 params: { fajr: 18, isha: 18 } },118 },119 // Default Parameters in Calculation Methods120 defaultParams = {121 maghrib: '0 min', midnight: 'Standard'122 },123 124 125 //----------------------- Parameter Values ----------------------126 /*127 128 // Asr Juristic Methods129 asrJuristics = [ 130 'Standard', // Shafi`i, Maliki, Ja`fari, Hanbali131 'Hanafi' // Hanafi132 ],133 // Midnight Mode134 midnightMethods = [ 135 'Standard', // Mid Sunset to Sunrise136 'Jafari' // Mid Sunset to Fajr137 ],138 // Adjust Methods for Higher Latitudes139 highLatMethods = [140 'NightMiddle', // middle of night141 'AngleBased', // angle/60th of night142 'OneSeventh', // 1/7th of night143 'None' // No adjustment144 ],145 // Time Formats146 timeFormats = [147 '24h', // 24-hour format148 '12h', // 12-hour format149 '12hNS', // 12-hour format with no suffix150 'Float' // floating point number 151 ],152 */ 153 //---------------------- Default Settings --------------------154 155 calcMethod = 'MWL',156 // do not change anything here; use adjust method instead157 setting = { 158 imsak : '10 min',159 dhuhr : '0 min', 160 asr : 'Standard',161 highLats : 'NightMiddle'162 },163 timeFormat = '24h',164 timeSuffixes = ['am', 'pm'],165 invalidTime = '-----',166 timePrecision = 'show',167 numIterations = 1,168 offset = {},169 //----------------------- Local Variables ---------------------170 lat, lng, elv, // coordinates171 timeZone, jDate; // time variables172 173 //---------------------- Initialization -----------------------174 175 176 // set methods defaults177 var defParams = defaultParams;178 for (var i in methods) {179 var params = methods[i].params;180 for (var j in defParams)181 if ((typeof(params[j]) == 'undefined'))182 params[j] = defParams[j];183 };184 // initialize settings185 calcMethod = methods[method] ? method : calcMethod;186 var params = methods[calcMethod].params;187 for (var id in params)188 setting[id] = params[id];189 // init time offsets190 for (var i in timeNames)191 offset[i] = 0;192 193 194 //----------------------- Public Functions ------------------------195 return {196 197 // set calculation method 198 setMethod: function(method) {199 if (methods[method]) {200 this.adjust(methods[method].params);201 calcMethod = method;202 }203 },204 // set calculating parameters205 adjust: function(params) {206 for (var id in params)207 setting[id] = params[id];208 },209 // set time offsets210 tune: function(timeOffsets) {211 for (var i in timeOffsets)212 offset[i] = timeOffsets[i];213 },214 // get current calculation method215 getMethod: function() { return calcMethod; },216 // get current setting217 getSetting: function() { return setting; },218 // get current time offsets219 getOffsets: function() { return offset; },220 // get default calc parametrs221 getDefaults: function() { return methods; },222 // return prayer times for a given date223 getTimes: function(date, coords, timezone, dst, format, precision) {224 lat = 1* coords[0];225 lng = 1* coords[1]; 226 elv = coords[2] ? 1* coords[2] : 0;227 timeFormat = format || timeFormat;228 timePrecision = precision || timePrecision;229 if (date.constructor === Date)230 date = [date.getFullYear(), date.getMonth()+ 1, date.getDate()];231 if (typeof(timezone) == 'undefined' || timezone == 'auto')232 timezone = this.getTimeZone(date);233 if (typeof(dst) == 'undefined' || dst == 'auto') 234 dst = this.getDst(date);235 timeZone = 1* timezone+ (1* dst ? 1 : 0);236 jDate = this.julian(date[0], date[1], date[2])- lng/ (15* 24);237 238 return this.computeTimes();239 },240 // convert float time to the given format (see timeFormats)241 getFormattedTime: function(time, format, suffixes) {242 if (isNaN(time))243 return invalidTime;244 if (format == 'Float') return time;245 suffixes = suffixes || timeSuffixes;246 time = DMath.fixHour(time + 0.0 / 60); // don't add 0.5 minutes to round247 var hours = Math.floor(time); 248 var minutes = Math.floor((time - hours)* 60);249 var seconds = Math.floor((((time - hours)* 60) - minutes) * 60);250 //console.log(time + " - " + hours + ":" + minutes + ":" + seconds);251 var suffix = (format == '12h') ? suffixes[hours < 12 ? 0 : 1] : '';252 var hour = (format == '24h') ? this.twoDigitsFormat(hours) : ((hours+ 12 -1)% 12+ 1);253 if (timePrecision == 'show') {254 return hour+ ':' + this.twoDigitsFormat(minutes) + ':' + this.twoDigitsFormat(seconds) + (suffix ? ' '+ suffix : '');255 } else {256 return hour+ ':' + this.twoDigitsFormat(minutes) + (suffix ? ' '+ suffix : '');257 }258 },259 //---------------------- Calculation Functions -----------------------260 // compute mid-day time261 midDay: function(time) {262 var eqt = this.sunPosition(jDate+ time).equation;263 var noon = DMath.fixHour(12- eqt);264 return noon;265 },266 // compute the time at which sun reaches a specific angle below horizon267 sunAngleTime: function(angle, time, direction) {268 var decl = this.sunPosition(jDate+ time).declination;269 var noon = this.midDay(time);270 var t = 1/15* DMath.arccos((-DMath.sin(angle)- DMath.sin(decl)* DMath.sin(lat))/ 271 (DMath.cos(decl)* DMath.cos(lat)));272 return noon+ (direction == 'ccw' ? -t : t);273 },274 // compute asr time 275 asrTime: function(factor, time) { 276 var decl = this.sunPosition(jDate+ time).declination;277 var angle = -DMath.arccot(factor+ DMath.tan(Math.abs(lat- decl)));278 return this.sunAngleTime(angle, time);279 },280 // compute declination angle of sun and equation of time281 // Ref: http://aa.usno.navy.mil/faq/docs/SunApprox.php282 sunPosition: function(jd) {283 var D = jd - 2451545.0;284 var g = DMath.fixAngle(357.529 + 0.98560028* D);285 var q = DMath.fixAngle(280.459 + 0.98564736* D);286 var L = DMath.fixAngle(q + 1.915* DMath.sin(g) + 0.020* DMath.sin(2*g));287 var R = 1.00014 - 0.01671* DMath.cos(g) - 0.00014* DMath.cos(2*g);288 var e = 23.439 - 0.00000036* D;289 var RA = DMath.arctan2(DMath.cos(e)* DMath.sin(L), DMath.cos(L))/ 15;290 var eqt = q/15 - DMath.fixHour(RA);291 var decl = DMath.arcsin(DMath.sin(e)* DMath.sin(L));292 return {declination: decl, equation: eqt};293 },294 // convert Gregorian date to Julian day295 // Ref: Astronomical Algorithms by Jean Meeus296 julian: function(year, month, day) {297 if (month <= 2) {298 year -= 1;299 month += 12;300 };301 var A = Math.floor(year/ 100);302 var B = 2- A+ Math.floor(A/ 4);303 var JD = Math.floor(365.25* (year+ 4716))+ Math.floor(30.6001* (month+ 1))+ day+ B- 1524.5;304 return JD;305 },306 307 //---------------------- Compute Prayer Times -----------------------308 // compute prayer times at given julian date309 computePrayerTimes: function(times) {310 times = this.dayPortion(times);311 var params = setting;312 313 var imsak = this.sunAngleTime(this.eval(params.imsak), times.imsak, 'ccw');314 var fajr = this.sunAngleTime(this.eval(params.fajr), times.fajr, 'ccw');315 var sunrise = this.sunAngleTime(this.riseSetAngle(), times.sunrise, 'ccw'); 316 var dhuhr = this.midDay(times.dhuhr);317 var asr = this.asrTime(this.asrFactor(params.asr), times.asr);318 var sunset = this.sunAngleTime(this.riseSetAngle(), times.sunset);;319 var maghrib = this.sunAngleTime(this.eval(params.maghrib), times.maghrib);320 var isha = this.sunAngleTime(this.eval(params.isha), times.isha);321 return {322 imsak: imsak, fajr: fajr, sunrise: sunrise, dhuhr: dhuhr, 323 asr: asr, sunset: sunset, maghrib: maghrib, isha: isha324 };325 },326 // compute prayer times 327 computeTimes: function() {328 // default times329 var times = { 330 imsak: 5, fajr: 5, sunrise: 6, dhuhr: 12, 331 asr: 13, sunset: 18, maghrib: 18, isha: 18332 };333 // main iterations334 for (var i=1 ; i<=numIterations ; i++) 335 times = this.computePrayerTimes(times);336 times = this.adjustTimes(times);337 338 // add midnight time339 times.midnight = (setting.midnight == 'Jafari') ? 340 times.sunset+ this.timeDiff(times.sunset, times.fajr)/ 2 :341 times.sunset+ this.timeDiff(times.sunset, times.sunrise)/ 2;342 // add tahajjud time343 times.tahajjud = times.sunset+ (this.timeDiff(times.sunset, times.sunrise)/ 3) * 2;344 times = this.tuneTimes(times);345 return this.modifyFormats(times);346 },347 // adjust times 348 adjustTimes: function(times) {349 var params = setting;350 for (var i in times)351 times[i] += timeZone- lng/ 15;352 353 if (params.highLats != 'None')354 times = this.adjustHighLats(times);355 356 if (this.isMin(params.imsak))357 times.imsak = times.fajr- this.eval(params.imsak)/ 60;358 if (this.isMin(params.maghrib))359 times.maghrib = times.sunset+ this.eval(params.maghrib)/ 60;360 if (this.isMin(params.isha))361 times.isha = times.maghrib+ this.eval(params.isha)/ 60;362 times.dhuhr += this.eval(params.dhuhr)/ 60; 363 return times;364 },365 // get asr shadow factor366 asrFactor: function(asrParam) {367 var factor = {Standard: 1, Hanafi: 2}[asrParam];368 return factor || this.eval(asrParam);369 },370 // return sun angle for sunset/sunrise371 riseSetAngle: function() {372 //var earthRad = 6371009; // in meters373 //var angle = DMath.arccos(earthRad/(earthRad+ elv));374 var angle = 0.0347* Math.sqrt(elv); // an approximation375 return 0.833+ angle;376 },377 // apply offsets to the times378 tuneTimes: function(times) {379 for (var i in times)380 times[i] += offset[i]/ 60; 381 return times;382 },383 // convert times to given time format384 modifyFormats: function(times) {385 for (var i in times)386 times[i] = this.getFormattedTime(times[i], timeFormat); 387 return times;388 },389 // adjust times for locations in higher latitudes390 adjustHighLats: function(times) {391 var params = setting;392 var nightTime = this.timeDiff(times.sunset, times.sunrise); 393 times.imsak = this.adjustHLTime(times.imsak, times.sunrise, this.eval(params.imsak), nightTime, 'ccw');394 times.fajr = this.adjustHLTime(times.fajr, times.sunrise, this.eval(params.fajr), nightTime, 'ccw');395 times.isha = this.adjustHLTime(times.isha, times.sunset, this.eval(params.isha), nightTime);396 times.maghrib = this.adjustHLTime(times.maghrib, times.sunset, this.eval(params.maghrib), nightTime);397 398 return times;399 },400 401 // adjust a time for higher latitudes402 adjustHLTime: function(time, base, angle, night, direction) {403 var portion = this.nightPortion(angle, night);404 var timeDiff = (direction == 'ccw') ? 405 this.timeDiff(time, base):406 this.timeDiff(base, time);407 if (isNaN(time) || timeDiff > portion) 408 time = base+ (direction == 'ccw' ? -portion : portion);409 return time;410 },411 412 // the night portion used for adjusting times in higher latitudes413 nightPortion: function(angle, night) {414 var method = setting.highLats;415 var portion = 1/2 // MidNight416 if (method == 'AngleBased')417 portion = 1/60* angle;418 if (method == 'OneSeventh')419 portion = 1/7;420 return portion* night;421 },422 // convert hours to day portions 423 dayPortion: function(times) {424 for (var i in times)425 times[i] /= 24;426 return times;427 },428 //---------------------- Time Zone Functions -----------------------429 // get local time zone430 getTimeZone: function(date) {431 var year = date[0];432 var t1 = this.gmtOffset([year, 0, 1]);433 var t2 = this.gmtOffset([year, 6, 1]);434 return Math.min(t1, t2);435 },436 437 // get daylight saving for a given date438 getDst: function(date) {439 return 1* (this.gmtOffset(date) != this.getTimeZone(date));440 },441 // GMT offset for a given date442 gmtOffset: function(date) {443 var localDate = new Date(date[0], date[1]- 1, date[2], 12, 0, 0, 0);444 var GMTString = localDate.toGMTString();445 var GMTDate = new Date(GMTString.substring(0, GMTString.lastIndexOf(' ')- 1));446 var hoursDiff = (localDate- GMTDate) / (1000* 60* 60);447 return hoursDiff;448 },449 450 //---------------------- Misc Functions -----------------------451 // convert given string into a number452 eval: function(str) {453 return 1* (str+ '').split(/[^0-9.+-]/)[0];454 },455 // detect if input contains 'min'456 isMin: function(arg) {457 return (arg+ '').indexOf('min') != -1;458 },459 // compute the difference between two times 460 timeDiff: function(time1, time2) {461 return DMath.fixHour(time2- time1);462 },463 // add a leading 0 if necessary464 twoDigitsFormat: function(num) {465 return (num <10) ? '0'+ num : num;466 }467 468}}469//---------------------- Degree-Based Math Class -----------------------470var DMath = {471 dtr: function(d) { return (d * Math.PI) / 180.0; },472 rtd: function(r) { return (r * 180.0) / Math.PI; },473 sin: function(d) { return Math.sin(this.dtr(d)); },474 cos: function(d) { return Math.cos(this.dtr(d)); },475 tan: function(d) { return Math.tan(this.dtr(d)); },476 arcsin: function(d) { return this.rtd(Math.asin(d)); },477 arccos: function(d) { return this.rtd(Math.acos(d)); },478 arctan: function(d) { return this.rtd(Math.atan(d)); },479 arccot: function(x) { return this.rtd(Math.atan(1/x)); },480 arctan2: function(y, x) { return this.rtd(Math.atan2(y, x)); },481 fixAngle: function(a) { return this.fix(a, 360); },482 fixHour: function(a) { return this.fix(a, 24 ); },483 fix: function(a, b) { 484 a = a- b* (Math.floor(a/ b));485 return (a < 0) ? a+ b : a;486 }487}488//---------------------- Init Object -----------------------...

Full Screen

Full Screen

KeyframeTrack.js

Source:KeyframeTrack.js Github

copy

Full Screen

1import {2 InterpolateLinear,3 InterpolateSmooth,4 InterpolateDiscrete5} from '../constants.js';6import { CubicInterpolant } from '../math/interpolants/CubicInterpolant.js';7import { LinearInterpolant } from '../math/interpolants/LinearInterpolant.js';8import { DiscreteInterpolant } from '../math/interpolants/DiscreteInterpolant.js';9import { AnimationUtils } from './AnimationUtils.js';10class KeyframeTrack {11 constructor( name, times, values, interpolation ) {12 if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );13 if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );14 this.name = name;15 this.times = AnimationUtils.convertArray( times, this.TimeBufferType );16 this.values = AnimationUtils.convertArray( values, this.ValueBufferType );17 this.setInterpolation( interpolation || this.DefaultInterpolation );18 }19 // Serialization (in static context, because of constructor invocation20 // and automatic invocation of .toJSON):21 static toJSON( track ) {22 const trackType = track.constructor;23 let json;24 // derived classes can define a static toJSON method25 if ( trackType.toJSON !== this.toJSON ) {26 json = trackType.toJSON( track );27 } else {28 // by default, we assume the data can be serialized as-is29 json = {30 'name': track.name,31 'times': AnimationUtils.convertArray( track.times, Array ),32 'values': AnimationUtils.convertArray( track.values, Array )33 };34 const interpolation = track.getInterpolation();35 if ( interpolation !== track.DefaultInterpolation ) {36 json.interpolation = interpolation;37 }38 }39 json.type = track.ValueTypeName; // mandatory40 return json;41 }42 InterpolantFactoryMethodDiscrete( result ) {43 return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );44 }45 InterpolantFactoryMethodLinear( result ) {46 return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );47 }48 InterpolantFactoryMethodSmooth( result ) {49 return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );50 }51 setInterpolation( interpolation ) {52 let factoryMethod;53 switch ( interpolation ) {54 case InterpolateDiscrete:55 factoryMethod = this.InterpolantFactoryMethodDiscrete;56 break;57 case InterpolateLinear:58 factoryMethod = this.InterpolantFactoryMethodLinear;59 break;60 case InterpolateSmooth:61 factoryMethod = this.InterpolantFactoryMethodSmooth;62 break;63 }64 if ( factoryMethod === undefined ) {65 const message = 'unsupported interpolation for ' +66 this.ValueTypeName + ' keyframe track named ' + this.name;67 if ( this.createInterpolant === undefined ) {68 // fall back to default, unless the default itself is messed up69 if ( interpolation !== this.DefaultInterpolation ) {70 this.setInterpolation( this.DefaultInterpolation );71 } else {72 throw new Error( message ); // fatal, in this case73 }74 }75 console.warn( 'THREE.KeyframeTrack:', message );76 return this;77 }78 this.createInterpolant = factoryMethod;79 return this;80 }81 getInterpolation() {82 switch ( this.createInterpolant ) {83 case this.InterpolantFactoryMethodDiscrete:84 return InterpolateDiscrete;85 case this.InterpolantFactoryMethodLinear:86 return InterpolateLinear;87 case this.InterpolantFactoryMethodSmooth:88 return InterpolateSmooth;89 }90 }91 getValueSize() {92 return this.values.length / this.times.length;93 }94 // move all keyframes either forwards or backwards in time95 shift( timeOffset ) {96 if ( timeOffset !== 0.0 ) {97 const times = this.times;98 for ( let i = 0, n = times.length; i !== n; ++ i ) {99 times[ i ] += timeOffset;100 }101 }102 return this;103 }104 // scale all keyframe times by a factor (useful for frame <-> seconds conversions)105 scale( timeScale ) {106 if ( timeScale !== 1.0 ) {107 const times = this.times;108 for ( let i = 0, n = times.length; i !== n; ++ i ) {109 times[ i ] *= timeScale;110 }111 }112 return this;113 }114 // removes keyframes before and after animation without changing any values within the range [startTime, endTime].115 // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values116 trim( startTime, endTime ) {117 const times = this.times,118 nKeys = times.length;119 let from = 0,120 to = nKeys - 1;121 while ( from !== nKeys && times[ from ] < startTime ) {122 ++ from;123 }124 while ( to !== - 1 && times[ to ] > endTime ) {125 -- to;126 }127 ++ to; // inclusive -> exclusive bound128 if ( from !== 0 || to !== nKeys ) {129 // empty tracks are forbidden, so keep at least one keyframe130 if ( from >= to ) {131 to = Math.max( to, 1 );132 from = to - 1;133 }134 const stride = this.getValueSize();135 this.times = AnimationUtils.arraySlice( times, from, to );136 this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );137 }138 return this;139 }140 // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable141 validate() {142 let valid = true;143 const valueSize = this.getValueSize();144 if ( valueSize - Math.floor( valueSize ) !== 0 ) {145 console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );146 valid = false;147 }148 const times = this.times,149 values = this.values,150 nKeys = times.length;151 if ( nKeys === 0 ) {152 console.error( 'THREE.KeyframeTrack: Track is empty.', this );153 valid = false;154 }155 let prevTime = null;156 for ( let i = 0; i !== nKeys; i ++ ) {157 const currTime = times[ i ];158 if ( typeof currTime === 'number' && isNaN( currTime ) ) {159 console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );160 valid = false;161 break;162 }163 if ( prevTime !== null && prevTime > currTime ) {164 console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );165 valid = false;166 break;167 }168 prevTime = currTime;169 }170 if ( values !== undefined ) {171 if ( AnimationUtils.isTypedArray( values ) ) {172 for ( let i = 0, n = values.length; i !== n; ++ i ) {173 const value = values[ i ];174 if ( isNaN( value ) ) {175 console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );176 valid = false;177 break;178 }179 }180 }181 }182 return valid;183 }184 // removes equivalent sequential keys as common in morph target sequences185 // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)186 optimize() {187 // times or values may be shared with other tracks, so overwriting is unsafe188 const times = AnimationUtils.arraySlice( this.times ),189 values = AnimationUtils.arraySlice( this.values ),190 stride = this.getValueSize(),191 smoothInterpolation = this.getInterpolation() === InterpolateSmooth,192 lastIndex = times.length - 1;193 let writeIndex = 1;194 for ( let i = 1; i < lastIndex; ++ i ) {195 let keep = false;196 const time = times[ i ];197 const timeNext = times[ i + 1 ];198 // remove adjacent keyframes scheduled at the same time199 if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {200 if ( ! smoothInterpolation ) {201 // remove unnecessary keyframes same as their neighbors202 const offset = i * stride,203 offsetP = offset - stride,204 offsetN = offset + stride;205 for ( let j = 0; j !== stride; ++ j ) {206 const value = values[ offset + j ];207 if ( value !== values[ offsetP + j ] ||208 value !== values[ offsetN + j ] ) {209 keep = true;210 break;211 }212 }213 } else {214 keep = true;215 }216 }217 // in-place compaction218 if ( keep ) {219 if ( i !== writeIndex ) {220 times[ writeIndex ] = times[ i ];221 const readOffset = i * stride,222 writeOffset = writeIndex * stride;223 for ( let j = 0; j !== stride; ++ j ) {224 values[ writeOffset + j ] = values[ readOffset + j ];225 }226 }227 ++ writeIndex;228 }229 }230 // flush last keyframe (compaction looks ahead)231 if ( lastIndex > 0 ) {232 times[ writeIndex ] = times[ lastIndex ];233 for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {234 values[ writeOffset + j ] = values[ readOffset + j ];235 }236 ++ writeIndex;237 }238 if ( writeIndex !== times.length ) {239 this.times = AnimationUtils.arraySlice( times, 0, writeIndex );240 this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );241 } else {242 this.times = times;243 this.values = values;244 }245 return this;246 }247 clone() {248 const times = AnimationUtils.arraySlice( this.times, 0 );249 const values = AnimationUtils.arraySlice( this.values, 0 );250 const TypedKeyframeTrack = this.constructor;251 const track = new TypedKeyframeTrack( this.name, times, values );252 // Interpolant argument to constructor is not saved, so copy the factory method directly.253 track.createInterpolant = this.createInterpolant;254 return track;255 }256}257KeyframeTrack.prototype.TimeBufferType = Float32Array;258KeyframeTrack.prototype.ValueBufferType = Float32Array;259KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;...

Full Screen

Full Screen

loopedslider.js

Source:loopedslider.js Github

copy

Full Screen

1/*2 * loopedSlider 0.5.6 - jQuery plugin3 * written by Nathan Searles 4 * http://nathansearles.com/loopedslider/5 *6 * Copyright (c) 2009 Nathan Searles (http://nathansearles.com/)7 * Dual licensed under the MIT (MIT-LICENSE.txt)8 * and GPL (GPL-LICENSE.txt) licenses.9 *10 * Built for jQuery library11 * http://jquery.com12 * Compatible with jQuery 1.3.2+13 *14 */15/*16 * markup example for $("#loopedSlider").loopedSlider();17 *18 * <div id="loopedSlider"> 19 * <div class="container">20 * <div class="slides">21 * <div><img src="01.jpg" alt="" /></div>22 * <div><img src="02.jpg" alt="" /></div>23 * <div><img src="03.jpg" alt="" /></div>24 * <div><img src="04.jpg" alt="" /></div>25 * </div>26 * </div>27 * <a href="#" class="previous">previous</a>28 * <a href="#" class="next">next</a> 29 * </div>30 *31*/32if(typeof jQuery != 'undefined') {33 jQuery(function($) {34 $.fn.extend({35 loopedSlider: function(options) {36 var settings = $.extend({}, $.fn.loopedSlider.defaults, options);37 38 return this.each(39 function() {40 if($.fn.jquery < '1.3.2') {return;}41 var $t = $(this);42 var o = $.metadata ? $.extend({}, settings, $t.metadata()) : settings;43 44 var distance = 0;45 var times = 1;46 var slides = $(o.slides,$t).children().size();47 var width = $(o.slides,$t).children().outerWidth();48 var position = 0;49 var active = false;50 var number = 0;51 var interval = 0;52 var restart = 0;53 var pagination = $("."+o.pagination+" li a",$t);54 if(o.addPagination && !$(pagination).length){55 var buttons = slides;56 $($t).append("<ul class="+o.pagination+">");57 $(o.slides,$t).children().each(function(){58 if (number<buttons) {59 $("."+o.pagination,$t).append("<li><a rel="+(number+1)+" href=\"#\" >"+(number+1)+"</a></li>");60 number = number+1;61 } else {62 number = 0;63 return false;64 }65 $("."+o.pagination+" li a:eq(0)",$t).parent().addClass("active");66 });67 pagination = $("."+o.pagination+" li a",$t);68 } else {69 $(pagination,$t).each(function(){70 number=number+1;71 $(this).attr("rel",number);72 $(pagination.eq(0),$t).parent().addClass("active");73 });74 }75 if (slides===1) {76 $(o.slides,$t).children().css({position:"absolute",left:position,display:"block"});77 return;78 }79 $(o.slides,$t).css({width:(slides*width)});80 $(o.slides,$t).children().each(function(){81 $(this).css({position:"absolute",left:position,display:"block"});82 position=position+width;83 });84 $(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:-width});85 if (slides>3) {86 $(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:-width});87 }88 if(o.autoHeight){autoHeight(times);}89 $(".next",$t).click(function(){90 if(active===false) {91 animate("next",true);92 if(o.autoStart){93 if (o.restart) {autoStart();}94 else {clearInterval(sliderIntervalID);}95 }96 } return false;97 });98 $(".previous",$t).click(function(){99 if(active===false) { 100 animate("prev",true);101 if(o.autoStart){102 if (o.restart) {autoStart();}103 else {clearInterval(sliderIntervalID);}104 }105 } return false;106 });107 if (o.containerClick) {108 $(o.container,$t).click(function(){109 if(active===false) {110 animate("next",true);111 if(o.autoStart){112 if (o.restart) {autoStart();}113 else {clearInterval(sliderIntervalID);}114 }115 } return false;116 });117 }118 $(pagination,$t).click(function(){119 if ($(this).parent().hasClass("active")) {return false;}120 else {121 times = $(this).attr("rel");122 $(pagination,$t).parent().siblings().removeClass("active");123 $(this).parent().addClass("active");124 animate("fade",times);125 if(o.autoStart){126 if (o.restart) {autoStart();}127 else {clearInterval(sliderIntervalID);}128 }129 } return false;130 });131 if (o.autoStart) {132 sliderIntervalID = setInterval(function(){133 if(active===false) {animate("next",true);}134 },o.autoStart);135 function autoStart() {136 if (o.restart) {137 clearInterval(sliderIntervalID);138 clearInterval(interval);139 clearTimeout(restart);140 restart = setTimeout(function() {141 interval = setInterval( function(){142 animate("next",true);143 },o.autoStart);144 },o.restart);145 } else {146 sliderIntervalID = setInterval(function(){147 if(active===false) {animate("next",true);}148 },o.autoStart);149 }150 };151 }152 function current(times) {153 if(times===slides+1){times = 1;}154 if(times===0){times = slides;}155 $(pagination,$t).parent().siblings().removeClass("active");156 $(pagination+"[rel='" + (times) + "']",$t).parent().addClass("active");157 };158 function autoHeight(times) {159 if(times===slides+1){times=1;}160 if(times===0){times=slides;} 161 var getHeight = $(o.slides,$t).children(":eq("+(times-1)+")",$t).outerHeight();162 $(o.container,$t).animate({height: getHeight},o.autoHeight); 163 }; 164 function animate(dir,clicked){ 165 active = true; 166 switch(dir){167 case "next":168 times = times+1;169 distance = (-(times*width-width));170 current(times);171 if(o.autoHeight){autoHeight(times);}172 if(slides<3){173 if (times===3){$(o.slides,$t).children(":eq(0)").css({left:(slides*width)});}174 if (times===2){$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:width});}175 }176 $(o.slides,$t).animate({left: distance}, o.slidespeed,function(){177 if (times===slides+1) {178 times = 1;179 $(o.slides,$t).css({left:0},function(){$(o.slides,$t).animate({left:distance})}); 180 $(o.slides,$t).children(":eq(0)").css({left:0});181 $(o.slides,$t).children(":eq("+(slides-1)+")").css({ position:"absolute",left:-width}); 182 }183 if (times===slides) $(o.slides,$t).children(":eq(0)").css({left:(slides*width)});184 if (times===slides-1) $(o.slides,$t).children(":eq("+(slides-1)+")").css({left:(slides*width-width)});185 active = false;186 }); 187 break; 188 case "prev":189 times = times-1;190 distance = (-(times*width-width));191 current(times);192 if(o.autoHeight){autoHeight(times);}193 if (slides<3){194 if(times===0){$(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:(-width)});}195 if(times===1){$(o.slides,$t).children(":eq(0)").css({position:"absolute",left:0});}196 }197 $(o.slides,$t).animate({left: distance}, o.slidespeed,function(){198 if (times===0) {199 times = slides;200 $(o.slides,$t).children(":eq("+(slides-1)+")").css({position:"absolute",left:(slides*width-width)});201 $(o.slides,$t).css({left: -(slides*width-width)});202 $(o.slides,$t).children(":eq(0)").css({left:(slides*width)});203 }204 if (times===2 ) $(o.slides,$t).children(":eq(0)").css({position:"absolute",left:0});205 if (times===1) $(o.slides,$t).children(":eq("+ (slides-1) +")").css({position:"absolute",left:-width});206 active = false;207 });208 break;209 case "fade":210 times = [times]*1;211 distance = (-(times*width-width));212 current(times);213 if(o.autoHeight){autoHeight(times);}214 $(o.slides,$t).children().fadeOut(o.fadespeed, function(){215 $(o.slides,$t).css({left: distance});216 $(o.slides,$t).children(":eq("+(slides-1)+")").css({left:slides*width-width});217 $(o.slides,$t).children(":eq(0)").css({left:0});218 if(times===slides){$(o.slides,$t).children(":eq(0)").css({left:(slides*width)});}219 if(times===1){$(o.slides,$t).children(":eq("+(slides-1)+")").css({ position:"absolute",left:-width});}220 $(o.slides,$t).children().fadeIn(o.fadespeed);221 active = false;222 });223 break; 224 default:225 break;226 } 227 };228 }229 );230 }231 });232 $.fn.loopedSlider.defaults = {233 container: ".container", //Class/id of main container. You can use "#container" for an id.234 slides: ".slides", //Class/id of slide container. You can use "#slides" for an id.235 pagination: "pagination", //Class name of parent ul for numbered links. Don't add a "." here.236 containerClick: false, //Click slider to goto next slide? true/false237 autoStart: 5000, //Set to positive number for true. This number will be the time between transitions.238 restart: 0, //Set to positive number for true. Sets time until autoStart is restarted.239 slidespeed: 300, //Speed of slide animation, 1000 = 1second.240 fadespeed: 200, //Speed of fade animation, 1000 = 1second.241 autoHeight:1, //Set to positive number for true. This number will be the speed of the animation.242 addPagination: false //Add pagination links based on content? true/false243 };244 });...

Full Screen

Full Screen

TimesRowRenderer-dbg.js

Source:TimesRowRenderer-dbg.js Github

copy

Full Screen

1/*!2 * UI development toolkit for HTML5 (OpenUI5)3 * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.4 * Licensed under the Apache License, Version 2.0 - see LICENSE.txt.5 */6sap.ui.define(['jquery.sap.global', 'sap/ui/unified/calendar/CalendarUtils', 'sap/ui/core/date/UniversalDate'],7 function(jQuery, CalendarUtils, UniversalDate) {8 "use strict";9 /**10 * Month renderer.11 * @namespace12 */13 var TimesRowRenderer = {14 };15 /**16 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.17 *18 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer19 * @param {sap.ui.unified.calendar.TimesRow} oTimesRow An object representation of the control that should be rendered20 */21 TimesRowRenderer.render = function(oRm, oTimesRow){22 var oDate = oTimesRow._getStartDate();23 var sTooltip = oTimesRow.getTooltip_AsString();24 var sId = oTimesRow.getId();25 var oAriaLabel = {value: sId + "-Descr", append: true};26 oRm.write("<div");27 oRm.writeControlData(oTimesRow);28 oRm.addClass("sapUiCalTimesRow");29 oRm.addClass("sapUiCalRow");30 oRm.writeClasses();31 if (sTooltip) {32 oRm.writeAttributeEscaped("title", sTooltip);33 }34 if (oTimesRow._getShowHeader()) {35 oAriaLabel.value = oAriaLabel.value + " " + sId + "-Head";36 }37 oRm.writeAccessibilityState(oTimesRow, {38 role: "grid",39 readonly: "true",40 multiselectable: !oTimesRow.getSingleSelection() || oTimesRow.getIntervalSelection(),41 labelledby: oAriaLabel42 });43 oRm.write(">"); // div element44 oRm.write("<span id=\"" + sId + "-Descr\" style=\"display: none;\">" + oTimesRow._rb.getText("CALENDAR_DIALOG") + "</span>");45 if (oTimesRow.getIntervalSelection()) {46 oRm.write("<span id=\"" + sId + "-Start\" style=\"display: none;\">" + oTimesRow._rb.getText("CALENDAR_START_TIME") + "</span>");47 oRm.write("<span id=\"" + sId + "-End\" style=\"display: none;\">" + oTimesRow._rb.getText("CALENDAR_END_TIME") + "</span>");48 }49 this.renderRow(oRm, oTimesRow, oDate);50 oRm.write("</div>");51 };52 TimesRowRenderer.renderRow = function(oRm, oTimesRow, oDate){53 var sId = oTimesRow.getId();54 // header line55 this.renderHeader(oRm, oTimesRow, oDate);56 // time items57 oRm.write("<div id=\"" + sId + "-times\" class=\"sapUiCalItems\">"); // extra DIV around the times to allow rerendering only it's content58 this.renderTimes(oRm, oTimesRow, oDate);59 oRm.write("</div>");60 };61 TimesRowRenderer.renderHeader = function(oRm, oTimesRow, oDate){62 // header63 if (oTimesRow._getShowHeader()) {64 var oLocaleData = oTimesRow._getLocaleData();65 var sId = oTimesRow.getId();66 oRm.write("<div id=\"" + sId + "-Head\">");67 this.renderHeaderLine(oRm, oTimesRow, oLocaleData, oDate);68 oRm.write("</div>");69 }70 };71 TimesRowRenderer.renderHeaderLine = function(oRm, oTimesRow, oLocaleData, oDate){72 var oFormatDate = oTimesRow._getFormatDate();73 var sId = oTimesRow.getId();74 var iItems = oTimesRow.getItems();75 var oItemDate = oTimesRow._getIntervalStart(oDate);76 var iMinutes = oTimesRow.getIntervalMinutes();77 var sWidth = "";78 var sDay = 0;79 var aDayIntervals = [];80 var i = 0;81 for (i = 0; i < iItems; i++) {82 sDay = oFormatDate.format(oItemDate, true);83 if (aDayIntervals.length > 0 && aDayIntervals[aDayIntervals.length - 1].sDay == sDay) {84 aDayIntervals[aDayIntervals.length - 1].iItems++;85 }else {86 aDayIntervals.push({sDay: sDay, iItems: 1});87 }88 oItemDate.setUTCMinutes(oItemDate.getUTCMinutes() + iMinutes);89 }90 for (i = 0; i < aDayIntervals.length; i++) {91 var oDayInterval = aDayIntervals[i];92 sWidth = ( 100 / iItems * oDayInterval.iItems) + "%";93 oRm.write("<div id=\"" + sId + "-Head" + i + "\"class=\"sapUiCalHeadText\" style=\"width:" + sWidth + "\">");94 oRm.write(oDayInterval.sDay);95 oRm.write("</div>");96 }97 };98 TimesRowRenderer.renderTimes = function(oRm, oTimesRow, oDate){99 var oHelper = this.getHelper(oTimesRow, oDate);100 var iItems = oTimesRow.getItems();101 var sWidth = ( 100 / iItems ) + "%";102 var oItemDate = oTimesRow._getIntervalStart(oDate);103 var sOldAmPm = "";104 var sAmPm = "";105 for (var i = 0; i < iItems; i++) {106 if (oHelper.oFormatTimeAmPm) {107 sAmPm = oHelper.oFormatTimeAmPm.format(oItemDate, true);108 if (sOldAmPm == sAmPm) {109 sAmPm = "";110 } else {111 sOldAmPm = sAmPm;112 }113 }114 this.renderTime(oRm, oTimesRow, oItemDate, oHelper, sWidth, sAmPm);115 oItemDate.setUTCMinutes(oItemDate.getUTCMinutes() + oHelper.iMinutes);116 }117 };118 TimesRowRenderer.getHelper = function(oTimesRow, oDate){119 var oHelper = {};120 oHelper.sLocale = oTimesRow._getLocale();121 oHelper.oLocaleData = oTimesRow._getLocaleData();122 oHelper.oNow = CalendarUtils._createUniversalUTCDate(new Date(), undefined, true);123 oHelper.sCurrentTime = oTimesRow._rb.getText("CALENDAR_CURRENT_TIME");124 oHelper.sId = oTimesRow.getId();125 oHelper.oFormatLong = oTimesRow._getFormatLong();126 oHelper.oFormatTime = oTimesRow._getFormatTime();127 oHelper.oFormatTimeAmPm = oTimesRow._oFormatTimeAmPm;128 oHelper.iMinutes = oTimesRow.getIntervalMinutes();129 var sLegendId = oTimesRow.getLegend();130 if (sLegendId) {131 var oLegend = sap.ui.getCore().byId(sLegendId);132 if (oLegend) {133 if (!(oLegend instanceof sap.ui.unified.CalendarLegend)) {134 throw new Error(oLegend + " is not an sap.ui.unified.CalendarLegend. " + oTimesRow);135 }136 oHelper.aTypes = oLegend.getItems();137 } else {138 jQuery.sap.log.warning("CalendarLegend " + sLegendId + " does not exist!", oTimesRow);139 }140 } else {141 oHelper.aTypes = [];142 }143 return oHelper;144 };145 TimesRowRenderer.renderTime = function(oRm, oTimesRow, oDate, oHelper, sWidth, sAmPm){146 var mAccProps = {147 role: "gridcell",148 selected: false,149 label: "",150 describedby: ""151 };152 var sYyyyMMddHHmm = oTimesRow._oFormatYyyyMMddHHmm.format(oDate.getJSDate(), true);153 var iSelected = oTimesRow._checkDateSelected(oDate);154 var oType = oTimesRow._getDateType(oDate);155 var bEnabled = oTimesRow._checkTimeEnabled(oDate);156 oRm.write("<div");157 oRm.writeAttribute("id", oHelper.sId + "-" + sYyyyMMddHHmm);158 oRm.addClass("sapUiCalItem");159 if (sWidth) {160 oRm.addStyle("width", sWidth);161 }162 var oNextInterval = new UniversalDate(oDate.getTime());163 oNextInterval.setUTCMinutes(oNextInterval.getUTCMinutes() + oHelper.iMinutes);164 if (oDate.getTime() <= oHelper.oNow.getTime() && oNextInterval.getTime() > oHelper.oNow.getTime()) {165 oRm.addClass("sapUiCalItemNow");166 mAccProps["label"] = oHelper.sCurrentTime + " ";167 }168 if (iSelected > 0) {169 oRm.addClass("sapUiCalItemSel"); // time selected170 mAccProps["selected"] = true;171 }172 if (iSelected == 2) {173 oRm.addClass("sapUiCalItemSelStart"); // interval start174 mAccProps["describedby"] = mAccProps["describedby"] + " " + oHelper.sId + "-Start";175 } else if (iSelected == 3) {176 oRm.addClass("sapUiCalItemSelEnd"); // interval end177 mAccProps["describedby"] = mAccProps["describedby"] + " " + oHelper.sId + "-End";178 } else if (iSelected == 4) {179 oRm.addClass("sapUiCalItemSelBetween"); // interval between180 } else if (iSelected == 5) {181 oRm.addClass("sapUiCalItemSelStart"); // interval start182 oRm.addClass("sapUiCalItemSelEnd"); // interval end183 mAccProps["describedby"] = mAccProps["describedby"] + " " + oHelper.sId + "-Start";184 mAccProps["describedby"] = mAccProps["describedby"] + " " + oHelper.sId + "-End";185 }186 if (oType && oType.type != sap.ui.unified.CalendarDayType.None) {187 oRm.addClass("sapUiCalItem" + oType.type);188 if (oType.tooltip) {189 oRm.writeAttributeEscaped('title', oType.tooltip);190 }191 }192 if (!bEnabled) {193 oRm.addClass("sapUiCalItemDsbl"); // time disabled194 mAccProps["disabled"] = true;195 }196 oRm.writeAttribute("tabindex", "-1");197 oRm.writeAttribute("data-sap-time", sYyyyMMddHHmm);198 mAccProps["label"] = mAccProps["label"] + oHelper.oFormatLong.format(oDate, true);199 if (oType && oType.type != sap.ui.unified.CalendarDayType.None) {200 // as legend must not be rendered add text of type201 for (var i = 0; i < oHelper.aTypes.length; i++) {202 var oLegendType = oHelper.aTypes[i];203 if (oLegendType.getType() == oType.type) {204 mAccProps["label"] = mAccProps["label"] + "; " + oLegendType.getText();205 break;206 }207 }208 }209 oRm.writeAccessibilityState(null, mAccProps);210 oRm.writeClasses();211 oRm.writeStyles();212 oRm.write(">"); // div element213 oRm.write("<span");214 oRm.addClass("sapUiCalItemText");215 oRm.writeClasses();216 oRm.write(">"); // span217 oRm.write(oHelper.oFormatTime.format(oDate, true));218// oRm.write("</span>");219 if (sAmPm) {220 oRm.write("<span");221 oRm.addClass("sapUiCalItemTextAmPm");222 oRm.writeClasses();223 oRm.write(">"); // span224 oRm.write(sAmPm);225 oRm.write("</span>");226 }227 oRm.write("</span>");228 oRm.write("</div>");229 };230 return TimesRowRenderer;...

Full Screen

Full Screen

time.jsx

Source:time.jsx Github

copy

Full Screen

1import React from "react";2import PropTypes from "prop-types";3import {4 getHour,5 getMinute,6 newDate,7 getStartOfDay,8 addMinutes,9 cloneDate,10 formatDate,11 isTimeInDisabledRange,12 isTimeDisabled,13 timesToInjectAfter14} from "./date_utils";15export default class Time extends React.Component {16 static propTypes = {17 format: PropTypes.string,18 includeTimes: PropTypes.array,19 intervals: PropTypes.number,20 selected: PropTypes.object,21 onChange: PropTypes.func,22 todayButton: PropTypes.string,23 minTime: PropTypes.object,24 maxTime: PropTypes.object,25 excludeTimes: PropTypes.array,26 monthRef: PropTypes.object,27 timeCaption: PropTypes.string,28 injectTimes: PropTypes.array29 };30 static get defaultProps() {31 return {32 intervals: 30,33 onTimeChange: () => {},34 todayButton: null,35 timeCaption: "Time"36 };37 }38 componentDidMount() {39 // code to ensure selected time will always be in focus within time window when it first appears40 const multiplier = 60 / this.props.intervals;41 const currH = this.props.selected42 ? getHour(this.props.selected)43 : getHour(newDate());44 this.list.scrollTop = 30 * (multiplier * currH);45 }46 handleClick = time => {47 if (48 ((this.props.minTime || this.props.maxTime) &&49 isTimeInDisabledRange(time, this.props)) ||50 (this.props.excludeTimes &&51 isTimeDisabled(time, this.props.excludeTimes)) ||52 (this.props.includeTimes &&53 !isTimeDisabled(time, this.props.includeTimes))54 ) {55 return;56 }57 this.props.onChange(time);58 };59 liClasses = (time, currH, currM) => {60 let classes = ["react-datepicker__time-list-item"];61 if (currH === getHour(time) && currM === getMinute(time)) {62 classes.push("react-datepicker__time-list-item--selected");63 }64 if (65 ((this.props.minTime || this.props.maxTime) &&66 isTimeInDisabledRange(time, this.props)) ||67 (this.props.excludeTimes &&68 isTimeDisabled(time, this.props.excludeTimes)) ||69 (this.props.includeTimes &&70 !isTimeDisabled(time, this.props.includeTimes))71 ) {72 classes.push("react-datepicker__time-list-item--disabled");73 }74 if (75 this.props.injectTimes &&76 (getHour(time) * 60 + getMinute(time)) % this.props.intervals !== 077 ) {78 classes.push("react-datepicker__time-list-item--injected");79 }80 return classes.join(" ");81 };82 renderTimes = () => {83 let times = [];84 const format = this.props.format ? this.props.format : "hh:mm A";85 const intervals = this.props.intervals;86 const activeTime = this.props.selected ? this.props.selected : newDate();87 const currH = getHour(activeTime);88 const currM = getMinute(activeTime);89 let base = getStartOfDay(newDate());90 const multiplier = 1440 / intervals;91 const sortedInjectTimes =92 this.props.injectTimes &&93 this.props.injectTimes.sort(function(a, b) {94 return a - b;95 });96 for (let i = 0; i < multiplier; i++) {97 const currentTime = addMinutes(cloneDate(base), i * intervals);98 times.push(currentTime);99 if (sortedInjectTimes) {100 const timesToInject = timesToInjectAfter(101 base,102 currentTime,103 i,104 intervals,105 sortedInjectTimes106 );107 times = times.concat(timesToInject);108 }109 }110 return times.map((time, i) => (111 <li112 key={i}113 onClick={this.handleClick.bind(this, time)}114 className={this.liClasses(time, currH, currM)}115 >116 {formatDate(time, format)}117 </li>118 ));119 };120 render() {121 let height = null;122 if (this.props.monthRef) {123 height = this.props.monthRef.clientHeight - 39;124 }125 return (126 <div127 className={`react-datepicker__time-container ${128 this.props.todayButton129 ? "react-datepicker__time-container--with-today-button"130 : ""131 }`}132 >133 <div className="react-datepicker__header react-datepicker__header--time">134 <div className="react-datepicker-time__header">135 {this.props.timeCaption}136 </div>137 </div>138 <div className="react-datepicker__time">139 <div className="react-datepicker__time-box">140 <ul141 className="react-datepicker__time-list"142 ref={list => {143 this.list = list;144 }}145 style={height ? { height } : {}}146 >147 {this.renderTimes.bind(this)()}148 </ul>149 </div>150 </div>151 </div>152 );153 }...

Full Screen

Full Screen

format.js

Source:format.js Github

copy

Full Screen

1/**2 * Formats nested key val array to key val map3 * @param {Array} keyValArray - [['key', 'val'], ..]4 * @returns {Object} - { key: val, ..}5 */6export const formatKeyVal = keyValArray => {7 const keyValObj = {}8 // strip out empties (if BOTH key and val empty)9 for (let keyVal of keyValArray) {10 if (keyVal[0] === '' && keyVal[1] === '') continue11 keyValObj[keyVal[0]] = keyVal[1]12 }13 return keyValObj14}15/**16 * Formats a request object to axios config input17 * @param {Object} request - provided request object18 * @returns {Object} - formatted to axios request config19 */20export const formatToAxios = request => {21 const params = request.params.form22 const headers = request.headers.form23 const body = request.body[request.body.active]24 const axiosConfig = {25 method: request.method,26 url: request.url27 }28 if (headers.length) axiosConfig.headers = formatKeyVal(headers)29 if (params.length) axiosConfig.params = formatKeyVal(params)30 // request body excluded for GET requests31 if (request.method !== 'get') {32 // form data handled on `requests` worker, as read stream for file uploads can't be33 // passed as arg, and new stream needed for each request (see 'utils/request.js')34 if (request.body.active === 'form' && body.length) axiosConfig.data = body35 if (request.body.active === 'text' && body) axiosConfig.data = body36 if (request.body.active === 'json' && body) axiosConfig.data = JSON.parse(body)37 }38 return axiosConfig39}40/**41 * Aggregates all responses from request workers42 * @param {Array} responses - worker responses [ { times: [], statusCodes: [] }, ...]43 * @returns {Object} - { times: [], statusCodes: { code: amount, ... } }44 */45export const aggregateResponses = responses => {46 let times = []47 let statusCodes = {}48 responses.forEach(response => {49 times = times.concat(response.times)50 response.statusCodes.forEach(code => {51 if (statusCodes[code]) {52 statusCodes[code] += 153 } else {54 statusCodes[code] = 155 }56 })57 })58 return { times, statusCodes }59}60/**61 * Sorts array of int times62 * @param {Array} times - unsorted, single depth array of int times63 * @returns {Array} - [ sorted times ... ]64 */65export const sortTimes = times => {66 // TODO: implement better sorting algorithm for large data sets67 return times.sort((a, b) => a - b)68}69/**70 * Formats sorted response times to a percentile distribution71 * @param {Array} sortedResponseTimes - sorted, single depth array of int response times72 * @returns {Object} - { 10: requestTimesforPercentile, 25: requestTimesforPercentile, ...}73 */74export const latencyDistribution = sortedResponseTimes => {75 const distribution = {}76 const times = sortedResponseTimes77 const tenPercent = Math.floor(times.length / 10)78 const twentyFivePercent = Math.floor(times.length / 4)79 const fiftyPercent = Math.floor(times.length / 2)80 const seventyFivePercent = Math.floor((times.length / 4) * 3)81 const ninetyPercent = Math.floor((times.length / 10) * 9)82 const ninetyNinePercent = times.length - Math.floor(times.length / 100)83 const oneHundredPercent = times.length84 if (times.length >= 10 && tenPercent) distribution['10'] = times[tenPercent - 1]85 if (times.length >= 4 && twentyFivePercent) distribution['25'] = times[twentyFivePercent - 1]86 if (times.length >= 2 && fiftyPercent) distribution['50'] = times[fiftyPercent - 1]87 if (times.length >= 4 && seventyFivePercent) distribution['75'] = times[seventyFivePercent - 1]88 if (times.length >= 10 && ninetyPercent) distribution['90'] = times[ninetyPercent - 1]89 if (times.length >= 100 && ninetyNinePercent) distribution['99'] = times[ninetyNinePercent - 1]90 if (ninetyNinePercent) distribution['100'] = times[oneHundredPercent - 1]91 return distribution...

Full Screen

Full Screen

profiler.js

Source:profiler.js Github

copy

Full Screen

1/*!2 * Augment mw.loader to facilitate module-level profiling.3 *4 * @since 1.325 */6/* global mw */7( function () {8 'use strict';9 var moduleTimes = Object.create( null );10 /**11 * Private hooks inserted into mw.loader code if MediaWiki configuration12 * `$wgResourceLoaderEnableJSProfiler` is `true`.13 *14 * To use this data, run `mw.inspect( 'time' )` from the browser console.15 * See mw#inspect().16 *17 * @private18 * @class19 * @singleton20 */21 mw.loader.profiler = {22 onExecuteStart: function ( moduleName ) {23 var time = performance.now();24 if ( moduleTimes[ moduleName ] ) {25 throw new Error( 'Unexpected perf record for "' + moduleName + '".' );26 }27 moduleTimes[ moduleName ] = {28 executeStart: time,29 executeEnd: null,30 scriptStart: null,31 scriptEnd: null32 };33 },34 onExecuteEnd: function ( moduleName ) {35 var time = performance.now();36 moduleTimes[ moduleName ].executeEnd = time;37 },38 onScriptStart: function ( moduleName ) {39 var time = performance.now();40 moduleTimes[ moduleName ].scriptStart = time;41 },42 onScriptEnd: function ( moduleName ) {43 var time = performance.now();44 moduleTimes[ moduleName ].scriptEnd = time;45 },46 /**47 * For internal use by inspect.reports#time.48 *49 * @private50 * @param {string} moduleName51 * @return {Object|null}52 * @throws {Error} If the perf record is incomplete.53 */54 getProfile: function ( moduleName ) {55 var times, key, execute, script, total;56 times = moduleTimes[ moduleName ];57 if ( !times ) {58 return null;59 }60 for ( key in times ) {61 if ( times[ key ] === null ) {62 throw new Error( 'Incomplete perf record for "' + moduleName + '".', times );63 }64 }65 execute = times.executeEnd - times.executeStart;66 script = times.scriptEnd - times.scriptStart;67 total = execute + script;68 return {69 name: moduleName,70 execute: execute,71 script: script,72 total: total73 };74 }75 };...

Full Screen

Full Screen

times.test.js

Source:times.test.js Github

copy

Full Screen

1'use strict';2require('should');3describe('times', function ( ) {4 var times = require('../lib/times');5 it('hours to mins, secs, and msecs', function () {6 times.hour().mins.should.equal(60);7 times.hour().secs.should.equal(3600);8 times.hour().msecs.should.equal(3600000);9 times.hours(3).mins.should.equal(180);10 times.hours(3).secs.should.equal(10800);11 times.hours(3).msecs.should.equal(10800000);12 });13 it('mins to secs and msecs', function () {14 times.min().secs.should.equal(60);15 times.min().msecs.should.equal(60000);16 times.mins(2).secs.should.equal(120);17 times.mins(2).msecs.should.equal(120000);18 });19 it('secs as msecs', function () {20 times.sec().msecs.should.equal(1000);21 times.secs(15).msecs.should.equal(15000);22 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button')5 .wait(3000)6 .click('#tried-test-cafe')7 .click('#macos')8 .click('#submit-button')9 .wait(3000)10 .click('#article-header');11});12test('My second test', async t => {13 .typeText('#developer-name', 'John Smith')14 .click('#submit-button')15 .wait(3000)16 .click('#tried-test-cafe')17 .click('#macos')18 .click('#submit-button')19 .wait(3000)20 .click('#article-header');21});22 .beforeEach( async t => {23 .maximizeWindow()24 .typeText('#developer-name', 'John Smith')25 .click('#submit-button')26 .wait(3000)27 .click('#tried-test-cafe')28 .click('#macos')29 .click('#submit-button')30 .wait(3000)31 .click('#article-header');32 })33 ('My first test', async t => {34 .click('#article-header');35 })36 .times(2);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button')5 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7import { Selector } from 'testcafe';8test('My first test', async t => {9 .typeText('#developer-name', 'John Smith')10 .click('#submit-button')11 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');12});13import { Selector } from 'testcafe';14test('My first test', async t => {15 .typeText('#developer-name', 'John Smith')16 .click('#submit-button')17 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');18});19import { Selector } from 'testcafe';20test('My first test', async t => {21 .typeText('#developer-name', 'John Smith')22 .click('#submit-button')23 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');24});25import { Selector } from 'testcafe';26test('My first test', async t => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5 const articleHeader = await Selector('.result-content').find('h1');6 let headerText = await articleHeader.innerText;7});8> 14 | let headerText = await articleHeader.innerText;9const articleHeader = await Selector('.result-content').find('h1');10const articleHeader = await Selector('.result-content').find('h1').withText('Thank you, John Smith!');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#windows')5 .click('#submit-button');6});7import { Selector } from 'testcafe';8test('My first test', async t => {9 .typeText('#developer-name', 'John Smith')10 .click('#windows')11 .click('#submit-button');12});13import { Selector } from 'testcafe';14test('My first test', async t => {15 .typeText('#developer-name', 'John Smith')16 .click('#windows')17 .click('#submit-button');18});19import { Selector } from 'testcafe';20test('My first test', async t => {21 .typeText('#developer-name', 'John Smith')22 .click('#windows')23 .click('#submit-button');24});25import { Selector } from 'testcafe';26test('My first test', async t => {27 .typeText('#developer-name', 'John Smith')28 .click('#windows')29 .click('#submit-button');30});31import { Selector } from 'testcafe';32test('My first test', async t => {33 .typeText('#developer-name',

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My test', async t => {3 const slider = Selector('#slider');4 .click(slider)5 .pressKey('right')6 .pressKey('right')7 .pressKey('right')8 .pressKey('right')9 .pressKey('right');10});11import { Selector } from 'testcafe';12test('My test', async t => {13 const slider = Selector('#slider');14 .click(slider)15 .pressKey('right'.times(5));16});17import { Selector } from 'testcafe';18test('My test', async t => {19 const macOSRadioButton = Selector('label').withText('MacOS');20 .click(macOSRadioButton);21});22import { Selector } from 'testcafe

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My test', async t => {3});4import { Selector } from 'testcafe';5test('My test', async t => {6});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .click('#populate')4 .click(Selector('input[type=radio]').withAttribute('value', 'Bugs'));5});6import { Selector } from 'testcafe';7test('My first test', async t => {8 .click('#populate')9 .click(Selector('input[type=radio]').nth(1));10});11import { Selector } from 'testcafe';12test('My first test', async t => {13 .click('#populate')14 .click(Selector('input[type=radio]').withText('Bugs'));15});16import { Selector } from 'testcafe';17test('My first test', async t => {18 .click('#populate')19 .click(Selector('input[type=radio]').filter('[value="Bugs"]'));20});21import { Selector } from 'testcafe';22test('My first test', async t => {23 .click('#populate')24 .click(Selector('input[type=radio]').withExactText('Bugs'));25});26import { Selector } from 'testcafe';

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcafe automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful