_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q46000
|
mimeMatch
|
train
|
function mimeMatch (expected, actual) {
// invalid type
if (expected === false) {
return false
}
// split types
var actualParts = actual.split('/')
var expectedParts = expected.split('/')
// invalid format
if (actualParts.length !== 2 || expectedParts.length !== 2) {
return false
}
// validate type
if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) {
return false
}
// validate suffix wildcard
if (expectedParts[1].substr(0, 2) === '*+') {
return expectedParts[1].length <= actualParts[1].length + 1 &&
expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length)
}
// validate subtype
if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) {
return false
}
return true
}
|
javascript
|
{
"resource": ""
}
|
q46001
|
normalizeType
|
train
|
function normalizeType (value) {
// parse the type
var type = typer.parse(value)
// remove the parameters
type.parameters = undefined
// reformat it
return typer.format(type)
}
|
javascript
|
{
"resource": ""
}
|
q46002
|
isErrorMessage
|
train
|
function isErrorMessage(message) {
const level = message.fatal ? 2 : message.severity;
if (Array.isArray(level)) {
return level[0] > 1;
}
return level > 1;
}
|
javascript
|
{
"resource": ""
}
|
q46003
|
countFixableErrorMessage
|
train
|
function countFixableErrorMessage(count, message) {
return count + Number(isErrorMessage(message) && message.fix !== undefined);
}
|
javascript
|
{
"resource": ""
}
|
q46004
|
countFixableWarningMessage
|
train
|
function countFixableWarningMessage(count, message) {
return count + Number(message.severity === 1 && message.fix !== undefined);
}
|
javascript
|
{
"resource": ""
}
|
q46005
|
gulpEslint
|
train
|
function gulpEslint(options) {
options = migrateOptions(options) || {};
const linter = new CLIEngine(options);
return transform((file, enc, cb) => {
const filePath = relative(process.cwd(), file.path);
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new PluginError('gulp-eslint', 'gulp-eslint doesn\'t support vinyl files with Stream contents.'));
return;
}
if (linter.isPathIgnored(filePath)) {
// Note:
// Vinyl files can have an independently defined cwd, but ESLint works relative to `process.cwd()`.
// (https://github.com/gulpjs/gulp/blob/master/docs/recipes/specifying-a-cwd.md)
// Also, ESLint doesn't adjust file paths relative to an ancestory .eslintignore path.
// E.g., If ../.eslintignore has "foo/*.js", ESLint will ignore ./foo/*.js, instead of ../foo/*.js.
// Eslint rolls this into `CLIEngine.executeOnText`. So, gulp-eslint must account for this limitation.
if (linter.options.ignore && options.warnFileIgnored) {
// Warn that gulp.src is needlessly reading files that ESLint ignores
file.eslint = createIgnoreResult(file);
}
cb(null, file);
return;
}
let result;
try {
result = linter.executeOnText(file.contents.toString(), filePath).results[0];
} catch (e) {
cb(new PluginError('gulp-eslint', e));
return;
}
// Note: Fixes are applied as part of "executeOnText".
// Any applied fix messages have been removed from the result.
if (options.quiet) {
// ignore warnings
file.eslint = filterResult(result, options.quiet);
} else {
file.eslint = result;
}
// Update the fixed output; otherwise, fixable messages are simply ignored.
if (file.eslint.hasOwnProperty('output')) {
file.contents = Buffer.from(file.eslint.output);
file.eslint.fixed = true;
}
cb(null, file);
});
}
|
javascript
|
{
"resource": ""
}
|
q46006
|
train
|
function(focusWindow, fromPoint, toPoint, duration, callback){
this.currentDataTransferItem = null;
this.focusWindow = focusWindow;
// A series of events to simulate a drag operation
this._mouseOver(fromPoint);
this._mouseEnter(fromPoint);
this._mouseMove(fromPoint);
this._mouseDown(fromPoint);
this._dragStart(fromPoint);
this._drag(fromPoint);
this._dragEnter(fromPoint);
this._dragOver(fromPoint);
DragonDrop.startMove(fromPoint, toPoint, duration, function () {
// this happens later
DragonDrop._dragLeave(fromPoint);
DragonDrop._dragEnd(fromPoint);
DragonDrop._mouseOut(fromPoint);
DragonDrop._mouseLeave(fromPoint);
DragonDrop._drop(toPoint);
DragonDrop._dragEnd(toPoint);
DragonDrop._mouseOver(toPoint);
DragonDrop._mouseEnter(toPoint);
// these are the "user" moving the mouse away after the drop
DragonDrop._mouseMove(toPoint);
DragonDrop._mouseOut(toPoint);
DragonDrop._mouseLeave(toPoint);
callback();
DragonDrop.cleanup();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46007
|
train
|
function(point, eventName, options){
if (point){
var targetElement = elementFromPoint(point, this.focusWindow);
syn.trigger(targetElement, eventName, options);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46008
|
train
|
function(dataFlavor, value){
var tempdata = {};
tempdata.dataFlavor = dataFlavor;
tempdata.val = value;
this.data.push(tempdata);
}
|
javascript
|
{
"resource": ""
}
|
|
q46009
|
train
|
function(dataFlavor){
for (var i = 0; i < this.data.length; i++){
var tempdata = this.data[i];
if (tempdata.dataFlavor === dataFlavor){
return tempdata.val;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46010
|
train
|
function (el, type) {
while (el && el.nodeName.toLowerCase() !== type.toLowerCase()) {
el = el.parentNode;
}
return el;
}
|
javascript
|
{
"resource": ""
}
|
|
q46011
|
train
|
function (el, func) {
var res;
while (el && res !== false) {
res = func(el);
el = el.parentNode;
}
return el;
}
|
javascript
|
{
"resource": ""
}
|
|
q46012
|
train
|
function (elem) {
var attributeNode;
// IE8 Standards doesn't like this on some elements
if (elem.getAttributeNode) {
attributeNode = elem.getAttributeNode("tabIndex");
}
return this.focusable.test(elem.nodeName) ||
(attributeNode && attributeNode.specified) &&
syn.isVisible(elem);
}
|
javascript
|
{
"resource": ""
}
|
|
q46013
|
train
|
function (elem) {
var attributeNode = elem.getAttributeNode("tabIndex");
return attributeNode && attributeNode.specified && (parseInt(elem.getAttribute('tabIndex')) || 0);
}
|
javascript
|
{
"resource": ""
}
|
|
q46014
|
toQueryParams
|
train
|
function toQueryParams(object){
return Object.keys(object)
.filter(key => !!object[key])
.map(key => key + "=" + encodeURIComponent(object[key]))
.join("&")
}
|
javascript
|
{
"resource": ""
}
|
q46015
|
copy
|
train
|
function copy(cb) {
gulp.src(['adal-angular.d.ts']).pipe(gulp.dest('./dist/'));
console.log('adal-angular.d.ts Copied to Dist Directory');
gulp.src(['README.md']).pipe(gulp.dest('./dist/'));
console.log('README.md Copied to Dist Directory');
cb();
}
|
javascript
|
{
"resource": ""
}
|
q46016
|
replace_d
|
train
|
function replace_d(cb) {
gulp.src('./dist/adal.service.d.ts')
.pipe(replace('../adal-angular.d.ts', './adal-angular.d.ts'))
.pipe(gulp.dest('./dist/'));
console.log('adal.service.d.ts Path Updated');
cb();
}
|
javascript
|
{
"resource": ""
}
|
q46017
|
bump_version
|
train
|
function bump_version(cb) {
gulp.src('./package.json')
.pipe(bump({
type: 'patch'
}))
.pipe(gulp.dest('./'));
console.log('Version Bumped');
cb();
}
|
javascript
|
{
"resource": ""
}
|
q46018
|
git_commit
|
train
|
function git_commit(cb) {
var package = require('./package.json');
exec('git commit -m "Version ' + package.version + ' release."', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q46019
|
doOverride
|
train
|
function doOverride(uiSchema, params) {
Object.keys(params).forEach(field => {
let appendVal = params[field];
let fieldUiSchema = uiSchema[field];
if (!fieldUiSchema) {
uiSchema[field] = appendVal;
} else if (typeof appendVal === "object" && !Array.isArray(appendVal)) {
doOverride(fieldUiSchema, appendVal);
} else {
uiSchema[field] = appendVal;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46020
|
doAppend
|
train
|
function doAppend(uiSchema, params) {
Object.keys(params).forEach(field => {
let appendVal = params[field];
let fieldUiSchema = uiSchema[field];
if (!fieldUiSchema) {
uiSchema[field] = appendVal;
} else if (Array.isArray(fieldUiSchema)) {
toArray(appendVal)
.filter(v => !fieldUiSchema.includes(v))
.forEach(v => fieldUiSchema.push(v));
} else if (typeof appendVal === "object" && !Array.isArray(appendVal)) {
doAppend(fieldUiSchema, appendVal);
} else if (typeof fieldUiSchema === "string") {
if (!fieldUiSchema.includes(appendVal)) {
uiSchema[field] = fieldUiSchema + " " + appendVal;
}
} else {
uiSchema[field] = appendVal;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46021
|
asRegExp
|
train
|
function asRegExp(pattern) {
// if regex then return it
if (isRegExp(pattern)) {
return pattern;
}
// if string then test for valid regex then convert to regex and return
const match = pattern.match(REGEX);
if (match) {
return new RegExp(match[1], match[2]);
}
return new RegExp(pattern);
}
|
javascript
|
{
"resource": ""
}
|
q46022
|
styledJSON
|
train
|
function styledJSON (obj) {
let json = JSON.stringify(obj, null, 2)
if (cli.color.enabled) {
let cardinal = require('cardinal')
let theme = require('cardinal/themes/jq')
cli.log(cardinal.highlight(json, {json: true, theme: theme}))
} else {
cli.log(json)
}
}
|
javascript
|
{
"resource": ""
}
|
q46023
|
styledHeader
|
train
|
function styledHeader (header) {
cli.log(cli.color.dim('=== ') + cli.color.bold(header))
}
|
javascript
|
{
"resource": ""
}
|
q46024
|
styledObject
|
train
|
function styledObject (obj, keys) {
let keyLengths = Object.keys(obj).map(key => key.toString().length)
let maxKeyLength = Math.max.apply(Math, keyLengths) + 2
function pp (obj) {
if (typeof obj === 'string' || typeof obj === 'number') {
return obj
} else if (typeof obj === 'object') {
return Object.keys(obj).map(k => k + ': ' + util.inspect(obj[k])).join(', ')
} else {
return util.inspect(obj)
}
}
function logKeyValue (key, value) {
cli.log(`${key}:` + ' '.repeat(maxKeyLength - key.length - 1) + pp(value))
}
for (var key of (keys || Object.keys(obj).sort())) {
let value = obj[key]
if (Array.isArray(value)) {
if (value.length > 0) {
logKeyValue(key, value[0])
for (var e of value.slice(1)) {
cli.log(' '.repeat(maxKeyLength) + pp(e))
}
}
} else if (value !== null && value !== undefined) {
logKeyValue(key, value)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46025
|
preauth
|
train
|
function preauth (app, heroku, secondFactor) {
return heroku.request({
method: 'PUT',
path: `/apps/${app}/pre-authorizations`,
headers: { 'Heroku-Two-Factor-Code': secondFactor }
})
}
|
javascript
|
{
"resource": ""
}
|
q46026
|
promiseOrCallback
|
train
|
function promiseOrCallback (fn) {
return function () {
if (typeof arguments[arguments.length - 1] === 'function') {
let args = Array.prototype.slice.call(arguments)
let callback = args.pop()
fn.apply(null, args).then(function () {
let args = Array.prototype.slice.call(arguments)
args.unshift(null)
callback.apply(null, args)
}).catch(function (err) {
callback(err)
})
} else {
return fn.apply(null, arguments)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46027
|
groupTextsByFontFamilyProps
|
train
|
function groupTextsByFontFamilyProps(
textByPropsArray,
availableFontFaceDeclarations
) {
const snappedTexts = _.flatMapDeep(textByPropsArray, textAndProps => {
const family = textAndProps.props['font-family'];
if (family === undefined) {
return [];
}
// Find all the families in the traced font-family that we have @font-face declarations for:
const families = fontFamily
.parse(family)
.filter(family =>
availableFontFaceDeclarations.some(
fontFace =>
fontFace['font-family'].toLowerCase() === family.toLowerCase()
)
);
return families.map(family => {
const activeFontFaceDeclaration = fontSnapper(
availableFontFaceDeclarations,
{
...textAndProps.props,
'font-family': fontFamily.stringify([family])
}
);
if (!activeFontFaceDeclaration) {
return [];
}
const { relations, ...props } = activeFontFaceDeclaration;
const fontUrl = getPreferredFontUrl(relations);
return {
text: textAndProps.text,
props,
fontRelations: relations,
fontUrl
};
});
}).filter(textByProps => textByProps && textByProps.fontUrl);
const textsByFontUrl = _.groupBy(snappedTexts, 'fontUrl');
return _.map(textsByFontUrl, (textsPropsArray, fontUrl) => {
const texts = textsPropsArray.map(obj => obj.text);
const fontFamilies = new Set(
textsPropsArray.map(obj => obj.props['font-family'])
);
const pageText = _.uniq(texts.join(''))
.sort()
.join('');
let smallestOriginalSize;
let smallestOriginalFormat;
for (const relation of textsPropsArray[0].fontRelations) {
if (relation.to.isLoaded) {
const size = relation.to.rawSrc.length;
if (smallestOriginalSize === undefined || size < smallestOriginalSize) {
smallestOriginalSize = size;
smallestOriginalFormat = relation.to.type.toLowerCase();
}
}
}
return {
smallestOriginalSize,
smallestOriginalFormat,
texts,
pageText,
text: pageText,
props: { ...textsPropsArray[0].props },
fontUrl,
fontFamilies
};
});
}
|
javascript
|
{
"resource": ""
}
|
q46028
|
getSharedProperties
|
train
|
function getSharedProperties(configA, configB) {
const bKeys = Object.keys(configB);
return Object.keys(configA).filter(p => bKeys.includes(p));
}
|
javascript
|
{
"resource": ""
}
|
q46029
|
generateBundleName
|
train
|
function generateBundleName(name, modules, conditionValueOrVariationObject) {
// first check if the given modules already matches an existing bundle
let existingBundleName;
for (const bundleName of Object.keys(bundles)) {
const bundleModules = bundles[bundleName].modules;
if (
containsModules(modules, bundleModules) &&
containsModules(bundleModules, modules)
) {
existingBundleName = bundleName;
}
}
if (existingBundleName) {
return existingBundleName;
}
let shortName = name.split('/').pop();
const dotIndex = shortName.lastIndexOf('.');
if (dotIndex > 0) {
shortName = shortName.substr(0, dotIndex);
}
let bundleName = shortName.replace(/[ .]/g, '').toLowerCase();
if (conditionValueOrVariationObject) {
if (typeof conditionValueOrVariationObject === 'string') {
bundleName += `-${conditionValueOrVariationObject}`;
} else {
for (const condition of Object.keys(conditionValueOrVariationObject)) {
bundleName += `-${conditionValueOrVariationObject[condition]}`;
}
}
}
let i;
if (bundles[bundleName]) {
i = 1;
while (bundles[`${bundleName}-${i}`]) {
i += 1;
}
}
return bundleName + (i ? `-${i}` : '');
}
|
javascript
|
{
"resource": ""
}
|
q46030
|
intersectModules
|
train
|
function intersectModules(modulesA, modulesB) {
const intersection = [];
for (const module of modulesA) {
if (modulesB.includes(module)) {
intersection.push(module);
}
}
return intersection;
}
|
javascript
|
{
"resource": ""
}
|
q46031
|
subtractModules
|
train
|
function subtractModules(modulesA, modulesB) {
const subtracted = [];
for (const module of modulesA) {
if (!modulesB.includes(module)) {
subtracted.push(module);
}
}
return subtracted;
}
|
javascript
|
{
"resource": ""
}
|
q46032
|
downloadGoogleFonts
|
train
|
async function downloadGoogleFonts(
fontProps,
{ formats = ['woff2', 'woff'], fontDisplay = 'swap', text } = {}
) {
const sortedFormats = [];
for (const format of formatOrder) {
if (formats.includes(format)) {
sortedFormats.push(format);
}
}
const result = {};
const googleFontId = getGoogleIdForFontProps(fontProps);
let fontCssUrl = `https://fonts.googleapis.com/css?family=${googleFontId}`;
if (text) {
fontCssUrl += `&text=${encodeURIComponent(text)}`;
}
result.src = await Promise.all(
sortedFormats.map(async format => {
const assetGraph = new AssetGraph();
assetGraph.teepee.headers['User-Agent'] = formatAgents[format];
const [cssAsset] = await assetGraph.loadAssets(fontCssUrl);
await assetGraph.populate();
const [fontRelation] = assetGraph.findRelations({
from: cssAsset,
type: 'CssFontFaceSrc'
});
fontRelation.node.each(decl => {
if (decl.prop !== 'src') {
result[decl.prop] = decl.value;
}
});
return [fontRelation.to, fontRelation.format];
})
);
if (!('unicode-range' in result)) {
const font = result.src[0][0];
result['unicode-range'] = unicodeRange(
fontkit.create(font.rawSrc).characterSet
);
}
result['font-display'] = fontDisplay;
// Output font face declaration object as CSS
const declarationStrings = [];
for (const [property, value] of Object.entries(result)) {
if (property !== 'src') {
declarationStrings.push(` ${property}: ${value};`);
}
}
const sources = result.src.map(([font, format]) => {
return `url('${font.dataUrl}') format('${format}')`;
});
declarationStrings.push(` src: \n ${sources.join(',\n ')};`);
return ['@font-face {', ...declarationStrings, '}'].join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q46033
|
findCustomPropertyDefinitions
|
train
|
function findCustomPropertyDefinitions(cssAssets) {
const definitionsByProp = {};
const incomingReferencesByProp = {};
for (const cssAsset of cssAssets) {
cssAsset.eachRuleInParseTree(cssRule => {
if (
cssRule.parent.type === 'rule' &&
cssRule.type === 'decl' &&
/^--/.test(cssRule.prop)
) {
(definitionsByProp[cssRule.prop] =
definitionsByProp[cssRule.prop] || new Set()).add(cssRule);
for (const customPropertyName of extractReferencedCustomPropertyNames(
cssRule.value
)) {
(incomingReferencesByProp[cssRule.prop] =
incomingReferencesByProp[cssRule.prop] || new Set()).add(
customPropertyName
);
}
}
});
}
const expandedDefinitionsByProp = {};
for (const prop of Object.keys(definitionsByProp)) {
expandedDefinitionsByProp[prop] = new Set();
const seenProps = new Set();
const queue = [prop];
while (queue.length > 0) {
const referencedProp = queue.shift();
if (!seenProps.has(referencedProp)) {
seenProps.add(referencedProp);
if (definitionsByProp[referencedProp]) {
for (const cssRule of definitionsByProp[referencedProp]) {
expandedDefinitionsByProp[prop].add(cssRule);
}
}
const incomingReferences = incomingReferencesByProp[referencedProp];
if (incomingReferences) {
for (const incomingReference of incomingReferences) {
queue.push(incomingReference);
}
}
}
}
}
return expandedDefinitionsByProp;
}
|
javascript
|
{
"resource": ""
}
|
q46034
|
getMinimumIeVersionUsage
|
train
|
function getMinimumIeVersionUsage(asset, stack = []) {
if (asset.type === 'Html') {
return 1;
}
if (minimumIeVersionByAsset.has(asset)) {
return minimumIeVersionByAsset.get(asset);
}
stack.push(asset);
const minimumIeVersion = Math.min(
...asset.incomingRelations
.filter(incomingRelation => !stack.includes(incomingRelation.from))
.map(incomingRelation => {
let matchCondition;
if (incomingRelation.type === 'HtmlConditionalComment') {
matchCondition = incomingRelation.condition.match(
/^(gte?|lte?)\s+IE\s+(\d+)$/i
);
} else if (
incomingRelation.conditionalComments &&
incomingRelation.conditionalComments.length > 0
) {
matchCondition = incomingRelation.conditionalComments[0].nodeValue.match(
/^\[if\s+(gte?|lte?)\s+IE\s+(\d+)\s*\]\s*>\s*<\s*!\s*$/i
);
}
if (matchCondition) {
if (matchCondition[1].substr(0, 2) === 'lt') {
return 1;
} else {
return (
parseInt(matchCondition[2], 10) +
(matchCondition[1].toLowerCase() === 'gt' ? 1 : 0)
);
}
} else {
return getMinimumIeVersionUsage(incomingRelation.from, stack);
}
})
);
minimumIeVersionByAsset.set(asset, minimumIeVersion);
return minimumIeVersion;
}
|
javascript
|
{
"resource": ""
}
|
q46035
|
fieldsFromMongo
|
train
|
function fieldsFromMongo(projection = {}, includeIdDefault = false) {
const fields = _.reduce(projection, (memo, value, key) => {
if (key !== '_id' && value !== undefined && !value) {
throw new TypeError('projection includes exclusion, but we do not support that');
}
if (value || (key === '_id' && value === undefined && includeIdDefault)) {
memo.push(key);
}
return memo;
}, []);
return ProjectionFieldSet.fromDotted(fields);
}
|
javascript
|
{
"resource": ""
}
|
q46036
|
resolveFields
|
train
|
function resolveFields(desiredFields, allowedFields, overrideFields) {
if (desiredFields != null && !Array.isArray(desiredFields)) {
throw new TypeError('expected nullable array for desiredFields');
}
if (allowedFields != null && !_.isObject(allowedFields)) {
throw new TypeError('expected nullable plain object for allowedFields');
}
if (overrideFields !== undefined && !_.isObject(overrideFields)) {
throw new TypeError('expected optional plain object for overrideFields');
}
// If no desired fields are specified, we treat that as wanting the default set of fields.
const desiredFieldset = _.isEmpty(desiredFields) ? new ProjectionFieldSet([[]]) :
ProjectionFieldSet.fromDotted(desiredFields);
// If allowedFields isn't provided, we treat that as not having restrictions. However, if it's an
// empty array, we treat that as have no valid fields.
const allowedFieldset = allowedFields ? fieldsFromMongo(allowedFields) :
new ProjectionFieldSet([[]]);
// Don't trust fields passed in the querystring, so whitelist them against the
// fields defined in parameters. Add override fields from parameters.
const fields = desiredFieldset.intersect(allowedFieldset).union(fieldsFromMongo(overrideFields));
if (fields.isEmpty()) {
// This projection isn't representable as a mongo projection - nor should it be. We don't want
// to query mongo for zero fields.
return null;
}
// Generate the mongo projection.
const projection = fields.toMongo();
// Whether overrideFields explicitly removes _id.
const disableIdOverride = overrideFields && overrideFields._id !== undefined && !overrideFields._id;
// Explicitly exclude the _id field (which mongo includes by default) if we don't allow it, or
// if we've disabled it in the override.
if (!fields.contains(['_id']) || disableIdOverride) {
// If the override excludes _id, then enforce that here. All other fields will be included by
// default, so we don't need to specify them individually, as we only support whitelisting
// fields, and do not support field blacklists.
projection._id = 0;
}
return projection;
}
|
javascript
|
{
"resource": ""
}
|
q46037
|
_joiVector
|
train
|
function _joiVector(proto) {
let arr = Joi.array();
if (arr.includes) {
return arr.includes(proto);
}
return arr.items(proto);
}
|
javascript
|
{
"resource": ""
}
|
q46038
|
deepLoad
|
train
|
function deepLoad(module, callback, parentLocation, id) {
// If this module is already loading then don't proceed.
// This is a bug.
// If a module is requested but not loaded then the module isn't ready,
// but we callback as if it is. Oh well, 1k!
if (module.g) {
return callback(module.e, module);
}
var location = module.g = module.l;
var request = new XMLHttpRequest();
request.onload = function (deps, count) {
if (request.status == 200 || module.t) {
// Should really use an object and then Object.keys to avoid
// duplicate dependencies. But that costs bytes.
deps = [];
(module.t = module.t || request.response).replace(/(?:^|[^\w\$_.])require\s*\(\s*["']([^"']*)["']\s*\)/g, function (_, id) {
deps.push(id);
});
count = deps.length;
function loaded() {
// We call loaded straight away below in case there
// are no dependencies. Putting this check first
// and the decrement after saves us an `if` for that
// special case
if (!count--) {
callback(undefined, module);
}
}
deps.map(function (dep) {
deepLoad(
resolveModuleOrGetExports(module.l, dep),
loaded,
// If it doesn't begin with a ".", then we're searching
// node_modules, so pass in the info to make this
// possible
dep[0] != "." ? location + "/../" : undefined,
dep
);
});
loaded();
} else {
// parentLocation is only given if we're searching in node_modules
if (parentLocation) {
// Recurse up the tree trying to find the dependency
// (generating 404s on the way)
deepLoad(
module.n = resolveModuleOrGetExports(parentLocation += "../", id),
callback,
parentLocation,
id
);
} else {
module.e = request;
callback(request, module);
}
}
};
// If the module already has text because we're using a factory
// function, then there's no need to load the file!
if (module.t) {
request.onload();
} else {
request.open("GET", location, true);
request.send();
}
}
|
javascript
|
{
"resource": ""
}
|
q46039
|
resolveModuleOrGetExports
|
train
|
function resolveModuleOrGetExports(baseOrModule, relative, resolved) {
// This should really be after the relative check, but because we are
// `throw`ing, it messes up the optimizations. If we are being called
// as resolveModule then the string `base` won't have the `e` property,
// so we're fine.
if (baseOrModule.e) {
throw baseOrModule.e;
}
// If 2 arguments are given, then we are resolving modules...
if (relative) {
baseElement.href = baseOrModule;
// If the relative url doesn't begin with a "." or a "/", then it's
// in node_modules
relativeElement.href = (relative[0] != "." && relative[0] != "/") ? "./node_modules/" + relative : relative;
resolved = relativeElement.href.substr(-3).toLowerCase() == ".js" ?
relativeElement.href :
relativeElement.href + ".js";
baseElement.href = "";
return (MODULES[resolved] = MODULES[resolved] || {l: resolved});
}
// ...otherwise we are getting the exports
// Is this module a redirect to another one?
if (baseOrModule.n) {
return resolveModuleOrGetExports(baseOrModule.n);
}
if (!baseOrModule[tmp]) {
(baseOrModule.f || globalEval("(function(require,"+tmp+",module){" + baseOrModule.t + "\n})//# sourceURL=" + baseOrModule.l))(
function require (id) {
return resolveModuleOrGetExports(resolveModuleOrGetExports(baseOrModule.l, id));
}, // require
baseOrModule[tmp] = {}, // exports
baseOrModule // module
);
}
return baseOrModule[tmp];
}
|
javascript
|
{
"resource": ""
}
|
q46040
|
Generate
|
train
|
function Generate(options) {
if (!(this instanceof Generate)) {
return new Generate(options);
}
Assemble.call(this, options);
this.is('generate');
this.initGenerate(this.options);
if (!setArgs) {
setArgs = true;
this.base.option(utils.argv);
}
}
|
javascript
|
{
"resource": ""
}
|
q46041
|
verify_nylas_request
|
train
|
function verify_nylas_request(req) {
const digest = crypto
.createHmac('sha256', config.nylasClientSecret)
.update(req.rawBody)
.digest('hex');
return digest === req.get('x-nylas-signature');
}
|
javascript
|
{
"resource": ""
}
|
q46042
|
buildUmdDev
|
train
|
function buildUmdDev() {
return rollup.rollup({
entry: 'src/index.js',
plugins: [
babel(babelOptions)
]
}).then(function (bundle) {
bundle.generate({
format: 'umd',
banner: banner,
name: 'rc-datetime-picker'
}).then(({ code }) => {
return write('dist/rc-datetime-picker.js', code);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q46043
|
determineFreqCategories
|
train
|
function determineFreqCategories() {
if (mean - sd < 0) {
var lowrange = 0 + mean / 3;
} else {
var lowrange = mean - sd;
}
var midrange = [mean + sd, lowrange];
var highrange = mean + sd;
var i = 0;
for (; i < potentialexamples.length; i++) {
var word = potentialexamples[i][0];
if ('undefined' != typeof wordfreq[word.simplified]) {
pushFrequency(word);
}
}
function pushFrequency(word) {
if (wordfreq[word.simplified] < lowrange) {
lowfreq.push(word);
}
if (
wordfreq[word.simplified] >= midrange[1] &&
wordfreq[word.simplified] < midrange[0]
) {
midfreq.push(word);
}
if (wordfreq[word.simplified] >= highrange) {
highfreq.push(word);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46044
|
makeRequest
|
train
|
function makeRequest(url, handler) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = handler.type;
xhr.onload = function onLoad(e) {
if (this.status === 200 || this.status === 0) {
handler.fn(null, xhr);
return;
}
handler.fn(e, xhr);
};
xhr.onerror = function onError(e) {
handler.fn(e, xhr);
};
xhr.send();
}
|
javascript
|
{
"resource": ""
}
|
q46045
|
arraybufferHandler
|
train
|
function arraybufferHandler(callback) {
return {
type: 'arraybuffer',
fn: (error, xhrObject) => {
if (error) {
callback(error);
return;
}
callback(null, xhrObject.response);
},
};
}
|
javascript
|
{
"resource": ""
}
|
q46046
|
showGlInfo
|
train
|
function showGlInfo(gl) {
const vertexUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
const fragmentUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
const combinedUnits = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
console.log('vertex texture image units:', vertexUnits);
console.log('fragment texture image units:', fragmentUnits);
console.log('combined texture image units:', combinedUnits);
}
|
javascript
|
{
"resource": ""
}
|
q46047
|
compileShader
|
train
|
function compileShader(gl, src, type) {
const shader = gl.createShader(type);
gl.shaderSource(shader, src);
// Compile and check status
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
// Something went wrong during compilation; get the error
const lastError = gl.getShaderInfoLog(shader);
console.error(`Error compiling shader '${shader}': ${lastError}`);
gl.deleteShader(shader);
return null;
}
return shader;
}
|
javascript
|
{
"resource": ""
}
|
q46048
|
applyProgramDataMapping
|
train
|
function applyProgramDataMapping(
gl,
programName,
mappingName,
glConfig,
glResources
) {
const program = glResources.programs[programName];
const mapping = glConfig.mappings[mappingName];
mapping.forEach((bufferMapping) => {
const glBuffer = glResources.buffers[bufferMapping.id];
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
program[bufferMapping.name] = gl.getAttribLocation(
program,
bufferMapping.attribute
);
gl.enableVertexAttribArray(program[bufferMapping.name]);
gl.vertexAttribPointer(
program[bufferMapping.name],
...bufferMapping.format
);
// FIXME: Remove this check when Apple fixes this bug
/* global navigator */
// const buggyBrowserVersion = ['AppleWebKit/602.1.50', 'AppleWebKit/602.2.14'];
if (navigator.userAgent.indexOf('AppleWebKit/602') === -1) {
gl.bindBuffer(gl.ARRAY_BUFFER, null);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46049
|
bindTextureToFramebuffer
|
train
|
function bindTextureToFramebuffer(gl, fbo, texture) {
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
fbo.width,
fbo.height,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
null
);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
texture,
0
);
// Check fbo status
const fbs = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
if (fbs !== gl.FRAMEBUFFER_COMPLETE) {
console.log('ERROR: There is a problem with the framebuffer:', fbs);
}
// Clear the bindings we created in this function.
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
|
javascript
|
{
"resource": ""
}
|
q46050
|
freeGLResources
|
train
|
function freeGLResources(glResources) {
const gl = glResources.gl;
// Delete each program
Object.keys(glResources.programs).forEach((programName) => {
const program = glResources.programs[programName];
const shaders = program.shaders;
let count = shaders.length;
// Delete shaders
while (count) {
count -= 1;
gl.deleteShader(shaders[count]);
}
// Delete program
gl.deleteProgram(program);
});
// Delete framebuffers
Object.keys(glResources.framebuffers).forEach((fbName) => {
gl.deleteFramebuffer(glResources.framebuffers[fbName]);
});
// Delete textures
Object.keys(glResources.textures).forEach((textureName) => {
gl.deleteTexture(glResources.textures[textureName]);
});
// Delete buffers
Object.keys(glResources.buffers).forEach((bufferName) => {
gl.deleteBuffer(glResources.buffers[bufferName]);
});
}
|
javascript
|
{
"resource": ""
}
|
q46051
|
createGLResources
|
train
|
function createGLResources(gl, glConfig) {
const resources = {
gl,
buffers: {},
textures: {},
framebuffers: {},
programs: {},
};
const buffers = glConfig.resources.buffers || [];
const textures = glConfig.resources.textures || [];
const framebuffers = glConfig.resources.framebuffers || [];
// Create Buffer
buffers.forEach((buffer) => {
const glBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
gl.bufferData(gl.ARRAY_BUFFER, buffer.data, gl.STATIC_DRAW);
resources.buffers[buffer.id] = glBuffer;
});
// Create Texture
textures.forEach((texture) => {
const glTexture = gl.createTexture();
const pixelStore = texture.pixelStore || [];
const texParameter = texture.texParameter || [];
gl.bindTexture(gl.TEXTURE_2D, glTexture);
pixelStore.forEach((option) => {
gl.pixelStorei(gl[option[0]], option[1]);
});
texParameter.forEach((option) => {
gl.texParameteri(gl.TEXTURE_2D, gl[option[0]], gl[option[1]]);
});
resources.textures[texture.id] = glTexture;
});
// Create Framebuffer
framebuffers.forEach((framebuffer) => {
const glFramebuffer = gl.createFramebuffer();
glFramebuffer.width = framebuffer.width;
glFramebuffer.height = framebuffer.height;
resources.framebuffers[framebuffer.id] = glFramebuffer;
});
// Create programs
Object.keys(glConfig.programs).forEach((programName) => {
buildShaderProgram(gl, programName, glConfig, resources);
});
// Add destroy function
resources.destroy = () => {
freeGLResources(resources);
};
return resources;
}
|
javascript
|
{
"resource": ""
}
|
q46052
|
styleRows
|
train
|
function styleRows(selection, self) {
selection
.classed(style.row, true)
.style('height', `${self.rowHeight}px`)
.style(
transformCSSProp,
(d, i) => `translate3d(0,${d.key * self.rowHeight}px,0)`
);
}
|
javascript
|
{
"resource": ""
}
|
q46053
|
styleBoxes
|
train
|
function styleBoxes(selection, self) {
selection
.style('width', `${self.boxWidth}px`)
.style('height', `${self.boxHeight}px`);
// .style('margin', `${self.boxMargin / 2}px`)
}
|
javascript
|
{
"resource": ""
}
|
q46054
|
getFieldRow
|
train
|
function getFieldRow(name) {
if (model.nest === null) return 0;
const foundRow = model.nest.reduce((prev, item, i) => {
const val = item.value.filter((def) => def.name === name);
if (val.length > 0) {
return item.key;
}
return prev;
}, 0);
return foundRow;
}
|
javascript
|
{
"resource": ""
}
|
q46055
|
updateStatusBarVisibility
|
train
|
function updateStatusBarVisibility() {
const cntnr = d3.select(model.container);
if (model.statusBarVisible) {
cntnr
.select('.status-bar-container')
.style('width', function updateWidth() {
return this.dataset.width;
});
cntnr.select('.show-button').classed(style.hidden, true);
cntnr.select('.hide-button').classed(style.hidden, false);
cntnr.select('.status-bar-text').classed(style.hidden, false);
} else {
cntnr.select('.status-bar-container').style('width', '20px');
cntnr.select('.show-button').classed(style.hidden, false);
cntnr.select('.hide-button').classed(style.hidden, true);
cntnr.select('.status-bar-text').classed(style.hidden, true);
}
}
|
javascript
|
{
"resource": ""
}
|
q46056
|
singleClick
|
train
|
function singleClick(d, i) {
// single click handler
const overCoords = d3.mouse(model.container);
const info = findGroupAndBin(overCoords);
if (info.radius > veryOutermostRadius) {
showAllChords();
} else if (
info.radius > outerRadius ||
(info.radius <= innerRadius &&
pmiChordMode.mode === PMI_CHORD_MODE_ONE_BIN_ALL_VARS &&
info.group === pmiChordMode.srcParam)
) {
if (info.found) {
model.renderState.pmiAllBinsTwoVars = null;
model.renderState.pmiOneBinAllVars = {
group: info.group,
bin: info.bin,
d,
i,
};
drawPMIOneBinAllVars()(d, i);
publicAPI.selectStatusBarText();
}
}
// },
}
|
javascript
|
{
"resource": ""
}
|
q46057
|
flushDataToListener
|
train
|
function flushDataToListener(dataListener, dataChanged) {
try {
if (dataListener) {
const dataToForward = dataHandler.get(
model[dataContainerName],
dataListener.request,
dataChanged
);
if (
dataToForward &&
(JSON.stringify(dataToForward) !== dataListener.request.lastPush ||
dataListener.request.metadata.forceFlush)
) {
dataListener.request.lastPush = JSON.stringify(dataToForward);
dataListener.onDataReady(dataToForward);
}
}
} catch (err) {
console.log(`flush ${dataName} error caught:`, err);
}
}
|
javascript
|
{
"resource": ""
}
|
q46058
|
getMouseEventInfo
|
train
|
function getMouseEventInfo(event, divElt) {
const clientRect = divElt.getBoundingClientRect();
return {
relX: event.clientX - clientRect.left,
relY: event.clientY - clientRect.top,
eltBounds: clientRect,
};
}
|
javascript
|
{
"resource": ""
}
|
q46059
|
ensureRuleNumbers
|
train
|
function ensureRuleNumbers(rule) {
if (!rule || rule.length === 0) {
return;
}
const ruleSelector = rule.type;
if (ruleSelector === 'rule') {
ensureRuleNumbers(rule.rule);
}
if (ruleSelector === 'logical') {
rule.terms.filter((r, idx) => idx > 0).forEach((r) => ensureRuleNumbers(r));
}
if (ruleSelector === '5C') {
const terms = rule.terms;
terms[0] = Number(terms[0]);
terms[4] = Number(terms[4]);
}
}
|
javascript
|
{
"resource": ""
}
|
q46060
|
md2json
|
train
|
function md2json(tree) {
var slide = null;
var slides = [];
var globalProperties = {}
var elements = tree.slice(1);
for (var i = 0; i < elements.length; ++i) {
var el = elements[i];
var add = true;
if (el[0] === 'header' && el[1].level === 1) {
if (slide) slides.push(Slide(slide.md_tree, slide.actions, slide.properties));
slide = {
md_tree: [],
html: '',
actions: [],
properties: {}
};
} else if (el[0] === 'para') {
// search inline code inside it
var actions = [];
for(var j = 1; j < el.length; ++j) {
var subel = el[j];
if (subel[0] === "inlinecode") {
var lines = subel[1].split('\n');
for (var ln = 0; ln < lines.length; ++ln) {
var line = lines[ln];
if (trim(line) !== '') {
// if matches property, parse it
if (prop_re.exec(line)) {
var p = parseProperties(subel[1]);
var prop = slide ? slide.properties: globalProperties
for(var k in p) {
prop[k] = {
order: ln,
value: p[k]
}
}
} else {
slide && slide.actions.push({
cmd: line,
order: ln
});
}
}
}
// remove from list
el.splice(j, 1);
--j;
}
}
}
add && slide && slide.md_tree.push(el);
}
if (slide) slides.push(Slide(slide.md_tree, slide.actions, slide.properties));
// remove the order for globalProperties
slides.global = {};
for(var k in globalProperties) {
slides.global[k] = globalProperties[k].value;
}
return slides;
}
|
javascript
|
{
"resource": ""
}
|
q46061
|
addAction
|
train
|
function addAction(codemirror, slideNumer, action) {
// parse properties from the new actions to next compare with
// the current ones in the slide
var currentActions = O.Template.parseProperties(action);
var currentLine;
var c = 0;
var blockStart;
// search for a actions block
for (var i = slideNumer + 1; i < codemirror.lineCount(); ++i) {
var line = codemirror.getLineHandle(i).text;
if (ACTIONS_BLOCK_REGEXP.exec(line)) {
if (++c === 2) {
// parse current slide properties
var slideActions = O.Template.parseProperties(getLines(codemirror, blockStart, i));
var updatedActions = {};
// search for the same in the slides
for (var k in currentActions) {
if (k in slideActions) {
updatedActions[k] = currentActions[k];
}
}
// remove the ones that need update
for (var k in updatedActions) {
for (var linePos = blockStart + 1; linePos < i; ++linePos) {
if (k in O.Template.parseProperties(codemirror.getLine(linePos))) {
codemirror.removeLine(linePos);
i -= 1;
}
}
}
// insert in the previous line
currentLine = codemirror.getLineHandle(i);
codemirror.setLine(i, action + "\n" + currentLine.text);
return;
} else {
blockStart = i;
}
} else if(SLIDE_REGEXP.exec(line)) {
// not found, insert a block
currentLine = codemirror.getLineHandle(slideNumer);
codemirror.setLine(slideNumer, currentLine.text + "\n```\n" + action +"\n```\n");
return;
}
}
// insert at the end
currentLine = codemirror.getLineHandle(slideNumer);
codemirror.setLine(slideNumer, currentLine.text + "\n```\n"+ action + "\n```\n");
}
|
javascript
|
{
"resource": ""
}
|
q46062
|
placeActionButtons
|
train
|
function placeActionButtons(el, codemirror) {
// search for h1's
var positions = [];
var lineNumber = 0;
codemirror.eachLine(function(a) {
if (SLIDE_REGEXP.exec(a.text)) {
positions.push({
pos: codemirror.heightAtLine(lineNumber)-66, // header height
line: lineNumber
});
}
++lineNumber;
});
//remove previously added buttons
el.selectAll('.actionButton').remove()
var buttons = el.selectAll('.actionButton')
.data(positions);
// enter
buttons.enter()
.append('div')
.attr('class', 'actionButton')
.style({ position: 'absolute' })
.html('add')
.on('click', function(d, i) {
d3.event.stopPropagation();
var self = this;
open(this, context.actions()).on('click', function(e) {
context.getAction(e, function(action) {
addAction(codemirror, d.line, action);
context.changeSlide(i);
});
close(self);
});
});
el.on('click.actionbutton', function() {
//close popup
close();
})
// update
var LINE_HEIGHT = 38;
buttons.style({
top: function(d) { return (d.pos - LINE_HEIGHT) + "px"; },
left: 16 + "px"
});
}
|
javascript
|
{
"resource": ""
}
|
q46063
|
Debug
|
train
|
function Debug() {
function _debug() {};
_debug.log = function(_) {
return Action({
enter: function() {
console.log("STATE =>", _, arguments);
},
update: function() {
console.log("STATE (.)", _, arguments);
},
exit: function() {
console.log("STATE <=", _, arguments);
}
});
};
return _debug;
}
|
javascript
|
{
"resource": ""
}
|
q46064
|
leaflet_method
|
train
|
function leaflet_method(name) {
_map[name] = function() {
var args = arguments;
return Action(function() {
map[name].apply(map, args);
});
};
}
|
javascript
|
{
"resource": ""
}
|
q46065
|
train
|
function(elem) {
// is this already initialized?
if ($(elem).data('spriteanim')) return $(elem).data('spriteanim');
var spriteanim = new SpriteAnim(elem);
$(elem).data('spriteanim', spriteanim);
return spriteanim;
}
|
javascript
|
{
"resource": ""
}
|
|
q46066
|
Edge
|
train
|
function Edge(a, b) {
var s = 0;
function t() {}
a._story(null, function() {
if(s !== 0) {
t.trigger();
}
s = 0;
});
b._story(null, function() {
if(s !== 1) {
t.trigger();
}
s = 1;
});
return Trigger(t);
}
|
javascript
|
{
"resource": ""
}
|
q46067
|
processFeature
|
train
|
function processFeature(_raw, _name, _feature, _other, _do) {
if(_feature === '.' || _feature === true) {
var skip = [_name];
if(_other) skip.push.apply(skip, angular.isArray(_other) ? _other : [_other]);
exclude(_raw, skip, _do);
} else if(typeof _feature === 'string') {
exclude(_raw[_feature], [], _do);
} else { // links is an array
include(_raw, _feature, _do);
}
}
|
javascript
|
{
"resource": ""
}
|
q46068
|
applyHooks
|
train
|
function applyHooks(_target, _hooks, _owner) {
for(var key in _hooks) {
if(_hooks.hasOwnProperty(key)) {
_target.$on(key, wrapHook(_hooks[key], _owner));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46069
|
processGroup
|
train
|
function processGroup(_records, _target, _params) {
// extract targets
var targets = [], record;
for(var i = 0, l = _records.length; i < l; i++) {
record = _records[i][_target];
if(angular.isArray(record)) {
targets.push.apply(targets, record);
} else if(record) {
targets.push(record);
}
}
// populate targets
if(targets.length > 0) {
var promise = typeof targets[0].$type.$populate === 'function' ?
targets[0].$type.$populate(targets, _params).$asPromise() :
populate(targets, _params);
if(promise) {
return promise.then(function() {
return targets;
});
}
}
return $q.when(targets);
}
|
javascript
|
{
"resource": ""
}
|
q46070
|
train
|
function() {
return {
/**
* @memberof BuilderApi#
*
* @description Sets an attribute mapping.
*
* Allows a explicit server to model property mapping to be defined.
*
* For example, to map the response property `stats.created_at` to model's `created` property.
*
* ```javascript
* builder.attrMap('created', 'stats.created_at');
* ```
*
* It's also posible to use a wildcard '*' as server name to use the default name decoder as
* server name. This is used to force a property to be processed on decode/encode even if its
* not present on request/record (respectively), by doing this its posible, for example, to define
* a dynamic property that is generated automatically before the object is send to the server.
*
* @param {string} _attr Attribute name
* @param {string} _serverName Server (request/response) property name
* @return {BuilderApi} self
*/
attrMap: function(_attr, _serverPath, _forced) {
// extract parent node from client name:
var index = _attr.lastIndexOf('.'),
node = index !== -1 ? _attr.substr(0, index) : '',
leaf = index !== -1 ? _attr.substr(index + 1) : _attr;
mapped[_attr] = true;
var nodes = (mappings[node] || (mappings[node] = []));
nodes.push({ path: leaf, map: _serverPath === '*' ? null : _serverPath.split('.'), mapPath: _serverPath, forced: _forced });
return this;
},
/**
* @memberof BuilderApi#
*
* @description Sets an attribute mask.
*
* An attribute mask prevents the attribute to be loaded from or sent to the server on certain operations.
*
* The attribute mask is a string composed by:
* * C: To prevent attribute from being sent on create
* * R: To prevent attribute from being loaded from server
* * U: To prevent attribute from being sent on update
*
* For example, the following will prevent an attribute to be send on create or update:
*
* ```javascript
* builder.attrMask('readOnly', 'CU');
* ```
*
* If a true boolean value is passed as mask, then 'CRU' will be used
* If a false boolean valus is passed as mask, then mask will be removed
*
* @param {string} _attr Attribute name
* @param {boolean|string} _mask Attribute mask
* @return {BuilderApi} self
*/
attrMask: function(_attr, _mask) {
if(!_mask) {
delete masks[_attr];
} else {
masks[_attr] = _mask;
}
return this;
},
/**
* @memberof BuilderApi#
*
* @description Assigns a decoding function/filter to a given attribute.
*
* @param {string} _name Attribute name
* @param {string|function} _filter filter or function to register
* @param {mixed} _filterParam Misc filter parameter
* @param {boolean} _chain If true, filter is chained to the current attribute filter.
* @return {BuilderApi} self
*/
attrDecoder: function(_attr, _filter, _filterParam, _chain) {
if(typeof _filter === 'string') {
var filter = $filter(_filter);
_filter = function(_value) { return filter(_value, _filterParam); };
}
decoders[_attr] = _chain ? Utils.chain(decoders[_attr], _filter) : _filter;
return this;
},
/**
* @memberof BuilderApi#
*
* @description Assigns a encoding function/filter to a given attribute.
*
* @param {string} _name Attribute name
* @param {string|function} _filter filter or function to register
* @param {mixed} _filterParam Misc filter parameter
* @param {boolean} _chain If true, filter is chained to the current attribute filter.
* @return {BuilderApi} self
*/
attrEncoder: function(_attr, _filter, _filterParam, _chain) {
if(typeof _filter === 'string') {
var filter = $filter(_filter);
_filter = function(_value) { return filter(_value, _filterParam); };
}
encoders[_attr] = _chain ? Utils.chain(encoders[_attr], _filter) : _filter;
return this;
},
/**
* @memberof BuilderApi#
*
* @description Makes an attribute volatile, a volatile attribute is deleted from source after encoding.
*
* @param {string} _name Attribute name
* @param {boolean} _isVolatile defaults to true, if set to false then the attribute is no longer volatile.
* @return {BuilderApi} self
*/
attrVolatile: function(_attr, _isVolatile) {
vol[_attr] = _isVolatile === undefined ? true : _isVolatile;
return this;
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q46071
|
train
|
function(_chain) {
for(var i = 0, l = _chain.length; i < l; i++) {
this.mixin(_chain[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46072
|
train
|
function(_mix) {
if(_mix.$$chain) {
this.chain(_mix.$$chain);
} else if(typeof _mix === 'string') {
this.mixin($injector.get(_mix));
} else if(isArray(_mix)) {
this.chain(_mix);
} else if(isFunction(_mix)) {
_mix.call(this.dsl, $injector);
} else {
this.dsl.describe(_mix);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46073
|
buildAsyncSaveFun
|
train
|
function buildAsyncSaveFun(_this, _oldSave, _promise, _oldPromise) {
return function() {
// swap promises so save behaves like it has been called during the original call.
var currentPromise = _this.$promise;
_this.$promise = _oldPromise;
// when save resolves, the timeout promise is resolved and the last resource promise returned
// so it behaves
_oldSave.call(_this).$promise.then(
function(_data) {
_promise.resolve(_data);
_this.$promise = currentPromise;
}, function(_reason) {
_promise.reject(_reason);
_this.$promise = currentPromise;
}
);
_this.$dmStatus = null;
};
}
|
javascript
|
{
"resource": ""
}
|
q46074
|
applyRules
|
train
|
function applyRules(_string, _ruleSet, _skip) {
if(_skip.indexOf(_string.toLowerCase()) === -1) {
var i = 0, rule;
while(rule = _ruleSet[i++]) {
if(_string.match(rule[0])) {
return _string.replace(rule[0], rule[1]);
}
}
}
return _string;
}
|
javascript
|
{
"resource": ""
}
|
q46075
|
train
|
function(_hook, _args, _ctx) {
var cbs = hooks[_hook], i, cb;
if(cbs) {
for(i = 0; !!(cb = cbs[i]); i++) {
cb.apply(_ctx || this, _args || []);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q46076
|
train
|
function(_items) {
var list = new List();
if(_items) list.push.apply(list, _items);
return list;
}
|
javascript
|
{
"resource": ""
}
|
|
q46077
|
train
|
function(_params, _scope) {
_params = this.$params ? angular.extend({}, this.$params, _params) : _params;
return newCollection(_params, _scope || this.$scope);
}
|
javascript
|
{
"resource": ""
}
|
|
q46078
|
helpDefine
|
train
|
function helpDefine(_api, _name, _fun) {
var api = APIS[_api];
Utils.assert(!!api, 'Invalid api name $1', _api);
if(_name) {
api[_name] = Utils.override(api[_name], _fun);
} else {
Utils.extendOverriden(api, _fun);
}
}
|
javascript
|
{
"resource": ""
}
|
q46079
|
validateFile
|
train
|
async function validateFile (file, options) {
if (file instanceof File === false) {
return null
}
await file.setOptions(Object.assign(file.validationOptions, options)).runValidations()
return _.size(file.error()) ? file.error().message : null
}
|
javascript
|
{
"resource": ""
}
|
q46080
|
train
|
function (type, data) {
if (type === 'size') {
return `File size should be less than ${bytes(data.size)}`
}
if (type === 'type') {
const verb = data.types.length === 1 ? 'is' : 'are'
return `Invalid file type ${data.subtype} or ${data.type}. Only ${data.types.join(', ')} ${verb} allowed`
}
if (type === 'extname') {
const verb = data.extnames.length === 1 ? 'is' : 'are'
return `Invalid file extension ${data.extname}. Only ${data.extnames.join(', ')} ${verb} allowed`
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46081
|
_empty
|
train
|
function _empty( x, y, force ) {
if ( x < 0 || x >= that.width || y < 0 || y >= that.height ) return;
var pos = that.pos(x, y);
var d = that.grid[pos];
if (d && (d & SLAB_MASK) && (force || !(d & APPLE_MASK))) {
that.grid[pos] &= ~SLAB_MASK; // clear out slab
// Clear next neighbor if this is empty tile
if (that.grid[pos] == 0) {
_empty(x, y - 1) // north
_empty(x, y + 1) // south
_empty(x - 1, y) // west
_empty(x - 1, y - 1) // north west
_empty(x - 1, y + 1) // south east
_empty(x + 1, y) // east
_empty(x + 1, y - 1) // north east
_empty(x + 1, y + 1) // south east
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46082
|
directoryHTML
|
train
|
function directoryHTML( res, urldir, pathname, list ) {
var ulist = [];
function sendHTML( list ) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.send('<!DOCTYPE html>' +
'<html>\n' +
'<title>Directory listing for '+htmlsafe(urldir)+'</title>\n' +
'<body>\n' +
'<h2>Directory listing for '+htmlsafe(urldir)+'</h2>\n' +
'<hr><ul>\n' +
list.join('\n') +
'</ul><hr>\n' +
'</body>\n' +
'</html>');
}
if ( !list.length ) {
// Nothing to resolve
return sendHTML( ulist );
}
// Check for each file if it's a directory or a file
var q = async.queue(function(item, cb) {
fs.stat(path.join(pathname, item), function(err, stat) {
if ( !stat ) cb();
var link = escape(item);
item = htmlsafe(item);
if ( stat.isDirectory() ) {
ulist.push('<li><a href="'+link+'/">'+item+'/</a></li>')
} else {
ulist.push('<li><a href="'+link+'">'+item+'</a></li>')
}
cb();
});
}, 4);
list.forEach(function(item) {
q.push(item);
});
q.drain = function() {
// Finished checking files, send the response
sendHTML(ulist);
};
}
|
javascript
|
{
"resource": ""
}
|
q46083
|
_check
|
train
|
function _check(err, id) {
updateProgress(1);
if (err) {
alert('Failed to load ' + id + ': ' + err);
}
loadc++;
if (itemc == loadc) callback();
}
|
javascript
|
{
"resource": ""
}
|
q46084
|
_fill_canvas
|
train
|
function _fill_canvas(canvas, items) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#ddd';
for (var i = 0; i < ITEM_COUNT; i++) {
var asset = items[i];
ctx.save();
ctx.shadowColor = "rgba(0,0,0,0.5)";
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 5;
ctx.drawImage(asset.img, 3, i * SLOT_HEIGHT + IMAGE_TOP_MARGIN);
ctx.drawImage(asset.img, 3, (i + ITEM_COUNT) * SLOT_HEIGHT + IMAGE_TOP_MARGIN);
ctx.restore();
ctx.fillRect(0, i * SLOT_HEIGHT, 70, SLOT_SEPARATOR_HEIGHT);
ctx.fillRect(0, (i + ITEM_COUNT) * SLOT_HEIGHT, 70, SLOT_SEPARATOR_HEIGHT);
}
}
|
javascript
|
{
"resource": ""
}
|
q46085
|
_find
|
train
|
function _find( items, id ) {
for ( var i=0; i < items.length; i++ ) {
if (items[i].id == id) return i;
}
}
|
javascript
|
{
"resource": ""
}
|
q46086
|
_check_slot
|
train
|
function _check_slot(offset, result) {
if (now - that.lastUpdate > SPINTIME) {
var c = parseInt(Math.abs(offset / SLOT_HEIGHT)) % ITEM_COUNT;
if (c == result) {
if (result == 0) {
if (Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {
return true; // done
}
} else if (Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {
return true; // done
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q46087
|
initAudio
|
train
|
function initAudio( audios, callback ) {
var format = 'mp3';
var elem = document.createElement('audio');
if ( elem ) {
// Check if we can play mp3, if not then fall back to ogg
if( !elem.canPlayType( 'audio/mpeg;' ) && elem.canPlayType('audio/ogg;')) format = 'ogg';
}
var AudioContext = window.webkitAudioContext || window.mozAudioContext || window.MSAudioContext || window.AudioContext;
if ( AudioContext ) {
$('#audio_debug').text('WebAudio Supported');
// Browser supports webaudio
// https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
return _initWebAudio( AudioContext, format, audios, callback );
} else if ( elem ) {
$('#audio_debug').text('HTML5 Audio Supported');
// HTML5 Audio
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#the-audio-element
return _initHTML5Audio(format, audios, callback);
} else {
$('#audio_debug').text('Audio NOT Supported');
// audio not supported
audios.forEach(function(item) {
item.play = function() {}; // dummy play
});
callback();
}
}
|
javascript
|
{
"resource": ""
}
|
q46088
|
_build_object
|
train
|
function _build_object( game, x, y, speed ) {
var car_asset = game.carAssets[parseInt(Math.random()*game.carAssets.length)]
var framex = car_asset.w * parseInt(Math.random() * car_asset.count);
return {
collided: 0,
width: car_asset.w,
height: car_asset.h,
img: car_asset.img,
framex: framex,
pos: {
x: x,
y: y
},
speed: speed,
cleanup: function() {
if (this.bubble) {
this.bubble.remove();
}
},
update: function( t ) {
if (this.collided > 2 && !this.bubble) {
this.collided = 0;
this.bubble = $('<div class="bubble">'+BLURB_TBL[parseInt(Math.random()*BLURB_TBL.length)]+'</div>').appendTo('#area');
this.bubble.css({
left: this.pos.x - 30,
top: this.pos.y - 20
})
this.bubbleEnd = t + 1000;
} else if (this.bubbleEnd < t) {
this.bubble.remove();
} else if (this.bubble) {
this.bubble.css({
left: this.pos.x - 30,
top: this.pos.y - 20
})
}
},
clear: function( ctx ) {
ctx.clearRect( this.pos.x - 1, this.pos.y - 1, this.width + 1 , this.height + 1 );
},
draw: function( ctx ) {
ctx.drawImage( this.img, this.framex, 0, this.width, this.height,
this.pos.x, this.pos.y, this.width, this.height );
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46089
|
select
|
train
|
function select(elems) {
var r = Math.random();
var ref = 0;
for(var i=0; i < elems.length; i++) {
var elem= elems[i];
ref += elem[1];
if (r < ref) return elem[0];
}
// This happens only if probabilities don't add up to 1
return null;
}
|
javascript
|
{
"resource": ""
}
|
q46090
|
configStripper
|
train
|
function configStripper (c) {
return {
DeadLetterConfig: c.DeadLetterConfig,
Description: c.Description,
Environment: c.Environment,
Handler: c.Handler,
MemorySize: c.MemorySize,
Role: c.Role,
Runtime: c.Runtime,
Timeout: c.Timeout,
TracingConfig: c.TracingConfig
}
}
|
javascript
|
{
"resource": ""
}
|
q46091
|
validateTicket
|
train
|
function validateTicket(req, options, callback) {
var query = {
service: utils.getPath('service', options),
ticket: req.query.ticket
};
var logger = utils.getLogger(req, options);
if (options.paths.proxyCallback) query.pgtUrl = utils.getPath('pgtUrl', options);
var casServerValidPath = utils.getPath('serviceValidate', options) + '?' + queryString.stringify(query);
logger.info('Sending request to: "' + casServerValidPath + '" to validate ticket.');
var startTime = Date.now();
utils.getRequest(casServerValidPath, function(err, response) {
/* istanbul ignore if */
logger.access('|GET|' + casServerValidPath + '|' + (err ? 500 : response.status) + "|" + (Date.now() - startTime));
if (err) {
logger.error('Error when sending request to CAS server, error: ', err.toString());
logger.error(err);
return callback(err);
}
callback(null, response);
});
}
|
javascript
|
{
"resource": ""
}
|
q46092
|
retrievePGTFromPGTIOU
|
train
|
function retrievePGTFromPGTIOU(req, res, callback, pgtIou, options) {
var logger = utils.getLogger(req, options);
logger.info('Trying to retrieve pgtId from pgtIou...');
req.sessionStore.get(pgtIou, function(err, session) {
/* istanbul ignore if */
if (err) {
logger.error('Get pgtId from sessionStore failed!');
logger.error(err);
req.sessionStore.destroy(pgtIou);
return callback(function(req, res, next) {
res.status(500).send({
message: 'Get pgtId from sessionStore failed!',
error: err
});
});
}
if (session && session.pgtId) {
var lastUrl = utils.getLastUrl(req, options, logger);
if (!req.session || req.session && !req.session.cas) {
logger.error('Here session.cas should not be empty!', req.session);
req.session.cas = {};
}
req.session.cas.pgt = session.pgtId;
req.session.save(function(err) {
/* istanbul ignore if */
if (err) {
logger.error('Trying to save session failed!');
logger.error(err);
return callback(function(req, res, next) {
res.status(500).send({
message: 'Trying to save session failed!',
error: err
});
});
}
// 释放
req.sessionStore.destroy(pgtIou);
/* istanbul ignore if */ // 测一次就够了
lastUrl = getLastUrl(req, res, options, logger, lastUrl);
logger.info('CAS proxy mode login and validation succeed, pgtId finded. Redirecting to lastUrl: ' + lastUrl);
return callback(function(req, res, next) {
res.redirect(302, lastUrl);
});
});
} else {
logger.error('CAS proxy mode login and validation succeed, but can\' find pgtId from pgtIou: `' + pgtIou + '`, maybe something wrong with sessionStroe!');
callback(function(req, res, next) {
res.status(401).send({
message: 'CAS proxy mode login and validation succeed, but can\' find pgtId from pgtIou: `' + pgtIou + '`, maybe something wrong with sessionStroe!'
});
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46093
|
requestPT
|
train
|
function requestPT(path, callback, retryHandler) {
logger.info('Trying to request proxy ticket from ', proxyPath);
var startTime = Date.now();
utils.getRequest(path, function(err, response) {
/* istanbul ignore if */
logger.access('|GET|' + path + '|' + (err ? 500 : response.status) + "|" + (Date.now() - startTime));
if (err) {
logger.error('Error happened when sending request to: ' + path);
logger.error(err);
return callback(err);
}
if (response.status !== 200) {
logger.error('Request fail when trying to get proxy ticket', response);
if (typeof retryHandler === 'function') return retryHandler(err);
return callback(new Error('Request fail when trying to get proxy ticket, response status: ' + response.status +
', response body: ' + response.body));
}
var pt = parseCasResponse(response.body);
if (pt) {
logger.info('Request proxy ticket succeed, receive pt: ', pt);
callback(null, pt);
} else {
logger.error('Can\' get pt from get proxy ticket response.');
logger.error('Request for PT succeed, but response is invalid, response: ', response.body);
if (typeof retryHandler === 'function') return retryHandler(new Error('Request for PT succeed, but response is invalid, response: ' + response.body));
return callback(new Error('Request for PT succeed, but the response is invalid, response: ' + response.body));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46094
|
isMatchRule
|
train
|
function isMatchRule(req, pathname, rule) {
if (typeof rule === 'string') {
return pathname.indexOf(rule) > -1;
} else if (rule instanceof RegExp) {
return rule.test(pathname);
} else if (typeof rule === 'function') {
return rule(pathname, req);
}
}
|
javascript
|
{
"resource": ""
}
|
q46095
|
shouldIgnore
|
train
|
function shouldIgnore(req, options) {
var logger = getLogger(req, options);
if (options.match && options.match.splice && options.match.length) {
var matchedRule;
var hasMatch = options.match.some(function (rule) {
matchedRule = rule;
return isMatchRule(req, req.path, rule);
});
if (hasMatch) {
logger.info('Matched match rule.', matchedRule, ' Go into CAS authentication.');
return false;
}
return true;
}
if (options.ignore && options.ignore.splice && options.ignore.length) {
var matchedIgnoreRule;
var hasMatchIgnore = options.ignore.some(function (rule) {
matchedIgnoreRule = rule;
return isMatchRule(req, req.path, rule);
});
if (hasMatchIgnore) {
logger.info('Matched ignore rule.', matchedIgnoreRule, ' Go through CAS.');
return true;
}
return false;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q46096
|
getRequest
|
train
|
function getRequest(path, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {
method: 'get'
};
} else {
options.method = 'get';
}
if (options.params) {
var uri = url.parse(path, true);
uri.query = _.merge({}, uri.query, options.params);
path = url.format(uri);
delete options.params;
}
sendRequest(path, options, callback);
}
|
javascript
|
{
"resource": ""
}
|
q46097
|
schema_jsonSchema
|
train
|
function schema_jsonSchema(name) {
let result;
name = name || this.options.name;
if (this.__buildingSchema) {
this.__jsonSchemaId =
this.__jsonSchemaId ||
'#schema-' + (++schema_jsonSchema.__jsonSchemaIdCounter);
return {'$ref': this.__jsonSchemaId}
}
if (!this.__jsonSchema) {
this.__buildingSchema = true;
this.__jsonSchema = __build(name, this);
this.__buildingSchema = false;
if (this.__jsonSchemaId) {
this.__jsonSchema = Object.assign(
{id: this.__jsonSchemaId}, this.__jsonSchema
)
}
}
result = JSON.parse(JSON.stringify(this.__jsonSchema));
if (name) {
result.title = name;
} else {
delete result.title;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q46098
|
simpleType_jsonSchema
|
train
|
function simpleType_jsonSchema(name) {
var result = {};
result.type = this.instance.toLowerCase();
__processOptions(result, this.options)
return result;
}
|
javascript
|
{
"resource": ""
}
|
q46099
|
objectId_jsonSchema
|
train
|
function objectId_jsonSchema(name) {
var result = simpleType_jsonSchema.call(this, name);
result.type = 'string';
result.pattern = '^[0-9a-fA-F]{24}$';
return result;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.