_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q57800
|
resolveOutputTarget
|
train
|
function resolveOutputTarget(customPath, filename) {
const realPath = path.resolve('.', customPath);
const getPath = tryCatch(
realPath => fs.lstatSync(realPath).isDirectory()
? path.join(realPath, filename)
: realPath,
identity);
return getPath(realPath);
}
|
javascript
|
{
"resource": ""
}
|
q57801
|
objCompare
|
train
|
function objCompare(rootObj, objAry) {
var aryLen = objAry.length;
// var rootStr = JSON.stringify(rootObj);
var matchNum = 0;
for (var i = 0; i < aryLen; i++) {
// var compareStr = JSON.stringify(objAry[i]);
var compareObj = objAry[i];
matchNum += rootObj == compareObj ? 1 : 0;
}
return matchNum > 0 ? true : false;
}
|
javascript
|
{
"resource": ""
}
|
q57802
|
serialize
|
train
|
function serialize(input) {
const value = JSON.stringify(input);
return value === undefined
? reject(new Error(`Unsupported type ${type(input)}`))
: resolve(value);
}
|
javascript
|
{
"resource": ""
}
|
q57803
|
resolveRungFolder
|
train
|
function resolveRungFolder() {
const folder = path.join(os.homedir(), '.rung');
const createIfNotExists = tryCatch(
~(fs.lstatSync(folder).isDirectory()
? resolve()
: reject(new Error('~/.rung is not a directory'))),
~createFolder(folder)
);
return createIfNotExists();
}
|
javascript
|
{
"resource": ""
}
|
q57804
|
watchChanges
|
train
|
function watchChanges(io, params) {
const folder = process.cwd();
return watch(folder, { recursive: true }, () => {
emitInfo('changes detected. Recompiling...');
io.sockets.emit('load');
const start = new Date().getTime();
executeWithParams(params)
.tap(alerts => {
const ellapsed = new Date().getTime() - start;
emitSuccess(`wow! recompiled and executed in ${ellapsed}ms!`);
io.sockets.emit('update', compileMarkdown(alerts));
})
.catch(err => {
emitError(`hot compilation error, baby: ${err.message}`);
io.sockets.emit('failure', err.stack);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57805
|
startServer
|
train
|
function startServer(alerts, params, port, resources) {
const compiledAlerts = compileMarkdown(alerts);
const app = http.createServer((req, res) =>
res.end(resources[req.url] || resources['/index.html']));
const io = listen(app);
io.on('connection', socket => {
emitInfo(`new session for ${socket.handshake.address}`);
socket.emit('update', compiledAlerts);
socket.on('disconnect', () => {
emitInfo(`disconnected session ${socket.handshake.address}`);
});
});
return new Promise(resolve => app.listen(port, emitRungEmoji & resolve))
.then(~watchChanges(io, params));
}
|
javascript
|
{
"resource": ""
}
|
q57806
|
cli
|
train
|
function cli(args) {
const { _: [command] } = args;
return getModule(command).default(args)
.catch(err => {
getModule('input').emitError(err.message);
process.exit(1);
});
}
|
javascript
|
{
"resource": ""
}
|
q57807
|
InteractionManager
|
train
|
function InteractionManager(stage)
{
/**
* a refference to the stage
*
* @property stage
* @type Stage
*/
this.stage = stage;
/**
* the mouse data
*
* @property mouse
* @type InteractionData
*/
this.mouse = new InteractionData();
/**
* an object that stores current touches (InteractionData) by id reference
*
* @property touchs
* @type Object
*/
this.touchs = {};
// helpers
this.tempPoint = new Point();
//this.tempMatrix = mat3.create();
this.mouseoverEnabled = true;
//tiny little interactiveData pool!
this.pool = [];
this.interactiveItems = [];
this.interactionDOMElement = null;
this.last = 0;
}
|
javascript
|
{
"resource": ""
}
|
q57808
|
RenderTexture
|
train
|
function RenderTexture(width, height)
{
EventTarget.call( this );
this.width = width || 100;
this.height = height || 100;
this.identityMatrix = mat3.create();
this.frame = new Rectangle(0, 0, this.width, this.height);
if(globals.gl)
{
this.initWebGL();
}
else
{
this.initCanvas();
}
}
|
javascript
|
{
"resource": ""
}
|
q57809
|
MovieClip
|
train
|
function MovieClip(textures)
{
Sprite.call(this, textures[0]);
/**
* The array of textures that make up the animation
*
* @property textures
* @type Array
*/
this.textures = textures;
/**
* The speed that the MovieClip will play at. Higher is faster, lower is slower
*
* @property animationSpeed
* @type Number
* @default 1
*/
this.animationSpeed = 1;
/**
* Whether or not the movie clip repeats after playing.
*
* @property loop
* @type Boolean
* @default true
*/
this.loop = true;
/**
* Function to call when a MovieClip finishes playing
*
* @property onComplete
* @type Function
*/
this.onComplete = null;
/**
* [read-only] The index MovieClips current frame (this may not have to be a whole number)
*
* @property currentFrame
* @type Number
* @default 0
* @readOnly
*/
this.currentFrame = 0;
/**
* [read-only] Indicates if the MovieClip is currently playing
*
* @property playing
* @type Boolean
* @readOnly
*/
this.playing = false;
}
|
javascript
|
{
"resource": ""
}
|
q57810
|
AbstractFilter
|
train
|
function AbstractFilter(fragmentSrc, uniforms)
{
/**
* An array of passes - some filters contain a few steps this array simply stores the steps in a liniear fashion.
* For example the blur filter has two passes blurX and blurY.
* @property passes
* @type Array an array of filter objects
* @private
*/
this.passes = [this];
this.dirty = true;
this.padding = 0;
/**
@property uniforms
@private
*/
this.uniforms = uniforms || {};
this.fragmentSrc = fragmentSrc || [];
}
|
javascript
|
{
"resource": ""
}
|
q57811
|
DisplayObject
|
train
|
function DisplayObject()
{
this.last = this;
this.first = this;
/**
* The coordinate of the object relative to the local coordinates of the parent.
*
* @property position
* @type Point
*/
this.position = new Point();
/**
* The scale factor of the object.
*
* @property scale
* @type Point
*/
this.scale = new Point(1,1);//{x:1, y:1};
/**
* The pivot point of the displayObject that it rotates around
*
* @property pivot
* @type Point
*/
this.pivot = new Point(0,0);
/**
* The rotation of the object in radians.
*
* @property rotation
* @type Number
*/
this.rotation = 0;
/**
* The opacity of the object.
*
* @property alpha
* @type Number
*/
this.alpha = 1;
/**
* The visibility of the object.
*
* @property visible
* @type Boolean
*/
this.visible = true;
/**
* This is the defined area that will pick up mouse / touch events. It is null by default.
* Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children)
*
* @property hitArea
* @type Rectangle|Circle|Ellipse|Polygon
*/
this.hitArea = null;
/**
* This is used to indicate if the displayObject should display a mouse hand cursor on rollover
*
* @property buttonMode
* @type Boolean
*/
this.buttonMode = false;
/**
* Can this object be rendered
*
* @property renderable
* @type Boolean
*/
this.renderable = false;
/**
* [read-only] The display object container that contains this display object.
*
* @property parent
* @type DisplayObjectContainer
* @readOnly
*/
this.parent = null;
/**
* [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage.
*
* @property stage
* @type Stage
* @readOnly
*/
this.stage = null;
/**
* [read-only] The multiplied alpha of the displayobject
*
* @property worldAlpha
* @type Number
* @readOnly
*/
this.worldAlpha = 1;
/**
* [read-only] Whether or not the object is interactive, do not toggle directly! use the `interactive` property
*
* @property _interactive
* @type Boolean
* @readOnly
* @private
*/
this._interactive = false;
this.defaultCursor = 'pointer';
/**
* [read-only] Current transform of the object based on world (parent) factors
*
* @property worldTransform
* @type Mat3
* @readOnly
* @private
*/
this.worldTransform = mat3.create();//mat3.identity();
/**
* [read-only] Current transform of the object locally
*
* @property localTransform
* @type Mat3
* @readOnly
* @private
*/
this.localTransform = mat3.create();//mat3.identity();
/**
* [NYI] Unkown
*
* @property color
* @type Array<>
* @private
*/
this.color = [];
/**
* [NYI] Holds whether or not this object is dynamic, for rendering optimization
*
* @property dynamic
* @type Boolean
* @private
*/
this.dynamic = true;
// chach that puppy!
this._sr = 0;
this._cr = 1;
this.filterArea = new Rectangle(0,0,1,1);
/*
* MOUSE Callbacks
*/
/**
* A callback that is used when the users clicks on the displayObject with their mouse
* @method click
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user clicks the mouse down over the sprite
* @method mousedown
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the mouse that was over the displayObject
* for this callback to be fired the mouse must have been pressed down over the displayObject
* @method mouseup
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the mouse that was over the displayObject but is no longer over the displayObject
* for this callback to be fired, The touch must have started over the displayObject
* @method mouseupoutside
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the users mouse rolls over the displayObject
* @method mouseover
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the users mouse leaves the displayObject
* @method mouseout
* @param interactionData {InteractionData}
*/
/*
* TOUCH Callbacks
*/
/**
* A callback that is used when the users taps on the sprite with their finger
* basically a touch version of click
* @method tap
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user touch's over the displayObject
* @method touchstart
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases a touch over the displayObject
* @method touchend
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the touch that was over the displayObject
* for this callback to be fired, The touch must have started over the sprite
* @method touchendoutside
* @param interactionData {InteractionData}
*/
}
|
javascript
|
{
"resource": ""
}
|
q57812
|
train
|
function (fn, name) {
function proxiedFn() {
'use strict';
var fields = privates.get(this); // jshint ignore:line
return fn.apply(fields, arguments);
}
Object.defineProperty(proxiedFn, 'name', {
value: name,
configurable: true
});
return proxiedFn;
}
|
javascript
|
{
"resource": ""
}
|
|
q57813
|
prepareView
|
train
|
function prepareView() {
_(this).el = document.createElement('div');
_(this).el.setAttribute('class', 'VirtualScrollingTree');
let contentDiv = `<div class="VirtualScrollingTree-content"></div>`;
_(this).el.innerHTML = `
${_(this).smoothScrolling? '' : contentDiv}
<div class="VirtualScrollingTree-scrollbar ${_(this).scrollbarClass}">
${_(this).smoothScrolling? contentDiv : ''}
<div class="VirtualScrollingTree-scrollbarContent"></div>
</div>
`.replace(/\n\s+/g, '');
_(this).view = {
content: _(this).el.querySelector('.VirtualScrollingTree-content'),
scrollbar: _(this).el.querySelector('.VirtualScrollingTree-scrollbar'),
scrollbarContent: _(this).el.querySelector('.VirtualScrollingTree-scrollbarContent')
};
if (!_(this).smoothScrolling) {
_(this).view.content.addEventListener('wheel', e => {
_(this).view.scrollbar.scrollTop += e.deltaY;
}, true);
}
// Scrolling either the content with the middle mouse wheel, or manually
// scrolling the scrollbar directly should accomplish the same thing.
// Note it's important for this to come after the transform above.
// If it's not, when the DOM is being manipulated the scrollbar will jump.
let lastScrollTop = 0;
_(this).view.scrollbar.addEventListener('scroll', (e) => {
if (_(this).scrollLocked) {
return;
}
let newScrollTop = parseInt(_(this).view.scrollbar.scrollTop / _(this).itemHeight);
if (lastScrollTop !== newScrollTop) {
lastScrollTop = newScrollTop;
if (_(this).smoothScrolling) {
_(this).view.content.style.transform = `translateY(${newScrollTop * _(this).itemHeight}px)`;
}
requestData.call(this);
}
}, true);
_(this).parent.appendChild(_(this).el);
}
|
javascript
|
{
"resource": ""
}
|
q57814
|
updateViewDimensions
|
train
|
function updateViewDimensions(totalItems) {
let visibleItems = Math.floor(_(this).parent.offsetHeight / _(this).itemHeight);
_(this).view.scrollbar.style.height = visibleItems * _(this).itemHeight + 'px';
_(this).view.scrollbarContent.style.height = totalItems * _(this).itemHeight + 'px';
let scrollbarWidth = totalItems < visibleItems? 0 : getNativeScrollbarWidth.call(this);
if (!_(this).smoothScrolling) {
_(this).view.content.style.width = Math.floor(_(this).el.getBoundingClientRect().width) - scrollbarWidth - 1 + 'px';
_(this).view.scrollbar.style.width = scrollbarWidth + 1 + 'px';
// Not needed for smooth
_(this).view.content.style.height = visibleItems * _(this).itemHeight + 'px';
} else {
_(this).view.scrollbar.style.width = '100%';
_(this).view.content.style.width = 'calc(100% - 1px)';
}
}
|
javascript
|
{
"resource": ""
}
|
q57815
|
getNativeScrollbarWidth
|
train
|
function getNativeScrollbarWidth() {
let outer = document.createElement('div');
outer.style.overflowY = 'scroll';
outer.setAttribute('class', _(this).scrollbarClass);
outer.style.visibility = 'hidden';
outer.style.width = '100px';
document.body.appendChild(outer);
let content = document.createElement('div');
outer.appendChild(content);
var width = 100 - Math.floor(content.getBoundingClientRect().width);
document.body.removeChild(outer);
return width;
}
|
javascript
|
{
"resource": ""
}
|
q57816
|
requestData
|
train
|
function requestData() {
let visible = Math.ceil(_(this).parent.offsetHeight / _(this).itemHeight);
let scrollIndex = Math.floor(_(this).view.scrollbar.scrollTop / _(this).itemHeight);
let request = buildRequest.call(this, scrollIndex, visible);
_(this).request = request;
_(this).onDataFetch(request, setData.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q57817
|
renderItem
|
train
|
function renderItem (element, data, updating) {
_(this).onItemRender(element, {
...data.original,
expanded: isExpanded.call(this, data.id),
indent: calculateLevel.call(this, data),
toggle: () => {
// Check to see if this item is expanded or not
let expanded = isExpanded.call(this, data.id);
if (expanded) {
collapseItem.call(this, data);
} else {
expandItem.call(this, data);
}
// Each time we expand or collapse we need to re-request data.
requestData.call(this);
}
}, updating);
}
|
javascript
|
{
"resource": ""
}
|
q57818
|
createItem
|
train
|
function createItem (data) {
let itemEl = document.createElement('div');
itemEl.setAttribute('class', 'VirtualScrollingTree-item');
renderItem.call(this, itemEl, data);
return {
id: data.id,
el: itemEl
};
}
|
javascript
|
{
"resource": ""
}
|
q57819
|
forEachExpansion
|
train
|
function forEachExpansion(expansions, fn) {
let impl = function(expansions) {
expansions.forEach((expansion) => {
fn(expansion);
impl(expansion.expansions);
});
};
impl(expansions);
}
|
javascript
|
{
"resource": ""
}
|
q57820
|
findExpansion
|
train
|
function findExpansion(id) {
let result;
forEachExpansion(_(this).expansions, (expansion) => {
if (expansion.id === id) {
result = expansion;
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q57821
|
collapseItem
|
train
|
function collapseItem(data) {
let parentExpansions = findExpansion.call(this, data.parent).expansions;
let index = parentExpansions.findIndex((expansion) => {
return expansion.id === data.id;
});
parentExpansions.splice(index, 1);
}
|
javascript
|
{
"resource": ""
}
|
q57822
|
expandItem
|
train
|
function expandItem(data) {
// Cloning to avoid modification of the original data item.
data = JSON.parse(JSON.stringify(data));
if (!data.expansions) {
data.expansions = [];
}
// Expansions are stored in a tree structure.
let obj = findExpansion.call(this, data.parent);
obj.expansions.push(data);
}
|
javascript
|
{
"resource": ""
}
|
q57823
|
sortExpansions
|
train
|
function sortExpansions() {
let impl = function(expansions) {
expansions.sort((a, b) => {
return a.offset - b.offset;
});
for (let i = 0; i < expansions.length; i++) {
impl(expansions[i].expansions);
}
}
impl(_(this).expansions);
}
|
javascript
|
{
"resource": ""
}
|
q57824
|
calculateExpansions
|
train
|
function calculateExpansions() {
let impl = function(expansions, parentStart, parentLevel) {
expansions.forEach((expansion, index) => {
expansion._level = parentLevel;
// We need to calculate the start position of this expansion. The start
// position isn't just the offset of the item relative to the parent, but
// also takes into account expanded items above it.
//
// One easy way to do this is to just check the previous item and get its end index.
// We fetch the one on the same level not above or below. That should in theory
// already have a start/end relative to the parent. If there isn't a previous sibling
// then we will take the parent start value. Add onto this the offset for the item
// and we've got our starting value.
//
// eg.
// Item 1 <-- start 0, end 0
// Item 2 <-- start 2, end 8
// Item 2.1 <-- start 3, end 3
// Item 2.1.1
// Item 2.2
// Item 2.3 <-- start 6, end 6
// Item 2.3.1
// Item 2.4 <-- start 8, end 8
// Item 2.4.1
// Item 3
// Item 4 <-- start 11, end 12
// Item 4.1
// Item 4.2
let start, end;
let prevSibling = expansions[index - 1];
if (prevSibling) {
start = prevSibling._end + 1 + (expansion.offset - prevSibling.offset);
} else {
start = parentStart + 1 + expansion.offset;
}
expansion._start = start;
// To calculate the ending, we recursively add the children
// for this expansion, and that will be added to the start value.
let totalChildren = expansion.children;
forEachExpansion(expansion.expansions, (expansion) => {
totalChildren += expansion.children;
});
// We add the children and substract one. We subtract one because
// the start is one of the children.
expansion._end = expansion._start + totalChildren - 1;
// Repeat this recursively for all of the nested expansions.
// The nested expansions will have a relative start to this
// expansion.
impl(expansion.expansions, expansion._start, parentLevel + 1);
});
}
impl(_(this).expansions, -1, 0);
}
|
javascript
|
{
"resource": ""
}
|
q57825
|
buildRequest
|
train
|
function buildRequest(scrollPos, viewport) {
// Variables
let queries = [];
let requestedTotal = 0;
let expanded = _(this).expansions;
sortExpansions.call(this);
calculateExpansions.call(this);
// One-dimensional collision detection.
// It checks to see if start/end are both either before
// the viewport, and after. If it's not before or after, it's colliding.
let inViewPort = function(v1, v2, e1, e2) {
return !((e1 < v1 && e2 < v1) || (e1 > v2 && e2 > v2));
};
let calculateExpansionQueries = function(expansions, parentQuery) {
expansions.forEach((e) => {
if (inViewPort(scrollPos, scrollPos + viewport, e._start, e._end)) {
// We want to find out how many items for this expansion are
// visible in the view port. To do this we find the first item that's
// visible, the last item that's visible, subtract them and cap it to the viewport size.
let start = Math.max(scrollPos, e._start);
let end = Math.min(scrollPos + viewport - 1, e._end);
let visible = Math.max(0, Math.min(end - start + 1, viewport));
if (parentQuery) {
// If there are nested children visible, we need to subtract
// this from the parent. Note that visible also includes any expanded
// children nested further because we're using the _start and _end
// values we've already calculated.
parentQuery.limit -= visible;
if (scrollPos > e._start) {
let notVisible = (e._end - e._start + 1) - visible;
if (notVisible > 0) {
parentQuery.offset -= notVisible;
}
}
}
// This query object is what's given to the end user.
// The parent represents who we want the children of.
// The offset is based on how much we've scrolled past the beginning.
// The limit is total items that are visible in the viewport.
let query = {
parent: e.id,
offset: scrollPos > e._start? scrollPos - e._start : 0,
limit: Math.min(visible, viewport)
};
queries.push(query);
calculateExpansionQueries(e.expansions, query);
} else if (scrollPos > e._end && parentQuery) {
// If we've completely scrolled past this object, just substract all of its expanded children from the parent offset.
parentQuery.offset -= (e._end - e._start + 1);
}
});
};
calculateExpansionQueries(_(this).expansions);
return queries;
}
|
javascript
|
{
"resource": ""
}
|
q57826
|
BuildHead
|
train
|
function BuildHead(metaObject = {}) {
const metaCopy = Object.assign({}, metaObject);
let finalString = "";
if (metaCopy.title) {
finalString += `<title>${metaCopy.title}</title>`;
}
if (metaCopy.meta) {
throw new Error("WARNING - DEPRECATED: It looks like you're using the old meta object, please migrate to the new one");
}
if (metaCopy.metas) {
for (let index = 0; index < metaCopy.metas.length; index++) {
const headItem = metaCopy.metas[index];
const processedItem = ProcessMetaItem(headItem);
if (processedItem !== undefined) {
finalString += processedItem;
}
}
}
if (metaCopy.scripts) {
for (let index = 0; index < metaCopy.scripts.length; index++) {
const headItem = metaCopy.scripts[index];
const processedItem = ProcessScriptItem(headItem);
if (processedItem !== undefined) {
finalString += processedItem;
}
}
}
if (metaCopy.styles) {
for (let index = 0; index < metaCopy.styles.length; index++) {
const headItem = metaCopy.styles[index];
const processedItem = ProcessStyleItem(headItem);
if (processedItem !== undefined) {
finalString += processedItem;
}
}
}
if (metaCopy.structuredData) {
finalString += `<script type="application/ld+json">${JSON.stringify(metaCopy.structuredData)}</script>`;
}
return finalString;
}
|
javascript
|
{
"resource": ""
}
|
q57827
|
findItemInDataForExpansion
|
train
|
function findItemInDataForExpansion (label) {
for (let i = 0; i < data.length; i++) {
if (data[i].label === label) {
let item = data[i];
let offset = data.filter(d => d.parent === item.parent).findIndex(d => d.id === item.id);
return {
parent: item.parent,
id: item.id,
children: item.children,
offset: offset
};
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57828
|
onDataFetch
|
train
|
function onDataFetch(query, resolve) {
let output = [];
query.forEach(function(query) {
let filteredItems = data.filter(function(obj) {
return obj.parent === query.parent;
});
output.push({
parent: query.parent,
items: filteredItems.splice(query.offset, query.limit)
});
});
resolve(JSON.parse(JSON.stringify(output)));
}
|
javascript
|
{
"resource": ""
}
|
q57829
|
EmberAddon
|
train
|
function EmberAddon() {
var args = [];
var options = {};
console.log("Addon init")
for (var i = 0, l = arguments.length; i < l; i++) {
args.push(arguments[i]);
}
if (args.length === 1) {
options = args[0];
} else if (args.length > 1) {
args.reverse();
options = defaults.apply(null, args);
}
process.env.EMBER_ADDON_ENV = process.env.EMBER_ADDON_ENV || 'development';
this.appConstructor(defaults(options, {
name: 'dummy',
configPath: './tests/dummy/config/environment',
trees: {
app: 'tests/dummy/app',
styles: 'tests/dummy/app/styles',
templates: 'tests/dummy/app/templates',
public: 'tests/dummy/public',
tests: new Funnel('tests', {
exclude: [ /^dummy/ ]
})
},
jshintrc: {
tests: './tests',
app: './tests/dummy'
},
}));
}
|
javascript
|
{
"resource": ""
}
|
q57830
|
Sprite
|
train
|
function Sprite(texture)
{
DisplayObjectContainer.call(this);
/**
* The anchor sets the origin point of the texture.
* The default is 0,0 this means the textures origin is the top left
* Setting than anchor to 0.5,0.5 means the textures origin is centered
* Setting the anchor to 1,1 would mean the textures origin points will be the bottom right
*
* @property anchor
* @type Point
*/
this.anchor = new Point();
/**
* The texture that the sprite is using
*
* @property texture
* @type Texture
*/
this.texture = texture;
/**
* The blend mode of sprite.
* currently supports blendModes.NORMAL and blendModes.SCREEN
*
* @property blendMode
* @type Number
*/
this.blendMode = blendModes.NORMAL;
/**
* The width of the sprite (this is initially set by the texture)
*
* @property _width
* @type Number
* @private
*/
this._width = 0;
/**
* The height of the sprite (this is initially set by the texture)
*
* @property _height
* @type Number
* @private
*/
this._height = 0;
if(texture.baseTexture.hasLoaded)
{
this.updateFrame = true;
}
else
{
var that = this;
this.texture.addEventListener( 'update', function () {
that.onTextureUpdate();
});
}
this.renderable = true;
}
|
javascript
|
{
"resource": ""
}
|
q57831
|
Texture
|
train
|
function Texture(baseTexture, frame)
{
EventTarget.call( this );
if(!frame)
{
this.noFrame = true;
frame = new Rectangle(0,0,1,1);
}
if(baseTexture instanceof Texture)
baseTexture = baseTexture.baseTexture;
/**
* The base texture of this texture
*
* @property baseTexture
* @type BaseTexture
*/
this.baseTexture = baseTexture;
/**
* The frame specifies the region of the base texture that this texture uses
*
* @property frame
* @type Rectangle
*/
this.frame = frame;
/**
* The trim point
*
* @property trim
* @type Point
*/
this.trim = new Point();
this.scope = this;
if(baseTexture.hasLoaded)
{
if(this.noFrame)frame = new Rectangle(0,0, baseTexture.width, baseTexture.height);
//console.log(frame)
this.setFrame(frame);
}
else
{
var scope = this;
baseTexture.addEventListener('loaded', function(){ scope.onBaseTextureLoaded(); });
}
}
|
javascript
|
{
"resource": ""
}
|
q57832
|
BaseTexture
|
train
|
function BaseTexture(source, scaleMode)
{
EventTarget.call(this);
/**
* [read-only] The width of the base texture set when the image has loaded
*
* @property width
* @type Number
* @readOnly
*/
this.width = 100;
/**
* [read-only] The height of the base texture set when the image has loaded
*
* @property height
* @type Number
* @readOnly
*/
this.height = 100;
/**
* The scale mode to apply when scaling this texture
* @property scaleMode
* @type PIXI.BaseTexture.SCALE_MODE
* @default PIXI.BaseTexture.SCALE_MODE.LINEAR
*/
this.scaleMode = scaleMode || BaseTexture.SCALE_MODE.DEFAULT;
/**
* [read-only] Describes if the base texture has loaded or not
*
* @property hasLoaded
* @type Boolean
* @readOnly
*/
this.hasLoaded = false;
/**
* The source that is loaded to create the texture
*
* @property source
* @type Image
*/
this.source = source;
if(!source)return;
if('complete' in this.source)
{
if(this.source.complete)
{
this.hasLoaded = true;
this.width = this.source.width;
this.height = this.source.height;
globals.texturesToUpdate.push(this);
}
else
{
var scope = this;
this.source.onload = function() {
scope.hasLoaded = true;
scope.width = scope.source.width;
scope.height = scope.source.height;
// add it to somewhere...
globals.texturesToUpdate.push(scope);
scope.dispatchEvent( { type: 'loaded', content: scope } );
};
//this.image.src = imageUrl;
}
}
else
{
this.hasLoaded = true;
this.width = this.source.width;
this.height = this.source.height;
globals.texturesToUpdate.push(this);
}
this.imageUrl = null;
this._powerOf2 = false;
}
|
javascript
|
{
"resource": ""
}
|
q57833
|
pointInTriangle
|
train
|
function pointInTriangle(px, py, ax, ay, bx, by, cx, cy)
{
var v0x = cx-ax;
var v0y = cy-ay;
var v1x = bx-ax;
var v1y = by-ay;
var v2x = px-ax;
var v2y = py-ay;
var dot00 = v0x*v0x+v0y*v0y;
var dot01 = v0x*v1x+v0y*v1y;
var dot02 = v0x*v2x+v0y*v2y;
var dot11 = v1x*v1x+v1y*v1y;
var dot12 = v1x*v2x+v1y*v2y;
var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
}
|
javascript
|
{
"resource": ""
}
|
q57834
|
convex
|
train
|
function convex(ax, ay, bx, by, cx, cy, sign)
{
return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign;
}
|
javascript
|
{
"resource": ""
}
|
q57835
|
Circle
|
train
|
function Circle(x, y, radius)
{
/**
* @property x
* @type Number
* @default 0
*/
this.x = x || 0;
/**
* @property y
* @type Number
* @default 0
*/
this.y = y || 0;
/**
* @property radius
* @type Number
* @default 0
*/
this.radius = radius || 0;
}
|
javascript
|
{
"resource": ""
}
|
q57836
|
ImageMock
|
train
|
function ImageMock() {
var _complete = true;
var _width = 0;
var _height = 0;
var _src = '';
var _onLoad = null;
var _loadTimeoutId;
Object.defineProperties(this, {
complete: {
get: function getComplete() {
return _complete;
},
enumerable: true
},
onload: {
get: function getOnload() {
return _onLoad;
},
set: function setOnload(callback) {
_onLoad = callback;
},
enumerable: true
},
width: {
get: function getWidth() {
return _width;
},
enumerable: true
},
height: {
get: function getHeight() {
return _height;
},
enumerable: true
},
src: {
get: function getSrc() {
return _src;
},
set: function setSrc(src) {
_complete = false;
platform.global.clearTimeout(_loadTimeoutId);
if (src) {
_loadTimeoutId = platform.global.setTimeout(function () {
_width = 10;
_height = 10;
_complete = true;
if (this.onload) this.onload(/*no event used*/);
}.bind(this), 200);
_src = src;
} else {
_width = 0;
_height = 0;
_src = '';
}
},
enumerable: true
}
});
}
|
javascript
|
{
"resource": ""
}
|
q57837
|
ignore
|
train
|
function ignore(fileMeta, opts) {
if (typeof opts.ignore === 'function') {
return opts.ignore(fileMeta, opts);
}
if (typeof opts.ignore === 'string' || Array.isArray(opts.ignore)) {
return micromatch.any(fileMeta.sourceValue, opts.ignore);
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q57838
|
getFileMeta
|
train
|
function getFileMeta(dirname, sourceInputFile, value, opts) {
const parsedUrl = url.parse(value, true);
const filename = decodeURI(parsedUrl.pathname);
const pathname = path.resolve(dirname, filename);
const params = parsedUrl.search || '';
const hash = parsedUrl.hash || '';
// path between the basePath and the filename
const basePath = findBasePath(opts.basePath, pathname);
if (!basePath) {
throw Error(`"basePath" not found in ${pathname}`);
}
const ext = path.extname(pathname);
const fileMeta = {
sourceInputFile,
sourceValue: value,
filename,
// the absolute path without the #hash param and ?query
absolutePath: pathname,
fullName: path.basename(pathname),
path: path.relative(basePath, path.dirname(pathname)),
// name without extension
name: path.basename(pathname, ext),
// extension without the '.'
ext: ext.slice(1),
query: params + hash,
qparams: params.length > 0 ? params.slice(1) : '',
qhash: hash.length > 0 ? hash.slice(1) : '',
basePath
};
return fileMeta;
}
|
javascript
|
{
"resource": ""
}
|
q57839
|
processUrl
|
train
|
function processUrl(result, decl, node, opts) {
// ignore from the css file by `!`
if (node.value.indexOf('!') === 0) {
node.value = node.value.slice(1);
return Promise.resolve();
}
if (
node.value.indexOf('/') === 0 ||
node.value.indexOf('data:') === 0 ||
node.value.indexOf('#') === 0 ||
/^[a-z]+:\/\//.test(node.value)
) {
return Promise.resolve();
}
/**
* dirname of the read file css
* @type {String}
*/
const dirname = path.dirname(decl.source.input.file);
let fileMeta = getFileMeta(
dirname,
decl.source.input.file,
node.value,
opts
);
// ignore from the fileMeta config
if (ignore(fileMeta, opts)) {
return Promise.resolve();
}
return copy(
fileMeta.absolutePath,
() => fileMeta.resultAbsolutePath,
(contents, isModified) => {
fileMeta.contents = contents;
return Promise.resolve(
isModified ? opts.transform(fileMeta) : fileMeta
)
.then(fileMetaTransformed => {
fileMetaTransformed.hash = opts.hashFunction(
fileMetaTransformed.contents
);
let tpl = opts.template;
if (typeof tpl === 'function') {
tpl = tpl(fileMetaTransformed);
} else {
tags.forEach(tag => {
tpl = tpl.replace(
'[' + tag + ']',
fileMetaTransformed[tag] || opts[tag] || ''
);
});
}
const resultUrl = url.parse(tpl);
fileMetaTransformed.resultAbsolutePath = decodeURI(
path.resolve(
opts.dest,
resultUrl.pathname
)
);
fileMetaTransformed.extra = (resultUrl.search || '') +
(resultUrl.hash || '');
return fileMetaTransformed;
})
.then(fileMetaTransformed => fileMetaTransformed.contents);
}
).then(() => {
const destPath = defineCSSDestPath(
dirname,
fileMeta.basePath,
result,
opts
);
node.value = path
.relative(destPath, fileMeta.resultAbsolutePath)
.split('\\')
.join('/') + fileMeta.extra;
});
}
|
javascript
|
{
"resource": ""
}
|
q57840
|
processDecl
|
train
|
function processDecl(result, decl, opts) {
const promises = [];
decl.value = valueParser(decl.value).walk(node => {
if (
node.type !== 'function' ||
node.value !== 'url' ||
node.nodes.length === 0
) {
return;
}
const promise = Promise.resolve()
.then(() => processUrl(result, decl, node.nodes[0], opts))
.catch(err => {
decl.warn(result, err.message);
});
promises.push(promise);
});
return Promise.all(promises).then(() => decl);
}
|
javascript
|
{
"resource": ""
}
|
q57841
|
init
|
train
|
function init(userOpts = {}) {
const opts = Object.assign(
{
template: '[hash].[ext][query]',
preservePath: false,
hashFunction(contents) {
return crypto
.createHash('sha1')
.update(contents)
.digest('hex')
.substr(0, 16);
},
transform(fileMeta) {
return fileMeta;
},
ignore: []
},
userOpts
);
return (style, result) => {
if (opts.basePath) {
if (typeof opts.basePath === 'string') {
opts.basePath = [path.resolve(opts.basePath)];
} else {
opts.basePath = opts.basePath.map(elem => path.resolve(elem));
}
} else {
opts.basePath = [process.cwd()];
}
if (opts.dest) {
opts.dest = path.resolve(opts.dest);
} else {
throw new Error('Option `dest` is required in postcss-copy');
}
const promises = [];
style.walkDecls(decl => {
if (decl.value && decl.value.indexOf('url(') > -1) {
promises.push(processDecl(result, decl, opts));
}
});
return Promise.all(promises).then(decls =>
decls.forEach(decl => {
decl.value = String(decl.value);
})
);
};
}
|
javascript
|
{
"resource": ""
}
|
q57842
|
Stage
|
train
|
function Stage(backgroundColor)
{
DisplayObjectContainer.call(this);
/**
* [read-only] Current transform of the object based on world (parent) factors
*
* @property worldTransform
* @type Mat3
* @readOnly
* @private
*/
this.worldTransform = mat3.create();
/**
* Whether or not the stage is interactive
*
* @property interactive
* @type Boolean
*/
this.interactive = true;
/**
* The interaction manage for this stage, manages all interactive activity on the stage
*
* @property interactive
* @type InteractionManager
*/
this.interactionManager = new InteractionManager(this);
/**
* Whether the stage is dirty and needs to have interactions updated
*
* @property dirty
* @type Boolean
* @private
*/
this.dirty = true;
this.__childrenAdded = [];
this.__childrenRemoved = [];
//the stage is it's own stage
this.stage = this;
//optimize hit detection a bit
this.stage.hitArea = new Rectangle(0,0,100000, 100000);
this.setBackgroundColor(backgroundColor);
this.worldVisible = true;
}
|
javascript
|
{
"resource": ""
}
|
q57843
|
AtlasLoader
|
train
|
function AtlasLoader(url, crossorigin) {
EventTarget.call(this);
this.url = url;
this.baseUrl = url.replace(/[^\/]*$/, '');
this.crossorigin = crossorigin;
this.loaded = false;
}
|
javascript
|
{
"resource": ""
}
|
q57844
|
addIdToSnapshot
|
train
|
function addIdToSnapshot(snapshot) {
var record = snapshot.record;
record.get('store').updateId(record, { id: generateUniqueId() });
return record._createSnapshot();
}
|
javascript
|
{
"resource": ""
}
|
q57845
|
assign
|
train
|
function assign(node, token, clone) {
copy(node, token, clone);
ensureNodes(node, clone);
if (token.constructor && token.constructor.name === 'Token') {
copy(node, token.constructor.prototype, clone);
}
}
|
javascript
|
{
"resource": ""
}
|
q57846
|
train
|
function(a, b) {
let aVal = a[sortField];
let bVal = b[sortField];
return (!aVal && bVal) || (aVal < bVal) ? -1 : (aVal && !bVal) || (aVal > bVal) ? 1 : 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q57847
|
containsRelationships
|
train
|
function containsRelationships(query) {
let contains = false;
if (query.predicate instanceof SimplePredicate || query.predicate instanceof StringPredicate || query.predicate instanceof DatePredicate) {
contains = Information.parseAttributePath(query.predicate.attributePath).length > 1;
}
if (query.predicate instanceof DetailPredicate) {
return true;
}
if (query.predicate instanceof ComplexPredicate) {
query.predicate.predicates.forEach((predicate) => {
if (containsRelationships({ predicate })) {
contains = true;
}
});
}
if (query.order) {
for (let i = 0; i < query.order.length; i++) {
let attributePath = query.order.attribute(i).name;
if (Information.parseAttributePath(attributePath).length > 1) {
contains = true;
}
}
}
return contains;
}
|
javascript
|
{
"resource": ""
}
|
q57848
|
filterOptions
|
train
|
function filterOptions(options, filter, substitutions) {
// If the filter is blank, return the full list of Options.
if (!filter) {
return options;
}
var cleanFilter = cleanUpText(filter, substitutions);
return options
// Filter out undefined or null Options.
.filter(function (_ref) {
var label = _ref.label,
value = _ref.value;
return label != null && value != null;
})
// Create a {score, Option} pair for each Option based on its label's
// similarity to the filter text.
.map(function (option) {
return {
option: option,
score: typeaheadSimilarity(cleanUpText(option.label, substitutions), cleanFilter)
};
})
// Only include matches of the entire substring, with a slight
// affordance for transposition or extra characters.
.filter(function (pair) {
return pair.score >= cleanFilter.length - 2;
})
// Sort 'em by order of their score.
.sort(function (a, b) {
return b.score - a.score;
})
// …and grab the original Options back from their pairs.
.map(function (pair) {
return pair.option;
});
}
|
javascript
|
{
"resource": ""
}
|
q57849
|
typeaheadSimilarity
|
train
|
function typeaheadSimilarity(a, b) {
var aLength = a.length;
var bLength = b.length;
var table = [];
if (!aLength || !bLength) {
return 0;
}
// Ensure `a` isn't shorter than `b`.
if (aLength < bLength) {
var _ref2 = [b, a];
a = _ref2[0];
b = _ref2[1];
}
// Early exit if `a` includes `b`; these will be scored higher than any
// other options with the same `b` (filter string), with a preference for
// shorter `a` strings (option labels).
if (a.indexOf(b) !== -1) {
return bLength + 1 / aLength;
}
// Initialize the table axes:
//
// 0 0 0 0 ... bLength
// 0
// 0
//
// ...
//
// aLength
//
for (var x = 0; x <= aLength; ++x) {
table[x] = [0];
}
for (var y = 0; y <= bLength; ++y) {
table[0][y] = 0;
}
// Populate the rest of the table with a dynamic programming algorithm.
for (var _x = 1; _x <= aLength; ++_x) {
for (var _y = 1; _y <= bLength; ++_y) {
table[_x][_y] = a[_x - 1] === b[_y - 1] ? 1 + table[_x - 1][_y - 1] : Math.max(table[_x][_y - 1], table[_x - 1][_y]);
}
}
return table[aLength][bLength];
}
|
javascript
|
{
"resource": ""
}
|
q57850
|
fullStringDistance
|
train
|
function fullStringDistance(a, b) {
var aLength = a.length;
var bLength = b.length;
var table = [];
if (!aLength) {
return bLength;
}
if (!bLength) {
return aLength;
}
// Initialize the table axes:
//
// 0 1 2 3 4 ... bLength
// 1
// 2
//
// ...
//
// aLength
//
for (var x = 0; x <= aLength; ++x) {
table[x] = [x];
}
for (var y = 0; y <= bLength; ++y) {
table[0][y] = y;
}
// Populate the rest of the table with a dynamic programming algorithm.
for (var _x2 = 1; _x2 <= aLength; ++_x2) {
for (var _y2 = 1; _y2 <= bLength; ++_y2) {
table[_x2][_y2] = a[_x2 - 1] === b[_y2 - 1] ? table[_x2 - 1][_y2 - 1] : 1 + Math.min(table[_x2 - 1][_y2], // Substitution,
table[_x2][_y2 - 1], // insertion,
table[_x2 - 1][_y2 - 1]); // and deletion.
}
}
return table[aLength][bLength];
}
|
javascript
|
{
"resource": ""
}
|
q57851
|
cleanUpText
|
train
|
function cleanUpText(input, substitutions) {
if (!input) {
return '';
}
// Uppercase and remove all non-alphanumeric, non-accented characters.
// Also remove underscores.
input = input.toUpperCase().replace(/((?=[^\u00E0-\u00FC])\W)|_/g, '');
if (!substitutions) {
return input;
}
var safeSubstitutions = substitutions; // For Flow.
// Replace all strings in `safeSubstitutions` with their standardized
// counterparts.
return Object.keys(safeSubstitutions).reduce(function (output, substitution) {
var unsubbed = new RegExp(substitution, 'g');
return output.replace(unsubbed, safeSubstitutions[substitution]);
}, input);
}
|
javascript
|
{
"resource": ""
}
|
q57852
|
train
|
function(red, green, blue, model) {
red = red / 255;
green = green / 255;
blue = blue / 255;
var r = red > 0.04045 ? Math.pow(((red + 0.055) / 1.055), 2.4000000953674316) : red / 12.92;
var g = green > 0.04045 ? Math.pow(((green + 0.055) / 1.055), 2.4000000953674316) : green / 12.92;
var b = blue > 0.04045 ? Math.pow(((blue + 0.055) / 1.055), 2.4000000953674316) : blue / 12.92;
var x = r * 0.664511 + g * 0.154324 + b * 0.162028;
var y = r * 0.283881 + g * 0.668433 + b * 0.047685;
var z = r * 8.8E-5 + g * 0.07231 + b * 0.986039;
var xy = [x / (x + y + z), y / (x + y + z)];
if (isNaN(xy[0])) {
xy[0] = 0.0;
}
if (isNaN(xy[1])) {
xy[1] = 0.0;
}
var colorPoints = colorPointsForModel(model);
var inReachOfLamps = checkPointInLampsReach(xy, colorPoints);
if (!inReachOfLamps) {
var pAB = getClosestPointToPoints(colorPoints[0], colorPoints[1], xy);
var pAC = getClosestPointToPoints(colorPoints[2], colorPoints[0], xy);
var pBC = getClosestPointToPoints(colorPoints[1], colorPoints[2], xy);
var dAB = getDistanceBetweenTwoPoints(xy, pAB);
var dAC = getDistanceBetweenTwoPoints(xy, pAC);
var dBC = getDistanceBetweenTwoPoints(xy, pBC);
var lowest = dAB;
var closestPoint = pAB;
if (dAC < dAB) {
lowest = dAC;
closestPoint = pAC;
}
if (dBC < lowest) {
closestPoint = pBC;
}
xy[0] = closestPoint[0];
xy[1] = closestPoint[1];
}
xy[0] = precision(xy[0]);
xy[1] = precision(xy[1]);
return xy;
}
|
javascript
|
{
"resource": ""
}
|
|
q57853
|
isInt
|
train
|
function isInt(value) {
if (isNaN(value) || exports.isString(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
}
|
javascript
|
{
"resource": ""
}
|
q57854
|
isEmpty
|
train
|
function isEmpty(obj) {
if (isTrueEmpty(obj)) return true;
if (exports.isRegExp(obj)) {
return false;
} else if (exports.isDate(obj)) {
return false;
} else if (exports.isError(obj)) {
return false;
} else if (exports.isArray(obj)) {
return obj.length === 0;
} else if (exports.isString(obj)) {
return obj.length === 0;
} else if (exports.isNumber(obj)) {
return obj === 0;
} else if (exports.isBoolean(obj)) {
return !obj;
} else if (exports.isObject(obj)) {
for (const key in obj) {
return false && key; // only for eslint
}
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q57855
|
isExist
|
train
|
function isExist(dir) {
dir = path.normalize(dir);
try {
fs.accessSync(dir, fs.R_OK);
return true;
} catch (e) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q57856
|
isFile
|
train
|
function isFile(filePath) {
if (!isExist(filePath)) return false;
try {
const stat = fs.statSync(filePath);
return stat.isFile();
} catch (e) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q57857
|
isDirectory
|
train
|
function isDirectory(filePath) {
if (!isExist(filePath)) return false;
try {
const stat = fs.statSync(filePath);
return stat.isDirectory();
} catch (e) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q57858
|
chmod
|
train
|
function chmod(p, mode) {
try {
fs.chmodSync(p, mode);
return true;
} catch (e) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q57859
|
getdirFiles
|
train
|
function getdirFiles(dir, prefix = '') {
dir = path.normalize(dir);
if (!fs.existsSync(dir)) return [];
const files = fs.readdirSync(dir);
let result = [];
files.forEach(item => {
const currentDir = path.join(dir, item);
const stat = fs.statSync(currentDir);
if (stat.isFile()) {
result.push(path.join(prefix, item));
} else if (stat.isDirectory()) {
const cFiles = getdirFiles(currentDir, path.join(prefix, item));
result = result.concat(cFiles);
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q57860
|
rmdir
|
train
|
function rmdir(p, reserve) {
if (!isDirectory(p)) return Promise.resolve();
return fsReaddir(p).then(files => {
const promises = files.map(item => {
const filepath = path.join(p, item);
if (isDirectory(filepath)) return rmdir(filepath, false);
return fsUnlink(filepath);
});
return Promise.all(promises).then(() => {
if (!reserve) return fsRmdir(p);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57861
|
nodeModulePaths
|
train
|
function nodeModulePaths(from) {
// guarantee that 'from' is absolute.
from = path.resolve(from);
// note: this approach *only* works when the path is guaranteed
// to be absolute. Doing a fully-edge-case-correct path.split
// that works on both Windows and Posix is non-trivial.
var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//;
var paths = [];
var parts = from.split(splitRe);
for (var tip = parts.length - 1; tip >= 0; tip--) {
// don't search in .../node_modules/node_modules
if (parts[tip] === 'node_modules') {
continue;
}
var dir = parts.slice(0, tip + 1).concat('node_modules').join(path.sep);
paths.push(dir);
}
return paths;
}
|
javascript
|
{
"resource": ""
}
|
q57862
|
createStatEntry
|
train
|
function createStatEntry(file, fullpath, callback) {
fs.lstat(fullpath, function (err, stat) {
var entry = {
name: file
};
if (err) {
entry.err = err;
return callback(entry);
} else {
entry.size = stat.size;
entry.mtime = stat.mtime.valueOf();
if (stat.isDirectory()) {
entry.mime = "inode/directory";
} else if (stat.isBlockDevice()) entry.mime = "inode/blockdevice";
else if (stat.isCharacterDevice()) entry.mime = "inode/chardevice";
else if (stat.isSymbolicLink()) entry.mime = "inode/symlink";
else if (stat.isFIFO()) entry.mime = "inode/fifo";
else if (stat.isSocket()) entry.mime = "inode/socket";
else {
entry.mime = getMime(fullpath);
}
if (!stat.isSymbolicLink()) {
return callback(entry);
}
fs.readlink(fullpath, function (err, link) {
if (entry.name == link) {
entry.linkStatErr = "ELOOP: recursive symlink";
return callback(entry);
}
if (err) {
entry.linkErr = err.stack;
return callback(entry);
}
entry.link = link;
resolvePath(pathResolve(dirname(fullpath), link), {alreadyRooted: true}, function (err, newpath) {
if (err) {
entry.linkStatErr = err;
return callback(entry);
}
createStatEntry(basename(newpath), newpath, function (linkStat) {
entry.linkStat = linkStat;
linkStat.fullPath = newpath.substr(base.length) || "/";
return callback(entry);
});
});
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q57863
|
remove
|
train
|
function remove(path, fn, callback) {
var meta = {};
resolvePath(path, function (err, realpath) {
if (err) return callback(err);
fn(realpath, function (err) {
if (err) return callback(err);
// Remove metadata
resolvePath(WSMETAPATH + path, function (err, realpath) {
if (err) return callback(null, meta);
fn(realpath, function(){
return callback(null, meta);
});
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57864
|
resolve
|
train
|
function resolve() {
resolvePath(path, function (err, _resolvedPath) {
if (err) {
if (err.code !== "ENOENT") {
return error(err);
}
// If checkSymlinks is on we'll get an ENOENT when creating a new file.
// In that case, just resolve the parent path and go from there.
resolvePath(dirname(path), function (err, dir) {
if (err) return error(err);
resolvedPath = join(dir, basename(path));
createTempFile();
});
return;
}
resolvedPath = _resolvedPath;
createTempFile();
});
}
|
javascript
|
{
"resource": ""
}
|
q57865
|
consumeStream
|
train
|
function consumeStream(stream, callback) {
var chunks = [];
stream.on("data", onData);
stream.on("end", onEnd);
stream.on("error", onError);
function onData(chunk) {
chunks.push(chunk);
}
function onEnd() {
cleanup();
callback(null, chunks.join(""));
}
function onError(err) {
cleanup();
callback(err);
}
function cleanup() {
stream.removeListener("data", onData);
stream.removeListener("end", onEnd);
stream.removeListener("error", onError);
}
}
|
javascript
|
{
"resource": ""
}
|
q57866
|
evaluate
|
train
|
function evaluate(code) {
var exports = {};
var module = { exports: exports };
vm.runInNewContext(code, {
require: require,
exports: exports,
module: module,
console: console,
global: global,
process: process,
Buffer: Buffer,
setTimeout: setTimeout,
clearTimeout: clearTimeout,
setInterval: setInterval,
clearInterval: clearInterval
}, "dynamic-" + Date.now().toString(36), true);
return module.exports;
}
|
javascript
|
{
"resource": ""
}
|
q57867
|
calcEtag
|
train
|
function calcEtag(stat) {
return (stat.isFile() ? '': 'W/') + '"' + (stat.ino || 0).toString(36) + "-" + stat.size.toString(36) + "-" + stat.mtime.valueOf().toString(36) + '"';
}
|
javascript
|
{
"resource": ""
}
|
q57868
|
parse_style_json_object
|
train
|
function parse_style_json_object(text, options)
{
// remove multiline comments
text = text.replace(/\/\*([\s\S]*?)\*\//g, '')
// ignore curly braces for now.
// maybe support curly braces along with tabulation in future
text = text.replace(/[\{\}]/g, '')
const lines = text.split('\n')
// helper class for dealing with tabulation
const tabulator = new Tabulator(Tabulator.determine_tabulation(lines))
// parse text into JSON object
let style_json = parse_style_class(tabulator.extract_tabulation(lines), [])
// expand CSS shorthand properties
// (e.g. `margin: 1px` -> `margin-left: 1px; ...`)
if (options.expand)
{
style_json = style_builder.build(style_json)
}
// expand "modifier" style classes
// (which can override some of the expanded shorthand CSS properties)
return expand_modifier_style_classes(style_json)
}
|
javascript
|
{
"resource": ""
}
|
q57869
|
split_into_style_lines_and_children_lines
|
train
|
function split_into_style_lines_and_children_lines(lines)
{
// get this node style lines
const style_lines = lines.filter(function(line)
{
// styles always have indentation of 1
if (line.tabs !== 1)
{
return false
}
// detect generic css style line (skip modifier classes and media queries)
const colon_index = line.line.indexOf(':')
// is not a modifier class
return !starts_with(line.line, '&')
// is not a media query style class name declaration
&& !starts_with(line.line, '@media')
// is not a keyframes style class name declaration
&& !starts_with(line.line, '@keyframes')
// has a colon
&& colon_index >= 0
// is not a state class (e.g. :hover) name declaration
&& colon_index !== 0
// is not a yaml-style class name declaration
&& colon_index < line.line.length - 1
})
// get children nodes' lines
const children_lines = lines.filter(line => style_lines.indexOf(line) < 0)
// reduce tabulation for this child node's (or these child nodes') child nodes' lines
children_lines.forEach(line => line.tabs--)
return { style_lines, children_lines}
}
|
javascript
|
{
"resource": ""
}
|
q57870
|
parse_node_name
|
train
|
function parse_node_name(name)
{
// is it a "modifier" style class
let is_a_modifier = false
// detect modifier style classes
if (starts_with(name, '&'))
{
name = name.substring('&'.length)
is_a_modifier = true
}
// support old-school CSS syntax
if (starts_with(name, '.'))
{
name = name.substring('.'.length)
}
// if there is a trailing colon in the style class name - trim it
// (Python people with yaml-alike syntax)
if (ends_with(name, ':'))
{
name = name.substring(0, name.length - ':'.length)
// throw new Error(`Remove the trailing colon at line: ${original_line}`)
}
return { name, is_a_modifier }
}
|
javascript
|
{
"resource": ""
}
|
q57871
|
parse_children
|
train
|
function parse_children(lines, parent_node_names)
{
// preprocess the lines (filter out comments, blank lines, etc)
lines = filter_lines_for_parsing(lines)
// return empty object if there are no lines to parse
if (lines.length === 0)
{
return {}
}
// parse each child node's lines
return split_lines_by_child_nodes(lines).map(function(lines)
{
// the first line is this child node's name (or names)
const declaration_line = lines.shift()
// check for excessive indentation of the first child style class
if (declaration_line.tabs !== 0)
{
throw new Error(`Excessive indentation (${declaration_line.tabs} more "tabs" than needed) at line ${declaration_line.index}: "${declaration_line.original_line}"`)
}
// style class name declaration
const declaration = declaration_line.line
// child nodes' names
const names = declaration.split(',').map(name => name.trim())
// style class nesting validation
validate_child_style_class_types(parent_node_names, names)
// parse own CSS styles and recursively parse all child nodes
const style_json = parse_style_class(lines, names)
// generate style json for this child node (or child nodes)
return names.map(function(node_declaration)
{
// parse this child node name
const { name, is_a_modifier } = parse_node_name(node_declaration)
// clone the style JSON object for this child node
const json = extend({}, style_json)
// set the modifier flag if it's the case
if (is_a_modifier)
{
json._is_a_modifier = true
}
// this child node's style JSON object
return { name, json }
})
})
// convert an array of arrays to a flat array
.reduce(function(array, child_array)
{
return array.concat(child_array);
},
[])
// combine all the child nodes into a single JSON object
.reduce(function(nodes, node)
{
// if style already exists for this child node, extend it
if (nodes[node.name])
{
extend(nodes[node.name], node.json)
}
else
{
nodes[node.name] = node.json
}
return nodes
},
{})
}
|
javascript
|
{
"resource": ""
}
|
q57872
|
filter_lines_for_parsing
|
train
|
function filter_lines_for_parsing(lines)
{
// filter out blank lines
lines = lines.filter(line => !is_blank(line.line))
lines.forEach(function(line)
{
// remove single line comments
line.line = line.line.replace(/^\s*\/\/.*/, '')
// remove any trailing whitespace
line.line = line.line.trim()
})
return lines
}
|
javascript
|
{
"resource": ""
}
|
q57873
|
split_lines_by_child_nodes
|
train
|
function split_lines_by_child_nodes(lines)
{
// determine lines with indentation = 0 (child node entry lines)
const node_entry_lines = lines.map((line, index) =>
{
return { tabs: line.tabs, index }
})
.filter(line => line.tabs === 0)
.map(line => line.index)
// deduce corresponding child node ending lines
const node_ending_lines = node_entry_lines.map(line_index => line_index - 1)
node_ending_lines.shift()
node_ending_lines.push(lines.length - 1)
// each child node boundaries in terms of starting line index and ending line index
const from_to = zip(node_entry_lines, node_ending_lines)
// now lines are split by child nodes
return from_to.map(from_to => lines.slice(from_to[0], from_to[1] + 1))
}
|
javascript
|
{
"resource": ""
}
|
q57874
|
expand_modifier_style_classes
|
train
|
function expand_modifier_style_classes(node)
{
const style = get_node_style(node)
const pseudo_classes_and_media_queries_and_keyframes = get_node_pseudo_classes_and_media_queries_and_keyframes(node)
const modifiers = Object.keys(node)
// get all modifier style class nodes
.filter(name => typeof(node[name]) === 'object' && node[name]._is_a_modifier)
// for each modifier style class node
modifiers.forEach(function(name)
{
// // delete the modifier flags
// delete node[name]._is_a_modifier
// include parent node's styles and pseudo-classes into the modifier style class node
node[name] = extend({}, style, pseudo_classes_and_media_queries_and_keyframes, node[name])
// expand descendant style class nodes of this modifier
expand_modified_subtree(node, node[name])
})
// for each modifier style class node
modifiers.forEach(function(name)
{
// delete the modifier flags
delete node[name]._is_a_modifier
})
// recurse
Object.keys(node)
// get all style class nodes
.filter(name => typeof(node[name]) === 'object')
// for each style class node
.forEach(function(name)
{
// recurse
expand_modifier_style_classes(node[name])
})
return node
}
|
javascript
|
{
"resource": ""
}
|
q57875
|
get_node_style
|
train
|
function get_node_style(node)
{
return Object.keys(node)
// get all CSS styles of this style class node
.filter(property => typeof(node[property]) !== 'object')
// for each CSS style of this style class node
.reduce(function(style, style_property)
{
style[style_property] = node[style_property]
return style
},
{})
}
|
javascript
|
{
"resource": ""
}
|
q57876
|
get_node_pseudo_classes_and_media_queries_and_keyframes
|
train
|
function get_node_pseudo_classes_and_media_queries_and_keyframes(node)
{
return Object.keys(node)
// get all child style classes this style class node,
// which aren't modifiers and are a pseudoclass or a media query or keyframes
.filter(property => typeof(node[property]) === 'object'
&& (is_pseudo_class(property) || is_media_query(property) || is_keyframes(property))
&& !node[property]._is_a_modifier)
// for each child style class of this style class node
.reduce(function(pseudo_classes_and_media_queries_and_keyframes, name)
{
pseudo_classes_and_media_queries_and_keyframes[name] = node[name]
return pseudo_classes_and_media_queries_and_keyframes
},
{})
}
|
javascript
|
{
"resource": ""
}
|
q57877
|
validate_child_style_class_types
|
train
|
function validate_child_style_class_types(parent_node_names, names)
{
for (let parent of parent_node_names)
{
// if it's a pseudoclass, it can't contain any style classes
if (is_pseudo_class(parent) && not_empty(names))
{
throw new Error(`A style class declaration "${names[0]}" found inside a pseudoclass "${parent}". Pseudoclasses (:hover, etc) can't contain child style classes.`)
}
// if it's a media query style class, it must contain only pseudoclasses
if (is_media_query(parent))
{
const non_pseudoclass = names.filter(x => !is_pseudo_class(x))[0]
if (non_pseudoclass)
{
throw new Error(`A non-pseudoclass "${non_pseudoclass}" found inside a media query style class "${parent}". Media query style classes can only contain pseudoclasses (:hover, etc).`)
}
}
// if it's a keyframes style class, it must contain only keyframe selectors
if (is_keyframes(parent)) {
const non_keyframe_selector = names.filter(x => !is_keyframe_selector(x))[0]
if (non_keyframe_selector)
{
throw new Error(`A non-keyframe-selector "${non_keyframe_selector}" found inside a keyframes style class "${parent}". Keyframes style classes can only contain keyframe selectors (from, 100%, etc).`);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57878
|
parse_style_class
|
train
|
function parse_style_class(lines, node_names)
{
// separate style lines from children lines
const { style_lines, children_lines } = split_into_style_lines_and_children_lines(lines)
// convert style lines info to just text lines
const styles = style_lines.map(line => line.line)
// using this child node's (or these child nodes') style lines
// and this child node's (or these child nodes') child nodes' lines,
// generate this child node's (or these child nodes') style JSON object
// (this is gonna be a recursion)
return parse_node_json(styles, children_lines, node_names)
}
|
javascript
|
{
"resource": ""
}
|
q57879
|
move_up
|
train
|
function move_up(object, upside, new_name)
{
let prefix
if (upside)
{
upside[new_name] = object
prefix = `${new_name}_`
}
else
{
upside = object
prefix = ''
}
for (let key of Object.keys(object))
{
const child_object = object[key]
if (is_object(child_object) && !is_pseudo_class(key) && !is_media_query(key))
{
delete object[key]
move_up(child_object, upside, `${prefix}${key}`)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57880
|
SigningError
|
train
|
function SigningError(cause) {
this.code = 'SigningError';
assert.optionalObject(cause);
var msg = 'error signing request';
var args = (cause ? [cause, msg] : [msg]);
WError.apply(this, args);
}
|
javascript
|
{
"resource": ""
}
|
q57881
|
listAllVms
|
train
|
function listAllVms(cb) {
var limit = undefined;
var offset = params.offset;
var vms = [];
var stop = false;
async.whilst(
function testAllVmsFetched() {
return !stop;
},
listVms,
function doneFetching(fetchErr) {
return cb(fetchErr, vms);
});
function listVms(whilstNext) {
// These options are passed once they are set for the first time
// or they are passed by the client calling listImages()
if (offset) {
params.offset += offset;
} else {
params.offset = 0;
}
if (limit) {
params.limit = limit;
}
self.get(reqOpts, function (listErr, someVms) {
if (listErr) {
stop = true;
return whilstNext(listErr);
}
if (!limit) {
limit = someVms.length;
}
if (!offset) {
offset = someVms.length;
}
if (someVms.length < limit) {
stop = true;
}
// We hit this when we either reached an empty page of
// results or an empty first result
if (!someVms.length) {
stop = true;
return whilstNext();
}
vms = vms.concat(someVms);
return whilstNext();
});
}
}
|
javascript
|
{
"resource": ""
}
|
q57882
|
updateApplication
|
train
|
function updateApplication(uuid, opts, callback) {
assert.string(uuid, 'uuid');
assert.object(opts, 'opts');
return (this.put(sprintf('/applications/%s', uuid), opts, callback));
}
|
javascript
|
{
"resource": ""
}
|
q57883
|
createInstanceAsync
|
train
|
function createInstanceAsync(service_uuid, opts, callback) {
assert.string(service_uuid, 'service_uuid');
if (typeof (opts) === 'function') {
callback = opts;
opts = {};
}
assert.object(opts, 'opts');
assert.func(callback, 'callback');
opts.service_uuid = service_uuid;
return (this.post('/instances?async=true', opts, callback));
}
|
javascript
|
{
"resource": ""
}
|
q57884
|
listInstances
|
train
|
function listInstances(search_opts, callback) {
if (arguments.length === 1) {
callback = search_opts;
search_opts = {};
}
var uri = '/instances?' + qs.stringify(search_opts);
return (this.get(uri, callback));
}
|
javascript
|
{
"resource": ""
}
|
q57885
|
reprovisionInstance
|
train
|
function reprovisionInstance(uuid, image_uuid, callback) {
assert.string(uuid, 'uuid');
assert.string(image_uuid, 'image_uuid');
var opts = {};
opts.image_uuid = image_uuid;
return (this.put(sprintf('/instances/%s/upgrade', uuid), opts, callback));
}
|
javascript
|
{
"resource": ""
}
|
q57886
|
prettify
|
train
|
function prettify (luaCode) {
const lines = luaCode
.split("\n")
.map(line => line.trim());
const { code } = lines.reduce((result, line) => {
const { code, indentation } = result;
let currentIndentation = indentation;
let nextLineIndentation = indentation;
if (indentIncrease.some(entry => entry(line))) {
nextLineIndentation++;
}
if (indentDecrease.some(entry => entry(line))) {
currentIndentation--;
nextLineIndentation--;
}
code.push(line && line.padStart(line.length + currentIndentation * 2) || line);
return {
code,
indentation: Math.max(0, nextLineIndentation)
};
}, {
code: [],
indentation: 0
});
return code.join("\n");
}
|
javascript
|
{
"resource": ""
}
|
q57887
|
buildOptions
|
train
|
function buildOptions(i) {
var index = (i + 1);
var isCurrent = i === current;
// Options for each text, arrow and image, using the base options and the index
var text = extend({}, optionsText, {paths: '#jelly-text-' + index + ' path'});
var arrow = extend({}, optionsArrow, {paths: '#jelly-arrow-' + index});
var image = extend({}, isCurrent ? optionsImage : optionsCircle, {image: 'img/image-' + index + '.jpg'});
// If not the current item, set circle in the position defined, hide text, and hide arrow
if (!isCurrent) {
extend(image, circlePositions[i]);
extend(text, {hidden: true});
extend(arrow, {hidden: true});
}
// Push all of these to the options array
options.push(text);
options.push(arrow);
options.push(image);
}
|
javascript
|
{
"resource": ""
}
|
q57888
|
applyBinds
|
train
|
function applyBinds(fns, instance) {
var i,
current;
for (i = fns.length - 1; i >= 0; i -= 1) {
current = instance[fns[i]];
instance[fns[i]] = bind(current, instance);
}
}
|
javascript
|
{
"resource": ""
}
|
q57889
|
doBind
|
train
|
function doBind(func) {
/*jshint validthis:true*/
var args = toArray(arguments),
bound;
if (this && !func[$wrapped] && this.$static && this.$static[$class]) {
func = wrapMethod(null, func, this.$self || this.$static);
}
args.splice(1, 0, this);
bound = bind.apply(func, args);
return bound;
}
|
javascript
|
{
"resource": ""
}
|
q57890
|
optimizeConstructor
|
train
|
function optimizeConstructor(constructor) {
var tmp = constructor[$class],
canOptimizeConst,
newConstructor,
parentInitialize;
// Check if we can optimize the constructor
if (tmp.efficient) {
canOptimizeConst = constructor.$canOptimizeConst;
delete constructor.$canOptimizeConst;
if (canOptimizeConst && !tmp.properties.length && !tmp.binds.length) {
if (hasOwn(constructor.prototype, 'initialize')) {
newConstructor = constructor.prototype.initialize;
} else {
parentInitialize = constructor.prototype.initialize;
// Optimize common use cases
// Default to the slower apply..
switch (parentInitialize.length) {
case 0:
newConstructor = function () { parentInitialize.call(this); };
break;
case 1:
newConstructor = function (a) { parentInitialize.call(this, a); };
break;
case 2:
newConstructor = function (a, b) { parentInitialize.call(this, a, b); };
break;
case 3:
newConstructor = function (a, b, c) { parentInitialize.call(this, a, b, c); };
break;
case 4:
newConstructor = function (a, b, c, d) { parentInitialize.call(this, a, b, c, d); };
break;
default:
newConstructor = function () { parentInitialize.apply(this, arguments); };
}
}
if (constructor.$parent) {
inheritPrototype(newConstructor, constructor);
newConstructor.$parent = constructor.$parent;
}
mixIn(newConstructor.prototype, constructor.prototype);
mixIn(newConstructor, constructor);
obfuscateProperty(newConstructor, $class, constructor[$class]);
return newConstructor;
}
}
return constructor;
}
|
javascript
|
{
"resource": ""
}
|
q57891
|
attemptToExtractStatusCode
|
train
|
function attemptToExtractStatusCode(req) {
if (has(req, 'response') && isObject(req.response) &&
has(req.response, 'statusCode')) {
return req.response.statusCode;
} else if (has(req, 'response') && isObject(req.response) &&
isObject(req.response.output)) {
return req.response.output.statusCode;
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
q57892
|
extractRemoteAddressFromRequest
|
train
|
function extractRemoteAddressFromRequest(req) {
if (has(req.headers, 'x-forwarded-for')) {
return req.headers['x-forwarded-for'];
} else if (isObject(req.info)) {
return req.info.remoteAddress;
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q57893
|
hapiRequestInformationExtractor
|
train
|
function hapiRequestInformationExtractor(req) {
var returnObject = new RequestInformationContainer();
if (!isObject(req) || !isObject(req.headers) || isFunction(req) ||
isArray(req)) {
return returnObject;
}
returnObject.setMethod(req.method)
.setUrl(req.url)
.setUserAgent(req.headers['user-agent'])
.setReferrer(req.headers.referrer)
.setStatusCode(attemptToExtractStatusCode(req))
.setRemoteAddress(extractRemoteAddressFromRequest(req));
return returnObject;
}
|
javascript
|
{
"resource": ""
}
|
q57894
|
addScope
|
train
|
function addScope (scope) {
if (!scope) {
return
}
var oldScope = new Set(this.scope.split(' '))
var newScope
// Convert the incoming new scopes to a Set
if (typeof scope === 'string') {
newScope = new Set(scope.split(' '))
} else if (Array.isArray(scope)) {
newScope = new Set(scope)
} else {
throw new RangeError('Trying to add an invalid scope object')
}
oldScope.forEach(function (item) {
newScope.add(item)
})
// Convert back to string
this.scope = Array.from(newScope).join(' ')
}
|
javascript
|
{
"resource": ""
}
|
q57895
|
discover
|
train
|
function discover () {
var self = this
// construct the uri
var uri = url.parse(this.issuer)
uri.pathname = '.well-known/openid-configuration'
uri = url.format(uri)
var requestOptions = {
url: uri,
method: 'GET',
json: true,
agentOptions: self.agentOptions
}
if (self.proxy) {
requestOptions.proxy = self.proxy
}
// return a promise
return new Promise(function (resolve, reject) {
request(requestOptions)
.then(function (data) {
// data will be an object if the server returned JSON
if (typeof data === 'object') {
self.configuration = data
resolve(data)
// If data is not an object, the server is not serving
// .well-known/openid-configuration as expected
} else {
reject(new Error('Unable to retrieve OpenID Connect configuration'))
}
})
.catch(function (err) {
reject(err)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q57896
|
initAdminAPI
|
train
|
function initAdminAPI () {
this.clients = {
list: clients.list.bind(this),
get: clients.get.bind(this),
create: clients.create.bind(this),
update: clients.update.bind(this),
delete: clients.delete.bind(this),
roles: {
list: clientRoles.listRoles.bind(this),
add: clientRoles.addRole.bind(this),
delete: clientRoles.deleteRole.bind(this)
}
}
this.roles = {
list: roles.list.bind(this),
get: roles.get.bind(this),
create: roles.create.bind(this),
update: roles.update.bind(this),
delete: roles.delete.bind(this),
scopes: {
list: roleScopes.listScopes.bind(this),
add: roleScopes.addScope.bind(this),
delete: roleScopes.deleteScope.bind(this)
}
}
this.scopes = {
list: scopes.list.bind(this),
get: scopes.get.bind(this),
create: scopes.create.bind(this),
update: scopes.update.bind(this),
delete: scopes.delete.bind(this)
}
this.users = {
list: users.list.bind(this),
get: users.get.bind(this),
create: users.create.bind(this),
update: users.update.bind(this),
delete: users.delete.bind(this),
roles: {
list: userRoles.listRoles.bind(this),
add: userRoles.addRole.bind(this),
delete: userRoles.deleteRole.bind(this)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57897
|
authorizationUri
|
train
|
function authorizationUri (options) {
var u = url.parse(this.configuration.authorization_endpoint)
// assign endpoint and ensure options
var endpoint = 'authorize'
if (typeof options === 'string') {
endpoint = options
options = {}
} else if (typeof options === 'object') {
endpoint = options.endpoint
} else {
options = {}
}
// pathname
u.pathname = endpoint
// request params
u.query = this.authorizationParams(options)
return url.format(u)
}
|
javascript
|
{
"resource": ""
}
|
q57898
|
verify
|
train
|
function verify (token, options) {
options = options || {}
options.issuer = options.issuer || this.issuer
options.client_id = options.client_id || this.client_id
options.client_secret = options.client_secret || this.client_secret
options.scope = options.scope || this.scope
options.key = options.key || this.jwks.sig
return new Promise(function (resolve, reject) {
AccessToken.verify(token, options, function (err, claims) {
if (err) { return reject(err) }
resolve(claims)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q57899
|
extractFromObject
|
train
|
function extractFromObject(err, errorMessage) {
if (has(err, 'message')) {
errorMessage.setMessage(err.message);
}
if (has(err, 'user')) {
errorMessage.setUser(err.user);
}
if (has(err, 'filePath')) {
errorMessage.setFilePath(err.filePath);
}
if (has(err, 'lineNumber')) {
errorMessage.setLineNumber(err.lineNumber);
}
if (has(err, 'functionName')) {
errorMessage.setFunctionName(err.functionName);
}
if (has(err, 'serviceContext') && isObject(err.serviceContext)) {
errorMessage.setServiceContext(err.serviceContext.service,
err.serviceContext.version);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.