_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q22700
LocalIndexedDBStoreBackend
train
function LocalIndexedDBStoreBackend( indexedDBInterface, dbName, ) { this.indexedDB = indexedDBInterface; this._dbName = "matrix-js-sdk:" + (dbName || "default"); this.db = null; this._disconnected = true; this._syncAccumulator = new SyncAccumulator(); this._isNewlyCreated = false; }
javascript
{ "resource": "" }
q22701
train
function() { if (!this._disconnected) { console.log( `LocalIndexedDBStoreBackend.connect: already connected or connecting`, ); return Promise.resolve(); } this._disconnected = false; console.log( `LocalIndexedDBStoreBackend.connect: connecting...`, ); const req = this.indexedDB.open(this._dbName, VERSION); req.onupgradeneeded = (ev) => { const db = ev.target.result; const oldVersion = ev.oldVersion; console.log( `LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`, ); if (oldVersion < 1) { // The database did not previously exist. this._isNewlyCreated = true; createDatabase(db); } if (oldVersion < 2) { upgradeSchemaV2(db); } if (oldVersion < 3) { upgradeSchemaV3(db); } // Expand as needed. }; req.onblocked = () => { console.log( `can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`, ); }; console.log( `LocalIndexedDBStoreBackend.connect: awaiting connection...`, ); return reqAsEventPromise(req).then((ev) => { console.log( `LocalIndexedDBStoreBackend.connect: connected`, ); this.db = ev.target.result; // add a poorly-named listener for when deleteDatabase is called // so we can close our db connections. this.db.onversionchange = () => { this.db.close(); }; return this._init(); }); }
javascript
{ "resource": "" }
q22702
train
function() { return Promise.all([ this._loadAccountData(), this._loadSyncData(), ]).then(([accountData, syncData]) => { console.log( `LocalIndexedDBStoreBackend: loaded initial data`, ); this._syncAccumulator.accumulate({ next_batch: syncData.nextBatch, rooms: syncData.roomsData, groups: syncData.groupsData, account_data: { events: accountData, }, }); }); }
javascript
{ "resource": "" }
q22703
train
function(roomId) { return new Promise((resolve, reject) =>{ const tx = this.db.transaction(["oob_membership_events"], "readonly"); const store = tx.objectStore("oob_membership_events"); const roomIndex = store.index("room"); const range = IDBKeyRange.only(roomId); const request = roomIndex.openCursor(range); const membershipEvents = []; // did we encounter the oob_written marker object // amongst the results? That means OOB member // loading already happened for this room // but there were no members to persist as they // were all known already let oobWritten = false; request.onsuccess = (event) => { const cursor = event.target.result; if (!cursor) { // Unknown room if (!membershipEvents.length && !oobWritten) { return resolve(null); } return resolve(membershipEvents); } const record = cursor.value; if (record.oob_written) { oobWritten = true; } else { membershipEvents.push(record); } cursor.continue(); }; request.onerror = (err) => { reject(err); }; }).then((events) => { console.log(`LL: got ${events && events.length}` + ` membershipEvents from storage for room ${roomId} ...`); return events; }); }
javascript
{ "resource": "" }
q22704
train
async function(roomId, membershipEvents) { console.log(`LL: backend about to store ${membershipEvents.length}` + ` members for ${roomId}`); const tx = this.db.transaction(["oob_membership_events"], "readwrite"); const store = tx.objectStore("oob_membership_events"); membershipEvents.forEach((e) => { store.put(e); }); // aside from all the events, we also write a marker object to the store // to mark the fact that OOB members have been written for this room. // It's possible that 0 members need to be written as all where previously know // but we still need to know whether to return null or [] from getOutOfBandMembers // where null means out of band members haven't been stored yet for this room const markerObject = { room_id: roomId, oob_written: true, state_key: 0, }; store.put(markerObject); await txnAsPromise(tx); console.log(`LL: backend done storing for ${roomId}!`); }
javascript
{ "resource": "" }
q22705
train
function() { return new Promise((resolve, reject) => { console.log(`Removing indexeddb instance: ${this._dbName}`); const req = this.indexedDB.deleteDatabase(this._dbName); req.onblocked = () => { console.log( `can't yet delete indexeddb ${this._dbName}` + ` because it is open elsewhere`, ); }; req.onerror = (ev) => { // in firefox, with indexedDB disabled, this fails with a // DOMError. We treat this as non-fatal, so that we can still // use the app. console.warn( `unable to delete js-sdk store indexeddb: ${ev.target.error}`, ); resolve(); }; req.onsuccess = () => { console.log(`Removed indexeddb instance: ${this._dbName}`); resolve(); }; }); }
javascript
{ "resource": "" }
q22706
train
function(accountData) { return Promise.try(() => { const txn = this.db.transaction(["accountData"], "readwrite"); const store = txn.objectStore("accountData"); for (let i = 0; i < accountData.length; i++) { store.put(accountData[i]); // put == UPSERT } return txnAsPromise(txn); }); }
javascript
{ "resource": "" }
q22707
train
function() { console.log( `LocalIndexedDBStoreBackend: loading account data...`, ); return Promise.try(() => { const txn = this.db.transaction(["accountData"], "readonly"); const store = txn.objectStore("accountData"); return selectQuery(store, undefined, (cursor) => { return cursor.value; }).then((result) => { console.log( `LocalIndexedDBStoreBackend: loaded account data`, ); return result; }); }); }
javascript
{ "resource": "" }
q22708
train
function() { console.log( `LocalIndexedDBStoreBackend: loading sync data...`, ); return Promise.try(() => { const txn = this.db.transaction(["sync"], "readonly"); const store = txn.objectStore("sync"); return selectQuery(store, undefined, (cursor) => { return cursor.value; }).then((results) => { console.log( `LocalIndexedDBStoreBackend: loaded sync data`, ); if (results.length > 1) { console.warn("loadSyncData: More than 1 sync row found."); } return (results.length > 0 ? results[0] : {}); }); }); }
javascript
{ "resource": "" }
q22709
_walkObject
train
function _walkObject(object, callback, path, config) { const {walkArrays, walkArraysMatchingKeys} = config; Object.keys(object).forEach(key => { // Callback can force traversal to stop by returning `true`. if (callback(key, object, path.get(object, key))) { return; } const value = object[key]; if (isPlainObject(value) || doArrayWalk(key, value, walkArrays, walkArraysMatchingKeys)) { _walkObject(value, callback, path.set(object, key), config); } }); }
javascript
{ "resource": "" }
q22710
handleEscaping
train
function handleEscaping(tokens, token, index) { if (index === 0) { return [token]; } const previousToken = tokens[index - 1]; if (!previousToken.endsWith('\\')) { return [...tokens, token]; } return [...tokens.slice(0, index - 1), `${previousToken.slice(0, -1)} ${token}`]; }
javascript
{ "resource": "" }
q22711
isEnv
train
function isEnv(envAlias) { // Check for default case if (envAlias === ENV_ALIAS.DEV && Object.keys(env).length === 0) { return true; } return envAlias.some(alias => env[alias]); }
javascript
{ "resource": "" }
q22712
cors
train
function cors(req, res, next) { const port = process.env.NODE_ENV === 'production' ? null : new url.URL(req.query.__amp_source_origin).port; const host = process.env.NODE_ENV === 'production' ? `https://${req.hostname}` : `http://${req.hostname}:${port}`; res.header('amp-access-control-allow-source-origin', host); next(); }
javascript
{ "resource": "" }
q22713
filter
train
function filter(data, query) { var results = []; var push = true; // omit every result that doesn't pass _every_ filter data.forEach((val) => { var push = true; // if we fail a filter condition, then don't push // check if we're over the max price if (query.maxPrice > 0) { if (val.price.value > query.maxPrice) { push = false; } } // check if the city is included if (query.cities.length > 0) { if (!query.cities.includes(val.location.city)) { push = false; } } // check if the type is anywhere to be found var found = false; if (query.types.length > 0) { query.types.forEach((type) => { if (val.types.includes(type)) found = true; }); } else { // assume it's found if there's no `query.types` on the request found = true; } if (!found) { push = false; } // if we found something, then push it to the results array if (push) { results.push(val); } }); return results; }
javascript
{ "resource": "" }
q22714
selectedCities
train
function selectedCities(travelData, cities) { var selected = []; travelData.activities.forEach((data) => { const isSelected = cities.includes(data.location.city); // check if the city already exists in our cities array var existsIdx = -1; selected.forEach((city, idx) => { if (city.name === data.location.city) { existsIdx = idx; } }); const city = travelData.cities.find((city) => city.name === data.location.city); // if it doesn't exist already, add it if (existsIdx === -1) { selected.push({ img: city ? city.img : '', name: data.location.city, isSelected: isSelected, }); // otherwise update the existing entry only if it's currently false, // otherwise we could overwrite a previous match } else { if (!selected[existsIdx].isSelected) { selected[existsIdx].isSelected = isSelected; } } }); return selected; }
javascript
{ "resource": "" }
q22715
sortResults
train
function sortResults(val, results) { const sortPopularity = (a, b) => { if (a.reviews.count < b.reviews.count) { return 1; } else if (a.reviews.count > b.reviews.count) { return -1; } return 0; }; const sortRating = (a, b) => { if (a.reviews.averageRating.value < b.reviews.averageRating.value) { return 1; } else if (a.reviews.averageRating.value > b.reviews.averageRating.value) { return -1; } return sortPopularity(a, b); }; const sortPrice = (a, b) => { if (a.price.value > b.price.value) { return 1; } else if (a.price.value < b.price.value) { return -1; } return sortRating(a, b); }; const sortNew = (a, b) => { if (!a.flags.new && b.flags.new) { return 1; } else if (a.flags.new && !b.flags.new) { return -1; } return sortRating(a, b); }; switch (val.toLowerCase()) { case "popularity-desc": return results.slice().sort(sortPopularity); case "rating-desc": return results.slice().sort(sortRating); case "age-asc": return results.slice().sort(sortNew); case "price-asc": return results.slice().sort(sortPrice); default: return results; } }
javascript
{ "resource": "" }
q22716
getSVGGraphPathData
train
function getSVGGraphPathData(data, width, height) { var max = Math.max.apply(null, data); var width = 800; var height = 100; var scaleH = width / (data.length - 1) var scaleV = height / max; var factor = 0.25; var commands = [`m0,${applyScaleV(data[0])}`]; function round(val) { return Math.round(val * 1000) / 1000; } function applyScaleH(val) { return round(val * scaleH); } function applyScaleV(val) { return round(100 - val * scaleV); } for (let i = 0, max = data.length - 1; i < max; i++) { current = data[i]; next = data[i + 1]; let x = (i + 0.5); let y = current + (next - current) * 0.5 let sX = (i + (0.5 - factor)); let sY = current + (next - current) * (0.5 - factor); commands.push(`S${applyScaleH(sX)} ${applyScaleV(sY)},${applyScaleH(x)} ${applyScaleV(y)}`); } var finalY = data[data.length - 1]; commands.push(`S${width} ${applyScaleV(finalY)},${width} ${applyScaleV(finalY)}`); return commands.join(' '); }
javascript
{ "resource": "" }
q22717
handleHashChange_
train
function handleHashChange_() { cssTranspiler.getCssWithVars(getUrlCssVars()).then(updatedStyles => { iframeManager.setStyle(updatedStyles); }).catch(error => { // Don't set the styles, log the error console.error(error); }); }
javascript
{ "resource": "" }
q22718
argPoint
train
function argPoint(bbox, args) { var x = args.x; if (util.isString(x)) { x = parseFloat(x) / 100 * bbox.width; } var y = args.y; if (util.isString(y)) { y = parseFloat(y) / 100 * bbox.height; } return g.point(x || 0, y || 0); }
javascript
{ "resource": "" }
q22719
findLineIntersections
train
function findLineIntersections(line, crossCheckLines) { return util.toArray(crossCheckLines).reduce(function(res, crossCheckLine) { var intersection = line.intersection(crossCheckLine); if (intersection) { res.push(intersection); } return res; }, []); }
javascript
{ "resource": "" }
q22720
createJumps
train
function createJumps(line, intersections, jumpSize) { return intersections.reduce(function(resultLines, point, idx) { // skipping points that were merged with the previous line // to make bigger arc over multiple lines that are close to each other if (point.skip === true) { return resultLines; } // always grab the last line from buffer and modify it var lastLine = resultLines.pop() || line; // calculate start and end of jump by moving by a given size of jump var jumpStart = g.point(point).move(lastLine.start, -(jumpSize)); var jumpEnd = g.point(point).move(lastLine.start, +(jumpSize)); // now try to look at the next intersection point var nextPoint = intersections[idx + 1]; if (nextPoint != null) { var distance = jumpEnd.distance(nextPoint); if (distance <= jumpSize) { // next point is close enough, move the jump end by this // difference and mark the next point to be skipped jumpEnd = nextPoint.move(lastLine.start, distance); nextPoint.skip = true; } } else { // this block is inside of `else` as an optimization so the distance is // not calculated when we know there are no other intersection points var endDistance = jumpStart.distance(lastLine.end); // if the end is too close to possible jump, draw remaining line instead of a jump if (endDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) { resultLines.push(lastLine); return resultLines; } } var startDistance = jumpEnd.distance(lastLine.start); if (startDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) { // if the start of line is too close to jump, draw that line instead of a jump resultLines.push(lastLine); return resultLines; } // finally create a jump line var jumpLine = g.line(jumpStart, jumpEnd); // it's just simple line but with a `isJump` property jumpLine.isJump = true; resultLines.push( g.line(lastLine.start, jumpStart), jumpLine, g.line(jumpEnd, lastLine.end) ); return resultLines; }, []); }
javascript
{ "resource": "" }
q22721
train
function() { var step = this.step; return { x: -step, y: -step, width: 2 * step, height: 2 * step }; }
javascript
{ "resource": "" }
q22722
getTargetBBox
train
function getTargetBBox(linkView, opt) { // expand by padding box if (opt && opt.paddingBox) return linkView.targetBBox.clone().moveAndExpand(opt.paddingBox); return linkView.targetBBox.clone(); }
javascript
{ "resource": "" }
q22723
getSourceAnchor
train
function getSourceAnchor(linkView, opt) { if (linkView.sourceAnchor) return linkView.sourceAnchor; // fallback: center of bbox var sourceBBox = getSourceBBox(linkView, opt); return sourceBBox.center(); }
javascript
{ "resource": "" }
q22724
getTargetAnchor
train
function getTargetAnchor(linkView, opt) { if (linkView.targetAnchor) return linkView.targetAnchor; // fallback: center of bbox var targetBBox = getTargetBBox(linkView, opt); return targetBBox.center(); // default }
javascript
{ "resource": "" }
q22725
getDirectionAngle
train
function getDirectionAngle(start, end, numDirections, grid, opt) { var quadrant = 360 / numDirections; var angleTheta = start.theta(fixAngleEnd(start, end, grid, opt)); var normalizedAngle = g.normalizeAngle(angleTheta + (quadrant / 2)); return quadrant * Math.floor(normalizedAngle / quadrant); }
javascript
{ "resource": "" }
q22726
getDirectionChange
train
function getDirectionChange(angle1, angle2) { var directionChange = Math.abs(angle1 - angle2); return (directionChange > 180) ? (360 - directionChange) : directionChange; }
javascript
{ "resource": "" }
q22727
getGridOffsets
train
function getGridOffsets(directions, grid, opt) { var step = opt.step; util.toArray(opt.directions).forEach(function(direction) { direction.gridOffsetX = (direction.offsetX / step) * grid.x; direction.gridOffsetY = (direction.offsetY / step) * grid.y; }); }
javascript
{ "resource": "" }
q22728
getGrid
train
function getGrid(step, source, target) { return { source: source.clone(), x: getGridDimension(target.x - source.x, step), y: getGridDimension(target.y - source.y, step) }; }
javascript
{ "resource": "" }
q22729
snapToGrid
train
function snapToGrid(point, grid) { var source = grid.source; var snappedX = g.snapToGrid(point.x - source.x, grid.x) + source.x; var snappedY = g.snapToGrid(point.y - source.y, grid.y) + source.y; return new g.Point(snappedX, snappedY); }
javascript
{ "resource": "" }
q22730
align
train
function align(point, grid, precision) { return round(snapToGrid(point.clone(), grid), precision); }
javascript
{ "resource": "" }
q22731
normalizePoint
train
function normalizePoint(point) { return new g.Point( point.x === 0 ? 0 : Math.abs(point.x) / point.x, point.y === 0 ? 0 : Math.abs(point.y) / point.y ); }
javascript
{ "resource": "" }
q22732
estimateCost
train
function estimateCost(from, endPoints) { var min = Infinity; for (var i = 0, len = endPoints.length; i < len; i++) { var cost = from.manhattanDistance(endPoints[i]); if (cost < min) min = cost; } return min; }
javascript
{ "resource": "" }
q22733
resolveOptions
train
function resolveOptions(opt) { opt.directions = util.result(opt, 'directions'); opt.penalties = util.result(opt, 'penalties'); opt.paddingBox = util.result(opt, 'paddingBox'); opt.padding = util.result(opt, 'padding'); if (opt.padding) { // if both provided, opt.padding wins over opt.paddingBox var sides = util.normalizeSides(opt.padding); opt.paddingBox = { x: -sides.left, y: -sides.top, width: sides.left + sides.right, height: sides.top + sides.bottom }; } util.toArray(opt.directions).forEach(function(direction) { var point1 = new g.Point(0, 0); var point2 = new g.Point(direction.offsetX, direction.offsetY); direction.angle = g.normalizeAngle(point1.theta(point2)); }); }
javascript
{ "resource": "" }
q22734
router
train
function router(vertices, opt, linkView) { resolveOptions(opt); // enable/disable linkView perpendicular option linkView.options.perpendicular = !!opt.perpendicular; var sourceBBox = getSourceBBox(linkView, opt); var targetBBox = getTargetBBox(linkView, opt); var sourceAnchor = getSourceAnchor(linkView, opt); //var targetAnchor = getTargetAnchor(linkView, opt); // pathfinding var map = (new ObstacleMap(opt)).build(linkView.paper.model, linkView.model); var oldVertices = util.toArray(vertices).map(g.Point); var newVertices = []; var tailPoint = sourceAnchor; // the origin of first route's grid, does not need snapping // find a route by concatenating all partial routes (routes need to pass through vertices) // source -> vertex[1] -> ... -> vertex[n] -> target var to, from; for (var i = 0, len = oldVertices.length; i <= len; i++) { var partialRoute = null; from = to || sourceBBox; to = oldVertices[i]; if (!to) { // this is the last iteration // we ran through all vertices in oldVertices // 'to' is not a vertex. to = targetBBox; // If the target is a point (i.e. it's not an element), we // should use dragging route instead of main routing method if it has been provided. var isEndingAtPoint = !linkView.model.get('source').id || !linkView.model.get('target').id; if (isEndingAtPoint && util.isFunction(opt.draggingRoute)) { // Make sure we are passing points only (not rects). var dragFrom = (from === sourceBBox) ? sourceAnchor : from; var dragTo = to.origin(); partialRoute = opt.draggingRoute.call(linkView, dragFrom, dragTo, opt); } } // if partial route has not been calculated yet use the main routing method to find one partialRoute = partialRoute || findRoute.call(linkView, from, to, map, opt); if (partialRoute === null) { // the partial route cannot be found return opt.fallbackRouter(vertices, opt, linkView); } var leadPoint = partialRoute[0]; // remove the first point if the previous partial route had the same point as last if (leadPoint && leadPoint.equals(tailPoint)) partialRoute.shift(); // save tailPoint for next iteration tailPoint = partialRoute[partialRoute.length - 1] || tailPoint; Array.prototype.push.apply(newVertices, partialRoute); } return newVertices; }
javascript
{ "resource": "" }
q22735
TypedArray
train
function TypedArray(arg1) { var result; if (typeof arg1 === 'number') { result = new Array(arg1); for (var i = 0; i < arg1; ++i) { result[i] = 0; } } else { result = arg1.slice(0); } result.subarray = subarray; result.buffer = result; result.byteLength = result.length; result.set = set_; if (typeof arg1 === 'object' && arg1.buffer) { result.buffer = arg1.buffer; } return result; }
javascript
{ "resource": "" }
q22736
train
function(knots) { console.warn('deprecated'); var firstControlPoints = []; var secondControlPoints = []; var n = knots.length - 1; var i; // Special case: Bezier curve should be a straight line. if (n == 1) { // 3P1 = 2P0 + P3 firstControlPoints[0] = new Point( (2 * knots[0].x + knots[1].x) / 3, (2 * knots[0].y + knots[1].y) / 3 ); // P2 = 2P1 – P0 secondControlPoints[0] = new Point( 2 * firstControlPoints[0].x - knots[0].x, 2 * firstControlPoints[0].y - knots[0].y ); return [firstControlPoints, secondControlPoints]; } // Calculate first Bezier control points. // Right hand side vector. var rhs = []; // Set right hand side X values. for (i = 1; i < n - 1; i++) { rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x; } rhs[0] = knots[0].x + 2 * knots[1].x; rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0; // Get first control points X-values. var x = this.getFirstControlPoints(rhs); // Set right hand side Y values. for (i = 1; i < n - 1; ++i) { rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y; } rhs[0] = knots[0].y + 2 * knots[1].y; rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0; // Get first control points Y-values. var y = this.getFirstControlPoints(rhs); // Fill output arrays. for (i = 0; i < n; i++) { // First control point. firstControlPoints.push(new Point(x[i], y[i])); // Second control point. if (i < n - 1) { secondControlPoints.push(new Point( 2 * knots [i + 1].x - x[i + 1], 2 * knots[i + 1].y - y[i + 1] )); } else { secondControlPoints.push(new Point( (knots[n].x + x[n - 1]) / 2, (knots[n].y + y[n - 1]) / 2) ); } } return [firstControlPoints, secondControlPoints]; }
javascript
{ "resource": "" }
q22737
train
function(c) { return !!c && this.start.x === c.start.x && this.start.y === c.start.y && this.controlPoint1.x === c.controlPoint1.x && this.controlPoint1.y === c.controlPoint1.y && this.controlPoint2.x === c.controlPoint2.x && this.controlPoint2.y === c.controlPoint2.y && this.end.x === c.end.x && this.end.y === c.end.y; }
javascript
{ "resource": "" }
q22738
train
function(t) { var start = this.start; var control1 = this.controlPoint1; var control2 = this.controlPoint2; var end = this.end; // shortcuts for `t` values that are out of range if (t <= 0) { return { startControlPoint1: start.clone(), startControlPoint2: start.clone(), divider: start.clone(), dividerControlPoint1: control1.clone(), dividerControlPoint2: control2.clone() }; } if (t >= 1) { return { startControlPoint1: control1.clone(), startControlPoint2: control2.clone(), divider: end.clone(), dividerControlPoint1: end.clone(), dividerControlPoint2: end.clone() }; } var midpoint1 = (new Line(start, control1)).pointAt(t); var midpoint2 = (new Line(control1, control2)).pointAt(t); var midpoint3 = (new Line(control2, end)).pointAt(t); var subControl1 = (new Line(midpoint1, midpoint2)).pointAt(t); var subControl2 = (new Line(midpoint2, midpoint3)).pointAt(t); var divider = (new Line(subControl1, subControl2)).pointAt(t); var output = { startControlPoint1: midpoint1, startControlPoint2: subControl1, divider: divider, dividerControlPoint1: subControl2, dividerControlPoint2: midpoint3 }; return output; }
javascript
{ "resource": "" }
q22739
train
function(opt) { opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSubdivisions() call var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions; // not using localOpt var length = 0; var n = subdivisions.length; for (var i = 0; i < n; i++) { var currentSubdivision = subdivisions[i]; length += currentSubdivision.endpointDistance(); } return length; }
javascript
{ "resource": "" }
q22740
train
function(ratio, opt) { if (!this.isDifferentiable()) return null; if (ratio < 0) ratio = 0; else if (ratio > 1) ratio = 1; var t = this.tAt(ratio, opt); return this.tangentAtT(t); }
javascript
{ "resource": "" }
q22741
train
function(length, opt) { if (!this.isDifferentiable()) return null; var t = this.tAtLength(length, opt); return this.tangentAtT(t); }
javascript
{ "resource": "" }
q22742
train
function(t) { if (!this.isDifferentiable()) return null; if (t < 0) t = 0; else if (t > 1) t = 1; var skeletonPoints = this.getSkeletonPoints(t); var p1 = skeletonPoints.startControlPoint2; var p2 = skeletonPoints.dividerControlPoint1; var tangentStart = skeletonPoints.divider; var tangentLine = new Line(p1, p2); tangentLine.translate(tangentStart.x - p1.x, tangentStart.y - p1.y); // move so that tangent line starts at the point requested return tangentLine; }
javascript
{ "resource": "" }
q22743
train
function(ratio, opt) { if (ratio <= 0) return 0; if (ratio >= 1) return 1; opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions; var localOpt = { precision: precision, subdivisions: subdivisions }; var curveLength = this.length(localOpt); var length = curveLength * ratio; return this.tAtLength(length, localOpt); }
javascript
{ "resource": "" }
q22744
train
function(dx, dy) { if (dx === undefined) { dx = 0; } if (dy === undefined) { dy = dx; } this.a += 2 * dx; this.b += 2 * dy; return this; }
javascript
{ "resource": "" }
q22745
train
function(p) { var refPointDelta = 30; var x0 = p.x; var y0 = p.y; var a = this.a; var b = this.b; var center = this.bbox().center(); var m = center.x; var n = center.y; var q1 = x0 > center.x + a / 2; var q3 = x0 < center.x - a / 2; var y, x; if (q1 || q3) { y = x0 > center.x ? y0 - refPointDelta : y0 + refPointDelta; x = (a * a / (x0 - m)) - (a * a * (y0 - n) * (y - n)) / (b * b * (x0 - m)) + m; } else { x = y0 > center.y ? x0 + refPointDelta : x0 - refPointDelta; y = ( b * b / (y0 - n)) - (b * b * (x0 - m) * (x - m)) / (a * a * (y0 - n)) + n; } return (new Point(x, y)).theta(p); }
javascript
{ "resource": "" }
q22746
train
function(arg) { var segments = this.segments; var numSegments = segments.length; // works even if path has no segments var currentSegment; var previousSegment = ((numSegments !== 0) ? segments[numSegments - 1] : null); // if we are appending to an empty path, previousSegment is null var nextSegment = null; if (!Array.isArray(arg)) { // arg is a segment if (!arg || !arg.isSegment) throw new Error('Segment required.'); currentSegment = this.prepareSegment(arg, previousSegment, nextSegment); segments.push(currentSegment); } else { // arg is an array of segments if (!arg[0].isSegment) throw new Error('Segments required.'); var n = arg.length; for (var i = 0; i < n; i++) { var currentArg = arg[i]; currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment); segments.push(currentSegment); previousSegment = currentSegment; } } }
javascript
{ "resource": "" }
q22747
train
function() { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array var bbox; for (var i = 0; i < numSegments; i++) { var segment = segments[i]; if (segment.isVisible) { var segmentBBox = segment.bbox(); bbox = bbox ? bbox.union(segmentBBox) : segmentBBox; } } if (bbox) return bbox; // if the path has only invisible elements, return end point of last segment var lastSegment = segments[numSegments - 1]; return new Rect(lastSegment.end.x, lastSegment.end.y, 0, 0); }
javascript
{ "resource": "" }
q22748
train
function() { var segments = this.segments; var numSegments = segments.length; // works even if path has no segments var path = new Path(); for (var i = 0; i < numSegments; i++) { var segment = segments[i].clone(); path.appendSegment(segment); } return path; }
javascript
{ "resource": "" }
q22749
train
function(p) { if (!p) return false; var segments = this.segments; var otherSegments = p.segments; var numSegments = segments.length; if (otherSegments.length !== numSegments) return false; // if the two paths have different number of segments, they cannot be equal for (var i = 0; i < numSegments; i++) { var segment = segments[i]; var otherSegment = otherSegments[i]; // as soon as an inequality is found in segments, return false if ((segment.type !== otherSegment.type) || (!segment.equals(otherSegment))) return false; } // if no inequality found in segments, return true return true; }
javascript
{ "resource": "" }
q22750
train
function(index) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) throw new Error('Path has no segments.'); if (index < 0) index = numSegments + index; // convert negative indices to positive if (index >= numSegments || index < 0) throw new Error('Index out of range.'); return segments[index]; }
javascript
{ "resource": "" }
q22751
train
function(opt) { var segments = this.segments; var numSegments = segments.length; // works even if path has no segments opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // not using opt.segmentSubdivisions // not using localOpt var segmentSubdivisions = []; for (var i = 0; i < numSegments; i++) { var segment = segments[i]; var subdivisions = segment.getSubdivisions({ precision: precision }); segmentSubdivisions.push(subdivisions); } return segmentSubdivisions; }
javascript
{ "resource": "" }
q22752
train
function(opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return 0; // if segments is an empty array opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSegmentSubdivisions() call var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; // not using localOpt var length = 0; for (var i = 0; i < numSegments; i++) { var segment = segments[i]; var subdivisions = segmentSubdivisions[i]; length += segment.length({ subdivisions: subdivisions }); } return length; }
javascript
{ "resource": "" }
q22753
train
function(ratio, opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array if (ratio <= 0) return this.start.clone(); if (ratio >= 1) return this.end.clone(); opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions }; var pathLength = this.length(localOpt); var length = pathLength * ratio; return this.pointAtLength(length, localOpt); }
javascript
{ "resource": "" }
q22754
train
function(length, opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array if (length === 0) return this.start.clone(); var fromStart = true; if (length < 0) { fromStart = false; // negative lengths mean start calculation from end point length = -length; // absolute value } opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; // not using localOpt var lastVisibleSegment; var l = 0; // length so far for (var i = (fromStart ? 0 : (numSegments - 1)); (fromStart ? (i < numSegments) : (i >= 0)); (fromStart ? (i++) : (i--))) { var segment = segments[i]; var subdivisions = segmentSubdivisions[i]; var d = segment.length({ precision: precision, subdivisions: subdivisions }); if (segment.isVisible) { if (length <= (l + d)) { return segment.pointAtLength(((fromStart ? 1 : -1) * (length - l)), { precision: precision, subdivisions: subdivisions }); } lastVisibleSegment = segment; } l += d; } // if length requested is higher than the length of the path, return last visible segment endpoint if (lastVisibleSegment) return (fromStart ? lastVisibleSegment.end : lastVisibleSegment.start); // if no visible segment, return last segment end point (no matter if fromStart or no) var lastSegment = segments[numSegments - 1]; return lastSegment.end.clone(); }
javascript
{ "resource": "" }
q22755
train
function(segment, previousSegment, nextSegment) { // insert after previous segment and before previous segment's next segment segment.previousSegment = previousSegment; segment.nextSegment = nextSegment; if (previousSegment) previousSegment.nextSegment = segment; if (nextSegment) nextSegment.previousSegment = segment; var updateSubpathStart = segment; if (segment.isSubpathStart) { segment.subpathStartSegment = segment; // assign self as subpath start segment updateSubpathStart = nextSegment; // start updating from next segment } // assign previous segment's subpath start (or self if it is a subpath start) to subsequent segments if (updateSubpathStart) this.updateSubpathStartSegment(updateSubpathStart); return segment; }
javascript
{ "resource": "" }
q22756
train
function(index) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) throw new Error('Path has no segments.'); if (index < 0) index = numSegments + index; // convert negative indices to positive if (index >= numSegments || index < 0) throw new Error('Index out of range.'); var removedSegment = segments.splice(index, 1)[0]; var previousSegment = removedSegment.previousSegment; var nextSegment = removedSegment.nextSegment; // link the previous and next segments together (if present) if (previousSegment) previousSegment.nextSegment = nextSegment; // may be null if (nextSegment) nextSegment.previousSegment = previousSegment; // may be null // if removed segment used to start a subpath, update all subsequent segments until another subpath start segment is reached if (removedSegment.isSubpathStart && nextSegment) this.updateSubpathStartSegment(nextSegment); }
javascript
{ "resource": "" }
q22757
train
function(length, opt) { var segments = this.segments; var numSegments = segments.length; if (numSegments === 0) return null; // if segments is an empty array var fromStart = true; if (length < 0) { fromStart = false; // negative lengths mean start calculation from end point length = -length; // absolute value } opt = opt || {}; var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions; // not using localOpt var lastValidSegment; // visible AND differentiable (with a tangent) var l = 0; // length so far for (var i = (fromStart ? 0 : (numSegments - 1)); (fromStart ? (i < numSegments) : (i >= 0)); (fromStart ? (i++) : (i--))) { var segment = segments[i]; var subdivisions = segmentSubdivisions[i]; var d = segment.length({ precision: precision, subdivisions: subdivisions }); if (segment.isDifferentiable()) { if (length <= (l + d)) { return segment.tangentAtLength(((fromStart ? 1 : -1) * (length - l)), { precision: precision, subdivisions: subdivisions }); } lastValidSegment = segment; } l += d; } // if length requested is higher than the length of the path, return tangent of endpoint of last valid segment if (lastValidSegment) { var t = (fromStart ? 1 : 0); return lastValidSegment.tangentAtT(t); } // if no valid segment, return null return null; }
javascript
{ "resource": "" }
q22758
train
function(segment) { var previousSegment = segment.previousSegment; // may be null while (segment && !segment.isSubpathStart) { // assign previous segment's subpath start segment to this segment if (previousSegment) segment.subpathStartSegment = previousSegment.subpathStartSegment; // may be null else segment.subpathStartSegment = null; // if segment had no previous segment, assign null - creates an invalid path! previousSegment = segment; segment = segment.nextSegment; // move on to the segment after etc. } }
javascript
{ "resource": "" }
q22759
train
function(ref, distance) { var theta = toRad((new Point(ref)).theta(this)); var offset = this.offset(cos(theta) * distance, -sin(theta) * distance); return offset; }
javascript
{ "resource": "" }
q22760
train
function(sx, sy, origin) { origin = (origin && new Point(origin)) || new Point(0, 0); this.x = origin.x + sx * (this.x - origin.x); this.y = origin.y + sy * (this.y - origin.y); return this; }
javascript
{ "resource": "" }
q22761
train
function(o) { o = (o && new Point(o)) || new Point(0, 0); var x = this.x; var y = this.y; this.x = sqrt((x - o.x) * (x - o.x) + (y - o.y) * (y - o.y)); // r this.y = toRad(o.theta(new Point(x, y))); return this; }
javascript
{ "resource": "" }
q22762
train
function(p) { if (!p) return false; var points = this.points; var otherPoints = p.points; var numPoints = points.length; if (otherPoints.length !== numPoints) return false; // if the two polylines have different number of points, they cannot be equal for (var i = 0; i < numPoints; i++) { var point = points[i]; var otherPoint = p.points[i]; // as soon as an inequality is found in points, return false if (!point.equals(otherPoint)) return false; } // if no inequality found in points, return true return true; }
javascript
{ "resource": "" }
q22763
train
function() { var points = this.points; var numPoints = points.length; if (numPoints === 0) return ''; // if points array is empty var output = ''; for (var i = 0; i < numPoints; i++) { var point = points[i]; output += point.x + ',' + point.y + ' '; } return output.trim(); }
javascript
{ "resource": "" }
q22764
train
function(angle) { if (!angle) return this.clone(); var theta = toRad(angle); var st = abs(sin(theta)); var ct = abs(cos(theta)); var w = this.width * ct + this.height * st; var h = this.width * st + this.height * ct; return new Rect(this.x + (this.width - w) / 2, this.y + (this.height - h) / 2, w, h); }
javascript
{ "resource": "" }
q22765
train
function(p, angle) { p = new Point(p); var center = new Point(this.x + this.width / 2, this.y + this.height / 2); var result; if (angle) p.rotate(center, angle); // (clockwise, starting from the top side) var sides = [ this.topLine(), this.rightLine(), this.bottomLine(), this.leftLine() ]; var connector = new Line(center, p); for (var i = sides.length - 1; i >= 0; --i) { var intersection = sides[i].intersection(connector); if (intersection !== null) { result = intersection; break; } } if (result && angle) result.rotate(center, -angle); return result; }
javascript
{ "resource": "" }
q22766
train
function(sx, sy, origin) { origin = this.origin().scale(sx, sy, origin); this.x = origin.x; this.y = origin.y; this.width *= sx; this.height *= sy; return this; }
javascript
{ "resource": "" }
q22767
train
function(domain, range, value) { var domainSpan = domain[1] - domain[0]; var rangeSpan = range[1] - range[0]; return (((value - domain[0]) / domainSpan) * rangeSpan + range[0]) || 0; }
javascript
{ "resource": "" }
q22768
train
function() { var args = []; var n = arguments.length; for (var i = 0; i < n; i++) { args.push(arguments[i]); } if (!(this instanceof Closepath)) { // switching context of `this` to Closepath when called without `new` return applyToNew(Closepath, args); } if (n > 0) { throw new Error('Closepath constructor expects no arguments.'); } return this; }
javascript
{ "resource": "" }
q22769
train
function(obj) { this.guid.id = this.guid.id || 1; obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id); return obj.id; }
javascript
{ "resource": "" }
q22770
train
function(blob, fileName) { if (window.navigator.msSaveBlob) { // requires IE 10+ // pulls up a save dialog window.navigator.msSaveBlob(blob, fileName); } else { // other browsers // downloads directly in Chrome and Safari // presents a save/open dialog in Firefox // Firefox bug: `from` field in save dialog always shows `from:blob:` // https://bugzilla.mozilla.org/show_bug.cgi?id=1053327 var url = window.URL.createObjectURL(blob); var link = document.createElement('a'); link.href = url; link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(url); // mark the url for garbage collection } }
javascript
{ "resource": "" }
q22771
train
function(dataUri, fileName) { var blob = joint.util.dataUriToBlob(dataUri); joint.util.downloadBlob(blob, fileName); }
javascript
{ "resource": "" }
q22772
train
function(url, callback) { if (!url || url.substr(0, 'data:'.length) === 'data:') { // No need to convert to data uri if it is already in data uri. // This not only convenient but desired. For example, // IE throws a security error if data:image/svg+xml is used to render // an image to the canvas and an attempt is made to read out data uri. // Now if our image is already in data uri, there is no need to render it to the canvas // and so we can bypass this error. // Keep the async nature of the function. return setTimeout(function() { callback(null, url); }, 0); } // chrome, IE10+ var modernHandler = function(xhr, callback) { if (xhr.status === 200) { var reader = new FileReader(); reader.onload = function(evt) { var dataUri = evt.target.result; callback(null, dataUri); }; reader.onerror = function() { callback(new Error('Failed to load image ' + url)); }; reader.readAsDataURL(xhr.response); } else { callback(new Error('Failed to load image ' + url)); } }; var legacyHandler = function(xhr, callback) { var Uint8ToString = function(u8a) { var CHUNK_SZ = 0x8000; var c = []; for (var i = 0; i < u8a.length; i += CHUNK_SZ) { c.push(String.fromCharCode.apply(null, u8a.subarray(i, i + CHUNK_SZ))); } return c.join(''); }; if (xhr.status === 200) { var bytes = new Uint8Array(xhr.response); var suffix = (url.split('.').pop()) || 'png'; var map = { 'svg': 'svg+xml' }; var meta = 'data:image/' + (map[suffix] || suffix) + ';base64,'; var b64encoded = meta + btoa(Uint8ToString(bytes)); callback(null, b64encoded); } else { callback(new Error('Failed to load image ' + url)); } }; var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.addEventListener('error', function() { callback(new Error('Failed to load image ' + url)); }); xhr.responseType = window.FileReader ? 'blob' : 'arraybuffer'; xhr.addEventListener('load', function() { if (window.FileReader) { modernHandler(xhr, callback); } else { legacyHandler(xhr, callback); } }); xhr.send(); }
javascript
{ "resource": "" }
q22773
train
function(xhr, callback) { if (xhr.status === 200) { var reader = new FileReader(); reader.onload = function(evt) { var dataUri = evt.target.result; callback(null, dataUri); }; reader.onerror = function() { callback(new Error('Failed to load image ' + url)); }; reader.readAsDataURL(xhr.response); } else { callback(new Error('Failed to load image ' + url)); } }
javascript
{ "resource": "" }
q22774
train
function(el) { this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); this.el = this.$el[0]; if (this.svgElement) this.vel = V(this.el); }
javascript
{ "resource": "" }
q22775
train
function(cells, opt) { var preparedCells = joint.util.toArray(cells).map(function(cell) { return this._prepareCell(cell, opt); }, this); this.get('cells').reset(preparedCells, opt); return this; }
javascript
{ "resource": "" }
q22776
train
function(elementA, elementB) { var isSuccessor = false; this.search(elementA, function(element) { if (element === elementB && element !== elementA) { isSuccessor = true; return false; } }, { outbound: true }); return isSuccessor; }
javascript
{ "resource": "" }
q22777
train
function(elementA, elementB) { var isPredecessor = false; this.search(elementA, function(element) { if (element === elementB && element !== elementA) { isPredecessor = true; return false; } }, { inbound: true }); return isPredecessor; }
javascript
{ "resource": "" }
q22778
train
function(model, opt) { this.getConnectedLinks(model).forEach(function(link) { link.set((link.source().id === model.id ? 'source' : 'target'), { x: 0, y: 0 }, opt); }); }
javascript
{ "resource": "" }
q22779
train
function(rect, opt) { rect = g.rect(rect); opt = joint.util.defaults(opt || {}, { strict: false }); var method = opt.strict ? 'containsRect' : 'intersect'; return this.getElements().filter(function(el) { return rect[method](el.getBBox()); }); }
javascript
{ "resource": "" }
q22780
train
function(element, opt) { opt = joint.util.defaults(opt || {}, { searchBy: 'bbox' }); var bbox = element.getBBox(); var elements = (opt.searchBy === 'bbox') ? this.findModelsInArea(bbox) : this.findModelsFromPoint(bbox[opt.searchBy]()); // don't account element itself or any of its descendents return elements.filter(function(el) { return element.id !== el.id && !el.isEmbeddedIn(element); }); }
javascript
{ "resource": "" }
q22781
train
function(cells, opt) { return joint.util.toArray(cells).reduce(function(memo, cell) { if (cell.isLink()) return memo; var rect = cell.getBBox(opt); var angle = cell.angle(); if (angle) rect = rect.bbox(angle); if (memo) { return memo.union(rect); } else { return rect; } }, null); }
javascript
{ "resource": "" }
q22782
dWrapper
train
function dWrapper(opt) { function pathConstructor(value) { return new g.Path(V.normalizePathData(value)); } var shape = shapeWrapper(pathConstructor, opt); return function(value, refBBox, node) { var path = shape(value, refBBox, node); return { d: path.serialize() }; }; }
javascript
{ "resource": "" }
q22783
pointsWrapper
train
function pointsWrapper(opt) { var shape = shapeWrapper(g.Polyline, opt); return function(value, refBBox, node) { var polyline = shape(value, refBBox, node); return { points: polyline.serialize() }; }; }
javascript
{ "resource": "" }
q22784
train
function() { var ancestors = []; if (!this.graph) { return ancestors; } var parentCell = this.getParentCell(); while (parentCell) { ancestors.push(parentCell); parentCell = parentCell.getParentCell(); } return ancestors; }
javascript
{ "resource": "" }
q22785
train
function(path, opt) { // Once a property is removed from the `attrs` attribute // the cellView will recognize a `dirty` flag and rerender itself // in order to remove the attribute from SVG element. opt = opt || {}; opt.dirty = true; var pathArray = Array.isArray(path) ? path : path.split('/'); if (pathArray.length === 1) { // A top level property return this.unset(path, opt); } // A nested property var property = pathArray[0]; var nestedPath = pathArray.slice(1); var propertyValue = joint.util.cloneDeep(this.get(property)); joint.util.unsetByPath(propertyValue, nestedPath, '/'); return this.set(property, propertyValue, opt); }
javascript
{ "resource": "" }
q22786
train
function(attrs, value, opt) { var args = Array.from(arguments); if (args.length === 0) { return this.get('attrs'); } if (Array.isArray(attrs)) { args[0] = ['attrs'].concat(attrs); } else if (joint.util.isString(attrs)) { // Get/set an attribute by a special path syntax that delimits // nested objects by the colon character. args[0] = 'attrs/' + attrs; } else { args[0] = { 'attrs' : attrs }; } return this.prop.apply(this, args); }
javascript
{ "resource": "" }
q22787
train
function(path, opt) { if (Array.isArray(path)) { return this.removeProp(['attrs'].concat(path)); } return this.removeProp('attrs/' + path, opt); }
javascript
{ "resource": "" }
q22788
train
function(el) { var $el = this.$(el); var $rootEl = this.$el; if ($el.length === 0) { $el = $rootEl; } do { var magnet = $el.attr('magnet'); if ((magnet || $el.is($rootEl)) && magnet !== 'false') { return $el[0]; } $el = $el.parent(); } while ($el.length > 0); // If the overall cell has set `magnet === false`, then return `undefined` to // announce there is no magnet found for this cell. // This is especially useful to set on cells that have 'ports'. In this case, // only the ports have set `magnet === true` and the overall element has `magnet === false`. return undefined; }
javascript
{ "resource": "" }
q22789
train
function(el, prevSelector) { var selector; if (el === this.el) { if (typeof prevSelector === 'string') selector = '> ' + prevSelector; return selector; } if (el) { var nthChild = V(el).index() + 1; selector = el.tagName + ':nth-child(' + nthChild + ')'; if (prevSelector) { selector += ' > ' + prevSelector; } selector = this.getSelector(el.parentNode, selector); } return selector; }
javascript
{ "resource": "" }
q22790
train
function(angle, absolute, origin, opt) { if (origin) { var center = this.getBBox().center(); var size = this.get('size'); var position = this.get('position'); center.rotate(origin, this.get('angle') - angle); var dx = center.x - size.width / 2 - position.x; var dy = center.y - size.height / 2 - position.y; this.startBatch('rotate', { angle: angle, absolute: absolute, origin: origin }); this.position(position.x + dx, position.y + dy, opt); this.rotate(angle, absolute, null, opt); this.stopBatch('rotate'); } else { this.set('angle', absolute ? angle : (this.get('angle') + angle) % 360, opt); } return this; }
javascript
{ "resource": "" }
q22791
train
function() { var element = this.model; var markup = element.get('markup') || element.markup; if (!markup) throw new Error('dia.ElementView: markup required'); if (Array.isArray(markup)) return this.renderJSONMarkup(markup); if (typeof markup === 'string') return this.renderStringMarkup(markup); throw new Error('dia.ElementView: invalid markup'); }
javascript
{ "resource": "" }
q22792
train
function(evt, x, y) { var data = this.eventData(evt); if (data.embedding) this.finalizeEmbedding(data); }
javascript
{ "resource": "" }
q22793
train
function(idx, label, opt) { var labels = this.labels(); idx = (isFinite(idx) && idx !== null) ? (idx | 0) : 0; if (idx < 0) idx = labels.length + idx; // getter if (arguments.length <= 1) return this.prop(['labels', idx]); // setter return this.prop(['labels', idx], label, opt); }
javascript
{ "resource": "" }
q22794
train
function() { var connectionAncestor; if (this.graph) { var cells = [ this, this.getSourceElement(), // null if source is a point this.getTargetElement() // null if target is a point ].filter(function(item) { return !!item; }); connectionAncestor = this.graph.getCommonAncestor.apply(this.graph, cells); } return connectionAncestor || null; }
javascript
{ "resource": "" }
q22795
train
function(cell) { var cellId = (joint.util.isString(cell) || joint.util.isNumber(cell)) ? cell : cell.id; var ancestor = this.getRelationshipAncestor(); return !!ancestor && (ancestor.id === cellId || ancestor.isEmbeddedIn(cellId)); }
javascript
{ "resource": "" }
q22796
train
function() { var defaultLabel = this.get('defaultLabel') || this.defaultLabel || {}; var label = {}; label.markup = defaultLabel.markup || this.get('labelMarkup') || this.labelMarkup; label.position = defaultLabel.position; label.attrs = defaultLabel.attrs; label.size = defaultLabel.size; return label; }
javascript
{ "resource": "" }
q22797
train
function(endType) { // create handler for specific end type (source|target). var onModelChange = function(endModel, opt) { this.onEndModelChange(endType, endModel, opt); }; function watchEndModel(link, end) { end = end || {}; var endModel = null; var previousEnd = link.previous(endType) || {}; if (previousEnd.id) { this.stopListening(this.paper.getModelById(previousEnd.id), 'change', onModelChange); } if (end.id) { // If the observed model changes, it caches a new bbox and do the link update. endModel = this.paper.getModelById(end.id); this.listenTo(endModel, 'change', onModelChange); } onModelChange.call(this, endModel, { cacheOnly: true }); return this; } return watchEndModel; }
javascript
{ "resource": "" }
q22798
train
function(x, y, opt) { // accept input in form `{ x, y }, opt` or `x, y, opt` var isPointProvided = (typeof x !== 'number'); var localX = isPointProvided ? x.x : x; var localY = isPointProvided ? x.y : y; var localOpt = isPointProvided ? y : opt; var vertex = { x: localX, y: localY }; var idx = this.getVertexIndex(localX, localY); this.model.insertVertex(idx, vertex, localOpt); return idx; }
javascript
{ "resource": "" }
q22799
train
function(angle, cx, cy) { // getter if (angle === undefined) { return V.matrixToRotate(this.matrix()); } // setter // If the origin is not set explicitely, rotate around the center. Note that // we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us // the real bounding box (`bbox()`) including transformations). if (cx === undefined) { var bbox = this.viewport.getBBox(); cx = bbox.width / 2; cy = bbox.height / 2; } var ctm = this.matrix().translate(cx,cy).rotate(angle).translate(-cx,-cy); this.matrix(ctm); return this; }
javascript
{ "resource": "" }