How to use warmUp method in qawolf

Best JavaScript code snippet using qawolf

YEP_X_SkillCooldowns.js

Source:YEP_X_SkillCooldowns.js Github

copy

Full Screen

1//=============================================================================2// Yanfly Engine Plugins - Skill Cost Extension - Cooldowns3// YEP_X_SkillCooldowns.js4//=============================================================================5var Imported = Imported || {};6Imported.YEP_X_SkillCooldowns = true;7var Yanfly = Yanfly || {};8Yanfly.SCD = Yanfly.SCD || {};9Yanfly.SCD.version = 1.12;10//=============================================================================11 /*:12 * @plugindesc v1.12 (Requires YEP_SkillCore.js) Cooldowns can be applied13 * to skills to prevent them from being used continuously.14 * @author Yanfly Engine Plugins15 *16 * @param ---Cooldown---17 * @default18 *19 * @param Cooldown Format20 * @parent ---Cooldown---21 * @desc This is the text format used for cooldowns.22 * %1 - Turns Remaining23 * @default %1CD24 *25 * @param Cooldown Font Size26 * @parent ---Cooldown---27 * @type number28 * @min 029 * @desc This is the font size used for cooldowns.30 * Default: 2831 * @default 2032 *33 * @param Cooldown Text Color34 * @parent ---Cooldown---35 * @type number36 * @min 037 * @max 3138 * @desc Adjusts the text color used for cooldowns.39 * @default 640 *41 * @param Cooldown Icon42 * @parent ---Cooldown---43 * @type number44 * @min 045 * @desc What icon to be used for cooldowns.46 * Use 0 for no icon.47 * @default 7548 *49 * @param Cooldown After Battle50 * @parent ---Cooldown---51 * @type number52 * @desc How are cooldowns handled after battle?53 * @default -1054 *55 * @param Cooldown Steps56 * @parent ---Cooldown---57 * @type number58 * @min 059 * @desc Outside of battle, this is how many steps on the map the60 * player must walk to drop each cooldown by 1.61 * @default 562 *63 * @param Cooldown Bypass64 * @parent ---Cooldown---65 * @desc This is a list of skills that cannot be on cooldown so that66 * way, skills like Attack, Guard.67 * @default 1 2 3 4 5 6 768 *69 * @param Cooldown Bypass List70 * @parent ---Cooldown---71 * @type skill[]72 * @desc This is a list of skills that cannot be on cooldown so that73 * way, skills like Attack, Guard. Requires RPG Maker MV 1.5.0+74 * @default []75 *76 * @param ---Warmup---77 * @default78 *79 * @param Warmup Format80 * @parent ---Warmup---81 * @desc This is the text format used for warmups.82 * %1 - Turns Remaining83 * @default %1WU84 *85 * @param Warmup Font Size86 * @parent ---Warmup---87 * @type number88 * @min 189 * @desc This is the font size used for warmups.90 * Default: 2891 * @default 2092 *93 * @param Warmup Text Color94 * @parent ---Warmup---95 * @type number96 * @min 097 * @max 3198 * @desc Adjusts the text color used for warmups.99 * @default 4100 *101 * @param Warmup Icon102 * @parent ---Warmup---103 * @type number104 * @min 0105 * @desc What icon to be used for warmups.106 * Use 0 for no icon.107 * @default 75108 *109 * @param ---Battle Core---110 * @default111 *112 * @param Time Based113 * @parent ---Battle Core---114 * @type boolean115 * @on Time-Based116 * @off Turn-Based117 * @desc If a battle system is Tick-based, use time instead118 * of turns for cooldowns? NO - false YES - true119 * @default false120 *121 * @param Turn Time122 * @parent ---Battle Core---123 * @type number124 * @min 1125 * @desc How many ticks must pass to equal 1 cooldown turn?126 * @default 100127 *128 * @help129 * ============================================================================130 * Introduction131 * ============================================================================132 *133 * This plugin requires YEP_SkillCore.134 * Make sure this plugin is located under YEP_SkillCore in the plugin list.135 *136 * This plugin allows you to give your skills cooldowns. Cooldowns are a limit137 * enforced on a skill to prevent them from being used constantly.138 *139 * ============================================================================140 * Cooldown Types141 * ============================================================================142 *143 * Cooldown (Standard)144 * The standard cooldown only occurs if the skill has a cooldown to pay. When145 * used, the skill cannot be used for x turns as indicated by the cooldown.146 * There are a number of things that contribute to cooldowns going down. The147 * first would be simply waiting. Each turn in battle causes a cooldown to148 * drop by 1 turn. Skills and the such can be used to speed up this process.149 * The second would be to finish battles. Finishing a battle will cause all150 * cooldowns to drop by a certain amount (can be defined in the parameters).151 * And the third would be walking on the field map. Every certain amount of152 * steps allow a skill's cooldown to decrease.153 *154 * Warmups155 * As far as most things go, Warmups do the same thing as Cooldowns: prevent156 * skills from being used until their timer is up. The difference, however, is157 * that warmups only occur once during battle: at the very start of it. If a158 * skill has a warmup timer, it will trigger the moment it goes into battle159 * and instantly disappear after battle. Warmups do not stack on top of any160 * existing cooldowns. If a cooldown is already occurring when a skill is in161 * the warmup phase, both the warmup and cooldown simultaneously update.162 *163 * Linked Cooldowns164 * A linked cooldown occurs when a skill that's used causes another skill in165 * the owner's skill library to have a cooldown. All other attributes of this166 * cooldown are the same as a standard cooldown's. This cooldown type will take167 * priority over Skill Type Cooldowns and Global Cooldowns if this value is168 * defined.169 *170 * Skill Type Cooldowns171 * When a Skill Type Cooldown occurs, all skills currently in the battler's172 * skill library with the matching Skill Type will be on cooldown. All other173 * attributes of this cooldown are the same as a standard cooldown's. This174 * cooldown type will take priority over Global Cooldowns if this value is175 * defined.176 *177 * When a cooldown is applied for a skill that already has a cooldown, the178 * cooldown will change to whatever is the largest value. This means if a179 * skill has 3 turns for a cooldown and a Skill Type Cooldown would set for180 * 1 turn, the 3 turns would remain. On the flip side, if the skill has 3 turns181 * and the Skill Type Cooldown would set for 5 turns, then the cooldown would182 * be changed to 5 turns instead.183 *184 * ============================================================================185 * Notetags186 * ============================================================================187 *188 * Use the following notetags to alter the cooldown properties of a skill.189 *190 * Skill Notetags:191 * <Cooldown: x>192 * Sets the cooldown for the skill to X turns. This cooldown only affects193 * this skill alone. This value will take priority over Skill Type Cooldowns194 * and Global Cooldowns.195 *196 * <Warmup: x>197 * Sets the warmup for the skill to X turns. When entering a new battle, the198 * skill will be on a warmup phase and cannot be used until the warmup phase199 * is over.200 *201 * <After Battle Cooldown: +x>202 * <After Battle Cooldown: -x>203 * After a battle ends (victory, loss, or escape), change the cooldown for204 * this skill by +x turns or -x turns.205 *206 * <Cooldown Steps: x>207 * Outside of battle, every x steps that the Player takes, this skill's208 * cooldown will drop by 1.209 *210 * <Skill x Cooldown: y>211 * <Skill name Cooldown: y>212 * When using this skill, after paying the skill cost, skill x will have a213 * linked cooldown of y turns. This value will take priority over Skill Type214 * Cooldowns and Global Cooldowns.215 *216 * <SType x Cooldown: y>217 * When using this skill, after paying the skill cost, all skills with the218 * matching Skill Type x to have a cooldown of y. This value will take219 * priority over Global Cooldowns.220 *221 * <Global Cooldown: x>222 * When using this skill, all skills within the battler's skill library area223 * set to be on cooldown for x turns. This value has less priority than224 * Individual Cooldowns and Skill Type Cooldowns.225 *226 * <Bypass Cooldown>227 * This causes the skill to bypass cooldowns, no matter what. This should be228 * used for skills like Attack, Guard, Escape, etc. that should not have a229 * cooldown assigned to them.230 *231 * Skill and Item Notetags:232 * <Skill x Cooldown: +y>233 * <Skill x Cooldown: -y>234 * <Skill name Cooldown: +y>235 * <Skill name Cooldown: -y>236 * Targets hit by this skill will have skill x's cooldown adjusted by y.237 * This does not apply to the user and applies only to the targets.238 *239 * <SType x Cooldown: +y>240 * <SType x Cooldown: -y>241 * Targets hit by this skill will have all skills in their skill library with242 * Skill Type x to have their cooldowns adjusted by y. This does not apply to243 * the user and applies only to the targets.244 *245 * <Global Cooldown: +x>246 * <Global Cooldown: -x>247 * Targets hit by this skill will have all skills in their skill library to248 * have their cooldowns adjusted by y. This does not apply to the user and249 * applies only to the targets.250 *251 * Actor, Class, Enemy, Weapon, Armor, and State Notetags:252 *253 * <Skill x Cooldown Duration: y%>254 * <Skill name Cooldown Duration: y%>255 * Alters the cooldown duration of skill x to y% when the cooldown cost is256 * applied. This effect only applies to skill x.257 *258 * <SType x Cooldown Duration: y%>259 * Alters the cooldown duration of skills with Skill Type x to y% when the260 * cooldown cost is applied. This effect only applies to Skill Type x.261 *262 * <Global Cooldown Duration: x%>263 * Alters the cooldown duration of all skills to x% when the cooldown cost264 * is applied.265 *266 * <Skill x Cooldown Rate: y%>267 * <Skill name Cooldown Rate: y%>268 * Sets the cooldown rate for skill x to y% when the cooldown counter goes269 * down. This effect only applies to skill x.270 *271 * <SType x Cooldown Rate: y%>272 * Sets the cooldown rate for Skill Type x skills to y% when the cooldown273 * counter goes down. This effect only applies to Skill Type x skills.274 *275 * <Global Cooldown Rate: x%>276 * Sets the cooldown rate for all skills to x% when the cooldown counter277 * goes down.278 *279 * <Skill x Cooldown: +y>280 * <Skill x Cooldown: -y>281 * <Skill name Cooldown: +y>282 * <Skill name Cooldown: -y>283 * If the user performs skill x, it will have an increased or decreased284 * cooldown value as long as the user is the actor, class, enemy, or has the285 * weapon or armor equipped, or is affected by the state with this notetag.286 * These flat cooldown modifications are applied after the rates and duration287 * modifiers have been calculated.288 *289 * <SType x Cooldown: +y>290 * <SType x Cooldown: -y>291 * If the user performs skill with skill type x, it will have an increased or292 * decreased cooldown value as long as the user is the actor, class, enemy,293 * or has the weapon or armor equipped, or is affected by the state with this294 * notetag. These flat cooldown modifications are applied after the rates and295 * duration modifiers have been calculated.296 *297 * <Global Cooldown: +x>298 * <Global Cooldown: -x>299 * If the user performs any skill, it will have an increased or decreased300 * cooldown value as long as the user is the actor, class, enemy, or has the301 * weapon or armor equipped, or is affected by the state with this notetag.302 * These flat cooldown modifications are applied after the rates and duration303 * modifiers have been calculated.304 *305 * <Skill x Warmup: +y>306 * <Skill x Warmup: -y>307 * <Skill name Warmup: +y>308 * <Skill name Warmup: -y>309 * At the start of battle, skill x will have an increased or decreased warmup310 * value as long as the user is the actor, class, enemy, or has the weapon or311 * armor equipped, or is affected by the state with this notetag. These flat312 * warmup modifications are applied after the rates and duration modifiers313 * have been calculated.314 *315 * <SType x Warmup: +y>316 * <SType x Warmup: -y>317 * At the start of battle, all skills with skill type x it will have an318 * increased or decreased warmup value as long as the user is the actor,319 * class, enemy, or has the weapon or armor equipped, or is affected by the320 * state with this notetag. These flat warmup modifications are applied after321 * the rates and duration modifiers have been calculated.322 *323 * <Global Warmup: +x>324 * <Global Warmup: -x>325 * At the start of battle, all skills will have an increased or decreased326 * warmup value as long as the user is the actor, class, enemy, or has the327 * weapon or armor equipped, or is affected by the state with this notetag.328 * These flat warmup modifications are applied after the rates and duration329 * modifiers have been calculated.330 *331 * ============================================================================332 * Lunatic Mode - Specialized Cooldowns333 * ============================================================================334 *335 * For skills, you can set cooldowns to have a special code determine its value336 * when the skill is used.337 *338 * Skill Notetag339 * <Cooldown Eval>340 * cooldown = x;341 * cooldown += x;342 * </Cooldown Eval>343 * Insert these two tags into the skill's notebox to give it a unique way to344 * determine the cooldown's value. The 'cooldown' variable determines the345 * amount of turns for the cooldown.346 *347 * <Warmup Eval>348 * warmup = x;349 * warmup += x;350 * </Warmup Eval>351 * Insert these two tags into the skill's notebox to give it a unique way to352 * determine the warmup's value. The 'warmup' variable determines the amount353 * of turns for the warmup.354 *355 * ============================================================================356 * Yanfly Engine Plugins - Battle Engine Extension - Action Sequence Commands357 * ============================================================================358 *359 * If you have YEP_BattleEngineCore.js installed with this plugin located360 * underneath it in the Plugin Manager, you can make use of these extra361 * cooldown related action sequences.362 *363 *=============================================================================364 * GLOBAL COOLDOWN: targets, +X365 * GLOBAL COOLDOWN: targets, -X366 * GLOBAL COOLDOWN: targets, X367 *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -368 * Sets the cooldown for all of the targets to be adjusted by X value. This369 * applies to every skill that doesn't bypass cooldowns.370 *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -371 * Usage Example: global cooldown: target, +5372 * global cooldown: user, -3373 * global cooldown: enemies, 10374 *=============================================================================375 *376 *=============================================================================377 * SKILL X COOLDOWN: targets, +Y378 * SKILL X COOLDOWN: targets, -Y379 * SKILL X COOLDOWN: targets, Y380 *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -381 * Causes skill X to be adjusted by Y value for the targets. This only applies382 * the specific skill x's cooldown.383 *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -384 * Usage Example: skill 10 cooldown: target, +5385 * skill 12 cooldown: user, -3386 * skill 15 cooldown: enemies, 10387 *=============================================================================388 *389 *=============================================================================390 * SKILL TYPE X COOLDOWN: targets, +Y391 * SKILL TYPE X COOLDOWN: targets, -Y392 * SKILL TYPE X COOLDOWN: targets, Y393 *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -394 * Causes skill type X skills to be adjusted by Y value for the targets. This395 * only applies the specific skill type x skill's cooldown.396 *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -397 * Usage Example: skill type 1 cooldown: target, +5398 * skill type 2 cooldown: user, -3399 * skill type 5 cooldown: enemies, 10400 *=============================================================================401 *402 * ============================================================================403 * Changelog404 * ============================================================================405 *406 * Version 1.12:407 * - Updated for RPG Maker MV version 1.5.0.408 * - Added Parameter: Cooldown Bypass List409 *410 * Version 1.11:411 * - Lunatic Mode fail safes added.412 *413 * Version 1.10:414 * - Compatibility update with Equip Battle Skills.415 * - Documentation update. Added help information for <warmup: x>.416 *417 * Version 1.09:418 * - Fixed a bug with the <Skill x Cooldown Rate: y%>,419 * <SType x Cooldown Rate: y%>, and <Global Cooldown Rate: x%> notetags not420 * working as intended.421 *422 * Version 1.08:423 * - Updated for RPG Maker MV version 1.1.0.424 *425 * Version 1.07:426 * - Named versions of these notetags have been added:427 * <Skill x Cooldown: y>, <Skill x Cooldown: +/-y>,428 * <Skill x Cooldown Duration: y%>, <Skill x Cooldown: +/-y>,429 * <Skill x Warmup: +/-y>430 *431 * Version 1.06a:432 * - Fixed a bug with cooldown duration modifiers not modifying by the correct433 * value indicated.434 * - Added a fail safe for when there are no targets.435 *436 * Version 1.05:437 * - Fixed a bug that prevented <Cooldown Eval> from running properly.438 *439 * Version 1.04:440 * - Fixed a bug that didn't alter cooldowns correctly.441 *442 * Version 1.03:443 * - Optimized for Battle Engine Core v1.08.444 *445 * Version 1.02a:446 * - Added return for drawSkillCost to assist others scripters when making447 * compatibility notes.448 *449 * Version 1.01:450 * - Cooldowns can now be applied to skills that aren't learned by the actor.451 *452 * Version 1.00:453 * - Finished plugin!454 */455//=============================================================================456if (Imported.YEP_SkillCore) {457//=============================================================================458// Parameter Variables459//=============================================================================460Yanfly.Parameters = PluginManager.parameters('YEP_X_SkillCooldowns');461Yanfly.Param = Yanfly.Param || {};462Yanfly.Icon = Yanfly.Icon || {};463Yanfly.Param.CDFmt = String(Yanfly.Parameters['Cooldown Format']);464Yanfly.Param.CDFontSize = Number(Yanfly.Parameters['Cooldown Font Size']);465Yanfly.Param.CDTextColor = Number(Yanfly.Parameters['Cooldown Text Color']);466Yanfly.Icon.Cooldown = Number(Yanfly.Parameters['Cooldown Icon']);467Yanfly.Param.CDAfterBattle = Number(Yanfly.Parameters['Cooldown After Battle']);468Yanfly.Param.CDSteps = Number(Yanfly.Parameters['Cooldown Steps']);469Yanfly.Param.WUFmt = String(Yanfly.Parameters['Warmup Format']);470Yanfly.Param.WUFontSize = Number(Yanfly.Parameters['Warmup Font Size']);471Yanfly.Param.WUTextColor = Number(Yanfly.Parameters['Warmup Text Color']);472Yanfly.Param.CDTimeBased = String(Yanfly.Parameters['Time Based']);473Yanfly.Param.CDTurnTime = Number(Yanfly.Parameters['Turn Time']);474Yanfly.Icon.Warmup = Number(Yanfly.Parameters['Warmup Icon']);475Yanfly.SetupParameters = function() {476 Yanfly.Param.CDBypass = String(Yanfly.Parameters['Cooldown Bypass']);477 Yanfly.Param.CDBypass = Yanfly.Param.CDBypass.split(' ');478 for (var i = 0; i < Yanfly.Param.CDBypass.length; ++i) {479 Yanfly.Param.CDBypass[i] = parseInt(Yanfly.Param.CDBypass[i]);480 }481 var data = JSON.parse(Yanfly.Parameters['Cooldown Bypass List'] || '[]');482 for (var i = 0; i < data.length; ++i) {483 var id = parseInt(data[i]);484 if (id <= 0) continue;485 if (Yanfly.Param.CDBypass.contains(id)) continue;486 Yanfly.Param.CDBypass.push(id);487 }488};489Yanfly.SetupParameters()490//=============================================================================491// DataManager492//=============================================================================493Yanfly.SCD.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded;494DataManager.isDatabaseLoaded = function() {495 if (!Yanfly.SCD.DataManager_isDatabaseLoaded.call(this)) return false;496 if (!Yanfly._loaded_YEP_X_SkillCooldowns) {497 this.processSCDNotetagsS($dataSkills);498 this.processSCDNotetags1($dataSkills);499 this.processSCDNotetags2($dataSkills);500 this.processSCDNotetags2($dataItems);501 this.processSCDNotetags2($dataActors);502 this.processSCDNotetags2($dataClasses);503 this.processSCDNotetags2($dataEnemies);504 this.processSCDNotetags2($dataWeapons);505 this.processSCDNotetags2($dataArmors);506 this.processSCDNotetags2($dataStates);507 this.processSCDNotetags3($dataActors);508 this.processSCDNotetags3($dataClasses);509 this.processSCDNotetags3($dataEnemies);510 this.processSCDNotetags3($dataWeapons);511 this.processSCDNotetags3($dataArmors);512 this.processSCDNotetags3($dataStates);513 Yanfly._loaded_YEP_X_SkillCooldowns = true;514 }515 return true;516};517DataManager.processSCDNotetagsS = function(group) {518 if (Yanfly.SkillIdRef) return;519 Yanfly.SkillIdRef = {};520 for (var n = 1; n < group.length; n++) {521 var obj = group[n];522 if (obj.name.length <= 0) continue;523 Yanfly.SkillIdRef[obj.name.toUpperCase()] = n;524 }525};526DataManager.processSCDNotetags1 = function(group) {527 for (var n = 1; n < group.length; n++) {528 var obj = group[n];529 var notedata = obj.note.split(/[\r\n]+/);530 obj.cooldown = {};531 obj.stypeCooldown = {}532 obj.globalCooldown = 0;533 obj.afterBattleCooldown = Yanfly.Param.CDAfterBattle;534 obj.cooldownSteps = Math.max(1, parseInt(Yanfly.Param.CDSteps));535 obj.warmup = 0;536 obj.bypassCooldown = Yanfly.Param.CDBypass.contains(obj.id);537 obj.cooldownEval = '';538 obj.warmupEval = '';539 var evalMode = 'none';540 for (var i = 0; i < notedata.length; i++) {541 var line = notedata[i];542 if (line.match(/<(?:COOLDOWN):[ ](\d+)>/i)) {543 obj.cooldown[obj.id] = parseInt(RegExp.$1);544 } else if (line.match(/<(?:AFTER BATTLE COOLDOWN):[ ]([\+\-]\d+)>/i)) {545 obj.afterBattleCooldown = parseInt(RegExp.$1);546 } else if (line.match(/<(?:COOLDOWN STEPS):[ ](\d+)>/i)) {547 obj.cooldownSteps = parseInt(RegExp.$1);548 } else if (line.match(/<(?:WARMUP):[ ](\d+)>/i)) {549 obj.warmup = parseInt(RegExp.$1);550 } else if (line.match(/<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN):[ ](\d+)>/i)) {551 obj.cooldown[parseInt(RegExp.$1)] = parseInt(RegExp.$2);552 } else if (line.match(/<(?:SKILL)[ ](.*)[ ](?:COOLDOWN):[ ](\d+)>/i)) {553 var name = String(RegExp.$1).toUpperCase();554 if (Yanfly.SkillIdRef[name]) {555 var id = Yanfly.SkillIdRef[name];556 } else {557 continue;558 }559 obj.cooldown[id] = parseInt(RegExp.$2);560 } else if (line.match(/<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN):[ ](\d+)>/i)) {561 obj.stypeCooldown[parseInt(RegExp.$1)] = parseInt(RegExp.$2);562 } else if (line.match(/<(?:GLOBAL COOLDOWN):[ ](\d+)>/i)) {563 obj.globalCooldown = parseInt(RegExp.$1);564 } else if (line.match(/<(?:BYPASS COOLDOWN)>/i)) {565 obj.bypassCooldown = true;566 } else if (line.match(/<(?:COOLDOWN EVAL)>/i)) {567 obj.cooldown[obj.id] = obj.cooldown[obj.id] || 0;568 evalMode = 'cooldown';569 } else if (line.match(/<\/(?:COOLDOWN EVAL)>/i)) {570 evalMode = 'none';571 } else if (line.match(/<(?:WARMUP EVAL)>/i)) {572 evalMode = 'warmup';573 } else if (line.match(/<\/(?:WARMUP EVAL)>/i)) {574 evalMode = 'none';575 } else if (evalMode === 'cooldown') {576 obj.cooldownEval = obj.cooldownEval + line + '\n';577 } else if (evalMode === 'warmup') {578 obj.warmupEval = obj.warmupEval + line + '\n';579 }580 }581 }582};583DataManager.processSCDNotetags2 = function(group) {584 var note1 = /<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN):[ ]([\+\-]\d+)>/i;585 var note1a = /<(?:SKILL)[ ](.*)[ ](?:COOLDOWN):[ ]([\+\-]\d+)>/i;586 var note2 = /<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN):[ ]([\+\-]\d+)>/i;587 var note3 = /<(?:GLOBAL COOLDOWN):[ ]([\+\-]\d+)>/i;588 var note4 = /<(?:SKILL)[ ](\d+)[ ](?:WARMUP):[ ]([\+\-]\d+)>/i;589 var note4a = /<(?:SKILL)[ ](.*)[ ](?:WARMUP):[ ]([\+\-]\d+)>/i;590 var note5 = /<(?:STYPE)[ ](\d+)[ ](?:WARMUP):[ ]([\+\-]\d+)>/i;591 var note6 = /<(?:GLOBAL WARMUP):[ ]([\+\-]\d+)>/i;592 for (var n = 1; n < group.length; n++) {593 var obj = group[n];594 var notedata = obj.note.split(/[\r\n]+/);595 obj.cooldownChange = {};596 obj.stypeCooldownChange = {};597 obj.globalCooldownChange = 0;598 obj.warmupChange = {};599 obj.stypeWarmupChange = {};600 obj.globalWarmupChange = 0;601 for (var i = 0; i < notedata.length; i++) {602 var line = notedata[i];603 if (line.match(note1)) {604 obj.cooldownChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2);605 } else if (line.match(note1a)) {606 var name = String(RegExp.$1).toUpperCase();607 if (Yanfly.SkillIdRef[name]) {608 var id = Yanfly.SkillIdRef[name];609 } else {610 continue;611 }612 obj.cooldownChange[id] = parseInt(RegExp.$2);613 } else if (line.match(note2)) {614 obj.stypeCooldownChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2);615 } else if (line.match(note3)) {616 obj.globalCooldownChange = parseInt(RegExp.$1);617 } else if (line.match(note4)) {618 obj.warmupChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2);619 } else if (line.match(note4a)) {620 var name = String(RegExp.$1).toUpperCase();621 if (Yanfly.SkillIdRef[name]) {622 var id = Yanfly.SkillIdRef[name];623 } else {624 continue;625 }626 obj.warmupChange[id] = parseInt(RegExp.$2);627 } else if (line.match(note5)) {628 obj.stypeWarmupChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2);629 } else if (line.match(note6)) {630 obj.globalWarmupChange = parseInt(RegExp.$1);631 }632 }633 }634};635DataManager.processSCDNotetags3 = function(group) {636 var note1 = /<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN DURATION):[ ](\d+)([%%])>/i;637 var note1a = /<(?:SKILL)[ ](.*)[ ](?:COOLDOWN DURATION):[ ](\d+)([%%])>/i;638 var note2 = /<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN DURATION):[ ](\d+)([%%])>/i;639 var note3 = /<(?:GLOBAL COOLDOWN DURATION):[ ](\d+)([%%])>/i;640 var note4 = /<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN RATE):[ ](\d+)([%%])>/i;641 var note4a = /<(?:SKILL)[ ](.*)[ ](?:COOLDOWN RATE):[ ](\d+)([%%])>/i;642 var note5 = /<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN RATE):[ ](\d+)([%%])>/i;643 var note6 = /<(?:GLOBAL COOLDOWN RATE):[ ](\d+)([%%])>/i;644 for (var n = 1; n < group.length; n++) {645 var obj = group[n];646 var notedata = obj.note.split(/[\r\n]+/);647 obj.cooldownDuration = {};648 obj.stypeCooldownDuration = {};649 obj.globalCooldownDuration = 1.0;650 obj.cooldownRate = {};651 obj.stypeCooldownRate = {};652 obj.globalCooldownRate = 1.0;653 for (var i = 0; i < notedata.length; i++) {654 var line = notedata[i];655 if (line.match(note1)) {656 obj.cooldownDuration[parseInt(RegExp.$1)] = 657 parseFloat(RegExp.$2) * 0.01;658 } else if (line.match(note1a)) {659 var name = String(RegExp.$1).toUpperCase();660 if (Yanfly.SkillIdRef[name]) {661 var id = Yanfly.SkillIdRef[name];662 } else {663 continue;664 }665 obj.cooldownDuration[id] = parseFloat(RegExp.$2) * 0.01;666 } else if (line.match(note2)) {667 obj.stypeCooldownDuration[parseInt(RegExp.$1)] = 668 parseFloat(RegExp.$2) * 0.01;669 } else if (line.match(note3)) {670 obj.globalCooldownDuration = parseFloat(RegExp.$1) * 0.01;671 } else if (line.match(note4)) {672 obj.cooldownRate[parseInt(RegExp.$1)] = parseFloat(RegExp.$2) * 0.01;673 } else if (line.match(note4a)) {674 var name = String(RegExp.$1).toUpperCase();675 if (Yanfly.SkillIdRef[name]) {676 var id = Yanfly.SkillIdRef[name];677 } else {678 continue;679 }680 obj.cooldownRate[id] = parseFloat(RegExp.$2) * 0.01;681 } else if (line.match(note5)) {682 obj.stypeCooldownRate[parseInt(RegExp.$1)] = 683 parseFloat(RegExp.$2) * 0.01;684 } else if (line.match(note6)) {685 obj.globalCooldownRate = parseFloat(RegExp.$1 * 0.01);686 }687 }688 }689};690//=============================================================================691// BattleManager692//=============================================================================693Yanfly.SCD.BattleManager_endBattle = BattleManager.endBattle;694BattleManager.endBattle = function(result) {695 Yanfly.SCD.BattleManager_endBattle.call(this, result);696 $gameParty.endBattleCooldowns();697};698BattleManager.timeBasedCooldowns = function() {699 if (!$gameParty.inBattle()) return false;700 if (!Imported.YEP_BattleEngineCore) return false;701 if (this.isTurnBased()) return false;702 if (this._timeBasedCooldowns !== undefined) return this._timeBasedCooldowns;703 this._timeBasedCooldowns = eval(Yanfly.Param.CDTimeBased);704 return this._timeBasedCooldowns;705};706if (Imported.YEP_BattleEngineCore) {707Yanfly.SCD.BattleManager_processActionSequence =708 BattleManager.processActionSequence;709 BattleManager.processActionSequence = function(actionName, actionArgs) {710 // GLOBAL COOLDOWN711 if (actionName === 'GLOBAL COOLDOWN') {712 return this.actionGlobalCooldown(actionArgs);713 }714 // SKILL COOLDOWN715 if (actionName.match(/SKILL[ ](\d+)[ ]COOLDOWN/i)) {716 return this.actionSkillCooldown(parseInt(RegExp.$1), actionArgs);717 }718 // SKILL TYPE COOLDOWN719 if (actionName.match(/SKILL[ ]TYPE[ ](\d+)[ ]COOLDOWN/i)) {720 return this.actionSTypeCooldown(parseInt(RegExp.$1), actionArgs);721 }722 // STYPE COOLDOWN723 if (actionName.match(/STYPE[ ](\d+)[ ]COOLDOWN/i)) {724 return this.actionSTypeCooldown(parseInt(RegExp.$1), actionArgs);725 }726 return Yanfly.SCD.BattleManager_processActionSequence.call(this,727 actionName, actionArgs);728 };729};730BattleManager.actionGlobalCooldown = function(actionArgs) {731 var targets = this.makeActionTargets(actionArgs[0]);732 if (targets.length < 1) return true;733 var cmd = actionArgs[1];734 if (cmd.match(/([\+\-]\d+)/i)) {735 var value = parseInt(RegExp.$1);736 for (var t = 0; t < targets.length; ++t) {737 var target = targets[t];738 for (var i = 0; i < target.allSkills().length; ++i) {739 var skill = target.allSkills()[i];740 if (skill) {741 target.addCooldown(skill.id, value);742 }743 }744 }745 } else if (cmd.match(/(\d+)/i)) {746 var value = parseInt(RegExp.$1);747 for (var t = 0; t < targets.length; ++t) {748 var target = targets[t];749 for (var i = 0; i < target.allSkills().length; ++i) {750 var skill = target.allSkills()[i];751 if (skill) {752 target.setCooldown(skill.id, value);753 }754 }755 }756 } else {757 return true;758 }759 return true;760};761BattleManager.actionSkillCooldown = function(skillId, actionArgs) {762 var targets = this.makeActionTargets(actionArgs[0]);763 if (targets.length < 1) return true;764 var cmd = actionArgs[1];765 if (cmd.match(/([\+\-]\d+)/i)) {766 var value = parseInt(RegExp.$1);767 for (var t = 0; t < targets.length; ++t) {768 var target = targets[t];769 target.addCooldown(skillId, value);770 }771 } else if (cmd.match(/(\d+)/i)) {772 var value = parseInt(RegExp.$1);773 for (var t = 0; t < targets.length; ++t) {774 var target = targets[t];775 target.setCooldown(skillId, value);776 }777 } else {778 return true;779 }780 return true;781};782BattleManager.actionSTypeCooldown = function(stypeId, actionArgs) {783 var targets = this.makeActionTargets(actionArgs[0]);784 if (targets.length < 1) return true;785 var cmd = actionArgs[1];786 if (cmd.match(/([\+\-]\d+)/i)) {787 var value = parseInt(RegExp.$1);788 for (var t = 0; t < targets.length; ++t) {789 var target = targets[t];790 for (var i = 0; i < target.allSkills().length; ++i) {791 var skill = target.allSkills()[i];792 if (skill && skill.stypeId === stypeId) {793 target.addCooldown(skill.id, value);794 }795 }796 }797 } else if (cmd.match(/(\d+)/i)) {798 var value = parseInt(RegExp.$1);799 for (var t = 0; t < targets.length; ++t) {800 var target = targets[t];801 for (var i = 0; i < target.allSkills().length; ++i) {802 var skill = target.allSkills()[i];803 if (skill && skill.stypeId === stypeId) {804 target.setCooldown(skill.id, value);805 }806 }807 }808 } else {809 return true;810 }811 return true;812};813//=============================================================================814// Game_BattlerBase815//=============================================================================816Yanfly.SCD.Game_BattlerBase_initMembers =817 Game_BattlerBase.prototype.initMembers;818Game_BattlerBase.prototype.initMembers = function() {819 Yanfly.SCD.Game_BattlerBase_initMembers.call(this);820 this.clearCooldowns();821 this.clearWarmups();822};823Game_BattlerBase.prototype.clearCooldowns = function() {824 this._cooldownTurns = {};825};826Game_BattlerBase.prototype.clearWarmups = function() {827 this._warmupTurns = {};828};829Game_BattlerBase.prototype.cooldown = function(skillId) {830 if (this._cooldownTurns === undefined) this.clearCooldowns();831 if (this._cooldownTurns[skillId] === undefined) {832 this._cooldownTurns[skillId] = 0;833 }834 return this._cooldownTurns[skillId];835};836Game_BattlerBase.prototype.warmup = function(skillId) {837 if (this._warmupTurns === undefined) this.clearWarmups();838 if (this._warmupTurns[skillId] === undefined) {839 this._warmupTurns[skillId] = 0;840 }841 return this._warmupTurns[skillId];842};843Game_BattlerBase.prototype.setCooldown = function(skillId, value) {844 if (!$dataSkills[skillId]) return;845 if ($dataSkills[skillId].bypassCooldown) return;846 if (this._cooldownTurns === undefined) this.clearCooldowns();847 this._cooldownTurns[skillId] = value;848};849Game_BattlerBase.prototype.addCooldown = function(skillId, value) {850 if (!$dataSkills[skillId]) return;851 if ($dataSkills[skillId].bypassCooldown) return;852 if (this._cooldownTurns === undefined) this.clearCooldowns();853 if (!this._cooldownTurns[skillId]) this._cooldownTurns[skillId] = 0;854 this._cooldownTurns[skillId] += value;855};856Game_BattlerBase.prototype.setWarmup = function(skillId, value) {857 if (!$dataSkills[skillId]) return;858 if ($dataSkills[skillId].bypassCooldown) return;859 if (this._warmupTurns === undefined) this.clearWarmups();860 this._warmupTurns[skillId] = value;861};862Game_BattlerBase.prototype.startWarmups = function() {863 if (this._warmupTurns === undefined) this.clearWarmups();864 for (var i = 0; i < this.allSkills().length; ++i) {865 var skill = this.allSkills()[i];866 if (!skill) continue;867 var warmup = skill.warmup;868 if (skill.warmupEval.length > 0) {869 var item = skill;870 var a = this;871 var user = this;872 var subject = this;873 var s = $gameSwitches._data;874 var v = $gameVariables._data;875 var code = skill.warmupEval;876 try {877 eval(code);878 } catch (e) {879 Yanfly.Util.displayError(e, code, 'CUSTOM WARMUP EVAL ERROR');880 }881 }882 warmup *= this.cooldownDuration(skill);883 warmup += this.getWarmupMods(skill);884 this.setWarmup(skill.id, warmup);885 }886};887Game_BattlerBase.prototype.updateCooldowns = function() {888 if (this._cooldownTurns === undefined) this.clearCooldowns();889 for (var skillId in this._cooldownTurns) {890 var skill = $dataSkills[skillId];891 if (!skill) continue;892 this._cooldownTurns[skillId] -= this.cooldownRate(skill);893 }894};895Game_BattlerBase.prototype.updateWarmups = function() {896 if (this._warmupTurns === undefined) this.clearWarmups();897 for (var skillId in this._warmupTurns) {898 var skill = $dataSkills[skillId];899 if (!skill) continue;900 this._warmupTurns[skillId] -= this.cooldownRate(skill);901 }902};903Game_BattlerBase.prototype.cooldownRateTick = function(skill) {904 this._cooldownTickRate = this._cooldownTickRate || {};905 if (!this._cooldownTickRate[skill.id]) {906 this._cooldownTickRate[skill.id] = this.cooldownRate(skill);907 }908 var rate = this._cooldownTickRate[skill.id];909 rate *= BattleManager.tickRate() / Yanfly.Param.CDTurnTime;910 return rate;911};912Game_BattlerBase.prototype.updateCooldownTicks = function() {913 if (this._cooldownTurns === undefined) this.clearCooldowns();914 for (var skillId in this._cooldownTurns) {915 var skill = $dataSkills[skillId];916 if (!skill) continue;917 if (this._cooldownTurns[skillId] <= 0) continue;918 this._cooldownTurns[skillId] -= this.cooldownRateTick(skill);919 this._cooldownTurns[skillId] = Math.max(0, this._cooldownTurns[skillId]);920 }921};922Game_BattlerBase.prototype.updateWarmupTicks = function() {923 if (this._warmupTurns === undefined) this.clearWarmups();924 for (var skillId in this._warmupTurns) {925 var skill = $dataSkills[skillId];926 if (!skill) continue;927 if (this._warmupTurns[skillId] <= 0) continue;928 this._warmupTurns[skillId] -= this.cooldownRateTick(skill);929 this._warmupTurns[skillId] = Math.max(0, this._warmupTurns[skillId]);930 }931};932Yanfly.SCD.Game_BattlerBase_meetsSkillConditions =933 Game_BattlerBase.prototype.meetsSkillConditions;934Game_BattlerBase.prototype.meetsSkillConditions = function(skill) {935 if (this.cooldown(skill.id) > 0) return false;936 if (this.warmup(skill.id) > 0) return false;937 return Yanfly.SCD.Game_BattlerBase_meetsSkillConditions.call(this, skill);938};939Yanfly.SCD.Game_BattlerBase_paySkillCost = 940 Game_BattlerBase.prototype.paySkillCost;941Game_BattlerBase.prototype.paySkillCost = function(skill) {942 Yanfly.SCD.Game_BattlerBase_paySkillCost.call(this, skill);943 this.payGlobalCooldown(skill);944 this.payStypeCooldownCost(skill);945 this.payCooldownCost(skill);946 this.applyCooldownMods(skill);947};948Game_BattlerBase.prototype.payGlobalCooldown = function(mainSkill) {949 for (var i = 0; i < this.allSkills().length; ++i) {950 var skill = this.allSkills()[i];951 if (!skill) continue;952 var value = mainSkill.globalCooldown;953 value *= this.cooldownDuration(mainSkill);954 value = Math.max(value, this.cooldown(skill.id));955 this.setCooldown(skill.id, value);956 }957};958Game_BattlerBase.prototype.payStypeCooldownCost = function(mainSkill) {959 for (var stypeId in mainSkill.stypeCooldown) {960 stypeId = parseInt(stypeId);961 for (var i = 0; i < this.allSkills().length; ++i) {962 var skill = this.allSkills()[i];963 if (!skill) continue;964 if (skill.stypeId !== stypeId) continue;965 var value = mainSkill.stypeCooldown[stypeId];966 value *= this.cooldownDuration(mainSkill);967 value = Math.max(value, this.cooldown(skill.id));968 this.setCooldown(skill.id, value);969 }970 }971};972Game_BattlerBase.prototype.payCooldownCost = function(skill) {973 for (var skillId in skill.cooldown) {974 skillId = parseInt(skillId);975 if (!$dataSkills[skillId]) continue;976 var cooldown = skill.cooldown[skillId];977 if (skill.id === skillId) {978 if (skill.cooldownEval.length > 0) {979 var item = skill;980 var a = this;981 var user = this;982 var subject = this;983 var s = $gameSwitches._data;984 var v = $gameVariables._data;985 var code = skill.cooldownEval;986 try {987 eval(code);988 } catch (e) {989 Yanfly.Util.displayError(e, code, 'CUSTOM COOLDOWN EVAL ERROR');990 }991 }992 }993 cooldown *= this.cooldownDuration(skill);994 cooldown = Math.max(cooldown, this.cooldown(skillId));995 this.setCooldown(skillId, cooldown);996 }997};998Game_BattlerBase.prototype.endBattleCooldowns = function() {999 this.resetCooldownTickRates();1000 for (var skillId in this._cooldownTurns) {1001 this._cooldownTurns[skillId] += $dataSkills[skillId].afterBattleCooldown;1002 }1003};1004Game_BattlerBase.prototype.resetCooldownTickRates = function() {1005 this._cooldownTickRate = {};1006};1007Game_BattlerBase.prototype.updateCooldownSteps = function() {1008 for (var skillId in this._cooldownTurns) {1009 var skill = $dataSkills[skillId];1010 if (skill) {1011 if ($gameParty.steps() % skill.cooldownSteps === 0) {1012 this._cooldownTurns[skillId] -= this.cooldownRate(skill);1013 }1014 }1015 }1016};1017Game_BattlerBase.prototype.applyCooldownEffect = function(skill) {1018 this.applyGlobalCooldownChange(skill);1019 this.applyStypeCooldownChange(skill);1020 this.applyCooldownChange(skill);1021};1022Game_BattlerBase.prototype.applyCooldownChange = function(skill) {1023 for (var skillId in skill.cooldownChange) {1024 skillId = parseInt(skillId);1025 if (!$dataSkills[skillId]) continue;1026 if (!skill.cooldownChange[skillId]) continue;1027 var value = skill.cooldownChange[skillId];1028 this.addCooldown(skillId, value);1029 }1030};1031Game_BattlerBase.prototype.applyStypeCooldownChange = function(mainSkill) {1032 for (var stypeId in mainSkill.stypeCooldownChange) {1033 stypeId = parseInt(stypeId);1034 for (var i = 0; i < this.allSkills().length; ++i) {1035 var skill = this.allSkills()[i];1036 if (!skill) continue;1037 if (skill.stypeId !== stypeId) continue;1038 if (!mainSkill.stypeCooldownChange[stypeId]) continue;1039 var value = mainSkill.stypeCooldownChange[stypeId];1040 this.addCooldown(skill.id, value);1041 }1042 }1043};1044Game_BattlerBase.prototype.applyGlobalCooldownChange = function(mainSkill) {1045 for (var i = 0; i < this.allSkills().length; ++i) {1046 var skill = this.allSkills()[i];1047 if (!skill) continue;1048 var value = mainSkill.globalCooldownChange;1049 this.addCooldown(skill.id, value);1050 }1051};1052Game_BattlerBase.prototype.getWarmupMods = function(skill) {1053 var value = 0;1054 value += this.flatWarmupChange(skill);1055 return value;1056};1057Game_BattlerBase.prototype.applyCooldownMods = function(skill) {1058 var value = this.cooldown(skill.id);1059 value += this.flatCooldownChange(skill);1060 this.setCooldown(skill.id, Math.max(0, value));1061};1062//=============================================================================1063// Game_Battler1064//=============================================================================1065Game_Battler.prototype.onBattleStartCooldowns = function() {1066 this.resetCooldownTickRates();1067 this.startWarmups();1068};1069Game_Battler.prototype.cooldownDuration = function(skill) {1070 var skillId = skill.id;1071 var stypeId = skill.stypeId;1072 var value = 1.0;1073 for (var i = 0; i < this.states().length; ++i) {1074 var state = this.states()[i];1075 if (!state) continue;1076 if (state.cooldownDuration[skillId] !== undefined) {1077 value *= state.cooldownDuration[skillId];1078 }1079 if (state.stypeCooldownDuration[stypeId] !== undefined) {1080 value *= state.stypeCooldownDuration[stypeId];1081 }1082 value *= state.globalCooldownDuration;1083 }1084 return value;1085};1086Game_Battler.prototype.cooldownRate = function(skill) {1087 var skillId = skill.id;1088 var stypeId = skill.stypeId;1089 var value = 1;1090 for (var i = 0; i < this.states().length; ++i) {1091 var state = this.states()[i];1092 if (!state) continue;1093 if (state.cooldownRate[skillId] !== undefined) {1094 value *= state.cooldownRate[skillId];1095 }1096 if (state.stypeCooldownRate[stypeId] !== undefined) {1097 value *= state.stypeCooldownRate[stypeId];1098 }1099 value *= state.globalCooldownRate;1100 }1101 return value;1102};1103Game_Battler.prototype.flatCooldownChange = function(skill) {1104 var skillId = skill.id;1105 var stypeId = skill.stypeId;1106 var value = 0;1107 for (var i = 0; i < this.states().length; ++i) {1108 var state = this.states()[i];1109 if (!state) continue;1110 if (state.cooldownChange[skillId] !== undefined) {1111 value += state.cooldownChange[skillId];1112 }1113 if (state.stypeCooldownChange[stypeId] !== undefined) {1114 value += state.stypeCooldownChange[stypeId];1115 }1116 value += state.globalCooldownChange;1117 }1118 return value;1119};1120Game_Battler.prototype.flatWarmupChange = function(skill) {1121 var skillId = skill.id;1122 var stypeId = skill.stypeId;1123 var value = 0;1124 for (var i = 0; i < this.states().length; ++i) {1125 var state = this.states()[i];1126 if (!state) continue;1127 if (state.warmupChange[skillId] !== undefined) {1128 value += state.warmupChange[skillId];1129 }1130 if (state.stypeWarmupChange[stypeId] !== undefined) {1131 value += state.stypeWarmupChange[stypeId];1132 }1133 value += state.globalWarmupChange;1134 }1135 return value;1136};1137Yanfly.SCD.Game_Battler_refresh = Game_Battler.prototype.refresh;1138Game_Battler.prototype.refresh = function() {1139 Yanfly.SCD.Game_Battler_refresh.call(this);1140 this.resetCooldownTickRates();1141};1142if (Imported.YEP_BattleEngineCore) {1143 Yanfly.SCD.Game_Battler_onTurnStart = Game_Battler.prototype.onTurnStart;1144 Game_Battler.prototype.onTurnStart = function() {1145 Yanfly.SCD.Game_Battler_onTurnStart.call(this);1146 if (BattleManager.isTickBased() && !BattleManager.timeBasedCooldowns()) {1147 this.updateCooldowns();1148 this.updateWarmups();1149 }1150 };1151 Yanfly.SCD.Game_Battler_updateTick = Game_Battler.prototype.updateTick;1152 Game_Battler.prototype.updateTick = function() {1153 Yanfly.SCD.Game_Battler_updateTick.call(this);1154 if (BattleManager.isTickBased() && BattleManager.timeBasedCooldowns()) {1155 this.updateCooldownTicks();1156 this.updateWarmupTicks();1157 };1158 };1159}; // Imported.YEP_BattleEngineCore1160Game_Battler.prototype.allSkills = function() {1161 var prevCase = $gameTemp._disableBattleSkills;1162 $gameTemp._disableBattleSkills = true;1163 var skills = this.skills();1164 $gameTemp._disableBattleSkills = prevCase;1165 return skills;1166};1167//=============================================================================1168// Game_Actor1169//=============================================================================1170Game_Actor.prototype.cooldownDuration = function(skill) {1171 var value = Game_Battler.prototype.cooldownDuration.call(this, skill);1172 var skillId = skill.id;1173 var stypeId = skill.stypeId;1174 if (this.actor().cooldownDuration[skillId] !== undefined) {1175 value *= this.actor().cooldownDuration[skillId];1176 }1177 if (this.currentClass().cooldownDuration[skillId] !== undefined) {1178 value *= this.currentClass().cooldownDuration[skillId];1179 }1180 if (this.actor().stypeCooldownDuration[stypeId] !== undefined) {1181 value *= this.actor().stypeCooldownDuration[stypeId];1182 }1183 if (this.currentClass().stypeCooldownDuration[stypeId] !== undefined) {1184 value *= this.currentClass().stypeCooldownDuration[stypeId];1185 }1186 value *= this.actor().globalCooldownDuration;1187 value *= this.currentClass().globalCooldownDuration;1188 for (var i = 0; i < this.equips().length; ++i) {1189 var equip = this.equips()[i];1190 if (!equip) continue;1191 if (equip.cooldownDuration !== undefined) {1192 if (equip.cooldownDuration[skillId] !== undefined) {1193 value *= equip.cooldownDuration[skillId];1194 }1195 }1196 if (equip.stypeCooldownDuration !== undefined) {1197 if (equip.stypeCooldownDuration[stypeId] !== undefined) {1198 value *= equip.stypeCooldownDuration[stypeId];1199 }1200 }1201 if (equip.globalCooldownDuration !== undefined) {1202 value *= equip.globalCooldownDuration;1203 }1204 }1205 return value;1206};1207Game_Actor.prototype.cooldownRate = function(skill) {1208 var value = Game_Battler.prototype.cooldownRate.call(this, skill);1209 var skillId = skill.id;1210 var stypeId = skill.stypeId;1211 if (this.actor().cooldownRate[skillId] !== undefined) {1212 value *= this.actor().cooldownRate[skillId];1213 }1214 if (this.currentClass().cooldownRate[skillId] !== undefined) {1215 value *= this.currentClass().cooldownRate[skillId];1216 }1217 if (this.actor().stypeCooldownRate[stypeId] !== undefined) {1218 value *= this.actor().stypeCooldownRate[stypeId];1219 }1220 if (this.currentClass().stypeCooldownRate[stypeId] !== undefined) {1221 value *= this.currentClass().stypeCooldownRate[stypeId];1222 }1223 value *= this.actor().globalCooldownRate;1224 value *= this.currentClass().globalCooldownRate;1225 for (var i = 0; i < this.equips().length; ++i) {1226 var equip = this.equips()[i];1227 if (!equip) continue;1228 if (equip.cooldownRate !== undefined) {1229 if (equip.cooldownRate[skillId] !== undefined) {1230 value *= equip.cooldownRate[skillId];1231 }1232 }1233 if (equip.stypeCooldownRate !== undefined) {1234 if (equip.stypeCooldownRate[stypeId] !== undefined) {1235 value *= equip.stypeCooldownRate[stypeId];1236 }1237 }1238 if (equip.globalCooldownRate !== undefined) {1239 value *= equip.globalCooldownRate;1240 }1241 }1242 return value;1243};1244Game_Actor.prototype.flatCooldownChange = function(skill) {1245 var skillId = skill.id;1246 var stypeId = skill.stypeId;1247 var value = Game_Battler.prototype.flatCooldownChange.call(this, skill);1248 if (this.actor().cooldownChange[skillId] !== undefined) {1249 value += this.actor().cooldownChange[skillId];1250 }1251 if (this.currentClass().cooldownChange[skillId] !== undefined) {1252 value += this.currentClass().cooldownChange[skillId];1253 }1254 if (this.actor().stypeCooldownChange[stypeId] !== undefined) {1255 value += this.actor().stypeCooldownChange[stypeId];1256 }1257 if (this.currentClass().stypeCooldownChange[stypeId] !== undefined) {1258 value += this.currentClass().stypeCooldownChange[stypeId];1259 }1260 value += this.actor().globalCooldownChange;1261 value += this.currentClass().globalCooldownChange;1262 for (var i = 0; i < this.equips().length; ++i) {1263 var equip = this.equips()[i];1264 if (!equip) continue;1265 if (equip.cooldownChange === undefined) continue;1266 if (equip.cooldownChange[skillId] !== undefined) {1267 value += equip.cooldownChange[skillId];1268 }1269 if (equip.stypeCooldownChange[stypeId] !== undefined) {1270 value += equip.stypeCooldownChange[stypeId];1271 }1272 value += equip.globalCooldownChange;1273 }1274 return value;1275};1276Game_Actor.prototype.flatWarmupChange = function(skill) {1277 var skillId = skill.id;1278 var stypeId = skill.stypeId;1279 var value = Game_Battler.prototype.flatWarmupChange.call(this, skill);1280 if (this.actor().warmupChange[skillId] !== undefined) {1281 value += this.actor().warmupChange[skillId];1282 }1283 if (this.currentClass().warmupChange[skillId] !== undefined) {1284 value += this.currentClass().warmupChange[skillId];1285 }1286 if (this.actor().stypeWarmupChange[stypeId] !== undefined) {1287 value += this.actor().stypeWarmupChange[stypeId];1288 }1289 if (this.currentClass().stypeWarmupChange[stypeId] !== undefined) {1290 value += this.currentClass().stypeWarmupChange[stypeId];1291 }1292 value += this.actor().globalWarmupChange;1293 value += this.currentClass().globalWarmupChange;1294 for (var i = 0; i < this.equips().length; ++i) {1295 var equip = this.equips()[i];1296 if (!equip) continue;1297 if (equip.warmupChange === undefined) continue;1298 if (equip.warmupChange[skillId] !== undefined) {1299 value += equip.warmupChange[skillId];1300 }1301 if (equip.stypeWarmupChange[stypeId] !== undefined) {1302 value += equip.stypeWarmupChange[stypeId];1303 }1304 value += equip.globalWarmupChange;1305 }1306 return value;1307};1308//=============================================================================1309// Game_Enemy1310//=============================================================================1311if (!Game_Enemy.prototype.skills) {1312 Game_Enemy.prototype.skills = function() {1313 var skills = []1314 for (var i = 0; i < this.enemy().actions.length; ++i) {1315 var skill = $dataSkills[this.enemy().actions[i].skillId]1316 if (skill) skills.push(skill);1317 }1318 return skills;1319 }1320};1321Game_Enemy.prototype.cooldownDuration = function(skill) {1322 var value = Game_Battler.prototype.cooldownDuration.call(this, skill);1323 var skillId = skill.id;1324 var stypeId = skill.stypeId;1325 if (this.enemy().cooldownDuration[skillId] !== undefined) {1326 value *= this.enemy().cooldownDuration[skillId];1327 }1328 if (this.enemy().stypeCooldownDuration[stypeId] !== undefined) {1329 value *= this.enemy().stypeCooldownDuration[stypeId];1330 }1331 value *= this.enemy().globalCooldownDuration;1332 return value;1333};1334Game_Enemy.prototype.cooldownRate = function(skill) {1335 var value = Game_Battler.prototype.cooldownRate.call(this, skill);1336 var skillId = skill.id;1337 var stypeId = skill.stypeId;1338 if (this.enemy().cooldownRate[skillId] !== undefined) {1339 value *= this.enemy().cooldownRate[skillId];1340 }1341 if (this.enemy().stypeCooldownRate[stypeId] !== undefined) {1342 value *= this.enemy().stypeCooldownRate[stypeId];1343 }1344 value *= this.enemy().globalCooldownRate;1345 return value;1346};1347Game_Enemy.prototype.flatCooldownChange = function(skill) {1348 var skillId = skill.id;1349 var stypeId = skill.stypeId;1350 var value = Game_Battler.prototype.flatCooldownChange.call(this, skill);1351 if (this.enemy().cooldownChange[skillId] !== undefined) {1352 value += this.enemy().cooldownChange[skillId];1353 }1354 if (this.enemy().stypeCooldownChange[stypeId] !== undefined) {1355 value += this.enemy().stypeCooldownChange[stypeId];1356 }1357 value += this.enemy().globalCooldownChange;1358 return value;1359};1360Game_Enemy.prototype.flatWarmupChange = function(skill) {1361 var skillId = skill.id;1362 var stypeId = skill.stypeId;1363 var value = Game_Battler.prototype.flatWarmupChange.call(this, skill);1364 if (this.enemy().warmupChange[skillId] !== undefined) {1365 value += this.enemy().warmupChange[skillId];1366 }1367 if (this.enemy().stypeWarmupChange[stypeId] !== undefined) {1368 value += this.enemy().stypeWarmupChange[stypeId];1369 }1370 value += this.enemy().globalWarmupChange;1371 return value;1372};1373//=============================================================================1374// Game_Action1375//=============================================================================1376Yanfly.SCD.Game_Action_applyItemUserEffect =1377 Game_Action.prototype.applyItemUserEffect;1378Game_Action.prototype.applyItemUserEffect = function(target) {1379 Yanfly.SCD.Game_Action_applyItemUserEffect.call(this, target);1380 if (target) target.applyCooldownEffect(this.item());1381};1382//=============================================================================1383// Game_Unit1384//=============================================================================1385Yanfly.SCD.Game_Unit_onBattleStart = Game_Unit.prototype.onBattleStart;1386Game_Unit.prototype.onBattleStart = function() {1387 Yanfly.SCD.Game_Unit_onBattleStart.call(this);1388 this.onBattleStartCooldowns();1389};1390Game_Unit.prototype.onBattleStartCooldowns = function() {1391 var members = this.cooldownMembers();1392 var length = members.length1393 for (var i = 0; i < length; ++i) {1394 var member = members[i];1395 if (member) member.onBattleStartCooldowns();1396 }1397};1398Game_Unit.prototype.updateCooldowns = function() {1399 if (BattleManager.timeBasedCooldowns()) return;1400 var members = this.members();1401 var length = members.length1402 for (var i = 0; i < length; ++i) {1403 var member = members[i];1404 if (member) {1405 member.updateCooldowns();1406 member.updateWarmups();1407 }1408 }1409};1410Game_Unit.prototype.endBattleCooldowns = function() {1411 var members = this.members();1412 var length = members.length1413 for (var i = 0; i < length; ++i) {1414 var member = members[i];1415 if (member) {1416 member.endBattleCooldowns();1417 member.clearWarmups();1418 }1419 }1420};1421Game_Unit.prototype.cooldownMembers = function() {1422 return this.members();1423};1424//=============================================================================1425// Game_Party1426//=============================================================================1427Yanfly.SCD.Game_Party_increaseSteps = Game_Party.prototype.increaseSteps;1428Game_Party.prototype.increaseSteps = function() {1429 Yanfly.SCD.Game_Party_increaseSteps.call(this);1430 this.updateCooldownSteps();1431};1432Game_Party.prototype.updateCooldownSteps = function() {1433 return this.members().forEach(function(member) {1434 return member.updateCooldownSteps();1435 });1436};1437Game_Party.prototype.cooldownMembers = function() {1438 return this.allMembers();1439};1440//=============================================================================1441// Game_Troop1442//=============================================================================1443Yanfly.SCD.Game_Troop_increaseTurn = Game_Troop.prototype.increaseTurn;1444Game_Troop.prototype.increaseTurn = function() {1445 Yanfly.SCD.Game_Troop_increaseTurn.call(this);1446 if (Imported.YEP_BattleEngineCore) {1447 if (BattleManager.isTurnBased()) {1448 this.updateCooldowns();1449 $gameParty.updateCooldowns();1450 }1451 } else {1452 this.updateCooldowns();1453 $gameParty.updateCooldowns();1454 }1455};1456//=============================================================================1457// Window_SkillList1458//=============================================================================1459Yanfly.SCD.Window_SkillList_drawCost = Window_SkillList.prototype.drawSkillCost;1460Window_SkillList.prototype.drawSkillCost = function(skill, wx, wy, ww) {1461 if (this._actor.warmup(skill.id) > 0) {1462 return this.drawWarmup(skill, wx, wy, ww);1463 } else if (this._actor.cooldown(skill.id) > 0) {1464 return this.drawCooldown(skill, wx, wy, ww);1465 } else {1466 return Yanfly.SCD.Window_SkillList_drawCost.call(this, skill, wx, wy, ww);1467 }1468};1469Window_SkillList.prototype.drawCooldown = function(skill, wx, wy, dw) {1470 if (Yanfly.Icon.Cooldown > 0) {1471 var iw = wx + dw - Window_Base._iconWidth;1472 this.drawIcon(Yanfly.Icon.Cooldown, iw, wy + 2);1473 dw -= Window_Base._iconWidth + 2;1474 }1475 this.changeTextColor(this.textColor(Yanfly.Param.CDTextColor));1476 var fmt = Yanfly.Param.CDFmt;1477 var value = this._actor.cooldown(skill.id);1478 if (value % 1 !== 0) value = value.toFixed(2);1479 if (value <= 0.009) value = 0.01;1480 var text = fmt.format(Yanfly.Util.toGroup(value));1481 this.contents.fontSize = Yanfly.Param.CDFontSize;1482 this.drawText(text, wx, wy, dw, 'right');1483 var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding;1484 this.resetFontSettings();1485 return returnWidth;1486};1487Window_SkillList.prototype.drawWarmup = function(skill, wx, wy, dw) {1488 if (Yanfly.Icon.Warmup > 0) {1489 var iw = wx + dw - Window_Base._iconWidth;1490 this.drawIcon(Yanfly.Icon.Warmup, iw, wy + 2);1491 dw -= Window_Base._iconWidth + 2;1492 }1493 this.changeTextColor(this.textColor(Yanfly.Param.WUTextColor));1494 var fmt = Yanfly.Param.WUFmt;1495 var value = this._actor.warmup(skill.id);1496 if (value % 1 !== 0) value = value.toFixed(2);1497 if (value <= 0.009) value = 0.01;1498 var text = fmt.format(Yanfly.Util.toGroup(value));1499 this.contents.fontSize = Yanfly.Param.WUFontSize;1500 this.drawText(text, wx, wy, dw, 'right');1501 var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding;1502 this.resetFontSettings();1503 return returnWidth;1504};1505//=============================================================================1506// Utilities1507//=============================================================================1508Yanfly.Util = Yanfly.Util || {};1509if (!Yanfly.Util.toGroup) {1510 Yanfly.Util.toGroup = function(inVal) {1511 return inVal;1512 }1513};1514//=============================================================================1515// End of File1516//=============================================================================...

Full Screen

Full Screen

CacheWarmupMenu.ts

Source:CacheWarmupMenu.ts Github

copy

Full Screen

1'use strict'2/*3 * This file is part of the TYPO3 CMS extension "warming".4 *5 * Copyright (C) 2021 Elias Häußler <elias@haeussler.dev>6 *7 * This program is free software: you can redistribute it and/or modify8 * it under the terms of the GNU General Public License as published by9 * the Free Software Foundation, either version 2 of the License, or10 * (at your option) any later version.11 *12 * This program is distributed in the hope that it will be useful,13 * but WITHOUT ANY WARRANTY; without even the implied warranty of14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the15 * GNU General Public License for more details.16 *17 * You should have received a copy of the GNU General Public License18 * along with this program. If not, see <https://www.gnu.org/licenses/>.19 */20import 'select2';21import * as clipboard from 'clipboard-polyfill/text';22import IconIdentifiers from '../../../lib/Enums/IconIdentifiers';23import LanguageKeys from '../../../lib/Enums/LanguageKeys';24import WarmupProgress from '../../../lib/WarmupProgress';25import WarmupRequest from '../../../lib/WarmupRequest';26import WarmupRequestMode from '../../../lib/Enums/WarmupRequestMode';27import WarmupRequestType from '../../../lib/Enums/WarmupRequestType';28import WarmupState from '../../../lib/Enums/WarmupState';29// Modules30import $ from 'jquery';31import ImmediateAction from "TYPO3/CMS/Backend/ActionButton/ImmediateAction";32import Icons from 'TYPO3/CMS/Backend/Icons';33import Notification from 'TYPO3/CMS/Backend/Notification';34import Viewport from 'TYPO3/CMS/Backend/Viewport';35import AjaxRequest from 'TYPO3/CMS/Core/Ajax/AjaxRequest';36import AjaxResponse from 'TYPO3/CMS/Core/Ajax/AjaxResponse';37import CacheWarmupProgressModal from '../Modal/CacheWarmupProgressModal';38import CacheWarmupReportModal from '../Modal/CacheWarmupReportModal';39/**40 * Selectors for several components within cache warmup menu.41 *42 * @author Elias Häußler <elias@haeussler.dev>43 * @license GPL-2.0-or-later44 */45enum CacheWarmupMenuSelectors {46 container = '#eliashaeussler-typo3warming-backend-toolbaritems-cachewarmuptoolbaritem',47 dropdownTable = '.dropdown-table',48 menuItem = 'a.toolbar-cache-warmup-action',49 toolbarIcon = '.toolbar-item-icon .t3js-icon',50 languageSelect = '.tx-warming-language-select',51 languageSelectWrapper = '.tx-warming-language-select-wrapper',52 languageSelectDropdown = '.tx-warming-language-select-dropdown',53 useragentCopy = 'button.toolbar-cache-warmup-useragent-copy-action',54 useragentCopyIcon = '.t3js-icon',55 useragentCopyText = '.toolbar-cache-warmup-useragent-copy-text',56}57/**58 * AMD module that handles cache warmup from the Backend toolbar.59 *60 * Module: TYPO3/CMS/Warming/Backend/Toolbar/CacheWarmupMenu61 *62 * @author Elias Häußler <elias@haeussler.dev>63 * @license GPL-2.0-or-later64 */65export class CacheWarmupMenu {66 private notificationDuration = 15;67 constructor() {68 Viewport.Topbar.Toolbar.registerEvent((): void => this.fetchSites());69 // Copy user agent to clipboard in case the copy button is clicked70 $(CacheWarmupMenuSelectors.container).on('click', CacheWarmupMenuSelectors.useragentCopy, (event: JQuery.TriggeredEvent): void => {71 event.preventDefault();72 event.stopImmediatePropagation();73 const userAgent = $(event.currentTarget).attr('data-text');74 if (userAgent) {75 this.copyUserAgentToClipboard(userAgent);76 }77 });78 }79 /**80 * Trigger cache warmup for given page in given mode.81 *82 * Creates a new object of {@link WarmupRequest} for the given page id and warmup83 * request mode and starts cache warmup. In the meantime, the toolbar icon is84 * replaced by a spinner indicating that a cache warmup is in progress. Once the85 * cache warmup is finished, a notification is shown. If it fails, an error86 * notification is shown instead.87 *88 * @param pageId {number} Root page ID whose caches should be warmed up89 * @param mode {WarmupRequestMode} Requested warmup request mode90 * @param languageId {number|null} Optional language ID of a specific site language whose caches should be warmed up91 */92 public warmupCache(pageId: number, mode: WarmupRequestMode = WarmupRequestMode.Site, languageId: number | null = null): void {93 const $toolbarItemIcon = $(CacheWarmupMenuSelectors.toolbarIcon, CacheWarmupMenuSelectors.container);94 const $existingIcon = $toolbarItemIcon.clone();95 // Close dropdown menu96 $(CacheWarmupMenuSelectors.container).removeClass('open');97 // Show spinner during cache warmup98 Icons.getIcon(IconIdentifiers.spinner, Icons.sizes.small).then((spinner: string): void => {99 $toolbarItemIcon.replaceWith(spinner);100 });101 const request = new WarmupRequest(pageId, mode, languageId);102 request.runWarmup()103 .then(104 // Success105 (data: WarmupProgress): void => {106 let action;107 // Add option to restart cache warmup if it has been aborted108 if (WarmupState.Aborted === data.state) {109 action = {110 label: TYPO3.lang[LanguageKeys.notificationActionRetry],111 action: new ImmediateAction((): void => this.warmupCache(pageId, mode, languageId)),112 };113 }114 this.showNotification(data, action);115 // Apply trigger function to "retry" button of progress modal116 if (WarmupRequestType.EventSource === request.requestType && WarmupState.Aborted !== data.state) {117 CacheWarmupProgressModal.getRetryButton()118 .removeClass('hidden')119 .off('button.clicked')120 .on('button.clicked', (): void => this.warmupCache(pageId, mode, languageId));121 }122 },123 // Error124 (): void => CacheWarmupMenu.errorNotification(),125 )126 .finally((): void => {127 $(CacheWarmupMenuSelectors.toolbarIcon, CacheWarmupMenuSelectors.container).replaceWith($existingIcon);128 });129 }130 /**131 * Fetch sites that are available for cache warmup.132 *133 * Creates an AJAX request to fetch all available sites that are ready for134 * cache warmup and replaces the table in the toolbar menu item with the135 * fetched content.136 *137 * @private138 */139 private fetchSites(): void {140 const $toolbarItemIcon = $(CacheWarmupMenuSelectors.toolbarIcon, CacheWarmupMenuSelectors.container);141 const $existingIcon = $toolbarItemIcon.clone();142 // Close dropdown menu143 $(CacheWarmupMenuSelectors.container).removeClass('open');144 // Show spinner during cache warmup145 Icons.getIcon(IconIdentifiers.spinner, Icons.sizes.small).then((spinner: string): void => {146 $toolbarItemIcon.replaceWith(spinner);147 });148 // Fetch rendered sites149 (new AjaxRequest(TYPO3.settings.ajaxUrls.tx_warming_fetch_sites))150 .get()151 .then(152 async (response: typeof AjaxResponse): Promise<void> => {153 // Replace placeholder with real data154 const data = await response.resolve();155 $(CacheWarmupMenuSelectors.dropdownTable, CacheWarmupMenuSelectors.container).html(data);156 // Initialize events for inserted DOM elements157 this.initializeEvents();158 }159 )160 .finally((): void => {161 $(CacheWarmupMenuSelectors.toolbarIcon, CacheWarmupMenuSelectors.container).replaceWith($existingIcon);162 });163 }164 /**165 * Initialize DOM events for several components in the cache warmup menu.166 *167 * @private168 */169 private initializeEvents(): void {170 // Trigger cache warmup in case a menu item is clicked171 $(CacheWarmupMenuSelectors.container).on('click', CacheWarmupMenuSelectors.menuItem, (event: JQuery.TriggeredEvent): void => {172 event.preventDefault();173 const pageId = $(event.currentTarget).attr('data-page-id');174 if (pageId) {175 this.warmupCache(Number(pageId));176 }177 });178 const $languageSelectWrapper = $(CacheWarmupMenuSelectors.languageSelectWrapper, CacheWarmupMenuSelectors.container);179 const $languageSelect = $(CacheWarmupMenuSelectors.languageSelect, $languageSelectWrapper);180 // Initialize select2 element for language selections181 $languageSelect.select2({182 placeholder: {183 // Use first select option with value="null" (disabled) as placeholder184 id: 'null',185 text: TYPO3.lang[LanguageKeys.toolbarSitemapPlaceholder],186 },187 // Disable search form188 minimumResultsForSearch: Infinity,189 width: '100%',190 dropdownCssClass: 'tx-warming-language-select-dropdown',191 dropdownAutoWidth: true,192 templateResult: (state: Select2.LoadingData): JQuery | null => {193 // Only valid language options are supported194 if (!state.id) {195 return null;196 }197 // Build option element from icon (flag) and text198 const $element = $(state.element as unknown as string);199 const $flag = $('<span class="tx-warming-language-select-option-flag">').append($element.data('icon'));200 const $content = $('<span class="tx-warming-language-select-option-text">').append(201 $('<strong>').text(state.text),202 $('<br>')203 );204 // Add sitemap URL or error message to option element205 if ($element.data('missing')) {206 $content.append(TYPO3.lang[LanguageKeys.toolbarSitemapMissing]);207 } else {208 $content.append($element.data('sitemap-url'));209 }210 // Create and return final option element211 return $('<span class="tx-warming-language-select-option">').append($flag, $content);212 }213 });214 // Prevent Bootstrap from closing toolbar item (= dropdown)215 // when language select menu is opened or interacted with216 $languageSelectWrapper.on('click', '.select2', (event: JQuery.TriggeredEvent): void => {217 event.preventDefault();218 event.stopImmediatePropagation();219 });220 $languageSelect.on('select2:open', (): void => {221 const $dropdown = $(CacheWarmupMenuSelectors.languageSelectDropdown);222 $dropdown.off('click', 'li');223 $dropdown.on('click', 'li', (event: JQuery.TriggeredEvent): void => {224 event.preventDefault();225 event.stopImmediatePropagation();226 });227 });228 // Trigger warmup for a concrete language229 $languageSelect.on('change', (event: JQuery.TriggeredEvent): void => {230 const $selectedOption = $(event.target).find(':selected');231 const pageId = $selectedOption.data('page-id');232 const languageId = $selectedOption.val();233 if (pageId && 'string' === typeof languageId) {234 // Trigger cache warmup for page and language235 this.warmupCache(Number(pageId), WarmupRequestMode.Site, Number(languageId));236 // Reset language selection to placeholder option237 $(event.target).val('null').trigger('change');238 }239 });240 }241 /**242 * Copy given User-Agent header to clipboard.243 *244 * @param userAgent {string} User-Agent header to be copied to clipboard245 * @private246 */247 private copyUserAgentToClipboard(userAgent: string): void {248 const $copyIcon = $(CacheWarmupMenuSelectors.useragentCopyIcon, CacheWarmupMenuSelectors.useragentCopy);249 const $existingIcon = $copyIcon.clone();250 // Show spinner when copying user agent251 Icons.getIcon(IconIdentifiers.spinner, Icons.sizes.small).then((spinner: string): void => {252 $copyIcon.replaceWith(spinner);253 });254 // Copy user agent to clipboard255 Promise.all([256 (navigator.clipboard ?? clipboard).writeText(userAgent),257 Icons.getIcon(IconIdentifiers.check, Icons.sizes.small),258 ])259 .then(260 async ([, icon]): Promise<void> => {261 const existingText = $(CacheWarmupMenuSelectors.useragentCopyText).text();262 $(CacheWarmupMenuSelectors.useragentCopyText).text(TYPO3.lang[LanguageKeys.toolbarCopySuccessful]);263 $(CacheWarmupMenuSelectors.useragentCopyIcon, CacheWarmupMenuSelectors.useragentCopy).replaceWith(icon);264 // Restore copy button after 3 seconds265 window.setTimeout((): void => {266 $(CacheWarmupMenuSelectors.useragentCopyIcon, CacheWarmupMenuSelectors.useragentCopy).replaceWith($existingIcon);267 $(CacheWarmupMenuSelectors.useragentCopyText).text(existingText);268 $(CacheWarmupMenuSelectors.useragentCopy).trigger('blur');269 }, 3000);270 },271 (): void => {272 $(CacheWarmupMenuSelectors.useragentCopyIcon, CacheWarmupMenuSelectors.useragentCopy).replaceWith($existingIcon);273 }274 );275 }276 /**277 * Show notification for given cache warmup progress.278 *279 * @param progress {WarmupProgress} Progress of the cache warmup a notification is built for280 * @param additionalAction {object|null} Additional action to be used for the generated notification281 * @private282 */283 private showNotification(progress: WarmupProgress, additionalAction?: { label: string, action: typeof ImmediateAction }): void {284 let {title, message} = progress.response;285 // Create action to open full report as modal286 const reportAction = CacheWarmupReportModal.createModalAction(progress);287 // Define modal actions288 const actions = [reportAction];289 if (additionalAction) {290 actions.push(additionalAction);291 }292 // Show notification293 switch (progress.state) {294 case WarmupState.Failed:295 Notification.error(title, message, this.notificationDuration, actions);296 break;297 case WarmupState.Warning:298 Notification.warning(title, message, this.notificationDuration, actions);299 break;300 case WarmupState.Success:301 Notification.success(title, message, this.notificationDuration, actions);302 break;303 case WarmupState.Aborted:304 title = TYPO3.lang[LanguageKeys.notificationAbortedTitle];305 message = TYPO3.lang[LanguageKeys.notificationAbortedMessage];306 Notification.info(title, message, this.notificationDuration, actions);307 break;308 case WarmupState.Unknown:309 Notification.notice(title, message, this.notificationDuration);310 break;311 default:312 CacheWarmupMenu.errorNotification();313 break;314 }315 }316 /**317 * Show error notification on erroneous cache warmup.318 *319 * @private320 */321 private static errorNotification(): void {322 Notification.error(TYPO3.lang[LanguageKeys.notificationErrorTitle], TYPO3.lang[LanguageKeys.notificationErrorMessage]);323 }324}...

Full Screen

Full Screen

binaryarith.js

Source:binaryarith.js Github

copy

Full Screen

1setJitCompilerOption('ion.forceinlineCaches', 1);2function warmup(fun, input_array) {3 for (var index = 0; index < input_array.length; index++) {4 input = input_array[index];5 input_lhs = input[0];6 input_rhs = input[1];7 output = input[2];8 for (var i = 0; i < 30; i++) {9 var y = fun(input_lhs, input_rhs);10 assertEq(y, output)11 }12 }13}14// Add: Int32 + Int32 Overflow15var funAdd1 = (a, b) => { return a + b; }16warmup(funAdd1, [[1,2, 3], [3,4, 7], [4294967295, 2, 4294967297]]);17// Add: Doubles18var funAdd2 = (a, b) => { return a + b; }19warmup(funAdd2, [[1.2, 2, 3.2], [3.5, 4, 7.5], [4294967295.1, 2, 4294967297.1]]);20// Add: Type Change Int32 -> Double21var funAdd3 = (a, b) => { return a + b; }22warmup(funAdd3, [[1, 2, 3], [3, 4, 7], [4294967295, 2, 4294967297], [1.2, 2, 3.2]]);23//Add: String Concat24var funAdd4 = (a, b) => { return a + b; }25warmup(funAdd4, [["","a","a"], ["ab","ba","abba"], ["123","456","123456"]])26function D(name) { this.name = name; }27D.prototype.toString = function stringify() {28 return this.name;29}30obj1 = new D('A');31// Add: String Object Concat32var funAdd4 = (a, b) => { return a + b; }33warmup(funAdd4, [["x", obj1, "xA"], [obj1, "bba", "Abba"]]);34// Add: Int32 Boolean35var funAdd5 = (a, b) => { return a + b; }36warmup(funAdd5, [[true, 10, 11], [false, 1, 1], [10, true, 11], [1, false, 1],37 [2147483647, true, 2147483648],[true, 2147483647, 2147483648]]);38// Add: String Number Concat39var funAdd6 = (a, b) => { return a + b; }40warmup(funAdd6, [["x", 10, "x10"], [10, "bba", "10bba"], ["x", 1.2, "x1.2"],41 [1.2, "bba", "1.2bba"]]);42// Add: String Boolean43var funAddStrBool = (a, b) => { return a + b; }44warmup(funAddStrBool, [[true, "true", "truetrue"], [false, "true", "falsetrue"],45 ["a string", true, "a stringtrue"]]);46// Sub Int3247var funSub1 = (a, b) => { return a - b; }48warmup(funSub1, [[7, 0, 7], [7, 8, -1], [4294967295, 2, 4294967293], [0,0,0]]);49// Sub Double50var funSub2 = (a, b) => { return a - b; }51warmup(funSub2, [[7.5, 0, 7.5], [7, 8.125, -1.125], [4294967295.3125, 2, 4294967293.3125], [NaN,10,NaN]]);52// Sub Int32 + Boolean53var funSub3 = (a, b) => { return a - b; }54warmup(funSub3, [[7, false, 7], [7, true, 6], [false, 1, -1], [true,1,0]]);55// Mul: Int32+ Int32 Overflow56var funMul1 = (a, b) => { return a * b; }57warmup(funMul1, [[1, 2, 2], [10, 21, 210], [3, 4, 12], [2147483649, 2, 4294967298], [1073741824, 1024, 1099511627776 ]]);58// Mul: Doubles59var funMul2 = (a, b) => { return a * b; }60warmup(funMul2, [[3/32, 32, 3], [16/64, 32, 8], [3.0, 1.0, 3], [-1, 0, -0], [0, -20, -0]]);61// Mul: Type change Int32 -> Double62var funMul3 = (a, b) => { return a * b; }63warmup(funMul3, [[1,2, 2], [10, 21, 210], [3, 4, 12], [63/32, 32, 63], [16/64, 32, 8]]);64// Mul: Boolean65var funMul1 = (a, b) => { return a * b; }66warmup(funMul1, [[1, true, 1], [10, false, 0], [false, 4, 0], [2147483640, true, 2147483640]]);67//Div: Int3268var funDiv1 = (a,b) => { return a / b;}69warmup(funDiv1,[[8, 4, 2], [16, 32, 0.5], [10, 0, Infinity], [0, 0, NaN]]);70//Div: Double71var funDiv2 = (a,b) => { return a / b;}72warmup(funDiv2, [[8.8, 4, 2.2], [16.8, 32, 0.525], [10, 0.5, 20]]);73//Div: Type change Int32 -> Double74var funDiv3 = (a,b) => { return a / b;}75warmup(funDiv1, [[8, 4, 2], [16, 32, 0.5], [10, 0, Infinity], [0, 0, NaN], [8.8, 4, 2.2],76 [16.8, 32, 0.525], [10, 0.5, 20]]);77//Div: Boolean w/ Int3278var funDiv4 = (a,b) => { return a / b;}79warmup(funDiv4,[[8, true, 8], [true, 2, 0.5], [10, false, Infinity], [false, false, NaN]]);80//Mod: Int3281var funMod1 = (a,b) => {return a % b};82warmup(funMod1, [[8, 4, 0], [9, 4, 1], [-1, 2, -1], [4294967297, 2, 1],83 [10, -3, 1]]);84//Mod: Double85var funMod2 = (a,b) => {return a % b};86warmup(funMod2, [[8.5, 1, 0.5], [9.5, 0.5, 0], [-0.03125, 0.0625, -0.03125], [1.64, 1.16, 0.48]]);87//Mod: Type change Int32 -> Double88var funMod3 = (a,b) => {return a % b};89warmup(funMod3, [[10, 0, NaN], [8, 4, 0], [9, 4, 1], [-1, 2, -1], [4294967297, 2, 1],90 [8.5, 1, 0.5], [9.5, 0.5, 0], [-0.03125, 0.0625, -0.03125],91 [1.64, 1.16, 0.48]]);92//Mod: Boolean w/ Int3293var funMod4 = (a,b) => {return a % b};94warmup(funMod4, [[10, false, NaN], [8, true, 0], [false, 4, 0], [true, 2, 1]]);95//Pow: Int3296var funPow1 = (a,b) => {return a ** b};97warmup(funPow1, [[8, 4, 4096], [9, 4, 6561], [-1, 2, 1], [2, -10000, 0],98 [-3, 3, -27]]);99//Pow: Double100var funPow2 = (a,b) => {return a ** b};101warmup(funPow2, [[8.5, 1, 8.5], [16, 0.5, 4], [4.5, 5, 1845.28125], [18.0625, 0.5, 4.25],102 [4, -1, 0.25]]);103//Pow: Type change Int32 -> Double104var funPow3 = (a,b) => {return a ** b};105warmup(funPow3, [[10, 0, 1], [8, 4, 4096], [9, 4, 6561], [-1, 2, 1], [2, -10000, 0],106 [8.5, 1, 8.5], [16, 0.5, 4], [4.5, 5, 1845.28125], [18.0625, 0.5, 4.25],107 [4, -1, 0.25]]);108//Pow: Boolean w/ Int32109var funPow4 = (a,b) => {return a ** b};110warmup(funPow4, [[10, 2, 100], [8, true, 8], [false, 4, 0], [true, 2, 1]]);111//BitOr Int32112var funBitOr1 = (a, b) => { return a | b; }113warmup(funBitOr1, [[1, 1, 1], [8, 1, 9], [0, 1233, 1233], [5, 0, 5],114 [4294967295, 123231, -1], [2147483647, 1243524, 2147483647]]);115//BitOr Boolean w/ Int32116var funBitOr3 = (a, b) => { return a | b; }117warmup(funBitOr3, [[1, true, 1], [8, true, 9], [false, 1233, 1233], [5, false, 5]]);118//BitOr null w/ Int32119var funBitOr4 = (a, b) => { return a | b; }120warmup(funBitOr4, [[1, null, 1], [8, null, 8], [null, 1233, 1233], [5, null, 5]]);121//BitOr undefined w/ Int32122var funBitOr5 = (a, b) => { return a | b; }123warmup(funBitOr5, [[1, void 0, 1], [8, void 0, 8], [void 0, 1233, 1233], [5, void 0, 5]]);124//BitXOr Int32125var funBitXOr1 = (a, b) => { return a ^ b; }126warmup(funBitXOr1, [[1, 1, 0], [5, 1, 4], [63, 31, 32], [4294967295, 2147483647, -2147483648 ] ]);127//BitXOr Int32128var funBitXOr2 = (a, b) => { return a ^ b; }129warmup(funBitXOr2, [[1, true, 0], [5, true, 4], [5, false, 5], [false, 1, 1]]);130//BitXOr Double+int32131var funBitXOr3 = (a, b) => { return a ^ b; }132warmup(funBitXOr3, [[1.3, 1, 0], [5, 1.4, 4], [63.1, 31, 32], [4294967295.9, 2147483647, -2147483648 ] ]);133//BitXOr Number Number134var funBitXOr4 = (a, b) => { return a ^ b; }135warmup(funBitXOr4, [[54772703898, 2890608493, 1828589047],136 [-54772703898, 2890608493, -1828589045],137 [18446744073709551615, 54772703898, -1061870950], //UINT64 Max138 [-18446744073709551615, 54772703898, -1061870950],139 [4294967295, -1, 0]]);140//BitXOr null+int32141var funBitXOr5 = (a, b) => { return a ^ b; }142warmup(funBitXOr5, [[1, null, 1], [5, null, 5], [5, null, 5], [null, 1, 1]]);143//BitXOr undefined+int32144var funBitXOr6 = (a, b) => { return a ^ b; }145warmup(funBitXOr6, [[1, void 0, 1], [5, void 0, 5], [5, void 0, 5], [void 0, 1, 1]]);146//BitAnd Int32147var funBitAnd1 = (a, b) => { return a & b; }148warmup(funBitAnd1, [[1,1,1], [5,1,1], [63,31,31], [4294967295,2147483647,2147483647],149 [-2,10,10], [-15,-2,-16], [4,128,0]]);150//BitAnd Double w/ Int32151var funBitAnd2 = (a, b) => { return a & b; }152warmup(funBitAnd2, [[1.2 ,1, 1], [5, 1.4, 1], [63,31.99,31],153 [4294967295.98,2147483647,2147483647],154 [-2.9, 10, 10], [-15,-2.9,-16], [4,128.01,0]]);155//BitAnd Int32 + Boolean156var funBitAnd1 = (a, b) => { return a & b; }157warmup(funBitAnd1, [[1,true,1], [5,false,0], [true, 6, 0], [false, 12, 0]]);158//BitAnd Int32 + null159var funBitAnd4 = (a, b) => { return a & b; }160warmup(funBitAnd4, [[1, null, 0], [5, null, 0], [null, 6, 0], [null, 12, 0]]);161//BitAnd Int32 + undefined162var funBitAnd5 = (a, b) => { return a & b; }163warmup(funBitAnd5, [[1, void 0, 0], [5, void 0, 0], [void 0, 6, 0], [void 0, 12, 0]]);164//Lsh Int32165var funLsh1 = (a, b) => { return a << b; }166warmup(funLsh1, [[5,1,10], [1,1,2], [63,31,-2147483648],167 [4294967295,2147483647,-2147483648], [-2,10,-2048], [-15,-2,1073741824],168 [4,128,4], [1,10,1024], [1024,2,4096]]);169//Lsh Boolean w/ Int32170var funLsh2 = (a, b) => { return a << b; }171warmup(funLsh2, [[5,true,10], [true,1,2], [63,false,63], [false, 12, 0]]);172//Lsh Number Number173var funLsh3 = (a, b) => { return a << b; }174warmup(funLsh3, [[54772703898, 1, -2123741900],[2147483658, 0, -2147483638]]);175//Lsh Boolean w/ null176var funLsh4 = (a, b) => { return a << b; }177warmup(funLsh4, [[5, null, 5], [null, 1, 0], [63, null, 63], [null, 12, 0]]);178//Lsh Boolean w/ undefined179var funLsh5 = (a, b) => { return a << b; }180warmup(funLsh5, [[5, void 0, 5], [void 0, 1, 0], [63, void 0, 63], [void 0, 12, 0]]);181//Rsh Int32182var funRsh1 = (a, b) => { return a >> b; }183warmup(funRsh1, [[1,1,0], [5,1,2], [63,31,0], [4294967295,2147483647,-1], [-2,10,-1],184 [-15,-2,-1], [4,128,4], [1,10,0], [1024,2,256]]);185//Rsh Int32186var funRsh2 = (a, b) => { return a >> b; }187warmup(funRsh2, [[true,1,0], [1,true,0], [false, 3, 0], [3, false, 3]]);188//Rsh Number Number189var funRsh3 = (a, b) => { return a >> b; }190warmup(funRsh3, [[54772703898, 11, -518492 ], [2147483658, 0, -2147483638]]);191//Rsh Int32 null192var funRsh4 = (a, b) => { return a >> b; }193warmup(funRsh4, [[null, 1, 0], [1, null, 1], [null, 3, 0], [3, null, 3]]);194//Rsh Int32 undefined195var funRsh5 = (a, b) => { return a >> b; }196warmup(funRsh5, [[void 0, 1, 0], [1, void 0, 1], [void 0, 3, 0], [3, void 0, 3]]);197//URsh Int32198var funURsh1 = (a, b) => { return a >>> b; }199warmup(funURsh1, [[1,1,0], [5,1,2], [63,31,0], [4294967295,2147483647,1], [-2,10,4194303],200 [-15,-2,3], [4,128,4], [1,10,0], [1024,2,256], [0, -6, 0], [0, 6, 0],201 [0x55005500, 2, 0x15401540]]);202//URsh Boolean Int32203var funURsh2 = (a, b) => { return a >>> b; }204warmup(funURsh2, [[true,1,0], [5,true,2], [63,false,63], [false, 20, 0]]);205//URsh Int32206var funURsh3 = (a, b) => { return a >>> b; }207warmup(funURsh3, [[4294967295, 0, 4294967295]]);208//URsh Number Number209var funURsh4 = (a, b) => { return a >>> b; }210warmup(funURsh4, [[54772703898, 11, 1578660], [2147483658, 11, 1048576],211 [4294967295, 0, 4294967295]]);212//URsh null Int32213var funURsh5 = (a, b) => { return a >>> b; }214warmup(funURsh5, [[null, 1, 0], [5, null, 5], [63, null, 63], [null, 20, 0]]);215//URsh undefined Int32216var funURsh6 = (a, b) => { return a >>> b; }217warmup(funURsh6, [[void 0, 1, 0], [5, void 0, 5], [63, void 0, 63], [void 0, 20, 0]]);218// Other Test cases that Have been useful:219for (var k=0; k < 30; k++) {220 A="01234567";221 res =""222 for (var i = 0; i < 8; ++i) {223 var v = A[7 - i];224 res+=v;225 }226 assertEq(res, "76543210");227}228// Begin OOM testing:229if (!('oomTest' in this))230 quit();231// Add: String Number Concat OOM test232var addOom = (a, b) => { return a + b; }233function generate_digits(prefix, start) {234 digits = []235 number = ""+start+".25";236 for (var i = 1; i < 7; i++) {237 number = i + number;238 digits.push([prefix, Number(number), prefix + number]);239 }240 return digits;241}242// Trying to defeat dtoacache: Warm the IC with one set of digits, then actually oomTest243// using another set.244var warmup_digits = generate_digits("x", 1);245var test_digits = generate_digits("x", 2);246function ot(digits) {247 warmup(addOom, digits);248}249// Ensure ICs are warmed250ot(warmup_digits);...

Full Screen

Full Screen

test_lr_schedulers.py

Source:test_lr_schedulers.py Github

copy

Full Screen

1#!/usr/bin/env python32# Copyright (c) Facebook, Inc. and its affiliates.3# This source code is licensed under the MIT license found in the4# LICENSE file in the root directory of this source tree.5import os6import unittest7import torch8import parlai.nn.lr_scheduler as lr_scheduler9import parlai.utils.testing as testing_utils10class TestLRSchedulers(unittest.TestCase):11 def _run_pass(self, max_lr=1.0, total_steps=1000, end_zero=False, **args):12 if 'max_train_steps' not in args:13 args['max_train_steps'] = total_steps14 # for checks of correctness, hardcode warmup_rate to be 015 args['warmup_rate'] = 016 p = torch.nn.Parameter(torch.randn(4, 4))17 optimizer = torch.optim.SGD([p], lr=max_lr)18 scheduler = lr_scheduler.ParlAILRScheduler.lr_scheduler_factory(19 args, optimizer, {}, True20 )21 output = []22 for step in range(total_steps):23 scheduler.step(step)24 output.append(scheduler.get_last_lr())25 for value in output:26 assert value >= 027 for step, o in enumerate(output): # noqa: B00728 assert o <= max_lr29 assert o > 0 or step == total_steps - 130 warmup_updates = args.get('warmup_updates', 0)31 assert warmup_updates >= 032 if warmup_updates > 0:33 assert output[warmup_updates - 1] == max_lr34 # LR is always linear35 for step in range(warmup_updates - 2):36 self.assertAlmostEqual(37 output[step + 1] - output[step], 1 / warmup_updates38 )39 if end_zero:40 self.assertAlmostEquals(output[-1], 0)41 else:42 self.assertNotAlmostEqual(output[-1], 0)43 return output44 def _run_resume(self, max_lr=1.0, warmup_updates=0, total_steps=200, **args):45 args['warmup_updates'] = warmup_updates46 if 'max_train_steps' not in args:47 args['max_train_steps'] = total_steps48 p = torch.nn.Parameter(torch.randn(4, 4))49 optimizer = torch.optim.SGD([p], lr=max_lr)50 scheduler = lr_scheduler.ParlAILRScheduler.lr_scheduler_factory(51 args, optimizer, {}, True52 )53 for step in range(total_steps):54 p = torch.nn.Parameter(torch.randn(4, 4))55 optimizer2 = torch.optim.SGD([p], lr=max_lr)56 sd = {57 'number_training_updates': step,58 'lr_scheduler': scheduler.get_state_dict(),59 'lr_scheduler_type': args['lr_scheduler'],60 'warmup_scheduler': scheduler.get_warmup_state_dict(),61 }62 scheduler2 = lr_scheduler.ParlAILRScheduler.lr_scheduler_factory(63 args, optimizer2, sd, False64 )65 assert scheduler.get_last_lr() == scheduler2.get_last_lr(), step66 scheduler.step(step)67 sd = {68 'number_training_updates': step,69 'lr_scheduler': scheduler.get_state_dict(),70 'lr_scheduler_type': args['lr_scheduler'],71 'warmup_scheduler': scheduler.get_warmup_state_dict(),72 }73 optimizer2 = torch.optim.SGD([p], lr=max_lr)74 scheduler2 = lr_scheduler.ParlAILRScheduler.lr_scheduler_factory(75 args, optimizer2, sd, False76 )77 assert scheduler.get_last_lr() == scheduler2.get_last_lr()78 def test_cosine(self):79 self._run_pass(lr_scheduler='cosine', warmup_updates=0, end_zero=True)80 self._run_pass(lr_scheduler='cosine', warmup_updates=50, end_zero=True)81 with self.assertRaises(lr_scheduler.StopTrainException):82 self._run_pass(lr_scheduler='cosine', max_train_steps=100, total_steps=1000)83 def test_linear(self):84 self._run_pass(lr_scheduler='linear', warmup_updates=0, end_zero=True)85 self._run_pass(lr_scheduler='linear', warmup_updates=50, end_zero=True)86 with self.assertRaises(lr_scheduler.StopTrainException):87 self._run_pass(lr_scheduler='linear', max_train_steps=100, total_steps=1000)88 def test_invsqrt(self):89 self._run_pass(lr_scheduler='invsqrt', warmup_updates=0, end_zero=False)90 self._run_pass(lr_scheduler='invsqrt', warmup_updates=50, end_zero=False)91 # decay very fast92 steps = self._run_pass(93 lr_scheduler='invsqrt',94 warmup_updates=50,95 invsqrt_lr_decay_gamma=1,96 end_zero=False,97 )98 self.assertAlmostEquals(steps[-1], 0.03242722)99 # decay very slowly100 steps = self._run_pass(101 lr_scheduler='invsqrt',102 warmup_updates=50,103 invsqrt_lr_decay_gamma=5000,104 end_zero=False,105 )106 assert all(x > 0.9 for x in steps[50:])107 def test_cosine_resume(self):108 self._run_resume(lr_scheduler='cosine', warmup_updates=0, end_zero=True)109 self._run_resume(lr_scheduler='cosine', warmup_updates=50, end_zero=True)110 def test_linear_resume(self):111 self._run_resume(lr_scheduler='linear', warmup_updates=0, end_zero=True)112 self._run_resume(lr_scheduler='linear', warmup_updates=50, end_zero=True)113 def test_invsqrt_resume(self):114 self._run_resume(lr_scheduler='invsqrt', warmup_updates=0, end_zero=True)115 self._run_resume(lr_scheduler='invsqrt', warmup_updates=50, end_zero=True)116 def _run_end2end(117 self, lr_scheduler, max_lr=1.0, warmup_updates=0, total_steps=100, **args118 ):119 testing_utils.train_model(120 {121 'task': 'integration_tests:nocandidate',122 'model': 'test_agents/unigram',123 'skip_generation': True,124 'lr_scheduler': lr_scheduler,125 'max_train_steps': total_steps,126 'warmup_updates': warmup_updates,127 'learningrate': max_lr,128 }129 )130 def test_end2end_cosine(self):131 self._run_end2end(lr_scheduler='cosine', warmup_updates=0)132 self._run_end2end(lr_scheduler='cosine', warmup_updates=50)133 def test_end2end_linear(self):134 self._run_end2end(lr_scheduler='linear', warmup_updates=0)135 self._run_end2end(lr_scheduler='linear', warmup_updates=50)136 def test_end2end_invsqrt(self):137 self._run_end2end(lr_scheduler='invsqrt', warmup_updates=0)138 self._run_end2end(lr_scheduler='invsqrt', warmup_updates=50)139class TestLRIntegration(unittest.TestCase):140 """141 Deep LR scheduler tests to check how we handle preemption.142 """143 PREEMPT = 30144 def _test_scheduler(self, **kwargs):145 from parlai.scripts.train_model import TrainModel, TrainLoop146 # shallow copy to prevent overwrites147 kwargs = kwargs.copy()148 with testing_utils.tempdir() as tmpdir:149 kwargs['model'] = 'test_agents/unigram'150 kwargs['task'] = 'integration_tests'151 kwargs['skip_generation'] = True152 kwargs['validation_metric'] = 'loss'153 kwargs['model_file'] = os.path.join(tmpdir, 'model')154 kwargs['dict_file'] = 'zoo:unittest/transformer_generator2/model.dict'155 kwargs['log_every_n_steps'] = 1156 kwargs['validation_every_n_steps'] = 10157 kwargs['max_train_steps'] = 100158 kwargs['save_after_valid'] = True159 kwargs['learningrate'] = 1160 opt = TrainModel.setup_args().parse_kwargs(**kwargs)161 logs_first = []162 for i, train_step_log in enumerate(TrainLoop(opt).train_steps(), 1):163 logs_first.append(train_step_log)164 if i >= self.PREEMPT - 2:165 # simulate preemption166 break167 # resume training168 logs_second = []169 for train_step_log in TrainLoop(opt).train_steps():170 logs_second.append(train_step_log)171 # check correctness172 assert (173 logs_first[20]['total_train_updates']174 == logs_second[0]['total_train_updates']175 )176 assert logs_first[20]['lr'] == logs_second[0]['lr']177 if 'warump_updates' in kwargs:178 full_logs = logs_first[:20] + logs_second179 assert full_logs[kwargs['warmup_updates']]['lr'] == 1.0180 return logs_first, logs_second181 def test_invsqrt(self):182 self._test_scheduler(lr_scheduler='invsqrt')183 def test_invsqrt_warmup(self):184 self._test_scheduler(lr_scheduler='invsqrt', warmup_updates=25)185 def test_invsqrt_long_warmup(self):186 self._test_scheduler(lr_scheduler='invsqrt', warmup_updates=self.PREEMPT + 30)187 def test_reduceonplateau(self):188 self._test_scheduler(lr_scheduler='reduceonplateau')189 def test_reduceonplateau_warmup(self):190 self._test_scheduler(lr_scheduler='reduceonplateau', warmup_updates=25)191 def test_reduceonplateau_long_warmup(self):192 self._test_scheduler(193 lr_scheduler='reduceonplateau', warmup_updates=self.PREEMPT + 30194 )195 def test_linear(self):196 self._test_scheduler(lr_scheduler='linear')197 def test_linear_warmup(self):198 self._test_scheduler(lr_scheduler='linear', warmup_updates=25)199 def test_linear_long_warmup(self):200 self._test_scheduler(lr_scheduler='linear', warmup_updates=self.PREEMPT + 30)201 def test_cosine(self):202 self._test_scheduler(lr_scheduler='cosine')203 def test_cosine_warmup(self):204 self._test_scheduler(lr_scheduler='cosine', warmup_updates=25)205 def test_cosine_long_warmup(self):...

Full Screen

Full Screen

lr_scheduler.py

Source:lr_scheduler.py Github

copy

Full Screen

1"""Popular Learning Rate Schedulers"""2from __future__ import division3import math4import torch5from bisect import bisect_right6__all__ = ['LRScheduler', 'WarmupMultiStepLR', 'WarmupPolyLR']7class LRScheduler(object):8 r"""Learning Rate Scheduler9 Parameters10 ----------11 mode : str12 Modes for learning rate scheduler.13 Currently it supports 'constant', 'step', 'linear', 'poly' and 'cosine'.14 base_lr : float15 Base learning rate, i.e. the starting learning rate.16 target_lr : float17 Target learning rate, i.e. the ending learning rate.18 With constant mode target_lr is ignored.19 niters : int20 Number of iterations to be scheduled.21 nepochs : int22 Number of epochs to be scheduled.23 iters_per_epoch : int24 Number of iterations in each epoch.25 offset : int26 Number of iterations before this scheduler.27 power : float28 Power parameter of poly scheduler.29 step_iter : list30 A list of iterations to decay the learning rate.31 step_epoch : list32 A list of epochs to decay the learning rate.33 step_factor : float34 Learning rate decay factor.35 """36 def __init__(self, mode, base_lr=0.01, target_lr=0, niters=0, nepochs=0, iters_per_epoch=0,37 offset=0, power=0.9, step_iter=None, step_epoch=None, step_factor=0.1, warmup_epochs=0):38 super(LRScheduler, self).__init__()39 assert (mode in ['constant', 'step', 'linear', 'poly', 'cosine'])40 if mode == 'step':41 assert (step_iter is not None or step_epoch is not None)42 self.niters = niters43 self.step = step_iter44 epoch_iters = nepochs * iters_per_epoch45 if epoch_iters > 0:46 self.niters = epoch_iters47 if step_epoch is not None:48 self.step = [s * iters_per_epoch for s in step_epoch]49 self.step_factor = step_factor50 self.base_lr = base_lr51 self.target_lr = base_lr if mode == 'constant' else target_lr52 self.offset = offset53 self.power = power54 self.warmup_iters = warmup_epochs * iters_per_epoch55 self.mode = mode56 def __call__(self, optimizer, num_update):57 self.update(num_update)58 assert self.learning_rate >= 059 self._adjust_learning_rate(optimizer, self.learning_rate)60 def update(self, num_update):61 N = self.niters - 162 T = num_update - self.offset63 T = min(max(0, T), N)64 if self.mode == 'constant':65 factor = 066 elif self.mode == 'linear':67 factor = 1 - T / N68 elif self.mode == 'poly':69 factor = pow(1 - T / N, self.power)70 elif self.mode == 'cosine':71 factor = (1 + math.cos(math.pi * T / N)) / 272 elif self.mode == 'step':73 if self.step is not None:74 count = sum([1 for s in self.step if s <= T])75 factor = pow(self.step_factor, count)76 else:77 factor = 178 else:79 raise NotImplementedError80 # warm up lr schedule81 if self.warmup_iters > 0 and T < self.warmup_iters:82 factor = factor * 1.0 * T / self.warmup_iters83 if self.mode == 'step':84 self.learning_rate = self.base_lr * factor85 else:86 self.learning_rate = self.target_lr + (self.base_lr - self.target_lr) * factor87 def _adjust_learning_rate(self, optimizer, lr):88 optimizer.param_groups[0]['lr'] = lr89 # enlarge the lr at the head90 for i in range(1, len(optimizer.param_groups)):91 optimizer.param_groups[i]['lr'] = lr * 1092# separating MultiStepLR with WarmupLR93# but the current LRScheduler design doesn't allow it94# reference: https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/solver/lr_scheduler.py95class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):96 def __init__(self, optimizer, milestones, gamma=0.1, warmup_factor=1.0 / 3,97 warmup_iters=500, warmup_method="linear", last_epoch=-1):98 super(WarmupMultiStepLR, self).__init__(optimizer, last_epoch)99 if not list(milestones) == sorted(milestones):100 raise ValueError(101 "Milestones should be a list of" " increasing integers. Got {}", milestones)102 if warmup_method not in ("constant", "linear"):103 raise ValueError(104 "Only 'constant' or 'linear' warmup_method accepted got {}".format(warmup_method))105 self.milestones = milestones106 self.gamma = gamma107 self.warmup_factor = warmup_factor108 self.warmup_iters = warmup_iters109 self.warmup_method = warmup_method110 def get_lr(self):111 warmup_factor = 1112 if self.last_epoch < self.warmup_iters:113 if self.warmup_method == 'constant':114 warmup_factor = self.warmup_factor115 elif self.warmup_factor == 'linear':116 alpha = float(self.last_epoch) / self.warmup_iters117 warmup_factor = self.warmup_factor * (1 - alpha) + alpha118 return [base_lr * warmup_factor * self.gamma ** bisect_right(self.milestones, self.last_epoch)119 for base_lr in self.base_lrs]120class WarmupPolyLR(torch.optim.lr_scheduler._LRScheduler):121 def __init__(self, optimizer, target_lr=0, max_iters=0, power=0.9, warmup_factor=1.0 / 3,122 warmup_iters=500, warmup_method='linear', last_epoch=-1):123 if warmup_method not in ("constant", "linear"):124 raise ValueError(125 "Only 'constant' or 'linear' warmup_method accepted "126 "got {}".format(warmup_method))127 self.target_lr = target_lr128 self.max_iters = max_iters129 self.power = power130 self.warmup_factor = warmup_factor131 self.warmup_iters = warmup_iters132 self.warmup_method = warmup_method133 super(WarmupPolyLR, self).__init__(optimizer, last_epoch)134 def get_lr(self):135 N = self.max_iters - self.warmup_iters136 T = self.last_epoch - self.warmup_iters137 if self.last_epoch < self.warmup_iters:138 if self.warmup_method == 'constant':139 warmup_factor = self.warmup_factor140 elif self.warmup_method == 'linear':141 alpha = float(self.last_epoch) / self.warmup_iters142 warmup_factor = self.warmup_factor * (1 - alpha) + alpha143 else:144 raise ValueError("Unknown warmup type.")145 return [self.target_lr + (base_lr - self.target_lr) * warmup_factor for base_lr in self.base_lrs]146 factor = pow(1 - T / N, self.power)147 return [self.target_lr + (base_lr - self.target_lr) * factor for base_lr in self.base_lrs]148if __name__ == '__main__':149 import torch150 import torch.nn as nn151 model = nn.Conv2d(16, 16, 3, 1, 1)152 optimizer = torch.optim.Adam(model.parameters(), lr=0.01)...

Full Screen

Full Screen

warmup-handler.test.js

Source:warmup-handler.test.js Github

copy

Full Screen

1/* eslint-disable no-console */2import WarmupHandler from "../src/warmup-handler";3let consoleOutput;4console["log"] = jest.fn(input => (consoleOutput = input));5jest.useFakeTimers();6describe("WarmupHandler", () => {7 describe("constructor", () => {8 const warmupHandler = new WarmupHandler();9 const extraCallback = jest.fn();10 const warmupHandlerWithExtraCallback = new WarmupHandler(extraCallback);11 it("should initialize variables correctly", () => {12 expect(warmupHandler.defaultDelayInMs).toEqual(100);13 expect(warmupHandler.extraCallback).not.toBeDefined();14 expect(warmupHandlerWithExtraCallback.defaultDelayInMs).toEqual(100);15 expect(warmupHandlerWithExtraCallback.extraCallback).toBe(extraCallback);16 });17 });18 describe("setTimeoutEvent", () => {19 describe("without extra callback", () => {20 const warmupHandler = new WarmupHandler();21 const callback = jest.fn();22 const delayInMs = 150;23 warmupHandler.setTimeoutEvent(callback, delayInMs);24 jest.runAllTimers();25 it("should call callback after delayInMs", () => {26 expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), delayInMs);27 expect(callback).toHaveBeenCalledTimes(1);28 });29 });30 describe("with extra callback", () => {31 const extraCallback = jest.fn();32 const warmupHandler = new WarmupHandler(extraCallback);33 const callback = jest.fn();34 const delayInMs = 150;35 warmupHandler.setTimeoutEvent(callback, delayInMs);36 jest.runAllTimers();37 it("should call callback and extraCallback after delayInMs", () => {38 expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), delayInMs);39 expect(callback).toHaveBeenCalledTimes(1);40 expect(extraCallback).toHaveBeenCalledTimes(1);41 });42 });43 });44 describe("handleEmptyWarmupRequest", () => {45 const warmupHandler = new WarmupHandler();46 const callback = jest.fn();47 warmupHandler.setTimeoutEvent = jest.fn();48 warmupHandler.handleEmptyWarmupRequest(callback);49 it("should call setTimeoutEvent with callback and defaultDelayInMs", () => {50 expect(warmupHandler.setTimeoutEvent).toHaveBeenCalledTimes(1);51 expect(warmupHandler.setTimeoutEvent).toHaveBeenLastCalledWith(callback, warmupHandler.defaultDelayInMs);52 });53 });54 describe("handleNonemptyWarmupRequest", () => {55 describe("without extra delay", () => {56 const warmupHandler = new WarmupHandler();57 const callback = jest.fn();58 warmupHandler.setTimeoutEvent = jest.fn();59 const event = "#warmup";60 warmupHandler.handleNonemptyWarmupRequest(event, callback);61 it("should call setTimeoutEvent with callback and defaultDelayInMs", () => {62 expect(warmupHandler.setTimeoutEvent).toHaveBeenCalledTimes(1);63 expect(warmupHandler.setTimeoutEvent).toHaveBeenLastCalledWith(callback, warmupHandler.defaultDelayInMs);64 });65 });66 describe("with extra delay", () => {67 const warmupHandler = new WarmupHandler();68 const callback = jest.fn();69 warmupHandler.setTimeoutEvent = jest.fn();70 const extraDelay = 50;71 const event = "#warmup wait=" + extraDelay;72 warmupHandler.handleNonemptyWarmupRequest(event, callback);73 it("should call setTimeoutEvent with callback and defaultDelayInMs + extraDelay", () => {74 expect(warmupHandler.setTimeoutEvent).toHaveBeenCalledTimes(1);75 expect(warmupHandler.setTimeoutEvent).toHaveBeenLastCalledWith(callback, warmupHandler.defaultDelayInMs + extraDelay);76 });77 });78 });79 describe("checkAndHandleWarmupRequest", () => {80 describe("when it is warmup", () => {81 describe("with empty request message", () => {82 const warmupHandler = new WarmupHandler();83 const callback = jest.fn();84 const event = {};85 warmupHandler.handleEmptyWarmupRequest = jest.fn();86 warmupHandler.handleNonemptyWarmupRequest = jest.fn();87 const isWarmup = warmupHandler.checkAndHandleWarmupRequest(event,callback);88 it("should call handleEmptyWarmupRequest", () => {89 expect(isWarmup).toBe(true);90 expect(warmupHandler.handleEmptyWarmupRequest).toHaveBeenCalledWith(callback);91 expect(warmupHandler.handleNonemptyWarmupRequest).not.toBeCalled();92 });93 });94 describe("with nonempty request message", () => {95 const warmupHandler = new WarmupHandler();96 const callback = jest.fn();97 const event = "#warmup";98 warmupHandler.handleEmptyWarmupRequest = jest.fn();99 warmupHandler.handleNonemptyWarmupRequest = jest.fn();100 const isWarmup = warmupHandler.checkAndHandleWarmupRequest(event,callback);101 it("should call handleNonemptyWarmupRequest", () => {102 expect(isWarmup).toBe(true);103 expect(warmupHandler.handleNonemptyWarmupRequest).toHaveBeenCalledWith(event,callback);104 expect(warmupHandler.handleEmptyWarmupRequest).not.toBeCalled();105 });106 });107 });108 describe("when it is not a warmup", () => {109 const warmupHandler = new WarmupHandler();110 const callback = jest.fn();111 const event = {key: "value"};112 warmupHandler.handleEmptyWarmupRequest = jest.fn();113 warmupHandler.handleNonemptyWarmupRequest = jest.fn();114 const isWarmup = warmupHandler.checkAndHandleWarmupRequest(event,callback);115 it("should not call handleEmptyWarmupRequest or handleNonemptyWarmupRequest", () => {116 expect(isWarmup).toBe(false);117 expect(warmupHandler.handleEmptyWarmupRequest).not.toBeCalled();118 expect(warmupHandler.handleNonemptyWarmupRequest).not.toBeCalled();119 });120 });121 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { warmUp } = require("qawolf");2const { create } = require("qawolf");3const { launch } = require("qawolf");4const { create } = require("qawolf");5const { launch } = require("qawolf");6const { create } = require("qawolf");7const { launch } = require("qawolf");8const { create } = require("qawolf");9const { launch } = require("qawolf");10const { create } = require("qawolf");11const { launch } = require("qawolf");12const { create } = require("qawolf");13const { launch } = require("qawolf");14const { create } = require("qawolf");15const { launch } = require("qawolf");16const { create } = require("qawolf");17const { launch } = require("qawolf");18const { create } = require("qawolf");19const { launch } = require("qawolf");20const { create } = require("qawolf");21const { launch } = require("qawolf");22const { create } = require("qawolf");23const { launch } = require("qawolf");

Full Screen

Using AI Code Generation

copy

Full Screen

1const { warmUp } = require("qawolf");2const browser = await warmUp("chrome");3const { create } = require("qawolf");4const browser = await create("chrome");5const context = await browser.newContext();6const page = await context.newPage();7const { launch } = require("qawolf");8const browser = await launch("chrome");9const context = await browser.newContext();10const page = await context.newPage();11const { register } = require("qawolf");12await register();13const { run } = require("qawolf");14const { saveArtifacts } = require("qawolf");15await saveArtifacts();16const { saveCode } = require("qawolf");17await saveCode();18const { saveTest } = require("qawolf");19await saveTest();20const { start } = require("qawolf");21await start();22const { stop } = require("qawolf");23await stop();24const { teardown } = require("qawolf");25await teardown();26const { test } = require("qawolf");27const { track } = require("qawolf");28await track();29const { waitFor } = require("qawolf");30await waitFor();31const { waitForEvent } = require("qawolf");32await waitForEvent();33const { waitForEvent } = require("qawolf");34await waitForEvent();35const { waitForPage } = require("qawolf

Full Screen

Using AI Code Generation

copy

Full Screen

1import { launch } from 'qawolf';2import { test } from './test';3describe('test', () => {4 let browser;5 beforeAll(async () => {6 browser = await launch();7 });8 afterAll(async () => {9 await browser.close();10 });11 it('test', async () => {12 const page = await browser.newPage();13 await test(page);14 });15});16export async function test(page) {17 await page.click('input[type="text"]');18 await page.type('input[type="text"]', 'Hello World');19 await page.click('input[type="submit"]');20}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { warmUp } = require('qawolf');2const { launch } = require('qawolf');3const { closeBrowser } = require('qawolf');4const { toMatchImageSnapshot } = require('jest-image-snapshot');5expect.extend({ toMatchImageSnapshot });6test('test', async () => {7 const browser = await launch();8 const page = await browser.newPage();9 await warmUp(page);10 await page.click('text="Sign Up"');11 await page.fill('input[name="email"]', '

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require("qawolf")2const browser = await qawolf.launch()3await qawolf.warmUp(browser)4await browser.close()5const qawolf = require("qawolf")6const browser = await qawolf.launch()7await qawolf.warmUp(browser)8await browser.close()9const qawolf = require("qawolf")10const browser = await qawolf.launch()11await qawolf.warmUp(browser)12await browser.close()13const qawolf = require("qawolf")14const browser = await qawolf.launch()15await qawolf.warmUp(browser)16await browser.close()17const qawolf = require("qawolf")18const browser = await qawolf.launch()19await qawolf.warmUp(browser)20await browser.close()21const qawolf = require("qawolf")22const browser = await qawolf.launch()23await qawolf.warmUp(browser)24await browser.close()25import qawolf from "qawolf"26const browser = await qawolf.launch()27await qawolf.warmUp(browser)28await browser.close()29import qawolf from "qawolf"30const browser = await qawolf.launch()31await qawolf.warmUp(browser)32await browser.close()33import qawolf from "qawolf"34const browser = await qawolf.launch()35await qawolf.warmUp(browser)36await browser.close()37const qawolf = require("qawolf")38const browser = await qawolf.launch()39await qawolf.warmUp(browser)40await browser.close()41const qawolf = require("qawolf")42const browser = await qawolf.launch()43await qawolf.warmUp(browser)44await browser.close()45const qawolf = require("qawolf")46const browser = await qawolf.launch()47await qawolf.warmUp(browser)48await browser.close()

Full Screen

Using AI Code Generation

copy

Full Screen

1const { warmUp } = require("qawolf");2const { launch } = require("qawolf");3const browser = await launch();4await warmUp(browser);5const context = await browser.createIncognitoBrowserContext();6const page = await context.newPage();7await page.type("input[name=q]", "qawolf");8await page.click("input[value=Google Search]");9await page.close();10await context.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require('qawolf');2const { chromium } = require('playwright');3const { launch } = require('qawolf');4const browser = await chromium.launch({ headless: false });5const context = await browser.newContext();6const browserContext = await launch({ launchOptions: { headless: false } });7await qawolf.warmUp({ context: browserContext });8const browserContext = await launch({ launchOptions: { headless: false } });9await qawolf.warmUp({ context: browserContext });10const browserContext = await launch({ launchOptions: { headless: false } });11await qawolf.warmUp({ context: browserContext });12const browserContext = await launch({ launchOptions: { headless: false } });13await qawolf.warmUp({ context: browserContext });14const browserContext = await launch({ launchOptions: { headless: false } });15await qawolf.warmUp({ context: browserContext });16const browserContext = await launch({ launchOptions: { headless: false } });17await qawolf.warmUp({ context: browserContext });18const browserContext = await launch({ launchOptions: { headless: false } });19await qawolf.warmUp({ context: browserContext });20const browserContext = await launch({ launchOptions: { headless: false } });21await qawolf.warmUp({ context: browserContext });22const browserContext = await launch({ launchOptions: { headless: false } });

Full Screen

Using AI Code Generation

copy

Full Screen

1const { launch } = require('qawolf');2const selectors = require('../selectors/test');3const config = require('../qawolf.config');4await browser.warmUp(selectors);5await browser.type(selectors[0], 'hello world');6await browser.click(selectors[1]);7await browser.close();8];9module.exports = {10 launchOptions: {11 }12}13Error: Protocol error (Runtime.callFunctionOn): Cannot find context with specified id undefined

Full Screen

Using AI Code Generation

copy

Full Screen

1const { warmUp } = require('qawolf');2const { launch } = require('qawolf');3beforeAll(async () => {4 await warmUp();5});6test('test', async () => {7 const browser = await launch();8 const context = await browser.newContext();9 const page = await context.newPage();10 await page.close();11 await context.close();12 await browser.close();13});14{15 "scripts": {16 },17 "devDependencies": {18 }19}20module.exports = {21};22{23 {24 }25}26module.exports = {27};28{29 "scripts": {30 },31 "devDependencies": {32 }33}34const { warmUp } = require('qawolf');35const { launch } = require('qawolf');36beforeAll(async () => {37 await warmUp();38});

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 qawolf 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