_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q8700
|
queryWorksheet
|
train
|
async function queryWorksheet(workSheetInfo, query, options) {
var key = util.createIdentifier(
workSheetInfo.worksheetId,
JSON.stringify(query)
);
options = options || {};
options.query = query;
return await fetchData(
key,
api.converter.queryResponse,
() => {
let payload = util._extend(
workSheetInfo,
api.converter.queryRequest(options)
);
return executeRequest('query_worksheet', payload);
});
}
|
javascript
|
{
"resource": ""
}
|
q8701
|
deleteEntries
|
train
|
async function deleteEntries(worksheetInfo, entityIds) {
entityIds.reverse();
// since google pushes up the removed row, the ID will change to the previous
// avoiding this iterate through the collection in reverse order
// TODO: needs performance improvement
var response;
for (let id of entityIds) {
let payload = util._extend({entityId: id}, worksheetInfo);
response = await executeRequest('delete_entry', payload);
}
cache.clear();
return response;
}
|
javascript
|
{
"resource": ""
}
|
q8702
|
queryFields
|
train
|
async function queryFields(workSheetInfo) {
var key = util.createIdentifier(
'queryFields',
workSheetInfo.worksheetId
);
return await fetchData(
key,
api.converter.queryFieldNames,
() => executeRequest('query_fields', workSheetInfo)
);
}
|
javascript
|
{
"resource": ""
}
|
q8703
|
createXMLWriter
|
train
|
function createXMLWriter(extended) {
extended = extended || false;
var xw = new XmlWriter().startElement('entry')
.writeAttribute('xmlns', 'http://www.w3.org/2005/Atom');
return extended ?
xw.writeAttribute(
'xmlns:gsx',
'http://schemas.google.com/spreadsheets/2006/extended'
) :
xw.writeAttribute(
'xmlns:gs',
'http://schemas.google.com/spreadsheets/2006'
);
}
|
javascript
|
{
"resource": ""
}
|
q8704
|
queryRequest
|
train
|
function queryRequest(queryOptions) {
if (!queryOptions) {
return;
}
var options = util._extend({}, queryOptions);
if (options.query && options.query.length) {
options.query = '&sq=' + encodeURIComponent(options.query);
}
if (options.sort) {
options.orderBy = '&orderby=column:' + options.sort;
delete options.sort;
}
if (options.descending) {
options.reverse = '&reverse=true';
delete options.descending;
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
q8705
|
worksheetData
|
train
|
function worksheetData(worksheet) {
return {
worksheetId: getItemIdFromUrl(g(worksheet.id)),
title: g(worksheet.title),
updated: g(worksheet.updated),
colCount: g(worksheet['gs$colCount']),
rowCount: g(worksheet['gs$rowCount'])
};
}
|
javascript
|
{
"resource": ""
}
|
q8706
|
worksheetEntry
|
train
|
function worksheetEntry(entry, fieldPrefix) {
fieldPrefix = fieldPrefix || 'gsx$';
var data = {
'_id': getItemIdFromUrl(g(entry.id)),
'_updated': g(entry.updated)
};
Object.keys(entry)
.filter(function(key) {
return ~key.indexOf(fieldPrefix) && g(entry[key], true);
})
.forEach(function(key) {
var normalizedKey = key.substr(fieldPrefix.length);
data[normalizedKey] = g(entry[key]);
});
return data;
}
|
javascript
|
{
"resource": ""
}
|
q8707
|
sheetInfoResponse
|
train
|
function sheetInfoResponse(rawData) {
var feed = rawData.feed;
return {
title: g(feed.title),
updated: g(feed.updated),
workSheets: feed.entry.map(worksheetData),
authors: feed.author.map(item => ({ name: g(item.name), email: g(item.email) }))
};
}
|
javascript
|
{
"resource": ""
}
|
q8708
|
workSheetInfoResponse
|
train
|
function workSheetInfoResponse(rawData) {
if (typeof rawData === 'string') {
rawData = JSON.parse(rawData);
}
return worksheetData(rawData.entry);
}
|
javascript
|
{
"resource": ""
}
|
q8709
|
queryResponse
|
train
|
function queryResponse(rawData) {
var entry = rawData.feed.entry || [];
return entry.map(function(item) {
return worksheetEntry(item);
});
}
|
javascript
|
{
"resource": ""
}
|
q8710
|
queryFieldNames
|
train
|
function queryFieldNames(rawData) {
var entry = rawData.feed.entry || [];
return entry.map(function(item) {
var field = worksheetEntry(item, 'gs$');
field.cell = field.cell.replace(/_/g, '');
return field;
});
}
|
javascript
|
{
"resource": ""
}
|
q8711
|
createWorksheetRequest
|
train
|
function createWorksheetRequest(options) {
options = options || {};
// TODO: needs to handle overflow cases and create ore dynamically
var rowCount = util.coerceNumber(options.rowCount || 5000);
var colCount = util.coerceNumber(options.colCount || 50);
options.rowCount = Math.max(rowCount, 10);
options.colCount = Math.max(colCount, 10);
var xw = createXMLWriter()
.startElement('title')
.text(options.title)
.endElement()
.startElement('gs:rowCount')
.text(options.rowCount)
.endElement()
.startElement('gs:colCount')
.text(options.colCount)
.endElement()
.endElement();
return xw.toString();
}
|
javascript
|
{
"resource": ""
}
|
q8712
|
createEntryRequest
|
train
|
function createEntryRequest(entry) {
var xw = createXMLWriter(true);
Object.keys(entry).forEach(function(key) {
xw = xw.startElement('gsx:' + key)
.text(util.coerceNumber(entry[key]).toString())
.endElement();
});
return xw.endElement().toString();
}
|
javascript
|
{
"resource": ""
}
|
q8713
|
updateEntryRequest
|
train
|
function updateEntryRequest(entry) {
var xw = createXMLWriter(true);
Object.keys(entry)
.filter(function(key) {
// filter out internal properties
return key.indexOf('_') !== 0;
})
.forEach(function(key) {
xw = xw.startElement('gsx:' + key)
.text(util.coerceNumber(entry[key]).toString())
.endElement();
});
return xw.endElement().toString();
}
|
javascript
|
{
"resource": ""
}
|
q8714
|
createFieldRequest
|
train
|
function createFieldRequest(columnName, position) {
if (util.isNaN(position) || position <= 0) {
throw new TypeError('Position should be a number which is higher than one!');
}
var xw = createXMLWriter();
xw = xw.startElement('gs:cell')
.writeAttribute('row', 1)
.writeAttribute('col', position)
.writeAttribute('inputValue', columnName)
.endElement();
return xw.endElement().toString();
}
|
javascript
|
{
"resource": ""
}
|
q8715
|
chunk
|
train
|
function chunk(iterable, size=1) {
let current = 0
if (_.isEmpty(iterable)) {
return iterable
}
let result = List()
while (current < iterable.size) {
result = result.push(iterable.slice(current, current + size))
current += size
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q8716
|
difference
|
train
|
function difference(iterable, values) {
const valueSet = Set(values)
return iterable.filterNot((x) => valueSet.has(x))
}
|
javascript
|
{
"resource": ""
}
|
q8717
|
fill
|
train
|
function fill(iterable, value, start=0, end=iterable.size) {
let num = end - start
return iterable.splice(start, num, ...Repeat(value, num))
}
|
javascript
|
{
"resource": ""
}
|
q8718
|
intersection
|
train
|
function intersection(...iterables) {
if (_.isEmpty(iterables)) return OrderedSet()
let result = OrderedSet(iterables[0])
for (let iterable of iterables.slice(1)) {
result = result.intersect(iterable)
}
return result.toSeq()
}
|
javascript
|
{
"resource": ""
}
|
q8719
|
sample
|
train
|
function sample(iterable) {
let index = lodash.random(0, iterable.size - 1)
return iterable.get(index)
}
|
javascript
|
{
"resource": ""
}
|
q8720
|
sampleSize
|
train
|
function sampleSize(iterable, n=1) {
let index = -1
let result = List(iterable)
const length = result.size
const lastIndex = length - 1
while (++index < n) {
const rand = lodash.random(index, lastIndex)
const value = result.get(rand)
result = result.set(rand, result.get(index))
result = result.set(index, value)
}
return result.slice(0, Math.min(length, n))
}
|
javascript
|
{
"resource": ""
}
|
q8721
|
at
|
train
|
function at(map, paths) {
return paths.map((path) => {
return map.getIn(splitPath(path))
})
}
|
javascript
|
{
"resource": ""
}
|
q8722
|
defaults
|
train
|
function defaults(map, ...sources) {
return map.mergeWith((prev, next) => {
return prev === undefined ? next : prev
}, ...sources)
}
|
javascript
|
{
"resource": ""
}
|
q8723
|
defaultsDeep
|
train
|
function defaultsDeep(map, ...sources) {
return map.mergeDeepWith((prev, next) => {
return prev === undefined ? next : prev
}, ...sources)
}
|
javascript
|
{
"resource": ""
}
|
q8724
|
pick
|
train
|
function pick(map, props) {
props = Set(props)
return _.pickBy(map, (key) => {
return props.has(key)
})
}
|
javascript
|
{
"resource": ""
}
|
q8725
|
coerceNumber
|
train
|
function coerceNumber(value) {
if (typeof value === 'number') {
return value;
}
let isfloat = /^\d*(\.|,)\d*$/;
if (isfloat.test(value)) {
value = value.replace(',', '.');
}
let numberValue = Number(value);
return numberValue == value || !value ? numberValue : value
}
|
javascript
|
{
"resource": ""
}
|
q8726
|
coerceDate
|
train
|
function coerceDate(value) {
if (value instanceof Date) {
return value;
}
let timestamp = Date.parse(value);
if (!isNaN(timestamp)) {
return new Date(timestamp);
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q8727
|
coerceValue
|
train
|
function coerceValue(value) {
let numValue = coerceNumber(value);
if (numValue === value) {
return coerceDate(value);
}
return numValue;
}
|
javascript
|
{
"resource": ""
}
|
q8728
|
getArrayFields
|
train
|
function getArrayFields(array) {
return (array || []).reduce((old, current) => {
arrayDiff(Object.keys(current), old)
.forEach(key => old.push(key));
return old;
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q8729
|
arrayDiff
|
train
|
function arrayDiff(arrayTarget, arrayCheck) {
if (!(arrayTarget instanceof Array) || !(arrayCheck instanceof Array)) {
throw new Error('Both objects have to be an array');
}
return arrayTarget.filter(item => !~arrayCheck.indexOf(item));
}
|
javascript
|
{
"resource": ""
}
|
q8730
|
copyMetaProperties
|
train
|
function copyMetaProperties(dest, source) {
if (!dest || !source) {
return dest;
}
let fields = ['_id', '_updated'];
for (let field of fields) {
dest[field] = source[field];
}
return dest;
}
|
javascript
|
{
"resource": ""
}
|
q8731
|
renderSASS
|
train
|
function renderSASS(input, output) {
var d = Q.defer();
sass.render({
file: input
}, function (e, out) {
if (e) return d.reject(e);
fs.writeFileSync(output, out.css);
d.resolve();
});
return d.promise;
}
|
javascript
|
{
"resource": ""
}
|
q8732
|
train
|
function() {
var book = this;
var styles = book.config.get('styles');
return _.reduce(styles, function(prev, filename, type) {
return prev.then(function() {
var extension = path.extname(filename).toLowerCase();
if (extension != '.sass' && extension != '.scss') return;
book.log.info.ln('compile sass file: ', filename);
// Temporary CSS file
var tmpfile = type+'-'+Date.now()+'.css';
// Replace config
book.config.set('styles.'+type, tmpfile);
return renderSASS(
book.resolve(filename),
path.resolve(book.options.output, tmpfile)
);
});
}, Q());
}
|
javascript
|
{
"resource": ""
}
|
|
q8733
|
_keyPathNormalize
|
train
|
function _keyPathNormalize(kp) {
return new String(kp).replace(/\[([^\[\]]+)\]/g, function(m, k) {
return '.' + k.replace(/^["']|["']$/g, '')
})
}
|
javascript
|
{
"resource": ""
}
|
q8734
|
_set
|
train
|
function _set(obj, keypath, value, hook) {
var parts = _keyPathNormalize(keypath).split('.')
var last = parts.pop()
var dest = obj
parts.forEach(function(key) {
// Still set to non-object, just throw that error
dest = dest[key]
})
if (hook) {
// hook proxy set value
hook(dest, last, value)
} else {
dest[last] = value
}
return obj
}
|
javascript
|
{
"resource": ""
}
|
q8735
|
_get
|
train
|
function _get(obj, keypath) {
var parts = _keyPathNormalize(keypath).split('.')
var dest = obj
parts.forEach(function(key) {
if (isNon(dest)) return !(dest = undf())
dest = dest[key]
})
return dest
}
|
javascript
|
{
"resource": ""
}
|
q8736
|
_join
|
train
|
function _join(pre, tail) {
var _hasBegin = !!pre
if(!_hasBegin) pre = ''
if (/^\[.*\]$/.exec(tail)) return pre + tail
else if (typeof(tail) == 'number') return pre + '[' + tail + ']'
else if (_hasBegin) return pre + '.' + tail
else return tail
}
|
javascript
|
{
"resource": ""
}
|
q8737
|
listToFragment
|
train
|
function listToFragment(list) {
var fragment = document.createDocumentFragment();
for (var i = 0, l = list.length; i < l; i++) {
// Use toFragment since this may be an array of text, a jQuery object of `<template>`s, etc.
fragment.appendChild(toFragment(list[i]));
if (l === list.length + 1) {
// adjust for NodeLists which are live, they shrink as we pull nodes out of the DOM
i--;
l--;
}
}
return fragment;
}
|
javascript
|
{
"resource": ""
}
|
q8738
|
train
|
function(string) {
if (!string) {
var fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode(''));
return fragment;
}
var templateElement;
templateElement = document.createElement('template');
templateElement.innerHTML = string;
return templateElement.content;
}
|
javascript
|
{
"resource": ""
}
|
|
q8739
|
createFile
|
train
|
function createFile() {
let fileContent = '';
/*
* Customize data by type
*/
switch (options.type) {
case 'js':
fileContent += `'use strict';` + '\n';
for (let collectionKey in _variableCollection) {
fileContent += `const ${collectionKey} = '${_variableCollection[collectionKey]}';` + '\n';
}
if (_.endsWith(options.file, 'js') === false) options.file += '.js';
break;
default:
/* json */
fileContent = JSON.stringify(_variableCollection);
if (_.endsWith(options.file, 'json') === false) options.file += '.json';
}
/*
* Write file
*/
return fs.writeFileSync(options.file, fileContent, 'utf8');
}
|
javascript
|
{
"resource": ""
}
|
q8740
|
propertyMatch
|
train
|
function propertyMatch(property) {
for (let count = 0; count < options.match.length; count++) {
if (property.indexOf(options.match[count]) > -1) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q8741
|
extractVariables
|
train
|
function extractVariables(value) {
let regex = [/var\((.*?)\)/g, /\$([a-zA-Z0-9_\-]*)/g ],
result = [],
matchResult;
regex.forEach(expression => {
while (matchResult = expression.exec(value)) {
result.push({ origin: matchResult[0], variable: matchResult[1] });
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8742
|
resolveReferences
|
train
|
function resolveReferences() {
for (let key in _variableCollection) {
let referenceVariables = extractVariables(_variableCollection[key]);
for (let current = 0; current < referenceVariables.length; current++) {
if (_.isEmpty(_variableCollection[_.camelCase(referenceVariables[current].variable)]) === false) {
_variableCollection[key] = _variableCollection[key].replace(referenceVariables[current].origin, _variableCollection[_.camelCase(referenceVariables[current].variable)]);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8743
|
escapeValue
|
train
|
function escapeValue(value) {
switch (options.type) {
case 'js':
return value.replace(/'/g, '\\\'');
case 'json':
return value.replace(/"/g, '\\"');
default:
return value;
}
}
|
javascript
|
{
"resource": ""
}
|
q8744
|
convertToTokens
|
train
|
function convertToTokens( contents, filterParams ) {
var tokens = marked.lexer( contents );
// Simple case: no filtering needs to happen
if ( ! filterParams ) {
// Return the array of tokens from this content
return tokens;
}
/**
* Filter method to check whether a token is valid, based on the provided
* object of filter parameters
*
* If the filter object defines a RegExp for a key, test the token's property
* against that RegExp; otherwise, do a strict equality check between the
* provided value and the token's value for a given key.
*
* @param {Object} token A token object
* @return {Boolean} Whether the provided token object is valid
*/
function isTokenValid( token ) {
/**
* Reducer function to check token validity: start the token out as valid,
* then reduce through the provided filter parameters, updating the validity
* of the token after checking each value.
*
* @param {Boolean} valid Reducer function memo value
* @param {String|RegExp} targetValue The expected value of the specified property
* on this token, or else a RegExp against which
* to test that property
* @param {String} key The key within the token to test
* @return {Boolean} Whether the token is still valid, after
* validating the provided key
*/
function checkTokenParam( valid, targetValue, key ) {
// Once invalid, always invalid: fast-fail in this case
if ( ! valid ) {
return false;
}
// Without a target value, filtering doesn't mean much: move along
if ( typeof targetValue === 'undefined' ) {
return true;
}
var tokenPropToTest = token[ key ];
if ( isRegExp( targetValue ) ) {
// Special-case if the target value is a RegExp
return targetValue.test( tokenPropToTest );
}
return tokenPropToTest === targetValue;
}
// Check each property on this token against the provided params
return reduce( filterParams, checkTokenParam, true );
}
// Return a filtered array of tokens from the provided content
return tokens.filter( isTokenValid );
}
|
javascript
|
{
"resource": ""
}
|
q8745
|
isTokenValid
|
train
|
function isTokenValid( token ) {
/**
* Reducer function to check token validity: start the token out as valid,
* then reduce through the provided filter parameters, updating the validity
* of the token after checking each value.
*
* @param {Boolean} valid Reducer function memo value
* @param {String|RegExp} targetValue The expected value of the specified property
* on this token, or else a RegExp against which
* to test that property
* @param {String} key The key within the token to test
* @return {Boolean} Whether the token is still valid, after
* validating the provided key
*/
function checkTokenParam( valid, targetValue, key ) {
// Once invalid, always invalid: fast-fail in this case
if ( ! valid ) {
return false;
}
// Without a target value, filtering doesn't mean much: move along
if ( typeof targetValue === 'undefined' ) {
return true;
}
var tokenPropToTest = token[ key ];
if ( isRegExp( targetValue ) ) {
// Special-case if the target value is a RegExp
return targetValue.test( tokenPropToTest );
}
return tokenPropToTest === targetValue;
}
// Check each property on this token against the provided params
return reduce( filterParams, checkTokenParam, true );
}
|
javascript
|
{
"resource": ""
}
|
q8746
|
tokenizeMarkdownFromFiles
|
train
|
function tokenizeMarkdownFromFiles( files, filterParams ) {
/**
* Read in the provided file and return its contents as markdown tokens
*
* @param {String} file A file path to read in
* @return {Array} An array of the individual markdown tokens found
* within the provided list of files
*/
function readAndTokenize( file ) {
// Read the file
var fileContents = grunt.file.read( file );
// Map file into an object defining the tokens for this file
return {
file: file,
tokens: convertToTokens( fileContents, filterParams )
};
}
// Expand the provided file globs into a list of files, and process each
// one into an object containing that file's markdown tokens
return grunt.file.expand( files ).map( readAndTokenize );
}
|
javascript
|
{
"resource": ""
}
|
q8747
|
readAndTokenize
|
train
|
function readAndTokenize( file ) {
// Read the file
var fileContents = grunt.file.read( file );
// Map file into an object defining the tokens for this file
return {
file: file,
tokens: convertToTokens( fileContents, filterParams )
};
}
|
javascript
|
{
"resource": ""
}
|
q8748
|
MuxFactory
|
train
|
function MuxFactory(options) {
function Class (receiveProps) {
Ctor.call(this, options, receiveProps)
}
Class.prototype = Object.create(Mux.prototype)
return Class
}
|
javascript
|
{
"resource": ""
}
|
q8749
|
_defPrivateProperty
|
train
|
function _defPrivateProperty(name, value) {
if (instanceOf(value, Function)) value = value.bind(model)
_privateProperties[name] = value
$util.def(model, name, {
enumerable: false,
value: value
})
}
|
javascript
|
{
"resource": ""
}
|
q8750
|
_emitChange
|
train
|
function _emitChange(propname/*, arg1, ..., argX*/) {
var args = arguments
var kp = $normalize($join(_rootPath(), propname))
args[0] = CHANGE_EVENT + ':' + kp
_emitter.emit(CHANGE_EVENT, kp)
emitter.emit.apply(emitter, args)
args = $util.copyArray(args)
args[0] = kp
args.unshift('*')
emitter.emit.apply(emitter, args)
}
|
javascript
|
{
"resource": ""
}
|
q8751
|
_prop2CptDepsMapping
|
train
|
function _prop2CptDepsMapping (propname, dep) {
// if ($indexOf(_computedKeys, dep))
// return $warn('Dependency should not computed property')
$util.patch(_cptDepsMapping, dep, [])
var dest = _cptDepsMapping[dep]
if ($indexOf(dest, propname)) return
dest.push(propname)
}
|
javascript
|
{
"resource": ""
}
|
q8752
|
_subInstance
|
train
|
function _subInstance (target, props, kp) {
var ins
var _mux = target.__mux__
if (_mux && _mux.__kp__ === kp && _mux.__root__ === __muxid__) {
// reuse
ins = target
// emitter proxy
ins._$emitter(emitter)
// a private emitter for communication between instances
ins._$_emitter(_emitter)
} else {
ins = new Mux({
props: props,
emitter: emitter,
_emitter: _emitter,
__kp__: kp
})
}
if (!ins.__root__) {
$util.def(ins, '__root__', {
enumerable: false,
value: __muxid__
})
}
return ins
}
|
javascript
|
{
"resource": ""
}
|
q8753
|
_walk
|
train
|
function _walk (name, value, mountedPath) {
var tov = $type(value) // type of value
// initial path prefix is root path
var kp = mountedPath ? mountedPath : $join(_rootPath(), name)
/**
* Array methods hook
*/
if (tov == ARRAY) {
$arrayHook(value, function (self, methodName, nativeMethod, args) {
var pv = $util.copyArray(self)
var result = nativeMethod.apply(self, args)
// set value directly after walk
_props[name] = _walk(name, self, kp)
if (methodName == 'splice') {
_emitChange(kp, self, pv, methodName, args)
} else {
_emitChange(kp, self, pv, methodName)
}
return result
})
}
// deep observe into each property value
switch(tov) {
case OBJECT:
// walk deep into object items
var props = {}
var obj = value
if (instanceOf(value, Mux)) obj = value.$props()
$util.objEach(obj, function (k, v) {
props[k] = _walk(k, v, $join(kp, k))
})
return _subInstance(value, props, kp)
case ARRAY:
// walk deep into array items
value.forEach(function (item, index) {
value[index] = _walk(index, item, $join(kp, index))
})
return value
default:
return value
}
}
|
javascript
|
{
"resource": ""
}
|
q8754
|
_$set
|
train
|
function _$set(kp, value, lazyEmit) {
if (_destroy) return _destroyNotice()
return _$sync(kp, value, lazyEmit)
// if (!diff) return
/**
* Base type change of object type will be trigger change event
* next and pre value are not keypath value but property value
*/
// if ( kp == diff.mounted && $util.diff(diff.next, diff.pre) ) {
// var propname = diff.mounted
// // emit change immediately
// _emitChange(propname, diff.next, diff.pre)
// }
}
|
javascript
|
{
"resource": ""
}
|
q8755
|
_$setMulti
|
train
|
function _$setMulti(keyMap) {
if (_destroy) return _destroyNotice()
if (!keyMap || $type(keyMap) != OBJECT) return
var changes = []
$util.objEach(keyMap, function (key, item) {
var cg = _$set(key, item, true)
if (cg) changes.push(cg)
})
changes.forEach(function (args) {
_emitChange.apply(null, args)
})
}
|
javascript
|
{
"resource": ""
}
|
q8756
|
_$add
|
train
|
function _$add(prop, value, lazyEmit) {
if (prop.match(/[\.\[\]]/)) {
throw new Error('Propname shoudn\'t contains "." or "[" or "]"')
}
if ($indexOf(_observableKeys, prop)) {
// If value is specified, reset value
return arguments.length > 1 ? true : false
}
_props[prop] = _walk(prop, $util.copyValue(value))
_observableKeys.push(prop)
$util.def(model, prop, {
enumerable: true,
get: function() {
return _props[prop]
},
set: function (v) {
_$set(prop, v)
}
})
// add peroperty will trigger change event
if (!lazyEmit) {
_emitChange(prop, value)
} else {
return {
kp: prop,
vl: value
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8757
|
_walkResetEmiter
|
train
|
function _walkResetEmiter (ins, em, _pem) {
if ($type(ins) == OBJECT) {
var items = ins
if (instanceOf(ins, Mux)) {
ins._$emitter(em, _pem)
items = ins.$props()
}
$util.objEach(items, function (k, v) {
_walkResetEmiter(v, em, _pem)
})
} else if ($type(ins) == ARRAY) {
ins.forEach(function (v) {
_walkResetEmiter(v, em, _pem)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q8758
|
train
|
function (apiBaseUrl, apiKey, projectId) {
this.config = {
apiBaseUrl: apiBaseUrl,
apiKey: apiKey,
projectId: projectId
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8759
|
connect
|
train
|
function connect(sheetId, options) {
options = options || {};
// TODO: needs better access token handling
let api = apiFactory.getApi(options.version);
let restClient = clientFactory({
token: options.token,
gApi: api,
gCache: cache
});
return new Spreadsheet(sheetId, restClient, options);
}
|
javascript
|
{
"resource": ""
}
|
q8760
|
train
|
function(node, callback) {
if (node.firstViewNode) node = node.firstViewNode;
this.animateNode('out', node, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q8761
|
polylinearScale
|
train
|
function polylinearScale (domain, range, clamp) {
const domains = domain || [0, 1]
const ranges = range || [0, 1]
clamp = clamp || false
if (domains.length !== ranges.length) {
throw new Error('polylinearScale requires domain and range to have an equivalent number of values')
}
/**
* The compiled scale to return
*
* @param {Number} value The number to scale
* @return {Number} The result
*/
return function (value) {
var rangeMin
var rangeMax
var domain
var range
var ratio
var result
var i = 0
/* eslint-disable no-sequences */
while (i < domains.length - 1) {
if (value >= domains[i] && value <= domains[i + 1]) {
domain = [domains[i], domains[i + 1]],
range = [ranges[i], ranges[i + 1]]
break
}
i++
}
// Value is outside given domain
if (domain === undefined) {
if (value < domains[0]) {
domain = [domains[0], domains[1]]
range = [ranges[0], ranges[1]]
} else {
domain = [domains[domains.length - 2], domains[domains.length - 1]]
range = [ranges[ranges.length - 2], ranges[ranges.length - 1]]
}
}
ratio = (range[1] - range[0]) / (domain[1] - domain[0])
result = range[0] + ratio * (value - domain[0])
if (clamp) {
rangeMin = Math.min(range[0], range[1])
rangeMax = Math.max(range[0], range[1])
result = Math.min(rangeMax, Math.max(rangeMin, result))
}
return result
}
}
|
javascript
|
{
"resource": ""
}
|
q8762
|
inherit
|
train
|
function inherit(inheritor, inherited) {
inheritor.prototype = Object.create(inherited.prototype);
inheritor.prototype.constructor = inheritor;
}
|
javascript
|
{
"resource": ""
}
|
q8763
|
rename
|
train
|
function rename(cls, name) {
try {
Object.defineProperty(cls, "name", { value: name });
}
catch (ex) {
// Trying to defineProperty on `name` fails on Safari with a TypeError.
if (!(ex instanceof TypeError)) {
throw ex;
}
}
cls.prototype.name = name;
}
|
javascript
|
{
"resource": ""
}
|
q8764
|
makeError
|
train
|
function makeError(jqXHR, textStatus, errorThrown, options) {
var Constructor = statusToError[textStatus];
// We did not find anything in the map, which would happen if the textStatus
// was "error". Determine whether an ``HttpError`` or an ``AjaxError`` must
// be thrown.
if (!Constructor) {
Constructor = statusToError[(jqXHR.status !== 0) ? "http" : "ajax"];
}
return new Constructor(jqXHR, textStatus, errorThrown, options);
}
|
javascript
|
{
"resource": ""
}
|
q8765
|
connectionCheck
|
train
|
function connectionCheck(error, diagnose) {
var servers = diagnose.knownServers;
// Nothing to check so we fail immediately.
if (!servers || servers.length === 0) {
throw new ServerDownError(error);
}
// We check all the servers that the user asked to check. If none respond,
// we blame the network. Otherwise, we blame the server.
return Promise.all(servers.map(function urlToAjax(url) {
// eslint-disable-next-line no-use-before-define
return ajax({ url: dedupURL(normalizeURL(url)), timeout: 1000 })
.reflect();
})).filter(function filterSuccessfulServers(result) {
return result.isFulfilled();
}).then(function checkAnyFullfilled(fulfilled) {
if (fulfilled.length === 0) {
throw new NetworkDownError(error);
}
throw new ServerDownError(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q8766
|
diagnoseIt
|
train
|
function diagnoseIt(error, diagnose) {
// The browser reports being offline, blame the problem on this.
if (("onLine" in navigator) && !navigator.onLine) {
throw new BrowserOfflineError(error);
}
var serverURL = diagnose.serverURL;
var check;
// If the user gave us a server URL to check whether the server is up at
// all, use it. If that failed, then we need to check the connection. If we
// do not have a server URL, then we need to check the connection right
// away.
if (serverURL) {
// eslint-disable-next-line no-use-before-define
check = ajax({ url: dedupURL(normalizeURL(serverURL)) })
.catch(function failed() {
return connectionCheck(error, diagnose);
});
}
else {
check = connectionCheck(error, diagnose);
}
return check.then(function success() {
// All of our checks passed... and we have no tries left, so just rethrow
// what we would have thrown in the first place.
throw error;
});
}
|
javascript
|
{
"resource": ""
}
|
q8767
|
isNetworkIssue
|
train
|
function isNetworkIssue(error) {
// We don't want to retry when a HTTP error occurred.
return !(error instanceof errors.HttpError) &&
!(error instanceof errors.ParserError) &&
!(error instanceof errors.AbortError);
}
|
javascript
|
{
"resource": ""
}
|
q8768
|
doit
|
train
|
function doit(originalArgs, originalSettings, jqOptions, bjOptions) {
var xhr;
var p = new Promise(function resolver(resolve, reject) {
xhr = bluetry.perform.call(this, originalSettings, jqOptions, bjOptions);
function succeded(data, textStatus, jqXHR) {
resolve(bjOptions.verboseResults ? [data, textStatus, jqXHR] : data);
}
function failed(jqXHR, textStatus, errorThrown) {
var error = makeError(
jqXHR, textStatus, errorThrown,
bjOptions.verboseExceptions ? originalArgs : null);
if (!isNetworkIssue(error)) {
// As mentioned earlier, errors that are not due to the network cause
// an immediate rejection: no diagnosis.
reject(error);
}
else {
// Move to perhaps diagnosing what could be the problem.
var diagnose = bjOptions.diagnose;
if (!diagnose || !diagnose.on) {
// The user did not request diagnosis: fail now.
reject(error);
}
else {
// Otherwise, we perform the requested diagnosis. We cannot just
// call ``reject`` with the return value of ``diagnoseIt``, as the
// rejection value would be a promise and not an error. (``resolve``
// assimilates promises, ``reject`` does not).
resolve(diagnoseIt(error, diagnose));
}
}
}
xhr.fail(failed).done(succeded);
});
return { xhr: xhr, promise: p };
}
|
javascript
|
{
"resource": ""
}
|
q8769
|
_ajax$
|
train
|
function _ajax$(url, settings, override) {
// We just need to split up the arguments and pass them to ``doit``.
var originalArgs = settings ? [url, settings] : [url];
var originalSettings = settings || url;
var extracted = bluetry.extractBluejaxOptions(originalArgs);
// We need a copy here so that we do not mess up what the user passes to us.
var bluejaxOptions = $.extend({}, override, extracted[0]);
var cleanedOptions = extracted[1];
return doit(originalArgs, originalSettings, cleanedOptions, bluejaxOptions);
}
|
javascript
|
{
"resource": ""
}
|
q8770
|
init
|
train
|
function init(config) {
// the given config is only applied if no config has been set already (stored as localConfig)
if (Object.keys(localConfig).length === 0) {
if (config.hasOwnProperty("logging") && (config.logging.constructor === {}.constructor)) {
// config has "logging" key with an {} object value
//console.log("LOGGER: Setting config");
localConfig = _merge({}, config.logging);
}
else {
// no valid config - use default
localConfig = { default: { console: {}}};
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8771
|
trueOrMatch
|
train
|
function trueOrMatch(needle, haystack) {
if (needle === true) {
return true;
}
if (_.isRegExp(needle) && needle.test(haystack)) {
return true;
}
if (_.isString(needle) && haystack.indexOf(needle) !== -1) {
return true;
}
if (needle instanceof Array) {
for (var i in needle) {
if (trueOrMatch(needle[i], haystack)) {
return true;
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q8772
|
splitIniLine
|
train
|
function splitIniLine(line) {
var separator = line.indexOf('=');
if (separator === -1) {
return [line];
}
return [
line.substr(0, separator),
line.substr(separator + 1)
];
}
|
javascript
|
{
"resource": ""
}
|
q8773
|
ini2json
|
train
|
function ini2json(iniData) {
var result = {};
var iniLines = iniData.toString().split('\n');
var context = null;
for (var i in iniLines) {
var fields = splitIniLine(iniLines[i]);
for (var j in fields) {
fields[j] = fields[j].trim();
}
if (fields[0].length) {
if (fields[0].indexOf('[')===0) {
context = fields[0].substring(1, fields[0].length - 1);
} else {
if (context) {
if (!result[context]) {
result[context] = {};
}
result[context][fields[0]] = fields[1];
} else {
result[fields[0]] = fields[1];
}
}
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8774
|
splitCsvLine
|
train
|
function splitCsvLine(line) {
if (!line.trim().length) {
return [];
}
var fields = [];
var inQuotes = false;
var separator = 0;
for (var i = 0; i < line.length; i++) {
switch(line[i]) {
case "\"":
if (i>0 && line[i-1] != "\\") {
inQuotes = !inQuotes;
}
break;
case ",":
if (!inQuotes) {
if (separator < i) {
var field = line.substring(separator, i).trim();
if (field.length) {
fields.push(field);
}
}
separator = i + 1;
}
break;
}
}
fields.push(line.substring(separator).trim());
return fields;
}
|
javascript
|
{
"resource": ""
}
|
q8775
|
csv2json
|
train
|
function csv2json(csvData) {
var result = {};
var csvLines = csvData.toString().split('\n');
for (var i in csvLines) {
var fields = splitCsvLine(csvLines[i]);
if (fields.length) {
var key = '';
for (var k = 0; k < fields.length - 1; k++) {
if (fields[k].length) {
key += '.' + fields[k];
}
}
result[key.substr(1)] = fields[fields.length - 1];
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8776
|
load
|
train
|
function load(options) {
if (cache[options.locales]) {
options.verbose && gutil.log('Skip loading cached translations from', options.locales);
return dictionaries = cache[options.locales];
}
try {
options.verbose && gutil.log('Loading translations from', options.locales);
var files = fs.readdirSync(options.locales);
var count = 0;
for (var i in files) {
var file = files[i];
switch (path.extname(file)) {
case '.json':
case '.js':
dictionaries[path.basename(file, path.extname(file))] = flat(require(path.join(process.cwd(), options.locales, file)));
options.verbose && gutil.log('Added translations from', file);
count++;
break;
case '.ini':
var iniData = fs.readFileSync(path.join(process.cwd(), options.locales, file));
dictionaries[path.basename(file, path.extname(file))] = flat(ini2json(iniData));
options.verbose && gutil.log('Added translations from', file);
count++;
break;
case '.csv':
var csvData = fs.readFileSync(path.join(process.cwd(), options.locales, file));
dictionaries[path.basename(file, path.extname(file))] = csv2json(csvData);
options.verbose && gutil.log('Added translations from', file);
count++;
break;
default:
options.verbose && gutil.log('Ignored file', file);
}
}
options.verbose && gutil.log('Loaded', count, 'translations from', options.locales);
if (options.cache) {
options.verbose && gutil.log('Cashing translations from', options.locales);
cache[options.locales] = dictionaries;
}
} catch (e) {
e.message = 'No translation dictionaries have been found!';
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q8777
|
isBinary
|
train
|
function isBinary(buffer) {
var chunk = buffer.toString('utf8', 0, Math.min(buffer.length, 24));
for (var i in chunk) {
var charCode = chunk.charCodeAt(i);
if (charCode == 65533 || charCode <= 8) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q8778
|
replace
|
train
|
function replace(file, options) {
var contents = file.contents;
var copied = 0;
var processed = translate(options, contents, copied, file.path);
var files = [];
for (var lang in processed) {
var params = {};
params.ext = path.extname(file.path).substr(1);
params.name = path.basename(file.path, path.extname(file.path));
params.path = file.path.substring(file.base.length, file.path.lastIndexOf(path.sep));
params.lang = lang;
var filePath = options.filename;
for (var param in params) {
filePath = filePath.replace('${' + param + '}', params[param]);
}
filePath = path.join(file.base,filePath);
var newFile = new gutil.File({
base: file.base,
cwd: file.cwd,
path: filePath,
contents: new Buffer(processed[lang], 'utf8')
});
files.push(newFile);
}
return files;
}
|
javascript
|
{
"resource": ""
}
|
q8779
|
findAndReplace
|
train
|
function findAndReplace(target, find, replaceWith, config) {
if (config === void 0) { config = { onlyPlainObjects: false }; }
if ((config.onlyPlainObjects === false && !isAnyObject(target)) ||
(config.onlyPlainObjects === true && !isPlainObject(target))) {
if (target === find)
return replaceWith;
return target;
}
return Object.keys(target)
.reduce(function (carry, key) {
var val = target[key];
carry[key] = findAndReplace(val, find, replaceWith, config);
return carry;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q8780
|
findAndReplaceIf
|
train
|
function findAndReplaceIf(target, checkFn) {
if (!isPlainObject(target))
return checkFn(target);
return Object.keys(target)
.reduce(function (carry, key) {
var val = target[key];
carry[key] = findAndReplaceIf(val, checkFn);
return carry;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q8781
|
train
|
function ( e ) {
// Default context is `this` element
var context = (selector ? matchElement( e.target, selector, true ) : this);
// Handle `mouseenter` and `mouseleave`
if ( event === "mouseenter" || event === "mouseleave" ) {
var relatedElement = (event === "mouseenter" ? e.fromElement : e.toElement);
if ( context && ( relatedElement !== context && !context.contains( relatedElement ) ) ) {
callback.call( context, e );
}
// Fire callback if context element
} else if ( context ) {
callback.call( context, e );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8782
|
binaryOperator
|
train
|
function binaryOperator(queryObject, actualField, key) {
return actualField + OPS[key] + stringify(queryObject, actualField);
}
|
javascript
|
{
"resource": ""
}
|
q8783
|
logicalOperator
|
train
|
function logicalOperator(queryObject, actualField, key) {
let textQuery = '(';
for (let i = 0; i < queryObject.length; i++) {
textQuery += (i > 0 ? OPS[key] : '') + stringify(queryObject[i], actualField);
}
return textQuery + ')';
}
|
javascript
|
{
"resource": ""
}
|
q8784
|
updateObject
|
train
|
function updateObject(entities, descriptor) {
if (!entities) {
return entities;
}
let result = Array.isArray(entities) ? entities : [entities];
if (!isUpdateDescriptor(descriptor)) {
return descriptor && typeof descriptor === 'object'
? [util.copyMetaProperties(descriptor, result[0])]
: result;
}
// get updater operations
let operations = Object.keys(descriptor)
.map(opType => ({name: opType, transformation: UPDATE_OPS[opType]}))
.filter(op => op.transformation);
for (let operator of operations) {
result = mutate(result, descriptor[operator.name], operator.transformation);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8785
|
mutate
|
train
|
function mutate(entities, operationDescription, transformation) {
if (!operationDescription) {
return object;
}
return entities.map(item => {
Object.keys(operationDescription)
.forEach(key => transformation(item, key, operationDescription[key]));
return item;
});
}
|
javascript
|
{
"resource": ""
}
|
q8786
|
isUpdateDescriptor
|
train
|
function isUpdateDescriptor(descriptor) {
if (typeof descriptor !== 'object' || !descriptor) {
return false;
}
return Object.keys(descriptor).some(op => op in UPDATE_OPS);
}
|
javascript
|
{
"resource": ""
}
|
q8787
|
train
|
function(doc) {
if (!doc) {
doc = document;
}
if (doc === document && this.pool.length) {
return this.pool.pop();
}
return View.makeInstanceOf(doc.importNode(this, true), this);
}
|
javascript
|
{
"resource": ""
}
|
|
q8788
|
computeWeight
|
train
|
function computeWeight(i) {
if(dead[i]) {
return Infinity
}
//TODO: Check that the line segment doesn't cross once simplified
var s = inv[i]
var t = outv[i]
if((s<0) || (t<0)) {
return Infinity
} else {
return errorWeight(positions[i], positions[s], positions[t])
}
}
|
javascript
|
{
"resource": ""
}
|
q8789
|
heapDown
|
train
|
function heapDown(i) {
var w = heapWeight(i)
while(true) {
var tw = w
var left = 2*i + 1
var right = 2*(i + 1)
var next = i
if(left < heapCount) {
var lw = heapWeight(left)
if(lw < tw) {
next = left
tw = lw
}
}
if(right < heapCount) {
var rw = heapWeight(right)
if(rw < tw) {
next = right
}
}
if(next === i) {
return i
}
heapSwap(i, next)
i = next
}
}
|
javascript
|
{
"resource": ""
}
|
q8790
|
heapUp
|
train
|
function heapUp(i) {
var w = heapWeight(i)
while(i > 0) {
var parent = heapParent(i)
if(parent >= 0) {
var pw = heapWeight(parent)
if(w < pw) {
heapSwap(i, parent)
i = parent
continue
}
}
return i
}
}
|
javascript
|
{
"resource": ""
}
|
q8791
|
heapUpdate
|
train
|
function heapUpdate(i, w) {
var a = heap[i]
if(weights[a] === w) {
return i
}
weights[a] = -Infinity
heapUp(i)
heapPop()
weights[a] = w
heapCount += 1
return heapUp(heapCount-1)
}
|
javascript
|
{
"resource": ""
}
|
q8792
|
getComputedCSS
|
train
|
function getComputedCSS(styleName) {
if (this.ownerDocument.defaultView && this.ownerDocument.defaultView.opener) {
return this.ownerDocument.defaultView.getComputedStyle(this)[styleName];
}
return window.getComputedStyle(this)[styleName];
}
|
javascript
|
{
"resource": ""
}
|
q8793
|
animateElement
|
train
|
function animateElement(css, options) {
var playback = { onfinish: null };
if (!Array.isArray(css) || css.length !== 2 || !options || !options.hasOwnProperty('duration')) {
Promise.resolve().then(function() {
if (playback.onfinish) {
playback.onfinish();
}
});
return playback;
}
var element = this;
var duration = options.duration || 0;
var delay = options.delay || 0;
var easing = options.easing;
var initialCss = css[0];
var finalCss = css[1];
var allCss = {};
Object.keys(initialCss).forEach(function(key) {
allCss[key] = true;
element.style[key] = initialCss[key];
});
// trigger reflow
element.offsetWidth;
var transitionOptions = ' ' + duration + 'ms';
if (easing) {
transitionOptions += ' ' + easing;
}
if (delay) {
transitionOptions += ' ' + delay + 'ms';
}
element.style.transition = Object.keys(finalCss).map(function(key) {
return key + transitionOptions;
}).join(', ');
Object.keys(finalCss).forEach(function(key) {
allCss[key] = true;
element.style[key] = finalCss[key];
});
setTimeout(function() {
Object.keys(allCss).forEach(function(key) {
element.style[key] = '';
});
if (playback.onfinish) {
playback.onfinish();
}
}, duration + delay);
return playback;
}
|
javascript
|
{
"resource": ""
}
|
q8794
|
capitalize
|
train
|
function capitalize(str) {
let result = str.trim();
return result.substring(0, 1).toUpperCase() + result.substring(1);
}
|
javascript
|
{
"resource": ""
}
|
q8795
|
getWithLength
|
train
|
function getWithLength(length) {
var arrays = pool[length];
var array;
var i;
// Create the first array for the specified length
if (!arrays) {
array = create(length);
}
// Find an unused array among the created arrays for the specified length
if (!array) {
for (i = arrays.length; i--;) {
if (!arrays[i].inUse) {
array = arrays[i];
break;
}
}
// If no array was found, create a new one
if (!array) {
array = create(length);
}
}
array.inUse = true;
return array;
}
|
javascript
|
{
"resource": ""
}
|
q8796
|
giveBack
|
train
|
function giveBack(array) {
// Don't return arrays that didn't originate from this pool
if (!array.hasOwnProperty('originalLength')) return;
// Reset all the elements
for (var i = array.length; i--;) {
array[i] = undefined;
}
// Reset the length
array.length = array.originalLength;
// Remove custom properties that the Matrix class might have added
delete array.rows;
delete array.cols;
// Let the pool know that it's no longer in use
array.inUse = false;
}
|
javascript
|
{
"resource": ""
}
|
q8797
|
create
|
train
|
function create(length) {
var array = new Array(length);
// Create a non-enumerable property as a flag to know if the array is in use
Object.defineProperties(array, {
inUse: {
enumerable: false,
writable: true,
value: false
},
originalLength: {
enumerable: false,
value: length
}
});
if (!pool[length]) pool[length] = [];
pool[length].push(array);
return array;
}
|
javascript
|
{
"resource": ""
}
|
q8798
|
Typpy
|
train
|
function Typpy(input, target) {
if (arguments.length === 2) {
return Typpy.is(input, target);
}
return Typpy.get(input, true);
}
|
javascript
|
{
"resource": ""
}
|
q8799
|
bind
|
train
|
function bind(scope, method) {
var args = slice.call(arguments, 2)
if (typeof method === 'string') {
method = scope[method]
}
if (!method) {
throw new Error('Proxy: method `' + method + '` does not exist')
}
return function() {
return method.apply(scope, concat.apply(args, arguments))
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.