_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q60600
titleCase
validation
function titleCase (s) { var arr = []; libs.object.each(s.split(' '), function (t) { arr.push(libs.string.ucFirst(t)); }); return arr.join(' '); }
javascript
{ "resource": "" }
q60601
splice
validation
function splice (s, index, count, add) { return s.slice(0, index) + (add || '') + s.slice(index + count); }
javascript
{ "resource": "" }
q60602
ellipses_
validation
function ellipses_ (s, length, place, ellipses) { if(isNaN(parseInt(length, 10))) length = s.length; if(length < 0 || !isFinite(length)) length = 0; ellipses = typeof ellipses === 'string' ? ellipses : '...'; if(s.length <= length) return s; if(length <= ellipses.length) { return ellipses.substring(0, length); } else if(!place || place !== 'front') { return s.substr(0, length - ellipses.length) + ellipses; } else { return ellipses + s.substr(0, length - ellipses.length); } }
javascript
{ "resource": "" }
q60603
shuffle
validation
function shuffle (s, splitter) { var a = s.split(typeof splitter === 'string' ? splitter : ''), n = a.length, replaceSplits = n - 1; for(var i = n - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)), tmp = a[i]; a[i] = a[j]; a[j] = tmp; } for(var k = 0; k < replaceSplits; k++) a.splice(libs.number.randomIntInRange(0, a.length), 0, splitter); return a.join(''); }
javascript
{ "resource": "" }
q60604
reverse
validation
function reverse (s) { if(s.length < 64) { var str = ''; for(var i = s.length; i >= 0; i--) str += s.charAt(i); return str; } else { return s.split('').reverse().join(''); } }
javascript
{ "resource": "" }
q60605
withoutTrailingSlash
validation
function withoutTrailingSlash (s) { if(!IS_BROWSER && HAS_OS && require('os').platform === 'win32') return s.replace(/\\+$/, ''); return s.replace(/\/+$/, ''); }
javascript
{ "resource": "" }
q60606
pad
validation
function pad (s, length, delim, pre) { var i, thisLength = s.length; if(!delim) delim = ' '; if(length === 0) return ''; else if(isNaN(parseInt(length, 10))) return s; length = parseInt(length, 10); if(length < thisLength) return !pre ? s.slice(0, length) : s.slice(-length); if(pre) { for(i = 0; i < length - thisLength; i++) s = delim + s; } else { for(i = 0; i < length - thisLength; i++) s += delim; } return s; }
javascript
{ "resource": "" }
q60607
wordWrapToLength
validation
function wordWrapToLength (s, width, padleft, padright, omitFirst) { if(padright === undefined && padleft) padright = padleft; padleft = !isNaN(parseInt(padleft, 10)) ? parseInt(padleft, 10) : 0; padright = !isNaN(parseInt(padright, 10)) ? parseInt(padright, 10) : 0; var paddingLeft = ''; for(var n = 0; n < padleft; n++) paddingLeft += ' '; var cols = !isNaN(parseInt(width, 10)) ? length : 120, arr = s.split(' '), item = null, len = !omitFirst ? cols - padright - padleft : cols - padright, str = !omitFirst ? paddingLeft : '', olen = cols - padright - padleft; while((item = arr.shift()) !== undefined) { if(item.length < len) { str += item + ' '; len -= item.length + 1; } else if(item.length > olen) { str += item.substring(0, len - 1) + '-\n' + paddingLeft; arr.unshift(item.substring(len, item.length - 1)); len = cols - padright - padleft; } else { str += '\n' + paddingLeft + item + ' '; len = cols - padright - 1 - padleft - item.length; } } return str; }
javascript
{ "resource": "" }
q60608
advanceDays
validation
function advanceDays (d, daysInTheFuture, adjustForWeekend) { if(!(d instanceof Date)) return d; daysInTheFuture = daysInTheFuture && libs.generic.isNumeric(daysInTheFuture) ? daysInTheFuture : 1; d.setTime(d.getTime() + (daysInTheFuture * 86400000)); if(adjustForWeekend && (d.getDay() === 0 || d.getDay() === 6)) { while(d.getDay() === 0 || d.getDay() === 6) d.setTime(d.getTime() + 86400000); } return d; }
javascript
{ "resource": "" }
q60609
advanceMonths
validation
function advanceMonths (d, monthsInTheFuture, adjustForWeekend) { if(!(d instanceof Date)) return d; monthsInTheFuture = monthsInTheFuture && libs.generic.isNumeric(monthsInTheFuture) ? monthsInTheFuture : 1; d.setTime(d.getTime() + (monthsInTheFuture * 2629746000)); if(adjustForWeekend && (d.getDay() === 0 || d.getDay() === 6)) { while(d.getDay() === 0 || d.getDay() === 6) d.setTime(d.getTime() + 86400000); } return d; }
javascript
{ "resource": "" }
q60610
advanceYears
validation
function advanceYears (d, yearsInTheFuture, adjustForWeekend) { if(!(d instanceof Date)) return d; yearsInTheFuture = yearsInTheFuture && libs.generic.isNumeric(yearsInTheFuture) ? yearsInTheFuture : 1; d.setTime(d.getTime() + (yearsInTheFuture * 31536000000)); if(adjustForWeekend && (d.getDay() === 0 || d.getDay() === 6)) { while(d.getDay() === 0 || d.getDay() === 6) d.setTime(d.getTime() + 86400000); } return d; }
javascript
{ "resource": "" }
q60611
yyyymmdd
validation
function yyyymmdd (d, delim) { if(!(d instanceof Date)) return d; delim = typeof delim !== 'string' ? '-' : delim ; var dd = d.getDate(), mm = d.getMonth() + 1, yyyy = d.getFullYear(); if(dd < 10) dd = '0' + dd; if(mm < 10) mm = '0' + mm; return yyyy + delim + mm + delim + dd; }
javascript
{ "resource": "" }
q60612
validation
function (n, placeholder) { if(n === undefined || n === null || !libs.object.isNumeric(n)) return n; placeholder = typeof placeholder === 'string' ? placeholder : '.'; var rest, idx, int, ns = n.toString(), neg = n < 0; idx = ns.indexOf('.'); int = parseInt(Math.abs(n), 10).toString(); if(idx > -1) rest = '.' + ns.substring(idx + 1, ns.length); return (neg ? '-' : '') + libs.string.reverse(libs.string.reverse(int).replace(/(\d{3})(?!$)/g, '$1,')) + (rest || ''); }
javascript
{ "resource": "" }
q60613
validation
function (n, symbol) { if(n === undefined || n === null || !libs.object.isNumeric(n)) return n; n = libs.object.getNumeric(n).toFixed(2); symbol = typeof symbol === 'string' ? symbol : '$'; return n.replace(/^(-)?(\d+)\.(\d+)$/, function ($0, $1, $2, $3) { $1 = $2 === '0' && $3 === '00' ? null : $1; return ($1 || '') + symbol + libs.number.withPlaceholders($2) + '.' + $3; }); }
javascript
{ "resource": "" }
q60614
factorial
validation
function factorial (n) { if(typeof n !== 'number' || n < 0) return NaN; if(n > 170) return Infinity; if(n === 0 || n === 1) return 1; return n * factorial(n - 1); }
javascript
{ "resource": "" }
q60615
isInt
validation
function isInt () { return libs.object.every(arguments, function (n) { return typeof n === 'number' && n % 1 === 0 && n.toString().indexOf('.') === -1; }); }
javascript
{ "resource": "" }
q60616
choose
validation
function choose (n, k) { if(typeof n !== 'number' || typeof k !== 'number') return NaN; if(k === 0) return 1; return (n * choose(n - 1, k - 1)) / k; }
javascript
{ "resource": "" }
q60617
pad
validation
function pad (n, length) { return libs.string.pad(n.toString(), length, '0', true); }
javascript
{ "resource": "" }
q60618
inherits
validation
function inherits (constructor, superConstructor) { if (constructor === undefined || constructor === null) throw new TypeError('The constructor to "inherits" must not be ' + 'null or undefined'); if (superConstructor === undefined || superConstructor === null) throw new TypeError('The super constructor to "inherits" must not ' + 'be null or undefined'); if (superConstructor.prototype === undefined) throw new TypeError('The super constructor to "inherits" must ' + 'have a prototype'); constructor.super_ = superConstructor; Object.setPrototypeOf(constructor.prototype, superConstructor.prototype); // Kill al the ProtoLib cache, for all instances... ProtoLib.killCacheForConstructor(constructor); return constructor; }
javascript
{ "resource": "" }
q60619
union
validation
function union (a) { var args = libs.object.only(libs.object.toArray(arguments), 'array'); var union = []; args.unshift(a); libs.object.each(args, function (array) { libs.object.each(array, function (item) { if(union.indexOf(item) === -1) union.push(item); }); }); return union; }
javascript
{ "resource": "" }
q60620
intersect
validation
function intersect () { var arrays = libs.object.only(libs.object.toArray(arguments), 'array'); if(arrays.length === 0) return []; if(arrays.length === 1) return libs.object.copy(arrays[0]); var intersection = arrays[0], intermediate = []; for(var i = 1; i < arrays.length; i++) { var arr = libs.object.copy(arrays[i]); // Don't want to modify the original array! for(var n = 0; n < intersection.length; n++) { if(arr.indexOf(intersection[n]) > -1) { intermediate.push(intersection[n]); var idx = arr.indexOf(intersection[n]); arr.splice(idx, 1); } } intersection = intermediate; intermediate = []; } return intersection; }
javascript
{ "resource": "" }
q60621
rotateLeft
validation
function rotateLeft (a, amount) { if(!(a instanceof Array)) return a; return libs.array.rotate(a, 'left', amount); }
javascript
{ "resource": "" }
q60622
makeUnique
validation
function makeUnique (a) { if(!(a instanceof Array)) return a; var visited = []; for(var i = 0; i < a.length; i++) { if(visited.indexOf(a[i]) === -1) { visited.push(a[i]); } else { a.splice(i, 1); i--; // Splice will affect the internal array pointer, so fix it... } } return a; }
javascript
{ "resource": "" }
q60623
unique
validation
function unique (a) { if(!(a instanceof Array)) return a; var visited = [], unique = []; libs.object.each(a, function (item) { if(visited.indexOf(item) === -1) { unique.push(item); visited.push(item); } }); return unique; }
javascript
{ "resource": "" }
q60624
ascending
validation
function ascending (a) { if(!(a instanceof Array)) return a; return a.sort(function (a, b) { if(a !== undefined && a !== null) a = a.toString(); if(b !== undefined && b !== null) b = b.toString(); return a < b ? -1 : a > b ? 1 : 0; }); }
javascript
{ "resource": "" }
q60625
descending
validation
function descending (a) { if(!(a instanceof Array)) return a; return a.sort(function (a, b) { if(a !== undefined && a !== null) a = a.toString(); if(b !== undefined && b !== null) b = b.toString(); return a > b ? -1 : a < b ? 1 : 0; }); }
javascript
{ "resource": "" }
q60626
histogram
validation
function histogram () { var histogram = {}; libs.object.every(arguments, function (o) { if(typeof o === 'boolean') { if(!histogram[o]) histogram[o] = 1; else histogram[o]++; } else if(typeof o === 'function') { if(!histogram['function']) histogram['function'] = 1; else histogram[o]++; } else { libs.object.every(o, function (val) { switch(true) { case typeof val === 'function': case typeof val === 'undefined': val = typeof val; break; case typeof val === 'object' && val === null: val = 'null'; break; case typeof val === 'object' && val instanceof Array: val = 'array'; break; case typeof val === 'object': val = 'object'; break; default: val = val.toString(); } if(typeof histogram[val] !== 'number') histogram[val] = 0; histogram[val]++; }); } }); return histogram; }
javascript
{ "resource": "" }
q60627
copy
validation
function copy (item) { var copy; if(!item) return item; switch (typeof item) { case 'string': case 'number': case 'function': case 'boolean': return item; default: if(item instanceof Array) { return item.slice(0); } else { copy = {}; } } libs.object.every(item, function (o, k) { copy[k] = o; }); return copy; }
javascript
{ "resource": "" }
q60628
occurrencesOf
validation
function occurrencesOf (obj, what) { if(arguments.length < 2) return 0; if(typeof obj === 'boolean') { return 0; } if(typeof obj === 'number') { return occurrencesOf(obj.toString(), what); } else if(typeof obj === 'function') { return occurrencesOf(fixFirefoxFunctionString(obj.toString()), what); } var count = 0; if(typeof obj === 'string') { if(typeof what === 'string' || typeof what === 'number') { var regexp = new RegExp(what.toString(), 'g'), m; while(m = regexp.exec(obj)) count++; // jshint ignore:line } } else if(typeof obj !== 'string') { libs.object.every(obj, function (item) { if(item === what) count++; }); } return count; }
javascript
{ "resource": "" }
q60629
keys
validation
function keys (o) { if(o === undefined || o === null) return []; var keys = getKeys(o), idx; if(libs.object.isArguments(o)) { idx = keys.indexOf('length'); if(idx > -1) keys.splice(idx, 1); } return keys; }
javascript
{ "resource": "" }
q60630
isNumeric
validation
function isNumeric () { return libs.object.every(arguments, function (item) { return !isNaN(parseFloat(item)) && isFinite(item); }); }
javascript
{ "resource": "" }
q60631
getNumeric
validation
function getNumeric () { var vals = []; libs.object.every(arguments, function (o) { vals.push(libs.object.isNumeric(o) ? parseFloat(o) : NaN); }); return vals.length === 1 ? vals[0] : vals; }
javascript
{ "resource": "" }
q60632
isArguments
validation
function isArguments () { return libs.object.every(arguments, function (item) { return Object.prototype.toString.call(item) === '[object Arguments]'; }); }
javascript
{ "resource": "" }
q60633
toInt
validation
function toInt () { var vals = []; libs.object.every(arguments, function (o) { var radix = /^0x/.test(o) ? 16 : 10; // Check for hex string vals.push(libs.object.isNumeric(o) ? parseInt(o, radix) : NaN); }); return vals.length === 1 ? vals[0] : vals; }
javascript
{ "resource": "" }
q60634
random
validation
function random (o) { if(typeof o === 'object') { return o instanceof Array ? o[Math.floor(Math.random() * o.length)] : o[Object.keys(o)[Math.floor(Math.random() * Object.keys(o).length)]]; } else if(typeof o === 'string' || typeof o === 'number') { var val = o, negative = false; if(o.length === 0) return ''; if(typeof o === 'number' && o < 0) { negative = true; val = Math.abs(val); } val = val.toString()[Math.floor(Math.random() * val.toString().length)]; if(typeof o === 'number') val = parseInt(val, 10); return negative ? -val : val; } return o; }
javascript
{ "resource": "" }
q60635
any
validation
function any (o, f) { f = f instanceof Function ? f : undefined; if(f instanceof Function) { var self = o, keys, property, value; if(typeof self === 'number' || typeof self === 'function' || typeof self === 'boolean') self = o.toString(); // Firefox does some funky stuff here... if(typeof o === 'function') self = fixFirefoxFunctionString(self); // For Safari... var isArgs = Object.prototype.toString.call(o) === '[object Arguments]', idx = -1; keys = getKeys(self); idx = keys.indexOf('length'); if(isArgs && idx > -1) keys.splice(idx, 1); for(var n = 0; n < keys.length; n++) { property = keys[n]; value = (typeof o === 'number' && !isNaN(parseFloat(self[property]))) ? parseFloat(self[property]) : self[property]; var ret = f.call(o, value, property, n, o); if(ret !== undefined) return ret; } } return undefined; }
javascript
{ "resource": "" }
q60636
first
validation
function first (o, n) { var gotN = (n === 0 ? true : !!n), v; n = parseInt(n, 10); n = isNaN(n) || !isFinite(n) ? 1 : n; if(typeof o === 'boolean') { return o; } else if(typeof o !== 'object') { if(n !== 0) v = o.toString().slice(0, n); else return undefined; } else if(o instanceof Array) { if(n === 1 && !gotN) return o[0]; if(n === 0 && !gotN) return undefined; return n !== 0 ? o.slice(0, n) : []; } else { v = {}; libs.object.each(o, 0, n - 1, function (item, key) { v[key] = item; }); var keys = getKeys(v); if(n === 1 && !gotN && keys.length === 0) return undefined; return keys.length === 1 && !gotN ? v[keys[0]] : v; } return v.length === 1 && !gotN ? v[0] : v; }
javascript
{ "resource": "" }
q60637
last
validation
function last (o, n) { if(typeof o === 'boolean') return o; var gotN = (!!n || n === 0); n = parseInt(n, 10); n = isNaN(n) || !isFinite(n) ? 1 : n; var v = null, keys, len = libs.object.size(o), idx; if(typeof o === 'boolean') { return o; } else if(libs.object.isArguments(o)) { keys = getKeys(o); idx = keys.indexOf('length'); if(idx > -1) keys.splice(idx, 1); v = []; len = keys.length; // Arguments object should ignore undefined members... libs.object.each(keys, 0, len, function (k) { if(o[k] !== undefined) v.unshift(o[k]); }); v = v.slice(0, n); } else if(typeof o !== 'object') { if(n !== 0) v = o.toString().slice(-n); else return null; } else if(o instanceof Array) { if(n === 1 && !gotN) return o[o.length -1]; if(n === 0 && !gotN) return undefined; return n !== 0 ? o.slice(-n) : []; } else { v = {}; if(n < 0) n = 0; libs.object.each(o, len - n, len, function (item, key) { v[key] = item; }); keys = getKeys(v); if(n === 1 && !gotN && keys.length === 0) return undefined; return keys.length === 1 && !gotN ? v[keys[0]] : v; } return v.length === 1 && !gotN ? v[0] : v; }
javascript
{ "resource": "" }
q60638
getCallback
validation
function getCallback (o) { var last = libs.object.last(o); return last instanceof Function ? last : NULL_FUNCTION; }
javascript
{ "resource": "" }
q60639
only
validation
function only (o, types) { types = libs.object.toArray(arguments); types.shift(); // Allows the 'plural' form of the type... libs.object.each(types, function (type, key) { this[key] = type.replace(/s$/, ''); }); if(typeof o !== 'object' || !o) return o; var isArray = o instanceof Array ? true : false, filtered = isArray ? [] : {}, typeArr = types.indexOf('array'), typeObj = types.indexOf('object object'); libs.object.each(o, function (item, key) { var typeItem = types.indexOf(typeof item); if(typeObj !== -1 && typeArr === -1) { if((typeof item === 'object' && !(item instanceof Array)) || (typeof item !== 'object' && typeItem !== -1)) { if(isArray) filtered.push(item); else filtered[key] = item; } } else if(typeObj !== -1 && typeArr !== -1) { types.push('object'); if(typeItem !== -1) { if(isArray) filtered.push(item); else filtered[key] = item; } } else if(typeItem !== -1 || (item instanceof Array && typeArr !== -1)) { if(isArray) filtered.push(item); else filtered[key] = item; } }); return filtered; }
javascript
{ "resource": "" }
q60640
whereKeys
validation
function whereKeys (o, predicate) { if(!(predicate instanceof Function)) { var temp = predicate; predicate = function (k) { return k == temp; }; // jshint ignore:line } if(o === null || o === undefined) return o; if(typeof 0 === 'boolean') return predicate.call(o, o, 0); var isObject = typeof o === 'object' && !(o instanceof Array) ? true : false, filtered = !isObject ? [] : {}; libs.object.each(o, function (item, key) { if(predicate.call(key, key, item)) { if(isObject) filtered[key] = item; else filtered.push(item); } }); if(typeof o !== 'object') filtered = filtered.join(''); return filtered; }
javascript
{ "resource": "" }
q60641
max
validation
function max (o, func) { if(!o || typeof o !== 'object') return o; if(libs.object.size(o) === 0) return; if(!(func instanceof Function)) func = undefined; var max, maxValue; if(!func) { max = libs.object.first(o); libs.object.each(o, 1, function (item) { if(item >= max) max = item; }); } else { max = libs.object.first(o); maxValue = func.call(max, max); libs.object.each(o, 1, function (item) { var value = func.call(item, item); if(value >= maxValue) { max = item; maxValue = value; } }); } return max; }
javascript
{ "resource": "" }
q60642
keyOfMax
validation
function keyOfMax (o, func) { if(!o || typeof o !== 'object') return o; if(libs.object.size(o) === 0) return; if(!(func instanceof Function)) func = undefined; var max, maxValue, maxKey; if(!func) { max = libs.object.first(o); maxKey = libs.object.keys(o)[0]; libs.object.each(o, 1, function (item, key) { if(item >= max) { max = item; maxKey = key; } }); } else { max = libs.object.first(o); maxKey = libs.object.keys(o)[0]; maxValue = func.call(max, max); libs.object.each(o, 1, function (item, key) { var value = func.call(item, item); if(value >= maxValue) { if(value >= maxValue) { max = item; maxValue = value; maxKey = key; } } }); } return maxKey; }
javascript
{ "resource": "" }
q60643
min
validation
function min (o, func) { if(!o || typeof o !== 'object') return o; if(libs.object.size(o) === 0) return; if(!(func instanceof Function)) func = undefined; if(typeof o !== 'object') return o; var min, minValue; if(!func) { min = libs.object.first(o); libs.object.each(o, 1, function (item) { if(item <= min) min = item; }); } else { min = libs.object.first(o); minValue = func.call(min, min); libs.object.each(o, 1, function (item) { var value = func.call(item, item); if(value <= minValue) { min = item; minValue = value; } }); } return min; }
javascript
{ "resource": "" }
q60644
keyOfMin
validation
function keyOfMin (o, func) { if(!o || typeof o !== 'object') return o; if(libs.object.size(o) === 0) return; if(!(func instanceof Function)) func = undefined; if(typeof o !== 'object') return o; var min, minValue, minKey; if(!func) { min = libs.object.first(o); minKey = libs.object.keys(o)[0]; libs.object.each(o, 1, function (item, key) { if(item <= min) { min = item; minKey = key; } }); } else { min = libs.object.first(o); minValue = func.call(min, min); minKey = libs.object.keys(o)[0]; libs.object.each(o, 1, function (item, key) { var value = func.call(item, item); if(value <= minValue) { min = item; minValue = value; minKey = key; } }); } return minKey; }
javascript
{ "resource": "" }
q60645
_implements
validation
function _implements () { var args = libs.object.toArray(arguments), a = args.shift(); if(!a) return false; return libs.object.every(args, function (m) { if(!(a[m] instanceof Function)) return false; }); }
javascript
{ "resource": "" }
q60646
implementsOwn
validation
function implementsOwn (o, method) { var args = libs.object.toArray(arguments), a = args.shift(); if(!a) return false; return libs.object.every(args, function (m) { if(!(a[m] instanceof Function) || !o.hasOwnProperty(method)) return false; }); }
javascript
{ "resource": "" }
q60647
create
validation
function create(props) { var joystick = Object.create(this); // apply Widget defaults, then overwrite (if applicable) with Slider defaults _canvasWidget2.default.create.call(joystick); // ...and then finally override with user defaults Object.assign(joystick, Joystick.defaults, props); // set underlying value if necessary... TODO: how should this be set given min/max? if (props.value) joystick.__value = props.value; // inherits from Widget joystick.init(); return joystick; }
javascript
{ "resource": "" }
q60648
create
validation
function create() { var shouldUseTouch = _utilities2.default.getMode() === 'touch'; _widget2.default.create.call(this); Object.assign(this, DOMWidget.defaults); // ALL INSTANCES OF DOMWIDGET MUST IMPLEMENT CREATE ELEMENT if (typeof this.createElement === 'function') { /** * The DOM element used by the DOMWidget * @memberof DOMWidget * @instance */ this.element = this.createElement(); } else { throw new Error('widget inheriting from DOMWidget does not implement createElement method; this is required.'); } }
javascript
{ "resource": "" }
q60649
place
validation
function place() { var containerWidth = this.container.getWidth(), containerHeight = this.container.getHeight(), width = this.width <= 1 ? containerWidth * this.width : this.width, height = this.height <= 1 ? containerHeight * this.height : this.height, x = this.x < 1 ? containerWidth * this.x : this.x, y = this.y < 1 ? containerHeight * this.y : this.y; if (!this.attached) { this.attached = true; } if (this.isSquare) { if (height > width) { height = width; } else { width = height; } } this.element.width = width; this.element.style.width = width + 'px'; this.element.height = height; this.element.style.height = height + 'px'; this.element.style.left = x; this.element.style.top = y; /** * Bounding box, in absolute coordinates, of the DOMWidget * @memberof DOMWidget * @instance * @type {Object} */ this.rect = this.element.getBoundingClientRect(); }
javascript
{ "resource": "" }
q60650
equalArrayElements
validation
function equalArrayElements (needle, haystack) { let missingNeedle = needle.filter(n => haystack.indexOf(n) === -1) if (missingNeedle.length !== 0) { return false } let missingHaystack = haystack.filter(h => needle.indexOf(h) === -1) return missingHaystack.length === 0 }
javascript
{ "resource": "" }
q60651
Series
validation
function Series(asyncFncWrapper) { asyncFncWrapper = getAsyncFncWrapper(asyncFncWrapper); this.add = function() { var fnc, args; if(arguments.length===1) { fnc=arguments[0]; } else if(arguments.length > 1) { fnc=arguments[arguments.length - 1]; args = []; for(var i=0;i<arguments.length-1;i++){ args.push(arguments[i]); } } if(typeof fnc!=='function') throw new Error('Async Series: Last argument have to be function(arg1, arg2, ..., next).'); this._fncQueue = this._fncQueue || []; this._fncQueue.push({ args:args, fnc:fnc }); this.execute = function(finalFnc){ var fncQueue = this._fncQueue; fncQueue.current = 0; fncQueue.scheduled = 0; function run(itm) { asyncFncWrapper(function(){ fncQueue.scheduled = fncQueue.current; if(itm.args) { itm.args.push(next); itm.fnc.apply(itm, itm.args); } else itm.fnc(next); }); } function next(){ if(!fncQueue || fncQueue.scheduled !== fncQueue.current) throw new Error('Async Series: cannot execute next() more than once per function'); // if(arguments.length > 0) { if(arguments.length > 0 && (arguments[0] !== null && typeof arguments[0] !== 'undefined')) { var args = Array.prototype.slice.call(arguments); fncQueue = null; if(typeof finalFnc==='function') asyncFncWrapper(function(){ finalFnc.apply(this, args); }); } else if(fncQueue.current + 1 < fncQueue.length) { fncQueue.current+=1; run(fncQueue[fncQueue.current]); } else { fncQueue = null; if(typeof finalFnc==='function') asyncFncWrapper(finalFnc); } } if(fncQueue && fncQueue.length>0) run(fncQueue[fncQueue.current]); }; return this; }; this.execute = function(fnc){ if(typeof fnc==='function') asyncFncWrapper(fnc); }; }
javascript
{ "resource": "" }
q60652
Parallel
validation
function Parallel(asyncFncWrapper) { asyncFncWrapper = getAsyncFncWrapper(asyncFncWrapper); this.add = function() { var fnc, args; if(arguments.length===1) { fnc=arguments[0]; } else if(arguments.length > 1) { fnc=arguments[arguments.length - 1]; args = []; for(var i=0;i<arguments.length-1;i++){ args.push(arguments[i]); } } if(typeof fnc!=='function') throw new Error('Async Parallel: Last argument have to be function(arg1, arg2, ..., next).'); this._fncQueue = this._fncQueue || []; this._fncQueue.push({ args:args, fnc:fnc }); this.execute = function(finalFnc){ var fncQueue = this._fncQueue; fncQueue.finished = 0; function run(itm) { asyncFncWrapper(function(){ if(itm.args) { itm.args.push(next); itm.fnc.apply(itm, itm.args); } else itm.fnc(next); }); } function next(){ if(arguments.length > 0) throw new Error('Async Parallel: next() callback do not accept any arguments, ' + 'because of parallel behaviour, it cannot stop executing on error argument in callback'); else if(!fncQueue) // TODO: implement trackign finished queue items // (fncQueue.scheduled !== fncQueue.current) throw new Error('Async Parallel: cannot execute next() more than once per function'); else if(fncQueue.finished + 1 < fncQueue.length) { fncQueue.finished+=1; } else { fncQueue = null; if(typeof finalFnc==='function') asyncFncWrapper(finalFnc); } } for(var i=0; i< (fncQueue || []).length; i++) { run(fncQueue[i]); } }; return this; }; this.execute = function(fnc){ if(typeof fnc==='function') asyncFncWrapper(fnc); }; }
javascript
{ "resource": "" }
q60653
create
validation
function create(props) { var menu = Object.create(this); _domWidget2.default.create.call(menu); Object.assign(menu, Menu.defaults, props); menu.createOptions(); menu.element.addEventListener('change', function (e) { menu.__value = e.target.value; menu.output(); if (menu.onvaluechange !== null) { menu.onvaluechange(menu.value); } }); return menu; }
javascript
{ "resource": "" }
q60654
createOptions
validation
function createOptions() { this.element.innerHTML = ''; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = this.options[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var option = _step.value; var optionEl = document.createElement('option'); optionEl.setAttribute('value', option); optionEl.innerText = option; this.element.appendChild(optionEl); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } }
javascript
{ "resource": "" }
q60655
create
validation
function create(props) { var multiSlider = Object.create(this); // apply Widget defaults, then overwrite (if applicable) with MultiSlider defaults _canvasWidget2.default.create.call(multiSlider); // ...and then finally override with user defaults Object.assign(multiSlider, MultiSlider.defaults, props); // set underlying value if necessary... TODO: how should this be set given min/max? if (props.value) multiSlider.__value = props.value; // inherits from Widget multiSlider.init(); if (props.value === undefined && multiSlider.count !== 4) { for (var i = 0; i < multiSlider.count; i++) { multiSlider.__value[i] = i / multiSlider.count; } } else if (typeof props.value === 'number') { for (var _i = 0; _i < multiSlider.count; _i++) { multiSlider.__value[_i] = props.value; } } return multiSlider; }
javascript
{ "resource": "" }
q60656
processPointerPosition
validation
function processPointerPosition(e) { var prevValue = this.value, sliderNum = void 0; if (this.style === 'horizontal') { sliderNum = Math.floor(e.clientY / this.rect.height / (1 / this.count)); this.__value[sliderNum] = (e.clientX - this.rect.left) / this.rect.width; } else { sliderNum = Math.floor(e.clientX / this.rect.width / (1 / this.count)); this.__value[sliderNum] = 1 - (e.clientY - this.rect.top) / this.rect.height; } for (var i = 0; i < this.count; i++) { if (this.__value[i] > 1) this.__value[i] = 1; if (this.__value[i] < 0) this.__value[i] = 0; } var shouldDraw = this.output(); if (shouldDraw) this.draw(); }
javascript
{ "resource": "" }
q60657
matchAll
validation
function matchAll (regex, string) { let match let matches = [] while ((match = regex.exec(string)) !== null) { delete match['index'] delete match['input'] matches.push(match) } return matches }
javascript
{ "resource": "" }
q60658
beforeEach
validation
function beforeEach(test, context, done) { context.dir = tmp.dirSync().name; process.chdir(context.dir); done && done(); }
javascript
{ "resource": "" }
q60659
promiseShouldFail
validation
function promiseShouldFail(promise, done, handler) { promise.then(result => done(new Error('Promise expected to fail'))). catch(error => { handler(error) done() }). catch(error => done(error)) }
javascript
{ "resource": "" }
q60660
promiseShouldSucceed
validation
function promiseShouldSucceed(promise, done, handler) { promise.then(result => { handler(result) done() }). catch(error => done(error)) }
javascript
{ "resource": "" }
q60661
copyAssetToContext
validation
function copyAssetToContext(src, dest, context) { var sourceAsset = path.join(testDir, src); var targetAsset = path.join(context.dir, dest); if (!fs.existsSync(sourceAsset)) { // The source asset requested is missing throw new Error("The test asset is missing"); } // Attempt to copy the asset fs.copySync(sourceAsset, targetAsset); if (!fs.existsSync(targetAsset)) { // The target asset was not copied successfully throw new Error("The test asset could not be copied"); } }
javascript
{ "resource": "" }
q60662
deepSet
validation
function deepSet(parent, key, value, mode) { // if(typeof value==='string') value = value.replace(/(\r\n|\r|\n)\s*$/, ''); // replace line endings and white spaces var parts = key.split('.'); var current = parent; if(key==='this') { if(mode==='push') parent.push(value); else parent = value.toString(); } else { for(var i=0; i<parts.length; i++) { if(i >= parts.length-1) { if(mode==='push') current[parts[i]].push(value); else current[parts[i]] = value; } else current[parts[i]] = current[parts[i]] || {}; current = current[parts[i]]; } } return parent; }
javascript
{ "resource": "" }
q60663
validation
function (fPath, strict, fn) { if (typeof(strict) === 'function') { fn = strict; strict = false; } var dir = path.dirname(fPath); var base = path.basename(fPath); if (typeof watched === 'undefined') { return fn && fn('[checkFile] watched array not properly defined.'); } else { fs.stat(fPath, function onStat(err, stats) { //If we get back an error, then the directory doesn't exist. So we aren't watching it, duh! if (err) { return fn && fn(null, false); } //If the watched [] has not been initialized, we know the file isn't tracked if (typeof watched[dir] === 'undefined' || typeof watched[dir].files === 'undefined') { return fn && fn(null, false); } if (strict) { return fn && fn(null, watched[dir].files[base] === stats.mtime.valueOf()); } else { return fn && fn(null, typeof watched[dir].files[base] !== 'undefined'); } }); } }
javascript
{ "resource": "" }
q60664
create
validation
function create(props) { var shouldUseTouch = _utilities2.default.getMode() === 'touch'; _domWidget2.default.create.call(this); Object.assign(this, CanvasWidget.defaults); /** * Store a reference to the canvas 2D context. * @memberof CanvasWidget * @instance * @type {CanvasRenderingContext2D} */ this.ctx = this.element.getContext('2d'); this.applyHandlers(shouldUseTouch); }
javascript
{ "resource": "" }
q60665
createElement
validation
function createElement() { var element = document.createElement('canvas'); element.setAttribute('touch-action', 'none'); element.style.position = 'absolute'; element.style.display = 'block'; return element; }
javascript
{ "resource": "" }
q60666
convertOfficialMap
validation
function convertOfficialMap (attributes) { let map = {} for (let attribute in attributes) { let key = officialAttributeMap[attribute] map[key] = attributes[attribute] } return map }
javascript
{ "resource": "" }
q60667
validation
function() { return _.map(ko.unwrap(that.relations), function(relation) { return ko.unwrap(relation.relatedPost.id); }); }
javascript
{ "resource": "" }
q60668
validation
function(element, valueAccessor, allBindings, viewModel, bindingContext) { var $element = $(element); var observable = valueAccessor(); if (ko.unwrap(observable)) { $element.datepicker('update', observable.datePicker().format('DD.MM.YYYY')); // same as for .datepicker())); } }
javascript
{ "resource": "" }
q60669
disposable
validation
async function disposable() { const name = "tmp" + Math.floor(Math.random() * 10000); await connection.dbCreate(name).run(); const r = Object.create(connection); r.dispose = async function() { await this.dbDrop(name).run(); }; r._poolMaster._options.db = name; return r; }
javascript
{ "resource": "" }
q60670
runRequestQueue
validation
function runRequestQueue (socket) { var queue = socket.requestQueue; if (!queue) return; for (var i in queue) { // Double-check that `queue[i]` will not // inadvertently discover extra properties attached to the Object // and/or Array prototype by other libraries/frameworks/tools. // (e.g. Ember does this. See https://github.com/balderdashy/sails.io.js/pull/5) var isSafeToDereference = ({}).hasOwnProperty.call(queue, i); if (isSafeToDereference) { // Emit the request. _emitFrom(socket, queue[i]); } } // Now empty the queue to remove it as a source of additional complexity. queue = null; }
javascript
{ "resource": "" }
q60671
create
validation
function create(props) { var slider = Object.create(this); // apply Widget defaults, then overwrite (if applicable) with Slider defaults _canvasWidget2.default.create.call(slider); // ...and then finally override with user defaults Object.assign(slider, Slider.defaults, props); // set underlying value if necessary... TODO: how should this be set given min/max? if (props.value) slider.__value = props.value; // inherits from Widget slider.init(); return slider; }
javascript
{ "resource": "" }
q60672
processPointerPosition
validation
function processPointerPosition(e) { var prevValue = this.value; if (this.style === 'horizontal') { this.__value = (e.clientX - this.rect.left) / this.rect.width; } else { this.__value = 1 - (e.clientY - this.rect.top) / this.rect.height; } // clamp __value, which is only used internally if (this.__value > 1) this.__value = 1; if (this.__value < 0) this.__value = 0; var shouldDraw = this.output(); if (shouldDraw) this.draw(); }
javascript
{ "resource": "" }
q60673
storeJob
validation
function storeJob(jobCompleted) { // if jobCompleted is jobFootPrint let emitterStore = new EventEmitter(); let socketStoreJob = io.connect(urlSocket); let msg = messageBuilder(jobCompleted, 'storeJob', true); socketStoreJob.on('connect', function () { socketStoreJob.emit('storeJob', msg); }) .on('addingResponse', (messageRes) => { logger_1.logger.log('info', `Job footprint stored in Warehouse`); //logger.log('info', `Message receive from server (add job request) \n ${JSON.stringify(messageRes)}`); logger_1.logger.log('debug', `Message returned: \n ${JSON.stringify(messageRes)}`); if (messageRes.value === 'success') emitterStore.emit('addSuccess', messageRes); if (messageRes.value === 'errorAddjob') emitterStore.emit('addError', messageRes); }); return emitterStore; }
javascript
{ "resource": "" }
q60674
handshake
validation
function handshake(param) { return new Promise((resolve, reject) => { if (types.isClientConfig(param)) { logger_1.logger.log('info', `Client config paramaters perfectly loaded`); logger_1.logger.log('debug', `Config file content: \n ${JSON.stringify(param)}`); let socket = io.connect(`http://${param.warehouseAddress}:${param.portSocket}`); socket.on('connect', function () { logger_1.logger.log('info', `Connection with Warehouse server succeed, starting communication...\n`); resolve(); }) .on('connect_error', function () { logger_1.logger.log('debug', `Connection with Warehouse server cannot be establish, disconnecting socket...\n`); reject(); socket.disconnect(); }); } else { logger_1.logger.log('error', `Config file not in good format \n ${JSON.stringify(config)}`); reject(); } }); }
javascript
{ "resource": "" }
q60675
pivotTable
validation
function pivotTable(dataset) { var column_names = []; var xvalues = []; var values = {}; var rows = {}; for (rn in dataset.data) { // at first run fill the existing data (rows/columns/values) if (rn == 0) { // skip first row as it contains column names we don't need for pivot continue; } var val1 = dataset.data[rn][0]; var val2 = dataset.data[rn][1]; if (column_names.indexOf(val2) == -1) { column_names.push(val2); } if (xvalues.indexOf(val1) == -1) { xvalues.push(val1); } if (!(val1 in values)) { values[val1] = []; } values[val1][val2] = dataset.data[rn][2]; } for (n in xvalues) { // at second run fill the missing values with nulls var val1 = xvalues[n]; rows[val1] = []; for (m in column_names) { var val2 = column_names[m]; if (val1 in values && val2 in values[val1]) { rows[val1].push(values[val1][val2]); } else { rows[val1].push(null); } } } var res = []; column_names.unshift(dataset.fields[0].name); res.push(column_names); // first row is pivot column names xvalues.forEach(function (item) { var r = [item].concat(rows[item]); res.push(r); }); return res; }
javascript
{ "resource": "" }
q60676
init
validation
function init(user_id, secret, storage, callback) { API_USER_ID = user_id; API_SECRET = secret; TOKEN_STORAGE = storage; if (!callback) { callback = function() {} } if (!fs.existsSync(TOKEN_STORAGE)) { mkdirSyncRecursive(TOKEN_STORAGE); } if (TOKEN_STORAGE.substr(-1) !== '/') { TOKEN_STORAGE += '/'; } var hashName = md5(API_USER_ID+'::'+API_SECRET); if (fs.existsSync(TOKEN_STORAGE+hashName)) { TOKEN = fs.readFileSync(TOKEN_STORAGE+hashName,{encoding:'utf8'}); } if (! TOKEN.length) { getToken(callback); return; } callback(TOKEN) }
javascript
{ "resource": "" }
q60677
getEmailTemplate
validation
function getEmailTemplate(callback, id){ if (id === undefined) { return callback(returnError('Empty email template id')); } sendRequest('template/' + id, 'GET', {}, true, callback); }
javascript
{ "resource": "" }
q60678
updateEmailVariables
validation
function updateEmailVariables(callback,id,email,variables){ if ((id===undefined) || (email === undefined) || (variables === undefined) || (! variables.length)) { return callback(returnError("Empty email, variables or book id")); } var data = { email: email, variables: variables }; sendRequest( 'addressbooks/' + id + '/emails/variable', 'POST', data, true, callback ); }
javascript
{ "resource": "" }
q60679
smsAddPhonesWithVariables
validation
function smsAddPhonesWithVariables(callback, addressbook_id, phones) { if ((addressbook_id === undefined) || (phones === undefined) || (!Object.keys(phones).length)) { return callback(returnError("Empty phones or book id")); } var data = { addressBookId: addressbook_id, phones: JSON.stringify(phones) }; sendRequest('sms/numbers/variables', 'POST', data, true, callback); }
javascript
{ "resource": "" }
q60680
smsGetPhoneInfo
validation
function smsGetPhoneInfo(callback, addressbook_id, phone) { if ((addressbook_id === undefined) || (phone === undefined)) { return callback(returnError("Empty phone or book id")); } sendRequest('sms/numbers/info/' + addressbook_id + '/' + phone, 'GET', {}, true, callback); }
javascript
{ "resource": "" }
q60681
smsUpdatePhonesVariables
validation
function smsUpdatePhonesVariables(callback, addressbook_id, phones, variables) { if (addressbook_id === undefined) { return callback(returnError("Empty book id")); } if ((phones === undefined) || (!phones.length)) { return callback(returnError("Empty phones")); } if ((variables === undefined) || (!Object.keys(variables).length)) { return callback(returnError("Empty variables")); } var data = { 'addressBookId': addressbook_id, 'phones': JSON.stringify(phones), 'variables': JSON.stringify(variables) } sendRequest('sms/numbers', 'PUT', data, true, callback); }
javascript
{ "resource": "" }
q60682
smsAddPhonesToBlacklist
validation
function smsAddPhonesToBlacklist(callback, phones, comment){ if ((phones === undefined) || (!phones.length)) { return callback(returnError("Empty phones")); } var data = { 'phones': JSON.stringify(phones), 'description': comment } sendRequest('sms/black_list', 'POST', data, true, callback); }
javascript
{ "resource": "" }
q60683
smsDeletePhonesFromBlacklist
validation
function smsDeletePhonesFromBlacklist(callback, phones) { if ((phones === undefined) || (!phones.length)) { return callback(returnError("Empty phones")); } var data = { 'phones': JSON.stringify(phones), } sendRequest('sms/black_list', 'DELETE', data, true, callback); }
javascript
{ "resource": "" }
q60684
smsAddCampaign
validation
function smsAddCampaign(callback, sender_name, addressbook_id, body, date, transliterate){ if (sender_name === undefined) { return callback(returnError("Empty sender name")); } if (addressbook_id === undefined) { return callback(returnError("Empty book id")); } if (body === undefined) { return callback(returnError("Empty sms text")); } var data = { 'sender': sender_name, 'addressBookId': addressbook_id, 'body': body, 'date': date, 'transliterate': transliterate } sendRequest('sms/campaigns', 'POST', data, true, callback); }
javascript
{ "resource": "" }
q60685
smsSend
validation
function smsSend(callback, sender_name, phones, body, date, transliterate) { if (sender_name === undefined) { return callback(returnError("Empty sender name")); } if ((phones === undefined) || (!phones.length)) { return callback(returnError("Empty phones")); } if (body === undefined) { return callback(returnError("Empty sms text")); } var data = { 'sender': sender_name, 'phones': JSON.stringify(phones), 'body': body, 'date': date, 'transliterate': transliterate } sendRequest('sms/send', 'POST', data, true, callback); }
javascript
{ "resource": "" }
q60686
smsGetListCampaigns
validation
function smsGetListCampaigns(callback, date_from, date_to) { var data = { 'dateFrom': date_from, 'dateTo': date_to } sendRequest('sms/campaigns/list', 'GET', data, true, callback); }
javascript
{ "resource": "" }
q60687
smsGetCampaignInfo
validation
function smsGetCampaignInfo(callback, campaign_id){ if (campaign_id === undefined) { return callback(returnError("Empty sms campaign id")); } sendRequest('sms/campaigns/info/' + campaign_id, 'GET', {}, true, callback); }
javascript
{ "resource": "" }
q60688
smsCancelCampaign
validation
function smsCancelCampaign(callback, campaign_id) { if (campaign_id === undefined) { return callback(returnError("Empty sms campaign id")); } sendRequest('sms/campaigns/cancel/' + campaign_id, 'PUT', {}, true, callback); }
javascript
{ "resource": "" }
q60689
smsGetCampaignCost
validation
function smsGetCampaignCost(callback, sender_name, body, addressbook_id, phones){ if (sender_name === undefined) { return callback(returnError("Empty sender name")); } if (body === undefined) { return callback(returnError("Empty sms text")); } if ((addressbook_id === undefined) || (phones === undefined) || (!phones.length)) { return callback(returnError("Empty book id or phones")); } var data = { 'sender': sender_name, 'body': body, 'addressBookId': addressbook_id } if (phones.length) { data['phones'] = JSON.stringify(phones); } sendRequest('sms/campaigns/cost', 'GET', data, true, callback); }
javascript
{ "resource": "" }
q60690
smsDeleteCampaign
validation
function smsDeleteCampaign(callback, campaign_id) { if (campaign_id === undefined) { return callback(returnError("Empty sms campaign id")); } var data = { 'id': campaign_id } sendRequest('sms/campaigns', 'DELETE', data, true, callback); }
javascript
{ "resource": "" }
q60691
forEach
validation
function forEach(arr, callback, scope) { var i, len = arr.length; for (i = 0; i < len; i += 1) { callback.call(scope, arr[i], i); } }
javascript
{ "resource": "" }
q60692
emit
validation
function emit(instance, name) { var args = [].slice.call(arguments, 2); if (events.indexOf(name) > -1) { if (instance.handlers[name] && instance.handlers[name] instanceof Array) { forEach(instance.handlers[name], function (handle) { window.setTimeout(function () { handle.callback.apply(handle.context, args); }, 0); }); } } else { throw new Error(name + ' event cannot be found on TreeView.'); } }
javascript
{ "resource": "" }
q60693
render
validation
function render(self) { var container = isDOMElement(self.node) ? self.node : document.getElementById(self.node); var leaves = [], click; var renderLeaf = function (item) { var leaf = document.createElement('div'); var content = document.createElement('div'); var text = document.createElement('div'); var expando = document.createElement('div'); leaf.setAttribute('class', 'tree-leaf'); content.setAttribute('class', 'tree-leaf-content'); content.setAttribute('data-item', JSON.stringify(item)); text.setAttribute('class', 'tree-leaf-text'); text.textContent = item.name; expando.setAttribute('class', 'tree-expando ' + (item.expanded ? 'expanded' : '')); expando.textContent = item.expanded ? '-' : '+'; content.appendChild(expando); content.appendChild(text); leaf.appendChild(content); if (item.children && item.children.length > 0) { var children = document.createElement('div'); children.setAttribute('class', 'tree-child-leaves'); forEach(item.children, function (child) { var childLeaf = renderLeaf(child); children.appendChild(childLeaf); }); if (!item.expanded) { children.classList.add('hidden'); } leaf.appendChild(children); } else { expando.classList.add('hidden'); } return leaf; }; forEach(self.data, function (item) { leaves.push(renderLeaf.call(self, item)); }); container.innerHTML = leaves.map(function (leaf) { return leaf.outerHTML; }).join(''); click = function (e) { var parent = (e.target || e.currentTarget).parentNode; var data = JSON.parse(parent.getAttribute('data-item')); var leaves = parent.parentNode.querySelector('.tree-child-leaves'); if (leaves) { if (leaves.classList.contains('hidden')) { self.expand(parent, leaves); } else { self.collapse(parent, leaves); } } else { emit(self, 'select', { target: e, data: data }); } }; forEach(container.querySelectorAll('.tree-leaf-text'), function (node) { node.onclick = click; }); forEach(container.querySelectorAll('.tree-expando'), function (node) { node.onclick = click; }); }
javascript
{ "resource": "" }
q60694
validatePackageName
validation
function validatePackageName(package_name) { //Make the package conform to Java package types //http://developer.android.com/guide/topics/manifest/manifest-element.html#package //Enforce underscore limitation var msg = 'Error validating package name. '; if (!/^[a-zA-Z][a-zA-Z0-9_]+(\.[a-zA-Z][a-zA-Z0-9_]*)+$/.test(package_name)) { return Q.reject(new CordovaError(msg + 'Package name must look like: com.company.Name')); } //Class is a reserved word if(/\b[Cc]lass\b/.test(package_name)) { return Q.reject(new CordovaError(msg + '"class" is a reserved word')); } return Q.resolve(); }
javascript
{ "resource": "" }
q60695
validateProjectName
validation
function validateProjectName(project_name) { var msg = 'Error validating project name. '; //Make sure there's something there if (project_name === '') { return Q.reject(new CordovaError(msg + 'Project name cannot be empty')); } //Enforce stupid name error if (project_name === 'CordovaActivity') { return Q.reject(new CordovaError(msg + 'Project name cannot be CordovaActivity')); } //Classes in Java don't begin with numbers if (/^[0-9]/.test(project_name)) { return Q.reject(new CordovaError(msg + 'Project name must not begin with a number')); } return Q.resolve(); }
javascript
{ "resource": "" }
q60696
validation
function (file) { var contents = fs.readFileSync(file, 'utf-8'); if (contents) { // Windows is the BOM. Skip the Byte Order Mark. contents = contents.substring(contents.indexOf('<')); } var doc = new et.ElementTree(et.XML(contents)); // eslint-disable-line babel/new-cap var root = doc.getroot(); if (root.tag !== 'widget') { // Throw an error if widget is not the root tag throw new Error(file + ' has incorrect root node name (expected "widget", was "' + root.tag + '")'); } return doc; }
javascript
{ "resource": "" }
q60697
Config
validation
function Config(file) { this._file = file; this._doc = _this.parse(file); this._root = this._doc.getroot(); }
javascript
{ "resource": "" }
q60698
captureStream
validation
function captureStream(name, callback) { var stream = process[name]; var originalWrite = stream.write; stream.write = function(str) { callback(name, str); }; return { restore: function() { stream.write = originalWrite; } }; }
javascript
{ "resource": "" }
q60699
messageHandler
validation
function messageHandler() { var message = messages.read(arguments, _session.signer); if (!message) { return; } var handler = _session.handlers[message.header.msg_type]; if (handler) { handler(message); } }
javascript
{ "resource": "" }