_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q13100
|
train
|
function(obj, propName, message) {
assert(typeof(propName) === 'string');
if ( ! message) message = "Using this property indicates old/broken code.";
// already blocked?
bphush = true;
try {
let v = obj[propName];
} catch (err) {
return obj;
}
bphush = false;
if (obj[propName] !== undefined) {
// already set to a value :(
const ex = new Error("Having "+propName+" is blocked! "+message);
if ( ! bphush) console.error(ex, this); // react can swallow stuff
throw ex;
}
if ( ! Object.isExtensible(obj)) {
// no need -- frozen or sealed
return;
}
Object.defineProperty(obj, propName, {
get: function () {
const ex = new Error(propName+" is blocked! "+message);
if ( ! bphush) console.error(ex, this); // react can swallow stuff
throw ex;
},
set: function () {
const ex = new Error("Set "+propName+" is blocked! "+message);
if ( ! bphush) console.error(ex, this); // react can swallow stuff
throw ex;
}
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q13101
|
coreFlags
|
train
|
function coreFlags() {
console.log('Core flags:');
console.log();
flags.forEach(function(flag) {
console.log(' ' + flag);
});
}
|
javascript
|
{
"resource": ""
}
|
q13102
|
pluginFlags
|
train
|
function pluginFlags(plugins) {
var pflags = [];
var len = 0;
plugins.forEach(function(plugin) {
Object.keys(plugin.flags || {}).forEach(function(flag) {
pflags.push([flag, plugin.flags[flag]]);
len = Math.max(flag.length, len);
});
});
if (pflags.length) {
console.log();
console.log('Plugin flags:');
console.log();
pflags.forEach(function(flag) {
console.log(' %s %s', ljust(flag[0], len), flag[1]);
});
}
console.log();
}
|
javascript
|
{
"resource": ""
}
|
q13103
|
loadConfig
|
train
|
function loadConfig(path) {
var configuration = {};
var configurationFiles = fs.readdirSync(path);
configurationFiles.forEach(function(configurationFile) {
configuration[configurationFile.replace(/\.js$/, '')] = require(path + '/' + configurationFile);
});
return configuration;
}
|
javascript
|
{
"resource": ""
}
|
q13104
|
SocketServer
|
train
|
function SocketServer() {
Object.defineProperties(this, {
/**
* The Socket.io server.
*
* @property io
* @type Server
*/
io: {value: null, writable: true},
/**
* The list of namespaces added to the server indexed by names.
*
* @property namespaces
* @type Object
*/
namespaces: {value: {}}
});
}
|
javascript
|
{
"resource": ""
}
|
q13105
|
train
|
function (scanner, matcher) {
var start = scanner.pos;
var result = matcher(scanner);
scanner.pos = start;
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q13106
|
train
|
function (scanner, inAttribute) {
// look for `&` followed by alphanumeric
if (! peekMatcher(scanner, getPossibleNamedEntityStart))
return null;
var matcher = getNamedEntityByFirstChar[scanner.rest().charAt(1)];
var entity = null;
if (matcher)
entity = peekMatcher(scanner, matcher);
if (entity) {
if (entity.slice(-1) !== ';') {
// Certain character references with no semi are an error, like `<`.
// In attribute values, however, this is not fatal if the next character
// is alphanumeric.
//
// This rule affects href attributes, for example, deeming "/?foo=bar<c=abc"
// to be ok but "/?foo=bar<=abc" to not be.
if (inAttribute && ALPHANUMERIC.test(scanner.rest().charAt(entity.length)))
return null;
scanner.fatal("Character reference requires semicolon: " + entity);
} else {
scanner.pos += entity.length;
return entity;
}
} else {
// we couldn't match any real entity, so see if this is a bad entity
// or something we can overlook.
var badEntity = peekMatcher(scanner, getApparentNamedEntity);
if (badEntity)
scanner.fatal("Invalid character reference: " + badEntity);
// `&aaaa` is ok with no semicolon
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13107
|
ready
|
train
|
function ready(callback) {
let onLoaded = (event) => {
if (document.addEventListener) {
document.removeEventListener('DOMContentLoaded', onLoaded, false);
window.removeEventListener('load', onLoaded, false);
}
else if (document.attachEvent) {
document.detachEvent('onreadystatechange', onLoaded);
window.detachEvent('onload', onLoaded);
}
setTimeout(callback, 1);
};
if (document.readyState === 'complete') return setTimeout(callback, 1);
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', onLoaded, false);
window.addEventListener('load', onLoaded, false);
}
else if (document.attachEvent) {
document.attachEvent('onreadystatechange', onLoaded);
window.attachEvent('onload', onLoaded);
}
}
|
javascript
|
{
"resource": ""
}
|
q13108
|
addSwatchGroup
|
train
|
function addSwatchGroup(name) {
var swatchGroup = doc.swatchGroups.add();
swatchGroup.name = name;
return swatchGroup;
}
|
javascript
|
{
"resource": ""
}
|
q13109
|
addSwatch
|
train
|
function addSwatch(name, color) {
var swatch = doc.swatches.add();
swatch.color = color;
swatch.name = name;
return swatch;
}
|
javascript
|
{
"resource": ""
}
|
q13110
|
removeAllSwatches
|
train
|
function removeAllSwatches() {
for (var i = 0; i < doc.swatches.length; i++) {
doc.swatches[i].remove();
}
}
|
javascript
|
{
"resource": ""
}
|
q13111
|
removeAllSwatchGroups
|
train
|
function removeAllSwatchGroups() {
for (var i = 0; i < doc.swatchGroups.length; i++) {
doc.swatchGroups[i].remove();
}
}
|
javascript
|
{
"resource": ""
}
|
q13112
|
drawSwatchRect
|
train
|
function drawSwatchRect(top, left, width, height, name, color) {
var layer = doc.layers[0];
var rect = layer.pathItems.rectangle(top, left, width, height);
rect.filled = true;
rect.fillColor = color;
rect.stroked = false;
var textBounds = layer.pathItems.rectangle(top - height * config.swatchRect.textPosition, left + width * config.swatchRect.textPosition, width * (1 - config.swatchRect.textPosition * 2), height * (1 - config.swatchRect.textPosition * 2));
var text = layer.textFrames.areaText(textBounds);
text.contents = name + '\n' + colorToString(color);
charStyles['swatchRectTitle'].applyTo(text.textRange);
return rect;
}
|
javascript
|
{
"resource": ""
}
|
q13113
|
getColorGroups
|
train
|
function getColorGroups(colors) {
var colorGroups = [];
colors.forEach(function (color) {
if (colorGroups.indexOf(color.group) < 0) {
colorGroups.push(color.group);
}
});
return colorGroups;
}
|
javascript
|
{
"resource": ""
}
|
q13114
|
getMaxShades
|
train
|
function getMaxShades(colors) {
var max = 0;
var colorGroups = getColorGroups(colors);
colorGroups.forEach(function (colorGroup, colorGroupIndex) {
// Gets colors that belong to group.
var groupColors = colors.filter(function (o) {
return o.group === colorGroup;
});
var len = groupColors.length;
if (len > max) {
max = len;
}
});
return max;
}
|
javascript
|
{
"resource": ""
}
|
q13115
|
train
|
function(_tpl,_map){
_map = _map||_o;
return _tpl.replace(_reg1,function($1,$2){
var _arr = $2.split('|');
return _map[_arr[0]]||_arr[1]||'0';
});
}
|
javascript
|
{
"resource": ""
}
|
|
q13116
|
read
|
train
|
async function read(reader, patcher) {
let {done, value} = await reader.read();
if(done || isAttached()) {
return false;
}
//!steal-remove-start
log.mutations(value);
//!steal-remove-end
patcher.patch(value);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q13117
|
getLibOptions
|
train
|
function getLibOptions(aliases, itemsToOmit) {
let aliased = _.transform(options, function(result, value, key) {
let alias = aliases[key];
result[alias || key] = value;
});
return _.omit(aliased, itemsToOmit);
}
|
javascript
|
{
"resource": ""
}
|
q13118
|
define
|
train
|
function define() {
let libOptions = getLibOptions({
alternate: 'alternateExchange'
}, ['persistent', 'publishTimeout']);
topLog.debug(`Declaring ${options.type} exchange \'${options.name}\' on connection \'${connectionName}\' with the options: ${JSON.stringify(_.omit(libOptions, ['name', 'type']))}`);
return channel.assertExchange(options.name, options.type, libOptions);
}
|
javascript
|
{
"resource": ""
}
|
q13119
|
WhenProperty
|
train
|
function WhenProperty(whenExpression, thenExpression) {
if (!thenExpression) {
thenExpression = whenExpression;
whenExpression = 'true';
}
this.whenExpression = whenExpression;
this.thenExpression = thenExpression;
}
|
javascript
|
{
"resource": ""
}
|
q13120
|
StatsdClient
|
train
|
function StatsdClient(opts) {
BaseClient.apply(this, arguments);
opts = opts || {};
this.host = opts.host || '127.0.0.1';
this.port = opts.port || 8125;
this.keyBuilder = opts.keyBuilder || defaultMetricsKeyBuilder;
this.socket = dgram.createSocket('udp4');
}
|
javascript
|
{
"resource": ""
}
|
q13121
|
mimeType
|
train
|
function mimeType( path ) {
var extension = path.replace( /.*[./\\]/ , '' ).toLowerCase() ;
if ( ! mimeType.extension[ extension ] ) {
// default MIME type, when nothing is found
return 'application/octet-stream' ;
}
return mimeType.extension[ extension ] ;
}
|
javascript
|
{
"resource": ""
}
|
q13122
|
Application
|
train
|
function Application(options) {
var self = this;
if (!(self instanceof Application)) {
return new Application(options);
}
stream.Duplex.call(self, { objectMode: true });
self.id = hat();
self.server = net.createServer(self._handleInbound.bind(self));
self.options = merge(Object.create(Application.DEFAULTS), options);
self.connections = { inbound: [], outbound: [] };
// setup middlware stack with initial entry a simple passthrough
self.stack = [function(socket) {
return through(function(data) {
this.queue(data);
});
}];
Object.defineProperty(self, 'log', {
value: this.options.logger || {
info: NOOP, warn: NOOP, error: NOOP
}
});
// connect to seeds
self._enterNetwork();
setInterval(self._enterNetwork.bind(self), self.options.retryInterval);
}
|
javascript
|
{
"resource": ""
}
|
q13123
|
sendEmail
|
train
|
function sendEmail(options = {}) {
return new Promise((resolve, reject) => {
try {
const mailoptions = options;
let mailTransportConfig = (this && this.config && this.config.transportConfig)
? this.config.transportConfig
: options.transportConfig;
let mailtransport = (this && this.transport)
? this.transport
: options.transport;
Promise.resolve(mailoptions)
.then(mailoptions => {
if (mailoptions.html || mailoptions.emailtemplatestring) {
return mailoptions.html || mailoptions.emailtemplatestring;
} else {
return getEmailTemplateHTMLString(mailoptions);
}
})
.then(emailTemplateString => {
mailoptions.emailtemplatestring = emailTemplateString;
if (mailoptions.html) {
return mailoptions.html;
} else {
if (mailoptions.emailtemplatefilepath && !mailoptions.emailtemplatedata.filename) {
mailoptions.emailtemplatedata.filename = mailoptions.emailtemplatefilepath;
}
mailoptions.html = ejs.render(mailoptions.emailtemplatestring, mailoptions.emailtemplatedata);
return mailoptions.html;
}
})
.then(mailhtml => {
if (mailtransport && mailtransport.sendMail) {
return mailtransport;
} else {
return getTransport({ transportObject: mailTransportConfig })
.then(transport => {
mailtransport = transport;
return Promise.resolve(transport);
})
.catch(reject);
}
})
.then(mt => {
mt.sendMail(mailoptions, (err, status) => {
if (err) {
reject(err);
} else {
resolve(status);
}
});
})
.catch(reject);
} catch (e) {
reject(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q13124
|
writeLogs
|
train
|
function writeLogs(customMethods) {
// Error level logging with a message but no error
console.error('Testing ERROR LEVEL without actual error')
// Error level logging with an error but no message
// This shows enhanced error parsing in logging
console.error(new Error("some error"));
// Error level logging with both message and error
// This shows enhanced error parsing in logging
console.error('Testing ERROR LEVEL with an error', new Error("some error"));
// Warn level logging
console.warn('Testing WARN LEVEL');
// Info level logging
console.info('Testing INFO LEVEL');
// Log/Debug level logging
console.log('Testing LOG LEVEL');
if(customMethods) {
// Log/Debug level loggin using "debug" alias (not standard but clearer)
console.debug('Testing DEBUG (AKA LOG) LEVEL');
// Verbose level logging (new level added to go beyond DEBUG)
console.verbose('Testing TRACE LEVEL');
}
}
|
javascript
|
{
"resource": ""
}
|
q13125
|
train
|
function(hoast, filePath, content) {
return new Promise(function(resolve, reject) {
hoast.helpers.createDirectory(path.dirname(filePath))
.then(function() {
fs.writeFile(filePath, JSON.stringify(content), `utf8`, function(error) {
if (error) {
return reject(error);
}
resolve();
});
})
.catch(function(error) {
reject(error);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q13126
|
train
|
function(hoast, files) {
debug(`Running module.`);
// Loop through the files.
const filtered = files.filter(function(file) {
debug(`Filtering file '${file.path}'.`);
// If it does not match
if (this.expressions && hoast.helpers.matchExpressions(file.path, this.expressions, options.patternOptions.all)) {
debug(`File path valid for skipping.`);
return true;
}
// If it is in the list and not changed since the last time do not process.
if (this.list[file.path] && this.list[file.path] >= file.stats.mtimeMs) {
debug(`File not changed since last process.`);
return false;
}
debug(`File changed or not processed before.`);
// Update changed time and process.
this.list[file.path] = file.stats.mtimeMs;
return true;
}, mod);
debug(`Finished filtering files.`);
// Return filtered files.
return filtered;
}
|
javascript
|
{
"resource": ""
}
|
|
q13127
|
CommonTransport
|
train
|
function CommonTransport( logger , config = {} ) {
this.logger = null ;
this.monitoring = false ;
this.minLevel = 0 ;
this.maxLevel = 7 ;
this.messageFormatter = logger.messageFormatter.text ;
this.timeFormatter = logger.timeFormatter.dateTime ;
Object.defineProperty( this , 'logger' , { value: logger } ) ;
if ( config.monitoring !== undefined ) { this.monitoring = !! config.monitoring ; }
if ( config.minLevel !== undefined ) {
if ( typeof config.minLevel === 'number' ) { this.minLevel = config.minLevel ; }
else if ( typeof config.minLevel === 'string' ) { this.minLevel = this.logger.levelHash[ config.minLevel ] ; }
}
if ( config.maxLevel !== undefined ) {
if ( typeof config.maxLevel === 'number' ) { this.maxLevel = config.maxLevel ; }
else if ( typeof config.maxLevel === 'string' ) { this.maxLevel = this.logger.levelHash[ config.maxLevel ] ; }
}
if ( config.messageFormatter ) {
if ( typeof config.messageFormatter === 'function' ) { this.messageFormatter = config.messageFormatter ; }
else { this.messageFormatter = this.logger.messageFormatter[ config.messageFormatter ] ; }
}
if ( config.timeFormatter ) {
if ( typeof config.timeFormatter === 'function' ) { this.timeFormatter = config.timeFormatter ; }
else { this.timeFormatter = this.logger.timeFormatter[ config.timeFormatter ] ; }
}
}
|
javascript
|
{
"resource": ""
}
|
q13128
|
HouseholdCommunications
|
train
|
function HouseholdCommunications (f1, householdID) {
if (!householdID) {
throw new Error('HouseholdCommunications requires a household ID!')
}
Communications.call(this, f1, {
path: '/Households/' + householdID + '/Communications'
})
}
|
javascript
|
{
"resource": ""
}
|
q13129
|
assemble
|
train
|
function assemble( page ) {
if( typeof page !== 'object' ) {
return Promise.reject( new Error(
'PageAssembler.assemble must be called with a page artifact (object)'
) );
}
removeDisabledItems( page );
return loadPageRecursively( page, page.name, [] );
}
|
javascript
|
{
"resource": ""
}
|
q13130
|
train
|
function(extension) {
// If transformer already cached return that.
if (extension in transformers) {
return transformers[extension];
}
// Retrieve the transformer if available.
const transformer = totransformer(extension);
transformers[extension] = transformer ? jstransformer(transformer) : false;
// Return transformer.
return transformers[extension];
}
|
javascript
|
{
"resource": ""
}
|
|
q13131
|
Database
|
train
|
function Database(configuration) {
Database.super_.call(this, configuration);
Object.defineProperties(this, {
/**
* Database host.
*
* @property host
* @type String
* @final
*/
host: {value: configuration.host},
/**
* Database port.
*
* @property port
* @type Number
* @final
*/
port: {value: configuration.port},
/**
* Database name.
*
* @property name
* @type String
* @final
*/
name: {value: configuration.database},
/**
* Database user name.
*
* @property username
* @type String
* @final
*/
username: {value: configuration.username},
/**
* Database user password.
*
* @property password
* @type String
* @final
*/
password: {value: configuration.password}
});
}
|
javascript
|
{
"resource": ""
}
|
q13132
|
train
|
function(err, changes) {
if(cleaner.called) {
return;
}
cleaner.called = true;
if(err) {
// Build a custom extra object, with hydration error details
var extra = JSON.parse(JSON.stringify(task));
extra.changes = changes;
extra.stdout = stdout;
extra.stderr = stderr;
logError(err, extra);
child.reset();
}
else {
// Make the child available again
child.available = true;
}
cb(err, changes);
if(stdout !== "") {
loggingTask.std = "out";
log.info(loggingTask, stdout);
}
if(stderr !== "") {
loggingTask.std = "err";
log.info(loggingTask, stderr);
}
clearTimeout(timeout);
}
|
javascript
|
{
"resource": ""
}
|
|
q13133
|
train
|
function(elem) {
if(util.isArray(elem)) {
return (elem.length === 0);
}
if(elem instanceof Object) {
if(util.isDate(elem)) {
return false;
}
return (Object.getOwnPropertyNames(elem).length === 0);
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q13134
|
DateToStr
|
train
|
function DateToStr(date) {
// Init the return variable
var sRet = '';
// Add the year
sRet += date.getFullYear() + '-';
// Add the month
var iMonth = date.getMonth();
sRet += ((iMonth < 10) ? '0' + iMonth : iMonth.toString()) + '-'
// Add the day
var iDay = date.getDate();
sRet += ((iDay < 10) ? '0' + iDay : iDay.toString())
// Return the date
return sRet;
}
|
javascript
|
{
"resource": ""
}
|
q13135
|
DateTimeToStr
|
train
|
function DateTimeToStr(datetime) {
// Init the return variable with the date
var sRet = DateToStr(datetime);
// Add the time
sRet += ' ' + datetime.toTimeString().substr(0,8);
// Return the new date/time
return sRet;
}
|
javascript
|
{
"resource": ""
}
|
q13136
|
Hydro
|
train
|
function Hydro() {
if (!(this instanceof Hydro)) {
return new Hydro();
}
this.loader = loader;
this.plugins = [];
this.emitter = new EventEmitter;
this.runner = new Runner;
this.frame = new Frame(this.runner.topLevel);
this.interface = new Interface(this, this.frame);
this.config = new Config;
}
|
javascript
|
{
"resource": ""
}
|
q13137
|
twTokenStrike
|
train
|
function twTokenStrike(stream, state) {
var maybeEnd = false,
ch, nr;
while (ch = stream.next()) {
if (ch == "-" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "-");
}
return ret("text", "strikethrough");
}
|
javascript
|
{
"resource": ""
}
|
q13138
|
Provider
|
train
|
function Provider(storage) {
Object.defineProperties(this, {
/**
* The provider storage.
*
* @property storage
* @type Storage
* @final
*/
storage: {value: storage}
});
if (!(this.storage instanceof Storage))
throw new TypeError('storage must be of type Storage');
}
|
javascript
|
{
"resource": ""
}
|
q13139
|
train
|
function() {
return {
useConsumer: useConsumer,
useEventDispatcher: useEventDispatcher,
useEnvelope: useEnvelope,
usePipeline: usePipeline,
useRouteName: useRouteName,
useRoutePattern: useRoutePattern
};
}
|
javascript
|
{
"resource": ""
}
|
|
q13140
|
Timer
|
train
|
function Timer (callback, start) {
this.callback = callback;
this.startDate = null;
if (!exists(start) || start !== false) {
this.start();
}
}
|
javascript
|
{
"resource": ""
}
|
q13141
|
train
|
function(_list,_low,_high){
if (_low>_high) return -1;
var _middle = Math.ceil((_low+_high)/2),
_result = _docheck(_list[_middle],_middle,_list);
if (_result==0)
return _middle;
if (_result<0)
return _doSearch(_list,_low,_middle-1);
return _doSearch(_list,_middle+1,_high);
}
|
javascript
|
{
"resource": ""
}
|
|
q13142
|
train
|
function(url, img) {
var svgImage = document.createElementNS(SVG_NS_URL, 'image');
svgImage.setAttributeNS(XLINK_NS_URL, 'xlink:href', url);
svgImage.setAttribute('x', 0);
svgImage.setAttribute('y', 0);
svgImage.setAttribute('width', img.width);
svgImage.setAttribute('height', img.height);
return svgImage;
}
|
javascript
|
{
"resource": ""
}
|
|
q13143
|
train
|
function(_id,_clazz,_event){
_cache[_id] = _v._$page(_event);
_e._$addClassName(_id,_clazz);
}
|
javascript
|
{
"resource": ""
}
|
|
q13144
|
_wrap
|
train
|
function _wrap (handler, emitter) {
return async (req, res) => {
try {
let response = await handler(req)
await response.send(res)
} catch (err) {
// normalize
if (! (err instanceof Error)) {
err = new Error(`Non-error thrown: "${typeof err}"`)
}
// support ENOENT
if (err.code === 'ENOENT') {
err.expose = true
err.status = 404
}
// send
res.statusCode = err.status || err.statusCode || 500
res.end()
// delegate
emitter.emit('error', err)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q13145
|
_onError
|
train
|
function _onError (err) {
if (err.status === 404 || err.statusCode === 404 || err.expose) return
let msg = err.stack || err.toString()
console.error(`\n${msg.replace(/^/gm, ' ')}\n`)
}
|
javascript
|
{
"resource": ""
}
|
q13146
|
train
|
function (ttag, scanner) {
if (ttag.type === 'INCLUSION' || ttag.type === 'BLOCKOPEN') {
var args = ttag.args;
if (ttag.path[0] === 'each' && args[1] && args[1][0] === 'PATH' &&
args[1][1][0] === 'in') {
// For slightly better error messages, we detect the each-in case
// here in order not to complain if the user writes `{{#each 3 in x}}`
// that "3 is not a function"
} else {
if (args.length > 1 && args[0].length === 2 && args[0][0] !== 'PATH') {
// we have a positional argument that is not a PATH followed by
// other arguments
scanner.fatal("First argument must be a function, to be called on " +
"the rest of the arguments; found " + args[0][0]);
}
}
}
var position = ttag.position || TEMPLATE_TAG_POSITION.ELEMENT;
if (position === TEMPLATE_TAG_POSITION.IN_ATTRIBUTE) {
if (ttag.type === 'DOUBLE' || ttag.type === 'ESCAPE') {
return;
} else if (ttag.type === 'BLOCKOPEN') {
var path = ttag.path;
var path0 = path[0];
if (! (path.length === 1 && (path0 === 'if' ||
path0 === 'unless' ||
path0 === 'with' ||
path0 === 'each'))) {
scanner.fatal("Custom block helpers are not allowed in an HTML attribute, only built-in ones like #each and #if");
}
} else {
scanner.fatal(ttag.type + " template tag is not allowed in an HTML attribute");
}
} else if (position === TEMPLATE_TAG_POSITION.IN_START_TAG) {
if (! (ttag.type === 'DOUBLE')) {
scanner.fatal("Reactive HTML attributes must either have a constant name or consist of a single {{helper}} providing a dictionary of names and values. A template tag of type " + ttag.type + " is not allowed here.");
}
if (scanner.peek() === '=') {
scanner.fatal("Template tags are not allowed in attribute names, only in attribute values or in the form of a single {{helper}} that evaluates to a dictionary of name=value pairs.");
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13147
|
train
|
function (path, args, mustacheType) {
var self = this;
var nameCode = self.codeGenPath(path);
var argCode = self.codeGenMustacheArgs(args);
var mustache = (mustacheType || 'mustache');
return 'Spacebars.' + mustache + '(' + nameCode +
(argCode ? ', ' + argCode.join(', ') : '') + ')';
}
|
javascript
|
{
"resource": ""
}
|
|
q13148
|
validate
|
train
|
function validate (rootPath) {
var manifest;
var webextensionManifest;
var errors = {};
try {
manifest = JSON.parse(fs.readFileSync(join(rootPath, "package.json")));
} catch (e) {
errors.parsing = utils.getErrorMessage("COULD_NOT_PARSE") + "\n" + e.message;
return errors;
}
if (!validateID(manifest)) {
errors.id = utils.getErrorMessage("INVALID_ID");
}
if (!validateMain(rootPath)) {
errors.main = utils.getErrorMessage("MAIN_DNE");
}
if (!validateTitle(manifest)) {
errors.title = utils.getErrorMessage("INVALID_TITLE");
}
if (!validateName(manifest)) {
errors.name = utils.getErrorMessage("INVALID_NAME");
}
if (!validateVersion(manifest)) {
errors.version = utils.getErrorMessage("INVALID_VERSION");
}
// If both a package.json and a manifest.json files exists in the addon
// root dir, raise an helpful error message that suggest to use web-ext instead.
if (fs.existsSync(join(rootPath, "manifest.json"))) {
errors.webextensionManifestFound = utils.getErrorMessage("WEBEXT_ERROR");
}
return errors;
}
|
javascript
|
{
"resource": ""
}
|
q13149
|
train
|
function (tagName) {
// HTMLTag is the per-tagName constructor of a HTML.Tag subclass
var HTMLTag = function (/*arguments*/) {
// Work with or without `new`. If not called with `new`,
// perform instantiation by recursively calling this constructor.
// We can't pass varargs, so pass no args.
var instance = (this instanceof HTML.Tag) ? this : new HTMLTag;
var i = 0;
var attrs = arguments.length && arguments[0];
if (attrs && (typeof attrs === 'object')) {
// Treat vanilla JS object as an attributes dictionary.
if (! HTML.isConstructedObject(attrs)) {
instance.attrs = attrs;
i++;
} else if (attrs instanceof HTML.Attrs) {
var array = attrs.value;
if (array.length === 1) {
instance.attrs = array[0];
} else if (array.length > 1) {
instance.attrs = array;
}
i++;
}
}
// If no children, don't create an array at all, use the prototype's
// (frozen, empty) array. This way we don't create an empty array
// every time someone creates a tag without `new` and this constructor
// calls itself with no arguments (above).
if (i < arguments.length)
instance.children = SLICE.call(arguments, i);
return instance;
};
HTMLTag.prototype = new HTML.Tag;
HTMLTag.prototype.constructor = HTMLTag;
HTMLTag.prototype.tagName = tagName;
return HTMLTag;
}
|
javascript
|
{
"resource": ""
}
|
|
q13150
|
NotFoundError
|
train
|
function NotFoundError(id) {
Error.captureStackTrace(this, this.constructor);
Object.defineProperties(this, {
/**
* The resource id which hasn't been found.
*
* @property id
* @type Mixed
* @final
*/
id: {value: id},
/**
* Error message.
*
* @property message
* @type String
* @final
*/
message: {value: 'Could not found resource "' + id + '"', writable: true},
/**
* The error name.
*
* @property name
* @type String
* @final
*/
name: {value: 'NotFoundError', writable: true}
});
}
|
javascript
|
{
"resource": ""
}
|
q13151
|
mkdirRecursive
|
train
|
function mkdirRecursive(directoryPath, callback) {
directoryPath = path.resolve(directoryPath);
// Try to create directory
fs.mkdir(directoryPath, function(error) {
if (error && error.code === 'EEXIST') {
// Can't create directory it already exists
// It may have been created by another loop
callback();
} else if (error && error.code === 'ENOENT') {
// Can't create directory, parent directory does not exist
// Create parent directory
mkdirRecursive(path.dirname(directoryPath), function(error) {
if (!error) {
// Now that parent directory is created, create requested directory
fs.mkdir(directoryPath, function(error) {
if (error && error.code === 'EEXIST') {
// Can't create directory it already exists
// It may have been created by another loop
callback();
} else
callback(error);
});
} else
callback(error);
});
} else
callback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q13152
|
rmdirRecursive
|
train
|
function rmdirRecursive(directoryPath, callback) {
// Open directory
fs.readdir(directoryPath, function(error, resources) {
// Failed reading directory
if (error)
return callback(error);
var pendingResourceNumber = resources.length;
// No more pending resources, done for this directory
if (!pendingResourceNumber) {
// Remove directory
fs.rmdir(directoryPath, callback);
}
// Iterate through the list of resources in the directory
resources.forEach(function(resource) {
var resourcePath = path.join(directoryPath, resource);
// Get resource stats
fs.stat(resourcePath, function(error, stats) {
if (error)
return callback(error);
// Resource correspond to a directory
if (stats.isDirectory()) {
resources = rmdirRecursive(path.join(directoryPath, resource), function(error) {
if (error)
return callback(error);
pendingResourceNumber--;
if (!pendingResourceNumber)
fs.rmdir(directoryPath, callback);
});
} else {
// Resource does not correspond to a directory
// Mark resource as treated
// Remove file
fs.unlink(resourcePath, function(error) {
if (error)
return callback(error);
else {
pendingResourceNumber--;
if (!pendingResourceNumber)
fs.rmdir(directoryPath, callback);
}
});
}
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q13153
|
copyFile
|
train
|
function copyFile(sourceFilePath, destinationFilePath, callback) {
var onError = function(error) {
callback(error);
};
var safecopy = function(sourceFilePath, destinationFilePath, callback) {
if (sourceFilePath && destinationFilePath && callback) {
try {
var is = fs.createReadStream(sourceFilePath);
var os = fs.createWriteStream(destinationFilePath);
is.on('error', onError);
os.on('error', onError);
is.on('end', function() {
os.end();
});
os.on('finish', function() {
callback();
});
is.pipe(os);
} catch (e) {
callback(new Error(e.message));
}
} else callback(new Error('File path not defined'));
};
var pathDir = path.dirname(destinationFilePath);
this.mkdir(pathDir,
function(error) {
if (error) callback(error);
else safecopy(sourceFilePath, destinationFilePath, callback);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q13154
|
removeResizeListener
|
train
|
function removeResizeListener(resizeListener) {
removeIdFromList(rootListener, resizeListener.id);
if (a4p.isDefined(listenersIndex[resizeListener.id])) {
delete listenersIndex[resizeListener.id];
}
if (a4p.isDefined(listenersIndex[resizeListener.name]) && (listenersIndex[resizeListener.name].id == resizeListener.id)) {
delete listenersIndex[resizeListener.name];
}
}
|
javascript
|
{
"resource": ""
}
|
q13155
|
keyExpansion
|
train
|
function keyExpansion(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [�5.2]
var Nb = 4; // Number of columns (32-bit words) comprising the State. For this standard, Nb = 4.
var Nk = key.length / 4; // Number of 32-bit words comprising the Cipher Key. Nk = 4/6/8 for 128/192/256-bit keys
var Nr = Nk + 6; // Number of rounds. Nr = 10/12/14 for 128/192/256-bit keys
var trace;
var w = new Array(Nb * (Nr + 1));
var temp = new Array(4);
for (var i = 0; i < Nk; i++) {
var r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]];
w[i] = r;
/*
trace = new Array(4);
for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]);
console.log('w['+i+']='+fidj.Hex.encode(trace.join('')));
*/
}
for (var i = Nk; i < (Nb * (Nr + 1)); i++) {
w[i] = new Array(4);
for (var t = 0; t < 4; t++) temp[t] = w[i - 1][t];
if (i % Nk == 0) {
temp = subWord(rotWord(temp));
for (var t = 0; t < 4; t++) temp[t] ^= rCon[i / Nk][t];
} else if (Nk > 6 && i % Nk == 4) {
temp = subWord(temp);
}
for (var t = 0; t < 4; t++) w[i][t] = w[i - Nk][t] ^ temp[t];
/*
trace = new Array(4);
for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]);
console.log('w['+i+']='+fidj.Hex.encode(trace.join('')));
*/
}
return w;
}
|
javascript
|
{
"resource": ""
}
|
q13156
|
slugify
|
train
|
function slugify(s, opts) {
opts = opts || {};
s = str(s);
if (!opts.mixedCase) { s = s.toLowerCase(); }
return s
.replace(/&/g, '-and-')
.replace(/\+/g, '-plus-')
.replace((opts.allow ?
new RegExp('[^-.a-zA-Z0-9' + _.escapeRegExp(opts.allow) + ']+', 'g') :
/[^-.a-zA-Z0-9]+/g), '-')
.replace(/--+/g, '-')
.replace(/^-(.)/, '$1')
.replace(/(.)-$/, '$1');
}
|
javascript
|
{
"resource": ""
}
|
q13157
|
unPrefix
|
train
|
function unPrefix(s, prefix) {
s = str(s);
if (!prefix) return s;
if (s.slice(0, prefix.length) === prefix) return s.slice(prefix.length);
return s;
}
|
javascript
|
{
"resource": ""
}
|
q13158
|
cap1
|
train
|
function cap1(s) {
s = str(s);
return s.slice(0,1).toUpperCase() + s.slice(1);
}
|
javascript
|
{
"resource": ""
}
|
q13159
|
csv
|
train
|
function csv(arg) {
return ( _.isArray(arg) ? arg :
_.isObject(arg) ? _.values(arg) :
[arg]).join(', ');
}
|
javascript
|
{
"resource": ""
}
|
q13160
|
matchedMetadata
|
train
|
function matchedMetadata(file, metadata) {
for (let name in metadata) {
const data = metadata[name];
if (!data.pattern) return undefined;
if (minimatch(file, data.pattern)) return data.metadata;
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q13161
|
removeUrlPath
|
train
|
function removeUrlPath (uri) {
var parsed = url.parse(uri);
if (parsed.host) {
delete parsed.pathname;
}
return url.format(parsed);
}
|
javascript
|
{
"resource": ""
}
|
q13162
|
transform
|
train
|
function transform(file) {
// Parses CSS file and turns it into a \n-separated img URLs.
var data = file.contents.toString('utf-8');
var matches = [];
var match;
while ((match = url_pattern.exec(data)) !== null) {
var url = match[1];
// Ensure it is an absolute URL (no relative URLs).
var has_origin = url.search(/(https?):|\/\//) === 0 || url[0] === '/';
if (!has_origin) {
var absolute_path = path.join(MKT_CONFIG.CSS_DEST_PATH, url);
url = '/' + path.relative('src', absolute_path);
}
if (img_urls.indexOf(url) === -1) {
matches.push(url);
img_urls.push(url);
}
}
return matches.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q13163
|
build
|
train
|
function build(config, locale, done) {
const shouldWatch = (util.env[`watch`] || util.env[`w`]) && (config.watch !== false);
if (locale && config.i18n && (config.i18n.locales instanceof Array) && (locale === config.i18n.locales[0]))
locale = undefined;
config = normalizeConfig(config, locale);
metalsmith(config.base || __dirname)
.clean(false)
.source(config.src)
.ignore(config.ignore)
.destination(config.dest)
.metadata(config.metadata.global)
.use(collections(config.collections))
.use(related(config.related))
.use((config.tags) ? tags(config.tags) : noop())
.use(pagination(config.pagination))
.use(metadata(config.metadata.collections))
.use(markdown(config.markdown))
.use(config.multilingual ? multilingual(locale) : noop())
.use(permalinks(config.permalinks))
.use(pathfinder(locale, config.i18n && config.i18n.locales))
.use(layouts(config.layouts))
.use(inPlace(config.inPlace))
.use((config.prism !== false) ? prism(config.prism, locale) : noop())
.use((config.mathjax !== false) ? mathjax(config.mathjax, locale) : noop())
.use(permalinks(config.permalinks))
.use(reporter(locale))
.build(function(err) {
if (err && shouldWatch) util.log(util.colors.blue(`[metalsmith]`), util.colors.red(err));
done(!shouldWatch && err);
});
}
|
javascript
|
{
"resource": ""
}
|
q13164
|
getDefaults
|
train
|
function getDefaults(context, options) {
const defaults = _.cloneDeep(DEFAULT_CONFIG);
const taskName = context && context.seq[0];
if (options.src) {
if (taskName)
defaults.watch = {
files: [$.glob(`**/*`, { base: $.glob(options.src, { base: options.base }), exts: FILE_EXTENSIONS })],
tasks: [taskName]
};
defaults.jade.basedir = $.glob(options.src, { base: options.base });
defaults.pug.basedir = $.glob(options.src, { base: options.base });
defaults.inPlace.engineOptions.basedir = $.glob(options.src, { base: options.base });
}
return defaults;
}
|
javascript
|
{
"resource": ""
}
|
q13165
|
getConfig
|
train
|
function getConfig(context, options, extendsDefaults) {
const defaults = getDefaults(context, options);
const config = $.config(options, defaults, (typeof extendsDefaults !== `boolean`) || extendsDefaults);
config.metadata = { global: config.metadata, collections: {
'error-pages': {
pattern: `**/{500,404}.*`,
metadata: {
permalink: false
}
}
}};
return config;
}
|
javascript
|
{
"resource": ""
}
|
q13166
|
train
|
function(entries, exchangePrefix, connectionFunc, options) {
events.EventEmitter.call(this);
assert(options.validator, 'options.validator must be provided');
this._conn = null;
this.__reconnectTimer = null;
this._connectionFunc = connectionFunc;
this._channel = null;
this._connecting = null;
this._entries = entries;
this._exchangePrefix = exchangePrefix;
this._options = options;
this._errCount = 0;
this._lastErr = Date.now();
this._lastTime = 0;
this._sleeping = null;
this._sleepingTimeout = null;
if (options.drain || options.component) {
console.log('taskcluster-lib-stats is now deprecated!\n' +
'Use the `monitor` option rather than `drain`.\n' +
'`monitor` should be an instance of taskcluster-lib-monitor.\n' +
'`component` is no longer needed. Prefix your `monitor` before use.');
}
var monitor = null;
if (options.monitor) {
monitor = options.monitor;
}
entries.forEach((entry) => {
this[entry.name] = (...args) => {
// Construct message and routing key from arguments
var message = entry.messageBuilder.apply(undefined, args);
common.validateMessage(this._options.rootUrl, this._options.serviceName, this._options.version,
options.validator, entry, message);
var routingKey = common.routingKeyToString(entry, entry.routingKeyBuilder.apply(undefined, args));
var CCs = entry.CCBuilder.apply(undefined, args);
assert(CCs instanceof Array, 'CCBuilder must return an array');
// Serialize message to buffer
var payload = new Buffer(JSON.stringify(message), 'utf8');
// Find exchange name
var exchange = exchangePrefix + entry.exchange;
// Log that we're publishing a message
debug('Publishing message on exchange: %s', exchange);
// Return promise
return this._connect().then(channel => {
return new Promise((accept, reject) => {
// Start timer
var start = null;
if (monitor) {
start = process.hrtime();
}
// Set a timeout
let done = false;
this._sleep12Seconds().then(() => {
if (!done) {
let err = new Error('publish message timed out after 12s');
this._handleError(err);
reject(err);
}
});
// Publish message
channel.publish(exchange, routingKey, payload, {
persistent: true,
contentType: 'application/json',
contentEncoding: 'utf-8',
CC: CCs,
}, (err, val) => {
// NOTE: many channel errors will not invoke this callback at all,
// hence the 12-second timeout
done = true;
if (monitor) {
var d = process.hrtime(start);
monitor.measure(exchange, d[0] * 1000 + d[1] / 1000000);
monitor.count(exchange);
}
// Handle errors
if (err) {
err.methodName = entry.name;
err.exchange = exchange;
err.routingKey = routingKey;
err.payload = payload;
err.ccRoutingKeys = CCs;
debug('Failed to publish message: %j and routingKey: %s, ' +
'with error: %s, %j', message, routingKey, err, err);
if (monitor) {
monitor.reportError(err);
}
return reject(err);
}
accept(val);
});
});
});
};
});
}
|
javascript
|
{
"resource": ""
}
|
|
q13167
|
train
|
function(options) {
this._entries = [];
this._options = {
durableExchanges: true,
};
assert(options.serviceName, 'serviceName must be provided');
assert(options.projectName, 'projectName must be provided');
assert(options.version, 'version must be provided');
assert(options.title, 'title must be provided');
assert(options.description, 'description must be provided');
assert(!options.exchangePrefix, 'exchangePrefix is not allowed');
assert(!options.schemaPrefix, 'schemaPrefix is not allowed');
this.configure(options);
}
|
javascript
|
{
"resource": ""
}
|
|
q13168
|
LoggerConfiguration
|
train
|
function LoggerConfiguration(logger) {
/**
* Override default logger instance with the provided logger
* @public
* @param {Object|Function} loggerOrFactoryFunction - the logger instance or factory function
*/
function useLogger(loggerOrFactoryFunction) {
cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction');
if (typeof(loggerOrFactoryFunction) === 'function') {
logger = loggerOrFactoryFunction();
}
else {
logger = loggerOrFactoryFunction;
}
};
/**
* Gets the default or overridden logger
* @public
*/
function getParams() {
return { logger };
}
return {
/**
* Gets the target for a configurator function to run on
* @public
*/
getTarget: function() {
return { useLogger: useLogger };
},
getParams: getParams
};
}
|
javascript
|
{
"resource": ""
}
|
q13169
|
useLogger
|
train
|
function useLogger(loggerOrFactoryFunction) {
cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction');
if (typeof(loggerOrFactoryFunction) === 'function') {
logger = loggerOrFactoryFunction();
}
else {
logger = loggerOrFactoryFunction;
}
}
|
javascript
|
{
"resource": ""
}
|
q13170
|
getParams
|
train
|
function getParams(configFunc, configurator) {
assert.optionalFunc(configurator, 'configurator');
let config = configFunc();
let loggerConfig = LoggerConfiguration(logger);
if (configurator) {
let configTarget = _.assign({}, config.getTarget(), loggerConfig.getTarget());
configurator(configTarget);
}
return _.assign({}, config.getParams(), loggerConfig.getParams());
}
|
javascript
|
{
"resource": ""
}
|
q13171
|
createTopology
|
train
|
function createTopology(connectionInfo, logger) {
let options = connectionInfo;
if (typeof(connectionInfo) === 'string') {
let parsed = url.parse(connectionInfo);
options = {
server: parsed.hostname,
port: parsed.port || '5672',
protocol: parsed.protocol || 'amqp://',
user: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[0]) : 'guest',
pass: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[1]) : 'guest',
vhost: parsed.path && parsed.path.substring(1)
};
}
let connection = Connection(options, logger.withNamespace('connection'));
let topology = Topology(connection, logger.withNamespace('topology'));
return topology;
}
|
javascript
|
{
"resource": ""
}
|
q13172
|
generatePrismicDocuments
|
train
|
function generatePrismicDocuments(config) {
return prismic.getAPI(config.apiEndpoint, { accessToken: config.accessToken })
.then(api => (prismic.getEverything(api, null, ``, _.flatMap(config.collections, (val, key) => (`my.${key}.${val.sortBy}${val.reverse ? ` desc` : ``}`)))))
.then(res => {
util.log(util.colors.blue(`[prismic]`), `Fetched a total of ${res.results.length} documents`);
if (res.results.length) res.results.forEach(doc => util.log(util.colors.blue(`[prismic]`), `Fetched document [${doc.type}]: ${doc.slug}`));
const documents = prismic.reduce(res.results, false, config);
// Populate config metadata with retrieved documents.
if (!config.metadata) config.metadata = { $data: {} };
_.merge(config.metadata.$data, documents);
for (let docType in documents) {
const c = _.get(config, `collections.${docType}`);
if (c && c.permalink) {
const subdir = `.prismic/${docType}`;
const dir = path.join(path.join(config.base || ``, config.src || ``), subdir);
c.pattern = path.join(subdir, `**/*`);
documents[docType].forEach(doc => {
const filename = `${doc.uid || _.kebabCase(doc.slug)}.html`;
const frontMatter = yaml.stringify(_.omit(doc, [`next`, `prev`]));
fs.mkdirsSync(dir);
fs.writeFileSync(path.join(dir, filename), `---\n${frontMatter}---\n`);
});
}
}
return;
});
}
|
javascript
|
{
"resource": ""
}
|
q13173
|
train
|
function(linesImagesPaths, linePath, lineWidth, lineHeight, horizontally, lineQuality) {
return function(callback) {
self.aggregate(
linesImagesPaths,
linePath,
lineWidth,
lineHeight,
horizontally,
lineQuality,
temporaryDirectoryPath,
callback
);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q13174
|
train
|
function(callback) {
if (imagesPaths.length >= numberOfColumns * numberOfRows) return callback();
var transparentImagePath = path.join(temporaryDirectoryPath, 'transparent.png');
gm(width, height, '#00000000').write(transparentImagePath, function(error) {
// Add as many as needed transparent images to the list of images
var totalMissingImages = numberOfColumns * numberOfRows - imagesPaths.length;
for (var i = 0; i < totalMissingImages; i++)
imagesPaths.push(transparentImagePath);
callback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q13175
|
train
|
function(callback) {
var asyncFunctions = [];
for (var i = 0; i < numberOfRows; i++) {
var rowsImagesPaths = imagesPaths.slice(i * numberOfColumns, i * numberOfColumns + numberOfColumns);
var lineWidth = width;
var lineHeight = height;
var linePath = path.join(temporaryDirectoryPath, 'line-' + i);
linesPaths.push(linePath);
asyncFunctions.push(createLine(rowsImagesPaths, linePath, lineWidth, lineHeight, true, 100));
}
async.parallel(asyncFunctions, function(error, results) {
if (error) return callback(error);
results.forEach(function(line) {
line.forEach(function(image) {
if (image.image === path.join(temporaryDirectoryPath, 'transparent.png')) return;
var spritePathChunks = path.parse(image.sprite).name.match(/-([0-9]+)$/);
var lineIndex = (spritePathChunks && parseInt(spritePathChunks[1])) || 0;
image.y = image.y + (lineIndex * height);
image.sprite = destinationPath;
images.push(image);
});
});
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q13176
|
train
|
function(callback) {
createLine(linesPaths, destinationPath, width * numberOfColumns, height, false, quality)(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q13177
|
train
|
function(spriteImagesPaths, spriteDestinationPath) {
return function(callback) {
self.generateSprite(
spriteImagesPaths,
spriteDestinationPath,
width,
height,
totalColumns,
maxRows,
quality,
temporaryDirectoryPath,
callback
);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q13178
|
train
|
function () {
var properties = this.properties;
_.forEach(properties, function (prop, name) {
prop = this.getProperty(name);
this.stopListening(prop, EVENT_CHANGE);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q13179
|
train
|
function (properties) {
properties = properties || {};
_.forEach(properties, function (property, name) {
this.initProperty(name, property);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q13180
|
train
|
function (name, value) {
var prop = this.getProperty(name);
var Constructor;
if (!prop) {
Constructor = this.getConstructor(name, value);
prop = new Constructor();
prop = this.setProperty(name, prop);
}
if (typeof value !== 'undefined') {
prop.set(value);
}
return prop;
}
|
javascript
|
{
"resource": ""
}
|
|
q13181
|
train
|
function (name) {
var args = arguments;
var len = args.length;
if (len === 0) {
return this.getMap();
}
else if (len === 1) {
return this.getValue(name);
}
else {
return this.getValues.apply(this, args);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13182
|
train
|
function () {
var map = this.properties;
var pairs = _.map(map, function (prop, name) {
return [name, prop.get()];
});
var result = _.object(pairs);
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q13183
|
train
|
function () {
var result = [];
var args = arguments;
var l = args.length;
var name, value;
for (var i = 0; i < l; i++) {
name = args[i];
value = this.getValue(name);
result.push(value);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q13184
|
train
|
function (name, newValue) {
if (arguments.length > 1) {
this.setValue(name, newValue);
}
else {
var attrs = name;
this.setMap(attrs);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13185
|
train
|
function (attrs) {
attrs = attrs || {};
_.forEach(attrs, function (val, name) {
this.setValue(name, val);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q13186
|
train
|
function (name, newValue) {
var property = this.getProperty(name);
if (!property) {
this.initProperty(name, newValue);
}
else {
property.set(newValue);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13187
|
train
|
function (name, prop) {
this.unsetProperty(name);
this.properties[name] = prop;
this.listenTo(prop, EVENT_CHANGE, this.change);
return prop;
}
|
javascript
|
{
"resource": ""
}
|
|
q13188
|
train
|
function (name) {
var prop = this.properties[name];
if (prop) {
this.stopListening(prop, EVENT_CHANGE, this.change);
delete this.properties[name];
return prop;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q13189
|
train
|
function (/* items... */) {
var items = slice(arguments);
var item;
for (var i = 0, l = items.length; i < l; i++) {
item = items[i];
$Array.push.call(this, item);
this.trigger(EVENT_ADD, item, this.length);
}
return this.length;
}
|
javascript
|
{
"resource": ""
}
|
|
q13190
|
train
|
function (start, length) {
var removed, item;
if (arguments.length < 1) {
start = 0;
}
if (arguments.length < 2) {
length = this.length - start;
}
removed = [];
while (start < this.length && length-- > 0) {
item = this[start];
$Array.splice.call(this, start, 1);
this.trigger(EVENT_REMOVE, item);
removed.push(item);
}
return removed;
}
|
javascript
|
{
"resource": ""
}
|
|
q13191
|
train
|
function (start/*, items... */) {
var items = slice(arguments, 1);
var item, index;
for (var i = 0, l = items.length; i < l; i++) {
item = items[i];
index = start + i;
$Array.splice.call(this, index, 0, item);
this.trigger(EVENT_ADD, item, index);
}
return this.length;
}
|
javascript
|
{
"resource": ""
}
|
|
q13192
|
train
|
function (items) {
var args = slice(items);
args.unshift(0);
this.empty();
this.insert.apply(this, args);
return this.length;
}
|
javascript
|
{
"resource": ""
}
|
|
q13193
|
train
|
function (index) {
if (arguments.length < 1) {
return this;
}
if (index < 0) {
index = this.length + index;
}
if (hasProperty(this, index)) {
return this[index];
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q13194
|
Collection
|
train
|
function Collection (items) {
this.items = new ok.Items();
this.start();
if (items) {
this.add(items);
}
this.init();
}
|
javascript
|
{
"resource": ""
}
|
q13195
|
train
|
function () {
this.stop();
this.listenTo(this.items, EVENT_ADD, this.triggerAdd);
this.listenTo(this.items, EVENT_REMOVE, this.triggerRemove);
this.listenTo(this.items, EVENT_SORT, this.triggerSort);
this.listenTo(this.items, EVENT_ADD, this.updateLength);
this.listenTo(this.items, EVENT_REMOVE, this.updateLength);
this.listenTo(this.items, EVENT_ADD, this.watchItem);
this.listenTo(this.items, EVENT_REMOVE, this.unwatchItem);
}
|
javascript
|
{
"resource": ""
}
|
|
q13196
|
train
|
function () {
var items = _.flatten(arguments);
for (var i = 0, l = items.length; i < l; i++) {
this.addItem(items[i], this.items.length);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13197
|
train
|
function (item/*, index*/) {
var old = item;
var Constructor;
if (!(item instanceof ok.Base)) {
Constructor = this.getConstructor(item);
item = new Constructor(item);
}
var identified = this.identify(item);
if (identified) {
identified.set(old);
}
else {
var index = this.findInsertIndex(item);
this.items.insert(index + 1, item);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13198
|
train
|
function (item) {
var index = -1;
this.items.forEach(function (comparedTo, newIndex) {
if (this.comparator(comparedTo, item) <= 0) {
index = newIndex;
return false;
}
}, this);
return index;
}
|
javascript
|
{
"resource": ""
}
|
|
q13199
|
train
|
function (item) {
var items = this.items;
var removed = 0;
for (var i = 0, l = items.length; i < l; i++) {
if (items[i] === item) {
items.splice(i, 1);
i--;
removed++;
}
}
return removed;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.