_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q25300 | train | function (name, value) {
if (DOMProperty.isReservedProp(name)) {
return false;
}
if ((name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
return false;
}
if (value === null) {
return true;
}
switch (typeof value) {
case 'boolean':
return DOMProperty.shouldAttributeAcceptBooleanValue(name);
case 'undefined':
case 'number':
case 'string':
case 'object':
return true;
default:
// function, symbol
return false;
}
} | javascript | {
"resource": ""
} | |
q25301 | getTopLevelCallbackBookKeeping | train | function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) {
if (callbackBookkeepingPool.length) {
var instance = callbackBookkeepingPool.pop();
instance.topLevelType = topLevelType;
instance.nativeEvent = nativeEvent;
instance.targetInst = targetInst;
return instance;
}
return {
topLevelType: topLevelType,
nativeEvent: nativeEvent,
targetInst: targetInst,
ancestors: []
};
} | javascript | {
"resource": ""
} |
q25302 | getVendorPrefixedEventName | train | function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) {
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
return prefixedEventNames[eventName] = prefixMap[styleProp];
}
}
return '';
} | javascript | {
"resource": ""
} |
q25303 | train | function (styles) {
{
var serialized = '';
var delimiter = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (styleValue != null) {
var isCustomProperty = styleName.indexOf('--') === 0;
serialized += delimiter + hyphenateStyleName$1(styleName) + ':';
serialized += dangerousStyleValue_1(styleName, styleValue, isCustomProperty);
delimiter = ';';
}
}
return serialized || null;
}
} | javascript | {
"resource": ""
} | |
q25304 | train | function (node, name, expected) {
{
var propertyInfo = DOMProperty_1.getPropertyInfo(name);
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod || propertyInfo.mustUseProperty) {
return node[propertyInfo.propertyName];
} else {
var attributeName = propertyInfo.attributeName;
var stringValue = null;
if (propertyInfo.hasOverloadedBooleanValue) {
if (node.hasAttribute(attributeName)) {
var value = node.getAttribute(attributeName);
if (value === '') {
return true;
}
if (shouldIgnoreValue(propertyInfo, expected)) {
return value;
}
if (value === '' + expected) {
return expected;
}
return value;
}
} else if (node.hasAttribute(attributeName)) {
if (shouldIgnoreValue(propertyInfo, expected)) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
return node.getAttribute(attributeName);
}
if (propertyInfo.hasBooleanValue) {
// If this was a boolean, it doesn't matter what the value is
// the fact that we have it is the same as the expected.
return expected;
}
// Even if this property uses a namespace we use getAttribute
// because we assume its namespaced name is the same as our config.
// To use getAttributeNS we need the local name which we don't have
// in our config atm.
stringValue = node.getAttribute(attributeName);
}
if (shouldIgnoreValue(propertyInfo, expected)) {
return stringValue === null ? expected : stringValue;
} else if (stringValue === '' + expected) {
return expected;
} else {
return stringValue;
}
}
}
}
} | javascript | {
"resource": ""
} | |
q25305 | train | function (node, name, expected) {
{
if (!isAttributeNameSafe(name)) {
return;
}
if (!node.hasAttribute(name)) {
return expected === undefined ? undefined : null;
}
var value = node.getAttribute(name);
if (value === '' + expected) {
return expected;
}
return value;
}
} | javascript | {
"resource": ""
} | |
q25306 | train | function (parent, html) {
if (!testDocument) {
testDocument = document.implementation.createHTMLDocument();
}
var testElement = parent.namespaceURI === HTML_NAMESPACE$1 ? testDocument.createElement(parent.tagName) : testDocument.createElementNS(parent.namespaceURI, parent.tagName);
testElement.innerHTML = html;
return testElement.innerHTML;
} | javascript | {
"resource": ""
} | |
q25307 | findInsertionPosition | train | function findInsertionPosition(queue, update) {
var priorityLevel = update.priorityLevel;
var insertAfter = null;
var insertBefore = null;
if (queue.last !== null && comparePriority(queue.last.priorityLevel, priorityLevel) <= 0) {
// Fast path for the common case where the update should be inserted at
// the end of the queue.
insertAfter = queue.last;
} else {
insertBefore = queue.first;
while (insertBefore !== null && comparePriority(insertBefore.priorityLevel, priorityLevel) <= 0) {
insertAfter = insertBefore;
insertBefore = insertBefore.next;
}
}
return insertAfter;
} | javascript | {
"resource": ""
} |
q25308 | train | function (fn) {
!(showDialog === defaultShowDialog) ? invariant(false, 'The custom dialog was already injected.') : void 0;
!(typeof fn === 'function') ? invariant(false, 'Injected showDialog() must be a function.') : void 0;
showDialog = fn;
} | javascript | {
"resource": ""
} | |
q25309 | safelyCallComponentWillUnmount | train | function safelyCallComponentWillUnmount(current, instance) {
{
invokeGuardedCallback$2(null, callComponentWillUnmountWithTimerInDev, null, current, instance);
if (hasCaughtError$1()) {
var unmountError = clearCaughtError$1();
captureError(current, unmountError);
}
}
} | javascript | {
"resource": ""
} |
q25310 | resetNextUnitOfWork | train | function resetNextUnitOfWork() {
// Clear out roots with no more work on them, or if they have uncaught errors
while (nextScheduledRoot !== null && nextScheduledRoot.current.pendingWorkPriority === NoWork$2) {
// Unschedule this root.
nextScheduledRoot.isScheduled = false;
// Read the next pointer now.
// We need to clear it in case this root gets scheduled again later.
var next = nextScheduledRoot.nextScheduledRoot;
nextScheduledRoot.nextScheduledRoot = null;
// Exit if we cleared all the roots and there's no work to do.
if (nextScheduledRoot === lastScheduledRoot) {
nextScheduledRoot = null;
lastScheduledRoot = null;
nextPriorityLevel = NoWork$2;
return null;
}
// Continue with the next root.
// If there's no work on it, it will get unscheduled too.
nextScheduledRoot = next;
}
var root = nextScheduledRoot;
var highestPriorityRoot = null;
var highestPriorityLevel = NoWork$2;
while (root !== null) {
if (root.current.pendingWorkPriority !== NoWork$2 && (highestPriorityLevel === NoWork$2 || highestPriorityLevel > root.current.pendingWorkPriority)) {
highestPriorityLevel = root.current.pendingWorkPriority;
highestPriorityRoot = root;
}
// We didn't find anything to do in this root, so let's try the next one.
root = root.nextScheduledRoot;
}
if (highestPriorityRoot !== null) {
nextPriorityLevel = highestPriorityLevel;
// Before we start any new work, let's make sure that we have a fresh
// stack to work from.
// TODO: This call is buried a bit too deep. It would be nice to have
// a single point which happens right before any new work and
// unfortunately this is it.
resetContextStack();
nextUnitOfWork = createWorkInProgress$1(highestPriorityRoot.current, highestPriorityLevel);
if (highestPriorityRoot !== nextRenderedTree) {
// We've switched trees. Reset the nested update counter.
nestedUpdateCount = 0;
nextRenderedTree = highestPriorityRoot;
}
return;
}
nextPriorityLevel = NoWork$2;
nextUnitOfWork = null;
nextRenderedTree = null;
return;
} | javascript | {
"resource": ""
} |
q25311 | getSiblingNode | train | function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
} | javascript | {
"resource": ""
} |
q25312 | getNodeForCharacterOffset | train | function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === TEXT_NODE$3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
} | javascript | {
"resource": ""
} |
q25313 | traverseEnterLeave | train | function traverseEnterLeave(from, to, fn, argFrom, argTo) {
var common = from && to ? getLowestCommonAncestor(from, to) : null;
var pathFrom = [];
while (from && from !== common) {
pathFrom.push(from);
from = getParent(from);
}
var pathTo = [];
while (to && to !== common) {
pathTo.push(to);
to = getParent(to);
}
var i;
for (i = 0; i < pathFrom.length; i++) {
fn(pathFrom[i], 'bubbled', argFrom);
}
for (i = pathTo.length; i-- > 0;) {
fn(pathTo[i], 'captured', argTo);
}
} | javascript | {
"resource": ""
} |
q25314 | listenerAtPhase | train | function listenerAtPhase(inst, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(inst, registrationName);
} | javascript | {
"resource": ""
} |
q25315 | accumulateDirectDispatchesSingle | train | function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event._targetInst, null, event);
}
} | javascript | {
"resource": ""
} |
q25316 | isPresto | train | function isPresto() {
var opera = window.opera;
return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
} | javascript | {
"resource": ""
} |
q25317 | isFallbackCompositionEnd | train | function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case 'topKeyUp':
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case 'topKeyDown':
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case 'topKeyPress':
case 'topMouseDown':
case 'topBlur':
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
} | javascript | {
"resource": ""
} |
q25318 | extractBeforeInputEvent | train | function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var event = SyntheticInputEvent_1.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
event.data = chars;
EventPropagators_1.accumulateTwoPhaseDispatches(event);
return event;
} | javascript | {
"resource": ""
} |
q25319 | modifierStateGetter | train | function modifierStateGetter(keyArg) {
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
} | javascript | {
"resource": ""
} |
q25320 | isValidContainer | train | function isValidContainer(node) {
return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));
} | javascript | {
"resource": ""
} |
q25321 | finish | train | function finish(e) {
if (e && e.target !== node) {
return;
}
clearTimeout(timer);
if (removeListeners) removeListeners();
(0, _removeClass2.default)(node, className);
(0, _removeClass2.default)(node, activeClassName);
if (removeListeners) removeListeners();
// Usually this optional callback is used for informing an owner of
// a leave animation and telling it to remove the child.
if (finishCallback) {
finishCallback();
}
} | javascript | {
"resource": ""
} |
q25322 | getChildMapping | train | function getChildMapping(children) {
if (!children) {
return children;
}
var result = {};
_react.Children.map(children, function (child) {
return child;
}).forEach(function (child) {
result[child.key] = child;
});
return result;
} | javascript | {
"resource": ""
} |
q25323 | escape | train | function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = ('' + key).replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
} | javascript | {
"resource": ""
} |
q25324 | getComponentKey | train | function getComponentKey(component, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (typeof component === 'object' && component !== null && component.key != null) {
// Explicit key
return escape(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
} | javascript | {
"resource": ""
} |
q25325 | triggerGlobal | train | function triggerGlobal(settings, context, eventName, data) {
if (settings.global)
return triggerAndReturn(context || document, eventName, data);
} | javascript | {
"resource": ""
} |
q25326 | ajaxBeforeSend | train | function ajaxBeforeSend(xhr, settings) {
var context = settings.context;
if (settings.beforeSend.call(context, xhr, settings) === false || triggerGlobal(settings, context, 'ajaxBeforeSend', [
xhr,
settings
]) === false)
return false;
triggerGlobal(settings, context, 'ajaxSend', [
xhr,
settings
]);
} | javascript | {
"resource": ""
} |
q25327 | train | function (e) {
if (e.targetTouches.length < 2) return 1;
var x1 = e.targetTouches[0].pageX,
y1 = e.targetTouches[0].pageY,
x2 = e.targetTouches[1].pageX,
y2 = e.targetTouches[1].pageY;
var distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
return distance;
} | javascript | {
"resource": ""
} | |
q25328 | invokeToneAsync | train | function invokeToneAsync(assistantPayload, toneAnalyzer) {
return new Promise(function(resolve, reject) {
toneAnalyzer.tone({ text: assistantPayload.input.text }, function(error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
} | javascript | {
"resource": ""
} |
q25329 | updateTone | train | function updateTone(user, tones, maintainHistory) {
var maxScore = 0.0;
var primaryTone = null;
var primaryToneScore = null;
tones.forEach(function(tone) {
if (tone.score > maxScore) {
maxScore = tone.score;
primaryTone = tone.tone_name.toLowerCase();
primaryToneScore = tone.score;
}
});
// update user tone
user.tone.current = primaryTone;
if (maintainHistory) {
if (typeof user.tone.history === 'undefined') {
user.tone.history = [];
}
user.tone.history.push({
tone_name: primaryTone,
score: primaryToneScore,
});
}
} | javascript | {
"resource": ""
} |
q25330 | onEvent | train | function onEvent(name, event) {
console.log(name, JSON.stringify(event, null, 2));
} | javascript | {
"resource": ""
} |
q25331 | compileHistory | train | function compileHistory(resultingArrayOfCommits) {
var lastSha;
if (historyCommits.length > 0) {
lastSha = historyCommits[historyCommits.length - 1].commit.sha();
if (
resultingArrayOfCommits.length == 1 &&
resultingArrayOfCommits[0].commit.sha() == lastSha
) {
return;
}
}
resultingArrayOfCommits.forEach(function(entry) {
historyCommits.push(entry);
});
lastSha = historyCommits[historyCommits.length - 1].commit.sha();
walker = repo.createRevWalk();
walker.push(lastSha);
walker.sorting(nodegit.Revwalk.SORT.TIME);
return walker.fileHistoryWalk(historyFile, 500)
.then(compileHistory);
} | javascript | {
"resource": ""
} |
q25332 | walk | train | function walk() {
return revWalk.next().then(function(oid) {
if (!oid) {
return;
}
return repo.getCommit(oid).then(function(commit) {
console.log("Commit:", commit.toString());
return walk();
});
});
} | javascript | {
"resource": ""
} |
q25333 | performRebase | train | function performRebase(
repository,
rebase,
signature,
beforeNextFn,
beforeFinishFn
) {
var beforeNextFnResult;
/* In the case of FF merges and a beforeFinishFn, this will fail
* when looking for 'rewritten' so we need to handle that case.
*/
function readRebaseMetadataFile(fileName, continueOnError) {
return fse.readFile(
path.join(repository.path(), "rebase-merge", fileName),
{ encoding: "utf8" }
)
.then(fp.trim)
.catch(function(err) {
if (continueOnError) {
return null;
}
throw err;
});
}
function calcHeadName(input) {
return input.replace(/refs\/heads\/(.*)/, "$1");
}
function getPromise() {
return rebase.next()
.then(function() {
return repository.refreshIndex();
})
.then(function(index) {
if (index.hasConflicts()) {
throw index;
}
return rebase.commit(null, signature);
})
.then(function() {
return performRebase(
repository,
rebase,
signature,
beforeNextFn,
beforeFinishFn
);
})
.catch(function(error) {
if (error && error.errno === NodeGit.Error.CODE.ITEROVER) {
const calcRewritten = fp.cond([
[fp.isEmpty, fp.constant(null)],
[fp.stubTrue, fp.flow([
fp.split("\n"),
fp.map(fp.split(" "))
])]
]);
const beforeFinishFnPromise = !beforeFinishFn ?
Promise.resolve() :
Promise.all([
readRebaseMetadataFile("onto_name"),
readRebaseMetadataFile("onto"),
readRebaseMetadataFile("head-name").then(calcHeadName),
readRebaseMetadataFile("orig-head"),
readRebaseMetadataFile("rewritten", true).then(calcRewritten)
])
.then(function([
ontoName,
ontoSha,
originalHeadName,
originalHeadSha,
rewritten
]) {
return beforeFinishFn({
ontoName,
ontoSha,
originalHeadName,
originalHeadSha,
rebase,
rewritten
});
});
return beforeFinishFnPromise
.then(function() {
return rebase.finish(signature);
});
} else {
throw error;
}
});
}
if(beforeNextFn) {
beforeNextFnResult = beforeNextFn(rebase);
// if beforeNextFn returns a promise, chain the promise
return Promise.resolve(beforeNextFnResult)
.then(getPromise);
}
return getPromise();
} | javascript | {
"resource": ""
} |
q25334 | lastHunkStagedPromise | train | function lastHunkStagedPromise(result) {
return NodeGit.Diff.indexToWorkdir(repo, index, {
flags:
NodeGit.Diff.OPTION.SHOW_UNTRACKED_CONTENT |
NodeGit.Diff.OPTION.RECURSE_UNTRACKED_DIRS |
(additionalDiffOptions || 0)
})
.then(function(diff) {
return diff.patches();
})
.then(function(patches) {
var pathPatch = patches.filter(function(patch) {
return patch.newFile().path() === filePath;
});
var emptyPatch = false;
if (pathPatch.length > 0) {
// No hunks, unchanged file mode, and no type changes.
emptyPatch = pathPatch[0].size() === 0 &&
pathPatch[0].oldFile().mode() === pathPatch[0].newFile().mode() &&
!pathPatch[0].isTypeChange();
}
if (emptyPatch) {
return index.addByPath(filePath)
.then(function() {
return index.write();
});
}
return result;
});
} | javascript | {
"resource": ""
} |
q25335 | lookupWrapper | train | function lookupWrapper(objectType, lookupFunction) {
lookupFunction = lookupFunction || objectType.lookup;
return function(repo, id, callback) {
if (id instanceof objectType) {
return Promise.resolve(id).then(function(obj) {
obj.repo = repo;
if (typeof callback === "function") {
callback(null, obj);
}
return obj;
}, callback);
}
return lookupFunction(repo, id).then(function(obj) {
obj.repo = repo;
if (typeof callback === "function") {
callback(null, obj);
}
return obj;
}, callback);
};
} | javascript | {
"resource": ""
} |
q25336 | computeBuffer | train | function computeBuffer() {
this._buffer = map.layerPointToLatLng(new L.Point(0,0)).lat -
map.layerPointToLatLng(new L.Point(this.options.snapDistance, 0)).lat;
} | javascript | {
"resource": ""
} |
q25337 | train | function(matrix) {
var skew = this._skew;
if (!skew) {
skew = this._createElement('skew');
this._container.appendChild(skew);
skew.style.behavior = 'url(#default#VML)';
this._skew = skew;
}
// handle skew/translate separately, cause it's broken
var mt = matrix[0].toFixed(8) + " " + matrix[1].toFixed(8) + " " +
matrix[2].toFixed(8) + " " + matrix[3].toFixed(8) + " 0 0";
var offset = Math.floor(matrix[4]).toFixed() + ", " +
Math.floor(matrix[5]).toFixed() + "";
var s = this._container.style;
var l = parseFloat(s.left);
var t = parseFloat(s.top);
var w = parseFloat(s.width);
var h = parseFloat(s.height);
if (isNaN(l)) l = 0;
if (isNaN(t)) t = 0;
if (isNaN(w) || !w) w = 1;
if (isNaN(h) || !h) h = 1;
var origin = (-l / w - 0.5).toFixed(8) + " " + (-t / h - 0.5).toFixed(8);
skew.on = "f";
skew.matrix = mt;
skew.origin = origin;
skew.offset = offset;
skew.on = true;
} | javascript | {
"resource": ""
} | |
q25338 | train | function(e) {
if ((this.dragging && this.dragging.moved()) ||
(this._map.dragging && this._map.dragging.moved())) {
return;
}
this._fireMouseEvent(e);
} | javascript | {
"resource": ""
} | |
q25339 | train | function(matrix) {
var path = this._path;
var i, len, latlng;
var px = L.point(matrix[4], matrix[5]);
var crs = path._map.options.crs;
var transformation = crs.transformation;
var scale = crs.scale(path._map.getZoom());
var projection = crs.projection;
var diff = transformation.untransform(px, scale)
.subtract(transformation.untransform(L.point(0, 0), scale));
// console.time('transform');
// all shifts are in-place
if (path._point) { // L.Circle
path._latlng = projection.unproject(
projection.project(path._latlng)._add(diff));
path._point._add(px);
} else if (path._originalPoints) { // everything else
for (i = 0, len = path._originalPoints.length; i < len; i++) {
latlng = path._latlngs[i];
path._latlngs[i] = projection
.unproject(projection.project(latlng)._add(diff));
path._originalPoints[i]._add(px);
}
}
// holes operations
if (path._holes) {
for (i = 0, len = path._holes.length; i < len; i++) {
for (var j = 0, len2 = path._holes[i].length; j < len2; j++) {
latlng = path._holes[i][j];
path._holes[i][j] = projection
.unproject(projection.project(latlng)._add(diff));
path._holePoints[i][j]._add(px);
}
}
}
// console.timeEnd('transform');
path._updatePath();
} | javascript | {
"resource": ""
} | |
q25340 | train | function(evt) {
var poly = this._shape || this._poly;
var marker = evt.target;
poly.fire('mousedown', L.Util.extend(evt, {
containerPoint: L.DomUtil.getPosition(marker._icon)
.add(poly._map._getMapPanePos())
}));
} | javascript | {
"resource": ""
} | |
q25341 | train | function (obj) { // (LatLng) or (LatLngBounds)
if (!obj) { return this; }
var latLng = L.latLng(obj);
if (latLng !== null) {
obj = latLng;
} else {
obj = L.latLngBounds(obj);
}
if (obj instanceof L.LatLng) {
if (!this._southWest && !this._northEast) {
this._southWest = new L.LatLng(obj.lat, obj.lng);
this._northEast = new L.LatLng(obj.lat, obj.lng);
} else {
this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
}
} else if (obj instanceof L.LatLngBounds) {
this.extend(obj._southWest);
this.extend(obj._northEast);
}
return this;
} | javascript | {
"resource": ""
} | |
q25342 | train | function (center, zoom) {
zoom = zoom === undefined ? this.getZoom() : zoom;
this._resetView(L.latLng(center), this._limitZoom(zoom));
return this;
} | javascript | {
"resource": ""
} | |
q25343 | train | function (offset, bounds) {
if (!bounds) { return offset; }
var viewBounds = this.getPixelBounds(),
newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
return offset.add(this._getBoundsOffset(newBounds, bounds));
} | javascript | {
"resource": ""
} | |
q25344 | train | function (points, sqTolerance) {
var reducedPoints = [points[0]];
for (var i = 1, prev = 0, len = points.length; i < len; i++) {
if (this._sqDist(points[i], points[prev]) > sqTolerance) {
reducedPoints.push(points[i]);
prev = i;
}
}
if (prev < len - 1) {
reducedPoints.push(points[len - 1]);
}
return reducedPoints;
} | javascript | {
"resource": ""
} | |
q25345 | train | function (a, b, bounds, useLastCode) {
var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
codeB = this._getBitCode(b, bounds),
codeOut, p, newCode;
// save 2nd code to avoid calculating it on the next segment
this._lastCode = codeB;
while (true) {
// if a,b is inside the clip window (trivial accept)
if (!(codeA | codeB)) {
return [a, b];
// if a,b is outside the clip window (trivial reject)
} else if (codeA & codeB) {
return false;
// other cases
} else {
codeOut = codeA || codeB;
p = this._getEdgeIntersection(a, b, codeOut, bounds);
newCode = this._getBitCode(p, bounds);
if (codeOut === codeA) {
a = p;
codeA = newCode;
} else {
b = p;
codeB = newCode;
}
}
}
} | javascript | {
"resource": ""
} | |
q25346 | train | function (p, p1, p2, sqDist) {
var x = p1.x,
y = p1.y,
dx = p2.x - x,
dy = p2.y - y,
dot = dx * dx + dy * dy,
t;
if (dot > 0) {
t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
if (t > 1) {
x = p2.x;
y = p2.y;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p.x - x;
dy = p.y - y;
return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
} | javascript | {
"resource": ""
} | |
q25347 | bundleFiles | train | function bundleFiles(files, copy, version) {
var node = new SourceNode(null, null, null, '');
node.add(new SourceNode(null, null, null, copy + '(function (window, document, undefined) {'));
for (var i = 0, len = files.length; i < len; i++) {
var contents = fs.readFileSync(files[i], 'utf8');
if (files[i] === 'src/Leaflet.draw.js') {
contents = contents.replace(
new RegExp('drawVersion = \'.*\''),
'drawVersion = ' + JSON.stringify(version)
);
}
var lines = contents.split('\n');
var lineCount = lines.length;
var fileNode = new SourceNode(null, null, null, '');
fileNode.setSourceContent(files[i], contents);
for (var j = 0; j < lineCount; j++) {
fileNode.add(new SourceNode(j + 1, 0, files[i], lines[j] + '\n'));
}
node.add(fileNode);
node.add(new SourceNode(null, null, null, '\n\n'));
}
node.add(new SourceNode(null, null, null, '}(window, document));'));
var bundle = node.toStringWithSourceMap();
return {
src: bundle.code,
srcmap: bundle.map.toString()
};
} | javascript | {
"resource": ""
} |
q25348 | calculateVersion | train | function calculateVersion(officialRelease, callback) {
var version = require('./package.json').version;
if (officialRelease) {
callback(version);
} else {
git.short(function (str) {
callback(version + '+' + str);
});
}
} | javascript | {
"resource": ""
} |
q25349 | bind | train | function bind(func, obj) {
var slice = Array.prototype.slice;
var args = slice.call(arguments, 2);
return function () {
return func.apply(obj, args.concat(slice.call(arguments)));
};
} | javascript | {
"resource": ""
} |
q25350 | parseURL | train | function parseURL(url) {
const endpoint = {};
const purl = urlParser.parse(url, true);
if (purl.protocol && purl.protocol.startsWith('http')) {
endpoint.protocol = purl.protocol.slice(0, -1);
if (purl.hostname) {
endpoint.hostname = purl.hostname;
if (purl.port) {
endpoint.port = parseInt(purl.port);
}
} else {
throw new Error('InvalidURL: missing hostname.');
}
} else {
throw new Error('InvalidURL: url must start with http or https.');
}
return endpoint;
} | javascript | {
"resource": ""
} |
q25351 | makeRealPem | train | function makeRealPem(pem) {
let result = null;
if (typeof pem === 'string') {
result = pem.replace(/-----BEGIN -----/, '-----BEGIN CERTIFICATE-----');
result = result.replace(/-----END -----/, '-----END CERTIFICATE-----');
result = result.replace(/-----([^-]+) ECDSA ([^-]+)-----([^-]*)-----([^-]+) ECDSA ([^-]+)-----/, '-----$1 EC $2-----$3-----$4 EC $5-----');
}
return result;
} | javascript | {
"resource": ""
} |
q25352 | verifyTransactionName | train | function verifyTransactionName(name) {
if (typeof name !== 'string' || name.length === 0) {
const msg = util.format('Transaction name must be a non-empty string: %j', name);
logger.error('verifyTransactionName:', msg);
throw new Error(msg);
}
} | javascript | {
"resource": ""
} |
q25353 | verifyNamespace | train | function verifyNamespace(namespace) {
if (namespace && typeof namespace !== 'string') {
const msg = util.format('Namespace must be a non-empty string: %j', namespace);
logger.error('verifyNamespace:', msg);
throw new Error(msg);
}
} | javascript | {
"resource": ""
} |
q25354 | verifyArguments | train | function verifyArguments(args) {
const isInvalid = args.some((arg) => typeof arg !== 'string');
if (isInvalid) {
const argsString = args.map((arg) => util.format('%j', arg)).join(', ');
const msg = util.format('Transaction arguments must be strings: %s', argsString);
logger.error('verifyArguments:', msg);
throw new Error(msg);
}
} | javascript | {
"resource": ""
} |
q25355 | _stringToSignature | train | function _stringToSignature(string_signatures) {
const signatures = [];
for (let signature of string_signatures) {
// check for properties rather than object type
if (signature && signature.signature_header && signature.signature) {
logger.debug('_stringToSignature - signature is protobuf');
} else {
logger.debug('_stringToSignature - signature is string');
const signature_bytes = Buffer.from(signature, 'hex');
signature = _configtxProto.ConfigSignature.decode(signature_bytes);
}
signatures.push(signature);
}
return signatures;
} | javascript | {
"resource": ""
} |
q25356 | _getNetworkConfig | train | function _getNetworkConfig(loadConfig, client) {
let network_config = null;
let network_data = null;
let network_config_loc = null;
if (typeof loadConfig === 'string') {
network_config_loc = path.resolve(loadConfig);
logger.debug('%s - looking at absolute path of ==>%s<==', '_getNetworkConfig', network_config_loc);
const file_data = fs.readFileSync(network_config_loc);
const file_ext = path.extname(network_config_loc);
// maybe the file is yaml else has to be JSON
if ((/(yml|yaml)$/i).test(file_ext)) {
network_data = yaml.safeLoad(file_data);
} else {
network_data = JSON.parse(file_data);
}
} else {
network_data = loadConfig;
}
try {
if (!network_data) {
throw new Error('missing configuration data');
}
if (!network_data.version) {
throw new Error('"version" is missing');
}
const parsing = Client.getConfigSetting('network-config-schema');
if (!parsing) {
throw new Error('missing "network-config-schema" configuration setting');
}
const pieces = network_data.version.toString().split('.');
const version = pieces[0] + '.' + pieces[1];
if (!parsing[version]) {
throw new Error('common connection profile has an unknown "version"');
}
const NetworkConfig = require(parsing[version]);
network_config = new NetworkConfig(network_data, client, network_config_loc);
} catch (error) {
throw new Error(util.format('Invalid common connection profile due to %s', error.message));
}
return network_config;
} | javascript | {
"resource": ""
} |
q25357 | _getProposalResponseResults | train | function _getProposalResponseResults(proposal_response) {
if (!proposal_response.payload) {
throw new Error('Parameter must be a ProposalResponse Object');
}
const payload = _responseProto.ProposalResponsePayload.decode(proposal_response.payload);
const extension = _proposalProto.ChaincodeAction.decode(payload.extension);
// TODO should we check the status of this action
logger.debug('_getWriteSet - chaincode action status:%s message:%s', extension.response.status, extension.response.message);
// return a buffer object which has an equals method
return extension.results.toBuffer();
} | javascript | {
"resource": ""
} |
q25358 | printDebugWithCode | train | function printDebugWithCode(msg, code) {
// eslint-disable-next-line no-console
console.log(`\n\n${msg}:\n`);
// eslint-disable-next-line no-console
console.log(`${highlightFn(code)}\n`);
} | javascript | {
"resource": ""
} |
q25359 | Polygon | train | function Polygon( sides, x, y, tileSize, ctx, num, analyser, streamData, tiles, fgRotation ){
this.analyser = analyser;
this.sides = sides;
this.tileSize = tileSize;
this.ctx = ctx;
this.tiles = tiles;
this.fgRotation = fgRotation;
/*
The number of the tile, starting at 0
*/
this.num = num;
/*
The highest colour value, which then fades out
*/
this.high = 0;
/*
Increase this value to fade out faster.
*/
this.decay = this.num > 42 ? 1.5 : 2;
/* For highlighted stroke effect
figure out the x and y coordinates of the center of the polygon based on the
60 degree XY axis coordinates passed in
*/
this.highlight = 0;
var step = Math.round(Math.cos(Math.PI/6)*tileSize*2);
this.y = Math.round(step * Math.sin(Math.PI/3) * -y );
this.x = Math.round(x * step + y * step/2 );
/*
Calculate the vertices of the polygon
*/
this.vertices = [];
for (var i = 1; i <= this.sides;i += 1) {
x = this.x + this.tileSize * Math.cos(i * 2 * Math.PI / this.sides + Math.PI/6);
y = this.y + this.tileSize * Math.sin(i * 2 * Math.PI / this.sides + Math.PI/6);
this.vertices.push([x, y]);
}
this.streamData = streamData;
} | javascript | {
"resource": ""
} |
q25360 | Star | train | function Star( x, y, starSize, ctx, fgCanvas, analyser, streamData ){
this.x = x;
this.y = y;
this.angle = Math.atan( Math.abs(y) / Math.abs(x) );
this.starSize = starSize;
this.ctx = ctx;
this.high = 0;
this.fgCanvas = fgCanvas;
this.analyser = analyser;
this.streamData = streamData;
} | javascript | {
"resource": ""
} |
q25361 | train | function(stream, state) {
if (stream.match(settings.leftDelimiter, true)) {
if (stream.eat("*")) {
return helpers.chain(stream, state, parsers.inBlock("comment", "*" + settings.rightDelimiter));
} else {
// Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode
state.depth++;
var isEol = stream.eol();
var isFollowedByWhitespace = /\s/.test(stream.peek());
if (settings.smartyVersion === 3 && settings.leftDelimiter === "{" && (isEol || isFollowedByWhitespace)) {
state.depth--;
return null;
} else {
state.tokenize = parsers.smarty;
last = "startTag";
return "tag";
}
}
} else {
stream.next();
return null;
}
} | javascript | {
"resource": ""
} | |
q25362 | jsbinShowEdit | train | function jsbinShowEdit(options) {
'use strict';
if (window.location.hash === '#noedit') {return;}
var moveTimer, over,
doc = document,
aEL = 'addEventListener',
path = options.root + window.location.pathname,
style = doc.createElement('link'),
btn = doc.createElement('a');
// Add button:
btn.id = 'edit-with-js-bin';
btn.href = path + (path.slice(-1) === '/' ? '' : '/') + 'edit';
btn.innerHTML = 'Edit in JS Bin <img src="' + options['static'] + '/images/favicon.png" width="16" height="16">';
doc.documentElement.appendChild(btn);
// Style button:
style.setAttribute('rel', 'stylesheet');
style.setAttribute('href', options['static'] + '/css/edit.css');
doc.documentElement.appendChild(style);
// show / hide button:
btn.onmouseover = btn.onmouseout = function() {
over = !over;
(over ? show : hide)();
};
function show() {
clearTimeout(moveTimer);
btn.style.top = '0';
moveTimer = setTimeout(hide, 2000);
}
function hide() {
if (!over) { btn.style.top = '-60px'; }
}
show();
if (aEL in doc) {doc[aEL]('mousemove', show, false);}
else {doc.attachEvent('mousemove', show);}
} | javascript | {
"resource": ""
} |
q25363 | normal | train | function normal(source, setState) {
if (source.eatWhile(whiteCharRE)) {
return null;
}
var ch = source.next();
if (specialRE.test(ch)) {
if (ch == '{' && source.eat('-')) {
var t = "comment";
if (source.eat('#')) {
t = "meta";
}
return switchState(source, setState, ncomment(t, 1));
}
return null;
}
if (ch == '\'') {
if (source.eat('\\')) {
source.next(); // should handle other escapes here
}
else {
source.next();
}
if (source.eat('\'')) {
return "string";
}
return "error";
}
if (ch == '"') {
return switchState(source, setState, stringLiteral);
}
if (largeRE.test(ch)) {
source.eatWhile(idRE);
if (source.eat('.')) {
return "qualifier";
}
return "variable-2";
}
if (smallRE.test(ch)) {
source.eatWhile(idRE);
return "variable";
}
if (digitRE.test(ch)) {
if (ch == '0') {
if (source.eat(/[xX]/)) {
source.eatWhile(hexitRE); // should require at least 1
return "integer";
}
if (source.eat(/[oO]/)) {
source.eatWhile(octitRE); // should require at least 1
return "number";
}
}
source.eatWhile(digitRE);
var t = "number";
if (source.match(/^\.\d+/)) {
t = "number";
}
if (source.eat(/[eE]/)) {
t = "number";
source.eat(/[-+]/);
source.eatWhile(digitRE); // should require at least 1
}
return t;
}
if (ch == "." && source.eat("."))
return "keyword";
if (symbolRE.test(ch)) {
if (ch == '-' && source.eat(/-/)) {
source.eatWhile(/-/);
if (!source.eat(symbolRE)) {
source.skipToEnd();
return "comment";
}
}
var t = "variable";
if (ch == ':') {
t = "variable-2";
}
source.eatWhile(symbolRE);
return t;
}
return "error";
} | javascript | {
"resource": ""
} |
q25364 | train | function (err, req, res, next) {
err = this.coerceError(err);
if (err instanceof errors.NotFound && req.accepts('html')) {
if (err instanceof errors.BinNotFound) {
if (req.editor) {
return (new BinHandler(this.sandbox)).notFound(req, res, next);
}
}
return this.renderErrorPage('error', err, req, res);
} else if (err instanceof errors.HTTPError) {
// return this.renderError(err, req, res);
return this.renderErrorPage(err.status, err, req, res);
}
if (err) {
// console.error(err.stack);
}
next(err);
} | javascript | {
"resource": ""
} | |
q25365 | train | function (req, res) {
var error = new errors.NotFound('Page Does Not Exist');
if (req.accepts('html') && (req.url.indexOf('/api/') !== 0)) {
this.renderErrorPage('404', error, req, res);
} else {
this.renderError(error, req, res);
}
} | javascript | {
"resource": ""
} | |
q25366 | train | function (err, req, res) {
console.error('uncaughtError', req.method + ' ' + req.url);
this.sendErrorReport(err, req);
if (req.accepts('html')) {
this.renderErrorPage('error', err, req, res);
} else {
var error = new errors.HTTPError(500, 'Internal Server Error');
this.renderError(error, req, res);
}
} | javascript | {
"resource": ""
} | |
q25367 | train | function (err) {
var status = typeof err === 'number' ? err : err.status;
if (!(err instanceof errors.HTTPError) && status) {
return errors.create(status, err.message);
}
return err;
} | javascript | {
"resource": ""
} | |
q25368 | formData | train | function formData(form) {
var length = form.length;
var data = {};
var value;
var el;
var type;
var name;
var append = function (data, name, value) {
if (data[name] === undefined) {
data[name] = value;
} else {
if (typeof data[name] === 'string') {
data[name] = [data[name]];
}
data[name].push(value);
}
};
for (var i = 0; i < length; i++) {
el = form[i];
value = el.value;
type = el.type;
name = el.name;
if (type === 'radio') {
if (el.checked) {
append(data, name, value);
}
} else if (type === 'checkbox') {
if (data[name] === undefined) {
data[name] = [];
}
if (el.checked) {
append(data, name, value);
}
} else {
append(data, name, value);
}
}
return data;
} | javascript | {
"resource": ""
} |
q25369 | train | function() {
var htmlState = htmlMode.startState();
var rubyState = rubyMode.startState();
return {
htmlState: htmlState,
rubyState: rubyState,
indented: 0,
previousToken: { style: null, indented: 0},
tokenize: html
};
} | javascript | {
"resource": ""
} | |
q25370 | htmlDispatch | train | function htmlDispatch(stream, state) {
if (stream.match(scriptStartRegex, false)) {
state.token=scriptingDispatch;
return scriptingMode.token(stream, state.scriptState);
}
else
return htmlMixedMode.token(stream, state.htmlState);
} | javascript | {
"resource": ""
} |
q25371 | train | function(cm, key) {
var command;
var vim = maybeInitVimState(cm);
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.enteredMacroMode) {
if (key == 'q') {
actions.exitMacroRecordMode();
vim.inputState = new InputState();
return;
}
}
if (key == '<Esc>') {
// Clear input state and get back to normal mode.
vim.inputState = new InputState();
if (vim.visualMode) {
exitVisualMode(cm);
}
return;
}
// Enter visual mode when the mouse selects text.
if (!vim.visualMode &&
!cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
vim.visualMode = true;
vim.visualLine = false;
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
cm.on('mousedown', exitVisualMode);
}
if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
// Have to special case 0 since it's both a motion and a number.
command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
}
if (!command) {
if (isNumber(key)) {
// Increment count unless count is 0 and key is 0.
vim.inputState.pushRepeatDigit(key);
}
return;
}
if (command.type == 'keyToKey') {
// TODO: prevent infinite recursion.
for (var i = 0; i < command.toKeys.length; i++) {
this.handleKey(cm, command.toKeys[i]);
}
} else {
if (macroModeState.enteredMacroMode) {
logKey(macroModeState, key);
}
commandDispatcher.processCommand(cm, vim, command);
}
} | javascript | {
"resource": ""
} | |
q25372 | InputState | train | function InputState() {
this.prefixRepeat = [];
this.motionRepeat = [];
this.operator = null;
this.operatorArgs = null;
this.motion = null;
this.motionArgs = null;
this.keyBuffer = []; // For matching multi-key commands.
this.registerName = null; // Defaults to the unamed register.
} | javascript | {
"resource": ""
} |
q25373 | train | function(name) {
if (!this.isValidRegister(name)) {
return this.unamedRegister;
}
name = name.toLowerCase();
if (!this.registers[name]) {
this.registers[name] = new Register();
}
return this.registers[name];
} | javascript | {
"resource": ""
} | |
q25374 | getFullyMatchedCommandOrNull | train | function getFullyMatchedCommandOrNull(command) {
if (keys.length < command.keys.length) {
// Matches part of a multi-key command. Buffer and wait for next
// stroke.
inputState.keyBuffer.push(key);
return null;
} else {
if (command.keys[keys.length - 1] == 'character') {
inputState.selectedCharacter = selectedCharacter;
}
// Clear the buffer since a full match was found.
inputState.keyBuffer = [];
return command;
}
} | javascript | {
"resource": ""
} |
q25375 | train | function(cm, operatorArgs, _vim, curStart, curEnd) {
// If the ending line is past the last line, inclusive, instead of
// including the trailing \n, include the \n before the starting line
if (operatorArgs.linewise &&
curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) {
curStart.line--;
curStart.ch = lineLength(cm, curStart.line);
}
vimGlobalState.registerController.pushText(
operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd),
operatorArgs.linewise);
cm.replaceRange('', curStart, curEnd);
if (operatorArgs.linewise) {
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
} else {
cm.setCursor(curStart);
}
} | javascript | {
"resource": ""
} | |
q25376 | isInRange | train | function isInRange(pos, start, end) {
if (typeof pos != 'number') {
// Assume it is a cursor position. Get the line number.
pos = pos.line;
}
if (start instanceof Array) {
return inArray(pos, start);
} else {
if (end) {
return (pos >= start && pos <= end);
} else {
return pos == start;
}
}
} | javascript | {
"resource": ""
} |
q25377 | buildVimKeyMap | train | function buildVimKeyMap() {
/**
* Handle the raw key event from CodeMirror. Translate the
* Shift + key modifier to the resulting letter, while preserving other
* modifers.
*/
// TODO: Figure out a way to catch capslock.
function cmKeyToVimKey(key, modifier) {
var vimKey = key;
if (isUpperCase(vimKey)) {
// Convert to lower case if shift is not the modifier since the key
// we get from CodeMirror is always upper case.
if (modifier == 'Shift') {
modifier = null;
}
else {
vimKey = vimKey.toLowerCase();
}
}
if (modifier) {
// Vim will parse modifier+key combination as a single key.
vimKey = modifier.charAt(0) + '-' + vimKey;
}
var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
vimKey = specialKey ? specialKey : vimKey;
vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
return vimKey;
}
// Closure to bind CodeMirror, key, modifier.
function keyMapper(vimKey) {
return function(cm) {
CodeMirror.Vim.handleKey(cm, vimKey);
};
}
var cmToVimKeymap = {
'nofallthrough': true,
'style': 'fat-cursor'
};
function bindKeys(keys, modifier) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!modifier && inArray(key, specialSymbols)) {
// Wrap special symbols with '' because that's how CodeMirror binds
// them.
key = "'" + key + "'";
}
var vimKey = cmKeyToVimKey(keys[i], modifier);
var cmKey = modifier ? modifier + '-' + key : key;
cmToVimKeymap[cmKey] = keyMapper(vimKey);
}
}
bindKeys(upperCaseAlphabet);
bindKeys(upperCaseAlphabet, 'Shift');
bindKeys(upperCaseAlphabet, 'Ctrl');
bindKeys(specialSymbols);
bindKeys(specialSymbols, 'Ctrl');
bindKeys(numbers);
bindKeys(numbers, 'Ctrl');
bindKeys(specialKeys);
bindKeys(specialKeys, 'Ctrl');
return cmToVimKeymap;
} | javascript | {
"resource": ""
} |
q25378 | onChange | train | function onChange(_cm, changeObj) {
var macroModeState = vimGlobalState.macroModeState;
var lastChange = macroModeState.lastInsertModeChanges;
while (changeObj) {
lastChange.expectCursorActivityForChange = true;
if (changeObj.origin == '+input' || changeObj.origin == 'paste'
|| changeObj.origin === undefined /* only in testing */) {
var text = changeObj.text.join('\n');
lastChange.changes.push(text);
}
// Change objects may be chained with next.
changeObj = changeObj.next;
}
} | javascript | {
"resource": ""
} |
q25379 | onCursorActivity | train | function onCursorActivity() {
var macroModeState = vimGlobalState.macroModeState;
var lastChange = macroModeState.lastInsertModeChanges;
if (lastChange.expectCursorActivityForChange) {
lastChange.expectCursorActivityForChange = false;
} else {
// Cursor moved outside the context of an edit. Reset the change.
lastChange.changes = [];
}
} | javascript | {
"resource": ""
} |
q25380 | onKeyEventTargetKeyDown | train | function onKeyEventTargetKeyDown(e) {
var macroModeState = vimGlobalState.macroModeState;
var lastChange = macroModeState.lastInsertModeChanges;
var keyName = CodeMirror.keyName(e);
function onKeyFound() {
lastChange.changes.push(new InsertModeKey(keyName));
return true;
}
if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
}
} | javascript | {
"resource": ""
} |
q25381 | repeatLastEdit | train | function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
var macroModeState = vimGlobalState.macroModeState;
macroModeState.inReplay = true;
var isAction = !!vim.lastEditActionCommand;
var cachedInputState = vim.inputState;
function repeatCommand() {
if (isAction) {
commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
} else {
commandDispatcher.evalInput(cm, vim);
}
}
function repeatInsert(repeat) {
if (macroModeState.lastInsertModeChanges.changes.length > 0) {
// For some reason, repeat cw in desktop VIM will does not repeat
// insert mode changes. Will conform to that behavior.
repeat = !vim.lastEditActionCommand ? 1 : repeat;
repeatLastInsertModeChanges(cm, repeat, macroModeState);
}
}
vim.inputState = vim.lastEditInputState;
if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
// o and O repeat have to be interlaced with insert repeats so that the
// insertions appear on separate lines instead of the last line.
for (var i = 0; i < repeat; i++) {
repeatCommand();
repeatInsert(1);
}
} else {
if (!repeatForInsert) {
// Hack to get the cursor to end up at the right place. If I is
// repeated in insert mode repeat, cursor will be 1 insert
// change set left of where it should be.
repeatCommand();
}
repeatInsert(repeat);
}
vim.inputState = cachedInputState;
if (vim.insertMode && !repeatForInsert) {
// Don't exit insert mode twice. If repeatForInsert is set, then we
// were called by an exitInsertMode call lower on the stack.
exitInsertMode(cm);
}
macroModeState.inReplay = false;
} | javascript | {
"resource": ""
} |
q25382 | prettyDate | train | function prettyDate(time){
'use strict';
// Remy Sharp edit: July 13, 2014 specific to JS Bin
// Need to replace Z in ISO8601 timestamp with +0000 so prettyDate() doesn't
// completely remove it (and parse the date using the local timezone).
var date = new Date((time || '').replace('Z', '+0000').replace(/-/g,'/').replace(/[TZ]/g,' ')),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
dayDiff = Math.floor(diff / 86400);
if ( isNaN(dayDiff) || dayDiff < 0 ) {
return;
}
return dayDiff === 0 && (
diff < 60 && 'just now' ||
diff < 120 && '1 minute ago' ||
diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago' ||
diff < 7200 && '1 hour ago' ||
diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago') ||
shortDate(date.getTime());
} | javascript | {
"resource": ""
} |
q25383 | train | function(name, file) {
if (!ternLoaded[name]) {
$.ajax({
url: file,
dataType: 'json',
success: function(data) {
addTernDefinition(data);
ternLoaded[name] = true;
}
});
}
} | javascript | {
"resource": ""
} | |
q25384 | train | function(name, file) {
if (!ternLoaded[name]) {
$.ajax({
url: file,
dataType: 'script',
success: function(data) {
ternServer.server.addFile(name, data);
ternLoaded[name] = true;
}
});
}
} | javascript | {
"resource": ""
} | |
q25385 | train | function (data, fn) {
this.store.generateBinId(data.length, 0, function generateBinId(err, id) {
if (err) {
return fn(err);
}
data.url = id;
data.revision = 1;
data.latest = true;
data.streamingKey = this.createStreamingKey(id, data.revision);
this.store.setBin(data, function (err, id) {
data.id = id;
fn(err || null, err ? undefined : data);
});
}.bind(this));
} | javascript | {
"resource": ""
} | |
q25386 | train | function (data, fn) {
data.streamingKey = this.createStreamingKey(data.url, data.revision);
this.store.setBin(data, function (err, id) {
data.id = id;
fn(err || null, err ? undefined : data);
});
} | javascript | {
"resource": ""
} | |
q25387 | train | function (req, res, next) {
// Check request's accepts header for event-stream. Move on if it doesn't
// support it.
if (!req.headers.accept || req.headers.accept.indexOf('text/event-stream') === -1) {
return next();
}
// Restore or create a session for the bin
var session = utils.sessionForBin(req.bin, true),
key = utils.keyForBin(req.bin),
userSession = req.session,
checksum = req.param('checksum'),
// cache the bin because req.bin is just a reference and gets changed when
// the revision gets bumped.
bin = req.bin,
keepalive = null,
close, closeTimer;
if (isOwnerWithWrite(userSession, bin, checksum) && pendingToKillStreaming[key]) {
clearTimeout(pendingToKillStreaming[key] || null);
}
openSpikes += 1;
metrics.gauge('spike.open', openSpikes);
// console.log('STREAM ACCEPTED', req.originalUrl);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache'
});
res.write('id: 0\n\n');
session.res.push(res);
if (req.keepLatest) {
if (!sessionsFromUser[req.user.name]) {
sessionsFromUser[req.user.name] = [];
}
sessionsFromUser[req.user.name].push({ key: key, res: res });
}
keepalive = setInterval(function () {
if (!res.connection.writable) {
return close();
}
res.write('id: 0\n\n');
}, 15 * 1000);
// FIXME this will break when using /rem/last/ as req.bin won't be the same bin anymore.
var closed = false;
close = function () {
if (closed) {
return;
}
closed = true;
if (isOwnerWithWrite(userSession, bin, checksum)) {
// this means the owner has disconnected from jsbin, and it's possible
// that we can remove their write access to the bin (and thus not add
// streaming to full previews). So we set a timer, and if this eventsource
// isn't reopened then we assume it's closed. If this eventsource *does*
// reopen, then we clear the timer, and they can continue to stream.
pendingToKillStreaming[key] = setTimeout(function () {
binModel.updateBinData(req.bin, {streaming_key: ''}, function (error) {
if (error) {
console.error(error);
}
});
}, 24 * 60 * 1000); // leave it open for 24 hours
}
clearInterval(keepalive);
clearTimeout(closeTimer);
utils.removeConnection(utils.keyForBin(req.bin), res);
// ping stats
spike.ping(req.bin, {}, true);
};
// every 5 minutes, let's let them reconnect
closeTimer = setTimeout(function () {
res.end();
req.emit('close');
}, 15 * 60 * 1000);
res.socket.on('close', close);
req.on('close', close);
res.req = req;
// ping stats
spike.ping(req.bin, {}, true);
} | javascript | {
"resource": ""
} | |
q25388 | train | function (bin) {
var session = utils.sessionForBin(bin);
if (session) {
session.res.forEach(function (res) {
res.write('event: reload\ndata: 0\n\n');
if (res.ajax) {
res.end(); // lets older browsers finish their xhr request
res.req.emit('close');
}
});
}
} | javascript | {
"resource": ""
} | |
q25389 | train | function (oldBin, newBin) {
if (!newBin || !newBin.url) {
// FIXME this is just patching a problem, the source of which I'm not sure
console.error('spike/index.js#bump-revision - missing newBin', newBin);
return;
}
var oldSession = utils.sessionForBin(oldBin),
oldKey = utils.keyForBin(oldBin),
newSession = utils.sessionForBin(newBin, true),
newKey = utils.keyForBin(newBin);
if (!oldSession) { return; }
// Move connections from one session to another
oldSession.res.forEach(function (res) {
// Add the connection to the new session's list
newSession.res.push(res);
// Upgrade the connection with the new bin
res.req.bin = newBin;
// Tell the client to bump their revision
res.write(utils.makeEvent('bump-revision', newKey));
if (res.ajax) {
// lets older browsers finish their xhr request
res.end();
res.req.emit('close');
}
return false;
});
// There should be no more connections to this bin, so byebye!
oldSession.res = [];
delete sessions[oldKey];
} | javascript | {
"resource": ""
} | |
q25390 | train | function (bin, data, statsRequest) {
var id = bin.id,
delayTrigger = 500;
if (!pending[id]) {
pending[id] = {};
}
pending[id].bin = bin;
pending[id][data.panelId] = utils.process(data, bin.settings);
// Clear the previous ping
clearTimeout(pending[id].timer);
// NOTE: this will only fire once per jsbin session -
// not for every panel sent - because we clear the timer
pending[id].timer = setTimeout(function () {
var session = utils.sessionForBin(bin),
data = null,
ping = pending[id];
if (!ping) { return; }
// Javascript and HTML cause reloads. CSS is injected.
data = ping.javascript || ping.html || ping.css || (statsRequest ? {} : false);
// Forget this ping, it's done with now
delete pending[id];
if (!data) { return; }
if (!session) { return; }
// Send the update to all connected sessions in original and raw flavours
session.res.forEach(function (res) {
var raw = data.raw || data.content;
if (!res.req.stats) {
res.write(utils.makeEvent(data.panelId, raw));
res.write(utils.makeEvent(data.panelId + ':processed', data.content));
}
res.write(utils.makeEvent('stats', { connections: session.res.filter(function (res) {
return !res.req.stats;
}).length }));
if (res.ajax && !statsRequest) {
res.end(); // lets older browsers finish their xhr request
res.req.emit('close');
}
});
}, delayTrigger);
} | javascript | {
"resource": ""
} | |
q25391 | train | function () {
return function (req, res, next) {
var headers = req.header('Access-Control-Request-Headers');
var origin = req.header('Origin');
// TODO should this check if the request is via the API?
if (req.method === 'OPTIONS' || (req.method === 'GET' && req.headers.origin)) {
res.header({
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Headers': headers,
'Access-Control-Allow-Credentials': 'true'
});
req.cors = true;
}
if (req.method === 'OPTIONS') {
res.send(204);
} else {
next();
}
};
} | javascript | {
"resource": ""
} | |
q25392 | train | function (options) {
var ignore = options.ignore || [],
csrf = csurf(options),
always = {OPTIONS: 1, GET: 1, HEAD: 1};
return function (req, res, next) {
if (always[req.method]) {
return csrf(req, res, next);
} else {
var url = parse(req.url);
var skipCSRF = false;
ignore.forEach(function(matcher) {
if (typeof matcher === 'string') {
if (matcher === url.pathname) {
skipCSRF = true;
}
} else {
// regular expression matcher
if (url.pathname.match(matcher)) {
skipCSRF = true;
}
}
});
if (skipCSRF) {
next();
} else {
return csrf(req, res, next);
}
}
};
} | javascript | {
"resource": ""
} | |
q25393 | train | function () {
return function (req, res, next) {
var apphost = config.url.host,
outputHost = undefsafe(config, 'security.preview'),
host = req.header('Host', ''),
offset = host.indexOf(apphost);
if (host === outputHost) {
offset = host.indexOf(outputHost);
}
if (offset > 0) {
// Slice the host from the subdomain and subtract 1 for
// trailing . on the subdomain.
req.subdomain = host.slice(0, offset - 1);
}
next();
};
} | javascript | {
"resource": ""
} | |
q25394 | train | function (options) {
// Parse a string representing a file size and convert it into bytes.
// A number on it's own will be assumed to be bytes. A multiple such as
// "k" or "m" can be appended to the string to handle larger numbers. This
// is case insensitive and uses powers of 1024 rather than (1000).
// So both 1kB and 1kb == 1024.
function parseLimit(string) {
var matches = ('' + string).toLowerCase().match(regexp),
bytes = null, power;
if (matches) {
bytes = parseFloat(matches[1]);
power = powers[matches[2]];
if (bytes && power) {
bytes = Math.pow(bytes * 1024, power);
}
}
return bytes || null;
}
var powers = { k: 1, m: 2, g: 3, t: 4 },
regexp = /^(\d+(?:.\d+)?)\s*([kmgt]?)b?$/,
limit = options && parseLimit(options.limit);
return function (req, res, next) {
if (limit) {
var contentLength = parseInt(req.header('Content-Length', 0), 10),
message = 'Sorry, the content you have uploaded is larger than JS Bin can handle. Max size is ' + options.limit;
if (limit && contentLength > limit) {
return next(new errors.RequestEntityTooLarge(message));
}
}
next();
};
} | javascript | {
"resource": ""
} | |
q25395 | train | function () {
return function (req, res, next) {
var userModel = models.user;
if (req.url.indexOf('/api') === 0) {
req.isApi = true;
// Make the API requests stateless by removin the cookie set by middleware cookieSession
onHeaders(res, () => res.removeHeader('Set-Cookie'));
if (config.api.requireSSL) {
if (!req.secure && (String(req.headers['x-forwarded-proto']).toLowerCase() !== 'https') ) {
res.status(403); // forbidden
res.json({ error: 'All API requests must be made over SSL/TLS' });
return;
}
}
if (req.query.api_key) {
req.apiKey = req.query.api_key;
} else if (req.headers.authorization) {
req.apiKey = req.headers.authorization.replace(/token\s/i,'');
}
var validateApiRequest = function () {
if (config.api.allowAnonymousReadWrite || (config.api.allowAnonymousRead && req.method === 'GET')) {
next();
} else {
if (!req.apiKey) {
res.status(403); // forbidden
res.json({ error: 'You need to provide a valid API key when using this API' });
} else {
next();
}
}
};
if (req.apiKey) {
userModel.loadByApiKey(req.apiKey, function (err, user) {
if (err) {
return next(err);
}
if (user) {
req.session.user = user;
// since we're setting the user session via the API
// we need to ensure that the user is totally trashed
// from the session to avoid abuse directly in the browser
// i.e. stolen api key can only create bins, nothing more.
onHeaders(res, () => delete req.session);
validateApiRequest();
} else {
res.status(403); // forbidden
res.json({ error: 'The API key you provided is not valid' });
}
});
} else {
validateApiRequest();
}
} else {
next();
}
};
} | javascript | {
"resource": ""
} | |
q25396 | train | function (cmd, cb) {
var internalCmd = internalCommand(cmd);
if (internalCmd) {
return cb(['info', internalCmd]);
}
$document.trigger('console:run', cmd);
} | javascript | {
"resource": ""
} | |
q25397 | train | function (cmd, blind, response) {
var toecho = '';
if (typeof cmd !== 'string') {
toecho = cmd.echo;
blind = cmd.blind;
response = cmd.response;
cmd = cmd.cmd;
} else {
toecho = cmd;
}
cmd = trim(cmd);
// Add the command to the user's history – unless this was blind
if (!blind) {
history.push(cmd.trim());
setHistory(history);
}
// Show the user what they typed
echo(toecho.trim());
// If we were handed a response, show the response straight away – otherwise
// runs it
if (response) return showResponse(response);
run(cmd, showResponse);
setCursorTo('');
} | javascript | {
"resource": ""
} | |
q25398 | train | function (response) {
// order so it appears at the top
var el = document.createElement('div'),
li = document.createElement('li'),
span = document.createElement('span'),
parent = output.parentNode;
historyPosition = history.length;
if (typeof response === 'undefined') return;
el.className = 'response';
span.innerHTML = response[1];
if (response[0] != 'info') prettyPrint([span]);
el.appendChild(span);
li.className = response[0];
li.innerHTML = '<span class="gutter"></span>';
li.appendChild(el);
appendLog(li);
exec.value = '';
if (enableCC) {
try {
if (jsbin.panels && jsbin.panels.focused.id === 'console') {
if (!jsbin.embed) {
getCursor().focus();
}
document.execCommand('selectAll', false, null);
document.execCommand('delete', false, null);
}
} catch (e) {}
}
} | javascript | {
"resource": ""
} | |
q25399 | getMostPowerful | train | function getMostPowerful(state) {
var context = state.cmdState;
for (var i = context.length - 1; i >= 0; i--) {
var plug = context[i];
if (plug.name == "DEFAULT") {
continue;
}
return plug;
}
return { styleIdentifier: function() { return null; } };
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.