_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q65000 | test | function (expected, expectedIndex, value) {
var i = expectedIndex - 1;
var matchingRequires = 0
while (i >= 0) {
if (!isOptionalType(expected[i]) && isOfType(value, expected[i])) {
matchingRequires++;
}
i--;
}
return matchingRequires;
} | javascript | {
"resource": ""
} |
|
q65001 | test | function (expected, actual) {
var argNames = [];
var expectedNames = [];
for (var i = 0; i < actual.length; i++) {
argNames.push(getNameForValue(actual[i]));
};
for (var i = 0; i < expected.length; i++) {
expectedNames.push(getNameForType(expected[i]));
};
return 'Expected arguments to be (' + expectedNames.join(', ') + ') but received (' +
argNames.join(', ') + ') instead.';
} | javascript | {
"resource": ""
} |
|
q65002 | test | function (value, type) {
if (!isValidType(type)) {
throw Error('Invalid type supplied.');
}
if (!isOfType(value, type)) {
argName = getNameForValue(value);
typeName = getNameForType(type);
throw Error('Expected ' + argName + ' to be an instance of ' + typeName + '.');
}
} | javascript | {
"resource": ""
} |
|
q65003 | test | function (type) {
if (type === null) return true;
if (type === undefined) return true;
if (type instanceof AnyType) return true;
if (type instanceof Array) {
// An array is only valid if it contains one or more valid types.
if (!type.length) return false;
for (var i = 0; i < type.length; i++) {
if (!isValidType(type[i])) return false;
};
return true;
}
if (type instanceof ArrayOf) return isValidType(type.type);
if (type instanceof EnumType) return (type.enumerable instanceof Object);
return (type instanceof Object);
} | javascript | {
"resource": ""
} |
|
q65004 | test | function (value) {
if (value === undefined) return 'undefined';
if (value === null) return 'null';
// Look inside the array to determine the inner type.
if (value instanceof Array) {
if (!value.length) return 'Array(empty)';
var innerType = undefined;
for (var i = 0; i < value.length; i++) {
type = getNameForValue(value[i]);
if (innerType !== undefined && innerType !== type) {
return 'Array(mixed)';
}
innerType = type;
};
return 'Array<' + innerType + '>';
}
if (value instanceof Function) {
if (value.name) return value.name;
return 'Anonymous function';
}
// Try and use the constructor to find the name of the type.
if (value instanceof Object) {
if (value.constructor) return value.constructor.name;
return 'Object';
}
// No other way to determine the name of the type, just capitilize the typeof value.
name = typeof value;
return name[0].toUpperCase() + name.substring(1);
} | javascript | {
"resource": ""
} |
|
q65005 | test | function (type) {
if (type === undefined) return 'undefined';
if (type === null) return 'null';
// Create a list of all the possible types.
if (type instanceof Array) {
if (!type.length) return 'None';
var possibleTypes = [];
for (var i = 0; i < type.length; i++) {
possibleTypes.push(getNameForType(type[i]));
};
return possibleTypes.join(' or ');
}
// Look inside the array to determine the inner type.
if (type instanceof ArrayOf) {
return 'Array<' + getNameForType(type.type) + '>';
}
// All types should be functions.
if (type instanceof Function) return type.name
return 'Invalid type';
} | javascript | {
"resource": ""
} |
|
q65006 | test | function(request) {
var me = this,
url = me.callParent(arguments),
params = Ext.apply({}, request.getParams()),
filters = params.filters,
filter, i, value;
delete params.filters;
if (me.getAutoAppendParams()) {
url = Ext.urlAppend(url, Ext.Object.toQueryString(params));
}
if (filters && filters.length) {
for (i = 0; i < filters.length; i++) {
filter = filters[i];
value = filter.getValue();
if (value) {
url = Ext.urlAppend(url, filter.getProperty() + "=" + value);
}
}
}
return url;
} | javascript | {
"resource": ""
} |
|
q65007 | getStateFromOptions | test | function getStateFromOptions (options, propertyName) {
propertyName = propertyName || 'state';
const stateName = options[propertyName] || options.resource.defaultState;
let stateObj = options.resource.states[stateName] || {validate: false};
stateObj.name = stateName;
return stateObj;
} | javascript | {
"resource": ""
} |
q65008 | validate | test | function validate (resource, doc, doValidate) {
return new Promise((resolve, reject) => {
if (doValidate !== true) {
return resolve();
}
if (resource.validate(doc)) {
return resolve();
} else {
debug('model have %d error(s)', resource.validate.errors.length);
return reject(resource.validate.errors);
}
});
} | javascript | {
"resource": ""
} |
q65009 | prune | test | function prune(str, max, nice, suf) {
max = max || 140
nice = _.isBoolean(nice) ? nice : false
if (!str || max <= 0 || str.length <= max) return str
suf = suf || "..."
str = str.substr(0, max)
return nice ? str.substr(0, Math.min(str.length, str.lastIndexOf(" "))) + suf : str
} | javascript | {
"resource": ""
} |
q65010 | attemptRender | test | function attemptRender(reporter, filename, src, resolve, reject, globals) {
globals = globals || {};
less.render(src, {
// Specify search paths for @import directives
paths : [
"public/static/less"
],
// Specify a filename, for better error messages
filename : filename,
modifyVars : globals,
compress : false
}, function(e, css) {
if (e) {
if ((/^variable @(.+?) is undefined$/).test(e.message)) {
// ignore undef variable
globals[(/^variable @(.+?) is undefined$/).exec(e.message)[1]] = "1";
attemptRender(reporter, filename, src, resolve, reject, globals);
return;
}
reporter("LESS", filename, e.line, e.message);
reject();
return;
}
resolve({
filename : filename,
src : css.css || css
});
});
} | javascript | {
"resource": ""
} |
q65011 | validateArray | test | function validateArray(indexes) {
var valid = false;
if (typeof indexes === 'string') {
if (indexes.match(TYPE_ARRAY_REGEX)) {
valid = true;
}
}
return valid;
} | javascript | {
"resource": ""
} |
q65012 | addRoutes | test | function addRoutes( pies, pie, routes, app ) {
// Add the GET routes
if ( 'get' in routes ) {
routes.get.forEach( function( route ) {
Object.keys( route ).forEach( function( r ) {
var middlewares = true;
if ( typeof route[ r ] === 'string' ) {
middlewares = false;
}
loadRoute( app, 'get', r, pies[ pie ].path, route[ r ], middlewares );
});
});
}
// Add the POST routes
if ( 'post' in routes ) {
routes.post.forEach( function( route ) {
Object.keys( route ).forEach( function( r ) {
var middlewares = true;
if ( typeof route[ r ] === 'string' ) {
middlewares = false;
}
loadRoute( app, 'post', r, pies[ pie ].path, route[ r ], middlewares );
});
});
}
} | javascript | {
"resource": ""
} |
q65013 | generateUUID | test | function generateUUID() {
let dat = new Date().getTime();
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (cha) => {
const ran = (dat + (Math.random() * 16)) % 16 | 0;
dat = Math.floor(dat / 16);
return (cha === 'x' ? ran : ran & 0x3 | 0x8).toString(16);
});
} | javascript | {
"resource": ""
} |
q65014 | randomString | test | function randomString(length, charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
let str = '',
isAllNumeric = false,
isNegative = false,
useCharSet = charSet;
if (+length) {
if (!isString(charSet)) {
if (isNumber(charSet)) {
if (+charSet) {
isAllNumeric = true;
isNegative = +charSet < 0;
useCharSet = `${Math.abs(+charSet)}`;
} else {
useCharSet = ALPHANUMERIC_CHARS;
}
} else {
useCharSet = ALPHANUMERIC_CHARS;
}
}
const generateChar = function gc(len) {
return Math.round(Math.random() * (len - 1));
}.bind(null, useCharSet.length);
str = Array(+length).fill().map((v, index) => {
const newChar = generateChar();
/* If we are generating a random number, make sure the first digit is not zero */
if (!index && isAllNumeric && !newChar) {
return useCharSet.charAt(newChar + 1);
}
return useCharSet.charAt(newChar);
}).join('');
}
if (isAllNumeric) {
return isNegative ? -+str : +str;
}
return str;
} | javascript | {
"resource": ""
} |
q65015 | toUint | test | function toUint(str) {
const string = window.btoa(unescape(encodeURIComponent(str))),
chars = string.split(''),
len = chars.length,
uintArray = [];
Array(len).fill().forEach((val, i) => uintArray.push(chars[i].charCodeAt(0)));
return new Uint8Array(uintArray);
} | javascript | {
"resource": ""
} |
q65016 | toArrayBuffer | test | function toArrayBuffer(str) {
/* eslint no-bitwise: "off" */
const len = isString(str) ? str.length : 0,
buf = new ArrayBuffer(len),
view = new Uint8Array(buf);
Array(len).fill().forEach((val, i) => (view[i] = str.charCodeAt(i) & 0xFF));
return view;
} | javascript | {
"resource": ""
} |
q65017 | test | function() {
if (!this.$backButtonContainer) {
return;
}
var i = 0,
backButtonContainer = this.$backButtonContainer,
items = backButtonContainer.items,
item;
for(;i < items.length; i++) {
item = items.get(i);
if(!item.isHidden()) {
this.$backButtonContainer.show();
return;
}
}
this.$backButtonContainer.hide();
} | javascript | {
"resource": ""
} |
|
q65018 | test | function(message, priority, callerId) {
if (!this.getEnabled()) {
return this;
}
var statics = Logger,
priorities = statics.priorities,
priorityValue = priorities[priority],
caller = this.log.caller,
callerDisplayName = '',
writers = this.getWriters(),
event, i, originalCaller;
if (!priority) {
priority = 'info';
}
if (priorities[this.getMinPriority()] > priorityValue) {
return this;
}
if (!callerId) {
callerId = 1;
}
if (Ext.isArray(message)) {
message = message.join(" ");
}
else {
message = String(message);
}
if (typeof callerId == 'number') {
i = callerId;
do {
i--;
caller = caller.caller;
if (!caller) {
break;
}
if (!originalCaller) {
originalCaller = caller.caller;
}
if (i <= 0 && caller.displayName) {
break;
}
}
while (caller !== originalCaller);
callerDisplayName = Ext.getDisplayName(caller);
}
else {
caller = caller.caller;
callerDisplayName = Ext.getDisplayName(callerId) + '#' + caller.$name;
}
event = {
time: Ext.Date.now(),
priority: priorityValue,
priorityName: priority,
message: message,
caller: caller,
callerDisplayName: callerDisplayName
};
for (i in writers) {
if (writers.hasOwnProperty(i)) {
writers[i].write(Ext.merge({}, event));
}
}
return this;
} | javascript | {
"resource": ""
} |
|
q65019 | copyFileSync | test | function copyFileSync(source, destination) {
if (validateFileSync(source)) {
fs.writeFileSync(destination, fs.readFileSync(source));
}
} | javascript | {
"resource": ""
} |
q65020 | copyFilesMatchSync | test | function copyFilesMatchSync(match, source, destination) {
fs.readdirSync(source).forEach(function eachTemplate(filename) {
var sourceFile = path.join(source, filename);
var destinationFile = path.join(destination, filename);
if (match.test(path.basename(filename))) {
fs.writeFileSync(destinationFile, fs.readFileSync(sourceFile));
}
});
} | javascript | {
"resource": ""
} |
q65021 | replaceMatchFilesSync | test | function replaceMatchFilesSync(match, source, destination) {
unlinkFilesMatchSync(match, destination);
copyFilesMatchSync(match, source, destination);
} | javascript | {
"resource": ""
} |
q65022 | unlinkFilesMatchSync | test | function unlinkFilesMatchSync(match, location) {
fs.readdirSync(location).forEach(function eachTemplate(filename) {
if (match.test(path.basename(filename))) {
var filePath = path.join(location, filename);
if (validateFileSync(filePath)) {
fs.unlinkSync(filePath);
}
}
});
} | javascript | {
"resource": ""
} |
q65023 | validateDirectorySync | test | function validateDirectorySync(path, errorMessage) {
errorMessage = errorMessage || 'Error validateDirectorySync() the directory path is not valid ' + path;
var isValid = existsDirectorySync(path);
if (!isValid) {
console.error(errorMessage);
}
return isValid;
} | javascript | {
"resource": ""
} |
q65024 | validateFileSync | test | function validateFileSync(path, errorMessage) {
errorMessage = errorMessage || 'Error validateFileSync() the file path is not valid ' + path;
var isValid = existsFileSync(path);
if (!isValid) {
console.error(errorMessage);
}
return isValid;
} | javascript | {
"resource": ""
} |
q65025 | subDirectoriesWithFile | test | function subDirectoriesWithFile(base, filename) {
var result = [];
if (fs.existsSync(base) && fs.statSync(base).isDirectory()) {
if (fs.existsSync(path.join(base, filename))) {
result.push(base);
}
fs.readdirSync(base)
.forEach(function (subdir) {
result.push.apply(result, subDirectoriesWithFile(path.join(base, subdir), filename));
});
}
return result;
} | javascript | {
"resource": ""
} |
q65026 | maximisePath | test | function maximisePath() {
// Ensure each element in the path exists,
// where it is a regex, match it and replace the element with a string
var elements = Array.prototype.slice.call(arguments);
for (var i = 1; i < elements.length; i++) {
// the directory is elements 0 .. i-1 joined
var directory = path.resolve(path.join.apply(path, elements.slice(0, i)));
// no directory implies failure
if (!fs.existsSync(directory)) {
return null;
}
// regex element is matched
else if ((typeof elements[i] !== 'string') && ('test' in elements[i])) {
var matches = resolveDirMatches(directory, elements[i]);
// no match implies failure, else use the item with the highest numeric index
if (matches.length === 0) {
return null;
} else {
elements[i] = matches[0];
}
}
// anything else is cast to string
else {
elements[i] = String(elements[i]);
}
}
// now join them all together
// do a final check to make sure it exists
var result = path.resolve(elements.join(path.sep));
return fs.existsSync(result) && result;
} | javascript | {
"resource": ""
} |
q65027 | resolveDirMatches | test | function resolveDirMatches(directory, match) {
if (validateDirectorySync(directory)) {
return fs.readdirSync(directory)
.filter(function eachDirectoryItem(item) {
var resolved = path.resolve(path.join(directory, item));
return match.test(item) && fs.statSync(resolved).isDirectory();
})
.sort(compareHigher);
} else {
return [];
}
} | javascript | {
"resource": ""
} |
q65028 | compareHigher | test | function compareHigher(a, b) {
var numA = parseFloat(/[\d\.]+$/.exec(a)[0]);
var numB = parseFloat(/[\d\.]+$/.exec(b)[0]);
if (isNaN(numA) || (numB > numA)) {
return +1;
} else if (isNaN(numB) || (numA > numB)) {
return -1;
} else {
return 0;
}
} | javascript | {
"resource": ""
} |
q65029 | reduceDirectories | test | function reduceDirectories() {
return Array.prototype.slice.call(arguments)
.map(function (candidate) {
return path.normalize(candidate);
})
.filter(function (candidate) {
return fs.existsSync(candidate) && fs.statSync(candidate).isDirectory();
})
.shift();
} | javascript | {
"resource": ""
} |
q65030 | test | function(side) {
var menus = this.getMenus() || {},
menu = menus[side];
if(menu) this.hideMenu(side);
delete menus[side];
this.setMenus(menus);
} | javascript | {
"resource": ""
} |
|
q65031 | test | function(side) {
var menus = this.getMenus(),
menu = menus[side],
before, after,
viewportBefore, viewportAfter;
if (!menu || menu.isAnimating) {
return;
}
this.hideOtherMenus(side);
before = {
translateX: 0,
translateY: 0
};
after = {
translateX: 0,
translateY: 0
};
viewportBefore = {
translateX: 0,
translateY: 0
};
viewportAfter = {
translateX: 0,
translateY: 0
};
if (menu.$reveal) {
Ext.getBody().insertFirst(menu.element);
}
else {
Ext.Viewport.add(menu);
}
menu.show();
menu.addCls('x-' + side);
var size = (side == 'left' || side == 'right') ? menu.element.getWidth() : menu.element.getHeight();
if (side == 'left') {
before.translateX = -size;
viewportAfter.translateX = size;
}
else if (side == 'right') {
before.translateX = size;
viewportAfter.translateX = -size;
}
else if (side == 'top') {
before.translateY = -size;
viewportAfter.translateY = size;
}
else if (side == 'bottom') {
before.translateY = size;
viewportAfter.translateY = -size;
}
if (menu.$reveal) {
if (Ext.browser.getPreferredTranslationMethod() != 'scrollposition') {
menu.translate(0, 0);
}
}
else {
menu.translate(before.translateX, before.translateY);
}
if (menu.$cover) {
menu.getTranslatable().on('animationend', function() {
menu.isAnimating = false;
}, this, {
single: true
});
menu.translate(after.translateX, after.translateY, {
preserveEndState: true,
duration: 200
});
}
else {
this.translate(viewportBefore.translateX, viewportBefore.translateY);
this.getTranslatable().on('animationend', function() {
menu.isAnimating = false;
}, this, {
single: true
});
this.translate(viewportAfter.translateX, viewportAfter.translateY, {
preserveEndState: true,
duration: 200
});
}
// Make the menu as animating
menu.isAnimating = true;
} | javascript | {
"resource": ""
} |
|
q65032 | test | function(side, animate) {
var menus = this.getMenus(),
menu = menus[side],
after, viewportAfter,
size;
animate = (animate === false) ? false : true;
if (!menu || (menu.isHidden() || menu.isAnimating)) {
return;
}
after = {
translateX: 0,
translateY: 0
};
viewportAfter = {
translateX: 0,
translateY: 0
};
size = (side == 'left' || side == 'right') ? menu.element.getWidth() : menu.element.getHeight();
if (side == 'left') {
after.translateX = -size;
}
else if (side == 'right') {
after.translateX = size;
}
else if (side == 'top') {
after.translateY = -size;
}
else if (side == 'bottom') {
after.translateY = size;
}
if (menu.$cover) {
if (animate) {
menu.getTranslatable().on('animationend', function() {
menu.isAnimating = false;
menu.hide();
}, this, {
single: true
});
menu.translate(after.translateX, after.translateY, {
preserveEndState: true,
duration: 200
});
}
else {
menu.translate(after.translateX, after.translateY);
menu.hide()
}
}
else {
if (animate) {
this.getTranslatable().on('animationend', function() {
menu.isAnimating = false;
menu.hide();
}, this, {
single: true
});
this.translate(viewportAfter.translateX, viewportAfter.translateY, {
preserveEndState: true,
duration: 200
});
}
else {
this.translate(viewportAfter.translateX, viewportAfter.translateY);
menu.hide();
}
}
} | javascript | {
"resource": ""
} |
|
q65033 | test | function(side, animation){
var menus = this.getMenus();
for (var menu in menus) {
if (side != menu) {
this.hideMenu(menu, animation);
}
}
} | javascript | {
"resource": ""
} |
|
q65034 | test | function(side) {
var menus = this.getMenus(), menu;
if (menus[side]) {
menu = menus[side];
if (menu.isHidden()) {
this.showMenu(side);
} else {
this.hideMenu(side);
}
}
} | javascript | {
"resource": ""
} |
|
q65035 | init | test | function init(adapter, config) {
if (!fs) {
var Adapter = require('./adapters/' + adapter);
fs = new Adapter(config);
}
} | javascript | {
"resource": ""
} |
q65036 | getHierarchy | test | function getHierarchy(cb) {
getConfig(function (err, config) {
if (err) {
cb(err);
return;
}
cb(null, config[':hierarchy']);
});
} | javascript | {
"resource": ""
} |
q65037 | getBackends | test | function getBackends(cb) {
getConfig(function (err, config) {
if (err) {
cb(err);
return;
}
cb(null, config[':backends']);
});
} | javascript | {
"resource": ""
} |
q65038 | getBackendConfig | test | function getBackendConfig(backend, cb) {
getConfig(function (err, config) {
if (err) {
cb(err);
return;
}
cb(null, config[':' + backend]);
});
} | javascript | {
"resource": ""
} |
q65039 | getFile | test | function getFile(backend, file, cb) {
getBackendConfig(backend, function (err, config) {
file = [ config[':datadir'], '/', file ].join('');
fs.readFile(file, cb);
});
} | javascript | {
"resource": ""
} |
q65040 | saveFile | test | function saveFile(backend, file, data, cb) {
cb = typeof(cb) === 'function' ? cb : function () {};
getBackendConfig(backend, function (err, config) {
var datadir = config[':datadir'];
file = path.join(datadir, file);
fs.writeFile(file, data, cb);
});
} | javascript | {
"resource": ""
} |
q65041 | getOverrides | test | function getOverrides(backend, file, cb) {
async.parallel([
function hierarchy(cb) {
getHierarchy(cb);
},
function backendConfig(cb) {
getBackendConfig(backend, cb);
}
], function (err, results) {
var hierarchy, datadir, filename, tasks,
pos, searchHierarchy, tasks;
hierarchy = results[0];
datadir = results[1][':datadir'];
filename = file.remove('.' + backend);
tasks = [];
// remove the file's matching hierarchy
pos = hierarchy.findIndex(filename);
searchHierarchy = hierarchy.to(pos);
getFile(backend, file, function (err, data) {
var sourceData;
if (err) {
cb(err);
return;
}
sourceData = yaml.safeLoad(data);
// setup hierarchy search tasks
_.each(searchHierarchy, function (hierarchy) {
tasks.push(hierarchy + '.' + backend);
});
async.map(tasks, function (f, cb) {
// get data for each file in the hierarchy
// TODO: support magic hiera vars
getFile(backend, f, function (err, data) {
cb(null, {
file : f,
data : yaml.safeLoad(data)
});
});
}, function (err, comparisonData) {
var list = {};
if (err) {
cb(err);
return;
}
_.each(sourceData, function (key, value) {
_.each(comparisonData, function (set) {
_.each(set.data, function (cKey, cValue) {
if (cKey === key) {
list[cKey] = {
file : set.file,
value : cValue
};
}
});
if (list[key]) {
// already exists
return false;
}
});
});
cb(null, list);
});
});
});
} | javascript | {
"resource": ""
} |
q65042 | done | test | function done(result, callback) {
if (!_.isFunction(callback)) return
process.nextTick(function () { callback(null, result) })
} | javascript | {
"resource": ""
} |
q65043 | fail | test | function fail(err, callback) {
if (!_.isFunction(callback)) return
let uError = new Error('Unknown Error')
err = err ? _.isError(err) ? err : _.isString(err) ? new Error(err) : uError : uError
process.nextTick(function () { callback(err) })
} | javascript | {
"resource": ""
} |
q65044 | test | function(data) {
var fieldsCollection = this.getModel().getFields();
/*
* We check here whether the fields are dirty since the last read.
* This works around an issue when a Model is used for both a Tree and another
* source, because the tree decorates the model with extra fields and it causes
* issues because the readers aren't notified.
*/
if (fieldsCollection.isDirty) {
this.buildExtractors(true);
delete fieldsCollection.isDirty;
}
if (this.rootAccessor) {
return this.rootAccessor.call(this, data);
} else {
return data;
}
} | javascript | {
"resource": ""
} |
|
q65045 | arrIncludes | test | function arrIncludes (arr, values) {
if (!Array.isArray(values)) { return inArray(arr, values) }
var len = values.length;
var i = -1;
while (i++ < len) {
var j = inArray(arr, values[i]);
if (j) {
return j
}
}
return false
} | javascript | {
"resource": ""
} |
q65046 | clean | test | function clean(src) {
let pidx = src.indexOf('http')
if(pidx > 0) src = src.substr(pidx)
return src ? pidx >= 0 || src.indexOf('//') >= 0 ? src : '/' + src : ''
} | javascript | {
"resource": ""
} |
q65047 | jquery | test | function jquery(src) {
src = clean(src);
let params = {}
let match = null
if (!url || !_.isString(src)) return params
while (match = REGX_QUERY_OBJECT.exec(src)) { params[match[1]] = match[2] }
return params
} | javascript | {
"resource": ""
} |
q65048 | test | function (el, options) {
events.EventEmitter.call(this);
this.el = el;
this.options = extend({}, this.options);
extend(this.options, options);
this.showTab = this._show;
this._init();
} | javascript | {
"resource": ""
} |
|
q65049 | toParam | test | function toParam(obj, dontEncode) {
const arr = [];
let vals;
if (isObject(obj) && !isArray(obj)) {
Object.keys(obj).forEach((val) => {
if (isArray(obj[val])) {
vals = `[${
obj[val].map(v => (isNaN(v) ? `"${v}"` : v)).join(',')
}]`;
} else {
vals = isNaN(obj[val]) ? `"${obj[val]}"` : obj[val];
}
arr.push(`${val}:${vals}`);
});
if (dontEncode) {
return `{${arr.join(',')}}`;
}
return encodeURIComponent(`{${arr.join(',')}}`);
}
return '';
} | javascript | {
"resource": ""
} |
q65050 | test | function(anchor, local, size) {
//<debug warn>
Ext.Logger.deprecate("getAnchorXY() is no longer available for Ext.Element. Please see Ext.Component#showBy() " +
"to do anchoring at Component level instead", this);
//</debug>
//Passing a different size is useful for pre-calculating anchors,
//especially for anchored animations that change the el size.
anchor = (anchor || "tl").toLowerCase();
size = size || {};
var me = this,
vp = me.dom == document.body || me.dom == document,
width = size.width || vp ? window.innerWidth: me.getWidth(),
height = size.height || vp ? window.innerHeight: me.getHeight(),
xy,
rnd = Math.round,
myXY = me.getXY(),
extraX = vp ? 0: !local ? myXY[0] : 0,
extraY = vp ? 0: !local ? myXY[1] : 0,
hash = {
c: [rnd(width * 0.5), rnd(height * 0.5)],
t: [rnd(width * 0.5), 0],
l: [0, rnd(height * 0.5)],
r: [width, rnd(height * 0.5)],
b: [rnd(width * 0.5), height],
tl: [0, 0],
bl: [0, height],
br: [width, height],
tr: [width, 0]
};
xy = hash[anchor];
return [xy[0] + extraX, xy[1] + extraY];
} | javascript | {
"resource": ""
} |
|
q65051 | test | function(fn, scope){
var items = [].concat(this.items), // each safe for removal
i = 0,
len = items.length,
item;
for (; i < len; i++) {
item = items[i];
if (fn.call(scope || item, item, i, len) === false) {
break;
}
}
} | javascript | {
"resource": ""
} |
|
q65052 | test | function(config) {
if (config.path == null) {
Ext.Logger.error('Ext.device.filesystem.DirectoryEntry#getFile: You must specify a `path` of the file.');
return null;
}
if (config.options == null) {
config.options = {};
}
var me = this;
Ext.device.Communicator.send({
command: 'FileSystem#getEntry',
path: this.path,
fileSystemId: this.fileSystem.id,
newPath: config.path,
directory: config.directory,
create: config.options.create,
exclusive: config.options.exclusive,
callbacks: {
success: function(path) {
if (config.success) {
var entry = config.directory
? Ext.create('Ext.device.filesystem.DirectoryEntry', path, me.fileSystem)
: Ext.create('Ext.device.filesystem.FileEntry', path, me.fileSystem);
config.success.call(config.scope || this, entry);
}
},
failure: function(error) {
if (config.failure) {
config.failure.call(config.scope || this, error);
}
}
},
scope: config.scope || this
});
} | javascript | {
"resource": ""
} |
|
q65053 | toHaveText | test | function toHaveText() {
return {
compare: function compare(element, text) {
var regexp = text instanceof RegExp ? text : new RegExp(text, 'ig');
var pass = element.getDOMNode().textContent.match(regexp);
var message = pass ? 'Text "' + text + '" is found within an element' : 'Text "' + text + '" is not found within an element';
return { pass: pass, message: message };
}
};
} | javascript | {
"resource": ""
} |
q65054 | test | function() {
var me = this,
container = me.container,
baseCls = me.getBaseCls(),
scrollable, scrollViewElement, pinnedHeader;
Ext.apply(me, {
listItems: [],
headerItems: [],
updatedItems: [],
headerMap: [],
scrollDockItems: {
top: [],
bottom: []
}
});
// We determine the translation methods for headers and items within this List based
// on the best strategy for the device
this.translationMethod = Ext.browser.is.AndroidStock2 ? 'cssposition' : 'csstransform';
// Create the inner container that will actually hold all the list items
if (!container) {
container = me.container = Ext.factory({
xtype: 'container',
scrollable: {
scroller: {
autoRefresh: !me.getInfinite(),
direction: 'vertical'
}
}
});
}
// We add the container after creating it manually because when you add the container,
// the items config is initialized. When this happens, any scrollDock items will be added,
// which in turn tries to add these items to the container
me.add(container);
// We make this List's scrollable the inner containers scrollable
scrollable = container.getScrollable();
scrollViewElement = me.scrollViewElement = scrollable.getElement();
me.scrollElement = scrollable.getScroller().getElement();
me.setScrollable(scrollable);
me.scrollableBehavior = container.getScrollableBehavior();
// Create the pinnedHeader instance thats being used when grouping is enabled
// and insert it into the scrollElement
pinnedHeader = me.pinnedHeader = Ext.factory({
xtype: 'listitemheader',
html: ' ',
translatable: {
translationMethod: this.translationMethod
},
cls: [baseCls + '-header', baseCls + '-header-swap']
});
pinnedHeader.translate(0, -10000);
pinnedHeader.$position = -10000;
scrollViewElement.insertFirst(pinnedHeader.renderElement);
// We want to intercept any translate calls made on the scroller to perform specific list logic
me.bind(scrollable.getScroller().getTranslatable(), 'doTranslate', 'onTranslate');
} | javascript | {
"resource": ""
} |
|
q65055 | test | function() {
var me = this,
container = me.container,
scrollViewElement = me.scrollViewElement,
indexBar = me.getIndexBar(),
triggerEvent = me.getTriggerEvent(),
triggerCtEvent = me.getTriggerCtEvent();
if (indexBar) {
scrollViewElement.appendChild(indexBar.renderElement);
}
if (triggerEvent) {
me.on(triggerEvent, me.onItemTrigger, me);
}
if (triggerCtEvent) {
me.on(triggerCtEvent, me.onContainerTrigger, me);
}
container.element.on({
delegate: '.' + me.getBaseCls() + '-disclosure',
tap: 'handleItemDisclosure',
scope: me
});
container.element.on({
resize: 'onContainerResize',
scope: me
});
// Android 2.x not a direct child
container.innerElement.on({
touchstart: 'onItemTouchStart',
touchend: 'onItemTouchEnd',
tap: 'onItemTap',
taphold: 'onItemTapHold',
singletap: 'onItemSingleTap',
doubletap: 'onItemDoubleTap',
swipe: 'onItemSwipe',
delegate: '.' + Ext.baseCSSPrefix + 'list-item',
scope: me
});
if (me.getStore()) {
me.refresh();
}
} | javascript | {
"resource": ""
} |
|
q65056 | test | function(index) {
var listItems = this.listItems,
ln = listItems.length,
i, listItem;
for (i = 0; i < ln; i++) {
listItem = listItems[i];
if (listItem.$dataIndex == index) {
return listItem;
}
}
} | javascript | {
"resource": ""
} |
|
q65057 | test | function(url, onLoad, onError, scope, charset) {
var script = document.createElement('script'),
me = this,
onLoadFn = function() {
me.cleanupScriptElement(script);
onLoad.call(scope);
},
onErrorFn = function() {
me.cleanupScriptElement(script);
onError.call(scope);
};
script.type = 'text/javascript';
script.src = url;
script.onload = onLoadFn;
script.onerror = onErrorFn;
script.onreadystatechange = function() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
onLoadFn();
}
};
if (charset) {
script.charset = charset;
}
this.documentHead.appendChild(script);
return script;
} | javascript | {
"resource": ""
} |
|
q65058 | test | function(url, onLoad, onError, scope, synchronous) {
var me = this,
isFileLoaded = this.isFileLoaded,
scriptElements = this.scriptElements,
noCacheUrl = url + (this.getConfig('disableCaching') ? ('?' + this.getConfig('disableCachingParam') + '=' + Ext.Date.now()) : ''),
xhr, status, content, onScriptError;
if (isFileLoaded[url]) {
return this;
}
scope = scope || this;
this.isLoading = true;
if (!synchronous) {
onScriptError = function() {
//<debug error>
onError.call(scope, "Failed loading '" + url + "', please verify that the file exists", synchronous);
//</debug>
};
if (!Ext.isReady && Ext.onDocumentReady) {
Ext.onDocumentReady(function() {
if (!isFileLoaded[url]) {
scriptElements[url] = me.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
}
});
}
else {
scriptElements[url] = this.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
}
}
else {
if (typeof XMLHttpRequest != 'undefined') {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
try {
xhr.open('GET', noCacheUrl, false);
xhr.send(null);
}
catch (e) {
//<debug error>
onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; It's likely that the file is either " +
"being loaded from a different domain or from the local file system whereby cross origin " +
"requests are not allowed due to security reasons. Use asynchronous loading with " +
"Ext.require instead.", synchronous);
//</debug>
}
status = (xhr.status == 1223) ? 204 : xhr.status;
content = xhr.responseText;
if ((status >= 200 && status < 300) || status == 304 || (status == 0 && content.length > 0)) {
// Debugger friendly, file names are still shown even though they're eval'ed code
// Breakpoints work on both Firebug and Chrome's Web Inspector
Ext.globalEval(content + "\n//@ sourceURL=" + url);
onLoad.call(scope);
}
else {
//<debug>
onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; please " +
"verify that the file exists. " +
"XHR status code: " + status, synchronous);
//</debug>
}
// Prevent potential IE memory leak
xhr = null;
}
} | javascript | {
"resource": ""
} |
|
q65059 | test | async function (fname, attrs) {
let partialDirs;
if (typeof module.exports.configuration.partialDirs === 'undefined'
|| !module.exports.configuration.partialDirs
|| module.exports.configuration.partialDirs.length <= 0) {
partialDirs = [ __dirname ];
} else {
partialDirs = module.exports.configuration.partialDirs;
}
var partialFound = await globfs.findAsync(partialDirs, fname);
if (!partialFound) throw new Error(`No partial found for ${fname} in ${util.inspect(partialDirs)}`);
// Pick the first partial found
partialFound = partialFound[0];
// console.log(`module.exports.configuration renderPartial ${partialFound}`);
if (!partialFound) throw new Error(`No partial found for ${fname} in ${util.inspect(partialDirs)}`);
var partialFname = path.join(partialFound.basedir, partialFound.path);
var stats = await fs.stat(partialFname);
if (!stats.isFile()) {
throw new Error(`doPartialAsync non-file found for ${fname} - ${partialFname}`);
}
var partialText = await fs.readFile(partialFname, 'utf8');
if (/\.ejs$/i.test(partialFname)) {
try { return ejs.render(partialText, attrs); } catch (e) {
throw new Error(`EJS rendering of ${fname} failed because of ${e}`);
}
} /* else if (/\.literal$/i.test(partialFname)) {
try {
const t = literal(partialText);
return t(attrs);
} catch (e) {
throw new Error(`Literal rendering of ${fname} failed because of ${e}`);
}
} */ else if (/\.html$/i.test(partialFname)) {
// NOTE: The partialBody gets lost in this case
return partialText;
} else {
throw new Error("No rendering support for ${fname}");
}
} | javascript | {
"resource": ""
} |
|
q65060 | test | function (record) {
var me = this,
fields = record.getFields(),
idProperty = record.getIdProperty(),
uniqueIdStrategy = me.getUniqueIdStrategy(),
data = {},
name, value;
fields.each(function (field) {
if (field.getPersist()) {
name = field.getName();
if (name === idProperty && !uniqueIdStrategy) {
return;
}
value = record.get(name);
if (field.getType().type == 'date') {
value = me.writeDate(field, value);
}
data[name] = value;
}
}, me);
return data;
} | javascript | {
"resource": ""
} |
|
q65061 | test | function(provider) {
var me = this,
args = Ext.toArray(arguments),
i = 0, ln;
if (args.length > 1) {
for (ln = args.length; i < ln; ++i) {
me.addProvider(args[i]);
}
return;
}
// if provider has not already been instantiated
if (!provider.isProvider) {
provider = Ext.create('direct.' + provider.type + 'provider', provider);
}
me.providers.add(provider);
provider.on('data', me.onProviderData, me);
if (!provider.isConnected()) {
provider.connect();
}
return provider;
} | javascript | {
"resource": ""
} |
|
q65062 | test | function(provider) {
var me = this,
providers = me.providers;
provider = provider.isProvider ? provider : providers.get(provider);
if (provider) {
provider.un('data', me.onProviderData, me);
providers.remove(provider);
return provider;
}
return null;
} | javascript | {
"resource": ""
} |
|
q65063 | test | function(config) {
config = config || {};
Ext.applyIf(config, {
application: this
});
this.initConfig(config);
//it's common to pass in functions to an application but because they are not predictable config names they
//aren't ordinarily placed onto this so we need to do it manually
for (var key in config) {
this[key] = config[key];
}
// <deprecated product=touch since=2.0>
if (config.autoCreateViewport) {
Ext.Logger.deprecate(
'[Ext.app.Application] autoCreateViewport has been deprecated in Sencha Touch 2. Please implement a ' +
'launch function on your Application instead and use Ext.create("MyApp.view.Main") to create your initial UI.'
);
}
// </deprecated>
//<debug>
Ext.Loader.setConfig({ enabled: true });
//</debug>
Ext.require(this.getRequires(), function() {
if (this.getEnableLoader() !== false) {
Ext.require(this.getProfiles(), this.onProfilesLoaded, this);
}
}, this);
} | javascript | {
"resource": ""
} |
|
q65064 | test | function(name, profileName) {
var instances = this.getControllerInstances(),
appName = this.getName(),
format = Ext.String.format,
topLevelName;
if (name instanceof Ext.app.Controller) {
return name;
}
if (instances[name]) {
return instances[name];
} else {
topLevelName = format("{0}.controller.{1}", appName, name);
profileName = format("{0}.controller.{1}.{2}", appName, profileName, name);
return instances[profileName] || instances[topLevelName];
}
} | javascript | {
"resource": ""
} |
|
q65065 | test | function() {
delete this.onItemAdd;
if (this.innerHtmlElement && !this.getHtml()) {
this.innerHtmlElement.destroy();
delete this.innerHtmlElement;
}
this.on('innerstatechange', 'onItemInnerStateChange', this, {
delegate: '> component'
});
return this.onItemAdd.apply(this, arguments);
} | javascript | {
"resource": ""
} |
|
q65066 | test | function(item, destroy) {
var me = this,
index = me.indexOf(item),
innerItems = me.getInnerItems();
if (destroy === undefined) {
destroy = me.getAutoDestroy();
}
if (index !== -1) {
if (!me.removingAll && innerItems.length > 1 && item === me.getActiveItem()) {
me.on({
activeitemchange: 'doRemove',
scope: me,
single: true,
order: 'after',
args: [item, index, destroy]
});
me.doResetActiveItem(innerItems.indexOf(item));
}
else {
me.doRemove(item, index, destroy);
if (innerItems.length === 0) {
me.setActiveItem(null);
}
}
}
return me;
} | javascript | {
"resource": ""
} |
|
q65067 | test | function(destroy, everything) {
var items = this.items,
ln = items.length,
i = 0,
item;
if (typeof destroy != 'boolean') {
destroy = this.getAutoDestroy();
}
everything = Boolean(everything);
// removingAll flag is used so we don't unnecessarily change activeItem while removing all items.
this.removingAll = true;
for (; i < ln; i++) {
item = items.getAt(i);
if (item && (everything || item.isInnerItem())) {
this.doRemove(item, i, destroy);
i--;
ln--;
}
}
this.setActiveItem(null);
this.removingAll = false;
return this;
} | javascript | {
"resource": ""
} |
|
q65068 | test | function(activeItem, animation) {
var layout = this.getLayout(),
defaultAnimation;
if (this.activeItemAnimation) {
this.activeItemAnimation.destroy();
}
this.activeItemAnimation = animation = new Ext.fx.layout.Card(animation);
if (animation && layout.isCard) {
animation.setLayout(layout);
defaultAnimation = layout.getAnimation();
if (defaultAnimation) {
defaultAnimation.disable();
}
animation.on('animationend', function() {
if (defaultAnimation) {
defaultAnimation.enable();
}
animation.destroy();
}, this);
}
return this.setActiveItem(activeItem);
} | javascript | {
"resource": ""
} |
|
q65069 | test | function(deep) {
var items = this.getItems().items.slice(),
ln = items.length,
i, item;
if (deep) {
for (i = 0; i < ln; i++) {
item = items[i];
if (item.getRefItems) {
items = items.concat(item.getRefItems(true));
}
}
}
return items;
} | javascript | {
"resource": ""
} |
|
q65070 | test | function(e) {
var srcElement = e.srcElement.nodeName.toUpperCase(),
selectableElements = ['INPUT', 'TEXTAREA'];
if (selectableElements.indexOf(srcElement) == -1) {
return false;
}
} | javascript | {
"resource": ""
} |
|
q65071 | test | function(number, min, max) {
number = parseFloat(number);
if (!isNaN(min)) {
number = Math.max(number, min);
}
if (!isNaN(max)) {
number = Math.min(number, max);
}
return number;
} | javascript | {
"resource": ""
} |
|
q65072 | test | function(value, increment, minValue, maxValue) {
var newValue = value,
m;
if (!(increment && value)) {
return value;
}
m = value % increment;
if (m !== 0) {
newValue -= m;
if (m * 2 >= increment) {
newValue += increment;
} else if (m * 2 < -increment) {
newValue -= increment;
}
}
return Ext.Number.constrain(newValue, minValue, maxValue);
} | javascript | {
"resource": ""
} |
|
q65073 | test | function(value, precision) {
if (isToFixedBroken) {
precision = precision || 0;
var pow = Math.pow(10, precision);
return (Math.round(value * pow) / pow).toFixed(precision);
}
return value.toFixed(precision);
} | javascript | {
"resource": ""
} |
|
q65074 | logger | test | function logger(req, res, next) {
if (req.url.substr(0, 2) === "/r") {
console.log(req.method, decodeURIComponent(req.url), req.body ? JSON.stringify(req.body) : "");
}
next();
} | javascript | {
"resource": ""
} |
q65075 | typeConvert | test | function typeConvert(obj, onlyDate) {
var i, res;
if (typeof obj === "object") {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
obj[i] = typeConvert(obj[i], onlyDate);
}
}
} else if (typeof obj === "string") {
if (!onlyDate && obj.match(/^([0-9.]+|true|false|undefined|null)$/)) {
obj = eval(obj);
} else {
res = obj.match(/^"?(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)"?$/);
if (res) {
obj = new Date(res[1]);
}
}
}
return obj;
} | javascript | {
"resource": ""
} |
q65076 | typeConvertMiddleware | test | function typeConvertMiddleware(req, res, next) {
typeConvert(req.params);
typeConvert(req.body, true);
next();
} | javascript | {
"resource": ""
} |
q65077 | defineRoute | test | function defineRoute(method, route, handler) {
server[method](route, function (req, res) {
var store = stores.get(req.params.resource);
delete req.params.resource;
handler(req, store, function (error, docs) {
if (error) {
res.status(500);
res.end(error);
} else if (!docs) {
res.status(404);
res.end("Not found");
} else {
res.json(docs);
}
});
});
} | javascript | {
"resource": ""
} |
q65078 | routeURL | test | function routeURL() {
var prefix = options.prefix || "",
args = ["/" + prefix, ":resource"].concat(Array.prototype.slice.call(arguments));
return path.join.apply(path, args);
} | javascript | {
"resource": ""
} |
q65079 | createPasswordHash | test | function createPasswordHash(object) {
if (!object) return object;
var password = object.password;
if (password) {
delete object.password;
object.passwordSalt = sha1(Math.random().toString());
object.passwordHash = sha1("restify-magic" + object.passwordSalt + password);
}
return object;
} | javascript | {
"resource": ""
} |
q65080 | test | function( json, typeSpecification, array ) {
var keys,
current = json,
nested = [],
nestedKeys = [],
levels = [],
query = 'COLUMN_CREATE(',
root = true,
curNest = '',
curItem,
item = 0,
level = 0;
while( current ) {
keys = Object.keys( current );
var len = keys.length;
var _l;
var deepestLevel = 1;
for( var i = 0; i < len; ++i ) {
if( ( _l = current[ keys[ i ] ] ) === null || _l === undefined ) {
continue;
}
if( typeof( _l ) === 'object' ) {
// skip empty objects, we do not store them,
// this needs us to set NULL instead
if( !Object.keys( _l ).length ) {
_l = null;
if( !typeSpecification ) {
query += '\'' + keys[ i ].replace(/\\/g, '\\\\')
.replace(/\u0008/g, '\\b')
.replace(/'/g, '\\\'')
.replace(/\u0000/g, '\\0') + '\', NULL, ';
}
else {
query += '?, NULL, ';
array.push( keys[ i ] );
}
continue;
}
nested.push( _l );
nestedKeys.push( keys[ i ] );
if ( curItem !== item ) {
curItem = item;
++level;
levels.push( { level: level - 1, nestSep: curNest + ')' } );
}
else {
levels.push( { level: level - 1, nestSep: ')' } );
}
//save nesting level
}
else {
var queryType = typeof( _l );
if( !typeSpecification ) {
query += '\'' + keys[ i ].replace(/\\/g, '\\\\')
.replace(/\u0008/g, '\\b')
.replace(/'/g, '\\\'')
.replace(/\u0000/g, '\\0') + '\', ';
}
else {
query += '?, ';
array.push( keys[ i ] );
}
switch( queryType ) {
case 'boolean':
query += ( ( _l === true ) ? 1 : 0 ) + ' AS unsigned integer, ';
break;
case 'number':
query += _l + ' AS double, ';
break;
default:
if( !typeSpecification ) {
query += '\'' + _l.replace(/\\/g, '\\\\')
.replace(/\u0008/g, '\\b')
.replace(/'/g, '\\\'')
.replace(/\u0000/g, '\\0') + '\', ';
}
else {
query += '?, ';
array.push( _l );
}
break;
}
}
}
if( root ) {
root = false;
}
else {
if( level === 0 )
query = query.substring( 0, query.length - 2 ) + curNest + ', ';
}
if( nested.length !== 0 ) {
if( !typeSpecification ) {
query += '\'' + nestedKeys.pop().replace(/\\/g, '\\\\')
.replace(/\u0008/g, '\\b')
.replace(/'/g, '\\\'')
.replace(/\u0000/g, '\\0') + '\', COLUMN_CREATE(';
}
else {
query += '?, COLUMN_CREATE(';
array.push( nestedKeys.pop() );
}
}
else {
query = query.substring( 0, query.length - 2 );
}
current = nested.pop();
++item;
//restore nesting level
level = levels.pop() || 0;
if ( level ) {
curNest = level.nestSep;
level = level.level;
}
deepestLevel = level + 1;
}
query += ')';
return query;
} | javascript | {
"resource": ""
} |
|
q65081 | test | function(node) {
if (Ext.isObject(node) && !node.isModel) {
node = Ext.data.ModelManager.create(node, this.modelName);
}
// Make sure the node implements the node interface
return Ext.data.NodeInterface.decorate(node);
} | javascript | {
"resource": ""
} |
|
q65082 | test | function(silent) {
var me = this,
parentNode = me.parentNode,
isFirst = (!parentNode ? true : parentNode.firstChild == me),
isLast = (!parentNode ? true : parentNode.lastChild == me),
depth = 0,
parent = me,
children = me.childNodes,
ln = children.length,
i;
while (parent.parentNode) {
++depth;
parent = parent.parentNode;
}
me.beginEdit();
me.set({
isFirst: isFirst,
isLast: isLast,
depth: depth,
index: parentNode ? parentNode.indexOf(me) : 0,
parentId: parentNode ? parentNode.getId() : null
});
me.endEdit(silent);
if (silent) {
me.commit(silent);
}
for (i = 0; i < ln; i++) {
children[i].updateInfo(silent);
}
} | javascript | {
"resource": ""
} |
|
q65083 | test | function(node, destroy, suppressEvents, suppressNodeUpdate) {
var me = this,
index = me.indexOf(node);
if (index == -1 || (suppressEvents !== true && me.fireEvent("beforeremove", me, node) === false)) {
return false;
}
// remove it from childNodes collection
Ext.Array.erase(me.childNodes, index, 1);
// update child refs
if (me.firstChild == node) {
me.setFirstChild(node.nextSibling);
}
if (me.lastChild == node) {
me.setLastChild(node.previousSibling);
}
if (suppressEvents !== true) {
me.fireEvent("remove", me, node);
}
// update siblings
if (node.previousSibling) {
node.previousSibling.nextSibling = node.nextSibling;
node.previousSibling.updateInfo(suppressNodeUpdate);
}
if (node.nextSibling) {
node.nextSibling.previousSibling = node.previousSibling;
node.nextSibling.updateInfo(suppressNodeUpdate);
}
// If this node suddenly doesn't have childnodes anymore, update myself
if (!me.childNodes.length) {
me.set('loaded', me.isLoaded());
}
if (destroy) {
node.destroy(true);
} else {
node.clear();
}
return node;
} | javascript | {
"resource": ""
} |
|
q65084 | test | function(destroy) {
var me = this;
// clear any references from the node
me.parentNode = me.previousSibling = me.nextSibling = null;
if (destroy) {
me.firstChild = me.lastChild = null;
}
} | javascript | {
"resource": ""
} |
|
q65085 | test | function(silent) {
/*
* Silent is to be used in a number of cases
* 1) When setRoot is called.
* 2) When destroy on the tree is called
* 3) For destroying child nodes on a node
*/
var me = this,
options = me.destroyOptions;
if (silent === true) {
me.clear(true);
Ext.each(me.childNodes, function(n) {
n.destroy(true);
});
me.childNodes = null;
delete me.destroyOptions;
me.callOverridden([options]);
} else {
me.destroyOptions = silent;
// overridden method will be called, since remove will end up calling destroy(true);
me.remove(true);
}
} | javascript | {
"resource": ""
} |
|
q65086 | test | function(node, refNode, suppressEvents) {
var me = this,
index = me.indexOf(refNode),
oldParent = node.parentNode,
refIndex = index,
ps;
if (!refNode) { // like standard Dom, refNode can be null for append
return me.appendChild(node);
}
// nothing to do
if (node == refNode) {
return false;
}
// Make sure it is a record with the NodeInterface
node = me.createNode(node);
if (suppressEvents !== true && me.fireEvent("beforeinsert", me, node, refNode) === false) {
return false;
}
// when moving internally, indexes will change after remove
if (oldParent == me && me.indexOf(node) < index) {
refIndex--;
}
// it's a move, make sure we move it cleanly
if (oldParent) {
if (suppressEvents !== true && node.fireEvent("beforemove", node, oldParent, me, index, refNode) === false) {
return false;
}
oldParent.removeChild(node);
}
if (refIndex === 0) {
me.setFirstChild(node);
}
Ext.Array.splice(me.childNodes, refIndex, 0, node);
node.parentNode = me;
node.nextSibling = refNode;
refNode.previousSibling = node;
ps = me.childNodes[refIndex - 1];
if (ps) {
node.previousSibling = ps;
ps.nextSibling = node;
ps.updateInfo();
} else {
node.previousSibling = null;
}
node.updateInfo();
if (!me.isLoaded()) {
me.set('loaded', true);
}
// If this node didn't have any childnodes before, update myself
else if (me.childNodes.length === 1) {
me.set('loaded', me.isLoaded());
}
if (suppressEvents !== true) {
me.fireEvent("insert", me, node, refNode);
if (oldParent) {
node.fireEvent("move", node, oldParent, me, refIndex, refNode);
}
}
return node;
} | javascript | {
"resource": ""
} |
|
q65087 | test | function(destroy, suppressEvents) {
var parentNode = this.parentNode;
if (parentNode) {
parentNode.removeChild(this, destroy, suppressEvents, true);
}
return this;
} | javascript | {
"resource": ""
} |
|
q65088 | test | function(destroy, suppressEvents) {
var cn = this.childNodes,
n;
while ((n = cn[0])) {
this.removeChild(n, destroy, suppressEvents);
}
return this;
} | javascript | {
"resource": ""
} |
|
q65089 | test | function(sortFn, recursive, suppressEvent) {
var cs = this.childNodes,
ln = cs.length,
i, n;
if (ln > 0) {
Ext.Array.sort(cs, sortFn);
for (i = 0; i < ln; i++) {
n = cs[i];
n.previousSibling = cs[i-1];
n.nextSibling = cs[i+1];
if (i === 0) {
this.setFirstChild(n);
}
if (i == ln - 1) {
this.setLastChild(n);
}
n.updateInfo(suppressEvent);
if (recursive && !n.isLeaf()) {
n.sort(sortFn, true, true);
}
}
this.notifyStores('afterEdit', ['sorted'], {sorted: 'sorted'});
if (suppressEvent !== true) {
this.fireEvent('sort', this, cs);
}
}
} | javascript | {
"resource": ""
} |
|
q65090 | test | function(recursive, callback, scope) {
var me = this;
if (!me.isLeaf()) {
if (me.isLoading()) {
me.on('expand', function() {
me.expand(recursive, callback, scope);
}, me, {single: true});
}
else {
if (!me.isExpanded()) {
// The TreeStore actually listens for the beforeexpand method and checks
// whether we have to asynchronously load the children from the server
// first. Thats why we pass a callback function to the event that the
// store can call once it has loaded and parsed all the children.
me.fireAction('expand', [this], function() {
me.set('expanded', true);
Ext.callback(callback, scope || me, [me.childNodes]);
});
}
else {
Ext.callback(callback, scope || me, [me.childNodes]);
}
}
} else {
Ext.callback(callback, scope || me);
}
} | javascript | {
"resource": ""
} |
|
q65091 | test | function(recursive, callback, scope) {
var me = this;
// First we start by checking if this node is a parent
if (!me.isLeaf() && me.isExpanded()) {
this.fireAction('collapse', [me], function() {
me.set('expanded', false);
Ext.callback(callback, scope || me, [me.childNodes]);
});
} else {
Ext.callback(callback, scope || me, [me.childNodes]);
}
} | javascript | {
"resource": ""
} |
|
q65092 | test | function (nextTargetFn, fnOpt) {
tail.next = {
fns: [nextTargetFn],
opts: [fnOpt]
};
tail = tail.next;
dispatch();
return controller;
} | javascript | {
"resource": ""
} |
|
q65093 | test | function() {
var mask = Ext.getBody().createChild({
cls: Ext.baseCSSPrefix + 'mask ' + Ext.baseCSSPrefix + 'mask-transparent'
});
setTimeout(function() {
mask.destroy();
}, 0);
} | javascript | {
"resource": ""
} |
|
q65094 | test | function(el, prefix) {
if (el && el.id) {
return el.id;
}
el = Ext.getDom(el) || {};
if (el === document || el === document.documentElement) {
el.id = 'ext-app';
}
else if (el === document.body) {
el.id = 'ext-body';
}
else if (el === window) {
el.id = 'ext-window';
}
el.id = el.id || ((prefix || 'ext-') + (++Ext.idSeed));
return el.id;
} | javascript | {
"resource": ""
} |
|
q65095 | test | function(dest, source, names, usePrototypeKeys) {
if (typeof names == 'string') {
names = names.split(/[,;\s]/);
}
Ext.each (names, function(name) {
if (usePrototypeKeys || source.hasOwnProperty(name)) {
dest[name] = source[name];
}
}, this);
return dest;
} | javascript | {
"resource": ""
} |
|
q65096 | test | function(node) {
if (node && node.parentNode && node.tagName != 'BODY') {
Ext.get(node).clearListeners();
node.parentNode.removeChild(node);
delete Ext.cache[node.id];
}
} | javascript | {
"resource": ""
} |
|
q65097 | addAction | test | function addAction(name, fn) {
if (typeof name === "object" && fn == null) {
_.each(name, function(fn, n) { this.addAction(n, fn); }, this);
return this;
}
if (typeof name !== "string" || name === "") throw new Error("Expecting non-empty string for action name.");
if (typeof fn !== "function") throw new Error("Expecting function for action.");
if (this._actions == null) this._actions = {};
if (this._actions[name] == null) this._actions[name] = [];
if (!~this._actions[name].indexOf(fn)) this._actions[name].push(fn);
return this;
} | javascript | {
"resource": ""
} |
q65098 | test | function(property, obj, newProperty) {
if (config.hasOwnProperty(property)) {
if (obj) {
config[obj] = config[obj] || {};
config[obj][(newProperty) ? newProperty : property] = config[obj][(newProperty) ? newProperty : property] || config[property];
} else {
config[newProperty] = config[property];
}
delete config[property];
//<debug warn>
Ext.Logger.deprecate("'" + property + "' config is deprecated, use the '" + ((obj) ? obj + "." : "") + ((newProperty) ? newProperty : property) + "' config instead", 2);
//</debug>
}
} | javascript | {
"resource": ""
} |
|
q65099 | Store | test | function Store(name, items) {
if (!name) {
throw new Error('Please give the store a name!');
}
this.name = name;
this.items = items || {};
this.type = 'object';
this.setType();
return this;
} | javascript | {
"resource": ""
} |