code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
//! moment.js //! version : 2.15.1 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.moment = factory() }(this, function () { 'use strict'; var hookCallback; function utils_hooks__hooks () { return hookCallback.apply(null, arguments); } // This is done to register the method called with moment() // without creating circular dependencies. function setHookCallback (callback) { hookCallback = callback; } function isArray(input) { return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; } function isObject(input) { // IE8 will treat undefined and null as object if it wasn't for // input != null return input != null && Object.prototype.toString.call(input) === '[object Object]'; } function isObjectEmpty(obj) { var k; for (k in obj) { // even if its not own property I'd still call it non-empty return false; } return true; } function isDate(input) { return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function hasOwnProp(a, b) { return Object.prototype.hasOwnProperty.call(a, b); } function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function create_utc__createUTC (input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, true).utc(); } function defaultParsingFlags() { // We need to deep clone this object. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso : false, parsedDateParts : [], meridiem : null }; } function getParsingFlags(m) { if (m._pf == null) { m._pf = defaultParsingFlags(); } return m._pf; } var some; if (Array.prototype.some) { some = Array.prototype.some; } else { some = function (fun) { var t = Object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(this, t[i], i, t)) { return true; } } return false; }; } function valid__isValid(m) { if (m._isValid == null) { var flags = getParsingFlags(m); var parsedParts = some.call(flags.parsedDateParts, function (i) { return i != null; }); var isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidMonth && !flags.invalidWeekday && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || (flags.meridiem && parsedParts)); if (m._strict) { isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined; } if (Object.isFrozen == null || !Object.isFrozen(m)) { m._isValid = isNowValid; } else { return isNowValid; } } return m._isValid; } function valid__createInvalid (flags) { var m = create_utc__createUTC(NaN); if (flags != null) { extend(getParsingFlags(m), flags); } else { getParsingFlags(m).userInvalidated = true; } return m; } function isUndefined(input) { return input === void 0; } // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. var momentProperties = utils_hooks__hooks.momentProperties = []; function copyConfig(to, from) { var i, prop, val; if (!isUndefined(from._isAMomentObject)) { to._isAMomentObject = from._isAMomentObject; } if (!isUndefined(from._i)) { to._i = from._i; } if (!isUndefined(from._f)) { to._f = from._f; } if (!isUndefined(from._l)) { to._l = from._l; } if (!isUndefined(from._strict)) { to._strict = from._strict; } if (!isUndefined(from._tzm)) { to._tzm = from._tzm; } if (!isUndefined(from._isUTC)) { to._isUTC = from._isUTC; } if (!isUndefined(from._offset)) { to._offset = from._offset; } if (!isUndefined(from._pf)) { to._pf = getParsingFlags(from); } if (!isUndefined(from._locale)) { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (!isUndefined(val)) { to[prop] = val; } } } return to; } var updateInProgress = false; // Moment prototype object function Moment(config) { copyConfig(this, config); this._d = new Date(config._d != null ? config._d.getTime() : NaN); // Prevent infinite loop in case updateOffset creates new moment // objects. if (updateInProgress === false) { updateInProgress = true; utils_hooks__hooks.updateOffset(this); updateInProgress = false; } } function isMoment (obj) { return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); } function absFloor (number) { if (number < 0) { // -0 -> 0 return Math.ceil(number) || 0; } else { return Math.floor(number); } } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { value = absFloor(coercedNumber); } return value; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function warn(msg) { if (utils_hooks__hooks.suppressDeprecationWarnings === false && (typeof console !== 'undefined') && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (utils_hooks__hooks.deprecationHandler != null) { utils_hooks__hooks.deprecationHandler(null, msg); } if (firstTime) { var args = []; var arg; for (var i = 0; i < arguments.length; i++) { arg = ''; if (typeof arguments[i] === 'object') { arg += '\n[' + i + '] '; for (var key in arguments[0]) { arg += key + ': ' + arguments[0][key] + ', '; } arg = arg.slice(0, -2); // Remove trailing comma and space } else { arg = arguments[i]; } args.push(arg); } warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); firstTime = false; } return fn.apply(this, arguments); }, fn); } var deprecations = {}; function deprecateSimple(name, msg) { if (utils_hooks__hooks.deprecationHandler != null) { utils_hooks__hooks.deprecationHandler(name, msg); } if (!deprecations[name]) { warn(msg); deprecations[name] = true; } } utils_hooks__hooks.suppressDeprecationWarnings = false; utils_hooks__hooks.deprecationHandler = null; function isFunction(input) { return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; } function locale_set__set (config) { var prop, i; for (i in config) { prop = config[i]; if (isFunction(prop)) { this[i] = prop; } else { this['_' + i] = prop; } } this._config = config; // Lenient ordinal parsing accepts just a number in addition to // number + (possibly) stuff coming from _ordinalParseLenient. this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source); } function mergeConfigs(parentConfig, childConfig) { var res = extend({}, parentConfig), prop; for (prop in childConfig) { if (hasOwnProp(childConfig, prop)) { if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { res[prop] = {}; extend(res[prop], parentConfig[prop]); extend(res[prop], childConfig[prop]); } else if (childConfig[prop] != null) { res[prop] = childConfig[prop]; } else { delete res[prop]; } } } for (prop in parentConfig) { if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) { // make sure changes to properties don't modify parent config res[prop] = extend({}, res[prop]); } } return res; } function Locale(config) { if (config != null) { this.set(config); } } var keys; if (Object.keys) { keys = Object.keys; } else { keys = function (obj) { var i, res = []; for (i in obj) { if (hasOwnProp(obj, i)) { res.push(i); } } return res; }; } var defaultCalendar = { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }; function locale_calendar__calendar (key, mom, now) { var output = this._calendar[key] || this._calendar['sameElse']; return isFunction(output) ? output.call(mom, now) : output; } var defaultLongDateFormat = { LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY h:mm A', LLLL : 'dddd, MMMM D, YYYY h:mm A' }; function longDateFormat (key) { var format = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; if (format || !formatUpper) { return format; } this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); return this._longDateFormat[key]; } var defaultInvalidDate = 'Invalid date'; function invalidDate () { return this._invalidDate; } var defaultOrdinal = '%d'; var defaultOrdinalParse = /\d{1,2}/; function ordinal (number) { return this._ordinal.replace('%d', number); } var defaultRelativeTime = { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }; function relative__relativeTime (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (isFunction(output)) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); } function pastFuture (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return isFunction(format) ? format(output) : format.replace(/%s/i, output); } var aliases = {}; function addUnitAlias (unit, shorthand) { var lowerCase = unit.toLowerCase(); aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; } function normalizeUnits(units) { return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } var priorities = {}; function addUnitPriority(unit, priority) { priorities[unit] = priority; } function getPrioritizedUnits(unitsObj) { var units = []; for (var u in unitsObj) { units.push({unit: u, priority: priorities[u]}); } units.sort(function (a, b) { return a.priority - b.priority; }); return units; } function makeGetSet (unit, keepTime) { return function (value) { if (value != null) { get_set__set(this, unit, value); utils_hooks__hooks.updateOffset(this, keepTime); return this; } else { return get_set__get(this, unit); } }; } function get_set__get (mom, unit) { return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; } function get_set__set (mom, unit, value) { if (mom.isValid()) { mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } // MOMENTS function stringGet (units) { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](); } return this; } function stringSet (units, value) { if (typeof units === 'object') { units = normalizeObjectUnits(units); var prioritized = getPrioritizedUnits(units); for (var i = 0; i < prioritized.length; i++) { this[prioritized[i].unit](units[prioritized[i].unit]); } } else { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](value); } } return this; } function zeroFill(number, targetLength, forceSign) { var absNumber = '' + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign = number >= 0; return (sign ? (forceSign ? '+' : '') : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; } var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; var formatFunctions = {}; var formatTokenFunctions = {}; // token: 'M' // padded: ['MM', 2] // ordinal: 'Mo' // callback: function () { this.month() + 1 } function addFormatToken (token, padded, ordinal, callback) { var func = callback; if (typeof callback === 'string') { func = function () { return this[callback](); }; } if (token) { formatTokenFunctions[token] = func; } if (padded) { formatTokenFunctions[padded[0]] = function () { return zeroFill(func.apply(this, arguments), padded[1], padded[2]); }; } if (ordinal) { formatTokenFunctions[ordinal] = function () { return this.localeData().ordinal(func.apply(this, arguments), token); }; } } function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = '', i; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } var match1 = /\d/; // 0 - 9 var match2 = /\d\d/; // 00 - 99 var match3 = /\d{3}/; // 000 - 999 var match4 = /\d{4}/; // 0000 - 9999 var match6 = /[+-]?\d{6}/; // -999999 - 999999 var match1to2 = /\d\d?/; // 0 - 99 var match3to4 = /\d\d\d\d?/; // 999 - 9999 var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 var match1to3 = /\d{1,3}/; // 0 - 999 var match1to4 = /\d{1,4}/; // 0 - 9999 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 var matchUnsigned = /\d+/; // 0 - inf var matchSigned = /[+-]?\d+/; // -inf - inf var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 // any word (or two) characters or numbers including two/three word month in arabic. // includes scottish gaelic two word and hyphenated months var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; var regexes = {}; function addRegexToken (token, regex, strictRegex) { regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { return (isStrict && strictRegex) ? strictRegex : regex; }; } function getParseRegexForToken (token, config) { if (!hasOwnProp(regexes, token)) { return new RegExp(unescapeFormat(token)); } return regexes[token](config._strict, config._locale); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function unescapeFormat(s) { return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; })); } function regexEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } var tokens = {}; function addParseToken (token, callback) { var i, func = callback; if (typeof token === 'string') { token = [token]; } if (typeof callback === 'number') { func = function (input, array) { array[callback] = toInt(input); }; } for (i = 0; i < token.length; i++) { tokens[token[i]] = func; } } function addWeekParseToken (token, callback) { addParseToken(token, function (input, array, config, token) { config._w = config._w || {}; callback(input, config._w, config, token); }); } function addTimeToArrayFromToken(token, input, config) { if (input != null && hasOwnProp(tokens, token)) { tokens[token](input, config._a, config, token); } } var YEAR = 0; var MONTH = 1; var DATE = 2; var HOUR = 3; var MINUTE = 4; var SECOND = 5; var MILLISECOND = 6; var WEEK = 7; var WEEKDAY = 8; var indexOf; if (Array.prototype.indexOf) { indexOf = Array.prototype.indexOf; } else { indexOf = function (o) { // I know var i; for (i = 0; i < this.length; ++i) { if (this[i] === o) { return i; } } return -1; }; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } // FORMATTING addFormatToken('M', ['MM', 2], 'Mo', function () { return this.month() + 1; }); addFormatToken('MMM', 0, 0, function (format) { return this.localeData().monthsShort(this, format); }); addFormatToken('MMMM', 0, 0, function (format) { return this.localeData().months(this, format); }); // ALIASES addUnitAlias('month', 'M'); // PRIORITY addUnitPriority('month', 8); // PARSING addRegexToken('M', match1to2); addRegexToken('MM', match1to2, match2); addRegexToken('MMM', function (isStrict, locale) { return locale.monthsShortRegex(isStrict); }); addRegexToken('MMMM', function (isStrict, locale) { return locale.monthsRegex(isStrict); }); addParseToken(['M', 'MM'], function (input, array) { array[MONTH] = toInt(input) - 1; }); addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid. if (month != null) { array[MONTH] = month; } else { getParsingFlags(config).invalidMonth = input; } }); // LOCALES var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/; var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); function localeMonths (m, format) { if (!m) { return this._months; } return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; } var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); function localeMonthsShort (m, format) { if (!m) { return this._monthsShort; } return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; } function units_month__handleStrictParse(monthName, format, strict) { var i, ii, mom, llc = monthName.toLocaleLowerCase(); if (!this._monthsParse) { // this is not used this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; for (i = 0; i < 12; ++i) { mom = create_utc__createUTC([2000, i]); this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } } } function localeMonthsParse (monthName, format, strict) { var i, mom, regex; if (this._monthsParseExact) { return units_month__handleStrictParse.call(this, monthName, format, strict); } if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } // TODO: add sorting // Sorting makes sure if one month (or abbr) is a prefix of another // see sorting in computeMonthsParse for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = create_utc__createUTC([2000, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); } if (!strict && !this._monthsParse[i]) { regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { return i; } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } } // MOMENTS function setMonth (mom, value) { var dayOfMonth; if (!mom.isValid()) { // No op return mom; } if (typeof value === 'string') { if (/^\d+$/.test(value)) { value = toInt(value); } else { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function getSetMonth (value) { if (value != null) { setMonth(this, value); utils_hooks__hooks.updateOffset(this, true); return this; } else { return get_set__get(this, 'Month'); } } function getDaysInMonth () { return daysInMonth(this.year(), this.month()); } var defaultMonthsShortRegex = matchWord; function monthsShortRegex (isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsShortStrictRegex; } else { return this._monthsShortRegex; } } else { if (!hasOwnProp(this, '_monthsShortRegex')) { this._monthsShortRegex = defaultMonthsShortRegex; } return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; } } var defaultMonthsRegex = matchWord; function monthsRegex (isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsStrictRegex; } else { return this._monthsRegex; } } else { if (!hasOwnProp(this, '_monthsRegex')) { this._monthsRegex = defaultMonthsRegex; } return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; } } function computeMonthsParse () { function cmpLenRev(a, b) { return b.length - a.length; } var shortPieces = [], longPieces = [], mixedPieces = [], i, mom; for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = create_utc__createUTC([2000, i]); shortPieces.push(this.monthsShort(mom, '')); longPieces.push(this.months(mom, '')); mixedPieces.push(this.months(mom, '')); mixedPieces.push(this.monthsShort(mom, '')); } // Sorting makes sure if one month (or abbr) is a prefix of another it // will match the longer piece. shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 12; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); } for (i = 0; i < 24; i++) { mixedPieces[i] = regexEscape(mixedPieces[i]); } this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._monthsShortRegex = this._monthsRegex; this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); } // FORMATTING addFormatToken('Y', 0, 0, function () { var y = this.year(); return y <= 9999 ? '' + y : '+' + y; }); addFormatToken(0, ['YY', 2], 0, function () { return this.year() % 100; }); addFormatToken(0, ['YYYY', 4], 0, 'year'); addFormatToken(0, ['YYYYY', 5], 0, 'year'); addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES addUnitAlias('year', 'y'); // PRIORITIES addUnitPriority('year', 1); // PARSING addRegexToken('Y', matchSigned); addRegexToken('YY', match1to2, match2); addRegexToken('YYYY', match1to4, match4); addRegexToken('YYYYY', match1to6, match6); addRegexToken('YYYYYY', match1to6, match6); addParseToken(['YYYYY', 'YYYYYY'], YEAR); addParseToken('YYYY', function (input, array) { array[YEAR] = input.length === 2 ? utils_hooks__hooks.parseTwoDigitYear(input) : toInt(input); }); addParseToken('YY', function (input, array) { array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input); }); addParseToken('Y', function (input, array) { array[YEAR] = parseInt(input, 10); }); // HELPERS function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } // HOOKS utils_hooks__hooks.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; // MOMENTS var getSetYear = makeGetSet('FullYear', true); function getIsLeapYear () { return isLeapYear(this.year()); } function createDate (y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getFullYear())) { date.setFullYear(y); } return date; } function createUTCDate (y) { var date = new Date(Date.UTC.apply(null, arguments)); //the Date.UTC function remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) { date.setUTCFullYear(y); } return date; } // start-of-first-week - start-of-year function firstWeekOffset(year, dow, doy) { var // first-week day -- which january is always in the first week (4 for iso, 1 for other) fwd = 7 + dow - doy, // first-week day local weekday -- which local weekday is fwd fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; return -fwdlw + fwd - 1; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, dow, doy) { var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; if (dayOfYear <= 0) { resYear = year - 1; resDayOfYear = daysInYear(resYear) + dayOfYear; } else if (dayOfYear > daysInYear(year)) { resYear = year + 1; resDayOfYear = dayOfYear - daysInYear(year); } else { resYear = year; resDayOfYear = dayOfYear; } return { year: resYear, dayOfYear: resDayOfYear }; } function weekOfYear(mom, dow, doy) { var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; if (week < 1) { resYear = mom.year() - 1; resWeek = week + weeksInYear(resYear, dow, doy); } else if (week > weeksInYear(mom.year(), dow, doy)) { resWeek = week - weeksInYear(mom.year(), dow, doy); resYear = mom.year() + 1; } else { resYear = mom.year(); resWeek = week; } return { week: resWeek, year: resYear }; } function weeksInYear(year, dow, doy) { var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; } // FORMATTING addFormatToken('w', ['ww', 2], 'wo', 'week'); addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES addUnitAlias('week', 'w'); addUnitAlias('isoWeek', 'W'); // PRIORITIES addUnitPriority('week', 5); addUnitPriority('isoWeek', 5); // PARSING addRegexToken('w', match1to2); addRegexToken('ww', match1to2, match2); addRegexToken('W', match1to2); addRegexToken('WW', match1to2, match2); addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { week[token.substr(0, 1)] = toInt(input); }); // HELPERS // LOCALES function localeWeek (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; } var defaultLocaleWeek = { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }; function localeFirstDayOfWeek () { return this._week.dow; } function localeFirstDayOfYear () { return this._week.doy; } // MOMENTS function getSetWeek (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); } function getSetISOWeek (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); } // FORMATTING addFormatToken('d', 0, 'do', 'day'); addFormatToken('dd', 0, 0, function (format) { return this.localeData().weekdaysMin(this, format); }); addFormatToken('ddd', 0, 0, function (format) { return this.localeData().weekdaysShort(this, format); }); addFormatToken('dddd', 0, 0, function (format) { return this.localeData().weekdays(this, format); }); addFormatToken('e', 0, 0, 'weekday'); addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES addUnitAlias('day', 'd'); addUnitAlias('weekday', 'e'); addUnitAlias('isoWeekday', 'E'); // PRIORITY addUnitPriority('day', 11); addUnitPriority('weekday', 11); addUnitPriority('isoWeekday', 11); // PARSING addRegexToken('d', match1to2); addRegexToken('e', match1to2); addRegexToken('E', match1to2); addRegexToken('dd', function (isStrict, locale) { return locale.weekdaysMinRegex(isStrict); }); addRegexToken('ddd', function (isStrict, locale) { return locale.weekdaysShortRegex(isStrict); }); addRegexToken('dddd', function (isStrict, locale) { return locale.weekdaysRegex(isStrict); }); addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { week.d = weekday; } else { getParsingFlags(config).invalidWeekday = input; } }); addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { if (typeof input !== 'string') { return input; } if (!isNaN(input)) { return parseInt(input, 10); } input = locale.weekdaysParse(input); if (typeof input === 'number') { return input; } return null; } function parseIsoWeekday(input, locale) { if (typeof input === 'string') { return locale.weekdaysParse(input) % 7 || 7; } return isNaN(input) ? null : input; } // LOCALES var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); function localeWeekdays (m, format) { if (!m) { return this._weekdays; } return isArray(this._weekdays) ? this._weekdays[m.day()] : this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; } var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); function localeWeekdaysShort (m) { return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; } var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); function localeWeekdaysMin (m) { return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; } function day_of_week__handleStrictParse(weekdayName, format, strict) { var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); if (!this._weekdaysParse) { this._weekdaysParse = []; this._shortWeekdaysParse = []; this._minWeekdaysParse = []; for (i = 0; i < 7; ++i) { mom = create_utc__createUTC([2000, 1]).day(i); this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } } } function localeWeekdaysParse (weekdayName, format, strict) { var i, mom, regex; if (this._weekdaysParseExact) { return day_of_week__handleStrictParse.call(this, weekdayName, format, strict); } if (!this._weekdaysParse) { this._weekdaysParse = []; this._minWeekdaysParse = []; this._shortWeekdaysParse = []; this._fullWeekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = create_utc__createUTC([2000, 1]).day(i); if (strict && !this._fullWeekdaysParse[i]) { this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i'); this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i'); this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i'); } if (!this._weekdaysParse[i]) { regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { return i; } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { return i; } } } // MOMENTS function getSetDayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } } function getSetLocaleDayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); } function getSetISODayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. if (input != null) { var weekday = parseIsoWeekday(input, this.localeData()); return this.day(this.day() % 7 ? weekday : weekday - 7); } else { return this.day() || 7; } } var defaultWeekdaysRegex = matchWord; function weekdaysRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysStrictRegex; } else { return this._weekdaysRegex; } } else { if (!hasOwnProp(this, '_weekdaysRegex')) { this._weekdaysRegex = defaultWeekdaysRegex; } return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } } var defaultWeekdaysShortRegex = matchWord; function weekdaysShortRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysShortStrictRegex; } else { return this._weekdaysShortRegex; } } else { if (!hasOwnProp(this, '_weekdaysShortRegex')) { this._weekdaysShortRegex = defaultWeekdaysShortRegex; } return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } } var defaultWeekdaysMinRegex = matchWord; function weekdaysMinRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysMinStrictRegex; } else { return this._weekdaysMinRegex; } } else { if (!hasOwnProp(this, '_weekdaysMinRegex')) { this._weekdaysMinRegex = defaultWeekdaysMinRegex; } return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } } function computeWeekdaysParse () { function cmpLenRev(a, b) { return b.length - a.length; } var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = create_utc__createUTC([2000, 1]).day(i); minp = this.weekdaysMin(mom, ''); shortp = this.weekdaysShort(mom, ''); longp = this.weekdays(mom, ''); minPieces.push(minp); shortPieces.push(shortp); longPieces.push(longp); mixedPieces.push(minp); mixedPieces.push(shortp); mixedPieces.push(longp); } // Sorting makes sure if one weekday (or abbr) is a prefix of another it // will match the longer piece. minPieces.sort(cmpLenRev); shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 7; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); mixedPieces[i] = regexEscape(mixedPieces[i]); } this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._weekdaysShortRegex = this._weekdaysRegex; this._weekdaysMinRegex = this._weekdaysRegex; this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); } // FORMATTING function hFormat() { return this.hours() % 12 || 12; } function kFormat() { return this.hours() || 24; } addFormatToken('H', ['HH', 2], 0, 'hour'); addFormatToken('h', ['hh', 2], 0, hFormat); addFormatToken('k', ['kk', 2], 0, kFormat); addFormatToken('hmm', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); }); addFormatToken('hmmss', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); addFormatToken('Hmm', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2); }); addFormatToken('Hmmss', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); function meridiem (token, lowercase) { addFormatToken(token, 0, 0, function () { return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); }); } meridiem('a', true); meridiem('A', false); // ALIASES addUnitAlias('hour', 'h'); // PRIORITY addUnitPriority('hour', 13); // PARSING function matchMeridiem (isStrict, locale) { return locale._meridiemParse; } addRegexToken('a', matchMeridiem); addRegexToken('A', matchMeridiem); addRegexToken('H', match1to2); addRegexToken('h', match1to2); addRegexToken('HH', match1to2, match2); addRegexToken('hh', match1to2, match2); addRegexToken('hmm', match3to4); addRegexToken('hmmss', match5to6); addRegexToken('Hmm', match3to4); addRegexToken('Hmmss', match5to6); addParseToken(['H', 'HH'], HOUR); addParseToken(['a', 'A'], function (input, array, config) { config._isPm = config._locale.isPM(input); config._meridiem = input; }); addParseToken(['h', 'hh'], function (input, array, config) { array[HOUR] = toInt(input); getParsingFlags(config).bigHour = true; }); addParseToken('hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); getParsingFlags(config).bigHour = true; }); addParseToken('hmmss', function (input, array, config) { var pos1 = input.length - 4; var pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); getParsingFlags(config).bigHour = true; }); addParseToken('Hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); }); addParseToken('Hmmss', function (input, array, config) { var pos1 = input.length - 4; var pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); }); // LOCALES function localeIsPM (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); } var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; function localeMeridiem (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } } // MOMENTS // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. var getSetHour = makeGetSet('Hours', true); var baseConfig = { calendar: defaultCalendar, longDateFormat: defaultLongDateFormat, invalidDate: defaultInvalidDate, ordinal: defaultOrdinal, ordinalParse: defaultOrdinalParse, relativeTime: defaultRelativeTime, months: defaultLocaleMonths, monthsShort: defaultLocaleMonthsShort, week: defaultLocaleWeek, weekdays: defaultLocaleWeekdays, weekdaysMin: defaultLocaleWeekdaysMin, weekdaysShort: defaultLocaleWeekdaysShort, meridiemParse: defaultLocaleMeridiemParse }; // internal storage for locale config files var locales = {}; var globalLocale; function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; // TODO: Find a better way to register and load all the locales in Node if (!locales[name] && (typeof module !== 'undefined') && module && module.exports) { try { oldLocale = globalLocale._abbr; require('./locale/' + name); // because defineLocale currently also sets the global locale, we // want to undo that for lazy loaded locales locale_locales__getSetGlobalLocale(oldLocale); } catch (e) { } } return locales[name]; } // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. function locale_locales__getSetGlobalLocale (key, values) { var data; if (key) { if (isUndefined(values)) { data = locale_locales__getLocale(key); } else { data = defineLocale(key, values); } if (data) { // moment.duration._locale = moment._locale = data; globalLocale = data; } } return globalLocale._abbr; } function defineLocale (name, config) { if (config !== null) { var parentConfig = baseConfig; config.abbr = name; if (locales[name] != null) { deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); parentConfig = locales[name]._config; } else if (config.parentLocale != null) { if (locales[config.parentLocale] != null) { parentConfig = locales[config.parentLocale]._config; } else { // treat as if there is no base config deprecateSimple('parentLocaleUndefined', 'specified parentLocale is not defined yet. See http://momentjs.com/guides/#/warnings/parent-locale/'); } } locales[name] = new Locale(mergeConfigs(parentConfig, config)); // backwards compat for now: also set the locale locale_locales__getSetGlobalLocale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } } function updateLocale(name, config) { if (config != null) { var locale, parentConfig = baseConfig; // MERGE if (locales[name] != null) { parentConfig = locales[name]._config; } config = mergeConfigs(parentConfig, config); locale = new Locale(config); locale.parentLocale = locales[name]; locales[name] = locale; // backwards compat for now: also set the locale locale_locales__getSetGlobalLocale(name); } else { // pass null for config to unupdate, useful for tests if (locales[name] != null) { if (locales[name].parentLocale != null) { locales[name] = locales[name].parentLocale; } else if (locales[name] != null) { delete locales[name]; } } } return locales[name]; } // returns locale data function locale_locales__getLocale (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); } function locale_locales__listLocales() { return keys(locales); } function checkOverflow (m) { var overflow; var a = m._a; if (a && getParsingFlags(m).overflow === -2) { overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } if (getParsingFlags(m)._overflowWeeks && overflow === -1) { overflow = WEEK; } if (getParsingFlags(m)._overflowWeekday && overflow === -1) { overflow = WEEKDAY; } getParsingFlags(m).overflow = overflow; } return m; } // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/; var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/; var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; var isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], // YYYYMM is NOT allowed by the standard ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/] ]; // iso time formats and regexes var isoTimes = [ ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/] ]; var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; // date from iso format function configFromISO(config) { var i, l, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat; if (match) { getParsingFlags(config).iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(match[1])) { dateFormat = isoDates[i][0]; allowTime = isoDates[i][2] !== false; break; } } if (dateFormat == null) { config._isValid = false; return; } if (match[3]) { for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(match[3])) { // match[2] should be 'T' or space timeFormat = (match[2] || ' ') + isoTimes[i][0]; break; } } if (timeFormat == null) { config._isValid = false; return; } } if (!allowTime && timeFormat != null) { config._isValid = false; return; } if (match[4]) { if (tzRegex.exec(match[4])) { tzFormat = 'Z'; } else { config._isValid = false; return; } } config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); configFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function configFromString(config) { var matched = aspNetJsonRegex.exec(config._i); if (matched !== null) { config._d = new Date(+matched[1]); return; } configFromISO(config); if (config._isValid === false) { delete config._isValid; utils_hooks__hooks.createFromInputFallback(config); } } utils_hooks__hooks.createFromInputFallback = deprecate( 'value provided is not in a recognized ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non ISO date formats are ' + 'discouraged and will be removed in an upcoming major release. Please refer to ' + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) { config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); } ); // Pick the first defined of two or three arguments. function defaults(a, b, c) { if (a != null) { return a; } if (b != null) { return b; } return c; } function currentDateArray(config) { // hooks is actually the exported moment object var nowValue = new Date(utils_hooks__hooks.now()); if (config._useUTC) { return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; } return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function configFromArray (config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { getParsingFlags(config)._overflowDayOfYear = true; } date = createUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // Check for 24:00:00.000 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); // Apply timezone offset from input. The actual utcOffset can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year); week = defaults(w.W, 1); weekday = defaults(w.E, 1); if (weekday < 1 || weekday > 7) { weekdayOverflow = true; } } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year); week = defaults(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < 0 || weekday > 6) { weekdayOverflow = true; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; if (w.e < 0 || w.e > 6) { weekdayOverflow = true; } } else { // default to begining of week weekday = dow; } } if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { getParsingFlags(config)._overflowWeeks = true; } else if (weekdayOverflow != null) { getParsingFlags(config)._overflowWeekday = true; } else { temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } } // constant that refers to the ISO standard utils_hooks__hooks.ISO_8601 = function () {}; // date from string and format string function configFromStringAndFormat(config) { // TODO: Move this to another part of the creation flow to prevent circular deps if (config._f === utils_hooks__hooks.ISO_8601) { configFromISO(config); return; } config._a = []; getParsingFlags(config).empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; // console.log('token', token, 'parsedInput', parsedInput, // 'regex', getParseRegexForToken(token, config)); if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { getParsingFlags(config).unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { getParsingFlags(config).empty = false; } else { getParsingFlags(config).unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { getParsingFlags(config).unusedTokens.push(token); } } // add remaining unparsed input length to the string getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { getParsingFlags(config).unusedInput.push(string); } // clear _12h flag if hour is <= 12 if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) { getParsingFlags(config).bigHour = undefined; } getParsingFlags(config).parsedDateParts = config._a.slice(0); getParsingFlags(config).meridiem = config._meridiem; // handle meridiem config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); configFromArray(config); checkOverflow(config); } function meridiemFixWrap (locale, hour, meridiem) { var isPm; if (meridiem == null) { // nothing to do return hour; } if (locale.meridiemHour != null) { return locale.meridiemHour(hour, meridiem); } else if (locale.isPM != null) { // Fallback isPm = locale.isPM(meridiem); if (isPm && hour < 12) { hour += 12; } if (!isPm && hour === 12) { hour = 0; } return hour; } else { // this is not supposed to happen return hour; } } // date from string and array of format strings function configFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { getParsingFlags(config).invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._f = config._f[i]; configFromStringAndFormat(tempConfig); if (!valid__isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += getParsingFlags(tempConfig).charsLeftOver; //or tokens currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; getParsingFlags(tempConfig).score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } function configFromObject(config) { if (config._d) { return; } var i = normalizeObjectUnits(config._i); config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { return obj && parseInt(obj, 10); }); configFromArray(config); } function createFromConfig (config) { var res = new Moment(checkOverflow(prepareConfig(config))); if (res._nextDay) { // Adding is smart enough around DST res.add(1, 'd'); res._nextDay = undefined; } return res; } function prepareConfig (config) { var input = config._i, format = config._f; config._locale = config._locale || locale_locales__getLocale(config._l); if (input === null || (format === undefined && input === '')) { return valid__createInvalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (isMoment(input)) { return new Moment(checkOverflow(input)); } else if (isArray(format)) { configFromStringAndArray(config); } else if (isDate(input)) { config._d = input; } else if (format) { configFromStringAndFormat(config); } else { configFromInput(config); } if (!valid__isValid(config)) { config._d = null; } return config; } function configFromInput(config) { var input = config._i; if (input === undefined) { config._d = new Date(utils_hooks__hooks.now()); } else if (isDate(input)) { config._d = new Date(input.valueOf()); } else if (typeof input === 'string') { configFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); configFromArray(config); } else if (typeof(input) === 'object') { configFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { utils_hooks__hooks.createFromInputFallback(config); } } function createLocalOrUTC (input, format, locale, strict, isUTC) { var c = {}; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } if ((isObject(input) && isObjectEmpty(input)) || (isArray(input) && input.length === 0)) { input = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c._isAMomentObject = true; c._useUTC = c._isUTC = isUTC; c._l = locale; c._i = input; c._f = format; c._strict = strict; return createFromConfig(c); } function local__createLocal (input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, false); } var prototypeMin = deprecate( 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = local__createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other < this ? this : other; } else { return valid__createInvalid(); } } ); var prototypeMax = deprecate( 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = local__createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other > this ? this : other; } else { return valid__createInvalid(); } } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return local__createLocal(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (!moments[i].isValid() || moments[i][fn](res)) { res = moments[i]; } } return res; } // TODO: Use [].sort instead? function min () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); } function max () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); } var now = function () { return Date.now ? Date.now() : +(new Date()); }; function Duration (duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = locale_locales__getLocale(); this._bubble(); } function isDuration (obj) { return obj instanceof Duration; } function absRound (number) { if (number < 0) { return Math.round(-1 * number) * -1; } else { return Math.round(number); } } // FORMATTING function offset (token, separator) { addFormatToken(token, 0, 0, function () { var offset = this.utcOffset(); var sign = '+'; if (offset < 0) { offset = -offset; sign = '-'; } return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); }); } offset('Z', ':'); offset('ZZ', ''); // PARSING addRegexToken('Z', matchShortOffset); addRegexToken('ZZ', matchShortOffset); addParseToken(['Z', 'ZZ'], function (input, array, config) { config._useUTC = true; config._tzm = offsetFromString(matchShortOffset, input); }); // HELPERS // timezone chunker // '+10:00' > ['10', '00'] // '-1530' > ['-15', '30'] var chunkOffset = /([\+\-]|\d\d)/gi; function offsetFromString(matcher, string) { var matches = ((string || '').match(matcher) || []); var chunk = matches[matches.length - 1] || []; var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; var minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? minutes : -minutes; } // Return a moment from input, that is local/utc/zone equivalent to model. function cloneWithOffset(input, model) { var res, diff; if (model._isUTC) { res = model.clone(); diff = (isMoment(input) || isDate(input) ? input.valueOf() : local__createLocal(input).valueOf()) - res.valueOf(); // Use low-level api, because this fn is low-level api. res._d.setTime(res._d.valueOf() + diff); utils_hooks__hooks.updateOffset(res, false); return res; } else { return local__createLocal(input).local(); } } function getDateOffset (m) { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return -Math.round(m._d.getTimezoneOffset() / 15) * 15; } // HOOKS // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. utils_hooks__hooks.updateOffset = function () {}; // MOMENTS // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. function getSetOffset (input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (!this.isValid()) { return input != null ? this : NaN; } if (input != null) { if (typeof input === 'string') { input = offsetFromString(matchShortOffset, input); } else if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = getDateOffset(this); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.add(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; utils_hooks__hooks.updateOffset(this, true); this._changeInProgress = null; } } return this; } else { return this._isUTC ? offset : getDateOffset(this); } } function getSetZone (input, keepLocalTime) { if (input != null) { if (typeof input !== 'string') { input = -input; } this.utcOffset(input, keepLocalTime); return this; } else { return -this.utcOffset(); } } function setOffsetToUTC (keepLocalTime) { return this.utcOffset(0, keepLocalTime); } function setOffsetToLocal (keepLocalTime) { if (this._isUTC) { this.utcOffset(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.subtract(getDateOffset(this), 'm'); } } return this; } function setOffsetToParsedOffset () { if (this._tzm) { this.utcOffset(this._tzm); } else if (typeof this._i === 'string') { var tZone = offsetFromString(matchOffset, this._i); if (tZone === 0) { this.utcOffset(0, true); } else { this.utcOffset(offsetFromString(matchOffset, this._i)); } } return this; } function hasAlignedHourOffset (input) { if (!this.isValid()) { return false; } input = input ? local__createLocal(input).utcOffset() : 0; return (this.utcOffset() - input) % 60 === 0; } function isDaylightSavingTime () { return ( this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset() ); } function isDaylightSavingTimeShifted () { if (!isUndefined(this._isDSTShifted)) { return this._isDSTShifted; } var c = {}; copyConfig(c, this); c = prepareConfig(c); if (c._a) { var other = c._isUTC ? create_utc__createUTC(c._a) : local__createLocal(c._a); this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; } else { this._isDSTShifted = false; } return this._isDSTShifted; } function isLocal () { return this.isValid() ? !this._isUTC : false; } function isUtcOffset () { return this.isValid() ? this._isUTC : false; } function isUtc () { return this.isValid() ? this._isUTC && this._offset === 0 : false; } // ASP.NET json date format regex var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere // and further modified to allow for strings containing both week and day var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/; function create__createDuration (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, diffRes; if (isDuration(input)) { duration = { ms : input._milliseconds, d : input._days, M : input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : 0, d : toInt(match[DATE]) * sign, h : toInt(match[HOUR]) * sign, m : toInt(match[MINUTE]) * sign, s : toInt(match[SECOND]) * sign, ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match }; } else if (!!(match = isoRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : parseIso(match[2], sign), M : parseIso(match[3], sign), w : parseIso(match[4], sign), d : parseIso(match[5], sign), h : parseIso(match[6], sign), m : parseIso(match[7], sign), s : parseIso(match[8], sign) }; } else if (duration == null) {// checks for null or undefined duration = {}; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; } create__createDuration.fn = Duration.prototype; function parseIso (inp, sign) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; if (!(base.isValid() && other.isValid())) { return {milliseconds: 0, months: 0}; } other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = create__createDuration(val, period); add_subtract__addSubtract(this, dur, direction); return this; }; } function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = absRound(duration._days), months = absRound(duration._months); if (!mom.isValid()) { // No op return; } updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); } if (days) { get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding); } if (months) { setMonth(mom, get_set__get(mom, 'Month') + months * isAdding); } if (updateOffset) { utils_hooks__hooks.updateOffset(mom, days || months); } } var add_subtract__add = createAdder(1, 'add'); var add_subtract__subtract = createAdder(-1, 'subtract'); function getCalendarFormat(myMoment, now) { var diff = myMoment.diff(now, 'days', true); return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; } function moment_calendar__calendar (time, formats) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're local/utc/offset or not. var now = time || local__createLocal(), sod = cloneWithOffset(now, this).startOf('day'), format = utils_hooks__hooks.calendarFormat(this, sod) || 'sameElse'; var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); return this.format(output || this.localeData().calendar(format, this, local__createLocal(now))); } function clone () { return new Moment(this); } function isAfter (input, units) { var localInput = isMoment(input) ? input : local__createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); if (units === 'millisecond') { return this.valueOf() > localInput.valueOf(); } else { return localInput.valueOf() < this.clone().startOf(units).valueOf(); } } function isBefore (input, units) { var localInput = isMoment(input) ? input : local__createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); if (units === 'millisecond') { return this.valueOf() < localInput.valueOf(); } else { return this.clone().endOf(units).valueOf() < localInput.valueOf(); } } function isBetween (from, to, units, inclusivity) { inclusivity = inclusivity || '()'; return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) && (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units)); } function isSame (input, units) { var localInput = isMoment(input) ? input : local__createLocal(input), inputMs; if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units || 'millisecond'); if (units === 'millisecond') { return this.valueOf() === localInput.valueOf(); } else { inputMs = localInput.valueOf(); return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); } } function isSameOrAfter (input, units) { return this.isSame(input, units) || this.isAfter(input,units); } function isSameOrBefore (input, units) { return this.isSame(input, units) || this.isBefore(input,units); } function diff (input, units, asFloat) { var that, zoneDelta, delta, output; if (!this.isValid()) { return NaN; } that = cloneWithOffset(input, this); if (!that.isValid()) { return NaN; } zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; units = normalizeUnits(units); if (units === 'year' || units === 'month' || units === 'quarter') { output = monthDiff(this, that); if (units === 'quarter') { output = output / 3; } else if (units === 'year') { output = output / 12; } } else { delta = this - that; output = units === 'second' ? delta / 1e3 : // 1000 units === 'minute' ? delta / 6e4 : // 1000 * 60 units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst delta; } return asFloat ? output : absFloor(output); } function monthDiff (a, b) { // difference in months var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month) anchor = a.clone().add(wholeMonthDiff, 'months'), anchor2, adjust; if (b - anchor < 0) { anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor - anchor2); } else { anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor2 - anchor); } //check for negative zero, return zero if negative zero return -(wholeMonthDiff + adjust) || 0; } utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; utils_hooks__hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; function toString () { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } function moment_format__toISOString () { var m = this.clone().utc(); if (0 < m.year() && m.year() <= 9999) { if (isFunction(Date.prototype.toISOString)) { // native implementation is ~50x faster, use it when we can return this.toDate().toISOString(); } else { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } } function format (inputString) { if (!inputString) { inputString = this.isUtc() ? utils_hooks__hooks.defaultFormatUtc : utils_hooks__hooks.defaultFormat; } var output = formatMoment(this, inputString); return this.localeData().postformat(output); } function from (time, withoutSuffix) { if (this.isValid() && ((isMoment(time) && time.isValid()) || local__createLocal(time).isValid())) { return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function fromNow (withoutSuffix) { return this.from(local__createLocal(), withoutSuffix); } function to (time, withoutSuffix) { if (this.isValid() && ((isMoment(time) && time.isValid()) || local__createLocal(time).isValid())) { return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function toNow (withoutSuffix) { return this.to(local__createLocal(), withoutSuffix); } // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. function locale (key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = locale_locales__getLocale(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } } var lang = deprecate( 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ); function localeData () { return this._locale; } function startOf (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': case 'date': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); } // weeks are a special case if (units === 'week') { this.weekday(0); } if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; } function endOf (units) { units = normalizeUnits(units); if (units === undefined || units === 'millisecond') { return this; } // 'date' is an alias for 'day', so it should be considered as such. if (units === 'date') { units = 'day'; } return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); } function to_type__valueOf () { return this._d.valueOf() - ((this._offset || 0) * 60000); } function unix () { return Math.floor(this.valueOf() / 1000); } function toDate () { return new Date(this.valueOf()); } function toArray () { var m = this; return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; } function toObject () { var m = this; return { years: m.year(), months: m.month(), date: m.date(), hours: m.hours(), minutes: m.minutes(), seconds: m.seconds(), milliseconds: m.milliseconds() }; } function toJSON () { // new Date(NaN).toJSON() === null return this.isValid() ? this.toISOString() : null; } function moment_valid__isValid () { return valid__isValid(this); } function parsingFlags () { return extend({}, getParsingFlags(this)); } function invalidAt () { return getParsingFlags(this).overflow; } function creationData() { return { input: this._i, format: this._f, locale: this._locale, isUTC: this._isUTC, strict: this._strict }; } // FORMATTING addFormatToken(0, ['gg', 2], 0, function () { return this.weekYear() % 100; }); addFormatToken(0, ['GG', 2], 0, function () { return this.isoWeekYear() % 100; }); function addWeekYearFormatToken (token, getter) { addFormatToken(0, [token, token.length], 0, getter); } addWeekYearFormatToken('gggg', 'weekYear'); addWeekYearFormatToken('ggggg', 'weekYear'); addWeekYearFormatToken('GGGG', 'isoWeekYear'); addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES addUnitAlias('weekYear', 'gg'); addUnitAlias('isoWeekYear', 'GG'); // PRIORITY addUnitPriority('weekYear', 1); addUnitPriority('isoWeekYear', 1); // PARSING addRegexToken('G', matchSigned); addRegexToken('g', matchSigned); addRegexToken('GG', match1to2, match2); addRegexToken('gg', match1to2, match2); addRegexToken('GGGG', match1to4, match4); addRegexToken('gggg', match1to4, match4); addRegexToken('GGGGG', match1to6, match6); addRegexToken('ggggg', match1to6, match6); addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { week[token.substr(0, 2)] = toInt(input); }); addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { week[token] = utils_hooks__hooks.parseTwoDigitYear(input); }); // MOMENTS function getSetWeekYear (input) { return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy); } function getSetISOWeekYear (input) { return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4); } function getISOWeeksInYear () { return weeksInYear(this.year(), 1, 4); } function getWeeksInYear () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } function getSetWeekYearHelper(input, week, weekday, dow, doy) { var weeksTarget; if (input == null) { return weekOfYear(this, dow, doy).year; } else { weeksTarget = weeksInYear(input, dow, doy); if (week > weeksTarget) { week = weeksTarget; } return setWeekAll.call(this, input, week, weekday, dow, doy); } } function setWeekAll(weekYear, week, weekday, dow, doy) { var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); this.year(date.getUTCFullYear()); this.month(date.getUTCMonth()); this.date(date.getUTCDate()); return this; } // FORMATTING addFormatToken('Q', 0, 'Qo', 'quarter'); // ALIASES addUnitAlias('quarter', 'Q'); // PRIORITY addUnitPriority('quarter', 7); // PARSING addRegexToken('Q', match1); addParseToken('Q', function (input, array) { array[MONTH] = (toInt(input) - 1) * 3; }); // MOMENTS function getSetQuarter (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); } // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIOROITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { return isStrict ? locale._ordinalParse : locale._ordinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0], 10); }); // MOMENTS var getSetDayOfMonth = makeGetSet('Date', true); // FORMATTING addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES addUnitAlias('dayOfYear', 'DDD'); // PRIORITY addUnitPriority('dayOfYear', 4); // PARSING addRegexToken('DDD', match1to3); addRegexToken('DDDD', match3); addParseToken(['DDD', 'DDDD'], function (input, array, config) { config._dayOfYear = toInt(input); }); // HELPERS // MOMENTS function getSetDayOfYear (input) { var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); } // FORMATTING addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES addUnitAlias('minute', 'm'); // PRIORITY addUnitPriority('minute', 14); // PARSING addRegexToken('m', match1to2); addRegexToken('mm', match1to2, match2); addParseToken(['m', 'mm'], MINUTE); // MOMENTS var getSetMinute = makeGetSet('Minutes', false); // FORMATTING addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES addUnitAlias('second', 's'); // PRIORITY addUnitPriority('second', 15); // PARSING addRegexToken('s', match1to2); addRegexToken('ss', match1to2, match2); addParseToken(['s', 'ss'], SECOND); // MOMENTS var getSetSecond = makeGetSet('Seconds', false); // FORMATTING addFormatToken('S', 0, 0, function () { return ~~(this.millisecond() / 100); }); addFormatToken(0, ['SS', 2], 0, function () { return ~~(this.millisecond() / 10); }); addFormatToken(0, ['SSS', 3], 0, 'millisecond'); addFormatToken(0, ['SSSS', 4], 0, function () { return this.millisecond() * 10; }); addFormatToken(0, ['SSSSS', 5], 0, function () { return this.millisecond() * 100; }); addFormatToken(0, ['SSSSSS', 6], 0, function () { return this.millisecond() * 1000; }); addFormatToken(0, ['SSSSSSS', 7], 0, function () { return this.millisecond() * 10000; }); addFormatToken(0, ['SSSSSSSS', 8], 0, function () { return this.millisecond() * 100000; }); addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { return this.millisecond() * 1000000; }); // ALIASES addUnitAlias('millisecond', 'ms'); // PRIORITY addUnitPriority('millisecond', 16); // PARSING addRegexToken('S', match1to3, match1); addRegexToken('SS', match1to3, match2); addRegexToken('SSS', match1to3, match3); var token; for (token = 'SSSS'; token.length <= 9; token += 'S') { addRegexToken(token, matchUnsigned); } function parseMs(input, array) { array[MILLISECOND] = toInt(('0.' + input) * 1000); } for (token = 'S'; token.length <= 9; token += 'S') { addParseToken(token, parseMs); } // MOMENTS var getSetMillisecond = makeGetSet('Milliseconds', false); // FORMATTING addFormatToken('z', 0, 0, 'zoneAbbr'); addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS function getZoneAbbr () { return this._isUTC ? 'UTC' : ''; } function getZoneName () { return this._isUTC ? 'Coordinated Universal Time' : ''; } var momentPrototype__proto = Moment.prototype; momentPrototype__proto.add = add_subtract__add; momentPrototype__proto.calendar = moment_calendar__calendar; momentPrototype__proto.clone = clone; momentPrototype__proto.diff = diff; momentPrototype__proto.endOf = endOf; momentPrototype__proto.format = format; momentPrototype__proto.from = from; momentPrototype__proto.fromNow = fromNow; momentPrototype__proto.to = to; momentPrototype__proto.toNow = toNow; momentPrototype__proto.get = stringGet; momentPrototype__proto.invalidAt = invalidAt; momentPrototype__proto.isAfter = isAfter; momentPrototype__proto.isBefore = isBefore; momentPrototype__proto.isBetween = isBetween; momentPrototype__proto.isSame = isSame; momentPrototype__proto.isSameOrAfter = isSameOrAfter; momentPrototype__proto.isSameOrBefore = isSameOrBefore; momentPrototype__proto.isValid = moment_valid__isValid; momentPrototype__proto.lang = lang; momentPrototype__proto.locale = locale; momentPrototype__proto.localeData = localeData; momentPrototype__proto.max = prototypeMax; momentPrototype__proto.min = prototypeMin; momentPrototype__proto.parsingFlags = parsingFlags; momentPrototype__proto.set = stringSet; momentPrototype__proto.startOf = startOf; momentPrototype__proto.subtract = add_subtract__subtract; momentPrototype__proto.toArray = toArray; momentPrototype__proto.toObject = toObject; momentPrototype__proto.toDate = toDate; momentPrototype__proto.toISOString = moment_format__toISOString; momentPrototype__proto.toJSON = toJSON; momentPrototype__proto.toString = toString; momentPrototype__proto.unix = unix; momentPrototype__proto.valueOf = to_type__valueOf; momentPrototype__proto.creationData = creationData; // Year momentPrototype__proto.year = getSetYear; momentPrototype__proto.isLeapYear = getIsLeapYear; // Week Year momentPrototype__proto.weekYear = getSetWeekYear; momentPrototype__proto.isoWeekYear = getSetISOWeekYear; // Quarter momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter; // Month momentPrototype__proto.month = getSetMonth; momentPrototype__proto.daysInMonth = getDaysInMonth; // Week momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek; momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek; momentPrototype__proto.weeksInYear = getWeeksInYear; momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear; // Day momentPrototype__proto.date = getSetDayOfMonth; momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek; momentPrototype__proto.weekday = getSetLocaleDayOfWeek; momentPrototype__proto.isoWeekday = getSetISODayOfWeek; momentPrototype__proto.dayOfYear = getSetDayOfYear; // Hour momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour; // Minute momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute; // Second momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond; // Millisecond momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond; // Offset momentPrototype__proto.utcOffset = getSetOffset; momentPrototype__proto.utc = setOffsetToUTC; momentPrototype__proto.local = setOffsetToLocal; momentPrototype__proto.parseZone = setOffsetToParsedOffset; momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset; momentPrototype__proto.isDST = isDaylightSavingTime; momentPrototype__proto.isLocal = isLocal; momentPrototype__proto.isUtcOffset = isUtcOffset; momentPrototype__proto.isUtc = isUtc; momentPrototype__proto.isUTC = isUtc; // Timezone momentPrototype__proto.zoneAbbr = getZoneAbbr; momentPrototype__proto.zoneName = getZoneName; // Deprecations momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); momentPrototype__proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); var momentPrototype = momentPrototype__proto; function moment__createUnix (input) { return local__createLocal(input * 1000); } function moment__createInZone () { return local__createLocal.apply(null, arguments).parseZone(); } function preParsePostFormat (string) { return string; } var prototype__proto = Locale.prototype; prototype__proto.calendar = locale_calendar__calendar; prototype__proto.longDateFormat = longDateFormat; prototype__proto.invalidDate = invalidDate; prototype__proto.ordinal = ordinal; prototype__proto.preparse = preParsePostFormat; prototype__proto.postformat = preParsePostFormat; prototype__proto.relativeTime = relative__relativeTime; prototype__proto.pastFuture = pastFuture; prototype__proto.set = locale_set__set; // Month prototype__proto.months = localeMonths; prototype__proto.monthsShort = localeMonthsShort; prototype__proto.monthsParse = localeMonthsParse; prototype__proto.monthsRegex = monthsRegex; prototype__proto.monthsShortRegex = monthsShortRegex; // Week prototype__proto.week = localeWeek; prototype__proto.firstDayOfYear = localeFirstDayOfYear; prototype__proto.firstDayOfWeek = localeFirstDayOfWeek; // Day of Week prototype__proto.weekdays = localeWeekdays; prototype__proto.weekdaysMin = localeWeekdaysMin; prototype__proto.weekdaysShort = localeWeekdaysShort; prototype__proto.weekdaysParse = localeWeekdaysParse; prototype__proto.weekdaysRegex = weekdaysRegex; prototype__proto.weekdaysShortRegex = weekdaysShortRegex; prototype__proto.weekdaysMinRegex = weekdaysMinRegex; // Hours prototype__proto.isPM = localeIsPM; prototype__proto.meridiem = localeMeridiem; function lists__get (format, index, field, setter) { var locale = locale_locales__getLocale(); var utc = create_utc__createUTC().set(setter, index); return locale[field](utc, format); } function listMonthsImpl (format, index, field) { if (typeof format === 'number') { index = format; format = undefined; } format = format || ''; if (index != null) { return lists__get(format, index, field, 'month'); } var i; var out = []; for (i = 0; i < 12; i++) { out[i] = lists__get(format, i, field, 'month'); } return out; } // () // (5) // (fmt, 5) // (fmt) // (true) // (true, 5) // (true, fmt, 5) // (true, fmt) function listWeekdaysImpl (localeSorted, format, index, field) { if (typeof localeSorted === 'boolean') { if (typeof format === 'number') { index = format; format = undefined; } format = format || ''; } else { format = localeSorted; index = format; localeSorted = false; if (typeof format === 'number') { index = format; format = undefined; } format = format || ''; } var locale = locale_locales__getLocale(), shift = localeSorted ? locale._week.dow : 0; if (index != null) { return lists__get(format, (index + shift) % 7, field, 'day'); } var i; var out = []; for (i = 0; i < 7; i++) { out[i] = lists__get(format, (i + shift) % 7, field, 'day'); } return out; } function lists__listMonths (format, index) { return listMonthsImpl(format, index, 'months'); } function lists__listMonthsShort (format, index) { return listMonthsImpl(format, index, 'monthsShort'); } function lists__listWeekdays (localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); } function lists__listWeekdaysShort (localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); } function lists__listWeekdaysMin (localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); } locale_locales__getSetGlobalLocale('en', { ordinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); // Side effect imports utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale); utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale); var mathAbs = Math.abs; function duration_abs__abs () { var data = this._data; this._milliseconds = mathAbs(this._milliseconds); this._days = mathAbs(this._days); this._months = mathAbs(this._months); data.milliseconds = mathAbs(data.milliseconds); data.seconds = mathAbs(data.seconds); data.minutes = mathAbs(data.minutes); data.hours = mathAbs(data.hours); data.months = mathAbs(data.months); data.years = mathAbs(data.years); return this; } function duration_add_subtract__addSubtract (duration, input, value, direction) { var other = create__createDuration(input, value); duration._milliseconds += direction * other._milliseconds; duration._days += direction * other._days; duration._months += direction * other._months; return duration._bubble(); } // supports only 2.0-style add(1, 's') or add(duration) function duration_add_subtract__add (input, value) { return duration_add_subtract__addSubtract(this, input, value, 1); } // supports only 2.0-style subtract(1, 's') or subtract(duration) function duration_add_subtract__subtract (input, value) { return duration_add_subtract__addSubtract(this, input, value, -1); } function absCeil (number) { if (number < 0) { return Math.floor(number); } else { return Math.ceil(number); } } function bubble () { var milliseconds = this._milliseconds; var days = this._days; var months = this._months; var data = this._data; var seconds, minutes, hours, years, monthsFromDays; // if we have a mix of positive and negative values, bubble down first // check: https://github.com/moment/moment/issues/2166 if (!((milliseconds >= 0 && days >= 0 && months >= 0) || (milliseconds <= 0 && days <= 0 && months <= 0))) { milliseconds += absCeil(monthsToDays(months) + days) * 864e5; days = 0; months = 0; } // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absFloor(milliseconds / 1000); data.seconds = seconds % 60; minutes = absFloor(seconds / 60); data.minutes = minutes % 60; hours = absFloor(minutes / 60); data.hours = hours % 24; days += absFloor(hours / 24); // convert days to months monthsFromDays = absFloor(daysToMonths(days)); months += monthsFromDays; days -= absCeil(monthsToDays(monthsFromDays)); // 12 months -> 1 year years = absFloor(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; return this; } function daysToMonths (days) { // 400 years have 146097 days (taking into account leap year rules) // 400 years have 12 months === 4800 return days * 4800 / 146097; } function monthsToDays (months) { // the reverse of daysToMonths return months * 146097 / 4800; } function as (units) { var days; var months; var milliseconds = this._milliseconds; units = normalizeUnits(units); if (units === 'month' || units === 'year') { days = this._days + milliseconds / 864e5; months = this._months + daysToMonths(days); return units === 'month' ? months : months / 12; } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + Math.round(monthsToDays(this._months)); switch (units) { case 'week' : return days / 7 + milliseconds / 6048e5; case 'day' : return days + milliseconds / 864e5; case 'hour' : return days * 24 + milliseconds / 36e5; case 'minute' : return days * 1440 + milliseconds / 6e4; case 'second' : return days * 86400 + milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 864e5) + milliseconds; default: throw new Error('Unknown unit ' + units); } } } // TODO: Use this.as('ms')? function duration_as__valueOf () { return ( this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6 ); } function makeAs (alias) { return function () { return this.as(alias); }; } var asMilliseconds = makeAs('ms'); var asSeconds = makeAs('s'); var asMinutes = makeAs('m'); var asHours = makeAs('h'); var asDays = makeAs('d'); var asWeeks = makeAs('w'); var asMonths = makeAs('M'); var asYears = makeAs('y'); function duration_get__get (units) { units = normalizeUnits(units); return this[units + 's'](); } function makeGetter(name) { return function () { return this._data[name]; }; } var milliseconds = makeGetter('milliseconds'); var seconds = makeGetter('seconds'); var minutes = makeGetter('minutes'); var hours = makeGetter('hours'); var days = makeGetter('days'); var months = makeGetter('months'); var years = makeGetter('years'); function weeks () { return absFloor(this.days() / 7); } var round = Math.round; var thresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) { var duration = create__createDuration(posNegDuration).abs(); var seconds = round(duration.as('s')); var minutes = round(duration.as('m')); var hours = round(duration.as('h')); var days = round(duration.as('d')); var months = round(duration.as('M')); var years = round(duration.as('y')); var a = seconds < thresholds.s && ['s', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days] || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years]; a[2] = withoutSuffix; a[3] = +posNegDuration > 0; a[4] = locale; return substituteTimeAgo.apply(null, a); } // This function allows you to set the rounding function for relative time strings function duration_humanize__getSetRelativeTimeRounding (roundingFunction) { if (roundingFunction === undefined) { return round; } if (typeof(roundingFunction) === 'function') { round = roundingFunction; return true; } return false; } // This function allows you to set a threshold for relative time strings function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) { if (thresholds[threshold] === undefined) { return false; } if (limit === undefined) { return thresholds[threshold]; } thresholds[threshold] = limit; return true; } function humanize (withSuffix) { var locale = this.localeData(); var output = duration_humanize__relativeTime(this, !withSuffix, locale); if (withSuffix) { output = locale.pastFuture(+this, output); } return locale.postformat(output); } var iso_string__abs = Math.abs; function iso_string__toISOString() { // for ISO strings we do not use the normal bubbling rules: // * milliseconds bubble up until they become hours // * days do not bubble at all // * months bubble up until they become years // This is because there is no context-free conversion between hours and days // (think of clock changes) // and also not between days and months (28-31 days per month) var seconds = iso_string__abs(this._milliseconds) / 1000; var days = iso_string__abs(this._days); var months = iso_string__abs(this._months); var minutes, hours, years; // 3600 seconds -> 60 minutes -> 1 hour minutes = absFloor(seconds / 60); hours = absFloor(minutes / 60); seconds %= 60; minutes %= 60; // 12 months -> 1 year years = absFloor(months / 12); months %= 12; // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var Y = years; var M = months; var D = days; var h = hours; var m = minutes; var s = seconds; var total = this.asSeconds(); if (!total) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (total < 0 ? '-' : '') + 'P' + (Y ? Y + 'Y' : '') + (M ? M + 'M' : '') + (D ? D + 'D' : '') + ((h || m || s) ? 'T' : '') + (h ? h + 'H' : '') + (m ? m + 'M' : '') + (s ? s + 'S' : ''); } var duration_prototype__proto = Duration.prototype; duration_prototype__proto.abs = duration_abs__abs; duration_prototype__proto.add = duration_add_subtract__add; duration_prototype__proto.subtract = duration_add_subtract__subtract; duration_prototype__proto.as = as; duration_prototype__proto.asMilliseconds = asMilliseconds; duration_prototype__proto.asSeconds = asSeconds; duration_prototype__proto.asMinutes = asMinutes; duration_prototype__proto.asHours = asHours; duration_prototype__proto.asDays = asDays; duration_prototype__proto.asWeeks = asWeeks; duration_prototype__proto.asMonths = asMonths; duration_prototype__proto.asYears = asYears; duration_prototype__proto.valueOf = duration_as__valueOf; duration_prototype__proto._bubble = bubble; duration_prototype__proto.get = duration_get__get; duration_prototype__proto.milliseconds = milliseconds; duration_prototype__proto.seconds = seconds; duration_prototype__proto.minutes = minutes; duration_prototype__proto.hours = hours; duration_prototype__proto.days = days; duration_prototype__proto.weeks = weeks; duration_prototype__proto.months = months; duration_prototype__proto.years = years; duration_prototype__proto.humanize = humanize; duration_prototype__proto.toISOString = iso_string__toISOString; duration_prototype__proto.toString = iso_string__toISOString; duration_prototype__proto.toJSON = iso_string__toISOString; duration_prototype__proto.locale = locale; duration_prototype__proto.localeData = localeData; // Deprecations duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString); duration_prototype__proto.lang = lang; // Side effect imports // FORMATTING addFormatToken('X', 0, 0, 'unix'); addFormatToken('x', 0, 0, 'valueOf'); // PARSING addRegexToken('x', matchSigned); addRegexToken('X', matchTimestamp); addParseToken('X', function (input, array, config) { config._d = new Date(parseFloat(input, 10) * 1000); }); addParseToken('x', function (input, array, config) { config._d = new Date(toInt(input)); }); // Side effect imports utils_hooks__hooks.version = '2.15.1'; setHookCallback(local__createLocal); utils_hooks__hooks.fn = momentPrototype; utils_hooks__hooks.min = min; utils_hooks__hooks.max = max; utils_hooks__hooks.now = now; utils_hooks__hooks.utc = create_utc__createUTC; utils_hooks__hooks.unix = moment__createUnix; utils_hooks__hooks.months = lists__listMonths; utils_hooks__hooks.isDate = isDate; utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale; utils_hooks__hooks.invalid = valid__createInvalid; utils_hooks__hooks.duration = create__createDuration; utils_hooks__hooks.isMoment = isMoment; utils_hooks__hooks.weekdays = lists__listWeekdays; utils_hooks__hooks.parseZone = moment__createInZone; utils_hooks__hooks.localeData = locale_locales__getLocale; utils_hooks__hooks.isDuration = isDuration; utils_hooks__hooks.monthsShort = lists__listMonthsShort; utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin; utils_hooks__hooks.defineLocale = defineLocale; utils_hooks__hooks.updateLocale = updateLocale; utils_hooks__hooks.locales = locale_locales__listLocales; utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort; utils_hooks__hooks.normalizeUnits = normalizeUnits; utils_hooks__hooks.relativeTimeRounding = duration_humanize__getSetRelativeTimeRounding; utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold; utils_hooks__hooks.calendarFormat = getCalendarFormat; utils_hooks__hooks.prototype = momentPrototype; var _moment = utils_hooks__hooks; return _moment; }));
snipelixir/printing-amazone
public/assets/backend/plugins/calendar/moment.min.js
JavaScript
agpl-3.0
140,641
/* Copyright (c) 2016 eyeOS This file is part of Open365. Open365 is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ wdi.keyShortcutsHandled = { CTRLV: 0, CTRLC: 1 }; wdi.Keymap = { keymap: {}, ctrlKeymap: {}, ctrlForbiddenKeymap: {}, charmap: {}, ctrlPressed: false, twoBytesScanCodes: [0x5B, 0xDB, /*0x38, 0xB8,*/ 0x5C, 0xDC, 0x1D, 0x9D, 0x5D, 0xDD, 0x52, 0xD2, 0x53, 0xD3, 0x4B, 0xCB, 0x47, 0xC9, 0x4F, 0xCF, 0x48, 0xC8, 0x50, 0xD0, 0x49, 0xC9, 0x51, 0xD1, 0x4D, 0xCD, 0x1C, 0x9C], loadKeyMap: function(layout, stuckKeysHandler) { try { this.keymap = wdi['Keymap' + layout.toUpperCase()].getKeymap(); this.ctrlKeymap = wdi['Keymap' + layout.toUpperCase()].getCtrlKeymap(); this.ctrlForbiddenKeymap = wdi['Keymap' + layout.toUpperCase()].getCtrlForbiddenKeymap(); this.reservedCtrlKeymap = wdi['Keymap' + layout.toUpperCase()].getReservedCtrlKeymap(); this.charmap = wdi['KeymapObj' + layout.toUpperCase()].getCharmap(); this.stuckKeysHandler = stuckKeysHandler; } catch(e) { this.keymap = wdi.KeymapES.getKeymap(); this.ctrlKeymap = wdi.KeymapES.getCtrlKeymap(); this.ctrlForbiddenKeymap = wdi.KeymapES.getCtrlForbiddenKeymap(); this.reservedCtrlKeymap = wdi.KeymapES.getReservedCtrlKeymap(); this.charmap = wdi.KeymapObjES.getCharmap(); this.stuckKeysHandler = stuckKeysHandler; } }, isInKeymap: function(keycode) { return this.keymap[keycode] !== undefined; }, /** * Returns the associated spice key code from the given browser keyboard event * @param e * @returns {*} */ getScanCodes: function(e) { if (e['hasScanCode']) { return e['scanCode']; } else if (this.isForbiddenCombination(e)) { return []; } else if (this.isGeneratedShortcut(e['type'], e['keyCode'], e['generated'])) { return this.getScanCodeFromKeyCode(e['keyCode'], e['type'], this.ctrlKeymap, this.reservedCtrlKeymap); } else if (this.handledByCharmap(e['type'])) { return this.getScanCodesFromCharCode(e['charCode']); } else if (this.handledByNormalKeyCode(e['type'], e['keyCode'])) { return this.getScanCodeFromKeyCode(e['keyCode'], e['type'], this.keymap); } else { return []; } }, getScanCodeFromKeyCode: function(keyCode, type, keymap, additionalKeymap) { this.controlPressed(keyCode, type); var key = null; if(keyCode in keymap) { key = keymap[keyCode]; } else { key = additionalKeymap[keyCode]; } if (key === undefined) return []; if (key < 0x100) { if (type == 'keydown') { return [this.makeKeymap(key)]; } else if (type == 'keyup') { return [this.makeKeymap(key | 0x80)]; } } else { if (type == 'keydown') { return [this.makeKeymap(0xe0 | ((key - 0x100) << 8))]; } else if (type == 'keyup') { return [this.makeKeymap(0x80e0 | ((key - 0x100) << 8))]; } } return key; }, isForbiddenCombination: function(e) { var keyCode = e['keyCode'], type = e['type'], keymap = this.ctrlForbiddenKeymap; if(wdi.KeyEvent.isCtrlPressed(e) && keymap[keyCode]) { if(keymap[keyCode]) { return true; } } return false; }, controlPressed: function(keyCode, type, event) { if (!event) return false; if (keyCode !== 17 && keyCode !== 91) { // Ctrl or CMD key if (type === 'keydown') { if(wdi.KeyEvent.isCtrlPressed(event)){ this.ctrlPressed = true; } } else if (type === 'keyup') { if(!wdi.KeyEvent.isCtrlPressed(event)){ this.ctrlPressed = false; } } } }, handledByCtrlKeyCode: function(type, keyCode, generated) { if (type === 'keydown' || type === 'keyup' || type === 'keypress') { if (this.ctrlPressed) { if (type === 'keypress') { return true; } if (this.ctrlKeymap[keyCode]) { return true; // is the second key in a keyboard shortcut (i.e. the x in Ctrl+x) } } } return false; }, isGeneratedShortcut: function(type, keyCode, generated) { if (type === 'keydown' || type === 'keyup' || type === 'keypress') { if (this.ctrlPressed) { //check if the event is a fake event generated from our gui or programatically if(generated && this.reservedCtrlKeymap[keyCode]) { return true; } } } return false; }, handledByNormalKeyCode: function(type, keyCode) { if (type === 'keydown' || type === 'keyup') { if (this.keymap[keyCode]) { return true; } } return false; }, handledByCharmap: function(type) { return type === 'inputmanager'; }, getScanCodesFromCharCode: function(charCode) { var scanCodeObj = this.charmap[String.fromCharCode(charCode)]; var scanCodeObjModifier = new wdi.ScanCodeObjModifier(scanCodeObj); if(this.stuckKeysHandler.shiftKeyPressed) { if(scanCodeObjModifier.containsShiftDown()) { scanCodeObjModifier.removeShift(); } else { scanCodeObjModifier.addShiftUp(); scanCodeObjModifier.addShiftDown(); } } var scanCode = scanCodeObjModifier.getScanCode(); return scanCode; }, makeKeymap: function(scancode) { if ($.inArray(scancode, this.twoBytesScanCodes) != -1) { return [0xE0, scancode, 0, 0]; } else { return [scancode, 0, 0]; } } };
Open365/spice-web-client
keymaps/keymap.js
JavaScript
agpl-3.0
6,798
import { expect } from 'chai'; import semverCompare from './semverCompare'; describe('semverCompare', () => { const chaos = [ '2.5.10.4159', '0.5', '0.4.1', '1', '1.1', '2.5.0', '2', '2.5.10', '10.5', '1.25.4', '1.2.15', ]; const order = [ '0.4.1', '0.5', '1', '1.1', '1.2.15', '1.25.4', '2', '2.5.0', '2.5.10', '2.5.10.4159', '10.5', ]; it('sorts arrays correctly', () => { expect(chaos.sort(semverCompare)).to.deep.equal(order); }); it('leaves equal version numbers in place', () => { expect(['1', '1.0.0'].sort(semverCompare)).to.deep.equal(['1', '1.0.0']); expect(['1.0.0', '1'].sort(semverCompare)).to.deep.equal(['1.0.0', '1']); }); });
ahoereth/lawly
src/helpers/semverCompare.test.js
JavaScript
agpl-3.0
764
var clover = new Object(); // JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]} clover.pageData = {"classes":[{"el":190,"id":232647,"methods":[{"el":61,"sc":2,"sl":55},{"el":113,"sc":2,"sl":63},{"el":153,"sc":2,"sl":115},{"el":162,"sc":2,"sl":155},{"el":166,"sc":2,"sl":164},{"el":170,"sc":2,"sl":168},{"el":174,"sc":2,"sl":172},{"el":178,"sc":2,"sl":176},{"el":183,"sc":2,"sl":180},{"el":188,"sc":2,"sl":185}],"name":"ValueReplenishmentModel","sl":44}]} // JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...}; clover.testTargets = {} // JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]}; clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
cm-is-dog/rapidminer-studio-core
report/html/com/rapidminer/operator/preprocessing/filter/ValueReplenishmentModel.js
JavaScript
agpl-3.0
1,448
"use strict"; var assert = require('assert') , _ = require('underscore') describe('Autocompleter widget', function () { var Autocompleter = require('../utils/autocomplete_widget') describe('instance', function () { var testAutocompleter = new Autocompleter(null, 'egp', 'topics'); it('should query the correct url', function () { assert.equal(testAutocompleter.url, '/api/projects/egp/topics/'); }); it('should build a query string from a term', function () { var query = testAutocompleter.buildQuery('Alexander Berkman'); assert.deepEqual(query, { 'q': 'Alexander Berkman' }); }); it('should create its own input element when not passed one', function () { assert.equal(testAutocompleter.$el.length, 1); }); it('should be able to be enabled', function () { var $el = testAutocompleter.$el; assert.equal(_.isEmpty($el.data('ui-autocomplete')), false); assert.equal($el.prop('placeholder'), 'Begin typing to search for topics.'); }); it('should be able to be disabled', function () { var testAutocompleter = new Autocompleter(null, 'egp', 'topics'); testAutocompleter.disable(); assert.equal(_.isEmpty(testAutocompleter.$el.data('ui-autocomplete')), true); assert.equal(testAutocompleter.$el.prop('placeholder'), ''); }); it('should be able to be enabled after being disabled', function () { var testAutocompleter = new Autocompleter(null, 'egp', 'topics') , $el = testAutocompleter.$el; testAutocompleter.disable(); testAutocompleter.enable(); testAutocompleter.disable(); testAutocompleter.enable(); assert.equal(_.isEmpty($el.data('ui-autocomplete')), false); assert.equal($el.prop('placeholder'), 'Begin typing to search for topics.'); }); }); describe('should throw an error when its constructor', function () { it('is not passed a project', function () { assert.throws( function () { new Autocompleter() }, /Must pass project slug/ ); }); it('is passed an invalid model', function () { assert.throws( function () { new Autocompleter(null, 'blah', 'fakemodel') }, /Invalid model/ ); }); it('is passed an element other than a text input', function () { var el = global.document.createElement('div'); assert.throws( function () { new Autocompleter(el, 'blah', 'notes') }, /Element must be a text input/ ); }); }); }); describe('Text editor', function () { var Editor = require('../utils/text_editor.js') it('should fail without being passed an element', function () { assert.throws( function () { new Editor() }, /Must pass exactly one element/ ); }); it('should fail when passed a non-visible element', function () { var el = global.document.createElement('div'); assert.throws( function () { new Editor(el) }, /Can't edit text of element that is not visible/ ); }); describe('', function () { var sandboxes = [] , sandbox , testEl beforeEach(function (done) { sandbox = global.document.createElement('div'); testEl = global.document.createElement('p'); global.document.body.appendChild(sandbox); testEl.innerHTML = 'Test content'; sandbox.appendChild(testEl); sandboxes.push(sandbox); done(); }); after(function (done) { _.forEach(sandboxes, function (sandbox) { global.document.body.removeChild(sandbox); }); done(); }); it('should allow passing a non-jquery element', function () { var editor = new Editor(testEl); assert.equal(editor.$el[0], testEl); }); it('should assign a unique ID to its element automatically', function () { var editor = new Editor(testEl); assert.notStrictEqual(editor.id, undefined); }); it('should create its own textarea', function () { var editor = new Editor(testEl); assert.equal(editor.$textarea.length, 1); assert.equal(editor.$textarea.is('textarea'), true); }); it('should create its own toolbar', function () { var editor = new Editor(testEl); assert.equal(editor.$toolbar.is('div.wysihtml5-toolbar'), true); }); it('should be able to get its own value', function (done) { var editor = new Editor(testEl); editor.editor.on('load', function () { assert.equal(editor.value(), 'Test content'); done(); }); }); it('should clean up after itself', function (done) { var editor = new Editor(testEl); editor.editor.on('load', function () { editor.value('<p>new value</p>'); editor.destroy(); }); editor.$el.on('editor:destroyed', function (e, val) { assert.equal(val, '<p>new value</p>'); assert.equal(editor.$el.html(), '<p>new value</p>'); done(); }); }); }); }); describe('Citation generator', function () { var CitationGenerator = require('../utils/citation_generator'); it('should be able to be created', function () { var testGenerator = new CitationGenerator(); assert.notEqual(testGenerator.engine, undefined); }); it('should be able to produce citations', function () { var testGenerator = new CitationGenerator() , testData = { id: 'testing', type: 'book', title: 'Living My Life', author: [{ family: 'Goldman', given: 'Emma' }], issued: { raw: '1931' } } assert.equal( testGenerator.makeCitation(testData), 'Emma Goldman, <em>Living My Life</em>, 1931.' ) }); }); describe('Zotero => CSL converter', function () { var converter = require('../utils/zotero_to_csl') it('should give me a CSL object when passed a Zotero object', function () { var testData , expected testData = { itemType: 'book', title: 'Living My Life', creators: [{ creatorType: 'author', firstName: 'Emma', lastName: 'Goldman' }], date: '1931' } expected = { type: 'book', title: 'Living My Life', author: [{ family: 'Goldman', given: 'Emma' }], issued: { raw: '1931' } } assert.deepEqual(converter(testData), expected); }); });
CENDARI/editorsnotes
editorsnotes_app/js/test/utils.js
JavaScript
agpl-3.0
6,316
var clover = new Object(); // JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]} clover.pageData = {"classes":[{"el":70,"id":245172,"methods":[{"el":61,"sc":2,"sl":48},{"el":65,"sc":2,"sl":63},{"el":69,"sc":2,"sl":67}],"name":"ResourceLabel","sl":33}]} // JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...}; clover.testTargets = {} // JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]}; clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
cm-is-dog/rapidminer-studio-core
report/html/com/rapidminer/gui/tools/ResourceLabel.js
JavaScript
agpl-3.0
765
import { toArray, exists, stringToBoolean } from '../../../utils/utils' import { head } from 'ramda' export default function intent (addressbar, params) { const setAppMode$ = addressbar.get('appMode') .map(d => d.pop()) // what mode is the app in ? ("editor" or "viewer" only for now) const setToolsets$ = addressbar.get('tools') .map(d => d.pop()) .filter(data => data.length > 0) .map(function (data) { if (data.indexOf(',') > -1) { return data.split(',').filter(d => d.length > 0) } else { return data } }) .map(toArray) const setAutoSave$ = addressbar.get('autoSave') .map(data => head(data)) .filter(exists) .map(stringToBoolean) const setAutoLoad$ = addressbar.get('autoLoad') .map(data => head(data)) .filter(exists) .map(stringToBoolean) return { setAppMode$, setToolsets$, setAutoSave$, setAutoLoad$ } }
usco/Jam
src/core/settings/actions/fromAddressbar.js
JavaScript
agpl-3.0
928
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import axios from 'axios'; import Fixtures from 'spec/jsx/gradebook-history/Fixtures'; import HistoryApi from 'jsx/gradebook-history/api/HistoryApi'; QUnit.module('HistoryApi', { setup () { this.courseId = 123; this.getStub = this.stub(axios, 'get') .returns(Promise.resolve({ status: 200, response: Fixtures.historyResponse() })); } }); test('getGradebookHistory sends a request to the grade change audit url', function () { const url = `/api/v1/audit/grade_change/courses/${this.courseId}`; HistoryApi.getGradebookHistory(this.courseId, {}); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course and assignment', function () { const assignment = '21'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/assignments/${assignment}`; HistoryApi.getGradebookHistory(this.courseId, { assignment }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course and grader', function () { const grader = '22'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/graders/${grader}`; HistoryApi.getGradebookHistory(this.courseId, { grader }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course and student', function () { const student = '23'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/students/${student}`; HistoryApi.getGradebookHistory(this.courseId, { student }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course, assignment, and grader', function () { const grader = '22'; const assignment = '210'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/assignments/${assignment}/graders/${grader}`; HistoryApi.getGradebookHistory(this.courseId, { assignment, grader }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course, assignment, and student', function () { const student = '23'; const assignment = '210'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/assignments/${assignment}/students/${student}`; HistoryApi.getGradebookHistory(this.courseId, { assignment, student }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course, grader, and student', function () { const grader = '23'; const student = '230'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/graders/${grader}/students/${student}`; HistoryApi.getGradebookHistory(this.courseId, { grader, student }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course, assignment, grader, and student', function () { const grader = '22'; const assignment = '220'; const student = '2200' const url = `/api/v1/audit/grade_change/courses/${this.courseId}/assignments/${assignment}/graders/${grader}/students/${student}`; HistoryApi.getGradebookHistory(this.courseId, { assignment, grader, student }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getNextPage makes an axios get request', function () { const url = encodeURI('http://example.com/grades?include[]=current_grade&page=42&per_page=100000000'); HistoryApi.getNextPage(url); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); });
venturehive/canvas-lms
spec/javascripts/jsx/gradebook-history/api/HistoryApiSpec.js
JavaScript
agpl-3.0
4,496
function fetchData{{ id }}() { function onDataReceived(series) { data = [series]; $.plot("#{{ id }}", data, { series: { shadowSize: 0, }, bars: { show: true, barWidth: series.barWidth, align: "center" }, xaxis: { tickDecimals: 0, mode: "time", timezone: "browser", }, yaxis: { tickDecimals: 0, min: 0, }, }); $("#{{ id }}loading").hide(); }; $.ajax({ url: '{% url id %}', type: "GET", dataType: "json", success: onDataReceived, }); }; {% include 'pages/refreshbutton.js' %} $('#{{ id }}remove').click(function(){ var url = "{% url 'usersprofiledash' 'off' id %}"; $.ajax({ url: url, type: "GET", }); });
inteos/IBAdmin
templates/pages/runningjobswidget.js
JavaScript
agpl-3.0
855
import React from 'react'; import Wrapper from 'common/Wrapper'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import CoreAbilities from 'Parser/Core/Modules/Abilities'; import ISSUE_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE'; class Abilities extends CoreAbilities { spellbook() { const combatant = this.combatants.selected; return [ // Rotational Spells { spell: [SPELLS.NEW_MOON, SPELLS.HALF_MOON, SPELLS.FULL_MOON], category: Abilities.SPELL_CATEGORIES.ROTATIONAL, cooldown: 15, isOnGCD: true, charges: 3, castEfficiency: { suggestion: true, recommendedEfficiency: 0.95, averageIssueEfficiency: 0.9, majorIssueEfficiency: 0.85, extraSuggestion: ( <Wrapper> Your <SpellLink id={SPELLS.NEW_MOON.id} />, <SpellLink id={SPELLS.HALF_MOON.id} /> and <SpellLink id={SPELLS.FULL_MOON.id} /> cast efficiency can be improved, try keeping yourself at low Moon charges at all times; you should (almost) never be at max (3) charges. </Wrapper> ), }, timelineSortIndex: 1, }, { spell: SPELLS.STARSURGE_MOONKIN, category: Abilities.SPELL_CATEGORIES.ROTATIONAL, isOnGCD: true, timelineSortIndex: 2, }, { spell: SPELLS.STARFALL_CAST, category: Abilities.SPELL_CATEGORIES.ROTATIONAL, isOnGCD: true, timelineSortIndex: 3, }, { spell: SPELLS.SOLAR_WRATH_MOONKIN, category: Abilities.SPELL_CATEGORIES.ROTATIONAL, isOnGCD: true, timelineSortIndex: 4, }, { spell: SPELLS.LUNAR_STRIKE, category: Abilities.SPELL_CATEGORIES.ROTATIONAL, isOnGCD: true, timelineSortIndex: 5, }, { spell: SPELLS.MOONFIRE, category: Abilities.SPELL_CATEGORIES.ROTATIONAL, isOnGCD: true, timelineSortIndex: 6, }, { spell: SPELLS.SUNFIRE_CAST, category: Abilities.SPELL_CATEGORIES.ROTATIONAL, isOnGCD: true, timelineSortIndex: 7, }, { spell: SPELLS.STELLAR_FLARE_TALENT, category: Abilities.SPELL_CATEGORIES.ROTATIONAL, enabled: combatant.hasTalent(SPELLS.STELLAR_FLARE_TALENT.id), isOnGCD: true, timelineSortIndex: 8, }, // Cooldowns { spell: SPELLS.INCARNATION_CHOSEN_OF_ELUNE_TALENT, category: Abilities.SPELL_CATEGORIES.COOLDOWNS, cooldown: 180, enabled: combatant.hasTalent(SPELLS.INCARNATION_CHOSEN_OF_ELUNE_TALENT.id), castEfficiency: { suggestion: true, recommendedEfficiency: 0.9, }, timelineSortIndex: 9, }, { spell: SPELLS.CELESTIAL_ALIGNMENT, category: Abilities.SPELL_CATEGORIES.COOLDOWNS, cooldown: 180, enabled: !combatant.hasTalent(SPELLS.INCARNATION_CHOSEN_OF_ELUNE_TALENT.id), castEfficiency: { suggestion: true, recommendedEfficiency: 0.9, }, timelineSortIndex: 9, }, { spell: SPELLS.WARRIOR_OF_ELUNE_TALENT, category: Abilities.SPELL_CATEGORIES.COOLDOWNS, cooldown: 48, enabled: combatant.hasTalent(SPELLS.WARRIOR_OF_ELUNE_TALENT.id), castEfficiency: { suggestion: true, recommendedEfficiency: 0.9, }, timelineSortIndex: 10, }, { spell: SPELLS.FORCE_OF_NATURE_TALENT, category: Abilities.SPELL_CATEGORIES.COOLDOWNS, cooldown: 60, enabled: combatant.hasTalent(SPELLS.FORCE_OF_NATURE_TALENT.id), isOnGCD: true, castEfficiency: { suggestion: true, recommendedEfficiency: 0.9, }, timelineSortIndex: 10, }, { spell: SPELLS.ASTRAL_COMMUNION_TALENT, category: Abilities.SPELL_CATEGORIES.COOLDOWNS, cooldown: 80, enabled: combatant.hasTalent(SPELLS.ASTRAL_COMMUNION_TALENT.id), castEfficiency: { suggestion: true, recommendedEfficiency: 0.9, }, timelineSortIndex: 11, }, //Utility { spell: SPELLS.INNERVATE, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 180, castEfficiency: { suggestion: true, recommendedEfficiency: 0.70, averageIssueEfficiency: 0.50, majorIssueEfficiency: 0.30, }, timelineSortIndex: 12, }, { spell: SPELLS.BARKSKIN, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 60, castEfficiency: { suggestion: true, recommendedEfficiency: 0.6, importance: ISSUE_IMPORTANCE.MINOR, }, timelineSortIndex: 13, }, { spell: SPELLS.RENEWAL_TALENT, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 90, enabled: combatant.hasTalent(SPELLS.RENEWAL_TALENT.id), timelineSortIndex: 14, }, { spell: SPELLS.DISPLACER_BEAST_TALENT, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 30, enabled: combatant.hasTalent(SPELLS.DISPLACER_BEAST_TALENT.id), isOnGCD: true, }, { spell: [SPELLS.WILD_CHARGE_TALENT, SPELLS.WILD_CHARGE_MOONKIN, SPELLS.WILD_CHARGE_CAT, SPELLS.WILD_CHARGE_BEAR, SPELLS.WILD_CHARGE_TRAVEL], category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 15, enabled: combatant.hasTalent(SPELLS.WILD_CHARGE_TALENT.id), }, { spell: SPELLS.MIGHTY_BASH_TALENT, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 50, enabled: combatant.hasTalent(SPELLS.MIGHTY_BASH_TALENT.id), isOnGCD: true, }, { spell: SPELLS.MASS_ENTANGLEMENT_TALENT, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 30, enabled: combatant.hasTalent(SPELLS.MASS_ENTANGLEMENT_TALENT.id), isOnGCD: true, }, { spell: SPELLS.TYPHOON, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 30, enabled: combatant.hasTalent(SPELLS.TYPHOON_TALENT.id), isOnGCD: true, }, { spell: SPELLS.ENTANGLING_ROOTS, category: Abilities.SPELL_CATEGORIES.UTILITY, isOnGCD: true, }, { spell: SPELLS.DASH, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 180, isOnGCD: true, //It is not on the GCD if already in catform. Pretty low prio to fix since you can't cast anything meaning full in catform anyway. }, { spell: SPELLS.SOLAR_BEAM, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 45, }, { spell: SPELLS.REMOVE_CORRUPTION, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 8, isOnGCD: true, }, { spell: SPELLS.REBIRTH, category: Abilities.SPELL_CATEGORIES.UTILITY, isOnGCD: true, }, { spell: SPELLS.GROWL, category: Abilities.SPELL_CATEGORIES.UTILITY, cooldown: 8, }, { spell: SPELLS.BEAR_FORM, category: Abilities.SPELL_CATEGORIES.UTILITY, isOnGCD: true, }, { spell: SPELLS.CAT_FORM, category: Abilities.SPELL_CATEGORIES.UTILITY, isOnGCD: true, }, { spell: SPELLS.MOONKIN_FORM, category: Abilities.SPELL_CATEGORIES.UTILITY, isOnGCD: true, }, { spell: SPELLS.TRAVEL_FORM, category: Abilities.SPELL_CATEGORIES.UTILITY, isOnGCD: true, }, { spell: SPELLS.REGROWTH, category: Abilities.SPELL_CATEGORIES.UTILITY, isOnGCD: true, }, { spell: SPELLS.FRENZIED_REGENERATION, category: Abilities.SPELL_CATEGORIES.UTILITY, enabled: combatant.hasTalent(SPELLS.GUARDIAN_AFFINITY_TALENT_SHARED.id), }, { spell: SPELLS.SWIFTMEND, category: Abilities.SPELL_CATEGORIES.UTILITY, enabled: combatant.hasTalent(SPELLS.RESTORATION_AFFINITY_TALENT.id), isOnGCD: true, }, { spell: SPELLS.REJUVENATION, category: Abilities.SPELL_CATEGORIES.UTILITY, enabled: combatant.hasTalent(SPELLS.RESTORATION_AFFINITY_TALENT.id), isOnGCD: true, }, { spell: SPELLS.SWIFTMEND, category: Abilities.SPELL_CATEGORIES.UTILITY, enabled: combatant.hasTalent(SPELLS.RESTORATION_AFFINITY_TALENT.id), isOnGCD: true, }, ]; } } export default Abilities;
hasseboulen/WoWAnalyzer
src/Parser/Druid/Balance/Modules/Features/Abilities.js
JavaScript
agpl-3.0
8,771
/* INPUT: * workspaceId * contactId DESCRIPTION An editable list of phone numbers (`workspacesContactsPhoneNumbers`) owned by contactId. */ define([ "dojo/_base/declare" , "dijit/form/ValidationTextBox" , "put-selector/put" , "hotplate/hotClientDojo/dgridWidgets/commonMixins" , "hotplate/hotClientDojo/widgets/EditingWidget" , "hotplate/hotClientDojo/widgets/SharedValidationTextBox" , "hotplate/hotClientDojo/widgets/widgets" , "hotplate/hotClientDojo/dgridWidgets/EditableList" , "hotplate/hotClientDojo/widgets/BusyButton" , "hotplate/hotClientDojo/stores/stores" , "hotplate/hotClientDojo/globals/globals" , "hotplate/hotClientDojo/storeConfig/ConfigVars" ], function( declare , ValidationTextBox , put , commonMixins , EditingWidget , SharedValidationTextBox , widgets , EditableList , BusyButton , stores , globals , ConfigVars ){ var templateString = '' + '<div>\n' + ' <div class="inline-form">\n' + ' <form data-dojo-type="dijit/form/Form" data-dojo-attach-point="formWidget" method="POST">\n' + ' <input class="dial-code" id="${id}_dialCode" name="dialCode" data-dojo-type="hotplate/hotClientDojo/widgets/SharedValidationTextBox" maxlength="4" data-dojo-props="value: this.countryDialCodeDefault, placeHolder:this.countryDialCodeDefault, required: true, sharedValidator: \'dialCode\'" data-dojo-attach-point="dialCodeWidget" />\n' + ' <input class="number" id="${id}_number" name="number" data-dojo-type="hotplate/hotClientDojo/widgets/SharedValidationTextBox" maxlength="20" data-dojo-props="placeHolder:\'Type a phone number...\', required: true, sharedValidator: \'phoneNumber\'" data-dojo-attach-point="numberWidget" />\n' + ' <input class="form-submit" type="submit" data-dojo-attach-point="buttonWidget" data-dojo-type="hotplate/hotClientDojo/widgets/BusyButton" label="Save" />' + ' </form>\n'+ ' </div>\n'+ '</div>\n'+ ''; return declare( [ EditableList ], { closeDialogAfterSubmit: true, ownClass: 'workspaces-contacts-phone-numbers', postMixInProperties: function(){ this.inherited(arguments); this.storeParameters = { workspaceId: this.workspaceId, contactId: this.contactId }; }, ListConstructor: declare( [ commonMixins.FullOnDemandList ], { renderRow: function(object, options){ if( object.dialCode ) var row = put('div.row', '+' + object.dialCode + ' ' + object.number ); else var row = put('div.row', object.number ); return row; }, dndParams: { selfAccept: true }, refresh: function(){ this.inherited( arguments ); }, }), EditingWidgetConstructor: declare([ EditingWidget ], { templateString: templateString, alertBarDomPlacement: 'last', resetOnSuccess: true, buildRendering: function(){ this.countryDialCodeDefault = ConfigVars.workspacesInfo.countryDialCodeDefault; this.inherited( arguments ); }, manipulateValuesBeforeSubmit: function( values ){ //console.log(values); //values.orderByNameDefault = values.orderByNameDefault.indexOf( 'on' ) !== -1; }, }), storeName: 'workspacesContactsPhoneNumbers', editingWidgetPlacement: 'inline', multipleEditingAllowed: false, addingWidgetPosition: 'top', gutters: false, buttonsPosition: 'after', // or "top" or "bottom" } ); }); /* var countryOptions = []; var countryDialCodes = sharedFunctions.bd.countryDialCodes(); for( var code in countryDialCodes ){ var country = countryDialCodes[ code ]; console.log( country, code ); countryOptions.push( { label: country + ' (+' + code + ')', value: code }); console.log( "OPTIONS: ", countryOptions ); } var CountrySelect = declare( 'bd/DialCode', Select, { name: "dialCode", options: countryOptions }); */
mercmobily/bookingdojo
node_modules/bd/client/WorkspacesContacts/WorkspacesContactsPhoneNumbers.js
JavaScript
agpl-3.0
3,890
var webpack = require('webpack'); var dotenv = require('dotenv').load(); module.exports = exports = require('./webpack.config'); exports.plugins = [ new webpack.DefinePlugin({ __API_URL__: JSON.stringify(process.env.LANDLINE_API_URL), __PROD__: false, __S3_BUCKET__: JSON.stringify('landline-dev') }), new webpack.NoErrorsPlugin() ]; exports.output = Object.create(exports.output); exports.output.filename = exports.output.filename.replace(/\.js$/, ".dev.js"); exports.devtool = 'source-map';
asm-products/landline-web
webpack.config.dev.js
JavaScript
agpl-3.0
513
var root2 = { "name": "flare", "children": [ { "name": "analytics", "children": [ { "name": "cluster", "children": [ {"name": "AgglomerativeCluster", "size": 3938}, {"name": "CommunityStructure", "size": 3812}, {"name": "MergeEdge", "size": 743} ] }, { "name": "graph", "children": [ {"name": "BetweennessCentrality", "size": 3534}, {"name": "LinkDistance", "size": 5731} ] } ] } ] }
agentlab/ru.agentlab.maia
tools/ru.agentlab.maia.admin.ui/_old/js/_old/root2.js
JavaScript
lgpl-2.1
499
/* * File: ui-list.js * Author: Li XianJing <xianjimli@hotmail.com> * Brief: List * * Copyright (c) 2011 - 2015 Li XianJing <xianjimli@hotmail.com> * */ function UIList() { return; } UIList.prototype = new UIElement(); UIList.prototype.isUIList = true; UIList.prototype.isUILayout = true; UIList.prototype.initUIList = function(type, border, itemHeight, bg) { this.initUIElement(type); this.setMargin(border, border); this.setSizeLimit(100, 100, 1000, 1000); this.setDefSize(400, itemHeight * 3 + 2 * border); this.itemHeight = itemHeight; this.widthAttr = UIElement.WIDTH_FILL_PARENT; this.setTextType(Shape.TEXT_INPUT); this.setImage(UIElement.IMAGE_DEFAULT, bg); this.rectSelectable = false; this.itemHeightVariable = false; this.addEventNames(["onInit"]); if(!bg) { this.style.setFillColor("White"); } return this; } UIList.prototype.getItemHeight = function() { return this.itemHeight; } UIList.prototype.setItemHeight = function(itemHeight) { this.itemHeight = itemHeight; return; } UIList.prototype.shapeCanBeChild = function(shape) { if(!shape.isUIListItem) { return false; } return true; } UIList.prototype.childIsBuiltin = function(child) { return child.name === "ui-list-item-update-status" || child.name === "ui-list-item-update-tips" || child.name === "ui-last" || child.name.indexOf("prebuild") >= 0 || child.name.indexOf("builtin") >= 0; } UIList.FIRST_ITEM = -1; UIList.LAST_ITEM = 1; UIList.MIDDLE_ITEM = 0; UIList.SINGLE_ITEM = 2; UIList.prototype.fixListItemImage = function(item, position) { var images = item.images; for(var key in images) { var value = images[key]; if(key != "display") { var src = value.getImageSrc(); if(!src) { continue; } switch(position) { case UIList.FIRST_ITEM: { src = src.replace(/\.single\./, ".first."); src = src.replace(/\.middle\./, ".first."); src = src.replace(/\.last\./, ".first."); break; } case UIList.MIDDLE_ITEM: { src = src.replace(/\.single\./, ".middle."); src = src.replace(/\.first\./, ".middle."); src = src.replace(/\.last\./, ".middle."); break; } case UIList.LAST_ITEM: { src = src.replace(/\.single\./, ".last."); src = src.replace(/\.first\./, ".last."); src = src.replace(/\.middle\./, ".last."); break; } case UIList.SINGLE_ITEM: { src = src.replace(/\.first\./, ".single."); src = src.replace(/\.middle\./, ".single."); src = src.replace(/\.last\./, ".single."); break; } } value.setImageSrc(src); } } return; } UIList.prototype.relayoutChildren = function(animHint) { if(this.disableRelayout) { return; } var hMargin = this.getHMargin(); var vMargin = this.getVMargin(); var x = hMargin; var y = vMargin; var w = this.getWidth(true); var itemHeight = this.getItemHeight(); var h = itemHeight; var n = this.children.length; var itemHeightVariable = this.itemHeightVariable; for(var i = 0; i < n; i++) { var config = {}; var animatable = false; var child = this.children[i]; if(itemHeightVariable || child.isHeightVariable()) { h = child.measureHeight(itemHeight); } else { h = itemHeight; } if(n === 1) { this.fixListItemImage(child, UIList.SINGLE_ITEM); } else if(i === 0) { this.fixListItemImage(child, UIList.FIRST_ITEM); } else if(i === (n - 1)) { this.fixListItemImage(child, UIList.LAST_ITEM); } else { this.fixListItemImage(child, UIList.MIDDLE_ITEM); } if(this.h <= (y + vMargin + h)) { this.h = y + vMargin + h; } animatable = (y < this.h) && (animHint || this.mode === Shape.MODE_EDITING); if(animatable) { child.setSize(w, h); config.xStart = child.x; config.yStart = child.y; config.wStart = child.w; config.hStart = child.h; config.xEnd = x; config.yEnd = y; config.wEnd = w; config.hEnd = h; config.delay = 10; config.duration = 1000; config.element = child; config.onDone = function (el) { el.relayoutChildren(); } child.animate(config); } else { child.move(x, y); child.setSize(w, h); child.relayoutChildren(); } child.setUserMovable(true); child.widthAttr = UIElement.WIDTH_FILL_PARENT; if(child.heightAttr === UIElement.HEIGHT_FILL_PARENT) { child.heightAttr = UIElement.HEIGHT_FIX; } child.setUserResizable(itemHeightVariable || child.isHeightVariable()); if(!this.isUIScrollView) { child.setDraggable(this.itemDraggable); } y += h; } return; } UIList.prototype.beforePaintChildren = function(canvas) { canvas.beginPath(); canvas.rect(0, 0, this.w, this.h); canvas.clip(); canvas.beginPath(); return; } UIList.prototype.afterPaintChildren = function(canvas) { return; } UIList.prototype.afterChildAppended = function(shape) { if(shape.view && this.mode === Shape.MODE_EDITING && shape.isCreatingElement()) { this.sortChildren(); } this.moveMustBeLastItemToLast(); shape.setUserMovable(true); shape.setUserResizable(false); shape.setCanRectSelectable(false, true); shape.autoAdjustHeight = this.itemHeightVariable; shape.setDraggable(this.itemDraggable); return true; } UIList.prototype.sortChildren = function() { this.children.sort(function(a, b) { var bb = b.y; var aa = (b.pointerDown && b.hitTestResult === Shape.HIT_TEST_MM) ? (a.y + a.h*0.8) : a.y; return aa - bb; }); return; } UIList.prototype.onKeyUpRunning = function(code) { var targetShapeIndex = 0; if(!this.children.length) { return; } switch(code) { case KeyEvent.DOM_VK_UP: { targetShapeIndex = this.children.indexOf(this.targetShape) - 1; break; } case KeyEvent.DOM_VK_DOWN: { targetShapeIndex = this.children.indexOf(this.targetShape) + 1; break; } default: { return; } } var n = this.children.length; targetShapeIndex = (targetShapeIndex + this.children.length)%n; var targetShape = this.children[targetShapeIndex]; this.setTarget(targetShape); this.postRedraw(); if(this.isUIListView) { if(this.offset > targetShape.y) { this.offset = targetShape.y; } if((this.offset + this.h) < (targetShape.y + targetShape.h)) { this.offset = targetShape.y - (this.h - targetShape.h); } } return; } UIList.prototype.onKeyDownRunning = function(code) { } UIList.prototype.getValue = function() { var ret = null; var n = this.children.length; if(n < 1) return ret; for(var i = 0; i < n; i++) { var iter = this.children[i]; if(!iter.isUIListCheckableItem || !iter.value) continue; if(iter.isRadio) { return i; } else { if(!ret) ret = []; ret.push(i); } } return ret; } UIList.prototype.setValue = function(value) { var arr = null; if(typeof value === "array") { arr = value; } else if(typeof value === "number") { arr = [value]; } else { arr = []; } var n = this.children.length; for(var i = 0; i < n; i++) { var item = this.children[i]; if(item.isUIListCheckableItem) { item.setValue(false); } } for(var i = 0; i < arr.length; i++) { var index = arr[i]; if(index >= 0 && index < n) { var item = this.children[index]; if(item.isUIListCheckableItem) { item.setChecked(true); } } } return this; } function UIListCreator(border, itemHeight, bg) { var args = ["ui-list", "ui-list", null, 1]; ShapeCreator.apply(this, args); this.createShape = function(createReason) { var g = new UIList(); return g.initUIList(this.type, border, itemHeight, bg); } return; } ShapeFactoryGet().addShapeCreator(new UIListCreator(5, 114, null));
noikiy/cantk
controls/js/ui-list.js
JavaScript
lgpl-2.1
7,568
/* http://www.kryogenix.org/code/browser/searchhi/ */ /* Modified 20021006 to fix query string parsing and add case insensitivity */ /* Modified 20030227 by sgala@hisitech.com to skip words with "-" and cut %2B (+) preceding pages */ function highlightWord(node,word) { // Iterate into this nodes childNodes if (node.hasChildNodes) { var hi_cn; for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) { highlightWord(node.childNodes[hi_cn],word); } } // And do this node itself if (node.nodeType == 3) { // text node tempNodeVal = node.nodeValue.toLowerCase(); tempWordVal = word.toLowerCase(); if (tempNodeVal.indexOf(tempWordVal) != -1) { pn = node.parentNode; if (pn.className != "searchword") { // word has not already been highlighted! nv = node.nodeValue; ni = tempNodeVal.indexOf(tempWordVal); // Create a load of replacement nodes before = document.createTextNode(nv.substr(0,ni)); docWordVal = nv.substr(ni,word.length); // alert( "Found: " + docWordVal ); after = document.createTextNode(nv.substr(ni+word.length)); hiwordtext = document.createTextNode(docWordVal); hiword = document.createElement("span"); hiword.className = "searchword"; hiword.appendChild(hiwordtext); pn.insertBefore(before,node); pn.insertBefore(hiword,node); pn.insertBefore(after,node); pn.removeChild(node); } } } } function googleSearchHighlight() { if (!document.createElement) return; ref = document.referrer; //or URL for highlighting in place if (ref.indexOf('?') == -1) return; qs = ref.substr(ref.indexOf('?')+1); qsa = qs.split('&'); for (i=0;i<qsa.length;i++) { qsip = qsa[i].split('='); if (qsip.length == 1) continue; // q= for Google, p= for Yahoo // query= for JSPWiki if (qsip[0] == 'query' || qsip[0] == 'q') { words = qsip[1].replace(/%2B/g,''); words = words.replace(/-\S+\s/g,''); words = unescape(words.replace(/\+/g,' ')).split(/\s+/); for (w=0;w<words.length;w++) { highlightWord(document.getElementsByTagName("body")[0],words[w]); } } } } window.onload = googleSearchHighlight;
hgschmie/EyeWiki
jspwiki/templates/old/search_highlight.js
JavaScript
lgpl-2.1
2,580
var interface_c_p_event = [ [ "buttonNumber", "interface_c_p_event.html#a95f060acf8268fe7f3a16c42ea121466", null ], [ "characters", "interface_c_p_event.html#a1bf8cbf0c017151070a99236c957fc94", null ], [ "charactersIgnoringModifiers", "interface_c_p_event.html#aa1b99c685842a415f6736d776c8aba90", null ], [ "clickCount", "interface_c_p_event.html#a21ba312feb01ac26df9cab0eae85cdcc", null ], [ "currentTimestamp", "interface_c_p_event.html#a0370261e16fa1b67388c1a027efff02a", null ], [ "data1", "interface_c_p_event.html#a2129df252602ed408c8e9241d8e89aad", null ], [ "data2", "interface_c_p_event.html#a5a9e2ed2d7faffaef4648da3257ac31b", null ], [ "deltaX", "interface_c_p_event.html#a8bcf33e092b83a9bf10fc2aabae6c249", null ], [ "deltaY", "interface_c_p_event.html#a1804678959cc324a1af7386b71720cf2", null ], [ "deltaZ", "interface_c_p_event.html#adb216a38817ab6a03fc50276fb7abad9", null ], [ "description", "interface_c_p_event.html#af262b1f3b4aced3b2bd3044bd15af565", null ], [ "globalLocation", "interface_c_p_event.html#ad464fd6df3bf20110075dc81ce662a44", null ], [ "isARepeat", "interface_c_p_event.html#a0d6e1d0c4afa0c4231bedcdd9401ba87", null ], [ "keyCode", "interface_c_p_event.html#a5ecd01fadd6c4bc25a8508dc4bb7cca7", null ], [ "keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:", "interface_c_p_event.html#af5f96235d926dc455c492ece4d907744", null ], [ "locationInWindow", "interface_c_p_event.html#a5a57f4fa909de5d83e5402a8d8af4b94", null ], [ "modifierFlags", "interface_c_p_event.html#ae1990580a2f73b19009f30f27ff1e396", null ], [ "mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:", "interface_c_p_event.html#ad6bbef973e2dd36732fe8b51be55e3e7", null ], [ "mouseLocation", "interface_c_p_event.html#a91d4b5abd148e3976056714f6cf658fc", null ], [ "otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:", "interface_c_p_event.html#a90910bafcdc04fe2641c9350669d9810", null ], [ "pressure", "interface_c_p_event.html#acac4af271cc9cbeb999d0c148767fc99", null ], [ "startPeriodicEventsAfterDelay:withPeriod:", "interface_c_p_event.html#a474ff767ceaf957fbde1a662d01b4788", null ], [ "stopPeriodicEvents", "interface_c_p_event.html#a5071c8f5ce8fd7d8a08e6ae4756b1d2d", null ], [ "timestamp", "interface_c_p_event.html#ab290762686ceda8bb462e0e989f62e04", null ], [ "type", "interface_c_p_event.html#abbbd5ff6550996fa3ef524ef27a1ef80", null ], [ "window", "interface_c_p_event.html#af9a0e45bbaba9bc6587a222e74bf0703", null ], [ "windowNumber", "interface_c_p_event.html#a15734c6e53f37894f69326ac46ec3600", null ] ];
davidsiaw/cappuccino-docs
interface_c_p_event.js
JavaScript
lgpl-2.1
2,799
#!/usr/bin/env node // requires var webcredits = require('../lib/webcredits.js'); var program = require('commander'); /** * version as a command */ function bin(argv) { // setup config var config = require('../config/dbconfig.js'); program .option('-c, --currency <currency>', 'Currency') .option('-d, --database <database>', 'Database') .option('-w, --wallet <wallet>', 'Wallet') .parse(argv); var defaultCurrency = 'https://w3id.org/cc#bit'; var defaultDatabase = 'webcredits'; var defaultWallet = 'https://localhost/wallet/test#this'; config.currency = program.currency || config.currency || defaultCurrency; config.database = program.database || config.database || defaultDatabase; config.wallet = program.wallet || config.wallet || defaultWallet; webcredits.createDB(config, function(err, ret) { if (err) { console.error(err); } else { console.log(ret); } }); } // If one import this file, this is a module, otherwise a library if (require.main === module) { bin(process.argv); } module.exports = bin;
webcredits/webcredits
bin/create.js
JavaScript
lgpl-3.0
1,085
var searchData= [ ['scurve3',['SCurve3',['../class_u_noise_interp.html#a22a2c02d3c1a30fca2907a2c3509d8d8',1,'UNoiseInterp']]], ['scurve5',['SCurve5',['../class_u_noise_interp.html#ada246d3dbbe6a2a61fe306253d64efaf',1,'UNoiseInterp']]], ['setangles',['SetAngles',['../class_u_rotate_point.html#a99a935b295c0afda4706304530518cfb',1,'URotatePoint']]], ['setbias',['SetBias',['../class_u_scale_bias.html#aeebe8e9a7edd8e319f9e0eebdd5b5ef3',1,'UScaleBias']]], ['setbounds',['SetBounds',['../class_u_clamp.html#afa4a212b01ad5df6a009ae011f1f3d7a',1,'UClamp::SetBounds()'],['../class_u_select.html#ad8920c33f5aa8746d96b6fce69d2f871',1,'USelect::SetBounds()']]], ['setconstvalue',['SetConstValue',['../class_u_const.html#acd3db35e01a2b0e79fdbca1630a89651',1,'UConst']]], ['setcontrolmodule',['SetControlModule',['../class_u_blend.html#a99216423a69c1ff76ac017c4f4160fef',1,'UBlend::SetControlModule()'],['../class_u_select.html#ab0087927c8acb8c77f509b7e064bea61',1,'USelect::SetControlModule()']]], ['setdisplacement',['SetDisplacement',['../class_u_voronoi.html#a89a4c409b0eb129a00d145bae7237f47',1,'UVoronoi']]], ['setdisplacemodules',['SetDisplaceModules',['../class_u_displace.html#a5bed2df7a9f48b262912d050bcd39763',1,'UDisplace']]], ['setedgefalloff',['SetEdgeFalloff',['../class_u_select.html#a1a0d785db8384b053d804929330e0ef8',1,'USelect']]], ['setexponent',['SetExponent',['../class_u_exponent.html#ad461ce36e6d8284b048d3da3f8286d0a',1,'UExponent']]], ['setfrequency',['SetFrequency',['../class_u_billow.html#accb2e6793dc2bb8457f576c6fbae9752',1,'UBillow::SetFrequency()'],['../class_u_cylinders.html#a48cf0289b4a18c6444bbcb37a6d5c354',1,'UCylinders::SetFrequency()'],['../class_u_perlin.html#a21c22bedac205aca917fdc5f7e251216',1,'UPerlin::SetFrequency()'],['../class_u_ridged_multi.html#a07968d6932798a27fdc54cf12c4ee09f',1,'URidgedMulti::SetFrequency()'],['../class_u_spheres.html#a9a1a7b24c92a2ceb50d095baf31d081f',1,'USpheres::SetFrequency()'],['../class_u_turbulence.html#a4240b5bd6ac667a4d96071313df0f2a1',1,'UTurbulence::SetFrequency()'],['../class_u_voronoi.html#ab92796cfb66598aad7799078a2da7416',1,'UVoronoi::SetFrequency()']]], ['setlacunarity',['SetLacunarity',['../class_u_billow.html#a6f0e4c225032d1976e87a94c7bc24f58',1,'UBillow::SetLacunarity()'],['../class_u_perlin.html#a8408f13c3570e2f1d4a555706454ee59',1,'UPerlin::SetLacunarity()'],['../class_u_ridged_multi.html#a947741e4a59265bb187ab67088059a4b',1,'URidgedMulti::SetLacunarity()']]], ['setnoisemodule',['SetNoiseModule',['../class_u_noise_map.html#a950914ad41f05881456e8d8b6c4a3bfb',1,'UNoiseMap']]], ['setnoisequality',['SetNoiseQuality',['../class_u_billow.html#a829e28f0964a352382b992580a313223',1,'UBillow::SetNoiseQuality()'],['../class_u_perlin.html#a353bcd379748a3a393ae5cc79dd50b8b',1,'UPerlin::SetNoiseQuality()'],['../class_u_ridged_multi.html#aa28915ad017a0b69db08dcf35964aed6',1,'URidgedMulti::SetNoiseQuality()']]], ['setoctavecount',['SetOctaveCount',['../class_u_billow.html#aea02c076dbdfdb72e950b75c5c3efe2f',1,'UBillow::SetOctaveCount()'],['../class_u_perlin.html#af39e340969211a0abeaa11fc073c9cb5',1,'UPerlin::SetOctaveCount()'],['../class_u_ridged_multi.html#aee4154efd932b3152fa80c0d42e14866',1,'URidgedMulti::SetOctaveCount()']]], ['setpersistence',['SetPersistence',['../class_u_billow.html#a5c3517220958cb8f0b84812c7f1d120b',1,'UBillow::SetPersistence()'],['../class_u_perlin.html#ac9c0b73c6f6b4f74298d63121570eb13',1,'UPerlin::SetPersistence()']]], ['setpower',['SetPower',['../class_u_turbulence.html#a0f007b6d79096b9d0e0b06ec1d7992d4',1,'UTurbulence']]], ['setroughness',['SetRoughness',['../class_u_turbulence.html#ad031377e0500106498a057c0bb654772',1,'UTurbulence']]], ['setscale',['SetScale',['../class_u_scale_bias.html#a7681b66e2fc646e8ac01941ba812a657',1,'UScaleBias']]], ['setseed',['SetSeed',['../class_u_billow.html#a3cc68740e99b56ffd6de2c2b4bc6a8c5',1,'UBillow::SetSeed()'],['../class_u_perlin.html#ae925f8e241fefb6de6e3cdf68113558f',1,'UPerlin::SetSeed()'],['../class_u_ridged_multi.html#a8bb9d6c350a3329f22915166a2a605de',1,'URidgedMulti::SetSeed()'],['../class_u_turbulence.html#a0dbb349f46b6a8115ff14b6415cc760d',1,'UTurbulence::SetSeed()'],['../class_u_voronoi.html#ae3a51cab502f3468d968dea5db318998',1,'UVoronoi::SetSeed()']]], ['setsize',['SetSize',['../class_u_noise_map.html#ab19489db338e64bbe7e8056b7cdc3920',1,'UNoiseMap']]], ['setsourcemodule',['SetSourceModule',['../class_u_cache.html#a1768f4385b4a66b22b98eeac904ea666',1,'UCache::SetSourceModule()'],['../class_u_noise_module.html#a0bd5fc900b073d1d06b878a22bf8fff3',1,'UNoiseModule::SetSourceModule()']]], ['settranslation',['SetTranslation',['../class_u_translate_point.html#a15386006025bca4ac8ebe1af0a349022',1,'UTranslatePoint']]], ['settranslationxyz',['SetTranslationXYZ',['../class_u_translate_point.html#a00fe463c88b41d42b26f8096319a3a90',1,'UTranslatePoint']]], ['setvalue',['SetValue',['../class_u_noise_map.html#a5488982a815bb6773e4f81d1333683a7',1,'UNoiseMap']]], ['setxangle',['SetXAngle',['../class_u_rotate_point.html#af6b8d740889a6ad0b902034836bc3ddc',1,'URotatePoint']]], ['setxdisplacemodule',['SetXDisplaceModule',['../class_u_displace.html#ae81bc5ec5eae674e156c9bf672f489a4',1,'UDisplace']]], ['setxtranslation',['SetXTranslation',['../class_u_translate_point.html#a34f77532c07cc5ed277aa8a0d54e7276',1,'UTranslatePoint']]], ['setyangle',['SetYAngle',['../class_u_rotate_point.html#a865004a6a3e291b2b68e06720f6a58dc',1,'URotatePoint']]], ['setydisplacemodule',['SetYDisplaceModule',['../class_u_displace.html#aba0356e35535699f6f1ff83ca2ad3663',1,'UDisplace']]], ['setytranslation',['SetYTranslation',['../class_u_translate_point.html#afc47185a8e1ddff021e3b958a3952ff5',1,'UTranslatePoint']]], ['setzangle',['SetZAngle',['../class_u_rotate_point.html#a5373184431877ed5cafe9f27608d078c',1,'URotatePoint']]], ['setzdisplacemodule',['SetZDisplaceModule',['../class_u_displace.html#a200f2ffeedf3c9614f8a80e3558aa5d5',1,'UDisplace']]], ['setztranslation',['SetZTranslation',['../class_u_translate_point.html#a4c7b2941136780440d78d21a57ae5fb4',1,'UTranslatePoint']]], ['shutdownmodule',['ShutdownModule',['../class_f_unreal_lib_noise_module.html#a1bca0cbc801a13ceae78e694914a06ca',1,'FUnrealLibNoiseModule']]], ['startupmodule',['StartupModule',['../class_f_unreal_lib_noise_module.html#a5a0b6532fa31ea1e486df19e39d2b4eb',1,'FUnrealLibNoiseModule']]] ];
NovanMK2/UnrealLibNoise
Documentation/html/search/functions_9.js
JavaScript
lgpl-3.0
6,411
export default [ { name: 'hello-wold-functional', displayName: 'Hello World (functional)', directory: 'hello-world', files: ['hello-world-functional.js'] }, { name: 'hello-wold-class', displayName: 'Hello World (class component)', directory: 'hello-world', files: ['hello-world-class.js'] }, { name: 'clock', displayName: 'Clock', directory: 'clock', files: ['clock.js'] }, { name: 'simple-counter', displayName: 'Simple Counter', directory: 'counter', files: ['simple-counter.js'] }, { name: 'complex-counter', displayName: 'Complex Counter', directory: 'counter', files: ['complex-counter.js'] }, { name: 'injection', displayName: 'Injection', directory: 'injection', files: ['injection.js'] }, { name: 'i18n', displayName: 'Internationalization', directory: 'i18n', files: ['i18n.js'] } ];
js-works/js-scenery
boxroom/archive/js-reactify_2018-04-27/src/demo/available-demos.js
JavaScript
lgpl-3.0
1,074
var structshyft_1_1timeseries_1_1d__ref__t_3_01_t_00_01typename_01enable__if_3_01is__shared__ptr_3_0a96d8130ed21daa23ed2d27c0d825333 = [ [ "type", "structshyft_1_1timeseries_1_1d__ref__t_3_01_t_00_01typename_01enable__if_3_01is__shared__ptr_3_0a96d8130ed21daa23ed2d27c0d825333.html#a88ec5a232f62e1394dc393ac07b0096c", null ] ];
statkraft/shyft-doc
core/html/structshyft_1_1timeseries_1_1d__ref__t_3_01_t_00_01typename_01enable__if_3_01is__shared__ptr_3_0a96d8130ed21daa23ed2d27c0d825333.js
JavaScript
lgpl-3.0
331
/* * Copyright (C) 2021 Inera AB (http://www.inera.se) * * This file is part of sklintyg (https://github.com/sklintyg). * * sklintyg is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * sklintyg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ angular.module('StatisticsApp').directive('dataerrorview', function() { 'use strict'; return { restrict: 'A', transclude: true, replace: true, scope: { errorPageUrl: '=', showError: '=' }, templateUrl: '/components/directives/dataerrorview/dataerrorview.html' }; });
sklintyg/statistik
web/src/main/webapp/components/directives/dataerrorview/dataerrorview.directive.js
JavaScript
lgpl-3.0
1,078
Famono.scope('famous/surfaces/Gruntfile', ["load-grunt-tasks","time-grunt"], function(require, define) { define(function() { /*global module:false*/ /*Generated initially from grunt-init, heavily inspired by yo webapp*/ module.exports = function(grunt) { 'use strict'; // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Project configuration. grunt.initConfig({ eslint: { options: { config: '.eslintrc' }, target: ['*.js'] }, jscs: { src: ['*.js'], options: { config: '.jscsrc' } } }); grunt.registerTask('test', [ 'jscs', 'eslint' ]); grunt.registerTask('default', [ 'test' ]); }; }); });
ricardogarcia/responsive-webapp
AudienceTool/.meteor/.famono-base/lib/famous/surfaces/Gruntfile.js
JavaScript
lgpl-3.0
819
import getURL from '../utils/getURL.js' import getUserInfo from './getUserInfo.js' import people from './people.js' /** @name $SP().getManager @function @category people @description Return the manager for the provided user, as a People string @param {String} [username] With or without the domain, and you can also use an email address, and if you leave it empty it's the current user by default @param {Object} [setup] Options (see below) @param {String} [setup.url='current website'] The website url @return {Function} resolve(manager), reject(error) @example $SP().getManager("john_doe",{url:"http://my.si.te/subdir/"}) .then(function(manager) { console.log(manager); // 42;#Smith,, Jane,#i:0#.w|domain\Jane_Smith,#Jane_Smith@Domain.com,#Jane_Smith@Domain.com,#Smith,, Jane manager = $SP().getPeopleLookup(manager); console.log(manager.name); // "Smith, Jane" }) .catch(function(err) { console.log("Err => ",err) }); */ export default async function getManager(username, setup) { try { if (arguments.length===1 && typeof username === "object") { setup=username; username="" } // default values username = (username || ""); setup = setup || {}; if (!setup.url) { setup.url = await getURL.call(this); } let pres = await people.call(this, username, setup); let managerUserName = pres.Manager; if (!managerUserName.startsWith('i:0')) managerUserName = "i:0#.w|" + managerUserName; let res = await getUserInfo.call(this, managerUserName, setup); // "42;#Doe,, John,#i:0#.w|domain\John_Doe,#John_Doe@Domain.com,#John_Doe@Domain.com,#Doe,, John let displayName = res.Name.replace(/,/,",,"); return Promise.resolve(res.ID+";#"+displayName+",#"+managerUserName+",#"+res.Email+",#"+res.Email+",#"+displayName); } catch(err) { return Promise.reject(err); } }
Aymkdn/SharepointPlus
src/people/getManager.js
JavaScript
lgpl-3.0
1,871
/** * Copyright (C) 2005-2015 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ /** * @module aikauTesting/mockservices/ListMockService * @extends module:alfresco/core/Core * @author Dave Draper * @author Martin Doyle */ define([ "alfresco/core/Core", "alfresco/core/CoreXhr", "dojo/_base/array", "dojo/_base/declare", "dojo/_base/lang", "dojo/io-query", "service/constants/Default" ], function(AlfCore, CoreXhr, array, declare, lang, ioQuery, AlfConstants) { return declare([AlfCore, CoreXhr], { /** * Constructor * * @instance */ constructor: function alfresco_testing_mockservices_ListMockService__constructor() { this.alfSubscribe("ALF_RETRIEVE_DOCUMENTS_REQUEST", lang.hitch(this, this.onRetrieveDocumentsRequest)); }, /** * Handle document retrieval requests * * @instance */ onRetrieveDocumentsRequest: function alfresco_testing_mockservices_ListMockService__onRetrieveDocumentsRequest(payload) { // Setup the request parameters object var filterKeys = (payload.dataFilters && Object.keys(payload.dataFilters)) || [], filters = filterKeys.map(function(filterKey) { var filter = payload.dataFilters[filterKey]; return filter.name + "|" + filter.value; }).join(), pageNum = payload.page || 1, pageSize = payload.pageSize || 0, startIndex = (pageNum - 1) * pageSize; // Setup request params var requestParams = {}; if (startIndex) { requestParams.startIndex = startIndex; } if (pageSize) { requestParams.pageSize = pageSize; } if (filters) { requestParams.filters = filters; } // Make an XHR var serviceUrl = AlfConstants.URL_SERVICECONTEXT + "mockdata/list"; if (Object.keys(requestParams).length) { serviceUrl += "?" + ioQuery.objectToQuery(requestParams); } this.serviceXhr({ alfTopic: payload.alfResponseTopic, url: serviceUrl, method: "GET", callbackScope: this }); } }); });
nzheyuti/Aikau
aikau/src/test/resources/testApp/js/aikau/testing/mockservices/ListMockService.js
JavaScript
lgpl-3.0
3,106
var cats; (function (cats) { 'use strict'; var initModule = function () { }; var getCat = function () { return "tabby"; }; cats.model = { initModule: initModule, getCat: getCat }; })(cats || (cats = {}));
henrjk/ts-js-module-pattern
app/cats.model.js
JavaScript
unlicense
270
(function($, window, document, undefined) { 'use strict'; var gridContainer = $('#grid-container'), filtersContainer = $('#filters-container'), wrap, filtersCallback; /********************************* init cubeportfolio *********************************/ gridContainer.cubeportfolio({ layoutMode: 'grid', rewindNav: true, scrollByPage: false, defaultFilter: '*', animationType: 'slideLeft', gapHorizontal: 0, gapVertical: 0, gridAdjustment: 'responsive', mediaQueries: [{ width: 800, cols: 2 }, { width: 500, cols: 2 }, { width: 320, cols: 1 }], caption: 'zoom', displayType: 'lazyLoading', displayTypeSpeed: 100 }); /********************************* add listener for filters *********************************/ if (filtersContainer.hasClass('cbp-l-filters-dropdown')) { wrap = filtersContainer.find('.cbp-l-filters-dropdownWrap'); wrap.on({ 'http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseover.cbp': function() { wrap.addClass('cbp-l-filters-dropdownWrap-open'); }, 'http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseleave.cbp': function() { wrap.removeClass('cbp-l-filters-dropdownWrap-open'); } }); filtersCallback = function(me) { wrap.find('.cbp-filter-item').removeClass('cbp-filter-item-active'); wrap.find('.cbp-l-filters-dropdownHeader').text(me.text()); me.addClass('cbp-filter-item-active'); wrap.trigger('http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseleave.cbp'); }; } else { filtersCallback = function(me) { me.addClass('cbp-filter-item-active').siblings().removeClass('cbp-filter-item-active'); }; } filtersContainer.on('http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/click.cbp', '.cbp-filter-item', function() { var me = $(this); if (me.hasClass('cbp-filter-item-active')) { return; } // get cubeportfolio data and check if is still animating (reposition) the items. if (!$.data(gridContainer[0], 'cubeportfolio').isAnimating) { filtersCallback.call(null, me); } // filter the items gridContainer.cubeportfolio('filter', me.data('filter'), function() {}); }); /********************************* activate counter for filters *********************************/ gridContainer.cubeportfolio('showCounter', filtersContainer.find('.cbp-filter-item'), function() { // read from url and change filter active var match = /#cbpf=(.*?)([#|?&]|$)/gi.exec(location.href), item; if (match !== null) { item = filtersContainer.find('.cbp-filter-item').filter('[data-filter="' + match[1] + '"]'); if (item.length) { filtersCallback.call(null, item); } } }); })(jQuery, window, document);
master-zhuang/SearchMax
backend/handler/web/assets/js/plugins/cube-portfolio/cube-portfolio-2-ns.js
JavaScript
unlicense
3,401
// LauncherOSX // // Created by Boris Schneiderman. // Copyright (c) 2012-2013 The Readium Foundation. // // The Readium SDK is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * Top level ReadiumSDK namespace * @class ReadiumSDK * @static */ ReadiumSDK = { /** Current version of the JS SDK @method version @static @return {string} version */ version: function() { return "0.8.0"; }, Models : { Smil: {} }, Views : {}, Collections: {}, Routers: {}, Helpers: {} }; _.extend(ReadiumSDK, Backbone.Events);
bjctw/SDKLauncher-Linux-Qt
res/host_app/js/readium_sdk.js
JavaScript
unlicense
1,213
/*! Waypoints - 4.0.0 Copyright © 2011-2015 Caleb Troughton Licensed under the MIT license. https://github.com/imakewebthings/waypoints/blog/master/licenses.txt */ ! function () { "use strict"; function t(o) { if (!o) throw new Error("No options passed to Waypoint constructor"); if (!o.element) throw new Error("No element option passed to Waypoint constructor"); if (!o.handler) throw new Error("No handler option passed to Waypoint constructor"); this.key = "waypoint-" + e, this.options = t.Adapter.extend({}, t.defaults, o), this.element = this.options.element, this.adapter = new t.Adapter(this.element), this.callback = o.handler, this.axis = this.options.horizontal ? "horizontal" : "vertical", this.enabled = this.options.enabled, this.triggerPoint = null, this.group = t.Group.findOrCreate({ name: this.options.group , axis: this.axis }), this.context = t.Context.findOrCreateByElement(this.options.context), t.offsetAliases[this.options.offset] && (this.options.offset = t.offsetAliases[this.options.offset]), this.group.add(this), this.context.add(this), i[this.key] = this, e += 1 } var e = 0 , i = {}; t.prototype.queueTrigger = function (t) { this.group.queueTrigger(this, t) }, t.prototype.trigger = function (t) { this.enabled && this.callback && this.callback.apply(this, t) }, t.prototype.destroy = function () { this.context.remove(this), this.group.remove(this), delete i[this.key] }, t.prototype.disable = function () { return this.enabled = !1, this }, t.prototype.enable = function () { return this.context.refresh(), this.enabled = !0, this }, t.prototype.next = function () { return this.group.next(this) }, t.prototype.previous = function () { return this.group.previous(this) }, t.invokeAll = function (t) { var e = []; for (var o in i) e.push(i[o]); for (var n = 0, r = e.length; r > n; n++) e[n][t]() }, t.destroyAll = function () { t.invokeAll("destroy") }, t.disableAll = function () { t.invokeAll("disable") }, t.enableAll = function () { t.invokeAll("enable") }, t.refreshAll = function () { t.Context.refreshAll() }, t.viewportHeight = function () { return window.innerHeight || document.documentElement.clientHeight }, t.viewportWidth = function () { return document.documentElement.clientWidth }, t.adapters = [], t.defaults = { context: window , continuous: !0 , enabled: !0 , group: "default" , horizontal: !1 , offset: 0 }, t.offsetAliases = { "bottom-in-view": function () { return this.context.innerHeight() - this.adapter.outerHeight() } , "right-in-view": function () { return this.context.innerWidth() - this.adapter.outerWidth() } }, window.Waypoint = t }() , function () { "use strict"; function t(t) { window.setTimeout(t, 1e3 / 60) } function e(t) { this.element = t, this.Adapter = n.Adapter, this.adapter = new this.Adapter(t), this.key = "waypoint-context-" + i, this.didScroll = !1, this.didResize = !1, this.oldScroll = { x: this.adapter.scrollLeft() , y: this.adapter.scrollTop() }, this.waypoints = { vertical: {} , horizontal: {} }, t.waypointContextKey = this.key, o[t.waypointContextKey] = this, i += 1, this.createThrottledScrollHandler(), this.createThrottledResizeHandler() } var i = 0 , o = {} , n = window.Waypoint , r = window.onload; e.prototype.add = function (t) { var e = t.options.horizontal ? "horizontal" : "vertical"; this.waypoints[e][t.key] = t, this.refresh() }, e.prototype.checkEmpty = function () { var t = this.Adapter.isEmptyObject(this.waypoints.horizontal) , e = this.Adapter.isEmptyObject(this.waypoints.vertical); t && e && (this.adapter.off(".waypoints"), delete o[this.key]) }, e.prototype.createThrottledResizeHandler = function () { function t() { e.handleResize(), e.didResize = !1 } var e = this; this.adapter.on("resize.waypoints", function () { e.didResize || (e.didResize = !0, n.requestAnimationFrame(t)) }) }, e.prototype.createThrottledScrollHandler = function () { function t() { e.handleScroll(), e.didScroll = !1 } var e = this; this.adapter.on("scroll.waypoints", function () { (!e.didScroll || n.isTouch) && (e.didScroll = !0, n.requestAnimationFrame(t)) }) }, e.prototype.handleResize = function () { n.Context.refreshAll() }, e.prototype.handleScroll = function () { var t = {} , e = { horizontal: { newScroll: this.adapter.scrollLeft() , oldScroll: this.oldScroll.x , forward: "right" , backward: "left" } , vertical: { newScroll: this.adapter.scrollTop() , oldScroll: this.oldScroll.y , forward: "down" , backward: "up" } }; for (var i in e) { var o = e[i] , n = o.newScroll > o.oldScroll , r = n ? o.forward : o.backward; for (var s in this.waypoints[i]) { var a = this.waypoints[i][s] , l = o.oldScroll < a.triggerPoint , h = o.newScroll >= a.triggerPoint , p = l && h , u = !l && !h; (p || u) && (a.queueTrigger(r), t[a.group.id] = a.group) } } for (var c in t) t[c].flushTriggers(); this.oldScroll = { x: e.horizontal.newScroll , y: e.vertical.newScroll } }, e.prototype.innerHeight = function () { return this.element == this.element.window ? n.viewportHeight() : this.adapter.innerHeight() }, e.prototype.remove = function (t) { delete this.waypoints[t.axis][t.key], this.checkEmpty() }, e.prototype.innerWidth = function () { return this.element == this.element.window ? n.viewportWidth() : this.adapter.innerWidth() }, e.prototype.destroy = function () { var t = []; for (var e in this.waypoints) for (var i in this.waypoints[e]) t.push(this.waypoints[e][i]); for (var o = 0, n = t.length; n > o; o++) t[o].destroy() }, e.prototype.refresh = function () { var t, e = this.element == this.element.window , i = e ? void 0 : this.adapter.offset() , o = {}; this.handleScroll(), t = { horizontal: { contextOffset: e ? 0 : i.left , contextScroll: e ? 0 : this.oldScroll.x , contextDimension: this.innerWidth() , oldScroll: this.oldScroll.x , forward: "right" , backward: "left" , offsetProp: "left" } , vertical: { contextOffset: e ? 0 : i.top , contextScroll: e ? 0 : this.oldScroll.y , contextDimension: this.innerHeight() , oldScroll: this.oldScroll.y , forward: "down" , backward: "up" , offsetProp: "top" } }; for (var r in t) { var s = t[r]; for (var a in this.waypoints[r]) { var l, h, p, u, c, d = this.waypoints[r][a] , f = d.options.offset , w = d.triggerPoint , y = 0 , g = null == w; d.element !== d.element.window && (y = d.adapter.offset()[s.offsetProp]), "function" == typeof f ? f = f.apply(d) : "string" == typeof f && (f = parseFloat(f), d.options.offset.indexOf("%") > -1 && (f = Math.ceil(s.contextDimension * f / 100))), l = s.contextScroll - s.contextOffset, d.triggerPoint = y + l - f, h = w < s.oldScroll, p = d.triggerPoint >= s.oldScroll, u = h && p, c = !h && !p, !g && u ? (d.queueTrigger(s.backward), o[d.group.id] = d.group) : !g && c ? (d.queueTrigger(s.forward), o[d.group.id] = d.group) : g && s.oldScroll >= d.triggerPoint && (d.queueTrigger(s.forward), o[d.group.id] = d.group) } } return n.requestAnimationFrame(function () { for (var t in o) o[t].flushTriggers() }), this }, e.findOrCreateByElement = function (t) { return e.findByElement(t) || new e(t) }, e.refreshAll = function () { for (var t in o) o[t].refresh() }, e.findByElement = function (t) { return o[t.waypointContextKey] }, window.onload = function () { r && r(), e.refreshAll() }, n.requestAnimationFrame = function (e) { var i = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || t; i.call(window, e) }, n.Context = e }() , function () { "use strict"; function t(t, e) { return t.triggerPoint - e.triggerPoint } function e(t, e) { return e.triggerPoint - t.triggerPoint } function i(t) { this.name = t.name, this.axis = t.axis, this.id = this.name + "-" + this.axis, this.waypoints = [], this.clearTriggerQueues(), o[this.axis][this.name] = this } var o = { vertical: {} , horizontal: {} } , n = window.Waypoint; i.prototype.add = function (t) { this.waypoints.push(t) }, i.prototype.clearTriggerQueues = function () { this.triggerQueues = { up: [] , down: [] , left: [] , right: [] } }, i.prototype.flushTriggers = function () { for (var i in this.triggerQueues) { var o = this.triggerQueues[i] , n = "up" === i || "left" === i; o.sort(n ? e : t); for (var r = 0, s = o.length; s > r; r += 1) { var a = o[r]; (a.options.continuous || r === o.length - 1) && a.trigger([i]) } } this.clearTriggerQueues() }, i.prototype.next = function (e) { this.waypoints.sort(t); var i = n.Adapter.inArray(e, this.waypoints) , o = i === this.waypoints.length - 1; return o ? null : this.waypoints[i + 1] }, i.prototype.previous = function (e) { this.waypoints.sort(t); var i = n.Adapter.inArray(e, this.waypoints); return i ? this.waypoints[i - 1] : null }, i.prototype.queueTrigger = function (t, e) { this.triggerQueues[e].push(t) }, i.prototype.remove = function (t) { var e = n.Adapter.inArray(t, this.waypoints); e > -1 && this.waypoints.splice(e, 1) }, i.prototype.first = function () { return this.waypoints[0] }, i.prototype.last = function () { return this.waypoints[this.waypoints.length - 1] }, i.findOrCreate = function (t) { return o[t.axis][t.name] || new i(t) }, n.Group = i }() , function () { "use strict"; function t(t) { this.$element = e(t) } var e = window.jQuery , i = window.Waypoint; e.each(["innerHeight", "innerWidth", "off", "offset", "on", "outerHeight", "outerWidth", "scrollLeft", "scrollTop"], function (e, i) { t.prototype[i] = function () { var t = Array.prototype.slice.call(arguments); return this.$element[i].apply(this.$element, t) } }), e.each(["extend", "inArray", "isEmptyObject"], function (i, o) { t[o] = e[o] }), i.adapters.push({ name: "jquery" , Adapter: t }), i.Adapter = t }() , function () { "use strict"; function t(t) { return function () { var i = [] , o = arguments[0]; return t.isFunction(arguments[0]) && (o = t.extend({}, arguments[1]), o.handler = arguments[0]), this.each(function () { var n = t.extend({}, o, { element: this }); "string" == typeof n.context && (n.context = t(this).closest(n.context)[0]), i.push(new e(n)) }), i } } var e = window.Waypoint; window.jQuery && (window.jQuery.fn.waypoint = t(window.jQuery)), window.Zepto && (window.Zepto.fn.waypoint = t(window.Zepto)) }();
jvaane/www
js/jquery.waypoints.min.js
JavaScript
unlicense
12,699
import { Application } from 'spectron'; import electron from 'electron-prebuilt'; import { assert } from 'chai'; import MockServer from '../util/mock-server'; import items from '../test-cases/items'; import models from '../test-cases/models'; describe('Creating an Item', function () { this.timeout(10000); let app; let mockServer = new MockServer(); before(() => { app = new Application({ path: electron, args: ['index.js', '--port=8080'] }); return app.start().then(() => { return mockServer.start(8080); }); }); beforeEach(() => { mockServer.clearExpectations(); }); it('creates a new item', () => { mockServer.expect({ method: 'get', endpoint: 'item/all', response: { status: 'success', data: { items: items.slice(0, 3) } } }); mockServer.expect({ method: 'get', endpoint: 'model/all', response: { status: 'success', data: { models } } }); mockServer.expect({ method: 'get', endpoint: 'model/all', response: { status: 'success', data: { models } } }); mockServer.expect({ method: 'post', endpoint: 'item', json: { modelAddress: models[0].address }, response: { status: 'success', data: { address: 'iGwEZVvgu', modelName: 'Resistor' } } }); models[0].count ++; return app.client.click('#view-items').then(() => { return app.client.waitForVisible('#items', 5000); }).then(() => { return app.client.click('#items button'); }).then(() => { return app.client.waitForVisible('.create-item-form', 1000); }).then(() => { return app.client.getValue('.create-item-form select option'); }).then(vals => { assert.include(vals, models[0].address); assert.include(vals, models[1].address); return app.client.selectByValue('.create-item-form select', models[0].address); }).then(() => { return app.client.submitForm('.create-item-form form'); }).then(() => { return app.client.waitForVisible('.toast', 2500); }).then(() => { return app.client.getText('.toast'); }).then(text => { assert.strictEqual(text, 'New item added: Resistor (iGwEZVvgu)'); return app.client.click('.toast'); }).then(() => { return app.client.waitForVisible('.toast', 10000, true); }).then(() => { return app.client.elements('#items .item'); }).then(elements => { assert.lengthOf(elements.value, 3); mockServer.validate(); }); }); it('tells the user to select a model', () => { mockServer.expect({ method: 'get', endpoint: 'item/all', response: { status: 'success', data: { items: items.slice(0, 4) } } }); mockServer.expect({ method: 'get', endpoint: 'model/all', response: { status: 'success', data: { models } } }); mockServer.expect({ method: 'get', endpoint: 'model/all', response: { status: 'success', data: { models } } }); mockServer.expect({ method: 'post', endpoint: 'item', json: { modelAddress: models[1].address }, response: { status: 'success', data: { address: 'iGwEZW6nn', modelName: 'Transistor' } } }); models[1].count ++; return app.client.click('#omnibar img').then(() => { return app.client.click('#view-items'); }).then(() => { return app.client.waitForVisible('#items', 5000); }).then(() => { return app.client.click('#items button'); }).then(() => { return app.client.waitForVisible('.create-item-form', 1000); }).then(() => { return app.client.submitForm('.create-item-form form'); }).then(() => { return app.client.waitForVisible('.toast', 1000); }).then(() => { return app.client.getText('.toast'); }).then(text => { assert.strictEqual(text, 'Please select a model.'); return app.client.click('.toast'); }).then(() => { return app.client.waitForVisible('.toast', 10000, true); }).then(() => { return app.client.getValue('.create-item-form select option'); }).then(vals => { assert.include(vals, models[0].address); assert.include(vals, models[1].address); return app.client.selectByValue('.create-item-form select', models[1].address); }).then(() => { return app.client.submitForm('.create-item-form form'); }).then(() => { return app.client.waitForVisible('.toast', 2500); }).then(() => { return app.client.getText('.toast'); }).then(text => { assert.strictEqual(text, 'New item added: Transistor (iGwEZW6nn)'); return app.client.click('.toast'); }).then(() => { return app.client.waitForVisible('.toast', 10000, true); }).then(() => { return app.client.elements('#items .item'); }).then(elements => { assert.lengthOf(elements.value, 4); mockServer.validate(); }); }); it('creates another new item', () => { mockServer.expect({ method: 'get', endpoint: 'model/all', response: { status: 'success', data: { models } } }); mockServer.expect({ method: 'get', endpoint: 'model/all', response: { status: 'success', data: { models } } }); mockServer.expect({ method: 'post', endpoint: 'item', json: { modelAddress: models[1].address }, response: { status: 'success', data: { address: 'iGwEZWXhn', modelName: 'Transistor' } } }); models[1].count ++; return app.client.waitForVisible('#items', 5000).then(() => { return app.client.click('#items button'); }).then(() => { return app.client.waitForVisible('.create-item-form', 1000); }).then(() => { return app.client.getValue('.create-item-form select option'); }).then(vals => { assert.include(vals, models[0].address); assert.include(vals, models[1].address); return app.client.selectByValue('.create-item-form select', models[1].address); }).then(() => { return app.client.submitForm('.create-item-form form'); }).then(() => { return app.client.waitForVisible('.toast', 2500); }).then(() => { return app.client.getText('.toast'); }).then(text => { assert.strictEqual(text, 'New item added: Transistor (iGwEZWXhn)'); return app.client.click('.toast'); }).then(() => { return app.client.waitForVisible('.toast', 10000, true); }).then(() => { return app.client.elements('#items .item'); }).then(elements => { assert.lengthOf(elements.value, 4); mockServer.validate(); }); }); after(() => { if (app && app.isRunning()) { return app.stop().then(() => { return mockServer.stop(); }); } }); });
TheFourFifths/consus-client
test/functional/create-item.js
JavaScript
unlicense
8,677
var Base64 = new function() { this.encode = function(string) { return window.btoa(string); }; this.urlSafeEncode = function(string) { return this.encode(string).replace('+', '-').replace('/', '_'); }; this.decode = function(base64) { try { return window.atob(base64.replace('-', '+').replace('_', '/')); } catch(err) { return ''; } }; } var AsciiHex = new function() { this.encode = function(string) { var hexString = ''; string.split('').forEach(function(b) { hexString += b.charCodeAt(0).toString(16); }); return hexString; }; this.decode = function(string) { if (string.match(/^[a-f0-9]+$/) !== null) { var decodedString = '' string.match(/.{1,2}/g).forEach(function(b) { decodedString += String.fromCharCode(parseInt(b, 16)); }); return decodedString; } else { return ''; } } } var UrlEncode = new function() { this.encode = function(string) { return window.escape(string); }; this.encodeAll = function(string) { encodedString = ''; string.split('').forEach(function(b) { b = b.charCodeAt(0).toString(16).toUpperCase(); if (b.length === 1) { b = '0' + b; } encodedString += '%' + b; }); return encodedString; }; this.decode = function(string) { return window.unescape(string); } } var HtmlEntity = new function() { this.escape = function(string) { var escapedString = ''; string.split('').forEach(function(b) { escapedString += '&#x' + b.charCodeAt(0).toString(16) + ';'; }); return escapedString; }; this.unescape = function(string) { return $('<div />').html(string).text(); }; } var BitFlip = new function() { this.rint = function (max) { return Math.floor(Math.random() * max); }; this.flip = function(input) { var where = this.rint(input.length); return input.substring(0, where) + String.fromCharCode((input.charCodeAt(where)) ^ (Math.pow(2, this.rint(8)))) + input.substring(where + 1,input.length + 1); } } var HMAC = new function() { this.hash = function(input, secret, messageDigest) { if (input === '' || secret === '' || messageDigest === '') { return ''; } switch (messageDigest) { case 'sha1': var hash = CryptoJS.HmacSHA1(input, secret); break; case 'sha256': var hash = CryptoJS.HmacSHA256(input, secret); break; case 'sha512': var hash = CryptoJS.HmacSHA512(input, secret); break; default: var hash = CryptoJS.HmacMD5(input, secret); break; } return hash.toString(); }; } var Beautify = new function() { this.json = function(code, callback) { try { json = JSON.parse(code); formattedJson = JSON.stringify(json, null, 2); Rainbow.color(formattedJson, 'javascript', function(highlightedJson) { callback(highlightedJson); }); } catch (err) { callback(null); } }; this.javascript = function(code, callback) { try { var deobfuscatedJavascript = this.deobfuscateJavascript(code); var formattedJavascript = js_beautify(deobfuscatedJavascript, { 'indent_size': 2, 'indent_char': ' ' }); Rainbow.color(formattedJavascript, 'javascript', function(highlightedJavascript) { callback(highlightedJavascript); }); } catch (err) { callback(null); } }; this.html = function(code, callback) { try { var formattedHtml = html_beautify(code, { 'indent_size': 2, 'indent_char': ' ' }); Rainbow.color(formattedHtml, 'html', function(highlightedHtml) { callback(highlightedHtml); }); } catch (err) { callback(null); } }; this.css = function(code, callback) { try { var formattedCss = css_beautify(code, { 'indent_size': 2, 'indent_char': ' ' }); Rainbow.color(formattedCss, 'css', function(highlightedCss) { callback(highlightedCss); }); } catch (err) { callback(null); } }; this.deobfuscateJavascript = function(code) { if (JavascriptObfuscator.detect(code)) { console.log('Obfuscation detected'); return JavascriptObfuscator.unpack(code); } else if (MyObfuscate.detect(code)) { return MyObfuscate.unpack(code); } else if (P_A_C_K_E_R.detect(code)) { return P_A_C_K_E_R.unpack(code); } else if (Urlencoded.detect(code)) { return Urlencoded.unpack(code); } return code; }; } var TabController = new function() { this.render = function(tab, input) { switch (tab) { case 'encoding': this.renderEncodingTab(input); break; case 'decoding': this.renderDecodingTab(input); break; case 'hashing': this.renderHashingTab(input); break; case 'beautifying': this.renderBeautifyingTab(input); break; case 'misc': this.renderMiscTab(input); break; } }; this.renderEncodingTab = function(input) { if ($('#url_safe_base64').is(':checked')) { $('#base64_encoding').val(Base64.urlSafeEncode(input)); } else { $('#base64_encoding').val(Base64.encode(input)); } if ($('#url_encode_all').is(':checked')) { $('#url_encoding').val(UrlEncode.encodeAll(input)); } else { $('#url_encoding').val(UrlEncode.encode(input)); } $('#ascii_hex_encoding').val(AsciiHex.encode(input)); $('#html_entity_escaping').val(HtmlEntity.escape(input)); }; this.renderDecodingTab = function(input) { $('#base64_decoding').val(Base64.decode(input)); $('#url_decoding').val(UrlEncode.decode(input)); $('#ascii_hex_decoding').val(AsciiHex.decode(input)); $('#html_entity_unescaping').val(HtmlEntity.unescape(input)); }; this.renderHashingTab = function(input) { if (input !== '') { $('#md5_hashing').val(CryptoJS.MD5(input).toString()); $('#sha1_hashing').val(CryptoJS.SHA1(input).toString()); $('#sha256_hashing').val(CryptoJS.SHA256(input).toString()); $('#hmac_hashing').val(HMAC.hash(input, $('#hmac_hashing_secret').val(), $('#hmac_hashing_message_digest').val())); } } this.renderBeautifyingTab = function(input) { }; this.renderMiscTab = function(input) { $('#uppercasing').val(input.toUpperCase()); $('#lowercasing').val(input.toLowerCase()); $('#reversed').val(input.split('').reverse().join('')); $('#bit_flipping').val(BitFlip.flip(input)); }; } $(document).ready(function() { $('.use-as-input').tooltip({ 'placement': 'left', 'title': 'Transfer to input field' }); $('.view-larger').tooltip({ 'placement': 'left', 'title': 'View output in bigger window' }); $("#input").on('focus', function() { $(this).select(); }); $('#input').on('textchange', function() { var input = $(this).val(); var currentTab = $('.nav.nav-tabs li.active').attr('data-tab'); TabController.render(currentTab, input); }); $('.nav.nav-tabs li a').on('click', function() { var input = $('#input').val(); var currentTab = $(this).closest('li').attr('data-tab'); TabController.render(currentTab, input); }); $('#url_safe_base64').on('click', function() { if ($(this).is(':checked')) { $('#base64_encoding').val(Base64.urlSafeEncode($('#input').val())); } else { $('#base64_encoding').val(Base64.encode($('#input').val())); } }); $('#url_encode_all').on('click', function() { if ($(this).is(':checked')) { $('#url_encoding').val(UrlEncode.encodeAll($('#input').val())); } else { $('#url_encoding').val(UrlEncode.encode($('#input').val())); } }); $('.use-as-input').on('click', function(e) { e.preventDefault(); var value = $($(this).attr('data-target')).val(); if (value !== '') { $('#input').val(value); var currentTab = $('.nav.nav-tabs li.active').attr('data-tab'); TabController.render(currentTab, value); } }); $('.view-larger').on('click', function(e) { e.preventDefault(); var target = $($(this).attr('data-target')); if ($(target).is('pre')) { var modalBody = $('<pre />').addClass('output-field large').html($(target).html()); } else { var modalBody = $('<textarea readonly />').addClass('output-field large').val($(target).val()); } $('#view-larger-modal .modal-body').html(modalBody); $('#view-larger-modal').modal('show'); }); $('#hmac_hashing_secret').on('textchange', function() { $('#hmac_hashing').val(HMAC.hash($('#input').val(), $('#hmac_hashing_secret').val(), $('#hmac_hashing_message_digest').val())); }); $('#hmac_hashing_message_digest').on('change', function() { $('#hmac_hashing').val(HMAC.hash($('#input').val(), $('#hmac_hashing_secret').val(), $('#hmac_hashing_message_digest').val())); }); $('#beautify_javascript').on('click', function(e) { e.preventDefault(); code = $('#input').val(); if (code !== '') { $('#javascript_beautifying_container .loader').css('display', 'inline-block'); setTimeout(function() { Beautify.javascript(code, function(beautified) { $('#javascript_beautifying_container .loader').css('display', 'none'); if (beautified !== null) { $('#javascript_beautifying').html(beautified); } else { $('#javascript_beautifying').html('<p>Invalid Javascript.</p>'); } }); }, 100); } }); $('#beautify_json').on('click', function(e) { e.preventDefault(); code = $('#input').val(); if (code !== '') { $('#json_beautifying_container .loader').css('display', 'inline-block'); setTimeout(function() { Beautify.json(code, function(beautified) { $('#json_beautifying_container .loader').css('display', 'none'); if (beautified !== null) { $('#json_beautifying').html(beautified); } else { $('#json_beautifying').html('<p>Invalid JSON.</p>'); } }); }, 100); } }); $('#beautify_html').on('click', function(e) { e.preventDefault(); code = $('#input').val(); if (code !== '') { $('#html_beautifying_container .loader').css('display', 'inline-block'); setTimeout(function() { Beautify.html(code, function(beautified) { $('#html_beautifying_container .loader').css('display', 'none'); if (beautified !== null) { $('#html_beautifying').html(beautified); } else { $('#html_beautifying').html('<p>Invalid HTML.</p>'); } }); }, 100); } }); $('#beautify_css').on('click', function(e) { e.preventDefault(); code = $('#input').val(); if (code !== '') { $('#css_beautifying_container .loader').css('display', 'inline-block'); setTimeout(function() { Beautify.css(code, function(beautified) { $('#css_beautifying_container .loader').css('display', 'none'); if (beautified !== null) { $('#css_beautifying').html(beautified); } else { $('#css_beautifying').html('<p>Invalid CSS.</p>'); } }); }, 100); } }); $('#flip_again').on('click', function(e) { e.preventDefault(); $('#bit_flipping').val(BitFlip.flip($('#input').val())); }); $('#input').focus(); });
michenriksen/hackpad
assets/javascripts/application.js
JavaScript
unlicense
11,479
// ==UserScript== // @name Discussion Board Patch // @namespace https://lms.rmit.edu.au/webapps/discussionboard // @version 3 // @grant none // @match https://lms.rmit.edu.au/webapps/discussionboard/do/message* // @match https://lms.rmit.edu.au/webapps/discussionboard/do/forum* // @match https://lms.rmit.edu.au/webapps/discussionboard/do/conference* // ==/UserScript== /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * Summary: * * Patches the discussion board. * * * * Author(s): * * Steven David GRUEBER * * Shyam NATH - "Shyam Has Your Anomaly Mitigated! :D" (recursive bacronym)* * * * Last Modified: * * 2015-01-26 03:58:06 * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /****************************************************************************** * Function retrieves the element with the ID of string. * * Trevor Reynolds posted this in the Web Programming discussion board. * ******************************************************************************/ function getId(string) { return document.getElementById(string); } /****************************************************************************** * Function retrieves the elements with the class of string. * ******************************************************************************/ function getClass(string) { return document.getElementsByClassName(string); } /****************************************************************************** * Hides the white bar from the top of the page, along with a usability * * feature. * * * * The button with the ID "appTabList" would be useful to keep on screen... * * http://stackoverflow.com/a/18681207 * * ...For the next update! :D * ******************************************************************************/ var obtrusiveHeader = getId("globalNavPageNavArea"); obtrusiveHeader.style.display = 'none'; /****************************************************************************** * Allows the vertical scroll position to increment as the content area is * * essentially framed, allowing posts to be automatically marked as read, * * posts must be in the expanded state for the autonomous marking to occur. * * The auto_mark_read.js file is responsible for this functionality. * ******************************************************************************/ var contentArea = getId("globalNavPageContentArea"); contentArea.style.overflow = 'visible'; contentArea.style.height = '100%'; /****************************************************************************** * Forces posts to expand as the user scrolls over them. * ******************************************************************************/ window.addEventListener("scroll", expandAllMessagesInTheTree, false); /****************************************************************************** * Keeps the useful side-bar navigational tool on the screen at all times. * * * * Fails to work on the "conference" pages for unkown reasons.* * Manual input from the console behaves predictably though... * ******************************************************************************/ var navBox = getId("navigationPane"); navBox.style.position = 'fixed'; navBox.style.top = '55px'; /****************************************************************************** * Keeps the Quick Links attached to the useful side-bar navigational tool. * * * * Fails to work on the "conference" pages for unkown reasons.* * Manual input from the console behaves predictably though... * ******************************************************************************/ var quickLinks = getId("quick_links_wrap"); quickLinks.style.position = 'fixed'; quickLinks.style.top = '55px'; /****************************************************************************** * Keeps the drop-down menu and logout buttons on the screen in the top-right * * corner. * * * * Fails to work on the "conference" pages for unkown reasons.* * Manual input from the console behaves predictably though... * ******************************************************************************/ var buttons = getClass("global-nav-bar-wrap"); buttons[0].style.position = 'fixed'; buttons[0].style.top = '0px'; buttons[0].style.right = '0px'; /****************************************************************************** * One of these could be used to make the Help button more visible. * * But it adds a secondary scroll bar... * ******************************************************************************/ //document.body.style.paddingTop = '10px'; //document.body.style.marginTop = '10px'; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * G+ Student Group: https://plus.google.com/communities/106999491150778386594* * * * RMIT * * OUA * * Bachelor * * Of * * Technology * * Students * * * We are Robots. We are Students. We do not plagiarise. We do not cheat. Employ us! ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
ROBOTS-WAREZ/Discussion-Board-Patch.js
DBP.user.js
JavaScript
unlicense
6,943
import { categorySave, categorySortSave, categoryDel, categoryGetById, categoryGetList } from '../platformApi'; const categoryModule = { namespaced: true, state: { loading: false, }, mutations: { setLoading(state, val) { state.loading = val; }, }, actions: { async getList(ctx, params) { ctx.commit("setLoading", true); let nParams = Object.assign({}, params); let result = await categoryGetList(nParams); ctx.commit("setLoading", false); return result; }, async save(ctx, params) { ctx.commit("setLoading", true); let result = await categorySave(params); ctx.commit("setLoading", false); return result; }, async sortSave(ctx, params) { ctx.commit("setLoading", true); let result = await categorySortSave(params); ctx.commit("setLoading", false); return result; }, async del(ctx, params) { ctx.commit("setLoading", true); let result = await categoryDel(params); ctx.commit("setLoading", false); return result; }, async getById(ctx, params) { ctx.commit("setLoading", true); let result = await categoryGetById(params); ctx.commit("setLoading", false); return result; }, } } export default categoryModule;
lesenro/ggcms-CSharp
VueAdmin/src/modules/category.js
JavaScript
apache-2.0
1,521
import { isObject, isFunction, keys } from 'lodash'; // Removes all functions in an object so you can test // against objects without errors export const withoutFunctions = (obj) => { if (!isObject(obj)) { return obj; } let temp = {} const _keys = keys(obj) _keys.forEach((k) => { if (isObject(obj[k])) { temp[k] = withoutFunctions(obj[k]); } else if (isFunction(obj[k])) { temp[k] = null; } else { temp[k] = obj[k]; } }); return temp; }
veritone/veritone-sdk
packages/veritone-widgets/test/helpers/utils.js
JavaScript
apache-2.0
490
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* Load top 5 recommendations */ function loadTopRecommendations() { // Get category, costRating and crowdRating from user input radio buttons const chosenCategory = document.querySelector('input[name="recommendation-category"]:checked').value; const preferredCost = document.querySelector('input[name="price"]:checked').value; const preferredCrowd = document.querySelector('input[name="crowd"]:checked').value; const url = "recommender?category=" + chosenCategory +"&cost-rating=" + preferredCost +"&crowd-rating=" + preferredCrowd; fetch(url).then(response => response.json()).then((recommendations) => { displayRecommendation(recommendations); }); } /* Update HTML to display recommendation */ function displayRecommendation(recommendations) { const topRecommendationsList = document.getElementById("top-recommendations-list"); topRecommendationsList.innerHTML = ""; for (var i = 0; i < recommendations.length; i++) { const recommendationBox = document.createElement("div"); recommendationBox.className = "recommendation-box"; // if highest recommendation, label with 'Most Recommended' in the HTML if (i == 0) { recommendationBox.innerHTML = "<p class=\"top-recommendation\">Most Recommended</p>"; } const recommendation = recommendations[i]; const nameHTML = "<h3><b>#" + (i + 1) + " " + recommendation.name + "</b></h3>"; const locationHTML = "<p>latitiude: " + recommendation.lat + ", longitude: " + recommendation.lng + "</p>"; const ratingHTML = "<p>crowd: " + recommendation.crowdRating + "/5, price: " + recommendation.costRating + "/5</p>"; const descriptionHTML = "<p>" + recommendation.description + "</p>"; recommendationBox.innerHTML += nameHTML + locationHTML + ratingHTML + descriptionHTML; topRecommendationsList.append(recommendationBox); } }
googleinterns/step241-2020
src/main/webapp/scripts/personalised-recommendations.js
JavaScript
apache-2.0
2,440
var detect = require('rtc-core/detect'); var extend = require('cog/extend'); var test = require('tape'); var expect = require('./helpers/expect-constraints'); var format = require('./helpers/format'); function mozMediaSource(type) { return { mozMediaSource: type, mediaSource: type }; } test('share', expect({ audio: false, video: extend(detect.moz ? mozMediaSource('window') : {}, { mandatory: detect.moz ? {} : { chromeMediaSource: 'screen' }, optional: [ { maxWidth: 1920 }, { maxHeight: 1080 } ] }) }, format.LEGACY)); test('share', expect({ audio: false, video: extend(detect.moz ? mozMediaSource('window') : {}, detect.moz ? { width: { max: 1920 }, height: { max: 1080 } } : { chromeMediaSource: 'screen', width: { max: 1920 }, height: { max: 1080 } } ) }, format.STANDARD)); test('share:window', expect({ audio: false, video: extend(detect.moz ? mozMediaSource('window') : {}, { mandatory: detect.moz ? {} : { chromeMediaSource: 'screen' }, optional: [ { maxWidth: 1920 }, { maxHeight: 1080 } ] }) }, format.LEGACY)); test('share:window', expect({ audio: false, video: extend(detect.moz ? mozMediaSource('window') : {}, detect.moz ? { width: { max: 1920 }, height: { max: 1080 } } : { chromeMediaSource: 'screen', width: { max: 1920 }, height: { max: 1080 } } ) }, format.STANDARD));
rtc-io/rtc-captureconfig
test/share-constraints.js
JavaScript
apache-2.0
1,483
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Wrapper class for handling XmlHttpRequests. * * One off requests can be sent through goog.net.XhrIo.send() or an * instance can be created to send multiple requests. Each request uses its * own XmlHttpRequest object and handles clearing of the event callback to * ensure no leaks. * * XhrIo is event based, it dispatches events on success, failure, finishing, * ready-state change, or progress (download and upload). * * The ready-state or timeout event fires first, followed by * a generic completed event. Then the abort, error, or success event * is fired as appropriate. Progress events are fired as they are * received. Lastly, the ready event will fire to indicate that the * object may be used to make another request. * * The error event may also be called before completed and * ready-state-change if the XmlHttpRequest.open() or .send() methods throw. * * This class does not support multiple requests, queuing, or prioritization. * * When progress events are supported by the browser, and progress is * enabled via .setProgressEventsEnabled(true), the * goog.net.EventType.PROGRESS event will be the re-dispatched browser * progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event * will be fired for download and upload progress respectively. */ goog.provide('goog.net.XhrIo'); goog.provide('goog.net.XhrIo.ResponseType'); goog.forwardDeclare('goog.Uri'); goog.require('goog.Timer'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.debug.entryPointRegistry'); goog.require('goog.events.EventTarget'); goog.require('goog.json.hybrid'); goog.require('goog.log'); goog.require('goog.net.ErrorCode'); goog.require('goog.net.EventType'); goog.require('goog.net.HttpStatus'); goog.require('goog.net.XmlHttp'); goog.require('goog.object'); goog.require('goog.string'); goog.require('goog.structs'); goog.require('goog.structs.Map'); goog.require('goog.uri.utils'); goog.require('goog.userAgent'); goog.scope(function() { /** * Basic class for handling XMLHttpRequests. * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when * creating XMLHttpRequest objects. * @constructor * @extends {goog.events.EventTarget} */ goog.net.XhrIo = function(opt_xmlHttpFactory) { XhrIo.base(this, 'constructor'); /** * Map of default headers to add to every request, use: * XhrIo.headers.set(name, value) * @type {!goog.structs.Map} */ this.headers = new goog.structs.Map(); /** * Optional XmlHttpFactory * @private {goog.net.XmlHttpFactory} */ this.xmlHttpFactory_ = opt_xmlHttpFactory || null; /** * Whether XMLHttpRequest is active. A request is active from the time send() * is called until onReadyStateChange() is complete, or error() or abort() * is called. * @private {boolean} */ this.active_ = false; /** * The XMLHttpRequest object that is being used for the transfer. * @private {?goog.net.XhrLike.OrNative} */ this.xhr_ = null; /** * The options to use with the current XMLHttpRequest object. * @private {?Object} */ this.xhrOptions_ = null; /** * Last URL that was requested. * @private {string|goog.Uri} */ this.lastUri_ = ''; /** * Method for the last request. * @private {string} */ this.lastMethod_ = ''; /** * Last error code. * @private {!goog.net.ErrorCode} */ this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; /** * Last error message. * @private {Error|string} */ this.lastError_ = ''; /** * Used to ensure that we don't dispatch an multiple ERROR events. This can * happen in IE when it does a synchronous load and one error is handled in * the ready statte change and one is handled due to send() throwing an * exception. * @private {boolean} */ this.errorDispatched_ = false; /** * Used to make sure we don't fire the complete event from inside a send call. * @private {boolean} */ this.inSend_ = false; /** * Used in determining if a call to {@link #onReadyStateChange_} is from * within a call to this.xhr_.open. * @private {boolean} */ this.inOpen_ = false; /** * Used in determining if a call to {@link #onReadyStateChange_} is from * within a call to this.xhr_.abort. * @private {boolean} */ this.inAbort_ = false; /** * Number of milliseconds after which an incomplete request will be aborted * and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout * is set. * @private {number} */ this.timeoutInterval_ = 0; /** * Timer to track request timeout. * @private {?number} */ this.timeoutId_ = null; /** * The requested type for the response. The empty string means use the default * XHR behavior. * @private {goog.net.XhrIo.ResponseType} */ this.responseType_ = ResponseType.DEFAULT; /** * Whether a "credentialed" request is to be sent (one that is aware of * cookies and authentication). This is applicable only for cross-domain * requests and more recent browsers that support this part of the HTTP Access * Control standard. * * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute * * @private {boolean} */ this.withCredentials_ = false; /** * Whether progress events are enabled for this request. This is * disabled by default because setting a progress event handler * causes pre-flight OPTIONS requests to be sent for CORS requests, * even in cases where a pre-flight request would not otherwise be * sent. * * @see http://xhr.spec.whatwg.org/#security-considerations * * Note that this can cause problems for Firefox 22 and below, as an * older "LSProgressEvent" will be dispatched by the browser. That * progress event is no longer supported, and can lead to failures, * including throwing exceptions. * * @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631 * @see b/23469793 * * @private {boolean} */ this.progressEventsEnabled_ = false; /** * True if we can use XMLHttpRequest's timeout directly. * @private {boolean} */ this.useXhr2Timeout_ = false; }; goog.inherits(goog.net.XhrIo, goog.events.EventTarget); var XhrIo = goog.net.XhrIo; /** * Response types that may be requested for XMLHttpRequests. * @enum {string} * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute */ goog.net.XhrIo.ResponseType = { DEFAULT: '', TEXT: 'text', DOCUMENT: 'document', // Not supported as of Chrome 10.0.612.1 dev BLOB: 'blob', ARRAY_BUFFER: 'arraybuffer', }; var ResponseType = goog.net.XhrIo.ResponseType; /** * A reference to the XhrIo logger * @private {?goog.log.Logger} * @const */ goog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo'); /** * The Content-Type HTTP header name * @type {string} */ goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type'; /** * The Content-Transfer-Encoding HTTP header name * @type {string} */ goog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding'; /** * The pattern matching the 'http' and 'https' URI schemes * @type {!RegExp} */ goog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i; /** * The methods that typically come along with form data. We set different * headers depending on whether the HTTP action is one of these. * @type {!Array<string>} */ goog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT']; /** * The Content-Type HTTP header value for a url-encoded form * @type {string} */ goog.net.XhrIo.FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded;charset=utf-8'; /** * The XMLHttpRequest Level two timeout delay ms property name. * * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute * * @private {string} * @const */ goog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout'; /** * The XMLHttpRequest Level two ontimeout handler property name. * * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute * * @private {string} * @const */ goog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout'; /** * All non-disposed instances of goog.net.XhrIo created * by {@link goog.net.XhrIo.send} are in this Array. * @see goog.net.XhrIo.cleanup * @private {!Array<!goog.net.XhrIo>} */ goog.net.XhrIo.sendInstances_ = []; /** * Static send that creates a short lived instance of XhrIo to send the * request. * @see goog.net.XhrIo.cleanup * @param {string|goog.Uri} url Uri to make request to. * @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function * for when request is complete. * @param {string=} opt_method Send method, default: GET. * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=} * opt_content Body data. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @param {number=} opt_timeoutInterval Number of milliseconds after which an * incomplete request will be aborted; 0 means no timeout is set. * @param {boolean=} opt_withCredentials Whether to send credentials with the * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}. * @return {!goog.net.XhrIo} The sent XhrIo. */ goog.net.XhrIo.send = function( url, opt_callback, opt_method, opt_content, opt_headers, opt_timeoutInterval, opt_withCredentials) { var x = new goog.net.XhrIo(); goog.net.XhrIo.sendInstances_.push(x); if (opt_callback) { x.listen(goog.net.EventType.COMPLETE, opt_callback); } x.listenOnce(goog.net.EventType.READY, x.cleanupSend_); if (opt_timeoutInterval) { x.setTimeoutInterval(opt_timeoutInterval); } if (opt_withCredentials) { x.setWithCredentials(opt_withCredentials); } x.send(url, opt_method, opt_content, opt_headers); return x; }; /** * Disposes all non-disposed instances of goog.net.XhrIo created by * {@link goog.net.XhrIo.send}. * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance * it creates when the request completes or fails. However, if * the request never completes, then the goog.net.XhrIo is not disposed. * This can occur if the window is unloaded before the request completes. * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo * it creates and make the client of {@link goog.net.XhrIo.send} be * responsible for disposing it in this case. However, this makes things * significantly more complicated for the client, and the whole point * of {@link goog.net.XhrIo.send} is that it's simple and easy to use. * Clients of {@link goog.net.XhrIo.send} should call * {@link goog.net.XhrIo.cleanup} when doing final * cleanup on window unload. */ goog.net.XhrIo.cleanup = function() { var instances = goog.net.XhrIo.sendInstances_; while (instances.length) { instances.pop().dispose(); } }; /** * Installs exception protection for all entry point introduced by * goog.net.XhrIo instances which are not protected by * {@link goog.debug.ErrorHandler#protectWindowSetTimeout}, * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or * {@link goog.events.protectBrowserEventEntryPoint}. * * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to * protect the entry point(s). */ goog.net.XhrIo.protectEntryPoints = function(errorHandler) { goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = errorHandler.protectEntryPoint( goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); }; /** * Disposes of the specified goog.net.XhrIo created by * {@link goog.net.XhrIo.send} and removes it from * {@link goog.net.XhrIo.pendingStaticSendInstances_}. * @private */ goog.net.XhrIo.prototype.cleanupSend_ = function() { this.dispose(); goog.array.remove(goog.net.XhrIo.sendInstances_, this); }; /** * Returns the number of milliseconds after which an incomplete request will be * aborted, or 0 if no timeout is set. * @return {number} Timeout interval in milliseconds. */ goog.net.XhrIo.prototype.getTimeoutInterval = function() { return this.timeoutInterval_; }; /** * Sets the number of milliseconds after which an incomplete request will be * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no * timeout is set. * @param {number} ms Timeout interval in milliseconds; 0 means none. */ goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) { this.timeoutInterval_ = Math.max(0, ms); }; /** * Sets the desired type for the response. At time of writing, this is only * supported in very recent versions of WebKit (10.0.612.1 dev and later). * * If this is used, the response may only be accessed via {@link #getResponse}. * * @param {goog.net.XhrIo.ResponseType} type The desired type for the response. */ goog.net.XhrIo.prototype.setResponseType = function(type) { this.responseType_ = type; }; /** * Gets the desired type for the response. * @return {goog.net.XhrIo.ResponseType} The desired type for the response. */ goog.net.XhrIo.prototype.getResponseType = function() { return this.responseType_; }; /** * Sets whether a "credentialed" request that is aware of cookie and * authentication information should be made. This option is only supported by * browsers that support HTTP Access Control. As of this writing, this option * is not supported in IE. * * @param {boolean} withCredentials Whether this should be a "credentialed" * request. */ goog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) { this.withCredentials_ = withCredentials; }; /** * Gets whether a "credentialed" request is to be sent. * @return {boolean} The desired type for the response. */ goog.net.XhrIo.prototype.getWithCredentials = function() { return this.withCredentials_; }; /** * Sets whether progress events are enabled for this request. Note * that progress events require pre-flight OPTIONS request handling * for CORS requests, and may cause trouble with older browsers. See * progressEventsEnabled_ for details. * @param {boolean} enabled Whether progress events should be enabled. */ goog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) { this.progressEventsEnabled_ = enabled; }; /** * Gets whether progress events are enabled. * @return {boolean} Whether progress events are enabled for this request. */ goog.net.XhrIo.prototype.getProgressEventsEnabled = function() { return this.progressEventsEnabled_; }; /** * Instance send that actually uses XMLHttpRequest to make a server call. * @param {string|goog.Uri} url Uri to make request to. * @param {string=} opt_method Send method, default: GET. * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=} * opt_content Body data. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different * types of parameters for opt_headers. */ goog.net.XhrIo.prototype.send = function( url, opt_method, opt_content, opt_headers) { if (this.xhr_) { throw new Error( '[goog.net.XhrIo] Object is active with another request=' + this.lastUri_ + '; newUri=' + url); } var method = opt_method ? opt_method.toUpperCase() : 'GET'; this.lastUri_ = url; this.lastError_ = ''; this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; this.lastMethod_ = method; this.errorDispatched_ = false; this.active_ = true; // Use the factory to create the XHR object and options this.xhr_ = this.createXhr(); this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() : goog.net.XmlHttp.getOptions(); // Set up the onreadystatechange callback this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this); // Set up upload/download progress events, if progress events are supported. if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) { this.xhr_.onprogress = goog.bind(function(e) { this.onProgressHandler_(e, true); }, this); if (this.xhr_.upload) { this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this); } } /** * Try to open the XMLHttpRequest (always async), if an error occurs here it * is generally permission denied */ try { goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr')); this.inOpen_ = true; this.xhr_.open(method, String(url), true); // Always async! this.inOpen_ = false; } catch (err) { goog.log.fine( this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message)); this.error_(goog.net.ErrorCode.EXCEPTION, err); return; } // We can't use null since this won't allow requests with form data to have a // content length specified which will cause some proxies to return a 411 // error. var content = opt_content || ''; var headers = this.headers.clone(); // Add headers specific to this request if (opt_headers) { goog.structs.forEach( opt_headers, function(value, key) { headers.set(key, value); }); } // Find whether a content type header is set, ignoring case. // HTTP header names are case-insensitive. See: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 var contentTypeKey = goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_); var contentIsFormData = (goog.global['FormData'] && (content instanceof goog.global['FormData'])); if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) && !contentTypeKey && !contentIsFormData) { // For requests typically with form data, default to the url-encoded form // content type unless this is a FormData request. For FormData, // the browser will automatically add a multipart/form-data content type // with an appropriate multipart boundary. headers.set( goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE); } // Add the headers to the Xhr object headers.forEach(function(value, key) { this.xhr_.setRequestHeader(key, value); }, this); if (this.responseType_) { this.xhr_.responseType = this.responseType_; } // Set xhr_.withCredentials only when the value is different, or else in // synchronous XMLHtppRequest.open Firefox will throw an exception. // https://bugzilla.mozilla.org/show_bug.cgi?id=736340 if ('withCredentials' in this.xhr_ && this.xhr_.withCredentials !== this.withCredentials_) { this.xhr_.withCredentials = this.withCredentials_; } /** * Try to send the request, or other wise report an error (404 not found). */ try { this.cleanUpTimeoutTimer_(); // Paranoid, should never be running. if (this.timeoutInterval_ > 0) { this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_); goog.log.fine( this.logger_, this.formatMsg_( 'Will abort after ' + this.timeoutInterval_ + 'ms if incomplete, xhr2 ' + this.useXhr2Timeout_)); if (this.useXhr2Timeout_) { this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_; this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = goog.bind(this.timeout_, this); } else { this.timeoutId_ = goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this); } } goog.log.fine(this.logger_, this.formatMsg_('Sending request')); this.inSend_ = true; this.xhr_.send(content); this.inSend_ = false; } catch (err) { goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message)); this.error_(goog.net.ErrorCode.EXCEPTION, err); } }; /** * Determines if the argument is an XMLHttpRequest that supports the level 2 * timeout value and event. * * Currently, FF 21.0 OS X has the fields but won't actually call the timeout * handler. Perhaps the confusion in the bug referenced below hasn't * entirely been resolved. * * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute * @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816 * * @param {!goog.net.XhrLike.OrNative} xhr The request. * @return {boolean} True if the request supports level 2 timeout. * @private */ goog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) { return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) && typeof xhr[goog.net.XhrIo.XHR2_TIMEOUT_] === 'number' && xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_] !== undefined; }; /** * @param {string} header An HTTP header key. * @return {boolean} Whether the key is a content type header (ignoring * case. * @private */ goog.net.XhrIo.isContentTypeHeader_ = function(header) { return goog.string.caseInsensitiveEquals( goog.net.XhrIo.CONTENT_TYPE_HEADER, header); }; /** * Creates a new XHR object. * @return {!goog.net.XhrLike.OrNative} The newly created XHR object. * @protected */ goog.net.XhrIo.prototype.createXhr = function() { return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() : goog.net.XmlHttp(); }; /** * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_} * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts * the request. * @private */ goog.net.XhrIo.prototype.timeout_ = function() { if (typeof goog == 'undefined') { // If goog is undefined then the callback has occurred as the application // is unloading and will error. Thus we let it silently fail. } else if (this.xhr_) { this.lastError_ = 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting'; this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT; goog.log.fine(this.logger_, this.formatMsg_(this.lastError_)); this.dispatchEvent(goog.net.EventType.TIMEOUT); this.abort(goog.net.ErrorCode.TIMEOUT); } }; /** * Something errorred, so inactivate, fire error callback and clean up * @param {goog.net.ErrorCode} errorCode The error code. * @param {Error} err The error object. * @private */ goog.net.XhrIo.prototype.error_ = function(errorCode, err) { this.active_ = false; if (this.xhr_) { this.inAbort_ = true; this.xhr_.abort(); // Ensures XHR isn't hung (FF) this.inAbort_ = false; } this.lastError_ = err; this.lastErrorCode_ = errorCode; this.dispatchErrors_(); this.cleanUpXhr_(); }; /** * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do * not dispatch multiple error events. * @private */ goog.net.XhrIo.prototype.dispatchErrors_ = function() { if (!this.errorDispatched_) { this.errorDispatched_ = true; this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.ERROR); } }; /** * Abort the current XMLHttpRequest * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use - * defaults to ABORT. */ goog.net.XhrIo.prototype.abort = function(opt_failureCode) { if (this.xhr_ && this.active_) { goog.log.fine(this.logger_, this.formatMsg_('Aborting')); this.active_ = false; this.inAbort_ = true; this.xhr_.abort(); this.inAbort_ = false; this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT; this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.ABORT); this.cleanUpXhr_(); } }; /** * Nullifies all callbacks to reduce risks of leaks. * @override * @protected */ goog.net.XhrIo.prototype.disposeInternal = function() { if (this.xhr_) { // We explicitly do not call xhr_.abort() unless active_ is still true. // This is to avoid unnecessarily aborting a successful request when // dispose() is called in a callback triggered by a complete response, but // in which browser cleanup has not yet finished. // (See http://b/issue?id=1684217.) if (this.active_) { this.active_ = false; this.inAbort_ = true; this.xhr_.abort(); this.inAbort_ = false; } this.cleanUpXhr_(true); } XhrIo.base(this, 'disposeInternal'); }; /** * Internal handler for the XHR object's readystatechange event. This method * checks the status and the readystate and fires the correct callbacks. * If the request has ended, the handlers are cleaned up and the XHR object is * nullified. * @private */ goog.net.XhrIo.prototype.onReadyStateChange_ = function() { if (this.isDisposed()) { // This method is the target of an untracked goog.Timer.callOnce(). return; } if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) { // Were not being called from within a call to this.xhr_.send // this.xhr_.abort, or this.xhr_.open, so this is an entry point this.onReadyStateChangeEntryPoint_(); } else { this.onReadyStateChangeHelper_(); } }; /** * Used to protect the onreadystatechange handler entry point. Necessary * as {#onReadyStateChange_} maybe called from within send or abort, this * method is only called when {#onReadyStateChange_} is called as an * entry point. * {@see #protectEntryPoints} * @private */ goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() { this.onReadyStateChangeHelper_(); }; /** * Helper for {@link #onReadyStateChange_}. This is used so that * entry point calls to {@link #onReadyStateChange_} can be routed through * {@link #onReadyStateChangeEntryPoint_}. * @private */ goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() { if (!this.active_) { // can get called inside abort call return; } if (typeof goog == 'undefined') { // NOTE(user): If goog is undefined then the callback has occurred as the // application is unloading and will error. Thus we let it silently fail. } else if ( this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] && this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE && this.getStatus() == 2) { // NOTE(user): In IE if send() errors on a *local* request the readystate // is still changed to COMPLETE. We need to ignore it and allow the // try/catch around send() to pick up the error. goog.log.fine( this.logger_, this.formatMsg_('Local request error detected and ignored')); } else { // In IE when the response has been cached we sometimes get the callback // from inside the send call and this usually breaks code that assumes that // XhrIo is asynchronous. If that is the case we delay the callback // using a timer. if (this.inSend_ && this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) { goog.Timer.callOnce(this.onReadyStateChange_, 0, this); return; } this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE); // readyState indicates the transfer has finished if (this.isComplete()) { goog.log.fine(this.logger_, this.formatMsg_('Request complete')); this.active_ = false; try { // Call the specific callbacks for success or failure. Only call the // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED) if (this.isSuccess()) { this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.SUCCESS); } else { this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR; this.lastError_ = this.getStatusText() + ' [' + this.getStatus() + ']'; this.dispatchErrors_(); } } finally { this.cleanUpXhr_(); } } } }; /** * Internal handler for the XHR object's onprogress event. Fires both a generic * PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to * allow specific binding for each XHR progress event. * @param {!ProgressEvent} e XHR progress event. * @param {boolean=} opt_isDownload Whether the current progress event is from a * download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS * event should be dispatched. * @private */ goog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) { goog.asserts.assert( e.type === goog.net.EventType.PROGRESS, 'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.'); this.dispatchEvent( goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS)); this.dispatchEvent( goog.net.XhrIo.buildProgressEvent_( e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS : goog.net.EventType.UPLOAD_PROGRESS)); }; /** * Creates a representation of the native ProgressEvent. IE doesn't support * constructing ProgressEvent via "new", and the alternatives (e.g., * ProgressEvent.initProgressEvent) are non-standard or deprecated. * @param {!ProgressEvent} e XHR progress event. * @param {!goog.net.EventType} eventType The type of the event. * @return {!ProgressEvent} The progress event. * @private */ goog.net.XhrIo.buildProgressEvent_ = function(e, eventType) { return /** @type {!ProgressEvent} */ ({ type: eventType, lengthComputable: e.lengthComputable, loaded: e.loaded, total: e.total, }); }; /** * Remove the listener to protect against leaks, and nullify the XMLHttpRequest * object. * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to * fire any events). * @private */ goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) { if (this.xhr_) { // Cancel any pending timeout event handler. this.cleanUpTimeoutTimer_(); // Save reference so we can mark it as closed after the READY event. The // READY event may trigger another request, thus we must nullify this.xhr_ var xhr = this.xhr_; var clearedOnReadyStateChange = this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ? goog.nullFunction : null; this.xhr_ = null; this.xhrOptions_ = null; if (!opt_fromDispose) { this.dispatchEvent(goog.net.EventType.READY); } try { // NOTE(user): Not nullifying in FireFox can still leak if the callbacks // are defined in the same scope as the instance of XhrIo. But, IE doesn't // allow you to set the onreadystatechange to NULL so nullFunction is // used. xhr.onreadystatechange = clearedOnReadyStateChange; } catch (e) { // This seems to occur with a Gears HTTP request. Delayed the setting of // this onreadystatechange until after READY is sent out and catching the // error to see if we can track down the problem. goog.log.error( this.logger_, 'Problem encountered resetting onreadystatechange: ' + e.message); } } }; /** * Make sure the timeout timer isn't running. * @private */ goog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() { if (this.xhr_ && this.useXhr2Timeout_) { this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null; } if (this.timeoutId_) { goog.Timer.clear(this.timeoutId_); this.timeoutId_ = null; } }; /** * @return {boolean} Whether there is an active request. */ goog.net.XhrIo.prototype.isActive = function() { return !!this.xhr_; }; /** * @return {boolean} Whether the request has completed. */ goog.net.XhrIo.prototype.isComplete = function() { return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE; }; /** * @return {boolean} Whether the request completed with a success. */ goog.net.XhrIo.prototype.isSuccess = function() { var status = this.getStatus(); // A zero status code is considered successful for local files. return goog.net.HttpStatus.isSuccess(status) || status === 0 && !this.isLastUriEffectiveSchemeHttp_(); }; /** * @return {boolean} whether the effective scheme of the last URI that was * fetched was 'http' or 'https'. * @private */ goog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() { var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_)); return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme); }; /** * Get the readystate from the Xhr object * Will only return correct result when called from the context of a callback * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*. */ goog.net.XhrIo.prototype.getReadyState = function() { return this.xhr_ ? /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) : goog.net.XmlHttp.ReadyState .UNINITIALIZED; }; /** * Get the status from the Xhr object * Will only return correct result when called from the context of a callback * @return {number} Http status. */ goog.net.XhrIo.prototype.getStatus = function() { /** * IE doesn't like you checking status until the readystate is greater than 2 * (i.e. it is receiving or complete). The try/catch is used for when the * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. */ try { return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? this.xhr_.status : -1; } catch (e) { return -1; } }; /** * Get the status text from the Xhr object * Will only return correct result when called from the context of a callback * @return {string} Status text. */ goog.net.XhrIo.prototype.getStatusText = function() { /** * IE doesn't like you checking status until the readystate is greater than 2 * (i.e. it is receiving or complete). The try/catch is used for when the * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. */ try { return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? this.xhr_.statusText : ''; } catch (e) { goog.log.fine(this.logger_, 'Can not get status: ' + e.message); return ''; } }; /** * Get the last Uri that was requested * @return {string} Last Uri. */ goog.net.XhrIo.prototype.getLastUri = function() { return String(this.lastUri_); }; /** * Get the response text from the Xhr object * Will only return correct result when called from the context of a callback. * @return {string} Result from the server, or '' if no result available. */ goog.net.XhrIo.prototype.getResponseText = function() { try { return this.xhr_ ? this.xhr_.responseText : ''; } catch (e) { // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute // states that responseText should return '' (and responseXML null) // when the state is not LOADING or DONE. Instead, IE can // throw unexpected exceptions, for example when a request is aborted // or no data is available yet. goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message); return ''; } }; /** * Get the response body from the Xhr object. This property is only available * in IE since version 7 according to MSDN: * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx * Will only return correct result when called from the context of a callback. * * One option is to construct a VBArray from the returned object and convert * it to a JavaScript array using the toArray method: * `(new window['VBArray'](xhrIo.getResponseBody())).toArray()` * This will result in an array of numbers in the range of [0..255] * * Another option is to use the VBScript CStr method to convert it into a * string as outlined in http://stackoverflow.com/questions/1919972 * * @return {Object} Binary result from the server or null if not available. */ goog.net.XhrIo.prototype.getResponseBody = function() { try { if (this.xhr_ && 'responseBody' in this.xhr_) { return this.xhr_['responseBody']; } } catch (e) { // IE can throw unexpected exceptions, for example when a request is aborted // or no data is yet available. goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message); } return null; }; /** * Get the response XML from the Xhr object * Will only return correct result when called from the context of a callback. * @return {Document} The DOM Document representing the XML file, or null * if no result available. */ goog.net.XhrIo.prototype.getResponseXml = function() { try { return this.xhr_ ? this.xhr_.responseXML : null; } catch (e) { goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message); return null; } }; /** * Get the response and evaluates it as JSON from the Xhr object * Will only return correct result when called from the context of a callback * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for * stripping of the response before parsing. This needs to be set only if * your backend server prepends the same prefix string to the JSON response. * @throws Error if the response text is invalid JSON. * @return {Object|undefined} JavaScript object. */ goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) { if (!this.xhr_) { return undefined; } var responseText = this.xhr_.responseText; if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) { responseText = responseText.substring(opt_xssiPrefix.length); } return goog.json.hybrid.parse(responseText); }; /** * Get the response as the type specificed by {@link #setResponseType}. At time * of writing, this is only directly supported in very recent versions of WebKit * (10.0.612.1 dev and later). If the field is not supported directly, we will * try to emulate it. * * Emulating the response means following the rules laid out at * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute * * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only * response types of DEFAULT or TEXT may be used, and the response returned will * be the text response. * * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5), * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the * response returned will be either the text response or the Mozilla * implementation of the array buffer response. * * On browsers will full support, any valid response type supported by the * browser may be used, and the response provided by the browser will be * returned. * * @return {*} The response. */ goog.net.XhrIo.prototype.getResponse = function() { try { if (!this.xhr_) { return null; } if ('response' in this.xhr_) { return this.xhr_.response; } switch (this.responseType_) { case ResponseType.DEFAULT: case ResponseType.TEXT: return this.xhr_.responseText; // DOCUMENT and BLOB don't need to be handled here because they are // introduced in the same spec that adds the .response field, and would // have been caught above. // ARRAY_BUFFER needs an implementation for Firefox 4, where it was // implemented using a draft spec rather than the final spec. case ResponseType.ARRAY_BUFFER: if ('mozResponseArrayBuffer' in this.xhr_) { return this.xhr_.mozResponseArrayBuffer; } } // Fell through to a response type that is not supported on this browser. goog.log.error( this.logger_, 'Response type ' + this.responseType_ + ' is not ' + 'supported on this browser'); return null; } catch (e) { goog.log.fine(this.logger_, 'Can not get response: ' + e.message); return null; } }; /** * Get the value of the response-header with the given name from the Xhr object * Will only return correct result when called from the context of a callback * and the request has completed * @param {string} key The name of the response-header to retrieve. * @return {string|undefined} The value of the response-header named key. */ goog.net.XhrIo.prototype.getResponseHeader = function(key) { if (!this.xhr_ || !this.isComplete()) { return undefined; } var value = this.xhr_.getResponseHeader(key); return value === null ? undefined : value; }; /** * Gets the text of all the headers in the response. * Will only return correct result when called from the context of a callback * and the request has completed. * @return {string} The value of the response headers or empty string. */ goog.net.XhrIo.prototype.getAllResponseHeaders = function() { // getAllResponseHeaders can return null if no response has been received, // ensure we always return an empty string. return this.xhr_ && this.isComplete() ? (this.xhr_.getAllResponseHeaders() || '') : ''; }; /** * Returns all response headers as a key-value map. * Multiple values for the same header key can be combined into one, * separated by a comma and a space. * Note that the native getResponseHeader method for retrieving a single header * does a case insensitive match on the header name. This method does not * include any case normalization logic, it will just return a key-value * representation of the headers. * See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method * @return {!Object<string, string>} An object with the header keys as keys * and header values as values. */ goog.net.XhrIo.prototype.getResponseHeaders = function() { // TODO(user): Make this function parse headers as per the spec // (https://tools.ietf.org/html/rfc2616#section-4.2). var headersObject = {}; var headersArray = this.getAllResponseHeaders().split('\r\n'); for (var i = 0; i < headersArray.length; i++) { if (goog.string.isEmptyOrWhitespace(headersArray[i])) { continue; } var keyValue = goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1); var key = keyValue[0]; var value = keyValue[1]; if (typeof value !== 'string') { // There must be a value but it can be the empty string. continue; } // Whitespace at the start and end of the value is meaningless. value = value.trim(); // The key should not contain whitespace but we currently ignore that. var values = headersObject[key] || []; headersObject[key] = values; values.push(value); } return goog.object.map(headersObject, function(values) { return values.join(', '); }); }; /** * Get the value of the response-header with the given name from the Xhr object. * As opposed to {@link #getResponseHeader}, this method does not require that * the request has completed. * @param {string} key The name of the response-header to retrieve. * @return {?string} The value of the response-header, or null if it is * unavailable. */ goog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) { return this.xhr_ ? this.xhr_.getResponseHeader(key) : null; }; /** * Gets the text of all the headers in the response. As opposed to * {@link #getAllResponseHeaders}, this method does not require that the request * has completed. * @return {string} The value of the response headers or empty string. */ goog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() { return this.xhr_ ? this.xhr_.getAllResponseHeaders() : ''; }; /** * Get the last error message * @return {!goog.net.ErrorCode} Last error code. */ goog.net.XhrIo.prototype.getLastErrorCode = function() { return this.lastErrorCode_; }; /** * Get the last error message * @return {string} Last error message. */ goog.net.XhrIo.prototype.getLastError = function() { return typeof this.lastError_ === 'string' ? this.lastError_ : String(this.lastError_); }; /** * Adds the last method, status and URI to the message. This is used to add * this information to the logging calls. * @param {string} msg The message text that we want to add the extra text to. * @return {string} The message with the extra text appended. * @private */ goog.net.XhrIo.prototype.formatMsg_ = function(msg) { return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' + this.getStatus() + ']'; }; // Register the xhr handler as an entry point, so that // it can be monitored for exception handling, etc. goog.debug.entryPointRegistry.register( /** * @param {function(!Function): !Function} transformer The transforming * function. */ function(transformer) { goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); }); }); // goog.scope
lucidsoftware/closure-library
closure/goog/net/xhrio.js
JavaScript
apache-2.0
45,131
var dir_4d08ff304006deda5c4a9fa99aae6a31 = [ [ "java", "dir_8e445b0d87012ac190b46837b3341970.html", "dir_8e445b0d87012ac190b46837b3341970" ] ];
onosfw/apis
onos/apis/dir_4d08ff304006deda5c4a9fa99aae6a31.js
JavaScript
apache-2.0
147
import { PROBES_SCIENCE_QUERY, PROBES_SCIENCE_SUB, PROBES_SCIENCE_CONTACT_SUB, } from "components/views/ProbeScience"; import systems from "../data/systems"; import sensors from "../data/sensors"; import sensorContacts from "../data/sensorContacts"; import { PROBE_SCIENCE_CORE_QUERY, PROBES_SCIENCE_CORE_SUB, PROBE_SCIENCE_CONTACTS_CORE_SUB, } from "components/views/ProbeScience/core"; import {PROBE_SCIENCE_EMITTER_SUB} from "components/views/ProbeScience/probeScience"; export default [ { request: { query: PROBES_SCIENCE_QUERY, variables: {simulatorId: "test"}, }, result: { data: { sensorContacts, sensors, probes: systems.probes, }, }, }, { request: { query: PROBES_SCIENCE_SUB, variables: {simulatorId: "test"}, }, result: { data: { probesUpdate: systems.probes, }, }, }, { request: { query: PROBES_SCIENCE_CONTACT_SUB, variables: {simulatorId: "test"}, }, result: { data: { sensorContactUpdate: sensorContacts, }, }, }, { request: { query: PROBE_SCIENCE_EMITTER_SUB, variables: {simulatorId: "test"}, }, result: { data: { scienceProbeEmitter: { name: null, type: null, charge: null, }, }, }, }, { request: { query: PROBE_SCIENCE_EMITTER_SUB, variables: {simulatorId: "test"}, }, result: { data: { scienceProbeEmitter: { name: null, type: null, charge: null, }, }, }, }, { request: { query: PROBE_SCIENCE_CORE_QUERY, variables: {simulatorId: "test"}, }, result: { data: { sensorContacts, sensors, probes: systems.probes, }, }, }, { request: { query: PROBES_SCIENCE_CORE_SUB, variables: {simulatorId: "test"}, }, result: { data: { probesUpdate: systems.probes, }, }, }, { request: { query: PROBE_SCIENCE_CONTACTS_CORE_SUB, variables: {simulatorId: "test"}, }, result: { data: { sensorContactUpdate: sensorContacts, }, }, }, ];
Thorium-Sim/thorium
src/mocks/cards/ProbeScience.mock.js
JavaScript
apache-2.0
2,270
var multiplayer = new function(){ this.players = []; this.add_player = function(player){ console.log("new player"); var scale = [1,1,1]; var data = {}; data['x1'] = 0; data['y1'] = 0; elements.add_OBJ(link_mushroom_obj,link_tree_texture,data, scale,"opponent",false, player.id); }; this.remove_player = function(id){ scene.remove(multiplayer.players[""+id]); delete multiplayer.players[""+id]; } }; Arena.when({ playerMove: function (player) { var local_player = multiplayer.players[""+player.id]; if(local_player == undefined){ return; } local_player.position.x = player.x; local_player.position.y = player.y - 15; local_player.position.z = player.z; }, newRegularMushroom: function (position) { elements.addMushroomWithPosition(position); }, pickupMushroom: function (id, team, position) { elements.removeElementPositionMush(position); }, newPlayer: function (player) { multiplayer.add_player(player); }, playerLeft: function (id) { multiplayer.remove_player(id); }, newMegaMushroom: function (position) { position.isMegamush = true; elements.addMushroomWithPosition(position); }, updateScore: function (score) { game.player.points = score[0]; game.opponent.points = score[1]; message.showScore(); }, displayMegaMushroom: function () { message.showStrobMessage("MEGA MUSH !!",20); }, displayMushroomWave: function () { message.showStrobMessage("Vague de champignons !",20); } });
lucas34/mushroom-hunter
core/javascript/multiplayer/socket.js
JavaScript
apache-2.0
1,464
define(function(require, exports, module) { exports.init = function(){ Manager() } function Manager(){ $("#manager").click(function(){ location.href = $(this).attr("data-href"); }); } });
yuhaya/LocalServer
static/js/card/index.js
JavaScript
apache-2.0
242
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import merge from 'deepmerge'; import {Platform} from 'react-native'; import {Navigation} from 'react-native-navigation'; import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import * as NavigationActions from '@actions/navigation'; import {NavigationTypes} from '@constants'; import Preferences from '@mm-redux/constants/preferences'; import EventEmitter from '@mm-redux/utils/event_emitter'; import EphemeralStore from '@store/ephemeral_store'; import intitialState from '@store/initial_state'; import Store from '@store/store'; jest.unmock('@actions/navigation'); const mockStore = configureMockStore([thunk]); const store = mockStore(intitialState); Store.redux = store; // Mock EphemeralStore add/remove modal const add = EphemeralStore.addNavigationModal; const remove = EphemeralStore.removeNavigationModal; EphemeralStore.removeNavigationModal = (componentId) => { remove(componentId); EphemeralStore.removeNavigationComponentId(componentId); }; EphemeralStore.addNavigationModal = (componentId) => { add(componentId); EphemeralStore.addNavigationComponentId(componentId); }; describe('@actions/navigation', () => { const topComponentId = 'top-component-id'; const name = 'name'; const title = 'title'; const theme = Preferences.THEMES.denim; const passProps = { testProp: 'prop', }; const options = { testOption: 'test', }; beforeEach(() => { EphemeralStore.clearNavigationComponents(); EphemeralStore.clearNavigationModals(); // mock that we have a root screen EphemeralStore.addNavigationComponentId(topComponentId); }); // EphemeralStore.getNavigationTopComponentId.mockReturnValue(topComponentId); test('resetToChannel should call Navigation.setRoot', () => { const setRoot = jest.spyOn(Navigation, 'setRoot'); const expectedLayout = { root: { stack: { children: [{ component: { id: 'Channel', name: 'Channel', passProps, options: { layout: { componentBackgroundColor: theme.centerChannelBg, }, statusBar: { visible: true, }, topBar: { visible: false, height: 0, backButton: { visible: false, enableMenu: false, color: theme.sidebarHeaderTextColor, }, background: { color: theme.sidebarHeaderBg, }, }, }, }, }], }, }, }; NavigationActions.resetToChannel(passProps); expect(setRoot).toHaveBeenCalledWith(expectedLayout); }); test('resetToSelectServer should call Navigation.setRoot', () => { const setRoot = jest.spyOn(Navigation, 'setRoot'); const allowOtherServers = false; const expectedLayout = { root: { stack: { children: [{ component: { id: 'SelectServer', name: 'SelectServer', passProps: { allowOtherServers, }, options: { layout: { backgroundColor: theme.centerChannelBg, componentBackgroundColor: theme.centerChannelBg, }, statusBar: { visible: true, }, topBar: { backButton: { color: theme.sidebarHeaderTextColor, enableMenu: false, title: '', }, background: { color: theme.sidebarHeaderBg, }, visible: false, height: 0, }, }, }, }], }, }, }; NavigationActions.resetToSelectServer(allowOtherServers); expect(setRoot).toHaveBeenCalledWith(expectedLayout); }); test('resetToTeams should call Navigation.setRoot', () => { const setRoot = jest.spyOn(Navigation, 'setRoot'); const defaultOptions = { layout: { componentBackgroundColor: theme.centerChannelBg, }, statusBar: { visible: true, }, topBar: { visible: true, title: { color: theme.sidebarHeaderTextColor, text: title, }, backButton: { color: theme.sidebarHeaderTextColor, enableMenu: false, title: '', }, background: { color: theme.sidebarHeaderBg, }, }, }; const expectedLayout = { root: { stack: { children: [{ component: { id: name, name, passProps, options: merge(defaultOptions, options), }, }], }, }, }; NavigationActions.resetToTeams(name, title, passProps, options); expect(setRoot).toHaveBeenCalledWith(expectedLayout); }); test('goToScreen should call Navigation.push', () => { const push = jest.spyOn(Navigation, 'push'); const defaultOptions = { layout: { componentBackgroundColor: theme.centerChannelBg, }, popGesture: true, sideMenu: { left: {enabled: false}, right: {enabled: false}, }, topBar: { animate: true, visible: true, backButton: { color: theme.sidebarHeaderTextColor, enableMenu: false, title: '', testID: 'screen.back.button', }, background: { color: theme.sidebarHeaderBg, }, title: { color: theme.sidebarHeaderTextColor, text: title, }, }, }; const expectedLayout = { component: { id: name, name, passProps, options: merge(defaultOptions, options), }, }; NavigationActions.goToScreen(name, title, passProps, options); expect(push).toHaveBeenCalledWith(topComponentId, expectedLayout); }); test('popTopScreen should call Navigation.pop', () => { const pop = jest.spyOn(Navigation, 'pop'); NavigationActions.popTopScreen(); expect(pop).toHaveBeenCalledWith(topComponentId); const otherComponentId = `other-${topComponentId}`; NavigationActions.popTopScreen(otherComponentId); expect(pop).toHaveBeenCalledWith(otherComponentId); }); test('popToRoot should call Navigation.popToRoot', async () => { const popToRoot = jest.spyOn(Navigation, 'popToRoot'); await NavigationActions.popToRoot(); expect(popToRoot).toHaveBeenCalledWith(topComponentId); }); test('showModal should call Navigation.showModal', () => { const showModal = jest.spyOn(Navigation, 'showModal'); const defaultOptions = { modalPresentationStyle: Platform.select({ios: 'pageSheet', android: 'none'}), layout: { componentBackgroundColor: theme.centerChannelBg, }, statusBar: { visible: true, }, topBar: { animate: true, visible: true, backButton: { color: theme.sidebarHeaderTextColor, enableMenu: false, title: '', }, background: { color: theme.sidebarHeaderBg, }, title: { color: theme.sidebarHeaderTextColor, text: title, }, leftButtonColor: theme.sidebarHeaderTextColor, rightButtonColor: theme.sidebarHeaderTextColor, }, }; const expectedLayout = { stack: { children: [{ component: { id: name, name, passProps, options: merge(defaultOptions, options), }, }], }, }; NavigationActions.showModal(name, title, passProps, options); expect(showModal).toHaveBeenCalledWith(expectedLayout); }); test('showModalOverCurrentContext should call Navigation.showModal', () => { const showModal = jest.spyOn(Navigation, 'showModal'); const showModalOverCurrentContextTitle = ''; const showModalOverCurrentContextOptions = { modalPresentationStyle: 'overCurrentContext', layout: { backgroundColor: 'transparent', componentBackgroundColor: 'transparent', }, topBar: { visible: false, height: 0, }, animations: { showModal: { enter: { enabled: false, }, exit: { enabled: false, }, }, dismissModal: { enter: { enabled: false, }, exit: { enabled: false, }, }, }, }; const showModalOptions = { modalPresentationStyle: Platform.select({ios: 'fullScreen', android: 'none'}), layout: { componentBackgroundColor: theme.centerChannelBg, }, statusBar: { visible: true, }, topBar: { animate: true, visible: true, backButton: { color: theme.sidebarHeaderTextColor, enableMenu: false, title: '', }, background: { color: theme.sidebarHeaderBg, }, title: { color: theme.sidebarHeaderTextColor, text: showModalOverCurrentContextTitle, }, leftButtonColor: theme.sidebarHeaderTextColor, rightButtonColor: theme.sidebarHeaderTextColor, }, }; const defaultOptions = merge(showModalOverCurrentContextOptions, options); const expectedLayout = { stack: { children: [{ component: { id: name, name, passProps, options: merge(showModalOptions, defaultOptions), }, }], }, }; NavigationActions.showModalOverCurrentContext(name, passProps, options); expect(showModal).toHaveBeenCalledWith(expectedLayout); }); test('showSearchModal should call Navigation.showModal', () => { const showModal = jest.spyOn(Navigation, 'showModal'); const showSearchModalName = 'Search'; const showSearchModalTitle = ''; const initialValue = 'initial-value'; const showSearchModalPassProps = {initialValue}; const showSearchModalOptions = { topBar: { visible: false, height: 0, }, }; const defaultOptions = { modalPresentationStyle: Platform.select({ios: 'pageSheet', android: 'none'}), layout: { componentBackgroundColor: theme.centerChannelBg, }, statusBar: { visible: true, }, topBar: { animate: true, visible: true, backButton: { color: theme.sidebarHeaderTextColor, enableMenu: false, title: '', }, background: { color: theme.sidebarHeaderBg, }, title: { color: theme.sidebarHeaderTextColor, text: showSearchModalTitle, }, leftButtonColor: theme.sidebarHeaderTextColor, rightButtonColor: theme.sidebarHeaderTextColor, }, }; const expectedLayout = { stack: { children: [{ component: { id: showSearchModalName, name: showSearchModalName, passProps: showSearchModalPassProps, options: merge(defaultOptions, showSearchModalOptions), }, }], }, }; NavigationActions.showSearchModal(initialValue); expect(showModal).toHaveBeenCalledWith(expectedLayout); }); test('dismissModal should call Navigation.dismissModal', async () => { const dismissModal = jest.spyOn(Navigation, 'dismissModal'); NavigationActions.showModal('First', 'First Modal', passProps, options); await NavigationActions.dismissModal(options); expect(dismissModal).toHaveBeenCalledWith('First', options); }); test('dismissAllModals should call Navigation.dismissAllModals', async () => { const dismissModal = jest.spyOn(Navigation, 'dismissModal'); NavigationActions.showModal('First', 'First Modal', passProps, options); NavigationActions.showModal('Second', 'Second Modal', passProps, options); await NavigationActions.dismissAllModals(options); expect(dismissModal).toHaveBeenCalledTimes(2); }); test('mergeNavigationOptions should call Navigation.mergeOptions', () => { const mergeOptions = jest.spyOn(Navigation, 'mergeOptions'); NavigationActions.mergeNavigationOptions(topComponentId, options); expect(mergeOptions).toHaveBeenCalledWith(topComponentId, options); }); test('setButtons should call Navigation.mergeOptions', () => { const mergeOptions = jest.spyOn(Navigation, 'mergeOptions'); const buttons = { leftButtons: ['left-button'], rightButtons: ['right-button'], }; const setButtonsOptions = { topBar: { ...buttons, }, }; NavigationActions.setButtons(topComponentId, buttons); expect(mergeOptions).toHaveBeenCalledWith(topComponentId, setButtonsOptions); }); test('showOverlay should call Navigation.showOverlay', () => { const showOverlay = jest.spyOn(Navigation, 'showOverlay'); const defaultOptions = { layout: { backgroundColor: 'transparent', componentBackgroundColor: 'transparent', }, overlay: { interceptTouchOutside: false, }, }; const expectedLayout = { component: { name, passProps, options: merge(defaultOptions, options), }, }; NavigationActions.showOverlay(name, passProps, options); expect(showOverlay).toHaveBeenCalledWith(expectedLayout); }); test('dismissOverlay should call Navigation.dismissOverlay', async () => { const dismissOverlay = jest.spyOn(Navigation, 'dismissOverlay'); await NavigationActions.dismissOverlay(topComponentId); expect(dismissOverlay).toHaveBeenCalledWith(topComponentId); }); test('dismissAllModalsAndPopToRoot should call Navigation.dismissAllModals, Navigation.popToRoot, and emit event', async () => { const dismissModal = jest.spyOn(Navigation, 'dismissModal'); const popToRoot = jest.spyOn(Navigation, 'popToRoot'); EventEmitter.emit = jest.fn(); NavigationActions.showModal('First', 'First Modal', passProps, options); NavigationActions.showModal('Second', 'Second Modal', passProps, options); await NavigationActions.dismissAllModalsAndPopToRoot(); expect(dismissModal).toHaveBeenCalledTimes(2); expect(popToRoot).toHaveBeenCalledWith(topComponentId); expect(EventEmitter.emit).toHaveBeenCalledWith(NavigationTypes.NAVIGATION_DISMISS_AND_POP_TO_ROOT); }); });
mattermost/mattermost-mobile
app/actions/navigation/index.test.js
JavaScript
apache-2.0
18,305
MapSearchApp.init = function () { var realEstates = MapSearchApp.Repositories.realEstateRepository.getAll(); var pageView = new MapSearchApp.Views.PageView({ collection: realEstates }); pageView.render(); $(".js-app").html(pageView.$el); MapSearchApp.trigger("afterRender"); }; $(function () { MapSearchApp.init(); });
gawelczyk/ol-search-app
js/app.js
JavaScript
apache-2.0
357
(function(){ function CollectionCtrl(Fixtures){ this.albums = Fixtures.getCollection(12); } angular .module('blocJams') .controller('CollectionCtrl',['Fixtures', CollectionCtrl]); })();
albinoalligator/bloc-jams-angular
app/scripts/controllers/CollectionCtrl.js
JavaScript
apache-2.0
232
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ /** * Verify that the provided component is inputDateHtml on mobile/tablet, and inputDate on desktop */ testCorrectComponentProvided: { test: function (cmp) { var isDesktop = $A.get('$Browser.formFactor').toLowerCase() === "desktop"; var providedCmpName = cmp.getDef().getDescriptor().getQualifiedName(); if (isDesktop) { $A.test.assertEquals("markup://ui:inputDate", providedCmpName, "should use inputDate on desktop"); } else { $A.test.assertEquals("markup://ui:inputDateHtml", providedCmpName, "should use inputDate on desktop"); } } }, // TODO: W-1937288 Fix flapping _testInitialValue: { attributes: {displayDatePicker: 'true', value: '2012-09-10', format: 'MM/dd/yyyy'}, test: function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; $A.test.assertEquals("09/10/2012", inputDateStr, "Dates are not the same and they should be"); } }, /** * Verify behavior when 'format' attribute is not assigned a value. */ testDefaultFormat: { browsers: ['DESKTOP'], attributes: {displayDatePicker: 'true', value: '2012-09-10'}, test: function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; $A.test.assertEquals("Sep 10, 2012", inputDateStr, "Dates are not the same and they should be"); } }, /** * Verify behavior when 'format' attribute is assigned an empty string. */ testEmptyFormat: { browsers: ['DESKTOP'], attributes: {displayDatePicker: 'true', value: '2012-09-10', format: ''}, test: function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; $A.test.assertEquals("Sep 10, 2012", inputDateStr, "Dates are not the same and they should be"); } }, /** * Verify behavior when 'format' attribute is assigned a garbage value. */ testInvalidFormat: { browsers: ['DESKTOP'], attributes: {displayDatePicker: 'true', format: 'KKKKKK'}, test: [function (cmp) { cmp.find("datePicker").get('c.selectToday').runDeprecated(); }, function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; var dt = moment().format('KKKKKK'); $A.test.assertEquals(dt, inputDateStr, "Dates are not the same and they should be"); }] }, /** * Verify behavior when 'langLocale' attribute is not assigned a value. */ testDefaultLangLocale: { browsers: ['DESKTOP'], attributes: {displayDatePicker: 'true', format: 'MMMM dd, yyyy', value: '2012-09-10'}, test: function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; $A.test.assertEquals("September 10, 2012", inputDateStr, "Dates are not the same and they should be"); } }, /** * Verify behavior when 'langLocale' attribute is assigned a different value. */ testLangLocale: { browsers: ['DESKTOP'], attributes: {displayDatePicker: 'true', format: 'MMMM dd, yyyy', value: '2012-09-10', langLocale: 'es'}, test: function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; $A.test.assertEquals("Septiembre 10, 2012", inputDateStr, "Dates are not the same and they should be"); } }, /** * Verify behavior when 'langLocale' attribute is not assigned an empty string. */ testEmptyLangLocale: { browsers: ['DESKTOP'], attributes: {displayDatePicker: 'true', format: 'MMMM dd, yyyy', value: '2012-09-10', langLocale: ''}, test: function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; $A.test.assertEquals("September 10, 2012", inputDateStr, "Dates are not the same and they should be"); } }, /** * Verify behavior when 'langLocale' attribute is not assigned an invalid value. */ testInvalidLangLocale: { browsers: ['DESKTOP'], attributes: {displayDatePicker: 'true', format: 'MMMM dd, yyyy', value: '2012-09-10', langLocale: 'xx'}, test: function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; $A.test.assertEquals("September 10, 2012", inputDateStr, "Dates are not the same and they should be"); } }, /** * Verify behavior of Today() with default 'format' value. */ // TODO(W-2671175): Fails due to GMT/PST timezone difference for user.timezone and actual timezone _testToday: { attributes: {displayDatePicker: 'true', format: 'MMM dd, yyyy'}, test: [function (cmp) { cmp.find("datePicker").get('c.selectToday').runDeprecated(); }, function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; var dt = moment().format('MMM DD, YYYY'); $A.test.assertEquals(dt, inputDateStr, "Dates are not the same and they should be"); }] }, /** * Verify behavior of Today() when 'format' is assigned a valid value. */ // TODO(W-2671175): Fails due to GMT/PST timezone difference for user.timezone and actual timezone _testTodayDifferentFormat: { attributes: {displayDatePicker: 'true', format: 'DD/MM/YYYY'}, test: [function (cmp) { cmp.find("datePicker").get('c.selectToday').runDeprecated(); }, function (cmp) { var inputDateStr = cmp.find("inputText").getElement().value; var dt = moment().format('DD/MM/YYYY'); $A.test.assertEquals(dt, inputDateStr, "Dates are not the same and they should be"); }] }, /** * Test input date picker with label set. */ testDatePickerWithLabel: { browsers: ['DESKTOP'], attributes: {displayDatePicker: 'true', label: 'my date cmp'}, test: function (cmp) { var datePickerOpener = cmp.find("datePickerOpener"); $A.test.assertNotNull(datePickerOpener, "datePickerOpener anchor not present"); var datePicker = cmp.find("datePicker"); $A.test.assertNotNull(datePicker, "datePicker not present"); } } /*eslint-disable semi */ }) /*eslint-enable semi */
badlogicmanpreet/aura
aura-components/src/main/components/ui/inputDate/inputDateTest.js
JavaScript
apache-2.0
7,062
/** * TODO: Rename. Refactor with VerticalLabelNames. */ Ext.define('HorizontalLabelNames', { alias: "widget.HorizontalLabelNames", extend: 'Ext.panel.Panel', layout: 'absolute', items: [ { xtype: 'component', autoEl: 'canvas', itemId: 'canvas', x: 0, y: 0, style: { 'z-index': '0' } }, { xtype: 'component', autoEl: 'canvas', itemId: 'canvasOverlay', x: 0, y: 0, style: { 'z-index': '1' } } ], config: { labelVisibleLength: null, propertiesToRender: [] }, initComponent: function () { this.callParent(arguments); }, afterRender: function () { this.callParent(arguments); this.canvas = this.getComponent("canvas").getEl(); this.ctx = this.canvas.dom.getContext("2d"); this.canvasOverlay = this.getComponent("canvasOverlay").getEl(); this.ctxOverlay = this.canvasOverlay.dom.getContext("2d"); }, refreshCanvasSize: function () { this.canvas.dom.width = this.getWidth(); this.canvas.dom.height = this.getLabelVisibleLength(); this.canvasOverlay.dom.width = this.getWidth(); this.canvasOverlay.dom.height = this.getLabelVisibleLength(); }, /** * */ draw: function () { this.refreshCanvasSize(); this.ctx.save(); this.ctx.translate(0, this.getLabelVisibleLength()); this.ctx.fillStyle = "black"; for (var i = 0; i < this.propertiesToRender.length; i++) { var property = this.propertiesToRender[i]; this.ctx.translate(0, -(property.size / 2 + 4)); //fontSize this.ctx.fillText(property.name, 0, 0); this.ctx.translate(0, -(property.size / 2 - 4)); //fontSize } this.ctx.restore(); } });
ppavlidis/aspiredb
aspiredb/src/main/webapp/scripts/lib/matrix2viz/js/HorizontalLabelNames.js
JavaScript
apache-2.0
2,001
var ns4 = (document.layers)? true : false; var ie4 = (document.all)? true : false; // var ie4 = (document.all && !document.getElementById)? true : false; // var ie5 = (document.getElementById && document.all)? true : false; var ns6 = (document.getElementById && !document.all)? true: false; var w3c = (document.getElementById)? true : false; var wMin, prevGray; var maxMins = 5; function bgclr(el,whatColor, field) { if (whatColor == 0) {whatColor = "";} if (whatColor == 1) {whatColor = "#ffffcc"} if (whatColor == 2) {whatColor = "#ccccff"} if (ie4 || ns6) { // alert (el.style.backgroundColor); if (el.style.backgroundColor != "#ccccff" && el.style.backgroundColor != "rgb(204,204,255)") { el.style.backgroundColor = whatColor; } } else if (ns4) { // this doesn't work if (el.backgroundColor != "#ccccff") { el.backgroundColor = whatColor; } } if (whatColor == "#ccccff") { whatID = el.id; fixedID = whatID.replace(field,"") whatIDNum = parseInt(fixedID); numLoc = fixedID.indexOf(whatIDNum); nameID = fixedID.slice(0,numLoc); score = fixedID.charAt(fixedID.length-1); //alert(score); changebg(nameID, score); // Display score if (!wMin) {wMin = 1} //alert("replaced: "+fixedID+" from "+whatID+" : "+getLabel(field+""+wMin + nameID)); //alert("do we have " + field+""+wMin + nameID + "?"); wScoreEl = eval(getLabel(field+""+wMin + nameID)); if (wScoreEl.innerHTML != "" && wScoreEl.innerHTML != "&nbsp;" && !(prevGray)) { // alert("wScoreEl = " + wScoreEl.id + "\nprevGray = " + prevGray); var n=1; while (n <= maxMins) { //alert("id:"+getLabel(field+""+n + nameID)); checkScore = eval(getLabel(field+""+n + nameID)); if (checkScore.innerHTML != "" && checkScore.innerHTML != "&nbsp;") { checkScore.innerHTML = score; addScores(n, field); break; } if (n == maxMins) { //alert(getLabel(maxMins + nameID)); checkScore = eval(getLabel(maxMins + nameID)); checkScore.innerHTML = score; addScores(maxMins, field); break; } n += 5; } } else if (ie4 || ns6) {wScoreEl.innerHTML = score;} if (ns4) {} // Add scores addScores(wMin, field); // var nScore = addScores(wMin); // if (nScore > 6 || isNaN(nScore)) {whatColor = "#ccccff"} } return true; } function scoreNum(nameID) { // Identify score of element scoreEl = eval(getLabel(nameID)); score = scoreEl.innerHTML; return score; } function addScores(thisMin, field) { var h = parseInt(scoreNum(field+""+thisMin + "h")); var r = parseInt(scoreNum(field+""+thisMin + "r")); var m = parseInt(scoreNum(field+""+thisMin + "m")); var x = parseInt(scoreNum(field+""+thisMin + "x")); var c = parseInt(scoreNum(field+""+thisMin + "c")); if (!(isNaN(h) || isNaN(r) || isNaN(m) || isNaN(x) || isNaN(c))) { var nScore = h + r + m + x + c; whatScoreEl = eval(getLabel(field+""+thisMin + "score")); whatScoreEl.innerHTML = nScore; if (document.getElementById("inputWidget"+field)) { document.getElementById("inputWidget"+field).value = nScore; } } else {return} // Create new column, if score is less than 6 if (nScore <= 6 && parseInt(thisMin) >= 5) { var nextMin = 5 + parseInt(thisMin); if (nextMin > maxMins) {addColumn(nextMin, "",field);} } // Remove column, if score greater than 6 if (nScore > 6 && parseInt(thisMin) >= 5 && maxMins > 5) { for (whatCols = (parseInt(thisMin) + 5); whatCols <= maxMins; whatCols += 5) { addColumn(whatCols, "none", field); } maxMins = thisMin; wMin = thisMin; whatMin(wMin + "c"); } return; } function addColumn (minCol,dispWhat, field) { var pMin = getLabel(field+""+minCol + "min"); //alert(field+""+minCol + "min"); pMin = eval(pMin); pMin.style.display = dispWhat; var pH = getLabel(field+""+minCol + "h"); //alert(field+""+minCol + "h"); pH = eval(pH); pH.style.display = dispWhat; var pR = getLabel(field+""+minCol + "r"); pR = eval(pR); pR.style.display = dispWhat; var pM = getLabel(field+""+minCol + "m"); pM = eval(pM); pM.style.display = dispWhat; var pX = getLabel(field+""+minCol + "x"); pX = eval(pX); pX.style.display = dispWhat; var pC = getLabel(field+""+minCol + "c"); pC = eval(pC); pC.style.display = dispWhat; var pScore = getLabel(field+""+minCol + "score"); pScore = eval(pScore); pScore.style.display = dispWhat; /* var tableID = "apgar"; var table = eval(getLabel(tableID)); var numRows = table.rows.length; var row, cell; for (var z=0; z < numRows; z++) { row = table.rows[z]; cell = row.insertCell(); if (z == 0) { cell.innerHTML = minCol + "-minute<br>score"; cell.id = minCol + "min"; cell.style.backgroundColor = "#0033cc"; cell.style.color = "white"; cell.style.fontWeight = "bold"; // cell.onclick = whatMin(cell.id); } if (z == 1) {cell.id = minCol + "h"; // alert("cell.id = " + cell.id); } if (z == 2) {cell.id = minCol + "r"} if (z == 3) {cell.id = minCol + "m"} if (z == 4) {cell.id = minCol + "x"} if (z == 5) {cell.id = minCol + "c"} if (z == 6) {cell.id = minCol + "score"} if (z != 0) { cell.innerHTML = "&nbsp;"; cell.className = "score"; cell.style.backgroundColor = ""; cell.onclick = "whatMin(\"" + cell.id + "\");" } } alert ("onclick = " + cell.onclick); */ if (dispWhat == "") { wMin = minCol; maxMins = minCol; whatMin(pC.id); } /* if (document.getElementById) { //NN6 bug inserting cells in wrong sequence for (var i = arguments.length - 1; i >= 1; i--) { var cell = row.insertCell(arguments.length - 1 - i); cell.appendChild(document.createTextNode(arguments[i])); } } */ return; } function getLabel(nameID) { var whatTag; if (ie4) {whatTag = "document.all[\"" + nameID + "\"]";} if (ns6) {whatTag = "document.getElementById(\"" + nameID + "\")";} return whatTag; } function changebg(nameID, idNum) { // Change color of previously-selected element to blank for (i=0; i <= 2; i++) { if (ie4) {tempEl = eval("document.all." + nameID + i);} else if (ns6) {tempEl = eval("document.getElementById(\"" + nameID + i + "\")");} // alert (tempEl) if ((ie4 || ns6) && tempEl) { if ((tempEl.style.backgroundColor == "#ccccff" || tempEl.style.backgroundColor == "rgb(204,204,255)") && (i != idNum)) { // alert("i = " + i + "\nidNum = " + idNum); tempEl.style.backgroundColor = ""; } } } return; } function whatMin(el, field) { var char1 = el.charAt(1); if (isNaN(char1)) {wMin = el.charAt(0);} else {wMin = el.substring(0,2);} // alert ("el = " + el + "\nwMin = " + wMin); if (prevGray) { var pChar1 = prevGray.charAt(1); if (isNaN(pChar1)) {prevMin = prevGray.charAt(0);} else {prevMin = prevGray.substring(0,2);} if (prevMin != wMin) { // Convert previous gray boxes to no-color var pH = getLabel(field+""+prevMin + "h"); pH = eval(pH); pH.style.backgroundColor = ""; var pR = getLabel(field+""+prevMin + "r"); pR = eval(pR); pR.style.backgroundColor = ""; var pM = getLabel(field+""+prevMin + "m"); pM = eval(pM); pM.style.backgroundColor = ""; var pX = getLabel(field+""+prevMin + "x"); pX = eval(pX); pX.style.backgroundColor = ""; var pC = getLabel(field+""+prevMin + "c"); pC = eval(pC); pC.style.backgroundColor = ""; } } prevGray = el; // Convert selected column to gray boxes //alert(field+""+wMin + "h"); pH = getLabel(field+""+wMin + "h"); pH = eval(pH); pH.style.backgroundColor = "#c6c6c6"; changeScore(pH.id); pR = getLabel(field+""+wMin + "r"); pR = eval(pR); pR.style.backgroundColor = "#c6c6c6"; changeScore(pR.id); pM = getLabel(field+""+wMin + "m"); pM = eval(pM); pM.style.backgroundColor = "#c6c6c6"; changeScore(pM.id); pX = getLabel(field+""+wMin + "x"); pX = eval(pX); pX.style.backgroundColor = "#c6c6c6"; changeScore(pX.id); pC = getLabel(field+""+wMin + "c"); pC = eval(pC); pC.style.backgroundColor = "#c6c6c6"; changeScore(pC.id); // el = getLabel(el); // el = eval(el); // el.style.backgroundColor = "#c6c6c6"; return; } function changeScore(whatID1) { var char1, idNum, scoreID1, whatScore, checkBox; char1 = whatID1.charAt(1); if (isNaN(char1)) {idNum = whatID1.charAt(0);} else {idNum = whatID1.substring(0,2);} idName = whatID1.charAt(whatID1.length-1); // alert("idNum = " + idNum + "\nidName = " + idName); scoreID1 = getLabel(idNum + idName); scoreID1 = eval(scoreID1); var whatScore = scoreID1.innerHTML; for (var q=0; q < 3; q++) { checkBox = getLabel(idName + q); checkBox = eval(checkBox); if (whatScore == q) {checkBox.style.backgroundColor = "#ccccff";} else {checkBox.style.backgroundColor = "";} } return; } function resetAll() { return; } /* // This code from http://www.woram.com/TESTS/JAVA-08.HTM function buttonCheck(btn) { var browser = navigator.appName.substring (0,4 ); var mouseButton = 0; if (browser=="Micr") mouseButton=event.button; else if (browser=="Nets") mouseButton=btn.which; if ((browser=="Micr" && mouseButton==4) || (browser=="Nets" && mouseButton==2)) {alert(mouseButton + ". Middle Button");} else if ((browser=="Micr" && mouseButton==2) || (browser=="Nets" && mouseButton==3)){alert(mouseButton + ". Secondary Button");} else if (mouseButton==1) {alert(mouseButton + ". Primary Button");} } function imageCheck() { if (document.images) {for (var pic=0; pic<document.images.length; pic++) document.images[pic].onmousedown = buttonCheck;} } window.onload=imageCheck; // ----------------------------------------------------------- // This code from http://javascript.internet.com/page-details/no-right-click.html function right(e) { if (navigator.appName == 'Netscape' && e.which > 1) return false; else if (navigator.appName == 'Microsoft Internet Explorer' && event.button > 1) { alert("Sorry, you do not have permission to right click."); return false; } return true; } document.onmousedown=right; // document.onmouseup=right; if (document.layers) window.captureEvents(Event.MOUSEDOWN); // if (document.layers) window.captureEvents(Event.MOUSEUP); window.onmousedown=right; // window.onmouseup=right; // //////////////////////////////////////////////////////////////////////// */ function checkForm() { var ktv = document.ktv; var height = ktv.height.value; if (!checkError(height, "height", "patient's height")) return false; return true; } function checkError(whatVar, varName, varText) { if ((whatVar == "") || (whatVar <= 0) || (isNaN(whatVar))) { alert("Please enter the " + varText + "."); eval("document.ktv." + varName + ".focus();"); eval("document.ktv." + varName + ".select();"); return false; } return true; } function roundNum(thisNum,dec) { thisNum = thisNum * Math.pow(10,dec); thisNum = Math.round(thisNum); thisNum = thisNum / Math.pow(10,dec); return thisNum; }
chrisekelley/zeprs
web/zeprs/js/apgar.js
JavaScript
apache-2.0
10,823
import React, { PropTypes } from 'react'; import c from '../../pages/common.css'; import cx from 'classnames'; class ApplicationPanel extends React.Component { static propTypes = { handleChange: React.PropTypes.func, value: React.PropTypes.string }; render() { const {handleChange, value} = this.props; return ( <form role="form"> <div className="form-group"> <label htmlFor="input1" className="required-pf">Application</label> <textarea type="text" className="form-control" id="input1" required="" rows="10" placeholder="paste application json..." value={value} onChange={handleChange}/> </div> </form> ) } } export default ApplicationPanel;
priley86/labs-console
components/Canvas/ApplicationPanel.js
JavaScript
apache-2.0
788
/* * Copyright 2013 Amadeus s.a.s. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Test different API for the section statement */ Aria.classDefinition({ $classpath : "test.aria.templates.section.sectionAttributes.SectionAttributesTestCase", $extends : "aria.jsunit.TemplateTestCase", $dependencies : ["aria.utils.Dom"], $prototype : { runTemplateTest : function () { this.dom = this.templateCtxt.$getElementById('section_1'); this.checkGetAttribute(); }, checkGetAttribute : function (args) { var dom = this.dom; var title = dom.getAttribute('title'); this.assertEquals(title, "This is my section", "getAttributes doesn't work properly"); this.checkClasses(); }, checkClasses : function (args) { var dom = this.dom; this.assertTrue(dom.classList.contains("class1"), "The dom should contains the class1"); this.assertTrue(dom.classList.contains("class2"), "The dom should contains the class2"); this.assertEquals(dom.classList.getClassName(), "class1 class2", "classList.getClassName should return 'class1 class2'"); dom.classList.add("class3"); this.assertTrue(dom.classList.contains("class3"), "The dom should contains the class3"); dom.classList.remove("class2"); this.assertFalse(dom.classList.contains("class2"), "The dom shouldn't contains the class2"); dom.classList.toggle("class3"); this.assertFalse(dom.classList.contains("class3"), "The dom shouldn't contains the class3"); dom.classList.toggle("class2"); this.assertTrue(dom.classList.contains("class2"), "The dom should contains the class2"); dom.classList.setClassName("foo1 foo2"); this.assertFalse(dom.classList.contains("class1"), "The dom shouldn't contains class1"); this.assertTrue(dom.classList.contains("foo1"), "The dom should contains foo1"); this.assertTrue(dom.classList.contains("foo2"), "The dom should contains foo2"); this.checkExpando(); }, checkExpando : function (args) { var dom = this.dom; this.assertEquals(dom.getData("foo1"), "Foo 1", "The expando attribute 'foo1' should be set to 'Foo 1'"); this.assertEquals(dom.getData("foo2"), "Foo 2", "The expando attribute 'foo2' should be set to 'Foo 2'"); this.testEnd(); }, testEnd : function () { this.notifyTemplateTestEnd(); } } });
vcarle/ariatemplates
test/aria/templates/section/sectionAttributes/SectionAttributesTestCase.js
JavaScript
apache-2.0
3,140
(function () { 'use strict'; angular.module('xos.dashboardManager') .directive('dashboardForm', function(){ return { restrict: 'E', scope: {}, bindToController: true, controllerAs: 'vm', templateUrl: 'templates/dashboard-form.tpl.html', controller: function($stateParams, $log, Dashboards){ this.dashboard = { enabled: true }; if($stateParams.id){ Dashboards.get({id: $stateParams.id}).$promise .then(dash => { this.dashboard = dash; }) .catch(e => { console.log(e); }) } this.formConfig = { exclude: [ 'backend_register', 'controllers', 'deployments', 'enacted', 'humanReadableName', 'lazy_blocked', 'no_policy', 'no_sync', 'policed', 'write_protect', 'icon', 'icon_active' ], actions: [ { label: 'Save', icon: 'ok', cb: (item,form) => { if (!form.$valid){ return; } if(item.name && item.url && item.custom_icon){ var indexOfXos = item.url.indexOf('xos'); if (indexOfXos>=0){ var dashboard_name = item.url.slice(indexOfXos+3,item.url.length).toLowerCase(); item.icon =dashboard_name.concat('-icon.png'); item.icon_active =dashboard_name.concat('-icon-active.png'); } else{ item.icon ='default-icon.png'; item.icon_active ='default-icon-active.png'; } } else{ item.icon ='default-icon.png'; item.icon_active ='default-icon-active.png'; } this.createOrUpdateDashboard(item); }, class: 'success' }, { label: 'Esport to TOSCA', icon: 'export', cb: (item) => { this.toTosca(item); }, class: 'primary' } ], formName: 'dashboardForm', feedback: { show: false, message: 'Form submitted successfully !!!', type: 'success' }, fields: { name: { type: 'string', validators: { required: true } }, url: { type: 'string', validators: { required: true } }, enabled: { type: 'boolean' }, custom_icon: { type: 'boolean' } } }; this.createOrUpdateDashboard = dashboard => { let p; if(dashboard.id){ delete dashboard.controllers; delete dashboard.deployments; p = dashboard.$save(); } else{ p = Dashboards.save(dashboard).$promise; } p.then(res => { this.formConfig.feedback.show = true; }) .catch(e => { $log.info(e); this.formConfig.feedback.show = true; this.formConfig.feedback.message = e; this.formConfig.feedback.type='danger'; }) }; this.toTosca = dashboard => { const yaml = {} yaml[dashboard.name] = { type: 'tosca.nodes.DashboardView', properties: { url: dashboard.url } }; this.tosca = jsyaml.dump(yaml).replace(/'/g, ''); const yamlRequirements = { requirements: [] }; const dashboardRequirements = {}; dashboardRequirements[`${dashboard.name.toLowerCase()}_dashboard`] = { node: dashboard.name, relationship: 'tosca.relationships.UsesDashboard' } yamlRequirements.requirements.push(dashboardRequirements); this.toscaRequirements = jsyaml.dump(yamlRequirements).replace(/'/g, ''); }; } } }); })();
zdw/xos
views/ngXosViews/dashboardManager/src/js/dashboard-form.directive.js
JavaScript
apache-2.0
4,386
// Get dependencies const express = require('express'); const path = require('path'); const http = require('http'); const bodyParser = require('body-parser'); // Get our API routes const api = require('./server/routes/api'); const app = express(); // Parsers for POST data app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Point static path to dist app.use(express.static(path.join(__dirname, 'dist'))); // Set our api routes app.use('/api', api); // Catch all other routes and return the index file app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist/index.html')); }); /** * Get port from environment and store in Express. */ const port = process.env.PORT || '3000'; app.set('port', port); /** * Create HTTP server. */ const server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port, () => console.log(`API running on localhost:${port}`));
rdicharry/evolute
server.js
JavaScript
apache-2.0
966
const assert = require('assert'); const adminHelper = require('../common/admin-helper')(); const Config = require('../../lib/config/config'); const os = require('os'); const fs = require('fs'); const path = require('path'); const idGen = require('uuid62'); const yaml = require('js-yaml'); describe('REST: policies', () => { let config; beforeEach(() => { config = new Config(); config.gatewayConfigPath = path.join(os.tmpdir(), idGen.v4() + 'yml'); }); afterEach(() => { return adminHelper.stop(); }); describe('when no policies defined', () => { beforeEach(() => { const initialConfig = { admin: { port: 0 } }; fs.writeFileSync(config.gatewayConfigPath, yaml.dump(initialConfig)); config.loadGatewayConfig(); return adminHelper.start({ config }); }); it('should activate new policy', () => { return adminHelper.admin.config.policies .activate('test') .then(() => { const data = fs.readFileSync(config.gatewayConfigPath, 'utf8'); const cfg = yaml.load(data); assert.deepStrictEqual(cfg.policies, ['test']); }); }); }); describe('when policies defined', () => { beforeEach(() => { const initialConfig = { admin: { port: 0 }, policies: ['example', 'hello'] }; fs.writeFileSync(config.gatewayConfigPath, yaml.dump(initialConfig)); config.loadGatewayConfig(); return adminHelper.start({ config }); }); it('should create a new api endpoint', () => { return adminHelper.admin.config.policies .activate('test') .then(() => { const data = fs.readFileSync(config.gatewayConfigPath, 'utf8'); const cfg = yaml.load(data); assert.deepStrictEqual(cfg.policies, ['example', 'hello', 'test']); }); }); it('should deactivate existing policy', () => { return adminHelper.admin.config.policies .deactivate('example') .then(() => { const data = fs.readFileSync(config.gatewayConfigPath, 'utf8'); const cfg = yaml.load(data); assert.deepStrictEqual(cfg.policies, ['hello']); }); }); it('should list all enabled policies', () => { return adminHelper.admin.config.policies .list() .then((policies) => { assert.deepStrictEqual(policies, ['example', 'hello']); }); }); }); });
ExpressGateway/express-gateway
test/rest-api/policies.test.js
JavaScript
apache-2.0
2,441
describe("", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("build/docs/examples/example-example100/index.html"); }); it('should format numbers', function() { expect(element(by.id('number-default')).getText()).toBe('1,234.568'); expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); }); it('should update', function() { element(by.model('val')).clear(); element(by.model('val')).sendKeys('3374.333'); expect(element(by.id('number-default')).getText()).toBe('3,374.333'); expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); }); });
LADOSSIFPB/nutrif
nutrif-web/lib/angular/docs/ptore2e/example-example100/default_test.js
JavaScript
apache-2.0
826
import React from 'react' import { Component } from 'react' import Select from 'react-select' import './CategorySelect.scss' export default class CategorySelect extends Component { render() { const {categories, value, onChange, handleBeingTouched, touched, error} = this.props var options = categories.map(function(category) { return {label: category.display_name, value: category.id} }) return ( <div className='category-select-container'> <label className='category-select-label ncss-label'>Category</label> <Select className={((touched && error) ? 'category-select select-container-error' : 'category-select select-container')} onChange = {(v) => { handleBeingTouched(); onChange(v)} } onBlur={() => { handleBeingTouched() }} placeholder="Choose a Category" value={value} options={options} /> {touched && error && <div className='select-error-msg'>{error}</div>} </div> ) } }
tlisonbee/cerberus-management-service
dashboard/app/components/CategorySelect/CategorySelect.js
JavaScript
apache-2.0
1,135
import React from 'react'; import { BannerRow, H2, Button } from '@appbaseio/designkit'; import PropTypes from 'prop-types'; import { css } from 'react-emotion'; import { SecondaryLink } from '../styles'; const style = css` p { color: #ffffff; font-weight: 300; } `; const button = { fontSize: '14px', lineHeight: '19px', fontWeight: 'bold', }; const Banner = ({ config, theme, configName }) => ( <BannerRow> {config.map((b, i) => ( <BannerRow.Column key={ // eslint-disable-next-line i } className={style} style={{ backgroundColor: b.backgroundColor, }} > <div> <H2 light>{b.title}</H2> <p>{b.description}</p> <div className="button-row center"> <Button href={b.button.href} uppercase big primary={configName !== 'vue'} bold style={{ backgroundColor: theme.secondary, ...button, }} > {b.button.title} </Button> <SecondaryLink href={b.link.href}>{b.link.title}</SecondaryLink> </div> </div> </BannerRow.Column> ))} </BannerRow> ); Banner.defaultProps = { configName: 'web', }; Banner.propTypes = { // eslint-disable-next-line theme: PropTypes.object, configName: PropTypes.string, config: PropTypes.arrayOf(PropTypes.shape({ backgroundColor: PropTypes.string, title: PropTypes.string, description: PropTypes.string, button: PropTypes.shape({ title: PropTypes.string, href: PropTypes.string, }), link: PropTypes.shape({ title: PropTypes.string, href: PropTypes.string, }), })).isRequired, }; export default Banner;
appbaseio/reactivesearch
site/src/components/BannerRow.js
JavaScript
apache-2.0
1,642
/* * Copyright 2015 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var container = require('rhea'); var amqp_message = container.message; var args = require('./options.js').options({ 'm': { alias: 'messages', default: 100, describe: 'number of messages to send'}, 'n': { alias: 'node', default: 'examples', describe: 'name of node (e.g. queue) to which messages are sent'}, 'h': { alias: 'host', default: 'localhost', describe: 'dns or ip name of server where you want to connect'}, 'p': { alias: 'port', default: 5672, describe: 'port to connect to'} }).help('help').argv; var confirmed = 0, sent = 0; var total = args.messages; container.on('sendable', function (context) { while (context.sender.sendable() && sent < total) { sent++; console.log('sent ' + sent); var stringifiedPayload = JSON.stringify({'sequence':sent}); // In this example, we are sending a byte array containing ascii // characters though this can be any opaque binary payload var body = amqp_message.data_section(new Buffer(stringifiedPayload, 'utf8')); context.sender.send({message_id:sent, body}); } }); container.on('accepted', function (context) { if (++confirmed === total) { console.log('all messages confirmed'); context.connection.close(); } }); container.on('disconnected', function (context) { if (context.error) console.error('%s %j', context.error, context.error); sent = confirmed; }); container.connect({port: args.port, host: args.host}).open_sender(args.node);
grs/rhea
examples/send_raw.js
JavaScript
apache-2.0
2,096
function appointment(input) { Ti.include('/ui/common/helpers/dateTime.js'); Ti.include('/ui/common/database/users_db.js'); Ti.include('/ui/common/database/children_db.js'); Ti.include('/ui/common/database/relationships_db.js'); Ti.include('/ui/common/database/records_db.js'); Ti.include('/ui/common/database/incidents_db.js'); Ti.include('/ui/common/database/entries_db.js'); Ti.include('/ui/common/database/activities_db.js'); Ti.include('/ui/common/database/appointments_db.js'); Ti.include('/ui/common/database/treatments_db.js'); Ti.include('/ui/common/cloud/appcelerator/objects.js'); var appointment = { id: input.id?input.id:null, entry_id: input.entry_id?input.entry_id:null, diagnosis: input.diagnosis?input.diagnosis:null, complete: (input.complete == 1)?true:false, date: input.date?input.date:timeFormatted(new Date).date, time: input.time?input.time:timeFormatted(new Date).time, symptoms: input.symptoms?input.symptoms:[], doctor: input.doctor?input.doctor:{ name: null, location: null, street: null, city: null, state: null, zip: null, country: 'USA', }, activities: input.activities?input.activities:[], treatments: input.treatments?input.treatments:[], } var symptoms_string=''; for(var i=0;i < appointment.symptoms.length; i++) { symptoms_string += appointment.symptoms[i]; if(i != appointment.symptoms.length -1) symptoms_string += ', '; } var window = Ti.UI.createWindow({ backgroundColor:'white', navBarHidden: 'true', windowSoftInputMode: Ti.UI.Android.SOFT_INPUT_ADJUST_PAN, }); window.result = null; var windowTitleBar = require('ui/handheld/windowNavBar'); windowTitleBar = new windowTitleBar('100%', 'Appointment', 'Cancel', 'Save'); window.add(windowTitleBar); var warning = Ti.UI.createView({ top: 70, width: '100%', zIndex: 3, height: 70, backgroundColor: 'red', borderColor: 'red' }); warning.add(Ti.UI.createLabel({ text: 'NOTE: This is for personal records, it does not schedule an actual appointment', textAlign: 'center', color: 'white', width: Titanium.Platform.displayCaps.platformWidth*0.90, })); window.add(warning); var cancel_btn = windowTitleBar.leftNavButton; cancel_btn.addEventListener('click', function() { window.close(); }); var save_btn = windowTitleBar.rightNavButton; save_btn.addEventListener('click', function() { if(table.scrollable == false) { return; } var name_test=false, dateTime_test=false, symptoms_test=false; if(!isValidDateTime(date.text+' '+time.text) && complete_switcher.value == false) { alert('You may have entered a date that has already passed. Kindly recheck'); } else { dateTime_test = true; } //Remove the whitespace then test to make sure there are only letters var onlyLetters = /^[a-zA-Z]/.test(name.value.replace(/\s/g, '')); if(name.value != null && name.value.length > 1 && onlyLetters) { name_test = true; } else { alert('Doctors name must be longer than one character and contain only letters'); } if(symptoms_field.value == null || symptoms_field.value == '') { alert('You must list at least one symptom'); } else { symptoms_test=true; } if(dateTime_test && name_test && symptoms_test) { if(diagnosis.value != null) { diagnosis.value = diagnosis.value.replace("'", "''"); } //If diagnosis exists, remove quotes before submitting if(appointment.id == null) { if(!Titanium.Network.online) { alert('Error:\n You are not connected to the internet. Cannot create new appointment'); return; } var entry_id = '"'+appointment.entry_id+'"'; appointment.id = insertAppointmentLocal(entry_id,appointment.date,appointment.time,diagnosis.value); appointment.doctor.id = insertDoctorForAppointmentLocal(appointment.id,name.value,location.value,street.value,city.value,state.value,zip.value,country.value); createObjectACS('appointments', { id: appointment.id, entry_id: appointment.entry_id, date: appointment.date, time: appointment.time, complete: complete_switcher.value, diagnosis: diagnosis.value, }); } else { updateAppointmentLocal(appointment.id,appointment.date,appointment.time,diagnosis.value); updateDoctorForAppointmentLocal(appointment.id,name.value,location.value,street.value,city.value,state.value,zip.value,country.value); } deleteSymptomsForAppointmentLocal(appointment.id); appointment.symptoms.splice(0, appointment.symptoms.length); if(symptoms_field.value != null) { if(symptoms_field.value.length > 1) { var final_symptoms = symptoms_field.value.split(','); for(var i=0;i < final_symptoms.length;i++) { if(final_symptoms[i].length < 2) continue; final_symptoms[i] = final_symptoms[i].replace(/^\s\s*/, ''); // Remove Preceding white space insertSymptomForAppointmentLocal(appointment.id,final_symptoms[i]); appointment.symptoms.push(final_symptoms[i]); } } } updateAppointmentCompleteStatus(appointment.id,complete_switcher.value); updateRecordTimesForEntryLocal(appointment.entry_id,timeFormatted(new Date()).date,timeFormatted(new Date()).time); appointment.doctor.name = name.value; appointment.doctor.location = location.value; appointment.doctor.street = street.value; appointment.doctor.city = city.value; appointment.doctor.state = state.value; appointment.doctor.zip = zip.value; appointment.doctor.country = country.value; appointment.complete = complete_switcher.value; appointment.diagnosis = diagnosis.value; window.result = appointment; window.close(); } }); var table = Ti.UI.createTableView({ top: 140, separatorColor: 'transparent', }); var sectionDetails = Ti.UI.createTableViewSection({ headerTitle: 'Doctor Details(*=required)' }); sectionDetails.add(Ti.UI.createTableViewRow({ height: 45, })); sectionDetails.add(Ti.UI.createTableViewRow({ height: 45, })); sectionDetails.add(Ti.UI.createTableViewRow({ height: 135, })); var name_title = Titanium.UI.createLabel({ text: '*Name', color: 'black', left: 15, font: { fontWeight: 'bold', fontSize: 18, }, }); var name = Ti.UI.createTextField({ hintText: 'eg: James Smith', color: 'black', value: appointment.doctor.name, left: '40%', width: '60%' }); var location_title = Titanium.UI.createLabel({ text: 'Location', color: 'black', left: 15, font: { fontWeight: 'bold', fontSize: 18, }, }); var location = Ti.UI.createTextField({ hintText: 'Clinic/Hospital name', color: 'black', value: appointment.doctor.location, left: '40%', width: '60%' }); var address_title = Titanium.UI.createLabel({ text: 'Address', color: 'black', left: 15, font: { fontWeight: 'bold', fontSize: 18, }, }); var street = Ti.UI.createTextField({ hintText: 'Street', color: 'black', value: appointment.doctor.street, borderColor: '#CCC', leftButtonPadding: 5, height: 45, width: '60%', left: '40%', top: 0 }); var city = Ti.UI.createTextField({ hintText: 'City', color: 'black', value: appointment.doctor.city, borderColor: '#CCC', leftButtonPadding: 5, left: '40%', height: 45, width: '40%', top: 45 }); var state = Ti.UI.createTextField({ hintText: 'State', color: 'black', value: appointment.doctor.state, borderColor: '#CCC', leftButtonPadding: 5, left: '80%', height: 45, width: '20%', top: 45 }); var zip = Ti.UI.createTextField({ hintText: 'ZIP', color: 'black', value: appointment.doctor.zip, borderColor: '#CCC', leftButtonPadding: 5, left: '40%', height: 45, width: '20%', top: 90 }); var country = Ti.UI.createTextField({ hintText: 'Country', color: 'black', value: appointment.doctor.country, borderColor: '#CCC', leftButtonPadding: 5, left: '60%', height: 45, width: '40%', top: 90 }); sectionDetails.rows[0].add(name_title); sectionDetails.rows[0].add(name); sectionDetails.rows[1].add(location_title); sectionDetails.rows[1].add(location); sectionDetails.rows[2].add(address_title); sectionDetails.rows[2].add(street); sectionDetails.rows[2].add(city); sectionDetails.rows[2].add(state); sectionDetails.rows[2].add(zip); sectionDetails.rows[2].add(country); var sectionDateTime = Ti.UI.createTableViewSection({ headerTitle: 'Date and Time(tap to change)' }); sectionDateTime.add(Ti.UI.createTableViewRow({ height: 45, })); var date = Ti.UI.createLabel({ text: appointment.date, color: 'black', left: 15, font: { fontWeight: 'bold', fontSize: 18, }, }); var time = Ti.UI.createLabel({ text: appointment.time, color: 'black', left: 160, font: { fontWeight: 'bold', fontSize: 18, }, }); sectionDateTime.rows[0].add(date); sectionDateTime.rows[0].add(time); var sectionSymptoms = Ti.UI.createTableViewSection({ headerTitle: '*Symptoms(list using commas)' }); sectionSymptoms.add(Ti.UI.createTableViewRow({ height: 90, selectedBackgroundColor: 'white' })); var symptoms_field = Ti.UI.createTextArea({ hintText: 'Seperate each symptom by comma', value: symptoms_string, width: '100%', top: 5, font: { fontSize: 17 }, height: 70, borderRadius: 10 }); sectionSymptoms.rows[0].add(symptoms_field); var sectionDiagnosis = Ti.UI.createTableViewSection(); sectionDiagnosis.add(Ti.UI.createTableViewRow({ selectedBackgroundColor: 'white' })); sectionDiagnosis.add(Ti.UI.createTableViewRow({ selectedBackgroundColor: 'white' })); var complete_title = Ti.UI.createLabel({ text: 'Complete', color: 'black', left: 15, font: { fontWeight: 'bold', fontSize: 18, }, }); var complete_switcher = Ti.UI.createSwitch({ value: appointment.complete, left: '50%', }); var diagnosis_title = Ti.UI.createLabel({ text: 'Diagnosis', left: 15, font: { fontWeight: 'bold', fontSize: 18, }, }); var diagnosis = Ti.UI.createTextField({ hintText: 'Enter here', value: appointment.diagnosis, width: '50%', left: '50%' }); sectionDiagnosis.rows[0].add(complete_title); sectionDiagnosis.rows[0].add(complete_switcher); sectionDiagnosis.rows[1].add(diagnosis_title); sectionDiagnosis.rows[1].add(diagnosis); table.data = [sectionDateTime, sectionDetails, sectionSymptoms, sectionDiagnosis ]; window.add(table); date.addEventListener('click', function(e) { modalPicker = require('ui/common/helpers/modalPicker'); var modalPicker = new modalPicker(Ti.UI.PICKER_TYPE_DATE_AND_TIME,null,date.text); modalPicker.showDatePickerDialog({ value: new Date(date.text), callback: function(e) { if (e.cancel) { } else { //var result = timeFormatted(e.value); date.text = e.value.toDateString(); appointment.date = date.text; } } }); }); time.addEventListener('click', function(e) { modalPicker = require('ui/common/helpers/modalPicker'); var modalPicker = new modalPicker(Ti.UI.PICKER_TYPE_DATE_AND_TIME,null,date.text+' '+time.text); modalPicker.showTimePickerDialog({ value: new Date(date.text+' '+time.text), callback: function(e) { if (e.cancel) { } else { var result = timeFormatted(e.value); time.text = result.time; appointment.time = time.text; } } }); }); return window; } module.exports = appointment;
leokenner/SE-Android
Resources/ui/common/forms/appointment_form.js
JavaScript
apache-2.0
11,099
"use strict"; var chakram = require("chakram"), util = require("util"), curry = require("curry"), Q = require("q"), auth = require("../common/auth.js"), common = require("./common.js"), sharing = require("../sharing/common.js"), habits = require("../habits/common.js"), journal = require("../journal/common.js"), doctors = require("../doctors/common.js"), pharmacies = require("../pharmacies/common.js"), medications = require("../medications/common.js"), doses = require("../doses/common.js"); var expect = chakram.expect; describe("Patients", function () { describe("View Patient JSON Data Dump (GET /patients/:patientid.json)", function () { // basic endpoint var dump = function (patientId, accessToken) { var url = util.format("http://localhost:5000/v1/patients/%d.json", patientId); return chakram.get(url, auth.genAuthHeaders(accessToken)); }; var dumpPatient = function (patient) { return dump(patient._id, patient.user.accessToken); }; // check an authenticated user is required common.itRequiresAuthentication(dump); // check it requires a valid patient ID corresponding to a patient we have read // access to common.itRequiresValidPatientId(dump); common.itRequiresReadAuthorization(dumpPatient); describe("with test data set up", function () { // setup test user var user; before(function () { return auth.createTestUser(undefined, true).then(function (u) { user = u; }); }); // setup test patient owned by another user, shared with this patient in the // anyone group var patient; before(function () { // create patient return auth.createTestUser(undefined, true).then(curry(common.createOtherPatient)({}, user)).then(function (p) { patient = p; // share patient return Q.nbind(patient.share, patient)(user.email, "default", "anyone"); }); }); // setup test doctor before(function () { return Q.nbind(patient.createDoctor, patient)({ name: "test doctor" }); }); // setup test pharmacy before(function () { return Q.nbind(patient.createPharmacy, patient)({ name: "test pharmacy" }); }); // setup test medication we have access to var shownMed; before(function () { return Q.nbind(patient.createMedication, patient)({ name: "test medication" }).then(function (m) { shownMed = m; }); }); // setup test medication we have no access to var hiddenMed; before(function () { return Q.nbind(patient.createMedication, patient)({ name: "test medication", access_anyone: "none" }).then(function (m) { hiddenMed = m; }); }); // create journal entry we have access to var shownEntry; before(function () { return Q.nbind(patient.createJournalEntry, patient)({ date: {utc: (new Date()).toISOString(), timezone: "America/Los_Angeles"}, text: "example journal entry", creator: "adam@west.com", medication_ids: [shownMed._id] }).then(function (e) { shownEntry = e; }); }); // create journal entry we have no access to before(function () { return Q.nbind(patient.createJournalEntry, patient)({ date: {utc: (new Date()).toISOString(), timezone: "America/Los_Angeles"}, text: "example journal entry", creator: "adam@west.com", medication_ids: [hiddenMed._id] }); }); // create dose event we have access to var shownDose; before(function () { return Q.nbind(patient.createDose, patient)({ medication_id: shownMed._id, date: {utc: (new Date()).toISOString(), timezone: "America/Los_Angeles"}, creator: "adam@west.com", taken: true }).then(function (d) { shownDose = d; }); }); // create dose event we have no access to before(function () { return Q.nbind(patient.createDose, patient)({ medication_id: hiddenMed._id, date: {utc: (new Date()).toISOString(), timezone: "America/Los_Angeles"}, creator: "adam@west.com", taken: true }); }); // get dump var response, dump; before(function () { return dumpPatient(patient).then(function (r) { response = r; dump = r.body; }); }); before(function (done) { require("fs").writeFile("/tmp/test.json", JSON.stringify(dump, null, 4), done); }); it("returns a valid dump", function () { expect(response).to.be.a.patient.dumpSuccess; }); it("contains the patient's details", function () { // remove success and ignore additional properties (not just patient // data shown here); var patientSchema = JSON.parse(JSON.stringify(common.schema)); patientSchema.required.splice(patientSchema.required.indexOf("success"), 1); delete patientSchema.properties.success; patientSchema.additionalProperties = true; expect(dump).to.have.property("patient"); expect({ body: dump.patient }).to.have.schema(patientSchema); }); it("contains users the patient is shared with", function () { // success removed by genericListSuccess expect(response).to.be.an.api.genericListSuccess("shares", sharing.schema, false); // share for owner and share with current user expect(dump.shares.length).to.equal(2); }); it("contains the patient's habits", function () { // remove success key var habitsSchema = JSON.parse(JSON.stringify(habits.schema)); habitsSchema.required.splice(habitsSchema.required.indexOf("success"), 1); delete habitsSchema.properties.success; habitsSchema.additionalProperties = true; // chakram schema validation checks the schema of obj.body expect(dump).to.have.property("habits"); expect({ body: dump.habits }).to.have.schema(habitsSchema); }); it("contains the patient's journal entries", function () { // success removed by genericListSuccess expect(response).to.be.an.api.genericListSuccess("entries", journal.schema, false); }); it("only shows journal entries we have access to medications for", function () { expect(dump.entries.length).to.equal(1); expect(dump.entries[0].id).to.equal(shownEntry._id); }); it("contains the patient's doctors", function () { // success removed by genericListSuccess expect(response).to.be.an.api.genericListSuccess("doctors", doctors.schema, false); // one doctor created expect(dump.doctors.length).to.equal(1); }); it("contains the patient's pharmacies", function () { // success removed by genericListSuccess expect(response).to.be.an.api.genericListSuccess("pharmacies", pharmacies.schema, false); // one pharmacy created expect(dump.pharmacies.length).to.equal(1); }); it("contains the patient's medications", function () { // success removed by genericListSuccess // but additional properties (e.g., summary) are added var medicationsSchema = JSON.parse(JSON.stringify(medications.schema)); medicationsSchema.additionalProperties = true; expect(response).to.be.an.api.genericListSuccess("medications", medicationsSchema, false); }); it("only shows medications the user has access to", function () { expect(dump.medications.length).to.equal(1); expect(dump.medications[0].id).to.equal(shownMed._id); }); it("contains the patient's doses", function () { // success removed by genericListSuccess expect(response).to.be.an.api.genericListSuccess("doses", doses.schema, false); }); it("only shows doses the user has access to", function () { expect(dump.doses.length).to.equal(1); expect(dump.doses[0].id).to.equal(shownDose._id); }); }); }); });
amida-tech/orange-api
test/patients/dump_patient_test.js
JavaScript
apache-2.0
9,896
let obj = { @readonly firstName: "first", @readonly lastName: "last", @nonconfigurable fullName() { return `${this.firstName} ${this.lastName}`; } }; /* // Desugaring // // The following is an approximate down-level desugaring to match the expected semantics. // The actual host implementation would generally be more efficient. let obj = declareObject( // Object literal declaration { firstName: "first", lastName: "last", fullName() { return `${this.firstName} ${this.lastName}`; } }, // Object description { members: [ { kind: "property", name: "firstName", decorations: [readonly] }, { kind: "property", name: "lastName", decorations: [readonly] }, { kind: "method", name: "fullName", decorations: [nonconfigurable] } ] } ).finishDeclarationInitialization(); */
rbuckton/ecmascript-mirrors
samples/objects.js
JavaScript
apache-2.0
945
/* Copyright 2017 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var _primitives = require('../../core/primitives'); describe('primitives', function () { function XRefMock(array) { this.map = Object.create(null); for (var elem in array) { var obj = array[elem]; var ref = obj.ref, data = obj.data; this.map[ref.toString()] = data; } } XRefMock.prototype = { fetch: function fetch(ref) { return this.map[ref.toString()]; }, fetchIfRef: function fetchIfRef(obj) { if (!(0, _primitives.isRef)(obj)) { return obj; } return this.fetch(obj); }, fetchAsync: function fetchAsync(ref) { return Promise.resolve(this.fetch(ref)); }, fetchIfRefAsync: function fetchIfRefAsync(obj) { return Promise.resolve(this.fetchIfRef(obj)); } }; describe('Name', function () { it('should retain the given name', function () { var givenName = 'Font'; var name = _primitives.Name.get(givenName); expect(name.name).toEqual(givenName); }); it('should create only one object for a name and cache it', function () { var firstFont = _primitives.Name.get('Font'); var secondFont = _primitives.Name.get('Font'); var firstSubtype = _primitives.Name.get('Subtype'); var secondSubtype = _primitives.Name.get('Subtype'); expect(firstFont).toBe(secondFont); expect(firstSubtype).toBe(secondSubtype); expect(firstFont).not.toBe(firstSubtype); }); }); describe('Cmd', function () { it('should retain the given cmd name', function () { var givenCmd = 'BT'; var cmd = _primitives.Cmd.get(givenCmd); expect(cmd.cmd).toEqual(givenCmd); }); it('should create only one object for a command and cache it', function () { var firstBT = _primitives.Cmd.get('BT'); var secondBT = _primitives.Cmd.get('BT'); var firstET = _primitives.Cmd.get('ET'); var secondET = _primitives.Cmd.get('ET'); expect(firstBT).toBe(secondBT); expect(firstET).toBe(secondET); expect(firstBT).not.toBe(firstET); }); }); describe('Dict', function () { var checkInvalidHasValues = function checkInvalidHasValues(dict) { expect(dict.has()).toBeFalsy(); expect(dict.has('Prev')).toBeFalsy(); }; var checkInvalidKeyValues = function checkInvalidKeyValues(dict) { expect(dict.get()).toBeUndefined(); expect(dict.get('Prev')).toBeUndefined(); expect(dict.get('Decode', 'D')).toBeUndefined(); expect(dict.get('FontFile', 'FontFile2', 'FontFile3')).toBeNull(); }; var emptyDict, dictWithSizeKey, dictWithManyKeys; var storedSize = 42; var testFontFile = 'file1'; var testFontFile2 = 'file2'; var testFontFile3 = 'file3'; beforeAll(function (done) { emptyDict = new _primitives.Dict(); dictWithSizeKey = new _primitives.Dict(); dictWithSizeKey.set('Size', storedSize); dictWithManyKeys = new _primitives.Dict(); dictWithManyKeys.set('FontFile', testFontFile); dictWithManyKeys.set('FontFile2', testFontFile2); dictWithManyKeys.set('FontFile3', testFontFile3); done(); }); afterAll(function () { emptyDict = dictWithSizeKey = dictWithManyKeys = null; }); it('should return invalid values for unknown keys', function () { checkInvalidHasValues(emptyDict); checkInvalidKeyValues(emptyDict); }); it('should return correct value for stored Size key', function () { expect(dictWithSizeKey.has('Size')).toBeTruthy(); expect(dictWithSizeKey.get('Size')).toEqual(storedSize); expect(dictWithSizeKey.get('Prev', 'Size')).toEqual(storedSize); expect(dictWithSizeKey.get('Prev', 'Root', 'Size')).toEqual(storedSize); }); it('should return invalid values for unknown keys when Size key is stored', function () { checkInvalidHasValues(dictWithSizeKey); checkInvalidKeyValues(dictWithSizeKey); }); it('should return correct value for stored Size key with undefined value', function () { var dict = new _primitives.Dict(); dict.set('Size'); expect(dict.has('Size')).toBeTruthy(); checkInvalidKeyValues(dict); }); it('should return correct values for multiple stored keys', function () { expect(dictWithManyKeys.has('FontFile')).toBeTruthy(); expect(dictWithManyKeys.has('FontFile2')).toBeTruthy(); expect(dictWithManyKeys.has('FontFile3')).toBeTruthy(); expect(dictWithManyKeys.get('FontFile3')).toEqual(testFontFile3); expect(dictWithManyKeys.get('FontFile2', 'FontFile3')).toEqual(testFontFile2); expect(dictWithManyKeys.get('FontFile', 'FontFile2', 'FontFile3')).toEqual(testFontFile); }); it('should asynchronously fetch unknown keys', function (done) { var keyPromises = [dictWithManyKeys.getAsync('Size'), dictWithSizeKey.getAsync('FontFile', 'FontFile2', 'FontFile3')]; Promise.all(keyPromises).then(function (values) { expect(values[0]).toBeUndefined(); expect(values[1]).toBeNull(); done(); }).catch(function (reason) { done.fail(reason); }); }); it('should asynchronously fetch correct values for multiple stored keys', function (done) { var keyPromises = [dictWithManyKeys.getAsync('FontFile3'), dictWithManyKeys.getAsync('FontFile2', 'FontFile3'), dictWithManyKeys.getAsync('FontFile', 'FontFile2', 'FontFile3')]; Promise.all(keyPromises).then(function (values) { expect(values[0]).toEqual(testFontFile3); expect(values[1]).toEqual(testFontFile2); expect(values[2]).toEqual(testFontFile); done(); }).catch(function (reason) { done.fail(reason); }); }); it('should callback for each stored key', function () { var callbackSpy = jasmine.createSpy('spy on callback in dictionary'); dictWithManyKeys.forEach(callbackSpy); expect(callbackSpy).toHaveBeenCalled(); var callbackSpyCalls = callbackSpy.calls; expect(callbackSpyCalls.argsFor(0)).toEqual(['FontFile', testFontFile]); expect(callbackSpyCalls.argsFor(1)).toEqual(['FontFile2', testFontFile2]); expect(callbackSpyCalls.argsFor(2)).toEqual(['FontFile3', testFontFile3]); expect(callbackSpyCalls.count()).toEqual(3); }); it('should handle keys pointing to indirect objects, both sync and async', function (done) { var fontRef = new _primitives.Ref(1, 0); var xref = new XRefMock([{ ref: fontRef, data: testFontFile }]); var fontDict = new _primitives.Dict(xref); fontDict.set('FontFile', fontRef); expect(fontDict.getRaw('FontFile')).toEqual(fontRef); expect(fontDict.get('FontFile', 'FontFile2', 'FontFile3')).toEqual(testFontFile); fontDict.getAsync('FontFile', 'FontFile2', 'FontFile3').then(function (value) { expect(value).toEqual(testFontFile); done(); }).catch(function (reason) { done.fail(reason); }); }); it('should handle arrays containing indirect objects', function () { var minCoordRef = new _primitives.Ref(1, 0), maxCoordRef = new _primitives.Ref(2, 0); var minCoord = 0, maxCoord = 1; var xref = new XRefMock([{ ref: minCoordRef, data: minCoord }, { ref: maxCoordRef, data: maxCoord }]); var xObjectDict = new _primitives.Dict(xref); xObjectDict.set('BBox', [minCoord, maxCoord, minCoordRef, maxCoordRef]); expect(xObjectDict.get('BBox')).toEqual([minCoord, maxCoord, minCoordRef, maxCoordRef]); expect(xObjectDict.getArray('BBox')).toEqual([minCoord, maxCoord, minCoord, maxCoord]); }); it('should get all key names', function () { var expectedKeys = ['FontFile', 'FontFile2', 'FontFile3']; var keys = dictWithManyKeys.getKeys(); expect(keys.sort()).toEqual(expectedKeys); }); it('should create only one object for Dict.empty', function () { var firstDictEmpty = _primitives.Dict.empty; var secondDictEmpty = _primitives.Dict.empty; expect(firstDictEmpty).toBe(secondDictEmpty); expect(firstDictEmpty).not.toBe(emptyDict); }); it('should correctly merge dictionaries', function () { var expectedKeys = ['FontFile', 'FontFile2', 'FontFile3', 'Size']; var fontFileDict = new _primitives.Dict(); fontFileDict.set('FontFile', 'Type1 font file'); var mergedDict = _primitives.Dict.merge(null, [dictWithManyKeys, dictWithSizeKey, fontFileDict]); var mergedKeys = mergedDict.getKeys(); expect(mergedKeys.sort()).toEqual(expectedKeys); expect(mergedDict.get('FontFile')).toEqual(testFontFile); }); }); describe('Ref', function () { it('should retain the stored values', function () { var storedNum = 4; var storedGen = 2; var ref = new _primitives.Ref(storedNum, storedGen); expect(ref.num).toEqual(storedNum); expect(ref.gen).toEqual(storedGen); }); }); describe('RefSet', function () { it('should have a stored value', function () { var ref = new _primitives.Ref(4, 2); var refset = new _primitives.RefSet(); refset.put(ref); expect(refset.has(ref)).toBeTruthy(); }); it('should not have an unknown value', function () { var ref = new _primitives.Ref(4, 2); var refset = new _primitives.RefSet(); expect(refset.has(ref)).toBeFalsy(); refset.put(ref); var anotherRef = new _primitives.Ref(2, 4); expect(refset.has(anotherRef)).toBeFalsy(); }); }); describe('isName', function () { it('handles non-names', function () { var nonName = {}; expect((0, _primitives.isName)(nonName)).toEqual(false); }); it('handles names', function () { var name = _primitives.Name.get('Font'); expect((0, _primitives.isName)(name)).toEqual(true); }); it('handles names with name check', function () { var name = _primitives.Name.get('Font'); expect((0, _primitives.isName)(name, 'Font')).toEqual(true); expect((0, _primitives.isName)(name, 'Subtype')).toEqual(false); }); }); describe('isCmd', function () { it('handles non-commands', function () { var nonCmd = {}; expect((0, _primitives.isCmd)(nonCmd)).toEqual(false); }); it('handles commands', function () { var cmd = _primitives.Cmd.get('BT'); expect((0, _primitives.isCmd)(cmd)).toEqual(true); }); it('handles commands with cmd check', function () { var cmd = _primitives.Cmd.get('BT'); expect((0, _primitives.isCmd)(cmd, 'BT')).toEqual(true); expect((0, _primitives.isCmd)(cmd, 'ET')).toEqual(false); }); }); describe('isDict', function () { it('handles non-dictionaries', function () { var nonDict = {}; expect((0, _primitives.isDict)(nonDict)).toEqual(false); }); it('handles empty dictionaries with type check', function () { var dict = _primitives.Dict.empty; expect((0, _primitives.isDict)(dict)).toEqual(true); expect((0, _primitives.isDict)(dict, 'Page')).toEqual(false); }); it('handles dictionaries with type check', function () { var dict = new _primitives.Dict(); dict.set('Type', _primitives.Name.get('Page')); expect((0, _primitives.isDict)(dict, 'Page')).toEqual(true); expect((0, _primitives.isDict)(dict, 'Contents')).toEqual(false); }); }); describe('isRef', function () { it('handles non-refs', function () { var nonRef = {}; expect((0, _primitives.isRef)(nonRef)).toEqual(false); }); it('handles refs', function () { var ref = new _primitives.Ref(1, 0); expect((0, _primitives.isRef)(ref)).toEqual(true); }); }); describe('isRefsEqual', function () { it('should handle different Refs pointing to the same object', function () { var ref1 = new _primitives.Ref(1, 0); var ref2 = new _primitives.Ref(1, 0); expect((0, _primitives.isRefsEqual)(ref1, ref2)).toEqual(true); }); it('should handle Refs pointing to different objects', function () { var ref1 = new _primitives.Ref(1, 0); var ref2 = new _primitives.Ref(2, 0); expect((0, _primitives.isRefsEqual)(ref1, ref2)).toEqual(false); }); }); });
rcassola/DigiCard
src/main/webapp/bower_components/pdfjs-dist/lib/test/unit/primitives_spec.js
JavaScript
apache-2.0
12,916
'use strict'; angular.module('moviefanApp') .controller('LoginController', function ($rootScope, $scope, $state, $timeout, Auth) { $scope.user = {}; $scope.errors = {}; $scope.rememberMe = true; $timeout(function (){angular.element('[ng-model="username"]').focus();}); $scope.login = function (event) { event.preventDefault(); Auth.login({ username: $scope.username, password: $scope.password, rememberMe: $scope.rememberMe }).then(function () { $scope.authenticationError = false; if ($rootScope.previousStateName === 'register') { $state.go('home'); } else { $rootScope.back(); } }).catch(function () { $scope.authenticationError = true; }); }; });
ozkangokturk/moviefan
src/main/webapp/scripts/app/account/login/login.controller.js
JavaScript
apache-2.0
937
/* * ../../../..//jax/input/MathML/entities/k.js * * Copyright (c) 2009-2018 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /************************************************************* * * MathJax/jax/output/HTML-CSS/entities/k.js * * Copyright (c) 2010-2018 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ (function(MATHML) { MathJax.Hub.Insert(MATHML.Parse.Entity, { KHcy: "\u0425", KJcy: "\u040C", Kappa: "\u039A", Kcedil: "\u0136", Kcy: "\u041A", kcedil: "\u0137", kcy: "\u043A", kgreen: "\u0138", khcy: "\u0445", kjcy: "\u045C" }); MathJax.Ajax.loadComplete(MATHML.entityDir + "/k.js"); })(MathJax.InputJax.MathML);
GerHobbelt/MathJax
jax/input/MathML/entities/k.js
JavaScript
apache-2.0
1,778
var clusterpost = require("clusterpost-lib"); var path = require('path'); var Promise = require('bluebird'); var argv = require('minimist')(process.argv.slice(2)); const os = require('os'); const fs = require('fs'); var agentoptions = { rejectUnauthorized: false } clusterpost.setAgentOptions(agentoptions); const help = function(){ console.error("Help: Download tasks from the server."); console.error("\nOptional parameters:"); console.error("--dir Output directory, default: ./out"); console.error("--status one of [DONE, RUN, FAIL, EXIT, UPLOADING, CREATE], default: DONE"); console.error("--print , if provided the information is printed only"); console.error("--delete, default false, when downloading jobs with status 'DONE', the jobs will be deleted upon completion"); console.error("--j job id, default: "); console.error("--executable executable, default: all executables"); console.error("--email email, default: (authenticated user)"); console.error("--config_codename codename, default: clusterpost"); } if(argv["h"] || argv["help"]){ help(); process.exit(1); } var deletejobs = false; if(argv["delete"] !== undefined){ console.log("After successful download, jobs with status DONE will be deleted!"); deletejobs = true; } var userEmail = undefined; if(argv["email"]){ userEmail = argv["email"]; } var outputdir = "./out"; if(argv["dir"]){ outputdir = argv["dir"]; } var status = 'DONE'; if(argv["status"]){ status = argv["status"]; } var jobid = argv["j"]; var executable = argv["executable"]; var print = argv["print"]; console.log("Output dir", outputdir); console.log("Status", status); if(jobid){ console.log("jobid", jobid); } if(executable){ console.log("executable", executable); } if(print){ console.log("print", print); } var config_codename = 'clusterpost'; if(argv["config_codename"]){ config_codename = argv["config_codename"]; } clusterpost.start(path.join(os.homedir(), '.' + config_codename + '.json')) .then(function(){ if(!print){ if(!jobid){ return clusterpost.getJobs(executable, status, userEmail) .then(function(jobs){ return Promise.map(jobs, function(job){ console.log(JSON.stringify(job, null, 2)); if(job.outputdir){ return clusterpost.getJobOutputs(job, job.outputdir) .then(function(){ if(job.name){ console.log(job.name, "downloaded..."); }else{ console.log(job._id, "downloaded..."); } if(deletejobs){ console.log("Deleting job"); return clusterpost.deleteJob(job._id); } }); }else{ var joboutputdir = undefined; if(job.name){ joboutputdir = path.join(outputdir, job.name); }else{ joboutputdir = path.join(outputdir, job._id); } return clusterpost.getJobOutputs(job, joboutputdir) .then(function(){ if(job.name){ console.log(job.name, "downloaded..."); }else{ console.log(job._id, "downloaded..."); } if(deletejobs){ console.log("Deleting job"); return clusterpost.deleteJob(job._id); } }); } }, { concurrency: 1 }); }); }else{ return clusterpost.getDocument(jobid) .then(function(job){ if(job.outputdir){ return clusterpost.getJobOutputs(job, job.outputdir); }else{ var joboutputdir = undefined; if(job.name){ joboutputdir = path.join(outputdir, job.name); }else{ joboutputdir = path.join(outputdir, job._id); } return clusterpost.getJobOutputs(job, joboutputdir); } }) .then(function(){ console.log("job downloaded..."); if(deletejobs){ console.log("Deleting job"); return clusterpost.deleteJob(jobid); } }); } }else{ if(!jobid){ return clusterpost.getJobs(executable, status, userEmail) .then(function(jobs){ console.log(JSON.stringify(jobs, null, 2)) }); }else{ return clusterpost.getDocument(jobid) .then(function(job){ console.log(JSON.stringify(job, null, 2)) }); } } }) .catch(console.error)
juanprietob/clusterpost
src/clusterpost-app/get.js
JavaScript
apache-2.0
5,412
'use strict'; angular.module('aquilaApp') .config(function ($stateProvider) { $stateProvider .state('register', { parent: 'account', url: '/register', data: { roles: [], pageTitle: 'register.title' }, views: { 'content@': { templateUrl: 'scripts/app/account/register/register.html', controller: 'RegisterController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('register'); return $translate.refresh(); }] } }); });
onpointtech/stack-reference
src/main/webapp/scripts/app/account/register/register.js
JavaScript
apache-2.0
919
/** * 微信网页端调用JS * @author dodge * @contact dodgepudding@gmail.com * @link http://blog.4wer.com/wechat-timeline-share * @version 1.1 * * 自定义分享使用: * WeixinJS.hideOptionMenu() 隐藏右上角按钮 * WeixinJS.showOptionMenu() 显示右上角按钮 * WeixinJS.hideToolbar() 隐藏工具栏 * WeixinJS.showToolbar() 显示工具栏 * WeixinJS.getNetworkType() 获取网络状态 * WeixinJS.closeWindow() 关闭窗口 * WeixinJS.scanQRCode() 扫描二维码 * WeixinJS.openUrlByExtBrowser(url) 使用浏览器打开网址 * WeixinJS.jumpToBizProfile(username) 跳转到指定公众账号页面 * WeixinJS.sendEmail(title,content) 发送邮件 * WeixinJS.openProductView(latitude,longitude,name,address,scale,infoUrl) 查看地图 * WeixinJS.addContact(username) 添加微信账号 * WeixinJS.imagePreview(urls,current) 调出微信内图片预览 * WeixinJS.payCallback(appId,package,timeStamp,nonceStr,signType,paySign,callback) 微信JsApi支付接口 * WeixinJS.editAddress(appId,addrSign,timeStamp,nonceStr,callback) 微信JsApi支付接口 * 自定义分享内容数据格式: * var dataForWeixin={ appId:"", MsgImg:"消息图片路径", TLImg:"时间线图路径", url:"分享url路径", title:"标题", desc:"描述", fakeid:"", prepare:function(argv){ if (typeof argv.shareTo!='undefined') switch(argv.shareTo) { case 'friend': //发送给朋友 alert(argv.scene); //friend break; case 'timeline': //发送给朋友 break; case 'weibo': //发送到微博 alert(argv.url); break; case 'favorite': //收藏 alert(argv.scene);//favorite break; case 'connector': //分享到第三方应用 alert(argv.scene);//connector break; default: } }, callback:function(res){ //发送给好友或应用 if (res.err_msg=='send_app_msg:confirm') { //todo:func1(); alert(res.err_desc); } if (res.err_msg=='send_app_msg:cancel') { //todo:func2(); alert(res.err_desc); } //分享到朋友圈 if (res.err_msg=='share_timeline:confirm') { //todo:func1(); alert(res.err_desc); } if (res.err_msg=='share_timeline:cancel') { //todo:func1(); alert(res.err_desc); } //分享到微博 if (res.err_msg=='share_weibo:confirm') { //todo:func1(); alert(res.err_desc); } if (res.err_msg=='share_weibo:cancel') { //todo:func1(); alert(res.err_desc); } //收藏或分享到应用 if (res.err_msg=='send_app_msg:ok') { //todo:func1(); alert(res.err_desc); } } }; */ WeixinJS = typeof WeixinJS!='undefined' || {}; //隐藏右上角按钮 WeixinJS.hideOptionMenu = function() { document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.call('hideOptionMenu'); }); }; //显示右上角按钮 WeixinJS.showOptionMenu = function() { document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.call('showOptionMenu'); }); }; //隐藏底部导航栏 WeixinJS.hideToolbar = function() { document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.call('hideToolbar'); }); }; //显示底部导航栏 WeixinJS.showToolbar = function() { document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.call('showToolbar'); }); }; //网页获取用户网络状态 netType={"network_type:wifi":"wifi网络","network_type:edge":"非wifi,包含3G/2G","network_type:fail":"网络断开连接","network_type:wwan":"2g或者3g"}; WeixinJS.getNetworkType = function(callback) { document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke('getNetworkType',{}, function(res){ //result: network_type:wifi,network_type:edge,network_type:fail,network_type:wwan //netType[e.err_msg] callback(res.err_msg); }); }); }; //关闭窗口 WeixinJS.closeWindow = function() { if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke("closeWindow", {}); }; //扫描二维码 WeixinJS.scanQRCode = function() { if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke("scanQRCode", {}); }; //使用浏览器打开网址 WeixinJS.openUrlByExtBrowser=function(url){ if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke("openUrlByExtBrowser",{"url" : url}); }; //跳转到指定公众账号页面 WeixinJS.jumpToBizProfile=function(username){ if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke("jumpToBizProfile",{"tousername" : username}); }; //发送邮件 WeixinJS.sendEmail=function(title,content){ if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke("sendEmail",{ "title" : title, "content" : content }); }; //查看地图 WeixinJS.openProductView=function(latitude,longitude,name,address,scale,infoUrl){ if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke("openProductView",{ "latitude" : latitude, //纬度 "longitude" : longitude, //经度 "name" : name, //名称 "address" : address, //地址 "scale" : scale, //地图缩放级别 "infoUrl" : infoUrl, //查看位置界面底部的超链接 }); }; //添加微信账号 WeixinJS.addContact=function weixinAddContact(username){ if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke("addContact", { "webtype": "1", "username": username }, function(e) { WeixinJSBridge.log(e.err_msg); //e.err_msg:add_contact:added 已经添加 //e.err_msg:add_contact:cancel 取消添加 //e.err_msg:add_contact:ok 添加成功 if(e.err_msg == 'add_contact:added' || e.err_msg == 'add_contact:ok'){ //关注成功,或者已经关注过 } }); }; /** * 调出微信内图片预览scrollview * @param array urls 图片url数组 * @param string current 当前图片url */ WeixinJS.imagePreview = function(urls,current) { if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke("imagePreview", { current: current, urls: urls }); }; WeixinJS.payCallback = function(appId,package,timeStamp,nonceStr,signType,paySign,callback){ if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke('getBrandWCPayRequest',{ "appId" : appId.toString(), "timeStamp" : timeStamp.toString(), "nonceStr" : nonceStr.toString(), "package" : package.toString(), "signType" : signType.toString(), "paySign" : paySign.toString() },function(res){ // res.err_msg == "get_brand_wcpay_request:ok" return true; // res.err_msg == "get_brand_wcpay_request:cancel" return false; callback(res); }); }; //编辑收货地址 WeixinJS.editAddress = function(appId,addrSign,timeStamp,nonceStr,callback){ var postdata = { "appId" : appId.toString(), "scope" : "jsapi_address", "signType" : "sha1", "addrSign" : addrSign.toString(), "timeStamp" : timeStamp.toString(), "nonceStr" : nonceStr.toString() }; if (typeof WeixinJSBridge!='undefined') WeixinJSBridge.invoke('editAddress',postdata, function(res){ //return res.proviceFirstStageName,res.addressCitySecondStageName,res.addressCountiesThirdStageName,res.addressDetailInfo,res.userName,res.addressPostalCode,res.telNumber //error return res.err_msg callback(res); }); }; (function(){ if (typeof dataForWeixin=="undefined") return; var onBridgeReady=function(){ WeixinJSBridge.on('menu:share:appmessage', function(argv){ (dataForWeixin.prepare)(argv); WeixinJSBridge.invoke('sendAppMessage',{ "appid":dataForWeixin.appId, "img_url":dataForWeixin.MsgImg, "img_width":"120", "img_height":"120", "link":dataForWeixin.url, "desc":dataForWeixin.desc, "title":dataForWeixin.title }, function(res){(dataForWeixin.callback)(res);}); }); WeixinJSBridge.on('menu:share:timeline', function(argv){ (dataForWeixin.prepare)(argv); WeixinJSBridge.invoke('shareTimeline',{ "img_url":dataForWeixin.TLImg, "img_width":"120", "img_height":"120", "link":dataForWeixin.url, "desc":dataForWeixin.desc, "title":dataForWeixin.title }, function(res){(dataForWeixin.callback)(res);}); }); WeixinJSBridge.on('menu:share:weibo', function(argv){ (dataForWeixin.prepare)(argv); WeixinJSBridge.invoke('shareWeibo',{ "content":dataForWeixin.title, "url":dataForWeixin.url }, function(res){(dataForWeixin.callback)(res);}); }); WeixinJSBridge.on('menu:share:facebook', function(argv){ (dataForWeixin.prepare)(argv); WeixinJSBridge.invoke('shareFB',{ "img_url":dataForWeixin.TLImg, "img_width":"120", "img_height":"120", "link":dataForWeixin.url, "desc":dataForWeixin.desc, "title":dataForWeixin.title }, function(res){(dataForWeixin.callback)(res);}); }); }; if(document.addEventListener){ document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false); }else if(document.attachEvent){ document.attachEvent('WeixinJSBridgeReady' , onBridgeReady); document.attachEvent('onWeixinJSBridgeReady' , onBridgeReady); } })();
selecterskyphp/weixin_award
Public/js/wechat.js
JavaScript
apache-2.0
9,639
var pulse = pulse || {}; pulse.NoteGroup = Backbone.Collection.extend({ model: pulse.Note, });
renfredxh/pulse
app/assets/javascripts/pulse-app/collections/noteGroup.js
JavaScript
apache-2.0
101
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import { act, renderHook } from '@testing-library/react-hooks'; import { SnackbarContext } from '@googleforcreators/design-system'; import { ConfigContext } from '@googleforcreators/story-editor'; /** * Internal dependencies */ import useMediaPicker from '../useMediaPicker'; jest.mock('@googleforcreators/design-system', () => ({ ...jest.requireActual('@googleforcreators/design-system'), useSnackbar: () => { return { showSnackbar: jest.fn(), }; }, })); function setup({ args, cropParams }) { const configValue = { capabilities: { hasUploadMediaAction: true, }, ...args, }; const wrapper = ({ children }) => ( <ConfigContext.Provider value={configValue}> <SnackbarContext.Provider>{children}</SnackbarContext.Provider> </ConfigContext.Provider> ); const onSelect = jest.fn(); const onClose = jest.fn(); const onPermissionError = jest.fn(); const { result } = renderHook( () => useMediaPicker({ onSelect, onClose, onPermissionError, cropParams }), { wrapper, } ); return { openMediaPicker: result.current, onPermissionError, }; } describe('useMediaPicker', () => { it('user unable to upload', () => { const { openMediaPicker, onPermissionError } = setup({ args: { capabilities: { hasUploadMediaAction: false, }, }, }); act(() => { openMediaPicker(new Event('click')); }); expect(onPermissionError).toHaveBeenCalledTimes(1); }); it('user unable to upload with cropped', () => { const { openMediaPicker, onPermissionError } = setup({ args: { capabilities: { hasUploadMediaAction: false, }, }, cropParams: { height: 500, width: 500, flex_width: false, flex_height: false, }, }); act(() => { openMediaPicker(new Event('click')); }); expect(onPermissionError).toHaveBeenCalledTimes(1); }); });
GoogleForCreators/web-stories-wp
packages/wp-story-editor/src/components/mediaUpload/mediaPicker/test/useMediaPicker.js
JavaScript
apache-2.0
2,607
import { clamp, mean, isNaN, get, isArray } from 'lodash'; import update from 'immutability-helper'; import { helpers } from 'veritone-redux-common'; const { createReducer } = helpers; export const PICK_START = 'PICK_START'; export const PICK_END = 'PICK_END'; export const RETRY_REQUEST = 'RETRY_REQUEST'; export const RETRY_DONE = 'RETRY_DONE'; export const ABORT_REQUEST = 'ABORT_REQUEST'; export const UPLOAD_REQUEST = 'UPLOAD_REQUEST'; export const UPLOAD_PROGRESS = 'UPLOAD_PROGRESS'; export const UPLOAD_COMPLETE = 'UPLOAD_COMPLETE'; export const CLEAR_FILEPICKER_DATA = 'CLEAR_FILEPICKER_DATA'; export const namespace = 'filePicker'; const defaultPickerState = { open: false, state: 'selecting', // selecting | uploading | complete progressPercentByFileKey: {}, success: false, error: false, warning: false, uploadResult: null }; const defaultState = { // populated like: // [pickerId]: { ...defaultPickerState } }; export default createReducer(defaultState, { [PICK_START]( state, { meta: { id } } ) { return { [id]: { ...defaultPickerState, open: true, state: 'selecting' } }; }, [PICK_END]( state, { meta: { id } } ) { return { ...state, [id]: { ...state[id], open: false } }; }, [CLEAR_FILEPICKER_DATA]( state, { meta: { id } } ) { return update(state, { $unset: [id] }); }, [ABORT_REQUEST]( state, { meta: { id, fileKey } } ) { let newProgressPercentByFileKey = get(state, [id, 'progressPercentByFileKey'], {}); if (fileKey) { newProgressPercentByFileKey = update(newProgressPercentByFileKey, { [fileKey]: { aborted: { $set: 'aborted' } } }); } else { Object.keys(get(state, [id, 'progressPercentByFileKey'], {})).forEach(fileKey => { newProgressPercentByFileKey = update(newProgressPercentByFileKey, { [fileKey]: { aborted: { $set: 'aborted' } } }); }); } return { ...state, [id]: { ...state[id], progressPercentByFileKey: newProgressPercentByFileKey } } }, [RETRY_REQUEST]( state, { meta: { id } } ) { return { ...state, [id]: { ...state[id], state: 'uploading', progressPercentByFileKey: {}, success: null, error: null, warning: null } } }, [RETRY_DONE]( state, { meta: { id } } ) { return { ...state, [id]: { ...state[id], state: 'complete' } }; }, [UPLOAD_REQUEST]( state, { meta: { id } } ) { // todo: status message return { ...state, [id]: { ...state[id], state: 'uploading', progressPercentByFileKey: {}, success: null, error: null, warning: null, uploadResult: null } }; }, [UPLOAD_PROGRESS]( state, { payload, meta: { fileKey, id } } ) { // todo: status message return { ...state, [id]: { ...state[id], progressPercentByFileKey: { ...state[id].progressPercentByFileKey, [fileKey]: { ...state[id].progressPercentByFileKey[fileKey], ...payload } } } }; }, [UPLOAD_COMPLETE]( state, { payload, meta: { warning, error, id } } ) { const errorMessage = get(error, 'message', error); // Error or string // Extract failed files to be reuploaded const failedFiles = isArray(payload) ? payload .filter(result => result.error) .map(result => result.file) : []; // Combine existing uploadResult if any const prevUploadResult = (get(state, [id, 'uploadResult']) || []) .filter(result => !result.error); return { ...state, [id]: { ...state[id], success: !(warning || error) || null, error: error ? errorMessage : null, warning: warning || null, state: 'complete', uploadResult: prevUploadResult.concat(payload), failedFiles } }; } }); const local = state => state[namespace]; export const pick = id => ({ type: PICK_START, meta: { id } }); export const endPick = id => ({ type: PICK_END, meta: { id } }); export const retryRequest = (id, callback) => ({ type: RETRY_REQUEST, payload: { callback }, meta: { id } }); export const abortRequest = (id, fileKey) => ({ type: ABORT_REQUEST, meta: { id, fileKey } }); export const retryDone = (id, callback) => ({ type: RETRY_DONE, payload: { callback }, meta: { id } }); export const uploadRequest = (id, files, callback) => ({ type: UPLOAD_REQUEST, payload: { files, callback }, meta: { id } }); export const uploadProgress = (id, fileKey, data) => ({ type: UPLOAD_PROGRESS, payload: { ...data, percent: clamp(Math.round(data.percent), 100) }, meta: { fileKey, id } }); export const uploadComplete = (id, result, { warning, error }) => ({ type: UPLOAD_COMPLETE, payload: result, meta: { warning, error, id } }); export const isOpen = (state, id) => get(local(state), [id, 'open']); export const state = (state, id) => get(local(state), [id, 'state'], 'selecting'); // Keep this in case we want to go back to using mean percentage progresses export const progressPercent = (state, id) => { const currentProgress = get(local(state), [id, 'progressPercentByFileKey']); if (!currentProgress) { return 0; } const meanProgress = mean(Object.values(currentProgress)); const rounded = Math.round(meanProgress); return isNaN(rounded) ? 0 : rounded; }; export const percentByFiles = (state, id) => { const currentFiles = get(local(state), [id, 'progressPercentByFileKey'], {}); return Object.keys(currentFiles).map(key => { const value = currentFiles[key]; return { key, value }; }) } export const failedFiles = (state, id) => { const failedFiles = get(local(state), [id, 'failedFiles'], []); return failedFiles; }; export const uploadResult = (state, id) => get(local(state), [id, 'uploadResult']); export const didSucceed = (state, id) => !!get(local(state), [id, 'success']); export const didError = (state, id) => !!get(local(state), [id, 'error']); export const didWarn = (state, id) => !!get(local(state), [id, 'warning']); // todo: status message for normal cases export const statusMessage = (state, id) => get(local(state), [id, 'warning']) || get(local(state), [id, 'error']) || '';
veritone/veritone-sdk
packages/veritone-widgets/src/redux/modules/filePicker/index.js
JavaScript
apache-2.0
6,708
/** * @license * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const Audit = require('../../../audits/accessibility/aria-allowed-attr.js'); const assert = require('assert'); /* eslint-env mocha */ describe('Accessibility: aria-allowed-attr audit', () => { it('generates an audit output', () => { const artifacts = { Accessibility: { violations: [{ id: 'aria-allowed-attr', nodes: [], help: 'http://example.com/' }] } }; const output = Audit.audit(artifacts); assert.equal(output.rawValue, false); assert.equal(output.displayValue, ''); }); it('generates an audit output (single node)', () => { const artifacts = { Accessibility: { violations: [{ id: 'aria-allowed-attr', nodes: [{}], help: 'http://example.com/' }] } }; const output = Audit.audit(artifacts); assert.equal(output.rawValue, false); assert.equal(output.displayValue, ''); }); });
tommycli/lighthouse
lighthouse-core/test/audits/accessibility/aria-allowed-attr-test.js
JavaScript
apache-2.0
1,594
import Vue from 'vue' import App from './App.vue' import './registerServiceWorker' import router from './router' import store from './store' import vuetify from './plugins/vuetify'; import 'roboto-fontface/css/roboto/roboto-fontface.css' import '@mdi/font/css/materialdesignicons.css' import VueCompositionApi from "@vue/composition-api"; Vue.use(VueCompositionApi); Vue.config.productionTip = false new Vue({ router, store, vuetify, render: h => h(App) }).$mount('#app')
FDSoftware/OpenEFI-Tuner
src/main.js
JavaScript
apache-2.0
483
/** * @namespace export */ module.exports = { CmConfiguration: require('./CmConfiguration.js').CmConfiguration, CmExporter: require('./CmExporter.js').CmExporter, CmRenderer: require('./CmRenderer.js').CmRenderer, CmTransformer: require('./CmTransformer.js').CmTransformer, renderer: require('./renderer/index.js'), transformer: require('./transformer/index.js') };
entoj/entoj-export-cm
source/export/index.js
JavaScript
apache-2.0
392
import { setPropertiesFromJSON } from '../../json-helper'; import Entity from './Entity'; /** * Generated class for shr.entity.Group. * @extends Entity */ class Group extends Entity { /** * Get the entry information. * @returns {Entry} The shr.base.Entry */ get entryInfo() { return this._entryInfo; } /** * Set the entry information. * @param {Entry} entryInfo - The shr.base.Entry */ set entryInfo(entryInfo) { this._entryInfo = entryInfo; } /** * Get the Type. * @returns {Type} The shr.entity.Type */ get type() { return this._type; } /** * Set the Type. * @param {Type} type - The shr.entity.Type */ set type(type) { this._type = type; } /** * Get the ActiveFlag. * @returns {ActiveFlag} The shr.entity.ActiveFlag */ get activeFlag() { return this._activeFlag; } /** * Set the ActiveFlag. * @param {ActiveFlag} activeFlag - The shr.entity.ActiveFlag */ set activeFlag(activeFlag) { this._activeFlag = activeFlag; } /** * Get the Title. * @returns {Title} The shr.core.Title */ get title() { return this._title; } /** * Set the Title. * @param {Title} title - The shr.core.Title */ set title(title) { this._title = title; } /** * Get the Definitional. * @returns {Definitional} The shr.core.Definitional */ get definitional() { return this._definitional; } /** * Set the Definitional. * @param {Definitional} definitional - The shr.core.Definitional */ set definitional(definitional) { this._definitional = definitional; } /** * Get the MembershipCriterion array. * @returns {Array<MembershipCriterion>} The shr.entity.MembershipCriterion array */ get membershipCriterion() { return this._membershipCriterion; } /** * Set the MembershipCriterion array. * @param {Array<MembershipCriterion>} membershipCriterion - The shr.entity.MembershipCriterion array */ set membershipCriterion(membershipCriterion) { this._membershipCriterion = membershipCriterion; } /** * Get the Member array. * @returns {Array<Member>} The shr.entity.Member array */ get member() { return this._member; } /** * Set the Member array. * @param {Array<Member>} member - The shr.entity.Member array */ set member(member) { this._member = member; } /** * Get the Count. * @returns {Count} The shr.core.Count */ get count() { return this._count; } /** * Set the Count. * @param {Count} count - The shr.core.Count */ set count(count) { this._count = count; } /** * Deserializes JSON data to an instance of the Group class. * The JSON must be valid against the Group JSON schema, although this is not validated by the function. * @param {object} json - the JSON data to deserialize * @returns {Group} An instance of Group populated with the JSON data */ static fromJSON(json={}) { const inst = new Group(); setPropertiesFromJSON(inst, json); return inst; } } export default Group;
standardhealth/flux
src/model/shr/entity/Group.js
JavaScript
apache-2.0
3,110
import React from 'react'; export default () => {return <h1>Page Under Construction</h1>}
mrFlick72/mrFlick72.github.io
app/page/PageUnderConstruction.js
JavaScript
apache-2.0
90
// a Bar chart Bridle.BarChart = function() { var mode = 'stacked'; var margin = { top : 50, bottom : 100, left : 100, right : 100 }; var height = 400; var width = 1000; var xValue = function(d) { return d.x; }; var yValue = function(d) { return d.y; }; var nameValue = function(d) { return d.name; }; var values = function(d) { return d.values; }; var offset = 'zero'; var order = 'default'; var yScale = d3.scale.linear(); var colors = d3.scale.category10(); var yAxis = d3.svg.axis().scale(yScale).orient('left'); var title = 'Chart Title'; var yAxisTitle = 'Axis Title'; var duration = 1000; var legend = Bridle.LegendBox().nameAccessor(function(d) { return nameValue(d); }); // set legend's colors to be the same as for the chart legend.colors(colors); var xScale = d3.scale.ordinal(); var xAxis = d3.svg.axis() .scale(xScale) .tickSize(5) .orient('bottom'); var tickFormat = d3.time.format('%Y-%m-%d'); var formatterX = d3.time.format('%Y-%m-%d'); var formatterY = d3.format('.02f'); function toDate(e) { return new Date(e); } var sortByDateDesc = function(a, b) { return toDate(xValue(a)) > toDate(xValue(b)) ? 1 : -1; }; var dispatch = d3.dispatch('showTooltip', 'hideTooltip', 'pointMouseover', 'pointMouseout'); function chart(selection) { selection.each(function(rawData) { var containerID = this; // preserve rawData variable (needed to control updates of legend module) var data = rawData.filter(function(d) { return !d.disabled; }); //sort the data points in each layer data.forEach(function(layer) { values(layer).sort(sortByDateDesc); }); // convert the data to an appropriate representation data = d3.layout.stack() .offset(offset) .order(order) .values(values) .x(xValue) .y(yValue) (data); // we pass the data as context var legendWidth = legend.width(); // we set the height of the legend as the same as // the chart legend.height(height); // set up scales and axes xScale.domain(data[0].values.map(function(d) { return xValue(d); })) .rangeRoundBands([0, width - (margin.right + legendWidth)], 0.1); // how many data points are there in each layer on average var avgDataPoints = function() { var sumPoints = 0; data.forEach(function(layer) { sumPoints += layer.values.length; }); // //console.log('THIS', sumPoints, data.length, sumPoints / data.length) return (sumPoints / data.length); }; xAxis.tickFormat(tickFormat) .tickValues(xScale.domain().filter(function(d, i) { var nthLabel = Math.ceil(200 / (width / avgDataPoints())); // //console.log(nthLabel) return i % nthLabel === 0; })); var yGroupMax = d3.max(data, function(layer) { return d3.max(layer.values, function(d) { return d.y; }); }); var yStackMax = d3.max(data, function(layer) { return d3.max(layer.values, function(d) { return d.y0 + d.y; }); }); var numLayers = data.length; yScale.range([height - margin.top - margin.bottom, 0]); if (mode === 'stacked') { yScale.domain([0, yStackMax]); } else { yScale.domain([0, yGroupMax]); } // functions for rect attributes depending on stacked/group mode var xScaleMode = function(d, i, j) { if (mode === 'stacked') { return xScale(xValue(d)); } else { return xScale(xValue(d)) + xScale.rangeBand() / numLayers * j; } }; var yScaleMode = function(d) { if (mode === 'stacked') { return yScale(d.y0 + d.y); } else { return yScale(d.y); } }; var heightMode = function(d) { if (mode === 'stacked') { return yScale(d.y0) - yScale(d.y0 + d.y); } else { return height - yScale(d.y) - margin.top - margin.bottom; } }; var widthMode = function() { if (mode === 'stacked') { return xScale.rangeBand(); } else { return xScale.rangeBand() / numLayers; } }; // set up the scaffolding // note: enter only fires if data is empty var svg = d3.select(containerID).selectAll('svg').data([data]); var gEnter = svg.enter().append('svg').attr('class', 'bridle').append('g'); gEnter.append('g').attr('class', 'rects'); gEnter.append('g').attr('class', 'x axis'); gEnter.append('g').attr('class', 'y axis').append('text') .attr('transform', 'rotate(-90)') .attr('y', 6) .attr('dy', '.72em') .attr('class', 'y axis label') .attr('text-anchor', 'middle'); gEnter.append('svg:text').attr('class', 'chartTitle label') .attr('text-anchor', 'middle') .attr('dy', '1em') .attr('transform', 'translate(' + (width - margin.left - margin.right + 20) / 2 + ',' + (-margin.top) + ')'); gEnter.append('g') .attr('class', 'legend') .attr('transform', 'translate(' + (width - (margin.right + legendWidth) + 20) + ',' + 0 + ')') .style('font-size', '12px'); // update the outer dimensions svg.attr('width', width) .attr('height', height); // update the inner dimensions var g = svg.select('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // reasign the data to trigger points // specify a key function based on *name*, // so that entering/exiting works properly when filters are triggered var gLayer = g.select('.rects').selectAll('g.layerrects') .data(function(d) { return d; }, function(d) { return nameValue(d); }) .classed('hover', function(d) { return d.hover; }); gLayer .exit() .transition() .duration(duration) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); var gLayerEnter = gLayer.enter(); // update entering rects var gRects = gLayerEnter.append('g').attr('class', 'layerrects') .attr('fill', function(d) { return colors(nameValue(d)); }) .selectAll('g.rect') .data(function(d) { d.values.forEach(function(v) { v.name = nameValue(d); }); return d.values; }); gRects.exit() .transition() .duration(duration) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); var rectsEnter = gRects.enter().append('g').attr('class', 'rect'); rectsEnter.append('rect') .attr('opacity', 0.1) .attr('x', function(d, i, j) { return xScaleMode(d, i, j); }) .attr('y', function() { return height - margin.top - margin.bottom; }) .attr('width', function() { return widthMode(); }) .attr('height', 0) .on('mouseover', function(d, i, j) { dispatch.pointMouseover({ x : xValue(d), y : yValue(d), series : d.name, pos : [xScale(xValue(d)), yScaleMode(d)], pointIndex : i, seriesIndex : j }); }) .on('mouseout', function() { dispatch.pointMouseout({ // point: d, // series: data[d.series], // pointIndex: d.point, // seriesIndex: d.series }); }); // update the chillin rects g.selectAll('g.layerrects').selectAll('g.rect') .select('rect') .transition() .duration(duration) .attr('opacity', 0.9) .attr('y', function(d) { return yScaleMode(d); }) .attr('height', function(d) { return heightMode(d); }) .attr('width', function() { return widthMode(); }) .attr('x', function(d, i, j) { return xScaleMode(d, i, j); }); // update the title g.select('text.chartTitle') .text(title); // update the x-axis g.select('.x.axis') .attr('transform', 'translate(0,' + yScale.range()[0] + ')') .call(xAxis); // update the y-axis g.select('.y.axis') //.attr('transform', 'translate(') .transition() .duration(duration) .attr('transform', 'translate(-25,0)') .call(yAxis); g.select('.y.axis.label') .attr('y', -45) .attr('x', (-height + margin.top + margin.bottom) / 2) .attr('dy', '.1em') .text(yAxisTitle); function change() { ////console.log('mode change') if (this.value === 'grouped') { mode = 'grouped'; yScale.domain([0, yGroupMax]); transitionGrouped(); } else { mode = 'stacked'; yScale.domain([0, yStackMax]); transitionStacked(); } } // handle change from/to stacked/grouped d3.selectAll('input.bridle.modeChanger').on('change', change); // transition to grouped layout function transitionGrouped() { // update the y-axis g.select('.y.axis') //.attr('transform', 'translate(') .transition() .duration(duration) .attr('transform', 'translate(-25,0)') .call(yAxis); g.selectAll('g.layerrects').selectAll('rect') .transition() .duration(500) .delay(function(d, i) { return i * 10; }) .attr('x', function(d, i, j) { // //console.log(d,i,j) return xScale(xValue(d)) + xScale.rangeBand() / numLayers * j; }) .attr('width', xScale.rangeBand() / numLayers) .transition() .attr('y', function(d) { return yScale(d.y); }) .attr('height', function(d) { return height - yScale(d.y) - margin.top - margin.bottom; }); } //transition to stacked layout function transitionStacked() { // update the y-axis g.select('.y.axis') //.attr('transform', 'translate(') .transition() .duration(duration) .attr('transform', 'translate(-25,0)') .call(yAxis); g.selectAll('g.layerrects').selectAll('rect') .transition() .duration(500) .delay(function(d, i) { return i * 10; }) .attr('y', function(d) { return yScale(d.y0 + d.y); }) .attr('height', function(d) { return yScale(d.y0) - yScale(d.y0 + d.y); }) .transition() .attr('x', function(d) { return xScale(xValue(d)); }) .attr('width', xScale.rangeBand()); } // update the legend only if the data has changed if (legend.numData() !== rawData.length) { // update the legend g.select('.legend') .datum(rawData) .call(legend); } // listen for click events from the legend module, // filter the relevant data series legend.dispatch.on('legendClick', function(d) { d.disabled = !d.disabled; // disallow deactivating last active legend item if (!data.some(function(d) { return !d.disabled; })) { d.disabled = false; } selection.call(chart); }); // listen for mouseover events from legend module // flag 'hover' on data series legend.dispatch.on('legendMouseover', function(d) { d.hover = true; selection.call(chart); }); // listen for mouseout events from legend module // remove 'hover' from data series legend.dispatch.on('legendMouseout', function(d) { d.hover = false; selection.call(chart); }); // listen for mouseover events within this module // (i.e. on rectangles) and show tooltip dispatch.on('pointMouseover.tooltip', function(e) { var offset = $(containerID).offset(), // { left: 0, top: 0 } left = e.pos[0] + offset.left + margin.left, top = e.pos[1] + offset.top + margin.top; var content = '<h3>' + e.series + '</h3>' + '<p>' + '<span class="value">[' + formatterX(e.x) + ', ' + formatterY(e.y) + ']</span>' + '</p>'; Bridle.tooltip.show([left, top], content); }); // listen for mouseout events within this module // hide tooltip dispatch.on('pointMouseout.tooltip', function() { Bridle.tooltip.cleanup(); }); }); } chart.dispatch = dispatch; chart.margin = function(_) { if (!arguments.length) { return margin; } margin = _; return chart; }; chart.width = function(_) { if (!arguments.length) { return width; } width = _; return chart; }; chart.height = function(_) { if (!arguments.length) { return height; } height = _; return chart; }; chart.title = function(_) { if (!arguments.length) { return title; } title = _; return chart; }; chart.xAxis = function(_) { if (!arguments.length) { return xAxis; } xAxis = _; return chart; }; chart.yAxis = function(_) { if (!arguments.length) { return yAxis; } yAxis = _; return chart; }; chart.yAxisTitle = function(_) { if (!arguments.length) { return yAxisTitle; } yAxisTitle = _; return chart; }; chart.duration = function(_) { if (!arguments.length) { return duration; } duration = _; return chart; }; chart.tickFormat = function(_) { if (!arguments.length) { return tickFormat; } tickFormat = _; return chart; }; chart.legend = function(_) { if (!arguments.length) { return legend; } legend = _; return chart; }; chart.xValue = function(_) { if (!arguments.length) { return xValue; } xValue = _; return chart; }; chart.yValue = function(_) { if (!arguments.length) { return yValue; } yValue = _; return chart; }; chart.nameValue = function(_) { if (!arguments.length) { return nameValue; } nameValue = _; return chart; }; chart.values = function(_) { if (!arguments.length) { return values; } values = _; return chart; }; chart.colors = function(_) { if (!arguments.length) { return colors; } colors = _; /* set the colors for the legend as well */ chart.legend().colors(colors); return chart; }; chart.mode = function(_) { if (!arguments.length) { return mode; } mode = _; return chart; }; chart.formatterX = function(_) { if (!arguments.length) { return formatterX; } formatterX = _; return chart; }; chart.formatterY = function(_) { if (!arguments.length) { return formatterY; } formatterY = _; return chart; }; return chart; };
pearson-enabling-technologies/bridle
src/barChart.js
JavaScript
apache-2.0
15,544
document.write('2018年1月');
kulend/Vino.Core.CMS
source/Ku.Core.CMS.Web.Backend/wwwroot/lib/data_location/version.js
JavaScript
apache-2.0
30
/** * @fileoverview Utility to detect and address folder and file sharing which is broader than intended * Removes overly broad permissions at folder level * Notifies specified email of breaches */ function main() { var user = Session.getActiveUser().getEmail(); var hostDomain = user.split('@')[1]; var permittedDomainArr = []; var folder = DriveApp.getFolderById(ROOT_FOLDER_ID); var notificationObj = {}; folderPermissions_(hostDomain, folder, permittedDomainArr, notificationObj); var rootFolderName = folder.getName(); notify(notificationObj, rootFolderName); } // recursive rename function folderPermissions_(hostDomain, folder, permittedDomainArr, notificationObj) { //Logger.log('permittedDomainArr '+JSON.stringify(permittedDomainArr)); //Logger.log('notificationObj '+JSON.stringify(notificationObj)); var file; var isFolder; try { // check whether down at shared folder level var folderId = folder.getId(); if (SHARED_FOLDER_OBJ[folderId]) { // add to list of permitted domains at this level permittedDomainArr.push(SHARED_FOLDER_OBJ[folderId]); } //validate folder permissions isFolder = true; var userArr = folder.getViewers(); // includes commenters validatePermissions_(hostDomain, isFolder, folder, 'VIEWER', userArr, permittedDomainArr, notificationObj); var userArr = folder.getEditors(); validatePermissions_(hostDomain, isFolder, folder, 'EDITOR', userArr, permittedDomainArr, notificationObj); //validate file permissions isFolder = false; var files = folder.getFiles(); while (files.hasNext()) { file = files.next(); if (!file.isTrashed()) { var userArr = file.getViewers(); // includes commenters validatePermissions_(hostDomain, isFolder, file, 'VIEWER', userArr, permittedDomainArr, notificationObj); var userArr = file.getEditors(); validatePermissions_(hostDomain, isFolder, file, 'EDITOR', userArr, permittedDomainArr, notificationObj); } } //do the same for nested folders var folders = folder.getFolders(); while (folders.hasNext()) { folder = folders.next(); var branchPermittedDomainArr = (permittedDomainArr.length > 0) ? permittedDomainArr: []; // need one per branch or permissions are accumulated across folders as well as down folderPermissions_(hostDomain, folder, permittedDomainArr, notificationObj); } } catch (error) { Logger.log(error); } } function validatePermissions_(hostDomain, isFolder, fileOrFolder, permissionType, userArr, permittedDomainArr, notificationObj) { var permissionsArr = []; var userArrLen = userArr.length; var userDomain; for (var i=userArrLen; i--;) { userDomain = userArr[i].getDomain(); if (userDomain != hostDomain && permittedDomainArr.indexOf(userDomain) == -1) { fixPermissions_(isFolder, fileOrFolder, permissionType, userArr[i], permittedDomainArr, notificationObj); } } } function fixPermissions_(isFolder, fileOrFolder, permissionType, user, permittedDomainArr, notificationObj) { var result = ''; if ((isFolder && REMOVE_FOLDER_PERMISSIONS) || (!isFolder && REMOVE_FILE_PERMISSIONS)) { // may not want to remove individual file shares if (permissionType == 'VIEWER') { try { fileOrFolder.removeViewer(user); // includes commenter result = 'SUCCESS'; } catch (error){ result = 'FAILURE'; } } else { try { fileOrFolder.removeEditor(user); // includes commenter result = 'SUCCESS'; } catch (error){ result = 'FAILURE'; } } } if (isFolder || NOTIFY_FILE_ISSUES) { addNotification_(isFolder, fileOrFolder, user, permissionType, permittedDomainArr, notificationObj, result); } } function addNotification_(isFolder, fileOrFolder, user, permissionType, permittedDomainArr, notificationObj, result) { var id; var name; var url; var email; try { id = fileOrFolder.getId(); name = fileOrFolder.getName(); url = fileOrFolder.getUrl(); email = user.getEmail(); } catch (error){ } var assetType = isFolder ? 'Folder' : 'File'; var permittedDomains = ''; var permittedDomainArrLen = permittedDomainArr.length; for (var i=0;i<permittedDomainArrLen;i++) { if (permittedDomains) { permittedDomains = permittedDomains + ', '; } permittedDomains = permittedDomains + permittedDomainArr[i]; } if (!notificationObj[id]) { notificationObj[id] = {assetType: assetType, fileOrFolder: fileOrFolder, name: name, url: url, permittedDomains: permittedDomains, emailArr: [email], permissionTypeArr: [permissionType], resultArr: [result]}; } else { notificationObj[id].emailArr.push(email); notificationObj[id].permissionTypeArr.push(permissionType); notificationObj[id].resultArr.push(result); } }
demoforwork/public
DrivePermissionsScrubber/Scrub.js
JavaScript
apache-2.0
4,949
import Ember from 'ember'; export default Ember.Route.extend({ k8s: Ember.inject.service(), model(params) { return this.get('k8s').getService(params.name); } });
nrvale0/ui
app/k8s-tab/namespace/services/service/route.js
JavaScript
apache-2.0
174
angular.module('elementBoxApp.products.productInfo') .controller('ProductInfoCtrl', [ '$scope', '$rootScope', '$state', '$stateParams', '$timeout', 'ModalAlert', 'ProductsService', 'UserService', 'CommentsService', 'EVENT_NAMES', function($scope, $rootScope, $state, $stateParams, $timeout, ModalAlert, ProductsService, UserService, CommentsService, EVENT_NAMES) { $scope.slides = []; $scope.slidesIndex = 0; $scope.userHasRated = false; $scope.rateVal = null; $scope.newComment = ''; $scope.commentSent = false; var ratingInProcess = false; $rootScope.$emit('title', 'TITLE_MY_PRODUCT_INFO'); // Comments pagination: $scope.comments = []; $scope.commentsData = { page: 1, pageSize: 3, totalPages: 0, totalComments: 0 }; var onNeedToLogin = function() { ModalAlert.alert({ title: 'PRODUCTS.PLEASE_SIGNIN', msg: 'PRODUCTS.PLEASE_SIGNIN_TO_ACCESS' }); }; // $scope.myInterval = 5000; // $scope.slides2 = []; // Fetching product: $scope.product = ProductsService.get({ id: $stateParams.productId }, function(p) { // success cbk. p.images = p.images ? p.images : []; p.images.forEach(function(image, index) { $scope.slides.push({ url: image.url, index: index+1 }); }); // p.rating.value = parseInt(p.rating.value); }, function(err) { // error cbk. $state.go('main.products.info-404'); }); $scope.fetchPage = function() { CommentsService.query({ prodId: $stateParams.productId, page: $scope.commentsData.page, pageSize: $scope.commentsData.pageSize }) .$promise.then(function(res) { $scope.comments = res.results; $scope.commentsData.page = res.page; $scope.commentsData.totalPages = res.totalPages; $scope.commentsData.totalComments = res.total; $scope.commentsData.pageSize = res.pageSize; }); }; $scope.addComment = function(commentTxt) { if (!commentTxt || !commentTxt.trim()) { return; } if (!$scope.currentUser || !$scope.currentUser.id) { onNeedToLogin(); return; } var newComment = { prodId: $stateParams.productId, text: commentTxt }; CommentsService.save(newComment, function(data) { $scope.fetchPage(); $rootScope.$emit(EVENT_NAMES.addComment, newComment); $scope.newComment = ''; $scope.commentSent = true; }); }; $scope.$watch('commentsData.page', function(newVal, oldVal) { $scope.fetchPage(); }); $scope.rate = function(val) { if ($scope.rateVal || ratingInProcess) { return; } if (!$scope.currentUser || !$scope.currentUser.id) { onNeedToLogin(); return; } ratingInProcess = true; ProductsService.rate({_id: $scope.product._id, rating: val}, function() { // success cbk. $scope.userHasRated = true; $scope.rateVal = val; ratingInProcess = false; }, function() { // err cbk. ratingInProcess = false; }); }; $scope.addToWishList = function() { if (!$scope.currentUser || !$scope.currentUser.id) { return onNeedToLogin(); } UserService.addToWishList({ prodId: $scope.product._id }, function() { $rootScope.$emit(EVENT_NAMES.addWishList, $scope.product); }); }; $scope.removeFromWishList = function() { UserService.removeFromWishList({ itemId: $scope.product._id }, function() { $rootScope.$emit(EVENT_NAMES.removeWishList, $scope.product); }); }; $scope.hasWishListedProduct = function() { if (!$scope.currentUser || !$scope.product) { return false; } if (!$scope.currentUser.wishList) { $scope.currentUser.wishList = []; } return $scope.currentUser.wishList.indexOf($scope.product._id) >= 0; }; // $scope.fetchPage(); // fetching first page. } ]);
mauroBus/element
client/src/app/products/product-info/product-info.controller.js
JavaScript
apache-2.0
4,089
var dir_40645110f4b881381ac11b52da3dfc1e = [ [ "provider", "dir_9a95dbcede8719bb251f64fc00e6b0a1.html", "dir_9a95dbcede8719bb251f64fc00e6b0a1" ] ];
onosfw/apis
onos/apis/dir_40645110f4b881381ac11b52da3dfc1e.js
JavaScript
apache-2.0
151
// @flow import Spinner from '@atlaskit/spinner'; import React from 'react'; import { translate } from '../../base/i18n'; import { AbstractPage } from '../../base/react'; import { connect } from '../../base/redux'; import { openSettingsDialog, SETTINGS_TABS } from '../../settings'; import { createCalendarClickedEvent, sendAnalytics } from '../../analytics'; import { refreshCalendar } from '../actions'; import { ERRORS } from '../constants'; import CalendarListContent from './CalendarListContent'; declare var interfaceConfig: Object; /** * The type of the React {@code Component} props of {@link CalendarList}. */ type Props = { /** * The error object containing details about any error that has occurred * while interacting with calendar integration. */ _calendarError: ?Object, /** * Whether or not a calendar may be connected for fetching calendar events. */ _hasIntegrationSelected: boolean, /** * Whether or not events have been fetched from a calendar. */ _hasLoadedEvents: boolean, /** * Indicates if the list is disabled or not. */ disabled: boolean, /** * The Redux dispatch function. */ dispatch: Function, /** * The translate function. */ t: Function }; /** * Component to display a list of events from the user's calendar. */ class CalendarList extends AbstractPage<Props> { /** * Initializes a new {@code CalendarList} instance. * * @inheritdoc */ constructor(props) { super(props); // Bind event handlers so they are only bound once per instance. this._getRenderListEmptyComponent = this._getRenderListEmptyComponent.bind(this); this._onOpenSettings = this._onOpenSettings.bind(this); this._onRefreshEvents = this._onRefreshEvents.bind(this); } /** * Implements React's {@link Component#render}. * * @inheritdoc */ render() { const { disabled } = this.props; return ( CalendarListContent ? <CalendarListContent disabled = { disabled } listEmptyComponent = { this._getRenderListEmptyComponent() } /> : null ); } /** * Returns a component for showing the error message related to calendar * sync. * * @private * @returns {React$Component} */ _getErrorMessage() { const { _calendarError = {}, t } = this.props; let errorMessageKey = 'calendarSync.error.generic'; let showRefreshButton = true; let showSettingsButton = true; if (_calendarError.error === ERRORS.GOOGLE_APP_MISCONFIGURED) { errorMessageKey = 'calendarSync.error.appConfiguration'; showRefreshButton = false; showSettingsButton = false; } else if (_calendarError.error === ERRORS.AUTH_FAILED) { errorMessageKey = 'calendarSync.error.notSignedIn'; showRefreshButton = false; } return ( <div className = 'meetings-list-empty'> <p className = 'description'> { t(errorMessageKey) } </p> <div className = 'calendar-action-buttons'> { showSettingsButton && <div className = 'button' onClick = { this._onOpenSettings }> { t('calendarSync.permissionButton') } </div> } { showRefreshButton && <div className = 'button' onClick = { this._onRefreshEvents }> { t('calendarSync.refresh') } </div> } </div> </div> ); } _getRenderListEmptyComponent: () => Object; /** * Returns a list empty component if a custom one has to be rendered instead * of the default one in the {@link NavigateSectionList}. * * @private * @returns {React$Component} */ _getRenderListEmptyComponent() { const { _calendarError, _hasIntegrationSelected, _hasLoadedEvents, t } = this.props; if (_calendarError) { return this._getErrorMessage(); } else if (_hasIntegrationSelected && _hasLoadedEvents) { return ( <div className = 'meetings-list-empty'> <p className = 'description'> { t('calendarSync.noEvents') } </p> <div className = 'button' onClick = { this._onRefreshEvents }> { t('calendarSync.refresh') } </div> </div> ); } else if (_hasIntegrationSelected && !_hasLoadedEvents) { return ( <div className = 'meetings-list-empty'> <Spinner invertColor = { true } isCompleting = { false } size = 'medium' /> </div> ); } return ( <div className = 'meetings-list-empty'> <p className = 'description'> { t('welcomepage.connectCalendarText', { app: interfaceConfig.APP_NAME, provider: interfaceConfig.PROVIDER_NAME }) } </p> <div className = 'button' onClick = { this._onOpenSettings }> { t('welcomepage.connectCalendarButton') } </div> </div> ); } _onOpenSettings: () => void; /** * Opens {@code SettingsDialog}. * * @private * @returns {void} */ _onOpenSettings() { sendAnalytics(createCalendarClickedEvent('calendar.connect')); this.props.dispatch(openSettingsDialog(SETTINGS_TABS.CALENDAR)); } _onRefreshEvents: () => void; /** * Gets an updated list of calendar events. * * @private * @returns {void} */ _onRefreshEvents() { this.props.dispatch(refreshCalendar(true)); } } /** * Maps (parts of) the Redux state to the associated props for the * {@code CalendarList} component. * * @param {Object} state - The Redux state. * @private * @returns {{ * _calendarError: Object, * _hasIntegrationSelected: boolean, * _hasLoadedEvents: boolean * }} */ function _mapStateToProps(state) { const { error, events, integrationType, isLoadingEvents } = state['features/calendar-sync']; return { _calendarError: error, _hasIntegrationSelected: Boolean(integrationType), _hasLoadedEvents: Boolean(events) || !isLoadingEvents }; } export default translate(connect(_mapStateToProps)(CalendarList));
bgrozev/jitsi-meet
react/features/calendar-sync/components/CalendarList.web.js
JavaScript
apache-2.0
7,243
'use strict'; const _ = require('lodash'); const serviceUtils = require('../serviceUtils'); /** * @summary Retrieve a Coding System object. * @param {String} source Abbreviation of the source coding system under test. * @param {Function} callback Function called on process completion, with standard (err, result) signature. * @return {Object} Coding System object * 'sourceAbbreviation' {String} Abbreviated name of the coding system * 'nomenclature' {String} Longer description * 'implementationDate' {String} Implementation date in ISO format * * @memberof LexiconService * @instance */ function lookupCodingSystem(source, cb) { if (!source) { return cb(this.error('INVALID_CODING_SYSTEM_SOURCE_VALUE')); } const findObject = { query: { sourceAbbreviation: source }, projection: serviceUtils.createProjection(['sourceAbbreviation', 'implementationDate']), }; this.find('CodingSystems', findObject, (err, res) => { if (err) { return cb(err); } const codingSystem = _.first(res); const impDate = _.get(codingSystem, 'implementationDate'); if (_.isDate(impDate)) { _.set(codingSystem, 'implementationDate', impDate.toISOString()); } cb(null, codingSystem); }); } module.exports = { lookupCodingSystem, };
vistadataproject/metaPureJS
services/lexiconService/lookupCodingSystem.js
JavaScript
apache-2.0
1,445
'use strict'; concertoPanel.service('TestWizardParam', ["$filter", function ($filter) { this.getTypeName = function (type) { switch (parseInt(type)) { case 0: return Trans.TEST_WIZARD_PARAM_TYPE_SINGLE_LINE_TEXT; case 1: return Trans.TEST_WIZARD_PARAM_TYPE_MULTI_LINE_TEXT; case 2: return Trans.TEST_WIZARD_PARAM_TYPE_HTML; case 3: return Trans.TEST_WIZARD_PARAM_TYPE_SELECT; case 4: return Trans.TEST_WIZARD_PARAM_TYPE_CHECKBOX; case 5: return Trans.TEST_WIZARD_PARAM_TYPE_VIEW; case 6: return Trans.TEST_WIZARD_PARAM_TYPE_TABLE; case 7: return Trans.TEST_WIZARD_PARAM_TYPE_COLUMN; case 8: return Trans.TEST_WIZARD_PARAM_TYPE_TEST; case 9: return Trans.TEST_WIZARD_PARAM_TYPE_GROUP; case 10: return Trans.TEST_WIZARD_PARAM_TYPE_LIST; case 11: return Trans.TEST_WIZARD_PARAM_TYPE_R; case 12: return Trans.TEST_WIZARD_PARAM_TYPE_COLUMN_MAP; case 13: return Trans.TEST_WIZARD_PARAM_TYPE_WIZARD; } return type; }; this.getDefinerTitle = function (param) { if (!param) return ""; var info = param.label ? param.label : this.getTypeName(param.type); switch (parseInt(param.type)) { case 0: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_SINGLE_LINE.pf(info); case 1: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_MULTI_LINE.pf(info); case 2: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_HTML.pf(info); case 3: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_SELECT.pf(info); case 4: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_CHECKBOX.pf(info); case 5: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_TEMPLATE.pf(info); case 6: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_TABLE.pf(info); case 8: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_TEST.pf(info); case 9: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_GROUP.pf(info); case 10: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_LIST.pf(info); case 11: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_R_CODE.pf(info); case 12: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_COLUMN_MAP.pf(info); case 13: return Trans.TEST_WIZARD_PARAM_DEFINER_TITLES_WIZARD.pf(info); } return ""; }; this.getSetterTitle = function (param) { if (!param) return ""; switch (parseInt(param.type)) { case 1: return Trans.TEST_WIZARD_PARAM_SETTER_TITLES_TEXTAREA.pf(param.label); case 2: return Trans.TEST_WIZARD_PARAM_SETTER_TITLES_HTML.pf(param.label); case 7: return Trans.TEST_WIZARD_PARAM_SETTER_TITLES_COLUMN.pf(param.label); case 9: return Trans.TEST_WIZARD_PARAM_SETTER_TITLES_GROUP.pf(param.label); case 10: return Trans.TEST_WIZARD_PARAM_SETTER_TITLES_LIST.pf(param.label); case 11: return Trans.TEST_WIZARD_PARAM_SETTER_TITLES_R.pf(param.label); case 12: return Trans.TEST_WIZARD_PARAM_SETTER_TITLES_COLUMN_MAP.pf(param.label); case 13: return Trans.TEST_WIZARD_PARAM_SETTER_TITLES_WIZARD.pf(param.label); } return ""; }; this.getDefinerSummary = function (param) { if (!param) return ""; switch (parseInt(param.type)) { case 3: if (param.definition == undefined || !param.definition.options) return ""; var info = param.definition.options.length + " - ["; for (var i = 0; i < param.definition.options.length; i++) { if (i > 0) info += ","; info += param.definition.options[i].label; } info += "]"; return Trans.TEST_WIZARD_PARAM_DEFINER_SUMMARIES_SELECT.pf(info); case 9: if (param.definition == undefined || !param.definition.fields) return ""; var info = param.definition.fields.length + " - ["; for (var i = 0; i < param.definition.fields.length; i++) { if (i > 0) info += ","; info += param.definition.fields[i].name; } info += "]"; return Trans.TEST_WIZARD_PARAM_DEFINER_SUMMARIES_GROUP.pf(info); case 10: if (param.definition == undefined || param.definition.element == undefined) return ""; var info = this.getTypeName(param.definition.element.type); return Trans.TEST_WIZARD_PARAM_DEFINER_SUMMARIES_LIST.pf(info); case 12: if (param.definition == undefined || !param.definition.cols) return ""; var info = param.definition.cols.length + " - ["; for (var i = 0; i < param.definition.cols.length; i++) { if (i > 0) info += ","; info += param.definition.cols[i].name; } info += "]"; return Trans.TEST_WIZARD_PARAM_DEFINER_SUMMARIES_COLUMN_MAP.pf(info); } return ""; }; this.getSetterSummary = function (param, output) { if (!param || !output) return ""; switch (parseInt(param.type)) { case 1: var summary = output; if (summary.length > 100) { summary = summary.substring(0, 97) + "..."; } return Trans.TEST_WIZARD_PARAM_SETTER_SUMMARIES_TEXTAREA.pf(summary); case 2: var summary = output; if (summary.length > 100) { summary = summary.substring(0, 97) + "..."; } return Trans.TEST_WIZARD_PARAM_SETTER_SUMMARIES_HTML.pf(summary); case 7: return Trans.TEST_WIZARD_PARAM_SETTER_SUMMARIES_COLUMN.pf(output.table, output.column); case 9: return Trans.TEST_WIZARD_PARAM_SETTER_SUMMARIES_GROUP.pf(this.getDefinerSummary(param)); case 10: return Trans.TEST_WIZARD_PARAM_SETTER_SUMMARIES_LIST.pf(output.length); case 11: var summary = output; if (summary.length > 100) { summary = summary.substring(0, 97) + "..."; } return Trans.TEST_WIZARD_PARAM_SETTER_SUMMARIES_R.pf(summary); case 12: if (!param.definition.cols) return ""; var info = param.definition.cols.length + " - ["; for (var i = 0; i < param.definition.cols.length; i++) { if (i > 0) info += ","; var dst = "?"; if (output.columns != null && output.columns != undefined) { var map = output.columns[param.definition.cols[i].name]; if (map !== null && map != undefined) dst = map; } info += param.definition.cols[i].name + "->" + dst; } info += "]"; return Trans.TEST_WIZARD_PARAM_SETTER_SUMMARIES_COLUMN_MAP.pf(info); } return ""; }; this.wizardParamsToTestVariables = function (test, steps, vars) { for (var j = 0; j < steps.length; j++) { for (var k = 0; k < steps[j].params.length; k++) { var param = steps[j].params[k]; this.serializeParamValue(param); var found = false; for (var i = 0; i < vars.length; i++) { var variable = vars[i]; if (param.name === variable.name) { variable.value = param.value; found = true; break; } } if (!found) { vars.push({ id: 0, name: param.name, test: test.id, type: 0, description: param.description, value: param.value, passableThroughUrl: param.passableThroughUrl, parentVariable: param.testVariable }); } } } }; this.testVariablesToWizardParams = function (vars, steps) { for (var i = 0; i < vars.length; i++) { var variable = vars[i]; for (var j = 0; j < steps.length; j++) { for (var k = 0; k < steps[j].params.length; k++) { var param = steps[j].params[k]; if (variable.name === param.name && variable.type == 0) { param.value = variable.value; param.exposed = variable.exposed; this.unserializeParamValue(param); break; } } } } }; this.serializeParamValue = function (param) { try { if (param.type == 7 || param.type == 9 || param.type == 10 || param.type == 12 || param.type == 13) { this.deobjectifyListElements(param, param.output); param.value = angular.toJson(param.output); } else param.value = param.output; if (param.value === null) { throw "null param value (" + param.label + ")"; } } catch (err) { switch (parseInt(param.type)) { case 4: param.value = "0"; break; case 7: case 9: case 12: case 13: param.value = "{}"; break; case 10: param.value = "[]"; break; default: param.value = ""; break; } } }; this.unserializeParamValue = function (param) { var setDefault = false; if (param.value === null) { setDefault = true; } else { try { if (!this.isSimpleType(param.type)) { param.output = angular.fromJson(param.value); this.objectifyListElements(param, param.output); } else { param.output = param.value; } if (!this.validateUnserializedParamOutput(param.output, param.type)) { throw "invalid unserialized param value (" + param.label + ")"; } } catch (err) { setDefault = true; } } if (setDefault) param.output = this.getParamOutputDefault(param); }; this.getParamOutputDefault = function (param) { let result = null; switch (parseInt(param.type)) { case 0: //single line case 1: //multi line case 2: //HTML case 3: //select case 5: //view template case 6: //data table case 8: //test case 11: //R result = param.definition.defvalue; if (!this.validateUnserializedParamOutput(result, param.type)) result = ""; break; case 4: //checkbox result = param.definition.defvalue; if (!this.validateUnserializedParamOutput(result, param.type)) result = "0"; break; case 7: //data table column case 12: //column map case 13: //test wizard result = {}; break; case 9: //group result = {}; for (let i = 0; i < param.definition.fields.length; i++) { let field = param.definition.fields[i]; result[field.name] = this.getParamOutputDefault(field); } break; case 10: //list result = []; break; } return result; }; this.validateUnserializedParamOutput = function (output, type) { if (output === null || output === undefined) return false; switch (parseInt(type)) { case 0: //single line case 1: //multi line case 2: //HTML case 3: //select case 4: //checkbox case 5: //view template case 6: //data table case 8: //test case 11: //R if (typeof output === 'object') return false; break; case 7: //data table column case 9: //group case 12: //column map case 13: //test wizard if (typeof output !== 'object' || output.constructor === Array) return false; break; case 10: //list if (typeof output !== 'object' || output.constructor !== Array) return false; break; } return true; }; this.isParamVisible = function (param, parent, grandParent, values) { try { if (!param.hideCondition || param.hideCondition === undefined) { return true; } var res = eval(param.hideCondition); if (res === true) { return false; } } catch (err) { } return true; }; this.objectifyListElements = function (param, output) { switch (parseInt(param.type)) { case 9: { for (let i = 0; i < param.definition.fields.length; i++) { let field = param.definition.fields[i]; this.objectifyListElements(field, output[field.name]); } break; } case 10: { if (this.isSimpleType(param.definition.element.type)) { for (let i = 0; i < output.length; i++) { if (typeof output[i] !== 'object') output[i] = {value: output[i]}; } } break; } } }; this.deobjectifyListElements = function (param, output) { switch (parseInt(param.type)) { case 9: { for (let i = 0; i < param.definition.fields.length; i++) { let field = param.definition.fields[i]; this.deobjectifyListElements(field, output[field.name]); } break; } case 10: { if (this.isSimpleType(param.definition.element.type)) { for (let i = 0; i < output.length; i++) { output[i] = output[i].value; } } break; } } }; this.isSimpleType = function (type) { let validSimpleTypes = [0, 1, 2, 3, 4, 5, 6, 8, 11]; return validSimpleTypes.indexOf(parseInt(type)) !== -1; } } ]);
campsych/concerto-platform
src/Concerto/PanelBundle/Resources/public/angularjs/app/concerto_panel/js/services/test_wizard_param_service.js
JavaScript
apache-2.0
17,666
/* * forms.js: highlight form-related elements */ function initForms () { addPolyfills(); let targetList = [ {selector: "button", color: "purple", label: "button"}, {selector: "input", color: "navy", label: "input"}, {selector: "keygen", color: "gray", label: "keygen"}, {selector: "meter", color: "maroon", label: "meter"}, {selector: "output", color: "teal", label: "output"}, {selector: "progress", color: "olive", label: "progress"}, {selector: "select", color: "green", label: "select"}, {selector: "textarea", color: "brown", label: "textarea"} ]; let selectors = targetList.map(function (tgt) {return '<li>' + tgt.selector + '</li>';}).join(''); function getInfo (element, target) { return new InfoObject(element, 'FORM INFO'); } let params = { appName: "Forms", cssClass: getCssClass("Forms"), msgText: "No form-related elements found: <ul>" + selectors + "</ul>", targetList: targetList, getInfo: getInfo, dndFlag: true }; return new Bookmarklet(params); } /* * headings.js: highlight heading elements */ function initHeadings () { addPolyfills(); let targetList = [ {selector: "h1", color: "navy", label: "h1"}, {selector: "h2", color: "olive", label: "h2"}, {selector: "h3", color: "purple", label: "h3"}, {selector: "h4", color: "green", label: "h4"}, {selector: "h5", color: "gray", label: "h5"}, {selector: "h6", color: "brown", label: "h6"} ]; let selectors = targetList.map(function (tgt) {return tgt.selector;}).join(', '); function getInfo (element, target) { let info = new InfoObject(element, 'HEADING INFO'); info.addProps('level ' + target.label.substring(1)); return info; } let params = { appName: "Headings", cssClass: getCssClass("Headings"), msgText: "No heading elements (" + selectors + ") found.", targetList: targetList, getInfo: getInfo, dndFlag: true }; return new Bookmarklet(params); } /* * images.js: highlight image elements */ function initImages () { addPolyfills(); let targetList = [ {selector: "area", color: "teal", label: "area"}, {selector: "img", color: "olive", label: "img"}, {selector: "svg", color: "purple", label: "svg"} ]; let selectors = targetList.map(function (tgt) {return tgt.selector;}).join(', '); function getInfo (element, target) { return new InfoObject(element, 'IMAGE INFO'); } let params = { appName: "Images", cssClass: getCssClass("Images"), msgText: "No image elements (" + selectors + ") found.", targetList: targetList, getInfo: getInfo, dndFlag: true }; return new Bookmarklet(params); } /* * landmarks.js: highlight ARIA landmarks */ function initLandmarks () { addPolyfills(); // Filter function called on a list of elements returned by selector // 'footer, [role="contentinfo"]'. It returns true for the following // conditions: (1) element IS NOT a footer element; (2) element IS a // footer element AND IS NOT a descendant of article or section. function isContentinfo (element) { if (element.tagName.toLowerCase() !== 'footer') return true; if (!isDescendantOf(element, ['article', 'section'])) return true; return false; } // Filter function called on a list of elements returned by selector // 'header, [role="banner"]'. It returns true for the following // conditions: (1) element IS NOT a header element; (2) element IS a // header element AND IS NOT a descendant of article or section. function isBanner (element) { if (element.tagName.toLowerCase() !== 'header') return true; if (!isDescendantOf(element, ['article', 'section'])) return true; return false; } let targetList = [ {selector: 'aside:not([role]), [role~="complementary"], [role~="COMPLEMENTARY"]', color: "maroon", label: "complementary"}, {selector: 'footer, [role~="contentinfo"], [role~="CONTENTINFO"]', filter: isContentinfo, color: "olive", label: "contentinfo"}, {selector: '[role~="application"], [role~="APPLICATION"]', color: "black", label: "application"}, {selector: 'nav, [role~="navigation"], [role~="NAVIGATION"]', color: "green", label: "navigation"}, {selector: '[role~="region"][aria-labelledby], [role~="REGION"][aria-labelledby]', color: "teal", label: "region"}, {selector: '[role~="region"][aria-label], [role~="REGION"][aria-label]', color: "teal", label: "region"}, {selector: 'section[aria-labelledby], section[aria-label]', color: "teal", label: "region"}, {selector: 'header, [role~="banner"], [role~="BANNER"]', filter: isBanner, color: "gray", label: "banner"}, {selector: '[role~="search"], [role~="SEARCH"]', color: "purple", label: "search"}, {selector: 'main, [role~="main"], [role~="MAIN"]', color: "navy", label: "main"} ]; let selectors = targetList.map(function (tgt) {return '<li>' + tgt.selector + '</li>';}).join(''); function getInfo (element, target) { return new InfoObject(element, 'LANDMARK INFO'); } let params = { appName: "Landmarks", cssClass: getCssClass("Landmarks"), msgText: "No elements with ARIA Landmark roles found: <ul>" + selectors + "</ul>", targetList: targetList, getInfo: getInfo, dndFlag: true }; return new Bookmarklet(params); } /* * lists.js: highlight list elements */ function initLists () { addPolyfills(); let targetList = [ {selector: "dl", color: "olive", label: "dl"}, {selector: "ol", color: "purple", label: "ol"}, {selector: "ul", color: "navy", label: "ul"} ]; let selectors = targetList.map(function (tgt) {return tgt.selector;}).join(', '); function getInfo (element, target) { let listCount; switch (target.label) { case 'dl': listCount = countChildrenWithTagNames(element, ['DT', 'DD']); break; case 'ol': case 'ul': listCount = countChildrenWithTagNames(element, ['LI']); break; } let info = new InfoObject(element, 'LIST INFO'); info.addProps(listCount + ' items'); return info; } let params = { appName: "Lists", cssClass: getCssClass("Lists"), msgText: "No list elements (" + selectors + ") found.", targetList: targetList, getInfo: getInfo, dndFlag: true }; return new Bookmarklet(params); } /* * Bookmarklet.js */ /* eslint no-console: 0 */ function logVersionInfo (appName) { console.log(getTitle() + ' : v' + getVersion() + ' : ' + appName); } function Bookmarklet (params) { let globalName = getGlobalName(params.appName); // use singleton pattern if (typeof window[globalName] === 'object') return window[globalName]; this.appName = params.appName; this.cssClass = params.cssClass; this.msgText = params.msgText; this.params = params; this.show = false; let dialog = new MessageDialog(); window.addEventListener('resize', event => { removeNodes(this.cssClass); dialog.resize(); this.show = false; }); window[globalName] = this; logVersionInfo(this.appName); } Bookmarklet.prototype.run = function () { let dialog = new MessageDialog(); dialog.hide(); this.show = !this.show; if (this.show) { if (addNodes(this.params) === 0) { dialog.show(this.appName, this.msgText); this.show = false; } } else { removeNodes(this.cssClass); } }; /* * InfoObject.js */ /* * nameIncludesDescription: Determine whether accName object's name * property includes the accDesc object's name property content. */ function nameIncludesDescription (accName, accDesc) { if (accName === null || accDesc === null) return false; let name = accName.name, desc = accDesc.name; if (typeof name === 'string' && typeof desc === 'string') { return name.toLowerCase().includes(desc.toLowerCase()); } return false; } function InfoObject (element, title) { this.title = title; this.element = getElementInfo(element); this.grpLabels = getGroupingLabels(element); this.accName = getAccessibleName(element); this.accDesc = getAccessibleDesc(element); this.role = getAriaRole(element); // Ensure that accessible description is not a duplication // of accessible name content. If it is, nullify the desc. if (nameIncludesDescription (this.accName, this.accDesc)) { this.accDesc = null; } } InfoObject.prototype.addProps = function (val) { this.props = val; } /* * constants.js */ var CONSTANTS = {}; Object.defineProperty(CONSTANTS, 'classPrefix', { value: 'a11yGfdXALm' }); Object.defineProperty(CONSTANTS, 'globalPrefix', { value: 'a11y' }); Object.defineProperty(CONSTANTS, 'title', { value: 'oaa-tools/bookmarklets' }); Object.defineProperty(CONSTANTS, 'version', { value: '0.2.2' }); function getCssClass (appName) { const prefix = CONSTANTS.classPrefix; switch (appName) { case 'Forms': return prefix + '0'; case 'Headings': return prefix + '1'; case 'Images': return prefix + '2'; case 'Landmarks': return prefix + '3'; case 'Lists': return prefix + '4'; case 'Interactive': return prefix + '5'; } return 'unrecognizedName'; } function getGlobalName (appName) { return CONSTANTS.globalPrefix + appName; } function getTitle () { return CONSTANTS.title } function getVersion () { return CONSTANTS.version } /* * dialog.js: functions for creating, modifying and deleting message dialog */ /* * setBoxGeometry: Set the width and position of message dialog based on * the width of the browser window. Called by functions resizeMessage and * createMsgOverlay. */ function setBoxGeometry (dialog) { let width = window.innerWidth / 3.2; let left = window.innerWidth / 2 - width / 2; let scroll = getScrollOffsets(); dialog.style.width = width + "px"; dialog.style.left = (scroll.x + left) + "px"; dialog.style.top = (scroll.y + 30) + "px"; } /* * createMsgDialog: Construct and position the message dialog whose * purpose is to alert the user when no target elements are found by * a bookmarklet. */ function createMsgDialog (cssClass, handler) { let dialog = document.createElement("div"); let button = document.createElement("button"); dialog.className = cssClass; setBoxGeometry(dialog); button.onclick = handler; dialog.appendChild(button); document.body.appendChild(dialog); return dialog; } /* * deleteMsgDialog: Use reference to delete message dialog. */ function deleteMsgDialog (dialog) { if (dialog) document.body.removeChild(dialog); } /* * MessageDialog: Wrapper for show, hide and resize methods */ function MessageDialog () { this.GLOBAL_NAME = 'a11yMessageDialog'; this.CSS_CLASS = 'oaa-message-dialog'; } /* * show: show message dialog */ MessageDialog.prototype.show = function (title, message) { const MSG_DIALOG = this.GLOBAL_NAME; let h2, div; if (!window[MSG_DIALOG]) window[MSG_DIALOG] = createMsgDialog(this.CSS_CLASS, event => this.hide()); h2 = document.createElement("h2"); h2.innerHTML = title; window[MSG_DIALOG].appendChild(h2); div = document.createElement("div"); div.innerHTML = message; window[MSG_DIALOG].appendChild(div); }; /* * hide: hide message dialog */ MessageDialog.prototype.hide = function () { const MSG_DIALOG = this.GLOBAL_NAME; if (window[MSG_DIALOG]) { deleteMsgDialog(window[MSG_DIALOG]); delete(window[MSG_DIALOG]); } }; /* * resize: resize message dialog */ MessageDialog.prototype.resize = function () { const MSG_DIALOG = this.GLOBAL_NAME; if (window[MSG_DIALOG]) setBoxGeometry(window[MSG_DIALOG]); }; /* * dom.js: functions and constants for adding and removing DOM overlay elements */ /* * isVisible: Recursively check element properties from getComputedStyle * until document element is reached, to determine whether element or any * of its ancestors has properties set that affect its visibility. Called * by addNodes function. */ function isVisible (element) { function isVisibleRec (el) { if (el.nodeType === Node.DOCUMENT_NODE) return true; let computedStyle = window.getComputedStyle(el, null); let display = computedStyle.getPropertyValue('display'); let visibility = computedStyle.getPropertyValue('visibility'); let hidden = el.getAttribute('hidden'); let ariaHidden = el.getAttribute('aria-hidden'); if ((display === 'none') || (visibility === 'hidden') || (hidden !== null) || (ariaHidden === 'true')) { return false; } return isVisibleRec(el.parentNode); } return isVisibleRec(element); } /* * countChildrenWithTagNames: For the specified DOM element, return the * number of its child elements with tagName equal to one of the values * in the tagNames array. */ function countChildrenWithTagNames (element, tagNames) { let count = 0; let child = element.firstElementChild; while (child) { if (tagNames.indexOf(child.tagName) > -1) count += 1; child = child.nextElementSibling; } return count; } /* * isDescendantOf: Determine whether element is a descendant of any * element in the DOM with a tagName in the list of tagNames. */ function isDescendantOf (element, tagNames) { if (typeof element.closest === 'function') { return tagNames.some(name => element.closest(name) !== null); } return false; } /* * hasParentWithName: Determine whether element has a parent with * tagName in the list of tagNames. */ function hasParentWithName (element, tagNames) { let parentTagName = element.parentElement.tagName.toLowerCase(); if (parentTagName) { return tagNames.some(name => parentTagName === name); } return false; } /* * addNodes: Use targetList to generate nodeList of elements and to * each of these, add an overlay with a unique CSS class name. * Optionally, if getInfo is specified, add tooltip information; * if dndFlag is set, add drag-and-drop functionality. */ function addNodes (params) { let targetList = params.targetList, cssClass = params.cssClass, getInfo = params.getInfo, evalInfo = params.evalInfo, dndFlag = params.dndFlag; let counter = 0; targetList.forEach(function (target) { // Collect elements based on selector defined for target let elements = document.querySelectorAll(target.selector); // Filter elements if target defines a filter function if (typeof target.filter === 'function') elements = Array.prototype.filter.call(elements, target.filter); Array.prototype.forEach.call(elements, function (element) { if (isVisible(element)) { let info = getInfo(element, target); if (evalInfo) evalInfo(info, target); let boundingRect = element.getBoundingClientRect(); let overlayNode = createOverlay(target, boundingRect, cssClass); if (dndFlag) addDragAndDrop(overlayNode); let labelNode = overlayNode.firstChild; labelNode.title = formatInfo(info); document.body.appendChild(overlayNode); counter += 1; } }); }); return counter; } /* * removeNodes: Use the unique CSS class name supplied to addNodes * to remove all instances of the overlay nodes. */ function removeNodes (cssClass) { let selector = "div." + cssClass; let elements = document.querySelectorAll(selector); Array.prototype.forEach.call(elements, function (element) { document.body.removeChild(element); }); } /* * embedded.js */ // LOW-LEVEL FUNCTIONS /* * getInputValue: Get current value of 'input' or 'textarea' element. */ function getInputValue (element) { return normalize(element.value); } /* * getRangeValue: Get current value of control with role 'spinbutton' * or 'slider' (i.e., subclass of abstract 'range' role). */ function getRangeValue (element) { let value; value = getAttributeValue(element, 'aria-valuetext'); if (value.length) return value; value = getAttributeValue(element, 'aria-valuenow'); if (value.length) return value; return getInputValue(element); } // HELPER FUNCTIONS FOR SPECIFIC ROLES function getTextboxValue (element) { let inputTypes = ['email', 'password', 'search', 'tel', 'text', 'url'], tagName = element.tagName.toLowerCase(), type = element.type; if (tagName === 'input' && inputTypes.indexOf(type) !== -1) { return getInputValue(element); } if (tagName === 'textarea') { return getInputValue(element); } return ''; } function getComboboxValue (element) { let inputTypes = ['email', 'search', 'tel', 'text', 'url'], tagName = element.tagName.toLowerCase(), type = element.type; if (tagName === 'input' && inputTypes.indexOf(type) !== -1) { return getInputValue(element); } return ''; } function getSliderValue (element) { let tagName = element.tagName.toLowerCase(), type = element.type; if (tagName === 'input' && type === 'range') { return getRangeValue(element); } return ''; } function getSpinbuttonValue (element) { let tagName = element.tagName.toLowerCase(), type = element.type; if (tagName === 'input' && type === 'number') { return getRangeValue(element); } return ''; } function getListboxValue (element) { let tagName = element.tagName.toLowerCase(); if (tagName === 'select') { let arr = [], selectedOptions = element.selectedOptions; for (let i = 0; i < selectedOptions.length; i++) { let option = selectedOptions[i]; let value = normalize(option.value); if (value.length) arr.push(value); } if (arr.length) return arr.join(' '); } return ''; } /* * isEmbeddedControl: Determine whether element has a role that corresponds * to an HTML form control that could be embedded within text content. */ function isEmbeddedControl (element) { let embeddedControlRoles = [ 'textbox', 'combobox', 'listbox', 'slider', 'spinbutton' ]; let role = getAriaRole(element); return (embeddedControlRoles.indexOf(role) !== -1); } /* * getEmbeddedControlValue: Based on the role of element, use native semantics * of HTML to get the corresponding text value of the embedded control. */ function getEmbeddedControlValue (element) { let role = getAriaRole(element); switch (role) { case 'textbox': return getTextboxValue(element); case 'combobox': return getComboboxValue(element); case 'listbox': return getListboxValue(element); case 'slider': return getSliderValue(element); case 'spinbutton': return getSpinbuttonValue(element); } return ''; } /* * getaccname.js * * Note: Information in this module is based on the following documents: * 1. HTML Accessibility API Mappings 1.0 (http://rawgit.com/w3c/aria/master/html-aam/html-aam.html) * 2. SVG Accessibility API Mappings (http://rawgit.com/w3c/aria/master/svg-aam/svg-aam.html) */ /* * getFieldsetLegendLabels: Recursively collect legend contents of * fieldset ancestors, starting with the closest (innermost). * Return collection as a possibly empty array of strings. */ function getFieldsetLegendLabels (element) { let arrayOfStrings = []; if (typeof element.closest !== 'function') { return arrayOfStrings; } function getLabelsRec (elem, arr) { let fieldset = elem.closest('fieldset'); if (fieldset) { let legend = fieldset.querySelector('legend'); if (legend) { let text = getElementContents(legend); if (text.length){ arr.push({ name: text, source: 'fieldset/legend' }); } } // process ancestors getLabelsRec(fieldset.parentNode, arr); } } getLabelsRec(element, arrayOfStrings); return arrayOfStrings; } /* * getGroupingLabels: Return an array of grouping label objects for * element, each with two properties: 'name' and 'source'. */ function getGroupingLabels (element) { // We currently only handle labelable elements as defined in HTML 5.1 if (isLabelableElement(element)) { return getFieldsetLegendLabels(element); } return []; } /* * nameFromNativeSemantics: Use method appropriate to the native semantics * of element to find accessible name. Includes methods for all interactive * elements. For non-interactive elements, if the element's ARIA role allows * its acc. name to be derived from its text contents, or if recFlag is set, * indicating that we are in a recursive aria-labelledby calculation, the * nameFromContents method is used. */ function nameFromNativeSemantics (element, recFlag) { let tagName = element.tagName.toLowerCase(), ariaRole = getAriaRole(element), accName = null; // TODO: Verify that this applies to all elements if (ariaRole && (ariaRole === 'presentation' || ariaRole === 'none')) { return null; } switch (tagName) { // FORM ELEMENTS: INPUT case 'input': switch (element.type) { // HIDDEN case 'hidden': if (recFlag) { accName = nameFromLabelElement(element); } break; // TEXT FIELDS case 'email': case 'password': case 'search': case 'tel': case 'text': case 'url': accName = nameFromLabelElement(element); if (accName === null) accName = nameFromAttribute(element, 'placeholder'); break; // OTHER INPUT TYPES case 'button': accName = nameFromAttribute(element, 'value'); break; case 'reset': accName = nameFromAttribute(element, 'value'); if (accName === null) accName = nameFromDefault('Reset'); break; case 'submit': accName = nameFromAttribute(element, 'value'); if (accName === null) accName = nameFromDefault('Submit'); break; case 'image': accName = nameFromAltAttribute(element); if (accName === null) accName = nameFromAttribute(element, 'value'); break; default: accName = nameFromLabelElement(element); break; } break; // FORM ELEMENTS: OTHER case 'button': accName = nameFromContents(element); break; case 'label': accName = nameFromContents(element); break; case 'keygen': case 'meter': case 'output': case 'progress': case 'select': accName = nameFromLabelElement(element); break; case 'textarea': accName = nameFromLabelElement(element); if (accName === null) accName = nameFromAttribute(element, 'placeholder'); break; // EMBEDDED ELEMENTS case 'audio': // if 'controls' attribute is present accName = { name: 'NOT YET IMPLEMENTED', source: '' }; break; case 'embed': accName = { name: 'NOT YET IMPLEMENTED', source: '' }; break; case 'iframe': accName = nameFromAttribute(element, 'title'); break; case 'img': case 'area': // added accName = nameFromAltAttribute(element); break; case 'object': accName = { name: 'NOT YET IMPLEMENTED', source: '' }; break; case 'svg': // added accName = nameFromDescendant(element, 'title'); break; case 'video': // if 'controls' attribute is present accName = { name: 'NOT YET IMPLEMENTED', source: '' }; break; // OTHER ELEMENTS case 'a': accName = nameFromContents(element); break; case 'details': accName = nameFromDetailsOrSummary(element); break; case 'figure': accName = nameFromDescendant(element, 'figcaption'); break; case 'table': accName = nameFromDescendant(element, 'caption'); break; // ELEMENTS NOT SPECIFIED ABOVE default: if (nameFromIncludesContents(element) || recFlag) accName = nameFromContents(element); break; } // LAST RESORT USE TITLE if (accName === null) accName = nameFromAttribute(element, 'title'); return accName; } /* * nameFromAttributeIdRefs: Get the value of attrName on element (a space- * separated list of IDREFs), visit each referenced element in the order it * appears in the list and obtain its accessible name (skipping recursive * aria-labelledby or aria-describedby calculations), and return an object * with name property set to a string that is a space-separated concatena- * tion of those results if any, otherwise return null. */ function nameFromAttributeIdRefs (element, attribute) { let value = getAttributeValue(element, attribute); let idRefs, i, refElement, accName, arr = []; if (value.length) { idRefs = value.split(' '); for (i = 0; i < idRefs.length; i++) { refElement = document.getElementById(idRefs[i]); if (refElement) { accName = getAccessibleName(refElement, true); if (accName && accName.name.length) arr.push(accName.name); } } } if (arr.length) return { name: arr.join(' '), source: attribute }; return null; } /* * getAccessibleName: Use the ARIA Roles Model specification for accessible * name calculation based on its precedence order: * (1) Use aria-labelledby, unless a traversal is already underway; * (2) Use aria-label attribute value; * (3) Use whatever method is specified by the native semantics of the * element, which includes, as last resort, use of the title attribute. */ function getAccessibleName (element, recFlag) { let accName = null; if (!recFlag) accName = nameFromAttributeIdRefs(element, 'aria-labelledby'); if (accName === null) accName = nameFromAttribute(element, 'aria-label'); if (accName === null) accName = nameFromNativeSemantics(element, recFlag); return accName; } /* * getAccessibleDesc: Use the ARIA Roles Model specification for accessible * description calculation based on its precedence order: * (1) Use aria-describedby, unless a traversal is already underway; * (2) As last resort, use the title attribute. */ function getAccessibleDesc (element, recFlag) { let accDesc = null; if (!recFlag) accDesc = nameFromAttributeIdRefs(element, 'aria-describedby'); if (accDesc === null) accDesc = nameFromAttribute(element, 'title'); return accDesc; } /* * info.js: Function for displaying information on highlighted elements */ /* * getElementInfo: Extract tagName and other attribute information * based on tagName and return as formatted string. */ function getElementInfo (element) { let tagName = element.tagName.toLowerCase(), elementInfo = tagName; if (tagName === 'input') { let type = element.type; if (type && type.length) elementInfo += ' [type="' + type + '"]'; } if (tagName === 'label') { let forVal = getAttributeValue(element, 'for'); if (forVal.length) elementInfo += ' [for="' + forVal + '"]'; } if (isLabelableElement(element)) { let id = element.id; if (id && id.length) elementInfo += ' [id="' + id + '"]'; } if (element.hasAttribute('role')) { let role = getAttributeValue(element, 'role'); if (role.length) elementInfo += ' [role="' + role + '"]'; } return elementInfo; } /* * formatInfo: Convert info properties into a string with line breaks. */ function formatInfo (info) { let value = ''; let title = info.title, element = info.element, grpLabels = info.grpLabels, accName = info.accName, accDesc = info.accDesc, role = info.role, props = info.props; value += '=== ' + title + ' ==='; if (element) value += '\nELEMENT: ' + element; if (grpLabels && grpLabels.length) { // array starts with innermost label, so process from the end for (let i = grpLabels.length - 1; i >= 0; i--) { value += '\nGRP. LABEL: ' + grpLabels[i].name + '\nFROM: ' + grpLabels[i].source; } } if (accName) { value += '\nACC. NAME: ' + accName.name + '\nFROM: ' + accName.source; } if (accDesc) { value += '\nACC. DESC: ' + accDesc.name + '\nFROM: ' + accDesc.source; } if (role) value += '\nROLE: ' + role; if (props) value += '\nPROPERTIES: ' + props; return value; } /* * namefrom.js */ // LOW-LEVEL FUNCTIONS /* * normalize: Trim leading and trailing whitespace and condense all * interal sequences of whitespace to a single space. Adapted from * Mozilla documentation on String.prototype.trim polyfill. Handles * BOM and NBSP characters. */ function normalize (s) { let rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; return s.replace(rtrim, '').replace(/\s+/g, ' '); } /* * getAttributeValue: Return attribute value if present on element, * otherwise return empty string. */ function getAttributeValue (element, attribute) { let value = element.getAttribute(attribute); return (value === null) ? '' : normalize(value); } /* * couldHaveAltText: Based on HTML5 specification, determine whether * element could have an 'alt' attribute. */ function couldHaveAltText (element) { let tagName = element.tagName.toLowerCase(); switch (tagName) { case 'img': case 'area': return true; case 'input': return (element.type && element.type === 'image'); } return false; } /* * hasEmptyAltText: Determine whether the alt attribute is present * and its value is the empty string. */ function hasEmptyAltText (element) { let value = element.getAttribute('alt'); // Attribute is present if (value !== null) return (normalize(value).length === 0); return false; } /* * isLabelableElement: Based on HTML5 specification, determine whether * element can be associated with a label. */ function isLabelableElement (element) { let tagName = element.tagName.toLowerCase(), type = element.type; switch (tagName) { case 'input': return (type !== 'hidden'); case 'button': case 'keygen': case 'meter': case 'output': case 'progress': case 'select': case 'textarea': return true; default: return false; } } /* * addCssGeneratedContent: Add CSS-generated content for pseudo-elements * :before and :after. According to the CSS spec, test that content value * is other than the default computed value of 'none'. * * Note: Even if an author specifies content: 'none', because browsers add * the double-quote character to the beginning and end of computed string * values, the result cannot and will not be equal to 'none'. */ function addCssGeneratedContent (element, contents) { let result = contents, prefix = getComputedStyle(element, ':before').content, suffix = getComputedStyle(element, ':after').content; if (prefix !== 'none') result = prefix + result; if (suffix !== 'none') result = result + suffix; return result; } /* * getNodeContents: Recursively process element and text nodes by aggregating * their text values for an ARIA text equivalent calculation. * 1. This includes special handling of elements with 'alt' text and embedded * controls. * 2. The forElem parameter is needed for label processing to avoid inclusion * of an embedded control's value when the label is for the control itself. */ function getNodeContents (node, forElem) { let contents = ''; if (node === forElem) return ''; switch (node.nodeType) { case Node.ELEMENT_NODE: if (couldHaveAltText(node)) { contents = getAttributeValue(node, 'alt'); } else if (isEmbeddedControl(node)) { contents = getEmbeddedControlValue(node); } else { if (node.hasChildNodes()) { let children = node.childNodes, arr = []; for (let i = 0; i < children.length; i++) { let nc = getNodeContents(children[i], forElem); if (nc.length) arr.push(nc); } contents = (arr.length) ? arr.join(' ') : ''; } } // For all branches of the ELEMENT_NODE case... contents = addCssGeneratedContent(node, contents); break; case Node.TEXT_NODE: contents = normalize(node.textContent); } return contents; } /* * getElementContents: Construct the ARIA text alternative for element by * processing its element and text node descendants and then adding any CSS- * generated content if present. */ function getElementContents (element, forElement) { let result = ''; if (element.hasChildNodes()) { let children = element.childNodes, arrayOfStrings = []; for (let i = 0; i < children.length; i++) { let contents = getNodeContents(children[i], forElement); if (contents.length) arrayOfStrings.push(contents); } result = (arrayOfStrings.length) ? arrayOfStrings.join(' ') : ''; } return addCssGeneratedContent(element, result); } /* * getContentsOfChildNodes: Using predicate function for filtering element * nodes, collect text content from all child nodes of element. */ function getContentsOfChildNodes (element, predicate) { let arr = [], content; Array.prototype.forEach.call(element.childNodes, function (node) { switch (node.nodeType) { case (Node.ELEMENT_NODE): if (predicate(node)) { content = getElementContents(node); if (content.length) arr.push(content); } break; case (Node.TEXT_NODE): content = normalize(node.textContent); if (content.length) arr.push(content); break; } }); if (arr.length) return arr.join(' '); return ''; } // HIGHER-LEVEL FUNCTIONS THAT RETURN AN OBJECT WITH SOURCE PROPERTY /* * nameFromAttribute */ function nameFromAttribute (element, attribute) { let name; name = getAttributeValue(element, attribute); if (name.length) return { name: name, source: attribute }; return null; } /* * nameFromAltAttribute */ function nameFromAltAttribute (element) { let name = element.getAttribute('alt'); // Attribute is present if (name !== null) { name = normalize(name); return (name.length) ? { name: name, source: 'alt' } : { name: '<empty>', source: 'alt' }; } // Attribute not present return null; } /* * nameFromContents */ function nameFromContents (element) { let name; name = getElementContents(element); if (name.length) return { name: name, source: 'contents' }; return null; } /* * nameFromDefault */ function nameFromDefault (name) { return name.length ? { name: name, source: 'default' } : null; } /* * nameFromDescendant */ function nameFromDescendant (element, tagName) { let descendant = element.querySelector(tagName); if (descendant) { let name = getElementContents(descendant); if (name.length) return { name: name, source: tagName + ' element' }; } return null; } /* * nameFromLabelElement */ function nameFromLabelElement (element) { let name, label; // label [for=id] if (element.id) { label = document.querySelector('[for="' + element.id + '"]'); if (label) { name = getElementContents(label, element); if (name.length) return { name: name, source: 'label reference' }; } } // label encapsulation if (typeof element.closest === 'function') { label = element.closest('label'); if (label) { name = getElementContents(label, element); if (name.length) return { name: name, source: 'label encapsulation' }; } } return null; } /* * nameFromDetailsOrSummary: If element is expanded (has open attribute), * return the contents of the summary element followed by the text contents * of element and all of its non-summary child elements. Otherwise, return * only the contents of the first summary element descendant. */ function nameFromDetailsOrSummary (element) { let name, summary; function isExpanded (elem) { return elem.hasAttribute('open'); } // At minimum, always use summary contents summary = element.querySelector('summary'); if (summary) name = getElementContents(summary); // Return either summary + details (non-summary) or summary only if (isExpanded(element)) { name += getContentsOfChildNodes(element, function (elem) { return elem.tagName.toLowerCase() !== 'summary'; }); if (name.length) return { name: name, source: 'contents' }; } else { if (name.length) return { name: name, source: 'summary element' }; } return null; } /* * overlay.js: functions for creating and modifying DOM overlay elements */ var zIndex = 100000; /* * createOverlay: Create overlay div with size and position based on the * boundingRect properties of its corresponding target element. */ function createOverlay (tgt, rect, cname) { let scrollOffsets = getScrollOffsets(); const MINWIDTH = 68; const MINHEIGHT = 27; let node = document.createElement("div"); node.setAttribute("class", [cname, 'oaa-element-overlay'].join(' ')); node.startLeft = (rect.left + scrollOffsets.x) + "px"; node.startTop = (rect.top + scrollOffsets.y) + "px"; node.style.left = node.startLeft; node.style.top = node.startTop; node.style.width = Math.max(rect.width, MINWIDTH) + "px"; node.style.height = Math.max(rect.height, MINHEIGHT) + "px"; node.style.borderColor = tgt.color; node.style.zIndex = zIndex; let label = document.createElement("div"); label.setAttribute("class", 'oaa-overlay-label'); label.style.backgroundColor = tgt.color; label.innerHTML = tgt.label; node.appendChild(label); return node; } /* * addDragAndDrop: Add drag-and-drop and reposition functionality to an * overlay div element created by the createOverlay function. */ function addDragAndDrop (node) { function hoistZIndex (el) { let incr = 100; el.style.zIndex = zIndex += incr; } function repositionOverlay (el) { el.style.left = el.startLeft; el.style.top = el.startTop; } let labelDiv = node.firstChild; labelDiv.onmousedown = function (event) { drag(this.parentNode, hoistZIndex, event); }; labelDiv.ondblclick = function (event) { repositionOverlay(this.parentNode); }; } /* * roles.js * * Note: The information in this module is based on the following documents: * 1. ARIA in HTML (https://specs.webplatform.org/html-aria/webspecs/master/) * 2. WAI-ARIA 1.1 (http://www.w3.org/TR/wai-aria-1.1/) * 3. WAI-ARIA 1.0 (http://www.w3.org/TR/wai-aria/) */ /* * inListOfOptions: Determine whether element is a child of * 1. a select element * 2. an optgroup element that is a child of a select element * 3. a datalist element */ function inListOfOptions (element) { let parent = element.parentElement, parentName = parent.tagName.toLowerCase(), parentOfParentName = parent.parentElement.tagName.toLowerCase(); if (parentName === 'select') return true; if (parentName === 'optgroup' && parentOfParentName === 'select') return true; if (parentName === 'datalist') return true; return false; } /* * validRoles: Reference list of all concrete ARIA roles as specified in * WAI-ARIA 1.1 Working Draft of 14 July 2015 */ var validRoles = [ // LANDMARK 'application', 'banner', 'complementary', 'contentinfo', 'form', 'main', 'navigation', 'search', // WIDGET 'alert', 'alertdialog', 'button', 'checkbox', 'dialog', 'gridcell', 'link', 'log', 'marquee', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'progressbar', 'radio', 'scrollbar', 'searchbox', // ARIA 1.1 'slider', 'spinbutton', 'status', 'switch', // ARIA 1.1 'tab', 'tabpanel', 'textbox', 'timer', 'tooltip', 'treeitem', // COMPOSITE WIDGET 'combobox', 'grid', 'listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid', // DOCUMENT STRUCTURE 'article', 'cell', // ARIA 1.1 'columnheader', 'definition', 'directory', 'document', 'group', 'heading', 'img', 'list', 'listitem', 'math', 'none', // ARIA 1.1 'note', 'presentation', 'region', 'row', 'rowgroup', 'rowheader', 'separator', 'table', // ARIA 1.1 'text', // ARIA 1.1 'toolbar' ]; /* * getValidRole: Examine each value in space-separated list by attempting * to find its match in the validRoles array. If a match is found, return * it. Otherwise, return null. */ function getValidRole (spaceSepList) { let arr = spaceSepList.split(' '); for (let i = 0; i < arr.length; i++) { let value = arr[i].toLowerCase(); let validRole = validRoles.find(role => role === value); if (validRole) return validRole; } return null; } /* * getAriaRole: Get the value of the role attribute, if it is present. If * not specified, get the default role of element if it has one. Based on * ARIA in HTML as of 21 October 2015. */ function getAriaRole (element) { let tagName = element.tagName.toLowerCase(), type = element.type; if (element.hasAttribute('role')) { return getValidRole(getAttributeValue(element, 'role')); } switch (tagName) { case 'a': if (element.hasAttribute('href')) return 'link'; break; case 'area': if (element.hasAttribute('href')) return 'link'; break; case 'article': return 'article'; case 'aside': return 'complementary'; case 'body': return 'document'; case 'button': return 'button'; case 'datalist': return 'listbox'; case 'details': return 'group'; case 'dialog': return 'dialog'; case 'dl': return 'list'; case 'fieldset': return 'group'; case 'footer': if (!isDescendantOf(element, ['article', 'section'])) return 'contentinfo'; break; case 'form': return 'form'; case 'h1': return 'heading'; case 'h2': return 'heading'; case 'h3': return 'heading'; case 'h4': return 'heading'; case 'h5': return 'heading'; case 'h6': return 'heading'; case 'header': if (!isDescendantOf(element, ['article', 'section'])) return 'banner'; break; case 'hr': return 'separator'; case 'img': if (!hasEmptyAltText(element)) return 'img'; break; case 'input': if (type === 'button') return 'button'; if (type === 'checkbox') return 'checkbox'; if (type === 'email') return (element.hasAttribute('list')) ? 'combobox' : 'textbox'; if (type === 'image') return 'button'; if (type === 'number') return 'spinbutton'; if (type === 'password') return 'textbox'; if (type === 'radio') return 'radio'; if (type === 'range') return 'slider'; if (type === 'reset') return 'button'; if (type === 'search') return (element.hasAttribute('list')) ? 'combobox' : 'textbox'; if (type === 'submit') return 'button'; if (type === 'tel') return (element.hasAttribute('list')) ? 'combobox' : 'textbox'; if (type === 'text') return (element.hasAttribute('list')) ? 'combobox' : 'textbox'; if (type === 'url') return (element.hasAttribute('list')) ? 'combobox' : 'textbox'; break; case 'li': if (hasParentWithName(element, ['ol', 'ul'])) return 'listitem'; break; case 'link': if (element.hasAttribute('href')) return 'link'; break; case 'main': return 'main'; case 'menu': if (type === 'toolbar') return 'toolbar'; break; case 'menuitem': if (type === 'command') return 'menuitem'; if (type === 'checkbox') return 'menuitemcheckbox'; if (type === 'radio') return 'menuitemradio'; break; case 'meter': return 'progressbar'; case 'nav': return 'navigation'; case 'ol': return 'list'; case 'option': if (inListOfOptions(element)) return 'option'; break; case 'output': return 'status'; case 'progress': return 'progressbar'; case 'section': return 'region'; case 'select': return 'listbox'; case 'summary': return 'button'; case 'tbody': return 'rowgroup'; case 'tfoot': return 'rowgroup'; case 'thead': return 'rowgroup'; case 'textarea': return 'textbox'; // TODO: th can have role 'columnheader' or 'rowheader' case 'th': return 'columnheader'; case 'ul': return 'list'; } return null; } /* * nameFromIncludesContents: Determine whether the ARIA role of element * specifies that its 'name from' includes 'contents'. */ function nameFromIncludesContents (element) { let elementRole = getAriaRole(element); if (elementRole === null) return false; let contentsRoles = [ 'button', 'cell', // ARIA 1.1 'checkbox', 'columnheader', 'directory', 'gridcell', 'heading', 'link', 'listitem', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'row', 'rowgroup', 'rowheader', 'switch', // ARIA 1.1 'tab', 'text', // ARIA 1.1 'tooltip', 'treeitem' ]; let contentsRole = contentsRoles.find(role => role === elementRole); return (typeof contentsRole !== 'undefined'); } /* * utils.js: utility functions */ /* * getScrollOffsets: Use x and y scroll offsets to calculate positioning * coordinates that take into account whether the page has been scrolled. * From Mozilla Developer Network: Element.getBoundingClientRect() */ function getScrollOffsets () { let t; let xOffset = (typeof window.pageXOffset === "undefined") ? (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.ScrollLeft === 'number' ? t : document.body).ScrollLeft : window.pageXOffset; let yOffset = (typeof window.pageYOffset === "undefined") ? (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.ScrollTop === 'number' ? t : document.body).ScrollTop : window.pageYOffset; return { x: xOffset, y: yOffset }; } /* * drag: Add drag and drop functionality to an element by setting this * as its mousedown handler. Depends upon getScrollOffsets function. * From JavaScript: The Definitive Guide, 6th Edition (slightly modified) */ function drag (elementToDrag, dragCallback, event) { let scroll = getScrollOffsets(); let startX = event.clientX + scroll.x; let startY = event.clientY + scroll.y; let origX = elementToDrag.offsetLeft; let origY = elementToDrag.offsetTop; let deltaX = startX - origX; let deltaY = startY - origY; if (dragCallback) dragCallback(elementToDrag); if (document.addEventListener) { document.addEventListener("mousemove", moveHandler, true); document.addEventListener("mouseup", upHandler, true); } else if (document.attachEvent) { elementToDrag.setCapture(); elementToDrag.attachEvent("onmousemove", moveHandler); elementToDrag.attachEvent("onmouseup", upHandler); elementToDrag.attachEvent("onlosecapture", upHandler); } if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true; if (event.preventDefault) event.preventDefault(); else event.returnValue = false; function moveHandler (e) { if (!e) e = window.event; let scroll = getScrollOffsets(); elementToDrag.style.left = (e.clientX + scroll.x - deltaX) + "px"; elementToDrag.style.top = (e.clientY + scroll.y - deltaY) + "px"; elementToDrag.style.cursor = "move"; if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; } function upHandler (e) { if (!e) e = window.event; elementToDrag.style.cursor = "grab"; elementToDrag.style.cursor = "-moz-grab"; elementToDrag.style.cursor = "-webkit-grab"; if (document.removeEventListener) { document.removeEventListener("mouseup", upHandler, true); document.removeEventListener("mousemove", moveHandler, true); } else if (document.detachEvent) { elementToDrag.detachEvent("onlosecapture", upHandler); elementToDrag.detachEvent("onmouseup", upHandler); elementToDrag.detachEvent("onmousemove", moveHandler); elementToDrag.releaseCapture(); } if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; } } /* * addPolyfills: Add polyfill implementations for JavaScript object methods * defined in ES6 and used by bookmarklets: * 1. Array.prototype.find * 2. String.prototype.includes */ function addPolyfills () { // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find if (!Array.prototype.find) { Array.prototype.find = function (predicate) { if (this === null) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; }; } // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes if (!String.prototype.includes) { String.prototype.includes = function (search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > this.length) { return false; } else { return this.indexOf(search, start) !== -1; } }; } }
oaa-tools/bookmarklets-library
extension/library.js
JavaScript
apache-2.0
50,228
import * as utils from '../src/utils.js'; import {config} from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; const BIDDER_CODE = 'vdoai'; const ENDPOINT_URL = 'https://prebid.vdo.ai/auction'; export const spec = { code: BIDDER_CODE, supportedMediaTypes: [BANNER, VIDEO], /** * Determines whether or not the given bid request is valid. * * @param {BidRequest} bid The bid params to validate. * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: function (bid) { return !!(bid.params.placementId); }, /** * Make a server request from the list of BidRequests. * * @return Array Info describing the request to the server. * @param validBidRequests * @param bidderRequest */ buildRequests: function (validBidRequests, bidderRequest) { if (validBidRequests.length === 0) { return []; } return validBidRequests.map(bidRequest => { const sizes = utils.getAdUnitSizes(bidRequest); const payload = { placementId: bidRequest.params.placementId, sizes: sizes, bidId: bidRequest.bidId, referer: bidderRequest.refererInfo.referer, id: bidRequest.auctionId, mediaType: bidRequest.mediaTypes.video ? 'video' : 'banner' }; bidRequest.params.bidFloor && (payload['bidFloor'] = bidRequest.params.bidFloor); return { method: 'POST', url: ENDPOINT_URL, data: payload }; }); }, /** * Unpack the response from the server into a list of bids. * * @param {ServerResponse} serverResponse A successful response from the server. * @param bidRequest * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: function (serverResponse, bidRequest) { const bidResponses = []; const response = serverResponse.body; const creativeId = response.adid || 0; // const width = response.w || 0; const width = response.width; // const height = response.h || 0; const height = response.height; const cpm = response.price || 0; response.rWidth = width; response.rHeight = height; const adCreative = response.vdoCreative; if (width !== 0 && height !== 0 && cpm !== 0 && creativeId !== 0) { // const dealId = response.dealid || ''; const currency = response.cur || 'USD'; const netRevenue = true; // const referrer = bidRequest.data.referer; const bidResponse = { requestId: response.bidId, cpm: cpm, width: width, height: height, creativeId: creativeId, // dealId: dealId, currency: currency, netRevenue: netRevenue, ttl: config.getConfig('_bidderTimeout'), // referrer: referrer, // ad: response.adm // ad: adCreative, mediaType: response.mediaType }; if (response.mediaType == 'video') { bidResponse.vastXml = adCreative; } else { bidResponse.ad = adCreative; } if (response.adDomain) { bidResponse.meta = { advertiserDomains: response.adDomain } } bidResponses.push(bidResponse); } return bidResponses; }, getUserSyncs: function(syncOptions, serverResponse) { let syncUrls = serverResponse[0] && serverResponse[0].body && serverResponse[0].body.cookiesync && serverResponse[0].body.cookiesync.bidder_status; if (syncOptions.iframeEnabled && syncUrls && syncUrls.length > 0) { let prebidSyncUrls = syncUrls.map(syncObj => { return { url: syncObj.usersync.url, type: 'iframe' } }) return prebidSyncUrls; } return []; }, onTImeout: function(data) {}, onBidWon: function(bid) {}, onSetTargeting: function(bid) {} }; registerBidder(spec);
tchibirev/Prebid.js
modules/vdoaiBidAdapter.js
JavaScript
apache-2.0
3,931
var auth = require( './auth' ), surveyTemplate = require( '../lib/survey_template' ), SurveyResponse = require( '../models/survey_response' ); var ExportController = function() { this.csv = function( req, res ) { var now = new Date(), cleanTitle = req.survey.title.replace( /[^a-z0-9]/ig, '' ), key = req.param( 'key' ), today = now.getFullYear() + '_' + ( now.getMonth() + 1 ) + '_' + now.getDate(), flatSurvey = [], csvData = [], survey = surveyTemplate.getSurvey( req.survey.version ); survey.pages.forEach( function( page ) { page.fields.forEach( function( q ) { if( q.type === 'gridselect' ) { for( var key in q.options ) { flatSurvey.push( { name: key, label: q.options[ key ] } ); } } else { flatSurvey.push( { name: q.name, label: q.label } ); } } ); } ); csvData.push( flatSurvey.map( function( q ) { return q.label; } ) ); SurveyResponse.find( { surveyId: req.survey.id }, function( err, responses ) { if( responses && responses.length ) { responses.forEach( function( response ) { csvData.push( flatSurvey.map( function( q ) { try { return response.response[ q.name ]; } catch( e ) { return ''; } } ) ); } ); } res.header('Content-Disposition', 'attachment; filename=' + today + '_' + cleanTitle + '.csv'); res.csv( csvData ); } ); }; }; exports.setup = function( app ) { var exporter = new ExportController(); app.get( '/export/:key', auth.canAccessSurvey, exporter.csv ); };
UCSoftware/responsive-pulse
controllers/export.js
JavaScript
apache-2.0
1,943
/****************************************************************************** * $URL: https://source.sakaiproject.org/svn/user/tags/sakai-10.1/user-tool/tool/src/webapp/js/userCreateValidation.js $ * $Id: userCreateValidation.js 308075 2014-04-11 12:34:16Z azeckoski@unicon.net $ ****************************************************************************** * * Copyright (c) 2003-2014 The Apereo Foundation * * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://opensource.org/licenses/ecl2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ // USER declared in userValidationCommon.js // Validate the password from the form USER.validatePassword = function () { var username = USER.trim(USER.get("eid").value); var pw = USER.get("pw").value; var strongMsg = USER.get("strongMsg"); var moderateMsg = USER.get("moderateMsg"); var weakMsg = USER.get("weakMsg"); var failMsg = USER.get("failMsg"); var strengthInfo = USER.get("strengthInfo"); var strengthBar = USER.get("strengthBar"); var strengthBarMeter = USER.get("strengthBarMeter"); // If the password field has a value: // 1) make the AJAX call to the validate password REST endpoint // 2) conditionally display the appropriate messages // 3) conditionally hide/show the strength info message if (USER.isPasswordPolicyEnabled && pw.length > 0) { USER.validatePasswordREST(pw, username); USER.displayMessages(strongMsg, moderateMsg, weakMsg, failMsg, strengthBar, strengthBarMeter); USER.displayStrengthInfo(); } // Otherwise, password policy is disabled OR the password field has no value else { USER.passwordValid = pw.length > 0; USER.hideAllElements(strongMsg, moderateMsg, weakMsg, failMsg, strengthInfo, strengthBar, strengthBarMeter); } // Verify the passwords match (which in turn validates the form) USER.verifyPasswordsMatch(); }; // Verify the passwords match USER.verifyPasswordsMatch = function () { var pw = USER.get("pw").value; var pw2 = USER.get("pw0").value; var matchMsg = USER.get("matchMsg"); var noMatchMsg = USER.get("noMatchMsg"); USER.passwordsMatch = pw === pw2; if (pw.length > 0 || pw2.length > 0) { USER.display(matchMsg, USER.passwordsMatch); USER.display(noMatchMsg, !USER.passwordsMatch); } else { USER.display(matchMsg, false); USER.display(noMatchMsg, false); } USER.validateForm(); } // Validate the user ID from the form USER.validateUserId = function () { var userId = USER.trim(USER.get("eid").value); USER.userValid = userId.length > 0; USER.validatePassword(); }; // Validate the email address from the form USER.validateEmail = function () { var email = USER.trim(USER.get("email").value); var emailWarningMsg = USER.get("emailWarningMsg"); if (email.length < 1) { USER.emailValid = true; } else { USER.emailValid = USER.checkEmail(email); } USER.display(emailWarningMsg, !USER.emailValid); USER.validateForm(); }; // Validate the form (enable/disable the submit button) USER.validateForm = function () { var submitButton = USER.get("eventSubmit_doSave"); if (USER.userValid && USER.emailValid && USER.passwordValid && USER.passwordsMatch) { submitButton.disabled = false; } else { submitButton.disabled = true; } setMainFrameHeightNow(window.name); }; // Initialization function jQuery(document).ready(function () { USER.validateEmail(); USER.validateUserId(); });
harfalm/Sakai-10.1
user/user-tool/tool/src/webapp/js/userCreateValidation.js
JavaScript
apache-2.0
4,100
define({"topics" : [{"title":"Local Buffer Resource Requirements","href":"datacollector\/UserGuide\/Origins\/OracleCDC.html#concept_atl_ytf_p1b","attributes": {"data-id":"concept_atl_ytf_p1b",},"menu": {"hasChildren":false,},"tocID":"concept_atl_ytf_p1b-d46e55285","topics":[]},{"title":"Uncommitted Transaction Handling","href":"datacollector\/UserGuide\/Origins\/OracleCDC.html#concept_ssg_tgm_p1b","attributes": {"data-id":"concept_ssg_tgm_p1b",},"menu": {"hasChildren":false,},"tocID":"concept_ssg_tgm_p1b-d46e55398","topics":[]}]});
rockmkd/datacollector
docs/generated/oxygen-webhelp/app/nav-links/json/concept_yqk_3hn_n1b-d46e55152.js
JavaScript
apache-2.0
537
/** * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ const path = require('path'); const Benchmark = require('benchmark'); const parsePackageString = require('npm-package-arg'); const InstallationUtils = require('../src/utils/installation-utils'); const BenchmarkUtils = require('./utils/benchmark-utils'); const { getLocalPackageEcmaVersion } = require('../src/index.js'); async function coldStartBenchmark(packageString) { const installPath = await InstallationUtils.getInstallPath(); await InstallationUtils.installPackage(packageString, installPath); const packageName = parsePackageString(packageString).name; const packagePath = path.join(installPath, 'node_modules', packageName); console.log( '| %s | %dms |', packageString, await BenchmarkUtils.getAsyncRuntime(() => getLocalPackageEcmaVersion(packagePath) ) ); await InstallationUtils.cleanupPath(installPath); } // Multiple asynchronous suites will interfere in BenchmarkJS so we must use // suite.on('complete') to sequentially run suites async function warmRunBenchmark(packageStrings, index) { if (index >= packageStrings.length) { return; } const packageString = packageStrings[index]; const installPath = await InstallationUtils.getInstallPath(); await InstallationUtils.installPackage(packageString, installPath); const packageName = parsePackageString(packageString).name; const packagePath = path.join(installPath, 'node_modules', packageName); const suite = new Benchmark.Suite('getLocalPackageEcmaVersion'); suite .add(`Benchmarking getLocalPackageEcmaVersion for ${packageString}`, { defer: true, fn: async function (deferred) { await getLocalPackageEcmaVersion(packagePath); deferred.resolve(); }, }) .on('cycle', function (event) { console.log('%s ', String(event.target)); console.log( ' Mean runtime: %dms ', String((event.target.stats.mean * 1000).toFixed(2)) ); }) .on('complete', async function (event) { await InstallationUtils.cleanupPath(installPath); warmRunBenchmark(packageStrings, index + 1); }); suite.run(); } async function main() { const packageNames = [ 'bowser@2.10.0', 'chalk@4.1.0', '@lattice/configurer@0.0.1', '@babel/core@7.11.4', 'request@2.88.2', 'react@16.13.1', 'react-dom@16.13.1', 'lit-html@1.2.1', 'lodash@4.17.19', 'lodash-es@4.17.15', 'conf@7.1.1', 'swr@0.3.0', 'vue@2.6.11', '@nelsongomes/ts-timeframe@0.2.2', ]; console.log('Cold-start Benchmarks'); console.log(''); console.log('| File | Time |'); console.log('|------|------|'); for (const packageName of packageNames) { await coldStartBenchmark(packageName); } console.log('\nWarm-run Benchmarks '); await warmRunBenchmark(packageNames, 0); } main();
GoogleChromeLabs/detect-es-version
scripts/get-local-package-ecma-version-benchmark.js
JavaScript
apache-2.0
3,413
var gulp = require('gulp'); var karma = require('karma'); var fs = require('fs'); gulp.task('test', function() { new karma.Server({configFile: __dirname + '/karma.conf.js', reporters: 'dots'}).start(); var content = fs.readFileSync('copyAndRenameTest.js'); console.log(content); });
mlaval/test-karma
gulpfile.js
JavaScript
apache-2.0
289
/** * @license Apache-2.0 * * Copyright (c) 2022 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Compute the hyperbolic cosecant of a number. * * @module @stdlib/math/base/special/csch * * @example * var csch = require( '@stdlib/math/base/special/csch' ); * * var v = csch( 0.0 ); * // returns Infinity * * v = csch( 2.0 ); * // returns ~0.2757 * * v = csch( -2.0 ); * // returns ~-0.2757 * * v = csch( NaN ); * // returns NaN */ // MODULES // var main = require( './main.js' ); // EXPORTS // module.exports = main;
stdlib-js/stdlib
lib/node_modules/@stdlib/math/base/special/csch/lib/index.js
JavaScript
apache-2.0
1,075
var Q = require("q") Q.longStackSupport = true function a() { Q.delay(100).done(b) } function b() { throw new Error("foo") } a() // Error: foo // at b (/path/to/snippets/q-longStack-after.js:5:22) // From previous event: // at a (/path/to/snippets/q-longStack-after.js:4:29) // at Object.<anonymous> (/path/to/snippets/q-longStack-after.js:7:1)
pmuellr/slides
2014/04-debugging-node/snippets/q-longStack-after.js
JavaScript
apache-2.0
359
goog.provide('recoil.ui.widgets.table.LabelColumn'); goog.require('recoil.frp.Behaviour'); goog.require('recoil.frp.struct'); goog.require('recoil.ui.BoolWithExplanation'); goog.require('recoil.ui.widgets.LabelWidget'); goog.require('recoil.ui.widgets.table.Column'); /** * @implements {recoil.ui.widgets.table.Column} * @template T * @constructor * @param {recoil.structs.table.ColumnKey} key * @param {string|Node} name * @param {(recoil.frp.Behaviour<Object>|Object)=} opt_meta */ recoil.ui.widgets.table.LabelColumn = function(key, name, opt_meta) { this.key_ = key; this.name_ = name; this.options_ = opt_meta || {}; }; /** * adds all the meta information that a column should need * this should at least include cellWidgetFactory * other meta data can include: * headerDecorator * cellDecorator * and anything else specific to this column such as options for a combo box * * @param {Object} curMeta * @return {Object} */ recoil.ui.widgets.table.LabelColumn.prototype.getMeta = function(curMeta) { var meta = {name: this.name_, cellWidgetFactory: recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory_}; goog.object.extend(meta, this.options_, curMeta); return meta; }; /** * @private * @param {!recoil.ui.WidgetScope} scope * @param {!recoil.frp.Behaviour<recoil.structs.table.TableCell>} cellB * @return {!recoil.ui.Widget} */ recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory_ = function(scope, cellB) { var frp = scope.getFrp(); var widget = new recoil.ui.widgets.LabelWidget(scope); var value = recoil.frp.table.TableCell.getValue(frp, cellB); var metaData = recoil.frp.table.TableCell.getMeta(frp, cellB); widget.attachStruct(recoil.frp.struct.extend(frp, metaData, {name: value})); return widget; }; /** * @const * @type {!Object} */ recoil.ui.widgets.table.LabelColumn.meta = {cellWidgetFactory: recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory_}; /** * @param {!recoil.ui.WidgetScope} scope * @param {!recoil.frp.Behaviour<recoil.structs.table.TableCell>} cellB * @return {!recoil.ui.Widget} */ recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory = recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory_; /** * @return {recoil.structs.table.ColumnKey} */ recoil.ui.widgets.table.LabelColumn.prototype.getKey = function() { return this.key_; };
evaks/recoil
src/ui/widgets/table/label_column.js
JavaScript
apache-2.0
2,400
var assert = require('assert'); describe('Array', function(){ describe('#indexOf()', function(){ it('should return -1 when the value is not present', function(){ assert.equal(-1, [1,2,3,4].indexOf(5)); }); }); });
joaquindev/ponghtml5game-c-s
test/tests.spec.js
JavaScript
apache-2.0
233
var Location = function (jsonInFeed) { var jsonContent = JSON.parse(jsonInFeed); this.globalid = jsonContent.identifier[0].value; this.name = jsonContent.name; this.parentId = jsonContent.managingOrganization.reference; this.fullName = function () { var fullName = this.parent.fullName() + ', ' + this.name; // FIXME: we shouldn't need this once Evan fixed RapidPro db restriction if (fullName.length > 64) { fullName = fullName.substring(0, 62) + '..'; } return fullName; }; this.groups = function () { return [this.fullName()].concat(this.parent.groups()); }; }; Location.loadAll = function (url) { var FeedReader = require(__dirname + '/feed-reader'); var feedReader = new FeedReader(Location, url); return feedReader.loadAll(); }; module.exports = Location;
openhie/mhero-synch
app/location.js
JavaScript
apache-2.0
870
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Creates an http server to handle static * files and list directories for use with the gulp live server */ var BBPromise = require('bluebird'); var app = require('express')(); var bacon = require('baconipsum'); var bodyParser = require('body-parser'); var fs = BBPromise.promisifyAll(require('fs')); var formidable = require('formidable'); var jsdom = require('jsdom'); var path = require('path'); var request = require('request'); var url = require('url'); app.use(bodyParser.json()); app.use('/request-bank', require('./request-bank')); // Append ?csp=1 to the URL to turn on the CSP header. // TODO: shall we turn on CSP all the time? app.use(function(req, res, next) { if (req.query.csp) { res.set({ 'content-security-policy': "default-src * blob: data:; script-src https://cdn.ampproject.org/rtv/ https://cdn.ampproject.org/v0.js https://cdn.ampproject.org/v0/ https://cdn.ampproject.org/viewer/ http://localhost:8000 https://localhost:8000; object-src 'none'; style-src 'unsafe-inline' https://cloud.typography.com https://fast.fonts.net https://fonts.googleapis.com https://maxcdn.bootstrapcdn.com; report-uri https://csp-collector.appspot.com/csp/amp", }); } next(); }); app.use('/pwa', function(req, res, next) { var file; var contentType; if (!req.url || req.url == '/') { // pwa.html contentType = 'text/html'; file = '/examples/pwa/pwa.html'; } else if (req.url == '/pwa.js') { // pwa.js contentType = 'application/javascript'; file = '/examples/pwa/pwa.js'; } else if (req.url == '/pwa-sw.js') { // pwa.js contentType = 'application/javascript'; file = '/examples/pwa/pwa-sw.js'; } else { // Redirect to the underlying resource. // TODO(dvoytenko): would be nicer to do forward instead of redirect. res.writeHead(302, {'Location': req.url}); res.end(); return; } res.statusCode = 200; res.setHeader('Content-Type', contentType); fs.readFileAsync(process.cwd() + file).then((file) => { res.end(file); }); }); app.use('/api/show', function(req, res) { res.json({ showNotification: true }); }); app.use('/api/dont-show', function(req, res) { res.json({ showNotification: false }); }); app.use('/api/echo/post', function(req, res) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(req.body, null, 2)); }); /** * In practice this would be *.ampproject.org and the publishers * origin. Please see AMP CORS docs for more details: * https://goo.gl/F6uCAY * @type {RegExp} */ const ORIGIN_REGEX = new RegExp('^http://localhost:8000|' + '^https?://.+\.herokuapp\.com'); /** * In practice this would be the publishers origin. * Please see AMP CORS docs for more details: * https://goo.gl/F6uCAY * @type {RegExp} */ const SOURCE_ORIGIN_REGEX = new RegExp('^http://localhost:8000|' + '^https?://.+\.herokuapp\.com'); app.use('/form/html/post', function(req, res) { assertCors(req, res, ['POST']); var form = new formidable.IncomingForm(); form.parse(req, function(err, fields) { res.setHeader('Content-Type', 'text/html'); if (fields['email'] == 'already@subscribed.com') { res.statusCode = 500; res.end(` <h1 style="color:red;">Sorry ${fields['name']}!</h1> <p>The email ${fields['email']} is already subscribed!</p> `); } else { res.end(` <h1>Thanks ${fields['name']}!</h1> <p>Please make sure to confirm your email ${fields['email']}</p> `); } }); }); app.use('/form/redirect-to/post', function(req, res) { assertCors(req, res, ['POST'], ['AMP-Redirect-To']); res.setHeader('AMP-Redirect-To', 'https://google.com'); res.end('{}'); }); app.use('/form/echo-json/post', function(req, res) { assertCors(req, res, ['POST']); var form = new formidable.IncomingForm(); form.parse(req, function(err, fields) { res.setHeader('Content-Type', 'application/json; charset=utf-8'); if (fields['email'] == 'already@subscribed.com') { res.statusCode = 500; } res.end(JSON.stringify(fields)); }); }); app.use('/form/json/poll1', function(req, res) { assertCors(req, res, ['POST']); var form = new formidable.IncomingForm(); form.parse(req, function(err, fields) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ result: [{ answer: 'Penguins', percentage: new Array(77), }, { answer: 'Ostriches', percentage: new Array(8), }, { answer: 'Kiwis', percentage: new Array(14), }, { answer: 'Wekas', percentage: new Array(1), },] })); }); }); app.use('/form/search-html/get', function(req, res) { res.setHeader('Content-Type', 'text/html'); res.end(` <h1>Here's results for your search<h1> <ul> <li>Result 1</li> <li>Result 2</li> <li>Result 3</li> </ul> `); }); app.use('/form/search-json/get', function(req, res) { assertCors(req, res, ['GET']); res.json({ results: [{title: 'Result 1'}, {title: 'Result 2'}, {title: 'Result 3'}] }); }); app.use('/share-tracking/get-outgoing-fragment', function(req, res) { res.setHeader('AMP-Access-Control-Allow-Source-Origin', req.protocol + '://' + req.headers.host); res.json({ fragment: '54321' }); }); // Fetches an AMP document from the AMP proxy and replaces JS // URLs, so that they point to localhost. function proxyToAmpProxy(req, res, minify) { var url = 'https://cdn.ampproject.org/' + (req.query['amp_js_v'] ? 'v' : 'c') + req.url; console.log('Fetching URL: ' + url); request(url, function(error, response, body) { body = body // Unversion URLs. .replace(/https\:\/\/cdn\.ampproject\.org\/rtv\/\d+\//g, 'https://cdn.ampproject.org/') // <base> href pointing to the proxy, so that images, etc. still work. .replace('<head>', '<head><base href="https://cdn.ampproject.org/">'); const inabox = req.query['inabox'] == '1'; const urlPrefix = getUrlPrefix(req); body = replaceUrls(minify ? 'min' : 'max', body, urlPrefix, inabox); if (inabox) { // Allow CORS requests for A4A. const origin = req.headers.origin || urlPrefix; enableCors(req, res, origin); } res.status(response.statusCode).send(body); }); } var liveListUpdateFile = '/examples/live-list-update.amp.html'; var liveListCtr = 0; var itemCtr = 2; var liveListDoc = null; var doctype = '<!doctype html>\n'; // Only handle min/max app.use('/examples/live-list-update.amp.(min|max).html', function(req, res) { var filePath = req.baseUrl; var mode = getPathMode(filePath); // When we already have state in memory and user refreshes page, we flush // the dom we maintain on the server. if (!('amp_latest_update_time' in req.query) && liveListDoc) { var outerHTML = liveListDoc.documentElement./*OK*/outerHTML; outerHTML = replaceUrls(mode, outerHTML); res.send(`${doctype}${outerHTML}`); return; } if (!liveListDoc) { var liveListUpdateFullPath = `${process.cwd()}${liveListUpdateFile}`; var liveListFile = fs.readFileSync(liveListUpdateFullPath); liveListDoc = jsdom.jsdom(liveListFile); } var action = Math.floor(Math.random() * 3); var liveList = liveListDoc.querySelector('#my-live-list'); var perPage = Number(liveList.getAttribute('data-max-items-per-page')); var items = liveList.querySelector('[items]'); var pagination = liveListDoc.querySelector('#my-live-list [pagination]'); var item1 = liveList.querySelector('#list-item-1'); if (liveListCtr != 0) { if (Math.random() < .8) { // Always run a replace on the first item liveListReplace(item1); if (Math.random() < .5) { liveListTombstone(liveList); } if (Math.random() < .8) { liveListInsert(liveList, item1); } pagination.textContent = ''; var liveChildren = [].slice.call(items.children) .filter(x => !x.hasAttribute('data-tombstone')); var pageCount = Math.ceil(liveChildren.length / perPage); var pageListItems = Array.apply(null, Array(pageCount)) .map((_, i) => `<li>${i + 1}</li>`).join(''); var newPagination = '<nav aria-label="amp live list pagination">' + `<ul class="pagination">${pageListItems}</ul>` + '</nav>'; pagination./*OK*/innerHTML = newPagination; } else { // Sometimes we want an empty response to simulate no changes. res.send(`${doctype}<html></html>`); return; } } var outerHTML = liveListDoc.documentElement./*OK*/outerHTML; outerHTML = replaceUrls(mode, outerHTML); liveListCtr++; res.send(`${doctype}${outerHTML}`); }); function liveListReplace(item) { item.setAttribute('data-update-time', Date.now()); var itemContents = item.querySelectorAll('.content'); itemContents[0].textContent = Math.floor(Math.random() * 10); itemContents[1].textContent = Math.floor(Math.random() * 10); } function liveListInsert(liveList, node) { var iterCount = Math.floor(Math.random() * 2) + 1; console.log(`inserting ${iterCount} item(s)`); for (var i = 0; i < iterCount; i++) { var child = node.cloneNode(true); child.setAttribute('id', `list-item-${itemCtr++}`); child.setAttribute('data-sort-time', Date.now()); liveList.querySelector('[items]').appendChild(child); } } function liveListTombstone(liveList) { var tombstoneId = Math.floor(Math.random() * itemCtr); console.log(`trying to tombstone #list-item-${tombstoneId}`); // We can tombstone any list item except item-1 since we always do a // replace example on item-1. if (tombstoneId != 1) { var item = liveList./*OK*/querySelector(`#list-item-${tombstoneId}`); if (item) { item.setAttribute('data-tombstone', ''); } } } // Generate a random number between min and max // Value is inclusive of both min and max values. function range(min, max) { var values = Array.apply(null, Array(max - min + 1)).map((_, i) => min + i); return values[Math.round(Math.random() * (max - min))] } // Returns the result of a coin flip, true or false function flip() { return !!Math.floor(Math.random() * 2); } function getLiveBlogItem() { var now = Date.now(); // Generate a 3 to 7 worded headline var headline = bacon(range(3, 7)); var numOfParagraphs = range(1, 2); var body = Array.apply(null, Array(numOfParagraphs)).map(x => { return `<p>${bacon(range(50, 90))}</p>`; }).join('\n'); var img = `<amp-img src="${flip() ? 'https://placekitten.com/300/350' : 'https://baconmockup.com/300/350'}" layout="responsive" height="300" width="350"> </amp-img>`; return `<!doctype html> <html amp><body> <amp-live-list id="live-blog-1"> <div items> <div id="live-blog-item-${now}" data-sort-time="${now}"> <h3 class="headline"> <a href="#live-blog-item-${now}">${headline}</a> </h3> <div class="author"> <div class="byline"> <p> by <span itemscope itemtype="http://schema.org/Person" itemprop="author"><b>Lorem Ipsum</b> <a class="mailto" href="mailto:lorem.ipsum@"> lorem.ipsum@</a></span> </p> <p class="brand">PublisherName News Reporter<p> <p><span itemscope itemtype="http://schema.org/Date" itemprop="Date">${Date(now).replace(/ GMT.*$/, '')}<span></p> </div> </div> <div class="article-body">${body}</div> ${img} <div class="social-box"> <amp-social-share type="facebook" data-param-text="Hello world" data-param-href="https://example.com/?ref=URL" data-param-app_id="145634995501895"></amp-social-share> <amp-social-share type="twitter"></amp-social-share> </div> </div> </div> </amp-live-list></body></html>`; } function getLiveBlogItemWithBindAttributes() { var now = Date.now(); // Generate a 3 to 7 worded headline var headline = bacon(range(3, 7)); var numOfParagraphs = range(1, 2); var body = Array.apply(null, Array(numOfParagraphs)).map(x => { return `<p>${bacon(range(50, 90))}</p>`; }).join('\n'); return `<!doctype html> <html amp><body> <amp-live-list id="live-blog-1"> <div items> <div id="live-blog-item-${now}" data-sort-time="${now}"> <div class="article-body"> ${body} <p> As you can see, bacon is far superior to <b><span [text]='favoriteFood'>everything!</span></b>!</p> </div> </div> </div> </amp-live-list></body></html>`; } app.use('/examples/live-blog(-non-floating-button)?.amp.(min.|max.)?html', function(req, res, next) { if ('amp_latest_update_time' in req.query) { res.setHeader('Content-Type', 'text/html'); res.end(getLiveBlogItem()); return; } next(); }); app.use('/examples/bind/live-list.amp.(min.|max.)?html', function(req, res, next) { if ('amp_latest_update_time' in req.query) { res.setHeader('Content-Type', 'text/html'); res.end(getLiveBlogItemWithBindAttributes()); return; } next(); }); app.use('/examples/amp-fresh.amp.(min.|max.)?html', function(req, res, next) { if ('amp-fresh' in req.query && req.query['amp-fresh']) { res.setHeader('Content-Type', 'text/html'); res.end(`<!doctype html> <html ⚡> <body> <amp-fresh id="amp-fresh-1"><span>hello</span> world!</amp-fresh> <amp-fresh id="amp-fresh-2">foo bar</amp-fresh> </body> </html>`); return; } next(); }); app.use('/impression-proxy/', function(req, res) { assertCors(req, res, ['GET']); // Fake response with the following optional fields: // location: The Url the that server would have sent redirect to w/o ALP // tracking_url: URL that should be requested to track click // gclid: The conversion tracking value const body = { 'location': 'localhost:8000/examples/?gclid=1234&foo=bar&example=123', 'tracking_url': 'tracking_url', 'gclid': '1234', }; res.send(body); }); // Proxy with unminified JS. // Example: // http://localhost:8000/max/s/www.washingtonpost.com/amphtml/news/post-politics/wp/2016/02/21/bernie-sanders-says-lower-turnout-contributed-to-his-nevada-loss-to-hillary-clinton/ app.use('/max/', function(req, res) { proxyToAmpProxy(req, res, /* minify */ false); }); // Proxy with minified JS. // Example: // http://localhost:8000/min/s/www.washingtonpost.com/amphtml/news/post-politics/wp/2016/02/21/bernie-sanders-says-lower-turnout-contributed-to-his-nevada-loss-to-hillary-clinton/ app.use('/min/', function(req, res) { proxyToAmpProxy(req, res, /* minify */ true); }); // Nest the response in an iframe. // Example: // http://localhost:8000/iframe/examples/ads.amp.max.html app.get('/iframe/*', function(req, res) { // Returns an html blob with an iframe pointing to the url after /iframe/. res.send(`<!doctype html> <html style="width:100%; height:100%;"> <body style="width:98%; height:98%;"> <iframe src="${req.url.substr(7)}" style="width:100%; height:100%;"> </iframe> </body> </html>`); }); // Returns a document that echoes any post messages received from parent. // An optional `message` query param can be appended for an initial post // message sent on document load. // Example: // http://localhost:8000/iframe-echo-message?message=${payload} app.get('/iframe-echo-message', function(req, res) { const message = req.query.message; res.send( `<!doctype html> <body style="background-color: yellow"> <script> if (${message}) { echoMessage(${message}); } window.addEventListener('message', function(event) { echoMessage(event.data); }); function echoMessage(message) { parent.postMessage(message, '*'); } </script> </body> </html>`); }); // A4A envelope. // Examples: // http://localhost:8000/a4a[-3p]/examples/animations.amp.max.html // http://localhost:8000/a4a[-3p]/max/s/www.washingtonpost.com/amphtml/news/post-politics/wp/2016/02/21/bernie-sanders-says-lower-turnout-contributed-to-his-nevada-loss-to-hillary-clinton/ // http://localhost:8000/a4a[-3p]/min/s/www.washingtonpost.com/amphtml/news/post-politics/wp/2016/02/21/bernie-sanders-says-lower-turnout-contributed-to-his-nevada-loss-to-hillary-clinton/ app.use('/a4a(|-3p)/', function(req, res) { var force3p = req.baseUrl.indexOf('/a4a-3p') == 0; var adUrl = req.url; var templatePath = '/build-system/server-a4a-template.html'; var urlPrefix = getUrlPrefix(req); if (!adUrl.startsWith('/m') && urlPrefix.indexOf('//localhost') != -1) { // This is a special case for testing. `localhost` URLs are transformed to // `ads.localhost` to ensure that the iframe is fully x-origin. adUrl = urlPrefix.replace('localhost', 'ads.localhost') + adUrl; } adUrl = addQueryParam(adUrl, 'inabox', 1); fs.readFileAsync(process.cwd() + templatePath, 'utf8').then(template => { var result = template .replace(/FORCE3P/g, force3p) .replace(/DISABLE3PFALLBACK/g, !force3p) .replace(/OFFSET/g, req.query.offset || '0px') .replace(/AD_URL/g, adUrl) .replace(/AD_WIDTH/g, req.query.width || '300') .replace(/AD_HEIGHT/g, req.query.height || '250'); res.end(result); }); }); // In-a-box envelope. // Examples: // http://localhost:8000/inabox/examples/animations.amp.max.html // http://localhost:8000/inabox/max/s/www.washingtonpost.com/amphtml/news/post-politics/wp/2016/02/21/bernie-sanders-says-lower-turnout-contributed-to-his-nevada-loss-to-hillary-clinton/ // http://localhost:8000/inabox/min/s/www.washingtonpost.com/amphtml/news/post-politics/wp/2016/02/21/bernie-sanders-says-lower-turnout-contributed-to-his-nevada-loss-to-hillary-clinton/ app.use('/inabox/', function(req, res) { var adUrl = req.url; var templatePath = '/build-system/server-inabox-template.html'; var urlPrefix = getUrlPrefix(req); if (!adUrl.startsWith('/m') && // Ignore /min and /max urlPrefix.indexOf('//localhost') != -1) { // This is a special case for testing. `localhost` URLs are transformed to // `ads.localhost` to ensure that the iframe is fully x-origin. adUrl = urlPrefix.replace('localhost', 'ads.localhost') + adUrl; } adUrl = addQueryParam(adUrl, 'inabox', 1); fs.readFileAsync(process.cwd() + templatePath, 'utf8').then(template => { var result = template .replace(/AD_URL/g, adUrl) .replace(/OFFSET/g, req.query.offset || '0px') .replace(/AD_WIDTH/g, req.query.width || '300') .replace(/AD_HEIGHT/g, req.query.height || '250'); res.end(result); }); }); app.use('/examples/analytics.config.json', function(req, res, next) { res.setHeader('AMP-Access-Control-Allow-Source-Origin', getUrlPrefix(req)); next(); }); app.use(['/examples/*', '/extensions/*'], function (req, res, next) { var sourceOrigin = req.query['__amp_source_origin']; if (sourceOrigin) { res.setHeader('AMP-Access-Control-Allow-Source-Origin', sourceOrigin); } next(); }); /** * Append ?sleep=5 to any included JS file in examples to emulate delay in loading that * file. This allows you to test issues with your extension being late to load * and testing user interaction with your element before your code loads. * * Example delay loading amp-form script by 5 seconds: * <script async custom-element="amp-form" * src="https://cdn.ampproject.org/v0/amp-form-0.1.js?sleep=5"></script> */ app.use(['/dist/v0/amp-*.js'], function(req, res, next) { var sleep = parseInt(req.query.sleep || 0) * 1000; setTimeout(next, sleep); }); app.get(['/examples/*', '/test/manual/*'], function(req, res, next) { var filePath = req.path; var mode = getPathMode(filePath); if (!mode) { return next(); } const inabox = req.query['inabox'] == '1'; filePath = filePath.substr(0, filePath.length - 9) + '.html'; fs.readFileAsync(process.cwd() + filePath, 'utf8').then(file => { if (req.query['amp_js_v']) { file = addViewerIntegrationScript(req.query['amp_js_v'], file); } file = replaceUrls(mode, file, '', inabox); if (inabox && req.headers.origin && req.query.__amp_source_origin) { // Allow CORS requests for A4A. enableCors(req, res, req.headers.origin); } // Extract amp-ad for the given 'type' specified in URL query. if (req.path.indexOf('/examples/ads.amp') == 0 && req.query.type) { var ads = file.match(new RegExp('<(amp-ad|amp-embed) [^>]*[\'"]' + req.query.type + '[\'"][^>]*>([\\s\\S]+?)<\/(amp-ad|amp-embed)>', 'gm')); file = file.replace( /<body>[\s\S]+<\/body>/m, '<body>' + ads.join('') + '</body>'); } res.send(file); }).catch(() => { next(); }); }); // Data for example: http://localhost:8000/examples/bind/xhr.amp.max.html app.use('/bind/form/get', function(req, res, next) { assertCors(req, res, ['GET']); res.json({ bindXhrResult: 'I was fetched from the server!' }); }); // Data for example: http://localhost:8000/examples/bind/ecommerce.amp.max.html app.use('/bind/ecommerce/sizes', function(req, res, next) { assertCors(req, res, ['GET']); setTimeout(() => { var prices = { "0": { "sizes": ["XS"] }, "1": { "sizes": ["S", "M", "L"] }, "2": { "sizes": ["XL"] }, "3": { "sizes": ["M", "XL"] }, "4": { "sizes": ["S", "L"] }, "5": { "sizes": ["S", "XL"] }, "6": { "sizes": ["XS", "M"] }, "7": { "sizes": ["M", "L", "XL"] }, "8": { "sizes": ["XS", "M", "XL"] } }; const object = {}; object[req.query.shirt] = prices[req.query.shirt]; res.json(object); }, 1000); // Simulate network delay. }); app.use('/list/fruit-data/get', function(req, res, next) { assertCors(req, res, ['GET']); res.json({ items: [ {name: 'apple', quantity: 47, unitPrice: '0.33'}, {name: 'pear', quantity: 538, unitPrice: '0.54'}, {name: 'tomato', quantity: 0, unitPrice: '0.23'}, ], }); }); app.use('/list/vegetable-data/get', function(req, res, next) { assertCors(req, res, ['GET']); res.json({ items: [ {name: 'cabbage', quantity: 5, unitPrice: '1.05'}, {name: 'carrot', quantity: 10, unitPrice: '0.01'}, {name: 'brocoli', quantity: 7, unitPrice: '0.02'}, ], }); }); // Simulated Cloudflare signed Ad server const cloudflareDataDir = '/extensions/amp-ad-network-cloudflare-impl/0.1/data'; const fakeAdNetworkDataDir = '/extensions/amp-ad-network-fake-impl/0.1/data' /** * Handle CORS headers */ app.use([cloudflareDataDir], function fakeCors(req, res, next) { assertCors(req, res, ['GET', 'OPTIONS'], ['X-AmpAdSignature']); if (req.method=='OPTIONS') { res.status(204).end(); } else { next(); } }); /** * Handle fake a4a data */ app.get([ fakeAdNetworkDataDir + '/*', cloudflareDataDir + '/*'], function(req, res) { var filePath = req.path; var unwrap = false; if (req.path.endsWith('.html')) { filePath = req.path.slice(0,-5) unwrap = true } filePath = process.cwd() + filePath fs.readFileAsync(filePath).then(file => { if (!unwrap) { res.end(file) return } const metadata = JSON.parse(file); res.setHeader('Content-Type', 'text/html'); res.setHeader('X-AmpAdSignature', metadata.signature); res.end(metadata.creative); }).error( () => { res.status(404); res.end("Not found: " + filePath); }); }); /* * Start Cache SW LOCALDEV section */ app.get(['/dist/sw.js', '/dist/sw.max.js'], function(req, res, next) { var filePath = req.path; fs.readFileAsync(process.cwd() + filePath, 'utf8').then(file => { var n = new Date(); // Round down to the nearest 5 minutes. n -= ((n.getMinutes() % 5) * 1000 * 60) + (n.getSeconds() * 1000) + n.getMilliseconds(); file = 'self.AMP_CONFIG = {v: "99' + n + '",' + 'cdnUrl: "http://localhost:8000/dist"};' + file; res.setHeader('Content-Type', 'application/javascript'); res.setHeader('Date', new Date().toUTCString()); res.setHeader('Cache-Control', 'no-cache;max-age=150'); res.end(file); }).catch(next); }); app.get('/dist/rtv/9[89]*/*.js', function(req, res, next) { res.setHeader('Content-Type', 'application/javascript'); res.setHeader('Date', new Date().toUTCString()); res.setHeader('Cache-Control', 'no-cache;max-age=31536000'); setTimeout(() => { // Cause a delay, to show the "stale-while-revalidate" if (req.path.includes('v0.js')) { var path = req.path.replace(/rtv\/\d+/, ''); return fs.readFileAsync(process.cwd() + path, 'utf8') .then(file => { res.end(file); }).catch(next); } res.end(` var li = document.createElement('li'); li.textContent = '${req.path}'; loaded.appendChild(li); `); }, 2000); }); app.get(['/dist/cache-sw.min.html', '/dist/cache-sw.max.html'], function(req, res, next) { var filePath = '/test/manual/cache-sw.html'; fs.readFileAsync(process.cwd() + filePath, 'utf8').then(file => { var n = new Date(); // Round down to the nearest 5 minutes. n -= ((n.getMinutes() % 5) * 1000 * 60) + (n.getSeconds() * 1000) + n.getMilliseconds(); var percent = parseFloat(req.query.canary) || 0.01; var env = '99'; if (Math.random() < percent) { env = '98'; n += 5 * 1000 * 60; } file = file.replace(/dist\/v0/g, `dist/rtv/${env}${n}/v0`); file = file.replace(/CURRENT_RTV/, env + n); res.setHeader('Content-Type', 'text/html'); res.end(file); }).catch(next); }); app.get('/dist/diversions', function(req, res, next) { var n = new Date(); // Round down to the nearest 5 minutes. n -= ((n.getMinutes() % 5) * 1000 * 60) + (n.getSeconds() * 1000) + n.getMilliseconds(); n += 5 * 1000 * 60; res.setHeader('Content-Type', 'application/json'); res.setHeader('Date', new Date().toUTCString()); res.setHeader('Cache-Control', 'no-cache;max-age=150'); res.end(JSON.stringify(["98" + n])); }); /* * End Cache SW LOCALDEV section */ /** * Web worker binary. */ app.get(['/dist/ww.js', '/dist/ww.max.js'], function(req, res) { fs.readFileAsync(process.cwd() + req.path).then(file => { res.setHeader('Content-Type', 'text/javascript'); res.setHeader('Access-Control-Allow-Origin', '*'); res.end(file); }); }); /** * @param {string} mode * @param {string} file * @param {string=} hostName * @param {boolean=} inabox */ function replaceUrls(mode, file, hostName, inabox) { hostName = hostName || ''; if (mode == 'max') { file = file.replace('https://cdn.ampproject.org/v0.js', hostName + '/dist/amp.js'); file = file.replace('https://cdn.ampproject.org/amp4ads-v0.js', hostName + '/dist/amp-inabox.js'); file = file.replace(/https:\/\/cdn.ampproject.org\/v0\/(.+?).js/g, hostName + '/dist/v0/$1.max.js'); if (inabox) { file = file.replace('/dist/amp.js', '/dist/amp-inabox.js'); } } else if (mode == 'min') { file = file.replace('https://cdn.ampproject.org/v0.js', hostName + '/dist/v0.js'); file = file.replace('https://cdn.ampproject.org/amp4ads-v0.js', hostName + '/dist/amp4ads-v0.js'); file = file.replace(/https:\/\/cdn.ampproject.org\/v0\/(.+?).js/g, hostName + '/dist/v0/$1.js'); file = file.replace(/\/dist.3p\/current\/(.*)\.max.html/, hostName + '/dist.3p/current-min/$1.html'); if (inabox) { file = file.replace('/dist/v0.js', '/dist/amp4ads-v0.js'); } } return file; } /** * @param {string} ampJsVersion * @param {string} file */ function addViewerIntegrationScript(ampJsVersion, file) { ampJsVersion = parseFloat(ampJsVersion); if (!ampJsVersion) { return file; } var viewerScript; if (Number.isInteger(ampJsVersion)) { // Viewer integration script from gws, such as // https://cdn.ampproject.org/viewer/google/v7.js viewerScript = '<script async src="https://cdn.ampproject.org/viewer/google/v' + ampJsVersion + '.js"></script>'; } else { // Viewer integration script from runtime, such as // https://cdn.ampproject.org/v0/amp-viewer-integration-0.1.js viewerScript = '<script async src="https://cdn.ampproject.org/v0/amp-viewer-integration-' + ampJsVersion + '.js" data-amp-report-test="viewer-integr.js"></script>'; } file = file.replace('</head>', viewerScript + '</head>'); return file; } /** * @param {string} path * @return {string} */ function extractFilePathSuffix(path) { return path.substr(-9); } /** * @param {string} path * @return {?string} */ function getPathMode(path) { var suffix = extractFilePathSuffix(path); if (suffix == '.max.html') { return 'max'; } else if (suffix == '.min.html') { return 'min'; } else { return null; } } function getUrlPrefix(req) { return req.protocol + '://' + req.headers.host; } /** * @param {string} url * @param {string} param * @param {*} value * @return {string} */ function addQueryParam(url, param, value) { const paramValue = encodeURIComponent(param) + '=' + encodeURIComponent(value); if (!url.includes('?')) { url += '?' + paramValue; } else { url += '&' + paramValue; } return url; } function enableCors(req, res, origin, opt_exposeHeaders) { res.setHeader('Access-Control-Allow-Credentials', 'true'); res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Access-Control-Expose-Headers', ['AMP-Access-Control-Allow-Source-Origin'] .concat(opt_exposeHeaders || []).join(', ')); res.setHeader('AMP-Access-Control-Allow-Source-Origin', req.query.__amp_source_origin); } function assertCors(req, res, opt_validMethods, opt_exposeHeaders) { const validMethods = opt_validMethods || ['GET', 'POST', 'OPTIONS']; const invalidMethod = req.method + ' method is not allowed. Use POST.'; const invalidOrigin = 'Origin header is invalid.'; const invalidSourceOrigin = '__amp_source_origin parameter is invalid.'; const unauthorized = 'Unauthorized Request'; var origin; if (validMethods.indexOf(req.method) == -1) { res.statusCode = 405; res.end(JSON.stringify({message: invalidMethod})); throw invalidMethod; } if (req.headers.origin) { origin = req.headers.origin; if (!ORIGIN_REGEX.test(req.headers.origin)) { res.statusCode = 500; res.end(JSON.stringify({message: invalidOrigin})); throw invalidOrigin; } if (!SOURCE_ORIGIN_REGEX.test(req.query.__amp_source_origin)) { res.statusCode = 500; res.end(JSON.stringify({message: invalidSourceOrigin})); throw invalidSourceOrigin; } } else if (req.headers['amp-same-origin'] == 'true') { origin = getUrlPrefix(req); } else { res.statusCode = 401; res.end(JSON.stringify({message: unauthorized})); throw unauthorized; } enableCors(req, res, origin, opt_exposeHeaders); } module.exports = app;
lzanol/amphtml
build-system/app.js
JavaScript
apache-2.0
31,997
/** * Created by jan on 20/10/14. */ function AccountManager() { } AccountManager.prototype.generateAmount = function () { var s1 = Math.floor(Math.random() * 7) % 10; var s2 = Math.floor(Math.random() * 7) % 10; var s3 = Math.floor(Math.random() * 7) % 10; var sum = s1 * 1000 + s2 * 100 + s3 * 10; return sum; } AccountManager.prototype.generateAccount = function (accounts) { var owners = (function (a) { var o = []; for (var i = 0; i < a.length; i++) { o[i] = a[i].getOwner(); } return o; }); var _owners = function () { return owners(accounts()) }; var owner = (new OwnerGenerator(_owners)).generateOwner(); var account = new Account(owner, this.generateAmount()); (accounts())[accounts().length] = account; return account; } AccountManager.prototype.donateRandomToAllAccounts = function (accounts) { var allAccounts = accounts(); for (var i = 0; i < allAccounts.length; i++) { //We will donate only to active accounts if (allAccounts[i].isActive()) allAccounts[i].add(this.generateAmount()); } }
janpalencar/g-transaction
js/AccountManager.js
JavaScript
apache-2.0
1,157
// increment the number below each time you push a new model version // (forces rebuild on phone) var current_migration_version = 1; // create the tables if required joli.models.migrate(current_migration_version); joli.models.initialize();
xavierlacot/xavccMobileApp
Resources/js/lib/install.js
JavaScript
apache-2.0
241
import { newRxTypeError, newRxError } from '../../rx-error'; import { getPreviousVersions } from '../../rx-schema'; /** * checks if the migrationStrategies are ok, throws if not * @throws {Error|TypeError} if not ok */ export function checkMigrationStrategies(schema, migrationStrategies) { // migrationStrategies must be object not array if (typeof migrationStrategies !== 'object' || Array.isArray(migrationStrategies)) { throw newRxTypeError('COL11', { schema: schema }); } var previousVersions = getPreviousVersions(schema); // for every previousVersion there must be strategy if (previousVersions.length !== Object.keys(migrationStrategies).length) { throw newRxError('COL12', { have: Object.keys(migrationStrategies), should: previousVersions }); } // every strategy must have number as property and be a function previousVersions.map(function (vNr) { return { v: vNr, s: migrationStrategies[vNr + 1] }; }).filter(function (strat) { return typeof strat.s !== 'function'; }).forEach(function (strat) { throw newRxTypeError('COL13', { version: strat.v, type: typeof strat, schema: schema }); }); return true; } //# sourceMappingURL=check-migration-strategies.js.map
pubkey/rxdb
dist/es/plugins/dev-mode/check-migration-strategies.js
JavaScript
apache-2.0
1,283
Template.favoritesPages.onCreated(function () { var template = this; template.subscribe('FavoritesPages'); }); Template.favoritesPages.helpers({ favoritesPages: function () { if (Meteor.userId()) { return Pages.find( { $or: [{ isPublic: true }, { owners: Meteor.userId() }, { users: Meteor.userId() }], favorites: Meteor.userId() }, { sort: { updatedAt: -1 } } ); } } }); Template.favoritesPages.events({ }); Template.favoritesPages.onRendered(function () { });
guidouil/gotlogin
client/favoritesPages/favoritesPages_script.js
JavaScript
apache-2.0
509
'use strict'; /** * Expose 'NetworkTask' */ module.exports = NetworkTask; /** * Module dependencies */ var networkObject = require('./network-object'); var readLine = require('readline'); var childProcess = require('child_process'); /** * Constants */ var NETWORK_TOPIC = 'monitor/network'; /** * Constructor * Initialize a new NetworkTask */ function NetworkTask(info){ this.noInstance = null; this.generalInfo = info; } /** * Class Methods */ NetworkTask.prototype.runAndParse = function(callback){ if(this.generalInfo){ //run the command, parse the command, return a result console.log('running network command'); //make sure this is a new instance everytime this.noInstance = new networkObject(this.generalInfo.thingId); //lets run ifconfig to get mac address and ip if(this.generalInfo.os === 'darwin'){ var res = getNetworkInterfacesMac(); if(res){ this.noInstance.nInterface=res.iname; this.noInstance.ipAddress=res.ip; this.noInstance.macAddress=res.mac; } } else if(this.generalInfo.os === 'linux'){ var res = getNetworkInterfacesLinux(); if(res){ this.noInstance.nInterface=res.iname; this.noInstance.ipAddress=res.ip; this.noInstance.macAddress=res.mac; } } else{ console.log('not implemented'); } //create the child process to execute $ iftop -t -s 2 -P -N //must run as ROOT on ubuntu side //add the interface - from the active network var commandLine = childProcess.spawn('iftop', ['-t','-s','3','-P','-N','-b','-B','-i',this.noInstance.nInterface]); var noPass = this.noInstance; var lineReader = readLine.createInterface(commandLine.stdout, commandLine.stdin); lineReader.on('line', function(line){ noPass.read(line); }); commandLine.on('close', function(code, signal){ //console.log('read ' + noPass.counter + ' lines'); callback(NETWORK_TOPIC, noPass); }); } else{ //skipping execution console.log('skipping network task due to missing general information'); } } /** * Helper Methods */ // get all available network interfaces for mac // return an object with {iname, ip, mac, status} function getNetworkInterfacesMac(){ var result={}; var availableInterfaces=[]; var returnObject = childProcess.spawnSync('ifconfig', ['-a']); if(returnObject.stdout){ var displayStr = returnObject.stdout.toString().trim().toLowerCase(); if(displayStr){ var ifSplit = displayStr.split('\n'); if(ifSplit){ //declare a point array var currInterface={}; for(var i=0; i<ifSplit.length; i++){ var temp = ifSplit[i].reduceWhiteSpace().trim(); //search for the first line of each if(temp.indexOf('flags=')>=0){ if(currInterface.iname){ //lets save this interface availableInterfaces.push(currInterface); } //this is the first line var interfaceSplit = temp.split(':'); if(interfaceSplit.length == 2){ //lets get the name var iName = interfaceSplit[0]; //create a new interface and point current to this one var tempInterface = {}; tempInterface.iname=iName; currInterface = tempInterface; } } else{ //this is a regular line //search for ether - which contains the mac address //search for inet which should contain the ip address //search for status, which indicates status //space is important here to diffrentiate between inet6 if(temp.indexOf('inet ') >=0){ var ipSplit = temp.split(' '); if(ipSplit.length >= 4){ currInterface.ip=ipSplit[1].trim(); } } if(temp.indexOf('ether')>=0){ var macSplit = temp.split(' '); if(macSplit.length >= 2){ currInterface.mac=macSplit[1].trim(); } } //we'll use a different algo on mac osx since //it actually returns the current if(temp.indexOf('status')>=0){ var statusSplit = temp.split(':'); if(statusSplit.length >= 2){ currInterface.status=statusSplit[1].trim(); } } } } //lets save the last interface if(currInterface.iname){ availableInterfaces.push(currInterface); } } } } if(availableInterfaces.length > 0){ for(var j=0; j<availableInterfaces.length; j++){ var tRes = availableInterfaces[j]; if(tRes){ //we still have a possibility of seeing 2 interfaces available if(tRes.status==='active' && tRes.ip && tRes.mac){ result=tRes; return result; } } } } return result; } function getNetworkInterfacesLinux(){ var result={}; var availableInterfaces=[]; var returnObject = childProcess.spawnSync('ifconfig', ['-a']); if(returnObject.stdout){ var displayStr = returnObject.stdout.toString().trim().toLowerCase(); if(displayStr){ var ifSplit = displayStr.split('\n'); if(ifSplit){ //declare a point array var currInterface={}; for(var i=0; i<ifSplit.length; i++){ var temp = ifSplit[i].reduceWhiteSpace().trim(); //search for the first line of each if(temp.indexOf('link encap')>=0){ if(currInterface.iname){ //lets save this interface availableInterfaces.push(currInterface); } //this is the first line var interfaceSplit = temp.split('link encap:'); if(interfaceSplit.length == 2){ //lets get the name var iName = interfaceSplit[0].trim(); var macAddr=''; //lets get the macaddr var macSplit = interfaceSplit[1].trim().split(' '); if(macSplit.length==3){ macAddr = macSplit[2]; } //create a new interface and point current to this one var tempInterface = {}; tempInterface.iname=iName; if(macAddr){ tempInterface.mac=macAddr; } currInterface = tempInterface; } } else{ //this is a regular line //search for ether - which contains the mac address //search for inet which should contain the ip address //search for status, which indicates status //space is important here to diffrentiate between inet6 if(temp.indexOf('inet addr:') >=0){ var ipBlockSplit = temp.split(' '); if(ipBlockSplit.length >= 2){ //take the second entry var ipSplit=ipBlockSplit[1].split(':'); if(ipSplit.length >= 2){ currInterface.ip=ipSplit[1].trim(); //if both ip and mac exist if(currInterface.mac){ currInterface.status='active'; } } } } } } //lets save the last interface if(currInterface.iname){ availableInterfaces.push(currInterface); } } } } //currently only returns the first active link - if there are multiple //interfaces active, we will probably need to handle multiple if(availableInterfaces.length > 0){ for(var j=0; j<availableInterfaces.length; j++){ var tRes = availableInterfaces[j]; if(tRes){ if(tRes.status==='active'){ result=tRes; } } } } return result; }
ArrowElectronics/aws-iot-dragonpulse-js
DragonBoard/src/lib/network/network-task.js
JavaScript
apache-2.0
7,159
'use strict'; /** * @ngdoc object * @name activityApp * @requires $routeProvider * @requires activityControllers * @requires ui.bootstrap * * @description * Root app, which routes and specifies the partial html and controller depending on the url requested. * */ var app = angular.module('activityApp', ['activityControllers', 'ngRoute', 'ui.bootstrap', 'ui.bootstrap.datetimepicker']). config(['$routeProvider', function ($routeProvider) { $routeProvider. when('/activity', { templateUrl: '/partials/show_activities.html', controller: 'ShowActivityCtrl' }). when('/activity/create', { templateUrl: '/partials/create_activities.html', controller: 'CreateActivityCtrl' }). when('/activity/detail/:websafeActivityKey', { templateUrl: '/partials/activity_detail.html', controller: 'ActivityDetailCtrl' }). when('/profile', { templateUrl: '/partials/profile.html', controller: 'MyProfileCtrl' }). when('/', { templateUrl: '/partials/home.html' }). otherwise({ redirectTo: '/' }); }]); /** * @ngdoc filter * @name startFrom * * @description * A filter that extracts an array from the specific index. * */ app.filter('startFrom', function () { /** * Extracts an array from the specific index. * * @param {Array} data * @param {Integer} start * @returns {Array|*} */ var filter = function (data, start) { return data.slice(start); } return filter; }); /** * @ngdoc constant * @name HTTP_ERRORS * * @description * Holds the constants that represent HTTP error codes. * */ app.constant('HTTP_ERRORS', { 'UNAUTHORIZED': 401 }); /** * @ngdoc service * @name oauth2Provider * * @description * Service that holds the OAuth2 information shared across all the pages. * */ app.factory('oauth2Provider', function ($modal) { var oauth2Provider = { CLIENT_ID: '411586073540-cq6ialm9aojdtjts6f12bb68up7k04t1.apps.googleusercontent.com', SCOPES: 'https://www.googleapis.com/auth/userinfo.email profile', signedIn: false }; /** * Calls the OAuth2 authentication method. */ oauth2Provider.signIn = function (callback) { gapi.auth.signIn({ 'clientid': oauth2Provider.CLIENT_ID, 'cookiepolicy': 'single_host_origin', 'accesstype': 'online', 'approveprompt': 'auto', 'scope': oauth2Provider.SCOPES, 'callback': callback }); }; /** * Logs out the user. */ oauth2Provider.signOut = function () { gapi.auth.signOut(); // Explicitly set the invalid access token in order to make the API calls fail. gapi.auth.setToken({access_token: ''}); oauth2Provider.signedIn = false; }; /** * Shows the modal with Google+ sign in button. * * @returns {*|Window} */ oauth2Provider.showLoginModal = function() { var modalInstance = $modal.open({ templateUrl: '/partials/login.modal.html', controller: 'OAuth2LoginModalCtrl' }); return modalInstance; }; return oauth2Provider; });
du6/yourlittleone
src/main/webapp/js/app.js
JavaScript
apache-2.0
3,544