_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q64700 | test | function(prop, value) {
var me = this,
dom = me.dom,
hooks = me.styleHooks,
style = dom.style,
valueFrom = Ext.valueFrom,
name, hook;
// we don't promote the 2-arg form to object-form to avoid the overhead...
if (typeof prop == 'string') {
hook = hooks[prop];
if (!hook) {
hooks[prop] = hook = { name: Ext.dom.Element.normalize(prop) };
}
value = valueFrom(value, '');
if (hook.set) {
hook.set(dom, value, me);
} else {
style[hook.name] = value;
}
}
else {
for (name in prop) {
if (prop.hasOwnProperty(name)) {
hook = hooks[name];
if (!hook) {
hooks[name] = hook = { name: Ext.dom.Element.normalize(name) };
}
value = valueFrom(prop[name], '');
if (hook.set) {
hook.set(dom, value, me);
}
else {
style[hook.name] = value;
}
}
}
}
return me;
} | javascript | {
"resource": ""
} |
|
q64701 | test | function() {
//<debug warn>
Ext.Logger.deprecate("Ext.dom.Element.getViewSize() is deprecated", this);
//</debug>
var doc = document,
dom = this.dom;
if (dom == doc || dom == doc.body) {
return {
width: Element.getViewportWidth(),
height: Element.getViewportHeight()
};
}
else {
return {
width: dom.clientWidth,
height: dom.clientHeight
};
}
} | javascript | {
"resource": ""
} |
|
q64702 | test | function(prop) {
//<debug warn>
Ext.Logger.deprecate("Ext.dom.Element.isTransparent() is deprecated", this);
//</debug>
var value = this.getStyle(prop);
return value ? this.transparentRe.test(value) : false;
} | javascript | {
"resource": ""
} |
|
q64703 | printCounter | test | function printCounter(indicator) {
counter++;
process.stdout.write(indicator);
if (counter === filesLength || counter % lineLength === 0) {
process.stdout.write(lineSpacing.slice(-1 * ((lineLength - counter) % lineLength)) + " ");
process.stdout.write(String(" " + counter).slice(-3) + " / " + String(" " + filesLength).slice(-3));
process.stdout.write("\n");
}
} | javascript | {
"resource": ""
} |
q64704 | encode | test | function encode(string) {
function hex(code) {
var hex_code = code.toString(16).toUpperCase();
if (hex_code.length < 2) {
hex_code = 0 + hex_code;
}
return '%' + hex_code;
}
string = string + '';
var reserved_chars = /[ :\/?#\[\]@!$&'()*+,;=<>"{}|\\`\^%\r\n\u0080-\uffff]/;
var str_len = string.length;
var i;
var string_arr = string.split('');
var c;
for (i = 0; i < str_len; i += 1) {
if (c = string_arr[i].match(reserved_chars)) {
c = c[0].charCodeAt(0);
if (c < 128) {
string_arr[i] = hex(c);
} else if (c < 2048) {
string_arr[i] = hex(192 + (c >> 6)) + hex(128 + (c & 63));
} else if (c < 65536) {
string_arr[i] = hex(224 + (c >> 12)) + hex(128 + ((c >> 6) & 63)) + hex(128 + (c & 63));
} else if (c < 2097152) {
string_arr[i] = hex(240 + (c >> 18)) + hex(128 + ((c >> 12) & 63)) + hex(128 + ((c >> 6) & 63)) + hex(128 + (c & 63));
}
}
}
return string_arr.join('');
} | javascript | {
"resource": ""
} |
q64705 | decode | test | function decode(string) {
return string.replace(/%[a-fA-F0-9]{2}/ig, function (match) {
return String.fromCharCode(parseInt(match.replace('%', ''), 16));
});
} | javascript | {
"resource": ""
} |
q64706 | getNonce | test | function getNonce(key_length) {
function rand() {
return Math.floor(Math.random() * chars.length);
}
key_length = key_length || 64;
var key_bytes = key_length / 8;
var value = '';
var key_iter = key_bytes / 4;
var key_remainder = key_bytes % 4;
var i;
var chars = ['20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2A', '2B', '2C', '2D', '2E', '2F', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3A', '3B', '3C', '3D', '3E', '3F', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4A', '4B', '4C', '4D', '4E', '4F', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5A', '5B', '5C', '5D', '5E', '5F', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6A', '6B', '6C', '6D', '6E', '6F', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7A', '7B', '7C', '7D', '7E'];
for (i = 0; i < key_iter; i += 1) {
value += chars[rand()] + chars[rand()] + chars[rand()] + chars[rand()];
}
// handle remaing bytes
for (i = 0; i < key_remainder; i += 1) {
value += chars[rand()];
}
return value;
} | javascript | {
"resource": ""
} |
q64707 | toHeaderString | test | function toHeaderString(params, realm) {
var arr = [];
var i;
for (i in params) {
if (typeof params[i] !== 'object' && params[i] !== '' && params[i] !== undefined) {
arr.push(encode(i) + '="' + encode(params[i]) + '"');
}
}
arr.sort();
if (realm) {
arr.unshift('realm="' + encode(realm) + '"');
}
return arr.join(', ');
} | javascript | {
"resource": ""
} |
q64708 | toSignatureBaseString | test | function toSignatureBaseString(method, url, header_params, query_params) {
var arr = [];
var i;
for (i in header_params) {
if (header_params[i] !== undefined && header_params[i] !== '') {
arr.push([encode(i), encode(header_params[i] + '')]);
}
}
for (i in query_params) {
if (query_params[i] !== undefined && query_params[i] !== '') {
arr.push([encode(i), encode(query_params[i] + '')]);
}
}
arr = arr.sort(function lexicalSort(a, b) {
if (a[0] < b[0]) {
return -1;
} else if (a[0] > b[0]) {
return 1;
} else {
if (a[1] < b[1]) {
return -1;
} else if (a[1] > b[1]) {
return 1;
} else {
return 0;
}
}
}).map(function (el) {
return el.join("=");
});
return [method, encode(url), encode(arr.join('&'))].join('&');
} | javascript | {
"resource": ""
} |
q64709 | test | function (application_secret, token_secret, signature_base) {
var passphrase;
var signature;
application_secret = encode(application_secret);
token_secret = encode(token_secret || '');
passphrase = application_secret + '&' + token_secret;
signature = Cryptography.hmac(Cryptography.SHA1, passphrase, signature_base);
return btoa(signature);
} | javascript | {
"resource": ""
} |
|
q64710 | test | function(values, animated) {
var me = this,
slots = me.getInnerItems(),
ln = slots.length,
key, slot, loopSlot, i, value;
if (!values) {
values = {};
for (i = 0; i < ln; i++) {
//set the value to false so the slot will return null when getValue is called
values[slots[i].config.name] = null;
}
}
for (key in values) {
slot = null;
value = values[key];
for (i = 0; i < slots.length; i++) {
loopSlot = slots[i];
if (loopSlot.config.name == key) {
slot = loopSlot;
break;
}
}
if (slot) {
if (animated) {
slot.setValueAnimated(value);
} else {
slot.setValue(value);
}
}
}
me._values = me._value = values;
return me;
} | javascript | {
"resource": ""
} |
|
q64711 | test | function(useDom) {
var values = {},
items = this.getItems().items,
ln = items.length,
item, i;
if (useDom) {
for (i = 0; i < ln; i++) {
item = items[i];
if (item && item.isSlot) {
values[item.getName()] = item.getValue(useDom);
}
}
this._values = values;
}
return this._values;
} | javascript | {
"resource": ""
} |
|
q64712 | addTranslation | test | function addTranslation(translations, locale) {
if (typeof translations !== 'object') {
return;
}
// add translations with format like
// {
// en: {},
// fr: {},
// }
if (locale === undefined) {
for (var key in translations) {
addTranslation(translations[key], key);
}
return;
}
if (I18n.translations[locale] === undefined) {
I18n.translations[locale] = translations;
} else {
Object.assign(I18n.translations[locale], translations);
}
} | javascript | {
"resource": ""
} |
q64713 | test | function() {
var me = this,
pressedButtons = [],
ln, i, item, items;
//call the parent first so the items get converted into a MixedCollection
me.callParent(arguments);
items = this.getItems();
ln = items.length;
for (i = 0; i < ln; i++) {
item = items.items[i];
if (item.getInitialConfig('pressed')) {
pressedButtons.push(items.items[i]);
}
}
me.updateFirstAndLastCls(items);
me.setPressedButtons(pressedButtons);
} | javascript | {
"resource": ""
} |
|
q64714 | test | function(newButtons, oldButtons) {
var me = this,
items = me.getItems(),
pressedCls = me.getPressedCls(),
events = [],
item, button, ln, i, e;
//loop through existing items and remove the pressed cls from them
ln = items.length;
if (oldButtons && oldButtons.length) {
for (i = 0; i < ln; i++) {
item = items.items[i];
if (oldButtons.indexOf(item) != -1 && newButtons.indexOf(item) == -1) {
item.removeCls([pressedCls, item.getPressedCls()]);
events.push({
item: item,
toggle: false
});
}
}
}
//loop through the new pressed buttons and add the pressed cls to them
ln = newButtons.length;
for (i = 0; i < ln; i++) {
button = newButtons[i];
if (!oldButtons || oldButtons.indexOf(button) == -1) {
button.addCls(pressedCls);
events.push({
item: button,
toggle: true
});
}
}
//loop through each of the events and fire them after a delay
ln = events.length;
if (ln && oldButtons !== undefined) {
Ext.defer(function() {
for (i = 0; i < ln; i++) {
e = events[i];
me.fireEvent('toggle', me, e.item, e.toggle);
}
}, 50);
}
} | javascript | {
"resource": ""
} |
|
q64715 | test | function() {
var me = this,
record;
if (me.getAutoSelect()) {
var store = me.getStore();
record = (me.originalValue) ? me.originalValue : store.getAt(0);
} else {
var usePicker = me.getUsePicker(),
picker = usePicker ? me.picker : me.listPanel;
if (picker) {
picker = picker.child(usePicker ? 'pickerslot' : 'dataview');
picker.deselectAll();
}
record = null;
}
me.setValue(record);
return me;
} | javascript | {
"resource": ""
} |
|
q64716 | RPC | test | function RPC (contact, options) {
assert(this instanceof RPC, 'Invalid instance supplied')
assert(contact instanceof Contact, 'Invalid contact was supplied')
events.EventEmitter.call(this)
options = options || {}
if (options.replyto) {
assert(options.replyto instanceof Contact, 'Invalid contact was supplied')
}
this._hooks = {
before: {},
after: {}
}
this._pendingCalls = {}
this._contact = options.replyto || contact
this._log = options && options.logger
this.readyState = 0
this.open()
} | javascript | {
"resource": ""
} |
q64717 | Channel | test | function Channel (id, exchange) {
var self = this;
events.EventEmitter.call(this);
this.id = id;
this.exchange = exchange;
this.exchange.on(this.id, function (message) {
self.emit('message', message);
});
this.setMaxListeners(0);
} | javascript | {
"resource": ""
} |
q64718 | continuable | test | function continuable(func, context) {
ensureFunc(func, 'function');
if (context) { // TODO: Handle falsy things?
func = bind(func, context);
}
steps.push(func);
return continuable;
} | javascript | {
"resource": ""
} |
q64719 | extractDescription | test | function extractDescription (d) {
if (!d) return;
if (d === "ERROR: No README data found!") return;
// the first block of text before the first heading
// that isn't the first line heading
d = d.trim().split('\n')
for (var s = 0; d[s] && d[s].trim().match(/^(#|$)/); s ++);
var l = d.length
for (var e = s + 1; e < l && d[e].trim(); e ++);
return d.slice(s, e).join(' ').trim()
} | javascript | {
"resource": ""
} |
q64720 | addComment | test | function addComment(type, value, start, end, loc) {
var comment;
assert(typeof start === 'number', 'Comment must have valid position');
// Because the way the actual token is scanned, often the comments
// (if any) are skipped twice during the lexical analysis.
// Thus, we need to skip adding a comment if the comment array already
// handled it.
if (state.lastCommentStart >= start) {
return;
}
state.lastCommentStart = start;
comment = {
type: type,
value: value
};
if (extra.range) {
comment.range = [start, end];
}
if (extra.loc) {
comment.loc = loc;
}
extra.comments.push(comment);
if (extra.attachComment) {
extra.leadingComments.push(comment);
extra.trailingComments.push(comment);
}
} | javascript | {
"resource": ""
} |
q64721 | expectKeyword | test | function expectKeyword(keyword, contextual) {
var token = lex();
if (token.type !== (contextual ? Token.Identifier : Token.Keyword) ||
token.value !== keyword) {
throwUnexpected(token);
}
} | javascript | {
"resource": ""
} |
q64722 | parseArrayInitialiser | test | function parseArrayInitialiser() {
var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true,
marker = markerCreate();
expect('[');
while (!match(']')) {
if (lookahead.value === 'for' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
matchKeyword('for');
tmp = parseForStatement({ignoreBody: true});
tmp.of = tmp.type === Syntax.ForOfStatement;
tmp.type = Syntax.ComprehensionBlock;
if (tmp.left.kind) { // can't be let or const
throwError({}, Messages.ComprehensionError);
}
blocks.push(tmp);
} else if (lookahead.value === 'if' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
expectKeyword('if');
expect('(');
filter = parseExpression();
expect(')');
} else if (lookahead.value === ',' &&
lookahead.type === Token.Punctuator) {
possiblecomprehension = false; // no longer allowed.
lex();
elements.push(null);
} else {
tmp = parseSpreadOrAssignmentExpression();
elements.push(tmp);
if (tmp && tmp.type === Syntax.SpreadElement) {
if (!match(']')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
} else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) {
expect(','); // this lexes.
possiblecomprehension = false;
}
}
}
expect(']');
if (filter && !blocks.length) {
throwError({}, Messages.ComprehensionRequiresBlock);
}
if (blocks.length) {
if (elements.length !== 1) {
throwError({}, Messages.ComprehensionError);
}
return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0]));
}
return markerApply(marker, delegate.createArrayExpression(elements));
} | javascript | {
"resource": ""
} |
q64723 | parsePropertyFunction | test | function parsePropertyFunction(options) {
var previousStrict, previousYieldAllowed, previousAwaitAllowed,
params, defaults, body, marker = markerCreate();
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = options.generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = options.async;
params = options.params || [];
defaults = options.defaults || [];
body = parseConciseBody();
if (options.name && strict && isRestrictedWord(params[0].name)) {
throwErrorTolerant(options.name, Messages.StrictParamName);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(marker, delegate.createFunctionExpression(
null,
params,
defaults,
body,
options.rest || null,
options.generator,
body.type !== Syntax.BlockStatement,
options.async,
options.returnType,
options.typeParameters
));
} | javascript | {
"resource": ""
} |
q64724 | parsePostfixExpression | test | function parsePostfixExpression() {
var marker = markerCreate(),
expr = parseLeftHandSideExpressionAllowCall(),
token;
if (lookahead.type !== Token.Punctuator) {
return expr;
}
if ((match('++') || match('--')) && !peekLineTerminator()) {
// 11.3.1, 11.3.2
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPostfix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
token = lex();
expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr));
}
return expr;
} | javascript | {
"resource": ""
} |
q64725 | parseUnaryExpression | test | function parseUnaryExpression() {
var marker, token, expr;
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
return parsePostfixExpression();
}
if (match('++') || match('--')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
// 11.4.4, 11.4.5
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPrefix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (match('+') || match('-') || match('~') || match('!')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr));
if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
throwErrorTolerant({}, Messages.StrictDelete);
}
return expr;
}
return parsePostfixExpression();
} | javascript | {
"resource": ""
} |
q64726 | reinterpretAsAssignmentBindingPattern | test | function reinterpretAsAssignmentBindingPattern(expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.type === Syntax.SpreadProperty) {
if (i < len - 1) {
throwError({}, Messages.PropertyAfterSpreadProperty);
}
reinterpretAsAssignmentBindingPattern(property.argument);
} else {
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInAssignment);
}
reinterpretAsAssignmentBindingPattern(property.value);
}
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
/* istanbul ignore else */
if (element) {
reinterpretAsAssignmentBindingPattern(element);
}
}
} else if (expr.type === Syntax.Identifier) {
if (isRestrictedWord(expr.name)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
} else if (expr.type === Syntax.SpreadElement) {
reinterpretAsAssignmentBindingPattern(expr.argument);
if (expr.argument.type === Syntax.ObjectPattern) {
throwError({}, Messages.ObjectPatternAsSpread);
}
} else {
/* istanbul ignore else */
if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
throwError({}, Messages.InvalidLHSInAssignment);
}
}
} | javascript | {
"resource": ""
} |
q64727 | parseExpressionStatement | test | function parseExpressionStatement() {
var marker = markerCreate(), expr = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createExpressionStatement(expr));
} | javascript | {
"resource": ""
} |
q64728 | parseReturnStatement | test | function parseReturnStatement() {
var argument = null, marker = markerCreate();
expectKeyword('return');
if (!state.inFunctionBody) {
throwErrorTolerant({}, Messages.IllegalReturn);
}
// 'return' followed by a space and an identifier is very common.
if (source.charCodeAt(index) === 32) {
if (isIdentifierStart(source.charCodeAt(index + 1))) {
argument = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
}
}
if (peekLineTerminator()) {
return markerApply(marker, delegate.createReturnStatement(null));
}
if (!match(';')) {
if (!match('}') && lookahead.type !== Token.EOF) {
argument = parseExpression();
}
}
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
} | javascript | {
"resource": ""
} |
q64729 | extend | test | function extend(object, properties) {
var entry, result = {};
for (entry in object) {
/* istanbul ignore else */
if (object.hasOwnProperty(entry)) {
result[entry] = object[entry];
}
}
for (entry in properties) {
/* istanbul ignore else */
if (properties.hasOwnProperty(entry)) {
result[entry] = properties[entry];
}
}
return result;
} | javascript | {
"resource": ""
} |
q64730 | reflowText | test | function reflowText (text, width, gfm) {
// Hard break was inserted by Renderer.prototype.br or is
// <br /> when gfm is true
var splitRe = gfm ? HARD_RETURN_GFM_RE : HARD_RETURN_RE,
sections = text.split(splitRe),
reflowed = [];
sections.forEach(function (section) {
var words = section.split(/[ \t\n]+/),
column = 0,
nextText = '';
words.forEach(function (word) {
var addOne = column != 0;
if ((column + textLength(word) + addOne) > width) {
nextText += '\n';
column = 0;
} else if (addOne) {
nextText += " ";
column += 1;
}
nextText += word;
column += textLength(word);
});
reflowed.push(nextText);
});
return reflowed.join('\n');
} | javascript | {
"resource": ""
} |
q64731 | isAbsolute | test | function isAbsolute(fp) {
if (typeof fp !== 'string') {
throw new TypeError('isAbsolute expects a string.');
}
if (!isWindows() && isAbsolute.posix(fp)) {
return true;
}
return isAbsolute.win32(fp);
} | javascript | {
"resource": ""
} |
q64732 | repeat | test | function repeat(str, num) {
if (typeof str !== 'string') {
throw new TypeError('repeat-string expects a string.');
}
if (num === 1) return str;
if (num === 2) return str + str;
var max = str.length * num;
if (cache !== str || typeof cache === 'undefined') {
cache = str;
res = '';
}
while (max > res.length && num > 0) {
if (num & 1) {
res += str;
}
num >>= 1;
if (!num) break;
str += str;
}
return res.substr(0, max);
} | javascript | {
"resource": ""
} |
q64733 | uniqSet | test | function uniqSet(arr) {
var seen = new Set();
return arr.filter(function (el) {
if (!seen.has(el)) {
seen.add(el);
return true;
}
});
} | javascript | {
"resource": ""
} |
q64734 | error | test | function error(msg, _continue) {
if (state.error === null)
state.error = '';
state.error += state.currentCmd + ': ' + msg + '\n';
if (msg.length > 0)
log(state.error);
if (config.fatal)
process.exit(1);
if (!_continue)
throw '';
} | javascript | {
"resource": ""
} |
q64735 | wrap | test | function wrap(cmd, fn, options) {
return function() {
var retValue = null;
state.currentCmd = cmd;
state.error = null;
try {
var args = [].slice.call(arguments, 0);
if (options && options.notUnix) {
retValue = fn.apply(this, args);
} else {
if (args.length === 0 || typeof args[0] !== 'string' || args[0][0] !== '-')
args.unshift(''); // only add dummy option if '-option' not already present
retValue = fn.apply(this, args);
}
} catch (e) {
if (!state.error) {
// If state.error hasn't been set it's an error thrown by Node, not us - probably a bug...
console.log('shell.js: internal error');
console.log(e.stack || e);
process.exit(1);
}
if (config.fatal)
throw e;
}
state.currentCmd = 'shell.js';
return retValue;
};
} | javascript | {
"resource": ""
} |
q64736 | writeableDir | test | function writeableDir(dir) {
if (!dir || !fs.existsSync(dir))
return false;
if (!fs.statSync(dir).isDirectory())
return false;
var testFile = dir+'/'+common.randomFileName();
try {
fs.writeFileSync(testFile, ' ');
common.unlinkSync(testFile);
return dir;
} catch (e) {
return false;
}
} | javascript | {
"resource": ""
} |
q64737 | mkdirSyncRecursive | test | function mkdirSyncRecursive(dir) {
var baseDir = path.dirname(dir);
// Base dir exists, no recursion necessary
if (fs.existsSync(baseDir)) {
fs.mkdirSync(dir, parseInt('0777', 8));
return;
}
// Base dir does not exist, go recursive
mkdirSyncRecursive(baseDir);
// Base dir created, can create dir
fs.mkdirSync(dir, parseInt('0777', 8));
} | javascript | {
"resource": ""
} |
q64738 | splitPath | test | function splitPath(p) {
for (i=1;i<2;i++) {}
if (!p)
return [];
if (common.platform === 'win')
return p.split(';');
else
return p.split(':');
} | javascript | {
"resource": ""
} |
q64739 | updateStdout | test | function updateStdout() {
if (options.silent || !fs.existsSync(stdoutFile))
return;
var stdoutContent = fs.readFileSync(stdoutFile, 'utf8');
// No changes since last time?
if (stdoutContent.length <= previousStdoutContent.length)
return;
process.stdout.write(stdoutContent.substr(previousStdoutContent.length));
previousStdoutContent = stdoutContent;
} | javascript | {
"resource": ""
} |
q64740 | formatArgs | test | function formatArgs() {
var args = arguments;
var useColors = this.useColors;
var name = this.namespace;
if (useColors) {
var c = this.color;
args[0] = ' \u001b[3' + c + ';1m' + name + ' '
+ '\u001b[0m'
+ args[0] + '\u001b[3' + c + 'm'
+ ' +' + exports.humanize(this.diff) + '\u001b[0m';
} else {
args[0] = new Date().toUTCString()
+ ' ' + name + ' ' + args[0];
}
return args;
} | javascript | {
"resource": ""
} |
q64741 | GNTP | test | function GNTP(type, opts) {
opts = opts || {};
this.type = type;
this.host = opts.host || 'localhost';
this.port = opts.port || 23053;
this.request = 'GNTP/1.0 ' + type + ' NONE' + nl;
this.resources = [];
this.attempts = 0;
this.maxAttempts = 5;
} | javascript | {
"resource": ""
} |
q64742 | Growly | test | function Growly() {
this.appname = 'Growly';
this.notifications = undefined;
this.labels = undefined;
this.count = 0;
this.registered = false;
this.host = undefined;
this.port = undefined;
} | javascript | {
"resource": ""
} |
q64743 | Command | test | function Command(name) {
this.commands = [];
this.options = [];
this._execs = [];
this._allowUnknownOption = false;
this._args = [];
this._name = name;
} | javascript | {
"resource": ""
} |
q64744 | baseDifference | test | function baseDifference(array, values) {
var length = array ? array.length : 0,
result = [];
if (!length) {
return result;
}
var index = -1,
indexOf = baseIndexOf,
isCommon = true,
cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null,
valuesLength = values.length;
if (cache) {
indexOf = cacheIndexOf;
isCommon = false;
values = cache;
}
outer:
while (++index < length) {
var value = array[index];
if (isCommon && value === value) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === value) {
continue outer;
}
}
result.push(value);
}
else if (indexOf(values, value, 0) < 0) {
result.push(value);
}
}
return result;
} | javascript | {
"resource": ""
} |
q64745 | peek | test | function peek(p) {
var i = p || 0, j = 0, t;
while (j <= i) {
t = lookahead[j];
if (!t) {
t = lookahead[j] = lex.token();
}
j += 1;
}
// Peeking past the end of the program should produce the "(end)" token.
if (!t && state.tokens.next.id === "(end)") {
return state.tokens.next;
}
return t;
} | javascript | {
"resource": ""
} |
q64746 | identifier | test | function identifier(fnparam, prop) {
var i = optionalidentifier(fnparam, prop, false);
if (i) {
return i;
}
// parameter destructuring with rest operator
if (state.tokens.next.value === "...") {
if (!state.option.esnext) {
warning("W119", state.tokens.next, "spread/rest operator");
}
advance();
if (checkPunctuators(state.tokens.next, ["..."])) {
warning("E024", state.tokens.next, "...");
while (checkPunctuators(state.tokens.next, ["..."])) {
advance();
}
}
if (!state.tokens.next.identifier) {
warning("E024", state.tokens.curr, "...");
return;
}
return identifier(fnparam, prop);
} else {
error("E030", state.tokens.next, state.tokens.next.value);
// The token should be consumed after a warning is issued so the parser
// can continue as though an identifier were found. The semicolon token
// should not be consumed in this way so that the parser interprets it as
// a statement delimeter;
if (state.tokens.next.id !== ";") {
advance();
}
}
} | javascript | {
"resource": ""
} |
q64747 | destructuringAssignOrJsonValue | test | function destructuringAssignOrJsonValue() {
// lookup for the assignment (esnext only)
// if it has semicolons, it is a block, so go parse it as a block
// or it's not a block, but there are assignments, check for undeclared variables
var block = lookupBlockType();
if (block.notJson) {
if (!state.inESNext() && block.isDestAssign) {
warning("W104", state.tokens.curr, "destructuring assignment");
}
statements();
// otherwise parse json value
} else {
state.option.laxbreak = true;
state.jsonMode = true;
jsonValue();
}
} | javascript | {
"resource": ""
} |
q64748 | shouldGetter | test | function shouldGetter() {
if (this instanceof String || this instanceof Number || this instanceof Boolean ) {
return new Assertion(this.valueOf(), null, shouldGetter);
}
return new Assertion(this, null, shouldGetter);
} | javascript | {
"resource": ""
} |
q64749 | isA | test | function isA(object, value) {
if (_isFunction2['default'](value)) return object instanceof value;
if (value === 'array') return Array.isArray(object);
return typeof object === value;
} | javascript | {
"resource": ""
} |
q64750 | test | function(bin, opt) {
cmd = bin;
if ( opt.testing !== 'undefined') { opt.dryRun = opt.testing; }
if (typeof opt.testSuite === 'undefined') { opt.testSuite = ''; }
if (typeof opt.verbose === 'undefined') { opt.verbose = ''; }
if (typeof opt.dryRun === 'undefined') { opt.dryRun = false; }
if (typeof opt.silent === 'undefined') { opt.silent = false; }
if (typeof opt.testing === 'undefined') { opt.testing = false; }
if (typeof opt.debug === 'undefined') { opt.debug = false; }
if (typeof opt.testClass === 'undefined') { opt.testClass = ''; }
if (typeof opt.clear === 'undefined') { opt.clear = false; }
if (typeof opt.flags === 'undefined') { opt.flags = ''; }
if (typeof opt.notify === 'undefined') { opt.notify = false; }
if (typeof opt.noInteraction === 'undefined') { opt.noInteraction = true; }
if (typeof opt.noAnsi === 'undefined') { opt.noAnsi = false; }
if (typeof opt.quiet === 'undefined') { opt.quiet = false; }
if (typeof opt.formatter === 'undefined') { opt.formatter = ''; }
cmd = opt.clear ? 'clear && ' + cmd : cmd;
// assign default class and/or test suite
if (opt.testSuite) { cmd += ' ' + opt.testSuite; }
if (opt.testClass) { cmd += ' ' + opt.testClass; }
if (opt.verbose) { cmd += ' -' + opt.verbose; }
if (opt.formatter) { cmd += ' -f' + opt.formatter; }
if (opt.quiet) { cmd += ' --quiet'; }
if (opt.noInteraction) { cmd += ' --no-interaction'; }
cmd += opt.noAnsi ? ' --no-ansi' : ' --ansi';
cmd += ' ' + opt.flags;
cmd.trim(); // clean up any lingering space remnants
return cmd;
} | javascript | {
"resource": ""
} |
|
q64751 | eatNargs | test | function eatNargs (i, key, args) {
var toEat = checkAllAliases(key, opts.narg)
if (args.length - (i + 1) < toEat) error = Error(__('Not enough arguments following: %s', key))
for (var ii = i + 1; ii < (toEat + i + 1); ii++) {
setArg(key, args[ii])
}
return (i + toEat)
} | javascript | {
"resource": ""
} |
q64752 | setConfig | test | function setConfig (argv) {
var configLookup = {}
// expand defaults/aliases, in-case any happen to reference
// the config.json file.
applyDefaultsAndAliases(configLookup, aliases, defaults)
Object.keys(flags.configs).forEach(function (configKey) {
var configPath = argv[configKey] || configLookup[configKey]
if (configPath) {
try {
var config = require(path.resolve(process.cwd(), configPath))
Object.keys(config).forEach(function (key) {
// setting arguments via CLI takes precedence over
// values within the config file.
if (argv[key] === undefined || (flags.defaulted[key])) {
delete argv[key]
setArg(key, config[key])
}
})
} catch (ex) {
if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath))
}
}
})
} | javascript | {
"resource": ""
} |
q64753 | extendAliases | test | function extendAliases (obj) {
Object.keys(obj || {}).forEach(function (key) {
aliases[key] = [].concat(opts.alias[key] || [])
// For "--option-name", also set argv.optionName
aliases[key].concat(key).forEach(function (x) {
if (/-/.test(x)) {
var c = camelCase(x)
aliases[key].push(c)
newAliases[c] = true
}
})
aliases[key].forEach(function (x) {
aliases[x] = [key].concat(aliases[key].filter(function (y) {
return x !== y
}))
})
})
} | javascript | {
"resource": ""
} |
q64754 | checkAllAliases | test | function checkAllAliases (key, flag) {
var isSet = false
var toCheck = [].concat(aliases[key] || [], key)
toCheck.forEach(function (key) {
if (flag[key]) isSet = flag[key]
})
return isSet
} | javascript | {
"resource": ""
} |
q64755 | guessType | test | function guessType (key, flags) {
var type = 'boolean'
if (flags.strings && flags.strings[key]) type = 'string'
else if (flags.arrays && flags.arrays[key]) type = 'array'
return type
} | javascript | {
"resource": ""
} |
q64756 | maxWidth | test | function maxWidth (table) {
var width = 0
// table might be of the form [leftColumn],
// or {key: leftColumn}}
if (!Array.isArray(table)) {
table = Object.keys(table).map(function (key) {
return [table[key]]
})
}
table.forEach(function (v) {
width = Math.max(v[0].length, width)
})
// if we've enabled 'wrap' we should limit
// the max-width of the left-column.
if (wrap) width = Math.min(width, parseInt(wrap * 0.5, 10))
return width
} | javascript | {
"resource": ""
} |
q64757 | normalizeAliases | test | function normalizeAliases () {
var demanded = yargs.getDemanded()
var options = yargs.getOptions()
;(Object.keys(options.alias) || []).forEach(function (key) {
options.alias[key].forEach(function (alias) {
// copy descriptions.
if (descriptions[alias]) self.describe(key, descriptions[alias])
// copy demanded.
if (demanded[alias]) yargs.demand(key, demanded[alias].msg)
// type messages.
if (~options.boolean.indexOf(alias)) yargs.boolean(key)
if (~options.count.indexOf(alias)) yargs.count(key)
if (~options.string.indexOf(alias)) yargs.string(key)
if (~options.normalize.indexOf(alias)) yargs.normalize(key)
if (~options.array.indexOf(alias)) yargs.array(key)
})
})
} | javascript | {
"resource": ""
} |
q64758 | defaultString | test | function defaultString (value, defaultDescription) {
var string = '[' + __('default:') + ' '
if (value === undefined && !defaultDescription) return null
if (defaultDescription) {
string += defaultDescription
} else {
switch (typeof value) {
case 'string':
string += JSON.stringify(value)
break
case 'object':
string += JSON.stringify(value)
break
default:
string += value
}
}
return string + ']'
} | javascript | {
"resource": ""
} |
q64759 | find_attr_value | test | function find_attr_value(attrForms, attrName) {
var attrVal;
var attrPos = -1;
if(attrForms && Array.isArray(attrForms)) {
attrKey = attrForms.find(function (form, i) {
attrPos = i;
return (i % 2 === 1) && form.value === attrName;
})
if(attrKey && attrPos+1 < attrForms.length) {
attrVal = attrForms[attrPos+1];
}
}
return attrVal;
} | javascript | {
"resource": ""
} |
q64760 | test | function(options) {
options = options || {}
if (
this.passports
&& this.passports.every(t => t instanceof app.orm['Passport'])
&& options.reload !== true
) {
return Promise.resolve(this)
}
else {
return this.getPassports({transaction: options.transaction || null})
.then(passports => {
passports = passports || []
this.passports = passports
this.setDataValue('passports', passports)
this.set('passports', passports)
return this
})
}
} | javascript | {
"resource": ""
} |
|
q64761 | write | test | function write(path, str) {
fs.writeFileSync(path, str);
console.log(terminal.cyan(pad('create : ')) + path);
} | javascript | {
"resource": ""
} |
q64762 | mkdir | test | function mkdir(path, silent) {
if(!exists(path)) {
fs.mkdirSync(path, 0755);
if(!silent) console.log(terminal.cyan(pad('create : ')) + path);
}
} | javascript | {
"resource": ""
} |
q64763 | isEmptyDirectory | test | function isEmptyDirectory(path) {
var files;
try {
files = fs.readdirSync(path);
if(files.length > 0) {
return false;
}
} catch(err) {
if(err.code) {
terminal.abort('Error: ', err);
} else {
throw e;
}
}
return true;
} | javascript | {
"resource": ""
} |
q64764 | test | function(config,callback,scope) {
//
Ext.data.utilities.check('DatabaseDefinition', 'constructor', 'config', config, ['key','database_name','generation','system_name','replica_number']);
//
this.set(config);
config.config_id= 'definition';
Ext.data.DatabaseDefinition.superclass.constructor.call(this, config);
} | javascript | {
"resource": ""
} |
|
q64765 | test | function() {
var actions = this.getActions(),
previousAction = actions[actions.length - 2];
if (previousAction) {
actions.pop();
previousAction.getController().getApplication().redirectTo(previousAction.getUrl());
}
else {
actions[actions.length - 1].getController().getApplication().redirectTo('');
}
} | javascript | {
"resource": ""
} |
|
q64766 | GrelRequest | test | function GrelRequest(grel) {
var authString;
if (grel.token) {
authString = grel.token + ':';
} else {
authString = grel.user + ':' + grel.password;
}
this.headers = {
'Authorization': 'Basic ' + new Buffer(authString).toString('base64'),
'Accept': 'application/vnd.github.manifold-preview',
'User-Agent': 'Grel'
};
this.grel = grel;
this.content = null;
} | javascript | {
"resource": ""
} |
q64767 | handleResponse | test | function handleResponse(res, data, callback) {
// HTTP 204 doesn't have a response
var json = data && JSON.parse(data) || {};
if ((res.statusCode >= 200) && (res.statusCode <= 206)) {
// Handle a few known responses
switch (json.message) {
case 'Bad credentials':
callback.call(this, json);
break;
default:
callback.call(this, null, json);
}
} else {
callback.call(this, json);
}
} | javascript | {
"resource": ""
} |
q64768 | splitHeader | test | function splitHeader(content) {
// New line characters need to handle all operating systems.
const lines = content.split(/\r?\n/);
if (lines[0] !== '---') {
return {};
}
let i = 1;
for (; i < lines.length - 1; ++i) {
if (lines[i] === '---') {
break;
}
}
return {
header: lines.slice(1, i + 1).join('\n'),
content: lines.slice(i + 1).join('\n'),
};
} | javascript | {
"resource": ""
} |
q64769 | test | function(x, y, animation) {
if (this.isDestroyed) {
return this;
}
//<deprecated product=touch since=2.0>
if (typeof x != 'number' && arguments.length === 1) {
//<debug warn>
Ext.Logger.deprecate("Calling scrollTo() with an object argument is deprecated, " +
"please pass x and y arguments instead", this);
//</debug>
y = x.y;
x = x.x;
}
//</deprecated>
var translatable = this.getTranslatable(),
position = this.position,
positionChanged = false,
translationX, translationY;
if (this.isAxisEnabled('x')) {
if (isNaN(x) || typeof x != 'number') {
x = position.x;
}
else {
if (position.x !== x) {
position.x = x;
positionChanged = true;
}
}
translationX = -x;
}
if (this.isAxisEnabled('y')) {
if (isNaN(y) || typeof y != 'number') {
y = position.y;
}
else {
if (position.y !== y) {
position.y = y;
positionChanged = true;
}
}
translationY = -y;
}
if (positionChanged) {
if (animation !== undefined && animation !== false) {
translatable.translateAnimated(translationX, translationY, animation);
}
else {
this.fireEvent('scroll', this, position.x, position.y);
translatable.translate(translationX, translationY);
}
}
return this;
} | javascript | {
"resource": ""
} |
|
q64770 | test | function(animation) {
var size = this.getSize(),
cntSize = this.getContainerSize();
return this.scrollTo(size.x - cntSize.x, size.y - cntSize.y, animation);
} | javascript | {
"resource": ""
} |
|
q64771 | test | function(x, y, animation) {
var position = this.position;
x = (typeof x == 'number') ? x + position.x : null;
y = (typeof y == 'number') ? y + position.y : null;
return this.scrollTo(x, y, animation);
} | javascript | {
"resource": ""
} |
|
q64772 | test | function(config) {
var element;
this.extraConstraint = {};
this.initialConfig = config;
this.offset = {
x: 0,
y: 0
};
this.listeners = {
dragstart: 'onDragStart',
drag : 'onDrag',
dragend : 'onDragEnd',
resize : 'onElementResize',
touchstart : 'onPress',
touchend : 'onRelease',
scope: this
};
if (config && config.element) {
element = config.element;
delete config.element;
this.setElement(element);
}
return this;
} | javascript | {
"resource": ""
} |
|
q64773 | addActions | test | function addActions(actions) {
if (typeof actions === 'string') {
add(actions);
} else if (Array.isArray(actions)) {
actions.forEach(addActions);
} else if (typeof actions === 'object') {
for (var type in actions) {
add(type, actions[type]);
}
}
} | javascript | {
"resource": ""
} |
q64774 | test | function(pattern, count, sep) {
for (var buf = [], i = count; i--; ) {
buf.push(pattern);
}
return buf.join(sep || '');
} | javascript | {
"resource": ""
} |
|
q64775 | test | function(config) {
var options = new FileUploadOptions();
options.fileKey = config.fileKey || "file";
options.fileName = this.path.substr(this.path.lastIndexOf('/') + 1);
options.mimeType = config.mimeType || "image/jpeg";
options.params = config.params || {};
options.headers = config.headers || {};
options.chunkMode = config.chunkMode || true;
var fileTransfer = new FileTransfer();
fileTransfer.upload(this.path, encodeURI(config.url), config.success, config.failure, options, config.trustAllHosts || false);
return fileTransfer;
} | javascript | {
"resource": ""
} |
|
q64776 | test | function(config) {
var fileTransfer = new FileTransfer();
fileTransfer.download(
encodeURI(config.source),
this.path,
config.success,
config.failure,
config.trustAllHosts || false,
config.options || {}
);
return fileTransfer;
} | javascript | {
"resource": ""
} |
|
q64777 | test | function(property, value, anyMatch, caseSensitive) {
// Support for the simple case of filtering by property/value
if (property) {
if (Ext.isString(property)) {
this.addFilters({
property : property,
value : value,
anyMatch : anyMatch,
caseSensitive: caseSensitive
});
return this.items;
}
else {
this.addFilters(property);
return this.items;
}
}
this.items = this.mixins.filterable.filter.call(this, this.all.slice());
this.updateAfterFilter();
if (this.sorted && this.getAutoSort()) {
this.sort();
}
} | javascript | {
"resource": ""
} |
|
q64778 | test | function(fn, scope) {
var keys = this.keys,
items = this.items,
ln = keys.length, i;
for (i = 0; i < ln; i++) {
fn.call(scope || window, keys[i], items[i], i, ln);
}
} | javascript | {
"resource": ""
} |
|
q64779 | test | function(fn, scope) {
var me = this,
newCollection = new this.self(),
keys = me.keys,
items = me.all,
length = items.length,
i;
newCollection.getKey = me.getKey;
for (i = 0; i < length; i++) {
if (fn.call(scope || me, items[i], me.getKey(items[i]))) {
newCollection.add(keys[i], items[i]);
}
}
return newCollection;
} | javascript | {
"resource": ""
} |
|
q64780 | test | function(item) {
var index = this.items.indexOf(item);
if (index === -1) {
Ext.Array.remove(this.all, item);
if (typeof this.getKey == 'function') {
var key = this.getKey(item);
if (key !== undefined) {
delete this.map[key];
}
}
return item;
}
return this.removeAt(this.items.indexOf(item));
} | javascript | {
"resource": ""
} |
|
q64781 | test | function(items) {
if (items) {
var ln = items.length, i;
for (i = 0; i < ln; i++) {
this.remove(items[i]);
}
}
return this;
} | javascript | {
"resource": ""
} |
|
q64782 | test | function(item) {
if (this.dirtyIndices) {
this.updateIndices();
}
var index = item ? this.indices[this.getKey(item)] : -1;
return (index === undefined) ? -1 : index;
} | javascript | {
"resource": ""
} |
|
q64783 | test | function(item) {
var key = this.getKey(item);
if (key) {
return this.containsKey(key);
} else {
return Ext.Array.contains(this.items, item);
}
} | javascript | {
"resource": ""
} |
|
q64784 | test | function(start, end) {
var me = this,
items = me.items,
range = [],
i;
if (items.length < 1) {
return range;
}
start = start || 0;
end = Math.min(typeof end == 'undefined' ? me.length - 1 : end, me.length - 1);
if (start <= end) {
for (i = start; i <= end; i++) {
range[range.length] = items[i];
}
} else {
for (i = start; i >= end; i--) {
range[range.length] = items[i];
}
}
return range;
} | javascript | {
"resource": ""
} |
|
q64785 | test | function(fn, scope, start) {
var me = this,
keys = me.keys,
items = me.items,
i = start || 0,
ln = items.length;
for (; i < ln; i++) {
if (fn.call(scope || me, items[i], keys[i])) {
return i;
}
}
return -1;
} | javascript | {
"resource": ""
} |
|
q64786 | test | function() {
var me = this,
copy = new this.self(),
keys = me.keys,
items = me.items,
i = 0,
ln = items.length;
for(; i < ln; i++) {
copy.add(keys[i], items[i]);
}
copy.getKey = me.getKey;
return copy;
} | javascript | {
"resource": ""
} |
|
q64787 | test | function(newMonthText, oldMonthText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if ((typeof item.title == "string" && item.title == oldMonthText) || (item.title.html == oldMonthText)) {
item.setTitle(newMonthText);
}
}
}
} | javascript | {
"resource": ""
} |
|
q64788 | test | function(yearText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if (item.title == this.yearText) {
item.setTitle(yearText);
}
}
}
} | javascript | {
"resource": ""
} |
|
q64789 | test | function() {
var me = this,
slotOrder = me.getSlotOrder(),
yearsFrom = me.getYearFrom(),
yearsTo = me.getYearTo(),
years = [],
days = [],
months = [],
reverse = yearsFrom > yearsTo,
ln, i, daysInMonth;
while (yearsFrom) {
years.push({
text : yearsFrom,
value : yearsFrom
});
if (yearsFrom === yearsTo) {
break;
}
if (reverse) {
yearsFrom--;
} else {
yearsFrom++;
}
}
daysInMonth = me.getDaysInMonth(1, new Date().getFullYear());
for (i = 0; i < daysInMonth; i++) {
days.push({
text : i + 1,
value : i + 1
});
}
for (i = 0, ln = Ext.Date.monthNames.length; i < ln; i++) {
months.push({
text : Ext.Date.monthNames[i],
value : i + 1
});
}
var slots = [];
slotOrder.forEach(function (item) {
slots.push(me.createSlot(item, days, months, years));
});
me.setSlots(slots);
} | javascript | {
"resource": ""
} |
|
q64790 | test | function(name, days, months, years) {
switch (name) {
case 'year':
return {
name: 'year',
align: 'center',
data: years,
title: this.getYearText(),
flex: 3
};
case 'month':
return {
name: name,
align: 'right',
data: months,
title: this.getMonthText(),
flex: 4
};
case 'day':
return {
name: 'day',
align: 'center',
data: days,
title: this.getDayText(),
flex: 2
};
}
} | javascript | {
"resource": ""
} |
|
q64791 | test | function(user) {
if (user) {
if (!!~this.roles.indexOf('*')) {
return true;
} else {
for (var userRoleIndex in user.roles) {
for (var roleIndex in this.roles) {
if (this.roles[roleIndex] === user.roles[userRoleIndex]) {
return true;
}
}
}
}
} else {
return this.isPublic;
}
return false;
} | javascript | {
"resource": ""
} |
|
q64792 | test | function() {
var text = this.backButtonStack[this.backButtonStack.length - 2],
useTitleForBackButtonText = this.getUseTitleForBackButtonText();
if (!useTitleForBackButtonText) {
if (text) {
text = this.getDefaultBackButtonText();
}
}
return text;
} | javascript | {
"resource": ""
} |
|
q64793 | test | function(element) {
var ghost, x, y, left, width;
ghost = element.dom.cloneNode(true);
ghost.id = element.id + '-proxy';
//insert it into the toolbar
element.getParent().dom.appendChild(ghost);
//set the x/y
ghost = Ext.get(ghost);
x = element.getX();
y = element.getY();
left = element.getLeft();
width = element.getWidth();
ghost.setStyle('position', 'absolute');
ghost.setX(x);
ghost.setY(y);
ghost.setHeight(element.getHeight());
ghost.setWidth(width);
return {
x: x,
y: y,
left: left,
width: width,
ghost: ghost
};
} | javascript | {
"resource": ""
} |
|
q64794 | plugin | test | function plugin(options) {
options = options || {};
options.key = options.key || 'untemplatized';
return function(files, metalsmith, done){
setImmediate(done);
Object.keys(files).forEach(function(file){
debug('checking file: %s', file);
var data = files[file];
var contents = data.contents.toString().replace(/^\n+/g, '');
debug('storing untemplatized content: %s', file);
data[options.key] = new Buffer(contents);
});
};
} | javascript | {
"resource": ""
} |
q64795 | defaultMapFn | test | function defaultMapFn(data) {
return Object.keys(data).slice(0, this.headers.length).map(function(key) {
return data[key]
})
} | javascript | {
"resource": ""
} |
q64796 | scheduleJob | test | function scheduleJob(trigger, jobFunc, jobData) {
const job = Job.createJob(trigger, jobFunc, jobData);
const excuteTime = job.excuteTime();
const id = job.id;
map[id] = job;
const element = {
id: id,
time: excuteTime
};
const curJob = queue.peek();
if (!curJob || excuteTime < curJob.time) {
queue.offer(element);
setTimer(job);
return job.id;
}
queue.offer(element);
return job.id;
} | javascript | {
"resource": ""
} |
q64797 | defineType | test | function defineType(type, validator) {
var typeDef;
var regKey;
if (type instanceof Function) {
validator = _customValidator(type);
type = type.name;
//console.log("Custom type", typeof type, type, validator);
} else if (!(validator instanceof Function)) {
throw TypeException('Validator must be a function for `{{type}}`', null, null, { type: type });
}
typeDef = parseTypeDef(type);
regKey = typeDef.name.toLocaleLowerCase();
if (primitives[regKey]) {
throw TypeException('Cannot override primitive type `{{type}}`', null, null, { type: typeDef.name });
} else if (registry[regKey] && (registry[regKey].validator !== validator)) {
throw TypeException('Validator conflict for type `{{type}}` ', null, null, { type: typeDef.name });
}
registry[regKey] = {
type: typeDef.name,
validator: validator
};
return validator;
} | javascript | {
"resource": ""
} |
q64798 | undefineType | test | function undefineType(type) {
var validator;
var typeDef = parseTypeDef(type);
var regKey = typeDef.name.toLocaleLowerCase();
if (primitives[regKey]) {
throw TypeException('Cannot undefine primitive type `{{type}}`', null, null, { type: typeDef.name });
}
validator = registry[regKey] && registry[regKey].validator;
delete registry[regKey];
return validator || false;
} | javascript | {
"resource": ""
} |
q64799 | checkType | test | function checkType(type, value, previous, attributeName) {
var typeDef = parseTypeDef(type);
var regKey = typeDef.name.toLocaleLowerCase();
validator = primitives[regKey] || (registry[regKey] && registry[regKey].validator);
if (!validator) {
throw TypeException('Unknown type `{{type}}`', null, [ attributeName ], { type: typeDef.name });
} else if (typeDef.indexes) {
return arrayValidation(typeDef, 0, value, previous, attributeName, validator);
}
return validator(value, previous, attributeName);
} | javascript | {
"resource": ""
} |