code
stringlengths
2
1.05M
/** * Created by guangqiang on 2017/10/16. */ import React, { StyleSheet, Platform } from 'react-native' class _EnhancedStyleSheet { static create(styleSheets) { let keys = Object.keys(styleSheets) keys.map((key) => { Object.keys(styleSheets[key]).map((property) => { if (Platform.OS === 'ios') { if (property.indexOf('_') === 0) { delete styleSheets[key][property] } } else if (Platform.OS === 'android') { if (property.indexOf('_') === 0) { let _newProp = property.substr(1) styleSheets[key][_newProp] = styleSheets[key][property] delete styleSheets[key][property] } } }) }) return StyleSheet.create(styleSheets) } static flatten(styleSheets) { return StyleSheet.flatten(styleSheets) } } export {_EnhancedStyleSheet as StyleSheet}
version https://git-lfs.github.com/spec/v1 oid sha256:310dd07a39933a80dd38e086a5915027c2e72fe082586428b54a6bbcc1a25800 size 846
version https://git-lfs.github.com/spec/v1 oid sha256:f357010c6d6198a65e01c586726e59f06825e8e9d2deb32a092d85c225dc9330 size 21065
"use strict"; var _getSert = require("./../getsert"); var generateCode = require("../../../src/utils/code-generator"); class RangeDiscProductDataUtil { getSert(input) { var ManagerType = require("../../../src/managers/master/range-disc-product-manager"); return _getSert(input, ManagerType, (data) => { return { code: data.code }; }); } getNewData() { var Model = require("bateeq-models").master.RangeDiscProduct; var data = new Model(); // var now = new Date(); // var stamp = now / 1000 | 0; var code = generateCode(); data.code = code; data.name = `name[${code}]`; data.description = `description for ${code}`; return Promise.resolve(data); } } module.exports = new RangeDiscProductDataUtil();
/* ----------------------------------------------------------------------------- This source file is part of Cell Cloud. Copyright (c) 2009-2014 Cell Cloud Team (www.cellcloud.net) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ /** * HashMap 封装。 */ function HashMap() { // 定义长度 var length = 0; // 创建一个对象 var obj = new Object(); /** * 判断 Map 是否为空 */ this.isEmpty = function() { return length == 0; }; /** * 判断对象中是否包含给定 Key */ this.containsKey = function(key) { return (key in obj); }; /** * 判断对象中是否包含给定的 Value */ this.containsValue = function(value) { for (var key in obj) { if (obj[key] == value) { return true; } } return false; }; /** * 向 Map 中添加数据 */ this.put = function(key, value) { if (!this.containsKey(key)) { length++; } obj[key] = value; }; /** * 根据给定的 Key 获得 Value */ this.get = function(key) { return this.containsKey(key) ? obj[key] : null; }; /** * 根据给定的 Key 删除一个值 */ this.remove = function(key) { if (this.containsKey(key) && (delete obj[key])) { length--; } }; /** * 获得 Map 中的所有 Value */ this.values = function() { var _values = new Array(); for (var key in obj) { _values.push(obj[key]); } return _values; }; /** * 获得 Map 中的所有 Key */ this.keySet = function() { var _keys = new Array(); for (var key in obj) { _keys.push(key); } return _keys; }; /** * 获得 Map 的长度 */ this.size = function() { return length; }; /** * 清空 Map */ this.clear = function() { length = 0; obj = new Object(); }; }
import Ember from 'ember'; import Validator from 'ember-cli-data-validation/validator'; import { hasValue } from 'ember-cli-data-validation/utils'; /** * Validator that uses a RegExp pattern to test * the attribute value. * * You should be able to create a PatternValidator by * just assigning a `pattern` value. * * @class PatternValidator * @extends {Validator} */ export default Validator.extend({ /** * RegExp like pattern that would be used to test * the Attribute value. * * @property pattern * @type {RegExp} * @default null */ pattern: null, validate: function(name, value /*, attribute, model*/) { var pattern = this.get('pattern'); Ember.assert('You must define a RegExp pattern in order to validate.', pattern instanceof RegExp); if (hasValue(value) && !value.toString().match(pattern)) { return this.format(); } }, });
import React from 'react'; import Example from '../Example'; import Checkbox from '../../../lib/Checkbox'; import Radio from '../../../lib/Radio'; import Switch from '../../../lib/Switch'; import IconToggle from '../../../lib/IconToggle'; import RadioGroupExample from './RadioGroupExample'; export default( props ) => ( <section { ...props }> <h3>Toggles</h3> <Example> <Checkbox label="Checkbox" /> <Checkbox label="Checkbox with ripple" ripple /> </Example> <p>Radio Button</p> <RadioGroupExample name="radio-group-demo" defaultValue="opt1" > <Radio value="opt1">Option</Radio> <br /> <Radio value="opt2" ripple>Option with ripple</Radio> </RadioGroupExample> <p>Radio Button with custom containers</p> <RadioGroupExample container="ul" childContainer="li" name="radio-group-demo2" defaultValue="opt1" > <Radio value="opt1">Option</Radio> <Radio value="opt2" ripple>Option with ripple</Radio> </RadioGroupExample> <p>Icon toggle</p> <Example> <IconToggle id="bold" name="format_bold" /> <IconToggle id="italic" name="format_italic" ripple /> </Example> <p>Switch</p> <Example> <Switch id="switch1">Switch</Switch> <Switch id="switch2" ripple>Ripple switch</Switch> </Example> </section> );
var MAX_PERFORMATIVE_MEMORY = 10; var MAXIMUM_DISTANCE_TO_BE_CONSIDERED_THIS = 128; var NLDereferenceHint = /** @class */ (function () { function NLDereferenceHint(c, r) { this.clause = c; this.result = r; } return NLDereferenceHint; }()); var NLContextEntity = /** @class */ (function () { function NLContextEntity(id, time, distance, tl) { this.objectID = null; this.mentionTime = null; this.distanceFromSpeaker = null; this.terms = []; this.lastUpdateTime = -1; this.objectID = id; this.mentionTime = time; this.distanceFromSpeaker = distance; this.terms = tl; } NLContextEntity.prototype.properNounMatch = function (name) { for (var _i = 0, _a = this.terms; _i < _a.length; _i++) { var term = _a[_i]; if (term.functor.name == "name") { if (term.attributes[1] instanceof ConstantTermAttribute && (term.attributes[1]).value == name) { return true; } } } return false; }; NLContextEntity.prototype.sortMatch = function (sort) { for (var _i = 0, _a = this.terms; _i < _a.length; _i++) { var term = _a[_i]; if (term.attributes.length == 1 && term.functor.is_a(sort)) { return true; } } return false; }; NLContextEntity.prototype.adjectiveMatch = function (sort, o) { for (var _i = 0, _a = this.terms; _i < _a.length; _i++) { var term = _a[_i]; if (term.attributes.length == 1 && term.functor.is_a(sort)) { return true; } else if (term.attributes.length == 2 && term.functor.is_a(o.getSort("property-with-value")) && (term.attributes[1] instanceof ConstantTermAttribute) && term.attributes[1].sort.is_a(sort)) { return true; } } return false; }; NLContextEntity.prototype.relationMatch = function (relation, o, pos) { for (var _i = 0, _a = this.terms; _i < _a.length; _i++) { var term = _a[_i]; if (relation.subsumesNoBindings(term) == 1) { return true; } } if (pos != null && pos.reverseRelations[relation.functor.name] != null) { var inverseRelation = o.getSort(pos.reverseRelations[relation.functor.name]); var relation_reverse = new Term(inverseRelation, [relation.attributes[1], relation.attributes[0]]); for (var _b = 0, _c = this.terms; _b < _c.length; _b++) { var term = _c[_b]; if (relation_reverse.subsumesNoBindings(term) == 1) { return true; } } } return false; }; NLContextEntity.prototype.addTerm = function (t) { for (var _i = 0, _a = this.terms; _i < _a.length; _i++) { var t2 = _a[_i]; if (t.equalsNoBindings(t2) == 1) return; } this.terms.push(t); }; NLContextEntity.prototype.addStateTerm = function (t) { for (var _i = 0, _a = this.terms; _i < _a.length; _i++) { var t2 = _a[_i]; if (TermContainer.termReplacesPreviousStateTerm(t, t2)) { if (t.equalsNoBindings(t2) == 1) return; // replace! this.terms.splice(this.terms.indexOf(t2), 1); this.terms.push(t); return; } } this.terms.push(t); }; NLContextEntity.fromXML = function (xml, o) { var id = new ConstantTermAttribute(xml.getAttribute("id"), o.getSort(xml.getAttribute("sort"))); var time = 0; var distance = null; var tl = []; if (xml.getAttribute("mentionTime") != null) time = Number(xml.getAttribute("mentionTime")); if (xml.getAttribute("distanceFromSpeaker") != null) distance = Number(xml.getAttribute("distanceFromSpeaker")); for (var _i = 0, _a = getElementChildrenByTag(xml, "term"); _i < _a.length; _i++) { var t_xml = _a[_i]; var t = Term.fromString(t_xml.getAttribute("term"), o); if (t != null) tl.push(t); } return new NLContextEntity(id, time, distance, tl); }; NLContextEntity.prototype.outerHTML = function () { return this.saveToXML(); }; NLContextEntity.prototype.saveToXML = function () { var str = "<NLContextEntity id=\"" + this.objectID.value + "\" sort=\"" + this.objectID.sort.name + "\""; if (this.mentionTime != null) str += " mentionTime=\"" + this.mentionTime + "\""; if (this.distanceFromSpeaker != null) str += " distanceFromSpeaker=\"" + this.distanceFromSpeaker + "\""; str += ">\n"; for (var _i = 0, _a = this.terms; _i < _a.length; _i++) { var t = _a[_i]; str += "<term term=\"" + t.toStringXML() + "\"/>\n"; } str += "</NLContextEntity>"; return str; }; NLContextEntity.prototype.toString = function () { return "[NLCE: " + this.objectID + "," + this.mentionTime + "," + this.distanceFromSpeaker + "]"; }; return NLContextEntity; }()); var NLContextPerformative = /** @class */ (function () { function NLContextPerformative(t, speaker, p, parse, derefErrors, c, context, timeStamp) { this.text = null; this.speaker = null; this.performative = null; this.parse = null; this.derefErrors = null; // for those performatives that cannot be parsed properly this.cause = null; // the cause of having said this performative this.context = null; this.timeStamp = 0; // cycle when it was recorded this.IDs = null; // the IDs of the objects mentioned in this performative this.text = t; this.speaker = speaker; this.performative = p; this.parse = parse; this.derefErrors = derefErrors; this.cause = c; this.context = context; this.timeStamp = timeStamp; this.IDs = null; } // find all the entities mentioned in the clause: NLContextPerformative.prototype.IDsInPerformative = function (o) { if (this.IDs != null) return this.IDs; this.IDs = []; var perf = this.performative; if (perf == null) return this.IDs; for (var i = 0; i < perf.attributes.length; i++) { if (perf.attributes[i] instanceof ConstantTermAttribute) { this.IDs.push((perf.attributes[i])); } else if (perf.attributes[i] instanceof TermTermAttribute) { NLContext.searchForIDsInClause(perf.attributes[i].term, this.IDs, o); } } return this.IDs; }; NLContextPerformative.prototype.addMentionToPerformative = function (id, o) { if (id == null) return; this.IDsInPerformative(o); // make sure we have calculated the IDs in the performative for (var _i = 0, _a = this.IDs; _i < _a.length; _i++) { var id2 = _a[_i]; if ((id2 instanceof ConstantTermAttribute) && id2.value == id) { // already mentioned: return; } } var newID = new ConstantTermAttribute(id, o.getSort("#id")); this.IDs.push(newID); var ce = this.context.newContextEntity(newID, this.timeStamp, null, o, false); if (ce != null) { var idx = this.context.mentions.indexOf(ce); if (idx != -1) this.context.mentions.splice(idx, 1); this.context.mentions.unshift(ce); } else { console.error("addMentionToPerformative: could not create NLContextEntity!"); } }; NLContextPerformative.fromXML = function (xml, context, o) { var cause = null; var p_xml = getFirstElementChildByTag(xml, "cause"); if (p_xml != null) { cause = CauseRecord.fromXML(p_xml, o); } var performative = null; if (xml.getAttribute("performative") != null) performative = Term.fromString(xml.getAttribute("performative"), o); return new NLContextPerformative(xml.getAttribute("text"), xml.getAttribute("speaker"), performative, null, // TODO: save/load NLParseRecord null, // TODO: save/load NLDerefErrorRecord[] cause, context, Number(xml.getAttribute("timeStamp"))); }; NLContextPerformative.prototype.outerHTML = function () { return this.saveToXML(); }; NLContextPerformative.prototype.saveToXML = function () { if (this.cause == null) { var tmp = "<NLContextPerformative text=\"" + this.text + "\" " + "speaker=\"" + this.speaker + "\" " + (this.performative != null ? "performative=\"" + this.performative + "\" " : "") + "timeStamp=\"" + this.timeStamp + "\"/>"; return tmp; } else { var tmp = "<NLContextPerformative text=\"" + this.text + "\" " + "speaker=\"" + this.speaker + "\" " + (this.performative != null ? "performative=\"" + this.performative + "\" " : "") + "timeStamp=\"" + this.timeStamp + "\">"; tmp += this.cause.saveToXML(); tmp += "</NLContextPerformative>"; return tmp; } }; return NLContextPerformative; }()); var NLContext = /** @class */ (function () { function NLContext(speaker, ai, mentionMemorySize) { this.speaker = null; this.ai = null; this.shortTermMemory = []; this.longTermMemory = {}; // a cache for not having to create entities constantly during parsing... this.mentions = []; this.performatives = []; this.cache_sort_space_at = null; this.cache_sort_contains = null; // conversation state: this.inConversation = false; this.lastPerformativeInvolvingThisCharacterWasToUs = false; this.expectingYes = false; this.expectingThankYou = false; this.expectingYouAreWelcome = false; this.expectingGreet = false; this.expectingFarewell = false; this.expectingNicetomeetyoutoo = false; this.expectingAnswerToQuestion_stack = []; this.expectingAnswerToQuestionTimeStamp_stack = []; this.expectingConfirmationToRequest_stack = []; this.expectingConfirmationToRequestTimeStamp_stack = []; this.lastEnumeratedQuestion_answered = null; this.lastEnumeratedQuestion_answers = null; this.lastEnumeratedQuestion_next_answer_index = 0; // the "mentions" list can be at most this size: this.mentionMemorySize = 10; // when hypothetical entities are mentioned in conversation, new IDs are given to them, this variable // determines which is the next ID to give them: this.nextHypotheticalID = 0; this.lastDerefErrorType = 0; this.lastTimeUpdated = -1; // Entity rephrasing: If the user's sentence could not be parsed due to a dereference error, and the user issued a clarification // such as "I meant the one to your right", this list will contain the clarification, so that when it comes time to parse the // previous sentence again, this can be used: this.dereference_hints = []; this.speaker = speaker; this.ai = ai; this.mentionMemorySize = mentionMemorySize; this.cache_sort_space_at = this.ai.o.getSort("space.at"); this.cache_sort_contains = this.ai.o.getSort("verb.contains"); } NLContext.prototype.reset = function () { this.endConversation(); this.shortTermMemory = []; this.longTermMemory = {}; this.mentions = []; this.performatives = []; this.lastDerefErrorType = 0; this.lastTimeUpdated = -1; }; NLContext.prototype.endConversation = function () { this.inConversation = false; this.lastPerformativeInvolvingThisCharacterWasToUs = false; this.expectingYes = false; this.expectingThankYou = false; this.expectingYouAreWelcome = false; this.expectingGreet = false; this.expectingFarewell = false; this.expectingNicetomeetyoutoo = false; this.expectingAnswerToQuestion_stack = []; this.expectingAnswerToQuestionTimeStamp_stack = []; this.expectingConfirmationToRequest_stack = []; this.expectingConfirmationToRequestTimeStamp_stack = []; this.lastEnumeratedQuestion_answered = null; this.lastEnumeratedQuestion_answers = null; this.lastEnumeratedQuestion_next_answer_index = 0; }; NLContext.prototype.newContextEntity = function (idAtt, time, distance, o, isFromLongTermMemory) { //console.log("newContextEntity: " + idAtt); var ID = idAtt.value; var e = this.findByID(ID); var itsAnExistingOne = false; if (e != null) { if (time != null) { if (e.mentionTime == null || e.mentionTime < time) e.mentionTime = time; } if (distance != null) { e.distanceFromSpeaker = distance; } // return e; itsAnExistingOne = true; } else { if (isFromLongTermMemory && ID in this.longTermMemory) { e = this.longTermMemory[ID]; } // console.log("newContextEntity: creating " + ID + " from scratch..."); if (e == null) { e = new NLContextEntity(idAtt, time, distance, []); if (isFromLongTermMemory) this.longTermMemory[ID] = e; } } if (this.ai.timeStamp <= e.lastUpdateTime) { // no need to reupdate it... return e; } // console.log("newContextEntity: "+this.ai.selfID+" updating " + ID + "(" + e.lastUpdateTime + " -> " + this.ai.timeStamp + ")"); e.terms = []; // entities need to be updated every time, otherwise, info is outdated! e.lastUpdateTime = this.ai.timeStamp; // find everything we can about it: var typeSorts = []; var typeSortsWithArity = []; var pSort = o.getSort("property"); var pwvSort = o.getSort("property-with-value"); var rSort = o.getSort("relation"); for (var _i = 0, _a = POSParser.sortsToConsiderForTypes; _i < _a.length; _i++) { var s = _a[_i]; typeSorts.push(o.getSort(s)); typeSortsWithArity.push([o.getSort(s), 1]); } typeSortsWithArity.push([pSort, 1]); typeSortsWithArity.push([pwvSort, 2]); typeSortsWithArity.push([rSort, 2]); /* for(let t of this.ai.perceptionBuffer) { if (t.functor.is_a(oSort) || t.functor.is_a(pSort)) { if (t.attributes[0] instanceof ConstantTermAttribute && (<ConstantTermAttribute>t.attributes[0]).value == ID) { e.terms.push(t); } } } */ for (var _b = 0, _c = this.ai.shortTermMemory.plainTermList; _b < _c.length; _b++) { var te = _c[_b]; if (POSParser.sortIsConsideredForTypes(te.term.functor, o) || te.term.functor.is_a(pSort) || te.term.functor.is_a(pwvSort) || te.term.functor.is_a(rSort)) { for (var _d = 0, _e = te.term.attributes; _d < _e.length; _d++) { var att = _e[_d]; if (att instanceof ConstantTermAttribute && att.value == ID) { e.addTerm(te.term); } } } } for (var _f = 0, typeSortsWithArity_1 = typeSortsWithArity; _f < typeSortsWithArity_1.length; _f++) { var tmp = typeSortsWithArity_1[_f]; var s_l = this.ai.longTermMemory.allSingleTermMatches((tmp[0]), (tmp[1]), o); for (var _g = 0, s_l_1 = s_l; _g < s_l_1.length; _g++) { var s = s_l_1[_g]; for (var _h = 0, _j = s.terms[0].attributes; _h < _j.length; _h++) { var att = _j[_h]; if (att instanceof ConstantTermAttribute && att.value == ID) { e.addTerm(s.terms[0]); } } } } if (e.terms.length == 0) { if (itsAnExistingOne) this.deleteContextEntity(e); return null; } return e; }; NLContext.prototype.deleteContextEntity = function (e) { var idx = this.shortTermMemory.indexOf(e); if (idx >= 0) this.shortTermMemory.splice(idx, 1); idx = this.mentions.indexOf(e); if (idx >= 0) this.mentions.splice(idx, 1); }; NLContext.prototype.newLongTermTerm = function (term) { for (var _i = 0, _a = this.shortTermMemory; _i < _a.length; _i++) { var ce = _a[_i]; for (var _b = 0, _c = term.attributes; _b < _c.length; _b++) { var att = _c[_b]; if (att instanceof ConstantTermAttribute && att.value == ce.objectID.value) { if (ce.terms.indexOf(term) == -1) ce.addTerm(term); } } } for (var _d = 0, _e = this.mentions; _d < _e.length; _d++) { var ce = _e[_d]; for (var _f = 0, _g = term.attributes; _f < _g.length; _f++) { var att = _g[_f]; if (att instanceof ConstantTermAttribute && att.value == ce.objectID.value) { if (ce.terms.indexOf(term) == -1) ce.addTerm(term); } } } }; NLContext.prototype.newLongTermStateTerm = function (term) { for (var _i = 0, _a = this.shortTermMemory; _i < _a.length; _i++) { var ce = _a[_i]; for (var _b = 0, _c = term.attributes; _b < _c.length; _b++) { var att = _c[_b]; if (att instanceof ConstantTermAttribute && att.value == ce.objectID.value) { if (ce.terms.indexOf(term) == -1) ce.addStateTerm(term); } } } for (var _d = 0, _e = this.mentions; _d < _e.length; _d++) { var ce = _e[_d]; for (var _f = 0, _g = term.attributes; _f < _g.length; _f++) { var att = _g[_f]; if (att instanceof ConstantTermAttribute && att.value == ce.objectID.value) { if (ce.terms.indexOf(term) == -1) ce.addStateTerm(term); } } } }; NLContext.prototype.addMention = function (id, timeStamp, o) { if (id == null) return; var newID = new ConstantTermAttribute(id, o.getSort("#id")); var ce = this.newContextEntity(newID, timeStamp, null, o, false); if (ce != null) { var idx = this.mentions.indexOf(ce); if (idx != -1) this.mentions.splice(idx, 1); this.mentions.unshift(ce); } else { console.error("addMention: could not create NLContextEntity!"); } }; NLContext.prototype.newPerformative = function (speakerID, perfText, perf, parse, derefErrors, cause, o, timeStamp) { var newPerformatives = []; if (perf != null && perf.functor.name == "#list") { var parsePerformatives = Term.elementsInList(perf, "#list"); for (var _i = 0, parsePerformatives_1 = parsePerformatives; _i < parsePerformatives_1.length; _i++) { var parsePerformative = parsePerformatives_1[_i]; if (parsePerformative instanceof TermTermAttribute) { newPerformatives = newPerformatives.concat(this.newPerformative(speakerID, perfText, parsePerformative.term, parse, derefErrors, cause, o, timeStamp)); } } return newPerformatives; } var cp = new NLContextPerformative(perfText, speakerID, perf, parse, derefErrors, cause, this, timeStamp); var IDs = cp.IDsInPerformative(o); for (var _a = 0, IDs_1 = IDs; _a < IDs_1.length; _a++) { var id = IDs_1[_a]; var ce = this.newContextEntity(id, timeStamp, null, o, false); if (ce != null) { var idx = this.mentions.indexOf(ce); if (idx != -1) this.mentions.splice(idx, 1); this.mentions.unshift(ce); } } // add the clause: this.performatives.unshift(cp); while (this.performatives.length > MAX_PERFORMATIVE_MEMORY) { this.performatives.pop(); } this.sortEntities(); if (this.mentions.length > this.mentionMemorySize) { this.mentions = this.mentions.slice(0, this.mentionMemorySize); } // update conversation context: this.inConversation = true; if (perf != null && speakerID == this.ai.selfID) { this.expectingThankYou = false; this.expectingYouAreWelcome = false; if (perf.functor.name == "perf.inform.answer") { this.expectingThankYou = true; } else if (perf.functor.name == "perf.thankyou") { this.expectingYouAreWelcome = true; } this.expectingGreet = false; this.expectingFarewell = false; this.expectingNicetomeetyoutoo = false; if (perf.functor.name == "perf.greet") { this.expectingGreet = true; } else if (perf.functor.name == "perf.farewell") { this.expectingFarewell = true; this.inConversation = false; } else if (perf.functor.name == "perf.nicetomeetyou") { this.expectingNicetomeetyoutoo = true; } if (perf.functor.is_a(this.ai.o.getSort("perf.question"))) { if (perf.functor.name == "perf.q.how" && perf.attributes.length >= 2 && (perf.attributes[1] instanceof TermTermAttribute) && perf.attributes[1].term.functor.name == "verb.help") { // no need to push anything to the stack here } else { this.expectingAnswerToQuestion_stack.push(cp); this.expectingAnswerToQuestionTimeStamp_stack.push(timeStamp); } } if (perf.functor.is_a(this.ai.o.getSort("perf.request.action"))) { this.expectingConfirmationToRequest_stack.push(cp); this.expectingConfirmationToRequestTimeStamp_stack.push(timeStamp); } else { // For now, just clear these stacks if we move on in the conversation, since requests do not necessarily need an answer this.expectingConfirmationToRequest_stack = []; this.expectingConfirmationToRequestTimeStamp_stack = []; } this.expectingYes = false; if (perf.functor.is_a(this.ai.o.getSort("perf.callattention"))) { this.expectingYes = true; } } return [cp]; }; NLContext.prototype.popLastQuestion = function () { if (this.expectingAnswerToQuestion_stack.length > 0) { this.expectingAnswerToQuestion_stack.splice(this.expectingAnswerToQuestion_stack.length - 1, 1); this.expectingAnswerToQuestionTimeStamp_stack.splice(this.expectingAnswerToQuestionTimeStamp_stack.length - 1, 1); } }; NLContext.prototype.lastPerformativeBy = function (speaker) { for (var i = 0; i < this.performatives.length; i++) { if (this.performatives[i].speaker == speaker) return this.performatives[i]; } return null; }; NLContext.prototype.lastPerformativeByExcept = function (speaker, perf) { for (var i = 0; i < this.performatives.length; i++) { if (this.performatives[i].speaker == speaker && this.performatives[i].performative != perf) return this.performatives[i]; } return null; }; NLContext.searchForIDsInClause = function (clause, IDs, o) { for (var i = 0; i < clause.attributes.length; i++) { if (clause.attributes[i] instanceof ConstantTermAttribute && clause.attributes[i].sort.name == "#id") { IDs.push((clause.attributes[i])); } else if (clause.attributes[i] instanceof TermTermAttribute) { NLContext.searchForIDsInClause(clause.attributes[i].term, IDs, o); } } }; NLContext.prototype.sortEntities = function () { this.shortTermMemory.sort(function (e1, e2) { if (e1.distanceFromSpeaker == null && e2.distanceFromSpeaker == null) { return 0; } else if (e1.distanceFromSpeaker == null) { return 1; } else if (e2.distanceFromSpeaker == null) { return -1; } else { return e1.distanceFromSpeaker - e2.distanceFromSpeaker; } }); this.mentions.sort(function (e1, e2) { if (e1.mentionTime == null && e2.mentionTime == null) { return 0; } else if (e1.mentionTime == null) { return 1; } else if (e2.mentionTime == null) { return -1; } else { return e2.mentionTime - e1.mentionTime; } }); }; NLContext.prototype.deref = function (clause, listenerVariable, nlpr, o, pos, AI) { // check if there are any deref hints: for (var _i = 0, _a = this.dereference_hints; _i < _a.length; _i++) { var hint = _a[_i]; if (hint.clause.term.equalsNoBindings(clause) == 1) { return [new ConstantTermAttribute(hint.result, o.getSort("#id"))]; } } return this.derefInternal(Term.elementsInList(clause, "#and"), listenerVariable, nlpr, o, pos, AI, false); ; }; NLContext.prototype.derefInternal = function (clauseElements, listenerVariable, nlpr, o, pos, AI, returnAllCandidatesBeforeDisambiguation) { this.lastDerefErrorType = 0; var properNounSort = o.getSort("proper-noun"); var nounSort = o.getSort("noun"); var pronounSort = o.getSort("pronoun"); var personalPronounSort = o.getSort("personal-pronoun"); var reflexivePronounSort = o.getSort("reflexive-pronoun"); var adjectiveSort = o.getSort("adjective"); var determinerSort = o.getSort("determiner"); var possessiveDeterminerSort = o.getSort("possessive-determiner"); var firstPerson = o.getSort("first-person"); var secondPerson = o.getSort("second-person"); var thirdPerson = o.getSort("third-person"); var relationSort = o.getSort("relation"); var spatialRelationSort = o.getSort("spatial-relation"); var properNounTerms = []; var nounTerms = []; var pronounTerms = []; var adjectiveTerms = []; var negatedAdjectiveTerms = []; var determinerTerms = []; var relationTerms = []; var otherTerms = []; var genitiveTerm = null; for (var _i = 0, clauseElements_1 = clauseElements; _i < clauseElements_1.length; _i++) { var tmp = clauseElements_1[_i]; if (tmp instanceof TermTermAttribute) { var tmp2 = tmp.term; NLParser.resolveCons(tmp2, o); if (tmp2.functor.is_a(properNounSort)) { properNounTerms.push(tmp2); } else if (tmp2.functor.name == "saxon-genitive") { if (genitiveTerm != null) { console.warn("two saxon genitives in a noun phrase, not supported!"); return null; } genitiveTerm = tmp2; } else if (tmp2.functor.is_a(nounSort)) { nounTerms.push(tmp2); } else if (tmp2.functor.is_a(pronounSort)) { pronounTerms.push(tmp2); } else if (tmp2.functor.is_a(adjectiveSort)) { adjectiveTerms.push(tmp2); } else if (tmp2.functor.name == "#not" && tmp2.attributes.length == 1 && (tmp2.attributes[0] instanceof TermTermAttribute) && (tmp2.attributes[0].term.functor.is_a(adjectiveSort))) { negatedAdjectiveTerms.push(tmp2.attributes[0].term); // console.log("negated adjectives are not supported in #derefFromContext!"); return null; } else if (tmp2.functor.is_a(determinerSort)) { determinerTerms.push(tmp2); } else if (tmp2.functor.is_a(relationSort)) { relationTerms.push([tmp2]); } else { otherTerms.push(tmp2); } } else { console.error("context.deref: clause contains an element that is not a term!"); } } if (genitiveTerm != null) return null; var all_determiner = null; var other_determiner = null; for (var _a = 0, determinerTerms_1 = determinerTerms; _a < determinerTerms_1.length; _a++) { var t = determinerTerms_1[_a]; if (t.functor.name == 'all') { if (determinerTerms.length == 1) { // this clause refers to a hypothetical, and not to entities in the context! this.lastDerefErrorType = DEREF_ERROR_CANNOT_PROCESS_EXPRESSION; return null; } else { all_determiner = t; } } else if (t.functor.name == 'determiner.other') { other_determiner = t; } } // remove "all" and "other" if (all_determiner != null) determinerTerms.splice(determinerTerms.indexOf(all_determiner), 1); if (other_determiner != null) determinerTerms.splice(determinerTerms.indexOf(other_determiner), 1); // we should really only have one determiner other than "all" or "other": if (determinerTerms.length > 1) { console.warn("NLContext.derefInternal: too many determiners other than all/other" + determinerTerms); this.lastDerefErrorType = DEREF_ERROR_CANNOT_PROCESS_EXPRESSION; return null; } if (properNounTerms.length > 0) { var output = []; for (var _b = 0, properNounTerms_1 = properNounTerms; _b < properNounTerms_1.length; _b++) { var properNounTerm = properNounTerms_1[_b]; if (properNounTerm.attributes[0] instanceof ConstantTermAttribute) { var name_1 = (properNounTerm.attributes[0]).value; var entities = this.findAllProperNoun(name_1, o); for (var _c = 0, entities_1 = entities; _c < entities_1.length; _c++) { var entity = entities_1[_c]; if (output.indexOf(entity.objectID) == -1) output.push(entity.objectID); } } } return output; } else if (pronounTerms.length > 0) { // Special case for single pronouns ("it", "him", "her", etc.) that could deref to // an entity in the current NLParseRecord: if (pronounTerms.length == 1 && clauseElements.length == 1 && nlpr.derefs.length > 0) { var pronounTerm = pronounTerms[0]; var deref = nlpr.derefs[nlpr.derefs.length - 1]; var nlprResult = this.matchPronounToNLPRDeref(pronounTerm, deref, o); if (nlprResult != null) return nlprResult; } var output = []; for (var _d = 0, pronounTerms_1 = pronounTerms; _d < pronounTerms_1.length; _d++) { var pronounTerm = pronounTerms_1[_d]; if (pronounTerm.functor.is_a(personalPronounSort) || pronounTerm.functor.is_a(reflexivePronounSort)) { if (pronounTerm.attributes[3].sort.is_a(firstPerson)) { output.push(new ConstantTermAttribute(this.speaker, o.getSort("#id"))); } else if (pronounTerm.attributes[3].sort.is_a(secondPerson)) { output.push(listenerVariable); } else if (pronounTerm.attributes[3].sort.is_a(thirdPerson)) { // find the most recent mention that could match with the pronoun var entity = this.pronounMatch(pronounTerm, this.mentions, o); if (entity != null) output.push(entity.objectID); } else { console.log("context.deref: unknown person dereferencing personal pronoun: " + clauseElements); } } else { if (pronounTerm.attributes[0] instanceof ConstantTermAttribute) { var pronounType = pronounTerm.attributes[0].value; if (pronounType == "pronoun.everybody") { // match with all the known "character" entities: var tmp = this.findEntitiesOfSort(o.getSort("character"), o); var allCharacters = []; for (var _e = 0, tmp_1 = tmp; _e < tmp_1.length; _e++) { var tmpl = tmp_1[_e]; for (var _f = 0, tmpl_1 = tmpl; _f < tmpl_1.length; _f++) { var ce = tmpl_1[_f]; if (allCharacters.indexOf(ce) == -1) allCharacters.push(ce); } } for (var _g = 0, allCharacters_1 = allCharacters; _g < allCharacters_1.length; _g++) { var ce = allCharacters_1[_g]; output.push(ce.objectID); } } else if (pronounType == "pronoun.everybody.else") { // match with all the known "character" entities, except speaker and listener: var tmp = this.findEntitiesOfSort(o.getSort("character"), o); var allCharacters = []; for (var _h = 0, tmp_2 = tmp; _h < tmp_2.length; _h++) { var tmpl = tmp_2[_h]; for (var _j = 0, tmpl_2 = tmpl; _j < tmpl_2.length; _j++) { var ce = tmpl_2[_j]; if (allCharacters.indexOf(ce) == -1) allCharacters.push(ce); } } for (var _k = 0, allCharacters_2 = allCharacters; _k < allCharacters_2.length; _k++) { var ce = allCharacters_2[_k]; if (ce.objectID.value != this.speaker && ce.objectID.value != this.ai.selfID) output.push(ce.objectID); } } } else { console.log("context.deref: unsupported pronoun! " + pronounTerm); } } } if (output.length == 0) { this.lastDerefErrorType = DEREF_ERROR_NO_REFERENTS; return null; } return output; } else if (nounTerms.length == 1) { var output = []; for (var _l = 0, nounTerms_1 = nounTerms; _l < nounTerms_1.length; _l++) { var nounTerm = nounTerms_1[_l]; if (nounTerm.attributes.length == 2 && nounTerm.attributes[0] instanceof ConstantTermAttribute && nounTerm.attributes[0].value == "space.here") { // find the location of the speaker: var hereEntity = this.findLocationOfID(this.speaker); if (hereEntity != null) { return [hereEntity.objectID]; } } else if (nounTerm.attributes.length == 2 && nounTerm.attributes[0] instanceof ConstantTermAttribute && nounTerm.attributes[0].value == "space.there") { // Find if there is a location we just talked about (and that is not the place where the speaker is): var hereEntity = this.findLocationOfID(this.speaker); var thereEntity = null; var entities_mpl = this.findEntitiesOfSort(o.getSort("space.location"), o); var candidateThereEntities = this.applySingularTheDeterminer(entities_mpl); if (candidateThereEntities != null && candidateThereEntities.length == 1) thereEntity = candidateThereEntities[0]; if (thereEntity != null && thereEntity != hereEntity) { return [thereEntity.objectID]; } } else if (nounTerm.attributes.length == 2 && nounTerm.attributes[0] instanceof ConstantTermAttribute && nounTerm.attributes[0].value == "space.outside") { // Find the most specific location that is "outdoers" and the player is in right now var outsideEntity = this.findMostSpecificOutdoorLocationOfID(this.speaker, o); if (outsideEntity != null) { return [outsideEntity.objectID]; } } else if (nounTerm.attributes.length == 2 && nounTerm.attributes[0] instanceof ConstantTermAttribute) { var name_2 = (nounTerm.attributes[0]).value; var nameSort = o.getSortSilent(name_2); var grammaticalNumberSort = nounTerm.attributes[1].sort; var singular = false; if (grammaticalNumberSort.name == "singular") singular = true; if (nameSort != null) { // See if we have any determiners that will modify the search: // - "the" -> resolve to the latest one mentioned if there is more than one (if it's from shortTermMemory, and there is more than one, then fail) // - "every" -> change from singular to plural // - possessive: -> look for "owned-by" relationship // - "this" -> if it's a mention, consider the closest one, if it's in shortTermMemory, look for the closest one to the character // - "these" -> (ignore) // - "that" -> if it's a mention, consider the second one, if it's in shortTermMemory, consider the further one // - "those" -> (ignore) // - "other" -> removes all the matches from short term memory or from mentions // "a"/"any" -> fail // "some"/"much"/"many" -> ??? var the_determiner = false; // let a_determiner:boolean = false; var this_determiner = false; var that_determiner = false; // console.log("context.derefInternal: nounTerm = " + nounTerm); for (var _m = 0, determinerTerms_2 = determinerTerms; _m < determinerTerms_2.length; _m++) { var determinerTerm = determinerTerms_2[_m]; // console.log("determinerTerm: " + determinerTerm); var determinerNumberSort = determinerTerm.attributes[1].sort; if (determinerTerm.functor.name == "the") { // if (singular) { the_determiner = true; // } else { // ignore for now ... // } } else if (determinerTerm.functor.name == "every") { singular = false; } else if (determinerTerm.functor.name == "close-demonstrative-determiner") { if (determinerNumberSort.name == "singular") this_determiner = true; // if it's plural ("these"), ignore } else if (determinerTerm.functor.name == "far-demonstrative-determiner") { if (determinerNumberSort.name == "singular") that_determiner = true; // if it's plural ("those"), ignore } else if (determinerTerm.functor.is_a(possessiveDeterminerSort)) { if (determinerTerm.functor.name == "determiner.my") { // find owner: // let ownerRelation:Term = Term.fromString("verb.own('"+this.speaker+"'[#id])", o); // ownerRelation.addAttribute(determinerTerm.attributes[0]); // relationTerms.push(ownerRelation); var belongsRelation = new Term(o.getSort("verb.own"), [new ConstantTermAttribute(this.speaker, o.getSort("#id")), determinerTerm.attributes[0]]); var haveRelation = new Term(o.getSort("verb.have"), [new ConstantTermAttribute(this.speaker, o.getSort("#id")), determinerTerm.attributes[0]]); relationTerms.push([belongsRelation, haveRelation]); } else if (determinerTerm.functor.name == "determiner.your") { // find owner: // let ownerRelation:Term = Term.fromString("verb.own('"+this.ai.selfID+"'[#id])", o); // ownerRelation.addAttribute(determinerTerm.attributes[0]); // relationTerms.push(ownerRelation); var belongsRelation = new Term(o.getSort("verb.own"), [new ConstantTermAttribute(this.ai.selfID, o.getSort("#id")), determinerTerm.attributes[0]]); var haveRelation = new Term(o.getSort("verb.have"), [new ConstantTermAttribute(this.ai.selfID, o.getSort("#id")), determinerTerm.attributes[0]]); relationTerms.push([belongsRelation, haveRelation]); } else { console.log("context.deref: determiner " + determinerTerm + " not yet supported!"); } } else if (determinerTerm.functor.name == "article.any") { // a_determiner = true; // console.log("context.deref: determiner " + determinerTerm + " is invalid in contex dereference!"); return null; } else if (determinerTerm.functor.name == "a") { // a_determiner = true; // console.log("context.deref: determiner " + determinerTerm + " is invalid in contex dereference!"); return null; } else { console.log("context.deref: determiner " + determinerTerm + " not yet supported!"); } } //console.log("nameSort: '" + nameSort + "'"); //console.log("relationTerms: '" + relationTerms + "'"); var entities_mpl = this.findEntitiesOfSort(nameSort, o); if (entities_mpl == null) { console.log("No entities match name constraint '" + nameSort + "'"); this.lastDerefErrorType = DEREF_ERROR_NO_REFERENTS; return null; } //console.log("entities_mpl: " + entities_mpl); // adjectives: for (var _o = 0, adjectiveTerms_1 = adjectiveTerms; _o < adjectiveTerms_1.length; _o++) { var adjectiveTerm = adjectiveTerms_1[_o]; if (Term.equalsNoBindingsAttribute(nounTerm.attributes[0], adjectiveTerm.attributes[0]) == 1 && adjectiveTerm.attributes[1] instanceof ConstantTermAttribute) { // console.log("clauseElements: " + clauseElements); // console.log("nounTerm: " + nounTerm); // console.log("adjectiveTerm: " + adjectiveTerm); var adjectiveStr = (adjectiveTerm.attributes[1].value); var specificAdjectiveSort = o.getSortSilent(adjectiveStr); if (specificAdjectiveSort != null) { // console.log("adjective sort: " + specificAdjectiveSort.name); entities_mpl = this.filterByAdjective(specificAdjectiveSort, entities_mpl, o); } // } else { // console.log(" discarded... (didn't match noun)"); } } //console.log("entities_mpl (after adjectives): " + entities_mpl); // apply relations: for (var _p = 0, relationTerms_1 = relationTerms; _p < relationTerms_1.length; _p++) { var relationTermL = relationTerms_1[_p]; var relationTerm = relationTermL[0]; // check if it's a spatial relation (which are not in the logic representation, to save computation requirements): if (relationTerm.functor.is_a(spatialRelationSort)) { if (Term.equalsNoBindingsAttribute(nounTerm.attributes[0], relationTerm.attributes[0]) == 1 && ((relationTerm.attributes[1] instanceof ConstantTermAttribute) || relationTerm.attributes[1] == listenerVariable)) { var otherEntityID = void 0; if (relationTerm.attributes[1] == listenerVariable) { // in this case, we synthesize a relation with the variable replaced by a constant, since otherwise // the matching functions will fail: otherEntityID = this.ai.selfID; relationTerm = relationTerm.clone([]); relationTerm.attributes[1] = new ConstantTermAttribute(otherEntityID, this.ai.cache_sort_id); } else { otherEntityID = (relationTerm.attributes[1]).value; } var results_mpl = []; for (var _q = 0, entities_mpl_1 = entities_mpl; _q < entities_mpl_1.length; _q++) { var entities_5 = entities_mpl_1[_q]; var results = []; for (var _r = 0, entities_2 = entities_5; _r < entities_2.length; _r++) { var entity = entities_2[_r]; var spatialRelations = AI.spatialRelations(entity.objectID.value, otherEntityID); if (spatialRelations != null) { for (var _s = 0, spatialRelations_1 = spatialRelations; _s < spatialRelations_1.length; _s++) { var sr = spatialRelations_1[_s]; if (relationTerm.functor.subsumes(sr)) { results.push(entity); break; } } } else { var tmp = relationTerm.attributes[0]; relationTerm.attributes[0] = entity.objectID; if (results.indexOf(entity) == -1 && entity.relationMatch(relationTerm, o, pos)) results.push(entity); relationTerm.attributes[0] = tmp; } } results_mpl.push(results); } entities_mpl = results_mpl; } else if (Term.equalsNoBindingsAttribute(nounTerm.attributes[0], relationTerm.attributes[1]) == 1 && ((relationTerm.attributes[0] instanceof ConstantTermAttribute) || relationTerm.attributes[0] == listenerVariable)) { var otherEntityID = void 0; if (relationTerm.attributes[1] == listenerVariable) { // in this case, we synthesize a relation with the variable replaced by a constant, since otherwise // the matching functions will fail: otherEntityID = this.ai.selfID; relationTerm = relationTerm.clone([]); relationTerm.attributes[0] = new ConstantTermAttribute(otherEntityID, this.ai.cache_sort_id); } else { otherEntityID = (relationTerm.attributes[0]).value; } var results_mpl = []; for (var _t = 0, entities_mpl_2 = entities_mpl; _t < entities_mpl_2.length; _t++) { var entities_6 = entities_mpl_2[_t]; var results = []; for (var _u = 0, entities_3 = entities_6; _u < entities_3.length; _u++) { var entity = entities_3[_u]; var spatialRelations = AI.spatialRelations(entity.objectID.value, otherEntityID); if (spatialRelations != null) { console.log(" spatialRelations != null"); for (var _v = 0, spatialRelations_2 = spatialRelations; _v < spatialRelations_2.length; _v++) { var sr = spatialRelations_2[_v]; if (relationTerm.functor.subsumes(sr)) { results.push(entity); break; } } } else { var tmp = relationTerm.attributes[0]; relationTerm.attributes[1] = entity.objectID; console.log(" spatialRelations == null, checking manually (2) for " + relationTerm); if (results.indexOf(entity) == -1 && entity.relationMatch(relationTerm, o, pos)) results.push(entity); relationTerm.attributes[1] = tmp; } } results_mpl.push(results); } entities_mpl = results_mpl; } //console.log("After " + relationTerm + ": " + entities_mpl[0].length + ", " + entities_mpl[1].length + ", " + entities_mpl[2].length); } else { if (Term.equalsNoBindingsAttribute(nounTerm.attributes[0], relationTerm.attributes[0]) == 1 && relationTerm.attributes[1] instanceof ConstantTermAttribute) { // console.log("Considering relation (1): " + relationTerm); entities_mpl = this.filterByAtLeastOneRelation1(relationTermL, entities_mpl, o, pos); } else if (Term.equalsNoBindingsAttribute(nounTerm.attributes[0], relationTerm.attributes[1]) == 1 && relationTerm.attributes[0] instanceof ConstantTermAttribute) { // console.log("Considering relation (2): " + relationTerm); entities_mpl = this.filterByAtLeastOneRelation2(relationTermL, entities_mpl, o, pos); } } } //console.log("entities_mpl (after relations): " + entities_mpl); if (entities_mpl[0].length == 0 && entities_mpl[1].length == 0 && entities_mpl[2].length == 0) { this.lastDerefErrorType = DEREF_ERROR_NO_REFERENTS; return null; } if (this_determiner || that_determiner) { // remove both the speaker and listener: var toDelete = []; for (var _w = 0, _x = entities_mpl[1]; _w < _x.length; _w++) { var e = _x[_w]; if (e.objectID.value == this.speaker || e.objectID.value == this.ai.selfID) { toDelete.push(e); } } for (var _y = 0, toDelete_1 = toDelete; _y < toDelete_1.length; _y++) { var e = toDelete_1[_y]; entities_mpl[1].splice(entities_mpl[1].indexOf(e), 1); } // sort! entities_mpl[1].sort(function (e1, e2) { if (e1.distanceFromSpeaker == null && e2.distanceFromSpeaker == null) { return 0; } else if (e1.distanceFromSpeaker == null) { return 1; } else if (e2.distanceFromSpeaker == null) { return -1; } else { return e1.distanceFromSpeaker - e2.distanceFromSpeaker; } }); } if (returnAllCandidatesBeforeDisambiguation) { var pool = null; if (entities_mpl[0].length > 0) { pool = entities_mpl[0]; } else if (entities_mpl[1].length > 0) { pool = entities_mpl[1]; } else { pool = entities_mpl[2]; } pool = removeListDuplicates(pool); var output_1 = []; for (var _z = 0, pool_1 = pool; _z < pool_1.length; _z++) { var e = pool_1[_z]; output_1.push(e.objectID); } return output_1; } // console.log("Before determiners: \nM: " + entities_mpl[0] + "\nP: " + entities_mpl[1] + "\nL: " + entities_mpl[2]); // apply determiners: // If there is no determiners, assume a "the": if (determinerTerms.length == 0) the_determiner = true; var entities = null; if (other_determiner) { if (the_determiner) { // first easy case: discard the speaker and listener, and see if that leaves already just 1: var candidatesEliminated = false; var entitiesButListenerAndSpeaker = []; for (var _0 = 0, entities_mpl_3 = entities_mpl; _0 < entities_mpl_3.length; _0++) { var e_l = entities_mpl_3[_0]; for (var _1 = 0, e_l_1 = e_l; _1 < e_l_1.length; _1++) { var e = e_l_1[_1]; if (e.objectID.value == this.speaker || e.objectID.value == this.ai.selfID) { candidatesEliminated = true; } else { entitiesButListenerAndSpeaker.push(e); } } } if (candidatesEliminated && entitiesButListenerAndSpeaker.length == 1) { entities = entitiesButListenerAndSpeaker; } else { var toDiscard = this.applySingularTheDeterminer(entities_mpl); if (toDiscard.length > 0) { var e = toDiscard[0]; if (entities_mpl[0].indexOf(e) != -1) entities_mpl[0].splice(entities_mpl[0].indexOf(e), 1); if (entities_mpl[1].indexOf(e) != -1) entities_mpl[1].splice(entities_mpl[1].indexOf(e), 1); if (entities_mpl[2].indexOf(e) != -1) entities_mpl[2].splice(entities_mpl[2].indexOf(e), 1); if (singular) { entities = this.applySingularTheDeterminer(entities_mpl); } else { entities = entities_mpl[0].concat(entities_mpl[1]).concat(entities_mpl[2]); } } } } else { for (var _2 = 0, _3 = entities_mpl[0]; _2 < _3.length; _2++) { var e = _3[_2]; if (entities_mpl[2].indexOf(e) != -1) entities_mpl[2].splice(entities_mpl[2].indexOf(e), 1); } for (var _4 = 0, _5 = entities_mpl[1]; _4 < _5.length; _4++) { var e = _5[_4]; if (entities_mpl[2].indexOf(e) != -1) entities_mpl[2].splice(entities_mpl[2].indexOf(e), 1); } entities_mpl[0] = []; entities_mpl[1] = []; if (singular) { entities = this.applySingularTheDeterminer(entities_mpl); } else { entities = entities_mpl[2]; } } } else if (the_determiner) { if (singular) { entities = this.applySingularTheDeterminer(entities_mpl); } else { entities = entities_mpl[0].concat(entities_mpl[1]).concat(entities_mpl[2]); } // console.log("the determiner with entities_mpl: " + entities_mpl + "\nResult: " + entities); } else if (this_determiner) { // remove the speaker, and the content of the inventory from the list of candidates: // since it's very weird to use "this" to refer to the inventory... (but // we save it in ``toConsiderIfNoneLeft" just in case...) var toDelete = []; var toConsiderIfNoneLeft = []; for (var idx = 0; idx < entities_mpl[1].length; idx++) { if (entities_mpl[1][idx].objectID.value == this.speaker) { toDelete.push(entities_mpl[1][idx]); } else if (entities_mpl[1][idx].distanceFromSpeaker == 0 && entities_mpl[1][idx].relationMatch(new Term(o.getSort("verb.have"), [new ConstantTermAttribute(this.speaker, o.getSort("#id")), entities_mpl[1][idx].objectID]), o, pos)) { toDelete.push(entities_mpl[1][idx]); toConsiderIfNoneLeft.push(entities_mpl[1][idx]); } else { // see if the object is contained in any other object we can see, and also remove: for (var _6 = 0, _7 = entities_mpl[1][idx].terms; _6 < _7.length; _6++) { var t = _7[_6]; if (t.functor.is_a(this.cache_sort_contains) && t.attributes.length >= 2 && Term.equalsAttribute(t.attributes[1], entities_mpl[1][idx].objectID, new Bindings())) { toDelete.push(entities_mpl[1][idx]); } } } } for (var _8 = 0, toDelete_2 = toDelete; _8 < toDelete_2.length; _8++) { var e = toDelete_2[_8]; entities_mpl[1].splice(entities_mpl[1].indexOf(e), 1); } if (entities_mpl[1].length > 0) { // get the one that is closest to the speaker: if (entities_mpl[1].length > 1) { if ((entities_mpl[1][0].distanceFromSpeaker < entities_mpl[1][1].distanceFromSpeaker) || (entities_mpl[1][0].distanceFromSpeaker != null && entities_mpl[1][1].distanceFromSpeaker == null)) { if (entities_mpl[1][0].distanceFromSpeaker < MAXIMUM_DISTANCE_TO_BE_CONSIDERED_THIS) { entities = [entities_mpl[1][0]]; } } else { // several locations are equally close (TODO: think to see if there is a way to disambiguate further) // ... // the two closest entities are at the same distance, we cannot disambiguate! } } else { if (entities_mpl[1][0].distanceFromSpeaker < MAXIMUM_DISTANCE_TO_BE_CONSIDERED_THIS) { entities = [entities_mpl[1][0]]; } } } if (entities == null) { if (entities_mpl[0].length == 1) { entities = [entities_mpl[0][0]]; } else if (entities_mpl[2].length == 1) { entities = [entities_mpl[2][0]]; } else { entities = []; } } // If we cannot find the entity we are looking for but one entity in the inventory matches, then maybe // the speaker refers to that one: if (entities.length == 0 && toConsiderIfNoneLeft.length == 1) { entities = toConsiderIfNoneLeft; } // console.log("\"this\" determiner with entities_mpl: " + entities_mpl + "\nResult: " + entities); } else if (that_determiner) { if (entities_mpl[0].length == 1) { entities = [entities_mpl[0][0]]; } else if (entities_mpl[1].length == 1) { entities = [entities_mpl[1][0]]; } else if (entities_mpl[1].length == 2) { // get the one that is further to the speaker: if (entities_mpl[1][0].distanceFromSpeaker < entities_mpl[1][1].distanceFromSpeaker) { entities = [entities_mpl[1][1]]; } else { // the two closest entities are at the same distance, we cannot disambiguate! entities = []; } } else if (entities_mpl[2].length == 1) { entities = [entities_mpl[2][0]]; } else { entities = []; } // } else if (a_determiner) { // // just get the first one if it exists: // entities = entities_mpl[0].concat(entities_mpl[1]).concat(entities_mpl[2]); // if (entities.length>0) entities = [entities[0]]; } else { // if there is no determiner, then this should not be a context dereference ... entities = entities_mpl[0].concat(entities_mpl[1]).concat(entities_mpl[2]); } if (entities != null) { entities = removeListDuplicates(entities); // consider grammatical number: if (entities.length == 1) { output.push(entities[0].objectID); } else if (entities.length > 1) { if (singular) { // console.log("NLContext.deref noun: more than one entity matches a singular noun constraint ("+nameSort.name+"): " + entities); } else { for (var _9 = 0, entities_4 = entities; _9 < entities_4.length; _9++) { var e = entities_4[_9]; output.push(e.objectID); } } } else { // console.log("NLContext.deref noun: no entity matches the noun constraint ("+nameSort.name+")"); } } /* if (determinerTerms.length > 0) { console.log("After determiners/number: " + output); } */ } } } if (output.length == 0) this.lastDerefErrorType = DEREF_ERROR_CANNOT_DISAMBIGUATE; //console.log("output: " + output); return output; } else if (nounTerms.length > 1) { this.lastDerefErrorType = DEREF_ERROR_CANNOT_PROCESS_EXPRESSION; return null; } this.lastDerefErrorType = DEREF_ERROR_CANNOT_PROCESS_EXPRESSION; return null; }; NLContext.prototype.pronounMatch = function (pronounTerm, candidates, o) { var entity; // get the gender, only characters can match with "he"/"she", and only live humans do not match with "it" var gender = -1; if (pronounTerm.attributes[2].sort.name == "gender-masculine") gender = 0; else if (pronounTerm.attributes[2].sort.name == "gender-femenine") gender = 1; else if (pronounTerm.attributes[2].sort.name == "gender-neutral") gender = 2; for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { var e2 = candidates_1[_i]; if (gender == 0 || gender == 1) if (!e2.sortMatch(o.getSort("character"))) continue; if (gender == 2) if (e2.sortMatch(o.getSort("human")) && !e2.sortMatch(o.getSort("corpse"))) continue; if (e2.objectID.value != this.speaker && e2.objectID.value != this.ai.selfID) { if (entity == null) { entity = e2; } else { if (entity.mentionTime > e2.mentionTime) { // we found it! return entity; } // there is ambiguity... abort! this.lastDerefErrorType = DEREF_ERROR_CANNOT_DISAMBIGUATE; return null; } } } return entity; }; NLContext.prototype.matchPronounToNLPRDeref = function (pronounTerm, deref, o) { if (pronounTerm.attributes.length == 4 && pronounTerm.attributes[1].sort.name == "singular" && pronounTerm.attributes[3].sort.is_a(o.getSort("third-person"))) { // singular: // check if the last deref record would be a good match for this pronoun: if (deref.functor.name == "#derefFromContext" && deref.attributes.length == 2) { var id = deref.attributes[1]; if (id instanceof ConstantTermAttribute) { var idstr = id.value; var entity = this.findByID(idstr); if (entity != null) { entity = this.pronounMatch(pronounTerm, [entity], o); if (entity != null) { // console.log(" matchPronounToNLPRDeref match (#derefFromContext): " + id); return [id]; } } } } else if (deref.functor.name == "#derefQuery" && deref.attributes.length == 3 && deref.attributes[2] instanceof TermTermAttribute) { // console.log("pronounTerm: " + pronounTerm) // console.log("deref: " + deref); // See if the query could match: var gender = -1; if (pronounTerm.attributes[2].sort.name == "gender-masculine") gender = 0; else if (pronounTerm.attributes[2].sort.name == "gender-femenine") gender = 1; else if (pronounTerm.attributes[2].sort.name == "gender-neutral") gender = 2; var match = true; var queryTerms = NLParser.termsInList(deref.attributes[2].term, "#and"); for (var _i = 0, queryTerms_1 = queryTerms; _i < queryTerms_1.length; _i++) { var queryTerm = queryTerms_1[_i]; if (gender == 0 || gender == 1) if (!queryTerm.functor.is_a(o.getSort("character"))) { match = false; break; } if (gender == 2) if (queryTerm.functor.is_a(o.getSort("human")) && !queryTerm.functor.is_a(o.getSort("corpse"))) { match = false; break; } } if (match) { // console.log(" matchPronounToNLPRDeref match (#derefQuery): " + deref.attributes[1]); return [deref.attributes[1]]; } } else { // TODO: handle universals/hypotheticals // ... } } else { // TODO: support the plural case // ... } return null; }; /* - Given a list containing [entities in mentions, entities in short term memory, entities in long-term memory] - This function returns the list of entities that the deteminer "the" (singular) refers to - If no entity applies, then it will return an empty list */ NLContext.prototype.applySingularTheDeterminer = function (msl) { var pool = null; if (msl[0].length > 0) { pool = msl[0]; } else if (msl[1].length > 0) { pool = msl[1]; } else { pool = msl[2]; } // console.log("applySingularTheDeterminer (before), M: " + msl[0] + "\nP: " + msl[1] + "\nL: " + msl[2]); // console.log("pool: " + pool); if (pool.length == 1) { // mentions: return [pool[0]]; } else if (pool.length > 1) { // mentions: // console.log(" msl[0][0].mentionTime: " + msl[0][0].mentionTime + " (" + msl[0][0].objectID + ")"); // console.log(" msl[0][1].mentionTime: " + msl[0][1].mentionTime + " (" + msl[0][0].objectID + ")"); if (pool[0].mentionTime > pool[1].mentionTime) { return [pool[0]]; } else { // the two closest entities were mentioned at the same time. // Since we cannot disambiguate just by time, try to disambiguate by distance: var candidates = []; var bestTime = null; for (var _i = 0, pool_2 = pool; _i < pool_2.length; _i++) { var e = pool_2[_i]; if (bestTime == null || e.mentionTime < bestTime) { bestTime = e.mentionTime; candidates = [e]; } else if (bestTime == e.mentionTime) { candidates.push(e); } } if (candidates.length <= 1) return candidates; // sort by distance: candidates.sort(function (e1, e2) { if (e1.distanceFromSpeaker == null && e2.distanceFromSpeaker == null) { return 0; } else if (e1.distanceFromSpeaker == null) { return 1; } else if (e2.distanceFromSpeaker == null) { return -1; } else { return e1.distanceFromSpeaker - e2.distanceFromSpeaker; } }); // console.log("sorted candidates: " + candidates); // console.log("SPACE_NEAR_FAR_THRESHOLD: " + SPACE_NEAR_FAR_THRESHOLD); // if the closest one is clearly closer (and the others are far), disambiguate: if (candidates[0].distanceFromSpeaker < candidates[1].distanceFromSpeaker && candidates[0].distanceFromSpeaker < SPACE_NEAR_FAR_THRESHOLD && candidates[1].distanceFromSpeaker > SPACE_NEAR_FAR_THRESHOLD) { return [candidates[0]]; } return []; } } return []; }; NLContext.prototype.findLocationOfID = function (id) { for (var _i = 0, _a = this.shortTermMemory; _i < _a.length; _i++) { var entity = _a[_i]; if (entity.objectID.value == id) { for (var _b = 0, _c = entity.terms; _b < _c.length; _b++) { var t = _c[_b]; if (t.functor.is_a(this.cache_sort_space_at) && t.attributes.length == 2 && t.attributes[0] instanceof ConstantTermAttribute && t.attributes[1] instanceof ConstantTermAttribute && t.attributes[0].value == id) { return this.findByID(t.attributes[1].value); } } } } for (var _d = 0, _e = this.mentions; _d < _e.length; _d++) { var entity = _e[_d]; if (entity.objectID.value == id) { for (var _f = 0, _g = entity.terms; _f < _g.length; _f++) { var t = _g[_f]; if (t.functor.is_a(this.cache_sort_space_at) && t.attributes.length == 2 && t.attributes[0] instanceof ConstantTermAttribute && t.attributes[1] instanceof ConstantTermAttribute && t.attributes[0].value == id) { return this.findByID(t.attributes[1].value); } } } } return null; }; NLContext.prototype.findMostSpecificOutdoorLocationOfID = function (id, o) { var open = []; var closed = []; var outdoors_sort = o.getSort("outdoor.location"); for (var _i = 0, _a = this.shortTermMemory; _i < _a.length; _i++) { var entity = _a[_i]; if (entity.objectID.value == id) { for (var _b = 0, _c = entity.terms; _b < _c.length; _b++) { var t = _c[_b]; if (t.functor.is_a(this.cache_sort_space_at) && t.attributes.length == 2 && t.attributes[0] instanceof ConstantTermAttribute && t.attributes[1] instanceof ConstantTermAttribute && t.attributes[0].value == id) { open.push(entity); } } } } while (open.length > 0) { var current = open[0]; open.splice(0, 1); closed.push(current); for (var _d = 0, _e = current.terms; _d < _e.length; _d++) { var t = _e[_d]; if (t.functor.is_a(outdoors_sort)) { return current; } if (t.functor.is_a(this.cache_sort_space_at) && t.attributes.length == 2 && t.attributes[0] instanceof ConstantTermAttribute && t.attributes[1] instanceof ConstantTermAttribute && t.attributes[0].value == current.objectID.value) { var next = this.findByID(t.attributes[1].value); if (next != null && closed.indexOf(next) == -1 && open.indexOf(next) == -1) open.push(next); } } } return null; }; NLContext.prototype.findByID = function (id) { for (var _i = 0, _a = this.shortTermMemory; _i < _a.length; _i++) { var entity = _a[_i]; if (entity.objectID.value == id) return entity; } for (var _b = 0, _c = this.mentions; _b < _c.length; _b++) { var entity = _c[_b]; if (entity.objectID.value == id) return entity; } return null; }; NLContext.prototype.findClosestProperNoun = function (name, o) { // console.log("NLContext.findClosestProperNoun: " + name); for (var _i = 0, _a = this.shortTermMemory; _i < _a.length; _i++) { var entity = _a[_i]; if (entity.properNounMatch(name)) return entity; } for (var _b = 0, _c = this.mentions; _b < _c.length; _b++) { var entity = _c[_b]; if (entity.properNounMatch(name)) return entity; } var nameSort = o.getSort("name"); for (var _d = 0, _e = this.ai.longTermMemory.allSingleTermMatches(nameSort, 2, o); _d < _e.length; _d++) { var s = _e[_d]; if (s.terms[0].functor == nameSort && s.terms[0].attributes[1] instanceof ConstantTermAttribute && s.terms[0].attributes[1].value == name) { var e = this.newContextEntity((s.terms[0].attributes[0]), 0, null, o, true); if (e != null) return e; } } return null; }; NLContext.prototype.findAllProperNoun = function (name, o) { var matches = []; for (var _i = 0, _a = this.shortTermMemory; _i < _a.length; _i++) { var entity = _a[_i]; if (entity.properNounMatch(name)) matches.push(entity); } for (var _b = 0, _c = this.mentions; _b < _c.length; _b++) { var entity = _c[_b]; if (entity.properNounMatch(name)) matches.push(entity); } var nameSort = o.getSort("name"); for (var _d = 0, _e = this.ai.longTermMemory.allSingleTermMatches(nameSort, 2, o); _d < _e.length; _d++) { var s = _e[_d]; if (s.terms[0].functor == nameSort && (s.terms[0].attributes[0] instanceof ConstantTermAttribute) && (s.terms[0].attributes[1] instanceof ConstantTermAttribute) && s.terms[0].attributes[1].value == name) { //console.log(" findAllProperNoun: '"+(<ConstantTermAttribute>s.terms[0].attributes[0]).value+"'"); var e = this.newContextEntity((s.terms[0].attributes[0]), 0, null, o, true); if (e != null) { matches.push(e); } else { // console.log(" findAllProperNoun: failed to create entity for name '"+name+"'"); } } } return matches; }; // returns 3 arrays, containins matches in mentions, shortTermMemory and long-term memory NLContext.prototype.findEntitiesOfSort = function (sort, o) { var results_mpl = []; var results = []; // let any_match:boolean = false; for (var _i = 0, _a = this.mentions; _i < _a.length; _i++) { var entity = _a[_i]; if (entity.sortMatch(sort)) { results.push(entity); //any_match = true; } } results_mpl.push(results); results = []; for (var _b = 0, _c = this.shortTermMemory; _b < _c.length; _b++) { var entity = _c[_b]; if (entity.sortMatch(sort)) { results.push(entity); // any_match = true; } } results_mpl.push(results); // if (any_match) { // if we have found something on shortTermMemory or mentions, do not check for long-term memory: // results_mpl.push([]); // return results_mpl; // } results = []; for (var _d = 0, _e = this.ai.longTermMemory.allSingleTermMatches(sort, 1, o); _d < _e.length; _d++) { var s = _e[_d]; if (s.terms[0].functor.is_a(sort) && s.terms[0].attributes[0] instanceof ConstantTermAttribute) { var e = this.newContextEntity((s.terms[0].attributes[0]), 0, null, o, true); if (e != null) results.push(e); } } results_mpl.push(results); return results_mpl; }; // returns 3 arrays, containins matches in mentions, shortTermMemory and long-term memory NLContext.prototype.filterByAdjective = function (adjective, entities_mpl, o) { // console.log("filterByAdjective: " + adjective); var results_mpl = []; for (var _i = 0, entities_mpl_4 = entities_mpl; _i < entities_mpl_4.length; _i++) { var entities = entities_mpl_4[_i]; var results = []; for (var _a = 0, entities_7 = entities; _a < entities_7.length; _a++) { var entity = entities_7[_a]; if (entity.adjectiveMatch(adjective, o)) results.push(entity); } results_mpl.push(results); } return results_mpl; }; // returns 3 arrays, containins matches in mentions, shortTermMemory and long-term memory NLContext.prototype.filterByRelation1 = function (relation, entities_mpl, o, pos) { var results_mpl = []; for (var _i = 0, entities_mpl_5 = entities_mpl; _i < entities_mpl_5.length; _i++) { var entities = entities_mpl_5[_i]; var results = []; for (var _a = 0, entities_8 = entities; _a < entities_8.length; _a++) { var entity = entities_8[_a]; var tmp = relation.attributes[0]; relation.attributes[0] = entity.objectID; if (entity.relationMatch(relation, o, pos)) results.push(entity); relation.attributes[0] = tmp; } results_mpl.push(results); } return results_mpl; }; // returns 3 arrays, containins matches in mentions, shortTermMemory and long-term memory NLContext.prototype.filterByAtLeastOneRelation1 = function (relationL, entities_mpl, o, pos) { var results_mpl = []; for (var _i = 0, entities_mpl_6 = entities_mpl; _i < entities_mpl_6.length; _i++) { var entities = entities_mpl_6[_i]; var results = []; for (var _a = 0, entities_9 = entities; _a < entities_9.length; _a++) { var entity = entities_9[_a]; for (var _b = 0, relationL_1 = relationL; _b < relationL_1.length; _b++) { var relation = relationL_1[_b]; var tmp = relation.attributes[0]; relation.attributes[0] = entity.objectID; if (results.indexOf(entity) == -1 && entity.relationMatch(relation, o, pos)) results.push(entity); relation.attributes[0] = tmp; } } results_mpl.push(results); } return results_mpl; }; // returns 3 arrays, containins matches in mentions, shortTermMemory and long-term memory NLContext.prototype.filterByRelation2 = function (relation, entities_mpl, o, pos) { var results_mpl = []; for (var _i = 0, entities_mpl_7 = entities_mpl; _i < entities_mpl_7.length; _i++) { var entities = entities_mpl_7[_i]; var results = []; for (var _a = 0, entities_10 = entities; _a < entities_10.length; _a++) { var entity = entities_10[_a]; var tmp = relation.attributes[1]; relation.attributes[1] = entity.objectID; if (entity.relationMatch(relation, o, pos)) results.push(entity); relation.attributes[1] = tmp; } results_mpl.push(results); } return results_mpl; }; // returns 3 arrays, containins matches in mentions, shortTermMemory and long-term memory NLContext.prototype.filterByAtLeastOneRelation2 = function (relationL, entities_mpl, o, pos) { var results_mpl = []; for (var _i = 0, entities_mpl_8 = entities_mpl; _i < entities_mpl_8.length; _i++) { var entities = entities_mpl_8[_i]; var results = []; for (var _a = 0, entities_11 = entities; _a < entities_11.length; _a++) { var entity = entities_11[_a]; for (var _b = 0, relationL_2 = relationL; _b < relationL_2.length; _b++) { var relation = relationL_2[_b]; var tmp = relation.attributes[1]; relation.attributes[1] = entity.objectID; if (results.indexOf(entity) == -1 && entity.relationMatch(relation, o, pos)) results.push(entity); relation.attributes[1] = tmp; } } results_mpl.push(results); } return results_mpl; }; // Attempts to complete verb arguments by looking at previous sentences in the context. For example, if some one says: // "Do you know my password?" // and then "Would qwerty know?" -> then the parameter "my password" should be transferred to the "qwerty know" verb NLContext.prototype.completeVerbArgumentsFromContext = function (verb, outputVariable, o) { if (verb.attributes.length == 0) return null; var verbSort = verb.functor; var firstAttribute = verb.attributes[0]; var nAttributes = verb.attributes.length; if (verbSort.name == "#cons") { nAttributes = verb.attributes.length - 1; if (verb.attributes.length >= 2 && verb.attributes[0] instanceof ConstantTermAttribute) { verbSort = o.getSort(verb.attributes[0].value); firstAttribute = verb.attributes[1]; } else { return null; } } // get the last performative by each agent: var performativesToConsider = []; { var perf = this.lastPerformativeBy(this.ai.selfID); if (perf != null) performativesToConsider.push(perf); perf = this.lastPerformativeBy(this.speaker); if (perf != null) performativesToConsider.push(perf); } var possibleOutputs = []; for (var _i = 0, performativesToConsider_1 = performativesToConsider; _i < performativesToConsider_1.length; _i++) { var perf = performativesToConsider_1[_i]; var verb2 = perf.performative.findSubtermWithFunctorSort(verbSort); if (verb2 != null) { // found it! reconstruct a possible verb: var output = new Term(verbSort, [firstAttribute]); for (var i = 1; i < verb2.attributes.length; i++) { output.attributes.push(verb2.attributes[i]); } possibleOutputs.push(new TermTermAttribute(output)); } } if (possibleOutputs.length == 0) { if (verbSort.is_a(o.getSort("verb.know"))) { for (var _a = 0, performativesToConsider_2 = performativesToConsider; _a < performativesToConsider_2.length; _a++) { var perf = performativesToConsider_2[_a]; if (perf.performative.functor.name == "perf.q.query" && perf.performative.attributes.length == 3) { var output = new Term(verbSort, [firstAttribute, perf.performative.attributes[2]]); possibleOutputs.push(new TermTermAttribute(output)); } else { /* <sort name="perf.question" super="perf.request"/> <sort name="perf.q.predicate" super="perf.question"/> <sort name="perf.q.predicate-negated" super="perf.question"/> <sort name="perf.q.whereis" super="perf.question"/> <sort name="perf.q.whereto" super="perf.question"/> <sort name="perf.q.query-followup" super="perf.q.query"/> <sort name="perf.q.whois.name" super="perf.question"/> <sort name="perf.q.whois.noname" super="perf.question"/> <sort name="perf.q.whatis.name" super="perf.question"/> <sort name="perf.q.whatis.noname" super="perf.question"/> <sort name="perf.q.action" super="perf.question,perf.request.action"/> <!-- this is similar to perf.request.action, except that it is a question, rather than a command --> <sort name="perf.q.howareyou" super="perf.question"/> <sort name="perf.q.when" super="perf.question"/> <sort name="perf.q.howmany" super="perf.question"/> <sort name="perf.q.why" super="perf.question"/> <sort name="perf.q.how" super="perf.question"/> */ } } } else if (verbSort.is_a(o.getSort("verb.go"))) { if (nAttributes == 1) { // we are missing the destination, see if in the last performative, we mentioned a location: for (var _b = 0, performativesToConsider_3 = performativesToConsider; _b < performativesToConsider_3.length; _b++) { var perf = performativesToConsider_3[_b]; var IDs = perf.IDsInPerformative(o); for (var _c = 0, IDs_2 = IDs; _c < IDs_2.length; _c++) { var ID = IDs_2[_c]; var e = this.findByID(ID.value); if (e != null && e.sortMatch(o.getSort("space.location"))) { var output = new Term(verbSort, [firstAttribute, ID]); possibleOutputs.push(new TermTermAttribute(output)); } } } } } } return possibleOutputs; }; NLContext.prototype.newHypotheticalID = function () { this.nextHypotheticalID++; return "H-" + this.speaker + "-" + this.nextHypotheticalID; }; NLContext.prototype.getNLContextPerformative = function (perf) { for (var _i = 0, _a = this.performatives; _i < _a.length; _i++) { var p = _a[_i]; if (p.performative == perf) return p; } return null; }; NLContext.fromXML = function (xml, o, ai, mentionMemorySize) { var c = new NLContext(xml.getAttribute("speaker"), ai, mentionMemorySize); var p_xml = getFirstElementChildByTag(xml, "shortTermMemory"); if (p_xml != null) { for (var _i = 0, _a = getElementChildrenByTag(p_xml, "NLContextEntity"); _i < _a.length; _i++) { var ce_xml = _a[_i]; var ce = NLContextEntity.fromXML(ce_xml, o); if (ce != null) c.shortTermMemory.push(ce); } } var m_xml = getFirstElementChildByTag(xml, "mentions"); if (m_xml != null) { for (var _b = 0, _c = getElementChildrenByTag(m_xml, "NLContextEntity"); _b < _c.length; _b++) { var ce_xml = _c[_b]; var ce = NLContextEntity.fromXML(ce_xml, o); if (ce != null) c.mentions.push(ce); } } var pf_xml = getFirstElementChildByTag(xml, "performatives"); if (pf_xml != null) { for (var _d = 0, _e = getElementChildrenByTag(pf_xml, "NLContextPerformative"); _d < _e.length; _d++) { var cp_xml = _e[_d]; var cp = NLContextPerformative.fromXML(cp_xml, c, o); if (cp != null) c.performatives.push(cp); } } var tmp_xml = getFirstElementChildByTag(xml, "inConversation"); if (tmp_xml != null) c.inConversation = tmp_xml.getAttribute("value") == "true"; tmp_xml = getFirstElementChildByTag(xml, "lastPerformativeInvolvingThisCharacterWasToUs"); if (tmp_xml != null) c.lastPerformativeInvolvingThisCharacterWasToUs = tmp_xml.getAttribute("value") == "true"; tmp_xml = getFirstElementChildByTag(xml, "expectingYes"); if (tmp_xml != null) c.expectingYes = tmp_xml.getAttribute("value") == "true"; tmp_xml = getFirstElementChildByTag(xml, "expectingThankYou"); if (tmp_xml != null) c.expectingThankYou = tmp_xml.getAttribute("value") == "true"; tmp_xml = getFirstElementChildByTag(xml, "expectingYouAreWelcome"); if (tmp_xml != null) c.expectingYouAreWelcome = tmp_xml.getAttribute("value") == "true"; tmp_xml = getFirstElementChildByTag(xml, "expectingGreet"); if (tmp_xml != null) c.expectingGreet = tmp_xml.getAttribute("value") == "true"; tmp_xml = getFirstElementChildByTag(xml, "expectingFarewell"); if (tmp_xml != null) c.expectingFarewell = tmp_xml.getAttribute("value") == "true"; tmp_xml = getFirstElementChildByTag(xml, "expectingNicetomeetyoutoo"); if (tmp_xml != null) c.expectingNicetomeetyoutoo = tmp_xml.getAttribute("value") == "true"; for (var _f = 0, _g = getElementChildrenByTag(xml, "expectingAnswerToQuestion_stack"); _f < _g.length; _f++) { var tmp_xml2 = _g[_f]; c.expectingAnswerToQuestion_stack.push(c.performatives[Number(tmp_xml2.getAttribute("value"))]); c.expectingAnswerToQuestionTimeStamp_stack.push(Number(tmp_xml2.getAttribute("time"))); } for (var _h = 0, _j = getElementChildrenByTag(xml, "expectingConfirmationToRequest_stack"); _h < _j.length; _h++) { var tmp_xml2 = _j[_h]; c.expectingConfirmationToRequest_stack.push(c.performatives[Number(tmp_xml2.getAttribute("value"))]); c.expectingConfirmationToRequestTimeStamp_stack.push(Number(tmp_xml2.getAttribute("time"))); } tmp_xml = getFirstElementChildByTag(xml, "lastEnumeratedQuestion_answered"); if (tmp_xml != null) c.lastEnumeratedQuestion_answered = c.performatives[Number(tmp_xml.getAttribute("value"))]; c.lastEnumeratedQuestion_answers = null; for (var _k = 0, _l = getElementChildrenByTag(xml, "lastEnumeratedQuestion_answers"); _k < _l.length; _k++) { var tmp_xml2 = _l[_k]; if (c.lastEnumeratedQuestion_answers == null) c.lastEnumeratedQuestion_answers = []; // c.lastEnumeratedQuestion_answers.push(Term.fromString(tmp_xml2.getAttribute("value"), o)); c.lastEnumeratedQuestion_answers.push(Term.parseAttribute(tmp_xml2.getAttribute("value"), o, [], [])); } tmp_xml = getFirstElementChildByTag(xml, "lastEnumeratedQuestion_next_answer_index"); if (tmp_xml != null) c.lastEnumeratedQuestion_next_answer_index = Number(tmp_xml.getAttribute("value")); tmp_xml = getFirstElementChildByTag(xml, "nextHypotheticalID"); if (tmp_xml != null) c.nextHypotheticalID = Number(tmp_xml.getAttribute("value")); tmp_xml = getFirstElementChildByTag(xml, "lastDerefErrorType"); if (tmp_xml != null) c.lastDerefErrorType = Number(tmp_xml.getAttribute("value")); return c; }; NLContext.prototype.outerHTML = function () { return this.saveToXML(); }; NLContext.prototype.saveToXML = function () { var str = "<context speaker=\"" + this.speaker + "\">\n"; str += "<shortTermMemory>\n"; for (var _i = 0, _a = this.shortTermMemory; _i < _a.length; _i++) { var ce = _a[_i]; str += ce.saveToXML() + "\n"; } str += "</shortTermMemory>\n"; str += "<mentions>\n"; for (var _b = 0, _c = this.mentions; _b < _c.length; _b++) { var ce = _c[_b]; str += ce.saveToXML() + "\n"; } str += "</mentions>\n"; str += "<performatives>\n"; for (var _d = 0, _e = this.performatives; _d < _e.length; _d++) { var cp = _e[_d]; str += cp.saveToXML() + "\n"; } str += "</performatives>\n"; str += "<inConversation value=\"" + this.inConversation + "\"/>\n"; str += "<lastPerformativeInvolvingThisCharacterWasToUs value=\"" + this.lastPerformativeInvolvingThisCharacterWasToUs + "\"/>\n"; str += "<expectingYes value=\"" + this.expectingYes + "\"/>\n"; str += "<expectingThankYou value=\"" + this.expectingThankYou + "\"/>\n"; str += "<expectingYouAreWelcome value=\"" + this.expectingYouAreWelcome + "\"/>\n"; str += "<expectingGreet value=\"" + this.expectingGreet + "\"/>\n"; str += "<expectingFarewell value=\"" + this.expectingFarewell + "\"/>\n"; str += "<expectingNicetomeetyoutoo value=\"" + this.expectingNicetomeetyoutoo + "\"/>\n"; for (var i = 0; i < this.expectingAnswerToQuestion_stack.length; i++) { str += "<expectingAnswerToQuestion_stack value=\"" + this.performatives.indexOf(this.expectingAnswerToQuestion_stack[i]) + "\" time=\"" + this.expectingAnswerToQuestionTimeStamp_stack[i] + "\"/>\n"; } for (var i = 0; i < this.expectingConfirmationToRequest_stack.length; i++) { str += "<expectingConfirmationToRequest_stack value=\"" + this.performatives.indexOf(this.expectingConfirmationToRequest_stack[i]) + "\" time=\"" + this.expectingConfirmationToRequestTimeStamp_stack[i] + "\"/>\n"; } if (this.lastEnumeratedQuestion_answered != null) { str += "<lastEnumeratedQuestion_answered value=\"" + this.performatives.indexOf(this.lastEnumeratedQuestion_answered) + "\"/>\n"; } if (this.lastEnumeratedQuestion_answers != null) { for (var i = 0; i < this.lastEnumeratedQuestion_answers.length; i++) { str += "<lastEnumeratedQuestion_answers value=\"" + this.lastEnumeratedQuestion_answers[i].toStringXML() + "\"/>\n"; } } str += "<lastEnumeratedQuestion_next_answer_index value=\"" + this.lastEnumeratedQuestion_next_answer_index + "\"/>\n"; str += "<nextHypotheticalID value=\"" + this.nextHypotheticalID + "\"/>\n"; str += "<lastDerefErrorType value=\"" + this.lastDerefErrorType + "\"/>\n"; str += "</context>"; return str; }; return NLContext; }());
(function () { 'use strict'; angular .module('AppThree.profiles', []); })(); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImFwcC9wcm9maWxlcy9wcm9maWxlcy5tb2R1bGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsQ0FBQztJQUNBLFlBQVksQ0FBQztJQUViLE9BQU87U0FDTCxNQUFNLENBQUMsbUJBQW1CLEVBQUUsRUFBRSxDQUFDLENBQUM7QUFDbkMsQ0FBQyxDQUFDLEVBQUUsQ0FBQyIsImZpbGUiOiJhcHAvcHJvZmlsZXMvcHJvZmlsZXMubW9kdWxlLmpzIiwic291cmNlc0NvbnRlbnQiOlsiKGZ1bmN0aW9uKCkge1xyXG5cdCd1c2Ugc3RyaWN0JztcclxuXHRcclxuXHRhbmd1bGFyXHJcblx0XHQubW9kdWxlKCdBcHBUaHJlZS5wcm9maWxlcycsIFtdKTtcclxufSkoKTsiXSwic291cmNlUm9vdCI6Ii9zb3VyY2UvIn0=
var fs = require('fs'); var path = require('path'); var request = require('request'); var crypto = require('crypto'); var readWXConfig = function() { var wxConf = fs.readFileSync(path.resolve(__dirname, '../', 'config/', 'weixin_config.json')); return wxConf; } var writeWXConfig = function(wxConf) { fs.writeFileSync(path.resolve(__dirname, '../', 'config/', 'weixin_config.json'), JSON.stringify(wxConf, null, 4)); } /** * 获取微信的access_token,微信access_token临时保存地方,7200秒刷新一次,修改本文件里面新获取到的access_token相关的值 * @return {[type]} [description] */ var getAccessToken = function() { console.log("获取access_token"); var wxConf = JSON.parse(readWXConfig()); var APPID = wxConf.appid; var APPSECRET = wxConf.secret; var getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET; request.get(getAccessTokenUrl, function(err, response, body) { if (!err && response.statusCode == 200) { //成功 var accessToken = JSON.parse(body).access_token; wxConf.access_token = accessToken; console.log("access_token success!!!"); getJsapiTicket(wxConf, accessToken); } }); var timer = null; if (timer === null) { setTimeout(function() { clearTimeout(timer); timer = null; getAccessToken(); }, 10000) } } /** * 根据access_token获取签名所需要的jsapi_ticket * @param {[type]} access_token [description] * @return {[type]} [description] */ var getJsapiTicket = function(wxConf, accessToken) { console.log("获取jsapi_ticket"); var getTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi"; request.get(getTicketUrl, function(err, response, body) { wxConf.jsapi_ticket = JSON.parse(body).ticket; writeWXConfig(wxConf); }); } //sha1加密 function sha1(str) { var sha1 = crypto.createHash('sha1'); sha1.update(str); var sha1Str = sha1.digest("hex"); return sha1Str; } /** * 获取随机数 * @return {[type]} [description] */ var createNonceStr = function() { return Math.random().toString(36).substr(2, 15); }; /** * 获取时间戳 * @return {[type]} [description] */ var createTimestamp = function() { return parseInt(new Date().getTime() / 1000) + ''; }; var raw = function(args) { var keys = Object.keys(args); keys = keys.sort() var newArgs = {}; keys.forEach(function(key) { newArgs[key.toLowerCase()] = args[key]; }); var string = ''; for (var k in newArgs) { string += '&' + k + '=' + newArgs[k]; } string = string.substr(1); return string; }; /** * @synopsis 签名算法 * @param jsapi_ticket 用于签名的 jsapi_ticket * @param url 用于签名的 url ,注意必须动态获取,不能 hardcode * * @returns */ var sign = function(url) { var ret = { jsapi_ticket: JSON.parse(readWXConfig()).jsapi_ticket, nonceStr: createNonceStr(), timestamp: createTimestamp(), url: url }; var string = sha1(raw(ret)); ret.signature = string; ret.appid = JSON.parse(readWXConfig()).appid return ret; }; module.exports = { sha1: sha1, readWXConfig: readWXConfig, getAccessToken: getAccessToken, sign: sign };
var Promise = require('promise'); var zlib = require('zlib'); var http = require("https"); function stackExchange(args, fname){ return new Promise((resolve, reject) =>{ console.log("In StackExchange API, switch functionality now"); console.log(fname); var queryUrl = 'https://api.stackexchange.com/2.2/'; switch(fname){ case "advancedSearch": queryUrl = advancedSearch(args, queryUrl); break; case "questionID": queryUrl = questionID(args, queryUrl); break; } console.log(queryUrl); // buffer to store the streamed decompression var buffer = []; http.get(queryUrl, function (res) { // pipe the response into the gunzip to decompress var gunzip = zlib.createGunzip(); res.pipe(gunzip); gunzip.on('data', function (data) { // decompression chunk ready, add it to the buffer buffer.push(data.toString()) }).on("end", function () { // response and decompression complete, join the buffer and return console.log("send response data back"); var data = JSON.parse(buffer.join("")); resolve(data); }).on("error", function (e) { console.log("1.error"); reject(e); }) }).on('error', function (e) { console.log("2.error"); reject(e) }); }); } function advancedSearch(args, queryUrl){ queryUrl += "search/advanced?site=stackoverflow"; for(var key in args){ queryUrl += '&' + key + '=' + encodeURIComponent(args[key]); } console.log(queryUrl); return queryUrl } function questionID(args, queryUrl){ queryUrl += "questions/"+args.ids+"?site=stackoverflow"; for(var key in args){ if(key == "ids") continue; queryUrl += '&' + key + '=' + encodeURIComponent(args[key]); } console.log(queryUrl); return queryUrl } module.exports = { stackExchange }
{ switch (bundleType) { case NODE_DEV: case FB_DEV: case RN_DEV: return "\n})();\n}\n"; default: return ""; } }
window.Status = (function() { var loadersList = {}, registeredRefreshes = {}, refreshInteralMultiplier = 1; function registerRefresh(name, callback, interval, paused) { var refreshData = { name: name, func: callback, interval: interval, paused: paused // false on init almost always }; registeredRefreshes[name] = refreshData; refreshData.timer = setTimeout(function() { execRefresh(refreshData); }, refreshData.interval * refreshInteralMultiplier); } function setRefreshInterval(val) { if (val === 0) return; // don't do that console.log('Setting refresh speed to ' + (100/val).toFixed(0) + '% of normal.'); refreshInteralMultiplier = val; } function getRefresh(name) { return registeredRefreshes[name]; } function runRefresh(name) { console.log('Forcing a full refresh.'); pauseRefresh(name, true); resumeRefresh(name, true); } function scheduleRefresh(ms) { return setTimeout(runRefresh, ms); } function execRefresh(refreshData) { if (refreshData.paused) { return; } var def = refreshData.func(); if (typeof (def.done) === 'function') { def.done(function() { refreshData.timer = setTimeout(function() { execRefresh(refreshData); }, refreshData.interval * refreshInteralMultiplier); }); } refreshData.running = def; refreshData.timer = 0; } function pauseRefresh(name, silent) { function pauseSingleRefresh(r) { r.paused = true; if (r.timer) { clearTimeout(r.timer); r.timer = 0; } if (r.running) { if (typeof (r.running.reject) === 'function') { r.running.reject(); } if (typeof (r.running.abort) === 'function') { r.running.abort(); } } } if (name && registeredRefreshes[name]) { if (!silent) { console.log('Refresh paused for: ' + name); } pauseSingleRefresh(registeredRefreshes[name]); return; } if (!silent) { console.log('Refresh paused'); } for (var key in registeredRefreshes) { if (registeredRefreshes.hasOwnProperty(key)) { pauseSingleRefresh(registeredRefreshes[key]); } } } function resumeRefresh(name, silent) { function resumeSingleRefresh(r) { if (r.timer) { clearTimeout(r.timer); } r.paused = false; execRefresh(r); } if (name && registeredRefreshes[name]) { if (!silent) { console.log('Refresh resumed for: ' + name); } resumeSingleRefresh(registeredRefreshes[name]); return; } if (!silent) { console.log('Refresh resumed'); } for (var key in registeredRefreshes) { if (registeredRefreshes.hasOwnProperty(key)) { resumeSingleRefresh(registeredRefreshes[key]); } } } var currentDialog = null, prevHash = null; function closePopup() { if (currentDialog) { var dialog = currentDialog; currentDialog = null; dialog.modal('hide'); } } function popup(url, data, options) { closePopup(); var hash = window.location.hash, dialog = currentDialog = bootbox.dialog({ message: '<div class="modal-loader js-summary-popup"></div>', title: 'Loading...', size: 'large', backdrop: true, buttons: options && options.buttons, onEscape: function () { } }); dialog.on('hide.bs.modal', function () { var l = window.location; if (hash === l.hash) { // Only clear when we aren't shifting hashes if ('pushState' in history) { history.pushState('', document.title, l.pathname + l.search); hashChangeHandler(); } else { l.hash = ''; } } if (options && options.onClose) { options.onClose.call(this); } }); dialog.on('hidden.bs.modal', function() { if ($('.bootbox').length) { $('body').addClass('modal-open'); } }); if (options && options.modalClass) { dialog.find('.modal-lg').removeClass('modal-lg').addClass(options.modalClass); } // TODO: refresh intervals via header $('.js-summary-popup') .appendWaveLoader() .load(Status.options.rootPath + url, data, function (responseText, textStatus, req) { if (textStatus === 'error') { $(this).closest('.modal-content').find('.modal-header .modal-title').addClass('text-warning').text('Error'); $(this).html('<div class="alert alert-warning"><h5>Error loading</h5><p class="error-stack">Status: ' + req.statusText + '\nCode: ' + req.status + '\nUrl: ' + url + '</p></div><p>Direct link: <a href="' + url + '">' + url + '</a></p>'); return; } var titleElem = $(this).findWithSelf('h4.modal-title'); if (titleElem) { $(this).closest('.modal-content').find('.modal-header .modal-title').replaceWith(titleElem); } if (options && options.onLoad) { options.onLoad.call(this); } }); return dialog; } function hashChangeHandler(firstLoad) { var hash = window.location.hash; if (!hash || hash.length > 1) { for (var h in loadersList) { if (loadersList.hasOwnProperty(h) && hash.indexOf(h) === 0) { var val = hash.replace(h, ''); loadersList[h](val, firstLoad, prevHash); } } } if (!hash) { closePopup(); } prevHash = hash; } function registerLoaders(loaders) { $.extend(loadersList, loaders); } $(window).on('hashchange', function () { hashChangeHandler(); }); $(function() { // individual sections add via Status.loaders.register(), delay running until after they're added on-load setTimeout(function () { hashChangeHandler(true); }, 1); }); function prepTableSorter() { $.tablesorter.addParser({ id: 'relativeDate', is: function() { return false; }, format: function(s, table, cell) { var date = $(cell).find('.js-relative-time').attr('title'); // e.g. 2011-03-31 01:57:59Z if (!date) return 0; var exp = /(\d{4})-(\d{1,2})-(\d{1,2})\W*(\d{1,2}):(\d{1,2}):(\d{1,2})Z/i.exec(date); return new Date(exp[1], exp[2], exp[3], exp[4], exp[5], exp[6], 0).getTime(); }, type: 'numeric' }); $.tablesorter.addParser({ id: 'commas', is: function() { return false; }, format: function(s) { return s.replace('$', '').replace(/,/g, ''); }, type: 'numeric' }); $.tablesorter.addParser({ id: 'dataVal', is: function() { return false; }, format: function(s, table, cell) { return $(cell).data('val') || 0; }, type: 'numeric' }); $.tablesorter.addParser({ id: 'cellText', is: function() { return false; }, format: function(s, table, cell) { return $(cell).text(); }, type: 'text' }); } function init(options) { Status.options = options; if (options.HeaderRefresh) { Status.refresh.register('TopBar', function() { return $.ajax(options.rootPath + 'top-refresh', { data: { tab: Status.options.Tab } }).done(function (html) { var resp = $(html); var tabs = $('.js-top-tabs', resp); if (tabs.length) { $('.js-top-tabs').replaceWith(tabs); } // TODO: Just replace issues completely if not expanded, otherwise skip when expanded var issuesList = $('.js-issues-button', resp); var curList = $('.js-issues-button'); if (issuesList.length) { // TODO: Fix replacement // Re-think what comes down here, plan for websockets var issueCount = issuesList.data('count'); // TODO: don't if hovering if (issueCount > 0) { if (!curList.children().length) { curList.replaceWith(issuesList.find('.issues-button').fadeIn().end()); } else { $('.issues-button').html($('.issues-button', issuesList).html()); $('.issues-dropdown').html($('.issues-dropdown', issuesList).html()); } } else { curList.fadeOut(function() { $(this).empty(); }); } } }).fail(Status.UI.ajaxError); }, Status.options.HeaderRefresh * 1000); } var resizeTimer, dropdownPause; $(window).resize(function() { clearTimeout(resizeTimer); resizeTimer = setTimeout(function() { $(this).trigger('resized'); }, 100); }); $(document).on('click', '.js-reload-link', function(e) { var data = { type: $(this).data('type'), key: $(this).data('uk'), guid: $(this).data('guid') }; if (!data.type && ($(this).attr('href') || '#') !== '#') return; e.preventDefault(); if (data.type && data.key) { // Node to refresh, do it if ($(this).hasClass('active')) return; var link = $(this).addClass('active'); link.find('.fa').addClass('fa-spin'); link.find('.js-text').text('Polling...'); Status.refresh.pause(); $.post(Status.options.rootPath + 'poll', data) .fail(function() { toastr.error('There was an error polling this node.', 'Polling', { positionClass: 'toast-top-right-spaced', timeOut: 5 * 1000 }); }).done(function () { if (link.closest('.js-refresh').length) { // TODO: Refresh only this section, not all others // Possibly pause refresh on refreshing sections via an upfront // .closest('.js-refresh').addClass() Status.refresh.resume(); } else { window.location.reload(true); } //link.removeClass('reloading') // .find('.js-text') // .text('Poll Now'); }); } else { window.location.reload(true); } }).on('click', '.js-poll-now', function () { var type = $(this).data('type'), key = $(this).data('key'); if ($(this).hasClass('disabled')) { return false; } if (type && key) { $(this).text('').prependWaveLoader().addClass('disabled'); $.ajax(Status.options.rootPath + 'poll', { data: { type: type, key: key, guid: $(this).data('id') } }).done(function () { var name = $(this).closest('.js-refresh[data-name]').data('name'); if (name) { Status.refresh.get('Dashboard').func(name); } else { window.location.reload(true); } }); } return false; }).on('click', '.js-dropdown-actions', function (e) { e.preventDefault(); e.stopPropagation(); var jThis = $(this); if (jThis.hasClass('open')) { jThis.removeClass('open'); resumeRefresh(); } else { $('.js-dropdown-actions.open').removeClass('open'); var ddSource = $('.js-haproxy-server-dropdown ul').clone(); jThis.append(ddSource); var actions = jThis.data('actions'); if (actions) { jThis.find('a[data-action]').each(function(_, i) { $(i).toggleClass('disabled', actions.indexOf($(i).data('action')) === -1); }); } jThis.addClass('open'); pauseRefresh(); } }).on('click', '.js-dropdown-actions a', function (e) { e.preventDefault(); }).on({ 'click': function() { $('.action-popup').remove(); $('.js-dropdown-actions.open').removeClass('open'); }, 'show': function() { setRefreshInterval(1); runRefresh(); }, 'hide': function() { setRefreshInterval(10); } }); prepTableSorter(); prettyPrint(); } return { init: init, popup: popup, loaders: { list: loadersList, register: registerLoaders }, graphCount: 0, refresh: { register: registerRefresh, pause: pauseRefresh, resume: resumeRefresh, get: getRefresh, run: runRefresh, registered: registeredRefreshes, schedule: scheduleRefresh } }; })(); Status.UI = (function () { function ajaxError(xhr, status, error, thing) { console.log(xhr, status, error, thing); } return { ajaxError: ajaxError }; })(); Status.Dashboard = (function () { function applyFilter(filter) { Status.Dashboard.options.filter = filter = (filter || '').toLowerCase(); if (!filter) { $('[data-search]').closest('tbody').andSelf().removeClass('hidden'); return; } $('[data-search]').each(function () { var show = $(this).data('search').indexOf(filter) > -1; $(this).toggleClass('hidden', !show); }); $('[data-search]').closest('tbody').each(function () { var show = $('td:visible', this).length; $(this).toggleClass('hidden', !show); }); // TODO: Look at children cases, e.g. search for a category where children don't match // Thoughts: they should include the category in their search strings and be covered } function init(options) { Status.Dashboard.options = options; Status.loaders.register({ '#/dashboard/graph/': function (val) { Status.popup('dashboard/graph/' + val); } }); if (options.refresh) { Status.refresh.register('Dashboard', function (filter) { return $.ajax(Status.Dashboard.options.refreshUrl || window.location.href, { data: $.extend({}, Status.Dashboard.options.refreshData), cache: false }).done(function (html) { var resp = $(html); var refreshGroups = resp.find('.js-refresh[data-name]').add(resp.filter('.js-refresh[data-name]')); $('.js-refresh[data-name]').each(function () { var name = $(this).data('name'), match = refreshGroups.filter('[data-name="' + name + '"]'); if (filter && name !== filter) { return; } if (!match.length) { console.log('Unable to find: ' + name + '.'); } else { $(this).replaceWith(match); } }); if (Status.Dashboard.options.filter) applyFilter(Status.Dashboard.options.filter); if (Status.Dashboard.options.afterRefresh) Status.Dashboard.options.afterRefresh(); }).fail(function () { console.log('Failed to refresh', this, arguments); }); }, Status.Dashboard.options.refresh * 1000); } $(document).on('keyup', '.js-filter', function () { applyFilter(this.value); }); if (Status.Dashboard.options.filter) $('.js-filter').keyup(); } return { init: init }; })(); Status.Dashboard.Server = (function () { function init(options) { Status.Dashboard.Server.options = options; Status.loaders.register({ '#/dashboard/summary/': function (val) { Status.popup('dashboard/node/summary/' + val, { node: Status.Dashboard.Server.options.node }); } }); $('.realtime-cpu').on('click', function () { var start = +$(this).parent().siblings('.total-cpu-percent').text().replace(' %',''); liveDashboard(start); return false; }); $('table.js-interfaces').tablesorter({ headers: { 1: { sorter: 'dataVal', sortInitialOrder: 'desc' }, 2: { sorter: 'dataVal', sortInitialOrder: 'desc' }, 3: { sorter: 'dataVal', sortInitialOrder: 'desc' }, 4: { sorter: 'dataVal', sortInitialOrder: 'desc' }, 5: { sorter: 'dataVal', sortInitialOrder: 'desc' } } }); } function liveDashboard(startValue) { if ($('#cpu-graph').length) return; var container = '<div id="cpu-graph"><div class="cpu-total"><div id="cpu-total-graph" class="chart" data-title="Total CPU Utilization"></div></div></div>', wrap = $(container).appendTo('.js-content'), liveGraph = $('#cpu-total-graph').lived3graph({ type: 'cpu', width: 'auto', height: 250, startValue: startValue, params: { node: Status.Dashboard.Server.options.node }, series: [{ name: 'total', label: 'CPU' }], max: 100, leftMargin: 30, areaTooltipFormat: function(value) { return '<span class="label">CPU: </span><b>' + (value || 0).toFixed(0) + '%</b>'; } }); wrap.modal({ overlayClose: true, onClose: function(dialog) { dialog.data.fadeOut('fast', function() { dialog.container.hide('fast', function() { $.modal.close(); liveGraph.stop(); $('#cpu-graph').remove(); }); }); } }); } return { init: init }; })(); Status.Elastic = (function () { function init(options) { Status.Elastic.options = options; Status.loaders.register({ '#/elastic/node/': function (val) { Status.popup('elastic/node/modal/' + val, { cluster: Status.Elastic.options.cluster, node: Status.Elastic.options.node }); }, '#/elastic/cluster/': function (val) { Status.popup('elastic/cluster/modal/' + val, { cluster: Status.Elastic.options.cluster, node: Status.Elastic.options.node }); }, '#/elastic/index/': function (val) { var parts = val.split('/'); var reqOptions = $.extend({}, options, { index: parts[0] }); Status.popup('elastic/index/modal/' + parts[1], reqOptions); } }); } return { init: init }; })(); Status.NodeSearch = (function () { function init(options) { Status.NodeSearch.options = options; var ac = $('.js-filter').on('click', function() { var val = $(this).val(); $(this).select().autocomplete('search', '').removeClass('icon').val(''); setTimeout(function() { var selected = $('.status-icon[data-host="' + val + '"]'); if (selected.length) { var top = selected.closest('li').addClass('ac_over').position().top; $('.ac_results ul').scrollTop(top); } }, 0); }); //.autocomplete(options.nodes, { // max: 500, // minChars: 0, // matchContains: true, // delay: 50, // inputClass: "autocomplete-input", // resultsClass: "autocomplete-results", // loadingClass: "autocomplete-loading", // formatItem: function (row) { // return '<span class="status-icon ' + row.sClass + ' icon" data-host="' + row.node + '">●</span> <span class="text-muted">' + row.category + ':</span> <span class="' + row.sClass + '">' + row.name + '</span>'; // }, // formatResult: function (row) { return row.node; }, // formatMatch: function (row) { return row.category + ': ' + row.node; } //}).result(function (e, data) { // $(this).addClass('left-icon ' + data.sClass).closest('form').submit(); //}).keydown(function (e) { // return e.keyCode !== 13; //}); var ai = ac.autocomplete({ minLength: 0, delay: 25, source: options.nodes, appendTo: ac.parent(), messages: { noResults: '', results: function () { } }, select: function (event, ui) { $(this).val(ui.item.value).closest('form').submit(); } }).autocomplete('instance'); ai._renderMenu = function (ul, items) { var that = this; $.each(items, function (index, item) { that._renderItemData(ul, item); }); $(ul).addClass('dropdown-menu navbar-list'); }; ai._renderItem = function(ul, item) { var html = '<span class="' + item.icon + '">●</span> ' + '<span class="text-muted">' + item.category + ':</span> ' + item.label; return $('<li>').data('data-value', item.value).append('<a>' + html + '</a>').appendTo(ul); }; $('.server-search').on('click', '.js-show-all-down', function () { $(this).siblings('.hidden').removeClass('hidden').end().remove(); }); $('.node-category-list').on('click', '.filters-current', function (e) { if (e.target.tagName !== 'INPUT') $('.filters, .filters-toggle').toggle(); }).on('keyup', '.filter-form', function (e) { if (e.keyCode === 13) { $(this).submit(); $('.filters').hide(); $('.filters-current').addClass('loading'); } }); } return { init: init }; })(); Status.SQL = (function () { function loadCluster(val) { var pieces = val.split('/'); Status.Dashboard.options.refreshData = { cluster: pieces.length > 0 ? pieces[0] : null, ag: pieces.length > 1 ? pieces[1] : null, node: pieces.length > 2 ? pieces[2] : null }; Status.popup('sql/servers', $.extend({}, Status.Dashboard.options.refreshData, { detailOnly: true })); } function loadPlan(val) { var parts = val.split('/'), handle = parts[0], offset = parts.length > 1 ? parts[1] : null; $('.plan-row[data-plan-handle="' + handle + '"]').addClass('info'); Status.popup('sql/top/detail', { node: Status.SQL.options.node, handle: handle, offset: offset }, { onLoad: function() { $(this).closest('.modal-lg').removeClass('modal-lg').addClass('modal-huge'); prettyPrint(); $('.qp-root').drawQueryPlanLines(); var currentTt; $(this).find('.qp-node').hover(function() { var pos = $(this).offset(); var tt = $(this).find('.qp-tt'); currentTt = tt.clone(); currentTt.addClass('sql-query-tooltip') .appendTo(document.body) .css({ top: pos.top + $(this).outerHeight(), left: pos.left }) .show(); }, function() { if (currentTt) currentTt.hide(); }); $(this).find('.js-remove-plan').on('click', function() { if ($(this).hasClass('js-confirm')) { $(this).text('confirm?').removeClass('js-confirm'); return false; } var $link = $(this).addClass('loading'); $.ajax($link.attr('href'), { type: 'POST', success: function(data, status, xhr) { if (data === true) { window.location.hash = ''; window.location.reload(true); } else { $link.removeClass('loading').errorPopupFromJSON(xhr, 'An error occurred removing this plan from cache.'); } }, error: function(xhr) { $link.removeClass('loading').errorPopupFromJSON(xhr, 'An error occurred removing this plan from cache.'); } }); return false; }); $(this).find('.show-toggle').on('click', function(e) { var grad = $(this).closest('.hide-gradient'), excerpt = grad.prev('.sql-query-excerpt'); excerpt.animate({ 'max-height': excerpt[0].scrollHeight }, 400, function() { $(window).resize(); }); grad.fadeOut(400); e.preventDefault(); }); }, onClose: function() { $('.plan-row.selected').removeClass('info'); } }); } function init(options) { Status.SQL.options = options; var filterOptions = { modalClass: 'modal-md', buttons: { "Apply Filters": function (e) { $(this).find('form').submit(); return false; } } } Status.loaders.register({ '#/cluster/': loadCluster, '#/plan/': loadPlan, '#/sql/summary/': function (val) { Status.popup('sql/instance/summary/' + val, { node: Status.SQL.options.node }, { modalClass: val === 'errors' ? 'modal-huge' : 'modal-lg' }); }, '#/sql/top/filters': function () { Status.popup('sql/top/filters' + window.location.search, null, filterOptions); }, '#/sql/active/filters': function () { Status.popup('sql/active/filters' + window.location.search, null, filterOptions); }, '#/db/': function (val, firstLoad, prev) { var obj = val.indexOf('tables/') > 0 || val.indexOf('views/') || val.indexOf('storedprocedures/') > 0 ? val.split('/').pop() : null; function showColumns() { $('.js-next-collapsible').removeClass('info').next().hide(); var cell = $('[data-obj="' + obj + '"]').addClass('info').next().show(200).find('td'); if (cell.length === 1) { cell.css('max-width', cell.closest('.js-database-modal-right').width()); } } if (!firstLoad) { // TODO: Generalize this to not need the replace? Possibly a root load in the modal if ((/\/tables/.test(val) && /\/tables/.test(prev)) || (/\/views/.test(val) && /\/views/.test(prev)) || (/\/storedprocedures/.test(val) && /\/storedprocedures/.test(prev))) { showColumns(); return; } } Status.popup('sql/db/' + val, { node: Status.SQL.options.node }, { modalClass: 'modal-huge', onLoad: function () { showColumns(); } }); } }); $('.js-content').on('click', '.plan-row[data-plan-handle]', function () { var $this = $(this), handle = $this.data('plan-handle'), offset = $this.data('offset'); if (!handle) return; window.location.hash = '#/plan/' + handle + (offset ? '/' + offset : ''); $('.plan-row.selected').removeClass('selected'); $this.addClass('selected').find('.query-col').addClass('loading'); }).on('click', '.filters-current', function () { $('.filters').fadeToggle(); }).on('keyup', '.filter-form', function (e) { if (e.keyCode === 13) { $(this).submit(); $('.filters').hide(); $('.filters-current').addClass('loading'); } }).on('click', '.filters, .filters-current', function (e) { e.stopPropagation(); }); function agentAction(link, route, errMessage) { var origText = link.text(); var $link = link.text('').prependWaveLoader(); $.ajax(Status.options.rootPath + 'sql/' + route, { type: 'POST', data: { node: Status.SQL.options.node, guid: link.closest('[data-guid]').data('guid'), enable: link.data('enable') }, success: function (data, status, xhr) { if (data === true) { Status.popup('sql/instance/summary/jobs', { node: Status.SQL.options.node }); } else { $link.text(origText).errorPopupFromJSON(xhr, errMessage); } }, error: function (xhr) { $link.text(origText).errorPopupFromJSON(xhr, errMessage); } }); return false; } $(document).on('click', function () { $('.filters').toggle(false); }).on('click', '.js-sql-job-action', function () { var link = $(this); switch (link.data('action')) { case 'toggle': return agentAction($(this), 'toggle-agent-job', 'An error occurred toggling this job.'); case 'start': return agentAction($(this), 'start-agent-job', 'An error occurred starting this job.'); case 'stop': return agentAction($(this), 'stop-agent-job', 'An error occurred stopping this job.'); } return false; }).on('click', '.ag-node', function() { window.location.hash = $('.ag-node-name a', this)[0].hash; }).on('click', '.js-next-collapsible', function () { window.location.hash = window.location.hash.replace(/\/tables\/.*/, '/tables').replace(/\/views\/.*/, '/views').replace(/\/storedprocedures\/.*/, '/storedprocedures'); }); } return { init: init }; })(); Status.Redis = (function () { function init(options) { Status.Redis.options = options; Status.loaders.register({ '#/redis/summary/': function(val) { Status.popup('redis/instance/summary/' + val, { node: Status.Redis.options.node + ':' + Status.Redis.options.port }); }, '#/redis/actions/': function (val) { Status.popup('redis/instance/actions/' + val); } }); function runAction(link, options) { var action = $(link).data('action'), node = $(link).closest('.js-redis-actions').data('node'), confirmMessage = options && options.confirmMessage || $(link).data('confirm'); function innerRun() { $.post('redis/instance/actions/' + node + '/' + action, options && options.data) .done(options && options.onComplete || function () { Status.refresh.run(); bootbox.hideAll(); }); } if (confirmMessage) { bootbox.confirm(confirmMessage, function (result) { if (result) { innerRun(); } }); } else { innerRun(); } } $(document).on('change', '.js-redis-role-new-master', function () { $('button.js-redis-role-slave').prop('disabled', this.value.length === 0); }).on('click', '.js-instance-action', function (e) { e.preventDefault(); runAction(this); }).on('click', '.js-redis-role-slave', function (e) { var modal = $(this).closest('.js-redis-actions'), node = modal.data('node'), newMaster = $('[name=newMaster]', modal).val(); e.preventDefault(); runAction(this, { confirmMessage: 'Are you sure you want make ' + node + ' a slave of ' + newMaster + '?', data: { newMaster: newMaster } }); }).on('click', '.js-redis-key-purge', function (e) { var modal = $(this).closest('.js-redis-actions'), key = $('[name=key]', modal).val(); e.preventDefault(); runAction(this, { data: { db: $('[name=database]', modal).val(), key: key }, onComplete: function (result) { bootbox.alert(result ? 'Keys removed: ' + result.removed : 'Error removing keys'); } }); }); } return { init: init }; })(); Status.Exceptions = (function () { function refreshCounts(data) { if (!(data.Groups && data.Groups.length)) return; var log = Status.Exceptions.options.log, logCount = 0, group = Status.Exceptions.options.group, groupCount = 0; // For any not found... $('.js-exception-total').text('0'); data.Groups.forEach(function(g) { if (g.Name === group) { groupCount = g.Total; } $('.js-exception-total[data-name="' + g.Name + '"]').text(g.Total.toLocaleString()); g.Applications.forEach(function(app) { if (app.Name === log) { logCount = app.Total; } $('.js-exception-total[data-name="' + g.Name + '-' + app.Name + '"]').text(app.Total.toLocaleString()); }); }); if (Status.Exceptions.options.search) return; function setTitle(name, count) { $('.js-exception-title').html(count.toLocaleString() + ' ' + name + ' Exception' + (count !== 1 ? 's' : '')); } if (log) { setTitle(log, logCount); } else if (group) { setTitle(group, groupCount); } else { setTitle('', data.Total); } $('.js-top-tabs .badge[data-name="Exceptions"]').text(data.Total.toLocaleString()); } function init(options) { Status.Exceptions.options = options; // TODO: Set refresh params function getLoadCount() { // If scrolled back to the top, load 500 if ($(window).scrollTop() === 0) { return 500; } return Math.max($('.js-exceptions tbody tr').length, 500); } if (options.refresh) { Status.Dashboard.init({ refresh: Status.Exceptions.options.refresh }); } var loadingMore = false, allDone = false, lastSelected; function loadMore() { if (loadingMore || allDone) return; if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) { loadingMore = true; $('.js-bottom-loader').show(); var lastGuid = $('.js-exceptions tr.js-error').last().data('id'); $.ajax(Status.options.rootPath + 'exceptions/load-more', { data: { log: options.log, sort: options.sort, count: options.loadMore, prevLast: lastGuid }, cache: false }).done(function (html) { var newRows = $(html).filter('tr'); $('.js-exceptions tbody').append(newRows); $('.js-bottom-loader').hide(); if (newRows.length < options.loadMore) { allDone = true; $('.js-bottom-no-more').fadeIn(); } loadingMore = false; }); } } if (options.loadMore) { allDone = $('.js-exceptions tbody tr.js-error').length < 250; $(document).on('scroll exception-deleted', loadMore); } function deleteError(elem) { var jThis = $(elem), url = jThis.attr('href'), jRow = jThis.closest('tr'), jCell = jThis.closest('td'); $(elem).addClass('icon-rotate-flip'); if (!options.showingDeleted) { jRow.hide(); } $.ajax({ type: 'POST', data: { log: jRow.data('log') || options.log, id: jRow.data('id') }, url: url, success: function (data) { if (options.showingDeleted) { jThis.attr('title', 'Error is already deleted').addClass('disabled'); jRow.addClass('deleted'); // TODO: Replace protected glyph here //jCell.find('span.protected').replaceWith('<a title="Undelete and protect this error" class="protect-link" href="' + url.replace('/delete', '/protect') + '">&nbsp;P&nbsp;</a>'); } else { var table = jRow.closest('table'); if (!jRow.siblings().length) { $('.clear-all-div').remove(); $('.no-content').fadeIn('fast'); } jRow.remove(); table.trigger('update', [true]); refreshCounts(data); $(document).trigger('exception-deleted'); } }, error: function (xhr) { jThis.attr('href', url); jRow.show(); jCell.removeClass('loading').errorPopupFromJSON(xhr, 'An error occurred deleting'); }, complete: function () { jThis.removeClass('icon-rotate-flip'); } }); } // ajax the error deletion on the list page $(document).on('click', '.js-exceptions a.js-delete-link', function (e) { var jThis = $(this); // if we're already deleted, bomb out early if (jThis.closest('.js-error.js-deleted').length) return false; // if we've "protected" this error, confirm the deletion if (jThis.closest('tr.js-protected').length && !e.ctrlKey) { bootbox.confirm('Really delete this protected error?', function (result) { if (result) { deleteError(jThis[0]); } }); return false; } deleteError(this); return false; }); // ajax the protection on the list page $('.js-content').on('click', '.js-exceptions a.js-protect-link', function () { var url = $(this).attr('href'), jRow = $(this).closest('tr'), jCell = $(this).closest('td'); $(this).addClass('icon-rotate-flip'); $.ajax({ type: 'POST', data: { log: jRow.data('log') || options.log, id: jRow.data('id') }, context: this, url: url, success: function (data) { $(this).siblings('.js-delete-link').attr('title', 'Delete this error') .end() .replaceWith('<span class="js-protected fa fa-lock fa-fw text-primary" title="This error is protected"></span>'); jRow.addClass('js-protected protected').removeClass('deleted'); refreshCounts(data); }, error: function (xhr) { $(this).attr('href', url).addClass('hover-pulsate'); jCell.errorPopupFromJSON(xhr, 'An error occurred protecting'); }, complete: function () { $(this).removeClass('icon-rotate-flip'); } }); return false; }).on('click', '.js-exceptions tbody td', function (e) { if ($(e.target).closest('a').length) { return; } var row = $(this).closest('tr'); row.toggleClass('active warning'); if (e.shiftKey) { var index = row.index(), lastIndex = lastSelected.index(); if (!e.ctrlKey) { row.siblings().andSelf().removeClass('active warning'); } row.parent() .children() .slice(Math.min(index, lastIndex), Math.max(index, lastIndex)).add(lastSelected).add(row) .addClass('active warning'); if (!e.ctrlKey) { lastSelected = row.first(); } // TODO: Improve, possibly with a before/after unselectable style application window.getSelection().removeAllRanges(); } else if (e.ctrlKey) { lastSelected = row.first(); } else { if ($('.js-exceptions tbody td').length > 2) { row.addClass('active warning'); } row.siblings().removeClass('active warning'); lastSelected = row.first(); } }); $(document).keydown(function(e) { if (e.keyCode === 46 || e.keyCode === 8) { var selected = $('.js-error.active').not('.js-protected'); if (selected.length > 0) { var ids = selected.map(function () { return $(this).data('id'); }).get(); selected.find('.js-delete-link').addClass('icon-rotate-flip'); if (!options.showingDeleted) { selected.hide(); } $.ajax({ type: 'POST', context: this, traditional: true, data: { ids: ids, returnCounts: true }, url: Status.options.rootPath + 'exceptions/delete-list', success: function (data) { var table = selected.closest('table'); selected.remove(); table.trigger('update', [true]); refreshCounts(data); }, error: function (xhr) { if (!options.showingDeleted) { selected.show(); } selected.find('.js-delete-link').removeClass('icon-rotate-flip'); selected.last().children().first().errorPopupFromJSON(xhr, 'An error occurred clearing selected exceptions'); } }); return false; } } return true; }); $(document).on('click', 'a.js-clear-all', function () { var jThis = $(this), id = jThis.data('id') || options.id; bootbox.confirm('Really delete all non-protected errors' + (id ? ' like this one' : '') + '?', function(result) { if (result) { jThis.find('.fa').addClass('icon-rotate-flip'); $.ajax({ type: 'POST', data: { group: jThis.data('group') || options.group, log: jThis.data('log') || options.log, id: jThis.data('id') || options.id }, url: jThis.data('url'), success: function(data) { window.location.href = data.url; }, error: function(xhr) { jThis.find('.fa').removeClass('icon-rotate-flip'); jThis.parent().errorPopupFromJSON(xhr, 'An error occurred clearing this log'); } }); } }); return false; }); $(document).on('click', 'a.js-clear-visible', function () { var jThis = $(this); bootbox.confirm('Really delete all visible, non-protected errors?', function (result) { if (result) { var ids = $('.js-error:not(.protected,.deleted)').map(function () { return $(this).data('id'); }).get(); jThis.find('.fa').addClass('icon-rotate-flip'); $.ajax({ type: 'POST', traditional: true, data: { group: options.group, log: options.log, ids: ids }, url: jThis.data('url'), success: function (data) { window.location.href = data.url; }, error: function (xhr) { jThis.find('.fa').removeClass('icon-rotate-flip'); jThis.parent().errorPopupFromJSON(xhr, 'An error occurred clearing visible exceptions'); } }); } }); return false; }); $.tablesorter.addParser({ id: 'errorCount', is: function () { return false; }, format: function (s, table, cell) { var count = $(cell).data('count'); // e.g. 2011-03-31 01:57:59Z if (!count) return 0; return parseInt(count, 10); }, type: 'numeric' }); /* Error previews */ if (options.enablePreviews) { var previewTimer = 0; $('.js-content').on({ mouseenter: function (e) { if ($(e.target).closest('.js-error td:nth-child(4)').length) { var jThis = $(this).find('.js-exception-link'), url = jThis.attr('href').replace('/detail', '/preview'); clearTimeout(previewTimer); previewTimer = setTimeout(function() { $.get(url, function(resp) { var sane = $(resp).filter('.error-preview'); if (!sane.length) return; $('.error-preview-popup').fadeOut(125, function() { $(this).remove(); }); var errDiv = $('<div class="error-preview-popup" />').append(resp); errDiv.appendTo(jThis.parent()).fadeIn('fast'); }); }, 600); } }, mouseleave: function () { clearTimeout(previewTimer); $('.error-preview-popup', this).fadeOut(125, function () { $(this).remove(); }); } }, '.js-exceptions tbody tr'); } /* Error detail handlers*/ $('.info-delete-link a').on('click', function () { $(this).addClass('loading'); $.ajax({ type: 'POST', data: { id: options.id, log: options.log, redirect: true }, context: this, url: Status.options.rootPath + 'exceptions/delete', success: function (data) { window.location.href = data.url; }, error: function () { $(this).removeClass('loading').parent().errorPopup('An error occured while trying to delete this error (yes, irony).'); } }); return false; }); /* Jira action handlers*/ $('.info-jira-action-link a').on('click', function () { $(this).addClass('loading'); var actionid = $(this).data("actionid"); $.ajax({ type: 'POST', data: { id: options.id, log: options.log, actionid: actionid }, context: this, url: Status.options.rootPath + 'exceptions/jiraaction', success: function (data) { $(this).removeClass('loading'); if (data.success) { if (data.browseUrl && data.browseUrl !== "") { var issueLink = '<a href="' + data.browseUrl + '" target="_blank">' + data.issueKey + '</a>'; $("#jira-links-container").show(); $("#jira-links-container").append('<span> ( ' + issueLink + ' ) </span>'); toastr.success('<div style="margin-top:5px">' + issueLink + '</div>', 'Issue Created'); } else { toastr.success("Issue created : " + data.issueKey, 'Success'); } } else { toastr.error(data.message, 'Error'); } }, error: function () { $(this).removeClass('loading').parent().errorPopup('An error occured while trying to perform the selected Jira issue action.'); } }); return false; }); } return { init: init }; })(); Status.HAProxy = (function () { function init(options) { Status.HAProxy.options = options; if (options.refresh) { Status.Dashboard.init({ refresh: Status.HAProxy.options.refresh }); } // Admin Panel (security is server-side) $('.js-content').on('click', '.js-haproxy-action, .js-haproxy-actions a', function (e) { var jThis = $(this), data = { group: jThis.closest('[data-group]').data('group'), proxy: jThis.closest('[data-proxy]').data('proxy'), server: jThis.closest('[data-server]').data('server'), act: jThis.data('action') }; function haproxyAction() { jThis.find('.fa').addBack('.fa').addClass('icon-rotate-flip'); var cog = jThis.closest('.js-dropdown-actions').find('.hover-spin > .fa').addClass('spin'); $.ajax({ type: 'POST', data: data, url: Status.options.rootPath + 'haproxy/admin/action', success: function () { Status.refresh.run(); }, error: function () { jThis.removeClass('icon-rotate-flip').parent().errorPopup('An error occured while trying to ' + data.act + '.'); cog.removeClass('spin'); } }); } function confirmAction(message) { bootbox.confirm(message, function (result) { if (result) { haproxyAction(); } }); return false; } if (jThis.hasClass('disabled')) return false; // We're at the Tier level if (data.group && !data.proxy && !data.server) { return confirmAction('Are you sure you want to ' + data.act.toLowerCase() + ' every server in <b>' + data.group + '</b>?'); } // We're at the Server level if (!e.ctrlKey && !data.group && !data.proxy && data.server) { return confirmAction('Are you sure you want to ' + data.act.toLowerCase() + ' <b>' + data.server + '</b> from all backends?'); } // We're at the Proxy level if (!e.ctrlKey && data.group && data.proxy && !data.server) { return confirmAction('Are you sure you want to ' + data.act.toLowerCase() + ' all of <b>' + data.proxy + '</b>?'); } haproxyAction(); return false; }); } return { init: init }; })(); (function () { function bytesToSize(bytes, large, zeroLabel) { var sizes = large ? ['Bytes', 'KB', 'MB', 'GB', 'TB'] : ['bytes', 'kb', 'mb', 'gb', 'tb']; if (bytes === 0) return '0 ' + (zeroLabel || sizes[0]); var ubytes = Math.abs(bytes); var i = parseInt(Math.floor(Math.log(ubytes) / Math.log(1024))); var dec = (ubytes / Math.pow(1024, i)).toFixed(1).replace('.0', ''); return dec + ' ' + sizes[i]; } function commify(num) { return (num + '').replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); } function getExtremes(array, series, min, max, stacked) { if (max === 'auto' || min === 'auto') { var maximums = { up: 0, down: 0 }; if (stacked) { min = 0; max = d3.max(array, function (p) { return d3.sum(series, function (s) { return p[s.name]; }); }); } else { series.forEach(function (s) { var direction = s.direction || 'up'; maximums[direction] = Math.max(maximums[direction] || 0, d3.max(array, function (ss) { return ss[s.name]; })); }); } min = min === 'auto' ? -maximums.down : min; max = max === 'auto' ? maximums.up : max; } return [min, max]; } // Open specific methods for access Status.helpers = { bytesToSize: bytesToSize, commify: commify }; var chartFunctions = { tooltipTimeFormat: d3.time.format.utc('%A, %b %d %H:%M') }; var waveHtml = '<div class="sk-wave loader"><div></div><div></div><div></div><div></div><div></div></div>'; // Creating jQuery plguins... $.fn.extend({ findWithSelf: function (selector) { return this.find(selector).andSelf().filter(selector); }, appendWaveLoader: function () { return this.append(waveHtml); }, prependWaveLoader: function () { return this.prepend(waveHtml); }, appendError: function(title, message) { return this.append('<div class="alert alert-warning"><h5>' + title + '</h5><p>' + message + '</p></div>'); }, prependError: function (title, message) { return this.prepend('<div class="alert alert-warning"><h5>' + title + '</h5><p>' + message + '</p></div>'); }, inlinePopup: function (className, msg, callback, removeTimeout, clickDismiss) { $('.' + className).remove(); var jDiv = $('<div class="' + className + '">' + msg + '</div>').appendTo(this); jDiv.fadeIn('fast'); var remove = function () { jDiv.fadeOut('fast', function () { $(this).remove(); }); if (callback) callback(); }; if (clickDismiss) { jDiv.on('click', remove); } if (removeTimeout) { setTimeout(remove, removeTimeout); } return this; }, actionPopup: function (msg, callback) { return this.inlinePopup('action-popup', msg, callback); }, errorPopup: function (msg, callback) { return this.inlinePopup('error-popup', msg, callback, 15000, true); }, errorPopupFromJSON: function (xhr, defaultMsg) { var msg = defaultMsg; if ((xhr && xhr.getResponseHeader('content-type') || '').indexOf('json') > -1) { var json = JSON.parse(xhr.responseText); if (json && json.ErrorMessage) { msg = json.ErrorMessage; } } return this.errorPopup(msg); }, cpuGraph: function (options) { return this.d3graph({ type: 'cpu', series: [{ name: 'value', label: 'CPU' }], yAxis: { tickLines: true, tickFormat: function (d) { return d + '%'; } }, max: 100, leftMargin: 40, areaTooltipFormat: function (value) { return '<span>CPU: </span><b>' + value.toFixed(2) + '%</b>'; } }, options); }, memoryGraph: function (options) { return this.d3graph({ type: 'memory', series: [{ name: 'value', label: 'Memory' }], yAxis: { tickLines: true, tickFormat: function (d) { return Status.helpers.bytesToSize(d * 1024 * 1024, true, 'GB'); } }, leftMargin: 60, max: this.data('max'), areaTooltipFormat: function (value) { return '<span>Memory: </span><b>' + Status.helpers.bytesToSize(value * 1024 * 1024, true) + '</b>'; } }, options); }, networkGraph: function (options) { return this.d3graph({ type: 'network', series: [ { name: 'main_in', label: 'In' }, { name: 'main_out', label: 'Out', direction: 'down' } ], min: 'auto', leftMargin: 60, areaTooltipFormat: function(value, series, name) { return '<span>Bandwidth (<span class="series-' + name + '">' + series + '</span>): </span><b>' + Status.helpers.bytesToSize(value, false) + '/s</b>'; }, yAxis: { tickFormat: function (d) { return Status.helpers.bytesToSize(d, false); } } }, options); }, haproxyGraph: function (options) { var comma = d3.format(','); return this.d3graph({ type: 'haproxy', subtype: 'traffic', ajaxZoom: false, series: [ { name: 'main_hits', label: 'Total' }, { name: 'main_pages', label: 'Pages' } ], min: 'auto', leftMargin: 80, areaTooltipFormat: function (value, series, name) { return '<span>Hits (<span class="series-' + name + '">' + series + '</span>): </span><b>' + comma(value) + '</b>'; }, yAxis: { tickFormat: comma } }, options); }, haproxyRouteGraph: function (route, days, host, options) { return this.d3graph({ type: 'haproxy', subtype: 'route-performance', ajaxZoom: false, stacked: true, subtitle: route, interpolation: 'linear', dateRanges: false, params: { route: route, days: days, host: host }, autoColors: true, series: [ { name: 'dot_net', label: 'ASP.Net', color: '#0E2A4C' }, { name: 'sql', label: 'SQL', color: '#143D65' }, { name: 'redis', label: 'Redis', color: '#194D79' }, { name: 'http', label: 'HTTP', color: '#1D5989' }, { name: 'tag_engine', label: 'Tag Engine', color: '#206396' }, { name: 'other', label: 'Other', color: '#64B6D0' } ], rightSeries: [ { name: 'hits', label: 'Hits', color: 'rgb(116, 196, 118)', width: 2 } ], rightMargin: 70, min: 'auto', leftMargin: 60, // TODO: Style except for BG color in .less rightAreaTooltipFormat: function (value, series, name, color) { return '<label>' + (color ? '<div style="background-color: ' + color + '; width: 16px; height: 13px; display: inline-block;"></div> ' : '') + '<span class="series-' + name + '">' + series + '</span>: </label><b>' + Status.helpers.commify(value) + '</b>'; }, areaTooltipFormat: function (value, series, name, color) { return '<label>' + (color ? '<div style="background-color: ' + color + '; width: 16px; height: 13px; display: inline-block;"></div> ' : '') + '<span class="series-' + name + '">' + series + '</span>: </label><b>' + Status.helpers.commify(value) + ' <span class="text-muted">ms</span></b>'; }, yAxis: { tickFormat: function (d) { return Status.helpers.commify(d) + ' ms'; } } }, options); }, d3graph: function (options, addOptions) { var defaults = { series: [{ name: 'value', label: 'Main' }], ajaxZoom: true, stacked: false, autoColors: false, dateRanges: true, interpolation: 'linear', leftMargin: 40, live: false, id: this.data('id'), title: this.data('title'), subtitle: this.data('subtitle'), start: this.data('start'), end: this.data('end'), width: 'auto', height: 'auto', max: 'auto', min: 0 }; options = $.extend(true, {}, defaults, options, addOptions); this.addClass('chart'); var minDate, maxDate, topBrushArea, bottomBrushArea, dataLoaded, curWidth, curHeight, curData, chart = this, buildTooltip = $('<div class="build-tooltip chart-tooltip small" />').appendTo(chart), areaTooltip = $('<div class="area-tooltip chart-tooltip small" />').appendTo(chart), series = options.series, rightSeries = options.rightSeries, leftPalette = options.autoColors === true ? options.leftPalette || 'PuBu' : (options.autoColors || null), rightPalette = options.autoColors === true ? options.rightPalette || 'Greens' : (options.rightPalette || options.autoColors || null), margin, margin2, width, height, height2, x, x2, y, yr, y2, xAxis, xAxis2, yAxis, yrAxis, brush, brush2, clipId = 'clip' + Status.graphCount++, gradientId = 'gradient-' + Status.graphCount, svg, focus, context, clip, currentArea, refreshTimer, urlPath = Status.options.rootPath + 'graph/' + options.type + (options.subtype ? '/' + options.subtype : '') + '/json', params = { summary: true }, stack, stackArea, stackSummaryArea, stackFunc; // stacked specific vars if (options.id) params.id = options.id; if (options.iid) params.iid = options.iid; if (options.start) params.start = (new Date(options.start).getTime() / 1000).toFixed(0); if (options.end) params.end = (new Date(options.end).getTime() / 1000).toFixed(0); $.extend(params, options.params); options.width = options.width === 'auto' ? (chart.width() - 10) : options.width; options.height = options.height === 'auto' ? (chart.height() - 5) : options.height; if (options.title) { var titleDiv = $('<div class="chart-title"/>').text(options.title).prependTo(chart); if (options.subtitle) { $('<div class="chart-subtitle"/>').text(options.subtitle).appendTo(titleDiv); } } function drawElements() { if (options.width - 10 - options.leftMargin < 300) options.width = 300 + 10 + options.leftMargin; margin = { top: 10, right: options.rightMargin || 10, bottom: options.live ? 25 : 100, left: options.leftMargin }; width = options.width - margin.left - margin.right; height = options.height - margin.top - margin.bottom; var timeFormats = d3.time.format.utc.multi([ ['.%L', function (d) { return d.getUTCMilliseconds(); }], [':%S', function (d) { return d.getUTCSeconds(); }], ['%H:%M', function (d) { return d.getUTCMinutes(); }], ['%H:%M', function (d) { return d.getUTCHours(); }], ['%a %d', function (d) { return d.getUTCDay() && d.getUTCDate() !== 1; }], ['%b %d', function (d) { return d.getUTCDate() !== 1; }], ['%B', function (d) { return d.getUTCMonth(); }], ['%Y', function () { return true; }] ]); x = d3.time.scale.utc().range([0, width]); y = d3.scale.linear().range([height, 0]); yr = d3.scale.linear().range([height, 0]); xAxis = d3.svg.axis().scale(x).orient('bottom').tickFormat(timeFormats); yAxis = d3.svg.axis().scale(y).orient('left'); yrAxis = d3.svg.axis().scale(yr).orient('right'); if (options.yAxis) { if (options.yAxis.tickFormat) { yAxis.tickFormat(options.yAxis.tickFormat); } if (options.yAxis.tickSize) { yAxis.tickSize(options.yAxis.tickSize); } if (options.yAxis.tickLines) { yAxis.tickSize(-width); } } brush = d3.svg.brush() .x(x) .on('brushend', redrawFromMain); svg = d3.select(chart[0]).append('svg') .attr('width', options.width) .attr('height', options.height); clip = svg.append('defs').append('clipPath') .attr('id', clipId) .append('rect') .attr('width', width) .attr('height', height); focus = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); if (!options.live) { // Summary elements margin2 = { top: options.height - 77, right: 10, bottom: 20, left: options.leftMargin }; height2 = options.height - margin2.top - margin2.bottom; x2 = d3.time.scale.utc().range([0, width]); y2 = d3.scale.linear().range([height2, 0]); xAxis2 = d3.svg.axis().scale(x2).orient('bottom').tickFormat(timeFormats); brush2 = d3.svg.brush() .x(x2) .on('brush', redrawFromSummary); context = svg.append('g').attr('transform', 'translate(' + margin2.left + ',' + margin2.top + ')'); } } function getClass(prefix, s) { return function (a) { return prefix + ' ' + ('series-' + (s || a).name) + ((s || a).cssClass ? ' ' + (s || a).cssClass : ''); }; } function getColor(pSeries, palette, inverse) { pSeries = pSeries || series; palette = palette || leftPalette; // TODO: Move this up, no need to re-run on hover if (!palette) return null; var colors = colorbrewer[palette]; if (!colors) return null; var cPalette = colors[pSeries.length < 3 ? 3 : pSeries.length > 9 ? 9 : pSeries.length]; return function (a, i) { return pSeries[i].color || cPalette[inverse ? cPalette.length - 1 - i : i]; }; } function drawPrimaryGraphs(data) { x.domain(options.ajaxZoom ? d3.extent(data.points.map(function (d) { return d.date; })) : [minDate, maxDate]); if (!options.live) { // Summary x2.domain(d3.extent(data.summary.map(function(d) { return d.date; }))); y2.domain(getExtremes(data.summary, series, options.min, options.max)); } rescaleYAxis(data, true); if (options.stacked) { stack = d3.layout.stack().values(function (d) { return d.values; }); stackArea = d3.svg.area() .interpolate(options.interpolation) .x(function(d) { return x(d.date); }) .y0(function(d) { return y(d.y0); }) .y1(function (d) { return y(d.y0 + d.y); }); if (!options.live) { // Summary stackSummaryArea = d3.svg.area() .x(function(d) { return x2(d.date); }) .y0(function(d) { return y2(d.y0); }) .y1(function(d) { return y2(d.y0 + d.y); }); } stackFunc = function(dataList) { return stack(series.map(function(s) { var result = { name: s.name, values: dataList.map(function (d) { return { date: d.date, y: d[s.name] }; }) }; if (s.cssClass) result.cssClass = s.cssClass; if (s.color) result.color = s.color; return result; })); }; focus.selectAll('.area') .data(stackFunc(data.points)) .enter() .append('path') .attr('class', getClass('area')) .attr('fill', getColor()) .attr('clip-path', 'url(#' + clipId + ')') .attr('d', function (d) { return stackArea(d.values); }); context.selectAll('.area') .data(stackFunc(data.summary)) .enter() .append('path') .attr('class', getClass('summary-area')) .attr('fill', getColor()) .attr('d', function (d) { return stackSummaryArea(d.values); }); } else { // draw a path for each series in the main graph series.forEach(function (s) { focus.append('path') .datum(data.points) .attr('class', getClass('area', s)) .attr('fill', options.colorStops ? 'url(#' + gradientId + ')' : getColor()) .attr('clip-path', 'url(#' + clipId + ')') .attr('d', s.area.y0(y(0))); if (!options.live) { // and the summary context.append('path') .datum(data.summary) .attr('class', getClass('summary-area', s)) .attr('fill', getColor()) .attr('d', s.summaryArea.y0(y2(0))); } }); } if (options.rightSeries) { rightSeries.forEach(function (s) { var line = focus.append('path') .datum(data.summary) .attr('class', getClass('line', s, series.length)) .attr('fill', 'none') .attr('stroke', getColor(rightSeries, rightPalette)) .attr('clip-path', 'url(#' + clipId + ')') .attr('d', s.line); if (s.width) { line.attr('stroke-width', s.width); } }); } // x-axis focus.append('g') .attr('class', 'x axis') .attr('transform', 'translate(0,' + height + ')') .call(xAxis); // y-axis focus.append('g') .attr('class', 'y axis') .call(yAxis); // right-hand y-axis if (rightSeries) { focus.append('g') .attr('class', 'yr axis') .attr('transform', 'translate(' + width + ', 0)') .call(yAxis); } rescaleYAxis(data, false); // current hover area currentArea = focus.append('g') .attr('class', 'current-area') .style('display', 'none'); // hover line currentArea.append('svg:line') .attr('x1', 0) .attr('x2', 0) .attr('y1', height + margin.top) .attr('y2', margin.top) .attr('class', 'area-tooltip-line'); // hover circle(s) if (options.stacked) { currentArea.selectAll('circle') .data(stackFunc(data.summary)) .enter() .append('circle') .attr('class', getClass('')) .attr('fill', getColor()) .attr('r', 4.5); } else { series.forEach(function (s) { currentArea.append('circle') .attr('class', getClass('', s)) .attr('fill', getColor()) .attr('r', 4.5); }); } if (rightSeries) { rightSeries.forEach(function (s) { currentArea.append('circle') .attr('class', getClass('', s)) .attr('fill', getColor()) .attr('r', 4.5); }); } // top selection brush, for main graph topBrushArea = focus.append('g') .attr('class', 'x brush') .on('mousemove', areaHover) .on('mouseover', areaEnter) .on('mouseout', areaLeave) .call(brush); topBrushArea.selectAll('rect') .attr('y', 0) .attr('height', height + 1); if (!options.live) { context.append('g') .attr('class', 'x axis') .attr('transform', 'translate(0,' + height2 + ')') .call(xAxis2); // bottom selection brush, for summary bottomBrushArea = context.append('g') .attr('class', 'x brush') .call(brush2); bottomBrushArea.selectAll('rect') .attr('y', -6) .attr('height', height2 + 7); } curWidth = chart.width(); curHeight = chart.height(); } function drawBuilds(data) { if (!data.builds) return; focus.append('svg:g') .attr('class', 'build-dots') .selectAll('scatter-dots') .data(data.builds) .enter().append('svg:circle') .attr('class', 'build-dot') .attr('cy', y(0)) .attr('cx', function (d) { return x(d.date); }) .attr('r', 6) .style('opacity', 0.6) .on('mouseover', function (d) { var pos = $(this).position(); buildTooltip.html('<span class="label">Build: </span>' + d.text) .css({ left: pos.left - (buildTooltip.width() / 2), top: pos.top + 25 }) .stop(true, true) .fadeIn(200); }) .on('mouseout', function () { buildTooltip.stop(true, true).fadeOut(200); }) .on('click', function () { window.open(data.link, '_blank'); }); } function clearBuilds() { focus.selectAll('.build-dots').remove(); focus.selectAll('.build-dot').remove(); } function prepSeries() { series.forEach(function (s) { var negative = s.direction === 'down'; s.area = d3.svg.area() .interpolate(options.interpolation) .x(function (d) { return x(d.date); }) .y1(function (d) { return y(negative ? -d[s.name] : d[s.name]); }); s.summaryArea = d3.svg.area() .interpolate(options.interpolation) .x(function (d) { return x2(d.date); }) .y1(function(d) { return y2(negative ? -d[s.name] : d[s.name]); }); }); if (rightSeries) { rightSeries.forEach(function (s) { var negative = s.direction === 'down'; s.line = d3.svg.line() .interpolate(options.interpolation) .x(function (d) { return x(d.date); }) .y(function (d) { return yr(negative ? -d[s.name] : d[s.name]); }); }); } } function rescaleYAxis(data, rescale) { if (rescale) { y.domain(getExtremes(data.points, series, options.min, options.max, options.stacked)); if (rightSeries) { yr.domain(getExtremes(data.points, rightSeries, 'auto', 'auto')); } } focus.select('g.y.axis') .call(yAxis) .selectAll('g.tick.major line') .attr('x1', width); if (rightSeries) { focus.select('g.yr.axis') .call(yrAxis) .selectAll('g.tick.major line') .attr('x1', width); } } function areaEnter() { if (curData && curData.points && curData.points.length) { currentArea.style('display', null); areaTooltip.show(); } } function areaLeave() { currentArea.style('display', 'none'); areaTooltip.hide(); } function areaHover() { // no data! what the hell are you trying to hover? if (!dataLoaded) return; var pos = d3.mouse(this), date = x.invert(pos[0]), bisector = d3.bisector(function(d) { return d.date; }).left, tooltip = '<div class="tooltip-date">' + chartFunctions.tooltipTimeFormat(date) + ' <span class="text-muted">UTC</span></div>', data = options.ajaxZoom ? curData.points : curData.summary, index = bisector(data, date, 1), // bisect the curData array to get the index of the hovered date dateBefore = data[Math.max(index - 1, 0)], // get the date before the hover dateAfter = data[Math.min(index, data.length - 1)], // and the date after d = dateBefore && date - dateBefore.date > dateAfter.date - date ? dateAfter : dateBefore, // pick the nearest through = dateBefore && (date.getTime() - dateBefore.date.getTime()) / (dateAfter.date.getTime() - dateBefore.date.getTime()), tooltipRows = []; if (!d) { currentArea.style('display', 'none'); return; } // align the moons! or at least the series hover dots var runningTotal = 0; if (rightSeries) { rightSeries.forEach(function (s, i) { var val = d[s.name] || 0, gc = getColor(rightSeries, rightPalette), fakeVal = options.interpolation === 'linear' ? d3.interpolate(dateBefore[s.name], dateAfter[s.name])(through) : val, cPos = (s.direction === 'down' ? -1 : 1) * fakeVal; tooltip += (options.rightAreaTooltipFormat || areaTooltipFormat)(val, s.label, s.name, gc ? gc(s, i) : null); currentArea.select('circle.series-' + s.name).attr('transform', 'translate(0, ' + yr(cPos) + ')'); }); } series.forEach(function (s, i) { var val = d[s.name] || 0, gc = getColor(), fakeVal = options.interpolation === 'linear' ? d3.interpolate(dateBefore[s.name], dateAfter[s.name])(through) : val; runningTotal += fakeVal; var cPos = (s.direction === 'down' ? -1 : 1) * (options.stacked ? runningTotal : fakeVal); tooltipRows.push(options.areaTooltipFormat(val, s.label, s.name, gc ? gc(s, i) : null)); currentArea.select('circle.series-' + s.name).attr('transform', 'translate(0, ' + y(cPos) + ')'); }); if (options.stacked) { tooltipRows.reverse(); } tooltip += tooltipRows.join(''); areaTooltip.html(tooltip) .css({ left: pos[0] + 80, top: pos[1] + 60 }); currentArea.attr('transform', 'translate(' + (pos[0]) + ', 0)'); } function onWindowResized() { var newWidth = chart.width(), newHeight = chart.height(); if (curWidth !== newWidth || curHeight !== newHeight) { options.width = curWidth = newWidth; curHeight = newHeight; if (dataLoaded) { //TODO: Chart re-use by resize, with transform svg.remove(); drawElements(); drawPrimaryGraphs(curData); drawBuilds(curData); } } } $(window).on('resize', onWindowResized); // lay it all out soon as possible drawElements(); function handleData(data) { postProcess(data); prepSeries(); drawPrimaryGraphs(data); drawBuilds(data); dataLoaded = true; chart.find('.loader').hide(); if (!options.live) { // set the initial summary brush to reflect what was loaded up top brush2.extent(x.domain())(bottomBrushArea); } if (options.showBuilds && !data.builds) { //$.getJSON(Status.options.rootPath + 'graph/builds/json', params, function (bData) { // postProcess(bData); // drawBuilds(bData); //}); } } if (options.data) { handleData(options.data); } else { $.getJSON(urlPath, params) .done(handleData) .fail(function () { chart.prependError('Error', 'Could not load graph'); }); } function postProcess(data) { function process(name) { if (data[name]) { data[name].forEach(function(d) { d.date = new Date(d.date * 1000); }); curData[name] = data[name]; } } if (!options.ajaxZoom && !data.points) data.points = data.summary; if (!curData) curData = {}; process('points'); process('summary'); process('builds'); if (data.summary) { if (data.summary.length >= 2) { minDate = data.summary[0].date; maxDate = data.summary[data.summary.length - 1].date; } } } function redrawFromMain() { var bounds = brush.empty() ? x.domain() : brush.extent(); brush.clear()(topBrushArea); brush2.extent(bounds)(bottomBrushArea); redrawMain(bounds, 1); } function redrawFromSummary() { redrawMain(brush2.empty() ? x2.domain() : brush2.extent()); } function redrawMain(newBounds, timerDelay) { var start = Math.round(newBounds[0] / 1000), end = Math.round(newBounds[1] / 1000); // load low-res summary view quickly if (options.ajaxZoom) { if (options.stacked) { focus.selectAll('.area') .datum(curData.summary); } else { //TODO: This is probably broken focus.selectAll('path.area') .datum(curData.summary); } if (rightSeries) { rightSeries.forEach(function (s) { focus.append('path') .datum(data.points) .attr('d', s.line); }); } } // set the new bounds from the summary selection x.domain(newBounds); clearBuilds(); if (options.ajaxZoom) { //refresh with high-res goodness clearTimeout(refreshTimer); refreshTimer = setTimeout(function () { $.getJSON(urlPath, { id: options.id, start: start, end: end }, function (newData) { postProcess(newData); rescaleYAxis(newData, true); series.forEach(function (s) { focus.select('path.area.series-' + s.name) .datum(newData.points) .attr('d', s.area.y0(y(0))) .attr('fill-opacity', 1); }); drawBuilds(newData); }); }, timerDelay || 50); } else { curData.points = curData.summary.filter(function (p) { var t = p.date.getTime(); return start <= t && t <= end; }); rescaleYAxis(curData, true); } // redraw if (options.stacked) { focus.selectAll('.area').attr('d', function(d) { return stackArea(d.values); }); } else { series.forEach(function (s) { focus.select('path.area.series-' + s.name) .attr('d', s.area.y0(y(0))); }); } if (rightSeries) { rightSeries.forEach(function (s) { focus.select('path.line.series-' + s.name).attr('d', s.line); }); } focus.select('.x.axis').call(xAxis); } return this .removeClass('cpu-chart memory-chart network-chart') .addClass(options.type + (options.subtype ? '-' + options.subtype : '') + '-chart'); }, lived3graph: function(options) { var defaults = { series: [{ name: 'value', label: 'Main' }], leftMargin: 40, id: this.data('id'), start: this.data('start'), end: this.data('end'), title: this.data('title'), subtitle: this.data('subtitle'), slideDurationMs: 1000, durationSeconds: 5 * 60, width: 660, height: 300, max: 'auto', min: 0 }; options = $.extend({}, defaults, options); var curWidth, curHeight, now = new Date(), series = options.series, curData = d3.range(60 * 10).map(function(i) { var result = { date: new Date(+now - (60 * 10 * 1000) + (i * 1000)) }; series.forEach(function (s) { result[s.name] = i === 60 * 10 ? 0 : null; }); return result; }), chart = this, areaTooltip = $('<div class="area-tooltip chart-tooltip" />').appendTo(chart), margin, width, height, x, y, xAxis, yAxis, svg, focus, clip, clipId = 'clip' + Status.graphCount++, currentArea, urlPath = '/dashboard/node/poll/' + options.type + (options.subtype ? '/' + options.subtype : ''), params = $.extend({}, { id: options.id, start: options.start / 1000, end: options.end / 1000 }, options.params); options.width = options.width === 'auto' ? (chart.width() - 10) : options.width; options.height = options.height === 'auto' ? (chart.height() - 40) : options.height; if (options.title) { var titleDiv = $('<div class="chart-title"/>').text(options.title).prependTo(chart); if (options.subtitle) { $('<div class="chart-subtitle"/>').text(options.subtitle).appendTo(titleDiv); } } function drawElements() { if (options.width - 10 - options.leftMargin < 300) options.width = 300 + 10 + options.leftMargin; margin = { top: 10, right: 10, bottom: 20, left: options.leftMargin }; width = options.width - margin.left - margin.right; height = options.height - margin.top - margin.bottom; x = d3.time.scale.utc().range([0, width]); y = d3.scale.linear().range([height, 0]); xAxis = d3.svg.axis().scale(x).orient('bottom'); yAxis = d3.svg.axis().scale(y).orient('left'); if (options.yAxis) { if (options.yAxis.tickFormat) { yAxis.tickFormat(options.yAxis.tickFormat); } if (options.yAxis.tickSize) { yAxis.tickSize(options.yAxis.tickSize); } } svg = d3.select(chart[0]).append('svg') .attr('width', options.width) .attr('height', options.height); clip = svg.append('defs').append('clipPath') .attr('id', clipId) .append('rect') .attr('width', width) .attr('height', height); focus = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); } function drawPrimaryGraphs(data) { rescaleYAxis(data, true); // draw a path for each series in the main graph series.forEach(function (s) { focus.append('path') .datum(data) .attr('class', 'area series-' + s.name) .attr('clip-path', 'url(#' + clipId + ')') .attr('d', s.area.y0(y(0))); }); // top hover brush, for main graph focus.append('g') .attr('class', 'x brush') .on('mousemove', areaHover) .on('mouseover', areaEnter) .on('mouseout', areaLeave) .call(d3.svg.brush().x(x)) .selectAll('rect') .attr('y', 0) .attr('height', height + 1); // x-axis focus.append('g') .attr('class', 'x axis') .attr('transform', 'translate(0,' + height + ')') .call(xAxis); // y-axis focus.append('g') .attr('class', 'y axis') .call(yAxis); rescaleYAxis(data, false); // current hover area currentArea = focus.append('g') .attr('class', 'current-area') .style('display', 'none'); // hover line currentArea.append('svg:line') .attr('x1', 0) .attr('x2', 0) .attr('y1', height + margin.top) .attr('y2', margin.top) .attr('class', 'area-tooltip-line'); // hover circle(s) series.forEach(function (s) { currentArea.append('circle') .attr('class', 'series-' + s.name) .attr('r', 4.5); }); curWidth = chart.width(); curHeight = chart.height(); } function prepSeries() { series.forEach(function (s) { var negative = s.direction === 'down'; s.area = d3.svg.area() .interpolate('basis') .x(function (d) { return x(d.date); }) .y1(function (d) { return y(negative ? -d[s.name] : d[s.name]); }); }); } function rescaleYAxis(data, rescale) { if(rescale) y.domain(getExtremes(data, series, options.min, options.max)); focus.select('g.y.axis') .call(yAxis) .selectAll('g.tick.major line') .attr('x1', width); } function areaEnter() { currentArea.style('display', null); areaTooltip.show(); } function areaLeave() { currentArea.style('display', 'none'); areaTooltip.hide(); } function areaHover() { var pos = d3.mouse(this), date = x.invert(pos[0]), bisector = d3.bisector(function (d) { return d.date; }).left, tooltip = '<div class="tooltip-date">' + chartFunctions.tooltipTimeFormat(date) + ' <span class="text-muted">UTC</span></div>'; // align the moons! or at least the series hover dots series.forEach(function (s) { var data = curData, index = bisector(data, date, 1), // bisect the curData array to get the index of the hovered date dateBefore = data[index - 1], // get the date before the hover dateAfter = data[index], // and the date after d = dateBefore && date - dateBefore.date > dateAfter && dateAfter.date - date ? dateAfter : dateBefore; // pick the nearest tooltip += options.areaTooltipFormat(d[s.name], s.label, s.name); currentArea.select('circle.series-' + s.name).attr('transform', 'translate(0, ' + y(s.direction === 'down' ? -d[s.name] : d[s.name]) + ')'); }); areaTooltip.html(tooltip) .css({ left: pos[0] - (areaTooltip.width() / 2), top: pos[1] - areaTooltip.height() - 20 }); currentArea.attr('transform', 'translate(' + (pos[0]) + ', 0)'); } function onWindowResized() { var newWidth = chart.width(), newHeight = chart.height(); if (curWidth !== newWidth || curHeight !== newHeight) { options.width = curWidth = newWidth; curHeight = newHeight; svg.remove(); drawElements(); drawPrimaryGraphs(curData); } } $(window).on('resize', onWindowResized); // lay it all out soon as possible drawElements(); var start = new Date(); x.domain([start - (options.durationSeconds - 2) * options.slideDurationMs, start - options.slideDurationMs]); var curValue = { total: options.startValue || 0 }; // should be passed a { date: dateVal, series1: value, series2: value } style object function tick() { // update the domains var toInsert = { total: curValue.total }; now = new Date(); toInsert.date = now; x.domain([now - options.durationSeconds * 1000 - options.slideDurationMs, now - options.slideDurationMs]); // push the accumulated count onto the back, and reset the count curData.push(toInsert); curData.shift(); // redraw the areas series.forEach(function (s) { focus.select('path.series-' + s.name) .attr('d', s.area) .attr('transform', null); focus.select('path.series-' + s.name) .transition() .duration(options.slideDurationMs) .ease('linear') .attr('transform', 'translate(' + x(now - options.durationSeconds * 1000) + ')'); }); // slide the x-axis left focus.select('g.x.axis') .transition() .duration(options.slideDurationMs) .ease('cubic-in-out') .call(xAxis); } prepSeries(); drawPrimaryGraphs(curData); var ticker = setInterval(tick, options.slideDurationMs), abort = false; var dataPoll = function() { $.getJSON(urlPath, params, function (data) { curValue = data; if (!abort) setTimeout(dataPoll, options.slideDurationMs); }); }; dataPoll(); this.removeClass('cpu-chart memory-chart network-chart') .addClass(options.type + (options.subtype ? '-' + options.subtype : '') + '-chart'); function stop() { clearInterval(ticker); abort = true; } return { tick: tick, stop: stop }; } }); })();
(function () { //'use strict'; define(['app'], function (app) { app.controller('articleListCtrl', articleListCtrl); articleListCtrl.$inject = ['$http', 'mainViewFactory']; function articleListCtrl($http, mainFac) { var vm = this; vm.article_list_data = ''; vm.goToArticle = goToArticle; getArticleList(); function getArticleList() { var url = mainFac.getApiUrl() + "app/articleList"; $http.post(url).success(function (res) { if (res.err) { console.log('err', res.err); } else { vm.article_list_data = res.data; } }); } function goToArticle(inp) { console.log('>>>>>', inp); } } }); }());
// https://github.com/stefanpenner/ember-cli/blob/master/lib/ext/promise.js /*jshint node:true*/ 'use strict'; var RSVP = require('rsvp'); var Promise = RSVP.Promise; module.exports = PromiseExt; // Utility functions on on the native CTOR need some massaging module.exports.hash = function() { return this.resolve(RSVP.hash.apply(null, arguments)); }; module.exports.denodeify = function() { var fn = RSVP.denodeify.apply(null, arguments); var Constructor = this; return function() { return Constructor.resolve(fn.apply(null, arguments)); }; }; module.exports.filter = function() { return this.resolve(RSVP.filter.apply(null, arguments)); }; module.exports.map = function() { return this.resolve(RSVP.map.apply(null, arguments)); }; function PromiseExt() { Promise.apply(this, arguments); } PromiseExt.prototype = Object.create(Promise.prototype); PromiseExt.prototype.constructor = PromiseExt; PromiseExt.__proto__ = Promise; PromiseExt.prototype.returns = function(value) { return this.then(function() { return value; }); }; PromiseExt.prototype.invoke = function(method) { var args = Array.prototype.slice(arguments, 1); return this.then(function(value) { return value[method].apply(value, args); }, undefined, 'invoke: ' + method + ' with: ' + args); }; PromiseExt.prototype.map = function(mapFn) { var Constructor = this.constructor; return this.then(function(values) { return Constructor.map(values, mapFn); }); }; PromiseExt.prototype.filter = function(mapFn) { var Constructor = this.constructor; return this.then(function(values) { return Constructor.filter(values, mapFn); }); };
export const ic_stars_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm7.48 7.16l-5.01-.43-2-4.71c3.21.19 5.91 2.27 7.01 5.14zm-5.07 6.26L12 13.98l-2.39 1.44.63-2.72-2.11-1.83 2.78-.24L12 8.06l1.09 2.56 2.78.24-2.11 1.83.64 2.73zm-2.86-11.4l-2 4.72-5.02.43c1.1-2.88 3.8-4.97 7.02-5.15zM4 12c0-.64.08-1.26.23-1.86l3.79 3.28-1.11 4.75C5.13 16.7 4 14.48 4 12zm3.84 6.82L12 16.31l4.16 2.5c-1.22.75-2.64 1.19-4.17 1.19-1.52 0-2.94-.44-4.15-1.18zm9.25-.65l-1.11-4.75 3.79-3.28c.14.59.23 1.22.23 1.86 0 2.48-1.14 4.7-2.91 6.17z"},"children":[]}]};
;(function() { /** * Concenctration game service factory * * Stores the state of the game, performs all the actions and notifies the app about changes * */ angular .module('concentrationGameApp') .factory('ConcentrationGame', ConcentrationGame); ConcentrationGame.$inject = []; function ConcentrationGame() { /* Constants and Variables */ var maxPairsNum = 26; var minPairsNum = 1; var cardRanks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king', 'ace']; var cardSuits = ['clubs', 'spades', 'diamonds', 'hearts']; /* Game initialization */ var ConcentrationGame = function (pairsNum) { // Verification if (pairsNum > maxPairsNum) { pairsNum = maxPairsNum; } else if (pairsNum < minPairsNum) { pairsNum = minPairsNum; } this.pairsTotal = pairsNum; this.matchesGoal = pairsNum; this.matchesFound = 0; this.cards = []; this.generateCards(pairsNum); }; ConcentrationGame.prototype.generateCards = function (pairsNum) { for (var i = 0; i < (this.pairsTotal * 2); i++) { this.cards.push({ number: i, rank: cardRanks[parseInt(i / cardSuits.length)], suit: cardSuits[ (i % cardSuits.length)], flipped: false, matched: false }); } shuffleArray(this.cards); }; /* Event handling */ var eventHandlers = {}; ConcentrationGame.prototype.on = function (eventName, cb) { eventHandlers[eventName] = cb; }; function emit (thisArg, eventName, argsArray) { if (eventHandlers[eventName]) { eventHandlers[eventName].apply(thisArg, argsArray); } } /* Actions */ var isFlipped = false; // is the new card has been flipped var flippedCard = null; // reference to the first flipped card in the current pair ConcentrationGame.prototype.flipCard = function (cardNumber) { var card = findCard(this.cards, cardNumber); if (card) { // Exit if user clicked the same card twice if (flippedCard && (flippedCard === card)) { return; } if (!isFlipped && !flippedCard) { // Flip the first card in a pair card.flipped = true; isFlipped = true; flippedCard = card; } else if (isFlipped && flippedCard) { // Flip the second card in a pair and check card.flipped = true; if ((card.rank === flippedCard.rank) && hasSameColor(card, flippedCard)) { this.registerMatch(card, flippedCard); } isFlipped = true; flippedCard = null; } else if (isFlipped && !flippedCard) { // Flip all the unmatched cards back and flip the current one this.cards.forEach(function (card) { if (!card.matched) { card.flipped = false; } }); card.flipped = true; isFlipped = true; flippedCard = card; } } } ConcentrationGame.prototype.registerMatch = function (card1, card2) { card1.matched = true; card2.matched = true; this.matchesFound += 1; var matchesLeft = this.matchesGoal - this.matchesFound; var progress = this.matchesFound / this.matchesGoal * 100.0; emit(this, 'matchFound', [matchesLeft, progress]); if (matchesLeft <= 0) { emit(this, 'gameWon'); } } /* Helper functions */ function shuffleArray (o) { for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } function findCard (cards, cardNumber) { var searchResults = cards.filter(function (card) { if (card.number === cardNumber) { return card; } }); if (searchResults.length > 0) { return searchResults[0]; } else { return null; } } function hasSameColor (card1, card2) { if (((card1.suit === 'clubs' || card1.suit === 'spades') && (card2.suit === 'clubs' || card2.suit === 'spades')) || ((card1.suit === 'diamonds' || card1.suit === 'hearts') && (card2.suit === 'diamonds' || card2.suit === 'hearts'))){ return true; } else { return false; } } return function (pairsNum) { return new ConcentrationGame(pairsNum); }; } })();
$.widget('tableau.radioWidget',{ options:{ element: '', filterEnum: { replace: 'REPLACE', add: 'ADD', remove: 'REMOVE' }, template: '{{each appliedValues}}<div class="radio">\ <label>\ <input type="radio" name="radioWidget" value="${this.value}">\ ${this.formattedValue}\ </label>\ </div>{{/each}}', }, _create: function(){ if(this.options.hidden){ this.element.hide(); } //fetch top menu data this.render(); }, destroy: function(){ $.Widget.prototype.destroy.apply(this, arguments); this.unbindEvents(); }, unbindEvents:function(){ this.element.find( 'input[name=radioWidget]' ).off( 'change', this, this.onChecked ); }, bindEvents:function(){ this.element.find( 'input[name=radioWidget]' ).on( 'change', this, this.onChecked ); }, onChecked:function(event){ var $target = $(event.currentTarget), widget = event.data; widget.onFilter($target.val()); }, //for radio it's 1 value only onFilter:function(val){ this.filterSingleValue(val, this.options.filterEnum.replace); }, filterSingleValue:function(val, type){ this.removeValuesFromFilter(); var activeSheet = $.interactionManager.activeSheet.get(); activeSheet.applyFilterAsync( this.options.fieldName, val, tableauSoftware.FilterUpdateType[type] ); }, removeValuesFromFilter:function(){ var activeSheet = $.interactionManager.activeSheet.get(); activeSheet.clearFilterAsync(this.options.fieldName); }, render:function(){ $.tmpl(this.options.template,this.options).appendTo(this.element); this.bindEvents(); } });
const {basename, join} = require('path'); const promiseLens = require('../functional/promise-lens'); const curryOptions = require('../functional/curry-options'); const categorise = require('../functional/categorise'); const defaults = require('./defaults'); const isValid = (listed) => ({canonical, checksum, birthtime}) => { const {checksum: actualChecksum, birthtime: actualBirthtime} = listed .find(({absolute}) => (basename(absolute) === canonical)) || {}; return (actualChecksum === checksum) && (+actualBirthtime === +birthtime); }; const isInvalid = (listed) => (args) => !isValid(listed)(args); const plan = curryOptions( defaults, (options) => (args, {merge, lens} = promiseLens(options)) => Promise.resolve(args) .then(merge( require('./scan')(options), require('./list')(options) )) .then(lens({from: '*', to: 'plan'})( ({ scan: {images: scanImg, videos: scanVid}, list: {base, images: listImg, videos: listVid} }) => categorise({ base, present: isValid(listImg.concat(listVid)), pending: isInvalid(listImg.concat(listVid)) })(scanImg.concat(scanVid)) )) .then(lens({from: 'plan'})( lens({from: '*', to: 'pending'})( ({base, pending}) => pending .map(({absolute, canonical, checksum, birthtime}) => ({ canonical, checksum, birthtime, source: absolute, destination: join(base, canonical), toString: () => canonical })) ) )) ); module.exports = plan;
import Picker from './js/picker'; export default Picker;
/* eslint-env node */ 'use strict'; module.exports = { name: 'yet-another-ember-table' };
import { connect } from 'react-redux' import { default as React, Component, PropTypes } from 'react' import { Button, Panel } from 'react-bootstrap' import { Route, withRouter } from 'react-router-dom' import { SectionHeader } from 'components' import { InvoiceItem, InvoiceItems } from 'containers' import { INVOICE_ID_PARAM } from 'routes/params' import { InvoiceType } from 'api/enums' import { getInvoice, getInvoiceItems, getIsFetchingInvoices } from 'redux/reducers' import * as actions from 'redux/actions' import * as routes from 'routes' import InvoiceDetails from './InvoiceDetails' class View extends Component { constructor (props) { super(props) this.goBack = this.goBack.bind(this) this.onEditClick = this.onEditClick.bind(this) this.onDeleteClick = this.onDeleteClick.bind(this) this.onAddItemClick = this.onAddItemClick.bind(this) this.onItemClick = this.onItemClick.bind(this) this.onDeleteItemsClick = this.onDeleteItemsClick.bind(this) } componentWillMount () { const { loadInvoice, match } = this.props const invoiceId = match.params[INVOICE_ID_PARAM] loadInvoice(invoiceId) } goBack () { const { history } = this.props history.push(routes.invoices()) } onEditClick (event) { event.preventDefault() const { history, match } = this.props const invoiceId = match.params[INVOICE_ID_PARAM] history.push(routes.invoiceEdit(invoiceId)) } onDeleteClick (event) { event.preventDefault() const { deleteInvoice, match } = this.props const invoiceId = match.params[INVOICE_ID_PARAM] deleteInvoice(invoiceId) this.goBack() } onAddItemClick (event) { event.preventDefault() const { history, match } = this.props const invoiceId = match.params[INVOICE_ID_PARAM] history.push(routes.invoiceItemNew(invoiceId)) } onItemClick (itemId) { const { history, match } = this.props const invoiceId = match.params[INVOICE_ID_PARAM] history.push(routes.invoiceItemEdit(invoiceId, itemId)) } onDeleteItemsClick (itemsIds) { const { deleteInvoiceItem, match } = this.props const invoiceId = match.params[INVOICE_ID_PARAM] itemsIds.forEach(id => deleteInvoiceItem(invoiceId, id + '')) } render () { const { invoice, invoiceItems, isFetchingInvoices } = this.props return ( <div> <Panel> <SectionHeader title='Invoice Info'> <Button onClick={this.onEditClick}> Edit </Button> <Button bsStyle='danger' onClick={this.onDeleteClick}> Delete </Button> </SectionHeader> { isFetchingInvoices && !invoice.id ? ( <div>Loading...</div> ) : ( <InvoiceDetails data={invoice} /> ) } </Panel> { invoice.type === InvoiceType.DETAILED && ( <Panel> <Route path={routes.invoiceItemNew()} component={InvoiceItem} /> <Route path={routes.invoiceItemEdit()} component={InvoiceItem} /> <SectionHeader title='Invoice Items'> <Button bsStyle='primary' onClick={this.onAddItemClick}> New Item </Button> </SectionHeader> <InvoiceItems data={invoiceItems} onItemClick={this.onItemClick} onDeleteClick={this.onDeleteItemsClick} /> </Panel> )} </div> ) } } View.propTypes = { invoice: PropTypes.object.isRequired } const mapStateToProps = (state, { match }) => ({ invoice: getInvoice(state, match.params[INVOICE_ID_PARAM]), invoiceItems: getInvoiceItems(state, match.params[INVOICE_ID_PARAM]), isFetchingInvoices: getIsFetchingInvoices(state) }) export default withRouter(connect(mapStateToProps, actions)(View))
while (true) { b(a = 1); }
/** * Highshelf Filter * * @plugin * @param {Object} [params] map of optional values * @param {Number} [params.frequency=440] frequency * @param {Number} [params.q=0] Q * @param {Number} [params.gain=0] gain */ //create & connect white noise and a highshelf filter //(with a frequency of 880, gain of 1 & Q of 10) to output __(). white(). highshelf({ frequency:880, q:10, gain:1 }). dac(0.25); //connect to the previously created white noise and //create a highshelf filter (with a frequency of 600) // and connect to output __("white").highshelf(600).connect("dac"); //connect to the previously created white noise and //create a highshelf filter (default frequency 440) // and connect to output __("white").highshelf().connect("dac"); __("white").start();
function emove(){ } function collide(){ } function dispchr(){ } function putn(){ } function chrname(stg){ switch(stg){ case "circle": return chr1; break; case "heart": return chr2; break; case "fill": return chr3; break; case "sw": return chr4; break; case "se": return chr5; break; case "wave": return chr6; break; case "spade": return chr7; break; case "sharp": return chr8; break; case "star": return chr9; break; case "flag": return chr10; break; case "slash": return chr11; break; case "backslash": return chr12; break; case "nw": return chr13; break; case "ne": return chr14; break; case "block": return chr15; break; case "brick": return chr16; break; case "equal": return chr17; break; default: break; } } function put(chrcode,cx,cy){ var chrctx=new Array(0,8,5); putc(chrcode,chrctx,cx*8,cy*5); }
import StockStore from './stock_store.coffee'; const ArticleStore = new StockStore({ sortKey: 'character_sum', descKeys: { character_sum: true, view_count: true }, modelKey: 'article' } ); export default ArticleStore.store;
import { firebaseAuth } from '../firebase'; import { loadRecos, importRecosFromLocalStorage } from '../recos/actions'; import { INIT_AUTH, LOGIN, LOGIN_ERROR, SIGNUP_ERROR, LOGOUT_ERROR, LOGOUT } from './action-types'; const _initAuthAction = (user) => ({ type: INIT_AUTH, user }); export const initAuthAction = (user) => { return (dispatch) => { dispatch(_initAuthAction(user)); if(user) { dispatch(loadRecos()); dispatch(importRecosFromLocalStorage()); } }; }; export const signInWithEmailAndPassword = (email, password) => { return (dispatch) => { return firebaseAuth.signInWithEmailAndPassword(email, password) .then(result => dispatch(login(result))) .catch(error => dispatch(loginError(error))); }; }; export const signUpWithEmailAndPassword = (email, password) => { return (dispatch) => { return firebaseAuth.createUserWithEmailAndPassword(email, password) .then(result => dispatch(login(result))) .catch(error => dispatch(signupError(error))); }; }; export const logoutFromDatabase = () => { return (dispatch) => { return firebaseAuth.signOut() .then(result => dispatch(logout(result))) .catch(error => dispatch(logoutError(error))); }; }; export const login = (user) => ({ type: LOGIN, user }); export const loginError = (error) => ({ type: LOGIN_ERROR, error }); export const signupError = (error) => ({ type: SIGNUP_ERROR, error }); export const logoutError = (error) => ({ type: LOGOUT_ERROR, error }); export const logout = () => ({ type: LOGOUT });
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * ------------------------------------------------------------------------ * Simple Backdrop * ------------------------------------------------------------------------ */ var Backdrop = function () { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var STYLES = '\n .ghost-backdrop {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1040;\n background-color: #000;\n opacity: 0;\n transition: ease all 0.5s;\n }\n '; var Default = { removeDelay: 0, 'zIndex': 2001, allowMany: false, closeOnClick: true }; var Backdrop = function () { function Backdrop(options) { _classCallCheck(this, Backdrop); this.defaults = Utils.extend(Default, options); if (this.__proto__.instances.length && !this.defaults.allowMany) { return; } this.__proto__.instances.push(this); this.injectStyles(); this.createDOM(); } // getters _createClass(Backdrop, [{ key: 'injectStyles', value: function injectStyles() { //if styles exists do nothing if (document.getElementById('backdropStyles')) return; var tag = document.createElement('style'); tag.type = 'text/css'; tag.id = 'backdropStyles'; if (tag.styleSheet) { tag.styleSheet.cssText = STYLES; } else { tag.appendChild(document.createTextNode(STYLES)); } document.getElementsByTagName('head')[0].appendChild(tag); } }, { key: 'createDOM', value: function createDOM() { // remove on click or not var ev = this.defaults.closeOnClick ? { click: this.__proto__.removeAll.bind(this) } : {}; var elm = new Elm('div.ghost-backdrop', ev, document.body); elm.style.zIndex = this.defaults.zIndex; setTimeout(function () { elm.style.opacity = 0.5; }); } }, { key: 'remove', value: function remove() { setTimeout(function () { var backdrops = document.querySelectorAll('.ghost-backdrop'); var _loop = function _loop() { console.log('i', i); var elm = backdrops[i]; elm.style.opacity = 0; setTimeout(function () { console.log(elm); elm.parentNode.removeChild(elm); }, 500); }; for (var i = 0; i < backdrops.length; i++) { _loop(); } }, this.defaults.removeDelay); } }, { key: 'STYLES', get: function get() { return STYLES; } }]); return Backdrop; }(); Backdrop.prototype.instances = []; Backdrop.prototype.removeAll = function () { this.instances.forEach(function (item) { item.remove(); }); this.instances.length = 0; }; return Backdrop; }();
const webpack = require('webpack') const path = require('path') const { NODE_ENV } = process.env const plugins = [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV) }) ] const filename = `horizon-redux${NODE_ENV === 'production' ? '.min' : ''}.js` NODE_ENV === 'production' && plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { pure_getters: true, unsafe: true, unsafe_comps: true, screw_ie8: true, warnings: false } }) ) module.exports = { module: { loaders: [ { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ } ] }, entry: [ './src/index' ], output: { path: path.join(__dirname, 'dist'), filename, library: 'HorizonRedux', libraryTarget: 'umd' }, plugins }
/* Ratings and how they work: -2: Extremely detrimental The sort of ability that relegates Pokemon with Uber-level BSTs into NU. ex. Slow Start, Truant -1: Detrimental An ability that does more harm than good. ex. Defeatist, Normalize 0: Useless An ability with no net effect during a singles battle. ex. Healer, Illuminate 1: Ineffective An ability that has a minimal effect. Should not be chosen over any other ability. ex. Damp, Shell Armor 2: Situationally useful An ability that can be useful in certain situations. ex. Blaze, Insomnia 3: Useful An ability that is generally useful. ex. Infiltrator, Sturdy 4: Very useful One of the most popular abilities. The difference between 3 and 4 can be ambiguous. ex. Protean, Regenerator 5: Essential The sort of ability that defines metagames. ex. Desolate Land, Shadow Tag */ exports.BattleAbilities = { "adaptability": { desc: "This Pokemon's moves that match one of its types have a same-type attack bonus (STAB) of 2 instead of 1.5.", shortDesc: "This Pokemon's same-type attack bonus (STAB) is 2 instead of 1.5.", onModifyMove: function (move) { move.stab = 2; }, id: "adaptability", name: "Adaptability", rating: 3.5, num: 91 }, "aftermath": { desc: "If this Pokemon is knocked out with a contact move, that move's user loses 1/4 of its maximum HP, rounded down. If any active Pokemon has the Ability Damp, this effect is prevented.", shortDesc: "If this Pokemon is KOed with a contact move, that move's user loses 1/4 its max HP.", id: "aftermath", name: "Aftermath", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.flags['contact'] && !target.hp) { this.damage(source.maxhp / 4, source, target, null, true); } }, rating: 2.5, num: 106 }, "aerilate": { desc: "This Pokemon's Normal-type moves become Flying-type moves and have their power multiplied by 1.3. This effect comes after other effects that change a move's type, but before Ion Deluge and Electrify's effects.", shortDesc: "This Pokemon's Normal-type moves become Flying type and have 1.3x power.", onModifyMovePriority: -1, onModifyMove: function (move, pokemon) { if (move.type === 'Normal' && move.id !== 'naturalgift') { move.type = 'Flying'; if (move.category !== 'Status') pokemon.addVolatile('aerilate'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); } }, id: "aerilate", name: "Aerilate", rating: 4, num: 185 }, "airlock": { shortDesc: "While this Pokemon is active, the effects of weather conditions are disabled.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Air Lock'); }, onAnyTryWeather: false, id: "airlock", name: "Air Lock", rating: 3, num: 76 }, "analytic": { desc: "The power of this Pokemon's move is multiplied by 1.3 if it is the last to move in a turn. Does not affect Doom Desire and Future Sight.", shortDesc: "This Pokemon's attacks have 1.3x power if it is the last to move in a turn.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (!this.willMove(defender)) { this.debug('Analytic boost'); return this.chainModify([0x14CD, 0x1000]); // The Analytic modifier is slightly higher than the normal 1.3 (0x14CC) } }, id: "analytic", name: "Analytic", rating: 2, num: 148 }, "angerpoint": { desc: "If this Pokemon, but not its substitute, is struck by a critical hit, its Attack is raised by 12 stages.", shortDesc: "If this Pokemon (not its substitute) takes a critical hit, its Attack is raised 12 stages.", onAfterDamage: function (damage, target, source, move) { if (!target.hp) return; if (move && move.effectType === 'Move' && move.crit) { target.setBoost({atk: 6}); this.add('-setboost', target, 'atk', 12, '[from] ability: Anger Point'); } }, id: "angerpoint", name: "Anger Point", rating: 2, num: 83 }, "anticipation": { desc: "On switch-in, this Pokemon is alerted if any opposing Pokemon has an attack that is super effective on this Pokemon, or an OHKO move. Counter, Metal Burst, and Mirror Coat count as attacking moves of their respective types, while Hidden Power, Judgment, Natural Gift, Techno Blast, and Weather Ball are considered Normal-type moves.", shortDesc: "On switch-in, this Pokemon shudders if any foe has a supereffective or OHKO move.", onStart: function (pokemon) { var targets = pokemon.side.foe.active; for (var i = 0; i < targets.length; i++) { if (!targets[i] || targets[i].fainted) continue; for (var j = 0; j < targets[i].moveset.length; j++) { var move = this.getMove(targets[i].moveset[j].move); if (move.category !== 'Status' && (this.getImmunity(move.type, pokemon) && this.getEffectiveness(move.type, pokemon) > 0 || move.ohko)) { this.add('-activate', pokemon, 'ability: Anticipation'); return; } } } }, id: "anticipation", name: "Anticipation", rating: 1, num: 107 }, "arenatrap": { desc: "Prevents adjacent opposing Pokemon from choosing to switch out unless they are immune to trapping or are airborne.", shortDesc: "Prevents adjacent foes from choosing to switch unless they are airborne.", onFoeModifyPokemon: function (pokemon) { if (!this.isAdjacent(pokemon, this.effectData.target)) return; if (pokemon.isGrounded()) { pokemon.tryTrap(true); } }, onFoeMaybeTrapPokemon: function (pokemon, source) { if (!source) source = this.effectData.target; if (!this.isAdjacent(pokemon, source)) return; if (pokemon.isGrounded()) { pokemon.maybeTrapped = true; } }, id: "arenatrap", name: "Arena Trap", rating: 4.5, num: 71 }, "aromaveil": { desc: "This Pokemon and its allies cannot be affected by Attract, Disable, Encore, Heal Block, Taunt, or Torment.", shortDesc: "Protects user/allies from Attract, Disable, Encore, Heal Block, Taunt, and Torment.", onAllyTryHit: function (target, source, move) { if (move && move.id in {attract:1, disable:1, encore:1, healblock:1, taunt:1, torment:1}) { return false; } }, id: "aromaveil", name: "Aroma Veil", rating: 1.5, num: 165 }, "aurabreak": { desc: "While this Pokemon is active, the effects of the Abilities Dark Aura and Fairy Aura are reversed, multiplying the power of Dark- and Fairy-type moves, respectively, by 3/4 instead of 1.33.", shortDesc: "While this Pokemon is active, the Dark Aura and Fairy Aura power modifier is 0.75x.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Aura Break'); }, onAnyTryPrimaryHit: function (target, source, move) { if (target === source || move.category === 'Status') return; source.addVolatile('aurabreak'); }, effect: { duration: 1 }, id: "aurabreak", name: "Aura Break", rating: 2, num: 188 }, "baddreams": { desc: "Causes adjacent opposing Pokemon to lose 1/8 of their maximum HP, rounded down, at the end of each turn if they are asleep.", shortDesc: "Causes sleeping adjacent foes to lose 1/8 of their max HP at the end of each turn.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (!pokemon.hp) return; for (var i = 0; i < pokemon.side.foe.active.length; i++) { var target = pokemon.side.foe.active[i]; if (!target || !target.hp) continue; if (target.status === 'slp') { this.damage(target.maxhp / 8, target); } } }, id: "baddreams", name: "Bad Dreams", rating: 2, num: 123 }, "battlearmor": { shortDesc: "This Pokemon cannot be struck by a critical hit.", onCriticalHit: false, id: "battlearmor", name: "Battle Armor", rating: 1, num: 4 }, "bigpecks": { shortDesc: "Prevents other Pokemon from lowering this Pokemon's Defense stat stage.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; if (boost['def'] && boost['def'] < 0) { boost['def'] = 0; if (!effect.secondaries) this.add("-fail", target, "unboost", "Defense", "[from] ability: Big Pecks", "[of] " + target); } }, id: "bigpecks", name: "Big Pecks", rating: 0.5, num: 145 }, "blaze": { desc: "When this Pokemon has 1/3 or less of its maximum HP, rounded down, its attacking stat is multiplied by 1.5 while using a Fire-type attack.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Fire attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) { this.debug('Blaze boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) { this.debug('Blaze boost'); return this.chainModify(1.5); } }, id: "blaze", name: "Blaze", rating: 2, num: 66 }, "bulletproof": { shortDesc: "This Pokemon is immune to bullet moves.", onTryHit: function (pokemon, target, move) { if (move.flags['bullet']) { this.add('-immune', pokemon, '[msg]', '[from] Bulletproof'); return null; } }, id: "bulletproof", name: "Bulletproof", rating: 3, num: 171 }, "cheekpouch": { desc: "If this Pokemon eats a Berry, it restores 1/3 of its maximum HP, rounded down, in addition to the Berry's effect.", shortDesc: "If this Pokemon eats a Berry, it restores 1/3 of its max HP after the Berry's effect.", onEatItem: function (item, pokemon) { this.heal(pokemon.maxhp / 3); }, id: "cheekpouch", name: "Cheek Pouch", rating: 2, num: 167 }, "chlorophyll": { shortDesc: "If Sunny Day is active, this Pokemon's Speed is doubled.", onModifySpe: function (speMod) { if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chain(speMod, 2); } }, id: "chlorophyll", name: "Chlorophyll", rating: 2.5, num: 34 }, "clearbody": { shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; var showMsg = false; for (var i in boost) { if (boost[i] < 0) { delete boost[i]; showMsg = true; } } if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Clear Body", "[of] " + target); }, id: "clearbody", name: "Clear Body", rating: 2, num: 29 }, "cloudnine": { shortDesc: "While this Pokemon is active, the effects of weather conditions are disabled.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Cloud Nine'); }, onAnyTryWeather: false, id: "cloudnine", name: "Cloud Nine", rating: 3, num: 13 }, "colorchange": { desc: "This Pokemon's type changes to match the type of the last move that hit it, unless that type is already one of its types. This effect applies after all hits from a multi-hit move; Sheer Force prevents it from activating if the move has a secondary effect.", shortDesc: "This Pokemon's type changes to the type of a move it's hit by, unless it has the type.", onAfterMoveSecondary: function (target, source, move) { var type = move.type; if (target.isActive && move.effectType === 'Move' && move.category !== 'Status' && type !== '???' && !target.hasType(type)) { if (!target.setType(type)) return false; this.add('-start', target, 'typechange', type, '[from] Color Change'); target.update(); } }, id: "colorchange", name: "Color Change", rating: 1, num: 16 }, "competitive": { desc: "This Pokemon's Special Attack is raised by 2 stages for each of its stat stages that is lowered by an opposing Pokemon.", shortDesc: "This Pokemon's Sp. Atk is raised by 2 for each of its stats that is lowered by a foe.", onAfterEachBoost: function (boost, target, source) { if (!source || target.side === source.side) { return; } var statsLowered = false; for (var i in boost) { if (boost[i] < 0) { statsLowered = true; } } if (statsLowered) { this.boost({spa: 2}); } }, id: "competitive", name: "Competitive", rating: 2.5, num: 172 }, "compoundeyes": { shortDesc: "This Pokemon's moves have their accuracy multiplied by 1.3.", onSourceModifyAccuracy: function (accuracy) { if (typeof accuracy !== 'number') return; this.debug('compoundeyes - enhancing accuracy'); return accuracy * 1.3; }, id: "compoundeyes", name: "Compound Eyes", rating: 3.5, num: 14 }, "contrary": { shortDesc: "If this Pokemon has a stat stage raised it is lowered instead, and vice versa.", onBoost: function (boost) { for (var i in boost) { boost[i] *= -1; } }, id: "contrary", name: "Contrary", rating: 4, num: 126 }, "cursedbody": { desc: "If this Pokemon is hit by an attack, there is a 30% chance that move gets disabled unless one of the attacker's moves is already disabled.", shortDesc: "If this Pokemon is hit by an attack, there is a 30% chance that move gets disabled.", onAfterDamage: function (damage, target, source, move) { if (!source || source.volatiles['disable']) return; if (source !== target && move && move.effectType === 'Move') { if (this.random(10) < 3) { source.addVolatile('disable'); } } }, id: "cursedbody", name: "Cursed Body", rating: 2, num: 130 }, "cutecharm": { desc: "There is a 30% chance a Pokemon making contact with this Pokemon will become infatuated if it is of the opposite gender.", shortDesc: "30% chance of infatuating Pokemon of the opposite gender if they make contact.", onAfterDamage: function (damage, target, source, move) { if (move && move.flags['contact']) { if (this.random(10) < 3) { source.addVolatile('attract', target); } } }, id: "cutecharm", name: "Cute Charm", rating: 1, num: 56 }, "damp": { desc: "While this Pokemon is active, Self-Destruct, Explosion, and the Ability Aftermath are prevented from having an effect.", shortDesc: "While this Pokemon is active, Self-Destruct, Explosion, and Aftermath have no effect.", id: "damp", onAnyTryMove: function (target, source, effect) { if (effect.id === 'selfdestruct' || effect.id === 'explosion') { this.attrLastMove('[still]'); this.add('-activate', this.effectData.target, 'ability: Damp'); return false; } }, onAnyDamage: function (damage, target, source, effect) { if (effect && effect.id === 'aftermath') { return false; } }, name: "Damp", rating: 1, num: 6 }, "darkaura": { desc: "While this Pokemon is active, the power of Dark-type moves used by active Pokemon is multiplied by 1.33.", shortDesc: "While this Pokemon is active, a Dark move used by any Pokemon has 1.33x power.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Dark Aura'); }, onAnyTryPrimaryHit: function (target, source, move) { if (target === source || move.category === 'Status') return; if (move.type === 'Dark') { source.addVolatile('aura'); } }, id: "darkaura", name: "Dark Aura", rating: 3, num: 186 }, "defeatist": { desc: "While this Pokemon has 1/2 or less of its maximum HP, its Attack and Special Attack are halved.", shortDesc: "While this Pokemon has 1/2 or less of its max HP, its Attack and Sp. Atk are halved.", onModifyAtkPriority: 5, onModifyAtk: function (atk, pokemon) { if (pokemon.hp < pokemon.maxhp / 2) { return this.chainModify(0.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, pokemon) { if (pokemon.hp < pokemon.maxhp / 2) { return this.chainModify(0.5); } }, onResidual: function (pokemon) { pokemon.update(); }, id: "defeatist", name: "Defeatist", rating: -1, num: 129 }, "defiant": { desc: "This Pokemon's Attack is raised by 2 stages for each of its stat stages that is lowered by an opposing Pokemon.", shortDesc: "This Pokemon's Attack is raised by 2 for each of its stats that is lowered by a foe.", onAfterEachBoost: function (boost, target, source) { if (!source || target.side === source.side) { return; } var statsLowered = false; for (var i in boost) { if (boost[i] < 0) { statsLowered = true; } } if (statsLowered) { this.boost({atk: 2}); } }, id: "defiant", name: "Defiant", rating: 2.5, num: 128 }, "deltastream": { desc: "On switch-in, the weather becomes strong winds that remove the weaknesses of the Flying type from Flying-type Pokemon. This weather remains in effect until this Ability is no longer active for any Pokemon, or the weather is changed by Desolate Land or Primordial Sea.", shortDesc: "On switch-in, strong winds begin until this Ability is not active in battle.", onStart: function (source) { this.setWeather('deltastream'); }, onAnySetWeather: function (target, source, weather) { if (this.getWeather().id === 'deltastream' && !(weather.id in {desolateland:1, primordialsea:1, deltastream:1})) return false; }, onEnd: function (pokemon) { if (this.weatherData.source !== pokemon) return; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var target = this.sides[i].active[j]; if (target === pokemon) continue; if (target && target.hp && target.hasAbility('deltastream')) { this.weatherData.source = target; return; } } } this.clearWeather(); }, id: "deltastream", name: "Delta Stream", rating: 5, num: 191 }, "desolateland": { desc: "On switch-in, the weather becomes extremely harsh sunlight that prevents damaging Water-type moves from executing, in addition to all the effects of Sunny Day. This weather remains in effect until this Ability is no longer active for any Pokemon, or the weather is changed by Delta Stream or Primordial Sea.", shortDesc: "On switch-in, extremely harsh sunlight begins until this Ability is not active in battle.", onStart: function (source) { this.setWeather('desolateland'); }, onAnySetWeather: function (target, source, weather) { if (this.getWeather().id === 'desolateland' && !(weather.id in {desolateland:1, primordialsea:1, deltastream:1})) return false; }, onEnd: function (pokemon) { if (this.weatherData.source !== pokemon) return; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var target = this.sides[i].active[j]; if (target === pokemon) continue; if (target && target.hp && target.hasAbility('desolateland')) { this.weatherData.source = target; return; } } } this.clearWeather(); }, id: "desolateland", name: "Desolate Land", rating: 5, num: 190 }, "download": { desc: "On switch-in, this Pokemon's Attack or Special Attack is raised by 1 stage based on the weaker combined defensive stat of all opposing Pokemon. Attack is raised if their Defense is lower, and Special Attack is raised if their Special Defense is the same or lower.", shortDesc: "On switch-in, Attack or Sp. Atk is raised 1 stage based on the foes' weaker Defense.", onStart: function (pokemon) { var foeactive = pokemon.side.foe.active; var totaldef = 0; var totalspd = 0; for (var i = 0; i < foeactive.length; i++) { if (!foeactive[i] || foeactive[i].fainted) continue; totaldef += foeactive[i].getStat('def', false, true); totalspd += foeactive[i].getStat('spd', false, true); } if (totaldef && totaldef >= totalspd) { this.boost({spa:1}); } else if (totalspd) { this.boost({atk:1}); } }, id: "download", name: "Download", rating: 4, num: 88 }, "drizzle": { shortDesc: "On switch-in, this Pokemon summons Rain Dance.", onStart: function (source) { this.setWeather('raindance'); }, id: "drizzle", name: "Drizzle", rating: 4, num: 2 }, "drought": { shortDesc: "On switch-in, this Pokemon summons Sunny Day.", onStart: function (source) { this.setWeather('sunnyday'); }, id: "drought", name: "Drought", rating: 4, num: 70 }, "dryskin": { desc: "This Pokemon is immune to Water-type moves and restores 1/4 of its maximum HP, rounded down, when hit by a Water-type move. The power of Fire-type moves is multiplied by 1.25 when used on this Pokemon. At the end of each turn, this Pokemon restores 1/8 of its maximum HP, rounded down, if the weather is Rain Dance, and loses 1/8 of its maximum HP, rounded down, if the weather is Sunny Day.", shortDesc: "This Pokemon is healed 1/4 by Water, 1/8 by Rain; is hurt 1.25x by Fire, 1/8 by Sun.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Water') { if (!this.heal(target.maxhp / 4)) { this.add('-immune', target, '[msg]'); } return null; } }, onBasePowerPriority: 7, onFoeBasePower: function (basePower, attacker, defender, move) { if (this.effectData.target !== defender) return; if (move.type === 'Fire') { return this.chainModify(1.25); } }, onWeather: function (target, source, effect) { if (effect.id === 'raindance' || effect.id === 'primordialsea') { this.heal(target.maxhp / 8); } else if (effect.id === 'sunnyday' || effect.id === 'desolateland') { this.damage(target.maxhp / 8); } }, id: "dryskin", name: "Dry Skin", rating: 3.5, num: 87 }, "earlybird": { shortDesc: "This Pokemon's sleep counter drops by 2 instead of 1.", id: "earlybird", name: "Early Bird", // Implemented in statuses.js rating: 2.5, num: 48 }, "effectspore": { desc: "30% chance a Pokemon making contact with this Pokemon will be poisoned, paralyzed, or fall asleep.", shortDesc: "30% chance of poison/paralysis/sleep on others making contact with this Pokemon.", onAfterDamage: function (damage, target, source, move) { if (move && move.flags['contact'] && !source.status && source.runImmunity('powder')) { var r = this.random(100); if (r < 11) { source.setStatus('slp', target); } else if (r < 21) { source.setStatus('par', target); } else if (r < 30) { source.setStatus('psn', target); } } }, id: "effectspore", name: "Effect Spore", rating: 2, num: 27 }, "fairyaura": { desc: "While this Pokemon is active, the power of Fairy-type moves used by active Pokemon is multiplied by 1.33.", shortDesc: "While this Pokemon is active, a Fairy move used by any Pokemon has 1.33x power.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Fairy Aura'); }, onAnyTryPrimaryHit: function (target, source, move) { if (target === source || move.category === 'Status') return; if (move.type === 'Fairy') { source.addVolatile('aura'); } }, id: "fairyaura", name: "Fairy Aura", rating: 3, num: 187 }, "filter": { shortDesc: "This Pokemon receives 3/4 damage from supereffective attacks.", onSourceModifyDamage: function (damage, source, target, move) { if (move.typeMod > 0) { this.debug('Filter neutralize'); return this.chainModify(0.75); } }, id: "filter", name: "Filter", rating: 3, num: 111 }, "flamebody": { shortDesc: "30% chance a Pokemon making contact with this Pokemon will be burned.", onAfterDamage: function (damage, target, source, move) { if (move && move.flags['contact']) { if (this.random(10) < 3) { source.trySetStatus('brn', target, move); } } }, id: "flamebody", name: "Flame Body", rating: 2, num: 49 }, "flareboost": { desc: "While this Pokemon is burned, the power of its special attacks is multiplied by 1.5.", shortDesc: "While this Pokemon is burned, its special attacks have 1.5x power.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (attacker.status === 'brn' && move.category === 'Special') { return this.chainModify(1.5); } }, id: "flareboost", name: "Flare Boost", rating: 2.5, num: 138 }, "flashfire": { desc: "This Pokemon is immune to Fire-type moves. The first time it is hit by a Fire-type move, its attacking stat is multiplied by 1.5 while using a Fire-type attack as long as it remains active and has this Ability. If this Pokemon is frozen, it cannot be defrosted by Fire-type attacks.", shortDesc: "This Pokemon's Fire attacks do 1.5x damage if hit by one Fire move; Fire immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Fire') { move.accuracy = true; if (!target.addVolatile('flashfire')) { this.add('-immune', target, '[msg]'); } return null; } }, onEnd: function (pokemon) { pokemon.removeVolatile('flashfire'); }, effect: { noCopy: true, // doesn't get copied by Baton Pass onStart: function (target) { this.add('-start', target, 'ability: Flash Fire'); }, onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Fire') { this.debug('Flash Fire boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Fire') { this.debug('Flash Fire boost'); return this.chainModify(1.5); } }, onEnd: function (target) { this.add('-end', target, 'ability: Flash Fire', '[silent]'); } }, id: "flashfire", name: "Flash Fire", rating: 3, num: 18 }, "flowergift": { desc: "If this Pokemon is a Cherrim and Sunny Day is active, it changes to Sunshine Form and the Attack and Special Defense of it and its allies are multiplied by 1.5.", shortDesc: "If user is Cherrim and Sunny Day is active, it and allies' Attack and Sp. Def are 1.5x.", onStart: function (pokemon) { delete this.effectData.forme; }, onUpdate: function (pokemon) { if (!pokemon.isActive || pokemon.baseTemplate.speciesid !== 'cherrim') return; if (this.isWeather(['sunnyday', 'desolateland'])) { if (pokemon.template.speciesid !== 'cherrimsunshine') { pokemon.formeChange('Cherrim-Sunshine'); this.add('-formechange', pokemon, 'Cherrim-Sunshine', '[msg]'); } } else { if (pokemon.template.speciesid === 'cherrimsunshine') { pokemon.formeChange('Cherrim'); this.add('-formechange', pokemon, 'Cherrim', '[msg]'); } } }, onModifyAtkPriority: 3, onAllyModifyAtk: function (atk) { if (this.effectData.target.template.speciesid !== 'cherrim') return; if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chainModify(1.5); } }, onModifySpDPriority: 4, onAllyModifySpD: function (spd) { if (this.effectData.target.template.speciesid !== 'cherrim') return; if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chainModify(1.5); } }, id: "flowergift", name: "Flower Gift", rating: 2.5, num: 122 }, "flowerveil": { desc: "Grass-type Pokemon on this Pokemon's side cannot have their stat stages lowered by other Pokemon or have a major status condition inflicted on them by other Pokemon.", shortDesc: "This side's Grass types can't have stats lowered or status inflicted by other Pokemon.", onAllyBoost: function (boost, target, source, effect) { if ((source && target === source) || !target.hasType('Grass')) return; var showMsg = false; for (var i in boost) { if (boost[i] < 0) { delete boost[i]; showMsg = true; } } if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Flower Veil", "[of] " + target); }, onAllySetStatus: function (status, target) { if (target.hasType('Grass')) return false; }, id: "flowerveil", name: "Flower Veil", rating: 0, num: 166 }, "forecast": { desc: "If this Pokemon is a Castform, its type changes to the current weather condition's type, except Sandstorm.", shortDesc: "Castform's type changes to the current weather condition's type, except Sandstorm.", onUpdate: function (pokemon) { if (pokemon.baseTemplate.species !== 'Castform' || pokemon.transformed) return; var forme = null; switch (this.effectiveWeather()) { case 'sunnyday': case 'desolateland': if (pokemon.template.speciesid !== 'castformsunny') forme = 'Castform-Sunny'; break; case 'raindance': case 'primordialsea': if (pokemon.template.speciesid !== 'castformrainy') forme = 'Castform-Rainy'; break; case 'hail': if (pokemon.template.speciesid !== 'castformsnowy') forme = 'Castform-Snowy'; break; default: if (pokemon.template.speciesid !== 'castform') forme = 'Castform'; break; } if (pokemon.isActive && forme) { pokemon.formeChange(forme); this.add('-formechange', pokemon, forme, '[msg]'); } }, id: "forecast", name: "Forecast", rating: 3, num: 59 }, "forewarn": { desc: "On switch-in, this Pokemon is alerted to the move with the highest power, at random, known by an opposing Pokemon.", shortDesc: "On switch-in, this Pokemon is alerted to the foes' move with the highest power.", onStart: function (pokemon) { var targets = pokemon.side.foe.active; var warnMoves = []; var warnBp = 1; for (var i = 0; i < targets.length; i++) { if (targets[i].fainted) continue; for (var j = 0; j < targets[i].moveset.length; j++) { var move = this.getMove(targets[i].moveset[j].move); var bp = move.basePower; if (move.ohko) bp = 160; if (move.id === 'counter' || move.id === 'metalburst' || move.id === 'mirrorcoat') bp = 120; if (!bp && move.category !== 'Status') bp = 80; if (bp > warnBp) { warnMoves = [[move, targets[i]]]; warnBp = bp; } else if (bp === warnBp) { warnMoves.push([move, targets[i]]); } } } if (!warnMoves.length) return; var warnMove = warnMoves[this.random(warnMoves.length)]; this.add('-activate', pokemon, 'ability: Forewarn', warnMove[0], warnMove[1]); }, id: "forewarn", name: "Forewarn", rating: 1, num: 108 }, "friendguard": { shortDesc: "This Pokemon's allies receive 3/4 damage from other Pokemon's attacks.", id: "friendguard", name: "Friend Guard", onAnyModifyDamage: function (damage, source, target, move) { if (target !== this.effectData.target && target.side === this.effectData.target.side) { this.debug('Friend Guard weaken'); return this.chainModify(0.75); } }, rating: 0, num: 132 }, "frisk": { shortDesc: "On switch-in, this Pokemon identifies the held items of all opposing Pokemon.", onStart: function (pokemon) { var foeactive = pokemon.side.foe.active; for (var i = 0; i < foeactive.length; i++) { if (!foeactive[i] || foeactive[i].fainted) continue; if (foeactive[i].item) { this.add('-item', foeactive[i], foeactive[i].getItem().name, '[from] ability: Frisk', '[of] ' + pokemon, '[identify]'); } } }, id: "frisk", name: "Frisk", rating: 1.5, num: 119 }, "furcoat": { shortDesc: "This Pokemon's Defense is doubled.", onModifyDefPriority: 6, onModifyDef: function (def) { return this.chainModify(2); }, id: "furcoat", name: "Fur Coat", rating: 3.5, num: 169 }, "galewings": { shortDesc: "This Pokemon's Flying-type moves have their priority increased by 1.", onModifyPriority: function (priority, pokemon, target, move) { if (move && move.type === 'Flying') return priority + 1; }, id: "galewings", name: "Gale Wings", rating: 4.5, num: 177 }, "gluttony": { shortDesc: "When this Pokemon has 1/2 or less of its maximum HP, it uses certain Berries early.", id: "gluttony", name: "Gluttony", rating: 1, num: 82 }, "gooey": { shortDesc: "Pokemon making contact with this Pokemon have their Speed lowered by 1 stage.", onAfterDamage: function (damage, target, source, effect) { if (effect && effect.flags['contact']) this.boost({spe: -1}, source, target); }, id: "gooey", name: "Gooey", rating: 2.5, num: 183 }, "grasspelt": { shortDesc: "If Grassy Terrain is active, this Pokemon's Defense is multiplied by 1.5.", onModifyDefPriority: 6, onModifyDef: function (pokemon) { if (this.isTerrain('grassyterrain')) return this.chainModify(1.5); }, id: "grasspelt", name: "Grass Pelt", rating: 0.5, num: 179 }, "guts": { desc: "If this Pokemon has a major status condition, its Attack is multiplied by 1.5; burn's physical damage halving is ignored.", shortDesc: "If this Pokemon is statused, its Attack is 1.5x; ignores burn halving physical damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, pokemon) { if (pokemon.status) { return this.chainModify(1.5); } }, id: "guts", name: "Guts", rating: 3, num: 62 }, "harvest": { desc: "If the last item this Pokemon used is a Berry, there is a 50% chance it gets restored at the end of each turn. If Sunny Day is active, this chance is 100%.", shortDesc: "If last item used is a Berry, 50% chance to restore it each end of turn. 100% in Sun.", id: "harvest", name: "Harvest", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (this.isWeather(['sunnyday', 'desolateland']) || this.random(2) === 0) { if (pokemon.hp && !pokemon.item && this.getItem(pokemon.lastItem).isBerry) { pokemon.setItem(pokemon.lastItem); this.add('-item', pokemon, pokemon.getItem(), '[from] ability: Harvest'); } } }, rating: 2.5, num: 139 }, "healer": { desc: "There is a 30% chance of curing an adjacent ally's major status condition at the end of each turn.", shortDesc: "30% chance of curing an adjacent ally's status at the end of each turn.", id: "healer", name: "Healer", onResidualOrder: 5, onResidualSubOrder: 1, onResidual: function (pokemon) { var allyActive = pokemon.side.active; if (allyActive.length === 1) { return; } for (var i = 0; i < allyActive.length; i++) { if (allyActive[i] && this.isAdjacent(pokemon, allyActive[i]) && allyActive[i].status && this.random(10) < 3) { allyActive[i].cureStatus(); } } }, rating: 0, num: 131 }, "heatproof": { desc: "The power of Fire-type attacks against this Pokemon is halved, and any burn damage taken is 1/16 of its maximum HP, rounded down.", shortDesc: "The power of Fire-type attacks against this Pokemon is halved; burn damage halved.", onBasePowerPriority: 7, onSourceBasePower: function (basePower, attacker, defender, move) { if (move.type === 'Fire') { return this.chainModify(0.5); } }, onDamage: function (damage, target, source, effect) { if (effect && effect.id === 'brn') { return damage / 2; } }, id: "heatproof", name: "Heatproof", rating: 2.5, num: 85 }, "heavymetal": { shortDesc: "This Pokemon's weight is doubled.", onModifyWeight: function (weight) { return weight * 2; }, id: "heavymetal", name: "Heavy Metal", rating: -1, num: 134 }, "honeygather": { shortDesc: "No competitive use.", id: "honeygather", name: "Honey Gather", rating: 0, num: 118 }, "hugepower": { shortDesc: "This Pokemon's Attack is doubled.", onModifyAtkPriority: 5, onModifyAtk: function (atk) { return this.chainModify(2); }, id: "hugepower", name: "Huge Power", rating: 5, num: 37 }, "hustle": { desc: "This Pokemon's Attack is multiplied by 1.5 and the accuracy of its physical attacks is multiplied by 0.8.", shortDesc: "This Pokemon's Attack is 1.5x and accuracy of its physical attacks is 0.8x.", // This should be applied directly to the stat as opposed to chaining witht he others onModifyAtkPriority: 5, onModifyAtk: function (atk) { return this.modify(atk, 1.5); }, onModifyMove: function (move) { if (move.category === 'Physical' && typeof move.accuracy === 'number') { move.accuracy *= 0.8; } }, id: "hustle", name: "Hustle", rating: 3, num: 55 }, "hydration": { desc: "This Pokemon has its major status condition cured at the end of each turn if Rain Dance is active.", shortDesc: "This Pokemon has its status cured at the end of each turn if Rain Dance is active.", onResidualOrder: 5, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.status && this.isWeather(['raindance', 'primordialsea'])) { this.debug('hydration'); pokemon.cureStatus(); } }, id: "hydration", name: "Hydration", rating: 2, num: 93 }, "hypercutter": { shortDesc: "Prevents other Pokemon from lowering this Pokemon's Attack stat stage.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; if (boost['atk'] && boost['atk'] < 0) { boost['atk'] = 0; if (!effect.secondaries) this.add("-fail", target, "unboost", "Attack", "[from] ability: Hyper Cutter", "[of] " + target); } }, id: "hypercutter", name: "Hyper Cutter", rating: 1.5, num: 52 }, "icebody": { desc: "If Hail is active, this Pokemon restores 1/16 of its maximum HP, rounded down, at the end of each turn. This Pokemon takes no damage from Hail.", shortDesc: "If Hail is active, this Pokemon heals 1/16 of its max HP each turn; immunity to Hail.", onWeather: function (target, source, effect) { if (effect.id === 'hail') { this.heal(target.maxhp / 16); } }, onImmunity: function (type, pokemon) { if (type === 'hail') return false; }, id: "icebody", name: "Ice Body", rating: 1.5, num: 115 }, "illuminate": { shortDesc: "No competitive use.", id: "illuminate", name: "Illuminate", rating: 0, num: 35 }, "illusion": { desc: "When this Pokemon switches in, it appears as the last unfainted Pokemon in its party until it takes direct damage from another Pokemon's attack. This Pokemon's actual level and HP are displayed instead of those of the mimicked Pokemon.", shortDesc: "This Pokemon appears as the last Pokemon in the party until it takes direct damage.", onBeforeSwitchIn: function (pokemon) { pokemon.illusion = null; var i; for (i = pokemon.side.pokemon.length - 1; i > pokemon.position; i--) { if (!pokemon.side.pokemon[i]) continue; if (!pokemon.side.pokemon[i].fainted) break; } if (!pokemon.side.pokemon[i]) return; if (pokemon === pokemon.side.pokemon[i]) return; pokemon.illusion = pokemon.side.pokemon[i]; }, // illusion clearing is hardcoded in the damage function id: "illusion", name: "Illusion", rating: 4.5, num: 149 }, "immunity": { shortDesc: "This Pokemon cannot be poisoned. Gaining this Ability while poisoned cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'psn' || pokemon.status === 'tox') { pokemon.cureStatus(); } }, onImmunity: function (type) { if (type === 'psn') return false; }, id: "immunity", name: "Immunity", rating: 2, num: 17 }, "imposter": { desc: "On switch-in, this Pokemon Transforms into the opposing Pokemon that is facing it. If there is no Pokemon at that position, this Pokemon does not Transform.", shortDesc: "On switch-in, this Pokemon Transforms into the opposing Pokemon that is facing it.", onStart: function (pokemon) { var target = pokemon.side.foe.active[pokemon.side.foe.active.length - 1 - pokemon.position]; if (target) { pokemon.transformInto(target, pokemon); } }, id: "imposter", name: "Imposter", rating: 4.5, num: 150 }, "infiltrator": { desc: "This Pokemon's moves ignore substitutes and the opposing side's Reflect, Light Screen, Safeguard, and Mist.", shortDesc: "Moves ignore substitutes and opposing Reflect, Light Screen, Safeguard, and Mist.", onModifyMove: function (move) { move.infiltrates = true; }, id: "infiltrator", name: "Infiltrator", rating: 3, num: 151 }, "innerfocus": { shortDesc: "This Pokemon cannot be made to flinch.", onFlinch: false, id: "innerfocus", name: "Inner Focus", rating: 1.5, num: 39 }, "insomnia": { shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'slp') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'slp') return false; }, id: "insomnia", name: "Insomnia", rating: 2, num: 15 }, "intimidate": { desc: "On switch-in, this Pokemon lowers the Attack of adjacent opposing Pokemon by 1 stage. Pokemon behind a substitute are immune.", shortDesc: "On switch-in, this Pokemon lowers the Attack of adjacent opponents by 1 stage.", onStart: function (pokemon) { var foeactive = pokemon.side.foe.active; for (var i = 0; i < foeactive.length; i++) { if (!foeactive[i] || !this.isAdjacent(foeactive[i], pokemon)) continue; if (foeactive[i].volatiles['substitute']) { // does it give a message? this.add('-activate', foeactive[i], 'Substitute', 'ability: Intimidate', '[of] ' + pokemon); } else { this.add('-ability', pokemon, 'Intimidate', '[of] ' + foeactive[i]); this.boost({atk: -1}, foeactive[i], pokemon); } } }, id: "intimidate", name: "Intimidate", rating: 3.5, num: 22 }, "ironbarbs": { desc: "Pokemon making contact with this Pokemon lose 1/8 of their maximum HP, rounded down.", shortDesc: "Pokemon making contact with this Pokemon lose 1/8 of their max HP.", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.flags['contact']) { this.damage(source.maxhp / 8, source, target, null, true); } }, id: "ironbarbs", name: "Iron Barbs", rating: 3, num: 160 }, "ironfist": { desc: "This Pokemon's punch-based attacks have their power multiplied by 1.2.", shortDesc: "This Pokemon's punch-based attacks have 1.2x power. Sucker Punch is not boosted.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.flags['punch']) { this.debug('Iron Fist boost'); return this.chainModify(1.2); } }, id: "ironfist", name: "Iron Fist", rating: 3, num: 89 }, "justified": { shortDesc: "This Pokemon's Attack is raised by 1 stage after it is damaged by a Dark-type move.", onAfterDamage: function (damage, target, source, effect) { if (effect && effect.type === 'Dark') { this.boost({atk:1}); } }, id: "justified", name: "Justified", rating: 2, num: 154 }, "keeneye": { desc: "Prevents other Pokemon from lowering this Pokemon's accuracy stat stage. This Pokemon ignores a target's evasiveness stat stage.", shortDesc: "This Pokemon's accuracy can't be lowered by others; ignores their evasiveness stat.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; if (boost['accuracy'] && boost['accuracy'] < 0) { boost['accuracy'] = 0; if (!effect.secondaries) this.add("-fail", target, "unboost", "accuracy", "[from] ability: Keen Eye", "[of] " + target); } }, onModifyMove: function (move) { move.ignoreEvasion = true; }, id: "keeneye", name: "Keen Eye", rating: 1, num: 51 }, "klutz": { desc: "This Pokemon's held item has no effect. This Pokemon cannot use Fling successfully. Macho Brace, Power Anklet, Power Band, Power Belt, Power Bracer, Power Lens, and Power Weight still have their effects.", shortDesc: "This Pokemon's held item has no effect, except Macho Brace. Fling cannot be used.", // Item suppression implemented in BattlePokemon.ignoringItem() within battle-engine.js id: "klutz", name: "Klutz", rating: -1, num: 103 }, "leafguard": { desc: "If Sunny Day is active, this Pokemon cannot gain a major status condition and Rest will fail for it.", shortDesc: "If Sunny Day is active, this Pokemon cannot be statused and Rest will fail for it.", onSetStatus: function (pokemon) { if (this.isWeather(['sunnyday', 'desolateland'])) { return false; } }, onTryHit: function (target, source, move) { if (move && move.id === 'yawn' && this.isWeather(['sunnyday', 'desolateland'])) { return false; } }, id: "leafguard", name: "Leaf Guard", rating: 1, num: 102 }, "levitate": { desc: "This Pokemon is immune to Ground. Gravity, Ingrain, Smack Down, Thousand Arrows, and Iron Ball nullify the immunity.", shortDesc: "This Pokemon is immune to Ground; Gravity/Ingrain/Smack Down/Iron Ball nullify it.", onImmunity: function (type) { if (type === 'Ground') return false; }, id: "levitate", name: "Levitate", rating: 3.5, num: 26 }, "lightmetal": { shortDesc: "This Pokemon's weight is halved.", onModifyWeight: function (weight) { return weight / 2; }, id: "lightmetal", name: "Light Metal", rating: 1, num: 135 }, "lightningrod": { desc: "This Pokemon is immune to Electric-type moves and raises its Special Attack by 1 stage when hit by an Electric-type move. If this Pokemon is not the target of a single-target Electric-type move used by another Pokemon, this Pokemon redirects that move to itself if it is within the range of that move.", shortDesc: "This Pokemon draws Electric moves to itself to raise Sp. Atk by 1; Electric immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Electric') { if (!this.boost({spa:1})) { this.add('-immune', target, '[msg]'); } return null; } }, onAnyRedirectTargetPriority: 1, onAnyRedirectTarget: function (target, source, source2, move) { if (move.type !== 'Electric' || move.id in {firepledge:1, grasspledge:1, waterpledge:1}) return; if (this.validTarget(this.effectData.target, source, move.target)) { return this.effectData.target; } }, id: "lightningrod", name: "Lightning Rod", rating: 3.5, num: 32 }, "limber": { shortDesc: "This Pokemon cannot be paralyzed. Gaining this Ability while paralyzed cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'par') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'par') return false; }, id: "limber", name: "Limber", rating: 1.5, num: 7 }, "liquidooze": { shortDesc: "This Pokemon damages those draining HP from it for as much as they would heal.", id: "liquidooze", onSourceTryHeal: function (damage, target, source, effect) { this.debug("Heal is occurring: " + target + " <- " + source + " :: " + effect.id); var canOoze = {drain: 1, leechseed: 1}; if (canOoze[effect.id]) { this.damage(damage, null, null, null, true); return 0; } }, name: "Liquid Ooze", rating: 1.5, num: 64 }, "magicbounce": { desc: "This Pokemon blocks certain status moves and instead uses the move against the original user.", shortDesc: "This Pokemon blocks certain status moves and bounces them back to the user.", id: "magicbounce", name: "Magic Bounce", onTryHitPriority: 1, onTryHit: function (target, source, move) { if (target === source || move.hasBounced || !move.flags['reflectable']) { return; } var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; }, onAllyTryHitSide: function (target, source, move) { if (target.side === source.side || move.hasBounced || !move.flags['reflectable']) { return; } var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; }, effect: { duration: 1 }, rating: 4.5, num: 156 }, "magicguard": { desc: "This Pokemon can only be damaged by direct attacks. Curse and Substitute on use, Belly Drum, Pain Split, Struggle recoil, and confusion damage are considered direct damage.", shortDesc: "This Pokemon can only be damaged by direct attacks.", onDamage: function (damage, target, source, effect) { if (effect.effectType !== 'Move') { return false; } }, id: "magicguard", name: "Magic Guard", rating: 4.5, num: 98 }, "magician": { desc: "If this Pokemon has no item, it steals the item off a Pokemon it hits with an attack. Does not affect Doom Desire and Future Sight.", shortDesc: "If this Pokemon has no item, it steals the item off a Pokemon it hits with an attack.", onSourceHit: function (target, source, move) { if (!move || !target) return; if (target !== source && move.category !== 'Status') { if (source.item) return; var yourItem = target.takeItem(source); if (!yourItem) return; if (!source.setItem(yourItem)) { target.item = yourItem.id; // bypass setItem so we don't break choicelock or anything return; } this.add('-item', source, yourItem, '[from] ability: Magician', '[of] ' + target); } }, id: "magician", name: "Magician", rating: 1.5, num: 170 }, "magmaarmor": { shortDesc: "This Pokemon cannot be frozen. Gaining this Ability while frozen cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'frz') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'frz') return false; }, id: "magmaarmor", name: "Magma Armor", rating: 0.5, num: 40 }, "magnetpull": { desc: "Prevents adjacent opposing Steel-type Pokemon from choosing to switch out unless they are immune to trapping.", shortDesc: "Prevents adjacent Steel-type foes from choosing to switch.", onFoeModifyPokemon: function (pokemon) { if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, this.effectData.target)) { pokemon.tryTrap(true); } }, onFoeMaybeTrapPokemon: function (pokemon, source) { if (!source) source = this.effectData.target; if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, source)) { pokemon.maybeTrapped = true; } }, id: "magnetpull", name: "Magnet Pull", rating: 4.5, num: 42 }, "marvelscale": { desc: "If this Pokemon has a major status condition, its Defense is multiplied by 1.5.", shortDesc: "If this Pokemon is statused, its Defense is 1.5x.", onModifyDefPriority: 6, onModifyDef: function (def, pokemon) { if (pokemon.status) { return this.chainModify(1.5); } }, id: "marvelscale", name: "Marvel Scale", rating: 2.5, num: 63 }, "megalauncher": { desc: "This Pokemon's pulse moves have their power multiplied by 1.5. Heal Pulse restores 3/4 of a target's maximum HP, rounded half down.", shortDesc: "This Pokemon's pulse moves have 1.5x power. Heal Pulse heals 3/4 target's max HP.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.flags['pulse']) { return this.chainModify(1.5); } }, id: "megalauncher", name: "Mega Launcher", rating: 3.5, num: 178 }, "minus": { desc: "If an active ally has this Ability or the Ability Plus, this Pokemon's Special Attack is multiplied by 1.5.", shortDesc: "If an active ally has this Ability or the Ability Plus, this Pokemon's Sp. Atk is 1.5x.", onModifySpAPriority: 5, onModifySpA: function (spa, pokemon) { var allyActive = pokemon.side.active; if (allyActive.length === 1) { return; } for (var i = 0; i < allyActive.length; i++) { if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) { return this.chainModify(1.5); } } }, id: "minus", name: "Minus", rating: 0, num: 58 }, "moldbreaker": { shortDesc: "This Pokemon's moves and their effects ignore the Abilities of other Pokemon.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Mold Breaker'); }, stopAttackEvents: true, id: "moldbreaker", name: "Mold Breaker", rating: 3.5, num: 104 }, "moody": { desc: "This Pokemon has a random stat raised by 2 stages and another stat lowered by 1 stage at the end of each turn.", shortDesc: "Raises a random stat by 2 and lowers another stat by 1 at the end of each turn.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { var stats = [], i = ''; var boost = {}; for (var i in pokemon.boosts) { if (pokemon.boosts[i] < 6) { stats.push(i); } } if (stats.length) { i = stats[this.random(stats.length)]; boost[i] = 2; } stats = []; for (var j in pokemon.boosts) { if (pokemon.boosts[j] > -6 && j !== i) { stats.push(j); } } if (stats.length) { i = stats[this.random(stats.length)]; boost[i] = -1; } this.boost(boost); }, id: "moody", name: "Moody", rating: 5, num: 141 }, "motordrive": { desc: "This Pokemon is immune to Electric-type moves and raises its Speed by 1 stage when hit by an Electric-type move.", shortDesc: "This Pokemon's Speed is raised 1 stage if hit by an Electric move; Electric immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Electric') { if (!this.boost({spe:1})) { this.add('-immune', target, '[msg]'); } return null; } }, id: "motordrive", name: "Motor Drive", rating: 3, num: 78 }, "moxie": { desc: "This Pokemon's Attack is raised by 1 stage if it attacks and knocks out another Pokemon.", shortDesc: "This Pokemon's Attack is raised by 1 stage if it attacks and KOes another Pokemon.", onSourceFaint: function (target, source, effect) { if (effect && effect.effectType === 'Move') { this.boost({atk:1}, source); } }, id: "moxie", name: "Moxie", rating: 3.5, num: 153 }, "multiscale": { shortDesc: "If this Pokemon is at full HP, damage taken from attacks is halved.", onSourceModifyDamage: function (damage, source, target, move) { if (target.hp >= target.maxhp) { this.debug('Multiscale weaken'); return this.chainModify(0.5); } }, id: "multiscale", name: "Multiscale", rating: 4, num: 136 }, "multitype": { shortDesc: "If this Pokemon is an Arceus, its type changes to match its held Plate.", // Multitype's type-changing itself is implemented in statuses.js id: "multitype", name: "Multitype", rating: 4, num: 121 }, "mummy": { desc: "Pokemon making contact with this Pokemon have their Ability changed to Mummy. Does not affect the Abilities Multitype or Stance Change.", shortDesc: "Pokemon making contact with this Pokemon have their Ability changed to Mummy.", id: "mummy", name: "Mummy", onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.flags['contact']) { var oldAbility = source.setAbility('mummy', source, 'mummy', true); if (oldAbility) { this.add('-endability', source, oldAbility, '[from] Mummy'); this.add('-ability', source, 'Mummy', '[from] Mummy'); } } }, rating: 2, num: 152 }, "naturalcure": { shortDesc: "This Pokemon has its major status condition cured when it switches out.", onSwitchOut: function (pokemon) { pokemon.setStatus(''); }, id: "naturalcure", name: "Natural Cure", rating: 3.5, num: 30 }, "noguard": { shortDesc: "Every move used by or against this Pokemon will always hit.", onAnyAccuracy: function (accuracy, target, source, move) { if (move && (source === this.effectData.target || target === this.effectData.target)) { return true; } return accuracy; }, id: "noguard", name: "No Guard", rating: 4, num: 99 }, "normalize": { desc: "This Pokemon's moves are changed to be Normal type. This effect comes before other effects that change a move's type.", shortDesc: "This Pokemon's moves are changed to be Normal type.", onModifyMovePriority: 1, onModifyMove: function (move) { if (move.id !== 'struggle') { move.type = 'Normal'; } }, id: "normalize", name: "Normalize", rating: -1, num: 96 }, "oblivious": { desc: "This Pokemon cannot be infatuated or taunted. Gaining this Ability while affected cures it.", shortDesc: "This Pokemon cannot be infatuated or taunted. Gaining this Ability cures it.", onUpdate: function (pokemon) { if (pokemon.volatiles['attract']) { pokemon.removeVolatile('attract'); this.add('-end', pokemon, 'move: Attract', '[from] ability: Oblivious'); } if (pokemon.volatiles['taunt']) { pokemon.removeVolatile('taunt'); // Taunt's volatile already sends the -end message when removed } }, onImmunity: function (type, pokemon) { if (type === 'attract') { this.add('-immune', pokemon, '[from] Oblivious'); return false; } }, onTryHit: function (pokemon, target, move) { if (move.id === 'captivate' || move.id === 'taunt') { this.add('-immune', pokemon, '[msg]', '[from] Oblivious'); return null; } }, id: "oblivious", name: "Oblivious", rating: 1, num: 12 }, "overcoat": { shortDesc: "This Pokemon is immune to powder moves and damage from Sandstorm or Hail.", onImmunity: function (type, pokemon) { if (type === 'sandstorm' || type === 'hail' || type === 'powder') return false; }, id: "overcoat", name: "Overcoat", rating: 2.5, num: 142 }, "overgrow": { desc: "When this Pokemon has 1/3 or less of its maximum HP, its attacking stat is multiplied by 1.5 while using a Grass-type attack.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Grass attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) { this.debug('Overgrow boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) { this.debug('Overgrow boost'); return this.chainModify(1.5); } }, id: "overgrow", name: "Overgrow", rating: 2, num: 65 }, "owntempo": { shortDesc: "This Pokemon cannot be confused. Gaining this Ability while confused cures it.", onUpdate: function (pokemon) { if (pokemon.volatiles['confusion']) { pokemon.removeVolatile('confusion'); } }, onImmunity: function (type, pokemon) { if (type === 'confusion') { this.add('-immune', pokemon, 'confusion'); return false; } }, id: "owntempo", name: "Own Tempo", rating: 1, num: 20 }, "parentalbond": { desc: "This Pokemon's damaging moves become multi-hit moves that hit twice. The second hit has its damage halved. Does not affect multi-hit moves or moves that have multiple targets.", shortDesc: "This Pokemon's damaging moves hit twice. The second hit has its damage halved.", onModifyMove: function (move, pokemon, target) { if (move.category !== 'Status' && !move.selfdestruct && !move.multihit && ((target.side && target.side.active.length < 2) || move.target in {any:1, normal:1, randomNormal:1})) { move.multihit = 2; pokemon.addVolatile('parentalbond'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower) { if (this.effectData.hit) { return this.chainModify(0.5); } else { this.effectData.hit = true; } } }, id: "parentalbond", name: "Parental Bond", rating: 5, num: 184 }, "pickup": { shortDesc: "If this Pokemon has no item, it finds one used by an adjacent Pokemon this turn.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.item) return; var pickupTargets = []; var target; for (var i = 0; i < pokemon.side.active.length; i++) { target = pokemon.side.active[i]; if (target.lastItem && target.usedItemThisTurn && this.isAdjacent(pokemon, target)) { pickupTargets.push(target); } } for (var i = 0; i < pokemon.side.foe.active.length; i++) { target = pokemon.side.foe.active[i]; if (target.lastItem && target.usedItemThisTurn && this.isAdjacent(pokemon, target)) { pickupTargets.push(target); } } if (!pickupTargets.length) return; target = pickupTargets[this.random(pickupTargets.length)]; pokemon.setItem(target.lastItem); target.lastItem = ''; var item = pokemon.getItem(); this.add('-item', pokemon, item, '[from] Pickup'); if (item.isBerry) pokemon.update(); }, id: "pickup", name: "Pickup", rating: 0.5, num: 53 }, "pickpocket": { desc: "If this Pokemon has no item, it steals the item off a Pokemon that makes contact with it. This effect applies after all hits from a multi-hit move; Sheer Force prevents it from activating if the move has a secondary effect.", shortDesc: "If this Pokemon has no item, it steals the item off a Pokemon making contact with it.", onAfterMoveSecondary: function (target, source, move) { if (source && source !== target && move && move.flags['contact']) { if (target.item) { return; } var yourItem = source.takeItem(target); if (!yourItem) { return; } if (!target.setItem(yourItem)) { source.item = yourItem.id; return; } this.add('-item', target, yourItem, '[from] ability: Pickpocket', '[of] ' + source); } }, id: "pickpocket", name: "Pickpocket", rating: 1, num: 124 }, "pixilate": { desc: "This Pokemon's Normal-type moves become Fairy-type moves and have their power multiplied by 1.3. This effect comes after other effects that change a move's type, but before Ion Deluge and Electrify's effects.", shortDesc: "This Pokemon's Normal-type moves become Fairy type and have 1.3x power.", onModifyMovePriority: -1, onModifyMove: function (move, pokemon) { if (move.type === 'Normal' && move.id !== 'naturalgift') { move.type = 'Fairy'; if (move.category !== 'Status') pokemon.addVolatile('pixilate'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); } }, id: "pixilate", name: "Pixilate", rating: 4, num: 182 }, "plus": { desc: "If an active ally has this Ability or the Ability Minus, this Pokemon's Special Attack is multiplied by 1.5.", shortDesc: "If an active ally has this Ability or the Ability Minus, this Pokemon's Sp. Atk is 1.5x.", onModifySpAPriority: 5, onModifySpA: function (spa, pokemon) { var allyActive = pokemon.side.active; if (allyActive.length === 1) { return; } for (var i = 0; i < allyActive.length; i++) { if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) { return this.chainModify(1.5); } } }, id: "plus", name: "Plus", rating: 0, num: 57 }, "poisonheal": { desc: "If this Pokemon is poisoned, it restores 1/8 of its maximum HP, rounded down, at the end of each turn instead of losing HP.", shortDesc: "This Pokemon is healed by 1/8 of its max HP each turn when poisoned; no HP loss.", onDamage: function (damage, target, source, effect) { if (effect.id === 'psn' || effect.id === 'tox') { this.heal(target.maxhp / 8); return false; } }, id: "poisonheal", name: "Poison Heal", rating: 4, num: 90 }, "poisonpoint": { shortDesc: "30% chance a Pokemon making contact with this Pokemon will be poisoned.", onAfterDamage: function (damage, target, source, move) { if (move && move.flags['contact']) { if (this.random(10) < 3) { source.trySetStatus('psn', target, move); } } }, id: "poisonpoint", name: "Poison Point", rating: 2, num: 38 }, "poisontouch": { shortDesc: "This Pokemon's contact moves have a 30% chance of poisoning.", // upokecenter says this is implemented as an added secondary effect onModifyMove: function (move) { if (!move || !move.flags['contact']) return; if (!move.secondaries) { move.secondaries = []; } move.secondaries.push({ chance: 30, status: 'psn' }); }, id: "poisontouch", name: "Poison Touch", rating: 2, num: 143 }, "prankster": { shortDesc: "This Pokemon's non-damaging moves have their priority increased by 1.", onModifyPriority: function (priority, pokemon, target, move) { if (move && move.category === 'Status') { return priority + 1; } }, id: "prankster", name: "Prankster", rating: 4.5, num: 158 }, "pressure": { desc: "If this Pokemon is the target of an opposing Pokemon's move, that move loses one additional PP.", shortDesc: "If this Pokemon is the target of a foe's move, that move loses one additional PP.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Pressure'); }, onSourceDeductPP: function (pp, target, source) { if (target.side === source.side) return; return pp + 1; }, id: "pressure", name: "Pressure", rating: 1.5, num: 46 }, "primordialsea": { desc: "On switch-in, the weather becomes heavy rain that prevents damaging Fire-type moves from executing, in addition to all the effects of Rain Dance. This weather remains in effect until this Ability is no longer active for any Pokemon, or the weather is changed by Delta Stream or Desolate Land.", shortDesc: "On switch-in, heavy rain begins until this Ability is not active in battle.", onStart: function (source) { this.setWeather('primordialsea'); }, onAnySetWeather: function (target, source, weather) { if (this.getWeather().id === 'primordialsea' && !(weather.id in {desolateland:1, primordialsea:1, deltastream:1})) return false; }, onEnd: function (pokemon) { if (this.weatherData.source !== pokemon) return; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var target = this.sides[i].active[j]; if (target === pokemon) continue; if (target && target.hp && target.hasAbility('primordialsea')) { this.weatherData.source = target; return; } } } this.clearWeather(); }, id: "primordialsea", name: "Primordial Sea", rating: 5, num: 189 }, "protean": { desc: "This Pokemon's type changes to match the type of the move it is about to use. This effect comes after all effects that change a move's type.", shortDesc: "This Pokemon's type changes to match the type of the move it is about to use.", onPrepareHit: function (source, target, move) { var type = move.type; if (type && type !== '???' && source.getTypes().join() !== type) { if (!source.setType(type)) return; this.add('-start', source, 'typechange', type, '[from] Protean'); } }, id: "protean", name: "Protean", rating: 4, num: 168 }, "purepower": { shortDesc: "This Pokemon's Attack is doubled.", onModifyAtkPriority: 5, onModifyAtk: function (atk) { return this.chainModify(2); }, id: "purepower", name: "Pure Power", rating: 5, num: 74 }, "quickfeet": { desc: "If this Pokemon has a major status condition, its Speed is multiplied by 1.5; the Speed drop from paralysis is ignored.", shortDesc: "If this Pokemon is statused, its Speed is 1.5x; ignores Speed drop from paralysis.", onModifySpe: function (speMod, pokemon) { if (pokemon.status) { return this.chain(speMod, 1.5); } }, id: "quickfeet", name: "Quick Feet", rating: 2.5, num: 95 }, "raindish": { desc: "If Rain Dance is active, this Pokemon restores 1/16 of its maximum HP, rounded down, at the end of each turn.", shortDesc: "If Rain Dance is active, this Pokemon heals 1/16 of its max HP each turn.", onWeather: function (target, source, effect) { if (effect.id === 'raindance' || effect.id === 'primordialsea') { this.heal(target.maxhp / 16); } }, id: "raindish", name: "Rain Dish", rating: 1.5, num: 44 }, "rattled": { desc: "This Pokemon's Speed is raised by 1 stage if hit by a Bug-, Dark-, or Ghost-type attack.", shortDesc: "This Pokemon's Speed is raised 1 stage if hit by a Bug-, Dark-, or Ghost-type attack.", onAfterDamage: function (damage, target, source, effect) { if (effect && (effect.type === 'Dark' || effect.type === 'Bug' || effect.type === 'Ghost')) { this.boost({spe:1}); } }, id: "rattled", name: "Rattled", rating: 1.5, num: 155 }, "reckless": { desc: "This Pokemon's attacks with recoil or crash damage have their power multiplied by 1.2. Does not affect Struggle.", shortDesc: "This Pokemon's attacks with recoil or crash damage have 1.2x power; not Struggle.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.recoil || move.hasCustomRecoil) { this.debug('Reckless boost'); return this.chainModify(1.2); } }, id: "reckless", name: "Reckless", rating: 3, num: 120 }, "refrigerate": { desc: "This Pokemon's Normal-type moves become Ice-type moves and have their power multiplied by 1.3. This effect comes after other effects that change a move's type, but before Ion Deluge and Electrify's effects.", shortDesc: "This Pokemon's Normal-type moves become Ice type and have 1.3x power.", onModifyMovePriority: -1, onModifyMove: function (move, pokemon) { if (move.type === 'Normal' && move.id !== 'naturalgift') { move.type = 'Ice'; if (move.category !== 'Status') pokemon.addVolatile('refrigerate'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); } }, id: "refrigerate", name: "Refrigerate", rating: 4, num: 174 }, "regenerator": { shortDesc: "This Pokemon restores 1/3 of its maximum HP, rounded down, when it switches out.", onSwitchOut: function (pokemon) { pokemon.heal(pokemon.maxhp / 3); }, id: "regenerator", name: "Regenerator", rating: 4, num: 144 }, "rivalry": { desc: "This Pokemon's attacks have their power multiplied by 1.25 against targets of the same gender or multiplied by 0.75 against targets of the opposite gender. There is no modifier if either this Pokemon or the target is genderless.", shortDesc: "This Pokemon's attacks do 1.25x on same gender targets; 0.75x on opposite gender.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (attacker.gender && defender.gender) { if (attacker.gender === defender.gender) { this.debug('Rivalry boost'); return this.chainModify(1.25); } else { this.debug('Rivalry weaken'); return this.chainModify(0.75); } } }, id: "rivalry", name: "Rivalry", rating: 0.5, num: 79 }, "rockhead": { desc: "This Pokemon does not take recoil damage besides Struggle, Life Orb, and crash damage.", shortDesc: "This Pokemon does not take recoil damage besides Struggle/Life Orb/crash damage.", onDamage: function (damage, target, source, effect) { if (effect.id === 'recoil' && this.activeMove.id !== 'struggle') return null; }, id: "rockhead", name: "Rock Head", rating: 3, num: 69 }, "roughskin": { desc: "Pokemon making contact with this Pokemon lose 1/8 of their maximum HP, rounded down.", shortDesc: "Pokemon making contact with this Pokemon lose 1/8 of their max HP.", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.flags['contact']) { this.damage(source.maxhp / 8, source, target, null, true); } }, id: "roughskin", name: "Rough Skin", rating: 3, num: 24 }, "runaway": { shortDesc: "No competitive use.", id: "runaway", name: "Run Away", rating: 0, num: 50 }, "sandforce": { desc: "If Sandstorm is active, this Pokemon's Ground-, Rock-, and Steel-type attacks have their power multiplied by 1.3. This Pokemon takes no damage from Sandstorm.", shortDesc: "This Pokemon's Ground/Rock/Steel attacks do 1.3x in Sandstorm; immunity to it.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (this.isWeather('sandstorm')) { if (move.type === 'Rock' || move.type === 'Ground' || move.type === 'Steel') { this.debug('Sand Force boost'); return this.chainModify([0x14CD, 0x1000]); // The Sand Force modifier is slightly higher than the normal 1.3 (0x14CC) } } }, onImmunity: function (type, pokemon) { if (type === 'sandstorm') return false; }, id: "sandforce", name: "Sand Force", rating: 2, num: 159 }, "sandrush": { desc: "If Sandstorm is active, this Pokemon's Speed is doubled. This Pokemon takes no damage from Sandstorm.", shortDesc: "If Sandstorm is active, this Pokemon's Speed is doubled; immunity to Sandstorm.", onModifySpe: function (speMod, pokemon) { if (this.isWeather('sandstorm')) { return this.chain(speMod, 2); } }, onImmunity: function (type, pokemon) { if (type === 'sandstorm') return false; }, id: "sandrush", name: "Sand Rush", rating: 2.5, num: 146 }, "sandstream": { shortDesc: "On switch-in, this Pokemon summons Sandstorm.", onStart: function (source) { this.setWeather('sandstorm'); }, id: "sandstream", name: "Sand Stream", rating: 4, num: 45 }, "sandveil": { desc: "If Sandstorm is active, this Pokemon's evasiveness is multiplied by 1.25. This Pokemon takes no damage from Sandstorm.", shortDesc: "If Sandstorm is active, this Pokemon's evasiveness is 1.25x; immunity to Sandstorm.", onImmunity: function (type, pokemon) { if (type === 'sandstorm') return false; }, onModifyAccuracy: function (accuracy) { if (typeof accuracy !== 'number') return; if (this.isWeather('sandstorm')) { this.debug('Sand Veil - decreasing accuracy'); return accuracy * 0.8; } }, id: "sandveil", name: "Sand Veil", rating: 1.5, num: 8 }, "sapsipper": { desc: "This Pokemon is immune to Grass-type moves and raises its Attack by 1 stage when hit by a Grass-type move.", shortDesc: "This Pokemon's Attack is raised 1 stage if hit by a Grass move; Grass immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Grass') { if (!this.boost({atk:1})) { this.add('-immune', target, '[msg]'); } return null; } }, onAllyTryHitSide: function (target, source, move) { if (target === this.effectData.target || target.side !== source.side) return; if (move.type === 'Grass') { this.boost({atk:1}, this.effectData.target); } }, id: "sapsipper", name: "Sap Sipper", rating: 3.5, num: 157 }, "scrappy": { shortDesc: "This Pokemon can hit Ghost types with Normal- and Fighting-type moves.", onModifyMovePriority: -5, onModifyMove: function (move) { if (!move.ignoreImmunity) move.ignoreImmunity = {}; if (move.ignoreImmunity !== true) { move.ignoreImmunity['Fighting'] = true; move.ignoreImmunity['Normal'] = true; } }, id: "scrappy", name: "Scrappy", rating: 3, num: 113 }, "serenegrace": { shortDesc: "This Pokemon's moves have their secondary effect chance doubled.", onModifyMove: function (move) { if (move.secondaries && move.id !== 'secretpower') { this.debug('doubling secondary chance'); for (var i = 0; i < move.secondaries.length; i++) { move.secondaries[i].chance *= 2; } } }, id: "serenegrace", name: "Serene Grace", rating: 4, num: 32 }, "shadowtag": { desc: "Prevents adjacent opposing Pokemon from choosing to switch out unless they are immune to trapping or also have this Ability.", shortDesc: "Prevents adjacent foes from choosing to switch unless they also have this Ability.", onFoeModifyPokemon: function (pokemon) { if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, this.effectData.target)) { pokemon.tryTrap(true); } }, onFoeMaybeTrapPokemon: function (pokemon, source) { if (!source) source = this.effectData.target; if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, source)) { pokemon.maybeTrapped = true; } }, id: "shadowtag", name: "Shadow Tag", rating: 5, num: 23 }, "shedskin": { desc: "This Pokemon has a 33% chance to have its major status condition cured at the end of each turn.", shortDesc: "This Pokemon has a 33% chance to have its status cured at the end of each turn.", onResidualOrder: 5, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.hp && pokemon.status && this.random(3) === 0) { this.debug('shed skin'); this.add('-activate', pokemon, 'ability: Shed Skin'); pokemon.cureStatus(); } }, id: "shedskin", name: "Shed Skin", rating: 3.5, num: 61 }, "sheerforce": { desc: "This Pokemon's attacks with secondary effects have their power multiplied by 1.3, but the secondary effects are removed.", shortDesc: "This Pokemon's attacks with secondary effects have 1.3x power; nullifies the effects.", onModifyMove: function (move, pokemon) { if (move.secondaries) { delete move.secondaries; // Actual negation of `AfterMoveSecondary` effects implemented in scripts.js pokemon.addVolatile('sheerforce'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); // The Sheer Force modifier is slightly higher than the normal 1.3 (0x14CC) } }, id: "sheerforce", name: "Sheer Force", rating: 4, num: 125 }, "shellarmor": { shortDesc: "This Pokemon cannot be struck by a critical hit.", onCriticalHit: false, id: "shellarmor", name: "Shell Armor", rating: 1, num: 75 }, "shielddust": { shortDesc: "This Pokemon is not affected by the secondary effect of another Pokemon's attack.", onTrySecondaryHit: function () { this.debug('Shield Dust prevent secondary'); return null; }, id: "shielddust", name: "Shield Dust", rating: 2.5, num: 19 }, "simple": { shortDesc: "If this Pokemon's stat stages are raised or lowered, the effect is doubled instead.", onBoost: function (boost) { for (var i in boost) { boost[i] *= 2; } }, id: "simple", name: "Simple", rating: 4, num: 86 }, "skilllink": { shortDesc: "This Pokemon's multi-hit attacks always hit the maximum number of times.", onModifyMove: function (move) { if (move.multihit && move.multihit.length) { move.multihit = move.multihit[1]; } }, id: "skilllink", name: "Skill Link", rating: 4, num: 92 }, "slowstart": { shortDesc: "On switch-in, this Pokemon's Attack and Speed are halved for 5 turns.", onStart: function (pokemon) { pokemon.addVolatile('slowstart'); }, onEnd: function (pokemon) { delete pokemon.volatiles['slowstart']; this.add('-end', pokemon, 'Slow Start', '[silent]'); }, effect: { duration: 5, onStart: function (target) { this.add('-start', target, 'Slow Start'); }, onModifyAtkPriority: 5, onModifyAtk: function (atk, pokemon) { return this.chainModify(0.5); }, onModifySpe: function (speMod, pokemon) { return this.chain(speMod, 0.5); }, onEnd: function (target) { this.add('-end', target, 'Slow Start'); } }, id: "slowstart", name: "Slow Start", rating: -2, num: 112 }, "sniper": { shortDesc: "If this Pokemon strikes with a critical hit, the damage is multiplied by 1.5.", onModifyDamage: function (damage, source, target, move) { if (move.crit) { this.debug('Sniper boost'); return this.chainModify(1.5); } }, id: "sniper", name: "Sniper", rating: 1, num: 97 }, "snowcloak": { desc: "If Hail is active, this Pokemon's evasiveness is multiplied by 1.25. This Pokemon takes no damage from Hail.", shortDesc: "If Hail is active, this Pokemon's evasiveness is 1.25x; immunity to Hail.", onImmunity: function (type, pokemon) { if (type === 'hail') return false; }, onModifyAccuracy: function (accuracy) { if (typeof accuracy !== 'number') return; if (this.isWeather('hail')) { this.debug('Snow Cloak - decreasing accuracy'); return accuracy * 0.8; } }, id: "snowcloak", name: "Snow Cloak", rating: 1.5, num: 81 }, "snowwarning": { shortDesc: "On switch-in, this Pokemon summons Hail.", onStart: function (source) { this.setWeather('hail'); }, id: "snowwarning", name: "Snow Warning", rating: 3.5, num: 117 }, "solarpower": { desc: "If Sunny Day is active, this Pokemon's Special Attack is multiplied by 1.5 and it loses 1/8 of its maximum HP, rounded down, at the end of each turn.", shortDesc: "If Sunny Day is active, this Pokemon's Sp. Atk is 1.5x; loses 1/8 max HP per turn.", onModifySpAPriority: 5, onModifySpA: function (spa, pokemon) { if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chainModify(1.5); } }, onWeather: function (target, source, effect) { if (effect.id === 'sunnyday' || effect.id === 'desolateland') { this.damage(target.maxhp / 8); } }, id: "solarpower", name: "Solar Power", rating: 1.5, num: 94 }, "solidrock": { shortDesc: "This Pokemon receives 3/4 damage from supereffective attacks.", onSourceModifyDamage: function (damage, source, target, move) { if (move.typeMod > 0) { this.debug('Solid Rock neutralize'); return this.chainModify(0.75); } }, id: "solidrock", name: "Solid Rock", rating: 3, num: 116 }, "soundproof": { shortDesc: "This Pokemon is immune to sound-based moves, including Heal Bell.", onTryHit: function (target, source, move) { if (target !== source && move.flags['sound']) { this.add('-immune', target, '[msg]'); return null; } }, id: "soundproof", name: "Soundproof", rating: 2, num: 43 }, "speedboost": { desc: "This Pokemon's Speed is raised by 1 stage at the end of each full turn it has been on the field.", shortDesc: "This Pokemon's Speed is raised 1 stage at the end of each full turn on the field.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.activeTurns) { this.boost({spe:1}); } }, id: "speedboost", name: "Speed Boost", rating: 4.5, num: 3 }, "stall": { shortDesc: "This Pokemon moves last among Pokemon using the same or greater priority moves.", onModifyPriority: function (priority) { return priority - 0.1; }, id: "stall", name: "Stall", rating: -1, num: 100 }, "stancechange": { desc: "If this Pokemon is an Aegislash, it changes to Blade Forme before attempting to use an attacking move, and changes to Shield Forme before attempting to use King's Shield.", shortDesc: "If Aegislash, changes Forme to Blade before attacks and Shield before King's Shield.", onBeforeMovePriority: 11, onBeforeMove: function (attacker, defender, move) { if (attacker.template.baseSpecies !== 'Aegislash') return; if (move.category === 'Status' && move.id !== 'kingsshield') return; var targetSpecies = (move.id === 'kingsshield' ? 'Aegislash' : 'Aegislash-Blade'); if (attacker.template.species !== targetSpecies && attacker.formeChange(targetSpecies)) { this.add('-formechange', attacker, targetSpecies); } }, id: "stancechange", name: "Stance Change", rating: 5, num: 176 }, "static": { shortDesc: "30% chance a Pokemon making contact with this Pokemon will be paralyzed.", onAfterDamage: function (damage, target, source, effect) { if (effect && effect.flags['contact']) { if (this.random(10) < 3) { source.trySetStatus('par', target, effect); } } }, id: "static", name: "Static", rating: 2, num: 9 }, "steadfast": { shortDesc: "If this Pokemon flinches, its Speed is raised by 1 stage.", onFlinch: function (pokemon) { this.boost({spe: 1}); }, id: "steadfast", name: "Steadfast", rating: 1, num: 80 }, "stench": { shortDesc: "This Pokemon's attacks without a chance to flinch have a 10% chance to flinch.", onModifyMove: function (move) { if (move.category !== "Status") { this.debug('Adding Stench flinch'); if (!move.secondaries) move.secondaries = []; for (var i = 0; i < move.secondaries.length; i++) { if (move.secondaries[i].volatileStatus === 'flinch') return; } move.secondaries.push({ chance: 10, volatileStatus: 'flinch' }); } }, id: "stench", name: "Stench", rating: 0.5, num: 1 }, "stickyhold": { shortDesc: "This Pokemon cannot lose its held item due to another Pokemon's attack.", onTakeItem: function (item, pokemon, source) { if (this.suppressingAttackEvents() && pokemon !== this.activePokemon) return; if ((source && source !== pokemon) || this.activeMove.id === 'knockoff') { this.add('-activate', pokemon, 'ability: Sticky Hold'); return false; } }, id: "stickyhold", name: "Sticky Hold", rating: 1.5, num: 60 }, "stormdrain": { desc: "This Pokemon is immune to Water-type moves and raises its Special Attack by 1 stage when hit by a Water-type move. If this Pokemon is not the target of a single-target Water-type move used by another Pokemon, this Pokemon redirects that move to itself if it is within the range of that move.", shortDesc: "This Pokemon draws Water moves to itself to raise Sp. Atk by 1; Water immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Water') { if (!this.boost({spa:1})) { this.add('-immune', target, '[msg]'); } return null; } }, onAnyRedirectTargetPriority: 1, onAnyRedirectTarget: function (target, source, source2, move) { if (move.type !== 'Water' || move.id in {firepledge:1, grasspledge:1, waterpledge:1}) return; if (this.validTarget(this.effectData.target, source, move.target)) { move.accuracy = true; return this.effectData.target; } }, id: "stormdrain", name: "Storm Drain", rating: 3.5, num: 114 }, "strongjaw": { desc: "This Pokemon's bite-based attacks have their power multiplied by 1.5.", shortDesc: "This Pokemon's bite-based attacks have 1.5x power. Bug Bite is not boosted.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.flags['bite']) { return this.chainModify(1.5); } }, id: "strongjaw", name: "Strong Jaw", rating: 3, num: 173 }, "sturdy": { desc: "If this Pokemon is at full HP, it survives one hit with at least 1 HP. OHKO moves fail when used against this Pokemon.", shortDesc: "If this Pokemon is at full HP, it survives one hit with at least 1 HP. Immune to OHKO.", onTryHit: function (pokemon, target, move) { if (move.ohko) { this.add('-immune', pokemon, '[msg]'); return null; } }, onDamagePriority: -100, onDamage: function (damage, target, source, effect) { if (target.hp === target.maxhp && damage >= target.hp && effect && effect.effectType === 'Move') { this.add('-activate', target, 'Sturdy'); return target.hp - 1; } }, id: "sturdy", name: "Sturdy", rating: 3, num: 5 }, "suctioncups": { shortDesc: "This Pokemon cannot be forced to switch out by another Pokemon's attack or item.", onDragOutPriority: 1, onDragOut: function (pokemon) { this.add('-activate', pokemon, 'ability: Suction Cups'); return null; }, id: "suctioncups", name: "Suction Cups", rating: 2, num: 21 }, "superluck": { shortDesc: "This Pokemon's critical hit ratio is raised by 1 stage.", onModifyMove: function (move) { move.critRatio++; }, id: "superluck", name: "Super Luck", rating: 1.5, num: 105 }, "swarm": { desc: "When this Pokemon has 1/3 or less of its maximum HP, rounded down, its attacking stat is multiplied by 1.5 while using a Bug-type attack.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Bug attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) { this.debug('Swarm boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) { this.debug('Swarm boost'); return this.chainModify(1.5); } }, id: "swarm", name: "Swarm", rating: 2, num: 68 }, "sweetveil": { shortDesc: "This Pokemon and its allies cannot fall asleep.", id: "sweetveil", name: "Sweet Veil", onAllySetStatus: function (status, target, source, effect) { if (status.id === 'slp') { this.debug('Sweet Veil interrupts sleep'); return false; } }, onAllyTryHit: function (target, source, move) { if (move && move.id === 'yawn') { this.debug('Sweet Veil blocking yawn'); return false; } }, rating: 2, num: 175 }, "swiftswim": { shortDesc: "If Rain Dance is active, this Pokemon's Speed is doubled.", onModifySpe: function (speMod, pokemon) { if (this.isWeather(['raindance', 'primordialsea'])) { return this.chain(speMod, 2); } }, id: "swiftswim", name: "Swift Swim", rating: 2.5, num: 33 }, "symbiosis": { desc: "If an ally uses its item, this Pokemon gives its item to that ally immediately. Does not activate if the ally's item was stolen or knocked off.", shortDesc: "If an ally uses its item, this Pokemon gives its item to that ally immediately.", onAllyAfterUseItem: function (item, pokemon) { var sourceItem = this.effectData.target.getItem(); var noSharing = sourceItem.onTakeItem && sourceItem.onTakeItem(sourceItem, pokemon) === false; if (!sourceItem || noSharing) { return; } sourceItem = this.effectData.target.takeItem(); if (!sourceItem) { return; } if (pokemon.setItem(sourceItem)) { this.add('-activate', pokemon, 'ability: Symbiosis', sourceItem, '[of] ' + this.effectData.target); } }, id: "symbiosis", name: "Symbiosis", rating: 0, num: 180 }, "synchronize": { desc: "If another Pokemon burns, paralyzes, poisons, or badly poisons this Pokemon, that Pokemon receives the same major status condition.", shortDesc: "If another Pokemon burns/poisons/paralyzes this Pokemon, it also gets that status.", onAfterSetStatus: function (status, target, source, effect) { if (!source || source === target) return; if (effect && effect.id === 'toxicspikes') return; if (status.id === 'slp' || status.id === 'frz') return; source.trySetStatus(status, target); }, id: "synchronize", name: "Synchronize", rating: 2.5, num: 28 }, "tangledfeet": { shortDesc: "This Pokemon's evasiveness is doubled as long as it is confused.", onModifyAccuracy: function (accuracy, target) { if (typeof accuracy !== 'number') return; if (target && target.volatiles['confusion']) { this.debug('Tangled Feet - decreasing accuracy'); return accuracy * 0.5; } }, id: "tangledfeet", name: "Tangled Feet", rating: 1, num: 77 }, "technician": { desc: "This Pokemon's moves of 60 power or less have their power multiplied by 1.5. Does affect Struggle.", shortDesc: "This Pokemon's moves of 60 power or less have 1.5x power. Includes Struggle.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (basePower <= 60) { this.debug('Technician boost'); return this.chainModify(1.5); } }, id: "technician", name: "Technician", rating: 4, num: 101 }, "telepathy": { shortDesc: "This Pokemon does not take damage from attacks made by its allies.", onTryHit: function (target, source, move) { if (target.side === source.side && move.category !== 'Status') { this.add('-activate', target, 'ability: Telepathy'); return null; } }, id: "telepathy", name: "Telepathy", rating: 0, num: 140 }, "teravolt": { shortDesc: "This Pokemon's moves and their effects ignore the Abilities of other Pokemon.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Teravolt'); }, stopAttackEvents: true, id: "teravolt", name: "Teravolt", rating: 3.5, num: 164 }, "thickfat": { desc: "If a Pokemon uses a Fire- or Ice-type attack against this Pokemon, that Pokemon's attacking stat is halved when calculating the damage to this Pokemon.", shortDesc: "Fire/Ice-type moves against this Pokemon deal damage with a halved attacking stat.", onModifyAtkPriority: 6, onSourceModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Ice' || move.type === 'Fire') { this.debug('Thick Fat weaken'); return this.chainModify(0.5); } }, onModifySpAPriority: 5, onSourceModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Ice' || move.type === 'Fire') { this.debug('Thick Fat weaken'); return this.chainModify(0.5); } }, id: "thickfat", name: "Thick Fat", rating: 3.5, num: 47 }, "tintedlens": { shortDesc: "This Pokemon's attacks that are not very effective on a target deal double damage.", onModifyDamage: function (damage, source, target, move) { if (move.typeMod < 0) { this.debug('Tinted Lens boost'); return this.chainModify(2); } }, id: "tintedlens", name: "Tinted Lens", rating: 3.5, num: 110 }, "torrent": { desc: "When this Pokemon has 1/3 or less of its maximum HP, rounded down, its attacking stat is multiplied by 1.5 while using a Water-type attack.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Water attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) { this.debug('Torrent boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) { this.debug('Torrent boost'); return this.chainModify(1.5); } }, id: "torrent", name: "Torrent", rating: 2, num: 67 }, "toxicboost": { desc: "While this Pokemon is poisoned, the power of its physical attacks is multiplied by 1.5.", shortDesc: "While this Pokemon is poisoned, its physical attacks have 1.5x power.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if ((attacker.status === 'psn' || attacker.status === 'tox') && move.category === 'Physical') { return this.chainModify(1.5); } }, id: "toxicboost", name: "Toxic Boost", rating: 3, num: 137 }, "toughclaws": { shortDesc: "This Pokemon's contact moves have their power multiplied by 1.3.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.flags['contact']) { return this.chainModify([0x14CD, 0x1000]); } }, id: "toughclaws", name: "Tough Claws", rating: 3.5, num: 181 }, "trace": { desc: "On switch-in, this Pokemon copies a random adjacent opposing Pokemon's Ability. If there is no Ability that can be copied at that time, this Ability will activate as soon as an Ability can be copied. Abilities that cannot be copied are Flower Gift, Forecast, Illusion, Imposter, Multitype, Stance Change, Trace, and Zen Mode.", shortDesc: "On switch-in, or when it can, this Pokemon copies a random adjacent foe's Ability.", onUpdate: function (pokemon) { var possibleTargets = []; for (var i = 0; i < pokemon.side.foe.active.length; i++) { if (pokemon.side.foe.active[i] && !pokemon.side.foe.active[i].fainted) possibleTargets.push(pokemon.side.foe.active[i]); } while (possibleTargets.length) { var rand = 0; if (possibleTargets.length > 1) rand = this.random(possibleTargets.length); var target = possibleTargets[rand]; var ability = this.getAbility(target.ability); var bannedAbilities = {flowergift:1, forecast:1, illusion:1, imposter:1, multitype:1, stancechange:1, trace:1, zenmode:1}; if (bannedAbilities[target.ability]) { possibleTargets.splice(rand, 1); continue; } this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target); pokemon.setAbility(ability); return; } }, id: "trace", name: "Trace", rating: 3, num: 36 }, "truant": { shortDesc: "This Pokemon skips every other turn instead of using a move.", onBeforeMovePriority: 9, onBeforeMove: function (pokemon, target, move) { if (pokemon.removeVolatile('truant')) { this.add('cant', pokemon, 'ability: Truant', move); return false; } pokemon.addVolatile('truant'); }, effect: { duration: 2 }, id: "truant", name: "Truant", rating: -2, num: 54 }, "turboblaze": { shortDesc: "This Pokemon's moves and their effects ignore the Abilities of other Pokemon.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Turboblaze'); }, stopAttackEvents: true, id: "turboblaze", name: "Turboblaze", rating: 3.5, num: 163 }, "unaware": { desc: "This Pokemon ignores other Pokemon's Attack, Special Attack, and accuracy stat stages when taking damage, and ignores other Pokemon's Defense, Special Defense, and evasiveness stat stages when dealing damage.", shortDesc: "This Pokemon ignores other Pokemon's stat stages when taking or doing damage.", id: "unaware", name: "Unaware", onAnyModifyBoost: function (boosts, target) { var source = this.effectData.target; if (source === target) return; if (source === this.activePokemon && target === this.activeTarget) { boosts['def'] = 0; boosts['spd'] = 0; boosts['evasion'] = 0; } if (target === this.activePokemon && source === this.activeTarget) { boosts['atk'] = 0; boosts['spa'] = 0; boosts['accuracy'] = 0; } }, rating: 3, num: 109 }, "unburden": { desc: "If this Pokemon loses its held item for any reason, its Speed is doubled. This boost is lost if it switches out or gains a new item or Ability.", shortDesc: "Speed is doubled on held item loss; boost is lost if it switches, gets new item/Ability.", onAfterUseItem: function (item, pokemon) { if (pokemon !== this.effectData.target) return; pokemon.addVolatile('unburden'); }, onTakeItem: function (item, pokemon) { pokemon.addVolatile('unburden'); }, onEnd: function (pokemon) { pokemon.removeVolatile('unburden'); }, effect: { onModifySpe: function (speMod, pokemon) { if (!pokemon.item) { return this.chain(speMod, 2); } } }, id: "unburden", name: "Unburden", rating: 3.5, num: 84 }, "unnerve": { shortDesc: "While this Pokemon is active, it prevents opposing Pokemon from using their Berries.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Unnerve', pokemon.side.foe); }, onFoeEatItem: false, id: "unnerve", name: "Unnerve", rating: 1.5, num: 127 }, "victorystar": { shortDesc: "This Pokemon and its allies' moves have their accuracy multiplied by 1.1.", onAllyModifyMove: function (move) { if (typeof move.accuracy === 'number') { move.accuracy *= 1.1; } }, id: "victorystar", name: "Victory Star", rating: 2.5, num: 162 }, "vitalspirit": { shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'slp') { pokemon.cureStatus(); } }, onImmunity: function (type) { if (type === 'slp') return false; }, id: "vitalspirit", name: "Vital Spirit", rating: 2, num: 72 }, "voltabsorb": { desc: "This Pokemon is immune to Electric-type moves and restores 1/4 of its maximum HP, rounded down, when hit by an Electric-type move.", shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Electric moves; Electric immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Electric') { if (!this.heal(target.maxhp / 4)) { this.add('-immune', target, '[msg]'); } return null; } }, id: "voltabsorb", name: "Volt Absorb", rating: 3.5, num: 10 }, "waterabsorb": { desc: "This Pokemon is immune to Water-type moves and restores 1/4 of its maximum HP, rounded down, when hit by a Water-type move.", shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Water moves; Water immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Water') { if (!this.heal(target.maxhp / 4)) { this.add('-immune', target, '[msg]'); } return null; } }, id: "waterabsorb", name: "Water Absorb", rating: 3.5, num: 11 }, "waterveil": { shortDesc: "This Pokemon cannot be burned. Gaining this Ability while burned cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'brn') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'brn') return false; }, id: "waterveil", name: "Water Veil", rating: 2, num: 41 }, "weakarmor": { desc: "If a physical attack hits this Pokemon, its Defense is lowered by 1 stage and its Speed is raised by 1 stage.", shortDesc: "If a physical attack hits this Pokemon, Defense is lowered by 1, Speed is raised by 1.", onAfterDamage: function (damage, target, source, move) { if (move.category === 'Physical') { this.boost({spe:1, def:-1}); } }, id: "weakarmor", name: "Weak Armor", rating: 0.5, num: 133 }, "whitesmoke": { shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; var showMsg = false; for (var i in boost) { if (boost[i] < 0) { delete boost[i]; showMsg = true; } } if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: White Smoke", "[of] " + target); }, id: "whitesmoke", name: "White Smoke", rating: 2, num: 73 }, "wonderguard": { shortDesc: "This Pokemon can only be damaged by supereffective moves and indirect damage.", onTryHit: function (target, source, move) { if (target === source || move.category === 'Status' || move.type === '???' || move.id === 'struggle' || move.isFutureMove) return; this.debug('Wonder Guard immunity: ' + move.id); if (target.runEffectiveness(move) <= 0) { this.add('-activate', target, 'ability: Wonder Guard'); return null; } }, id: "wonderguard", name: "Wonder Guard", rating: 5, num: 25 }, "wonderskin": { desc: "All non-damaging moves that check accuracy have their accuracy changed to 50% when used on this Pokemon. This change is done before any other accuracy modifying effects.", shortDesc: "Status moves with accuracy checks are 50% accurate when used on this Pokemon.", onModifyAccuracyPriority: 10, onModifyAccuracy: function (accuracy, target, source, move) { if (move.category === 'Status' && typeof move.accuracy === 'number') { this.debug('Wonder Skin - setting accuracy to 50'); return 50; } }, id: "wonderskin", name: "Wonder Skin", rating: 2, num: 147 }, "zenmode": { desc: "If this Pokemon is a Darmanitan, it changes to Zen Mode if it has 1/2 or less of its maximum HP at the end of a turn. If Darmanitan's HP is above 1/2 of its maximum HP at the end of a turn, it changes back to Standard Mode. If Darmanitan loses this Ability while in Zen Mode it reverts to Standard Mode immediately.", shortDesc: "If Darmanitan, at end of turn changes Mode to Standard if > 1/2 max HP, else Zen.", onResidualOrder: 27, onResidual: function (pokemon) { if (pokemon.baseTemplate.species !== 'Darmanitan') { return; } if (pokemon.hp <= pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitan') { pokemon.addVolatile('zenmode'); } else if (pokemon.hp > pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitanzen') { pokemon.removeVolatile('zenmode'); } }, effect: { onStart: function (pokemon) { if (pokemon.formeChange('Darmanitan-Zen')) { this.add('-formechange', pokemon, 'Darmanitan-Zen'); } else { return false; } }, onEnd: function (pokemon) { if (pokemon.formeChange('Darmanitan')) { this.add('-formechange', pokemon, 'Darmanitan'); } else { return false; } }, onUpdate: function (pokemon) { if (!pokemon.hasAbility('zenmode')) { pokemon.transformed = false; pokemon.removeVolatile('zenmode'); } } }, id: "zenmode", name: "Zen Mode", rating: -1, num: 161 }, // CAP "mountaineer": { shortDesc: "On switch-in, this Pokemon avoids all Rock-type attacks and Stealth Rock.", onDamage: function (damage, target, source, effect) { if (effect && effect.id === 'stealthrock') { return false; } }, onImmunity: function (type, target) { if (type === 'Rock' && !target.activeTurns) { return false; } }, id: "mountaineer", isNonstandard: true, name: "Mountaineer", rating: 3.5, num: -2 }, "rebound": { desc: "On switch-in, this Pokemon blocks certain status moves and instead uses the move against the original user.", shortDesc: "On switch-in, blocks certain status moves and bounces them back to the user.", id: "rebound", isNonstandard: true, name: "Rebound", onTryHitPriority: 1, onTryHit: function (target, source, move) { if (this.effectData.target.activeTurns) return; if (target === source || move.hasBounced || !move.flags['reflectable']) { return; } var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; }, onAllyTryHitSide: function (target, source, move) { if (this.effectData.target.activeTurns) return; if (target.side === source.side || move.hasBounced || !move.flags['reflectable']) { return; } var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; }, effect: { duration: 1 }, rating: 3.5, num: -3 }, "persistent": { shortDesc: "The duration of certain field effects is increased by 2 turns if used by this Pokemon.", id: "persistent", isNonstandard: true, name: "Persistent", // implemented in the corresponding move rating: 3.5, num: -4 } };
var big_image; $().ready(function () { $('.selector').click(function () { SelectColor(this); }); var selectCol = 0; if (selectCol == 0) { if ($('body').hasClass('landing-page1')) { } } }); $(window).on('scroll', function () { responsive = $(window).width(); if (responsive >= 768) { parallax(); } }); function SelectColor(btn) { oldColor = $('.filter-gradient').attr('data-color'); newColor = $(btn).attr('data-color'); oldButton = $('a[id^="Demo"]').attr('data-button'); newButton = $(btn).attr('data-button'); $('.filter-gradient').removeClass(oldColor).addClass(newColor).attr('data-color', newColor); $('a[id^="Demo"]').removeClass("btn-" + oldButton).addClass("btn-" + newButton).attr('data-button', newButton); $('.carousel-indicators').removeClass("carousel-indicators-" + oldColor).addClass("carousel-indicators-" + newColor); $('.card').removeClass("card-" + oldColor).addClass("card-" + newColor); $('.selector').removeClass('active'); $(btn).addClass('active'); }; $('.switch').each(function () { var selector = $(this).parent('li') $(this).click(function () { if (selector.siblings().hasClass('active')) { selector.addClass('active'); selector.siblings().removeClass('active'); var slide = $(this).attr('data-slide') var lastClass = $('body').attr('class').split(' ').pop(); $('body').removeClass(lastClass); $('body').addClass('landing-page' + slide); } }); }); var parallax = debounce(function () { no_of_elements = 0; $('.parallax').each(function () { var $elem = $(this); if (isElementInViewport($elem)) { var parent_top = $elem.offset().top; var window_bottom = $(window).scrollTop(); var $image = $elem.find('.parallax-background-image') var $oVal = ((window_bottom - parent_top) / 3); $image.css('margin-top', $oVal + 'px'); } }); }, 6); /* ----------------------------------------------------------- */ /* Team Carousel /* ----------------------------------------------------------- */ var owl = $("#owl-team"); owl.owlCarousel({ navigation: false, // Show next and prev buttons // navigationText: ["prev","next"], navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], slideSpeed: 300, paginationSpeed: 400, autoPlay: true, items: 4, itemsDesktop: [1199, 4], itemsDesktopSmall: [979, 3], //As above. itemsTablet: [768, 3], //As above. // itemsTablet:[640,2], itemsMobile: [479, 1], //As above goToFirst: true, //Slide to first item if autoPlay reach end goToFirstSpeed: 1000 }); /* ----------------------------------------------------------- */ /* Team Carousel END /* ----------------------------------------------------------- */ function debounce(func, wait, immediate) { var timeout; return function () { var context = this, args = arguments; clearTimeout(timeout); timeout = setTimeout(function () { timeout = null; if (!immediate) func.apply(context, args); }, wait); if (immediate && !timeout) func.apply(context, args); }; }; function isElementInViewport(elem) { var $elem = $(elem); // Get the scroll position of the page. var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html'); var viewportTop = $(scrollElem).scrollTop(); var viewportBottom = viewportTop + $(window).height(); // Get the position of the element on the page. var elemTop = Math.round($elem.offset().top); var elemBottom = elemTop + $elem.height(); return ((elemTop < viewportBottom) && (elemBottom > viewportTop)); }; /* ----------------------------------------------------------- */ /* Nob Mailer START /* ----------------------------------------------------------- */ $(document).ready(function() { $('form.form-email').submit(function(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; var thisForm = $(this).closest('form.form-email'); document.getElementsByClassName("form-email")[0].getElementsByTagName("button")[0].disabled = true if (thisForm.attr('data-form-type').indexOf("nob") > -1) { // Nob form var sendFrom = document.getElementById("email").value, sendTo = "harrisonchowhk@yahoo.com", subject = "Message from " + sendFrom, msg = document.getElementById("message").value, msgHTML = "<p>" + document.getElementById("message").value + "<p>", fromName = "CSA York", toName = "CSA York Execs"; var sendData = JSON.stringify({ 'sendFrom': sendFrom, 'fromName': fromName, 'sendTo': sendTo, 'toName': toName, 'subject': subject, 'msg': msg, 'msgHTML': msgHTML }); $.ajax({ url: 'assets/mail/mailer.php', crossDomain: false, data: sendData, method: "POST", cache: false, dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { // Deal with JSON console.log(data); var returnData = JSON.parse(data.responseText); if (returnData.success) { // Throw success msg } else { // Throw error message } document.getElementsByClassName("form-email")[0].getElementsByTagName("button")[0].disabled = false; }, error: function (error) { console.log(error); // Throw error message document.getElementsByClassName("form-email")[0].getElementsByTagName("button")[0].disabled = false; } }); } }); }); /* ----------------------------------------------------------- */ /* Nob Mailer END /* ----------------------------------------------------------- */
"use strict"; const runPrettier = require("../run-prettier.js"); describe("write cursorOffset to stderr with --cursor-offset <int>", () => { runPrettier("cli", ["--cursor-offset", "2", "--parser", "babel"], { input: " 1", }).test({ status: 0, }); }); describe("cursorOffset should not be affected by full-width character", () => { runPrettier("cli", ["--cursor-offset", "21", "--parser", "babel"], { input: 'const x = ["中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文", "中文"];', // ^ offset = 21 ^ width = 80 }).test({ /** * const x = [ * "中文", * "中文", * ^ offset = 26 * "中文", * "中文", * "中文", * "中文", * "中文", * "中文", * "中文", * "中文", * "中文" * ]; */ stderr: "26\n", status: 0, }); });
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(m,w,q){m instanceof String&&(m=String(m));for(var x=m.length,B=0;B<x;B++){var J=m[B];if(w.call(q,J,B,m))return{i:B,v:J}}return{i:-1,v:void 0}};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;$jscomp.ISOLATE_POLYFILLS=!1;$jscomp.FORCE_POLYFILL_PROMISE=!1;$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1; $jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(m,w,q){if(m==Array.prototype||m==Object.prototype)return m;m[w]=q.value;return m};$jscomp.getGlobal=function(m){m=["object"==typeof globalThis&&globalThis,m,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var w=0;w<m.length;++w){var q=m[w];if(q&&q.Math==Math)return q}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this); $jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(m,w){var q=$jscomp.propertyToPolyfillSymbol[w];if(null==q)return m[w];q=m[q];return void 0!==q?q:m[w]}; $jscomp.polyfill=function(m,w,q,x){w&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(m,w,q,x):$jscomp.polyfillUnisolated(m,w,q,x))};$jscomp.polyfillUnisolated=function(m,w,q,x){q=$jscomp.global;m=m.split(".");for(x=0;x<m.length-1;x++){var B=m[x];if(!(B in q))return;q=q[B]}m=m[m.length-1];x=q[m];w=w(x);w!=x&&null!=w&&$jscomp.defineProperty(q,m,{configurable:!0,writable:!0,value:w})}; $jscomp.polyfillIsolated=function(m,w,q,x){var B=m.split(".");m=1===B.length;x=B[0];x=!m&&x in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var J=0;J<B.length-1;J++){var M=B[J];if(!(M in x))return;x=x[M]}B=B[B.length-1];q=$jscomp.IS_SYMBOL_NATIVE&&"es6"===q?x[B]:null;w=w(q);null!=w&&(m?$jscomp.defineProperty($jscomp.polyfills,B,{configurable:!0,writable:!0,value:w}):w!==q&&(void 0===$jscomp.propertyToPolyfillSymbol[B]&&(q=1E9*Math.random()>>>0,$jscomp.propertyToPolyfillSymbol[B]=$jscomp.IS_SYMBOL_NATIVE? $jscomp.global.Symbol(B):$jscomp.POLYFILL_PREFIX+q+"$"+B),$jscomp.defineProperty(x,$jscomp.propertyToPolyfillSymbol[B],{configurable:!0,writable:!0,value:w})))};$jscomp.polyfill("Array.prototype.find",function(m){return m?m:function(w,q){return $jscomp.findInternal(this,w,q).v}},"es6","es3");$jscomp.arrayIteratorImpl=function(m){var w=0;return function(){return w<m.length?{done:!1,value:m[w++]}:{done:!0}}};$jscomp.arrayIterator=function(m){return{next:$jscomp.arrayIteratorImpl(m)}}; $jscomp.initSymbol=function(){};$jscomp.polyfill("Symbol",function(m){if(m)return m;var w=function(J,M){this.$jscomp$symbol$id_=J;$jscomp.defineProperty(this,"description",{configurable:!0,writable:!0,value:M})};w.prototype.toString=function(){return this.$jscomp$symbol$id_};var q="jscomp_symbol_"+(1E9*Math.random()>>>0)+"_",x=0,B=function(J){if(this instanceof B)throw new TypeError("Symbol is not a constructor");return new w(q+(J||"")+"_"+x++,J)};return B},"es6","es3"); $jscomp.polyfill("Symbol.iterator",function(m){if(m)return m;m=Symbol("Symbol.iterator");for(var w="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),q=0;q<w.length;q++){var x=$jscomp.global[w[q]];"function"===typeof x&&"function"!=typeof x.prototype[m]&&$jscomp.defineProperty(x.prototype,m,{configurable:!0,writable:!0,value:function(){return $jscomp.iteratorPrototype($jscomp.arrayIteratorImpl(this))}})}return m},"es6", "es3");$jscomp.iteratorPrototype=function(m){m={next:m};m[Symbol.iterator]=function(){return this};return m};$jscomp.iteratorFromArray=function(m,w){m instanceof String&&(m+="");var q=0,x=!1,B={next:function(){if(!x&&q<m.length){var J=q++;return{value:w(J,m[J]),done:!1}}x=!0;return{done:!0,value:void 0}}};B[Symbol.iterator]=function(){return B};return B};$jscomp.polyfill("Array.prototype.keys",function(m){return m?m:function(){return $jscomp.iteratorFromArray(this,function(w){return w})}},"es6","es3"); $jscomp.checkStringArgs=function(m,w,q){if(null==m)throw new TypeError("The 'this' value for String.prototype."+q+" must not be null or undefined");if(w instanceof RegExp)throw new TypeError("First argument to String.prototype."+q+" must not be a regular expression");return m+""}; $jscomp.polyfill("String.prototype.repeat",function(m){return m?m:function(w){var q=$jscomp.checkStringArgs(this,null,"repeat");if(0>w||1342177279<w)throw new RangeError("Invalid count value");w|=0;for(var x="";w;)if(w&1&&(x+=q),w>>>=1)q+=q;return x}},"es6","es3"); (function(m){"object"==typeof exports&&"object"==typeof module?m(require("../lib/codemirror"),require("../addon/search/searchcursor"),require("../addon/dialog/dialog"),require("../addon/edit/matchbrackets.js")):"function"==typeof define&&define.amd?define(["../lib/codemirror","../addon/search/searchcursor","../addon/dialog/dialog","../addon/edit/matchbrackets"],m):m(CodeMirror)})(function(m){function w(M,K){M=M.state.vim;if(!M||M.insertMode)return K.head;var aa=M.sel.head;if(!aa)return K.head;if(!M.visualBlock|| K.head.line==aa.line)return K.from()!=K.anchor||K.empty()||K.head.line!=aa.line||K.head.ch==aa.ch?K.head:new q(K.head.line,K.head.ch-1)}var q=m.Pos,x=[{keys:"<Left>",type:"keyToKey",toKeys:"h"},{keys:"<Right>",type:"keyToKey",toKeys:"l"},{keys:"<Up>",type:"keyToKey",toKeys:"k"},{keys:"<Down>",type:"keyToKey",toKeys:"j"},{keys:"g<Up>",type:"keyToKey",toKeys:"gk"},{keys:"g<Down>",type:"keyToKey",toKeys:"gj"},{keys:"<Space>",type:"keyToKey",toKeys:"l"},{keys:"<BS>",type:"keyToKey",toKeys:"h",context:"normal"}, {keys:"<Del>",type:"keyToKey",toKeys:"x",context:"normal"},{keys:"<C-Space>",type:"keyToKey",toKeys:"W"},{keys:"<C-BS>",type:"keyToKey",toKeys:"B",context:"normal"},{keys:"<S-Space>",type:"keyToKey",toKeys:"w"},{keys:"<S-BS>",type:"keyToKey",toKeys:"b",context:"normal"},{keys:"<C-n>",type:"keyToKey",toKeys:"j"},{keys:"<C-p>",type:"keyToKey",toKeys:"k"},{keys:"<C-[>",type:"keyToKey",toKeys:"<Esc>"},{keys:"<C-c>",type:"keyToKey",toKeys:"<Esc>"},{keys:"<C-[>",type:"keyToKey",toKeys:"<Esc>",context:"insert"}, {keys:"<C-c>",type:"keyToKey",toKeys:"<Esc>",context:"insert"},{keys:"s",type:"keyToKey",toKeys:"cl",context:"normal"},{keys:"s",type:"keyToKey",toKeys:"c",context:"visual"},{keys:"S",type:"keyToKey",toKeys:"cc",context:"normal"},{keys:"S",type:"keyToKey",toKeys:"VdO",context:"visual"},{keys:"<Home>",type:"keyToKey",toKeys:"0"},{keys:"<End>",type:"keyToKey",toKeys:"$"},{keys:"<PageUp>",type:"keyToKey",toKeys:"<C-b>"},{keys:"<PageDown>",type:"keyToKey",toKeys:"<C-f>"},{keys:"<CR>",type:"keyToKey", toKeys:"j^",context:"normal"},{keys:"<Ins>",type:"keyToKey",toKeys:"i",context:"normal"},{keys:"<Ins>",type:"action",action:"toggleOverwrite",context:"insert"},{keys:"H",type:"motion",motion:"moveToTopLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"M",type:"motion",motion:"moveToMiddleLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"L",type:"motion",motion:"moveToBottomLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"h",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!1}}, {keys:"l",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!0}},{keys:"j",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,linewise:!0}},{keys:"k",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,linewise:!0}},{keys:"gj",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!0}},{keys:"gk",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!1}},{keys:"w",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1}},{keys:"W",type:"motion",motion:"moveByWords", motionArgs:{forward:!0,wordEnd:!1,bigWord:!0}},{keys:"e",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,inclusive:!0}},{keys:"E",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"b",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1}},{keys:"B",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1,bigWord:!0}},{keys:"ge",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,inclusive:!0}}, {keys:"gE",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"{",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!1,toJumplist:!0}},{keys:"}",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!0,toJumplist:!0}},{keys:"(",type:"motion",motion:"moveBySentence",motionArgs:{forward:!1}},{keys:")",type:"motion",motion:"moveBySentence",motionArgs:{forward:!0}},{keys:"<C-f>",type:"motion",motion:"moveByPage",motionArgs:{forward:!0}}, {keys:"<C-b>",type:"motion",motion:"moveByPage",motionArgs:{forward:!1}},{keys:"<C-d>",type:"motion",motion:"moveByScroll",motionArgs:{forward:!0,explicitRepeat:!0}},{keys:"<C-u>",type:"motion",motion:"moveByScroll",motionArgs:{forward:!1,explicitRepeat:!0}},{keys:"gg",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"G",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!0,explicitRepeat:!0,linewise:!0, toJumplist:!0}},{keys:"g$",type:"motion",motion:"moveToEndOfDisplayLine"},{keys:"g^",type:"motion",motion:"moveToStartOfDisplayLine"},{keys:"g0",type:"motion",motion:"moveToStartOfDisplayLine"},{keys:"0",type:"motion",motion:"moveToStartOfLine"},{keys:"^",type:"motion",motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"+",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0}},{keys:"-",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,toFirstChar:!0}},{keys:"_",type:"motion", motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0,repeatOffset:-1}},{keys:"$",type:"motion",motion:"moveToEol",motionArgs:{inclusive:!0}},{keys:"%",type:"motion",motion:"moveToMatchedSymbol",motionArgs:{inclusive:!0,toJumplist:!0}},{keys:"f<character>",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"F<character>",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!1}},{keys:"t<character>",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!0, inclusive:!0}},{keys:"T<character>",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!1}},{keys:";",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!0}},{keys:",",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!1}},{keys:"'<character>",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0,linewise:!0}},{keys:"`<character>",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0}},{keys:"]`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0}}, {keys:"[`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1}},{keys:"]'",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0,linewise:!0}},{keys:"['",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1,linewise:!0}},{keys:"]p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0,matchIndent:!0}},{keys:"[p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0,matchIndent:!0}},{keys:"]<character>",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!0, toJumplist:!0}},{keys:"[<character>",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!1,toJumplist:!0}},{keys:"|",type:"motion",motion:"moveToColumn"},{keys:"o",type:"motion",motion:"moveToOtherHighlightedEnd",context:"visual"},{keys:"O",type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{sameLine:!0},context:"visual"},{keys:"d",type:"operator",operator:"delete"},{keys:"y",type:"operator",operator:"yank"},{keys:"c",type:"operator",operator:"change"},{keys:"=",type:"operator",operator:"indentAuto"}, {keys:">",type:"operator",operator:"indent",operatorArgs:{indentRight:!0}},{keys:"<",type:"operator",operator:"indent",operatorArgs:{indentRight:!1}},{keys:"g~",type:"operator",operator:"changeCase"},{keys:"gu",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},isEdit:!0},{keys:"gU",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},isEdit:!0},{keys:"n",type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:!0}},{keys:"N",type:"motion",motion:"findNext",motionArgs:{forward:!1, toJumplist:!0}},{keys:"gn",type:"motion",motion:"findAndSelectNextInclusive",motionArgs:{forward:!0}},{keys:"gN",type:"motion",motion:"findAndSelectNextInclusive",motionArgs:{forward:!1}},{keys:"x",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!0},operatorMotionArgs:{visualLine:!1}},{keys:"X",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!1},operatorMotionArgs:{visualLine:!0}},{keys:"D",type:"operatorMotion",operator:"delete", motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"D",type:"operator",operator:"delete",operatorArgs:{linewise:!0},context:"visual"},{keys:"Y",type:"operatorMotion",operator:"yank",motion:"expandToLine",motionArgs:{linewise:!0},context:"normal"},{keys:"Y",type:"operator",operator:"yank",operatorArgs:{linewise:!0},context:"visual"},{keys:"C",type:"operatorMotion",operator:"change",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"C",type:"operator",operator:"change", operatorArgs:{linewise:!0},context:"visual"},{keys:"~",type:"operatorMotion",operator:"changeCase",motion:"moveByCharacters",motionArgs:{forward:!0},operatorArgs:{shouldMoveCursor:!0},context:"normal"},{keys:"~",type:"operator",operator:"changeCase",context:"visual"},{keys:"<C-u>",type:"operatorMotion",operator:"delete",motion:"moveToStartOfLine",context:"insert"},{keys:"<C-w>",type:"operatorMotion",operator:"delete",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1},context:"insert"},{keys:"<C-w>", type:"idle",context:"normal"},{keys:"<C-i>",type:"action",action:"jumpListWalk",actionArgs:{forward:!0}},{keys:"<C-o>",type:"action",action:"jumpListWalk",actionArgs:{forward:!1}},{keys:"<C-e>",type:"action",action:"scroll",actionArgs:{forward:!0,linewise:!0}},{keys:"<C-y>",type:"action",action:"scroll",actionArgs:{forward:!1,linewise:!0}},{keys:"a",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"charAfter"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode", isEdit:!0,actionArgs:{insertAt:"eol"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"endOfSelectedArea"},context:"visual"},{keys:"i",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"inplace"},context:"normal"},{keys:"gi",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"lastEdit"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"firstNonBlank"},context:"normal"}, {keys:"gI",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"bol"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"startOfSelectedArea"},context:"visual"},{keys:"o",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!0},context:"normal"},{keys:"O",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!1},context:"normal"},{keys:"v", type:"action",action:"toggleVisualMode"},{keys:"V",type:"action",action:"toggleVisualMode",actionArgs:{linewise:!0}},{keys:"<C-v>",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"<C-q>",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"gv",type:"action",action:"reselectLastSelection"},{keys:"J",type:"action",action:"joinLines",isEdit:!0},{keys:"gJ",type:"action",action:"joinLines",actionArgs:{keepSpaces:!0},isEdit:!0},{keys:"p",type:"action",action:"paste", isEdit:!0,actionArgs:{after:!0,isEdit:!0}},{keys:"P",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0}},{keys:"r<character>",type:"action",action:"replace",isEdit:!0},{keys:"@<character>",type:"action",action:"replayMacro"},{keys:"q<character>",type:"action",action:"enterMacroRecordMode"},{keys:"R",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{replace:!0},context:"normal"},{keys:"R",type:"operator",operator:"change",operatorArgs:{linewise:!0,fullLine:!0},context:"visual", exitVisualBlock:!0},{keys:"u",type:"action",action:"undo",context:"normal"},{keys:"u",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},context:"visual",isEdit:!0},{keys:"U",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},context:"visual",isEdit:!0},{keys:"<C-r>",type:"action",action:"redo"},{keys:"m<character>",type:"action",action:"setMark"},{keys:'"<character>',type:"action",action:"setRegister"},{keys:"zz",type:"action",action:"scrollToCursor",actionArgs:{position:"center"}}, {keys:"z.",type:"action",action:"scrollToCursor",actionArgs:{position:"center"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"zt",type:"action",action:"scrollToCursor",actionArgs:{position:"top"}},{keys:"z<CR>",type:"action",action:"scrollToCursor",actionArgs:{position:"top"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"z-",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"}},{keys:"zb",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"},motion:"moveToFirstNonWhiteSpaceCharacter"}, {keys:".",type:"action",action:"repeatLastEdit"},{keys:"<C-a>",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!0,backtrack:!1}},{keys:"<C-x>",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!1,backtrack:!1}},{keys:"<C-t>",type:"action",action:"indent",actionArgs:{indentRight:!0},context:"insert"},{keys:"<C-d>",type:"action",action:"indent",actionArgs:{indentRight:!1},context:"insert"},{keys:"a<character>",type:"motion",motion:"textObjectManipulation"}, {keys:"i<character>",type:"motion",motion:"textObjectManipulation",motionArgs:{textObjectInner:!0}},{keys:"/",type:"search",searchArgs:{forward:!0,querySrc:"prompt",toJumplist:!0}},{keys:"?",type:"search",searchArgs:{forward:!1,querySrc:"prompt",toJumplist:!0}},{keys:"*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"g*",type:"search", searchArgs:{forward:!0,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:"g#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:":",type:"ex"}],B=x.length,J=[{name:"colorscheme",shortName:"colo"},{name:"map"},{name:"imap",shortName:"im"},{name:"nmap",shortName:"nm"},{name:"vmap",shortName:"vm"},{name:"unmap"},{name:"write",shortName:"w"},{name:"undo",shortName:"u"},{name:"redo",shortName:"red"},{name:"set",shortName:"se"},{name:"setlocal",shortName:"setl"},{name:"setglobal", shortName:"setg"},{name:"sort",shortName:"sor"},{name:"substitute",shortName:"s",possiblyAsync:!0},{name:"nohlsearch",shortName:"noh"},{name:"yank",shortName:"y"},{name:"delmarks",shortName:"delm"},{name:"registers",shortName:"reg",excludeFromCommandHistory:!0},{name:"vglobal",shortName:"v"},{name:"global",shortName:"g"}];m.Vim=function(){function M(a,b){this==m.keyMap.vim&&(a.options.$customCursor=null,m.rmClass(a.getWrapperElement(),"cm-fat-cursor"));b&&b.attach==K||(a.setOption("disableInput", !1),a.off("cursorActivity",Ja),m.off(a.getInputField(),"paste",Ka(a)),a.state.vim=null,oa&&clearTimeout(oa))}function K(a,b){this==m.keyMap.vim&&(a.curOp&&(a.curOp.selectionChanged=!0),a.options.$customCursor=w,m.addClass(a.getWrapperElement(),"cm-fat-cursor"));b&&b.attach==K||(a.setOption("disableInput",!0),a.setOption("showCursorWhenSelecting",!1),m.signal(a,"vim-mode-change",{mode:"normal"}),a.on("cursorActivity",Ja),pa(a),m.on(a.getInputField(),"paste",Ka(a)))}function aa(a,b){if(b){if(this[a])return this[a]; a=vb(a);if(!a)return!1;var c=ia.findKey(b,a);"function"==typeof c&&m.signal(b,"vim-keypress",a);return c}}function vb(a){if("'"==a.charAt(0))return a.charAt(1);a=a.split(/-(?!$)/);var b=a[a.length-1];if(1==a.length&&1==a[0].length||2==a.length&&"Shift"==a[0]&&1==b.length)return!1;for(var c=!1,d=0;d<a.length;d++){var f=a[d];f in La?a[d]=La[f]:c=!0;f in Ma&&(a[d]=Ma[f])}if(!c)return!1;ja.test(b)&&(a[a.length-1]=b.toLowerCase());return"<"+a.join("-")+">"}function Ka(a){var b=a.state.vim;b.onPasteFn|| (b.onPasteFn=function(){b.insertMode||(a.setCursor(N(a.getCursor(),0,1)),qa.enterInsertMode(a,{},b))});return b.onPasteFn}function xa(a,b){for(var c=[],d=a;d<a+b;d++)c.push(String.fromCharCode(d));return c}function ya(a,b){return b>=a.firstLine()&&b<=a.lastLine()}function ca(a){return/^\s*$/.test(a)}function za(a,b){for(var c=0;c<b.length;c++)if(b[c]==a)return!0;return!1}function ra(a,b,c,d,f){if(void 0===b&&!f)throw Error("defaultValue is required unless callback is provided");c||(c="string");X[a]= {type:c,defaultValue:b,callback:f};if(d)for(c=0;c<d.length;c++)X[d[c]]=X[a];b&&Aa(a,b)}function Aa(a,b,c,d){var f=X[a];d=d||{};d=d.scope;if(!f)return Error("Unknown option: "+a);if("boolean"==f.type){if(b&&!0!==b)return Error("Invalid argument: "+a+"="+b);!1!==b&&(b=!0)}f.callback?("local"!==d&&f.callback(b,void 0),"global"!==d&&c&&f.callback(b,c)):("local"!==d&&(f.value="boolean"==f.type?!!b:b),"global"!==d&&c&&(c.state.vim.options[a]={value:b}))}function da(a,b,c){var d=X[a];c=c||{};c=c.scope;if(!d)return Error("Unknown option: "+ a);if(d.callback){a=b&&d.callback(void 0,b);if("global"!==c&&void 0!==a)return a;if("local"!==c)return d.callback()}else return a="global"!==c&&b&&b.state.vim.options[a],(a||"local"!==c&&d||{}).value}function Na(){this.latestRegister=void 0;this.isRecording=this.isPlaying=!1;this.replaySearchQueries=[];this.onRecordingDone=void 0;this.lastInsertModeChanges=Oa()}function pa(a){a.state.vim||(a.state.vim={inputState:new sa,lastEditInputState:void 0,lastEditActionCommand:void 0,lastHPos:-1,lastHSPos:-1, lastMotion:null,marks:{},insertMode:!1,insertModeRepeat:void 0,visualMode:!1,visualLine:!1,visualBlock:!1,lastSelection:null,lastPastedText:null,sel:{},options:{}});return a.state.vim}function Pa(){u={searchQuery:null,searchIsReversed:!1,lastSubstituteReplacePart:void 0,jumpList:wb(),macroModeState:new Na,lastCharacterSearch:{increment:0,forward:!0,selectedCharacter:""},registerController:new Qa({}),searchHistoryController:new Ba,exCommandHistoryController:new Ba};for(var a in X){var b=X[a];b.value= b.defaultValue}}function sa(){this.prefixRepeat=[];this.motionRepeat=[];this.motionArgs=this.motion=this.operatorArgs=this.operator=null;this.keyBuffer=[];this.registerName=null}function O(a,b){a.state.vim.inputState=new sa;m.signal(a,"vim-command-done",b)}function S(a,b,c){this.clear();this.keyBuffer=[a||""];this.insertModeChanges=[];this.searchQueries=[];this.linewise=!!b;this.blockwise=!!c}function Qa(a){this.registers=a;this.unnamedRegister=a['"']=new S;a["."]=new S;a[":"]=new S;a["/"]=new S} function Ba(){this.historyBuffer=[];this.iterator=0;this.initialPrefix=null}function Ra(a,b){for(var c=[],d=0;d<b;d++)c.push(a);return c}function P(a,b){var c=a.state.vim,d=c.insertMode||c.visualMode;c=Math.min(Math.max(a.firstLine(),b.line),a.lastLine());a=I(a,c)-1+!!d;return new q(c,Math.min(Math.max(0,b.ch),a))}function ta(a){var b={},c;for(c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}function N(a,b,c){"object"===typeof b&&(c=b.ch,b=b.line);return new q(a.line+b,a.ch+c)}function Sa(a,b,c){return function(){for(var d= 0;d<c;d++)b(a)}}function G(a){return new q(a.line,a.ch)}function Q(a,b){return a.ch==b.ch&&a.line==b.line}function H(a,b){return a.line<b.line||a.line==b.line&&a.ch<b.ch?!0:!1}function R(a,b){2<arguments.length&&(b=R.apply(void 0,Array.prototype.slice.call(arguments,1)));return H(a,b)?a:b}function ea(a,b){2<arguments.length&&(b=ea.apply(void 0,Array.prototype.slice.call(arguments,1)));return H(a,b)?b:a}function Ta(a,b,c){a=H(a,b);b=H(b,c);return a&&b}function I(a,b){return a.getLine(b).length}function Ca(a){return a.trim? a.trim():a.replace(/^\s+|\s+$/g,"")}function xb(a,b,c){var d=I(a,b);c=Array(c-d+1).join(" ");a.setCursor(new q(b,d));a.replaceRange(c,a.getCursor())}function Ua(a,b){var c=[],d=a.listSelections(),f=G(a.clipPos(b)),e=!Q(b,f),h;a:{var k=a.getCursor("head");for(h=0;h<d.length;h++){var g=Q(d[h].anchor,k),l=Q(d[h].head,k);if(g||l)break a}h=-1}k=Q(d[h].head,d[h].anchor);g=d.length-1;var n=g-h>h?g:0;h=d[n].anchor;var p=Math.min(h.line,f.line);g=Math.max(h.line,f.line);l=h.ch;f=f.ch;d=d[n].head.ch-l;n=f- l;0<d&&0>=n?(l++,e||f--):0>d&&0<=n?(l--,k||f++):0>d&&-1==n&&(l--,f++);for(e=p;e<=g;e++)d={anchor:new q(e,l),head:new q(e,f)},c.push(d);a.setSelections(c);b.ch=f;h.ch=l;return h}function Va(a,b,c){for(var d=[],f=0;f<c;f++){var e=N(b,f,0);d.push({anchor:e,head:e})}a.setSelections(d,0)}function yb(a,b){var c=b.lastSelection,d=function(){var e=a.listSelections(),h=e[0];e=e[e.length-1];h=H(h.anchor,h.head)?h.anchor:h.head;e=H(e.anchor,e.head)?e.head:e.anchor;return[h,e]},f=function(){var e=a.getCursor(), h=a.getCursor(),k=c.visualBlock;if(k){h=new q(e.line+k.height,e.ch+k.width);k=[];for(var g=e.line;g<h.line;g++){var l=new q(g,e.ch),n=new q(g,h.ch);k.push({anchor:l,head:n})}a.setSelections(k)}else g=c.anchorMark.find(),l=c.headMark.find(),k=l.line-g.line,g=l.ch-g.ch,h={line:h.line+k,ch:k?h.ch:g+h.ch},c.visualLine&&(e=new q(e.line,0),h=new q(h.line,I(a,h.line))),a.setSelection(e,h);return[e,h]};return b.visualMode?d():f()}function Wa(a,b){var c=b.sel.anchor,d=b.sel.head;b.lastPastedText&&(d=a.posFromIndex(a.indexFromPos(c)+ b.lastPastedText.length),b.lastPastedText=null);b.lastSelection={anchorMark:a.setBookmark(c),headMark:a.setBookmark(d),anchor:G(c),head:G(d),visualMode:b.visualMode,visualLine:b.visualLine,visualBlock:b.visualBlock}}function ka(a,b,c){var d=a.state.vim;b=b||d.sel;c=c||d.visualLine?"line":d.visualBlock?"block":"char";b=Da(a,b,c);a.setSelections(b.ranges,b.primary)}function Da(a,b,c,d){var f=G(b.head),e=G(b.anchor);if("char"==c)return f=d||H(b.head,b.anchor)?0:1,a=H(b.head,b.anchor)?1:0,f=N(b.head, 0,f),e=N(b.anchor,0,a),{ranges:[{anchor:e,head:f}],primary:0};if("line"==c)return H(b.head,b.anchor)?(f.ch=0,e.ch=I(a,e.line)):(e.ch=0,b=a.lastLine(),f.line>b&&(f.line=b),f.ch=I(a,f.line)),{ranges:[{anchor:e,head:f}],primary:0};if("block"==c){b=Math.min(e.line,f.line);a=e.ch;c=Math.max(e.line,f.line);e=f.ch;a<e?e+=1:a+=1;c=c-b+1;f=f.line==b?0:c-1;d=[];for(var h=0;h<c;h++)d.push({anchor:new q(b+h,a),head:new q(b+h,e)});return{ranges:d,primary:f}}}function T(a,b){var c=a.state.vim;!1!==b&&a.setCursor(P(a, c.sel.head));Wa(a,c);c.visualMode=!1;c.visualLine=!1;c.visualBlock=!1;c.insertMode||m.signal(a,"vim-mode-change",{mode:"normal"})}function U(a){if(!a)return 0;var b=a.search(/\S/);return-1==b?a.length:b}function ua(a,b,c,d,f){c=a.getCursor("head");1==a.getSelection().length&&(c=R(c,a.getCursor("anchor")));a=a.getLine(c.line);var e=c.ch;for(f=f?va[0]:Ea[0];!f(a.charAt(e));)if(e++,e>=a.length)return null;d?f=Ea[0]:(f=va[0],f(a.charAt(e))||(f=va[1]));for(d=e;f(a.charAt(d))&&d<a.length;)d++;for(;f(a.charAt(e))&& 0<=e;)e--;e++;if(b){for(b=d;/\s/.test(a.charAt(d))&&d<a.length;)d++;if(b==d){for(b=e;/\s/.test(a.charAt(e-1))&&0<e;)e--;e||(e=b)}}return{start:new q(c.line,e),end:new q(c.line,d)}}function Xa(a,b){u.lastCharacterSearch.increment=a;u.lastCharacterSearch.forward=b.forward;u.lastCharacterSearch.selectedCharacter=b.selectedCharacter}function Ya(a,b,c,d,f){b=new q(b.line+c.repeat-1,Infinity);c=a.clipPos(b);c.ch--;f||(d.lastHPos=Infinity,d.lastHSPos=a.charCoords(c,"div").left);return b}function Fa(a,b, c,d){for(var f=a.getCursor(),e=f.ch,h,k=0;k<b;k++){h=a.getLine(f.line);var g=d;h=c?h.indexOf(g,e+1):h.lastIndexOf(g,e-1);if(-1==h)return null;e=h}return new q(a.getCursor().line,h)}function Y(a,b,c,d){za(c,zb)&&(b.marks[c]&&b.marks[c].clear(),b.marks[c]=a.setBookmark(d))}function Za(a,b,c,d,f){function e(l,n,p){return p?!a.getLine(l)!=!a.getLine(l+n):!!a.getLine(l)&&!a.getLine(l+n)}b=b.line;var h=a.firstLine(),k=a.lastLine(),g=b;if(d){for(;h<=g&&g<=k&&0<c;)e(g,d)&&c--,g+=d;return new q(g,0)}g=a.state.vim; g.visualLine&&e(b,1,!0)&&(g=g.sel.anchor,e(g.line,-1,!0)&&(f&&g.line==b||(b+=1)));d=!a.getLine(b);for(g=b;g<=k&&c;g++)e(g,1,!0)&&(f&&!a.getLine(g)==d||c--);c=new q(g,0);g>k&&!d?d=!0:f=!1;for(g=b;g>h&&(f&&!a.getLine(g)!=d&&g!=b||!e(g,-1,!0));g--);return{start:new q(g,0),end:c}}function Ab(a,b,c,d){function f(k,g){0>g.pos+g.dir||g.pos+g.dir>=g.line.length?(g.ln+=g.dir,ya(k,g.ln)?(g.line=k.getLine(g.ln),g.pos=0<g.dir?0:g.line.length-1):(g.line=null,g.ln=null,g.pos=null)):g.pos+=g.dir}function e(k,g, l,n){var p=k.getLine(g),t=""===p;p={line:p,ln:g,pos:l,dir:n};g={ln:p.ln,pos:p.pos};l=""===p.line;for(f(k,p);null!==p.line;){g.ln=p.ln;g.pos=p.pos;if(""!==p.line||l){if(t&&""!==p.line&&!ca(p.line[p.pos]))return{ln:p.ln,pos:p.pos};-1==".?!".indexOf(p.line[p.pos])||t||p.pos!==p.line.length-1&&!ca(p.line[p.pos+1])||(t=!0)}else return{ln:p.ln,pos:p.pos};f(k,p)}p=k.getLine(g.ln);g.pos=0;for(k=p.length-1;0<=k;--k)if(!ca(p[k])){g.pos=k;break}return g}function h(k,g,l,n){var p=k.getLine(g);p={line:p,ln:g, pos:l,dir:n};g={ln:p.ln,pos:null};l=""===p.line;for(f(k,p);null!==p.line;){if(""!==p.line||l){if(-1!=".?!".indexOf(p.line[p.pos])&&null!==g.pos&&(p.ln!==g.ln||p.pos+1!==g.pos))return g;""===p.line||ca(p.line[p.pos])||(l=!1,g={ln:p.ln,pos:p.pos})}else return null!==g.pos?g:{ln:p.ln,pos:p.pos};f(k,p)}p=k.getLine(g.ln);for(k=g.pos=0;k<p.length;++k)if(!ca(p[k])){g.pos=k;break}return g}for(b={ln:b.line,pos:b.ch};0<c;)b=0>d?h(a,b.ln,b.pos,d):e(a,b.ln,b.pos,d),c--;return new q(b.ln,b.pos)}function $a(){} function V(a){a=a.state.vim;return a.searchState_||(a.searchState_=new $a)}function ab(a,b){b=bb(a,b)||[];if(!b.length)return[];var c=[];if(0===b[0]){for(var d=0;d<b.length;d++)"number"==typeof b[d]&&c.push(a.substring(b[d]+1,b[d+1]));return c}}function bb(a,b){b||(b="/");for(var c=!1,d=[],f=0;f<a.length;f++){var e=a.charAt(f);c||e!=b||d.push(f);c=!c&&"\\"==e}return d}function fa(a){"string"===typeof a&&(a=document.createElement(a));for(var b,c=1;c<arguments.length;c++)if(b=arguments[c])if("object"!== typeof b&&(b=document.createTextNode(b)),b.nodeType)a.appendChild(b);else for(var d in b)Object.prototype.hasOwnProperty.call(b,d)&&("$"===d[0]?a.style[d.slice(1)]=b[d]:a.setAttribute(d,b[d]));return a}function F(a,b){b=fa("pre",{$color:"red",class:"cm-vim-message"},b);a.openNotification?a.openNotification(b,{bottom:!0,duration:5E3}):alert(b.innerText)}function wa(a,b){var c=b.prefix;var d=b.desc;c=fa(document.createDocumentFragment(),fa("span",{$fontFamily:"monospace",$whiteSpace:"pre"},c,fa("input", {type:"text",autocorrect:"off",autocapitalize:"off",spellcheck:"false"})),d&&fa("span",{$color:"#888"},d));a.openDialog?a.openDialog(c,b.onClose,{onKeyDown:b.onKeyDown,onKeyUp:b.onKeyUp,bottom:!0,selectValueOnOpen:!1,value:b.value}):(a="","string"!=typeof b.prefix&&b.prefix&&(a+=b.prefix.textContent),b.desc&&(a+=" "+b.desc),b.onClose(prompt(a,"")))}function la(a,b,c,d){if(b){var f=V(a);c=!!c;d=!!d;u.registerController.getRegister("/").setText(b);if(b instanceof RegExp)var e=b;else{var h=bb(b,"/"); if(h.length){var k=b.substring(0,h[0]);e=-1!=b.substring(h[0]).indexOf("i")}else k=b;if(k){if(!da("pcre")){b=k;h=!1;k=[];for(var g=-1;g<b.length;g++){var l=b.charAt(g)||"",n=b.charAt(g+1)||"",p=n&&-1!="|(){".indexOf(n);h?("\\"===l&&p||k.push(l),h=!1):"\\"===l?(h=!0,n&&-1!="}".indexOf(n)&&(p=!0),p&&"\\"!==n||k.push(l)):(k.push(l),p&&"\\"!==n&&k.push("\\"))}k=k.join("")}d&&(c=/^[^A-Z]*$/.test(k));e=new RegExp(k,c||e?"im":"m")}else e=null}if(e){cb(a,e);a:if(a=f.getQuery(),e instanceof RegExp&&a instanceof RegExp){c=["global","multiline","ignoreCase","source"];for(d=0;d<c.length;d++)if(b=c[d],e[b]!==a[b]){a=!1;break a}a=!0}else a=!1;if(a)return e;f.setQuery(e);return e}}}function Bb(a){if("^"==a.source.charAt(0))var b=!0;return{token:function(c){if(b&&!c.sol())c.skipToEnd();else{var d=c.match(a,!1);if(d){if(0==d[0].length)return c.next(),"searching";if(!c.sol()&&(c.backUp(1),!a.exec(c.next()+d[0])))return c.next(),null;c.match(a);return"searching"}for(;!c.eol()&&(c.next(),!c.match(a,!1)););}},query:a}} function cb(a,b){clearTimeout(oa);oa=setTimeout(function(){if(a.state.vim){var c=V(a),d=c.getOverlay();d&&b==d.query||(d&&a.removeOverlay(d),d=Bb(b),a.addOverlay(d),a.showMatchesOnScrollbar&&(c.getScrollbarAnnotate()&&c.getScrollbarAnnotate().clear(),c.setScrollbarAnnotate(a.showMatchesOnScrollbar(b))),c.setOverlay(d))}},50)}function db(a,b,c,d){void 0===d&&(d=1);return a.operation(function(){for(var f=a.getCursor(),e=a.getSearchCursor(c,f),h=0;h<d;h++){var k=e.find(b);if(0==h&&k&&Q(e.from(),f)){var g= b?e.from():e.to();(k=e.find(b))&&!k[0]&&Q(e.from(),g)&&a.getLine(g.line).length==g.ch&&(k=e.find(b))}if(!k&&(e=a.getSearchCursor(c,b?new q(a.lastLine()):new q(a.firstLine(),0)),!e.find(b)))return}return e.from()})}function Cb(a,b,c,d,f){void 0===d&&(d=1);return a.operation(function(){var e=a.getCursor(),h=a.getSearchCursor(c,e),k=h.find(!b);!f.visualMode&&k&&Q(h.from(),e)&&h.find(!b);for(e=0;e<d;e++)if(k=h.find(b),!k&&(h=a.getSearchCursor(c,b?new q(a.lastLine()):new q(a.firstLine(),0)),!h.find(b)))return; return[h.from(),h.to()]})}function Ga(a){var b=V(a);a.removeOverlay(V(a).getOverlay());b.setOverlay(null);b.getScrollbarAnnotate()&&(b.getScrollbarAnnotate().clear(),b.setScrollbarAnnotate(null))}function Db(a,b,c){"number"!=typeof a&&(a=a.line);return b instanceof Array?za(a,b):"number"==typeof c?a>=b&&a<=c:a==b}function Ha(a){var b=a.getScrollInfo(),c=a.coordsChar({left:0,top:6+b.top},"local");a=a.coordsChar({left:0,top:b.clientHeight-10+b.top},"local");return{top:c.line,bottom:a.line}}function eb(a, b,c){return"'"==c||"`"==c?u.jumpList.find(a,-1)||new q(0,0):"."==c?fb(a):(a=b.marks[c])&&a.find()}function fb(a){a=a.doc.history.done;for(var b=a.length;b--;)if(a[b].changes)return G(a[b].changes[0].to)}function Eb(a,b,c,d,f,e,h,k,g){function l(){a.operation(function(){for(;!r;)n(),t();v()})}function n(){var E=a.getRange(e.from(),e.to()).replace(h,k),z=e.to().line;e.replace(E);A=e.to().line;f+=A-z;C=A<z}function p(){var E=y&&G(e.to()),z=e.findNext();z&&!z[0]&&E&&Q(e.from(),E)&&(z=e.findNext());return z} function t(){for(;p()&&Db(e.from(),d,f);)if(c||e.from().line!=A||C){a.scrollIntoView(e.from(),30);a.setSelection(e.from(),e.to());y=e.from();r=!1;return}r=!0}function v(E){E&&E();a.focus();y&&(a.setCursor(y),E=a.state.vim,E.exMode=!1,E.lastHPos=E.lastHSPos=y.ch);g&&g()}a.state.vim.exMode=!0;var r=!1,y,A,C;t();r?F(a,"No matches for "+h.source):b?wa(a,{prefix:fa("span","replace with ",fa("strong",k)," (y/n/a/q/l)"),onKeyDown:function(E,z,D){m.e_stop(E);switch(m.keyName(E)){case "Y":n();t();break;case "N":t(); break;case "A":E=g;g=void 0;a.operation(l);g=E;break;case "L":n();case "Q":case "Esc":case "Ctrl-C":case "Ctrl-[":v(D)}r&&v(D);return!0}}):(l(),g&&g())}function ma(a){var b=a.state.vim,c=u.macroModeState,d=u.registerController.getRegister("."),f=c.isPlaying,e=c.lastInsertModeChanges;f||(a.off("change",gb),m.off(a.getInputField(),"keydown",hb));!f&&1<b.insertModeRepeat&&(ib(a,b,b.insertModeRepeat-1,!0),b.lastEditInputState.repeatOverride=b.insertModeRepeat);delete b.insertModeRepeat;b.insertMode=!1; a.setCursor(a.getCursor().line,a.getCursor().ch-1);a.setOption("keyMap","vim");a.setOption("disableInput",!0);a.toggleOverwrite(!1);d.setText(e.changes.join(""));m.signal(a,"vim-mode-change",{mode:"normal"});c.isRecording&&(c.isPlaying||(a=u.registerController.getRegister(c.latestRegister))&&a.pushInsertModeChanges&&a.pushInsertModeChanges(c.lastInsertModeChanges))}function jb(a){x.unshift(a)}function gb(a,b){var c=u.macroModeState,d=c.lastInsertModeChanges;if(!c.isPlaying)for(;b;){d.expectCursorActivityForChange= !0;if(1<d.ignoreCount)d.ignoreCount--;else if("+input"==b.origin||"paste"==b.origin||void 0===b.origin)c=a.listSelections().length,1<c&&(d.ignoreCount=c),c=b.text.join("\n"),d.maybeReset&&(d.changes=[],d.maybeReset=!1),c&&(a.state.overwrite&&!/\n/.test(c)?d.changes.push([c]):d.changes.push(c));b=b.next}}function Ja(a){var b=a.state.vim;if(b.insertMode)a=u.macroModeState,a.isPlaying||(a=a.lastInsertModeChanges,a.expectCursorActivityForChange?a.expectCursorActivityForChange=!1:a.maybeReset=!0);else if(!a.curOp.isVimOp){var c= a.getCursor("anchor"),d=a.getCursor("head");b.visualMode&&!a.somethingSelected()?T(a,!1):b.visualMode||b.insertMode||!a.somethingSelected()||(b.visualMode=!0,b.visualLine=!1,m.signal(a,"vim-mode-change",{mode:"visual"}));if(b.visualMode){var f=H(d,c)?0:-1,e=H(d,c)?-1:0;d=N(d,0,f);c=N(c,0,e);b.sel={anchor:c,head:d};Y(a,b,"<",R(d,c));Y(a,b,">",ea(d,c))}else b.insertMode||(b.lastHPos=a.getCursor().ch)}}function Ia(a){this.keyName=a}function hb(a){function b(){c.maybeReset&&(c.changes=[],c.maybeReset= !1);c.changes.push(new Ia(d));return!0}var c=u.macroModeState.lastInsertModeChanges,d=m.keyName(a);d&&(-1==d.indexOf("Delete")&&-1==d.indexOf("Backspace")||m.lookupKey(d,"vim-insert",b))}function ib(a,b,c,d){function f(){k?ba.processAction(a,b,b.lastEditActionCommand):ba.evalInput(a,b)}function e(n){0<h.lastInsertModeChanges.changes.length&&(n=b.lastEditActionCommand?n:1,kb(a,h.lastInsertModeChanges.changes,n))}var h=u.macroModeState;h.isPlaying=!0;var k=!!b.lastEditActionCommand,g=b.inputState;b.inputState= b.lastEditInputState;if(k&&b.lastEditActionCommand.interlaceInsertRepeat)for(var l=0;l<c;l++)f(),e(1);else d||f(),e(c);b.inputState=g;b.insertMode&&!d&&ma(a);h.isPlaying=!1}function kb(a,b,c){function d(p){if("string"==typeof p)m.commands[p](a);else p(a);return!0}var f=a.getCursor("head"),e=u.macroModeState.lastInsertModeChanges.visualBlock;e&&(Va(a,f,e+1),c=a.listSelections().length,a.setCursor(f));for(var h=0;h<c;h++){e&&a.setCursor(N(f,h,0));for(var k=0;k<b.length;k++){var g=b[k];if(g instanceof Ia)m.lookupKey(g.keyName,"vim-insert",d);else if("string"==typeof g)a.replaceSelection(g);else{var l=a.getCursor(),n=N(l,0,g[0].length);a.replaceRange(g[0],l,n);a.setCursor(n)}}}e&&a.setCursor(N(f,0,1))}m.defineOption("vimMode",!1,function(a,b,c){b&&"vim"!=a.getOption("keyMap")?a.setOption("keyMap","vim"):!b&&c!=m.Init&&/^vim/.test(a.getOption("keyMap"))&&a.setOption("keyMap","default")});var La={Shift:"S",Ctrl:"C",Alt:"A",Cmd:"D",Mod:"A",CapsLock:""},Ma={Enter:"CR",Backspace:"BS",Delete:"Del",Insert:"Ins"}, Fb=/[\d]/,va=[m.isWordChar,function(a){return a&&!m.isWordChar(a)&&!/\s/.test(a)}],Ea=[function(a){return/\S/.test(a)}],lb=xa(65,26),mb=xa(97,26),nb=xa(48,10),zb=[].concat(lb,mb,nb,["<",">"]),ob=[].concat(lb,mb,nb,'-".:_/'.split(""));try{var ja=RegExp("^[\\p{Lu}]$","u")}catch(a){ja=/^[A-Z]$/}var X={};ra("filetype",void 0,"string",["ft"],function(a,b){if(void 0!==b){if(void 0===a)return a=b.getOption("mode"),"null"==a?"":a;b.setOption("mode",""==a?"null":a)}});var wb=function(){function a(e,h){b+= h;b>c?b=c:b<d&&(b=d);var k=f[(100+b)%100];if(k&&!k.find()){h=0<h?1:-1;var g;e=e.getCursor();do if(b+=h,(k=f[(100+b)%100])&&(g=k.find())&&!Q(e,g))break;while(b<c&&b>d)}return k}var b=-1,c=0,d=0,f=Array(100);return{cachedCursor:void 0,add:function(e,h,k){function g(n){var p=++b%100,t=f[p];t&&t.clear();f[p]=e.setBookmark(n)}var l=f[b%100];l?(l=l.find())&&!Q(l,h)&&g(h):g(h);g(k);c=b;d=b-100+1;0>d&&(d=0)},find:function(e,h){var k=b;e=a(e,h);b=k;return e&&e.find()},move:a}},Oa=function(a){return a?{changes:a.changes, expectCursorActivityForChange:a.expectCursorActivityForChange}:{changes:[],expectCursorActivityForChange:!1}};Na.prototype={exitMacroRecordMode:function(){var a=u.macroModeState;if(a.onRecordingDone)a.onRecordingDone();a.onRecordingDone=void 0;a.isRecording=!1},enterMacroRecordMode:function(a,b){var c=u.registerController.getRegister(b);c&&(c.clear(),this.latestRegister=b,a.openDialog&&(this.onRecordingDone=a.openDialog(document.createTextNode("(recording)["+b+"]"),null,{bottom:!0})),this.isRecording= !0)}};var u,na,ia={buildKeyMap:function(){},getRegisterController:function(){return u.registerController},resetVimGlobalState_:Pa,getVimGlobalState_:function(){return u},maybeInitVimState_:pa,suppressErrorLogging:!1,InsertModeKey:Ia,map:function(a,b,c){W.map(a,b,c)},unmap:function(a,b){return W.unmap(a,b)},noremap:function(a,b,c){function d(p){return p?[p]:["normal","insert","visual"]}for(var f=d(c),e=x.length,h=e-B;h<e&&f.length;h++){var k=x[h];if(!(k.keys!=b||c&&k.context&&k.context!==c)&&"ex"!== k.type.substr(0,2)&&"key"!==k.type.substr(0,3)){var g={},l;for(l in k)g[l]=k[l];g.keys=a;c&&!g.context&&(g.context=c);this._mapCommand(g);var n=d(k.context);f=f.filter(function(p){return-1===n.indexOf(p)})}}},mapclear:function(a){var b=x.length,c=x.slice(0,b-B);x=x.slice(b-B);if(a)for(b=c.length-1;0<=b;b--){var d=c[b];if(a!==d.context)if(d.context)this._mapCommand(d);else{var f=["normal","insert","visual"],e;for(e in f)if(f[e]!==a){var h={},k;for(k in d)h[k]=d[k];h.context=f[e];this._mapCommand(h)}}}}, setOption:Aa,getOption:da,defineOption:ra,defineEx:function(a,b,c){if(!b)b=a;else if(0!==a.indexOf(b))throw Error('(Vim.defineEx) "'+b+'" is not a prefix of "'+a+'", command not registered');pb[a]=c;W.commandMap_[b]={name:a,shortName:b,type:"api"}},handleKey:function(a,b,c){a=this.findKey(a,b,c);if("function"===typeof a)return a()},findKey:function(a,b,c){function d(){if("<Esc>"==b)return O(a),h.visualMode?T(a):h.insertMode&&ma(a),!0}function f(){if(d())return!0;for(var g=h.inputState.keyBuffer+= b,l=1==b.length,n=ba.matchCommand(g,x,h.inputState,"insert");1<g.length&&"full"!=n.type;){g=h.inputState.keyBuffer=g.slice(1);var p=ba.matchCommand(g,x,h.inputState,"insert");"none"!=p.type&&(n=p)}if("none"==n.type)return O(a),!1;if("partial"==n.type)return na&&window.clearTimeout(na),na=window.setTimeout(function(){h.insertMode&&h.inputState.keyBuffer&&O(a)},da("insertModeEscKeysTimeout")),!l;na&&window.clearTimeout(na);if(l){l=a.listSelections();for(p=0;p<l.length;p++){var t=l[p].head;a.replaceRange("", N(t,0,-(g.length-1)),t,"+input")}u.macroModeState.lastInsertModeChanges.changes.pop()}O(a);return n.command}function e(){a:{var g=u.macroModeState;if(g.isRecording){if("q"==b){g.exitMacroRecordMode();O(a);var l=!0;break a}"mapping"!=c&&(l=b,g.isPlaying||(g=u.registerController.getRegister(g.latestRegister))&&g.pushText(l))}l=void 0}if(l||d())return!0;l=h.inputState.keyBuffer+=b;if(/^[1-9]\d*$/.test(l))return!0;g=/^(\d*)(.*)$/.exec(l);if(!g)return O(a),!1;var n=h.visualMode?"visual":"normal";g=g[2]|| g[1];h.inputState.operatorShortcut&&h.inputState.operatorShortcut.slice(-1)==g&&(g=h.inputState.operatorShortcut);n=ba.matchCommand(g,x,h.inputState,n);if("none"==n.type)return O(a),!1;if("partial"==n.type)return!0;h.inputState.keyBuffer="";g=/^(\d*)(.*)$/.exec(l);g[1]&&"0"!=g[1]&&h.inputState.pushRepeatDigit(g[1]);return n.command}var h=pa(a);var k=h.insertMode?f():e();return!1===k?h.insertMode||1!==b.length?void 0:function(){return!0}:!0===k?function(){return!0}:function(){return a.operation(function(){a.curOp.isVimOp= !0;try{if("keyToKey"==k.type)for(var g=k.toKeys,l;g;)l=/<\w+-.+?>|<\w+>|./.exec(g),b=l[0],g=g.substring(l.index+b.length),ia.handleKey(a,b,"mapping");else ba.processCommand(a,h,k)}catch(n){throw a.state.vim=void 0,pa(a),ia.suppressErrorLogging||console.log(n),n;}return!0})}},handleEx:function(a,b){W.processCommand(a,b)},defineMotion:function(a,b){Z[a]=b},defineAction:function(a,b){qa[a]=b},defineOperator:function(a,b){qb[a]=b},mapCommand:function(a,b,c,d,f){a={keys:a,type:b};a[b]=c;a[b+"Args"]=d; for(var e in f)a[e]=f[e];jb(a)},_mapCommand:jb,defineRegister:function(a,b){var c=u.registerController.registers;if(!a||1!=a.length)throw Error("Register name must be 1 character");if(c[a])throw Error("Register already defined "+a);c[a]=b;ob.push(a)},exitVisualMode:T,exitInsertMode:ma};sa.prototype.pushRepeatDigit=function(a){this.operator?this.motionRepeat=this.motionRepeat.concat(a):this.prefixRepeat=this.prefixRepeat.concat(a)};sa.prototype.getRepeat=function(){var a=0;if(0<this.prefixRepeat.length|| 0<this.motionRepeat.length)a=1,0<this.prefixRepeat.length&&(a*=parseInt(this.prefixRepeat.join(""),10)),0<this.motionRepeat.length&&(a*=parseInt(this.motionRepeat.join(""),10));return a};S.prototype={setText:function(a,b,c){this.keyBuffer=[a||""];this.linewise=!!b;this.blockwise=!!c},pushText:function(a,b){b&&(this.linewise||this.keyBuffer.push("\n"),this.linewise=!0);this.keyBuffer.push(a)},pushInsertModeChanges:function(a){this.insertModeChanges.push(Oa(a))},pushSearchQuery:function(a){this.searchQueries.push(a)}, clear:function(){this.keyBuffer=[];this.insertModeChanges=[];this.searchQueries=[];this.linewise=!1},toString:function(){return this.keyBuffer.join("")}};Qa.prototype={pushText:function(a,b,c,d,f){if("_"!==a){d&&"\n"!==c.charAt(c.length-1)&&(c+="\n");var e=this.isValidRegister(a)?this.getRegister(a):null;if(e)ja.test(a)?e.pushText(c,d):e.setText(c,d,f),this.unnamedRegister.setText(e.toString(),d);else{switch(b){case "yank":this.registers["0"]=new S(c,d,f);break;case "delete":case "change":-1==c.indexOf("\n")? this.registers["-"]=new S(c,d):(this.shiftNumericRegisters_(),this.registers["1"]=new S(c,d))}this.unnamedRegister.setText(c,d,f)}}},getRegister:function(a){if(!this.isValidRegister(a))return this.unnamedRegister;a=a.toLowerCase();this.registers[a]||(this.registers[a]=new S);return this.registers[a]},isValidRegister:function(a){return a&&za(a,ob)},shiftNumericRegisters_:function(){for(var a=9;2<=a;a--)this.registers[a]=this.getRegister(""+(a-1))}};Ba.prototype={nextMatch:function(a,b){var c=this.historyBuffer, d=b?-1:1;null===this.initialPrefix&&(this.initialPrefix=a);for(var f=this.iterator+d;b?0<=f:f<c.length;f+=d)for(var e=c[f],h=0;h<=e.length;h++)if(this.initialPrefix==e.substring(0,h))return this.iterator=f,e;if(f>=c.length)return this.iterator=c.length,this.initialPrefix;if(0>f)return a},pushInput:function(a){var b=this.historyBuffer.indexOf(a);-1<b&&this.historyBuffer.splice(b,1);a.length&&this.historyBuffer.push(a)},reset:function(){this.initialPrefix=null;this.iterator=this.historyBuffer.length}}; var ba={matchCommand:function(a,b,c,d){var f=[];var e=[];for(var h=0;h<b.length;h++){var k=b[h],g;if(g=!("insert"==d&&"insert"!=k.context||k.context&&k.context!=d||c.operator&&"action"==k.type)){var l=a;var n=k.keys;if("<character>"==n.slice(-11)){g=n.length-11;var p=l.slice(0,g);n=n.slice(0,g);l=p==n&&l.length>g?"full":0==n.indexOf(p)?"partial":!1}else l=l==n?"full":0==n.indexOf(l)?"partial":!1;g=l}g&&("partial"==l&&f.push(k),"full"==l&&e.push(k))}b=f.length&&f;e=e.length&&e;if(!e&&!b)return{type:"none"}; if(!e&&b)return{type:"partial"};var t;for(b=0;b<e.length;b++)d=e[b],t||(t=d);if("<character>"==t.keys.slice(-11)){a=(e=/^.*(<[^>]+>)$/.exec(a))?e[1]:a.slice(-1);if(1<a.length)switch(a){case "<CR>":a="\n";break;case "<Space>":a=" ";break;default:a=""}if(!a)return{type:"none"};c.selectedCharacter=a}return{type:"full",command:t}},processCommand:function(a,b,c){b.inputState.repeatOverride=c.repeatOverride;switch(c.type){case "motion":this.processMotion(a,b,c);break;case "operator":this.processOperator(a, b,c);break;case "operatorMotion":this.processOperatorMotion(a,b,c);break;case "action":this.processAction(a,b,c);break;case "search":this.processSearch(a,b,c);break;case "ex":case "keyToEx":this.processEx(a,b,c)}},processMotion:function(a,b,c){b.inputState.motion=c.motion;b.inputState.motionArgs=ta(c.motionArgs);this.evalInput(a,b)},processOperator:function(a,b,c){var d=b.inputState;if(d.operator){if(d.operator==c.operator){d.motion="expandToLine";d.motionArgs={linewise:!0};this.evalInput(a,b);return}O(a)}d.operator= c.operator;d.operatorArgs=ta(c.operatorArgs);1<c.keys.length&&(d.operatorShortcut=c.keys);c.exitVisualBlock&&(b.visualBlock=!1,ka(a));b.visualMode&&this.evalInput(a,b)},processOperatorMotion:function(a,b,c){var d=b.visualMode,f=ta(c.operatorMotionArgs);f&&d&&f.visualLine&&(b.visualLine=!0);this.processOperator(a,b,c);d||this.processMotion(a,b,c)},processAction:function(a,b,c){var d=b.inputState,f=d.getRepeat(),e=!!f,h=ta(c.actionArgs)||{};d.selectedCharacter&&(h.selectedCharacter=d.selectedCharacter); c.operator&&this.processOperator(a,b,c);c.motion&&this.processMotion(a,b,c);(c.motion||c.operator)&&this.evalInput(a,b);h.repeat=f||1;h.repeatIsExplicit=e;h.registerName=d.registerName;O(a);b.lastMotion=null;c.isEdit&&this.recordLastEdit(b,d,c);qa[c.action](a,h,b)},processSearch:function(a,b,c){function d(r,y,A){u.searchHistoryController.pushInput(r);u.searchHistoryController.reset();try{la(a,r,y,A)}catch(C){F(a,"Invalid regex: "+r);O(a);return}ba.processMotion(a,b,{type:"motion",motion:"findNext", motionArgs:{forward:!0,toJumplist:c.searchArgs.toJumplist}})}function f(r){a.scrollTo(p.left,p.top);d(r,!0,!0);var y=u.macroModeState;y.isRecording&&(y.isPlaying||(y=u.registerController.getRegister(y.latestRegister))&&y.pushSearchQuery&&y.pushSearchQuery(r))}function e(r,y,A){var C=m.keyName(r);if("Up"==C||"Down"==C){var E=r.target?r.target.selectionEnd:0;y=u.searchHistoryController.nextMatch(y,"Up"==C?!0:!1)||"";A(y);E&&r.target&&(r.target.selectionEnd=r.target.selectionStart=Math.min(E,r.target.value.length))}else"Left"!= C&&"Right"!=C&&"Ctrl"!=C&&"Alt"!=C&&"Shift"!=C&&u.searchHistoryController.reset();try{var z=la(a,y,!0,!0)}catch(D){}z?a.scrollIntoView(db(a,!k,z),30):(Ga(a),a.scrollTo(p.left,p.top))}function h(r,y,A){var C=m.keyName(r);"Esc"==C||"Ctrl-C"==C||"Ctrl-["==C||"Backspace"==C&&""==y?(u.searchHistoryController.pushInput(y),u.searchHistoryController.reset(),la(a,n),Ga(a),a.scrollTo(p.left,p.top),m.e_stop(r),O(a),A(),a.focus()):"Up"==C||"Down"==C?m.e_stop(r):"Ctrl-U"==C&&(m.e_stop(r),A(""))}if(a.getSearchCursor){var k= c.searchArgs.forward,g=c.searchArgs.wholeWordOnly;V(a).setReversed(!k);var l=k?"/":"?",n=V(a).getQuery(),p=a.getScrollInfo();switch(c.searchArgs.querySrc){case "prompt":g=u.macroModeState;g.isPlaying?(l=g.replaySearchQueries.shift(),d(l,!0,!1)):wa(a,{onClose:f,prefix:l,desc:"(JavaScript regexp)",onKeyUp:e,onKeyDown:h});break;case "wordUnderCursor":var t=ua(a,!1,!0,!1,!0),v=!0;t||(t=ua(a,!1,!0,!1,!1),v=!1);t&&(l=a.getLine(t.start.line).substring(t.start.ch,t.end.ch),l=v&&g?"\\b"+l+"\\b":l.replace(/([.?*+$\[\]\/\\(){}|\-])/g, "\\$1"),u.jumpList.cachedCursor=a.getCursor(),a.setCursor(t.start),d(l,!0,!1))}}},processEx:function(a,b,c){function d(e){u.exCommandHistoryController.pushInput(e);u.exCommandHistoryController.reset();W.processCommand(a,e)}function f(e,h,k){var g=m.keyName(e);if("Esc"==g||"Ctrl-C"==g||"Ctrl-["==g||"Backspace"==g&&""==h)u.exCommandHistoryController.pushInput(h),u.exCommandHistoryController.reset(),m.e_stop(e),O(a),k(),a.focus();if("Up"==g||"Down"==g){m.e_stop(e);var l=e.target?e.target.selectionEnd: 0;h=u.exCommandHistoryController.nextMatch(h,"Up"==g?!0:!1)||"";k(h);l&&e.target&&(e.target.selectionEnd=e.target.selectionStart=Math.min(l,e.target.value.length))}else"Ctrl-U"==g?(m.e_stop(e),k("")):"Left"!=g&&"Right"!=g&&"Ctrl"!=g&&"Alt"!=g&&"Shift"!=g&&u.exCommandHistoryController.reset()}"keyToEx"==c.type?W.processCommand(a,c.exArgs.input):b.visualMode?wa(a,{onClose:d,prefix:":",value:"'<,'>",onKeyDown:f,selectValueOnOpen:!1}):wa(a,{onClose:d,prefix:":",onKeyDown:f})},evalInput:function(a,b){var c= b.inputState,d=c.motion,f=c.motionArgs||{},e=c.operator,h=c.operatorArgs||{},k=c.registerName,g=b.sel,l=G(b.visualMode?P(a,g.head):a.getCursor("head")),n=G(b.visualMode?P(a,g.anchor):a.getCursor("anchor")),p=G(l);n=G(n);e&&this.recordLastEdit(b,c);var t=void 0!==c.repeatOverride?c.repeatOverride:c.getRepeat();if(0<t&&f.explicitRepeat)f.repeatIsExplicit=!0;else if(f.noRepeat||!f.explicitRepeat&&0===t)t=1,f.repeatIsExplicit=!1;c.selectedCharacter&&(f.selectedCharacter=h.selectedCharacter=c.selectedCharacter); f.repeat=t;O(a);if(d){var v=Z[d](a,l,f,b,c);b.lastMotion=Z[d];if(!v)return;f.toJumplist&&(d=u.jumpList,(c=d.cachedCursor)?(Q(c,v)||u.jumpList.add(a,c,v),delete d.cachedCursor):Q(l,v)||u.jumpList.add(a,l,v));if(v instanceof Array){var r=v[0];v=v[1]}v||(v=G(l));b.visualMode?(b.visualBlock&&Infinity===v.ch||(v=P(a,v)),r&&(r=P(a,r)),r=r||n,g.anchor=r,g.head=v,ka(a),Y(a,b,"<",H(r,v)?r:v),Y(a,b,">",H(r,v)?v:r)):e||(v=P(a,v),a.setCursor(v.line,v.ch))}if(e){h.lastSel?(r=n,g=h.lastSel,v=Math.abs(g.head.line- g.anchor.line),l=Math.abs(g.head.ch-g.anchor.ch),v=g.visualLine?new q(n.line+v,n.ch):g.visualBlock?new q(n.line+v,n.ch+l):g.head.line==g.anchor.line?new q(n.line,n.ch+l):new q(n.line+v,n.ch),b.visualMode=!0,b.visualLine=g.visualLine,b.visualBlock=g.visualBlock,g=b.sel={anchor:r,head:v},ka(a)):b.visualMode&&(h.lastSel={anchor:G(g.anchor),head:G(g.head),visualBlock:b.visualBlock,visualLine:b.visualLine});if(b.visualMode){if(r=R(g.head,g.anchor),g=ea(g.head,g.anchor),p=b.visualLine||h.linewise,f=b.visualBlock? "block":p?"line":"char",r=Da(a,{anchor:r,head:g},f),p)if(g=r.ranges,"block"==f)for(f=0;f<g.length;f++)g[f].head.ch=I(a,g[f].head.line);else"line"==f&&(g[0].head=new q(g[0].head.line+1,0))}else{r=G(r||n);g=G(v||p);H(g,r)&&(p=r,r=g,g=p);if(p=f.linewise||h.linewise)l=g,r.ch=0,l.ch=0,l.line++;else if(f.forward&&(l=g,d=a.getRange(r,l),/\n\s*$/.test(d))){d=d.split("\n");d.pop();for(c=d.pop();0<d.length&&c&&ca(c);c=d.pop())l.line--,l.ch=0;c?(l.line--,l.ch=I(a,l.line)):l.ch=0}r=Da(a,{anchor:r,head:g},"char", !f.inclusive||p)}a.setSelections(r.ranges,r.primary);b.lastMotion=null;h.repeat=t;h.registerName=k;h.linewise=p;e=qb[e](a,h,r.ranges,n,v);b.visualMode&&T(a,null!=e);e&&a.setCursor(e)}},recordLastEdit:function(a,b,c){var d=u.macroModeState;d.isPlaying||(a.lastEditInputState=b,a.lastEditActionCommand=c,d.lastInsertModeChanges.changes=[],d.lastInsertModeChanges.expectCursorActivityForChange=!1,d.lastInsertModeChanges.visualBlock=a.visualBlock?a.sel.head.line-a.sel.anchor.line:0)}},Z={moveToTopLine:function(a, b,c){b=Ha(a).top+c.repeat-1;return new q(b,U(a.getLine(b)))},moveToMiddleLine:function(a){var b=Ha(a);b=Math.floor(.5*(b.top+b.bottom));return new q(b,U(a.getLine(b)))},moveToBottomLine:function(a,b,c){b=Ha(a).bottom-c.repeat+1;return new q(b,U(a.getLine(b)))},expandToLine:function(a,b,c){return new q(b.line+c.repeat-1,Infinity)},findNext:function(a,b,c){b=V(a);var d=b.getQuery();if(d){var f=!c.forward;f=b.isReversed()?!f:f;cb(a,d);return db(a,f,d,c.repeat)}},findAndSelectNextInclusive:function(a, b,c,d,f){b=V(a);var e=b.getQuery();if(e){var h=!c.forward;h=b.isReversed()?!h:h;if(e=Cb(a,h,e,c.repeat,d)){if(f.operator)return e;f=e[0];e=new q(e[1].line,e[1].ch-1);if(d.visualMode){if(d.visualLine||d.visualBlock)d.visualLine=!1,d.visualBlock=!1,m.signal(a,"vim-mode-change",{mode:"visual",subMode:""});if(a=d.sel.anchor)return b.isReversed()?c.forward?[a,f]:[a,e]:c.forward?[a,e]:[a,f]}else d.visualMode=!0,d.visualLine=!1,d.visualBlock=!1,m.signal(a,"vim-mode-change",{mode:"visual",subMode:""});return h? [e,f]:[f,e]}}},goToMark:function(a,b,c,d){return(b=eb(a,d,c.selectedCharacter))?c.linewise?{line:b.line,ch:U(a.getLine(b.line))}:b:null},moveToOtherHighlightedEnd:function(a,b,c,d){return d.visualBlock&&c.sameLine?(b=d.sel,[P(a,new q(b.anchor.line,b.head.ch)),P(a,new q(b.head.line,b.anchor.ch))]):[d.sel.head,d.sel.anchor]},jumpToMark:function(a,b,c,d){for(var f=0;f<c.repeat;f++){var e=b,h;for(h in d.marks)if(/^[a-z]$/.test(h)){var k=d.marks[h].find();if(c.forward?!H(k,e):!H(e,k))if(!c.linewise||k.line!= e.line){var g=Q(e,b),l=c.forward?Ta(e,k,b):Ta(b,k,e);if(g||l)b=k}}}c.linewise&&(b=new q(b.line,U(a.getLine(b.line))));return b},moveByCharacters:function(a,b,c){a=c.repeat;return new q(b.line,c.forward?b.ch+a:b.ch-a)},moveByLines:function(a,b,c,d){var f=b.ch;switch(d.lastMotion){case this.moveByLines:case this.moveByDisplayLines:case this.moveByScroll:case this.moveToColumn:case this.moveToEol:f=d.lastHPos;break;default:d.lastHPos=f}var e=c.repeat+(c.repeatOffset||0),h=c.forward?b.line+e:b.line-e, k=a.firstLine(),g=a.lastLine();e=a.findPosV(b,c.forward?e:-e,"line",d.lastHSPos);if(c.forward?e.line>h:e.line<h)h=e.line,f=e.ch;if(h<k&&b.line==k)return this.moveToStartOfLine(a,b,c,d);if(h>g&&b.line==g)return Ya(a,b,c,d,!0);c.toFirstChar&&(f=U(a.getLine(h)),d.lastHPos=f);d.lastHSPos=a.charCoords(new q(h,f),"div").left;return new q(h,f)},moveByDisplayLines:function(a,b,c,d){switch(d.lastMotion){case this.moveByDisplayLines:case this.moveByScroll:case this.moveByLines:case this.moveToColumn:case this.moveToEol:break; default:d.lastHSPos=a.charCoords(b,"div").left}var f=c.repeat;b=a.findPosV(b,c.forward?f:-f,"line",d.lastHSPos);b.hitSide&&(c.forward?(c={top:a.charCoords(b,"div").top+8,left:d.lastHSPos},b=a.coordsChar(c,"div")):(c=a.charCoords(new q(a.firstLine(),0),"div"),c.left=d.lastHSPos,b=a.coordsChar(c,"div")));d.lastHPos=b.ch;return b},moveByPage:function(a,b,c){var d=c.repeat;return a.findPosV(b,c.forward?d:-d,"page")},moveByParagraph:function(a,b,c){return Za(a,b,c.repeat,c.forward?1:-1)},moveBySentence:function(a, b,c){return Ab(a,b,c.repeat,c.forward?1:-1)},moveByScroll:function(a,b,c,d){var f=a.getScrollInfo(),e=c.repeat;e||(e=f.clientHeight/(2*a.defaultTextHeight()));var h=a.charCoords(b,"local");c.repeat=e;b=Z.moveByDisplayLines(a,b,c,d);if(!b)return null;c=a.charCoords(b,"local");a.scrollTo(null,f.top+c.top-h.top);return b},moveByWords:function(a,b,c){var d=b,f=c.repeat;b=!!c.forward;var e=!!c.wordEnd,h=!!c.bigWord;c=G(d);var k=[];(b&&!e||!b&&e)&&f++;for(var g=!(b&&e),l=0;l<f;l++){b:{var n=a;var p=b,t= h,v=g,r=d.line,y=d.ch,A=n.getLine(r),C=p?1:-1;t=t?Ea:va;if(v&&""==A){r+=C;A=n.getLine(r);if(!ya(n,r)){n=null;break b}y=p?0:A.length}for(;;){if(v&&""==A){n={from:0,to:0,line:r};break b}p=0<C?A.length:-1;for(var E,z;y!=p;){for(var D=!1,L=0;L<t.length&&!D;++L)if(t[L](A.charAt(y))){for(E=y;y!=p&&t[L](A.charAt(y));)y+=C;z=y;D=E!=z;if(E!=d.ch||r!=d.line||z!=E+C){n={from:Math.min(E,z+1),to:Math.max(E,z),line:r};break b}}D||(y+=C)}r+=C;if(!ya(n,r)){n=null;break b}A=n.getLine(r);y=0<C?0:A.length}}if(!n){h= I(a,a.lastLine());k.push(b?{line:a.lastLine(),from:h,to:h}:{line:0,from:0,to:0});break}k.push(n);d=new q(n.line,b?n.to-1:n.from)}a=k.length!=f;f=k[0];h=k.pop();b&&!e?(a||f.from==c.ch&&f.line==c.line||(h=k.pop()),b=new q(h.line,h.from)):b&&e?b=new q(h.line,h.to-1):!b&&e?(a||f.to==c.ch&&f.line==c.line||(h=k.pop()),b=new q(h.line,h.to)):b=new q(h.line,h.from);return b},moveTillCharacter:function(a,b,c){a=Fa(a,c.repeat,c.forward,c.selectedCharacter);b=c.forward?-1:1;Xa(b,c);if(!a)return null;a.ch+=b; return a},moveToCharacter:function(a,b,c){var d=c.repeat;Xa(0,c);return Fa(a,d,c.forward,c.selectedCharacter)||b},moveToSymbol:function(a,b,c){var d=c.repeat,f=c.forward,e=c.selectedCharacter;c=G(a.getCursor());var h=f?1:-1,k=f?a.lineCount():-1,g=c.ch,l=c.line,n=a.getLine(l);f={lineText:n,nextCh:n.charAt(g),lastCh:null,index:g,symb:e,reverseSymb:(f?{")":"(","}":"{"}:{"(":")","{":"}"})[e],forward:f,depth:0,curMoveThrough:!1};if(g=Gb[e]){e=rb[g].init;g=rb[g].isComplete;for(e&&e(f);l!==k&&d;)f.index+= h,f.nextCh=f.lineText.charAt(f.index),f.nextCh||(l+=h,f.lineText=a.getLine(l)||"",0<h?f.index=0:(e=f.lineText.length,f.index=0<e?e-1:0),f.nextCh=f.lineText.charAt(f.index)),g(f)&&(c.line=l,c.ch=f.index,d--);a=f.nextCh||f.curMoveThrough?new q(l,f.index):c}else a=c;return a||b},moveToColumn:function(a,b,c,d){c=c.repeat;d.lastHPos=c-1;d.lastHSPos=a.charCoords(b,"div").left;b=a.getCursor().line;return P(a,new q(b,c-1))},moveToEol:function(a,b,c,d){return Ya(a,b,c,d,!1)},moveToFirstNonWhiteSpaceCharacter:function(a, b){return new q(b.line,U(a.getLine(b.line)))},moveToMatchedSymbol:function(a,b){for(var c=b.line,d=b.ch,f=a.getLine(c),e;d<f.length&&(!(e=f.charAt(d))||-1=="()[]{}".indexOf(e)||(e=a.getTokenTypeAt(new q(c,d+1)),"string"===e||"comment"===e));d++);return d<f.length?(b="<"===d||">"===d?/[(){}[\]<>]/:/[(){}[\]]/,a.findMatchingBracket(new q(c,d),{bracketRegex:b}).to):b},moveToStartOfLine:function(a,b){return new q(b.line,0)},moveToLineOrEdgeOfDocument:function(a,b,c){b=c.forward?a.lastLine():a.firstLine(); c.repeatIsExplicit&&(b=c.repeat-a.getOption("firstLineNumber"));return new q(b,U(a.getLine(b)))},moveToStartOfDisplayLine:function(a){a.execCommand("goLineLeft");return a.getCursor()},moveToEndOfDisplayLine:function(a){a.execCommand("goLineRight");a=a.getCursor();"before"==a.sticky&&a.ch--;return a},textObjectManipulation:function(a,b,c,d){var f={"'":!0,'"':!0,"`":!0},e=c.selectedCharacter;"b"==e?e="(":"B"==e&&(e="{");var h=!c.textObjectInner;if({"(":")",")":"(","{":"}","}":"{","[":"]","]":"[","<":">", ">":"<"}[e]){var k={"(":/[()]/,")":/[()]/,"[":/[[\]]/,"]":/[[\]]/,"{":/[{}]/,"}":/[{}]/,"<":/[<>]/,">":/[<>]/}[e];var g={"(":"(",")":"(","[":"[","]":"[","{":"{","}":"{","<":"<",">":"<"}[e];c=a.getLine(b.line).charAt(b.ch)===g?1:0;g=a.scanForBracket(new q(b.line,b.ch+c),-1,void 0,{bracketRegex:k});k=a.scanForBracket(new q(b.line,b.ch+c),1,void 0,{bracketRegex:k});if(g&&k){g=g.pos;k=k.pos;if(g.line==k.line&&g.ch>k.ch||g.line>k.line)b=g,g=k,k=b;h?k.ch+=1:g.ch+=1;b={start:g,end:k}}else b={start:b,end:b}}else if(f[e]){c= e;b=G(b);d=a.getLine(b.line).split("");e=d.indexOf(c);b.ch<e?b.ch=e:e<b.ch&&d[b.ch]==c&&(k=b.ch,--b.ch);if(d[b.ch]!=c||k)for(e=b.ch;-1<e&&!g;e--)d[e]==c&&(g=e+1);else g=b.ch+1;if(g&&!k)for(e=g,f=d.length;e<f&&!k;e++)d[e]==c&&(k=e);g&&k?(h&&(--g,++k),b={start:new q(b.line,g),end:new q(b.line,k)}):b={start:b,end:b}}else if("W"===e)b=ua(a,h,!0,!0);else if("w"===e)b=ua(a,h,!0,!1);else if("p"===e)if(b=Za(a,b,c.repeat,0,h),c.linewise=!0,d.visualMode)d.visualLine||(d.visualLine=!0);else{if(h=d.inputState.operatorArgs)h.linewise= !0;b.end.line--}else if("t"===e)b=m.findMatchingTag&&m.findEnclosingTag?(g=m.findMatchingTag(a,b)||m.findEnclosingTag(a,b))&&g.open&&g.close?h?{start:g.open.from,end:g.close.to}:{start:g.open.to,end:g.close.from}:{start:b,end:b}:{start:b,end:b};else return null;return a.state.vim.visualMode?(h=b.start,b=b.end,k=a.state.vim.sel,g=k.head,k=k.anchor,H(b,h)&&(c=b,b=h,h=c),H(g,k)?(g=R(h,g),k=ea(k,b)):(k=R(h,k),g=ea(g,b),g=N(g,0,-1),-1==g.ch&&g.line!=a.firstLine()&&(g=new q(g.line-1,I(a,g.line-1)))),[k, g]):[b.start,b.end]},repeatLastCharacterSearch:function(a,b,c){var d=u.lastCharacterSearch,f=c.repeat,e=c.forward===d.forward,h=(d.increment?1:0)*(e?-1:1);a.moveH(-h,"char");c.inclusive=e?!0:!1;c=Fa(a,f,e,d.selectedCharacter);if(!c)return a.moveH(h,"char"),b;c.ch+=h;return c}},qb={change:function(a,b,c){var d=a.state.vim;var f=c[0].anchor;var e=c[0].head;if(d.visualMode)if(b.fullLine){e.ch=Number.MAX_VALUE;e.line--;a.setSelection(f,e);var h=a.getSelection();a.replaceSelection("")}else h=a.getSelection(), f=Ra("",c.length),a.replaceSelections(f),f=R(c[0].head,c[0].anchor);else{h=a.getRange(f,e);d=d.lastEditInputState||{};if("moveByWords"==d.motion&&!ca(h)){var k=/\s+$/.exec(h);k&&d.motionArgs&&d.motionArgs.forward&&(e=N(e,0,-k[0].length),h=h.slice(0,-k[0].length))}d=new q(f.line-1,Number.MAX_VALUE);k=a.firstLine()==a.lastLine();e.line>a.lastLine()&&b.linewise&&!k?a.replaceRange("",d,e):a.replaceRange("",f,e);b.linewise&&(k||(a.setCursor(d),m.commands.newlineAndIndent(a)),f.ch=Number.MAX_VALUE)}u.registerController.pushText(b.registerName, "change",h,b.linewise,1<c.length);qa.enterInsertMode(a,{head:f},a.state.vim)},"delete":function(a,b,c){var d=a.state.vim;if(d.visualBlock){var f=a.getSelection();var e=Ra("",c.length);a.replaceSelections(e);c=R(c[0].head,c[0].anchor)}else e=c[0].anchor,c=c[0].head,b.linewise&&c.line!=a.firstLine()&&e.line==a.lastLine()&&e.line==c.line-1&&(e.line==a.firstLine()?e.ch=0:e=new q(e.line-1,I(a,e.line-1))),f=a.getRange(e,c),a.replaceRange("",e,c),c=e,b.linewise&&(c=Z.moveToFirstNonWhiteSpaceCharacter(a, e));u.registerController.pushText(b.registerName,"delete",f,b.linewise,d.visualBlock);return P(a,c)},indent:function(a,b,c){var d=a.state.vim,f=c[0].anchor.line,e=d.visualBlock?c[c.length-1].anchor.line:c[0].head.line;d=d.visualMode?b.repeat:1;for(b.linewise&&e--;f<=e;f++)for(var h=0;h<d;h++)a.indentLine(f,b.indentRight);return Z.moveToFirstNonWhiteSpaceCharacter(a,c[0].anchor)},indentAuto:function(a,b,c){a.execCommand("indentAuto");return Z.moveToFirstNonWhiteSpaceCharacter(a,c[0].anchor)},changeCase:function(a, b,c,d,f){for(var e=a.getSelections(),h=[],k=b.toLower,g=0;g<e.length;g++){var l=e[g],n="";if(!0===k)n=l.toLowerCase();else if(!1===k)n=l.toUpperCase();else for(var p=0;p<l.length;p++){var t=l.charAt(p);n+=ja.test(t)?t.toLowerCase():t.toUpperCase()}h.push(n)}a.replaceSelections(h);return b.shouldMoveCursor?f:!a.state.vim.visualMode&&b.linewise&&c[0].anchor.line+1==c[0].head.line?Z.moveToFirstNonWhiteSpaceCharacter(a,d):b.linewise?d:R(c[0].anchor,c[0].head)},yank:function(a,b,c,d){var f=a.state.vim; a=a.getSelection();c=f.visualMode?R(f.sel.anchor,f.sel.head,c[0].head,c[0].anchor):d;u.registerController.pushText(b.registerName,"yank",a,b.linewise,f.visualBlock);return c}},qa={jumpListWalk:function(a,b,c){c.visualMode||(c=b.repeat,b=(b=(b=u.jumpList.move(a,b.forward?c:-c))?b.find():void 0)?b:a.getCursor(),a.setCursor(b))},scroll:function(a,b,c){if(!c.visualMode){var d=b.repeat||1;c=a.defaultTextHeight();var f=a.getScrollInfo().top;d*=c;f=b.forward?f+d:f-d;d=G(a.getCursor());var e=a.charCoords(d, "local");b.forward?f>e.top?(d.line+=(f-e.top)/c,d.line=Math.ceil(d.line),a.setCursor(d),e=a.charCoords(d,"local"),a.scrollTo(null,e.top)):a.scrollTo(null,f):(b=f+a.getScrollInfo().clientHeight,b<e.bottom?(d.line-=(e.bottom-b)/c,d.line=Math.floor(d.line),a.setCursor(d),e=a.charCoords(d,"local"),a.scrollTo(null,e.bottom-a.getScrollInfo().clientHeight)):a.scrollTo(null,f))}},scrollToCursor:function(a,b){var c=a.getCursor().line,d=a.charCoords(new q(c,0),"local");c=a.getScrollInfo().clientHeight;var f= d.top;d=d.bottom-f;switch(b.position){case "center":f=f-c/2+d;break;case "bottom":f=f-c+d}a.scrollTo(null,f)},replayMacro:function(a,b,c){var d=b.selectedCharacter;b=b.repeat;var f=u.macroModeState;for("@"==d?d=f.latestRegister:f.latestRegister=d;b--;){var e=a,h=c,k=f,g=d,l=u.registerController.getRegister(g);if(":"==g)l.keyBuffer[0]&&W.processCommand(e,l.keyBuffer[0]);else{g=l.keyBuffer;var n=0;k.isPlaying=!0;k.replaySearchQueries=l.searchQueries.slice(0);for(var p=0;p<g.length;p++)for(var t=g[p], v,r;t;)v=/<\w+-.+?>|<\w+>|./.exec(t),r=v[0],t=t.substring(v.index+r.length),ia.handleKey(e,r,"macro"),h.insertMode&&(v=l.insertModeChanges[n++].changes,u.macroModeState.lastInsertModeChanges.changes=v,kb(e,v,1),ma(e))}k.isPlaying=!1}},enterMacroRecordMode:function(a,b){var c=u.macroModeState;b=b.selectedCharacter;u.registerController.isValidRegister(b)&&c.enterMacroRecordMode(a,b)},toggleOverwrite:function(a){a.state.overwrite?(a.toggleOverwrite(!1),a.setOption("keyMap","vim-insert"),m.signal(a,"vim-mode-change", {mode:"insert"})):(a.toggleOverwrite(!0),a.setOption("keyMap","vim-replace"),m.signal(a,"vim-mode-change",{mode:"replace"}))},enterInsertMode:function(a,b,c){if(!a.getOption("readOnly")){c.insertMode=!0;c.insertModeRepeat=b&&b.repeat||1;var d=b?b.insertAt:null,f=c.sel,e=b.head||a.getCursor("head"),h=a.listSelections().length;if("eol"==d)e=new q(e.line,I(a,e.line));else if("bol"==d)e=new q(e.line,0);else if("charAfter"==d)e=N(e,0,1);else if("firstNonBlank"==d)e=Z.moveToFirstNonWhiteSpaceCharacter(a, e);else if("startOfSelectedArea"==d){if(!c.visualMode)return;c.visualBlock?(e=new q(Math.min(f.head.line,f.anchor.line),Math.min(f.head.ch,f.anchor.ch)),h=Math.abs(f.head.line-f.anchor.line)+1):e=f.head.line<f.anchor.line?f.head:new q(f.anchor.line,0)}else if("endOfSelectedArea"==d){if(!c.visualMode)return;c.visualBlock?(e=new q(Math.min(f.head.line,f.anchor.line),Math.max(f.head.ch,f.anchor.ch)+1),h=Math.abs(f.head.line-f.anchor.line)+1):e=f.head.line>=f.anchor.line?N(f.head,0,1):new q(f.anchor.line, 0)}else if("inplace"==d){if(c.visualMode)return}else"lastEdit"==d&&(e=fb(a)||e);a.setOption("disableInput",!1);b&&b.replace?(a.toggleOverwrite(!0),a.setOption("keyMap","vim-replace"),m.signal(a,"vim-mode-change",{mode:"replace"})):(a.toggleOverwrite(!1),a.setOption("keyMap","vim-insert"),m.signal(a,"vim-mode-change",{mode:"insert"}));u.macroModeState.isPlaying||(a.on("change",gb),m.on(a.getInputField(),"keydown",hb));c.visualMode&&T(a);Va(a,e,h)}},toggleVisualMode:function(a,b,c){var d=b.repeat,f= a.getCursor();c.visualMode?c.visualLine^b.linewise||c.visualBlock^b.blockwise?(c.visualLine=!!b.linewise,c.visualBlock=!!b.blockwise,m.signal(a,"vim-mode-change",{mode:"visual",subMode:c.visualLine?"linewise":c.visualBlock?"blockwise":""}),ka(a)):T(a):(c.visualMode=!0,c.visualLine=!!b.linewise,c.visualBlock=!!b.blockwise,b=P(a,new q(f.line,f.ch+d-1)),c.sel={anchor:f,head:b},m.signal(a,"vim-mode-change",{mode:"visual",subMode:c.visualLine?"linewise":c.visualBlock?"blockwise":""}),ka(a),Y(a,c,"<",R(f, b)),Y(a,c,">",ea(f,b)))},reselectLastSelection:function(a,b,c){b=c.lastSelection;c.visualMode&&Wa(a,c);if(b){var d=b.anchorMark.find(),f=b.headMark.find();d&&f&&(c.sel={anchor:d,head:f},c.visualMode=!0,c.visualLine=b.visualLine,c.visualBlock=b.visualBlock,ka(a),Y(a,c,"<",R(d,f)),Y(a,c,">",ea(d,f)),m.signal(a,"vim-mode-change",{mode:"visual",subMode:c.visualLine?"linewise":c.visualBlock?"blockwise":""}))}},joinLines:function(a,b,c){if(c.visualMode){var d=a.getCursor("anchor");var f=a.getCursor("head"); if(H(f,d)){var e=f;f=d;d=e}f.ch=I(a,f.line)-1}else f=Math.max(b.repeat,2),d=a.getCursor(),f=P(a,new q(d.line+f-1,Infinity));for(var h=0,k=d.line;k<f.line;k++){h=I(a,d.line);e=new q(d.line+1,I(a,d.line+1));var g=a.getRange(d,e);g=b.keepSpaces?g.replace(/\n\r?/g,""):g.replace(/\n\s*/g," ");a.replaceRange(g,d,e)}b=new q(d.line,h);c.visualMode&&T(a,!1);a.setCursor(b)},newLineAndEnterInsertMode:function(a,b,c){c.insertMode=!0;var d=G(a.getCursor());d.line!==a.firstLine()||b.after?(d.line=b.after?d.line: d.line-1,d.ch=I(a,d.line),a.setCursor(d),(m.commands.newlineAndIndentContinueComment||m.commands.newlineAndIndent)(a)):(a.replaceRange("\n",new q(a.firstLine(),0)),a.setCursor(a.firstLine(),0));this.enterInsertMode(a,{repeat:b.repeat},c)},paste:function(a,b,c){var d=G(a.getCursor()),f=u.registerController.getRegister(b.registerName),e=f.toString();if(e){if(b.matchIndent){var h=a.getOption("tabSize"),k=function(r){var y=r.split("\t").length-1;r=r.split(" ").length-1;return y*h+1*r},g=a.getLine(a.getCursor().line), l=k(g.match(/^\s*/)[0]);g=e.replace(/\n$/,"");var n=e!==g,p=k(e.match(/^\s*/)[0]);e=g.replace(/^\s*/gm,function(r){r=l+(k(r)-p);return 0>r?"":a.getOption("indentWithTabs")?Array(Math.floor(r/h)+1).join("\t"):Array(r+1).join(" ")});e+=n?"\n":""}1<b.repeat&&(e=Array(b.repeat+1).join(e));g=f.linewise;if(f=f.blockwise){e=e.split("\n");g&&e.pop();for(n=0;n<e.length;n++)e[n]=""==e[n]?" ":e[n];d.ch+=b.after?1:0;d.ch=Math.min(I(a,d.line),d.ch)}else g?c.visualMode?e=c.visualLine?e.slice(0,-1):"\n"+e.slice(0, e.length-1)+"\n":b.after?(e="\n"+e.slice(0,e.length-1),d.ch=I(a,d.line)):d.ch=0:d.ch+=b.after?1:0;var t;if(c.visualMode){c.lastPastedText=e;b=yb(a,c);d=b[0];b=b[1];n=a.getSelection();var v=a.listSelections();v=Array(v.length).join("1").split("1");c.lastSelection&&(t=c.lastSelection.headMark.find());u.registerController.unnamedRegister.setText(n);f?(a.replaceSelections(v),b=new q(d.line+e.length-1,d.ch),a.setCursor(d),Ua(a,b),a.replaceSelections(e),e=d):c.visualBlock?(a.replaceSelections(v),a.setCursor(d), a.replaceRange(e,d,d),e=d):(a.replaceRange(e,d,b),e=a.posFromIndex(a.indexFromPos(d)+e.length-1));t&&(c.lastSelection.headMark=a.setBookmark(t));g&&(e.ch=0)}else if(f){a.setCursor(d);for(n=0;n<e.length;n++)t=d.line+n,t>a.lastLine()&&a.replaceRange("\n",new q(t,0)),I(a,t)<d.ch&&xb(a,t,d.ch);a.setCursor(d);Ua(a,new q(d.line+e.length-1,d.ch));a.replaceSelections(e);e=d}else a.replaceRange(e,d),g&&b.after?e=new q(d.line+1,U(a.getLine(d.line+1))):g&&!b.after?e=new q(d.line,U(a.getLine(d.line))):!g&&b.after? (t=a.indexFromPos(d),e=a.posFromIndex(t+e.length-1)):(t=a.indexFromPos(d),e=a.posFromIndex(t+e.length));c.visualMode&&T(a,!1);a.setCursor(e)}},undo:function(a,b){a.operation(function(){Sa(a,m.commands.undo,b.repeat)();a.setCursor(a.getCursor("anchor"))})},redo:function(a,b){Sa(a,m.commands.redo,b.repeat)()},setRegister:function(a,b,c){c.inputState.registerName=b.selectedCharacter},setMark:function(a,b,c){Y(a,c,b.selectedCharacter,a.getCursor())},replace:function(a,b,c){var d=b.selectedCharacter,f= a.getCursor(),e=a.listSelections();if(c.visualMode){f=a.getCursor("start");var h=a.getCursor("end")}else h=a.getLine(f.line),b=f.ch+b.repeat,b>h.length&&(b=h.length),h=new q(f.line,b);"\n"==d?(c.visualMode||a.replaceRange("",f,h),(m.commands.newlineAndIndentContinueComment||m.commands.newlineAndIndent)(a)):(b=a.getRange(f,h),b=b.replace(/[^\n]/g,d),c.visualBlock?(f=Array(a.getOption("tabSize")+1).join(" "),b=a.getSelection(),b=b.replace(/\t/g,f).replace(/[^\n]/g,d).split("\n"),a.replaceSelections(b)): a.replaceRange(b,f,h),c.visualMode?(f=H(e[0].anchor,e[0].head)?e[0].anchor:e[0].head,a.setCursor(f),T(a,!1)):a.setCursor(N(h,0,-1)))},incrementNumberToken:function(a,b){for(var c=a.getCursor(),d=a.getLine(c.line),f=/(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi,e,h,k;null!==(e=f.exec(d))&&!(h=e.index,k=h+e[0].length,c.ch<k););if((b.backtrack||!(k<=c.ch))&&e){d=e[2]||e[4];f=e[3]||e[5];var g=b.increase?1:-1,l={"0b":2,0:8,"":10,"0x":16}[d.toLowerCase()];b=(parseInt(e[1]+f,l)+g*b.repeat).toString(l);e=d?Array(f.length- b.length+1+e[1].length).join("0"):"";b="-"===b.charAt(0)?"-"+d+e+b.substr(1):d+e+b;e=new q(c.line,h);k=new q(c.line,k);a.replaceRange(b,e,k);a.setCursor(new q(c.line,h+b.length-1))}},repeatLastEdit:function(a,b,c){if(c.lastEditInputState){var d=b.repeat;d&&b.repeatIsExplicit?c.lastEditInputState.repeatOverride=d:d=c.lastEditInputState.repeatOverride||d;ib(a,c,d,!1)}},indent:function(a,b){a.indentLine(a.getCursor().line,b.indentRight)},exitInsertMode:ma},Gb={"(":"bracket",")":"bracket","{":"bracket", "}":"bracket","[":"section","]":"section","*":"comment","/":"comment",m:"method",M:"method","#":"preprocess"},rb={bracket:{isComplete:function(a){if(a.nextCh===a.symb){if(a.depth++,1<=a.depth)return!0}else a.nextCh===a.reverseSymb&&a.depth--;return!1}},section:{init:function(a){a.curMoveThrough=!0;a.symb=(a.forward?"]":"[")===a.symb?"{":"}"},isComplete:function(a){return 0===a.index&&a.nextCh===a.symb}},comment:{isComplete:function(a){var b="*"===a.lastCh&&"/"===a.nextCh;a.lastCh=a.nextCh;return b}}, method:{init:function(a){a.symb="m"===a.symb?"{":"}";a.reverseSymb="{"===a.symb?"}":"{"},isComplete:function(a){return a.nextCh===a.symb?!0:!1}},preprocess:{init:function(a){a.index=0},isComplete:function(a){if("#"===a.nextCh){var b=a.lineText.match(/^#(\w+)/)[1];if("endif"===b){if(a.forward&&0===a.depth)return!0;a.depth++}else if("if"===b){if(!a.forward&&0===a.depth)return!0;a.depth--}if("else"===b&&0===a.depth)return!0}return!1}}};ra("pcre",!0,"boolean");$a.prototype={getQuery:function(){return u.query}, setQuery:function(a){u.query=a},getOverlay:function(){return this.searchOverlay},setOverlay:function(a){this.searchOverlay=a},isReversed:function(){return u.isReversed},setReversed:function(a){u.isReversed=a},getScrollbarAnnotate:function(){return this.annotate},setScrollbarAnnotate:function(a){this.annotate=a}};var sb={"\\n":"\n","\\r":"\r","\\t":"\t"},tb={"\\/":"/","\\\\":"\\","\\n":"\n","\\r":"\r","\\t":"\t","\\&":"&"},oa=0,ub=function(){this.buildCommandMap_()};ub.prototype={processCommand:function(a, b,c){var d=this;a.operation(function(){a.curOp.isVimOp=!0;d._processCommand(a,b,c)})},_processCommand:function(a,b,c){var d=a.state.vim,f=u.registerController.getRegister(":"),e=f.toString();d.visualMode&&T(a);d=new m.StringStream(b);f.setText(b);c=c||{};c.input=b;try{this.parseInput_(a,d,c)}catch(g){throw F(a,g.toString()),g;}var h;if(c.commandName){if(h=this.matchCommand_(c.commandName)){var k=h.name;h.excludeFromCommandHistory&&f.setText(e);this.parseCommandArgs_(d,c,h);if("exToKey"==h.type){for(b= 0;b<h.toKeys.length;b++)ia.handleKey(a,h.toKeys[b],"mapping");return}if("exToEx"==h.type){this.processCommand(a,h.toInput);return}}}else void 0!==c.line&&(k="move");if(k)try{pb[k](a,c),h&&h.possiblyAsync||!c.callback||c.callback()}catch(g){throw F(a,g.toString()),g;}else F(a,'Not an editor command ":'+b+'"')},parseInput_:function(a,b,c){b.eatWhile(":");b.eat("%")?(c.line=a.firstLine(),c.lineEnd=a.lastLine()):(c.line=this.parseLineSpec_(a,b),void 0!==c.line&&b.eat(",")&&(c.lineEnd=this.parseLineSpec_(a, b)));a=b.match(/^(\w+|!!|@@|[!#&*<=>@~])/);c.commandName=a?a[1]:b.match(/.*/)[0];return c},parseLineSpec_:function(a,b){var c=b.match(/^(\d+)/);if(c)return parseInt(c[1],10)-1;switch(b.next()){case ".":return this.parseLineSpecOffset_(b,a.getCursor().line);case "$":return this.parseLineSpecOffset_(b,a.lastLine());case "'":c=b.next();a=eb(a,a.state.vim,c);if(!a)throw Error("Mark not set");return this.parseLineSpecOffset_(b,a.line);case "-":case "+":return b.backUp(1),this.parseLineSpecOffset_(b,a.getCursor().line); default:b.backUp(1)}},parseLineSpecOffset_:function(a,b){if(a=a.match(/^([+-])?(\d+)/)){var c=parseInt(a[2],10);b="-"==a[1]?b-c:b+c}return b},parseCommandArgs_:function(a,b,c){a.eol()||(b.argString=a.match(/.*/)[0],a=c.argDelimiter||/\s+/,a=Ca(b.argString).split(a),a.length&&a[0]&&(b.args=a))},matchCommand_:function(a){for(var b=a.length;0<b;b--){var c=a.substring(0,b);if(this.commandMap_[c]&&(c=this.commandMap_[c],0===c.name.indexOf(a)))return c}return null},buildCommandMap_:function(){this.commandMap_= {};for(var a=0;a<J.length;a++){var b=J[a];this.commandMap_[b.shortName||b.name]=b}},map:function(a,b,c){if(":"!=a&&":"==a.charAt(0)){if(c)throw Error("Mode not supported for ex mappings");c=a.substring(1);":"!=b&&":"==b.charAt(0)?this.commandMap_[c]={name:c,type:"exToEx",toInput:b.substring(1),user:!0}:this.commandMap_[c]={name:c,type:"exToKey",toKeys:b,user:!0}}else b=":"!=b&&":"==b.charAt(0)?{keys:a,type:"keyToEx",exArgs:{input:b.substring(1)}}:{keys:a,type:"keyToKey",toKeys:b},c&&(b.context=c), x.unshift(b)},unmap:function(a,b){if(":"!=a&&":"==a.charAt(0)){if(b)throw Error("Mode not supported for ex mappings");a=a.substring(1);if(this.commandMap_[a]&&this.commandMap_[a].user)return delete this.commandMap_[a],!0}else for(var c=0;c<x.length;c++)if(a==x[c].keys&&x[c].context===b)return x.splice(c,1),!0}};var pb={colorscheme:function(a,b){!b.args||1>b.args.length?F(a,a.getOption("theme")):a.setOption("theme",b.args[0])},map:function(a,b,c){var d=b.args;!d||2>d.length?a&&F(a,"Invalid mapping: "+ b.input):W.map(d[0],d[1],c)},imap:function(a,b){this.map(a,b,"insert")},nmap:function(a,b){this.map(a,b,"normal")},vmap:function(a,b){this.map(a,b,"visual")},unmap:function(a,b,c){var d=b.args;(!d||1>d.length||!W.unmap(d[0],c))&&a&&F(a,"No such mapping: "+b.input)},move:function(a,b){ba.processCommand(a,a.state.vim,{type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0},repeatOverride:b.line+1})},set:function(a,b){var c=b.args,d=b.setCfg||{};if(!c|| 1>c.length)a&&F(a,"Invalid mapping: "+b.input);else{var f=c[0].split("=");c=f[0];f=f[1];var e=!1;if("?"==c.charAt(c.length-1)){if(f)throw Error("Trailing characters: "+b.argString);c=c.substring(0,c.length-1);e=!0}void 0===f&&"no"==c.substring(0,2)&&(c=c.substring(2),f=!1);(b=X[c]&&"boolean"==X[c].type)&&void 0==f&&(f=!0);!b&&void 0===f||e?(d=da(c,a,d),d instanceof Error?F(a,d.message):!0===d||!1===d?F(a," "+(d?"":"no")+c):F(a," "+c+"="+d)):(d=Aa(c,f,a,d),d instanceof Error&&F(a,d.message))}},setlocal:function(a, b){b.setCfg={scope:"local"};this.set(a,b)},setglobal:function(a,b){b.setCfg={scope:"global"};this.set(a,b)},registers:function(a,b){var c=b.args;b=u.registerController.registers;var d="----------Registers----------\n\n";if(c){c=c.join("");for(var f=0;f<c.length;f++)if(h=c.charAt(f),u.registerController.isValidRegister(h)){var e=b[h]||new S;d+='"'+h+" "+e.toString()+"\n"}}else for(var h in b)c=b[h].toString(),c.length&&(d+='"'+h+" "+c+"\n");F(a,d)},sort:function(a,b){function c(z,D){if(f){var L= z;z=D;D=L}e&&(z=z.toLowerCase(),D=D.toLowerCase());L=k&&t.exec(z);var ha=k&&t.exec(D);if(!L)return z<D?-1:1;L=parseInt((L[1]+L[2]).toLowerCase(),v);ha=parseInt((ha[1]+ha[2]).toLowerCase(),v);return L-ha}function d(z,D){if(f){var L=z;z=D;D=L}e&&(z[0]=z[0].toLowerCase(),D[0]=D[0].toLowerCase());return z[0]<D[0]?-1:1}var f,e,h,k,g,l=function(){if(b.argString){var z=new m.StringStream(b.argString);z.eat("!")&&(f=!0);if(!z.eol()){if(!z.eatSpace())return"Invalid arguments";var D=z.match(/([dinuox]+)?\s*(\/.+\/)?\s*/); if(!D&&!z.eol())return"Invalid arguments";if(D[1]){e=-1!=D[1].indexOf("i");h=-1!=D[1].indexOf("u");z=-1!=D[1].indexOf("d")||-1!=D[1].indexOf("n")&&1;var L=-1!=D[1].indexOf("x")&&1,ha=-1!=D[1].indexOf("o")&&1;if(1<z+L+ha)return"Invalid arguments";k=z&&"decimal"||L&&"hex"||ha&&"octal"}D[2]&&(g=new RegExp(D[2].substr(1,D[2].length-2),e?"i":""))}}}();if(l)F(a,l+": "+b.argString);else{l=b.line||a.firstLine();var n=b.lineEnd||b.line||a.lastLine();if(l!=n){l=new q(l,0);n=new q(n,I(a,n));var p=a.getRange(l, n).split("\n"),t=g?g:"decimal"==k?/(-?)([\d]+)/:"hex"==k?/(-?)(?:0x)?([0-9a-f]+)/i:"octal"==k?/([0-7]+)/:null,v="decimal"==k?10:"hex"==k?16:"octal"==k?8:null,r=[],y=[];if(k||g)for(var A=0;A<p.length;A++){var C=g?p[A].match(g):null;C&&""!=C[0]?r.push(C):!g&&t.exec(p[A])?r.push(p[A]):y.push(p[A])}else y=p;r.sort(g?d:c);if(g)for(A=0;A<r.length;A++)r[A]=r[A].input;else k||y.sort(c);p=f?r.concat(y):y.concat(r);if(h)for(r=p,p=[],A=0;A<r.length;A++){r[A]!=E&&p.push(r[A]);var E=r[A]}a.replaceRange(p.join("\n"), l,n)}}},vglobal:function(a,b){this.global(a,b)},global:function(a,b){var c=b.argString;if(c){var d="v"===b.commandName[0],f=void 0!==b.line?b.line:a.firstLine();b=b.lineEnd||b.line||a.lastLine();var e=ab(c,"/");if(e.length){c=e[0];var h=e.slice(1,e.length).join("/")}if(c)try{la(a,c,!0,!0)}catch(n){F(a,"Invalid regex: "+c);return}c=V(a).getQuery();for(var k=[];f<=b;f++)e=a.getLineHandle(f),c.test(e.text)!==d&&k.push(h?e:e.text);if(h){var g=0,l=function(){if(g<k.length){var n=k[g++];n=a.getLineNumber(n); null==n?l():W.processCommand(a,n+1+h,{callback:l})}};l()}else F(a,k.join("\n"))}else F(a,"Regular Expression missing from global")},substitute:function(a,b){if(!a.getSearchCursor)throw Error("Search feature not available. Requires searchcursor.js or any other getSearchCursor implementation.");var c=b.argString,d=c?ab(c,c[0]):[],f="",e,h=!1,k=!1;if(d.length){var g=d[0];da("pcre")&&""!==g&&(g=(new RegExp(g)).source);f=d[1];if(void 0!==f){if(da("pcre")){f=f.replace(/([^\\])&/g,"$1$$&");f=new m.StringStream(f); for(e=[];!f.eol();){for(;f.peek()&&"\\"!=f.peek();)e.push(f.next());c=!1;for(var l in tb)if(f.match(l,!0)){c=!0;e.push(tb[l]);break}c||e.push(f.next())}f=e.join("")}else{l=!1;e=[];for(c=-1;c<f.length;c++){var n=f.charAt(c)||"",p=f.charAt(c+1)||"";sb[n+p]?(e.push(sb[n+p]),c++):l?(e.push(n),l=!1):"\\"===n?(l=!0,Fb.test(p)||"$"===p?e.push("$"):"/"!==p&&"\\"!==p&&e.push("\\")):("$"===n&&e.push("$"),e.push(n),"/"===p&&e.push("\\"))}f=e.join("")}u.lastSubstituteReplacePart=f}e=d[2]?d[2].split(" "):[]}else if(c&& c.length){F(a,"Substitutions should be of the form :s/pattern/replace/");return}if(e){d=e[0];var t=parseInt(e[1]);d&&(-1!=d.indexOf("c")&&(h=!0),-1!=d.indexOf("g")&&(k=!0),g=da("pcre")?g+"/"+d:g.replace(/\//g,"\\/")+"/"+d)}if(g)try{la(a,g,!0,!0)}catch(v){F(a,"Invalid regex: "+g);return}f=f||u.lastSubstituteReplacePart;void 0===f?F(a,"No previous substitute regular expression"):(g=V(a).getQuery(),d=void 0!==b.line?b.line:a.getCursor().line,l=b.lineEnd||d,d==a.firstLine()&&l==a.lastLine()&&(l=Infinity), t&&(d=l,l=d+t-1),t=P(a,new q(d,0)),t=a.getSearchCursor(g,t),Eb(a,h,k,d,l,t,g,f,b.callback))},redo:m.commands.redo,undo:m.commands.undo,write:function(a){m.commands.save?m.commands.save(a):a.save&&a.save()},nohlsearch:function(a){Ga(a)},yank:function(a){var b=G(a.getCursor()).line;a=a.getLine(b);u.registerController.pushText("0","yank",a,!0,!0)},delmarks:function(a,b){if(b.argString&&Ca(b.argString))for(var c=a.state.vim,d=new m.StringStream(Ca(b.argString));!d.eol();){d.eatSpace();var f=d.pos;if(!d.match(/[a-zA-Z]/, !1)){F(a,"Invalid argument: "+b.argString.substring(f));break}var e=d.next();if(d.match("-",!0)){if(!d.match(/[a-zA-Z]/,!1)){F(a,"Invalid argument: "+b.argString.substring(f));break}var h=d.next();if(/^[a-z]$/.test(e)&&/^[a-z]$/.test(h)||ja.test(e)&&ja.test(h)){e=e.charCodeAt(0);h=h.charCodeAt(0);if(e>=h){F(a,"Invalid argument: "+b.argString.substring(f));break}for(f=0;f<=h-e;f++){var k=String.fromCharCode(e+f);delete c.marks[k]}}else{F(a,"Invalid argument: "+e+"-");break}}else delete c.marks[e]}else F(a, "Argument required")}},W=new ub;m.keyMap.vim={attach:K,detach:M,call:aa};ra("insertModeEscKeysTimeout",200,"number");m.keyMap["vim-insert"]={fallthrough:["default"],attach:K,detach:M,call:aa};m.keyMap["vim-replace"]={Backspace:"goCharLeft",fallthrough:["vim-insert"],attach:K,detach:M,call:aa};Pa();return ia}()});
import test from 'ava' import Promise from 'bluebird' import { assert } from '../../../../helpers/chai' import { normalizeHandler } from '../../../../helpers/normalizer' import { mock } from '../../../../helpers/boleto' import * as boletoHandler from '../../../../../build/resources/boleto' const create = normalizeHandler(boletoHandler.create) test('creates a boleto (provider success)', async (t) => { const payload = mock payload.amount = 5000000 payload.issuer = 'development' const { body, statusCode } = await create({ body: payload }) t.is(statusCode, 201) t.is(body.object, 'boleto') t.true(body.title_id != null) t.true(body.barcode != null) t.true(typeof body.title_id === 'number') assert.containSubset(body, { status: 'registered', paid_amount: 0, amount: payload.amount, instructions: payload.instructions, issuer: payload.issuer, issuer_id: null, payer_name: payload.payer_name, payer_document_type: payload.payer_document_type, payer_document_number: payload.payer_document_number, company_name: payload.company_name, company_document_number: payload.company_document_number, queue_url: payload.queue_url }) })
(function(window, $, undefined) { $(function() { // 初始化赠品数据 fnInitGiftList(); // 初始化配件数据 fnInitListParts(); }); // init gift list data function fnInitGiftList() { var $wrapper = $('#giftWrapper'), $btnPrev = $wrapper.find('.btn-prev'), $btnNext = $wrapper.find('.btn-next'), $giftList = $wrapper.find('.gift-list'), liW = 240, liML = 10, viewNum = 3, iLeft = 0, maxW = 0, len = 0; // handle for init list (function() { // 数字蜡烛模拟数据 var _data = { list: [{ link: 'javascript:;', img: '/assets/imgs/exchange/group_01.jpg', desc: '纯芝士与醇香奶油的梦幻组合', name: { cn: '芒果拿破仑', en: 'Mango Napoleon' }, spec: '4只装', price: 189 }, { link: 'javascript:;', img: '/assets/imgs/exchange/group_02.jpg', desc: '纯芝士与醇香奶油的梦幻组合', name: { cn: '芒果拿破仑', en: 'Mango Napoleon' }, spec: '1.5磅', price: 189 }, { link: 'javascript:;', img: '/assets/imgs/exchange/group_03.jpg', desc: '纯芝士与醇香奶油的梦幻组合', name: { cn: '芒果拿破仑', en: 'Mango Napoleon' }, spec: '1.5磅', price: 189 }, { link: 'javascript:;', img: '/assets/imgs/exchange/group_01.jpg', desc: '纯芝士与醇香奶油的梦幻组合', name: { cn: '芒果拿破仑', en: 'Mango Napoleon' }, spec: '1.5磅', price: 189 }, { link: 'javascript:;', img: '/assets/imgs/exchange/group_02.jpg', desc: '纯芝士与醇香奶油的梦幻组合', name: { cn: '芒果拿破仑', en: 'Mango Napoleon' }, spec: '4只装', price: 189 }, { link: 'javascript:;', img: '/assets/imgs/exchange/group_03.jpg', desc: '纯芝士与醇香奶油的梦幻组合', name: { cn: '芒果拿破仑', en: 'Mango Napoleon' }, spec: '1.5磅', price: 189 }, { link: 'javascript:;', img: '/assets/imgs/exchange/group_01.jpg', desc: '纯芝士与醇香奶油的梦幻组合', name: { cn: '芒果拿破仑', en: 'Mango Napoleon' }, spec: '1.5磅', price: 189 }, { link: 'javascript:;', img: '/assets/imgs/exchange/group_02.jpg', desc: '纯芝士与醇香奶油的梦幻组合', name: { cn: '芒果拿破仑', en: 'Mango Napoleon' }, spec: '1.5磅', price: 189 }] }; // set list position left to 0 $giftList.css({ left: 0 }); len = _data.list.length; maxW = (len - viewNum) * (liW + liML); $giftList.width((liW + liML) * len); // reset previous button style if ($btnPrev.hasClass('active')) { $btnPrev.removeClass('active'); } // reset next button style if (len > viewNum) { $btnNext.addClass('active'); } else { if ($btnNext.hasClass('active')) { $btnNext.removeClass('active'); } } var _html = template('tplGiftList', _data); $giftList.html(_html); })(); // handle for next slide $btnNext.on('click', function(e) { if (!$(this).hasClass('active')) { return false; } iLeft += (liW + liML); if (iLeft >= maxW) { iLeft = maxW; $(this).removeClass('active'); } $giftList.animate({ left: -iLeft + 'px' }); if (len > viewNum && !$btnPrev.hasClass('active')) { $btnPrev.addClass('active'); } }); // handle for previous slide $btnPrev.on('click', function(e) { if (!$(this).hasClass('active')) { return false; } iLeft -= (liW + liML); if (iLeft <= 0) { iLeft = 0; $(this).removeClass('active'); } $giftList.animate({ left: -iLeft + 'px' }); if (len > viewNum && !$btnNext.hasClass('active')) { $btnNext.addClass('active'); } }); // 选中切换 $giftList.on('click', '.selector', function(e) { var $element = $(this).closest('li'); $element.toggleClass('selected'); if($element.hasClass('selected')){ $(this).addClass('active').text('取消'); }else { $(this).text('确定').removeClass('active'); } e.preventDefault(); }); // 数量加减 $giftList.on('click', '.num-add', function(e) { var minusDom = $(this).siblings('.num-minus'), inputDom = $(this).siblings('.txt-num'), inputVal = parseInt(inputDom.val().trim(), 10); inputVal++; inputDom.val(inputVal); if (inputVal >= 2) { minusDom.addClass('active'); } }).on('click', '.num-minus', function(e) { var inputDom = $(this).siblings('.txt-num'), inputVal = parseInt(inputDom.val().trim(), 10); inputVal--; if (inputVal <= 1) { inputVal = 1; $(this).removeClass('active'); } inputDom.val(inputVal); }); } // init list parts data function fnInitListParts() { var $wrapper = $('#partsWrapper'), $mask = $('#numberCandle'); // 选中配件 $wrapper.on('click', '.part-item', function(e) { if($(this).hasClass('active')) { $(this).removeClass('active'); } else { $(this).addClass('active'); } }); // 配件数量加减 $wrapper.on('click', '.num-add', function(e) { var $input = $(this).prev('.txt-num'), amount = parseInt($input.val()); amount++; if (amount > 1) { $(this).siblings('.num-minus').addClass('active'); } $input.val(amount); e.preventDefault(); e.stopPropagation(); }).on('click', '.num-minus', function(e) { var $input = $(this).next('.txt-num'), amount = parseInt($input.val()); amount--; if (amount <= 1) { amount = 1; $(this).removeClass('active'); } $input.val(amount); e.preventDefault(); e.stopPropagation(); }).on('click', '.operate', function(e) { e.preventDefault(); e.stopPropagation(); }); // 数字蜡烛加入购物车 $wrapper.on('click', '.btn-candle', function(e) { $mask.fadeIn(); e.preventDefault(); e.stopPropagation(); }); // 关闭数字蜡烛弹窗 $mask.on('click', '.numbercandle-close', function(e) { $mask.fadeOut(); }); // 数字蜡烛选择 $mask.on('click', '.container-body li', function(e) { $(this).toggleClass('active'); }); // 增加数量 $mask.on('click', '.num-add', function(e) { var $input = $(this).prev('.txt-num'), amount = parseInt($input.val()); amount++; if (amount > 1) { $(this).siblings('.num-minus').addClass('active'); } $input.val(amount); e.preventDefault(); e.stopPropagation(); }); // 减少数量 $mask.on('click', '.num-minus', function(e) { var $input = $(this).next('.txt-num'), amount = parseInt($input.val()); amount--; if (amount <= 1) { amount = 1; $(this).removeClass('active'); } $input.val(amount); e.preventDefault(); e.stopPropagation(); }); } })(window, jQuery);
export class Circle { constructor() { let i; let circles = document.getElementsByTagName('circle'); for (i = 0; i < circles.length; i++) { this.findCircleElement(circles[i]); } let circleClasses = document.getElementsByClassName('circle'); for (i = 0; i < circleClasses.length; i++) { this.findCircleElement(circleClasses[i]); } } findCircleElement(circle) { if (circle.hasAttribute('shape-radius')) { getRadius(); } if (circle.hasAttribute('shape-background')) { getBackground(); } if (circle.hasAttribute('shape-border')) { getBorder(); } if(circle.hasAttribute('transition')){ getTransition(); } function getTransition() { let transition =circle.getAttribute('transition'); if(transition=='off') circle.style.transition = 'none'; } function getBorder() { let border = circle.getAttribute('shape-border'); if (border.indexOf(',')) { let match = border.split(/\s*,\s*/); circle.style.border= match[0] + 'px solid ' + match[1]; } else { circle.style.border = border; } } function getBackground() { let background = circle.getAttribute('shape-background'); circle.style.backgroundColor = background; } // radius method start function getRadius() { let radius = circle.getAttribute('shape-radius'); let value = radius.replace(/[^0-9]/g, ''); let unit = radius.replace(/[0-9]/g, ''); if (unit == '%') { unit = 'em'; } radius = Number(value) + unit; circle.style.width = radius; circle.style.height = radius; circle.style.borderRadius = Number(value) / 2 + unit; circle.style.MozBorderRadius = Number(value) / 2 + unit; circle.style.WebkitBorderRadius = Number(value) / 2 + unit; circle.style.lineHeight=radius; } } }
(function() { 'use strict'; angular .module('lumx.checkbox', []) .directive('lxCheckbox', lxCheckbox) .directive('lxCheckboxLabel', lxCheckboxLabel) .directive('lxCheckboxHelp', lxCheckboxHelp); function lxCheckbox() { return { restrict: 'E', templateUrl: 'checkbox.html', scope: { ngModel: '=', name: '@?', ngTrueValue: '@?', ngFalseValue: '@?', ngChange: '&?', ngDisabled: '=?', lxColor: '@?' }, controller: LxCheckboxController, controllerAs: 'lxCheckbox', bindToController: true, transclude: true, replace: true }; } LxCheckboxController.$inject = ['$timeout', 'LxUtils']; function LxCheckboxController($timeout, LxUtils) { var lxCheckbox = this; var checkboxId; var checkboxHasChildren; lxCheckbox.getCheckboxId = getCheckboxId; lxCheckbox.getCheckboxHasChildren = getCheckboxHasChildren; lxCheckbox.setCheckboxId = setCheckboxId; lxCheckbox.setCheckboxHasChildren = setCheckboxHasChildren; lxCheckbox.triggerNgChange = triggerNgChange; init(); //////////// function getCheckboxId() { return checkboxId; } function getCheckboxHasChildren() { return checkboxHasChildren; } function init() { setCheckboxId(LxUtils.generateUUID()); setCheckboxHasChildren(false); lxCheckbox.ngTrueValue = angular.isUndefined(lxCheckbox.ngTrueValue) ? true : lxCheckbox.ngTrueValue; lxCheckbox.ngFalseValue = angular.isUndefined(lxCheckbox.ngFalseValue) ? false : lxCheckbox.ngFalseValue; lxCheckbox.lxColor = angular.isUndefined(lxCheckbox.lxColor) ? 'accent' : lxCheckbox.lxColor; } function setCheckboxId(_checkboxId) { checkboxId = _checkboxId; } function setCheckboxHasChildren(_checkboxHasChildren) { checkboxHasChildren = _checkboxHasChildren; } function triggerNgChange() { $timeout(lxCheckbox.ngChange); } } function lxCheckboxLabel() { return { restrict: 'AE', require: ['^lxCheckbox', '^lxCheckboxLabel'], templateUrl: 'checkbox-label.html', link: link, controller: LxCheckboxLabelController, controllerAs: 'lxCheckboxLabel', bindToController: true, transclude: true, replace: true }; function link(scope, element, attrs, ctrls) { ctrls[0].setCheckboxHasChildren(true); ctrls[1].setCheckboxId(ctrls[0].getCheckboxId()); } } function LxCheckboxLabelController() { var lxCheckboxLabel = this; var checkboxId; lxCheckboxLabel.getCheckboxId = getCheckboxId; lxCheckboxLabel.setCheckboxId = setCheckboxId; //////////// function getCheckboxId() { return checkboxId; } function setCheckboxId(_checkboxId) { checkboxId = _checkboxId; } } function lxCheckboxHelp() { return { restrict: 'AE', require: '^lxCheckbox', templateUrl: 'checkbox-help.html', transclude: true, replace: true }; } })();
import React from 'react'; import AddTodo from './AddTodo'; import TodoList from './TodoList'; import Footer from './Footer'; const styles = { todoContainer: { display: 'flex', flexDirection: 'column', margin: 12 } }; const TodoApp = () => ( <div style={styles.todoContainer}> <AddTodo /> <TodoList /> <Footer /> </div> ); export default TodoApp;
/*jshint curly:false, expr: true */ var should = require('should'), mongoose = require('mongoose'), kabamKernel = require('./../index.js'), kabam, User; describe('User model OAuth methods', function(){ before(function(done){ var config = {MONGO_URL: 'mongodb://localhost/kabam_test'}; var connection = mongoose.createConnection(config.MONGO_URL); // We should first connect manually to the database and delete it because if we would use kabam.mongoConnection // then models would not recreate their indexes because mongoose would initialise before we would drop database. kabam = kabamKernel(config); connection.on('open', function(){ connection.db.dropDatabase(function(){ kabam.on('started', function(){ User = kabam.model.User; done(); }); kabam.start('app'); }); }); }); describe('#signUpWithService', function(){ afterEach(function(done){ User.remove(function(err){ done(err); }); }); it('should create a new user with the given email and save service profile to the keychain', function(done){ User.signUpWithService('john@doe.com', {id: 1, provider: 'github'}, function(err, user){ if (err) return done(err); should.ok(typeof user === 'object'); user.should.have.property('email', 'john@doe.com'); user.should.have.property('keychain'); user.keychain.should.have.property('github', 1); done(); }); }); it('should return error if user exist', function(done){ User.signUpWithService('john@doe.com', {id: 1, provider: 'github'}, function(err){ if (err) return done(err); User.signUpWithService('john@doe.com', {id: 1, provider: 'github'}, function(err/*, user*/){ should.exist(err); kabam.model.User.find(function(err, users){ should(users.length === 1); done(); }); }); }); }); it('should create a new user without email just by saving proper keychain', function(done){ User.signUpWithService(null, {id: 1, provider: 'github'}, function(err, user){ if (err) return done(err); should.ok(typeof user === 'object'); user.should.not.have.property('email'); user.should.have.property('emailVerified', false); user.should.have.property('keychain'); user.keychain.should.have.property('github', 1); done(); }); }); it('should save last and first name if profile has them property', function(done){ var profile = {id: 1, provider: 'github', firstName: 'John', lastName: 'Malkovich'}; User.signUpWithService(null, profile, function(err, user){ if (err) return done(err); should.ok(typeof user === 'object'); user.should.have.property('firstName', 'John'); user.should.have.property('lastName', 'Malkovich'); done(); }); }); }); describe('#linkWithService', function(){ afterEach(function(done){ User.remove(function(err){ done(err); }); }); describe('if user is not provided', function(){ describe('if can create', function(){ it('should create a new user if account wasn\'t linked before', function(done){ var profile = {id: 1, provider: 'github', emails: [ {value: 'john@doe.com'} ]}; User.linkWithService(null, profile, true, function(err, user, created){ if (err) return done(err); /* jshint expr: true *///noinspection BadExpressionStatementJS created.should.be.true; user.should.have.property('email', 'john@doe.com'); user.should.have.property('emailVerified', true); user.should.have.property('keychain'); user.keychain.should.have.property('github', 1); done(); }); }); it('should create a new user with empty email if account wasn\'t linked before and has no email', function(done){ var profile = {id: 1, provider: 'github'}; User.linkWithService(null, profile, true, function(err, user, created){ if (err) return done(err); /* jshint expr: true *///noinspection BadExpressionStatementJS created.should.be.true; user.should.not.have.property('email'); user.should.have.property('emailVerified', false); user.should.have.property('keychain'); user.keychain.should.have.property('github', 1); done(); }); }); it('should not create a new or update the existing user if there is someone with same email', function(done){ User.signUpWithService('john@doe.com', {id: 1, provider: 'github'}, function(err/*, user*/){ if (err) return done(err); var profile = {id: 1, provider: 'google', emails: [ {value: 'john@doe.com'} ]}; User.linkWithService(null, profile, true, function(err, user, info){ if (err) done(err); //noinspection BadExpressionStatementJS user.should.be.false; info.should.have.property('message'); should(info.message.indexOf('john@doe.com') !== -1); done(); }); }); }); }); it('should login already linked user if profile has an email', function(done){ User.signUpWithService('john@doe.com', {id: 1, provider: 'github'}, function(err/*, user*/){ if (err) return done(err); var profile = {id: 1, provider: 'github', emails: [ {value: 'john@doe.com'} ]}; User.linkWithService(null, profile, false, function(err, user, created){ if (err) done(err); /* jshint expr: true *///noinspection BadExpressionStatementJS created.should.be.false; user.should.have.property('email'); user.should.have.property('emailVerified', true); user.should.have.property('keychain'); user.keychain.should.have.property('github', 1); done(); }); }); }); it('should login already linked user if profile don\'t has an email', function(done){ User.signUpWithService('john@doe.com', {id: 1, provider: 'github'}, function(err/*, user*/){ if (err) return done(err); var profile = {id: 1, provider: 'github'}; User.linkWithService(null, profile, false, function(err, user, created){ if (err) done(err); //noinspection BadExpressionStatementJS created.should.be.false; user.should.have.property('email'); user.should.have.property('emailVerified', true); user.should.have.property('keychain'); user.keychain.should.have.property('github', 1); done(); }); }); }); it('should not create a new user if canCreate is false', function(done){ var profile = {id: 1, provider: 'github', emails: [ {value: 'john@doe.com'} ]}; User.linkWithService(null, profile, false, function(err, user, info){ if (err) return done(err); //noinspection BadExpressionStatementJS user.should.be.false; info.should.have.property('message'); should(info.message.indexOf('Cannot login using Github') !== -1); done(); }); }); }); describe('if user provided', function(){ it('should login login user if they have same keychain', function(done){ User.signUpWithService('john@doe.com', {id: 1, provider: 'github'}, function(err, user){ if (err) return done(err); var profile = {id: 1, provider: 'github', emails: [ {value: 'john@doe.com'} ]}; User.linkWithService(user, profile, false, function(err, user, created){ if (err) return done(err); should.exist(user); created.should.have.type('boolean'); //noinspection BadExpressionStatementJS created.should.not.be.true; done(); }); }); }); it('should link accounts if user doesn\'t have the same keychain', function(done){ User.signUpWithService('john@doe.com', {id: 123, provider: 'github'}, function(err, user){ if (err) return done(err); var profile = {id: 1, provider: 'facebook', emails: [ {value: 'mark@facebook.com'} ]}; User.linkWithService(user, profile, false, function(err, user, created){ if (err) return done(err); should.exist(user); /* jshint expr: true *///noinspection BadExpressionStatementJS created.should.not.be.true; user.should.have.property('keychain'); user.keychain.should.have.property('github', 123); user.keychain.should.have.property('facebook', 1); done(); }); }); }); it('should not change user\'s email', function(done){ User.signUpWithService('john@doe.com', {id: 123, provider: 'github'}, function(err, user){ if (err) return done(err); var profile = {id: 1, provider: 'facebook', emails: [ {value: 'mark@facebook.com'} ]}; User.linkWithService(user, profile, false, function(err, user, created){ if (err) return done(err); should.exist(user); //noinspection BadExpressionStatementJS created.should.not.be.true; user.should.have.property('email', 'john@doe.com'); done(); }); }); }); it('should throw error if there is a user with the same keychain', function(done){ User.signUpWithService('john@doe.com', {id: 123, provider: 'github'}, function(err/*, user*/){ if (err) return done(err); User.signUpWithService('john@malkovich.com', {id: 321, provider: 'facebook'}, function(err, user){ if (err) return done(err); // trying to lik to the second user the same keychain as for the first user User.linkWithService(user, {id: 123, provider: 'github'}, false, function(err, user, info){ if (err) return done(err); should.exist(user); info.should.have.type('object'); info.should.have.property('message'); should(info.message.indexOf('Someone already linked this Github account') !== -1); done(); }); }); }); }); }); }); });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * ProductBrand Schema */ var ProductBrandSchema = new Schema({ created: { type: Date, default: Date.now }, name: { type: String, default: '', trim: true }, number: { type: String, unique: true }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('ProductBrand', ProductBrandSchema);
// // Created by CaoTao, 2018/03/08 // /* * LeetCode link: * https://leetcode.com/problems/maximum-subarray/description/ */ /** * @param {number[]} nums * @return {number} */ var maxSubArray = function(nums) { var length = nums.length if (length < 2) { return nums[0] } var maxSum = nums[0], currentMaxSum = nums[0] for (var i = 1; i < length; i++) { currentMaxSum = currentMaxSum > 0 ? currentMaxSum + nums[i] : nums[i] if (currentMaxSum > maxSum) { maxSum = currentMaxSum } } return maxSum };
/* * angular-ui-bootstrap * http://angular-ui.github.io/bootstrap/ * Version: 1.0.0-SNAPSHOT - 2015-12-29 * License: MIT */ angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}","ui.bootstrap.${name}"]); angular.module("ui.bootstrap.tpls", []);
"use strict"; if (!('contains' in String.prototype)) { String.prototype.contains = function (str, startIndex) { return -1 !== String.prototype.indexOf.call(this, str, startIndex); }; } //set up global vars var datavar = {'limit': '50'};//party bitches var loading = false;//shits not loading var after;//yup var imagearray = []; //loops through the url generated by checkurl() and outputs image html. //should change this to "dynammically" generate the page, and reduce the number of sudden image requests //even better change it to lazy load the images function imgload(url) { $.ajax({ url: url, jsonp: "jsonp", data: datavar, dataType: "jsonp" }).done(function (json) { $('.alert').remove(); loading = false; console.log(json); after = json.data.after; var finalhtml, r = 0, image, subreddit, title, id; for (r < json.data.children.length;) { //loops through the reddit results image = json.data.children[r].data.url; //sets up a nice reference to the image url subreddit = json.data.children[r].data.subreddit; //sets up a nice refernce to the subreddit url title = json.data.children[r].data.title; //sets up a nice refernce to the title id = json.data.children[r].data.id; //sets a nice reference to the reddit id if (image.contains("i.imgur")) { //checks if the url points to imgur imagearray.push({'id': id, 'url': image, 'subreddit': subreddit, 'title': title}); //adds valid images to the imagearray if (json.data.children[r].data.over_18 === true) { console.log("nsfw"); //finalhtml += '<div class="image '+ subreddit +" "+ id +'" id="'+ id +'"><img class="nsfw" src='+ image +'><h1 class="title">'+ title +'</h1></div>'; //$('.images').append('<div class="image '+ subreddit +" "+ id +'" id="'+ id +'"><img class="nsfw" src='+ image +'><h1 class="title">'+ title +'</h1></div>'); } else if (json.data.children[r].data.over_18 === false) { finalhtml = '<div class="image ' + subreddit + " " + id + '" id="' + id + '"><img src=' + image + '><h1 class="title">' + title + '</h1></div>'; $('.images').append(finalhtml); } } r++; } console.log(finalhtml); //$('.images').append(finalhtml);//appends the html we built console.log(imagearray[0].id); }); } //does what it says on the tin, checks url's. specifically pulls together a nice subreddit list. function checkurl() { var sub = window.location.hash, //gets the hash varible we built up earlyer subreddits = sub.replace('#', ' ').trimLeft(),//removes the hash and trims it up url; console.log(subreddits);//logging dis bitch if (localStorage.getItem("includepics") === 'true') { if (window.location.hash) { url = "http://www.reddit.com/r/pics+" + subreddits + ".json"; //sets url to /r/pics + other subreddits $('.alert').remove(); //removes the "add subreddits" text imgload(url); } else { url = "http://www.reddit.com/r/pics.json";//sets url to the default only /r/pics $('.alert').remove(); //removes the "add subreddits" text imgload(url); } } else if (localStorage.getItem("includepics") === 'false' && window.location.hash) { url = "http://www.reddit.com/r/" + subreddits + ".json"; //sets url to just other subreddits $('.alert').remove(); //removes the "add subreddits" text $(".pics").remove(); //removes all /r/pics images imgload(url); } else { $('.images').append('<div class="image alert" id="plz"><h1>Add Subreddits Plz</h1></div>'); //appends a nice alert... lol } } $('#addsub').submit(function () { var sub = document.getElementById("subname").value; if (window.location.hash) { window.location.hash += "+" + sub; checkurl(); return false; } window.location.hash += sub; checkurl(); return false; }); //infinite loading function $(window).scroll(function () { if ($(window).scrollTop() >= $(document).height() - $(window).height() - 1000) { console.log($(document).height()); console.log("bottom!"); if (loading === false){ console.log(after); datavar = {'limit': '50', 'after':after}; checkurl(); loading = true; } else if (loading === true){ console.log("loading..."); } } }); //basic button click and input handlers follow $( "#picstrue" ).click(function(){ localStorage.setItem("includepics", "true"); $( ".image" ).remove(); $('.alert').remove(); window.scrollTo(0, 0); //set the window to top checkurl(); }); $( "#picsfalse" ).click(function(){ localStorage.setItem("includepics", "false"); $( ".image" ).remove(); $('.images').prepend('<div class="image alert" id="plz"><h1>Add Subreddits plz</h1></div>'); window.scrollTo(0, 0); //set the window to top checkurl(); }); /*$("nsfw:checked"){ //display: block; } $("nsfw:unchecked"){ //display: none; }*/ $("#reload").click(function(){//remove the auto-reload on adding subreddits? window.scrollTo(0, 0); //set the window back to top checkurl(); }); //main code $(document).ready(function() {//add a check for /false or /true and set the includepics var appropriatly if(localStorage.getItem("includepics") === null){//checks if /r/pics is included/if this is first visit, and sets /r/pics to be included localStorage.setItem("includepics", "true"); $('#picstrue').prop('checked', true); console.log("null - set all true"); checkurl(); } else if (localStorage.getItem("includepics") === 'true'){//checks if /r/pics is included and sets the radio to true. $('#picstrue').prop('checked', true); console.log("true - set radio true"); checkurl(); } else if (localStorage.getItem("includepics") === 'false'){//checks if /r/pics is set to false and set the radio to false $('#picsfalse').prop('checked', true); console.log("false - set radio false"); //set include pics radio to false so we dont break the rest of the code -_- checkurl(); } });
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 5h-3.17l-1.24-1.35c-.37-.41-.91-.65-1.47-.65H9.88c-.56 0-1.1.24-1.47.65L7.17 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-8 4c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm4 8H8v-.57c0-.81.48-1.53 1.22-1.85.85-.37 1.79-.58 2.78-.58s1.93.21 2.78.58c.74.32 1.22 1.04 1.22 1.85V17z" /> , 'PhotoCameraFrontRounded');
import Ember from 'ember'; const { RSVP: { resolve, reject } } = Ember; export default class QueryLoader { constructor() { this.state = { isLoading: false, isLoaded: false, isError: false, error: null }; this.needed = true; this.promise = null; } // getProxy() { // } // getQuery() { // } // didLoad(results) { // } setState(state, notify=true) { for(let key in this.state) { if(!state.hasOwnProperty(key)) { state[key] = this.state[key]; } } this.state = state; let proxy = this.getProxy(); if(proxy && notify) { proxy.notifyPropertyChange('state'); } } setNeedsReload() { this.needed = true; let proxy = this.getProxy(); proxy.beginPropertyChanges(); { proxy.notifyPropertyChange('promise'); proxy.notifyPropertyChange('content'); proxy.notifyPropertyChange('state'); } proxy.endPropertyChanges(); } setLoaded(notify) { this.setState({ isLoaded: true }, notify); this.needed = false; } createPromise(notify=true) { let query = this.getQuery(); this.setState({ isLoading: true, isError: false, error: null }, notify); return query._find().then(result => { this.didLoad(result); this.setState({ isLoading: false, isLoaded: true, isError: false, error: false }); return this.getProxy(); }, err => { this.setState({ isLoading: false, isError: true, error: err }); return reject(err); }); } shouldCreatePromise() { if(!this.needed) { return false; } let query = this.getQuery(); if(!query) { return false; } if(!query.get('_isLoadable')) { return false; } return true; } getPromise(notify) { let promise = this.promise; if(!promise) { if(!this.shouldCreatePromise()) { return resolve(this.getProxy()); } this.needed = false; const done = arg => { if(this.promise === promise) { this.promise = null; } return arg; }; promise = this.createPromise(notify).then(arg => done(resolve(arg)), err => done(reject(err))); this.promise = promise; } return promise; } load(notify) { this.getPromise(notify); } getState() { this.load(false); return this.state; } }
import { delay } from 'redux-saga'; import { call, put, takeEvery, select } from 'redux-saga/effects'; import * as apiClient from '../utils/apiClient'; import { success, error } from '../actions/message'; import actions, { QUERY_COMMENTS, DELETE_COMMENT } from '../actions/comment'; const getCommentState = state => state.comment; function* queryComments() { try { const commentState = yield select(getCommentState); yield put(actions.requestQueryComments()); const result = yield call(apiClient.get, 'comment', {...commentState.queryParams }); yield put(actions.successQueryComments(result)); } catch (e) { yield put(actions.failureQueryComments()); yield put(error(e.message)); } } function* deleteComment(action) { try { yield put(actions.requestDeleteComment()); const result = yield call(apiClient.del, `comment/${action.payload.id}`); yield put(actions.successDeleteComment()); yield put(success(result.message)); yield call(queryComments); } catch (e) { yield put(actions.failureDeleteComment()); yield put(error(e.message)); } } export default function* comment() { yield takeEvery(QUERY_COMMENTS, queryComments); yield takeEvery(DELETE_COMMENT, deleteComment); }
(function() { /** Implementation of the 'convert' verb for HackMyResume. @module verbs/convert @license MIT. See LICENSE.md for details. */ /** Private workhorse method. Convert 0..N resumes between FRESH and JRS formats. */ /** Private workhorse method. Convert a single resume. */ var ConvertVerb, HMEVENT, HMSTATUS, ResumeFactory, Verb, _, _convert, _convertOne, chalk; ResumeFactory = require('../core/resume-factory'); chalk = require('chalk'); Verb = require('../verbs/verb'); HMSTATUS = require('../core/status-codes'); _ = require('underscore'); HMEVENT = require('../core/event-codes'); module.exports = ConvertVerb = class ConvertVerb extends Verb { constructor() { super('convert', _convert); } }; _convert = function(srcs, dst, opts) { var fmtUp, results, targetVer; if (!srcs || !srcs.length) { this.err(HMSTATUS.resumeNotFound, { quit: true }); return null; } if (!dst || !dst.length) { if (srcs.length === 1) { this.err(HMSTATUS.inputOutputParity, { quit: true }); } else if (srcs.length === 2) { dst = dst || []; dst.push(srcs.pop()); } else { this.err(HMSTATUS.inputOutputParity, { quit: true }); } } // Different number of source and dest resumes? Error out. if (srcs && dst && srcs.length && dst.length && srcs.length !== dst.length) { this.err(HMSTATUS.inputOutputParity, { quit: true }); } // Validate the destination format (if specified) targetVer = null; if (opts.format) { fmtUp = opts.format.trim().toUpperCase(); if (!_.contains(['FRESH', 'FRESCA', 'JRS', 'JRS@1', 'JRS@edge'], fmtUp)) { this.err(HMSTATUS.invalidSchemaVersion, { data: opts.format.trim(), quit: true }); } } // freshVerRegex = require '../utils/fresh-version-regex' // matches = fmtUp.match freshVerRegex() // # null // # [ 'JRS@1.0', 'JRS', '1.0', index: 0, input: 'FRESH' ] // # [ 'FRESH', 'FRESH', undefined, index: 0, input: 'FRESH' ] // if not matches // @err HMSTATUS.invalidSchemaVersion, data: opts.format.trim(), quit: true // targetSchema = matches[1] // targetVer = matches[2] || '1' // If any errors have occurred this early, we're done. if (this.hasError()) { this.reject(this.errorCode); return null; } // Map each source resume to the converted destination resume results = _.map(srcs, function(src, idx) { var r; // Convert each resume in turn r = _convertOne.call(this, src, dst, idx, fmtUp); // Handle conversion errors if (r.fluenterror) { r.quit = opts.assert; this.err(r.fluenterror, r); } return r; }, this); if (this.hasError() && !opts.assert) { this.reject(results); } else if (!this.hasError()) { this.resolve(results); } return results; }; _convertOne = function(src, dst, idx, targetSchema) { var err, rez, rinfo, srcFmt, targetFormat; // Load the resume rinfo = ResumeFactory.loadOne(src, { format: null, objectify: true, inner: { privatize: false } }); // If a load error occurs, report it and move on to the next file (if any) if (rinfo.fluenterror) { this.stat(HMEVENT.beforeConvert, { srcFile: src, //rinfo.file srcFmt: '???', dstFile: dst[idx], dstFmt: '???', error: true }); //@err rinfo.fluenterror, rinfo return rinfo; } // Determine the resume's SOURCE format // TODO: replace with detector component rez = rinfo.rez; srcFmt = ''; if (rez.meta && rez.meta.format) { //&& rez.meta.format.substr(0, 5).toUpperCase() == 'FRESH' srcFmt = 'FRESH'; } else if (rez.basics) { srcFmt = 'JRS'; } else { rinfo.fluenterror = HMSTATUS.unknownSchema; return rinfo; } // Determine the TARGET format for the conversion targetFormat = targetSchema || (srcFmt === 'JRS' ? 'FRESH' : 'JRS'); // Fire the beforeConvert event this.stat(HMEVENT.beforeConvert, { srcFile: rinfo.file, srcFmt: srcFmt, dstFile: dst[idx], dstFmt: targetFormat }); try { // Save it to the destination format rez.saveAs(dst[idx], targetFormat); } catch (error) { err = error; if (err.badVer) { return { fluenterror: HMSTATUS.invalidSchemaVersion, quit: true, data: err.badVer }; } } return rez; }; }).call(this); //# sourceMappingURL=convert.js.map
import React from 'react' import { Link } from 'gatsby' import Layout from '../components/Layout' export default ({ location }) => ( <Layout location={location}> <Link to="/"> <h1>NOT FOUND</h1> </Link> </Layout> )
(window.webpackJsonp=window.webpackJsonp||[]).push([[87],{452:function(t,a,s){"use strict";s.r(a);var e=s(1),r=Object(e.a)({},(function(){var t=this,a=t.$createElement,s=t._self._c||a;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h2",{attrs:{id:"examples"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#examples"}},[t._v("#")]),t._v(" Examples")]),t._v(" "),s("div",{staticClass:"language- extra-class"},[s("pre",{pre:!0,attrs:{class:"language-text"}},[s("code",[t._v("datahub-cli publish my-data-package/\n")])])]),s("h2",{attrs:{id:"solutions"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#solutions"}},[t._v("#")]),t._v(" Solutions")]),t._v(" "),s("p",[s("strong",[t._v("DataHub")]),s("br"),t._v("\nIt’s a free and open source data hub. Built to work seamlessly with other Frictionless Data tools.")])])}),[],!1,null,null,null);a.default=r.exports}}]);
'use strict'; module.exports = Routes Routes.$inject = ['$routeProvider', '$locationProvider'] function Routes($routeProvider, $locationProvider) { $locationProvider.html5Mode(false); $routeProvider.when('/', { templateUrl: '/partials/find-station.html' ,controller: 'findStation' }) $routeProvider.when('/:lat,:lon/', { templateUrl: '/partials/tide-view.html' ,controller: 'station' }) $routeProvider.when('/:lat,:lon/:year-:month-:day/', { templateUrl: '/partials/tide-view.html' ,controller: 'station' }) };
/* * Kendo UI v2015.1.408 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["en-AU"] = { name: "en-AU", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["-$n","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "$" } }, calendars: { standard: { days: { names: ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"], namesAbbr: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"], namesShort: ["Su","Mo","Tu","We","Th","Fr","Sa"] }, months: { names: ["January","February","March","April","May","June","July","August","September","October","November","December"], namesAbbr: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] }, AM: ["AM","am","AM"], PM: ["PM","pm","PM"], patterns: { d: "d/MM/yyyy", D: "dddd, d MMMM yyyy", F: "dddd, d MMMM yyyy h:mm:ss tt", g: "d/MM/yyyy h:mm tt", G: "d/MM/yyyy h:mm:ss tt", m: "MMMM d", M: "MMMM d", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "h:mm tt", T: "h:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
//module.exports = require("./bin/DevToolsDetector"); module.exports = require("./lib/DevToolsDetector");
'use strict'; const scribble = require('../'); const theChords = scribble.getChordsByProgression('G minor', 'i III v VI'); const notesArr = scribble.arp({ chords: theChords, count: 4, // you can set any number from 2 to 8 // The default value of order is 01234567 as count is 8 by default // but here we set count to 4 hence we are only using the first 4 indices to set a order order: '0103', }); scribble.midi( scribble.clip({ notes: notesArr, pattern: '[RxRx]'.repeat(8), }), 'arp.mid' ); // This will create a file called arp.mid in the same location as you run this script // Generate a pad from the chords used scribble.midi( scribble.clip({ notes: theChords, pattern: 'x___'.repeat(4), subdiv: '1n', }), 'pad.mid' ); // This will create a file called pad.mid in the same location as you run this script // Generate a melody to go along with the arp and the pad const getRandomPattern = function(count) { let str = ''; for (let i = 0; i < (count || 8); i++) { str += Math.round(Math.random()) ? 'x-' : '-x'; } return str; }; const ptn = getRandomPattern(); const arpedNotes = scribble.arp({ chords: scribble.getChordsByProgression('G minor', 'i III'), count: 4, order: '0213', }); scribble.midi( scribble.clip({ notes: arpedNotes, pattern: ptn, subdiv: '16n', }), 'melody.mid' ); // You can use lodash's sampleSize method to randomly select a set of notes // from a scale to construct random chords // e.g. https://scribbletune.com/examples/random-chords const arpedNotesFromChordArr = scribble.arp({ chords: [ ['A3', 'F#4', 'A4'], ['F#3', 'G4', 'B4'], ['B4', 'C3', 'B3'], ['E4', 'C4', 'G3'], ['G3', 'A3', 'D3'], ['G3', 'B4', 'F#4'], ['B3', 'F#4', 'G4'], ['E4', 'A4', 'D3'], ['A4', 'G4', 'A3'], ['D3', 'B3', 'A4'], ['F#4', 'B3', 'E4'], ['C4', 'A3', 'F#4'], ], count: 4, order: '0213', }); scribble.midi( scribble.clip({ notes: arpedNotesFromChordArr, pattern: 'xx-x-xxx'.repeat(5).slice(0, 32), subdiv: '16n', }), 'melody2.mid' );
/** * Finds verse references and highlights them * * @author John Dyer (http://j.hn/) */ docs.plugins.push({ init: function(docManager) { // insert style $('<style id="verse-popup-style">.tagged-reference { cursor: pointer; color: #779; }</style>').appendTo($(document.body)); // create popup var versePopup = docs.createModal('Verses', 'Verses'); versePopup.content.css({'max-height': '150px', 'overflow': 'auto'}); // setup events to add media icons docManager.addEventListener('load', function(e) { findVerses(e.chapter); }); function findVerses(chapter) { bibly.ignoreClassName = 'cf'; bibly.handleLinks = function(node, reference) { //node.style.fontWeight = 'bold'; //node.style.color = '#0ff'; node.className = 'tagged-reference'; $(node).on('mouseover', function() { // measure position var node = $(this), nodePos = node.offset(), nodeWidth = node.width(), nodeHeight = node.height(), popupWidth = versePopup.window.outerWidth(true), popupHeight = versePopup.window.outerHeight(true), windowWidth = $(window).width(), windowHeight = $(window).height(), // default to below and to the right top = (nodePos.top + nodeHeight + nodeHeight > windowHeight) ? nodePos.top - popupHeight - 5 : nodePos.top + nodeHeight + 4, left = (nodePos.left + popupWidth > windowWidth) ? windowWidth - popupWidth : nodePos.left; versePopup.title.html(reference.toString()); versePopup.show(); versePopup.window.css({top: top, left: left}); var chapterUrl = 'content/bibles/' + docManager.documents[0].selector.val() + '/' + reference.osisBookID + '.' + reference.chapter1 + '.html'; versePopup.content.html('Loading...'); // TODO: get verse text! $.ajax({ url: chapterUrl, dataType: 'html', success: function(data) { var verseClasses = [], startVerse = reference.verse1 > 0 ? reference.verse1 : 1, endVerse = reference.verse2 > 0 ? Math.min(reference.verse1+3,reference.verse2) : reference.verse1; for (var i=startVerse; i<=endVerse; i++) { verseClasses.push('.' + reference.osisBookID + '_' + reference.chapter1 + '_' + i); } versePopup.content.empty(); var verses = $(data).find( verseClasses.join(',') ) .find('span.note, span.cf') .remove() .end(); verses.appendTo(versePopup.content); }, error: function() { console.log('error', chapterUrl); } }); }).on('mouseout', function() { versePopup.hide(); }).on('click', function() { var firstDoc = docManager.documents[0]; firstDoc.input.val( reference.toString() ); firstDoc.navigateToUserInput(); }); } //console.log('scan', chapter[0]); bibly.scanForReferences(chapter[0]); } } }); bible.genNames = function() { var names = [], i = 0, il = bible.DEFAULT_BIBLE.length; for (; i<il; i++) { var osisName = bible.DEFAULT_BIBLE[i]; names.push( bible.BOOK_DATA[osisName].names['eng'].join('|') ); } return names.join('|'); }; // adapted from old scripturizer.js code (function() { /* Scripture API methods */ var callbackIndex = 100000, jsonpCache = {}, jsonp = function(url, callback){ var jsonpName = 'callback' + (callbackIndex++), script = doc.createElement("script"); win[jsonpName] = function(d) { callback(d); } jsonpCache[url] = jsonpName; url += (url.indexOf("?") > -1 ? '&' : '?') + 'callback=' + jsonpName; //url += '&' + new Date().getTime().toString(); // prevent caching script.setAttribute("src",url); script.setAttribute("type","text/javascript"); body.appendChild(script); }, getBibleText = function(refString, callback) { var v = getPopupVersion(), max = bibly.maxVerses, reference = new bible.Reference(refString); // check that it's only 4 verses if (reference.verse1 > 0 && reference.verse2 > 0 && reference.verse2 - reference.verse1 > (max-1)) { reference.verse2 = reference.verse1 + (max-1); } else if (reference.verse1 <= 0 && reference.verse2 <= 0) { reference.verse1 = 1; reference.verse2 = max; reference.chapter2 = -1; } switch (v) { default: case 'NET': jsonp('http://labs.bible.org/api/?passage=' + encodeURIComponent(reference.toString()) + '&type=json', callback); break; case 'KJV': case 'LEB': jsonp('http://api.biblia.com/v1/bible/content/' + v + '.html.json?style=oneVersePerLine&key=' + bibly.bibliaApiKey + '&passage=' + encodeURIComponent(reference.toString()), callback); break; case 'ESV': jsonp('http://www.esvapi.org/crossref/ref.php?reference=' + encodeURIComponent(reference.toString()), callback); break; } }, handleBibleText = function(d) { var v = getPopupVersion(), p = bibly.popup, max = bibly.maxVerses, text = '', className = v + '-version', i,il; switch (v) { default: case 'NET': for (i=0,il=d.length; i<il && i<max; i++) { text += '<span class="bibly_verse_number">' + d[i].verse + '</span>' + d[i].text + ' '; } break; case 'KJV': case 'LEB': className += ' biblia'; text = d.text; break; case 'ESV': text = d.content; break; } p.content.innerHTML = '<div class="' + className + '">' + text + '</div>'; }; /* handler for when a verse node is found */ var createBiblyLinks = function(newNode, reference) { newNode.setAttribute('href', reference.toShortUrl() + (bibly.linkVersion != '' ? '.' + bibly.linkVersion : '')); newNode.setAttribute('title', 'Read ' + reference.toString()); newNode.setAttribute('rel', reference.toString()); newNode.setAttribute('class', bibly.className); if (bibly.newWindow) { newNode.setAttribute('target', '_blank') } if (bibly.enablePopups) { addEvent(newNode,'mouseover', handleLinkMouseOver); addEvent(newNode,'mouseout', handleLinkMouseOut); } }, checkPosTimeout, handleLinkMouseOver = function(e) { if (!e) e = win.event; clearPositionTimer(); var target = (e.target) ? e.target : e.srcElement, p = bibly.popup, pos = getPosition(target), x = y = 0, v = getPopupVersion(); referenceText = target.getAttribute('rel'), viewport = getWindowSize(), scrollPos = getScroll(); p.outer.style.display = 'block'; p.header.innerHTML = referenceText + ' (' + v + ')'; p.content.innerHTML = 'Loading...<br/><br/><br/>'; p.footer.innerHTML = getFooter(v); function positionPopup() { x = pos.left - (p.outer.offsetWidth/2) + (target.offsetWidth/2); y = pos.top - p.outer.clientHeight; // for the arrow if (x < 0) { x = 0; } else if (x + p.outer.clientWidth > viewport.width) { x = viewport.width - p.outer.clientWidth - 20; } if (y < 0 || (y < scrollPos.y) ){ // above the screen y = pos.top + target.offsetHeight + 10; p.arrowtop.style.display = 'block'; p.arrowtop_border.style.display = 'block'; p.arrowbot.style.display = 'none'; p.arrowbot_border.style.display = 'none'; } else { y = y-10; p.arrowtop.style.display = 'none'; p.arrowtop_border.style.display = 'none'; p.arrowbot.style.display = 'block'; p.arrowbot_border.style.display = 'block'; } p.outer.style.top = y + 'px'; p.outer.style.left = x + 'px'; } positionPopup(); getBibleText(referenceText, function(d) { // handle the various JSON outputs handleBibleText(d); // reposition the popup //y = pos.top - p.outer.clientHeight - 10; // border //p.outer.style.top = y + 'px'; positionPopup(); }); }, handleLinkMouseOut = function(e) { startPositionTimer(); }, handlePopupMouseOver = function(e) { clearPositionTimer(); }, handlePopupMouseOut = function(e) { startPositionTimer(); }, /* Timer on/off */ startPositionTimer = function () { checkPosTimeout = setTimeout(hidePopup, 500); }, clearPositionTimer = function() { clearTimeout(checkPosTimeout); delete checkPosTimeout; }, hidePopup = function() { var p = bibly.popup; p.outer.style.display = 'none'; }, getPosition = function(node) { var curleft = curtop = curtopscroll = curleftscroll = 0; if (node.offsetParent) { do { curleft += node.offsetLeft; curtop += node.offsetTop; curleftscroll += node.offsetParent ? node.offsetParent.scrollLeft : 0; curtopscroll += node.offsetParent ? node.offsetParent.scrollTop : 0; } while (node = node.offsetParent); } return {left:curleft,top:curtop,leftScroll:curleftscroll,topScroll:curtopscroll}; }, getWindowSize= function() { var width = 0, height = 0; if( typeof( win.innerWidth ) == 'number' ) { // Non-IE width = win.innerWidth; height = win.innerHeight; } else if( doc.documentElement && ( doc.documentElement.clientWidth || doc.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' width = doc.documentElement.clientWidth; height = doc.documentElement.clientHeight; } else if( body && ( body.clientWidth || body.clientHeight ) ) { //IE 4 compatible width = body.clientWidth; height = body.clientHeight; } return {width:width, height: height}; }, getScroll = function () { var scrOfX = 0, scrOfY = 0; if( body && ( body.scrollLeft || body.scrollTop ) ) { //DOM compliant scrOfY = body.scrollTop; scrOfX = body.scrollLeft; } else if( doc.documentElement && ( doc.documentElement.scrollLeft || doc.documentElement.scrollTop ) ) { //IE6 standards compliant mode scrOfY = doc.documentElement.scrollTop; scrOfX = doc.documentElement.scrollLeft; } else if( typeof( win.pageYOffset ) == 'number' ) { //Netscape compliant scrOfY = win.pageYOffset; scrOfX = win.pageXOffset; } return {x: scrOfX, y:scrOfY }; }; /* core bibly functions */ var bibly = { version: '0.9.2', maxNodes: 500, className: 'bibly_reference', enablePopups: true, popupVersion: 'ESV', linkVersion: '', bibliaApiKey: '436e02d01081d28a78a45d65f66f4416', autoStart: true, startNodeId: '', maxVerses: 4, newWindow: false, ignoreClassName: 'bibly_ignore', ignoreTags: ['h1','h2','h3','h4'], newTagName: 'A', handleLinks: createBiblyLinks }, win = window, doc = document, body = null, defaultPopupVersion = 'ESV', allowedPopupVersions = ['NET','ESV','KJV','LEB','DARBY'], bok = bible.genNames(), // 1 OR 1:1 OR 1:1-2, 100, but not 1000 ver = '(' + // '(1?\\d{1,2})' + // 1 '([\.:]\\s?(\\d+))?' + // :2 ')' + '(' + '\\s?[-Ð&]\\s?(\\d+)' + // -3 '([\.:]\\s?(\\d+))?' + // :4 ')?', // NOT 1. Only 1:1 OR 1:1-2 ver2 = '(1?\\d{1,2})' // 1## + '[\.:]\\s?(\\d+)' + '(\\s?[-Ð&]\\s?(\\d+))?', // this is needed so verses after semi-colons require a :. Problem John 3:16; 2 Cor 3:3 <-- the 2 will be a verse) regexPattern = '\\b('+bok+')\.?\\s+' // book name with period and/or spaces afterward + '(' + ver // verse pattern (1 OR 1:1 OR 1:1-2) + '(' + '(\\s?,(\\s+)?'+ver+')|' // , VERSE + '(\\s?;(\\s+)?'+ver2+')' // ; CHAPTER:Verse + ')*' // infinite reoccurance + ')\\b', referenceRegex = new RegExp(regexPattern, 'mi'), verseRegex = new RegExp(ver, 'mi'), alwaysSkipTags = ['a','script','style','textarea'], lastReference = null, textHandler = function(node) { var match = referenceRegex.exec(node.data), val, referenceNode, afterReferenceNode, newLink; // reset this lastReference = null; if (match) { val = match[0]; // see https://developer.mozilla.org/en/DOM/text.splitText // split into three parts [node=before][referenceNode][afterReferenceNode] referenceNode = node.splitText(match.index); afterReferenceNode = referenceNode.splitText(val.length); // send the matched text down the newLink = createLinksFromNode(node, referenceNode); return newLink; } else { return node; } }, createLinksFromNode = function(node, referenceNode) { if (referenceNode.nodeValue == null) return referenceNode; // split up match by ; and , characters and make a unique link for each var newLink, commaIndex = referenceNode.nodeValue.indexOf(','), semiColonIndex = referenceNode.nodeValue.indexOf(';'), separatorIndex = (commaIndex > 0 && semiColonIndex > 0) ? Math.min(commaIndex, semiColonIndex) : Math.max(commaIndex, semiColonIndex), separator, remainder, reference, startRemainder; // if there is a separator ,; then split up into three parts [node][separator][after] if (separatorIndex > 0) { separator = referenceNode.splitText(separatorIndex); startRemainder = 1; while(startRemainder < separator.nodeValue.length && separator.nodeValue.substring(startRemainder,startRemainder+1) == ' ') startRemainder++; remainder = separator.splitText(startRemainder); } // test if the text matches a real reference refText = referenceNode.nodeValue; reference = parseRefText(refText); if (typeof reference != 'undefined' && reference.isValid()) { // replace the referenceNode TEXT with an anchor node to bib.ly newNode = node.ownerDocument.createElement(bibly.newTagName); node.parentNode.replaceChild(newNode, referenceNode); // this can be overridden for other systems bibly.handleLinks(newNode, reference); newNode.appendChild(referenceNode); // if there was a separator, now parse the stuff after it if (remainder) { newNode = createLinksFromNode(node, remainder); } return newNode; } else { // for false matches, return it unchanged return referenceNode; } }, parseRefText = function(refText) { var text = refText, reference = new bible.Reference(text), match = null, p1, p2, p3, p4; if (reference != null && typeof reference.isValid != 'undefined' && reference.isValid()) { lastReference = reference; return reference; } else if (lastReference != null) { // single verse match (3) match = verseRegex.exec(refText); if (match) { // "1" ["1", "1", "1", u, u, u, u, u, u] // "1:2" ["1:2", "1:2", "1", ":2", "2", u, u, u, u] // "1-2" ["1-2", "1", "1", u, u, "-2", "2", u, u] // "1:2-3" ["1:2-3", "1:2", "1", ":2", "2", "-3", "3", u, u] // "1:2-3:4" ["1:2-3:4", "1:2", "1", ":2", "2", "-3:4", "3", ":4", "4"] p1 = parseInt(match[2],10); p2 = parseInt(match[4],10); p3 = parseInt(match[6],10); p4 = parseInt(match[8],10); if (isNaN(p2)) { p2 = 0; } if (isNaN(p3)) { p3 = 0; } if (isNaN(p4)) { p4 = 0; } // single verse (1) if (p1 > 0 && p2 == 0 && p3 == 0 && p4 == 0) { lastReference.verse1 = p1; lastReference.chapter2 = -1; lastReference.verse2 = -1; // 1:2 } else if (p1 > 0 && p2 > 0 && p3 == 0 && p4 == 0) { lastReference.chapter1 = p1; lastReference.verse1 = p2; lastReference.chapter2 = -1; lastReference.verse2 = -1; // 1-2 } else if (p1 > 0 && p2 == 0 && p3 > 0 && p4 == 0) { lastReference.verse1 = p1; lastReference.chapter2 = -1; lastReference.verse2 = p3; // 1:2-3 } else if (p1 > 0 && p2 > 0 && p3 > 0 && p4 == 0) { lastReference.chapter1 = p1; lastReference.verse1 = p2; lastReference.chapter2 = -1; lastReference.verse2 = p3; // 1:2-3:4 } else if (p1 > 0 && p2 > 0 && p3 > 0 && p4 > 0) { lastReference.chapter1 = p1; lastReference.verse1 = p2; lastReference.chapter2 = p3; lastReference.verse2 = p4; } return lastReference; } // failure return { refText: refText, toShortUrl: function() { return 'http://bib.ly/' + refText.replace(/\s/ig,'').replace(/:/ig,'.').replace(/Ð/ig,'-'); }, toString: function() { return refText + " = Can't parse it"; } }; } else { return undefined; } }, getFooter = function(version) { switch (version) { case 'NET': return '<a href="http://bible.org/">NET Bible¨ copyright ©1996-2006 by Biblical Studies Press, LLC</a>'; case 'ESV': return 'English Standard Version. Copyright &copy;2001 by <a href="http://www.crosswaybibles.org">Crossway Bibles</a>'; case 'LEB': case 'KJV': return version + ' powered by <a href="http://biblia.com/">Biblia</a> web services from <a href="http://www.logos.com/">Logos Bible Software</a>'; default: return ''; } }, getPopupVersion = function() { var v = bibly.popupVersion.toUpperCase(), indexOf=-1, i=0, il=allowedPopupVersions.length; // old IEs don't have Array.indexOf for (; i < il; i++) { if (allowedPopupVersions[i].toUpperCase() === v) { indexOf = i; break; } } return (indexOf > -1) ? v : defaultPopupVersion; }, scanForReferences = function(node) { // build doc traverseDOM(node.childNodes[0], 1, textHandler); }, traverseDOM = function(node, depth, textHandler) { var count = 0, //skipRegex = /^(a|script|style|textarea)$/i, skipRegex = new RegExp('^(' + alwaysSkipTags.concat(bibly.ignoreTags).join('|') + ')$', 'i'); while (node && depth > 0) { count++; if (count >= bibly.maxNodes) { setTimeout(function() { traverseDOM(node, depth, textHandler); }, 50); return; } switch (node.nodeType) { case 1: // ELEMENT_NODE if (!skipRegex.test(node.tagName.toLowerCase()) && node.childNodes.length > 0 && (bibly.ignoreClassName == '' || node.className.toString().indexOf(bibly.ignoreClassName) == -1)) { node = node.childNodes[0]; depth ++; continue; } break; case 3: // TEXT_NODE case 4: // CDATA_SECTION_NODE node = textHandler(node); break; } if (node.nextSibling) { node = node.nextSibling; } else { while (depth > 0) { node = node.parentNode; depth --; if (node.nextSibling) { node = node.nextSibling; break; } } } } }, addEvent = function(obj,name,fxn) { if (obj.attachEvent) { obj.attachEvent('on' + name, fxn); } else if (obj.addEventListener) { obj.addEventListener(name, fxn, false); } else { var __ = obj['on' + name]; obj['on' + name] = function() { fxn(); __(); }; } }, isStarted = false, extend = function() { // borrowed from ender var options, name, src, copy, target = arguments[0] || {}, i = 1, length = arguments.length; // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && typeof target !== "function" ) { target = {}; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }, startBibly = function() { if (isStarted) return; isStarted = true; doc = document; body = doc.body; // create popup var p = bibly.popup = { outer: doc.createElement('div') }, parts = ['header','content','footer','arrowtop_border','arrowtop','arrowbot_border','arrowbot'], i, il, div, name, node = null; p.outer.className = 'bibly_popup_outer'; // build all the parts for (i=0,il=parts.length; i<il; i++) { name = parts[i]; div = doc.createElement('div'); div.className = 'bibly_popup_' + name; p.outer.appendChild(div); p[name] = div; } body.appendChild(p.outer); addEvent(p.outer,'mouseover',handlePopupMouseOver); addEvent(p.outer,'mouseout',handlePopupMouseOut); if (bibly.autoStart) { if (bibly.startNodeId != '') { node = doc.getElementById(bibly.startNodeId); } if (node == null) { node = body; } scanForReferences(node); } }; // super cheater version of DOMoade // do whatever happens first addEvent(doc,'DOMContentLoaded',startBibly); addEvent(win,'load',startBibly); if (typeof window.bibly != 'undefined') bibly = extend(bibly, window.bibly); // export bibly.startBibly = startBibly; bibly.scanForReferences = scanForReferences; win.bibly = bibly; })();
"use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var dispatcher = _interopRequire(require("./dispatcher")); /* rxtx should be object like: { 'rxEvent1': 'txEvent1', 'rxEvent2': 'txEvent2' } */ module.exports = function (nodelist, rxtx) { // coerce node list to array var elements = Array.prototype.slice.call(nodelist), // get all other elements except for one from elements array getOthers = function (me) { return elements.filter(function (elm) { return me !== elm; }); }, // multiple elements dispatch same event dispatchAll = function (elements, eventName, data) { return elements.forEach(function (elm) { return dispatcher(elm, eventName, data); }); }, // add rx listener to element which sends tx event(s) to others initElement = function (element) { var others = getOthers(element); Object.keys(rxtx).forEach(function (k) { return element.addEventListener(k, function (e) { return dispatchAll(others, rxtx[k], e.detail); }); }); }; elements.forEach(initElement); };
'use strict'; function getData({ url, method = 'post' } = {}, callback) { callback(url, method); } getData({ url: 'myposturl.com' }, function (url, method) { console.log(url, method); }); getData({ url: 'myputurl.com', method: 'put' }, function (url, method) { console.log(url, method); });
// @flow export type Range = {| start: number, end: number, |} export type Resolved = | {| type: "url", url: string |} | {| type: "file", filename: ?string |} type ExternalModule = {| local: string, start: number, end: number, moduleName: string, imported: string, |} export type SuggestionFromImport = {| type: "from-import", moduleName: string, imported: string, bindingStart: number, bindingEnd: number, |} type BindingSuggestion = {| type: "binding", start: number, end: number, |} export type PathSuggestion = {| type: "path", imported: string, moduleName: string, range: Range, |} export type Suggestion = | SuggestionFromImport | BindingSuggestion | PathSuggestion export type SuggestionOptions = { // This can't be an exact type because buildSuggestion has a default value // of `{}`. I don't know why Flow inists the two are incompatible when // `jumpToImport` is optional. jumpToImport?: boolean, } type Path = {| imported: string, moduleName: string, range: Range, |} type Binding = {| identifier: Range, |} type BabelScope = {| block: Range, hasBinding: string => boolean, getBinding: string => Binding, |} type ParseError = {| type: "parse-error", parseError: Error, |} export type Info = | ParseError | { type: "info", parseError?: typeof undefined, exports: { [string]: Range, }, scopes: Array<BabelScope>, externalModules: Array<ExternalModule>, paths: Array<Path>, }
var request = require('request'); var _ = require('underscore'); var cheerio = require('cheerio'); var baseURL = 'http://news.ycombinator.com'; var call = function (path, callback) { request(baseURL + path, function(err, res, body) { if(err) return callback(err); parsePage(body, callback); }); }; var parsePage = function (body, callback) { var items = []; var $ = cheerio.load(body); $('td.title').each(function (index, element) { if(index % 2 !== 1) return true; var item = {}; var tempHref = $(this).parent().next().find('a').next().attr('href'); if(!tempHref) return false; item.id = parseInt(tempHref.match(/id=([0-9]+)/)[1], 10); item.title = $(this).find('a').text(); item.url = $(this).find('a').attr('href'); items.push(item); }); callback(null, items); }; var home = function (callback) { call('/', callback); }; var newest = function (callback) { call('/newest', callback); }; var best = function (callback) { call('/best', callback); }; // Export Vars module.exports.baseURL = baseURL; // Export Parser module.exports.parsePage = parsePage; // Export Call module.exports.call = call; // Export Call Proxies module.exports.home = home; module.exports.newest = newest; module.exports.best = best;
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { dist: { files: { 'css/framework.css': 'sass/barebone.scss' } } }, watch: { css: { files: ['sass/*'], tasks: ['sass'] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask("default", ["sass"]); };
var async = require('async'); var helpers = require('./helpers'); /** * TODO: Add discription here ... * */ var Dependence = module.exports = function(shared) { this.shareDependencies = shared === undefined ? true : !!shared; this.dependencies = {}; this.shared = {}; this.providers = []; this.use = Dependence.prototype.use.bind(this); this.register = Dependence.prototype.register.bind(this); this.resolve = Dependence.prototype.resolve.bind(this); } Dependence.prototype = { /** * Use a provider to resolve dependencies by name. * param {Function} provider Provider to resolve a dependency by name. */ use: function(provider) { switch (typeof provider) { case 'function': this.providers.unshift(provider); break; case 'string': this.registerFiles(provider); break; default: throw "'provider' must be either of string or function! Actual type: " + typeof provider; } }, /** * Register a dependency directly without using a provider. * You can also overwrite dependencies here! * param {String} name Name of the dependency. Should be the same as the parameter name of the resolving function. * param {Function} dependency Dependency that can also have multiple dependencies in its parameters. */ register: function(name, dependency) { if (typeof dependency === 'function') return this.dependencies[name] = dependency; this.shared[name] = dependency; }, /** * Resolves all dependencies defined in the parameters of a function * or just a single dependency by passing the specific name. * param {Function|String} arg Either the name or a function to resolve. * param {Function(err, dependency)} callback Function to receive either an error and a dependency (if resolving directly by name) or the return value of the resolved function. */ resolve: function(arg, callback) { switch (typeof arg) { case 'string': this.resolveDependency(arg, callback); break; case 'function': this.resolveFunction(arg, callback); break; default: throw "'arg' must be either string or function! It was: " + typeof arg; } }, /** * Resolves all dependencies defined in the parameters of a function * param {Function} func Function that can have multiple dependencies in its parameters. * param {Function} callback Receives the result of func. */ resolveFunction: function(func, callback, history) { var self = this; // Extract dependency names var dependencyNames = func.require || helpers.extractFunctionParameters(func); // If there is nothing to resolve -> just call func if (dependencyNames.length == 0) return callback(func()); if (!history) history = []; // Resolve dependencies and call func async.map(dependencyNames, function(name, callback) { // Resolve dependency pasing the cloned history. self.resolveDependency(name, function(dependency) { callback(null, dependency); }, history.slice()); }, function done(err, dependencies) { callFunc(dependencies); }); function callFunc(dependencies) { var result = func.apply(self, dependencies); // Calls the dependency constructor passing the dependencies if (callback) callback(result); // Provide the result of func to callback } }, /** * Tries to resolve a dependency directly by name * param {String} name Dependency name * param {Function(dependency)} callback Provides the resolved dependency */ resolveDependency: function(name, callback, history) { var self = this; if (!history) history = []; // Check circular dependency if (history.indexOf(name) !== -1) { history.push("[" + name + "]"); console.error("Circular dependency found!\n" + history.join("\n -> ")); return callback(null); } else { history.push(name); } // If dependency was resolved already -> return the result var shared = this.shared[name]; if (shared) return callback(shared); // If dependency was found already -> resolve it and return result var dependency = this.dependencies[name]; if (dependency) return done(dependency); // Walk through the providers until one of them gives back a dependency async.eachSeries(self.providers, function(provider, callback) { provider(name, function(dependency) { if (!dependency) return callback(); if (typeof dependency !== 'function') { callback(); throw "Provider returned an invalid dependency of type: " + typeof dependency; } callback(dependency); }); }, done); // Resolve the dependencies of the dependency and return the result function done(dependency) { // Could not be resolved if (!dependency) { return callback(undefined); } // Ensure dependency is a function if (typeof dependency !== 'function') { return callback(undefined); } // Save dependency self.dependencies[name] = dependency; // Resolve dependency self.resolveFunction(dependency, function(resolved) { var saveToShared = dependency.shared !== undefined ? dependency.shared : self.shareDependencies; if (saveToShared) self.shared[name] = resolved; callback(resolved); }, history || []) } } }
version https://git-lfs.github.com/spec/v1 oid sha256:e18f876039ea5216f19c9ce3ad1cbebffb9e230d2a5c74d5b000d759a78c2e2d size 29766
// Regular expression that matches all symbols in the Halfwidth and Fullwidth Forms block as per Unicode v5.2.0: /[\uFF00-\uFFEF]/;
/** * Simple Alert * * This little function allows us to display alerts to the user. The alerts * append to a wrapper of choice, and takes on two other variables. * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2014, Call Me Nick * http://callmenick.com */ ;( function( window ) { 'use strict'; /** * Extend obj function * * This is an object extender function. It allows us to extend an object * by passing in additional variables and overwriting the defaults. */ function extend( a, b ) { for( var key in b ) { if( b.hasOwnProperty( key ) ) { a[key] = b[key]; } } return a; } /** * SimpleAlert * * @param {object} options - The options object */ function SimpleAlert( options ) { this.options = extend( {}, this.options ); extend( this.options, options ); this._init(); } /** * SimpleAlert options Object * * @type {HTMLElement} wrapper - The wrapper to append alerts to. * @param {string} type - The type of alert. * @param {string} message - The alert message. */ SimpleAlert.prototype.options = { wrapper : document.body, type : "default", message : "Default message." } /** * SimpleAlert _init * * This is the initializer function. It builds the HTML and gets the alert * ready for showing. * * @type {HTMLElement} this.sa - The Simple Alert div * @param {string} strinner - The inner HTML for our alert */ SimpleAlert.prototype._init = function() { // create element this.sa = document.createElement('div'); this.sa.className = 'simple-alert ' + this.options.type; // create html var strinner = ''; strinner += '<span class="simple-alert__content">'; strinner += this.options.message; strinner += '</span>'; strinner += '<a href="#" class="simple-alert__dismiss">close</a>'; this.sa.innerHTML = strinner; // run the events this._events(); }; /** * SimpleAlert _events * * This is our events function, and its sole purpose is to listen for * any events inside our Simple Alert. * * @type {HTMLElement} btn_dismiss - The dismiss-alert button */ SimpleAlert.prototype._events = function() { // cache vars var btn_dismiss = this.sa.querySelector('.simple-alert__dismiss'), self = this; // listen for dismiss btn_dismiss.addEventListener( "click", function(e) { e.preventDefault(); self.dismiss(); }); } /** * SimpleAlert show * * This function simply shows our Simple Alert by appending it * to the wrapper in question. */ SimpleAlert.prototype.show = function() { this.options.wrapper.appendChild(this.sa); } /** * SimpleAlert dismiss * * This function simply hides our Simple Alert by removing it * from the wrapper in question. */ SimpleAlert.prototype.dismiss = function() { this.options.wrapper.removeChild(this.sa); }; /** * Add to global namespace */ window.SimpleAlert = SimpleAlert; })( window );
'use strict'; angular.module('applicationApp') .controller('AdminCtrl', function ($scope, $http, Auth, User) { // Use the User $resource to fetch all users $scope.users = User.query(); $scope.delete = function(user) { User.remove({ id: user._id }); angular.forEach($scope.users, function(u, i) { if (u === user) { $scope.users.splice(i, 1); } }); }; });
var spawn = require('./spawn'); var createOptions = require('./create-options'); function grabModuleData(context, next) { // launch npm info as a child process, using the tmp directory // as the working directory. var proc = spawn( 'npm', ['view', '--json', context.module.raw], createOptions( context.path, context)); var data = ''; proc.stdout.on('data', function(chunk) { data += chunk; }); proc.on('error', function(err) { next(err); }); proc.on('close', function(code) { if (code > 0) { context.emit('data', 'silly','npm-view','No npm package information available'); if (context.module.type == 'hosted' && context.module.hosted.type == 'github') { context.meta = { repository : { type: 'git', url: context.module.hosted.gitUrl } }; } next(null, context); return; } context.emit('data', 'silly','npm-view','Data retrieved'); try { context.meta = JSON.parse(data); } catch (ex) { next(ex); return; } next(null, context); }); } module.exports = grabModuleData;
function Stats(simulation, configuration) { function DataSet(stats, interval, avgMultiplier, eventsAsArrays) { this.events = []; this.avg = null; this.avgHistory = []; this.interval = interval || 1; this.avgMultiplier = avgMultiplier || 1; this.stats = stats; this.updateHistoryFrom = 0; this.eventsAsArrays = eventsAsArrays; this.getAvg = function (index, forceRecalculate) { index = index == undefined ? this.events.length - 1 : index; if (forceRecalculate || !this.avg) { var subArray = this.events.slice(Math.max(0, index - (this.stats.dataPointsToRemember / this.interval)), index); if (this.eventsAsArrays) { subArray = [].concat.apply([], subArray); } this.avg = subArray.average() * this.avgMultiplier; } return this.avg; } this.getAvgHistory = function () { for (var i = this.updateHistoryFrom; i < this.events.length; i++) { this.avgHistory.push({x: i * this.interval, y: this.getAvg(i, true)}); } this.updateHistoryFrom = this.events.length; return this.avgHistory; } this.recalculateAvg = function () { this.avgHistory = []; this.updateHistoryFrom = 0; } this.addEvent = function (event) { this.events.push(event); this.avg = null; } } this.configuration = configuration; this.dataPointsToRemember = 8 * this.configuration.get("stats.noOfDaysForMovingAverage"); // hours * days this.cfdData = {}; this.wip = new DataSet(this); this.throughput = new DataSet(this, 1, 8); this.availablePeople = new DataSet(this); this.busyPeople = new DataSet(this); this.capacityUtilisation = new DataSet(this); this.leadTime = new DataSet(this, 1, 1 / (8 * 60), true); this.touchTimePercent = new DataSet(this, 1, 1, true); this.costOfDelay = new DataSet(this, 8); this.valueDelivered = new DataSet(this, 8); this.valueDropped = new DataSet(this, 8); this.leadTimesHistory = []; for (var i = 0; i < simulation.board.columns.length; i++) { this.cfdData[simulation.board.columns[i].name] = []; } this.changeNoOfDaysForCountingAverages = function (newNoOfDays) { newNoOfDays = parseInt(newNoOfDays); if (Number.isNaN(newNoOfDays) || newNoOfDays <= 0) return; this.dataPointsToRemember = newNoOfDays * 8; this.wip.recalculateAvg(); this.throughput.recalculateAvg(); this.capacityUtilisation.recalculateAvg(); this.leadTime.recalculateAvg(); this.touchTimePercent.recalculateAvg(); this.costOfDelay.recalculateAvg(); this.valueDelivered.recalculateAvg(); this.valueDropped.recalculateAvg(); } this.configuration.onChange("stats.noOfDaysForMovingAverage", this.changeNoOfDaysForCountingAverages.bind(this)); this.recalculateStats = function (simulation) { this.calculateAvailablePeople(simulation); this.calculateWip(simulation); if (simulation.time % 60 != 0) return; this.updateCfdData(simulation.board, simulation.time); var lastColumn = simulation.board.lastColumn(); var leadTimes = []; var touchTimes = []; lastColumn.tasks.forEach(function (task) { var leadTime = task.getLeadTime(); var touchTime = task.getTouchCount() * (60 / simulation.ticksPerHour); leadTimes.push(leadTime); touchTimes.push(100 * touchTime / leadTime); }); this.leadTime.addEvent(leadTimes); this.touchTimePercent.addEvent(touchTimes); this.wip.addEvent(this.currentWip / simulation.ticksPerHour); this.currentWip = 0; this.throughput.addEvent(simulation.board.getDoneTasksCount(simulation.time - 60, simulation.time)); this.availablePeople.addEvent(this.notWorkingCountSummed / simulation.ticksPerHour); this.busyPeople.addEvent(this.busyCountSummed / simulation.ticksPerHour); var lastPos = this.busyPeople.events.length - 1; this.capacityUtilisation.addEvent(100 * this.busyPeople.events[lastPos] / (this.busyPeople.events[lastPos] + this.availablePeople.events[lastPos])); this.notWorkingCountSummed = 0; this.busyCountSummed = 0; if (simulation.time % (60 * 8) == 0) { var cod = simulation.board.getCostOfDelay(); this.costOfDelay.addEvent(cod); var tasksDone = simulation.board.getDoneTasks(); var valueDelivered = 0; for (var i = 0; i < tasksDone.length; i++) { valueDelivered += tasksDone[i].value.remainingValue(simulation.time); } this.valueDelivered.addEvent(valueDelivered); var tasksDropped = simulation.board.droppedTasks; var valueDroppedSummed = 0; for (var i = 0; i < tasksDropped.length; i++) { valueDroppedSummed += tasksDropped[i].value.totalValue(); } this.valueDropped.addEvent(valueDroppedSummed); } this.updateHistory(simulation.time); } this.notWorkingCountSummed = 0; this.busyCountSummed = 0; this.calculateAvailablePeople = function (simulation) { var notWorkingCount = simulation.team.getNotWorking().length; var teamSize = simulation.team.members.length; this.notWorkingCountSummed += notWorkingCount; this.busyCountSummed += teamSize - notWorkingCount; } this.currentWip = 0; this.calculateWip = function (simulation) { var currentWip = simulation.board.getCurrentWip(); this.currentWip += currentWip; } this.updateHistory = function (time) { var tasks = simulation.board.getDoneTasks(simulation.time - 60, simulation.time); for (var i = 0; i < tasks.length; i++) { this.leadTimesHistory.push({x: time, y: tasks[i].getLeadTime() / 60 / 8}); } } this.updateCfdData = function (board, time) { if (time % (60 * 8) != 0) return; var day = (time / 60 / 8); for (var i = 0; i < board.columns.length - 1; i++) { this.cfdData[board.columns[i].name].push({x: day, y: board.columns[i].tasks.length}); } var lastColumnName = board.columns[board.columns.length - 1].name; var lastColumn = this.cfdData[lastColumnName]; var lastDoneCount = lastColumn[lastColumn.length - 1] ? lastColumn[lastColumn.length - 1].y : 0; lastColumn.push({x: day, y: (board.columns[board.columns.length - 1].tasks.length + lastDoneCount)}); } }
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var NavbarService = (function () { function NavbarService() { this.userInfo = new core_1.EventEmitter(); } NavbarService.prototype.updateUserInfo = function (newInfo) { this.userInfo.emit(newInfo); }; NavbarService.prototype.getEmittedValue = function () { return this.userInfo; }; __decorate([ core_1.Output(), __metadata('design:type', core_1.EventEmitter) ], NavbarService.prototype, "userInfo", void 0); NavbarService = __decorate([ core_1.Injectable(), __metadata('design:paramtypes', []) ], NavbarService); return NavbarService; }()); exports.NavbarService = NavbarService; //# sourceMappingURL=navbar.service.js.map
// // Rule: color.js // Description: // ------------------------------------------------ dry.addRule((function(){ var init = function(parser, callback) { var colorMap = []; parser.addListener("property", function(event){ if(/color/g.test(event.property)) { if(/\\/g.test(event.value) === false) { colorMap[event.value] = (colorMap[event.value] || 0) + 1; } } }); parser.addListener("endstylesheet", function(){ if(callback){ callback({ type: 'colors', data: colorMap }); } }); }; return { init: init }; }()));
'use strict'; angular.module('myApp.view1', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view1', { templateUrl: 'view1/view1.html', controller: 'View1Ctrl' }); }]) .controller('View1Ctrl', ['$scope', '$http', '$sce', function($scope, $http, $sce) { $http.get('http://localhost:8080/recent_posts').success(function(data) { $scope.posts = data; for (var i = 0; i < data.length; i++) { data[i].num_comments = data[i].comments.length; data[i].body = $sce.trustAsHtml(data[i].body); } }). error(function(data) { $scope.posts = [{'title':'Error loading posts'}] }) }]);
import * as ActionTypes from '../actions' import {isEqual, without} from 'lodash' export default function productsReducer(state = {}, action) { switch (action.type) { case ActionTypes.LOAD_ORDERS: return {...state, orders: action.orders} case ActionTypes.ADD_ORDER: return {...state, orders: action.newOrder } case ActionTypes.DELETE_ORDER: let orders = state.orders state.orders = orders.filter(obj => { if(isEqual(obj, action.order)) { obj = null } return obj }) return {...state, orders: state.orders} default: return state } }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M15 19v-2H8.41L20 5.41 18.59 4 7 15.59V9H5v10h10z" /> , 'SouthWestOutlined');
import React from 'react'; const Section = props => ( <section> <h2 id={props.title}> <a href={`#${props.title}`}>{props.title}</a> </h2> {props.children} </section> ); export default Section;
const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const config = require('./webpack.config'); const app = new (require('express'))(); const port = 4000; const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); app.use((req, res) => { res.sendFile(`${__dirname}/index.html`); }); app.listen(port, (error) => { if (error) { console.error(error); } else { console.info('==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port); } });
var game; var speedMult = 0.7; // this is the friction which will slow down the map. Must be less than 1 var friction = 0.99; window.onload = function() { game = new Phaser.Game(480, 480, Phaser.AUTO, ""); game.state.add("PlayGame", playGame); game.state.start("PlayGame"); } var playGame = function(game) {}; playGame.prototype = { preload: function() { game.load.image("map", "assets/map.png"); }, create: function() { // the big map to scroll this.scrollingMap = game.add.image(0, 0, "map"); // map will accept inputs this.scrollingMap.inputEnabled = true; // map can be dragged this.scrollingMap.input.enableDrag(false); // custom property: we save map position this.scrollingMap.savedPosition = new Phaser.Point(this.scrollingMap.x, this.scrollingMap.y); // custom property: the map is not being dragged at the moment this.scrollingMap.isBeingDragged = false; // custom property: map is not moving (or is moving at no speed) this.scrollingMap.movingSpeed = 0; // map can be dragged only if it entirely remains into this rectangle this.scrollingMap.input.boundsRect = new Phaser.Rectangle(game.width - this.scrollingMap.width, game.height - this.scrollingMap.height, this.scrollingMap.width * 2 - game.width, this.scrollingMap.height * 2 - game.height); // when the player starts dragging... this.scrollingMap.events.onDragStart.add(function() { // set isBeingDragged property to true this.scrollingMap.isBeingDragged = true; // set movingSpeed property to zero. This will stop moving the map // if the player wants to drag when it's already moving this.scrollingMap.movingSpeed = 0; }, this); // when the player stops dragging... this.scrollingMap.events.onDragStop.add(function() { // set isBeingDragged property to false this.scrollingMap.isBeingDragged = false; }, this); }, update: function() { // if the map is being dragged... if (this.scrollingMap.isBeingDragged) { // save current map position this.scrollingMap.savedPosition = new Phaser.Point(this.scrollingMap.x, this.scrollingMap.y); } // if the map is NOT being dragged... else { // if the moving speed is greater than 1... if (this.scrollingMap.movingSpeed > 1) { // adjusting map x position according to moving speed and angle using trigonometry this.scrollingMap.x += this.scrollingMap.movingSpeed * Math.cos(this.scrollingMap.movingangle); // adjusting map y position according to moving speed and angle using trigonometry this.scrollingMap.y += this.scrollingMap.movingSpeed * Math.sin(this.scrollingMap.movingangle); // keep map within boundaries if (this.scrollingMap.x < game.width - this.scrollingMap.width) { this.scrollingMap.x = game.width - this.scrollingMap.width; } // keep map within boundaries if (this.scrollingMap.x > 0) { this.scrollingMap.x = 0; } // keep map within boundaries if (this.scrollingMap.y < game.height - this.scrollingMap.height) { this.scrollingMap.y = game.height - this.scrollingMap.height; } // keep map within boundaries if (this.scrollingMap.y > 0) { this.scrollingMap.y = 0; } // applying friction to moving speed this.scrollingMap.movingSpeed *= friction; // save current map position this.scrollingMap.savedPosition = new Phaser.Point(this.scrollingMap.x, this.scrollingMap.y); } // if the moving speed is less than 1... else { // checking distance between current map position and last saved position // which is the position in the previous frame var distance = this.scrollingMap.savedPosition.distance(this.scrollingMap.position); // same thing with the angle var angle = this.scrollingMap.savedPosition.angle(this.scrollingMap.position); // if the distance is at least 4 pixels (an arbitrary value to see I am swiping) if (distance > 4) { // set moving speed value this.scrollingMap.movingSpeed = distance * speedMult; // set moving angle value this.scrollingMap.movingangle = angle; } } } } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createTyped = void 0; var _is = require("../../utils/is"); var _typedFunction = _interopRequireDefault(require("typed-function")); var _number = require("../../utils/number"); var _factory = require("../../utils/factory"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /** * Create a typed-function which checks the types of the arguments and * can match them against multiple provided signatures. The typed-function * automatically converts inputs in order to find a matching signature. * Typed functions throw informative errors in case of wrong input arguments. * * See the library [typed-function](https://github.com/josdejong/typed-function) * for detailed documentation. * * Syntax: * * math.typed(name, signatures) : function * math.typed(signatures) : function * * Examples: * * // create a typed function with multiple types per argument (type union) * const fn2 = typed({ * 'number | boolean': function (b) { * return 'b is a number or boolean' * }, * 'string, number | boolean': function (a, b) { * return 'a is a string, b is a number or boolean' * } * }) * * // create a typed function with an any type argument * const log = typed({ * 'string, any': function (event, data) { * console.log('event: ' + event + ', data: ' + JSON.stringify(data)) * } * }) * * @param {string} [name] Optional name for the typed-function * @param {Object<string, function>} signatures Object with one or multiple function signatures * @returns {function} The created typed-function. */ var _createTyped2 = function _createTyped() { // initially, return the original instance of typed-function // consecutively, return a new instance from typed.create. _createTyped2 = _typedFunction["default"].create; return _typedFunction["default"]; }; var dependencies = ['?BigNumber', '?Complex', '?DenseMatrix', '?Fraction']; /** * Factory function for creating a new typed instance * @param {Object} dependencies Object with data types like Complex and BigNumber * @returns {Function} */ var createTyped = /* #__PURE__ */ (0, _factory.factory)('typed', dependencies, function createTyped(_ref) { var BigNumber = _ref.BigNumber, Complex = _ref.Complex, DenseMatrix = _ref.DenseMatrix, Fraction = _ref.Fraction; // TODO: typed-function must be able to silently ignore signatures with unknown data types // get a new instance of typed-function var typed = _createTyped2(); // define all types. The order of the types determines in which order function // arguments are type-checked (so for performance it's important to put the // most used types first). typed.types = [{ name: 'number', test: _is.isNumber }, { name: 'Complex', test: _is.isComplex }, { name: 'BigNumber', test: _is.isBigNumber }, { name: 'Fraction', test: _is.isFraction }, { name: 'Unit', test: _is.isUnit }, { name: 'string', test: _is.isString }, { name: 'Chain', test: _is.isChain }, { name: 'Array', test: _is.isArray }, { name: 'Matrix', test: _is.isMatrix }, { name: 'DenseMatrix', test: _is.isDenseMatrix }, { name: 'SparseMatrix', test: _is.isSparseMatrix }, { name: 'Range', test: _is.isRange }, { name: 'Index', test: _is.isIndex }, { name: 'boolean', test: _is.isBoolean }, { name: 'ResultSet', test: _is.isResultSet }, { name: 'Help', test: _is.isHelp }, { name: 'function', test: _is.isFunction }, { name: 'Date', test: _is.isDate }, { name: 'RegExp', test: _is.isRegExp }, { name: 'null', test: _is.isNull }, { name: 'undefined', test: _is.isUndefined }, { name: 'AccessorNode', test: _is.isAccessorNode }, { name: 'ArrayNode', test: _is.isArrayNode }, { name: 'AssignmentNode', test: _is.isAssignmentNode }, { name: 'BlockNode', test: _is.isBlockNode }, { name: 'ConditionalNode', test: _is.isConditionalNode }, { name: 'ConstantNode', test: _is.isConstantNode }, { name: 'FunctionNode', test: _is.isFunctionNode }, { name: 'FunctionAssignmentNode', test: _is.isFunctionAssignmentNode }, { name: 'IndexNode', test: _is.isIndexNode }, { name: 'Node', test: _is.isNode }, { name: 'ObjectNode', test: _is.isObjectNode }, { name: 'OperatorNode', test: _is.isOperatorNode }, { name: 'ParenthesisNode', test: _is.isParenthesisNode }, { name: 'RangeNode', test: _is.isRangeNode }, { name: 'SymbolNode', test: _is.isSymbolNode }, { name: 'Object', test: _is.isObject } // order 'Object' last, it matches on other classes too ]; typed.conversions = [{ from: 'number', to: 'BigNumber', convert: function convert(x) { if (!BigNumber) { throwNoBignumber(x); } // note: conversion from number to BigNumber can fail if x has >15 digits if ((0, _number.digits)(x) > 15) { throw new TypeError('Cannot implicitly convert a number with >15 significant digits to BigNumber ' + '(value: ' + x + '). ' + 'Use function bignumber(x) to convert to BigNumber.'); } return new BigNumber(x); } }, { from: 'number', to: 'Complex', convert: function convert(x) { if (!Complex) { throwNoComplex(x); } return new Complex(x, 0); } }, { from: 'number', to: 'string', convert: function convert(x) { return x + ''; } }, { from: 'BigNumber', to: 'Complex', convert: function convert(x) { if (!Complex) { throwNoComplex(x); } return new Complex(x.toNumber(), 0); } }, { from: 'Fraction', to: 'BigNumber', convert: function convert(x) { throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' + 'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.'); } }, { from: 'Fraction', to: 'Complex', convert: function convert(x) { if (!Complex) { throwNoComplex(x); } return new Complex(x.valueOf(), 0); } }, { from: 'number', to: 'Fraction', convert: function convert(x) { if (!Fraction) { throwNoFraction(x); } var f = new Fraction(x); if (f.valueOf() !== x) { throw new TypeError('Cannot implicitly convert a number to a Fraction when there will be a loss of precision ' + '(value: ' + x + '). ' + 'Use function fraction(x) to convert to Fraction.'); } return f; } }, { // FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))` // from: 'Fraction', // to: 'number', // convert: function (x) { // return x.valueOf() // } // }, { from: 'string', to: 'number', convert: function convert(x) { var n = Number(x); if (isNaN(n)) { throw new Error('Cannot convert "' + x + '" to a number'); } return n; } }, { from: 'string', to: 'BigNumber', convert: function convert(x) { if (!BigNumber) { throwNoBignumber(x); } try { return new BigNumber(x); } catch (err) { throw new Error('Cannot convert "' + x + '" to BigNumber'); } } }, { from: 'string', to: 'Fraction', convert: function convert(x) { if (!Fraction) { throwNoFraction(x); } try { return new Fraction(x); } catch (err) { throw new Error('Cannot convert "' + x + '" to Fraction'); } } }, { from: 'string', to: 'Complex', convert: function convert(x) { if (!Complex) { throwNoComplex(x); } try { return new Complex(x); } catch (err) { throw new Error('Cannot convert "' + x + '" to Complex'); } } }, { from: 'boolean', to: 'number', convert: function convert(x) { return +x; } }, { from: 'boolean', to: 'BigNumber', convert: function convert(x) { if (!BigNumber) { throwNoBignumber(x); } return new BigNumber(+x); } }, { from: 'boolean', to: 'Fraction', convert: function convert(x) { if (!Fraction) { throwNoFraction(x); } return new Fraction(+x); } }, { from: 'boolean', to: 'string', convert: function convert(x) { return String(x); } }, { from: 'Array', to: 'Matrix', convert: function convert(array) { if (!DenseMatrix) { throwNoMatrix(); } return new DenseMatrix(array); } }, { from: 'Matrix', to: 'Array', convert: function convert(matrix) { return matrix.valueOf(); } }]; return typed; }); exports.createTyped = createTyped; function throwNoBignumber(x) { throw new Error("Cannot convert value ".concat(x, " into a BigNumber: no class 'BigNumber' provided")); } function throwNoComplex(x) { throw new Error("Cannot convert value ".concat(x, " into a Complex number: no class 'Complex' provided")); } function throwNoMatrix() { throw new Error('Cannot convert array into a Matrix: no class \'DenseMatrix\' provided'); } function throwNoFraction(x) { throw new Error("Cannot convert value ".concat(x, " into a Fraction, no class 'Fraction' provided.")); }
/** * Created by Neil on 2015-4-13. */ var app = angular.module('ngb1.chp2.demo11', []); app.controller('ParentController', function ($scope) { $scope.parent = 'parent'; }); app.controller('ChildController', function ($scope) { $scope.child = 'child'; //$scope.parent = 'child2'; });
{ throw new Error("this is unexpected."); }
import React, {PropTypes} from 'react'; import {Link} from 'react-router'; const AuthorListRow = ({author}) => { return ( <tr className="authorRow"> <td><Link to={'/author/' + author.id}>{author.firstName} {author.lastName}</Link></td> <td>{author.courseCount}</td> </tr> ); }; AuthorListRow.propTypes = { author: PropTypes.object.isRequired }; export default AuthorListRow;
import { Fragment, createElement, Component, useEffect, useRef, useState, } from '@wordpress/element' import classnames from 'classnames' import { getDefaultFonts } from './default-data' import { humanizeVariations, fontFamilyToCSSFamily } from './helpers' import { FixedSizeList as List } from 'react-window' import WebFontLoader from 'webfontloader' import AutoSizer from 'react-virtualized-auto-sizer' let loadedFonts = [] const loadGoogleFonts = (font_families) => { if (font_families.length === 0) return loadedFonts = [...loadedFonts, ...font_families.map(({ family }) => family)] const googleFonts = font_families .map(({ family }) => family) .filter((family) => family.indexOf('ct_typekit') === -1) const typekitFonts = font_families.filter( ({ family }) => family.indexOf('ct_typekit') > -1 ) if (googleFonts.length > 0 || typekitFonts.length > 0) { WebFontLoader.load({ ...(googleFonts.length > 0 ? { google: { families: googleFonts, }, } : {}), ...(typekitFonts.length > 0 ? { typekit: { id: typekitFonts[0].kit, }, } : {}), classes: false, text: 'abcdefghijklmnopqrstuvwxyz', }) } } const SingleFont = ({ data: { linearFontsList, onPickFamily, value }, index, style, }) => { const family = linearFontsList[index] return ( <div style={style} onClick={() => onPickFamily(family)} className={classnames( 'ct-typography-single-font', `ct-${family.source}`, { active: family.family === value.family, } )} key={family.family}> <span className="ct-font-name"> {family.display || family.family} </span> <span style={{ fontFamily: fontFamilyToCSSFamily(family.family), }} className="ct-font-preview"> Simply dummy text </span> </div> ) } const FontsList = ({ option, value, onPickFamily, typographyList, linearFontsList, currentView, searchTerm, }) => { const listRef = useRef(null) const timerRef = useRef(null) const [scrollTimer, setScrollTimer] = useState(null) useEffect(() => { if (value.family) { listRef.current.scrollToItem( linearFontsList .map(({ family }) => family) .indexOf(value.family), 'start' ) } }, []) const onScroll = () => { scrollTimer && clearTimeout(scrollTimer) setScrollTimer( setTimeout(() => { if (!listRef.current) { return } const [overscanStartIndex] = listRef.current._getRangeToRender() const perPage = 25 const totalPages = Math.ceil(linearFontsList.length / perPage) const startingPage = Math.ceil( (overscanStartIndex + 1) / perPage ) // const stopPage = Math.ceil((overscanStopIndex + 1) / perPage) const pageItems = [...Array(perPage)] .map((_, i) => (startingPage - 1) * perPage + i) .map((index) => linearFontsList[index]) .filter((s) => !!s) .filter( ({ source, family }) => loadedFonts.indexOf(family) === -1 && (source === 'google' || source === 'typekit') ) loadGoogleFonts(pageItems) }, 100) ) } useEffect(() => { onScroll() }, [linearFontsList]) return ( <List height={360} itemCount={linearFontsList.length} itemSize={85} ref={listRef} onScroll={(e) => { onScroll() }} itemData={{ linearFontsList, onPickFamily, value, }} onItemsRendered={({ overscanStartIndex, overscanStopIndex }) => {}} className="ct-typography-fonts"> {SingleFont} </List> ) } export default FontsList
'use strict'; var jsonSql = require('../lib')(); var expect = require('chai').expect; describe('Insert', function() { it('should throw error without `values` property', function() { expect(function() { jsonSql.build({ type: 'insert', table: 'users' }); }).to.throw('`values` property is not set in `insert` clause'); }); it('should be ok with `values` property', function() { var result = jsonSql.build({ type: 'insert', table: 'users', values: { name: 'Max' } }); expect(result.query).to.be.equal('insert into "users" ("name") values ($p1);'); expect(result.values).to.be.eql({p1: 'Max'}); }); it('should be ok with `with` property', function() { var result = jsonSql.build({ 'with': [{ name: 't_1', select: { table: 't_1' } }], type: 'insert', table: 'users', values: { name: 'Max', age: 17, lastVisit: null, active: true } }); expect(result.query).to.be.equal( 'with "t_1" as (select * from "t_1") insert into "users" ' + '("name", "age", "lastVisit", "active") values ($p1, 17, null, true);' ); expect(result.values).to.be.eql({p1: 'Max'}); }); it('should be ok with `returning` property', function() { var result = jsonSql.build({ type: 'insert', table: 'users', values: { name: 'Max', age: 17, lastVisit: null, active: true }, returning: ['users.*'] }); expect(result.query).to.be.equal( 'insert into "users" ("name", "age", "lastVisit", "active") ' + 'values ($p1, 17, null, true) returning "users".*;' ); expect(result.values).to.be.eql({p1: 'Max'}); }); });
var React = require('react'); var Fluxible = require('fluxible'); var app = new Fluxible({ component: require('./components/SpaApp.react') }); app.registerStore(require('./stores/RouteStore')); app.registerStore(require('./stores/ApplicationStore')); app.registerStore(require('./stores/NewsStore')); var context = app.createContext(); React.render(context.createElement(), document.body);
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users'); var answers = require('../../app/controllers/answers'); // Answers Routes app.route('/answers') .get(answers.list) .post(users.requiresLogin, answers.create); app.route('/answers/:answerId') .get(answers.read) .put(users.requiresLogin, answers.hasAuthorization, answers.update) .delete(users.requiresLogin, answers.hasAuthorization, answers.delete); // Finish by binding the Answer middleware app.param('answerId', answers.answerByID); };
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the License.txt file included with this file. /** @scope modules */ const Modes = Module("modes", { requires: ["config", "util"], init: function () { this._main = 1; // NORMAL this._extended = 0; // NONE this._lastShown = null; this._passNextKey = false; this._processNextKey = false; this._passAllKeys = false; this._passKeysExceptions = null; // Which keys are still allowed in ignore mode. ONLY set when an :ignorekeys LocationChange triggered it this._isRecording = false; this._isReplaying = false; // playing a macro this._modeStack = []; this._mainModes = [this.NONE]; this._lastMode = 0; this._modeMap = {}; // main modes, only one should ever be active this.addMode("NORMAL", { char: "n", display: -1 }); this.addMode("INSERT", { char: "i", input: true }); this.addMode("VISUAL", { char: "v", display: function () "VISUAL" + (editor.getVisualMode() ? " " + editor.getVisualMode() : "") }); this.addMode("COMMAND_LINE", { char: "c", input: true, display: -1 }); this.addMode("CARET"); // text cursor is visible this.addMode("TEXTAREA", { char: "i" }); this.addMode("EMBED", { input: true }); this.addMode("CUSTOM", { display: function () plugins.mode }); // this._extended modes, can include multiple modes, and even main modes this.addMode("EX", true); this.addMode("HINTS", true); this.addMode("INPUT_MULTILINE", true); this.addMode("OUTPUT_MULTILINE", true); this.addMode("SEARCH_FORWARD", true); this.addMode("SEARCH_BACKWARD", true); this.addMode("SEARCH_VIEW_FORWARD", true); this.addMode("SEARCH_VIEW_BACKWARD", true); this.addMode("LINE", true); // linewise visual mode this.addMode("PROMPT", true); config.modes.forEach(function (mode) { this.addMode.apply(this, mode); }, this); }, _getModeMessage: function () { if (this._processNextKey) { if (this._main == modes.NORMAL) { return "NORMAL (next)"; } else if (!this._main in this._modeMap || typeof this._modeMap[this._main].display !== "function") { return "PROCESS (next)"; } return this._modeMap[this._main].display() + " (next)"; } else if (this._passNextKey) { return "PASSTHROUGH (next)"; } else if (this._passAllKeys) { if (!this._passKeysExceptions || this._passKeysExceptions.length == 0) return "PASSTHROUGH"; else return "PASSTHROUGH (All except " + this._passKeysExceptions + ")"; } // when recording or replaying a macro if (modes.isRecording) return "RECORDING"; else if (modes.isReplaying) return "REPLAYING"; if (this._main in this._modeMap && typeof this._modeMap[this._main].display === "function") return this._modeMap[this._main].display(); return ""; // default mode message }, // NOTE: Pay attention that you don't run into endless loops // Usually you should only indicate to leave a special mode like HINTS // by calling modes.reset() and adding the stuff which is needed // for its cleanup here _handleModeChange: function (oldMode, newMode, oldExtended) { switch (oldMode) { case modes.TEXTAREA: case modes.INSERT: editor.unselectText(); break; case modes.VISUAL: if (newMode == modes.CARET) { try { // clear any selection made; a simple if (selection) does not work let selection = Buffer.focusedWindow.getSelection(); selection.collapseToStart(); } catch (e) {} } else editor.unselectText(); break; case modes.CUSTOM: plugins.stop(); break; case modes.COMMAND_LINE: // clean up for HINT mode if (oldExtended & modes.HINTS) hints.hide(); commandline.close(); break; } if (newMode == modes.NORMAL) { // disable caret mode when we want to switch to normal mode if (options.getPref("accessibility.browsewithcaret")) options.setPref("accessibility.browsewithcaret", false); if (oldMode == modes.COMMAND_LINE) liberator.focusContent(false); // when coming from the commandline, we might want to keep the focus (after a Search, e.g.) else liberator.focusContent(true); // unfocus textareas etc. } else if (newMode === modes.COMPOSE) { services.get("focus").clearFocus(window); } }, NONE: 0, __iterator__: function () util.Array.itervalues(this.all), get all() this._mainModes.slice(), get mainModes() (mode for ([k, mode] in Iterator(modes._modeMap)) if (!mode.extended && mode.name == k)), get mainMode() this._modeMap[this._main], addMode: function (name, extended, options) { let disp = name.replace(/_/g, " "); this[name] = 1 << this._lastMode++; if (typeof extended == "object") { options = extended; extended = false; } this._modeMap[name] = this._modeMap[this[name]] = update({ extended: extended, count: true, input: false, mask: this[name], name: name, disp: disp }, options); this._modeMap[name].display = this._modeMap[name].display || function () disp; if (!extended) this._mainModes.push(this[name]); if ("mappings" in modules) mappings.addMode(this[name]); }, getMode: function (name) this._modeMap[name], getCharModes: function (chr) [m for (m in values(this._modeMap)) if (m.char == chr)], matchModes: function (obj) [m for (m in values(this._modeMap)) if (array(keys(obj)).every(function (k) obj[k] == (m[k] || false)))], // show the current mode string in the command line show: function () { if (options["showmode"]) commandline.setModeMessage(this._getModeMessage()); }, // add/remove always work on the this._extended mode only add: function (mode) { this._extended |= mode; this.show(); }, // helper function to set both modes in one go // if silent == true, you also need to take care of the mode handling changes yourself set: function (mainMode, extendedMode, silent, stack) { silent = (silent || this._main == mainMode && this._extended == extendedMode); // if a this._main mode is set, the this._extended is always cleared let oldMain = this._main, oldExtended = this._extended; if (typeof extendedMode === "number") this._extended = extendedMode; if (typeof mainMode === "number") { this._main = mainMode; if (!extendedMode) this._extended = modes.NONE; if (this._main != oldMain) { this._handleModeChange(oldMain, mainMode, oldExtended); liberator.triggerObserver("modeChange", [oldMain, oldExtended], [this._main, this._extended]); // liberator.log("Changing mode from " + oldMain + "/" + oldExtended + " to " + this._main + "/" + this._extended + "(" + this._getModeMessage() + ")"); if (!silent) this.show(); } } }, // TODO: Deprecate this in favor of addMode? --Kris // Ya --djk setCustomMode: function (modestr, oneventfunc, stopfunc) { // TODO this.plugin[id]... ('id' maybe submode or what..) plugins.mode = modestr; plugins.onEvent = oneventfunc; plugins.stop = stopfunc; }, passAllKeysExceptSome: function passAllKeysExceptSome(exceptions) { this._passAllKeys = true; this._passKeysExceptions = exceptions || []; this.show(); }, isKeyIgnored: function isKeyIgnored(key) { if (modes.passNextKey) return true; if (modes.processNextKey) return false; if (modes.passAllKeys) { // handle Escape-all-keys mode (Shift-Esc) // Respect "unignored" keys if (modes._passKeysExceptions == null || modes._passKeysExceptions.indexOf(key) < 0) return true; else return false; // TODO: "unignore" option // TODO: config.ignoreKeys support or remove config.ignoreKeys } return false; }, // keeps recording state reset: function (silent) { this._modeStack = []; if (config.isComposeWindow) this.set(modes.COMPOSE, modes.NONE, silent); else this.set(modes.NORMAL, modes.NONE, silent); }, remove: function (mode) { if (this._extended & mode) { this._extended &= ~mode; this.show(); } }, isMenuShown: false, // when a popup menu is active justSet: false, // when we just changed a mode between keydown and keypress get passNextKey() this._passNextKey, set passNextKey(value) { this._passNextKey = value; this.show(); }, get processNextKey() this._processNextKey, set processNextKey(value) { this._processNextKey = value; this.show(); }, get passAllKeys() this._passAllKeys, set passAllKeys(value) { this._passAllKeys = value; this._passKeysExceptions = null; this.show(); }, get isRecording() this._isRecording, set isRecording(value) { this._isRecording = value; this.show(); }, get isReplaying() this._isReplaying, set isReplaying(value) { this._isReplaying = value; this.show(); }, get main() this._main, set main(value) { this.set(value); }, get extended() this._extended, set extended(value) { this.set(null, value); } }); // vim: set fdm=marker sw=4 ts=4 et:
module.exports={A:{A:{"2":"H D G E A B HB"},B:{"1":"0 C p J L N I"},C:{"1":"0 1 2 3 4 6 7 8 9 F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y z AB BB aB UB","16":"cB"},D:{"1":"0 1 2 4 6 7 8 9 F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y z AB BB OB eB GB IB FB JB KB LB MB"},E:{"1":"F K H D G E A B C NB EB PB QB RB SB TB b VB"},F:{"1":"2 B C J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y z WB XB YB ZB b CB bB DB","16":"E"},G:{"1":"5 G C EB dB fB gB hB iB jB kB lB mB nB oB"},H:{"1":"pB"},I:{"1":"3 5 F GB qB rB sB tB uB vB"},J:{"1":"D A"},K:{"1":"A B C M b CB DB"},L:{"1":"FB"},M:{"1":"1"},N:{"2":"A B"},O:{"1":"wB"},P:{"1":"F K xB yB"},Q:{"1":"zB"},R:{"1":"0B"}},B:7,C:"document.evaluate & XPath"};
var fspath = require("path"); /* * Match a tree against a string, regex, or custom function. A custom function * should accept a tree as its first argument and return a boolean value. * * string: returns true if the path contains the string * regex: returns true if the path matches the regex * function: returns true if the function returns true */ module.exports = function(tree, query) { // Custom function if (typeof query === "function") { return query(tree); } var filename = fspath.basename(tree.path()); // Check for sub string if (typeof query === "string") { return filename.indexOf(query) !== -1; } // Assume regex return query.test(filename); };
var express= require('express'); var router = express.Router(); var mongojs = require('mongojs'); var db = mongojs('mongodb://st:st123@ds145208.mlab.com:45208/st123',['tasks']) var Sequelize = require('sequelize'); var User= require('../database/Db object/user').User; module.exports = router;
function traverse(matrix) { const DIRECTIONS = [[0, 1], [0, -1], [1, 0], [-1, 0]]; const rows = matrix.length; const cols = matrix[0].length; const visited = matrix.map(row => Array(row.length).fill(false)); function dfs(i, j) { if (visited[i][j]) { return; } visited[i][j] = true; DIRECTIONS.forEach(dir => { const row = i + dir[0], col = j + dir[1]; // Boundary check. if (row < 0 || row >= rows || col < 0 || col >= cols) { return; } // Valid neighbor check. if (matrix[row][col] !== 1) { return; } dfs(row, col); }); } for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { dfs(i, j); } } }
import Validator from 'validator'; import isEmpty from 'lodash/isEmpty'; export function validateLogin(data) { let errors = {}; if (Validator.isEmpty(data.email)) { errors.email = 'Email is required'; } if (!Validator.isEmail(data.email)) { errors.email = 'Invalid email format'; } if (Validator.isEmpty(data.password)) { errors.password = 'Password is required'; } return { errors, isValid: isEmpty(errors) }; } export function validateRecovery(data) { let errors = {}; if (Validator.isEmpty(data.email)) { errors.email = 'Email is required'; } if (!Validator.isEmail(data.email)) { errors.email = 'Invalid email format'; } return { errors, isValid: isEmpty(errors) }; } export function validateReset(data) { let errors = {}; if (Validator.isEmpty(data.password)) { errors.password = 'Password is required'; } if (Validator.isEmpty(data.confirmPassword)) { errors.confirmPassword = 'Confirm your password'; } if (!Validator.equals(data.password, data.confirmPassword)) { errors.confirmPassword = 'Passwords must match'; } return { errors, isValid: isEmpty(errors) }; } export function validateSignup(data) { let errors = {}; if (Validator.isEmpty(data.name)) { errors.name = 'Name is required'; } if (Validator.isEmpty(data.email)) { errors.email = 'Email is required'; } if (!Validator.isEmail(data.email)) { errors.email = 'Invalid email format'; } if (Validator.isEmpty(data.password)) { errors.password = 'Password is required'; } if (Validator.isEmpty(data.passwordConfirmation)) { errors.passwordConfirmation = 'Confirm your password'; } if (!Validator.equals(data.password, data.passwordConfirmation)) { errors.passwordConfirmation = 'Passwords must match'; } return { errors, isValid: isEmpty(errors) }; } export function validateSurveyCreation(data) { let errors = {}; if (Validator.isEmpty(data.title)) { errors.form = 'Title is required'; } if (Validator.isEmpty(data.description)) { errors.form = 'General description is required'; } if (Validator.isEmpty(data.creatorId)) { errors.form = 'Something gone wrong. Please try again later.'; } return { isValid: isEmpty(errors) }; } export function validateUpdateProfile(data) { let errors = {}; if (Validator.isEmpty(data.name)) { errors.name = 'Name is required'; } if (Validator.isEmpty(data.email)) { errors.email = 'Email is required'; } if (!Validator.isEmail(data.email)) { errors.email = 'Invalid email format'; } return { errors, isValid: isEmpty(errors) }; }
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Router, useRouterHistory } from 'react-router'; import { createHashHistory } from 'history'; import configureStore from './store/configure'; import routes from './routes'; const history = useRouterHistory(createHashHistory)({ queryKey: false }); const store = configureStore(); ReactDOM.render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('app') );
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.LightBoxItem sap.ui.define([ 'jquery.sap.global', './library', 'sap/ui/core/Element', './Image', './Text'], function(jQuery, library, Element, Image, Text) { "use strict"; /** * Constructor for a new LightBoxItem. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] Initial settings for the new control * * @class * Represents an item which is displayed within a sap.m.LightBox. This item holds all properties of the image as * well as the title and subtitle. * @extends sap.ui.core.Element * * @author SAP SE * @version 1.46.7 * * @constructor * @public * @since 1.42 * @alias sap.m.LightBoxItem * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var LightBoxItem = Element.extend("sap.m.LightBoxItem", /** @lends sap.m.LightBoxItem.prototype */ { metadata: { library: "sap.m", properties: { /** * Source for the image. This property is mandatory. If not set the popup will not open */ imageSrc: {type: 'sap.ui.core.URI', group: 'Appearance', multiple: false, defaultValue: ''}, /** * Alt value for the image */ alt: {type: 'string', group: 'Appearance', multiple: false, defaultValue: ''}, /** * Title text for the image. This property is mandatory. */ title: {type: 'string', group: 'Appearance', multiple: false, defaultValue: ''}, /** * Subtitle text for the image */ subtitle: {type: 'string', group: 'Appearance', multiple: false, defaultValue: ''} }, aggregations: { /** * The image aggregation inside the LightBoxItem control. * @private */ _image: {type: 'sap.m.Image', multiple: false, visibility: 'hidden'}, /** * The title aggregation inside the LightBoxItem control. * @private */ _title: {type: 'sap.m.Text', multiple: false, visibility: 'hidden'}, /** * The subtitle aggregation inside the LightBoxItem control. * @private */ _subtitle: {type: 'sap.m.Text', multiple: false, visibility: 'hidden'} } } }); LightBoxItem.prototype.init = function() { this._createNativeImage(); this.setAggregation('_image', new Image({ decorative: false, densityAware: false }), true); this.setAggregation('_title', new Text({ wrapping : false }), true); this.setAggregation('_subtitle', new Text({ wrapping : false }), true); }; /** * Creates a native JavaScript Image object. * @private */ LightBoxItem.prototype._createNativeImage = function () { var that = this; this._imageState = sap.m.LightBoxLoadingStates.Loading; this._oImage = new window.Image(); this._oImage.onload = function(oEvent) { if (this.complete && that._imageState === sap.m.LightBoxLoadingStates.Loading) { that._setImageState(sap.m.LightBoxLoadingStates.Loaded); } }; this._oImage.onerror = function(oEvent) { that._setImageState(sap.m.LightBoxLoadingStates.Error); }; }; LightBoxItem.prototype.exit = function () { this._oImage = null; }; /** * Sets the state of the image. Possible values are "LOADING", "LOADED" and "ERROR" * @private * @param sImageState */ LightBoxItem.prototype._setImageState = function (sImageState) { if (sImageState !== this._imageState) { this._imageState = sImageState; if (this.getParent()) { this.getParent()._imageStateChanged(sImageState); } } }; /** * Gets the state of the image. * @private * @returns {string} State of the image */ LightBoxItem.prototype._getImageState = function() { return this._imageState; }; /** * Gets the native JavaScript Image object. * @private * @returns {Image|*} */ LightBoxItem.prototype._getNativeImage = function () { return this._oImage; }; /** * Sets the source of the image. * @public * @param {sap.ui.core.URI} sImageSrc The image URI * @returns {sap.m.LightBoxItem} Pointer to the control instance for chaining. */ LightBoxItem.prototype.setImageSrc = function(sImageSrc) { var oImage = this.getAggregation("_image"), oLightBox = this.getParent(); if (this.getImageSrc() === sImageSrc) { return this; } this._imageState = sap.m.LightBoxLoadingStates.Loading; if (oLightBox && oLightBox._oPopup.getOpenState() === sap.ui.core.OpenState.OPEN) { this._oImage.src = sImageSrc; } this.setProperty("imageSrc", sImageSrc, false); oImage.setSrc(sImageSrc); return this; }; /** * Sets the alt text of the image. * @public * @param {string} sAlt The alt text * @returns {sap.m.LightBoxItem} Pointer to the control instance for chaining. */ LightBoxItem.prototype.setAlt = function (sAlt) { var oImage = this.getAggregation("_image"); this.setProperty("alt", sAlt, false); oImage.setAlt(sAlt); return this; }; /** * Sets the title of the image. * @public * @param {string} sTitle The image title * @returns {sap.m.LightBoxItem} Pointer to the control instance for chaining. */ LightBoxItem.prototype.setTitle = function (sTitle) { var oTitle = this.getAggregation("_title"); this.setProperty("title", sTitle, false); oTitle.setText(sTitle); return this; }; /** * Sets the subtitle of the image. * @public * @param {string} sSubtitle The image subtitle * @returns {sap.m.LightBoxItem} Pointer to the control instance for chaining. */ LightBoxItem.prototype.setSubtitle = function (sSubtitle) { var oSubtitle = this.getAggregation("_subtitle"); this.setProperty("subtitle", sSubtitle, false); oSubtitle.setText(sSubtitle); return this; }; return LightBoxItem; }, /* bExport= */true);
const Util = require('../util'); const InterceptorArray = require('./interceptor-array'); const constants = require('../constants'); module.exports = class TypeBuilder { static buildDetectorMock(object) { object._handle = {}; return new Proxy(object, { get: function(target, name) { let value = target[name]; if (!name.startsWith('_')) { let cardinality = Array.isArray(value) ? constants.relationCardinality.many : constants.relationCardinality.one; target._handle = {name, cardinality}; } return value; } }); } static addProperty(classRef, propertyName, getter, setter) { Object.defineProperty(classRef.prototype, propertyName, { enumerable:true, get:getter, set:setter }); } }
'use strict'; 'format es6'; /*eslint no-unused-vars: [0] */ import routes from './ng-routes'; export default ['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { angular.forEach(Object.keys(routes), function routesRegister(stateName) { $stateProvider.state(stateName, routes[stateName]); }); }, ];
"use strict"; function merge(left, right) { return function () { left(); right(); }; } function observable(left) { left.map = function (lambda) { return observable(function (listener) { return left(function (value) { listener(lambda(value)); }); }); }; left.filter = function (lambda) { return observable(function (listener) { return left(function (value) { if (lambda(value)) { listener(value); } }); }); }; left.one = function () { return observable(function (listener) { var undo = left(function (value) { listener(value); undo(); }); return undo; }); }; left.merge = function (right) { return observable(function (listener) { return merge(left(listener), right(listener)); }); }; left.delay = function (right) { return observable(function (listener) { var values = []; return merge(left(function (value) { values.push(value); }), right(function () { values.forEach(function (value) { listener(value); }); })); }); }; left.sample = function (right) { return observable(function (listener) { var last; return merge(left(function () { listener(last); }), right(function (value) { last = value; })); }); }; left.recycle = function () { var result = observable(function (observer) { var undo = left(function (value) { observer(value); undo = result(observer); }); return function () { undo(); }; }); return result; }; left.is = function (right) { return right === observable; }; left.bind = function () { return observable(Function.prototype.bind.apply(left, arguments)); }; return left; } module.exports = observable;
'use strict'; angular.module("ngLocale", [], ["$provide", function ($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u121b\u1208\u12f6", "\u1243\u121b" ], "DAY": [ "\u12c8\u130b", "\u1233\u12ed\u1296", "\u121b\u1246\u1233\u129b", "\u12a0\u1229\u12cb", "\u1203\u1219\u1233", "\u12a0\u122d\u1263", "\u1244\u122b" ], "MONTH": [ "\u1303\u1295\u12e9\u12c8\u122a", "\u134c\u1265\u1229\u12c8\u122a", "\u121b\u122d\u127d", "\u12a4\u1355\u1228\u120d", "\u121c\u12ed", "\u1301\u1295", "\u1301\u120b\u12ed", "\u12a6\u1308\u1235\u1275", "\u1234\u1355\u1274\u121d\u1260\u122d", "\u12a6\u12ad\u1270\u12cd\u1260\u122d", "\u1296\u126c\u121d\u1260\u122d", "\u12f2\u1234\u121d\u1260\u122d" ], "SHORTDAY": [ "\u12c8\u130b", "\u1233\u12ed\u1296", "\u121b\u1246\u1233\u129b", "\u12a0\u1229\u12cb", "\u1203\u1219\u1233", "\u12a0\u122d\u1263", "\u1244\u122b" ], "SHORTMONTH": [ "\u1303\u1295\u12e9", "\u134c\u1265\u1229", "\u121b\u122d\u127d", "\u12a4\u1355\u1228", "\u121c\u12ed", "\u1301\u1295", "\u1301\u120b\u12ed", "\u12a6\u1308\u1235", "\u1234\u1355\u1274", "\u12a6\u12ad\u1270", "\u1296\u126c\u121d", "\u12f2\u1234\u121d" ], "fullDate": "EEEE\u1365 dd MMMM \u130b\u120b\u1233 y G", "longDate": "dd MMMM y", "medium": "dd-MMM-y h:mm:ss a", "mediumDate": "dd-MMM-y", "mediumTime": "h:mm:ss a", "short": "dd/MM/yy h:mm a", "shortDate": "dd/MM/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Birr", "DECIMAL_SEP": ".", "GROUP_SEP": "\u2019", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "wal", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; } }); }]);
angular.module('ngCordova.plugins', [ 'ngCordova.plugins.actionSheet', 'ngCordova.plugins.adMob', 'ngCordova.plugins.appAvailability', 'ngCordova.plugins.appRate', 'ngCordova.plugins.appVersion', 'ngCordova.plugins.backgroundGeolocation', 'ngCordova.plugins.badge', 'ngCordova.plugins.barcodeScanner', 'ngCordova.plugins.batteryStatus', 'ngCordova.plugins.ble', 'ngCordova.plugins.bluetoothSerial', 'ngCordova.plugins.brightness', 'ngCordova.plugins.calendar', 'ngCordova.plugins.camera', 'ngCordova.plugins.capture', 'ngCordova.plugins.clipboard', 'ngCordova.plugins.contacts', 'ngCordova.plugins.datePicker', 'ngCordova.plugins.device', 'ngCordova.plugins.deviceMotion', 'ngCordova.plugins.deviceOrientation', 'ngCordova.plugins.dialogs', 'ngCordova.plugins.emailComposer', 'ngCordova.plugins.facebook', 'ngCordova.plugins.facebookAds', 'ngCordova.plugins.file', 'ngCordova.plugins.fileTransfer', 'ngCordova.plugins.fileOpener2', 'ngCordova.plugins.flashlight', 'ngCordova.plugins.flurryAds', 'ngCordova.plugins.ga', 'ngCordova.plugins.geolocation', 'ngCordova.plugins.globalization', 'ngCordova.plugins.googleAds', 'ngCordova.plugins.googleAnalytics', 'ngCordova.plugins.googleMap', 'ngCordova.plugins.healthKit', 'ngCordova.plugins.httpd', 'ngCordova.plugins.iAd', 'ngCordova.plugins.imagePicker', 'ngCordova.plugins.inAppBrowser', 'ngCordova.plugins.keyboard', 'ngCordova.plugins.keychain', 'ngCordova.plugins.localNotification', 'ngCordova.plugins.media', 'ngCordova.plugins.mMediaAds', 'ngCordova.plugins.mobfoxAds', 'ngCordova.plugins.mopubAds', 'ngCordova.plugins.nativeAudio', 'ngCordova.plugins.network', 'ngCordova.plugins.oauth', 'ngCordova.plugins.oauthUtility', 'ngCordova.plugins.pinDialog', 'ngCordova.plugins.prefs', 'ngCordova.plugins.printer', 'ngCordova.plugins.progressIndicator', 'ngCordova.plugins.push', 'ngCordova.plugins.sms', 'ngCordova.plugins.socialSharing', 'ngCordova.plugins.spinnerDialog', 'ngCordova.plugins.splashscreen', 'ngCordova.plugins.sqlite', 'ngCordova.plugins.statusbar', 'ngCordova.plugins.toast', 'ngCordova.plugins.touchid', 'ngCordova.plugins.vibration', 'ngCordova.plugins.videoCapturePlus', 'ngCordova.plugins.zip', 'ngCordova.plugins.insomnia' ]);
var default_consumer = { consumer_key: 'yBSjn0E6IH5ccRcFqu5Bg', consumer_secret: 's6mmPCRVKFFz6lp6c2npBZ3tcUDPFolZX2A2Kr4kvs' }; Ripple.setupConsumer(default_consumer); var sub_consumer = { consumer_key: 'Lp3DKTAhhUwaBvEOIrAqA', consumer_secret: 'LuVB86K07thONyg8ypI4nrJm85zInHBTAPaNV93BY' }; function getViewHeight() { return lscache.get('popup_view_height') || 600; } function createPopup() { var width = 400; var height = getViewHeight(); var url = '/popup.html?new_window=true'; var size = getDefaultWindowSize(width, height); var pos = lscache.get('popup_pos') || { x: Math.round((screen.width - size.width) / 2), y: Math.round((screen.height - size.height) / 2) }; var options = { url: url, focused: true, type: 'panel', width: Math.round(size.width), height: Math.round(size.height), left: pos.x, top: pos.y }; chrome.windows.create(options); } function createXiamiPlayerPopup(id) { var size = getDefaultWindowSize(257, 33); var options = { url: 'http://www.xiami.com/widget/0_' + id + '/singlePlayer.swf', focused: true, type: 'panel', width: Math.round(size.width), height: Math.round(size.height) }; chrome.windows.create(options); } var waitFor = (function() { var waiting_list = []; var interval = 0; var lock = false; function setWaiting() { if (interval) return; interval = setInterval(function() { if (lock) return; lock = true; var not_avail = 0; for (var i = 0; i < waiting_list.length; ++i) { var item = waiting_list[i]; if (item) { if (item.checker()) { item.worker(); waiting_list[i] = null; } else { ++not_avail; } } } if (! not_avail) { interval = 0 * clearInterval(interval); } lock = false; }, 40); } return function(checker, worker) { if (checker()) return worker(); waiting_list.push({ checker: checker, worker: worker }); setWaiting(); }; })(); var getRandomNumber = (function() { var today = new Date(); var seed = today.getTime(); function rnd() { seed = (seed * 9301 + 49297) % 233280; return seed / 233280.0; } return function(number) { return Math.ceil(rnd(seed) * number); } })(); var getRelativeTime = Ripple.helpers.generateTimeFormater(function(table) { return [ [ 15 * table.s, function() { return 'Just now'; } ], [ table.m, function(convertor) { return convertor.s() + ' secs ago'; } ], [ table.h, function(convertor) { var m = convertor.m(); return m + ' min' + (m === '1' ? '' : 's') + ' ago'; } ], [ table.d, function(convertor) { var h = convertor.h(); return h + ' hr' + (h === '1' ? '' : 's') + ' ago'; } ], function(c) { return c._h(2) + ':' + c._m(2) + ', ' + c._d() + ' ' + c._MS(3); } ]; }); var getMDY = Ripple.helpers.generateTimeFormater(function(table) { return [ function(c) { return c._ms(2) + '-' + c._d(2) + '-' + c._yr(); } ]; }); var getShortTime = Ripple.helpers.generateTimeFormater(function(table) { return [ function(c) { return c._h(2) + ':' + c._m(2) + ', ' + c._d() + ' ' + c._MS(3); } ]; }); var getFullTime = Ripple.helpers.generateTimeFormater(function(table) { return [ function(c) { return c._ms(2) + '-' + c._d(2) + '-' + c._yr() + ' ' + c._h(2) + ':' + c._m(2) + ':' + c._s(2); } ]; }); function fixTweetList(tweets) { var $text = $('<div />'); tweets = tweets.filter(function(tweet) { tweet.relativeTime = getRelativeTime(tweet.created_at); var retweeted = tweet.retweeted_status; if (retweeted) { retweeted.relativeTime = getRelativeTime(retweeted.created_at); } return ! tweet.filtered_out; }); return tweets.sort(function(tweet_a, tweet_b) { return PREFiX.generateFakeId(tweet_b.id_str) - PREFiX.generateFakeId(tweet_a.id_str); }); } function filter(list, tweets) { if (! tweets.length) return tweets; var ids = { }; list.forEach(function(s) { ids[s.id_str] = true; }); return tweets.filter(function(tweet) { return ids[tweet.id_str] !== true; }); } function push(list, tweets, reverse) { tweets = filter(list, tweets); if (! tweets.length) return; tweets = fixTweetList(tweets); if (reverse) tweets = tweets.reverse(); list.push.apply(list, tweets); } function unshift(list, tweets, reverse) { tweets = filter(list, tweets); if (! tweets.length) return; tweets = fixTweetList(tweets); if (reverse) tweets = tweets.reverse(); list.unshift.apply(list, tweets); } function isImage(type) { switch (type) { case 'image/jpeg': case 'image/png': case 'image/gif': case 'image/bmp': case 'image/jpg': return true; default: return false; } } function computeSize(size) { var units = ['', 'K', 'M', 'G', 'T']; while (size / 1024 >= .75) { size = size / 1024; units.shift(); } size = Math.round(size * 10) / 10 + units[0] + 'B'; return size; } function fixTransparentPNG(file) { var d = new Deferred; var img = new Image; var fr = new FileReader; fr.onload = function(e) { img.src = fr.result; Ripple.helpers.image2canvas(img). next(function(canvas) { var ctx = canvas.getContext('2d'); var image_data = ctx.getImageData(0, 0, canvas.width, canvas.height); var pixel_array = image_data.data; var m, a, s; for (var i = 0, len = pixel_array.length; i < len; i += 4) { a = pixel_array[i+3]; if (a === 255) continue; s = 255 - a; a /= 255; m = 3; while (m--) { pixel_array[i+m] = pixel_array[i+m] * a + s; } pixel_array[i+3] = 255; } ctx.putImageData(image_data, 0, 0); canvas.toBlob(function(blob) { blob.name = file.name; d.call(blob); }); }); } fr.readAsDataURL(file); return d; } function getDefaultWindowSize(width, height) { var PREFiX = chrome.extension.getBackgroundPage().PREFiX; var ratio = +PREFiX.settings.current.zoomRatio; width = Math.round(width * ratio); height = Math.round(height * ratio); var delta_x = lscache.get('delta_x') || outerWidth - innerWidth; var delta_y = lscache.get('delta_y') || outerHeight - innerHeight; return { width: Math.round(width + delta_x), height: Math.round(height + delta_y) }; } var fixing_size = false; function initFixSize(width, height) { var PREFiX = chrome.extension.getBackgroundPage().PREFiX; var ratio = +PREFiX.settings.current.zoomRatio; var target_width = Math.round(width * ratio); var target_height = Math.round(height * ratio); onresize = _.throttle(function() { if (fixing_size) return; fixing_size = true; var size = getDefaultWindowSize(width, height); size.height = Math.max(size.height, outerHeight); resizeTo(size.width, size.height); setTimeout(function() { var _height = Math.max(innerHeight, target_height); resizeBy(target_width - innerWidth, _height - innerHeight); setTimeout(function() { lscache.set('delta_x', outerWidth - innerWidth); lscache.set('delta_y', outerHeight - innerHeight); setViewHeight(innerHeight / ratio); fixing_size = false; }, 48); }, 36); }, 24); setInterval(function() { if (innerWidth !== target_width || innerHeight < target_height) onresize(); }, 250); }
version https://git-lfs.github.com/spec/v1 oid sha256:0d3ca8a6eac7771d9fa00d7a9f68ec36a60b4f97628593d60c0c36de32907592 size 1951
const helper = require('./helper') const net = require('net') const portfinder = require('portfinder') const test = require('tape') test('TCP connect works (echo test)', function (t) { portfinder.getPort(function (err, port) { t.error(err, 'Found free port') let child const server = net.createServer() server.on('listening', function () { const env = { PORT: port } helper.browserify('tcp-connect.js', env, function (err) { t.error(err, 'Clean browserify build') child = helper.launchBrowser() }) }) let i = 0 server.on('connection', function (c) { c.on('data', function (data) { if (i === 0) { t.equal(data.toString(), 'beep', 'Got beep') c.write('boop', 'utf8') } else if (i === 1) { t.equal(data.toString(), 'pass', 'Boop was received') c.end() server.close() child.kill() t.end() } else { t.fail('TCP client sent unexpected data') } i += 1 }) }) server.listen(port) }) }) test('TCP connect works with direct API (echo test)', function (t) { portfinder.getPort(function (err, port) { t.error(err, 'Found free port') let child const server = net.createServer() server.on('listening', function () { const env = { PORT: port } helper.browserify('tcp-connect-direct.js', env, function (err) { t.error(err, 'Clean browserify build') child = helper.launchBrowser() }) }) let i = 0 server.on('connection', function (c) { c.on('data', function (data) { if (i === 0) { t.equal(data.toString(), 'beep', 'Got beep') c.write('boop', 'utf8') } else if (i === 1) { t.equal(data.toString(), 'pass', 'Boop was received') c.end() server.close() child.kill() t.end() } else { t.fail('TCP client sent unexpected data') } i += 1 }) }) server.listen(port) }) })
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("smiley","af",{options:"Lagbekkie opsies",title:"Voeg lagbekkie by",toolbar:"Lagbekkie"});
export class MessagePortTarget { constructor(sender, receiver) { this.sender = sender || []; this.receiver = receiver || []; if (!(this.sender instanceof Array)) { this.sender = [this.sender]; } if (!(this.receiver instanceof Array)) { this.receiver = [this.receiver]; } } /* @param data @param origin */ postMessage(...args) { this.sender.forEach((item) => item.postMessage(...args)); } addEventListener(type, handler) { this.receiver.forEach((item) => item.addEventListener(type, handler)); } removeEventListener(type, handler) { this.receiver.forEach((item) => item.removeEventListener(type, handler)); } } export default MessagePortTarget;