_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q22500
|
JSONPPolling
|
train
|
function JSONPPolling (socket) {
io.Transport['xhr-polling'].apply(this, arguments);
this.index = io.j.length;
var self = this;
io.j.push(function (msg) {
self._(msg);
});
}
|
javascript
|
{
"resource": ""
}
|
q22501
|
extractStateDefinitions
|
train
|
function extractStateDefinitions (contractName, sourcesList, contracts) {
if (!contracts) {
contracts = extractContractDefinitions(sourcesList)
}
var node = contracts.contractsByName[contractName]
if (node) {
var stateItems = []
var stateVar = []
var baseContracts = getLinearizedBaseContracts(node.id, contracts.contractsById)
baseContracts.reverse()
for (var k in baseContracts) {
var ctr = baseContracts[k]
for (var i in ctr.children) {
var item = ctr.children[i]
stateItems.push(item)
if (item.name === 'VariableDeclaration') {
stateVar.push(item)
}
}
}
return {
stateDefinitions: stateItems,
stateVariables: stateVar
}
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q22502
|
train
|
function (hexString) {
if (hexString.slice(0, 2) === '0x') {
hexString = hexString.slice(2)
}
var integers = []
for (var i = 0; i < hexString.length; i += 2) {
integers.push(parseInt(hexString.slice(i, i + 2), 16))
}
return integers
}
|
javascript
|
{
"resource": ""
}
|
|
q22503
|
getPreimage
|
train
|
function getPreimage (web3, key) {
return new Promise((resolve, reject) => {
web3.debug.preimage(key.indexOf('0x') === 0 ? key : '0x' + key, function (error, preimage) {
if (error) {
resolve(null)
} else {
resolve(preimage)
}
})
})
}
|
javascript
|
{
"resource": ""
}
|
q22504
|
decodeState
|
train
|
async function decodeState (stateVars, storageResolver) {
var ret = {}
for (var k in stateVars) {
var stateVar = stateVars[k]
try {
var decoded = await stateVar.type.decodeFromStorage(stateVar.storagelocation, storageResolver)
decoded.constant = stateVar.constant
if (decoded.constant) {
decoded.value = '<constant>'
}
ret[stateVar.name] = decoded
} catch (e) {
console.log(e)
ret[stateVar.name] = '<decoding failed - ' + e.message + '>'
}
}
return ret
}
|
javascript
|
{
"resource": ""
}
|
q22505
|
isDynamicArrayAccess
|
train
|
function isDynamicArrayAccess (node) {
return node && nodeType(node, exactMatch(nodeTypes.IDENTIFIER)) && (node.attributes.type.endsWith('[] storage ref') || node.attributes.type === 'bytes storage ref' || node.attributes.type === 'string storage ref')
}
|
javascript
|
{
"resource": ""
}
|
q22506
|
isConstantFunction
|
train
|
function isConstantFunction (node) {
return isFunctionDefinition(node) && (
node.attributes.constant === true ||
node.attributes.stateMutability === 'view' ||
node.attributes.stateMutability === 'pure'
)
}
|
javascript
|
{
"resource": ""
}
|
q22507
|
isPlusPlusUnaryOperation
|
train
|
function isPlusPlusUnaryOperation (node) {
return nodeType(node, exactMatch(nodeTypes.UNARYOPERATION)) && operator(node, exactMatch(util.escapeRegExp('++')))
}
|
javascript
|
{
"resource": ""
}
|
q22508
|
isFullyImplementedContract
|
train
|
function isFullyImplementedContract (node) {
return nodeType(node, exactMatch(nodeTypes.CONTRACTDEFINITION)) && node.attributes.fullyImplemented === true
}
|
javascript
|
{
"resource": ""
}
|
q22509
|
isLibrary
|
train
|
function isLibrary (node) {
return nodeType(node, exactMatch(nodeTypes.CONTRACTDEFINITION)) && node.attributes.isLibrary === true
}
|
javascript
|
{
"resource": ""
}
|
q22510
|
isLibraryCall
|
train
|
function isLibraryCall (node) {
return isMemberAccess(node, basicRegex.FUNCTIONTYPE, undefined, basicRegex.LIBRARYTYPE, undefined)
}
|
javascript
|
{
"resource": ""
}
|
q22511
|
isNowAccess
|
train
|
function isNowAccess (node) {
return nodeType(node, exactMatch(nodeTypes.IDENTIFIER)) &&
expressionType(node, exactMatch(basicTypes.UINT)) &&
name(node, exactMatch('now'))
}
|
javascript
|
{
"resource": ""
}
|
q22512
|
isBlockBlockHashAccess
|
train
|
function isBlockBlockHashAccess (node) {
return isSpecialVariableAccess(node, specialVariables.BLOCKHASH) || isBuiltinFunctionCall(node) && getLocalCallName(node) === 'blockhash'
}
|
javascript
|
{
"resource": ""
}
|
q22513
|
isThisLocalCall
|
train
|
function isThisLocalCall (node) {
return isMemberAccess(node, basicRegex.FUNCTIONTYPE, exactMatch('this'), basicRegex.CONTRACTTYPE, undefined)
}
|
javascript
|
{
"resource": ""
}
|
q22514
|
isSuperLocalCall
|
train
|
function isSuperLocalCall (node) {
return isMemberAccess(node, basicRegex.FUNCTIONTYPE, exactMatch('super'), basicRegex.CONTRACTTYPE, undefined)
}
|
javascript
|
{
"resource": ""
}
|
q22515
|
isLocalCall
|
train
|
function isLocalCall (node) {
return nodeType(node, exactMatch(nodeTypes.FUNCTIONCALL)) &&
minNrOfChildren(node, 1) &&
nodeType(node.children[0], exactMatch(nodeTypes.IDENTIFIER)) &&
expressionType(node.children[0], basicRegex.FUNCTIONTYPE) &&
!expressionType(node.children[0], basicRegex.EXTERNALFUNCTIONTYPE) &&
nrOfChildren(node.children[0], 0)
}
|
javascript
|
{
"resource": ""
}
|
q22516
|
isLLCall
|
train
|
function isLLCall (node) {
return isMemberAccess(node,
exactMatch(util.escapeRegExp(lowLevelCallTypes.CALL.type)),
undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALL.ident))
}
|
javascript
|
{
"resource": ""
}
|
q22517
|
isLLCallcode
|
train
|
function isLLCallcode (node) {
return isMemberAccess(node,
exactMatch(util.escapeRegExp(lowLevelCallTypes.CALLCODE.type)),
undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALLCODE.ident))
}
|
javascript
|
{
"resource": ""
}
|
q22518
|
isLLDelegatecall
|
train
|
function isLLDelegatecall (node) {
return isMemberAccess(node,
exactMatch(util.escapeRegExp(lowLevelCallTypes.DELEGATECALL.type)),
undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.DELEGATECALL.ident))
}
|
javascript
|
{
"resource": ""
}
|
q22519
|
buildFunctionSignature
|
train
|
function buildFunctionSignature (paramTypes, returnTypes, isPayable, additionalMods) {
return 'function (' + util.concatWithSeperator(paramTypes, ',') + ')' + ((isPayable) ? ' payable' : '') + ((additionalMods) ? ' ' + additionalMods : '') + ((returnTypes.length) ? ' returns (' + util.concatWithSeperator(returnTypes, ',') + ')' : '')
}
|
javascript
|
{
"resource": ""
}
|
q22520
|
findFirstSubNodeLTR
|
train
|
function findFirstSubNodeLTR (node, type) {
if (!node || !node.children) return null
for (let i = 0; i < node.children.length; ++i) {
var item = node.children[i]
if (nodeType(item, type)) return item
else {
var res = findFirstSubNodeLTR(item, type)
if (res) return res
}
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q22521
|
Ethdebugger
|
train
|
function Ethdebugger (opts) {
this.opts = opts || {}
if (!this.opts.compilationResult) this.opts.compilationResult = () => { return null }
this.web3 = opts.web3
this.event = new EventManager()
this.tx
this.traceManager = new TraceManager({web3: this.web3})
this.codeManager = new CodeManager(this.traceManager)
this.solidityProxy = new SolidityProxy(this.traceManager, this.codeManager)
this.storageResolver = null
this.callTree = new InternalCallTree(this.event, this.traceManager, this.solidityProxy, this.codeManager, { includeLocalVariables: true })
}
|
javascript
|
{
"resource": ""
}
|
q22522
|
visitContracts
|
train
|
function visitContracts (contracts, cb) {
for (var file in contracts) {
for (var name in contracts[file]) {
if (cb({ name: name, object: contracts[file][name], file: file })) return
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22523
|
train
|
function (raw) {
var code = []
for (var i = 0; i < raw.length; i++) {
var opcode = opcodes(raw[i], true)
if (opcode.name.slice(0, 4) === 'PUSH') {
var length = raw[i] - 0x5f
opcode.pushData = raw.slice(i + 1, i + length + 1)
// in case pushdata extends beyond code
if (i + 1 + length > raw.length) {
for (var j = opcode.pushData.length; j < length; j++) {
opcode.pushData.push(0)
}
}
i += length
}
code.push(opcode)
}
return code
}
|
javascript
|
{
"resource": ""
}
|
|
q22524
|
train
|
function (funABI, values, contractbyteCode) {
var encoded
var encodedHex
try {
encoded = helper.encodeParams(funABI, values)
encodedHex = encoded.toString('hex')
} catch (e) {
return { error: 'cannot encode arguments' }
}
if (contractbyteCode) {
return { data: '0x' + contractbyteCode + encodedHex.replace('0x', '') }
} else {
return { data: helper.encodeFunctionId(funABI) + encodedHex.replace('0x', '') }
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22525
|
train
|
function (contract, params, funAbi, linkLibraries, linkReferences, callback) {
this.encodeParams(params, funAbi, (error, encodedParam) => {
if (error) return callback(error)
var bytecodeToDeploy = contract.evm.bytecode.object
if (bytecodeToDeploy.indexOf('_') >= 0) {
if (linkLibraries && linkReferences) {
for (var libFile in linkLibraries) {
for (var lib in linkLibraries[libFile]) {
var address = linkLibraries[libFile][lib]
if (!ethJSUtil.isValidAddress(address)) return callback(address + ' is not a valid address. Please check the provided address is valid.')
bytecodeToDeploy = this.linkLibraryStandardFromlinkReferences(lib, address.replace('0x', ''), bytecodeToDeploy, linkReferences)
}
}
}
}
if (bytecodeToDeploy.indexOf('_') >= 0) {
return callback('Failed to link some libraries')
}
return callback(null, { dataHex: bytecodeToDeploy + encodedParam.dataHex, funAbi, funArgs: encodedParam.funArgs, contractBytecode: contract.evm.bytecode.object })
})
}
|
javascript
|
{
"resource": ""
}
|
|
q22526
|
train
|
function (contractName, contract, contracts, params, funAbi, callback, callbackStep, callbackDeployLibrary) {
this.encodeParams(params, funAbi, (error, encodedParam) => {
if (error) return callback(error)
var dataHex = ''
var contractBytecode = contract.evm.bytecode.object
var bytecodeToDeploy = contract.evm.bytecode.object
if (bytecodeToDeploy.indexOf('_') >= 0) {
this.linkBytecode(contract, contracts, (err, bytecode) => {
if (err) {
callback('Error deploying required libraries: ' + err)
} else {
bytecodeToDeploy = bytecode + dataHex
return callback(null, {dataHex: bytecodeToDeploy, funAbi, funArgs: encodedParam.funArgs, contractBytecode, contractName: contractName})
}
}, callbackStep, callbackDeployLibrary)
return
} else {
dataHex = bytecodeToDeploy + encodedParam.dataHex
}
callback(null, {dataHex: bytecodeToDeploy, funAbi, funArgs: encodedParam.funArgs, contractBytecode, contractName: contractName})
})
}
|
javascript
|
{
"resource": ""
}
|
|
q22527
|
train
|
function (vmTraceIndex, trace) {
var step = trace[vmTraceIndex]
if (this.isCreateInstruction(step)) {
return this.contractCreationToken(vmTraceIndex)
} else if (this.isCallInstruction(step)) {
var stack = step.stack // callcode, delegatecall, ...
return ui.normalizeHexAddress(stack[stack.length - 2])
}
return undefined
}
|
javascript
|
{
"resource": ""
}
|
|
q22528
|
typeClass
|
train
|
function typeClass (fullType) {
fullType = util.removeLocation(fullType)
if (fullType.lastIndexOf(']') === fullType.length - 1) {
return 'array'
}
if (fullType.indexOf('mapping') === 0) {
return 'mapping'
}
if (fullType.indexOf(' ') !== -1) {
fullType = fullType.split(' ')[0]
}
var char = fullType.indexOf('bytes') === 0 ? 'X' : ''
return fullType.replace(/[0-9]+/g, char)
}
|
javascript
|
{
"resource": ""
}
|
q22529
|
parseType
|
train
|
function parseType (type, stateDefinitions, contractName, location) {
var decodeInfos = {
'contract': address,
'address': address,
'array': array,
'bool': bool,
'bytes': dynamicByteArray,
'bytesX': fixedByteArray,
'enum': enumType,
'string': stringType,
'struct': struct,
'int': int,
'uint': uint,
'mapping': mapping
}
var currentType = typeClass(type)
if (currentType === null) {
console.log('unable to retrieve decode info of ' + type)
return null
}
if (decodeInfos[currentType]) {
return decodeInfos[currentType](type, stateDefinitions, contractName, location)
} else {
return null
}
}
|
javascript
|
{
"resource": ""
}
|
q22530
|
analyseCallGraph
|
train
|
function analyseCallGraph (callGraph, funcName, context, nodeCheck) {
return analyseCallGraphInternal(callGraph, funcName, context, (a, b) => a || b, nodeCheck, {})
}
|
javascript
|
{
"resource": ""
}
|
q22531
|
train
|
function (from, data, value, gasLimit, txRunner, callbacks, finalCallback) {
if (!callbacks.confirmationCb || !callbacks.gasEstimationForceSend || !callbacks.promptCb) {
return finalCallback('all the callbacks must have been defined')
}
var tx = { from: from, to: null, data: data, useCall: false, value: value, gasLimit: gasLimit }
txRunner.rawRun(tx, callbacks.confirmationCb, callbacks.gasEstimationForceSend, callbacks.promptCb, (error, txResult) => {
// see universaldapp.js line 660 => 700 to check possible values of txResult (error case)
finalCallback(error, txResult)
})
}
|
javascript
|
{
"resource": ""
}
|
|
q22532
|
train
|
function (txResult) {
var errorCode = {
OUT_OF_GAS: 'out of gas',
STACK_UNDERFLOW: 'stack underflow',
STACK_OVERFLOW: 'stack overflow',
INVALID_JUMP: 'invalid JUMP',
INVALID_OPCODE: 'invalid opcode',
REVERT: 'revert',
STATIC_STATE_CHANGE: 'static state change'
}
var ret = {
error: false,
message: ''
}
if (!txResult.result.vm.exceptionError) {
return ret
}
var exceptionError = txResult.result.vm.exceptionError.error || ''
var error = `VM error: ${exceptionError}.\n`
var msg
if (exceptionError === errorCode.INVALID_OPCODE) {
msg = `\t\n\tThe execution might have thrown.\n`
ret.error = true
} else if (exceptionError === errorCode.OUT_OF_GAS) {
msg = `\tThe transaction ran out of gas. Please increase the Gas Limit.\n`
ret.error = true
} else if (exceptionError === errorCode.REVERT) {
var returnData = txResult.result.vm.return
// It is the hash of Error(string)
if (returnData && (returnData.slice(0, 4).toString('hex') === '08c379a0')) {
var abiCoder = new ethers.utils.AbiCoder()
var reason = abiCoder.decode(['string'], returnData.slice(4))[0]
msg = `\tThe transaction has been reverted to the initial state.\nReason provided by the contract: "${reason}".`
} else {
msg = `\tThe transaction has been reverted to the initial state.\nNote: The called function should be payable if you send value and the value you send should be less than your current balance.`
}
ret.error = true
} else if (exceptionError === errorCode.STATIC_STATE_CHANGE) {
msg = `\tState changes is not allowed in Static Call context\n`
ret.error = true
}
ret.message = `${error}${exceptionError}${msg}\tDebug the transaction to get more information.`
return ret
}
|
javascript
|
{
"resource": ""
}
|
|
q22533
|
Element
|
train
|
function Element (tagName, props, children) {
if (!(this instanceof Element)) {
if (!_.isArray(children) && children != null) {
children = _.slice(arguments, 2).filter(_.truthy)
}
return new Element(tagName, props, children)
}
if (_.isArray(props)) {
children = props
props = {}
}
this.tagName = tagName
this.props = props || {}
this.children = children || []
this.key = props
? props.key
: void 666
var count = 0
_.each(this.children, function (child, i) {
if (child instanceof Element) {
count += child.count
} else {
children[i] = '' + child
}
count++
})
this.count = count
}
|
javascript
|
{
"resource": ""
}
|
q22534
|
Facade
|
train
|
function Facade (obj) {
obj = clone(obj);
if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date();
else obj.timestamp = newDate(obj.timestamp);
traverse(obj);
this.obj = obj;
}
|
javascript
|
{
"resource": ""
}
|
q22535
|
traverse
|
train
|
function traverse (input, strict) {
if (strict === undefined) strict = true;
if (is.object(input)) return object(input, strict);
if (is.array(input)) return array(input, strict);
return input;
}
|
javascript
|
{
"resource": ""
}
|
q22536
|
object
|
train
|
function object (obj, strict) {
each(obj, function (key, val) {
if (isodate.is(val, strict)) {
obj[key] = isodate.parse(val);
} else if (is.object(val) || is.array(val)) {
traverse(val, strict);
}
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q22537
|
array
|
train
|
function array (arr, strict) {
each(arr, function (val, x) {
if (is.object(val)) {
traverse(val, strict);
} else if (isodate.is(val, strict)) {
arr[x] = isodate.parse(val);
}
});
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q22538
|
isEmpty
|
train
|
function isEmpty (val) {
if (null == val) return true;
if ('number' == typeof val) return 0 === val;
if (undefined !== val.length) return 0 === val.length;
for (var key in val) if (has.call(val, key)) return false;
return true;
}
|
javascript
|
{
"resource": ""
}
|
q22539
|
object
|
train
|
function object(obj, fn) {
for (var key in obj) {
if (has.call(obj, key)) {
fn(key, obj[key]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22540
|
multiple
|
train
|
function multiple (fn) {
return function (obj, path, val, options) {
var normalize = options && isFunction(options.normalizer) ? options.normalizer : defaultNormalize;
path = normalize(path);
var key;
var finished = false;
while (!finished) loop();
function loop() {
for (key in obj) {
var normalizedKey = normalize(key);
if (0 === path.indexOf(normalizedKey)) {
var temp = path.substr(normalizedKey.length);
if (temp.charAt(0) === '.' || temp.length === 0) {
path = temp.substr(1);
var child = obj[key];
// we're at the end and there is nothing.
if (null == child) {
finished = true;
return;
}
// we're at the end and there is something.
if (!path.length) {
finished = true;
return;
}
// step into child
obj = child;
// but we're done here
return;
}
}
}
key = undefined;
// if we found no matching properties
// on the current object, there's no match.
finished = true;
}
if (!key) return;
if (null == obj) return obj;
// the `obj` and `key` is one above the leaf object and key, so
// start object: { a: { 'b.c': 10 } }
// end object: { 'b.c': 10 }
// end key: 'b.c'
// this way, you can do `obj[key]` and get `10`.
return fn(obj, key, val);
};
}
|
javascript
|
{
"resource": ""
}
|
q22541
|
replace
|
train
|
function replace (obj, key, val) {
if (obj.hasOwnProperty(key)) obj[key] = val;
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q22542
|
currency
|
train
|
function currency(val) {
if (!val) return;
if (typeof val === 'number') return val;
if (typeof val !== 'string') return;
val = val.replace(/\$/g, '');
val = parseFloat(val);
if (!isNaN(val)) return val;
}
|
javascript
|
{
"resource": ""
}
|
q22543
|
bindMethods
|
train
|
function bindMethods (obj, methods) {
methods = [].slice.call(arguments, 1);
for (var i = 0, method; method = methods[i]; i++) {
obj[method] = bind(obj, obj[method]);
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q22544
|
set
|
train
|
function set(name, value, options) {
options = options || {};
var str = encode(name) + '=' + encode(value);
if (null == value) options.maxage = -1;
if (options.maxage) {
options.expires = new Date(+new Date + options.maxage);
}
if (options.path) str += '; path=' + options.path;
if (options.domain) str += '; domain=' + options.domain;
if (options.expires) str += '; expires=' + options.expires.toUTCString();
if (options.secure) str += '; secure';
document.cookie = str;
}
|
javascript
|
{
"resource": ""
}
|
q22545
|
parse
|
train
|
function parse(str) {
var obj = {};
var pairs = str.split(/ *; */);
var pair;
if ('' == pairs[0]) return obj;
for (var i = 0; i < pairs.length; ++i) {
pair = pairs[i].split('=');
obj[decode(pair[0])] = decode(pair[1]);
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q22546
|
train
|
function (dest, src, recursive) {
for (var prop in src) {
if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) {
dest[prop] = defaults(dest[prop], src[prop], true);
} else if (! (prop in dest)) {
dest[prop] = src[prop];
}
}
return dest;
}
|
javascript
|
{
"resource": ""
}
|
|
q22547
|
all
|
train
|
function all() {
var str;
try {
str = document.cookie;
} catch (err) {
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(err.stack || err);
}
return {};
}
return parse(str);
}
|
javascript
|
{
"resource": ""
}
|
q22548
|
Group
|
train
|
function Group(options) {
this.defaults = Group.defaults;
this.debug = debug;
Entity.call(this, options);
}
|
javascript
|
{
"resource": ""
}
|
q22549
|
includes
|
train
|
function includes(searchElement, collection) {
var found = false;
// Delegate to String.prototype.indexOf when `collection` is a string
if (typeof collection === 'string') {
return strIndexOf.call(collection, searchElement) !== -1;
}
// Iterate through enumerable/own array elements and object properties.
each(function(value) {
if (sameValueZero(value, searchElement)) {
found = true;
// Exit iteration early when found
return false;
}
}, collection);
return found;
}
|
javascript
|
{
"resource": ""
}
|
q22550
|
isArrayLike
|
train
|
function isArrayLike(val) {
return val != null && (isArray(val) || (val !== 'function' && isNumber(val.length)));
}
|
javascript
|
{
"resource": ""
}
|
q22551
|
arrayEach
|
train
|
function arrayEach(iterator, array) {
for (var i = 0; i < array.length; i += 1) {
// Break iteration early if `iterator` returns `false`
if (iterator(array[i], i, array) === false) {
break;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22552
|
baseEach
|
train
|
function baseEach(iterator, object) {
var ks = keys(object);
for (var i = 0; i < ks.length; i += 1) {
// Break iteration early if `iterator` returns `false`
if (iterator(object[ks[i]], ks[i], object) === false) {
break;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22553
|
objectKeys
|
train
|
function objectKeys(target, pred) {
pred = pred || has;
var results = [];
for (var key in target) {
if (pred(target, key)) {
results.push(String(key));
}
}
return results;
}
|
javascript
|
{
"resource": ""
}
|
q22554
|
toFunction
|
train
|
function toFunction(obj) {
switch ({}.toString.call(obj)) {
case '[object Object]':
return objectToFunction(obj);
case '[object Function]':
return obj;
case '[object String]':
return stringToFunction(obj);
case '[object RegExp]':
return regexpToFunction(obj);
default:
return defaultToFunction(obj);
}
}
|
javascript
|
{
"resource": ""
}
|
q22555
|
objectToFunction
|
train
|
function objectToFunction(obj) {
var match = {};
for (var key in obj) {
match[key] = typeof obj[key] === 'string'
? defaultToFunction(obj[key])
: toFunction(obj[key]);
}
return function(val){
if (typeof val !== 'object') return false;
for (var key in match) {
if (!(key in val)) return false;
if (!match[key](val[key])) return false;
}
return true;
};
}
|
javascript
|
{
"resource": ""
}
|
q22556
|
get
|
train
|
function get(str) {
var props = expr(str);
if (!props.length) return '_.' + str;
var val, i, prop;
for (i = 0; i < props.length; i++) {
prop = props[i];
val = '_.' + prop;
val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")";
// mimic negative lookbehind to avoid problems with nested properties
str = stripNested(prop, str, val);
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q22557
|
map
|
train
|
function map(str, props, fn) {
var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;
return str.replace(re, function(_){
if ('(' == _[_.length - 1]) return fn(_);
if (!~props.indexOf(_)) return _;
return fn(_);
});
}
|
javascript
|
{
"resource": ""
}
|
q22558
|
unique
|
train
|
function unique(arr) {
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (~ret.indexOf(arr[i])) continue;
ret.push(arr[i]);
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q22559
|
pageDefaults
|
train
|
function pageDefaults() {
return {
path: canonicalPath(),
referrer: document.referrer,
search: location.search,
title: document.title,
url: canonicalUrl(location.search)
};
}
|
javascript
|
{
"resource": ""
}
|
q22560
|
canonicalPath
|
train
|
function canonicalPath() {
var canon = canonical();
if (!canon) return window.location.pathname;
var parsed = url.parse(canon);
return parsed.pathname;
}
|
javascript
|
{
"resource": ""
}
|
q22561
|
canonicalUrl
|
train
|
function canonicalUrl(search) {
var canon = canonical();
if (canon) return includes('?', canon) ? canon : canon + search;
var url = window.location.href;
var i = url.indexOf('#');
return i === -1 ? url : url.slice(0, i);
}
|
javascript
|
{
"resource": ""
}
|
q22562
|
pick
|
train
|
function pick(props, object) {
if (!existy(object) || !isObject(object)) {
return {};
}
if (isString(props)) {
props = [props];
}
if (!isArray(props)) {
props = [];
}
var result = {};
for (var i = 0; i < props.length; i += 1) {
if (isString(props[i]) && props[i] in object) {
result[props[i]] = object[props[i]];
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q22563
|
User
|
train
|
function User(options) {
this.defaults = User.defaults;
this.debug = debug;
Entity.call(this, options);
}
|
javascript
|
{
"resource": ""
}
|
q22564
|
render
|
train
|
function render(template, locals){
return foldl(function(attrs, val, key) {
attrs[key] = val.replace(/\{\{\ *(\w+)\ *\}\}/g, function(_, $1){
return locals[$1];
});
return attrs;
}, {}, template.attrs);
}
|
javascript
|
{
"resource": ""
}
|
q22565
|
fmt
|
train
|
function fmt(str){
var args = [].slice.call(arguments, 1);
var j = 0;
return str.replace(/%([a-z])/gi, function(_, f){
return fmt[f]
? fmt[f](args[j++])
: _ + f;
});
}
|
javascript
|
{
"resource": ""
}
|
q22566
|
attach
|
train
|
function attach(el, fn){
el.attachEvent('onreadystatechange', function(e){
if (!/complete|loaded/.test(el.readyState)) return;
fn(null, e);
});
el.attachEvent('onerror', function(e){
var err = new Error('failed to load the script "' + el.src + '"');
err.event = e || window.event;
fn(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q22567
|
uncamelize
|
train
|
function uncamelize (string) {
return string.replace(camelSplitter, function (m, previous, uppers) {
return previous + ' ' + uppers.toLowerCase().split('').join(' ');
});
}
|
javascript
|
{
"resource": ""
}
|
q22568
|
objectify
|
train
|
function objectify(str) {
// replace `src` with `data-src` to prevent image loading
str = str.replace(' src="', ' data-src="');
var el = domify(str);
var attrs = {};
each(el.attributes, function(attr){
// then replace it back
var name = attr.name === 'data-src' ? 'src' : attr.name;
if (!includes(attr.name + '=', str)) return;
attrs[name] = attr.value;
});
return {
type: el.tagName.toLowerCase(),
attrs: attrs
};
}
|
javascript
|
{
"resource": ""
}
|
q22569
|
toSpaceCase
|
train
|
function toSpaceCase (string) {
return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) {
return match ? ' ' + match : '';
});
}
|
javascript
|
{
"resource": ""
}
|
q22570
|
toIsoString
|
train
|
function toIsoString (date) {
return date.getUTCFullYear()
+ '-' + pad(date.getUTCMonth() + 1)
+ '-' + pad(date.getUTCDate())
+ 'T' + pad(date.getUTCHours())
+ ':' + pad(date.getUTCMinutes())
+ ':' + pad(date.getUTCSeconds())
+ '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5)
+ 'Z';
}
|
javascript
|
{
"resource": ""
}
|
q22571
|
alias
|
train
|
function alias (obj, method) {
switch (type(method)) {
case 'object': return aliasByDictionary(clone(obj), method);
case 'function': return aliasByFunction(clone(obj), method);
}
}
|
javascript
|
{
"resource": ""
}
|
q22572
|
aliasByDictionary
|
train
|
function aliasByDictionary (obj, aliases) {
for (var key in aliases) {
if (undefined === obj[key]) continue;
obj[aliases[key]] = obj[key];
delete obj[key];
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q22573
|
aliasByFunction
|
train
|
function aliasByFunction (obj, convert) {
// have to create another object so that ie8 won't infinite loop on keys
var output = {};
for (var key in obj) output[convert(key)] = obj[key];
return output;
}
|
javascript
|
{
"resource": ""
}
|
q22574
|
convertDates
|
train
|
function convertDates (obj, convert) {
obj = clone(obj);
for (var key in obj) {
var val = obj[key];
if (is.date(val)) obj[key] = convert(val);
if (is.object(val)) obj[key] = convertDates(val, convert);
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q22575
|
handler
|
train
|
function handler () {
for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q22576
|
onError
|
train
|
function onError (fn) {
callbacks.push(fn);
if (window.onerror != handler) {
callbacks.push(window.onerror);
window.onerror = handler;
}
}
|
javascript
|
{
"resource": ""
}
|
q22577
|
ecommerce
|
train
|
function ecommerce(event, track, arr) {
push.apply(null, [
'_fxm.ecommerce.' + event,
track.id() || track.sku(),
track.name(),
track.category()
].concat(arr || []));
}
|
javascript
|
{
"resource": ""
}
|
q22578
|
clean
|
train
|
function clean(obj) {
var ret = {};
// Remove traits/properties that are already represented
// outside of the data container
// TODO: Refactor into `omit` call
var excludeKeys = ['id', 'name', 'firstName', 'lastName'];
each(excludeKeys, function(omitKey) {
clear(obj, omitKey);
});
// Flatten nested hierarchy, preserving arrays
obj = flatten(obj);
// Discard nulls, represent arrays as comma-separated strings
// FIXME: This also discards `undefined`s. Is that OK?
for (var key in obj) {
if (has.call(obj, key)) {
var val = obj[key];
if (val == null) {
continue;
}
if (is.array(val)) {
ret[key] = val.toString();
continue;
}
ret[key] = val;
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q22579
|
flatten
|
train
|
function flatten(source) {
var output = {};
function step(object, prev) {
for (var key in object) {
if (has.call(object, key)) {
var value = object[key];
var newKey = prev ? prev + ' ' + key : key;
if (!is.array(value) && is.object(value)) {
return step(value, newKey);
}
output[newKey] = value;
}
}
}
step(source);
return output;
}
|
javascript
|
{
"resource": ""
}
|
q22580
|
convert
|
train
|
function convert(key, value) {
key = camel(key);
if (is.string(value)) return key + '_str';
if (isInt(value)) return key + '_int';
if (isFloat(value)) return key + '_real';
if (is.date(value)) return key + '_date';
if (is.boolean(value)) return key + '_bool';
}
|
javascript
|
{
"resource": ""
}
|
q22581
|
toCamelCase
|
train
|
function toCamelCase (string) {
return toSpace(string).replace(/\s(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
|
javascript
|
{
"resource": ""
}
|
q22582
|
path
|
train
|
function path(properties, options) {
if (!properties) return;
var str = properties.path;
if (options.includeSearch && properties.search) str += properties.search;
return str;
}
|
javascript
|
{
"resource": ""
}
|
q22583
|
metrics
|
train
|
function metrics(obj, data) {
var dimensions = data.dimensions;
var metrics = data.metrics;
var names = keys(metrics).concat(keys(dimensions));
var ret = {};
for (var i = 0; i < names.length; ++i) {
var name = names[i];
var key = metrics[name] || dimensions[name];
var value = dot(obj, name) || obj[name];
if (value == null) continue;
ret[key] = value;
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q22584
|
enhancedEcommerceTrackProduct
|
train
|
function enhancedEcommerceTrackProduct(track) {
var props = track.properties();
window.ga('ec:addProduct', {
id: track.id() || track.sku(),
name: track.name(),
category: track.category(),
quantity: track.quantity(),
price: track.price(),
brand: props.brand,
variant: props.variant,
currency: track.currency()
});
}
|
javascript
|
{
"resource": ""
}
|
q22585
|
enhancedEcommerceProductAction
|
train
|
function enhancedEcommerceProductAction(track, action, data) {
enhancedEcommerceTrackProduct(track);
window.ga('ec:setAction', action, data || {});
}
|
javascript
|
{
"resource": ""
}
|
q22586
|
extractCheckoutOptions
|
train
|
function extractCheckoutOptions(props) {
var options = [
props.paymentMethod,
props.shippingMethod
];
// Remove all nulls, empty strings, zeroes, and join with commas.
var valid = select(options, function(e) {return e; });
return valid.length > 0 ? valid.join(', ') : null;
}
|
javascript
|
{
"resource": ""
}
|
q22587
|
createProductTrack
|
train
|
function createProductTrack(track, properties) {
properties.currency = properties.currency || track.currency();
return new Track({ properties: properties });
}
|
javascript
|
{
"resource": ""
}
|
q22588
|
push
|
train
|
function push() {
window._gs = window._gs || function() {
window._gs.q.push(arguments);
};
window._gs.q = window._gs.q || [];
window._gs.apply(null, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q22589
|
omit
|
train
|
function omit(keys, object){
var ret = {};
for (var item in object) {
ret[item] = object[item];
}
for (var i = 0; i < keys.length; i++) {
delete ret[keys[i]];
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q22590
|
pick
|
train
|
function pick(obj){
var keys = [].slice.call(arguments, 1);
var ret = {};
for (var i = 0, key; key = keys[i]; i++) {
if (key in obj) ret[key] = obj[key];
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q22591
|
prefix
|
train
|
function prefix(event, properties) {
var prefixed = {};
each(properties, function(key, val) {
if (key === 'Billing Amount') {
prefixed[key] = val;
} else {
prefixed[event + ' - ' + key] = val;
}
});
return prefixed;
}
|
javascript
|
{
"resource": ""
}
|
q22592
|
convert
|
train
|
function convert(traits) {
var arr = [];
each(traits, function(key, value) {
arr.push({ name: key, value: value });
});
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q22593
|
lowercase
|
train
|
function lowercase(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < arr.length; ++i) {
ret[i] = String(arr[i]).toLowerCase();
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q22594
|
ads
|
train
|
function ads(query){
var params = parse(query);
for (var key in params) {
for (var id in QUERYIDS) {
if (key === id) {
return {
id : params[key],
type : QUERYIDS[id]
};
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22595
|
store
|
train
|
function store(key, value){
var length = arguments.length;
if (0 == length) return all();
if (2 <= length) return set(key, value);
if (1 != length) return;
if (null == key) return storage.clear();
if ('string' == typeof key) return get(key);
if ('object' == typeof key) return each(key, set);
}
|
javascript
|
{
"resource": ""
}
|
q22596
|
set
|
train
|
function set(key, val){
return null == val
? storage.removeItem(key)
: storage.setItem(key, JSON.stringify(val));
}
|
javascript
|
{
"resource": ""
}
|
q22597
|
all
|
train
|
function all(){
var len = storage.length;
var ret = {};
var key;
while (0 <= --len) {
key = storage.key(len);
ret[key] = get(key);
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q22598
|
set
|
train
|
function set (protocol) {
try {
define(window.location, 'protocol', {
get: function () { return protocol; }
});
} catch (err) {
mockedProtocol = protocol;
}
}
|
javascript
|
{
"resource": ""
}
|
q22599
|
formatOptions
|
train
|
function formatOptions(options) {
return alias(options, {
forumId: 'forum_id',
accentColor: 'accent_color',
smartvote: 'smartvote_enabled',
triggerColor: 'trigger_color',
triggerBackgroundColor: 'trigger_background_color',
triggerPosition: 'trigger_position',
screenshotEnabled: 'screenshot_enabled',
customTicketFields: 'ticket_custom_fields'
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.