_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q4200
toYaml
train
function toYaml(data, options) { var defaults = {indent: 2, skipInvalid: false, flowLevel: -1}; var opts = extend(defaults, options);
javascript
{ "resource": "" }
q4201
codegen
train
function codegen(compiled, options) { const { code } = generate(t.file(t.program(compiled)),
javascript
{ "resource": "" }
q4202
getBlocks
train
function getBlocks(ast) { ast = Array.isArray(ast) ? ast : [ast]; return ast.map((node) => { if (t.isReturnStatement(node)) { return getBlocks(node.argument); } if (t.isConditionalExpression(node)) { return node.alternate ? [ ...getBlocks(node.consequent), ...getBlocks(node.alternate), ]
javascript
{ "resource": "" }
q4203
blocks
train
function blocks(ast) { const body = [ast]; // start with body of function const nodes = getBlocks(ast.body.body); if (nodes.length) { const {
javascript
{ "resource": "" }
q4204
evaluate
train
function evaluate(code) { const context = { module: { exports: {}, }, }; // eslint-disable-next-line no-new-func const renderFunction = new Function('module', code);
javascript
{ "resource": "" }
q4205
PathExpression
train
function PathExpression(path) { const iterPattern = /^(.*)\[(\d+)]$/; const paths = path.split('.').reduce((prev, key) => { const matches = key.match(iterPattern); if (matches) { const [, rest, index] =
javascript
{ "resource": "" }
q4206
ConcatStringList
train
function ConcatStringList(outputs) { return outputs.length ? outputs.reduce(
javascript
{ "resource": "" }
q4207
UnsafeIter
train
function UnsafeIter(branch) { const key = c.KEY_I(branch.iterSuffix); const arr = t.identifier('arr'); const output = t.identifier('output'); return t.callExpression(t.functionExpression(null, [], t.blockStatement([ t.variableDeclaration('var', [ t.variableDeclarator(arr, Guard(branch.subject.path)), t.variableDeclarator(output, t.stringLiteral('')), t.variableDeclarator(c.LENGTH, t.memberExpression(arr, c.LENGTH)),
javascript
{ "resource": "" }
q4208
tokenizer
train
function tokenizer(input) { const topLevelTokens = getTopLevelTokens(); const length = input.length; const output = []; let cursor = 0; let lastBreak = 0; while (cursor < length) { const slice = input.slice(cursor); const found = matchPattern(topLevelTokens, slice, false); if (found && input[cursor - 1] === '\\') { const text = input.slice(lastBreak, cursor - 1); if (text) { output.push(new Text(text)); } const escapedText = found[1][0]; output.push(new Text(escapedText)); cursor += escapedText.length; lastBreak = cursor; } else if (found) { const [Tok, matches] = found; const text
javascript
{ "resource": "" }
q4209
_buildDependencyTreeOf
train
function _buildDependencyTreeOf(node) { var requireStatements = getRequireStatements(getCode(node.path)) if (requireStatements.length == 0) { return leaves.push(node) } each(requireStatements, function(requireStatement)
javascript
{ "resource": "" }
q4210
_buildLevel
train
function _buildLevel(nodes) { var level = [] levels.push(level) var parents = [] each(nodes, function(node) { if (!seenPaths[node.path]) { seenPaths[node.path] = true
javascript
{ "resource": "" }
q4211
train
function(n) { // If number given, swap endian if (n.constructor == Number) { return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; }
javascript
{ "resource": "" }
q4212
train
function(n) { for (var bytes = []; n > 0; n--)
javascript
{ "resource": "" }
q4213
train
function(words) { for (var bytes = [], b = 0; b < words.length *
javascript
{ "resource": "" }
q4214
train
function(bytes) { for (var hex = [], i = 0; i < bytes.length; i++) { hex.push((bytes[i] >>> 4).toString(16));
javascript
{ "resource": "" }
q4215
train
function(bytes) { for (var base64 = [], i = 0; i < bytes.length; i += 3) { var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; for (var j = 0; j < 4; j++) if (i * 8 + j * 6 <= bytes.length * 8)
javascript
{ "resource": "" }
q4216
train
function(base64) { // Remove non-base-64 characters base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { if (imod4 == 0) continue; bytes.push(((base64map.indexOf(base64.charAt(i - 1))
javascript
{ "resource": "" }
q4217
FtdiDevice
train
function FtdiDevice(settings) { if (typeof(settings) === 'number') { settings = { index: settings }; } EventEmitter.call(this);
javascript
{ "resource": "" }
q4218
train
function(vid, pid, callback) { if (arguments.length === 2) { callback = pid; pid = null; } else if (arguments.length === 1) { callback
javascript
{ "resource": "" }
q4219
matrixFunction
train
function matrixFunction(data, evaluatedData) { const m = data.x.length; var ans = new Array(m); for (var point = 0; point < m; point++) { ans[point]
javascript
{ "resource": "" }
q4220
getLocation
train
function getLocation (node, sourceCode) { if (node.type === 'ArrowFunctionExpression') {
javascript
{ "resource": "" }
q4221
train
function (codePath, node) { funcInfo = { upper: funcInfo, codePath: codePath, hasReturn: false, shouldCheck: TARGET_NODE_TYPE.test(node.type) &&
javascript
{ "resource": "" }
q4222
train
function (node) { if (funcInfo.shouldCheck) { funcInfo.hasReturn = true if (!node.argument) { context.report({ node: node,
javascript
{ "resource": "" }
q4223
hasPromise
train
function hasPromise (node, inBooleanPosition) { switch (node.type) { case 'CallExpression': return hasPromiseMethod(node) case 'UnaryExpression': return hasPromise(node.argument, true) case 'BinaryExpression': return hasPromise(node.left, false) || hasPromise(node.right, false) case 'LogicalExpression': var leftHasPromise = hasPromise(node.left, inBooleanPosition) var rightHasPromise = hasPromise(node.right,
javascript
{ "resource": "" }
q4224
isArgumentLiteral
train
function isArgumentLiteral (node) { return node.arguments
javascript
{ "resource": "" }
q4225
isArgumentByLocator
train
function isArgumentByLocator (node) { if (node.arguments && node.arguments.length && node.arguments[0].type === 'CallExpression') {
javascript
{ "resource": "" }
q4226
_proxy
train
function _proxy(rule, metas) { var opts = _getRequestOpts(metas.req, rule); var request = httpsSyntax.test(rule.replace) ? httpsReq : httpReq; var pipe = request(opts, function (res) { res.headers.via = opts.headers.via; metas.res.writeHead(res.statusCode, res.headers); res.on('error', function (err) {
javascript
{ "resource": "" }
q4227
_getRequestOpts
train
function _getRequestOpts(req, rule) { var opts = url.parse(req.url.replace(rule.regexp, rule.replace), true); var query = (opts.search != null) ? opts.search : ''; if(query) { opts.path = opts.pathname + query;
javascript
{ "resource": "" }
q4228
argvPlugin
train
function argvPlugin(dynamicConfig, options) { var self = this; var separator; var whitelist; if (options && typeof options === "object") { separator = options.separator; whitelist = options.whitelist; }
javascript
{ "resource": "" }
q4229
envPlugin
train
function envPlugin(dynamicConfig, options) { var self = this; var separator; var whitelist; if (options && typeof options === "object") { separator = options.separator; whitelist = options.whitelist;
javascript
{ "resource": "" }
q4230
open
train
function open (path, delimiter = '\r\n') { const self = this; const flags = 'r+'; return new Promise((resolve, reject) => { // Open file for reading and writing. An exception occurs if the file does not exist.
javascript
{ "resource": "" }
q4231
isValidRecord
train
function isValidRecord(rec) { if (rec.v === null || rec.level === null || rec.name === null || rec.hostname === null || rec.pid === null ||
javascript
{ "resource": "" }
q4232
term
train
function term (portPath, delimiter, fd) { return new Promise((resolve, reject) => { let out = '', event = new events.EventEmitter(); try { const _fd = { fd: fd }; // Open a write stream Duplex.Writable = fs.createWriteStream(null, _fd); // Open a read stream Duplex.Readable = fs.createReadStream(null, _fd); Duplex.Readable.setEncoding('utf8'); } catch (error) { reject(error); return; } /** * Serial data receiver; emits the data when received. * @param {String} data - The received data */ Duplex.Readable.on('data', function (data) { if (!data) return; out += data; if (delimiter) { // Check if he data contains the delimiter if (out.indexOf(delimiter) < 0) { return; } // Replace the delimiter in the output data out = out.replace(delimiter, ''); } // Emit the output event.emit('data', out); // Reset the output out = ''; }); /** * Eventhandler that will close the communication. * @param {String} data - The last received data */ const onend = (data) => { if (!event.isOpen) return; event.isOpen = false; event.emit('closed', data); }; /**
javascript
{ "resource": "" }
q4233
compileMappings
train
function compileMappings(oldMappings) { var mappings = oldMappings.slice(0); mappings.sort(function(map1, map2) { if (!map1.attribute) return 1; if (!map2.attribute) return -1; if (map1.attribute !== map2.attribute) { return map1.attribute < map2.attribute ? -1 : 1; } if (map1.value !== map2.value) { return map1.value < map2.value ? -1 : 1; } if (! ('replace' in map1) && ! ('replace' in map2)) { throw
javascript
{ "resource": "" }
q4234
matchClosing
train
function matchClosing(input, tagname, html) { var closeTag = '</' + tagname + '>', openTag = new RegExp('< *' + tagname + '( *|>)', 'g'), closeCount = 0, openCount = -1, from, to, chunk ; from = html.search(input); to = from; while(to > -1 && closeCount !== openCount) { to = html.indexOf(closeTag, to); if (to > -1) {
javascript
{ "resource": "" }
q4235
BunyanFormatWritable
train
function BunyanFormatWritable (opts, out) { if (!(this instanceof BunyanFormatWritable)) return new BunyanFormatWritable(opts, out); opts = opts || {}; opts.objectMode = true; Writable.call(this, opts); this.opts = xtend({
javascript
{ "resource": "" }
q4236
_parseWithXml2js
train
function _parseWithXml2js(xmlContent) { return new Promise(function(resolve, reject) { // parse the pom, erasing all xml2js.parseString(xmlContent, XML2JS_OPTS, function(err, pomObject) { if (err) { // Reject with the error reject(err); } // Replace the arrays with single elements with strings
javascript
{ "resource": "" }
q4237
removeSingleArrays
train
function removeSingleArrays(obj) { // Traverse all the elements of the object traverse(obj).forEach(function traversing(value) { // As the XML parser returns single fields as arrays.
javascript
{ "resource": "" }
q4238
joinNodeModules
train
function joinNodeModules(jsPaths){ _.each(jsPaths, function(jsPath){ var libPath = path.join(nodeModules, jsPath), flattenedLibPath = path.join(flattenedNodeModules, jsPath); if (fs.existsSync(libPath)) {
javascript
{ "resource": "" }
q4239
find
train
function find () { const serialPath = this.paths.linux.serial; const readLink = (file, filePath) => ( new Promise((resolve, reject) => { fs.readlink(filePath, (error, link) => { if (error) { reject(error); } else { resolve({ 'info': file.replace(/\_/g, ' '), 'port': path.resolve(serialPath, link) }); } }); }) ); const readDir = (directory) => ( new Promise((resolve, reject) => { fs.readdir(directory, (error, files) => {
javascript
{ "resource": "" }
q4240
findById
train
function findById (id) { return new Promise(async (resolve, reject) => { try { if (!id || !id.length) { throw new Error('Undefined parameter id!'); }
javascript
{ "resource": "" }
q4241
sliceInit
train
function sliceInit(opt) { var defer = $.Deferred(); var file = opt.file; var that = this; var url = this.getCgiUrl(opt.path, opt.sign); var formData = new FormData(); var uploadparts = opt.uploadparts; formData.append('uploadparts', JSON.stringify(uploadparts)); formData.append('sha', opt.sha); formData.append('op', 'upload_slice_init'); formData.append('filesize', file.size); formData.append('slice_size', opt.sliceSize); formData.append('biz_attr', opt.biz_attr); formData.append('insertOnly', opt.insertOnly); $.ajax({ type: 'POST', dataType: "JSON", url: url, data: formData, success: function (res) { if (opt.globalTask.state === 'cancel') return; res = res || {}; if (res.code == 0) { if (res.data.access_url) {//如果秒传命中则直接返回 defer.resolve(res); return; } var session = res.data.session; var sliceSize = parseInt(res.data.slice_size); var offset = res.data.offset || 0; opt.session = session; opt.slice_size = sliceSize; opt.offset = offset; sliceUpload.call(that, opt).done(function (r) { defer.resolve(r); }).fail(function (r) {
javascript
{ "resource": "" }
q4242
AttributionControl
train
function AttributionControl(controlDiv) { // Set CSS for the control border. let controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#fff'; controlUI.style.opacity = '0.7'; controlUI.style.border = '2px solid #fff'; controlUI.style.cursor = 'pointer'; controlDiv.appendChild(controlUI); // Set CSS for the control interior. let
javascript
{ "resource": "" }
q4243
RequestError
train
function RequestError(message, url, error, statusCode, body) { this.name = 'RequestError'; this.stack = (new Error()).stack; /** @member {String} error message */ this.message = message; /** @member {String} request URL */ this.url = url; /** @member optional error cause */ this.error = error;
javascript
{ "resource": "" }
q4244
train
function(source, baseUrl, requestFormatter, responseFormatter) { const querier = pointToQuery(baseUrl, requestFormatter, responseFormatter)(source);
javascript
{ "resource": "" }
q4245
baseRequest
train
function baseRequest(uri, cb) { var url = `${BASE_URL}${uri}`; request(url, function (error, response, body) { debug(`Url: ${url} statusCode: ${response && response.statusCode}`);
javascript
{ "resource": "" }
q4246
getServerStatus
train
function getServerStatus(cb) { async.parallel({ live: (cb) => { request('http://live.albiononline.com/status.txt', (error, response, body) => { if(error) { return cb(error); } cb(null, JSON.parse(body.trim())); }); }, staging: (cb) => { request('http://staging.albiononline.com/status.txt', (error, response, body) => { if(error) { return cb(error); } cb(null, JSON.parse(body.trim())); }); }
javascript
{ "resource": "" }
q4247
getGuildTopKills
train
function getGuildTopKills(guildId, opts, cb) { opts = opts || {}; query = "?"; if(opts.limit) { query += `limit=${opts.limit}`; } if(opts.offset) { query += `offset=${opts.offset}`; } if(opts.range) { // week, lastWeek, month, lastMonth query +=
javascript
{ "resource": "" }
q4248
getPlayerTopKills
train
function getPlayerTopKills(playerId, opts, cb) { // https://gameinfo.albiononline.com/api/gameinfo/players/Nubya8P6QWGhI6hDLQHIQQ opts = opts || {}; query = "?"; if(opts.limit) { query += `limit=${opts.limit}`; } if(opts.offset) {
javascript
{ "resource": "" }
q4249
_enumKeys
train
function _enumKeys(it) { var result = _objectKeys(it); var getSymbols = _objectGops.f; if (getSymbols) { var symbols = getSymbols(it);
javascript
{ "resource": "" }
q4250
_flags
train
function _flags() { var that = _anObject(this); var result = ''; if (that.global) result += 'g'; if (that.ignoreCase)
javascript
{ "resource": "" }
q4251
determineTaskList
train
function determineTaskList(packages, server=false) { if ( packages === null ) { return server ? conf.live_server_packages : conf.packages; } else if (typeof packages === 'string'){ return packages.split(',')
javascript
{ "resource": "" }
q4252
isRegisteredTask
train
function isRegisteredTask(arg) { const flag = this.server ? conf.live_server_packages.includes(arg) : conf.packages.includes(arg); if (!flag) { console.log('WARNING: a package name (' + arg +') was
javascript
{ "resource": "" }
q4253
setMapLoc
train
function setMapLoc(lib, opts, map) { let oldZoom; let view; switch (lib) { case 'leaflet': map.panTo([opts.lat,opts.lon]); if (opts.zoom){map.setZoom(opts.zoom)} break; case 'googlemaps': map.setCenter({lat: opts.lat,lng:opts.lon}); if (opts.zoom) {map.setZoom(opts.zoom)} break; case 'openlayers': oldZoom = map.getView().getZoom();
javascript
{ "resource": "" }
q4254
wrap1
train
function wrap1(val, opts, key) { switch(getType(val, opts, key)) { case 'B': return {'B': val}; case 'BS': return {'BS': val}; case 'N': return {'N': val.toString()}; case 'NS': return {'NS': eachToString(val)}; case 'S': return {'S': val.toString()}; case 'SS': return {'SS': eachToString(val)}; case 'BOOL':
javascript
{ "resource": "" }
q4255
wrap
train
function wrap(obj, opts) { var result = {}; for (var key in obj) { if(obj.hasOwnProperty(key)) { var wrapped = wrap1(obj[key], opts, key);
javascript
{ "resource": "" }
q4256
unwrap1
train
function unwrap1(dynamoData) { var keys = Object.keys(dynamoData); if (keys.length !== 1) throw new Error('Unexpected DynamoDB AttributeValue');
javascript
{ "resource": "" }
q4257
unwrap
train
function unwrap(attrVal) { var result = {}; for (var key in attrVal) { if(attrVal.hasOwnProperty(key)) { var value = attrVal[key]; if
javascript
{ "resource": "" }
q4258
marshalList
train
function marshalList(item, marshal) { return
javascript
{ "resource": "" }
q4259
marshalMap
train
function marshalMap(item, marshal) { return transform(_.isPlainObject,
javascript
{ "resource": "" }
q4260
train
function(str, tagInner) { tagInner = tagInner .replace(/^ +| +$/g, '') // Not .trim() that removes \f. .replace(/(?: *\/ +| +\/ *)/g, '/') // Remove whitespaces
javascript
{ "resource": "" }
q4261
unmarshalList
train
function unmarshalList(item, unmarshal) { return
javascript
{ "resource": "" }
q4262
unmarshalMap
train
function unmarshalMap(item, unmarshal) { return transform(_.has('M'),
javascript
{ "resource": "" }
q4263
unmarshalPassThrough
train
function unmarshalPassThrough(item) { var key = _.find(function(type) { return _.has(type, item);
javascript
{ "resource": "" }
q4264
StylingAttributeDefinition
train
function StylingAttributeDefinition(ns, name, initialValue, appliesTo, isInherit, isAnimatable, parseFunc, computeFunc) { this.name = name; this.ns = ns; this.qname = ns + " " + name; this.inherit = isInherit; this.animatable =
javascript
{ "resource": "" }
q4265
parseWaypoint
train
function parseWaypoint(qualifiedWaypoint) { var parts; if (!parsedWaypoints[qualifiedWaypoint]) { parts = qualifiedWaypoint.split('.'); if (parts.length === 1) { parts.unshift('globals'); } parsedWaypoints[qualifiedWaypoint] =
javascript
{ "resource": "" }
q4266
setWaypoint
train
function setWaypoint(collection, waypoint) { angular.forEach(collection,
javascript
{ "resource": "" }
q4267
eagerSlice
train
function eagerSlice (list, start, end) { const sliced = []
javascript
{ "resource": "" }
q4268
train
function(elem, other_elems) { // Pairwise overlap detection var overlapping = function(a, b) { if (Math.abs(2.0*a.offsetLeft + a.offsetWidth - 2.0*b.offsetLeft - b.offsetWidth) < a.offsetWidth + b.offsetWidth) { if (Math.abs(2.0*a.offsetTop + a.offsetHeight - 2.0*b.offsetTop - b.offsetHeight) < a.offsetHeight + b.offsetHeight) { return true; } } return false; };
javascript
{ "resource": "" }
q4269
train
function(a, b) { if (Math.abs(2.0*a.offsetLeft + a.offsetWidth - 2.0*b.offsetLeft - b.offsetWidth) < a.offsetWidth + b.offsetWidth) { if (Math.abs(2.0*a.offsetTop +
javascript
{ "resource": "" }
q4270
istanbulCoberturaBadger
train
function istanbulCoberturaBadger(opts, callback) { // Resolve the options opts = extend({ // Setting the default coverage file generated by istanbul cobertura report. istanbulReportFile: "./coverage/cobertura-coverage.xml", // The default location for the destination being the coverage directory from istanbul. destinationDir: null, // The shields host to be used for retrieving the badge. https://github.com/badges/shields shieldsHost: process.env.SHIELDS_HOST || "https://img.shields.io", // The style of shield icon to generate (plastic, flat-square, flat) shieldStyle: "flat", // The name of the badge file to be generated badgeFileName: "coverage", // The thresholds to be used to give colors to the badge. thresholds: defaultThresholds }, opts); opts.badgeFormat = opts.badgeFormat || "svg"; reportParser(opts.istanbulReportFile, function(err, report) { if (err) { return callback(err); } // The color depends on the fixed thresholds (RED: 0 >= % < 60) (YELLOW: 60 >= % < 90)
javascript
{ "resource": "" }
q4271
processReport
train
function processReport(xml, computation) { if (xml.packages.package instanceof Array) { // Process all the packages xml.packages.package.forEach(function(packageObject) {
javascript
{ "resource": "" }
q4272
processPackage
train
function processPackage(packageObject, computation) { if (packageObject.classes.class instanceof Array) { // Process each individual class packageObject.classes.class.forEach(function(clazz) { processClass(clazz, computation); });
javascript
{ "resource": "" }
q4273
processClass
train
function processClass(clazz, computation) { if (!clazz.methods.method) { return; } if (clazz.methods.method instanceof Array) { clazz.methods.method.forEach(function(method) { ++computation.total; // Incremente the total number of methods if there were hits. Don't increment for no hit computation.passed = parseInt(method.hits) > 0 ? ++computation.passed : computation.passed; }); }
javascript
{ "resource": "" }
q4274
HarmonyClient
train
function HarmonyClient (xmppClient) { debug('create new harmony client') var self = this self._xmppClient = xmppClient self._responseHandlerQueue = [] self._availableCommandsCache = null function handleStanza (stanza) { debug('handleStanza(' + stanza.toString() + ')') // Check for state digest: var event = stanza.getChild('event') if (event && event.attr('type') === 'connect.stateDigest?notify') { onStateDigest.call(self, JSON.parse(event.getText())) } // Check for queued response handlers: self._responseHandlerQueue.forEach(function (responseHandler, index, array) { if (responseHandler.canHandleStanza(stanza)) { debug('received response stanza for queued response handler') var response = stanza.getChildText('oa') var decodedResponse if (responseHandler.responseType === 'json') {
javascript
{ "resource": "" }
q4275
startActivity
train
function startActivity (activityId) { var timestamp = new Date().getTime() var body = 'activityId=' + activityId + ':timestamp=' + timestamp return this.request('startactivity', body, 'encoded', function (stanza) { // This canHandleStanzaFn waits for a stanza that confirms starting the activity. var event = stanza.getChild('event') var canHandleStanza = false if (event && event.attr('type') === 'connect.stateDigest?notify') { var digest = JSON.parse(event.getText())
javascript
{ "resource": "" }
q4276
isOff
train
function isOff () { debug('check if turned off') return this.getCurrentActivity() .then(function (activityId) { var off = (activityId === '-1')
javascript
{ "resource": "" }
q4277
getAvailableCommands
train
function getAvailableCommands () { debug('retrieve available commands') if (this._availableCommandsCache) { debug('using cached config') var deferred = Q.defer() deferred.resolve(this._availableCommandsCache) return deferred.promise } var
javascript
{ "resource": "" }
q4278
buildCommandIqStanza
train
function buildCommandIqStanza (command, body) { debug('buildCommandIqStanza for command "' + command + '" with body ' + body) return xmppUtil.buildIqStanza( 'get' ,
javascript
{ "resource": "" }
q4279
request
train
function request (command, body, expectedResponseType, canHandleStanzaPredicate) { debug('request with command "' + command + '" with body ' + body) var deferred = Q.defer() var iq = buildCommandIqStanza(command, body) var id = iq.attr('id') expectedResponseType = expectedResponseType || 'encoded' canHandleStanzaPredicate = canHandleStanzaPredicate || defaultCanHandleStanzaPredicate.bind(null, id)
javascript
{ "resource": "" }
q4280
send
train
function send (command, body) { debug('send command "' + command + '" with body ' + body)
javascript
{ "resource": "" }
q4281
train
function (table) { var mt; if (table instanceof shine.Table) { if ((mt = table.__shine.metatable) && (mt = mt.__metatable)) return mt;
javascript
{ "resource": "" }
q4282
train
function (table, index) { // SLOOOOOOOW... var found = (index === undefined), numValues = table.__shine.numValues, keys, key, value, i, l; if (found || (typeof index == 'number' && index > 0 && index == index >> 0)) { if ('keys' in Object) { // Use Object.keys, if available. keys = Object['keys'](numValues); if (found) { // First pass i = 1; } else if (i = keys.indexOf('' + index) + 1) { found = true; } if (found) { while ((key = keys[i]) !== void 0 && (value = numValues[key]) === void 0) i++; if (value !== void 0) return [key >>= 0, value]; } } else { // Else use for-in (faster than for loop on tables with large holes) for (l in numValues) { i = l >> 0; if (!found) { if (i === index) found = true; } else if (numValues[i] !== undefined) { return [i, numValues[i]]; } } } } for (i in table) { if (table.hasOwnProperty(i) && !(i
javascript
{ "resource": "" }
q4283
train
function (table) { if (!((table || shine.EMPTY_OBJ) instanceof shine.Table))
javascript
{ "resource": "" }
q4284
train
function (table, metatable) { var mt; if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in setmetatable(). Table expected'); if (!(metatable === undefined || (metatable || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #2 in setmetatable(). Nil or table expected'); if ((mt
javascript
{ "resource": "" }
q4285
train
function (min, max) { if (min === undefined && max === undefined) return getRandom(); if (typeof min !== 'number') throw new shine.Error("bad argument #1 to 'random' (number expected)"); if (max === undefined) { max = min; min = 1; } else if (typeof max !== 'number') { throw new shine.Error("bad argument
javascript
{ "resource": "" }
q4286
train
function (table) { var time; if (!table) { time = Date['now']? Date['now']() : new Date().getTime(); } else { var day, month, year, hour, min, sec; if (!(day = table.getMember('day'))) throw new shine.Error("Field 'day' missing in date table"); if (!(month = table.getMember('month'))) throw new shine.Error("Field 'month' missing in date table"); if (!(year = table.getMember('year'))) throw new shine.Error("Field 'year' missing in date table"); hour = table.getMember('hour') || 12;
javascript
{ "resource": "" }
q4287
train
function (table, index, obj) { if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in table.insert(). Table expected'); if (obj == undefined) { obj = index; index = table.__shine.numValues.length;
javascript
{ "resource": "" }
q4288
train
function (table, index) { if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in table.remove(). Table expected'); var max = shine.lib.table.getn(table), vals = table.__shine.numValues, result; if (index
javascript
{ "resource": "" }
q4289
train
function (obj) { for (var i in obj) if (obj.hasOwnProperty(i)) delete obj[i];
javascript
{ "resource": "" }
q4290
train
function (val) { if (!val || !(val instanceof shine.Table) || val.__shine.refCount
javascript
{ "resource": "" }
q4291
train
function (val) { if (val === undefined || val === null) return; if (val instanceof Array) return this.cacheArray(val); if (typeof val == 'object' && val.constructor == Object) return this.cacheObject(val); if (!(val instanceof shine.Table) || val.__shine.refCount === undefined) return; var i, l, meta = val.__shine; for (i = 0, l = meta.keys.length; i < l; i++) this.decrRef(meta.keys[i]); for (i = 0, l = meta.values.length; i < l; i++) this.decrRef(meta.values[i]); for (i
javascript
{ "resource": "" }
q4292
formatValue
train
function formatValue (value) { if (typeof value == 'string') { value = value.replace(NEWLINE_PATTERN, '\\n');
javascript
{ "resource": "" }
q4293
train
function (val, errorMessage) { switch(true) { case typeof val == 'string': return val; case val === undefined: case val === null: return 'nil'; case val === Infinity: return 'inf'; case val === -Infinity: return '-inf'; case typeof val ==
javascript
{ "resource": "" }
q4294
train
function (table) { var isArr = shine.lib.table.getn (table) > 0, result = shine.gc['create' + (isArr? 'Array' : 'Object')](), numValues = table.__shine.numValues, i, l = numValues.length; for (i = 1; i < l; i++) { result[i - 1] = ((numValues[i]
javascript
{ "resource": "" }
q4295
train
function (url, success, error) { var xhr = new XMLHttpRequest(), parse; xhr.open('GET', url, true); // Use ArrayBuffer where possible. Luac files do not load properly with 'text'. if ('ArrayBuffer' in window) { xhr.responseType = 'arraybuffer'; parse = function (data) { // There is a limit on the number of arguments one can pass to a function. So far iPad is the lowest, and 10000 is safe. // If safe number of arguments to pass to fromCharCode: if (data.byteLength <= 10000) return String.fromCharCode.apply(String, Array.prototype.slice.call(new Uint8Array(data))); // otherwise break up bytearray: var i, l, arr = new Uint8Array(data), result = ''; for (i = 0, l = data.byteLength; i < l; i += 10000) { result += String.fromCharCode.apply(String,
javascript
{ "resource": "" }
q4296
defaults
train
function defaults(options) { options || (options = {}); options.apiKey || (options.apiKey = 'YOUR_API_KEY'); options.host || (options.host = 'cdn.segment.com'); if (!has.call(options, 'page'))
javascript
{ "resource": "" }
q4297
renderPage
train
function renderPage(page) { if (!page) return ''; var args = []; if (page.category) args.push(page.category); if (page.name) args.push(page.name); if (page.properties) args.push(page.properties); //
javascript
{ "resource": "" }
q4298
getValidInterval
train
function getValidInterval([min, max]) { let [validMin, validMax] = [min, max];
javascript
{ "resource": "" }
q4299
getFormatStep
train
function getFormatStep(roughStep, allowDecimals, correctionFactor) { if (roughStep.lte(0)) { return new Decimal(0); } const digitCount = Arithmetic.getDigitCount(roughStep.toNumber()); // The ratio between the rough step and the smallest number which has a bigger // order of magnitudes than the rough step const digitCountValue = new Decimal(10).pow(digitCount); const stepRatio = roughStep.div(digitCountValue); // When an integer and a float multiplied, the accuracy of result may be wrong const stepRatioScale = digitCount !== 1 ? 0.05
javascript
{ "resource": "" }