_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q61300
|
createVinylFile
|
validation
|
async function createVinylFile(filePath, options) {
options.lookup.set(filePath, vinylFile.read(filePath, options));
if (options.debugVcjd) debug(`Reading contents of: ${filePath}`);
return await options.lookup.get(filePath);
}
|
javascript
|
{
"resource": ""
}
|
q61301
|
getVinylFiles
|
validation
|
function getVinylFiles(files, options) {
return Promise.all(files.map(file=>getVinylFile(file, options)));
}
|
javascript
|
{
"resource": ""
}
|
q61302
|
resolveModule
|
validation
|
async function resolveModule(moduleId, options, root=options.base) {
if (options.lookup.has(moduleId)) return options.lookup.get(moduleId);
const absolutePath = await options.resolver(moduleId, root);
if (options.mapper.hasOwnProperty(absolutePath)) return options.mapper[absolutePath];
if (options.lookup.has(absolutePath)) return options.lookup.get(absolutePath);
return absolutePath;
}
|
javascript
|
{
"resource": ""
}
|
q61303
|
getRequires
|
validation
|
function getRequires(file, options) {
return [...fileRequires(file, options)].map(async (moduleId)=>{
if (options.internalOnly && (moduleId.charAt(0) !== '.') && (moduleId.charAt(0) !== '/')) {
if (options.mapper[moduleId] !== true) return undefined;
}
if (options.mapper.hasOwnProperty(moduleId) && !(options.internalOnly && (options.mapper[moduleId] === true))) {
if (options.mapper[moduleId]) return resolveModule(options.mapper[moduleId], options);
return undefined;
}
return resolveModule(moduleId, options, path.dirname(file.path));
});
}
|
javascript
|
{
"resource": ""
}
|
q61304
|
filterDuplicateFiles
|
validation
|
function filterDuplicateFiles() {
const lookup = new Map();
return value=>{
if (lookup.has(value)) return false;
return lookup.set(value, true);
}
}
|
javascript
|
{
"resource": ""
}
|
q61305
|
getFiles
|
validation
|
async function getFiles(paths, options) {
const files = (await getVinylFiles(paths, options))
.map(file=>[file, ...getRequires(file, options)]);
return (await promiseFlatten(files)).filter(file=>file).filter(filterDuplicateFiles());
}
|
javascript
|
{
"resource": ""
}
|
q61306
|
getAllFiles
|
validation
|
async function getAllFiles(file, options) {
let files = await getFiles([file], options);
while (hasUnloaded(files)) files = await getFiles(files, options);
return files;
}
|
javascript
|
{
"resource": ""
}
|
q61307
|
srcFilePusher
|
validation
|
function srcFilePusher(options) {
return through.obj(function(file, encoding, done) {
getAllFiles(file, options).then(files=>{
files.forEach(file=>this.push(file));
done();
}, err=>{});
})
}
|
javascript
|
{
"resource": ""
}
|
q61308
|
createResolver
|
validation
|
function createResolver(options) {
return (moduleId, base)=>new Promise((resolve, reject)=>{
const resolver = new Resolver(options.resolver?options.resolver:{});
resolver.resolve(moduleId, base, (err, absolutePath)=>{
if (err) {
if (options.debugVcjd) debug(`Could not resolve path to module: ${moduleId}\n\tfrom base: ${base}`);
return reject(err);
}
if (options.debugVcjd) debug(`Resolved module: ${moduleId}:\n\tfrom base: ${base}\n\t:is: ${base}`);
return resolve(absolutePath);
});
})
}
|
javascript
|
{
"resource": ""
}
|
q61309
|
parseOptions
|
validation
|
function parseOptions(options={}, vinylCjsDeps) {
const _options = Object.assign({
gulp: vinylCjsDeps.gulp || require('gulp'),
base: options.cwd || process.cwd(),
cwd: options.base || process.cwd(),
internalOnly: false,
debugVcjd: false
}, options);
_options.mapper = Object.assign({}, options.mapper || {});
_options.lookup = new Map(options.lookup || []);
_options.resolver = createResolver(options);
return _options;
}
|
javascript
|
{
"resource": ""
}
|
q61310
|
validation
|
function(){
var me = this,
prev = me.store.currentPage - 1;
if (prev > 0) {
if (me.fireEvent('beforechange', me, prev) !== false) {
me.store.previousPage();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61311
|
validation
|
function(){
var me = this,
total = me.getPageData().pageCount,
next = me.store.currentPage + 1;
if (next <= total) {
if (me.fireEvent('beforechange', me, next) !== false) {
me.store.nextPage();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61312
|
validation
|
function(){
var me = this,
last = me.getPageData().pageCount;
if (me.fireEvent('beforechange', me, last) !== false) {
me.store.loadPage(last);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61313
|
validation
|
function(){
var me = this,
current = me.store.currentPage;
if (me.fireEvent('beforechange', me, current) !== false) {
me.store.loadPage(current);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61314
|
validation
|
function(fromClass, members) {
//<debug>
Ext.classSystemMonitor && Ext.classSystemMonitor(this, 'Ext.Base#borrow', arguments);
//</debug>
var prototype = this.prototype,
fromPrototype = fromClass.prototype,
//<debug>
className = Ext.getClassName(this),
//</debug>
i, ln, name, fn, toBorrow;
members = Ext.Array.from(members);
for (i = 0,ln = members.length; i < ln; i++) {
name = members[i];
toBorrow = fromPrototype[name];
if (typeof toBorrow == 'function') {
fn = Ext.Function.clone(toBorrow);
//<debug>
if (className) {
fn.displayName = className + '#' + name;
}
//</debug>
fn.$owner = this;
fn.$name = name;
prototype[name] = fn;
}
else {
prototype[name] = toBorrow;
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q61315
|
getOptions
|
validation
|
function getOptions(opts) {
opts = opts || {};
// command line arguments override options
_.extend(opts, argv);
delete opts.$0;
delete opts._;
// these values are used in multiple tasks, so set defaults here
opts.unitTestCode = opts.unitTestCode || 'test/unit/**/*.js';
opts.unitTargetCode = opts.unitTargetCode || 'lib/**/*.js';
opts.testDir = opts.testDir || 'test';
opts.rootDir = opts.rootDir || process.cwd();
opts.targetDir = opts.targetDir || (opts.rootDir + '/lib');
opts.tasksets = _.extend({ 'default': ['lint', 'test'] }, opts.tasksets);
return opts;
}
|
javascript
|
{
"resource": ""
}
|
q61316
|
getPlugins
|
validation
|
function getPlugins(opts) {
var batterRootDir = __dirname.replace(delim + 'lib', '');
var batterTasks = { rootDir: batterRootDir };
var currentProject = { rootDir: opts.rootDir };
var plugins = opts.plugins || [];
// tasks in batter go to the front of the list; current project at the end (i.e. most important)
plugins.unshift(batterTasks);
if (batterRootDir !== opts.rootDir) {
plugins.push(currentProject);
}
return plugins;
}
|
javascript
|
{
"resource": ""
}
|
q61317
|
whip
|
validation
|
function whip(gulp, taste, opts) {
opts = getOptions(opts);
opts.taste = taste;
var tasks = _.extend({}, opts.tasksets);
// loop through plugins so we can get tasks from them
_.each(getPlugins(opts), function (plugin) {
var pluginRoot = plugin.rootDir;
var pluginBuildDir = pluginRoot + delim + 'build';
// look through files in the plugin build directory to try and find tasks
if (fs.existsSync(pluginBuildDir)) {
_.each(fs.readdirSync(pluginBuildDir), function (pluginFile) {
var taskName, task;
// if the file name starts with 'task.' then it is a task file
if (taskRegex.test(pluginFile)) {
// the task name is the middle part of the file name (i.e. blah for task.blah.js)
taskName = pluginFile.match(taskRegex)[1];
task = require(pluginBuildDir + delim + pluginFile)(gulp, opts);
// if task is function or an object with deps and task
if (_.isFunction(task) || (task.deps && task.task)) {
tasks[taskName] = task;
}
// else if it's an object, then there are subtasks
else if (_.isObject(task)) {
_.each(task, function (subtask, subtaskName) {
var fullTaskName = subtaskName === '' ? taskName : taskName + '.' + subtaskName;
tasks[fullTaskName] = subtask;
});
}
else {
throw new Error(pluginBuildDir + delim + pluginFile + ' is invalid');
}
}
});
}
});
// now we have all the tasks in an object so let's add them to gulp
_.each(tasks, function (task, taskName) {
if (_.isFunction(task) || _.isArray(task)) {
gulp.task(taskName, task);
}
else if (task.deps && task.task) {
gulp.task(taskName, task.deps, task.task);
}
else {
throw new Error('Invalid task for ' + taskName);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q61318
|
validation
|
function(module, method) {
var all = {urlparams:[]}
for(var i=2;i<u.length;i++) all.urlparams.push(decodeURIComponent(u[i]));
req.cookies = {}
req.headers.cookie && req.headers.cookie.split(';').forEach(function( cookie ) {
var parts = cookie.split('=')
,key = parts[0].trim()
,val = decodeURIComponent((parts[1] || '').trim());
all[key] = val;
req.cookies[key] = val
});
if(url.query != null) for(var i in url.query) all[i] = url.query[i]
if(post != null) for(var i in post) all[i] = post[i]
all.response = res
all.request = req
all._query = url.query
if(me.config.LOCALE && !all.locale) {
all.locale = req.url.substr(1,2)
if(!me.config.LOCALE[all.locale]) delete all.locale
}
// Проверяем JSON в запросе
if(all.jsonData) {
try{
all.RequestData = JSON.parse(all.jsonData)
} catch(e) {}
if(all.RequestData && !me.checkVersion(all.RequestData)) {
mcallback({}, {code: 4})
return;
}
}
if(!all.RequestData) all.RequestData = {}
var run = function(auth) {
all.href = req.url
if(all.about !== null && all.about !== undefined && module[method].aboutObject !== null) {
mcallback(module[method].aboutObject)
} else {
module[method](all, mcallback, auth);
}
}
if(me.inits.checkauth != null) { // if isser user checkauth function
me.inits.checkauth(all, function(a) {run(a)})
} else {
run(null);
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q61319
|
validation
|
function(request){
var me = this,
requests = me.requests,
key;
if (request) {
if (!request.id) {
request = requests[request];
}
me.handleAbort(request);
} else {
for (key in requests) {
if (requests.hasOwnProperty(key)) {
me.abort(requests[key]);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61320
|
validation
|
function(result, request){
var success = true;
if (request.timeout) {
clearTimeout(request.timeout);
}
delete this[request.callbackName];
delete this.requests[request.id];
this.cleanupErrorHandling(request);
Ext.fly(request.script).remove();
if (request.errorType) {
success = false;
Ext.callback(request.failure, request.scope, [request.errorType]);
} else {
Ext.callback(request.success, request.scope, [result]);
}
Ext.callback(request.callback, request.scope, [success, result, request.errorType]);
Ext.EventManager.idleEvent.fire();
}
|
javascript
|
{
"resource": ""
}
|
|
q61321
|
validation
|
function(url, params, options) {
var script = document.createElement('script');
script.setAttribute("src", Ext.urlAppend(url, Ext.Object.toQueryString(params)));
script.setAttribute("async", true);
script.setAttribute("type", "text/javascript");
return script;
}
|
javascript
|
{
"resource": ""
}
|
|
q61322
|
createTableGrid
|
validation
|
function createTableGrid(node) {
var selection = ed.selection, tblElm = ed.dom.getParent(node || selection.getNode(), 'table');
if (tblElm)
return new TableGrid(tblElm, ed.dom, selection);
}
|
javascript
|
{
"resource": ""
}
|
q61323
|
fixTableCellSelection
|
validation
|
function fixTableCellSelection(ed) {
if (!tinymce.isWebKit)
return;
var rng = ed.selection.getRng();
var n = ed.selection.getNode();
var currentCell = ed.dom.getParent(rng.startContainer, 'TD,TH');
if (!tableCellSelected(ed, rng, n, currentCell))
return;
if (!currentCell) {
currentCell=n;
}
// Get the very last node inside the table cell
var end = currentCell.lastChild;
while (end.lastChild)
end = end.lastChild;
// Select the entire table cell. Nothing outside of the table cell should be selected.
rng.setEnd(end, end.nodeValue.length);
ed.selection.setRng(rng);
}
|
javascript
|
{
"resource": ""
}
|
q61324
|
fixTableCaretPos
|
validation
|
function fixTableCaretPos() {
var last;
// Skip empty text nodes form the end
for (last = ed.getBody().lastChild; last && last.nodeType == 3 && !last.nodeValue.length; last = last.previousSibling) ;
if (last && last.nodeName == 'TABLE') {
if (ed.settings.forced_root_block)
ed.dom.add(ed.getBody(), ed.settings.forced_root_block, null, tinymce.isIE ? ' ' : '<br data-mce-bogus="1" />');
else
ed.dom.add(ed.getBody(), 'br', {'data-mce-bogus': '1'});
}
}
|
javascript
|
{
"resource": ""
}
|
q61325
|
validation
|
function(column) {
var result = column.width || 0,
subcols, len, i;
// <debug>
if (column.flex) {
Ext.Error.raise("Columns which are locked do NOT support a flex width. You must set a width on the " + column.text + "column.");
}
// </debug>
if (!result && column.isGroupHeader) {
subcols = column.items.items;
len = subcols.length;
for (i = 0; i < len; i++) {
result += this.getColumnWidth(subcols[i]);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q61326
|
validation
|
function(activeHd, toIdx) {
var me = this,
normalGrid = me.normalGrid,
lockedGrid = me.lockedGrid,
normalHCt = normalGrid.headerCt,
lockedHCt = lockedGrid.headerCt,
refreshFlags,
ownerCt;
activeHd = activeHd || normalHCt.getMenu().activeHeader;
ownerCt = activeHd.ownerCt;
// if column was previously flexed, get/set current width
// and remove the flex
if (activeHd.flex) {
activeHd.width = activeHd.getWidth();
delete activeHd.flex;
}
Ext.suspendLayouts();
ownerCt.remove(activeHd, false);
activeHd.locked = true;
// Flag to the locked column add listener to do nothing
me.ignoreAddLockedColumn = true;
if (Ext.isDefined(toIdx)) {
lockedHCt.insert(toIdx, activeHd);
} else {
lockedHCt.add(activeHd);
}
me.ignoreAddLockedColumn = false;
refreshFlags = me.syncLockedWidth();
if (refreshFlags[0]) {
lockedGrid.getView().refresh();
}
if (refreshFlags[1]) {
normalGrid.getView().refresh();
}
Ext.resumeLayouts(true);
me.fireEvent('lockcolumn', me, activeHd);
}
|
javascript
|
{
"resource": ""
}
|
|
q61327
|
validation
|
function(store, columns) {
var me = this,
oldStore = me.store,
lockedGrid = me.lockedGrid,
normalGrid = me.normalGrid;
Ext.suspendLayouts();
if (columns) {
lockedGrid.headerCt.removeAll();
normalGrid.headerCt.removeAll();
columns = me.processColumns(columns);
// Flag to the locked column add listener to do nothing
me.ignoreAddLockedColumn = true;
lockedGrid.headerCt.add(columns.locked.items);
me.ignoreAddLockedColumn = false;
normalGrid.headerCt.add(columns.normal.items);
// Ensure locked grid is set up correctly with correct width and bottom border,
// and that both grids' visibility and scrollability status is correct
me.syncLockedWidth();
}
if (store && store !== oldStore) {
store = Ext.data.StoreManager.lookup(store);
me.store = store;
lockedGrid.bindStore(store);
normalGrid.bindStore(store);
} else {
lockedGrid.getView().refresh();
normalGrid.getView().refresh();
}
Ext.resumeLayouts(true);
}
|
javascript
|
{
"resource": ""
}
|
|
q61328
|
defaultTransformer
|
validation
|
function defaultTransformer(...args) {
try {
let [record, ...rest] = args
try {
record = typeof record === 'string' ? JSON.parse(record) : record
} catch(err) {
return { type: 'bunyan', record: { err: new Error('Could not parse message.') } }
}
return { type: 'bunyan', record }
} catch(err) {
return { type: 'bunyan', record: { err: new Error('Internal error occurred.')}}
}
}
|
javascript
|
{
"resource": ""
}
|
q61329
|
getString
|
validation
|
function getString(ref)
{
try
{
if (ref)
{
try
{
return ref;
} catch (e) {
return ref.toString();
}
}
else {
try
{
return ref.toString();
}
catch (e)
{
return "undefined";
}
}
} catch (e)
{
// if we can not convert it to a string write "undefined" just like javascript
return "undefined";
}
}
|
javascript
|
{
"resource": ""
}
|
q61330
|
clickMe
|
validation
|
function clickMe (print_r, str)
{
return (function(){
print_r.objRef = eval(str);
print_r.strObjRef = str;
print_r.refresh();
});
}
|
javascript
|
{
"resource": ""
}
|
q61331
|
arrSort
|
validation
|
function arrSort(a,b)
{
var acomp = a['name'].toString(10);
var bcomp = b['name'].toString(10);
if (!isNaN(Number(acomp)))
{
acomp = Number(acomp);
}
if (!isNaN(Number(bcomp)))
{
bcomp = Number(bcomp);
}
if (acomp < bcomp)
{
return -1;
}
if (acomp > bcomp)
{
return 1;
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
q61332
|
validation
|
function(filter, index, list) {
// Shortcuts
if (filter === 'combine') {
list[index] = self.filters.combine;
return;
}
// Solfege URI
if (typeof filter === 'string' && self.application.isSolfegeUri(filter)) {
list[index] = self.application.resolveSolfegeUri(filter, self);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61333
|
getCurrentExpectedTypes
|
validation
|
function getCurrentExpectedTypes(type) {
var currentType;
var expectedType;
if (type.name) {
currentType = type.name;
} else if (type.expression) {
currentType = type.expression.name;
}
expectedType = currentType && preferType[currentType];
return {
currentType: currentType,
expectedType: expectedType
};
}
|
javascript
|
{
"resource": ""
}
|
q61334
|
validateType
|
validation
|
function validateType(jsdocNode, type) {
if (!type || !canTypeBeValidated(type.type)) {
return;
}
var typesToCheck = [];
var elements = [];
switch (type.type) {
case 'TypeApplication': // {Array.<String>}
elements = type.applications[0].type === 'UnionType' ? type.applications[0].elements : type.applications;
typesToCheck.push(getCurrentExpectedTypes(type));
break;
case 'RecordType': // {{20:String}}
elements = type.fields;
break;
case 'UnionType': // {String|number|Test}
case 'ArrayType': // {[String, number, Test]}
elements = type.elements;
break;
case 'FieldType': // Array.<{count: number, votes: number}>
typesToCheck.push(getCurrentExpectedTypes(type.value));
break;
default:
typesToCheck.push(getCurrentExpectedTypes(type));
}
elements.forEach(validateType.bind(null, jsdocNode));
typesToCheck.forEach(function(typeToCheck) {
if (typeToCheck.expectedType &&
typeToCheck.expectedType !== typeToCheck.currentType) {
context.report({
node: jsdocNode,
message: 'Use \'{{expectedType}}\' instead of \'{{currentType}}\'.',
data: {
currentType: typeToCheck.currentType,
expectedType: typeToCheck.expectedType
}
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q61335
|
requireJsDoc
|
validation
|
function requireJsDoc(node, isVirtual, paramsToCheck) {
var lines = sourceCode.lines;
var index = node.loc.start.line;
lines = lines.slice(0, index);
var matches = lines.filter(function(line) {
return line.match(/\/\*\*/gi);
});
var lastIndex = lines.lastIndexOf(matches[matches.length - 1]);
var jsdocComment = findJSDocComment(sourceCode.ast.comments, lastIndex);
if (!jsdocComment) {
report(node);
return;
}
checkJSDoc(node, jsdocComment, isVirtual, paramsToCheck);
}
|
javascript
|
{
"resource": ""
}
|
q61336
|
SelectionType
|
validation
|
function SelectionType(typeSpec) {
if (!Array.isArray(typeSpec.data) && typeof typeSpec.data !== 'function') {
throw new Error('instances of SelectionType need typeSpec.data to be an array or function that returns an array:' + JSON.stringify(typeSpec));
}
Object.keys(typeSpec).forEach(function(key) {
this[key] = typeSpec[key];
}, this);
}
|
javascript
|
{
"resource": ""
}
|
q61337
|
DeferredType
|
validation
|
function DeferredType(typeSpec) {
if (typeof typeSpec.defer !== 'function') {
throw new Error('Instances of DeferredType need typeSpec.defer to be a function that returns a type');
}
Object.keys(typeSpec).forEach(function(key) {
this[key] = typeSpec[key];
}, this);
}
|
javascript
|
{
"resource": ""
}
|
q61338
|
ArrayType
|
validation
|
function ArrayType(typeSpec) {
if (typeSpec instanceof Type) {
this.subtype = typeSpec;
}
else if (typeof typeSpec === 'string') {
this.subtype = types.getType(typeSpec);
if (this.subtype == null) {
throw new Error('Unknown array subtype: ' + typeSpec);
}
}
else {
throw new Error('Can\' handle array subtype');
}
}
|
javascript
|
{
"resource": ""
}
|
q61339
|
validation
|
function() {
var conversion = this.parse('');
if (lastSetting) {
var current = lastSetting.get();
if (conversion.predictions.length === 0) {
conversion.predictions.push(current);
}
else {
// Remove current from predictions
var removed = false;
while (true) {
var index = conversion.predictions.indexOf(current);
if (index === -1) {
break;
}
conversion.predictions.splice(index, 1);
removed = true;
}
// If the current value wasn't something we would predict, leave it
if (removed) {
conversion.predictions.push(current);
}
}
}
return conversion;
}
|
javascript
|
{
"resource": ""
}
|
|
q61340
|
ConversionHint
|
validation
|
function ConversionHint(conversion, arg) {
this.status = conversion.status;
this.message = conversion.message;
if (arg) {
this.start = arg.start;
this.end = arg.end;
}
else {
this.start = 0;
this.end = 0;
}
this.predictions = conversion.predictions;
}
|
javascript
|
{
"resource": ""
}
|
q61341
|
Argument
|
validation
|
function Argument(emitter, text, start, end, prefix, suffix) {
this.emitter = emitter;
this.setText(text);
this.start = start;
this.end = end;
this.prefix = prefix;
this.suffix = suffix;
}
|
javascript
|
{
"resource": ""
}
|
q61342
|
validation
|
function(text) {
if (text == null) {
throw new Error('Illegal text for Argument: ' + text);
}
var ev = { argument: this, oldText: this.text, text: text };
this.text = text;
this.emitter._dispatchEvent('argumentChange', ev);
}
|
javascript
|
{
"resource": ""
}
|
|
q61343
|
validation
|
function(command, arg) {
var docs = [];
docs.push('<strong><tt> > ');
docs.push(command.name);
if (command.params && command.params.length > 0) {
command.params.forEach(function(param) {
if (param.defaultValue === undefined) {
docs.push(' [' + param.name + ']');
}
else {
docs.push(' <em>[' + param.name + ']</em>');
}
}, this);
}
docs.push('</tt></strong><br/>');
docs.push(command.description ? command.description : '(No description)');
docs.push('<br/>');
if (command.params && command.params.length > 0) {
docs.push('<ul>');
command.params.forEach(function(param) {
docs.push('<li>');
docs.push('<strong><tt>' + param.name + '</tt></strong>: ');
docs.push(param.description ? param.description : '(No description)');
if (param.defaultValue === undefined) {
docs.push(' <em>[Required]</em>');
}
else if (param.defaultValue === null) {
docs.push(' <em>[Optional]</em>');
}
else {
docs.push(' <em>[Default: ' + param.defaultValue + ']</em>');
}
docs.push('</li>');
}, this);
docs.push('</ul>');
}
return new Hint(Status.VALID, docs.join(''), arg);
}
|
javascript
|
{
"resource": ""
}
|
|
q61344
|
validation
|
function(assignment) {
// This is all about re-creating Assignments
if (assignment.param.name !== '__command') {
return;
}
this._assignments = {};
if (assignment.value) {
assignment.value.params.forEach(function(param) {
this._assignments[param.name] = new Assignment(param, this);
}, this);
}
this.assignmentCount = Object.keys(this._assignments).length;
this._dispatchEvent('commandChange', { command: assignment.value });
}
|
javascript
|
{
"resource": ""
}
|
|
q61345
|
validation
|
function(nameOrNumber) {
var name = (typeof nameOrNumber === 'string') ?
nameOrNumber :
Object.keys(this._assignments)[nameOrNumber];
return this._assignments[name];
}
|
javascript
|
{
"resource": ""
}
|
|
q61346
|
validation
|
function() {
// TODO: work out when to clear this out for the plain Requisition case
// this._hints = [];
this.getAssignments(true).forEach(function(assignment) {
this._hints.push(assignment.getHint());
}, this);
Hint.sort(this._hints);
// We would like to put some initial help here, but for anyone but
// a complete novice a 'type help' message is very annoying, so we
// need to find a way to only display this message once, or for
// until the user click a 'close' button or similar
// TODO: Add special case for '' input
}
|
javascript
|
{
"resource": ""
}
|
|
q61347
|
validation
|
function() {
var args = {};
this.getAssignments().forEach(function(assignment) {
args[assignment.param.name] = assignment.value;
}, this);
return args;
}
|
javascript
|
{
"resource": ""
}
|
|
q61348
|
validation
|
function(includeCommand) {
var args = [];
if (includeCommand === true) {
args.push(this.commandAssignment);
}
Object.keys(this._assignments).forEach(function(name) {
args.push(this.getAssignment(name));
}, this);
return args;
}
|
javascript
|
{
"resource": ""
}
|
|
q61349
|
validation
|
function() {
var line = [];
line.push(this.commandAssignment.value.name);
Object.keys(this._assignments).forEach(function(name) {
var assignment = this._assignments[name];
var type = assignment.param.type;
// TODO: This will cause problems if there is a non-default value
// after a default value. Also we need to decide when to use
// named parameters in place of positional params. Both can wait.
if (assignment.value !== assignment.param.defaultValue) {
line.push(' ');
line.push(type.stringify(assignment.value));
}
}, this);
return line.join('');
}
|
javascript
|
{
"resource": ""
}
|
|
q61350
|
CliView
|
validation
|
function CliView(cli, env) {
cli.cliView = this;
this.cli = cli;
this.doc = document;
this.win = dom.getParentWindow(this.doc);
this.env = env;
// TODO: we should have a better way to specify command lines???
this.element = this.doc.getElementById('cockpitInput');
if (!this.element) {
// console.log('No element with an id of cockpit. Bailing on cli');
return;
}
this.settings = env.settings;
this.hintDirection = this.settings.getSetting('hintDirection');
this.outputDirection = this.settings.getSetting('outputDirection');
this.outputHeight = this.settings.getSetting('outputHeight');
// If the requisition tells us something has changed, we use this to know
// if we should ignore it
this.isUpdating = false;
this.createElements();
this.update();
}
|
javascript
|
{
"resource": ""
}
|
q61351
|
validation
|
function() {
// Certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(this.output.scrollHeight, this.output.clientHeight);
this.output.scrollTop = scrollHeight - this.output.clientHeight;
}
|
javascript
|
{
"resource": ""
}
|
|
q61352
|
validation
|
function() {
var rect = this.element.getClientRects()[0];
this.completer.style.top = rect.top + 'px';
var height = rect.bottom - rect.top;
this.completer.style.height = height + 'px';
this.completer.style.lineHeight = height + 'px';
this.completer.style.left = rect.left + 'px';
var width = rect.right - rect.left;
this.completer.style.width = width + 'px';
if (this.hintDirection.get() === 'below') {
this.hinter.style.top = rect.bottom + 'px';
this.hinter.style.bottom = 'auto';
}
else {
this.hinter.style.top = 'auto';
this.hinter.style.bottom = (this.doc.documentElement.clientHeight - rect.top) + 'px';
}
this.hinter.style.left = (rect.left + 30) + 'px';
this.hinter.style.maxWidth = (width - 110) + 'px';
if (this.popupOutput) {
if (this.outputDirection.get() === 'below') {
this.output.style.top = rect.bottom + 'px';
this.output.style.bottom = 'auto';
}
else {
this.output.style.top = 'auto';
this.output.style.bottom = (this.doc.documentElement.clientHeight - rect.top) + 'px';
}
this.output.style.left = rect.left + 'px';
this.output.style.width = (width - 80) + 'px';
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61353
|
validation
|
function(ev, hashId, keyCode) {
var stopEvent;
if (keyCode === keys.TAB ||
keyCode === keys.UP ||
keyCode === keys.DOWN) {
stopEvent = true;
} else if (hashId != 0 || keyCode != 0) {
stopEvent = canon.execKeyCommand(this.env, 'cli', hashId, keyCode);
}
stopEvent && event.stopEvent(ev);
}
|
javascript
|
{
"resource": ""
}
|
|
q61354
|
validation
|
function(ev) {
var handled;
/*
var handled = keyboardManager.processKeyEvent(ev, this, {
isCommandLine: true, isKeyUp: true
});
*/
// RETURN does a special exec/highlight thing
if (ev.keyCode === keys.RETURN) {
var worst = this.cli.getWorstHint();
// Deny RETURN unless the command might work
if (worst.status === Status.VALID) {
this.cli.exec();
this.element.value = '';
}
else {
// If we've denied RETURN because the command was not VALID,
// select the part of the command line that is causing problems
// TODO: if there are 2 errors are we picking the right one?
dom.setSelectionStart(this.element, worst.start);
dom.setSelectionEnd(this.element, worst.end);
}
}
this.update();
// Special actions which delegate to the assignment
var current = this.cli.getAssignmentAt(dom.getSelectionStart(this.element));
if (current) {
// TAB does a special complete thing
if (ev.keyCode === keys.TAB) {
current.complete();
this.update();
}
// UP/DOWN look for some history
if (ev.keyCode === keys.UP) {
current.increment();
this.update();
}
if (ev.keyCode === keys.DOWN) {
current.decrement();
this.update();
}
}
return handled;
}
|
javascript
|
{
"resource": ""
}
|
|
q61355
|
validation
|
function() {
this.isUpdating = true;
var input = {
typed: this.element.value,
cursor: {
start: dom.getSelectionStart(this.element),
end: dom.getSelectionEnd(this.element.selectionEnd)
}
};
this.cli.update(input);
var display = this.cli.getAssignmentAt(input.cursor.start).getHint();
// 1. Update the completer with prompt/error marker/TAB info
dom.removeCssClass(this.completer, Status.VALID.toString());
dom.removeCssClass(this.completer, Status.INCOMPLETE.toString());
dom.removeCssClass(this.completer, Status.INVALID.toString());
var completion = '<span class="cptPrompt">></span> ';
if (this.element.value.length > 0) {
var scores = this.cli.getInputStatusMarkup();
completion += this.markupStatusScore(scores);
}
// Display the "-> prediction" at the end of the completer
if (this.element.value.length > 0 &&
display.predictions && display.predictions.length > 0) {
var tab = display.predictions[0];
completion += ' ⇥ ' + (tab.name ? tab.name : tab);
}
this.completer.innerHTML = completion;
dom.addCssClass(this.completer, this.cli.getWorstHint().status.toString());
// 2. Update the hint element
var hint = '';
if (this.element.value.length !== 0) {
hint += display.message;
if (display.predictions && display.predictions.length > 0) {
hint += ': [ ';
display.predictions.forEach(function(prediction) {
hint += (prediction.name ? prediction.name : prediction);
hint += ' | ';
}, this);
hint = hint.replace(/\| $/, ']');
}
}
this.hinter.innerHTML = hint;
if (hint.length === 0) {
dom.addCssClass(this.hinter, 'cptNoPopup');
}
else {
dom.removeCssClass(this.hinter, 'cptNoPopup');
}
this.isUpdating = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q61356
|
validation
|
function(scores) {
var completion = '';
// Create mark-up
var i = 0;
var lastStatus = -1;
while (true) {
if (lastStatus !== scores[i]) {
completion += '<span class=' + scores[i].toString() + '>';
lastStatus = scores[i];
}
completion += this.element.value[i];
i++;
if (i === this.element.value.length) {
completion += '</span>';
break;
}
if (lastStatus !== scores[i]) {
completion += '</span>';
}
}
return completion;
}
|
javascript
|
{
"resource": ""
}
|
|
q61357
|
validation
|
function(ev) {
if (this.isUpdating) {
return;
}
var prefix = this.element.value.substring(0, ev.argument.start);
var suffix = this.element.value.substring(ev.argument.end);
var insert = typeof ev.text === 'string' ? ev.text : ev.text.name;
this.element.value = prefix + insert + suffix;
// Fix the cursor.
var insertEnd = (prefix + insert).length;
this.element.selectionStart = insertEnd;
this.element.selectionEnd = insertEnd;
}
|
javascript
|
{
"resource": ""
}
|
|
q61358
|
RequestView
|
validation
|
function RequestView(request, cliView) {
this.request = request;
this.cliView = cliView;
this.imageUrl = imageUrl;
// Elements attached to this by the templater. For info only
this.rowin = null;
this.rowout = null;
this.output = null;
this.hide = null;
this.show = null;
this.duration = null;
this.throb = null;
new Templater().processNode(row.cloneNode(true), this);
this.cliView.output.appendChild(this.rowin);
this.cliView.output.appendChild(this.rowout);
this.request.addEventListener('output', this.onRequestChange.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q61359
|
validation
|
function(ev) {
this.cliView.cli.update({
typed: this.request.typed,
cursor: { start:0, end:0 }
});
this.cliView.cli.exec();
}
|
javascript
|
{
"resource": ""
}
|
|
q61360
|
validation
|
function(member, clone, ref) {
ref.parentNode.insertBefore(clone, ref);
data[paramName] = member;
self.processNode(clone, data);
delete data[paramName];
}
|
javascript
|
{
"resource": ""
}
|
|
q61361
|
string
|
validation
|
function string(state) {
return [
{
token : "string",
regex : '".*?"'
}, {
token : "string", // multi line string start
regex : '["].*$',
next : state + "-qqstring"
}, {
token : "string",
regex : "'.*?'"
}, {
token : "string", // multi line string start
regex : "['].*$",
next : state + "-qstring"
}]
}
|
javascript
|
{
"resource": ""
}
|
q61362
|
validation
|
function(data, hashId, key) {
// If we pressed any command key but no other key, then ignore the input.
// Otherwise "shift-" is added to the buffer, and later on "shift-g"
// which results in "shift-shift-g" which doesn't make senese.
if (hashId != 0 && (key == "" || String.fromCharCode(0))) {
return null;
}
// Compute the current value of the keyboard input buffer.
var r = this.$composeBuffer(data, hashId, key);
var buffer = r.bufferToUse;
var symbolicName = r.symbolicName;
r = this.$find(data, buffer, symbolicName, hashId, key);
if (DEBUG) {
console.log("KeyboardStateMapper#match", buffer, symbolicName, r);
}
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q61363
|
validation
|
function(model, req) {
if(!model) return {}
var fields = {}
,queryFieldSet
if(req) {
if(req.fieldSet) {
queryFieldSet = {}
try {
queryFieldSet = JSON.parse(req.fieldSet)
} catch(e) {queryFieldSet = null}
} else if(req.urlparams && req.urlparams[1]) {
queryFieldSet = {}
var x = req.urlparams[1].split(',')
for(var i=0;i<x.length;i++) queryFieldSet[x[i]] = 1
}
}
for(var i in model.fields) if(model.fields[i] && model.fields[i].visable) {
if(!queryFieldSet || queryFieldSet[model.fields[i].name]) fields[model.fields[i].name] = 1
}
return fields;
}
|
javascript
|
{
"resource": ""
}
|
|
q61364
|
validation
|
function(grid) {
var me = this;
if (grid.rendered) {
me.grid = grid;
grid.getView().on({
render: function(v) {
me.view = v;
Ext.ux.dd.CellFieldDropZone.superclass.constructor.call(me, me.view.el);
},
single: true
});
} else {
grid.on('render', me.init, me, {single: true});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61365
|
validation
|
function(target, dd, e, dragData) {
delete this.dropOK;
if (!target) {
return;
}
// Check that a field is being dragged.
var f = dragData.field;
if (!f) {
return;
}
// Check whether the data type of the column being dropped on accepts the
// dragged field type. If so, set dropOK flag, and highlight the target node.
var type = target.record.fields.get(target.fieldName).type,
types = Ext.data.Types;
switch(type){
case types.FLOAT:
case types.INT:
if (!f.isXType('numberfield')) {
return;
}
break;
case types.DATE:
if (!f.isXType('datefield')) {
return;
}
break;
case types.BOOL:
if (!f.isXType('checkbox')) {
return;
}
}
this.dropOK = true;
Ext.fly(target.node).addCls('x-drop-target-active');
}
|
javascript
|
{
"resource": ""
}
|
|
q61366
|
validation
|
function(target, dd, e, dragData) {
if (this.dropOK) {
var value = dragData.field.getValue();
target.record.set(target.fieldName, value);
this.onCellDrop(target.fieldName, value);
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61367
|
validation
|
function(cssText, id) {
var ss,
head = doc.getElementsByTagName("head")[0],
styleEl = doc.createElement("style");
styleEl.setAttribute("type", "text/css");
if (id) {
styleEl.setAttribute("id", id);
}
if (Ext.isIE) {
head.appendChild(styleEl);
ss = styleEl.styleSheet;
ss.cssText = cssText;
} else {
try{
styleEl.appendChild(doc.createTextNode(cssText));
} catch(e) {
styleEl.cssText = cssText;
}
head.appendChild(styleEl);
ss = styleEl.styleSheet ? styleEl.styleSheet : (styleEl.sheet || doc.styleSheets[doc.styleSheets.length-1]);
}
CSS.cacheStyleSheet(ss);
return ss;
}
|
javascript
|
{
"resource": ""
}
|
|
q61368
|
validation
|
function(id) {
var existing = doc.getElementById(id);
if (existing) {
existing.parentNode.removeChild(existing);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61369
|
validation
|
function(id, url) {
var ss;
CSS.removeStyleSheet(id);
ss = doc.createElement("link");
ss.setAttribute("rel", "stylesheet");
ss.setAttribute("type", "text/css");
ss.setAttribute("id", id);
ss.setAttribute("href", url);
doc.getElementsByTagName("head")[0].appendChild(ss);
}
|
javascript
|
{
"resource": ""
}
|
|
q61370
|
validation
|
function(refreshCache) {
var result = {},
selector;
if (rules === null || refreshCache) {
CSS.refreshCache();
}
for (selector in rules) {
result[selector] = rules[selector].cssRule;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q61371
|
validation
|
function(styleSheet, selector, cssText) {
var result,
ruleSet = styleSheet.cssRules || styleSheet.rules,
index = ruleSet.length;
if (styleSheet.insertRule) {
styleSheet.insertRule(selector + '{' + cssText + '}', index);
} else {
styleSheet.addRule(selector, cssText||' ');
}
CSS.cacheRule(result = ruleSet[index], styleSheet);
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q61372
|
cloneObject
|
validation
|
function cloneObject( obj ) {
if ( obj === null || typeof obj !== 'object' ) {
return obj;
}
var temp = obj.constructor( ); // give temp the original obj's constructor
for ( var key in obj ) {
temp[ key ] = cloneObject( obj[ key ] );
}
return temp;
}
|
javascript
|
{
"resource": ""
}
|
q61373
|
validation
|
function(node, callback, scope, args) {
var me = this,
reader, dataRoot, data,
callbackArgs;
// Children are loaded go ahead with expand
if (node.isLoaded()) {
callbackArgs = [node.childNodes];
if (args) {
callbackArgs.push.apply(callbackArgs, args);
}
Ext.callback(callback, scope || node, callbackArgs);
}
// There are unloaded child nodes in the raw data because of the lazy configuration, load them then call back.
else if (dataRoot = (data = (node.raw || node[node.persistenceProperty])[(reader = me.getProxy().getReader()).root])) {
me.fillNode(node, reader.extractData(dataRoot));
delete data[reader.root];
callbackArgs = [node.childNodes];
if (args) {
callbackArgs.push.apply(callbackArgs, args);
}
Ext.callback(callback, scope || node, callbackArgs);
}
// The node is loading
else if (node.isLoading()) {
me.on('load', function() {
callbackArgs = [node.childNodes];
if (args) {
callbackArgs.push.apply(callbackArgs, args);
}
Ext.callback(callback, scope || node, callbackArgs);
}, me, {single: true});
}
// Node needs loading
else {
me.read({
node: node,
callback: function() {
// Clear the callback, since if we're introducing a custom one,
// it may be re-used on reload
delete me.lastOptions.callback;
callbackArgs = [node.childNodes];
if (args) {
callbackArgs.push.apply(callbackArgs, args);
}
Ext.callback(callback, scope || node, callbackArgs);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61374
|
validation
|
function(node1, node2) {
return node1[node1.persistenceProperty].index - node2[node2.persistenceProperty].index;
}
|
javascript
|
{
"resource": ""
}
|
|
q61375
|
init
|
validation
|
function init(tag, attrs, params) { // {{{2
/**
* View constructor
*
* @copyParams ose-html5.lib.wrap/constructor
*
* @method constructor
*/
O.inherited(this)(tag || 'ul', attrs, params);
this.updating = 0;
this.hook();
this.text('Loading ...');
}
|
javascript
|
{
"resource": ""
}
|
q61376
|
validation
|
function(req, res, runMethod) {
var form = new formidable.IncomingForm()
,files = {}
,fields = {}
,size = 0
for(var i in formConfig) {
form[i] = formConfig[i]
}
form.on('file', function(field, file) {
size += file.size
if(size > maxUploadSize) {
return false;
}
if(files[field]) {
if(!util.isArray(files[field])) files[field] = [files[field]]
files[field].push(file)
} else {
files[field] = file;
}
})
form.on('field', function(field, value) {
if(fields[field]) {
if(!util.isArray(fields[field])) fields[field] = [fields[field]]
fields[field].push(value)
} else {
fields[field] = value;
}
})
form.on('end', function() {
fields.files = files
runMethod(req, res, fields);
});
form.parse(req);
}
|
javascript
|
{
"resource": ""
}
|
|
q61377
|
sortArgs
|
validation
|
function sortArgs(app, argv, options) {
options = options || [];
var first = options.first || [];
var last = options.last || [];
var cliKeys = [];
if (app.cli && app.cli.keys) {
cliKeys = app.cli.keys;
}
var keys = utils.union(first, cliKeys, Object.keys(argv));
keys = utils.diff(keys, last);
keys = utils.union(keys, last);
var len = keys.length;
var idx = -1;
var res = {};
while (++idx < len) {
var key = keys[idx];
if (argv.hasOwnProperty(key)) {
res[key] = argv[key];
}
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q61378
|
validation
|
function() {
var me = this,
picker = new Ext.tree.Panel({
shrinkWrapDock: 2,
store: me.store,
floating: true,
displayField: me.displayField,
columns: me.columns,
minHeight: me.minPickerHeight,
maxHeight: me.maxPickerHeight,
manageHeight: false,
shadow: false,
listeners: {
scope: me,
itemclick: me.onItemClick
},
viewConfig: {
listeners: {
scope: me,
render: me.onViewRender
}
}
}),
view = picker.getView();
if (Ext.isIE9 && Ext.isStrict) {
// In IE9 strict mode, the tree view grows by the height of the horizontal scroll bar when the items are highlighted or unhighlighted.
// Also when items are collapsed or expanded the height of the view is off. Forcing a repaint fixes the problem.
view.on({
scope: me,
highlightitem: me.repaintPickerView,
unhighlightitem: me.repaintPickerView,
afteritemexpand: me.repaintPickerView,
afteritemcollapse: me.repaintPickerView
});
}
return picker;
}
|
javascript
|
{
"resource": ""
}
|
|
q61379
|
validation
|
function() {
var style = this.picker.getView().getEl().dom.style;
// can't use Element.repaint because it contains a setTimeout, which results in a flicker effect
style.display = style.display;
}
|
javascript
|
{
"resource": ""
}
|
|
q61380
|
validation
|
function() {
var me = this,
picker;
if (me.isExpanded) {
picker = me.getPicker();
if (me.matchFieldWidth) {
// Auto the height (it will be constrained by max height)
picker.setWidth(me.bodyEl.getWidth());
}
if (picker.isFloating()) {
me.doAlign();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61381
|
validation
|
function(e, el) {
var key = e.getKey();
if(key === e.ENTER || (key === e.TAB && this.selectOnTab)) {
this.selectItem(this.picker.getSelectionModel().getSelection()[0]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61382
|
validation
|
function(record) {
var me = this;
me.setValue(record.getId());
me.picker.hide();
me.inputEl.focus();
me.fireEvent('select', me, record)
}
|
javascript
|
{
"resource": ""
}
|
|
q61383
|
validation
|
function() {
var me = this,
picker = me.picker,
store = picker.store,
value = me.value,
node;
if (value) {
node = store.getNodeById(value);
}
if (!node) {
node = store.getRootNode();
}
picker.selectPath(node.getPath());
Ext.defer(function() {
picker.getView().focus();
}, 1);
}
|
javascript
|
{
"resource": ""
}
|
|
q61384
|
validation
|
function(value) {
var me = this,
record;
me.value = value;
if (me.store.loading) {
// Called while the Store is loading. Ensure it is processed by the onLoad method.
return me;
}
// try to find a record in the store that matches the value
record = value ? me.store.getNodeById(value) : me.store.getRootNode();
if (value === undefined) {
record = me.store.getRootNode();
me.value = record.getId();
} else {
record = me.store.getNodeById(value);
}
// set the raw value to the record's display field if a record was found
me.setRawValue(record ? record.get(me.displayField) : '');
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q61385
|
validation
|
function(key) {
var pos = key.indexOf('[');
if (pos === -1) return { type: 'string', val: key };
return { type: 'array', val: key.substr(0, pos) };
}
|
javascript
|
{
"resource": ""
}
|
|
q61386
|
validation
|
function(direction) {
var me = this;
me.direction = direction ? direction.toUpperCase() : direction;
me.updateSortFunction();
}
|
javascript
|
{
"resource": ""
}
|
|
q61387
|
validation
|
function() {
var me = this;
me.direction = Ext.String.toggle(me.direction, "ASC", "DESC");
me.updateSortFunction();
}
|
javascript
|
{
"resource": ""
}
|
|
q61388
|
validation
|
function(fn) {
var me = this;
fn = fn || me.sorterFn || me.defaultSorterFn;
me.sort = me.createSortFunction(fn);
}
|
javascript
|
{
"resource": ""
}
|
|
q61389
|
Recurring
|
validation
|
function Recurring(str) {
var parts = str.split('/');
if(str.charAt(0) != 'R' || parts.length != 3) {
throw new Error('Invalid Recurring Date');
}
// We must have start and end. error if both aren't set
if(!parts[1] || !parts[2]) {
throw new Error('Recurring must have a start and end');
}
var countNum = parts[0].substr(1);
// Validate count is a number if set
if(countNum) {
if(!(/^[0-9]+$/.test(countNum))) {
throw new Error('Invalid recurrence count: not a number')
}
this.count = parseInt(countNum, 10);
if(this.count < 0) throw new Error('Invalid recurrence count');
}
Range.call(this, parts[1]+'/'+parts[2]);
// If we have a count, replace end with the actual end date or undefined.
delete this.end;
if(this.count) {
this.end = this.getNth(this.count);
}
}
|
javascript
|
{
"resource": ""
}
|
q61390
|
iopaStaticSend
|
validation
|
function iopaStaticSend(context, path, opts) {
opts = opts || {};
return new Promise(function iopaStaticLoad(resolve, reject){
var root = opts.root ? normalize(pathResolve(opts.root)) : '';
var index = opts.index;
var maxage = opts.maxage || 0;
var hidden = opts.hidden || false;
var sync = opts.sync || false;
opts = null;
// normalize path
path = decode(path);
if (path =="")
path = "/";
var trailingSlash = '/' == path[path.length - 1];
if (-1 == path) return reject('failed to decode');
// null byte(s)
if (~path.indexOf('\0')) return reject('null bytes');
// index file support
if (index && trailingSlash) path += index;
// malicious path
if (!root && !isAbsolute(path)) return reject('relative paths require the .root option');
if (!root && ~path.indexOf('..')) return reject('malicious path');
// relative to root
path = normalize(join(root, path));
// out of bounds
if (root && 0 != path.indexOf(root)) return reject('malicious path');
// hidden file support, ignore
if (!hidden && leadingDot(path)) return resolve();
var stats;
try
{
stats = fs.statSync(path);
}
catch (err) {
return resolve(null);
}
if (stats.isDirectory())
{
return resolve(null);
}
var contentType = mime.lookup(path) || 'application/octet-stream';
context.response.writeHead(200, {
'Content-Type' : contentType,
'Last-Modified' : stats.mtime.toUTCString(),
'Content-Length': stats.size + '',
'Cache-Control': 'max-age=' + (maxage / 1000 | 0)});
if (sync)
{
var bodyBuffer = fs.readFileSync(path);
context.response.end(bodyBuffer);
bodyBuffer = null;
context = null;
return resolve();
}
else
{
var stream = fs.createReadStream(path, { flags: 'r',
encoding: null,
autoClose: true
});
stream.on('error', function(err){
console.log(err);
stream = null;
context = null;
reject(err);
});
stream.on('end', function(){
context.response.end();
stream = null;
context = null;
resolve();
});
stream.pipe(context.response[IOPA.Body]);
return;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q61391
|
validation
|
function(ed) {
var self = this, testKey = PLUGIN_NAME + '_test', testVal = "OK";
self.key = PLUGIN_NAME + ed.id;
// Loop though each storage engine type until we find one that works
tinymce.each([
function() {
// Try HTML5 Local Storage
if (localStorage) {
localStorage.setItem(testKey, testVal);
if (localStorage.getItem(testKey) === testVal) {
localStorage.removeItem(testKey);
return localStorage;
}
}
},
function() {
// Try HTML5 Session Storage
if (sessionStorage) {
sessionStorage.setItem(testKey, testVal);
if (sessionStorage.getItem(testKey) === testVal) {
sessionStorage.removeItem(testKey);
return sessionStorage;
}
}
},
function() {
// Try IE userData
if (tinymce.isIE) {
ed.getElement().style.behavior = "url('#default#userData')";
// Fake localStorage on old IE
return {
autoExpires : TRUE,
setItem : function(key, value) {
var userDataElement = ed.getElement();
userDataElement.setAttribute(key, value);
userDataElement.expires = self.getExpDate();
try {
userDataElement.save("TinyMCE");
} catch (e) {
// Ignore, saving might fail if "Userdata Persistence" is disabled in IE
}
},
getItem : function(key) {
var userDataElement = ed.getElement();
try {
userDataElement.load("TinyMCE");
return userDataElement.getAttribute(key);
} catch (e) {
// Ignore, loading might fail if "Userdata Persistence" is disabled in IE
return null;
}
},
removeItem : function(key) {
ed.getElement().removeAttribute(key);
}
};
}
},
], function(setup) {
// Try executing each function to find a suitable storage engine
try {
self.storage = setup();
if (self.storage)
return false;
} catch (e) {
// Ignore
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q61392
|
validation
|
function() {
var self = this, storage = self.storage, editor = self.editor, expires, content;
// Is the contents dirty
if (storage) {
// If there is no existing key and the contents hasn't been changed since
// it's original value then there is no point in saving a draft
if (!storage.getItem(self.key) && !editor.isDirty())
return;
// Store contents if the contents if longer than the minlength of characters
content = editor.getContent({draft: true});
if (content.length > editor.settings.autosave_minlength) {
expires = self.getExpDate();
// Store expiration date if needed IE userData has auto expire built in
if (!self.storage.autoExpires)
self.storage.setItem(self.key + "_expires", expires);
self.storage.setItem(self.key, content);
self.onStoreDraft.dispatch(self, {
expires : expires,
content : content
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61393
|
validation
|
function() {
var self = this, storage = self.storage, content;
if (storage) {
content = storage.getItem(self.key);
if (content) {
self.editor.setContent(content);
self.onRestoreDraft.dispatch(self, {
content : content
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61394
|
validation
|
function() {
var self = this, storage = self.storage, key = self.key, content;
if (storage) {
// Get current contents and remove the existing draft
content = storage.getItem(key);
storage.removeItem(key);
storage.removeItem(key + "_expires");
// Dispatch remove event if we had any contents
if (content) {
self.onRemoveDraft.dispatch(self, {
content : content
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61395
|
validation
|
function(e) {
var msg;
tinymce.each(tinyMCE.editors, function(ed) {
// Store a draft for each editor instance
if (ed.plugins.autosave)
ed.plugins.autosave.storeDraft();
// Never ask in fullscreen mode
if (ed.getParam("fullscreen_is_enabled"))
return;
// Setup a return message if the editor is dirty
if (!msg && ed.isDirty() && ed.getParam("autosave_ask_before_unload"))
msg = ed.getLang("autosave.unload_msg");
});
return msg;
}
|
javascript
|
{
"resource": ""
}
|
|
q61396
|
request
|
validation
|
function request(url){
return new Promise(function(resolve, reject) {
_request(url, function (error, response, body) {
if(error) return reject(error);
resolve({response, body})
});
});
}
|
javascript
|
{
"resource": ""
}
|
q61397
|
validation
|
function (grid, state) {
var filters = {};
this.filters.each(function (filter) {
if (filter.active) {
filters[filter.dataIndex] = filter.getValue();
}
});
return (state.filters = filters);
}
|
javascript
|
{
"resource": ""
}
|
|
q61398
|
validation
|
function(store) {
var me = this;
// Unbind from the old Store
if (me.store && me.storeListeners) {
me.store.un(me.storeListeners);
}
// Set up correct listeners
if (store) {
me.storeListeners = {
scope: me
};
if (me.local) {
me.storeListeners.load = me.onLoad;
} else {
me.storeListeners['before' + (store.buffered ? 'prefetch' : 'load')] = me.onBeforeLoad;
}
store.on(me.storeListeners);
} else {
delete me.storeListeners;
}
me.store = store;
}
|
javascript
|
{
"resource": ""
}
|
|
q61399
|
validation
|
function () {
var me = this,
headerCt = me.view.headerCt;
if (headerCt) {
headerCt.items.each(function(header) {
var filter = me.getFilter(header.dataIndex);
header[filter && filter.active ? 'addCls' : 'removeCls'](me.filterCls);
});
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.