_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q27000 | addMiter | train | function addMiter (v, coordCurr, normPrev, normNext, miter_len_sq, isBeginning, context) {
var miterVec = createMiterVec(normPrev, normNext);
// Miter limit: if miter join is too sharp, convert to bevel instead
if (Vector.lengthSq(miterVec) > miter_len_sq) {
addJoin(JOIN_TYPE.bevel, v, coordCurr, normPrev, normNext, isBeginning, context);
}
else {
addVertex(coordCurr, miterVec, miterVec, 1, v, context, 1);
addVertex(coordCurr, miterVec, miterVec, 0, v, context, -1);
if (!isBeginning) {
indexPairs(1, context);
}
}
} | javascript | {
"resource": ""
} |
q27001 | addJoin | train | function addJoin(join_type, v, coordCurr, normPrev, normNext, isBeginning, context) {
var miterVec = createMiterVec(normPrev, normNext);
var isClockwise = (normNext[0] * normPrev[1] - normNext[1] * normPrev[0] > 0);
if (context.texcoord_index != null) {
zero_v[1] = v;
one_v[1] = v;
}
if (isClockwise){
addVertex(coordCurr, miterVec, miterVec, 1, v, context, 1);
addVertex(coordCurr, normPrev, miterVec, 0, v, context, -1);
if (!isBeginning) {
indexPairs(1, context);
}
addFan(coordCurr,
// extrusion vector of first vertex
Vector.neg(normPrev),
// controls extrude distance of pivot vertex
miterVec,
// extrusion vector of last vertex
Vector.neg(normNext),
// line normal (unused here)
miterVec,
// uv coordinates
zero_v, one_v, zero_v,
false, (join_type === JOIN_TYPE.bevel), context
);
addVertex(coordCurr, miterVec, miterVec, 1, v, context, 1);
addVertex(coordCurr, normNext, miterVec, 0, v, context, -1);
} else {
addVertex(coordCurr, normPrev, miterVec, 1, v, context, 1);
addVertex(coordCurr, miterVec, miterVec, 0, v, context, -1);
if (!isBeginning) {
indexPairs(1, context);
}
addFan(coordCurr,
// extrusion vector of first vertex
normPrev,
// extrusion vector of pivot vertex
Vector.neg(miterVec),
// extrusion vector of last vertex
normNext,
// line normal for offset
miterVec,
// uv coordinates
one_v, zero_v, one_v,
false, (join_type === JOIN_TYPE.bevel), context
);
addVertex(coordCurr, normNext, miterVec, 1, v, context, 1);
addVertex(coordCurr, miterVec, miterVec, 0, v, context, -1);
}
} | javascript | {
"resource": ""
} |
q27002 | indexPairs | train | function indexPairs(num_pairs, context){
var vertex_elements = context.vertex_data.vertex_elements;
var num_vertices = context.vertex_data.vertex_count;
var offset = num_vertices - 2 * num_pairs - 2;
for (var i = 0; i < num_pairs; i++){
vertex_elements.push(offset + 2 * i + 2);
vertex_elements.push(offset + 2 * i + 1);
vertex_elements.push(offset + 2 * i + 0);
vertex_elements.push(offset + 2 * i + 2);
vertex_elements.push(offset + 2 * i + 3);
vertex_elements.push(offset + 2 * i + 1);
context.geom_count += 2;
}
} | javascript | {
"resource": ""
} |
q27003 | addCap | train | function addCap (coord, v, normal, type, isBeginning, context) {
var neg_normal = Vector.neg(normal);
var has_texcoord = (context.texcoord_index != null);
switch (type){
case CAP_TYPE.square:
var tangent;
// first vertex on the lineString
if (isBeginning){
tangent = [normal[1], -normal[0]];
addVertex(coord, Vector.add(normal, tangent), normal, 1, v, context, 1);
addVertex(coord, Vector.add(neg_normal, tangent), normal, 0, v, context, 1);
if (has_texcoord) {
// Add length of square cap to texture coordinate
v += 0.5 * context.texcoord_width * context.v_scale;
}
addVertex(coord, normal, normal, 1, v, context, 1);
addVertex(coord, neg_normal, normal, 0, v, context, 1);
}
// last vertex on the lineString
else {
tangent = [-normal[1], normal[0]];
addVertex(coord, normal, normal, 1, v, context, 1);
addVertex(coord, neg_normal, normal, 0, v, context, 1);
if (has_texcoord) {
// Add length of square cap to texture coordinate
v += 0.5 * context.texcoord_width * context.v_scale;
}
addVertex(coord, Vector.add(normal, tangent), normal, 1, v, context, 1);
addVertex(coord, Vector.add(neg_normal, tangent), normal, 0, v, context, 1);
}
indexPairs(1, context);
break;
case CAP_TYPE.round:
// default for end cap, beginning cap will overwrite below (this way we're always passing a non-null value,
// even if texture coords are disabled)
var uvA = zero_v, uvB = one_v, uvC = mid_v;
var nA, nB;
// first vertex on the lineString
if (isBeginning) {
nA = normal;
nB = neg_normal;
if (has_texcoord){
v += 0.5 * context.texcoord_width * context.v_scale;
uvA = one_v, uvB = zero_v, uvC = mid_v; // update cap UV order
}
}
// last vertex on the lineString - flip the direction of the cap
else {
nA = neg_normal;
nB = normal;
}
if (has_texcoord) {
zero_v[1] = v, one_v[1] = v, mid_v[1] = v; // update cap UV values
}
addFan(coord,
nA, zero_vec2, nB, // extrusion normal
normal, // line normal, for offsets
uvA, uvC, uvB, // texture coords (ignored if disabled)
true, false, context
);
break;
case CAP_TYPE.butt:
return;
}
} | javascript | {
"resource": ""
} |
q27004 | trianglesPerArc | train | function trianglesPerArc (angle, width) {
if (angle < 0) {
angle = -angle;
}
var numTriangles = (width > 2 * MIN_FAN_WIDTH) ? Math.log2(width / MIN_FAN_WIDTH) : 1;
return Math.ceil(angle / Math.PI * numTriangles);
} | javascript | {
"resource": ""
} |
q27005 | permuteLine | train | function permuteLine(line, startIndex){
var newLine = [];
for (let i = 0; i < line.length; i++){
var index = (i + startIndex) % line.length;
// skip the first (repeated) index
if (index !== 0) {
newLine.push(line[index]);
}
}
newLine.push(newLine[0]);
return newLine;
} | javascript | {
"resource": ""
} |
q27006 | collapseLeadingSlashes | train | function collapseLeadingSlashes (str) {
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) !== 0x2f /* / */) {
break
}
}
return i > 1
? '/' + str.substr(i)
: str
} | javascript | {
"resource": ""
} |
q27007 | createRedirectDirectoryListener | train | function createRedirectDirectoryListener () {
return function redirect (res) {
if (this.hasTrailingSlash()) {
this.error(404)
return
}
// get original URL
var originalUrl = parseUrl.original(this.req)
// append trailing slash
originalUrl.path = null
originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/')
// reformat the URL
var loc = encodeUrl(url.format(originalUrl))
var doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + escapeHtml(loc) + '">' +
escapeHtml(loc) + '</a>')
// send redirect response
res.statusCode = 301
res.setHeader('Content-Type', 'text/html; charset=UTF-8')
res.setHeader('Content-Length', Buffer.byteLength(doc))
res.setHeader('Content-Security-Policy', "default-src 'self'")
res.setHeader('X-Content-Type-Options', 'nosniff')
res.setHeader('Location', loc)
res.end(doc)
}
} | javascript | {
"resource": ""
} |
q27008 | yolo | train | async function yolo(
input,
model,
{
classProbThreshold = DEFAULT_CLASS_PROB_THRESHOLD,
iouThreshold = DEFAULT_IOU_THRESHOLD,
filterBoxesThreshold = DEFAULT_FILTER_BOXES_THRESHOLD,
yoloAnchors = YOLO_ANCHORS,
maxBoxes = DEFAULT_MAX_BOXES,
width: widthPx = DEFAULT_INPUT_DIM,
height: heightPx = DEFAULT_INPUT_DIM,
numClasses = 80,
classNames = class_names,
} = {},
) {
const outs = tf.tidy(() => { // Keep as one var to dispose easier
const activation = model.predict(input);
const [box_xy, box_wh, box_confidence, box_class_probs ] =
yolo_head(activation, yoloAnchors, numClasses);
const all_boxes = yolo_boxes_to_corners(box_xy, box_wh);
let [boxes, scores, classes] = yolo_filter_boxes(
all_boxes, box_confidence, box_class_probs, filterBoxesThreshold);
// If all boxes have been filtered out
if (boxes == null) {
return null;
}
const width = tf.scalar(widthPx);
const height = tf.scalar(heightPx);
const image_dims = tf.stack([height, width, height, width]).reshape([1,4]);
boxes = tf.mul(boxes, image_dims);
return [boxes, scores, classes];
});
if (outs === null) {
return [];
}
const [boxes, scores, classes] = outs;
const indices = await tf.image.nonMaxSuppressionAsync(boxes, scores, maxBoxes, iouThreshold)
// Pick out data that wasn't filtered out by NMS and put them into
// CPU land to pass back to consumer
const classes_indx_arr = await classes.gather(indices).data();
const keep_scores = await scores.gather(indices).data();
const boxes_arr = await boxes.gather(indices).data();
tf.dispose(outs);
indices.dispose();
const results = [];
classes_indx_arr.forEach((class_indx, i) => {
const classProb = keep_scores[i];
if (classProb < classProbThreshold) {
return;
}
const className = classNames[class_indx];
let [top, left, bottom, right] = [
boxes_arr[4 * i],
boxes_arr[4 * i + 1],
boxes_arr[4 * i + 2],
boxes_arr[4 * i + 3],
];
top = Math.max(0, top);
left = Math.max(0, left);
bottom = Math.min(heightPx, bottom);
right = Math.min(widthPx, right);
const resultObj = {
className,
classProb,
bottom,
top,
left,
right,
};
results.push(resultObj);
});
return results;
} | javascript | {
"resource": ""
} |
q27009 | redirect | train | function redirect(url) {
// unset headers
const { res } = this;
res
.getHeaderNames()
.filter(name => !name.match(/^access-control-|vary|x-amz-/i))
.forEach(name => res.removeHeader(name));
this.set("Location", url);
// status
if (!statuses.redirect[this.status]) this.status = 302;
if (this.status === 302) {
const redirect = new S3Error("Found", "Resource Found");
redirect.description = "302 Moved Temporarily";
this.body = redirect.toHTML();
this.type = "text/html";
} else {
this.body = "";
this.type = "";
}
} | javascript | {
"resource": ""
} |
q27010 | onerror | train | async function onerror(err) {
// don't do anything if there is no error.
// this allows you to pass `this.onerror`
// to node-style callbacks.
if (null == err) return;
if (!(err instanceof Error))
err = new Error(format("non-error thrown: %j", err));
let headerSent = false;
if (this.headerSent || !this.writable) {
headerSent = err.headerSent = true;
}
// delegate
this.app.emit("error", err, this);
// nothing we can do here other
// than delegate to the app-level
// handler and log.
if (headerSent) {
return;
}
const { res } = this;
if (!(err instanceof S3Error)) {
err = S3Error.fromError(err);
}
// first unset all headers
res
.getHeaderNames()
.filter(name => !name.match(/^access-control-|vary|x-amz-/i))
.forEach(name => res.removeHeader(name));
// (the presence of x-amz-error-* headers needs additional research)
// this.set(err.headers);
// force text/html
this.type = "text/html";
if (!err.description)
err.description = `${err.status} ${statuses[err.status]}`;
// respond
const { website } = this.state;
if (
err.code !== "NoSuchBucket" &&
err.code !== "UnsupportedQuery" &&
website.errorDocumentKey
) {
// attempt to serve error document
const object = await this.store.getObject(
this.params.bucket,
website.errorDocumentKey
);
if (object) {
const objectRedirectLocation =
object.metadata["x-amz-website-redirect-location"];
if (objectRedirectLocation) {
object.content.destroy();
this.status = 301;
this.redirect(objectRedirectLocation);
res.end(this.body);
} else {
this.type = object.metadata["content-type"];
this.length = object.size;
object.content.pipe(res);
}
return;
}
this.logger.error(
"Custom Error Document not found: " + website.errorDocumentKey
);
const errorDocumentErr = new S3Error(
"NoSuchKey",
"The specified key does not exist.",
{ Key: website.errorDocumentKey }
);
errorDocumentErr.description =
"An Error Occurred While Attempting to Retrieve a Custom Error Document";
err.errors.push(errorDocumentErr);
}
const msg = err.toHTML();
this.status = err.status;
this.length = Buffer.byteLength(msg);
res.end(msg);
} | javascript | {
"resource": ""
} |
q27011 | getStringToSign | train | function getStringToSign(canonicalRequest) {
return [
canonicalRequest.method,
canonicalRequest.contentMD5,
canonicalRequest.contentType,
canonicalRequest.timestamp,
...canonicalRequest.amzHeaders,
canonicalRequest.querystring
? `${canonicalRequest.uri}?${canonicalRequest.querystring}`
: canonicalRequest.uri
].join("\n");
} | javascript | {
"resource": ""
} |
q27012 | calculateSignature | train | function calculateSignature(stringToSign, signingKey, algorithm) {
const signature = createHmac(algorithm, signingKey);
signature.update(stringToSign, "utf8");
return signature.digest("base64");
} | javascript | {
"resource": ""
} |
q27013 | onerror | train | function onerror(err) {
// don't do anything if there is no error.
// this allows you to pass `this.onerror`
// to node-style callbacks.
if (null == err) return;
if (!(err instanceof Error))
err = new Error(format("non-error thrown: %j", err));
let headerSent = false;
if (this.headerSent || !this.writable) {
headerSent = err.headerSent = true;
}
// delegate
this.app.emit("error", err, this);
// nothing we can do here other
// than delegate to the app-level
// handler and log.
if (headerSent) {
return;
}
const { res } = this;
if (!(err instanceof S3Error)) {
err = S3Error.fromError(err);
}
// first unset all headers
res
.getHeaderNames()
.filter(name => !name.match(/^access-control-|vary|x-amz-/i))
.forEach(name => res.removeHeader(name));
// (the presence of x-amz-error-* headers needs additional research)
// this.set(err.headers);
// force application/xml
this.type = "application/xml";
// respond
const msg = err.toXML();
this.status = err.status;
this.length = Buffer.byteLength(msg);
res.end(msg);
} | javascript | {
"resource": ""
} |
q27014 | Shopify | train | function Shopify(options) {
if (!(this instanceof Shopify)) return new Shopify(options);
if (
!options ||
!options.shopName ||
!options.accessToken && (!options.apiKey || !options.password) ||
options.accessToken && (options.apiKey || options.password)
) {
throw new Error('Missing or invalid options');
}
EventEmitter.call(this);
this.options = defaults(options, { timeout: 60000 });
//
// API call limits, updated with each request.
//
this.callLimits = {
remaining: undefined,
current: undefined,
max: undefined
};
this.baseUrl = {
auth: !options.accessToken && `${options.apiKey}:${options.password}`,
hostname: !options.shopName.endsWith('.myshopify.com')
? `${options.shopName}.myshopify.com`
: options.shopName,
protocol: 'https:'
};
if (options.autoLimit) {
const conf = transform(options.autoLimit, (result, value, key) => {
if (key === 'calls') key = 'limit';
result[key] = value;
}, { bucketSize: 35 });
this.request = stopcock(this.request, conf);
}
} | javascript | {
"resource": ""
} |
q27015 | listenersById | train | function listenersById(state = {}, { type, path, payload }) {
switch (type) {
case actionTypes.SET_LISTENER:
return {
...state,
[payload.name]: {
name: payload.name,
path,
},
};
case actionTypes.UNSET_LISTENER:
return omit(state, [payload.name]);
default:
return state;
}
} | javascript | {
"resource": ""
} |
q27016 | allListeners | train | function allListeners(state = [], { type, payload }) {
switch (type) {
case actionTypes.SET_LISTENER:
return [...state, payload.name];
case actionTypes.UNSET_LISTENER:
return state.filter(name => name !== payload.name);
default:
return state;
}
} | javascript | {
"resource": ""
} |
q27017 | addDoc | train | function addDoc(array = [], action) {
const { meta, payload } = action;
if (!meta.subcollections || meta.storeAs) {
return [
...array.slice(0, payload.ordered.newIndex),
{ id: meta.doc, ...payload.data },
...array.slice(payload.ordered.newIndex),
];
}
// Add doc to subcollection by modifying the existing doc at this level
return modifyDoc(array, action);
} | javascript | {
"resource": ""
} |
q27018 | removeDoc | train | function removeDoc(array, action) {
// Update is at doc level (not subcollection level)
if (!action.meta.subcollections || action.meta.storeAs) {
// Remove doc from collection array
return reject(array, { id: action.meta.doc }); // returns a new array
}
// Update is at subcollection level
const subcollectionSetting = action.meta.subcollections[0];
// Meta does not contain doc, remove whole subcollection
if (!subcollectionSetting.doc) {
return updateItemInArray(
array,
action.meta.doc,
item => omit(item, [subcollectionSetting.collection]), // omit creates a new object
);
}
// Meta contains doc setting, remove doc from subcollection
return updateItemInArray(array, action.meta.doc, item => {
const subcollectionVal = get(item, subcollectionSetting.collection, []);
// Subcollection exists within doc, update item within subcollection
if (subcollectionVal.length) {
return {
...item,
[subcollectionSetting.collection]: reject(array, {
id: subcollectionSetting.doc,
}),
};
}
// Item does not contain subcollection
return item;
});
} | javascript | {
"resource": ""
} |
q27019 | arrayToStr | train | function arrayToStr(key, value) {
if (isString(value) || isNumber(value)) return `${key}=${value}`;
if (isString(value[0])) return `${key}=${value.join(':')}`;
if (value && value.toString) return `${key}=${value.toString()}`;
return value.map(val => arrayToStr(key, val));
} | javascript | {
"resource": ""
} |
q27020 | pickQueryParams | train | function pickQueryParams(obj) {
return [
'where',
'orderBy',
'limit',
'startAfter',
'startAt',
'endAt',
'endBefore',
].reduce((acc, key) => (obj[key] ? { ...acc, [key]: obj[key] } : acc), {});
} | javascript | {
"resource": ""
} |
q27021 | docChangeEvent | train | function docChangeEvent(change, originalMeta = {}) {
const meta = { ...cloneDeep(originalMeta), path: change.doc.ref.path };
if (originalMeta.subcollections && !originalMeta.storeAs) {
meta.subcollections[0] = { ...meta.subcollections[0], doc: change.doc.id };
} else {
meta.doc = change.doc.id;
}
return {
type: changeTypeToEventType[change.type] || actionTypes.DOCUMENT_MODIFIED,
meta,
payload: {
data: change.doc.data(),
ordered: { oldIndex: change.oldIndex, newIndex: change.newIndex },
},
};
} | javascript | {
"resource": ""
} |
q27022 | createWithFirebaseAndDispatch | train | function createWithFirebaseAndDispatch(firebase, dispatch) {
return func => (...args) =>
func.apply(firebase, [firebase, dispatch, ...args]);
} | javascript | {
"resource": ""
} |
q27023 | train | function (diffX, diffY) {
if (diffX === 0 && diffY === -1) return EasyStar.TOP
else if (diffX === 1 && diffY === -1) return EasyStar.TOP_RIGHT
else if (diffX === 1 && diffY === 0) return EasyStar.RIGHT
else if (diffX === 1 && diffY === 1) return EasyStar.BOTTOM_RIGHT
else if (diffX === 0 && diffY === 1) return EasyStar.BOTTOM
else if (diffX === -1 && diffY === 1) return EasyStar.BOTTOM_LEFT
else if (diffX === -1 && diffY === 0) return EasyStar.LEFT
else if (diffX === -1 && diffY === -1) return EasyStar.TOP_LEFT
throw new Error('These differences are not valid: ' + diffX + ', ' + diffY)
} | javascript | {
"resource": ""
} | |
q27024 | getTouches | train | function getTouches(touches) {
return Array.prototype.slice.call(touches).map(function (touch) {
return {
left: touch.pageX,
top: touch.pageY
};
});
} | javascript | {
"resource": ""
} |
q27025 | getComputedTranslate | train | function getComputedTranslate(obj) {
var result = {
translateX: 0,
translateY: 0,
translateZ: 0,
scaleX: 1,
scaleY: 1,
offsetX: 0,
offsetY: 0
};
var offsetX = 0, offsetY = 0;
if (!global.getComputedStyle || !obj) return result;
var style = global.getComputedStyle(obj), transform, origin;
transform = style.webkitTransform || style.mozTransform;
origin = style.webkitTransformOrigin || style.mozTransformOrigin;
var par = origin.match(/(.*)px\s+(.*)px/);
if (par.length > 1) {
offsetX = par[1] - 0;
offsetY = par[2] - 0;
}
if (transform === 'none') return result;
var mat3d = transform.match(/^matrix3d\((.+)\)$/);
var mat2d = transform.match(/^matrix\((.+)\)$/);
var str;
if (mat3d) {
str = mat3d[1].split(', ');
result = {
translateX: str[12] - 0,
translateY: str[13] - 0,
translateZ: str[14] - 0,
offsetX: offsetX - 0,
offsetY: offsetY - 0,
scaleX: str[0] - 0,
scaleY: str[5] - 0,
scaleZ: str[10] - 0
};
} else if (mat2d) {
str = mat2d[1].split(', ');
result = {
translateX: str[4] - 0,
translateY: str[5] - 0,
offsetX: offsetX - 0,
offsetY: offsetY - 0,
scaleX: str[0] - 0,
scaleY: str[3] - 0
};
}
return result;
} | javascript | {
"resource": ""
} |
q27026 | startHandler | train | function startHandler(evt) {
startHandlerOriginal.call(this, evt);
// must be a picture, only one picture!!
var node = this.els[1].querySelector('img:first-child');
var device = this.deviceEvents;
if (device.hasTouch && node !== null) {
IN_SCALE_MODE = true;
var transform = getComputedTranslate(node);
startTouches = getTouches(evt.targetTouches);
startX = transform.translateX - 0;
startY = transform.translateY - 0;
currentScale = transform.scaleX;
zoomNode = node;
var pos = getPosition(node);
if (evt.targetTouches.length == 2) {
lastTouchStart = null;
var touches = evt.touches;
var touchCenter = getCenter({
x: touches[0].pageX,
y: touches[0].pageY
}, {
x: touches[1].pageX,
y: touches[1].pageY
});
node.style.webkitTransformOrigin = generateTransformOrigin(touchCenter.x - pos.left, touchCenter.y - pos.top);
} else if (evt.targetTouches.length === 1) {
var time = (new Date()).getTime();
gesture = 0;
if (time - lastTouchStart < 300) {
evt.preventDefault();
gesture = 3;
}
lastTouchStart = time;
}
}
} | javascript | {
"resource": ""
} |
q27027 | moveHandler | train | function moveHandler(evt) {
if (IN_SCALE_MODE) {
var result = 0;
var node = zoomNode;
var device = this.deviceEvents;
if (device.hasTouch) {
if (evt.targetTouches.length === 2) {
node.style.webkitTransitionDuration = '0';
evt.preventDefault();
scaleImage(evt);
result = 2;
} else if (evt.targetTouches.length === 1 && currentScale > 1) {
node.style.webkitTransitionDuration = '0';
evt.preventDefault();
moveImage.call(this, evt);
result = 1;
}
gesture = result;
if (result > 0) {
return;
}
}
}
moveHandlerOriginal.call(this, evt);
} | javascript | {
"resource": ""
} |
q27028 | handleDoubleTap | train | function handleDoubleTap(evt) {
var zoomFactor = zoomFactor || 2;
var node = zoomNode;
var pos = getPosition(node);
currentScale = currentScale == 1 ? zoomFactor : 1;
node.style.webkitTransform = generateTranslate(0, 0, 0, currentScale);
if (currentScale != 1) node.style.webkitTransformOrigin = generateTransformOrigin(evt.touches[0].pageX - pos.left, evt.touches[0].pageY - pos.top);
} | javascript | {
"resource": ""
} |
q27029 | endHandler | train | function endHandler(evt) {
if (IN_SCALE_MODE) {
var result = 0;
if (gesture === 2) {//双手指
resetImage(evt);
result = 2;
} else if (gesture == 1) {//放大拖拽
resetImage(evt);
result = 1;
} else if (gesture === 3) {//双击
handleDoubleTap(evt);
resetImage(evt);
IN_SCALE_MODE = false;
}
if (result > 0) {
return;
}
}
endHandlerOriginal.call(this, evt);
} | javascript | {
"resource": ""
} |
q27030 | valueInViewScope | train | function valueInViewScope(node, value, tag) {
var min, max;
var pos = getPosition(node);
viewScope = {
start: {left: pos.left, top: pos.top},
end: {left: pos.left + node.clientWidth, top: pos.top + node.clientHeight}
};
var str = tag == 1 ? 'left' : 'top';
min = viewScope.start[str];
max = viewScope.end[str];
return (value >= min && value <= max);
} | javascript | {
"resource": ""
} |
q27031 | _A | train | function _A(a) {
return Array.prototype.slice.apply(a, Array.prototype.slice.call(arguments, 1));
} | javascript | {
"resource": ""
} |
q27032 | detectPlatform | train | function detectPlatform(platform) {
var name = platform.toLowerCase();
var prefix = "", suffix = "";
// Detect NuGet/Squirrel.Windows files
if (name == 'releases' || hasSuffix(name, '.nupkg')) return platforms.WINDOWS_32;
// Detect prefix: osx, widnows or linux
if (_.contains(name, 'win')
|| hasSuffix(name, '.exe')) prefix = platforms.WINDOWS;
if (_.contains(name, 'linux')
|| _.contains(name, 'ubuntu')
|| hasSuffix(name, '.deb')
|| hasSuffix(name, '.rpm')
|| hasSuffix(name, '.tgz')
|| hasSuffix(name, '.tar.gz')) {
if (_.contains(name, 'linux_deb') || hasSuffix(name, '.deb')) {
prefix = platforms.LINUX_DEB;
}
else if (_.contains(name, 'linux_rpm') || hasSuffix(name, '.rpm')) {
prefix = platforms.LINUX_RPM;
}
else if (_.contains(name, 'linux') || hasSuffix(name, '.tgz') || hasSuffix(name, '.tar.gz')) {
prefix = platforms.LINUX;
}
}
if (_.contains(name, 'mac')
|| _.contains(name, 'osx')
|| name.indexOf('darwin') >= 0
|| hasSuffix(name, '.dmg')) prefix = platforms.OSX;
// Detect suffix: 32 or 64
if (_.contains(name, '32')
|| _.contains(name, 'ia32')
|| _.contains(name, 'i386')) suffix = '32';
if (_.contains(name, '64') || _.contains(name, 'x64') || _.contains(name, 'amd64')) suffix = '64';
suffix = suffix || (prefix == platforms.OSX? '64' : '32');
return _.compact([prefix, suffix]).join('_');
} | javascript | {
"resource": ""
} |
q27033 | satisfiesPlatform | train | function satisfiesPlatform(platform, list) {
if (_.contains(list, platform)) return true;
// By default, user 32bits version
if (_.contains(list+'_32', platform)) return true;
return false;
} | javascript | {
"resource": ""
} |
q27034 | resolveForVersion | train | function resolveForVersion(version, platformID, opts) {
opts = _.defaults(opts || {}, {
// Order for filetype
filePreference: ['.exe', '.dmg', '.deb', '.rpm', '.tgz', '.tar.gz', '.zip', '.nupkg'],
wanted: null
});
// Prepare file prefs
if (opts.wanted) opts.filePreference = _.uniq([opts.wanted].concat(opts.filePreference));
// Normalize platform id
platformID = detectPlatform(platformID);
return _.chain(version.platforms)
.filter(function(pl) {
return pl.type.indexOf(platformID) === 0;
})
.sort(function(p1, p2) {
var result = 0;
// Compare by arhcitecture ("osx_64" > "osx")
if (p1.type.length > p2.type.length) result = -1;
else if (p2.type.length > p1.type.length) result = 1;
// Order by file type if samee architecture
if (result == 0) {
var ext1 = path.extname(p1.filename);
var ext2 = path.extname(p2.filename);
var pos1 = _.indexOf(opts.filePreference, ext1);
var pos2 = _.indexOf(opts.filePreference, ext2);
pos1 = pos1 == -1? opts.filePreference.length : pos1;
pos2 = pos2 == -1? opts.filePreference.length : pos2;
if (pos1 < pos2) result = -1;
else if (pos2 < pos1) result = 1;
}
return result;
})
.first()
.value()
} | javascript | {
"resource": ""
} |
q27035 | mergeForVersions | train | function mergeForVersions(versions, opts) {
opts = _.defaults(opts || {}, {
includeTag: true
});
return _.chain(versions)
.reduce(function(prev, version) {
if (!version.notes) return prev;
// Include tag as title
if (opts.includeTag) {
prev = prev + '## ' + version.tag + '\n';
}
// Include notes
prev = prev + version.notes + '\n';
// New lines
if (opts.includeTag) {
prev = prev + '\n';
}
return prev;
}, '')
.value();
} | javascript | {
"resource": ""
} |
q27036 | hashPrerelease | train | function hashPrerelease(s) {
if (_.isString(s[0])) {
return (_.indexOf(CHANNELS, s[0]) + 1) * CHANNEL_MAGINITUDE + (s[1] || 0);
} else {
return s[0];
}
} | javascript | {
"resource": ""
} |
q27037 | normVersion | train | function normVersion(tag) {
var parts = new semver.SemVer(tag);
var prerelease = "";
if (parts.prerelease && parts.prerelease.length > 0) {
prerelease = hashPrerelease(parts.prerelease);
}
return [
parts.major,
parts.minor,
parts.patch
].join('.') + (prerelease? '.'+prerelease : '');
} | javascript | {
"resource": ""
} |
q27038 | toSemver | train | function toSemver(tag) {
var parts = tag.split('.');
var version = parts.slice(0, 3).join('.');
var prerelease = Number(parts[3]);
// semver == windows version
if (!prerelease) return version;
var channelId = Math.floor(prerelease/CHANNEL_MAGINITUDE);
var channel = CHANNELS[channelId - 1];
var count = prerelease - (channelId*CHANNEL_MAGINITUDE);
return version + '-' + channel + '.' + count
} | javascript | {
"resource": ""
} |
q27039 | generateRELEASES | train | function generateRELEASES(entries) {
return _.map(entries, function(entry) {
var filename = entry.filename;
if (!filename) {
filename = [
entry.app,
entry.version,
entry.isDelta? 'delta.nupkg' : 'full.nupkg'
].join('-');
}
return [
entry.sha,
filename,
entry.size
].join(' ');
})
.join('\n');
} | javascript | {
"resource": ""
} |
q27040 | normalizeVersion | train | function normalizeVersion(release) {
// Ignore draft
if (release.draft) return null;
var downloadCount = 0;
var releasePlatforms = _.chain(release.assets)
.map(function(asset) {
var platform = platforms.detect(asset.name);
if (!platform) return null;
downloadCount = downloadCount + asset.download_count;
return {
id: String(asset.id),
type: platform,
filename: asset.name,
size: asset.size,
content_type: asset.content_type,
raw: asset
};
})
.compact()
.value();
return {
tag: normalizeTag(release.tag_name).split('-')[0],
channel: extractChannel(release.tag_name),
notes: release.body || "",
published_at: new Date(release.published_at),
platforms: releasePlatforms
};
} | javascript | {
"resource": ""
} |
q27041 | compareVersions | train | function compareVersions(v1, v2) {
if (semver.gt(v1.tag, v2.tag)) {
return -1;
}
if (semver.lt(v1.tag, v2.tag)) {
return 1;
}
return 0;
} | javascript | {
"resource": ""
} |
q27042 | execute | train | function execute(args, live, silent) {
const env = Object.assign({}, process.env);
return new Promise((resolve, reject) => {
if (live === true) {
const pid = childProcess.spawn(getPath(), args, {
env,
stdio: ['inherit', silent ? 'pipe' : 'inherit', 'inherit'],
});
pid.on('exit', () => {
resolve();
});
} else {
childProcess.execFile(getPath(), args, { env }, (err, stdout) => {
if (err) {
reject(err);
} else {
resolve(stdout);
}
});
}
});
} | javascript | {
"resource": ""
} |
q27043 | getSetJ | train | function getSetJ(h, lw, phi, dec, n, M, L) {
var w = hourAngle(h, phi, dec),
a = approxTransit(w, lw, n);
return solarTransitJ(a, M, L);
} | javascript | {
"resource": ""
} |
q27044 | getLimitedLinksMetadata | train | function getLimitedLinksMetadata (limitedLinks) {
return limitedLinks.map((link, index) => {
if (link === ELLIPSES && limitedLinks[index - 1] === 0) {
return 'left-ellipses'
} else if (link === ELLIPSES && limitedLinks[index - 1] !== 0) {
return 'right-ellipses'
}
return link
})
} | javascript | {
"resource": ""
} |
q27045 | findDelegate | train | function findDelegate(start) {
let frag = start;
let delegate, el;
out: while (frag) {
// find next element
el = 0;
while (!el && frag) {
if (frag.owner.type === ELEMENT) el = frag.owner;
if (frag.owner.ractive && frag.owner.ractive.delegate === false) break out;
frag = frag.parent || frag.componentParent;
}
if (el.delegate === false) break out;
delegate = el.delegate || el;
// find next repeated fragment
while (frag) {
if (frag.iterations) break;
if (frag.owner.ractive && frag.owner.ractive.delegate === false) break out;
frag = frag.parent || frag.componentParent;
}
}
return delegate;
} | javascript | {
"resource": ""
} |
q27046 | variants | train | function variants(name, initial) {
const map = initial ? initStars : bubbleStars;
if (map[name]) return map[name];
const parts = name.split('.');
const result = [];
let base = false;
// initial events the implicit namespace of 'this'
if (initial) {
parts.unshift('this');
base = true;
}
// use max - 1 bits as a bitmap to pick a part or a *
// need to skip the full star case if the namespace is synthetic
const max = Math.pow(2, parts.length) - (initial ? 1 : 0);
for (let i = 0; i < max; i++) {
const join = [];
for (let j = 0; j < parts.length; j++) {
join.push(1 & (i >> j) ? '*' : parts[j]);
}
result.unshift(join.join('.'));
}
if (base) {
// include non-this-namespaced versions
if (parts.length > 2) {
result.push.apply(result, variants(name, false));
} else {
result.push('*');
result.push(name);
}
}
map[name] = result;
return result;
} | javascript | {
"resource": ""
} |
q27047 | transpile | train | function transpile(src, options) {
return buble.transform(src, {
target: { ie: 9 },
transforms: { modules: false }
});
} | javascript | {
"resource": ""
} |
q27048 | replacePlaceholders | train | function replacePlaceholders(src, options) {
return Object.keys(placeholders).reduce((out, placeholder) => {
return out.replace(new RegExp(`${placeholder}`, 'g'), placeholders[placeholder]);
}, src);
} | javascript | {
"resource": ""
} |
q27049 | decomposeSyllable | train | function decomposeSyllable(codePoint) {
const sylSIndex = codePoint - SBASE;
const sylTIndex = sylSIndex % TCOUNT;
return String.fromCharCode(LBASE + sylSIndex / NCOUNT)
+ String.fromCharCode(VBASE + (sylSIndex % NCOUNT) / TCOUNT)
+ ((sylTIndex > 0) ? String.fromCharCode(TBASE + sylTIndex) : '');
} | javascript | {
"resource": ""
} |
q27050 | groupArray | train | function groupArray(array, fn) {
var ret = {};
for (var ii = 0; ii < array.length; ii++) {
var result = fn.call(array, array[ii], ii);
if (!ret[result]) {
ret[result] = [];
}
ret[result].push(array[ii]);
}
return ret;
} | javascript | {
"resource": ""
} |
q27051 | compare | train | function compare(name, version, query, normalizer) {
// check for exact match with no version
if (name === query) {
return true;
}
// check for non-matching names
if (!query.startsWith(name)) {
return false;
}
// full comparison with version
let range = query.slice(name.length);
if (version) {
range = normalizer ? normalizer(range) : range;
return VersionRange.contains(range, version);
}
return false;
} | javascript | {
"resource": ""
} |
q27052 | getElementPosition | train | function getElementPosition(element) {
const rect = getElementRect(element);
return {
x: rect.left,
y: rect.top,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
} | javascript | {
"resource": ""
} |
q27053 | checkOrExpression | train | function checkOrExpression(range, version) {
const expressions = range.split(orRegex);
if (expressions.length > 1) {
return expressions.some(range => VersionRange.contains(range, version));
} else {
range = expressions[0].trim();
return checkRangeExpression(range, version);
}
} | javascript | {
"resource": ""
} |
q27054 | zeroPad | train | function zeroPad(array, length) {
for (let i = array.length; i < length; i++) {
array[i] = '0';
}
} | javascript | {
"resource": ""
} |
q27055 | compare | train | function compare(a, b) {
invariant(typeof a === typeof b, '"a" and "b" must be of the same type');
if (a > b) {
return 1;
} else if (a < b) {
return -1;
} else {
return 0;
}
} | javascript | {
"resource": ""
} |
q27056 | compareComponents | train | function compareComponents(a, b) {
const [aNormalized, bNormalized] = normalizeVersions(a, b);
for (let i = 0; i < bNormalized.length; i++) {
const result = compareNumeric(aNormalized[i], bNormalized[i]);
if (result) {
return result;
}
}
return 0;
} | javascript | {
"resource": ""
} |
q27057 | hiraganaToKatakana | train | function hiraganaToKatakana(str) {
if (!hasKana(str)) {
return str;
}
return str.split('').map(charCodeToKatakana).join('');
} | javascript | {
"resource": ""
} |
q27058 | isKanaWithTrailingLatin | train | function isKanaWithTrailingLatin(str) {
REGEX_IS_KANA_WITH_TRAILING_LATIN = REGEX_IS_KANA_WITH_TRAILING_LATIN ||
new RegExp('^' + '[' + R_KANA + ']+' + '[' + R_LATIN + ']' + '$');
return REGEX_IS_KANA_WITH_TRAILING_LATIN.test(str);
} | javascript | {
"resource": ""
} |
q27059 | getDocumentScrollElement | train | function getDocumentScrollElement(doc) {
doc = doc || document;
if (doc.scrollingElement) {
return doc.scrollingElement;
}
return !isWebkit && doc.compatMode === 'CSS1Compat' ?
doc.documentElement :
doc.body;
} | javascript | {
"resource": ""
} |
q27060 | printWarning | train | function printWarning(format, ...args) {
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, () => args[argIndex++]);
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
} | javascript | {
"resource": ""
} |
q27061 | concatAllArray | train | function concatAllArray(array) {
var ret = [];
for (var ii = 0; ii < array.length; ii++) {
var value = array[ii];
if (Array.isArray(value)) {
push.apply(ret, value);
} else if (value != null) {
throw new TypeError(
'concatAllArray: All items in the array must be an array or null, ' +
'got "' + value + '" at index "' + ii + '" instead'
);
}
}
return ret;
} | javascript | {
"resource": ""
} |
q27062 | train | function(element, className) {
invariant(
!/\s/.test(className),
'CSSCore.addClass takes only a single class name. "%s" contains ' +
'multiple classes.', className
);
if (className) {
if (element.classList) {
element.classList.add(className);
} else if (!CSSCore.hasClass(element, className)) {
element.className = element.className + ' ' + className;
}
}
return element;
} | javascript | {
"resource": ""
} | |
q27063 | train | function(element, className) {
invariant(
!/\s/.test(className),
'CSSCore.removeClass takes only a single class name. "%s" contains ' +
'multiple classes.', className
);
if (className) {
if (element.classList) {
element.classList.remove(className);
} else if (CSSCore.hasClass(element, className)) {
element.className = element.className
.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1')
.replace(/\s+/g, ' ') // multiple spaces to one
.replace(/^\s*|\s*$/g, ''); // trim the ends
}
}
return element;
} | javascript | {
"resource": ""
} | |
q27064 | train | function(element, className, bool) {
return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className);
} | javascript | {
"resource": ""
} | |
q27065 | createArrayFromMixed | train | function createArrayFromMixed(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
} | javascript | {
"resource": ""
} |
q27066 | getElementRect | train | function getElementRect(elem) {
const docElem = elem.ownerDocument.documentElement;
// FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect().
// IE9- will throw if the element is not in the document.
if (!('getBoundingClientRect' in elem) || !containsNode(docElem, elem)) {
return {
left: 0,
right: 0,
top: 0,
bottom: 0
};
}
// Subtracts clientTop/Left because IE8- added a 2px border to the
// <html> element (see http://fburl.com/1493213). IE 7 in
// Quicksmode does not report clientLeft/clientTop so there
// will be an unaccounted offset of 2px when in quirksmode
const rect = elem.getBoundingClientRect();
return {
left: Math.round(rect.left) - docElem.clientLeft,
right: Math.round(rect.right) - docElem.clientLeft,
top: Math.round(rect.top) - docElem.clientTop,
bottom: Math.round(rect.bottom) - docElem.clientTop
};
} | javascript | {
"resource": ""
} |
q27067 | train | function(node) {
if (!node) {
return null;
}
var ownerDocument = node.ownerDocument;
while (node && node !== ownerDocument.body) {
if (_isNodeScrollable(node, 'overflow') ||
_isNodeScrollable(node, 'overflowY') ||
_isNodeScrollable(node, 'overflowX')) {
return node;
}
node = node.parentNode;
}
return ownerDocument.defaultView || ownerDocument.parentWindow;
} | javascript | {
"resource": ""
} | |
q27068 | mapModule | train | function mapModule(state, module) {
var moduleMap = state.opts.map || {};
if (moduleMap.hasOwnProperty(module)) {
return moduleMap[module];
}
// Jest understands the haste module system, so leave modules intact.
if (process.env.NODE_ENV !== 'test') {
var modulePrefix = state.opts.prefix;
if (modulePrefix == null) {
modulePrefix = './';
}
return modulePrefix + module;
}
return null;
} | javascript | {
"resource": ""
} |
q27069 | transformTypeImport | train | function transformTypeImport(path, state) {
var source = path.get('source');
if (source.type === 'StringLiteral') {
var module = mapModule(state, source.node.value);
if (module) {
source.replaceWith(t.stringLiteral(module));
}
}
} | javascript | {
"resource": ""
} |
q27070 | phpEscape | train | function phpEscape(s) {
var result = '"';
for (let cp of UnicodeUtils.getCodePoints(s)) {
let special = specialEscape[cp];
if (special !== undefined) {
result += special;
} else if (cp >= 0x20 && cp <= 0x7e) {
result += String.fromCodePoint(cp);
} else if (cp <= 0xFFFF) {
result += '\\u{' + zeroPaddedHex(cp, 4) + '}';
} else {
result += '\\u{' + zeroPaddedHex(cp, 6) + '}';
}
}
result += '"';
return result;
} | javascript | {
"resource": ""
} |
q27071 | jsEscape | train | function jsEscape(s) {
var result = '"';
for (var i = 0; i < s.length; i++) {
let cp = s.charCodeAt(i);
let special = specialEscape[cp];
if (special !== undefined) {
result += special;
} else if (cp >= 0x20 && cp <= 0x7e) {
result += String.fromCodePoint(cp);
} else {
result += '\\u' + zeroPaddedHex(cp, 4);
}
}
result += '"';
return result;
} | javascript | {
"resource": ""
} |
q27072 | getBrowserVersion | train | function getBrowserVersion(version) {
if (!version) {
return {
major: '',
minor: '',
};
}
var parts = version.split('.');
return {
major: parts[0],
minor: parts[1],
};
} | javascript | {
"resource": ""
} |
q27073 | getCodePoints | train | function getCodePoints(str) {
const codePoints = [];
for (let pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
codePoints.push(str.codePointAt(pos));
}
return codePoints;
} | javascript | {
"resource": ""
} |
q27074 | train | function (version) {
var that = this;
var createValidators = function (spec, validatorsMap) {
return _.reduce(validatorsMap, function (result, schemas, schemaName) {
result[schemaName] = helpers.createJsonValidator(schemas);
return result;
}, {});
};
var fixSchemaId = function (schemaName) {
// Swagger 1.2 schema files use one id but use a different id when referencing schema files. We also use the schema
// file name to reference the schema in ZSchema. To fix this so that the JSON Schema validator works properly, we
// need to set the id to be the name of the schema file.
var fixed = _.cloneDeep(that.schemas[schemaName]);
fixed.id = schemaName;
return fixed;
};
var primitives = ['string', 'number', 'boolean', 'integer', 'array'];
switch (version) {
case '1.2':
this.docsUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/1.2.md';
this.primitives = _.union(primitives, ['void', 'File']);
this.schemasUrl = 'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v1.2';
// Here explicitly to allow browserify to work
this.schemas = {
'apiDeclaration.json': require('../schemas/1.2/apiDeclaration.json'),
'authorizationObject.json': require('../schemas/1.2/authorizationObject.json'),
'dataType.json': require('../schemas/1.2/dataType.json'),
'dataTypeBase.json': require('../schemas/1.2/dataTypeBase.json'),
'infoObject.json': require('../schemas/1.2/infoObject.json'),
'modelsObject.json': require('../schemas/1.2/modelsObject.json'),
'oauth2GrantType.json': require('../schemas/1.2/oauth2GrantType.json'),
'operationObject.json': require('../schemas/1.2/operationObject.json'),
'parameterObject.json': require('../schemas/1.2/parameterObject.json'),
'resourceListing.json': require('../schemas/1.2/resourceListing.json'),
'resourceObject.json': require('../schemas/1.2/resourceObject.json')
};
this.validators = createValidators(this, {
'apiDeclaration.json': _.map([
'dataTypeBase.json',
'modelsObject.json',
'oauth2GrantType.json',
'authorizationObject.json',
'parameterObject.json',
'operationObject.json',
'apiDeclaration.json'
], fixSchemaId),
'resourceListing.json': _.map([
'resourceObject.json',
'infoObject.json',
'oauth2GrantType.json',
'authorizationObject.json',
'resourceListing.json'
], fixSchemaId)
});
break;
case '2.0':
this.docsUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md';
this.primitives = _.union(primitives, ['file']);
this.schemasUrl = 'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v2.0';
// Here explicitly to allow browserify to work
this.schemas = {
'schema.json': require('../schemas/2.0/schema.json')
};
this.validators = createValidators(this, {
'schema.json': [fixSchemaId('schema.json')]
});
break;
default:
throw new Error(version + ' is an unsupported Swagger specification version');
}
this.version = version;
} | javascript | {
"resource": ""
} | |
q27075 | csurf | train | function csurf (options) {
var opts = options || {}
// get cookie options
var cookie = getCookieOptions(opts.cookie)
// get session options
var sessionKey = opts.sessionKey || 'session'
// get value getter
var value = opts.value || defaultValue
// token repo
var tokens = new Tokens(opts)
// ignored methods
var ignoreMethods = opts.ignoreMethods === undefined
? ['GET', 'HEAD', 'OPTIONS']
: opts.ignoreMethods
if (!Array.isArray(ignoreMethods)) {
throw new TypeError('option ignoreMethods must be an array')
}
// generate lookup
var ignoreMethod = getIgnoredMethods(ignoreMethods)
return function csrf (req, res, next) {
// validate the configuration against request
if (!verifyConfiguration(req, sessionKey, cookie)) {
return next(new Error('misconfigured csrf'))
}
// get the secret from the request
var secret = getSecret(req, sessionKey, cookie)
var token
// lazy-load token getter
req.csrfToken = function csrfToken () {
var sec = !cookie
? getSecret(req, sessionKey, cookie)
: secret
// use cached token if secret has not changed
if (token && sec === secret) {
return token
}
// generate & set new secret
if (sec === undefined) {
sec = tokens.secretSync()
setSecret(req, res, sessionKey, sec, cookie)
}
// update changed secret
secret = sec
// create new token
token = tokens.create(secret)
return token
}
// generate & set secret
if (!secret) {
secret = tokens.secretSync()
setSecret(req, res, sessionKey, secret, cookie)
}
// verify the incoming token
if (!ignoreMethod[req.method] && !tokens.verify(secret, value(req))) {
return next(createError(403, 'invalid csrf token', {
code: 'EBADCSRFTOKEN'
}))
}
next()
}
} | javascript | {
"resource": ""
} |
q27076 | defaultValue | train | function defaultValue (req) {
return (req.body && req.body._csrf) ||
(req.query && req.query._csrf) ||
(req.headers['csrf-token']) ||
(req.headers['xsrf-token']) ||
(req.headers['x-csrf-token']) ||
(req.headers['x-xsrf-token'])
} | javascript | {
"resource": ""
} |
q27077 | getCookieOptions | train | function getCookieOptions (options) {
if (options !== true && typeof options !== 'object') {
return undefined
}
var opts = Object.create(null)
// defaults
opts.key = '_csrf'
opts.path = '/'
if (options && typeof options === 'object') {
for (var prop in options) {
var val = options[prop]
if (val !== undefined) {
opts[prop] = val
}
}
}
return opts
} | javascript | {
"resource": ""
} |
q27078 | getIgnoredMethods | train | function getIgnoredMethods (methods) {
var obj = Object.create(null)
for (var i = 0; i < methods.length; i++) {
var method = methods[i].toUpperCase()
obj[method] = true
}
return obj
} | javascript | {
"resource": ""
} |
q27079 | getSecret | train | function getSecret (req, sessionKey, cookie) {
// get the bag & key
var bag = getSecretBag(req, sessionKey, cookie)
var key = cookie ? cookie.key : 'csrfSecret'
if (!bag) {
throw new Error('misconfigured csrf')
}
// return secret from bag
return bag[key]
} | javascript | {
"resource": ""
} |
q27080 | getSecretBag | train | function getSecretBag (req, sessionKey, cookie) {
if (cookie) {
// get secret from cookie
var cookieKey = cookie.signed
? 'signedCookies'
: 'cookies'
return req[cookieKey]
} else {
// get secret from session
return req[sessionKey]
}
} | javascript | {
"resource": ""
} |
q27081 | setCookie | train | function setCookie (res, name, val, options) {
var data = Cookie.serialize(name, val, options)
var prev = res.getHeader('set-cookie') || []
var header = Array.isArray(prev) ? prev.concat(data)
: [prev, data]
res.setHeader('set-cookie', header)
} | javascript | {
"resource": ""
} |
q27082 | setSecret | train | function setSecret (req, res, sessionKey, val, cookie) {
if (cookie) {
// set secret on cookie
var value = val
if (cookie.signed) {
value = 's:' + sign(val, req.secret)
}
setCookie(res, cookie.key, value, cookie)
} else {
// set secret on session
req[sessionKey].csrfSecret = val
}
} | javascript | {
"resource": ""
} |
q27083 | verifyConfiguration | train | function verifyConfiguration (req, sessionKey, cookie) {
if (!getSecretBag(req, sessionKey, cookie)) {
return false
}
if (cookie && cookie.signed && !req.secret) {
return false
}
return true
} | javascript | {
"resource": ""
} |
q27084 | train | function (message) {
receiveQueue.push(message);
//reason I need this setTmeout is to return this function as fast as
//possible to release the native side thread.
setTimeout(function () {
var message = receiveQueue.pop();
callFunc(WebViewBridge.onMessage, message);
}, 15); //this magic number is just a random small value. I don't like 0.
} | javascript | {
"resource": ""
} | |
q27085 | train | function (message) {
if ('string' !== typeof message) {
callFunc(WebViewBridge.onError, "message is type '" + typeof message + "', and it needs to be string");
return;
}
//we queue the messages to make sure that native can collects all of them in one shot.
sendQueue.push(message);
//signal the objective-c that there is a message in the queue
signalNative();
} | javascript | {
"resource": ""
} | |
q27086 | main | train | function main(argv) {
try {
shell.mkdir('-p', 'docs')
shell.pushd('-q', 'docs')
handleErrorCode(shell.exec('npm init -y'))
handleErrorCode(shell.exec('npm install docusaurus-init'))
handleErrorCode(shell.exec('docusaurus-init'))
shell.mv('docs-examples-from-docusaurus/', 'docs')
shell.mv('website/blog-examples-from-docusaurus/', 'website/blog')
shell.pushd('-q', 'website')
handleErrorCode(shell.exec('npm run examples versions'))
shell.popd('-q')
shell.popd('-q')
}
catch (err) {
shell.rm('-rf', 'docs')
throw err
}
} | javascript | {
"resource": ""
} |
q27087 | attach | train | function attach() {
const container = this.options.container;
if (container instanceof HTMLElement) {
const style = window.getComputedStyle(container);
if (style.position === 'static') {
container.style.position = 'relative';
}
}
container.addEventListener('scroll', this._scroll);
window.addEventListener('resize', this._scroll);
this._scroll();
this.attached = true;
} | javascript | {
"resource": ""
} |
q27088 | off | train | function off(event, selector, handler) {
const enterCallbacks = Object.keys(this.trackedElements[selector].enter || {});
const leaveCallbacks = Object.keys(this.trackedElements[selector].leave || {});
if ({}.hasOwnProperty.call(this.trackedElements, selector)) {
if (handler) {
if (this.trackedElements[selector][event]) {
const callbackName = (typeof handler === 'function') ? handler.name : handler;
delete this.trackedElements[selector][event][callbackName];
}
} else {
delete this.trackedElements[selector][event];
}
}
if (!enterCallbacks.length && !leaveCallbacks.length) {
delete this.trackedElements[selector];
}
} | javascript | {
"resource": ""
} |
q27089 | destroy | train | function destroy() {
this.options.container.removeEventListener('scroll', this._scroll);
window.removeEventListener('resize', this._scroll);
this.attached = false;
} | javascript | {
"resource": ""
} |
q27090 | on | train | function on(event, selector, callback) {
const allowed = ['enter', 'leave'];
if (!event) throw new Error('No event given. Choose either enter or leave');
if (!selector) throw new Error('No selector to track');
if (allowed.indexOf(event) < 0) throw new Error(`${event} event is not supported`);
if (!{}.hasOwnProperty.call(this.trackedElements, selector)) {
this.trackedElements[selector] = {};
}
this.trackedElements[selector].nodes = [];
for (let i = 0, elems = document.querySelectorAll(selector); i < elems.length; i++) {
const item = {
isVisible: false,
wasVisible: false,
node: elems[i]
};
this.trackedElements[selector].nodes.push(item);
}
if (typeof callback === 'function') {
if (!this.trackedElements[selector][event]) {
this.trackedElements[selector][event] = {};
}
this.trackedElements[selector][event][(callback.name || 'anonymous')] = callback;
}
} | javascript | {
"resource": ""
} |
q27091 | debouncedScroll | train | function debouncedScroll() {
let timeout;
return () => {
clearTimeout(timeout);
timeout = setTimeout(() => {
scrollHandler(this.trackedElements, this.options);
}, this.options.debounce);
};
} | javascript | {
"resource": ""
} |
q27092 | inContainer | train | function inContainer(el, options = { tolerance: 0, container: '' }) {
if (!el) {
throw new Error('You should specify the element you want to test');
}
if (typeof el === 'string') {
el = document.querySelector(el);
}
if (typeof options === 'string') {
options = {
tolerance: 0,
container: document.querySelector(options)
};
}
if (typeof options.container === 'string') {
options.container = document.querySelector(options.container);
}
if (options instanceof HTMLElement) {
options = {
tolerance: 0,
container: options
};
}
if (!options.container) {
throw new Error('You should specify a container element');
}
const containerRect = options.container.getBoundingClientRect();
return (
// // Check bottom boundary
(el.offsetTop + el.clientHeight) - options.tolerance >
options.container.scrollTop &&
// Check right boundary
(el.offsetLeft + el.clientWidth) - options.tolerance >
options.container.scrollLeft &&
// Check left boundary
el.offsetLeft + options.tolerance <
containerRect.width + options.container.scrollLeft &&
// // Check top boundary
el.offsetTop + options.tolerance <
containerRect.height + options.container.scrollTop
);
} | javascript | {
"resource": ""
} |
q27093 | observeDOM | train | function observeDOM(obj, callback) {
const MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
/* istanbul ignore else */
if (MutationObserver) {
const obs = new MutationObserver(callback);
obs.observe(obj, {
childList: true,
subtree: true
});
} else {
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
} | javascript | {
"resource": ""
} |
q27094 | OnScreen | train | function OnScreen(options = { tolerance: 0, debounce: 100, container: window }) {
this.options = {};
this.trackedElements = {};
Object.defineProperties(this.options, {
container: {
configurable: false,
enumerable: false,
get() {
let container;
if (typeof options.container === 'string') {
container = document.querySelector(options.container);
} else if (options.container instanceof HTMLElement) {
container = options.container;
}
return container || window;
},
set(value) {
options.container = value;
}
},
debounce: {
get() {
return parseInt(options.debounce, 10) || 100;
},
set(value) {
options.debounce = value;
}
},
tolerance: {
get() {
return parseInt(options.tolerance, 10) || 0;
},
set(value) {
options.tolerance = value;
}
}
});
Object.defineProperty(this, '_scroll', {
enumerable: false,
configurable: false,
writable: false,
value: this._debouncedScroll.call(this)
});
observeDOM(document.querySelector('body'), () => {
Object.keys(this.trackedElements).forEach((element) => {
this.on('enter', element);
this.on('leave', element);
});
});
this.attach();
} | javascript | {
"resource": ""
} |
q27095 | inViewport | train | function inViewport(el, options = { tolerance: 0 }) {
if (!el) {
throw new Error('You should specify the element you want to test');
}
if (typeof el === 'string') {
el = document.querySelector(el);
}
const elRect = el.getBoundingClientRect();
return (
// Check bottom boundary
elRect.bottom - options.tolerance > 0 &&
// Check right boundary
elRect.right - options.tolerance > 0 &&
// Check left boundary
elRect.left + options.tolerance < (window.innerWidth ||
document.documentElement.clientWidth) &&
// Check top boundary
elRect.top + options.tolerance < (window.innerHeight ||
document.documentElement.clientHeight)
);
} | javascript | {
"resource": ""
} |
q27096 | deployFIFSRegistrar | train | function deployFIFSRegistrar(deployer, tld) {
var rootNode = getRootNodeFromTLD(tld);
// Deploy the ENS first
deployer.deploy(ENS)
.then(() => {
// Deploy the FIFSRegistrar and bind it with ENS
return deployer.deploy(FIFSRegistrar, ENS.address, rootNode.namehash);
})
.then(function() {
// Transfer the owner of the `rootNode` to the FIFSRegistrar
return ENS.at(ENS.address).then((c) => c.setSubnodeOwner('0x0', rootNode.sha3, FIFSRegistrar.address));
});
} | javascript | {
"resource": ""
} |
q27097 | lookup | train | async function lookup(words) {
const index = new Index();
const hits = await index.lookup(words);
index.quit();
words.forEach((word, i) => {
console.log(`hits for "${word}":`, hits[i].join(', '));
});
return hits;
} | javascript | {
"resource": ""
} |
q27098 | extractDescription | train | function extractDescription(texts) {
let document = '';
texts.forEach(text => {
document += text.description || '';
});
return document.toLowerCase();
} | javascript | {
"resource": ""
} |
q27099 | extractDescriptions | train | async function extractDescriptions(filename, index, response) {
if (response.textAnnotations.length) {
const words = extractDescription(response.textAnnotations);
await index.add(filename, words);
} else {
console.log(`${filename} had no discernable text.`);
await index.setContainsNoText(filename);
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.