_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q9800
|
buildOpeningElementAttributes
|
train
|
function buildOpeningElementAttributes(attribs, file) {
let _props = []
let objs = []
function pushProps() {
if (_props.length === 0) return
objs.push(t.objectExpression(_props))
_props = []
}
while (attribs.length) {
const prop = attribs.shift()
if (t.isJSXSpreadAttribute(prop)) {
pushProps()
prop.argument._isSpread = true
objs.push(prop.argument)
} else {
_props.push(convertAttribute(prop))
}
}
pushProps()
objs = objs.map(o => {
return o._isSpread ? o : groupProps(o.properties, t)
})
if (objs.length === 1) {
// Only one object
attribs = objs[0]
} else if (objs.length > 0) {
// Add prop merging helper
const helper = file.addImport('babel-helper-vue-jsx-merge-props', 'default', '_mergeJSXProps')
// Spread it
attribs = t.callExpression(
helper,
[t.arrayExpression(objs)]
)
}
return attribs
}
|
javascript
|
{
"resource": ""
}
|
q9801
|
decoder
|
train
|
function decoder(mtype) {
const gen = util.codegen([ 'r', 'l' ], mtype.name + '$decode')('if(!(r instanceof Reader))')('r=Reader.create(r)')('var c=l===undefined?r.len:r.pos+l,m=new this.ctor' + (mtype.fieldsArray.filter(field => field.map).length ? ',k' : ''))('while(r.pos<c){')('var t=r.uint32()');
if (mtype.group) {
gen('if((t&7)===4)')('break');
}
gen('switch(t>>>3){');
for (let i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
const field = mtype._fieldsArray[i].resolve();
const type = field.resolvedType instanceof Enum ? 'int32' : field.type;
const ref = 'm' + util.safeProp(field.name);
gen('case %i:', field.id);
// Map fields
if (field.map) {
gen('r.skip().pos++')('if(%s===util.emptyObject)', ref)('%s=new Map()', ref)('k=r.%s()', field.keyType)('r.pos++'); // assumes id 2 + value wireType
// NOTE: 原来这里将 Long 对象转换成 hash 字符串是因为 Object 的 key 只能是字符串,现在用 Map 来实现后就让它原样输出就好了
// if (types.long[field.keyType] !== undefined) {
// if (types.basic[type] === undefined) {
// gen('%s.set(typeof k==="object"?util.longToHash(k):k, types[%i].decode(r,r.uint32()));', ref, i); // can't be groups
// } else {
// gen('%s.set(typeof k==="object"?util.longToHash(k):k, r.%s());', ref, type);
// }
// } else {
if (types.basic[type] === undefined) {
gen('%s.set(k, types[%i].decode(r,r.uint32()));', ref, i); // can't be groups
} else {
gen('%s.set(k, r.%s());', ref, type);
}
// }
// Repeated fields
} else if (field.repeated) {
gen('if(!(%s&&%s.length))', ref, ref)('%s=[]', ref);
// Packable (always check for forward and backward compatiblity)
if (types.packed[type] !== undefined) {
gen('if((t&7)===2){')('var c2=r.uint32()+r.pos')('while(r.pos<c2)')('%s.push(r.%s())', ref, type)('}else');
}
// Non-packed
if (types.basic[type] === undefined) {
gen(field.resolvedType.group ? '%s.push(types[%i].decode(r))' : '%s.push(types[%i].decode(r,r.uint32()))', ref, i);
} else {
gen('%s.push(r.%s())', ref, type);
}
// Non-repeated
} else if (types.basic[type] === undefined) {
gen(field.resolvedType.group ? '%s=types[%i].decode(r)' : '%s=types[%i].decode(r,r.uint32())', ref, i);
} else {
gen('%s=r.%s()', ref, type);
}
gen('break');
// Unknown fields
}
gen('default:')('r.skipType(t&7)')('break')('}')('}');
// Field presence
for (let i = 0; i < mtype._fieldsArray.length; ++i) {
const rfield = mtype._fieldsArray[i];
if (rfield.required) {
gen('if(!m.hasOwnProperty(%j))', rfield.name)('throw util.ProtocolError(%j,{instance:m})', missing(rfield));
}
}
return gen('return m');
}
|
javascript
|
{
"resource": ""
}
|
q9802
|
populateOptions
|
train
|
function populateOptions(node, values) {
if (node.tagName !== 'option') {
for (var i = 0, len = node.children.length; i < len ; i++) {
populateOptions(node.children[i], values);
}
return;
}
var value = node.attrs && node.attrs.value;
value = value || node.props && node.props.value;
if (!values.hasOwnProperty(value)) {
return;
}
node.attrs = node.attrs || {};
node.attrs.selected = 'selected';
node.props = node.props || {};
node.props.selected = true;
}
|
javascript
|
{
"resource": ""
}
|
q9803
|
train
|
function(sInput, levels, indentString) {
var indentedLineBreak;
indentString = indentString || '\t';
indentedLineBreak = '\n'+ ( new Array( levels + 1 ).join( indentString ) );
return indentedLineBreak + sInput.split('\n').join(indentedLineBreak);
}
|
javascript
|
{
"resource": ""
}
|
|
q9804
|
train
|
function(baseUri, branch, filePath, fileName) {
var varPath = fileName ? 'blob/' : 'tree/'
,branch = branch ? branch + '/' : 'develop'
,filePath = path.relative(process.cwd(), filePath) + '/'
;
fileName = fileName || '';
return baseUri ? baseUri + varPath + branch + filePath + fileName : null;
}
|
javascript
|
{
"resource": ""
}
|
|
q9805
|
register
|
train
|
function register(types, converter) {
types.split(' ').forEach(function (type) {
converters[type] = converter;
});
}
|
javascript
|
{
"resource": ""
}
|
q9806
|
run
|
train
|
function run () {
var midSequence = this.middlewares.reverse()
var initialNext = this.next.bind()
var req = this.req
var res = this.res
var nestedCallSequence
// create the call sequence
nestedCallSequence = midSequence.reduce(middlewareReducer, initialNext)
// call it
nestedCallSequence.call()
/**
* Reduce the middleware sequence to a nested middleware handler sequence
* @function
* @inner
* @private
* @param {Function} callSequence intermediate resulting call sequence
* @param {Function} middleware the current middleware
* @returns {Function} the new intermediate resulting call sequence
*/
function middlewareReducer (callSequence, middleware) {
return function nextHandler (err) {
// if the previous middleware passed an error argument
if (err !== undefined) {
if (isErrorHandler(middleware)) {
// call the current middleware if it is an error handler middleware
middleware(err, req, res, callSequence)
} else {
// else skip the current middleware and call the intermediate sequence
callSequence(err)
}
} else {
// if no error argument is passed
if (isErrorHandler(middleware)) {
// skip the current middleware if it is an errorHandler
callSequence()
} else {
// else call it
middleware(req, res, callSequence)
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9807
|
middlewareReducer
|
train
|
function middlewareReducer (callSequence, middleware) {
return function nextHandler (err) {
// if the previous middleware passed an error argument
if (err !== undefined) {
if (isErrorHandler(middleware)) {
// call the current middleware if it is an error handler middleware
middleware(err, req, res, callSequence)
} else {
// else skip the current middleware and call the intermediate sequence
callSequence(err)
}
} else {
// if no error argument is passed
if (isErrorHandler(middleware)) {
// skip the current middleware if it is an errorHandler
callSequence()
} else {
// else call it
middleware(req, res, callSequence)
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9808
|
append
|
train
|
function append (/* mid_0, ..., mid_n */) {
var i
for (i = 0; i < arguments.length; i++) {
if (typeof arguments[i] !== 'function') {
var type = typeof arguments[i]
var errMsg = 'Given middlewares must be functions. "' + type + '" given.'
throw new TypeError(errMsg)
}
}
for (i = 0; i < arguments.length; i++) {
this.middlewares.push(arguments[i])
}
return this
}
|
javascript
|
{
"resource": ""
}
|
q9809
|
appendList
|
train
|
function appendList (middlewares) {
if (!Array.isArray(middlewares)) {
var errorMsg = 'First argument must be an array of middlewares. '
errorMsg += typeof middlewares + ' given.'
throw new TypeError(errorMsg)
}
return this.append.apply(this, middlewares)
}
|
javascript
|
{
"resource": ""
}
|
q9810
|
appendIf
|
train
|
function appendIf (filter /*, middlewares */) {
var errorMsg
var middlewares = []
if (arguments.length < 2) {
errorMsg = 'ConnectSequence#appendIf() takes 2 arguments. '
errorMsg += arguments.length + ' given.'
throw new MissingArgumentError(errorMsg)
}
if (typeof filter !== 'function') {
errorMsg = 'The first argument must be a filter function. '
errorMsg += typeof filter + ' given.'
throw new TypeError(errorMsg)
}
var middleware, i
for (i = 1; i < arguments.length; i++) {
middleware = arguments[i]
if (typeof middleware !== 'function') {
errorMsg = 'The second argument must be a middleware function. '
errorMsg += typeof middleware + ' given.'
throw new TypeError(errorMsg)
}
middlewares.push(middleware)
}
var firstMiddleware = middlewares[0]
if (isErrorHandler(firstMiddleware)) {
this.append(function (err, req, res, next) {
req.__connectSequenceFilterValue = filter(req)
if (req.__connectSequenceFilterValue) {
firstMiddleware(err, req, res, next)
} else {
next()
}
})
} else {
this.append(function (req, res, next) {
req.__connectSequenceFilterValue = filter(req)
if (req.__connectSequenceFilterValue) {
firstMiddleware(req, res, next)
} else {
next()
}
})
}
for (i = 1; i < middlewares.length; i++) {
middleware = middlewares[i]
appendOnFilterValue.call(this, middleware)
}
return this
}
|
javascript
|
{
"resource": ""
}
|
q9811
|
appendListIf
|
train
|
function appendListIf (filter, middlewares) {
var args = [filter]
for (var i = 0; i < middlewares.length; i++) {
args.push(middlewares[i])
}
return this.appendIf.apply(this, args)
}
|
javascript
|
{
"resource": ""
}
|
q9812
|
isErrorHandler
|
train
|
function isErrorHandler (cb) {
var str = cb.toString()
var args = str.split('(')[1].split(')')[0].split(',')
return args.length === 4
}
|
javascript
|
{
"resource": ""
}
|
q9813
|
condense
|
train
|
function condense (node) {
if (node.nodes.length === 1 && node.nodes[0].nodes.length > 0) {
return condense({
label: (node.label || '') + node.nodes[0].label,
nodes: node.nodes[0].nodes
})
} else {
return {
label: node.label,
nodes: node.nodes.map(condense)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9814
|
Device
|
train
|
function Device(Connection) {
var self = this;
// call super class
EventEmitter2.call(this, {
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
if (this.log) {
this.log = _.wrap(this.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
} else if (Device.prototype.log) {
Device.prototype.log = _.wrap(Device.prototype.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
this.log = Device.prototype.log;
} else {
var debug = require('debug')(this.constructor.name);
this.log = function(msg) {
debug(msg);
};
}
this.id = uuid();
this.Connection = Connection;
this.attributes = { id: this.id };
this.on('disconnect', function() {
self.connection = null;
});
}
|
javascript
|
{
"resource": ""
}
|
q9815
|
FtdiDevice
|
train
|
function FtdiDevice(deviceSettings, connectionSettings, Connection) {
// call super class
Device.call(this, Connection);
if (deviceSettings instanceof ftdi.FtdiDevice) {
this.ftdiDevice = deviceSettings;
this.set(this.ftdiDevice.deviceSettings);
} else {
this.set(deviceSettings);
}
this.set('connectionSettings', connectionSettings);
this.set('state', 'close');
}
|
javascript
|
{
"resource": ""
}
|
q9816
|
train
|
function(taskFn, taskParams) {
var task = this._buildTask(taskFn, taskParams);
if(task.params.weight > this._params.weightLimit) {
throw Error('task with weight of ' +
task.params.weight +
' can\'t be performed in queue with limit of ' +
this._params.weightLimit);
}
this._enqueueTask(task);
this._isStopped || this._scheduleRun();
task.defer.promise().always(
function() {
this._stats.processingTasksCount--;
this._stats.processedTasksCount++;
},
this);
return task.defer.promise();
}
|
javascript
|
{
"resource": ""
}
|
|
q9817
|
train
|
function() {
if(!this._isStopped) {
return;
}
this._isStopped = false;
var processedBuffer = this._processedBuffer;
if(processedBuffer.length) {
this._processedBuffer = [];
nextTick(function() {
while(processedBuffer.length) {
processedBuffer.shift()();
}
});
}
this._hasPendingTasks() && this._scheduleRun();
}
|
javascript
|
{
"resource": ""
}
|
|
q9818
|
countMatches
|
train
|
function countMatches(orders) {
var matched = 0, dimension = orders[0].length
while(matched < dimension) {
for(var j=1; j<orders.length; ++j) {
if(orders[j][matched] !== orders[0][matched]) {
return matched
}
}
++matched
}
return matched
}
|
javascript
|
{
"resource": ""
}
|
q9819
|
FtdiSerialDevice
|
train
|
function FtdiSerialDevice(deviceSettings, connectionSettings, Connection) {
if (_.isString(deviceSettings) && (deviceSettings.indexOf('COM') === 0 || deviceSettings.indexOf('/') === 0)) {
this.isSerialDevice = true;
// call super class
SerialDevice.call(this,
deviceSettings,
connectionSettings,
Connection
);
} else {
this.isFtdiDevice = true;
// call super class
FtdiDevice.call(this,
deviceSettings,
connectionSettings,
Connection
);
}
}
|
javascript
|
{
"resource": ""
}
|
q9820
|
strongDirFromContent
|
train
|
function strongDirFromContent (text) {
var m = text.match(strongDirRegExp)
if (!m) {
return null
}
if (m[2] === undefined) {
return 'ltr'
}
return 'rtl'
}
|
javascript
|
{
"resource": ""
}
|
q9821
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomCategory)){
return new AtomCategory(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomCategory.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9822
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Agent)){
return new Agent(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Agent.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9823
|
toSQL
|
train
|
function toSQL() {
if (this._cached) {
return this._cached;
}
if (Array.isArray(this.bindings)) {
this._cached = replaceRawArrBindings(this);
} else if (this.bindings && typeof this.bindings === 'object') {
this._cached = replaceKeyBindings(this);
} else {
this._cached = {
method: 'raw',
sql: this.sql,
bindings: this.bindings
};
}
if (this._wrappedBefore) {
this._cached.sql = this._wrappedBefore + this._cached.sql;
}
if (this._wrappedAfter) {
this._cached.sql = this._cached.sql + this._wrappedAfter;
}
this._cached.options = assign({}, this._options);
return this._cached;
}
|
javascript
|
{
"resource": ""
}
|
q9824
|
reqres
|
train
|
function reqres(res, req) {
if (req && req._headers) {
throw new Error('Received response object where request object was expected');
}
this.res = res;
this.req = req;
if (res) {
if (res.$ && res.$.data) {
this.data = res.$.data;
}
else {
this.data = { error: null };
if (!res.$) {
res.$ = this;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9825
|
xreqhan
|
train
|
function xreqhan(res, req, output) {
if (isResHeaderSent(res)) {
return console.error('request already closed', new Error().stack);
}
output = output || '';
var isBinary = output && Buffer.isBuffer(output);
if (isBinary) {
res.end(output, 'binary');
}
else if (res.send) { //Express adds send
res.send(output);
}
else if (res.end) { //base way to end request
output = reqResOutputToString(req, res, output);
res.end(output);
}
resMarkClosed(res); //add indicators that show response has been closed
}
|
javascript
|
{
"resource": ""
}
|
q9826
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof CollectionContent)){
return new CollectionContent(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(CollectionContent.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9827
|
isGoodHash
|
train
|
function isGoodHash (hash, target) {
hash = new Buffer(hash, 'hex')
target = new Buffer(target, 'hex')
return _.range(32).some(function (index) {
return hash[index] < target[index]
})
}
|
javascript
|
{
"resource": ""
}
|
q9828
|
verifyHeader
|
train
|
function verifyHeader (currentHash, currentHeader, hashPrevBlock, prevHeader, target, isTestnet) {
try {
// check hashPrevBlock
assert.equal(hashPrevBlock, currentHeader.hashPrevBlock)
try {
// check difficulty
assert.equal(currentHeader.bits, target.bits)
// check hash and target
assert.equal(isGoodHash(currentHash, target.target), true)
} catch (err) {
// special case for testnet:
// If no block has been found in 20 minutes, the difficulty automatically
// resets back to the minimum for a single block, after which it returns
// to its previous value.
if (!(err instanceof assert.AssertionError &&
isTestnet &&
currentHeader.time - prevHeader.time > 1200)) {
throw err
}
assert.equal(currentHeader.bits, MAX_BITS)
assert.equal(isGoodHash(currentHash, MAX_TARGET), true)
}
} catch (err) {
if (err instanceof assert.AssertionError) {
throw new errors.Blockchain.VerifyHeaderError(currentHash, 'verification failed')
}
throw err
}
}
|
javascript
|
{
"resource": ""
}
|
q9829
|
clean
|
train
|
function clean(source) {
if (!source) return BLANK;
if (source.charCodeAt(0) === BOM_CODE) source = source.slice(1);
source = source.replace(CR_REGEXP, BLANK).replace(TRAILING_WHITESPACE_REGEXP, BLANK);
return source;
}
|
javascript
|
{
"resource": ""
}
|
q9830
|
lex
|
train
|
function lex(source) {
var tokens = [];
var chunk = clean(source);
var total = chunk.length;
var iterations = 0;
while (chunk.length > 0) {
for (var regexpName in REGEXPS) {
var regexp = REGEXPS[regexpName];
var match = regexp.exec(chunk);
if (match) {
var original = match[0];
var str = original;
if (regexpName === 'string') str = str.replace(/\\"/g, '"');
tokens.push({ type: regexpName, string: str, original: original });
// Need to slice the chunk at the original match length
chunk = chunk.slice(match[0].length, chunk.length);
break;
}
}
// We've probably failed to parse correctly if we get here
if (iterations++ > total) {
var parts = [
'Runiq: Lexer ran too many iterations!',
'--- Failed at chunk: `' + chunk + '`'
];
throw new Error(parts.join('\n'));
}
}
return tokens;
}
|
javascript
|
{
"resource": ""
}
|
q9831
|
Deb
|
train
|
function Deb () {
this.data = tar.pack()
this.control = tar.pack()
this.pkgSize = 0
this.controlFile = {}
this.filesMd5 = []
this.dirs = {}
}
|
javascript
|
{
"resource": ""
}
|
q9832
|
buildControlFile
|
train
|
function buildControlFile (tempPath, definition, callback) {
var self = this
var author = ''
if (definition.package.author) {
author = typeof definition.package.author === 'string'
? definition.package.author
: definition.package.author.name + ' <' + definition.package.author.email + '>'
}
self.controlFile = {
Package: definition.info.name || definition.package.name,
Version: definition.package.version + '-' + (definition.info.rev || '1'),
'Installed-Size': Math.ceil(self.pkgSize / 1024),
Section: 'misc',
Priority: 'optional',
Architecture: definition.info.arch || 'all',
Depends: definition.info.depends || 'lsb-base (>= 3.2)',
Maintainer: author
}
// optional items
if (definition.package.license) {
self.controlFile.License = definition.package.license
}
// optional items
if (definition.package.homepage) {
self.controlFile.Homepage = definition.package.homepage
}
self.controlFile.Description = definition.package.description + '\n ' +
(definition.info.name || definition.package.name) +
': ' + definition.package.description
// create the control file
async.parallel([
function createControlFile (prlDone) {
var controlHeader = ''
async.forEachOf(self.controlFile, function (value, key, done) {
controlHeader += key + ': ' + value + '\n'
done()
}, function (err) {
if (err) {
debug('could not write control file')
return prlDone(err)
}
self.control.entry({name: './control'}, controlHeader, prlDone)
})
}, function createHashFile (prlDone) {
var fileContent = ''
for (var i = 0; i < self.filesMd5.length; i++) {
fileContent += self.filesMd5[i].md5 + ' ' + self.filesMd5[i].path.replace(/^\W*/, '') + '\n'
}
self.control.entry({name: './md5sums'}, fileContent, prlDone)
}, function addScripts (prlDone) {
async.forEachOf(definition.info.scripts, function (path, scriptName, doneScript) {
debug('processing script ', path)
async.waterfall([
fs.access.bind(fs, path, fs.F_OK),
fs.stat.bind(fs, path),
function readFile (stats, wtfDone) {
fs.readFile(path, function (err, data) {
wtfDone(err, stats, data)
})
},
function addScript (stats, data, wtfDone) {
debug('adding script ', scriptName)
self.control.entry({
name: './' + scriptName,
size: stats.size,
mode: parseInt('755', 8)
}, data, wtfDone)
}
], doneScript)
}, prlDone)
}
], function (err) {
if (err) {
debug('could not write control tarball')
return callback(err)
}
debug('successfully created control file')
self.control.finalize()
var file = fs.createWriteStream(path.join(tempPath, 'control.tar.gz'))
file.on('finish', callback)
var compress = zlib.createGzip()
compress.pipe(file)
self.control.pipe(compress)
})
}
|
javascript
|
{
"resource": ""
}
|
q9833
|
packFiles
|
train
|
function packFiles (tempPath, files, callback) {
var self = this
async.eachSeries(files, function (crtFile, done) {
var filePath = path.resolve(crtFile.src[0])
debug('adding %s', filePath)
async.waterfall([
fs.stat.bind(fs, filePath),
function (stats, wtfDone) {
if (stats.isDirectory()) {
addParentDirs(self.data, crtFile.dest, self.dirs, done)
} else {
async.waterfall([
fs.readFile.bind(fs, filePath),
function writeFileToTarball (data, wtf2Done) {
self.data.entry({
name: '.' + crtFile.dest,
size: stats.size
}, data, function (err) {
wtf2Done(err, data)
})
},
function processFile (fileData, wtf2Done) {
self.pkgSize += stats.size
self.filesMd5.push({
path: crtFile.dest,
md5: crypto.createHash('md5').update(fileData).digest('hex')
})
wtf2Done()
}
], wtfDone)
}
}
], done)
}, function (err) {
if (err) {
debug('there was a problem adding files to the .deb package: ', err)
callback(err)
} else {
debug('successfully added files to .deb package')
var file = fs.createWriteStream(path.join(tempPath, 'data.tar.gz'))
file.on('finish', callback)
var compress = zlib.createGzip()
compress.pipe(file)
self.data.pipe(compress)
self.data.finalize()
}
})
}
|
javascript
|
{
"resource": ""
}
|
q9834
|
generateSignature
|
train
|
function generateSignature(email, password) {
let googleDefaultPublicKey = 'AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ==';
let keyBuffer = Buffer.from(googleDefaultPublicKey, 'base64');
let pem = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKJv9Wv79JW5TtlG67etCdoHLl
0pYxhUF4HMmVr3lixMKOqa8IIt4iSGXaHcoSmUKzVqeZyid7K0V3FFvhdQQ922hF
RnJhIKmi2VDQY5tOe6SkSNepAdGKaXhseaiEOUIys7EfBE0GyizVoEWNEETVc9+J
DCUdz/y4B2sf+q5n+QIDAQAB
-----END PUBLIC KEY-----`;
let sha = crypto.createHash('sha1');
sha.update(keyBuffer);
let hash = sha.digest().slice(0, 4);
let rsa = new nodeRSA(pem);
let encrypted = rsa.encrypt(email + '\x00' + password);
let base64Output = Buffer.concat([
Buffer.from([0]),
hash,
encrypted
]).toString('base64');
base64Output = base64Output.replace(/\+/g, '-');
base64Output = base64Output.replace(/\//g, '_');
return base64Output;
}
|
javascript
|
{
"resource": ""
}
|
q9835
|
train
|
function(selectedPort, callback) {
if(selectedPort === false)
grunt.fatal('No available port was found')
self.data.targets.forEach(function(prop) {
pp.injectPort(prop, selectedPort)
})
if(pp.options.name) {
pp.injectPort(pp.options.name, selectedPort)
}
callback(null)
return
}
|
javascript
|
{
"resource": ""
}
|
|
q9836
|
train
|
function(callback) {
var step = 0
async.whilst(
function() {
return ++step <= pp.options.extra
},
function(callback) {
pp.tryPorts = []
var c = grunt.config.get('port-pick-' + step)
// With multiple tasks, do not find a port that we've already found
// in a previous task
if(c) {
callback()
return
}
async.waterfall([
pp.findPort,
function(selectedPort, callback) {
if(selectedPort === false)
grunt.fatal('No available port was found')
grunt.config.set('port-pick-' + this.step, selectedPort)
grunt.log.writeln( '>> '.green + 'port-pick-' + this.step + '=' +
selectedPort)
callback()
}.bind({step: step})
],
function(err) {
callback()
})
},
function(err) {
done()
}
)
}
|
javascript
|
{
"resource": ""
}
|
|
q9837
|
columnize
|
train
|
function columnize(target) {
var columns = typeof target === 'string' ? [target] : target;
var str = '',
i = -1;
while (++i < columns.length) {
if (i > 0) {
str += ', ';
}
str += this.wrap(columns[i]);
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q9838
|
parameter
|
train
|
function parameter(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
return this.unwrapRaw(value, true) || '?';
}
|
javascript
|
{
"resource": ""
}
|
q9839
|
wrap
|
train
|
function wrap(value) {
var raw;
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
raw = this.unwrapRaw(value);
if (raw) {
return raw;
}
if (typeof value === 'number') {
return value;
}
return this._wrapString(value + '');
}
|
javascript
|
{
"resource": ""
}
|
q9840
|
operator
|
train
|
function operator(value) {
var raw = this.unwrapRaw(value);
if (raw) {
return raw;
}
if (operators[(value || '').toLowerCase()] !== true) {
throw new TypeError('The operator "' + value + '" is not permitted');
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q9841
|
direction
|
train
|
function direction(value) {
var raw = this.unwrapRaw(value);
if (raw) {
return raw;
}
return orderBys.indexOf((value || '').toLowerCase()) !== -1 ? value : 'asc';
}
|
javascript
|
{
"resource": ""
}
|
q9842
|
compileCallback
|
train
|
function compileCallback(callback, method) {
var client = this.client;
// Build the callback
var builder = client.queryBuilder();
callback.call(builder, builder);
// Compile the callback, using the current formatter (to track all bindings).
var compiler = client.queryCompiler(builder);
compiler.formatter = this;
// Return the compiled & parameterized sql.
return compiler.toSQL(method || 'select');
}
|
javascript
|
{
"resource": ""
}
|
q9843
|
outputQuery
|
train
|
function outputQuery(compiled, isParameter) {
var sql = compiled.sql || '';
if (sql) {
if (compiled.method === 'select' && (isParameter || compiled.as)) {
sql = '(' + sql + ')';
if (compiled.as) {
return this.alias(sql, this.wrap(compiled.as));
}
}
}
return sql;
}
|
javascript
|
{
"resource": ""
}
|
q9844
|
_wrapString
|
train
|
function _wrapString(value) {
var segments,
asIndex = value.toLowerCase().indexOf(' as ');
if (asIndex !== -1) {
var first = value.slice(0, asIndex);
var second = value.slice(asIndex + 4);
return this.alias(this.wrap(first), this.wrap(second));
}
var i = -1,
wrapped = [];
segments = value.split('.');
while (++i < segments.length) {
value = segments[i];
if (i === 0 && segments.length > 1) {
wrapped.push(this.wrap((value || '').trim()));
} else {
wrapped.push(this.client.wrapIdentifier((value || '').trim()));
}
}
return wrapped.join('.');
}
|
javascript
|
{
"resource": ""
}
|
q9845
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Collection)){
return new Collection(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Collection.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9846
|
train
|
function(xhr) {
var response = {
headers: {},
statusCode: xhr.status
};
var headerPairs = xhr.getAllResponseHeaders().split('\u000d\u000a');
for (var i = 0; i < headerPairs.length; i++) {
var headerPair = headerPairs[i],
index = headerPair.indexOf('\u003a\u0020');
if (index > 0) {
var key = headerPair.substring(0, index);
var val = headerPair.substring(index + 2);
response.headers[key.toLowerCase()] = val;
}
}
return response;
}
|
javascript
|
{
"resource": ""
}
|
|
q9847
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Fact)){
return new Fact(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Fact.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9848
|
Handshake
|
train
|
function Handshake(context, options) {
if (!this) return new Handshake(context, options);
options = options || {};
this.stringify = options.stringify || qs.stringify;
this.configure = Object.create(null);
this.timers = new Tick(context);
this.id = options.id || v4;
this.context = context;
this.payload = {};
this.timeout = 'handshake timeout' in options
? options['handshake timeout']
: '5 seconds';
this.update();
}
|
javascript
|
{
"resource": ""
}
|
q9849
|
Route
|
train
|
function Route(query, node, callbacks, options) {
options = options || {};
this.query = query;
this.node = node;
this.callbacks = callbacks;
this.regexp = normalize(node
, this.keys = []
, options.sensitive
, options.strict);
}
|
javascript
|
{
"resource": ""
}
|
q9850
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Root)){
return new Root(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Root.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9851
|
factory
|
train
|
function factory( query, context = document ) {
const converter = bsc();
const selectorEngine = new SelectorEngine();
const bemQuery = new BEMQuery( query, context, converter, selectorEngine );
return bemQuery;
}
|
javascript
|
{
"resource": ""
}
|
q9852
|
addChild
|
train
|
function addChild(data) {
var child = new TreeNode(data, this);
if (!this.children) {
this.children = [];
}
this.children.push(child);
return child;
}
|
javascript
|
{
"resource": ""
}
|
q9853
|
find
|
train
|
function find(data) {
if (data === this.data) {
return this;
}
if (this.children) {
for (var i = 0, _length = this.children.length, target = null; i < _length; i++) {
target = this.children[i].find(data);
if (target) {
return target;
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q9854
|
leaves
|
train
|
function leaves() {
if (!this.children || this.children.length === 0) {
// this is a leaf
return [this];
}
// if not a leaf, return all children's leaves recursively
var leaves = [];
if (this.children) {
for (var i = 0, _length2 = this.children.length; i < _length2; i++) {
leaves.push.apply(leaves, this.children[i].leaves());
}
}
return leaves;
}
|
javascript
|
{
"resource": ""
}
|
q9855
|
forEach
|
train
|
function forEach(callback) {
if (typeof callback !== 'function') {
throw new TypeError('forEach() callback must be a function');
}
// run this node through function
callback(this);
// do the same for all children
if (this.children) {
for (var i = 0, _length3 = this.children.length; i < _length3; i++) {
this.children[i].forEach(callback);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q9856
|
train
|
function() {
var self = this;
if (self.filter.get("valid")) {
self.$el.removeClass("invalidvalid");
self.$el.addClass("valid");
}
else {
self.$el.removeClass("valid");
self.$el.addClass("invalid");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9857
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomFeed)){
return new AtomFeed(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomFeed.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9858
|
pad
|
train
|
function pad(side, num, ch) {
var
exp = `${side === 'left' ? '' : '^'}.{${num}}${side === 'right' ? '' : '$'}`,
re = new RegExp(exp), pad = '';
do {
pad += ch;
} while(pad.length < num);
return re.exec( (side === 'left') ? (pad + this) : (this + pad) )[0];
}
|
javascript
|
{
"resource": ""
}
|
q9859
|
ImboClient
|
train
|
function ImboClient(options, publicKey, privateKey) {
// Run a feature check, ensuring all required features are present
features.checkFeatures();
// Initialize options
var opts = this.options = {
hosts: parseUrls(options.hosts || options),
publicKey: options.publicKey || publicKey,
privateKey: options.privateKey || privateKey,
user: options.user || options.publicKey || publicKey
};
// Validate options
['publicKey', 'privateKey', 'user'].forEach(function validateOption(opt) {
if (!opts[opt] || typeof opts[opt] !== 'string') {
throw new Error('`options.' + opt + '` must be a valid string');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q9860
|
train
|
function(file, callback) {
if (isBrowser && file instanceof window.File) {
// Browser File instance
return this.addImageFromBuffer(file, callback);
}
// File on filesystem. Note: the reason why we need the size of the file
// is because of reverse proxies like Varnish which doesn't handle chunked
// Transfer-Encoding properly - instead we need to explicitly pass the
// content length so it knows not to terminate the HTTP connection
readers.getLengthOfFile(file, function(err, fileSize) {
if (err) {
return callback(err);
}
readers.createReadStream(file).pipe(request({
method: 'POST',
uri: this.getSignedResourceUrl('POST', this.getImagesUrl()),
json: true,
headers: {
'Accept': 'application/json',
'User-Agent': 'imboclient-js',
'Content-Length': fileSize
},
onComplete: function(addErr, res, body) {
callback(addErr, body ? body.imageIdentifier : null, body, res);
}
}));
}.bind(this));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9861
|
train
|
function(source, callback) {
var url = this.getSignedResourceUrl('POST', this.getImagesUrl()),
isFile = isBrowser && source instanceof window.File,
onComplete = callback.onComplete || callback,
onProgress = callback.onProgress || null;
request({
method: 'POST',
uri: url,
body: source,
headers: {
'Accept': 'application/json',
'User-Agent': 'imboclient-js',
'Content-Length': isFile ? source.size : source.length
},
onComplete: function(err, res, body) {
body = jsonparse(body);
onComplete(err, body ? body.imageIdentifier : null, body, res);
},
onProgress: onProgress
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9862
|
train
|
function(url, callback) {
if (isBrowser) {
// Browser environments can't pipe, so download the file and add it
return this.getImageDataFromUrl(url, function(err, data) {
if (err) {
return callback(err);
}
this.addImageFromBuffer(data, callback);
}.bind(this));
}
// Pipe the source URL into a POST-request
request({ uri: url }).pipe(request({
method: 'POST',
uri: this.getSignedResourceUrl('POST', this.getImagesUrl()),
json: true,
headers: {
'Accept': 'application/json',
'User-Agent': 'imboclient-js'
},
onComplete: function(err, res, body) {
callback(err, body ? body.imageIdentifier : null, body, res);
}
}));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9863
|
train
|
function(callback) {
request.get(this.getStatsUrl(), function(err, res, body) {
callback(err, body, res);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9864
|
train
|
function(callback) {
request.get(this.getStatusUrl(), function(err, res, body) {
if (err) {
return callback(err);
}
body = body || {};
body.status = res.statusCode;
body.date = new Date(body.date);
callback(err, body, res);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9865
|
train
|
function(callback) {
request.get(this.getUserUrl(), function(err, res, body) {
if (body && body.lastModified) {
body.lastModified = new Date(body.lastModified);
}
if (body && !body.user && body.publicKey) {
body.user = body.publicKey;
}
callback(err, body, res);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9866
|
train
|
function(imageIdentifier, callback) {
var url = this.getImageUrl(imageIdentifier, { usePrimaryHost: true }),
signedUrl = this.getSignedResourceUrl('DELETE', url);
request.del(signedUrl, callback);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9867
|
train
|
function(imageIdentifier, callback) {
this.headImage(imageIdentifier, function(err, res) {
if (err) {
return callback(err);
}
var headers = res.headers,
prefix = 'x-imbo-original';
callback(err, {
width: parseInt(headers[prefix + 'width'], 10),
height: parseInt(headers[prefix + 'height'], 10),
filesize: parseInt(headers[prefix + 'filesize'], 10),
extension: headers[prefix + 'extension'],
mimetype: headers[prefix + 'mimetype']
});
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9868
|
train
|
function(imageIdentifier, data, callback, method) {
var url = this.getMetadataUrl(imageIdentifier);
request({
method: method || 'POST',
uri: this.getSignedResourceUrl(method || 'POST', url),
json: data,
onComplete: function(err, res, body) {
callback(err, body, res);
}
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9869
|
train
|
function(imageIdentifier, callback) {
request.get(this.getMetadataUrl(imageIdentifier), function(err, res, body) {
callback(err, body, res);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9870
|
train
|
function(imageIdentifier, callback) {
var url = this.getMetadataUrl(imageIdentifier);
request.del(this.getSignedResourceUrl('DELETE', url), callback);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9871
|
train
|
function(query, callback) {
if (typeof query === 'function' && !callback) {
callback = query;
query = null;
}
// Fetch the response
request.get(this.getImagesUrl(query), function(err, res, body) {
callback(
err,
body && body.images,
body && body.search,
res
);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9872
|
train
|
function(imageIdentifier, options) {
if (typeof imageIdentifier !== 'string' || imageIdentifier.length === 0) {
throw new Error(
'`imageIdentifier` must be a non-empty string, was "' + imageIdentifier + '"' +
' (' + typeof imageIdentifier + ')'
);
}
options = options || {};
return new ImageUrl({
baseUrl: this.getHostForImageIdentifier(
imageIdentifier,
options.usePrimaryHost
),
path: options.path,
user: this.options.user,
publicKey: this.options.publicKey,
privateKey: this.options.privateKey,
imageIdentifier: imageIdentifier
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9873
|
train
|
function(options) {
return new ImboUrl({
baseUrl: this.options.hosts[0],
user: typeof options.user !== 'undefined' ? options.user : this.options.user,
publicKey: this.options.publicKey,
privateKey: this.options.privateKey,
queryString: options.query,
path: options.path
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9874
|
train
|
function(imageIdentifier, callback) {
var url = this.getImageUrl(imageIdentifier).setPath('/shorturls'),
signed = this.getSignedResourceUrl('DELETE', url);
request.del(signed, callback);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9875
|
train
|
function(imageIdentifier, shortUrl, callback) {
var id = shortUrl instanceof ShortUrl ? shortUrl.getId() : shortUrl,
url = this.getImageUrl(imageIdentifier).setPath('/shorturls/' + id),
signed = this.getSignedResourceUrl('DELETE', url);
request.del(signed, callback);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9876
|
train
|
function(imgPath, callback) {
this.getImageChecksum(imgPath, function(err, checksum) {
if (err) {
return callback(err);
}
this.imageWithChecksumExists(checksum, callback);
}.bind(this));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9877
|
train
|
function(checksum, callback) {
var query = (new ImboQuery()).originalChecksums([checksum]).limit(1);
this.getImages(query, function(err, images, search) {
if (err) {
return callback(err);
}
var exists = search.hits > 0;
callback(err, exists, exists ? images[0].imageIdentifier : err);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9878
|
train
|
function(callback) {
request.get(
this.getResourceUrl({ path: '/groups', user: null }),
function onResourceGroupsResponse(err, res, body) {
callback(
err,
body && body.groups,
body && body.search,
res
);
}
);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9879
|
train
|
function(groupName, callback) {
request.get(
this.getResourceUrl({ path: '/groups/' + groupName, user: null }),
function onResourceGroupResponse(err, res, body) {
callback(err, body && body.resources, res);
}
);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9880
|
train
|
function(groupName, resources, callback) {
this.resourceGroupExists(groupName, function onGroupExistsResponse(err, exists) {
if (err) {
return callback(err);
}
if (exists) {
return callback(new Error(
'Resource group `' + groupName + '` already exists'
));
}
this.editResourceGroup(groupName, resources, callback);
}.bind(this));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9881
|
train
|
function(groupName, callback) {
var url = this.getResourceUrl({ path: '/groups/' + groupName, user: null });
request.del(this.getSignedResourceUrl('DELETE', url), callback);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9882
|
train
|
function(groupName, callback) {
request.head(
this.getResourceUrl({ path: '/groups/' + groupName, user: null }),
get404Handler(callback)
);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9883
|
train
|
function(publicKey, callback) {
request.head(
this.getResourceUrl({ path: '/keys/' + publicKey, user: null }),
get404Handler(callback)
);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9884
|
train
|
function(publicKey, expandGroups, callback) {
var qs = '';
if (!callback && typeof expandGroups === 'function') {
callback = expandGroups;
} else if (expandGroups) {
qs = '?expandGroups=1';
}
request.get(
this.getResourceUrl({ path: '/keys/' + publicKey + '/access' + qs, user: null }),
function onAccessControlRulesResponse(err, res, body) {
callback(err, body, res);
}
);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9885
|
train
|
function(publicKey, aclRuleId, callback) {
request.get(
this.getResourceUrl({
path: '/keys/' + publicKey + '/access/' + aclRuleId,
user: null
}),
function onAccessControlRulesResponse(err, res, body) {
callback(err, body, res);
}
);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9886
|
train
|
function(publicKey, rules, callback) {
if (!Array.isArray(rules)) {
rules = [rules];
}
if (!publicKey) {
throw new Error('Public key must be a valid string');
}
var url = this.getResourceUrl({ path: '/keys/' + publicKey + '/access', user: null });
request({
method: 'POST',
uri: this.getSignedResourceUrl('POST', url),
json: rules,
onComplete: function(err, res, body) {
callback(err, body, res);
}
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9887
|
train
|
function(imageUrl, callback) {
readers.getContentsFromUrl(imageUrl.toString(), function(err, data) {
callback(err, err ? null : data);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9888
|
train
|
function(imageIdentifier, usePrimary) {
if (usePrimary) {
return this.options.hosts[0];
}
var dec = imageIdentifier.charCodeAt(imageIdentifier.length - 1);
// If this is an old image identifier (32 character hex string),
// maintain backwards compatibility
if (imageIdentifier.match(/^[a-f0-9]{32}$/)) {
dec = parseInt(imageIdentifier.substr(0, 2), 16);
}
return this.options.hosts[dec % this.options.hosts.length];
}
|
javascript
|
{
"resource": ""
}
|
|
q9889
|
train
|
function(method, url, timestamp) {
var data = [method, url, this.options.publicKey, timestamp].join('|'),
signature = crypto.sha256(this.options.privateKey, data);
return signature;
}
|
javascript
|
{
"resource": ""
}
|
|
q9890
|
train
|
function(method, url, date) {
var timestamp = (date || new Date()).toISOString().replace(/\.\d+Z$/, 'Z'),
addPubKey = this.options.user !== this.options.publicKey,
qs = url.toString().indexOf('?') > -1 ? '&' : '?',
signUrl = addPubKey ? url + qs + 'publicKey=' + this.options.publicKey : url,
signature = this.generateSignature(method, signUrl.toString(), timestamp);
qs = addPubKey ? '&' : qs;
qs += 'signature=' + encodeURIComponent(signature);
qs += '×tamp=' + encodeURIComponent(timestamp);
return signUrl + qs;
}
|
javascript
|
{
"resource": ""
}
|
|
q9891
|
train
|
function(options){
var option,
o;
this.options || (this.options = {});
o = this.options = primish.merge(primish.clone(this.options), options);
// add the events as well, if class has events.
if ((this.on && this.off))
for (option in o){
if (o.hasOwnProperty(option)){
if (typeof o[option] !== sFunction || !(/^on[A-Z]/).test(option)) continue;
this.on(removeOn(option), o[option]);
delete o[option];
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9892
|
Service
|
train
|
function Service(options) {
if (!(this instanceof Service)) {
return new Service(options);
}
options = options || {};
debug('New Service: %j', options);
// There's no reasonable way to protect this, so we let it be writable with
// the understanding that .update is called in the future. TL;DR - Write at
// your own risk.
this.data = clone(options.data || {});
this._dataHash = sigmund(this.data);
this._initProperties(options);
assert(this.name, 'Name is required.');
}
|
javascript
|
{
"resource": ""
}
|
q9893
|
train
|
function(options) {
options = options || {};
var params = [
'color=' + (options.color || '000000').replace(/^#/, ''),
'width=' + toInt(options.width || 1),
'height=' + toInt(options.height || 1),
'mode=' + (options.mode || 'outbound')
];
return this.append('border:' + params.join(','));
}
|
javascript
|
{
"resource": ""
}
|
|
q9894
|
train
|
function(options) {
options = options || {};
if (!options.width || !options.height) {
throw new Error('width and height must be specified');
}
var params = [
'width=' + toInt(options.width),
'height=' + toInt(options.height)
];
if (options.mode) {
params.push('mode=' + options.mode);
}
if (options.x) {
params.push('x=' + toInt(options.x));
}
if (options.y) {
params.push('y=' + toInt(options.y));
}
if (options.bg) {
params.push('bg=' + options.bg.replace(/^#/, ''));
}
return this.append('canvas:' + params.join(','));
}
|
javascript
|
{
"resource": ""
}
|
|
q9895
|
train
|
function(options) {
var params = [],
opts = options || {},
transform = 'contrast';
if (opts.sharpen) {
params.push('sharpen=' + opts.sharpen);
}
if (params.length) {
transform += ':' + params.join(',');
}
return this.append(transform);
}
|
javascript
|
{
"resource": ""
}
|
|
q9896
|
train
|
function(options) {
var opts = options || {},
mode = opts.mode,
x = opts.x,
y = opts.y,
width = opts.width,
height = opts.height;
if (!mode && (isNaN(x) || isNaN(y))) {
throw new Error('x and y needs to be specified without a crop mode');
}
if (mode === 'center-x' && isNaN(y)) {
throw new Error('y needs to be specified when mode is center-x');
} else if (mode === 'center-y' && isNaN(x)) {
throw new Error('x needs to be specified when mode is center-y');
} else if (isNaN(width) || isNaN(height)) {
throw new Error('width and height needs to be specified');
}
var params = [
'width=' + toInt(width),
'height=' + toInt(height)
];
if (isNumeric(x)) {
params.push('x=' + toInt(x));
}
if (isNumeric(y)) {
params.push('y=' + toInt(y));
}
if (mode) {
params.push('mode=' + mode);
}
return this.append('crop:' + params.join(','));
}
|
javascript
|
{
"resource": ""
}
|
|
q9897
|
train
|
function(options) {
var params = [];
if (options.width) {
params.push('width=' + toInt(options.width));
}
if (options.height) {
params.push('height=' + toInt(options.height));
}
if (!params.length) {
throw new Error('width and/or height needs to be specified');
}
return this.append('maxSize:' + params.join(','));
}
|
javascript
|
{
"resource": ""
}
|
|
q9898
|
train
|
function(options) {
if (!options || isNaN(options.angle)) {
throw new Error('angle needs to be specified');
}
var bg = (options.bg || '000000').replace(/^#/, '');
return this.append('rotate:angle=' + options.angle + ',bg=' + bg);
}
|
javascript
|
{
"resource": ""
}
|
|
q9899
|
train
|
function(options) {
var params = [],
opts = options || {},
transform = 'sharpen';
if (opts.preset) {
params.push('preset=' + opts.preset);
}
if (typeof opts.radius !== 'undefined') {
params.push('radius=' + opts.radius);
}
if (typeof opts.sigma !== 'undefined') {
params.push('sigma=' + opts.sigma);
}
if (typeof opts.gain !== 'undefined') {
params.push('gain=' + opts.gain);
}
if (typeof opts.threshold !== 'undefined') {
params.push('threshold=' + opts.threshold);
}
if (params.length) {
transform += ':' + params.join(',');
}
return this.append(transform);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.