_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q59100
initMatic
validation
function initMatic() { if (!matic) { matic = new Matic({ maticProvider: process.env.MATIC_PROVIDER, parentProvider: process.env.PARENT_PROVIDER, rootChainAddress: process.env.ROOTCHAIN_ADDRESS, maticWethAddress: process.env.MATIC_WETH_ADDRESS, syncerUrl: process.env.SYNCER_URL, watcherUrl: process.env.WATCHER_URL, withdrawManagerAddress: process.env.WITHDRAWMANAGER_ADDRESS, }) matic.wallet = '<private-key>' // your private key } }
javascript
{ "resource": "" }
q59101
matchPath
validation
function matchPath(pathname, options = {}) { if (typeof options === 'string') options = { path: options }; const { path, exact = false, strict = false, sensitive = false } = options; const paths = [].concat(path); return paths.reduce((matched, p) => { if (matched) return matched; const { regexp, keys } = compilePath(p, { end: exact, strict, sensitive }); const match = regexp.exec(pathname); if (!match) return null; const [url, ...values] = match; const isExact = pathname === url; if (exact && !isExact) return null; return { path: p, // the p used to match url: p === '/' && url === '' ? '/' : url, // the matched portion of the URL isExact, // whether or not we matched exactly params: keys.reduce((memo, key, index) => { memo[key.name] = values[index]; return memo; }, {}) }; }, null); }
javascript
{ "resource": "" }
q59102
Redirect
validation
function Redirect({ computedMatch, to, push = false }) { return ( <RouterContext.Consumer> {(context) => { invariant(context, 'You should not use <Redirect> outside a <Router>'); const { history, staticContext } = context; const method = push ? history.push : history.replace; const location = createLocation( computedMatch ? typeof to === 'string' ? generatePath(to, computedMatch.params) : { ...to, pathname: generatePath(to.pathname, computedMatch.params) } : to ); // When rendering in a static context, // set the new location immediately. if (staticContext) { method(location); return null; } return ( <Lifecycle onMount={() => { method(location); }} onUpdate={(self, prevProps) => { const prevLocation = createLocation(prevProps.to); if ( !locationsAreEqual(prevLocation, { ...location, key: prevLocation.key }) ) { method(location); } }} to={to} /> ); }} </RouterContext.Consumer> ); }
javascript
{ "resource": "" }
q59103
entities
validation
function entities(state = { users: {}, repos: {} }, action) { if (action.response && action.response.entities) { return merge({}, state, action.response.entities) } return state }
javascript
{ "resource": "" }
q59104
errorMessage
validation
function errorMessage(state = null, action) { const { type, error } = action if (type === ActionTypes.RESET_ERROR_MESSAGE) { return null } else if (error) { return action.error } return state }
javascript
{ "resource": "" }
q59105
cancelMain
validation
function cancelMain() { if (mainTask.isRunning && !mainTask.isCancelled) { mainTask.isCancelled = true next(TASK_CANCEL) } }
javascript
{ "resource": "" }
q59106
currCb
validation
function currCb(res, isErr) { if (effectSettled) { return } effectSettled = true cb.cancel = noop // defensive measure if (sagaMonitor) { isErr ? sagaMonitor.effectRejected(effectId, res) : sagaMonitor.effectResolved(effectId, res) } cb(res, isErr) }
javascript
{ "resource": "" }
q59107
updateAttributes
validation
function updateAttributes(el, prevProps, props) { var propName; if (!props || prevProps === props) { return; } // Set attributes. for (propName in props) { if (!filterNonEntityPropNames(propName)) { continue; } doSetAttribute(el, props, propName); } // See if attributes were removed. if (prevProps) { for (propName in prevProps) { if (!filterNonEntityPropNames(propName)) { continue; } if (props[propName] === undefined) { el.removeAttribute(propName); } } } }
javascript
{ "resource": "" }
q59108
componentDidUpdate
validation
function componentDidUpdate(prevProps, prevState) { var el = this.el; var props = this.props; // Update events. updateEventListeners(el, prevProps.events, props.events); // Update entity. if (options.runSetAttributeOnUpdates) { updateAttributes(el, prevProps, props); } }
javascript
{ "resource": "" }
q59109
updateEventListeners
validation
function updateEventListeners(el, prevEvents, events) { var eventName; if (!prevEvents || !events || prevEvents === events) { return; } for (eventName in events) { // Didn't change. if (prevEvents[eventName] === events[eventName]) { continue; } // If changed, remove old previous event listeners. if (prevEvents[eventName]) { removeEventListeners(el, eventName, prevEvents[eventName]); } // Add new event listeners. addEventListeners(el, eventName, events[eventName]); } // See if event handlers were removed. for (eventName in prevEvents) { if (!events[eventName]) { removeEventListeners(el, eventName, prevEvents[eventName]); } } }
javascript
{ "resource": "" }
q59110
addEventListeners
validation
function addEventListeners(el, eventName, handlers) { var handler; var i; if (!handlers) { return; } // Convert to array. if (handlers.constructor === Function) { handlers = [handlers]; } // Register. for (i = 0; i < handlers.length; i++) { el.addEventListener(eventName, handlers[i]); } }
javascript
{ "resource": "" }
q59111
removeEventListeners
validation
function removeEventListeners(el, eventName, handlers) { var handler; var i; if (!handlers) { return; } // Convert to array. if (handlers.constructor === Function) { handlers = [handlers]; } // Unregister. for (i = 0; i < handlers.length; i++) { el.removeEventListener(eventName, handlers[i]); } }
javascript
{ "resource": "" }
q59112
makeHooksSafe
validation
function makeHooksSafe(routes, store) { if (Array.isArray(routes)) { return routes.map(route => makeHooksSafe(route, store)); } const onEnter = routes.onEnter; if (onEnter) { routes.onEnter = function safeOnEnter(...args) { try { store.getState(); } catch (err) { if (onEnter.length === 3) { args[2](); } // There's no store yet so ignore the hook return; } onEnter.apply(null, args); }; } if (routes.childRoutes) { makeHooksSafe(routes.childRoutes, store); } if (routes.indexRoute) { makeHooksSafe(routes.indexRoute, store); } return routes; }
javascript
{ "resource": "" }
q59113
auth
validation
function auth (req) { if (!req) { throw new TypeError('argument req is required') } if (typeof req !== 'object') { throw new TypeError('argument req is required to be an object') } // get header var header = getAuthorization(req) // parse header return parse(header) }
javascript
{ "resource": "" }
q59114
getAuthorization
validation
function getAuthorization (req) { if (!req.headers || typeof req.headers !== 'object') { throw new TypeError('argument req is required to have headers property') } return req.headers.authorization }
javascript
{ "resource": "" }
q59115
parse
validation
function parse (string) { if (typeof string !== 'string') { return undefined } // parse header var match = CREDENTIALS_REGEXP.exec(string) if (!match) { return undefined } // decode user pass var userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1])) if (!userPass) { return undefined } // return credentials object return new Credentials(userPass[1], userPass[2]) }
javascript
{ "resource": "" }
q59116
install
validation
function install(cef_version) { downloadCef(cef_version,function(err){ if(err) { util.log('Failed to add dependencies','error'); throw err; } copyDllWrapper(function(err) { if (err) { util.log('Failed to copy dll_wrapper.gyp'); throw err; } util.log('Done!'); }); }); }
javascript
{ "resource": "" }
q59117
download
validation
function download(url,onError) { var request = require('request'); util.log('Downloading cef tarball for '+platform+'-'+arch+'...'); var requestOpts = { uri: url, onResponse: true } // basic support for a proxy server var proxyUrl = process.env.http_proxy || process.env.HTTP_PROXY || process.env.npm_config_proxy if (proxyUrl) { util.log('using proxy: ' + proxyUrl,'verbose'); requestOpts.proxy = proxyUrl } return request(requestOpts).on('error',onError).on('response',function(res){onError(null,res)}); }
javascript
{ "resource": "" }
q59118
checkGlob
validation
function checkGlob(filename, globs) { // PostCSS turns relative paths into absolute paths filename = path.relative(process.cwd(), filename); return minimatchList(filename, globs); }
javascript
{ "resource": "" }
q59119
getCORSRequest
validation
function getCORSRequest() { var xhr = new root.XMLHttpRequest(); if ('withCredentials' in xhr) { xhr.withCredentials = this.withCredentials ? true : false; return xhr; } else if (!!root.XDomainRequest) { return new XDomainRequest(); } else { throw new Error('CORS is not supported by your browser'); } }
javascript
{ "resource": "" }
q59120
getReplyMethod
validation
function getReplyMethod(request) { let target = findTargetFromParentInfo(request); if (target) { return (...a) => { if ('isDestroyed' in target && target.isDestroyed()) return; target.send(...a); }; } else { d("Using reply to main process"); return (...a) => ipc.send(...a); } }
javascript
{ "resource": "" }
q59121
listenToIpc
validation
function listenToIpc(channel) { return Observable.create((subj) => { let listener = (event, ...args) => { d(`Got an event for ${channel}: ${JSON.stringify(args)}`); subj.next(args); }; d(`Setting up listener! ${channel}`); ipc.on(channel, listener); return new Subscription(() => ipc.removeListener(channel, listener)); }); }
javascript
{ "resource": "" }
q59122
getSendMethod
validation
function getSendMethod(windowOrWebView) { if (!windowOrWebView) return (...a) => ipc.send(...a); if ('webContents' in windowOrWebView) { return (...a) => { d(`webContents send: ${JSON.stringify(a)}`); if (!windowOrWebView.webContents.isDestroyed()) { windowOrWebView.webContents.send(...a); } else { throw new Error(`WebContents has been destroyed`); } }; } else { return (...a) => { d(`webView send: ${JSON.stringify(a)}`); windowOrWebView.send(...a); }; } }
javascript
{ "resource": "" }
q59123
listenerForId
validation
function listenerForId(id, timeout) { return listenToIpc(responseChannel) .do(([x]) => d(`Got IPC! ${x.id} === ${id}; ${JSON.stringify(x)}`)) .filter(([receive]) => receive.id === id && id) .take(1) .mergeMap(([receive]) => { if (receive.error) { let e = new Error(receive.error.message); e.stack = receive.error.stack; return Observable.throw(e); } return Observable.of(receive.result); }) .timeout(timeout); }
javascript
{ "resource": "" }
q59124
objectAndParentGivenPath
validation
function objectAndParentGivenPath(path) { let obj = global || window; let parent = obj; for (let part of path.split('.')) { parent = obj; obj = obj[part]; } d(`parent: ${parent}, obj: ${obj}`); if (typeof(parent) !== 'object') { throw new Error(`Couldn't access part of the object window.${path}`); } return [parent, obj]; }
javascript
{ "resource": "" }
q59125
executeMainProcessMethod
validation
function executeMainProcessMethod(moduleName, methodChain, args) { const theModule = electron[moduleName]; const path = methodChain.join('.'); return get(theModule, path).apply(theModule, args); }
javascript
{ "resource": "" }
q59126
validation
function(str, gga) { if (gga.length !== 16) { throw new Error('Invalid GGA length: ' + str); } /* 11 1 2 3 4 5 6 7 8 9 10 | 12 13 14 15 | | | | | | | | | | | | | | | $--GGA,hhmmss.ss,llll.ll,a,yyyyy.yy,a,x,xx,x.x,x.x,M,x.x,M,x.x,xxxx*hh 1) Time (UTC) 2) Latitude 3) N or S (North or South) 4) Longitude 5) E or W (East or West) 6) GPS Quality Indicator, 0 = Invalid, 1 = Valid SPS, 2 = Valid DGPS, 3 = Valid PPS 7) Number of satellites in view, 00 - 12 8) Horizontal Dilution of precision, lower is better 9) Antenna Altitude above/below mean-sea-level (geoid) 10) Units of antenna altitude, meters 11) Geoidal separation, the difference between the WGS-84 earth ellipsoid and mean-sea-level (geoid), '-' means mean-sea-level below ellipsoid 12) Units of geoidal separation, meters 13) Age of differential GPS data, time in seconds since last SC104 type 1 or 9 update, null field when DGPS is not used 14) Differential reference station ID, 0000-1023 15) Checksum */ return { 'time': parseTime(gga[1]), 'lat': parseCoord(gga[2], gga[3]), 'lon': parseCoord(gga[4], gga[5]), 'alt': parseDist(gga[9], gga[10]), 'quality': parseGGAFix(gga[6]), 'satellites': parseNumber(gga[7]), 'hdop': parseNumber(gga[8]), // dilution 'geoidal': parseDist(gga[11], gga[12]), // aboveGeoid 'age': parseNumber(gga[13]), // dgps time since update 'stationID': parseNumber(gga[14]) // dgpsReference?? }; }
javascript
{ "resource": "" }
q59127
validation
function(str, gsa) { if (gsa.length !== 19 && gsa.length !== 20) { throw new Error('Invalid GSA length: ' + str); } /* eg1. $GPGSA,A,3,,,,,,16,18,,22,24,,,3.6,2.1,2.2*3C eg2. $GPGSA,A,3,19,28,14,18,27,22,31,39,,,,,1.7,1.0,1.3*35 1 = Mode: M=Manual, forced to operate in 2D or 3D A=Automatic, 3D/2D 2 = Mode: 1=Fix not available 2=2D 3=3D 3-14 = PRNs of Satellite Vehicles (SVs) used in position fix (null for unused fields) 15 = PDOP 16 = HDOP 17 = VDOP (18) = systemID NMEA 4.10 18 = Checksum */ var sats = []; for (var i = 3; i < 15; i++) { if (gsa[i] !== '') { sats.push(parseInt(gsa[i], 10)); } } return { 'mode': parseGSAMode(gsa[1]), 'fix': parseGSAFix(gsa[2]), 'satellites': sats, 'pdop': parseNumber(gsa[15]), 'hdop': parseNumber(gsa[16]), 'vdop': parseNumber(gsa[17]), 'systemId': gsa.length > 19 ? parseNumber(gsa[18]) : null }; }
javascript
{ "resource": "" }
q59128
validation
function(str, rmc) { if (rmc.length !== 13 && rmc.length !== 14 && rmc.length !== 15) { throw new Error('Invalid RMC length: ' + str); } /* $GPRMC,hhmmss.ss,A,llll.ll,a,yyyyy.yy,a,x.x,x.x,ddmmyy,x.x,a*hh RMC = Recommended Minimum Specific GPS/TRANSIT Data 1 = UTC of position fix 2 = Data status (A-ok, V-invalid) 3 = Latitude of fix 4 = N or S 5 = Longitude of fix 6 = E or W 7 = Speed over ground in knots 8 = Track made good in degrees True 9 = UT date 10 = Magnetic variation degrees (Easterly var. subtracts from true course) 11 = E or W (12) = NMEA 2.3 introduced FAA mode indicator (A=Autonomous, D=Differential, E=Estimated, N=Data not valid) (13) = NMEA 4.10 introduced nav status 12 = Checksum */ return { 'time': parseTime(rmc[1], rmc[9]), 'status': parseRMC_GLLStatus(rmc[2]), 'lat': parseCoord(rmc[3], rmc[4]), 'lon': parseCoord(rmc[5], rmc[6]), 'speed': parseKnots(rmc[7]), 'track': parseNumber(rmc[8]), // heading 'variation': parseRMCVariation(rmc[10], rmc[11]), 'faa': rmc.length > 13 ? parseFAA(rmc[12]) : null, 'navStatus': rmc.length > 14 ? rmc[13] : null }; }
javascript
{ "resource": "" }
q59129
validation
function(str, gsv) { if (gsv.length % 4 % 3 === 0) { throw new Error('Invalid GSV length: ' + str); } /* $GPGSV,1,1,13,02,02,213,,03,-3,000,,11,00,121,,14,13,172,05*67 1 = Total number of messages of this type in this cycle 2 = Message number 3 = Total number of SVs in view repeat [ 4 = SV PRN number 5 = Elevation in degrees, 90 maximum 6 = Azimuth, degrees from true north, 000 to 359 7 = SNR (signal to noise ratio), 00-99 dB (null when not tracking, higher is better) ] N+1 = signalID NMEA 4.10 N+2 = Checksum */ var sats = []; for (var i = 4; i < gsv.length - 3; i += 4) { var prn = parseNumber(gsv[i]); var snr = parseNumber(gsv[i + 3]); /* Plot satellites in Radar chart with north on top by linear map elevation from 0° to 90° into r to 0 centerX + cos(azimuth - 90) * (1 - elevation / 90) * radius centerY + sin(azimuth - 90) * (1 - elevation / 90) * radius */ sats.push({ 'prn': prn, 'elevation': parseNumber(gsv[i + 1]), 'azimuth': parseNumber(gsv[i + 2]), 'snr': snr, 'status': prn !== null ? (snr !== null ? 'tracking' : 'in view') : null }); } return { 'msgNumber': parseNumber(gsv[2]), 'msgsTotal': parseNumber(gsv[1]), //'satsInView' : parseNumber(gsv[3]), // Can be obtained by satellites.length 'satellites': sats, 'signalId': gsv.length % 4 === 2 ? parseNumber(gsv[gsv.length - 2]) : null // NMEA 4.10 addition }; }
javascript
{ "resource": "" }
q59130
computeIndexChunks
validation
function computeIndexChunks(buffer) { var BLOCK_SIZE = 65536; var view = new jDataView(buffer, 0, buffer.byteLength, true /* little endian */); var minBlockIndex = Infinity; var contigStartOffsets = []; view.getInt32(); // magic var n_ref = view.getInt32(); for (var j = 0; j < n_ref; j++) { contigStartOffsets.push(view.tell()); var n_bin = view.getInt32(); for (var i = 0; i < n_bin; i++) { view.getUint32(); // bin ID var n_chunk = view.getInt32(); view.skip(n_chunk * 16); } var n_intv = view.getInt32(); if (n_intv) { var offset = VirtualOffset.fromBlob(view.getBytes(8), 0), coffset = offset.coffset + (offset.uoffset ? BLOCK_SIZE : 0); minBlockIndex = coffset ? Math.min(coffset, minBlockIndex) : BLOCK_SIZE; view.skip((n_intv - 1) * 8); } } contigStartOffsets.push(view.tell()); // At this point, `minBlockIndex` should be non-Infinity (see #405 & #406) return { chunks: _.zip(_.initial(contigStartOffsets), _.rest(contigStartOffsets)), minBlockIndex }; }
javascript
{ "resource": "" }
q59131
validation
function (el) { var genericCloseButton; if ($(el).data('popupoptions').closebuttonmarkup) { genericCloseButton = $(options.closebuttonmarkup).addClass(el.id + '_close'); } else { genericCloseButton = '<button class="popup_close ' + el.id + '_close" title="Close" aria-label="Close"><span aria-hidden="true">×</span></button>'; } if ($(el).data('popup-initialized')){ $(el).append(genericCloseButton); } }
javascript
{ "resource": "" }
q59132
validation
function (el, ordinal, func) { var options = $(el).data('popupoptions'); var openelement; var elementclicked; if (typeof options === 'undefined') return; openelement = options.openelement ? options.openelement : ('.' + el.id + opensuffix); elementclicked = $(openelement + '[data-popup-ordinal="' + ordinal + '"]'); if (typeof func == 'function') { func.call($(el), el, elementclicked); } }
javascript
{ "resource": "" }
q59133
validation
function (el) { var bounding = el.getBoundingClientRect(); return ( bounding.top >= 0 && bounding.left >= 0 && bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) && bounding.right <= (window.innerWidth || document.documentElement.clientWidth) ); }
javascript
{ "resource": "" }
q59134
main
validation
function main() { var app = new App(); function intentHandler(url) { Auth0Cordova.onRedirectUri(url); } window.handleOpenURL = intentHandler; app.run('#app'); }
javascript
{ "resource": "" }
q59135
WebView
validation
function WebView() { this.tab = null; this.handler = null; this.open = this.open.bind(this); this.handleFirstLoadEnd = this.handleFirstLoadEnd.bind(this); this.handleLoadError = this.handleLoadError.bind(this); this.handleExit = this.handleExit.bind(this); this.clearEvents = this.clearEvents.bind(this); this.close = this.close.bind(this); }
javascript
{ "resource": "" }
q59136
processProps
validation
function processProps(props) { const { title, label, key, value } = props; const cloneProps = { ...props }; // Warning user not to use deprecated label prop. if (label && !title) { if (!warnDeprecatedLabel) { warning(false, "'label' in treeData is deprecated. Please use 'title' instead."); warnDeprecatedLabel = true; } cloneProps.title = label; } if (!key) { cloneProps.key = value; } return cloneProps; }
javascript
{ "resource": "" }
q59137
writeHeaders
validation
function writeHeaders(file, headers, only = null) { for (let name in headers) { let value = headers[name]; if (only && !match(name, only)) continue; if (Array.isArray(value)) for (let item of value) file.write(`${name}: ${item}\n`); else file.write(`${name}: ${value}\n`); } }
javascript
{ "resource": "" }
q59138
match
validation
function match(name, regexps){ for (let regexp of regexps) if (regexp.test(name)) return true; return false; }
javascript
{ "resource": "" }
q59139
showHelpAndDie
validation
function showHelpAndDie(message) { if (message) { console.error(message); } console.error(commander.helpInformation()); process.exit(1); }
javascript
{ "resource": "" }
q59140
robohydraHeadType
validation
function robohydraHeadType(settings) { var parentClass = settings.parentClass || RoboHydraHead; var newConstructorFunction = function(props) { if (!props && settings.defaultProps) { deprecationWarning("deprecated 'defaultProps', please use 'defaultPropertyObject' instead"); props = settings.defaultProps; } props = props || settings.defaultPropertyObject || {}; // Checks mandatory and optional properties this._importProperties(newConstructorFunction, props); var parentPropBuilder = settings.parentPropertyBuilder || function() { return {}; }; if (settings.parentPropBuilder) { deprecationWarning("deprecated 'parentPropBuilder', please use 'parentPropertyBuilder' instead"); parentPropBuilder = settings.parentPropBuilder; } var parentProps = parentPropBuilder.call(this); IMPLICIT_OPTIONAL_PROPS.forEach(function(p) { var propName = typeof p === 'object' ? p.name : p; if (! (propName in parentProps)) { parentProps[propName] = this[propName]; } }, this); parentClass.call(this, parentProps); this.type = settings.name || '<undefined>'; if (typeof settings.init === 'function') { settings.init.call(this); } }; newConstructorFunction.mandatoryProperties = settings.mandatoryProperties || []; newConstructorFunction.optionalProperties = (settings.optionalProperties || []).concat(IMPLICIT_OPTIONAL_PROPS); newConstructorFunction.prototype = new parentClass(); return newConstructorFunction; }
javascript
{ "resource": "" }
q59141
proxyRequest
validation
function proxyRequest(req, res, proxyTo, opts) { opts = opts || {}; var httpRequestFunction = opts.httpRequestFunction || http.request; var httpsRequestFunction = opts.httpsRequestFunction || https.request; var setHostHeader = opts.setHostHeader; var proxyUrl = proxyTo; if (typeof(proxyTo) === 'string') { proxyUrl = url.parse(proxyTo, true); } var proxyToHost = proxyUrl.hostname; var proxyToPort = proxyUrl.port || (proxyUrl.protocol === 'https:' ? 443 : 80); var proxyToPath = proxyUrl.pathname + (proxyUrl.search === null ? "" : proxyUrl.search); var requestFunction = (proxyUrl.protocol === 'https:') ? httpsRequestFunction : httpRequestFunction; var headers = {}; for (var h in req.headers) { headers[h] = req.headers[h]; } if (setHostHeader) { headers.host = proxyToHost + (proxyUrl.port ? ":" + proxyUrl.port : ""); } var proxyReq = requestFunction( {host: proxyToHost, port: proxyToPort, method: req.method, path: proxyToPath, headers: headers}, function (proxyRes) { // Copy over headers and status code from proxied request res.statusCode = proxyRes.statusCode; res.headers = proxyRes.headers; proxyRes.on("data", function (chunk) { res.write(chunk); }); proxyRes.on("end", function () { res.end(); }); }); proxyReq.on('error', function (err) { res.statusCode = 502; res.send('Bad Gateway! Could not proxy request. Invalid host or proxy destination down? Reported error was: ' + err); }); if (req.rawBody) { proxyReq.write(req.rawBody); } proxyReq.end(); }
javascript
{ "resource": "" }
q59142
BigIq50LicenseProvider
validation
function BigIq50LicenseProvider(bigIp, options) { const injectedLogger = options ? options.logger : undefined; let loggerOptions = options ? options.loggerOptions : undefined; if (injectedLogger) { this.logger = injectedLogger; util.setLogger(injectedLogger); } else { loggerOptions = loggerOptions || { logLevel: 'none' }; loggerOptions.module = module; this.logger = Logger.getLogger(loggerOptions); util.setLoggerOptions(loggerOptions); } logger = this.logger; this.bigIp = bigIp; }
javascript
{ "resource": "" }
q59143
listPrivateKey
validation
function listPrivateKey(keyType, folder, name, noRetry) { let privateKeyName; // Try with .key suffix first. If unsuccessful, retry without the .key suffix if (noRetry) { // If present, remove '.key' suffix privateKeyName = name.replace(REG_EXPS.KEY_SUFFIX, ''); } else { // Append '.key' suffix, if not present privateKeyName = (name.match(REG_EXPS.KEY_SUFFIX)) ? name : `${name}.key`; } return util.runTmshCommand(`list sys ${keyType} /${folder}/${privateKeyName}`) .then((keyData) => { // If no result, retry if a retry hasn't occurred yet. if (!keyData) { if (!noRetry) { return listPrivateKey(keyType, folder, name, true); } return q(); } return q({ privateKeyName, keyData }); }) .catch((err) => { // If the object is not found (code: 01020036:3), retry if a retry hasn't occurred yet. const notFoundRegex = /01020036:3/; if (err.message.match(notFoundRegex) && !noRetry) { return listPrivateKey(keyType, folder, name, true); } return q.reject(err); }); }
javascript
{ "resource": "" }
q59144
createTrafficGroup
validation
function createTrafficGroup(bigIp, trafficGroup) { let createGroup = true; bigIp.list('/tm/cm/traffic-group') .then((response) => { response.forEach((group) => { if (group.name === trafficGroup) { createGroup = false; } }); if (createGroup) { return bigIp.create( '/tm/cm/traffic-group', { name: trafficGroup, partition: '/Common' } ); } return q(); }) .catch((err) => { return q.reject(err); }); }
javascript
{ "resource": "" }
q59145
becomeMaster
validation
function becomeMaster(provider, bigIp, options) { let hasUcs = false; logger.info('Becoming master.'); logger.info('Checking for backup UCS.'); return provider.getStoredUcs() .then((response) => { if (response) { hasUcs = true; return loadUcs(provider, bigIp, response, options.cloud); } return q(); }) .then(() => { // If we loaded UCS, re-initialize encryption so our keys // match each other if (hasUcs) { return initEncryption.call(this, provider, bigIp); } return q(); }) .then(() => { return bigIp.list('/tm/sys/global-settings'); }) .then((globalSettings) => { const hostname = globalSettings ? globalSettings.hostname : undefined; if (hostname) { this.instance.hostname = hostname; } else { logger.debug('hostname not found in this.instance or globalSettings'); } return bigIp.list('/tm/sys/provision'); }) .then((response) => { const modulesProvisioned = {}; if (response && response.length > 0) { response.forEach((module) => { modulesProvisioned[module.name] = !(module.level === 'none'); }); } // Make sure device group exists logger.info('Creating device group.'); const deviceGroupOptions = { autoSync: options.autoSync, saveOnAutoSync: options.saveOnAutoSync, fullLoadOnSync: options.fullLoadOnSync, asmSync: modulesProvisioned.asm || options.asmSync, networkFailover: options.networkFailover }; return bigIp.cluster.createDeviceGroup( options.deviceGroup, 'sync-failover', [this.instance.hostname], deviceGroupOptions ); }) .then(() => { logger.info('Writing master file.'); return writeMasterFile(hasUcs); }); }
javascript
{ "resource": "" }
q59146
getAutoscaleProcessCount
validation
function getAutoscaleProcessCount() { const actions = 'cluster-action update|-c update|cluster-action join|-c join'; const grepCommand = `grep autoscale.js | grep -E '${actions}' | grep -v 'grep autoscale.js'`; return util.getProcessCount(grepCommand) .then((response) => { return q(response); }) .catch((err) => { logger.error('Could not determine if another autoscale script is running'); return q.reject(err); }); }
javascript
{ "resource": "" }
q59147
initEncryption
validation
function initEncryption(provider, bigIp) { const PRIVATE_KEY_OUT_FILE = '/tmp/tempPrivateKey.pem'; let passphrase; if (provider.hasFeature(CloudProvider.FEATURE_ENCRYPTION)) { logger.debug('Generating public/private keys for autoscaling.'); return cryptoUtil.generateRandomBytes(PASSPHRASE_LENGTH, 'base64') .then((response) => { passphrase = response; return cryptoUtil.generateKeyPair( PRIVATE_KEY_OUT_FILE, { passphrase, keyLength: '3072' } ); }) .then((publicKey) => { return provider.putPublicKey(this.instanceId, publicKey); }) .then(() => { return bigIp.installPrivateKey( PRIVATE_KEY_OUT_FILE, AUTOSCALE_PRIVATE_KEY_FOLDER, AUTOSCALE_PRIVATE_KEY, { passphrase } ); }) .then(() => { return bigIp.save(); }) .catch((err) => { logger.info('initEncryption error', err && err.message ? err.message : err); return q.reject(err); }); } return q(); }
javascript
{ "resource": "" }
q59148
getMasterInstance
validation
function getMasterInstance(instances) { let instanceId; const instanceIds = Object.keys(instances); for (let i = 0; i < instanceIds.length; i++) { instanceId = instanceIds[i]; if (instances[instanceId].isMaster) { return { id: instanceId, instance: instances[instanceId] }; } } return null; }
javascript
{ "resource": "" }
q59149
markVersions
validation
function markVersions(instances) { let highestVersion = '0.0.0'; let instance; Object.keys(instances).forEach((instanceId) => { instance = instances[instanceId]; if (instance.version && util.versionCompare(instance.version, highestVersion) > 0) { highestVersion = instance.version; } }); Object.keys(instances).forEach((instanceId) => { instance = instances[instanceId]; if (!instance.version || util.versionCompare(instance.version, highestVersion) === 0) { instance.versionOk = true; } else { instance.versionOk = false; } }); }
javascript
{ "resource": "" }
q59150
isMasterExternalValueOk
validation
function isMasterExternalValueOk(masterId, instances) { const instanceIds = Object.keys(instances); let instance; let hasExternal; for (let i = 0; i < instanceIds.length; i++) { instance = instances[instanceIds[i]]; if (instance.external) { hasExternal = true; break; } } if (hasExternal) { return !!instances[masterId].external; } return true; }
javascript
{ "resource": "" }
q59151
getDataFromPropPath
validation
function getDataFromPropPath(pathArray, obj) { if (pathArray.length === 0) { return undefined; } return pathArray.reduce((result, prop) => { if (typeof result !== 'object' || result === null) { return {}; } if (prop === '') { return result; } return result[prop]; }, obj); }
javascript
{ "resource": "" }
q59152
checkTask
validation
function checkTask(taskPath, taskIdToCheck, options) { const func = function () { const deferred = q.defer(); this.list(`${taskPath}/${taskIdToCheck}`, undefined, util.NO_RETRY) .then((response) => { const statusAttribute = (options && options.statusAttribute) ? options.statusAttribute : '_taskState'; const taskState = response[statusAttribute]; if (taskState === 'VALIDATING' || taskState === 'STARTED') { // this is a normal state, just not done yet - keep waiting deferred.reject(); } else if (taskState === 'COMPLETED' || taskState === 'FINISHED') { deferred.resolve({ success: true, response }); } else if (taskState === 'FAILED') { deferred.resolve({ success: false, response }); } else { deferred.reject(new Error(`checkTask: unexpected command status: ${taskState}`)); } }) .catch(() => { // if this throws, assume it is because restjavad has been restarted // and we are done for now deferred.resolve({ success: true }); }); return deferred.promise; }; return util.tryUntil(this, util.DEFAULT_RETRY, func); }
javascript
{ "resource": "" }
q59153
BigIq54LicenseProvider
validation
function BigIq54LicenseProvider(bigIp, options) { const injectedLogger = options ? options.logger : undefined; let loggerOptions = options ? options.loggerOptions : undefined; this.constructorOptions = {}; if (options) { Object.keys(options).forEach((option) => { this.constructorOptions[option] = options[option]; }); } if (injectedLogger) { this.logger = injectedLogger; util.setLogger(injectedLogger); } else { loggerOptions = loggerOptions || { logLevel: 'none' }; loggerOptions.module = module; this.logger = Logger.getLogger(loggerOptions); util.setLoggerOptions(loggerOptions); } this.bigIp = bigIp; }
javascript
{ "resource": "" }
q59154
encrypt
validation
function encrypt(publicKeyDataOrFile, data) { const deferred = q.defer(); let publicKeyPromise; const getPublicKey = function getPublicKey(publicKeyFile) { const publicKeyDeferred = q.defer(); fs.readFile(publicKeyFile, (err, publicKey) => { if (err) { logger.warn('Error reading public key:', err); publicKeyDeferred.reject(err); } else { publicKeyDeferred.resolve(publicKey); } }); return publicKeyDeferred.promise; }; if (typeof data !== 'string') { deferred.reject(new Error('data must be a string')); return deferred.promise; } if (publicKeyDataOrFile.startsWith('-----BEGIN PUBLIC KEY-----')) { publicKeyPromise = q(publicKeyDataOrFile); } else { publicKeyPromise = getPublicKey(publicKeyDataOrFile); } publicKeyPromise .then((publicKey) => { let encrypted; try { encrypted = crypto.publicEncrypt(publicKey, util.createBufferFrom(data)); deferred.resolve(encrypted.toString('base64')); } catch (err) { logger.warn('Error encrypting data:', err); deferred.reject(err); } }) .catch((err) => { logger.warn('Unable to get public key:', err); deferred.reject(err); }); return deferred.promise; }
javascript
{ "resource": "" }
q59155
getLabel
validation
function getLabel(logLevel, moduleLogging, verboseLabel) { let parts; let label = ''; if (moduleLogging) { if (logLevel === 'debug' || logLevel === 'silly' || verboseLabel) { parts = moduleLogging.filename.split('/'); label = `${parts[parts.length - 2]}/${parts.pop()}`; } } return label; }
javascript
{ "resource": "" }
q59156
getLicenseProvider
validation
function getLicenseProvider(poolName, options) { const methodOptions = {}; Object.assign(methodOptions, options); const factoryOptions = {}; Object.assign(factoryOptions, this.constructorOptions); let licenseProvider; if (methodOptions.autoApiType) { return getApiType.call(this, poolName, methodOptions) .then((apiType) => { // Even though the main API by type is the same across BIG-IQ versions, // there are some subtle differences the implementations need to know // about factoryOptions.version = this.version; try { licenseProvider = bigIqLicenseProviderFactory.getLicenseProviderByType( apiType, this.bigIp, factoryOptions ); return q(licenseProvider); } catch (err) { this.logger.info( 'Error getting license provider by type', err && err.message ? err.message : err ); return q.reject(err); } }) .catch((err) => { this.logger.info('Error getting api type', err && err.message ? err.message : err); return q.reject(err); }); } try { licenseProvider = bigIqLicenseProviderFactory.getLicenseProviderByVersion( this.version, this.bigIp, factoryOptions ); return q(licenseProvider); } catch (err) { this.logger.info( 'Error getting license provider by type', err && err.message ? err.message : err ); return q.reject(err); } }
javascript
{ "resource": "" }
q59157
forceResetUserPassword
validation
function forceResetUserPassword(user) { const deferred = q.defer(); cryptoUtil.generateRandomBytes(24, 'hex') .then((randomBytes) => { util.runShellCommand(`echo -e "${randomBytes}\n${randomBytes}" | passwd ${user}`); deferred.resolve(randomBytes); }) .catch((err) => { deferred.reject(err); }); return deferred.promise; }
javascript
{ "resource": "" }
q59158
jscoverage_endLengthyOperation
validation
function jscoverage_endLengthyOperation() { var progressBar = document.getElementById('progressBar'); ProgressBar.setPercentage(progressBar, 100); setTimeout(function() { jscoverage_inLengthyOperation = false; progressBar.style.visibility = 'hidden'; var progressLabel = document.getElementById('progressLabel'); progressLabel.style.visibility = 'hidden'; progressLabel.innerHTML = ''; var tabs = document.getElementById('tabs').getElementsByTagName('div'); var i; for (i = 0; i < tabs.length; i++) { tabs.item(i).style.cursor = ''; } }, 50); }
javascript
{ "resource": "" }
q59159
jscoverage_initTabContents
validation
function jscoverage_initTabContents(queryString) { var showMissingColumn = false; var url = null; var windowURL = null; var parameters, parameter, i, index, name, value; if (queryString.length > 0) { // chop off the question mark queryString = queryString.substring(1); parameters = queryString.split(/&|;/); for (i = 0; i < parameters.length; i++) { parameter = parameters[i]; index = parameter.indexOf('='); if (index === -1) { // still works with old syntax url = decodeURIComponent(parameter); } else { name = parameter.substr(0, index); value = decodeURIComponent(parameter.substr(index + 1)); if (name === 'missing' || name === 'm') { showMissingColumn = jscoverage_getBooleanValue(value); } else if (name === 'url' || name === 'u' || name === 'frame' || name === 'f') { url = value; } else if (name === 'window' || name === 'w') { windowURL = value; } } } } var checkbox = document.getElementById('checkbox'); checkbox.checked = showMissingColumn; if (showMissingColumn) { jscoverage_appendMissingColumn(); } var isValidURL = function (url) { var result = jscoverage_isValidURL(url); if (! result) { alert('Invalid URL: ' + url); } return result; }; if (url !== null && isValidURL(url)) { // this will automatically propagate to the input field frames[0].location = url; } else if (windowURL !== null && isValidURL(windowURL)) { window.open(windowURL); } // if the browser tab is absent, we have to initialize the summary tab if (! document.getElementById('browserTab')) { jscoverage_recalculateSummaryTab(); } }
javascript
{ "resource": "" }
q59160
jscoverage_recalculateSourceTab
validation
function jscoverage_recalculateSourceTab() { if (! jscoverage_currentFile) { jscoverage_endLengthyOperation(); return; } var progressLabel = document.getElementById('progressLabel'); progressLabel.innerHTML = 'Calculating coverage ...'; var progressBar = document.getElementById('progressBar'); ProgressBar.setPercentage(progressBar, 20); setTimeout(jscoverage_makeTable, 0); }
javascript
{ "resource": "" }
q59161
jscoverage_selectTab
validation
function jscoverage_selectTab(tab) { if (typeof tab !== 'number') { tab = jscoverage_tabIndexOf(tab); } var tabs = document.getElementById('tabs'); var tabPages = document.getElementById('tabPages'); var nodeList; var tabNum; var i; var node; nodeList = tabs.childNodes; tabNum = 0; for (i = 0; i < nodeList.length; i++) { node = nodeList.item(i); if (node.nodeType !== 1) { continue; } if (node.className !== 'disabled') { if (tabNum === tab) { node.className = 'selected'; } else { node.className = ''; } } tabNum++; } nodeList = tabPages.childNodes; tabNum = 0; for (i = 0; i < nodeList.length; i++) { node = nodeList.item(i); if (node.nodeType !== 1) { continue; } if (tabNum === tab) { node.className = 'selected TabPage'; } else { node.className = 'TabPage'; } tabNum++; } }
javascript
{ "resource": "" }
q59162
compareAscending
validation
function compareAscending(a, b) { var ac = a.criteria, bc = b.criteria; // ensure a stable sort in V8 and other engines // http://code.google.com/p/v8/issues/detail?id=90 if (ac !== bc) { if (ac > bc || typeof ac == 'undefined') { return 1; } if (ac < bc || typeof bc == 'undefined') { return -1; } } // The JS engine embedded in Adobe applications like InDesign has a buggy // `Array#sort` implementation that causes it, under certain circumstances, // to return the same value for `a` and `b`. // See https://github.com/jashkenas/underscore/pull/1247 return a.index - b.index; }
javascript
{ "resource": "" }
q59163
baseFlatten
validation
function baseFlatten(array, isShallow, isArgArrays, fromIndex) { var index = (fromIndex || 0) - 1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value && typeof value == 'object' && typeof value.length == 'number' && (isArray(value) || isArguments(value))) { // recursively flatten arrays (susceptible to call stack limits) if (!isShallow) { value = baseFlatten(value, isShallow, isArgArrays); } var valIndex = -1, valLength = value.length, resIndex = result.length; result.length += valLength; while (++valIndex < valLength) { result[resIndex++] = value[valIndex]; } } else if (!isArgArrays) { result.push(value); } } return result; }
javascript
{ "resource": "" }
q59164
pluck
validation
function pluck(collection, property) { var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { var result = Array(length); while (++index < length) { result[index] = collection[index][property]; } } return result || map(collection, property); }
javascript
{ "resource": "" }
q59165
reduceRight
validation
function reduceRight(collection, callback, accumulator, thisArg) { var noaccum = arguments.length < 3; callback = baseCreateCallback(callback, thisArg, 4); forEachRight(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection); }); return accumulator; }
javascript
{ "resource": "" }
q59166
sample
validation
function sample(collection, n, guard) { var length = collection ? collection.length : 0; if (typeof length != 'number') { collection = values(collection); } if (n == null || guard) { return collection ? collection[random(length - 1)] : undefined; } var result = shuffle(collection); result.length = nativeMin(nativeMax(0, n), result.length); return result; }
javascript
{ "resource": "" }
q59167
bind
validation
function bind(func, thisArg) { return arguments.length > 2 ? createBound(func, 17, nativeSlice.call(arguments, 2), null, thisArg) : createBound(func, 1, null, null, thisArg); }
javascript
{ "resource": "" }
q59168
bindAll
validation
function bindAll(object) { var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), index = -1, length = funcs.length; while (++index < length) { var key = funcs[index]; object[key] = createBound(object[key], 1, null, null, object); } return object; }
javascript
{ "resource": "" }
q59169
curry
validation
function curry(func, arity) { arity = typeof arity == 'number' ? arity : (+arity || func.length); return createBound(func, 4, null, null, null, arity); }
javascript
{ "resource": "" }
q59170
wrap
validation
function wrap(value, wrapper) { if (!isFunction(wrapper)) { throw new TypeError; } return function() { var args = [value]; push.apply(args, arguments); return wrapper.apply(this, args); }; }
javascript
{ "resource": "" }
q59171
mixin
validation
function mixin(object, source) { var ctor = object, isFunc = !source || isFunction(ctor); if (!source) { ctor = lodashWrapper; source = object; object = lodash; } forEach(functions(source), function(methodName) { var func = object[methodName] = source[methodName]; if (isFunc) { ctor.prototype[methodName] = function() { var value = this.__wrapped__, args = [value]; push.apply(args, arguments); var result = func.apply(object, args); if (value && typeof value == 'object' && value === result) { return this; } result = new ctor(result); result.__chain__ = this.__chain__; return result; }; } }); }
javascript
{ "resource": "" }
q59172
validation
function() { var target = arguments[0]; for (var i = 1, l = arguments.length; i < l; i++) { var extension = arguments[i]; // Only functions and objects can be mixined. if ((Object(extension) !== extension) && !_.isFunction(extension) && (extension === null || extension === undefined)) { continue; } _.each(extension, function(copy, key) { if (this.mixin.deep && (Object(copy) === copy)) { if (!target[key]) { target[key] = _.isArray(copy) ? [] : {}; } this.mixin(target[key], copy); return; } if (target[key] !== copy) { if (!this.mixin.supplement || !target.hasOwnProperty(key)) { target[key] = copy; } } }, this); } return target; }
javascript
{ "resource": "" }
q59173
validation
function(args) { return _.template('<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>', { dx: args.dx || 0, dy: args.dy || 0, color: args.color || 'black', blur: _.isFinite(args.blur) ? args.blur : 4 }); }
javascript
{ "resource": "" }
q59174
validation
function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>', { a: 0.2126 + 0.7874 * (1 - amount), b: 0.7152 - 0.7152 * (1 - amount), c: 0.0722 - 0.0722 * (1 - amount), d: 0.2126 - 0.2126 * (1 - amount), e: 0.7152 + 0.2848 * (1 - amount), f: 0.0722 - 0.0722 * (1 - amount), g: 0.2126 - 0.2126 * (1 - amount), h: 0.0722 + 0.9278 * (1 - amount) }); }
javascript
{ "resource": "" }
q59175
validation
function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>', { amount: 1 - amount }); }
javascript
{ "resource": "" }
q59176
validation
function(sx, sy) { sy = (typeof sy === 'undefined') ? sx : sy; var transformAttr = this.attr('transform') || '', transform = parseTransformString(transformAttr); // Is it a getter? if (typeof sx === 'undefined') { return transform.scale; } transformAttr = transformAttr.replace(/scale\([^\)]*\)/g, '').trim(); this.attr('transform', transformAttr + ' scale(' + sx + ',' + sy + ')'); return this; }
javascript
{ "resource": "" }
q59177
validation
function(withoutTransformations, target) { // If the element is not in the live DOM, it does not have a bounding box defined and // so fall back to 'zero' dimension element. if (!this.node.ownerSVGElement) return { x: 0, y: 0, width: 0, height: 0 }; var box; try { box = this.node.getBBox(); // Opera returns infinite values in some cases. // Note that Infinity | 0 produces 0 as opposed to Infinity || 0. // We also have to create new object as the standard says that you can't // modify the attributes of a bbox. box = { x: box.x | 0, y: box.y | 0, width: box.width | 0, height: box.height | 0}; } catch (e) { // Fallback for IE. box = { x: this.node.clientLeft, y: this.node.clientTop, width: this.node.clientWidth, height: this.node.clientHeight }; } if (withoutTransformations) { return box; } var matrix = this.node.getTransformToElement(target || this.node.ownerSVGElement); var corners = []; var point = this.node.ownerSVGElement.createSVGPoint(); point.x = box.x; point.y = box.y; corners.push(point.matrixTransform(matrix)); point.x = box.x + box.width; point.y = box.y; corners.push(point.matrixTransform(matrix)); point.x = box.x + box.width; point.y = box.y + box.height; corners.push(point.matrixTransform(matrix)); point.x = box.x; point.y = box.y + box.height; corners.push(point.matrixTransform(matrix)); var minX = corners[0].x; var maxX = minX; var minY = corners[0].y; var maxY = minY; for (var i = 1, len = corners.length; i < len; i++) { var x = corners[i].x; var y = corners[i].y; if (x < minX) { minX = x; } else if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } else if (y > maxY) { maxY = y; } } return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; }
javascript
{ "resource": "" }
q59178
validation
function(x, y) { var svg = this.svg().node; var p = svg.createSVGPoint(); p.x = x; p.y = y; try { var globalPoint = p.matrixTransform(svg.getScreenCTM().inverse()); var globalToLocalMatrix = this.node.getTransformToElement(svg).inverse(); } catch(e) { // IE9 throws an exception in odd cases. (`Unexpected call to method or property access`) // We have to make do with the original coordianates. return p; } return globalPoint.matrixTransform(globalToLocalMatrix); }
javascript
{ "resource": "" }
q59179
validation
function(o) { o = (o && point(o)) || 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(point(x,y))); return this; }
javascript
{ "resource": "" }
q59180
validation
function(o, angle) { angle = (angle + 360) % 360; this.toPolar(o); this.y += toRad(angle); var p = point.fromPolar(this.x, this.y, o); this.x = p.x; this.y = p.y; return this; }
javascript
{ "resource": "" }
q59181
validation
function(ref, distance) { var theta = toRad(point(ref).theta(this)); return this.offset(cos(theta) * distance, -sin(theta) * distance); }
javascript
{ "resource": "" }
q59182
validation
function(p, angle) { p = point(p); var center = 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 = [ line(this.origin(), this.topRight()), line(this.topRight(), this.corner()), line(this.corner(), this.bottomLeft()), line(this.bottomLeft(), this.origin()) ]; var connector = 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": "" }
q59183
validation
function(r) { this.x += r.x; this.y += r.y; this.width += r.width; this.height += r.height; return this; }
javascript
{ "resource": "" }
q59184
validation
function(p, angle) { p = point(p); if (angle) p.rotate(point(this.x, this.y), angle); var dx = p.x - this.x; var dy = p.y - this.y; var result; if (dx === 0) { result = this.bbox().pointNearestToPoint(p); if (angle) return result.rotate(point(this.x, this.y), -angle); return result; } var m = dy / dx; var mSquared = m * m; var aSquared = this.a * this.a; var bSquared = this.b * this.b; var x = sqrt(1 / ((1 / aSquared) + (mSquared / bSquared))); x = dx < 0 ? -x : x; var y = m * x; result = point(this.x + x, this.y + y); if (angle) return result.rotate(point(this.x, this.y), -angle); return result; }
javascript
{ "resource": "" }
q59185
validation
function(knots) { 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] = point((2 * knots[0].x + knots[1].x) / 3, (2 * knots[0].y + knots[1].y) / 3); // P2 = 2P1 – P0 secondControlPoints[0] = 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(point(x[i], y[i])); // Second control point. if (i < n - 1) { secondControlPoints.push(point(2 * knots [i + 1].x - x[i + 1], 2 * knots[i + 1].y - y[i + 1])); } else { secondControlPoints.push(point((knots[n].x + x[n - 1]) / 2, (knots[n].y + y[n - 1]) / 2)); } } return [firstControlPoints, secondControlPoints]; }
javascript
{ "resource": "" }
q59186
validation
function(model, opt) { opt = opt || {}; if (_.isUndefined(opt.inbound) && _.isUndefined(opt.outbound)) { opt.inbound = opt.outbound = true; } var links = []; this.each(function(cell) { var source = cell.get('source'); var target = cell.get('target'); if (source && source.id === model.id && opt.outbound) { links.push(cell); } if (target && target.id === model.id && opt.inbound) { links.push(cell); } }); return links; }
javascript
{ "resource": "" }
q59187
validation
function(model) { _.each(this.getConnectedLinks(model), function(link) { link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0)); }); }
javascript
{ "resource": "" }
q59188
validation
function(attrs, value, opt) { var currentAttrs = this.get('attrs'); var delim = '/'; if (_.isString(attrs)) { // Get/set an attribute by a special path syntax that delimits // nested objects by the colon character. if (value) { var attr = {}; joint.util.setByPath(attr, attrs, value, delim); return this.set('attrs', _.merge({}, currentAttrs, attr), opt); } else { return joint.util.getByPath(currentAttrs, attrs, delim); } } return this.set('attrs', _.merge({}, currentAttrs, attrs), value); }
javascript
{ "resource": "" }
q59189
validation
function(el) { var $el = this.$(el); if ($el.length === 0 || $el[0] === this.el) { // 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`. var attrs = this.model.get('attrs') || {}; if (attrs['.'] && attrs['.']['magnet'] === false) { return undefined; } return this.el; } if ($el.attr('magnet')) { return $el[0]; } return this.findMagnet($el.parent()); }
javascript
{ "resource": "" }
q59190
validation
function(el, selector) { if (el === this.el) { return selector; } var index = $(el).index(); selector = el.tagName + ':nth-child(' + (index + 1) + ')' + ' ' + (selector || ''); return this.getSelector($(el).parent()[0], selector + ' '); }
javascript
{ "resource": "" }
q59191
validation
function() { var markup = this.model.markup || this.model.get('markup'); if (markup) { var nodes = V(markup); V(this.el).append(nodes); } else { throw new Error('properties.markup is missing while the default render() implementation is used.'); } this.update(); this.resize(); this.rotate(); this.translate(); return this; }
javascript
{ "resource": "" }
q59192
validation
function(idx, value) { idx = idx || 0; var labels = this.get('labels') || []; // Is it a getter? if (arguments.length === 0 || arguments.length === 1) { return labels[idx]; } var newValue = _.merge({}, labels[idx], value); var newLabels = labels.slice(); newLabels[idx] = newValue; return this.set({ labels: newLabels }); }
javascript
{ "resource": "" }
q59193
validation
function(endType) { function watchEnd(link, end) { end = end || {}; var previousEnd = link.previous(endType) || {}; // Pick updateMethod this._sourceBboxUpdate or this._targetBboxUpdate. var updateEndFunction = this['_' + endType + 'BBoxUpdate']; if (this._isModel(previousEnd)) { this.stopListening(this.paper.getModelById(previousEnd.id), 'change', updateEndFunction); } if (this._isModel(end)) { // If the observed model changes, it caches a new bbox and do the link update. this.listenTo(this.paper.getModelById(end.id), 'change', updateEndFunction); } _.bind(updateEndFunction, this)({ cacheOnly: true }); return this; } return watchEnd; }
javascript
{ "resource": "" }
q59194
validation
function(vertex) { this.model.set('attrs', this.model.get('attrs') || {}); var attrs = this.model.get('attrs'); // As it is very hard to find a correct index of the newly created vertex, // a little heuristics is taking place here. // The heuristics checks if length of the newly created // path is lot more than length of the old path. If this is the case, // new vertex was probably put into a wrong index. // Try to put it into another index and repeat the heuristics again. var vertices = (this.model.get('vertices') || []).slice(); // Store the original vertices for a later revert if needed. var originalVertices = vertices.slice(); // A `<path>` element used to compute the length of the path during heuristics. var path = this._V.connection.node.cloneNode(false); // Length of the original path. var originalPathLength = path.getTotalLength(); // Current path length. var pathLength; // Tolerance determines the highest possible difference between the length // of the old and new path. The number has been chosen heuristically. var pathLengthTolerance = 20; // Total number of vertices including source and target points. var idx = vertices.length + 1; // Loop through all possible indexes and check if the difference between // path lengths changes significantly. If not, the found index is // most probably the right one. while (idx--) { vertices.splice(idx, 0, vertex); V(path).attr('d', this.getPathData(vertices)); pathLength = path.getTotalLength(); // Check if the path lengths changed significantly. if (pathLength - originalPathLength > pathLengthTolerance) { // Revert vertices to the original array. The path length has changed too much // so that the index was not found yet. vertices = originalVertices.slice(); } else { break; } } this.model.set('vertices', vertices); // In manhattan routing, if there are no vertices, the path length changes significantly // with the first vertex added. Shall we check vertices.length === 0? at beginning of addVertex() // in order to avoid the temporary path construction and other operations? return Math.max(idx, 0); }
javascript
{ "resource": "" }
q59195
findMiddleVertex
validation
function findMiddleVertex(p1, p2, preferredDirection) { var direction = bestDirection(p1, p2, preferredDirection); if (direction === 'down' || direction === 'up') { return { x: p1.x, y: p2.y, d: direction }; } return { x: p2.x, y: p1.y, d: direction }; }
javascript
{ "resource": "" }
q59196
validation
function(cell) { var id = _.isString(cell) ? cell : cell.id; var $view = this.$('[model-id="' + id + '"]'); if ($view.length) { return $view.data('view'); } return undefined; }
javascript
{ "resource": "" }
q59197
validation
function(p) { p = g.point(p); var views = _.map(this.model.getElements(), this.findViewByModel); return _.filter(views, function(view) { return g.rect(V(view.el).bbox(false, this.viewport)).containsPoint(p); }, this); }
javascript
{ "resource": "" }
q59198
validation
function(r) { r = g.rect(r); var views = _.map(this.model.getElements(), this.findViewByModel); return _.filter(views, function(view) { return r.intersect(g.rect(V(view.el).bbox(false, this.viewport))); }, this); }
javascript
{ "resource": "" }
q59199
validation
function(command) { return _.isArray(command) ? _.find(command, function(singleCmd) { return !this._validateCommand(singleCmd); }, this) : this._validateCommand(command); }
javascript
{ "resource": "" }