_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q23200
|
canOverflow
|
train
|
function canOverflow(el, axis) {
var overflowValue = w.getComputedStyle(el, null)['overflow' + axis];
return overflowValue === 'auto' || overflowValue === 'scroll';
}
|
javascript
|
{
"resource": ""
}
|
q23201
|
isScrollable
|
train
|
function isScrollable(el) {
var isScrollableY = hasScrollableSpace(el, 'Y') && canOverflow(el, 'Y');
var isScrollableX = hasScrollableSpace(el, 'X') && canOverflow(el, 'X');
return isScrollableY || isScrollableX;
}
|
javascript
|
{
"resource": ""
}
|
q23202
|
findScrollableParent
|
train
|
function findScrollableParent(el) {
while (el !== d.body && isScrollable(el) === false) {
el = el.parentNode || el.host;
}
return el;
}
|
javascript
|
{
"resource": ""
}
|
q23203
|
smoothScroll
|
train
|
function smoothScroll(el, x, y) {
var scrollable;
var startX;
var startY;
var method;
var startTime = now();
// define scroll context
if (el === d.body) {
scrollable = w;
startX = w.scrollX || w.pageXOffset;
startY = w.scrollY || w.pageYOffset;
method = original.scroll;
} else {
scrollable = el;
startX = el.scrollLeft;
startY = el.scrollTop;
method = scrollElement;
}
// scroll looping over a frame
step({
scrollable: scrollable,
method: method,
startTime: startTime,
startX: startX,
startY: startY,
x: x,
y: y
});
}
|
javascript
|
{
"resource": ""
}
|
q23204
|
defineReactive$$1
|
train
|
function defineReactive$$1 (
obj,
key,
val,
customSetter,
shallow
) {
var dep = new Dep();
var property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
if ((!getter || setter) && arguments.length === 2) {
val = obj[key];
}
var childOb = !shallow && observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val;
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
if (Array.isArray(value)) {
dependArray(value);
}
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter();
}
// #7981: for accessor properties without setter
if (getter && !setter) { return }
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = !shallow && observe(newVal);
dep.notify();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q23205
|
queueWatcher
|
train
|
function queueWatcher (watcher) {
var id = watcher.id;
if (has[id] == null) {
has[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1;
while (i > index && queue[i].id > watcher.id) {
i--;
}
queue.splice(i + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
if (process.env.NODE_ENV !== 'production' && !config.async) {
flushSchedulerQueue();
return
}
nextTick(flushSchedulerQueue);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q23206
|
getStyle
|
train
|
function getStyle (vnode, checkChild) {
var res = {};
var styleData;
if (checkChild) {
var childNode = vnode;
while (childNode.componentInstance) {
childNode = childNode.componentInstance._vnode;
if (
childNode && childNode.data &&
(styleData = normalizeStyleData(childNode.data))
) {
extend(res, styleData);
}
}
}
if ((styleData = normalizeStyleData(vnode.data))) {
extend(res, styleData);
}
var parentNode = vnode;
while ((parentNode = parentNode.parent)) {
if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {
extend(res, styleData);
}
}
return res
}
|
javascript
|
{
"resource": ""
}
|
q23207
|
postTransformComponent
|
train
|
function postTransformComponent (
el,
options
) {
// $flow-disable-line (we know isReservedTag is there)
if (!options.isReservedTag(el.tag) && el.tag !== 'cell-slot') {
addAttr(el, RECYCLE_LIST_MARKER, 'true');
}
}
|
javascript
|
{
"resource": ""
}
|
q23208
|
registerComponentHook
|
train
|
function registerComponentHook (
componentId,
type, // hook type, could be "lifecycle" or "instance"
hook, // hook name
fn
) {
if (!document || !document.taskCenter) {
warn("Can't find available \"document\" or \"taskCenter\".");
return
}
if (typeof document.taskCenter.registerHook === 'function') {
return document.taskCenter.registerHook(componentId, type, hook, fn)
}
warn(("Failed to register component hook \"" + type + "@" + hook + "#" + componentId + "\"."));
}
|
javascript
|
{
"resource": ""
}
|
q23209
|
updateComponentData
|
train
|
function updateComponentData (
componentId,
newData,
callback
) {
if (!document || !document.taskCenter) {
warn("Can't find available \"document\" or \"taskCenter\".");
return
}
if (typeof document.taskCenter.updateData === 'function') {
return document.taskCenter.updateData(componentId, newData, callback)
}
warn(("Failed to update component data (" + componentId + ")."));
}
|
javascript
|
{
"resource": ""
}
|
q23210
|
initVirtualComponent
|
train
|
function initVirtualComponent (options) {
if ( options === void 0 ) options = {};
var vm = this;
var componentId = options.componentId;
// virtual component uid
vm._uid = "virtual-component-" + (uid$2++);
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm);
} else {
vm._renderProxy = vm;
}
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
initRender(vm);
callHook(vm, 'beforeCreate');
initInjections(vm); // resolve injections before data/props
initState(vm);
initProvide(vm); // resolve provide after data/props
callHook(vm, 'created');
// send initial data to native
var data = vm.$options.data;
var params = typeof data === 'function'
? getData(data, vm)
: data || {};
if (isPlainObject(params)) {
updateComponentData(componentId, params);
}
registerComponentHook(componentId, 'lifecycle', 'attach', function () {
callHook(vm, 'beforeMount');
var updateComponent = function () {
vm._update(vm._vnode, false);
};
new Watcher(vm, updateComponent, noop, null, true);
vm._isMounted = true;
callHook(vm, 'mounted');
});
registerComponentHook(componentId, 'lifecycle', 'detach', function () {
vm.$destroy();
});
}
|
javascript
|
{
"resource": ""
}
|
q23211
|
updateVirtualComponent
|
train
|
function updateVirtualComponent (vnode) {
var vm = this;
var componentId = vm.$options.componentId;
if (vm._isMounted) {
callHook(vm, 'beforeUpdate');
}
vm._vnode = vnode;
if (vm._isMounted && componentId) {
// TODO: data should be filtered and without bindings
var data = Object.assign({}, vm._data);
updateComponentData(componentId, data, function () {
callHook(vm, 'updated');
});
}
}
|
javascript
|
{
"resource": ""
}
|
q23212
|
resolveVirtualComponent
|
train
|
function resolveVirtualComponent (vnode) {
var BaseCtor = vnode.componentOptions.Ctor;
var VirtualComponent = BaseCtor.extend({});
var cid = VirtualComponent.cid;
VirtualComponent.prototype._init = initVirtualComponent;
VirtualComponent.prototype._update = updateVirtualComponent;
vnode.componentOptions.Ctor = BaseCtor.extend({
beforeCreate: function beforeCreate () {
// const vm: Component = this
// TODO: listen on all events and dispatch them to the
// corresponding virtual components according to the componentId.
// vm._virtualComponents = {}
var createVirtualComponent = function (componentId, propsData) {
// create virtual component
// const subVm =
new VirtualComponent({
componentId: componentId,
propsData: propsData
});
// if (vm._virtualComponents) {
// vm._virtualComponents[componentId] = subVm
// }
};
registerComponentHook(cid, 'lifecycle', 'create', createVirtualComponent);
},
beforeDestroy: function beforeDestroy () {
delete this._virtualComponents;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q23213
|
createInstanceContext
|
train
|
function createInstanceContext (
instanceId,
runtimeContext,
data
) {
if ( data === void 0 ) data = {};
var weex = runtimeContext.weex;
var instance = instanceOptions[instanceId] = {
instanceId: instanceId,
config: weex.config,
document: weex.document,
data: data
};
// Each instance has a independent `Vue` module instance
var Vue = instance.Vue = createVueModuleInstance(instanceId, weex);
// DEPRECATED
var timerAPIs = getInstanceTimer(instanceId, weex.requireModule);
var instanceContext = Object.assign({ Vue: Vue }, timerAPIs);
Object.freeze(instanceContext);
return instanceContext
}
|
javascript
|
{
"resource": ""
}
|
q23214
|
getInstanceTimer
|
train
|
function getInstanceTimer (
instanceId,
moduleGetter
) {
var instance = instanceOptions[instanceId];
var timer = moduleGetter('timer');
var timerAPIs = {
setTimeout: function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
var handler = function () {
args[0].apply(args, args.slice(2));
};
timer.setTimeout(handler, args[1]);
return instance.document.taskCenter.callbackManager.lastCallbackId.toString()
},
setInterval: function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
var handler = function () {
args[0].apply(args, args.slice(2));
};
timer.setInterval(handler, args[1]);
return instance.document.taskCenter.callbackManager.lastCallbackId.toString()
},
clearTimeout: function (n) {
timer.clearTimeout(n);
},
clearInterval: function (n) {
timer.clearInterval(n);
}
};
return timerAPIs
}
|
javascript
|
{
"resource": ""
}
|
q23215
|
applyModelTransform
|
train
|
function applyModelTransform (el, state) {
if (el.directives) {
for (var i = 0; i < el.directives.length; i++) {
var dir = el.directives[i];
if (dir.name === 'model') {
state.directives.model(el, dir, state.warn);
// remove value for textarea as its converted to text
if (el.tag === 'textarea' && el.props) {
el.props = el.props.filter(function (p) { return p.name !== 'value'; });
}
break
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q23216
|
isValidArrayIndex
|
train
|
function isValidArrayIndex (val) {
const n = parseFloat(String(val));
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
|
javascript
|
{
"resource": ""
}
|
q23217
|
makeMap
|
train
|
function makeMap (
str,
expectsLowerCase
) {
const map = Object.create(null);
const list = str.split(',');
for (let i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? val => map[val.toLowerCase()]
: val => map[val]
}
|
javascript
|
{
"resource": ""
}
|
q23218
|
toArray
|
train
|
function toArray (list, start) {
start = start || 0;
let i = list.length - start;
const ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
|
javascript
|
{
"resource": ""
}
|
q23219
|
cloneVNode
|
train
|
function cloneVNode (vnode) {
const cloned = new VNode(
vnode.tag,
vnode.data,
// #7975
// clone children array to avoid mutating original in case of cloning
// a child.
vnode.children && vnode.children.slice(),
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions,
vnode.asyncFactory
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isComment = vnode.isComment;
cloned.fnContext = vnode.fnContext;
cloned.fnOptions = vnode.fnOptions;
cloned.fnScopeId = vnode.fnScopeId;
cloned.asyncMeta = vnode.asyncMeta;
cloned.isCloned = true;
return cloned
}
|
javascript
|
{
"resource": ""
}
|
q23220
|
normalizeProps
|
train
|
function normalizeProps (options, vm) {
const props = options.props;
if (!props) return
const res = {};
let i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (const key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
} else {
warn(
`Invalid value for option "props": expected an Array or an Object, ` +
`but got ${toRawType(props)}.`,
vm
);
}
options.props = res;
}
|
javascript
|
{
"resource": ""
}
|
q23221
|
assertProp
|
train
|
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
let type = prop.type;
let valid = !type || type === true;
const expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (let i = 0; i < type.length && !valid; i++) {
const assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType || '');
valid = assertedType.valid;
}
}
if (!valid) {
warn(
getInvalidTypeMessage(name, value, expectedTypes),
vm
);
return
}
const validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q23222
|
checkKeyCodes
|
train
|
function checkKeyCodes (
eventKeyCode,
key,
builtInKeyCode,
eventKeyName,
builtInKeyName
) {
const mappedKeyCode = config.keyCodes[key] || builtInKeyCode;
if (builtInKeyName && eventKeyName && !config.keyCodes[key]) {
return isKeyNotMatch(builtInKeyName, eventKeyName)
} else if (mappedKeyCode) {
return isKeyNotMatch(mappedKeyCode, eventKeyCode)
} else if (eventKeyName) {
return hyphenate(eventKeyName) !== key
}
}
|
javascript
|
{
"resource": ""
}
|
q23223
|
markOnce
|
train
|
function markOnce (
tree,
index,
key
) {
markStatic(tree, `__once__${index}${key ? `_${key}` : ``}`, true);
return tree
}
|
javascript
|
{
"resource": ""
}
|
q23224
|
getOuterHTML
|
train
|
function getOuterHTML (el) {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div');
container.appendChild(el.cloneNode(true));
return container.innerHTML
}
}
|
javascript
|
{
"resource": ""
}
|
q23225
|
mpify
|
train
|
function mpify (node, options) {
var target = options.target; if ( target === void 0 ) target = 'wechat';
var imports = options.imports; if ( imports === void 0 ) imports = {};
var transformAssetUrls = options.transformAssetUrls; if ( transformAssetUrls === void 0 ) transformAssetUrls = {};
var scopeId = options.scopeId; if ( scopeId === void 0 ) scopeId = '';
sep = "'" + (LIST_TAIL_SEPS[target]) + "'";
var preset = presets[target];
var state = new State({
rootNode: node,
target: target,
preset: preset,
imports: imports,
transformAssetUrls: transformAssetUrls,
scopeId: scopeId
});
if (scopeId) {
addAttr$1(node, 'sc_', ("\"" + scopeId + "\""));
}
walk(node, state);
}
|
javascript
|
{
"resource": ""
}
|
q23226
|
isSupported
|
train
|
function isSupported() {
// if not checked before, run check
if (_supported === null) {
var viewMan = Windows.UI.ViewManagement;
_supported = (viewMan.StatusBar && viewMan.StatusBar.getForCurrentView);
}
return _supported;
}
|
javascript
|
{
"resource": ""
}
|
q23227
|
generateKey
|
train
|
function generateKey() {
let result = '';
for(let i=0; i<16; i++) {
let idx = Math.floor(Math.random() * CHARS.length);
result += CHARS[idx];
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q23228
|
mixin
|
train
|
function mixin(device, options) {
if(device.capabilities.indexOf('sensor') < 0) {
device.capabilities.push('sensor');
}
device.capabilities.push(options.name);
Object.defineProperty(device, options.name, {
get: function() {
return this.property(options.name);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q23229
|
getSnapOffset
|
train
|
function getSnapOffset(event, axis) {
var context = event.context,
shape = event.shape,
gridSnappingContext = context.gridSnappingContext || {},
snapLocation = gridSnappingContext.snapLocation;
if (!shape || !snapLocation) {
return 0;
}
if (axis === 'x') {
if (/left/.test(snapLocation)) {
return -shape.width / 2;
}
if (/right/.test(snapLocation)) {
return shape.width / 2;
}
} else {
if (/top/.test(snapLocation)) {
return -shape.height / 2;
}
if (/bottom/.test(snapLocation)) {
return shape.height / 2;
}
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
q23230
|
removeAttached
|
train
|
function removeAttached(elements) {
var ids = groupBy(elements, 'id');
return filter(elements, function(element) {
while (element) {
// host in selection
if (element.host && ids[element.host.id]) {
return false;
}
element = element.parent;
}
return true;
});
}
|
javascript
|
{
"resource": ""
}
|
q23231
|
start
|
train
|
function start(event, element, activate, context) {
if (isObject(activate)) {
context = activate;
activate = false;
}
// do not move connections or the root element
if (element.waypoints || !element.parent) {
return;
}
var referencePoint = mid(element);
dragging.init(event, referencePoint, 'shape.move', {
cursor: 'grabbing',
autoActivate: activate,
data: {
shape: element,
context: context || {}
}
});
// we've handled the event
return true;
}
|
javascript
|
{
"resource": ""
}
|
q23232
|
removeNested
|
train
|
function removeNested(elements) {
var ids = groupBy(elements, 'id');
return filter(elements, function(element) {
while ((element = element.parent)) {
// parent in selection
if (ids[element.id]) {
return false;
}
}
return true;
});
}
|
javascript
|
{
"resource": ""
}
|
q23233
|
setMarker
|
train
|
function setMarker(element, marker) {
[ MARKER_ATTACH, MARKER_OK, MARKER_NOT_OK, MARKER_NEW_PARENT ].forEach(function(m) {
if (m === marker) {
canvas.addMarker(element, m);
} else {
canvas.removeMarker(element, m);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q23234
|
makeDraggable
|
train
|
function makeDraggable(context, element, addMarker) {
previewSupport.addDragger(element, context.dragGroup);
if (addMarker) {
canvas.addMarker(element, MARKER_DRAGGING);
}
if (context.allDraggedElements) {
context.allDraggedElements.push(element);
} else {
context.allDraggedElements = [ element ];
}
}
|
javascript
|
{
"resource": ""
}
|
q23235
|
constructOverlay
|
train
|
function constructOverlay(box) {
var offset = 6;
var w = box.width + offset * 2;
var h = box.height + offset * 2;
var styles = [
'width: '+ w +'px',
'height: '+ h + 'px'
].join('; ');
return {
position: {
bottom: h - offset,
right: w - offset
},
show: true,
html: '<div style="' + styles + '" class="' + SearchPad.OVERLAY_CLASS + '"></div>'
};
}
|
javascript
|
{
"resource": ""
}
|
q23236
|
createInnerTextNode
|
train
|
function createInnerTextNode(parentNode, tokens, template) {
var text = createHtmlText(tokens);
var childNode = domify(template);
childNode.innerHTML = text;
parentNode.appendChild(childNode);
}
|
javascript
|
{
"resource": ""
}
|
q23237
|
createHtmlText
|
train
|
function createHtmlText(tokens) {
var htmlText = '';
tokens.forEach(function(t) {
if (t.matched) {
htmlText += '<strong class="' + SearchPad.RESULT_HIGHLIGHT_CLASS + '">' + t.matched + '</strong>';
} else {
htmlText += t.normal;
}
});
return htmlText !== '' ? htmlText : null;
}
|
javascript
|
{
"resource": ""
}
|
q23238
|
layoutNext
|
train
|
function layoutNext(lines, maxWidth, fakeText) {
var originalLine = lines.shift(),
fitLine = originalLine;
var textBBox;
for (;;) {
textBBox = getTextBBox(fitLine, fakeText);
textBBox.width = fitLine ? textBBox.width : 0;
// try to fit
if (fitLine === ' ' || fitLine === '' || textBBox.width < Math.round(maxWidth) || fitLine.length < 2) {
return fit(lines, fitLine, originalLine, textBBox);
}
fitLine = shortenLine(fitLine, textBBox.width, maxWidth);
}
}
|
javascript
|
{
"resource": ""
}
|
q23239
|
semanticShorten
|
train
|
function semanticShorten(line, maxLength) {
var parts = line.split(/(\s|-)/g),
part,
shortenedParts = [],
length = 0;
// try to shorten via spaces + hyphens
if (parts.length > 1) {
while ((part = parts.shift())) {
if (part.length + length < maxLength) {
shortenedParts.push(part);
length += part.length;
} else {
// remove previous part, too if hyphen does not fit anymore
if (part === '-') {
shortenedParts.pop();
}
break;
}
}
}
return shortenedParts.join('');
}
|
javascript
|
{
"resource": ""
}
|
q23240
|
getSimpleBendpoints
|
train
|
function getSimpleBendpoints(a, b, directions) {
var xmid = round((b.x - a.x) / 2 + a.x),
ymid = round((b.y - a.y) / 2 + a.y);
// one point, right or left from a
if (directions === 'h:v') {
return [ { x: b.x, y: a.y } ];
}
// one point, above or below a
if (directions === 'v:h') {
return [ { x: a.x, y: b.y } ];
}
// vertical segment between a and b
if (directions === 'h:h') {
return [
{ x: xmid, y: a.y },
{ x: xmid, y: b.y }
];
}
// horizontal segment between a and b
if (directions === 'v:v') {
return [
{ x: a.x, y: ymid },
{ x: b.x, y: ymid }
];
}
throw new Error('invalid directions: can only handle varians of [hv]:[hv]');
}
|
javascript
|
{
"resource": ""
}
|
q23241
|
getBendpoints
|
train
|
function getBendpoints(a, b, directions) {
directions = directions || 'h:h';
if (!isValidDirections(directions)) {
throw new Error(
'unknown directions: <' + directions + '>: ' +
'must be specified as <start>:<end> ' +
'with start/end in { h,v,t,r,b,l }'
);
}
// compute explicit directions, involving trbl dockings
// using a three segmented layouting algorithm
if (isExplicitDirections(directions)) {
var startSegment = getStartSegment(a, b, directions),
endSegment = getEndSegment(a, b, directions),
midSegment = getMidSegment(startSegment, endSegment);
return [].concat(
startSegment.waypoints,
midSegment.waypoints,
endSegment.waypoints
);
}
// handle simple [hv]:[hv] cases that can be easily computed
return getSimpleBendpoints(a, b, directions);
}
|
javascript
|
{
"resource": ""
}
|
q23242
|
tryRepairConnectionStart
|
train
|
function tryRepairConnectionStart(moved, other, newDocking, points) {
return _tryRepairConnectionSide(moved, other, newDocking, points);
}
|
javascript
|
{
"resource": ""
}
|
q23243
|
tryRepairConnectionEnd
|
train
|
function tryRepairConnectionEnd(moved, other, newDocking, points) {
var waypoints = points.slice().reverse();
waypoints = _tryRepairConnectionSide(moved, other, newDocking, waypoints);
return waypoints ? waypoints.reverse() : null;
}
|
javascript
|
{
"resource": ""
}
|
q23244
|
_tryRepairConnectionSide
|
train
|
function _tryRepairConnectionSide(moved, other, newDocking, points) {
function needsRelayout(moved, other, points) {
if (points.length < 3) {
return true;
}
if (points.length > 4) {
return false;
}
// relayout if two points overlap
// this is most likely due to
return !!find(points, function(p, idx) {
var q = points[idx - 1];
return q && pointDistance(p, q) < 3;
});
}
function repairBendpoint(candidate, oldPeer, newPeer) {
var alignment = pointsAligned(oldPeer, candidate);
switch (alignment) {
case 'v':
// repair vertical alignment
return { x: candidate.x, y: newPeer.y };
case 'h':
// repair horizontal alignment
return { x: newPeer.x, y: candidate.y };
}
return { x: candidate.x, y: candidate. y };
}
function removeOverlapping(points, a, b) {
var i;
for (i = points.length - 2; i !== 0; i--) {
// intersects (?) break, remove all bendpoints up to this one and relayout
if (pointInRect(points[i], a, INTERSECTION_THRESHOLD) ||
pointInRect(points[i], b, INTERSECTION_THRESHOLD)) {
// return sliced old connection
return points.slice(i);
}
}
return points;
}
// (0) only repair what has layoutable bendpoints
// (1) if only one bendpoint and on shape moved onto other shapes axis
// (horizontally / vertically), relayout
if (needsRelayout(moved, other, points)) {
return null;
}
var oldDocking = points[0],
newPoints = points.slice(),
slicedPoints;
// (2) repair only last line segment and only if it was layouted before
newPoints[0] = newDocking;
newPoints[1] = repairBendpoint(newPoints[1], oldDocking, newDocking);
// (3) if shape intersects with any bendpoint after repair,
// remove all segments up to this bendpoint and repair from there
slicedPoints = removeOverlapping(newPoints, moved, other);
if (slicedPoints !== newPoints) {
return _tryRepairConnectionSide(moved, other, newDocking, slicedPoints);
}
return newPoints;
}
|
javascript
|
{
"resource": ""
}
|
q23245
|
createContainer
|
train
|
function createContainer(options) {
options = assign({}, { width: '100%', height: '100%' }, options);
var container = options.container || document.body;
// create a <div> around the svg element with the respective size
// this way we can always get the correct container size
// (this is impossible for <svg> elements at the moment)
var parent = document.createElement('div');
parent.setAttribute('class', 'djs-container');
assign(parent.style, {
position: 'relative',
overflow: 'hidden',
width: ensurePx(options.width),
height: ensurePx(options.height)
});
container.appendChild(parent);
return parent;
}
|
javascript
|
{
"resource": ""
}
|
q23246
|
handleMove
|
train
|
function handleMove(context, delta) {
var shape = context.shape,
direction = context.direction,
resizeConstraints = context.resizeConstraints,
newBounds;
context.delta = delta;
newBounds = resizeBounds(shape, direction, delta);
// ensure constraints during resize
context.newBounds = ensureConstraints(newBounds, resizeConstraints);
// update + cache executable state
context.canExecute = self.canResize(context);
}
|
javascript
|
{
"resource": ""
}
|
q23247
|
handleStart
|
train
|
function handleStart(context) {
var resizeConstraints = context.resizeConstraints,
// evaluate minBounds for backwards compatibility
minBounds = context.minBounds;
if (resizeConstraints !== undefined) {
return;
}
if (minBounds === undefined) {
minBounds = self.computeMinResizeBox(context);
}
context.resizeConstraints = {
min: asTRBL(minBounds)
};
}
|
javascript
|
{
"resource": ""
}
|
q23248
|
handleEnd
|
train
|
function handleEnd(context) {
var shape = context.shape,
canExecute = context.canExecute,
newBounds = context.newBounds;
if (canExecute) {
// ensure we have actual pixel values for new bounds
// (important when zoom level was > 1 during move)
newBounds = roundBounds(newBounds);
// perform the actual resize
modeling.resizeShape(shape, newBounds);
}
}
|
javascript
|
{
"resource": ""
}
|
q23249
|
bootstrap
|
train
|
function bootstrap(bootstrapModules) {
var modules = [],
components = [];
function hasModule(m) {
return modules.indexOf(m) >= 0;
}
function addModule(m) {
modules.push(m);
}
function visit(m) {
if (hasModule(m)) {
return;
}
(m.__depends__ || []).forEach(visit);
if (hasModule(m)) {
return;
}
addModule(m);
(m.__init__ || []).forEach(function(c) {
components.push(c);
});
}
bootstrapModules.forEach(visit);
var injector = new Injector(modules);
components.forEach(function(c) {
try {
// eagerly resolve component (fn or string)
injector[typeof c === 'string' ? 'get' : 'invoke'](c);
} catch (e) {
console.error('Failed to instantiate component');
console.error(e.stack);
throw e;
}
});
return injector;
}
|
javascript
|
{
"resource": ""
}
|
q23250
|
createInjector
|
train
|
function createInjector(options) {
options = options || {};
var configModule = {
'config': ['value', options]
};
var modules = [ configModule, CoreModule ].concat(options.modules || []);
return bootstrap(modules);
}
|
javascript
|
{
"resource": ""
}
|
q23251
|
trapClickAndEnd
|
train
|
function trapClickAndEnd(event) {
var untrap;
// trap the click in case we are part of an active
// drag operation. This will effectively prevent
// the ghost click that cannot be canceled otherwise.
if (context.active) {
untrap = installClickTrap(eventBus);
// remove trap after minimal delay
setTimeout(untrap, 400);
// prevent default action (click)
preventDefault(event);
}
end(event);
}
|
javascript
|
{
"resource": ""
}
|
q23252
|
cancel
|
train
|
function cancel(restore) {
var previousContext;
if (!context) {
return;
}
var wasActive = context.active;
if (wasActive) {
fire('cancel');
}
previousContext = cleanup(restore);
if (wasActive) {
// last event to be fired when all drag operations are done
// at this point in time no drag operation is in progress anymore
fire('canceled', previousContext);
}
}
|
javascript
|
{
"resource": ""
}
|
q23253
|
init
|
train
|
function init(event, relativeTo, prefix, options) {
// only one drag operation may be active, at a time
if (context) {
cancel(false);
}
if (typeof relativeTo === 'string') {
options = prefix;
prefix = relativeTo;
relativeTo = null;
}
options = assign({}, defaultOptions, options || {});
var data = options.data || {},
originalEvent,
globalStart,
localStart,
endDrag,
isTouch;
if (options.trapClick) {
endDrag = trapClickAndEnd;
} else {
endDrag = end;
}
if (event) {
originalEvent = getOriginal(event) || event;
globalStart = toPoint(event);
stopPropagation(event);
// prevent default browser dragging behavior
if (originalEvent.type === 'dragstart') {
preventDefault(originalEvent);
}
} else {
originalEvent = null;
globalStart = { x: 0, y: 0 };
}
localStart = toLocalPoint(globalStart);
if (!relativeTo) {
relativeTo = localStart;
}
isTouch = isTouchEvent(originalEvent);
context = assign({
prefix: prefix,
data: data,
payload: {},
globalStart: globalStart,
displacement: deltaPos(relativeTo, localStart),
localStart: localStart,
isTouch: isTouch
}, options);
// skip dom registration if trigger
// is set to manual (during testing)
if (!options.manual) {
// add dom listeners
if (isTouch) {
domEvent.bind(document, 'touchstart', trapTouch, true);
domEvent.bind(document, 'touchcancel', cancel, true);
domEvent.bind(document, 'touchmove', move, true);
domEvent.bind(document, 'touchend', end, true);
} else {
// assume we use the mouse to interact per default
domEvent.bind(document, 'mousemove', move);
// prevent default browser drag and text selection behavior
domEvent.bind(document, 'dragstart', preventDefault);
domEvent.bind(document, 'selectstart', preventDefault);
domEvent.bind(document, 'mousedown', endDrag, true);
domEvent.bind(document, 'mouseup', endDrag, true);
}
domEvent.bind(document, 'keyup', checkCancel);
eventBus.on('element.hover', hover);
eventBus.on('element.out', out);
}
fire('init');
if (options.autoActivate) {
move(event, true);
}
}
|
javascript
|
{
"resource": ""
}
|
q23254
|
getDocking
|
train
|
function getDocking(point, referenceElement, moveAxis) {
var referenceMid,
inverseAxis;
if (point.original) {
return point.original;
} else {
referenceMid = getMid(referenceElement);
inverseAxis = flipAxis(moveAxis);
return axisSet(point, inverseAxis, referenceMid[inverseAxis]);
}
}
|
javascript
|
{
"resource": ""
}
|
q23255
|
cropConnection
|
train
|
function cropConnection(connection, newWaypoints) {
// crop connection, if docking service is provided only
if (!connectionDocking) {
return newWaypoints;
}
var oldWaypoints = connection.waypoints,
croppedWaypoints;
// temporary set new waypoints
connection.waypoints = newWaypoints;
croppedWaypoints = connectionDocking.getCroppedWaypoints(connection);
// restore old waypoints
connection.waypoints = oldWaypoints;
return croppedWaypoints;
}
|
javascript
|
{
"resource": ""
}
|
q23256
|
addClasses
|
train
|
function addClasses(el, classes) {
var newClasses = convertToArray(classes);
var classList;
if (el.className instanceof SVGAnimatedString) {
classList = convertToArray(el.className.baseVal);
} else {
classList = convertToArray(el.className);
}
newClasses.forEach(function (newClass) {
if (classList.indexOf(newClass) === -1) {
classList.push(newClass);
}
});
if (el instanceof SVGElement) {
el.setAttribute('class', classList.join(' '));
} else {
el.className = classList.join(' ');
}
}
|
javascript
|
{
"resource": ""
}
|
q23257
|
removeClasses
|
train
|
function removeClasses(el, classes) {
var newClasses = convertToArray(classes);
var classList;
if (el.className instanceof SVGAnimatedString) {
classList = convertToArray(el.className.baseVal);
} else {
classList = convertToArray(el.className);
}
newClasses.forEach(function (newClass) {
var index = classList.indexOf(newClass);
if (index !== -1) {
classList.splice(index, 1);
}
});
if (el instanceof SVGElement) {
el.setAttribute('class', classList.join(' '));
} else {
el.className = classList.join(' ');
}
}
|
javascript
|
{
"resource": ""
}
|
q23258
|
Tooltip
|
train
|
function Tooltip(_reference, _options) {
var _this = this;
_classCallCheck(this, Tooltip);
_defineProperty(this, "_events", []);
_defineProperty(this, "_setTooltipNodeEvent", function (evt, reference, delay, options) {
var relatedreference = evt.relatedreference || evt.toElement || evt.relatedTarget;
var callback = function callback(evt2) {
var relatedreference2 = evt2.relatedreference || evt2.toElement || evt2.relatedTarget; // Remove event listener after call
_this._tooltipNode.removeEventListener(evt.type, callback); // If the new reference is not the reference element
if (!reference.contains(relatedreference2)) {
// Schedule to hide tooltip
_this._scheduleHide(reference, options.delay, options, evt2);
}
};
if (_this._tooltipNode.contains(relatedreference)) {
// listen to mouseleave on the tooltip element to be able to hide the tooltip
_this._tooltipNode.addEventListener(evt.type, callback);
return true;
}
return false;
});
// apply user options over default ones
_options = _objectSpread({}, DEFAULT_OPTIONS, _options);
_reference.jquery && (_reference = _reference[0]);
this.show = this.show.bind(this);
this.hide = this.hide.bind(this); // cache reference and options
this.reference = _reference;
this.options = _options; // set initial state
this._isOpen = false;
this._init();
}
|
javascript
|
{
"resource": ""
}
|
q23259
|
scrapeIt
|
train
|
function scrapeIt (url, opts, cb) {
cb = assured(cb)
req(url, (err, $, res, body) => {
if (err) { return cb(err) }
try {
let scrapedData = scrapeIt.scrapeHTML($, opts)
cb(null, {
data: scrapedData,
$,
response: res,
body
})
}
catch (err) {
cb(err);
}
})
return cb._
}
|
javascript
|
{
"resource": ""
}
|
q23260
|
measure
|
train
|
function measure(ref) {
return new Promise(function (resolve) {
ref.measure(function (x, y, width, height, pageX, pageY) {
resolve({
x: pageX,
y: pageY,
width: width,
height: height
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23261
|
makeTouchable
|
train
|
function makeTouchable(TouchableComponent) {
var Touchable = TouchableComponent || reactNative.Platform.select({
android: reactNative.TouchableNativeFeedback,
ios: reactNative.TouchableHighlight,
default: reactNative.TouchableHighlight
});
var defaultTouchableProps = {};
if (Touchable === reactNative.TouchableHighlight) {
defaultTouchableProps = {
underlayColor: 'rgba(0, 0, 0, 0.1)'
};
}
return {
Touchable: Touchable,
defaultTouchableProps: defaultTouchableProps
};
}
|
javascript
|
{
"resource": ""
}
|
q23262
|
iterator2array
|
train
|
function iterator2array(it) {
// workaround around https://github.com/instea/react-native-popup-menu/issues/41#issuecomment-340290127
var arr = [];
for (var next = it.next(); !next.done; next = it.next()) {
arr.push(next.value);
}
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q23263
|
deprecatedComponent
|
train
|
function deprecatedComponent(message) {
var methods = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return function deprecatedComponentHOC(Component) {
var _temp;
return _temp =
/*#__PURE__*/
function (_React$Component) {
_inherits(DeprecatedComponent, _React$Component);
function DeprecatedComponent() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, DeprecatedComponent);
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(DeprecatedComponent)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "onRef", function (ref) {
return _this.ref = ref;
});
methods.forEach(function (name) {
// delegate methods to the component
_this[name] = function () {
var _this$ref;
return _this.ref && (_this$ref = _this.ref)[name].apply(_this$ref, arguments);
};
});
return _this;
}
_createClass(DeprecatedComponent, [{
key: "render",
value: function render() {
return React__default.createElement(Component, _extends({}, this.props, {
ref: this.onRef
}));
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
console.warn(message);
}
}]);
return DeprecatedComponent;
}(React__default.Component), _temp;
};
}
|
javascript
|
{
"resource": ""
}
|
q23264
|
isAsyncMode
|
train
|
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
|
javascript
|
{
"resource": ""
}
|
q23265
|
makeMenuRegistry
|
train
|
function makeMenuRegistry() {
var menus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Map();
/**
* Subscribes menu instance.
*/
function subscribe(instance) {
var name = instance.getName();
if (menus.get(name)) {
console.warn("incorrect usage of popup menu - menu with name ".concat(name, " already exists"));
}
menus.set(name, {
name: name,
instance: instance
});
}
/**
* Unsubscribes menu instance.
*/
function unsubscribe(instance) {
menus.delete(instance.getName());
}
/**
* Updates layout infomration.
*/
function updateLayoutInfo(name) {
var layouts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!menus.has(name)) {
return;
}
var menu = Object.assign({}, menus.get(name));
if (layouts.hasOwnProperty('triggerLayout')) {
menu.triggerLayout = layouts.triggerLayout;
}
if (layouts.hasOwnProperty('optionsLayout')) {
menu.optionsLayout = layouts.optionsLayout;
}
menus.set(name, menu);
}
function setOptionsCustomStyles(name, optionsCustomStyles) {
if (!menus.has(name)) {
return;
}
var menu = _objectSpread({}, menus.get(name), {
optionsCustomStyles: optionsCustomStyles
});
menus.set(name, menu);
}
/**
* Get `menu data` by name.
*/
function getMenu(name) {
return menus.get(name);
}
/**
* Returns all subscribed menus as array of `menu data`
*/
function getAll() {
return iterator2array(menus.values());
}
return {
subscribe: subscribe,
unsubscribe: unsubscribe,
updateLayoutInfo: updateLayoutInfo,
getMenu: getMenu,
getAll: getAll,
setOptionsCustomStyles: setOptionsCustomStyles
};
}
|
javascript
|
{
"resource": ""
}
|
q23266
|
subscribe
|
train
|
function subscribe(instance) {
var name = instance.getName();
if (menus.get(name)) {
console.warn("incorrect usage of popup menu - menu with name ".concat(name, " already exists"));
}
menus.set(name, {
name: name,
instance: instance
});
}
|
javascript
|
{
"resource": ""
}
|
q23267
|
updateLayoutInfo
|
train
|
function updateLayoutInfo(name) {
var layouts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!menus.has(name)) {
return;
}
var menu = Object.assign({}, menus.get(name));
if (layouts.hasOwnProperty('triggerLayout')) {
menu.triggerLayout = layouts.triggerLayout;
}
if (layouts.hasOwnProperty('optionsLayout')) {
menu.optionsLayout = layouts.optionsLayout;
}
menus.set(name, menu);
}
|
javascript
|
{
"resource": ""
}
|
q23268
|
setTag
|
train
|
function setTag(key, value, obj) {
if (!obj || !key) return
var skey = removeInvalidChars(key)
if (value) {
value = String(value)
}
obj[skey] = value
return obj
}
|
javascript
|
{
"resource": ""
}
|
q23269
|
train
|
function (successFn, errorFn) {
successFn = successFn || emptyFn;
errorFn = errorFn || emptyFn;
RNBackgroundGeolocation.getStationaryLocation(successFn, errorFn);
}
|
javascript
|
{
"resource": ""
}
|
|
q23270
|
_validateProductStructure
|
train
|
function _validateProductStructure(product) {
if (typeof product !== 'object') {
throw new TypeError(product + ' is not an object.');
}
if (Object.keys(product).length === 0 && product.constructor === Object) {
throw new Error(product + ' is empty.');
}
}
|
javascript
|
{
"resource": ""
}
|
q23271
|
buildOptions
|
train
|
function buildOptions (provinceNodeElement, provinces) {
var defaultValue = provinceNodeElement.getAttribute('data-default');
provinces.forEach(function (option) {
var optionElement = document.createElement('option');
optionElement.value = option[0];
optionElement.textContent = option[1];
provinceNodeElement.appendChild(optionElement);
})
if (defaultValue && getOption(provinceNodeElement, defaultValue)) {
provinceNodeElement.value = defaultValue;
}
}
|
javascript
|
{
"resource": ""
}
|
q23272
|
buildProvince
|
train
|
function buildProvince (countryNodeElement, provinceNodeElement, selectedValue) {
var selectedOption = getOption(countryNodeElement, selectedValue);
var provinces = JSON.parse(selectedOption.getAttribute('data-provinces'));
provinceNodeElement.options.length = 0;
if (provinces.length) {
buildOptions(provinceNodeElement, provinces)
}
return provinces;
}
|
javascript
|
{
"resource": ""
}
|
q23273
|
appendApiUrlParam
|
train
|
function appendApiUrlParam(fullUrl, apiUrl) {
let appendedUrl = fullUrl;
if (typeof apiUrl === 'string') {
if (fullUrl.indexOf('?') === -1) {
appendedUrl += '?';
} else {
appendedUrl += '&';
}
appendedUrl += 'apiUrl=';
// trim trailing slash from URL
appendedUrl += apiUrl.slice(-1) === '/' ? apiUrl.slice(0, -1) : apiUrl;
}
return appendedUrl;
}
|
javascript
|
{
"resource": ""
}
|
q23274
|
extractProtocolHost
|
train
|
function extractProtocolHost(url) {
const urlNoQuery = url.split('?')[0];
const [protocol, hostAndPath] = urlNoQuery.split('//');
const host = hostAndPath.split('/')[0];
return `${protocol}//${host}`;
}
|
javascript
|
{
"resource": ""
}
|
q23275
|
setLoaderClass
|
train
|
function setLoaderClass(c, t) {
timeouts.push(
setTimeout(() => {
loadbar.classList.add(c);
}, t)
);
}
|
javascript
|
{
"resource": ""
}
|
q23276
|
findExtensionsYAMLFile
|
train
|
function findExtensionsYAMLFile() {
for (var i = 0; i < paths.srcPaths.length; i++) {
var srcPath = path.resolve(cwd, paths.srcPaths[i]);
var extFile = path.resolve(srcPath, 'jenkins-js-extension.yaml');
if (fs.existsSync(extFile)) {
return extFile;
}
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q23277
|
loadSource
|
train
|
function loadSource(sourcePath) {
return new Promise((fulfil, reject) => {
fs.readFile(sourcePath, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
fulfil(data);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23278
|
saveSource
|
train
|
function saveSource(sourcePath, data) {
return new Promise((fulfil, reject) => {
fs.writeFile(sourcePath, data, 'utf8', err => {
if (err) {
reject(err);
} else {
fulfil(true);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23279
|
getSourceFilesFromGlob
|
train
|
function getSourceFilesFromGlob(globPattern, ignoreGlobs) {
return new Promise((fulfil, reject) => {
glob(globPattern, { ignore: ignoreGlobs }, (err, files) => {
if (err) {
reject(err);
} else {
fulfil(files);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23280
|
filterFiles
|
train
|
function filterFiles(files, validExtensions) {
const accepted = [];
for (const fileName of files) {
if (accepted.indexOf(fileName) === -1 && fileMatchesExtension(fileName, validExtensions)) {
accepted.push(fileName);
}
}
return accepted;
}
|
javascript
|
{
"resource": ""
}
|
q23281
|
splitFilesIntoBatches
|
train
|
function splitFilesIntoBatches(files, config) {
// We need to specifiy a different parser for TS files
const configTS = Object.assign({}, config);
configTS.parser = 'typescript';
const batches = [];
batches.push({
files: files.filter(fileName => fileMatchesExtension(fileName, EXTENSIONS.js)),
config: config,
});
batches.push({
files: files.filter(fileName => fileMatchesExtension(fileName, EXTENSIONS.ts)),
config: configTS,
});
return batches;
}
|
javascript
|
{
"resource": ""
}
|
q23282
|
prettifyBatches
|
train
|
function prettifyBatches(batches) {
return Promise.all(batches.map(({ files, config }) => prettifyFiles(files, config)));
}
|
javascript
|
{
"resource": ""
}
|
q23283
|
mergeBatchResults
|
train
|
function mergeBatchResults(batches) {
let files = [];
let unformattedFiles = [];
let formattedFiles = [];
let errors = [];
batches.forEach(batch => {
files.push(...batch.files);
unformattedFiles.push(...batch.unformattedFiles);
formattedFiles.push(...batch.formattedFiles);
errors.push(...batch.errors);
});
return { files, formattedFiles, unformattedFiles, errors };
}
|
javascript
|
{
"resource": ""
}
|
q23284
|
showResults
|
train
|
function showResults(files, formattedFiles, unformattedFiles, errors) {
const formattedCount = formattedFiles.length;
const unformattedCount = unformattedFiles.length;
const errorCount = errors.length;
const filesCount = files.length;
const okCount = filesCount - formattedCount - unformattedCount - errorCount;
if (okCount > 0 && !simplifyOutput) {
console.log(okCount + ' of ' + filesCount + ' files already correct.');
}
if (formattedCount > 0) {
if (!simplifyOutput) {
console.log('Formatted ' + formattedCount + ' of ' + filesCount + ' files:');
}
for (const sourcePath of formattedFiles) {
if (simplifyOutput) {
console.log(sourcePath);
} else {
console.log(' - ' + sourcePath);
}
}
}
if (unformattedCount > 0) {
// Should only happen when !fixMode
console.error(unformattedCount + ' of ' + filesCount + ' files need formatting:');
for (const sourcePath of unformattedFiles) {
console.error(' - ' + sourcePath);
}
process.exitCode = 1;
}
if (errorCount > 0) {
console.error('\x1b[32mErrors occured processing ' + errorCount + ' of ' + filesCount + ' files.\x1b[m');
process.exitCode = -1;
}
return { formattedFiles, unformattedFiles };
}
|
javascript
|
{
"resource": ""
}
|
q23285
|
delayReject
|
train
|
function delayReject(delay = 1000) {
const begin = time();
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (promise.payload) {
reject(promise.payload);
}
}, delay);
});
return function proceed(error) {
// if we haven't reached the delay yet, stash the payload
// so the setTimeout above will resolve it later
if (time() - begin < delay) {
promise.payload = error;
return promise;
}
throw error;
};
}
|
javascript
|
{
"resource": ""
}
|
q23286
|
sortByOrdinal
|
train
|
function sortByOrdinal(extensions, done) {
const sorted = extensions.sort((a, b) => {
if (a.ordinal || b.ordinal) {
if (!a.ordinal) return 1;
if (!b.ordinal) return -1;
if (a.ordinal < b.ordinal) return -1;
return 1;
}
return a.pluginId.localeCompare(b.pluginId);
});
if (done) {
done(sorted);
}
return sorted;
}
|
javascript
|
{
"resource": ""
}
|
q23287
|
prepareOptions
|
train
|
function prepareOptions(body) {
const fetchOptions = Object.assign({}, fetchOptionsCommon);
if (body) {
try {
fetchOptions.body = JSON.stringify(body);
} catch (e) {
console.warn('The form body are not added. Could not extract data from the body element', body);
}
}
return fetchOptions;
}
|
javascript
|
{
"resource": ""
}
|
q23288
|
validateSourcePath
|
train
|
function validateSourcePath(sourcePath) {
const materialPackageJSONPath = pathUtils.resolve(sourcePath, 'package.json');
return fs.readFileAsync(materialPackageJSONPath, { encoding: 'UTF8' })
.then(materialPackageJSONString => {
const package = JSON.parse(materialPackageJSONString);
if (package.name !== sourcePackageName) {
throw new Error(`Source path ${sourcePath} does not appear to be a clone of https://github.com/callemall/material-ui`);
}
return sourcePath;
});
}
|
javascript
|
{
"resource": ""
}
|
q23289
|
findSourceFiles
|
train
|
function findSourceFiles(sourceIconsRoot) {
let visitedDirectories = [];
let allSourceFiles = [];
function recurseDir(dir, depth) {
// Don't get in any loops
if (visitedDirectories.indexOf(dir) !== -1) {
return;
}
if (depth > 3) {
throw new Error('findSourceFiles() - directory tree too deep');
}
visitedDirectories.push(dir);
return fs.readdirAsync(dir)
.then(filenames => {
// Turn the list of filenames into paths
const paths = filenames
.filter(filename => filename[0] !== '.' && filename !== 'index.js') // Ignore index, hidden, '.' and '..'
.map(filename => pathUtils.resolve(dir, filename));
// For each path...
const statPromises = paths.map(filePath => {
return fs.statAsync(filePath) // ... get stats
.then(stats => ({ filePath, stats })); // ... and associate with path
});
// Turn the array of promises into a promise of arrays.
return Promise.all(statPromises);
})
.then(filePathsAndStats => {
// Pick out all the JS files in dir, while collecting the list of subdirectories
let subDirPaths = [];
for (const { filePath, stats } of filePathsAndStats) {
if (stats.isDirectory()) {
subDirPaths.push(filePath);
}
else if (stats.isFile() && pathUtils.extname(filePath).toLowerCase() === '.js') {
allSourceFiles.push(filePath);
}
}
if (subDirPaths.length === 0) {
return;
}
// Recurse
return Promise.all(subDirPaths.map(path => recurseDir(path, depth + 1)));
});
}
return recurseDir(sourceIconsRoot, 0).then(() => allSourceFiles);
}
|
javascript
|
{
"resource": ""
}
|
q23290
|
train
|
function(a, epsilon) {
if(epsilon == undefined) epsilon = EPSILON;
let allSignsFlipped = false;
if (e.length != a.length)
expected(e, "to have the same length as", a);
for (let i = 0; i < e.length; i++) {
if (isNaN(e[i]) !== isNaN(a[i]))
expected(e, "to be equalish to", a);
if (allSignsFlipped) {
if (Math.abs(e[i] - (-a[i])) >= epsilon)
expected(e, "to be equalish to", a);
} else {
if (Math.abs(e[i] - a[i]) >= epsilon) {
allSignsFlipped = true;
i = 0;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23291
|
onDeleteSuccess
|
train
|
function onDeleteSuccess(model, params, result) {
Flux.dispatch(actionTypes.API_DELETE_SUCCESS, {
model: model,
params: params,
result: result,
})
return result
}
|
javascript
|
{
"resource": ""
}
|
q23292
|
onDeleteFail
|
train
|
function onDeleteFail(model, params, reason) {
Flux.dispatch(actionTypes.API_DELETE_FAIL, {
model: model,
params: params,
reason: reason,
})
return Promise.reject(reason)
}
|
javascript
|
{
"resource": ""
}
|
q23293
|
getFlattenedDeps
|
train
|
function getFlattenedDeps(getter, existing) {
if (!existing) {
existing = Immutable.Set()
}
const toAdd = Immutable.Set().withMutations(set => {
if (!isGetter(getter)) {
throw new Error('getFlattenedDeps must be passed a Getter')
}
getDeps(getter).forEach(dep => {
if (isKeyPath(dep)) {
set.add(List(dep))
} else if (isGetter(dep)) {
set.union(getFlattenedDeps(dep))
} else {
throw new Error('Invalid getter, each dependency must be a KeyPath or Getter')
}
})
})
return existing.union(toAdd)
}
|
javascript
|
{
"resource": ""
}
|
q23294
|
createCacheEntry
|
train
|
function createCacheEntry(reactorState, getter) {
// evaluate dependencies
const args = getDeps(getter).map(dep => evaluate(reactorState, dep).result)
const value = getComputeFn(getter).apply(null, args)
const storeDeps = getStoreDeps(getter)
const storeStates = toImmutable({}).withMutations(map => {
storeDeps.forEach(storeId => {
const stateId = reactorState.getIn(['storeStates', storeId])
map.set(storeId, stateId)
})
})
return CacheEntry({
value: value,
storeStates: storeStates,
dispatchId: reactorState.get('dispatchId'),
})
}
|
javascript
|
{
"resource": ""
}
|
q23295
|
setMessagesRead
|
train
|
function setMessagesRead(state, { threadID }) {
return state.updateIn([threadID, 'messages'], messages => {
return messages.map(msg => msg.set('isRead', true))
})
}
|
javascript
|
{
"resource": ""
}
|
q23296
|
removeFsElement
|
train
|
function removeFsElement (element) {
let index = fsElements.indexOf(element)
if (index !== -1) {
fsElements.splice(index, 1)
}
}
|
javascript
|
{
"resource": ""
}
|
q23297
|
getTiming
|
train
|
function getTiming () {
let nativeTiming
let performance = window.performance
if (performance && performance.timing) {
nativeTiming = performance.timing.toJSON
? performance.timing.toJSON()
: util.fn.extend({}, performance.timing)
} else {
nativeTiming = {}
}
return util.fn.extend(nativeTiming, recorder)
}
|
javascript
|
{
"resource": ""
}
|
q23298
|
recordTiming
|
train
|
function recordTiming (name, timing) {
recorder[name] = parseInt(timing, 10) || Date.now()
performanceEvent.trigger('update', getTiming())
}
|
javascript
|
{
"resource": ""
}
|
q23299
|
lockFirstScreen
|
train
|
function lockFirstScreen () {
// when is prerendering, iframe container display none,
// all elements are not in viewport.
if (prerender.isPrerendering) {
return
}
let viewportRect = viewport.getRect()
fsElements = fsElements.filter((element) => {
if (prerender.isPrerendered) {
return element._resources.isInViewport(element, viewportRect)
}
return element.inViewport()
}).map((element) => {
element.setAttribute('mip-firstscreen-element', '')
return element
})
fsElementsLocked = true
tryRecordFirstScreen()
!prerender.isPrerendered && firstScreenLabel.sendLog()
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.