query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Evaluate the Lagrange interpolation polynomial at x = `at` using x and y Arrays that are of the same length, with corresponding elements constituting points on the polynomial. | function lagrange(at, x, y){
var sum = 0,
product,
i, j;
for(var i=0, len = x.length; i<len; i++){
if(!y[i]){
continue;
}
product = config.logs[y[i]];
for(var j=0; j<len; j++){
if(i === j){ continue; }
if(at === x[j]){ // happens when computing a share that is in the list of shares used to compute it
product = -1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1
break;
}
product = ( product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.max/* to make sure it's not negative */ ) % config.max;
}
sum = product === -1 ? sum : sum ^ config.exps[product]; // though exps[-1]= undefined and undefined ^ anything = anything in chrome, this behavior may not hold everywhere, so do the check
}
return sum;
} | [
"function linear_interpolate(x, x0, x1, y0, y1){\n return y0 + ((y1 - y0)*((x-x0) / (x1-x0)));\n}",
"function polyEval(evalPoint, constTerm, ...coeffs) {\n return add(constTerm, ...coeffs.map((c, j) => c.mul(scalar(evalPoint).toThe(scalar(j+1)))))\n}",
"function interpolate(x, xl, xh, yl, yh) {\n var r = 0;\n if ( x >= xh ) {\n r = yh;\n } else if ( x <= xl ) {\n r = yl;\n } else if ( (xh - xl) < 1.0E-8 ) {\n r = yl+(yh-yl)*((x-xl)/1.0E-8);\n } else {\n r = yl+(yh-yl)*((x-xl)/(xh-xl));\n }\n return r;\n }",
"function val2between({\n xy, //function y(x) set as pairs in array [e1,e2]\n x, //\"anchor\" value of x,\n //By default y=e1, x=e2,\n inv, //inverse pairs, means x=e2, y=e1,\n }){\n var xy = xy;\n var alen = xy.length;\n var alen1 = xy.length-1;\n var indMax = alen - 1;\n var indMin = 0;\n\n var frDim = inv ? 1 : 0;\n var depDim = frDim ? 0 : 1;\n\n var xMax = xy[ alen-1 ][frDim];\n var xMin = xy[ 0 ][frDim];\n //virtual direction\n var xDir = xMax - xMin > 0;\n\n if( xDir === 0 ) {\n return { x, y : xy[0][depDim], indMin : 0, indMax : 0, xMin, xMax, };\n }\n var xDir = xDir > 0 ? 1 : -1;\n\n if( ( xMax - x ) * xDir < 0 ) {\n return { x, y : xy[alen1][depDim], indMin : alen1, indMax : alen1, xMin, xMax, };\n }\n if( ( xMin - x ) * xDir > 0 ) {\n return { x, y : xy[0][depDim], indMin : 0, indMax : 0, xMin, xMax, };\n }\n\n var count = 0; //todom remove this protector\n while( indMax-indMin > 1 ) {\n\n /*\n //*********************************************\n // //\\\\ interpolating algo\n //=============================================\n //this is an alternative to binary division algo,\n //for y = x^5, this ago takes 230 steps vs binary which has only 14\n var frMa = xy[ indMax ][1];\n var frMi = xy[ indMin ][1];\n var scaleY = ( frMa - frMi ) / ( indMax - indMin );\n var indMiddle = scaleY === 0 ? indMin : ( y - frMi ) / scaleY + indMin;\n var { indMin, indMax } = findsContaningInterval(\n indMiddle, indMin, indMax, xy );\n if( count++ > 300 ) {\n throw new Error( 'divergent algo' );\n }\n //=============================================\n // \\\\// interpolating algo\n //*********************************************\n */\n\n //*********************************************\n // //\\\\ binary division algo\n //=============================================\n //this is an alternative to interpolating algo\n var binaryMiddle = ( indMax + indMin ) / 2;\n var { indMin, indMax } = findsContaningInterval(\n binaryMiddle, indMin, indMax, xy, frDim );\n if( count++ > 200 ) {\n throw new Error( 'divergent algo?' );\n }\n //=============================================\n // //\\\\ binary division algo\n //*********************************************\n\n //ccc( { indMin, indMax, count } );\n }\n\n //final result:\n var frMa = xy[ indMax ][frDim];\n var frMi = xy[ indMin ][frDim];\n if( indMax === indMin || Math.abs( scaleY ) < 1e-100 ) {\n var y = xy[ indMin ][depDim];\n var indMiddle = indMin;\n } else {\n var scaleY = ( frMa - frMi ) / ( indMax - indMin );\n if( Math.abs( scaleY ) < 1e-100 ) {\n var y = xy[ indMin ][depDim];\n var indMiddle = indMin;\n } else {\n var yMa = xy[ indMax ][depDim];\n var yMi = xy[ indMin ][depDim];\n var scaleX = ( yMa - yMi ) / ( indMax - indMin );\n var y = scaleX * ( x - frMi ) / scaleY + yMi;\n var indMiddle = ( indMax - indMin ) * ( x - frMi ) / scaleY + indMin;\n }\n }\n return { x, y, indMin, indMax, xMin, xMax, indMiddle, count };\n\n\n\n\n function findsContaningInterval(\n indMiddle, //proposed new position of interval boundary\n indMin, //current\n indMax, //current\n xy, //main array\n frDim,\n ){\n var newMin = Math.floor( indMiddle );\n var newMax = Math.ceil( indMiddle );\n if( ( x - xy[ newMin ][frDim] ) * xDir < 0 ) {\n ////new Min is above x, take it as max\n indMax = newMin;\n } else if( ( x - xy[ newMax ][frDim] ) * xDir > 0 ) {\n ////new Max is below x, take it as min\n indMin = newMax;\n } else {\n ////x is in between grid cell, it can be newMin === newMax,\n indMin = newMin;\n indMax = newMax;\n }\n return { indMin, indMax };\n }\n\n }",
"interpolateY(x) { // input x (real-number)\n var index = this.bisection(x);\n \n if(this.arySrcX[index] === x)\n return this.arySrcY[index];\n else\n return this.doCubicSpline(x, index);\n }",
"function lagrangeCoefficients(idx) {\n const res = Array(idx.length)\n const w = idx.reduce((w, id) => w * id, 1n)\n for (let i = 0; i < idx.length; i++) {\n let v = idx[i]\n for (let j = 0; j < idx.length; j++) {\n if (j != i) {\n v *= idx[j] - idx[i]\n }\n }\n res[i] = new math.Fr(v).invert().multiply(w).value\n }\n return res\n}",
"function generateLIP() {\n\tlet i = 0;\n\tlet j = 0;\n\tlet k = 0;\n\n\tlet den = 1;\n\tlet nom = \"\";\n\tlet equation = \"\";\n\n\tconst noms = []\n\tconst dens = [];\n\n\tlet continuous = checkContinuity();\n\tp2.hide();\n\n\tif (continuous) {\n\n\t\twhile (j < (xValues.length)) {\n\n\t\t\tif (k == (xValues.length)) {\n\t\t\t\tk = 0;\n\t\t\t\tj++;\n\t\t\t\tdens.push(den);\n\t\t\t\tden = 1;\n\t\t\t\tnoms.push(nom + yValues[j - 1]);\n\t\t\t\tnom = \"\";\n\t\t\t}\n\n\t\t\tif (j == k) {\n\t\t\t\tk++;\n\t\t\t} else {\n\t\t\t\tden *= (float(xValues[j]) - float(xValues[k]));\n\t\t\t\tnom += (\"(x - \" + xValues[k] + \") * \");\n\t\t\t\tk++;\n\t\t\t}\n\n\t\t}\n\n\t\twhile (i < ((yValues.length) - 1)) {\n\t\t\tequation += \"{\" + noms[i] + \"} / {\" + String(dens[i]) + \"}\" + \" + \";\n\t\t\ti++;\n\t\t}\n\n\t\tif (i == ((yValues.length) - 1)) {\n\t\t\tequation += \"{\" + noms[i] + \"} / {\" + String(dens[i]) + \"}\";\n\t\t}\n\n\t\tsaveStrings([equation], 'Curve.txt');\n\n\t} else {\n\t\tp2.show();\n\t}\n}",
"function lerp(x1,y1,x2,y2,y3) {\n\treturn ((y2-y3) * x1 + (y3-y1) * x2)/(y2-y1);\n}",
"function computeEachPoint(min, max, fx)\n{\n let xData = [];\n let yData = [];\n const step = 0.1;\n\n for(let i = min;i <= max; i += step)\n {\n xData.push(i);\n let y = fx(i);\n yData.push(y);\n }\n\n return [xData, yData];\n}",
"function lerpPolynomials(poly1, poly2, pct){\r\n var newPoly = [];\r\n for(let i = 0; i < polyDegree+1; i++){\r\n newPoly.push(lerp(poly1[i], poly2[i], pct));\r\n }\r\n\r\n return newPoly;\r\n}",
"function derive(){ // Fills Arrays of 1sd Derivative Coordinates\n\tvar m = 0; // Slope!\n\t\n\t//console.clear(); // For Debug.\n\t//console.log(\"Derivative Points:\"); // For Debug.\n\t// Find the Slope at Every Point of the Function\n\tfor(i=0;i<xPoints.length;i++) {\n\t\tm =(yPoints[i+1]-yPoints[i])/(xPoints[i+1]-xPoints[i]); // Calculate Slope\n\t\t//console.log(\"M: \"+m); // Debug\n\t\t/* if(xPoints[i]>0.5&&xPoints[i]<1)\n\t\t\tconsole.log(xPoints[i]+\", \"+m.toFixed(4)); */\n\n\t\tif(!isNaN(m)&&m!=Infinity&&!(Math.abs(m)>hLines/2*gScale)&&i>0){\n\t\t\t\t\n\t\t\t\n\t\t\tderX[i]=xPoints[i].toFixed(4);\n\t\t\tderY[i]=m.toFixed(4);\n\t\t\tif(functionInput.value.includes(\"abs\")&&derY[i]>0&&derY[i-1]<0||derY[i]<0&&derY[i-1]>0||derY[i]>0&&derY[i-1]==0||derY[i]<0&&derY[i-1]==0){\n\t\t\t\tderY[i]=NaN;\n\t\t\t}\n\t\t\t//if(derX[i]>-0.5&&derX[i]<0.5)\n\t\t\t\t//console.log(derX[i],derY[i]); // Debug\n\t\t}\n\t}\n}",
"function interpolateAt(x_, shares) {\n return interpolateListAt(x_, shares.reduce((acc, s, i) => { if (s) acc.push([i+1, s]); return acc }, [ ]))\n}",
"function interpolateListAt(x_, shares) {\n const x = scalar(x_)\n \n // the values being interpolated can either be scalars or elliptic curve points\n let typeOfShares = (shares[0][1].isScalar) ? scalar : point\n\n return shares.reduce((sacc, [i_, share]) => {\n const i = scalar(i_)\n const coeff = shares.reduce((acc, [j_]) => {\n if (i_ === j_) return acc\n \n const j = scalar(j_)\n return acc.mul(x.sub(j).div(i.sub(j))) // acc *= (x-j)/(i-j)\n }, scalar(1))\n \n return sacc.add(share.mul(coeff))\n }, typeOfShares(0))\n}",
"function bilinearInterpolateScalar(x, y, g00, g10, g01, g11) {\n var rx = (1 - x);\n var ry = (1 - y);\n return g00 * rx * ry + g10 * x * ry + g01 * rx * y + g11 * x * y;\n }",
"function interpolateValues(values, year) {\n var i = bisect.left(values, year, 0, values.length - 1),\n a = values[i];\n return a[1];\n }",
"function solveEquation(params, x, y) {\n\n\n console.log(\"Solving equation\");\n //gets x values from global\n\n decaycurve = function(x, P) {\n\n return x.map(\n function(xi) {\n return getPareto(xi, P[0], P[1])\n }\n\n )\n };\n\n\n //Parms=fminsearch(fun,[100,30,10,5000],x,y);\n // Returns an array of coeffcients\n Parms = fminsearch(decaycurve, [.1, .1], x, y, {\n maxIter: 10000,\n display: true\n });\n\n\n //Math.round(original*100)/100 \n\n ra1 = Parms[0];\n ra2 = Parms[1];\n //rb1 = Parms[2];\n a1 = Math.round(Parms[0] * 1000) / 1000;\n a2 = Math.round(Parms[1] * 1000) / 1000;\n //b1 = Math.round(Parms[2]*1000)/1000;\n\n /*\n for (i = 0; i < x.length; i++) {\n roascurve.push(getPareto(x[i], Parms[0], Parms[1]));\n\n }\n*/\n return Parms; // Returns Array of Co-Efficients\n\n\n}",
"function interpolate(c, p, alpha) {\n var x = p.x + ((c.x - p.x) * alpha);\n var y = p.y + ((c.y - p.y) * alpha);\n\n return { x: (x | 0), y: (y | 0) };\n}",
"function createInterpolator(data, numTimes, numStations) {\n interpolateProgram = GLProgram.create(gl)\n .loadShader('copyVertices')\n .loadShader('interpolate', '#define SIZE ' + numStations)\n .linkProgram()\n .setUniform('wh', canvas.width, canvas.height)\n .setUniform('stations', numStations)\n .setUniform('times', numTimes)\n .createTexture('data', data, numTimes, numStations, { color: 'rgba', type: 'float', minfilter: filterType, magfilter: filterType })\n .bindLoadedTexture('data', 1)\n .defineUnitQuad('vPosition', 'vTexCoord');\n }",
"function interpolateValues(values, getter, i, iteration) {\n if (i > 0) {\n var ta = iterations[i], tb = iterations[i - 1],\n t = (iteration - ta) / (tb - ta);\n return getter(values[i]) * (1 - t) + getter(values[i - 1]) * t;\n }\n return getter(values[i]);\n }",
"function cubic_interp_1d(p0, p1, p2, p3, x) {\n\t// Horner-scheme like separation of coefficients to save multiplications\n\treturn p1 + 0.5 * x*(p2 - p0 + x*(2.0*p0 - 5.0*p1 + 4.0*p2 - \n\t\tp3 + x*(3.0*(p1 - p2) + p3 - p0)));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This should fire off `ChildActivationStart` events for each route being activated at this level. In other words, if you're activating `a` and `b` below, `path` will contain the `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always return `true` so checks continue to run. | function fireChildActivationStart(snapshot, forwardEvent) {
if (snapshot !== null && forwardEvent) {
forwardEvent(new ChildActivationStart(snapshot));
}
return of(true);
} | [
"function activeRoute(routeName) {\n return window.location.href.indexOf(routeName) > -1 ? true : false\n }",
"function activateCurrentComponents() {\n\t\tcurrentChild.children('.koi-component')\n\t\t\t.removeClass('deeplink-component-disabled')\n\t\t\t.trigger('load-component');\n\t}",
"function OnLevelWasLoaded () {\nif(Application.loadedLevelName == \"menu\"){\n//we create an array of all the objects that are children, then deactivate all of them if its the menu.\n\tfor( var i = 0; i < transform.childCount; ++i ){\n\t\ttransform.GetChild(i).gameObject.SetActive(false);\n\t}\n//if the scene is not the menu, we make sure all children are activated using the same process above.\n}else{\n\tfor( i = 0; i < transform.childCount; ++i ){\n\t\ttransform.GetChild(i).gameObject.SetActive(true);\n\t}\n}\n}",
"attachListeners() {\n // Add listeners that updates the route\n this.listeners.push(this.parent != null\n // Attach child router listeners\n ? addListener(this.parent, \"changestate\", this.render)\n // Add global listeners.\n : addListener(GLOBAL_ROUTER_EVENTS_TARGET, \"changestate\", this.render));\n }",
"function IsItemActivated() { return bind.IsItemActivated(); }",
"function activate() {\n user.registerCb(function(){\n routes.fetch(user.getUser().username)\n .then(function() {});\n });\n\n }",
"_registerInstallActivateEvents() {\n self.addEventListener('install', (event) => {\n event.waitUntil(Promise.all([\n this._revisionedCacheManager.install(),\n this._unrevisionedCacheManager.install(),\n ]));\n });\n\n self.addEventListener('activate', (event) => {\n event.waitUntil(Promise.all([\n this._revisionedCacheManager.cleanup(),\n this._unrevisionedCacheManager.cleanup(),\n ]));\n });\n }",
"function queueActivatedComponent(vm) {\n // setting _inactive to false here so that a render function can\n // rely on checking whether it's in an inactive tree (e.g. router-view)\n vm._inactive = false;\n activatedChildren.push(vm);\n }",
"function onActivatedSurface(tuples, eventName, $event, range, nativeEvent) {\n var i;\n for (i = 0; i < tuples.length; i++) {\n if (tuples[i][0].isActive()) {\n tuples[i][1]($event, range, nativeEvent);\n }\n }\n }",
"function activate() {\n // Register the LatencyHistogramComponent as a role in Compass\n //\n // Available roles are:\n // - Instance.Tab\n // - Database.Tab\n // - Collection.Tab\n // - CollectionHUD.Item\n // - Header.Item\n\n global.hadronApp.appRegistry.registerRole('Collection.Tab', ROLE);\n global.hadronApp.appRegistry.registerAction('LatencyHistogram.Actions', LatencyHistogramActions);\n global.hadronApp.appRegistry.registerStore('LatencyHistogram.Store', LatencyHistogramStore);\n}",
"function activeNavigation() {\n var locationUrl = window.location.href;\n var handlerAndAction = locationUrl\n .replace(/(.*\\/\\/vacation.+?\\/)(index.cfm\\/)?/i, '')\n .replace(/\\?.+/, '')\n .split('/');\n var currentHandler = handlerAndAction[0].toLowerCase();\n var currentAction = handlerAndAction[1] || 'index';\n var currentObjectId = handlerAndAction[2];\n\n $('[data-handler=\"' + currentHandler + '\"]').addClass('active');\n\n // breadcrumbs\n buildBradcrumbs(currentHandler, currentAction, currentObjectId);\n}",
"_initialize() {\n if ( this._initialized ) {\n return;\n }\n\n this._log(2, `Initializing Routes...`);\n\n //Add routing information to crossroads\n // todo: handle internal only routes\n // An internal only route can be used to keep track of UI state\n // But it will never update the URL\n // You can't use .go() to get to an internal route\n // You can only get it via directly calling dispatch(route, params)\n //\n let routes = this.routes;\n\n for (let route of routes) {\n this._log(3, `Initializing >> ${route.name}`);\n\n // Set basename\n route.set_basename(this._basename);\n // Set crossroads_route\n route._crossroads = this.crossroads.addRoute(route.path, this._make_crossroads_shim(route));\n }\n\n this._log(3, `Initialized ${routes.length} routes`);\n this._initialized = true;\n }",
"function requestActivation()\r\n{\r\n\tbrowser.runtime.sendMessage({ type: \"getActivationSettings\" }).then(\r\n\t\tactivationSettings => activate(activationSettings),\t// background script passes a few settings needed for setup\r\n\t\tgetErrorHandler(\"Error sending getActivationSettings message from content script.\")\r\n\t);\r\n}",
"function possiblyActivateMenuItem (menuItem) {\n cancelPendingMenuItemActivations()\n if (shouldChangeActiveMenuItem()) {\n deactivateActiveMenuItem()\n activateMenuItem(menuItem)\n return true\n }\n }",
"function _isMapActivatable() {\n return self.type !== ScrollableMap.TYPE_NEWWEB && // Web maps are never activatable\n bodyScrolls &&\n pref('frameRequireFocus') &&\n enabled &&\n !mapClicked;\n }",
"function openActiveNav(){\n\n\t\tvar activeMenuItem = $('.fusion-main-menu').find('.current-menu-item');\n\t\tvar activeSubMenuItem = $('.fusion-main-menu').find('.current-menu-parent');\n\t\tif(activeSubMenuItem.length != 0){\n\t\t\tchangeDropdownIndicator(activeSubMenuItem);\n\t\t} else if(activeMenuItem.length != 0){\n\t\t\tchangeDropdownIndicator(activeMenuItem);\n\t\t} \n\n\t}",
"isComplete (packs) {\n return packs.every(pack => {\n return Pathfinder.isLifecycleValid (pack, packs)\n })\n }",
"eventsInit() {\n // Force a focus event to fire based on a click event for browsers which don't trigger focusin\n // from a 'click' by default (eg: Safari desktop)\n events.delegate(this.element, '.tabbed-content__trigger', 'click', (e) => {\n e.preventDefault();\n\n // Find the clicked link element (since an SVG icon could have fired this event)\n const targetElem = TabbedContent.findTriggerLinkElem(e);\n\n // Fire focus event is triggered from a click (not via a focusin) - eg: Safari desktop\n if (targetElem !== document.activeElement) {\n targetElem.focus();\n }\n });\n\n // Focus event for tabbing through the Tabbed Content component\n events.delegate(this.element, '.tabbed-content__trigger', this.eventType, (e) => {\n // Find the clicked link element (since an SVG icon could have fired this event)\n const targetElem = TabbedContent.findTriggerLinkElem(e);\n\n const requestedTabIndex = this.getRequestedTabIndex(targetElem);\n\n // Show the requested tab\n this.showRequestedTab(requestedTabIndex);\n });\n\n // Check that a tab is open when links inside it are focused upon\n // This is primarily to cover Shift+Tab, for reverse tabbing\n events.delegate(this.element, '.tabbed-content__content a', this.eventType, (e) => {\n e.preventDefault();\n\n const tabElemLinkBelongsTo = findParentNode({className: 'tabbed-content__content'}, e.target);\n\n if (!tabElemLinkBelongsTo.classList.contains('active')) {\n events.fire(tabElemLinkBelongsTo.previousElementSibling, this.eventType);\n }\n });\n }",
"async hasMiddleware(pathname) {\n const info = this.getEdgeFunctionInfo({\n page: pathname,\n middleware: true\n });\n return Boolean(info && info.paths.length > 0);\n }",
"getNextRoutes(path: PathElement<*, *>[], location: Location): Route<*, *>[] {\n const query = getQueryParams(location)\n return path.map(element => {\n const matchedQueryParams = this.getMatchedQueryParams(element.node, query)\n const newRoute = createRoute(element.node, element.parentUrl, element.segment, element.params, query)\n const existingRoute = this.routes.find(x => areRoutesEqual(x, newRoute))\n \n if (existingRoute) {\n return existingRoute\n } else {\n return observable(createRoute(element.node, element.parentUrl, element.segment, element.params, matchedQueryParams))\n }\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the query. Calls itself recursively if there are 'dynamic' entries deeper down in the query. | _init_query(config, parent_keys) {
parent_keys = parent_keys || [];
if (config.one_required) {
this._add_one_required(config.one_required, parent_keys);
}
if (!config.query) {
throw `Trying to initialize datasource without query (${this.get_id()})`;
}
for (let [key, subconfig] of Object.entries(config.query)) {
if (!Object.isObject(subconfig) || subconfig.type === undefined) {
// Straight up value
this._set_query_param(key, subconfig, parent_keys);
} else if (subconfig.type === 'static') {
// Type indicates it's a straight up value
this._set_query_param(key, subconfig.data, parent_keys);
} else if (subconfig.type === 'placeholder') {
this._set_query_param(key, subconfig.default, parent_keys);
if (subconfig.required) {
this._add_required_key(key, parent_keys);
}
} else if (subconfig.type === 'observer') {
// Observer, register for event
this._set_query_param(key, subconfig.default, parent_keys);
if (subconfig.required) {
this._add_required_key(key, parent_keys);
}
let mapping;
if (subconfig.mapping || subconfig.mapping_default) {
mapping = Mapping.gen_mapping(subconfig);
}
if (subconfig.event_type) {
let callback = payload => {
if (subconfig.event_filter) {
let filter = this.gen_event_filter(subconfig.event_filter);
if (!filter(this, subconfig.event_type, payload)) {
return;
}
}
let changed = false;
if (mapping) {
payload = mapping(payload);
}
if (Utils.is_set(payload, true) || subconfig.default === undefined) {
changed = this._set_query_param(key, payload, parent_keys);
} else {
changed = this._set_query_param(key, subconfig.default, parent_keys);
}
if (changed && this._auto_get_data) {
clearTimeout(this._get_data_timeout);
this._get_data_timeout = setTimeout(() => {
this._get_data(undefined, this._disable_cache);
}, this.get_data_timeout);
}
};
if (Object.isArray(subconfig.event_type)) {
Observer.register_many(subconfig.event_type, callback);
} else {
Observer.register(subconfig.event_type, callback);
}
}
} else if (subconfig.type === 'dynamic') {
// Subquery, init recursively
this._init_query(subconfig, [...parent_keys, key]);
} else {
// Invalid
throw 'Invalid query';
}
}
} | [
"fillPopulations(query) {\n if(this.populations && this.populations.length) {\n this.populations.forEach(function (populateObj) {\n query = query.populate(populateObj)\n })\n }\n\n return query\n }",
"_getQueryBy(callback) {\r\n var query = new Query(); // Create a new instance for nested scope.\r\n callback.call(query, query);\r\n query.sql = query.getSelectSQL();\r\n return query; // Generate SQL statement.\r\n }",
"static __query() {\n // Ensure model is registered before creating query\n assert.instanceOf(this.__db, DbApi, 'Model must be registered.');\n\n // Return a newly constructed DbQuery given `this` and internal DB API\n return new DbQuery(this, this.__db);\n }",
"function _postSubQuery( opt ){\r\n//console.log(\"_postSubQuery()\", arguments, \"caller: \", _postSubQuery.caller );\r\n//console.log(\"_postSubQuery()\", opt );\r\n//console.log(options);\r\n\r\n\t\t\tvar num_condition = opt[\"subQuery\"][\"num_condition\"];\r\n\t\t\t//var targetField = opt[\"baseQuery\"][\"where\"][num_condition][\"key\"];\r\n\t\t\tvar targetField = opt[\"subQuery\"][\"targetFields\"][0];\r\n\t\t\tvar data = opt[\"data\"]; \r\n//console.log(data, data.length, num_condition, targetField);\r\n\r\n\t\t\tvar filter = [];\r\n\t\t\tif( data.length > 0){\r\n\t\t\t\tfor( var n = 0; n < data.length; n++){\r\n//console.log(data[n], data[n][targetField], targetField);\r\n\t\t\t\t\tfilter.push( data[n][targetField] );\r\n\t\t\t\t}\r\n\t\t\t}\r\n//console.log( filter );\r\n\r\n\t\t\tif( opt[\"parentQuery\"] ){\r\n\t\t\t\topt[\"parentQuery\"][\"where\"][num_condition][\"value\"] = filter;\r\n\t\t\t} else {\r\n\t\t\t\topt[\"baseQuery\"][\"where\"][num_condition][\"value\"] = filter;\r\n//console.log(opt[\"baseQuery\"]);\r\n\t\t\t}\r\n\r\n\t\t\t//detect sub query in opt[\"subQuery\"]\r\n\t\t\t//if( opt[\"subQuery\"][\"where\"][0][\"value\"][\"action\"] ){\r\n//console.log(opt[\"subQuery\"], num_condition);\r\n\t\t\t\t//opt[\"baseQuery\"][\"where\"][num_condition][\"value\"] = opt[\"subQuery\"];\r\n\t\t\t//}\r\n\t\t\t//var subQuery = _detectSubQuery( opt[\"subQuery\"] );\r\n//console.log( subQuery );\r\n\t\t\t\t\r\n\t\t\t_query( {\r\n\t\t\t\t\"queryObj\" : opt[\"baseQuery\"],\r\n\t\t\t\t\"callback\" : options[\"callback\"]\r\n\t\t\t});\r\n\r\n\t\t}",
"buildSearchQuery() {\n if (this.get('invalidSearchTerm') || Ember.isEmpty(this.get('searchTerm'))) {\n return {};\n }\n const searchTerm = this.get('searchTerm');\n const query = {};\n\n if (this.get('searchType.date')) {\n if (_dates.default.isValidDate(searchTerm, 'MM/DD/YYYY')) {\n query.birthDate = searchTerm;\n } else {\n this.set('searchType.date', false);\n }\n }\n if (this.get('searchType.ssn')) {\n if (/^\\d{3}-?\\d{2}-?\\d{4}$/.test(searchTerm)) {\n query.socialSecurityNumber = searchTerm;\n this.set('searchTerm', _pfStringUtil.default.formatSSN(this.get('searchTerm')));\n } else {\n this.set('searchType.ssn', false);\n }\n }\n if (this.get('searchType.name')) {\n Ember.merge(query, _patientSearch.default.formatNameParameters(searchTerm));\n }\n if (this.get('searchType.prn')) {\n query.patientRecordNumber = searchTerm;\n }\n return query;\n }",
"function generateQuery (type) {\n const query = new rdf.Query()\n const rowVar = kb.variable(keyVariable.slice(1)) // don't pass '?'\n\n addSelectToQuery(query, type)\n addWhereToQuery(query, rowVar, type)\n addColumnsToQuery(query, rowVar, type)\n\n return query\n }",
"function buildQueryObject(formData) {\n const {\n time_range,\n since,\n until,\n order_desc,\n row_limit,\n row_offset,\n limit,\n timeseries_limit_metric,\n queryFields\n } = formData,\n residualFormData = _objectWithoutPropertiesLoose(formData, [\"time_range\", \"since\", \"until\", \"order_desc\", \"row_limit\", \"row_offset\", \"limit\", \"timeseries_limit_metric\", \"queryFields\"]);\n\n const numericRowLimit = Number(row_limit);\n const numericRowOffset = Number(row_offset);\n const {\n metrics,\n groupby,\n columns\n } = (0, _extractQueryFields.default)(residualFormData, queryFields);\n const groupbySet = new Set([...columns, ...groupby]);\n return _extends({\n extras: (0, _processExtras.default)(formData),\n granularity: processGranularity(formData),\n groupby: (0, _processGroupby.default)(Array.from(groupbySet)),\n is_timeseries: groupbySet.has(DTTM_ALIAS),\n metrics: metrics.map(_convertMetric.default),\n order_desc: typeof order_desc === 'undefined' ? true : order_desc,\n orderby: [],\n row_limit: row_limit == null || Number.isNaN(numericRowLimit) ? undefined : numericRowLimit,\n row_offset: row_offset == null || Number.isNaN(numericRowOffset) ? undefined : numericRowOffset,\n since,\n time_range,\n timeseries_limit: limit ? Number(limit) : 0,\n timeseries_limit_metric: timeseries_limit_metric ? (0, _convertMetric.default)(timeseries_limit_metric) : null,\n until\n }, (0, _processFilters.default)(formData));\n}",
"function prepareQuery(query, specialsData) {\n var special;\n\n for (special in specialsData) {\n var handler = handlers[special];\n var filterValue = specialsData[special];\n\n if (typeof handler !== 'function' || !filterValue) {\n continue;\n }\n\n // call the right handler for the special with the query as context\n handler.call(query, filterValue);\n }\n}",
"get query() {\n return this._parsed.query || {};\n }",
"_handleNestedWhere(callback) {\r\n var query = new Query(); // Create a new instance for nested scope.\r\n callback.call(query, query);\r\n if (query._where) {\r\n this._where += \"(\" + query._where + \")\";\r\n this._bindings = this._bindings.concat(query._bindings);\r\n }\r\n return this;\r\n }",
"function Query(key, param_settings) {\n this.key = key;\n this.cql_config = param_settings.cql_config;\n \n // the parent widget holding the search-clauses;\n this.widget ={};\n \n this.searchclauses = [];\n this.and_divs = [];\n\n /** add SC relative to an existing one */ \n this.addSearchClause = function(source_clause, rel) {\n \n var add_and = 0;\n // compute the position-index in the search-clauses (and/or-matrix)\n if (source_clause == null || rel=='and') {\n // if no related clause, put at the end\n and_pos = this.searchclauses.length;\n or_pos = 0;\n add_and = 1;\n } else {\n and_pos = source_clause.and_pos;\n or_pos = this.searchclauses[and_pos].length;\n }\n \n console.log (and_pos + '-' + or_pos);\n \n if (add_and==1) {\n this.searchclauses[and_pos] = [];\n var and_div = $(\"<div class='and_level'>\");\n this.widget.append(and_div);\n this.and_divs[and_pos] = and_div; \n } \n \n sc = new SearchClause(this, and_pos, or_pos);\n this.searchclauses[and_pos][or_pos] = sc;\n \n if (this.widget) {\n this.and_divs[and_pos].append(sc.widget);\n } \n }\n \n /** add SC relative to an existing one */ \n this.removeSearchClause = function(source_clause) {\n \n and_pos = source_clause.and_pos;\n or_pos = source_clause.or_pos;\n \n // don't remove the first SC \n if (!(and_pos==0 && or_pos==0)) { \n this.searchclauses[and_pos][or_pos] = null;\n source_clause.widget.remove();\n }\n }\n}",
"function setOperandOnLoad() {\n if (!_.isEmpty(scope.query._value)) {\n if (scope.query._value instanceof Object) {\n if (scope.operator === '$in' || scope.operator === \"$not\") {\n scope.operand['regex'] = filterRegex(scope.query._value['$regex']);\n scope.operand['options'] = scope.query._value['$options'];\n } else {\n scope.operand[scope.operator.replace('$', '')] = scope.query._value[scope.operator];\n }\n } else {\n scope.operand['equals'] = scope.query._value;\n }\n }\n }",
"runSoqlQuery()\n {\n this.setSelectedMapping();\n this.setSelectedAction();\n this.callRetrieveRecordsUsingWrapperApex();\n }",
"function analyzeQuery(query, root)\n {\n let allSubQueries = [{\n exact: [],\n sort: {},\n range: []\n }];\n\n // First, go through the query for all exact match fields\n Object.keys(query).forEach(function(key)\n {\n const value = query[key];\n\n // This is not a special mongo field\n if(key[0] != '$')\n {\n // Now look at the value, and decide what to do with it\n if(value instanceof Date || value instanceof mongodb.ObjectID || value instanceof mongodb.DBRef)\n {\n allSubQueries.forEach(subQuery => subQuery.exact.push(trimPeriods(root + key)));\n }\n else if(value instanceof Object)\n {\n const subQueries = analyzeQuery(value, root + key);\n allSubQueries = mergeSubQueries(allSubQueries, subQueries);\n }\n else\n {\n allSubQueries.forEach(subQuery => subQuery.exact.push(trimPeriods(root + key)));\n }\n }\n else\n {\n if(key == '$lt' || key == '$lte' || key == '$gt' || key == '$gte' || key == '$in' || key == '$nin' || key == '$neq' || key == '$ne' || key == '$exists' || key == '$mod' || key == '$all' || key == '$regex' || key == '$size')\n {\n allSubQueries.forEach(subQuery => subQuery.range.push(trimPeriods(root)));\n }\n else if(key == '$eq')\n {\n allSubQueries.forEach(subQuery => subQuery.exact.push(trimPeriods(root)));\n }\n else if(key == \"$not\")\n {\n const elemSubQueries = analyzeQuery(value, root);\n allSubQueries = mergeSubQueries(allSubQueries, elemSubQueries);\n }\n else if(key == '$elemMatch')\n {\n // For $elemMatch, we have to create a subquery, and then modify its field names and merge\n // it into our existing sub queries\n const elemSubQueries = analyzeQuery(value, root + \".\");\n allSubQueries = mergeSubQueries(allSubQueries, elemSubQueries);\n }\n else if(key == '$options' || key == '$hint' || key == '$explain' || key == '$text')\n {\n // We can safely ignore these\n }\n else if(key == '$and' || key == '$or')\n {\n // Ignore these, they are processed after\n }\n else if(key == '$comment')\n {\n // Comments can be used by the application to provide additional metadata about the query\n allComments.push(value);\n }\n else\n {\n console.error(\"Unrecognized field query command: \", key);\n }\n }\n });\n\n // Now if there are $and conditions, process them\n if (query['$and'])\n {\n query['$and'].forEach(function(andSubQuery)\n {\n allSubQueries = mergeSubQueries(allSubQueries, analyzeQuery(andSubQuery, root));\n });\n }\n\n // Lastly, process any $or conditions\n if (query['$or'])\n {\n allSubQueries = mergeSubQueries(allSubQueries, underscore.flatten(query['$or'].map(subQuery => analyzeQuery(subQuery, root))));\n }\n\n return allSubQueries;\n }",
"buildSOQL() {\n let soql;\n if (this.fields) soql = this.appendField();\n soql += this.appendWhere();\n soql += ' WITH SECURITY_ENFORCED ';\n\n //if we filter on a column then we ignore the ORDER BY defined in the configuration\n if (this.orderBy && !this.sortBy) {\n soql += ` ORDER BY ${this.orderBy}`;\n } else if (this.sortBy && this.sortDirection) {\n soql += ` ORDER BY ${this.sortBy} ${this.sortDirection} `;\n }\n\n if (this.limit && this.limit > 0) {\n soql += this.appendLimit();\n soql += this.appendOffset();\n }\n\n this.soql = soql;\n }",
"_initialize() {\n // The following version number must be updated if there is any\n // change to the way in which a GraphQL schema is mapped to a SQL\n // schema or the way in which the resulting SQL schema is\n // interpreted. If you've made a change and you're not sure whether\n // it requires bumping the version, bump it: requiring some extra\n // one-time cache resets is okay; doing the wrong thing is not.\n const blob = stringify({version: \"MIRROR_v1\", schema: this._schema});\n const db = this._db;\n _inTransaction(db, () => {\n // We store the metadata in a singleton table `meta`, whose unique row\n // has primary key `0`. Only the first ever insert will succeed; we\n // are locked into the first schema.\n db.prepare(\n dedent`\\\n CREATE TABLE IF NOT EXISTS meta (\n zero INTEGER PRIMARY KEY,\n schema TEXT NOT NULL\n )\n `\n ).run();\n\n const existingBlob: string | void = db\n .prepare(\"SELECT schema FROM meta\")\n .pluck()\n .get();\n if (existingBlob === blob) {\n // Already set up; nothing to do.\n return;\n } else if (existingBlob !== undefined) {\n throw new Error(\n \"Database already populated with incompatible schema or version\"\n );\n }\n db.prepare(\"INSERT INTO meta (zero, schema) VALUES (0, ?)\").run(blob);\n\n // First, create those tables that are independent of the schema.\n const structuralTables = [\n // Time is stored in milliseconds since 1970-01-01T00:00Z, with\n // ECMAScript semantics (leap seconds ignored, exactly 86.4M ms\n // per day, etc.).\n //\n // We use milliseconds rather than seconds because (a) this\n // simplifies JavaScript interop to a simple `+new Date()` and\n // `new Date(value)`, and (b) this avoids a lurking Year 2038\n // problem by surfacing >32-bit values immediately. (We have\n // over 200,000 years before the number of milliseconds since\n // epoch is more than `Number.MAX_SAFE_INTEGER`.)\n dedent`\\\n CREATE TABLE updates (\n rowid INTEGER PRIMARY KEY,\n time_epoch_millis INTEGER NOT NULL\n )\n `,\n dedent`\\\n CREATE TABLE objects (\n id TEXT NOT NULL PRIMARY KEY,\n typename TEXT NOT NULL,\n last_update INTEGER,\n FOREIGN KEY(last_update) REFERENCES updates(rowid)\n )\n `,\n dedent`\\\n CREATE TABLE links (\n rowid INTEGER PRIMARY KEY,\n parent_id TEXT NOT NULL,\n fieldname TEXT NOT NULL,\n child_id TEXT,\n UNIQUE(parent_id, fieldname),\n FOREIGN KEY(parent_id) REFERENCES objects(id),\n FOREIGN KEY(child_id) REFERENCES objects(id)\n )\n `,\n dedent`\\\n CREATE UNIQUE INDEX idx_links__parent_id__fieldname\n ON links (parent_id, fieldname)\n `,\n dedent`\\\n CREATE TABLE connections (\n rowid INTEGER PRIMARY KEY,\n object_id TEXT NOT NULL,\n fieldname TEXT NOT NULL,\n last_update INTEGER,\n -- Each of the below fields must be NULL if the connection\n -- has never been updated.\n total_count INTEGER,\n has_next_page BOOLEAN,\n -- The end cursor may be NULL if no items are in the connection;\n -- this is a consequence of GraphQL and the Relay pagination spec.\n -- (It may also be NULL if the connection was never updated.)\n end_cursor TEXT,\n CHECK((last_update IS NULL) = (total_count IS NULL)),\n CHECK((last_update IS NULL) = (has_next_page IS NULL)),\n CHECK((last_update IS NULL) <= (end_cursor IS NULL)),\n UNIQUE(object_id, fieldname),\n FOREIGN KEY(object_id) REFERENCES objects(id),\n FOREIGN KEY(last_update) REFERENCES updates(rowid)\n )\n `,\n dedent`\\\n CREATE UNIQUE INDEX idx_connections__object_id__fieldname\n ON connections (object_id, fieldname)\n `,\n dedent`\\\n CREATE TABLE connection_entries (\n rowid INTEGER PRIMARY KEY,\n connection_id INTEGER NOT NULL,\n idx INTEGER NOT NULL, -- impose an ordering\n child_id TEXT,\n UNIQUE(connection_id, idx),\n FOREIGN KEY(connection_id) REFERENCES connections(rowid),\n FOREIGN KEY(child_id) REFERENCES objects(id)\n )\n `,\n dedent`\\\n CREATE INDEX idx_connection_entries__connection_id\n ON connection_entries (connection_id)\n `,\n ];\n for (const sql of structuralTables) {\n db.prepare(sql).run();\n }\n\n // Then, create primitive-data tables, which depend on the schema.\n // We only create tables for object types, as union types have no\n // physical representation; they exist only at the type level.\n for (const typename of Object.keys(this._schemaInfo.objectTypes)) {\n const type = this._schemaInfo.objectTypes[typename];\n if (!isSqlSafe(typename)) {\n throw new Error(\n \"invalid object type name: \" + JSON.stringify(typename)\n );\n }\n for (const fieldname of type.primitiveFieldNames) {\n if (!isSqlSafe(fieldname)) {\n throw new Error(\"invalid field name: \" + JSON.stringify(fieldname));\n }\n }\n const tableName = _primitivesTableName(typename);\n const tableSpec = [\n \"id TEXT NOT NULL PRIMARY KEY\",\n ...type.primitiveFieldNames.map((fieldname) => `\"${fieldname}\"`),\n \"FOREIGN KEY(id) REFERENCES objects(id)\",\n ].join(\", \");\n db.prepare(`CREATE TABLE ${tableName} (${tableSpec})`).run();\n }\n });\n }",
"function initializeRows() {\n resultContainer.empty();\n var resultsToAdd = [];\n for (var i = 0; i < results.length; i++) {\n resultsToAdd.push(createNewRow(results[i]));\n }\n resultContainer.append(resultsToAdd);\n }",
"initializeResults() {\n\t\t$( '.mlp-search-field' ).each( ( index, element ) => this.initializeResult( element ) );\n\t}",
"_query(connection, obj) {\n if (!obj || typeof obj === 'string') obj = {sql: obj}\n return new Promise(function(resolver, rejecter) {\n let { sql } = obj\n if (!sql) return resolver()\n if (obj.options) sql = assign({sql}, obj.options)\n connection.query(sql, obj.bindings, function(err, rows, fields) {\n if (err) return rejecter(err)\n obj.response = [rows, fields]\n resolver(obj)\n })\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
publish to the team that the user has been added, and publish to the user that they've been added to the team | async publishAddToTeam (teamId) {
// get the team again since the team object has been modified,
// this should just fetch from the cache, not from the database
const team = await this.data.teams.getById(teamId);
await new AddTeamPublisher({
request: this,
broadcaster: this.api.services.broadcaster,
users: [this.transforms.createdUser],
team: team,
teamUpdate: this.transforms.teamUpdate,
userUpdates: this.transforms.userUpdates
}).publishAddedUsers();
} | [
"async publishPost () {\n\t\tif (!this.post.get('teamId')) { return; }\n\t\tawait new PostPublisher({\n\t\t\tdata: this.responseData,\n\t\t\trequest: this,\n\t\t\tbroadcaster: this.api.services.broadcaster,\n\t\t\tteamId: this.post.get('teamId')\n\t\t}).publishPost();\n\t}",
"publish() {\n if (Meteor.isServer) {\n // get the AppointmentCollection instance.\n const instance = this;\n /** This subscription publishes only the documents associated with the logged in user */\n Meteor.publish(appointmentPublications.appointment, function publish() {\n if (this.userId) {\n const username = Meteor.users.findOne(this.userId).username;\n return instance._collection.find({ owner: username });\n }\n return this.ready();\n });\n }\n }",
"addInterestedUser ({ commit, getters }, payload) {\n commit('setLoading', true)\n const user = getters.User\n const newInterestedPost = payload.id\n firebase\n .firestore()\n .collection('users')\n .doc(user.id)\n .update({\n interestedPosts: firebase.firestore.FieldValue.arrayUnion(newInterestedPost)\n })\n .then(() => {\n commit('updatePost', payload)\n commit('addInterestedUser', payload)\n })\n .catch(error => {\n alert(error)\n })\n firebase\n .firestore()\n .collection('posts')\n .doc(newInterestedPost)\n .update({\n interestedUsers: firebase\n .firestore\n .FieldValue\n .arrayUnion(user.id)\n })\n .then(() => {\n commit('setLoading', false)\n })\n .catch(error => {\n alert(error)\n })\n }",
"pushToFirebase() {\n // Create a user for the person who just made a team\n firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)\n .then((data) => {\n this.createUser(data.uid);\n })\n .catch((error) => {\n alert(error.message)\n })\n }",
"function subscriptionSucceeded(members) {\n console.log('Success!');\n // call addMember for each user already subscribed\n members.each(addMember);\n}",
"async afterAddMembers ({ groupId, newUserIds, reactivatedUserIds }) {\n const zapierTriggers = await ZapierTrigger.forTypeAndGroups('new_member', groupId).fetchAll()\n\n const members = await User.query(q => q.whereIn('id', newUserIds.concat(reactivatedUserIds))).fetchAll()\n\n if (zapierTriggers && zapierTriggers.length > 0) {\n const group = await Group.find(groupId)\n for (const trigger of zapierTriggers) {\n const response = await fetch(trigger.get('target_url'), {\n method: 'post',\n body: JSON.stringify(members.map(m => ({\n id: m.id,\n avatarUrl: m.get('avatar_url'),\n bio: m.get('bio'),\n contactEmail: m.get('contact_email'),\n contactPhone: m.get('contact_phone'),\n facebookUrl: m.get('facebook_url'),\n linkedinUrl: m.get('linkedin_url'),\n location: m.get('location'),\n name: m.get('name'),\n profileUrl: Frontend.Route.profile(m, group),\n tagline: m.get('tagline'),\n twitterName: m.get('twitter_name'),\n url: m.get('url'),\n // Whether this user was previously in the group and is being reactivated\n reactivated: reactivatedUserIds.includes(m.id),\n // Which group were they added to, since the trigger can be for multiple groups\n group: { id: group.id, name: group.get('name'), url: Frontend.Route.group(group) }\n }))),\n headers: { 'Content-Type': 'application/json' }\n })\n // TODO: what to do with the response? check if succeeded or not?\n }\n }\n\n for (const member of members) {\n mixpanel.track(AnalyticsEvents.GROUP_NEW_MEMBER, {\n distinct_id: member.id,\n groupId: [groupId]\n })\n }\n }",
"function mechanicsPublish() {\n\tnextTurn();\n}",
"givePermission() {\n const { id, userIdsWithPermission, documentCreatedBy } = this.state;\n userIdsWithPermission.map((userId) => {\n Meteor.call('upsertUserDocument', userId, id, documentCreatedBy, (error, result) => {\n if(error) {\n console.log(\"Fail to upsert the user\", error.reason);\n } else {\n console.log(\"Yay upserted successfully\");\n }\n });\n // TODO: Below setState not working properly\n // this.setState({\n // availableUsersForPermission: this.state.availableUsersForPermission\n // .filter( u => u._id !== userId)\n // })\n //TODO: Later, write a function to send emails to all permitted users.\n })\n }",
"function testPublishSupplement(){\n let _id = \"12345\";//Math.floor((Math.random() * 1000) + 1);\n let _args = ['{\"Owner\": \"studentEid\", \"University\":\"ntua\",\"Authorized\":[],\"Id\":\"'+_id+'\"}' ];\n let _enrollAttr = [{name:'typeOfUser',value:'University'},{name:\"eID\",value:\"ntua\"}];\n let _invAttr = ['typeOfUser','eID'];\n let req = {\n // Name (hash) required for invoke\n chaincodeID: basic.config.chaincodeID,\n // Function to trigger\n fcn: \"publish\",\n // Parameters for the invoke function\n args: _args,\n //pass explicit attributes to teh query\n attrs: _invAttr\n };\n basic.enrollAndRegisterUsers(\"ntuaTestUser\",_enrollAttr)\n .then(user => {\n basic.invoke(user,req).then(res=> {console.log(res);\n process.exit(0);\n }).catch(err =>{\n console.log(err);\n process.exit(1);\n });\n }).catch(err =>{\n console.log(err);\n });\n}",
"async publish(req, draft, options = {}) {\n const m = self.getManager(draft.type);\n return m.publish(req, draft, options);\n }",
"createMeetUp(state, payload) {\n state.loadedMeetUps.push(payload);\n }",
"function publish(user_message, attachment, action_links, target_id, user_message_prompt) {\n\t\t/*var attach = {\n\t\t\t\t'name':'Go grab your free bundle right now!',\n\t\t\t\t'href':'http://www.macheist.com/nano/facebook',\n\t\t\t\t'caption':'Download full copies of six top Mac apps normally costing over $150 totally for free at MacHeist!',\n\t\t\t\t'description':\"There’s something for everyone, whether you’re a gamer, a student, a writer, a twitter addict, or just love Mac apps. Plus as a Facebook user you can also get VirusBarrier X5 ($70) as a bonus. Don’t miss out!\",\n\t\t\t\t'media':[{'type':'image','src':'http://www.macheist.com/static/facebook/facebook_mh.png','href':'http://www.macheist.com/nano/facebook'}]\n\t\t\t}\n\t\t*/\t\n\t\t\n\t\tset_ready();\n\t\t\n\t\tFB.api({\n\t\t\t\tmethod: 'stream.publish', \n\t\t\t\tmessage: user_message, \n\t\t\t\tattachment: attachment, \n\t\t\t\taction_links: action_links, \n\t\t\t\ttarget_id: target_id\n\t\t\t}, function(result) {\n\t\t\t\ttrace(_s.PUBLISHED_POST);\n\n\t\t\t\ttrace(result); \n\n\t\t\t\tdispatchEvent(_s.PUBLISHED_POST, result);\n\t\t});\n\t}",
"async publish(draftLinks) {\n return this.apiClient.publishDraft(draftLinks);\n }",
"async sync() {\n // Update event on meetup if it is published and\n if (!this.draft && !this.internal) {\n if (this.meetupId) {\n // Update it on Meetup.com if it exists\n await meetup.update(this)\n } else {\n // Create on Meetup.com\n const id = await meetup.create(this)\n //this.save({ meetupId: id })\n }\n }\n }",
"function pushBusinessDev(projectId,businessDevelopment){\n Project.findById(projectId,function(err,proj){\n proj.businessDevelopment.push(businessDevelopment)\n proj.save();\n })\n}",
"function addUser(userInfo){\n const db = firebase.firestore()\n const usersCollection = db.collection('users')\n usersCollection.add({\n email: userInfo.email,\n name: userInfo.displayName,\n \n })\n .then(function(docRef){\n console.log(\"Document written with ID: \", docRef.id)\n\n })\n .catch(function(error){\n console.error(\"Error adding document: \", error)\n })\n}",
"inviteOtherUser (callback) {\n\t\tlet data = {\n\t\t\tteamId: this.team.id,\n\t\t\temail: this.userData[1].user.email\n\t\t};\n\t\tthis.apiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/users',\n\t\t\t\tdata,\n\t\t\t\ttoken: this.userData[0].accessToken\n\t\t\t},\n\t\t\tcallback\n\t\t);\n\t}",
"function createGame() {\n if(document.getElementById('opponent').value && document.getElementById('location').value &&\n document.getElementById('start-date').value && document.getElementById('start-time').value) {\n var email;\n firebase.auth().onAuthStateChanged(function(user) {\n if(user) {\n email = user.email.replace('.', '').replace('@', '');\n console.log(email);\n db.collection(\"users\").where(\"email\", \"==\", email).get().then(function(querySnapshot) {\n querySnapshot.forEach(function(doc) {\n var team = doc.data().team;\n console.log(doc.id);\n db.collection(\"teams\").doc(team).collection(\"schedule\").doc(document.getElementById('start-date').value +\n \" \" + document.getElementById('opponent').value).set({\n title: document.getElementById('opponent').value,\n location: document.getElementById('location').value,\n startDate: document.getElementById('start-date').value,\n startTime: document.getElementById('start-time').value,\n eventType: 'game'\n }).then(function(result) {\n window.location = \"schedule-admin.html\";\n return false;\n });\n });\n });\n }\n });\n }\n else {\n document.getElementById(\"warning\").innerHTML = \"Please fill out all event information!\";\n return false;\n }\n}",
"createThought({ body }, res) {\n Thought.create(body)\n .then(({ _id }) => {\n return User.findOneAndUpdate(\n { _id: body.userId },\n { $push: { thoughts: _id } },\n { new: true }\n );\n })\n .then(thoughtData => {\n if (!thoughtData) {\n res.status(404).json({ message: 'No thought found with that ID.' });\n return;\n }\n res.json({ message: 'Your thought was posted!', thoughtData });\n })\n .catch(err => res.status(400).json(err));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`fail` is a general way to quit when a fatal error has occurred. If `exitFn` hasn't been set, it will simply do a `process.exit`. | function fail(errcode) {
if (typeof(errcode) === 'undefined') {
errcode = 1;
}
if (exitFn) {
exitFn(errcode);
} else {
process.exit(errcode);
}
return null;
} | [
"function failure() {\n process.exit(ExitCode.Failure);\n}",
"function failedTestFn() {\n throw new Error('test failed');\n }",
"function exit(message, code = 1) {\n if (code === 0) {\n log(message);\n }\n else {\n error(message);\n }\n process.exit(code);\n}",
"function exit(msg, code = 0) {\n console.log(msg); // eslint-disable-line no-console\n process.exit(code);\n}",
"function errorMessage(){\n console.log(\"Exiting the game.\")\n process.exit();\n}",
"function onExit(done) {\n done();\n}",
"function success() {\n process.exit(ExitCode.Success);\n}",
"function karmaExit(exitCode) {\n plugins.util.log('Karma has exited with ' + exitCode);\n\n // do not kill process when watching\n if (!watching) {\n process.exit(exitCode);\n }\n}",
"_onError(target, event, fatal = false) {\n const message = fatal ?\n 'The Rollup build can\\'t be created' :\n 'There was a problem while creating the Rollup build';\n this.appLogger.error(message);\n if (event.error) {\n this.appLogger.error(event.error);\n }\n if (fatal) {\n process.exit(1);\n }\n }",
"exitTryExpression(ctx) {\n\t}",
"function nodeCB(code, stdout, stderr, cb) {\n if (code !== 0) {\n console.log('Program stderr:', stderr);\n shell.exit(1);\n } else {\n cb();\n }\n}",
"function failTest(reason) {\n addTestFailure(reason);\n throw new Error(reason);\n}",
"function fail() {\n putstr(padding_left(\" FAILED\", seperator, sndWidth));\n putstr(\"\\n\");\n }",
"async exit(command, error) {\n if (command !== this.entryCommand) {\n return;\n }\n await this.exitProcess(error);\n }",
"_onJobFailure(...args) {\n const onJobFailure = this.options.onJobFailure;\n if (isFunction(onJobFailure)) {\n onJobFailure(...args);\n } else if (!this.options.mute) {\n this.log.error('');\n this.log.error('--------------- RDB JOB ERROR/FAILURE ---------------');\n this.log.error(`Job: ${args[0].options.runs}` || args[0].queue);\n args[1].stack = args[2].join('\\n');\n this.log.error(args[1]);\n this.log.error('------------------------------------------------------');\n this.log.error('');\n }\n }",
"function envErr(){\n if (process.env.NODE_ENV === \"production\"){\n let message = \"Error: Set env var(s)\";\n\n for(let arg of arguments){\n message += \" '\" + arg + \"'\"\n }\n\n console.error(message);\n process.exit(1);\n }\n}",
"function envErr(){\n if (process.env.NODE_ENV === \"production\"){\n let message = \"Error: Set env var(s)\";\n\n for(let arg of arguments){\n message += \" '\" + arg + \"'\"\n }\n\n console.error(message);\n process.exit(1);\n }\n }",
"function exit() {\n\tsetTimeout(function() {\n\t\tphantom.exit();\n\t}, 0);\n}",
"exitExceptionType(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Preconditions: this._multiCanvas must have been set | _resetMultiCanvas() {
const numFrames = parseFloat(this._range.getAttribute("max"));
for (const data of this._multiCanvas) {
data.context.clearRect(0, 0, data.canvas.width, data.canvas.height);
data.canvas.setAttribute("width", this._canvasWidth);
data.canvas.setAttribute("height", 1);
data.canvas.style.height=`${3*1}px`;
data.canvasFactor = this._canvasWidth/numFrames;
}
} | [
"initCanvas() {\n // Create new canvas object.\n this._canvasContainer = document.getElementById(this._canvasId);\n if (!this._canvasContainer)\n throw new Error(`Canvas \"${this._canvasId}\" not found`);\n // Get rendering context.\n this._canvas = this._canvasContainer.getContext('2d');\n // Register canvas interaction event handlers.\n this._canvasContainer.addEventListener('mousedown', (event) => this.canvasMouseDown(event));\n this._canvasContainer.addEventListener('mouseup', (event) => this.canvasMouseUp(event));\n this._canvasContainer.addEventListener('mousemove', (event) => this.canvasMouseMove(event));\n this._canvasContainer.addEventListener('wheel', (event) => this.canvasScrollWheel(event));\n // Get width and height of canvas.\n this._canvasWidth = this._canvasContainer.width;\n this._canvasHeight = this._canvasContainer.height;\n }",
"function load_canvas() {\n var canvases = $('canvas');\n active_canvas = null;\n for(var i = 0; i < canvases.length; i++){\n if(canvases.eq(i).is(':visible')){\n active_canvas = canvases[i];\n break;\n }\n }\n}",
"animationFrame() {\n\t\t\tvar canvases = this._getCanvases();\n\t\t\tif(!canvases.length) {\n\t\t\t\t// No canvas to draw onto, do nothing\n\t\t\t\tif(this.warnIfNoElement) console.warn(\"No dw-paint element found for root \"+this.name+\".\");\n\t\t\t\tthis.warnIfNoElement = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tif(this._mmQueued) {\n\t\t\t\tthis.mouseX = this._mmQueued.x;\n\t\t\t\tthis.mouseY = this._mmQueued.y;\n\t\t\t\t\n\t\t\t\t// Components may change this, so reset it every frame\n\t\t\t\tmouse.cursor = \"initial\";\n\t\t\t\t\n\t\t\t\tGroup.prototype.interact.call(this, this._mmQueued);\n\t\t\t\tthis._mmQueued = null;\n\t\t\t}\n\t\t\t\n\t\t\tfor(var i = 0; i < canvases.length; i ++) {\n\t\t\t\tvar canvas = canvases[i];\n\t\t\t\t\n\t\t\t\tif(!this.noCleanCanvas) {\n\t\t\t\t\tcanvas.getContext(\"2d\").clearRect(0, 0, canvas.width, canvas.height);\n\t\t\t\t\tif(!this.noCacheCanvas)\n\t\t\t\t\t\tthis._cacheCanvases[i].getContext(\"2d\").clearRect(0, 0, canvas.width, canvas.height);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(this.noCacheCanvas) {\n\t\t\t\t\tthis.paint(canvas.getContext(\"2d\"), 0, 0, canvas.width, canvas.height);\n\t\t\t\t}else{\n\t\t\t\t\tthis.paint(this._cacheCanvases[i].getContext(\"2d\"), 0, 0, canvas.width, canvas.height);\n\t\t\t\t\tcanvas.getContext(\"2d\").drawImage(this._cacheCanvases[i], 0, 0, canvas.width, canvas.height);\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"setupCanvas(canvas){\n this.canvas.loadFromJSON(canvas, () => {\n this.canvas.renderAll(); \n });\n }",
"openCanvas() {\n this.g = this.canvas.getContext('2d');\n if (this.g == null)\n return false;\n\n // disable antialiasing\n this.g.imageSmoothingEnabled = false;\n this.g.mozImageSmoothingEnabled = false;\n this.g.webkitImageSmoothingEnabled = false;\n\n this.deferredFaceCount = 0;\n this.deferredFaces = [];\n this.mvVertexArray = new J3DIMath.J3DIVertexArray();\n this.mvpVertexArray = new J3DIMath.J3DIVertexArray();\n\n this.initScene();\n if (this.initCallback != null) {\n this.initCallback(this);\n }\n\n this.draw();\n return true;\n }",
"cloneCanvas ()\n {\n let maxZoomLevel = this.pixelInstance.core.getSettings().maxZoomLevel;\n\n let height = this.pixelInstance.core.publicInstance.getPageDimensionsAtZoomLevel(this.pageIndex, maxZoomLevel).height,\n width = this.pixelInstance.core.publicInstance.getPageDimensionsAtZoomLevel(this.pageIndex, maxZoomLevel).width;\n\n this.canvas = document.createElement('canvas');\n this.canvas.setAttribute(\"class\", \"pixel-canvas\");\n this.canvas.setAttribute(\"id\", \"layer-\" + this.layerId + \"-canvas\");\n this.canvas.width = width;\n this.canvas.height = height;\n\n this.ctx = this.canvas.getContext('2d');\n\n this.resizeLayerCanvasToZoomLevel(this.pixelInstance.core.getSettings().zoomLevel);\n this.placeLayerCanvasOnTopOfEditingPage();\n\n this.backgroundImageCanvas = document.createElement(\"canvas\");\n this.backgroundImageCanvas.width = this.canvas.width;\n this.backgroundImageCanvas.height = this.canvas.height;\n }",
"function modelSelect() {\n\n var background = document.getElementById(\"background\"); // Keep background canvas\n\n var photo = document.getElementById(\"photo\");\n while (photo.firstChild) { // Remove all child canvases\n photo.removeChild(photo.firstChild);\n }\n photo.appendChild(background); // Attach background canvas back\n\n var selectedModel = document.getElementById(\"modelSelect\").value; // Get the selected model value\n\n\n var canvasRef = document.getElementById(\"background\");\n let clientWidth = canvasRef.clientWidth;\n let clientHeight = canvasRef.clientHeight;\n\n switch (selectedModel) {\n\n case \"model1\":\n\n clientWidthRef = (canvasRef.clientWidth / 100) * 45;\n clientHeightRef = (canvasRef.clientHeight / 100) * 82;\n\n var layer1 = document.createElement('canvas');\n layer1.className = \"layer\";\n layer1.width = clientWidthRef;\n layer1.height = clientHeightRef;\n layer1.style.top = \"15px\";\n layer1.style.left = \"30px\";\n layer1.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer1);\n registerEvents(layer1);\n\n var layer2 = document.createElement('canvas');\n layer2.className = \"layer\";\n layer2.width = clientWidthRef;\n layer2.height = clientHeightRef;\n layer2.style.top = \"15px\";\n layer2.style.left = (clientWidthRef + 30 * 2) + \"px\";\n layer2.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer2);\n registerEvents(layer2);\n\n break;\n\n case \"model2\":\n\n clientWidthRef = (canvasRef.clientWidth / 100) * 28;\n clientHeightRef = (canvasRef.clientHeight / 100) * 82;\n\n var layer1 = document.createElement('canvas');\n layer1.className = \"layer\";\n layer1.width = clientWidthRef;\n layer1.height = clientHeightRef;\n layer1.style.top = \"15px\";\n layer1.style.left = \"35px\";\n layer1.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer1);\n registerEvents(layer1);\n\n var layer2 = document.createElement('canvas');\n layer2.className = \"layer\";\n layer2.width = clientWidthRef;\n layer2.height = clientHeightRef;\n layer2.style.top = \"15px\";\n layer2.style.left = (clientWidthRef + 35 * 2) + \"px\";\n layer2.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer2);\n registerEvents(layer2);\n\n var layer3 = document.createElement('canvas');\n layer3.className = \"layer\";\n layer3.width = clientWidthRef;\n layer3.height = clientHeightRef;\n layer3.style.top = \"15px\";\n layer3.style.left = (clientWidthRef * 2 + 35 * 3) + \"px\";\n layer3.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer3);\n registerEvents(layer3);\n\n break;\n\n case \"model3\":\n\n clientWidthRef = (canvasRef.clientWidth / 100) * 45;\n clientHeightRef = (canvasRef.clientHeight / 100) * 38;\n\n var layer1 = document.createElement('canvas');\n layer1.className = \"layer\";\n layer1.width = clientWidthRef;\n layer1.height = clientHeightRef;\n layer1.style.top = \"15px\";\n layer1.style.left = \"30px\";\n layer1.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer1);\n registerEvents(layer1);\n\n var layer2 = document.createElement('canvas');\n layer2.className = \"layer\";\n layer2.width = clientWidthRef;\n layer2.height = clientHeightRef;\n layer2.style.top = \"15px\";\n layer2.style.left = (clientWidthRef + 30 * 2) + \"px\";\n layer2.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer2);\n registerEvents(layer2);\n\n var layer3 = document.createElement('canvas');\n layer3.className = \"layer\";\n layer3.width = clientWidthRef;\n layer3.height = clientHeightRef;\n layer3.style.top = (clientHeightRef + 15 * 2) + \"px\";\n layer3.style.left = \"30px\";\n layer3.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer3);\n registerEvents(layer3);\n\n var layer4 = document.createElement('canvas');\n layer4.className = \"layer\";\n layer4.width = clientWidthRef;\n layer4.height = clientHeightRef;\n layer4.style.top = (clientHeightRef + 15 * 2) + \"px\";\n layer4.style.left = (clientWidthRef + 30 * 2) + \"px\";\n layer4.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer4);\n registerEvents(layer4);\n\n break;\n\n case \"model4\":\n\n clientWidthRef = (canvasRef.clientWidth / 100) * 28.5;\n clientHeightRef = (canvasRef.clientHeight / 100) * 38;\n\n var layer1 = document.createElement('canvas');\n layer1.className = \"layer\";\n layer1.width = clientWidthRef;\n layer1.height = clientHeightRef;\n layer1.style.top = \"15px\";\n layer1.style.left = \"30px\";\n layer1.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer1);\n registerEvents(layer1);\n\n var layer2 = document.createElement('canvas');\n layer2.className = \"layer\";\n layer2.width = clientWidthRef;\n layer2.height = clientHeightRef;\n layer2.style.top = \"15px\";\n layer2.style.left = (clientWidthRef + 30 * 2) + \"px\";\n layer2.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer2);\n registerEvents(layer2);\n\n var layer3 = document.createElement('canvas');\n layer3.className = \"layer\";\n layer3.width = clientWidthRef;\n layer3.height = clientHeightRef;\n layer3.style.top = \"15px\";\n layer3.style.left = (clientWidthRef * 2 + 30 * 3) + \"px\";\n layer3.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer3);\n registerEvents(layer3);\n\n var layer4 = document.createElement('canvas');\n layer4.className = \"layer\";\n layer4.width = clientWidthRef;\n layer4.height = clientHeightRef;\n layer4.style.top = (clientHeightRef + 15 * 2) + \"px\";\n layer4.style.left = \"30px\";\n layer4.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer4);\n registerEvents(layer4);\n\n var layer5 = document.createElement('canvas');\n layer5.className = \"layer\";\n layer5.width = clientWidthRef;\n layer5.height = clientHeightRef;\n layer5.style.top = (clientHeightRef + 15 * 2) + \"px\";\n layer5.style.left = (clientWidthRef + 30 * 2) + \"px\";\n layer5.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer5);\n registerEvents(layer5);\n\n var layer6 = document.createElement('canvas');\n layer6.className = \"layer\";\n layer6.width = clientWidthRef;\n layer6.height = clientHeightRef;\n layer6.style.top = (clientHeightRef + 15 * 2) + \"px\";\n layer6.style.left = (clientWidthRef * 2 + 30 * 3) + \"px\";\n layer6.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer6);\n registerEvents(layer6);\n\n break;\n\n case \"model5\":\n\n clientWidthRef = (canvasRef.clientWidth / 100) * 20;\n clientHeightRef = (canvasRef.clientHeight / 100) * 38;\n\n var centerWidth = ( canvasRef.clientWidth - (clientWidthRef * 2 )) - 70;\n var centerHeight = (canvasRef.clientHeight / 100) * 82;\n\n var layer1 = document.createElement('canvas');\n layer1.className = \"layer\";\n layer1.width = clientWidthRef;\n layer1.height = clientHeightRef;\n layer1.style.top = \"15px\";\n layer1.style.left = \"30px\";\n layer1.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer1);\n registerEvents(layer1);\n\n var layer2 = document.createElement('canvas');\n layer2.className = \"layer\";\n layer2.width = clientWidthRef;\n layer2.height = clientHeightRef;\n layer2.style.top = (clientHeightRef + 15 * 2) + \"px\";\n layer2.style.left = \"30px\";\n layer2.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer2);\n registerEvents(layer2);\n\n\n var layer3 = document.createElement('canvas');\n layer3.className = \"layer\";\n layer3.width = centerWidth;\n layer3.height = centerHeight;\n layer3.style.top = \"16px\";\n layer3.style.left = (clientWidthRef + 42) + \"px\";\n layer3.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer3);\n registerEvents(layer3);\n\n var layer4 = document.createElement('canvas');\n layer4.className = \"layer\";\n layer4.width = clientWidthRef;\n layer4.height = clientHeightRef;\n layer4.style.top = \"15px\";\n layer4.style.left = (clientWidthRef + centerWidth + 55) + \"px\";\n layer4.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer4);\n registerEvents(layer4);\n\n var layer5 = document.createElement('canvas');\n layer5.className = \"layer\";\n layer5.width = clientWidthRef;\n layer5.height = clientHeightRef;\n layer5.style.top = (clientHeightRef + 15 * 2) + \"px\";\n layer5.style.left = (clientWidthRef + centerWidth + 55) + \"px\";\n layer5.style.visibility = \"visible\";\n\n var body = document.getElementById(\"photo\");\n body.appendChild(layer5);\n registerEvents(layer5);\n\n break;\n\n default:\n document.getElementById(\"background\").style.visibility = \"hidden\"; // Hide canvas until model is selected\n }\n}",
"bindElements(canvasEl) {\n this.canvas = new MainCanvas(canvasEl);\n }",
"addCanvases(waveCanvas) {\n this.wave_canvas = waveCanvas;\n this.miniWave_wrapper.appendChild(waveCanvas.mainWave_canvas);\n this.setCanvasStyles()\n }",
"function changeCanvasSize(){ \n\tcanvasSize = canvasSelector.value();\n\tif(canvasSize == 2){\n\t\tmain_canvas = resizeCanvas(1920, 1000);\n\t}\n\telse if(canvasSize == 3){\n\t\tmain_canvas = resizeCanvas(2880, 1500);\n\t}\n\telse {\n\t\tmain_canvas = resizeCanvas(960, 500);\n\t}\n\tclear();\n\tbackground(0);\n\tredraw();\n}",
"buildCanvas(){\r\n $(this.parent).append($(`\r\n <canvas id=\"mobcanvas\">\r\n <p>Désolé, votre navigateur ne supporte pas Canvas. Mettez-vous à jour</p>\r\n </canvas>\r\n `));\r\n }",
"#runDrawCallbacks() {\n let dont_clear = false;\n if (this.#clear) { this.#context.clearRect(0, 0, this.#canvas.width, this.#canvas.height); }\n this.#context.translate(0.5, 0.5);\n this.#drawables.forEach(drawable => {\n dont_clear = drawable.draw(this.#context, this.#canvas.width, this.#canvas.height, this.#canvas, this.#clear) || dont_clear;\n });\n this.#context.translate(-0.5, -0.5);\n this.#clear = !dont_clear;\n }",
"function CharacterLoadCanvasAll() {\n\tfor (var C = 0; C < Character.length; C++)\n\t\tCharacterLoadCanvas(Character[C]);\n}",
"function selectAllObj(){\n console.log(\"select all\");\n var canvas = getCanvasAux();\n var context = canvas.getContext('2d');\n var colorSelected = \"red\"\n var totalPoints = []\n\n for (var i=0; i<canvas_obj['points'].length; i++){\n canvas_obj['points'][i].isSelected(true);\n totalPoints.push(canvas_obj['points'][i]);\n }\n for (var i=0; i<canvas_obj['lines'].length; i++){\n canvas_obj['lines'][i].isSelected(true);\n totalPoints.push(canvas_obj['lines'][i].p1);\n totalPoints.push(canvas_obj['lines'][i].p2);\n }\n for (var i=0; i<canvas_obj['polylines'].length; i++){\n canvas_obj['polylines'][i].isSelected(true);\n for(var j=0; j<canvas_obj['polylines'][i].arrayPoints.length; j++){\n totalPoints.push(canvas_obj['polylines'][i].arrayPoints[j])\n }\n }\n for (var i=0; i<canvas_obj['polygons'].length; i++){\n canvas_obj['polygons'][i].isSelected(true);\n for(var j=0; j<canvas_obj['polygons'][i].arrayPoints.length; j++){\n totalPoints.push(canvas_obj['polygons'][i].arrayPoints[j])\n }\n }\n\n allPoints = totalPoints;\n reloadCanvas(refresh=true);\n}",
"onResetCanvas(width, height) {\n if (this.canvas) {\n this.canvas.reset(width, height);\n }\n }",
"closeCanvas() {\n // empty\n }",
"function drawSelections() {\n\t\tif(selectionCanvas === null) {\n\t\t\tvar selectionCanvasElement = $scope.theView.parent().find('#theSelectionCanvas');\n\t\t\tif(selectionCanvasElement.length > 0) {\n\t\t\t\tselectionCanvas = selectionCanvasElement[0];\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//$log.log(preDebugMsg + \"no canvas to draw selections on!\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif(selectionCtx === null) {\n\t\t\tselectionCtx = selectionCanvas.getContext(\"2d\");\n\t\t}\n\n\t\tvar W = selectionCanvas.width;\n\t\tvar H = selectionCanvas.height;\n\n\t\tselectionCtx.clearRect(0,0, W,H);\n\n\t\tif(selectionColors === null) {\n\t\t\tparseSelectionColors(W, H);\n\t\t}\n\n\t\tfor(sel = 0; sel < selections.length; sel++) {\n\t\t\tselectionCtx.fillStyle = selectionColors.grad;\n\t\t\tselectionCtx.fillRect(selections[sel][2], topMarg-2, selections[sel][3] - selections[sel][2], drawH+4);\n\n\t\t\tselectionCtx.fillStyle = selectionColors.border;\n\t\t\tselectionCtx.fillRect(selections[sel][2], topMarg-2, 1, drawH+4);\n\t\t\tselectionCtx.fillRect(selections[sel][2], topMarg-2, selections[sel][3] - selections[sel][2], 1);\n\t\t\tselectionCtx.fillRect(selections[sel][2], topMarg+2 + drawH, selections[sel][3] - selections[sel][2], 1);\n\t\t\tselectionCtx.fillRect(selections[sel][3]-1, topMarg-2, 1, drawH+4);\n\t\t}\n\t\thideSelectionRect();\n\t}",
"function clearCanvas() {\n elements.gridCanvas.innerHTML = '';\n }",
"updateCanvasInfo() {\n const canvas = this.canvas;\n canvas.element = ReactDOM.findDOMNode(canvas.ref.current);\n const computedStyle = window.getComputedStyle(canvas.element);\n canvas.computedWidth = parseFloat(computedStyle.width);\n canvas.computedHeight = parseFloat(computedStyle.height);\n canvas.boundingClientRect = canvas.element.getBoundingClientRect();\n return this;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION: setParameter DESCRIPTION: set userdefined property in parameter object. Preserves original parameter object if performed on editable instance. See makeEditableCopy(). ARGUMENTS: name property name string value property value RETURNS: none | function ServerBehavior_setParameter(name, value)
{
if (this.bInEditMode)
{
this.applyParameters[name] = value;
}
else
{
this.parameters[name] = value;
}
} | [
"function Parameter(parent, name, param, mval, bval) {\n this.getClass = function() { return \"Parameter\" };\n this.parent = parent;\n this.name = name;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ime parametra v bazi \n this.param = param;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// stevilka parametra v bazi\n this.mval = parseInt(mval);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// oznaka za manjkajoco vrednost v bazi\n this.bval = (bval == null)? parseInt(mval) : parseInt(bval);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// vrednost parametra v baz zo. manjkajoca vrednost\n this.msr = isParamMeasured(this.parent.parent.postaje, this.parent.parent.parametri, this.param, this.parent.idmm, this.parent.datum); \t// ali se parameter meri\n this.edit = setEdit; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ali se parameter lahko editira\t\n this.val = (this.bval != this.mval)? new Number(this.bval) : null;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// vrednost parametra\t\n this.toXml = param2xml;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// transformacija v xml element \t\t\t\t\t\t\t\t\t\t\t\t\n this.nval; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// nova vrednost parametra\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n this.oval = this.val;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// stara vrednost parametra\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n this.isChanged = isValueChanged;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ali se je vrednost spremenila\n this.nval2bval = nval2bvalParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// izracun vrednosti za vnos v bazo\n this.correct = correctParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// popravek parametra\t\t\n this.generateErrorsSearch = generateErrorsSearchParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// funkcije za izvajanje kontrol\n this.generateErrorsBehavior = generateErrorsBehaviorParam;\n this.setNewVal = setNewValueParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// dolocanje nove vrednosti\n this.setOldVal = setOldValueParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// dolocanje stare vrednosti\n}",
"function setConfigParam(paramName, paramValue) {\n var configParams = jQuery(document).data(\"ConfigParameters\");\n if (!configParams) {\n configParams = new Object();\n jQuery(document).data(\"ConfigParameters\", configParams);\n }\n configParams[paramName] = paramValue;\n}",
"function ServerBehavior_setParameters(mapNameToVals)\n{\n if (this.bInEditMode)\n {\n this.applyParameters = mapNameToVals;\n }\n else\n {\n this.parameters = mapNameToVals;\n }\n}",
"function Parameter(props) {\n return __assign({ Type: 'AWS::SSM::Parameter' }, props);\n }",
"function ServerBehavior_handleParamChange(varName, oldVal, newVal)\n{\n if (this.bInEditMode)\n {\n return newVal;\n }\n else \n {\n // Localization *not* required. JS Developer debugging error string.\n throw \"Attempt to assign read-only property: \" + varName;\n }\n return oldVal; \n}",
"function setProperty(node, name, value) {\n \ttry {\n \t\tnode[name] = value;\n \t} catch (e) {}\n }",
"function setValue(param, value) {\n if (lmsConnected) {\n DEBUG.LOG(`setting ${param} to ${value}`);\n scorm.set(param, value);\n scorm.save();\n } else {\n DEBUG.WARN('LMS NOT CONNECTED');\n }\n}",
"function setattr( obj, name, value )\n { obj[name] = value; }",
"function setupCustomParameters(modelParameters, interactiveParameters) {\n if (!modelParameters && !interactiveParameters) return;\n var initialValues = {},\n customParameters,\n i,\n parameter,\n onChangeFunc; // append modelParameters second so they're processed later (and override entries of the\n // same name in interactiveParameters)\n\n customParameters = (interactiveParameters || []).concat(modelParameters || []);\n\n for (i = 0; i < customParameters.length; i++) {\n parameter = customParameters[i]; // onChange callback is optional.\n\n onChangeFunc = undefined;\n\n if (parameter.onChange) {\n onChangeFunc = scriptingAPI.makeFunctionInScriptContext('value', getStringFromArray(parameter.onChange));\n } // Define parameter using modeler.\n\n\n model.defineParameter(parameter.name, {\n label: parameter.label,\n unitType: parameter.unitType,\n unitName: parameter.unitName,\n unitPluralName: parameter.unitPluralName,\n unitAbbreviation: parameter.unitAbbreviation\n }, onChangeFunc);\n\n if (parameter.initialValue !== undefined) {\n // Deep copy of the initial value. Otherwise, if initial value is an object or array,\n // all updates to parameter value will be shared with its initial value.\n initialValues[parameter.name] = interactives_controller_clone(parameter.initialValue);\n }\n }\n\n model.set(initialValues);\n }",
"set(propObj, value) {\n propObj[this.id] = value;\n return propObj;\n }",
"set CustomProvidedInput(value) {}",
"function ParameterKliVidnost(parent, name, id, mval, bval) {\n Parameter.apply(this, [parent, name, id, mval, bval]);\n this.values = [0,1,2,3,4,5,6,7,8,9];\n}",
"function setProperty(propertyName, propertyValue)\r\n{\r\n loadSettingsDb();\r\n db.transaction(function(tx) {\r\n tx.executeSql(\"INSERT OR REPLACE INTO EasyListApp (property, value) VALUES (?,?)\", [propertyName, propertyValue]);\r\n });\r\n}",
"function mirrorParams2(){\n\n var endDate = prepsParam.EndDate;\n var firstDate = prepsParam.FirstDate;\n var isBqPerf = prepsParam.IsBqPerf;\n var Kpi = prepsParam.Kpi;\n \n if(app.pages.MyPreps.descendants.DropdownAgent.value !== null){\n \n var agent = app.pages.MyPreps.descendants.DropdownAgent.value.Name; \n app.datasources.PrepsByDate.query.parameters.AgentName = agent;\n console.log(agent);\n \n \n // Assigns supervisor parameter\n \n var sup = app.datasources.MeDatasource.item.Name;\n prepsParam.Supervisor = sup;\n console.log(sup);\n \n }\n \n app.datasources.PrepsByDate.query.parameters.EndDate = endDate;\n app.datasources.PrepsByDate.query.parameters.FirstDate = firstDate;\n app.datasources.PrepsByDate.query.parameters.IsBqPerf = isBqPerf;\n app.datasources.PrepsByDate.query.parameters.Kpi = Kpi;\n\n}",
"function ParameterKliStanjeTal(parent, name, id, mval, bval) {\n Parameter.apply(this, [parent, name, id, mval, bval]);\n this.values = [0,1,2,3,4,5,6,7,8,9];\n}",
"prop(propertyName, propertyValue) {\n\t\t\tif (typeof propertyValue === \"undefined\") {\n\t\t\t\treturn this.preset[propertyName];\n\t\t\t} else {\n\t\t\t\tthis.preset[propertyName] = propertyValue;\n\t\t\t\treturn this;\n\t\t\t}\n\t\t}",
"addProperty(property, value) {\n this.properties.set(property, value);\n }",
"createProperty(obj, name, value, post = null, priority = 0, transform = null, isPoly = false) {\n obj['__' + name] = {\n value,\n isProperty: true,\n sequencers: [],\n tidals: [],\n mods: [],\n name,\n type: obj.type,\n __owner: obj,\n\n fade(from = 0, to = 1, time = 4, delay = 0) {\n Gibber[obj.type].createFade(from, to, time, obj, name, delay);\n return obj;\n }\n\n };\n Gibber.addSequencing(obj, name, priority, value, '__');\n Object.defineProperty(obj, name, {\n configurable: true,\n get: Gibber[obj.type].createGetter(obj, name),\n set: Gibber[obj.type].createSetter(obj, name, post, transform, isPoly)\n });\n }",
"function ServerBehavior_getParameter(name)\n{\n var paramVal = null;\n var undefined; // Use to compare against 'undefined' type\n \n // Note: be careful about when we use the old parameter value. We only want do this\n // if the new version of the parameter is undefined. We may have assigned the\n // new version of the parameter to null, so we must check for '!== undefined'.\n if (this.bInEditMode && this.applyParameters && this.applyParameters[name] !== undefined)\n {\n paramVal = this.applyParameters[name];\n }\n else if (this.parameters[name] !== undefined)\n {\n paramVal = this.parameters[name];\n }\n return paramVal;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called if the user implicitly/explitly modifies the current shared ontologies | function _sharedOntologiesUpdated(newSharedOntologyIds, oldSharedOntologyIds) {
//console.debug("_sharedOntologiesUpdated::", newSharedOntologyIds);
var invalidIntegrationColumns = self.getIntegrationColumns().filter(function(column) {
return newSharedOntologyIds.indexOf(column.ontologyId) === -1;
});
} | [
"handleApproachChanged() {\n if (this.currentApproachName.startsWith('RN')) {\n this.approachMode = WT_ApproachType.RNAV;\n if (this.currentLateralActiveState === LateralNavModeState.APPR) {\n this.isVNAVOn = true;\n }\n \n if (this.currentVerticalActiveState === VerticalNavModeState.GS) {\n this.currentVerticalActiveState = VerticalNavModeState.GP;\n }\n\n if (this.currentVerticalArmedStates.includes(VerticalNavModeState.GS)) {\n this.currentVerticalArmedStates = [VerticalNavModeState.GP];\n }\n }\n\n if (this.currentApproachName.startsWith('ILS') || this.currentApproachName.startsWith('LDA')) {\n this.approachMode = WT_ApproachType.ILS;\n if (this.currentLateralActiveState === LateralNavModeState.APPR) {\n this.isVNAVOn = false;\n }\n\n if (this.currentVerticalActiveState === VerticalNavModeState.GP) {\n this.currentVerticalActiveState = VerticalNavModeState.GS;\n }\n\n if (this.currentVerticalArmedStates.includes(VerticalNavModeState.GP)) {\n this.currentVerticalArmedStates = [VerticalNavModeState.GS];\n }\n }\n }",
"function isModified() {\n\tif (is_modified)\n\t\tif (!confirm('Data on this page has been modified.\\nIf you proceed, changes wont\\'t be saved.\\nProceed anyway?'))\n\t\t\treturn false;\n\treturn true;\n}",
"function ontoggle() {\n selected = !selected;\n logic.ontoggle(selected);\n }",
"function SetAnyChangeToTrue()\t\n\t\t{\n\t\t\t//Change has taken place\n\t\t\tanyChange = 1;\n\t\t}",
"function set_share (value)\n {\n share = value;\n modify();\n }",
"function editorStoryAccessibleChange(element) {\n loadedStory.accessible = element.checked;\n editorDirty = true;\n}",
"function dublincoreChangeState() {\n\tvar tbutton = document.getElementById(\"dublincore-toolbarbutton\");\n\tvar sbutton = document.getElementById(\"dublincore-statusbarbutton\");\n\tif (tbutton) tbutton.disabled = true;\n\tsbutton.disabled = true;\n\t\n\t// quick check of metas\n\tvar metas = window.content.document.getElementsByTagName(\"meta\");\n\tvar links = window.content.document.getElementsByTagName(\"link\");\n\n\tif ((dc_crawler(metas,'name','content',dcElements,'dc.')) ||\n\t\t(dc_crawler(metas,'name','content',dcElementTerms,'dcterms.')) ||\n\t\t(dc_crawler(links,'rel','href',dcElements,'dc.')) ||\n\t\t(dc_crawler(links,'rel','href',dcElementTerms,'dcterms.'))) {\n\n\t\tif (tbutton) tbutton.disabled = false;\n\t\tsbutton.disabled = false;\n\n\t}\n}",
"function Activate_Master_Rep (model)\n{\n rep_stat=document.wm.pwlSimprepMasterActivate(model);\n}",
"toggleAddByDefault(){\n this.add_new_robot = !this.add_new_robot;\n }",
"updateActionStates() {\n ssui.originalUpdateActionStatesFunc.call(this);\n \tlet graph = this.editor.graph;\n this.actions.get('group').setEnabled(graph.getSelectionCount() >= 1);\n }",
"function MEX_Save() {\n if (mod_MEX_dict.is_permit_admin){\n MEXQ_Save();\n }\n } // MEX_Save",
"updateSketchDetails() {\n if(this.refs.child){\n this.refs.child.getAlert();\n }\n \n this.props.component.setActiveStatus(this.props.component.state.treedata);\n let savedVocabulary;\n let userDetails = JSON.parse(sessionStorage.getItem('userInfo'));\n let VocabularyStored = sessionStorage.getItem('vocabularyInfo')\n if (VocabularyStored) {\n savedVocabulary = JSON.parse(VocabularyStored);\n } else {\n savedVocabulary = []\n }\n\n updateSketch(this.props.component, savedVocabulary, ProjectService, browserHistory)\n }",
"function toggleShapes(){\n\tif (shapesOn) {\n\t\tshapesOn = false;\n\t} else {\n\t\tshapesOn = true;\n\t}\n}",
"function toggleHints(){\r\n\tif (GameStateScript.HintsOn()){\r\n\t\tGameStateScript.setHints(false);\r\n\t}else{\r\n\t\tGameStateScript.setHints(true);\r\n\t}\r\n}",
"function switchTool(event){\n var toolToEquip = event.target.getAttribute(\"data-tooltype\");\n workspace.activeTool = toolToEquip;\n}",
"function handleModifiedEvent(event) {\n setModified(true);\n}",
"_onApplyingUpdate(view, metadata) {\n if (view && _.isFunction(view.beforeApplyUpdate)) {\n view.beforeApplyUpdate(metadata);\n }\n }",
"startEditing() {\n if (this.editing) return;\n\n // Force the layer to be visible.\n if (!this.meanlines.on) {\n this.SeismogramMap.toggleLayer(this.meanlines);\n }\n\n this.meanlines.leafletLayer.getLayers().forEach((meanline) => {\n // We install the editing events on each mean line\n this.installEventsOnMeanline(meanline);\n // Turn on Leaflet.Editable on the mean line\n meanline.enableEdit();\n });\n\n this.editing = true;\n }",
"function systemOn (req, res) {\n\t\t// Here we will have calls to public controller functions to switch on/off a boolean\n\t\t// within each controller that lets it know whether it has permission to run\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the part owner | function create_owners(attempt, username, cb) {
const channel = helper.getChannelId();
const first_peer = helper.getFirstPeerName(channel);
var options = {
peer_urls: [helper.getPeersUrl(first_peer)],
args: {
part_owner: username,
owners_company: process.env.part_company
}
};
parts_lib.register_owner(options, function (e, resp) {
if (e != null) {
console.log('');
logger.error('error creating the part owner', e, resp);
cb(e, resp);
}
else {
cb(null, resp);
}
});
} | [
"function create_assets(build_parts_users) {\r\n\tbuild_parts_users = misc.saferNames(build_parts_users);\r\n\tlogger.info('Creating part owners and parts');\r\n\tvar owners = [];\r\n\r\n\tif (build_parts_users && build_parts_users.length > 0) {\r\n\t\tasync.each(build_parts_users, function (username, owner_cb) {\r\n\t\t\tlogger.debug('- creating part owner: ', username);\r\n\r\n\t\t\t// --- Create Each User --- //\r\n\t\t\tcreate_owners(0, username, function (errCode, resp) {\r\n\t\t\t\towners.push({ id: resp.id, username: username });\r\n\t\t\t\towner_cb();\r\n\t\t\t});\r\n\r\n\t\t}, function (err) {\r\n\t\t\tlogger.info('finished creating owners, now for parts');\r\n\t\t\tif (err == null) {\r\n\r\n\t\t\t\tvar parts = [];\r\n\t\t\t\tvar partsEach = 3;\t\t\t\t\t\t\t\t\t\t\t\t//number of parts each owner gets\r\n\t\t\t\tfor (var i in owners) {\r\n\t\t\t\t\tfor (var x = 0; x < partsEach; x++) {\r\n\t\t\t\t\t\tparts.push(owners[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tlogger.debug('prepared parts obj', parts.length, parts);\r\n\r\n\t\t\t\t// --- Create Parts--- //\r\n\t\t\t\tsetTimeout(function () {\r\n\t\t\t\t\tasync.each(parts, function (owner_obj, part_cb) { \t\t\t//iter through each one \r\n\t\t\t\t\t\tcreate_parts(owner_obj.id, owner_obj.username, part_cb);\r\n\t\t\t\t\t}, function (err) {\t\t\t\t\t\t\t\t\t\t\t\t//part owner creation finished\r\n\t\t\t\t\t\tlogger.debug('- finished creating asset');\r\n\t\t\t\t\t\tif (err == null) {\r\n\t\t\t\t\t\t\tall_done();\t\t\t\t\t\t\t\t\t\t\t\t//delay for peer catch up\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t}, helper.getBlockDelay());\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\telse {\r\n\t\tlogger.debug('- there are no new part owners to create');\r\n\t\tall_done();\r\n\t}\r\n}",
"function addPart(){\n var panel = View.panels.get('wo_upd_wr_form');\n var wrId = panel.getFieldValue(\"wr.wr_id\");\n \n var rest = new Ab.view.Restriction();\n rest.addClause(\"wrpt.wr_id\", wrId, \"=\");\n rest.addClause(\"wrpt.part_id\", '', \"=\");\n View.openDialog(\"ab-helpdesk-workrequest-newpart.axvw\", rest, true);\n}",
"addPart ({ id, owner, file, partNum }, portalOpts) {\n const args = this.addOptions({\n id,\n owner,\n file,\n partNum\n }, portalOpts);\n\n return addItemPart(args)\n .catch(handleError);\n }",
"async CreateProjectOwner(ctx, args) {\n args = JSON.parse(args);\n\n let projectOwner = {\n id: args.userId,\n companyName: args.companyName,\n type: 'projectOwner',\n projects: [],\n entity: 'user'\n };\n await ctx.stub.putState(args.userId, Buffer.from(JSON.stringify(projectOwner)));\n\n //add projectOwnerId to 'projectOwners' key\n let data = await ctx.stub.getState('projectOwners');\n if (data) {\n let projectOwners = JSON.parse(data.toString());\n projectOwners.push(args.userId);\n await ctx.stub.putState('projectOwners', Buffer.from(JSON.stringify(projectOwners)));\n } else {\n throw new Error('projectOwners not found');\n }\n\n // return projectOwner object\n return projectOwner;\n }",
"waitFor_horseProfile_Overview_OwnerContent() {\n this.horseProfile_Overview_OwnerContent.waitForExist();\n }",
"partName(part) {\n return this.blocks[part].getName('New Block', true);\n }",
"function createRoom(){\n\t\t\tconsole.log(\"creating room\");\n\t\t\t$scope.rooms.$add({\n\t\t\t\tplayer1: userId,\n\t\t\t\tplayer2: 0,\n\t\t\t\tproblemCode: null,\n\t\t\t\tready1: false,\n\t\t\t\tready2: false,\n\t\t\t\tlang1: \"not set\",\n\t\t\t\tlang2: \"not set\", \n\t\t\t\ttime: 5,\n\t\t\t\tstatus: 0,\n\t\t\t\twinner: 0,\n\t\t\t\tgiveup: 0\n\t\t\t}) .then(function(ref){\n\t\t\t\tp1_id = userId;\n\t\t\t\troomKey = ref.key;\n\n\t\t\t\t$scope.roomIndex = $scope.rooms.$indexFor(roomKey);\n\t\t\t\t$scope.hasRoom = true;\n\n\t\t\t\tcheckOpponent();\n\t\t\t\tconsole.log(\"Room has created\");\n\n\t\t\t\tuserModel.getPlayerDetails(userId)\n\t\t\t\t.success(function(response){\n\t\t\t\t\t$scope.p1_name = response;\n\t\t\t\t});\n\t\t\t});\n\t\t}",
"function creation() {\n return div('creation', \n row(\n col('col-4', div('creation__title title', 'News creation form')) + \n col('col-8', toolbox())\n ) +\n row(\n col('col-12', div('tab-content', textForm() + imageForm()))\n )\n \n ) \n}",
"function createElements() {\n var page = document.getElementById('page-content-wrapper');\n\n var img = document.createElement('img');\n img.setAttribute(\"class\", \"picture\");\n img.setAttribute(\"src\", \"../img/profile/\" + current.pic);\n\n var name = document.createElement('h2');\n name.setAttribute(\"class\", \"user-name\");\n name.innerHTML = current.name;\n\n var username = document.createElement('h3');\n username.setAttribute(\"class\", \"username-tag\");\n username.innerHTML = current.username;\n\n\n //Appends the element to the parent element\n current.win.appendChild(name);\n current.win.appendChild(username);\n current.win.appendChild(img);\n page.appendChild(current.win);\n }",
"static newFriendo(name, owner, element) {\n return new Friendo({ name, owner, element })\n }",
"function stateSetOwner() {\n var FlowState = w2ui.propertyForm.record.FlowState;\n var si = getCurrentStateInfo();\n var uid = 0;\n\n if (si == null) {\n console.log('Could not determine the current stateInfo object');\n return;\n }\n if (typeof w2ui.stateChangeForm.record.OwnerName == \"object\" && w2ui.stateChangeForm.record.OwnerName != null) {\n if (w2ui.stateChangeForm.record.OwnerName.length > 0) {\n uid = w2ui.stateChangeForm.record.OwnerName[0].UID;\n }\n }\n if (uid == 0) {\n w2ui.stateChangeForm.error('ERROR: You must select a valid user');\n return;\n }\n si.OwnerUID = uid;\n si.Reason = \"\";\n var x = document.getElementById(\"smOwnerReason\");\n if (x != null) {\n si.Reason = x.value;\n }\n if (si.Reason.length < 2) {\n w2ui.stateChangeForm.error('ERROR: You must supply a reason');\n return;\n }\n finishStateChange(si,\"setowner\");\n}",
"function createVendorTemplate(bundle) {\n const sender_password = bundle.authData.sender_password;\n const sender_id = bundle.authData.sender_id;\n const temp_session_ID = bundle.authData.temp_session_ID;\n const timestamp = Date.now();\n\n const name = bundle.inputData.name;\n const printAs = bundle.inputData.printAs;\n const companyName = bundle.inputData.companyName;\n\n var jsonObj = {\n request: {\n control: {\n senderid: sender_id,\n password: sender_password,\n controlid: timestamp,\n uniqueid: false,\n dtdversion: '3.0',\n includewhitespace: false,\n },\n operation: {\n authentication: {\n sessionid: temp_session_ID,\n },\n content: {\n function: { $: {controlid: \"220c4620-ed4b-4213-bfbb-10353bb73b62\" },\n create: {\n vendor: {\n name: name\n },\n displayContact: {\n printAs: printAs,\n companyName: companyName,\n \n // Enter more fields for Vendor Information here\n }\n }\n }\n }\n }\n }\n };\n\n return jsonObj;\n}",
"function pessimistic_create_owner(attempt, username, cb) {\n\tvar options = {\n\t\tpeer_urls: [helper.getPeersUrl(0)],\n\t\targs: {\n\t\t\tmarble_owner: username,\n\t\t\towners_company: process.env.marble_company\n\t\t}\n\t};\n\tmarbles_lib.register_owner(options, function (e) {\n\n\t\t// --- Does the user exist yet? --- //\n\t\tif (e && e.parsed && e.parsed.indexOf('owner already exists') >= 0) {\n\t\t\tconsole.log('');\n\t\t\tlogger.debug('finally the user exists, this is a good thing, moving on\\n\\n');\n\t\t\tcb(null);\n\t\t}\n\t\telse {\n\n\t\t\t// -- Try again -- //\n\t\t\tif (attempt < 4) {\n\t\t\t\tsetTimeout(function () {\t\t\t\t\t\t\t\t//delay for peer catch up\n\t\t\t\t\tlogger.debug('owner existance is not yet confirmed, trying again', attempt, username, Date.now());\n\t\t\t\t\treturn pessimistic_create_owner(++attempt, username, cb);\n\t\t\t\t}, helper.getBlockDelay() + 1000 * attempt);\n\t\t\t}\n\n\t\t\t// -- Give Up -- //\n\t\t\telse {\n\t\t\t\tlogger.debug('giving up on creating the user', attempt, username, Date.now());\n\t\t\t\tif (cb) return cb(e);\n\t\t\t\telse return;\n\t\t\t}\n\t\t}\n\t});\n}",
"setCreator (user) {\n if (typeof user === 'string') {\n this.creator.path = 'Users/' + user\n } else {\n this.creator.path = 'Users/' + user.key\n }\n }",
"function createPlayer() {\n\n entityManager.generatePlayer({\n cx : 240,\n cy : 266,\n });\n\n}",
"create() {\n const uuid = `urn:uuid:${uuidv4()}`;\n\n this.metadata = new PackageMetadata();\n this.manifest = new PackageManifest();\n this.spine = new PackageSpine();\n this.setUniqueIdentifier(uuid);\n }",
"function createObject(name, parent)\n{\n var component;\n\n if (name in components)\n component = components[name];\n else {\n component = Qt.createComponent(name);\n\n if (component == null || component.status != Component.Ready) {\n console.log(\"error loading '\" + name + \"' component\");\n console.log(component.errorString());\n return null;\n }\n\n components[name] = component;\n }\n\n var object = component.createObject(parent);\n\n if (object === null) {\n console.log(\"error creating object for: \" + name);\n console.log(component.errorString());\n return null;\n }\n\n return object;\n}",
"function createModuloPrincipal(nameSchema, namesTables) {\n const source = fs.readFileSync(\n 'src/base-nest/tamplate-nest/module.html',\n 'utf8',\n );\n const template = Handlebars.compile(source);\n\n const nameModule = namePrimaryMayus(nameSchema);\n const data = { nameModule, modulos: namesTables };\n const content = template(data);\n\n const folder = `${dir}${nameSchema}/${nameFolders(nameSchema)}.module.ts`;\n\n if (verifyFolderExists(folder)) {\n return;\n }\n fs.writeFile(folder, content, err => {\n if (err) {\n console.log(err);\n } else {\n console.log(\n colors().yellow(\n `--- Modulo Creado: src/${nameSchema}/${nameFolders(\n nameSchema,\n )}.module.ts`,\n ) + colors().green('✔'),\n );\n }\n });\n}",
"createAccount()\n {\n account = this.web3.eth.accounts.create();\n\n vaultData.account_list.push(account)\n\n this.selectAccount( account.address )\n\n this.saveVaultData( vaultData )\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Preview image from saved content image path value. | _previewImageByPath()
{
let imagePath = $("textarea#page_content_value").val();
let mediaDetailRoute = Routing.generate('reaccion_cms_admin_media_detail_by_path');
$("div#selected_image_preview").removeClass("d-none");
// load media data
$.post(mediaDetailRoute, { 'path' : imagePath }, function(response)
{
// create and dispatch event
var event = new CustomEvent(
'selectedItemFromMediaGallery',
{
'detail' : {
'image' : response
}
}
);
document.dispatchEvent(event);
// check media option for current image in the image preview component
for(var key in response)
{
if(imagePath == response[key])
{
$('input[data-path-key="' + key + '"]').attr('checked', 'checked');
}
}
// hide loader
$("div#selected_image_preview div.dimmer").removeClass("active");
},
"json");
} | [
"function rexShowMediaPreview() {\n var value, img_type;\n if($(this).hasClass(\"rex-js-widget-media\"))\n {\n value = $(\"input[type=text]\", this).val();\n img_type = \"rex_mediabutton_preview\";\n }else\n {\n value = $(\"select :selected\", this).text();\n img_type = \"rex_medialistbutton_preview\";\n }\n\n var div = $(\".rex-js-media-preview\", this);\n\n var url;\n var width = 0;\n if('.svg' != value.substr(value.length - 4) && $(this).hasClass(\"rex-js-widget-preview-media-manager\"))\n url = './index.php?rex_media_type='+ img_type +'&rex_media_file='+ value;\n else\n {\n url = '../media/'+ value;\n width = 246;\n }\n\n if(value && value.length != 0 && $.inArray(value.split('.').pop(), rex.imageExtensions))\n {\n // img tag nur einmalig einf�gen, ggf erzeugen wenn nicht vorhanden\n var img = $('img', div);\n if(img.length == 0)\n {\n div.html('<img />');\n img = $('img', div);\n }\n img.attr('src', url);\n if (width != 0)\n img.attr('width', width);\n\n div.stop(true, false).slideDown(\"fast\");\n }\n else\n {\n div.stop(true, false).slideUp(\"fast\");\n }\n }",
"function onImagePickerOptionChange(pickerOption) {\r\n $('#projectImagePreview').attr('src', $(pickerOption.option[0]).data('img-src'));\r\n}",
"function loadImg(img, target_name) {\n if (img.files && img.files[0]) {\n var FR = new FileReader();\n FR.onload = function (e) {\n //e.target.result = base64 format picture\n $('#' + target_name + '_preview').attr(\"src\", e.target.result);\n $('#' + target_name + '_input').val(e.target.result);\n };\n FR.readAsDataURL(img.files[0]);\n }\n}",
"function show_image_on_popup(image_path) {\n\tvar photo_enlarger_main_image = document.getElementById(\"photo_enlarger__photo\");\n\tphoto_enlarger_main_image.src = image_path;\n\t\n\ttoggle_photo_enlarger_display();\n}",
"loadPreviews () {\n this.files.map(file => {\n if (!file.previewData && window && window.FileReader && /^image\\//.test(file.file.type)) {\n const reader = new FileReader()\n reader.onload = e => Object.assign(file, { previewData: e.target.result })\n reader.readAsDataURL(file.file)\n }\n })\n }",
"function previewFile(file) {\n if(errorFormat !== undefined) {\n errorFormat.remove();\n }\n let reader = new FileReader()\n reader.readAsDataURL(file);\n reader.onloadend = function() {\n // here I take the dataURL and assign it to a variable to pass it to loadImage function if type is correct\n if(file.type == 'image/jpeg' || file.type == 'image/png') {\n let dragImage = this.result;\n loadImage(dragImage);\n } else {\n errorType();\n }\n }\n }",
"function showIconPicture() {\n // Listen for file selection.\n fileInput.addEventListener('change', function (e) {\n file = e.target.files[0];\n var blob = URL.createObjectURL(e.target.files[0]);\n // Change DOM image.\n image.src = blob;\n\n // Store using this name.\n storageRef = storage.ref(\"images/\" + docAppID + \"icon.jpg\");\n\n storageRef.put(file)\n .then(function () {\n console.log('Uploaded to Cloud Storage.');\n })\n })\n }",
"function Enter_image(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n\n reader.onload = function (e) {\n\t\t\tvar nextEI=$(input).next('.enter_image');\n nextEI.attr('src', e.target.result);\n\t\t\tnextEI.attr('width','50px');\n\t\t\tnextEI.attr('height','50px');\n }\n\n reader.readAsDataURL(input.files[0]);\n }\n}",
"function setPaperImg(){\n decision = \"paper\";\n document.getElementById('meImg').src = PAPERIMGPATH;\n}",
"set src(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.src[set]\");\n this._src = aValue;\n }",
"function paperLoadImage(path, callback) {\n if (raster) raster.remove();\n\n $('#preview').attr('src', '');\n responsiveResize();\n paper.canvas.tempLayer.opacity = 1;\n paper.canvas.tempLayer.activate();\n raster = new paper.Raster({\n position: paper.view.center,\n source: path\n });\n\n // If you create a Raster using a url, you can use the onLoad\n // handler to do something once it is loaded:\n raster.onLoad = function() {\n raster.fitBounds(paper.view.bounds);\n paperSaveImage(callback);\n };\n}",
"onFileChange(event) {\n const file = event.target.files[0];\n this.img = URL.createObjectURL(file);\n }",
"function imageUploaded(error, result) {\n $('#recipe-upload-image').prop(\"src\", result[0].secure_url);\n $('#image_upload_url').val(result[0].secure_url);\n}",
"displayImages() {\n observeDocument(node => this.displayOriginalImage(node));\n qa('iframe').forEach(iframe => iframe.querySelectorAll('a[href] img[src]').forEach(this.replaceImgSrc));\n }",
"swapPlaceholderImg(src) {\n this.$results.find('.results-overview-image img').attr('src', src).attr('alt', 'screenshot for ' + this.websiteUrl);\n }",
"function createPreview() {\n var createdNewElement = createItemElement(images[0]);\n createdNewElement.setAttribute(\"id\", \"preview\");\n return createdNewElement;\n}",
"load()\r\n {\r\n this.image = loadImage(this.imagePath);\r\n }",
"function insertImageUrl(uri, imageUrl) {\n const sourceUri = vscode.Uri.parse(uri);\n vscode.window.visibleTextEditors\n .filter((editor) => preview_content_provider_1.isMarkdownFile(editor.document) &&\n editor.document.uri.fsPath === sourceUri.fsPath)\n .forEach((editor) => {\n // const line = editor.selection.active.line\n editor.edit((textEditorEdit) => {\n textEditorEdit.insert(editor.selection.active, ``);\n });\n });\n }",
"function saveImage() {\n var data = canvas.toDataURL();\n $(\"#url\").val(data);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a number or percentage label for the national lines depending on the data being displayed | function setNationalLabel(label, nationalData) {
if (label.search("Percentage") > -1) {
return "National " + Math.round(nationalData * 100) + "%";
}
else {
return "National " + nationalData;
}
} | [
"function yLabelPosFormatter(y) {\n if (isNaN(y)) { return 'n/a'; }\n y = Math.round(y);\n return y === 0 ? 'P1' : 'P' + -y;\n }",
"function getLargestLabel() {\n return formatData(-88000000000, 1);\n}",
"labelCurrentTrack() {\n\t\tlet labl = 'empty';\n\t\tif (this.trks[tpos].usedInstruments.length === 1) {\n\t\t\tif (this.trks[tpos].hasPercussion) {\n\t\t\t\tlabl = 'Percussion';\n\t\t\t} else {\n\t\t\t\tlabl = getInstrumentLabel(this.trks[tpos].usedInstruments[0]);\n\t\t\t}\n\t\t} else if (this.trks[tpos].usedInstruments.length > 1) {\n\t\t\tlabl = 'Mixed Track';\n\t\t}\n\t\tthis.trks[tpos].label = `${labl} ${this.getLabelNumber(labl)}`;\n\t}",
"function generateLabel(myCongestionProject) {\r\n var total_funding = formatCurrency(myCongestionProject.total_funding_amount);\r\n var federal_funding = formatCurrency(myCongestionProject.fed_funding_amount);\r\n \r\n var label = myCongestionProject.principal_place_cc + \"<br>\" + myCongestionProject.project_description + \"<br>\" + \"Federal Funding $\" + federal_funding + \" out of $\" + total_funding + \" total\";\r\n \r\n return label;\r\n}",
"function show_total_no_of_suicides(ndx) {\n let total_no_of_suicides = ndx.groupAll().reduceSum(dc.pluck('suicides_100k'));\n\n dc.numberDisplay(\"#suicides-figure\")\n .group(total_no_of_suicides)\n .formatNumber(d3.format(\"d\"))\n .valueAccessor(function(d) {\n return d;\n });\n}",
"function displayInsulaLabels(){\n\t\tvar i;\n\t\tvar insulaId;\n\t\tvar insulaCenterCoordinates;\n\t\tvar shortInsulaName;\n\t\tfor(i=0;i<insulaGroupIdsList.length;i++){\n\t\t\tinsulaId=insulaGroupIdsList[i];\n\t\t\tinsulaCenterCoordinates=insulaCentersDict[insulaId];\n\t\t\tshortInsulaName=insulaShortNamesDict[insulaId];\n\t\t\t//insulaCenterCoordinates= adjustInsulaCenters(shortInsulaName, insulaCenterCoordinates);\n\t\t\tif(insulaCenterCoordinates!=null){\n\t\t\t\tshowALabelOnMap(insulaCenterCoordinates,shortInsulaName, \"small\", \"insula\");\n\t\t\t}\n\t\t}\n\t}",
"labeled() {\n return getLabels(this.grid);\n }",
"function getAreaLabel(area, crs) {\n var sqm = crs && crs.to_meter ? area * crs.to_meter * crs.to_meter : area;\n var sqkm = sqm / 1e6;\n return sqkm < 0.01 ? Math.round(sqm) + ' sqm' : sqkm + ' sqkm';\n}",
"drawChromosomeLabels() {\n var ideo = this;\n\n var chromosomeLabelClass = ideo._layout.getChromosomeLabelClass();\n\n var chrSetLabelXPosition = ideo._layout.getChromosomeSetLabelXPosition();\n var chrSetLabelTranslate = ideo._layout.getChromosomeSetLabelTranslate();\n\n // Append chromosomes set's labels\n d3.selectAll(ideo.selector + ' .chromosome-set-container')\n .append('text')\n .data(ideo.chromosomesArray)\n .attr('class', 'chromosome-set-label ' + chromosomeLabelClass)\n .attr('transform', chrSetLabelTranslate)\n .attr('x', chrSetLabelXPosition)\n .attr('y', function(d, i) {\n return ideo._layout.getChromosomeSetLabelYPosition(i);\n })\n .attr('text-anchor', ideo._layout.getChromosomeSetLabelAnchor())\n .each(function(d, i) {\n // Get label lines\n var lines;\n if (d.name.indexOf(' ') === -1) {\n lines = [d.name];\n } else {\n lines = d.name.match(/^(.*)\\s+([^\\s]+)$/).slice(1).reverse();\n }\n\n if (\n 'sex' in ideo.config &&\n ideo.config.ploidy === 2 &&\n i === ideo.sexChromosomes.index\n ) {\n if (ideo.config.sex === 'male') {\n lines = ['XY'];\n } else {\n lines = ['XX'];\n }\n }\n\n // Render label lines\n d3.select(this).selectAll('tspan')\n .data(lines)\n .enter()\n .append('tspan')\n .attr('dy', function(d, i) {\n return i * -1.2 + 'em';\n })\n .attr('x', ideo._layout.getChromosomeSetLabelXPosition())\n .attr('class', function(a, i) {\n var fullLabels = ideo.config.fullChromosomeLabels;\n return i === 1 && fullLabels ? 'italic' : null;\n }).text(String);\n });\n\n var setLabelTranslate = ideo._layout.getChromosomeSetLabelTranslate();\n\n // Append chromosomes labels\n d3.selectAll(ideo.selector + ' .chromosome-set-container')\n .each(function(a, chrSetNumber) {\n d3.select(this).selectAll('.chromosome')\n .append('text')\n .attr('class', 'chrLabel')\n .attr('transform', setLabelTranslate)\n .attr('x', function(d, i) {\n return ideo._layout.getChromosomeLabelXPosition(i);\n }).attr('y', function(d, i) {\n return ideo._layout.getChromosomeLabelYPosition(i);\n }).text(function(d, chrNumber) {\n return ideo._ploidy.getAncestor(chrSetNumber, chrNumber);\n }).attr('text-anchor', 'middle');\n });\n }",
"function setLabelPosition() {\r\n if (document.getElementById(\"rb1\").checked) {\r\n chart.labelRadius = 30;\r\n chart.labelText = \"[[title]]: [[value]]\";\r\n } else {\r\n chart.labelRadius = -30;\r\n chart.labelText = \"[[percents]]%\";\r\n }\r\n chart.validateNow();\r\n }",
"addLabelFromKey() {\n let { data, labelFromKey } = this.props;\n return data.map((d) => {\n d.label = `$${ (d[labelFromKey] / 1000).toPrecision(3) }k`\n })\n }",
"function getRadialLabels(passedData) {\t\n\tvar groupedData = _.groupBy(passedData, 'Day');\n\tfor (var k in groupedData) radial_labels.push(k);\n}",
"static get centeredGreyMiniLabel() {}",
"function students(total, part) {\n var percentage = d3.scaleLinear()\n .domain([0, 100]) // pass in a percent\n .range([0, total])\n\n return percentage(part)\n }",
"function getPercentage(str) {\n return parseFloat((str / max_cgMLST_count) * 100).toFixed(2);\n }",
"display() {\r\n console.log(`Это роутер ${this.name}, дальность(км) ${this.rangeKm}, число антенн ${this.antennaCount}`);\r\n }",
"drawBandLabels(chromosomes) {\n var i, chr, chrs, taxid, ideo, chrModel, chrIndex, textOffsets;\n\n ideo = this;\n\n chrs = [];\n\n for (taxid in chromosomes) {\n for (chr in chromosomes[taxid]) {\n chrs.push(chromosomes[taxid][chr]);\n }\n }\n\n textOffsets = {};\n\n chrIndex = 0;\n for (i = 0; i < chrs.length; i++) {\n chrIndex += 1;\n\n chrModel = chrs[i];\n\n chr = d3.select(ideo.selector + ' #' + chrModel.id);\n\n // var chrMargin = this.config.chrMargin * chrIndex,\n // lineY1, lineY2;\n //\n // lineY1 = chrMargin;\n // lineY2 = chrMargin - 8;\n //\n // if (\n // chrIndex === 1 &&\n // \"perspective\" in this.config && this.config.perspective === \"comparative\"\n // ) {\n // lineY1 += 18;\n // lineY2 += 18;\n // }\n\n textOffsets[chrModel.id] = [];\n\n chr.selectAll('text')\n .data(chrModel.bands)\n .enter()\n .append('g')\n .attr('class', function(d, i) {\n return 'bandLabel bsbsl-' + i;\n })\n .attr('transform', function(d) {\n var transform = ideo._layout.getChromosomeBandLabelTranslate(d, i);\n\n var x = transform.x;\n // var y = transform.y;\n\n textOffsets[chrModel.id].push(x + 13);\n\n return transform.translate;\n })\n .append('text')\n .attr('text-anchor', ideo._layout.getChromosomeBandLabelAnchor(i))\n .text(function(d) {\n return d.name;\n });\n\n // var adapter = ModelAdapter.getInstance(ideo.chromosomesArray[i]);\n // var view = Chromosome.getInstance(adapter, ideo.config, ideo);\n\n chr.selectAll('line.bandLabelStalk')\n .data(chrModel.bands)\n .enter()\n .append('g')\n .attr('class', function(d, i) {\n return 'bandLabelStalk bsbsl-' + i;\n })\n .attr('transform', function(d) {\n var x, y;\n\n x = ideo.round(d.px.start + d.px.width / 2);\n\n textOffsets[chrModel.id].push(x + 13);\n y = -10;\n\n return 'translate(' + x + ',' + y + ')';\n })\n .append('line')\n .attr('x1', 0)\n .attr('y1', function() {\n return ideo._layout.getChromosomeBandTickY1(i);\n })\n .attr('x2', 0)\n .attr('y2', function() {\n return ideo._layout.getChromosomeBandTickY2(i);\n });\n }\n\n for (i = 0; i < chrs.length; i++) {\n chrModel = chrs[i];\n\n var textsLength = textOffsets[chrModel.id].length,\n overlappingLabelXRight,\n index,\n indexesToShow = [],\n prevHiddenBoxIndex,\n xLeft,\n prevLabelXRight,\n prevTextBoxLeft,\n prevTextBoxWidth,\n textPadding;\n\n overlappingLabelXRight = 0;\n\n textPadding = 5;\n\n for (index = 0; index < textsLength; index++) {\n // Ensures band labels don't overlap\n\n xLeft = textOffsets[chrModel.id][index];\n\n if (xLeft < overlappingLabelXRight + textPadding === false) {\n indexesToShow.push(index);\n } else {\n prevHiddenBoxIndex = index;\n overlappingLabelXRight = prevLabelXRight;\n continue;\n }\n\n if (prevHiddenBoxIndex !== index) {\n // This getBoundingClientRect() forces Chrome's\n // 'Recalculate Style' and 'Layout', which takes 30-40 ms on Chrome.\n // TODO: This forced synchronous layout would be nice to eliminate.\n // prevTextBox = texts[index].getBoundingClientRect();\n // prevLabelXRight = prevTextBox.left + prevTextBox.width;\n\n // TODO: Account for number of characters in prevTextBoxWidth,\n // maybe also zoom.\n prevTextBoxLeft = textOffsets[chrModel.id][index];\n prevTextBoxWidth = 36;\n\n prevLabelXRight = prevTextBoxLeft + prevTextBoxWidth;\n }\n\n if (\n xLeft < prevLabelXRight + textPadding\n ) {\n prevHiddenBoxIndex = index;\n overlappingLabelXRight = prevLabelXRight;\n } else {\n indexesToShow.push(index);\n }\n }\n\n var selectorsToShow = [],\n ithLength = indexesToShow.length,\n j;\n\n for (j = 0; j < ithLength; j++) {\n index = indexesToShow[j];\n selectorsToShow.push('#' + chrModel.id + ' .bsbsl-' + index);\n }\n\n this.bandsToShow = this.bandsToShow.concat(selectorsToShow);\n }\n }",
"function getWidthOfLabels(stats)\n{\n var labelsWidth = null;\n var longestLabel = '';\n\n // Find longest label (text in vAxis)\n for (var i = 0; i < stats.length; i++) {\n if (stats[i][0].length > longestLabel.length) {\n longestLabel = stats[i][0];\n }\n }\n\n // If longest label found\n if (longestLabel !== '') {\n var $body = $('body');\n\n // Create/get test div and append longest text inside, than find the width of the div with text\n var $testDiv = $body.find('#testWidth');\n\n if (!$testDiv.length) {\n $body.append('<div id=\"testWidth\" style=\"position: absolute;visibility: hidden;height: auto;width: auto;white-space: nowrap;font-size: 12px !important;\"></div>');\n $testDiv = $body.find('#testWidth');\n }\n\n $testDiv.append(longestLabel);\n labelsWidth = $testDiv.width() + 25;\n\n $testDiv.text('');\n }\n\n return labelsWidth;\n}",
"function displayUnexcavatedLabels(){\n\t\tvar i;\n\t\tvar currentCenter;\n\t\tvar currentCoordinatesList;\n\t\tvar displayTheseUnexAreas = [];\n\t\tdisplayTheseUnexAreas.push(unexcavatedCentersList[0]);\n\t\tdisplayTheseUnexAreas.push(unexcavatedCentersList[1]);\n\t\tdisplayTheseUnexAreas.push(unexcavatedCentersList[6]);\n\t\tdisplayTheseUnexAreas=adjustUnexcavatedCenters(displayTheseUnexAreas);\n\t\tfor(i=0; i<displayTheseUnexAreas.length; i++){\n\t\t\tcurrentCenter=displayTheseUnexAreas[i];\n\t\t\tif(currentCenter!=null){\n\t\t\t\tshowALabelOnMap(currentCenter, \"unexcavated\", \"small\", \"unexcavated\");\n\t\t\t}\n\t\t}\n\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cut out query items from the records array. Returns ARRAY. | function spliceArray(query, record) {
return R.difference(record, query);
} | [
"filterPriceArray(startInd, stopInd) {\n var array = this.priceArray.slice(startInd, stopInd);\n return array.filter((row) => { return row.Open != null;});\n }",
"toArray() {\n const keys = this[ _schema ].keys,\n data = this[ _data ],\n changes = this[ _changeset ],\n arr = []\n\n for (let i = keys.length; i--;) {\n const key = keys[ i ],\n val = changes[ key ] || data[ key ]\n\n if (val != null)\n arr.push(key, val)\n }\n\n return arr\n }",
"function trimWorks(works){\r\n let works_trimmed = [];\r\n\r\n for(let i = 0; i < 3; i++){\r\n works_trimmed.push(works[i]);\r\n }\r\n return works_trimmed;\r\n}",
"getItems(offset, limit) {\n if (this.list.length < offset + limit && !this.lastItem) {\n // All the requested items don't exist and it's not the last page either.\n return null;\n }\n\n if (this.lastItem === 'empty') {\n // empty state\n return [];\n }\n\n const result = [];\n let curr;\n for (let i = offset; i < offset + limit; i++) {\n curr = this.items[this.list[i]];\n if (!curr) {\n // There's a gap in the list of items so the items are not there yet.\n return null;\n }\n result.push(curr);\n\n if (this.lastItem === curr[this.key]) {\n // That should be all items in the collection.\n break;\n }\n }\n\n return result;\n }",
"function fetchItems() {\n const offset = state.offset - 1;\n state.offset += 10 - 1;\n state.index += 10 - 1;\n return axios\n .get(\n `${apiURL}/api/trade/fetch/${state.itemIds.result.splice(\n state.index,\n offset\n )}?query=${state.itemIds.id}`\n )\n .then((res) => {\n return res.data;\n });\n }",
"static discardOldVersions (records) {\n for (let i=0; i < records.length-1; i++) {\n for (let j=i+1; j < records.length; j++) {\n if (records[i].spell_name === records[j].spell_name) {\n let dateA = new Date(records[i].published);\n let dateB = new Date(records[j].published);\n if (dateA < dateB || dateA === null || dateA === '') {\n records[j].rulebook.push(records[i].rulebook[0]);\n records[i] = records[j];\n } else {\n records[i].rulebook.push(records[j].rulebook[0]);\n }\n records.splice(j--, 1);\n }\n }\n }\n return records;\n }",
"function removeFlatDatasetResults() {\n\n\t\tif (!_searchResults || !_searchResults.items || _searchResults.items.length == 0) return;\n\n\t\tvar items = _searchResults.items;\n\t\tvar newItems = [];\n\t\tfor (var i = 0; i < items.length; i++) {\n\t\t\tvar item = items[i];\n\t\t\tif (item.dataset.datasetType.toLowerCase() === \"flat\") continue;\n\n\t\t\tnewItems.push(item);\n\t\t}\n\n\t\t_searchResults.items = newItems;\n\t}",
"function emptyUsedQuoteArrayAndRefillQuoteArray(){\n\t\t\twhile (usedQuotes.length > 0){\n\t\t\t\tquotes.push(usedQuotes.pop());\n\t\t\t}\n\t\t}",
"function removeVals(arr,start,end) {\n var temp=end-1;\n arr.splice(start,temp);\n return arr;\n }",
"function collectionsMappingAsArray () {\n return objectToArray(COLLECTIONS_MAPPING)\n .filter(function (collection) {\n return !isPseudoCollection(collection.id) && \n (typeof collection.category_id === 'undefined' || collection.category_id === null) &&\n (typeof collection.original_id === 'undefined' || collection.original_id === null);\n });\n }",
"function dropElements(arr, func) {\n var startArray = arr;\n var finalArray = startArray;\n for (var i=0; i<startArray.length; i++) {\n if (!(func(arr[i]))) {\n finalArray = startArray.slice(i+1, startArray.length);\n } else {\n return finalArray;\n }\n }\n return [];\n}",
"function createCollection (dimension){\n var arr = new Array();\n for (var index = 0; index < diseaseClasses.length; index++) { \n arr=[...arr, ...selectRows(recordValuesWithColNames[index], dimension)]; \n }//end for loop\n return arr;\n } //end createCollection()",
"function filterOutNulls(response) {\n let dataTable = response.getDataTable();\n\n let filtered = [];\n for (const i in dataTable.wg) {\n // remove nulls and objects with null as their value\n filtered[i] = dataTable.wg[i].c.filter(function (value, index, arr) {\n const kept = value !== null && value.v !== null;\n return kept;\n });\n\n // remove empty arrays\n if (!filtered[i].length) {\n filtered.splice(i, 1);\n break;\n }\n }\n\n dataTable.wg = filtered;\n return dataTable;\n}",
"function copyArrayExcludingEntry(array, id) {\n var newArray = [];\n array.forEach((item) => {\n if (!item._id.equals(id)) {\n newArray.push(item);\n }\n });\n return newArray;\n}",
"returnTopEightResults() {\n let results = [];\n for (let i = 0; i < 8; i++) {\n results.push(this.results[this.results.length - 1 - i]);\n }\n return results;\n }",
"function cleanup(a) {\n return _.filter(a, function (a) {\n var field = a[0];\n return attr[field];\n });\n }",
"function divideUsers(arrayOfUsers) {\n let arrayOfArrays = [];\n while(arrayOfUsers.length) {\n arrayOfArrays.push(arrayOfUsers.splice(0, 10))\n }\n if(arrayOfArrays[arrayOfArrays.length-1].length < 10){\n arrayOfArrays[arrayOfArrays.length-2] = arrayOfArrays[arrayOfArrays.length-2].concat(arrayOfArrays.pop())\n }\n return arrayOfArrays\n}",
"dropWhile(array, predicate) {\n for (let i = 0; i < array.length; i++) {\n if (!(predicate(array[i], array.indexOf(array[i]), array))) { // if predicate-function returns false...\n return this.drop(array, i); // ... drop the current element from the array\n }\n }\n return array;\n }",
"function removeFirstKitten(){\n var newArray = kittens.slice(1);\n return newArray;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the various data displays based on an input sequence. | function updateData(inputSequence) {
var rnaFlag = isRNA(inputSequence);
var mostFrequent = kmerMostFrequent(inputSequence, 4);
$('#most-frequent').html(mostFrequent.toString());
$('#most-frequent-copy').html(mostFrequent[0]);
$('#gc-content').html(Math.floor(gcContent(inputSequence) * 100) + "%");
$('#complement').html(complement(inputSequence, rnaFlag));
var acids = '';
var acidSequence = inputSequence;
if (!rnaFlag) {
acidSequence = dnaToRna(inputSequence);
}
console.log(acidSequence);
for (var i = 0; i < acidSequence.length - 2; i += 3) {
var current = acidSequence.substring(i, i + 3);
var name = codon.CODONS[current];
if (name != 'STOP') {
acids += name.tlc;
} else {
acids += name;
}
}
$('#acids').html(acids);
$('#positions').html(kmerPositions(inputSequence, mostFrequent[0]).toString());
$('#skews').html(minimumSkew(inputSequence).toString());
colorBases();
} | [
"function updateDisplayNum(){\n var totalCount = 0; // total numver of qualified anatomy annotations\n var matchCount = 0; // total matched number of filtered anatomy annotations\n var item = null;\n\n for(var i = 0; i < vm.annotationModels.length; i++){\n item = vm.annotationModels[i];\n totalCount = item.svgID && item.groupID ? totalCount + 1 : totalCount;\n if(filterAnnotations(item)){\n matchCount += 1;\n item.isShow = true;\n }\n else{\n item.isShow = false;\n }\n }\n\n vm.totalCount = totalCount;\n vm.matchCount = matchCount;\n }",
"function updateDisplay(){\n\t\t// Update any changes the Hero element\n\t\t$(\".hero\").html(\n\t\t\t\t\"<p>\" + hero.name + \"</p>\" +\n\t\t\t\t\"<img src='\" + hero.img + \"' >\" +\n\t\t\t\t\"<p> HP: \" + hero.hitPoints + \"</p>\"\n\t\t);\n\t\t// Update any changes the Defender element\n\t\t$(\".defender\").html(\n\t\t\t\t\"<p>\" + defender.name + \"</p>\" +\n\t\t\t\t\"<img src='\" + defender.img + \"' >\" +\n\t\t\t\t\"<p> HP: \" + defender.hitPoints + \"</p>\"\n\t\t);\n\t}",
"drawSequence() {\n\n // chords which are used in the sequence (in the correct order!)\n this.chords = ['C', 'F', 'G', 'Am'];\n\n // get the current sequence\n this.sequence = this.musicMenu.getSequence();\n\n this.chordTexts = [];\n let chord;\n\n // draw each chord of the sequence\n for (let i in this.sequence) {\n\n chord = this.add.text(this.xStart + i * this.distance, this.yPosition, this.chords[this.sequence[i]], this.styles.get(7)).setOrigin(0.5);\n this.chordTexts.push(chord);\n\n }\n\n }",
"function updateNumbers() {\n // look how I loop through all tiles\n tileSprites.forEach(function (item) {\n // retrieving the proper value to show\n var value = fieldArray[item.pos];\n // showing the value\n item.getChildAt(0).text = value;\n // tinting the tile\n item.tint = colors[value]\n });\n }",
"function displayElementValues(datapoint, stageClass) {\n // update only lines relevant to this instruction type and specific inst\n if (debug) {\n console.log(\"displayLineValues datapoint is :\", datapoint);\n console.log(\"displayLineValues stageClass is :\", stageClass);\n }\n\n //ID inst type first\n switch (datapoint) {\n\n case \"IF\":\n // The code below is repeated and should be replaced with a function.\n for (var i = 0; i < elements.length; i++) {\n var anElement = mipsValues[elements[i]];\n // perhpas another way similar to append in main?\n if (anElement.stage === \"IF\") {\n console.log(\"displayElementValues case IF is: \", anElement.stage);\n //create the html element and append to the IF tag.\n if (anElement.vis && anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0){\n d3.select(\"#IF\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"ifetch lineValues\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n } else if (anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0){\n d3.select(\"#IF\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"ifetch lineValues\")\n .style(\"fill\", \"lightgrey\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n }\n }\n }\n // label the PC value below the PC rectangle element\n d3.select(\"#IF\").append(\"text\")\n .text(\"PC: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"ifetch lineValues\")\n .attr(\"x\", 10)\n .attr(\"y\", 365);\n\n break;\n\n case \"ID\":\n\n for (var i = 0; i < elements.length; i++) {\n var anElement = mipsValues[elements[i]];\n // perhpas another way similar to append in main?\n if (anElement.stage === \"ID\") {\n console.log(\"displayElementValues case ID is: \", anElement.stage);\n //console.log(\"displayElementValues ID element is \", elements[i]);\n //create the html element and append to the IF tag.\n if (anElement.vis && anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0) {\n d3.select(\"#ID\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"idecode lineValues\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n } else if (anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0){\n d3.select(\"#ID\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"idecode lineValues\")\n .style(\"fill\", \"lightgrey\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n }\n }\n }\n // Display values that will not fit on processor graphic\n\n d3.select(\"#ID\").append(\"text\")\n .text(\"RD1: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"idecode lineValues\")\n .attr(\"x\", 10)\n .attr(\"y\", 469);\n d3.select(\"#ID\").append(\"text\")\n .text(\"RD2: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"idecode lineValues\")\n .attr(\"x\", 10)\n .attr(\"y\", 482);\n d3.select(\"#ID\").append(\"text\")\n .text(\"Sign Extended 32 bit value: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"idecode lineValues\")\n .attr(\"x\", 350)\n .attr(\"y\", 495);\n\n\n break;\n\n case \"EX\":\n\n for (var i = 0; i < elements.length; i++) {\n var anElement = mipsValues[elements[i]];\n // perhpas another way similar to append in main?\n if (anElement.stage == \"EX\") {\n console.log(\"displayElementValues case ID is: \", anElement.stage);\n //create the html element and append to the IF tag.\n if (anElement.vis && anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0) {\n d3.select(\"#EX\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"excode lineValues\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n } else if (anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0){\n d3.select(\"#EX\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"excode lineValues\")\n .style(\"fill\", \"lightgrey\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n }\n }\n }\n // Display values that will not fit on processor graphic\n d3.select(\"#EX\").append(\"text\")\n .text(\"ALUSrc Mux to ALU in: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"excode lineValues\")\n .attr(\"x\", 10)\n .attr(\"y\", 495);\n d3.select(\"#EX\").append(\"text\")\n .text(\"ALU Result: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"excode lineValues\")\n .attr(\"x\", 10)\n .attr(\"y\", 508);\n d3.select(\"#EX\").append(\"text\")\n .text(\"Shift Left 2 Result: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"excode lineValues\")\n .attr(\"x\", 10)\n .attr(\"y\", 521);\n d3.select(\"#EX\").append(\"text\")\n .text(\"Branch ALU Result: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"excode lineValues\")\n .attr(\"x\", 10)\n .attr(\"y\", 534);\n\n break;\n\n case \"MEM\":\n\n for (var i = 0; i < elements.length; i++) {\n var anElement = mipsValues[elements[i]];\n // perhpas another way similar to append in main?\n if (anElement.stage == \"MEM\") {\n console.log(\"displayElementValues case ID is: \", anElement.stage);\n //create the html element and append to the IF tag.\n if (anElement.vis && anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0) {\n d3.select(\"#MEM\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"memcode lineValues\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n } else if (anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0) {\n d3.select(\"#MEM\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"memcode lineValues\")\n .style(\"fill\", \"lightgrey\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n }\n }\n }\n break;\n\n case \"WB\":\n\n for (var i = 0; i < elements.length; i++) {\n var anElement = mipsValues[elements[i]];\n // perhpas another way similar to append in main?\n if (anElement.stage == \"WB\") {\n console.log(\"displayElementValues case ID is: \", anElement.stage);\n //create the html element and append to the IF tag.\n if (anElement.vis && anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0) {\n d3.select(\"#WB\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"wbcode lineValues\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n } else if (anElement.coordinates[0] !== 0 && anElement.coordinates[1] !== 0) {\n d3.select(\"#WB\").append(\"text\")\n .text(anElement.val)\n .style(\"font-size\", \"9px\")\n .attr(\"id\", elements[i])\n .attr(\"class\", \"wbcode lineValues\")\n .style(\"fill\", \"lightgrey\")\n .attr(\"x\", anElement.coordinates[0])\n .attr(\"y\", anElement.coordinates[1]);\n }\n }\n }\n d3.select(\"#WB\").append(\"text\")\n .text(\"Memory Read Data Result: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"wbcode lineValues\")\n .attr(\"x\", 10)\n .attr(\"y\", 547);\n d3.select(\"#WB\").append(\"text\")\n .text(\"Write Data Result: \")\n .style(\"font-size\", \"9px\")\n .attr(\"class\", \"wbcode lineValues\")\n .attr(\"x\", 350)\n .attr(\"y\", 508);\n\n break;\n\n default:\n console.log(\"displayElementValues: something went horribly wrong\");\n\n }\n\n }",
"function updateUiData(info){\n const {date , temp , feelings} = info;\n // update the date div \n dateEntry.innerHTML = \"Date: \" + date;\n\n // update the temp div \n tempEntry.innerHTML = \"Temp: \" + temp;\n\n // update the content entry \n content.innerHTML = \"Feelings: \" + feelings ;\n\n}",
"function updateDisplayArray() {\n\n\t\t/* First remove the existing data from the arrays */\n\t\twhile (displayArray.length > 0) {\n\t\t\tdisplayArray.shift();\n\t\t\t} \n\n\t\twhile (yearArray.length > 0) {\n\t\t\tyearArray.shift();\n\t\t\t} \n\n\t\twhile (checkArray.length > 0) {\n\t\t\tcheckArray.shift();\n\t\t\t} \n\n\t\twhile (sortArray.length > 0) {\n\t\t\tsortArray.shift();\n\t\t\t} \n\n\t\twhile (sortArray.length > 0) {\n\t\t\tsortArray.shift();\n\t\t\t} \n\n\t\tswitch (displayYear) { \n\t\t\tcase \"2008\":\n\t\t\t\tyearArray = data.year2008.slice(0);\n\t\t\t\tbreak;\n\t\t\tcase \"2009\":\n\t\t\t\tyearArray = data.year2009.slice(0);\n\t\t\t\tbreak;\n\t\t\tcase \"2010\":\n\t\t\t\tyearArray = data.year2010.slice(0);\n\t\t\t\tbreak;\n\t\t\tcase \"2011\":\n\t\t\t\tyearArray = data.year2011.slice(0);\n\t\t\t\tbreak;\n\t\t\tcase \"2012\":\n\t\t\t\tyearArray = data.year2012.slice(0);\n\t\t\t\tbreak; \t\t\t\t\t\t\t\t\t\t\t \n\t\t\tdefault:\n\t\t\t\tyearArray = data.year2012.slice(0);\n\t\t\t\tbreak;\t\t\n\t\t}\n\n\n\t\tfor (var i = 0; i < yearArray.length; i++) { \n\t\t\t\tcheckArray.push({});\n\t\t}\n\n\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\tcheckArray[i].country = yearArray[i].country;\n\t\t\tcheckArray[i].countryCode = yearArray[i].countryCode;\n\t\t\tcheckArray[i].continent = yearArray[i].continent;\n\t\t};\n\n\t\tif (count === \"cc\") {\n\t\t\tswitch (field) {\n\t\t\t\tcase \"all\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].cc;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"phys\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ccPhys;\n\t\t\t\t\t};\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"life\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ccLife;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"earth\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ccEarth;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"chem\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ccChem;\n\t\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].cc;\n\t\t\t\t\t};\t\t\t\t\t\t\t\t\t\t\n\t\t\t}\n\t\t} else if (count === \"ac\"){\n\t\t\tswitch (field) {\n\t\t\t\tcase \"all\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ac;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"phys\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].acPhys;\n\t\t\t\t\t};\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"life\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].acLife;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"earth\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].acEarth;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"chem\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].acChem;\n\t\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ac;\n\t\t\t\t\t};\t\t\t\t\t\t\t\t\t\t\n\t\t\t}\n\t\t};\n\n\t\t/*\tFind out if each country is checked and if so copy their\n\t\t\tobject from checkArray into displayArray */\n\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\tvar countryName = checkArray[i].country;\n\n\t\t\tif (d3.select(\".country-select [value=\" + countryName + \"]\").property(\"checked\")) {\n\t\t\t\tdisplayArray.push(checkArray[i]);\n\t\t\t}\n\t\t};\n\n\t\t/*\tSort displayArray into the descending order \n\t\t\tIf the contries happen to have the same value for choice then they are sorted into alphabetical order */\n\t\tdisplayArray.sort(function(a, b) {\n\t\t\t\tif (b.choice < a.choice) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\telse if (b.choice > a.choice) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else if (b.choice === a.choice) {\n\t\t\t\t\treturn a.country < b.country ? -1 : a.country > b.country ? 1 : 0;\n\t\t\t\t}\n\t\t\t})\n\n\t\tupdateBars();\n\t\tupdateHeader();\n\t\tsetupLabel();\n\t}",
"updateSimulationData(simData) {\n // console.log(\"Updating simulation info...\");\n\n this.resultDisplay.selectAll('p')\n .remove();\n\n this.resultDisplay\n .append(\"p\")\n .text(\"Total Combats: \" + simData.numFights.toLocaleString());\n\n this.resultDisplay\n .append(\"p\")\n .text(\"Player Wins: \" + simData.wins.players.toLocaleString() +\n \" (\" +\n Math.floor((simData.wins.players / simData.numFights) * 100) +\n \"%)\");\n\n this.resultDisplay\n .append(\"p\")\n .text(\"Monster Wins: \" + simData.wins.monsters.toLocaleString() +\n \" (\" +\n Math.floor((simData.wins.monsters / simData.numFights) * 100) +\n \"%)\");\n\n this.resultDisplay\n .append(\"p\")\n .text(\"Total Damage Dealt by All Players: \" +\n simData.damageSummary.players.toLocaleString());\n\n this.resultDisplay\n .append(\"p\")\n .text(\"Total Damage Dealt by All Monsters: \" +\n simData.damageSummary.monsters.toLocaleString());\n\n this.resultDisplay\n .append(\"p\")\n .text(\"Total Turns: \" + simData.turns.toLocaleString());\n\n this.resultDisplay\n .append(\"p\")\n .text(\"Average Turns Per Battle: \" +\n simData.avgTurns.toLocaleString());\n\n this.resultDisplay\n .append(\"p\")\n .text(\"Simulation Runtime: \" + simData.runtime);\n\n this.drawBarAttribute(\n this.contentRows.select(\".damageRow.simLeft\"),\n Object.values(simData.players),\n [0, 15000],\n \"damage\");\n\n this.drawBarAttribute(\n this.contentRows.select(\".damageRow.simRight\"),\n Object.values(simData.monsters),\n [0, 15000],\n \"damage\");\n\n }",
"function updateDisplay(num) {\n\tnum.addEventListener(\"click\", function() {\n\t\ttempArray.push(num.value);\n\t\tdisplay.textContent = tempArray.join('');\n\t});\n}",
"function updateTransactionsDisplay(){\n\t\n\t\t// date to display --> in Date format\n\t\tvar date = Account.transactionsArray[Account.transactionsArray.length -1].date ;\n\t\t\n\t\t// date to display --> in string format\n\t\tdate = getDisplayDate(date);\n\t\t\n\t\t// transaction amount to display\n\t\tvar amount = Account.transactionsArray[Account.transactionsArray.length -1].amount.toFixed(2);\n\t\t\n\t\t// running balance to display\n\t\tvar runBalance = Account.runningBalance.toFixed(2) ;\n\t\t\n\t\tformatDisplay(date, amount, runBalance);\n\t}",
"function updateCPUDisplay() {\n $('#CPU_PC').html(_CPU.PC.toString(16).toUpperCase());\n $('#CPU_ACC').html(_CPU.Acc.toString(16).toUpperCase());\n $('#CPU_XReg').html(_CPU.Xreg.toString(16).toUpperCase());\n $('#CPU_YReg').html(_CPU.Yreg.toString(16).toUpperCase());\n $('#CPU_ZFlag').html(_CPU.Zflag.toString(16).toUpperCase());\n}",
"function updateDisplay(value) {\n string = value.toString();\n if (string.length > 11) {\n displayValue = value.toPrecision(11);\n }\n document.getElementById(\"output\").innerHTML = displayValue;\n return;\n}",
"function updateGuessedDisplay() {\n $('#guessed0').html(currentGuess[0]);\n $('#guessed1').html(currentGuess[1]);\n $('#guessed2').html(currentGuess[2]);\n $('#guessed3').html(currentGuess[3]);\n updateDisplay();\n }",
"function changeDisplay(input) {\n if (input.length <= 8) {\n display.text(input);\n } else {\n clear();\n display.text('Err');\n finish = true;\n }\n }",
"function displayObservation(obs) {\n bilirubin.innerHTML = obs.hdl;\n creatinine.innerHTML = obs.ldl;\n INR.innerHTML = obs.sys;\n Sodium.innerHTML = obs.dia;\n}",
"function updateLifeDisplay() {\r\n\r\n var text, configuration, recLength, sleepLength, countResponse, completeRecCount, totalRecCount, recSize, truncatedRecordingSize, totalSize, energyUsed, totalRecLength, truncatedRecCount, truncatedRecTime;\r\n\r\n /* If no recording periods exist, do not perform energy calculations */\r\n\r\n if (timeHandler.getTimePeriods().length === 0) {\r\n\r\n lifeDisplayPanel.textContent = \"\";\r\n\r\n return;\r\n\r\n }\r\n\r\n configuration = configurations[parseInt(ui.getSelectedRadioValue(\"sample-rate-radio\"), 10)];\r\n\r\n recLength = parseInt(recordingDurationInput.value, 10);\r\n sleepLength = parseInt(sleepDurationInput.value, 10);\r\n\r\n /* Calculate the amount of time spent recording each day */\r\n\r\n countResponse = getDailyCounts(timeHandler.getTimePeriods(), recLength, sleepLength);\r\n completeRecCount = countResponse.completeRecCount;\r\n truncatedRecCount = countResponse.truncatedRecCount;\r\n truncatedRecTime = countResponse.truncatedRecTime;\r\n\r\n totalRecCount = completeRecCount + truncatedRecCount;\r\n totalRecLength = (completeRecCount * recLength) + truncatedRecTime;\r\n\r\n /* Calculate the size of a days worth of recordings */\r\n\r\n recSize = configuration.sampleRate / configuration.sampleRateDivider * 2 * recLength;\r\n truncatedRecordingSize = (truncatedRecTime * configuration.sampleRate / configuration.sampleRateDivider * 2);\r\n\r\n totalSize = (recSize * completeRecCount) + truncatedRecordingSize;\r\n\r\n /* Generate life display message */\r\n\r\n text = \"Each day this will produce \";\r\n\r\n text += totalRecCount + \" file\";\r\n\r\n text += totalRecCount > 1 ? \"s \" : \" \";\r\n\r\n if (completeRecCount > 0) {\r\n\r\n text += \" each up to \" + formatFileSize(recSize) + \" \";\r\n\r\n }\r\n\r\n text += \"totalling \" + formatFileSize(totalSize) + \".<br/>\";\r\n\r\n /* Calculate amount of energy used both recording a sleeping over the course of a day */\r\n\r\n energyUsed = totalRecLength * configuration.current / 3600;\r\n\r\n energyUsed += (86400 - totalRecLength) * sleepEnergy / 3600;\r\n\r\n text += \"Daily energy consumption will be approximately \" + Math.round(energyUsed) + \" mAh.\";\r\n\r\n lifeDisplayPanel.innerHTML = text;\r\n\r\n}",
"function updateDisplay() {\n\n var memLength = document.getElementById(\"memory-stack-display\").childElementCount;\n\n document.getElementById(\"display\").innerHTML = display;\n document.getElementById(\"calculations\").innerHTML = calculations.toString().replace(/,/g, \" \");\n\n document.getElementById('MC').disabled = memLength == 0;\n document.getElementById('MR').disabled = memLength == 0;\n document.getElementById('M').disabled = memLength == 0;\n if(display.indexOf('.') != -1){\n document.getElementById('dot').disabled = true;\n }\n\n if (memLength == 0) {\n MemoryActions.hideMemory();\n }\n\n setButtonState(buttonState);\n}",
"function displayAll() {\r\n displayInput();\r\n displayOutput();\r\n}",
"function displayIteration(iteration) {\n var interpolated = interpolateData(iteration, iterations, results).slice(0, 3100);\n\n //TODO: we can incorporate this inside interpolateDate\n var limits = interpolated.reduce(function (acc, data) {\n return [Math.max(acc[0], Math.abs(data.x)), Math.max(acc[1], Math.abs(data.y))];\n }, [0, 0]);\n updateScale([-limits[0], limits[0]], [-limits[1], limits[1]]);\n\n interpolated.forEach(function (data, i) {\n // unadjust zoom translate\n digits[i].position.x = xScale0(data.x) + margin.left;\n digits[i].position.y = yScale0(data.y) + margin.top;\n });\n\n if (animating)\n animate(); // repaint\n else\n renderMapbox(); // disable minimap during transition animation coz it's too slow\n\n label.text(pad(Math.round(iteration), 3));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
kebabToSnake() replace ""s with "_"s in input string | function kebabToSnake(str){
// while(str.indexOf("-") > 0) {
// str = str.replace("-", "_");
// }
return str.replace(/-/g, "_");
} | [
"function kebabToCamel(s) {\r\n return s.replace(/(\\-\\w)/g, function (m) { return m[1].toUpperCase(); });\r\n}",
"function keyify(str) {\r\n str = str.replace(/[^a-zA-Z0-9_ -]/g, '');\r\n str = trim(str);\r\n str = str.replace(/\\s/g, '_');\r\n return str.toLowerCase();\r\n}",
"function addunderscores( str ){ return str.replace(/\\'|\\\"| /g, '_'); }",
"function makeStandardJSName(s){\n return s.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });\n }",
"toSnakeCase(text, opts = {}) {\n //(1) get case if needed\n if (opts.case == \"lower\") text = text.toLowerCase();\n else if (opts.case == \"upper\") text = text.toUpperCase();\n\n //(2) replace - and whitespaces\n text = text.replace(/[ -]/g, \"_\");\n\n //(3) return\n return text;\n }",
"function capitalizeAndSpace(str) {\n\tvar newstr = str.replace(/_+/g, ' ');\n\t\n newstr = newstr.replace(/\\w+/g, function(a){\n return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();\n });\n\n return newstr;\n}",
"function camelize(s) {\n\t\t\t\t// Remove data- prefix and convert remaining dashed string to camelCase:\n\t\t\t\treturn s.replace(regexDataPrefix, '$1').replace(regexDashB4, function (m, m1) {\n\t\t\t\t\t\treturn m1.toUpperCase();\n\t\t\t\t});\n\t\t}",
"function generateKey() {\n if (!isOwnKey) {\n let $field = $('#space-title');\n let key = \"\";\n if ($field.val().includes(\" \")) {\n let parts = $field.val().split(\" \");\n parts.forEach(function (entry) {\n if (entry.length > 0 && entry[0].match(/[A-Za-z0-9äöüÄÖÜ]/)) key += entry[0].toUpperCase()\n })\n } else {\n for (let i = 0; i < $field.val().length; i++)\n if ($field.val()[i].match(/[A-Za-z0-9äöüÄÖÜ]/)) key += $field.val()[i].toUpperCase()\n };\n $('#space-key').val(key.replace(\"Ä\", \"A\").replace(\"Ö\", \"O\").replace(\"Ü\", \"U\"))\n }\n }",
"function makeUnderscore() {\n for (var i = 0; i < computerWord.length; i++) {\n compWordArray.push(\"_\");\n }\n\n}",
"function _g_chr_2(str) {\n\tlen=str.indexOf(\"_\");\n\tstr=str.substring(len+1);\n\tlen=str.indexOf(\"_\");\n\tstr=str.substring(len+1);\n\treturn str;\n}",
"function bandNameGenerator(str) {\n if(str[0] !== str[str.length-1]){\n return \"The \" + str.charAt(0).toUpperCase() + str.slice(1);\n }else{\n return str.charAt(0).toUpperCase() + str.slice(1) + str.slice(1);\n }\n}",
"set surround_key(string){ \n this.key_prefix = string\n this.key_suffix = string\n }",
"function cleanStationName(name) {\n name = name.replace(\"asema\", \"\")\n name = name.replace(\"_(Finljandski)\", \"\")\n name = name.replace(\"Lento\", \"Lentokenttä\")\n return name;\n}",
"function formatTitle(s){\r\n var formatted_last_part = s.replace(/-/g, \" \");\r\n return formatted_last_part.toLowerCase().replace( /\\b./g, function(a){ return a.toUpperCase(); } );\r\n }",
"function alternatingCaps(s) {\n\treturn s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]());\n}",
"function removeUnderscores() {\n for (i = 0; i < 4; i++) {\n var catBtnText = $(\"#categoryBtn-\" + i).text();\n var formattedText = catBtnText.replace(/_/g, \" \");\n $(\"#categoryBtn-\" + i).text(formattedText);\n }\n }",
"function camelize(name, forceLower){\n if (firstDefined(forceLower, false)) {\n name = name.toLowerCase();\n }\n return name.replace(/\\-./g, function(u){\n return u.substr(1).toUpperCase();\n });\n }",
"function caps(str){\n return str.replace(/\\w\\S*/g, function(txt){\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n}",
"function normalizeHeader_(header) {\n var key = \"\";\n var upperCase = false;\n for (var i = 0; i < header.length; ++i) {\n var letter = header[i];\n if (letter == \" \" && key.length > 0) {\n upperCase = true;\n continue;\n }\n if (!isAlnum_(letter)) { \n continue;\n }\n if (key.length == 0 && isDigit_(letter)) {\n continue; // first character must be a letter\n }\n if (upperCase) {\n upperCase = false;\n key += letter.toUpperCase();\n } else {\n key += letter.toLowerCase();\n }\n }\n return key;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
radian_oh calculates degrees using opposite and hypotenuse lengths(applies inverse sine) | function theta_oh(o,h) {
console.log((Math.asin(o/h))*180/Math.PI)
} | [
"function radian_ah(a,h) {\n console.log(Math.acos(a/h))\n}",
"function radian_oa(o,a) {\n console.log(Math.atan(o/a))\n}",
"function tan (angle) { return Math.tan(rad(angle)); }",
"function omtrek (diameter) {\n return diameter * Math.PI;\n}",
"function sin (angle) { return Math.sin(rad(angle)); }",
"function clockwise_arc_length(angle0, angle1) {\n var diff = angle1 - angle0;\n while (diff < 0) {\n diff = diff + 2 * Math.PI;\n }\n return diff;\n}",
"function getRadians(ts, unit)\n{\n //In order to orient the start of the clock's hands at 12, the\n //clock's hand needs to be rotated by 90 degrees, or PI/2\n var offset = Math.PI/2;\n var radians = 0 + offset;\n var offset_ms, offset_s,offset_mins,offset_hrs;\n //The clock's hands move in the opposite direction of the unit circle.\n //Each incremental movement of the hand must be subtracted from 2 pi.\n switch (unit) {\n case \"ms\":\n offset_ms = (2*Math.PI)-((ts.ms/1000)*(2*Math.PI));\n radians += offset_ms;\n break;\n case \"s\":\n //The offset for seconds written as is allow for the second\n //hand to \"tick\". An adjustment to allow for continuous movement\n //is further below and is conditionally\n offset_s = (2*Math.PI)-((ts.s/60)*(2*Math.PI));\n radians += offset_s;\n break;\n case \"mins\":\n offset_mins = (2*Math.PI)-((ts.mins/60)*(2*Math.PI));\n radians += offset_mins;\n //minutes are adjusted by both the amount of seconds that have passed\n //for the given minute and the portion of milliseconds\n //that have passed for the given second\n offset_s = ((2*Math.PI)*ts.s)/(Math.pow(60,2));\n offset_ms =((2*Math.PI)*ts.ms)/(1000*Math.pow(60,2));\n radians -= offset_s + offset_ms;\n break;\n case \"hrs\":\n\n offset_hrs = (2*Math.PI)-((ts.hrs/12)*(2*Math.PI));\n radians += offset_hrs;\n //hours are adjusted by the combined minutes that have passed for the\n //hour, the portion of seconds that have passed for the minute, and\n //the portion of milliseconds that have passed for the second\n offset_mins = ((2*Math.PI)*ts.mins)/(Math.pow(60,2));\n offset_s = ((2*Math.PI)*ts.s)/(Math.pow(60,3));\n offset_ms = ((2*Math.PI)*ts.ms)/(1000*Math.pow(60,3));\n radians -= offset_mins + offset_s + offset_ms;\n break;\n default:\n radians = radians;\n }\n //Incremental adjustments are to be made to each of the hands based on\n //how much time has elapsed for each smaller unit of measurement\n if (ts.type == 0)\n {\n if (unit==\"s\") {\n //seconds are adjusted by the total amount of ms that have passed\n //for the given second\n radians -= ((2*Math.PI)*ts.ms)/(1000*60);\n }\n }\n return radians;\n}",
"function toDegree(radian) {\n return (radian * 180) / Math.PI;\n }",
"function sine(theta) {\n return Math.sin(theta*(Math.PI / 180));\n}",
"function calcHourAngleSunrise(lat, solarDec) {\n var latRad = degToRad(lat);\n var sdRad = degToRad(solarDec);\n var HAarg = (Math.cos(degToRad(90.833))/(Math.cos(latRad)*Math.cos(sdRad))-Math.tan(latRad) * Math.tan(sdRad));\n var HA = (Math.acos(Math.cos(degToRad(90.833))/(Math.cos(latRad)*Math.cos(sdRad))-Math.tan(latRad) * Math.tan(sdRad)));\n return HA; // in radians\n}",
"function cos (angle) { return Math.cos(rad(angle)); }",
"function calcObliquityCorrection(t) {\n var e0 = calcMeanObliquityOfEcliptic(t);\n var omega = 125.04 - 1934.136 * t;\n var e = e0 + 0.00256 * Math.cos(degToRad(omega));\n return e; // in degrees\n}",
"function mapAngleToZeroAndTwoPI(angle) {\n while (angle < 0) {\n angle += TwoPI;\n }\n\n while (angle > TwoPI) {\n angle -= TwoPI;\n }\n\n return angle;\n }",
"function calcMeanObliquityOfEcliptic(t) {\n var seconds = 21.448 - t*(46.8150 + t*(0.00059 - t*(0.001813)));\n var e0 = 23.0 + (26.0 + (seconds/60.0))/60.0;\n return e0; // in degrees\n}",
"subtractAngles (rad1, rad2) {\n const PI = Math.PI\n let dr = rad1 - rad2\n if (dr <= -PI) dr += 2 * PI\n if (dr > PI) dr -= 2 * PI\n return dr\n }",
"function mod_0_360(x) {return mod0Real(360, x);}",
"function hammerRetroazimuthalRotation(phi0) {\n\t var sinPhi0 = Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"y\" /* sin */])(phi0),\n\t cosPhi0 = Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"h\" /* cos */])(phi0);\n\n\t return function (lambda, phi) {\n\t var cosPhi = Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"h\" /* cos */])(phi),\n\t x = Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"h\" /* cos */])(lambda) * cosPhi,\n\t y = Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"y\" /* sin */])(lambda) * cosPhi,\n\t z = Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"y\" /* sin */])(phi);\n\t return [Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"g\" /* atan2 */])(y, x * cosPhi0 - z * sinPhi0), Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"e\" /* asin */])(z * cosPhi0 + x * sinPhi0)];\n\t };\n\t}",
"function atan (tangent) { return deg(Math.atan(tangent)); }",
"function countSinus(x) {\r\n return Math.sin(x)\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all cells within a given radius of a cell at a specified resolution | function getCellsInRadius(cell, radius, resolution) {
let centerCell;
if (!resolution) {
// Transform passed cell to default resolution
centerCell = transformCellToResolution(cell, DEFAULT_RESOLUTION);
} else {
// Transform passed cell to passed resolution
centerCell = transformCellToResolution(cell, resolution);
}
const edges = h3.getH3UnidirectionalEdgesFromHexagon(centerCell);
const totalEdgeLength = edges
.map((edge) => h3js.exactEdgeLength(edge, 'm')) // Method not in h3-node
.reduce((totalLength, edgeLength) => {
return new Decimal(totalLength).add(edgeLength);
});
const centerCellRadius = totalEdgeLength.div(edges.length);
if (centerCellRadius.greaterThan(radius)) {
throw new RadiusError();
}
const ringSize = new Decimal(radius)
.div(centerCellRadius)
.ceil()
.toNumber();
return h3.kRing(centerCell, ringSize);
} | [
"function findGridAll(x, y, radius) {\n const c = grid.cells.c;\n let found = [findGridCell(x, y)];\n let r = Math.floor(radius / grid.spacing);\n if (r > 0) found = found.concat(c[found[0]]); \n if (r > 1) {\n let frontier = c[found[0]];\n while (r > 1) {\n let cycle = frontier.slice();\n frontier = [];\n cycle.forEach(function(s) {\n\n c[s].forEach(function(e) {\n if (found.indexOf(e) !== -1) return;\n found.push(e);\n frontier.push(e);\n });\n\n });\n r--;\n }\n }\n \n return found;\n\n}",
"function getSurroundCells(y,x) {\n var arr1 = [[y-1,x-1],[y-1,x],[y-1,x+1],[y,x-1],[y,x+1],[y+1,x-1],[y+1,x],[y+1,x+1]];\n var arr2 = [];\n for (ai=0; ai<arr1.length; ai++) {\n if (arr1[ai][0]<height && arr1[ai][1]<width && 0<=arr1[ai][0] && 0<=arr1[ai][1]) {\n arr2.push(arr1[ai]);\n }\n }\n return arr2;\n}",
"function getCellsInGeometry(geometry, resolution) {\n const { coordinates, type } = geometry;\n\n switch (type.toLowerCase()) {\n case 'polygon':\n return h3.polyfill(\n coordinates,\n resolution || DEFAULT_RESOLUTION,\n true\n );\n case 'multipolygon':\n return coordinates.flatMap((c) =>\n h3.polyfill(c, resolution || DEFAULT_RESOLUTION, true)\n );\n default:\n return [];\n }\n}",
"function getCellSols(x, y) {\r\n return sols.children[y * __nbCollonnesLignes + x];\r\n}",
"function getNeighbors(cell) {\n let neighbors = [];\n\n // A cells neighbors is all vertically, horizontally, and\n // diagonally adjacent cells. To find all neighbors we need to\n // iterate the 3x3 area surrounding the target cell. We can\n // accomplish this by starting our iteration one cell less than\n // the target cell, and end one cell beyond.\n let y = cell.getY() - 1\n let yBoundary = cell.getY() + 1\n\n while (y <= yBoundary) {\n\n // If the starting cell is out of bounds then we need to\n // determine which boundary is being violated. We will treat this\n // as an infinite space so the cell will switch to evaluating\n // the cell on the opposite end of the board.\n\n // If we are within the accepted boundaries then use the position.\n let yPosition = 0\n\n if (y >= 0 && y < config.cellsPerColumn) {\n yPosition = y;\n } else {\n\n // If we are negative then we have stretched beyond the top boundary.\n // Update the position to be at the bottom boundary. Otherwise, we\n // have stretched beyond the bottom boundary so update the position\n // to be at the top boundary.\n if (y < 0) {\n yPosition = config.cellsPerColumn - 1;\n }\n }\n\n let x = cell.getX() - 1\n let xBoundary = cell.getX() + 1\n\n while (x <= xBoundary) {\n\n // Similar to the y boundary, we need to determine if a\n // boundary is being violated, and respond accordingly.\n let xPosition = 0\n\n if (x >= 0 && x < config.cellsPerRow) {\n xPosition = x;\n } else {\n if (x < 0) {\n xPosition = config.cellsPerRow - 1;\n }\n }\n\n // Determine the index of the neighboring cell.\n const cellPosition = new Map()\n .set(Cell.ATTR_POSITION_Y, yPosition)\n .set(Cell.ATTR_POSITION_X, xPosition)\n const neighborIndex = calculateCellIndex(cellPosition)\n\n // Verify this cell is not the same as the target cell.\n // If it's not the same cell then add it to the array of\n // neighboring cells.\n let neighboringCell = cells[neighborIndex];\n\n if (neighboringCell !== cell) {\n neighbors.push(neighboringCell);\n }\n\n // Increment x position\n x++\n }\n\n // Increment y position\n y++\n }\n\n return neighbors;\n }",
"function insideCircles(node){\n\tvar strCircles = node.region.label;\n\tvar result = [];\n\t//console.log(circles);\n\n\tfor (var i = 0; i < circles.length; i++){\n\t\tvar circle = circles[i];\n\t\tvar distance = Math.sqrt( Math.pow(node.x - circle.x, 2) + Math.pow(node.y - circle.y, 2) );\n\t\t//does this node's region contain this circle\n\t\tif (strCircles.indexOf(circle.label) != -1) {\n\t\t\t//check node is inside\n\t\t\t\n\t\t\t//console.log(strCircles, label, circle, node, distance);\n\t\t\tif (distance >= circle.r){\n\t\t\t\tresult.push(circle);\n\t\t\t}\n\t\t} else {\n\t\t\t//check if node is outside\n\t\t\tif (distance <= circle.r){\n\t\t\t\tresult.push(circle);\n\t\t\t}\n\n\t\t}\n\t}\n\n/*\n\tfor (var i = 0; i < strCircles.length; i++){\n\t\tvar label = strCircles[i];\n\t\tvar circle = findCircle(label);\n\n\t\tvar distance = Math.sqrt( Math.pow(node.x - circle.x, 2) + Math.pow(node.y - circle.y, 2) );\n\n\t\t//console.log(strCircles, label, circle, node, distance);\n\t\tif (distance > circle.r){\n\t\t\tresult.push(circle);\n\t\t}\n\t}\n*/\t\t\t\treturn result;\n}",
"function randomCells() {\n generation = 0;\n clear = false;\n for (let y = 0; y < resolution; y++) {\n for (let x = 0; x < resolution; x++) {\n if (clear) cells[x][y] = false;\n else if (Math.random() < 0.5) cells[x][y] = true;\n }\n }\n }",
"mapCellsInRect(rect, callback) {\n const results = [];\n if (rect == null) {\n return results;\n }\n const { rowIndexStart, rowIndexEnd } = this.getRowIndicesInRect(rect);\n const { columnIndexStart, columnIndexEnd } = this.getColumnIndicesInRect(rect);\n for (let rowIndex = rowIndexStart; rowIndex <= rowIndexEnd; rowIndex++) {\n for (let columnIndex = columnIndexStart; columnIndex <= columnIndexEnd; columnIndex++) {\n results.push(callback(rowIndex, columnIndex));\n }\n }\n return results;\n }",
"function findCellByCoord(cellCoordinates) {\n if(cellCoordinates) {\n let my_cells = document.getElementsByClassName('game-cell');\n for (let cell of my_cells) {\n let cellRow = cell.getAttribute('data-coordinate-x');\n let cellCol = cell.getAttribute('data-coordinate-y');\n if (cellCoordinates[1] === +cellRow && cellCoordinates[0] === +cellCol) {\n return cell;\n }\n }\n }\n}",
"function checkSurroundingArea(icosphere, centerTile, radius) {\n\tvar queue = new Queue();\n\tvar visited = [];\n\tfor (var size = icosphere.tiles.length-1; size >= 0; size--) visited[size] = false;\n\tvar land = [];\n\tfor (var size = icosphere.tiles.length-1; size >= 0; size--) land[size] = false;\n\tvar distances = [];\n\tfor (var size = icosphere.tiles.length-1; size >= 0; size--) distances[size] = -2;\n\tvar shortestDistance = -1;\n\t\n\tqueue.enqueue(centerTile);\n\tvisited[centerTile] = true;\n\tdistances[centerTile] = 0;\n\twhile (!queue.isEmpty()) {\n\t\tvar tileIndex = queue.dequeue();\n\t\tvar tile = icosphere.tiles[tileIndex];\n\t\tvar neighbors = tile.getNeighborIndices();\n\t\t\n\t\tif (icosphere.vertexHeights[tile.vertexIndices[0]] != 0 ||\n\t\t\ticosphere.vertexHeights[tile.vertexIndices[1]] != 0 ||\n\t\t\ticosphere.vertexHeights[tile.vertexIndices[2]] != 0) {\n\t\t\t\t//Found a land tile\n\t\t\t\tland[tileIndex] = true;\n\t\t\t\tif (shortestDistance === -1 || distances[tileIndex] < shortestDistance) {\n\t\t\t\t\tshortestDistance = distances[tileIndex];\n\t\t\t\t}\n\t\t}\n\t\t\n\t\tfor (var i = 0; i < neighbors.length; i++) {\n\t\t\tvar neighbor = neighbors[i];\n\t\t\tif (!visited[neighbor]) {\n\t\t\t\tif (distances[tileIndex] < radius) {\n\t\t\t\t\tvisited[neighbor] = true;\n\t\t\t\t\tqueue.enqueue(neighbor);\n\t\t\t\t\tdistances[neighbor] = distances[tileIndex] + 1;\n\t\t\t\t}\n\t\t\t} else if (distances[tileIndex] + 1 < distances[neighbor]) {\n\t\t\t\tdistances[neighbor] = distances[tileIndex] + 1;\n\t\t\t\tif (land[neighbor]) {\n\t\t\t\t\tif (shortestDistance === -1 || distances[neighbor] < shortestDistance) {\n\t\t\t\t\t\tshortestDistance = distances[neighbor];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn shortestDistance;\n}",
"function getSearchGeometry(e, searchRadius, suppressZoomError) {\n if (searchRadius == 0) {\n return e.point;\n }\n var center = turf.point([e.lngLat.lng, e.lngLat.lat]);\n var circle = turf.circle(center, searchRadius, {'units': 'kilometers'});\n var bboxLngLat = turf.bbox(circle);\n\n // bbox format is [swpointlng, swpointlat, nepointlng, nepointlat] as \n // according to GeoJSON format \n var nePointPixels = map.project([bboxLngLat[2], bboxLngLat[3]]);\n var swPointPixels = map.project([bboxLngLat[0], bboxLngLat[1]]);\n\n if (!suppressZoomError) {\n validateZoom(e, searchRadius);\n }\n\n return [swPointPixels, nePointPixels];\n}",
"GetEntitiesInRadius( p, r, ignoreEntities ) { return null; }",
"function getGridPoints(number_of_rows, number_of_columns){\n var pointArray = [];\n var i = 0; \n for(c= 0; c< number_of_columns; c++){\n for(r= 0; r< number_of_rows; r++){\n var squareElement = document.getElementById('Square'+(i+1));\n var rect = squareElement.getBoundingClientRect();\n // Left and Top coordiates of grid\n pointArray.push({x: rect.left, y: rect.top});\n i++;\n }\n }\n return pointArray;\n}",
"getNeighbors(col, row){\n var res = [];\n //left border\n if(col > 0){\n this.agentController.ocean.lattice[col-1][row].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //right border\n if(col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //upper border\n if(row > 0){\n this.agentController.ocean.lattice[col][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower border\n if(row < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col][row+1].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //upper left corner\n if(row > 0 && col > 0){\n this.agentController.ocean.lattice[col-1][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //upper right corner\n if(row > 0 && col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower left corner\n if(row < (100/ocean.latticeSize)-1 && col > 0){\n this.agentController.ocean.lattice[col-1][row+1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower right corner\n if(row < (100/ocean.latticeSize)-1 && col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row+1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //own cell\n this.agentController.ocean.lattice[col][row].forEach( (agent) => {\n res.push(agent);\n });\n return res;\n }",
"function CellList(width, height, cellSize) {\n var api,\n colsNum,\n rowsNum,\n cellsNum,\n cell,\n init = function init() {\n var i;\n colsNum = Math.ceil(width / cellSize);\n rowsNum = Math.ceil(height / cellSize);\n cellsNum = colsNum * rowsNum;\n cell = new Array(cellsNum);\n\n for (i = 0; i < cellsNum; i++) {\n cell[i] = [];\n }\n };\n\n init(); // Public API.\n\n api = {\n reinitialize: function reinitialize(newWidth, newHeight, newCellSize) {\n var change = false;\n\n if (newWidth !== undefined) {\n if (newWidth !== width) {\n width = newWidth;\n change = true;\n }\n }\n\n if (newHeight !== undefined) {\n if (newHeight !== height) {\n height = newHeight;\n change = true;\n }\n }\n\n if (newCellSize !== undefined) {\n if (newCellSize !== cellSize) {\n cellSize = newCellSize;\n change = true;\n }\n }\n\n if (change) init();\n },\n addToCell: function addToCell(atomIdx, x, y) {\n var cellIdx = Math.floor(y / cellSize) * colsNum + Math.floor(x / cellSize);\n cell[cellIdx].push(atomIdx);\n },\n getCell: function getCell(idx) {\n return cell[idx];\n },\n getRowsNum: function getRowsNum() {\n return rowsNum;\n },\n getColsNum: function getColsNum() {\n return colsNum;\n },\n getNeighboringCells: function getNeighboringCells(rowIdx, colIdx) {\n var cellIdx = rowIdx * colsNum + colIdx,\n result = []; // Upper right.\n\n if (colIdx + 1 < colsNum && rowIdx + 1 < rowsNum) result.push(cell[cellIdx + colsNum + 1]); // Right.\n\n if (colIdx + 1 < colsNum) result.push(cell[cellIdx + 1]); // Bottom right.\n\n if (colIdx + 1 < colsNum && rowIdx - 1 >= 0) result.push(cell[cellIdx - colsNum + 1]); // Bottom.\n\n if (rowIdx - 1 >= 0) result.push(cell[cellIdx - colsNum]);\n return result;\n },\n clear: function clear() {\n var i;\n\n for (i = 0; i < cellsNum; i++) {\n cell[i].length = 0;\n }\n }\n };\n return api;\n}",
"function findGridCell(x, y, grid) {\n return (\n Math.floor(Math.min(y / grid.spacing, grid.cellsY - 1)) * grid.cellsX +\n Math.floor(Math.min(x / grid.spacing, grid.cellsX - 1))\n );\n}",
"function createNeighborCells(){\n\n var array = new Array();\n var cellPositions = new Array();\n\n // Array the contains fix positions for neighbor cells.\n cellPositions.push(-89.3837279950771);\n cellPositions.push(-142.1328674980365);\n cellPositions.push(-349.87550855851305);\n\n cellPositions.push(-223.32720969134115);\n cellPositions.push(-297.8942624611899);\n cellPositions.push(489.4060068507289);\n\n cellPositions.push(-297.9375904074462);\n cellPositions.push(-179.997998506319);\n cellPositions.push(434.85706179775775);\n\n cellPositions.push(-103.14517395561478);\n cellPositions.push(-224.56336401620294);\n cellPositions.push(-262.54609417884353);\n\n cellPositions.push(-27.395086427601314);\n cellPositions.push(-385.5400787010433);\n cellPositions.push(-352.1989179669081);\n\n cellPositions.push(-360.83258065228586);\n cellPositions.push(-100.64813434224845);\n cellPositions.push(-97.02796592925534);\n\n cellPositions.push(-398.3297307080477);\n cellPositions.push(-66.22930655000425);\n cellPositions.push(-225.59875363251174);\n\n cellPositions.push(405.1131090482779);\n cellPositions.push(143.88113972097028);\n cellPositions.push(310.4022310528064);\n\n cellPositions.push(-264.3245450648799);\n cellPositions.push(-228.868464037242);\n cellPositions.push(0.8838596830101437);\n\n // Array that stores the three different textures for the neighbor cells.\n array.push(\"images/cellTextures/cover1.jpg\");\n array.push(\"images/cellTextures/cover2.jpg\");\n array.push(\"images/cellTextures/cover3.jpg\");\n\n var geometry = new THREE.SphereBufferGeometry(35, 35, 35);\n\n for (var i = 0; i < 27; i = i + 3) {\n\n var random = Math.floor(Math.random() * 3);\n\n let uniforms = {\n cover: {\n type: \"t\",\n value: new THREE.TextureLoader().load(array[random], function(texture){\n\n renderer.render(scene, camera);\n })\n }\n }\n\n var material = new THREE.RawShaderMaterial({\n uniforms: uniforms,\n vertexShader: document.getElementById(\"vertexShader\").textContent,\n fragmentShader: document.getElementById(\"fragShader\").textContent\n\n });\n\n var object = new THREE.Mesh(geometry, material);\n\n // This statements produce random locations for neighbor cells.\n // object.position.x = Math.random() * 900 - 400;\n // object.position.y = Math.random() * 900 - 400;\n // object.position.z = Math.random() * 900 - 400;\n\n object.position.x = cellPositions[i];\n object.position.y = cellPositions[i + 1];\n object.position.z = cellPositions[i + 2];\n\n object.name = \"neighborCell\";\n scene.add(object)\n }\n}",
"_findGridPt (x, grid) {\n // TODO: Binary search, and be rid of this slow method\n let ret = []\n for (let i = 0; i < grid.length; i++) {\n if (grid[i].x === x) {\n ret.push(grid[i])\n }\n }\n return ret\n }",
"function poissonDiscSampler(width, height, radius) {\n var k = 30, // maximum number of samples before rejection\n radius2 = radius * radius,\n R = 3 * radius2,\n cellSize = radius * Math.SQRT1_2,\n gridWidth = Math.ceil(width / cellSize),\n gridHeight = Math.ceil(height / cellSize),\n grid = new Array(gridWidth * gridHeight),\n queue = [],\n queueSize = 0,\n sampleSize = 0;\n\n return function () {\n if (!sampleSize) return sample(Math.random() * width, Math.random() * height);\n\n // Pick a random existing sample and remove it from the queue.\n while (queueSize) {\n var i = Math.random() * queueSize | 0,\n s = queue[i];\n\n // Make a new candidate between [radius, 2 * radius] from the existing sample.\n for (var j = 0; j < k; ++j) {\n var a = 2 * Math.PI * Math.random(),\n r = Math.sqrt(Math.random() * R + radius2),\n x = s[0] + r * Math.cos(a),\n y = s[1] + r * Math.sin(a);\n\n // Reject candidates that are outside the allowed extent,\n // or closer than 2 * radius to any existing sample.\n if (0 <= x && x < width && 0 <= y && y < height && far(x, y)) return sample(x, y);\n }\n\n queue[i] = queue[--queueSize];\n queue.length = queueSize;\n }\n };\n\n function far(x, y) {\n var m = x / cellSize | 0,\n n = y / cellSize | 0,\n i0 = Math.max(m - 2, 0),\n j0 = Math.max(n - 2, 0),\n i1 = Math.min(m + 3, gridWidth),\n j1 = Math.min(n + 3, gridHeight);\n\n for (let j = j0; j < j1; ++j) {\n var o = j * gridWidth;\n for (let i = i0; i < i1; ++i) {\n if (grid[o + i]) {\n var s = grid[o + i],\n dx = s[0] - x,\n dy = s[1] - y;\n if (dx * dx + dy * dy < radius2) return false;\n }\n }\n }\n\n return true;\n }\n\n function sample(x, y) {\n var s = [x, y];\n queue.push(s);\n grid[gridWidth * (y / cellSize | 0) + (x / cellSize | 0)] = s;\n ++sampleSize;\n ++queueSize;\n return s;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
position left and right arrows | function positionArrows() {
// Position left arrow
leftArrow.style.left = menu.offsetLeft - 32 + "px";
leftArrow.style.top = menu.offsetTop + menu.offsetHeight / 2 - 25 + "px";
// Position right arrow
rightArrow.style.top = menu.offsetTop + menu.offsetHeight / 2 - 25 + "px";
rightArrow.style.left = menu.offsetLeft + menu.offsetWidth - 16 + "px";
} | [
"positionate () {\n foreach(arrow => arrow.positionate(), this.arrows)\n }",
"displayLeft() {\n image(arrowImg[3], this.arrowLeftX, this.arrowLeftY, this.size, this.size)\n }",
"function toggleButton() {\n leftPosition == 0 ? arrowLeft.hide() : arrowLeft.show();\n Math.abs(leftPosition) >= innerBoxWidth - containerWidth ? arrowRight.hide() : arrowRight.show();\n }",
"function drawArrowRight(xStart, yStart) {\n drawLine(xStart, yStart, xStart+20, yStart+30, context);\n drawLine(xStart+20, yStart+30, xStart, yStart+60, context);\n drawLine(xStart+20, yStart, xStart+40, yStart+30, context);\n drawLine(xStart+40, yStart+30, xStart+20, yStart+60, context);\n }",
"function drawArrowLeft(xStart, yStart) {\n drawLine(xStart, yStart, xStart-20, yStart+30, context);\n drawLine(xStart-20, yStart+30, xStart, yStart+60, context);\n drawLine(xStart+20, yStart, xStart, yStart+30, context);\n drawLine(xStart, yStart+30, xStart+20, yStart+60, context);\n }",
"displayRight2() {\n image(arrowImg[0], this.arrowRightX, this.arrowRightY2, this.size, this.size)\n }",
"function initArrows() {\n\n\t\tvar arrowNumber = $scope.round.arrowNumber,\n\t\t\tendNumber = $scope.round.endNumber;\n\n\t\tfor (var i = 0, j = 0;\n\t\t\ti < endNumber && j < arrowNumber;\n\t\t\tj++, i = (j === arrowNumber) ? i + 1 : i, j = (j === arrowNumber) ? j = 0 : j)\n\t\t{\n\n\t\t\tif (j === 0) {\n\n\t\t\t\t$scope.round.ends[i].active = (i === $scope.curEnd);\n\t\t\t\t$scope.round.ends[i].draggable = isEnabled;\n\t\t\t\t$scope.round.ends[i].style = {};\n\t\t\t\tdelete $scope.round.ends[i].radius;\n\n\t\t\t}\n\n\t\t\t$scope.round.ends[i].data[j].active = false;\n\n\t\t}\n\n\t}",
"function rightCursor() {\n let beforeScroll = menu.scrollLeft;\n menu.scrollLeft += 1;\n if (beforeScroll == menu.scrollLeft) {\n rightArrow.style.display = \"none\";\n } else {\n rightArrow.style.display = \"inline\";\n }\n menu.scrollLeft = beforeScroll;\n}",
"function updateArrows(stateIdx) {\n if (stateIdx == 0) {\n d3.select('#left-arrow')\n .attr('disabled', true);\n } else if (stateIdx == states.length - 1) {\n d3.select('#right-arrow')\n .attr('disabled', true);\n } else {\n d3.select('#left-arrow')\n .attr('disabled', null);\n d3.select('#right-arrow')\n .attr('disabled', null);\n }\n }",
"function positionThumbs(){\n\t\t\n\t\tif(g_isVertical == false)\n\t\t\tpositionThumbs_horizontal();\n\t\telse\n\t\t\tpositionThumbs_vertical();\t\n\t\t\t\t \t\t\n\t}",
"function leftWindowToRightLocation() {\n moveForward(15);\n turnRight(90);\n moveForward(50);\n turnRight(90);\n moveForward(7);\n turnRight(90);\n}",
"function getArrows(parameters) {\n\t// Just return all the arrows, the view will take those in the range\n\treturn tgArrows.getList();\n}",
"function slideLeftToRight(){\t\n\t\t\tinterval=setInterval(moveLeftToRight,settings['interval']);\n\t\t}",
"get leftArrowButton() {\n return 'a:nth-child(1) > b';\n }",
"function addReorderArrows(el, siblings) {\n\tif (siblings === 'before' || siblings === 'both') {\n\t\tel.append('<a class=\"lfr-ddm-reorder-up-button lfr-ddm-reorder-button icon-arrow-up\" href=\"javascript:;\"></a>');\n\t}\n\n\tif (siblings === 'after' || siblings === 'both') {\n\t\tel.append('<a class=\"lfr-ddm-reorder-down-button lfr-ddm-reorder-button icon-arrow-down\" href=\"javascript:;\"></a>');\n\t}\n}",
"function leftCursor() {\n let beforeScroll = menu.scrollLeft;\n menu.scrollLeft -= 1;\n if (beforeScroll == menu.scrollLeft) {\n leftArrow.style.display = \"none\";\n } else {\n leftArrow.style.display = \"inline\";\n }\n menu.scrollLeft = beforeScroll;\n}",
"function displayControls(){\n noStroke();\n fill(fgColor);\n text(\"left player: WASD. right player: Arrow keys.\", width/2, height-15);\n}",
"function drawLeftTri () {\n\tvar tip = \"Previous Year\";\n\tdrawAnImage (0, svgHeight - arrowSize-barPadding, arrowSize, arrowSize, \"../Resources/arrows/LeftArrow.png\")\n\t\t.on('click', function(){\n\t\t\td3.event.stopPropagation();\n\t\t\tyear = year - 1;\n\t\t\tperSeason();\n\t\t});\n}",
"function addLinesAcrossLeftRight() {\n\n\tconst corners = [\n\t\t{\n\t\t\tx: 0, \n\t\t\ty: 0\n\t\t},\n\t\t{\n\t\t\tx: editorSize, \n\t\t\ty: 0\n\t\t},\n\t\t{\n\t\t\tx: editorSize, \n\t\t\ty: editorSize\n\t\t},\n\t\t{\n\t\t\tx: 0, \n\t\t\ty: editorSize\n\t\t},\n\t];\n\n\tcorners.forEach(linesAcrossLRForCorner);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns path of the latest URL recorded in onBeforeRequest() | function getLastHookedPath() {
const path = lastHookedRequestUrl.pathname + lastHookedRequestUrl.search;
window.domAutomationController.send(path);
} | [
"function getLastPath() {\n if (url.path.components.length > 0) {\n return url.path.components[url.path.components.length - 1];\n }\n }",
"function getPath() {\n //this gets the full url\n var url = document.location.href, path;\n // first strip \n path = url.substr(url.indexOf('//') + 2, url.length - 1);\n path = path.substr(path.indexOf('/'), path.lastIndexOf('/') - path.indexOf('/') + 1);\n //return\n return path;\n }",
"get url() {\n return this._serverRequest.url;\n }",
"function get_UrlArg() {\n var loc = $(location).attr('href');\n var loc_separator = loc.indexOf('#');\n return (loc_separator == -1) ? '' : loc.substr(loc_separator + 1);\n }",
"function get_last_word_in_path(req) {\n\t\tconst parts = req.path ? req.path.split('/') : [];\t\t\t\t\t// grab the last word in the request's path\n\t\treturn parts[parts.length - 1] || '-';\t\t\t\t\t\t\t\t// return '-' when we can't find it\n\t}",
"function getSPSitePath() {\n\tvar url = window.location.origin;\n\tvar path_arr = window.location.pathname.split(\"/\");\n\tvar path = \"\";\n\t// This part needs to be tested\n\tfor (var x = 0; x < path_arr.length - 2; x++) {\n\t\t// Only append valid strings\n\t\tif (path_arr[x]) {\n\t\t\tpath += \"/\" + path_arr[x];\n\t\t}\n\t}\n\treturn (url+path);\n}",
"function getRootPathname() {\n let pathname,\n pathRoot,\n indEnd\n\n pathname = window.location.pathname;\n\n if (pathname === '/') {\n pathRoot = pathname;\n } else {\n indEnd = pathname.indexOf('/', 1);\n pathRoot = pathname.slice(0, indEnd);\n }\n return pathRoot;\n }",
"function getServerUrl() {\n\n var url = null,\n localServerUrl = window.location.protocol + \"//\" + window.location.host,\n context = getContext();\n\n\n if ( Xrm.Page.context.getClientUrl !== undefined ) {\n // since version SDK 5.0.13\n // http://www.magnetismsolutions.com/blog/gayan-pereras-blog/2013/01/07/crm-2011-polaris-new-xrm.page-method\n\n url = Xrm.Page.context.getClientUrl();\n }\n else if ( context.isOutlookClient() && !context.isOutlookOnline() ) {\n url = localServerUrl;\n }\n else {\n url = context.getServerUrl();\n url = url.replace( /^(http|https):\\/\\/([_a-zA-Z0-9\\-\\.]+)(:([0-9]{1,5}))?/, localServerUrl );\n url = url.replace( /\\/$/, \"\" );\n }\n return url;\n }",
"function get_started_url() {\n\n //\n // Return a constant\n //\n return COMMONCRAWL_GET_STARTED;\n\n}",
"function getCurrentPage() {\n var paths = location.href.split('/');\n return paths[paths.length-1].split('.')[0];\n}",
"function destPath() {\n // Remove preceding slash '/'.\n return window.location.pathname.slice(1) + window.location.search;\n }",
"function computeURL() {\n var url = settings.url;\n if (typeof settings.url == 'function') {\n url = settings.url.call();\n }\n return url;\n }",
"function getServerUrl() {\n\n if (SERVER_URL === null) {\n\n var url = null,\n localServerUrl = window.location.protocol + \"//\" + window.location.host,\n context = getContext();\n\n\n if ( Xrm.Page.context.getClientUrl !== undefined ) {\n // since version SDK 5.0.13 \n // http://www.magnetismsolutions.com/blog/gayan-pereras-blog/2013/01/07/crm-2011-polaris-new-xrm.page-method\n\n url = Xrm.Page.context.getClientUrl();\n }\n else if ( context.isOutlookClient() && !context.isOutlookOnline() ) {\n url = localServerUrl;\n }\n else {\n url = context.getServerUrl();\n url = url.replace( /^(http|https):\\/\\/([_a-zA-Z0-9\\-\\.]+)(:([0-9]{1,5}))?/, localServerUrl );\n url = url.replace( /\\/$/, \"\" );\n }\n\n SERVER_URL = url;\n\n }\n\n return SERVER_URL; \n }",
"getPathCsvUrlsFile() {\n return (0, _path.join)(this.getUrlsPath(), \"urls.csv\");\n }",
"function _getUrlExcludeQueryString(){\n \t\n \tif(window && window.location){\n \t\treturn window.location.protocol +\n \t\t\t \"//\" +//[http|https]:// \n \t\t\t window.location.hostname + \n \t\t\t window.location.pathname;\n \t};\n \treturn null;\n }",
"function getPortal() {\n\tvar path = window.location.pathname;\n\tvar pos = path.indexOf('/', 1);\n\tif (pos > 0) {\n\t\tpath = path.substring(1, pos);\n\t}\n\treturn path;\n}",
"function makeUrl(){\r\n var url = location.origin + location.pathname +\r\n '?cid=' + collectedData.currentComment;\r\n return url;\r\n}",
"function ssw_js_get_site_complete_path() {\n\n var site_address_bucket = document.getElementById('ssw-steps').site_address_bucket.value;\n var site_address = document.getElementById('ssw-steps').site_address.value;\n site_address = site_address.toLowerCase();\n var site_complete_path = ''; \n\n //Sample value for ssw_custom_ajax.site_address_bucket_none_value: [\"Personal\", \"Personal1\", \"\"];\n var site_address_bucket_none_value = ssw_custom_ajax.site_address_bucket_none_value;\n\n if (jQuery.inArray(site_address_bucket, site_address_bucket_none_value) < 0 && site_address_bucket != '') {\n site_complete_path = site_address_bucket + '-' + site_address;\n }\n else {\n site_complete_path = site_address;\n }\n\n return site_complete_path;\n}",
"getSrc(){\n\t\tif( this.props.activeTrack ) {\n\t\t\treturn this.props.activeTrack.url;\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Commits, made by an author, and an optional different committer, contain a message, an associated :class:`gitteh::Tree`, and zero or more parent :class:`gitteh::Commit` objects. Zero parents generally indicate the initial commit for the repository. More than one parent commits indicate a merge commit. Properties: id: (String) OID of this commit (SHA1 hash) treeId: (String) OID of associated :class:`gitteh::Tree` parents: (String[]) list of parent commit OIDs message: (String) messageEncoding: (???) ??? TODO: author: (:class:`gitteh::Signature`) committer: (:class:`gitteh::Signature`) | function Commit(repository, obj) {
this.repository = repository;
obj.author = new Signature(obj.author);
obj.committer = new Signature(obj.committer);
_immutable(this, obj).set("id").set("tree", "treeId").set("parents").set("message").set("messageEncoding").set("author").set("committer");
} | [
"parentHashes(str) {\n if (Objects.type(str) === 'commit') {\n return str.split('\\n')\n .filter(line => line.match(/^parent/))\n .map(line => line.split(' ')[1]);\n }\n }",
"function formatCommitInfo( line ) {\n // Result is in format e.g. d748d93 1465819027 committer@email.com A commit message\n // First field is the truncated hash; second field is a unix timestamp (seconds\n // since epoch); third field is the committer email; subject is everything after.\n let fields = line.match(/^([0-9a-f]+)\\s+(\\d+)\\s+(\\S+)\\s+(.*)$/);\n if( fields ) {\n return {\n id: fields[1],\n commit: fields[1],\n date: new Date( Number( fields[2] ) * 1000 ),\n committer: fields[3],\n subject: fields[4]\n };\n }\n return false;\n}",
"function get_msg(commit) {\n\n var msg = commit.author.name + \" <\" + commit.author.email + \">\\n\";\n msg += commit.url + \"\\n\\n\" + commit.message + \"\\n\\n\";\n\n commit.added.forEach(function (val) {\n msg += \"A\\t\" + val + \"\\n\";\n });\n commit.removed.forEach(function (val) {\n msg += \"D\\t\" + val + \"\\n\";\n });\n commit.modified.forEach(function (val) {\n msg += \"M\\t\" + val + \"\\n\";\n });\n\n return msg;\n}",
"function getCommitMessages(settings) {\n\treturn new Promise(function ($return, $error) {\n\t\tconst cwd = settings.cwd,\n\t\t from = settings.from,\n\t\t to = settings.to,\n\t\t edit = settings.edit;\n\n\n\t\tif (edit) {\n\t\t\treturn $return(getEditCommit(cwd, edit));\n\t\t}\n\n\t\treturn $return(getHistoryCommits({ from, to }, { cwd }));\n\t}.bind(this));\n}",
"async function get_all_commits_sha() {\n const repo = await nodegit.Repository.open(local)\n\n const latest_master_commit = await repo.getMasterCommit()\n\n const commits = await new Promise(function (resolve, reject) {\n var hist = latest_master_commit.history()\n hist.start()\n hist.on(\"end\", resolve);\n hist.on(\"error\", reject);\n });\n\n /**\n * this part here is important in case you want to get the commits in increasing chronological order (oldest first)\n */\n commits.reverse()\n\n for (var i = 0; i < commits.length; i++) {\n //var sha = commits[i].sha().substr(0,7), for the sha shorthand, but getting a file by sha shorthand doesn't work at the moment\n /*\n var sha = commits[i].sha(),\n msg = commits[i].message().split('\\n')[0]; //will need this later so I'm leaving it in\n */\n //console.log(sha + \" \" + msg);\n \n\n if(i == 0) {\n //get (and display) all file contents since this is the first commit\n await display_tree(commits[i])\n } else {\n //only get file contents for files that changed since the prev commit\n await display_tree_diff(commits[i], commits[i - 1])\n }\n \n }\n\n}",
"function validateCommitMessage(commitMsg, options) {\n if (options === void 0) { options = {}; }\n var config = config_1.getCommitMessageConfig().commitMessage;\n var commit = typeof commitMsg === 'string' ? parse_1.parseCommitMessage(commitMsg) : commitMsg;\n var errors = [];\n /** Perform the validation checks against the parsed commit. */\n function validateCommitAndCollectErrors() {\n ////////////////////////////////////\n // Checking revert, squash, fixup //\n ////////////////////////////////////\n var _a;\n // All revert commits are considered valid.\n if (commit.isRevert) {\n return true;\n }\n // All squashes are considered valid, as the commit will be squashed into another in\n // the git history anyway, unless the options provided to not allow squash commits.\n if (commit.isSquash) {\n if (options.disallowSquash) {\n errors.push('The commit must be manually squashed into the target commit');\n return false;\n }\n return true;\n }\n // Fixups commits are considered valid, unless nonFixupCommitHeaders are provided to check\n // against. If `nonFixupCommitHeaders` is not empty, we check whether there is a corresponding\n // non-fixup commit (i.e. a commit whose header is identical to this commit's header after\n // stripping the `fixup! ` prefix), otherwise we assume this verification will happen in another\n // check.\n if (commit.isFixup) {\n if (options.nonFixupCommitHeaders && !options.nonFixupCommitHeaders.includes(commit.header)) {\n errors.push('Unable to find match for fixup commit among prior commits: ' +\n (options.nonFixupCommitHeaders.map(function (x) { return \"\\n \" + x; }).join('') || '-'));\n return false;\n }\n return true;\n }\n ////////////////////////////\n // Checking commit header //\n ////////////////////////////\n if (commit.header.length > config.maxLineLength) {\n errors.push(\"The commit message header is longer than \" + config.maxLineLength + \" characters\");\n return false;\n }\n if (!commit.type) {\n errors.push(\"The commit message header does not match the expected format.\");\n return false;\n }\n if (config_1.COMMIT_TYPES[commit.type] === undefined) {\n errors.push(\"'\" + commit.type + \"' is not an allowed type.\\n => TYPES: \" + Object.keys(config_1.COMMIT_TYPES).join(', '));\n return false;\n }\n /** The scope requirement level for the provided type of the commit message. */\n var scopeRequirementForType = config_1.COMMIT_TYPES[commit.type].scope;\n if (scopeRequirementForType === config_1.ScopeRequirement.Forbidden && commit.scope) {\n errors.push(\"Scopes are forbidden for commits with type '\" + commit.type + \"', but a scope of '\" + commit.scope + \"' was provided.\");\n return false;\n }\n if (scopeRequirementForType === config_1.ScopeRequirement.Required && !commit.scope) {\n errors.push(\"Scopes are required for commits with type '\" + commit.type + \"', but no scope was provided.\");\n return false;\n }\n var fullScope = commit.npmScope ? commit.npmScope + \"/\" + commit.scope : commit.scope;\n if (fullScope && !config.scopes.includes(fullScope)) {\n errors.push(\"'\" + fullScope + \"' is not an allowed scope.\\n => SCOPES: \" + config.scopes.join(', '));\n return false;\n }\n // Commits with the type of `release` do not require a commit body.\n if (commit.type === 'release') {\n return true;\n }\n //////////////////////////\n // Checking commit body //\n //////////////////////////\n // Due to an issue in which conventional-commits-parser considers all parts of a commit after\n // a `#` reference to be the footer, we check the length of all of the commit content after the\n // header. In the future, we expect to be able to check only the body once the parser properly\n // handles this case.\n var allNonHeaderContent = commit.body.trim() + \"\\n\" + commit.footer.trim();\n if (!((_a = config.minBodyLengthTypeExcludes) === null || _a === void 0 ? void 0 : _a.includes(commit.type)) &&\n allNonHeaderContent.length < config.minBodyLength) {\n errors.push(\"The commit message body does not meet the minimum length of \" + config.minBodyLength + \" characters\");\n return false;\n }\n var bodyByLine = commit.body.split('\\n');\n var lineExceedsMaxLength = bodyByLine.some(function (line) {\n // Check if any line exceeds the max line length limit. The limit is ignored for\n // lines that just contain an URL (as these usually cannot be wrapped or shortened).\n return line.length > config.maxLineLength && !COMMIT_BODY_URL_LINE_RE.test(line);\n });\n if (lineExceedsMaxLength) {\n errors.push(\"The commit message body contains lines greater than \" + config.maxLineLength + \" characters.\");\n return false;\n }\n // Breaking change\n // Check if the commit message contains a valid break change description.\n // https://github.com/angular/angular/blob/88fbc066775ab1a2f6a8c75f933375b46d8fa9a4/CONTRIBUTING.md#commit-message-footer\n if (INCORRECT_BREAKING_CHANGE_BODY_RE.test(commit.fullText)) {\n errors.push(\"The commit message body contains an invalid breaking change note.\");\n return false;\n }\n if (INCORRECT_DEPRECATION_BODY_RE.test(commit.fullText)) {\n errors.push(\"The commit message body contains an invalid deprecation note.\");\n return false;\n }\n return true;\n }\n return { valid: validateCommitAndCollectErrors(), errors: errors, commit: commit };\n }",
"function getHistoricalCommits() {\n return __awaiter(this, void 0, void 0, function* () {\n const projectDir = getProjectDir();\n if (!projectDir || !Util_1.isGitProject(projectDir)) {\n return null;\n }\n // get the repo url, branch, and tag\n const resourceInfo = yield getResourceInfo(projectDir);\n if (resourceInfo && resourceInfo.identifier) {\n const identifier = resourceInfo.identifier;\n const tag = resourceInfo.tag;\n const branch = resourceInfo.branch;\n const latestCommit = yield getLastCommit();\n let sinceOption = \"\";\n if (latestCommit) {\n // add a second\n const newTimestamp = parseInt(latestCommit.timestamp, 10) + 1;\n sinceOption = ` --since=${newTimestamp}`;\n }\n else {\n sinceOption = \" --max-count=50\";\n }\n const cmd = `git log --stat --pretty=\"COMMIT:%H,%ct,%cI,%s\" --author=${resourceInfo.email}${sinceOption}`;\n // git log --stat --pretty=\"COMMIT:%H, %ct, %cI, %s, %ae\"\n const resultList = yield GitUtil_1.getCommandResult(cmd, projectDir);\n if (!resultList) {\n // something went wrong, but don't try to parse a null or undefined str\n return null;\n }\n let commits = [];\n let commit = null;\n for (let i = 0; i < resultList.length; i++) {\n let line = resultList[i].trim();\n if (line && line.length > 0) {\n if (line.indexOf(\"COMMIT:\") === 0) {\n line = line.substring(\"COMMIT:\".length);\n if (commit) {\n // add it to the commits\n commits.push(commit);\n }\n // split by comma\n let commitInfos = line.split(\",\");\n if (commitInfos && commitInfos.length > 3) {\n let commitId = commitInfos[0].trim();\n if (latestCommit &&\n commitId === latestCommit.commitId) {\n commit = null;\n // go to the next one\n continue;\n }\n let timestamp = parseInt(commitInfos[1].trim(), 10);\n let date = commitInfos[2].trim();\n let message = commitInfos[3].trim();\n commit = {\n commitId,\n timestamp,\n date,\n message,\n changes: {},\n };\n }\n }\n else if (commit && line.indexOf(\"|\") !== -1) {\n // get the file and changes\n // i.e. backend/app.js | 20 +++++++++-----------\n line = line.replace(/ +/g, \" \");\n // split by the pipe\n let lineInfos = line.split(\"|\");\n if (lineInfos && lineInfos.length > 1) {\n let file = lineInfos[0].trim();\n let metricsLine = lineInfos[1].trim();\n let metricsInfos = metricsLine.split(\" \");\n if (metricsInfos && metricsInfos.length > 1) {\n let addAndDeletes = metricsInfos[1].trim();\n // count the number of plus signs and negative signs to find\n // out how many additions and deletions per file\n let len = addAndDeletes.length;\n let lastPlusIdx = addAndDeletes.lastIndexOf(\"+\");\n let insertions = 0;\n let deletions = 0;\n if (lastPlusIdx !== -1) {\n insertions = lastPlusIdx + 1;\n deletions = len - insertions;\n }\n else if (len > 0) {\n // all deletions\n deletions = len;\n }\n commit.changes[file] = {\n insertions,\n deletions,\n };\n }\n }\n }\n }\n }\n if (commit) {\n // add it to the commits\n commits.push(commit);\n }\n let commit_batch_size = 15;\n // send in batches of 15\n if (commits && commits.length > 0) {\n let batchCommits = [];\n for (let commit of commits) {\n batchCommits.push(commit);\n // if the batch size is greather than the theshold\n // send it off\n if (!Util_1.isBatchSizeUnderThreshold(batchCommits)) {\n // send off this set of commits\n let commitData = {\n commits: batchCommits,\n identifier,\n tag,\n branch,\n };\n yield sendCommits(commitData);\n batchCommits = [];\n }\n }\n // send the remaining\n if (batchCommits.length > 0) {\n let commitData = {\n commits: batchCommits,\n identifier,\n tag,\n branch,\n };\n yield sendCommits(commitData);\n batchCommits = [];\n }\n }\n // clear out the repo info in case they've added another one\n myRepoInfo = [];\n }\n /**\n * We'll get commitId, unixTimestamp, unixDate, commitMessage, authorEmail\n * then we'll gather the files\n * COMMIT:52d0ac19236ac69cae951b2a2a0b4700c0c525db, 1545507646, 2018-12-22T11:40:46-08:00, updated wlb to use local_start, xavluiz@gmail.com\n \n backend/app.js | 20 +++++++++-----------\n backend/app/lib/audio.js | 5 -----\n backend/app/lib/feed_helpers.js | 13 +------------\n backend/app/lib/sessions.js | 25 +++++++++++++++----------\n 4 files changed, 25 insertions(+), 38 deletions(-)\n */\n function sendCommits(commitData) {\n // send this to the backend\n HttpClient_1.softwarePost(\"/commits\", commitData, Util_1.getItem(\"jwt\"));\n }\n });\n}",
"ancestors(commitHash) {\n const parents = Objects.parentHashes(Objects.read(commitHash));\n return Util.flatten(parents.concat(parents.map(Objects.ancestors)));\n }",
"function getCommitsFromRepos(repos, days, callback) {\n /*\n pipe(\n // array functor\n trace(`input!`),\n map(gitlog),\n // Future functor\n trace(`glogged!`),\n map((c) => {\n console.log(c, `<<<<<<< CCCC`)\n barf(`c`, c)\n return ([\n `${c.abbrevHash}`,\n `-`,\n `${c.subject}`,\n `(${c.authorDateRel})`,\n `<${c.authorName.replace(`@end@\\n`, ``)}>`\n ].join(` `))\n }),\n trace(`mapped!`),\n all,\n // Future.map(filter)\n map(\n pipe(\n prop(`status`),\n length,\n gt(0),\n filter\n )\n ),\n fork(callback, (x) => callback(null, x))\n )(repos)\n */\n // /*\n let cmts = []\n async.each(repos, (repo, repoDone) => {\n try {\n gitlog({\n repo: repo,\n all: true,\n number: 100, // max commit count\n since: `${days} days ago`,\n fields: [`abbrevHash`, `subject`, `authorDateRel`, `authorName`],\n author\n }, (err, logs) => {\n // Error\n if (err) {\n fail(`Oh noes😱\\nThe repo ${repo} has failed:\\n${err}`)\n }\n // Find user commits\n const commits = logs.map((c) => {\n // barf(`commit`, JSON.stringify(c))\n // filter simple merge commits\n if (c.status && c.status.length) {\n return [\n `${c.abbrevHash}`,\n `-`,\n `${c.subject}`,\n `(${c.authorDateRel})`,\n `<${c.authorName.replace(`@end@\\n`, ``)}>`\n ].join(` `)\n }\n }).filter(I)\n\n // Add repo name and commits\n if (commits.length >= 1) {\n // Repo name\n cmts.push(repo)\n cmts.push(...commits)\n }\n\n repoDone()\n })\n } catch (err) {\n callback(err, null)\n }\n }, (err) => {\n callback(err, cmts.length > 0 ? cmts.join(`\\n`) : `Nothing yet. Start small!`)\n })\n // */\n}",
"function RepoCommit() {\n _classCallCheck(this, RepoCommit);\n\n RepoCommit.initialize(this);\n }",
"function validate_commits(data) {\n var commits;\n try {\n commits = JSON.parse(data).commits;\n } catch (e) {\n log('error parsing commit list:' + e);\n }\n\n if (!commits) {\n commits = [];\n }\n\n return commits;\n}",
"function validateCommitAndCollectErrors() {\n ////////////////////////////////////\n // Checking revert, squash, fixup //\n ////////////////////////////////////\n var _a;\n // All revert commits are considered valid.\n if (commit.isRevert) {\n return true;\n }\n // All squashes are considered valid, as the commit will be squashed into another in\n // the git history anyway, unless the options provided to not allow squash commits.\n if (commit.isSquash) {\n if (options.disallowSquash) {\n errors.push('The commit must be manually squashed into the target commit');\n return false;\n }\n return true;\n }\n // Fixups commits are considered valid, unless nonFixupCommitHeaders are provided to check\n // against. If `nonFixupCommitHeaders` is not empty, we check whether there is a corresponding\n // non-fixup commit (i.e. a commit whose header is identical to this commit's header after\n // stripping the `fixup! ` prefix), otherwise we assume this verification will happen in another\n // check.\n if (commit.isFixup) {\n if (options.nonFixupCommitHeaders && !options.nonFixupCommitHeaders.includes(commit.header)) {\n errors.push('Unable to find match for fixup commit among prior commits: ' +\n (options.nonFixupCommitHeaders.map(function (x) { return \"\\n \" + x; }).join('') || '-'));\n return false;\n }\n return true;\n }\n ////////////////////////////\n // Checking commit header //\n ////////////////////////////\n if (commit.header.length > config.maxLineLength) {\n errors.push(\"The commit message header is longer than \" + config.maxLineLength + \" characters\");\n return false;\n }\n if (!commit.type) {\n errors.push(\"The commit message header does not match the expected format.\");\n return false;\n }\n if (config_1.COMMIT_TYPES[commit.type] === undefined) {\n errors.push(\"'\" + commit.type + \"' is not an allowed type.\\n => TYPES: \" + Object.keys(config_1.COMMIT_TYPES).join(', '));\n return false;\n }\n /** The scope requirement level for the provided type of the commit message. */\n var scopeRequirementForType = config_1.COMMIT_TYPES[commit.type].scope;\n if (scopeRequirementForType === config_1.ScopeRequirement.Forbidden && commit.scope) {\n errors.push(\"Scopes are forbidden for commits with type '\" + commit.type + \"', but a scope of '\" + commit.scope + \"' was provided.\");\n return false;\n }\n if (scopeRequirementForType === config_1.ScopeRequirement.Required && !commit.scope) {\n errors.push(\"Scopes are required for commits with type '\" + commit.type + \"', but no scope was provided.\");\n return false;\n }\n var fullScope = commit.npmScope ? commit.npmScope + \"/\" + commit.scope : commit.scope;\n if (fullScope && !config.scopes.includes(fullScope)) {\n errors.push(\"'\" + fullScope + \"' is not an allowed scope.\\n => SCOPES: \" + config.scopes.join(', '));\n return false;\n }\n // Commits with the type of `release` do not require a commit body.\n if (commit.type === 'release') {\n return true;\n }\n //////////////////////////\n // Checking commit body //\n //////////////////////////\n // Due to an issue in which conventional-commits-parser considers all parts of a commit after\n // a `#` reference to be the footer, we check the length of all of the commit content after the\n // header. In the future, we expect to be able to check only the body once the parser properly\n // handles this case.\n var allNonHeaderContent = commit.body.trim() + \"\\n\" + commit.footer.trim();\n if (!((_a = config.minBodyLengthTypeExcludes) === null || _a === void 0 ? void 0 : _a.includes(commit.type)) &&\n allNonHeaderContent.length < config.minBodyLength) {\n errors.push(\"The commit message body does not meet the minimum length of \" + config.minBodyLength + \" characters\");\n return false;\n }\n var bodyByLine = commit.body.split('\\n');\n var lineExceedsMaxLength = bodyByLine.some(function (line) {\n // Check if any line exceeds the max line length limit. The limit is ignored for\n // lines that just contain an URL (as these usually cannot be wrapped or shortened).\n return line.length > config.maxLineLength && !COMMIT_BODY_URL_LINE_RE.test(line);\n });\n if (lineExceedsMaxLength) {\n errors.push(\"The commit message body contains lines greater than \" + config.maxLineLength + \" characters.\");\n return false;\n }\n // Breaking change\n // Check if the commit message contains a valid break change description.\n // https://github.com/angular/angular/blob/88fbc066775ab1a2f6a8c75f933375b46d8fa9a4/CONTRIBUTING.md#commit-message-footer\n if (INCORRECT_BREAKING_CHANGE_BODY_RE.test(commit.fullText)) {\n errors.push(\"The commit message body contains an invalid breaking change note.\");\n return false;\n }\n if (INCORRECT_DEPRECATION_BODY_RE.test(commit.fullText)) {\n errors.push(\"The commit message body contains an invalid deprecation note.\");\n return false;\n }\n return true;\n }",
"function merkleConstruct(data) {\n // for simplicity we use padded Merkle trees to avoid complications from unbalanced trees\n const paddedData = data.concat(arrayOf(roundUpPow2_(data.length)-data.length, () => 'empty leaf'))\n \n const tree = merkleConstruct_(paddedData)\n return { root:tree[0].slice(6), branch:(leaf) => merkleBranch_(tree, depth_(data.length), leaf) }\n}",
"function git_commit_hash () {\n if (!_HASH) {\n var start = process.cwd(); // get current working directory\n process.chdir(get_base_path()); // change to project root\n var cmd = 'git rev-parse HEAD'; // create name.zip from cwd\n var hash = exec_sync(cmd); // execute command synchronously\n process.chdir(start); // change back to original directory\n _HASH = hash.replace('\\n', ''); // replace the newline\n }\n return _HASH;\n}",
"visitCommit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"treeHash(str) {\n if (Objects.type(str) === 'commit') {\n return str.split(/\\s/)[1];\n }\n }",
"function commit_changes(file, user, message)\n{\n // try to diff file in repo\n simpleGit.diff([ file ], function(err, data) {\n if(err) {\n console.error(err)\n return;\n }\n\n if(data) // diff is not empty\n commit(file, user, message);\n });\n\n // check for new files not added in repo\n simpleGit.status(function(err, data) {\n if(err) {\n console.error(err)\n return;\n }\n\n if(data.not_added.length != 0) // some files have not beed added yet\n commit(file, user, message);\n });\n}",
"function getEditCommit(cwd, edit) {\n\treturn new Promise(function ($return, $error) {\n\t\tvar top, editFilePath, editFile;\n\t\treturn Promise.resolve((0, _topLevel2.default)(cwd)).then(function ($await_1) {\n\t\t\ttry {\n\t\t\t\ttop = $await_1;\n\n\n\t\t\t\tif (typeof top !== 'string') {\n\t\t\t\t\treturn $error(new TypeError(`Could not find git root from ${cwd}`));\n\t\t\t\t}\n\n\t\t\t\teditFilePath = typeof edit === 'string' ? _path2.default.resolve(top, edit) : _path2.default.join(top, '.git/COMMIT_EDITMSG');\n\t\t\t\treturn Promise.resolve(sander.readFile(editFilePath)).then(function ($await_2) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\teditFile = $await_2;\n\n\t\t\t\t\t\treturn $return([`${editFile.toString('utf-8')}\\n`]);\n\t\t\t\t\t} catch ($boundEx) {\n\t\t\t\t\t\treturn $error($boundEx);\n\t\t\t\t\t}\n\t\t\t\t}.bind(this), $error);\n\t\t\t} catch ($boundEx) {\n\t\t\t\treturn $error($boundEx);\n\t\t\t}\n\t\t}.bind(this), $error);\n\t}.bind(this));\n}",
"function update_old(id, newCommits, cb) {\n\n // No commits supplied. Go ahead\n if (newCommits.length === 0) {\n cb(null);\n return true;\n }\n\n var commitsKey = id + \":commits\";\n var commits = self.redis.asList(commitsKey);\n\n // Note: we allow to update the document with commits pointing\n // to a commit that does not need to be the last one.\n // E.g. this happens after undoing commits and adding new changes.\n // Instead of deleting the undone commits we keep them as detached refs\n // which allows to recover such versions.\n\n // Find the parent commit\n var lastSha = newCommits[0].parent;\n if (lastSha && !self.redis.exists(commitsKey + \":\" + lastSha)) {\n var msg = \"Parent commit not found.\";\n cb ? cb({\"error\": msg}) : console.log(msg);\n return false;\n }\n\n for(var idx=0; idx<newCommits.length; idx++) {\n\n var commit = newCommits[idx];\n\n // commit must be in proper order\n if (lastSha && commit.parent != lastSha) {\n var err = {err: -1, msg: \"Invalid commit chain.\"};\n cb ? cb(err) : console.log(err.msg);\n return false;\n }\n\n lastSha = commit.sha;\n }\n\n // save the commits after knowing that everything is fine\n for (var idx = 0; idx < newCommits.length; idx++) {\n var commit = newCommits[idx];\n if (!_.isObject(commit)) throw \"Can not store empty commit.\";\n\n commits.addAsString(commit.sha);\n // store the commit's data into an own field\n self.redis.set(commitsKey + \":\" + newCommits[idx].sha, commit);\n }\n\n self.setRef(id, \"master\", lastSha);\n self.setRef(id, \"tail\", lastSha);\n\n console.log('Stored these commits in the database', newCommits);\n\n\n if (cb) cb(null);\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hide the loading layer | function hideLoading() {
animate(loadingDiv, {
opacity: 0
}, {
duration: options.loading.hideDuration,
complete: function() {
css(loadingDiv, { display: NONE });
}
});
loadingShown = false;
} | [
"function showLoading() {\n loader.hidden = false;\n quoteContainer.hidden = true; \n}",
"showLoader () {\n if (this.hideLoader) return\n this.loadingWrapper.style.display = 'flex'\n this.canvas.style.display = 'none'\n }",
"function hideProcessing(){\n vm.processing = false;\n }",
"function LoaderShowHide() {\n if ($('#top-loading-gif').css('visibility') !== 'hidden') {\n $('#top-loading-gif').hideV();\n }\n else\n $('#top-loading-gif').showV();\n}",
"function hideOVLayer(name) {\t\t\n \tvar layer = getOVLayer(name);\t\t\n \tif (isNav4)\n \tlayer.visibility = \"hide\";\n \t//if (document.all)\n\telse\n \t layer.visibility = \"hidden\";\n\t //layer.display=\"block\";\n}",
"function optionViewLoaded() {\r\n disableDataUpdate();\r\n LoadingBar.hide();\r\n }",
"function stopLoadingIcon() {\n $('#loadingIcon').hide();\n}",
"function hideLayers(evt) {\r\n dialogLayer.style.display = \"none\";\r\n maskLayer.style.display = \"none\";\r\n }",
"function stopLoading(){\n\n\t// settings\n\tvar layer_text = \"loading_label\";\n\tvar layer_img = \"loading_img\";\n\tvar formname = \"analyzing\";\n\tvar buttonname = \"continue_bt\";\n\n\t// changes the text and the image in these layers\n\tif (document.all){ // IE\n\t\n\t\tdocument.all(layer_text).innerHTML = \"<h1 align='center'>Page loaded</h1>\";\n\t\tdocument.all(layer_img).innerHTML = \"\";\n\t\t\n\t} else if (document.getElementById) { // Firefox and others\n\t\n\t\tdocument.getElementById(layer_text).innerHTML = \"<h1 align='center'>Page loaded</h1>\";\n\t\tdocument.getElementById(layer_img).innerHTML = \"\";\n\t}\n\t\n\t// enable the button and modify foregroud color\n\teval(\"document.\"+formname+\".\"+buttonname+\".disabled = false\");\n\teval(\"document.\"+formname+\".\"+buttonname+\".style.color = '#000000'\");\n}",
"hideSpinner() {\n this.spinnerVisible = false;\n }",
"function hideTilesInitialLoad(){\n\t $(\".date\").hide();\n\t $(\"#weather-container\").hide();\n\t $(\"#food-container\").hide();\n\t}",
"function stopLoading2(){\n\n\t// settings\n\tvar layer_text = \"loading_label\";\n\tvar layer_img = \"loading_img\";\n\tvar formname = \"gen\";\n\tvar buttonname = \"finish\";\n\n\t// changes the text and the image in these layers\n\tif (document.all){ // IE\n\t\n\t\tdocument.all(layer_text).innerHTML = \"<h1 align='center'>Page loaded</h1>\";\n\t\tdocument.all(layer_img).innerHTML = \"\";\n\t\t\n\t} else if (document.getElementById) { // Firefox and others\n\t\n\t\tdocument.getElementById(layer_text).innerHTML = \"<h1 align='center'>Page loaded</h1>\";\n\t\tdocument.getElementById(layer_img).innerHTML = \"\";\n\t}\n\t\n\t// enable the button and modify foregroud color\n\teval(\"document.\"+formname+\".\"+buttonname+\".disabled = false\");\n\teval(\"document.\"+formname+\".\"+buttonname+\".style.color = '#000000'\");\n}",
"showContent () {\n this.loadingWrapper.style.display = 'none'\n this.canvas.style.display = 'block'\n }",
"function hidePlayer() {\r\n setBlockVis(\"annotations\", \"none\");\r\n setBlockVis(\"btnAnnotate\", \"none\");\r\n if (hideSegmentControls == true) { setBlockVis(\"segmentation\", \"none\"); }\r\n setBlockVis(\"player\", \"none\");\r\n}",
"function showMeasurementGraphLoadingOverlay() {\n $('#measurement-graph').LoadingOverlay(\"show\");\n\n setTimeout(function(){\n $('#measurement-graph').LoadingOverlay(\"hide\");\n }, 200);\n}",
"hide() {\n\n let svm = symbologyViewModel;\n let vm = this;\n\n svm.dictionary[svm.currentTab][vm.currentTypologyCode].isRadarDiagramVisible =\n !svm.dictionary[svm.currentTab][vm.currentTypologyCode].isRadarDiagramVisible;\n\n this.isVisible = false;\n\n $('#radarContainerVM').addClass('collapse');\n\n Spatial.sidebar.open('map-controls');\n\n $('#sidebar').removeClass('invisible');\n $('#sidebar').addClass('visible');\n\n }",
"hide() {\n\t\tthis.element.style.visibility = 'hidden';\n\t}",
"show() {\n\t\tthis.element.style.visibility = '';\n\t}",
"function hideLoadPage() {\n\tloadpageDiv.className = 'page transition up';\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
round the coordinates down for some perhaps overlyprecise input | function roundCoordinates(num) {
return Math.round(num * 10000) / 10000
} | [
"function fixLatLng(latlng) {\n\t\t\tlatlng[0] = latlng[0] * 2.6232 - 80.1968;\n\t\t\tlatlng[1] = latlng[1] * 1.964 + 159.8395;\n\t\t\treturn latlng;\n\t\t}",
"function convertCoordinates (ele)\r\n\t{\r\n\t\tvar gps = coordinates (ele); //gets the coordinates of the puzzle piece\r\n\r\n\t\tvar l = parseInt (gps[0], 10); //left value: x coordinate\r\n\t\tvar t = parseInt (gps[1], 10); //top value: y coordinate\r\n\r\n\t\tl = l/100;\r\n\t\tt = t/100;\r\n\r\n\t\treturn l + \" \" + t;\r\n\t}",
"function roundPoints(points, precision) {\n\n const pointsLength = points.length\n\n for (var i = 0; i < pointsLength; i++) {\n\n var point = points[i]\n\n if (point.selected !== PathPointSelection.ANCHORPOINT) {\n continue;\n }\n\n var prev = {\n lx: point.leftDirection[0],\n ly: point.leftDirection[1],\n rx: point.rightDirection[0],\n ry: point.rightDirection[1],\n ax: point.anchor[0],\n ay: point.anchor[1],\n }\n var ax = roundNumber(point.anchor[0], precision)\n var ay = roundNumber(point.anchor[1], precision)\n var moveX = ax - prev.ax\n var moveY = ay - prev.ay\n var lx = roundNumber(point.leftDirection[0] + moveX, precision)\n var ly = roundNumber(point.leftDirection[1] + moveY, precision)\n var rx = roundNumber(point.rightDirection[0] + moveX, precision)\n var ry = roundNumber(point.rightDirection[1] + moveY, precision)\n\n point.anchor = [ax, ay]\n point.leftDirection = [lx, ly]\n\n if ((lx === ax && ly === ay) || (rx === ax && ry === ay)) {\n\n point.pointType = PointType.SMOOTH\n\n } else if (isSmoothPoint(prev, precision)) {\n\n // Angle at leftDirection from [ax, ly] to anchor\n var angle = Math.atan2(ay - ly, ax - lx)\n // (Previous) distance between anchor and rightDirection\n var distance = Math.sqrt(Math.pow(prev.rx - prev.ax, 2) + Math.pow(prev.ry - prev.ay, 2))\n\n // Compute rx using distance and angle\n rx = roundNumber(ax + (distance * Math.cos(angle)), precision)\n // Compute ry using rx and slope\n if (ax !== lx) {\n // Slope from leftDirection to anchor\n var slope = (ay - ly) / (ax - lx)\n ry = ay + (slope * (rx - ax))\n }\n\n point.pointType = PointType.SMOOTH\n }\n\n point.rightDirection = [rx, ry]\n }\n}",
"function computeLatLng(location) {\n\tlet l = location.levels.length;\n\tlet x = location.x;\n\tlet y = location.y;\n\t\n\tfor (let i=l-1; i>=0; i--) {\n\t\tlet level = +location.levels[i];\n\t\tif (level === 1) {\n\t\t\tx /= 2;\n\t\t\ty = y/2 + 0.5;\n\t\t} else if (level === 2) {\n\t\t\tx /= 2;\n\t\t\ty /= 2;\n\t\t} else if (level === 3) {\n\t\t\tx = x/2 + 0.5;\n\t\t\ty /= 2;\n\t\t} else if (level === 0) {\n\t\t\tx = (1 - x)/2;\n\t\t\ty = (1 - y)/2;\n\t\t}\n// \t\tconsole.log(level, x,y);\n\t}\n\t\n\tx /= 1 - y;\n\tx *= 90;\n\ty *= 90;\n\t\n\tif (location.octant == 0) {\n\t\tx -= 180;\n\t} else if (location.octant == 1) {\n\t\tx -= 90;\n\t} else if (location.octant == 2) {\n\t\tx += 0;\n\t} else if (location.octant == 3) {\n\t\tx += 90;\n\t} else if (location.octant == 4) {\n\t\tx -= 180;\n\t\ty = -y;\n\t} else if (location.octant == 5) {\n\t\tx -= 90;\n\t\ty = -y;\n\t} else if (location.octant == 6) {\n\t\tx += 0;\n\t\ty = -y;\n\t} else if (location.octant == 7) {\n\t\tx += 90;\n\t\ty = -y;\n\t}\n\t\n\tlocation.lat = y;\n\tlocation.lng = x;\n\t\n\treturn location;\n}",
"function findBestCorner() {\n\t\t\n\t}",
"normalizeInputParameters() {\n if (this._max) this.handlePrecision(this._max);\n if (this._min) this.handlePrecision(this._min);\n if (this._step) this.handlePrecision(this._step);\n\n this._previousValue = this.value;\n }",
"function coordshift() {\n var key;\n var minx = Number.MAX_VALUE;\n var miny = Number.MAX_VALUE;\n for (key in inputobj.coords) {\n if (inputobj.coords.hasOwnProperty(key)) {\n var tempcoord = inputobj.coords[key];\n if (tempcoord[0] < minx) {\n minx = tempcoord[0];\n }\n if (tempcoord[1] < miny) {\n miny = tempcoord[1];\n }\n }\n }\n var xoffset = Math.max(0, 1 - minx); //if the smallest x value is -1, then an offset of 2 will be provided, etc.\n var yoffset = Math.max(0, 1 - miny);\n for (key in inputobj.coords) {\n if (inputobj.coords.hasOwnProperty(key)) {\n var tempcoord = inputobj.coords[key];\n tempcoord[0] += xoffset;\n tempcoord[1] += yoffset;\n inputobj.coords[key] = tempcoord;\n }\n }\n }",
"function hackMapProjection(lat, lon, originLat, originLon) {\n var lonCorrection = 1.5;\n var rMajor = 6378137.0;\n\n function lonToX(lon) {\n return rMajor * (lon * Math.PI / 180);\n }\n\n function latToY(lat) {\n if (lat === 0) {\n return 0;\n } else {\n return rMajor * Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI / 180) / 2));\n }\n }\n\n var x = lonToX(lon - originLon) / lonCorrection;\n var y = latToY(lat - originLat);\n return {'x': x, 'y': y};\n}",
"function handleRectify() {\n if (coords.length < 4) alert(\"Select 4 points!\");\n let [w, h] = findMinDims(coords);\n\n // Back-out any reduction to apply homography to full-size image\n w = Math.floor(w / reduction);\n h = Math.floor(h / reduction);\n let _coords = coords.map(c => [\n Math.floor(c[0] / reduction),\n Math.floor(c[1] / reduction)\n ]);\n\n // Apply magnification\n let magnify = Math.max(1, +document.getElementById(\"magnify\").value);\n w *= magnify;\n h *= magnify;\n\n solveHomography(_coords, [[0, 0], [w, 0], [w, h], [0, h]]);\n clearPoints();\n project(w, h);\n}",
"function getHighPrecisionSnapInterval(coords) {\n var maxCoord = Math.max.apply(null, coords.map(Math.abs));\n return maxCoord * 1e-14;\n}",
"function deg_to_min() {\n var lat_deg_decimal, long_deg_decimal;\n var lat_deg_value = parseFloat($(\".latitude input[name='lat_deg']\").val());\n var long_deg_value = parseFloat($(\".longitude input[name='long_deg']\").val());\n // Split the Degrees at Decimal point then subtract the Integer part from the Degrees to get the Decimal part\n lat_deg_decimal = parseFloat(lat_deg_value).toString().split(\".\");\n long_deg_decimal = parseFloat(long_deg_value).toString().split(\".\");\n lat_deg_decimal = (parseFloat(lat_deg_value) * 1000000 - parseInt(lat_deg_decimal[0]) * 1000000) / 1000000;\n long_deg_decimal = (parseFloat(long_deg_value) * 1000000 - parseInt(long_deg_decimal[0]) * 1000000) / 1000000 ;\n\n // Replace the Degrees value by Integer part only then Multiply the Decimal Degrees part by 60 to get the Minutes\n if(lat_deg_decimal > 0) {\n $(\".latitude input[name='lat_deg']\").val(parseInt(lat_deg_value));\n $(\".latitude input[name='lat_min']\").val(to_fixed(lat_deg_decimal * 60));\n }\n if(long_deg_decimal > 0) {\n $(\".longitude input[name='long_deg']\").val(parseInt(long_deg_value));\n $(\".longitude input[name='long_min']\").val(to_fixed(long_deg_decimal * 60));\n }\n}",
"function GroundResolution(latitude, levelOfDetail)\n\t{\n\t\tlatitude = Clip(latitude, MinLatitude, MaxLatitude);\n\t\treturn Math.cos(latitude * Math.PI / 180.0) * 2.0 * Math.PI * EarthRadius / MapSize(levelOfDetail);\n\t}",
"function adjustMouseCoords() {\n\t// adjust for zoom\n\txMouse /= zoomFactor;\n\tyMouse /= zoomFactor;\n\t// adjust for pan\n\t// first get viewBox info\n\tvar vBox = canvas.getAttribute(\"viewBox\").split(\" \");\n\tvar vBoxX = parseFloat(vBox[0]);\n\tvar vBoxY = parseFloat(vBox[1]);\n\tvar vBoxW = parseFloat(vBox[2]);\n\tvar vBoxH = parseFloat(vBox[3]);\n\t// then add the resulting offset\n\txMouse += vBoxX;\n\tyMouse += vBoxY;\n}",
"static normalize(rect) {\n if (rect.width < 0) {\n rect.width = -rect.width\n rect.x -= rect.width\n }\n\n if (rect.height < 0) {\n rect.height = -rect.height\n rect.y -= rect.height\n }\n }",
"function calcMouseCoords() {\n var xMid = canvasW / 2;\n var yMid = canvasH / 2;\n\n //var game0x = (xMid - camx * camzoom); (diff from 0x, then just scale mouse diff)\n gameMouseX = (rawMouseX - (xMid - camx * camzoom)) / camzoom; // + (rawMouseX)\n gameMouseY = (rawMouseY - (yMid - camy * camzoom)) / camzoom; //(rawMouseY) / camzoom;\n}",
"calculateDimensions() {\r\n let leftMostCoordinate = this.transformedPolygon[0][0],\r\n rightMostCoordinate = this.transformedPolygon[0][0],\r\n topMostCoordinate = this.transformedPolygon[0][1],\r\n bottomMostCoordinate = this.transformedPolygon[0][1];\r\n\r\n for(let i=0; i<this.transformedPolygon.length; i++) {\r\n if(this.transformedPolygon[i][0] < leftMostCoordinate) {\r\n leftMostCoordinate = this.transformedPolygon[i][0];\r\n } else if(this.transformedPolygon[i][0] > rightMostCoordinate) {\r\n rightMostCoordinate = this.transformedPolygon[i][0];\r\n }\r\n\r\n if(this.transformedPolygon[i][1] < topMostCoordinate) {\r\n topMostCoordinate = this.transformedPolygon[i][1];\r\n } else if(this.transformedPolygon[i][1] > bottomMostCoordinate) {\r\n bottomMostCoordinate = this.transformedPolygon[i][1];\r\n }\r\n }\r\n\r\n this.width = Math.abs(rightMostCoordinate - leftMostCoordinate);\r\n this.height = Math.abs(bottomMostCoordinate - topMostCoordinate);\r\n }",
"function clipSutherland() { \r\n\r\n clip1x = x1;\r\n clip1y = y1;\r\n clip2x = x2;\r\n clip2y = y2;\r\n\r\n var x = 0;\r\n var y = 0;\r\n var m = (clip2y - clip1y) / (clip2x - clip1x);\r\n\r\n var code1 = getCode(clip1x, clip1y);\r\n var code2 = getCode(clip2x, clip2y);\r\n\r\n while (code1 != INSIDE || code2 != INSIDE) {\r\n\r\n var clipCode;\r\n\r\n if ((code1 & code2) != INSIDE) {\r\n return false;\r\n }\r\n if (code1 == INSIDE) {\r\n clipCode = code2;\r\n }\r\n else { \r\n clipCode = code1\r\n }\r\n if ((clipCode & LEFT) != INSIDE) {\r\n x = xMin;\r\n y = (x - clip1x) * m + clip1y;\r\n }\r\n else if ((clipCode & RIGHT) != INSIDE) {\r\n x = xMax;\r\n y = (x - clip1x) * m + clip1y;\r\n }\r\n else if ((clipCode & BOTTOM) != INSIDE) {\r\n y = yMin;\r\n x = (y - clip1y) / m + clip1x;\r\n }\r\n else if ((clipCode & TOP) != INSIDE) {\r\n y = yMax;\r\n x = (y - clip1y) / m + clip1x;\r\n }\r\n if (clipCode == code1) {\r\n clip1x = x;\r\n clip1y = y;\r\n code1 = getCode(clip1x, clip1y);\r\n }\r\n else {\r\n clip2x = x;\r\n clip2y = y;\r\n code2 = getCode(clip2x, clip2y);\r\n }\r\n }\r\n return true;\r\n}",
"function sumPolygon(n) {\n\treturn (n-2) * 180;\n}",
"function val2between({\n xy, //function y(x) set as pairs in array [e1,e2]\n x, //\"anchor\" value of x,\n //By default y=e1, x=e2,\n inv, //inverse pairs, means x=e2, y=e1,\n }){\n var xy = xy;\n var alen = xy.length;\n var alen1 = xy.length-1;\n var indMax = alen - 1;\n var indMin = 0;\n\n var frDim = inv ? 1 : 0;\n var depDim = frDim ? 0 : 1;\n\n var xMax = xy[ alen-1 ][frDim];\n var xMin = xy[ 0 ][frDim];\n //virtual direction\n var xDir = xMax - xMin > 0;\n\n if( xDir === 0 ) {\n return { x, y : xy[0][depDim], indMin : 0, indMax : 0, xMin, xMax, };\n }\n var xDir = xDir > 0 ? 1 : -1;\n\n if( ( xMax - x ) * xDir < 0 ) {\n return { x, y : xy[alen1][depDim], indMin : alen1, indMax : alen1, xMin, xMax, };\n }\n if( ( xMin - x ) * xDir > 0 ) {\n return { x, y : xy[0][depDim], indMin : 0, indMax : 0, xMin, xMax, };\n }\n\n var count = 0; //todom remove this protector\n while( indMax-indMin > 1 ) {\n\n /*\n //*********************************************\n // //\\\\ interpolating algo\n //=============================================\n //this is an alternative to binary division algo,\n //for y = x^5, this ago takes 230 steps vs binary which has only 14\n var frMa = xy[ indMax ][1];\n var frMi = xy[ indMin ][1];\n var scaleY = ( frMa - frMi ) / ( indMax - indMin );\n var indMiddle = scaleY === 0 ? indMin : ( y - frMi ) / scaleY + indMin;\n var { indMin, indMax } = findsContaningInterval(\n indMiddle, indMin, indMax, xy );\n if( count++ > 300 ) {\n throw new Error( 'divergent algo' );\n }\n //=============================================\n // \\\\// interpolating algo\n //*********************************************\n */\n\n //*********************************************\n // //\\\\ binary division algo\n //=============================================\n //this is an alternative to interpolating algo\n var binaryMiddle = ( indMax + indMin ) / 2;\n var { indMin, indMax } = findsContaningInterval(\n binaryMiddle, indMin, indMax, xy, frDim );\n if( count++ > 200 ) {\n throw new Error( 'divergent algo?' );\n }\n //=============================================\n // //\\\\ binary division algo\n //*********************************************\n\n //ccc( { indMin, indMax, count } );\n }\n\n //final result:\n var frMa = xy[ indMax ][frDim];\n var frMi = xy[ indMin ][frDim];\n if( indMax === indMin || Math.abs( scaleY ) < 1e-100 ) {\n var y = xy[ indMin ][depDim];\n var indMiddle = indMin;\n } else {\n var scaleY = ( frMa - frMi ) / ( indMax - indMin );\n if( Math.abs( scaleY ) < 1e-100 ) {\n var y = xy[ indMin ][depDim];\n var indMiddle = indMin;\n } else {\n var yMa = xy[ indMax ][depDim];\n var yMi = xy[ indMin ][depDim];\n var scaleX = ( yMa - yMi ) / ( indMax - indMin );\n var y = scaleX * ( x - frMi ) / scaleY + yMi;\n var indMiddle = ( indMax - indMin ) * ( x - frMi ) / scaleY + indMin;\n }\n }\n return { x, y, indMin, indMax, xMin, xMax, indMiddle, count };\n\n\n\n\n function findsContaningInterval(\n indMiddle, //proposed new position of interval boundary\n indMin, //current\n indMax, //current\n xy, //main array\n frDim,\n ){\n var newMin = Math.floor( indMiddle );\n var newMax = Math.ceil( indMiddle );\n if( ( x - xy[ newMin ][frDim] ) * xDir < 0 ) {\n ////new Min is above x, take it as max\n indMax = newMin;\n } else if( ( x - xy[ newMax ][frDim] ) * xDir > 0 ) {\n ////new Max is below x, take it as min\n indMin = newMax;\n } else {\n ////x is in between grid cell, it can be newMin === newMax,\n indMin = newMin;\n indMax = newMax;\n }\n return { indMin, indMax };\n }\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Look for a existing file from a number of alternatives. | async function findFileMatch( basePath, path, exts, defaultPath ) {
// Iterate over the list of file extensions and test for each one.
for( const ext of exts ) {
const filePath = Path.join( basePath, `${path}.${ext}`);
if( await exists( filePath ) ) {
return filePath;
}
}
// No matches found, return the default path if it exists.
if( defaultPath && await exists( defaultPath ) ) {
return defaultPath;
}
// Nothing found.
return null;
} | [
"function find( filePath ){\n\tvar i,\n\t\tpathData = path.parse( filePath ),\n\t\tisAbsolute = path.isAbsolute( filePath ),\n\t\tMap = isAbsolute ?\n\t\t\t{\n\t\t\t\t'$BASE' : pathData.dir,\n\t\t\t\t'$DIR' : '',\n\t\t\t\t'$NAME' : pathData.name,\n\t\t\t\t//If no extension, then use the Current one\n\t\t\t\t'$EXT' : pathData.ext || this.Extension\n\t\t\t} :\n\t\t\t{\n\t\t\t\t'$BASE' : this.Base,\n\t\t\t\t'$INITIAL' : this.Initial,\n\t\t\t\t'$CURRENT' : path.parse(this.Location).dir,\n\t\t\t\t'$DIR' : pathData.dir,\n\t\t\t\t'$NAME' : pathData.name,\n\t\t\t\t//If no extension, then use the Current one\n\t\t\t\t'$EXT' : pathData.ext || this.Extension\n\t\t\t},\n\t\tPaths = getPaths( this.Format, Map, isAbsolute );\n\t\n\t//Traverse the Paths until a valid path is Found\n\tfor(i=0;i<Paths.length;i++){\n\t\tif( isFile( Paths[i] ) ){\n\t\t\treturn Resolution.resolve( new Finder( new FilePath( Paths[i], this.Initial, {\n\t\t\t\tBase : this.Base,\n\t\t\t\tFormat : this.Format,\n\t\t\t\tExtension : this.Extension,\n\t\t\t\tEncoding : this.Encoding\n\t\t\t})));\n\t\t}\n\t}\n\t\n\treturn Resolution.reject( new Error( '\\'' + filePath + '\\' does not resolve to a file' ) );\n}",
"function searchFileId(searchText) {\n if (searchText in cache.indexes) {\n return cache.content.files[cache.indexes[searchText]];\n }\n return false;\n}",
"static findFiles (dir) {\n return Walk.dir(dir)\n .catch({code: 'ENOENT'}, error => {\n error.message = `No such file or directory \"${error.path}\"`\n error.simple = `Failed to read templates for \"${this.base_name}\"`\n throw error\n })\n }",
"function checkFiles() {\n\t\tpkg.files &&\n\t\t\tpkg.files.forEach(pattern => {\n\t\t\t\t// skip patterns like \"!foo\"\n\t\t\t\tif (!pattern.startsWith('!')) {\n\t\t\t\t\tconst matchedFiles = globby.sync(pattern, {\n\t\t\t\t\t\tcwd: opts.cwd\n\t\t\t\t\t});\n\t\t\t\t\tif (matchedFiles.length === 0) {\n\t\t\t\t\t\tproblems.push({\n\t\t\t\t\t\t\tmessage: `cannot found file \"${pattern}\"(pkg.files).`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t}",
"static matchFilename(descs, filename) {\n for (let d of descs)\n if (d.filename && d.filename.test(filename)) return d\n let ext = /\\.([^.]+)$/.exec(filename)\n if (ext)\n for (let d of descs) if (d.extensions.indexOf(ext[1]) > -1) return d\n return null\n }",
"async findLaunchRegisteredApps(pattern, defaultPaths, suffixes) {\n const { stdout, } = await this.execa.command(`${this.lsRegisterCommand} | awk '$0 ~ /${pattern}${pathSuffixRe.source}?$/ { $1=\"\"; print $0 }'`, { shell: true, stdio: 'pipe' });\n const paths = [\n ...defaultPaths,\n ...stdout.split('\\n').map(l => l.trim().replace(pathSuffixRe, '')),\n ].filter(l => !!l);\n const preferred = this.getPreferredPath();\n if (preferred) {\n paths.push(preferred);\n }\n const installations = new Set();\n for (const inst of paths) {\n for (const suffix of suffixes) {\n const execPath = path_1.posix.join(inst.trim(), suffix);\n try {\n await this.fs.access(execPath);\n installations.add(execPath);\n }\n catch (e) {\n // no access => ignored\n }\n }\n }\n return installations;\n }",
"function findFileByAppName(array, appName) {\n if (array.length === 0 || !appName) return null;\n\n for (var i = 0; i < array.length; i++) {\n var path = array[i];\n if (path && path.indexOf(appName) !== -1) {\n return path;\n }\n }\n\n return null;\n }",
"function getExistingFile(filename, flag)\r\n{\r\n if (filename.length == 0 && flag)\r\n {\r\n var tempName = \"newRaffle\";\r\n var realName = tempName;\r\n var count = 0;\r\n\r\n while (fs.existsSync(tempName + \".json\"))\r\n {\r\n count++;\r\n tempName = realName + count;\r\n }\r\n\r\n tempName += \".json\";\r\n\r\n fs.openSync(tempName, 'w');\r\n fs.writeFileSync(tempName, \"{}\", (err) => {\r\n if (err)\r\n {\r\n console.log('\\x1b[31m%s\\x1b[0m', 'File failed to save.');\r\n process.exit();\r\n }\r\n })\r\n\r\n return tempName;\r\n }\r\n else if (filename.length == 0 && !flag)\r\n {\r\n return \"\";\r\n }\r\n else\r\n {\r\n while (!fs.existsSync(filename))\r\n {\r\n if (filename.toLowerCase() == \"quit\")\r\n {\r\n return \"quit\";\r\n }\r\n filename = readline.question(\"File not found, enter again or type QUIT: \\n\").trim();\r\n }\r\n }\r\n\r\n return filename;\r\n}",
"async function checkForArtwork(searchTerm) {\n const filePath = process.env.ARTWORK_PATH;\n console.log(`File path to artwork files: ${filePath}`);\n const checkFiles = await io.dirSearch(filePath, searchTerm);\n console.log('Matching Files');\n console.log(checkFiles);\n return checkFiles;\n}",
"function find_word(file_path,searchstring)\n{\n\tvar fso,f,s_SearchString,s_FilePath,s_FileContent;\n\tvar ForReading = 1, ForWriting = 2, ForAppending =8;\n\ts_SearchString = /searchstring/i;\n\t//s_SearchString = new String(searchstring);\n\ts_FilePath = new String (file_path);\n\tfso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\tf = fso.OpenTextFile(s_FilePath , ForReading);\n\ts_FileContent = new String (f.ReadAll());\n\tif (s_FileContent.search(s_SearchString) == -1)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn true;\n\t}\n}",
"function findFilePath (key) {\n let filePath = \"sounds/\"\n switch (key) {\n case \"w\":\n filePath += \"tom-1.mp3\"\n break;\n case \"a\":\n filePath += \"tom-2.mp3\"\n break;\n case \"s\":\n filePath += \"tom-3.mp3\"\n break\n case \"d\":\n filePath += \"tom-4.mp3\"\n break;\n case \"j\":\n filePath += \"snare.mp3\"\n break;\n case \"k\":\n filePath += \"crash.mp3\"\n break;\n case \"l\":\n filePath += \"kick-bass.mp3\"\n break;\n\n default: filePath = null;\n }\n return filePath;\n}",
"function pickSourceFile(file, minAssets, fullAssets) {\n\tif (minAssets.length > 0) {\n\t\tfile = minAssets[0];\n\t} else {\n\t\t//No min file, try to get latest full file.\n\t\tif (fullAssets.length > 0) {\n\t\t\tfile = fullAssets[0];\n\t\t}\n\t}\n\t\n\treturn file;\n}",
"function testPatternMatch (myTest, pattern, opts, re_file)\n{\n var tarball = fxs.constructedTar\n , entryList = fxs.constructedEntries\n \n readEntry(tarball, pattern, opts, function (tbErr, tbBuf) {\n if (tbErr) {\n myTest.fail(tbErr.message)\n return myTest.end()\n }\n\n var entryMatch\n , entryPath\n for (var i = 0; i < entryList.length; i++) {\n if (re_file.test(entryList[i])) {\n entryMatch = entryList[i]\n break\n }\n }\n if (!entryMatch) {\n throw new Error(\"No match for \"+re_file+\n \" against fixture entries of contructed.tar!\");\n }\n entryPath = path.resolve(__dirname, \"fixtures\", \"tarball_base\", entryMatch)\n\n fs.readFile(entryPath, function (fsErr, fsBuf) {\n if (fsErr) { myTest.fail(fsErr.message) }\n else {\n myTest.ok(tbBuf.equals(fsBuf), [\n \"Passing '\", pattern, \"' with opts \", JSON.stringify(opts),\n \" to readEntry() should yield same contents as \", entryMatch\n ].join(''))\n }\n myTest.end()\n })\n })\n}",
"findTemplateFiles ( dir_path ) {\n if (!dir_path) dir_path = this.path\n dir_path = path.resolve(this.base_path, this.base_name, 'files')\n return Walk.dir(dir_path).then( files => {\n return this.files = this.stripPrefixFromPaths(files, dir_path)\n })\n .catch({code: 'ENOENT'}, error => {\n error.original_message = error.message\n error.message = `Failed to read template set \"${this.base_name}\"\n No such file or directory \"${error.path}\"`\n throw error\n })\n }",
"async resolveAlternativeBinaryPath(platform) {\n const compatiblePlatforms = knownPlatforms.slice(1).filter(p => get_platform_1.mayBeCompatible(p, platform));\n const binariesExist = await Promise.all(compatiblePlatforms.map(async (platform) => {\n const filePath = this.getQueryEnginePath(platform);\n return {\n exists: await exists(filePath),\n platform,\n filePath,\n };\n }));\n const firstExistingPlatform = binariesExist.find(b => b.exists);\n if (firstExistingPlatform) {\n return firstExistingPlatform.filePath;\n }\n return null;\n }",
"function forEachFile(pathToFind,callback){\r\n if(!fs.existsSync(pathToFind)){\r\n return;\r\n }\r\n\t\tdir = ///$/.test(dir) ? dir : dir + '/';\r\n (function dir(dirpath, fn) {\r\n if(!dirpath.endsWith(\"/\")){\r\n dirpath += \"/\";\r\n }\r\n var files = fs.readdirSync(dirpath);\r\n for (var i in files) {\r\n var item = files[i];\r\n var info = fs.statSync(dirpath + \"/\" + item);\r\n if (info.isDirectory()) {\r\n dir(dirpath + item + '/', callback);\r\n } else {\r\n if(dirpath[dirpath.length-1] == \"/\"){\r\n callback(dirpath + item);\r\n }\r\n else{\r\n callback(dirpath + \"/\" + item);\r\n }\r\n \r\n }\r\n\r\n }\r\n\r\n })(pathToFind);\r\n}",
"_searchAndReplaceEntry(callback) {\n\n /**\n * Checks the entry html file for relative script, or link Paths.\n * If a match is found, it will prepend the version to the beginning\n * of the path.\n */\n replace({\n files: `${this.buildPath}/${this.options.entryHtml}`,\n replace: /(src=\"|href=\")(?!https?:\\/\\/)(?!\\.\\.\\/)\\.?\\/?([^\"]+\\.(js|css))\"/ig,\n with: `$1/${this.version}/$2\"`\n }, (error) => {\n\n if (error) {\n callback(error);\n }\n\n /**\n * For applications that store image paths (like react), we need to\n * use a replace regex to replace all paths to include the new version\n * directory.\n */\n replace({\n files: `${this.buildPath}/${this.output.filename}`,\n replace: /(?=\\w)([\\w\\/]+(?:\\.png|\\.jpg|\\.jpeg|\\.gif|\\.ttf|\\.otf|\\.eot|\\.mp4))|([\\.\\~\\-\\w\\/]+(?:\\.png|\\.jpg|\\.jpeg|\\.gif|\\.ttf|\\.otf|\\.eot|\\.mp4))\"/ig,\n with: `${this.version}$2\"`\n }, (error) => {\n\n if (error) {\n callback(error);\n }\n\n callback();\n });\n });\n }",
"function processFile(templatePath) {\n const template = fs.readFileSync(templatePath)\n return getAllMatches(template)\n}",
"function extPart_findInString(partName, theStr, findMultiple)\n{\n var retVal = null;\n var searchPatts = extPart.getSearchPatterns(partName);\n var quickSearch = extPart.getQuickSearch(partName);\n if (extUtils.findPatternsInString(theStr, quickSearch, searchPatts, findMultiple))\n {\n retVal = extUtils.extractParameters(searchPatts);\n }\n else if (extPart.DEBUG)\n {\n var MSG = new Array();\n MSG.push(\"match failed for participant: \" + partName);\n MSG.push(\"\");\n MSG.push(\"against string:\");\n MSG.push(theStr);\n MSG.push(\"\");\n MSG.push(\"using pattern:\");\n if (quickSearch && theStr.indexOf(quickSearch) == -1) {\n MSG.push(quickSearch);\n }\n else\n {\n for (var j=0; j < searchPatts.length; j++) {\n if (!searchPatts[j].match || !searchPatts[j].match.length) {\n MSG.push(searchPatts[j].pattern);\n }\n }\n }\n alert(MSG.join(\"\\n\"));\n }\n\n return retVal;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stockInfoURL() gets stock information based on stock symbol | function stockInfoURL(sym) {
var queryURL;
queryURL = IEXEndpoint + sym + IEXSuffix;
console.log("in stockInfoURL -- queryURL: " + queryURL);
$.ajax({
"method": "GET",
"url": queryURL
}).
done((response) => {
console.log("stock info response: " + JSON.stringify(response));
currentWatchRow.companyName = response.companyName;
currentWatchRow.website = response.website;
currentWatchRow.description = response.description;
}).
fail(() => {
console.log("Failure from Alpha Time Series function");
});
} | [
"function stockInfoURL(sym) {\n var queryURL;\n\n queryURL = IEXEndpoint + sym + IEXSuffix;\n console.log(\"in stockInfoURL -- queryURL: \" + queryURL);\n\n $.ajax({\n \"method\": \"GET\",\n \"url\": queryURL\n }).\n then((response) => {\n console.log(\"stock info response: \" + JSON.stringify(response));\n currentWatchRow.companyName = response.companyName;\n currentWatchRow.website = response.website;\n currentWatchRow.description = response.description;\n $(\"#stock-input\").show();\n }).\n fail(() => {\n console.log(\"Failure from IEX endpoint stock info function\");\n $(\"#stock-input\").show();\n });\n }",
"getStock(stockSymbol) {\n stockService.data(stockSymbol, (err, data) => {\n if (err) return this.handleError(err);\n\n const stock = JSON.parse(data);\n let stockData = stock.data.reverse().map(info => {\n return [\n (new Date(info[0])).getTime(),\n info[1]\n ]\n });\n\n // update chart with new data\n this.addStockToChart(stockSymbol, stockData);\n\n this.addStockToStockTable(stock.company, stock.symbol);\n });\n }",
"function displayStock(newCompany) {\n\n\n var proxy = \"https://cors-anywhere.herokuapp.com/\"\n var queryURL = proxy + [\"https://autoc.finance.yahoo.com/autoc?query=\" + newCompany + \"®ion=EU&lang=en-GB&x=NYSE\"];\n\n $.ajax({\n url: queryURL,\n method: \"GET\",\n crossDomain: true,\n }).done(function(response){\n console.log(response);\n \n var stockarry = [];\n\n \n if (response.ResultSet.Result.length === 0) {\n \n var nope = $(\"<p>\").text(\"No Stock Found\");\n\n $(\"#instructions\").addClass(\"hidden\");\n $(\"#stocktickers\").empty();\n $(\"#stocktickers\").append(nope);\n\n }else{\n for (i = 0; i < response.ResultSet.Result.length; i++) {\n if (response.ResultSet.Result[i].exchDisp === \"NYSE\") {\n stockarry.push(response.ResultSet.Result[i]);\n\n console.log(stockarry);\n\n var stockticker1 = stockarry[0].symbol;\n var stockname1 = stockarry[0].name;\n\n var stk1 = $(\"<p>\").text(stockname1 + \": \" + stockticker1);\n\n $(\"#instructions\").addClass(\"hidden\");\n $(\"#stocktickers\").empty();\n $(\"#stocktickers\").append(stk1)\n\n }else if (response.ResultSet.Result[i].exchDisp === \"NASDAQ\") {\n stockarry.push(response.ResultSet.Result[i]);\n\n console.log(stockarry);\n\n var stockticker1 = stockarry[0].symbol;\n var stockname1 = stockarry[0].name;\n\n var stk1 = $(\"<p>\").text(stockname1 + \": \" + stockticker1);\n\n $(\"#instructions\").addClass(\"hidden\");\n $(\"#stocktickers\").empty();\n $(\"#stocktickers\").append(stk1)\n\n }\n }\n }\n //stock ticker search function ends\n \n\n\n \n \n })\n }",
"function renderStockInfo(data) {\n var stockDiv = $(\"<div>\").addClass(\"card-body\").\n attr(\"id\",\"stock-info\"),\n cardh5 = $(\"<h5>\").addClass(\"card-title\"),\n cardBody = $(\"<p>\").addClass(\"card-text ticker-paragraph\"),\n addToWatchBtn = buildWatchBtn(data[\"1. symbol\"]),\n htmlText;\n\n // empty out any prior content of #stock-ticker-content\n $(\"#stock-ticker-content\").empty();\n\n cardh5.text(data[\"1. symbol\"]).\n attr(\"stock-sym\", data[\"1. symbol\"]);\n htmlText = \"Price: \" + numeral(data[\"2. price\"]).format(\"$0,0.00\") + \"<br />\";\n htmlText += \"Volume: \" + data[\"3. volume\"] + \"<br />\";\n htmlText += \"Company: <a href=\" + currentWatchRow.website + \" target=\\\"_blank\\\">\" + currentWatchRow.companyName + \"</a><br />\";\n htmlText += \"About: \" + currentWatchRow.description + \"<br />\";\n\n cardBody.html(htmlText).\n append(addToWatchBtn);\n\n stockDiv.append(cardh5, cardBody);\n $(\"#stock-ticker-content\").append(stockDiv);\n }",
"async getStocks (stockString) {\n\n return await axios.get(`https://portfolio-408-main.herokuapp.com/Portfol.io/Batch/Stock/${stockString}`);\n }",
"function renderStockInfo(data) {\n var stockDiv = $(\"<div>\").addClass(\"card-body\").\n attr(\"id\",\"stock-info\"),\n cardh5 = $(\"<h5>\").addClass(\"card-title\"),\n cardBody = $(\"<p>\").addClass(\"card-text ticker-paragraph\"),\n addToWatchBtn = buildWatchBtn(data[\"1. symbol\"]),\n buyBtn,\n htmlText;\n\n // empty out any prior content of #stock-ticker-content\n $(\"#stock-ticker-content\").empty();\n\n cardh5.text(data[\"1. symbol\"]).\n attr(\"stock-sym\", data[\"1. symbol\"]);\n htmlText = \"<strong>Price: </strong>\" + numeral(data[\"2. price\"]).format(\"$0,0.00\") + \"<br />\";\n htmlText += \"<strong>Volume: </strong>\" + numeral(data[\"3. volume\"]).format(\"0,0\") + \"<br />\";\n htmlText += \"<strong>Company: </strong><a href=\" + currentWatchRow.website + \" target=\\\"_blank\\\">\" + currentWatchRow.companyName + \"</a><br />\";\n htmlText += \"<strong>About: </strong>\" + currentWatchRow.description + \"<br />\";\n\n cardBody.html(htmlText).\n append(addToWatchBtn);\n\n // add buy option if user is logged in\n if (appUser.authenticated) {\n buyBtn = buildBuyBtn(data[\"1. symbol\"]);\n cardBody.append(buyBtn);\n }\n\n stockDiv.append(cardh5, cardBody);\n $(\"#stock-input\").show();\n $(\"#stock-ticker-content\").append(stockDiv);\n }",
"function getSymbol(company) {\n\n return new Promise((resolve, reject) => {\n\n const URL = 'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords=' + company + '&apikey=' + stockey;\n fetch(URL)\n .then(res => res.json())\n .then((res) => {\n\n resolve(res)\n\n }).catch((err) => reject(err));\n\n });\n}",
"function getDataRenderSummary(stockSymbol) {\n let dividendJsonUrl = makeDividendJsonUrl(stockSymbol);\n let stockQuoteJsonUrl = makeStockJsonUrl(stockSymbol);\n $.getJSON(dividendJsonUrl, data1 => {\n renderSummary(data1, stockSymbol, stockQuoteJsonUrl)\n }).error(e => { jsonErrorAlert(e) }); \n}",
"function topstock1() {\n homeStocksRef.on('value', getStockInfo1, errData);\n }",
"loadStocks() {\n stockService.get((err, data) => {\n if (err) return this.handleError(err);\n\n // the latest list of stocks on database\n const stocks = JSON.parse(data);\n\n // the list of stock symbols's currently on chart\n const chartedStockSymbols = this.stockChart.series.map((series) => {\n return series.name;\n });\n\n stocks.forEach((stock) => {\n // only get the pricing data of not-charted stock symbols\n if (chartedStockSymbols.indexOf(stock) == -1) {\n this.getStock(stock.symbol);\n }\n });\n\n this.stockSocket.start();\n });\n }",
"async function getHistDataBySymbol(...symbols) {\n try {\n const data = await te.getHistoricalMarkets((symbol = symbols))\n console.log('Historical data by symbol:', '\\n', data)\n } catch (error) {\n console.log(error)\n }\n}",
"async getPairs(baseSymbol) {\n let symbols;\n try {\n symbols = await axios.get(URL_BASE+'/api/v1/ticker/allPrices', {\n headers,\n });\n } catch (error) {\n console.log(`Error getting pairs for ${baseSymbol}: `, error);\n throw error;\n }\n // const baseSymbol = 'ETH';\n // ETH is in the name but in the last three char positions\n // If SYMBOLS is SGNLSETH, then length is 8\n // and ETH is at 012345, 5.\n symbols = symbols.data.filter((symbol) => {\n const ethPosition = symbol.symbol.indexOf(baseSymbol);\n return (ethPosition === symbol.symbol.length - baseSymbol.length);\n });\n\n symbols = symbols.map((symbol) => {\n return symbol.symbol;\n });\n console.log('symbols: ', symbols);\n return symbols;\n }",
"function stockDataRequest(ticker) {\n\n var apiKey = \"TFCCMLBLD91O6OFT\";\n var queryURL = \"https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY_ADJUSTED&symbol=\" + ticker + \"&apikey=\" + apiKey;\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n //changing the objects of objects into an array of objects\n var responseArray = [];\n for (item in response[\"Monthly Adjusted Time Series\"]) {\n responseArray.push(response[\"Monthly Adjusted Time Series\"][item]);\n }\n\n //storing 4 values in an array to show quarterly growth\n var quarterlyData = [];\n for (var i = 13; i > 0; i -= 4) {\n quarterlyData.push(responseArray[i][\"5. adjusted close\"]);\n }\n\n //check if the stock is worth buying and display it\n worthBuy(quarterlyData);\n\n //passing through the data we retrieved to the displayChart function to show the chart on screen\n displayChart(quarterlyData);\n displayStats(responseArray[0]);\n\n\n });\n}",
"function getStocks(){\n return JSON.parse(localStorage.getItem(STOCK_STORAGE_NAME));\n}",
"function getSongInfo(songTitle) {\n\n // Calls Spotify API to retrieve a track.\n spotify.search({ type: 'track', query: songTitle }, function (err, data) {\n if (err) {\n logOutput.error(err);\n return\n }\n\n var artistsArray = data.tracks.items[0].album.artists;\n\n // Array to hold artist names, when more than one artist exists for a song.\n var artistsNames = [];\n\n // Pushes artists for track to array.\n for (var i = 0; i < artistsArray.length; i++) {\n artistsNames.push(artistsArray[i].name);\n }\n\n // Converts artists array to string, and makes it pretty.\n var artists = artistsNames.join(\", \");\n\n // Prints the artist(s), track name, preview url, and album name.\n logOutput(\"Artist(s): \" + artists);\n logOutput(\"Song: \" + data.tracks.items[0].name)\n logOutput(\"Spotify Preview URL: \" + data.tracks.items[0].preview_url)\n logOutput(\"Album Name: \" + data.tracks.items[0].album.name);\n });\n\n\n\n}",
"function getStockSymbols(stocks) {\n var symbols = [], // empty array that is going to store our symbols\n counter, // keeps track of the current index in the array\n stock; // keeps track of the current stock in the array\n\n // three parts\n // first part is what we want to get executed, initializing the counter which will point to the first index in the array\n // second part is the condition that we want to be true as long as we want the for loop to continue, in this case we want\n // the for loop to continue as like as the counter is smaller than the length of the stocks\n // the third part is what we want to execute at the bottom of each iteration thru the loop, and in this case we want to\n // increment counter\n for(counter = 0; counter < stocks.length; counter++){\n // assigning stock at the index of the counter\n // were looping through each item in the stocks array and assigning it to variable stock\n stock = stocks[counter];\n // we are adding to the symbols array and pull out the symbol from the stock and add it to the symbols array\n symbols.push(stock.symbol);\n }\n\n return symbols;\n}",
"function fetchQuote (ticker) {\n console.log(`Fetching quote for ${ticker}...`)\n\n return new Promise((resolve, reject) => {\n const symbol = ticker === '^BVSP' ? ticker : `${ticker}.SA`\n\n yahooFinance.quote({\n symbol: symbol,\n modules: ['price']\n }).then(({ price }) => {\n resolve({\n ticker: ticker,\n previousClose: round(price.regularMarketPreviousClose),\n open: round(price.regularMarketOpen),\n high: round(price.regularMarketDayHigh),\n price: round(price.regularMarketPrice),\n low: round(price.regularMarketDayLow),\n volume: round(price.regularMarketVolume),\n requestTimestamp: new Date()\n })\n }).catch(err => {\n console.error(err)\n reject(err)\n })\n })\n}",
"getMarketCapSymbols() {\n // check cache\n let data = this._getMarketCapCachedData('symbols');\n if (undefined !== data) {\n return new Promise((resolve, reject) => {\n resolve(data);\n });\n }\n let path = '/marketCap/symbols';\n let url = this._getUrl(path);\n const params = {includeAliases:true};\n return this._sendRequest('get', url, {params:params}, (data) => {\n this._cacheMarketCapData('symbols', data)\n });\n\n}",
"function notifyStockInfo(inputs, info) {\n let message = \"```\\nStock: [STOCK_NAME]\\n\\nEvaluation dates: [START_DATE] to [END_DATE]\\n\\nStock Information:\\n[INFO]\\n```\";\n message = message.replace(\"[STOCK_NAME]\", inputs.stockSymbol);\n message = message.replace(\"[START_DATE]\", inputs.evalStartDate);\n message = message.replace(\"[END_DATE]\", inputs.evalEndDate);\n message = message.replace(\"[INFO]\", info);\n notify({\"text\": message, \"mrkdwn\": true});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate a SKILL command | function validateSkill (data, command) {
var invalidMsg = 'Invalid Command - (' + command.member.displayName() + ' SKILL): ';
var skill = new Skill(command.name, data);
if (!command.name) {
throw new Error(invalidMsg + 'command must include a skill name.');
} else if (!skill.is_set) {
throw new Error(invalidMsg + 'skill name ' + command.name + ' not found.');
} else if (!command.target.name && skill.target !== 'none') {
throw new Error(invalidMsg + 'command must include a target.');
}
return true;
} | [
"function validateItem (data, command) {\n var invalidMsg = 'Invalid Command - (' + command.member.displayName() + ' ITEM): ';\n var item = new Item(command.name, data);\n var ability;\n\n if (!command.name) {\n throw new Error(invalidMsg + 'command must include an item name.');\n } else if (!item.is_set) {\n throw new Error(invalidMsg + 'item ' + command.name + ' not found.');\n } else if (!item.hasItem(command.member)) {\n throw new Error(invalidMsg + 'inventory or equipment does not contain item ' + command.name);\n } else if (!command.target.name && item.target !== 'none') {\n throw new Error(invalidMsg + 'command must include a target');\n }\n\n ability = item.ability;\n if (ability) {\n switch (ability.type) {\n case 'SKILL':\n var skill = new Skill();\n if (!skill.findSkill(ability.name, data)) {\n throw new Error(invalidMsg + 'skill name ' + ability.name + ' not found.');\n }\n break;\n case 'SPELL':\n var spell = new Spell();\n if (!spell.findSpell(ability.name, data)) {\n throw new Error(invalidMsg + 'spell name ' + ability.name + ' not found.');\n }\n break;\n default:\n throw new Error(invalidMsg + 'unknown item ability type ' + ability.type);\n break;\n }\n }\n\n return true;\n }",
"function validateSpell (data, command) {\n var invalidMsg = 'Invalid Command - (' + command.member.displayName() + ' SPELL): ';\n var spell = new Spell(command.name, data);\n\n if (!command.name) {\n throw new Error(invalidMsg + 'command must include a spell name.');\n } else if (!spell.is_set) {\n throw new Error(invalidMsg + 'spell name ' + command.name + ' not found.');\n } else if (!command.target.name) {\n throw new Error(invalidMsg + 'command must include a target.');\n }\n\n if (command.member.type === 'character') {\n if (!spell.learned[command.member.job] || spell.level > command.member.level) {\n throw new Error(invalidMsg + 'this character cannot cast this spell.');\n }\n }\n \n return true;\n }",
"function validateParry (data, command) {\n // no additional validation necessary\n return true;\n }",
"function validateRun (data, command) {\n // no additional validation necessary\n return true;\n }",
"_validateAndParseCommandArguments() {\n const validationErrors = this._validateCommandArguments();\n\n if (validationErrors.length > 0) {\n _forEach(validationErrors, (error) => {\n throw error;\n });\n }\n }",
"function validateNone (data, command) {\n // good job!\n return true;\n }",
"isValidInputParams(context, word) {\n if (context < 0) {\n console.log(`Error: Context value ${context} should be zero or greater`);\n return false;\n }\n\n if (typeof this.mapWords[word] === 'undefined') {\n console.log(`Error: Word \"${word}\" is not present in the recording`);\n return false;\n }\n\n return true;\n }",
"function validateShift (data, command) {\n var invalidMsg = 'Invalid Command - (' + command.member.displayName() + ' SHIFT): ';\n var member_group = battleHelpers.groupType(command.member);\n var target_group = battleHelpers.groupType(command.target);\n command.name = (command.name || '').toLowerCase();\n var has_target = command.name !== 'new';\n\n if (!_.includes(['after', 'before', 'new'], command.name)) {\n throw new Error(invalidMsg + 'command must specify a location (BEFORE or AFTER or NEW) relative to the target.');\n } else if (has_target && !command.target.name) {\n throw new Error(invalidMsg + 'command must include a target.');\n } else if (has_target && member_group !== target_group) {\n throw new Error(invalidMsg + 'target must be in the ' + member_group + ' group.');\n } else if (has_target && command.member.group_index === command.target.group_index) {\n throw new Error(invalidMsg + 'target must come from a different group formation.');\n }\n\n if (has_target) {\n _.each(data.scenario.scenarios, function (scenario) {\n var group = scenario.battle[target_group].groups[command.target.group_index];\n var found = group && _.findIndex(group.members, { name : command.target.name });\n\n if (found !== -1) {\n if (group.members.length > 3) {\n throw new Error(invalidMsg + 'target group already contains the maximum amount of members.');\n }\n return false\n }\n });\n } else {\n _.each(data.scenario.scenarios, function (scenario) {\n var group = scenario.battle[member_group].groups[command.member.group_index];\n var found = group && _.findIndex(group.members, { name : command.member.name });\n\n if (found !== -1) {\n if (scenario.battle.has_fronts && !command.extra) {\n throw new Error(invalidMsg + 'command must specify a front name for this battle.');\n }\n return false;\n }\n })\n }\n\n return true;\n }",
"function invalidCommand(cmd) {\n\t\tconsole.log('Invalid Command', cmd);\n\t\tswitch(Math.floor(Math.random() * 4) + 1) {\n\t\t\tcase 1:\n\t\t\t\toutput.before(\"I don't know the word \\\"\"+cmd+\"\\\".<br />\");\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\toutput.before(\"We're not going down that road again!<br /><br />\");\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\toutput.before(\"What a concept!<br /><br />\");\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\toutput.before(\"Sorry, my memory is poor. Please give a direction.<br /><br />\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput.before(\"I'm not sure i get it!.<br /><br />\");\n\t\t}\n\t\tscrollDown();\n\t}",
"function inputValidation(item){\n const inputSchema = {\n Name: Joi.string().min(4).max(125).required(),\n Description:Joi.string().min(4).max(1024).required(),\n Price: Joi.number().min(5).required(),\n Categery: Joi.string().max(20).required().required(),\n SellingBy: Joi.string(),\n }\n \n return Joi.validate(item, inputSchema)\n}",
"function validateDismiss (data, command) {\n var invalidMsg = 'Invalid Command - (' + command.member.displayName() + ' DISMISS): ';\n var recruit = _.find(data.recruit, { name : command.name, owner : command.member.name });\n\n if (!recruit) {\n throw new Error(invalidMsg + 'recruit named ' + command.name + ' was not found.');\n }\n\n _.each(data.scenario.scenarios, function (scenario) {\n if (_.findIndex(scenario.characters, { name : command.member.name }) > -1) {\n if (_.findIndex(scenario.allies, { name : command.name, owner : command.member.name }) === -1) {\n throw new Error(invalidMsg + 'recruit named ' + command.name + ' is not in the battle.');\n }\n }\n\n return false;\n });\n\n return true;\n }",
"validateKeyFormat(key) {\n if (key.split('-').length !== 3) {\n console.error('Invalid key format. Please try your command again.');\n process.exit(1);\n }\n return;\n }",
"function validateRecall (data, command) {\n var invalidMsg = 'Invalid Command - (' + command.member.displayName() + ' RECALL): ';\n var recruit = _.find(data.recruit, { name : command.name, owner : command.member.name });\n var target = command.target;\n var group_index;\n var target_group;\n\n if (!recruit) {\n throw new Error(invalidMsg + 'recruit named ' + command.name + ' was not found.');\n }\n\n _.each(data.scenario.scenarios, function (scenario) {\n if (_.findIndex(scenario.characters, { name : command.member.name }) > -1) {\n if (_.findIndex(scenario.allies, { name : command.name, owner : command.member.name }) > -1) {\n throw new Error(invalidMsg + 'recruit named ' + command.name + ' is already in the battle.');\n } else if (_.filter(scenario.allies, { type : 'monster' }).length >= 4) {\n throw new Error(invalidMsg + 'this battle already contains the maximum number of monster allies.');\n }\n\n // validate target\n if (target.name && battleHelpers.groupType(target) !== 'allies') {\n throw new Error(invalidMsg + 'monster recruits can only join ally groups.');\n }\n\n group_index = _.result(_.find(scenario.allies, { owner : command.member.name }), 'group_index');\n if (group_index === -1) {\n // this recruit must create a new group by itself\n if (target.name) {\n throw new Error(invalidMsg + 'target is not in a valid group for ' + command.name + ' to join.');\n }\n\n } else {\n // this recruit must join others from the same owner\n if (!target.name) {\n // no target specified; add to back of group\n target_group = scenario.battle.allies.groups[group_index];\n target = target_group.members[target_group.members.length - 1];\n command.target = target;\n command.extra = 'after';\n\n }\n if (target.name && target.group_index !== group_index) {\n throw new Error(invalidMsg + 'target is not in a valid group for ' + command.name + ' to join.');\n }\n }\n\n return false;\n }\n });\n\n return true;\n }",
"function validateRetreat (data, command) {\n var invalidMsg = 'Invalid Command - (' + command.member.displayName() + ' RETREAT): ';\n var member_group = battleHelpers.groupType(command.member);\n var target_group = battleHelpers.groupType(command.target);\n\n if (member_group !== target_group) {\n throw new Error(invalidMsg + 'target must be in the ' + member_group + ' group.');\n } else if (command.member.group_index !== command.target.group_index) {\n throw new Error(invalidMsg + 'target must come from the same group formation.');\n } else {\n return true;\n }\n }",
"_validateCommandArguments() {\n const validatedCommandList = _map(this.commandList, (command) => {\n if (typeof command === 'undefined') {\n return null;\n }\n\n const errorMessage = command.validateArgs();\n\n if (errorMessage) {\n // we only return here so all the errors can be thrown at once\n // from within the calling method\n return errorMessage;\n }\n\n command.parseArgs();\n });\n\n return _compact(validatedCommandList);\n }",
"function isCommand(c){\n for(s = 0; s < valids.length; s++){\n if(c == valids[s]){\n return true;\n }\n }\n return false;\n}",
"function sanitizeCmd(input) {\r\n input = input.split(' ')\r\n //sanitize the array\r\n for (var i in input) {\r\n input[i] = input[i].toLowerCase().replace(/[^\\w\\s]/gi, '')\r\n }\r\n return {\r\n 'command': input[0],\r\n 'args': input.slice(1) //array slice the command off the args list\r\n }\r\n}",
"function getPromptQuestions (argvOptions, inputArgs) {\n var questions = [];\n for (var argI in argvOptions) {\n if (inputArgs[argvOptions[argI].name] === undefined) {\n switch (argvOptions[argI].name) {\n case 'skillname':\n questions.push({\n name: 'skillname',\n type: 'input',\n message: 'Skill name:',\n validate: function (value) {\n if (value.length) {\n return true;\n } else {\n return 'Please enter the skill name.';\n }\n }\n });\n break;\n case 'skillVersion':\n questions.push({\n name: 'skillversion',\n type: 'input',\n message: 'Enter the skill version:',\n validate: function (value) {\n if (value.length) {\n return true;\n } else {\n return 'Please provide a skill version.';\n }\n }\n });\n break;\n case 'entityname':\n questions.push({\n name: 'entityname',\n type: 'input',\n message: 'Entity name:',\n validate: function (value) {\n if (value.length) {\n return true;\n } else {\n return 'Please enter the entity name.';\n }\n }\n });\n break;\n case 'datapath':\n questions.push({\n name: 'datapath',\n type: 'input',\n message: 'Full patch file path:',\n validate: function (value) {\n if (value.length) {\n const path = (value.indexOf('~/') === 0) ? value.replace('~', os.homedir()) : value;\n if (!fs.existsSync(path)) {\n return value + ' doesn\\'t exist.';\n }\n return true;\n } else {\n return 'Please enter the full patch file path.';\n }\n }\n });\n break;\n case 'configpath':\n questions.push({\n name: 'configpath',\n type: 'input',\n message: 'Full config file path:',\n validate: function (value) {\n if (value.length) {\n const path = (value.indexOf('~/') === 0) ? value.replace('~', os.homedir()) : value;\n if (!fs.existsSync(path)) {\n return value + ' doesn\\'t exist.';\n }\n return true;\n } else {\n return 'Please enter the full configuration file path.';\n }\n }\n });\n break;\n };\n };\n };\n return questions;\n}",
"validateInstruction(instruction) {\n if (!instruction.match(/^\\+\\d{4}$/)) return false\n const checkOpCode = instruction.substring(1, 3)\n if (!this.validOpCodes.includes(parseInt(checkOpCode))) return false\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility function to extract database reference from resource string | function resourceToInstanceAndPath(resource) {
let resourceRegex = `projects/([^/]+)/instances/([^/]+)/refs(/.+)?`;
let match = resource.match(new RegExp(resourceRegex));
if (!match) {
throw new Error(`Unexpected resource string for Firebase Realtime Database event: ${resource}. ` +
'Expected string in the format of "projects/_/instances/{firebaseioSubdomain}/refs/{ref=**}"');
}
let [, project, dbInstanceName, path] = match;
if (project !== '_') {
throw new Error(`Expect project to be '_' in a Firebase Realtime Database event`);
}
let dbInstance = 'https://' + dbInstanceName + '.firebaseio.com';
return [dbInstance, path];
} | [
"function formatDynamicDataRef(str, format)\n{\n var ret = str;\n var iStart = str.indexOf(\"<%#\", 0);\n\n if (iStart > -1)\n {\n var iEnd = str.indexOf(\"%>\", iStart+1);\n \n\tif (iEnd > -1)\n {\n \t var dataRef = dwscripts.trim(str.substring(iStart+3, iEnd));\n \n\t // Replace ([\\s\\S]+) with dataRef\n\t // Replace \\s* with a space\n\t // Replace single quotes with double quotes\n\t // Remove rest of backslashes\n\n\t ret = format.expression;\n\n\t ret = ret.replace(/\\(\\[\\\\s\\\\S\\]\\+\\)/g, dataRef);\n\t ret = ret.replace(/\\\\s\\*/g, \" \");\n\t ret = ret.replace(/"/g, \"\\\"\");\n\t ret = ret.replace(/\\\\/g, \"\");\n }\n else\n {\n // Error: no termination of the ASP.Net block.\n }\n }\n else\n {\n // Error: no start of ASP.Net block.\n }\n \n return ret;\n}",
"byIdOrName (resource_identifier) {\n let uuid_regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n if (resource_identifier.match(uuid_regex)) return 'id';\n return 'name';\n }",
"function extractCitationReferenceInfo(id) {\n var md = id.match(/^ref_([^_]+)_([0-9])+$/);\n return (md && {id: md[1], count: parseInt(md[2])}) || null;\n}",
"ref(path = \"/\") {\n return this._mocking ? this.mock.ref(path) : this._database.ref(path);\n }",
"function parseUri(resourceUri) {\n var matchInd, matches, containerUrl;\n if (resourceUri.indexOf('http') !== 0) { // relative uri case\n if (resourceUri.indexOf('/dc/') !== 0) { // assuming modelType and optional query case\n resourceUri = '/dc/type/' + resourceUri;\n }\n matches = /^\\/+dc\\/+(type|h)\\/+([^\\/\\?]+)\\/*([^\\?]+)?\\??(.*)$/g.exec(resourceUri);\n containerUrl = dcConf.containerUrl;\n matchInd = 0;\n } else {\n matches = /^(http[s]?):\\/\\/+([^\\/]+)\\/+dc\\/+(type|h)\\/+([^\\/\\?]+)\\/*([^\\?]+)?\\??(.*)$/g.exec(resourceUri);\n containerUrl = matches[1] + '://' + matches[2];\n matchInd = 2;\n }\n /*var pInd = resourceUri.indexOf('/dc/type/');\n var containerUrl = resourceUri.substring(0, pInd);\n var mInd = pInd + '/dc/type/'.length;\n var nextSlashInd = resourceUri.indexOf('/', mInd);\n var encModelType = resourceUri.substring(mInd, (nextSlashInd !== -1) ? nextSlashInd : resourceUri.length);\n var encId = resourceUri.substring(resourceUri.indexOf('/', mInd) + 1);\n if (containerUrl.length === 0) {\n containerUrl = dcConf.containerUrl;\n resourceUri = containerUrl + resourceUri;\n }\n return {\n containerUrl : containerUrl,\n modelType : decodeURIComponent(encModelType),\n id : decodeURI(encId),\n uri : resourceUri\n };*/\n \n var isHistory = matches[matchInd + 1] // else is a find\n && matches[matchInd + 1] === 'h';\n var encodedModelType = matches[matchInd + 2];\n var modelType = decodeURIComponent(encodedModelType); // required ; assuming that never contains %\n // NB. modelType should be encoded as URIs, BUT must be decoded before used as GET URI\n // because swagger.js re-encodes\n var encodedId = matches[matchInd + 3];\n var query = matches[matchInd + 4]; // no decoding, else would need to be first split along & and =\n var version = null;\n if (isHistory) {\n try {\n var versionSlashIndex = encodedId.lastIndexOf('/');\n version = parseInt(encodedId.substring(versionSlashIndex + 1));\n if (encodedId) {\n encodedId = encodedId.substring(0, versionSlashIndex);\n }\n } catch (e) {}\n }\n\n var uri = containerUrl + '/dc/type/' + encodedModelType;\n \n var id = null;\n if (encodedId) {\n id = decodeURIComponent(encodedId); // and not decodeURI else an URI won't be decoded at all\n // ex. \"https%3A%2F%2Fwww.10thingstosee.com%2Fmedia%2Fphotos%2Ffrance-778943_HjRL4GM.jpg\n uri += '/' + encodedId;\n }\n if (!query) {\n query = null;\n }\n if (query !== null) {\n uri += '?' + query;\n }\n return {\n containerUrl : containerUrl,\n modelType : modelType, // decoded\n id : id,\n encodedId : encodedId,\n version : version, // only if isHistory\n query : query, // encoded\n uri : uri // resourceUri\n };\n }",
"_findResource(id) {\n return this.template.resources.find(res => {\n // Simple match on substring is possible after \n // fully resolving names & types\n return res.fqn.toLowerCase().includes(id.toLowerCase());\n });\n }",
"function getBranch(payload) {\n\n if ( payload.ref ) {\n // ref example: \"refs/tags/simple-tag\", this will get the last string\n return payload.ref.split(\"/\")[2];\n } else {\n return payload.pull_request.head.ref;\n }\n\n}",
"function readURL(id, callback) {\n \n console.log(\"Attempting database query against id: \" + id);\n \n db.collection(DB_COLLECTION_NAME).findOne({ \"short_url_id\": id }, function(err, doc) { \n if (err) {\n console.error(err);\n // Error in reading from database\n callback(null);\n }\n \n if (doc) {\n // Document was retrieved, return the url corresponding to the short id.\n callback(doc.original_url);\n } else {\n // No Document with that id was found in the database\n callback(null);\n }\n });\n \n}",
"function hyperDbKeyToId (key) {\n var components = key.split('/')\n return components[components.length - 1]\n}",
"function _getMongoDbName(str) {\n if (!/[/\\. \"*<>:|?@]/.test(str)) {\n return str;\n }\n \n str = str.replace(/\\//g, exports.constants.slash);\n str = str.replace(/\\\\/g, exports.constants.backslash);\n str = str.replace(/\\./g, exports.constants.dot);\n str = str.replace(/ /g, exports.constants.space);\n str = str.replace(/\"/g, exports.constants.doubleQuotes);\n str = str.replace(/\\*/g, exports.constants.star);\n str = str.replace(/</g, exports.constants.lessThan);\n str = str.replace(/>/g, exports.constants.greaterThan);\n str = str.replace(/:/g, exports.constants.colon);\n str = str.replace(/\\|/g, exports.constants.pipe);\n str = str.replace(/\\?/g, exports.constants.questionMark);\n str = str.replace(/@/g, exports.constants.at);\n\n return str;\n }",
"function TQualifiedReference(qname) {\n this.qname = qname; // string\n}",
"getInvoiceReference(invoice) {\n if (invoice.slug && !invoice.slug.startsWith('transaction-')) {\n return invoice.slug;\n }\n\n if (invoice.dateFrom && invoice.dateTo) {\n const startString = moment.utc(invoice.dateFrom).format('YYYYMMDD');\n const endString = moment.utc(invoice.dateTo).format('YYYYMMDD');\n return `${invoice.host.slug}_${invoice.fromCollective.slug}_${startString}-${endString}`;\n }\n\n return invoice.slug\n .split('-')\n .slice(0, 2)\n .join('-');\n }",
"function getId(dbEntity){\n return dbEntity.entity.key.path[0].id ||\n dbEntity.entity.key.path[0].name;\n}",
"function resolveType(aResource,RDF,BMDS)\n{\n\tvar type = getProperty(aResource,\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\",RDF,BMDS);\n\tif (type != \"\")\n\t\ttype = type.split(\"#\")[1];\n\n\tif (type==\"\")\n\t\ttype=\"Immutable\";\n\treturn type;\n}",
"static getReliableURItoLocateTarget (annotation) {\n if (_.has(annotation, 'target[0].source')) {\n const source = annotation.target[0].source\n // The most reliable source is DOI\n if (source.doi) {\n return source.doi\n }\n // The next more reliable URI is the URL, but only if it is not a local URL (protocol = file:) or is URN (protocol = urn:)\n if (source.url) {\n const protocol = new URL(source.url).protocol\n if (protocol !== 'file:' && protocol !== 'urn:') {\n return source.url\n }\n }\n }\n // For Hypothes.is it is not stored in source, is stored in documentMetadata\n if (_.has(annotation, 'documentMetadata')) {\n const documentMetadata = annotation.documentMetadata\n // The most reliable source is DOI\n if (_.has(documentMetadata, 'dc.identifier[0]')) {\n return documentMetadata.dc.identifier[0]\n }\n // The next more reliable URI is the URL, but only if it is not a local URL (protocol = file:)\n const reliableURL = annotation.documentMetadata.link.find(link => {\n const protocol = new URL(link.href).protocol\n return protocol !== 'urn:' && protocol !== 'file:'\n })\n if (reliableURL) {\n return reliableURL.href\n }\n }\n if (new URL(annotation.uri).protocol !== 'file:') {\n return annotation.uri\n }\n return null\n }",
"itemCollectionDbRef(uid, archiveId) {\n return firebase\n .firestore()\n .collection(\"archives\")\n .doc(uid)\n .collection(\"userarchives\")\n .doc(archiveId)\n .collection(\"items\");\n }",
"function get_Nature(theURL,mycompstr) {\r\n var theDOI = theURL.substring(mycompstr.length,theURL.length+1);\r\n return theDOI;\r\n}",
"get resourceRecordName() {\n return this.getStringAttribute('resource_record_name');\n }",
"getDatabaseName() {\n return this.application_id + '!' + this.name;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw a line on the given context from point `x1,y1` to point `x2,y2`. | function line(ctx, x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
} | [
"drawLine(start_x, start_y, end_x, end_y) {\n this.ctx.moveTo(start_x, start_y);\n this.ctx.lineTo(end_x, end_y);\n }",
"function renderLine(ctx, start, end) {\n ctx.save();\n\n ctx.beginPath();\n ctx.moveTo(start.x, start.y);\n ctx.lineTo(end.x, end.y);\n\n ctx.stroke();\n ctx.restore();\n}",
"function drawLineSegment(x1, y1, x2, y2, color, width) {\n if (color == undefined) color = colors[0];\n if (width == undefined) width = LINE_WIDTH;\n\n\tif(x1 != NaN && y1 != NaN && x1 != NaN && y2 != NaN && math.abs(y2-y1) < 10)\n\t{\n\t\tx1 = transformX(x1);\n\t\ty1 = transformY(y1);\n\t\tx2 = transformX(x2);\n\t\ty2 = transformY(y2);\n\n\t\tcontext.beginPath();\n\t\tcontext.moveTo(x1, y1);\n\t\tcontext.lineTo(x2, y2);\n\n\t\tcontext.strokeStyle = color;\n\t\tcontext.lineWidth = width;\n\t\tcontext.stroke();\n\t}\n}",
"function Line( x1, y1, x2, y2 ){\n this.startX = x1;\n this.startY = y1; \n this.endX = x2; \n this.endY = y2;\n}",
"breshnamDrawLine (point0, point1) {\n let x0 = point0.x >> 0;\n let y0 = point0.y >> 0;\n let x1 = point1.x >> 0;\n let y1 = point1.y >> 0;\n let dx = Math.abs(x1 - x0);\n let dy = Math.abs(y1 - y0);\n let color = new BABYLON.Color4(1,1,0,1);\n\n if(dy > dx){\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dx - dy;\n\n for(let y=y0; y!=y1; y=y+sy){\n this.drawPoint(new BABYLON.Vector2(x0, y), color);\n if(err >= 0) {\n x0 += sx ;\n err -= dy;\n }\n err += dx;\n }\n }\n else{\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dy - dx;\n\n for(let x=x0; x!=x1; x=x+sx){\n this.drawPoint(new BABYLON.Vector2(x, y0), color);\n if(err >= 0) {\n y0 += sy ;\n err -= dx;\n }\n err += dy;\n }\n }\n }",
"function drawDashLine(ctx, x1, y1, x2, y2, dashLen) {\n if (dashLen === undefined || dashLen === null)\n dashLen = 2;\n ctx.moveTo(x1, y1);\n\n var dX = x2 - x1;\n var dY = y2 - y1;\n var dashes = Math.floor(Math.sqrt(dX * dX + dY * dY) / dashLen);\n var dashX = dX / dashes;\n var dashY = dY / dashes;\n\n var q = 0,\n currX = x1,\n currY = y1;\n while (q++ < dashes) {\n currX += dashX;\n currY += dashY;\n if (q % 2 === 0 )\n ctx.moveTo(currX, currY);\n else\n ctx.lineTo(currX, currY);\n }\n ctx.lineTo(x2, y2);\n }",
"function RoadLine(x1, y1, x2, y2) {\n\tthis.startX1 = x1;\n\tthis.startY1 = y1;\n\tthis.diffX = x2 - x1;\n\tthis.diffY = y2 - y1;\n\t\n\tthis.x1 = x1;\n\tthis.y1 = y1;\n\tthis.x2 = x2;\n\tthis.y2 = y2;\n\t\n\t//Draws Road Lines.\n\tthis.draw = function() {\n\t\tctx.beginPath();\n\t\tctx.lineCap = \"round\";\n\t\tctx.moveTo(this.x1, this.y1);\n\t\tctx.lineTo(this.x2, this.y2);\n\t\tctx.closePath();\n\t\tctx.strokeStyle = \"white\";\n\t\tctx.lineWidth = \"10\";\n\t\tctx.stroke();\n\t}\n\t\n\t// Make modifications to animate the roadline. \n\tthis.update = function() {\n\t\tthis.x1 += speed * 2;\n\t\tthis.y1 += speed * 2 * slope;\n\t\tthis.x2 = this.x1 - this.diffX;\n\t\tthis.y2 = this.y1 - this.diffY;\n\t\t\n\t\tif (this.x1 > canvas.width) {\n\t\t\tthis.x2 = 0;\n\t\t\tthis.y2 = 576;\n\t\t\tthis.x1 = this.x2 - this.diffX;\n\t\t\tthis.y1 = this.y2 - this.diffY;\n\t\t} \n\t\t\n\t\tthis.draw();\n\t}\n}",
"function drawRoad(x1, y1, x2, y2, color) {\n ctx.beginPath();\n if (Math.abs(x1 - x2) > EPS) {\n ctx.moveTo(x1, y1 + 5);\n ctx.lineTo(x2, y2 + 5);\n ctx.lineTo(x2, y2 - 5);\n ctx.lineTo(x1, y1 - 5);\n } else if (y1 > y2) {\n ctx.moveTo(x1 - 4.5, y1 - 5);\n ctx.lineTo(x2 - 4.5, y2 + 5);\n ctx.lineTo(x2 + 4.5, y2 + 5);\n ctx.lineTo(x1 + 4.5, y1 - 5);\n } else if (y2 > y1) {\n ctx.moveTo(x1 - 4.5, y1 + 5);\n ctx.lineTo(x2 - 4.5, y2 - 5);\n ctx.lineTo(x2 + 4.5, y2 - 5);\n ctx.lineTo(x1 + 4.5, y1 + 5);\n }\n ctx.closePath();\n ctx.fillStyle = COLORS[color];\n ctx.fill();\n ctx.stroke();\n }",
"function drawTriangle(context2D, x1, y1, x2, y2, x3, y3) {\n context2D.beginPath();\n context2D.moveTo(x1, y1);\n context2D.lineTo(x2, y2);\n context2D.stroke();\n\n context2D.beginPath();\n context2D.moveTo(x2, y2);\n context2D.lineTo(x3, y3);\n context2D.stroke();\n\n context2D.beginPath();\n context2D.moveTo(x3, y3);\n context2D.lineTo(x1, y1);\n context2D.stroke();\n}",
"function drawLine() {\n let draw = game.add.graphics();\n draw.lineStyle(1, 0xffffff, .3);\n\n draw.moveTo(star1.worldPosition.x + 8, star1.worldPosition.y + 8)\n draw.beginFill();\n draw.lineTo(star2.worldPosition.x + 8, star2.worldPosition.y + 8);\n draw.endFill();\n\n connections.push({\n drawer: draw,\n star1: [star1.worldPosition.x + 8, star1.worldPosition.y + 8],\n star2: [star2.worldPosition.x + 8, star2.worldPosition.y + 8]\n });\n deselectStars();\n }",
"drawLine() {\r\n line(this.left.x, this.left.y, this.right.x, this.right.y);\r\n }",
"function _updateLine(args){\n\t\targs.line.setShape({\n\t\t\tx1 : args.startPoint.x,\n\t y1 : args.startPoint.y,\n\t x2 : args.endPoint.x,\n\t y2 : args.endPoint.y\n\t });\n\t\targs.selectArea.setShape({\n\t\t\tx1 : args.startPoint.x,\n\t y1 : args.startPoint.y,\n\t x2 : args.endPoint.x,\n\t y2 : args.endPoint.y\n\t });\n\t}",
"function lineEquation(pt1, pt2) {\n if (pt1.x === pt2.x) {\n return pt1.y === pt2.y ? null : {\n x: pt1.x\n };\n }\n\n var a = (pt2.y - pt1.y) / (pt2.x - pt1.x);\n return {\n a: a,\n b: pt1.y - a * pt1.x,\n };\n }",
"function createLine(element1, element2) {\n let line = document.createElementNS('http://www.w3.org/2000/svg', 'line');\n let x1 = getOffset(element1).left + (getWidth(element1) / 2);\n let y1 = getOffset(element1).top + (getHeight(element1));\n let x2 = getOffset(element2).left + (getWidth(element2) / 2);\n //let y2 = getOffset(element2).top + (getHeight(element2) / 4);\n let y2 = getOffset(element2).top;\n line.setAttributeNS(null, 'x1', x1);\n line.setAttributeNS(null, 'y1', y1);\n line.setAttributeNS(null, 'x2', x2);\n line.setAttributeNS(null, 'y2', y2);\n svg.appendChild(line);\n console.log(line);\n}",
"function drawRegressionLine() {\n let startPoint = regressionLine(90); \n let endPoint = regressionLine(122); \n startPoint = toCanvasPoint(startPoint);\n endPoint = toCanvasPoint(endPoint);\n line(startPoint.x, startPoint.y, endPoint.x, endPoint.y);\n}",
"function nearestPointOnLine(px,py,x1,y1,x2,y2){\n\n\tvar lx = x2 - x1;\n var ly = y2 - y1;\n\t\n if ( lx == 0 && ly == 0 ) {//If the vector is of length 0,\n\t\t//the two endpoints have the same position, so the nearest point is at that position\n return {\n\t\t\tx: x1,\n\t\t\ty: y1\n\t\t};\n } else {\n\t\t//Find the factor for how far along the line, from <x1,y1>, the nearest point is\n var g = ((px - x1) * lx + (py - y1) * ly) / (lx * lx + ly * ly);\n\t\tif( g < 0 ) g = 0;\n\t\telse if( g > 1 ) g = 1;\n\t\t//And calculate the nearest point\n\t\treturn new Point(x1 + g * lx, y1 + g * ly);\n }\n}",
"function drawBezierCurve(context, p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y, lines) {\r\n const bezierMatrix = [[-1, 3, -3, 1], [3, -6, 3, 0], [-3, 3, 0, 0], [1, 0, 0, 0]];\r\n const pointVectorX = [p1x, p2x, p3x, p4x];\r\n const pointVectorY = [p1y, p2y, p3y, p4y];\r\n\r\n const cx = multiplyMatrixByVector(bezierMatrix, pointVectorX);\r\n const cy = multiplyMatrixByVector(bezierMatrix, pointVectorY);\r\n\r\n step = 1/lines;\r\n for(let t = 0; Math.floor((t+step)*100)/100 <= 1; t+=step) {\r\n let startX = calculateCurvePoint(cx, 1-t);\r\n let startY = calculateCurvePoint(cy, 1-t);\r\n let endX = calculateCurvePoint(cx, 1-(t+step));\r\n let endY = calculateCurvePoint(cy, 1-(t+step));\r\n\r\n drawLine(context, startX, startY, endX, endY);\r\n if(Math.floor((t+step)*100)/100 === 1)\r\n break\r\n }\r\n}",
"function LineSegment2D (\n _lineSegmentBatch,\n _screenPosition1,\n _screenPosition2,\n _screenThickness,\n _color,\n _vertexPositions, // which is a [], not a Float32Array.\n _vertexColors // which is a [], not a Float32Array.\n){\n // 1. Vertex positions.\n LineSegment2D.createVertexPositions (\n // Part 1.\n _vertexPositions,\n // Part 2.\n _screenPosition1, _screenPosition2, _screenThickness\n );\n \n // 2. Vertex colors.\n LineSegment2D.createVertexColors(_vertexColors, _color);\n\n // Note:\n // Let LineSegment2DBatch get indices using LineSegment2D.INDICES directly.\n /*\n // 3. Indices.\n this.indices = LineSegment2D.INDICES;\n */\n}",
"function renderLine () {\n // Render each data point\n ctx.beginPath();\n ctx.strokeStyle = typeof dataset['strokeStyle'] !== 'undefined' ? dataset['strokeStyle'] : '#ffffff';\n ctx.lineWidth = typeof dataset['lineWidth'] !== 'undefined' ? dataset['lineWidth'] : 2;\n ctx.moveTo(points[0].x, points[0].y);\n\n for (var j = 1; j < points.length; j++) {\n ctx.lineTo(points[j].x, points[j].y);\n }\n\n ctx.stroke();\n }",
"function drawArrow(x1, y1, x2, y2) {\n\tvar scale = 3*Math.sqrt(c.lineWidth);\n\n\tvar deltaX = x2-x1;\n\tvar deltaY = y2-y1;\n\tvar oldLen = Math.sqrt(deltaX*deltaX+deltaY*deltaY);\n\tvar angle = 0.523598776;\n\tdeltaX *= scale/oldLen*3;\n\tdeltaY *= scale/oldLen*3;\n\n\t// draw head\n\tc.beginPath();\n\tc.moveTo(x2,y2);\n\tc.lineTo(x2-Math.sin(angle)*deltaY-Math.cos(angle)*deltaX,y2+\n\t\tMath.sin(angle)*deltaX-Math.cos(angle)*deltaY);\n\tc.lineTo(x2+Math.sin(angle)*deltaY-Math.cos(angle)*deltaX,y2-\n\t\tMath.sin(angle)*deltaX-Math.cos(angle)*deltaY);\n\tc.fill();\n\n\t// draw line\n\tc.beginPath();\n\tc.moveTo(x1,y1);\n\tc.lineTo(x2 - Math.cos(angle)*deltaX,y2 - Math.cos(angle)*deltaY);\n\tc.stroke();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a tank form JS | function addATank() {
var code = $("#tankCode").val();
var label = $("#tankLabel").val();
var latitude = $("#tankLatitude").val();
var longitude = $("#tankLongitude").val();
$.post("tank", {code: code, label: label, latitude: latitude, longitude: longitude, owner: userId, sate: 'pending'})
.done(function (data) {
/**
* Update user tank list
* */
$("#tankList").append("<li class='tank' id='" + data.id + "'>" + data.label + " [" + data.state + "]</li>");
});
} | [
"function tank() {\n $('#tank').show('slow', goTank)\n }",
"function newTank(data){\n\tlet spawnpoint = newSpawnpoint();\n\ttanks.push(new Tank(data[\"id\"], spawnpoint.x, spawnpoint.y, tankSettings[\"width\"], tankSettings[\"height\"], spawnpoint.angle, tankSettings[\"speed\"], tankSettings[\"acceleraton\"], data[\"color\"]));\n\tscoreboard.addPlayer(data[\"id\"], data[\"name\"], tankSettings[\"defaultElo\"], data[\"color\"]);\n}",
"function addFormElem(moduleChosen){\n\tclearForm();\n\tvar moduleCode = moduleChosen.split(' ')[0];\n\taddLecture(moduleCode);\n\taddRest(moduleCode);\n\taddButton();\n\tselectize();\n\tprepareInfoDisplay();\n\taddEventForFormElem(moduleCode);\n}",
"function addQuizForm() {\n $('main').find('fieldset').html(loadQuizQuestion)}",
"function Tank() {\n\tthis.type = \"Tank\";\n\tthis.health = Math.floor(Math.random() * (100 - 80) + 80);\n\tthis.attack = Math.floor(Math.random() * (30 - 20) + 20);\n\tthis.evade = Math.floor(Math.random() * (10 - 0) + 0);\n}",
"function CreateOrUpdateTank(name,teamID,health,KillCount,x,z,UID,delta_server){\n if(UID==GameObjs.Player.UID){\n GameObjs.Player.x = x;\n GameObjs.Player.z = z;\n GameObjs.Player.health = health;\n \n GameObjs.Player.KillCount = KillCount;\n return ;\n }\n for (var i = GameObjs.TANKs.length - 1; i >= 0; i--) {\n if(UID==GameObjs.TANKs[i].UID){\n GameObjs.TANKs[i].x = x;\n GameObjs.TANKs[i].z = z;\n\n GameObjs.TANKs[i].health = health;\n GameObjs.TANKs[i].KillCount = KillCount;\n return ;\n }\n }\n createTankPos(name,teamID,health,KillCount,x,z,UID,delta_server);\n}",
"function createTankPos(name,teamID,health,KillCount,posX,posZ,UID,delta_server){\n if(MESHES_LOADEDr && MESHES_LOADEDg && MESHES_LOADEDb ){\n var Team = GameObjs.Teams[teamID];\n var tank = new boxObj(Team.TankMesh);\n tank.x=posX;\n tank.z=posZ;\n tank.Team=Team;\n tank.delta=delta;\n tank.KillCount = KillCount;\n tank.shotColor=Team.color;\n this.DefshotColor=Team.color;\n tank.LifeObj=new boxObj(objs(\"life\",\"green\"));\n tank.setHealth(health);\n tank.Name=name;\n tank.UID=UID;\n\n\n GameObjs.TANKs.push(tank);\n\n delete(tank);\n \n }\n\n}",
"addTab() {\n this._insertItem(FdEditformTab.create({\n caption: `${this.get('i18n').t('forms.fd-editform-constructor.new-tab-caption').toString()} #${this.incrementProperty('_newTabIndex')}`,\n rows: A(),\n }), this.get('selectedItem') || this.get('controlsTree'));\n }",
"function buildCardTitleForm() {\n\t\t\tvar node = document.createElement('form')\n\t\t\tnode.innerHTML =\n\t\t\t\t'<div class=\"newitem-title-wrapper\">' +\n\t\t\t\t'<textarea class=\"trello-new-card-title-input\" type=\"text\"></textarea>' +\n\t\t\t\t'<input class=\"trello-new-card-title-submit\" type=\"submit\" value=\"Add\">' +\n\t\t\t\t'</div>'\n\t\t\tnode.style.display = 'none'\n\t\t\treturn node;\n\t\t}",
"function addNewToy() {\n addBtn = getDom(\"#new-toy-btn\")\n toyForm = getDom(\".container\")\n let addToy = false\n addBtn.addEventListener('click', () => {\n // hide & seek with the form\n addToy = !addToy\n if (addToy) {\n toyForm.style.display = 'block'\n // submit listener here\n } else {\n toyForm.style.display = 'none'\n }\n })\n}",
"function addSkill() {\r\n // get TOTAL_FORMS element from Django management_form of Skill formset\r\n let totalSkillForms = document.getElementById(\"id_skill-TOTAL_FORMS\");\r\n // get MAX_NUM_FORMS element from Django management_form of Skill formset\r\n let maxSkillForms = document.getElementById(\"id_skill-MAX_NUM_FORMS\");\r\n // only add new Skill fieldset if MAX_NUM_FORMS not reached yet\r\n if (totalSkillForms.value !== maxSkillForms.value) {\r\n // get all Skill fieldsets\r\n const skillFieldSets = document.getElementsByClassName(\"skill\");\r\n // get last Skill fieldset\r\n const lastSkill = skillFieldSets[skillFieldSets.length - 1];\r\n // clone last Skill fieldset\r\n let clone = lastSkill.cloneNode(true);\r\n // replace upcounting number in clone inner HTML\r\n const count = String(parseInt(totalSkillForms.value) - 1);\r\n const regex = new RegExp(count, \"g\");\r\n clone.innerHTML = clone.innerHTML.replace(regex, totalSkillForms.value);\r\n // get DIV of Skill fieldsets\r\n let skills = document.getElementById(\"skills\");\r\n // append clone to DIV\r\n skills.appendChild(clone);\r\n // add Skill Value Validation Event to newly created Skill Value field\r\n addSkillValueValidationEvent(totalSkillForms.value);\r\n // increase TOTAL_FORMS element to comply with Django logic\r\n totalSkillForms.value = String(parseInt(totalSkillForms.value) + 1);\r\n } else {\r\n // deactivate add Skill button in case MAX_NUM_FORMS reached\r\n button = document.getElementById(\"addSkill\");\r\n button.setAttribute(\"disabled\", true);\r\n }\r\n }",
"function createFormHandler(e) {\n e.preventDefault()\n// Add innerHTML apending to Brainstormer in this section\n const characterInput = document.querySelector(\"#user-edit-character\").value\n const setupInput = document.querySelector(\"#user-edit-setup\").value\n const twistInput = document.querySelector(\"#user-edit-twist\").value\n const genreInput = document.querySelector(\"#user-edit-genre_id\").value\n \n postIdea(characterInput, setupInput, twistInput, genreInput)\n }",
"function addFields () {\n\t\n\t$(\"#contestantsForm\").append('<input type=\"text\" /><br/><input type=\"text\" /><br/>');\n}",
"function handleSubmit(button_type) {\n\n // check if there are no more unranked items\n unranked_items = document.getElementById('unranked-items').children;\n if (unranked_items.length > 0) {\n window.alert('Please sort in all items first.');\n }\n else {\n //get the ranking and save it\n var item_ids = [];\n var ranked_items = document.getElementById(\"ranked-items\").children;\n for (var j=0, item; item = ranked_items[j]; j++) {\n item_ids.push(ranked_items[j].getAttribute('id'));\n }\n document.getElementsByName(\"rankingResult\")[0].value = item_ids;\n\n var btn = document.getElementsByName('buttonType')[0];\n if (btn) {\n btn.value = button_type;\n }\n\n // now submit the form\n document.getElementById(\"subForm\").submit();\n }\n\n}",
"function Tank (name, x, y, instructions) {\n\tthis.name = name;\n\tthis.type = 0;\n\tthis.code = instructions;\n\tthis.labels = {};\n\tthis.alive = true;\n\tthis.pc = 0;\n\tthis.x = x;\n\tthis.y = y;\n\tthis.orientation = 0;\n\tthis.system = {\n\t \"variables\" : Array.apply(null, Array(32)).map(function () {}),\n\t\t\"target\" : undefined,\n\t\t\"fuel\" : 999,\n\t\t\"hp\" : 5,\n\t\t\"ScanRange\" : 20,\n\t\t\"AttackRange\" : 10,\n\t}\n\n this.onHit = () => {\n\t this.system[\"hp\"] = this.system[\"hp\"] - 1;\n\t\tif(this.system[\"hp\"] == 0){\n\t\t\tthis.alive = false;\n\t\t\tSG.Board.cells[this.x][this.y].obj = null;\n\t\t}\n }\n\n\tthis.tileID = \"Tank0.svg\";\n\t// logs creation to client gamelog giving its name and coords\n\tgameLog(\"Creating \" + this.name + \" at \" + this.x + \", \" + this.y);\n\n\t// check if placement is available\n\tif (!SG.Board.cells[x][y].occupied()) {\n\t\tSG.Board.cells[x][y].obj = this;\n\t\tSG.GameObjects.push(this);\n\t\tSG.TankObjects.push(this);\n\t} else {\n\t\t// error message when tank creation conflicts with object already on SG.Board\n\t\tgameLog(\"Map location is already unoccupied.\");\n\t\treturn undefined;\n\t}\n\n\tthis.execute = () => {\n\n\t// method to map command instruction to tank method\n\n\t\t// if pc has reached the end of codestore set to 0 to wrap back to beginning\n\t\tif (this.pc >= this.code.length) {\n\t\t\tthis.pc = 0;\n\t\t}\n\t\t// grab next instruction and log it\n\t\tlet instruction = this.code[this.pc];\n\t\t//gameLog(this.pc + \" \" + this.name + \": \" + instruction.command + \" \" + instruction.args);\n\n\t\t// switch to map command to method\n\t\tswitch(instruction[0]) {\n\t\t\tcase 3: // move (1 == forward, -1 == backward)\n\t\t\t gameLog(this.pc + \" \" + this.name + \": Move 1\");\n\t\t\t\tthis.move(instruction[1]);\n\t\t\t\tbreak;\n\t\t\tcase 4: // scan ()\n gameLog(this.pc + \" \" + this.name + \": Scan\");\n this.scan(instruction[1]);\n break;\n case 5:\n gameLog(this.pc + \" \" + this.name + \": Turn\");\n this.turn(instruction[1], instruction[2]);\n break;\n\t\t\tcase 8:\n\t\t\t\tgameLog(this.pc + \" \" + this.name + \": Fire\");\n\t\t\t\tthis.fire();\n\t\t\t\tbreak;\n\t\t\tcase 73: // rotate (true == cw, false == ccw)\n\t\t\t\tthis.rotate(instruction.args[0])\n\t\t\tcase 35: // goto (program line)\n \t\t\tgameLog(this.pc + \" \" + this.name + \": goto \" + instruction[1]);\n\t\t\t\tthis.pc = instruction[1];\n\t\t\t\tthis.execute(); \n\t\t\t\tbreak;\n\t\t\tcase 34:\n\t\t\t\tswitch (instruction[1]) {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tthis.pc = instruction[3];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tthis.pc = instruction[3];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tlet tf = directions[this.orientation];\n\t\t\t\t\t\tlet tfx = this.x + tf[0];\n\t\t\t\t\t\tlet tfy = this.y + tf[1];\n\t\t\t\t\t\tif (SG.Board.cells[tfx][tfy].occupied()) {\n\t\t\t\t\t\t\tthis.pc = instruction[3];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\t tf = directions[this.orientation];\n\t\t\t\t\t\t tfx = this.x + tf[0];\n\t\t\t\t\t\t tfy = this.y + tf[1];\n\t\t\t\t\t\tif (!SG.Board.cells[tfx][tfy].occupied()) {\n\t\t\t\t\t\t\tthis.pc = instruction[3];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\tif (this.system.fuel > 0) this.pc = instruction[3];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\tif (this.system.fuel == 0) this.pc = instruction[3];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 6:\n\t\t\t\t\t\tvar temp = this.system.target;\n\t\t\t\t\t\tif (this.scan(1)) {\n\t\t\t\t\t\t\tthis.pc = instruction[3];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.system.target = temp;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 7:\n\t\t\t\t\t\tvar temp = this.system.target;\n\t\t\t\t\t\tif (!this.scan(1)) {\n\t\t\t\t\t\t\tthis.pc = instruction[3];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.system.target = temp;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 8:\n\t\t\t\t\t\tvar temp = this.system.target;\n\t\t\t\t\t\tif (this.scan(0)) {\n\t\t\t\t\t\t\tthis.pc = instruction[3];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.system.target = temp;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 9:\n\t\t\t\t\t\tvar temp = this.system.target;\n\t\t\t\t\t\tif (this.scan(0)) {\n\t\t\t\t\t\t\tthis.pc = instruction[3];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.system.target = temp;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 10:\n\t\t\t\t\t\tvar temp1 = this.x - this.system.target.x;\n\t\t\t\t\t\tvar temp2 = this.y - this.system.target.y;\n\t\t\t\t\t\ttemp1 = Math.pow(temp1, 2);\n\t\t\t\t\t\ttemp2 = Math.pow(temp2, 2);\n\t\t\t\t\t\tvar temp3 = Math.sqrt(temp1 + temp2);\n\t\t\t\t\t\tif (temp3 <= this.system.AttackRange) {\n\t\t\t\t\t\t\tthis.pc = instruction[3];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t// call execution of next instruction and increment pc\n\n\tthis.step = () => {\n\t\tthis.execute();\n\t\tthis.pc++;\n\t}\n\n this.scan = (type) => {\n let tx = this.x - this.system.ScanRange;\n let ty = this.y - this.system.ScanRange;\n for (let i = 0; i <= this.system.ScanRange * 2; i++) {\n for (let j = 0; j <= this.system.ScanRange * 2; j++) {\n if (tx + i < 0 || tx + i >= SG.boardWidth || ty + j < 0 || ty + j >= SG.boardHeight || (tx + i == this.x && ty + j == this.y)) {\n continue;\n }\n //console.log((tx + i) + \" \" + (ty + j));\n //ctx.fillStyle = \"rgba(0,255,0,0.5)\";\n //ctx.fillRect((tx + i) * 25 + 2, (ty + j) * 25 + 2, 23, 23);\n if (SG.Board.cells[tx + i][ty + j].contains(type)) {\n this.system.target = SG.Board.cells[tx + i][ty + j];\n gameLog(((type == 0) ? \"tank\" : \"obstacle\") + \" found at \" + (tx + i) + \",\" + (ty + j))\n //console.log(SG.Board.cells[tx + i][ty + j].obj.name);\n return true;\n }\n }\n }\n return false;\n }\n\n\t// method to execute move in the direction specified\n\n\tthis.move = (dir) => {\n\t\t// dir is 1 for forwards, -1 for backwards\n\t\tlet tf = (dir == 1) ? directions[this.orientation] : directions[(this.orientation - 180) % 360];\n\t\tlet tfx = this.x + tf[0];\n\t\tlet tfy = this.y + tf[1];\n\t\tif (!SG.Board.cells[tfx][tfy].occupied()) {\n\t\t\tSG.Board.cells[this.x][this.y].obj = undefined;\n\t\t\tthis.x = tfx;\n\t\t\tthis.y = tfy;\n\t\t\tSG.Board.cells[tfx][tfy].obj = this;\n\t\t\tthis.system.fuel -= 1;\n\t\t}\n\t}\n\n\t// method to echo current tank location\n\n\tthis.location = () => {\n\t\tgameLog(this.name + \" is at \" + this.x + \", \" + this.y + \".\");\n\t}\n\n\tthis.turn = (type, amount = undefined) => {\n\t\tswitch (type) {\n\t\t case 29: // right\n\t\t this.orientation = (this.orientation - ((45 * amount) % 360) + 360) % 360;\n\t\t break;\n\t\t case 30: // left\n\t\t this.orientation = (this.orientation + (45 * amount)) % 360;\n\t\t break;\n\t\t case 31: // angle\n\t\t this.orientation = (45 * amount) % 360;\n\t\t break;\n\t\t case 32: // face target\n\t\t \tif (!this.system.target) {\n\t\t \t\treturn;\n\t\t \t}\n\t\t let tx = this.system.target.x;\n\t\t let ty = this.system.target.y;\n\t\t if (this.x == tx && this.y > ty) { // north\n\t\t this.turn(31, 2);\n\t\t } else if (this.x == tx && this.y < ty) { // south\n this.turn(31, 6);\n\t\t } else if (this.x > tx && this.y == ty) { // west\n this.turn(31, 4);\n\t\t } else if (this.x < tx && this.y == ty) { // east\n this.turn(31, 0);\n\t\t } else if (this.x < tx && this.y > ty) { // northeast\n this.turn(31, 1);\n\t\t } else if (this.x < tx && this.y < ty) { // southeast\n this.turn(31, 7);\n\t\t } else if (this.x > tx && this.y > ty) { // northwest\n this.turn(31, 3);\n\t\t } else if (this.x > tx && this.y > ty) { // southwest\n this.turn(31, 5);\n\t\t }\n\t\t break;\n\t\t}\n\t\tthis.tileID = \"Tank\" + (this.orientation / 45) + \".svg\";\n\t}\n\n\tthis.fire = () => {\n var x0 = this.x;\n var y0 = this.y;\n var x1 = this.system.target.x;\n var y1 = this.system.target.y;\n var dx = Math.abs(x1-x0);\n var dy = Math.abs(y1-y0);\n var sx = (x0 < x1) ? 1 : -1;\n var sy = (y0 < y1) ? 1 : -1;\n var err = dx-dy;\n\n if ((x0==x1) && (y0==y1)) return;\n var e2 = 2*err;\n if (e2 >-dy){ err -= dy; x0 += sx; }\n if (e2 < dx){ err += dx; y0 += sy; }\n\n if (SG.Board.cells[x0][y0].occupied()) {\n SG.Board.cells[x0][y0].obj.onHit();\n return;\n }\n\n while(true){\n if ((x0==x1) && (y0==y1)) break;\n var e2 = 2*err;\n if (e2 >-dy){ err -= dy; x0 += sx; }\n if (e2 < dx){ err += dx; y0 += sy; }\n\n if (SG.Board.cells[x0][y0].occupied()) {\n SG.Board.cells[x0][y0].obj.onHit();\n return;\n }\n\n }\n }\n}",
"function addPartyToBallot(){\n\tlet inputTemp = {};\n\n\tlet partyBox = document.createElement('A');\n\tpartyBox.classList.add('list-group-item','list-group-item-action');\n\tpartyBox.id = `list-${partyCount}-list`;\n\tpartyBox.setAttribute('data-toggle','list');\n\tpartyBox.href = `#list-${partyCount}`;\n\n\t// Text input for party name\n\tlet partyName = document.createElement('input');\n\tpartyName.id = `list-${partyCount}-name`;\n\tpartyName.setAttribute('type','text');\n\tpartyName.classList.add('w-75');\n\tpartyName.value = '*Party Name*';\n\tpartyBox.appendChild(partyName);\n\n\t// Save input for later use\n\tinputTemp.partyName = partyName;\n\n\t// Remove Party button\n\tlet removeParty = document.createElement('button');\n\tremoveParty.setAttribute('title','Remove Party');\n\tremoveParty.setAttribute('data-toggle','tooltip');\n\tremoveParty.setAttribute('data-placement','top');\n\tremoveParty.classList.add('close');\n\tremoveParty.addEventListener('click',removePartyFromBallot)\n\tpartyBox.appendChild(removeParty);\n\n\t// 'X' icon\n\tlet x = document.createElement('span');\n\tx.innerHTML = '×';\n\tremoveParty.appendChild(x);\n\n\t// List of candidates for this party\n\tlet tabPane = document.createElement('div');\n\ttabPane.classList.add('tab-pane','list-group','mx-auto');\n\ttabPane.id = `list-${partyCount}`;\n\ttabPane.setAttribute('role','tabpanel');\n\tcandidateLists.appendChild(tabPane);\n\n\t// Add Candidate Button\n\tlet addCan = document.createElement('A');\n\taddCan.classList.add('list-group-item','list-group-item-action');\n\taddCan.style.cursor = 'pointer';\n\taddCan.setAttribute('title','Add Candidate');\n\taddCan.setAttribute('data-toggle','tooltip');\n\taddCan.setAttribute('data-placement','top');\n\taddCan.addEventListener('click',addCandidate);\n\ttabPane.appendChild(addCan);\n\t\n\t// '+' icon\n\tx = document.createElement('span');\n\tx.innerHTML = '+';\n\taddCan.appendChild(x);\n\n\tinputTemp.candidates = [];\n\tinputs.set(`list-${partyCount}-list`, inputTemp);\n\n\tpartyCount++;\n\tpartyList.insertBefore(partyBox,partyList.lastChild);\n\t$('[data-toggle=\"tooltip\"]').tooltip();\n}",
"function handleTippAmountFormSubmit(e) {\n e.preventDefault();\n const TIPP_MIN_AMOUNT = 1;\n const $tipp = document.querySelector('.tipp-ext-btn');\n const $amountInput = e.target.querySelector('#tipp-amount');\n const $label = $amountInput.parentNode.querySelector('label');\n const $chooseAmount = e.target.querySelector('button[type=submit]');\n const dollars = currencyToNumber($amountInput.value);\n if(!dollars || dollars < TIPP_MIN_AMOUNT) {\n // invalid dollar amount\n $amountInput.classList.add('tipp-invalid');\n $label.textContent = \"Enter Tipp Amount ($1.00 minimum)\";\n } else {\n // get necessary values for Stripe Checkout\n const amount = dollars*100; // in cents\n const fname = $tipp.getAttribute(\"data-fname\");\n const lname = $tipp.getAttribute(\"data-lname\");\n const displayname = $tipp.getAttribute(\"data-displayname\");\n // build dynamically-loaded Stripe Checkout button\n const $checkoutForm = createStripeCheckoutForm(amount, fname, lname, displayname);\n // replace choose amount button with Stripe Checkout button\n $amountInput.style.display = 'none';\n $label.style.display = 'none';\n $chooseAmount.style.display = 'none';\n e.target.appendChild($checkoutForm);\n }\n }",
"function AddThrees(){\n\t\t\t\tcheckCtrl = document.getElementById(\"keepThrees\");\n\t\t\t\tboxCtrl = document.getElementById(\"ThreesValue\");\n\t\t\t\tNumberCheck = 3;\n\n\t\t\t\tUpperCheck();\n\t\t\t}",
"function addKitten(event) {\r\n\r\n event.preventDefault();\r\n\r\n let form = event.target;\r\n\r\n console.log('Made it here');\r\n\r\n\r\n\r\n let kName = form.kittenName.value;\r\n console.log(`The name of the kitten is ${kName}`);\r\n\r\n\r\n let imageUrl = getKittenUrl(kName);\r\n\r\n console.log(imageUrl);\r\n\r\n loadKittens();\r\n\r\n\r\n //create kitten object\r\n\r\n let kitten =\r\n {\r\n id: generateId(),\r\n name: kName,\r\n image: imageUrl,\r\n mood: 'TOLERANT',\r\n affection: 5\r\n\r\n }\r\n\r\n console.log(`Name of the kitten: ${kitten.name}`);\r\n console.log(`Id of the kitten: ${kitten.id}`);\r\n console.log(`Url image of the kitten: ${kitten.image}`)\r\n ;\r\n console.log(`Mood of the kitten: ${kitten.mood}`);\r\n console.log(`Affection level of the kitten: ${kitten.affection}`);\r\n\r\n\r\n kittens.push(kitten);\r\n saveKittens();\r\n drawKittens();\r\n\r\n document.getElementById(\"input-add-kitten\").value = \"\";\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get employees from team | function getTeamEmployees(teamName, response) {
var query = `SELECT * FROM statusIndicator
WHERE teamName='${teamName}' ORDER BY displayName`;
connection.query(query, function (error, results, fields) {
if (error) {
var responseObject = {
status: "error",
text: "Error while retrieving employees with teamName! " + JSON.stringify(error)
};
response.statusCode = 500;
response.setHeader('Content-Type', 'application/json');
return response.end(JSON.stringify(responseObject));
}
var responseObject = {
"status": "success",
"teams": []
};
var currentTeamObject = {
"name": teamName,
"members": []
};
for (var i = 0; i < results.length; i++) {
currentTeamObject.members.push(formatMemberData(results[i]));
}
responseObject.teams.push(currentTeamObject);
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
return response.end(JSON.stringify(responseObject));
});
} | [
"findManagerEmployees(managerId) {\n return this.connection.query(\n \"SELECT employee.id, employee.first_name, employee.last_name, department.name AS department, role.title FROM employee LEFT JOIN role on role.id = employee.role_id LEFT JOIN department ON department.id = role.department_id WHERE manager_id = ?;\",\n managerId\n );\n }",
"function fetchAllEmployees() {\r\n\t\tvar deferred = $q.defer();\r\n\t\t$http.get('employees/')\r\n\t\t\t.then(\r\n\t\t\t\t\tfunction (response) {\r\n\t\t\t\t\t\tdeferred.resolve(response.data);\r\n\t\t\t\t\t},\r\n\t\t\t\t\tfunction (errResponse) {\r\n\t\t\t\t\t\tconsole.log(\"Error while fetching employees\");\r\n\t\t\t\t\t\tdeferred.reject(errResponse);\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\treturn deferred.promise;\r\n\t}",
"function findCoworkersFor(employee, employeesArr) {\n let coworkers = [];\n let manager = employee.managerId;\n\n employeesArr.forEach(employeeObj => {\n if (employeeObj.managerId === manager && employeeObj.name !== employee.name) {\n coworkers.push(employeeObj)\n }\n })\n\n return coworkers;\n}",
"function viewEmployeesByDepartment() {\n db.query(`SELECT * FROM department`, (err, data) => {\n if (err) throw err;\n\n const department = data.map(({\n id,\n name\n\n }) => ({\n name: name,\n value: id\n }));\n inquirer.prompt([{\n name: \"department\",\n type: \"list\",\n message: \"Select A Department:\",\n choices: department\n }]).then(event => {\n const department = event.department;\n db.query(`SELECT CONCAT(first_name, ' ', last_name) AS Employees, department.name AS Department FROM employee JOIN role ON employee.role_id = role.id JOIN department ON role.department_id = department.id WHERE department_id= ${department};`, function (err, results) {\n if (err) throw err\n console.table(results)\n\n initPrompt()\n })\n })\n })\n}",
"getEmployeesByJob() {\n return (req, res) => {\n EmployeeJobAssociation.find({ jobId: req.params.jobId }, {}, (err, employeeJobAssociations) => {\n if (err) {\n res.status(500).json({\n errors: [{\n status: 500,\n source: { pointer: 'GET /jobs/:jobId/employees' },\n title: \"Unable to get Employee Association in Company\",\n detail: err\n }]\n });\n } else if (employeeJobAssociations == null || employeeJobAssociations.length == 0) {\n res.status(404).json({\n errors: [{\n status: 404,\n source: { pointer: 'GET /jobs/:jobId/employees' },\n title: \"Unable to Find any EmployeeAssociations with that jobId\\njobd: \" + req.params.jobId,\n detail: \"No companies exist\"\n }]\n });\n } else {\n let employIds = employeeJobAssociations.map((employeeJobAssociation) => {\n return employeeJobAssociation.employeeId;\n });\n Employee.find({ _id: { $in: employIds } }, {}, (err, employees) => {\n if (err) {\n res.status(500).json({\n errors: [{\n status: 500,\n source: { pointer: 'GET /jobs/:jobId/employees' },\n title: \"Unable to get Employees\",\n detail: err\n }]\n });\n } else if (employees == null || employees.length == 0) {\n res.status(404).json({\n errors: [{\n status: 404,\n source: { pointer: 'GET /companies/:companyId' },\n title: \"Unable to Find any Employees with that jobId\\njobId: \" + req.params.jobId,\n detail: \"No Employees work for that company\"\n }]\n });\n } else {\n res.json({\n data: employees.map((employee) => {\n return {\n id: employee._id,\n type: \"Employee\",\n attributes: employee\n };\n })\n });\n }\n });\n }\n });\n\n };\n }",
"function promptEmployee() {\n return inquirer.prompt([\n {name: \"name\" , type: \"input\", message: \"TeamInfo: Employee Name? (<first> <last>)\"},\n {name: \"id\" , type: \"input\", message: \"TeamInfo: Badge Number?\"},\n {name: \"email\", type: \"input\", message: \"TeamInfo: E-mail? (<userName>@<mailServer>.<domain>)\"},\n {name: \"role\" , type: \"list\" , message: \"TeamInfo: Team Role? (manager|engineer|intern)\",\n choices: ['Manager','Engineer','Intern'], filter: function(val) {return val.toLowerCase();}},\n ]);\n}",
"function findManagerFor(employee, employeesArr) {\n let manager = employee.managerId;\n if (!manager) {\n return null;\n } else {\n for (let i = 0; i < employeesArr.length; i++) {\n if (manager === employeesArr[i].id) {\n return employeesArr[i];\n }\n }\n }\n}",
"function findEmployee(employeeName){\n for (let name of employeeDB) {\n if (employeeName == name.fname) \n return employeeName + \" works here\"\n }\n\n return false\n}",
"function viewEmployeeByDepartment() {\n\tconsole.log(\"View employees by department\\n\");\n\n\tvar query = `SELECT d.id, d.name\n\tFROM employee e\n\tLEFT JOIN role r\n\tON e.role_id = r.id\n\tLEFT JOIN department d\n\tON d.id = r.department_id\n\tGROUP BY d.id, d.name`;\n\n\tconnection.query(query, function (err, res) {\n\t\tif (err) throw err;\n\n\t\t// Select department\n\t\tconst departmentChoices = res.map((data) => ({\n\t\t\tvalue: data.id,\n\t\t\tname: data.name,\n\t\t}));\n\n\t\tinquirer\n\t\t\t.prompt(prompt.departmentPrompt(departmentChoices))\n\t\t\t.then(function (answer) {\n\t\t\t\tvar query = `SELECT e.id, e.first_name, e.last_name, r.title, d.name AS department \n\t\t\tFROM employee e\n\t\t\tJOIN role r\n\t\t\t\tON e.role_id = r.id\n\t\t\tJOIN department d\n\t\t\tON d.id = r.department_id\n\t\t\tWHERE d.id = ?`;\n\n\t\t\t\tconnection.query(query, answer.departmentId, function (err, res) {\n\t\t\t\t\tif (err) throw err;\n\n\t\t\t\t\tconsole.table(\"\\nDepartment Rota: \", res);\n\t\t\t\t\tconsole.log(\"\\n<<<<<<<<<<<<<<<<<<<< ⛔ >>>>>>>>>>>>>>>>>>>>\\n\");\n\n\t\t\t\t\tfirstPrompt();\n\t\t\t\t});\n\t\t\t});\n\t});\n}",
"function findEmployeeByName(name, employeesArr) {\n\n let employeeArr = employeesArr.filter(employeeObj => {\n if (employeeObj.name === name) {\n return employeeObj;\n }\n });\n return employeeArr[0];\n}",
"async function getEmployeeById(employeeId) {\n\tlet employee\n\tconst snap = await firebase\n\t\t.database()\n\t\t.ref(`/employees/${employeeId}`)\n\t\t.once('value')\n\temployee = snap.val()\n\tconst reportIds = Object.keys(employee.reports || [])\n\tconst getReports = reportIds.map(userId =>\n\t\tfirebase\n\t\t\t.database()\n\t\t\t.ref(`/employees/${userId}`)\n\t\t\t.once('value')\n\t)\n\tconst reportSnapshots = await Promise.all(getReports)\n\treports = reportSnapshots.map(snap => snap.val())\n\treturn { employee, reports: reports }\n}",
"function getEmployees(name_part){\n let emps = employees.filter(function(emp){\n return emp.first_name.toLowerCase().startsWith(name_part.toLowerCase()); \n })\n displayEmployees(emps);\n}",
"function displayEmployees(data) {\n employees = data;\n appendEmployeHTMLStringToDOM(employees);\n}",
"function checkTeam() {\n try {\n\n if (SA.currentUserID.toString() != '') {\n var olist = SA.appCtx.get_web().get_lists().getByTitle('Employee Info');\n var camlQuery = new SP.CamlQuery();\n camlQuery.set_viewXml(\"<View><Query><Where><Eq><FieldRef Name='AccountID' /><Value Type='User'>\"+SA.currentUserID+\"</Value></Eq></Where></Query></View>\");\n SA.olistItemColl = olist.getItems(camlQuery);\n SA.context.load(SA.olistItemColl, 'Include(Team)');\n SA.context.executeQueryAsync(onQuerySucceeded, onQueryFailed);\n }\n else {\n alert('Unable to fetch your info. Please reload the page. If the problem persists please contact the SharePoint team');\n }\n \n }\n catch (e) {\n alert(e.message);\n }\n }",
"function getEmployeeEmail(employee){\n var employeeNameIndex = 1;\n var employeeEmailIndex = 2;\n var employeeData = SpreadsheetApp.openById(sheetID).getSheetByName(\"Employee Data\"); // Employee Data Sheet\n for(var i=2; i <= employeeData.getLastRow(); i++){\n // Search for employee name down the name column\n if( employeeData.getRange(i,employeeNameIndex).getValue() == employee){\n // Once the name is found, capture the employee email in the email column\n return employeeData.getRange(i,employeeEmailIndex).getValue();\n }\n }\n // -1 returned if employee name is not found\n return -1;\n}",
"function beginTeam() {\n console.log(\"Please build your software engineering team\");\n inquirer.prompt(managerQuestions).then(answers => {\n const manager = new Manager(answers.managerName, answers.managerID, answers.managerEmail, answers.managerOffice);\n teamMembers.push(manager);\n idsArray.push(answers.managerID);\n employees();\n });\n }",
"function getAllEmployees(callback)\n{\n db.all(\"SELECT rowid, * FROM Employees\",\n function(err,results) { callback(results); });\n}",
"function generateEmployeesByPage(employees, pageNo) {\n // I assumed showing 10 employees per page\n const perPage = 10;\n if (employees.length) {\n // Filter 10 employees by page number\n return employees.filter((employee, i) => {\n return i >= perPage*(pageNo-1) && i < perPage*pageNo;\n });\n }\n return [];\n}",
"async GETMerchantEmployeeList({commit, dispatch, rootState}, payload) {\n\t\t\treturn new Promise( async (resolve, reject) => {\n\t\t\t\ttry {\n\t\t\t\t\tlet endpoint = 'employees-list/?merchant=';\n\t\t\t\t\tlet type = 'Get Merchant Employees List';\n\t\t\t\t\tlet response = await apiRoutes.FILTERListById(dispatch, rootState, payload, endpoint, type);\n\t\t\t\t\tconsole.log('GETMerchantEmployeeList response', response);\n\t\t\t\t\tcommit('SET_MERCHANT_EMPLOYEE_LIST', response.data);\n\t\t\t\t\treturn resolve(response.data)\n\n\t\t\t\t} catch(error) {\n\t\t\t\t\tconsole.error('TryCatch Error error.response', error.response)\n\t\t\t\t\treturn reject(error)\n\t\t\t\t}\n\t\t\t}).catch(error => {\n\t\t\t\tconsole.error('Promise Error error.response', error.response)\n\t\t\t\treturn error;\n\t\t\t});\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the User's annotations | function retrieveUserAnnotations(req, res) {
let targetUserDoc = null;
sec.authenticateApp(req.get('clientId')).then((result)=>{
return sec.authorizeUser(req.get('username'), req.get('accessToken'));
}).then(async (userDoc)=> {
// If the user specifies a target user in their request, check if they
// are an admin, if they aren't an admin, then throw an error
if(req.get('targetUser') && !userDoc.isAdmin) {
let err = new Error('User must have admin credentials to retrieve data of other users');
err.code = constants.UNAUTHORIZED;
throw err;
} else if(req.get('targetUser')){
// An admin account is attempting to retrieve another user's annotations
userDoc = await User.findOne({'username' : req.get('targetUser').toLowerCase()}).exec();
if (!userDoc) {
let err = new Error('User specified by admin account does not exist');
err.code = constants.NOT_FOUND;
throw err;
}
}
// Return the document in which to retrieve the annotations for
return userDoc;
}).then((userDoc) => {
targetUserDoc = userDoc;
// Get all of the hash values for all of the user annotations
let hashValList = new Array();
hashValList.push(...Array.from(targetUserDoc.annotations.keys()));
// Do a query with the list of hash values
return Source.find({
'hash' : {
$in : hashValList
}
}).select('hash phrase annotations').exec();
}).then((sourceDocList) =>{
let userAnnotationList = new Array();
// Retrieve the language => hash values for the user
sourceDocList.forEach((sourceItem) => {
// The current hash value
let currHashVal = sourceItem.hash;
// The original english phrase of the hash value
let originalPhrase = sourceItem.phrase;
// A mapping of the user's annotations
let annotationMap = {
'phrase' : originalPhrase,
'hash' : currHashVal,
'list' : []
};
// Create a list of the languages the user annotated for the current hash
targetUserDoc.annotations.get(currHashVal).forEach((value, language, anMap) => {
// Retrieve the translation for the current hash in the current language
let map = {};
map.language = language;
map.azureTranslation = sourceItem.annotations.get(language).azure.translation;
map.isAzureCorrect = value.isAzureCorrect;
map.googleTranslation = sourceItem.annotations.get(language).google.translation;
map.isGoogleCorrect = value.isGoogleCorrect;
map.yandexTranslation = sourceItem.annotations.get(language).yandex.translation;
map.isYandexCorrect = value.isYandexCorrect;
annotationMap.list.push(map);
});
// Append the newly created map to the user annotation list
userAnnotationList.push(annotationMap);
});
return res.status(constants.OK).json({'annotations' : userAnnotationList});
}).catch((err) => {
util.log(`Error in retrieveUserAnnotations in user middleware.\nError Message: ${err.message}`);
return res.status(err.code).json({message : err.message});
});
} | [
"function getAnnotationsInDoc() {\n var documentProperties = PropertiesService.getDocumentProperties();\n DocumentApp.getUi().alert('Annotations in the Document Properties: ' + documentProperties.getProperty('ANNOTATIONS'));\n //DocumentApp.getUi().alert('Annotations_type in the Document Properties: ' + documentProperties.getProperty('ANNOTATIONS_TYPE')); \n //DocumentApp.getUi().alert('Links in the Document Properties: ' + documentProperties.getProperty('LINKS')); \n}",
"annotation(type) {\n for (let ann of this.annotations) if (ann.type == type) return ann.value\n return undefined\n }",
"getAnnotations(columnId, rowId) {\n let url = this.get(HATEOAS_DATASET_GET_ANNOTATIONS);\n url += '?column=' + columnId + '&row=' + rowId;\n return url;\n }",
"function getUserInfo() {\n return user;\n }",
"function inferDefinitionFromAnnotation(\n annotations\n ) {\n return [...getAnnotationMap(annotations).values()].map(\n (a) => a.definition\n )\n } // CONCATENATED MODULE: ./src/lib/Editor/API/patchConfiguration/AttributeConfigurationGenerator/fillInferDefinitionFromAnnotation/index.js",
"function getUserIdentifications(userDB){\n return userDB.allDocs({\n include_docs : true,\n startkey: 'id',\n endkey: 'id\\ufff0'\n }).then(function(docs){\n return docs.rows;\n });\n}",
"function getAnnotationData(){\r\n $.ajax({\r\n url: arcs.baseURL + \"api/annotations/findByKid\",\r\n type: \"POST\",\r\n data: {\r\n kid: pageKidGlobal\r\n },\r\n success: function (data) {\r\n annotationDataGlobal = JSON.parse(data);\r\n displayAnnotations();\r\n isAnnotating = false;\r\n }\r\n });\r\n }",
"get userProfile() {\n return spPost(ProfileLoaderFactory(this, \"getuserprofile\"));\n }",
"function processAnnotations() {\n console.log('process annoations');\n\n CSE.res = JSON.parse(CSE.req.responseText);\n CSE.unreadCount += CSE.res.length;\n\n if (CSE.unreadCount > 0) {\n chrome.browserAction.setBadgeBackgroundColor({\n color: [255, 0, 0, 255]\n });\n chrome.browserAction.setBadgeText({text: '' + CSE.unreadCount});\n }\n CSE.annotations = CSE.res.concat(CSE.annotations);\n displayAnnotations();\n }",
"get user() {\n this._logger.debug(\"user[get]\");\n return this._user;\n }",
"function GetUser() {\n\n\tvar client = new SpiderDocsClient(SpiderDocsConf);\n\n\tclient.GetUser('administrator', 'Welcome1')\n\t\n .then(function (user) {\n debugger;\n console.log(user);\n });\n}",
"function getAnnotation (path: NodePath): TypeAnnotation {\n let annotation;\n try {\n annotation = getAnnotationShallow(path);\n }\n catch (e) {\n if (e instanceof SyntaxError) {\n throw e;\n }\n if (process.env.TYPECHECK_DEBUG) {\n console.error(e.stack);\n }\n }\n while (annotation && annotation.type === 'TypeAnnotation') {\n annotation = annotation.typeAnnotation;\n }\n return annotation || t.anyTypeAnnotation();\n }",
"userRecommended() {\n return this._get({\n url: 'https://app-api.pixiv.net/v1/user/recommended'\n });\n }",
"function annotationBlob() {\n return new Blob([JSON.stringify(annotationData())], {\n type: \"application/json\",\n });\n }",
"mergeAnnotations(a,b){return this.dedupeAnnotations(a.concat(b))}",
"get ownerUserProfile() {\n return spPost(this.getParent(ProfileLoaderFactory, \"_api/sp.userprofiles.profileloader.getowneruserprofile\"));\n }",
"of(value) {\n return new Annotation(this, value)\n }",
"function displayUser() {\n var user = firebase.auth().currentUser;\n var email;\n if (user != null) {\n email = user.email;\n }\n}",
"function listLabels() {\n // var request = gapi.client.gmail.users.labels.list({\n // 'userId': 'me'\n // });\n\n // request.execute(function(resp) {\n // var labels = resp.labels;\n // appendPre('Labels:');\n // //console.log(labels);\n // if (labels && labels.length > 0) {\n // for (i = 0; i < labels.length; i++) {\n // var label = labels[i];\n // appendPre(label.name)\n // }\n // } else {\n // appendPre('No Labels found.');\n // }\n // });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a twopass Gaussian blur for a cubemap. Normally this is done vertically and horizontally, but this breaks down on a cube. Here we apply the blur latitudinally (around the poles), and then longitudinally (towards the poles) to approximate the orthogonallyseparable blur. It is least accurate at the poles, but still does a decent job. | function _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
_halfBlur(
cubeUVRenderTarget,
_pingPongRenderTarget,
lodIn,
lodOut,
sigma,
'latitudinal',
poleAxis );
_halfBlur(
_pingPongRenderTarget,
cubeUVRenderTarget,
lodOut,
lodOut,
sigma,
'longitudinal',
poleAxis );
} | [
"function blurImage(img){\n return imageMapXY(img, blurPixel);\n}",
"function BlurPostProcess(name,/** The direction in which to blur the image. */direction,kernel,options,camera,samplingMode,engine,reusable,textureType,defines,blockCompilation){if(samplingMode===void 0){samplingMode=BABYLON.Texture.BILINEAR_SAMPLINGMODE;}if(textureType===void 0){textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}if(defines===void 0){defines=\"\";}if(blockCompilation===void 0){blockCompilation=false;}var _this=_super.call(this,name,\"kernelBlur\",[\"delta\",\"direction\",\"cameraMinMaxZ\"],[\"circleOfConfusionSampler\"],options,camera,samplingMode,engine,reusable,null,textureType,\"kernelBlur\",{varyingCount:0,depCount:0},true)||this;_this.direction=direction;_this.blockCompilation=blockCompilation;_this._packedFloat=false;_this._staticDefines=\"\";_this._staticDefines=defines;_this.onApplyObservable.add(function(effect){if(_this._outputTexture){effect.setFloat2('delta',1/_this._outputTexture.width*_this.direction.x,1/_this._outputTexture.height*_this.direction.y);}else{effect.setFloat2('delta',1/_this.width*_this.direction.x,1/_this.height*_this.direction.y);}});_this.kernel=kernel;return _this;}",
"function apply_sobel_filter(img) {\n img.loadPixels();\n var n = img.width * img.height;\n var sobel_array = new Uint32Array(n);\n\n // compute the gradient in soble_array\n var index;\n var x, y;\n var xk, yk;\n var xGradient, xMultiplier;\n var yGradient, yMultiplier;\n var pixelValue;\n for (x = 1; x < img.width - 1; x++) {\n for (y = 1; y < img.height- 1; y++) {\n i = x + y * img.width;\n xGradient = 0;\n yGradient = 0;\n for (xk = -1; xk <= 1; xk ++) {\n for (yk = -1; yk <= 1; yk ++) {\n pixelValue = img.pixels[4 * ((x + xk) + (y + yk) * img.width)];\n xGradient += pixelValue * xKernel[yk + 1][xk + 1];\n yGradient += pixelValue * yKernel[yk + 1][xk + 1];\n }\n }\n sobel_array[i] = Math.sqrt(\n Math.pow(xGradient, 2) + Math.pow(yGradient, 2)\n );\n }\n }\n\n // copy sobel_array to image pixels;\n for (x = 0; x < img.width; x++) {\n for (y = 0; y < img.height; y++) {\n i = x + y * img.width;\n img.pixels[4 * i] = sobel_array[i];\n img.pixels[4 * i + 1] = sobel_array[i];\n img.pixels[4 * i + 2] = sobel_array[i];\n }\n }\n img.updatePixels();\n}",
"function addSVGBlurToPolygons(basemap) {\n // must add a polygon to the map for the overlay layer to be created,\n // so add a random one to the north pole somewhere out of view\n var someLineIntheNorthPole = [[-126.562500,84.802474],[-122.343750,84.802474]];\n var polygon = L.polygon(someLineIntheNorthPole).addTo(basemap.leafletmap());\n\n var svg = basemap.leafletmap().getPanes().overlayPane.firstChild;\n var svgFilter = document.createElementNS('http://www.w3.org/2000/svg', 'filter');\n var svgBlur = document.createElementNS('http://www.w3.org/2000/svg', 'feGaussianBlur');\n\n svgFilter.setAttribute('id', 'blur');\n svgFilter.setAttribute('x', '-100%');\n svgFilter.setAttribute('y', '-100%');\n svgFilter.setAttribute('width', '500%');\n svgFilter.setAttribute('height', '500%');\n svgBlur.setAttribute('stdDeviation', 5);\n\n svgFilter.appendChild(svgBlur);\n svg.appendChild(svgFilter);\n}",
"function DepthOfFieldEffect(scene,depthTexture,blurLevel,pipelineTextureType,blockCompilation){if(blurLevel===void 0){blurLevel=DepthOfFieldEffectBlurLevel.Low;}if(pipelineTextureType===void 0){pipelineTextureType=0;}if(blockCompilation===void 0){blockCompilation=false;}var _this=_super.call(this,scene.getEngine(),\"depth of field\",function(){return _this._effects;},true)||this;/**\n * @hidden Internal post processes in depth of field effect\n */_this._effects=[];// Circle of confusion value for each pixel is used to determine how much to blur that pixel\n_this._circleOfConfusion=new BABYLON.CircleOfConfusionPostProcess(\"circleOfConfusion\",depthTexture,1,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,scene.getEngine(),false,pipelineTextureType,blockCompilation);// Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)\n// Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts\n// See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf\n_this._depthOfFieldBlurY=[];_this._depthOfFieldBlurX=[];var blurCount=1;var kernelSize=15;switch(blurLevel){case DepthOfFieldEffectBlurLevel.High:{blurCount=3;kernelSize=51;break;}case DepthOfFieldEffectBlurLevel.Medium:{blurCount=2;kernelSize=31;break;}default:{kernelSize=15;blurCount=1;break;}}var adjustedKernelSize=kernelSize/Math.pow(2,blurCount-1);var ratio=1.0;for(var i=0;i<blurCount;i++){var blurY=new BABYLON.DepthOfFieldBlurPostProcess(\"verticle blur\",scene,new BABYLON.Vector2(0,1.0),adjustedKernelSize,ratio,null,_this._circleOfConfusion,i==0?_this._circleOfConfusion:null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,scene.getEngine(),false,pipelineTextureType,blockCompilation);blurY.autoClear=false;ratio=0.75/Math.pow(2,i);var blurX=new BABYLON.DepthOfFieldBlurPostProcess(\"horizontal blur\",scene,new BABYLON.Vector2(1.0,0),adjustedKernelSize,ratio,null,_this._circleOfConfusion,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,scene.getEngine(),false,pipelineTextureType,blockCompilation);blurX.autoClear=false;_this._depthOfFieldBlurY.push(blurY);_this._depthOfFieldBlurX.push(blurX);}// Set all post processes on the effect.\n_this._effects=[_this._circleOfConfusion];for(var i=0;i<_this._depthOfFieldBlurX.length;i++){_this._effects.push(_this._depthOfFieldBlurY[i]);_this._effects.push(_this._depthOfFieldBlurX[i]);}// Merge blurred images with original image based on circleOfConfusion\n_this._dofMerge=new BABYLON.DepthOfFieldMergePostProcess(\"dofMerge\",_this._circleOfConfusion,_this._circleOfConfusion,_this._depthOfFieldBlurX,ratio,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,scene.getEngine(),false,pipelineTextureType,blockCompilation);_this._dofMerge.autoClear=false;_this._effects.push(_this._dofMerge);return _this;}",
"function colorAlgorithm(){\n\tvar temp = new Array();\n\t\n\tvar tag2 = document.getElementById('gloss').value;\n\tglossiness = tag2;\n\t\n\tvar lightVector = new Vector3([500, 500, 500]);\n\tlightVector.normalize();\n\tvar lightVector2 = new Vector3([0,500,0]);\n\tlightVector2.normalize();\n\t\tfor (var j = 3; j < normies.length; j+=6){\n\t\t\tvar nVector = new Vector3([normies[j],normies[j+1],normies[j+2]]);\n\t\t\tnVector.normalize();\n\t\t\tvar reflect = calcR(nVector,lightVector); //two times dot times normal minus lightdirection\n\t\t\tvar dot = (\n\t\t\t\tnormies[j] * lightVector.elements[0] +\n\t\t\t\tnormies[j+1] * lightVector.elements[1] +\n\t\t\t\tnormies[j+2] * lightVector.elements[2]\n\t\t\t\t);\n\t\t\t\tdot = dot/256; //////color hack\n\n\t\t\tif (pointLight&&lightDir.checked){\t\t\t\t\n\t\t\t\tvar L = new Vector3([\n\t\t\t\t\tlightVector2.elements[0] - normies[j],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+1],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+2]\n\t\t\t\t]);\n\t\t\t\tvar dot2 = (\n\t\t\t\t\tnormies[j] * lightVector2.elements[0] +\n\t\t\t\t\tnormies[j+1] * lightVector2.elements[1] +\n\t\t\t\t\tnormies[j+2] * lightVector2.elements[2]\n\t\t\t\t\t);\n\t\t\t\t\n\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1*dot2) + (1*dot) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + (0*dot) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + (0*dot) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1*dot2) + (1*dot) + Ia.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + (0*dot) + Ia.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + (0*dot) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\t\n\t\t\t\t}\t\t\n\t\t\t} else if (pointLight&&!lightDir.checked){\n\t\t\t\t\n\t\t\t\tvar L = new Vector3([\n\t\t\t\t\tlightVector2.elements[0] - normies[j],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+1],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+2]\n\t\t\t\t]);\n\t\t\t\tvar dot2 = (\n\t\t\t\t\tnormies[j] * lightVector2.elements[0] +\n\t\t\t\t\tnormies[j+1] * lightVector2.elements[1] +\n\t\t\t\t\tnormies[j+2] * lightVector2.elements[2]\n\t\t\t\t\t);\n\t\t\t\t\n\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1*dot2) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1*dot2) + Ia.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + Ia.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\t\n\t\t\t\t}\n\t\t\t} else if (lightDir.checked){\n\t\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1 * dot) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0 * dot) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0 * dot) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1 * dot) + Ia.elements[0];\n\t\t\t\t\tvar g = (0 * dot) + Ia.elements[1];\n\t\t\t\t\tvar b = (0 * dot) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse for (var k = 0; k < 20; k++) temp.push(0.5,0.5,0.5);\n\t\t}\n\t return temp;\n}",
"function applyBlur()\n\t\t\t\t{ TweenMax.set($('.main-img'), {webkitFilter:'blur('+ blurElement.a + 'px)'}); }",
"update(x,y){\n\n if (x > 0 & x < width){\n if(y > 0 & y < height/2){\n //if(!this.nearWall()){\n this.pos.x= x;\n this.pos.y= y;\n for (var i = 0; i < this.rays.length;i++) {\n this.rays[i].update(this.pos)\n let rmagold = Infinity;\n for(let bound of bounds){\n let rmag = bound.intersect(this.rays[i].pos,this.rays[i].dir);\n if(rmag < rmagold) rmagold = rmag;\n }\n this.rays[i].mag = rmagold;\n }\n //}\n }\n }\n }",
"function GaussianFilter(arr, w, h){\n\t\tvar k = 3,\n\t\t\tsigma = 1,\n\t\t\tg_filter = fspecial('gaussian', k, sigma),\n\t\t\td = Math.floor(k/2),\n\t\t\tnewArr = [];\n\n\t\tnewArr = arr;\n\n\t\tfor (var x = d; x < w-d; x++) {\n\t\t\tfor (var y = d; y < h-d; y++) {\n\t\t\t\tvar i = getPixel(x, y, w),\n\t\t\t\t\tiArr = [\n\t\t\t\t\t\t[getPixel(x-1, y-1, w),getPixel(x, y-1, w),getPixel(x+1, y-1, w)],\n\t\t\t\t\t\t[getPixel(x-1, y, w),i,getPixel(x+1, y, w)],\n\t\t\t\t\t\t[getPixel(x-1, y+1, w),getPixel(x, y+1, w),getPixel(x+1, y+1, w)]\n\t\t\t\t\t],\n\t\t\t\t\tr=[],g=[],b=[];\n\t\t\t\tiArr.map(function(a){\n\t\t\t\t\tr.push([]);\n\t\t\t\t\tg.push([]);\n\t\t\t\t\tb.push([]);\n\t\t\t\t\ta.map(function(c){\n\t\t\t\t\t\tr[r.length-1].push(arr[c]);\n\t\t\t\t\t\tg[g.length-1].push(arr[c+1]);\n\t\t\t\t\t\tb[b.length-1].push(arr[c+2]);\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tnewArr[i]=Math.floor(sum(mult(r,g_filter)))%255;\n\t\t\t\tnewArr[i+1]=Math.floor(sum(mult(g,g_filter)))%255;\n\t\t\t\tnewArr[i+2]=Math.floor(sum(mult(b,g_filter)))%255;\n\t\t\t}\n\t\t}\n\t\treturn newArr;\n\t}",
"function smoothterrain(rounding) {\n // Smussa il profilo del terreno.\n var n;\n while (rounding) {\n for (ptr = 0; ptr < 39798; ptr++) {\n n = p_surfacemap[ptr];\n n += p_surfacemap[ptr + 1];\n n += p_surfacemap[ptr + 200];\n n += p_surfacemap[ptr + 201];\n p_surfacemap[ptr] = n >> 2;\n }\n rounding--;\n }\n}",
"function smoothHeightMap(){\n if(G.length == 0){\n return;\n }\n for(var i = 0; i < N; i++){\n for(var j = 0; j < N; j++){\n G[i][j] = average(mapValue(G, i-1, j-1, max),\n mapValue(G, i-1, j, max),\n mapValue(G, i-1, j+1, max),\n mapValue(G, i, j-1, max),\n mapValue(G, i, j+1, max),\n mapValue(G, i+1, j-1, max),\n mapValue(G, i+1, j, max),\n mapValue(G, i+1, j+1, max));\n }\n }\n draw(G, N);\n}",
"static center(scene, camera, controls, axis, caf, inverse) {\n let BbMaxx = -Infinity;\n let BbMaxy = -Infinity;\n let BbMaxz = -Infinity;\n let BbMinx = Infinity;\n let BbMiny = Infinity;\n let BbMinz = Infinity;\n for (let i = 0; i < scene.children.length; i++) {\n if (scene.children[i] instanceof Camera ||\n scene.children[i] instanceof Light)\n continue;\n let bhelper = new BoxHelper(scene.children[i], 0xff0000);\n bhelper.geometry.computeBoundingBox();\n let WRSmin = bhelper.localToWorld(bhelper.geometry.boundingBox.min);\n let WRSmax = bhelper.localToWorld(bhelper.geometry.boundingBox.max);\n if (WRSmin.x < BbMinx) {\n BbMinx = WRSmin.x;\n }\n if (WRSmin.y < BbMiny) {\n BbMiny = WRSmin.y;\n }\n if (WRSmin.z < BbMinz) {\n BbMinz = WRSmin.z;\n }\n if (WRSmax.x > BbMaxx) {\n BbMaxx = WRSmax.x;\n }\n if (WRSmax.y > BbMaxy) {\n BbMaxy = WRSmax.y;\n }\n if (WRSmax.z > BbMaxz) {\n BbMaxz = WRSmax.z;\n }\n }\n if (BbMinx === Infinity) {\n BbMaxx = -10;\n BbMaxy = -10;\n BbMaxz = -10;\n BbMinx = 10;\n BbMiny = 10;\n BbMinz = 10;\n }\n\n var length = new Vector3(BbMaxx - BbMinx,\n BbMaxy - BbMiny,\n BbMaxz - BbMinz);\n\n var center = new Vector3(BbMinx + (length.x / 2),\n BbMiny + (length.y / 2),\n BbMinz + (length.z / 2));\n\n if (camera.type === CAMERA_TYPE.OrthographicCamera) {\n\n let lengthX = 0;\n let lengthY = 0;\n switch (axis) {\n case 0:\n lengthX = length.z;\n lengthY = length.y;\n break;\n case 1:\n lengthX = length.z;\n lengthY = length.x;\n break;\n case 2:\n lengthX = length.x;\n lengthY = length.y;\n break;\n default:\n break;\n }\n let aspectWidth = window.innerWidth / lengthX;\n let aspectHeight = window.innerHeight / lengthY;\n let maxIsWidth = aspectWidth < aspectHeight;\n if (!maxIsWidth) {\n let aspect = window.innerWidth / window.innerHeight;\n camera.left = lengthY * aspect * caf / -2;\n camera.right = lengthY * aspect * caf / 2;\n camera.top = lengthY * caf / 2;\n camera.bottom = lengthY * caf / -2;\n camera.position.set(0, 0, 0).setComponent(axis, center.getComponent(axis) + (lengthY * caf * inverse));\n\n } else {\n let aspect = window.innerHeight / window.innerWidth;\n camera.left = lengthX * caf / -2;\n camera.right = lengthX * caf / 2;\n camera.top = lengthX * aspect * caf / 2;\n camera.bottom = lengthX * aspect * caf / -2;\n camera.position.set(0, 0, 0).setComponent(axis, center.getComponent(axis) + (lengthX * caf * inverse));\n }\n\n\n } else {\n var maxLenght = Math.max(length.x, length.z);\n let dist = (maxLenght * caf) / 2 / Math.tan(Math.PI * camera.fov / 360);\n camera.position.set(center.x, center.y, center.z + (maxLenght * caf));\n if (controls) {\n controls.target = new Vector3(0, center.y, 0);\n }\n }\n camera.updateProjectionMatrix();\n }",
"function computeSurfaceArea( bounds ) {\n\n\tconst d0 = bounds[ 3 ] - bounds[ 0 ];\n\tconst d1 = bounds[ 4 ] - bounds[ 1 ];\n\tconst d2 = bounds[ 5 ] - bounds[ 2 ];\n\n\treturn 2 * ( d0 * d1 + d1 * d2 + d2 * d0 );\n\n}",
"function makeitBlur() {\n if (imageisloaded(image5)){\n output=new SimpleImage(image5.getWidth(),image5.getHeight());\n for (var px of image5.values()) {\n var x = px.getX();\n var y = px.getY();\n \n if(Math.random()<0.5){\n output.setPixel(x,y,px);\n }\n //if not, call getnewPixel() (does math, returns new pixel), call it newpix, set that new pixel to output \n else{\n newinpix = getnewPixel(image5,x,y);\n output.setPixel(x,y,newinpix);\n }\n output.drawTo(canvas);\n }\n } \n}",
"function thermalErode(){\n\t\tvar limitDiff = 0.004;\n\t\tvar limitDiffSq=limitDiff*limitDiff;\n\t\tfor (var it=0;it<100;it++){\t//want at least as many iterations as scale of features. to be safe, size of terrain\n\t\t\tfor (ii=0;ii<procTerrainSize;ii++){\n\t\t\t\tvar iiplus = (ii+1)%procTerrainSize;\n\t\t\t\tfor (jj=0;jj<procTerrainSize;jj++){\n\t\t\t\t\tvar centreHeight = allData[ii][jj];\n\n\t\t\t\t\tvar diffX1 = allData[iiplus][jj] - centreHeight;\n\n\t\t\t\t\tvar jjplus = (jj+1)%procTerrainSize;\n\t\t\t\t\tvar diffY1 = allData[ii][jjplus] - centreHeight;\n\n\t\t\t\t\t//\"surplus\" gradient\n\t\t\t\t\tvar gradTotalSq = diffX1*diffX1 + diffY1*diffY1;\n\t\t\t\t\tif (gradTotalSq<limitDiffSq){\n\t\t\t\t\t\tgradDataX[ii][jj]=0;\t//no surplus gradient (within limit)\n\t\t\t\t\t\tgradDataY[ii][jj]=0;\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//var extraScaleFactor = (Math.sqrt(gradTotalSq)- Math.sqrt(limitDiffSq))/Math.sqrt(gradTotalSq);\n\t\t\t\t\t\tvar extraScaleFactor = 1-limitDiff/Math.sqrt(gradTotalSq);\n\t\t\t\t\t\tgradDataX[ii][jj]=diffX1*extraScaleFactor;\n\t\t\t\t\t\tgradDataY[ii][jj]=diffY1*extraScaleFactor;\n\n\t\t\t\t\t\t//this works ok too. maybe more efficient.\n\t\t\t\t\t\t// gradDataX[ii][jj]=10.0*diffX1*(gradTotalSq-limitDiffSq);\t//is equation right? might combo with above by min/max\n\t\t\t\t\t\t// gradDataY[ii][jj]=10.0*diffY1*(gradTotalSq-limitDiffSq);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar multiplier = 0.2;\n\t\t\tfor (ii=0;ii<procTerrainSize;ii++){\n\t\t\t\tfor (jj=0;jj<procTerrainSize;jj++){\n\t\t\t\t\tvar iiplus = (ii+1)%procTerrainSize;\n\t\t\t\t\tvar jjplus = (jj+1)%procTerrainSize;\n\n\t\t\t\t\tallData[iiplus][jjplus]+=multiplier*gradDataX[iiplus][jjplus];\n\t\t\t\t\tallData[iiplus][jjplus]+=multiplier*gradDataY[iiplus][jjplus];\n\t\t\t\t\tallData[iiplus][jjplus]-=multiplier*gradDataX[ii][jj];\n\t\t\t\t\tallData[iiplus][jjplus]-=multiplier*gradDataY[ii][jj];\n\t\t\t\t\tallData[iiplus][jjplus]+=multiplier*gradDataX[iiplus][jj];\n\t\t\t\t\tallData[iiplus][jjplus]-=multiplier*gradDataY[iiplus][jj];\n\t\t\t\t\tallData[iiplus][jjplus]-=multiplier*gradDataX[ii][jjplus];\n\t\t\t\t\tallData[iiplus][jjplus]+=multiplier*gradDataY[ii][jjplus];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"_getVesselTexture(radius, blurFactor) {\n const tplCanvas = document.createElement('canvas');\n const tplCtx = tplCanvas.getContext('2d');\n const diameter = radius * 2;\n tplCanvas.width = (diameter * 2) + 1; // tiny offset between 2 frames\n tplCanvas.height = (diameter * VESSELS_HUES_INCREMENTS_NUM) + VESSELS_HUES_INCREMENTS_NUM;\n\n for (let hueIncrement = 0; hueIncrement < VESSELS_HUES_INCREMENTS_NUM; hueIncrement++) {\n const y = (diameter * hueIncrement) + hueIncrement;\n const yCenter = y + radius;\n\n // heatmap style\n let x = radius;\n const gradient = tplCtx.createRadialGradient(x, yCenter, radius * blurFactor, x, yCenter, radius);\n const hue = hueIncrementToHue(hueIncrement);\n const rgbString = hueToRgbString(hue);\n gradient.addColorStop(0, rgbString);\n\n const rgbOuter = hsvToRgb(wrapHue(hue + 30), 80, 100);\n gradient.addColorStop(1, `rgba(${rgbOuter.r}, ${rgbOuter.g}, ${rgbOuter.b}, 0)`);\n\n tplCtx.fillStyle = gradient;\n tplCtx.fillRect(0, y, diameter, diameter);\n\n // circle style\n x += diameter + 1; // tiny offset between 2 frames\n tplCtx.beginPath();\n tplCtx.arc(x, yCenter, radius, 0, 2 * Math.PI, false);\n tplCtx.fillStyle = rgbString;\n tplCtx.fill();\n }\n\n return tplCanvas;\n }",
"function computeSlopeMask(threshold) {\n var minWaterMask = mndwiMax.gt(ndwiMinWater) // maximum looks like water\n var maxLandMask = mndwiMin.lt(ndwiMaxLand) // minimum looks like land\n \n var mask = scale.unmask().abs().gt(threshold)\n .multiply(minWaterMask) \n .multiply(maxLandMask) \n\n if(ndviFilter > -1) {\n var ndviMask = ndviMin.lt(ndviFilter)\n mask = mask.multiply(ndviMask) // deforestation?\n }\n\n if(filterCount > 0) {\n var countMask = annualPercentile.select('count').min().gt(filterCount)\n mask = mask.multiply(countMask);\n }\n \n if(options.useSwbdMask) {\n mask = mask.multiply(swbdMask)\n }\n \n // add eroded original scale mask (small scale-friendly erosion, avoid kernel too large)\n var erodedScaleMask = scaleMask\n .focal_min(10000, 'square', 'meters').reproject('EPSG:4326', null, 1000)\n\n mask = mask.multiply(erodedScaleMask)\n\n if(options.debugMapLayers) {\n Map.addLayer(minWaterMask.not().mask(minWaterMask.not()), {}, 'min water mask', false)\n Map.addLayer(maxLandMask.not().mask(maxLandMask.not()), {}, 'max land mask', false)\n \n if(ndviFilter > -1) {\n Map.addLayer(ndviMask.not().mask(ndviMask.not()), {}, 'ndvi mask', false)\n }\n if(filterCount > 0) {\n Map.addLayer(countMask.not().mask(countMask.not()), {}, 'count mask', false)\n }\n \n if(options.useSwbdMask) {\n Map.addLayer(swbdMask.not().mask(swbdMask.not()), {}, 'swbd mask', false)\n }\n \n Map.addLayer(erodedScaleMask.not().mask(erodedScaleMask.not()), {}, 'scale original mask (eroded)', false)\n }\n\n return mask;\n }",
"function preproc()\n{\n // nodal coordinates as passed to opengl\n let coords = []\n // 3 corner nodes of a face to compute the face normal in the shader\n let As = []\n let Bs = []\n let Cs = []\n // triangles as passed to open gl\n let trias = []\n // displacement vector per vertex to displace said vertex\n let disps = []\n // global min/max to normalize result amplitudes\n let min = 0.0\n let max = 0.0\n // texture coordinates to properly map results per face\n let texcoords = []\n // all four corner nodes to compute the texture mapping\n let corners = []\n\n // for each quad\n for(let i = 0; i < quads.length; ++i) {\n let quad = quads[i]\n // triangulate\n trias.push(4 * i + 0, 4 * i + 1, 4 * i + 2, 4 * i + 0, 4 * i + 2, 4 * i + 3)\n // set texture coordinates\n texcoords.push(\n 0.0, 0.0,\n 0.0, 1.0,\n 1.0, 1.0,\n 1.0, 0.0\n )\n // push coordinates\n coords.push(\n nodes[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2],\n nodes[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2],\n nodes[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2],\n nodes[3 * quad[3] + 0],\n nodes[3 * quad[3] + 1],\n nodes[3 * quad[3] + 2])\n // push A,B and C corner nodes to compute the face normal\n As.push(\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2],\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2],\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2],\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2])\n Bs.push(\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2],\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2],\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2],\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2])\n Cs.push(\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2],\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2],\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2],\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2])\n // push displacements\n disps.push(\n results[3 * quad[0] + 0],\n results[3 * quad[0] + 1],\n results[3 * quad[0] + 2],\n results[3 * quad[1] + 0],\n results[3 * quad[1] + 1],\n results[3 * quad[1] + 2],\n results[3 * quad[2] + 0],\n results[3 * quad[2] + 1],\n results[3 * quad[2] + 2],\n results[3 * quad[3] + 0],\n results[3 * quad[3] + 1],\n results[3 * quad[3] + 2])\n let sqr = x => x*x;\n min = globalMin\n max = globalMax\n let result = state.component\n if(result == 3) {\n let sqr = (x) => x*x;\n corners.push(\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])),\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])),\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])),\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])))\n } else {\n corners.push(\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result],\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result],\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result],\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result])\n }\n // pick the appropriate min/max per the selected component\n max = max[result]\n min = min[result]\n }\n\n document.getElementById('progress').innerHTML = ''\n return {\n coords: coords,\n trias: trias,\n disps: disps,\n As: As,\n Bs: Bs,\n Cs, Cs,\n min: min,\n max: max,\n texcoords: texcoords,\n corners: corners\n }\n}",
"function subpixelColor(ray, objects, recursionDepth) {\n // determine the closest intersecting object\n const intersectData = intersection(ray, objects, Infinity);\n const closest = intersectData.obj;\n const tVal = intersectData.tVal;\n\n // compute color of each sub-pixel\n let resultColor = backgroundColor;\n if (closest != null) { // hit an object\n // transform the ray according to the object's inverse transformation matrix\n const transOrigin = util.transformPosition(ray.origin,\n closest.inverseTransform);\n const transDirection = util.transformDirection(ray.direction,\n closest.inverseTransform);\n const transRay = new Ray(transOrigin, transDirection);\n\n // find intersection of the (transformed) ray and the untransformed object\n const transPoint = transRay.pointAtParameter(tVal);\n const transNormal = closest.normal(transPoint, transRay.direction);\n\n // transform back to get intersection of the original ray and the transformed object\n // TODO: make a pre-computing function?\n const point = util.transformPosition(transPoint, closest.transform);\n let normal = util.transformDirection(transNormal,\n mat4.transpose(mat4.create(), closest.inverseTransform));\n vec3.normalize(normal, normal);\n let viewDirection = vec3.subtract(vec3.create(), ray.origin, point);\n vec3.normalize(viewDirection, viewDirection);\n const color = closest.colorAt(transPoint);\n const ambientColor = closest.ambientColorAt(transPoint);\n const ambientLight = closest.ambientLightAt(transPoint);\n const specularColor = closest.specularColorAt(transPoint);\n const specularLight = closest.specularLightAt(transPoint);\n const shininess = closest.shininess;\n const overPoint = biasedPoint(point, normal, Math.pow(10, -4)); // for shadow\n\n const ambient = computeAmbient(ambientColor, ambientLight); // independent of light\n let diffuse = [];\n let specular = [];\n let shadow = [];\n if (softShadowOn) {\n // for each sampling point in area light, compute diffuse, specular, and\n // shadow and accumulate\n let totalDiffuse = [0, 0, 0];\n let totalSpecular = [0, 0, 0];\n let totalShadow = [0, 0, 0];\n for (let uc = 0; uc < light.usteps; uc++) {\n for (let vc = 0; vc < light.vsteps; vc++) {\n const lightPoint = light.pointAt(uc, vc);\n let lightDirection = vec3.subtract(vec3.create(), lightPoint, point);\n vec3.normalize(lightDirection, lightDirection);\n\n // intermediates\n const diffuseI = computeDiffuse(color, normal, lightDirection);\n let halfVector = vec3.add(vec3.create(), viewDirection, lightDirection);\n vec3.normalize(halfVector, halfVector);\n const specularI = computeSpecular(specularColor, specularLight,\n normal, halfVector, shininess);\n const shadowRayI = new Ray(overPoint, lightDirection);\n const tLightI = vec3.distance(point, lightPoint);\n const shadowI = isInShadow(shadowRayI, tLightI, lightDirection, objects);\n\n // accumulate\n for (let c = 0; c < 3; c++) {\n totalDiffuse[c] += diffuseI[c];\n totalSpecular[c] += specularI[c];\n totalShadow[c] += shadowI[c];\n }\n }\n }\n // compute average diffuse, specular, and shadow\n for (let c = 0; c < 3; c++) {\n diffuse[c] = totalDiffuse[c] / light.samples;\n }\n for (let c = 0; c < 3; c++) {\n specular[c] = totalSpecular[c] / light.samples;\n }\n for (let c = 0; c < 3; c++) {\n shadow[c] = totalShadow[c] / light.samples;\n }\n } else {\n // treat area light as point light\n const lightDirection = vec3.subtract(vec3.create(), light.position, point);\n vec3.normalize(lightDirection, lightDirection);\n\n diffuse = computeDiffuse(color, normal, lightDirection);\n let halfVector = vec3.add(vec3.create(), viewDirection, lightDirection);\n vec3.normalize(halfVector, halfVector);\n specular = computeSpecular(specularColor, specularLight, normal,\n halfVector, shininess);\n const shadowRay = new Ray(overPoint, lightDirection);\n const tLight = vec3.distance(point, light.position);\n shadow = isInShadow(shadowRay, tLight, lightDirection, objects);\n }\n // compute final color of the sub-pixel\n resultColor = computeFinalColor(closest, ambient, diffuse, specular, shadow);\n\n // reflection and refraction\n // TODO: early termination if no significant color contribution\n if (recursionDepth < MAX_RECURSION) {\n // TODO: implement different materials\n const transparent = closest.getTransparency(transPoint);\n const reflective = closest.getReflectivity(transPoint);\n\n if (transparent && reflective) { // TODO: implemenet \"dielectric\" object type\n // compute fresnel (schlick's approximation)\n const reflectance = schlick(ray.direction, normal, closest.ior);\n\n // compute light attenuation according to beer's law\n const rayFromOutside = vec3.dot(ray.direction, normal) < 0;\n let absorb = [1, 1, 1];\n if (!rayFromOutside) { // ray inside the object\n absorb = closest.colorFilter.map(x => Math.pow(x, tVal));\n }\n\n // find refracted color\n let refractedColor = [0, 0, 0];\n if (reflectance < 1) { // no total internal reflection\n // cast refraction ray\n const refractOrigin = rayFromOutside ? biasedPoint(point, normal,\n -Math.pow(10, -4)) : biasedPoint(point, normal, Math.pow(10, -4));\n const refractDirection = refract(ray.direction, normal, closest.ior);\n const refractRay = new Ray(refractOrigin, refractDirection);\n refractedColor = subpixelColor(refractRay, objects, recursionDepth + 1);\n }\n\n // find reflected color\n let reflectedColor = closest.glowColor;\n if (reflectedColor == null) {\n // cast reflection ray\n const reflectOrigin = rayFromOutside ? biasedPoint(point, normal,\n Math.pow(10, -4)) : biasedPoint(point, normal, -Math.pow(10, -4));\n const reflectDirection = reflect(ray.direction, normal);\n const reflectRay = new Ray(reflectOrigin, reflectDirection);\n reflectedColor = subpixelColor(reflectRay, objects, recursionDepth + 1);\n }\n\n // combine reflected and refracted color and accumulate\n for (let c = 0; c < 3; c++) {\n resultColor[c] += absorb[c] * (reflectance * (reflectedColor[c] / 255) +\n (1 - reflectance) * (refractedColor[c] / 255));\n }\n }\n\n else if (reflective) {\n // compute reflection ray\n const rayFromOutside = vec3.dot(ray.direction, normal) < 0;\n const reflectOrigin = rayFromOutside ? biasedPoint(point, normal,\n Math.pow(10, -4)) : biasedPoint(point, normal, -Math.pow(10, -4));\n const reflectDirection = reflect(ray.direction, normal);\n const reflectRay = new Ray(reflectOrigin, reflectDirection);\n\n // cast reflection ray and accumulate reflected color\n const reflectedColor = subpixelColor(reflectRay, objects, recursionDepth + 1);\n for (let c = 0; c < 3; c++) {\n resultColor[c] += 0.8 * reflective * (reflectedColor[c] / 255); // TODO: remove 0.8?\n }\n }\n\n else if (transparent) {\n // compute refraction (transmittance) ray\n const rayFromOutside = vec3.dot(ray.direction, normal) < 0;\n const refractOrigin = rayFromOutside ? biasedPoint(point, normal,\n -Math.pow(10, -4)) : biasedPoint(point, normal, Math.pow(10, -4));\n const refractDirection = refract(ray.direction, normal, closest.ior);\n const refractRay = new Ray(refractOrigin, refractDirection);\n\n // cast refraction ray and accumulate refracted color\n const refractedColor = subpixelColor(refractRay, objects, recursionDepth + 1);\n for (let c = 0; c < 3; c++) {\n resultColor[c] += transparent * (refractedColor[c] / 255);\n }\n }\n }\n }\n\n // clamp between 0 and 1, then multiply by 255\n for (let c = 0; c < 3; c++) {\n resultColor[c] = Math.min(1, Math.max(0, resultColor[c])) * 255;\n }\n return resultColor;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Log manipulation functions +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ name of fight log Varname | function getFightLogVarname() {
return "estiah_pvp_fight_log_" + getUsername();
} | [
"attackMissLog(){\n let logString = `\\n${this.name} missed their attack!`;\n this.updateBattleLog(logString);\n }",
"attackHitLog(enemyName){\n let logString = `\\n${this.name} hit ${enemyName} for ${this.attack} damage!`;\n this.updateBattleLog(logString);\n }",
"getLogType() {\n\t\treturn LOG_TYPE;\n\t}",
"function myFun() \n{\n console.log(const_v,let_v,var_n);\n}",
"function MakeLogFilePathName(root)\r\n{\r\n var bdir, lfn;\r\n \r\n \r\n //\r\n // Construct/use folder path and create the folder if needed\r\n //\r\n bdir = root + \"\\\\\" + \"SystemSwap\"; // Substitute for directory path\r\n CreateFolder(bdir); // Make sure folder exists\r\n \r\n //\r\n // Construct the file name safely \r\n //\r\n lfn = \"SystemSwap-\" + Util.FormatVar(new Date().getVarDate(), \"yyyymmdd-HhNnSs\") + \".log\";\r\n \r\n \r\n \r\n return bdir + \"\\\\\" + lfn; // Return final path/name\r\n}",
"function logger(first, last) {\n console.log(first, last);\n const age = 20;\n\n console.log(age, fullName);\n}",
"function createVar(varName,value) {\n var varName = value;\n console.log(\"Value of your variable is currently \" + varName)\n}",
"function PrisonBecomeBadGirl() {\n\tLogAdd(\"Joined\", \"BadGirl\");\n}",
"function writeLog(brand) {\n let log = `content automatically generated by the script './branding/set_brand.js'\n\nBRAND ........... ${brand}\nRESOURCES ....... branding/brands/${brand}/resources => resources\nASSETS .......... branding/brands/${brand}/assets => src/assets\nSERVERCONFIG .... branding/common/config/server.config.json + branding/brands/${brand}/config.json => src/assets/config.json\nPROJECTCONFIG ... config.xml + branding/brands/${brand}/config.json => config.xml\nLANGUAGE ........ branding/common/i18n/* + branding/brands/${brand}/assets/i18n/* => src/assets/i18n/*\nBUILD ........... branding/brands/${brand}/build.json => build.json\n\nCONSOLE OUTPUT\n${console_log}`;\n FS.writeFileSync(\"branding/set_brand.log\", log);\n}",
"function logKeywords(keyword){\n $.each(keyword,function(key,value){\n if(!(value in fundamental_vars.log)){\n fundamental_vars.log[value] = {};\n }\n });\n}",
"initiateVariableName() {\n this.variableName = this.variableName || `val_${this.compiler.referenceVariableCounter++}`;\n }",
"function logText(text) {\n\tif(config.dev_log) {\n\t\tvar currentTime = new Date();\n\t\tvar currentDay = ensureNumberStringLength(currentTime.getDate(), 2);\n\t\tvar currentMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][currentTime.getMonth()];\n\t\tvar currentYear = currentTime.getFullYear();\n\t\tvar currentHours = ensureNumberStringLength(currentTime.getHours(), 2);\n\t\tvar currentMinutes = ensureNumberStringLength(currentTime.getMinutes(), 2);\n\t\tvar currentSeconds = ensureNumberStringLength(currentTime.getSeconds(), 2);\n\n\t\tvar timestamp = ' [{dd}/{month}/{yyyy} {hh}:{mm}:{ss}] '.format({\n\t\t\tdd: currentDay, month: currentMonth, yyyy: currentYear,\n\t\t\thh: currentHours, mm: currentMinutes, ss: currentSeconds\n\t\t});\n\n\t\tvar textArray = text.split('\\n');\n\n\t\tfor (var i = textArray.length - 1; i > 0; i--) {\n\t\t\t$('.log-pre').prepend('<span class=\"log-time\">{whitespace}</span>{text}\\n'.format({\n\t\t\t\twhitespace: ' '.repeat(24),\n\t\t\t\ttext: textArray[i]}));\n\t\t}\n\t\t$('.log-pre').prepend('<span class=\"log-time\">{stamp}</span>{text}\\n'.format({\n\t\t\tstamp: timestamp,\n\t\t\ttext: textArray[0]}));\n\t} else {\n\t\twindow.console.log(text);\n\t}\n}",
"function printLogDirectoryHint () {\n console.log(' \"logDir\" is the path to the directory to store logs in')\n console.log(' A typical \"logDir\" looks like: \"logDir\": \"logs\"')\n}",
"logAPI(apiName, uniqueID){\n logger.Logger.log('API Entry','Entry raised for transaction ID ' + uniqueID + ' from ' + apiName, '' ,5,false);\n }",
"getLogs() {\n this.logs.map((log)=>{\n console[log.type].call(null, log.msg);\n })\n }",
"function createVariable() {\n\t var id = nextVariableId++;\n\t var name = '$V';\n\t\n\t do {\n\t name += variableTokens[id % variableTokensLength];\n\t id = ~~(id / variableTokensLength);\n\t } while (id !== 0);\n\t\n\t return name;\n\t}",
"function trackListener(listenerName) {\r\n\tvar d = new Date();\r\n\tvar t = d.getTime();\r\n\r\n\tconsole.log(listenerName + ' was created at time: ' + t);\r\n}",
"function log(log){\n console.log(log);\n logbook.push(new Date(Date.now()).toLocaleString() + \":\" + log);\n if(log_channel != null){\n log_channel.send(\"`\"+log+\"`\");\n }\n}",
"function print_server_config(){\n log(\"Server Config:\\n-> SERVER: \" + guild.toString() + \"\\n-> LOG CHANNEL: \" + log_channel.name + \"\\n-> Meeting Timeout Time(s):\" + server.MEETING_TIMEOUT_TIME); \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the current LED from the API | function lookupNewLed() {
got(LED_URL)
.then(response => {
//console.log("API call finished with response: "+response.body);
if (response.body) {
try {
temp = new Number(response.body);
//console.log("Temp: "+temp);
if (temp >= 0 && temp < strip.length) {
setCurrentLed(temp);
}
} catch (e) {
console.log("Invalid number returned from the API: " + e.message);
}
}
})
.catch(err => {
console.error(err);
});
} | [
"function getCurrentLed() {\n return led;\n}",
"function toggleLED(url, res) {\n var indexRegex = /(\\d)$/;\n var result = indexRegex.exec(url);\n var index = +result[1];\n \n var led = tessel.led[index];\n \n led.toggle(function (err) {\n if (err) {\n console.log(err);\n res.writeHead(500, {\"Content-Type\": \"application/json\"});\n res.end(JSON.stringify({error: err}));\n } else {\n res.writeHead(200, {\"Content-Type\": \"application/json\"});\n res.end(JSON.stringify({on: led.isOn}));\n }\n });\n}",
"function updateLeds() {\n if (led_state.Red===\"blink\") {\n GPIO.blink(pin_Red, blink_On, blink_Off);\n }else {\n GPIO.blink(pin_Red,0,0); //Turn off blinking\n let redlight=(led_state.Red==='1') ? 1:0 ; \n GPIO.write(pin_Red,redlight);\n }\n if (led_state.Blue===\"blink\") {\n GPIO.blink(pin_Blue, blink_On, blink_Off);\n }else {\n GPIO.blink(pin_Blue,0,0); //Turn off blinking\n let bluelight=(led_state.Blue==='1') ? 1:0 ; \n GPIO.write(pin_Blue,bluelight);\n }\n}",
"function ledOnOff(event,x,y) {\n\t//set brightness to off (0)\n\tvar brightness = 0;\n //set current LED\n\tvar currentLED = document.getElementById('led('+x+','+y+')');\n var LEDTest = window.getComputedStyle(currentLED, null).getPropertyValue('background-color');\n //if LED off then switch on (turn red)\n if (LEDTest == 'rgb(128, 128, 128)') {\n \tcurrentLED.style.backgroundColor = 'red'; //rgb(255, 0, 0)\n //set brightness to max (9)\n brightness = 9;\n }\n //if LED not off then switch off (grey)\n if (LEDTest != 'rgb(128, 128, 128)') {\n \tcurrentLED.style.backgroundColor = 'grey'; //rgb(51, 51, 51)\n //set brightness to off (0)\n brightness = 0;\n } \n}",
"get lightsOn()\r\n\t{\r\n\t\treturn this._lightsOn;\r\n\t}",
"static availableAPI(builder) {\n\t\tbuilder.state('brightness')\n\t\t\t.type('percentage')\n\t\t\t.description('The brightness of this light')\n\t\t\t.done();\n\n\t\tbuilder.event('brightness')\n\t\t\t.type('percentage')\n\t\t\t.description('The brightness of the light has changed')\n\t\t\t.done();\n\n\t\tbuilder.action('brightness')\n\t\t\t.description('Get or set the brightness of this light')\n\t\t\t.argument('change:brightness', true, 'The change in brightness or absolute brightness')\n\t\t\t.returns('percentage', 'The brightness of the light')\n\t\t\t.getterForState('brightness')\n\t\t\t.done();\n\t}",
"function drawStatusLED()\n {\n // Check faulted state\n var faultCount = Object.keys(fault_detector.getCurrentFaults()).length;\n if (faultCount > 0)\n {\n // Set LED to green\n image = document.getElementById('status_led');\n image.src = 'static/images/red_light.png';\n }\n else\n {\n image = document.getElementById('status_led');\n image.src = 'static/images/green_light.png';\n }\n }",
"function lightStatus(brightness) {\n let result = brightness;\n\n if (brightness == 0) {\n result = \"off\";\n } else if (brightness > 0 && brightness < 200) {\n result = \"dimmed\";\n } else if (brightness >= 200) {\n result = \"on\";\n }\n\n return result;\n}",
"function refresh() {\n $.get(\"/api?drone_uid=\" + droneUID + \"&subset=state\")\n .done(function(result) {\n // Available: result.command, result.voltage, result.status, result.error\n $(\"#current-command\").text(result.command);\n var status = result.status;\n if (status == \"disarmed\") {\n switchOff(\"#arm-switch\");\n switchOff(\"#motor-switch\");\n } else if (status == \"armed\") {\n switchOn(\"#arm-switch\");\n switchOff(\"#motor-switch\");\n } else if (status == \"throttled\") {\n switchOn(\"#arm-switch\");\n enableSwitch(\"#motor-switch\");\n switchOn(\"#motor-switch\");\n }\n });\n}",
"getTrafficLights() {\n\t\treturn this.trafficLights;\n\t}",
"function decode_light_control_status(data) {\n\tdata.command = 'bro';\n\tdata.value = 'light control status - ';\n\n\t// Examples\n\t//\n\t// D1 D2\n\t// 11 01 Intensity=1, Lights=on, Reason=Twilight\n\t// 21 02 Intensity=2, Lights=on, Reason=Darkness\n\t// 31 04 Intensity=3, Lights=on, Reason=Rain\n\t// 41 08 Intensity=4, Lights=on, Reason=Tunnel\n\t// 50 00 Intensity=5, Lights=off, Reason=N/A\n\t// 60 00 Intensity=6, Lights=off, Reason=N/A\n\t//\n\t// D1 - Lights on/off + intensity\n\t// 0x01 : Bit0 : Lights on\n\t// 0x10 : Bit4 : Intensity 1\n\t// 0x20 : Bit5 : Intensity 2\n\t// 0x30 : Bit4+Bit5 : Intensity 3\n\t// 0x40 : Bit6 : Intensity 4\n\t// 0x50 : Bit4+Bit6 : Intensity 5\n\t// 0x60 : Bit5+Bit6 : Intensity 6\n\t//\n\t// D2 - Reason\n\t// 0x01 : Bit0 : Twilight\n\t// 0x02 : Bit1 : Darkness\n\t// 0x04 : Bit2 : Rain\n\t// 0x08 : Bit3 : Tunnel\n\t// 0x10 : Bit4 : Garage\n\n\tconst mask1 = bitmask.check(data.msg[1]).mask;\n\tconst mask2 = bitmask.check(data.msg[2]).mask;\n\n\tconst parse = {\n\t\tintensity : null,\n\t\tintensity_str : null,\n\t\tintensities : {\n\t\t\tl1 : mask1.bit4 && !mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl2 : !mask1.bit4 && mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl3 : mask1.bit4 && mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl4 : !mask1.bit4 && !mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl5 : mask1.bit4 && !mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl6 : !mask1.bit4 && mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl0 : !mask1.bit4 && !mask1.bit5 && !mask1.bit6 && mask1.bit8,\n\t\t},\n\n\t\tlights : mask1.bit0,\n\t\tlights_str : 'lights on: ' + mask1.bit0,\n\n\t\treason : null,\n\t\treason_str : null,\n\t\treasons : {\n\t\t\ttwilight : mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\tdarkness : !mask2.bit0 && mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\train : !mask2.bit0 && !mask2.bit1 && mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\ttunnel : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\tgarage : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && mask2.bit4 && !mask2.bit8,\n\t\t\tnone : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && mask2.bit8,\n\t\t},\n\t};\n\n\t// Loop intensity object to obtain intensity level\n\tfor (const intensity in parse.intensities) {\n\t\tif (parse.intensities[intensity] === true) {\n\t\t\t// Convert hacky object key name back to integer\n\t\t\tparse.intensity = parseInt(intensity.replace(/\\D/g, ''));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Loop reason object to obtain reason name\n\tfor (const reason in parse.reasons) {\n\t\tif (parse.reasons[reason] === true) {\n\t\t\tparse.reason = reason;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Append prefixes to log strings\n\tparse.intensity_str = 'intensity: ' + parse.intensity;\n\tparse.reason_str = 'reason: ' + parse.reason;\n\n\tupdate.status('rls.light.intensity', parse.intensity, false);\n\tupdate.status('rls.light.lights', parse.lights, false);\n\tupdate.status('rls.light.reason', parse.reason, false);\n\n\t// Assemble log string\n\tdata.value += parse.intensity_str + ', ' + parse.lights_str + ', ' + parse.reason_str;\n\n\treturn data;\n}",
"function getDeviceStatus(axios$$1, token) {\n return restAuthGet(axios$$1, '/statuses/' + token);\n }",
"get_wlanState() {\n return this.liveFunc._wlanState;\n }",
"getTrafficLights() {\n\t\treturn TRAFFIC_LIGHTS;\n\t}",
"lightsOn() {\n console.log('[johnny-five] Lights are on.');\n this.lights.on();\n }",
"function getLightBulbStatusDisplayString(status) {\n let result = status;\n\n switch (status) {\n case \"on\":\n return \"The house is bright!\";\n break;\n case \"off\":\n return \"The house is dark\";\n break;\n case \"dimmed\":\n return \"The house is nice and dim\";\n break;\n case \"missing\":\n case \"offline\":\n return \"The house is dark and we can't find the lightbulb!\";\n break;\n case \"deleted\":\n return \"The lightbulb has been removed from the system\";\n break;\n case \"broken\":\n return \"The house is dark and we can't turn the light on!\";\n break;\n default:\n return \"Something is wrong!\";\n }\n\n return result;\n}",
"getInverter(id) {\r\n\t\tlet device = this.getDevice({ id: id });\r\n\t\tlet result;\r\n\t\tif (device) {\r\n\t\t\tresult = device.inverter;\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"controlViaOnOff() {\n console.log(\"entrou ONOFF\")\n this.output = this.getTemp() < this.setpoint ? 1023 : 0;\n this.board.pwmWrite(19 , 0, 25, 10, this.output);\n }",
"changeLedsColor(binaryNumber) {\n\n let ledList = this.state.leds;\n let binaryString = binaryNumber.toString();\n\n let binaryDiff = 8 - binaryString.length;\n\n for (let i=0;i<binaryDiff;i++) {\n ledList[i].color = 'grey';\n }\n\n for (let i=0;i<binaryString.length;i++) {\n let ledIndex = i + binaryDiff;\n\n if (binaryString.charAt(i) === '1') {\n ledList[ledIndex].color = 'green';\n } else {\n ledList[ledIndex].color = 'grey';\n }\n }\n\n this.setState({leds: ledList});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ending Portion/////////////////////////////////////////////////////////////////////// function awakenFromDream() the function containing the final dialog box, prompts the user to awaken from the nightmare | function awakenFromDream() {
// remove remnants of part 3 dialogs
$('.question3').remove();
$('.question4').remove();
// append the new div tag to the body
$('body').append("<div class = 'awakenPrompt'><div>");
// set the contents of the dialog box
$('.awakenPrompt').html("You have completely restored yourself and remember your place in the world. Whether or not you can put your doubts behind you can wait another day. For now, you can [Awaken] from your bitter dreams and banish the abyss.");
// variables for randomizing location of dialog boxes
let horizontalOffset = Math.floor(Math.random() * 201) - 100;
let verticalOffset = Math.floor(Math.random() * 401) - 200;
// annyang functionality, simple this time
if (annyang) {
var commands = {
'awaken': function() {
// set the project to its final state after 3 seconds
setTimeout(endingFunction, 3000);
responsiveVoice.speak("You acknowledge yourself. Forward us the only way.", 'UK English Male');
console.log('annyang working');
doorSFX.play();
}
}
// annyang functionality
annyang.addCommands(commands);
annyang.start();
}
// create the dialog box with all its parameters
$(".awakenPrompt").dialog({
position: {
my: `center`+ verticalOffset,
at: `center`+ horizontalOffset
},
height: 380,
width: 550,
close: function() {
responsiveVoice.speak("You must wake up. The nightmare is over.", 'UK English Male', options);
$(".question4").remove();
setTimeout(awakenFromDream, 5000);
},
closeOnEscape: false,
title: "The Third Layer - Resurgeance (3)"
});
} | [
"finishAskTheAudience() {\n this.serverState.askTheAudience.populateAllAnswerBuckets();\n this.playSoundEffect(Audio.Sources.ASK_THE_AUDIENCE_END);\n\n // Update game is called first to make sure ask the audience end audio cue plays.\n this._updateGame();\n this.showHostRevealHotSeatChoice();\n }",
"function PrisonCatchKneelingEscape() {\n\tCharacterSetActivePose(Player, null, true);\n\tInventoryWear(Player, \"Chains\", \"ItemArms\", \"Default\", 3);\n\tInventoryGet(Player, \"ItemArms\").Property = { Type: \"Hogtied\", SetPose: [\"Hogtied\"], Difficulty: 0, Block: [\"ItemHands\", \"ItemLegs\", \"ItemFeet\", \"ItemBoots\"], Effect: [\"Block\", \"Freeze\", \"Prone\"] };\n\tCharacterRefresh(Player);\n\tPrisonPolice.Stage = \"CatchAggressive5\";\n\tPrisonPolice.CurrentDialog = DialogFind(PrisonPolice, \"CatchAggressiveFailedEscape\");\n}",
"function completeContinuePhase () {\n\t/* show the player removing an article of clothing */\n\tprepareToStripPlayer(recentLoser);\n updateAllGameVisuals();\n\t\n\t$mainButton.html(\"Strip\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}",
"function PrisonFightPoliceEnd() {\n\tCommonSetScreen(\"Room\", \"Prison\");\n\tSkillProgress(\"Willpower\", ((Player.KidnapMaxWillpower - Player.KidnapWillpower) + (PrisonPolice.KidnapMaxWillpower - PrisonPolice.KidnapWillpower)) * 2);\n\tif (!KidnapVictory) {\n\t\tCharacterRelease(PrisonPolice);\n\t\tInventoryRemove(PrisonPolice, \"ItemNeck\");\n\t\tPrisonWearPoliceEquipment(PrisonPolice);\n\t\tPrisonPolice.CurrentDialog = DialogFind(PrisonPolice, \"CatchDefeat\");\n\t\tPrisonPolice.Stage = \"Catch\";\n\t}else{\n\t\tPrisonPolice.CurrentDialog = DialogFind(PrisonPolice, \"CatchVictoryIntro\");\n\t\tPrisonPolice.Stage = \"CatchVictory\";\n\t}\n\tCharacterSetCurrent(PrisonPolice);\n}",
"function promptAnotherAction() {\n inquirer.prompt([\n // Prompt user for yes or no\n {\n type: \"confirm\",\n message: \"Would you like to perform another action?\",\n name: \"anotherAction\",\n },\n ]).then(function (inquirerResponse) {\n // If yes to prompt\n if (inquirerResponse.anotherAction) {\n console.log();\n // Show products again\n promptSelection();\n } else {\n console.log(\"\\nGoodbye!\\n\");\n\n // End DB connection\n connection.end();\n }\n });\n}",
"function afterAction() {\n console.log(\"\\n\");\n\n inquirer.prompt([\n {\n type: \"list\",\n message: \"Would you like to perform another action?\",\n choices: [\"Yes\", \"No\"],\n name: \"action\"\n }\n ]).then(function (response) {\n switch (response.action) {\n case \"Yes\":\n askManager();\n break;\n\n case \"No\":\n return;\n break;\n\n // No default needed here as it's not possible for the action to be anything but the 4 listed above\n }\n });\n}",
"function elsaDialog() {\n scenarioDialog(3, \"Maybe I should give them a break…\", elsaChoice);\n}",
"function exit(){\n inquirer\n .prompt([\n {\n type: 'list',\n message: 'Would you like to add an Engineer or an Intern to the team?',\n name: 'teamChoice',\n choices: [\n 'Engineer',\n 'Intern',\n 'None'\n ],\n },\n ]).then((answers) => {\n if(answers.teamChoice === 'Engineer'){\n engineerInit(); \n } else if (answers.teamChoice === 'Intern'){\n internInit();\n } else {\n noMoreTeam();\n }\n })\n}",
"function ghostChoice() {\n choiceDialog(1, 1, elsaDialog, 16000);\n}",
"function continueManage() {\n // prompt if another action is needed \n inquirer\n .prompt(\n {\n name: \"confirm\",\n type: \"confirm\",\n message: \"Would you like to do something else?\",\n default: true\n\n })\n .then(function (answer) {\n if (answer.confirm) {\n managerOptions();\n }\n else {\n console.log(\"Thank you! Goodbye.\")\n connection.end();\n }\n });\n}",
"function doExitMgen()\r\n{\r\n // For now, just close the window\r\n $('#monsteredit').slideUp();\r\n}",
"function confirmTrip() {\n console.log(\n \"Destination: \" +\n myTrip[0] +\n \" Restaurant: \" +\n myTrip[1] +\n \" Transportation: \" +\n myTrip[2] +\n \" Entertainment \" +\n myTrip[3]\n );\n let userHappinessRequest = prompt(\n \"Are you satisfied with all your random selections?\"\n );\n\n if (userHappinessRequest === \"yes\") {\n console.log(\"Day Trip confirmed! Have fun!\");\n } else {\n newUserChoices();\n }\n}",
"function completeRevealPhase () {\n /* reveal everyone's hand */\n for (var i = 0; i < players.length; i++) {\n if (players[i] && !players[i].out) {\n determineHand(i);\n showHand(i);\n }\n }\n \n /* figure out who has the lowest hand */\n recentLoser = determineLowestHand();\n console.log(\"Player \"+recentLoser+\" is the loser.\");\n \n /* look for the unlikely case of an absolute tie */\n if (recentLoser == -1) {\n console.log(\"Fuck... there was an absolute tie\");\n /* inform the player */\n \n /* hide the dialogue bubbles */\n for (var i = 1; i < players.length; i++) {\n $gameDialogues[i-1].html(\"\");\n $gameAdvanceButtons[i-1].css({opacity : 0});\n $gameBubbles[i-1].hide();\n }\n \n /* reset the round */\n $mainButton.html(\"Deal\");\n $mainButton.attr('disabled', false);\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame, FORFEIT_DELAY);\n }\n return;\n }\n \n /* update behaviour */\n\tvar clothes = playerMustStrip (recentLoser);\n updateAllGameVisuals();\n \n /* highlight the loser */\n for (var i = 0; i < players.length; i++) {\n if (recentLoser == i) {\n $gameLabels[i].css({\"background-color\" : loserColour});\n } else {\n $gameLabels[i].css({\"background-color\" : clearColour});\n }\n }\n \n /* set up the main button */\n\tif (recentLoser != HUMAN_PLAYER && clothes > 0) {\n\t\t$mainButton.html(\"Continue\");\n\t} else {\n\t\t$mainButton.html(\"Strip\");\n\t}\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}",
"function defeat() {\n losses++;\n $('#totalLosses').text(losses);\n alert(\"DEFEAT!\");\n reset();\n }",
"function afterAct() {\n inquirer.prompt([\n {\n type: \"list\",\n name: \"afterAction\",\n message: \"What would you like to do next?\",\n choices: [\"Add another item\", \"View my cart or make changes to my cart\", \"Check out\"]\n }\n ]).then(({ afterAction }) => {\n if (afterAction === \"Add another item\") {\n askProduct();\n }\n else if (afterAction === \"View my cart or make changes to my cart\") {\n showCart();\n }\n else if (afterAction === \"Check out\") {\n checkOut();\n }\n });\n}",
"function promptAnswer() {\n r = printRandQuestion();\n let answer = prompt('Whats the correct answer?');\n\n // Check if player wants to exit\n if (answer !== 'exit') {\n\n // Check answer and display result plus total score, then start again\n questions[r].checkAnswer(parseInt(answer));\n promptAnswer();\n\n }\n }",
"function stayPlay(){ \n // Turn off the hit and stay buttons\n hitHand.removeEventListener('click', hitPlay);\n stayHand.removeEventListener('click',stayPlay);\n // Function that checks if dealer should hit or stay\n updateDlrHnd();\n // Function that checks who wins the game\n checkWinner();\n}",
"function supervisorContinue() {\n inquirer.prompt([\n {\n name: \"stayOn\",\n message: \"Do you want to continue supervising inventory?\",\n type: \"confirm\"\n }\n ])\n .then(answer => {\n if (answer.stayOn) {\n supervisorQuestions();\n } else {\n connection.end();\n process.exit();\n }\n }).catch(error => {\n if (error) {\n console.log(error.message);\n }\n });\n}",
"function leavePurpleRoom() {\n const option = user.value;\n user.value = '';\n \n if(option === 'dörren' || option === 'DÖRREN' || option === 'Dörren'){\n orangeRoom();\n\n }else if(option === 'fönstret' || option === 'FÖNSTRET' || option === 'Fönstret'){\n story.innerHTML = 'Pang! Oj! fönstret gick sönder. Någon kastade in en sten. Vill du titta vem det var? (Ja eller Nej)';\n btn.innerHTML = 'Vad gör du?'; \n btn.onclick = outsideWindow;\n\n /**\n * Function outsideWindow selected.\n * Option to look out the window or not.\n */\n function outsideWindow() {\n const option = user.value;\n user.value = '';\n\n \n if(option === 'ja' || option === 'JA' || option === 'Ja'){\n story.innerHTML = 'Du tittar ut genom fönstret och ser en inbrottstjuv. Vem ringer du (Polisen eller Glasmästaren)?';\n btn.innerHTML = 'Vem ringer du?'; //Changing the buttons text.\n btn.onclick = callPolice;\n\n /**\n * Function callPolice selected\n * Options who to call between the police or the glazier\n */\n function callPolice(){\n const option = user.value;\n user.value = '';\n\n \n if(option === 'polisen' || option === 'POLISEN' || option === 'Polisen'){\n story.innerHTML = 'Polisen kom direkt och tog fast tjuven! Bra jobbat!';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = `Tillbaks till 'Val av rum'`; \n\n }else if(option === 'glasmästaren' || option === 'GLASMÄSTAREN' || option === 'Glasmästaren'){\n story.innerHTML = 'Glasmästaren kom en timme senare och bytte ut fönstret fast tjuven hann undan.';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = `Tillbaks till 'Val av rum'`;\n }\n }\n\n }else if(option === 'nej' || option === 'NEJ' || option === 'Nej'){\n story.innerHTML = 'Jakten på de försvunna nycklarna fortsätter! Gå ut och fortsätta leta när du känner för det';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = `Gå ut ur rummet`;\n }\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Meshes and other visible objects | function createMeshes() {
mesh_lantern1 = createLantern ();
scene.add(mesh_lantern1);
mesh_lantern2 = mesh_lantern1.clone();
mesh_lantern2.translateX(15.0);
scene.add(mesh_lantern2);
mesh_lantern3 = mesh_lantern1.clone();
mesh_lantern3.translateZ(-20.0);
scene.add(mesh_lantern3);
} | [
"initializeMeshes () {\r\n this.triangleMesh = new Mesh(this.cyanYellowHypnoMaterial, this.triangleGeometry);\r\n this.quadMesh = new Mesh(this.magentaMaterial, this.quadGeometry);\r\n\r\n // texture code\r\n this.texturedQuadMesh = new Mesh(this.texturedMaterial, this.texturedQuadGeometry);\r\n }",
"buildMaterials () {\n this._meshes.forEach((mesh) => {\n let material = mesh.material;\n\n let position = new THREE.PositionNode();\n let alpha = new THREE.FloatNode(1.0);\n let color = new THREE.ColorNode(0xEEEEEE);\n\n // Compute transformations\n material._positionVaryingNodes.forEach((varNode) => {\n position = new THREE.OperatorNode(\n position,\n varNode,\n THREE.OperatorNode.ADD\n );\n });\n\n let operator;\n material._transformNodes.forEach((transNode) => {\n position = getOperatornode(\n position,\n transNode.get('node'),\n transNode.get('operator')\n );\n });\n\n // Compute alpha\n material._alphaVaryingNodes.forEach((alphaVarNode) => {\n alpha = new THREE.OperatorNode(\n alpha,\n alphaVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._alphaNodes.forEach((alphaNode) => {\n alpha = getOperatornode(\n alpha,\n alphaNode.get('node'),\n alphaNode.get('operator')\n );\n });\n\n // Compute color\n material._colorVaryingNodes.forEach((colorVarNode) => {\n color = new THREE.OperatorNode(\n color,\n colorVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._colorNodes.forEach((colorNode) => {\n color = getOperatornode(\n color,\n colorNode.get('node'),\n colorNode.get('operator')\n );\n });\n\n // To display surfaces like 2D planes or iso-surfaces whatever\n // the point of view\n mesh.material.side = THREE.DoubleSide;\n\n // Set wireframe status and shading\n if (mesh.type !== 'LineSegments' && mesh.type !== 'Points') {\n mesh.material.wireframe = this._wireframe;\n mesh.material.shading = this._wireframe\n ? THREE.SmoothShading\n : THREE.FlatShading;\n } else {\n mesh.material.wireframe = false;\n // Why ?\n // mesh.material.shading = THREE.SmoothShading;\n }\n\n // Get isoColor node\n mesh.material.transform = position;\n mesh.material.alpha = alpha;\n mesh.material.color = color;\n mesh.material.build();\n });\n }",
"function AbstractMesh(name,scene){if(scene===void 0){scene=null;}var _this=_super.call(this,name,scene,false)||this;_this._facetData=new _FacetDataStorage();/** Gets ot sets the culling strategy to use to find visible meshes */_this.cullingStrategy=AbstractMesh.CULLINGSTRATEGY_STANDARD;// Events\n/**\n * An event triggered when this mesh collides with another one\n */_this.onCollideObservable=new BABYLON.Observable();/**\n * An event triggered when the collision's position changes\n */_this.onCollisionPositionChangeObservable=new BABYLON.Observable();/**\n * An event triggered when material is changed\n */_this.onMaterialChangedObservable=new BABYLON.Observable();// Properties\n/**\n * Gets or sets the orientation for POV movement & rotation\n */_this.definedFacingForward=true;_this._visibility=1.0;/** Gets or sets the alpha index used to sort transparent meshes\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index\n */_this.alphaIndex=Number.MAX_VALUE;/**\n * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true\n */_this.isVisible=true;/**\n * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true\n */_this.isPickable=true;/** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */_this.showSubMeshesBoundingBox=false;/** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)\n * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares\n */_this.isBlocker=false;/**\n * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)\n */_this.enablePointerMoveEvents=false;/**\n * Specifies the rendering group id for this mesh (0 by default)\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups\n */_this.renderingGroupId=0;_this._receiveShadows=false;/** Defines color to use when rendering outline */_this.outlineColor=BABYLON.Color3.Red();/** Define width to use when rendering outline */_this.outlineWidth=0.02;/** Defines color to use when rendering overlay */_this.overlayColor=BABYLON.Color3.Red();/** Defines alpha to use when rendering overlay */_this.overlayAlpha=0.5;_this._hasVertexAlpha=false;_this._useVertexColors=true;_this._computeBonesUsingShaders=true;_this._numBoneInfluencers=4;_this._applyFog=true;/** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */_this.useOctreeForRenderingSelection=true;/** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */_this.useOctreeForPicking=true;/** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */_this.useOctreeForCollisions=true;_this._layerMask=0x0FFFFFFF;/**\n * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)\n */_this.alwaysSelectAsActiveMesh=false;/**\n * Gets or sets the current action manager\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions\n */_this.actionManager=null;// Collisions\n_this._checkCollisions=false;_this._collisionMask=-1;_this._collisionGroup=-1;/**\n * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */_this.ellipsoid=new BABYLON.Vector3(0.5,1,0.5);/**\n * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */_this.ellipsoidOffset=new BABYLON.Vector3(0,0,0);_this._oldPositionForCollisions=new BABYLON.Vector3(0,0,0);_this._diffPositionForCollisions=new BABYLON.Vector3(0,0,0);// Edges\n/**\n * Defines edge width used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */_this.edgesWidth=1;/**\n * Defines edge color used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */_this.edgesColor=new BABYLON.Color4(1,0,0,1);/** @hidden */_this._renderId=0;/** @hidden */_this._intersectionsInProgress=new Array();/** @hidden */_this._unIndexed=false;/** @hidden */_this._lightSources=new Array();/**\n * An event triggered when the mesh is rebuilt.\n */_this.onRebuildObservable=new BABYLON.Observable();_this._onCollisionPositionChange=function(collisionId,newPosition,collidedMesh){if(collidedMesh===void 0){collidedMesh=null;}//TODO move this to the collision coordinator!\nif(_this.getScene().workerCollisions){newPosition.multiplyInPlace(_this._collider._radius);}newPosition.subtractToRef(_this._oldPositionForCollisions,_this._diffPositionForCollisions);if(_this._diffPositionForCollisions.length()>BABYLON.Engine.CollisionsEpsilon){_this.position.addInPlace(_this._diffPositionForCollisions);}if(collidedMesh){_this.onCollideObservable.notifyObservers(collidedMesh);}_this.onCollisionPositionChangeObservable.notifyObservers(_this.position);};_this.getScene().addMesh(_this);_this._resyncLightSources();return _this;}",
"function PhysicsViewer(scene){/** @hidden */this._impostors=[];/** @hidden */this._meshes=[];/** @hidden */this._numMeshes=0;this._scene=scene||BABYLON.Engine.LastCreatedScene;var physicEngine=this._scene.getPhysicsEngine();if(physicEngine){this._physicsEnginePlugin=physicEngine.getPhysicsPlugin();}}",
"createModel () {\n var model = new THREE.Object3D()\n var loader = new THREE.TextureLoader();\n var texturaOvo = null;\n\n var texturaEsfera = null;\n \n //var texturaGrua = new THREE.TextureLoader().load(\"imgs/tgrua.jpg\");\n this.robot = new Robot({});\n this.robot.scale.set(3,3,3);\n //model.add (this.robot);\n\n //Crear Objetos voladores\n var comportamiento = null; //Buenos - Malos\n\n for (var i = 0; i < this.maxMeteoritos; ++i) {\n if (i < this.dificultad) {\n comportamiento = false;\n texturaOvo = loader.load (\"imgs/cesped1.jpg\");\n } else {\n comportamiento = true;\n texturaOvo = loader.load (\"imgs/fuego.jpg\");\n }\n this.objetosVoladores[i] = new Ovo(new THREE.MeshPhongMaterial ({map: texturaOvo}), comportamiento);\n //model.add(this.objetosVoladores[i]);\n\n\n this.esfera = new Ovo(new THREE.MeshPhongMaterial ({map: texturaOvo}), comportamiento);\n model.add(this.esfera);\n //model.add(this.createEsfera());\n\n }\n\n\n //var loader = new THREE.TextureLoader();\n var textura = loader.load (\"imgs/suelo1.jpg\");\n this.ground = new Ground (300, 300, new THREE.MeshPhongMaterial ({map: textura}), 4);\n model.add (this.ground);\n\n return model;\n }",
"drawObject(mesh, drawShaders){\n\t\tvar ctx = this.ctx;\n\t\tctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT);\n\t\tvar perspectiveMatrix = GlUtils.makePerspective(89.95, this.realWidth/this.realHeight, 0.1, 100.0);\n\t\tGlUtils.loadIdentity();\n\t\tGlUtils.mvPushMatrix();\n\t\tmesh.translation && GlUtils.mvTranslate(mesh.translation);\n\t\tmesh.scale && GlUtils.mvScale([mesh.scale[0],mesh.scale[1],mesh.scale[2]]);\n\t\tmesh.rotation && GlUtils.mvRotateMultiple(mesh.rotation[0], [1,0,0], mesh.rotation[1], [0,1,0]);\n\t\tctx.useProgram(this.shaderProgram);\n\t\tctx.bindBuffer(ctx.ARRAY_BUFFER, mesh.vertexBuffer);\n\t\tctx.vertexAttribPointer(this.shaderProgram.vertexPositionAttribute, mesh.vertexBuffer.itemSize, ctx.FLOAT, false, 0, 0);\n\t\tctx.bindBuffer(ctx.ARRAY_BUFFER, mesh.normalBuffer);\n\t\tctx.vertexAttribPointer(this.shaderProgram.vertexNormalAttribute, mesh.normalBuffer.itemSize, ctx.FLOAT, false, 0, 0);\n\t\tctx.bindBuffer(ctx.ARRAY_BUFFER, mesh.textureBuffer);\n\t\tctx.vertexAttribPointer(this.shaderProgram.textureCoordAttribute, mesh.textureBuffer.itemSize, ctx.FLOAT, false, 0, 0);\n\t\tctx.activeTexture(ctx.TEXTURE0);\n\t\tctx.bindTexture(ctx.TEXTURE_2D, mesh.texture);\n\t\tctx.uniform1i(this.shaderProgram.samplerUniform, 0);\n\t\tctx.uniform2fv(this.shaderProgram.screenRatio, [1.0, this.frameInfo.screenRatio]);\n\t\tdrawShaders();\n\t\tctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, mesh.indexBuffer);\n\t\tGlUtils.setMatrixUniforms(ctx, this.shaderProgram, perspectiveMatrix);\n\t\tctx.drawElements(ctx.TRIANGLES, mesh.indexBuffer.numItems, ctx.UNSIGNED_SHORT, 0);\n\t\tGlUtils.mvPopMatrix();\n\t}",
"updateMeshDrawings() {\n let canvas = this;\n let scene = this.scene;\n if ('children' in this.scene) {\n scene.children.forEach(function(child) {\n canvas.updateMeshDrawingsRecurse(child);\n });\n }\n }",
"function GizmoManager(scene){var _this=this;this.scene=scene;this._gizmosEnabled={positionGizmo:false,rotationGizmo:false,scaleGizmo:false,boundingBoxGizmo:false};this._pointerObserver=null;this._attachedMesh=null;this._boundingBoxColor=BABYLON.Color3.FromHexString(\"#0984e3\");/**\n * When bounding box gizmo is enabled, this can be used to track drag/end events\n */this.boundingBoxDragBehavior=new BABYLON.SixDofDragBehavior();/**\n * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)\n */this.attachableMeshes=null;/**\n * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)\n */this.usePointerToAttachGizmos=true;this._defaultKeepDepthUtilityLayer=new BABYLON.UtilityLayerRenderer(scene);this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=false;this._defaultUtilityLayer=new BABYLON.UtilityLayerRenderer(scene);this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};// Instatiate/dispose gizmos based on pointer actions\nthis._pointerObserver=scene.onPointerObservable.add(function(pointerInfo,state){if(!_this.usePointerToAttachGizmos){return;}if(pointerInfo.type==BABYLON.PointerEventTypes.POINTERDOWN){if(pointerInfo.pickInfo&&pointerInfo.pickInfo.pickedMesh){var node=pointerInfo.pickInfo.pickedMesh;if(_this.attachableMeshes==null){// Attach to the most parent node\nwhile(node&&node.parent!=null){node=node.parent;}}else{// Attach to the parent node that is an attachableMesh\nvar found=false;_this.attachableMeshes.forEach(function(mesh){if(node&&(node==mesh||node.isDescendantOf(mesh))){node=mesh;found=true;}});if(!found){node=null;}}if(node instanceof BABYLON.AbstractMesh){if(_this._attachedMesh!=node){_this.attachToMesh(node);}}else{_this.attachToMesh(null);}}else{_this.attachToMesh(null);}}});}",
"set Mesh(value) {}",
"get MeshRenderer() {}",
"createScene() {\n\n this.heightMap = new NoiseMap();\n this.heightMaps = this.heightMap.maps;\n\n this.moistureMap = new NoiseMap();\n this.moistureMaps = this.moistureMap.maps;\n\n this.textureMap = new TextureMap();\n this.textureMaps = this.textureMap.maps;\n\n this.normalMap = new NormalMap();\n this.normalMaps = this.normalMap.maps;\n\n this.roughnessMap = new RoughnessMap();\n this.roughnessMaps = this.roughnessMap.maps;\n\n for (let i=0; i<6; i++) { //Create 6 materials, each with white color\n let material = new THREE.MeshStandardMaterial({\n color: new THREE.Color(0xFFFFFF)\n });\n this.materials[i] = material;\n }\n\n let geo = new THREE.BoxGeometry(1, 1, 1, 64, 64, 64); //Creating a box\n let radius = this.size;\n for (var i in geo.vertices) {\n \t\tvar vertex = geo.vertices[i];\n \t\tvertex.normalize().multiplyScalar(radius);\n \t}\n this.computeGeometry(geo); //Squeezing a box into a sphere\n\n this.ground = new THREE.Mesh(geo, this.materials); //Create ground mesh with squeezed box sphere and 6 materials\n this.view.add(this.ground);\n }",
"function transformFilled(){\n if(vueObjetsActuelle === \"vertex\"){\n deleteVertex();\n }\n vueObjetsActuelle = \"filled\";\n // affichage de tous les objets en filled\n for (let i=0; i<scene.children.length; i++){\n let object = scene.children[i];\n //vérification que c'est un objet\n if(object.name.split(\"_\")[0] === \"object\"){\n object.visible = true;\n object.children[0].material.wireframe = false\n }\n }\n}",
"makeThenRenderAGObject(obj_type, obj_left, obj_top) {\n let obj_buffer;\n let obj_buffer_ID;\n switch (obj_type) {\n case 'enemy':\n obj_buffer = new AGObject(\"AGgegner\", new Vector3((obj_left / this._scale), 1, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).tag = \"ENEMY\";\n getReferenceById(obj_buffer_ID).setSpeedSkalar(0);\n break;\n case 'wall':\n obj_buffer = new AGObject(\"Structure\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).tag = \"WALL\";\n break;\n case 'portal':\n obj_buffer = new AGPortal(\"Portal\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n break;\n case 'exit':\n obj_buffer = new AGRoomExit(\"Exit\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n break;\n case 'generic':\n obj_buffer = new AGObject(\"Generic\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).collidable = false;\n getReferenceById(obj_buffer_ID).tag = \"GENERIC\";\n }\n getReferenceById(this._AGroomID).add(obj_buffer_ID);\n this.renderAGObject(obj_buffer_ID);\n\n this.refreshObjectSelect();\n this.listItems();\n this.listConditions();\n\n return obj_buffer_ID;\n }",
"newScene() {\n if (confirm(\"Clear all objects of current room?\")) {\n let room_buffer = this._room_canvas;\n let scale_buffer = this._scale;\n let canvas_objects = room_buffer.getObjects();\n\n canvas_objects.forEach(function (item, i) {\n\n if (item.type == 'player') {\n\n item.LineArray = [];\n item.PathArray = [];\n getReferenceById(item.AGObjectID).clearRoute();\n getReferenceById(item.AGObjectID).movable = false;\n\n }\n if (item.isObject && item.type != 'player') {\n\n\n getReferenceById(item.AGObjectID).kill();\n }\n if (item.type != 'grid_line' && item.type != 'player') {\n room_buffer.remove(item);\n }\n });\n\n\n this.deleteItemsEventsEtc();\n room_buffer.renderAll();\n }\n }",
"function AxesViewer(scene,scaleLines){if(scaleLines===void 0){scaleLines=1;}this._xline=[BABYLON.Vector3.Zero(),BABYLON.Vector3.Zero()];this._yline=[BABYLON.Vector3.Zero(),BABYLON.Vector3.Zero()];this._zline=[BABYLON.Vector3.Zero(),BABYLON.Vector3.Zero()];/**\n * Gets or sets a number used to scale line length\n */this.scaleLines=1;this.scaleLines=scaleLines;this._xmesh=BABYLON.Mesh.CreateLines(\"xline\",this._xline,scene,true);this._ymesh=BABYLON.Mesh.CreateLines(\"yline\",this._yline,scene,true);this._zmesh=BABYLON.Mesh.CreateLines(\"zline\",this._zline,scene,true);this._xmesh.renderingGroupId=2;this._ymesh.renderingGroupId=2;this._zmesh.renderingGroupId=2;this._xmesh.material.checkReadyOnlyOnce=true;this._xmesh.color=new BABYLON.Color3(1,0,0);this._ymesh.material.checkReadyOnlyOnce=true;this._ymesh.color=new BABYLON.Color3(0,1,0);this._zmesh.material.checkReadyOnlyOnce=true;this._zmesh.color=new BABYLON.Color3(0,0,1);this.scene=scene;}",
"function init_threeScene(spec) {\n // grab a reference to our canvas\n CANVAS = document.getElementById('jeeFaceFilterCanvas')\n\n // INIT THE THREE.JS context\n THREERENDERER = new THREE.WebGLRenderer({\n context: spec.GL,\n canvas: spec.canvasElement\n });\n\n // COMPOSITE OBJECT WHICH WILL FOLLOW THE HEAD\n // in fact we create 2 objects to be able to shift the pivot point\n THREEFACEOBJ3D = new THREE.Object3D();\n THREEFACEOBJ3D.frustumCulled = false;\n THREEFACEOBJ3DPIVOTED = new THREE.Object3D();\n THREEFACEOBJ3DPIVOTED.frustumCulled = false;\n THREEFACEOBJ3DPIVOTED.position.set(0, -SETTINGS.pivotOffsetYZ[0], -SETTINGS.pivotOffsetYZ[1]);\n THREEFACEOBJ3DPIVOTED.scale.set(SETTINGS.scale, SETTINGS.scale, SETTINGS.scale);\n THREEFACEOBJ3D.add(THREEFACEOBJ3DPIVOTED);\n\n let frameMesh;\n let lensesMesh;\n let branchesMesh;\n let decoMesh;\n\n const loadingManager = new THREE.LoadingManager();\n\n // CREATE OUR FRAME\n const loaderFrame = new THREE.BufferGeometryLoader(loadingManager);\n\n loaderFrame.load(\n './models/glasses/frame.json',\n (geometry) => {\n const mat = new THREE.MeshPhongMaterial({\n color: 0x000000,\n shininess: 2,\n specular: 0xffffff,\n transparent: true\n });\n\n frameMesh = new THREE.Mesh(geometry, mat);\n frameMesh.scale.multiplyScalar(0.0067);\n frameMesh.frustumCulled = false;\n frameMesh.renderOrder = 10000;\n }\n )\n\n // CREATE OUR LENSES\n const loaderLenses = new THREE.BufferGeometryLoader(loadingManager);\n\n loaderLenses.load(\n './models/glasses/lenses.json',\n (geometry) => {\n const mat = new THREE.MeshBasicMaterial({\n map: new THREE.TextureLoader().load('./models/glasses/texture_mp.jpg')\n });\n\n lensesMesh = new THREE.Mesh(geometry, mat);\n lensesMesh.scale.multiplyScalar(0.0067);\n lensesMesh.frustumCulled = false;\n lensesMesh.renderOrder = 10000;\n }\n )\n // CREATE OUR BRANCHES\n const loaderBranches = new THREE.BufferGeometryLoader(loadingManager);\n\n loaderBranches.load(\n './models/glasses/branches.json',\n (geometry) => {\n const mat = new THREE.MeshBasicMaterial({\n alphaMap: new THREE.TextureLoader().load('./models/glasses/alpha_branches.jpg'),\n map: new THREE.TextureLoader().load('./models/glasses/textureBlack.jpg'),\n transparent: true\n });\n\n branchesMesh = new THREE.Mesh(geometry, mat);\n branchesMesh.scale.multiplyScalar(0.0067);\n branchesMesh.frustumCulled = false;\n branchesMesh.renderOrder = 10000;\n }\n )\n\n // CREATE OUR DECO\n const loaderDeco = new THREE.BufferGeometryLoader(loadingManager);\n\n loaderDeco.load(\n './models/glasses/deco.json',\n (geometry) => {\n const mat = new THREE.MeshBasicMaterial({\n color: 0xffffff\n });\n\n decoMesh = new THREE.Mesh(geometry, mat);\n decoMesh.scale.multiplyScalar(0.0067);\n \n decoMesh.frustumCulled = false;\n decoMesh.renderOrder = 10000;\n }\n )\n\n loadingManager.onLoad = () => {\n GLASSESOBJ3D.add(branchesMesh);\n GLASSESOBJ3D.add(frameMesh);\n GLASSESOBJ3D.add(lensesMesh);\n \n GLASSESOBJ3D.add(decoMesh);\n GLASSESOBJ3D.position.setY(0.05);\n\n addDragEventListener(GLASSESOBJ3D);\n\n THREEFACEOBJ3DPIVOTED.add(GLASSESOBJ3D);\n }\n\n // ADD OUR BEES\n const beeLoader = new THREE.JSONLoader();\n\n beeLoader.load(\n './models/bee/bee.json',\n (geometry) => {\n\n const materialBee = new THREE.MeshLambertMaterial({\n map: new THREE.TextureLoader().load('./models/bee/texture_bee.jpg'),\n transparent: true,\n morphTargets: true\n });\n\n BEEMESH = new THREE.Mesh(geometry, materialBee);\n\n // let butterFlyInstance\n // let action;\n let clips;\n let clip;\n let xRand;\n let yRand;\n let zRand;\n\n BEEOBJ3D = new THREE.Object3D();\n\n for (let i = 1; i < NUMBERBEES; i++) {\n const sign = i % 2 === 0 ? 1 : -1;\n const beeInstance = BEEMESH.clone();\n\n\n\n xRand = Math.random() * 1.5 - 0.75;\n yRand = Math.random() * 2 - 1 + 1;\n zRand = Math.random() * 0.5 - 0.25;\n\n beeInstance.position.set(xRand, yRand, zRand);\n beeInstance.scale.multiplyScalar(0.1);\n animateFlyBees(beeInstance, sign * ((i + 1) * 0.005 + 0.01), sign);\n let BEEINSTANCEOBJ3D = new THREE.Object3D();\n BEEINSTANCEOBJ3D.add(beeInstance);\n\n // CREATE BATTEMENT D'AILE ANIMATION\n if (!ISANIMATED) {\n // This is where adding our animation begins\n const mixer = new THREE.AnimationMixer(beeInstance);\n\n clips = beeInstance.geometry.animations;\n\n clip = clips[0];\n\n\n const action = mixer.clipAction(clip);\n\n\n ACTIONS.push(action);\n MIXERS.push(mixer);\n }\n\n BEEOBJ3D.add(BEEINSTANCEOBJ3D);\n }\n\n // We play the animation for each butterfly and shift their cycles\n // by adding a small timeout\n ACTIONS.forEach((a, index) => {\n setTimeout(() => {\n a.play();\n }, index*33);\n });\n\n \n THREEFACEOBJ3DPIVOTED.add(BEEOBJ3D);\n }\n )\n\n // CREATE THE SCENE\n THREESCENE = new THREE.Scene();\n THREESCENE.add(THREEFACEOBJ3D);\n\n // init video texture with red\n THREEVIDEOTEXTURE = new THREE.DataTexture(new Uint8Array([255,0,0]), 1, 1, THREE.RGBFormat);\n THREEVIDEOTEXTURE.needsUpdate = true;\n\n // CREATE THE VIDEO BACKGROUND\n function create_mat2d(threeTexture, isTransparent){ //MT216 : we put the creation of the video material in a func because we will also use it for the frame\n return new THREE.RawShaderMaterial({\n depthWrite: false,\n depthTest: false,\n transparent: isTransparent,\n vertexShader: \"attribute vec2 position;\\n\\\n varying vec2 vUV;\\n\\\n void main(void){\\n\\\n gl_Position=vec4(position, 0., 1.);\\n\\\n vUV=0.5+0.5*position;\\n\\\n }\",\n fragmentShader: \"precision lowp float;\\n\\\n uniform sampler2D samplerVideo;\\n\\\n varying vec2 vUV;\\n\\\n void main(void){\\n\\\n gl_FragColor=texture2D(samplerVideo, vUV);\\n\\\n }\",\n uniforms:{\n samplerVideo: { value: threeTexture }\n }\n });\n }\n const videoMaterial =create_mat2d(THREEVIDEOTEXTURE, false);\n const videoGeometry = new THREE.BufferGeometry()\n const videoScreenCorners = new Float32Array([-1,-1, 1,-1, 1,1, -1,1]);\n videoGeometry.addAttribute('position', new THREE.BufferAttribute( videoScreenCorners, 2));\n videoGeometry.setIndex(new THREE.BufferAttribute(new Uint16Array([0,1,2, 0,2,3]), 1));\n const videoMesh = new THREE.Mesh(videoGeometry, videoMaterial);\n videoMesh.onAfterRender = function () {\n // replace THREEVIDEOTEXTURE.__webglTexture by the real video texture\n THREERENDERER.properties.update(THREEVIDEOTEXTURE, '__webglTexture', spec.videoTexture);\n THREEVIDEOTEXTURE.magFilter = THREE.LinearFilter;\n THREEVIDEOTEXTURE.minFilter = THREE.LinearFilter;\n delete(videoMesh.onAfterRender);\n };\n videoMesh.renderOrder = -1000; // render first\n videoMesh.frustumCulled = false;\n THREESCENE.add(videoMesh);\n\n //MT216 : create the frame. We reuse the geometry of the video\n const calqueMesh = new THREE.Mesh(videoGeometry, create_mat2d(new THREE.TextureLoader().load('./images/frame.png'), true))\n calqueMesh.renderOrder = 999; // render last\n calqueMesh.frustumCulled = false;\n THREESCENE.add(calqueMesh);\n\n // CREATE THE CAMERA\n const aspecRatio = spec.canvasElement.width / spec.canvasElement.height;\n THREECAMERA = new THREE.PerspectiveCamera(SETTINGS.cameraFOV, aspecRatio, 0.1, 100);\n\n // CREATE A LIGHT\n const ambient = new THREE.AmbientLight(0xffffff, 1);\n THREESCENE.add(ambient)\n\n var dirLight = new THREE.DirectionalLight(0xffffff);\n dirLight.position.set(100, 1000, 100);\n\n THREESCENE.add(dirLight)\n} // end init_threeScene()",
"function loadModels() {\r\n\r\n const loader = new THREE.GLTFLoader();\r\n \r\n \r\n const onLoad = ( gltf, position ) => {\r\n \r\n model_tim = gltf.scene;\r\n model_tim.position.copy( position );\r\n //console.log(position)\r\n \r\n //model_tim_skeleton= new THREE.Skeleton(model_tim_bones);\r\n model_tim_skeleton= new THREE.SkeletonHelper(model_tim);\r\n model_tim_head_bone=model_tim_skeleton.bones[5];\r\n console.log(model_tim_head_bone);\r\n //console.log(model_tim_bones);\r\n animation_walk = gltf.animations[0];\r\n \r\n const mixer = new THREE.AnimationMixer( model_tim );\r\n mixers.push( mixer );\r\n \r\n action_walk = mixer.clipAction( animation_walk );\r\n // Uncomment you need to change the scale or position of the model \r\n //model_tim.scale.set(1,1,1);\r\n //model_tim.rotateY(Math.PI) ;\r\n\r\n scene.add( model_tim );\r\n \r\n //model_tim.geometry.computeBoundingBox();\r\n //var bb = model_tim.boundingBox;\r\n var bb = new THREE.Box3().setFromObject(model_tim);\r\n var object3DWidth = bb.max.x - bb.min.x;\r\n var object3DHeight = bb.max.y - bb.min.y;\r\n var object3DDepth = bb.max.z - bb.min.z;\r\n console.log(object3DWidth);\r\n console.log(object3DHeight);\r\n console.log(object3DDepth);\r\n // Uncomment if you want to change the initial camera position\r\n //camera.position.x = 0;\r\n //camera.position.y = 15;\r\n //camera.position.z = 200;\r\n \r\n \r\n };\r\n \r\n \r\n \r\n // the loader will report the loading progress to this function\r\n const onProgress = () => {console.log('Someone is here');};\r\n \r\n // the loader will send any error messages to this function, and we'll log\r\n // them to to console\r\n const onError = ( errorMessage ) => { console.log( errorMessage ); };\r\n \r\n // load the first model. Each model is loaded asynchronously,\r\n // so don't make any assumption about which one will finish loading first\r\n const tim_Position = new THREE.Vector3( 0,0,0 );\r\n loader.load('Timmy_sc_1_stay_in_place.glb', gltf => onLoad( gltf, tim_Position ), onProgress, onError );\r\n \r\n }",
"static save_both (comp) {\n if (comp.object3D) {\n const kid = comp.object3D\n kid.isVisible = true\n const kids = kid.getChildren()\n for (let i = 0; i < kids.length; i++) {\n kids[i].setEnabled(true)\n }\n kids[kids.length - 1].isVisible = false\n\n var myser = BABYLON.SceneSerializer.SerializeMesh(comp.object3D, false, true)\n var jsonData = JSON.stringify(myser)\n\n // Component.doDownload('part.babylon', new Blob([jsonData], { type: 'octet/stream' }))\n return [new Blob([jsonData], { type: 'octet/stream' }), new Blob([jsonData], { type: 'octet/stream' })]\n }\n }",
"function SceneManager()\n {\n EventEmitter.call(this);\n this.meshes = {};\n } // end SceneManager"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a subpatch for thunks | function thunks(a, b, patch, index) {
var nodes = handleThunk(a, b)
var thunkPatch = diff(nodes.a, nodes.b)
if (hasPatches(thunkPatch)) {
patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
}
} | [
"function performBackpatching()\n\t{\n\t\t// Reference Variables (static)\n\t\tperformReferenceBackpatching();\n\t\t// Jumps\n\t\tperformJumpBackpatching();\n\t}",
"function Window_ModPatchCreate() {\r\n this.initialize.apply(this, arguments);\r\n}",
"function utilPatch(orig, diff) /* patched object */ {\n\t\tconst\n\t\t\tkeys = Object.keys(diff || {}),\n\t\t\tpatched = clone(orig);\n\n\t\tfor (let i = 0, klen = keys.length; i < klen; ++i) {\n\t\t\tconst\n\t\t\t\tkey = keys[i],\n\t\t\t\tdiffP = diff[key];\n\n\t\t\tif (diffP === DiffOp.Delete) {\n\t\t\t\tdelete patched[key];\n\t\t\t}\n\t\t\telse if (Array.isArray(diffP)) {\n\t\t\t\tswitch (diffP[0]) {\n\t\t\t\tcase DiffOp.SpliceArray:\n\t\t\t\t\tpatched.splice(diffP[1], 1 + (diffP[2] - diffP[1]));\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase DiffOp.Copy:\n\t\t\t\t\tpatched[key] = clone(diffP[1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase DiffOp.CopyDate:\n\t\t\t\t\tpatched[key] = new Date(diffP[1]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpatched[key] = Util.patch(patched[key], diffP);\n\t\t\t}\n\t\t}\n\n\t\treturn patched;\n\t}",
"write(patch) {\n if (this[completed]) {\n throw new Error('This response has already completed.');\n }\n\n if (Array.isArray(patch)) {\n this[send]({patch});\n } else {\n this[send]({patch: [patch]});\n }\n }",
"function fork(value, __trace) {\n return new _primitives.IFork(value, O.none, O.none, __trace);\n}",
"function sendPatch(patchContent, buttonID) {\n\t\t\n\t{\n\t\tpatchContent = typeof patchContent !== 'undefined' ? patchContent : Date();\n\t}\n\t\n if (gistContents !== 'undefined') {\n \n \tvar tmpContents = gistContents['files']['savedURL.md']['content'];\n \tvar newContents = \"\\n\" + tmpContents + patchContent + \"\\n\\n\";\n \tvar newData = {\n \t\t\t\t\t\"files\": {\n \t\t\t\t\t\t\"savedURL.md\" : {\n \t\t\t\t\t\t\t\"content\": newContents\n \t\t\t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t}\n \t\t\t\t\t};\n \t\n \tgistData = createCORSRequest('PATCH', gistQuery, buttonID);\n colorRed(buttonID);\n \tgistData.send(JSON.stringify(newData));\n }\n}",
"function _generate(mirror, obj, patches, path) {\r\n if (obj === mirror) {\r\n return;\r\n }\r\n if (typeof obj.toJSON === \"function\") {\r\n obj = obj.toJSON();\r\n }\r\n var newKeys = helpers_1._objectKeys(obj);\r\n var oldKeys = helpers_1._objectKeys(mirror);\r\n var changed = false;\r\n var deleted = false;\r\n //if ever \"move\" operation is implemented here, make sure this test runs OK: \"should not generate the same patch twice (move)\"\r\n for (var t = oldKeys.length - 1; t >= 0; t--) {\r\n var key = oldKeys[t];\r\n var oldVal = mirror[key];\r\n if (helpers_1.hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {\r\n var newVal = obj[key];\r\n if (typeof oldVal == \"object\" && oldVal != null && typeof newVal == \"object\" && newVal != null) {\r\n _generate(oldVal, newVal, patches, path + \"/\" + helpers_1.escapePathComponent(key));\r\n }\r\n else {\r\n if (oldVal !== newVal) {\r\n changed = true;\r\n patches.push({ op: \"replace\", path: path + \"/\" + helpers_1.escapePathComponent(key), value: helpers_1._deepClone(newVal) });\r\n }\r\n }\r\n }\r\n else if (Array.isArray(mirror) === Array.isArray(obj)) {\r\n patches.push({ op: \"remove\", path: path + \"/\" + helpers_1.escapePathComponent(key) });\r\n deleted = true; // property has been deleted\r\n }\r\n else {\r\n patches.push({ op: \"replace\", path: path, value: obj });\r\n changed = true;\r\n }\r\n }\r\n if (!deleted && newKeys.length == oldKeys.length) {\r\n return;\r\n }\r\n for (var t = 0; t < newKeys.length; t++) {\r\n var key = newKeys[t];\r\n if (!helpers_1.hasOwnProperty(mirror, key) && obj[key] !== undefined) {\r\n patches.push({ op: \"add\", path: path + \"/\" + helpers_1.escapePathComponent(key), value: helpers_1._deepClone(obj[key]) });\r\n }\r\n }\r\n}",
"_beforePatch() {\n return new Promise((resolve) => {\n const patch = this.config.patch;\n const control = this.config.control;\n control.disable();\n patch.running = true;\n this._clearMessage();\n return resolve(true);\n });\n }",
"_getPatchBody(value) {\n let body = {};\n const patch = this.config.patch;\n value = typeof value !== 'undefined' ? value : this.config.control.value;\n if (IsObject(value)) {\n const val = value;\n body = Object.assign(Object.assign({}, body), val);\n }\n else if (IsArray(value)) {\n body[this.config.patch.field] = value;\n }\n else {\n body[this.config.patch.field] = value;\n if (this.config.empty && !body[this.config.patch.field]) {\n body[this.config.patch.field] = PopTransform(String(value), this.config.empty);\n }\n }\n if (this.config.patch.json)\n body[this.config.patch.field] = JSON.stringify(body[this.config.patch.field]);\n if (patch && patch.metadata) {\n for (const i in patch.metadata) {\n if (!patch.metadata.hasOwnProperty(i))\n continue;\n body[i] = patch.metadata[i];\n }\n }\n return body;\n }",
"patch(route, ...middleware) {\n return this._addRoute(route, middleware, \"PATCH\");\n }",
"function applyPatch(patchObject, graph, url) {\n debug('PATCH -- Applying patch')\n patchObject.deleted = []\n patchObject.inserted = []\n return new Promise((resolve, reject) =>\n graph.applyPatch(patchObject, graph.sym(url), (err) => {\n if (err) {\n const message = err.message || err // returns string at the moment\n debug(`PATCH -- FAILED. Returning 409. Message: '${message}'`)\n return reject(error(409, `The patch could not be applied. ${message}`))\n }\n resolve(graph)\n })\n )\n}",
"function YAbstractPatchPlacer(startx,starty,count,slopemin,slopemax,altmin,altmax,compact,slopeRatio,altRatio,noise,mask,lock) {\n\t this.sx = startx;\n\t this.sy = starty;\n\t this.barx = startx;\n\t this.bary = starty;\n\t this.card = 1;\n\t this.count = count;\n\t this.slopemin = slopemin;\n\t this.slopemax = slopemax;\n\t this.altmin = altmin;\n\t this.altmax = altmax;\n\t this.compact = compact;\n\t this.slopeRatio = slopeRatio;\n\t this.altRatio = altRatio;\n\t this.noise = noise;\n\t this.mask = mask | yALLMASK;\n\t this.lock = lock;\n\t this.base = g_TOMap.gCells[startx][starty].alt;\n\t this.border = [];\n\t this.zone = undefined;\n}",
"function patchRow(tr, device, patch) {\n for (var i = 0, l = patch.length; i < l; ++i) {\n var op = patch[i]\n switch (op[0]) {\n case 'insert':\n var col = scope.columnDefinitions[op[2]]\n tr.insertBefore(col.update(col.build(), device), tr.cells[op[1]])\n break\n case 'remove':\n tr.deleteCell(op[1])\n break\n case 'swap':\n tr.insertBefore(tr.cells[op[1]], tr.cells[op[2]])\n tr.insertBefore(tr.cells[op[2]], tr.cells[op[1]])\n break\n }\n }\n\n return tr\n }",
"function modifyState (patch) {\n autoUpdate(patch); //apply changes to UIs\n appState = _.merge(appState, patch); //destructively update appState\n Object.freeze(appState); //freeze!\n }",
"function startPatching () {\n let patching = true\n\n startLauncher('-image')\n .then(() => {\n patching = false\n document.querySelector('.patch-status').innerHTML = 'Game is up to date!'\n document.querySelector('.login-button').disabled = false\n })\n .catch(() => {\n patching = false\n document.querySelector('.patch-status').innerHTML = '<span style=\"color: red;\">Failed patching with the official launcher (using ' + config.get('executablePath') + ').<br>Please start the official launcher manually!</span>'\n document.querySelector('.login-button').disabled = true\n })\n\n // Show a fake status change if there seems to be stuff to download :>\n setTimeout(() => {\n if (patching) {\n document.querySelector('.patch-status').innerHTML = 'Downloading patch...'\n }\n }, 5000)\n}",
"function performReferenceBackpatching()\n\t{\n\t\t// Before we backpatch, delete the string entries, because their addresses and offsets have already been determined\n\t\tfor(key in referenceTable)\n\t\t{\n\t\t\t// Delete string entries\n\t\t\tif(referenceTable[key].type === \"string\")\n\t\t\t\tdelete referenceTable[key];\n\t\t}\n\n\t\t// Iterate the reference table\n\t\tfor(key in referenceTable)\n\t\t{\n\t\t\t// Calculate the permanent memory location of this static variable (bytecodeList.length + offset) and put it in hex form\n\t\t\tvar location = (referenceTable[key].offset + _ByteCodeList.length - 1).toString(16).toUpperCase();\n\n\t\t\t// Make sure the location is two hex digits\n\t\t\tif(location.length === 1)\n\t\t\t\tlocation = \"0\" + location;\n\n\t\t\t// Iterate the bytecode list to find all occurances of this key\n\t\t\tfor(var i = 0; i < _ByteCodeList.length; i++)\n\t\t\t{\n\t\t\t\t// When found. replace with the permanent memory location\n\t\t\t\tif(_ByteCodeList[i] === key)\n\t\t\t\t\t_ByteCodeList.splice(i, 1, location)\n\t\t\t}\n\n\t\t\t// Delete the temp entry in the reference table\n\t\t\tdelete referenceTable[key];\n\t\t}\n\t}",
"function performJumpBackpatching()\n\t{\n\t\t// Iterate the jump table\n\t\tfor(key in jumpTable)\n\t\t{\n\t\t\t// Iterate the bytecode list\n\t\t\tfor(var i = 0; i < _ByteCodeList.length; i++)\n\t\t\t{\n\t\t\t\t// Find the temporary jump key, this is the origin of the jump\n\t\t\t\tif(_ByteCodeList[i] === key)\n\t\t\t\t\tvar origin = i;\n\n\t\t\t\t// Find the No Op after the if/while statement block, this is the jump destination\n\t\t\t\tif(_ByteCodeList[i] === \"EA\")\n\t\t\t\t\tvar destination = i;\n\t\t\t}\n\n\t\t\t// Calculate the jump distance in hex\n\t\t\tvar jumpDistance = (destination - origin).toString(16).toUpperCase();\n\t\t\t// Make sure the jump distance is two hex digits\n\t\t\tif(jumpDistance.length === 1)\n\t\t\t\tjumpDistance = \"0\" + jumpDistance;\n\t\t\t// Replace the temp opcode with the actual jump distance\n\t\t\t_ByteCodeList.splice(origin, 1, jumpDistance)\n\t\t\t// Delete the temp entry in the jump table\n\t\t\tdelete jumpTable[key];\n\t\t}\n\t}",
"function applyCocoaPodsModifications(contents) {\n // Ensure installer blocks exist\n let src = addInstallerBlock(contents, 'pre');\n // src = addInstallerBlock(src, \"post\");\n src = addMapboxInstallerBlock(src, 'pre');\n // src = addMapboxInstallerBlock(src, \"post\");\n return src;\n}",
"function handler(req, res, next) {\n readEntity(req, res, () => patchHandler(req, res, next))\n}",
"function updateTeapot() {\r\n points = [];\r\n var P;\r\n var Px; \r\n var Py;\r\n var Pz;\r\n var M = mat4(1, 0, 0, 0,\r\n -3, 3, 0, 0,\r\n 3, -6, 3, 0,\r\n -1, 3, -3, 1);\r\n for (a = 0; a < teapotIndices.length; a++) { //iterate through all patches\r\n P = teapotIndices[a]; //indices of current patch\r\n \r\n P = flatten(m4Transpose(P));\r\n \r\n Px = mat4(teapotPoints[P[0]][0], teapotPoints[P[1]][0], teapotPoints[P[2]][0], teapotPoints[P[3]][0], //Px = x values for this patch\r\n teapotPoints[P[4]][0], teapotPoints[P[5]][0], teapotPoints[P[6]][0], teapotPoints[P[7]][0],\r\n teapotPoints[P[8]][0], teapotPoints[P[9]][0], teapotPoints[P[10]][0], teapotPoints[P[11]][0],\r\n teapotPoints[P[12]][0], teapotPoints[P[13]][0], teapotPoints[P[14]][0], teapotPoints[P[15]][0]);\r\n\r\n Py = mat4(teapotPoints[P[0]][1], teapotPoints[P[1]][1], teapotPoints[P[2]][1], teapotPoints[P[3]][1], //Py = y values for this patch\r\n teapotPoints[P[4]][1], teapotPoints[P[5]][1], teapotPoints[P[6]][1], teapotPoints[P[7]][1],\r\n teapotPoints[P[8]][1], teapotPoints[P[9]][1], teapotPoints[P[10]][1], teapotPoints[P[11]][1],\r\n teapotPoints[P[12]][1], teapotPoints[P[13]][1], teapotPoints[P[14]][1], teapotPoints[P[15]][1]);\r\n\r\n Pz = mat4(teapotPoints[P[0]][2], teapotPoints[P[1]][2], teapotPoints[P[2]][2], teapotPoints[P[3]][2], //Pz = z values for this patch\r\n teapotPoints[P[4]][2], teapotPoints[P[5]][2], teapotPoints[P[6]][2], teapotPoints[P[7]][2],\r\n teapotPoints[P[8]][2], teapotPoints[P[9]][2], teapotPoints[P[10]][2], teapotPoints[P[11]][2],\r\n teapotPoints[P[12]][2], teapotPoints[P[13]][2], teapotPoints[P[14]][2], teapotPoints[P[15]][2]);\r\n \r\n //generate and push points in a square to give wireframe a gridded appearance\r\n for (u = 0; u <= 1; u += .1) {\r\n var U = vec4(1, u, u * u, u * u * u); //U vector [1, u, u^2, u^3]\r\n for (v = 0; v <= 1; v += .1) {\r\n var V = vec4(1, v, v * v, v * v * v); //V vector\r\n var x = mult(vec4Transpose(U), mult(M, mult(Px, mult(m4Transpose(M), V)))); // x = uT * Mb * Px * Mb * v (parameterized function for x value)\r\n var y = mult(vec4Transpose(U), mult(M, mult(Py, mult(m4Transpose(M), V)))); // ^ same function for y and z, substituting Py and Pz\r\n var z = mult(vec4Transpose(U), mult(M, mult(Pz, mult(m4Transpose(M), V))));\r\n \r\n x = .25 * (x[0] + x[1] + x[2] + x[3]); //need to sum the elements to get the dot product because mult multiplies the elements of the vectors, but does not sum them\r\n y = .25 * (y[0] + y[1] + y[2] + y[3]);\r\n z = .25 * (z[0] + z[1] + z[2] + z[3]);\r\n\r\n points.push([x, y, z, 1]);\r\n\r\n u += .05;\r\n U = vec4(1, u, u * u, u * u * u);\r\n x = mult(vec4Transpose(U), mult(M, mult(Px, mult(m4Transpose(M), V)))); // x = uT * Mb * Px * Mb * v\r\n y = mult(vec4Transpose(U), mult(M, mult(Py, mult(m4Transpose(M), V))));\r\n z = mult(vec4Transpose(U), mult(M, mult(Pz, mult(m4Transpose(M), V))));\r\n\r\n x = .25 * (x[0] + x[1] + x[2] + x[3]); \r\n y = .25 * (y[0] + y[1] + y[2] + y[3]);\r\n z = .25 * (z[0] + z[1] + z[2] + z[3]);\r\n\r\n points.push([x, y, z, 1]);\r\n\r\n v += .05;\r\n V = vec4(1, v, v * v, v * v * v);\r\n x = mult(vec4Transpose(U), mult(M, mult(Px, mult(m4Transpose(M), V)))); // x = uT * Mb * Px * Mb * v\r\n y = mult(vec4Transpose(U), mult(M, mult(Py, mult(m4Transpose(M), V))));\r\n z = mult(vec4Transpose(U), mult(M, mult(Pz, mult(m4Transpose(M), V))));\r\n\r\n x = .25 * (x[0] + x[1] + x[2] + x[3]);\r\n y = .25 * (y[0] + y[1] + y[2] + y[3]);\r\n z = .25 * (z[0] + z[1] + z[2] + z[3]);\r\n\r\n points.push([x, y, z, 1]);\r\n\r\n v += .05;\r\n V = vec4(1, v, v * v, v * v * v);\r\n x = mult(vec4Transpose(U), mult(M, mult(Px, mult(m4Transpose(M), V)))); // x = uT * Mb * Px * Mb * v\r\n y = mult(vec4Transpose(U), mult(M, mult(Py, mult(m4Transpose(M), V))));\r\n z = mult(vec4Transpose(U), mult(M, mult(Pz, mult(m4Transpose(M), V))));\r\n\r\n x = .25 * (x[0] + x[1] + x[2] + x[3]);\r\n y = .25 * (y[0] + y[1] + y[2] + y[3]);\r\n z = .25 * (z[0] + z[1] + z[2] + z[3]);\r\n\r\n points.push([x, y, z, 1]);\r\n\r\n u += .05;\r\n U = vec4(1, u, u * u, u * u * u);\r\n x = mult(vec4Transpose(U), mult(M, mult(Px, mult(m4Transpose(M), V)))); // x = uT * Mb * Px * Mb * v\r\n y = mult(vec4Transpose(U), mult(M, mult(Py, mult(m4Transpose(M), V))));\r\n z = mult(vec4Transpose(U), mult(M, mult(Pz, mult(m4Transpose(M), V))));\r\n\r\n x = .25 * (x[0] + x[1] + x[2] + x[3]);\r\n y = .25 * (y[0] + y[1] + y[2] + y[3]);\r\n z = .25 * (z[0] + z[1] + z[2] + z[3]);\r\n\r\n points.push([x, y, z, 1]);\r\n\r\n //reset u and v\r\n u -= .1;\r\n v -= .1;\r\n }\r\n } \r\n \r\n }\r\n\r\n\r\n var vBuffer = gl.createBuffer();\r\n gl.bindBuffer(gl.ARRAY_BUFFER, vBuffer);\r\n gl.bufferData(gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW);\r\n\r\n var vPosition = gl.getAttribLocation(programId, \"vPosition\");\r\n gl.vertexAttribPointer(vPosition, 4, gl.FLOAT, false, 0, 0);\r\n gl.enableVertexAttribArray(vPosition);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Using ajax this function finds the correct script from a specific folder and returns it as text. The callback converts the text to runable code, and sends it to runChart(). | function loadScript(test) {
$.ajax({
url: 'tests-js/'+test,
success: function(data) {
tst = new Function([], "return " + data);
options = tst();
runChart(options, test);
},
dataType: 'text'
});
} | [
"function loadDivTextCharts(stockQuoteJsonUrl,stockSymbol, dividendDate, dividendAmount) {\n $.getJSON(stockQuoteJsonUrl, data2 => { renderDivTextCharts(data2, stockSymbol, dividendDate, dividendAmount)}); \n}",
"async function getScripts() {\n const url = '/api/scripts';\n const response = await fetch(url);\n const scriptFiles = await response.json();\n\n console.log(\"HUB: Script files have been recieved\");\n generateFileList(\"scriptsList\", \"delScriptsList\", scriptFiles);\n}",
"function loadContent(content) {\n\n $.get(\"/Main/LoadContent\", { name: content },function (data) {\n\n //load the html comming back from the get request into the #main div\n $(\"#main\").html(data);\n\n\n //Setup all the charting buttons for sensors (ie not == to home)\n if(content !== \"Home\")\n {\n \n \n try {\n chartProperties = JSON.parse($(\"#chartProperties\").attr(\"data-chart-prop\"));\n }\n catch (e) {\n //set a default chartProperties string\n chartProperties = {\n chartType: \"line\",\n datasetLabel: \"Default Dataset - error with Parse\",\n backgroundColor: \"rgba(255,0,0,1)\",\n borderColor: \"rgba(255,0,0,1)\",\n labelString: \"Default\"\n };\n }\n\n //must be a chart page. set up charting buttons\n setupBtnsSensorData(); //setup the demand and usage buttons\n setupBtnsSensorScale(); //setup the scale buttons\n setupBtnsSensorScroll(); //setup the scroll buttons\n updateChart(); //draw the chart first time\n }\n }, \"html\");\n //start the timer for user input\n \n}",
"function exec_script(script_name) {\n\t$.getScript(script_name, function(){\n\t\talert(script_name + \" loaded and executed.\");\n\t});\n}",
"function loadDynamicScripts(context) {\n var scriptPaths = context.scriptPaths;\n// var temp = scriptPaths[0];\n// scriptPaths[0] = scriptPaths[6];\n// scriptPaths[6] = temp;\n// console.log(\"scriptPaths Length: \" + scriptPaths.length);\n\n //console.log(\"scriptPaths: \" + scriptPaths);\n\n return new Promise(function (resolve, reject) {\n var loadScript, loadNext, settings;\n\n function failure() {\n var err = new Error(\"Unable to load \" + settings.url);\n reject(err);\n }\n\n\n settings = {};\n settings.dataType = \"script\";\n settings.contentType = false;\n settings.cache = true;\n\n loadScript = function (path) {\n settings.url = path;\n\n if (path) {\n $.ajax(settings).then(loadNext, failure);\n } else {\n resolve(context);\n }\n };\n\n loadNext = function () {\n loadScript(scriptPaths.shift());\n };\n\n loadNext();\n });\n }",
"function dependOn(dependency, callback) {\n var path = dependencies[dependency];\n if (/:\\/\\//.exec(path) !== null) {\n path = window.location.href + path;\n }\n var scripts = Array.prototype.slice.apply(document.getElementsByTagName('script'));\n if (!scripts.some(function(e) {return e.src === path;})) {\n var script = document.createElement('script');\n script.onload = callback();\n script.src = path;\n document.body.appendChild(script);\n } else {\n callback();\n }\n }",
"function loadScript(directoryName, filesArr) {\n\n for (var i = 0; i < filesArr.length; i++) {\n\n w.load(\"modules/\" + directoryName + \"/\" + filesArr[i] + '.js');\n }\n }",
"function read_data( path_name, callback ) {\n $.ajax({\n type: \"GET\",\n url: path_name,\n dataType: \"text\",\n success: function(data) { callback(data); }\n });\n}",
"function getScriptFromUrl(url) {\n\t\t if (typeof url === \"string\" && url) {\n\t\t for (var i = 0, len = scripts.length; i < len; i++) {\n\t\t\tif (scripts[i].src === url) {\n\t\t\t return scripts[i];\n\t\t\t}\n\t\t }\n\t\t }\n\t\t //return undefined;\n \t}",
"function executeScript() {\n chrome.tabs.executeScript(null, {\n file: 'scripts/getPagesSource.js'\n }, function() {\n // If you try and inject into an extensions page or the webstore/NTP you'll get an error\n if (chrome.runtime.lastError) {\n showErrorNotification('There was an error injecting script : \\n' + chrome.runtime.lastError.message, true);\n }\n });\n}",
"function GetGistFileContent(url, name, callback) {\n $.ajax({\n url: url,\n type: 'GET',\n dataType: 'text',\n cache: false\n }\n ).success(function (data) {\n if (data.length > 0) {\n callback(data, name);\n }\n else {\n LogErrorOverlay(\"Failed to retrieve File '\" + name + \"'.\", \"Github reported an error for this file.\", JSON.stringify(data, null, 2));\n }\n }).error(function (e) {\n LogErrorOverlay(\"Failed to retrieve File '\" + name + \"'.\", \"Github reported an error for this file.\", JSON.stringify(e, null, 2));\n });\n}",
"function build_run_chart(N, js, php, php_mt, online) {\n load_chart('chart', {\n title: {\n text: \"Random generators runs\"\n },\n yAxis: {\n title: {\n text: \"runs on \" + N + \" numbers\"\n }\n },\n series: [{\n name: 'Generators',\n colorByPoint: true,\n data: [{\n name: 'JS Math.random()',\n y: js,\n drilldown: 'JS Math.random()'\n }, {\n name: 'PHP rand()',\n y: php,\n drilldown: 'PHP rand()'\n }, {\n name: 'PHP mt_rand()',\n y: php_mt,\n drilldown: 'PHP mt_rand()'\n }, {\n name: 'Online random.org',\n y: online,\n drilldown: 'Online random.org'\n }]\n }],\n tooltip: {\n headerFormat: \"<span style=\\\"font-size:11px\\\">{series.name}</span><br>\",\n pointFormat: \"<span style=\\\"color:{point.color}\\\">{point.name}</span> runs<br/>\"\n }\n });\n}",
"function loadTitanFromLocDir(fname){\n//\tvar url = \"/cgi-bin/Final/RM_CGI_AutoComplete/AutoCompleteCgiQuerryjayson/FindResource2.cgi?action=gettitanfile&query=filename=\"+fname+\"^user=\"+globalUserName;\n//\tvar InfoType = \"XML\";\n//\tif(InfoType == \"XML\"){\n//\t\tvar url = getURL(\"ConfigEditorTopo\")+\"action=gettitanfile&query=filename=\"+fname+\"^user=\"+globalUserName;\n//\t}else{\n\t\tvar url = getURL('ConfigEditorTopo', 'JSON')+'action=gettitanfile&query={\"QUERY\":[{\"filename\": \"'+fname+'\", \"user\": \"'+globalUserName+'\"}]}';\n//\t}\n\t$.ajax({\n\t\turl: url,\n\t\tproccessData: false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data){\n\t\t\tif(data){\n//\t\t\t\tgetDataFromXML(data);\n\t\t\t\tgetStringJSON(globalMAINCONFIG[pageCanvas]);\n\t\t\t}else{\n\t\t\t\talert('Something went wrong, CGI did not return anything.');\n\t\t\t}\n\t\t\t$(\"#loadConfig\").dialog('close');\n\t\t},\n\t\terror: function (xhr, ajaxOptions, thrownError) {\n\t\t\talert(xhr.status+\" : \"+thrownError);\n\t\t}\n\t});\n}",
"function showFiles(container, samplePath, filesGlob) {\n // get current container\n var $ = cheerio.load(container);\n var filesCollection = filesGlob.split(','),\n sampleFiles = [];\n for (var i = 0; i < filesCollection.length; i++) {\n sampleFiles.push(samplePath + '/' + filesCollection[i]);\n }\n var patterString = sampleFiles.toString();\n // get the glob pattern from file arguments\n var globPattern = sampleFiles.length > 1 ? '{' + patterString + '}' : patterString;\n var files = glob.sync(globPattern);\n // append the ul for source tab\n $('.source').html('');\n $('.source').append('<div class=\"ej2-source-tab\"><ul class=\"nav nav-tabs\"></ul></div>');\n var active = 'active',\n hidden = '';\n // create source content for code snippets\n for (var i = 0; i < files.length; i++) {\n var fileName = path.basename(files[i]);\n var fileAttr = fileName.split('.').join('-');\n var fileType = types[path.extname(files[i])]\n var type = fileType ? fileType : 'javascript';\n var hlContent = renderCodeSnippets('```' + type + '\\n' + fs.readFileSync(files[i], 'utf8') + '\\n```');\n if (i > 0) {\n active = '';\n hidden = 'ej2-hidden';\n }\n // append the li to ul element\n var li = '<li class=\"' + active + ' ej2-source-li\" for=\"' + fileAttr + '\"><a data-toggle=\"tab\">' + fileName + '</a></li>';\n $('.ej2-source-tab .nav-tabs').append(li);\n // append the source content with highlight.js format in the container\n $('.ej2-source-tab').append('<div class=\"ej2-source-content ' + hidden + ' ' + fileAttr + '\">' + hlContent + '</div>');\n }\n return $.html();\n}",
"function fun( error , response , data ){\n // current directory => homepage.html , => html file of webpage\n parseData(data);\n}",
"function ajax_gethtml(){\r\n\tif(arguments.length == 0) return false;\r\n\tvar url = arguments.length > 0 ? arguments[0] : \"\";\r\n\tvar show = arguments.length > 1 ? arguments[1] : \"\";\r\n\tvar tip = arguments.length > 2 ? arguments[2] : \"\";\r\n\tvar loading = arguments.length > 3 ? arguments[3] : \"\";\r\n\tvar loaded = arguments.length > 4 ? arguments[4] : \"\";\r\n\tvar interactive = arguments.length > 5 ? arguments[5] : \"\";\r\n\tvar completed = arguments.length > 6 ? arguments[6] : \"\";\r\n\tvar ajax = new jieqi_ajax();\r\n\tajax.method = \"GET\";\r\n\tajax.requestFile = url;\r\n\tif(tip != \"\"){\r\n\t\t$(tip).innerHTML = \"\";\r\n\t\t$(tip).style.display = \"\";\r\n\t\tif(loading != \"\") ajax.onLoading = function(){$(tip).innerHTML = loading;};\r\n\t\tif(loaded != \"\") ajax.onLoaded = function(){$(tip).innerHTML = loaded;};\r\n\t\tif(interactive != \"\") ajax.onInteractive = function(){$(tip).innerHTML = interactive;};\r\n\t\tajax.onError = function() {$(tip).innerHTML = \"ERROR:\"+ajax.responseStatus[1]+\"(\"+ajax.responseStatus[0]+\")\";};\r\n\t\tajax.onFail = function() {$(tip).innerHTML = \"Your browser does not support AJAX!\";};\r\n\t}\r\n\tajax.onCompletion = function(){\r\n\t\tif(tip != \"\"){\r\n\t\t\tif(completed != \"\") $(tip).innerHTML = completed;\r\n\t\t\telse if(tip != show){\r\n\t\t\t\t$(tip).innerHTML = \"\";\r\n\t\t\t\t$(tip).style.display = \"none\";\r\n\t\t\t}\r\n\t\t}\r\n\t\t$(show).innerHTML = ajax.response;\r\n\t};\r\n\tajax.runAJAX();\r\n}",
"function includeJS(file_path){ \r\n var j = document.createElement(\"script\");\r\n j.type = \"text/javascript\";\r\n j.onload = function(){\r\n lib_loaded(file_path);\r\n };\r\n j.src = file_path;\r\n document.getElementsByTagName('head')[0].appendChild(j); \r\n}",
"function switch_chart_to(spec) {\n if (spec == \"\") {\n return;\n }\n\n document.getElementById(\"pre_chart_options\").style.display = 'block';\n\n // load scripts/data of the wanted chart if it's not already present\n var already_loaded = false;\n var scripts = document.scripts\n for (var i = scripts.length - 1; i >= 0; i--) {\n // if a script already is loaded for the fight style and spec, don't load again\n if (~scripts[i].src.indexOf(\"js/crucible/crucible_\" + spec + \"_\" + fight_style + \".js\")) {\n already_loaded = true;\n }\n }\n if ( ! already_loaded) {\n getScript(\"js/crucible/crucible_\" + spec + \"_\" + fight_style + \".js\");\n }\n\n // hide/show charts\n var container = document.getElementsByClassName(\"container-relics\");\n for (var i = container.length - 1; i >= 0; i--) {\n if (container[i].id === \"crucible_\" + spec + \"_\" + fight_style) {\n container[i].style.display = 'block';\n active_spec = spec;\n } else {\n container[i].style.display = 'none';\n }\n }\n\n // hide/show TC-resource and Discord of the spec\n var tc_boxes = document.getElementsByClassName(\"tc-box\");\n for (var i = tc_boxes.length - 1; i >= 0; i--) {\n if (tc_boxes[i].id === \"tc_\" + spec) {\n tc_boxes[i].style.display = 'block';\n } else {\n tc_boxes[i].style.display = 'none';\n }\n }\n\n ga('send', 'event', 'relics', fight_style, active_spec);\n\n if (language != \"EN\") {\n //console.log(\"Starting translation process.\");\n setTimeout(translate_charts, 200);\n }\n}",
"function readInChartCSV() {\n\tvar $ = jQuery;\n\t\n\t$.ajax({\n\t\turl: chartContainer.data('src'),\n\t\ttype: 'get',\n\t\tdataType: 'text',\n\t\tsuccess: function(result) {\n\t\t\tvar parseResult = $.parse(result,{header: false, dynamicTyping: true})\n\t\t\t//console.info(parseResult);\n\t\t\tvar chartArray = parseResult.results;\n\n\t\t\t$('#chart-data').html(result);\n\n\t\t\tswitch(chartContainer.data('charttype')) {\n\t\t\t\tcase 'line': case 'bar': case 'column':\n\t\t\t\t\tgenericChartParser(chartArray, chartContainer);\n\t\t\t\tbreak;\n\n\t\t\t\tcase 'pie':\n\t\t\t\t\tpieChartParser(chartArray, chartContainer);\n\t\t\t\tbreak;\n\n\t\t\t\tcase 'stock':\n\t\t\t\t\tstockChartParser(chartArray, chartContainer);\n\t\t\t\tbreak;\n\t\t\t};\n\t\t},\n\t\terror: function(error) {\n\t\t\tconsole.log(error.status + ' ' + error.statusText)\n\t\t}\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints 3 Impartial function | function impartial(x, y, z) {
return x + y + z;
} | [
"function skaiciavimai(x,y,z) {\n console.log(x+2, y+4, z*2);\n}",
"function printMetinisPajamuDydis() {\n\n console.log(\"Metinis atlyginiams \" + atlyginimas * 12);\n}",
"function displayQualifier1() {\n var i = 1;//assignam valoarea initiala (=1) pentru contorul i, pentru parcurgerea while\n while (i < 11) {//parcurgem while pana la i = 10\n text = \"Pentru \" + i + \", obtii calificativul \" + x(i) + \"\\n\";//variabila text va fi de forma \"Pentru 1, obtii calificativul E (rezultat din apelarea functiei de tip function expression x(i))\"\n console.log(text);//afisam in consola variabila text\n i++;//incrementam cu 1 unitate contorul i\n }\n}",
"function spausdinti(a, b, c) {\n console.log(a, b, c);\n }",
"function multThree() {\n\tfor (let i = 3; i <= 90; i++){\n\t\tif (i % 3 === 0) {\n\t\t\tconsole.log(i);\n\t\t}\n\t}\n}",
"function multiplysNum(n1, n2, n3){\n alert (n1 * n2 * n3)\n}",
"printPascal2 ( n) {\n for (let line = 1; line <= n; line++)\n {\n let C = 1; // used to represent C(line, i)\n\n let str = \" \";\n for (let i = 1; i <= line; i++)\n {\n str += C + \" \";\n // The first value in a line is always 1\n C = C * (line - i) / i;\n }\n console.log(str);\n }\n }",
"function mostrarNbMultiplicacion() {\n $multiplicacion.innerHTML = \"Multipliez x \" + nbMultiplicacion + \" ( points du prochain super Cookie : \" + points() + \" ) \";\n}",
"function multiPrint(a, b, c) {\n console.log(a)\n console.log(b)\n console.log(c)\n}",
"function triple(number) {\n return number * 3\n}",
"function fourNums(n1, n2, n3, n4){\n console.log (n1 + n2 - n3 - n4)\n}",
"function faculteit(n) {\n\n}",
"function TableMultiplication(X) {\n var i = 1;//on set l'itérateur de la boucle, qui est aussi le multiplicateur\n var X;//on déclare X\n //on crée la boucle afin d'afficher chaque ligne avec l'opération + résultat\n while (i<=10) \n {\n document.write(i + \" x \" + X + \" = \" + i*X+\"<br>\");//affichage de l'opération + résultat\n i++; \n }\n}",
"function i33( x )\n {\n\n let a = x.v[ 0 ] ;\n let b = x.v[ 1 ] ;\n let c = x.v[ 2 ] ;\n\n let d = x.v[ 3 ] ;\n let e = 0 ;\n let f = 0 ;\n \n if( x.nv == 6 )\n {\n \n e = x.v[ 4 ] ;\n f = x.v[ 5 ] ;\n\n } ; // end if{} -\n\n let r = ( (a * b * c) + (2 * d * e * f) - (a * f * f) - (b * e * e) - (c * d * d) ) ;\n\n return( r ) ;\n\n }",
"function multiplyByOne2() {\n var i = 0;//assignam valoarea initiala (=0) pentru contorul i, pentru parcurgerea while\n var x = 1;//declaram variabila x, reprezentand numarul cu care vom inmulti contorul nostru si ii assignam valoarea 1\n while (i < 11) {//parcurgem while pana la i = 10\n text = x + \" * \" + i + \" = \" + x * i + \"\\n\";//variabila text va deveni tabla inmultirii (ex.:1 * 0 = 0) si va fi de tip string\n console.log(text);//afisam in consola variabila text\n i++;//incrementam cu 1 unitate contorul i\n }\n}",
"function multipleOfThree() {\n for (let i = 1; i <= 100; i++) {\n if (i % 3 == 0 && i % 5 == 0) {\n console.log(\"CSC225 RULES I LOVE JAVASCRIPT\");\n } else if (i % 3 == 0) {\n console.log(\"CSC225 RULES\");\n } else if (i % 5 == 0) {\n console.log(\"I LOVE JAVASCRIPT\");\n } else {\n console.log(i);\n }\n }\n}",
"function addInitals(first, last){\n console.log ('Your Initals:', (first + last));\n}",
"function faktorial(n)\r\n{\r\n\tif (n == 0) return 1\r\n\treturn n * faktorial( n - 1 ) // 5 * ( 4 * ( 3 * ( 2 * ( 1 ) ) ) )\r\n}",
"function naturalNumber(){\n var printAll=0;\n var num = document.getElementById('sumInput').value;\n for(var i=1; i<=num; i++){\n printAll = printAll +','+i;\n }\n document.getElementById('naturalNumber').innerHTML=printAll;\n}",
"function kalikan(n,m){\n return n*m;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tabs hook to show an animated indicators that follows the active tab. The way we do it is by measuring the DOM Rect (or dimensions) of the active tab, and return that as CSS style for the indicator. | function useTabIndicator() {
var context = useTabsContext();
var {
selectedIndex,
orientation,
domContext
} = context;
var isHorizontal = orientation === "horizontal";
var isVertical = orientation === "vertical"; // Get the clientRect of the selected tab
var [rect, setRect] = (0, _react.useState)(() => {
if (isHorizontal) return {
left: 0,
width: 0
};
if (isVertical) return {
top: 0,
height: 0
};
});
var [hasMeasured, setHasMeasured] = (0, _react.useState)(false); // Update the selected tab rect when the selectedIndex changes
(0, _hooks.useSafeLayoutEffect)(() => {
var _tab$element;
if ((0, _utils.isUndefined)(selectedIndex)) return;
var tab = domContext.descendants[selectedIndex];
var tabRect = tab == null ? void 0 : (_tab$element = tab.element) == null ? void 0 : _tab$element.getBoundingClientRect(); // Horizontal Tab: Calculate width and left distance
if (isHorizontal && tabRect) {
var {
left,
width
} = tabRect;
setRect({
left,
width
});
} // Vertical Tab: Calculate height and top distance
if (isVertical && tabRect) {
var {
top,
height
} = tabRect;
setRect({
top,
height
});
} // Prevent unwanted transition from 0 to measured rect
// by setting the measured state in the next tick
var frameId = requestAnimationFrame(() => {
setHasMeasured(true);
});
return () => {
cancelAnimationFrame(frameId);
};
}, [selectedIndex, isHorizontal, isVertical, domContext.descendants]);
return _extends({
position: "absolute",
transition: hasMeasured ? "all 200ms cubic-bezier(0, 0, 0.2, 1)" : "none"
}, rect);
} | [
"function floatTab(tab, on) {\n if (on) {\n tab.node.classList.add(FLOATING_CLASS);\n }\n else {\n tab.node.classList.remove(FLOATING_CLASS);\n }\n }",
"function _jsTabControl_turnTabOn(tabID) {\n\tdocument.getElementById('tab' + tabID + 'text').style.backgroundImage = \"url(\" + IMG_TAB_ON[1].filename + \")\";\n\tdocument.images['tab' + tabID + 'left'].src = IMG_TAB_ON[0].filename;\n\tdocument.images['tab' + tabID + 'right'].src = IMG_TAB_ON[2].filename;\t\t\n}",
"_tabStyle() {\n this.$containerEl.find('.te-md-container').removeClass('te-preview-style-vertical');\n this.$containerEl.find('.te-md-container').addClass('te-preview-style-tab');\n }",
"function initTabbar() {\n _debug();\n if ($('#tabbar').length) {\n _debug(' #tabbar exists');\n\n // Find current class or 1st page in #jqt & the last stylesheet\n var firstPageID = '#' + ($('#jqt > .current').length === 0 ? $('#jqt > *:first') : $('#jqt > .current:first')).attr('id'),\n sheet = d.styleSheets[d.styleSheets.length - 1];\n\n // Make sure that the tabbar is not visible while its being built\n $('#tabbar').hide();\n $('#tabbar div:first').height($('#tabbar').height());\n _debug(' #tabbar height = ' + $('#tabbar').height() + 'px');\n $('#tabbar a').each(function (index) {\n var $me = $(this),\n mask2x = $me.attr('mask2x'),\n tabIcon = $me.attr('mask'),\n tabZoom = 1,\n parseJS = function(input) {return input.replace(/(\\r\\n|\\n|\\r)/gm,' ').replace(/\\s+/g,' ').replace(/^javascript:\\s*/i,'').replace(/return\\s*[\\(]*\\s*false\\s*[\\)]*[;]*$|return\\s*[\\(]*\\s*true\\s*[\\)]*[;]*$/i,'');};\n\n // PhoneGap integration\n if (typeof (PhoneGap) !== 'undefined' && jQT.barsSettings.phonegap) {\n $('body > #tabbar').css({\n bottom: '20px !important'\n });\n }\n\n // Enummerate the tabbar anchor tags\n $me.attr('id', 'tab_' + index);\n\n // If this is the button for the page with the current class then enable it\n if ($me.attr('href') === firstPageID) {\n $me.addClass('enabled');\n }\n\n // Create css masks from the anchor's mask property\n if (window.devicePixelRatio && window.devicePixelRatio === 2 && typeof (mask2x) !== 'undefined') {\n tabIcon = $(this).attr('mask2x');\n tabZoom = 0.5;\n }\n sheet.insertRule('a#tab_' + index + '::after, a#tab_' + index + '::before {-webkit-mask-image:url(\\'' + tabIcon + '\\');' + ' zoom: ' + tabZoom + ';}', sheet.cssRules.length);\n\n // Put page animation, if any, into data('animation')\n $me.data('animation', $me.attr('animation'));\n\n // Action code or url in href attribute\n if (typeof ($me.attr('href')) !== 'undefined' && $me.attr('href') !== null) {\n if ($me.attr('href').match(/^javascript:\\s*/i) !== null) {\n // Put action code into data('action')...\n $me.data('action', parseJS($me.attr('href')));\n $me.addClass('action');\n } else {\n // Put href target into data('defaultTarget')...\n $me.data('defaultTarget', $me.attr('href'));\n }\n // ...and remove href\n $me.removeAttr('href');\n }\n\n // Action code in onClick event\n if (typeof ($me.attr('onClick')) !== 'undefined' && $me.attr('onClick') !== null) {\n $me.data('action', parseJS($me.attr('onClick')));\n $me.removeAttr('onclick');\n if (typeof ($me.data('defaultTarget')) === 'undefined' || $me.data('defaultTarget') === null) {\n $me.addClass('action');\n }\n }\n\n // Tabbar tap event\n // Action\n if (typeof ($me.data('action')) !== 'undefined' && $me.data('action') !== null) {\n $me.click(function () {\n setTimeout($me.data('action'), 0);\n });\n }\n\n // Navigation\n if (typeof ($me.data('defaultTarget')) !== 'undefined' && $me.data('defaultTarget') !== null) {\n $me.click(function () {\n var $referrerTab = $('#tabbar .enabled'),\n $tabs = $('#tabbar a'),\n $targetTab = $(this),\n animation = animations.indexOf(':' + $me.data('animation') + ':') > -1 ? $me.data('animation') : '',\n i,\n referrerAnimation = animations.indexOf(':' + $referrerTab.data('animation') + ':') > -1 ? $referrerTab.data('animation') : '',\n referrerPage = $referrerTab.data('defaultTarget'),\n target = $me.data('defaultTarget'),\n targetAnimation = animations.indexOf(':' + $targetTab.data('animation') + ':') > -1 ? $targetTab.data('animation') : '',\n targetHist = $targetTab.data('hist'),\n targetPage = $targetTab.data('defaultTarget'),\n thisTab,\n TARDIS = function (anime) {\n var DW;\n if (anime.indexOf('left') > 0) {\n DW = anime.replace(/left/, 'right');\n } else if (anime.indexOf('right') > 0) {\n DW = anime.replace(/right/, 'left');\n } else if (anime.indexOf('up') > 0) {\n DW = anime.replace(/up/, 'down');\n } else if (anime.indexOf('down') > 0) {\n DW = anime.replace(/down/, 'up');\n } else {\n DW = anime;\n }\n return DW;\n };\n\n if (!$targetTab.hasClass('enabled')) {\n for (i = $('#tabbar a').length - 1; i >= 0; --i) {\n thisTab = $tabs.eq(i);\n thisTab.toggleClass('enabled', ($targetTab.get(0) === thisTab.get(0)));\n if ($targetTab.get(0) === thisTab.get(0)) {\n jQT.goTo(target, (targetAnimation === '' ? TARDIS(referrerAnimation) : targetAnimation));\n _debug('tabbbar touch, new tab');\n setPageHeight();\n }\n }\n } else {\n jQT.goTo(target);\n _debug('tabbar touch, same tab');\n setPageHeight();\n }\n });\n }\n });\n\n // Hide tabbar when page has a form or any form element or .hide_tabbar class except when the page's parent div has the .keep_tabbar class.\n // Show tabbar when leaving a form or .hide_tabbar page except when going into a page with a form or .hide_tabbar class\n $('#jqt > div, #jqt > form').each(function () {\n $(this).bind('pageAnimationStart', function (e, data) {\n var $target = $(e.target),\n isForm = function ($page) {\n return $page.has('button, datalist, fieldset, form, keygen, label, legend, meter, optgroup, option, output, progress, select, textarea').length > 0 && !($(':input', $page).length !== $(':input:hidden', $page).length);\n },\n isHide = function ($page) {\n return $page.hasClass('hide_tabbar') || $page.children().hasClass('hide_tabbar');\n },\n isKeep = function ($page) {\n return $page.hasClass('keep_tabbar') || $page.children().hasClass('keep_tabbar');\n };\n\n if (data.direction === 'in') {\n if ((!isForm($target) && !isHide($target)) || isKeep($target)) {\n $('#tabbar').show(function () {\n _debug('Show tabbar');\n setPageHeight();\n });\n } else {\n $('#tabbar').hide(function () {\n _debug('Hide tabbar');\n setPageHeight();\n });\n }\n }\n });\n });\n\n // Resize tabbar & scroll to enabled tab on rotation\n $('#jqt').bind('turn', function (e, data) {\n var $tabbar = $('#tabbar'),\n scroll = $tabbar.data('iscroll');\n if (scroll !== null && typeof (scroll) !== 'undefined') {\n setTimeout(function () {\n $tabbar.width = win.innerWidth;\n if ($('.enabled').offset().left + $('.enabled').width() >= win.innerWidth) {\n scroll.scrollToElement('#' + $('.enabled').attr('id'), 0);\n }\n }, 0);\n }\n });\n\n // Show tabbar now that it's been built, maybe\n if (!$('.current').hasClass('hide_tabbar')) {\n $('#tabbar').show(0, function () {\n _debug('initTabbar hide tabbar');\n setPageHeight();\n setBarWidth();\n });\n } else {\n _debug('initTabbar show tabbar');\n setPageHeight();\n setBarWidth();\n }\n }\n }",
"function pa_tabs_start(id_panel, id_content, active_index, adjust_content_position) {\n\tvar tab_elem = _( id_panel );\n\tvar items = tab_elem.getElementsByClassName('pa-tab-menu-item');\n\tvar i = 0;\n\tvar items_length = items.length;\n\tvar item_width = 1.0 / items_length;\n\twhile ( i < items_length ) {\n\t\tvar item = items[i];\n\t\titem.className += ' pa_width_' + item_width + ' pa_left_' + (i*item_width);\n\t\tpa_add( item );\n\t\t/// bindings\n\t\titem.addEventListener('click', function() {\n\t\t\tpa_tabs_active_tab(tab_elem, this);\n\t\t});\n\t\t++i;\n\t}\n\tpa_tabs_active_tab( tab_elem, items[active_index] );\n\tif ( adjust_content_position === true ) {\n\t\tpa_tabs_adjust_content_div_position( _(id_panel), _(id_content) );\n\t}\n}",
"function _jsTabControl_draw() {\n\n\t//calculate tabsperstrip\n\tthis.tabsPerStrip = parseInt((window.innerWidth - IMG_BTN_MORE.width - IMG_BTN_LESS.width) / this.tabWidth);\n\n\t//calculate number of strips needed\n\tvar numStrips = Math.ceil(this.tabs.length / this.tabsPerStrip);\n\t\n\t//draw each strip\n\tfor (i=0; i < numStrips; i++)\n\t\tthis.createStrip(0 + (this.tabsPerStrip * i), this.tabsPerStrip + (this.tabsPerStrip * i));\n\n}",
"function mouseOverTab(i){\n\tvar n=i.substring(i.length-1,i.length);\n\tvar tab_body_display=document.getElementById(\"tab_body\"+n).style.display;\n\tif(tab_body_display==\"none\"){\n\t\tdocument.getElementById(i).style.borderBottomColor=\"white\";\n\t}\n}",
"function _activeClass(tab) {\n if (vm.selectedTab == tab) {\n return \"active\";\n } else {\n return \"\";\n }\n }",
"renderTabs() {\n\t const { currentTabIndex } = this.state;\n\t const { children, accent, onTabChange } = this.props;\n\t return React.Children.map(children, (child, index) => {\n\t return React.cloneElement(child, {\n\t onClick: this.handleTabChange,\n\t tabIndex: index,\n\t isActive: index === currentTabIndex,\n\t onTabChange,\n\t });\n\t });\n\t}",
"renderTabBar() {\n return (\n <ul\n className={classNames({\n 'usaf-tab-group__tabs': this.props.type === 'tab',\n 'usaf-tab-group__pills': this.props.type === 'pill'\n })}\n >\n {\n this.childrenArray.map(\n (child, index) => (\n <li\n key={createUid(10)}\n className={classNames(\n 'usaf-tab-group__tab',\n { 'usaf-tab-group__tab--active': this.state.selectedIndex === index }\n )}\n >\n <button\n className={classNames(\n 'usaf-tab-group__btn',\n )}\n value={index}\n onClick={this.handleClick}\n >\n {child.props.label}\n </button>\n </li>\n )\n )\n }\n </ul>\n );\n }",
"function activeTabIntoPanel() {\n chrome.tabs.query({\n active: true,\n currentWindow: true\n }, function(tabs) {\n tabIntoPanel(tabs[0]);\n });\n}",
"function displaySettingsBackgroundTabs() {\r\n var $tabButton = $(\".settings-background-tab-button[data-settings-tabid=\" + getSettingsBackgroundTabId() + \"]\");\r\n $tabButton.tab('show');\r\n addSelectedTxt();\r\n blinkActiveSortType();\r\n}",
"function mouseOutTab(i){\n\tvar n=i.substring(i.length-1,i.length);\n\tvar tab_body_display=document.getElementById(\"tab_body\"+n).style.display;\n\tif(tab_body_display==\"none\"){\n\t\tdocument.getElementById(i).style.borderBottomColor=\"gray\";\n\t}\n}",
"function activePanelIntoTab() {\n chrome.windows.getAll(null, function(windows) {\n windows.forEach(function(vindov) {\n if (isPanel(vindov) && vindov.focused) {\n panelIntoTab(vindov.id);\n return;\n }\n });\n });\n}",
"function i2uiScrollTabsLeft(id)\r\n{\r\n if (document.layers)\r\n return;\r\n var obj = document.getElementById(id);\r\n if (obj != null)\r\n {\r\n var tablen = obj.rows[0].cells.length;\r\n\r\n var showid = 0;\r\n // show last invisible tab from right\r\n for (var i=tablen-3; i>4; i--)\r\n {\r\n if (obj.rows[0].cells[i].style.display == \"none\")\r\n {\r\n showid = i;\r\n i -= 3;\r\n }\r\n else\r\n if (showid > 0)\r\n {\r\n if (showid == 1)\r\n i2uiToggleItemVisibility(id+'_tabscrollerright','hide');\r\n else\r\n i2uiToggleItemVisibility(id+'_tabscrollerright','show');\r\n\r\n obj.rows[0].cells[showid].style.display = \"\";\r\n obj.rows[0].cells[showid].style.visibility = \"visible\";\r\n showid--;\r\n obj.rows[0].cells[showid].style.display = \"\";\r\n obj.rows[0].cells[showid].style.visibility = \"visible\";\r\n showid--;\r\n obj.rows[0].cells[showid].style.display = \"\";\r\n obj.rows[0].cells[showid].style.visibility = \"visible\";\r\n showid--;\r\n obj.rows[0].cells[showid].style.display = \"\";\r\n obj.rows[0].cells[showid].style.visibility = \"visible\";\r\n showid--;\r\n\r\n // show all other tabs\r\n for (var j=showid; j>0; j--)\r\n {\r\n obj.rows[0].cells[j].style.display = \"\";\r\n obj.rows[0].cells[j].style.visibility = \"visible\";\r\n }\r\n\r\n // now hide just enough of those on left\r\n i2uiManageTabs(id,null,\"front\",null,showid+4);\r\n\r\n break;\r\n }\r\n }\r\n }\r\n}",
"#updateStepIndicator() {\n if (!this.#stepIndicator.children.length) {\n this.#steps.forEach(({ name, status, label }, index) => {\n let item = document.createElement(\"li\");\n item.setAttribute(\"id\", name);\n item.setAttribute(\"status\", status);\n\n let subtitle = document.createElement(\"p\");\n subtitle.classList.add(\"subtitle\");\n subtitle.textContent = interpolate(gettext(\"Step %s\"), [index + 1]);\n item.appendChild(subtitle);\n\n let title = document.createElement(\"p\");\n title.classList.add(\"title\");\n title.textContent = gettext(label);\n item.appendChild(title);\n\n this.#stepIndicator.appendChild(item);\n });\n } else {\n this.#steps.forEach((step) => {\n let indicator = this.shadowRoot.getElementById(step.name);\n let title = indicator.querySelector(\".title\");\n indicator.setAttribute(\"status\", step.status);\n title.textContent = gettext(step.label);\n });\n }\n }",
"function question(evt, questionNo, type) {\n var i, tabcontent, tablinks;\n tabcontent = document.getElementsByClassName(\"tabcontent\");\n for (i = 0; i < tabcontent.length; i++) {\n tabcontent[i].style.display = \"none\";\n }\n tablinks = document.getElementsByClassName(\"tablinks\");\n for (i = 0; i < tablinks.length; i++) {\n tablinks[i].style.backgroundColor = \"\";\n }\n\n if (type == 'pre') {\n questionNo = parseInt(questionNo) - 1\n }\n if (type == 'next') {\n questionNo = parseInt(questionNo) + 1\n }\n document.getElementById(questionNo).style.display = \"block\";\n let tabid = 'defaultOpen' + questionNo\n}",
"function tabLinks( active ) {\n\tfunction tab( id, label ) {\n\t\treturn T( id == active ? 'tabLinkActive' : 'tabLinkInactive', {\n\t\t\tid: id,\n\t\t\tlabel: label\n\t\t});\n\t}\n\tif (((document.location.href.indexOf('nid=') > 0) \n\t&& (document.location.href.indexOf('gid=') > 0) \n\t&& (document.location.href.indexOf('pid=') > 0)) || (document.location.href.indexOf('cid=') > 0)) {\n\t\treturn T( 'tabLinks', {\n\t\t\ttab1: tab( '#detailsbox', 'معلومات' ),\n\t\t\ttab2: includeMap() ? tab( '#mapbox', 'الخـريطة' ) : '',\n\t\t\ttab3: '' \n\t\t});\t\n\t}\n\treturn T( 'tabLinks', {\n\t\ttab1: tab( '#detailsbox', 'معلومات' ),\n\t\ttab2: includeMap() ? tab( '#mapbox', 'الخـريطة' ) : '',\n\t\ttab3: pref.ready ? '' : tab( '#Poll411Gadget', 'بـحـــث' )\n\t});\n}",
"function onTabShown(event, tabId) {\n if (tabId === tabControl.TABS.EXPLORE) {\n showSpinner();\n UserPreferences.setPreference('method', 'explore');\n setFromUserPreferences();\n $(options.selectors.isochroneSliderContainer).removeClass(options.selectors.hiddenClass);\n clickedExplore();\n } else {\n $(options.selectors.alert).remove();\n mapControl.isochroneControl.clearIsochrone();\n mapControl.isochroneControl.clearDestinations();\n $(options.selectors.isochroneSliderContainer).addClass(options.selectors.hiddenClass);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return absolute offset for a target | function getOffset(target) {
if (target instanceof Array) {
return Rect(target[0], target[1], target[2] || target[0], target[3] || target[1]);
}
if (typeof target === 'string') {
//`100, 200` - coords relative to offsetParent
var coords = target.split(/\s*,\s*/).length;
if (coords === 2) {
return Rect(parseInt(coords[0]), parseInt(coords[1]));
}
}
if (!target) {
return Rect();
}
//`.selector` - calc selected target coords relative to offset parent
return offset(target);
} | [
"offsetByCanvas(canvasTarget) {\n const offset = { x: 0, y: 0 };\n let i;\n for (i = 0; i < this.indexOfTarget(canvasTarget); i += 1) {\n offset.x += this.canvases[i].getWidth();\n }\n return offset;\n }",
"get tileOffset() {}",
"function calculateOffsetTop(r){\n return absolute_offset(r,\"offsetTop\")\n}",
"absoluteX() {\n this.incrementPc();\n let lo = this.ram[this.cpu.pc];\n this.incrementPc();\n let hi = this.ram[this.cpu.pc];\n\n let target = (hi * 0x0100 + lo + this.cpu.xr) & 0xffff;\n\n if ((target & 0xff00) != (hi * 0x100)) {\n this.penaltyCycles += 1;\n }\n\n return target;\n }",
"getImageOffset(x, y, debug){\n // console.log(\"get sprite offset at world:\", x, y);\n let halfWidth = this.spriteGrid.length/2;\n let halfHeight = this.spriteGrid[0].length/2;\n let spriteSheetX = Math.floor((x/this.ENGINE.gridSize) + halfWidth);\n let spriteSheetY = Math.floor((y/this.ENGINE.gridSize) + halfHeight);\n if(spriteSheetX < 0 || spriteSheetX >= this.spriteGrid.length){\n spriteSheetX = 0;\n }\n if(spriteSheetY < 0 || spriteSheetY >= this.spriteGrid[0].length){\n spriteSheetY = 0;\n }\n let imageOffset = this.spriteGrid[spriteSheetX][spriteSheetY];\n // console.log(`${x}=>${spriteSheetX},${y}=>${spriteSheetY}: ${imageOffset}`);\n // console.log(spriteSheetX, spriteSheetY, this.spriteGrid.length);\n // console.log(imageOffset);\n if(debug) return {x:spriteSheetX, y:spriteSheetY};\n return imageOffset;\n }",
"relativeLevelPosition(level, target){\n if(!target){ return [\"none\", \"same\", level]; };\n var difference = target.indexes[level] - this.indexes[level];\n\n if(difference < -1){\n return [\"jump\", \"backwards\", \"by-\" + level];\n } else if(difference == -1){\n return [\"advance\", \"backwards\", \"by-\" + level];\n } else if(difference == 1){\n return [\"advance\", \"forwards\", \"by-\" + level];\n } else if(difference > 1){\n return [\"jump\", \"forwards\", \"by-\" + level];\n }\n\n return [\"none\", \"same\", \"by-\" + level];\n }",
"function offsetShouldReturnOffsetsForElement() {\n const data = element.offset(fixture.el.querySelector(\".container\"))\n expect(data)\n .toEqual({\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n })\n}",
"function get_unit_anim_offset(punit)\n{\n var offset = {};\n if (punit['anim_list'] != null && punit['anim_list'].length >= 2) {\n var anim_tuple_src = punit['anim_list'][0];\n var anim_tuple_dst = punit['anim_list'][1];\n var src_tile = index_to_tile(anim_tuple_src['tile']);\n var dst_tile = index_to_tile(anim_tuple_dst['tile']);\n var u_tile = index_to_tile(punit['tile']);\n\n anim_tuple_dst['i'] = anim_tuple_dst['i'] - 1;\n\n var i = Math.floor((anim_tuple_dst['i'] + 2 ) / 3);\n\n var r = map_to_gui_pos( src_tile['x'], src_tile['y']);\n var src_gx = r['gui_dx'];\n var src_gy = r['gui_dy'];\n\n var s = map_to_gui_pos(dst_tile['x'], dst_tile['y']);\n var dst_gx = s['gui_dx'];\n var dst_gy = s['gui_dy'];\n\n var t = map_to_gui_pos(u_tile['x'], u_tile['y']);\n var punit_gx = t['gui_dx'];\n var punit_gy = t['gui_dy'];\n\n var gui_dx = Math.floor((dst_gx - src_gx) * (i / ANIM_STEPS)) + (punit_gx - dst_gx);\n var gui_dy = Math.floor((dst_gy - src_gy) * (i / ANIM_STEPS)) + (punit_gy - dst_gy);\n\n\n if (i == 0) {\n punit['anim_list'].splice(0, 1);\n if (punit['anim_list'].length == 1) {\n punit['anim_list'].splice(0, 1);\n }\n } \n\n\n offset['x'] = - gui_dx ;\n offset['y'] = - gui_dy;\n\n\n } else {\n offset['x'] = 0;\n offset['y'] = 0;\n anim_units_count -= 1;\n }\n return offset;\n}",
"function getEasternOffset() {\r\n return 300;\r\n }",
"getDistance(){\n\t\tif(this.TargetPlanet!== null){\n\t\t\treturn Math.abs(this.Group.position.y - this.TargetPlanet.y);\n\t\t}\n\t\telse return 0;\n\t}",
"get positionTargetConfig() {\n const { viewHeight, viewWidth, viewOffsetTop, viewOffsetLeft } = this.viewAreaInfo;\n let left;\n let top;\n if (this.fullScreen) { /* keep it for caching only to not break other algorithms */\n return {\n rect: {\n top: 0,\n bottom: 0,\n left: 0,\n right: 0,\n height: viewHeight,\n width: viewWidth\n },\n position: [['center', 'middle']]\n };\n }\n if (this.positionTarget instanceof HTMLElement) {\n const positionTargetElRect = this.positionTarget.getBoundingClientRect();\n return {\n rect: {\n top: positionTargetElRect.top - viewOffsetTop,\n right: positionTargetElRect.right - viewOffsetLeft,\n bottom: positionTargetElRect.bottom - viewOffsetTop,\n left: positionTargetElRect.left - viewOffsetLeft,\n width: positionTargetElRect.width,\n height: positionTargetElRect.height\n },\n position: [...(this.positionStrategy || DEFAULT_TARGET_STRATEGY)]\n };\n }\n const x = this.x || 0;\n const y = this.y || 0;\n let positionTarget = `${typeof this.x === 'number' && this.x >= 0 ? 'left' : 'center'} ${typeof this.y === 'number' && this.y >= 0 ? 'top' : 'center'}`;\n if (typeof this.positionTarget === 'string') {\n positionTarget = this.positionTarget.trim() || positionTarget;\n const positionTargetList = positionTarget.split(' ').slice(0, 2);\n if (positionTargetList.length === 1) {\n positionTargetList.push('center');\n }\n positionTarget = positionTargetList.join(' ');\n }\n let defaultPosition;\n /* istanbul ignore next */\n switch (positionTarget) {\n case 'top left':\n case 'left top':\n left = x;\n top = y;\n defaultPosition = ['bottom', 'start'];\n break;\n case 'top center':\n case 'center top':\n left = viewWidth / 2 + x;\n top = y;\n defaultPosition = ['bottom', 'middle'];\n break;\n case 'top right':\n case 'right top':\n left = viewWidth - x;\n top = y;\n defaultPosition = ['bottom', 'end'];\n break;\n case 'center left':\n case 'left center':\n left = x;\n top = viewHeight / 2 + y;\n defaultPosition = ['right', 'middle'];\n break;\n case 'center right':\n case 'right center':\n left = viewWidth - x;\n top = viewHeight / 2 + y;\n defaultPosition = ['left', 'middle'];\n break;\n case 'bottom left':\n case 'left bottom':\n left = x;\n top = viewHeight - y;\n defaultPosition = ['top', 'start'];\n break;\n case 'bottom center':\n case 'center bottom':\n left = viewWidth / 2 + x;\n top = viewHeight - y;\n defaultPosition = ['top', 'middle'];\n break;\n case 'bottom right':\n case 'right bottom':\n left = viewWidth - x;\n top = viewHeight - y;\n defaultPosition = ['top', 'end'];\n break;\n case 'center center':\n default:\n left = viewWidth / 2 + x;\n top = viewHeight / 2 + y;\n defaultPosition = ['center', 'middle'];\n }\n return {\n rect: {\n top,\n bottom: top,\n left,\n right: left,\n height: 0,\n width: 0\n },\n position: [...(this.positionStrategy || [defaultPosition])]\n };\n }",
"function offsets() {\n var offsets = ($attrs.mdOffset || '0 0').split(' ').map(parseFloat);\n if (offsets.length == 2) {\n return {\n left: offsets[0],\n top: offsets[1]\n };\n } else if (offsets.length == 1) {\n return {\n top: offsets[0],\n left: offsets[0]\n };\n } else {\n throw Error('Invalid offsets specified. Please follow format <x, y> or <n>');\n }\n }",
"absolute() {\n this.incrementPc();\n let lo = this.ram[this.cpu.pc];\n this.incrementPc();\n let hi = this.ram[this.cpu.pc];\n\n return hi * 0x0100 + lo;\n }",
"function getVerticalSectionOffset( targetID ) {\n\t\tdocument.getElementById( targetID ).scrollIntoView( );\n\t\t\n\t\treturn window.pageYOffset;\n\t}",
"function calculateOffset(){\n const tableCell = document.getElementById('0');\n \n const htmlBoard = document.getElementById('board');\n // a table's border spacing will be a string w/ pixel value or 2px by default \n const borderSpacing = parseFloat(htmlBoard.style.borderSpacing) || 2;\n const topOffset = htmlBoard.offsetTop + borderSpacing + tableCell.offsetTop;\n\n // an offset is the combined size of border+padding+margin\n // for a table's cells/tiles, it's that + the table's border-spacing\n const tileOffset = tableCell.offsetHeight + borderSpacing;\n \n\n return {topOffset, tileOffset};\n}",
"function delta_index(start, current) {\n return {left: current.left - start.left, top: current.top - start.top};\n}",
"yOffset() {\n const minY = -this.h/2;\n let maxY = -this.requiredHeight + this.h/2;\n if(this.requiredHeight <= this.h) {\n maxY = minY;\n }\n\n return this.scrollPos * (maxY - minY);\n }",
"static get defaultContactOffset() {}",
"function getScrollOffset() {\n return {\n x: main.scrollLeft,\n y: main.scrollTop };\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME : checkObjectArray AUTHOR : James Turingan DATE : December 5, 2013 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : check if the device is already exist in the array PARAMETERS : path,myArray | function checkObjectArray(path,myArray,type){
var flag = false;
if(type != 'device'){
for(var t=0; t<myArray.length; t++){
if(myArray[t].ObjectPath == path){
flag = true;
break;
}
}
}else{
for(var t=0; t<myArray.length; t++){
if(myArray[t].DeviceName == path){
flag = true;
break;
}
}
}
return flag;
} | [
"static #checkIfObjectIsFound(array) {\n\n\t\t// Check if input is defined.\n\t\tif (!array) {\n\t\t\treturn console.log(`${array} is undefined or null.`)\n\t\t}\n\n\t\treturn array.length !== 0;\n\t}",
"static isExistInArray(arr, value, index=0){\n\t\tif( typeof arr === 'object'){\n\t\t\tlet arrList = [];\n\t\t\tforEach( arr, (item, key) => {\n\t\t\t\tif(item.id){\n\t\t\t\t\tarrList.push(item.id);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif(indexOf(arrList, value, index) >= 0){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}",
"function verifyIfExists(data, array) {\n //If the given data is an array\n if (data.constructor === Array) {\n // console.log(data);\n // console.log(array);\n\n let count = 0;\n\n //Verifies if any of the data content is equal to the data in the given array\n for (let i = 0; i < data.length; i++) {\n for (let j = 0; j < array.length; j++) {\n if (typeof(data[i]) == \"object\" && typeof(array[j]) == \"object\") {\n if (data[i].name == array[j].name) {\n count++;\n }\n }\n else if (typeof(data[i]) == \"string\" && typeof(array[j]) == \"object\") {\n if (data[i] == array[j].name) {\n count++;\n }\n }\n else if (typeof(data[i]) == \"string\" && typeof(array[j]) == \"string\") {\n if (data[i] == array[j]) {\n count++;\n }\n }\n else if (data[i].name == array[j]) {\n count++;\n }\n }\n }\n if (count == data.length) {\n return true;\n }\n else {\n return false;\n }\n }\n //If the given data is not an array\n else {\n \n for (let i = 0; i < array.length; i++) {\n if (typeof(array[i]) == \"object\" && array[i].name == data) {\n return true;\n }\n else if (array[i] == data) {\n return true;\n }\n \n }\n return false;\n }\n}",
"function addUnique(array, object) {\n for(var i in array) {\n if(array[i]==object) {\n return false;\n }\n }\n\n array[array.length] = object;\n return true;\n }",
"function verificaArray (elemento, array) {\r\n var inclusoArray = false;\r\n\r\n for (var count = 0; count < array.length; count++) {\r\n if (elemento === array[count]) {\r\n inclusoArray = true;\r\n }\r\n }\r\n\r\n return inclusoArray;\r\n}",
"function checkDeviceIfExist(devName,type){\n\tvar myReturn = false;\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tif(devName == \"\"){\n\t\tfor(var a=0; a < window['variable' + dynamicLineConnected[pageCanvas]].length;a++){\n\t\t\tif(pageCanvas == window['variable' + dynamicLineConnected[pageCanvas]][a].Page){\n\t\t\t\tmyReturn = true;\n\t\t\t}\n\t\t}\t\n\t}else{\n\t\tfor(var a=0; a<devices.length;a++){\n\t\t\tif (devName == devices[a].DeviceName && type != \"createdev\"){\n\t\t\t\tmyReturn = true;\n\t\t\t}else if(devName == devices[a].DeviceName && type == \"createdev\"){ \n\t\t\t\tmyReturn = true;\n\t\t\t}\t\n\t\t}\n\t}\n\treturn myReturn;\n}",
"function in_array(variable, theArray)\n{\n\tfor (var i in theArray)\n\t\tif (theArray[i] == variable)\n\t\t\treturn true;\n\n\treturn false;\n}",
"function IfUniqueAddItemToArray(item, arrayToCheck) {\n var count = arrayToCheck.length;\n var foundItem = false;\n\n // Look through the entire array and see if the item already exists\n for (var i = 0; i < count; i++) {\n\n // Check if the item is in the array (case insensitive)\n // This means that 'DogG' is the same as 'dogg'\n if (arrayToCheck[i].toLowerCase() == item.toLowerCase()) {\n foundItem = true;\n }\n }\n\n // If we did not find the item, add it to the array\n // arrayToCheck is an array\n // push the item onto the end of the array using arrayToCheck.push(item)\n if (!foundItem) {\n arrayToCheck.push(item);\n }\n}",
"function in_array(val, array) {\n\t\tfor(var i = 0, l = array.length; i < l; i++) {\n\t\t\tif(array[i] == val) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"function isDeviceExisted(dev_id, devices) {\n\tfor (var i in devices)\n\t{\n\t\tif(devices[i].deviceID == dev_id)\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}",
"function checkIfVehicleExists(vehicle, array) {\n for (var i = 0; i < array.length; i++) {\n if (vehicle.shortIdentifier == array[i].shortIdentifier) {\n return i;\n }\n }\n return -1;\n}",
"function tileIdExistsInArray(tileId, array) {\n\t\tfor (var i = 0; i < array.length; i++) {\n\t\t\tvar nextTileId = array[i].attr(\"id\");\n\t\t\tif (tileId == nextTileId) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n}",
"function getHasDevNameOnArray(){\n\tvar str =[];\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var a=0; a<devices.length; a++){\n\t\tif (devices[a].DeviceName!=\"\"){\n\t\t\tvar name = devices[a].DeviceName;\n\t\t\tstr.push(name);\n\t\t}\t\n\t}\n\treturn str;\n}",
"function isin(element, array) {\n\n var output = false;\n\n for (var i = 0; i <= array.length; i++) {\n\n if (element == array[i]) {\n\n output = true;\n\n }\n\n }\n\n return output;\n\n }",
"function isInArray(x,y)\n{\n\tvar counter = 0;\n\n\tfor (var i = 0; i < x.length; i++) \n\t{\n\t\tif(x[i] === y)\n\t\t{\n\t\t\tcounter++;\n\t\t}\n\t}\n\n\tif(counter === 0)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn true;\n\t}\n}",
"function arrayContains(arr, obj){\n \tfor (var i=0; i < arr.length; i++){\n \t\tif (arr[i] == obj){\n \t\t\treturn i;\n \t\t}\n \t}\n \treturn false;\n }",
"function includes(item, anArray) {\r\n\r\n for (let i = 0; i < anArray.length; i++) {\r\n if (anArray[i] == item) {\r\n return true;\r\n } \r\n }\r\n return false;\r\n}",
"function duplicationCheck(arrToCheck, phone, email) {\n if (arrToCheck.find((contact) => contact.phone === phone)) {\n alert(\"Contact with this PHONE NUMBER already exists!\");\n return true;\n }\n\n if (arrToCheck.find((contact) => contact.email === email)) {\n alert(\"Contact with this EMAIL already exists!\");\n return true;\n }\n\n return false;\n}",
"function validateArrayValueUnique (arr){\r\n var i = 0, j = 0;\r\n while (undefined !== arr[i]){\r\n j = i + 1;\r\n while(undefined !== arr[j]){\r\n if (arr[i] == arr[j]) {\r\n return false;\r\n }\r\n ++j;\r\n }\r\n ++i;\r\n }\r\n return true;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Choosing based on the number of variants and equal distribution | function getVariantURL(variants) {
let distribution = new Array(variants.length).fill(Number((1/variants.length).toFixed(2)))
const rand = (Math.random() * (variants.length - 1)).toFixed(2)
let acc = 0
distribution = distribution.map(weight => (acc = acc + weight))
return variants[distribution.findIndex(priority => priority > rand)]
} | [
"getRandomSolution() {\n var sol = []\n for (let g = 0; g < this.genesCount; g++) {\n // 0 or 1 randomly\n sol.push(Math.round(Math.random()))\n }\n\n return sol;\n }",
"rank_Selection() {\n // generate ranks (n, n-1, n-2, n-3, .., 1)\n var ranks = [...Array(this.solutionsCount).keys()].map(n => n + 1).reverse();\n var sumRank = ranks.reduce((a, b) => a + b);\n\n // random point on the circle (random sum) \n var randomPoint = Math.random() * sumRank;\n\n var currentSum = 0;\n\n // Loop through solutions and add their sum\n for (let s = 0; s < this.solutionsCount; s++) {\n // add sum of the current solution\n currentSum += ranks[s];\n\n // if currenSum exceed the random sum -> select solution\n if (currentSum > randomPoint) {\n return this.population[s];\n }\n }\n\n // return the first solution otherwise\n return this.population[0];\n }",
"rouletteWheel_Selection() {\n // Total sum of fitness values\n let sumFitness = this.fitness_values.reduce((a, b) => a + b);\n\n // random point on the circle (random sum) \n var randomPoint = Math.random() * sumFitness;\n\n var currentSum = 0;\n // Loop through solutions and add their sum\n for (let s = 0; s < this.solutionsCount; s++) {\n // add sum of the current solution\n currentSum += this.fitness_values[s];\n\n // if currenSum exceed the random sum -> select solution\n if (currentSum > randomPoint) {\n return this.population[s];\n }\n }\n\n // return the first solution otherwise\n return this.population[0];\n }",
"function test(number) {\n for (let i = 0; i < number; i++) {\n const result = findOptimalStrategiesSet(strategiesArr);\n console.log('result', result);\n }\n return _.sum(times)/times.length;\n}",
"CHANGE_PRICES(state) {\n // use a forEach() because it's an array\n // otherwise if it was an object you'd for(x in y)\n state.stocks.forEach(stock => {\n // doesn't make sense for the volatility to vary between a large range,\n // so it should only be a growth or shrinkage of the original price\n const min = 0.85\n const max = 1.15\n // the tried and true rand * (max - min) + min range calculation\n stock.pps = Math.round(stock.pps * (Math.random() * (max - min) + min))\n })\n }",
"findRelatedProbabilities(values) {\n const sampleProbabilities = this.props.sampleProbabilities;\n const sortedValues = values.sort();\n const added = new Set();\n var results = [];\n\n for(let i = 0, j = 0; i < sortedValues.length && j < sampleProbabilities.length - 1;) {\n const last = parseFloat(sampleProbabilities[j].probability);\n const next = parseFloat(sampleProbabilities[j+1].probability);\n const value = sortedValues[i];\n\n if(last <= value && value < next) { // we want to add last and next, if not added\n if(!added.has(j)) {\n results.push(sampleProbabilities[j])\n added.add(j);\n }\n if(!added.has(j+1)) {\n results.push(sampleProbabilities[j+1]);\n added.add(j+1);\n }\n i++;\n } else {\n j++;\n }\n }\n return results;\n }",
"function Topicsel (sTopic)\r\n {\r\n // scan array of question objects starting at gnQtop because questions\r\n // that have been selected already do not need to be re-scanned\r\n for (i=gnQtop; i<gaoQ.length; i++) \r\n {\r\n\t // Check topic and consider inclusion probability setting\r\n\t if (gaoQ[i].id.indexOf(sTopic)>-1 && Math.random()<(0.000001+gaoQ[i].p))\r\n \t {\r\n\t\t // If question qualifies move it to random position with already selected\r\n\t\t // questions to create different order of questions for each new session\r\n\t\t gaoQ.splice(Math.round((gnQtop+1)*Math.random()-0.5),0,gaoQ[i]);\r\n\t\t gaoQ.splice(i+1,1);\r\n\t\t gnQtop+=1;\t \r\n\t\t }\r\n\t }\r\n }",
"function probabilityGenerator(n, probabilities){\n //plan\n // generate a random int between 0 and 100\n // if int is probability[i] + all previous proababilies times 10\n // return n[i]\n\n}",
"function randomize() {\n var x;\n var y;\n var randNum; //only allow 30% of the grid to be generated with alive organisms\n\n for(x = 0; x < rows; x++) {\n for(y = 0; y < rows; y++) {\n\n randNum = Math.random();\n state[x][y] = Math.round(Math.random());\n\n if(state[x][y] === 1 && randNum > .7) {\n gridScheme[x][y].checked = true;\n }\n }\n }\n}",
"function getSpec(){\n specNum = Math.floor(Math.random()*speciesA.length);\n \n }",
"function isThereEnoughChocolateBags(small, big, total){\n const maxBigBoxes = total / 5;\n const bigBoxesWeCanUse = maxBigBoxes < big ? maxBigBoxes : big;\n total -= bigBoxesWeCanUse * 5;\n\n if(small < total)return false;\n else return true;\n}",
"function decide(state) {\n const plans = generatePlans(state).map(plan => [plan, scorePlan(state, plan)])\n const sorted = plans.sort((p1, p2) => {\n const s1 = p1[1]\n const s2 = p2[1]\n return s1 < s2 ? 1 : s2 < s1 ? -1 : 0\n })\n console.log(plans\n .filter((p, i) => i < 3)\n .map(([plan, score]) => `score: ${score} - ${plan.type.toString()}: ${JSON.stringify(plan.data)}`).join('\\n'))\n return sorted[0][0]\n}",
"function Eval_choose(p1) {\n const N = eval_1.Eval(defs_1.cadr(p1));\n const K = eval_1.Eval(defs_1.caddr(p1));\n const result = choose(N, K);\n stack_1.push(result);\n}",
"function choose(x, y) /* forall<a> (x : a, y : a) -> ndet a */ {\n return (random_bool()) ? x : y;\n}",
"async function _filter_for_sizes (variants, sizes){\n let ret = [];\n \n /*\n * If both sizes aren't defined, return everything (not ideal I know but until\n * we settle down regarding product types this is the least terrible option)\n */\n \n if (!sizes.top || !sizes.bottom){\n return variants;\n }\n \n for (let i = 0; i < variants.length; i++){\n // if a recognised 'top' type\n if (_product_type_tops.includes(variants[i].product_type)){\n // check for multiple sizes in sizes.top\n if (!Array.isArray(sizes.top)){\n // if a single size then push all variants with a size that matches\n if(variants[i].opt2 == sizes.top){\n ret.push(variants[i]);\n }\n }else if (sizes.top.includes(variants[i].opt2)){\n // else if array of sizes then check array for matchinf size and push\n ret.push(variants[i]);\n }\n // else if a recognised 'bottom' type....same again\n }else if (_product_type_bottoms.includes(variants[i].product_type)){\n if (!Array.isArray(sizes.bottom)){\n if(variants[i].opt2 == sizes.bottom){\n ret.push(variants[i]);\n }\n }else if (sizes.bottom.includes(variants[i].opt2)){\n ret.push(variants[i]);\n }\n // else if misc product type e.g hats, accessories etc.\n }else if (_product_type_misc.includes(variants[i].product_type)){\n // if size is One Size Fits All, then push\n if (variants[i].opt2 == 'OSFA'){\n ret.push(variants[i]);\n }\n \n // TODO: need to do better for socks and other misc items - map sizes\n }\n }\n\n return ret;\n}",
"function greedyStrategy(items, capacity) {\n let changed = false;\n const possibleItems = items;\n let weight = 0;\n const inventory = {\n selectedItems: [],\n totalCost: 0,\n totalValue: 0, \n };\n\n console.log(\"Capacity is: \", capacity);\n\n // sort the array by value/size ratio score\n possibleItems.sort(function(a, b) {\n return parseFloat(b.score) - parseFloat(a.score);\n });\n\n for(let i = 0; weight <= capacity && i < possibleItems.length; i++) {\n weight += possibleItems[i].size;\n if(weight <= capacity){\n inventory.selectedItems.push(possibleItems[i].index);\n inventory.totalCost = weight;\n inventory.totalValue += possibleItems[i].value;\n } else{\n weight -= possibleItems[i].size;\n }\n }\n\n console.log(\"\\nInventory to GREED: \\nItems to select: \", inventory.selectedItems, \"\\nTotal cost: \", inventory.totalCost, \"\\nTotal value: \", inventory.totalValue)\n\n return inventory;\n}",
"changeRandomWeight(){\n\t\tvar i = Math.floor(Math.random() * this.genes.length)\n\n\t\t//we can only use an available gene\n\t\tif (this.genes[i] != null){\n\t\t\tthis.genes[i].weigth = (Math.random() * 2) - 1 //betwenn -1 and 1\n\t\t} else {\n\t\t\tthis.changeRandomWeight()\n\t\t}\n\t}",
"function p3c(availableObjects, loadOf) {\n assert.arrayOfObject(availableObjects, 'availableObjects');\n assert.func(loadOf, 'loadOf');\n\n var n = availableObjects.length;\n\n var best = null;\n\n if (n < 3) {\n var bestAvailability = -1.0;\n _.forEach(availableObjects, function (obj) {\n if (loadOf(obj) > bestAvailability) {\n best = obj;\n bestAvailability = loadOf(obj);\n }\n });\n return best;\n }\n\n var obj1 = null;\n var obj2 = null;\n var obj3 = null;\n var objects = [];\n\n for (var e = 0; e < 5; e++) {\n // i1, i2 and i3 are 3 *different* random numbers in [0, n]\n var i1 = Math.floor(Math.random() * n);\n var i2 = Math.floor(Math.random() * (n - 1));\n var i3 = Math.floor(Math.random() * (n - 2));\n\n if (i2 >= i1) {\n i2++;\n\n if (i3 >= i1) {\n i3++;\n }\n\n if (i3 >= i2) {\n i3++;\n }\n } else {\n if (i3 >= i2) {\n i3++;\n }\n\n if (i3 >= i1) {\n i3++;\n }\n }\n\n obj1 = availableObjects[i1];\n obj2 = availableObjects[i2];\n obj3 = availableObjects[i3];\n objects.push(obj1);\n objects.push(obj2);\n objects.push(obj3);\n\n if (obj1 && obj1.availability() > 0\n && obj2 && obj2.availability() > 0\n && obj3 && obj3.availability() > 0) {\n break;\n }\n }\n\n var bestLoad = -1;\n _.forEach(objects, function (obj) {\n if (loadOf(obj) > bestLoad) {\n best = obj;\n bestLoad = loadOf(obj);\n }\n });\n return best;\n}",
"function getCompChoice(){\n cChoice = cChoiceArray[Math.floor(Math.random()* 3)]\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LLAMADO desde el Panel cada vez que se presiona al boton Modificar | function fModificar(){
//FRMPanel.fSetTraStatus("UpdateBegin");
fDisabled(false,"iEjercicio,");
FRMListado.fSetDisabled(true);
} | [
"function mostrarPanelDesdeModal() {\n checarDesdeModal();\n\n setTimeout(function() {\n console.log(privilegio);\n\n if(puesto == privilegio) { //si el puesto es igual, significa que ingresaste bien tu puesto\n if(privilegio == \"Administrador\") { //si el privilegio es Administrador te muestra el panel de admin\n let div = '<div id=\"holder\" class=\"row\" ></div>';\n\n $('#CalendarioUsuario').remove();\n $('#CalendarioAdmin').append(div);\n $('#panel-usuario').hide();\n $('#mainNav').show();\n $(\"title\").html(\"Panel de administrador\");\n $('#panel-admin').show();\n $('#modal').modal('hide');\n }\n if(privilegio == \"Usuario\") { //si el privilegio es Usuario normal te lleva al panel de usuario\n let div = '<div id=\"holder\" class=\"row\" ></div>';\n\n $('#CalendarioAdmin').remove();\n $('#CalendarioUsuario').append(div);\n $('#panel-admin').hide();\n $('#panel-usuario').show();\n $('title').html(\"Panel de usuario\");\n $('#modal').modal('hide');\n }\n }\n else {\n $('#error').html('Tu puesto es incorrecto').show(); //si ingresaste mal el puesto te muestra un error\n setTimeout(function() {\n $('#error').fadeOut(\"slow\").hide();\n }, 2000);\n }\n }, 2000);\n}",
"function fNuevo(){\n //FRMPanel.fSetTraStatus(\"UpdateBegin\");\n fBlanked();\n fDisabled(false,\"iEjercicio,\",\"--\");\n FRMListado.fSetDisabled(true);\n }",
"function fGuardar(){\n if(fValidaTodo()==true){\n if(fNavega()==true){\n //FRMPanel.fSetTraStatus(\"UpdateComplete\");\n fDisabled(true);\n FRMListado.fSetDisabled(false);\n }\n }\n }",
"function fGuardarA(){\n if(fValidaTodo()==true){\n if(fNavega()==true){\n //FRMPanel.fSetTraStatus(\"UpdateComplete\");\n fDisabled(true);\n FRMListado.fSetDisabled(false);\n }\n }\n }",
"function ingresarDescripcion(componente){\n\t//Oculta el popUp Anterior y lo cierra\n\t$(panelReclamos).hide();\n\t$(panelReclamos).dialog(\"close\");\n\t//Remueve los hijso del panel de descripcion\n\tvar cell = document.getElementById(\"panelDescripcion\");\n\tif ( cell.hasChildNodes() ){\n\t\twhile ( cell.childNodes.length >= 1 ){\n\t\t\tcell.removeChild( cell.firstChild );\n\t\t}\n\t}\n\n\t//Crear el contenido del popUP\n\tvar textArea = $(\"<textarea></textarea>\").attr(\"class\",\"form-control\");\n\ttextArea.attr(\"type\",\"textarea\");\n\ttextArea.attr(\"name\",\"message\");\n\ttextArea.attr(\"id\",\"txtDescripcion\");\n\ttextArea.attr(\"placeholder\",\"Escriba su mensaje aquí.\");\n\ttextArea.attr(\"maxlength\",\"500\");\n\ttextArea.attr(\"rows\",\"7\");\n\tvar lblText = $(\"<label></label>\").text(\"Escriba una descripcion de su reclamo (máx 500 caracteres)\");\n\tlblText.attr(\"for\",\"name\");\n\tvar divisor = $(\"<div></div>\").attr(\"class\",\"box-content\");\n\tvar divGroup = $(\"<div></div>\").attr(\"class\",\"form-group\");\n\tdivGroup.append(lblText);\n\tdivGroup.append(divisor);\n\tdivGroup.append(textArea);\n\tvar btnEnviar = $(\"<button></button>\").text(\"Enviar Reclamo →\");\n\tbtnEnviar.attr(\"type\",\"submit\");\n\tbtnEnviar.attr(\"class\",\"btn btn-lg btn-success btn-block\");\n\tbtnEnviar.click(function(){\n\t\tguardarReclamo(componente, latitud, longitud);\n\t});\n\tvar divBody\t= $(\"<div></div>\").attr(\"class\",\"modal-body\");\n\tdivBody.append(divGroup);\n\tdivBody.append(btnEnviar);\n\tvar titulo = $(\"<h4></h4>\").text(\"Describa su Reclamo:\");\n\ttitulo.attr(\"class\",\"modal-title\");\n\tvar divHeader = $(\"<div></div>\").attr(\"class\",\"modal-header\");\n\tdivHeader.append(titulo);\n\tvar divContent = $(\"<div></div>\").attr(\"class\",\"modal-content\");\n\tdivContent.append(divHeader);\n\tdivContent.append(divBody);\n\n\t$(panelDescripcion).append(divContent);\n\n\t//Crear el popUp\n\t$(panelDescripcion).dialog({\n\t\tcloseText: 'X'\n\t});\n\t//Muestra el popUp\n\t$(panelDescripcion).show();\n}",
"function OptionPanel(Opc) {\n\n Campo = Opc;\n\n switch (Opc) {\n\n case \"C\":\n $(\"#block_search_GA\").css(\"display\", \"none\");\n $(\"#Block_Insert_GA\").css(\"display\", \"block\");\n $(\"#Bloque_estado\").css(\"display\", \"none\");\n $(\"#BtnSave\").attr(\"value\", \"Crear\");\n $(\"#TxtGrupo_ID\").removeAttr(\"disabled\");\n $(\"#Select_Pais\").parent().find(\"input.ui-autocomplete-input\").autocomplete(\"option\", \"disabled\", false).prop(\"disabled\", false);\n $(\"#Select_Pais\").parent().find(\"a.ui-button\").button(\"enable\");\n $('#Select_Pais').siblings('.ui-combobox').find('.ui-autocomplete-input').val('Seleccione...');\n\n Estado_Process = \"C\";\n $(\"#Tab_GrupoActividad\").tabs({ disabled: false });\n Clear();\n break;\n\n case \"R\":\n $(\"#block_search_GA\").css(\"display\", \"block\");\n $(\"#Block_Insert_GA\").css(\"display\", \"none\");\n Estado_Process = \"R\";\n break;\n\n case \"U\":\n $(\"#block_search_GA\").css(\"display\", \"block\");\n $(\"#Block_Insert_GA\").css(\"display\", \"none\");\n Estado_Process = \"U\";\n break;\n\n case \"D\":\n $(\"#block_search_GA\").css(\"display\", \"block\");\n $(\"#Block_Insert_GA\").css(\"display\", \"none\");\n Estado_Process = \"D\";\n break;\n\n }\n}",
"function ocultarPanelJuego(){\n\tvar panel = document.getElementById(\"panel\");\n\tpanel.classList.add(\"invisible\");\n}",
"function cargarCgg_dhu_preguntaCtrls(){\n if(inRecordCgg_dhu_pregunta){\n tmpCdcat_codigo =inRecordCgg_dhu_pregunta.get('CDCAT_CODIGO');\n cbxCdcat_codigo.setValue(inRecordCgg_dhu_pregunta.get('CDCAT_NOMBRE'));\n gsCgg_dhu_pregunta.reload({\n params:{\n inCdcat_codigo:tmpCdcat_codigo,\n format:TypeFormat.JSON\n }\n\n });\n isEdit = true;\n habilitarCgg_dhu_preguntaCtrls(true);\n }}",
"function abre_modal_alterar_senha(){\r\n\r\n\t_START('abre_modal_alterar_senha');\r\n\tvar funCallBack\t=\tfunction(data)\r\n\t{\r\n\t\t_START('callbackabre_modal_alterar_senha');\r\n\t\t\r\n\t\t\t$('.modal-content-grid').html(data);\r\n\t\t\t$('.grid_alterar_senha #extraValues').val('');\r\n\t\t\twrs_window_grid_events_tools({btn:btn_window_grid_event_admin});\r\n\t\t\t\r\n\t\t_END('callbackabre_modal_alterar_senha');\t\r\n\t};\r\n\t\r\n\t$('#myModal').modal('show');\r\n\r\n\tgrid_window_modal(\r\n\t\t\t\t{\t\r\n\t\t\t\t\t'wrs_type_grid'\t:\t\t'form',\r\n\t\t\t\t\t'form_event'\t:\t\t'changePassword',\r\n\t\t\t\t\t'extraValues'\t: \t\t'self'\r\n\t\t\t\t},\r\n\t\t\t\tnull,\r\n\t\t\t\tfunCallBack);\r\n\t_END('abre_modal_alterar_senha');\t\r\n\t\r\n}",
"loadFormPuntos(){\n document.getElementById(\"content-right\").innerHTML = formulario;\n document.getElementById(\"boton_add_item\").addEventListener('click',function(){\n var name = document.getElementById(\"PointName\").value;\n var coordx= document.getElementById(\"PointX\").value;\n var coordy= document.getElementById(\"PointY\").value;\n var coordz= document.getElementById(\"PointZ\").value;\n var type= document.getElementById(\"Tipo\").value;\n var token= localStorage.getItem(\"token\");\n servicio_API.crearPunto(name,coordx,coordy,coordz,type,token).then(() => obtenerPuntos(0));\n })\n document.getElementById(\"boton_update_item\").addEventListener('click',function(){\n var id = document.getElementById(\"PointID\").value;\n var name = document.getElementById(\"PointName\").value;\n var coordx= document.getElementById(\"PointX\").value;\n var coordy= document.getElementById(\"PointY\").value;\n var coordz= document.getElementById(\"PointZ\").value;\n var type= document.getElementById(\"Tipo\").value;\n var token= localStorage.getItem(\"token\");\n servicio_API.actualizaPunto(id,name,coordx,coordy,coordz,type,token).then(() => obtenerPuntos(0));\n \n })\n }",
"function modificaTipoRegistrazioneIva() {\n var selectedOption = $(this).find(\"option:selected\");\n var selectedEsigibilita = selectedOption.data(\"tipoEsigibilitaIva\");\n var divs = $(\"#gruppoProtocolloProvvisorio, #gruppoProtocolloDefinitivo\");\n var divProvvisorio = $(\"#gruppoProtocolloProvvisorio\");\n var divDefinitivo = $(\"#gruppoProtocolloDefinitivo\");\n var regexDifferita = /DIFFERITA/;\n var regexImmediata = /IMMEDIATA/;\n\n if (regexDifferita.test(selectedEsigibilita) && !divProvvisorio.is(\":visible\")) {\n // Se ho selezionato il valore 'DIFFERITO' e il div e' ancora chiuso, lo apro\n divs.slideUp();\n divProvvisorio.slideDown();\n } else if (regexImmediata.test(selectedEsigibilita) && !divDefinitivo.is(\":visible\")) {\n // Se ho selezionato il valore 'IMMEDIATO' e il div e' ancora chiuso, lo apro\n divs.slideUp();\n divDefinitivo.slideDown();\n } else if (!selectedEsigibilita) {\n // Se non ho selezionato null, chiudo i div\n divs.slideUp();\n }\n // Se i div sono gia' aperti, non modifico nulla\n }",
"function modulemodify_response(req)\n{\n if (!req.isSuccess()) {\n Zikula.showajaxerror(req.getMessage());\n showinfo();\n return;\n }\n\n var data = req.getData();\n\n // check for modules internal error\n if(data.error == 1) {\n showinfo();\n Element.addClassName($('moduleinfo_' + data.id), 'z-hide');\n Element.removeClassName($('modulecontent_' + data.id), 'z-hide');\n\n /*\n // add events\n Event.observe('modifyajax_' + data.id, 'click', function(){modulemodifyinit(data.id)}, false);\n Event.observe('moduleeditsave_' + data.id, 'click', function(){modulemodify(data.id)}, false);\n Event.observe('moduleeditdelete_' + data.id, 'click', function(){moduledelete(data.id)}, false);\n Event.observe('moduleeditcancel_' + data.id, 'click', function(){modulemodifycancel(data.id)}, false);\n enableeditfields(data.id);\n */\n Zikula.showajaxerror(data.message);\n setmodifystatus(data.id, 0);\n modulemodifyinit(data.id);\n\n // refresh view/reload ???\n return;\n }\n\n $('enablelang_' + data.id).value = data.enablelang;\n\n Element.update('modulename_' + data.id, data.modname);\n Element.update('modulenavtype_' + data.id, data.navtype_disp);\n Element.update('moduleenablelang_' + data.id, data.enablelang_disp);\n Element.update('moduleexempt_' + data.id, data.exempt_disp);\n\n adding = adding.without(data.id);\n\n // show trascan icon for new moduless if necessary\n Element.removeClassName('moduleeditcancel_' + data.id, 'z-hide');\n // update delete icon to show trashcan icon\n Element.update('moduleeditdelete_' + data.id, deleteiconhtml);\n\n setmodifystatus(data.id, 0);\n showinfo(data.id);\n}",
"function ModConfirmSave(mode) {\n console.log(\" --- ModConfirmSave --- \");\n console.log(\"mode: \", mode);\n console.log(\"mod_dict: \", mod_dict);\n\n // mode : \"save\" \"reject\", \"remove\"\n// --- Upload Changes\n if (mod_dict.mode === \"check_birthcountry\"){\n const may_edit = (permit_dict.permit_crud && permit_dict.requsr_same_school);\n if(may_edit){\n const upload_dict = {\n mode: mod_dict.mode,\n table: \"student\"\n };\n UploadChanges(upload_dict, urls.url_change_birthcountry);\n };\n\n } else if([\"prelim_ex5\", \"prelim_ex6\", \"overview\"].includes(mod_dict.mode)){\n const el_modconfirm_link = document.getElementById(\"id_modconfirm_link\");\n if (el_modconfirm_link) {\n el_modconfirm_link.click();\n // show loader\n el_confirm_loader.classList.remove(cls_visible_hide)\n };\n\n } else if(mod_dict.mode === \"withdrawn\"){\n const may_edit = (permit_dict.permit_crud && permit_dict.requsr_same_school);\n if(may_edit){\n const upload_dict = {\n mode: mod_dict.mode,\n table: \"student\",\n student_pk: mod_dict.student_pk,\n withdrawn: mod_dict.withdrawn\n };\n UploadChanges(upload_dict, urls.url_student_upload);\n // --- change icon, before uploading\n // when validation on server side fails, the old value is reset by RefreshDataRowItem PR2022-05-27\n // updated_studsubj_rows must contain ie err_fields: ['has_reex']\n add_or_remove_class(mod_dict.el_input, \"tickmark_1_2\", mod_dict.withdrawn, \"tickmark_0_0\");\n };\n\n } else if(mod_dict.mode === \"gl_status\"){\n const may_edit = (permit_dict.permit_approve_result && permit_dict.requsr_role_insp);\n if (permit_dict.permit_approve_result && permit_dict.requsr_role_insp){\n\n const gl_status = (mode === \"remove\") ? 0 : (mode === \"reject\") ? 2 : 1;\n const upload_dict = {\n mode: mod_dict.mode,\n table: \"student\",\n //student_pk: mod_dict.student_pk,\n student_pk_list: mod_dict.student_pk_list,\n gl_status: gl_status\n };\n UploadChanges(upload_dict, urls.url_approve_result);\n // --- change icon, before uploading\n // when validation on server side fails, the old value is reset by RefreshDataRowItem PR2022-05-27\n // updated_studsubj_rows must contain ie err_fields: ['has_reex']\n add_or_remove_class(mod_dict.el_input, \"tickmark_1_2\", mod_dict.withdrawn, \"tickmark_0_0\");\n };\n };\n// --- hide modal\n $(\"#id_mod_confirm\").modal(\"hide\");\n }",
"function panel_fuel_update(KaTZPit_data){\n\t\n\t// Panneau de gestion fuel et de démarrage APU/Moteur\n\t\n\t\t// Affichage quantité fuel réservoir AV, AR, Total\n\t\tdocument.getElementById('Fuel_AV').innerHTML = KaTZPit_data[\"Fuel_1\"]\n\t\tdocument.getElementById('Fuel_AR').innerHTML = KaTZPit_data[\"Fuel_2\"]\n\t\tdocument.getElementById('Fuel_T').innerHTML = KaTZPit_data[\"Fuel_1\"] + KaTZPit_data[\"Fuel_2\"]\n\t\t\n\n\t\t\t\n\t\t\n\t// Position des Vannes (Fonctionnement des voyants de vannes Droite et Gauche inversé)\n\t// Pour la commande on utilise la commande de type 2 spécifique au KA50\n\t// 3 ordres executes dans DCS ouverturecapot/basculeinter/fermeturecapot\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_V\"],2) ==0) {\n\t\t\t$(\"#F-Vanne-G\").attr('src','images/fuel/FV-Vanne_V_O.gif')\n\t\t\t$(\"#F-Vanne-G\").data('internal-id','20300600')}\n\t\telse {\n\t\t\t$(\"#F-Vanne-G\").attr('src','images/fuel/FV-Vanne_V_F.gif')\n\t\t\t$(\"#F-Vanne-G\").data('internal-id','20300601')}\n\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_V\"],1)==0) {\n\t\t\t$(\"#F-Vanne-D\").attr('src','images/fuel/FV-Vanne_V_O.gif')\n\t\t\t$(\"#F-Vanne-D\").data('internal-id','20300800')}\n\t\telse {\n\t\t\t$(\"#F-Vanne-D\").attr('src','images/fuel/FV-Vanne_V_F.gif')\n\t\t\t$(\"#F-Vanne-D\").data('internal-id','20300801')}\n\t\t\t\n\t\t//if (KaTZPit_data[\"APU_V_Fuel\"] ==1) {\n\t\t//\t$(\"#F-Vanne-APU\").attr('src','images/fuel/FV-Vanne_V_O.gif')\n\t\t//\t$(\"#F-Vanne-APU\").data('internal-id','10301000')}\n\t\t//else {\n\t\t//\t$(\"#F-Vanne-APU\").attr('src','images/fuel/FV-Vanne_V_F.gif')\n\t\t//\t$(\"#F-Vanne-APU\").data('internal-id','10301001')}\n\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_V\"],3) ==1) {\n\t\t\t$(\"#F-Vanne-X\").attr('src','images/fuel/FV-Vanne_H_O.gif')\n\t\t\t$(\"#F-Vanne-X\").data('internal-id','20301200')}\n\t\telse {\n\t\t\t$(\"#F-Vanne-X\").attr('src','images/fuel/FV-Vanne_H_F.gif')\n\t\t\t$(\"#F-Vanne-X\").data('internal-id','20301201')}\n\n\t// Voyant des Cut Off et du frein de Rotor\n\t\tif (dataread_posit(KaTZPit_data[\"COff\"],2) ==1) {\n\t\t\t$(\"#FV-CutOff-G\").attr('src','images/fuel/FV_Cutoff_Off.gif')\n\t\t\t$(\"#FV-CutOff-G\").data('internal-id','10400900')}\n\t\telse {\n\t\t\t$(\"#FV-CutOff-G\").attr('src','images/fuel/FV_Cutoff_On.gif')\n\t\t\t$(\"#FV-CutOff-G\").data('internal-id','10400901')}\n\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"COff\"],1) == 1) {\n\t\t\t$(\"#FV-CutOff-D\").attr('src','images/fuel/FV_Cutoff_Off.gif')\n\t\t\t$(\"#FV-CutOff-D\").data('internal-id','10401000')}\n\t\telse {\n\t\t\t$(\"#FV-CutOff-D\").attr('src','images/fuel/FV_Cutoff_On.gif')\n\t\t\t$(\"#FV-CutOff-D\").data('internal-id','10401001')}\n\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"COff\"],3) == 1) {\n\t\t\t$(\"#FV-RotBrk\").attr('src','images/fuel/FV_RotorBtk_On.gif')\n\t\t\t$(\"#FV-RotBrk\").data('internal-id','10401100')}\n\t\telse {\n\t\t\t$(\"#FV-RotBrk\").attr('src','images/fuel/FV_RotorBtk_Off.gif')\n\t\t\t$(\"#FV-RotBrk\").data('internal-id','10401101')}\n\n\n\t// Fonctionnement des Pompes de Carburant\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_P\"],2) == 1) {\n\t\t\t$(\"#F-Pump-AV\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-AV\").data('internal-id','10300100')}\n\t\telse {\n\t\t\t$(\"#F-Pump-AV\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-AV\").data('internal-id','10300101')}\n\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_P\"],1) ==1) {\n\t\t\t$(\"#F-Pump-AR\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-AR\").data('internal-id','10300200')}\n\t\telse {\n\t\t\t$(\"#F-Pump-AR\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-AR\").data('internal-id','10300201')}\n\t\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_PE\"],3) ==1) {\n\t\t\t$(\"#F-Pump-IL\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-IL\").data('internal-id','10300300')}\n\t\telse {\n\t\t\t$(\"#F-Pump-IL\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-IL\").data('internal-id','10300301')}\n\t\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_PE\"],2) ==1) {\n\t\t\t$(\"#F-Pump-IR\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-IR\").data('internal-id','10300300')}\n\t\telse {\n\t\t\t$(\"#F-Pump-IR\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-IR\").data('internal-id','10300301')}\n\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_PE\"],4) ==1) {\n\t\t\t$(\"#F-Pump-EL\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-EL\").data('internal-id','10300400')}\n\t\telse {\n\t\t\t$(\"#F-Pump-EL\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-EL\").data('internal-id','10300401')}\n\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_PE\"],1) ==1) {\n\t\t\t$(\"#F-Pump-ER\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-ER\").data('internal-id','10300400')}\n\t\telse {\n\t\t\t$(\"#F-Pump-ER\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-ER\").data('internal-id','10300401')}\n\t\t\n\t\t\n\t// RPM Moteur et Rotor\n\t\tEngRpm = dataread_split_2(KaTZPit_data[\"Eng_rpm\"])\n\t\tdocument.getElementById('F-RPM-G').innerHTML = (EngRpm[1]/10).toFixed(0)\n\t\tdocument.getElementById('F-RPM-D').innerHTML = (EngRpm[0]/10).toFixed(0)\n\t\t\n\t\tdocument.getElementById('F-RPM-RO').innerHTML = KaTZPit_data[\"RPM_Rot\"]\n\t\t\n\t// Températures\tAPU\n\n\t\tdocument.getElementById('F-DEG-APU').innerHTML = dataread_split_2(KaTZPit_data[\"APU_Data\"])[0]\n\t\t\n\t// Voyants de l'APU\n\t// On va lire la valeur de chaque voyant dans la chaine \"APU_Voyants\"\n\t// avec la fonction dataread_posit(chaine,position), fonction se trouvant dans function_calcul.js\n\t\n\t\t// Ignition\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"APU_Voyants\"],1) ==1) {\n\t\t\t$(\"#F-Vanne-APU\").attr('src','images/fuel/FV-Vanne_V_O.gif')\n\t\t\t$(\"#F-Vanne-APU\").data('internal-id','20301000')\n\t\t\t$(\"#F-APU-Fuel\").fadeIn()} \n\n\t\telse {\n\t\t\t$(\"#F-Vanne-APU\").attr('src','images/fuel/FV-Vanne_V_F.gif')\n\t\t\t$(\"#F-Vanne-APU\").data('internal-id','20301001')\n\t\t\t$(\"#F-APU-Fuel\").fadeOut()}\n\n\n\t\t// Oil OK\n\t\tif (dataread_posit(KaTZPit_data[\"APU_Voyants\"],2) ==1) {$(\"#F-APU-Oil\").fadeIn()} else {$(\"#F-APU-Oil\").fadeOut()}\n\t\t// RPM OK\n\t\t//if (dataread_posit(KaTZPit_data[\"APU_Voyants\"],3) ==1) {$(\"#APU-V-RPM-OK\").fadeIn()} else {$(\"#APU-V-RPM-OK\").fadeOut()}\n\t\t// RPM High Alarm\n\t\tif (dataread_posit(KaTZPit_data[\"APU_Voyants\"],4) ==1) {$(\"#F-APU-Rpm\").fadeIn()} else {$(\"#F-APU-Rpm\").fadeOut()}\n\n\t\tif (dataread_posit(KaTZPit_data[\"APU_Voyants\"],3) ==1) {\n\t\t\t$(\"#F-APU-ON\").attr('src','images/fuel/FV_APU_ON.gif')\n\t\t\t// Bouton Start type press bouton 1000>0000\n\t\t\t$(\"#F-APU-ON\").data('internal-id','50400701')}\n\n\t\telse {\n\t\t\t// Bouton Stop type press bouton 1000>0000\n\t\t\t$(\"#F-APU-ON\").attr('src','images/fuel/FV_APU_Off.gif')\n\t\t\t$(\"#F-APU-ON\").data('internal-id','50400701')}\n\t\t\n\t\t\n\t\t//if (KaTZPit_data[\"APU_V_1\"] ==1) {$(\"#F-APU-Fuel\").fadeIn()} else {$(\"#F-APU-Fuel\").fadeOut()}\n\t\t//if (KaTZPit_data[\"APU_V_2\"] ==1) {$(\"#F-APU-Oil\").fadeIn()} else {$(\"#F-APU-Oil\").fadeOut()}\n\t\t//if (KaTZPit_data[\"APU_V_4\"] ==1) {$(\"#F-APU-Rpm\").fadeIn()} else {$(\"#F-APU-Rpm\").fadeOut()}\n\n\t// Sub-Panel Demarrage\n\t\tif (dataread_posit(KaTZPit_data[\"Start_V\"],1) == 1) {\n\t\t\t$(\"#F-Start-ON\").attr('src','images/fuel/FV_START.gif')\n\t\t\t// Bouton Start type press bouton 1000>0000\n\t\t\t$(\"#F-Start-ON\").data('internal-id','50400601')}\n\t\telse {\n\t\t\t// Bouton Stop type press bouton 1000>0000\n\t\t\t$(\"#F-Start-ON\").attr('src','images/fuel/FV_START_off.gif')\n\t\t\t$(\"#F-Start-ON\").data('internal-id','50400501')}\n\n\t\t// Alarme si collectif est levé pour éviter demmarage\n\t\t//if (KaTZPit_data[\"RPM_L\"] >70\t|| KaTZPit_data[\"RPM_R\"] >70) {\n\t\t//\tif (KaTZPit_data[\"Collectif\"]>10) {$(\"#FW-Collectif\").fadeIn()} else {$(\"#FW-Collectif\").fadeOut()}\n\t\t//\t}\n\n\t\t//\tSi selecteur = maintenance on efface le repère de selection\n\t\tif (KaTZPit_data[\"Start_Sel\"] == 3) {$(\"#F-1APU2\").fadeOut()} else {$(\"#F-1APU2\").fadeIn()}\n\n\n\t\t// Selecteur 3 positions Eng1, APU, Eng2\n\t\t// Selecteur 3 positions Start, Vent, Crank\t\n\t\tvar sel = 10 \t// Demarrage APU\n\t\tvar typ = 0 \t// Start\n\t\tif (KaTZPit_data[\"Start_Sel\"] == 1 ) {sel=0} \t// Demarrage Eng 1\n\t\tif (KaTZPit_data[\"Start_Sel\"] == 2 ) {sel=20}\t// Demarrage Eng 2\n\n\t\tif (KaTZPit_data[\"Start_Typ\"] == 1 ) {typ=10}\t// Venting\n\t\tif (KaTZPit_data[\"Start_Typ\"] == 2 ) {typ=20}\t// Cranking\n\t\t\n\t\tStart_Switch(sel,typ)\n\n\t// EEG Moteur\n\t\tif (dataread_posit(KaTZPit_data[\"E_AC_V\"],6) ==1) {\n\t\t\t$(\"#F-EEG-G\").attr('src','images/fuel/FV_EEG.gif')\n\t\t\t$(\"#F-EEG-G\").data('internal-id','20400100')}\n\t\telse {\n\t\t\t$(\"#F-EEG-G\").attr('src','images/fuel/FV_EEG_Off.gif')\n\t\t\t$(\"#F-EEG-G\").data('internal-id','20400101')}\n\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"E_AC_V\"],5) ==1) {\n\t\t\t$(\"#F-EEG-D\").attr('src','images/fuel/FV_EEG.gif')\n\t\t\t$(\"#F-EEG-D\").data('internal-id','20400300')}\n\t\telse {\n\t\t\t$(\"#F-EEG-D\").attr('src','images/fuel/FV_EEG_Off.gif')\n\t\t\t$(\"#F-EEG-D\").data('internal-id','20400301')}\n\t\t\n}",
"function seleccionar_lapiz() {\n\t\t\therramienta = btn_lapiz.value;\n\t\t}",
"function cargarCgg_res_tipo_notificacionCtrls(){\n if(inRecordCgg_res_tipo_notificacion){\n txtCrtnt_codigo.setValue(inRecordCgg_res_tipo_notificacion.get('CRTNT_CODIGO'));\n txtCrtnt_descripcion.setValue(inRecordCgg_res_tipo_notificacion.get('CRTNT_DESCRIPCION'));\n chkCrtnt_causal_salida.setValue(inRecordCgg_res_tipo_notificacion.get('CRTNT_CAUSAL_SALIDA'));\n txtCrtnt_sustento_legal.setValue(inRecordCgg_res_tipo_notificacion.get('CRTNT_SUSTENTO_LEGAL'));\n chkCrtnt_causal_caducidad.setValue(inRecordCgg_res_tipo_notificacion.get('CRTNT_CAUSAL_CADUCIDAD'));\n isEdit = true;\n habilitarCgg_res_tipo_notificacionCtrls(true);\n }}",
"function modifUnidad(unid,asig){\r\n\tdocument.getElementById('unid_tem').value=unid;\r\n\tdocument.getElementById('titulo').innerHTML=\"MODIFICAR TEMA\";\r\n\tdocument.getElementById('boton_temas').innerHTML=\"Modificar\";\r\n\tdocument.forms.agregarTema.action=\"comunicaciones/modifTema.php\";\r\n\tdocument.getElementById('unid_viejo').value=unid;\r\n\tdocument.getElementById('boton').value=\"Modificar\";\r\n\tdocument.getElementById(asig).selected=true;\r\n}",
"function cambioDependencia(){\n reiniciarSelect(\"horario\");\n reiniciarSelect(\"actividad\");\n reiniciarSelect(\"propuesta\");\n actualizarTodo(URLS.propuestaDeDependencia, \"propuesta\", \"dependencia\");\n}",
"function modifierVisiteAnnuelle(){\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Emit from the edge of a circle. | get CircleEdge() {} | [
"set CircleEdge(value) {}",
"function draw_circle() {\n ctxe.beginPath()\n ctxe.arc(EW_CENTER_POINT.x, EW_CENTER_POINT.y, inverseWavelength, 0, Math.PI * 2)\n ctxe.stroke()\n }",
"edgeBounce() {\r\n\t\tlet margin = 100;\r\n\r\n\t\tif (this.x < margin) {\r\n\t\t\tthis.vx += turnCo;\r\n\t\t}\r\n\t\tif (this.x > canvas.width - margin) {\r\n\t\t\tthis.vx -= turnCo;\r\n\t\t}\r\n\t\tif (this.y < margin) {\r\n\t\t\tthis.vy += turnCo;\r\n\t\t}\r\n\t\tif (this.y > canvas.height - margin) {\r\n\t\t\tthis.vy -= turnCo;\r\n\t\t}\r\n\t}",
"function mouseclicks()\n{\n //mouse makes yellow dot\n fill(255,255,0);\n circle(mousex, mousey, d);\n \n}",
"function ConeParticleEmitter(radius,angle,/** defines how much to randomize the particle direction [0-1] (default is 0) */directionRandomizer){if(radius===void 0){radius=1;}if(angle===void 0){angle=Math.PI;}if(directionRandomizer===void 0){directionRandomizer=0;}this.directionRandomizer=directionRandomizer;/**\n * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)\n */this.radiusRange=1;/**\n * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)\n */this.heightRange=1;/**\n * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)\n */this.emitFromSpawnPointOnly=false;this.angle=angle;this.radius=radius;}",
"function drawRightEye() {\n const x = ($canvas.width / 5) * 2 - 50;\n const y = $canvas.height / 8 + 50;\n const radius = 10;\n const sA = 0;\n const eA = 2 * Math.PI;\n\n ctx.beginPath();\n ctx.arc(x, y, radius, sA, eA);\n ctx.fillStyle = 'black';\n ctx.fill();\n ctx.strokeStyle = 'white';\n ctx.stroke();\n}",
"function CylinderDirectedParticleEmitter(radius,height,radiusRange,/**\n * The min limit of the emission direction.\n */direction1,/**\n * The max limit of the emission direction.\n */direction2){if(radius===void 0){radius=1;}if(height===void 0){height=1;}if(radiusRange===void 0){radiusRange=1;}if(direction1===void 0){direction1=new BABYLON.Vector3(0,1,0);}if(direction2===void 0){direction2=new BABYLON.Vector3(0,1,0);}var _this=_super.call(this,radius,height,radiusRange)||this;_this.direction1=direction1;_this.direction2=direction2;return _this;}",
"renderCircle() {\r\n\t\tconst x = this.ranges.x(this.data[this.data.length - 1].date);\r\n\t\tconst y = this.ranges.y(this.data[this.data.length - 1].value);\r\n\r\n\t\tthis.point = this.svg.select('.circle')\r\n\t\t\t.interrupt()\r\n\t\t\t.transition()\r\n\t\t\t\t.duration(this.numberGeneratorOptions.interval * 2.5)\r\n\t\t\t\t.attr('transform', `translate(${x}, ${y})`);\r\n\t}",
"function SphereDirectedParticleEmitter(radius,/**\n * The min limit of the emission direction.\n */direction1,/**\n * The max limit of the emission direction.\n */direction2){if(radius===void 0){radius=1;}if(direction1===void 0){direction1=new BABYLON.Vector3(0,1,0);}if(direction2===void 0){direction2=new BABYLON.Vector3(0,1,0);}var _this=_super.call(this,radius)||this;_this.direction1=direction1;_this.direction2=direction2;return _this;}",
"function drawPacmanDirection(xPacman, yPacman, raduisPacman, startPacman, endPacman, xMouse, yMouse, xEye, yEye, radiusEye, startEye, endEye) {\n context.beginPath();\n context.arc(xPacman, yPacman, raduisPacman, startPacman, endPacman); // half circle\n context.lineTo(xMouse, yMouse);\n context.fillStyle = \"yellow\"; //color\n context.fill();\n context.beginPath();\n context.arc(xEye, yEye, radiusEye, startEye, endEye); // circle\n context.fillStyle = \"black\"; //color\n context.fill();\n}",
"function radius(e)\n{\n return 4*Math.sqrt(e.size);\n}",
"function drawLeftEye() {\n const x = $canvas.width / 5;\n const y = $canvas.height / 8 + 50;\n const radius = 10;\n const sA = 0;\n const eA = 2 * Math.PI;\n\n ctx.beginPath();\n ctx.arc(x, y, radius, sA, eA);\n ctx.fillStyle = 'black';\n ctx.fill();\n ctx.strokeStyle = 'white';\n ctx.stroke();\n}",
"function drawPointerPos() {\n circle(context,pointer.x,pointer.y,pointer.radius/step*50);\n}",
"function drawCircle(x, y, radius, color){\n\tcontext.beginPath();\n\tcontext.arc(x, y, radius, 0, Math.PI * 2, true);\n\tcontext.fillStyle = color;\n\tcontext.fill();\n\tcontext.closePath();\n\tcontext.addHitRegion({id: x+'.'+y});\n}",
"function drawEdge(a, b, c, where, opacity) {\n let shadow = opacity;\n\n let startX;\n let startY;\n let endX;\n let endY;\n if (where == \"edge\") startX = 0, startY = 0;\n if (where == \"edge\") endX = map.width, endY = map.height;\n if (where == \"view\") startX = canvas.x * (-1), startY = canvas.y * (-1);\n if (where == \"view\") endX = canvas.x * (-1) + window.innerWidth, endY = canvas.y * (-1) + window.innerHeight;\n\n var gradient = ctx.createLinearGradient(map.height / 2, startY, map.height / 2, endY);\n gradient.addColorStop(0, \"rgba(\" + a + \",\" + b + \",\" + c + \",\" + shadow + \")\");\n gradient.addColorStop(.4, \"rgba(0, 0, 0, 0)\");\n gradient.addColorStop(.6, \"rgba(0, 0, 0, 0)\");\n gradient.addColorStop(1, \"rgba(\" + a + \",\" + b + \",\" + c + \",\" + shadow + \")\");\n ctx.fillStyle = gradient;\n ctx.fillRect(startX, startY, endX, endY);\n\n gradient = ctx.createLinearGradient(startX, map.width / 2, endX, map.width / 2);\n gradient.addColorStop(0, \"rgba(\" + a + \",\" + b + \",\" + c + \",\" + shadow + \")\");\n gradient.addColorStop(.4, \"rgba(0, 0, 0, 0)\");\n gradient.addColorStop(.6, \"rgba(0, 0, 0, 0)\");\n gradient.addColorStop(1, \"rgba(\" + a + \",\" + b + \",\" + c + \",\" + shadow + \")\");\n ctx.fillStyle = gradient;\n ctx.fillRect(startX, startY, endX, endY);\n}",
"drawBall() {\n fill('#FFFFFF');\n circle(this.x, this.y, 2 * this.radius);\n }",
"function CylinderParticleEmitter(/**\n * The radius of the emission cylinder.\n */radius,/**\n * The height of the emission cylinder.\n */height,/**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */radiusRange,/**\n * How much to randomize the particle direction [0-1].\n */directionRandomizer){if(radius===void 0){radius=1;}if(height===void 0){height=1;}if(radiusRange===void 0){radiusRange=1;}if(directionRandomizer===void 0){directionRandomizer=0;}this.radius=radius;this.height=height;this.radiusRange=radiusRange;this.directionRandomizer=directionRandomizer;}",
"function drawDoor() {\n //grey color\n penRGB(170, 170, 170, 1);\n penWidth(4);\n //starts where it ended after it drew the roof, so moves to where the door where will be located\n moveToDoorLocation();\n //the curve on the door\n moveForward(15);\n arcLeft(180, 5);\n moveForward(15);\n}",
"function strokedCircle(ctx, x, y, radius) {\r\n ctx.beginPath();\r\n ctx.arc(x, y, radius, 0, 2 * Math.PI, false);\r\n ctx.stroke();\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
must match test_robots.txt Count actual phantomjs processes in play, requires pgrep | function countSpawnedProcesses(cb) {
var pgrep = spawn("pgrep", [spawnedProcessPattern, "-c"]);
pgrep.stdout.on("data", cb);
} | [
"searchTasks(str){\r\n console.log(`Search: ${str}`)\r\n let numMatches= 0;\r\n\r\n //Go through Tasks and output any partial string matches found, matching on text attribute.\r\n this.projectList.forEach(project => {\r\n project.taskList.forEach(task =>{\r\n if(task.text.search(str) >= 0){\r\n numMatches++;\r\n tm.outputTask(task);\r\n }\r\n });\r\n });\r\n\r\n //Output # matches of found.\r\n if(numMatches > 0){\r\n console.log(`This search found ${numMatches} matches.`);\r\n }else{\r\n console.log(\"No matches were found.\");\r\n }\r\n\r\n console.log();\r\n return numMatches;\r\n }",
"function checkComposer() {\n\tvar process = runExec(pgrepPath, pgrepComposer, true);\n\t\n\tif (process.exitValue != 0) {\n\t\tstartComposer();\n\n\t\t//wait for the pipe to be created\n\t\tvar i = 0;\n\t\twhile (!checkPipe() && i < 5000) i++;\n\t}\n}",
"function countMatches() {\n\tnumberOfMatches += 1;\n\treturn numberOfMatches;\n}",
"function checkPhantomStatus() {\n if (phantomChildren.length < maxInstances) {\n return true;\n }\n return false;\n}",
"function restartPhantom(crawl, e) {\n if (e) {\n console.log(\"Phantom Error:\", e);\n try {\n console.log(\"try to kill: \", crawl.processId);\n process.kill(crawl.processId);\n } catch (err) {\n //\n }\n }\n\n removeFromArray(crawl.processId);\n crawl.websites = crawl.websites.slice(crawl.index);\n initPhantom(crawl.websites, crawl.crawlStatus);\n}",
"async waitForPageTitle (expected) {\n var waitFor = this.waitFor.bind(this)\n var pageTitle = this.pageTitle.bind(this)\n return new Promise(async resolve => {\n var result = await waitFor(async () => {\n var title = await pageTitle()\n if (expected instanceof RegExp) {\n return expected.test(title)\n } else {\n return title === expected\n }\n })\n resolve(result)\n })\n }",
"function googleSearch() {\n if(verbose == 1) console.log('entering googleSearch');\n comment = comments_to_search.shift();\n\n var url = 'http://www.google.com/search?q=' + comment + '+facebook';\n\n if(verbose == 1) console.log('google search for comment: ' + comment);\n\n var temp = '';\n var page = require('webpage').create();\n\n page.settings.userAgent = 'Mozilla/5.0 (X11; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0';\n\n page.open(url, function(status) {\n if (status === 'success') {\n var links = page.plainText.match(/https:\\/\\/www.facebook.com\\/(.*?)\\n/g);\n if(links != null){\n for(i = 0; i < links.length; i++) {\n temp = links[i].split(\"/\")[3];\n\n /* Remove duplicates and any entry that contains a dot.*/\n if(temp.indexOf(\"pages\") == -1 && temp.indexOf(\".\") == -1 && next_page.indexOf(temp) == -1) {\n next_page.push(temp.replace(/(\\r\\n|\\n|\\r)/gm,''));\n nextindex++;\n\n } \n }\n }\n } \n else {\n if(verbose == 1) console.log('error in googleSearch page ' );\n if(verbose == 1) console.log(\n \"Error opening url \\\"\" + page.reason_url\n + \"\\\": \" + page.reason\n );\n } \n page.release();\n if(verbose == 1) console.log('closing googleSearch page');\n\n page.close();\n searchHandler();\n\n });\n}",
"search_robots() {\n // if we need to search the network for robots\n if (robots_disp[0] == \"\") {\n // This is where robots and beacons are filtered\n // var patt = /^((?!B).)\\d{1,2}(?!_)/;\n // var handled_names = [];\n\n // for (let i = 0; i < topicsList.length; i++) {\n // console.log(\"Looking for robots on the network\");\n // let name = topicsList[i].split('/')[1];\n\n // if (handled_names.indexOf(name) == -1) {\n // if (patt.test(name) && (name != 'S01')) {\n // console.log('adding ', name, ' from the network');\n // if (_this.robot_name.indexOf(name) == -1) {\n // _this.robot_name.push(name);\n // _this.tabs_robot_name.push(name);\n // _this.x++;\n \n // }\n // }\n // handled_names.push(name);\n // }\n // }\n\n // Make decision of what to do with this improved system\n let topics = topicsList.filter(x => !handled_topics.includes(x));\n\n for (let i = 0; i < topics.length; i++) {\n // console.log(\"Looking for robots on the network\");\n if(topics[i].includes(ma_prefix) && topics[i].includes('odometry')){\n \n // reg ex patern for good robot names\n var patt = /\\b[A, C-R, T-Z]\\d{1,2}(?!_)\\b/i;\n let results = topics[i].match(patt);\n if(results){\n name = results[0];\n console.log('adding ', name, ' from the network');\n if (global_tabManager.robot_name.indexOf(name) == -1) {\n global_tabManager.robot_name.push(name);\n global_tabManager.tabs_robot_name.push(name);\n global_tabManager.x++;\n \n }\n }\n }\n handled_topics.push(topics[i]);\n }\n\n // If we can get robots from launch file\n } else {\n for (let i = 0; i < robots_disp.length; i++) {\n name = robots_disp[i];\n if (global_tabManager.robot_name.indexOf(name) == -1) {\n global_tabManager.robot_name.push(name);\n global_tabManager.tabs_robot_name.push(name);\n global_tabManager.x++;\n }\n }\n }\n\n let curr_robot_length = global_tabManager.robot_name.length; // Length of entire robots seen over all time after function\n\n // report robot as \"disconnect\" if it was previously discovered but we are no longer\n // receiving messages from it.\n let now = new Date();\n for (let i = 0; i < curr_robot_length; i++) {\n var battery_disp = $('#battery_' + global_tabManager.robot_name[i]);\n var battery_dom = $('#battery_status_' + global_tabManager.robot_name[i]);\n var color = 'grey';\n if (global_tabManager.battery[i] < 23.1) {\n color = 'red';\n } else if (global_tabManager.battery[i] < 24.5) {\n color = 'orange';\n }\n battery_disp.html('<font color=\"' + color + '\">' + global_tabManager.battery[i] + '</font>');\n battery_dom.html('<font color=\"' + color + '\">' + global_tabManager.robot_name[i] + '</font>');\n\n var status_dom = $('#connection_status_' + global_tabManager.robot_name[i]);\n if (global_tabManager.incomm[i]) {\n status_dom.html('<font color=\"green\">Connected</font>');\n }\n else {\n status_dom.html('<font color=\"red\">Disconnected</font>');\n }\n\n var task = '';\n var task_dom = $('#task_status_' + global_tabManager.robot_name[i]);\n var full_task = global_tabManager.tasks[i];\n if (full_task) {\n var tasks = full_task.split('+++');\n task = tasks[0];\n pubTask(task_dom, tasks, 1);\n }\n if (task == \"Home\") {\n task_dom.html('<font color=\"yellow\">Going Home</font>');\n } else if (task == \"Report\") {\n task_dom.html('<font color=\"yellow\">Reporting</font>');\n } else if (task == \"Deploy\") {\n task_dom.html('<font color=\"yellow\">Deploying Beacon</font>');\n } else if (task == \"Stop\") {\n task_dom.html('<font color=\"red\">Stopped</font>');\n } else if (task == \"Explore\") {\n task_dom.html('<font color=\"green\">Exploring</font>');\n } else if (task == \"guiCommand\") {\n task_dom.html('<font color=\"green\">GUI Goal</font>');\n } else {\n if (task == undefined) task = '';\n task_dom.html('<font color=\"red\">' + task + '</font>');\n }\n }\n\n for (global_tabManager.i; global_tabManager.i < curr_robot_length; global_tabManager.i++) {\n global_tabManager.add_tab();\n }\n }",
"function countModules (){\n \n return availableModules.length;\n}",
"function scanCheck() {\n let isScaning = GM_getValue(\"isScaning\");\n if (isScaning === undefined) {\n isScaning = false;\n }\n\n if (isScaning) {\n scanPosts();\n }\n}",
"function ListProcs() {\n\n // Get easy access to the debug output method\n var dbgOutput = host.diagnostics.debugLog;\n\n dbgOutput(\"List Processes!\\n\\n\");\n\n var processes = host.currentSession.Processes;\n\n for (var process of processes)\n {\n dbgOutput(\"Found Process:\\n\");\n dbgOutput(\"\\tName : \", process.Name, \"\\n\");\n dbgOutput(\"\\tId : \", process.Id, \"\\n\");\n }\n\n}",
"function checkServer(callback){\n\tps.lookup({command:config.webserverExecCmd},(err,result)=>{\n\t\tconsole.log(result)\n\t\tif(result.length>0) callback(true);\n\t\telse callback(false);\n\t});\n}",
"function spoccures(string, regex) {\n return (string.match(regex) || []).length;\n }",
"function count(regex, str) {\n return str.length - str.replace(regex, '').length;\n }",
"prepare() {\n this._koa.use(this.mock.bind(this));\n\n this._engines = {};\n\n const vhostConfigs = this._config.vhosts;\n let amountOfDomains = 0;\n\n for (const vhostName in vhostConfigs) {\n const vhostConfig = vhostConfigs[vhostName];\n\n const engine = new RuleEngine(this._name + '_RuleEngine', vhostConfig);\n this._beans.renderThenInitBean(engine, 'RuleEngine:' + vhostName);\n\n for (const domain of vhostConfig.domains) {\n if (this._engines[domain]) {\n throw new Error(`${this._name}: duplicated domain: domain`);\n }\n this._engines[domain] = engine;\n amountOfDomains++;\n\n if (!this.defaultDomain) {\n this.defaultDomain = domain;\n }\n\n this._logger.info(`virtual host: ${domain}`);\n }\n }\n\n if (amountOfDomains !== 1) {\n this.defaultDomain = undefined;\n }\n }",
"verifDescription() {\n let regexMoreTen = /[A-Z \\.\\,]{10,}/i;\n if (regexMoreTen.test(this.datas.description) === false) {\n this.errors.description = {\n message: \"La description doit avoir au moins 10 caractères\",\n old: this.datas.title\n };\n this.test++;\n }\n }",
"message(msg) {\n this.reports.forEach(report => {\n if (report.include.some(p => p.test(msg)) && !(report.exclude || []).some(p => p.test(msg))) {\n this.counts[report.name] = (this.counts[report.name] || 0) + 1;\n }\n });\n }",
"function checkIfProcessed(redditData, db, r) {\n db.get(\"SELECT name FROM redditPost WHERE name='\" + redditData.name + \"' AND processed='1'\", function (error, postId) {\n if (!postId) {\n console.log(\"Processing post\");\n checkIfEvent(redditData, db, r);\n }\n });\n}",
"function getEggRunningInfo() {\n const { stdout } = shell.exec('ps aux | grep node', { silent: true });\n const pidList = [];\n let port;\n\n stdout.split('\\n').forEach(line => {\n if (!line.includes('node ')) {\n return;\n }\n\n const m = line.match(REGEX);\n if (!m) return;\n\n const pid = m[1];\n const cmd = m[2];\n if (cmd.includes(`\"title\":\"egg-server-${pkgInfo.name}\"`)) {\n pidList.push(pid);\n\n if (!port && PORT_REGEX.test(cmd)) {\n port = RegExp.$1;\n }\n }\n });\n\n return {\n pidList,\n port,\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Screen readers on IE needs to have the role application set on the body. | function ensureBodyHasRoleApplication() {
document.body.setAttribute("role", "application");
} | [
"role() {\n const { disabled } = this.props;\n const role = SharedUtil.isSafari() ? 'group' : 'button';\n\n return disabled ? undefined : role;\n }",
"static get noRole() { return NO_ROLE; }",
"showToScreenReader() {\n this.adapter_.removeAttr(_constants.strings.ARIA_HIDDEN);\n }",
"function getBodyClassName() {\n return document.getElementsByTagName(\"body\")[0].className;\n}",
"_setAriaAttributes () {\n this.tablist.setAttribute('role', 'tablist')\n this.tabs.forEach(tab => tab.setAttribute('role', 'tab'))\n this.panels.forEach(panel => {\n panel.setAttribute('role', 'tabpanel')\n panel.setAttribute('tabindex', 0)\n })\n\n for (let i = 0; i < this.tabs.length; i++) {\n const tab = this.tabs[i]\n const panel = this.panels[i]\n const id = tab.getAttribute('id')\n\n panel.setAttribute('aria-labelledby', id)\n }\n }",
"function hasAccessibleName(vNode) {\n // testing for when browsers give a <section> a region role:\n // chrome - always a region role\n // firefox - if non-empty aria-labelledby, aria-label, or title\n // safari - if non-empty aria-lablledby or aria-label\n //\n // we will go with safaris implantation as it is the least common\n // denominator\n const ariaLabelledby = sanitize(arialabelledbyText(vNode));\n const ariaLabel = sanitize(arialabelText(vNode));\n\n return !!(ariaLabelledby || ariaLabel);\n}",
"renderStoreManagerForm() {\n console.log('@renderStoreManagerForm')\n console.log(this.props.loggedInUser.role[0])\n if (this.props.loggedInUser.roles[0] == \"ROLE_USER\") {\n return (\n <span style={{ fontSize: 12, color: \"#504F5A\", marginTop: 5 }}>Create a Store Manager</span>\n );\n }\n return;\n }",
"function seperateRole(){\n\n}",
"function _removeARIA() {\n if (settings.modalCloseClass) MODAL.classList.remove(settings.modalCloseClass);\n if (settings.modalOpenClass) MODAL.classList.remove(settings.modalOpenClass);\n if (settings.modalLabeledBy) MODAL_CONTENT.removeAttribute('aria-labelledby');\n if (settings.modalDescribedBy) MODAL_CONTENT.removeAttribute('aria-describedby');\n\n MODAL.removeAttribute('aria-hidden');\n MODAL_OVERLAY.removeAttribute('tabindex');\n MODAL_CONTENT.removeAttribute('role');\n }",
"__updateDrawerAriaAttributes() {\n const drawer = this.$.drawer;\n if (this.overlay) {\n drawer.setAttribute('role', 'dialog');\n drawer.setAttribute('aria-modal', 'true');\n drawer.setAttribute('aria-label', this.i18n.drawer);\n } else {\n drawer.removeAttribute('role');\n drawer.removeAttribute('aria-modal');\n drawer.removeAttribute('aria-label');\n }\n }",
"goFullScreen(name) {\r\n if (name && this._windows.has(name)) {\r\n this._windows.get(name).native.setFullScreen(true);\r\n return;\r\n }\r\n this._windows.forEach(win => win.native.setFullScreen(true));\r\n }",
"updateAriaAttrs () {\n if (!this.aria || this.isHeadless || !isCallable(this.el.setAttribute)) return;\n\n this.el.setAttribute('aria-required', this.isRequired ? 'true' : 'false');\n this.el.setAttribute('aria-invalid', this.flags.invalid ? 'true' : 'false');\n }",
"function getUserRole(name, role){\n switch (role) {\n case \"admin\":\n return `${name} is admin with all access`\n break; //this is not neccesary\n\n case \"subadmin\":\n return `${name} is sub-admin acess to delete and create courses`\n break;\n\n case \"testprep\":\n return `${name} is test-prep access with to delete and create tests `\n break;\n case \"user\":\n return `${name} is a user to consume content`\n break;\n \n default:\n return `${name} is admin access with to delete and create tests `\n break;\n }\n}",
"function setAppMenu() {\n let menuTemplate = [\n {\n label: appName,\n role: 'window',\n submenu: [\n {\n label: 'Quit',\n accelerator: 'CmdorCtrl+Q',\n role: 'close'\n }\n ]\n },\n {\n label: 'Edit',\n submenu: [\n {\n label: 'Cut',\n role: 'cut'\n },\n {\n label: 'Copy',\n role: 'copy'\n },\n {\n label: 'Paste',\n role: 'paste'\n },\n {\n label: 'Select All',\n role: 'selectall'\n }\n ]\n },\n {\n label: 'Help',\n role: 'help',\n submenu: [\n {\n label: 'Docs',\n accelerator: 'CmdOrCtrl+H',\n click() {\n shell.openExternal('https://docs.moodle.org/en/Moodle_Mobile');\n }\n }\n ]\n }\n ];\n\n Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate));\n}",
"bodyHide () {\n document.body.addEventListener(this.bodyEvent, ev => {\n this.hide()\n }, false)\n\n this.wrap.addEventListener(this.bodyEvent,\n ev => ev.stopPropagation() || ev.preventDefault(),\n false\n )\n }",
"function isTutor(req, res, next) {\n var user = req.user;\n if (user.roles.indexOf('tutor') > -1) {\n next();\n } else {\n res.status(403).end();\n }\n}",
"function setRoleplayInfo(name) {\n alt.emitServer('character:SetRoleplayInfo', name);\n showCursor(false);\n}",
"function checkScreenSize () {\n if ( $(window).width() <= 600 ) {\n body.removeClass('js-lg-screen');\n }\n\n if ( $(window).width() >= 600 && html.hasClass('nav-open') ) {\n html.removeClass('nav-open');\n\n // revert btnMenu attributes to original state\n btnMenu.attr('data-state', 'off');\n btnMenu.attr('aria-label', 'Reveal Navigation');\n btnMenu.attr('aria-expanded', false);\n }\n }",
"isFullscreenEnabled() {\n return isFullscreenEnabled(this.container);\n }",
"function changeBodyBg(color){\r\n document.body.style.background = color;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParserproc_decl_in_type. | visitProc_decl_in_type(ctx) {
return this.visitChildren(ctx);
} | [
"visitSubprog_decl_in_type(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitFunc_decl_in_type(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_procedure_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"enterAnnotationTypeMemberDeclaration(ctx) {\n\t}",
"visitType_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSubtype_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function parseType() {\n var id;\n var params = [];\n var result = [];\n\n if (token.type === _tokenizer.tokens.identifier) {\n id = identifierFromToken(token);\n eatToken();\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.func)) {\n eatToken(); // (\n\n eatToken(); // func\n\n if (token.type === _tokenizer.tokens.closeParen) {\n eatToken(); // function with an empty signature, we can abort here\n\n return t.typeInstruction(id, t.signature([], []));\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.param)) {\n eatToken(); // (\n\n eatToken(); // param\n\n params = parseFuncParam();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.result)) {\n eatToken(); // (\n\n eatToken(); // result\n\n result = parseFuncResult();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.typeInstruction(id, t.signature(params, result));\n }",
"visitCompile_type_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_function_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitRecord_type_def(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_elements_parameter(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDeclare_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitProcedure_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"declarations() {\n let declarationList = [];\n // starts with a var followed by bunch of var declarations\n if (this.currentToken.type === tokens.VAR) {\n this.eat(tokens.VAR);\n while (this.currentToken.type === tokens.ID) {\n declarationList = [...declarationList, ...this.variableDeclaration()];\n this.eat(tokens.semi);\n }\n }\n\n while (this.currentToken.type === \"PROCEDURE\") {\n this.eat(tokens.PROCEDURE);\n const procName = this.currentToken.name;\n this.eat(tokens.ID);\n this.eat(tokens.semi);\n const blockNode = this.block();\n const procDecl = new ProcedureDecl(procName, blockNode);\n declarationList.push(procDecl);\n this.eat(tokens.semi);\n }\n return declarationList;\n }",
"visitXmltype_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function collectTypes (path: NodePath): void {\n path.traverse({\n InterfaceDeclaration (path: NodePath) {\n path.scope.setData(`typechecker:${path.node.id.name}`, path);\n },\n TypeAlias (path: NodePath) {\n path.scope.setData(`typechecker:${path.node.id.name}`, path);\n },\n ImportDeclaration (path: NodePath) {\n if (path.node.importKind !== 'type') {\n return;\n }\n path.get('specifiers')\n .forEach(specifier => {\n const local = specifier.get('local');\n if (local.isIdentifier()) {\n path.scope.setData(`typechecker:${local.node.name}`, specifier);\n }\n else {\n path.scope.setData(`typechecker:${local.node.id.name}`, specifier);\n }\n });\n },\n \"Function|Class\" (path: NodePath) {\n const node = path.node;\n if (node.typeParameters && node.typeParameters.params) {\n path.get('typeParameters').get('params').forEach(typeParam => {\n path.get('body').scope.setData(`typeparam:${typeParam.node.name}`, typeParam);\n });\n }\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use the /clear_orders PHP AJAX call to purge all the information about known orders. Also clears the table from order data as the update_orders() call will only add new rows, never remove old ones | function clear_orders() {
reset();
$.ajax({
contentType: 'application/json; charset=UTF-8',
data: null,
dataType: 'json',
error: function (jqXHR, textStatus, errorThrown) {
failure('Failed to get clear order data', errorThrown.statusText);
},
success: function (data, textStatus, jqXHR) {
$('.orders table tr.order').remove();
$('.orders').addClass('hidden');
},
type: 'GET',
url: '/php/example.php/clear_orders',
});
} | [
"function destroyTable() {\n if ($.fn.DataTable.isDataTable('#ordersGrid')) {\n $('#ordersGrid').DataTable().destroy();\n $('#ordersGrid').empty();\n }\n }",
"function clearOrderForm(){\n $(\"#oi3PriceId\").val(\"\");\n $(\"#oi3SP\").val(\"\");\n $(\"#oi3Price\").html(\"\");\n $(\"#oi3Qty\").val(\"1\");\n $(\"#oi3Cus\").html(\"\");\n $(\"#oi3Remark\").val(\"\");\n $(\"#oi3Total\").html(\"\");\n}",
"function clear() {\n $('.tablesorter tbody tr').remove();\n $('.tablesorter').trigger('updateAll');\n}",
"function clearForm(){\n $('#cduForm')[0].reset();\n $( \"#uiuTable tr:gt(0)\").remove();\n uiu=[];\n}",
"function clearMessageLogTable()\n{\n $('#messageLogTable').dataTable().fnClearTable();\n}",
"function clearTrainTable() {\n $(\"#trainTable\").empty();\n}",
"function clearCart() {\r\n var tableRows = document.querySelectorAll('#cart tbody tr');\r\n for (var i = 0; i < tableRows.length; i++){\r\n if (tableRows[i]){\r\n tableRows[i].remove();\r\n }\r\n }\r\n}",
"function update_orders() {\n\t$.ajax({\n\t\tcontentType: 'application/json; charset=UTF-8',\n\t\tdata: null,\n\t\tdataType: 'json',\n\t\terror: function (jqXHR, textStatus, errorThrown) {\n\t\t\tfailure('Failed to get order data', jqXHR.statusText);\n\t\t},\n\t\tsuccess: function (data, textStatus, jqXHR) {\n\t\t\tif(data.result == 'ok') {\n\t\t\t\tfor(var i in data.orders) {\n\t\t\t\t\tvar order = data.orders[i];\n\n\t\t\t\t\tvar $row = $('.orders table tr[orderid=' + order.orderid + ']');\n\t\t\t\t\tif(!$row.length) {\n\t\t\t\t\t\tvar tr = document.createElement('TR');\n\t\t\t\t\t\ttr.setAttribute('orderid', order.orderid);\n\t\t\t\t\t\ttr.className = 'order';\n\n\t\t\t\t\t\tvar columns = ['orderid', 'amount', 'created', 'account', 'pending', 'credit', 'cancel', 'debit'];\n\n\t\t\t\t\t\tfor(var i in columns) {\n\t\t\t\t\t\t\tvar td = document.createElement('TD');\n\t\t\t\t\t\t\ttd.className = columns[i];\n\t\t\t\t\t\t\ttr.appendChild(td);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$row = $(tr);\n\t\t\t\t\t\t$('.orders table').append($row);\n\t\t\t\t\t}\n\t\t\t\t\tvar $row_td = $row.find('td');\n\t\t\t\t\t$row_td.eq(0).text(order.orderid);\n\n\t\t\t\t\tvar amount = '-';\n\t\t\t\t\tif(typeof(order.amount) != 'undefined' && order.amount != null) {\n\t\t\t\t\t\tamount = order.amount;\n\t\t\t\t\t}\n\t\t\t\t\tif(typeof(order.currency) != 'undefined' && order.currency != null) {\n\t\t\t\t\t\tamount = amount + ' ' + order.currency;\n\t\t\t\t\t}\n\t\t\t\t\t$row_td.eq(1).text(amount);\n\t\t\t\t\t$row_td.eq(2).text(order.created)?order.created:'';\n\n\t\t\t\t\t_build_notification_td($row_td.eq(3), order.account);\n\t\t\t\t\t_build_notification_td($row_td.eq(4), order.pending);\n\t\t\t\t\t_build_notification_td($row_td.eq(5), order.cancel);\n\t\t\t\t\t_build_notification_td($row_td.eq(6), order.credit);\n\t\t\t\t\t_build_notification_td($row_td.eq(7), order.debit);\n\t\t\t\t}\n\t\t\t\tif(data.orders.length) {\n\t\t\t\t\t$('.orders').removeClass('hidden');\n\n\t\t\t\t\t$('.orders table tr.order').click(function() {\n\t\t\t\t\t\t$(this).toggleClass('show-extra');\n\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\ttype: 'GET',\n\t\turl: '/php/example.php/orders',\n\t});\n}",
"clearData(){\n //reset table data \n this.config.currentData = {};\n this.config.pageCount=1; //table page count (will calculating later)\n this.config.pageLimit=10; //table page limit\n this.config.tableData={};\n this.config.currentPage=1; //table current page\n this.config.currentData={}; //table current data\n\n //clean body\n this.config.body.innerHTML = '';\n //clean pagination\n this.config.pagination.innerHTML = '';\n }",
"handleDeleteOrder(event) {\n let ordID = parseInt(event.target.getAttribute('data-order'), 10);\n let url = `http://localhost:3000/orders`;\n Request.del(url)\n .send({\n ordID\n })\n .end((error, response) => {\n if (error || !response.ok) {\n } else {\n }\n this.setState({\n orderDetails: [],\n orders: this.getOrders(),\n currentOrder: ''\n });\n });\n }",
"function removeAllJouralEntries() {\n $('#table_journal > tbody > tr').remove();\n}",
"function clearAll() {\n\t\t}",
"function clearTable(table) {\n table.empty();\n}",
"function clearAll() {\r\n hidePlayer();\r\n clearDiv(\"recordView\");\r\n clearDiv(\"annotations\");\r\n clearDiv(\"kwSearch\");\r\n clearDiv(\"keyWord\");\r\n processAjax (\"Introduction.php\", \"columnLeft\");\r\n}",
"static async clearOfPromotion(orderId) {\n const order = await Order.findOne({ id: orderId });\n // if Order.status =\"PAYMENT\" or \"ORDER\" can't clear promotions\n if (order.state === \"ORDER\")\n throw \"order with orderId \" + order.id + \"in state ORDER\";\n if (order.state === \"PAYMENT\")\n throw \"order with orderId \" + order.id + \"in state PAYMENT\";\n // ------------------------------------------ OrderDish update ------------------------------------------\n const orderDishes = await OrderDish.find({ order: order.id }).populate(\"dish\");\n for (const orderDish of orderDishes) {\n await OrderDish.update({ id: orderDish.id }, { discountTotal: 0, discountType: \"\" }).fetch();\n }\n await Order.updateOne({ id: order.id }, { discountTotal: 0 }); // isPromoting: false\n }",
"function clearTable(){\r\n\tcTable = document.getElementById(\"conversionTable\");\r\n\titemList = cTable.childNodes;\r\n\tif(cTable.childElementCount<=2){return;}\r\n\t//Store the header and \"add currency\" rows\r\n\theader = itemList[0];\r\n\tfooter = itemList[cTable.childElementCount-1];\r\n\t\r\n\t\r\n\t//Clear the table and used currencies\r\n\tcTable.innerHTML = \"\";\r\n\tusedCurrencies = [];\r\n\t\r\n\t//Add the header and \"add currency\" rows back to the table \r\n\tcTable.appendChild(header);\r\n\tcTable.appendChild(footer);\r\n\t\r\n\tupdateAddableCurrencies();\r\n}",
"function emptyShoppingList() {\n if (confirm('Are you sure you want to remove everything from your shopping list?')) {\n shoppingList = []\n updateShoppingListDOM()\n } \n}",
"function deleteAllProducts() {\n API.deleteAll()\n .then(res => {\n loadProducts();\n })\n\n }",
"function clearAddOns() {\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construction du panneau des brins | buildPanneau ()
{
let h = DOM.create('section', {id:'panneau_brins'})
let newo, listing
newo = DOM.create('div', {id: 'titre_panneau_brins', class:'titre', inner: "Liste des brins"})
h.appendChild(newo)
let typesTraited = []
// On conserve une liste des types qui vont être traités par
// les brins existants pour ajouter les types manquants à la
// suite afin de pouvoir faire entrer les brins dedans en les
// déplaçant.
// On classe
let bsg = new Map()
, lt = []
Brins.items.forEach((v,k) => {
if (undefined === bsg.get(v.type))
{ bsg.set(v.type,[]);lt.push(v.type) }
bsg.get(v.type).push(v)
})
lt.sort(function(a,b){ return a - b})
let brins_grouped = lt.map(type => { return bsg.get(type) })
listing = DOM.create('ul', {class:'brins', id: 'brins'})
brins_grouped.forEach( grpBrins => {
let typeId = grpBrins[0].type
listing.appendChild(this.buildDivTitre(typeId))
typesTraited.push(typeId)
grpBrins.forEach( brin => { listing.appendChild(brin.buildAsLI()) } )
})
h.appendChild(listing)
// Maintenant qu'on a construit tous les brins, on peut les mettre
// dans leur parent (en supposant bien entendu qu'ils appartiennent
// au même groupe/type de brins)
Brins.items.forEach( (b, bid) => {
if ( ! b.hasParent() ) return ;
b.parent.ULChildren.appendChild(b.LI)
})
/*- Ajout des titres de type non traités (i.e. qui ne possèdent pas
encore de brins) -*/
Brin.TYPES.forEach( (dType, type) => {
if ( typesTraited.includes(type) ) return ;
listing.appendChild(this.buildDivTitre(type))
})
let explication = `
<shortcut>↑</shortcut> <shortcut>i</shortcut> <shortcut>↓</shortcut> <shortcut>k</shortcut> = sélectionner brin.
<shortcut>↑</shortcut> <shortcut>↓</shortcut> + <code>cmd</code> = déplacer le brin (voir l'explication de l'effet dans l'aide).
<shortcut>←</shortcut> <shortcut>j</shortcut> <shortcut>→</shortcut> <shortcut>l</shortcut> = entrer/sortir le brin du parag (si parag édité).
<br><shortcut>e</shortcut> = éditer le brin courant, <shortcut>@</shortcut> = aide.
<shortcut>Enter</shortcut> ou <shortcut>Escape</shortcut> pour quitter le panneau.
`
newo = DOM.create('div', {class:'explication', inner: explication})
h.appendChild(newo)
this._panneau = h
this._panneau.opened = false
} | [
"function colocarPortaaviones(numero){\n\n for (let i=0; i < numero; i++){\n colocarBarco(new Barco(0,0,4, 'P'));\n }\n \n}",
"inicializa(){\n globais.placar = criarPlacar();\n }",
"function constructBan(sfen) {\n const n = sfen.length;\n\n // Pices on board\n var i;\n var ix = 0;\n var iy = 0;\n var iban = 0;\n\n for(var i = 0; i <nrow*nrow; i++)\n editor.ban[i] = '';\n\n for (i = 0; i < n; i++) {\n p = sfen.charAt(i);\n\n if (p === '+') {\n p = sfen.substring(i, i + 2);\n i++;\n }\n\n var number = Number(p);\n if (p == '/') { // Next row\n ix = 0;\n iy++;\n }\n else if (number) { // n black squares\n for(k=0; k<number; k++)\n editor.ban[iban + k] = '';\n iban += number;\n ix += number;\n }\n else if (p == ' ') { // End of board discription\n break;\n }\n else if(Piece[p.toLowerCase()]) { \n editor.ban[iban] = p;\n ix++;\n iban ++;\n }\n }\n\n i = skipTeban(sfen, i);\n\n i = constructSenteHand(sfen, i);\n i = constructGoteHand(sfen, i);\n\n if (sfenEditorJs.debug) {\n console.log('BanFromText', editor.ban);\n console.log('SenteHand', editor.senteHand);\n console.log('GoteHand', editor.goteHand);\n }\n}",
"constructor(args) {\n super();\n var { noodle: noodle, objMeta: meta, container: container, core: core, pos: pos } = args;\n meta = meta || {};\n meta.container = meta.container || new Container({ noodle: noodle });\n this.core = core = core || {};\n core.resetFuncs = core.resetFuncs || [];\n //core.outPorts = core.outPorts || [];\n\n this.pos = new Pos(pos || { x: 0, y: 0 });\n\n this.addMeta({ meta: meta }); //TODO: this.constructor.addMeta?\n this.meta.id = noodle.ids.firstFree()\n\n this.in = { ports: core.inPorts || [] };\n this.out = { ports: core.outPorts || [] };\n this.label = core.name;\n this.parNode = this;\n this.startPos = new Pos();\n\n var ports = this.ports.all;\n for (var i in ports) {\n var port = ports[i];\n port.meta.parNode = this;\n }\n\n }",
"function Gendarme(id) {\n\t \n\t this.index = id;\n\t this.cible = 0;\n\t\n\t // --------- association du corps avec son image html via le noeud enfant \"id\" du div page\n\t this.corps = document.getElementById(\"page\").children[id];\n\t \tthis.corps.style.zIndex = id;\n\t // --------- association des éléments du corps (6 pattes, 2 antennes et le tronc) avec leur image via noeuds enfants du corps\n\t var parts = this.corps.children;\n\t this.pat_0 = parts[0];\n\t this.pat_1 = parts[1];\n\t this.pat_2 = parts[2];\n\t this.pat_3 = parts[3];\n\t this.pat_4 = parts[4];\n\t this.pat_5 = parts[5];\n\t this.ant_0 = parts[6];\n\t this.ant_1 = parts[7];\n\t this.tronc = parts[8];\n\t\n\t\n\t // --------- coordonnées en x et y du gendarme\n\t this.posX = 0;\n\t this.posY = 0;\n\t\n\t // --------- coordonnées en x et y de la cible de déplacement\n\t this.targetX = 0;\n\t this.targetY = 0;\n\t\n\t // --------- mode de déplacement parmi [\"entre\", \"auto\", \"stop\", \"target\", \"suivi\", \"swap\", \"pris\", \"sort\"], initialisation en \"stop\"\n\t this.mode = \"stop\";\n\t\n\t // --------- variable de déplacement: accélération, vitesse, vitesse maximale (à priori 15) et cap (en radian)\n\t this.acc = 0;\n\t this.vit = 0;\n\t this.vMax = 15;\n\t this.cap = 0;\n\t this.dCap = 0;\n\t this.compteur = 0;\n\t\n\t // --------- table des n° d'image pour chaque patte (Rmq: n° compris entre 0 et 5, pour chacune des pattes)\n\t this.patFrame = [0, 0, 0, 0, 0, 0];\n\t\n\t // --------- table des n° d'image pour chaque antenne (Rmq: n° compris entre 0 et 8 pour chacune des antennes)\n\t this.antFrame = [0, 0];\n\t\n\t // --------- fonction d'initialisation du gendarme\n\t this.start = function() {\n\t\n\t\t// --------- positionnement aléatoire à l'extérieur de la fenêtre\n\t \tthis.posX = W/2 + PM()*(W/2 + padH);\n\t \tthis.posY = H/2 + PM()*(H/2 + padH);\n\t\n\t\t// --------- définition aléatoire d'une cible à l'intérieur de la fenêtre, puis d'un delai pour activation\n\t \tfaitEntrer(this, 1500);\n\t\n\t\t// --------- lancement des fonction \"de base\"\n\t gereAcceleration(this);\n\t gereToc(this);\n\t gereAnt(this);\n\t move(this);\n\t }\n\t \n\t // --------- lancement du gendarme dès sa création\n\t this.start();\n\t}",
"function Basin(index, basinX, basinY, basinCap, basinWidth, basinHeight) {\n var isQuad = true;\n\n this.basinX = basinX;\n this.basinY = basinY;\n this.basinCap = basinCap;\n this.basinWidth = basinWidth;\n this.basinHeight = basinHeight;\n\n MAX_SIZE = basinWidth * basinHeight;\n basinSize = new Array(2);\n basinSize[0] = int((basinCap[0] + basinCap[1]) / agileModel.maxCap * MAX_SIZE);\n basinSize[1] = int( basinCap[0] / agileModel.maxCap * MAX_SIZE);\n CORNER_BEVEL = new Array(2);\n CORNER_BEVEL[0] = 10;\n CORNER_BEVEL[1] = 5;\n s = new Array(2);\n\n // Designate CellType\n for (var i=0; i<basinSize[0]; i++) {\n var u = basinX + i%basinWidth;\n var v = basinY + i/basinWidth;\n cellType[u][v][0] = \"SITE_\" + index;\n if (i<basinSize[1]) {\n cellType[u][v][1] = \"EXISTING\";\n } else {\n cellType[u][v][1] = \"GREENFIELD\";\n }\n }\n\n // Outline (0 = Existing Capacity; 1 = Greenfield Capacity);\n for (var i=0; i<2; i++) {\n \n if (basinSize[i]%basinWidth != 0) {\n isQuad = false;\n } else {\n isQuad = true;\n }\n \n beginShape();\n noFill();\n strokeWeight(2*CORNER_BEVEL[i]);\n\n if (i==0) {\n stroke(255, 150);\n } else {\n stroke(GSK_ORANGE);\n }\n\n vertex( - CORNER_BEVEL[i] + basinX*cellW, - CORNER_BEVEL[i] + basinY*cellH);\n vertex( + CORNER_BEVEL[i] + (basinX + basinWidth) * cellW, - CORNER_BEVEL[i] + basinY*cellH);\n if (isQuad) {\n vertex( + CORNER_BEVEL[i] + (basinX + basinWidth) * cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth) * cellH);\n vertex( - CORNER_BEVEL[i] + basinX*cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth) * cellH);\n } else {\n vertex( + CORNER_BEVEL[i] + (basinX + basinWidth) * cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth) * cellH);\n vertex( + CORNER_BEVEL[i] + (basinX + basinSize[i]%basinWidth) * cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth) * cellH);\n vertex( + CORNER_BEVEL[i] + (basinX + basinSize[i]%basinWidth) * cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth + 1) * cellH);\n vertex( - CORNER_BEVEL[i] + basinX*cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth + 1) * cellH);\n }\n vertex( - CORNER_BEVEL[i] + basinX*cellW, - CORNER_BEVEL[i] + basinY*cellH);\n\n endShape(CLOSE);\n }\n \n }",
"function PanelPestanas( elemento) {\n\tvar hijos=null;\n\ttry {\n\tthis.element = elemento;\n\tthis.element.tabPane = this;\n\tthis.element.className = this.classNameTag + \" \" + this.element.className;\n\tthis.pages = [];\n\tthis.selectedIndex = null;\n\t// Crea el tab-row para anadirlo al panel\n\tthis.tabRow = document.createElement(\"div\");\n\tthis.tabRow.className = \"tab-row\";\n\t// Inserta el tab-row como primer nodo hijo\n\telemento.insertBefore(this.tabRow, elemento.firstChild);\n\tthis.selectedIndex = 0;\n\t// Obtiene todos los nodos hijos del panel\n\thijos = elemento.childNodes;\n\t// Anade todos los hijos al panel de pestanas\n\tfor (var i = 0; i < hijos.length; i++) {\n\t\t// Debe hacer la comprobacion para no anadir el tab-row\n\t\tif (hijos[i].nodeType == 1 && hijos[i].className.indexOf(\"tab-page\")!=-1) {\n\t\t\tthis.addPestana(hijos[i]);\n }\n\t}\n\t}finally{\n\t\t\n\t\thijos=null;\n\t}\n}",
"init() {\n const squaresCopy = this.board.squares.slice(0);\n this.board.placePlayers(this.players, squaresCopy);\n this.board.placeWeapons(this.weapons, squaresCopy);\n this.board.placeWalls(this.nbOfWalls, squaresCopy);\n }",
"function Bone(/**\n * defines the bone name\n */name,skeleton,parentBone,localMatrix,restPose,baseMatrix,index){if(parentBone===void 0){parentBone=null;}if(localMatrix===void 0){localMatrix=null;}if(restPose===void 0){restPose=null;}if(baseMatrix===void 0){baseMatrix=null;}if(index===void 0){index=null;}var _this=_super.call(this,name,skeleton.getScene())||this;_this.name=name;/**\n * Gets the list of child bones\n */_this.children=new Array();/** Gets the animations associated with this bone */_this.animations=new Array();/**\n * @hidden Internal only\n * Set this value to map this bone to a different index in the transform matrices\n * Set this value to -1 to exclude the bone from the transform matrices\n */_this._index=null;_this._absoluteTransform=new BABYLON.Matrix();_this._invertedAbsoluteTransform=new BABYLON.Matrix();_this._scalingDeterminant=1;_this._worldTransform=new BABYLON.Matrix();_this._needToDecompose=true;_this._needToCompose=false;_this._skeleton=skeleton;_this._localMatrix=localMatrix?localMatrix.clone():BABYLON.Matrix.Identity();_this._restPose=restPose?restPose:_this._localMatrix.clone();_this._baseMatrix=baseMatrix?baseMatrix:_this._localMatrix.clone();_this._index=index;skeleton.bones.push(_this);_this.setParent(parentBone,false);if(baseMatrix||localMatrix){_this._updateDifferenceMatrix();}return _this;}",
"function createPanel( pw, ph, director ){\n\t\tdashBG = new CAAT.Foundation.ActorContainer().\n\t\t\t\t\tsetPreferredSize( pw, ph ).\n\t\t\t\t\tsetBounds( 0, 0, pw, ph ).\n\t\t\t\t\tsetClip(false);\n\n \n\t\t//create bottom panel\n\t\tfor(var i=0;i<dashBoardEle.length;i++){\n\t\t\tvar oActor = game.__addImageOnScene( game._director.getImage(dashBoardEle[i][0]), 1, 1 );\n\t\t\toActor.\t\t\t\n\t\t\t\tsetLocation(dashBoardEle[i][1], dashBoardEle[i][2]);\n\t\t\t\n\t\t\tdashBG.addChild(oActor);\t\t\t\n\t\t}\t\t\t\n\t\t\n\t\t__createDashBoardTxt();\n\t\t__createDashBoardButton();\t\n\t\t__createIncDecButton();\n\t\treturn dashBG;\n\t}",
"function creaPestanas() {\n\t/**ADAPTADO PARA MOZILLA**/\n\tif (atcl_navegador.esIE())\n\t{\n\t\tall = document.all;\n\t}\n\telse if (atcl_navegador.esFF())\n\t{\n\t\tall = document.forms[0];\n\t}\n\t/**FIN ADAPTACION**/\n\n\tvar numElementos = all.length;\n\tvar nombreClase, elemento;\n\tvar parentTabPane;\n\n\tfor ( var i = 0; i < numElementos; i++ ) {\n\t\telemento = all[i];\n\t\tnombreClase = elemento.className;\n\t\tif ( nombreClase.indexOf('tab-pane')!=-1 && !elemento.tabPane ){\n\t\t\tnew PanelPestanas( elemento );\n\t\t} else if (nombreClase.indexOf('tab-page')!=-1 &&\n\t\t !elemento.tabPage &&\n\t\t\t\t elemento.parentNode.className.indexOf('tab-pane')!=-1) {\n\t\t\telemento.parentNode.tabPane.addPestana(elemento);\n\t\t}\n\t}\n}",
"constructor(args) {\n\t\tsuper(args);\n\t\tthis.color = \"LightSalmon\";\n\t\tthis.name = \"Balloon\";\n\t\tthis.image.height = 60;\n\t\tthis.image.width = 34;\n\t\tthis.height = 60;\n\t\tthis.width = 34;\n\t}",
"function verbind(a, b){\n var verbonden = a.isVerbondenMet(b), verbindingen = '';\n \n if(verbonden){\n verbindingen = 'dubbel';\n a.nieuweBrug(b, 2);\n b.nieuweBrug(a, 2);\n } else {\n a.nieuweBrug(b, 1);\n b.nieuweBrug(a, 1);\n }\n \n if(a.pos.x === b.pos.x){\n // Geef de steden een stukje brug mee\n var min = Math.min(a.pos.y,b.pos.y);\n var max = Math.max(a.pos.y,b.pos.y);\n cells[min][a.pos.x].cell.addClass('onder-brug ' + (verbindingen ? 'onder-' + verbindingen : ''));\n cells[max][a.pos.x].cell.addClass('boven-brug ' + (verbindingen ? 'boven-' + verbindingen : ''));\n \n // Kijk tussen de beide cellen in\n for(var i=min+1; i<max; i++){\n cells[i][a.pos.x].cell.addClass('v-brug ' + verbindingen);\n cells[i][a.pos.x].weg = true;\n }\n \n } else if(a.pos.y === b.pos.y){\n // Geef de steden een stukje brug mee\n var min = Math.min(a.pos.x,b.pos.x);\n var max = Math.max(a.pos.x,b.pos.x);\n cells[a.pos.y][min].cell.addClass('rechts-brug ' + (verbindingen ? 'rechts-' + verbindingen : ''));\n cells[a.pos.y][max].cell.addClass('links-brug ' + (verbindingen ? 'links-' + verbindingen : ''));\n // Kijk tussen de beide cellen in\n for(var i=min+1; i<max; i++){\n cells[a.pos.y][i].cell.addClass('h-brug ' + verbindingen);\n cells[a.pos.y][i].weg = true;\n }\n }\n }",
"function bajarPlanta() {\n if (pisoActual > pisoMin) {\n removeFloors(pisoActual);\n removeMeasuresLayer();\n pisoActual--;\n addMeasuresLayer(pisoActual);\n addFloors(pisoActual);\n floors.addTo(map);\n }\n}",
"budgieSetup() {\n this.budgieContainer = BudgieDom.setupBudgieContainer(this);\n BudgieDom.setupBudgieCSS(this);\n BudgieDom.insertBudgieElements(this);\n BudgieDom.setupBudgieMouseDrag(this);\n // Only append extra items, and bind the scroll event if this is infinite scroll.\n if(this.options.infiniteScroll){\n this.appendEndingItems();\n this.prependStartingItems();\n BudgieDom.setupBudgieScrollProperties(this);\n }\n }",
"inicializa(){\n globais.flappyBird = criarFlappyBird();\n globais.canos = criarCanos();\n globais.chao = criarChao();\n }",
"function generarPaleta() {\n nombreColores.forEach(color => {\n $(`<div></div>`, {\n class:'color-paleta',\n style:`background-color:${color}`\n }).appendTo(paleta);\n });\n }",
"constructor() {\n this.nbPartiesAffichees = 0\n this.parties = [];\n \n this.afficher();\n }",
"function Pestana( elemento,indicePanel ) {\n\t// Inicializa los valores de la pestana\n\tthis.element = elemento;\n this.element.tabPage = this;\n this.index = indicePanel;\n\n\t// Busca el elemento tab en los hijos de la pestana\n var hijos = elemento.childNodes;\n for (var i = 0; i < hijos.length; i++) {\n\tif (hijos[i].nodeType == 1 && hijos[i].className.indexOf(\"tab\")!=-1 && hijos[i].className.indexOf(\"tab-\")==-1) {\n \t\t\tthis.tab = hijos[i];\n break;\n\t\t}\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decodes and retuns counts and weights of all cells | static getCellData({countsData, size = 1}) {
const numCells = countsData.length / 4;
const cellWeights = new Float32Array(numCells * size);
const cellCounts = new Uint32Array(numCells);
for (let i = 0; i < numCells; i++) {
// weights in RGB channels
for (let sizeIndex = 0; sizeIndex < size; sizeIndex++) {
cellWeights[i * size + sizeIndex] = countsData[i * 4 + sizeIndex];
}
// count in Alpha channel
cellCounts[i] = countsData[i * 4 + 3];
}
return {cellCounts, cellWeights};
} | [
"static countCells(prop) {\n let n = prop.range;\n n = (n & 0x15555)+(n>>1 & 0x15555);\n n = (n & 0x3333) +(n>>2 & 0x3333);\n n = (n & 0xf0f) +(n>>4 & 0xf0f);\n return (n & 0xff)+(n>>8 & 0xff);\n }",
"function weightCells(grid, row, col) {\n var cellWeight;\n\n\n if (grid[row][col].state == 1) {\n cellWeight = 2000;\n return cellWeight;\n }\n\n if(row == 0 || col == 0 || row == Constants.numberOfRows - 1 ||\n col == Constants.numberOfColumns - 1) {\n cellWeight = 0;\n return cellWeight;\n }\nif(row < Constants.numberOfRows/2) {\n rowDistance = row * 2;\n }\n else {\n rowDistance = (Constants.numberOfRows - row) * 2;\n }\n if(col < Constants.numberOfColumns/2) {\n colDistance = col * 2;\n }\n else {\n colDistance = (Constants.numberOfColumns - col) * 2;\n }\n return countLiveNeighbors(grid, row, col) + rowDistance + colDistance;\n}",
"GetNeighboringCellsWithWeights(x, y) {\n let output = [];\n let funcs = [ Math.floor, function(x) { return Math.floor(x) + 1; } ];\n\n x -= this.cell_size / 2.0;\n y -= this.cell_size / 2.0;\n\n x = Math.max(0, Math.min(this.window_size - this.cell_size, x));\n y = Math.max(0, Math.min(this.window_size - this.cell_size, y));\n\n for (let i = 0; i < 2; ++i) {\n let y_idx = this.ClipInRange(funcs[i](y / this.cell_size));\n let neighbor_y = y_idx * this.cell_size;\n let wy = 1.0 - Math.abs(y - neighbor_y) / this.cell_size;\n for (let j = 0; j < 2; ++j) {\n let x_idx = this.ClipInRange(funcs[j](x / this.cell_size));\n let neighbor_x = x_idx * this.cell_size;\n let wx = 1.0 - Math.abs(x - neighbor_x) / this.cell_size;\n output.push({x_idx : x_idx, y_idx : y_idx, weight : wx * wy});\n }\n }\n // Ensure that weights are normalized and sum to 1.\n let weight_sum = 0.0;\n for (let i = 0; i < output.length; ++i) {\n weight_sum += output[i].weight;\n }\n console.assert(weight_sum > 0.0);\n for (let i = 0; i < output.length; ++i) {\n output[i].weight /= weight_sum;\n }\n\n return output;\n }",
"updateNeighborCounts () {\n // for each cell in the grid\n\t\tfor (var column = 0; column < this.numberOfColumns; column++) {\n for (var row = 0; row < this.numberOfRows; row++) {\n\n\t\t\t\t// reset it's neighbor count to 0\n this.cells[column][row].liveNeighborCount = 0;\n\n\t\t\t\t// get the cell's neighbors\n\t\t\t\tthis.getNeighbors(this.cells[column][row]);\n\n\t\t\t\t// increase liveNeighborCount by 1 for each neighbor that is alive\n\t\t\t\tfor (var i = 0; i < this.getNeighbors(this.cells[column][row]).length; i++){\n\t\t\t\t\tif (this.getNeighbors(this.cells[column][row])[i].isAlive == true){\n\t\t\t\t\t\tthis.cells[column][row].liveNeighborCount += 1;\n\t\t\t\t\t}\n\t\t\t\t}\n }\n }\n\t}",
"getWeights(){\n return this.weights;\n }",
"function getAliveCount() {\n\tvar count = 0;\n\tcells.map(function(alive) {\n\t\tif (alive) count++;\n\t});\n\treturn count;\n}",
"getHiddenWeights() {\n return this._hiddenLayer.reduce(\n (acc, neuron) => acc.concat(neuron.getWeights()),\n []);\n }",
"function setMinesNegsCount(board) {\r\n var currSize = gLevels[gChosenLevelIdx].SIZE;\r\n for (var i = 0; i < currSize; i++) {\r\n for (var j = 0; j < currSize; j++) {\r\n var cell = board[i][j];\r\n var count = calculateNegs(board, i, j)\r\n cell.minesAroundCount = count;\r\n }\r\n }\r\n\r\n\r\n}",
"function krijgMogelijkheden(cell){\n var buren = [], pointer;\n \n // boven\n for(pointer = cell.boven(); pointer; pointer = pointer.boven()){\n if(pointer.stad){\n if(kanVerbinden(cell, pointer)) buren.push(pointer);\n break;\n }\n }\n \n // onder\n for(pointer = cell.onder(); pointer; pointer = pointer.onder()){\n if(pointer.stad){\n if(kanVerbinden(cell, pointer)) buren.push(pointer);\n break;\n }\n }\n \n // links\n for(pointer = cell.links(); pointer; pointer = pointer.links()){\n if(pointer.stad){\n if(kanVerbinden(cell, pointer)) buren.push(pointer);\n break;\n }\n }\n \n // rechts\n for(pointer = cell.rechts(); pointer; pointer = pointer.rechts()){\n if(pointer.stad){\n if(kanVerbinden(cell, pointer)) buren.push(pointer);\n break;\n }\n }\n \n return buren;\n }",
"allWeight(){\n let progress = 0;\n if(this.weightLog.length >= 2){\n progress = this.weightLog[this.weightLog.length-1].weight - this.weightLog[0].weight;\n }\n return {weights: this.weightLog, progress: progress};\n }",
"getInputWeights() {\n return this._inputLayer.reduce(\n (acc, neuron) => acc.concat(neuron.getWeights()),\n []);\n }",
"function weight(cw) {\n return w[cw & 0xf] + w[(cw >> 4) & 0xf] + w[(cw >> 8) & 0xf] +\n w[(cw >> 12) & 0xf] + w[(cw >> 16) & 0xf] + w[(cw >> 20) & 0xf];\n}",
"function AnalyzeCells(img1, anadir, depth, resultname, intensities, areas, cell_xs, cell_ys) { \n\tif (img1.getNSlices() >= frame)\n\t\timg1.setSlice(frame);\n\n\tvar img3 = img1.duplicate(); \t\t\n\tif (img3.getNSlices() >= frame)\n \t\timg3.setSlice(frame);\n\n\tvar h = img1.getHeight(); \n\tvar w = img1.getWidth(); \n\t// set image scale cm->um \n var cal = img1.getCalibration(); \n\tcm2um(cal); \n\tvar stats = img1.getStatistics(MEASUREMENTS); \n\tvar fullarea = stats.area; \n\tvar bgval = stats.dmode;\n\t \n\t//Open mask file \n var maskfile = anadir + \"Capture-mask-\"+anaversion+\".\" + maskformat; \n var mask = openIf(maskfile, maskformat); \n\tsetMask(mask, depth, false); \n\t \n // get ROI of cell body \n var rs = new RoiSet(); \n\tvar rsname = anadir+\"analysis-RoiSet\"+anaversion+\".zip\"; \n\tvar rsfile = new File(rsname); \n\t// if rsfile does not exist, can still use the rsmanager window \n\tif (rsfile.exists()) \n\t\trs.runCommand(\"Open\", rsname); \n \n if (rs.getName(1) != \"Cells\") { \n IJ.showMessage(\"Error\", \"ROI Manager not populated\"); \n exit; \n } \n // get xy coordinates to identify cells with wand tool \n var rois = rs.getRoisAsArray(); // returns Java array of ij.gui.Roi[]\n\tvar xs = rois[1].getPolygon().xpoints; // returns Java array of int[]\n var ys = rois[1].getPolygon().ypoints; // returns Java array of int[]\n \n // invert image \n invertImage(img1); \n var ic = new Packages.ij.plugin.ImageCalculator(); \n var img2 = ic.run(\"Max create stack\", img1, mask); \n\tif (img2.getNSlices() >= frame)\n\t\timg2.setSlice(frame);\n \n // invert image \n invertImage(img2); \n \n\t// return to original image for quantitation \n\tvar rs = new RoiSet(); \n \n // set image scale cm->um \n var maskcal = mask.getCalibration(); \n\tcm2um(maskcal); \n\tvar maskstats = mask.getStatistics(MEASUREMENTS); \n\t\n\t// this is where the cell outlines are stored as ROIs\n for (var i = 0; i < xs.length; i++) { \n IJ.doWand(mask, xs[i], ys[i], 0, \"4-connected\"); \n\t\tStoreRoi(mask, mask.getRoi(), resultname+\" \"+IJ.d2s(i,0), rs); \n } \n\n \t// save mask \n saveImage(img2, format, anadir, \"Capture-mask-\"+resultname+anaversion, 0); \n \n // save rois \n rs.runCommand(\"Select All\"); \n rs.runCommand(\"Save\", anadir + \"cell-\"+resultname+\"-RoiSet\"+anaversion+\".zip\"); \n var rois = rs.getRoisAsArray(); \n\n // set image scale cm->um \n var cal = img3.getCalibration(); \n\tcm2um(cal); \n\t// Measure mean intensity in original unmodified image \n\tfor (var i = 0; i < rois.length; i++) { \n\t\timg3.setRoi(rois[i]); \n rs.select(img3, i); \n var cellstats = img3.getStatistics(MEASUREMENTS); \n // copy cell intensity and xy position to global data arrays\n intensities[i] = cellstats.mean - bgval; // mean background-corrected cell intensity\n if (xs[i] > 0 && ys[i] > 0) {\n \tcell_xs[i] = xs[i];\n \tcell_ys[i] = ys[i];\n }\n \n // Measure cell area and copy to global data array\n areas[i] = 0; \n if (cellstats.area < fullarea) // Incorrectly drawn ROIs will cover the full frame \n\t areas[i] = cellstats.area; \n IJ.log(IJ.d2s(intensities[i], 0)); \n } \n \n\tif (!DEBUG) { \n\t\timg1.close(); \n\t\timg2.close(); \n\t\timg3.close(); \n\t\tmask.close(); \n\t} \n}",
"[calculateCellWidth](cellIndex) {\n\t\tconst self = this;\n\t\tlet width = self.columns()[cellIndex].currentWidth || 0;\n\n\t\tif (cellIndex === 0 && self.columns()[0].type !== COLUMN_TYPES.CHECKBOX ||\n\t\t\tcellIndex === 1 && self.columns()[0].type === COLUMN_TYPES.CHECKBOX) {\n\t\t\twidth -= self[INDENT_WIDTH];\n\t\t}\n\n\t\treturn width + PIXELS;\n\t}",
"function getIntArray() {\n var intArray = [];\n $('#week-table td').each(function() { \n if($(this).hasClass(\"busy\")){ \n intArray.push(2);\n }\n else if($(this).hasClass(\"free\")){\n intArray.push(1);\n }\n else{\n intArray.push(0);\n };\n });\n return intArray;\n }",
"countMines(board, w, h) {\n let count = 0\n for (let i = 0; i < w; i++) {\n for (let j = 0; j < h; j++) {\n count += board[j][i];\n }\n }\n return count;\n }",
"_getTensorData(tensor, dimHints) {\n const offset = tensor.offset;\n const size = tensor.size;\n const ctor = this._getConstructorFromType(tensor.type.dataType);\n const length = size / ctor.BYTES_PER_ELEMENT;\n const nchwdata = new ctor(this._weights, offset, length);\n if (typeof dimHints !== 'undefined' && dimHints.length !== 0) {\n if (OpenVINOUtils.product(dimHints) !== length) {\n throw new Error(`Product of ${dimHints} doesn't match the length ${length}`);\n }\n return nchwdata;\n } else {\n return nchwdata;\n }\n }",
"function initCellLookup()\n{\n // WE'LL PUT ALL THE VALUES IN HERE\n cellLookup = new Array();\n \n // TOP LEFT\n var topLeftArray = new Array( 1, 0, 1, 1, 0, 1);\n cellLookup[TOP_LEFT] = new CellType(3, topLeftArray);\n \n // TOP RIGHT\n var topRightArray = new Array(-1, 0, -1, 1, 0, 1);\n cellLookup[TOP_RIGHT] = new CellType(3, topRightArray);\n \n // BOTTOM LEFT\n var bottomLeftArray = new Array( 1, 0, 1, -1, 0, -1);\n cellLookup[BOTTOM_LEFT] = new CellType(3, bottomLeftArray);\n \n // BOTTOM RIGHT\n var bottomRightArray = new Array(-1, 0, -1, -1, 0, -1);\n cellLookup[BOTTOM_RIGHT]= new CellType(3, bottomRightArray);\n \n // TOP \n var topArray = new Array(-1, 0, -1, 1, 0, 1, 1, 1, 1, 0);\n cellLookup[TOP] = new CellType(5, topArray);\n \n // BOTTOM\n var bottomArray = new Array(-1, 0, -1, -1, 0, -1, 1, -1, 1, 0);\n cellLookup[BOTTOM] = new CellType(5, bottomArray);\n\n // LEFT\n var leftArray = new Array(0, -1, 1, -1, 1, 0, 1, 1, 0, 1);\n cellLookup[LEFT] = new CellType(5, leftArray);\n\n // RIGHT\n var rightArray = new Array(0, -1, -1, -1, -1, 0, -1, 1, 0, 1);\n cellLookup[RIGHT] = new CellType(5, rightArray);\n \n // CENTER\n var centerArray = new Array(-1, -1, -1, 0, -1, 1, 0, 1, 1, 1, 1, 0, 1, -1, 0, -1);\n cellLookup[CENTER] = new CellType(8, centerArray);\n}",
"function heapWeight(i) {\n return weights[heap[i]]\n }",
"WeightIs(fromVertex, toVertex) {\n let row;\n let col;\n\n row = IndexIs(vertices, fromVertex);\n col = IndexIs(vertices, toVertex);\n return edges[row][col];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses graph_ent and graph_ret events that were inserted by the Linux kernel's function graph trace. | function KernelFuncParser(importer) {
LinuxPerfParser.call(this, importer);
importer.registerEventHandler('graph_ent',
KernelFuncParser.prototype.traceKernelFuncEnterEvent.
bind(this));
importer.registerEventHandler('graph_ret',
KernelFuncParser.prototype.traceKernelFuncReturnEvent.
bind(this));
this.model_ = importer.model_;
this.ppids_ = {};
} | [
"parseEvent() {\n\t\tlet addr = ppos;\n\t\tlet delta = this.parseDeltaTime();\n\t\ttrackDuration += delta;\n\t\tlet statusByte = this.fetchBytes(1);\n\t\tlet data = [];\n\t\tlet rs = false;\n\t\tlet EOT = false;\n\t\tif (statusByte < 128) { // Running status\n\t\t\tdata.push(statusByte);\n\t\t\tstatusByte = runningStatus;\n\t\t\trs = true;\n\t\t} else {\n\t\t\trunningStatus = statusByte;\n\t\t}\n\t\tlet eventType = statusByte >> 4;\n\t\tlet channel = statusByte & 0x0F;\n\t\tif (eventType === 0xF) { // System events and meta events\n\t\t\tswitch (channel) { // System message types are stored in the last nibble instead of a channel\n\t\t\t// Don't really need these and probably nobody uses them but we'll keep them for completeness.\n\n\t\t\tcase 0x0: // System exclusive message -- wait for exit sequence\n\t\t\t\t// console.log('sysex');\n\t\t\t\tlet cbyte = this.fetchBytes(1);\n\t\t\t\twhile (cbyte !== 247) {\n\t\t\t\t\tdata.push(cbyte);\n\t\t\t\t\tcbyte = this.fetchBytes(1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 0x2:\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tbreak;\n\n\t\t\tcase 0x3:\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tbreak;\n\n\t\t\tcase 0xF: // Meta events: where some actually important non-music stuff happens\n\t\t\t\tlet metaType = this.fetchBytes(1);\n\t\t\t\tlet len;\n\t\t\t\tswitch (metaType) {\n\t\t\t\tcase 0x2F: // End of track\n\t\t\t\t\tthis.skip(1);\n\t\t\t\t\tEOT = true;\n\t\t\t\t\t// console.log('EOT');\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0x51:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\tdata.push(this.fetchBytes(len)); // All one value\n\t\t\t\t\tif (this.firstTempo === 0) {\n\t\t\t\t\t\t[this.firstTempo] = data;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x58:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t\t}\n\t\t\t\t\tif (this.firstBbar === 0) {\n\t\t\t\t\t\tthis.firstBbar = data[0] / 2 ** data[1];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\t// console.log('Mlen = '+len);\n\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\teventType = getIntFromBytes([0xFF, metaType]);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tconsole.log('parser error');\n\t\t\t}\n\t\t\tif (channel !== 15) {\n\t\t\t\teventType = statusByte;\n\t\t\t}\n\t\t\tchannel = -1; // global\n\t\t} else {\n\t\t\tswitch (eventType) {\n\t\t\tcase 0x9:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tif (data[1] === 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tlet ins;\n\t\t\t\t// var ins = currentInstrument[channel]; // Patch out percussion splitting\n\t\t\t\t// TODO: Patch back in, in a new way\n\t\t\t\tif (channel === 9) {\n\t\t\t\t\tthis.trks[tpos].hasPercussion = true;\n\t\t\t\t\t[ins] = data;\n\t\t\t\t} else {\n\t\t\t\t\tins = currentInstrument[channel];\n\t\t\t\t}\n\t\t\t\tlet note = new Note(trackDuration, data[0], data[1], ins, channel);\n\t\t\t\tif ((data[0] < this.trks[tpos].lowestNote && !this.trks[tpos].hasPercussion)\n || this.trks[tpos].lowestNote === null) {\n\t\t\t\t\t[this.trks[tpos].lowestNote] = data;\n\t\t\t\t}\n\t\t\t\tif (data[0] > this.trks[tpos].highestNote && !this.trks[tpos].hasPercussion) {\n\t\t\t\t\t[this.trks[tpos].highestNote] = data;\n\t\t\t\t}\n\t\t\t\tthis.trks[tpos].notes.push(note);\n\t\t\t\tif (isNotInArr(this.trks[tpos].usedInstruments, ins)) {\n\t\t\t\t\tthis.trks[tpos].usedInstruments.push(ins);\n\t\t\t\t}\n\t\t\t\tif (isNotInArr(this.trks[tpos].usedChannels, channel)) {\n\t\t\t\t\tthis.trks[tpos].usedChannels.push(channel);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 0xC:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\t// console.log(tpos+': '+data[0]);\n\t\t\t\tcurrentLabel = getInstrumentLabel(data[0]);\n\t\t\t\t// The last instrument on a channel ends where an instrument on the same channel begins\n\t\t\t\t// this.usedInstruments[tpos].push({ins: data[0], ch: channel, start: trackDuration});\n\t\t\t\t// if(notInArr(this.usedInstruments,data[0])){this.usedInstruments.push(data[0])} // Do this for now\n\t\t\t\t[currentInstrument[channel]] = data;\n\t\t\t\tbreak;\n\t\t\tcase 0xD:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t}\n\t\t\tfor (let i = 0; i < noteDelta.length; i++) {\n\t\t\t\tnoteDelta[i] += delta;\n\t\t\t}\n\t\t\tif (eventType === 0x9 && data[1] !== 0) {\n\t\t\t\t// console.log(bpbStuff);\n\t\t\t\tfor (let i = 1; i <= 16; i++) {\n\t\t\t\t\tlet x = (i * noteDelta[channel]) / this.timing;\n\t\t\t\t\tlet roundX = Math.round(x);\n\t\t\t\t\t// console.log(\"Rounded by: \" + roundX-x);\n\t\t\t\t\tthis.trks[tpos].quantizeErrors[i - 1] += Math.round(Math.abs((roundX - x) / i) * 100);\n\t\t\t\t}\n\t\t\t\tnoteDelta[channel] = 0;\n\t\t\t\tthis.noteCount++;\n\t\t\t}\n\t\t}\n\t\tthis.trks[tpos].events.push(new MIDIevent(delta, eventType, channel, data, addr));\n\t\t// console.log('+'+delta+': '+eventType+' @'+channel);\n\t\t// console.log(data);\n\t\t// this.debug++;\n\t\tif (this.debug > 0) {\n\t\t\treturn true;\n\t\t}\n\t\treturn EOT;// || this.debug>=4;\n\t}",
"parseEvent(event) {\n //logger.info(\"Parse event %j\", event);\n this.web3.eth\n .getTransaction(event.transactionHash)\n .then(transaction => {\n if (transaction.blockNumber > this.highestBlock) {\n this.lastReadBlock = transaction.blockNumber;\n }\n if (!transaction.input) {\n return logger.error(new Error(\"no transaction input found\"));\n }\n let decodedData;\n try {\n decodedData = abiDecoder.decodeMethod(transaction.input);\n } catch (e) {\n return logger.error(e);\n }\n this.eventCount++;\n\n if (!decodedData || !decodedData.name) {\n return logger.error(new Error(\"error decoding method\"));\n }\n\n // updateAccount(_ipfsHash string)\n // reply(_ipfsHash string)\n // share(_ipfsHash string)\n // saveBatch(_ipfsHash string)\n // post(_ipfsHash string)\n // createAccount(_name bytes16,_ipfsHash string)\n // tip(_author address,_messageID string,_ownerTip uint256,_ipfsHash string)\n\n // unFollow(_followee address)\n // setIsActive(_isActive bool)\n // follow(_followee address)\n // changeName(_name bytes16)\n // setNewAddress(_address address)\n // newAddress()\n // transferAccount(_address address)\n\n // isActive()\n // names( address)\n // addresses( bytes32)\n // owner()\n // accountExists(_addr address)\n // isValidName(bStr bytes16)\n // tipPercentageLocked()\n\n // cashout()\n // setMinSiteTipPercentage(newMinPercentage uint256)\n // interfaceInstances( uint256)\n // lockMinSiteTipPercentage()\n // interfaceInstanceCount()\n // minSiteTipPercentage()\n // transferOwnership(newOwner address)\n\n switch (decodedData.name) {\n case \"updateAccount\":\n case \"reply\":\n case \"share\":\n case \"saveBatch\":\n case \"post\":\n case \"createAccount\":\n case \"tip\":\n // these are functions that have an IPFS payload that needs to be resolved\n var hash = decodedData.params.find(function(element) {\n return element.name === \"_ipfsHash\";\n }).value;\n this.throttledIPFS.cat(hash).then(ipfsData => {\n decodedData.ipfsData = JSON.parse(ipfsData.toString());\n if (parsers[decodedData.name]) {\n parsers[decodedData.name](\n {\n throttledIPFS: this.throttledIPFS,\n web3: this.web3\n },\n decodedData,\n transaction\n );\n } else {\n logger.warn(\"No parser for function %s\", decodedData.name);\n process.exit();\n }\n });\n break;\n\n case \"unFollow\":\n case \"setIsActive\":\n case \"follow\":\n case \"changeName\":\n case \"setNewAddress\":\n case \"newAddress\":\n case \"transferAccount\":\n if (parsers[decodedData.name]) {\n parsers[decodedData.name](\n {\n throttledIPFS: this.throttledIPFS,\n web3: this.web3\n },\n decodedData,\n transaction\n );\n } else {\n logger.warn(\"No parser for function %s\", decodedData.name);\n process.exit();\n }\n break;\n\n case \"cashout\":\n case \"setMinSiteTipPercentage\":\n case \"lockMinSiteTipPercentage\":\n case \"transferOwnership\":\n // ignore these\n break;\n\n // case \"post\":\n // case \"reply\":\n // var hash = decodedData.params.find(function(element) {\n // return element.name === \"_ipfsHash\";\n // }).value;\n // this.throttledIPFS.cat(hash).then(ipfsData => {\n // logger.info(\"command=%s - Data=%s\", decodedData.name, ipfsData);\n // });\n // // this.parsePeep(found.value);\n // break;\n // case \"saveBatch\":\n // var hash = decodedData.params.find(function(element) {\n // return element.name === \"_ipfsHash\";\n // }).value;\n // this.throttledIPFS.cat(hash).then(ipfsData => {\n // logger.info(\"command=%s - Data=%s\", decodedData.name, ipfsData);\n // const s = JSON.parse(ipfsData.toString());\n // if (s.batchSaveJSON && Array.isArray(s.batchSaveJSON)) {\n // s.batchSaveJSON.forEach(batchItem => {\n // const command = Object.keys(batchItem)[0];\n // switch (command) {\n // case \"follow\":\n // case \"unfollow\":\n // case \"changeName\":\n // break;\n // case \"peep\":\n // if (batchItem[command].ipfs) {\n // this.parsePeep(batchItem[command].ipfs);\n // }\n // break;\n // case \"love\":\n // if (batchItem[command].messageID) {\n // this.parsePeep(batchItem[command].messageID);\n // }\n // break;\n // default:\n // logger.warn(\"unknown function %s %j\", command, batchItem);\n // process.exit();\n // break;\n // }\n // });\n // }\n // });\n // break;\n // case \"share\":\n // var hash = decodedData.params.find(function(element) {\n // return element.name === \"_ipfsHash\";\n // }).value;\n // this.throttledIPFS.cat(hash).then(ipfsData => {\n // logger.info(\"command=%s - Data=%s\", decodedData.name, ipfsData);\n // });\n // // options.pinner\n // // .pin(metaData.contract, found.value, this.defaultTtl)\n // // .then(() => {\n // // this.pinCount++;\n // // })\n // // .catch(e => {\n // // logger.warn(\"Error pinning: %s\", e.message);\n // // });\n // // this.throttledIPFS.cat(hash).then(ipfsData => {\n // // const s = JSON.parse(ipfsData.toString());\n // // if (s.pic && s.pic != \"\") {\n // // this.picHashes.push(s.pic);\n // // // options.pinner\n // // // .pin(metaData.contract, s.pic, this.defaultTtl)\n // // // .then(() => {\n // // // this.pinCount++;\n // // // })\n // // // .catch(e => {\n // // // logger.warn(\"Error pinning: %s\", e.message);\n // // // });\n // // }\n // // if (s.shareID && s.shareID != \"\") {\n // // // options.pinner\n // // // .pin(metaData.contract, s.shareID, this.defaultTtl)\n // // // .then(() => {\n // // // this.pinCount++;\n // // // })\n // // // .catch(e => {\n // // // logger.warn(\"Error pinning: %s\", e);\n // // // });\n // // }\n // // });\n // break;\n // case \"love\":\n // var found = decodedData.params.find(function(element) {\n // return element.name === \"messageID\";\n // });\n // // options.pinner\n // // .pin(metaData.contract, found.value, this.defaultTtl)\n // // .then(() => {\n // // this.pinCount++;\n // // })\n // // .catch(e => {\n // // logger.warn(\"Error pinning: %s\", e.message);\n // // });\n // break;\n // case \"follow\":\n // case \"unFollow\":\n // case \"changeName\":\n // // no IPFS involved here..\n // break;\n default:\n logger.warn(\"unknown function %s\", decodedData.name);\n process.exit();\n break;\n }\n })\n .catch(e => {\n logger.error(e);\n });\n }",
"function drawEvents()\n {\n g.each(function(d, i) {\n d.forEach( function(datum, index){\n var data = datum.times;\n var hasLabel = (typeof(datum.label) != \"undefined\");\n \n g.selectAll(\"svg\").data(data).enter()\n .append(display)\n .attr('x', getXPos)\n .attr(\"y\", getStackPosition)\n .attr(\"width\", function (d, i) {\n return (d.ending_time - d.starting_time) * scaleFactor;\n })\n .attr(\"cy\", getStackPosition)\n .attr(\"cx\", getXPos)\n .attr(\"r\", itemHeight/5)\n .attr(\"height\", itemHeight)\n .style(\"fill\", getColor)\n .on(\"mousemove\", function (d, i) {\n hover(d, index, datum);\n })\n .on(\"mouseover\", function (d, i) {\n mouseover(d, i, datum, IDs); \n })\n .on(\"mouseout\", function (d, i) {\n mouseout(d, i, datum, IDs); \n })\n .on(\"click\", function (d, i) {\n click(d, index, datum);\n })\n ;\n \n // 1D: keeping track of functionally equivalent events fe_id \n // 2D: keeping track of send/receive events sr_id \n for (i = 0; i < data.length; i++){\n var id; \n if (timelineType == \"1d\"){ \n id = data[i].fe_id;\n } \n else if (timelineType == \"2d\"){\n id = data[i].sr_id; \n }\n if (!(id in IDs)){ \n IDs[id] = [getXPos(data[i],i), getStackPosition(data[i],i)];\n } else {\n IDs[id].push(getXPos(data[i],i)); \n IDs[id].push(getStackPosition(data[i],i));\n }\n }\n labelHeight = itemHeight/2 + margin.top + (itemHeight + itemMargin) * yAxisMapping[index]+ 75; \n // update relative position of the legend \n if (labelHeight > legendHeight){\n legendHeight = labelHeight;\n }\n \n // add the label\n if (hasLabel) {\n gParent.append('text')\n .attr(\"class\", \"timeline-label\")\n .attr(\"transform\", \"translate(\"+ 0 +\",\"+ labelHeight+\")\")\n .text(hasLabel ? datum.label : datum.id);\n \n // 2D: draw the line for each entity beside the label\n if (timelineType == \"2d\"){\n g.append(\"line\")\n .attr(\"x1\", margin.left)\n .attr(\"y1\", labelHeight - itemHeight/2)\n .attr(\"x2\", width - margin.right)\n .attr(\"y2\", labelHeight - itemHeight/2)\n .style(\"stroke\",\"rgb(0,0,0)\");\n }\n }\n if (typeof(datum.icon) != \"undefined\") {\n gParent.append('image')\n .attr(\"class\", \"timeline-label\")\n .attr(\"transform\", \"translate(\"+ 0 +\",\"+ labelHeight +\")\")\n .attr(\"xlink:href\", datum.icon)\n .attr(\"width\", margin.left)\n .attr(\"height\", itemHeight);\n }\n\n function getStackPosition(d, i){\n if (stacked){\n return margin.top + (itemHeight + itemMargin) * yAxisMapping[index] + 75;\n }\n return margin.top + 75;\n }\n\n function getColor(d, i){\n if (d.class in eventColors){\n return eventColors[d.class];\n }\n return colorCycle(0);\n }\n\n function getXPos(d, i) {\n return margin.left + (d.starting_time - beginning) * scaleFactor;\n }\n });\n });\n } // drawEvents",
"function parseEvent (src, start, end) {\n let lineStr = src.substring(start, end).trim()\n let event = lineStr.match(EVENT_REGEX)\n if (event) {\n try {\n return {\n tag: event[1],\n description: event[2]\n }\n } catch (err) {\n console.error('EVENT_REGEX is invalid')\n return false\n }\n }\n return false\n }",
"function processTrace(trace, generator) {\n const processedSegments = trace.Segments.map(processSegment);\n const entireFunctionSegment = processedSegments.find(seg => seg.origin == \"AWS::Lambda\");\n const totalDuration = entireFunctionSegment.duration;\n const userDuration = processedSegments.find(seg => seg.origin == \"AWS::Lambda::Function\").duration;\n return {\n generatorID: generator.generatorID,\n runtime: generator.runtime,\n memory: generator.memory,\n packageSize: generator.packageSize,\n region: generator.region,\n vpc: generator.vpc,\n systemDuration: to3DPs(totalDuration - userDuration),\n userDuration: to3DPs(userDuration),\n totalDuration: to3DPs(totalDuration),\n traceId: trace.Id,\n startTime: entireFunctionSegment.startTime,\n startFullDateTime: new Date(entireFunctionSegment.startTime * 1000).toString()\n }\n}",
"function parseSimulationHistory(simulation_history){\n\tif(simulation_history!==null&&simulation_history!==''){\n\t\ttimestampList=[];\n\t\tcurrent_simulation_history_list=simulation_history.state;\n\t\t//iterate through all of the states\n\t\tfor (var i=0; i<current_simulation_history_list.length; i++){\n\t\t\ttimestamp=current_simulation_history_list[i].timestamp;\n\t\t\t//arranges all simulations by timestamp in a key value pair\n\t\t\tSimulationMap[timestamp]=current_simulation_history_list[i].simulation;\n\t\t\ttimestampList.push(timestamp);\n\t\t}\n\t\treturn timestampList;\n\t}\n\telse{\n\t\tconsole.log('parseSimulationHistory was passed a null simulation_history');\n\t}\n}",
"function normalizeOnEventArgs(args) {\n if (typeof args[0] === 'object') {\n return args;\n }\n \n var selector = null;\n var eventMap = {};\n var callback = args[args.length - 1];\n var events = args[0].split(\" \");\n \n for (var i = 0; i < events.length; i++) {\n eventMap[events[i]] = callback;\n }\n \n // Selector is the optional second argument, callback is always last.\n if (args.length === 3) {\n selector = args[1];\n }\n \n return [ eventMap, selector ];\n }",
"function addEventsToCfa() {\n addPanEvent(\".cfa-svg\");\n d3.selectAll(\".cfa-node\")\n .on(\"mouseover\", (d) => {\n let message;\n if (Number(d) > 100000) {\n message =\n '<span class=\" bold \">type</span>: function call node <br>' +\n '<span class=\" bold \">dblclick</span>: Select function';\n } else {\n const node = cfaJson.nodes.find((n) => n.index === Number(d));\n message = `<span class=\" bold \">function</span>: ${node.func}`;\n if (d in cfaJson.combinedNodes) {\n message += `<br><span class=\" bold \">combines nodes</span> : ${Math.min.apply(\n null,\n cfaJson.combinedNodes[d]\n )}-${Math.max.apply(null, cfaJson.combinedNodes[d])}`;\n }\n message += `<br> <span class=\" bold \">reverse postorder Id</span>: ${node.rpid}`;\n }\n showToolTipBox(d3.event, message);\n })\n .on(\"mouseout\", () => {\n hideToolTipBox();\n });\n d3.selectAll(\".fcall\").on(\"dblclick\", (d, i) => {\n angular.element($(\"#cfa-toolbar\")).scope().selectedCFAFunction = d3\n .select(`#cfa-node${i} text`)\n .text();\n angular.element($(\"#cfa-toolbar\").scope()).setCFAFunction();\n });\n d3.selectAll(\".cfa-dummy\")\n .on(\"mouseover\", () => {\n showToolTipBox(\n d3.event,\n '<span class=\" bold \">type</span>: placeholder <br> <span class=\" bold \">dblclick</span>: jump to Target node'\n );\n })\n .on(\"mouseout\", () => {\n hideToolTipBox();\n })\n .on(\"dblclick\", () => {\n if (!d3.select(\".marked-cfa-node\").empty()) {\n d3.select(\".marked-cfa-node\").classed(\"marked-cfa-node\", false);\n }\n const selection = d3.select(\n `#cfa-node${d3.select(this).attr(\"id\").split(\"-\")[1]}`\n );\n selection.classed(\"marked-cfa-node\", true);\n const boundingRect = selection.node().getBoundingClientRect();\n $(\"#cfa-container\")\n .scrollTop(boundingRect.top + $(\"#cfa-container\").scrollTop() - 300)\n .scrollLeft(\n boundingRect.left +\n $(\"#cfa-container\").scrollLeft() -\n $(\"#errorpath_section\").width() -\n 2 * boundingRect.width\n );\n });\n d3.selectAll(\".cfa-edge\")\n .on(\"mouseover\", function mouseover() {\n d3.select(this).select(\"path\").style(\"stroke-width\", \"3px\");\n showToolTipBox(\n d3.event,\n '<span class=\" bold \">dblclick</span>: jump to Source line'\n );\n })\n .on(\"mouseout\", function mouseout() {\n d3.select(this).select(\"path\").style(\"stroke-width\", \"1.5px\");\n hideToolTipBox();\n })\n .on(\"dblclick\", function dblclick(d, i) {\n let edge = findCfaEdge(i);\n if (edge === undefined) {\n // this occurs for edges between graphs - splitting edges\n const thisEdgeData = d3.select(this).attr(\"id\").split(\"_\")[1];\n edge = findCfaEdge({\n v: thisEdgeData.split(\"-\")[0],\n w: thisEdgeData.split(\"-\")[1],\n });\n }\n document.querySelector(\"#set-tab-3\").click();\n let { line } = edge;\n if (line === 0) {\n line = 1;\n }\n if (!d3.select(\".marked-source-line\").empty()) {\n d3.select(\".marked-source-line\").classed(\"marked-source-line\", false);\n }\n const selection = d3.select(`#source-${line} td pre.prettyprint`);\n selection.classed(\"marked-source-line\", true);\n $(\".sourceContent\").scrollTop(\n selection.node().getBoundingClientRect().top +\n $(\".sourceContent\").scrollTop() -\n 200\n );\n });\n d3.selectAll(\".cfa-split-edge\")\n .on(\"mouseover\", function mouseover() {\n d3.select(this).select(\"path\").style(\"stroke-width\", \"3px\");\n showToolTipBox(\n d3.event,\n '<span class=\" bold \">type</span>: place holder <br> <span class=\" bold \">dblclick</span>: jump to Original edge'\n );\n })\n .on(\"mouseout\", function mouseout() {\n d3.select(this).select(\"path\").style(\"stroke-width\", \"1.5px\");\n hideToolTipBox();\n })\n .on(\"dblclick\", function dblclick() {\n const edgeSourceTarget = d3.select(this).attr(\"id\").split(\"_\")[1];\n if (!d3.select(\".marked-cfa-edge\").empty()) {\n d3.select(\".marked-cfa-edge\").classed(\"marked-cfa-edge\", false);\n }\n const selection = d3.select(\n `#cfa-edge_${edgeSourceTarget.split(\"-\")[0]}-${\n edgeSourceTarget.split(\"-\")[1]\n }`\n );\n selection.classed(\"marked-cfa-edge\", true);\n const boundingRect = selection.node().getBoundingClientRect();\n $(\"#cfa-container\")\n .scrollTop(boundingRect.top + $(\"#cfa-container\").scrollTop() - 300)\n .scrollLeft(\n boundingRect.left +\n $(\"#cfa-container\").scrollLeft() -\n $(\"#errorpath_section\").width() -\n 2 * boundingRect.width\n );\n });\n}",
"function parseInteractionGraphic(graphic, graphIds) {\n let interaction = null;\n\n const {searchedGeneGraphIds, matchingGraphIds} = graphIds;\n\n const endGraphRefs = [];\n let numMatchingPoints = 0;\n let isConnectedToSourceGene = false;\n let ixnType = null;\n let searchedGeneIndex = null;\n\n Array.from(graphic.children).forEach(child => {\n if (child.nodeName !== 'Point') return;\n const point = child;\n const graphRef = point.getAttribute('GraphRef');\n if (graphRef === null) return;\n\n if (matchingGraphIds.includes(graphRef)) {\n numMatchingPoints += 1;\n endGraphRefs.push(graphRef);\n\n if (searchedGeneGraphIds.includes(graphRef)) {\n isConnectedToSourceGene = true;\n }\n\n if (point.getAttribute('ArrowHead')) {\n const arrowHead = point.getAttribute('ArrowHead');\n const isStart = searchedGeneGraphIds.includes(graphRef);\n if (searchedGeneIndex === null) {\n searchedGeneIndex = isStart ? 0 : 1;\n }\n try {\n ixnType = interactionArrowMap[arrowHead][isStart ? 0 : 1];\n } catch (e) {\n // TODO: Handle e.g. HGF, where arrowHead is very rare ReceptorSquare\n }\n }\n }\n });\n\n if (numMatchingPoints >= 2 && isConnectedToSourceGene) {\n if (searchedGeneIndex === null || ixnType === null) {\n ixnType = 'interacts with';\n }\n ixnType = ixnType[0].toUpperCase() + ixnType.slice(1);\n const interactionGraphId = graphic.parentNode.getAttribute('GraphId');\n interaction = {\n 'interactionId': interactionGraphId,\n 'endIds': endGraphRefs,\n ixnType\n };\n }\n\n return interaction;\n}",
"visitDml_event_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function preprocessGraphLayout(g) {\n g.graph().ranksep = \"70\";\n var nodes = g.nodes();\n for (var i = 0; i < nodes.length; i++) {\n var node = g.node(nodes[i]);\n node.padding = \"5\";\n\n var firstSeparator;\n var secondSeparator;\n var splitter;\n if (node.isCluster) {\n firstSeparator = secondSeparator = labelSeparator;\n splitter = \"\\\\n\";\n } else {\n firstSeparator = \"<span class='stageId-and-taskId-metrics'>\";\n secondSeparator = \"</span>\";\n splitter = \"<br>\";\n }\n\n node.label.split(splitter).forEach(function(text, i) {\n var newTexts = text.match(stageAndTaskMetricsPattern);\n if (newTexts) {\n node.label = node.label.replace(\n newTexts[0],\n newTexts[1] + firstSeparator + newTexts[2] + secondSeparator + newTexts[3]);\n }\n });\n }\n // Curve the edges\n var edges = g.edges();\n for (var j = 0; j < edges.length; j++) {\n var edge = g.edge(edges[j]);\n edge.lineInterpolate = \"basis\";\n }\n}",
"parseEntries() {}",
"function getOperations(){ //-------------> working\n\nvar count = codeLines.length;\n\nfor(var i=0; i<count; i++){ \n\n\t\tvar commentTest = (/@/.test(codeLines[i].charAt(0))); //Checking for comments\n\t\tvar textTest = (/.text/.test( codeLines[i])); //checking for .text keyword \n\t\tvar globalTest = /.global/.test( codeLines[i]); //checking for .global keyword\n\t\tvar mainTest = /main:/.test( codeLines[i]); //checking for main: label -------> Just for now!! should change later!!!!\n\t\tvar labelTest = labels.hasItem(codeLines[i]); \n\t\n\t\tif(!(commentTest||textTest||globalTest||mainTest||!codeLines[i]||labelTest)){ //(!codeLines[i]) check if the line is blank\n\n\t\t\tvar splitLine = codeLines[i].split(/[ ,\\t]+/).filter(Boolean); //-----> working. filter(Boolean) removes null values\n\t\t\tfunctionsHash.setItem(i, splitLine[0]); //Store function names with their line numbers\n\t\t\t\n\t\t}\n\t}\t\n}",
"function _generalParse(xml) {\n\t\tvar x2js = new X2JS();\n\t\tvar afterCnv = x2js.xml_str2json(xml);\n\t\tconsole.log(afterCnv);\n\t\treturn afterCnv;\n\t}",
"function getContractAddressToTraces(structLogs, startAddress) {\n var contractAddressToTraces = {};\n var currentTraceSegment = [];\n var addressStack = [startAddress];\n if (_.isEmpty(structLogs)) {\n return contractAddressToTraces;\n }\n // tslint:disable-next-line:prefer-for-of\n for (var i = 0; i < structLogs.length; i++) {\n var structLog = structLogs[i];\n if (structLog.depth !== addressStack.length - 1) {\n throw new Error(\"Malformed trace. Trace depth doesn't match call stack depth\");\n }\n // After that check we have a guarantee that call stack is never empty\n // If it would: callStack.length - 1 === structLog.depth === -1\n // That means that we can always safely pop from it\n currentTraceSegment.push(structLog);\n if (utils_2.utils.isCallLike(structLog.op)) {\n var currentAddress = _.last(addressStack);\n var newAddress = utils_2.utils.getAddressFromStackEntry(structLog.stack[structLog.stack.length - constants_1.constants.opCodeToParamToStackOffset[ethereum_types_1.OpCode.Call].to - 1]);\n // Sometimes calls don't change the execution context (current address). When we do a transfer to an\n // externally owned account - it does the call and immediately returns because there is no fallback\n // function. We manually check if the call depth had changed to handle that case.\n var nextStructLog = structLogs[i + 1];\n if (nextStructLog.depth !== structLog.depth) {\n addressStack.push(newAddress);\n contractAddressToTraces[currentAddress] = (contractAddressToTraces[currentAddress] || []).concat(currentTraceSegment);\n currentTraceSegment = [];\n }\n }\n else if (utils_2.utils.isEndOpcode(structLog.op)) {\n var currentAddress = addressStack.pop();\n contractAddressToTraces[currentAddress] = (contractAddressToTraces[currentAddress] || []).concat(currentTraceSegment);\n currentTraceSegment = [];\n if (structLog.op === ethereum_types_1.OpCode.SelfDestruct) {\n // After contract execution, we look at all sub-calls to external contracts, and for each one, fetch\n // the bytecode and compute the coverage for the call. If the contract is destroyed with a call\n // to `selfdestruct`, we are unable to fetch it's bytecode and compute coverage.\n // TODO: Refactor this logic to fetch the sub-called contract bytecode before the selfdestruct is called\n // in order to handle this edge-case.\n utils_1.logUtils.warn(\"Detected a selfdestruct. We currently do not support that scenario. We'll just skip the trace part for a destructed contract\");\n }\n }\n else if (structLog.op === ethereum_types_1.OpCode.Create) {\n // TODO: Extract the new contract address from the stack and handle that scenario\n utils_1.logUtils.warn(\"Detected a contract created from within another contract. We currently do not support that scenario. We'll just skip that trace\");\n return contractAddressToTraces;\n }\n else {\n if (structLog !== _.last(structLogs)) {\n var nextStructLog = structLogs[i + 1];\n if (nextStructLog.depth === structLog.depth) {\n continue;\n }\n else if (nextStructLog.depth === structLog.depth - 1) {\n var currentAddress = addressStack.pop();\n contractAddressToTraces[currentAddress] = (contractAddressToTraces[currentAddress] || []).concat(currentTraceSegment);\n currentTraceSegment = [];\n }\n else {\n throw new Error('Malformed trace. Unexpected call depth change');\n }\n }\n }\n }\n if (addressStack.length !== 0) {\n utils_1.logUtils.warn('Malformed trace. Call stack non empty at the end');\n }\n if (currentTraceSegment.length !== 0) {\n var currentAddress = addressStack.pop();\n contractAddressToTraces[currentAddress] = (contractAddressToTraces[currentAddress] || []).concat(currentTraceSegment);\n currentTraceSegment = [];\n utils_1.logUtils.warn('Malformed trace. Current trace segment non empty at the end');\n }\n return contractAddressToTraces;\n}",
"function getStyledEvents(_ref7) {\n var unsortedEvents = _ref7.events,\n entityKeyAccessor = _ref7.entityKeyAccessor,\n startAccessor = _ref7.startAccessor,\n endAccessor = _ref7.endAccessor,\n min = _ref7.min,\n totalMin = _ref7.totalMin,\n step = _ref7.step,\n _ref7$rightOffset = _ref7.rightOffset,\n rightOffset = _ref7$rightOffset === undefined ? 0 : _ref7$rightOffset;\n\n var OVERLAP_MULTIPLIER = 0.3;\n var events = sort(unsortedEvents, { startAccessor: startAccessor, endAccessor: endAccessor, entityKeyAccessor: entityKeyAccessor });\n var helperArgs = { events: events, startAccessor: startAccessor, endAccessor: endAccessor, min: min, totalMin: totalMin, step: step };\n var styledEvents = [];\n // idx of top-most, left-most event in each group of events\n var idx = 0;\n\n // One iteration will cover all connected events.\n\n var _loop = function _loop() {\n var siblings = getSiblings(idx, helperArgs);\n\n var _getChildGroups = getChildGroups(idx, idx + siblings.length + 1, helperArgs),\n childGroups = _getChildGroups.childGroups;\n\n // Calculate number of columns based on top level events plus\n // any overlapping child events to ensure all events share\n // space equally\n\n\n var nbrOfColumns = siblings.length + 1;\n [idx].concat(siblings).forEach(function (eventIdx, siblingIdx) {\n childGroups.forEach(function (group) {\n if (isChild(eventIdx, group[0], helperArgs)) {\n // nbrOfColumns is the max of number of top level events plus\n // number of nested child events. Some top level events have more overlapping\n // child events than others.\n nbrOfColumns = Math.max(nbrOfColumns, group.length + siblingIdx + 1);\n }\n });\n });\n\n // Width of the top level events\n var width = (100 - rightOffset) / nbrOfColumns;\n\n // Calculate how much of the width need to be extended so that\n // the events can appear to be underneath each other, as opposed\n // to blocks that are stacked next to each other\n var xAdjustment = width * (nbrOfColumns > 1 ? OVERLAP_MULTIPLIER : 0);\n\n // Set styles to top level events.\n [idx].concat(siblings).forEach(function (eventIdx, siblingIdx) {\n var _getYStyles = getYStyles(eventIdx, helperArgs),\n top = _getYStyles.top,\n height = _getYStyles.height;\n\n // Determines if this event is the last in the number of top\n // level events + their overlapping child events\n\n\n var isLastEvent = nbrOfColumns === siblingIdx + 1;\n\n styledEvents[eventIdx] = {\n event: events[eventIdx],\n style: {\n top: top,\n height: height,\n width: width + (isLastEvent ? 0 : xAdjustment),\n xOffset: width * siblingIdx\n }\n };\n });\n\n childGroups.forEach(function (group) {\n var parentIdx = idx;\n var siblingIdx = 0;\n\n // Move child group to sibling if possible, since this will makes\n // room for more events.\n while (isChild(siblings[siblingIdx], group[0], helperArgs)) {\n parentIdx = siblings[siblingIdx];\n siblingIdx++;\n }\n\n // Set styles to child events.\n group.forEach(function (eventIdx, i) {\n var parentStyle = styledEvents[parentIdx].style;\n\n // Calculate space occupied by parent to know how much space the child groups\n // can occupy\n\n var spaceOccupiedByParent = parentStyle.width + parentStyle.xOffset - xAdjustment;\n\n // Calculate width of each child event\n var childColumns = Math.min(group.length, nbrOfColumns);\n var childWidth = (100 - rightOffset - spaceOccupiedByParent) / childColumns;\n\n // Adjust event width so they appear underneath others\n var childXAdjustment = i + 1 === group.length ? 0 : childWidth * OVERLAP_MULTIPLIER;\n\n var _getYStyles2 = getYStyles(eventIdx, helperArgs),\n top = _getYStyles2.top,\n height = _getYStyles2.height;\n\n styledEvents[eventIdx] = {\n event: events[eventIdx],\n style: {\n top: top,\n height: height,\n width: childWidth + childXAdjustment,\n xOffset: spaceOccupiedByParent + childWidth * i\n }\n };\n });\n });\n\n // Move past all events we just went through\n idx += 1 + siblings.length + childGroups.reduce(function (total, group) {\n return total + group.length;\n }, 0);\n };\n\n while (idx < events.length) {\n _loop();\n }\n\n return styledEvents;\n}",
"function get_osf_scall_vtable(exp) {\n\tvar sr = exp.GetProcAddress(\"rpcrt4.dll\", \"NdrSendReceive\");\n\tif (sr == null) {\n\t\tlog(\"Can't find NdrSendReceive\");\n\t\treturn null;\n\t}\n\t\n\tvar modulebase = exp.find_module_base(sr);\n\tvar pattern1 = exp.find_pattern_in_module(modulebase, osf_scall_function_pattern);\n\tif (pattern1 == null) {\n\t\tlog(\"pattern1 not found\");\n\t\treturn null;\n\t}\n\tvar within_vtable = exp.find_pattern_in_module(modulebase, pattern1);\n\tif (within_vtable == null) {\n\t\t// RFG add 9 bytes before\n\t\twithin_vtable = exp.find_pattern_in_module(modulebase, pattern1.sub(9));\n\t\tif (within_vtable == null) {\n\t\t\tlog(\"pattern2 not found (pattern 1 was \" + pattern1.Stringify(16) + \") with or without rfg\");\n\t\t\treturn null;\n\t\t}\n\t}\n\treturn within_vtable.sub(0xe8); // Function position in the vtable\n}",
"function getNodePointers(callback) {\n\tvar nodes = [];\n\tvar deltas = [];\n\n\t// get all modification data\n\tcon.query('SELECT * FROM modifications;', function(err, result) {\n\t\t// clear mod table\n\t\tcon.query('DELETE FROM modifications;', function(err, res) {\n\t\t\tif (err) throw err;\n\t\t});\n\n\t\tfor (var i = 0; i < result.length; i++) {\n\t\t\tif (Math.abs(result[i].delta) > 0) {\n\t\t\t\tglobal.stableTree.traceFullSection(result[i].word.split(''), function(search_res) {\n\t\t\t\t\t// if search completed\n\t\t\t\t\tif (search_res.remainingBranch.length == 0) {\n\t\t\t\t\t\tnodes.push({node: search_res.node, delta: result[i].delta});\t// keep track of node pointer with delta\n\t\t\t\t\t\tdeltas.push(Math.abs(result[i].delta));\t// add delta abs value for alpha calculation later\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tcallback({nodes: nodes, deltas: deltas});\n\t});\n}",
"visitDml_event_nested_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function parseFuncResult() {\n var results = [];\n\n while (token.type !== _tokenizer.tokens.closeParen) {\n if (token.type !== _tokenizer.tokens.valtype) {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in func result\" + \", given \" + tokenToString(token));\n }();\n }\n\n var valtype = token.value;\n eatToken();\n results.push(valtype);\n }\n\n return results;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether identifier is covered by this Resource Name Permission. Returns `true` when identifier matches, otherwise return `false`. | matchIdentifier(permission) {
let identifier;
if (_.isString(permission)) {
identifier = (new RNPermission(permission)).identifier();
} else {
identifier = permission.identifier();
}
return globToRegex(this.identifier()).test(identifier);
} | [
"hasIdentifiers() {\n return this.__getIdentifiers() !== undefined;\n }",
"function hasAccessibleName(vNode) {\n // testing for when browsers give a <section> a region role:\n // chrome - always a region role\n // firefox - if non-empty aria-labelledby, aria-label, or title\n // safari - if non-empty aria-lablledby or aria-label\n //\n // we will go with safaris implantation as it is the least common\n // denominator\n const ariaLabelledby = sanitize(arialabelledbyText(vNode));\n const ariaLabel = sanitize(arialabelText(vNode));\n\n return !!(ariaLabelledby || ariaLabel);\n}",
"allows(...permissions) {\n const perms = _.flatten(permissions).map(e => new RNPermission(e));\n return perms.every(e => this.matchIdentifier(e) && this.matchPrivileges(e.privileges()));\n }",
"hasIdentifierDescriptor() {\n return this.__getIdentifierDescriptor() !== undefined;\n }",
"isAuthorized(permissionId, region) {\n return this.getPermission(permissionId, region).then((permission) => permission.isAuthorized);\n }",
"function extPart_getIsIdentifier(groupName, partName)\n{\n var partType = extPart.getPartType(groupName, partName);\n return (!partType || partType == \"identifier\");\n}",
"function roleExists(roleName){\r\n for (i = 0; i < Z_ROLES.length; i++) {\r\n var z_userrole = Z_ROLES[i].toString().substring(0,25).trim();\r\n\t if(z_userrole.toUpperCase() == roleName.toUpperCase()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}",
"is(name) {\n if (typeof name == 'string') {\n if (this.name == name) return true\n let group = this.prop(dist_NodeProp.group)\n return group ? group.indexOf(name) > -1 : false\n }\n return this.id == name\n }",
"function isValidAbility(id) {\n if (typeof id === 'undefined' || id == null) {\n return false;\n };\n if (typeof ABILITIES[id.toLowerCase()] === 'undefined') {\n return false;\n } else {\n return true;\n };\n}",
"hasCache(identifier) {\n validation_1.CacheValidation.validateIdentifier(identifier);\n return this._resources.has(identifier);\n }",
"function hasPermission(role, route) {\n // console.log(route.meta)\n if (route.meta && route.meta.roles) {\n return route.meta.roles.includes(role)\n } else {\n return true\n }\n}",
"isAnyAuthorized(permissionIds, region) {\n return this.getPermissions(permissionIds, region).then((permissions) =>\n permissions.some((permission) => permission.isAuthorized)\n );\n }",
"function hasAccessibleAcl(dataset) {\n return typeof dataset.internal_resourceInfo.aclUrl === \"string\";\n}",
"hasPrimaryIdentifierAttribute() {\n return this.__getPrimaryIdentifierAttribute({ autoFork: false }) !== undefined;\n }",
"function isIdentifier (s) {\n \treturn /^[a-z]+$/.test(s);\n}",
"hasPrivilege (privilege) {\n let user = this.get('currentUser');\n if (user) {\n return (user.privileges.indexOf(privilege) > -1);\n } else {\n return false;\n }\n }",
"function can(permissionsData, permission) {\n try {\n const permissions = JSON.parse(permissionsData);\n return permissions[permission];\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(`Error parsing permissions data: ${permissionsData}`);\n }\n return false;\n}",
"function canAffect(userRole, targetRole) {\n if (userRole === 'owner') {\n return true;\n }\n\n if (targetRole === 'owner') {\n return false;\n }\n\n return userRole === 'moderator' && targetRole === 'user';\n}",
"hasShield() {\n if (this.bot.supportFeature('doesntHaveOffHandSlot'))\n return false;\n const slot = this.bot.inventory.slots[this.bot.getEquipmentDestSlot('off-hand')];\n if (!slot)\n return false;\n return slot.name.includes('shield');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
use truncate string algorithm I wrote for freeCodeCamp to shorten quote for Twitter (140 chars), accounts for OprahQuotes hashtag | function shortQuote(quote) {
if(quote.length>250) {
quote = quote.slice(0,280);
return quote + "...";
} else return quote;
} | [
"function truncated(input) {\n\tif (input.length > 100) {\n\t\treturn input.substring(0, 100) + \"...\";\n\t}\n\treturn input;\n}",
"function shorten(string) {\n \n // MAX CHARACTER LIMIT\n var max_length = 25;\n \n // CHECK IF THE STRING IS LONGER THAN 22 CHARACTERS\n if (string.length > max_length) {\n\n // ALLOW THE FIRST 20 CHARACTERS AND TAG ON THE TRIPLEDOT\n string = string.substring(0, (max_length - 3));\n string += '...';\n }\n\n return string;\n}",
"function truncateIfLongerThanthis(inputString,length){\n if(inputString.length>length){\n return inputString.substr(0,length);\n }\n return inputString;\n\n}",
"function truncateWords (longText, numWords) {\n\t// 1. Use the split() function to split the String into an Array\n\tvar arrayOfText = longText.split(\" \");\n\t// 2. Use the length attribut to find the number of words in the Array\t\n\tvar lengthOfArray = arrayOfText.length;\n\t// 3. Determine how many words should be removed from the String\n\tvar remainingWords = lengthOfArray - numWords;\n\t// 4. Remove those words from the Array\n\tvar splicedArray = arrayOfText.splice(0, remainingWords);\n\t// 5. Add an additional String item to the Array to put an ellipses in: \"...\"\t\n\tarrayOfText.push(\"...\");\n\t// 6. Use the join() function to convert the Array back into a String\n\tvar joinedText = arrayOfText.join(\" \");\n\t// 7. Return the truncated String from the Function\n\treturn joinedText;\n}",
"function truncateString(str, length) {\n if(length >= str.length) return str\n else if(length <= 3) return str.slice(0, length) + '...'\n return str.slice(0, length - 3) + '...'\n}",
"function trimSongName(name) {\n if (name.length > 20) {\n return name.slice(0, 17).concat(\"...\");\n }\n else {\n return name;\n }\n}",
"function truncate(s, count) /* (s : string, count : int) -> string */ {\n return string_3(extend(first(s), $std_core._int_sub(count,1)));\n}",
"function makeStr(str) {\n\tif(str.length <= 35){\n\t\treturn str;\n\t} else {\n\t\tvar index = 35;\n\t\twhile(index >= 0) {\n\t\t\tif(str.charAt(index) === \" \") {\n\t\t\t\treturn str.substr(0, index+1) + \"...\";\n\t\t\t} else {\n\t\t\t\tindex--;\n\t\t\t}\n\t\t}\n\t\treturn str.substr(0, 36) + \" ...\";\n\t}\n}",
"function shorten(str) {\n // Don't shorten if adding the ... wouldn't make the string shorter\n if (!str || str.length < 10) {\n return str;\n }\n return `${str.substr(0, 3)}...${str.slice(-3)}`;\n}",
"function trimStringToMaxLength(string) {\n return string.length > config.maxlength ?\n string.substring(0, config.maxlength - 3) + \"...\" :\n string;\n}",
"generateSmallDescription(text){\r\n\t if(text){\r\n\t\tif(text.length > 120){\r\n\t\t text= text.slice(0,120) + '...';\r\n\t\t return text;\r\n\t\t}\r\n\t\telse{\r\n\t\t return text;\r\n\t\t}\r\n\t }\r\n\t}",
"function shortenName(name){\n var split, partA, partB, finalName;\n\n if($.getSizeClassification('medium_up') && name.length > 35){\n split = Math.floor((name.length - 1) / 4);\n partA = name.substring(0,split);\n partB = name.substring(name.length-split);\n finalName = partA + '...' + partB;\n }else if($.getSizeClassification('small') && name.length > 20){\n split = Math.floor((name.length - 1) / 8);\n partA = name.substring(0,split + 2 );\n partB = name.substring(name.length - (split + 1));\n finalName = partA + '...' + partB;\n }else{\n finalName = name;\n }\n return finalName;\n}",
"function shortenUrl ( url , length ) {\n\n if( !Ember.isBlank( url ) && url.length > length) {\n url = url.substr( 0 , length ) + \"...\";\n }\n\n return url;\n}",
"function limitWidth(string, len) {\n var lines = string.split('\\n');\n len = (typeof len === 'number') ? len : 80;\n var chars;\n for (var i = 0; i < lines.length; i++) {\n if (lines[i].length > len) {\n chars = lines[i].split('');\n lines[i] = lines[i].slice(0, len - 1);\n lines.splice(i + 1, 0, chars.slice(len - 1).join(''));\n }\n }\n return lines.join('\\n');\n}",
"function stringLimitDots(input,length){\n\tif(input!=undefined){\n\t\tif(input.length>length)\n\t\t\treturn input.substring(0,length)+'...';\n\t\treturn input;\n\t}\n\telse return '';\n}",
"function lookupTruncation(longname, object, minlen) {\n\tif (!minlen) minlen = 1;\n\twhile (longname.length > minlen) { \n\t\tlongname = longname.substr(0, longname.length-1);\n\t\tif (object[longname])\n\t\t\treturn longname;\n\t}\n\treturn null;\n}",
"function cleanGeneratedTweet(tweet) {\n if (!tweet) return '';\n var searchSpace = tweet.slice(0, -1);\n\n var endSep = searchSpace.lastIndexOf(separator);\n var endPunc = _(searchSpace).findIndex((c, i) => {\n if (i < 2) return false;\n var isAlpha = searchSpace[i-2].match(/^[a-z]$/i);\n var precedesNonAlpha = searchSpace[i-1].match(/^[^a-z]$/i);\n return isAlpha && precedesNonAlpha;\n });\n\n var end = (endSep == -1) ? endPunc : endSep;\n return tweet.slice(0, end)\n .replace(new RegExp(separator, 'g'), ' ')\n .replace(/\\s+/g, ' ');\n}",
"function trimSearchTerm(search) {\n var maxLength = 200;\n if (search.length > maxLength) {\n search = search.slice(0, maxLength);\n var lastColonPosition = search.lastIndexOf(\":\");\n if (lastColonPosition !== -1) {\n search = search.slice(0, lastColonPosition);\n }\n }\n return search;\n}",
"cut(s, suffix) {\n return (s.substring(0, s.length - suffix.length));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Warning dialog for example project loaded | function showProjectExampleLoadedDialogue() {
showDialog({
title: 'Example Project Loaded',
text: 'Example project has been successfuly loaded'.split('\n').join('<br>'),
negative: {
title: 'Continue'
}
})
} | [
"function showProjectLoadTypeFailDialogue() {\n showDialog({\n title: 'WARNING: Incorrect project type',\n text: 'Reselect a <b>DSS-Risk-Analysis-</b><ProjectTitle>.json file:\\nCurrent project unchanged'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}",
"function showRiskAssessmentWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nThe objective weights for each category must TOTAL 100 \\nProblem groups highlighted in red.'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}",
"function showImpactAssessmentWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nRows of risk weights should NOT EXCEED 100 for each area\\nProblem groups highlighted in red'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}",
"function showRiskCharacteristicsWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nColumns of risk weights must TOTAL 100\\nProblem groups highlighted in red'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}",
"createProject(event) {\n const controller = event.data.controller;\n const warning = new WarningDialog(() => {\n controller.createNewProject();\n }, () => {\n MenubarController.createAfterWarning = true;\n $('#saveProject')\n .click();\n }, () => {\n MenubarController.createAfterWarning = true;\n $('#exportProject')\n .click();\n }, null);\n if (controller.isDirty()) {\n warning.show();\n }\n else {\n warning.callbackContinue();\n }\n MenubarController.createAfterWarning = false;\n }",
"function showResultsWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nThe aggregated project weights must TOTAL 100 \\nProblem groups highlighted in red.'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}",
"openProject(event) {\n const controller = event.data.controller;\n ListDialog.type = 'openProject';\n const warning = new WarningDialog(() => {\n const dialog = new ListDialog(() => {\n if (dialog.selectedItems.length != 0) {\n dialog.selectedItems\n .forEach((value) => {\n controller.loadProject(value);\n });\n if (controller.persistenceController.getCurrentProject().version > BeastController.BEAST_VERSION) {\n InfoDialog.showDialog('This BEAST-version is older than the version this project was created with!<br>Some of of the components may be incompatible with this version.');\n }\n }\n }, controller.listProjects());\n dialog.show();\n }, () => {\n MenubarController.openAfterWarning = true;\n $('#saveProject')\n .click();\n }, () => {\n MenubarController.openAfterWarning = true;\n $('#exportProject')\n .click();\n }, null);\n if (controller.isDirty()) {\n warning.show();\n }\n else {\n warning.callbackContinue();\n }\n MenubarController.openAfterWarning = false;\n }",
"function Dialog() {}",
"showDeleteProjectDialog() {\n // hide project options dialog\n this.shadowRoot.getElementById(\"dialog-project-options\").close();\n\n // open delete dialog\n this.shadowRoot.getElementById(\"dialog-delete-project\").open();\n }",
"function showSetupDialog() {\n openDialog('/html/setup.html', 500, 660);\n}",
"showWarningMessage(msg) {\n return vscode.window.showWarningMessage(Constants.extensionDisplayName + ': ' + msg);\n }",
"function confirmerSuppression() {\n let n = new Noty({\n text: 'Confirmer la demande de suppression ',\n layout: 'center', theme: 'sunset', modal: true, type: 'info',\n animation: {\n open: 'animated lightSpeedIn',\n close: 'animated lightSpeedOut'\n },\n buttons: [\n Noty.button('Oui', 'btn btn-sm btn-success marge ', function () {\n supprimer();\n n.close();\n }),\n Noty.button('Non', 'btn btn-sm btn-danger', function () { n.close(); })\n ]\n }).show();\n}",
"function ShowDemoWindow(p_open = null) {\r\n done = false;\r\n // IM_ASSERT(ImGui.GetCurrentContext() !== null && \"Missing dear imgui context. Refer to examples app!\"); // Exceptionally add an extra assert here for people confused with initial dear imgui setup\r\n // Examples Apps (accessible from the \"Examples\" menu)\r\n /* static */ const show_app_documents = STATIC(\"show_app_documents\", false);\r\n /* static */ const show_app_main_menu_bar = STATIC(\"show_app_main_menu_bar\", false);\r\n /* static */ const show_app_console = STATIC(\"show_app_console\", false);\r\n /* static */ const show_app_log = STATIC(\"show_app_log\", false);\r\n /* static */ const show_app_layout = STATIC(\"show_app_layout\", false);\r\n /* static */ const show_app_property_editor = STATIC(\"show_app_property_editor\", false);\r\n /* static */ const show_app_long_text = STATIC(\"show_app_long_text\", false);\r\n /* static */ const show_app_auto_resize = STATIC(\"show_app_auto_resize\", false);\r\n /* static */ const show_app_constrained_resize = STATIC(\"show_app_constrained_resize\", false);\r\n /* static */ const show_app_simple_overlay = STATIC(\"show_app_simple_overlay\", false);\r\n /* static */ const show_app_window_titles = STATIC(\"show_app_window_titles\", false);\r\n /* static */ const show_app_custom_rendering = STATIC(\"show_app_custom_rendering\", false);\r\n /* static */ const show_backend_checker_window = STATIC(\"show_backend_checker_window\", false);\r\n if (show_app_documents.value)\r\n ShowExampleAppDocuments((value = show_app_documents.value) => show_app_documents.value = value);\r\n if (show_app_main_menu_bar.value)\r\n ShowExampleAppMainMenuBar();\r\n if (show_app_console.value)\r\n ShowExampleAppConsole((value = show_app_console.value) => show_app_console.value = value);\r\n if (show_app_log.value)\r\n ShowExampleAppLog((value = show_app_log.value) => show_app_log.value = value);\r\n if (show_app_layout.value)\r\n ShowExampleAppLayout((value = show_app_layout.value) => show_app_layout.value = value);\r\n if (show_app_property_editor.value)\r\n ShowExampleAppPropertyEditor((value = show_app_property_editor.value) => show_app_property_editor.value = value);\r\n if (show_app_long_text.value)\r\n ShowExampleAppLongText((value = show_app_long_text.value) => show_app_long_text.value = value);\r\n if (show_app_auto_resize.value)\r\n ShowExampleAppAutoResize((value = show_app_auto_resize.value) => show_app_auto_resize.value = value);\r\n if (show_app_constrained_resize.value)\r\n ShowExampleAppConstrainedResize((value = show_app_constrained_resize.value) => show_app_constrained_resize.value = value);\r\n if (show_app_simple_overlay.value)\r\n ShowExampleAppSimpleOverlay((value = show_app_simple_overlay.value) => show_app_simple_overlay.value = value);\r\n if (show_app_window_titles.value)\r\n ShowExampleAppWindowTitles();\r\n if (show_app_custom_rendering.value)\r\n ShowExampleAppCustomRendering((value = show_app_custom_rendering.value) => show_app_custom_rendering.value = value);\r\n if (show_backend_checker_window.value)\r\n ShowBackendCheckerWindow((value = show_backend_checker_window.value) => show_backend_checker_window.value = value);\r\n // Dear ImGui Apps (accessible from the \"Help\" menu)\r\n /* static */ const show_app_style_editor = STATIC(\"show_app_style_editor\", false);\r\n /* static */ const show_app_metrics = STATIC(\"show_app_metrics\", false);\r\n /* static */ const show_app_about = STATIC(\"show_app_about\", false);\r\n if (show_app_metrics.value) {\r\n ShowMetricsWindow((value = show_app_metrics.value) => show_app_metrics.value = value);\r\n }\r\n if (show_app_style_editor.value) {\r\n Begin(\"Style Editor\", (value = show_app_style_editor.value) => show_app_style_editor.value = value); /*ImGui.*/\r\n ShowStyleEditor();\r\n End();\r\n }\r\n if (show_app_about.value) {\r\n ShowAboutWindow((value = show_app_about.value) => show_app_about.value = value);\r\n }\r\n // Demonstrate the various window flags. Typically you would just use the default!\r\n /* static */ const no_titlebar = STATIC(\"no_titlebar\", false);\r\n /* static */ const no_scrollbar = STATIC(\"no_scrollbar\", false);\r\n /* static */ const no_menu = STATIC(\"no_menu\", false);\r\n /* static */ const no_move = STATIC(\"no_move\", false);\r\n /* static */ const no_resize = STATIC(\"no_resize\", false);\r\n /* static */ const no_collapse = STATIC(\"no_collapse\", false);\r\n /* static */ const no_close = STATIC(\"no_close\", false);\r\n /* static */ const no_nav = STATIC(\"no_nav\", false);\r\n /* static */ const no_background = STATIC(\"no_background\", false);\r\n /* static */ const no_bring_to_front = STATIC(\"no_bring_to_front\", false);\r\n let window_flags = 0;\r\n if (no_titlebar.value)\r\n window_flags |= ImGuiWindowFlags.NoTitleBar;\r\n if (no_scrollbar.value)\r\n window_flags |= ImGuiWindowFlags.NoScrollbar;\r\n if (!no_menu.value)\r\n window_flags |= ImGuiWindowFlags.MenuBar;\r\n if (no_move.value)\r\n window_flags |= ImGuiWindowFlags.NoMove;\r\n if (no_resize.value)\r\n window_flags |= ImGuiWindowFlags.NoResize;\r\n if (no_collapse.value)\r\n window_flags |= ImGuiWindowFlags.NoCollapse;\r\n if (no_nav.value)\r\n window_flags |= ImGuiWindowFlags.NoNav;\r\n if (no_background.value)\r\n window_flags |= ImGuiWindowFlags.NoBackground;\r\n if (no_bring_to_front.value)\r\n window_flags |= ImGuiWindowFlags.NoBringToFrontOnFocus;\r\n if (no_close.value)\r\n p_open = null; // Don't pass our bool* to Begin\r\n // We specify a default position/size in case there's no data in the .ini file. Typically this isn't required! We only do it to make the Demo applications a little more welcoming.\r\n SetNextWindowPos(new ImVec2(650, 20), ImGuiCond.FirstUseEver);\r\n SetNextWindowSize(new ImVec2(550, 680), ImGuiCond.FirstUseEver);\r\n // Main body of the Demo window starts here.\r\n if (!Begin(\"Dear ImGui Demo\", p_open, window_flags)) {\r\n // Early out if the window is collapsed, as an optimization.\r\n End();\r\n return done;\r\n }\r\n // Most \"big\" widgets share a common width settings by default.\r\n //ImGui.PushItemWidth(ImGui.GetWindowWidth() * 0.65); // Use 2/3 of the space for widgets and 1/3 for labels (default)\r\n PushItemWidth(GetFontSize() * -12); // Use fixed width for labels (by passing a negative value), the rest goes to widgets. We choose a width proportional to our font size.\r\n // Menu Bar\r\n if (BeginMenuBar()) {\r\n if (BeginMenu(\"Menu\")) {\r\n ShowExampleMenuFile();\r\n EndMenu();\r\n }\r\n if (BeginMenu(\"Examples\")) {\r\n MenuItem(\"Main menu bar\", null, (value = show_app_main_menu_bar.value) => show_app_main_menu_bar.value = value);\r\n MenuItem(\"Console\", null, (value = show_app_console.value) => show_app_console.value = value);\r\n MenuItem(\"Log\", null, (value = show_app_log.value) => show_app_log.value = value);\r\n MenuItem(\"Simple layout\", null, (value = show_app_layout.value) => show_app_layout.value = value);\r\n MenuItem(\"Property editor\", null, (value = show_app_property_editor.value) => show_app_property_editor.value = value);\r\n MenuItem(\"Long text display\", null, (value = show_app_long_text.value) => show_app_long_text.value = value);\r\n MenuItem(\"Auto-resizing window\", null, (value = show_app_auto_resize.value) => show_app_auto_resize.value = value);\r\n MenuItem(\"Constrained-resizing window\", null, (value = show_app_constrained_resize.value) => show_app_constrained_resize.value = value);\r\n MenuItem(\"Simple overlay\", null, (value = show_app_simple_overlay.value) => show_app_simple_overlay.value = value);\r\n MenuItem(\"Manipulating window titles\", null, (value = show_app_window_titles.value) => show_app_window_titles.value = value);\r\n MenuItem(\"Custom rendering\", null, (value = show_app_custom_rendering.value) => show_app_custom_rendering.value = value);\r\n MenuItem(\"Documents\", null, (value = show_app_documents.value) => show_app_documents.value = value);\r\n MenuItem(\"Backend-checker window\", null, (value = show_backend_checker_window.value) => show_backend_checker_window.value = value);\r\n EndMenu();\r\n }\r\n if (BeginMenu(\"Help\")) {\r\n MenuItem(\"Metrics\", null, (value = show_app_metrics.value) => show_app_metrics.value = value);\r\n MenuItem(\"Style Editor\", null, (value = show_app_style_editor.value) => show_app_style_editor.value = value);\r\n MenuItem(\"About Dear ImGui\", null, (value = show_app_about.value) => show_app_about.value = value);\r\n EndMenu();\r\n }\r\n EndMenuBar();\r\n }\r\n Text(`dear imgui says hello. (${IMGUI_VERSION})`);\r\n Spacing();\r\n if (CollapsingHeader(\"Help\")) {\r\n Text(\"PROGRAMMER GUIDE:\");\r\n BulletText(\"Please see the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!\");\r\n BulletText(\"Please see the comments in imgui.cpp.\");\r\n BulletText(\"Please see the examples/ in application.\");\r\n BulletText(\"Enable 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls.\");\r\n BulletText(\"Enable 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls.\");\r\n Separator();\r\n Text(\"USER GUIDE:\");\r\n /*ImGui.*/ ShowUserGuide();\r\n }\r\n if (CollapsingHeader(\"Configuration\")) {\r\n const io = GetIO();\r\n if (TreeNode(\"Configuration##2\")) {\r\n CheckboxFlags(\"io.ConfigFlags: NavEnableKeyboard\", (value = io.ConfigFlags) => io.ConfigFlags = value, ImGuiConfigFlags.NavEnableKeyboard);\r\n CheckboxFlags(\"io.ConfigFlags: NavEnableGamepad\", (value = io.ConfigFlags) => io.ConfigFlags = value, ImGuiConfigFlags.NavEnableGamepad);\r\n SameLine();\r\n HelpMarker(\"Required back-end to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\\n\\nRead instructions in imgui.cpp for details.\");\r\n CheckboxFlags(\"io.ConfigFlags: NavEnableSetMousePos\", (value = io.ConfigFlags) => io.ConfigFlags = value, ImGuiConfigFlags.NavEnableSetMousePos);\r\n SameLine();\r\n HelpMarker(\"Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos.\");\r\n CheckboxFlags(\"io.ConfigFlags: NoMouse\", (value = io.ConfigFlags) => io.ConfigFlags = value, ImGuiConfigFlags.NoMouse);\r\n if (io.ConfigFlags & ImGuiConfigFlags.NoMouse) // Create a way to restore this flag otherwise we could be stuck completely!\r\n {\r\n if ((GetTime() % 0.40) < 0.20) {\r\n SameLine();\r\n Text(\"<<PRESS SPACE TO DISABLE>>\");\r\n }\r\n if (IsKeyPressed(GetKeyIndex(ImGuiKey.Space)))\r\n io.ConfigFlags &= ~ImGuiConfigFlags.NoMouse;\r\n }\r\n CheckboxFlags(\"io.ConfigFlags: NoMouseCursorChange\", (value = io.ConfigFlags) => io.ConfigFlags = value, ImGuiConfigFlags.NoMouseCursorChange);\r\n SameLine();\r\n HelpMarker(\"Instruct back-end to not alter mouse cursor shape and visibility.\");\r\n Checkbox(\"io.ConfigInputTextCursorBlink\", (value = io.ConfigInputTextCursorBlink) => io.ConfigInputTextCursorBlink = value);\r\n SameLine();\r\n HelpMarker(\"Set to false to disable blinking cursor, for users who consider it distracting\");\r\n Checkbox(\"io.ConfigWindowsResizeFromEdges [beta]\", (value = io.ConfigWindowsResizeFromEdges) => io.ConfigWindowsResizeFromEdges = value);\r\n SameLine();\r\n HelpMarker(\"Enable resizing of windows from their edges and from the lower-left corner.\\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback.\");\r\n Checkbox(\"io.ConfigWindowsMoveFromTitleBarOnly\", (value = io.ConfigWindowsMoveFromTitleBarOnly) => io.ConfigWindowsMoveFromTitleBarOnly = value);\r\n Checkbox(\"io.MouseDrawCursor\", (value = io.MouseDrawCursor) => io.MouseDrawCursor = value);\r\n SameLine();\r\n HelpMarker(\"Instruct Dear ImGui to render a mouse cursor for you. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\\n\\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).\");\r\n TreePop();\r\n Separator();\r\n }\r\n if (TreeNode(\"Backend Flags\")) {\r\n HelpMarker(\"Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities.\");\r\n let backend_flags = io.BackendFlags; // Make a local copy to avoid modifying the back-end flags.\r\n CheckboxFlags(\"io.BackendFlags: HasGamepad\", (value = backend_flags) => backend_flags = value, ImGuiBackendFlags.HasGamepad);\r\n CheckboxFlags(\"io.BackendFlags: HasMouseCursors\", (value = backend_flags) => backend_flags = value, ImGuiBackendFlags.HasMouseCursors);\r\n CheckboxFlags(\"io.BackendFlags: HasSetMousePos\", (value = backend_flags) => backend_flags = value, ImGuiBackendFlags.HasSetMousePos);\r\n CheckboxFlags(\"io.BackendFlags: RendererHasVtxOffset\", (value = backend_flags) => backend_flags = value, ImGuiBackendFlags.RendererHasVtxOffset);\r\n TreePop();\r\n Separator();\r\n }\r\n if (TreeNode(\"Style\")) {\r\n /*ImGui.*/ ShowStyleEditor();\r\n TreePop();\r\n Separator();\r\n }\r\n if (TreeNode(\"Capture/Logging\")) {\r\n TextWrapped(\"The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded.\");\r\n HelpMarker(\"Try opening any of the contents below in this window and then click one of the \\\"Log To\\\" button.\");\r\n LogButtons();\r\n TextWrapped(\"You can also call ImGui.LogText() to output directly to the log without a visual output.\");\r\n if (Button(\"Copy \\\"Hello, world!\\\" to clipboard\")) {\r\n LogToClipboard();\r\n LogText(\"Hello, world!\");\r\n LogFinish();\r\n }\r\n TreePop();\r\n }\r\n }\r\n if (CollapsingHeader(\"Window options\")) {\r\n Checkbox(\"No titlebar\", (value = no_titlebar.value) => no_titlebar.value = value);\r\n SameLine(150);\r\n Checkbox(\"No scrollbar\", (value = no_scrollbar.value) => no_scrollbar.value = value);\r\n SameLine(300);\r\n Checkbox(\"No menu\", (value = no_menu.value) => no_menu.value = value);\r\n Checkbox(\"No move\", (value = no_move.value) => no_move.value = value);\r\n SameLine(150);\r\n Checkbox(\"No resize\", (value = no_resize.value) => no_resize.value = value);\r\n SameLine(300);\r\n Checkbox(\"No collapse\", (value = no_collapse.value) => no_collapse.value = value);\r\n Checkbox(\"No close\", (value = no_close.value) => no_close.value = value);\r\n SameLine(150);\r\n Checkbox(\"No nav\", (value = no_nav.value) => no_nav.value = value);\r\n SameLine(300);\r\n Checkbox(\"No background\", (value = no_background.value) => no_background.value = value);\r\n Checkbox(\"No bring to front\", (value = no_bring_to_front.value) => no_bring_to_front.value = value);\r\n }\r\n // All demo contents\r\n ShowDemoWindowWidgets();\r\n ShowDemoWindowLayout();\r\n ShowDemoWindowPopups();\r\n ShowDemoWindowColumns();\r\n ShowDemoWindowMisc();\r\n // End of ShowDemoWindow()\r\n End();\r\n return done;\r\n }",
"function displayHelp() {\n\tlet helpText = require('../html/help.html.js');\n\tcreateDialog('show-dialog', 'Help', helpText['helpDialog'], undefined, true);\n}",
"newWorkspaceDialog() {\n\t\tlet Dialog_SelectWorkspace = require(path.join(__rootdir, \"js\", \"dialogs\", \"selworkspace.js\"))\n\t\tnew Dialog_SelectWorkspace(600, \"\", (result) => {\n\t\t\tif(result === false)\n\t\t\t\treturn\n\t\t\t\n\t\t\tlet ws = wmaster.addWorkspace(result)\n\t\t\tthis.setWorkspace(ws)\n\t\t\t\n\t\t\t// display loading indicator\n\t\t\tthis.body.innerHTML = `<div class=\"abs-fill flex-col\" style=\"justify-content: center\"><div style=\"align-self: center\">...</dib></div>`\n\t\t})\n\t}",
"function help_OnClick()\n{\n\ntry {\n\tDVDOpt.ActivateHelp();\n}\n\ncatch(e) {\n //e.description = L_ERRORHelp_TEXT;\n\t//HandleError(e);\n\treturn;\n}\n\n}",
"function checkPlugin()\n{\n\tvar dllVer = getRequestParameter('dllVer');\n\tif (!dllVer || pageData.latestVersion != getRequestParameter('dllVer'))\n\t{\n\t\t$('#newPlugin').show();\n\t}\n}",
"static set helpBox(value) {}",
"function myWarning( _msg )\n{\n\tif( _msg.length != 0 )\n\t{\n\t\t$('#alert-warnings').html('<div style=\"margin-top: 6px; margin-bottom: 0px;\" class=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button><strong>Warning!</strong> ' + _msg + '</div>' )\n\t\t$('#alert-warnings').css('display','block')\n\t\t$('#divider-warnings').css('display','block')\n\t}\n\telse\n\t{\n\t\t$('#alert-warnings').css('display','none')\n\t\t$('#divider-warnings').css('display','none')\n\t}\n}",
"function insertWarningInDOM() {\n var oldvalue = \"\";\n document.getElementById(\"projectWarning\").innerHTML = oldvalue + getAvertissement();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hardwired values for speed. Equivalent of macro GET_OPCODE | static OPCODE(instruction) {
// POS_OP == 0 (shift amount)
// SIZE_OP == 6 (opcode width)
return instruction & 0x3f;
} | [
"op (code) {\n return this.byte(code, \"op\");\n }",
"function getBytecode() {\n console.log(web3.eth.getCode(crowdsale.address));\n//\"0x\"\n//data: '0x' + bytecode\n}",
"indexedIndirect() {\n this.incrementPc();\n let zeroPageAddress = (this.ram[this.cpu.pc] + this.cpu.xr) & 0xff\n let lo = this.ram[zeroPageAddress] & 0xff\n let hi = this.ram[zeroPageAddress + 1] & 0xff\n\n return (hi * 0x0100 + lo) & 0xffff\n }",
"function CPU () //the CPU emulation for SID/PRG playback (ToDo: CIA/VIC-IRQ/NMI/RESET vectors, BCD-mode)\n { //'IR' is the instruction-register, naming after the hardware-equivalent\n IR=memory[PC]; cycles=2; storadd=0; //'cycle': ensure smallest 6510 runtime (for implied/register instructions)\n \n if(IR&1) { //nybble2: 1/5/9/D:accu.instructions, 3/7/B/F:illegal opcodes\n switch (IR&0x1F) { //addressing modes (begin with more complex cases), PC wraparound not handled inside to save codespace\n case 1: case 3: addr = memory[memory[++PC]+X] + memory[memory[PC]+X+1]*256; cycles=6; break; //(zp,x)\n case 0x11: case 0x13: addr = memory[memory[++PC]] + memory[memory[PC]+1]*256 + Y; cycles=6; break; //(zp),y\n case 0x19: case 0x1F: addr = memory[++PC] + memory[++PC]*256 + Y; cycles=5; break; //abs,y\n case 0x1D: addr = memory[++PC] + memory[++PC]*256 + X; cycles=5; break; //abs,x\n case 0xD: case 0xF: addr = memory[++PC] + memory[++PC]*256; cycles=4; break; //abs\n case 0x15: addr = memory[++PC] + X; cycles=4; break; //zp,x\n case 5: case 7: addr = memory[++PC]; cycles=3; break; //zp\n case 0x17: addr = memory[++PC] + Y; cycles=4; break; //zp,y for LAX/SAX illegal opcodes\n case 9: case 0xB: addr = ++PC; cycles=2; //immediate\n }\n addr&=0xFFFF;\n switch (IR&0xE0) {\n case 0x60: T=A; A+=memory[addr]+(ST&1); ST&=20; ST|=(A&128)|(A>255); A&=0xFF; ST|=(!A)<<1 | (!((T^memory[addr])&0x80) && ((T^A)&0x80))>>1; break; //ADC\n case 0xE0: T=A; A-=memory[addr]+!(ST&1); ST&=20; ST|=(A&128)|(A>=0); A&=0xFF; ST|=(!A)<<1 | (((T^memory[addr])&0x80) && ((T^A)&0x80))>>1; break; //SBC\n case 0xC0: T=A-memory[addr]; ST&=124;ST|=(!(T&0xFF))<<1|(T&128)|(T>=0); break; //CMP\n case 0x00: A|=memory[addr]; ST&=125;ST|=(!A)<<1|(A&128); break; //ORA \n case 0x20: A&=memory[addr]; ST&=125;ST|=(!A)<<1|(A&128); break; //AND\n case 0x40: A^=memory[addr]; ST&=125;ST|=(!A)<<1|(A&128); break; //EOR\n case 0xA0: A=memory[addr]; ST&=125;ST|=(!A)<<1|(A&128); if((IR&3)==3) X=A; break; //LDA / LAX (illegal, used by my 1 rasterline player)\n case 0x80: memory[addr]=A & (((IR&3)==3)?X:0xFF); storadd=addr; //STA / SAX (illegal)\n }\n }\n \n else if(IR&2) { //nybble2: 2:illegal/LDX, 6:A/X/INC/DEC, A:Accu-shift/reg.transfer/NOP, E:shift/X/INC/DEC\n switch (IR&0x1F) { //addressing modes\n case 0x1E: addr = memory[++PC] + memory[++PC]*256 + ( ((IR&0xC0)!=0x80) ? X:Y ); cycles=5; break; //abs,x / abs,y\n case 0xE: addr = memory[++PC] + memory[++PC]*256; cycles=4; break; //abs\n case 0x16: addr = memory[++PC] + ( ((IR&0xC0)!=0x80) ? X:Y ); cycles=4; break; //zp,x / zp,y\n case 6: addr = memory[++PC]; cycles=3; break; //zp\n case 2: addr = ++PC; cycles=2; //imm.\n } \n addr&=0xFFFF; \n switch (IR&0xE0) {\n case 0x00: ST&=0xFE; case 0x20: if((IR&0xF)==0xA) { A=(A<<1)+(ST&1); ST&=60;ST|=(A&128)|(A>255); A&=0xFF; ST|=(!A)<<1; } //ASL/ROL (Accu)\n else { T=(memory[addr]<<1)+(ST&1); ST&=60;ST|=(T&128)|(T>255); T&=0xFF; ST|=(!T)<<1; memory[addr]=T; cycles+=2; } break; //RMW (Read-Write-Modify)\n case 0x40: ST&=0xFE; case 0x60: if((IR&0xF)==0xA) { T=A; A=(A>>1)+(ST&1)*128; ST&=60;ST|=(A&128)|(T&1); A&=0xFF; ST|=(!A)<<1; } //LSR/ROR (Accu)\n else { T=(memory[addr]>>1)+(ST&1)*128; ST&=60;ST|=(T&128)|(memory[addr]&1); T&=0xFF; ST|=(!T)<<1; memory[addr]=T; cycles+=2; } break; //RMW\n case 0xC0: if(IR&4) { memory[addr]--; memory[addr]&=0xFF; ST&=125;ST|=(!memory[addr])<<1|(memory[addr]&128); cycles+=2; } //DEC\n else {X--; X&=0xFF; ST&=125;ST|=(!X)<<1|(X&128);} break; //DEX\n case 0xA0: if((IR&0xF)!=0xA) X=memory[addr]; else if(IR&0x10) {X=SP;break;} else X=A; ST&=125;ST|=(!X)<<1|(X&128); break; //LDX/TSX/TAX\n case 0x80: if(IR&4) {memory[addr]=X;storadd=addr;} else if(IR&0x10) SP=X; else {A=X; ST&=125;ST|=(!A)<<1|(A&128);} break; //STX/TXS/TXA\n case 0xE0: if(IR&4) { memory[addr]++; memory[addr]&=0xFF; ST&=125;ST|=(!memory[addr])<<1|(memory[addr]&128); cycles+=2; } //INC/NOP\n }\n }\n \n else if((IR&0xC)==8) { //nybble2: 8:register/status\n switch (IR&0xF0) {\n case 0x60: SP++; SP&=0xFF; A=memory[0x100+SP]; ST&=125;ST|=(!A)<<1|(A&128); cycles=4; break; //PLA\n case 0xC0: Y++; Y&=0xFF; ST&=125;ST|=(!Y)<<1|(Y&128); break; //INY\n case 0xE0: X++; X&=0xFF; ST&=125;ST|=(!X)<<1|(X&128); break; //INX\n case 0x80: Y--; Y&=0xFF; ST&=125;ST|=(!Y)<<1|(Y&128); break; //DEY\n case 0x00: memory[0x100+SP]=ST; SP--; SP&=0xFF; cycles=3; break; //PHP\n case 0x20: SP++; SP&=0xFF; ST=memory[0x100+SP]; cycles=4; break; //PLP\n case 0x40: memory[0x100+SP]=A; SP--; SP&=0xFF; cycles=3; break; //PHA\n case 0x90: A=Y; ST&=125;ST|=(!A)<<1|(A&128); break; //TYA\n case 0xA0: Y=A; ST&=125;ST|=(!Y)<<1|(Y&128); break; //TAY\n default: if(flagsw[IR>>5]&0x20) ST|=(flagsw[IR>>5]&0xDF); else ST&=255-(flagsw[IR>>5]&0xDF); //CLC/SEC/CLI/SEI/CLV/CLD/SED\n }\n }\n \n else { //nybble2: 0: control/branch/Y/compare 4: Y/compare C:Y/compare/JMP\n if ((IR&0x1F)==0x10) { PC++; T=memory[PC]; if(T&0x80) T-=0x100; //BPL/BMI/BVC/BVS/BCC/BCS/BNE/BEQ relative branch \n if(IR&0x20) {if (ST&branchflag[IR>>6]) {PC+=T;cycles=3;}} else {if (!(ST&branchflag[IR>>6])) {PC+=T;cycles=3;}} } \n else { //nybble2: 0:Y/control/Y/compare 4:Y/compare C:Y/compare/JMP\n switch (IR&0x1F) { //addressing modes\n case 0: addr = ++PC; cycles=2; break; //imm. (or abs.low for JSR/BRK)\n case 0x1C: addr = memory[++PC] + memory[++PC]*256 + X; cycles=5; break; //abs,x\n case 0xC: addr = memory[++PC] + memory[++PC]*256; cycles=4; break; //abs\n case 0x14: addr = memory[++PC] + X; cycles=4; break; //zp,x\n case 4: addr = memory[++PC]; cycles=3; //zp\n } \n addr&=0xFFFF; \n switch (IR&0xE0) {\n case 0x00: memory[0x100+SP]=PC%256; SP--;SP&=0xFF; memory[0x100+SP]=PC/256; SP--;SP&=0xFF; memory[0x100+SP]=ST; SP--;SP&=0xFF; \n PC = memory[0xFFFE]+memory[0xFFFF]*256-1; cycles=7; break; //BRK\n case 0x20: if(IR&0xF) { ST &= 0x3D; ST |= (memory[addr]&0xC0) | ( !(A&memory[addr]) )<<1; } //BIT\n else { memory[0x100+SP]=(PC+2)%256; SP--;SP&=0xFF; memory[0x100+SP]=(PC+2)/256; SP--;SP&=0xFF; PC=memory[addr]+memory[addr+1]*256-1; cycles=6; } break; //JSR\n case 0x40: if(IR&0xF) { PC = addr-1; cycles=3; } //JMP\n else { if(SP>=0xFF) return 0xFE; SP++;SP&=0xFF; ST=memory[0x100+SP]; SP++;SP&=0xFF; T=memory[0x100+SP]; SP++;SP&=0xFF; PC=memory[0x100+SP]+T*256-1; cycles=6; } break; //RTI\n case 0x60: if(IR&0xF) { PC = memory[addr]+memory[addr+1]*256-1; cycles=5; } //JMP() (indirect)\n else { if(SP>=0xFF) return 0xFF; SP++;SP&=0xFF; T=memory[0x100+SP]; SP++;SP&=0xFF; PC=memory[0x100+SP]+T*256-1; cycles=6; } break; //RTS\n case 0xC0: T=Y-memory[addr]; ST&=124;ST|=(!(T&0xFF))<<1|(T&128)|(T>=0); break; //CPY\n case 0xE0: T=X-memory[addr]; ST&=124;ST|=(!(T&0xFF))<<1|(T&128)|(T>=0); break; //CPX\n case 0xA0: Y=memory[addr]; ST&=125;ST|=(!Y)<<1|(Y&128); break; //LDY\n case 0x80: memory[addr]=Y; storadd=addr; //STY\n }\n }\n }\n \n PC++; PC&=0xFFFF; return 0; //memory[addr]&=0xFF; \n }",
"function get_value(loc, mode, intcode) {\r\n if (mode == 0) {\r\n // position mode\r\n return intcode[loc];\r\n } else if (mode == 1) {\r\n // immediate mode\r\n return loc;\r\n }\r\n}",
"function get_var_operand_types(operands_byte, operands_type) {\r\n for (var i = 0; i < 4; i++) {\r\n operands_type.push((operands_byte & 0xC0) >> 6);\r\n operands_byte <<= 2;\r\n }\r\n }",
"fetch() {\n const nextInstructionAddress = this.getRegister(\"ip\");\n const instruction = this.memory.getUint8(nextInstructionAddress);\n this.setRegister(\"ip\", nextInstructionAddress + 1);\n return instruction;\n }",
"loadNextInstruction() {\n switch (this.opCode) {\n case 0:\n this.instructionCounter = 0;\n break;\n case 40:\n this.instructionCounter = this.operand;\n break;\n case 41:\n if (this.accumulator < 0) {\n this.instructionCounter = this.operand;\n } else {\n this.instructionCounter++;\n }\n break;\n case 42:\n if (this.accumulator === 0) {\n this.instructionCounter = this.operand;\n } else {\n this.instructionCounter++;\n }\n break;\n default:\n this.instructionCounter++;\n break;\n }\n\n this.instructionRegister = this.memory[this.instructionCounter];\n this.opCode = Number.parseInt(('' + this.instructionRegister).substring(0, 2));\n this.operand = Number.parseInt(('' + this.instructionRegister).substring(2, 4));\n }",
"function get_var_operand_types( operands_byte, operands_type )\n\t{\n\t\tfor ( var i = 0; i < 4; i++ )\n\t\t{\n\t\t\toperands_type.push( (operands_byte & 0xC0) >> 6 );\n\t\t\toperands_byte <<= 2;\n\t\t}\n\t}",
"function assemblyToMachine(lineNumber, instructionAddress, instruction) {\n // format of the instruction should be an array of fields starting with opcode\n let opcode = instruction[0], immediate, jumpDistance;\n\n if(PSEUDO_OPS.includes(opcode)) {\n switch(opcode) {\n case 'li': // li rd imm --> addiu rd $zero imm\n opcode = 'addiu';\n instruction.splice(2, 0, '$zero');\n break;\n case 'move': // move rd, rt --> addu rd, $zero, rt\n opcode = 'addu';\n instruction.splice(2, 0, '$zero');\n break;\n case 'neg': // neg rd, rt --> sub rd, $zero, rt\n opcode = 'sub';\n instruction.splice(2, 0, '$zero');\n break;\n }\n }\n\n if(!(opcode in OPCODES)) return syntaxError(lineNumber, 'This instruction does not have a valid opcode');\n\n switch(opcode) {\n // R-Type: 6op 5rs 5rt 5rd 5shamt 6funct\n // op rd, rs, rt\n case 'add': case 'addu': case 'and': case 'nor': case 'or': case 'slt': case 'sltu': case 'sub': case 'subu': case 'xor':\n if(instruction.length != 4) return syntaxError(lineNumber, 'This instruction requires 3 parameters');\n if(!(instruction[1] in REGISTERS && instruction[2] in REGISTERS && instruction[3] in REGISTERS)) return syntaxError(lineNumber, 'All 3 parameters should be valid registers');\n return REGISTERS[instruction[2]] << 21 | REGISTERS[instruction[3]] << 16 | REGISTERS[instruction[1]] << 11 | OPCODES[opcode][1];\n // op rd, rt, rs\n case 'sllv': case 'srav': case 'srlv':\n if(instruction.length != 4) return syntaxError(lineNumber, 'This instruction requires 3 parameters');\n if(!(instruction[1] in REGISTERS && instruction[2] in REGISTERS && instruction[3] in REGISTERS)) return syntaxError(lineNumber, 'All 3 parameters should be valid registers');\n return REGISTERS[instruction[3]] << 21 | REGISTERS[instruction[2]] << 16 | REGISTERS[instruction[1]] << 11 | OPCODES[opcode][1];\n // op rd, rt, sa\n case 'sll': case 'sra': case 'srl':\n if(instruction.length != 4) return syntaxError(lineNumber, 'This instruction requires 3 parameters');\n if(!(instruction[1] in REGISTERS && instruction[2] in REGISTERS)) return syntaxError(lineNumber, 'Both parameters should be valid registers');\n if(instruction[3] > 0b11111 || instruction[3] < 0) return syntaxError(lineNumber, 'Shift amount cannot be more than 31 or less than 0');\n return REGISTERS[instruction[2]] << 16 | REGISTERS[instruction[1]] << 11 | instruction[3] << 6 | OPCODES[opcode][1];\n // op rs, rt\n case 'div': case 'divu': case 'mult': case 'multu':\n if(instruction.length != 3) return syntaxError(lineNumber, 'This instruction requires 2 parameters');\n if(!(instruction[1] in REGISTERS && instruction[2] in REGISTERS)) return syntaxError(lineNumber, 'Both parameters should be valid registers');\n return REGISTERS[instruction[1]] << 21 | REGISTERS[instruction[2]] << 16 | OPCODES[opcode][1];\n // op rd, rs | op rs\n case 'jalr':\n if(instruction.length == 3) {\n if(!(instruction[1] in REGISTERS && instruction[2] in REGISTERS)) return syntaxError(lineNumber, 'Both parameters should be valid registers');\n return REGISTERS[instruction[2]] << 21 | REGISTERS[instruction[1]] << 11 | OPCODES[opcode][1];\n }\n else if(instruction.length == 2) {\n if(!(instruction[1] in REGISTERS)) return syntaxError(lineNumber, 'The parameter should be a valid register');\n return REGISTERS[instruction[1]] << 21 | 0b11111 << 11 | OPCODES[opcode][1];\n }\n else return syntaxError(lineNumber, 'This instruction requires either 1 or 2 parameters');\n // op rs\n case 'jr': case 'mthi': case 'mtlo':\n if(instruction.length != 2) return syntaxError(lineNumber, 'This instruction requires 1 parameter');\n if(!(instruction[1] in REGISTERS)) return syntaxError(lineNumber, 'The parameter should be a valid register');\n return REGISTERS[instruction[1]] << 21 | OPCODES[opcode][1];\n // op rd\n case 'mfhi': case 'mflo':\n if(instruction.length != 2) return syntaxError(lineNumber, 'This instruction requires 1 parameter');\n if(!(instruction[1] in REGISTERS)) return syntaxError(lineNumber, 'The parameter should be a valid register');\n return REGISTERS[instruction[1]] << 11 | OPCODES[opcode][1];\n // op\n case 'syscall': case 'break': case 'nop':\n if(instruction.length != 1) return syntaxError(lineNumber, 'This instruction requires 0 parameters');\n return OPCODES[opcode][1];\n \n // I-type 6op 5rs 5rt 16imm\n // op rt, rs, imm\n case 'addi': case 'addiu': case 'andi': case 'ori': case 'slti': case 'sltiu': case 'xori':\n if(instruction.length != 4) return syntaxError(lineNumber, 'This instruction requires 3 parameters');\n if(!(instruction[1] in REGISTERS && instruction[2] in REGISTERS)) return syntaxError(lineNumber, 'First two parameters should be valid registers');\n if(instruction[3] > 32767 || instruction[3] < -32768) return syntaxError(lineNumber, \"Immediate value is not representable within 2's complement 16 bits\");\n immediate = instruction[3] & 0xffff;\n return OPCODES[opcode] << 26 | REGISTERS[instruction[2]] << 21 | REGISTERS[instruction[1]] << 16 | immediate;\n // op rs, rt, label *** Label has been converted to it's memory location prior to this function being called\n case 'beq': case 'bne':\n if(instruction.length != 4) return syntaxError(lineNumber, 'This instruction requires 3 parameters');\n if(!(instruction[1] in REGISTERS && instruction[2] in REGISTERS)) return syntaxError(lineNumber, 'First two parameters should be valid registers');\n jumpDistance = (instruction[3] - instructionAddress) / 4;\n if(jumpDistance > 32767 || jumpDistance < -32768) return syntaxError(lineNumber, \"Branching distance is not representable within 2's complement 16 bits (the label is too far away)\");\n immediate = jumpDistance & 0xffff;\n return OPCODES[opcode] << 26 | REGISTERS[instruction[1]] << 21 | REGISTERS[instruction[2]] << 16 | immediate;\n // op rs, label *** Label has been converted to it's memory location prior to this function being called\n case 'bgez': case 'bgtz': case 'blez': case 'bltz': case 'bgezal': case 'bltzal':\n if(instruction.length != 3) return syntaxError(lineNumber, 'This instruction requires 2 parameters');\n if(!(instruction[1] in REGISTERS)) return syntaxError(lineNumber, 'First parameter should be a valid register');\n jumpDistance = (instruction[2] - instructionAddress) / 4;\n if(jumpDistance > 32767 || jumpDistance < -32768) return syntaxError(lineNumber, \"Branching distance is not representable within 2's complement 16 bits (the label is too far away)\");\n immediate = jumpDistance & 0xffff;\n return OPCODES[opcode] << 26 | REGISTERS[instruction[1]] << 21 | immediate;\n // op rt, imm(rs) --> op rt, rs, imm\n case 'lb': case 'lbu': case 'lh': case 'lhu': case 'lw': case 'sb': case 'sh': case 'sw':\n if(instruction.length != 3) return syntaxError(lineNumber, 'This instruction requires 3 parameters');\n let lparen = instruction[2].indexOf('(');\n let rparen = instruction[2].indexOf(')');\n if(lparen == -1 || rparen == -1) return syntaxError(lineNumber, 'Bad formatting: this instruction is formatted like this: mnemonic register immediate(register)');\n instruction.push(instruction[2].slice(0, lparen));\n instruction[2] = instruction[2].slice(lparen + 1, rparen);\n \n if(!(instruction[1] in REGISTERS && instruction[2] in REGISTERS)) return syntaxError(lineNumber, 'Register parameters are not valid registers');\n let offset = instruction[3];\n if(offset > 32767 || offset < -32768) return syntaxError(lineNumber, \"Offset amount is not representable within 2's complement 16 bits (the immediate is too large)\");\n immediate = offset & 0xffff;\n return (OPCODES[opcode] << 26 | REGISTERS[instruction[2]] << 21 | REGISTERS[instruction[1]] << 16 | immediate) >>> 0;\n // op rt, imm\n case 'lui':\n if(instruction.length != 3) return syntaxError(lineNumber, 'This instruction requires 2 parameters');\n if(!(instruction[1] in REGISTERS)) return syntaxError(lineNumber, 'First parameter should be a valid register');\n if(instruction[2] > 32767 || instruction[2] < -32768) return syntaxError(lineNumber, \"Immediate value is not representable within 2's complement 16 bits\");\n immediate = instruction[2] & 0xffff;\n return OPCODES[opcode] << 26 | REGISTERS[instruction[1]] << 16 | immediate;\n \n // J-Type op, label *** Label has been converted to it's memory location prior to this function being called\n case 'j': case 'jal':\n if(instruction.length != 2) return syntaxError(lineNumber, 'This instruction requires 1 parameter');\n let target = (instruction[2] >>> 2) & 0b11_1111_1111_1111_1111_1111_1111;\n return OPCODES[opcode] << 26 | target;\n }\n\n return number;\n}",
"function generateConstantPUSH(memoryAddress) {\n return `\n@${memoryAddress}\nD=A\n@SP\nA=M\nM=D\n@SP\nM=M+1\n`;\n}",
"function get_code(req, res) {\n\t\tif (req._client_event === true && req.body) {\n\t\t\treturn !isNaN(req.body.http_code) ? Number(req.body.http_code) : 500;\n\t\t} else {\n\t\t\treturn t.ot_misc.get_code(res);\t\t\t\t\t\t\t\t// normal requests end up here\n\t\t}\n\t}",
"static getEncodeFunctionByName(functionName) {\n var _a;\n let fn = (_a = functionName === null || functionName === void 0 ? void 0 : functionName.toLowerCase()) === null || _a === void 0 ? void 0 : _a.trim();\n const result = (fn == \"fanspeed\") ? DatagramUtils.encodeFanSpeed :\n //(fn == \"onoff\") ? DatagramUtils.encodeOnOff : // TODO: think about this can be done (stateful set of bit in data word with multiple switches)\n (fn == \"humidity\") ? DatagramUtils.encodeHumidity :\n (fn == \"temperature\") ? DatagramUtils.encodeTemperature :\n DatagramUtils.encodeIdentity;\n return (!!result) ? result : DatagramUtils.encodeIdentity;\n }",
"immediate() {\n this.incrementPc();\n return this.cpu.pc;\n }",
"function getOps(str){\r\n let operands=[];\r\n let str2=str.replace(/\\w+(?=\\s)/,\"\").replace(/\\s/g,\"\");\r\n operands=(/,/.test(str2))?str2.split(','):str2.split();\r\n if (operands[0]!=\"\"){\r\n let i=0;\r\n let opsnumber=operands.length;\r\n console.log(\"this a test \"+operands[0].toUpperCase);\r\n for(i; i<opsnumber;i++){\r\n if (/\\[.*\\]/.test(operands[i])) {operands.push('M')}\r\n else if (segmentRegisters.includes(operands[i].toUpperCase())){operands.push('RS')}\r\n else if (wordRegisters.includes(operands[i].toUpperCase())) { operands.push('RX')}\r\n else if (byteRegisters.includes(operands[i].toUpperCase())){operands.push('Rl')}\r\n else (operands.push('I'))\r\n }\r\n }\r\n return operands\r\n }",
"static uint80(v) { return n(v, 80); }",
"getFlags() {\n this.context.store.dispatch(getFlags());\n }",
"generateCPU() {\n return {\n /** 16 bit counter to iterate through the memory array */\n programCounter: 512,\n /** array representing the register which is 8bit data register and 16 bloc of 8bit long */\n register: new Uint8Array(16),\n /** 16 bit counter to iterate through the Memory array (called I in most documentation) */\n I: 0,\n //array representing the stack\n stack: new Uint16Array(16),\n /** stack jump counter to iterate through the stack array must not go past 15 since the stack is 16 indexes long*/\n stackJumpCounter: 0,\n /** */\n delayTimer: 0,\n /** */\n soundTimer: 0\n }\n }",
"function nextCommand() {\n\t\t\tvar command = header.readByte();\n\n\t\t\t// Short waits\n\t\t\tif((command & 0xF0) == 0x70) {\n\t\t\t\treturn (command & 0x0F);\n\t\t\t}\n\n\t\t\t// Everything else\n\t\t\tswitch(command) {\n\t\t\t\tcase 0x4f:\t// GameGear PSG stereo register\n\t\t\t\t\theader.skipByte();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x50:\t// PSG\n\t\t\t\t\tpsg.write(header.readByte());\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x51:\t// YM2413\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x52:\t// YM2612 port 0\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x53:\t// YM2612 port 1\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x54:\t// YM2151\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x61:\t// Wait a number of samples\n\t\t\t\t\treturn header.readShort();\n\t\t\t\tcase 0x62:\t// Wait one frame (NTSC - 1/60th of a second)\n\t\t\t\t\treturn 735;\n\t\t\t\tcase 0x63:\t// Wait one frame (PAL - 1/50th of a second)\n\t\t\t\t\treturn 882;\n\t\t\t\tcase 0x66:\t// END\n\t\t\t\t\tif(settings.loop_samples > 0) {\n\t\t\t\t\t\theader.seek(settings.loop_offset);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisPlaying = false;\n\t\t\t\t\t}\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0xe0: // Seek\n\t\t\t\t\theader.skipLong();\n\t\t\t\t\treturn 0;\n\t\t\t\tdefault:\n\t\t\t\t\tif((command > 0x30) && (command <= 0x4e)) {\n\t\t\t\t\t\theader.skipByte();\n\t\t\t\t\t} else if((command > 0x55) && (command <= 0x5f)) {\n\t\t\t\t\t\theader.skipShort();\n\t\t\t\t\t} else if((command > 0xa0) && (command <= 0xbf)) {\n\t\t\t\t\t\theader.skipShort();\n\t\t\t\t\t} else if((command > 0xc0) && (command <= 0xdf)) {\n\t\t\t\t\t\theader.skipByte();\n\t\t\t\t\t\theader.skipShort();\n\t\t\t\t\t} else if((command > 0xe1) && (command <= 0xff)) {\n\t\t\t\t\t\theader.skipLong();\n\t\t\t\t\t}\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t}",
"function buildOperatorMap() {\n\tvar operatorMap = new Map();\n\n\toperatorMap.set('==', ':');\n\toperatorMap.set('!=', 'neq');\n\toperatorMap.set('<', 'lt');\n\toperatorMap.set('=lt=', 'lt');\n\toperatorMap.set('<=', 'lte');\n\toperatorMap.set('=le=', 'lte');\n\toperatorMap.set('>', 'gt');\n\toperatorMap.set('=gt=', 'gt');\n\toperatorMap.set('>=', 'gte');\n\toperatorMap.set('=ge=', 'gte');\n\toperatorMap.set('=in=', 'inq');\n\toperatorMap.set('=out=', 'nin');\n\n\treturn operatorMap;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
makes a string of of exercises array for sql statement | function makeExerciseSqlStr(exercisesValuesArr) {
let finalStr = "";
for (let c in exercisesValuesArr) {
if (c < exercisesValuesArr.length -1) {
finalStr = finalStr + makeStr(exercisesValuesArr[c]) + ','}
else {
finalStr = finalStr + makeStr(exercisesValuesArr[c])
}
}
return finalStr
} | [
"getEquationArray(amt1, eqstring='= ') {\n const line1 = this.getAmt1StringUnits(amt1);\n const line2 = eqstring + this.getAmt2StringUnits(amt1);\n return [line1, line2];\n }",
"function test_utility_logSortedData(studentData) {\n\n var formattedTestString = \"[\";\n for (var i = 0; i < studentData.length; ++i){\n formattedTestString += `{ \"_id\": \"${studentData[i].id}\", \"name\": \"${studentData[i].name}\", \"grade\": ${studentData[i].grade} } `\n\n if (i != studentData.length - 1) {\n formattedTestString += \", \"\n }\n\n }\n\n formattedTestString += \"]\"\n // console.log(studentData);\n console.log(formattedTestString);\n}",
"function getAllSql(version) {\n let tblData = getSqlTable(version);\n let sql = \"\";\n for (let tblName in tblData) {\n sql += getSql(tblName, tblData) + \"\\n\\n\";\n }\n cal.LOG(\"Storage: Full SQL statement is \" + sql);\n return sql;\n}",
"function getExercisesByMuscles(exercises) {\n\n // initialMuscleRelatedExercises= {muscle1:[], muscle2:[],muscle3:[],...}\n const initialMuscleRelatedExercises = muscles.reduce((accumulator, muscle) => ({\n ...accumulator,\n [muscle]: [],\n }\n ), {});\n\n\n return Object.entries(\n exercises.reduce((accumulator, currentExercise) => {\n const {muscles} = currentExercise;\n accumulator[muscles] = [...accumulator[muscles], currentExercise];\n\n return accumulator;\n }, initialMuscleRelatedExercises),\n );\n}",
"function zooInventory(array) {\n\t// create a variable, sentences and assign to an empty array\n\tconst sentences = [];\n\t// iterate through the array\n\tfor (let i = 0; i < array.length; i++) {\n\t\t// grab the elements assign to a variable animal\n\t\tlet animal = array[i];\n\t\t// create a name assign to the first element\n\t\tlet name = animal[0];\n\t\t// create a variable species assign to the first element at index 0\n\t\tlet species = animal[1][0];\n\t\t// create an age variable and assign to the first element at index 1\n\t\tlet age = animal[1][1];\n\t\t// create a variable called sentence assign to - name the species is age\n\t\tlet sentence = `${name} the ${species} is ${age}.`;\n\t\t// push sentence into sentences array\n\t\tsentences.push(sentence);\n\t}\n}",
"map (array, mapFunc = i => i) {\n if ((mapFunc instanceof Function) && array?.length > 0) {\n return this.glue(\n array.map(mapFunc).map((item) => SQL`${item}`),\n ','\n )\n }\n return null\n }",
"function askQ(qArray,toc,sections){\n let ans = [];\n inquirer.prompt(qArray).then((ans) => {\n createReadme(ans,toc,sections);\n}).catch(err => {console.log(err)})\n}",
"function ExamDB(_fname){\n\tthis.fname = _fname || \"\";\t// the \".edb\" suffix is NOT part of this field!\n\tthis.exams = [];\t\t\t// list of exams in this DB\n\tthis.questions = [];\t\t// a pool of all the questions for this set of exams\n\t\n\tthis.addExam();\n\tthis.addQuestion();\n\t\n\treturn this;\n}",
"toString(){\n let longestHeader = this.headerRow.reduce(LONGEST_STRING_LENGTH_IN_ARRAY, 0);\n let longestCell = this.body.reduce(LONGEST_STRING_LENGTH_IN_ARRAY_OF_ARRAYS, 0);\n let cellSize = (longestHeader < longestCell) ? longestCell : longestHeader;\n let ret = \"\";\n // build headers\n ret += PAD_JOIN_ARRAY(this.headerRow, cellSize);\n ret += this.body.map((row)=>'\\n' + PAD_JOIN_ARRAY(row, cellSize)).join('');\n\n return ret;\n }",
"addExerciseToDom(exercise)\n {\n var row = document.createElement(\"tr\");\n row.setAttribute('data-id', exercise.id);\n\n var nameCol = document.createElement(\"td\");\n nameCol.textContent = exercise.name;\n nameCol.className = \"mdl-data-table__cell--non-numeric\";\n\n var repsCol = document.createElement(\"td\");\n repsCol.textContent = exercise.reps;\n\n var restCol = document.createElement(\"td\");\n restCol.textContent = exercise.rest;\n\n var deleteCol = document.createElement(\"td\");\n var deleteIcon = document.createElement(\"i\");\n deleteIcon.className = \"deleteExercise material-icons\";\n deleteIcon.textContent = \"delete\";\n deleteCol.appendChild(deleteIcon);\n\n row.appendChild(nameCol);\n row.appendChild(repsCol);\n row.appendChild(restCol);\n row.appendChild(deleteCol);\n this.listEl.appendChild(row);\n }",
"function GetTopicNameArray(data, options){\n var self = this;\n var selectSql = 'select t.topicID, t.topicName from user_topic as ut left join topics as t on t.topicID=ut.topicID where t.groupID=data.groupID and ut.userID=data.userID;';\n \n self.connection.query(selectSql,function (err, result) {\n if(err){\n console.log('[INSERT ERROR] - ',err.message);\n return;\n } \n });\n}",
"function executePopulateTransection(tx, sqlCreateTableQuerry, sqlQuerry, dataSet) {\n // dataset has to be in Array of Array format\n // if it's not defined, create a blank Array of Array\n if ((dataSet === '') || (typeof (dataSet) === 'undefined')) {\n dataSet = [[]];\n \n\t\t} else {\n // if dataset is not in Array of Array format,\n // convert it to Array of Array\n if (!($.isArray(dataSet))) {\n \n\t\t\t\tdataSet = [[dataSet]];\n // if Only Array is passed (i.e. for a single record set), then\n // convert it into Array of Array\n \n\t\t\t} else {\n \n\t\t\t\tif (!($.isArray(dataSet[0]))) {\n dataSet = [dataSet];\n }\n }\n }\n //Array of Array\n tx.executeSql(sqlCreateTableQuerry);\n \n\t\tif (dataSet[0].length > 0) {\n for (var i = 0, l = dataSet.length; i < l; i++) {\n\n tx.executeSql(sqlQuerry, dataSet[i]);\n\n }\n }\n\n }",
"function genEnglish(senses) {\n return senses.map(s => s.english_definitions.join(', ')).join ('\\n');\n}",
"function kata11(smplArr){\n let newElement = document.createElement(\"article\");\n newElement.className = \"articleClass\";\n let headingElement= document.createElement(\"h1\");\n headingElement.className = \"subHeadingClass\";\n headingElement.appendChild(document.createTextNode(\"11--Display the 20 elements of sampleArray. (469, 755, 244, ..., 940, 472)\"));\n newElement.appendChild(headingElement);\n let tmpStr=\"\";\n for (let i=0;i<20;i++)\n {\n tmpStr+=smplArr[i]+\", \";\n }\n tmpStr=tmpStr.slice(0, -2);\n let newText = document.createTextNode(tmpStr);\n newElement.appendChild(newText);\n var destination = document.getElementById(\"mainSection\");\n destination.appendChild(newElement);\n}",
"toString() {\n var statement = this._statement;\n this._applyHas();\n this._applyLimit();\n\n var parts = {\n fields: statement.data('fields').slice(),\n joins: statement.data('joins').slice(),\n where: statement.data('where').slice(),\n limit: statement.data('limit')\n };\n\n var noFields = !statement.data('fields');\n if (noFields) {\n statement.fields({ [this.alias()]: ['*'] });\n }\n var sql = statement.toString(this._schemas, this._aliases);\n\n for (var name in parts) {\n statement.data(name, parts[name]);\n }\n this._aliasCounter = {};\n this._aliases = {};\n this.alias('', this.schema());\n return sql;\n }",
"function theBeatlesPlay(musiciansArr, instrumentsArr) {\n \n var musiciansAndInstruments = [];\n \n for (let i = 0; i < musiciansArr.length; i += 1) {\n \n var str = `${musiciansArr[i]} plays ${instrumentsArr[i]}`;\n musiciansAndInstruments = musiciansAndInstruments.concat(str);\n \n }\n \n return musiciansAndInstruments;\n}",
"function strConvert() {\n let result = \"\";\n for (let i = 0; i < 4; i++) {\n result += randCombo[i];\n\n }\n return result;\n }",
"function toPsql(rows) {\n return rows.map(toPsqlRow).join('\\n') + '\\n';\n}",
"function buildRow(countySelection) {\n \n for (let j = 0; j < database.length; j++ ) {\n \n if(database[j].content.$t.includes(countySelection) && database[j].gs$cell.col == 1) {\n let sameRow = database[j].gs$cell.row\n //will iterate through the 26 columns for a-z\n for (let r = j; r < j + columns; r++) {\n \n if(sameRow == database[r].gs$cell.row) {\n row.push({cellnum: database[r].title.$t.slice(0,1), text: database[r].content.$t })\n }\n }\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns whether the file exists on FS | fileExists() {
return fs.pathExists(this.location);
} | [
"function exists(file) {\n\treturn fs.existsSync(file) && file;\n}",
"isDirExists() {\t\n\t\ttry\t{\n\t\t\tfs.statSync(this.options.dir);\n\t\t} catch(e) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}",
"function check_file_exist(file){\n\tvar http = new XMLHttpRequest();\n\thttp.open('HEAD',file,false);\n\thttp.send();\n\treturn http.status == 404;\n}",
"function fileExistInNpm(filePath) {\n return existsSync(path.resolve(__dirname, '../../', filePath));\n}",
"function manifestExists() {\n return fs.existsSync(testManifestPath);\n}",
"function odk_json_exists(filename, callback) {\n read_git_release_data(REGION_FS_STORAGE, function(files) {\n res = false\n _.each(files, function(f, i) {\n if (basename(f) + \".json\" == filename) {\n res = true\n return\n }\n });\n\n callback(res)\n });\n}",
"hasEntry(...pth) {\n return fs.exists(this.dst, ...pth);\n }",
"function getCachedImage(path){\n\n\tif(!io.fileExistsSync(path)){\n\t\t// File does not exist so.. doenst really matter\n\t\treturn false;\n\t}else{\n\t\t// Should exist\n\t\treturn true;\n\t}\n}",
"isValid() {\n try {\n fs.accessSync(CONFIG_FILE_PATH, fs.constants.R_OK | fs.constants.W_OK);\n return true;\n } catch (err) {\n return false;\n }\n }",
"exists(objectHash) {\n return objectHash !== undefined\n && fs.existsSync(nodePath.join(Files.gitletPath(), 'objects', objectHash));\n }",
"validateFilePath(file) {\n try {\n if (fs.existsSync(file)) {\n return;\n } else {\n // File wasn't found, but we didn't get an error\n console.error('Provided file path was not valid or not found. Please try again.');\n process.exit(1);\n }\n } catch (error) {\n console.error('Provided file path was not valid or not found. Please try again.');\n process.exit(1);\n }\n }",
"function pageExists (slug) {\n\treturn test('-f', PAGE_DIR+slug+'.md');\n}",
"isInitable() {\n try {\n fs.accessSync(CONFIG_FILE_PATH, fs.constants.F_OK);\n return false;\n } catch (err) {\n return true;\n }\n }",
"function pageExists( title )\n{\n if (FILE.file_exists( pagePath( title ) ) || isSpecial( title ) ){\n return true;\n }else{\n return false;\n }\n}",
"checkFilenameExists(fileName){\n\n\t\tvar nodeIds = this.tree.get_node(this.workingDirectoryNode).children;\t\n\n\t\tfor (let i = 0; i < nodeIds.length; i++){\n\n\t\t\tvar child = this.tree.get_node({id: nodeIds[i] });\n\n\t\t\tif ( (child.data.name + child.data.ext) === fileName){\n\t\t\t\treturn child;\n\t\t\t}\n\n\t\t}\n\n\t}",
"function cookieFileExists() {\n log(\"cookie file exists.\");\n storage.readFile(COOKIE_FILE_NAME, function(filedata) {\n var data;\n function bailOut() {\n log(\"cookie file is not valid.\");\n storage.killFile(COOKIE_FILE_NAME, initiateHandshake);\n }\n try {data = JSON.parse(filedata);}\n catch (e) {return bailOut();}\n if (!data) return bailOut();\n if (!('expires' in data)) return bailOut();\n if (data.expires < myClock.originalClock()) return bailOut();\n token = data;\n haveToken();\n });\n }",
"function urlExists(url) {\n\t\tvar http = new XMLHttpRequest();\n\t\thttp.open('HEAD', url);\n\t\thttp.send();\n\t\tif (http.status !== 404) {\n\t\t\timgsNumber++;\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}",
"async _AssetExists(ctx, id) {\n const assetJSON = await ctx.stub.getState(id);\n return assetJSON && assetJSON.length > 0;\n }",
"function CSSExists() {\n return fs.existsSync(testCSSPath);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
iterate recursively node tree to index elements by name data is an array of objects, that contains id,name,children[] | function populateTree(data) {
for (let n=0;n<data.children.length;n++) {
populateTree(data.children[n]);
}
console.log("adding node:'"+ data.name + "' id:"+data.id);
nodeListByName[data.name]=data.id;
} | [
"function traverseDeserialize(data) {\n if(index > data.length || data[index] === \"#\") {\n return null;\n }\n var node = new TreeNode(parseInt(data[index]));\n index++;\n node.left = traverseDeserialize(data);\n index++;\n node.right = traverseDeserialize(data);\n return node;\n }",
"function flattenTreeData(data) {\n var dataMap = data.reduce(function(map, node) {\n map[node.name] = node;\n return map;\n }, {});\n\n // create the tree array\n var treeData = [];\n data.forEach(function(node) {\n // add to parent\n var parent = dataMap[node.parent];\n if (parent) {\n // create child array if it doesn't exist\n (parent.children || (parent.children = []))\n // add node to child array\n .push(node);\n } else {\n // parent is null or missing\n treeData.push(node);\n }\n });\n\n return treeData;\n}",
"_setChildren(item, data) {\n // find all children\n const children = data.filter((d) => item.id === d.parent);\n item.children = children;\n if (item.children.length > 0) {\n item.children.forEach((child) => {\n // recursively call itself\n this._setChildren(child, data);\n });\n }\n }",
"function traverse(node) {\n data.push(node.value);\n if (node.left) {\n traverse(node.left);\n }\n if (node.right) {\n traverse(node.right);\n }\n }",
"function generateElementMap(el, data = null){\n if (!data) {\n data = {};\n data[el.id] = {\n el: el,\n parent: null\n }\n }\n el.children && el.children.forEach(child => {\n generateElementMap(child, data);\n data[child.id] = {\n el: child,\n parent: el.id\n }\n });\n return data;\n}",
"getData() {\n const { tree, props } = this\n const { root } = props\n\n /* Create a new root, where each node contains height, depth, and parent.\n * Embeds the old node under the data attribute of the new node */\n const rootHierarchy = d3.hierarchy(\n root,\n (d) => d.children && Object.values(d.children)\n )\n\n /* Adds x, y to each node */\n tree(rootHierarchy)\n\n /* Return the array of nodes */\n const data = rootHierarchy.descendants()\n\n /* Use fixed depth to maintain position as items are added / removed */\n data.forEach((d) => {\n d.y = d.depth * 180\n })\n return data\n }",
"handleCalculation(data,tree){\n this.state.data.forEach((element) =>{\n if(element.aNumber == tree.attributes.id){\n data.totalTime = data.totalTime + element.timeSpend;\n data.totalArea = data.totalArea + element.areaCleaned;\n }\n })\n if(tree.children){\n tree.children.forEach((element) =>{\n data = this.handleCalculation(data,element);\n });\n }\n return data;\n }",
"spiderChildren(item, data, start, end, parent, parentFound, noDynamicLevel) {\n // see if we have the parent... or keep going\n if (item.id === parent || parentFound) {\n // set parent to current so it's gaurenteed to match on next one\n if (!parentFound) {\n parentFound = true;\n // support sliding scales, meaning that start / end is relative to active\n if (!noDynamicLevel && item.indent >= start) {\n start += item.indent;\n end += item.indent;\n }\n }\n // only add on what we're between\n if (item.indent >= start && item.indent <= end) {\n data.push(item);\n }\n // we've found it. Now everyone below here should match\n if (item.children.length > 0) {\n item.children.forEach((child) => {\n // recursively call itself\n this.spiderChildren(\n child,\n data,\n start,\n end,\n parent,\n parentFound,\n noDynamicLevel\n );\n });\n }\n } else {\n if (item.children.length > 0) {\n item.children.forEach((child) => {\n // recursively call itself\n this.spiderChildren(\n child,\n data,\n end,\n parent,\n parentFound,\n noDynamicLevel\n );\n });\n }\n }\n }",
"rebuildTreeIndex() {\n let columnIndex = 0;\n\n this.#rootsIndex.clear();\n\n arrayEach(this.#rootNodes, ([, { data: { colspan } }]) => {\n // Map tree range (colspan range/width) into visual column index of the root node.\n for (let i = columnIndex; i < columnIndex + colspan; i++) {\n this.#rootsIndex.set(i, columnIndex);\n }\n\n columnIndex += colspan;\n });\n }",
"function buildTree(P, arg, path)\n{\n if (!path)\n path = \"/\";\n report(\"buildTree \"+arg);\n if (Number.isInteger(arg)) {\n report(\"atomic case \"+arg);\n var tree = getTree(P, {n: arg});\n tree.name = path+\"A\";\n return tree;\n }\n else {\n report(\"list case case \"+arg);\n path = path+\"H\";\n var children = arg;\n var nodes = [];\n for (var i=0; i<children.length; i++) {\n nodes.push(buildTree(P, children[i], path+\"/\"+i));\n }\n var tree = getTree(P, {children: nodes});\n tree.name = path;\n return tree;\n }\n}",
"function recursiveStepForHierarchicalOrder(rootID, node, index, createdPage) {\n if (node.nodes[index].nodes.length > 0) {\n createHierarchies(createdPage.id, node.nodes[index], 0);\n };\n createHierarchies(rootID, node, index + 1)\n }",
"function Node(data){\n \n this.data = data;\n this.parent = null;\n this.children = [];\n\n}",
"depthFirstSearch(array) {\n // create an empty working array with root node\n let workingArray = [this]\n // while the workingArray has elements in the array\n while (workingArray.length) {\n // remove the first element/node of the workingArray\n let node = workingArray.shift()\n // push the first element/node's names into array\n array.push(node.name)\n // using spread operator, take every element from node's children array and push into the START of the workingArray\n workingArray.unshift(...node.children)\n }\n // return array\n return array\n }",
"function loadData(filename,len,count,tree_width,tree_len){\n d3.csv(filename)\n .then(function(data) {\n // console.log(data)\n\n // 1.rearrange the list\n var data_array=[];\n for(var i=0;i<count;i++){\n data_array.push(data.slice(i*len,(i+1)*len));\n }\n\n // 2.build hierarchy for each list\n var hierarchy_array=[];\n data_array.forEach(function(item){\n hierarchy_array.push(buildHierarchy(item)\n .sum(function(d){return d.size})\n .sort(function(a, b){return b.height - a.height || b.value - a.value}))\n\n })\n //console.log(hierarchy_array)\n\n\n // 3.set index and sequence\n\n /*\n for each node except the root set index, 0-first child, 1-second child\n for each leaf set the sequence, which is the sequence of the last list\n */\n var currentSequence=0;\n function setChildrenIndex(root){\n if(root.hasOwnProperty('children')){\n var c1=root.children[0];\n var c2=root.children[1];\n c1['index']=0;\n c2['index']=1;\n setChildrenIndex(c1);\n setChildrenIndex(c2);\n }\n else{\n root['sequence']=currentSequence;\n currentSequence+=1;\n }\n }\n hierarchy_array.forEach(function(root){\n currentSequence=0;\n setChildrenIndex(root)\n })\n\n\n // 4.reset the order according to the list before\n\n function generateIndexMap(hierarchy){\n // get leaves of the hierarchy\n var leaves=hierarchy\n .descendants()\n .filter(function(d){return !d.hasOwnProperty('children')})\n .sort(function(a,b){\n return a['sequence']-b['sequence'];})\n var mapIndex=[]\n mapIndex.length=len+1;\n for(var i=0;i<len+1;i++) mapIndex[leaves[i].data.name]=i;\n return mapIndex;\n }\n\n var arrIndexMap=[]\n hierarchy_array.forEach(function(hierarchy){\n arrIndexMap.push(generateIndexMap(hierarchy));\n })\n\n // calculate bias according to order\n function calculateBias_order(indexMap1,indexMap2){\n var bias=0;\n for(var i=0;i<len+1;i++){\n bias+=Math.abs(indexMap1[i]-indexMap2[i])\n }\n return bias;\n }\n\n // calculate bias according to crosses\n function calculateBias_cross(indexMap1,indexMap2){\n var bias=0;\n for(var i=0;i<len;i++){\n for(var j=i+1;j<len+1;j++){\n if((indexMap1[i]>=indexMap1[j])!=(indexMap2[i]>=indexMap2[j]))\n bias+=1;\n }\n }\n return bias;\n }\n\n\n // increase sequence for a tree given root\n function increaseSequence(root,bias){\n if(root.hasOwnProperty('children')) {\n increaseSequence(root.children[0],bias);\n increaseSequence(root.children[1],bias);\n }\n else{\n root.sequence+=bias;\n }\n }\n\n // swap the children of the root\n function swapChildren(root){\n var cR=root.children[0];\n var cL=root.children[1];\n root.children[0]=cL\n root.children[1]=cR;\n increaseSequence(cL,-cR.value);\n increaseSequence(cR,cL.value);\n }\n\n function optimizationFun_order(cL,cR, indexMapLeft){\n var bias0=0;\n var bias1=0;\n var biasL=cL.value;\n var biasR=cR.value;\n var leavesL=cL.descendants().filter(function(d){return !d.hasOwnProperty('children')})\n var leavesR=cR.descendants().filter(function(d){return !d.hasOwnProperty('children')})\n\n leavesL.forEach(function(d){\n var index=d.data.name;\n bias0+=Math.abs(d.sequence-indexMapLeft[index]);\n bias1+=Math.abs(d.sequence+biasR-indexMapLeft[index]);\n })\n leavesR.forEach(function(d){\n var index=d.data.name;\n bias0+=Math.abs(d.sequence-indexMapLeft[index]);\n bias1+=Math.abs(d.sequence-biasL-indexMapLeft[index]);\n })\n return bias1-bias0;\n }\n function optimizationFun_cross(cL,cR, indexMapLeft){\n var bias0=0;\n var bias1=0;\n var leavesL=cL.descendants().filter(function(d){return !d.hasOwnProperty('children')})\n var leavesR=cR.descendants().filter(function(d){return !d.hasOwnProperty('children')})\n\n leavesL.forEach(function(dL){\n var indexL=dL.data.name;\n leavesR.forEach(function(dR){\n var indexR=dR.data.name;\n if(indexMapLeft[indexL]>indexMapLeft[indexR])\n bias0+=1;\n else bias1+=1;\n })\n })\n return bias1-bias0;\n }\n\n // adjust tree given root according to the map index of the left tree\n function adjustTree(indexMapLeft,root){\n if(root.hasOwnProperty('children')){\n //console.log(root.data.name)\n var cL=root.children[0];\n var cR=root.children[1];\n //console.log(leavesL,leavesR)\n //console.log(bias0,bias1)\n\n var cross_result=optimizationFun_cross(cL,cR,indexMapLeft);\n if (cross_result<0){\n swapChildren(root);\n }\n else if(cross_result==0){\n if(optimizationFun_order(cL,cR,indexMapLeft)<0)\n swapChildren(root);\n }\n\n adjustTree(indexMapLeft,cL);\n adjustTree(indexMapLeft,cR);\n }\n }\n\n\n // check if change index0 and index1 will down bias\n function checkChange(index0,index1,funCB){\n var bias_order0=calculateBias_order(arrIndexMap[index0],arrIndexMap[index1])\n var bias_cross0=calculateBias_cross(arrIndexMap[index0],arrIndexMap[index1])\n funCB();\n arrIndexMap[index1]=generateIndexMap(hierarchy_array[index1])\n var bias_order1=calculateBias_order(arrIndexMap[index0],arrIndexMap[index1])\n var bias_cross1=calculateBias_cross(arrIndexMap[index0],arrIndexMap[index1])\n console.log('(',bias_order0,'->',bias_order1,');(',bias_cross0,'->',bias_cross1,')')\n\n }\n\n // optimize top two trees by each other\n function top2Optimization(){\n for (var i=0;i<5;i++){\n checkChange(1,0,function(){\n adjustTree(arrIndexMap[1],hierarchy_array[0])\n })\n checkChange(0,1,function(){\n adjustTree(arrIndexMap[0],hierarchy_array[1])\n })\n }\n }\n\n function manuallyOptimization(){\n checkChange(1,0,function(){\n swapChildren(hierarchy_array[0].children[0])\n\n })\n checkChange(0,1,function(){\n adjustTree(arrIndexMap[0],hierarchy_array[1])\n })\n }\n\n function sequentiallyOptimization(){\n for(var i=0;i<count-1;i++){\n checkChange(i,i+1,function(){\n adjustTree(arrIndexMap[i],hierarchy_array[i+1])\n })\n }\n }\n\n function reverselyOptimization(){\n for(var i=9;i>0;i--){\n checkChange(i,i-1,function(){\n adjustTree(arrIndexMap[i],hierarchy_array[i-1])\n })\n }\n }\n\n //manuallyOptimization();\n //top2Optimization();\n sequentiallyOptimization()\n //reverselyOptimization()\n\n console.log(hierarchy_array)\n $scope.donutChartData.hierarchy=hierarchy_array\n $scope.donutChartData.tree_width=tree_width;\n $scope.donutChartData.tree_len=tree_len;\n $scope.$apply();\n })\n .catch(function(error){\n // handle error\n })\n\n }",
"function buildTree(root, data, dimensions, value) {\n zeroCounts(root);\n var n = data.length,\n nd = dimensions.length;\n for (var i = 0; i < n; i++) {\n var d = data[i],\n v = +value(d, i),\n node = root;\n\n for (var j = 0; j < nd; j++) {\n var dimension = dimensions[j],\n category = d[dimension],\n children = node.children;\n node.count += v;\n node = children.hasOwnProperty(category) ? children[category]\n : children[category] = {\n children: j === nd - 1 ? null : {},\n count: 0,\n parent: node,\n dimension: dimension,\n name: category , \n class : d.class\n };\n }\n node.count += v;\n }\n return root;\n }",
"function fillPerformer(data){\n for(var i = 0; i < data[\"children\"].length; i++){\n var current = data[\"children\"][i];\n current[\"name\"] = gPerformer[current[\"reference\"]].name;\n current[\"specialty\"] = gPerformer[current[\"reference\"]].specialty;\n }\n}",
"function traverseInner(tree, callback, innerObj, stop) {\n innerObj = { ...innerObj\n };\n innerObj.depth += 1;\n\n if (Array.isArray(tree)) {\n\n for (let i = 0, len = tree.length; i < len; i++) {\n\n if (stop.now) {\n break;\n }\n\n const path = `${innerObj.path}.${i}`;\n innerObj.parent = clone(tree);\n innerObj.parentType = \"array\"; // innerObj.path = `${innerObj.path}[${i}]`\n\n callback(tree[i], undefined, { ...innerObj,\n path: trimFirstDot(path)\n }, stop);\n traverseInner(tree[i], callback, { ...innerObj,\n path: trimFirstDot(path)\n }, stop);\n }\n } else if (isObj(tree)) { // eslint-disable-next-line\n\n for (const key in tree) {\n\n if (stop.now && key != null) {\n break;\n }\n\n const path = `${innerObj.path}.${key}`;\n\n if (innerObj.depth === 0 && key != null) {\n innerObj.topmostKey = key;\n }\n\n innerObj.parent = clone(tree);\n innerObj.parentType = \"object\";\n callback(key, tree[key], { ...innerObj,\n path: trimFirstDot(path)\n }, stop);\n traverseInner(tree[key], callback, { ...innerObj,\n path: trimFirstDot(path)\n }, stop);\n }\n }\n return tree;\n } // for DRY purposes, we extract the function which reports the first element",
"reorder () {\n let nodes = []\n\n walk(this.root.children, (node) => {\n nodes.push(node)\n })\n\n let { baseOrder } = this\n nodes.forEach((node, i) => {\n node.order = baseOrder + i\n })\n }",
"function buildHierarchy(data){\n var len=data.length+1; // length of items is length of merging+1\n var list=[];\n // push items\n for (var i=0;i<len;i++){\n list.push({name:i,size:1})\n }\n // push merges\n for (var i=len;i<len*2-1;i++){\n list.push({name:i,children:[]})\n }\n // reversely build their parent-children relationships\n for(var i=len-2;i>=0;i--){\n var node=data[i];\n var id1=node['id1'];\n var id2=node['id2'];\n list[i+len].children.push(list[id1])\n list[i+len].children.push(list[id2])\n }\n return d3.hierarchy(list[len*2-2]);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update the test documents using a direct update operation | async updateDocuments () {
// do a direct update to change the text of our test documents
const regexp = new RegExp(`^${this.randomizer}yes$`);
await this.data.test.updateDirect(
{ flag: regexp },
{ $set: { text: 'goodbye'} }
);
} | [
"function updateSyncDoc(service, SyncDoc) {\n service\n .documents(SyncDoc)\n .update({\n data: { temperature: 30,\n humidity: 20 },\n })\n .then(response => {\n console.log(response);\n// console.log(\"== deleteSyncDoc ==\");\n})\n .catch(error => {\n console.log(error);\n });\n}",
"async updateModels () {\n\t\t// do a direct update to change the text of our test models\n\t\tconst regexp = new RegExp(`^${this.randomizer}yes$`);\n\t\tawait this.data.test.updateDirectWhenPersist(\n\t\t\t{ flag: regexp },\n\t\t\t{ $set: { text: 'goodbye'} }\n\t\t);\n\t}",
"function updateEsRecord(data) {\n esClient.search({\n index: 'products',\n body: {\n query : {\n term: { \"id\" : data.id }\n }\n }\n }).then(found => {\n \n console.log('Found item: ', found.hits.hits[0]._id);\n\n if(found){\n esClient.update({\n index: 'products',\n id: found.hits.hits[0]._id,\n body: {\n doc: {\n id: data.id,\n title: data.title,\n description: data.description\n }\n }\n })\n .then(response => {\n console.log('Updated successfully.');\n })\n .catch(err => {\n console.log('Update error: ' +err);\n })\n }\n })\n .catch(err => {\n console.log('Not found Error: '+ err);\n });\n}",
"function update(Model,_id,updated_obj){\n const promise = new Promise((resolve,reject)=>{\n Model.findOneAndReplace(_id,updated_obj,(err,docs)=>{\n \tif (err) {\n \t\treject(err);\n \t\treturn;\n \t}\n \tresolve(docs)\n })\n })\n return promise;\n}",
"executeUpdate(sparql, document) {\n if (this._source)\n throw new Error('Updates on non-subject sources not yet supported.');\n\n let executed = false;\n const next = async () => {\n if (!executed) {\n executed = true;\n\n // Send authenticated PATCH request to the document\n document = document || this.getDocument(await this._subject);\n const response = await auth.fetch(document, {\n method: 'PATCH',\n headers: {\n 'Content-Type': 'application/sparql-update',\n },\n body: sparql,\n });\n\n // Error if the server response was not ok\n if (!response.ok)\n throw new Error(`Update query failed (${response.status}): ${response.statusText}`);\n\n // Clear stale cached versions of the document\n await this.clearCache(document);\n\n // Mock Comunica's response for bindings as a Immutable.js object.\n return { value: { size: 1, values: () => ({ next: () => ({ value: { ok: true } }) }) } };\n }\n return { done: true };\n };\n return {\n next,\n [Symbol.asyncIterator]() { return this; },\n };\n }",
"Update(tablename, data, id, callback) {\n elasticClient.update({\n index: indexName,\n type: tablename,\n // version_type:version_type,\n id: id,\n // version: version,\n retry_on_conflict: 5,\n body: {\n doc: data,\n doc_as_upsert: true,\n }\n }, function (err, results) {\n callback(err, results)\n })\n }",
"async function updateByQueryFirstApproach(id){\n const course=await Course.findById({_id:id})\n if(!course)\n console.log(\"No course found with published Status: \"+id);\n else{\n // course.author=\"Ali\"\n // course.isPublished=true;\n \n course.set({\n author:\"Ali\",\n isPublished:true\n });\n\n const result=await course.save();\n console.log(result);\n\n }\n}",
"update(req, res) {\n return Education\n .find({\n where: {\n id: req.params.educationId,\n resumeId: req.params.resumeId,\n },\n })\n .then(education => {\n if (!education) {\n return res.status(404).send({\n message: 'education Not Found',\n });\n }\n \n return education\n .update(req.body, { fields: Object.keys(req.body) })\n\n .then(updatedEducation => res.status(200).send(updatedEducation))\n .catch(error => res.status(400).send(error));\n })\n .catch(error => res.status(400).send(error));\n }",
"async update ({ params, request, response }) {\n const requestAll = request.all()\n\n const find = await Vagas.find(params.id)\n\n if(!find){\n response.status(404)\n return HelpersStatusCode.status404()\n }\n\n find.merge({...requestAll})\n\n await find.save()\n\n return HelpersStatusCode.status200()\n }",
"function upsert(endpoint, doc) {\n var http = require('http');\n var url = require('url');\n var parts = url.parse(endpoint);\n var options = {\n host: parts.hostname,\n path: parts.path,\n port: parts.port,\n method: 'POST'\n };\n console.log(options);\n\n var req = http.request(options, function(res) {\n console.log('STATUS: ' + res.statusCode);\n console.log('HEADERS: ' + JSON.stringify(res.headers));\n res.setEncoding('utf8');\n res.on('data', function (chunk) {\n console.log('BODY: ' + chunk);\n });\n });\n req.write(JSON.stringify(doc));\n req.end();\n}",
"function updateRecord (criteria, query, done) {\n Klass.DB().collection(Klass.getCollectionName()).update(criteria, query, function (err, numUpdated, status) {\n if (err || numUpdated < 1) {\n return done(new Klass.Error('persistence', err ? err.toString() : numUpdated + \" records updated!\"));\n }\n return done(null, numUpdated);\n });\n }",
"function apiUpdate(req, res) {\n // console.log('PUT /api/breed/:name');\n // console.log(req.params.name);\n // console.log(req.body);\n\n // update the specified breed\n db.Breed.find({'name': req.params.name}, function(err, sheep) {\n //console.log(sheep);\n if (err) {\n res.status(404).send('ERROR: breed not found; you probably need to add this breed');\n } else {\n if (req.body.infoSources) {\n // get the list of new sources\n let infoList = req.body.infoSources.split(', ');\n // we're replacing the current list of sources with the new list\n req.body.infoSources = [];\n for (let i = 0; i < infoList.length; i++) {\n req.body.infoSources.push(infoList[i]);\n }\n //console.log('srcs: ' + req.body.infoSources);\n }\n\n //console.log(sheep[0]._id);\n db.Breed.update({ '_id': sheep[0]._id }, { $set: req.body }, function(err, updatedSheep) {\n if (err) {\n res.status(503).send('ERROR: could not update sheep info');\n } else {\n res.json(updatedSheep);\n }\n });\n }\n\n });\n}",
"function update(restaurant, update){\n Restaurant.findOneAndUpdate({name: restaurant}, {name: update}, {new: true}, function(err, docs){\n if(err){\n console.log(err);\n }\n else{\n console.log(docs);\n }\n })\n}",
"update(req, res) {\n Request.findByIdAndUpdate(req.params.id, req.body, {\n runValidators: true,\n new: true,\n })\n .then((updatedRequest) => res.json(updatedRequest))\n .catch((err) => res.status(400).json(err));\n }",
"update ( data ) {\n this.store.update(data);\n }",
"updateThought({ params, body }, res) {\n Thought.findOneAndUpdate({ _id: params.id }, body, { new: true, runValidators: true })\n .select('-__v')\n .then(thoughtData => {\n if (!thoughtData) {\n res.status(404).json({ message: 'No Thought found with that ID.' });\n return;\n }\n res.json({ message: 'Your thought was updated.', thoughtData });\n })\n .catch(err => res.status(400).json(err));\n }",
"update(numTarjeta, modificaciones) {\n return this.findOneAndUpdate({ numTarjeta: numTarjeta }, modificaciones, { multi: true });\n }",
"async function update(req, res) {\n let _id = req.params.venueId;\n let {\n name, type, imgUrl, about, phone, email, \n minCustomers, maxCustomers, zip, address \n } = req.body;\n\n let doc = compressDoc({\n _id, name, type, imgUrl, about, phone, email,\n minCustomers, maxCustomers, zip, address\n });\n\n let data = await venueService.update(doc);\n let payload = new Res.Ok({ data });\n res.status(payload.status).json(payload);\n}",
"update(userInfo) {\n const userID = this.findIdBySlug(userInfo.username);\n this._collection.update(userID, { $set: userInfo });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle when the selected object is edited by the editor.. this way we can fire an event and the app knows to update the source tabs | handleSelectedEdited(item){
//if this is the currently selected object, let's fire our change event
if(item.ID == this.selectedClassItem)
this.eventSelectionEdited.fire(item);
} | [
"onSelectionEdited(func){ return this.eventSelectionEdited.register(func); }",
"function on_piece_select()\n{\n\tupdate_editor();\n}",
"editPointViewClick() {\n this.deselectAllTabs();\n\n this.editPointViewTab.className = \"WallEditor_EditPointViewTab selected\";\n this.viewController = this.editPointView;\n\n this.selectCurrentTab();\n }",
"selectionSetDidChange() {}",
"function onSelectedChanged(val) {\n scope.$emit('selectedchange', val);\n }",
"handleEdit(event) {\n console.log('inside handleEdit');\n this.displayMode = 'Edit';\n }",
"handleModifySelPGTobj($change){\n\t const rIndex = this.props.UI.selectedRowIndex;\n\t this.props.onPGTobjArrayChange(\"update\", {index: rIndex, $Updater: $change});\n\t}",
"function FileList::SelectionChanged() \r\n\t\t{\r\n\t\t\tSelChanged();\r\n\t\t}",
"_listenFieldSelected() {\n var self = this;\n self.m_fieldChangeHandler = function (e) {\n if (!self.m_selected)\n return;\n var $selected = $(e.target).find(':selected');\n var fieldName = $selected.val();\n var fieldType = $selected.data('type');\n var domPlayerData = self._getBlockPlayerData();\n var xSnippet = $(domPlayerData).find('XmlItem');\n $(xSnippet).attr('fieldType', fieldType);\n $(xSnippet).attr('fieldName', fieldName);\n self._setBlockPlayerData(domPlayerData);\n };\n $(Elements.JSON_ITEM_TEXT_FIELDS, self.$el).on('change', self.m_fieldChangeHandler);\n }",
"registerSourceModuleChange() {\n\t\t\tthis.sourceModuleSelect = this.container.find('select[name=\"tabid\"]');\n\t\t\tthis.sourceTabId = this.sourceModuleSelect.val();\n\t\t\tthis.sourceModuleSelect.on('change', (e) => {\n\t\t\t\tlet value = $(e.currentTarget).val();\n\t\t\t\tif (this.sourceTabId !== value && this.sourceTabId !== null) {\n\t\t\t\t\tthis.sourceTabId = value;\n\t\t\t\t\tthis.loadConditionBuilderView(this.sourceTabId);\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"modelChanged() {\n }",
"function vB_Text_Editor_Events()\n{\n}",
"onSelectionChange(cb) {\n this.on('selection-change', cb)\n }",
"_listBoxChangeHandler(event) {\n const that = this;\n\n if ((that.dropDownAppendTo && that.dropDownAppendTo.length > 0) || that.enableShadowDOM) {\n that.$.fireEvent('change', event.detail);\n }\n\n that._applySelection(that.selectionMode, event.detail);\n }",
"function handleModifiedEvent(event) {\n setModified(true);\n}",
"editCornerViewClick () {\n this.deselectAllTabs();\n\n this.editCornerViewTab.className = \"WallEditor_EditCornerViewTab selected\";\n this.viewController = this.editCornerView;\n\n this.selectCurrentTab();\n }",
"function selectionChangedEventCB(event) \n{\n var dbIdArray = event.dbIdArray;\n if (dbIdArray.length == 0) \n {\n UpdateCommandLine(\"Selection changed event : No selection \");\n return;\n }\n\n for (i = 0; i < dbIdArray.length; i++) \n {\n var dbId = dbIdArray[i];\n\n var node = viewer3D.model.getNodeById(dbId);\n if (node != null) {\n UpdateCommandLine(\"Selection changed event : selecting object : \" + node.name + \" (dbId = \" + dbId + \")\");\n }\n else {\n UpdateCommandLine(\"Selection changed event : selecting object \" + dbId);\n }\n\n \n }\n}",
"function addEvents(object)\n\t{\n\t\tvar theObject = object.obj;\n\t\t\n\t\ttheObject.addEventListener('cursorup', function(event) \n\t\t{\n\t\t\tif (editMode)\n\t\t\t{\t\t\n\t\t\t\tif (!isUserCurrentlyEditing)\n\t\t\t\t{\n\t\t\t\t\tif (!object.settings.currentlyBeingEdited && !object.settings.locked)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartEditing(object);\n\t\t\t\t\t}\t\t\n\t\t\t\t}\t\n\t\t\t\telse if (isUserCurrentlyEditing && selectedObject.obj == theObject)\n\t\t\t\t{\n\t\t\t\t\tstopEditing(object);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\ttheObject.addEventListener('cursorenter', function (event) \n\t\t{\n\t\t\t\n\t\t\tif (!isUserCurrentlyEditing && !object.settings.currentlyBeingEdited && !object.settings.locked && editMode == true)\n\t\t\t{\n\t\t\t\tif (object.text)\n\t\t\t\t\tobject.text.visible = true;\n\t\t\t\t\n\t\t\t\ttheObject.traverse(function(child) \n\t\t\t\t{\n\t\t\t\t\tif (child instanceof THREE.Mesh) \n\t\t\t\t\t{\n\t\t\t\t\t\tchild.material.color = hoverColorOn;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\t\n\t\t});\n\t\t\n\t\ttheObject.addEventListener('cursorleave', function (event) \n\t\t{\n\t\t\t\n\t\t\tif (!isUserCurrentlyEditing && !object.settings.currentlyBeingEdited && !object.settings.locked && editMode == true)\n\t\t\t{\n\t\t\t\tif (object.text)\n\t\t\t\t\tobject.text.visible = false;\n\t\t\t\t\n\t\t\t\ttheObject.traverse(function(child) \n\t\t\t\t{\n\t\t\t\t\tif (child instanceof THREE.Mesh) \n\t\t\t\t\t{\n\t\t\t\t\t\tchild.material.color = hoverColorOff;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}",
"_emitChangeEvent(option) {\n this.selectionChange.emit({\n source: this,\n option: option,\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds all transactions from the CSV data string into this bank | loadCSVData(CSVData) {
let transactionStrings = CSVData.split('\n');
for(let i = 1; i < transactionStrings.length; i++) { // skip first row since it is header
let lineNumber = i + 1;
let transactionString = transactionStrings[i];
let transactionDetails = transactionString.split(',');
if(transactionDetails.length === 5) {
if(!this.addTransaction(moment(transactionDetails[0], 'DD/MM/YYYY', true), transactionDetails[1], transactionDetails[2], transactionDetails[3], transactionDetails[4])) {
logger.warn('Could not process transaction on line ' + lineNumber + ': ' + this.lastAddTransactionError);
this.lastDataLoadErrorCount++;
}
} else if(transactionString.length > 0) {
logger.warn('Could not process transaction on line ' + lineNumber + ': Not enough fields provided.');
this.lastDataLoadErrorCount++;
}
}
return true;
} | [
"function parseCSV (newSet, callback){\n\tvar parser = parse(function(err,data){\n\t\tif(err){\n\t\t\tconsole.log(err);\n\t\t} else {\n\t\t\tdata.shift();\n\t\t\tcallback(null,newSet,data);\n\t\t}\n\t});\n\tfs.createReadStream(__dirname + '/intercensalState.csv').pipe(parser);\n}",
"function readCSV(data) {\n var dataLines = data.split('\\r\\n');\n\n for(var i = 1; i < dataLines.length; ++i) {\n if(dataLines[i] === '') continue;\n entries.push(new RawEntry(dataLines[i].split(',')));\n }\n}",
"function addPendingTransactions() {\n blockchain.pendingTransactions.forEach(transaction => {\n const pendingTransactionsTable = document.getElementById(\"newPendingTransactionTable\");\n\n if (!document.getElementById(\"transactionId\") || transaction.transactionId !== document.getElementById(\"transactionId\").innerHTML) {\n let row = pendingTransactionsTable.insertRow();\n let transactionId = row.insertCell(0);\n transactionId.innerHTML = transaction.transactionId;\n transactionId.id = \"transactionId\";\n let txTimestamp = row.insertCell(1);\n txTimestamp.innerHTML = (new Date(transaction.txTimestamp)).toLocaleTimeString();\n let sender = row.insertCell(2);\n sender.innerHTML = transaction.sender;\n let recipient = row.insertCell(3);\n recipient.innerHTML = transaction.recipient;\n let amount = row.insertCell(4);\n amount.innerHTML = transaction.amount;\n } else {\n return;\n };\n });\n }",
"uploadSellsCsv(fileName,data) {\n let self=this;\n let parsedData=(Papa.parse(data));\n parsedData=parsedData.data[0];\n //Check if there is a file with the same name\n if(this.localStorageService.keys().indexOf('sells.'+fileName)!=-1){\n throw \"There is already a file with the same name.\";\n }else\n //If all of the fields exists\n if(parsedData.indexOf('selldate')!=-1 && parsedData.indexOf('amount')!=-1) {\n self.localStorageService.set('sells.'+fileName, Papa.parse(data,{header: true,skipEmptyLines: true}));\n }\n //If some of the fields doesnt exist, throw error, giving feedback of which fields are required in the file\n else{\n let missingFields='';\n if(parsedData.indexOf('selldate')==-1){\n missingFields+='selldate ';\n }\n if(parsedData.indexOf('sells')==-1){\n missingFields+='sells ';\n }\n throw \"Missing fields \"+missingFields+\"in CSV file.\";\n }\n }",
"function import_data_from_csv() {\n fetch(\"input.csv\")\n .then(v => v.text())\n .then(data => init_table_from_data(data))\n}",
"loadXMLData(XMLData) {\n let transactionsDetails;\n try {\n transactionsDetails = xmlParser.parseStringSync(XMLData).TransactionList.SupportTransaction;\n } catch(err) {\n logger.warn('Invalid syntax.');\n this.lastDataLoadErrorCount++;\n return false;\n }\n\n for(let i = 0; i < transactionsDetails.length; i++) {\n let objectNumber = i + 1;\n let transactionDetails = transactionsDetails[i];\n\n if(!this.addTransaction(moment.fromOADate(transactionDetails.$.Date), transactionDetails.Parties[0].From[0], transactionDetails.Parties[0].To[0], transactionDetails.Description, transactionDetails.Value)) {\n logger.warn('Could not process transaction number ' + objectNumber + ': ' + this.lastAddTransactionError);\n this.lastDataLoadErrorCount++;\n }\n }\n\n return true;\n }",
"function importData() {\n let heroes = [];\n\n // Read CSV file\n fs.createReadStream('all-heroes.csv')\n .pipe(csv({\n separator: ','\n }))\n .on('data', (data) => {\n heroes.push({\n 'id': data.id,\n 'name': data.name,\n 'description': data.description,\n 'imageUrl': data.imageUrl,\n 'secretIdentities': data.secretIdentities,\n 'aliases': data.aliases,\n 'partners': data.partners,\n 'universe': data.universe,\n 'gender': data.gender,\n 'suggest': [\n {\n \"input\": data.name,\n \"weight\": 10\n },\n {\n \"input\": data.aliases,\n \"weight\": 5\n },\n {\n \"input\": data.secretIdentities,\n \"weight\": 5\n },\n ]\n });\n })\n .on('end', () => {\n console.log('push data');\n sendData(heroes).then(() => {\n console.log('End');\n client.close();\n }, (err) => {\n console.log('End because of an error');\n console.trace(err);\n client.close();\n });\n });\n}",
"function Csv () {}",
"recordTransaction({transaction_arr}) {\n console.log(\"Record transaction for the transaction array : %s\", transaction_arr.toString());\n return knex(\"transactions\").insert(transaction_arr);\n }",
"function buildFromCsv(csvText, metaData) {\n if (metaData === void 0) { metaData = {}; }\n return ozone.columnStore.buildFromStore(ozone.rowStore.buildFromCsv(csvText), metaData);\n }",
"function readCSV(csv) {\n logger.info(\"Reading input CSV...\");\n\n csvtojson()\n .fromFile(csv)\n .on('json', (jsonObj) => {\n posts.push(jsonObj);\n })\n .on('done', (error) => {\n logger.info('Fetching countries...');\n for (i = 0; i < posts.length; i++) {\n done[i] = posts[i];\n // if it hasn't country already\n if (!done[i].country) {\n // if it can be found locally\n if (!!gc.get_country(Number(posts[i].location_latitude), Number(posts[i].location_longitude))) {\n done[i].country = gc.get_country(Number(posts[i].location_latitude), Number(posts[i].location_longitude)).name;\n doneCounter++;\n if (doneCounter == posts.length) {\n makeCSV();\n }\n // if we must use Google's API\n } else {\n\n function fnc(j) {\n if (useKey) {\n findCountries(j, \"https://maps.googleapis.com/maps/api/geocode/json\", { latlng: posts[j].location_latitude + \",\" + posts[j].location_longitude, key: process.env.GOOGLE_API_KEY });\n } else {\n setTimeout(function() { findCountries(j, \"https://maps.googleapis.com/maps/api/geocode/json\", { latlng: posts[j].location_latitude + \",\" + posts[j].location_longitude }); }, missCounter * pause);\n }\n }\n\n fnc(i);\n\n missCounter++;\n }\n } else {\n doneCounter++;\n }\n }\n });\n}",
"function addCustomer(){\n var customerArray = [];\n\n transactions.forEach(function(transaction){\n if (transaction.customer !== undefined ){\n var customer = transaction.customer\n customerArray.push(customer)\n }\n });\n var filterArray = [...new Set(customerArray)]\n return (filterArray)\n}",
"function parseTxs(payload) {\n var txs = [];\n for (var i = 1; i < payload.length; i++) {\n txs.push(new Transaction(payload[i]));\n }\n return txs;\n}",
"function processCSV(data, deletion_id = null) {\n let data_arr = csvToArray(data);\n\n\tif (deletion_id) {\n\t\tdata_arr = data_arr.filter(function(item) {\n\t\t\treturn item.Deletion == deletion_id\n\t\t})\n\t}\n\n data_arr.forEach(function(d) {\n\t\td.Count = +d.Count\n\t\td.ScaledProportion = +d.ScaledProportion\n\t});\n\n return data_arr;\n}",
"static parseAnnotationCsv(inputCsv){\n var parsed_val = d3.text(inputCsv, function(text) {\n // let data = d3.csv... ; // It was that before but that variable assignment isnt needed\n d3.csv.parseRows(text, function(d) { \n return d.map(Number);\n });\n });\n \n return parsed_val.then(data => {\n return data.split(',').map(function(item){\n return parseInt(item,10);\n })\n });\n }",
"function add_records(){\n fetch('/add', {\n headers: { 'Content-Type': 'application/json'},\n method: 'POST',\n body: JSON.stringify(transactions)\n })\n}",
"function setupCsvData() {\n d3.csv(\"./data/flying-etiquette.csv\", function(data) {\n processDotsData(data);\n //this loop saves all answers form the dataset into a temporary array that can then be sorted and provides the output we need, the first column of the data is an id, which is irrelevant at this point, so the loop starts at 1\n for(let i = 1; i < data.columns.length; i++){\n //this saves the data needed for the outer ring in a seperate array\n columnsData.push(data.columns[i]);\n \n //creates a list of all the answers from every participant for a single question\n for(let j = 0; j < data.length; j++){\n tempData.push(data[j][data.columns[i]]);\n }\n \n countArrayElements(tempData, data.columns[i]);\n //reset the temporary list of answers for the next loop\n tempData = [];\n }\n });\n }",
"static fromCSV(\n csvData,\n name,\n options) {\n if (options === undefined) {\n options = {};\n }\n var stringDelimiter = options.stringDelimiter || '\"';\n var cellDelimiter = options.cellDelimiter || ',';\n var lineDelimiter = options.lineDelimiter || '\\n';\n var keepDateWithOffset = options.keepDateWithOffset || true;\n var csvLines = csvData.split(lineDelimiter);\n var dataRows = [];\n $(csvLines).each(function() {\n var csvLine = this.toString();\n var dataRow = [];\n let position = 0;\n while (position < csvLine.length) {\n var startingChar = csvLine[position];\n ++position;\n if (startingChar == stringDelimiter) {\n // Parse a delimited string\n let closingQuotePosition = csvLine.indexOf(stringDelimiter,\n position);\n do {\n if (closingQuotePosition == -1) {\n throw new Error('No closing quote found; line: \"' \n + csvLine + '\"');\n }\n if (csvLine[closingQuotePosition - 1] != '\\\\') {\n break;\n }\n closingQuotePosition = csvLine.indexOf(\n stringDelimiter,\n closingQuotePosition + 1);\n } while (true);\n dataRow.push(csvLine.substring(\n position, \n closingQuotePosition));\n position = closingQuotePosition + 1;\n } else if (startingChar == cellDelimiter) {\n // Parse an empty cell\n dataRow.push(null);\n } else {\n // Parse a non-delimited string\n let commaPosition = csvLine.indexOf(\n cellDelimiter, \n position);\n if (commaPosition == -1) {\n commaPosition = csvLine.length;\n }\n dataRow.push(csvLine.substring(\n position - 1,\n commaPosition));\n position = commaPosition;\n }\n if (position < csvLine.length \n && csvLine[position] != cellDelimiter) {\n throw new Error('Unknown cell delimiter: \"' \n + csvLine[position] + '\"');\n }\n ++position;\n }\n dataRows.push(dataRow);\n });\n return new xlsxhelper.Sheet(name, dataRows, {\n keepDateWithOffset: keepDateWithOffset\n });\n }",
"async function fsrv_elig_trxnParser(err, data, pool) {\n let result;\n parser.parseString(data, async function (err, output) {\n result = output;\n });\n let completedNum = 0;\n let bulkContent = [];\n let bulkContentSpot = 0;\n let currentSEQ_ID = 0;\n let curProdArray = [];\n let selectedProduct = \"\";\n let sql = \"\";\n let fundListNum = result.FundSetup.FundList.length;\n for (let a = 0; a < fundListNum; a++) {\n let investProductNum = result.FundSetup.FundList[a].InvstProduct.length;\n for (let b = 0; b < investProductNum; b++) {\n selectedProduct = result.FundSetup.FundList[a].InvstProduct[b];\n sql = \"SELECT FSRV_ID FROM fsrv_prod WHERE (MGMT_CODE='\" +\n result.FundSetup.FundList[a].MgmtCode[0] + \"') AND (FUND_ID='\" +\n selectedProduct.FundID[0] + \"')\";\n currentSEQ_ID = await selectQuery(pool, sql);\n //Adding eligible transactions to the bulk content\n currentObject = selectedProduct.Eligible[0].EligTrxn[0];\n currentKeys = Object.keys(currentObject);\n for (let i = 0; i < currentKeys.length; i++) {\n currentSubObject = currentObject[currentKeys[i]];\n curProdArray = [];\n curProdArray[0] = currentSEQ_ID;\n switch (i) {\n case (0):\n curProdArray[1] = \"B\";\n break;\n case (1):\n curProdArray[1] = \"CR\";\n break;\n case (2):\n curProdArray[1] = \"SI\";\n break;\n case (3):\n curProdArray[1] = \"SO\";\n break;\n case (4):\n curProdArray[1] = \"S\";\n break;\n case (5):\n curProdArray[1] = \"II\";\n break;\n case (6):\n curProdArray[1] = \"IO\";\n break;\n case (7):\n curProdArray[1] = \"EI\";\n break;\n case (8):\n curProdArray[1] = \"EO\";\n break;\n case (9):\n curProdArray[1] = \"LI\";\n break;\n case (10):\n curProdArray[1] = \"LO\";\n break;\n case (11):\n curProdArray[1] = \"F\";\n break;\n case (12):\n curProdArray[1] = \"R\";\n break;\n case (13):\n curProdArray[1] = \"CI\";\n break;\n case (14):\n curProdArray[1] = \"CO\";\n break;\n case (15):\n curProdArray[1] = \"SM\";\n break;\n }\n curProdArray[2] = currentSubObject[0];\n bulkContent[bulkContentSpot] = curProdArray;\n bulkContentSpot++;\n completedNum++;\n }\n if (completedNum >= 1000) {\n await bulkInsert(pool, bulkContent, \"INSERT INTO fsrv_elig_trxn(SEQ_ID, TRXN_TYPE, TRXN_STATUS) values (?,?,?)\");\n bulkContentSpot = 0;\n bulkContent = [];\n completedNum = 0;\n }\n }\n }\n if (bulkContent[0] != null) {\n await bulkInsert(pool, bulkContent, \"INSERT INTO fsrv_elig_trxn(SEQ_ID, TRXN_TYPE, TRXN_STATUS) values (?,?,?)\");\n }\n //console.log(bulkContent);\n return true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that removes mouse events needed for drawing new patterns | inactivatePatternCreation() {
this.chartBody.on('mousedown', null);
this.chartBody.on('mousemove', null);
this.chartBody.on('mouseup', null);
this.chartBody.on('mousemove', null);
this.chartBody.on('click', null);
d3.select("#fixedPattern").remove();
} | [
"removeMouseInteractions() {\t\t\t\n\t\tthis.ctx.canvas.removeEventListener(\"click\", this.towerStoreClick);\n\t\t\n\t\tthis.ctx.canvas.removeEventListener(\"mousemove\", this.towerStoreMove);\t\t\n\t}",
"function disable_draw() {\n drawing_tools.setShape(null);\n}",
"function mouseouthandler(event) {\n //console.log(\"the mouse is no longer over canvas:: \" + event.target.id);\n mouseIn = 'none';\n }",
"_removeMouseDownListeners() {\n if (this._screenElement.ownerDocument) {\n this.lastEvent = null;\n\n this.eventsAdded = false;\n\n this._screenElement.ownerDocument.removeEventListener(\n 'mousemove',\n this._onMouseMove\n );\n this._screenElement.ownerDocument.removeEventListener(\n 'mouseup',\n this._onMouseUp\n );\n\n clearInterval(this.revalInterval);\n this.revalInterval = null;\n\n clearInterval(this.dragInterval);\n this.dragInterval = null;\n }\n }",
"function unfocusPoints() {\r\n // Unmagnify focused point\r\n G_CHART_AREA.selectAll(\".focused\")\r\n .classed(\"focused\", false)\r\n .transition()\r\n .duration(HOVER_TRANS_TIME)\r\n .attr(\"r\", CIRCLE_MIN_RADIUS);\r\n\r\n // Hide tooltip\r\n TIP.hide();\r\n }",
"stopTrackingMouse() {\n if (this._pointerWatch)\n this._pointerWatch.remove();\n\n this._pointerWatch = null;\n }",
"__removeParticleEventListener(){\n Utils.changeCursor(this.myScene.canvasNode, \"pointer\");\n this.myScene.canvasNode.addEventListener(\"mousedown\", this.__removeParticleDisposableEvent);\n }",
"clearTechToolMousePos() {\r\n this.m_mousePushed_x = -1;\r\n this.m_mousePushed_y = -1;\r\n this.m_mouseMoving_x = -1;\r\n this.m_mouseMoving_y = -1;\r\n this.m_drawInf.setMousePos(0, 0);\r\n }",
"function removeAllToolOverlays() {\n\t$('#notepad-body').find('.tools-disp').removeClass('tools-disp');\n\t$('#notepad-body').find('.expand-button i').removeClass();\n\t$('#notepad-body').find('.expand-button i').addClass('fa fa-ellipsis-h');\n\t$('#notepad-body .col-4 .color-selector').spectrum(\"destroy\");\n}",
"function eraseStroke(evt) {\n // mouse position\n const mouseX = evt.offsetX / slideZoom;\n const mouseY = evt.offsetY / slideZoom;\n const point = [mouseX, mouseY];\n\n svg.querySelectorAll(\"path\").forEach((stroke) => {\n if (isPointInStroke(stroke, point)) {\n pushUndoHistory(\"erase stroke\");\n stroke.remove();\n needToSave(true);\n }\n });\n }",
"function mouseReleased(){\n\n shocked = false;\n\n}",
"activateFlexiblePatternCreation() {\n \n var drawing = false;\n var startInd, stopInd;\n var x1, x2;\n var bandwidth = this.xScale.bandwidth();\n var padding = this.xScale.step()*this.xScale.padding();\n var rect;\n\n this.chartBody.on('mousedown', (d, i, nodes) => {\n drawing = true;\n // calculate index of clicked candle\n startInd = this.calculateClickedCandle(d3.mouse(nodes[i]));\n x1 = this.xScale(this.dtArray[startInd]) + bandwidth/2\n rect = this.chartBody.append(\"rect\").attr(\"class\", this.rectClassDict[this.newPatternDir])\n .attr(\"y\", 0)\n .attr(\"height\", this.h);\n });\n\n this.chartBody.on('mousemove', (d, i, nodes) => { \n if (drawing) {\n x2 = d3.mouse(nodes[i])[0];\n if (x2 >= x1) {\n rect.attr(\"x\", x1 - bandwidth/2 - padding/2)\n .attr(\"width\", x2 - x1 + bandwidth/2 + padding/2);\n } else if (x2 < x1) {\n rect.attr(\"x\", x2)\n .attr(\"width\", x1 + bandwidth/2 + padding/2 - x2);\n }\n }\n });\n\n this.chartBody.on('mouseup', (d, i, nodes) => {\n stopInd = this.calculateClickedCandle(d3.mouse(nodes[i]));\n x2 = this.xScale(this.dtArray[stopInd]) + bandwidth/2;\n if (x2 >= x1) {\n rect.attr(\"x\", x1 - bandwidth/2 - padding/2)\n .attr(\"width\", x2 - x1 + bandwidth + padding);\n this.confirmNewPattern(rect, startInd, stopInd, this.newPatternDir);\n } else if (x2 < x1) {\n rect.attr(\"x\", x2 - bandwidth/2 - padding/2)\n .attr(\"width\", x1 - x2 + bandwidth + padding);\n this.confirmNewPattern(rect, stopInd, startInd, this.newPatternDir);\n }\n drawing = false;\n });\n }",
"function resetDrawingHighlights() {\n abEamTcController.resetDrawingHighlights();\n}",
"function removeOutlineMap() {\n\tthis.style.border = \"1px solid #fff\";\n\tif (!this.classList.contains(\"starred\")) {\n\t\tvar star = document.getElementById(\"hoverStar\");\n\t\tthis.removeChild(star);\n\t}\n}",
"function pwPlateSelector_plateOnMouseOut(plate){\r\n\t//empty function\r\n}",
"function clearHighlightCanvas() {\n\tvar highlightCanvas = document.getElementById('highlight-points')\n\tvar highlightCtx = highlightCanvas.getContext('2d')\n\thighlightCtx.clearRect(0, 0, highlightCanvas.offsetWidth, highlightCanvas.offsetHeight)\n}",
"removeShortcut(keys) {\n Mousetrap.unbind(keys)\n }",
"function removeEventHandlers()\r\n {\r\n // remove keyboard events\r\n if (keyHandler != null)\r\n {\r\n $(document).unbind(\"keydown keyup\", keyHandler);\r\n }\r\n\r\n // remove mouse wheel events\r\n if (mouseWheelHandler != null)\r\n {\r\n $qtip.unbind(\"mousewheel\", mouseWheelHandler);\r\n $label.unbind(\"mousewheel\", mouseWheelHandler);\r\n }\r\n\r\n keyHandler = null;\r\n mouseWheelHandler = null;\r\n }",
"function mouseGrab(e) {\n console.log(\"mouseGrab\");\n var evt = e|| window.event;\n mousePiece = evt.target || evt.srcElement;\n maxZ ++;\n\n //Remove piece from array and stop animation\n $(mousePiece).stop(true);\n var index = movingPieces.indexOf(mousePiece);\n movingPieces.splice(index, 1);\n console.log(movingPieces);\n\n //Loop through an array with all removed pieces and assign a stop() to them\n // I think the updating of the animate array is a bit slow so it doesn't always apply when you click the piece\n stoppedPieces.push(mousePiece);\n\n mousePiece.style.zIndex = maxZ; // Place the piece above other objects\n\n mousePiece.style.cursor = \"move\";\n\n var mouseX = evt.clientX; // x-coordinate of pointer\n var mouseY = evt.clientY; // y-coordinate of pointer\n\n /* Calculate the distance from the pointer to the piece */\n diffX = parseInt(mousePiece.style.left) - mouseX;\n diffY = parseInt(mousePiece.style.top) - mouseY;\n\n /* Add event handlers for mousemove and mouseup events */\n addEvent(document, \"mousemove\", mouseMove, false);\n addEvent(document, \"mouseup\", mouseDrop, false);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse setting groups, skips columns with empty titles returns object where fields = group names: result. == columnNumber columnNumber is absoulute, starting from 1. | function getGroups(sheet){
var topLeftRow = paramSheetStructure.groupTitle.row;
var topLeftCol = paramSheetStructure.groupTitle.col;
var colCount = sheet.getLastColumn() - topLeftCol + 1;
// get column with parameter names. actually get 2D-range with colCount = 1
var headers = sheet.getRange(topLeftRow, topLeftCol, 1, colCount).getValues();
var result = {};
for (var c = 0; c < headers[0].length; c++) {
var settingGroup = headers[0][c];
if (settingGroup == '')
continue; // skip empty column names
result[settingGroup] = topLeftCol + c;
}
return result;
} | [
"function _addFieldGroups() {\n var dialog = $('#perc-folder-props-dialog');\n var fieldGroups = [\n { groupName : \"perc-folder-general-properties-container\", groupLabel : \"General\"}\n , { groupName : \"perc-user-permissions-container\", groupLabel : \"Permissions\"}\n , { groupName : \"perc-asset-folder-sites-container\", groupLabel : \"Security\"}\n ];\n \n $.each(fieldGroups, function(index) {\n // Create HTML markup with the groupName minimizer/maximizer and\n // insert it before the 1st field in each group\n var minmaxClass = (index == 0) ? \"perc-section-items-minimizer\" : \"perc-section-items-maximizer\";\n var groupHtml =\n \"<div class='perc-section-header'>\" +\n \"<div class='perc-section-label' groupName='\" + this.groupName + \"'>\" +\n \"<span class='perc-min-max \" + minmaxClass + \"' ></span>\" + this.groupLabel +\n \"</div>\" +\n \"</div>\";\n\n dialog.find('#' + this.groupName).before(groupHtml);\n\n // The first group will be the only one expanded (hide all others)\n index != 0 && dialog.find('#' + this.groupName).hide();\n });\n\n // Bind collapsible event\n dialog.find(\".perc-section-label\").unbind().click(function() {\n var self = $(this);\n self.find(\".perc-min-max\")\n .toggleClass('perc-section-items-minimizer')\n .toggleClass('perc-section-items-maximizer');\n \n dialog.find('#' + self.attr('groupName')).toggle();\n });\n }",
"function getGroupbyField(query) {\n var field = query.split('group by')[1].trim();\n // var filed = query.split('group by')[1].split('order by')[0].trim();\n console.log(field);\n}",
"groupFields (groupsArray, field, i, fieldsArray) {\n if (field.props.group === 'start') {\n this.openGroup = true\n groupsArray.push([])\n }\n\n if (this.openGroup) {\n groupsArray[groupsArray.length - 1].push(field)\n } else {\n groupsArray.push([field])\n }\n\n if (field.props.group === 'end') {\n this.openGroup = false\n }\n return groupsArray\n }",
"parseGroup() {\n const startPos = this.tok.pos;\n this.tok.consume(\"(\");\n let items = [];\n while (true) {\n const next = this.tok.peek();\n if (next == \"(\")\n items.push(this.parseGroup());\n else if (next !== null && /^[A-Z][a-z]*$/.test(next))\n items.push(this.parseElement());\n else if (next == \")\") {\n this.tok.consume(next);\n if (items.length == 0)\n throw new ParseError(\"Empty group\", startPos, this.tok.pos);\n break;\n }\n else\n throw new ParseError(\"Element, group, or closing parenthesis expected\", this.tok.pos);\n }\n return new Group(items, this.parseOptionalNumber());\n }",
"function loadGroups(that) {\r\n if (that.config.groups !== undefined) {\r\n $.each(that.config.groups, function (index, value) {\r\n //Group reducing function by Size\r\n if (that.config.groups[index].context === \"context:reduce\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduce(\r\n function (p, v) {\r\n ++p.count;\r\n p.AvgSize = v.AvgSize;\r\n p.sumAvgSize += v[that.config.groups[index].datafield];\r\n p.avgAvgSize = p.sumAvgSize / p.count;\r\n p.fluctuation += v[that.config.groups[index].datafield] - p.lastAvgSize;\r\n p.lastAvgSize = v[that.config.groups[index].datafield];\r\n \t\t\t if(p.avgAvgSize == 0){\r\n \t\t\t\tp.fluctuationPercentage = (Math.abs(p.fluctuation) / 1) * 100;\r\n \t\t\t }\r\n \t\t\t else{\r\n \tp.fluctuationPercentage = (Math.abs(p.fluctuation) / p.avgAvgSize) * 100;\r\n }\r\n return p;\r\n },\r\n function (p, v) {\r\n --p.count;\r\n p.AvgSize = v.AvgSize;\r\n p.sumAvgSize -= v[that.config.groups[index].datafield];\r\n p.avgAvgSize = p.sumAvgSize / p.count;\r\n p.fluctuation -= v[that.config.groups[index].datafield] - p.lastAvgSize;\r\n p.lastAvgSize = v[that.config.groups[index].datafield];\r\n if(p.avgAvgSize == 0){\r\n \t\t\t\tp.fluctuationPercentage = (Math.abs(p.fluctuation) / 1) * 100;\r\n \t\t\t }\r\n \t\t\t else{\r\n \t\t\t\t p.fluctuationPercentage = (Math.abs(p.fluctuation) / p.avgAvgSize) * 100;\r\n \t\t\t }\r\n return p;\r\n },\r\n function () {\r\n return { count: 0, AvgSize: 0, sumAvgSize: 0, avgAvgSize: 0, fluctuation: 0, lastAvgSize: 0, fluctuationPercentage: 0 };\r\n }\r\n );\r\n }\r\n\r\n //Group function\r\n if (that.config.groups[index].context === \"context:groupkey\") {\r\n //that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group(function(d){return d[that.config.groups[index].datafield];});\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group(function(d){\r\n console.log(d[that.config.groups[index].datafield]);\r\n return d[that.config.groups[index].datafield];\r\n });\r\n }\r\n\r\n //Group function\r\n if (that.config.groups[index].context === \"context:group\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group();\r\n }\r\n\r\n //Group Reduce Count function\r\n if (that.config.groups[index].context === \"context:reducecount\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduceCount(function (d) {\r\n return d3.time.month(d.dd);\r\n });\r\n }\r\n\r\n //Group Reduce Count function\r\n if (that.config.groups[index].context === \"context:reducecountkey\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduceCount();\r\n }\r\n\r\n //Group Reduce Sum function\r\n if (that.config.groups[index].context === \"context:reducesum\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduceSum(function (d) {\r\n return d[that.config.groups[index].datafield];\r\n });\r\n }\r\n });\r\n }\r\n }",
"_buildGroupHeader(){\n\t\tthis.element.classList.add(\"tabulator-col-group\");\n\t\tthis.element.setAttribute(\"role\", \"columngroup\");\n\t\tthis.element.setAttribute(\"aria-title\", this.definition.title);\n\n\t\t//asign additional css classes to column header\n\t\tif(this.definition.cssClass){\n\t\t\tvar classNames = this.definition.cssClass.split(\" \");\n\t\t\tclassNames.forEach((className) => {\n\t\t\t\tthis.element.classList.add(className);\n\t\t\t});\n\t\t}\n\n\t\tthis.titleElement.style.textAlign = this.definition.headerHozAlign;\n\n\t\tthis.element.appendChild(this.groupElement);\n\t}",
"visitGrouping_sets_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function _getGroupDataSelector(item) {\n return item.group;\n }",
"static generateFlatGroupListFromIniFile(inventory) {\r\n const hostsIni = loadIniFile.sync( inventory.filenameFullPath )\r\n var groupList = {}\r\n \r\n for (var groupName in hostsIni) {\r\n var _groupName = Group.normalizeGroupName(groupName)\r\n \r\n if (groupList[_groupName] === undefined) {\r\n groupList[_groupName] = new Group(inventory.name, inventory.env, groupName)\r\n }\r\n \r\n if (Group.hasHosts(groupName)) {\r\n // add hostnames\r\n for(var hostname in hostsIni[groupName]) {\r\n groupList[_groupName].hostnames.push(hostname.split(' ')[0])\r\n }\r\n }\r\n else if (Group.hasSubgroups(groupName)) {\r\n // add subgroups\r\n for(var subGroupName in hostsIni[groupName]) {\r\n groupList[_groupName].subgroups.push(subGroupName)\r\n // need to add goups here as well because they may be listed only as subgroups\r\n if (groupList[subGroupName] === undefined) {\r\n groupList[subGroupName] = new Group(inventory.name, inventory.env, subGroupName)\r\n }\r\n }\r\n } else if (Group.hasGroupVariables(groupName)) {\r\n // add variables from the hosts ini-file\r\n for (var varName in hostsIni[groupName]) {\r\n groupList[_groupName].variables[varName] = hostsIni[groupName][varName]\r\n }\r\n } else {\r\n console.log(\"During generation of flat group list, group '%s' could not be considered!\", groupName)\r\n }\r\n }\r\n\r\n // add variables and configuration from subfolder group_vars\r\n Group.internal_addVariablesFromFolder(inventory, groupList)\r\n\r\n Group.internal_addGroupAllIfNotExist(inventory, groupList)\r\n\r\n Group.internal_addGroupUngroupedIfNotExist(inventory, groupList)\r\n \r\n // console.log(\"Flat Group List: \")\r\n // console.dir(JSON.parse(JSON.stringify(groupList)), {depth: null, colors: true})\r\n return groupList\r\n }",
"function applyGrouping(groups) {\n var order = 0;\n groups.forEach(function (group, groupNumber) {\n group.forEach(function (player) {\n player.grouping = groupNumber;\n player.start_order = order;\n\n order++;\n });\n });\n }",
"visitGrouping_sets_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function collectGroups(groups) {\n let name = \"\"\n let tags = new Set()\n for (let group of groups) {\n name += `[${group.name}]+`\n collect(tags, group.tags)\n }\n\n name = name.substring(0, name.length - 1)\n \n return new Group(name, tags)\n}",
"function processContentGroups(myDoc) {\r\n\t// Content groups are in original 'main' group\r\n\tvar mainGroup = myDoc.groupItems[c_itsMainGroup];\t\r\n // So let's loop through...\r\n\tvar contentTotal = mainGroup.groupItems.length;\r\n\t// I can't assume that mainGroup contains *only* panel groups...\r\n\tfor (var gNo = contentTotal - 1; gNo >= 0; gNo--) {\r\n var myGroup = mainGroup.groupItems[gNo];\r\n if (myGroup.name.search('content') >= 0) {\r\n processContentGroup(myGroup, myDoc); \r\n } else if (myGroup.name.search('table') >= 0) {\r\n processTableGroup(myGroup, myDoc);\r\n }\r\n\t}\r\n\treturn true;\r\n}",
"function group_parsing(route, dest){\n d3.text(route, function (csvdata) {\n var groups = {};\n var grouped = {};\n var num = +experimentr.data()['num_pairs'];\n var parsedCSV = d3.csv.parseRows(csvdata);\n for (var j = 1; j < parsedCSV.length; j++) {\n if (!(parsedCSV[j][0] in groups)) {\n groups[parsedCSV[j][0]] = [parsedCSV[j]];\n } else {\n groups[parsedCSV[j][0]] = groups[parsedCSV[j][0]].concat([parsedCSV[j]]);\n }\n }\n var values = Object.keys(groups).map(function (key) {\n return groups[key];\n });\n var raw_binary = values.filter(function (d) {\n return d.length == 2;\n });\n if(experimentr.data()['section']=='mat'){\n n_pair = raw_binary.length;\n }\n if(experimentr.data()['section']=='section2'){\n s2_n_pair = raw_binary.length;\n }\n for(i in groups){\n var t = groups[i][0][groups[i][0].length-1];\n if(!(t in grouped)){\n grouped[t] = [groups[i]];\n }else{\n grouped[t] = grouped[t].concat([groups[i]]);\n }\n }\n data[dest] = [];\n var keys = Object.keys(grouped);\n keys.sort();\n var i, len = keys.length;\n for(i=0;i<len;i++){\n data[dest].push(grouped[keys[i]]);\n }\n data[dest].push([]);\n var answer = [];\n for(var i=0;i<raw_binary.length;i++){\n answer.push(raw_binary[i][0][17]);\n }\n data[dest+'_answer'] = answer;\n experimentr.addData(data);\n });\n}",
"function GroupItemMetadataProvider(options) {\n var _grid;\n var _defaults = {\n groupCssClass: \"slick-group\",\n totalsCssClass: \"slick-group-totals\",\n groupFocusable: true,\n totalsFocusable: false,\n toggleCssClass: \"slick-group-toggle\",\n toggleExpandedCssClass: \"expanded\",\n toggleCollapsedCssClass: \"collapsed\",\n enableExpandCollapse: true\n };\n\n options = $.extend(true, {}, _defaults, options);\n\n function defaultGroupCellFormatter(row, cell, value, columnDef, item) {\n if (!options.enableExpandCollapse) {\n return item.title;\n }\n\n return \"<span class='\" + options.toggleCssClass + \" \" +\n (item.collapsed ? options.toggleCollapsedCssClass : options.toggleExpandedCssClass) +\n \"'></span>\" + item.title;\n\n }\n\n function defaultTotalsCellFormatter(row, cell, value, columnDef, item) {\n return (columnDef.groupTotalsFormatter && columnDef.groupTotalsFormatter(item, columnDef)) || \"\";\n }\n\n\n function init(grid) {\n _grid = grid;\n _grid.onClick.subscribe(handleGridClick);\n _grid.onKeyDown.subscribe(handleGridKeyDown);\n\n }\n\n function destroy() {\n if (_grid) {\n _grid.onClick.unsubscribe(handleGridClick);\n _grid.onKeyDown.unsubscribe(handleGridKeyDown);\n }\n }\n\n function handleGridClick(e, args) {\n var item = this.getDataItem(args.row);\n if (item && item instanceof Slick.Group && $(e.target).hasClass(options.toggleCssClass)) {\n if (item.collapsed) {\n this.getData().expandGroup(item.value);\n }\n else {\n this.getData().collapseGroup(item.value);\n }\n\n e.stopImmediatePropagation();\n e.preventDefault();\n }\n }\n\n // TODO: add -/+ handling\n function handleGridKeyDown(e, args) {\n if (options.enableExpandCollapse && (e.which == $.ui.keyCode.SPACE)) {\n var activeCell = this.getActiveCell();\n if (activeCell) {\n var item = this.getDataItem(activeCell.row);\n if (item && item instanceof Slick.Group) {\n if (item.collapsed) {\n this.getData().expandGroup(item.value);\n }\n else {\n this.getData().collapseGroup(item.value);\n }\n\n e.stopImmediatePropagation();\n e.preventDefault();\n }\n }\n }\n }\n\n function getGroupRowMetadata(item) {\n return {\n selectable: false,\n focusable: options.groupFocusable,\n cssClasses: options.groupCssClass,\n columns: {\n 0: {\n colspan: \"*\",\n formatter: defaultGroupCellFormatter,\n editor: null\n }\n }\n };\n }\n\n function getTotalsRowMetadata(item) {\n return {\n selectable: false,\n focusable: options.totalsFocusable,\n cssClasses: options.totalsCssClass,\n formatter: defaultTotalsCellFormatter,\n editor: null\n };\n }\n\n\n return {\n \"init\": init,\n \"destroy\": destroy,\n \"getGroupRowMetadata\": getGroupRowMetadata,\n \"getTotalsRowMetadata\": getTotalsRowMetadata\n };\n }",
"function RecordSetGroup(props) {\n return __assign({ Type: 'AWS::Route53::RecordSetGroup' }, props);\n }",
"function kh_parseDefault() {\n var value = this.result[SETTINGS_KEYS.DEFAULT];\n if (value) {\n currentSettings.defaultLayouts = value;\n }\n kh_loadedSetting(SETTINGS_KEYS.DEFAULT);\n}",
"function setupYScaleAndGroups(tuples, yScale, rowHeight, padGroups, sortKeys) {\n var yGroups = [],\n // yGrouping is a specification \"#,#\" of the order for sorting the (eRAP_ID, dept) tuples\n // => 0 = eRAP_ID; 1 = department_name/collection_unit; leftmost number takes precedence\n yGrouping = _.map($yGrouping.val().split(\",\"), parseInt10),\n selector = function(tup) { return _.map(yGrouping, function(i) { return tup[i]; }) },\n paddedDomain = [],\n domain, height, prevGroup;\n \n sortKeys = sortKeys || [];\n domain = _.uniq(_.map(tuples, selector), false, stringifyTuple);\n domain = _.sortBy(domain, function(tup) { \n return stringifyTuple(_.map(tup, function(v, i) { \n return sortKeys[yGrouping[i]] ? sortKeys[yGrouping[i]][v] : v;\n }));\n });\n \n if (padGroups) {\n _.each(domain, function(tup, i) { \n if(i > 0 && tup[0] != prevGroup) { paddedDomain.push([prevGroup, null]); }\n paddedDomain.push(tup);\n prevGroup = tup[0];\n });\n paddedDomain.push([prevGroup, null]);\n domain = paddedDomain;\n }\n height = domain.length * rowHeight;\n yScale.rangePoints(padGroups ? [0.5 * rowHeight, height - rowHeight * 0.5] : [0, height - rowHeight]);\n yScale.domain(domain);\n \n _.each(domain, function(tup) {\n if (!yGroups.length || _.last(yGroups).label !== tup[0]) {\n var initialLength = (yGrouping.length == 1 && padGroups ? 2 : 1);\n yGroups.push({label: tup[0], start: tup, end: tup, length: initialLength});\n } else if (yGrouping.length > 1) {\n _.last(yGroups).end = tup;\n _.last(yGroups).length += 1;\n }\n });\n yGroups.grouping = yGrouping;\n yGroups.selector = selector;\n return yGroups;\n }",
"getCommandsByGroup() {\n const groupsToCommand = {\n \"movement\": [],\n \"editing\": [],\n \"selection\": [],\n \"tabs\": [],\n \"formatting\": [],\n \"other\": [],\n };\n\n for (const [key, command] of Object.entries(Commands.commands)) {\n groupsToCommand[command.group].push(key);\n }\n return groupsToCommand;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bresenham's line algo, fast but not rasterized | function drawLineBresenham(x0, y0, x1, y1, intensity, destArray) {//All the drawn pixels have the same intensity
/*
function draw(x,y){
if (x>=0 && y>=0 && x <sliceDimension && y < sliceDimension){
sliceGrid[x][y] += intensity;
}
}
*/
var dx = Math.abs(x1 - x0);
var dy = Math.abs(y1 - y0);
var sx = (x0 < x1) ? 1 : -1;
var sy = (y0 < y1) ? 1 : -1;
var err = dx - dy;
while(true) {
destArray[x0][y0] += intensity;
if (Math.abs(x0 - x1) < 0.0001 && Math.abs(y0 - y1) < 0.0001) break;
var e2 = 2*err;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
}
} | [
"function drawLineBresenham(ctx, startX, startY, endX, endY, color, storeIntersectionForScanlineFill) {\n\n var x = startX;\n var y = startY;\n\n // Abstand\n var dX = endX - startX;\n var dY = endY - startY;\n\n // Beträge\n var dXAbs = Math.abs(dX);\n var dYAbs = Math.abs(dY);\n\n // Start kleiner als Ende\n var dXSign = (dX > 0) ? 1 : -1;\n var dYSign = (dY > 0) ? 1 : -1;\n\n // shortcuts for speedup.\n var dXAbs2 = 2 * dXAbs;\n var dYAbs2 = 2 * dYAbs;\n var dXdYdiff2 = 2 * (dXAbs - dYAbs);\n var dYdXdiff2 = 2 * (dYAbs - dXAbs);\n var err;\n\n if(dXAbs >= dYAbs){\n err = dXAbs - dYAbs2;\n while (x != endX){\n x += dXSign;\n if (err > 0){\n err -= dYAbs2;\n } else {\n y += dYSign;\n err += dXdYdiff2;\n addIntersection(x, y);\n }\n framebuffer.set(x, y, getZ(x,y), color);\n }\n } else {\n err = dYAbs - dXAbs2;\n while (y != endY){\n y += dYSign;\n if(err > 0){\n err -= dXAbs2;\n } else {\n x += dXSign;\n err += dYdXdiff2;\n }\n framebuffer.set(x, y, getZ(x,y), color);\n addIntersection(x, y);\n }\n }\n }",
"breshnamDrawLine (point0, point1) {\n let x0 = point0.x >> 0;\n let y0 = point0.y >> 0;\n let x1 = point1.x >> 0;\n let y1 = point1.y >> 0;\n let dx = Math.abs(x1 - x0);\n let dy = Math.abs(y1 - y0);\n let color = new BABYLON.Color4(1,1,0,1);\n\n if(dy > dx){\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dx - dy;\n\n for(let y=y0; y!=y1; y=y+sy){\n this.drawPoint(new BABYLON.Vector2(x0, y), color);\n if(err >= 0) {\n x0 += sx ;\n err -= dy;\n }\n err += dx;\n }\n }\n else{\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dy - dx;\n\n for(let x=x0; x!=x1; x=x+sx){\n this.drawPoint(new BABYLON.Vector2(x, y0), color);\n if(err >= 0) {\n y0 += sy ;\n err -= dx;\n }\n err += dy;\n }\n }\n }",
"function rayXline(rx, ry, dx, dy, x1, y1, x2, y2, infinite){\n\t\n\tvar lx, ly, d, nx, ny, a, b;\n\tlx = x2 - x1;\n\tly = y2 - y1;\n\td = Math.sqrt(lx * lx + ly * ly);\n\tnx = ly / d;\n\tny = -lx / d;\n\t\n\ta = dx * nx + dy * ny;\n\tb = (x1 - rx) * nx + ( y1 - ry ) * ny;\n\n\tif( a != 0 && ( a > 0 ^ b < 0 ) ){//Check if there is an intersection with the inifinite line\n\t\n\t\tl = b / a;\n\t\tif( infinite )\n\t\t\treturn l;\n\t\telse {\n\t\t\tvar xx = rx + dx * l;\n\t\t\tvar yy = ry + dy * l;\n\t\t\tvar g = ((xx - x1) * lx + (yy - y1) * ly) / (lx * lx + ly * ly);\n\t\t\tif( g >= 0 && g <= 1)\n\t\t\t\treturn l;\n\t\t\telse return null;\n\t\t\t\n\t\t}\n\t} else return null;\n}",
"shakyLine(x0, y0, x1, y1) {\n // Let $v = (d_x, d_y)$ be a vector between points $P_0 = (x_0, y_0)$\n // and $P_1 = (x_1, y_1)$\n const dx = x1 - x0;\n const dy = y1 - y0;\n\n // Let $l$ be the length of $v$\n const l = Math.sqrt(dx * dx + dy * dy);\n\n // Now we need to pick two random points that are placed\n // on different sides of the line that passes through\n // $P_1$ and $P_2$ and not very far from it if length of\n // $P_1 P_2$ is small.\n const K = Math.sqrt(l) / 1.5;\n const k1 = Math.random();\n const k2 = Math.random();\n const l3 = Math.random() * K;\n const l4 = Math.random() * K;\n\n // Point $P_3$: pick a random point on the line between $P_0$ and $P_1$,\n // then shift it by vector $\\frac{l_1}{l} (d_y, -d_x)$ which is a line's normal.\n const x3 = x0 + dx * k1 + dy / l * l3;\n const y3 = y0 + dy * k1 - dx / l * l3;\n\n // Point $P_3$: pick a random point on the line between $P_0$ and $P_1$,\n // then shift it by vector $\\frac{l_2}{l} (-d_y, d_x)$ which also is a line's normal\n // but points into opposite direction from the one we used for $P_3$.\n const x4 = x0 + dx * k2 - dy / l * l4;\n const y4 = y0 + dy * k2 + dx / l * l4;\n\n // Draw a bezier curve through points $P_0$, $P_3$, $P_4$, $P_1$.\n // Selection of $P_3$ and $P_4$ makes line 'jerk' a little\n // between them but otherwise it will be mostly straight thus\n // creating illusion of being hand drawn.\n this.ctx.moveTo(x0, y0);\n this.ctx.bezierCurveTo(x3, y3, x4, y4, x1, y1);\n }",
"function bezierSelfIntersection(ps) {\n if (ps.length < 4) {\n // lines and quadratics don't have self-intersections (except of course\n // degenerate quadratics).\n return undefined;\n }\n // Apply fast pre-filter - we assume without good reason that about 1 in 10 \n // beziers will have a cusp.\n // First get fast naively calculated coefficients\n let { coeffs: [a, b, c], errBound: [a_, b_, c_] } = get_coeffs_3_1.getCoeffs3(ps);\n // if error in a cannot discern it from zero\n if (abs(a) <= a_) {\n // it is rare to get here \n // check for sure if a === 0 exactly\n let [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = ps;\n let a3 = x3 - 3 * x2 + 3 * x1 - x0; // <= exact if max bit-aligned bitlength <= 50\n let a2 = 3 * x2 - 6 * x1 + 3 * x0; // <= exact if max bit-aligned bitlength <= 49\n let b3 = y3 - 3 * y2 + 3 * y1 - y0; // <= exact if max bit-aligned bitlength <= 50\n let b2 = 3 * y2 - 6 * y1 + 3 * y0; // <= exact if max bit-aligned bitlength <= 49\n let a2b3 = flo_numerical_1.twoProduct(a2, b3);\n let a3b2 = flo_numerical_1.twoProduct(a3, b2);\n if (a2b3[0] === a3b2[0] && a2b3[1] === a3b2[1]) {\n return undefined; // a === 0 => no roots possible\n }\n }\n // DD = discriminant = b^2 - 4ac\n // calculate DD and its absolute error DD_\n let bb = b * b;\n let bb_ = 2 * b_ * abs(b) + error_analysis_1.γ1 * bb; // the error in b**2\n let ac4 = 4 * a * c;\n let ac4_ = 4 * (a_ * abs(c) + abs(a) * c_) + error_analysis_1.γ1 * abs(ac4);\n let DD = bb - ac4;\n let DD_ = bb_ + ac4_ + error_analysis_1.γ1 * abs(DD);\n // if the discriminant is smaller than negative the error bound then\n // certainly there are no roots, i.e. no cusp and no self-intersections\n if (DD < -DD_) {\n // discriminant is definitely negative\n return undefined;\n }\n // if the discriminant is definitely positive\n if (DD > DD_) {\n // calculate roots naively as a fast pre-filter\n let { est: D, err: D_ } = flo_numerical_1.sqrtWithErr(DD, DD_);\n let q1;\n if (b >= 0) {\n // let r1 = (-b - D) / 2*a;\n // let r2 = (2*c) / (-b - D);\n q1 = -b - D;\n }\n else {\n // let r2 = (-b + D) / 2*a;\n // let r1 = (2*c) / (-b + D);\n q1 = -b + D;\n }\n let q1_ = b_ + D_ + error_analysis_1.γ1 * abs(q1);\n let { est: r1, err: r1_ } = flo_numerical_1.divWithErr(q1, 2 * a, q1_, 2 * a_);\n let { est: r2, err: r2_ } = flo_numerical_1.divWithErr(2 * c, q1, 2 * c_, q1_);\n //console.log(r1,r2);\n // the actual 'filter' follows\n // IF\n // at least one root is definitely smaller than 0 ||\n // at least one root is definitely larger than 1 \n // THEN no self-intersection\n if (r1 + r1_ < 0 || r2 + r2_ < 0 ||\n r1 - r1_ > 1 || r2 - r2_ > 1) {\n return undefined;\n }\n }\n // we need to check exactly - (a !== 0) at this point - tested for earlier\n let [A, B, C] = get_coeffs_3_2.getCoeffs3Exact_(ps);\n // exact - DD = b^2 - 4ac\n let eDD = edif(epr(B, B), sce(4, epr(A, C)));\n let sgn = flo_numerical_1.sign(eDD);\n if (sgn < 0) {\n // sgn < 0 => no real roots => no cusp or double point for t in [0,1]\n return undefined;\n }\n if (sgn > 0) {\n let D = flo_numerical_1.qSqrt(toQuad(eDD));\n A = toQuad(A);\n B = toQuad(B);\n C = toQuad(C);\n let nBD;\n if (flo_numerical_1.sign(B) >= 0) {\n nBD = qno(qaq(B, D));\n //t1 = (-B - D) / (2*A);\n //t2 = (2*C) / (-B - D);\n }\n else {\n nBD = qaq(qno(B), D);\n //t1 = (2*C) / (-B + D);\n //t2 = (-B + D) / (2*A);\n }\n let t1 = flo_numerical_1.estimate(qdivq(nBD, qm2(A))); // max 1 ulps out\n let t2 = flo_numerical_1.estimate(qdivq(qm2(C), nBD)); // max 1 ulps out\n // if any root is outside the range => no double point for t in [0,1]\n if (t1 < -eps || t1 > 1 + eps ||\n t2 < -eps || t2 > 1 + eps) {\n return undefined;\n }\n t1 = t1 < 0\n ? 0\n : t1 > 1 ? 1 : t1;\n t2 = t2 < 0\n ? 0\n : t2 > 1 ? 1 : t2;\n return t1 < t2 ? [t1, t2] : [t2, t1];\n }\n // sign === 0 => cusp\n // set t = b/d = b/-2a\n let d = flo_numerical_1.eMultByNeg2(A);\n let sgnB = flo_numerical_1.sign(B);\n let sgnD = flo_numerical_1.sign(d);\n // if result is negative the cusp is outside the bezier endpoints\n let sgn_ = sgnB * sgnD;\n if (sgn_ < 0) {\n return undefined;\n }\n // if result is > 1 the cusp is outside the bezier endpoints\n if (flo_numerical_1.compare(flo_numerical_1.abs(B), flo_numerical_1.abs(d)) > 0) {\n return undefined;\n }\n let qB = toQuad(B);\n let qd = toQuad(d);\n let qt = qdivq(qB, qd);\n let t = qt[1];\n return [t, t];\n}",
"function sweptCircleXline(cx,cy,r,dx,dy,x1,y1,x2,y2){\n\t\n\tif(x2 == x1 && y2 == y1){\n\t\tif( (cx - x1) * (cx - x1) + (cy - y1) * (cy - y1) < r * r){\n\t\t\treturn 0;\n\t\t}else {\n\t\t\treturn rayCircle(cx, cy, dx, dy, x1, y1, r, 1);\n\t\t}\n\t} else {\n\n\t\tvar lx = x2 - x1;\n\t\tvar ly = y2 - y1;\n\t\t\n\t\tvar d = Math.sqrt(lx * lx + ly * ly);\n\t\tvar nx = ly / d;\n\t\tvar ny = -lx / d;\n\t\t\n\t\tif( Math.abs(nx * (cx - x1) + ny * (cy - y1)) > r ){\n\t\t\t\n\t\t\tvar cxo, cyo;\n\n\t\t\tif( (x1 - cx) * nx + ( y1 - cy ) * ny < 0 ) {\n\t\t\t\tcxo = cx - nx * r;\n\t\t\t\tcyo = cy - ny * r;\n\t\t\t} else {\n\t\t\t\tcxo = cx + nx * r;\n\t\t\t\tcyo = cy + ny * r;\n\t\t\t}\n\t\t\t\n\t\t\tvar a = dx * nx + dy * ny;\n\t\t\tvar b = (x1 - cxo) * nx + ( y1 - cyo ) * ny;\n\t\t\t\n\t\t\tif( a != 0 && ( a > 0 ^ b < 0 ) ){\n\t\t\t\n\t\t\t\tvar l = b / a;\n\t\t\t\tvar xx = cxo + dx * l;\n\t\t\t\tvar yy = cyo + dy * l;\n\t\t\t\tvar g = ((xx - x1) * lx + (yy - y1) * ly) / (lx * lx + ly * ly);\n\t\t\t\t\n\t\t\t\tif( g < 0 ){\n\t\t\t\t\treturn rayCircle(cx, cy, dx, dy, x1, y1, r, 1);\n\t\t\t\t}else if( g > 1 ){\n\t\t\t\t\treturn rayCircle(cx, cy, dx, dy, x2, y2, r, 1);\n\t\t\t\t}else {\n\t\t\t\t\treturn l;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\n\t\t\tif( lx * (cx - x1) + ly * (cy - y1) < 0 ){\n\t\t\t\n\t\t\t\tif( (cx - x1) * (cx - x1) + (cy - y1) * (cy - y1) < r * r){\n\t\t\t\t\treturn 0;\n\t\t\t\t}else {\n\t\t\t\t\treturn rayCircle(cx, cy, dx, dy, x1, y1, r, 1);\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t} else if( lx * (cx - x2) + ly * (cy - y2) > 0 ){\n\t\t\t\n\t\t\t\tif( (cx - x2) * (cx - x2) + (cy - y2) * (cy - y2) < r * r){\n\t\t\t\t\treturn 0;\n\t\t\t\t}else {\n\t\t\t\t\treturn rayCircle(cx, cy, dx, dy, x2, y2, r, 1);\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t} else {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n}",
"function PHSK_MagLineCalc() {\n\t//counter to avoid centerpiece\n\tlet l = 0;\n\tfor (let i = 0; i < 26; i++) {\n\t\t\t\n\t\tif(i == 13)\n\t\t\tl+=1;\n\t\t\n\t\tlet anchorPos = new Vec3 ( - 4.5 + (4.5 * (l%3)) , - 4.5 + (4.5 * (Math.floor(l/3)%3)) , - 4.5 + (4.5 * (Math.floor(l/9)%3)));\n\t\tl+=1;\n\t\t//if(i%2 ==1)\n\t\t//\tcontinue\n\n\t\tmaglines[i][magLineNumber/2] = anchorPos;\n\t\t\n\t\tfor (let j =(magLineNumber/2 -1); j >= 0; j--) {\n\t\t\tlet bfeld = new Vec3(0.0,0.0,0.0);\n\t\t\tlet bfeldSum= new Vec3(0.0,0.0,0.0);\n\t\t\tfor (let k = 1; k < wireLength; k++) {\n\t\t\t\tbfeld = PHSK_BFeld(GMTR_VectorsToLineSeg(wire[k - 1], wire[k]),maglines[i][j + 1]);\n\t\t\t\tbfeldSum = GMTR_VectorAddition(bfeldSum, bfeld);\n\t\t\t}\n\t\t\tmaglines[i][j] = GMTR_VectorAddition(maglines[i][j + 1], GMTR_ChangeSize(bfeldSum, magLineStep));\n\t\t}\n\t\tfor (let j = (magLineNumber/2 +1); j < magLineNumber; j++) {\n\t\t\tlet bfeld = new Vec3(0.0,0.0,0.0);\n\t\t\tlet bfeldSum= new Vec3(0.0,0.0,0.0);\n\t\t\tfor (let k = 1; k < wireLength; k++) {\n\t\t\t\tbfeld = PHSK_BFeld(GMTR_VectorsToLineSeg(wire[k - 1], wire[k]), maglines[i][j - 1]);\n\t\t\t\tbfeldSum = GMTR_VectorAddition(bfeldSum, bfeld);\n\t\t\t}\n\t\t\tmaglines[i][j] = GMTR_VectorAddition(maglines[i][j - 1], GMTR_ChangeSize(bfeldSum, -magLineStep));\n\t\t}\n\t}\n\t\t\n\treturn 0;\n}",
"function hamiltonianCycle() {\r\n\tvar current_x = x[0] / IMG_SIZE;\r\n\tvar current_y = y[0] / IMG_SIZE;\r\n\tvar head_x = x[0] / IMG_SIZE;\r\n\tvar head_y = y[0] / IMG_SIZE;\r\n\t//Head to top\r\n\twhile (current_y > 0) {\r\n\t\tcurrent_y--;\r\n\t\tpath.push(current_x + \",\" + current_y);\r\n\t}\r\n\t//Zig zag to the bottom (ending at bottom right corner)\r\n\twhile (current_y < MAX_BOUND) {\r\n\t\t//Go right on even y\r\n\t\tif (current_y % 2 == 0) {\r\n\t\t\twhile (current_x < MAX_BOUND) {\r\n\t\t\t\tcurrent_x++;\r\n\t\t\t\tpath.push(current_x + \",\" + current_y);\r\n\t\t\t}\r\n\t\t}\r\n\t\t//Go left on odd y\r\n\t\telse {\r\n\t\t\twhile (current_x > head_x + 1) {\r\n\t\t\t\tcurrent_x--;\r\n\t\t\t\tpath.push(current_x + \",\" + current_y);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcurrent_y++;\r\n\t\tpath.push(current_x + \",\" + current_y);\r\n\t}\r\n\t//To the left (bottom left corner)\r\n\twhile (current_x > 0) {\r\n\t\tcurrent_x--;\r\n\t\tpath.push(current_x + \",\" + current_y);\r\n\t}\r\n\t//To the top again (top left corner)\r\n\twhile (current_y > 0) {\r\n\t\tcurrent_y--;\r\n\t\tpath.push(current_x + \",\" + current_y);\r\n\t}\r\n\t//Zig zag down to second to last row\r\n\twhile (current_y < MAX_BOUND) {\r\n\t\t//Go right on odd y\r\n\t\tif (current_y % 2 == 1) {\r\n\t\t\twhile (current_x > 1) {\r\n\t\t\t\tcurrent_x--;\r\n\t\t\t\tpath.push(current_x + \",\" + current_y);\r\n\t\t\t}\r\n\t\t}\r\n\t\t//Go left on even y\r\n\t\telse {\r\n\t\t\twhile (current_x < head_x - 1) {\r\n\t\t\t\tcurrent_x++;\r\n\t\t\t\tpath.push(current_x + \",\" + current_y);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcurrent_y++;\r\n\t\tpath.push(current_x + \",\" + current_y);\r\n\t}\r\n\t//Undo the last move\r\n\tcurrent_y--;\r\n\tpath.pop();\r\n\t//Go right one\r\n\tcurrent_x++;\r\n\tpath.push(current_x + \",\" + current_y);\r\n\t//Back up to the start (cycle complete) \r\n\twhile (current_y > head_y) {\r\n\t\tcurrent_y--;\r\n\t\tpath.push(current_x + \",\" + current_y);\r\n\t}\r\n\t\r\n\ttimer = setInterval(hamiltonianMove, DELAY/4);\r\n}",
"function lineSegment(x, y, w, h) {\r\n fill(255, 234, 0);\r\n rect(x, y - 4, w, h);\r\n}",
"function ballHasLine(ball_id, ball_color)\n{\n\tvar line = false;\n\tvar line_len = 0;\t\n\tvar coords = getCoordsFromId(ball_id);\n\tvar elem_y = coords[0];\n\tvar elem_x = coords[1];\n\t\n\t//find lines\n\tvar line_n = doLine(elem_x, elem_y, 0, -1, ball_color, false); \n\tvar line_no = doLine(elem_x, elem_y, 1, -1, ball_color, false); \n\tvar line_o = doLine(elem_x, elem_y, 1, 0, ball_color, false); \n\tvar line_os = doLine(elem_x, elem_y, 1, 1, ball_color, false); \n\tvar line_s = doLine(elem_x, elem_y, 0, 1, ball_color, false); \n\tvar line_sw = doLine(elem_x, elem_y, -1, 1, ball_color, false);\n\tvar line_w = doLine(elem_x, elem_y, -1, 0, ball_color, false);\n\tvar line_nw = doLine(elem_x, elem_y, -1, -1, ball_color, false); \n\t\n\tvar line_hor = line_o + line_w;\n\t//console.log('hor: '+line_hor);\n\tvar line_ver = line_n + line_s;\n\t//console.log('ver: '+line_ver);\n\tvar line_slash = line_sw + line_no;\n\t//console.log('slash: '+line_slash);\n\tvar line_backslash = line_os + line_nw;\n\t//console.log('backslash: '+line_backslash);\n\t\t\n\t//delete lines\n\tif(line_hor >= line_len_min-1)\n\t{\n\t\t//alert(line_hor +' '+ line_len);\n\t line_len += line_hor;\n\t\tvar line_o = doLine(elem_x, elem_y, 1, 0, ball_color, true); \n\t\tvar line_w = doLine(elem_x, elem_y, -1, 0, ball_color, true);\n\t\tline = true;\n\t}\n\tif(line_ver >= line_len_min-1)\n\t{\n\t\t//alert(line_ver +' '+ line_len);\n\t line_len += line_ver;\n\t\tvar line_n = doLine(elem_x, elem_y, 0, -1, ball_color, true); \n\t\tvar line_s = doLine(elem_x, elem_y, 0, 1, ball_color, true);\n\t\tline = true;\n\t}\n\tif(line_slash >= line_len_min-1)\n\t{\n\t\t//alert(line_slash +' '+ line_len);\n\t line_len += line_slash;\n\t\tvar line_no = doLine(elem_x, elem_y, 1, -1, ball_color, true); \n\t\tvar line_sw = doLine(elem_x, elem_y, -1, 1, ball_color, true);\n\t\tline = true;\n\t}\n\tif(line_backslash >= line_len_min-1)\n\t{\n\t\t//alert(line_backslash +' '+ line_len);\n\t line_len += line_backslash;\n\t\tvar line_os = doLine(elem_x, elem_y, 1, 1, ball_color, true); \n\t\tvar line_wn = doLine(elem_x, elem_y, -1, -1, ball_color, true);\n\t\tline = true;\n\t}\n\t\n\tif(line)\n\t{\n\t\tremoveBallInLine(elem_x, elem_y);\n\t\t++line_len;\n\t}\n\t\n\t//console.log(line_len);\n\tupdateGui();\n\tdoBonusPoints(line_len);\n\treturn line;\n}",
"function hLine(i){\n var x1 = scaleUp(0);\n var x2 = scaleUp(boardSize - 1);\n var y = scaleUp(i); \n drawLine(x1, x2, y, y);\n //alert(\"i:\" + i+ \" x1:\"+x1+ \" x2:\"+x2+\" y1:\"+y+ \" y2:\"+y);\n }",
"function findDistances (img) {\n img.get = imgGet\n img.set = imgSet\n var view = new DataView(img.data.buffer)\n var nx = img.width\n var ny = img.height\n\n function distance (g, x, y, i) {\n return ((y - i) * (y - i) + g[i][x] * g[i][x])\n }\n\n function intersection (g, x, y0, y1) {\n return ((g[y0][x] * g[y0][x] - g[y1][x] * g[y1][x] + y0 * y0 - y1 * y1) / (2.0 * (y0 - y1)))\n }\n //\n // allocate arrays\n //\n var g = []\n for (var y = 0; y < ny; ++y) { g[y] = new Uint32Array(nx) }\n var h = []\n for (var y = 0; y < ny; ++y) { h[y] = new Uint32Array(nx) }\n var distances = []\n for (var y = 0; y < ny; ++y) { distances[y] = new Uint32Array(nx) }\n var starts = new Uint32Array(ny)\n var minimums = new Uint32Array(ny)\n //\n // column scan\n //\n for (var y = 0; y < ny; ++y) {\n //\n // right pass\n //\n var closest = -nx\n for (var x = 0; x < nx; ++x) {\n if (img.get(y, x, STATE) & INTERIOR) {\n g[y][x] = 0\n closest = x\n } else { g[y][x] = (x - closest) }\n }\n //\n // left pass\n //\n closest = 2 * nx\n for (var x = (nx - 1); x >= 0; --x) {\n if (img.get(y, x, STATE) & INTERIOR) { closest = x } else {\n var d = (closest - x)\n if (d < g[y][x]) { g[y][x] = d }\n }\n }\n }\n //\n // row scan\n //\n for (var x = 0; x < nx; ++x) {\n var segment = 0\n starts[0] = 0\n minimums[0] = 0\n //\n // down\n //\n for (var y = 1; y < ny; ++y) {\n while ((segment >= 0) &&\n (distance(g, x, starts[segment], minimums[segment]) > distance(g, x, starts[segment], y))) { segment -= 1 }\n if (segment < 0) {\n segment = 0\n minimums[0] = y\n } else {\n newstart = 1 + intersection(g, x, minimums[segment], y)\n if (newstart < ny) {\n segment += 1\n minimums[segment] = y\n starts[segment] = newstart\n }\n }\n }\n //\n // up\n //\n for (var y = (ny - 1); y >= 0; --y) {\n var d = Math.sqrt(distance(g, x, y, minimums[segment]))\n view.setUint32((img.height - 1 - y) * 4 * img.width + x * 4, d)\n if (y === starts[segment]) { segment -= 1 }\n }\n }\n}",
"function fillFromPoint(canvas, p1, rI, gI, bI){\n console.log(canvas);\n var frontier = [];\n var width = canvas.width;\n var height = canvas.height;\n var context = canvas.getContext('2d');\n var imgData = context.getImageData(0, 0, width, height);\n var pos = (p1.y * width + p1.x) * 4;\n\n frontier.push(p1);\n\n var r = imgData.data[pos];\n var g = imgData.data[pos + 1];\n var b = imgData.data[pos + 2];\n\n if (rI == r && g == gI && b == bI){\n return;\n }\n\n imgData.data[pos] = rI;\n imgData.data[pos + 1] = gI;\n imgData.data[pos + 2] = bI;\n\n while (frontier.length){\n var point, left, right;\n point = frontier.pop();\n\n pos = (point.y * width + point.x) * 4;\n\n for (var i=0; i < neigh.length; i++){\n\n var tPosX = point.x + neigh[i][0];\n var tPosY = point.y + neigh[i][1];\n\n if (tPosX >= 0 && tPosX < width && tPosY >= 0 && tPosY < height){\n var tPos = ((tPosY * width + tPosX) * 4);\n\n if (imgData.data[tPos] == r && imgData.data[tPos + 1] == g && imgData.data[tPos + 2] == b){\n imgData.data[pos] = rI;\n imgData.data[pos + 1] = gI;\n imgData.data[pos + 2] = bI;\n frontier.push(new Point(tPosX, tPosY));\n }\n }\n }\n }\n context.putImageData(imgData,0,0 );\n}",
"function calcWaypoints(vertices) {\n var waypoints = [];\n for (var i = 1; i < vertices.length; i+=2) {\n var pt0 = (vertices[i-1].x)*CANVAS_SIZE;\n var pt1 = (vertices[i].x)*CANVAS_SIZE;\n var dx = pt1 - pt0;\n var y0 = CANVAS_SIZE - (vertices[i-1].y)*CANVAS_SIZE; \n var y1 = CANVAS_SIZE - (vertices[i].y)*CANVAS_SIZE;\n var dy = y1 - y0;\n for (var j = 0; j < 100; j++) {\n var x = pt0 + dx * j / 100;\n var y = y0 + dy * j / 100;\n // var ver is later used to check if an object is hit at this vertex\n // as it can only be hit when j==99 (a top waypoint), set ver=-1 to indicate\n // that this waypoint is not a vertex\n var ver = {x: -1, y:-1}; \n if (j==99) {\n // since this waypoint is a vertex, set ver\n ver = {x: vertices[i].x, y: vertices[i].y}; \n } \n // \"ignore\" (aka do not draw) the last and first point to avoid drawing vertical lines\n // points with ignore=true use context.moveTo instead of context.lineTo\n var ignore = false; \n if (j==0 || j==99) {\n ignore = true;\n }\n\n waypoints.push({\n x: x, // the x coordinate on the graph\n y: y, // the y coordinate on the graph\n ignore: ignore, // if waypoint should NOT be drawn to \n hit: ver, // the specific vertex point, used to check if object is hit\n });\n }\n waypoints.push({x: pt1, y: 0, ignore: true, hit: {x: -1, y:-1}});\n } \n return (waypoints);\n }",
"function lineEquation(pt1, pt2) {\n if (pt1.x === pt2.x) {\n return pt1.y === pt2.y ? null : {\n x: pt1.x\n };\n }\n\n var a = (pt2.y - pt1.y) / (pt2.x - pt1.x);\n return {\n a: a,\n b: pt1.y - a * pt1.x,\n };\n }",
"function calculateYIntersection(line1, line2) {\n return (line1.m * line2.m * (line2.x - line1.x) + line1.y * line2.m - line2.y * line1.m) / (line2.m - line1.m);\n}",
"function onLine(line, point) {\n\tif(point.x <= Math.max(line.p1.x, line.p2.x) && point.x <= Math.min(line.p1.x, line.p2.x) &&\n\t\t(point.y <= Math.max(line.p1.y, line.p2.y) && point.y <= Math.min(line.p1.y, line.p2.y)))\n\t\treturn true;\n\treturn false;\n}",
"function vectorize2D (oldpath, error) {\n var path = []\n for (var seg = 0; seg < oldpath.length; ++seg) {\n var x0 = oldpath[seg][0][X]\n var y0 = oldpath[seg][0][Y]\n path[path.length] = [\n [x0, y0]\n ]\n var xsum = x0\n var ysum = y0\n var sum = 1\n for (var pt = 1; pt < oldpath[seg].length; ++pt) {\n var x = oldpath[seg][pt][X]\n var y = oldpath[seg][pt][Y]\n var xold = x\n var yold = y\n if (sum === 1) {\n xsum += x\n ysum += y\n sum += 1\n } else {\n var xmean = xsum / sum\n var ymean = ysum / sum\n var dx = xmean - x0\n var dy = ymean - y0\n var d = Math.sqrt(dx * dx + dy * dy)\n var nx = dy / d\n var ny = -dx / d\n var l = Math.abs(nx * (x - x0) + ny * (y - y0))\n if (l < error) {\n xsum += x\n ysum += y\n sum += 1\n } else {\n path[path.length - 1][path[path.length - 1].length] = [xold, yold]\n x0 = xold\n y0 = yold\n xsum = xold\n ysum = yold\n sum = 1\n }\n }\n if (pt === (oldpath[seg].length - 1)) {\n path[path.length - 1][path[path.length - 1].length] = [x, y]\n }\n }\n }\n return path\n}",
"function clipSutherland() { \r\n\r\n clip1x = x1;\r\n clip1y = y1;\r\n clip2x = x2;\r\n clip2y = y2;\r\n\r\n var x = 0;\r\n var y = 0;\r\n var m = (clip2y - clip1y) / (clip2x - clip1x);\r\n\r\n var code1 = getCode(clip1x, clip1y);\r\n var code2 = getCode(clip2x, clip2y);\r\n\r\n while (code1 != INSIDE || code2 != INSIDE) {\r\n\r\n var clipCode;\r\n\r\n if ((code1 & code2) != INSIDE) {\r\n return false;\r\n }\r\n if (code1 == INSIDE) {\r\n clipCode = code2;\r\n }\r\n else { \r\n clipCode = code1\r\n }\r\n if ((clipCode & LEFT) != INSIDE) {\r\n x = xMin;\r\n y = (x - clip1x) * m + clip1y;\r\n }\r\n else if ((clipCode & RIGHT) != INSIDE) {\r\n x = xMax;\r\n y = (x - clip1x) * m + clip1y;\r\n }\r\n else if ((clipCode & BOTTOM) != INSIDE) {\r\n y = yMin;\r\n x = (y - clip1y) / m + clip1x;\r\n }\r\n else if ((clipCode & TOP) != INSIDE) {\r\n y = yMax;\r\n x = (y - clip1y) / m + clip1x;\r\n }\r\n if (clipCode == code1) {\r\n clip1x = x;\r\n clip1y = y;\r\n code1 = getCode(clip1x, clip1y);\r\n }\r\n else {\r\n clip2x = x;\r\n clip2y = y;\r\n code2 = getCode(clip2x, clip2y);\r\n }\r\n }\r\n return true;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create "dialog" window with iFrame | function popupDialogWindow(pageTitle, pageURL) {
//var $dialog = $("#" + containerId)
var $dialog = $("#custom-iframe-container")
.html("<iframe src='" + pageURL + "'></iframe>")
.dialog({
appendTo: "body",
autoOpen: false,
modal: true,
height: 700,
width: 900,
title: pageTitle,
// closeOnEscape: false,
dialogClass: "custom-dialog",
draggable: true,
maxHeight: 700,
maxWidth: 900,
resizable: true,
open: function( event, ui ) {
//$("head").append("<base target='_top'>");
}
});
$dialog.dialog('open');
} | [
"function Dialog() {}",
"function ShowFacebookDialogue(){\n\t//setup dialogues\n\tvar dialogue = $(\"#dialogue\").dialog({autoOpen: false, modal: true, draggable:false, resizable:false, bgiframe:true});\n\n\t//setup options for this dialogue\n\t$(\"#dialogue\").dialog( \"option\", \"title\", 'Facebook - Adding Entry' );\n\t$(\"#dialogue\").dialog({ buttons: { \"Close\": function() { $(this).dialog(\"close\"); } } });\n\t$(\"#dialogue\").dialog( \"open\" );\n\t$(\"#dialogue\").html(\"<p>An example of a JQuery UI dialogue emulating Facebook's styles!</p>\");\n\t$(\"#dialogue\").bind( \"dialogbeforeclose\", function(event, ui) {\n\t\talert(\"You can bind events as you normally would to JQuery UI dialogues.\");\n\t});\n}",
"function OpenDialog(url, name, type)\n{\n\tWindowDef_1 = \"height=530, width= 530px, top=50, left=0\";\n\tWindowDef_2 = \"height=580, width= 850px, top=0, left=0\";\n\tWindowDef_3 = \"height=450, width= 300px, top=50, left=540\";\n\tWindowDef_4 = \"height=450, width= 550px, top=50, left=200\";\n\tWindowDef_5 = \"height=600, width= 800px, top=0, left=100\";\t\t\n\tvar WindowDef = eval(\"WindowDef_\" + type);\n\tvar attribs = \"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars,resizable,\" + WindowDef;\n\tvar DialogWindow = window.open(url,name,attribs);\n\treturn DialogWindow;\n}",
"newWorkspaceDialog() {\n\t\tlet Dialog_SelectWorkspace = require(path.join(__rootdir, \"js\", \"dialogs\", \"selworkspace.js\"))\n\t\tnew Dialog_SelectWorkspace(600, \"\", (result) => {\n\t\t\tif(result === false)\n\t\t\t\treturn\n\t\t\t\n\t\t\tlet ws = wmaster.addWorkspace(result)\n\t\t\tthis.setWorkspace(ws)\n\t\t\t\n\t\t\t// display loading indicator\n\t\t\tthis.body.innerHTML = `<div class=\"abs-fill flex-col\" style=\"justify-content: center\"><div style=\"align-self: center\">...</dib></div>`\n\t\t})\n\t}",
"function aePopupModalWindow(aParentWindow, aUri, aWinName, aWidth, aHeight, aResizable, aParams)\r\n{\r\n\treturn aePopupWindow(aParentWindow, aUri, aWinName, aWidth, aHeight, aResizable, true, aParams);\r\n}",
"function ShareDialog(parentSelector, interactiveContainerSelector, i18n, interactive) {\n var hash = share_dialog_location.hash,\n originMatch = share_dialog_location.href.match(/(.*?\\/\\/.*?)\\//),\n // Origin might not be available when Lab is running in iframe using srcdoc attr.\n origin = originMatch && originMatch[1],\n embeddablePath = share_dialog_location.pathname;\n basic_dialog.call(this, {\n dialogClass: \"share-dialog\",\n appendTo: parentSelector\n }, i18n);\n /** @private */\n\n this._view = {\n paste_html: i18n.t(\"share_dialog.paste_html\"),\n select_size: i18n.t(\"share_dialog.select_size\"),\n size_larger: i18n.t(\"share_dialog.size_larger\", {\n val: 50\n }),\n size_actual: i18n.t(\"share_dialog.size_actual\"),\n size_smaller: i18n.t(\"share_dialog.size_smaller\", {\n val: 30\n }),\n copyright: getCopyright(i18n)\n };\n this._i18n = i18n;\n\n if (lab_config[\"a\" /* default */].homeForSharing) {\n this._view.embeddableSharingUrl = lab_config[\"a\" /* default */].homeForSharing + lab_config[\"a\" /* default */].homeEmbeddablePath + hash;\n } else if (origin) {\n this._view.embeddableSharingUrl = origin + embeddablePath + hash;\n } else {\n // In this case sharing should be disabled. But if it's not, just provide anything.\n this._view.embeddableSharingUrl = \"\";\n }\n\n var link = \"<a class='opens-in-new-window' href='\" + this._view.embeddableSharingUrl + \"' target='_blank'>\" + i18n.t(\"share_dialog.link\") + \"</a>\";\n this._view.paste_email_im = i18n.t(\"share_dialog.paste_email_im\", {\n link: link\n });\n this.setContent(mustache_default.a.render(share_dialog, this._view));\n /** @private */\n\n this._$interactiveContainer = $(interactiveContainerSelector);\n /** @private */\n\n this._$iframeSize = this.$element.find(\"#iframe-size\");\n /** @private */\n\n this._$iframeContent = this.$element.find(\"#share-iframe-content\");\n\n this._$iframeSize.on('change', $.proxy(this.updateIframeSize, this));\n\n this.updateIframeSize();\n\n if (interactive) {\n this.update(interactive);\n }\n}",
"function createContentEditDialog(){\n var assetEditor = $.PercCreateNewAssetDialogData.assetEditor;\n //Create a dialog html with iframe, set the src to the content edit criteria url\n var url = assetEditor.url +\n \"&sys_folderid=\" + assetEditor.legacyFolderId +\n \"&sys_workflowid=\" + assetEditor.workflowId;\n \n var dlgHtml = \"<div id='create-new-asset-content-dlg'>\" +\n \"<iframe name='create-new-asset-content-frame' id='create-new-asset-content-frame'\" +\n \"height='100%' FRAMEBORDER='0' width='100%' src='\" + url +\n \"'></iframe>\" +\n \"</div>\";\n //Create dialog and set the preferred height and width from the criteria\n dialog = $(dlgHtml).perc_dialog({\n title: \"Edit Widget Content\",\n resizable: true,\n modal: true,\n height: 815,\n width: 965,\n percButtons: {\n \"Save\": {\n click: function(){\n saveAssetContent(successCallback);\n },\n id: \"perc-create-new-asset-save-button\"\n },\n \"Cancel\": {\n click: function(){\n dialog.remove();\n $.PercCreateNewAssetDialogData.cancelCallback();\n },\n id: \"perc-create-new-asset-cancel-button\"\n }\n },\n id: 'perc-create-new-asset-dialog'\n });\n }",
"function appendPopupIFrame(p, src, title){\r\n\t\tpopupIframe = document.createElement(\"IFRAME\");\r\n\t\tpopupIframe.setAttribute(\"src\", src);\r\n\t\tpopupIframe.setAttribute(\"title\", title);\r\n\t\tpopupIframe.setAttribute(\"id\", \"popup-iframe-id\");\r\n\t\tpopupIframe.setAttribute(\"scrolling\", \"no\");\r\n\t\tpopupIframe.setAttribute(\"marginheight\", \"0\");\r\n\t\tpopupIframe.setAttribute(\"marginwidth\", \"0\");\r\n\t\tpopupIframe.setAttribute(\"class\", \"popup-iframe-class\");\r\n\t\tpopupIframe.style.width = \"100%\"; //Always consume full width of container\r\n\t\tpopupIframe.style.height = \"100%\"; //When gauth renders in iframe it will message its height back to the client\r\n\t\tpopupIframe.style.border = \"none\";\r\n\t\tpopupIframe.frameBorder = \"0\"; //for IE\r\n\t\tp.appendChild(popupIframe);\r\n\t}",
"function openChildWindow(){\n setErrorFlag();\n var lstrWidth = '750px';//set default width\n var lstrHeight = '450px';//set default height\n var lstrURL;\n var lstrArgument;\n\n lstrURL = openChildWindow.arguments[0];\n if( lstrURL.indexOf(\"?\") == -1 ) {\n lstrURL = lstrURL + \"?childFw=Y\" ;\n } else {\n lstrURL = lstrURL + \"&childFw=Y\" ;\n }\n lstrURL = encodeURI(lstrURL);\n lstrArgument = openChildWindow.arguments[1];\n\n //set the width\n if(openChildWindow.arguments[2] != null && openChildWindow.arguments[2].length > 0 ){\n lstrWidth= openChildWindow.arguments[2];\n }\n\n //set the height\n if(openChildWindow.arguments[3] != null && openChildWindow.arguments[3].length > 0 ){\n lstrHeight= openChildWindow.arguments[3];\n }\n\n // for appending the readonly flag of Parent Screen\n if(document.getElementById('readOnlyFlg') != null && document.getElementById('readOnlyFlg')!= undefined){\n if(lstrURL.indexOf('?') != -1 ){\n lstrURL = lstrURL+ '&childScreen=true&readOnlyFlg='+document.getElementById('readOnlyFlg').value;\n }else{\n lstrURL = lstrURL+ '?childScreen=true&readOnlyFlg='+document.getElementById('readOnlyFlg').value;\n }\n }\n\n //open model dialog\n window.showModalDialog(lstrURL,lstrArgument, 'dialogHeight:' + lstrHeight + ';dialogWidth:' + lstrWidth + ';center:yes;status:no');\n // Set Error Flag to true so that Buttons are not disabled of parent\n isErrFlg = true;\n}",
"function wrapDialog(target){ \n\t\tvar t = $(target); \n\t\tt.wrapInner('<div class=\"dialog-content\"></div>'); \n\t\tvar contentPanel = t.find('>div.dialog-content'); \n\t\t \n\t\tcontentPanel.css('padding', t.css('padding')); \n\t\tt.css('padding', 0); \n\t\t \n\t\tcontentPanel.panel({ \n\t\t\tborder:false \n\t\t}); \n\t\t \n\t\treturn contentPanel; \n\t}",
"function openPreview(name, url){\n console.log(name, url);\n var modal = '<div class=\"modal fade\" id=\"bookPreview\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"bookPreviewLabel\" aria-hidden=\"true\">' +\n '<div class=\"modal-dialog\" role=\"document\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\" id=\"bookPreviewLabel\">'+ name +'</h5>' +\n '<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">' +\n '<span aria-hidden=\"true\">×</span>' +\n '</button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<iframe src=\"'+ url +'&output=embed\" frameborder=\"0\">' +\n '</iframe>' +\n '</div>' +\n '</div>' +\n '</div>' +\n '</div>';\n $('body').prepend(modal);\n $('#bookPreview').modal('show');\n $('#bookPreview').on('hidden.bs.modal', function(e){\n $('#bookPreview').remove();\n });\n}",
"function PopUp(url, name, width,height,center,resize,scroll,posleft,postop)\r\n{\r\n\tshowx = \"\";\r\n\tshowy = \"\";\r\n\t\r\n\tif (posleft != 0) { X = posleft }\r\n\tif (postop != 0) { Y = postop }\r\n\t\r\n\tif (!scroll) { scroll = 1 }\r\n\tif (!resize) { resize = 1 }\r\n\t\r\n\tif ((parseInt (navigator.appVersion) >= 4 ) && (center))\r\n\t{\r\n\t\tX = (screen.width - width ) / 2;\r\n\t\tY = (screen.height - height) / 2;\r\n\t}\r\n\t\r\n\tif ( X > 0 )\r\n\t{\r\n\t\tshowx = ',left='+X;\r\n\t}\r\n\t\r\n\tif ( Y > 0 )\r\n\t{\r\n\t\tshowy = ',top='+Y;\r\n\t}\r\n\t\r\n\tif (scroll != 0) { scroll = 1 }\r\n\t\r\n\tself.name=\"ori_window\";\r\n\tvar Win = window.open( url, name, 'width='+width+',height='+height+ showx + showy + ',resizable='+resize+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no');\r\n\tWin.focus();\r\n\tWin.document.close;\r\n\r\n}",
"function showDialog(){\n debug('Action');\n\n master.show(new Array({name: \"Child\", data:childrenList},\n {name: \"Action\", data:actions},\n {name: 'Shape', data:iceCreamShapes},\n {name: 'Taste', data:iceCreamTastes})\n , onComplete);\n\n document.getElementById('content').style.display = 'none';\n master._container.style.display = 'block';\n}",
"function dialogo(titulo, div, ancho, alto, url, parametros,faceptar,fverif_aceptar,fcancelar,fverif_cancelar,mensaje_aceptar,mensaje_cancelar){\n $(\"#\"+div).dialog({ // <!-- ------> muestra la ventana -->\n widthmin:ancho, width: ancho, widthmax:ancho, \n heightmin: alto,height: alto, heightmax: alto, \n show: \"scale\", // <!-- -----------> animación de la ventana al aparecer -->\n hide: \"scale\", // <!-- -----------> animación al cerrar la ventana -->\n resizable: \"false\", // <!-- ------> fija o redimensionable si ponemos este valor a \"true\" -->\n position: \"center\", // <!-- ------> posicion de la ventana en la pantalla (left, top, right...) -->\n modal: \"true\", // <!-- ------------> si esta en true bloquea el contenido de la web mientras la ventana esta activa (muy elegante) -->\n title: titulo,\n position: { \n my: \"center\", \n at: \"center\", \n of: window \n }, \n buttons: {\n //----------------------------------\n // ------ BOTON de ACEPTACION -----\n //----------------------------------\n \"Aceptar\": function() { \n var res_pregunta_aceptar = false;\n var respuesta_pregunta = false;\n \n if (!mensaje_aceptar){\n respuesta_pregunta = true; \n }else{\n if(confirm(mensaje_aceptar)){\n respuesta_pregunta = true;\n } \n }\n if (respuesta_pregunta){\n if(!fverif_aceptar){ // Si se ingreso la funcion a evaluar antes de faceptar\n if(!faceptar){// determinamos si hay funcion a ejecutar \n $( \"#\"+div ).dialog( \"close\" );\n return -1 \n }else{\n // Evaluamos la funcion ACEPTAR\n var aux1 = eval(faceptar);\n if(aux1){\n return aux1;\n $( \"#\"+div ).dialog( \"close\" ); \n }else{\n return -3 \n }\n }\n }else{\n var aux = eval(fverif_aceptar); // evaluamos la funcion de verificacion\n if(!aux){// si no paso las condiciones\n return -2;\n //$( \"#\"+div ).dialog( \"close\" );\n }else{ // Si paso la condicion\n if(!faceptar){// determinamos si hay funcion a ejecutar \n return aux; \n $( \"#\"+div ).dialog( \"close\" ); \n }else{\n var aux1 = eval(faceptar);\n if(aux1){\n return aux1;\n $( \"#\"+div ).dialog( \"close\" ); \n }else{\n return -4; \n }\n }\n } \n } \n }\n },\n //----------------------------------\n // ------ BOTON de CANCELAR -----\n //---------------------------------- \n \"Cancelar\": function() { \n var respuesta_pregunta = false;\n if (!mensaje_cancelar){\n respuesta_pregunta = true; \n }else{\n if(confirm(mensaje_cancelar)){\n respuesta_pregunta = true;\n } \n }\n if (respuesta_pregunta){\n if(!fverif_cancelar){ // Si se ingreso la funcion a evaluar antes de fcancelar\n if(!fcancelar){// determinamos si hay funcion a ejecutar \n $( \"#\"+div ).dialog( \"close\" );\n return -1 \n }else{\n // Evaluamos la funcion ACEPTAR\n var aux1 = eval(faceptar);\n if(aux1){\n $( \"#\"+div ).dialog( \"close\" ); \n return aux1; \n }else{\n return -3 \n }\n }\n }else{\n var aux = eval(fverif_cancelar); // evaluamos la funcion de verificacion\n if(!aux){// si no paso las condiciones\n return -2;\n //$( \"#\"+div ).dialog( \"close\" );\n }else{ // Si paso la condicion\n if(!fcancelar){// determinamos si hay funcion a ejecutar \n $( \"#\"+div ).dialog( \"close\" ); \n return aux \n }else{\n var aux1 = eval(faceptar);\n if(aux1){\n $( \"#\"+div ).dialog( \"close\" ); \n return aux1;\n }else{\n return -4 \n }\n }\n } \n } \n }\n }\n }\n });\n if(url!=\"\"){\n $(\"#\"+div).load(url,parametros, \n function(response, status, xhr) { \n switch (status) {\n case 'error':{ \n var msg = \"Error!, algo ha sucedido: \";\n $(\"#\"+div).html(msg + xhr.status + \" \" + xhr.statusText);\n break;}\n case 'success': {break;}\n case 'notmodified':{break;}\n case 'timeout': {break;}\n case 'parsererror':{break;}\n }\n }\n ); \n }\n\n}",
"showDialog(selectedObject) {\n\n\t\t// Create dialog\n\t\tvar window = this.createDialog(selectedObject)\n\t\tvar alert = window[0]\n\n\t\t// Show dialog window and store the 'response' in a variable\n\t\tvar response = alert.runModal()\n\n\t\t// Get user input and store it in selected object\n\t\tthis.storeDialogInput(response, selectedObject)\n\t}",
"function loadPopupInDialogBox(popupUrl, popupTitle){\r\n\r\n\t\tpopup_Div = document.getElementById(\"gauth-light-box\");\r\n\t \r\n\t\tpopup_Div.innerHTML = \"<a class='button' id='liteBoxClose' href='#' onclick='hideLightBox();return false;'><span>X</span></a>\";\r\n\t\t\r\n\t\tvar popup_source;\r\n\t\tvar host = getGAuthHost();\r\n\t\t\r\n\t\tpopup_source = host + popupUrl;\r\n\t \r\n consoleInfo(\"gauth-widget.js LoadPopupInDialogBox(): popup_source: \" + popup_source);\r\n\r\n\t if (document.getElementById('popup-iframe-id')){\r\n\t \tpurge(document.getElementById('popup-iframe-id'));\r\n\t \tpopup_Div.removeChild(document.getElementById('popup-iframe-id'));\r\n\t\t}\r\n\t\r\n\t //append iframe\r\n\t appendPopupIFrame(popup_Div, popup_source, popupTitle);\r\n\t}",
"function newRobotWindow() {\n\tvar robotWindow = window.open(\"Images/robot.png\", \"robotWindow\", \"resizable=no,width=400,height=300\");\n\treturn false;\n}",
"initDialog() {\n this.view = new InviteDialogView(this);\n }",
"function createFrameUi(frameStyle, text, sequenceNo, data) {\n var $frame = $(\"<span></span>\");\n $frame.addClass(\"frame\");\n $frame.addClass(frameStyle);\n $frame.text(text);\n $frame.attr(\"id\", sequenceNo);\n $frame.attr(\"name\", data);\n return $frame;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the actual extension ID given the extension name | function getExtensionID(name){
for(i=0; i < background.extensionsList.length; i++){
if(background.extensionsList[i]['name'] == name){
return background.extensionsList[i]['id'];
}
}
} | [
"function extension(type) {\n const match = EXTRACT_TYPE_REGEXP.exec(type);\n if (!match) {\n return;\n }\n const exts = exports.extensions.get(match[1].toLowerCase());\n if (!exts || !exts.length) {\n return;\n }\n return exts[0];\n }",
"function extension(filename, mimeType) {\n let ext = '';\n if (filename) {\n ext = path.extname(filename);\n }\n if (!ext && mimeType) {\n const mimeExt = mime.extension(mimeType);\n ext = mimeExt ? `.${mimeExt}` : '';\n }\n return ext;\n}",
"function getExtension(fileBlob) {\r\n\r\n // string separated by <file description>/<extension>\r\n var contentType = fileBlob.getContentType()\r\n var parsed_content = contentType.split(\"/\")\r\n var extension = parsed_content[1]\r\n \r\n return extension\r\n}",
"function getExt(filename) {\n if (!filename) return \"\";\n var parts = filename.split(\".\");\n if (parts.length === 1 || (parts[0] === \"\" && parts.length === 2)) return \"\";\n return parts.pop().toLowerCase();\n }",
"function GetImageExtension(image) {\n var partsOfImageName = image.name.split(\".\");\n var extension = (partsOfImageName.length > 1) ? partsOfImageName[partsOfImageName.length - 1] : \"jpg\";\n return extension;\n}",
"function GetChannelId( a_raw_channel_name )\n{\n\t// TODO: handle special characters etc\n\t// basically need to convert to a symbol that has \n\t// no spaces and no special characters\n\treturn a_raw_channel_name.substring(1);\n}",
"function getExtScript() {\n // process.argv is always like [0:node, 1:script, 2:...args]\n const args = process.argv.slice(2);\n if (!args[0]) {\n throw new Error('Please specify the script that runs with theiaext command.');\n }\n const scripts = extScriptsPck['theia-monorepo-scripts'];\n const script = 'ext:' + args[0];\n if (!(script in scripts)) {\n throw new Error('The ext script does not exist: ' + script);\n }\n return [scripts[script], ...args.slice(1, args.length)].join(' ');\n}",
"function has_extension(e) {\n\t//if(process.env.DEBUG_MVC) {\n\t//\tdebug.log('has_extension(', e, ')');\n\t//}\n\tdebug.assert(e).is('string');\n\treturn function has_extension_2(p) {\n\t\treturn PATH.extname(p) === e;\n\t};\n}",
"getDocNameNoExtension(docName) {\n let fileName;\n let documentArray = docName !== '' ? docName.split('.') : [];\n\n if(documentArray.length <= 0)\n return ''\n\n if(documentArray.length > 2)\n {\n let fileNameArray = documentArray[2].split('/');\n fileName = fileNameArray[fileNameArray.length - 1];\n } \n else\n fileName = docName;\n \n return fileName;\n\n }",
"function idOf(word) {\n return \".word_\" + word;\n}",
"function getFileNameWithoutExtension(fileName)\r{\r var pattern = /(.+)\\.indd/;\r var matchArray = pattern.exec(fileName);\r if (matchArray != null && matchArray.length > 1) {\r return matchArray[1];\r } else {\r return fileName;\r }\r}",
"function regToId(regname){\r\n switch(regname.toLowerCase()){\r\n case 'al':\r\n case 'ax':\r\n case 'es':\r\n return 0;\r\n break;\r\n case 'cl':\r\n case 'cx':\r\n case 'cs':\r\n return 1;\r\n break;\r\n case 'dl':\r\n case 'dx':\r\n case 'ss':\r\n \r\n return 2;\r\n break;\r\n case 'bl':\r\n case 'bx':\r\n case 'ds':\r\n return 3;\r\n break;\r\n case 'sp':\r\n case 'ah':\r\n return 4;\r\n break;\r\n case 'bp':\r\n case 'ch':\r\n return 5;\r\n break;\r\n case 'si':\r\n case 'dh':\r\n return 6;\r\n break;\r\n case 'di':\r\n case 'bh':\r\n return 7;\r\n break;\r\n }\r\n}",
"function has_sub_extension(e) {\n\t//if(process.env.DEBUG_MVC) {\n\t//\tdebug.log('has_sub_extension(', e, ')');\n\t//}\n\tdebug.assert(e).is('string');\n\treturn function has_sub_extension_2(p) {\n\t\tvar name = PATH.basename(p, PATH.extname(p));\n\t\treturn PATH.extname(name) === e;\n\t};\n}",
"function getIcFilename(ext, color, size) {\n let filename = `ic_${iconArg.trim().replace(' ', '_')}`;\n if (color)\n filename += `_${color}`;\n if (size) \n filename += `_${size}dp`;\n if (ext)\n filename += `.${ext}`;\n\n return filename;\n}",
"function getMatchIdFromUrl(url)\n{\n const URL_OBJ = new URL(url);\n return URL_OBJ.pathname.split('/')[2];\n}",
"function getAttachmentId(link){\n \n var replacedStr = link.replace(\"https://drive.google.com/open?id=\",\"\");\n return replacedStr;\n}",
"function hyperDbKeyToId (key) {\n var components = key.split('/')\n return components[components.length - 1]\n}",
"folder_name(x){\n\t\tlet extension = path.extname(x)\n\t\tlet folder_name = path.basename(x)\n\t\tif(extension.length) folder_name = path.basename(x.replace(folder_name,''))\n\t\treturn folder_name\n\t}",
"findUniqueIdentifier() {\n const metadataId = this.attributes[\"unique-identifier\"];\n if (metadataId) {\n const uidMetadata = this.metadata.findItemWithId(\n \"dc:identifier\",\n metadataId\n );\n if (uidMetadata) {\n return uidMetadata.value;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper function to get the internal path of a node | function getInternalPath (node) {
return node.getInternalPath();
} | [
"function get_path(parent_node) {\n if (parent_node === current_room) {\n //return path\n } else {\n var parent = bfs_parents[parent_node.getName()];\n path.push(parent);\n return get_path(parent);\n }\n }",
"function _pathToNode(node, ancestorNode) {\n\t\t// \n\t\tvar arr = [];\n\t\t// \n\t\twhile (node != ancestorNode) {\n\t\t\tarr.push(_nodeIndex(node));\n\t\t\tnode = node.parentNode;\n\t\t}\n\t\t// \n\t\treturn arr.reverse();\n\t}",
"function getPath() {\n //this gets the full url\n var url = document.location.href, path;\n // first strip \n path = url.substr(url.indexOf('//') + 2, url.length - 1);\n path = path.substr(path.indexOf('/'), path.lastIndexOf('/') - path.indexOf('/') + 1);\n //return\n return path;\n }",
"function getPathToNode(nodename, edges) {\n // calculate path to the given node\n let runner = nodename;\n let pathSegments = [];\n while (runner !== 'root') {\n pathSegments.unshift(runner);\n runner = edges[runner];\n }\n pathSegments.unshift('');\n return pathSegments.join('/');\n}",
"function anno_getXpathTo(element) {\n if (element.id !== '') {\n return \"//*[@id='\" + element.id + \"']\";\n }\n if (element === document.body) {\n return \"html/\" + element.tagName.toLowerCase();\n } //added 'html/' to generate a valid Xpath even if parent has no ID.\n var ix = 0;\n var siblings = element.parentNode.childNodes;\n for (var i = 0; i < siblings.length; i++) {\n var sibling = siblings[i];\n if (sibling === element) {\n return anno_getXpathTo(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';\n }\n if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {\n ix++;\n }\n }\n}",
"function relatizePath(path) {\r\n\t\tif ('string' !== typeof path && 'function' === typeof path.getAttribute)\r\n\t\t\tpath = path.getAttribute('d');\r\n\t\treturn Raphael.pathToRelative(path).flatten().join(' ');\r\n\t}",
"get nextPath() { return this.next && this.next.path }",
"get pathPart() {\n return this.getStringAttribute('path_part');\n }",
"function backtrackPath(last_node){\n var path = [];\n var temp = last_node;\n path.push(temp);\n\n while(temp.previous){\n path.push(temp.previous);\n temp = temp.previous;\n }\n\n return path;\n}",
"getPath() {\n return this.$data[ENTITY_PATH];\n }",
"function getLastPath() {\n if (url.path.components.length > 0) {\n return url.path.components[url.path.components.length - 1];\n }\n }",
"function fullpath(d, idx) {\r\n idx = idx || 0;\r\n curPath.push(d);\r\n return (\r\n d.parent ? fullpath(d.parent, curPath.length) : '') +\r\n '/<span class=\"nodepath'+(d.data.name === root.data.name ? ' highlight' : '')+\r\n '\" data-sel=\"'+ idx +'\" title=\"Set Root to '+ d.data.name +'\">' +\r\n d.name + '</span>';\r\n }",
"function getPortal() {\n\tvar path = window.location.pathname;\n\tvar pos = path.indexOf('/', 1);\n\tif (pos > 0) {\n\t\tpath = path.substring(1, pos);\n\t}\n\treturn path;\n}",
"function getLocationFromBreadcrumb(){\n\tvar breadcrumb = document.getElementById(\"breadcrumb\");\n\tvar breadcrumbA = breadcrumb.getElementsByTagName(\"a\");\n\tvar location = breadcrumbA[breadcrumbA.length-1].innerHTML;\n\treturn location;\n}",
"function _nodeFromPath(path, ancestorNode) {\n\t\t// \n\t\tvar pathLen = path.length,\n\t\t\tindex = -1,\n\t\t\tnode;\n\t\t// \n\t\twhile (++index < pathLen) ancestorNode = ancestorNode.childNodes[path[index]];\n\t\t// Return the ancestor node\n\t\treturn ancestorNode;\n\t}",
"get parent() {\n return new Path(this.parentPath);\n }",
"next(path) {\n if (path.length === 0) {\n throw new Error(\"Cannot get the next path of a root path [\".concat(path, \"], because it has no next index.\"));\n }\n\n var last = path[path.length - 1];\n return path.slice(0, -1).concat(last + 1);\n }",
"function ipPath(fromNet , toNet){\n var ret = [];\n if (!SPTree)\n updateSPTree();\n if (!SPTree[fromNet][toNet]){\n showTitle(\"No path available from \"+fromNet+\" to \" +toNet);\n return ret;\n }\n // We do a backward path, from destination do source\n var e2e = SPTree[fromNet][toNet];\n var next = toNet;\n for (var step=0; step<e2e.distance; step++){\n var target = SPTree[fromNet][next].predecessor,\n gwIP;\n if (next != fromNet){\n if (isLeaf(next)){\n // If it is a leaf we directly use the IP (it should be a /32)\n var sp = getNetworkSubnet((getNetworkID(next))).split(\"/\");\n ret.push(sp[0]);\n }\n else{\n gwIP = gatewayIpOnNet(netGraph.edge(next , target) , next);\n if (gwIP){\n ret.push(network.extractIp(gwIP));\n }\n }\n\n }\n next = SPTree[fromNet][next].predecessor;\n }\n return ret;\n}",
"function relativeLocationPath(lhs, stream, a, isOnlyRootOk) {\n if (null == lhs) {\n lhs = step(stream, a);\n if (null == lhs) return lhs;\n }\n var op;\n while (op = stream.trypop(['/', '//'])) {\n if ('//' === op) {\n lhs = a.node('/', lhs, a.node('Axis', 'descendant-or-self', 'node', undefined));\n }\n var rhs = step(stream, a);\n if (null == rhs && '/' === op && isOnlyRootOk) return lhs;else isOnlyRootOk = false;\n if (null == rhs) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected step after ' + op);\n lhs = a.node('/', lhs, rhs);\n }\n return lhs;\n }",
"function getRootPathname() {\n let pathname,\n pathRoot,\n indEnd\n\n pathname = window.location.pathname;\n\n if (pathname === '/') {\n pathRoot = pathname;\n } else {\n indEnd = pathname.indexOf('/', 1);\n pathRoot = pathname.slice(0, indEnd);\n }\n return pathRoot;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a byte to a signed number (e.g., 0xff to 1). | function signedByte(value) {
return value >= 128 ? value - 256 : value;
} | [
"function parseToSignedByte(value) {\n value = (value & 127) - (value & 128);\n return value;\n}",
"function UInt8toUInt32(value) {\n return (new DataView(value.buffer)).getUint32();\n}",
"function decode_int(v) {\n return bigEndianToInt(v);\n }",
"function toByte(x) {\n x = Math.max(0, Math.min(1, x));\n\n return Math.floor(x === 1 ? 255 : x * 256);\n}",
"function encode_int(v) {\n if (!(v instanceof BigInteger) ||\n v.compareTo(BigInteger.ZERO) < 0 ||\n v.compareTo(LARGEST_NUM_PLUS_ONE) >= 0) {\n throw new Error(\"BigInteger invalid or out of range\");\n }\n return intToBigEndian(v);\n }",
"function BIN2DEC(value) {\n var valueAsString;\n\n if (typeof value === \"string\") {\n valueAsString = value;\n } else if (typeof value !== \"undefined\") {\n valueAsString = value.toString();\n } else {\n return error$2.NA;\n }\n\n if (valueAsString.length > 10) return error$2.NUM;\n\n // we subtract 512 when the leading number is 0.\n if (valueAsString.length === 10 && valueAsString[0] === '1') {\n return parseInt(valueAsString.substring(1), 2) - 512;\n }\n\n // Convert binary number to decimal with built-in facility\n return parseInt(valueAsString, 2);\n}",
"function INT(x) { return Math.floor(x) }",
"function bits128ToNum(a, offset, cls) {\n return cls.fromBits(byteswap(a.slice(offset, offset + 4)).reverse());\n }",
"static int8(v) { return n(v, -8); }",
"function toAInt(v) {\n\tif (!(v instanceof AInt))\n\t\treturn new AInt(v);\n\treturn v;\n}",
"function clampToInt16(x) {\n return Math.max(Math.min(x, 32767), -32768);\n}",
"function scaleNum(num, pos) {\n var scaled = (num << (8 * pos)) >>> 0;\n return scaled;\n }",
"function byteArrayToLong(byteArray) {\n var value = 0;\n for (var i = byteArray.length - 1; i >= 0; i--){\n value = (value * 256) + byteArray[i];\n }\n return value;\n}",
"function getByteN(value, n) {\n return ((value >> (8 * n)) & 0b11111111);\n}",
"static int256(v) { return n(v, -256); }",
"function limitOctetNumber(value) {\r\n\r\n if (value > 255) {\r\n\r\n return Math.floor(value / 10);\r\n } else {\r\n return value;\r\n }\r\n}",
"function toHex(byte) {\n\treturn ('0' + (byte & 0xFF).toString(16)).slice(-2);\n}",
"static int128(v) { return n(v, -128); }",
"function bufferToBigInt(buf) {\n return BigInt('0x' + bufferToHex(buf))\n}",
"function ToIntegerOrInfinity(argument) { // eslint-disable-line no-unused-vars\n\t// 1. Let number be ? ToNumber(argument).\n\tvar number = ToNumber(argument);\n\t// 2. If number is NaN, +0𝔽, or -0𝔽, return 0.\n\tif (isNaN(number) || number === 0 || 1/number === -Infinity) return 0;\n\t// 3. If number is +∞𝔽, return +∞.\n\tif (number === Infinity) return Infinity;\n\t// 4. If number is -∞𝔽, return -∞.\n\tif (number === -Infinity) return -Infinity;\n\t// 5. Let integer be floor(abs(ℝ(number))).\n\tvar integer = Math.floor(Math.abs(number));\n\t// 6. If number < +0𝔽, set integer to -integer.\n\tif (number < 0) integer = -integer;\n\t// 7. Return integer.\n\treturn integer;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
console.log(JSON.stringify(state)); } this function checks that "symbol" exists as a value in the optionsArray return false if it cannot find the symbol among any value | function SymbolIsInOptions(symbol, optionsArray) {
// var IsInOptions = false
IsInOptions = optionsArray.includes(symbol)
return optionsArray.includes(symbol)
// return IsInOptions
} | [
"function isSymbolString(s) {\n return symbolValues[s] || isPrivateSymbol(s);\n }",
"isAdded(stockSymbol) {\n return this.stockChart.series.some((series) => {\n return series.name === stockSymbol.toUpperCase();\n });\n }",
"function check(symbol) {\n \t\t\t\t\n \t\tif (!mode.terminator && symbol==\";\") { // For single instruction do as if \";\" was specified \n \t\t\tif (test(symbol)) lexer.next();\n \t\t\treturn true;\n \t\t} else {\t\t\t\t\t\t\t\t// Normal operation\n \t\t\tif (symbol==\"{\") mode.terminatorOn;\t\t\t// Turn Termination on of on entering a block in Instruction Mode\n \t\t\telse if (symbol==\"}\") mode.terminatorOff;\n \t\t\n \t\t\tif (test(symbol)) {\n \t\t\t\tlexer.next();\n \t\t\t\treturn true;\n \t\t\t} else {\n \t\t\t\terror.expected(symbol);\n \t\t\t\treturn false;\n \t\t\t}\n \t\t}\n \t}",
"isNonterminal(symbol) {\n return this.nonterminals.includes(symbol);\n }",
"function isState(message){\n console.log(states.indexOf('' + message) + ' ' + message);\n if (states.indexOf(message) != -1){\n return true;\n } else {\n return false;\n }\n}",
"function test(symbol) {\n \t\tif (lexer.current.content == symbol) return true;\n \t\telse return false;\n \t}",
"hasSymbol(name, searchParent = true) {\n return !!this.getSymbol(name, searchParent);\n }",
"static isLateBoundSymbol(symbol) {\n // eslint-disable-next-line no-bitwise\n if (symbol.flags & ts.SymbolFlags.Transient &&\n symbol.checkFlags === ts.CheckFlags.Late) {\n return true;\n }\n return false;\n }",
"function hasOptions() {\n if (typeof currMsg.opt == 'undefined' || currMsg.opt.length == 0) {\n return false;\n }\n return true;\n}",
"checkWord(word){\n this.nonTerminalSymbols.forEach(item => {\n if (word.indexOf(item) !== -1) {\n this.wordExist = true;\n }\n });\n }",
"isInErrorState_(state) {\n return state == TermsOfServiceScreenState.ERROR;\n }",
"checkValidityProblems() {\n\t\t//Check whether there are any unnamed items or items without prices\n\t\tlet problems = false;\n\t\tif(this.state.albumName === \"\") {\n\t\t\tproblems = true;\n\t\t}\n\t\tfor (let item of this.state.items) {\n\t\t\tif(item.itemName === \"\" || (this.state.isISO && item.description === \"\") || (!this.state.isISO && (item.price === \"\" || item.pic === null)) ) {\n\t\t\t\tproblems = true;\n\t\t\t}\n\t\t}\n\t\tif (problems) {\n\t\t\tlet items = this.state.items;\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\titems[i].highlighted = true;\n\t\t\t}\n\t\t\tthis.setState({\n\t\t\t\tshowMissingFieldsPopup: true,\n\t\t\t\thighlighted: true,\n\t\t\t\titems: items\n\t\t\t})\n\t\t}\n\t\treturn(problems);\n\t}",
"_submitState() {\n let objFields = Object.values(Object.values(this.testObj));\n let stateArr = objFields.map(f => f.state); // Creates array from test object with state boolean values.\n // Checks if the test array includes false, and changes the submit button according to this result.\n this._inputState(this.HTML.submitForm, !stateArr.includes(false), false);\n }",
"function serializeSymbol(symbol) {\n //getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;\n var name009 = checker.getTypeOfSymbolAtLocation(symbol,symbol.valueDeclaration)//: string;\n\n // const kind = symbol.valueDeclaration ? symbol.valueDeclaration.kind : undefined\n var test = checker.getDefaultFromTypeParameter(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))\n \n var type = checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))\n var name = symbol.getName()\n if(name===\"idgen\"){\n type = JSON.parse(type)\n }\n\n //add optional value \n if(symbol.valueDeclaration ){\n if(symbol.valueDeclaration.questionToken){\n type = [ 'Optional', type ]\n }else if (symbol.valueDeclaration.initializer){\n //array of litteralexpression\n //var ss = checker.getTypeFromTypeNode(symbol.valueDeclaration.initializer)\n //var startV = checker.typeToString(symbol.valueDeclaration.initializer)\n\n }\n }\n\n \n\n // var checker.isOptionalParameter(node: ParameterDeclaration);\n\n //var opt = checker.isOptionalParameter(symbol.valueDeclaration);\n\n return {\n name: name,\n type: type//checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))\n };\n }",
"function processExtState() {\n //Error if current arg is not a value and no values encountered\n //yet for -ext. Otherwise, store values for the extensions.\n if ('-ext' !== sword) {\n if ('.' === sword.charAt(0) &&\n oresult.agoodExtVals.length ===\n oresult.aextValLangs.length) {\n\n oresult.agoodExtVals.unshift(sword);\n bok = false;\n } else if ('.' !== sword.charAt(0) &&\n '-' !== sword.charAt(0) &&\n oresult.agoodExtVals.length > oresult.aextValLangs.length) {\n oresult.aextValLangs.unshift(sword);\n bok = true;\n } else if ('-' === sword.charAt(0) &&\n oresult.agoodExtVals.length > 0 &&\n oresult.agoodExtVals.length ===\n oresult.aextValLangs.length) {\n sstate = '';\n i -= 1; //Reprocess the current stmt in the next state.\n } else if (('-' === sword.charAt(0) &&\n 0 === oresult.agoodExtVals.length) ||\n ('.' === sword.charAt(0) &&\n oresult.agoodExtVals.length !==\n oresult.aextValLangs.length) ||\n ('.' !== sword.charAt(0) &&\n oresult.agoodExtVals.length ===\n sword.charAt(0)) ||\n oresult.agoodExtVals.length < oresult.aextValLangs.length) {\n throw 'Invalid value for command -ext: ' + sword;\n }\n }\n }",
"checkUnknownOptions() {\n const { rawOptions, globalCommand } = this.cli;\n if (!this.config.allowUnknownOptions) {\n for (const name of Object.keys(rawOptions)) {\n if (name !== '--' &&\n !this.hasOption(name) &&\n !globalCommand.hasOption(name)) {\n console.error(`error: Unknown option \\`${name.length > 1 ? `--${name}` : `-${name}`}\\``);\n process.exit(1);\n }\n }\n }\n }",
"function testChoice() {\n var status = 40;\n var qualifiedState = true;\n $.each(checkChoice, function (ele, index) {\n if (checkChoice[ele] == '') {\n status -= 10;\n } else {\n switch (ele) {\n case \"address\":\n var text = $('.info_Choice input[states=address]').val();\n var reg = /^[a-zA-Z0-9\\u4e00-\\u9fa5]+$/;\n if (!reg.test(text)) {\n showTip(\"您的小区名有误请重新输入\");\n $('.info_Choice input[states=address]').focus();\n qualifiedState = false;\n return false;\n }\n break;\n case \"area\":\n var text = $('.info_Choice input[states=area]').val();\n var reg = /^\\+?[1-9][0-9]*$/;\n if (!reg.test(text)) {\n showTip(\"房屋面积为正整数请重新输入\");\n $('.info_import input[states=area]').focus();\n qualifiedState = false;\n return false;\n }\n break;\n case \"budget\":\n var text = $('.info_Choice input[states=budget]').val();\n var reg = /^\\+?[1-9][0-9]*$/;\n if (!reg.test(text)) {\n showTip(\"预算金额为正整数请重新输入\");\n $('.info_import input[states=budget]').focus();\n qualifiedState = false;\n return false;\n }\n break;\n }\n }\n });\n return {\n state:status,\n error:qualifiedState\n };\n }",
"function isOperation() {\n\t\treturn btnops.includes(track.last);\n\t}",
"getStatus(){ \n // return a clone of the current state garantees it can be \n // stored by the user without being altered when new input events happen\n return {...VIRTUAL_BUTTONS_STATE}; \n // ...eventually deep clone ... unnecessary rignt now ( no nested objects )\n // return JSON.parse( JSON.serialize( VIRTUAL_BUTTONS_STATE ) ); \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates scale of canvas to fit window width Also updates number of hiscores shown | function updateCanvasScale() {
cellSize = (window.innerWidth / 100) * gridCellSizePercent;
cellsPerWidth = parseInt(window.innerWidth / cellSize);
cellsPerHeight = parseInt((cellsPerWidth * 9) / 21);
canvasWidth = window.innerWidth;
canvasHeight = cellSize * cellsPerHeight;
resizeCanvas(canvasWidth, canvasHeight);
if (smallScreen != canvasWidth < minCanvasWidth) {
smallScreen = canvasWidth < minCanvasWidth;
if (!smallScreen) {
ui.showUIByState();
}
}
ui.hiscores.resize(false);
} | [
"function resizeGraph() {\r\n if ($(window).width() < 700) {\r\n $(\"#AdviceCanvas\").css({\"width\": $(window).width() - 50});\r\n $(\"#GraphCanvas\").css({\"width\": $(window).width() - 50});\r\n }\r\n}",
"function updateScale(increment) {\n var ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n //var viewportScale = document.getElementById(\"scale\").value;\n axes.scale += increment;\n draw();\n}",
"function updateLineWidth(size) {\r\n clearCanvas(); /* Clear the Canvas first */\r\n sliderInt = size;\r\n drawcells(); /* Redraw the cells */\r\n}",
"function responsive()\n{\n var w = document.getElementById(\"canvas-holder\").offsetWidth;\n // var defaultWidth = 1040;\n // var defRatio = 1.3;\n // var h = Math.round(w/defRatio);\n //\n // if (h > window.innerHeight) {\n // h = window.innerHeight - 240;\n // w = Math.round(h * 1.3);\n // }\n // var wRatio = w / defaultWidth;\n\n canvas.setWidth(w);\n // canvas.setHeight(h);\n}",
"function UpdateWindowSize()\n{\n var WindowSize = GetWindowSize();\n\n // Only update the sizes if they are larget than zero\n if(WindowSize.X != 0 && WindowSize.Y != 0)\n {\n // Update the canvas size\n Canvas.width = WindowSize.X;\n Canvas.height = WindowSize.Y;\n\n // Update the Vieport to match the size of the canvas\n gl.viewportWidth = Canvas.width;\n gl.viewportHeight = Canvas.height;\n }\n}",
"function resizeCanvas() {\n\t\t\t// When zoomed out to less than 100%, for some very strange reason,\n\t\t\t// some browsers report devicePixelRatio as less than 1\n\t\t\t// and only part of the canvas is cleared then.\n\t\t\tvar ratio = Math.max(window.devicePixelRatio || 1, 1);\n\t\t\tcanvas.width = canvas.offsetWidth * ratio;\n\t\t\tcanvas.height = canvas.offsetHeight * ratio;\n\t\t\tcanvas.getContext(\"2d\").scale(ratio, ratio);\n\t\t}",
"function changeCanvasSize(){ \n\tcanvasSize = canvasSelector.value();\n\tif(canvasSize == 2){\n\t\tmain_canvas = resizeCanvas(1920, 1000);\n\t}\n\telse if(canvasSize == 3){\n\t\tmain_canvas = resizeCanvas(2880, 1500);\n\t}\n\telse {\n\t\tmain_canvas = resizeCanvas(960, 500);\n\t}\n\tclear();\n\tbackground(0);\n\tredraw();\n}",
"function screenRatio(){\n sidebarWidth = width*0.25\n gameWidth = width*0.75;\n}",
"function scaleSketch(){\n\tvar dotElems = $(\"#draftLayer .dot\");\n\tvar textElems = $(\"#draftLayer [type=text]\");\n\n\tif(lastWidthDimen !== parseInt($(\"#draftLayer\").width())){\n\t\tfor (var i = 0; i < dotElems.length; i++) {\n\t\t\tdotElems[i].style.left = (parseInt(dotElems[i].style.left)) * \n\t\t\t\t\t\t\t\t\t ((parseInt($(\"#draftLayer\").width()))/lastWidthDimen) + \"px\";\n\t\t\tdotElems[i].style.top = (parseInt(dotElems[i].style.top)) * \n\t\t\t\t\t\t\t\t\t ((parseInt($(\"#draftLayer\").width()))/lastWidthDimen) + \"px\";\n\t\t}\n\n\t\tfor (var i = 0; i < textElems.length; i++) {\n\t\t\ttextElems[i].style.left = (parseInt(textElems[i].style.left)) * \n\t\t\t\t\t\t\t\t\t ((parseInt($(\"#draftLayer\").width()))/lastWidthDimen) + \"px\";\n\t\t\ttextElems[i].style.top = (parseInt(textElems[i].style.top)) * \n\t\t\t\t\t\t\t\t\t ((parseInt($(\"#draftLayer\").width()))/lastWidthDimen) + \"px\";\n\t\t}\n\n\t\t// Record the lastWidth (of the canvas) every time the smaller dimension of the screen is figured \n\t\t// out (calculated) will use this for scaling when having to reposition child elements of editable \n\t\t// div after scaling\n\t\tlastWidthDimen = parseInt($(\"#draftLayer\").width());\n\t}\n\t\n}",
"function resizeCanvas() {\n //Canvas size constraints\n var height = window.innerHeight;\n var width = window.innerWidth;\n\n graphCanvas = d3.select(\"canvas\")\n .attr(\"height\", height + \"px\")\n .attr(\"width\", width + \"px\")\n .node();\n\n formatMobile();\n}",
"function redrawChart() {\n\tif ($(window).width() != windowWidth) {\n\t\tinit();\n\t\twindowWidth = $(window).width();\n\t}\n}",
"function resizeCanvas() {\n var height = currentBlock.getHeight();\n\n // use the canvas view's dimensions as a starting point; factor out any\n // initial scroll height from the view\n canvas.width = canvasView.clientWidth;\n canvas.height = canvasView.clientHeight/2 * height;\n canvas.height -= canvasView.scrollHeight - canvas.clientHeight;\n\n // compute padding amounts according to the aspect ratio of the canvas\n // view and assign the results to the canvas context for later lookup\n var px, py;\n px = py = VISUAL_PADDING;\n ctx.aspectRatio = canvasView.clientHeight / canvasView.clientWidth;\n px *= ctx.aspectRatio;\n ctx.paddingX = px;\n ctx.paddingY = py;\n\n // perform a draw screen to make the changes apparent\n drawScreen();\n }",
"resize() {\n this.createCanvas();\n }",
"function handleWindowResize() {\r\n width = window.innerWidth;\r\n}",
"function resizeCanvas() {\n // When zoomed out to less than 100%, for some very strange reason,\n // some browsers report devicePixelRatio as less than 1\n // and only part of the canvas is cleared then.\n var ratio = Math.max(window.devicePixelRatio || 1, 1);\n\n // This part causes the canvas to be cleared\n canvas.width = canvas.offsetWidth * ratio;\n canvas.height = canvas.offsetHeight * ratio;\n canvas.getContext(\"2d\").scale(ratio, ratio);\n\n CanvasPad.clear();\n}",
"resizeAxisCanvas() {\n const desiredWidth = this.visualizer.canvas.width;\n const desiredHeight = this.visualizer.canvas.height;\n\n if (this.canvas.width !== desiredWidth || this.canvas.height !== desiredHeight) {\n this.canvas.width = desiredWidth;\n this.canvas.height = desiredHeight;\n }\n }",
"function resize(){\n const width = window.innerWidth - 100;\n const topHeight = d3.select(\".top\").node().clientHeight\n const height = window.innerHeight - topHeight - 50\n console.log(width, height)\n \n self.camera.aspect = width / height;\n self.camera.updateProjectionMatrix();\n self.renderer.setSize(width, height);\n render()\n\n }",
"setCanvasRatio() {\n const canvasElement = this.getCanvasElement();\n const cssWidth = parseInt(canvasElement.style.width, 10);\n const originWidth = canvasElement.width;\n const ratio = originWidth / cssWidth;\n\n this._ratio = ratio;\n }",
"function configureCanvas(){\n\tvar h = $(window).height();\n\tvar w = $(window).width();\n\t\n\tcanvas.width = w;\n\tcanvas.height = h;\n\t\n\tbuild_threshhold = w * (width.devicePixelRatio || 1);\n\tbreak_threshhold = build_threshhold * 1.3;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1 Using the varabile persons Create a function called avgAge that accept an array and return average age of this array Ex: avgAge(persons) => 41.2 | function avgAge(persons) {
var result = persons.reduce(function (total, elem) {
return total + elem.age;
}, 0);
return result / persons.length;
} | [
"function avgAge(persons) \n{\n var out;\nout=persons.reduce()\n\n return out\n}",
"function averageAge(people){\n\tvar average = 0;\n\tfor(var i = 0; i < people.length; i++){\n\t\taverage += people[i].age;\n\t}\n\treturn average / people.length;\n}",
"function average(){\n\t\t\tvar sum = 0;\n\t\t\tlist.forEach(function(item){\n\t\t\t\tsum += item.age;\n\t\t\t});\n\n\t\t\treturn sum / list.length;\n\t\t}",
"function sumAges(arr) {\n}",
"function getSummedAge(people) {\n return people.reduce((sum,i)=>sum+i.age,0);\n}",
"function avgValue(array)\n{\n\tvar sum = 0;\n\tfor(var i = 0; i <= array.length - 1; i++)\n\t{\n\t\tsum += array[i];\n\t}\n\tvar arrayLength = array.length;\n\treturn sum/arrayLength;\n}",
"average(marks) {}",
"function averageNumbers(array){\n let sum = 0;\n let avg;\n for ( let i = 0 ; i < array.length ; i++ ){\n sum = sum + array[i];\n avg = sum / array.length\n }\n return avg\n}",
"getSumOfAgeRatios() {\n let sum = 0;\n for (let ageGroup of this.ageGroups) {\n sum += this.getAgeRatio(ageGroup);\n }\n return sum;\n }",
"function calculateAverage(grades) {\n // grades is an array of numbers\n total = 0\n for(let i = 0; i <grades.length; i++){\n total += grades[i];\n }\n return Math.round(total / grades.length);\n}",
"function calculateAverage(ratings){\n var sum = 0;\n for(var i = 0; i < ratings.length; i++){\n sum += parseInt(ratings[i], 10);\n }\n\n var avg = sum/ratings.length;\n\n return avg;\n }",
"function avg(v){\n s = 0.0;\n for(var i=0; i<v.length; i++)\n s += v[i];\n return s/v.length;\n}",
"function calcAverage(tips){\n var sum = 0\n for(var i = 0; i < tips.length; i++){\n sum = sum + tips[i]\n }\n return sum / tips.length\n }",
"calculateStudentAverage(){\n this.totalPoints = calculateTotal(this)\n this.average = Number((this.totalPoints/this.submissions.length).toFixed(2))\n\n }",
"function five_match_average(array_of_scores){\n five_match_score=array_of_scores.slice(0,5)\n total=0\n for(var x in five_match_score){\n total+=five_match_score[x]\n }\n console.log(total/5)\n}",
"function find_average() {\n number_of_accounts = accounts.length;\n console.log(\"Number of bank accounts: \" + number_of_accounts);\n total = total_cash();\n average = total / number_of_accounts;\n console.log(\"Average bank account value: £\" + average);\n}",
"function averageMomChildAgeDiff() {\n var ageDifferences = [];\n \n // ignore the mothers that are null, or don't exist in our ancestry database\n var filteredAncestry = ancestry.filter(hasKnownMother);\n \n // for every person in our ancestry array\n filteredAncestry.forEach(function(person) {\n // get the birth year of the person\n var birth = person.born;\n // get the birth year of the mother\n var motherBirth = byName[person.mother].born;\n // calculate the age difference\n var ageDiff = birth - motherBirth;\n // push it to our age differences array\n ageDifferences.push(ageDiff); \n });\n\n return average(ageDifferences);\n}",
"function absAvg(arr){\n // arr is a typed array! \n var abs_avg = arr.reduce((a,b) => (a+Math.abs(b))) / arr.length;\n return abs_avg; \n}",
"function calcAverage (tips) {\n var sum = 0;\n for (var i = 0; i < tips.length; i++) {\n sum += tips[i];\n }\n return sum / tips.length;\n}",
"function calcAveragePages (arr) {\r\n let total = 0\r\n arr.forEach(number => {\r\n total += number\r\n return total\r\n })\r\n return Math.round(total / arr.length)\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for getV3ProjectsIdHooksHookId | getV3ProjectsIdHooksHookId(incomingOptions, cb) {
const Gitlab = require('./dist');
let defaultClient = Gitlab.ApiClient.instance;
// Configure API key authorization: private_token_header
let private_token_header = defaultClient.authentications['private_token_header'];
private_token_header.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_header.apiKeyPrefix = 'Token';
// Configure API key authorization: private_token_query
let private_token_query = defaultClient.authentications['private_token_query'];
private_token_query.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_query.apiKeyPrefix = 'Token';
let apiInstance = new Gitlab.ProjectsApi()
/*let id = "id_example";*/ // String | The ID of a projec
/*let hookId = 56;*/ // Number | The ID of a project hook
apiInstance.getV3ProjectsIdHooksHookId(incomingOptions.id, incomingOptions.hookId, (error, data, response) => {
if (error) {
cb(error, null)
} else {
cb(null, data)
}
});
} | [
"getV3ProjectsIdHooks(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdHooks(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"putV3ProjectsIdHooksHookId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let hookId = 56;*/ // Number | The ID of the hook to updat\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdHooksHookId(incomingOptions.id, incomingOptions.hookId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdHooks(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdHooks(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"deleteV3ProjectsIdHooksHookId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let hookId = 56;*/ // Number | The ID of the hook to delete\napiInstance.deleteV3ProjectsIdHooksHookId(incomingOptions.id, incomingOptions.hookId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3RunnersId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.RunnersApi()\n/*let id = 56;*/ // Number | The ID of the runner\napiInstance.getV3RunnersId(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3ProjectsIdDeploymentsDeploymentId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let deploymentId = 56;*/ // Number | The deployment ID\napiInstance.getV3ProjectsIdDeploymentsDeploymentId(incomingOptions.id, incomingOptions.deploymentId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3ProjectsIdBuildsBuildId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let buildId = 56;*/ // Number | The ID of a build\napiInstance.getV3ProjectsIdBuildsBuildId(incomingOptions.id, incomingOptions.buildId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"deleteV3HooksId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.HooksApi()\n/*let id = 56;*/ // Number | The ID of the system hook\napiInstance.deleteV3HooksId(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3ProjectsIdBuildsBuildIdTrace(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let buildId = 56;*/ // Number | The ID of a build\napiInstance.getV3ProjectsIdBuildsBuildIdTrace(incomingOptions.id, incomingOptions.buildId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"getV3ProjectsIdPipelinesPipelineId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let pipelineId = 56;*/ // Number | The pipeline ID\napiInstance.getV3ProjectsIdPipelinesPipelineId(incomingOptions.id, incomingOptions.pipelineId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3ProjectsIdTriggersToken(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let token = \"token_example\";*/ // String | The unique token of trigger\napiInstance.getV3ProjectsIdTriggersToken(incomingOptions.id, incomingOptions.token, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"function getId(commitRange) {\n //Get a string identifier that can be used as a key in a map of CommitRanges\n if (commitRange.getPullRequest()) {\n return commitRange.getPullRequest().getId();\n }\n\n return commitRange.getUntilRevision().getId() + \"_\" + (commitRange.getSinceRevision() ? commitRange.getSinceRevision().getId() : ROOT);\n }",
"getV3ProjectsIdKeys(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the project\napiInstance.getV3ProjectsIdKeys(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3ProjectsIdDeployKeysKeyId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the projec\n/*let keyId = 56;*/ // Number | The ID of the deploy key\napiInstance.getV3ProjectsIdDeployKeysKeyId(incomingOptions.id, incomingOptions.keyId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3ProjectsIdVariablesKey(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let key = \"key_example\";*/ // String | The key of the variable\napiInstance.getV3ProjectsIdVariablesKey(incomingOptions.id, incomingOptions.key, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3ProjectsIdVariables(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdVariables(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3ProjectsIdMergeRequestMergeRequestIdChanges(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number | \napiInstance.getV3ProjectsIdMergeRequestMergeRequestIdChanges(incomingOptions.id, incomingOptions.mergeRequestId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3SnippetsId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.SnippetsApi()\n/*let id = 56;*/ // Number | The ID of a snippet\napiInstance.getV3SnippetsId(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"project_script(id) {\n return query.project_script(id, this.network)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Drive the REST API to watch the item | function watch(itemNumber) {
console.log("Watch " + itemNumber);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/rest/wishlists/' + activeDistributorID);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(itemNumber);
} | [
"getWatchlists() {\n return new Request({\n path: '/_mobile/usercontent/watchlist',\n method: 'GET',\n headers: {\n 'X-AuthenticationSession': this.authenticationSession,\n 'X-SecurityToken': this.securityToken\n }\n });\n }",
"watch(mountpoint) {\n if (mountpoint.attributes.watch === false) {\n return;\n }\n\n if (this.core.config('vfs.watch') === false) {\n return;\n }\n\n if (!mountpoint.attributes.root) {\n return;\n }\n\n const adapter = mountpoint.adapter\n ? this.adapters[mountpoint.adapter]\n : this.adapters.system;\n\n if (typeof adapter.watch === 'function') {\n const watch = adapter.watch(mountpoint, (args, dir) => {\n const target = mountpoint.name + ':/' + dir;\n const keys = Object.keys(args);\n const filter = keys.length === 0\n ? () => true\n : ws => keys.every(k => ws._osjs_client[k] === args[k]);\n\n this.core.broadcast('osjs/vfs:watch:change', [{\n path: target\n }, args], filter);\n });\n\n this.watches.push({\n id: mountpoint.id,\n watch\n });\n\n signale.watch('Watching mountpoint', mountpoint.name);\n }\n }",
"watchUpdates(periodMS) {\n this.get('page').watchEntryUpdates(this, periodMS);\n }",
"function onWatch(request, response) {\n var sendResponse = function() {\n \tresponse.writeHead(200, { 'Content-Type': 'text/plain' });\n \tvar changed = [];\n \tfor (var key in changeSet) {\n \t changed.push(key);\n \t}\n \t response.write(changed.join(\"\\n\"), 'utf-8');\n \tresponse.end(\"\", 'utf-8');\n changeSet = {};\n };\n\n var anyKeys = false;\n for (var key in changeSet) {\n // Ensure that we're only checking keys for the changeSet and nothing that was inherited.\n if (changeSet.hasOwnProperty(key)) {\n anyKeys = true;\n break;\n }\n }\n\n if (!anyKeys) {\n activeWatcher = sendResponse;\n } else {\n // Consume all of the changes immediately.\n sendResponse();\n }\n }",
"function post (data, callback) {\n return $.ajax({\n type : 'POST'\n , url : '/' + prefix + '/watch'\n , contentType : 'application/json; charset=utf-8'\n , data : JSON.stringify(data)\n , dataType : 'json'\n , success : callback\n });\n }",
"async watchFriendsList()\n\t{\n\t\tawait DB.watchFriendsList();\n\t}",
"function unwatch(itemNumber) {\n\tconsole.log(\"Unwatch \" + itemNumber);\n\n\tvar xhr = new XMLHttpRequest();\n\txhr.open('DELETE', '/rest/wishlists/' + activeDistributorID + '/'\n\t\t\t+ itemNumber);\n\txhr.send();\n}",
"static setMediaTreeItem(req, res) {\n let id = req.params.id;\n let item = req.body;\n\n MediaHelper.setTreeItem(req.project, req.environment, id, item)\n .then(() => {\n res.status(200).send(item);\n })\n .catch((e) => {\n res.status(502).send(ApiController.printError(e));\n }); \n }",
"_fetchFromAPI() {\n // Generate new items\n let { indexedDb } = this;\n\n return indexedDb.add('item', [\n this._createItemPayload(),\n this._createItemPayload(),\n this._createItemPayload(),\n ]);\n }",
"function updateItemToList(item)\n{\n return jQuery.ajax({\n url: item.__metadata.uri,\n type: \"POST\",\n contentType: \"application/json;odata=verbose\",\n data: JSON.stringify(item),\n headers: {\n \"Accept\": \"application/json;odata=verbose\",\n \"X-HTTP-Method\": \"MERGE\",\n \"If-Match\": item.__metadata.etag\n }\n });\n}",
"function reqTV(message, args) {\n message.channel.send('Checking for: ' + args);\n request({\n headers: {'ApiKey': ombi},\n uri: base + 'Search/tv/' + args,\n method: 'GET'\n }, function (err, res, body) {\n var show = JSON.parse(body); \n var showData = {\n \"requestAll\": true,\n \"latestSeason\": true,\n \"firstSeason\": true,\n \"tvDbId\": show[0].id,\n \"seasons\": [{\"seasonNumber\": 0,\"episodes\": [{\"episodeNumber\": 0}]}]\n }\n reqTVPost(showData); \n message.channel.send(\"Making request for: \" + show[0].title);\n });\n}",
"_createWatcher() {\n const _watcher = Looper.create({\n immediate: true,\n });\n _watcher.on('tick', () => safeExec(this, 'fetch'));\n\n this.set('_watcher', _watcher);\n }",
"_handleButtonNewResourceList()\n {\n var project = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__PROJECT_GET_ACTIVE);\n Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__RESOURCELIST_CREATE, {project: project});\n }",
"function showWatchlist() {\n\n // create the list and display it\n let watched = '<ul id=\"watched\" class=\"list-group list-group-flush tabl\">';\n $(\"#stock-list\").empty();\n $(\"#stock-list\").append(watched);\n\n // get all stocks on the user's watchlist\n $.ajax({\n url: '/account/watchlist',\n type: 'GET',\n contentType: 'application/JSON',\n success: function(response) {\n let watched = JSON.parse(response);\n let entry;\n let cur_price;\n for(let i = 0; i < watched.length; i++) {\n let position = watched[i];\n\n // get the current price of each stock on the watchlist\n $.ajax({\n url: '/fh/price/c/' + position.symbol,\n type: 'GET',\n contentType: 'appliaction/JSON',\n success: function(response) {\n cur_price = JSON.parse(response);\n\n // append the stock's info to the list\n if(cur_price >= position.avgPrice) {\n entry = '<ul class=\"list-group list-group-horizontal\"><li class=\"list-group-item align-items-center\"><button type=\"button\" class=\"btn btn-outline-dark position-symbol\" onclick=\"detailView(event)\">'+position.symbol+'</button></li><li class=\"list-group-item align-items-center\"><div class=\"alert alert-success cur-price\">'+cur_price+'</div></li></ul>'\n }\n else {\n entry = '<ul class=\"list-group list-group-horizontal\"><li class=\"list-group-item align-items-center\"><button type=\"button\" class=\"btn btn-outline-dark position-symbol\" onclick=\"detailView(event)\">'+position.symbol+'</button></li><li class=\"list-group-item align-items-center\"><div class=\"alert alert-danger cur-price\">'+cur_price+'</div></li></ul>'\n }\n $(\"#watched\").append(entry);\n },\n error: function(xhr, status, error) {\n var errorMessage = xhr.status + ': ' + xhr.statusText\n alert('Error - ' + errorMessage);\n }\n })\n }\n },\n error: function(xhr, status, error) {\n var errorMessage = xhr.status + ': ' + xhr.statusText\n alert('Error - ' + errorMessage);\n }\n })\n }",
"function onclick_watched(e, video_id) {\n flixstack_api.mark_as_watched(video_id, function(data, textStatus) {\n update_link(video_id, false);\n }); \n\n e.preventDefault();\n e.stopPropagation();\n return false;\n}",
"list() {\n\t\tif (this.watchList.length) {\n\t\t\tchannel.appendLocalisedInfo('watched_paths');\n\n\t\t\tthis.watchList.forEach((item) => {\n\t\t\t\tchannel.appendLine(\n\t\t\t\t\ti18n.t('path_with_trigger_count', item.path, item.data.triggers)\n\t\t\t\t);\n\t\t\t});\n\n\t\t\tchannel.appendLine('');\n\t\t} else {\n\t\t\tchannel.appendLocalisedInfo('no_paths_watched');\n\t\t}\n\n\t\tchannel.show();\n\t}",
"function getItems() {\n fetch('http://genshinnews.com/api')\n .then(response => response.text())\n .then(data => {\n discordHooks = JSON.parse(`[${data}]`)\n webhookLoop(discordHooks)\n });\n }",
"function idpRestApiCollectionMonitor(req, resp) {\n var maxItemCount = MAX_API_RECORDS;\n var collName = COL_API_CALLS;\n var fName = entryLog(arguments.callee.name, 'triggered with max item count: ' + maxItemCount);\n\n ClearBlade.init({request:req});\n var col = ClearBlade.Collection({collectionName:collName});\n var rowsToDelete = 0;\n var rowsDeleted = 0;\n\n var deleteOldestRow = function (item_id) {\n vlog(logLevels.DEBUG, fName + ' deleteOldestRow deleting row ' + item_id);\n var col = ClearBlade.Collection({collectionName:collName});\n var query = ClearBlade.Query();\n query.equalTo('item_id', item_id);\n col.remove(query, function(err, result) {\n if (err) {\n vlog(logLevels.ERROR, fName + ' deleteOldestRow error: ' + JSON.stringify(result));\n resp.error('Collection remove error: ' + JSON.stringify(result));\n } else {\n vlog(logLevels.DEBUG, fName + ' deleted oldest row: ' + JSON.stringify(result));\n rowsDeleted++;\n }\n });\n };\n \n // TODO: check various API error conditions that should be notified to an admin indicating a problem needing investigation\n \n col.count(function(err, result){\n if (err) {\n vlog(logLevels.ERROR, fName + ' Collection count error: ' + JSON.stringify(result));\n resp.error('Collection count error: ' + JSON.stringify(result));\n } else {\n vlog(logLevels.DEBUG, fName + ' IDP API collection has ' + result.count + ' items of ' + maxItemCount + ' allowed');\n if (result.count > maxItemCount) {\n rowsToDelete = result.count - maxItemCount;\n }\n vlog(logLevels.DEBUG, fName + ' identified ' + rowsToDelete + ' rows to delete');\n }\n });\n if (rowsToDelete > 0) {\n var qDeleteRows = ClearBlade.Query({collectionName:collName});\n qDeleteRows.ascending('call_time');\n qDeleteRows.setPage(rowsToDelete, 1);\n qDeleteRows.fetch(function(err, result){\n if (err) {\n vlog(logLevels.ERROR, fName + ' qDeleteRows Query error: ' + JSON.stringify(result));\n resp.error('Query error: ' + JSON.stringify(result));\n } else {\n vlog(logLevels.INFO, fName + ' qDeleteRows found ' + result.DATA.length + ' results');\n for (var i=0; i < result.DATA.length; i++) {\n deleteOldestRow(result.DATA[i].item_id);\n }\n }\n });\n }\n if (rowsDeleted > 0) {\n vlog(logLevels.INFO, fName + 'Deleted ' + rowsDeleted + ' rows');\n }\n resp.success('Deleted ' + rowsDeleted + ' rows.');\n}",
"function subscribe(id) {\n weavy.api.follow(\"item\", id).then(function () {\n updateSubscribers(id);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inject the header of mocking child_process to JS file So that its child_process can also be instrumented and collected coverage, recursively. | function inject_mockery_header(file) {
var dirname = path.dirname(file),
basename = path.basename(file),
fs = require('fs'),
new_file,
orig_content,
mocker_module,
lines,
header;
new_file = path.resolve(dirname, injected_file_prefix + basename);
mocker_module = __dirname + "/" + path.basename(__filename);
header = "var mockery = require('mockery');\
var path = require('path');\
var mocker = require('" + mocker_module + "');\
var mock_child_process = { spawn: mocker.spawn };\
mocker.set_istanbul_root('" + istanbul_root + "');\
mocker.set_exclude_pattern('" + exclude_pattern + "');\
mockery.registerMock('child_process', mock_child_process);\
mockery.enable({ useCleanCache: true, warnOnReplace: false, warnOnUnregistered: false });";
orig_content = fs.readFileSync(file, 'utf8');
//check if the first line is shebang interpreter directive
lines = orig_content.split("\n");
if (lines[0].indexOf("#!") === 0) {
lines[0] += "\n" + header;
} else {
lines[0] = header + lines[0];
}
fs.writeFileSync(new_file, lines.join("\n"));
return new_file;
} | [
"before() {\n if (process.env.START_HOT) {\n console.log('Starting Main Process...');\n spawn('npm', ['run', 'start-main-dev'], {\n shell: true,\n env: process.env,\n stdio: 'inherit',\n })\n .on('close', code => process.exit(code))\n .on('error', spawnError => console.error(spawnError));\n }\n }",
"function mockedExecFile(util, args, doneCallback) {\n let outputFileName = args[args.length - 1];\n\n copyTestFile(outputFileName, function(copyTestFile) {\n doneCallback();\n });\n}",
"async function buildShims() {\n // Install a package.json file in BUILD_DIR to tell node.js that the\n // .js files therein are ESM not CJS, so we can import the\n // entrypoints to enumerate their exported names.\n const TMP_PACKAGE_JSON = path.join(BUILD_DIR, 'package.json');\n await fsPromises.writeFile(TMP_PACKAGE_JSON, '{\"type\": \"module\"}');\n\n // Import each entrypoint module, enumerate its exports, and write\n // a shim to load the chunk either by importing the entrypoint\n // module or by loading the compiled script.\n await Promise.all(chunks.map(async (chunk) => {\n const modulePath = posixPath(chunk.moduleEntry ?? chunk.entry);\n const scriptPath =\n path.posix.join(RELEASE_DIR, `${chunk.name}${COMPILED_SUFFIX}.js`);\n const shimPath = path.join(BUILD_DIR, `${chunk.name}.loader.mjs`);\n const parentImport =\n chunk.parent ?\n `import ${quote(`./${chunk.parent.name}.loader.mjs`)};` :\n '';\n const exports = await import(`../../${modulePath}`);\n\n await fsPromises.writeFile(shimPath,\n `import {loadChunk} from '../tests/scripts/load.mjs';\n${parentImport}\n\nexport const {\n${Object.keys(exports).map((name) => ` ${name},`).join('\\n')}\n} = await loadChunk(\n ${quote(modulePath)},\n ${quote(scriptPath)},\n ${quote(chunk.scriptExport)},\n);\n`);\n }));\n\n await fsPromises.rm(TMP_PACKAGE_JSON);\n}",
"_compile(content, filename, filename2) {\n\n content = internalModule.stripShebang(content);\n\n // create wrapper function\n var wrapper = Module.wrap(content);\n\n var compiledWrapper = vm.runInThisContext(wrapper, {\n filename: filename,\n lineOffset: 0,\n displayErrors: true\n });\n\n var inspectorWrapper = null;\n if (process._breakFirstLine && process._eval == null) {\n if (!resolvedArgv) {\n // we enter the repl if we're not given a filename argument.\n if (process.argv[1]) {\n resolvedArgv = Module._resolveFilename(process.argv[1], null, false);\n } else {\n resolvedArgv = 'repl';\n }\n }\n\n // Set breakpoint on module start\n if (filename2 === resolvedArgv) {\n delete process._breakFirstLine;\n inspectorWrapper = process.binding('inspector').callAndPauseOnStart;\n if (!inspectorWrapper) {\n const Debug = vm.runInDebugContext('Debug');\n Debug.setBreakPoint(compiledWrapper, 0, 0);\n }\n }\n }\n var dirname = path.dirname(filename);\n var require = internalModule.makeRequireFunction(this);\n var result;\n if (inspectorWrapper) {\n result = inspectorWrapper(compiledWrapper, this.exports, this.exports,\n require, this, filename, dirname, require.resolve);\n } else {\n result = compiledWrapper.call(this.exports, this.exports, require, this,\n filename, dirname, require.resolve);\n }\n return result;\n }",
"function onSeleniumStart (config, cb) {\n return function onSeleniumStart (error, child) {\n if (error) {\n if (cb) return cb(error.message)\n process.stderr.write(error.message)\n process.exit(1)\n }\n\n config.seleniumProcess = child\n if (cb) { cb(null, child) }\n }\n}",
"onPrepare() {\n jasmine.getEnv().addReporter({\n specDone: (res) => {\n if (res.status === 'failed') {\n const failedInfo = {\n fullName: res.fullName,\n failedExpectations: JSON.stringify(res.failedExpectations)\n }\n\n this.promises.push(browser.takeScreenshot()\n .then(imgur.uploadBase64)\n .then((imgurJson) => {\n failedInfo.screenshot = imgurJson.data.link\n })\n .then(() => {\n return browser.manage().logs().get('browser')\n })\n .then((browserLog) => {\n failedInfo.browserLog = JSON.stringify(browserLog)\n })\n .then(() => {\n this.failedSpecs.push(failedInfo)\n })\n .catch(GDocsPlugin.logError))\n }\n }\n })\n }",
"function setup() {\n\t// Redirect uncaught/unhandled things to console.error (makes logging them to file possible)\n\t// ------------------------------------------------------------------------------\n\tprocess.on('uncaughtException', (err) => {\n\t\tconsole.error(err);\n\t\tprocess.exit(1);\n\t});\n\tprocess.on('unhandledRejection', (reason, p) => {\n\t\tconsole.error('Unhandled Rejection at:', p, 'reason:', reason);\n\t\tprocess.exit(1);\n\t});\n\n\t// Redirect stdout/stderr to log files if app is run as packaged .exe\n\t// --------------------------------------------------------------------\n\tconst stdoutFile = fs.createWriteStream(PATHS.DEBUG_LOG, { flags: 'a' });\n\t// ignore stdout if not run with --debug\n\tconst isDebug = process.argv.includes('--debug');\n\tprocess.stdout.write = function (string, encoding) {\n\t\tif (isDebug) {\n\t\t\tstring = `${fecha.format(new Date(), 'HH:mm:ss.SSS')}: ${string}`;\n\t\t\tstdoutFile.write(string, encoding);\n\t\t}\n\t};\n\n\tconst stderrFile = fs.createWriteStream(PATHS.ERROR_LOG, { flags: 'a' });\n\tprocess.stderr.write = function (string, encoding) {\n\t\tstring = `${fecha.format(new Date(), 'HH:mm:ss.SSS')}: ${string}`;\n\t\tstderrFile.write(string, encoding);\n\t};\n}",
"_writingCommandJs() {\n let context = this.extensionConfig;\n\n this.fs.copy(this.sourceRoot() + '/vscode', context.name + '/.vscode');\n this.fs.copy(this.sourceRoot() + '/test', context.name + '/test');\n\n this.fs.copy(this.sourceRoot() + '/vscodeignore', context.name + '/.vscodeignore');\n\n if (this.extensionConfig.gitInit) {\n this.fs.copy(this.sourceRoot() + '/gitignore', context.name + '/.gitignore');\n }\n\n this.fs.copyTpl(this.sourceRoot() + '/README.md', context.name + '/README.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/CHANGELOG.md', context.name + '/CHANGELOG.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/vsc-extension-quickstart.md', context.name + '/vsc-extension-quickstart.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/jsconfig.json', context.name + '/jsconfig.json', context);\n\n this.fs.copyTpl(this.sourceRoot() + '/extension.js', context.name + '/extension.js', context);\n this.fs.copyTpl(this.sourceRoot() + '/package.json', context.name + '/package.json', context);\n this.fs.copyTpl(this.sourceRoot() + '/.eslintrc.json', context.name + '/.eslintrc.json', context);\n\n this.extensionConfig.installDependencies = true;\n }",
"_spawnProcess (command, args, onstdout, onstderr) {\n return new Promise((resolve, reject) => {\n let shell = Spawn(command, args);\n shell.on('close', (code) => {\n resolve(code);\n });\n\n shell.stdout.on('data', (data) => {\n if (onstdout) {\n let d = data.toString();\n if (d.length > 1) onstdout(d);\n }\n });\n\n shell.stderr.on('data', (data) => {\n if (onstderr) {\n let d = data.toString();\n if (d.length > 1) onstderr(d);\n }\n });\n });\n }",
"_writingCommandJs() {\n let context = this.extensionConfig;\n\n this.fs.copy(this.sourceRoot() + '/vscode', context.name + '/.vscode');\n this.fs.copy(this.sourceRoot() + '/test', context.name + '/test');\n this.fs.copy(this.sourceRoot() + '/typings', context.name + '/typings');\n this.fs.copy(this.sourceRoot() + '/vscodeignore', context.name + '/.vscodeignore');\n\n if (this.extensionConfig.gitInit) {\n this.fs.copy(this.sourceRoot() + '/gitignore', context.name + '/.gitignore');\n }\n\n this.fs.copyTpl(this.sourceRoot() + '/README.md', context.name + '/README.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/CHANGELOG.md', context.name + '/CHANGELOG.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/vsc-extension-quickstart.md', context.name + '/vsc-extension-quickstart.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/jsconfig.json', context.name + '/jsconfig.json', context);\n\n this.fs.copyTpl(this.sourceRoot() + '/extension.js', context.name + '/extension.js', context);\n this.fs.copyTpl(this.sourceRoot() + '/package.json', context.name + '/package.json', context);\n this.fs.copyTpl(this.sourceRoot() + '/.eslintrc.json', context.name + '/.eslintrc.json', context);\n this.fs.copyTpl(this.sourceRoot() + '/installTypings.js', context.name + '/installTypings.js', context);\n\n this.extensionConfig.installDependencies = true;\n }",
"function mockZippingGraphBuildReport (otpV2 = false) {\n let baseFolder, cwd\n if (otpV2) {\n baseFolder = `./${TEMP_TEST_FOLDER}/otp2-base-folder`\n cwd = `./${TEMP_TEST_FOLDER}/otp2-base-folder`\n } else {\n baseFolder = `./${TEMP_TEST_FOLDER}/default`\n cwd = `${TEMP_TEST_FOLDER}/default`\n }\n addCustomExecaMock({\n args: ['zip', ['-r', 'report.zip', 'report'], { cwd }],\n fn: async () => {\n await fs.writeFile(\n `${baseFolder}/report.zip`,\n await fs.readFile(`${baseFolder}/report`)\n )\n }\n })\n}",
"function processPythonInclude( page ){\n\n const dirPath = path.dirname(page.rawPath);\n var lines = page.content.split(\"\\n\");\n // !PYTHON src=\"\" exec=true link=true\n const token = \"!PYTHON\"\n var pageContent = \"\";\n var outputContent = \"\";\n for (let i = 0; i < lines.length; i++) {\n if( lines[i].includes(token) ){\n var line = lines[i];\n var tokens = line.replace(token, \"\").trim().split(\" \");\n var args = {}\n for( let j=0; j<tokens.length; j++){\n var the_arg= tokens[j].split(\"=\");\n args[the_arg[0]] = the_arg[1]; \n }\n\n var pyContent;\n if( \"src\" in args ){\n var relPath = args[\"src\"];\n var py_path = path.join(dirPath, relPath);\n pyContent = fs.readFileSync(py_path, \"utf8\");\n \n if( \"exec\" in args && args.exec == \"true\"){\n // Exec python script and catch stdout\n const wdir = path.dirname(py_path);\n const pyfile = path.basename(py_path);\n const cmd = this.config.get(\"pluginsConfig.python.executable\", \"python\"); \n const cmd_arg = pyfile;\n const timeout = 1000.*this.config.get(\"pluginsConfig.python.timeout\", 60.);\n var child = cp.spawnSync(cmd,[cmd_arg, ], {cwd:wdir, \n timeout:timeout});\n \n if( child.status != 0 ){\n outputContent = \"Execution Error \"\n this.log.warn(pyfile + \" Python execution failed\");\n this.log.debug('error ', child.error);\n this.log.debug('stdout ', child.stdout.toString());\n this.log.debug('stderr ', child.stderr.toString());\n }\n else{\n this.log.info(pyfile + \" succeed\")\n outputContent = child.stdout.toString();\n }\n }\n }\n else{\n this.log.warn(\"!PYTHON tag found but no source file specified\");\n continue; \n }\n\n pageContent += \"```python\\n\"\n pageContent += pyContent + \"\\n\";\n pageContent += \"```\\n\";\n pageContent += \"{\\% Download src=\\\"\" + args.src + \"\\\" \\%} {\\% endDownload \\%}\\n\";\n if( outputContent != \"\"){\n pageContent += \"```\\n\" + outputContent + \"\\n```\\n\";\n }\n\n }\n else{\n pageContent += lines[i] + \"\\n\";\n }\n\n }\n //console.log(this);\n page.content = pageContent;\n return page;\n}",
"async function runCoverage() {\n // If cowboyhat is already running skip.\n if (locked) {\n return\n }\n locked = true\n\n // Await coverage and testing.\n await new Promise((resolve) => {\n spawn(\n 'node_modules/.bin/nyc',\n nycOptions,\n spawnOptions,\n ).on('close', resolve)\n })\n\n // TODO: Find out why this is necessary and document it here.\n if (runCount) {\n console.log('\\n')\n }\n\n // When the report is done finish up.\n spinner.stop('\\nlcov.info complete.')\n locked = false\n runCount += 1\n }",
"setTheJsonOutputFile() {\n const frameworkName = `${process.env.npm_package_name}@${process.env.npm_package_version}`;\n this.outputFormat = ` --format json:${this.outputDirectory}json/${frameworkName}_report_pid_${process.pid}.json`;\n }",
"function startServer(serverPromise) {\n var self = this,\n startTime = Date.now(),\n browsersStarting,\n serverTimeout,\n serverProcess = fork(__dirname + '/KarmaWorker.js', { silent: true });\n\n // Limit the time it can take for a server to start to config.waitForServerTime seconds\n serverTimeout = setTimeout(function() {\n self._setStatus(KarmaServerStatus.DEFUNCT);\n serverPromise.reject(\n 'Could not connect to a Karma server on port ' + self._config.port + ' within ' +\n self._config.waitForServerTime + ' seconds'\n );\n }, self._config.waitForServerTime * 1000);\n\n serverProcess.send({ command: 'start', config: self._config });\n\n serverProcess.stdout.on('data', function(data) {\n var message = data.toString('utf-8'),\n messageParts = message.split(/\\s/g);\n\n logger.debug(message);\n\n //this is a hack: because Karma exposes no method of determining when the server is started up we'll dissect the log messages\n if(message.indexOf('Starting browser') > -1) {\n browsersStarting = browsersStarting ? browsersStarting.concat([messageParts[4]]) : [messageParts[4]];\n }\n if(message.indexOf('Connected on socket') > -1) {\n browsersStarting.pop();\n if(browsersStarting && browsersStarting.length === 0) {\n clearTimeout(serverTimeout);\n self._setStatus(KarmaServerStatus.READY);\n\n logger.info(\n 'Karma server started after %dms and is listening on port %d',\n (Date.now() - startTime), self._config.port\n );\n\n serverPromise.resolve(self);\n }\n }\n });\n\n return serverProcess;\n}",
"function main() {\n console.log(`testing ngtools API...`);\n\n Promise.resolve()\n .then(() => codeGenTest())\n .then(() => i18nTest())\n .then(() => lazyRoutesTest())\n .then(() => {\n console.log('All done!');\n process.exit(0);\n })\n .catch((err) => {\n console.error(err.stack);\n console.error('Test failed');\n process.exit(1);\n });\n}",
"function registerDevice() {\n //Simulate benchmark tests with dummy data.\n const now = new Date();\n const deviceSpecs = {\n memory: \"Fake Test Data\",\n diskSpace: \"Fake Test Data\",\n processor: \"Fake Test Data\",\n internetSpeed: \"Fake Test Data\",\n checkinTimeStamp: now.toISOString(),\n };\n\n const config = {\n deviceId: deviceConfig.deviceId,\n deviceSpecs: deviceSpecs,\n };\n\n const execaOptions = {\n stdout: \"inherit\",\n stderr: \"inherit\",\n };\n\n // Register with the server.\n p2pVpsServer\n .register(config)\n\n // Write out support files (Dockerfile, reverse-tunnel.js)\n .then(clientData => {\n //debugger;\n\n // Save data to a global variable for use in later functions.\n global.clientData = clientData.device;\n\n return (\n writeFiles\n // Write out the Dockerfile.\n .writeDockerfile(\n clientData.device.port,\n clientData.device.username,\n clientData.device.password)\n\n .then(() =>\n // Write out config.json file.\n writeFiles.writeClientConfig()\n )\n\n .catch(err => {\n logr.error(\"Problem writing out support files: \", err);\n })\n );\n })\n\n // Build the Docker container.\n .then(() => {\n logr.log(\"Building Docker Image.\");\n\n return execa(\"./lib/buildImage\", undefined, execaOptions)\n .then(result => {\n //debugger;\n console.log(result.stdout);\n })\n .catch(err => {\n debugger;\n console.error(\"Error while trying to build Docker image!\", err);\n logr.error(\"Error while trying to build Docker image!\", err);\n logr.error(JSON.stringify(err, null, 2));\n process.exit(1);\n });\n })\n\n // Run the Docker container\n .then(() => {\n logr.log(\"Running the Docker image.\");\n\n return execa(\"./lib/runImage\", undefined, execaOptions)\n .then(result => {\n //debugger;\n console.log(result.stdout);\n })\n .catch(err => {\n debugger;\n logr.error(\"Error while trying to run Docker image!\");\n logr.error(JSON.stringify(err, null, 2));\n process.exit(1);\n });\n })\n\n .then(() => {\n logr.log(\"Docker image has been built and is running.\");\n\n // Begin timer to check expiration.\n p2pVpsServer.startExpirationTimer(registerDevice);\n })\n\n .catch(err => {\n logr.error(\"Error in main program: \", err);\n process.exit(1);\n });\n}",
"async function processBenchmarkFile(benchmarkFile, directoryHash) {\n const targetDir = path.dirname(benchmarkFile);\n const benchmarkFileBasename = path.basename(benchmarkFile);\n const htmlFilename = path.join(targetDir, benchmarkFileBasename.replace('.js', '.html'));\n\n async function writeHtmlFile() {\n const html = createHtml(benchmarkFile);\n await writeFile(htmlFilename, html, 'utf8');\n }\n\n async function writeTachometerJsonFile() {\n const engineType = benchmarkFile.includes('/engine-server/') ? 'server' : 'dom';\n const benchmarkName = `${engineType}-${benchmarkFileBasename.split('.')[0]}`;\n const tachometerJson = await createTachometerJson(\n htmlFilename,\n benchmarkName,\n directoryHash\n );\n const jsonFilename = path.join(\n targetDir,\n `${benchmarkFileBasename.split('.')[0]}.tachometer.json`\n );\n await writeFile(jsonFilename, JSON.stringify(tachometerJson, null, 2), 'utf8');\n }\n\n await Promise.all([writeHtmlFile(), writeTachometerJsonFile()]);\n}",
"beforeCommand() { }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=================================================================================================================== Private methods Create a number of differently seeded noise generators equal to the current number of octaves. | _recreateNoiseGenerators() {
const rnd = new MersenneTwister( Math.trunc( this._noiseSeed * 0xFFFFFFFF ) );
for( let i = 0; i < this._options.noise.octaves; ++i ){
const derivedSeed = rnd.random();
const gen = this._noiseGenes[ i ];
if( gen ){
gen.seed = derivedSeed;
}
else {
this._noiseGenes[ i ] = new noise.NoiseGen( derivedSeed );
}
}
} | [
"function createNoiseTrackerArray(){\n\tvar xLimit = 11;\n\tfor(var y=0; y<=15; y++){\n\t\tnoiseTracker[y] = [];\n\t\tnoiseTracker2[y] = [];\n for(var x=0; x<=xLimit; x++){\n\t\t\tvar noiseValue = noise(x, y);\n\t\t\tif(y == 0 || y == 15){\n\t\t\t\tnoiseValue = 0.5;\n\t\t\t}\n\t\t\tnoiseTracker[y][x] = noiseValue;\n\t\t\tnoiseTracker2[y][x] = noise(x * y);\n\t\t}\n\t\tif((y % 2) == 0){\n xLimit = 12;\n }\n else {\n xLimit = 11;\n }\n\t}\n}",
"function genSeeds() {\r\n analyser.getByteTimeDomainData(dataArray);\r\n sliceSize = Math.floor(bufferLength / 5);\r\n\r\n var sum = 0;\r\n var scaleFactor = 138.0;\r\n\r\n // Seed A\r\n for (var i = 0; i < sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedA = sum / (bufferLength/5)\r\n sum = 0;\r\n\r\n // Seed B\r\n for (var i = sliceSize; i < 2*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedB = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed C\r\n for (var i = 2*sliceSize; i < 3*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedC = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed D\r\n for (var i = 3*sliceSize; i < 4*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedD = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed E\r\n for (var i = 4*sliceSize; i < 5*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedE = sum / sliceSize\r\n sum = 0;\r\n\r\n console.log(`A: ${seedA}, B: ${seedB}, C: ${seedC}, D: ${seedD}, E: ${seedE}`);\r\n}",
"function oscillatorCreator(num){\n let oscArray = [];\n for (var i = 0; i<num; i++){\n oscArray.push(audioCtx.createOscillator())\n }\n return oscArray\n}",
"generateSticks() {\n let numberOfSticks = Math.ceil(this.steps);\n for(let i = 0; i <= numberOfSticks; i++)\n new Stick();\n }",
"function randomWaves() {\n var randomX = randomMarkov(.1, .1, .4),\n randomY = randomMarkov(.1, .1, .4),\n randomTime = randomMarkov(.5, 0),\n randomHue = randomMarkov(.05, .1, .5);\n for (var i = 0; i < wavesLength; i++) {\n writeWave(i, [randomX(), randomY()], randomTime(), randomHue(), decayingSineWave);\n }\n }",
"function GenNoise()\n{\n var value;\n for (var i = 0; i < PATTERN_PIXELS; i += 4)\n {\n value = (Math.random() * 255);\n pattern_data.data[i] = value;\n pattern_data.data[i+1] = value;\n pattern_data.data[i+2] = value;\n pattern_data.data[i+3] = PATTERN_ALPHA;\n\n var frame_ind;\n if (transition)\n \tframe_ind = FRAME_IND_ANIM[still_current][anim_frame_current];\n else\n \tframe_ind = FRAME_IND_STILL[still_current];\n\t\tpattern_data.data[i+3] *= FRAME_GRAIN_ALPHA[frame_ind];\n }\n pattern_ctx.putImageData(pattern_data, 0, 0);\n}",
"function createStars() {\n for (var i = 0; i < 150; i += 1) {\n var star = new Star(Math.floor(random(0, width)), Math.floor(random(0, height)), random(1, 5), Math.floor(random(1, 5)));\n stars.push(star);\n }\n}",
"function createNewAliens() {\n aliens.push(\n new Alien(width * random(0.05, 0.12), 150),\n new Alien(width * random(0.2, 0.3), 150),\n new Alien(width * random(0.35, 0.45), 150),\n new Alien(width * random(0.5, 0.6), 150),\n new Alien(width * random(0.7, 0.9), 150)\n );\n}",
"static generateSmallGlows(number) {\n let h = $(window).height();\n let w = $(window).width();\n let scale = (w > h) ? h/800 : w/1200;\n\n h = h/scale;\n w = w/scale;\n\n for(let i = 0; i < number; i++) {\n let left = Math.floor(Math.random()*w) / 1280 * 100;\n let top = Math.floor(Math.random()*(h/2)) / 800 * 100;\n let size = Math.floor(Math.random()*8) + 4;\n $('.small-glows').prepend('<div class=\"small-glow\"></div>');\n let noise = $('.small-glows .small-glow').first();\n noise.css({left: left + '%', top: top + '%', height: size, width: size});\n }\n }",
"function noise1D(){\n\t/*xoff needs to be global, otherwise it wont change every frame\n\tbecause xoff is reset to 0 everytime it produces the same output\n\t(but only as long as the program is running i.e. refreshing the page creates a new output)\n\t*/\n\txoff=0;\n\n\tfor (let x=0; x < windowWidth; x++) {\n\t\txoff = xoff + .005;\n\t\tlet n = noise(xoff);\n\t\tstroke(255*n,0,0);\n\t\tline(x, height*n,x, height);\n\t}\n}",
"function generateTargets() {\n let number = 10;\n let result = [];\n while (result.length < number) {\n result.push({\n id: 'target-' + result.length,\n x: stage.width() * Math.random(),\n y: stage.height() * Math.random()\n });\n }\n return result;\n}",
"function genPoints() {\n noise.seed(Math.random());\n \n points = [];\n \n for (var i = 0; i < 100; i++) {\n var x = (Math.random()*height) - (height/2);\n var y = (Math.random()*width) - (width/2);\n var z = noise.perlin2(x/100, y/100) * 10;\n \n points.push([x, y, z]);\n }\n}",
"function createStars(){\n\tfor ( var i = 0; i < star_num; i++)\n\t {\n\t\tvar x = util.random((1/3)*canvas.width, (2/3)*canvas.width);\n\t\tvar y = util.random((1/3)*canvas.height, (2/3)*canvas.height);\n\t\tvar vx = util.random(1, SPEED, .1);\n\t\tvar vy = util.random(1, SPEED, .1);\n\n\t\tstars.push( new Star(x, y, vx, vy) );\n\t }\n }",
"function createCrystals() {\n $(\"#crystals\").empty();\n for (var i=0; i < 4; i++) {\n var imageCrystal = $(\"<img>\");\n imageCrystal.addClass(\"crystal-image\");\n imageCrystal.attr(\"src\", \"assets/images/crystal.png\");\n imageCrystal.attr(\"data-crystalvalue\", Math.floor(Math.random() * 12) + 1);\n $(\"#crystals\").append(imageCrystal);\n }\n }",
"addRandomDots(n_dots){\n for(let i= 0; i<n_dots;i++){\n this.addRandomDot();\n }\n }",
"function generator(spectra, options) {\n let options = Object.assign({}, {nComb: 1, threshold: 0.5}, options)\n var weights = new Array(options.nComb);\n var combinations = new Array(options.nComb);\n for (var i = 0; i < options.nComb; i++) {\n var tmp = new Array(spectra[0].length).fill(0);\n var weight = new Array(spectra.length);\n for(var j = 0; j < spectra.length; j++) {\n weight[j] = Math.random();\n if (Math.random() > options.threshold) {\n for (var k = 0; k < spectra[0].length; k++) {\n tmp[k] += spectra[j][k]*weight[j];\n }\n } else weight[j] = 0;\n }\n weights[i] = weight;\n combinations[i] = tmp;\n }\n return {weights: weights, combinations: combinations};\n}",
"function generateNSpheres(N, R) {\n\n var r_margin= R * 1.2\n var D = 2 * R ;\n var d_margin = 2 * R * 1.5 ; // 50% margin between 2 objects\n var elem_on_one_line = parseInt(1 / d_margin);\n var maxIndex = elem_on_one_line ** 2;\n const spheres = new Array();\n\n if (maxIndex < N) {\n throw new Error(\"Impossible situation, too many or too big spheres.\");\n }\n\n // Let's keep a bound on the computational cost of this:\n if (maxIndex > 1000000) {\n throw new Error(\"Radius is too small\");\n }\n\n occupied = [];\n // reservation of N values for N spheres\n for (var i = 0; i < N; i++) {\n occupied[i] = true;\n }\n // fill the rest of the array with false\n for (i = N; i < maxIndex; i++) {\n occupied[i] = false;\n }\n // Shuffle array so that occupied[i] = true is distributed randomly\n shuffleArray(occupied);\n var count = 0;\n for (var i = 0; i < maxIndex; i++) {\n if (occupied[i]) {\n // Random velocity. TODO: take velocity from Boltzmann distribution at set temperature!\n vx = (1 - 2 * Math.random()) * 0.3;\n vy =(1 - 2 * Math.random()) * 0.3;\n x = r_margin + d_margin * Math.floor(i / elem_on_one_line);\n y = r_margin + d_margin * (i % elem_on_one_line);\n sphere = new Sphere(R, 1, x, y, vx, vy, count);\n sphere.setStatus(STATUS_HEALTHY);\n spheres[count] = sphere;\n count++;\n }\n }\n // Setting the first sphere as infected\n spheres[N / 2].setStatus(STATUS_INFECTED)\n return spheres\n}",
"function imageGen() {\n\tfor (var i = 0; i < 4; i += 1) {\n\t\t\n\t\t//Generates values for image array\n\t\timageValues[i] = imageValue();\n\t\tconsole.log(imageValues)\n\t\t//Creates image container for new image\n\t\tvar turtleImg = $(\"<img>\");\n\n\t\t//adds turtle_image class for formating\n\t\tturtleImg.addClass(\"turtle_image\");\n\n\t\t//adds url for each individual image from url array\n\t\tturtleImg.attr(\"src\", urls[i]);\n\n\t\t//assigning each individual data attribue\n\t\tturtleImg.attr(\"data\", imageValues[i]);\n\n\t\t//adding image to container designatted for game\n\t\t$(\"#imageContainer\").append(turtleImg);\n\t}\n}",
"function generateCircles(number){\n\tfor (var i=0; i<=number;i++){\n\t\tvar circle= new CreateCircle();\n\t\tcircles.push(circle);\n\t};\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CHECKLABEL:function protoIsConst1() CHECKNEXT:frame = [] CHECKNEXT:%BB0: CHECKNEXT: %0 = AllocObjectInst 1 : number, null : null CHECKNEXT: %1 = StoreNewOwnPropertyInst 2 : number, %0 : object, "a" : string, true : boolean CHECKNEXT: %2 = ReturnInst %0 : object | function protoIsConst2() {
return {b: 3, __proto__: 10};
} | [
"function protoShorthandMix1(func) {\n var __proto__ = 42;\n return {__proto__, __proto__: {}};\n}",
"function $const(x, y) /* forall<a,b> (x : a, y : b) -> a */ {\n return x;\n}",
"function blockScopeBasicLetConstTestFunc() {\r\n let integer = 1;\r\n let string = \"2\";\r\n let object = { p1: 3, p2: 4 };\r\n const constInteger = 5;\r\n const constString = \"6\";\r\n const constObject = { cp1: { cp2: 7, cp3: 8 }, cp4: 9 };\r\n return 0;// /**bp:locals(2)**/\r\n}",
"function JSJaCPresence() {\n /**\n * @ignore\n */\n this.base = JSJaCPacket;\n this.base('presence');\n}",
"checkConstantExpression(node) {\n if (!(node.is(constantType) || node.is(arrayType) || node.is(negType) || node.is(posType))) {\n return false;\n }\n for (let [k, n] of node.getNodes()) {\n if (!this.checkConstantExpression(n)) {\n return false;\n }\n }\n return true;\n }",
"function getFakeProtoOf(func) {\n if (typeof func === 'function') {\n var shadow = getShadow(func);\n return shadow.prototype;\n } else if (typeof func === 'object' && func !== null) {\n return func.prototype;\n } else {\n return void 0;\n }\n }",
"noMoreThanOneConstructor(constructors) {\n doCheck(\n constructors.length <= 1,\n `A type declaration can define at most one constructor`\n );\n }",
"static bytes1(v) { return b(v, 1); }",
"function isConst(varDecl) {\n return Boolean(varDecl && varDecl.parent &&\n ts.isVariableDeclarationList(varDecl.parent) &&\n varDecl.parent.flags & ts.NodeFlags.Const);\n}",
"static signatureCond(from: BvmAddr): SignatureCond {\n return {\n type: 'signature',\n from,\n };\n }",
"function analyze_constant_declaration(stmt) {\n const name = constant_declaration_name(stmt);\n const value_func = analyze(constant_declaration_value(stmt));\n\n return (env, succeed, fail) => {\n value_func(env,\n (value, fail2) => {\n set_name_value(name, value, env, false);\n succeed(\"constant declared\", fail2);\n },\n fail);\n };\n\n}",
"function assert$c(value, struct) {\n const result = validate(value, struct);\n\n if (result[0]) {\n throw result[0];\n }\n}",
"serialize(obj) {\n if (!obj.constructor || typeof obj.constructor.encode !== \"function\" || !obj.constructor.$type) {\n throw new Error(\"Object \" + JSON.stringify(obj) +\n \" is not a protobuf object, and hence can't be dynamically serialized. Try passing the object to the \" +\n \"protobuf classes create function.\")\n }\n return Any.create({\n type_url: \"type.googleapis.com/\" + AnySupport.fullNameOf(obj.constructor.$type),\n value: obj.constructor.encode(obj).finish()\n });\n }",
"function validateProtocol(proto2,url2) {\n if (proto2 == \"\" && (/^disk[0-2]|disk$/.test(url2) == true || /^slot[0-1]$/.test(url2) == true || /^NVRAM$/.test(url2) == true || /^bootflash$/.test(url2) == true || /^flash[0-1]|flash$/.test(url2) == true)) {\n return 0;\n } else if (/^FTP$/i.test(proto2) == false && /^TFTP$/i.test(proto2) == false) {\n return 1;\n } else {\n return 0;\n }\n\n}",
"function isKeepAssigned(o) {\n return keepAssignedPrototype.isPrototypeOf(o);\n}",
"function constantGate (value) {\n return {\n id: nextId(),\n type: 'constant',\n inputs: Object.seal([]),\n outputs: Object.seal([pin()]),\n value: value || false\n }\n}",
"freeze() {}",
"_canSendPreEncodedFrame(packet) {\n var _a, _b, _c;\n return (!this.perMessageDeflate &&\n typeof ((_b = (_a = this.socket) === null || _a === void 0 ? void 0 : _a._sender) === null || _b === void 0 ? void 0 : _b.sendFrame) === \"function\" &&\n ((_c = packet.options) === null || _c === void 0 ? void 0 : _c.wsPreEncodedFrame) !== undefined);\n }",
"function isNonPrimitive(value) {\n return ((value !== null && typeof value === 'object') ||\n typeof value === 'function' ||\n typeof value === 'symbol');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets spinners in the mod area to 0. | function resetSpinners() {
"use strict";
document.getElementById("modScoreSpin").value = 0;
document.getElementById("modDiceSpin").value = 0;
document.getElementById("modBaseSpin").value = 0;
} | [
"idleSpin() {\n this._sectors.rotation = 0;\n this.idleSpinTween = gsap.to(this._sectors, { \n rotation: Math.PI * 2, \n repeat: -1, \n duration: 12, \n ease: 'linear', \n onUpdate: this._onRotation.bind(this)\n });\n }",
"hideSpinner() {\n this.spinnerVisible = false;\n }",
"function privateResetSongStatusSliders(){\n\t\tvar amplitude_song_sliders = document.getElementsByClassName(\"amplitude-song-slider\");\n\n\t\t/*\n\t\t\tIterate over all of the song sliders and sets them to\n\t\t\t0 essentially resetting them.\n\t\t*/\n\t\tfor( var i = 0; i < amplitude_song_sliders.length; i++ ){\n\t\t\tamplitude_song_sliders[i].value = 0;\n\t\t}\n\t}",
"function spin() {\n if (count % 100 === 0 && count !== 0) {\n spinIt.classList.add(\"spin\");\n celebrate();\n } else {\n spinIt.classList.remove(\"spin\");\n }\n}",
"reset(){\n this.setSpeed();\n this.setStartPosition();\n }",
"function resetSlider() {\n currentSlideIndex = 0\n }",
"function resetVote() {\n\tif(votedMesh!=null)\n\t{\n\t\tvotedPin.visibility = 0;\n\t}\n\tif(selectedMesh!=null)\n\t{\n\t\tselectedPin.visibility = 0;\n\t\tselectedMesh.material = plushMaterials[selectedMesh.name];\n\t}\n\tmeshName = \"\";\n\tpercentageTexts.forEach(function (item) {\n\t\titem.text = \"\";\n\t})\n\tvar reminderText = $('#reminder');\n\treminderText.hide();\n}",
"function spinSlot() {\n\t\tslot.getResults(function(output) { // callback function to retrieve data from the model\n\t\t\tslot.prependRandomSymbols(10,20,6);\n\t\t\tslot.initSlot(output);\n\t\t\tslot.animateReel();\n\t\t});\n\t}",
"resetCombo(){\n if(this.combo > 10)\n this.playFailSound();\n if(this.combo > this.maxCombo)\n this.maxCombo = this.combo;\n this.combo = 0;\n this.comboDisplay.setText(\"X\" +this.combo);\n }",
"function resetInputs()\n{\n\t$('#redSlider').slider(\"value\", 128);\n\t$('#greenSlider').slider(\"value\", 128);\n\t$('#blueSlider').slider(\"value\", 128);\n\t$('#red').val(128);\n\t$('#green').val(128);\n\t$('#blue').val(128);\n}",
"function initializeSpinnerControlForQuantity() {\n\n\tvar jQueryFloat = parseFloat(jQuery.fn.jquery); // 1.1\n\tif (jQueryFloat >= 3) {\n\n\t\t// Extend spinner.\n\t\tif (typeof $.fn.spinner === \"function\" && $.widget(\"ui.spinner\", $.ui.spinner, {\n\t\t\t\t\t\t\t\t_buttonHtml: function() {\n\n\t\t\t\t\t\treturn `\\n\\t\\t\\t\\t\\t<a class=\"ui-spinner-button ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only ui-spinner-down\" tabindex=\"-1\" role=\"button\">\\n\\t\\t\\t\\t\\t\\t<span class=\"ui-icon\"><i class=\\'fas fa-plus\\'></i></span>\\n\\t\\t\\t\\t\\t</a>\\n\\t\\t\\t\\t\\t<a class=\"ui-spinner-button ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only\" tabindex=\"-1\" role=\"button\">\\n\\t\\t\\t\\t\\t\\t<span class=\"ui-icon\"><i class=\\'fas fa-minus\\'></i></span>\\n\\t\\t\\t\\t\\t</a>\n\t\t`;\n\t\t\t\t\t}\n\t\t\t\t} ));\n\n\t}\n\n\n\tif (jQueryFloat < 3) {\n\n\t\tif ( $.isFunction( $.fn.spinner ) ) {\n\t\t$.widget( \"ui.spinner\", $.ui.spinner, {\n\t\t\t_buttonHtml: function() {\n\t\t\t\treturn `\n\t\t\t\t\t<a class=\"ui-spinner-button ui-spinner-down ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only\" tabindex=\"-1\" role=\"button\">\n\t\t\t\t\t\t<span class=\"ui-icon\"><i class='fas fa-minus'></i></span>\n\t\t\t\t\t</a>\n\t\t\t\t\t<a class=\"ui-spinner-button ui-spinner-up ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only\" tabindex=\"-1\" role=\"button\">\n\t\t\t\t\t\t<span class=\"ui-icon\"><i class='fas fa-plus'></i></span>\n\t\t\t\t\t</a>`;\n\t\t\t},\n\t\t} );\n\t}\n\n\n\n\t}\n\n\n\n\n\n// WP5.6\n//\tif (typeof $.fn.spinner === \"function\" && $.widget(\"ui.spinner\", $.ui.spinner, {\n\t// _buttonHtml: function() {\n//\t\t\t\t\t\t\t\treturn '\\n\\t\\t\\t\\t\\t<a class=\"ui-spinner-button ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only ui-spinner-down\" tabindex=\"-1\" role=\"button\">\\n\\t\\t\\t\\t\\t\\t<span class=\"ui-icon\"><i class=\\'fas fa-plus\\'></i></span>\\n\\t\\t\\t\\t\\t</a>\\n\\t\\t\\t\\t\\t<a class=\"ui-spinner-button ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only\" tabindex=\"-1\" role=\"button\">\\n\\t\\t\\t\\t\\t\\t<span class=\"ui-icon\"><i class=\\'fas fa-minus\\'></i></span>\\n\\t\\t\\t\\t\\t</a>'\n//\t\t\t\t\t\t}\n// }));\n\n\n\t// Initialze the spinner on load.\n\tinitSpinner();\n\n\t// Re-initialze the spinner on WooCommerce cart refresh.\n\t$( document.body ).on( 'updated_cart_totals', function() {\n\t\tinitSpinner();\n\t} );\n\n\t// Trigger quantity input when plus/minus buttons are clicked.\n\t(0,$)(document).on( 'click', '.ui-spinner-button', () => {\n\t\t$( '.ui-spinner-input' ).trigger( 'change' );\n\n\t} );\n}",
"reset() {\r\n\t\tthis.number = this.props.index + 1\r\n\t\tthis.counters = {\r\n\t\t\tfigure: 0\r\n\t\t}\r\n\t\t// TODO: Incorporate equation numbers.\r\n\t}",
"function toggleSpinning() {\n\t// Toggle the spinning animation\n\tif (isSpinning) {\n\t\t// Stop the arrow\n\t\tisSpinning = false;\n\t\tclearInterval(toggleSpinning.spinInt);\n\t\tspinButton.removeAttribute(\"disabled\");\n\t\tvar result = currentSlice+1;\n\t\tconsole.log(result);\n\t\tif (result == 1){\n\t\t\tthis_game.spin = result;\n\t\t} else {\n\t\t\tthis_game.spin = result;\n\t\t}\n\t\tthis_game.Determine_Route();\n\t\t$('#start_turn_button').prop('disabled', false);\n\t\t$('#spinner-button').prop('disabled', true);\n\t}\n\telse {\n\t\t// Start spinning the arrow\n\t\tisSpinning = true;\n\t\ttoggleSpinning.spinInt = setInterval(spinWheel, 1000/60);\n\t\t// Set how long the wheel will be spinning\n\t\tvar duration = Math.floor(Math.random() * 2000) + 1000;\n\t\tsetTimeout(toggleSpinning, duration);\n\t\t// Disable the spin button\n\t\tspinButton.setAttribute(\"disabled\", \"true\");\n\t}\n}",
"reset () {\n this.total = this.seconds * 1000.0;\n this._remaining = this.total;\n this._clearInterval();\n this.tick();\n }",
"function removeSpinner(){\n if(document.querySelector(\".spin\")){\n document.querySelector(\".form\").removeChild(document.querySelector(\".spin\"))\n }\n}",
"function init(){\n setupSquares();\n setupModeButtons();\n\n reset();\n}",
"function zeroMotors() {\n\tconfig.motors.forEach(function (motor) {\n\t\trawMotorValues[motor.position.key] = config.controller.ranges.throttle.min;\n\t});\n}",
"resetEverything() {\n this.resetLoader();\n this.remove(0, Infinity);\n }",
"function resetButtons() {\n hitButton.disabled = true;\n standButton.disabled = true;\n continueButton.disabled = false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge a custom breakpoint list with the default list based on unique alias values Items are added if the alias is not in the default list Items are merged with the custom override if the alias exists in the default list | function mergeByAlias(defaults, custom = []) {
const dict = {};
defaults.forEach(bp => {
dict[bp.alias] = bp;
});
// Merge custom breakpoints
custom.forEach((bp) => {
if (dict[bp.alias]) {
extendObject(dict[bp.alias], bp);
}
else {
dict[bp.alias] = bp;
}
});
return validateSuffixes(Object.keys(dict).map(k => dict[k]));
} | [
"_handleOverrideGroup(name, override, result) {\n let markerOverride = override;\n\n if (override.missing_in_dst) {\n result.push(new OverrideGroup({\n mode: 'empty'\n }));\n result.push(new OverrideGroup({\n name: name,\n mode: 'new'\n }));\n } else if (override.missing_in_src) {\n result.push(new OverrideGroup({\n name: name\n }));\n result.push(new OverrideGroup({\n name: name,\n mode: 'removed'\n }));\n } else {\n // for this case we are only adding a header on each side\n // so do not show an override marker for this\n markerOverride = null;\n\n result.push(new OverrideGroup({\n name: name\n }));\n result.push(new OverrideGroup({\n name: name\n }));\n }\n\n result.push(this._createOverrideMarker(markerOverride));\n }",
"function collapseAliasToUrn(alias, defaultName, defaultType, defaultParent) {\n return output_1.output(alias).apply((a) => {\n if (typeof a === \"string\") {\n return output_1.output(a);\n }\n const name = a.hasOwnProperty(\"name\") ? a.name : defaultName;\n const type = a.hasOwnProperty(\"type\") ? a.type : defaultType;\n const parent = a.hasOwnProperty(\"parent\") ? a.parent : defaultParent;\n const project = a.hasOwnProperty(\"project\") ? a.project : settings_1.getProject();\n const stack = a.hasOwnProperty(\"stack\") ? a.stack : settings_1.getStack();\n if (name === undefined) {\n throw new Error(\"No valid 'name' passed in for alias.\");\n }\n if (type === undefined) {\n throw new Error(\"No valid 'type' passed in for alias.\");\n }\n return createUrn(name, type, parent, project, stack);\n });\n}",
"function override(overrides){\r\n return newElementHolderProxy(undefined,overrides)\r\n }",
"function appendNameAliases() {\n for (var i = 0; i < vm.ctrpOrg.name_aliases.length; i++) {\n vm.addedNameAliases.push({\n id: vm.ctrpOrg.name_aliases[i].id,\n name: vm.ctrpOrg.name_aliases[i].name,\n _destroy: false\n });\n }\n }",
"function setMergeLocators(targetMatch, altMatch) {\n var alternationNdx = targetMatch.alternation,\n shouldMerge = altMatch === undefined || (alternationNdx === altMatch.alternation &&\n targetMatch.locator[alternationNdx].toString().indexOf(altMatch.locator[alternationNdx]) === -1);\n if (!shouldMerge && alternationNdx > altMatch.alternation) {\n for (var i = altMatch.alternation; i < alternationNdx; i++) {\n if (targetMatch.locator[i] !== altMatch.locator[i]) {\n alternationNdx = i;\n shouldMerge = true;\n break;\n }\n }\n }\n\n if (shouldMerge) {\n targetMatch.mloc = targetMatch.mloc || {};\n var locNdx = targetMatch.locator[alternationNdx];\n if (locNdx === undefined) {\n targetMatch.alternation = undefined;\n } else {\n if (typeof locNdx === \"string\") locNdx = locNdx.split(\",\")[0];\n if (targetMatch.mloc[locNdx] === undefined) targetMatch.mloc[locNdx] = targetMatch.locator.slice();\n if (altMatch !== undefined) {\n for (var ndx in altMatch.mloc) {\n if (typeof ndx === \"string\") ndx = ndx.split(\",\")[0];\n if (targetMatch.mloc[ndx] === undefined) targetMatch.mloc[ndx] = altMatch.mloc[ndx];\n }\n targetMatch.locator[alternationNdx] = Object.keys(targetMatch.mloc).join(\",\");\n }\n return true;\n }\n }\n return false;\n }",
"function mergeItem(tmpList, body) {\n item.resetOutput();\n let output = item.getOutput();\n for (let key in tmpList.data[0].Inventory.items) {\n if (tmpList.data[0].Inventory.items.hasOwnProperty(key)) {\n if (tmpList.data[0].Inventory.items[key]._id && tmpList.data[0].Inventory.items[key]._id === body.with) {\n for (let key2 in tmpList.data[0].Inventory.items) {\n if (tmpList.data[0].Inventory.items[key2]._id && tmpList.data[0].Inventory.items[key2]._id === body.item) {\n let stackItem0 = 1;\n let stackItem1 = 1;\n if (typeof tmpList.data[0].Inventory.items[key].upd !== \"undefined\")\n stackItem0 = tmpList.data[0].Inventory.items[key].upd.StackObjectsCount;\n if (typeof tmpList.data[0].Inventory.items[key2].upd !== \"undefined\")\n stackItem1 = tmpList.data[0].Inventory.items[key2].upd.StackObjectsCount;\n\n if (stackItem0 === 1)\n Object.assign(tmpList.data[0].Inventory.items[key], {\"upd\": {\"StackObjectsCount\": 1}});\n\n tmpList.data[0].Inventory.items[key].upd.StackObjectsCount = stackItem0 + stackItem1;\n\n output.data.items.del.push({\"_id\": tmpList.data[0].Inventory.items[key2]._id});\n tmpList.data[0].Inventory.items.splice(key2, 1);\n\n profile.setCharacterData(tmpList);\n return output;\n }\n }\n }\n }\n }\n\n return \"\";\n}",
"function merge_defaults() {\n if (defaults != null) {\n for (var i in defaults) {\n if (params[i] == null) {\n if (defaults[i] == null)\n alert(\"default for \"+i+\" is null?\");\n params[i] = defaults[i];\n }\n }\n }\n return params;\n }",
"getCustomMenuItemsConfig() {\n\t\treturn {\n\t\t\tmenuPopups: [{\n\t\t\t\tid: \"com.ibm.team.workitem\", // The id of the menu popup to customize.\n\t\t\t\taddGroups: [{\n\t\t\t\t\tid: \"create-workitem-from-git-group\", // The id of the new group to add to the menu.\n\t\t\t\t\ttitle: \"Create Work Item from Git Issue\", // The display title for the new group.\n\t\t\t\t\taddAfterGroupId: \"create-workitem-group\", // The group after which the new group should be placed.\n\t\t\t\t\tcreateMenuItems: function () { // A function that returns an array of menu items to add.\n\t\t\t\t\t\t// Create the menu items from the configured work item type ids.\n\t\t\t\t\t\treturn createGitIssueMenuItems(VisibleWorkItemTypeIds.getVisibleWorkItemTypeIds());\n\t\t\t\t\t}\n\t\t\t\t}]\n\t\t\t}]\n\t\t};\n\t}",
"function add_default_price_id() {\n vm.product.item_details.forEach(function (item) {\n if (item.id) {\n for (var i = 0; i < item.prices.length; i++) {\n if (item.prices[i].is_default && item.prices[i].is_active && !item.prices[i].id) {\n item.prices[i].id = vm.price_by_location_price_map[item.id] ? vm.price_by_location_price_map[item.id] : null;\n item.prices[i].variant = vm.variant_main_value;\n }\n }\n } else {\n for (var i = 0; i < item.prices.length; i++) {\n if (item.prices[i].is_default && item.prices[i].is_active && !item.prices[i].id) {\n item.prices[i].variant = vm.variant_main_value;\n }\n }\n }\n });\n }",
"async findLaunchRegisteredApps(pattern, defaultPaths, suffixes) {\n const { stdout, } = await this.execa.command(`${this.lsRegisterCommand} | awk '$0 ~ /${pattern}${pathSuffixRe.source}?$/ { $1=\"\"; print $0 }'`, { shell: true, stdio: 'pipe' });\n const paths = [\n ...defaultPaths,\n ...stdout.split('\\n').map(l => l.trim().replace(pathSuffixRe, '')),\n ].filter(l => !!l);\n const preferred = this.getPreferredPath();\n if (preferred) {\n paths.push(preferred);\n }\n const installations = new Set();\n for (const inst of paths) {\n for (const suffix of suffixes) {\n const execPath = path_1.posix.join(inst.trim(), suffix);\n try {\n await this.fs.access(execPath);\n installations.add(execPath);\n }\n catch (e) {\n // no access => ignored\n }\n }\n }\n return installations;\n }",
"function validateSuffixes(list) {\n list.forEach((bp) => {\n if (!bp.suffix) {\n bp.suffix = camelCase(bp.alias); // create Suffix value based on alias\n bp.overlapping = !!bp.overlapping; // ensure default value\n }\n });\n return list;\n}",
"static setDebugOverrides() {\n if (!game.settings.get(this.MODULE_ID, this.SETTINGS.overrideConfigDebug)) {\n this.log(false, 'doing nothing in setDebugOverrides');\n return;\n }\n\n const debugOverrideSettings = game.settings.get(this.MODULE_ID, this.SETTINGS.debugOverrides);\n\n // set all debug values to match settings\n Object.keys(CONFIG.debug).forEach((debugKey) => {\n const relevantSetting = debugOverrideSettings[debugKey];\n\n // only override booleans to avoid conflicts with other modules\n if (relevantSetting !== undefined && typeof relevantSetting === 'boolean') {\n CONFIG.debug[debugKey] = relevantSetting;\n }\n\n this.log(false, 'setDebugOverride', debugKey, 'to', relevantSetting);\n });\n }",
"function expandAliases(unit) {\n\t\tfor (var key in unit) {\n\t\t\tvar alias = unit[key].alias, i = alias.length;\n\t\t\twhile (i--) {\n\t\t\t\tunit[alias[i]] = unit[key];\n\t\t\t}\n\t\t}\n\t}",
"function extractCustomInfluencers() {\n const allInfluencersList = $scope.ui.influencers;\n $scope.ui.customInfluencers = _.difference($scope.job.analysis_config.influencers, allInfluencersList);\n console.log('extractCustomInfluencers: ', $scope.ui.customInfluencers);\n }",
"function searchForOverrides(parent, name, children = []) {\n const childrenArr = Children.map(children, child => child)\n\n return childrenArr.reduce((override, child) => {\n const childName = child.props.name\n const isOverride = child.type == FieldPropsOverride\n const unbracked = name.replace(/ *\\[[^)]*\\] */g, '')\n if (isOverride && (childName == name || childName == unbracked)) {\n const cloned = Object.assign({}, child.props)\n delete cloned.name\n\n return cloned\n } else {\n return override\n }\n }, {})\n}",
"function mergeItems(){\n\tfor(var i = 0; i < invArray.length; i++){\n\t\tif(invArray[i].select){\n\t\t\tvar item1 = invArray[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(var i = item1.invPos + 1; i < invArray.length; i++){\n\t\tif(invArray[i].select){\n\t\t\tvar item2 = invArray[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tcombine(item1, item2);\n}",
"function populate_defaults(obj) {\n\t\tif(!(obj && obj._meta && obj._meta.defaults)) {\n\t\t\treturn;\n\t\t}\n\t\tvar defs = obj._meta.defaults;\n\t\t// FIXME: Unnecessary jquery dependency -- foreach could be implemented depency-free\n\t\t$.each(defs, function(key, value) {\n\t\t\tif(!obj[key]) {\n\t\t\t\tobj[key] = value;\n\t\t\t}\n\t\t});\n\t}",
"function appendToDef(def, entry) {\n if (!entry)\n return def;\n if (typeof entry === 'string') {\n def[entry] = false;\n return def;\n }\n if (Array.isArray(entry)) {\n const [key, ...sugs] = entry.map((s) => s.trim());\n if (!key)\n return def;\n const s = sugs.map((s) => s.trim()).filter((s) => !!s);\n def[key] = !s.length ? false : s.length === 1 ? s[0] : s;\n return def;\n }\n Object.assign(def, entry);\n return def;\n}",
"_createGridLine(name, type, override, isArray) {\n let dstValue = override.dst_value;\n let srcValue = override.src_value;\n\n if (name === 'path' && override.path_data) {\n dstValue = override.path_data.dst.names.join('/');\n srcValue = override.path_data.src.names.join('/');\n }\n\n return [\n // left side uses dst_value and the entities from the template asset\n this._createLabelGroup(name, type, dstValue, isArray, this._templateEntities),\n // right side uses src_value and the entities from the scene\n this._createLabelGroup(name, type, srcValue, isArray, this._entities),\n // marker to apply or revert override\n this._createOverrideMarker(override)\n ];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This sample demonstrates how to Creates or updates the storage domain. | async function storageDomainsCreateOrUpdate() {
const subscriptionId = "9eb689cd-7243-43b4-b6f6-5c65cb296641";
const storageDomainName = "sd-fs-HSDK-4XY4FI2IVG";
const resourceGroupName = "ResourceGroupForSDKTest";
const managerName = "hAzureSDKOperations";
const storageDomain = {
name: "sd-fs-HSDK-4XY4FI2IVG",
encryptionStatus: "Disabled",
storageAccountCredentialIds: [
"/subscriptions/9eb689cd-7243-43b4-b6f6-5c65cb296641/resourceGroups/ResourceGroupForSDKTest/providers/Microsoft.StorSimple/managers/hAzureSDKOperations/storageAccountCredentials/sacforsdktest",
],
};
const credential = new DefaultAzureCredential();
const client = new StorSimpleManagementClient(credential, subscriptionId);
const result = await client.storageDomains.beginCreateOrUpdateAndWait(
storageDomainName,
resourceGroupName,
managerName,
storageDomain
);
console.log(result);
} | [
"function setDomains( domains, callback ) {\n\tchrome.storage.sync.set( {\n\t\tdomains: domains\n\t}, callback );\n}",
"function addDomain(domain){\n\n\tdb.collection('domains').insert({\"domain\": domain, \"grade\": \"Calculating\"}, function(err, result) {});\n\n\ttestSSL(domain, 0, function(grade){\n\t\tdb.collection('domains').update({\"domain\": domain},{$set: {\"grade\": grade}}, function(err, result){});\n\t});\n}",
"function saveDomain() {\n getCurrentUrl().then(function(url){\n var domain,\n protocol,\n full;\n\n domain = TOCAT_TOOLS.getDomainFromUrl(url);\n protocol = TOCAT_TOOLS.getProtocolFromUrl(url);\n full = protocol + '://' + domain;\n\n TOCAT_TOOLS.saveDomain(full);\n });\n }",
"function createDomainObject(domainName) {\n return { name: domainName, count: 1 };\n}",
"async store ({ request, response }) {\n let {name}=request.only(['name'])\n let servicetype=await ServiceType.create({name})\n return response.status(201).json({\"msg\":\"Creado\"})\n }",
"function idbCreate_entity() {\t// name, url, position of entity \r\n\tvar request = db.setVersion('1');\r\n\trequest.onerror = function(e){log(\"Error: IndexedDB create entity\");};\r\n\trequest.onsuccess = function(e) {\r\n\t\tif (!db.objectStoreNames.contains('entity')) {\r\n\t\t\ttry {\t\t\t\t\r\n\t\t\t\tdb.createObjectStore('entity', {keyPath: 'id'});\r\n\t\t\t\tlog(\"Object store entity created\");\r\n\t\t\t} catch (err) {\t\r\n\t\t\t\tlog(\"Error: IndexedDB create entity\");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tlog(\"Object store entity already exists\");\r\n\t\t}\r\n\t}\r\n}",
"static hashDomain(domain) {\n const domainFields = [];\n for (const name in domain) {\n if (domain[name] == null) {\n continue;\n }\n const type = domainFieldTypes[name];\n (0, index_js_4.assertArgument)(type, `invalid typed-data domain key: ${JSON.stringify(name)}`, \"domain\", domain);\n domainFields.push({ name, type });\n }\n domainFields.sort((a, b) => {\n return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name);\n });\n return TypedDataEncoder.hashStruct(\"EIP712Domain\", { EIP712Domain: domainFields }, domain);\n }",
"function saveProps(domain, props, callback) {\n chrome.storage.local.get(null, function(data) {\n if (data.sites[domain]) {\n $.extend(data.sites[domain], props);\n if (props.libs && props.libs.length != 0) {\n $.extend(data.sites[domain]['libs'], props.libs);\n }\n } else {\n data.sites[domain] = props;\n }\n chrome.storage.local.set(data, function() {\n if (callback) {\n callback();\n }\n });\n });\n}",
"async function localLoad() {\r\n console.log('Load urls and domains from local storage');\r\n await chrome.storage.local.get(['urls'], function (result) {\r\n if (result.urls.length == 0)\r\n urls = [];\r\n else {\r\n urls = result.urls;\r\n }\r\n });\r\n //domains in the storage don't have class Domain, so need to be convert to class Domain\r\n await chrome.storage.local.get(['domains'], function (result) {\r\n domains = {};\r\n var domainsInStorage = result.domains;\r\n if (Object.keys(domainsInStorage).length != 0) {\r\n console.log('Load', Object.keys(domainsInStorage).length, 'domains from local storage');\r\n for (domain_name of Object.keys(domainsInStorage)) {\r\n domain = domainsInStorage[domain_name];\r\n domains[domain_name] = new Domain(domain.name, domain.visit, domain.duration, domain.date, domain.weekDay, domain.networkTraffic);\r\n }\r\n }\r\n });\r\n}",
"function createSyncDoc(service, SyncDoc) {\n service.documents\n .create({\n uniqueName: SyncDoc,\n data: {\n temperature: '0',\n humidity: '0'\n },\n ttl: 0\n })\n .then(response => {\n// console.log(response);\n console.log(\"== createSyncDoc ==\");\n });\n}",
"function setUpStorageClient(err, credentials){\n if (err) return console.log(err);\n\n storageClient = new StorageManagementClient(credentials, subscriptionId);\n //getStorageAccountsLists();\n //getStorageKeyList();\n createStorageAccount();\n //getStorageKeyList();\n}",
"function Domain(props) {\n return __assign({ Type: 'AWS::SDB::Domain' }, props);\n }",
"setStorageEntity(key, value, description = \"\", comments = \"\") {\n return spPost(Web(this, \"setStorageEntity\"), request_builders_body({\n comments,\n description,\n key,\n value,\n }));\n }",
"create(req, res) {\n Origin.create(req.body)\n .then(function (neworigin) {\n res.status(200).json(neworigin);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }",
"async function accountsCreateOrUpdateWithActiveDirectory() {\n const subscriptionId =\n process.env[\"NETAPP_SUBSCRIPTION_ID\"] || \"D633CC2E-722B-4AE1-B636-BBD9E4C60ED9\";\n const resourceGroupName = process.env[\"NETAPP_RESOURCE_GROUP\"] || \"myRG\";\n const accountName = \"account1\";\n const body = {\n activeDirectories: [\n {\n aesEncryption: true,\n dns: \"10.10.10.3, 10.10.10.4\",\n domain: \"10.10.10.3\",\n ldapOverTLS: false,\n ldapSigning: false,\n organizationalUnit: \"OU=Engineering\",\n password: \"ad_password\",\n site: \"SiteName\",\n smbServerName: \"SMBServer\",\n username: \"ad_user_name\",\n },\n ],\n location: \"eastus\",\n };\n const credential = new DefaultAzureCredential();\n const client = new NetAppManagementClient(credential, subscriptionId);\n const result = await client.accounts.beginCreateOrUpdateAndWait(\n resourceGroupName,\n accountName,\n body\n );\n console.log(result);\n}",
"async function cosmosDbDatabaseAccountCreateMin() {\n const subscriptionId = process.env[\"COSMOSDB_SUBSCRIPTION_ID\"] || \"subid\";\n const resourceGroupName = process.env[\"COSMOSDB_RESOURCE_GROUP\"] || \"rg1\";\n const accountName = \"ddb1\";\n const createUpdateParameters = {\n createMode: \"Default\",\n databaseAccountOfferType: \"Standard\",\n location: \"westus\",\n locations: [\n {\n failoverPriority: 0,\n isZoneRedundant: false,\n locationName: \"southcentralus\",\n },\n ],\n };\n const credential = new DefaultAzureCredential();\n const client = new CosmosDBManagementClient(credential, subscriptionId);\n const result = await client.databaseAccounts.beginCreateOrUpdateAndWait(\n resourceGroupName,\n accountName,\n createUpdateParameters\n );\n console.log(result);\n}",
"function askForDomain () {\n return inquirer.prompt([{\n type: 'input',\n name: 'domain',\n message: 'Enter a domain name'\n }]).then(answers => answers.domain);\n}",
"function saveSettings(newSettings) {\n if (newSettings != null) {\n ctrl.settings = angular.copy(newSettings);\n }\n\n const isNewDomain = ctrl.settings.createDate == null;\n const items = {};\n\n if (isNewDomain) {\n ctrl.settings.createDate = new Date().getTime();\n }\n\n items[ctrl.activeDomain] = ctrl.settings;\n chrome.storage.local.set(items, function () {\n // TODO: handle errors\n // If it's a new domain, reset the rules for which icon to show\n if (isNewDomain) {\n hwRules.resetRules();\n }\n });\n }",
"function createSamplePersons() {\n var personsDS = Entity.Stores.get(DemoApp.Person);\n var p1 = DemoApp.Person.create({\n id:123,\n firstName:\"Aaron\",\n lastName:\"Bourne\",\n DOB:new Date()\n });\n personsDS.add(p1);\n var serialized = p1.serialize();\n personsDS.add(DemoApp.Person.create({\n id:234,\n firstName:\"Bonnie\",\n lastName:\"Highways\"\n })\n );\n personsDS.add(DemoApp.Person.create({\n id:345,\n firstName:\"Daddy\",\n lastName:\"Peacebucks\"\n })\n );\n personsDS.add(DemoApp.Person.create({\n id:456,\n firstName:\"Cotton\",\n lastName:\"Kandi\"\n })\n );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Command to go to the first Problem | function handleGotoFirstProblem() {
run();
if (_gotoEnabled) {
$problemsPanel.find("tr:not(.inspector-section)").first().trigger("click");
}
} | [
"function toProblem() {\n location.href = './problem.html?id=' + this.id;\n }",
"function jump_if_has_one(){\n if($scope.result.datasets != null) {\n\n if($scope.result.datasets.length == 1){\n dataset1 = $scope.result.datasets[0];\n location.href = \"#/dataset/\"+dataset1.source+\"/\"+dataset1.id;\n }\n }\n }",
"click_expertTips_1stHorse(){\n this.expertTips_1stHorse.waitForExist();\n this.expertTips_1stHorse.click();\n }",
"function firstHint() {\n hintState = 1;\n divHide('wrongmsg');\n changeHint('hint_btn1','Hint #2','secondHint()');\n jumbled = capital(jumbledArr, mapArr).join(\"\");\n getEl('gamebox').innerHTML = jumbled;\n getEl('user_id').focus();\n}",
"function secondHint() {\n hintState = 2;\n divHide('wrongmsg');\n changeHint('hint_btn2','No more hints!','');\n showDiv('defbox');\n var def = getDef(answer);\n // Some definitions have usage examples, which contain\n // the actual word in it. This removes the example portion.\n var indexColon = def.indexOf(\":\");\n getEl('defbox').innerHTML = def.slice(0,indexColon);\n getEl('user_id').focus();\n}",
"function getSuggestion(program, arg) {\n let message = '';\n program\n .showSuggestionAfterError() // make sure on\n .exitOverride()\n .configureOutput({\n writeErr: (str) => { message = str; }\n });\n // Do the same setup for subcommand.\n const sub = program._findCommand('sub');\n if (sub) sub.copyInheritedSettings(program);\n\n try {\n // Passing in an array for a few of the tests.\n const args = Array.isArray(arg) ? arg : [arg];\n program.parse(args, { from: 'user' });\n } catch (err) {\n }\n\n const match = message.match(/Did you mean (one of )?(.*)\\?/);\n return match ? match[2] : null;\n}",
"function help_OnClick()\n{\n\ntry {\n\tDVDOpt.ActivateHelp();\n}\n\ncatch(e) {\n //e.description = L_ERRORHelp_TEXT;\n\t//HandleError(e);\n\treturn;\n}\n\n}",
"function elsaDialog() {\n scenarioDialog(3, \"Maybe I should give them a break…\", elsaChoice);\n}",
"function invalidCommand(cmd) {\n\t\tconsole.log('Invalid Command', cmd);\n\t\tswitch(Math.floor(Math.random() * 4) + 1) {\n\t\t\tcase 1:\n\t\t\t\toutput.before(\"I don't know the word \\\"\"+cmd+\"\\\".<br />\");\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\toutput.before(\"We're not going down that road again!<br /><br />\");\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\toutput.before(\"What a concept!<br /><br />\");\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\toutput.before(\"Sorry, my memory is poor. Please give a direction.<br /><br />\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput.before(\"I'm not sure i get it!.<br /><br />\");\n\t\t}\n\t\tscrollDown();\n\t}",
"function goToQuiz() {\n toQuiz(funcGuess)\n funcGuess = \"\"\n }",
"submitCmd(){\n this.cmdText += `> ${this.cmd}\\n`\n let parsed = this.cmd.replace(/^\\s+/, '').split(/\\s+/)\n\n if(parsed[0]){\n let query = parsed[0].toLowerCase()\n if(cmds[query]){\n cmds[query](this, parsed.slice(1), mrp, db)\n }\n else {\n this.cmdText += `Command '${query}' not found. Type 'help' for a manual.`\n }\n }\n\n this.cmd = ''\n }",
"function liriGo(appCommand, userSearch) {\n switch (appCommand) {\n\n case \"concert-this\":\n getBandsInTown(userSearch);\n break;\n\n case \"spotify-this-song\":\n getSpotify(userSearch);\n break;\n\n case \"movie-this\":\n getOMDB(userSearch);\n break;\n\n case \"do-what-it-says\":\n getRandom();\n break;\n //if no input detected return message to user\n default:\n console.log(\"please enter a commmand, example: 'concert-this', 'spotify-this-song', 'movie-this', 'do-what-it-says'\");\n }\n}",
"clickHelp() {\n return this\n .waitForElementVisible('@helpLink')\n .assert.visible('@helpLink')\n .click('@helpLink');\n }",
"experimentDetail(experiment) {\n if (app.experiments.get(experiment, 'slug')) {\n app.trigger('router:new-page', {\n page: 'experimentDetail',\n opts: {\n slug: experiment\n }\n });\n } else {\n this.redirectTo('404');\n }\n }",
"click_expertTipsTab(){\n this.expertTipsTab.waitForExist();\n this.expertTipsTab.click();\n }",
"function go() {\n const editor = document.querySelector(\"#editor\");\n const textarea = editor.querySelector(\"textarea\");\n const contextsEl = editor.querySelector(\"#contexts\");\n\n contextsEl.innerText = contexts(\n textarea.value,\n firstVisibleLineNumber(textarea)\n ).join(\"\\n\");\n}",
"function startTracker() {\n inquirer\n .prompt(questions)\n .then(function(res, err) {\n if (err) throw err;\n switch (res.what_to_do) {\n case \"View Departments\":\n viewDepartments();\n break;\n case \"View Roles\":\n viewRoles();\n break;\n case \"View All Employees\":\n viewAllEmployees();\n break;\n // case \"View Employees by Manager\":\n // viewEmployeesByManager();\n // break;\n // case \"View Employees by Department\":\n // viewEmployeesByDepartment();\n case \"Add Employee\":\n addEmployee();\n break;\n // case \"Remove an Employee\":\n // removeEmployee();\n // break;\n case \"Add a Department\":\n addDepartments();\n break;\n case \"Add a Role\":\n addRoles();\n break;\n case \"Exit\":\n connection.end();\n break;\n default:\n console.log(\"Error Occured\");\n break;\n }\n })\n .catch(function(err, res) {\n console.log(err);\n });\n}",
"function viewDepartmentBudgetGoBack() {\n inquirer\n .prompt(\n {\n name: \"choice\",\n type: \"list\",\n choices: [\"BACK\", \"MAIN\"],\n message: \"Proceed:\"\n }\n )\n .then(function(answer) {\n switch (answer.choice) {\n case \"BACK\":\n viewDepartmentBudget()\n break;\n case \"MAIN\":\n start();\n break;\n }\n })\n}",
"function checkingTeamMate() {\n if (globalURL.indexOf(\"team#t1\") > -1) {\n allTeamMates[0].scrollIntoView();\n } else if (globalURL.indexOf(\"team#t2\") > -1) {\n allTeamMates[1].scrollIntoView();\n } else if (globalURL.indexOf(\"team#t3\") > -1) {\n allTeamMates[2].scrollIntoView();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gallery Class: controls grid view and lighthouse view | function Gallery(gridContainers, lighthouseContainers, loadMoreButton) {
this.lighthouse = new LightHouse(lighthouseContainers, this.hideLighthouseImage.bind(this));
this.grid = new Grid(gridContainers, this.showLighthouseImage.bind(this));
this.loadMoreButton = loadMoreButton;
this.page = 1; // Flickr pages is 1 index (so first page is page 1)
this.photos = [];
this.queryText = '';
//attach events
// Load more images on click
this.loadMoreButton.addEventListener('click', function() {
this.loadImages(this.queryText);
}.bind(this));
} | [
"openGallery_() {\n // Build gallery div for the first time\n if (!this.gallery_) {\n this.findOrBuildGallery_();\n }\n this.lightboxCaption_.toggleOverflow(false);\n this.mutateElement(() => {\n this.container_.setAttribute('gallery-view', '');\n toggle(dev().assertElement(this.carousel_), false);\n });\n triggerAnalyticsEvent(this.element, 'thumbnailsViewToggled');\n }",
"function setGallery(){\n\t//centerGallery(\"#galleryPic_1\");\n\thoverGallery(\"#galleryLabel_1\",\"#galleryPic_1\");\n\thoverGallery(\"#galleryLabel_2\",\"#galleryPic_2\");\n\thoverGallery(\"#galleryLabel_3\",\"#galleryPic_3\");\n\thoverGallery(\"#galleryLabel_4\",\"#galleryPic_4\");\n\thoverGallery(\"#galleryLabel_5\",\"#galleryPic_5\");\n}",
"function UGGridPanel(){\n\t\n\tvar t = this, g_objThis = jQuery(this);\n\tvar g_gallery = new UniteGalleryMain(), g_objGallery, g_objWrapper, g_objPanel;\n\tvar g_functions = new UGFunctions();\n\tvar g_objGrid = new UGThumbsGrid();\n\tvar g_panelBase = new UGPanelsBase();\n\tvar g_objArrowNext, g_objArrowPrev;\n\t\n\tthis.events = {\n\t\tFINISH_MOVE: \"gridpanel_move_finish\",\t//called after close or open panel (slide finish).\n\t\tOPEN_PANEL: \"open_panel\",\t\t\t\t//called before opening the panel.\n\t\tCLOSE_PANEL: \"close_panel\"\t\t\t\t//called before closing the panel.\n\t};\n\t\n\tvar g_options = {\n\t\t\tgridpanel_vertical_scroll: true,\t\t\t//vertical or horizontal grid scroll and arrows\n\t\t\tgridpanel_grid_align: \"middle\",\t\t\t\t//top , middle , bottom, left, center, right - the align of the grid panel in the gallery \n\t\t\tgridpanel_padding_border_top: 10,\t\t //padding between the top border of the panel\n\t\t\tgridpanel_padding_border_bottom: 4,\t\t\t//padding between the bottom border of the panel\n\t\t\tgridpanel_padding_border_left: 10,\t\t\t//padding between the left border of the panel\n\t\t\tgridpanel_padding_border_right: 10,\t\t\t//padding between the right border of the panel\n\t\t\t\n\t\t\tgridpanel_arrows_skin: \"\",\t\t\t\t\t//skin of the arrows, if empty inherit from gallery skin\n\t\t\tgridpanel_arrows_align_vert: \"middle\",\t\t//borders, grid, middle - vertical align of arrows, to the top and bottom botders, to the grid, or in the middle space.\n\t\t\tgridpanel_arrows_padding_vert: 4,\t\t\t//padding between the arrows and the grid, in case of middle align, it will be minimal padding\n\t\t\tgridpanel_arrows_align_hor: \"center\",\t\t//borders, grid, center - horizontal align of arrows, to the left and right botders, to the grid, or in the center space.\n\t\t\tgridpanel_arrows_padding_hor: 10,\t\t\t//in case of horizontal type only, minimal size from the grid in case of \"borders\" and size from the grid in case of \"grid\"\n\t\t\t\n\t\t\tgridpanel_space_between_arrows: 20,\t\t\t//space between arrows on horizontal grids only\n\t\t\tgridpanel_arrows_always_on: false,\t\t\t//always show arrows even if the grid is one pane only\n\n\t\t\tgridpanel_enable_handle: true,\t\t\t\t//enable grid handle\t\t\t\n\t\t\tgridpanel_handle_align: \"top\",\t\t\t\t//top, middle, bottom , left, right, center - close handle tip align on the handle bar according panel orientation\n\t\t\tgridpanel_handle_offset: 0,\t\t\t\t\t//offset of handle bar according the valign\n\t\t\tgridpanel_handle_skin: \"\",\t\t\t\t\t//skin of the handle, if empty inherit from gallery skin\n\t\t\t\n\t\t\tgridpanel_background_color:\"\"\t\t\t\t//background color of the grid wrapper, if not set, it will be taken from the css\n\t};\n\t\n\t\n\t//default options for vertical scroll\n\tvar g_defaultsVertical = {\n\t\t\tgridpanel_grid_align: \"middle\",\t\t\t//top , middle , bottom\n\t\t\tgridpanel_padding_border_top: 2,\t\t//padding between the top border of the panel\n\t\t\tgridpanel_padding_border_bottom: 2\t\t//padding between the bottom border of the panel\n\t};\n\t\n\t//default options for horizontal type panel\n\tvar g_defaultsHorType = {\n\t\t\tgridpanel_grid_align: \"center\"\t\t\t//left, center, right\t\t\t\n\t};\n\t\n\tvar g_temp = {\n\t\tpanelType: \"grid\",\n\t\tisHorType: false,\n\t\tarrowsVisible: false,\n\t\tpanelHeight: 0,\n\t\tpanelWidth: 0,\n\t\toriginalPosX:null,\n\t\tisEventsInited: false,\n\t\tisClosed: false,\n\t\torientation: null\n\t};\n\t\n\t\n\t/**\n\t * init the grid panel\n\t */\n\tfunction initGridPanel(gallery, customOptions){\n\t\t\n\t\tg_gallery = gallery;\n\t\t\n\t\tvalidateOrientation();\n\t\t\n\t\t//set defaults and custom options\n\t\tif(customOptions && customOptions.vertical_scroll){\n\t\t\tg_options.gridpanel_vertical_scroll = customOptions.vertical_scroll;\t\t\t\n\t\t}\n\t\t\n\t\tg_options = jQuery.extend(g_options, customOptions);\n\t\t\t\t\n\t\t//set defautls for horizontal panel type\n\t\tif(g_temp.isHorType == true){\n\t\t\t\t\t\t\n\t\t\tg_options = jQuery.extend(g_options, g_defaultsHorType);\n\t\t\tg_options = jQuery.extend(g_options, customOptions);\n\t\t\t\t\t\n\t\t}else if(g_options.gridpanel_vertical_scroll == true){\n\n\t\t\t//set defaults for vertical scroll\n\t\t\tg_options = jQuery.extend(g_options, g_defaultsVertical);\n\t\t\tg_options = jQuery.extend(g_options, customOptions);\n\t\t\tg_options.grid_panes_direction = \"bottom\";\t\t\n\t\t}\n\t\t\n\t\t//set arrows skin:\n\t\tvar galleryOptions = g_gallery.getOptions();\n\t\tvar globalSkin = galleryOptions.gallery_skin;\t\t\n\t\tif(g_options.gridpanel_arrows_skin == \"\")\n\t\t\tg_options.gridpanel_arrows_skin = globalSkin;\n\t\t\n\t\t\n\t\t//get the gallery wrapper\n\t\tvar objects = gallery.getObjects();\n\t\tg_objWrapper = objects.g_objWrapper;\n\t\t\n\t\t//init the base panel object:\n\t\tg_panelBase.init(g_gallery, g_temp, t, g_options, g_objThis);\t\t\n\t}\n\t\n\t\n\t/**\n\t * validate the orientation if exists\n\t */\n\tfunction validateOrientation(){\n\t\t\n\t\tif(g_temp.orientation == null)\n\t\t\tthrow new Error(\"Wrong orientation, please set panel orientation before run\");\n\t\t\n\t}\n\t\n\t/**\n\t * run the rid panel\n\t */\n\tfunction runPanel(){\n\t\t\n\t\t//validate orientation\n\t\tvalidateOrientation();\n\t\t\n\t\tprocessOptions();\n\t\t\n\t\tg_objGrid.run();\n\t\t\n\t\tsetArrows();\n\t\tsetPanelSize();\n\t\tplaceElements();\n\t\t\n\t\tinitEvents();\n\t}\n\t\n\t\n\t/**\n\t * set html of the grid panel\n\t */\n\tfunction setHtmlPanel(){\n\t\t\n\t\t//add panel wrapper\n\t\tg_objWrapper.append(\"<div class='ug-grid-panel'></div>\");\n\t\t\n\t\tg_objPanel = g_objWrapper.children('.ug-grid-panel');\n\t\t\n\t\t//add arrows:\n\t\tif(g_temp.isHorType){\n\t\t\t\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-left-hortype ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-right-hortype ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-left-hortype\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-right-hortype\");\n\t\t}\n\t\telse if(g_options.gridpanel_vertical_scroll == false){\t\t//horizonatl arrows\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-left ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-right ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-left\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-right\");\n\t\t\t\n\t\t}else{\t\t//vertical arrows\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-up ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-down ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-up\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-down\");\n\t\t}\n\t\t\n\t\tg_panelBase.setHtml(g_objPanel);\n\t\t\n\t\t//hide the arrows\n\t\tg_objArrowPrev.fadeTo(0,0);\n\t\tg_objArrowNext.fadeTo(0,0);\n\t\t\n\t\t//init the grid panel\n\t\tg_options.parent_container = g_objPanel;\n\t\tg_gallery.initThumbsPanel(\"grid\", g_options);\n\t\t\n\t\t//get the grid object\n\t\tvar objects = g_gallery.getObjects();\n\t\tg_objGrid = objects.g_objThumbs;\n\t\t\n\t\tsetHtmlProperties();\n\t}\n\t\n\t\n\t/**\n\t * set html properties according the options\n\t */\n\tfunction setHtmlProperties(){\n\t\t\n\t\t//set panel background color\n\t\tif(g_options.gridpanel_background_color != \"\")\n\t\t\tg_objPanel.css(\"background-color\",g_options.gridpanel_background_color);\n\t}\n\t\n\t\n\t/**\n\t * process and fix certain options, avoid arrows and validate options\n\t */\n\tfunction processOptions(){\n\t\t\n\t\tif(g_options.gridpanel_grid_align == \"center\")\n\t\t\tg_options.gridpanel_grid_align = \"middle\";\n\t}\n\t\n\t\t\n\t/**\n\t * place panel with some animation\n\t */\n\tfunction placePanelAnimation(panelX, functionOnComplete){\n\t\t\t\t\t\t\n\t\tvar objCss = {left: panelX + \"px\"};\n\t\t\n\t\tg_objPanel.stop(true).animate(objCss ,{\n\t\t\tduration: 300,\n\t\t\teasing: \"easeInOutQuad\",\n\t\t\tqueue: false,\n\t\t\tcomplete: function(){\n\t\t\t\tif(functionOnComplete)\n\t\t\t\t\tfunctionOnComplete();\n\t\t\t}\n\t\t});\n\t\t\n\t}\n\t\n\t\t\n\t\n\t/**\n\t * get max height of the grid according the arrows size\n\t */\n\tfunction getGridMaxHeight(){\n\t\t\n\t\t//check space taken without arrows for one pane grids\n\t\tvar spaceTaken = g_options.gridpanel_padding_border_top + g_options.gridpanel_padding_border_bottom;\n\t\tvar maxGridHeight = g_temp.panelHeight - spaceTaken;\n\t\t\n\t\tif(g_options.gridpanel_arrows_always_on == false){\n\t\t\tvar numPanes = g_objGrid.getNumPanesEstimationByHeight(maxGridHeight);\n\t\t\tif(numPanes == 1)\n\t\t\t\treturn(maxGridHeight);\n\t\t}\n\t\t\n\t\t//count the size with arrows\n\t\tvar arrowsSize = g_functions.getElementSize(g_objArrowNext);\n\t\tvar arrowsHeight = arrowsSize.height;\n\t\t\n\t\tvar spaceTaken = arrowsHeight + g_options.gridpanel_arrows_padding_vert;\n\t\t\n\t\tif(g_options.gridpanel_vertical_scroll == true)\t//in case of 2 arrows multiply by 2\n\t\t\tspaceTaken *= 2;\n\t\t\t\t\n\t\tspaceTaken += g_options.gridpanel_padding_border_top + g_options.gridpanel_padding_border_bottom;\n\t\t\n\t\tmaxGridHeight = g_temp.panelHeight - spaceTaken;\t\t\t\n\t\t\n\t\treturn(maxGridHeight);\n\t}\n\t\n\t\n\t/**\n\t * get grid maximum width\n\t */\n\tfunction getGridMaxWidth(){\n\t\t\t\t\n\t\t//check space taken without arrows for one pane grids\n\t\tvar spaceTaken = g_options.gridpanel_padding_border_left + g_options.gridpanel_padding_border_right;\n\t\t\t\t\n\t\tvar maxGridWidth = g_temp.panelWidth - spaceTaken;\n\t\t\n\t\tif(g_options.gridpanel_arrows_always_on == false){\n\t\t\tvar numPanes = g_objGrid.getNumPanesEstimationByWidth(maxGridWidth);\n\t\t\t\t\t\t\n\t\t\tif(numPanes == 1)\n\t\t\t\treturn(maxGridWidth);\n\t\t}\n\t\t\n\t\t//count the size with arrows\n\t\tvar arrowsSize = g_functions.getElementSize(g_objArrowNext);\n\t\tvar arrowsWidth = arrowsSize.width;\n\t\t\n\t\tspaceTaken += (arrowsWidth + g_options.gridpanel_arrows_padding_hor) * 2;\n\t\t\t\t\t\t\t\t\n\t\tmaxGridWidth = g_temp.panelWidth - spaceTaken;\t\t\t\n\t\t\n\t\treturn(maxGridWidth);\n\t}\n\t\t\n\t\n\t/**\n\t * enable / disable arrows according the grid\n\t */\n\tfunction setArrows(){\n\t\t\n\t\tvar showArrows = false;\n\t\tif(g_options.gridpanel_arrows_always_on == true){\n\t\t\tshowArrows = true;\n\t\t}\n\t\telse{\n\t\t\tvar numPanes = g_objGrid.getNumPanes();\n\t\t\tif(numPanes > 1)\n\t\t\t\tshowArrows = true;\n\t\t}\n\t\t\n\t\tif(showArrows == true){\t\t//show arrows\n\t\t\t\n\t\t\tg_objArrowNext.show().fadeTo(0,1);\n\t\t\tg_objArrowPrev.show().fadeTo(0,1);\n\t\t\tg_temp.arrowsVisible = true;\n\t\t\t\n\t\t}else{\t\t//hide arrows\n\t\t\t\n\t\t\tg_objArrowNext.hide();\n\t\t\tg_objArrowPrev.hide();\n\t\t\tg_temp.arrowsVisible = false;\t\t\t\n\t\t\n\t\t}\n\t\t\n\t}\n\t\n\t\n\t/**\n\t * set panel size by the given height and grid width\n\t */\n\tfunction setPanelSize(){\n\t\tvar gridSize = g_objGrid.getSize();\n\t\t\t\t\n\t\t//set panel size\n\t\tif(g_temp.isHorType == true)\n\t\t\tg_temp.panelHeight = gridSize.height + g_options.gridpanel_padding_border_top + g_options.gridpanel_padding_border_bottom;\n\t\telse\n\t\t\tg_temp.panelWidth = gridSize.width + g_options.gridpanel_padding_border_left + g_options.gridpanel_padding_border_right;\n\t\t\n\t\tg_functions.setElementSize(g_objPanel, g_temp.panelWidth, g_temp.panelHeight);\n\t\t\n\t}\n\t\n\t\n\t/**\n\t * place the panel without animation\n\t * @param panelDest\n\t */\n\tfunction placePanelNoAnimation(panelDest){\n\t\t\n\t\tswitch(g_temp.orientation){\n\t\t\tcase \"right\":\t\t//vertical\n\t\t\tcase \"left\":\n\t\t\t\tg_functions.placeElement(g_objPanel, panelDest, null);\n\t\t\tbreak;\n\t\t}\n\t\t\n\t}\n\t\n\t\n\t\n\tfunction __________EVENTS___________(){};\n\t\n\t\n\t\n\t/**\n\t * event on panel slide finish\n\t */\n\tfunction onPanelSlideFinish(){\n\t\t\t\t\n\t\tg_objThis.trigger(t.events.FINISH_MOVE);\n\t\t\t\n\t}\n\t\n\t\n\t/**\n\t * init panel events\n\t */\n\tfunction initEvents(){\n\t\t\n\t\tif(g_temp.isEventsInited == true)\n\t\t\treturn(false);\n\t\t\n\t\tg_temp.isEventsInited = true;\n\t\t\t\t\n\t\tif(g_objArrowPrev){\n\t\t\tg_functions.addClassOnHover(g_objArrowPrev);\n\t\t\tg_objGrid.setPrevPaneButton(g_objArrowPrev);\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\tif(g_objArrowNext){\n\t\t\tg_functions.addClassOnHover(g_objArrowNext);\n\t\t\tg_objGrid.setNextPaneButton(g_objArrowNext);\t\t\t\n\t\t}\n\t\t\n\t\tg_panelBase.initEvents();\n\t\t\n\t}\n\t\n\t\n\tfunction ______PLACE_ELEMENTS___________(){};\n\t\n\t\n\t/**\n\t * get padding left of the grid\n\t */\n\tfunction getGridPaddingLeft(){\n\t\t\n\t\tvar gridPanelLeft = g_options.gridpanel_padding_border_left;\n\t\t\n\t\treturn(gridPanelLeft);\n\t}\n\t\n\t\n\t/**\n\t * place elements vertical - grid only\n\t */\n\tfunction placeElements_noarrows(){\n\t\t\n\t\t//place grid\n\t\tvar gridY = g_options.gridpanel_grid_align, gridPaddingY = 0;\n\t\t\n\t\tswitch(gridY){\n\t\t\tcase \"top\":\n\t\t\t\tgridPaddingY = g_options.gridpanel_padding_border_top;\n\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase \"bottom\":\n\t\t\t\tgridPaddingY = g_options.gridpanel_padding_border_bottom;\t\t\t\t\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tvar gridPanelLeft = getGridPaddingLeft();\n\t\t\n\t\tvar gridElement = g_objGrid.getElement();\t\t\n\t\tg_functions.placeElement(gridElement, gridPanelLeft, gridY, 0 , gridPaddingY);\n\t\t\t\t\n\t}\n\t\n\t\n\t/**\n\t * place elements vertical - with arrows\n\t */\n\tfunction placeElementsVert_arrows(){\n\t\t\n\t\t//place grid\n\t\tvar gridY, prevArrowY, nextArrowY, nextArrowPaddingY;\n\t\tvar objArrowSize = g_functions.getElementSize(g_objArrowPrev);\t\t\n\t\tvar objGridSize = g_objGrid.getSize();\t\t\n\t\t\n\t\t\n\t\tswitch(g_options.gridpanel_grid_align){\n\t\t\tdefault:\n\t\t\tcase \"top\":\n\t\t\t\tgridY = g_options.gridpanel_padding_border_top + objArrowSize.height + g_options.gridpanel_arrows_padding_vert;\n\t\t\tbreak;\n\t\t\tcase \"middle\":\n\t\t\t\tgridY = \"middle\";\n\t\t\tbreak;\n\t\t\tcase \"bottom\":\n\t\t\t\tgridY = g_temp.panelHeight - objGridSize.height - objArrowSize.height - g_options.gridpanel_padding_border_bottom - g_options.gridpanel_arrows_padding_vert;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t//place the grid\n\t\tvar gridPanelLeft = getGridPaddingLeft();\n\t\t\n\t\tvar gridElement = g_objGrid.getElement();\t\t\n\t\tg_functions.placeElement(gridElement, gridPanelLeft, gridY);\n\t\t\n\t\tvar objGridSize = g_objGrid.getSize();\t\t\n\t\t\t\t\t\t\n\t\t//place arrows\n\t\tswitch(g_options.gridpanel_arrows_align_vert){\n\t\t\tdefault:\n\t\t\tcase \"center\":\n\t\t\tcase \"middle\":\n\t\t\t\tprevArrowY = (objGridSize.top - objArrowSize.height) / 2;\n\t\t\t\tnextArrowY = objGridSize.bottom + (g_temp.panelHeight - objGridSize.bottom - objArrowSize.height) / 2;\n\t\t\t\tnextArrowPaddingY = 0;\n\t\t\tbreak;\n\t\t\tcase \"grid\":\n\t\t\t\tprevArrowY = objGridSize.top - objArrowSize.height - g_options.gridpanel_arrows_padding_vert_vert\n\t\t\t\tnextArrowY = objGridSize.bottom + g_options.gridpanel_arrows_padding_vert;\n\t\t\t\tnextArrowPaddingY = 0;\n\t\t\tbreak;\n\t\t\tcase \"border\":\n\t\t\tcase \"borders\":\n\t\t\t\tprevArrowY = g_options.gridpanel_padding_border_top;\t\t\t\t\n\t\t\t\tnextArrowY = \"bottom\"; \n\t\t\t\tnextArrowPaddingY = g_options.gridpanel_padding_border_bottom;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tg_functions.placeElement(g_objArrowPrev, \"center\", prevArrowY);\n\t\t\t\t\t\t\n\t\tg_functions.placeElement(g_objArrowNext, \"center\", nextArrowY, 0, nextArrowPaddingY);\n\t}\n\t\n\t\n\t/**\n\t * place elements vertical\n\t */\n\tfunction placeElementsVert(){\n\t\t\n\t\tif(g_temp.arrowsVisible == true)\n\t\t\tplaceElementsVert_arrows();\n\t\telse\n\t\t\tplaceElements_noarrows();\n\t}\n\t\n\t\n\t/**\n\t * place elements horizontal with arrows\n\t */\n\tfunction placeElementsHor_arrows(){\n\t\t\n\t\tvar arrowsY, prevArrowPadding, arrowsPaddingY, nextArrowPadding;\n\t\tvar objArrowSize = g_functions.getElementSize(g_objArrowPrev);\t\t\n\t\tvar objGridSize = g_objGrid.getSize();\n\t\t\n\t\t//place grid\n\t\tvar gridY = g_options.gridpanel_padding_border_top;\n\t\t\n\t\tswitch(g_options.gridpanel_grid_align){\n\t\t\tcase \"middle\":\n\t\t\t\t\n\t\t\t\tswitch(g_options.gridpanel_arrows_align_vert){\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tvar elementsHeight = objGridSize.height + g_options.gridpanel_arrows_padding_vert + objArrowSize.height;\n\t\t\t\t\t\tgridY = (g_temp.panelHeight - elementsHeight) / 2;\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"border\":\n\t\t\t\t\tcase \"borders\":\n\t\t\t\t\t\tvar remainHeight = g_temp.panelHeight - objArrowSize.height - g_options.gridpanel_padding_border_bottom;\n\t\t\t\t\t\tgridY = (remainHeight - objGridSize.height) / 2;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase \"bottom\":\n\t\t\t\tvar elementsHeight = objGridSize.height + objArrowSize.height + g_options.gridpanel_arrows_padding_vert;\n\t\t\t\tgridY = g_temp.panelHeight - elementsHeight - g_options.gridpanel_padding_border_bottom;\n\t\t\tbreak;\n\t\t}\n\t\t\t\t\n\t\tvar gridElement = g_objGrid.getElement();\t\t\n\t\tvar gridPanelLeft = getGridPaddingLeft();\n\t\t\n\t\tg_functions.placeElement(gridElement, gridPanelLeft, gridY);\n\t\t\n\t\tvar objGridSize = g_objGrid.getSize();\n\t\t\n\t\tswitch(g_options.gridpanel_arrows_align_vert){\n\t\t\tdefault:\n\t\t\tcase \"center\":\n\t\t\tcase \"middle\":\n\t\t\t\tarrowsY = objGridSize.bottom + (g_temp.panelHeight - objGridSize.bottom - objArrowSize.height) / 2;\n\t\t\t\tarrowsPaddingY = 0;\t\t\t\t\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase \"grid\":\n\t\t\t\tarrowsY = objGridSize.bottom + g_options.gridpanel_arrows_padding_vert;\n\t\t\t\tarrowsPaddingY = 0;\n\t\t\tbreak;\n\t\t\tcase \"border\":\n\t\t\tcase \"borders\":\n\t\t\t\tarrowsY = \"bottom\";\n\t\t\t\tarrowsPaddingY = g_options.gridpanel_padding_border_bottom;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tprevArrowPadding = -objArrowSize.width/2 - g_options.gridpanel_space_between_arrows / 2;\n\t\t\t\t\n\t\tg_functions.placeElement(g_objArrowPrev, \"center\", arrowsY, prevArrowPadding, arrowsPaddingY);\n\t\t\t\t\t\t\n\t\t//place next arrow\n\t\tvar nextArrowPadding = Math.abs(prevArrowPadding);\t\t//make positive\n\t\t\t\t\n\t\tg_functions.placeElement(g_objArrowNext, \"center\", arrowsY, nextArrowPadding, arrowsPaddingY);\n\t\t\t\t\t\n\t}\n\t\n\t\n\t/**\n\t * place elements horizonatal\n\t */\n\tfunction placeElementsHor(){\n\t\t\n\t\tif(g_temp.arrowsVisible == true)\n\t\t\tplaceElementsHor_arrows();\n\t\telse\n\t\t\tplaceElements_noarrows();\n\t\t\n\t}\n\t\n\t\n\t/**\n\t * place elements horizontal type with arrows\n\t */\n\tfunction placeElementsHorType_arrows(){\n\t\t\n\t\t//place grid\n\t\tvar gridX, prevArrowX, nextArrowX, arrowsY;\n\t\tvar objArrowSize = g_functions.getElementSize(g_objArrowPrev);\t\t\n\t\tvar objGridSize = g_objGrid.getSize();\n\t\t\n\t\tswitch(g_options.gridpanel_grid_align){\n\t\t\tdefault:\n\t\t\tcase \"left\":\n\t\t\t\tgridX = g_options.gridpanel_padding_border_left + g_options.gridpanel_arrows_padding_hor + objArrowSize.width;\n\t\t\tbreak;\n\t\t\tcase \"middle\":\n\t\t\tcase \"center\":\n\t\t\t\tgridX = \"center\";\n\t\t\tbreak;\n\t\t\tcase \"right\":\n\t\t\t\tgridX = g_temp.panelWidth - objGridSize.width - objArrowSize.width - g_options.gridpanel_padding_border_right - g_options.gridpanel_arrows_padding_hor;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t//place the grid\t\t\n\t\tvar gridElement = g_objGrid.getElement();\n\t\tg_functions.placeElement(gridElement, gridX, g_options.gridpanel_padding_border_top);\n\t\tobjGridSize = g_objGrid.getSize();\n\t\t\n\t\t//place arrows, count Y\n\t\tswitch(g_options.gridpanel_arrows_align_vert){\n\t\t\tdefault:\n\t\t\tcase \"center\":\n\t\t\tcase \"middle\":\n\t\t\t\tarrowsY = (objGridSize.height - objArrowSize.height) / 2 + objGridSize.top;\n\t\t\tbreak;\n\t\t\tcase \"top\":\n\t\t\t\tarrowsY = g_options.gridpanel_padding_border_top + g_options.gridpanel_arrows_padding_vert;\n\t\t\tbreak;\n\t\t\tcase \"bottom\":\n\t\t\t\tarrowsY = g_temp.panelHeight - g_options.gridpanel_padding_border_bottom - g_options.gridpanel_arrows_padding_vert - objArrowSize.height;\n\t\t\tbreak;\n\t\t}\n\t\t\t\t\n\t\t//get arrows X\n\t\tswitch(g_options.gridpanel_arrows_align_hor){\n\t\t\tdefault:\n\t\t\tcase \"borders\":\n\t\t\t\tprevArrowX = g_options.gridpanel_padding_border_left;\n\t\t\t\tnextArrowX = g_temp.panelWidth - g_options.gridpanel_padding_border_right - objArrowSize.width;\n\t\t\tbreak;\n\t\t\tcase \"grid\":\n\t\t\t\tprevArrowX = objGridSize.left - g_options.gridpanel_arrows_padding_hor - objArrowSize.width;\n\t\t\t\tnextArrowX = objGridSize.right + g_options.gridpanel_arrows_padding_hor;\n\t\t\tbreak;\n\t\t\tcase \"center\":\n\t\t\t\tprevArrowX = (objGridSize.left - objArrowSize.width) / 2;\n\t\t\t\tnextArrowX = objGridSize.right + (g_temp.panelWidth - objGridSize.right - objArrowSize.width) / 2;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tg_functions.placeElement(g_objArrowPrev, prevArrowX, arrowsY);\t\t\n\t\tg_functions.placeElement(g_objArrowNext, nextArrowX, arrowsY);\n\t}\n\t\n\t\n\t/**\n\t * place elements horizontal type without arrows\n\t */\n\tfunction placeElementHorType_noarrows(){\n\t\t\n\t\tvar gridX;\n\t\tvar objGridSize = g_objGrid.getSize();\n\t\t\n\t\tswitch(g_options.gridpanel_grid_align){\n\t\t\tdefault:\n\t\t\tcase \"left\":\n\t\t\t\tgridX = g_options.gridpanel_padding_border_left;\n\t\t\tbreak;\n\t\t\tcase \"middle\":\n\t\t\tcase \"center\":\n\t\t\t\tgridX = \"center\";\n\t\t\tbreak;\n\t\t\tcase \"right\":\n\t\t\t\tgridX = g_temp.panelWidth - objGridSize.width - g_options.gridpanel_padding_border_right;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t//place the grid\t\t\n\t\tvar gridElement = g_objGrid.getElement();\n\t\tg_functions.placeElement(gridElement, gridX, g_options.gridpanel_padding_border_top);\n\t}\n\t\n\t\n\t/**\n\t * place elements when the grid in horizontal position\n\t */\n\tfunction placeElementsHorType(){\n\t\t\n\t\tif(g_temp.arrowsVisible == true)\n\t\t\tplaceElementsHorType_arrows();\n\t\telse\n\t\t\tplaceElementHorType_noarrows();\n\t\t\n\t}\n\t\n\t\n\t/**\n\t * place the arrows\n\t */\n\tfunction placeElements(){\n\t\t\n\t\tif(g_temp.isHorType == false){\n\t\t\t\n\t\t\tif(g_options.gridpanel_vertical_scroll == true)\n\t\t\t\tplaceElementsVert();\n\t\t\telse\n\t\t\t\tplaceElementsHor();\n\t\t\t\n\t\t}else{\n\t\t\tplaceElementsHorType();\n\t\t}\n\t\t\n\t\tg_panelBase.placeElements();\n\t}\n\t\n\t\n\t/**\n\t * get panel orientation\n\t */\n\tthis.getOrientation = function(){\n\t\t\n\t\treturn(g_temp.orientation);\n\t}\n\t\n\t\n\t/**\n\t * set panel orientation (left, right, top, bottom)\n\t */\n\tthis.setOrientation = function(orientation){\n\t\t\n\t\tg_temp.orientation = orientation;\n\t\t\n\t\t//set isHorType temp variable for ease of use\n\t\tswitch(orientation){\n\t\t\tcase \"right\":\n\t\t\tcase \"left\":\n\t\t\t\tg_temp.isHorType = false;\n\t\t\tbreak;\n\t\t\tcase \"top\":\n\t\t\tcase \"bottom\":\n\t\t\t\tg_temp.isHorType = true;\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\"Wrong grid panel orientation: \" + orientation);\n\t\t\tbreak;\n\t\t}\n\t\t\n\t}\n\t\n\t/**\n\t * set panel height\n\t */\n\tthis.setHeight = function(height){\n\t\t\n\t\tif(g_temp.isHorType == true)\n\t\t\tthrow new Error(\"setHeight is not appliable to this orientatio (\"+g_temp.orientation+\"). Please use setWidth\");\t\t\n\t\t\n\t\tg_temp.panelHeight = height;\n\t\tvar gridMaxHeight = getGridMaxHeight();\n\t\t\n\t\tg_objGrid.setMaxHeight(gridMaxHeight);\n\t}\n\t\n\t\n\t/**\n\t * set panel width\n\t */\n\tthis.setWidth = function(width){\n\n\t\tif(g_temp.isHorType == false)\n\t\t\tthrow new Error(\"setWidth is not appliable to this orientatio (\"+g_temp.orientation+\"). Please use setHeight\");\t\t\n\t\t\n\t\tg_temp.panelWidth = width;\n\t\t\n\t\tvar gridMaxWidth = getGridMaxWidth();\n\t\t\t\t\n\t\tg_objGrid.setMaxWidth(gridMaxWidth);\n\t}\n\t\n\t\n\t/**\n\t * init the panel\n\t */\n\tthis.init = function(gallery, customOptions){\n\t\t\n\t\tinitGridPanel(gallery, customOptions);\n\t}\n\t\n\t/**\n\t * place panel html\n\t */\n\tthis.setHtml = function(){\n\t\tsetHtmlPanel();\n\t}\n\t\n\t\n\t/**\n\t * run the panel\n\t */\n\tthis.run = function(){\n\t\t\n\t\trunPanel();\n\t}\n\t\n\t\n\t/**\n\t * get the panel element\n\t */\n\tthis.getElement = function(){\n\t\treturn(g_objPanel);\n\t}\n\t\n\t\n\t/**\n\t * get panel size object\n\t */\n\tthis.getSize = function(){\n\t\t\n\t\tvar objSize = g_functions.getElementSize(g_objPanel);\n\t\t\n\t\treturn(objSize);\n\t}\n\t\n\tthis.__________Functions_From_Base_____ = function() {}\n\t\n\t/**\n\t * tells if the panel is closed\n\t */\n\tthis.isPanelClosed = function() {\t\t\n\t\treturn (g_panelBase.isPanelClosed());\n\t}\n\n\t/**\n\t * get closed panel destanation\n\t */\n\tthis.getClosedPanelDest = function() {\n\t\treturn g_panelBase.getClosedPanelDest();\n\t}\t\n\t\t\n\t/**\n\t * open the panel\n\t */\t\n\tthis.openPanel = function(noAnimation) {\n\t\tg_panelBase.openPanel(noAnimation);\n\t}\n\t\n\t\n\t/**\n\t * close the panel (slide in)\n\t */\n\tthis.closePanel = function(noAnimation) {\n\t\tg_panelBase.closePanel(noAnimation);\t\t\n\t}\t\n\t\n\t/**\n\t * set the panel opened state\n\t */\n\tthis.setOpenedState = function(originalPos) {\n\t\tg_panelBase.setOpenedState(originalPos);\n\t}\n\n\t/**\n\t * set the panel that it's in closed state, and set original pos for opening later\n\t */\n\tthis.setClosedState = function(originalPos) {\n\t\tg_panelBase.setClosedState(originalPos);\t\n\t}\n\t\n\t\n\t/**\n\t * set panel disabled at start\n\t */\n\tthis.setDisabledAtStart = function(timeout){\n\t\t\n\t\tg_panelBase.setDisabledAtStart(timeout);\n\t\t\n\t}\n\t\n\t\n}",
"function buildGallery() {\n console.log('build gallery');\n}",
"function renderGallery() {\n var imgs = getImgs()\n var strHtmls = imgs.map(img => {\n return `<img onclick=\"onImageClick(this)\" id=\"${img.id}\" src=\"${img.url}\" alt=\"${img.keywords}\"> `\n })\n document.querySelector('.gallery-container').innerHTML = strHtmls.join('')\n}",
"function loadThumbnails()\r\n\t{\r\n\t\tvar gallery_id = $(\"#gallery_id\").val();\r\n\t\tjRpc.send(handleThumbnails, {plugin: plugin, method: 'loadThumbnails', params: {gallery_id: gallery_id}});\r\n\t}",
"function displayMusicLightbox(e) {\r\n $(e).click((event)=>{\r\n let albumIndex = $(event.target).attr('data-index');\r\n let index = parseInt(albumIndex, 10);\r\n let musicSlides = $('.music-slides');\r\n $('#lightbox-m').show();\r\n musicSlides.eq(index).show(); \r\n });\r\n}",
"function loadGallery(arr, str_title, str_parent){\n\t//remove existing if one exists\n\tunloadGallery(str_parent);\n\t//make actual parent container\n\tvar _parent = document.createElement(\"div\");\n\t_parent.id = str_parent;\n\t_parent.className = \"photomenuThumbs\";//\"photomenu\";\n\tdocument.body.appendChild(_parent);\n\t\n\t//make title element and place into parent\n\tvar _title = document.createElement(\"div\");\n\t_title.innerHTML = str_title;\n\t_title.id = \"div_title_\" + str_parent;\n\t_title.className = \"photomenuTitle\";\n\t//append\n\t//var _parent = document.getElementById(str_parent);\n\t_parent.appendChild(_title);\n\t\n\t//make next/prev scroll buttons\n\tvar _nextBtn = document.createElement(\"div\");\n\tvar _prevBtn = document.createElement(\"div\");\n\t_nextBtn.innerHTML = \"...show more >\";\n\t_prevBtn.innerHTML = \"< show less...\";\n\t_nextBtn.id = str_parent + \"_nextButton\";\n\t_prevBtn.id = str_parent + \"_prevButton\";\n\t_nextBtn.className = \"photomenuNext\";\n\t_prevBtn.className = \"photomenuPrev\";\n\t_parent.appendChild(_nextBtn);\n\t_parent.appendChild(_prevBtn);\n\t\n\t_nextBtn.addEventListener(\"mousedown\", event_ShowMore);\n\t_prevBtn.addEventListener(\"mousedown\", event_ShowLess);\n\t\n\t//make \"close this\" button\n\tvar _closeBtn = document.createElement(\"div\");\n\t_closeBtn.innerHTML = \"close this\";\n\t_closeBtn.id = str_parent + \"_closeBtn\";\n\t_closeBtn.className = \"photomenuClose\";\n\t_parent.appendChild(_closeBtn);\n\t\n\t_closeBtn.addEventListener(\"mousedown\", function(){\n\t\tunloadGallery(str_parent);\n\t});\n\t\n\tfor(var i = 0; i<arr.length; ++i){\n\t\t//\n\t\tvar _description = arr[i][0];\n\t\tvar _pathToImage = arr[i][1];\n\t\tvar _pathToThumbnail = arr[i][2];\n\t\t//String(i) is optional description\n\t\tloadImage(str_parent, _pathToThumbnail, String(i), _pathToImage, _description, i, arr);\n\t}\n\t\n}",
"function GalleryBottomManage() {\r\n\r\n switch( G.galleryDisplayMode.Get() ) {\r\n case 'PAGINATION':\r\n if( G.layout.support.rows && G.galleryMaxRows.Get() > 0 ) {\r\n ManagePagination( G.GOM.albumIdx );\r\n }\r\n break;\r\n case 'MOREBUTTON':\r\n G.$E.conTnBottom.off('click');\r\n var nb=G.GOM.items.length-G.GOM.itemsDisplayed;\r\n if( nb == 0 ) {\r\n G.$E.conTnBottom.empty();\r\n }\r\n else {\r\n G.$E.conTnBottom.html('<div class=\"nGY2GalleryMoreButton\"><div class=\"nGY2GalleryMoreButtonAnnotation\">+'+nb+' ' + G.O.icons.galleryMoreButton +'</div></div>');\r\n G.$E.conTnBottom.on('click', function(e) {\r\n G.GOM.displayedMoreSteps++;\r\n GalleryResize();\r\n });\r\n }\r\n break;\r\n case 'FULLCONTENT':\r\n default:\r\n break;\r\n }\r\n }",
"function UG_API(gallery){\n\t\n\tvar t = this, g_objThis = jQuery(t);\n\tvar g_gallery = new UniteGalleryMain(), g_objGallery;\n\tg_gallery = gallery;\n\tg_objGallery = jQuery(gallery);\n\t\n\t\n\t/**\n\t * get item data for output\n\t */\n\tfunction convertItemDataForOutput(item){\n\t\t\n\t\tvar output = {\n\t\t\t\tindex: item.index,\n\t\t\t\ttitle: item.title,\n\t\t\t\tdescription: item.description,\n\t\t\t\turlImage: item.urlImage,\n\t\t\t\turlThumb: item.urlThumb\n\t\t\t};\n\t\t\t\n\t\t\t//add aditional variables to the output\n\t\t\tvar addData = item.objThumbImage.data();\n\t\t\t\n\t\t\tfor(var key in addData){\n\t\t\t\tswitch(key){\n\t\t\t\t\tcase \"image\":\n\t\t\t\t\tcase \"description\":\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toutput[key] = addData[key];\n\t\t\t}\n\t\t\t\n\t\t\treturn(output);\n\t}\n\t\n\t\n\t/**\n\t * event handling function\n\t */\n\tthis.on = function(event, handlerFunction){\n\t\t\n\t\tswitch(event){\n\t\t\tcase \"item_change\":\n\t\t\t\t\n\t\t\t\tg_objGallery.on(g_gallery.events.ITEM_CHANGE, function(){\n\t\t\t\t\t\tvar currentItem = g_gallery.getSelectedItem();\n\t\t\t\t\t\tvar output = convertItemDataForOutput(currentItem);\n\t\t\t\t\t\thandlerFunction(output.index, output);\n\t\t\t\t});\n\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase \"resize\":\n\t\t\t\tg_objGallery.on(g_gallery.events.SIZE_CHANGE, handlerFunction);\n\t\t\tbreak;\n\t\t\tcase \"enter_fullscreen\":\n\t\t\t\tg_objGallery.on(g_gallery.events.ENTER_FULLSCREEN, handlerFunction);\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase \"exit_fullscreen\":\n\t\t\t\tg_objGallery.on(g_gallery.events.EXIT_FULLSCREEN, handlerFunction);\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase \"play\":\n\t\t\t\tg_objGallery.on(g_gallery.events.START_PLAY, handlerFunction);\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase \"stop\":\n\t\t\t\tg_objGallery.on(g_gallery.events.STOP_PLAY, handlerFunction);\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase \"pause\":\n\t\t\t\tg_objGallery.on(g_gallery.events.PAUSE_PLAYING, handlerFunction);\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase \"continue\":\n\t\t\t\tg_objGallery.on(g_gallery.events.CONTINUE_PLAYING, handlerFunction);\t\t\t\t\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif(console)\n\t\t\t\t\tconsole.log(\"wrong api event: \" + event);\n\t\t\tbreak;\n\t\t}\n\t\t\n\t}\n\t\n\t/**\n\t * start playing \n\t */\n\tthis.play = function(){\t\t\n\t\tg_gallery.startPlayMode();\t\t\n\t}\n\t\n\t/**\n\t * stop playing\n\t */\n\tthis.stop = function(){\n\t\tg_gallery.stopPlayMode();\n\t}\n\t\n\t\n\t/**\n\t * toggle playing\n\t */\n\tthis.togglePlay = function(){\n\t\tg_gallery.togglePlayMode();\n\t}\n\t\n\t\n\t/**\n\t * enter fullscreen\n\t */\n\tthis.enterFullscreen = function(){\n\t\tg_gallery.toFullScreen();\n\t}\n\t\n\t/**\n\t * exit fullscreen\n\t */\n\tthis.exitFullscreen = function(){\n\t\tg_gallery.exitFullScreen();\n\t}\n\t\n\t/**\n\t * toggle fullscreen\n\t */\n\tthis.toggleFullscreen = function(){\n\t\t\n\t\tg_gallery.toggleFullscreen();\t\t\n\t}\n\t\n\t\n\t/**\n\t * reset zoom\n\t */\n\tthis.resetZoom = function(){\n\t\tvar objSlider = g_gallery.getObjSlider();\n\t\tif(!objSlider)\n\t\t\treturn(false);\n\t\t\n\t\tobjSlider.zoomBack();\n\t}\n\t\n\t\n\t/**\n\t * zoom in\n\t */\n\tthis.zoomIn = function(){\n\t\t\n\t\tvar objSlider = g_gallery.getObjSlider();\n\t\tif(!objSlider)\n\t\t\treturn(false);\n\t\t\n\t\tobjSlider.zoomIn();\t\t\n\t}\n\n\t/**\n\t * zoom in\n\t */\n\tthis.zoomOut = function(){\n\t\t\n\t\tvar objSlider = g_gallery.getObjSlider();\n\t\tif(!objSlider)\n\t\t\treturn(false);\n\t\t\n\t\tobjSlider.zoomOut();\t\t\n\t}\n\t\n\t/**\n\t * next item\n\t */\n\tthis.nextItem = function(){\n\t\tg_gallery.nextItem();\n\t}\n\t\n\t\n\t/**\n\t * prev item\n\t */\n\tthis.prevItem = function(){\n\t\tg_gallery.prevItem();\n\t}\n\t\n\t/**\n\t * go to some item by index (0-numItems)\n\t */\n\tthis.selectItem = function(numItem){\n\t\t\n\t\tg_gallery.selectItem(numItem);\n\t\n\t}\n\t\n\t\n\t/**\n\t * resize the gallery to some width (height).\n\t */\n\tthis.resize = function(width, height){\n\t\t\n\t\tif(height)\n\t\t\tg_gallery.resize(width, height);\n\t\telse\n\t\t\tg_gallery.resize(width);\n\t}\n\t\n\t\n\t/**\n\t * get some item by index\n\t */\n\tthis.getItem = function(numItem){\n\t\t\n\t\tvar data = g_gallery.getItem(numItem);\n\t\tvar output = convertItemDataForOutput(data);\n\t\t\n\t\treturn(output);\n\t}\n\t\n\t\n\t/**\n\t * get number of items in the gallery\n\t */\n\tthis.getNumItems = function(){\n\t\tvar numItems = g_gallery.getNumItems();\n\t\treturn(numItems);\n\t}\n\t\n\t\n\t\n}",
"function loadGalleries() {\n //console.log('loading galleries');\n $('#gallerySpinner').show();\n loadGalleryType('type', 0)\n loadGalleryType('specimen', 0)\n loadGalleryType('other', 0)\n loadGalleryType('uncertain',0)\n}",
"function init_galleryslider(){\n var $owl = $(\".slider-thumbnail\");\n $owl.imagesLoaded( function(){\n $owl.owlCarousel({\n autoPlay : 3000,\n slideSpeed : 600,\n stopOnHover : true,\n items : 4,\n itemsDesktop : [1199,4],\n itemsDesktopSmall : [979,3],\n itemsTablet : [600,2],\n itemsMobile : [479,1],\n navigation : true,\n navigationText : [ '<i class=\"fa fa-angle-left\"></i>', '<i class=\"fa fa-angle-right\"></i>'],\n });\n });\n}",
"function addToGallery() {\n library.forEach(book => displayBooks(book));\n updateStats();\n library.splice(0, library.length);\n form.reset();\n}",
"function slideHandler (e) {\r\n var target = $(e.target);\r\n if (target.hasClass('gallery__preview-item')) {\r\n var img = target.closest('.gallery__preview-show').find('.gallery__preview-pic');\r\n var src = target.data('src');\r\n img.attr('src', src).hide().fadeIn(200);\r\n }\r\n }",
"function displayMovieLightbox(e) { \r\n $(e).click((event)=>{\r\n let posterIndex = $(event.target).attr(\"data-index\");\r\n let index = parseInt(posterIndex, 10);\r\n let movieSlides = $('.movie-slides');\r\n $('#lightbox-b').show();\r\n movieSlides.eq(index).show();\r\n });\r\n}",
"function initGallery2( ) {\n\t\tvar galleryBtns = document.querySelector( \".gallery2-control\" ).children;\n\n\t\tfor( var i = 0; i < galleryBtns.length; i++ ) {\n\t\t\tif( galleryBtns[ i ].addEventListener ) {\n\t\t\t\tgalleryBtns[ i ].addEventListener( 'click', function( e ) {\n\t\t\t\t\tvar frame \t= new FrameRegulator( 60, 250 );\n\t\t\t\t\tvar gallery = document.getElementById( \"gallery2\" );\n\n\t\t\t\t\tvar curLeftOffset = TextUtility.removeCSSSubfix( gallery.style.left ) || 0;\n\t\t\t\t\tvar targetOffset = ( ( PolyfillUtility.srcElement( e ).id ).split( \"\" ).pop( ) - 1 ) * 0.25 * -4300;\n\n\t\t\t\t\tvar diff = Math.abs( MathUtility.getDiff( curLeftOffset, targetOffset ) );\n\t\t\t\t\tvar diffPerSecond = diff / frame.getFPS( );\n\n\t\t\t\t\tgallery.style.left = curLeftOffset + \"px\";\n\n\t\t\t\t\tvar scrollIntervalId = setInterval( function( ) {\n\t\t\t\t\t\t// ==================================\n\t\t\t\t\t\t// SCROLL GALLERY TO THE LEFT\n\t\t\t\t\t\t//\t\tDECREASE THE LEFT VALUE\n\t\t\t\t\t\t//===================================\n\t\t\t\t\t\tif( curLeftOffset > targetOffset ) {\n\t\t\t\t\t\t\tgallery.style.left = CSSUtility.decrementProp( gallery.style.left, diffPerSecond );\n\n\t\t\t\t\t\t\tvar newOffset = TextUtility.removeCSSSubfix( gallery.style.left );\n\n\t\t\t\t\t\t\tif( newOffset <= targetOffset ) {\n\t\t\t\t\t\t\t\tgallery.style.left = targetOffset + \"px\";\n\t\t\t\t\t\t\t\tclearInterval( scrollIntervalId );\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// ==================================\n\t\t\t\t\t\t\t// SCROLL GALLERY TO THE RIGHT\n\t\t\t\t\t\t\t//\t\tINCREASE THE LEFT VALUE\n\t\t\t\t\t\t\t//===================================\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tgallery.style.left = CSSUtility.incrementProp( gallery.style.left, diffPerSecond );\n\n\t\t\t\t\t\t\tvar newOffset = TextUtility.removeCSSSubfix( gallery.style.left );\n\n\t\t\t\t\t\t\tif( newOffset >= targetOffset ) {\n\t\t\t\t\t\t\t\tgallery.style.left = targetOffset + \"px\";\n\t\t\t\t\t\t\t\tclearInterval( scrollIntervalId );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\t}, frame.calcFPS( ) );\n\t\t\t\t} );\n\t\t\t} else {\n\t\t\t\tgalleryBtns[ i ].attachEvent( 'click', function( e ) {\n\t\t\t\t\tvar frame \t= new FrameRegulator( 60, 250 );\n\t\t\t\t\tvar gallery = document.getElementById( \"gallery2\" );\n\n\t\t\t\t\tvar curLeftOffset = TextUtility.removeCSSSubfix( gallery.style.left ) || 0;\n\t\t\t\t\tvar targetOffset = ( ( PolyfillUtility.srcElement( e ).id ).split( \"\" ).pop( ) - 1 ) * 0.25 * -4300;\n\n\t\t\t\t\tvar diff = Math.abs( MathUtility.getDiff( curLeftOffset, targetOffset ) );\n\t\t\t\t\tvar diffPerSecond = diff / frame.getFPS( );\n\n\t\t\t\t\tgallery.style.left = curLeftOffset + \"px\";\n\n\t\t\t\t\tvar scrollIntervalId = setInterval( function( ) {\n\t\t\t\t\t\t// ==================================\n\t\t\t\t\t\t// SCROLL GALLERY TO THE LEFT\n\t\t\t\t\t\t//\t\tDECREASE THE LEFT VALUE\n\t\t\t\t\t\t//===================================\n\t\t\t\t\t\tif( curLeftOffset > targetOffset ) {\n\t\t\t\t\t\t\tgallery.style.left = CSSUtility.decrementProp( gallery.style.left, diffPerSecond );\n\n\t\t\t\t\t\t\tvar newOffset = TextUtility.removeCSSSubfix( gallery.style.left );\n\n\t\t\t\t\t\t\tif( newOffset <= targetOffset ) {\n\t\t\t\t\t\t\t\tgallery.style.left = targetOffset + \"px\";\n\t\t\t\t\t\t\t\tclearInterval( scrollIntervalId );\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// ==================================\n\t\t\t\t\t\t\t// SCROLL GALLERY TO THE RIGHT\n\t\t\t\t\t\t\t//\t\tINCREASE THE LEFT VALUE\n\t\t\t\t\t\t\t//===================================\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tgallery.style.left = CSSUtility.incrementProp( gallery.style.left, diffPerSecond );\n\n\t\t\t\t\t\t\tvar newOffset = TextUtility.removeCSSSubfix( gallery.style.left );\n\n\t\t\t\t\t\t\tif( newOffset >= targetOffset ) {\n\t\t\t\t\t\t\t\tgallery.style.left = targetOffset + \"px\";\n\t\t\t\t\t\t\t\tclearInterval( scrollIntervalId );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\t}, frame.calcFPS( ) );\n\t\t\t\t} );\n\t\t\t}\n\t\t}\n\t}",
"initializeThumbnails_() {\n const thumbnails = [];\n this.manager_\n .getThumbnails(this.currentLightboxGroupId_)\n .forEach((thumbnail) => {\n // Don't include thumbnails for ads, this may be subject to\n // change pending user feedback or ux experiments after launch\n if (thumbnail.element.tagName == 'AMP-AD') {\n return;\n }\n const thumbnailElement = this.createThumbnailElement_(thumbnail);\n thumbnails.push(thumbnailElement);\n });\n this.mutateElement(() =>\n thumbnails.forEach((thumbnailElement) =>\n this.gallery_.appendChild(thumbnailElement)\n )\n );\n }",
"function displayOnGrid(response, append)\n{\n\t//Optional default parameter\n\tif(append === undefined) {\n\t\tappend = false;\n\t}\n\n\tvar grid = document.getElementById(\"photo_grid\");\n\t\n\tif(!append){\n\t\tgrid.innerHTML = \"\";\n\t}\n\n\tvar photo_list = response.photo;\n\tvar new_photos = [];\n\tfor(var photo_num in photo_list){\n\n\t\tvar image = document.createElement(\"IMG\");\n\t\timage.src = \"https://farm\"+photo_list[photo_num].farm+\".staticflickr.com/\"+photo_list[photo_num].server+\"/\"+photo_list[photo_num].id+\"_\"+photo_list[photo_num].secret+\"_q.jpg\";\n\t\timage.title = photo_list[photo_num].title;\n\t\t\n\t\tvar column = document.createElement(\"DIV\");\n\t\tcolumn.className = \"thumb col\";\n\t\tcolumn.appendChild(image);\n\t\t\n\t\tgrid.appendChild(column);\n\t\tnew_photos.push(column);\n\t}\n\n\t//Delay to appreciate css transition\n\twindow.setTimeout(function(){\n\t\tfor (i = 0; i < new_photos.length; i++) {\n\t\t new_photos[i].className = \"thumb col display\";\n\t\t}\n\t}, 300)\n\n\t//Add next page to button\n\tvar load_more_button = document.getElementById(\"load_more\");\n\tload_more_button.setAttribute('data-page', response.page+1);\n}",
"galleryItems() {\n return this.items.map((i) => <img key={i} src={i} alt=\"productimage+i\" id=\"responsive-gallery-image\"></img>)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shall be used to parse output of any GDB machine interpreter (GDB/MI) command. | parseMIoutput(input) { return Parser.parse(input, { startRule: 'GDBMI_OUTPUT' }); } | [
"parseMIrecord(input) { return Parser.parse(input, { startRule: 'GDBMI_RECORD' }); }",
"exec(text) {\n\t\tif (text.length === 0) return;\n\t\tthis.prog = text.split(/\\s+/).reverse();\n\t\tthis.prog = this.prog.map((el) => { return el.toLowerCase(); });\n\t\twhile (this.prog.length) {\n\t\t\tlet tok = this.next_cmd(true);\n\t\t\tthis.operate(tok);\n\t\t}\n\t\t//console.log(this.stack);\n\t}",
"parse() {\n return new ParsedCommand(this.command, this.commandList, this.callsign);\n }",
"function parserPrintStack() {\n var i;\n\n console.log(\"States: [\");\n for(i=stackTop; i>=0; i--) {\n var ln = \" \" + stateStack[i];\n if (i == stackTop) {\n ln = ln + \"<--Top Of Stack (\" + stackTop + \")\";\n }\n console.log(ln);\n }\n console.log(\"]\");\n console.log(\"Values: [\");\n for (i=stackTop; i >=0; i--) {\n var ln = \" \" + (stack[i] != null ? stack[i] : \"(null)\");\n if (i == stackTop) {\n ln = ln + \"<--Top Of Stack (\" + stackTop + \")\";\n }\n console.log(ln);\n }\n console.log(\"]\");\n }",
"function parseCommand(data) {\n for (const command in commands) {\n const commandExpr = commands[command];\n if (commandExpr.test(data)) {\n return {\n name: command,\n argument: data.match(commandExpr)[1]\n }\n }\n }\n return null;\n}",
"function command_extractor(str){\n\n//breaking down the string at each space\n arr = str.split(' ');\n let command = [],\n //defining the positions of the first and second co-ordinates\n index = arr.indexOf('through'),\n first = arr[index - 1],\n second = arr[index + 1];\n\n//pushing the command (the words before the first number) to the command array\n for( i = 0; i < arr.length; i++){\n if (!parseInt(arr[i])){\n command.push(arr[i]);\n }\n else{\n break;\n }\n }\n//re-joining the command to a string\n command = command.join('');\n//reshaping the co-ordinates string into an array of numbers; [x,y]\n first = first.split(',').map(i => +i);\n second = second.split(',').map(i => +i);\n\n return [command, first, second]; //if 'turn off 812,389 through 865,874' was given as input, it would return [ 'turnoff', [ 812, 389 ], [ 865, 874 ] ]\n}",
"function run_command_and_set_fields(cmd, fields, callback) {\r\n exec(cmd, function(error, stdout, stderr) {\r\n if (error) return callback(error);\r\n for (var key in fields) {\r\n re = stdout.match(fields[key]);\r\n if (re && re.length > 1) {\r\n output[key] = re[1];\r\n }\r\n }\r\n callback(null);\r\n });\r\n }",
"function getEggRunningInfo() {\n const { stdout } = shell.exec('ps aux | grep node', { silent: true });\n const pidList = [];\n let port;\n\n stdout.split('\\n').forEach(line => {\n if (!line.includes('node ')) {\n return;\n }\n\n const m = line.match(REGEX);\n if (!m) return;\n\n const pid = m[1];\n const cmd = m[2];\n if (cmd.includes(`\"title\":\"egg-server-${pkgInfo.name}\"`)) {\n pidList.push(pid);\n\n if (!port && PORT_REGEX.test(cmd)) {\n port = RegExp.$1;\n }\n }\n });\n\n return {\n pidList,\n port,\n };\n}",
"function runBF(command){\n switch(command){\n case '>':\n stack_pointer++\n //stack_pointer %= stack_size\n break;\n case '<':\n stack_pointer--\n //if(stack_pointer < 0) stack_pointer = stack_size-1\n break;\n case '+':\n stack[stack_pointer]++\n break;\n case '-':\n stack[stack_pointer]--\n break;\n case '.':\n character = stack[stack_pointer]\n character = String.fromCharCode(character)\n document.getElementById('output').innerHTML += character\n break;\n case ',':\n ///gahhhhh how am i going to get input?\n //**LIGHT BULB** Input stream...\n chr = document.getElementById(\"input_text\").value\n document.getElementById(\"input_text\").value = chr.substring(1)\n x = chr.charCodeAt(0)\n if(x > 0)\n stack[stack_pointer] = x\n else\n stack[stack_pointer] = 0\n break;\n case '[':\n //IF THE CURRENT BYTE = 0, find the matching ] (the opposite of what you do at '[')\n if(stack[stack_pointer] == 0)\n {\n i = debug_pos + 1\n tomatch = 1\n \n while(tomatch > 0){ \n chr = bfuck_code.substring(i,i+1)\n if(chr == '['){tomatch++}\n if(chr == ']'){tomatch--}\n i++\n }\n debug_pos = i\n }\n break;\n case ']':\n //go to the matching [\n i = debug_pos - 1\n tomatch = 1\n \n //find the matching [\n while(tomatch > 0){\n i--;\n chr = bfuck_code.substring(i,i+1)\n if(chr == '['){tomatch--}\n if(chr == ']'){tomatch++}\n }\n debug_pos = i\n break;\n default:\n break;\n }\n}",
"_parse(args) {\n const parsed = args.map(arg => {\n if (arg.includes('=')) {\n const [flag, value] = arg.split('=');\n const command = this._commandParser.getCommand(flag);\n return new Argument(command, value);\n } else {\n const command = this._commandParser.getCommand(arg);\n return new Argument(command, null);\n }\n });\n\n return parsed;\n }",
"parseReplyText(line) {\r\n const isSupported = this.hasExtension('ENHANCEDSTATUSCODES');\r\n if (isSupported) {\r\n return line.substr(4).split(/[\\s](.+)?/, 2)[1];\r\n }\r\n else {\r\n return line.substr(4);\r\n }\r\n }",
"function parseInstructions(equips, chems, rawIns){\n // Parse the Instructions in the Experiment\n let instructions = [];\n for(var i = 0; i < rawIns.length; i++){\n let ins = rawIns[i];\n let actI = ins[EXP_JSON_INS_ACTOR_INDEX];\n let recI = ins[EXP_JSON_INS_RECEIVER_INDEX];\n let act = (ins[EXP_JSON_INS_ACTOR_IS_EQUIP]) ? equips[actI] : chems[actI];\n // If the receiverID is less than 0, use a null receiver, otherwise get the correct receiver from the equipment or chemical list\n let rec = (recI < 0) ? null : ((ins[EXP_JSON_INS_RECEIVER_IS_EQUIP]) ? equips[recI] : chems[recI]);\n let func = act.idToFunc(ins[EXP_JSON_INS_FUNC_ID]);\n\n instructions.push(new InstructionController2D(new Instruction(act, rec, func)));\n }\n return instructions;\n}",
"*update(command){\n\tconsole.log('executing', command);\n\t\tvar state = yield this.command(command);\n\t\tthis.stopped(state);\n\t\t\n\t\tthis.emit('status', {debugStatus: 'getting local variables'});\n\t\tconsole.log('getting locals');\n\t\tvar localVariables = yield this.getLocals();\n\t\t\n\t\tif (localVariables && localVariables.length){\n\t\t\tyield _co(this, 'createVariables', localVariables);\n\t\t\tthis.emit('variables', this.project, localVariables);\n\t\t}\n\t\t\n\t\tthis.emit('status', {debugStatus: 'getting backtrace'});\n\t\tconsole.log('getting backtrace');\n\t\tvar frameState = yield this.command('stackListFrames');\n\t\tif (frameState && frameState.status && frameState.status.stack){\n\t\t\tlet backtrace = [];\n\t\t\tfor (let frame of frameState.status.stack){\n\t\t\t\tlet output = frame.level+': '+frame.func;\n\t\t\t\tlet location;\n\t\t\t\tif (frame.file) location = frame.file.split('/');\n\t\t\t\telse if (frame.from) location = frame.from.split('/');\n\t\t\t\tif (location && location.length) output += ': '+location[location.length-1];\n\t\t\t\tbacktrace.push(output);\n\t\t\t}\n\t\t\tthis.emit('status', {backtrace});\n\t\t}\n\t\t\n\t\tthis.emit('status', {debugBelaRunning: false, debugStatus: 'idle'});\n\t\t\n\t}",
"consoleParseMacros(input) { return Parser.parse(input, { startRule: 'MACROS' }); }",
"function parse_raw_git_log(git_raw_log) {\n var comments = [];\n if (git_raw_log == null) {\n return;\n }\n\n var arr = git_raw_log.split(rev_separator);\n arr.forEach(function(s) {\n if (s.length > 0) {\n comments.push(s);\n }\n });\n return comments;\n}",
"function parse(stack) {\n var numStack = []; // Number stack\n var opStack = []; // Operator stack\n while (stack.length > 0) {\n var val = stack.pop();\n if (isOperator(val)) {\n opStack.push(val);\n } else if (typeof val == 'number') {\n numStack.push(val);\n } else if (val == ')') {\n var b = numStack.pop();\n var a = numStack.pop();\n var op = opStack.pop();\n numStack.push(performOp(a, b, op));\n }\n }\n console.log(numStack);\n}",
"function parse() {\n var action;\n\n stackTop = 0;\n stateStack[0] = 0;\n stack[0] = null;\n lexicalToken = parserElement(true);\n state = 0;\n errorFlag = 0;\n errorCount = 0;\n\n if (isVerbose()) {\n console.log(\"Starting to parse\");\n parserPrintStack();\n }\n\n while(2 != 1) { // forever with break and return below\n action = parserAction(state, lexicalToken);\n if (action == ACCEPT) {\n if (isVerbose()) {\n console.log(\"Program Accepted\");\n }\n return 1;\n }\n\n if (action > 0) {\n if(parserShift(lexicalToken, action) == 0) {\n return 0;\n }\n lexicalToken = parserElement(false);\n if(errorFlag > 0) {\n errorFlag--; // properly recovering from error\n }\n } else if(action < 0) {\n if (parserReduce(lexicalToken, -action) == 0) {\n if(errorFlag == -1) {\n if(parserRecover() == 0) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n } else if(action == 0) {\n if (parserRecover() == 0) {\n return 0;\n }\n }\n }\n }",
"function processAgentData(msg) {\n if (obj.agentInfo == null) return;\n var i, str = msg.toString('utf8'), command = null;\n if (str[0] == '{') {\n try { command = JSON.parse(str); } catch (ex) {\n // If the command can't be parsed, ignore it.\n parent.agentStats.invalidJsonCount++;\n parent.setAgentIssue(obj, \"invalidJson (\" + str.length + \"): \" + str);\n parent.parent.debug('agent', 'Unable to parse agent JSON (' + obj.remoteaddrport + ')');\n console.log('Unable to parse agent JSON (' + obj.remoteaddrport + '): ' + str, ex);\n return;\n }\n if (typeof command != 'object') { return; }\n switch (command.action) {\n case 'msg':\n {\n // If the same console command is processed many times, kick out this agent.\n // This is a safety mesure to guard against the agent DOS'ing the server.\n if (command.type == 'console') {\n if (obj.consoleKickValue == command.value) {\n if (obj.consoleKickCount) { obj.consoleKickCount++; } else { obj.consoleKickCount = 1; }\n if (obj.consoleKickCount > 30) { obj.close(); return; } // 30 identical console messages received, kick out this agent.\n } else {\n obj.consoleKickValue = command.value;\n }\n }\n\n // Route a message\n parent.routeAgentCommand(command, obj.domain.id, obj.dbNodeKey, obj.dbMeshKey);\n break;\n }\n case 'coreinfo':\n {\n // Sent by the agent to update agent information\n ChangeAgentCoreInfo(command);\n\n if ((obj.agentCoreUpdate === true) && (obj.agentExeInfo != null) && (typeof obj.agentExeInfo.url == 'string')) {\n // Agent update. The recovery core was loaded in the agent, send a command to update the agent\n parent.parent.taskLimiter.launch(function (argument, taskid, taskLimiterQueue) { // Medium priority task\n // If agent disconnection, complete and exit now.\n if ((obj.authenticated != 2) || (obj.agentExeInfo == null)) { parent.parent.taskLimiter.completed(taskid); return; }\n\n // Agent update. The recovery core was loaded in the agent, send a command to update the agent\n obj.agentCoreUpdateTaskId = taskid;\n const url = '*' + require('url').parse(obj.agentExeInfo.url).path;\n var cmd = { action: 'agentupdate', url: url, hash: obj.agentExeInfo.hashhex };\n parent.parent.debug('agentupdate', \"Sending agent update url: \" + cmd.url);\n\n // Add the hash\n if (obj.agentExeInfo.fileHash != null) { cmd.hash = obj.agentExeInfo.fileHashHex; } else { cmd.hash = obj.agentExeInfo.hashhex; }\n\n // Add server TLS cert hash\n if (isIgnoreHashCheck() == false) {\n const tlsCertHash = parent.webCertificateFullHashs[domain.id];\n if (tlsCertHash != null) { cmd.servertlshash = Buffer.from(tlsCertHash, 'binary').toString('hex'); }\n }\n\n // Send the agent update command\n obj.send(JSON.stringify(cmd));\n }, null, 1);\n }\n break;\n }\n case 'smbios':\n {\n // SMBIOS information must never be saved when NeDB is in use. NeDB will currupt that database.\n if (db.SetSMBIOS == null) break;\n\n // See if we need to save SMBIOS information\n if (domain.smbios === true) {\n // Store the RAW SMBios table of this computer\n // Perform sanity checks before storing\n try {\n for (var i in command.value) { var k = parseInt(i); if ((k != i) || (i > 255) || (typeof command.value[i] != 'object') || (command.value[i].length == null) || (command.value[i].length > 1024) || (command.value[i].length < 0)) { delete command.value[i]; } }\n db.SetSMBIOS({ _id: obj.dbNodeKey, domain: domain.id, time: new Date(), value: command.value });\n } catch (ex) { }\n }\n\n // Event the node interface information change (This is a lot of traffic, probably don't need this).\n //parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(obj.meshid, [obj.dbNodeKey]), obj, { action: 'smBiosChange', nodeid: obj.dbNodeKey, domain: domain.id, smbios: command.value, nolog: 1 });\n\n break;\n }\n case 'netinfo':\n {\n // Check if network information is present\n if ((command.netif2 == null) && (command.netif == null)) return;\n\n // Escape any field names that have special characters\n if (command.netif2 != null) {\n for (var i in command.netif2) {\n var esc = common.escapeFieldName(i);\n if (esc !== i) { command.netif2[esc] = command.netif2[i]; delete command.netif2[i]; }\n }\n }\n\n // Sent by the agent to update agent network interface information\n delete command.action;\n command.updateTime = Date.now();\n command._id = 'if' + obj.dbNodeKey;\n command.domain = domain.id;\n command.type = 'ifinfo';\n db.Set(command);\n\n // Event the node interface information change\n parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(obj.meshid, [obj.dbNodeKey]), obj, { action: 'ifchange', nodeid: obj.dbNodeKey, domain: domain.id, nolog: 1 });\n\n break;\n }\n case 'iplocation':\n {\n // Sent by the agent to update location information\n if ((command.type == 'publicip') && (command.value != null) && (typeof command.value == 'object') && (command.value.ip) && (command.value.loc)) {\n var x = {};\n x.publicip = command.value.ip;\n x.iploc = command.value.loc + ',' + (Math.floor(Date.now() / 1000));\n ChangeAgentLocationInfo(x);\n command.value._id = 'iploc_' + command.value.ip;\n command.value.type = 'iploc';\n command.value.date = Date.now();\n db.Set(command.value); // Store the IP to location data in the database\n // Sample Value: { ip: '192.55.64.246', city: 'Hillsboro', region: 'Oregon', country: 'US', loc: '45.4443,-122.9663', org: 'AS4983 Intel Corporation', postal: '97123' }\n }\n break;\n }\n case 'mc1migration':\n {\n if (command.oldnodeid.length != 64) break;\n const oldNodeKey = 'node//' + command.oldnodeid.toLowerCase();\n db.Get(oldNodeKey, function (err, nodes) {\n if ((nodes == null) || (nodes.length != 1)) return;\n const node = nodes[0];\n if (node.meshid == obj.dbMeshKey) {\n // Update the device name & host\n const newNode = { \"name\": node.name };\n if (node.intelamt != null) { newNode.intelamt = node.intelamt; }\n ChangeAgentCoreInfo(newNode);\n\n // Delete this node including network interface information and events\n db.Remove(node._id);\n db.Remove('if' + node._id);\n\n // Event node deletion\n const change = 'Migrated device ' + node.name;\n parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(node.meshid, [obj.dbNodeKey]), obj, { etype: 'node', action: 'removenode', nodeid: node._id, msg: change, domain: node.domain });\n }\n });\n break;\n }\n case 'openUrl':\n {\n // Sent by the agent to return the status of a open URL action.\n // Nothing is done right now.\n break;\n }\n case 'log':\n {\n // Log a value in the event log\n if ((typeof command.msg == 'string') && (command.msg.length < 4096)) {\n var event = { etype: 'node', action: 'agentlog', nodeid: obj.dbNodeKey, domain: domain.id, msg: command.msg };\n if (typeof command.msgid == 'number') { event.msgid = command.msgid; }\n if (typeof command.guestname == 'string') { event.guestname = command.guestname; }\n if (Array.isArray(command.msgArgs)) { event.msgArgs = command.msgArgs; }\n if (typeof command.remoteaddr == 'string') { event.remoteaddr = command.remoteaddr; }\n var targets = parent.CreateMeshDispatchTargets(obj.dbMeshKey, [obj.dbNodeKey]);\n if (typeof command.userid == 'string') {\n var loguser = parent.users[command.userid];\n if (loguser) { event.userid = command.userid; event.username = loguser.name; targets.push(command.userid); }\n }\n if (typeof command.xuserid == 'string') {\n var xloguser = parent.users[command.xuserid];\n if (xloguser) { targets.push(command.xuserid); }\n }\n if ((typeof command.sessionid == 'string') && (command.sessionid.length < 500)) { event.sessionid = command.sessionid; }\n parent.parent.DispatchEvent(targets, obj, event);\n\n // If this is a help request, see if we need to email notify anyone\n if (event.msgid == 98) {\n // Get the node and change it if needed\n db.Get(obj.dbNodeKey, function (err, nodes) { // TODO: THIS IS A BIG RACE CONDITION HERE, WE NEED TO FIX THAT. If this call is made twice at the same time on the same device, data will be missed.\n if ((nodes == null) || (nodes.length != 1)) { delete obj.deviceChanging; return; }\n const device = nodes[0];\n if (typeof device.name == 'string') { parent.parent.NotifyUserOfDeviceHelpRequest(domain, device.meshid, device._id, device.name, command.msgArgs[0], command.msgArgs[1]); }\n });\n }\n }\n break;\n }\n case 'ping': { sendPong(); break; }\n case 'pong': { break; }\n case 'getScript':\n {\n // Used by the agent to get configuration scripts.\n if (command.type == 1) {\n parent.getCiraConfigurationScript(obj.dbMeshKey, function (script) {\n obj.send(JSON.stringify({ action: 'getScript', type: 1, script: script.toString() }));\n });\n } else if (command.type == 2) {\n parent.getCiraCleanupScript(function (script) {\n obj.send(JSON.stringify({ action: 'getScript', type: 2, script: script.toString() }));\n });\n }\n break;\n }\n case 'diagnostic':\n {\n if (typeof command.value == 'object') {\n switch (command.value.command) {\n case 'register': {\n // Only main agent can do this\n if (((obj.agentInfo.capabilities & 0x40) == 0) && (typeof command.value.value == 'string') && (command.value.value.length == 64)) {\n // Store links to diagnostic agent id\n var daNodeKey = 'node/' + domain.id + '/' + db.escapeBase64(command.value.value);\n db.Set({ _id: 'da' + daNodeKey, domain: domain.id, time: obj.connectTime, raid: obj.dbNodeKey }); // DiagnosticAgent --> Agent\n db.Set({ _id: 'ra' + obj.dbNodeKey, domain: domain.id, time: obj.connectTime, daid: daNodeKey }); // Agent --> DiagnosticAgent\n }\n break;\n }\n case 'query': {\n // Only the diagnostic agent can do\n if ((obj.agentInfo.capabilities & 0x40) != 0) {\n // Return nodeid of main agent + connection status\n db.Get('da' + obj.dbNodeKey, function (err, nodes) {\n if ((nodes != null) && (nodes.length == 1)) {\n obj.realNodeKey = nodes[0].raid;\n\n // Get agent connection state\n var agentConnected = false;\n var state = parent.parent.GetConnectivityState(obj.realNodeKey);\n if (state) { agentConnected = ((state.connectivity & 1) != 0) }\n\n obj.send(JSON.stringify({ action: 'diagnostic', value: { command: 'query', value: obj.realNodeKey, agent: agentConnected } }));\n } else {\n obj.send(JSON.stringify({ action: 'diagnostic', value: { command: 'query', value: null } }));\n }\n });\n }\n break;\n }\n case 'log': {\n if (((obj.agentInfo.capabilities & 0x40) != 0) && (typeof command.value.value == 'string') && (command.value.value.length < 256)) {\n // If this is a diagnostic agent, log the event in the log of the main agent\n var event = { etype: 'node', action: 'diagnostic', nodeid: obj.realNodeKey, snodeid: obj.dbNodeKey, domain: domain.id, msg: command.value.value };\n parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(obj.dbMeshKey, [obj.dbNodeKey]), obj, event);\n }\n break;\n }\n }\n }\n break;\n }\n case 'sysinfo': {\n if ((typeof command.data == 'object') && (typeof command.data.hash == 'string')) {\n // Validate command.data.\n if (common.validateObjectForMongo(command.data, 1024) == false) break;\n\n // Save to database\n command.data._id = 'si' + obj.dbNodeKey;\n command.data.type = 'sysinfo';\n command.data.domain = domain.id;\n command.data.time = Date.now();\n db.Set(command.data); // Update system information in the database.\n\n // Event the new sysinfo hash, this will notify everyone that the sysinfo document was changed\n var event = { etype: 'node', action: 'sysinfohash', nodeid: obj.dbNodeKey, domain: domain.id, hash: command.data.hash, nolog: 1 };\n parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(obj.dbMeshKey, [obj.dbNodeKey]), obj, event);\n }\n break;\n }\n case 'sysinfocheck': {\n // Check system information update\n db.GetHash('si' + obj.dbNodeKey, function (err, results) {\n if ((results != null) && (results.length == 1)) { obj.send(JSON.stringify({ action: 'sysinfo', hash: results[0].hash })); } else { obj.send(JSON.stringify({ action: 'sysinfo' })); }\n });\n break;\n }\n case 'sessions': {\n // This is a list of sessions provided by the agent\n if (obj.sessions == null) { obj.sessions = {}; }\n if (typeof command.value != null) {\n if (command.type == 'kvm') { obj.sessions.kvm = command.value; }\n else if (command.type == 'terminal') { obj.sessions.terminal = command.value; }\n else if (command.type == 'files') { obj.sessions.files = command.value; }\n else if (command.type == 'help') { obj.sessions.help = command.value; }\n else if (command.type == 'tcp') { obj.sessions.tcp = command.value; }\n else if (command.type == 'udp') { obj.sessions.udp = command.value; }\n else if (command.type == 'msg') { obj.sessions.msg = command.value; }\n else if (command.type == 'app') { obj.sessions.app = command.value; }\n }\n\n // Any \"help\" session must have an associated app, if not, remove it.\n if (obj.sessions.help != null) {\n for (var i in obj.sessions.help) { if (obj.sessions.help[i] == null) { delete obj.sessions.help[i]; } }\n if (Object.keys(obj.sessions.help).length == 0) { delete obj.sessions.help; }\n }\n\n // Inform everyone of updated sessions\n obj.updateSessions();\n break;\n }\n case 'battery': {\n // Device battery and power state\n if (obj.sessions == null) { obj.sessions = {}; }\n if (obj.sessions.battery == null) { obj.sessions.battery = {}; }\n if ((command.state == 'ac') || (command.state == 'dc')) { obj.sessions.battery.state = command.state; } else { delete obj.sessions.battery.state; }\n if ((typeof command.level == 'number') && (command.level >= 0) && (command.level <= 100)) { obj.sessions.battery.level = command.level; } else { delete obj.sessions.battery.level; }\n obj.updateSessions();\n break;\n }\n case 'getcoredump': {\n // Check if we requested a core dump file in the last minute, if so, ignore this.\n if ((parent.lastCoreDumpRequest != null) && ((Date.now() - parent.lastCoreDumpRequest) < 60000)) break;\n\n // Indicates if the agent has a coredump available\n if ((command.exists === true) && (typeof command.agenthashhex == 'string') && (command.agenthashhex.length == 96)) {\n // Check if we already have this exact dump file\n const coreDumpFile = parent.path.join(parent.parent.datapath, '..', 'meshcentral-coredumps', obj.agentInfo.agentId + '-' + command.agenthashhex + '-' + obj.nodeid + '.dmp');\n parent.fs.stat(coreDumpFile, function (err, stats) {\n if (stats != null) return;\n obj.coreDumpPresent = true;\n\n // Check how many files are in the coredumps folder\n const coreDumpPath = parent.path.join(parent.parent.datapath, '..', 'meshcentral-coredumps');\n parent.fs.readdir(coreDumpPath, function (err, files) {\n if ((files != null) && (files.length >= 20)) return; // Don't get more than 20 core dump files.\n\n // Get the core dump uploaded to the server.\n parent.lastCoreDumpRequest = Date.now();\n obj.RequestCoreDump(command.agenthashhex, command.corehashhex);\n });\n });\n }\n break;\n }\n case 'tunnelCloseStats': {\n // TODO: This this extra stats from the tunnel, you can merge this into the tunnel event in the database.\n //console.log(command);\n\n // Validate input\n if ((command.sent == null) || (typeof command.sent != 'string')) return;\n if ((command.sentActual == null) || (typeof command.sentActual != 'string')) return;\n if ((command.sentActual == null) || (typeof command.sentActual != 'number')) return;\n\n // Event the session closed compression data.\n var event = { etype: 'node', action: 'sessioncompression', nodeid: obj.dbNodeKey, domain: domain.id, sent: parseInt(command.sent), sentActual: parseInt(command.sentActual), msgid: 54, msgArgs: [command.sentRatio, parseInt(command.sent), parseInt(command.sentActual)], msg: 'Agent closed session with ' + command.sentRatio + '% agent to server compression. Sent: ' + command.sent + ', Compressed: ' + command.sentActual + '.' };\n parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(obj.dbMeshKey, [obj.dbNodeKey]), obj, event);\n break;\n }\n case 'lmsinfo': {\n // Agents send the LMS port bindings\n // Example: {\"action\":\"lmsinfo\",\"value\":{\"ports\":[\"623\",\"16992\"]}}\n break;\n }\n case 'plugin': {\n if ((parent.parent.pluginHandler == null) || (typeof command.plugin != 'string')) break;\n try {\n parent.parent.pluginHandler.plugins[command.plugin].serveraction(command, obj, parent);\n } catch (e) {\n parent.parent.debug('agent', 'Error loading plugin handler (' + e + ')');\n console.log('Error loading plugin handler (' + e + ')');\n }\n break;\n }\n case 'meshToolInfo': {\n // Return information about a MeshCentral tool. Current tools are 'MeshCentralRouter' and 'MeshCentralAssistant'\n // Information includes file hash and download location URL\n if (typeof command.name != 'string') break;\n var info = parent.parent.meshToolsBinaries[command.name];\n if ((command.hash != null) && (info.hash == command.hash)) return;\n\n // To build the connection URL, if we are using a sub-domain or one with a DNS, we need to craft the URL correctly.\n var xdomain = (domain.dns == null) ? domain.id : '';\n if (xdomain != '') xdomain += '/';\n\n // Build the response\n const responseCmd = { action: 'meshToolInfo', name: command.name, tag: command.tag, sessionid: command.sessionid, hash: info.hash, size: info.size, url: info.url };\n if ((command.name == 'MeshCentralAssistant') && (command.msh == true)) { responseCmd.url = '*/' + xdomain + 'meshagents?id=10006'; } // If this is Assistant and the MSH needs to be included in the executable, change the URL.\n if (command.cookie === true) { responseCmd.url += ('&auth=' + parent.parent.encodeCookie({ download: info.dlname }, parent.parent.loginCookieEncryptionKey)); }\n if (command.pipe === true) { responseCmd.pipe = true; }\n if (parent.webCertificateHashs[domain.id] != null) { responseCmd.serverhash = Buffer.from(parent.webCertificateHashs[domain.id], 'binary').toString('hex'); }\n try { ws.send(JSON.stringify(responseCmd)); } catch (ex) { }\n break;\n }\n case 'agentupdate': {\n if ((obj.agentExeInfo != null) && (typeof obj.agentExeInfo.url == 'string')) {\n var func = function agentUpdateFunc(argument, taskid, taskLimiterQueue) { // Medium priority task\n // If agent disconnection, complete and exit now.\n if (obj.authenticated != 2) { parent.parent.taskLimiter.completed(taskid); return; }\n\n // Agent is requesting an agent update\n obj.agentCoreUpdateTaskId = taskid;\n const url = '*' + require('url').parse(obj.agentExeInfo.url).path;\n var cmd = { action: 'agentupdate', url: url, hash: obj.agentExeInfo.hashhex, sessionid: agentUpdateFunc.sessionid };\n parent.parent.debug('agentupdate', \"Sending user requested agent update url: \" + cmd.url);\n\n // Add the hash\n if (obj.agentExeInfo.fileHash != null) { cmd.hash = obj.agentExeInfo.fileHashHex; } else { cmd.hash = obj.agentExeInfo.hashhex; }\n\n // Add server TLS cert hash\n if (isIgnoreHashCheck() == false) {\n const tlsCertHash = parent.webCertificateFullHashs[domain.id];\n if (tlsCertHash != null) { cmd.servertlshash = Buffer.from(tlsCertHash, 'binary').toString('hex'); }\n }\n\n // Send the agent update command\n obj.send(JSON.stringify(cmd));\n }\n func.sessionid = command.sessionid;\n\n // Agent update. The recovery core was loaded in the agent, send a command to update the agent\n parent.parent.taskLimiter.launch(func, null, 1);\n }\n break;\n }\n case 'agentupdatedownloaded': {\n if (obj.agentCoreUpdateTaskId != null) {\n // Indicate this udpate task is complete\n parent.parent.taskLimiter.completed(obj.agentCoreUpdateTaskId);\n delete obj.agentCoreUpdateTaskId;\n }\n break;\n }\n case 'errorlog': { // This is the agent error log\n if ((!Array.isArray(command.log)) || (command.log.length == 0) || (parent.parent.agentErrorLog == null)) break;\n var lastLogEntry = command.log[command.log.length - 1];\n if ((lastLogEntry != null) && (typeof lastLogEntry == 'object') && (typeof lastLogEntry.t == 'number')) {\n parent.fs.write(parent.parent.agentErrorLog, obj.dbNodeKey + ', ' + Date.now() + ', ' + str + '\\r\\n', function (err) { });\n db.Set({ _id: 'al' + obj.dbNodeKey, lastEvent: lastLogEntry.t });\n }\n break;\n }\n case '2faauth': {\n // Validate input\n if ((typeof command.url != 'string') || (typeof command.approved != 'boolean') || (command.url.startsWith('2fa://') == false)) return;\n\n // parse the URL\n var url = null;\n try { url = require('url').parse(command.url); } catch (ex) { }\n if (url == null) return;\n\n // Decode the cookie\n var urlSplit = url.query.split('&c=');\n if (urlSplit.length != 2) return;\n const authCookie = parent.parent.decodeCookie(urlSplit[1], null, 1);\n if ((authCookie == null) || (typeof authCookie.c != 'string') || (('code=' + authCookie.c) != urlSplit[0])) return;\n if ((typeof authCookie.n != 'string') || (authCookie.n != obj.dbNodeKey) || (typeof authCookie.u != 'string')) return;\n\n // Fetch the user\n const user = parent.users[authCookie.u];\n if (user == null) return;\n\n // Add this device as the authentication push notification device for this user\n if (authCookie.a == 'addAuth') {\n // Do nothing if authentication is not approved.\n // We do not want to indicate that the remote user responded to this.\n if (command.approved !== true) return;\n\n // Change the user\n user.otpdev = obj.dbNodeKey;\n parent.db.SetUser(user);\n\n // Notify change\n var targets = ['*', 'server-users', user._id];\n if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }\n var event = { etype: 'user', userid: user._id, username: user.name, account: parent.CloneSafeUser(user), action: 'accountchange', msgid: 113, msg: \"Added push notification authentication device\", domain: domain.id };\n if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.\n parent.parent.DispatchEvent(targets, obj, event);\n }\n\n // Complete 2FA checking\n if (authCookie.a == 'checkAuth') {\n if (typeof authCookie.s != 'string') return;\n // Notify 2FA response\n parent.parent.DispatchEvent(['2fadev-' + authCookie.s], obj, { etype: '2fadev', action: '2faresponse', domain: domain.id, nodeid: obj.dbNodeKey, code: authCookie.a, userid: user._id, approved: command.approved, sessionid: authCookie.s, nolog: 1 });\n }\n\n break;\n }\n case 'getUserImage': {\n // Validate input\n if (typeof command.userid != 'string') {\n // Send back the default image if required\n if ((command.default) || (command.sentDefault)) {\n try { command.image = 'data:image/png;base64,' + Buffer.from(parent.fs.readFileSync(parent.parent.path.join(__dirname, 'public', 'images', 'user-128.png')), 'binary').toString('base64'); } catch (ex) { }\n obj.send(JSON.stringify(command));\n }\n return;\n }\n var useridsplit = command.userid.split('/');\n if ((useridsplit.length != 3) || (useridsplit[1] != domain.id)) return;\n\n // Add the user's real name if present\n var u = parent.users[command.userid];\n if (u == null) return;\n if (u.name) { command.name = u.name; }\n if (u.realname) { command.realname = u.realname; }\n\n // An agent can only request images of accounts with rights to the device.\n if (parent.GetNodeRights(command.userid, obj.dbMeshKey, obj.dbNodeKey) != 0) {\n parent.db.Get('im' + command.userid, function (err, images) {\n if ((err == null) && (images != null) && (images.length == 1)) {\n // Send back the account image\n command.image = images[0].image;\n } else {\n // Send back the default image if required\n if ((command.default) || (command.sentDefault)) {\n try { command.image = 'data:image/png;base64,' + Buffer.from(parent.fs.readFileSync(parent.parent.path.join(__dirname, 'public', 'images', 'user-128.png')), 'binary').toString('base64'); } catch (ex) { }\n }\n }\n obj.send(JSON.stringify(command));\n });\n }\n break;\n }\n case 'getServerImage': {\n if (command.agent === 'assistant') {\n // Return server title and image for MeshCentral Assistant\n if ((domain.assistantcustomization != null) && (typeof domain.assistantcustomization == 'object')) {\n var ok = false;\n if (typeof domain.assistantcustomization.title == 'string') { ok = true; command.title = domain.assistantcustomization.title; }\n if (typeof domain.assistantcustomization.image == 'string') { try { command.image = 'data:image/jpeg;base64,' + Buffer.from(parent.fs.readFileSync(parent.parent.getConfigFilePath(domain.assistantcustomization.image)), 'binary').toString('base64'); ok = true; } catch (ex) { console.log(ex); } }\n if (ok) { obj.send(JSON.stringify(command)); }\n }\n }\n if (command.agent === 'android') {\n // Return server title and image for MeshCentral Assistant\n if ((domain.androidcustomization != null) && (typeof domain.androidcustomization == 'object')) {\n var ok = false;\n if (typeof domain.androidcustomization.title == 'string') { ok = true; command.title = domain.androidcustomization.title; }\n if (typeof domain.androidcustomization.subtitle == 'string') { ok = true; command.subtitle = domain.androidcustomization.subtitle; }\n if (typeof domain.androidcustomization.image == 'string') { try { command.image = 'data:image/jpeg;base64,' + Buffer.from(parent.fs.readFileSync(parent.parent.getConfigFilePath(domain.androidcustomization.image)), 'binary').toString('base64'); ok = true; } catch (ex) { console.log(ex); } }\n if (ok) { obj.send(JSON.stringify(command)); }\n }\n }\n break;\n }\n case 'guestShare': {\n if ((command.flags == null) || (command.flags == 0)) {\n // Stop any current self-share, this is allowed even if self guest sharing is not allows so to clear any old shares.\n removeGuestSharing(function () {\n delete obj.guestSharing;\n obj.send(JSON.stringify({ action: 'guestShare', flags: command.flags, url: null, viewOnly: false }));\n });\n } else {\n // Add a new self-share, this will replace any share for this device\n if ((domain.agentselfguestsharing == null) || (domain.agentselfguestsharing == false) || (typeof command.flags != 'number')) return; // Check if agent self-sharing is allowed, this is off by default.\n if ((command.flags & 2) == 0) { command.viewOnly = false; } // Only allow \"view only\" if desktop is shared.\n addGuestSharing(command.flags, command.viewOnly, function (share) {\n obj.guestSharing = true;\n obj.send(JSON.stringify({ action: 'guestShare', url: share.url, flags: share.flags, viewOnly: share.viewOnly }));\n })\n }\n break;\n }\n case 'amtconfig': {\n // Sent by the agent when the agent needs a Intel AMT APF connection to the server\n const cookie = parent.parent.encodeCookie({ a: 'apf', n: obj.dbNodeKey, m: obj.dbMeshKey }, parent.parent.loginCookieEncryptionKey);\n try { obj.send(JSON.stringify({ action: 'amtconfig', user: '**MeshAgentApfTunnel**', pass: cookie })); } catch (ex) { }\n break;\n }\n case 'script-task': {\n // These command are for running regular batch jobs on the remote device\n if (parent.parent.taskManager != null) { parent.parent.taskManager.agentAction(command, obj); }\n break;\n }\n default: {\n parent.agentStats.unknownAgentActionCount++;\n parent.parent.debug('agent', 'Unknown agent action (' + obj.remoteaddrport + '): ' + JSON.stringify(command) + '.');\n console.log('Unknown agent action (' + obj.remoteaddrport + '): ' + JSON.stringify(command) + '.');\n break;\n }\n }\n if (parent.parent.pluginHandler != null) {\n parent.parent.pluginHandler.callHook('hook_processAgentData', command, obj, parent);\n }\n }\n }",
"function exec( stack ) {\n /* \n Register declarations\n From Malbolge Specification:\n ----------------------------\n The three registers are A, C, and D. A is the accumulator, used for\n data manipulation. A is implicitly set to the value written by all\n write operations on memory. (Standard I/O, a distinctly non-chip-level\n feature, is done directly with the A register.)\n\n C is the code pointer. It is automatically incremented after each\n instruction, and points the instruction being executed.\n\n D is the data pointer. It, too, is automatically incremented after each\n instruction, but the location it points to is used for the data\n manipulation commands.\n\n All registers begin with the value 0.\n */\n var a = 0, c = 0, d = 0;\n /*\n Integer variable declaration from line 108 of original C implementation\n */\n var x;\n while(true) {\n if ( stack[ c ] < 33 || stack[ c ] > 126 ) continue;\n var instructionIndex = ( ( stack[ c ] - 33 ) + c ) % 94;\n var instruction = xlat1[ instructionIndex ];\n switch (instruction) {\n case 'j': \n d = stack[ d ]; \n break;\n case 'i': \n c = stack[ d ];\n break;\n case '*':\n a = stack[ d ] = Math.floor( stack[ d ] / 3 ) + stack[ d ] % 3 * 19683;\n break;\n case 'p': \n a = stack[ d ] = op( a, stack[ d ] );\n break;\n case '<':\n /*\n The original specification declares '>' to be the instruction,\n however, whether by design or mistake, the original specification\n uses '<'. This implementation follows the original implementation\n so that previously written programs may run under this implementation.\n\n The original implementation uses only ASCII characters\n as well as the 'putc' function macro, which wraps\n values above 255.\n */\n process.stdout.write(String.fromCharCode(a % 256));\n break;\n case '/':\n a = process.stdin.read();\n break;\n case 'v':\n return;\n }\n stack[ c ] = xlat2.charCodeAt( stack[ c ] - 33 );\n if ( c === maxStackSize - 1 ) c = 0;\n else c++;\n \n if ( d === maxStackSize - 1 ) d = 0;\n else d++;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies linear interpolation to find the correct value for traveling from value oldValue to newValue taking into account that you are (i / steps) of the way through the process | function interpolateValue(oldValue, newValue, i, steps) {
return (((steps - i) / steps) * oldValue) + ((i / steps) * newValue);
} | [
"function interpolateValues(values, getter, i, iteration) {\n if (i > 0) {\n var ta = iterations[i], tb = iterations[i - 1],\n t = (iteration - ta) / (tb - ta);\n return getter(values[i]) * (1 - t) + getter(values[i - 1]) * t;\n }\n return getter(values[i]);\n }",
"function linear_interpolate(x, x0, x1, y0, y1){\n return y0 + ((y1 - y0)*((x-x0) / (x1-x0)));\n}",
"function interpolate() {\n progress += (isZooming ? self.p.zoomDelta : self.p.dragDelta);\n progress = Math.min(progress, 1);\n\n var k = sigma.easing.quadratic.easeout(progress);\n var oldRatio = self.ratio;\n\n self.ratio = oldRatio * (1 - k) + targetRatio * k;\n\n if (isZooming) {\n self.stageX = targetStageX +\n (self.stageX - targetStageX) *\n self.ratio /\n oldRatio;\n\n self.stageY = targetStageY +\n (self.stageY - targetStageY) *\n self.ratio /\n oldRatio;\n } else {\n self.stageX = oldStageX * (1 - k) + targetStageX * k;\n self.stageY = oldStageY * (1 - k) + targetStageY * k;\n }\n\n self.dispatch('interpolate');\n if (progress >= 1) {\n window.clearInterval(self.interpolationID);\n stopInterpolate();\n }\n }",
"static LerpToRef(startValue, endValue, gradient, result) {\n for (let index = 0; index < 16; index++) {\n result._m[index] =\n startValue._m[index] * (1.0 - gradient) + endValue._m[index] * gradient;\n }\n result._markAsUpdated();\n }",
"function interpolate(pBegin, pEnd, pStep, pMax) {\n if (pBegin < pEnd) {\n return ((pEnd - pBegin) * (pStep / pMax)) + pBegin;\n } else {\n return ((pBegin - pEnd) * (1 - (pStep / pMax))) + pEnd;\n }\n}",
"static LerpToRef(start, end, amount, result) {\n result.x = start.x + (end.x - start.x) * amount;\n result.y = start.y + (end.y - start.y) * amount;\n result.z = start.z + (end.z - start.z) * amount;\n }",
"static Lerp(startValue, endValue, gradient) {\n const result = new Matrix();\n Matrix.LerpToRef(startValue, endValue, gradient, result);\n return result;\n }",
"setInterpolatedDistance(valA, valB, t) {\n this.cam.state.distance = Scalar.mix(valA, valB, Scalar.smoothstep(t));\n }",
"function slider_equation(val)\n{\n return (4.5 * Math.pow(val,2) - (0.75 * val) + 0.25);\n}",
"interpolateY(x) { // input x (real-number)\n var index = this.bisection(x);\n \n if(this.arySrcX[index] === x)\n return this.arySrcY[index];\n else\n return this.doCubicSpline(x, index);\n }",
"function sliderMove()\r\n{\r\n var offset = 0\r\n for (var t = 0; t < sliders.length; t++)\r\n {\r\n var slid = map(sin(angle+offset), -1, 1, 0, 255)\r\n sliders[t].value(slid)\r\n offset += vTest;\r\n } \r\n}",
"function interpolate(x, xl, xh, yl, yh) {\n var r = 0;\n if ( x >= xh ) {\n r = yh;\n } else if ( x <= xl ) {\n r = yl;\n } else if ( (xh - xl) < 1.0E-8 ) {\n r = yl+(yh-yl)*((x-xl)/1.0E-8);\n } else {\n r = yl+(yh-yl)*((x-xl)/(xh-xl));\n }\n return r;\n }",
"_updateHandleAndProgress(newValue) {\n const max = this._effectiveMax;\n const min = this._effectiveMin;\n\n // The progress (completed) percentage of the slider.\n this._progressPercentage = (newValue - min) / (max - min);\n // How many pixels from the left end of the slider will be the placed the affected by the user action handle\n this._handlePositionFromStart = this._progressPercentage * 100;\n }",
"function linearStepwise(t0, v0, t1, v1, dt, t) {\n\t/*\n\t * perform the calculation according to formula\n\t * t - t0\n\t * dt ______\n\t * dt\n\t * v = v0 + (v1 - v0) ___________\n\t * t1 - t0\n\t *\n\t */\n\treturn v0 + Math.floor((v1 - v0) * Math.floor((t - t0) / dt) * dt / (t1 - t0));\n}",
"function lerp(x1,y1,x2,y2,y3) {\n\treturn ((y2-y3) * x1 + (y3-y1) * x2)/(y2-y1);\n}",
"function updateValue(val, id) {\n var value = validate();\n if (id == \"slope_text\") {\n if(value != INVALID_VALUE) {\n document.getElementById('slope_slider').value = parseFloat(value);\n }\n } else if (id == 'slope_slider') {\n findSmallestFraction(val);\n }\n\n if(value != INVALID_VALUE) {\n turnSatellite(value);\n }\n }",
"function tweenIteration() {\n var iteration = d3.interpolateNumber(+label.text(), maxIteration);\n return function (t) {\n displayIteration(iteration(t));\n };\n }",
"function linearlyApproach (current, target, delta) {\n if (Math.abs(current - target) < delta) {\n return target\n } else if (current < target) {\n return current + delta\n } else {\n return current - delta\n }\n }",
"CalculateReplacements(current_age, current_lifespan, new_age, new_lifespan) {\n var currentReplacements = 0\n if (current_age == 0) {\n currentReplacements = 1 + Math.floor((this._period - this._devswap) / current_lifespan);\n }\n else {\n if ((current_lifespan - current_age) < (this._period - this._devswap)) {\n currentReplacements = Math.ceil(((this._period + this._devswap) - (current_lifespan - current_age)) / current_lifespan)\n }\n }\n\n var newReplacements = 0;\n if (this._keep == 0) {\n if (new_age == 0) {\n newReplacements = 1 + Math.floor((this._period - this._devswap) / new_lifespan);\n }\n else {\n if ((new_lifespan - new_age) < (this._period - this._devswap)) {\n newReplacements = Math.ceil(((this._period + this._devswap) - (new_lifespan - new_age)) / new_lifespan)\n }\n }\n }\n else {\n if (current_age == 0) {\n var x = 0\n if (current_lifespan < (this._period - this._devswap)) {\n x = 1;\n }\n newReplacements = x + Math.round(Math.max(0, (this._period - this._devswap - (current_lifespan - current_age))) / new_lifespan);\n }\n else {\n newReplacements = Math.ceil(Math.max(0, (this._period - this._devswap - (current_lifespan - current_age)) - (new_lifespan - new_age)) / new_lifespan);\n }\n }\n //var currentReplacements = Math.floor((+(this._period) + current_age) / current_lifespan);\n //var newReplacements = Math.floor((+(this._period) - +(this._keep) * (current_lifespan - current_age) + new_age) / new_lifespan);\n var differenceReplacements = newReplacements - currentReplacements;\n\n this._currentReplacements = currentReplacements;\n this._newReplacements = newReplacements;\n this._differenceReplacements = differenceReplacements;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
upsample our lowquality buffer by 4 via linear interpolation to get to the max sample rate for audio context | function upSample(buf) {
var smallSampled = new Float32Array(buf.buf);
var length = smallSampled.length * 2;
var upSampled = new Float32Array(length);
for (var i = 0; i < smallSampled.length; i++) {
upSampled[i * 2] = smallSampled[i];
if (i + 1 < smallSampled.length) {
upSampled[i * 2 + 1] = (smallSampled[i] + smallSampled[i + 1]) / 2;
}
}
var b = buf;
b.buf = upSampled.buffer;
return b;
} | [
"function DownSample4x (source : RenderTexture, dest : RenderTexture){\n var off : float = 1.0f;\n Graphics.BlitMultiTap (source, dest, material,\n new Vector2(-off, -off),\n new Vector2(-off, off),\n new Vector2( off, off),\n new Vector2( off, -off)\n );\n}",
"set PreserveSampleRate(value) {}",
"renderbufferStorageMultisample(ctx, funcName, args) {\n const [target, samples, internalFormat, width, height] = args;\n updateRenderbuffer(target, samples, internalFormat, width, height);\n }",
"set OptimizeSampleRate(value) {}",
"function noiseLoader(buffer)\n{\n noiseSound.setBuffer(buffer);\n noiseSound.setRefDistance(100);\n noiseSound.setLoop(true);\n noiseSound.startTime = (Math.random()*((buffer.length / 44100) - 6));\n noiseSound.setPlaybackRate(.7);\n //noiseSound.panner.connect(audioContext.destination); //noise not connected for now\n whenLoaded();\n}",
"function testFilteringCenter() {\n var audiolet = new Audiolet();\n var sine = new Sine(audiolet, 300); // Should be filtered\n var brf = new BandRejectFilter(audiolet, 300);\n var recorder = new InputRecorder(audiolet, 1);\n\n sine.connect(brf);\n brf.connect(recorder);\n\n for (var i=0; i<81920; i++) {\n sine.tick();\n brf.tick();\n recorder.tick();\n }\n\n var buffer = recorder.buffers[0][0];\n Assert.assertContinuous(buffer);\n Assert.assertAudibleValues(buffer);\n Assert.assertValuesInRange(buffer, -0.5, 0.5); // Check for low amplitude\n}",
"set OverrideSampleRate(value) {}",
"function pcmGetClippingRatio(src) {\r\n const numSamples = src.length;\r\n let numClippedSamples = 0;\r\n for (let i = 0; i < numSamples; i++) {\r\n const sample = src[i];\r\n if (sample <= -32768 || sample >= 32767)\r\n numClippedSamples += 1;\r\n }\r\n return numClippedSamples / numSamples;\r\n }",
"function updateSound() {\n maxCheck();\n var soundLevel = AudioHandler.getLevel();\n if (soundLevel > 0.1) {\n inflate(soundLevel);\n } else {\n deflate();\n }\n requestAnimationFrame(updateSound);\n}",
"function spec2audio(speci) {\n\n var fftdata = new complex_array.ComplexArray(AudBuffSiz);\n\n // Initialise to 0\n for(var i=0; i<AudBuffSiz; i++) {\n fftdata.real[i] = 0;\n fftdata.imag[i] = 0;\n }\n\n // Loop over the input spectrum and map from input \"wavelength\" to spectral frequency\n for(i=0; i<DataDepth; i++) {\n var f = datafreq2audiofreq(i);\n var fi = audiofreq2fftindex(f);\n fftdata.real[fi] = fftdata.real[fi] + (AudAmplify * Math.pow(DataCube[speci + (i * DataWidth * DataHeight)], AudAmpScale));\n }\n\n fftdata.InvFFT();\n\n var tmpBuffer = AudioBuffer.getChannelData(0);\n for(i=0; i<AudBuffSiz; i++) {\n tmpBuffer[i] = fftdata.real[i];\n }\n var rampSize = 2048;\n for(i=0; i<rampSize; i++) {\n tmpBuffer[i] *= i / rampSize;\n tmpBuffer[tmpBuffer.length - i - 1] *= i / rampSize; \n }\n\n AudioSource.buffer = AudioBuffer;\n AudioSource.connect(AudioCtx.destination);\n AudioSource.loop = true;\n AudioSource.connect(GainNode);\n // Connect the gain node to the destination.\n GainNode.connect(AudioCtx.destination);\n GainNode.gain.value = 1;\n\n\n} // spec2audio()",
"get sampleRate() {\n if (this._buffer) {\n return this._buffer.sampleRate;\n } else {\n return (0, _Global.getContext)().sampleRate;\n }\n }",
"function setFrequency(value) {\n var minValue = 40;\n var maxValue = AUDIO.sampleRate / 2;\n var numberOfOctaves = Math.log(maxValue / minValue) / Math.LN2;\n var multiplier = Math.pow(2, numberOfOctaves * (value - 1.0));\n filterNode.frequency.value = maxValue * multiplier;\n}",
"function drawWave() {\n requestAnimationFrame(drawWave);\n analyser.getByteTimeDomainData(dataArray);\n canvasCtx.fillStyle = \"rgb(0,0,0)\";\n canvasCtx.fillRect(0, 0, canvas.width, canvas.height);\n canvasCtx.lineWidth = 2;\n canvasCtx.strokeStyle = \"rgb(255,255,255)\";\n canvasCtx.beginPath();\n const sliceWidth = (canvas.width * 1.0) / bufferLength;\n let x = 0;\n for (let i = 0; i < bufferLength; i++) {\n let v = dataArray[i] / 128;\n let y = (v * canvas.height) / 2;\n if (i === 0) {\n canvasCtx.moveTo(x, y);\n } else {\n canvasCtx.lineTo(x, y);\n }\n x += sliceWidth;\n }\n canvasCtx.stroke();\n}",
"loadSampleOver() {\n const audioOver = this.audioOver\n\n audioOver.defaultPlaybackRate = 1.0\n audioOver.src = db.alerts[0].src\n }",
"function playBuffers(buf) {\n var ctx = Recorder.audioContext;\n var fbuf = new Float32Array(buf.buf);\n\n var source = ctx.createBufferSource();\n var audioBuf = ctx.createBuffer(1, fbuf.length, SAMPLE_RATE);\n audioBuf.getChannelData(0).set(fbuf);\n\n source.buffer = audioBuf;\n source.connect(ctx.destination);\n source.noteOn(0);\n\n addTriangles(buf.n);\n}",
"function bufferToWave(abuffer, len) {\n var numOfChan = abuffer.numberOfChannels,\n length = len * numOfChan * 2 + 44,\n buffer = new ArrayBuffer(length),\n view = new DataView(buffer),\n channels = [], i, sample,\n offset = 0,\n pos = 0;\n\n // write WAVE header\n setUint32(0x46464952); // \"RIFF\"\n setUint32(length - 8); // file length - 8\n setUint32(0x45564157); // \"WAVE\"\n\n setUint32(0x20746d66); // \"fmt \" chunk\n setUint32(16); // length = 16\n setUint16(1); // PCM (uncompressed)\n setUint16(numOfChan);\n setUint32(abuffer.sampleRate);\n setUint32(abuffer.sampleRate * 2 * numOfChan); // avg. bytes/sec\n setUint16(numOfChan * 2); // block-align\n setUint16(16); // 16-bit (hardcoded in this demo)\n\n setUint32(0x61746164); // \"data\" - chunk\n setUint32(length - pos - 4); // chunk length\n\n // write interleaved data\n for(i = 0; i < abuffer.numberOfChannels; i++)\n channels.push(abuffer.getChannelData(i));\n\n while(pos < length) {\n for(i = 0; i < numOfChan; i++) { // interleave channels\n sample = Math.max(-1, Math.min(1, channels[i][offset])); // clamp\n sample = (0.5 + sample < 0 ? sample * 32768 : sample * 32767)|0; // scale to 16-bit signed int\n view.setInt16(pos, sample, true); // write 16-bit sample\n pos += 2;\n }\n offset++ // next source sample\n }\n\n\n //return new Blob([buffer], { 'type' : 'audio/ogg; codecs=opus' });\n return buffer;\n function setUint16(data) {\n view.setUint16(pos, data, true);\n pos += 2;\n }\n\n function setUint32(data) {\n view.setUint32(pos, data, true);\n pos += 4;\n }\n}",
"function goStream (stream) {\n var frequencyArray // array to hold frequency data\n\n // create the media stream from the audio input source (microphone)\n sourceNode = audioContext.createMediaStreamSource(stream)\n\n analyserNode = audioContext.createAnalyser()\n\n analyserNode.smoothingTimeConstant = 0.3 // **\n analyserNode.fftSize = b.fftSize // **\n\n javascriptNode = audioContext.createScriptProcessor(b.sampleSize, 1, 1)\n\n // setup the event handler that is triggered every time enough samples have been collected\n javascriptNode.onaudioprocess = function () {\n b.pow = 0\n\n frequencyArray = new Uint8Array(analyserNode.frequencyBinCount)\n analyserNode.getByteFrequencyData(frequencyArray)\n\n // put in all frequencyArray data\n for (var i = 0; i < frequencyArray.length; i++) {\n b.frequencyBin[i] = frequencyArray[i]\n }\n\n // sum all data in array\n b.frequencyBin.forEach(function (value) {\n b.pow += value\n })\n\n // set noise level increase noise level and if current is > than saved then current is our new noise level(room)\n if (b.noiseLevel === -1) { // For very first input signal, just to set it on\n b.noiseLevel = b.pow\n } else { // Setting noise level on off event and first 30 on event signals\n if (b.pow < b.noiseLevel) {\n b.noiseLevel = b.pow\n } else if (b.pow > b.noiseLevel) {\n if (b.countBlow < 30) {\n b.noiseLevel = b.noiseLevel + 10 // noise level\n } else if (b.countBlow > 30) {\n b.noiseLevel = b.noiseLevel + 0 // noise level\n }\n }\n }\n\n // Setting all thresholds for our on events\n b.ThrOnFast = Math.round(b.noiseLevel + b.noiseLevelConst)\n b.ThrOffFast = Math.round(b.noiseLevel + b.noiseOffConst)\n b.ThrOffSlow = Math.round(b.noiseLevel + b.noiseOffSlowConst)\n\n // Calculating variances - putting each b.pow in array and the sub current and one past\n b.PowerWindow[b.pw] = b.pow\n if (b.pw > 0 && b.pw < 500) {\n b.pwVariance = Math.round(b.PowerWindow[b.pw] - b.PowerWindow[b.pw - 1])\n } else if (b.pw > 500) {\n b.pw = 0\n b.PowerWindow.length = 0\n }\n\n b.pw++\n\n // Check if function for when exhalation is detected (on event) is running\n if (b.functionRunning === false) {\n b.countBlow = 0\n onEvent(b.pow, b.pwVariance)\n } else if (b.functionRunning === true) {\n b.countBlow++\n offEvent(b.pow, b.pwVariance)\n }\n }\n\n // Now connect the nodes together\n // Do not connect source node to destination - to avoid feedback\n sourceNode.connect(analyserNode)\n analyserNode.connect(javascriptNode)\n javascriptNode.connect(audioContext.destination)\n}",
"_bufferTransform() {\n if (this.mode === 'buffer') {\n const scale = this.bufferValue / 100;\n return { transform: `scaleX(${scale})` };\n }\n return null;\n }",
"resetSampleOver() {\n this.audioOver.pause()\n this.audioOver.currentTime = 0\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a method to validate coupon code on server /api/couponCodes/123asdf1223 | async validateCouponCode(code) {
let response = await axios.getCatalog("http://127.0.0.1:5000/api/couponCodes/" + code);
return response.data;
} | [
"ValidateACodeToGenerateAssociatedCreditMovement(inputCode, serviceId) {\n let url = `/me/credit/code`;\n return this.client.request('POST', url, { inputCode, serviceId });\n }",
"function checkCoupon(enteredCode, correctCode, currentDate, expirationDate){\n console.log(enteredCode + ' ' + correctCode + ' ' + currentDate + ' ' + expirationDate)\n console.log(enteredCode.length);\n if(enteredCode.toString().length < 3 || enteredCode.toString() != correctCode.toString() || enteredCode == '') {\n return false;\n }\n var dateNow = new Date(currentDate);\n var dateCoupon = new Date(expirationDate);\n if (dateNow > dateCoupon) {\n return false;\n }\n\n return true;\n\n}",
"validateResetPasswordCode(params, cb, errorCb) {\n\t\tconst url = `${endpoint}/password/reset/validate`;\n\t\tclient.post(url, params)\n\t\t\t.then((response) => {\n\t\t\t\tif (cb) {\n\t\t\t\t\tcb(response.data);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch((e) => {\n\t\t\t\tif (errorCb) {\n\t\t\t\t\terrorCb(e);\n\t\t\t\t}\n\t\t\t});\n\t}",
"function evalVATCode(countrycode, VATcode) \n{\n vatspec = getVATSpec(countrycode);\n \n if (VATcode.slice(0,vatspec.prefix.length) != vatspec.prefix) \n return 1;\n if(VATcode.length < vatspec.minlength)\n return 2;\n if(VATcode.length > vatspec.maxlength)\n return 3; \n \n return 0;\n}",
"function validateSendCoupon(formname)\n{\n \n if(validateForm(formname, 'frmUserEmail', 'User Email', 'RisEmail'))\n {\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"static validateValuationCodeEntered(pageClientAPI, dict) {\n let error = false;\n let message = '';\n //Code group is not empty\n if (!libThis.evalCodeGroupIsEmpty(dict)) {\n //Characteristic is blank\n if (libThis.evalIsCodeOnly(dict)) {\n error = (libThis.evalValuationCodeIsEmpty(dict));\n if (error) {\n message = pageClientAPI.localizeText('field_is_required');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ValuationCodeLstPkr'), message);\n }\n } else {\n //Code sufficient is set and reading is empty\n if (libThis.evalIsCodeSufficient(dict) && libThis.evalIsReadingEmpty(dict)) {\n error = (libThis.evalValuationCodeIsEmpty(dict));\n if (error) {\n message = pageClientAPI.localizeText('validation_valuation_code_or_reading_must_be_selected');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ValuationCodeLstPkr'), message);\n }\n }\n }\n }\n if (error) {\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n } else {\n return Promise.resolve(true);\n }\n }",
"function validateNumbers() {\n return auctions_id == [0-9]*$ ? axios.post('https://silent-auction-69.herokuapp.com/api/items', auction)\n .then(res => {\n console.log('res:', res)\n })\n .catch(err => {\n console.log('error:', err)\n }) : cogoToast.error('')\n }",
"async function checkForValidIndAndCo(ind, co) {\n const indResult = await db.query(`SELECT code FROM industries`);\n const industries = indResult.rows.map(val => val.code);\n\n const compResult = await db.query(`SELECT code FROM companies`);\n const companies = compResult.rows.map(val => val.code);\n\n if (!(industries.includes(ind) && companies.includes(co))) {\n throw new ExpressError('Please enter valid industry and company codes!', 400);\n }\n}",
"function validateCoupon(formname)\n{\n \n if(validateForm(formname, 'frmCouponCode', 'Coupon Code', 'R','frmCouponPriceValue', 'Price Value', 'RisDecimal', 'frmMinimumPurchaseAmount', 'Minimum Purchase Amount', 'RisDecimal', 'frmCouponPriceValue', 'Price Value', 'regDecimal','frmCouponActivateDate', 'Coupon Activate date', 'R','frmCouponExpiryDate', 'coupon expiry date', 'R'))\n {\t\n \t\n var CouponActivateDate=document.forms[0].frmCouponActivateDate.value;\n var CouponExpiryDate=document.forms[0].frmCouponExpiryDate.value;\n if(CouponActivateDate > CouponExpiryDate)\n {\n alert(SORRY_CANT_COMPLETE_YOUR_REQ);\n return false;\n }\n } \n else \n {\n return false;\n } \n}",
"static isTokenCodeValid(tokenCode) {\n const validation = (0, validation_1.validate)({ tokenCode }, { tokenCode: validation_1.allRules.chain });\n if (!validation.isValid) {\n throw new ValidationError_1.ValidationError(validation.errors);\n }\n return true;\n }",
"function validate() {\n var _a, _b;\n var count = 0;\n var code = (_a = document.getElementById('rocket-code')) === null || _a === void 0 ? void 0 : _a.value;\n var numBoosters = document.getElementById('boosters').value;\n //Validate all inputs have value\n var inputs = document.querySelectorAll('input');\n Array.from(inputs).forEach(function (element) {\n var input = element.value;\n if (input === \"\") {\n count++;\n }\n });\n //if validate its ok, call function\n if ((count === 0) && (code.length === 8) && (numBoosters <= 6 && numBoosters != 0)) {\n createBoostsInput();\n //hide create button\n ((_b = document.getElementById('rocket-btn')) === null || _b === void 0 ? void 0 : _b.classList.add('d-none'));\n }\n else if (count != 0) {\n alert('Rellena los campos');\n }\n else if (code.length != 8) {\n alert('El nombre del cohete ha de tener ocho caracteres');\n }\n else if (numBoosters > 6 || numBoosters == 0) {\n alert('Como máximo seis propulsores y mínimo 1');\n }\n}",
"function validateSecurityCode(elem){\r\n const value = elem.val();\r\n return validateTextField(elem,\r\n [(value.length === 3 || value.length === 4) && (value.match(/^\\d+$/))],\r\n [value.length >4 || !(value.match(/^\\d+$/))]\r\n );\r\n}",
"function validateEmiCard(self, type, charCode) {\n if (!(typeof charCode === 'boolean' || (charCode >= 48 && charCode <= 57))) {\n return false;\n } else if (self.value.length === 6 || !charCode) {\n var cardtype = document.getElementById('cardtype_em').value;\n if (!charCode) {\n if (cardtype === '') {\n return false;\n } else if (inValidType(self.value.length, 'em')) {\n return false;\n }\n }\n document.getElementById('ccnum_emi').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_emi').style.display = 'none';\n document.getElementById('amex_emi').style.display = 'none';\n document.getElementById('visa_emi').style.display = 'none';\n document.getElementById('master_emi').style.display = 'none';\n\n var data = {\n \"bin\" : self.value.substring(0,6),\n \"errorBlock\" : document.getElementById('error-ccnum_emi'),\n \"ccnum\" : document.getElementById('ccnum_emi'),\n \"ccvv\" : document.getElementById('ccvv_emi'),\n \"btn\" : document.getElementById('checkoutprocess_emi'),\n \"amex\" : document.getElementById('amex_emi'),\n \"visa\" : document.getElementById('visa_emi'),\n \"master\" : document.getElementById('master_emi'),\n \"processing\" : document.getElementById('processing_emi'),\n \"cardtype\" : document.getElementById('cardtype_em'),\n \"errorMsg\" : 'Invalid credit card type!'\n };\n processAjaxRequest(data, type);\n\n return true;\n } else {\n if (self.value.length < 6) {\n document.getElementById('ccnum_emi').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_emi').style.display = 'none';\n document.getElementById('amex_emi').style.display = 'none';\n document.getElementById('visa_emi').style.display = 'none';\n document.getElementById('master_emi').style.display = 'none';\n }\n\n return false;\n }\n}",
"validateInstruction(instruction) {\n if (!instruction.match(/^\\+\\d{4}$/)) return false\n const checkOpCode = instruction.substring(1, 3)\n if (!this.validOpCodes.includes(parseInt(checkOpCode))) return false\n return true;\n }",
"function get_dcode(){\n\tvar dcode = get_variable_from_query(\"dcode\");\n\tif(dcode){\n\t\t$.ajax({\n\t \ttype: \"GET\",\n\t \turl: \"https://blooom-api-staging.herokuapp.com/discount_codes/\" + dcode,\n\t \tdataType: 'json',\n\t \tsuccess: function (response) {\n\t\t\t\t$(\"#discount_code_id\").val(response.discount_code.id);\n\t \t},\n\t \terror: function (xhr, status, error) {\n\t \t}\n\t });\n\t}\n}",
"function get_code(req, res) {\n\t\tif (req._client_event === true && req.body) {\n\t\t\treturn !isNaN(req.body.http_code) ? Number(req.body.http_code) : 500;\n\t\t} else {\n\t\t\treturn t.ot_misc.get_code(res);\t\t\t\t\t\t\t\t// normal requests end up here\n\t\t}\n\t}",
"function checkCoupon(coupon) {\n// console.log(\"==checkCoupon==\");\n// set a limit to the expiration date of the coupon\nvar expirationDate = new Date(coupon);\nexpirationDate.setHours(23);\nexpirationDate.setMinutes(59);\nexpirationDate.setSeconds(59);\n// checking if the coupon's date exceeds the END of the date by setting a limit for day (hour, minute, seconds)\n if (expirationDate > new Date()) {\n return false;\n } else {\n return true;\n }\n\n}",
"getCondition() { return 'Bad Request' }",
"function validateDebitCard(self, type, charCode) {\n if (!(typeof charCode === 'boolean' || (charCode >= 48 && charCode <= 57))) {\n return false;\n } else if (self.value.length === 6 || !charCode) {\n var cardtype = document.getElementById('cardtype_dc').value;\n if (!charCode) {\n if (cardtype === '') {\n return false;\n } else if (inValidType(self.value.length, type.toLowerCase())) {\n return false;\n }\n }\n document.getElementById('ccnum_dc').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_dc').style.display = 'none';\n document.getElementById('amex_dc').style.display = 'none';\n document.getElementById('visa_dc').style.display = 'none';\n document.getElementById('master_dc').style.display = 'none';\n\n var data = {\n \"bin\" : self.value.substring(0,6),\n \"errorBlock\" : document.getElementById('error-ccnum_dc'),\n \"ccnum\" : document.getElementById('ccnum_dc'),\n \"ccvv\" : document.getElementById('ccvv_dc'),\n \"btn\" : document.getElementById('checkoutprocess_dc'),\n \"amex\" : document.getElementById('amex_dc'),\n \"visa\" : document.getElementById('visa_dc'),\n \"master\" : document.getElementById('master_dc'),\n \"processing\" : document.getElementById('processing_dc'),\n \"cardtype\" : document.getElementById('cardtype_dc'),\n \"errorMsg\" : 'Invalid debit card type!'\n };\n processAjaxRequest(data, type);\n\n return true;\n\n } else {\n if (self.value.length < 6) {\n document.getElementById('ccnum_dc').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_dc').style.display = 'none';\n document.getElementById('amex_dc').style.display = 'none';\n document.getElementById('visa_dc').style.display = 'none';\n document.getElementById('master_dc').style.display = 'none';\n }\n\n return false;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Action after done button is activated | function initDoneButton ()
{
getId('save_user').addEventListener( 'click', function(event) {
event.preventDefault();
finishAnnotationSingle();
stopAutoSave();
finished = true;
sendLogs();
return false;
}
);
} | [
"finish() {\n this.finishBtn.click();\n }",
"function done() {\n putstr(padding_left(\" DONE\", seperator, sndWidth));\n putstr(\"\\n\");\n }",
"function cpsh_onFinish(evt) {\n evt.preventDefault();\n finishConfirmDialog.hidden = true;\n WapPushManager.close();\n }",
"function switchToDoneBtn(context) {\n if ($(context).closest(\".timers\").css(\"background-color\")) {\n $(context).closest(\".timers\").css(\"background-color\", \"\");\n }\n deleteBtn(context);\n }",
"function onProceedClick() {\n setDisplayValue('q1');\n updateLastViewed('q1');\n showHideElements();\n}",
"function completeContinuePhase () {\n\t/* show the player removing an article of clothing */\n\tprepareToStripPlayer(recentLoser);\n updateAllGameVisuals();\n\t\n\t$mainButton.html(\"Strip\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}",
"function finishAsking(q) {\n // collect given answers and make request\n q.html.trigger('question.finish', q);\n var answers = {'_wizard': 1}, q2 = q, i = 0,\n html = $('<fieldset id=\"wizard_finish\">' +\n '<legend>'+_('Finished!')+'</legend>' +\n '</fieldset>');\n if (q.selected !== null) {\n answers[q.id] = q.selected;\n i += 1;\n }\n while (q2.prev) {\n q2 = q2.prev;\n answers[q2.id] = q2.selected;\n i += 1;\n }\n QuestionPrototype.container.addClass('finished');\n html.append($('<p></p>')\n .text(_('Please wait a second, we’re making those %s answers productive.', i))\n .prepend('<img src=\"/static/images/ajax.gif\" alt=\"\" width=\"16\" height=\"16\"/> '));\n $('#wizard_now').fadeOut('fast');\n q.html.fadeOut('fast', function() {\n html.hide().insertAfter(q.html).fadeIn('fast');\n q.html.detach();\n });\n window.location.href = '?' + $.param(answers);\n}",
"reviewComplete() {\n this.reviewInfo.text( 'All reviews resolved!' );\n this.acceptAll.remove();\n this.reviewCompleteButtons();\n }",
"function onboardingFollowCoursesNextStepButton() {\n $(\"#onboarding-follow-courses-modal\").modal(\"hide\"); // hide the modal\n $(\"#onboarding-follow-courses-modal\").remove();\n showOnboardingProfileStep(); // show the next step\n }",
"function onboardingFollowSubjectNextStepButton() {\n $(\"#onboarding-follow-subjects-modal\").modal(\"hide\"); // hide the modal\n $(\"#onboarding-follow-subjects-modal\").remove();\n showOnboardingFollowInstitutionsStep(); // show the next step\n }",
"function markGoalComplete() {\n\t\tprops.markGoalComplete(props.goalId);\n }",
"function toggle_done() {\n if (active_timer_idx >= 0 && active_timer_idx != selected_timer_idx) {\n return; // Special case of discussion toggled on. Don't set to done in this case.\n }\n\n var next_timer_idx = -1;\n if (active_timer_idx < 0) {\n timer_object = timers[selected_timer_idx];\n } else {\n timer_object = timers[active_timer_idx];\n if (typeof timers[active_timer_idx + 1] != 'undefined') {\n next_timer_idx = active_timer_idx + 1;\n }\n }\n if (timer_object != null) {\n if (active_timer_idx >= 0) {\n timer_object.circleProgress('timer_done', 1);\n start_stop_timer(active_timer_idx, 0);\n if (next_timer_idx >= 0) {\n change_selected_to(next_timer_idx);\n start_stop_timer(next_timer_idx, 1);\n active_timer_idx = next_timer_idx;\n } else {\n active_timer_idx = -1;\n }\n\n } else {\n timer_object.circleProgress('timer_done', -1);\n }\n }\n}",
"finish() {\n if (!this.disabled) {\n this._sendBatch();\n this.clearEvents();\n }\n }",
"function onboardingFollowInstitutionsNextStepButton() {\n $(\"#onboarding-follow-institutions-modal\").modal(\"hide\"); // hide the modal\n $(\"#onboarding-follow-institutions-modal\").remove();\n showOnboardingFollowCoursesStep(); // show the next step\n }",
"importingDone() { if (this.isSearchUI()) MySearchUI.importingDone(); }",
"function setFinish() {\r\n\t$(\".start\").removeClass(\"start\").addClass(\"finish\").html(\"FINISHED\");\r\n\t$(\".resume\").removeClass(\"resume\").addClass(\"finish\").html(\"FINISHED\");\r\n\t$(\".pause\").removeClass(\"pause\").addClass(\"finish\").html(\"FINISHED\");\r\n\t$(\".running\").removeClass(\"running\").addClass(\"finish\").html(\"FINISHED\");\r\n\t$(\"#funcBtn\").css(\"cursor\", \"default\");\r\n}",
"_onAddActionAnimationFinish() {\n if (!this._addAction) {\n this.$.addApplicationAction.style.display = 'none';\n }\n }",
"function finishProcessing(id,percent,state,error){\n\t\tvar stateBar = getStateBarElement(id);\n\t\tvar btnStart = getBtnStartElement(id);\n\t\tvar btnDownlaod=getBtnDownloadElement(id);\n\t\t\n\t\tstateBar.innerHTML=state;\n\t\tif(error){\n\t\t\tupdateProgressBar (id, 0);\n\t\t\tresetColorsProgressBar (id);\n\t\t\tbtnStart.disabled=false;\n\t\t\tbtnDownlaod.disabled=true;\n\t\t} else{\n\t\t\tbtnStart.disabled=false;\n\t\t\tbtnDownlaod.disabled=false;\n\t\t\tprocessStateTabs(id);\n\t\t\tupdateProgressBar (id, percent);\n\t\t}\n\t}",
"function afterAct() {\n inquirer.prompt([\n {\n type: \"list\",\n name: \"afterAction\",\n message: \"What would you like to do next?\",\n choices: [\"Add another item\", \"View my cart or make changes to my cart\", \"Check out\"]\n }\n ]).then(({ afterAction }) => {\n if (afterAction === \"Add another item\") {\n askProduct();\n }\n else if (afterAction === \"View my cart or make changes to my cart\") {\n showCart();\n }\n else if (afterAction === \"Check out\") {\n checkOut();\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable editable for all cell inside table | _disableEditableCell(event) {
if(event.target.tagName.toLowerCase() != 'td') return;
var data = [];
var index = +event.target.closest('tr').dataset.index;
event.target.removeAttribute("contenteditable");
event.target.classList.remove("editable");
for(var i = 0; i < event.target.closest('tr').querySelectorAll('td').length - 1; i++) {
data.push(event.target.closest('tr').querySelectorAll('td')[i].innerHTML);
}
this.options.fullData[index] = data;
} | [
"function setEditableStatus() {\n var $cells = $(\"#notebook-container\").children();\n for (var cellIndex = 0; cellIndex < Jupyter.notebook.get_cells().length; cellIndex++) {\n if (cellShouldBeUneditable(cellIndex)) {\n Jupyter.notebook.get_cell(cellIndex).metadata[\"editable\"] = false;\n } else {\n Jupyter.notebook.get_cell(cellIndex).metadata[\"editable\"] = true;\n }\n }\n }",
"function cellShouldBeUneditable(cellIndex) {\n if (cellIndex >= Jupyter.notebook.get_cells().length) {\n return false;\n }\n\n var cell = Jupyter.notebook.get_cell(cellIndex);\n if (cell == null) {\n return false;\n }\n // Some cells already have this editable tag set. Simply use this status as is.\n if (\"editable\" in cell.metadata) {\n return !cell.metadata[\"editable\"];\n } else {\n // questions, datasets, part prologues -> NOT editable\n if (\"question_id\" in cell.metadata ||\n \"dataset_id\" in cell.metadata ||\n \"part_id\" in cell.metadata && \"prologue\" == cell.metadata[\"type\"]) {\n return true;\n } else {\n return false;\n }\n }\n }",
"function disableEditing() {\n disableForm(true);\n}",
"function disableEditingNameViewForStudentID(id) {\n\n // Show the specific table cell\n $(`#${uniqueIDPrefix}name${id} span`).removeAttr('class', 'edit-content-hidden');\n\n // Access and destroy the input\n $(`#${uniqueIDPrefix}input-name${id}`).remove();\n\n}",
"function disableEditingGradeViewForStudentID(id) {\n\n // Show the specific table cell\n $(`#${uniqueIDPrefix}grade${id} span`).removeAttr('class', 'edit-content-hidden');\n\n // Access and destroy the input\n $(`#${uniqueIDPrefix}input-grade${id}`).remove();\n\n}",
"function disableKeyListenersForCell(cell) {\n cell.element[0].addEventListener(\n 'focus',\n () => {\n Jupyter.keyboard_manager.disable();\n },\n true\n );\n }",
"function disableme() {\n\tvar itms = getDisabledItems();\n\tfor(i=0; i< itms.length; i++) \n\t{\n\t\titms[i].readOnly = true;\n }\n}",
"function disableNativeFirefoxTableControls() {\n document.execCommand(\"enableObjectResizing\", false, \"false\");\n document.execCommand(\"enableInlineTableEditing\", false, \"false\");\n}",
"function setGridEvents() {\n $table.find(\"td.editable\").live(\"mousedown\", function() {\n $sel = $(this);\n setSelectedCell($sel);\n var editor = columns[$(this).attr(\"col\")].editor;\n $('#' + editor).trigger(\"hide\");//, [getCellValue(this)]);\n }).live(\"click\", function(e) {\n var editor = columns[$(this).attr(\"col\")].editor;\n $('#' + editor).trigger(\"show\", [this, getCellValue(this)]);\n });\n\n // Tabl events\n $table.bind({\n 'addRow': function() {\n addNewRow();\n }\n });\n\n }",
"onDisabled() {\n this.updateInvalid();\n }",
"function wireTableButtons() {\n // wire every table button\n $(\".btn\").click(function () {\n markSelected(this);\n $(\"#TVeditDiv :input\").attr(\"disabled\", \"disabled\"); // view mode: disable all controls in the form\n })\n}",
"function makeEditable(event) {\n\tvar choices = ['Acceptable', 'Good', 'Excellent'];\n\tvar td = event.target.parentNode;\n\tvar tr = td.parentNode;\n\n\t// Source: https://www.golangprograms.com/highlight-and-get-the-details-of-table-row-on-click-using-javascript.html\n\tvar currentRow = tr.cells;\n\tvar condition = currentRow.item(2);\n\n\t// Hide Update Button and Show Submit button.\n\tvar updateButton = currentRow.item(4).childNodes[1];\n\tupdateButton.style.display = 'none';\n\tvar submitButton = currentRow.item(4).childNodes[3];\n\tsubmitButton.style.display = 'block';\n\n\t// Hide Delete Button and Show Cancel Button.\n\tvar deleteButton = currentRow.item(5).childNodes[1];\n\tdeleteButton.style.display = 'none';\n\tvar cancelButton = currentRow.item(5).childNodes[3];\n\tcancelButton.style.display = 'block';\n\n\t// Create dropdown menu.\n\tvar newDrop = document.createElement('select');\n\tvar option1 = document.createElement('option');\n\tvar text = condition.innerText;\n\tcondition.removeChild(condition.childNodes[0]);\n\toption1.innerText = text;\n\tnewDrop.appendChild(option1);\n\n\tfor (var i = 0; i < choices.length; i++) {\n\t\tif (choices[i] != text) {\n\t\t\tvar option = document.createElement('option');\n\t\t\toption.innerText = choices[i];\n\t\t\tnewDrop.appendChild(option);\n\t\t}\n\t}\n\tcondition.appendChild(newDrop);\n}",
"function disableOtherEventsFromThisSubmission( ){\n const eventsFromThisSubmission = allEvents.filter( event => event.submissionId === selectedEvent.submissionId && event.id != selectedEvent.id ) ;\n eventsFromThisSubmission.forEach( event => updateField( event.rowNum, header.status, \"disabled\") );\n }",
"function isEditable() {\n return (current && current.isOwner && !current.frozen);\n}",
"function cellShouldBeGrey(cellIndex) {\n if (cellIndex >= Jupyter.notebook.get_cells().length) {\n return false;\n }\n var cell = Jupyter.notebook.get_cell(cellIndex);\n if (cell == null) {\n return false;\n }\n if (cell.metadata[\"editable\"] == false) {\n return true;\n } else {\n return false;\n }\n }",
"function pk_is_not_editable(pk) {\n return ((!pk.editable) || (pk.auto_created || isinstance(pk, AutoField))\n || (pk.rel && pk.rel.parent_link && pk_is_not_editable(pk.rel.to._meta.pk)));\n }",
"function editAnime(e){\n const rowId = e.parentNode.parentNode.id;\n\n var title = document.getElementById(rowId).cells[0];\n var rating = document.getElementById(rowId).cells[1];\n var status = document.getElementById(rowId).cells[2];\n var comment = document.getElementById(rowId).cells[3];\n\n // toggle edit/save\n document.getElementById(\"edit\" + rowId).toggleAttribute(\"hidden\");\n document.getElementById(\"save\" + rowId).toggleAttribute(\"hidden\");\n // get cell data\n var curTitle = document.getElementById(rowId).cells[0].innerHTML;\n var curRating = document.getElementById(rowId).cells[1].innerHTML;\n var curStatus = document.getElementById(rowId).cells[2].innerHTML;\n var curComment = document.getElementById(rowId).cells[3].innerHTML;\n \n // cell data editable\n title.innerHTML = \"<input id='title\"+ rowId +\"' type=\\\"text\\\" placeholder=\\\"Title\\\" required name=\\\"title\\\" value='\"+ curTitle +\"'>\"\n rating.innerHTML = \"\\\n <select id='rating\"+ rowId +\"' name='rating'> \\\n <option value='-'>-</option> \\\n <option value='1'>1</option> \\\n <option value='2'>2</option> \\\n <option value='3'>3</option> \\\n <option value='4'>4</option> \\\n <option value='5'>5</option> \\\n <option value='6'>6</option> \\\n <option value='7'>7</option> \\\n <option value='8'>8</option> \\\n <option value='9'>9</option> \\\n <option value='10'>10</option> \\\n </select>\"\n var selectRating = document.getElementById(\"rating\" + rowId);\n selectRating.value = curRating;\n\n status.innerHTML = \"\\\n <select id='status\" + rowId + \"' name='status'> \\\n <option value='Status' selected disabled>Status</option> \\\n <option value='Completed'>Completed</option> \\\n <option value='Watching'>Watching</option> \\\n <option value='Planning'>Planning</option> \\\n <option value='Dropped'>Dropped</option> \\\n </select>\"\n var selectStatus = document.getElementById(\"status\" + rowId);\n selectStatus.value = curStatus;\n\n comment.innerHTML = \"<input type='text' id='comment\" + rowId + \"' placeholder='Comment' name='comment' value='\" + curComment + \"'>\"\n}",
"function OnClickRowEnable(enabled)\r\n{\r\n var rows = iDoc.getElementById(\"dataTable\").rows;\r\n\r\n for (var i = 1; i < rows.length; i++)\r\n {\r\n if (rows[i].getAttribute(\"selected\") == 1)\r\n {\r\n if (enabled == true) StyleRemoveAttributes(rows[i], \"color\"); else StyleSetAttributes(rows[i], \"color: gray;\");\r\n rows[i].setAttribute(\"enabled\", (enabled == true) ? 1 : 0);\r\n changesMade = true;\r\n }\r\n }\r\n}",
"disablePlugin() {\n this.settings = {};\n this.hiddenColumns = [];\n this.lastSelectedColumn = -1;\n\n this.hot.render();\n super.disablePlugin();\n this.resetCellsMeta();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show Return Button function | function showReturn(ctx){
ctx.telegram.sendMessage(ctx.chat.id,wordsList[language].Return,{
reply_markup : {
inline_keyboard: [
[{text:"\u{21A9}",callback_data:"RETURN"}],
]
}
})
} | [
"function returnBtnSubjectTemplate(){\n\t$('#subjectTemplatePage .btnReturn').remove();\n\tlet prevButton = $('<button>');\n\tlet icon = $('<img>');\n\ticon.attr('src', './views/Images/btnReturn.png')\n\tprevButton.append(icon);\n\n\tprevButton.addClass('btnReturn')\n\tprevButton.click(function(){\n\t\t$('#subjectTemplatePage').css('display', 'none');\n\t\t$('#ContactUsPage').css('display', 'none');\n \t$('#indexPage').css('display', 'block');\n \t$('#uploadPage').css('display', 'none');\n\t\t$(this).remove();\n\t});\n\t$('#resContainer').before(prevButton);\n}",
"function onProceedClick() {\n setDisplayValue('q1');\n updateLastViewed('q1');\n showHideElements();\n}",
"function returnToSearchResults() {\n $('.returnSearch').on('click', function() {\n $('.js-search-results').show();\n $('.oneResult').hide();\n $('.returnSearch').hide();\n })\n}",
"function textBackwardButton() {\n\treturn (\n\t\t`<button class='mainPageButton' onclick='mainPage(); img='images/back.png'></button>`\n\t);\n}",
"function ex(btn){ \n thePlayerManager.showExercise(btn);\n}",
"function clickButtonOnEnter(event, button) {\r\n\tif (event && button && (event.which == 13 || event.keyCode == 13)) {\r\n\t\tif (button.length) {\r\n\t\t\tbutton[0].click();\r\n\t\t} else {\r\n\t\t\tbutton.click();\r\n\t\t}\r\n\t\treturn false;\r\n\t} else {\r\n\t\treturn true;\r\n\t}\r\n}",
"function enterAction(event, button) {\n\tevent.preventDefault();\n\tif (event.keyCode === 13) { \n\t\tdocument.activeElement.blur();\n\t\tbutton.click();\n\t}\n}",
"function showBackBt() {\n if (_historyObj.length > 1) {\n return true;\n } else {\n return false;\n }\n }",
"finish() {\n this.finishBtn.click();\n }",
"function generateRetakeButton(){\r\n $(\"main\").find(\"fieldset\").after(`<button type=\"button\" id=\"retake\">Retake</button>`);\r\n}",
"function displayResult() {}",
"maxBetButtonClickAction () {}",
"function clicked_button() {\n if (\n confirm(\n \"Are you sure you want to submit? When submitting, your answers will be sent and the voting page will be reset\"\n )\n ) {\n window.location.reload();\n } else {\n return false;\n }\n}",
"function showNewSearchOption() {\n $('.newSearch').html(`\n <button type=\"submit\" name=\"newSearchBut\" class=\"newSearchBut\">New Search</button>\n `);\n}",
"function generateNextButton(){\r\n // remove submit button\r\n $(\"main\").find(\"#submit\").remove();\r\n // replace submit button with retake button if on last question\r\n if (questionData[questionArrayIndex].questionNumber === 10){\r\n generateRetakeButton();\r\n generateResults();\r\n }\r\n else {\r\n // replace submit button with next button\r\n $(\"main\").find(\"fieldset\").after(`<button type=\"button\" id=\"next\">Next>></button>`);\r\n }\r\n // change isButtonSubmit to false since it has been converted into the next button\r\n isButtonSubmit = false;\r\n // add 1 to the questionArrayIndex in preperation to render next question once next button is clicked\r\n questionArrayIndex ++;\r\n}",
"function onPrompt(results) {\n\t\talert(\"You selected button number \" + results.buttonIndex + \" and entered \" + results.input1);\n\t}",
"function renderResultsButton() {\n btn.innerHTML = 'View Results';\n document.body.appendChild(btn);\n}",
"function showPlayAgainButton() {\n\t$(\"#play-again\").show().css({opacity:0}).stop().animate({opacity:1},400);\n}",
"function displayButton() {\n if (currentUnits == \"C\") {\n $(\"#units\").html(\"Use Fahrenheit\");\n } else {\n $(\"#units\").html(\"Use Celsius\");\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function used during window.onload to initialize Event listeners on Skill value form fields for validation | function eventListenerInit() {
// get TOTAL_FORMS element from Django management_form of Skill formset
let totalSkillForms = document.getElementById("id_skill-TOTAL_FORMS");
for (i = 0; i < totalSkillForms.value; i++) {
addSkillValueValidationEvent(i);
}
} | [
"function initialize() {\r\n var partySize = document.getElementById(\"maxPartySize\");\r\n partySize.addEventListener(\"blur\", validatePartySize);\r\n\r\n var parties = document.getElementById(\"maxParties\");\r\n parties.addEventListener(\"blur\", validateParties);\r\n}",
"function skillValuesValidation() {\r\n // get TOTAL_FORMS element from Django management_form of Skill formset\r\n let totalSkillForms = document.getElementById(\"id_skill-TOTAL_FORMS\");\r\n let skillValues = [];\r\n // iterate Skill value fields and collect valid values\r\n for (i = 0; i < totalSkillForms.value; i++) {\r\n let skillDeleteFlag = document.getElementById(`id_skill-${i}-DELETE`).checked;\r\n let skillValue = document.getElementById(`id_skill-${i}-value`).value;\r\n if (!skillDeleteFlag && skillValue !== \"\") {\r\n skillValues.push(parseInt(skillValue));\r\n }\r\n }\r\n // sum up Skill values\r\n const valuesSum = skillValues.reduce((a, b) => a + b, 0);\r\n // calculate remaining Skill Points\r\n const remainingPoints = 400 - valuesSum;\r\n let skillPointsRemaining = document.getElementById(\"skill-points-remaining\");\r\n // adapt Frontend message\r\n skillPointsRemaining.innerHTML = `Remaining Skill Points: ${remainingPoints}`;\r\n // handle Submit Button state\r\n if (remainingPoints !== 0) {\r\n document.getElementById(\"characterSubmit\").disabled = true;\r\n } else {\r\n document.getElementById(\"characterSubmit\").disabled = false;\r\n }\r\n}",
"function HookEvents() {\n\t// Get all the inputs we want to add events to, generally this will be input fields\n\tvar inputs = document.getinputsByTagName('input');\n\tfor (i = 0; i < inputs.length; i++) {\n\t\t//Add a function call to the onblur event\n\t\tAddFunctionToControlEvent(inputs[i], 'onblur', HookedFunction);\n\t}\n\t// We can also monitor dropdowns\n\tvar selects = document.getinputsByTagName('select');\n\tfor (i = 0; i < selects.length; i++) {\n\t\tif (selects[i].addEventListener) {\n\t\t\tselects[i].addEventListener('onblur', HookedFunction, false); \n\t\t}\n\t\telse {\n\t\t\tselects[i].attachEvent('onblur', HookedFunction); \n\t\t}\n\t}\n}",
"function registerFormEvents() {\n if (inlineJs.crudId == 1 || inlineJs.crudId == 2) {\n validateForm('form#' + inlineJs.controller + 'Post');\n\n //Size the forms\n sizeForm();\n\n //Max length indicator\n maxLengthIndicator();\n\n //Register searchable select\n registerSearchableSelect();\n\n }//E# if statement\n //Register Reset button\n resetForm('.resetButton');\n}",
"init() {\n chrome.input.ime.onActivate.addListener(this.onActivate_.bind(this));\n chrome.input.ime.onDeactivated.addListener(this.onDeactivated_.bind(this));\n chrome.input.ime.onFocus.addListener(this.onFocus_.bind(this));\n chrome.input.ime.onBlur.addListener(this.onBlur_.bind(this));\n chrome.input.ime.onInputContextUpdate.addListener(\n this.onInputContextUpdate_.bind(this));\n chrome.input.ime.onKeyEvent.addListener(\n this.onKeyEvent_.bind(this), ['async']);\n chrome.input.ime.onReset.addListener(this.onReset_.bind(this));\n chrome.input.ime.onMenuItemActivated.addListener(\n this.onMenuItemActivated_.bind(this));\n this.connectChromeVox_();\n }",
"function addSkill() {\r\n // get TOTAL_FORMS element from Django management_form of Skill formset\r\n let totalSkillForms = document.getElementById(\"id_skill-TOTAL_FORMS\");\r\n // get MAX_NUM_FORMS element from Django management_form of Skill formset\r\n let maxSkillForms = document.getElementById(\"id_skill-MAX_NUM_FORMS\");\r\n // only add new Skill fieldset if MAX_NUM_FORMS not reached yet\r\n if (totalSkillForms.value !== maxSkillForms.value) {\r\n // get all Skill fieldsets\r\n const skillFieldSets = document.getElementsByClassName(\"skill\");\r\n // get last Skill fieldset\r\n const lastSkill = skillFieldSets[skillFieldSets.length - 1];\r\n // clone last Skill fieldset\r\n let clone = lastSkill.cloneNode(true);\r\n // replace upcounting number in clone inner HTML\r\n const count = String(parseInt(totalSkillForms.value) - 1);\r\n const regex = new RegExp(count, \"g\");\r\n clone.innerHTML = clone.innerHTML.replace(regex, totalSkillForms.value);\r\n // get DIV of Skill fieldsets\r\n let skills = document.getElementById(\"skills\");\r\n // append clone to DIV\r\n skills.appendChild(clone);\r\n // add Skill Value Validation Event to newly created Skill Value field\r\n addSkillValueValidationEvent(totalSkillForms.value);\r\n // increase TOTAL_FORMS element to comply with Django logic\r\n totalSkillForms.value = String(parseInt(totalSkillForms.value) + 1);\r\n } else {\r\n // deactivate add Skill button in case MAX_NUM_FORMS reached\r\n button = document.getElementById(\"addSkill\");\r\n button.setAttribute(\"disabled\", true);\r\n }\r\n }",
"function OnInitializeRespondee() {\n\n var attributes = getSecurityRequestAttributesForRespondee();\n\n // Display the current respondee type selection\n\n ShowRespondeeTypeSelection(attributes);\n\n\n // Apply the visibility / read-write rules as per functional specifications\n\n ApplyBusinessRulesForRespondee(attributes.stage, attributes.status, attributes.securityRequestOwner, attributes.currentEmployeeNo);\n\n /*\n * Check the visibility for the respondee response. \n * If visible, populate the registered respondees within the respondee drop-down list for selection.\n */\n\n InitializeRespondeeResponse(attributes);\n \n /*\n * Apply event handlers to the respondee form controls.\n */\n\n SetRespondeeEventHandlers();\n\n}",
"function init() {\n var elementsArray = getAllElementsFromSelectos(inputAutocompleteSelector);\n //addEventsToElements(elementsArray, \"keydown\", disableChatOnPressReturn);\n\n for (var i = 0; i < elementsArray.length; i++) {\n addEvent(elementsArray[i], \"focus\", disableChat);\n addEvent(elementsArray[i], \"blur\", enableChat);\n }\n }",
"#registerEventListeners() {\n this.#addOnFocusEventListener();\n this.#addOnHelpIconClickEventListener();\n }",
"function addFormListeners() {\n /** \n * Collection of form elements.\n *\n * @private\n * @property forms\n * @type Array\n * @default null\n * */\n var forms = null,\n /** \n * Index reference.\n *\n * @private\n * @property i\n * @type Number\n * @default NaN\n * */\n i = NaN;\n\n forms = document.getElementsByTagName('form');\n\n for (i = 0; i < forms.length; i += 1) {\n Utils.addEventHandler(forms[i], 'submit', onFormSubmit);\n }\n }",
"function onSignUpClicked (event) {\n let isValid = true;\n let userType = 'student';\n\n $(getClassName(userType, 'signUpFirstNameError')).hide()\n $(getClassName(userType, 'signUpLastNameError')).hide()\n $(getClassName(userType, 'signUpCountryCodeError')).hide()\n $(getClassName(userType, 'SignUpPhoneNumberError')).hide()\n $(getClassName(userType, 'SignUpEmailError')).hide()\n $(getClassName(userType, 'SignUpPasswordError')).hide()\n const firstName = $(getClassName(userType, 'signUpFirstName'))[0].value;\n const lastName = $(getClassName(userType, 'signUpLastName'))[0].value;\n const countryCode = $(getClassName(userType, 'signUpCountryCode'))[0].value;\n const phoneNumber = $(getClassName(userType, 'signUpPhoneNumber'))[0].value;\n const emailId = $(getClassName(userType, 'signUpEmail'))[0].value;\n const password = $(getClassName(userType, 'signUpPassword'))[0].value;\n if (!firstName) {\n $(getClassName(userType, 'signUpFirstNameError')).text('Please provide First Name');\n $(getClassName(userType, 'signUpFirstNameError')).show()\n isValid = false;\n }\n if (!lastName) {\n $(getClassName(userType, 'signUpLastNameError')).text('Please provide Last Name');\n $(getClassName(userType, 'signUpLastNameError')).show()\n isValid = false;\n }\n if (countryCode === 'none') {\n $(getClassName(userType, 'signUpCountryCodeError')).text('Please select country code');\n $(getClassName(userType, 'signUpCountryCodeError')).show()\n isValid = false;\n }\n if (phoneNumber && !isPhoneNumberValid(phoneNumber)) {\n $(getClassName(userType, 'SignUpPhoneNumberError')).text('Please add valid phone number');\n $(getClassName(userType, 'SignUpPhoneNumberError')).show()\n isValid = false;\n }\n if (!emailId) {\n $(getClassName(userType, 'SignUpEmailError')).text('Please provide email');\n $(getClassName(userType, 'SignUpEmailError')).show()\n isValid = false;\n }\n if (!password) {\n $(getClassName(userType, 'SignUpPasswordError')).text('Please provide password');\n $(getClassName(userType, 'SignUpPasswordError')).show()\n isValid = false;\n }\n\n if (isValid) {\n signUpAPI(userType, firstName, lastName, `${countryCode}${phoneNumber}`, emailId, password)\n }\n}",
"function setupClickListener(id, types) {\n var radioButton = document.getElementById(id);\n /*radioButton.addEventListener('click', function() {\n autocomplete.setTypes(types);\n });*/\n }",
"function atgValidation_initValidationObjects() {\n \n // Reinitialize the success variable\n isSuccess = true;\n \n for (var i = 0; i < currentValidationObjectArray.length; i++) {\n var validationId = currentValidationObjectArray[i];\n \n var validationObject = document.getElementById(validationId);\n if (validationObject != null) {\n validationObject.innerHTML = \"\";\n validationObject.style.display=\"none\";\n }\n } \n \n // After cleaning up the array, initialize it to an empty array\n currentValidationObjectArray = new Array();\n \n // Set the default Substitution Token\n if (validationCode.DEFAULT_SUBSTITUTION_TOKEN != null)\n constants.defaultSubstitutionToken = validationCode.DEFAULT_SUBSTITUTION_TOKEN;\n}",
"function createInput(name, surname, age, experience, profession, functionSelection, idEmployee) {\n let inputBox = document.getElementById('input_box');\n let nameInput = document.createElement('input');\n let nameLabel = document.createElement('p');\n let surnameInput = document.createElement('input');\n let surnameLabel = document.createElement('p');\n let ageInput = document.createElement('input');\n let ageLabel = document.createElement('p');\n let experienceInput = document.createElement('input');\n let experienceLabel = document.createElement('p');\n let professionInput = document.createElement('div');\n let buttonAccept = document.createElement('button');\n nameLabel.innerText = \"Name\";\n nameInput.value = name;\n surnameLabel.innerText = \"Surname\";\n surnameInput.value = surname;\n ageLabel.innerText = \"Age\";\n ageInput.value = age;\n experienceLabel.innerText = \"Experience\";\n experienceInput.value = experience;let nameInputChecked = false;\n let surnameInputChecked = false;\n let ageInputChecked = false;\n let experienceInputChecked = false;\n let nameAndSurnameRegExp = /[a-zA-Zа-яА-Я]/g;\n let experienceAndAgeRegExp = /[0-9]/g;\n nameInput.addEventListener(\"blur\",function () {\n nameInputChecked = dataChecking(nameInput.value, nameAndSurnameRegExp);\n checkedInput(nameInput, nameInputChecked);\n });\n surnameInput.addEventListener(\"blur\",function () {\n surnameInputChecked = dataChecking(surnameInput.value, nameAndSurnameRegExp);\n checkedInput(surnameInput, surnameInputChecked);\n });\n ageInput.addEventListener(\"blur\",function () {\n ageInputChecked = dataChecking(ageInput.value, experienceAndAgeRegExp);\n checkedInput(ageInput, ageInputChecked);\n });\n experienceInput.addEventListener(\"blur\",function () {\n experienceInputChecked = dataChecking(experienceInput.value, experienceAndAgeRegExp);\n checkedInput(experienceInput, experienceInputChecked);\n });\n buttonAccept.innerText = \"Accept\";\n buttonAccept.id = \"accept\";\n\n for(let i=1; i<5; i++){\n let checkbox = document.createElement('input');\n let labelProfession = document.createElement('label');\n checkbox.name = \"profession\";\n checkbox.type = \"radio\";\n switch (i) {\n case 1: checkbox.value = \"driver\";\n break;\n case 2: checkbox.value = \"assistant\";\n break;\n case 3: checkbox.value = \"chief\";\n break;\n case 4: checkbox.value = \"conductor\";\n break;\n }\n if(checkbox.value == profession){\n checkbox.checked = true;\n }\n labelProfession.innerHTML = checkbox.value;\n professionInput.appendChild(labelProfession);\n professionInput.appendChild(checkbox);\n }\n\n inputBox.appendChild(nameLabel);\n inputBox.appendChild(nameInput);\n inputBox.appendChild(surnameLabel);\n inputBox.appendChild(surnameInput);\n inputBox.appendChild(ageLabel);\n inputBox.appendChild(ageInput);\n inputBox.appendChild(experienceLabel);\n inputBox.appendChild(experienceInput);\n inputBox.appendChild(professionInput);\n inputBox.appendChild(buttonAccept);\n\n buttonAccept.addEventListener(\"click\", function () {\n let checked_profession;\n\n let radioButtons = document.getElementsByName('profession');\n for(let i=0; i<radioButtons.length; i++){\n if(radioButtons[i].checked){\n checked_profession = radioButtons[i].value;\n }\n }\n if(nameInputChecked == true && surnameInputChecked == true && ageInputChecked == true && experienceInputChecked == true){\n sendData(nameInput.value, surnameInput.value, ageInput.value, experienceInput.value, checked_profession, functionSelection, idEmployee);\n }\n });\n}",
"function setCategoryCheckboxesEventListener() {\n let categoryForm = document.getElementById('category-form');\n categoryForm.addEventListener('change', filterByCategory);\n}",
"function initDropdowns() {\n $('#question-button').on('click', dropdownHandler);\n $('#question-input').on('keyup', questionFilterFunction);\n $('#myPerson').on('keyup', peopleFilterFunction);\n}",
"function initSecondWizardPage() \n{\n var profileName = document.getElementById(\"profileName\");\n profileName.select();\n profileName.focus();\n\n // Initialize profile name validation.\n checkCurrentInput(profileName.value);\n}",
"#initLocaleInputs() {\n this.localeInputs.forEach((localeInput) => {\n localeInput.addEventListener('change', (event) => {\n const locale = localeInput.value;\n\n this.#setLocale(locale);\n });\n });\n }",
"function initWsuIdInputs(slctrInputs) {\n var $wsuIdInputs = $(slctrInputs).find(\"input[type='text']\");\n\t\t$wsuIdInputs.keydown(function(e) {\n var $this = $(this);\n var inputText = $this.val();\n\t\t\tif((e.keyCode < 48 || (e.keyCode > 57 && e.keyCode < 96) || e.keyCode > 105) &&\n\t\t\t !~[8, 9, 20, 35, 36, 37, 39, 46, 110, 144].indexOf(e.keyCode) &&\n\t\t\t !(e.keyCode == 86 && e.ctrlKey)) {\n\t\t\t\te.preventDefault();\n\t\t\t}\n\t\t\telse if (!~[8, 9, 20, 35, 36, 37, 39, 46, 110, 144].indexOf(e.keyCode) &&\n\t\t\t\t\tinputText.length >= 9) {\n\t\t\t\te.preventDefault();\n\t\t\t\talert(\"Note: WSU ID numbers are no greater than nine (9) digits in length.\");\n\t\t\t}\n\t\t});\n $wsuIdInputs.on(\"paste\", function (e) {\n var $this = $(this);\n\t\t\tvar clipboardData = e.originalEvent.clipboardData || window.clipboardData;\n\t\t\tvar inputText = clipboardData.getData('Text');\n var regExMask = /[^0-9]+/g;\n if (regExMask.exec(inputText) != null) {\n\t\t\t\tvar errorMsg = \"Note: WSU ID numbers can only contain digits.\";\n\t\t\t\te.stopPropagation();\n\t\t\t\te.preventDefault();\n $this.val(inputText.replace(regExMask, \"\"));\n inputText = $this.val();\n\t\t\t\tif (inputText.length > 9) {\n\t\t\t\t\t$this.val(inputText.slice(0,9));\n\t\t\t\t\terrorMsg += \" Also, they must be no greater than nine (9) digits in length.\";\n\t\t\t\t}\n\t\t\t\terrorMsg += \" What you pasted will automatically be corrected; please check the \"\n\t\t\t\t\t+ \"result to see if further corrections are needed.\"\n\t\t\t\talert(errorMsg);\n }\n else if (inputText.length > 9) {\n\t\t\t\te.stopPropagation();\n\t\t\t\te.preventDefault();\n $this.val(inputText.slice(0,9));\n\t\t\t\talert(\"WSU ID numbers are no greater than nine (9) digits in length. What you \"\n\t\t\t\t\t+ \"pasted will automatically be corrected; please check the result to see if \"\n\t\t\t\t\t+ \"further corrections are needed.\");\n }\n });\n $wsuIdInputs.blur(function () {\n var $this = $(this);\n var regExFinalPttrn = /(?:^[0-9]{8}$)|(?:^0[0-9]{8}$)/;\n var inputText = $this.val();\n\t\t\tif (inputText != \"\") {\n\t\t\t\tif (regExFinalPttrn.exec(inputText) == null) {\t\t\t\t\t\n\t\t\t\t\t$this.val(\"\");\n\t\t\t\t\talert(\"Please try again: when the leading zero is included, WSU ID numbers are \"\n\t\t\t\t\t\t+ \"nine (9) digits long. (You can also drop the leading zero and enter in \"\n\t\t\t\t\t\t+ \"eight (8) digits.)\");\n\t\t\t\t}\n\t\t\t}\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update line, column, and offset based on `value`. | function updatePosition(subvalue) {
var lastIndex = -1;
var index = subvalue.indexOf('\n');
while (index !== -1) {
line++;
lastIndex = index;
index = subvalue.indexOf('\n', index + 1);
}
if (lastIndex === -1) {
column += subvalue.length;
} else {
column = subvalue.length - lastIndex;
}
if (line in offset) {
if (lastIndex !== -1) {
column += offset[line];
} else if (column <= offset[line]) {
column = offset[line] + 1;
}
}
} | [
"function updatePosition(subvalue) {\n var lastIndex = -1;\n var index = subvalue.indexOf('\\n');\n\n while (index !== -1) {\n line++;\n lastIndex = index;\n index = subvalue.indexOf('\\n', index + 1);\n }\n\n if (lastIndex === -1) {\n column += subvalue.length;\n } else {\n column = subvalue.length - lastIndex;\n }\n\n if (line in offset) {\n if (lastIndex !== -1) {\n column += offset[line];\n } else if (column <= offset[line]) {\n column = offset[line] + 1;\n }\n }\n }",
"incrLine() {\n const { line, column } = this;\n return Position.of(line + 1, column);\n }",
"setat(row,column,value)\n\t{\n\t\tif (row >= 0 && row < 4 && column >= 0 && column < 4 )\n\t\t\tthis._data[row][column] = value;\n\t}",
"set(x, y, value) {\n this.content[y * this.width + x] = value;\n }",
"set(x, y, value) {\n const index = this.linear(x, y);\n\n return new Matrix2D(this.xSize, this.ySize, [\n ...this.data.slice(0, index),\n value,\n ...this.data.slice(index + 1)\n ])\n }",
"function changeEyePosition(value) {\n let relativeDeviation = ((value / maxSlider) * 2 * eyedeviation) - eyedeviation;\n // console.log(relativeDeviation, lefteyeInitialPosX);\n lefteye[0].value = parseInt(lefteyeInitialPosX) + (relativeDeviation);\n righteye[0].value = parseInt(righteyeInitialPosX) + (relativeDeviation);\n}",
"_updateKnobPosition() {\n this._setKnobPosition(this._valueToPosition(this.getValue()));\n }",
"function set_board_pixel(board, x, y, value)\n{\n\tvar index = x + y * get_game_width();\n\tboard[index] = value;\n}",
"batchUpdate() {\n let { row, colStart, colEnd } = this.pendingUpdate;\n const { cursor } = this.screen;\n\n this.pendingUpdate.row = cursor.row;\n this.pendingUpdate.colStart = this.pendingUpdate.colEnd = cursor.col;\n\n // Skip cells up to number column width so we don't output line numbers\n colStart = Math.max(this.lineNumberColumns, colStart);\n\n const lineNumberString = this.screen.cells[row].slice(0, this.lineNumberColumns).join('');\n // If start of number string is '~' then we have reached the end of the\n // file. Ignore changes is the line number column and any changes on\n // rows outside of the main text buffer (eg. the status line and\n // command line)\n if (lineNumberString[0] === '~' || colStart >= colEnd || row >= (this.statusLineNumber)) {\n return;\n }\n\n const text = this.screen.cells[row].slice(colStart, colEnd).join('');\n // As the cells as just the visible rows we need to translate the cell\n // row number to the actual line number. We have line numbers enabled\n // to easily allow this - extract the line number from the cell\n // contents.\n const lineNumber = Number(lineNumberString) - 1;\n const range = [\n [lineNumber, colStart - this.lineNumberColumns],\n [lineNumber, colEnd - this.lineNumberColumns]\n ];\n\n this.batch.push([range, text]);\n }",
"_valueYChanged(value) {\n if (this.enableY) {\n this._handle.style.top = (this._canvas.scrollHeight)\n * ((value - this.minY) / (this.maxY - this.minY)) + 'px';\n }\n }",
"function setDebugLocation(ctx, line) {\n let { ed } = ctx;\n let meta = dbginfo.get(ed);\n\n clearDebugLocation(ctx);\n\n meta.debugLocation = line;\n ed.addMarker(line, \"breakpoints\", \"debugLocation\");\n ed.addLineClass(line, \"debug-line\");\n}",
"cursorSet(cursor, value) {\n if (cursor.buffer)\n this.setBuffer(cursor.buffer.buffer, cursor.index, value)\n else this.map.set(cursor.tree, value)\n }",
"updatePosition(x, y) {\r\n\t\tthis.x = x;\r\n\t\tthis.y = y;\r\n\t\t\t\r\n\t\tthis.currentTileRow = Math.floor( (this.y-this.levelGrid.yCanvas) / this.tileSideScale);\r\n\t\tthis.currentTileColumn = Math.floor( (this.x-this.levelGrid.xCanvas) / this.tileSideScale);\r\n\t}",
"moveRow(offset, options) {\n this._withTable(options, ({ range, lines, table, focus }) => {\n let newFocus = focus;\n // complete\n const completed = formatter.completeTable(table, options);\n if (completed.delimiterInserted && newFocus.row > 0) {\n newFocus = newFocus.setRow(newFocus.row + 1);\n }\n // move row\n let altered = completed.table;\n if (newFocus.row > 1) {\n const dest = Math.min(Math.max(newFocus.row + offset, 2), altered.getHeight() - 1);\n altered = formatter.moveRow(altered, newFocus.row, dest);\n newFocus = newFocus.setRow(dest);\n }\n // format\n const formatted = formatter.formatTable(altered, options);\n newFocus = newFocus.setOffset(exports._computeNewOffset(newFocus, altered, formatted, false));\n // apply\n this._textEditor.transact(() => {\n this._updateLines(range.start.row, range.end.row + 1, formatted.table.toLines(), lines);\n this._moveToFocus(range.start.row, formatted.table, newFocus);\n });\n this.resetSmartCursor();\n });\n }",
"function moveTo(position, value) {\r\n\t\tif (api.flip) value = 1 - value;\r\n\t\tcenter[api.orientation] = position[api.orientation] + ((0.5 - value) * api.size);\r\n\t}",
"add(xPos, yPos, value) {\n const x = \"x\" + xPos;\n const y = \"y\" + yPos;\n // Check if there is a value at this x position\n if (typeof this.locations[x] == 'undefined') {\n // Create new array for this x position\n this.locations[x] = [];\n }\n // Check if there is a value at this x and y position\n if (typeof this.locations[x][y] == 'undefined') {\n // Create new entry\n this.locations[x][y] = value;\n } else {\n //Append value to existing entry \n this.locations[x][y] += value;\n }\n }",
"updateSeekBar(seekBar, seekBarValue) {\n seekBar.value = seekBarValue;\n \n }",
"_valueXChanged(value) {\n if (this.enableX) {\n this._handle.style.left = (this._canvas.scrollWidth)\n * ((value - this.minX) / (this.maxX - this.minX)) + 'px';\n }\n }",
"set(x, y, value) {\n if(!this.grid[x]) {\n this.grid[x] = []\n }\n this.grid[x][y] = value\n }",
"placeAt(xx, yy, obj) {\r\n var xc = this.cw * xx + this.cw / 2;\r\n var yc = this.ch * yy + this.ch / 2;\r\n obj.x = xc;\r\n obj.y = yc;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function checks if the syntax for getQuestionAndAnswersByUsername | function getQuestionAndAnswersByUsername(req,res)
{
return onlyBy(req, 'username', true) && checkTable(req,'question_and_answer')
} | [
"function isAnswer() {\r\n\tif (!answer.branches)\r\n\t\treturn false;\r\n\t\t\r\n\tvar i = 0;\r\n\tfor (i in answer.branches) {\r\n\t\tvar branch = answer.branches[i];\r\n\t\tbranch.any = true;\r\n\t\tif (branch.words) {\r\n\t\t\tvar nb = compareSet(branch,userInput.list);\r\n\t\t\t/* console.log(\"branch: \" + branch.words,\r\n\t\t\t\t\t\t\"input: \" + userInput.list,\r\n\t\t\t\t\t\t\"matched: \" + nb); */\r\n\t\t\tif(nb >= 0.5) {\r\n\t\t\t\tbotAction.next = getAction(branch.action);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tbotAction.next = getAction(branch.action);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif(!answer.wait){\r\n\t\tanswer = {};\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\treturn true;\r\n}",
"function evaluate(userAnswer)\n{\n let correctAnswer = QUIZQUESTIONS[start].correct;\n\n if (userAnswer == correctAnswer)\n {\n return true;\n }\n else\n {\n return false;\n }\n}",
"function checkBabyBot(words){\n return words.includes(\"@\" + configs.bot.username)\n || words.includes(\"@pete_bot_\")\n || words.includes(\"@pete_bot\")\n || words.includes(\"pete_bot\")\n || words.includes(\"pete_bot_\")\n || words.includes(\"pete_bot__\")\n || words.includes(\"@pete_bot_\")\n || words.includes(\"@Pete_Bot_\")\n || words.includes(\"@Pete_bot_\")\n || words.includes(\"Pete_Bot_\")\n || words.includes(\"Pete_bot_\")\n}",
"function getRightAnswers() {\n}",
"function checkRequirements() {\n if (firstPassword.length < 5) {\n firstInputIssuesTracker.add(\"كلمه المرور اقل من 5 حروف\");\n } else if (firstPassword.length > 15) {\n firstInputIssuesTracker.add(\"كلمه المرور اكبر من 5 حروف\");\n }\n\n \n\n if (!firstPassword.match(/[a-z | A-Z | ا-ي]/g)) {\n firstInputIssuesTracker.add(\"الرجاء استخدام الحروف والارقام\");\n }\n\n \n\n var illegalCharacterGroup = firstPassword.match(/[^A-z0-9أ-ي!\\@\\#\\$\\%\\^\\&\\*]/g)\n if (illegalCharacterGroup) {\n illegalCharacterGroup.forEach(function (illegalChar) {\n firstInputIssuesTracker.add(\"غير مسموح بهذه الرموز: \" + illegalChar);\n });\n }\n }",
"function isValidWhoQuesion(answer, verb) {\n var ans = answer.split(' ');\n count = 0;\n for (var a of ans) {\n if (a == verb) {\n count += 1;\n }\n if (count > 1) {\n return false;\n }\n }\n return true;\n}",
"function getQuestion() {\n \n \n }",
"function checkQuestionnaires(game) {\n var names = [];\n var positions;\n var questions;\n for (var questionnaireName in game.questionnaires) {\n names.push(questionnaireName);\n // Positions array must exist and have only numiercal entries\n if (game.questionnaires[questionnaireName].positions) {\n positions = game.questionnaires[questionnaireName].positions;\n if (typeof positions === \"object\") {\n // Go through all postions\n if (positions.length) {\n for (var p = 0; p < positions.length; p++) {\n if (typeof positions[p] !== \"number\") {\n errors.push(\"Questionnaire \" + questionnaireName + \": \" + \"A position can only be a numerical value. \");\n break;\n }\n }\n } else {\n errors.push(\"Questionnaire \" + questionnaireName + \": \" + \"At least one position must be defined\");\n }\n } else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"The positions parameter must be an array. \");\n }\n } else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"Every questionnaire must define the positions array. \");\n }\n // A questionnaire must define a questions array\n if (game.questionnaires[questionnaireName].questions) {\n questions = game.questionnaires[questionnaireName].questions;\n if (typeof questions === \"object\") {\n // A questionnaire must define at least one question\n if (questions.length) {\n // Go through all questions\n var answer;\n var questionName;\n var questionText;\n for (var q = 0; q < questions.length; q++) {\n answer = questions[q].answer;\n // Answer attribute must be \"string\", \"number\" or array\n if (answer === \"string\" || answer === \"number\" || \n typeof answer === \"object\") {\n if (typeof answer === \"object\") {\n if (!answer.length) {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"A predefined answer must give at least one option:\");\n }\n }\n }\n else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+'answer must be \"string\", \"number\" or an array');\n }\n // The attribute questionName must be a string\n questionName = questions[q].questionName;\n if (typeof questionName !== \"string\") {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"The questionName must be of type String. \");\n }\n // The attribute questionText must be a string\n questionText = questions[q].questionText;\n if (typeof questionText !== \"string\") {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"The questionText must be of type String. \");\n }\n }\n }\n else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\n \"A questionnaire must define at least one question. The questionnare object must be an array.\");\n }\n } else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"The questions parameter must be an array. \");\n }\n } else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"A questionnaire must define the questions array. \");\n }\n // end for\n }\n names.sort();\n for (var n = 0; n < names.length; n++) {\n if (names[n] === names[n + 1]) {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+ \"is not unique. All questionnaire names must be unique\");\n }\n }\n }",
"function checkProvidedAnswer(question, answer){\n var checked = false\n if(answer.answerId == question.providedAnswer){\n checked = true\n }\n return checked\n }",
"function informationChecker (Username, Reason) {\n if (Username === '' || Reason === '') {\n return 'Please enter all information'\n } else {\n return 'Termination poll regarding ' + Username + ' successfully created for this reason: ' + Reason\n }\n}",
"function validUsername() {\n var userName = prompt(\"Enter username\");\n var len = userName.split(\"\");\n for(i = 0; i < len.length; i++) {\n if( (userName.slice(i,i+1) == \"@\") || (userName.slice(i,i+1) == \".\") || (userName.slice(i,i+1) == \"!\") ) {\n document.write(\"Invalid\");\n break;\n }\n }\n\n}",
"async function isUsernameAvailable(username) {\n const url = `https://passport.twitch.tv/usernames/${username}?users_service=true`;\n const response = await axios.head(url);\n\n return response.status === 204;\n }",
"function testResponse (res, keyword) {\n // for (var i=0; i<keyword.length; i++) {\n // if (keyword[i].test(res)) {\n // return true;\n // }\n // }\n // if (kyle.test(res) || davis.test(res)) {\n // return true;\n // }\n // if (name===\"Bebe Ballo\" || name===\"Shriyans Lenkala\" || name===\"Keyshawn Ebanks\") { \n // return true;\n // }\n return false;\n}",
"function getPromptQuestions (argvOptions, inputArgs) {\n var questions = [];\n for (var argI in argvOptions) {\n if (inputArgs[argvOptions[argI].name] === undefined) {\n switch (argvOptions[argI].name) {\n case 'skillname':\n questions.push({\n name: 'skillname',\n type: 'input',\n message: 'Skill name:',\n validate: function (value) {\n if (value.length) {\n return true;\n } else {\n return 'Please enter the skill name.';\n }\n }\n });\n break;\n case 'skillVersion':\n questions.push({\n name: 'skillversion',\n type: 'input',\n message: 'Enter the skill version:',\n validate: function (value) {\n if (value.length) {\n return true;\n } else {\n return 'Please provide a skill version.';\n }\n }\n });\n break;\n case 'entityname':\n questions.push({\n name: 'entityname',\n type: 'input',\n message: 'Entity name:',\n validate: function (value) {\n if (value.length) {\n return true;\n } else {\n return 'Please enter the entity name.';\n }\n }\n });\n break;\n case 'datapath':\n questions.push({\n name: 'datapath',\n type: 'input',\n message: 'Full patch file path:',\n validate: function (value) {\n if (value.length) {\n const path = (value.indexOf('~/') === 0) ? value.replace('~', os.homedir()) : value;\n if (!fs.existsSync(path)) {\n return value + ' doesn\\'t exist.';\n }\n return true;\n } else {\n return 'Please enter the full patch file path.';\n }\n }\n });\n break;\n case 'configpath':\n questions.push({\n name: 'configpath',\n type: 'input',\n message: 'Full config file path:',\n validate: function (value) {\n if (value.length) {\n const path = (value.indexOf('~/') === 0) ? value.replace('~', os.homedir()) : value;\n if (!fs.existsSync(path)) {\n return value + ' doesn\\'t exist.';\n }\n return true;\n } else {\n return 'Please enter the full configuration file path.';\n }\n }\n });\n break;\n };\n };\n };\n return questions;\n}",
"function validateUserAnswer(planet, id) {\n const position = planetToNumber(planet); // find planet position in array\n const userAnswer = $(\"input[name=user-answers]:checked\").parent('label').text().trim(); // find what answer the user picked\n let correctAnswer = ''; // placeholder for correct answer\n if (STORE.questionNumber === 0) {\n return true;\n }\n else {\n for (let i = 0; i <= 2; i++) { // loop through array until question is found\n currId = STORE.planets[position][planet][i].id; // current id to look at\n if (currId === id) { // if it matches passed id\n correctAnswer = STORE.planets[position][planet][i].correct; // set correct answer\n }\n }\n\n if (userAnswer === correctAnswer) { // if user answer is right return true, if it is not return false\n return true;\n }\n else\n return false;\n }\n\n}",
"function validUsername(username) {\n return (username.trim().length) >= 3;\n}",
"isValidInputParams(context, word) {\n if (context < 0) {\n console.log(`Error: Context value ${context} should be zero or greater`);\n return false;\n }\n\n if (typeof this.mapWords[word] === 'undefined') {\n console.log(`Error: Word \"${word}\" is not present in the recording`);\n return false;\n }\n\n return true;\n }",
"function allAreAnswered(questions){\n if(questions.status===1){\n return true\n }\n}",
"function checkRequirements() {\n if (password!==repeatPassword && repeatPassword.length > 0) {\n firstInputIssuesTracker.add(\"passwords must match\");\n }\n\n if (password.length < 8) {\n firstInputIssuesTracker.add(\"fewer than 8 characters\");\n } else if (password.length > 100) {\n firstInputIssuesTracker.add(\"greater than 100 characters\");\n }\n\n if (!password.match(/[\\!\\@\\#\\$\\%\\^\\&\\*]/g)) {\n firstInputIssuesTracker.add(\"missing a symbol (!, @, #, $, %, ^, &, *)\");\n }\n\n if (!password.match(/\\d/g)) {\n firstInputIssuesTracker.add(\"missing a number\");\n }\n\n if (!password.match(/[a-z]/g)) {\n firstInputIssuesTracker.add(\"missing a lowercase letter\");\n }\n\n if (!password.match(/[A-Z]/g)) {\n firstInputIssuesTracker.add(\"missing an uppercase letter\");\n }\n\n var illegalCharacterGroup = password.match(/[^A-z0-9\\!\\@\\#\\$\\%\\^\\&\\*]/g)\n if (illegalCharacterGroup) {\n\n illegalCharacterGroup.forEach(function (illegalChar) {\n firstInputIssuesTracker.add(\"includes illegal character: \" + illegalChar);\n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function for starting the receiver check interval if it's not already running. This function also takes care of stopping the interval when it is done. The receiver check interval is responsible for checking stale ChunkReceivers and stale pending reports. | function startCheckInterval() {
if (receiverCheckInterval) {
return;
}
receiverCheckInterval = setInterval(() => {
const oldestTimestamp = Date.now() - RCV_TIMEOUT;
for (const [messageId, receiver] of chunkReceivers) {
if (receiver.lastReceive < oldestTimestamp) {
MsrpSdk.Logger.warn(`[SocketHandler]: Timed out waiting for chunks for ${messageId}`);
// Clean up the receiver
receiver.abort();
chunkReceivers.delete(messageId);
MsrpSdk.Logger.debug(`[SocketHandler]: Removed receiver for ${messageId}. Num active receivers: ${chunkReceivers.size}`);
}
}
for (const [messageId, pendingData] of pendingReports) {
if (pendingData.timestamp < oldestTimestamp) {
MsrpSdk.Logger.warn(`[SocketHandler]: Timed out waiting to send report for ${messageId}`);
sendPendingReport(messageId, MsrpSdk.Status.REQUEST_TIMEOUT);
MsrpSdk.Logger.debug(`[SocketHandler]: Sent report for ${messageId}. Num pending reports: ${chunkReceivers.size}`);
}
}
// Stop the receiver poll when done receiving chunks / sending reports
if (chunkReceivers.size === 0 && pendingReports.size === 0) {
clearInterval(receiverCheckInterval);
receiverCheckInterval = null;
}
}, AUDIT_INTERVAL);
} | [
"function initPolling() {\n if (angular.isDefined(pollingInterval)) {\n return;\n }\n\n // Activate listener\n $rootScope.$on('syncUnreadMessagesCount', poll);\n\n // Check for unread messages in intervals\n setPollingInterval();\n }",
"function setBufferChecker() {\n bufferChecker = window.setInterval(function() {\n var allBuffered = true;\n\n var currTime = getCurrentTime(masterVideoId);\n\n for (var i = 0; i < videoIds.length; ++i) {\n var bufferedTimeRange = getBufferTimeRange(videoIds[i]);\n if (bufferedTimeRange) {\n var duration = getDuration(videoIds[i]);\n var currTimePlusBuffer = getCurrentTime(videoIds[i]) + bufferInterval;\n var buffered = false;\n for (j = 0;\n (j < bufferedTimeRange.length) && !buffered; ++j) {\n currTimePlusBuffer = (currTimePlusBuffer >= duration) ? duration : currTimePlusBuffer;\n if (isInInterval(currTimePlusBuffer, bufferedTimeRange.start(j), bufferedTimeRange.end(j))) {\n buffered = true;\n }\n }\n allBuffered = allBuffered && buffered;\n } else {\n // Do something?\n }\n }\n\n if (!allBuffered) {\n playWhenBuffered = true;\n ignoreNextPause = true;\n for (var i = 0; i < videoIds.length; ++i) {\n pause(videoIds[i]);\n }\n hitPauseWhileBuffering = false;\n $(document).trigger(\"sjs:buffering\", []);\n } else if (playWhenBuffered && !hitPauseWhileBuffering) {\n playWhenBuffered = false;\n play(masterVideoId);\n hitPauseWhileBuffering = false;\n $(document).trigger(\"sjs:bufferedAndAutoplaying\", []);\n } else if (playWhenBuffered) {\n playWhenBuffered = false;\n $(document).trigger(\"sjs:bufferedButNotAutoplaying\", []);\n }\n }, checkBufferInterval);\n }",
"function checkUserNotfication(){\n clearInterval(getNotificationInterval);\n getNotificationInterval =\"\";\n\tgetUserNotificationSession();\n\tgetNotificationInterval = setInterval(function(){\n\t\tgetUserNotificationSession();\n\t},60000);\n}",
"function start() {\n new CronJob(\n '00 * * * * *', // run every minute\n () => {\n const currentTime = new Date();\n // which code to run\n console.log(\n `Running Send Notifications Worker for ${moment(currentTime).format()}`\n );\n notifications.checkAndSendNecessaryNotifications(currentTime);\n },\n null, // don't run anything after finishing the job\n true, // start the timer\n '' // use default timezone\n );\n}",
"onInterval() {\n if (this.queue.length <= 0) {\n this.wait();\n return;\n }\n\n if (this.running) {\n const next = this.queue.dequeue();\n next.run();\n }\n }",
"function startMailReceiver(callback) {\n debug(\"startMailReceiver\");\n userModule.find({ access: \"IN('guest','full')\" }, function initUsers(err, result) {\n if (err) {\n return callback(new Error(\"Error during User Initialising for Mail \" + err.message));\n }\n mailReceiver.initialise(result);\n logger.info(\"Mail Receiver initialised.\");\n return callback();\n });\n}",
"function check() {\n clearTimeout(timer)\n\n if (device.present) {\n // We might get multiple status updates in rapid succession,\n // so let's wait for a while\n switch (device.type) {\n case 'device':\n case 'emulator':\n willStop = false\n timer = setTimeout(work, 100)\n break\n default:\n willStop = true\n timer = setTimeout(stop, 100)\n break\n }\n }\n else {\n willStop = true\n stop()\n }\n }",
"start(){\n\t\t// Run immediately to avoid having to wait for the first timeout\n\t\tthis.onUpdate();\n\n\t\tvar updater = this.onUpdate.bind(this);\n\t\tthis.interval = setInterval(updater, this.updateInterval);\n\t}",
"start() {\n if (!this.stop) return\n this.stop = false\n this.__poll()\n }",
"registerAutoWorker(){\r\n var functionPtr = Fatusjs.autoWorker;\r\n if(!this.autoInterval) {\r\n this.autoInterval = setInterval(\r\n functionPtr,\r\n 30000\r\n );\r\n }\r\n }",
"cycleInterval() {\n this.cycleTimer = new cycleTimer(() => {\n this.send(this.cycleCommand, this.cyclePhase, this.cycleData, this.cycleKey, this.cycleNonce);\n this.cycleNonce += 1;\n\n // Don't start again until message response is recieved?\n this.cycleInterval();\n }, this.cycleDelay);\n }",
"autoStart() {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n return this.config.autoStartRls && this.start().then(() => true);\r\n });\r\n }",
"startPolling() {\n if (!this.intervalId) {\n this.intervalId = setInterval(() => {\n if (!this.state.jobInfo) {\n clearInterval(this.intervalId);\n return this.emit('finalState', this.state);\n }\n this.getJobInfo((err) => {\n if (err) return this.emit('pollingError', err);\n this.getBatchInfos((err) => {\n if (err) return this.emit('pollingError', err);\n if (this.isJobFinalState() && this.isBatchFinalState()) {\n // TODO logic will need to change when we implement bulk\n // query PK chunking.\n if (this.state.jobInfo.operation === 'query') {\n this.getBatchResult(\n this.state.batchInfos[0].id,\n (err) => {\n if (err)\n return this.emit('pollingError', err);\n this.getQueryResult()\n .on('data', () => {\n clearInterval(this.intervalId);\n this.emit('finalState', this.state);\n })\n .on('error', (err) => {\n this.emit('pollingError', err);\n });\n });\n } else {\n clearInterval(this.intervalId);\n this.emit('finalState', this.state);\n }\n } else {\n this.emit('currentState', this.state);\n }\n\n });\n });\n }, 7000); // XXX WARNING TODO\n // Had to up polling interval to 7000 or else we die before we\n // start to do anything. must have missed a callback somewhere.\n // maybe false alarm.\n }\n }",
"_createWatcher() {\n const _watcher = Looper.create({\n immediate: true,\n });\n _watcher.on('tick', () => safeExec(this, 'fetch'));\n\n this.set('_watcher', _watcher);\n }",
"function startReportingActivity() {\n var id = Web.setInterval(function () {\n if (self.active()) {\n ucwa.send('POST', { rel: 'reportMyActivity' }, {\n nobatch: true\n }).catch(function (err) {\n // After a long period of inactivity, the connection with UCWA is usually lost.\n // While the connection is being restored, MePerson resends POST /makeMeAvailable.\n // However this periodic timer doesn't know about that logic and keeps sending\n // POST /reportMyActivity as usual. If the timer happens to wake up before the\n // /makeMeAvailable is completed, UCWA will reject this /reportMyActivity with a\n // 409.MakeMeAvailableRequired error.\n if (err && err.code == 'RequestFailed' && err.rsp.status == 409)\n return;\n debug.log('%c reportMyActivity stopped', 'color:red;font-weight:bold', err);\n Web.clearInterval(id);\n self.active(false, err);\n });\n }\n }, 3 * 60 * 1000);\n }",
"_startPollingData() {\n this._pollDataInterval = setInterval(() => this._getBalance(), 3000);\n\n // We run it once immediately so we don't have to wait for it\n this._getBalance();\n }",
"function startInterval(){\n /* Run the interval every seconde */\n var interval = setInterval(fn60sec,1000);\n /* Run the interval every minute */\n //interval = setInterval(fn60sec, 60 * 1000);\n }",
"_startPingInterval () {\n const setPongTimeout = () => {\n this._pongTimeout = setTimeout(\n () => this._reconnect(),\n this._options.pongTimeout\n )\n }\n\n this._pingInterval = setInterval(\n () => {\n this.ping()\n setPongTimeout()\n },\n this._options.pingInterval\n )\n }",
"function startTimer(tabId, title) {\n if (!tabIntervals[tabId]) {\n\n var intervalID = window.setInterval(function () {\n // This will call the onMessage event handler on the tab with the given tabId\n chrome.tabs.sendMessage(tabId, { action: \"getDom\" }, function (response) {\n if (response === \"finished\") {\n stopTimer(tabId);\n } else if (response === \"timeout\") {\n stopTimer(tabId);\n window.setTimeout(function () {\n startTimer(tabId);\n }, 10000);\n }\n });\n }, 500);\n tabIntervals[tabId] = { intervalID: intervalID, title: title };\n }\n else {\n alert('Already watching - ' + title);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finalize one payment method registration [BETA] [See on api.ovh.com]( | FinalizeOnePaymentMethodRegistration(paymentMethodId, expirationMonth, expirationYear, formSessionId, registrationId) {
let url = `/me/payment/method/${paymentMethodId}/finalize`;
return this.client.request('POST', url, { expirationMonth, expirationYear, formSessionId, registrationId });
} | [
"function submitPaymentJSON() {\n var order = Order.get(request.httpParameterMap.order_id.stringValue);\n if (!order.object || request.httpParameterMap.order_token.stringValue !== order.getOrderToken()) {\n app.getView().render('checkout/components/faults');\n return;\n }\n session.forms.billing.paymentMethods.clearFormElement();\n var requestObject = JSON.parse(request.httpParameterMap.requestBodyAsString);\n var form = session.forms.billing.paymentMethods;\n for (var requestObjectItem in requestObject) {\n var asyncPaymentMethodResponse = requestObject[requestObjectItem];\n var terms = requestObjectItem.split('_');\n if (terms[0] === 'creditCard') {\n var value = terms[1] === 'month' || terms[1] === 'year' ? Number(asyncPaymentMethodResponse) : asyncPaymentMethodResponse;\n form.creditCard[terms[1]].setValue(value);\n } else if (terms[0] === 'selectedPaymentMethodID') {\n form.selectedPaymentMethodID.setValue(asyncPaymentMethodResponse);\n }\n }\n if (app.getController('COBilling').HandlePaymentSelection('cart').error || handlePayments().error) {\n app.getView().render('checkout/components/faults');\n return;\n }\n app.getView().render('checkout/components/payment_methods_success');\n}",
"function finishRegistration() {\n if(!addressChosen) {\n alert(\"Please unlock your Ethereum address\");\n return;\n }\n\n if(state != 1) {\n alert(\"Please wait until Registration Phase\");\n return;\n }\n\n if(myvotingAddr.totalregistered() < 3) {\n alert(\"Election cannot begin until there is 3 or more registered voters\");\n return;\n }\n\n\n web3.personal.unlockAccount(addr,password);\n\n res = myvotingAddr.finishRegistrationPhase.sendTransaction({from:web3.eth.accounts[accountindex], gas: 4200000});\n document.getElementById(\"finishRegistration\").innerHTML = \"Waiting for Ethereum to confirm that Registration has finished\";\n\n //txlist(\"Finish Registration Phase: \" + res);\n}",
"ChallengeOnePaymentMethod(challenge, paymentMethodId) {\n let url = `/me/payment/method/${paymentMethodId}/challenge`;\n return this.client.request('POST', url, { challenge });\n }",
"function fillPromoRegisterFromCreateProfile() {\n\t$('#emailIdPromoCode').val($(\"#emailIdChkOut\").val());\n\t$('#confrmEmailIdPromoCode').val($(\"#confrmEmailIdChkOut\").val());\n\t$('#passwordPromoCode').val($(\"#passwordChkOut\").val());\n\t$('#mobileNoPromoCode').val($(\"#mobileNoChkOut\").val());\n\t$('#zipCodePromoCode').val($(\"#zipCodeChkOut\").val());\n\t$('#promoCodeDiscount1').val($(\"#promoCodeDiscount2\").val());\n\tif ($('#chkOptInEnhCreatProf').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', false);\n\t}\n\tclearFormField(\"createAccountBoxChkOut\");\n\t$(\"#createAccountBoxChkOut\").hide();\n\tclearIntervalApp(chkRegisterBtnCount);\n}",
"getManualPaymentMethod() {\n const pm = get(this.props.data, 'Collective.host.settings.paymentMethods.manual');\n if (!pm || get(this.state, 'stepDetails.interval')) {\n return null;\n }\n\n return {\n ...pm,\n instructions: this.props.intl.formatMessage(\n {\n id: 'host.paymentMethod.manual.instructions',\n defaultMessage:\n 'Instructions to make the payment of {amount} will be sent to your email address {email}. Your order will be pending until the funds have been received by the host ({host}).',\n },\n {\n amount: formatCurrency(get(this.state, 'stepDetails.totalAmount'), this.getCurrency()),\n email: get(this.props, 'LoggedInUser.email', ''),\n collective: get(this.props, 'loggedInUser.collective.slug', ''),\n host: get(this.props.data, 'Collective.host.name'),\n TierId: get(this.getTier(), 'id'),\n },\n ),\n };\n }",
"static updatePaymentResponseStructure(response) {\n var authResp = response.payment.authentication;\n response.method = authResp.method;\n response.url = authResp.url;\n\n if (response.method == \"POST\") {\n response.params = Array();\n\n for (var key of Object.values(Object.keys(authResp.params))) {\n response.params[key] = authResp.params[key];\n }\n }\n\n delete response.payment;\n return response;\n }",
"teardownPaymentForm() {\n // Safety check to make sure that there is a payment form to destroy;\n // otherwise, skip this step.\n if (this.paymentForm) {\n this.paymentForm.destroy();\n this.set('paymentForm', null);\n }\n\n return undefined;\n }",
"function Process() {\n var results = {};\n var arr = request.httpParameters.keySet().toArray();\n arr.filter(function (el) {\n results[el] = request.httpParameters.get(el).toLocaleString();\n return false;\n })\n\n var verificationObj = {\n ref: results.REF,\n returnmac: results.RETURNMAC,\n eci: results.ECI,\n amount: results.AMOUNT,\n currencycode: results.CURRENCYCODE,\n authorizationcode: results.AUTHORISATIONCODE,\n avsresult: results.AVSRESULT,\n cvsresult: results.CVVRESULT,\n fraudresult: results.FRAUDRESULT,\n externalreference: results.FRAUDRESULT,\n hostedCheckoutId: results.hostedCheckoutId\n\n }\n\n var order = session.getPrivacy().pendingOrder;\n var orderNo = session.getPrivacy().pendingOrderNo;\n var returnmac = session.getPrivacy().payment3DSCode;\n\n var cancelOrder = true;\n\n if (verificationObj.returnmac == returnmac) {\n var result = null;\n if(verificationObj.hostedCheckoutId != null){\n result = IngenicoPayments.getHostedPaymentStatus(verificationObj.hostedCheckoutId, true);\n }else if(verificationObj.ref){\n result = IngenicoPayments.getPaymentStatus(verificationObj.ref);\n }else{\n Logger.error(\"Missing verification reference - Params: \" + JSON.stringify(results) + \" VerificationObj: \" + JSON.stringify(verificationObj))\n }\n\n if(!result || result.error){\n Logger.warn(\"Error getting payment status: \" + JSON.stringify(result));\n app.getView({ redirect: URLUtils.url('COVerification-Confirmation', \"error=400\") }).render(\"checkout/3DSredirect\");\n return;\n }\n\n if(result.createdPaymentOutput){\n if(\"tokens\" in result.createdPaymentOutput && result.createdPaymentOutput && result.createdPaymentOutput.payment && result.createdPaymentOutput.payment.paymentOutput && result.createdPaymentOutput.payment.paymentOutput.cardPaymentMethodSpecificOutput){\n IngenicoOrderHelper.processHostedTokens(order.getCustomer(), result.createdPaymentOutput.tokens, result.createdPaymentOutput.payment.paymentOutput.cardPaymentMethodSpecificOutput)\n }\n result = result.createdPaymentOutput.payment;\n }\n \n var updatedOrderOK = UpdateOrder.updateOrderFromCallback(orderNo, result);\n\n if (result && result.status) {\n switch (result.status) {\n case ReturnStatus.REDIRECTED:\n case ReturnStatus.CAPTURE_REQUESTED:\n case ReturnStatus.PENDING_CAPTURE:\n case ReturnStatus.PENDING_PAYMENT:\n case ReturnStatus.AUTHORIZATION_REQUESTED: \n case ReturnStatus.PAID:\n case ReturnStatus.CAPTURED:\n cancelOrder = false;\n app.getView({ redirect: URLUtils.url('COVerification-Confirmation') }).render(\"checkout/3DSredirect\");\n return;\n case ReturnStatus.PENDING_FRAUD_APPROVAL:\n case ReturnStatus.PENDING_APPROVAL:\n cancelOrder = false;\n app.getView({ redirect: URLUtils.url('COVerification-Confirmation') }).render(\"checkout/3DSredirect\");\n return;\n case ReturnStatus.REJECTED:\n case ReturnStatus.REVERSED:\n case ReturnStatus.REJECTED_CAPTURE:\n case ReturnStatus.CANCELLED:\n case ReturnStatus.CHARGEBACKED: // Should never get this status back during checkout process.\n app.getView({ redirect: URLUtils.url('COVerification-COSummary') }).render(\"checkout/3DSredirect\");\n return; \n default:\n break;\n } \n }\n }\n}",
"function sdkResponseHandler(status, response) {\n\n if (status != 200 && status != 201) {\n \n alert(\"Verify the data\");\n \n }else{\n \n var form = document.querySelector('#pay');\n\n var card = document.createElement('input');\n card.setAttribute('name',\"card\");\n card.setAttribute('type',\"hidden\");\n card.setAttribute('value',response.id);\n\n form.appendChild(card);\n \n doSubmit=true;\n \n alert(\"card token: \"+response.id);\n \n form.submit();\n }\n }",
"function setupPaymentMethodsObserver16() {\n // Select the node that will be observed for mutations\n const targetNode = document.getElementById('HOOK_PAYMENT');\n\n // In case the targetNode does not exist return early\n if (null === targetNode) {\n return;\n }\n\n // Options for the observer (which mutations to observe)\n const config = {attributes: true, childList: true, subtree: false};\n\n // Callback function to execute when mutations are observed\n const callback = function(mutationsList, observer) {\n // extra check to make sure that we are on 1.6\n if (IS_PRESTA_SHOP_16) {\n // Set which methods have their own button\n componentButtonPaymentMethods = paymentMethodsWithPayButtonFromComponent;\n // Use traditional 'for loops' for IE 11\n for (const mutation of mutationsList) {\n if (mutation.type === 'childList') {\n // The children are being changed so disconnet the observer\n // at first to avoid infinite loop\n observer.disconnect();\n // Render the adyen checkout components\n renderPaymentMethods();\n }\n }\n\n // Connect the observer again in case the checkbox is clicked\n // multiple times\n observer.observe(targetNode, config);\n }\n };\n\n // Create an observer instance linked to the callback function\n const observer = new MutationObserver(callback);\n\n // Start observing the target node for configured mutations\n try {\n observer.observe(targetNode, config);\n } catch (e) {\n // observer exception\n }\n }",
"function buy() { // eslint-disable-line no-unused-vars\n document.getElementById('msg').innerHTML = '';\n\n if (!window.PaymentRequest) {\n print('Web payments are not supported in this browser');\n return;\n }\n\n let details = {\n total: {label: 'Total', amount: {currency: 'USD', value: '0.50'}},\n };\n\n let networks = ['visa', 'mastercard', 'amex', 'discover', 'diners', 'jcb',\n 'unionpay', 'mir'];\n let payment = new PaymentRequest( // eslint-disable-line no-undef\n [\n {\n supportedMethods: ['https://android.com/pay'],\n data: {\n merchantName: 'Web Payments Demo',\n allowedCardNetworks: ['AMEX', 'MASTERCARD', 'VISA', 'DISCOVER'],\n merchantId: '00184145120947117657',\n paymentMethodTokenizationParameters: {\n tokenizationType: 'GATEWAY_TOKEN',\n parameters: {\n 'gateway': 'stripe',\n 'stripe:publishableKey': 'pk_live_lNk21zqKM2BENZENh3rzCUgo',\n 'stripe:version': '2016-07-06',\n },\n },\n },\n },\n {\n supportedMethods: networks,\n },\n {\n supportedMethods: ['basic-card'],\n data: {\n supportedNetworks: networks,\n supportedTypes: ['debit', 'credit', 'prepaid'],\n },\n },\n \n ],\n details,\n {\n requestShipping: true,\n requestPayerName: true,\n requestPayerPhone: true,\n requestPayerEmail: true,\n shippingType: 'shipping',\n });\n\n payment.addEventListener('shippingaddresschange', function(evt) {\n evt.updateWith(new Promise(function(resolve) {\n fetch('/ship', {\n method: 'POST',\n headers: new Headers({'Content-Type': 'application/json'}),\n body: addressToJsonString(payment.shippingAddress),\n })\n .then(function(options) {\n if (options.ok) {\n return options.json();\n }\n cannotShip('Unable to calculate shipping options.', details,\n resolve);\n })\n .then(function(optionsJson) {\n if (optionsJson.status === 'success') {\n canShip(details, optionsJson.shippingOptions, resolve);\n } else {\n cannotShip('Unable to calculate shipping options.', details,\n resolve);\n }\n })\n .catch(function(error) {\n cannotShip('Unable to calculate shipping options. ' + error, details,\n resolve);\n });\n }));\n });\n\n payment.addEventListener('shippingoptionchange', function(evt) {\n evt.updateWith(new Promise(function(resolve) {\n for (let i in details.shippingOptions) {\n if ({}.hasOwnProperty.call(details.shippingOptions, i)) {\n details.shippingOptions[i].selected =\n (details.shippingOptions[i].id === payment.shippingOption);\n }\n }\n\n canShip(details, details.shippingOptions, resolve);\n }));\n });\n\n let paymentTimeout = window.setTimeout(function() {\n window.clearTimeout(paymentTimeout);\n payment.abort().then(function() {\n print('Payment timed out after 20 minutes.');\n }).catch(function() {\n print('Unable to abort, because the user is currently in the process ' +\n 'of paying.');\n });\n }, 20 * 60 * 1000); /* 20 minutes */\n\n payment.show()\n .then(function(instrument) {\n window.clearTimeout(paymentTimeout);\n\n if (instrument.methodName !== 'https://android.com/pay') {\n simulateCreditCardProcessing(instrument);\n return;\n }\n\n let instrumentObject = instrumentToDictionary(instrument);\n instrumentObject.total = details.total;\n let instrumentString = JSON.stringify(instrumentObject, undefined, 2);\n fetch('/buy', {\n method: 'POST',\n headers: new Headers({'Content-Type': 'application/json'}),\n body: instrumentString,\n })\n .then(function(buyResult) {\n if (buyResult.ok) {\n return buyResult.json();\n }\n complete(instrument, 'fail', 'Error sending instrument to server.');\n }).then(function(buyResultJson) {\n print(instrumentString);\n complete(instrument, buyResultJson.status, buyResultJson.message);\n });\n })\n .catch(function(error) {\n print('Could not charge user. ' + error);\n });\n}",
"function showRegFormOFPromoCode() {\n\tvar totalDueAmt = getFormatedNumber($(\"#amountDueTotal\").text(), false);\n\tvar totalPaymentAmt = getFormatedNumber($(\"#cashSummaryTotalAmount\").text(), false);\n\tif (!$('#chkPromoCode').is(\":checked\")) {\n\t\tvar arg0 = '<a href=\"javascript:void(0)\" class=\"blue_link\" onclick=\"showTermsUrl()\">';\n\t\tvar arg1 = '</a>';\n\t\tmessage = formatMessage(messages['checkout.guestUserPromoCodeRegisterTermCond'], arg0, arg1);\n\t\t$(\"#chkPromoCode\").prop('checked', true);\n\t\t$(\"#chkPromoCodeIcon\").removeClass(\"add_bill_inactiv_chkbox_icon flt_lft\");\n\t\t$(\"#chkPromoCodeIcon\").addClass(\"add_bill_activ_chkbox_icon flt_lft\");\n\t\t/* clearing promocode and password whenever expanding discount and promo section. Bug 4865*/\n\t\t$('#promoCodeDiscount1').val('');\n\t\t$('#passwordPromoCode').val('');\n\t\t$(\"#frmGuestPromoCodeRes\").show();\n\t\t$(\"#checkoutDiscountPromoTermsCond\").html(message);\n\t\t/* Show the check box for marketing Opt in */\n\t\tcreateOptInMsgAorBSection(\"chkOptInEnhCreatProfPromo\", \"optInEhnChkCreatProfPromo\", messages['createAccount.optInEnh']);\n\t\tif($(\"#additional_info_box\").is(\":visible\")) {\n\t\t\tfillPromoRegisterFromAdditionalInfo();\n\t\t} else if($(\"#createAccountBoxChkOut\").is(\":visible\")) {\n\t\t\tfillPromoRegisterFromCreateProfile();\n\t\t}\n\t\t/* To be called from create_acc_guest.js*/\n\t\tvalidateCheckoutRegistrationFields();\n\t\tenableCheckoutRegisterBtn();\n\t} else {\n\t\toffPromoCodeRegisterScreen();\n\t\t/* Fill the data in \"Create Profile\" area on click of Cancel or unmark of check box and if incase of \n\t\t * atleast 1 schedule payment if user clicked \"Register\" button then also same*/\n\t\tif (totalPaymentAmt > totalDueAmt || isRegisterSelected) {\n\t\t\tfillCreateProfileFromPromoRegister();\n\t\t} else if(totalPaymentAmt === totalDueAmt || $(\"#panel\"+jsonTypeConstant.DEBIT).is(\":visible\") || $(\"#panel\"+jsonTypeConstant.CREDIT).is(\":visible\")) {\n\t\t\tfillAdditionalInfoFromPromoRegister();\n\t\t}\n\t\tcancelBtnOfPromoCode();\n\t}\n}",
"function clearPaymentMethod() {\n\t$(\".selectable\").each(function(){\n\t\t$(this).attr(\"checked\", false);\t\t\t\n\t\tisPaymentMethodSelected = false;\n\t\tpaymentProfileId = \"0\";\n\t});\t\n}",
"function processPayment(amount, { number, expMonth, expYear, cvc }, callback){\n\n // Configure the request details\n const options = {\n protocol: \"https:\",\n hostname: \"api.stripe.com\",\n method: \"POST\",\n auth: `${config.stripe.secretKey}:`,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" }\n };\n\n // Configure the token request payload\n const tokenStringPayload = querystring.stringify({\n 'card[number]': number,\n 'card[exp_month]': expMonth,\n 'card[exp_year]': expYear,\n 'card[cvc]': cvc,\n });\n\n options.path = \"/v1/tokens\";\n options.headers[\"Content-Length\"] = Buffer.byteLength(tokenStringPayload);\n\n // Instantiate the token request\n const tokenReq = https.request(options, function(res){\n\n // Grab status from response\n const tokenResStatus = res.statusCode\n\n // Callback successfully if the request went through\n if(successStatus(tokenResStatus)){\n\n // Parse and read response\n res.setEncoding('utf8');\n res.on('data', chunk => {\n // Parse string response\n const tokenId = parseJsonToObject(chunk).id;\n\n // Configure the token request payload\n const chargeStringPayload = querystring.stringify({\n amount,\n currency: 'eur',\n // Extract token id from token response\n source: tokenId,\n });\n\n options.path = \"/v1/charges\";\n options.headers[\"Content-Length\"] = Buffer.byteLength(chargeStringPayload);\n\n // Create charge using order information using stripe service\n const chargeReq = https.request(options, function(res){\n\n // Grab status from response\n const chargeResStatus = res.statusCode\n\n // Callback successfully if the request went through\n if(successStatus(chargeResStatus)){\n\n // Parse and read response\n res.setEncoding('utf8');\n res.on('data', chunk => {\n // Parse string response\n const chargeStatus = parseJsonToObject(chunk).status;\n\n // Callback successfully if charge succeeded\n if(chargeStatus === 'succeeded'){\n callback(false);\n } else {\n callback(`Failed to charge payment successfully. Charge status returned was ${chargeStatus}`);\n };\n });\n\n } else {\n callback(`Failed charge request. Status code returned was ${chargeResStatus}`);\n };\n });\n\n // Bind to the error event so it doesn't get thrown\n chargeReq.on(\"error\", e => callback(e));\n\n // Add the payload\n chargeReq.write(chargeStringPayload);\n\n // End the request\n chargeReq.end();\n });\n\n } else {\n callback(`Failed token request. Status code returned was ${tokenResStatus}`);\n };\n });\n\n // Bind to the error event so it doesn't get thrown\n tokenReq.on(\"error\", e => callback(e));\n\n // Add the payload\n tokenReq.write(tokenStringPayload);\n\n // End the request\n tokenReq.end();\n}",
"function finishAutoSkipReview() {\r\n\tif ( !$('#tcsignup').validate().form() ) {\r\n\t\tpresentTCBusinessCard();\r\n\t}\r\n\r\n\t$('#btnNextStep').trigger('click');\r\n}",
"affiliateSignup (form_data, success_callback, failure_callback)\n {\n var url = '/global/crm/user/affiliate/signup';\n return WebClient.basicPost(form_data, url, success_callback, failure_callback);\n }",
"function updatePaymentInfo () {\n\n switch (document.querySelector(\"#payment\").value) {\n\n case \"credit card\":\n document.querySelector (\"#credit-card\").style.display = \"\";\n document.querySelector (\"#paypal\").style.display = \"none\";\n document.querySelector (\"#bitcoin\").style.display = \"none\";\n break;\n\n case \"paypal\":\n document.querySelector (\"#credit-card\").style.display = \"none\";\n document.querySelector (\"#paypal\").style.display = \"\";\n document.querySelector (\"#bitcoin\").style.display = \"none\";\n break;\n\n case \"bitcoin\":\n document.querySelector (\"#credit-card\").style.display = \"none\";\n document.querySelector (\"#paypal\").style.display = \"none\";\n document.querySelector (\"#bitcoin\").style.display = \"\";\n break;\n\n default: // this should never happen\n alert (\"internal error: no payment option detected\");\n break;\n }\n }",
"function setupPaymentMethods17() {\n const queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('message')) {\n showRedirectErrorMessage(queryParams.get('message'));\n }\n\n $('input[name=\"payment-option\"]').on('change', function(event) {\n\n let selectedPaymentForm = $('#pay-with-' + event.target.id + '-form .adyen-payment');\n\n // Adyen payment method\n if (selectedPaymentForm.length > 0) {\n\n // not local payment method\n if (!('localPaymentMethod' in\n selectedPaymentForm.get(0).dataset)) {\n\n resetPrestaShopPlaceOrderButtonVisibility();\n return;\n }\n\n let selectedAdyenPaymentMethodCode = selectedPaymentForm.get(\n 0).dataset.localPaymentMethod;\n\n if (componentButtonPaymentMethods.includes(selectedAdyenPaymentMethodCode)) {\n prestaShopPlaceOrderButton.hide();\n } else {\n prestaShopPlaceOrderButton.show();\n }\n } else {\n // In 1.7 in case the pay button is hidden and the customer selects a non adyen method\n resetPrestaShopPlaceOrderButtonVisibility();\n }\n });\n }",
"function fillCreateProfileFromPromoRegister() {\n\t$('#emailIdChkOut').val($(\"#emailIdPromoCode\").val());\n\t$('#confrmEmailIdChkOut').val($(\"#confrmEmailIdPromoCode\").val());\n\t$('#passwordChkOut').val($(\"#passwordPromoCode\").val());\n\t$('#mobileNoChkOut').val($(\"#mobileNoPromoCode\").val());\n\t$('#zipCodeChkOut').val($(\"#zipCodePromoCode\").val());\n\t$('#promoCodeDiscount2').val($(\"#promoCodeDiscount1\").val());\n\tif ($('#chkOptInEnhCreatProfPromo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProf\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProf\").prop('checked', false);\n\t}\n\t$(\"#createAccountBoxChkOut\").show();\n\tvalidateCreateProfile();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the height in pixels of the content area the text that the user has entered. | getContentHeight() {
let contentHeight = 0;
if (this.ckeInstance.ui &&
this.ckeInstance.ui.contentsElement &&
this.ckeInstance.ui.contentsElement.$ &&
this.ckeInstance.ui.contentsElement.$.style) {
const cssText = this.ckeInstance.ui.contentsElement.$.style.cssText;
if (cssText.indexOf('height: ') !== -1) {
let height = cssText.split('height: ')[1];
height = height.split('px')[0];
contentHeight = parseInt(height, 10);
}
}
return contentHeight;
} | [
"get height() {\n if ( !this.el ) return;\n\n return ~~this.parent.style.height.replace( 'px', '' );\n }",
"_calculateHeight() {\n\t\tif (this.options.height) {\n\t\t\treturn this.jumper.evaluate(this.options.height, { '%': this.jumper.getAvailableHeight() });\n\t\t}\n\n\t\treturn this.naturalHeight() + (this.hasScrollBarX() ? 1 : 0);\n\t}",
"function getHighestTextArea() {\r\n var textAreaHeight = 0;\r\n sAccTextArea.each(function () {\r\n if ($(this).height() > textAreaHeight) {\r\n textAreaHeight = $(this).outerHeight();\r\n }\r\n });\r\n return textAreaHeight;\r\n }",
"get inputMaxHeight(){\n var {footer, header, maxHeight} = this.props;\n var inputMaxHeight = maxHeight;\n if(footer) inputMaxHeight-=1;\n if(header) inputMaxHeight-=1;\n return inputMaxHeight;\n }",
"get height() {\n // spec says it is a string\n return this.getAttribute('height') || '';\n }",
"function getHeight() {\n return maxy + 1;\n }",
"_updateHeight() {\n this._mirroredTextareaRef.el.value = this.composer.textInputContent;\n this._textareaRef.el.style.height = (this._mirroredTextareaRef.el.scrollHeight) + \"px\";\n }",
"static getMaxHeight() { \n var result = Math.max(MainUtil.findAllRooms().map(room => (room.memory.console && room.memory.console.height)));\n return result || 10;\n }",
"getGameHeight() {\n return this.scene.sys.game.config.height;\n }",
"function getHeight() {\n return 2;\n }",
"function containerHeight() {\n var cnt = scope.data && scope.data.length || 0;\n return cnt * theight;\n }",
"get estimatedHeight() {\n return -1\n }",
"function height() {\n return gl.drawingBufferHeight / scale();\n }",
"function getLineHeightPx(node) {\n var computedStyle = window.getComputedStyle(node);\n\n // If the char code starts with a digit, it is either a value in pixels,\n // or unitless, as per:\n // https://drafts.csswg.org/css2/visudet.html#propdef-line-height\n // https://drafts.csswg.org/css2/cascade.html#computed-value\n if (isDigit(computedStyle.lineHeight.charCodeAt(0))) {\n // In real browsers the value is *always* in pixels, even for unit-less\n // line-heights. However, we still check as per the spec.\n if (isDigit(computedStyle.lineHeight.charCodeAt(computedStyle.lineHeight.length - 1))) {\n return parseFloat(computedStyle.lineHeight) * parseFloat(computedStyle.fontSize);\n } else {\n return parseFloat(computedStyle.lineHeight);\n }\n }\n\n // Otherwise, the value is \"normal\".\n // If the line-height is \"normal\", calculate by font-size\n var body = document.body;\n if (!body) {\n return 0;\n }\n var tempNode = document.createElement(node.nodeName);\n tempNode.innerHTML = ' ';\n tempNode.style.fontSize = computedStyle.fontSize;\n tempNode.style.fontFamily = computedStyle.fontFamily;\n body.appendChild(tempNode);\n // Assume the height of the element is the line-height\n var height = tempNode.offsetHeight;\n body.removeChild(tempNode);\n return height;\n}",
"setDimensions() {\n this.textbox.style.width = '';\n const scrollWidth = this.textbox.scrollWidth;\n const offsetWidth = this.textbox.offsetWidth;\n const width = (scrollWidth === offsetWidth ? offsetWidth - 1 : scrollWidth + 8);\n this.textbox.style.width = `${width}px`;\n\n /* Set the height of the absolute-positioned textarea to its background content's offsetHeight. Since the background\n content autoexpands, this allows the elements to be scrolled simultaneously using the parent element's scrollbars.\n Setting it to textbox.scrollHeight instead of bg.offsetHeight would also work, but that would require us to first\n blank style.height. It would also prevent us from improving seemless scrolling by adding trailing characters to the\n background content (which is done outside this method) before testing its height. Comparing bg.offsetHeight to the\n container's offsetHeight (minus 2 for borders) is done for the sake of IE6, since CSS min-height doesn't work\n there. */\n const height = Math.max(this.bg.offsetHeight, this.field.offsetHeight - 2);\n this.textbox.style.height = `${height}px`;\n }",
"get defaultLineHeight() {\n return this.viewState.heightOracle.lineHeight\n }",
"get inputMinHeight(){\n var {footer, header} = this.props;\n\n var inputMinHeight = this.minHeight;\n if(footer) inputMinHeight-=1;\n if(header) inputMinHeight-=1;\n return inputMinHeight;\n }",
"function getHeightInInches(sideInput){\n return storeInputValues(sideInput, 'getHeightInInch');\n }",
"updateEditorHeight() {\n $('#editor').height($('#editor-wrapper').height() - $('#file-tabs').height() - 3);\n }",
"function GetWindowHeight() { \n\n //return window.innerHeight||\n //document.documentElement&&document.documentElement.clientHeight||\n //document.body.clientHeight||0;\n \n var windowHeight = 0;\n if (typeof(window.innerHeight) == 'number') {\n windowHeight = window.innerHeight;\n }\n else {\n if (document.documentElement && document.documentElement.clientHeight) {\n windowHeight = document.documentElement.clientHeight;\n }\n else {\n if (document.body && document.body.clientHeight) {\n windowHeight = document.body.clientHeight;\n }\n }\n }\n \n return windowHeight; \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removes item from basket list display && provides value for basketArrayItemRemove before calling it && calls updateBasketTotal | function removeBasketItem(event) {
let buttonClicked = event.target;
let id = buttonClicked.previousElementSibling.innerText;
buttonClicked.parentElement.parentElement.remove();
let itemToRemove = { productId: id }
basketArrayItemRemove(itemToRemove)
updateBasketTotal();
} | [
"function removeFromBasket() {\n var id = jQuery(this).attr('data-item'); // Eg. 'x47'.\n basket.removeItem(id);\n //refreshBaskets();\n window.location.reload(true); // reload page (from server, not cache)\n }",
"function removeItem() {\n \n var idxToRemove = $('.remove-from-cart').attr('data-index');\n \n cart.items.splice(idxToRemove, 1);\n renderCart(cart, $('.template-cart'), $('.cart-container'));\n}",
"removeBike(bike) {\n //Removes bike from basket\n for (let i of basket) {\n if (bike == i) {\n this.totalPrice -= basket[basket.indexOf(i)].displayPrice;\n basket.splice(basket.indexOf(i), 1);\n shared.basketLength = basket.length;\n this.updateBasket();\n this.calcDiscount();\n }\n }\n\n //Removes all equipment belong to bike with it\n for (var i = 0; equipmentBasket.length > i; i++) {\n if (equipmentBasket[i].bike_id == bike.id) {\n equipmentBasket.splice(i, 1);\n this.totalPrice -= equipmentBasket[i].displayPrice;\n i--;\n }\n }\n }",
"function removeCart() {\n\tconsole.log(\"removing from cart\");\n\ttotal -= 1;\n\t$(\"#cartName\").html(\"cart (\" + total + \")\");\n\n\tlet itemDiv = document.getElementById(\"itemStart\");\n\titemDiv.style.display = \"none\";\n}",
"function removeCartItem(event){\r\n // event object has property target, which specifies the button clicked. \r\n var buttonClicked = event.target\r\n // So we want to go up 2 parent elements (classes) and remove the row when 'remove' button is clicked.\r\n buttonClicked.parentElement.parentElement.remove()\r\n updateCartTotal()\r\n}",
"function clearBasket() {\n basket.clear();\n renderBasket();\n}",
"function decQty() {\n\tconsole.log(\"Decreasing quantity\");\n\tconsole.log(this);\n\n\tvar id = this.getAttribute(\"id\");\n\tvar index = id.substr(3);\n\tvar count = --cart[index][0];\n\n\t// Removes the item from the list when the quantity is 0 or less.\n\tif (count <= 0) {\n\t\tcart.splice(index, 1)\n\t\tconsole.log($(this).parent().remove());\n\t}\n\n\tdisplayCart();\n}",
"basketRemove(equipment) {\n for (var i = 0; equipmentBasket.length > i; i++) {\n if (equipmentBasket[i].id == equipment.id) {\n equipmentBasket.splice(i, 1);\n }\n }\n\n this.specify();\n }",
"function removeCartDishItem(data){\n $.getJSON(\"/restaurace/removeItem\", data, function(dish){\n actualizeCalculationsAfterItemRemoved(dish);\n });\n }",
"onClickDel() {\n var itemIndex = parseInt(this.props.index);\n var listIndex = parseInt(this.props.listKey);\n this.props.removeItem(listIndex,itemIndex);\n }",
"function removeCustomCartDishItem(data){\n $.getJSON(\"/restaurace/removeCustomItem\", data, function(dish){\n actualizeCalculationsAfterItemRemoved(dish);\n });\n }",
"function deleteBought(product, boughtBtn) {\n let itemWrapper = Array.from(allLists.querySelectorAll('.itemWrapper')).filter(elem => elem.getAttribute('id') === product.id)[0];\n let boughtPrice = allLists.querySelector('.boughtPrice');\n product.bought = false;\n product.boughtPrice = 0;\n boughtPrice.innerHTML = `€ ${product.boughtPrice}`;\n itemWrapper.style.border = 'none';\n boughtPrice.style.display = 'none';\n changeState(boughtBtn);\n}",
"function removeCurrentItem() {\n //Iterate towards the current item list to find and remove the current item\n for(var i=0; i<currentItemList.length; i++){\n if(currentItem.itemId == currentItemList[i].itemId){\n //Delete the current item in the current item list\n currentItemList.splice(i,i+1);\n break;\n }\n }\n}",
"function deleteLast(){\r\n shoppingList.pop(); //deletes last item from shoppignList array\r\n document.getElementById(\"groceryList\").innerHTML = shoppingList; \r\n}",
"removeDiscount() {\n var price = PriceList.beverages[this.beverageType];\n this.condiments.forEach(condiment => price += PriceList.Options[condiment]);\n this.beveragePrice = price;\n this.discount = 0;\n }",
"function removeFromPortfolio() { \n portfolioArr = JSON.parse(localStorage.getItem(\"stock\"));\n portfolioCash = localStorage.getItem(\"cash\");\n let quantity = parseInt(stockSaleInput.val());\n console.log(sellQuantityAvailable);\n console.log(quantity);\n\n if(sellQuantityAvailable < quantity){\n $(\"#errorMessageDiv\").text(\"Insufficient shares available.\")\n }\n else {\n let saleTotal = quantity * sellPrice;\n portfolioCash = parseFloat(portfolioCash) + saleTotal;\n localStorage.setItem(\"cash\", portfolioCash);\n for (i=0 ; i<portfolioArr.length; i++){\n if(sellStock === portfolioArr[i].name){\n portfolioArr[i].quantity -= quantity;\n }\n }\n stockArr = JSON.stringify(portfolioArr);\n localStorage.setItem(\"stock\", stockArr);\n $(\"#portfolioDisplayDiv\").empty();\n generatePortfolio();\n $(\"#modalSell\").modal('close');\n }\n}",
"async removePaymentInstrument() {\n let paymentInstrumentId =\n basket.paymentInstruments && basket.paymentInstruments[0]?.paymentInstrumentId\n\n if (!paymentInstrumentId) {\n return\n }\n\n const response = await api.shopperBaskets.removePaymentInstrumentFromBasket({\n parameters: {\n basketId: basket.basketId,\n paymentInstrumentId: paymentInstrumentId\n }\n })\n\n setBasket(response)\n }",
"function removeItems()\n{\n\tif (checklocked() == false)\n\t{\n\t\tif ((remove_trade.length || remove_sale.length || remove_return.length) && confirm('Are you SURE you want to remove these items from the invoice?'))\n\t\t{\n\t\t\tvar frm = document.remfrm;\n\t\t\tfrm.remove_sale.value = remove_sale;\n\t\t\tfrm.remove_trade.value = remove_trade;\n\t\t\tfrm.remove_return.value = remove_return;\n\t\t\tfrm.submit();\n\t\t}\n\t}\n}",
"removeSeat() {\n //recount the number of tickets\n if (this._seatType === \"regular\") {\n regularSeatCount--;\n regularTicketNum.innerHTML = regularSeatCount; //display reg ticket num\n Seat.calcTotalPrice(regularSeatCount, this._seatType);\n } else if (this._seatType === \"vip\") {\n vipSeatCount--;\n vipTicketNum.innerHTML = vipSeatCount; //display vip ticket num\n Seat.calcTotalPrice(vipSeatCount, this._seatType);\n };\n //total ticket count\n this._totalTicketNum = regularSeatCount + vipSeatCount;\n totalTicketNum.innerHTML = this._totalTicketNum;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
scaling diplom on click | function scalingDiplom() {
let img = document.querySelector(".diplom__img");
img.addEventListener("click", function () {
img.classList.toggle("scaled");
})
} | [
"function _scaling ( /*[Object] event*/ e ) {\n\t\tvar activeObject = cnv.getActiveObject(),\n\t\tscale = activeObject.get('scaleY') * 100;\n\t\tif ( scale > 500 ) {\n\t\t\tactiveObject.scale(5);\n\t\t\tactiveObject.left = activeObject.lastGoodLeft;\n \tactiveObject.top = activeObject.lastGoodTop;\n\t\t}\n\t\tactiveObject.lastGoodTop = activeObject.top;\n \tactiveObject.lastGoodLeft = activeObject.left;\n\t\tif ( is_text(activeObject) ) {\n\t\t\teditTextScale.set( scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'scale', scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'top', activeObject.top );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'left', activeObject.left );\n\t\t}\n\t\telse {\n\t\t\teditImageScale.set(scale);\n\t\t}\n\t}",
"function scale( element, toggle )\n {\n var transform = new Transform( element ), // Instance of js class for works with transform css property\n min = 0.2, // Min image scale\n max = 3, // Max image scale\n prevExpandDistance = 0, // Previous expand distance between fingers\n prevPinchDistance = 0, // Previous pinch distance between fingers\n odds; // The difference between distance and e.detail.distance\n\n // Current scale of image\n element.scale = 1;\n\n // Create closure\n ( function (element, toggle)\n {\n // Определяем, какая из сторон изображения больше\n // И большей стороне присваиваем размер в 100%\n\n // var percent = '100%';\n var percent = '90%'; // 90% потому, что может быть момент, когда картинка будет равно по ширине или высоте вьюпорту. И лучше, если она будет четь меньше\n\n // Если ширина картинки больше, чем ее высота и ширина картинки больше, чем ширина viewport'a\n if ( element.offsetWidth > element.offsetHeight && element.offsetWidth > toggle.offsetWidth )\n {\n element.style.width = percent;\n }\n\n // Если ширина картинки больше, чем ее высота и ширина картинки меньше или равна, ширине viewport'a\n else if ( element.offsetWidth > element.offsetHeight && element.offsetWidth <= toggle.offsetWidth )\n {\n // Ничего не делаем =)\n }\n\n // Если высота картинки больше, чем ее ширина и высота картинки больше, чем высота vieport'а\n else if ( element.offsetWidth < element.offsetHeight && element.offsetHeight > toggle.offsetHeight )\n {\n element.style.height = percent;\n }\n\n // Если высота картинки больше, чем ее ширина и высота картинки меньше или равна, высоте vieport'а\n else if ( element.offsetWidth < element.offsetHeight && element.offsetHeight <= toggle.offsetHeight )\n {\n // Ничего не делаем\n }\n\n // Если ширина картинки и ее высота равны и они больше, чем высота viewport'a\n else if ( element.offsetWidth == element.offsetHeight && element.offsetWidth > toggle.offsetWidth)\n {\n // Определяем, портретная ориентация или альбомная\n // Если портретная, то ставим ширину 100%\n // Если альбомная, то высоту 100%\n var width = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,\n height = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;\n\n // Портретная\n if( width > height ) element.style.width = percent;\n\n // Альбомная\n else element.style.height = percent;\n }\n\n // Если ширина картинки и ее высота равны и они меньше или равны высоте viewport'a\n else if ( element.offsetWidth == element.offsetHeight && element.offsetWidth <= toggle.offsetWidth)\n {\n // Ничего не делаем\n }\n\n // Attach mouse wheel event to toggle\n toggle.addEventListener( 'wheel', function( e )\n {\n // Increase scale or decrease. If e.deltaY < 0, then increase, else decrease\n element.scale = e.deltaY < 0 ? ( element.scale += 0.1 ) : ( element.scale -= 0.1 );\n\n // Check scale on out of bounds\n element.scale = ( element.scale > max ? max : ( element.scale < min ? min : element.scale ) );\n\n // Scaling the image\n transform.scale( element.scale );\n //element.style.transform = 'scale(' + element.scale + ')';\n\n e.preventDefault();\n } );\n\n\n // Create a mobile events\n if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) )\n {\n var speed = 0.007; // Speed coefficient of expand and pinch\n // var speed = 0.002; // Speed coefficient of expand and pinch\n\n // Binding tap event to call toggle click.\n // It's necessary, because ZingTouch preventing attached to ovelay events\n region.bind( toggle, 'tap', function( e )\n {\n if ( e.target == toggle && e.detail.events[0].originalEvent.type != 'mouseup')\n {\n toggle.click();\n }\n } );\n\n // Bind tap to stop propagation toggle tap event\n // Else tap on image will close the overlay\n region.bind( element, 'tap', function( e )\n {\n // Do nothing\n } );\n\n // Binding expand event\n region.bind(toggle, 'expand', function( e )\n {\n // Setting up pinch distance to default everytime of transiton from Picnh to Expand\n prevPinchDistance = 0;\n\n // If the gesture occurs in the first time, then setting up expand distance equals to e.detail.distance\n prevExpandDistance == 0 && ( prevExpandDistance = e.detail.distance );\n\n // Calculating difference between prev distance and current distance to get the acceleration of finger movement\n odds = Math.max( prevExpandDistance, e.detail.distance ) - Math.min( prevExpandDistance, e.detail.distance )\n\n element.scale += odds * speed;\n\n // Check the scale of the element on out of bounds of allowed values(Не знаю правильно написал или нет =) )\n element.scale = ( element.scale > max ? max : ( element.scale < min ? min : element.scale ) );\n\n // Set the scale to element\n requestAnimationFrame(function()\n {\n transform.scale( element.scale );\n //element.setAttribute( 'style', '-webkit-transform: scale(' + element.scale + '); transform: scale(' + element.scale + ');');\n });\n\n // Memorization the distance\n prevExpandDistance = e.detail.distance;\n } );\n\n region.bind(toggle, 'pinch', function( e )\n {\n // Setting up expand distance to default everytime of transiton from Expand to Picnh\n prevExpandDistance = 0;\n\n // If the gesture occurs in the first time, then setting up pinch distance equals to e.detail.distance\n prevPinchDistance == 0 && ( prevPinchDistance = e.detail.distance );\n\n // Calculating difference between prev distance and current distance to get the acceleration of finger movement\n odds = Math.max( prevPinchDistance, e.detail.distance ) - Math.min( prevPinchDistance, e.detail.distance )\n\n element.scale -= odds * speed;\n\n // Check the scale of the element on out of bounds of allowed values(Не знаю правильно написал или нет =) )\n element.scale = ( element.scale > max ? max : ( element.scale < min ? min : element.scale ) );\n\n // Set the scale to element\n requestAnimationFrame(function()\n {\n transform.scale( element.scale );\n //element.setAttribute( 'style', '-webkit-transform: scale(' + element.scale + '); transform: scale(' + element.scale + ');');\n });\n\n // Memorization the scale of image to using in pan-function\n //elements.scale =\n\n // Memorization the distance\n prevPinchDistance = e.detail.distance;\n }, false);\n\n // Set expand distance and pinch distance to default on expand-end and pinch-end\n document.body.addEventListener('touchend', function( e )\n {\n prevExpandDistance = 0;\n prevPinchDistance = 0;\n }, false);\n }\n\n } )( element, toggle );\n }",
"changeSize() {\n // Calculate the distance between the mouse and the center of the shape\n this.distanceFromCenterX = mouseX - this.x;\n this.distanceFromCenterY = mouseY - this.y;\n // Change width and height according to the mouse position\n this.width = 2 * (this.distanceFromCenterX);\n this.height = 2 * (this.distanceFromCenterY);\n }",
"onTransformScaling() {\n const scale = this.getClosestScaleToFitExtentFeature();\n this.setScale(scale);\n }",
"function gScale(sx,sy,sz) {\r\n modelViewMatrix = mult(modelViewMatrix,scale(sx,sy,sz)) ;\r\n}",
"function maintainScale(item) {\n var small = 5; // smallest allowed size (diameter, not radius)\n var large = 20; // largest allowed size (diameter, not radius)\n\n if ((item.bounds.width >= large) || (item.bounds.width <= small)) {\n item.data.scale.direction *= -1; // reverse direction\n }\n}",
"handleClick (event) {\n minusSlides(1);\n }",
"function updateScale(increment) {\n var ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n //var viewportScale = document.getElementById(\"scale\").value;\n axes.scale += increment;\n draw();\n}",
"function massOfObjAChange(scope) {\n mass_ball_a = scope.mass_of_a;\n getChild(\"ball_a\").scaleX = 0.5 + (scope.mass_of_a - 1) / 20;\n getChild(\"ball_a\").scaleY = 0.5 + (scope.mass_of_a - 1) / 20;\n ball_a_radius = (getChild(\"ball_a\").image.height * getChild(\"ball_a\").scaleY) / 2;\n}",
"set scale(newscale)\n\t{\n\t\tthis.myscale.x = newscale;\n\t\tthis.myscale.y = newscale;\n\n\t\tthis.container.style.transform = \"scale(\" + newscale + \",\" + newscale + \")\";\n \n\t\t//get width and height metrics\n\t\tthis.size.x = this.container.getBoundingClientRect().width;\n this.size.y = this.container.getBoundingClientRect().height;\n\n\t\t//adjust z order based on scale\n\t\tthis.container.style.zIndex = (100 * newscale).toString();\n\t}",
"function handleStretchDefaultClick() {\n setStretchMode((previous) => !previous);\n }",
"setPanScale(scale_pan){\n this.scale_pan = scale_pan;\n }",
"function resetScaleTransform() {\n Data.Edit.Transform.Scale = 1;\n updateTransform();\n}",
"function scaleEliminationCursor() {\n var baseWidthsSum = 0;\n var activePlantCount = 0;\n for ( var i=0; i<plants.length; i++ ) { \n if ( plants[i].sourceSeed.hasGerminated && plants[i].isAlive ) { \n baseWidthsSum += plants[i].spB.l; \n activePlantCount++;\n } \n }\n baseWidthAvg = baseWidthsSum/activePlantCount;\n selectRadius = baseWidthAvg*1.5 > canvas.width*0.015 ? baseWidthAvg*1.5 : canvas.width*0.015 ;\n}",
"function massOfObjBChange(scope) {\n mass_ball_b = scope.mass_of_b;\n getChild(\"ball_b\").scaleX = 0.5 + (scope.mass_of_b - 1) / 20;\n getChild(\"ball_b\").scaleY = 0.5 + (scope.mass_of_b - 1) / 20;\n ball_b_radius = (getChild(\"ball_b\").image.height * getChild(\"ball_b\").scaleY) / 2;\n}",
"get scale() { return (this.myscale.x + this.myscale.y)/2;}",
"function scaleImage(scalePercentage){\n\n imgInContainer.style.width=scalePercentage+\"%\";\n imgInContainer.style.height= \"auto\";\n\n}",
"function setCurrentScale() {\n\t\tFloorPlanService.currentScale = $(FloorPlanService.panzoomSelector).panzoom(\"getMatrix\")[0];\n\t}",
"function scale_changed() {\n\n var s = document.getElementById(\"scale_input\");\n //alert(\"slider value \" + s.value);\n\n var range = s.value / 100; // .25 - 2\n\n g_config.scale_factor = range;\n\n if (g_enableInstrumentation) {\n alert(\"scale_factor \" + g_config.scale_factor);\n }\n\n updateScaleCSS(g_config.scale_factor);\n\n refreshMode();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scales positive and negative data into [0, width], [0, height] | function scaleData(unscaledData, height, width) {
scaledData = [];
//Create the scalers with computed min/max values
var x = d3.scaleLinear()
.domain([X_MIN, X_MAX])
.range([0, width]);
var y = d3.scaleLinear()
.domain([Y_MIN, Y_MAX])
.range([0, height]);
//Scale the data
for (var i = 0; i < unscaledData.length; i++) {
scaledData.push([x(unscaledData[i][0]), y(unscaledData[i][1])]);
};
return scaledData;
} | [
"function scale(data, chosenAxis, dir) {\n let r = [0, width]\n if (dir === height) {\n r = [height, 0]\n }\n var linearScale = d3.scaleLinear()\n .domain([d3.min(data, sd => sd[chosenAxis]) * 0.9, //0.8 and 1.2 gives us a buffer from the edges of the chart\n d3.max(data, sd => sd[chosenAxis]) * 1.1\n ])\n .range(r);\n return linearScale\n}",
"static scale(v) {\r\n\t\tres = identity(); \t\tres.M[0] = v.x; \r\n\t\tres.M[5] = v.y; \t\tres.M[10] = v.z; \r\n\t\treturn res; \r\n\t}",
"function maintainScale(item) {\n var small = 5; // smallest allowed size (diameter, not radius)\n var large = 20; // largest allowed size (diameter, not radius)\n\n if ((item.bounds.width >= large) || (item.bounds.width <= small)) {\n item.data.scale.direction *= -1; // reverse direction\n }\n}",
"static normalize(rect) {\n if (rect.width < 0) {\n rect.width = -rect.width\n rect.x -= rect.width\n }\n\n if (rect.height < 0) {\n rect.height = -rect.height\n rect.y -= rect.height\n }\n }",
"function resetScaleTransform() {\n Data.Edit.Transform.Scale = 1;\n updateTransform();\n}",
"get scale() { return (this.myscale.x + this.myscale.y)/2;}",
"onTransformScaling() {\n const scale = this.getClosestScaleToFitExtentFeature();\n this.setScale(scale);\n }",
"get scale() {\n\t\treturn {\n\t\t\tx: this.dimens.x/this.width,\n\t\t\ty: this.dimens.y/this.height,\n\t\t};\n\t}",
"set scale(newscale)\n\t{\n\t\tthis.myscale.x = newscale;\n\t\tthis.myscale.y = newscale;\n\n\t\tthis.container.style.transform = \"scale(\" + newscale + \",\" + newscale + \")\";\n \n\t\t//get width and height metrics\n\t\tthis.size.x = this.container.getBoundingClientRect().width;\n this.size.y = this.container.getBoundingClientRect().height;\n\n\t\t//adjust z order based on scale\n\t\tthis.container.style.zIndex = (100 * newscale).toString();\n\t}",
"toPixels(arr){\n let scaled = [];\n arr.forEach(index =>\n scaled.push({\n origin: {x: index.origin.x/this.state.scale, y: index.origin.y/this.state.scale},\n dest: {x: index.destination.x/this.state.scale, y: index.destination.y/this.state.scale},\n dist: index.distance})\n );\n return scaled;\n }",
"function gScale(sx,sy,sz) {\r\n modelViewMatrix = mult(modelViewMatrix,scale(sx,sy,sz)) ;\r\n}",
"function scaleMatrix(sx,sy,sz) { // identidade\n return [\n [sx, 0, 0, 0],\n [0, sy, 0, 0],\n [0, 0, sz, 0],\n [0, 0, 0, 1]\n ]; //retorna matriz 4x4\n}",
"scale(scale) {\n return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);\n }",
"function _updateImageScale ( values, handle ) {\n\t\tupdateScale.call( this, values, handle );\n\t}",
"_applyScale(point) {\n let scale = this.getScale()\n return {\n x: point.x * scale,\n y: point.y * scale,\n z: point.z * scale,\n }\n }",
"function updateScaleToZeroParameters() {\n lodash.defaultsDeep(ctrl.version, {\n ui: {\n scaleToZero: {\n scaleResources: scaleResourcesCopy\n }\n }\n });\n\n var scaleResources = lodash.get(ctrl.version, 'ui.scaleToZero.scaleResources');\n\n if (ctrl.minReplicas === 0) {\n lodash.set(ctrl.version, 'spec.scaleToZero.scaleResources', scaleResources);\n } else {\n lodash.unset(ctrl.version, 'spec.scaleToZero');\n }\n\n var maxWindowSize = lodash.chain(scaleResources)\n .maxBy(function (value) {\n return parseInt(value.windowSize);\n })\n .get('windowSize')\n .value();\n\n ctrl.windowSizeSlider = {\n value: maxWindowSize,\n options: {\n stepsArray: scaleToZero.inactivityWindowPresets,\n showTicks: true,\n showTicksValues: true,\n disabled: !Number.isSafeInteger(ctrl.minReplicas) ||\n ctrl.minReplicas > 0 ||\n ctrl.isFunctionDeploying(),\n onChange: function (_, newValue) {\n lodash.forEach(scaleResources, function (value) {\n value.windowSize = newValue;\n });\n\n if (ctrl.minReplicas === 0) {\n lodash.set(ctrl.version, 'spec.scaleToZero.scaleResources', scaleResources);\n }\n }\n }\n };\n }",
"static scale(_matrix, _x, _y, _z) {\n return Mat4.multiply(_matrix, this.scaling(_x, _y, _z));\n }",
"scaleToRange(x) {\r\n var t;\r\n t = this.minHeight + ((x - this.minTemp) * (this.maxHeight - this.minHeight)) / (this.maxTemp - this.minTemp); // Based on a formula googled from various sources.\r\n return t;\r\n }",
"scale(scale) {\n const result = new Matrix();\n this.scaleToRef(scale, result);\n return result;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show Icon menu Grabs all bundles from InfoStats2 and appends a dom element | function showIconAddMenu() {
var apps = FPI.apps.all, i, bundle, sel, name;
clearinnerHTML(appList);
showHideElement(appList, 'block');
appList.appendChild(createDOMElement('li', 'Disable Edit', 'name', 'Edit'));
for (i = 0; i < apps.length; i++) {
bundle = apps[i].bundle;
sel = FPI.bundle[bundle];
name = sel.name;
appList.appendChild(createDOMElement('li', name, 'name', bundle));
}
} | [
"function reshowAllGuiGenes() {\n updateGuiGenes();\n}",
"function displayCoins() {\r\n $('.loadIcon').show();\r\n\r\n const coinsAPI = \"https://api.coingecko.com/api/v3/coins/list\";\r\n\r\n $.get(coinsAPI, function (response) {\r\n let objCoins = response;\r\n // let objCoins = JSON.parse(JSON.stringify(response));\r\n const partialCoins = objCoins.slice(1500, 2200);\r\n\r\n let coinsHTML = `<div class=\"cardsContainer\">`;\r\n\r\n $.each(partialCoins, function (i, coin) {\r\n coinsHTML += `<div class=\"card\">\r\n <label class=\"switch\" title=\"select for live reports\">\r\n <input type=\"checkbox\" class=\"checkbox\" name=${coin.name.replace(/\\s+/g, '-').toLowerCase()} onchange=\"toggleSelected(event)\">\r\n <span class=\"slider round\"></span>\r\n </label>\r\n <p class=\"id\">${coin.id}</p>\r\n <p class=\"symbol uppercase\">${coin.symbol}</p>\r\n <p class=\"name\">${coin.name.toLowerCase()}</p> \r\n <div class=\"expander\"></div>\r\n <button class=\"infoBtn\" name=${coin.id} onclick=\"showInfo(event)\">More Info</button>\r\n </div>`;\r\n });\r\n\r\n coinsHTML += '</div>'\r\n\r\n $('.loadIcon').fadeOut();\r\n $('#results').hide().html(coinsHTML).fadeIn(2000);\r\n\r\n });\r\n}",
"function setupIconLibrarySelectionListener() {\n $('li[class^=ion]').click(function(e) {\n var originalElement = e.target;\n var imageName = originalElement.classList[0].slice(4);\n $('#IconLibraryModal').modal('hide');\n generateFlatIconFromImage('/img/ionicons/512/' + imageName + '.png');\n });\n}",
"function showRepositories(repositoriesArray) {\n var print = '<h5> Repositories </h5>'\n \n print += \"<table>\";\n\n //Compose the render with stargazers coun and forks from git\n for(var i = 0; i < repositoriesArray.length; i++) {\n print += '<tr>';\n print += '<td>' + repositoriesArray[i].name + '</td>' \n + '<td> <i class=\"fa fa-star\" aria-hidden=\"true\"> </i>' + repositoriesArray[i].stargazers_count + '</td>'\n + '<td> <i class=\"fa fa-code-fork\" aria-hidden=\"true\"> </i>' + repositoriesArray[i].forks + '</td>'; \n print += '</tr>' //tr\n }\n\n print += '</table>' //table\n\n //Add the render to index\n document.getElementById(\"result\").innerHTML = print;\n }",
"function refreshBar() {\n $('owd-menubar procs').html('');\n for (var i in processes) {\n var proc = processes[i];\n var app = processes[i].getApp();\n $('owd-menubar procs').append('<proc proc-id=\"'+processes[i].pid+'\"><img src=\"'+_helper.join(app.getUrl(), app.getConfig().icons['64x64'])+'\"/> '+app.getConfig().name+'</proc>');\n $.contextMenu({\n selector: 'owd-menubar procs proc[proc-id=\"'+processes[i].pid+'\"]',\n items: {\n kill: {\n name: \"关闭\",\n icon: 'quit',\n callback: killit\n }\n }\n });\n }\n }",
"function showAllCoins() {\n let allCoins = state.getAllCacheCoins();\n showCoinsUI(allCoins);\n $(\".loading-spinner-page\").hide();\n }",
"function insertAndiBarHtml(){\n\t\tvar menuButtons = \n\t\t\"<div id='ANDI508-control-buttons-container'>\"\n\t\t\t+\"<button id='ANDI508-button-relaunch' aria-label='Relaunch ANDI' title='Press To Relaunch ANDI' accesskey='\"+andiHotkeyList.key_relaunch.key+\"'><img src='\"+icons_url+\"reload.png' alt='' /></button>\" //refresh\n\t\t\t+\"<button id='ANDI508-button-highlights' aria-label='Element Highlights' title='Press to Hide Element Highlights' aria-pressed='true'><img src='\"+icons_url+\"highlights-on.png' alt='' /></button>\" //lightbulb\n\t\t\t+\"<button id='ANDI508-button-minimode' aria-label='Mini Mode' title='Press to Engage Mini Mode'><img src='\"+icons_url+\"more.png' alt='' /></button><input type='hidden' value='false' id='ANDI508-setting-minimode' />\" //underscore/minimize\n\t\t\t+\"<button id='ANDI508-button-keys' aria-label='ANDI Hotkeys List' title='Press to Show ANDI Hotkeys List'><img src='\"+icons_url+\"keys-off.png' alt='' /></button>\"\n\t\t\t+andiHotkeyList.buildHotkeyList()\n\t\t\t+\"<button id='ANDI508-button-help' aria-label='ANDI Help' title='Press to Open ANDI Help Page in New Window'><img src='\"+icons_url+\"help.png' alt='' /></button>\"\n\t\t\t+\"<button id='ANDI508-button-close' aria-label='Remove ANDI' title='Press to Remove ANDI'><img src='\"+icons_url+\"close.png' alt='' /></button>\"\n\t\t+\"</div>\";\n\t\tvar moduleButtons = \n\t\t\"<div id='ANDI508-module-launchers'>\"\n\t\t\t+\"<button id='ANDI508-module-button-f' aria-label='andi focusable elements'>focusable elements</button>\"\n\t\t\t//+\"<button id='ANDI508-module-button-l' aria-label='landi links'>links</button>\"\n\t\t\t//+\"<button id='ANDI508-module-button-g' aria-label='gandi graphics'>graphics</button>\"\n\t\t\t+\"<button id='ANDI508-module-button-t' aria-label='tandi tables' data-ANDI508-moduleMode='scope mode'>tables</button>\"\n\t\t+\"</div>\";\n\t\tvar andiBar = \"\\\n\t\t<section id='ANDI508' tabindex='0' aria-label='ANDI Accessibility Test Tool' aria-roledescription='ANDI Accessible Name And Description Inspector' style='display:none'>\\\n\t\t<div id='ANDI508-header'>\\\n\t\t\t<h1 id='ANDI508-toolName-heading'><a id='ANDI508-toolName-link' href='#' aria-haspopup='true' aria-label='ANDI \"+andiVersionNumber+\"'><span id='ANDI508-module-name' data-ANDI508-module-version=''> </span>ANDI</a></h1>\\\n\t\t\t<div id='ANDI508-module-modes' tabindex='-1' accesskey='\"+andiHotkeyList.key_jump.key+\"'></div>\\\n\t\t\t<div id='ANDI508-controls' tabindex='-1' accesskey='\"+andiHotkeyList.key_jump.key+\"'><h2 class='ANDI508-screenReaderOnly'>ANDI Controls</h2>\\\n\t\t\t\t\"+moduleButtons+\"\\\n\t\t\t\t\"+menuButtons+\"\\\n\t\t\t</div>\\\n\t\t</div>\\\n\t\t<div id='ANDI508-body'>\\\n\t\t\t<div id='ANDI508-activeElementInspection'><h2 class='ANDI508-screenReaderOnly'>ANDI Active Element Inspection</h2>\\\n\t\t\t\t<div id='ANDI508-startUpSummary' tabindex='0' accesskey='\"+andiHotkeyList.key_jump.key+\"' />\\\n\t\t\t\t<div id='ANDI508-activeElementResults'>\\\n\t\t\t\t\t<div id='ANDI508-tagNameContainer'><h3 class='ANDI508-heading'>Element:</h3>\\\n\t\t\t\t\t\t<a href='#' accesskey='\"+andiHotkeyList.key_jump.key+\"' id='ANDI508-tagNameLink'><<span id='ANDI508-tagNameDisplay' />></a>\\\n\t\t\t\t\t</div>\\\n\t\t\t\t\t<div id='ANDI508-accessibleComponentsTableContainer'>\\\n\t\t\t\t\t\t<h3 id='ANDI508-accessibleComponentsTable-heading' class='ANDI508-heading' tabindex='0'>Accessibility Components: <span id='ANDI508-accessibleComponentsTotal'></span></h3>\\\n\t\t\t\t\t\t<table id='ANDI508-accessibleComponentsTable' aria-labelledby='ANDI508-accessibleComponentsTable-heading'><tbody tabindex='0' /></table>\\\n\t\t\t\t\t</div>\\\n\t\t\t\t\t<div id='ANDI508-outputContainer'>\\\n\t\t\t\t\t\t<h3 class='ANDI508-heading' id='ANDI508-output-heading'>ANDI Output:</h3>\\\n\t\t\t\t\t\t<div id='ANDI508-outputText' tabindex='0' accesskey='\"+andiHotkeyList.key_output.key+\"' aria-labelledby='ANDI508-output-heading ANDI508-outputText' />\\\n\t\t\t\t\t</div>\\\n\t\t\t\t</div>\\\n\t\t\t</div>\\\n\t\t\t<div id='ANDI508-pageAnalysis'><h2 class='ANDI508-screenReaderOnly'>ANDI Page Analysis</h2>\\\n\t\t\t\t<h3 class='ANDI508-heading' tabindex='0' id='ANDI508-numberOfElements-resultsSummary'></h3>\\\n\t\t\t\t<button aria-label='Previous Element' title='Focus on Previous Element' accesskey='\"+andiHotkeyList.key_prev.key+\"' id='ANDI508-button-prevElement'><img src='\"+icons_url+\"prev.png' alt='' /></button>\\\n\t\t\t\t<button aria-label='Next Element' title='Focus on Next Element' accesskey='\"+andiHotkeyList.key_next.key+\"' id='ANDI508-button-nextElement'><img src='\"+icons_url+\"next.png' alt='' /></button><br />\\\n\t\t\t\t<div id='ANDI508-additionalPageResults' />\\\n\t\t\t\t<div id='ANDI508-alerts-list'>\\\n\t\t\t\t\t<h3 id='ANDI508-numberOfAccessibilityAlerts' accesskey='\"+andiHotkeyList.key_jump.key+\"' class='ANDI508-heading' tabindex='0'>Accessibility Alerts: <span class='ANDI508-total' /></h3>\\\n\t\t\t\t\t<div id='ANDI508-alerts-container-scrollable'>\\\n\t\t\t\t\t\t<ul id='ANDI508-alertType-dangers-container' />\\\n\t\t\t\t\t\t<ul id='ANDI508-alertType-warnings-container' />\\\n\t\t\t\t\t\t<ul id='ANDI508-alertType-cautions-container' />\\\n\t\t\t\t\t</div>\\\n\t\t\t\t</div>\\\n\t\t\t</div>\\\n\t\t</div>\\\n\t\t</section>\\\n\t\t<svg id='ANDI508-laser-container'><title>ANDI Laser</title><line id='ANDI508-laser' /></svg>\\\n\t\t\";\n\t\t$(\"html\")\n\t\t\t.addClass(\"ANDI508-testPage\")\n\t\t\t.find(\"body\")\n\t\t\t\t.addClass(\"ANDI508-testPage\")\n\t\t\t\t.wrapInner(\"<div id='ANDI508-testPage' accesskey='\"+andiHotkeyList.key_jump.key+\"' />\") //Add an outer container to the test page\n\t\t\t\t.prepend(andiBar); //insert ANDI display into body\n\t}",
"function displaySpellbook() {\r\n\t\t// Hide other menus\r\n\t\taddClass($('#main_menu #shortcuts'), 'hide');\r\n\t\taddClass($('#main_menu #story'), 'hide');\r\n\t\taddClass($('#main_menu #stats'), 'hide');\r\n\t\taddClass($('#main_menu #settings'), 'hide');\r\n\r\n\t\t// Hide inside menu and show the main spellbook menu\r\n\t\taddClass($('#main_menu #spellbook #custom'), 'hide');\r\n\t\tremoveClass($('#main_menu #spellbook #spells'), 'hide');\t\t\r\n\r\n\t\tfor (x in game.mSpell.spells) {\r\n\t\t\tif (!isNaN(x)) {\r\n\t\t\t\tvar spell = game.mSpell.spells[x];\r\n\t\t\t\tvar img = '<img id=\"spell_'+x+'\" src=\"img/icon/spells/512x512/'+SpellConf.previewIcons[spell.icon]+'\"/>';\r\n\t\t\t\tvar div = $('#main_menu #spellbook #spells div#spell_'+x);\r\n\t\t\t\tdiv.innerHTML = img;\r\n\t\t\t\tdiv.setAttribute('data-hint', game.mSpell.spells[x].name);\r\n\t\t\t\taddClass(div, 'hint--top');\r\n\t\t\t\taddClass(div, 'hint--error');\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Show spellbook screen\r\n\t\tremoveClass($('#main_menu #spellbook'), 'hide');\r\n\t}",
"function level2Display() {\n if (mobiHeadEl.className.match('level3')) {\n this.style.display = 'none';\n if (pageHeaderEl.querySelector('.mobi-head.level3 #reverse')) {\n pageHeaderEl.querySelector('.mobi-head.level3 #reverse').style.display = 'none';\n }\n\n for (var childId = 0; childId < childLis.length; childId++) {\n childLis[childId].removeAttribute('style');\n }\n\n for (var s3Id = 0; s3Id < subCatLis.length; s3Id++) {\n subCatLis[s3Id].style.display = 'block';\n }\n\n mobiHeadEl.className = mobiHeadEl.className.replace(' level3', '');\n mobiHeadEl.className += ' level2';\n\n if (pageHeaderEl.querySelector('.mobi-head.level2 #reverse')) {\n pageHeaderEl.querySelector('.mobi-head.level2 #reverse').removeAttribute('style');\n }\n\n if (mainCatVal == \"Partners Programs\") {\n mobiHeadEl.querySelector('.l_content').innerHTML = '<i style=\"margin-right:2px; width:auto;\" class=\"' + mainCatClass + '\"></i><i class=\"' + mainCatClass + '\"></i><span>' + mainCatVal + '</span>';\n mobiHeadEl.querySelector('.l_content').removeAttribute('style');\n } else {\n mobiHeadEl.querySelector('.l_content').innerHTML = '<i class=\"' + mainCatClass + '\"></i><span>' + mainCatVal + '</span>';\n mobiHeadEl.querySelector('.l_content').removeAttribute('style');\n }\n }\n}",
"function updateResourceIcons() {\n if (!currentVesselData) return; // too fast of a page through the history due to call delay of the function\n var resourceList = currentVesselData.Resources.Resources.split(\"|\");\n for (resCount=0; resCount<5; resCount++) { \n if (resCount+resIndex == resourceList.length) break;\n $(\"#resImg\" + resCount).attr(\"src\", resourceList[resCount+resIndex].split(\";\")[0] + \".png\");\n $(\"#resImg\" + resCount).fadeIn();\n $(\"#resTip\" + resCount).html(resourceList[resCount+resIndex].split(\";\")[1]);\n }\n currentVesselData.Resources.HTML = $(\"#dataField8\").html();\n}",
"addToolBarItems() {\n // Ignore if the buttons are already there\n if (document.getElementsByClassName('rvt-tools').length !== 0) {\n return;\n }\n\n let btnGroup = `<div class=\"BtnGroup rvt-tools\">\n <a id=\"${Constants.SHOW_ALL_BUTTON_ID}\" class=\"${Constants.TOOL_BUTTON_CLASS}\" href=\"#\" aria-label=\"Show All\">Show All Files</a>\n <a id=\"${Constants.COLLAPSE_ALL_BUTTON_ID}\" class=\"${Constants.TOOL_BUTTON_CLASS}\" href=\"#\" aria-label=\"Collapse All\">Collapse All Files</a>\n </div>`;\n\n document.querySelector(Constants.DIFF_BAR_SELECTOR).insertAdjacentHTML('afterBegin', btnGroup);\n\n document.getElementById(Constants.COLLAPSE_ALL_BUTTON_ID).addEventListener('click', this.hideAllBodies);\n document.getElementById(Constants.SHOW_ALL_BUTTON_ID).addEventListener('click', this.showAllBodies);\n }",
"function cargarIconos(){\n // iconos para mostrar puntos\n estilosIcons[\"origen\"] = styles.marcadorInicioRecorrido();\n estilosIcons[\"destino\"] = styles.marcadorFinRecorrido();\n }",
"function initiateTgtFaPlusMinusOps(){\n\t//when page launches only\n\tif (isInitTgtToggleLoad){\n\t\t//adding '+' (collapse) by default in target catalog when page launches\n\t\tfor (let i=0;i<mstEntityDesignArr.length;i++){\n\t\t\tlet mstEntityDesignJson = mstEntityDesignArr[i];\n\t\t\t\n\t\t\t//parsing each nodes and check whether the node contains sub nodes (i.e., ul > li), if exist -> then add 'fa plus' and 'hide' it\n\t\t\tlet children = $('#tgt-' + mstEntityDesignJson.dropId + ' > span').parent('li.parent_li').find(' > ul > li'); \n\t\t\tif (children.is(\":visible\")) {\n\t\t\t\tchildren.hide('fast');\n\t\t\t\t$('#tgt-' + mstEntityDesignJson.dropId + ' > span').find('i').addClass('fa-plus-square').removeClass('fa-minus-square');\n\t\t\t}\n\t\t\t\n\t\t\t//Adding click event for each node when page launches\n\t\t\t$('#tgt-' + mstEntityDesignJson.dropId + ' > span').on('click', function(e) {\n\t\t\t let children = $(this).parent('li.parent_li').find(' > ul > li');\n\t\t\t \n\t\t\t\tif (children.is(\":visible\")) {\n\t\t\t\t\tconsole.log(\"Loop 0\")\n\t\t\t children.hide('fast');\n\t\t\t $(this).find(' > i').addClass('fa-plus-square').removeClass('fa-minus-square');\n\t\t\t } else {\n\t\t\t \tconsole.log(\"Loop 1\")\n\t\t\t children.show('fast');\n\t\t\t $(this).find(' > i').addClass('fa-minus-square').removeClass('fa-plus-square');\n\t\t\t }\t\t\t\n\t\t\t\t\n\t\t\t e.stopPropagation();\n\t\t\t});\n\t\t}\n\n\t}\t\t\n}",
"showRepos(repos){\r\n let output = ' <h3>Latest Repos</h3>';\r\n console.log(repos);\r\n repos.forEach(repo => {\r\n output +=`\r\n <div class=\"repo-list row\">\r\n <span class=\"repo-name col-md-6\"><a href=\"${repo.html_url}\">${repo.name}</a></span>\r\n <button type=\"button\" class=\"btn btn-primary\">\r\n Stars <span class=\"badge badge-light\">${repo.stargazers_count}</span>\r\n </button>\r\n <button type=\"button\" class=\"btn btn-primary\">\r\n Watchers <span class=\"badge badge-light\">${repo.watchers}</span>\r\n </button>\r\n <button type=\"button\" class=\"btn btn-primary\">\r\n Forks <span class=\"badge badge-light\">${repo.forms}</span>\r\n </button>\r\n </div>\r\n `;\r\n\r\n });\r\n document.querySelector('.repos').innerHTML=output;\r\n }",
"function displayDetailedInfo(info) {\n $('#info-title').html(info[0]);\n $('#infobox-detailed-content').html(info[1]);\n $('#infobox-detailed').show();\n}",
"function createAllMarketMenu() {\n\tif (!fCustomiseFlag) {\n\t splitSkeleton('popular');\n\t\tdocument.getElementById(\"popularSportsTreeContainer\").innerHTML = getMenuItems(\"popularSkeletonArray\",0,0,\"popularSportsTreeContainer\",\"popularPathArray\",\"popularParents1\");\n\t}\n\tsplitSkeleton('all');\n\tmeatArray.length = 0\n\tsplitSkeleton('meat');\n\tdocument.getElementById(\"allSportsTreeContainer\").innerHTML = getMenuItems(\"allSkeletonArray\",0,0,\"allSportsTreeContainer\",\"allPathArray\",\"menuParents1\");\n\tprimeBrowserCache();\n}",
"function displayInsulaLabels(){\n\t\tvar i;\n\t\tvar insulaId;\n\t\tvar insulaCenterCoordinates;\n\t\tvar shortInsulaName;\n\t\tfor(i=0;i<insulaGroupIdsList.length;i++){\n\t\t\tinsulaId=insulaGroupIdsList[i];\n\t\t\tinsulaCenterCoordinates=insulaCentersDict[insulaId];\n\t\t\tshortInsulaName=insulaShortNamesDict[insulaId];\n\t\t\t//insulaCenterCoordinates= adjustInsulaCenters(shortInsulaName, insulaCenterCoordinates);\n\t\t\tif(insulaCenterCoordinates!=null){\n\t\t\t\tshowALabelOnMap(insulaCenterCoordinates,shortInsulaName, \"small\", \"insula\");\n\t\t\t}\n\t\t}\n\t}",
"function showWeapons(){\n\t\t$(\"#textResult\").append(\"<p class=\\\"weaponText\\\">Choose Your Weapon</p>\");\n\t \t$(\"#weaponHolderPlayer\"+playerID).empty();\n\t\tvar imgDiv = $(\"#weaponHolderPlayer\"+playerID);\n\t\tvar rock = \"<div class=\\\"text-center\\\"><img class=\\\"weaponImage\\\" data-item=\\\"rock\\\" width=\\\"80\\\" src=\\\"./assets/images/weapons/rock.png\\\"></div>\";\n\t\tvar paper = \"<div class=\\\"text-center\\\"><img class=\\\"weaponImage\\\" data-item=\\\"paper\\\" width=\\\"80\\\" src=\\\"./assets/images/weapons/paper.png\\\"></div>\";\n\t\tvar scissors = \"<div class=\\\"text-center\\\"><img class=\\\"weaponImage\\\" data-item=\\\"scissors\\\" width=\\\"80\\\" src=\\\"./assets/images/weapons/scissors.png\\\"></div>\";\n\t\timgDiv.append(rock,paper,scissors);\n\t\t$(\"#weaponHolderPlayer\"+playerID).css({\"visibility\":\"visible\"});\n}",
"function showLoadingStatus() {\n console.log(\"[menu_actions.js] Showing loading status\");\n showElementById(\"loading-status\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an instance of ConfigurationHandler | function createInstance() {
/**
* Initialize the configuration.
*
* @method module:ConfigurationHandler#init
* @param {string} region - REGION name where the App Configuration service instance is
* created.
* @param {string} guid - GUID of the App Configuration service.
* @param {string} apikey - APIKEY of the App Configuration service.
*/
function init(region, guid, apikey) {
_guid = guid;
urlBuilder.setRegion(region);
urlBuilder.setGuid(guid);
urlBuilder.setApikey(apikey);
urlBuilder.setAuthenticator();
}
/**
* Used to re-initialize this module
*
* 1. Clears the interval set for internet check
* 2. Clears any scheduled retries if they were set
* 3. Deletes the configurations stored in SDK defined file path
* @method module:ConfigurationHandler#cleanup
*/
function cleanup() {
clearInterval(interval);
clearTimeout(retryScheduled);
if (_persistentCacheDirectory) {
FileManager.deleteFileData(path.join(_persistentCacheDirectory, 'appconfiguration.json'));
}
_onSocketRetry = false;
}
/**
* Stores the given configurations data into respective maps.
* (_featureMap, _propertyMap, _segmentMap)
*
* @method module:ConfigurationHandler#loadConfigurationsToCache
* @param {JSON} data - The configurations data
*/
function loadConfigurationsToCache(data) {
if (data) {
if (data.features && Object.keys(data.features).length) {
const { features } = data;
_featureMap = {};
features.forEach((feature) => {
_featureMap[feature.feature_id] = new Feature(feature);
});
}
if (data.properties && Object.keys(data.properties).length) {
const { properties } = data;
_propertyMap = {};
properties.forEach((property) => {
_propertyMap[property.property_id] = new Property(property);
});
}
if (data.segments && Object.keys(data.segments).length) {
const { segments } = data;
_segmentMap = {};
segments.forEach((segment) => {
_segmentMap[segment.segment_id] = new Segment(segment);
});
}
}
}
/**
* Writes the given data on to the persistent volume.
*
* @async
* @param {JSON|string} fileData - The data to be written
* @returns {undefined} If fileData is null
*/
async function writeToPersistentStorage(fileData) {
if (fileData == null) {
logger.log('No data');
return;
}
const json = JSON.stringify(fileData);
FileManager.storeFiles(json, (path.join(_persistentCacheDirectory, 'appconfiguration.json')), () => { });
}
/**
* Creates API request and waits for the response.
* If response has data, then passes the response data to `writeToPersistentStorage()` method
* for further actions. Else, logs the error message to console.
*
* @async
* @method module:ConfigurationHandler#fetchFromAPI
*/
async function fetchFromAPI() {
retryCount -= 1;
try {
const query = {
environment_id: _environmentId,
};
const parameters = {
options: {
url: `/apprapp/feature/v1/instances/${_guid}/collections/${_collectionId}/config`,
method: 'GET',
qs: query,
},
defaultOptions: {
serviceUrl: urlBuilder.getBaseServiceUrl(),
headers: urlBuilder.getHeaders(),
},
};
const response = await ApiManager.createRequest(parameters);
if (response && _liveUpdate) {
// load the configurations in the response to cache maps
loadConfigurationsToCache(response.result);
emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);
// asynchronously write the response to persistent volume, if enabled
if (_persistentCacheDirectory) {
writeToPersistentStorage(response.result);
}
} else if (retryCount > 0) {
logger.log('Retrying to fetch the configurations');
fetchFromAPI();
} else {
logger.error(`Failed to fetch the configurations. Retrying after ${retryTime} minutes`);
retryCount = 3;
retryScheduled = setTimeout(() => fetchFromAPI(), retryTime * 60000);
}
} catch (error) {
logger.error(error.message);
}
}
/**
* Perform websocket connect to appconfiguration server
*
* @async
* @method module:ConfigurationHandler#connectWebSocket
*/
async function connectWebSocket() {
try {
const urlForWebsocket = urlBuilder.getWebSocketUrl(_collectionId, _environmentId);
const _bearerToken = await urlBuilder.getToken();
const headers = {
Authorization: _bearerToken,
};
closeWebSocket(); // close existing websocket connection if any
socketClient.connect(
urlForWebsocket, [], [], headers,
);
} catch (error) {
logger.warning(error.message);
logger.warning('Connection to the App Configuration server failed with unexpected error');
}
}
function isJSONDataEmpty(jsonData) {
if (Object.keys(jsonData).length === 0) {
return true;
}
return false;
}
async function fetchConfigurationsData() {
if (_liveUpdate) {
await fetchFromAPI();
connectWebSocket();
}
}
/**
* Sets the context of the SDK
*
* @method module:ConfigurationHandler#setContext
* @param {string} collectionId - Id of the collection created in App Configuration service
* instance.
* @param {string} environmentId - Id of the environment created in App Configuration
* service instance.
* @param {object} [options] - Options object
* @param {string} [options.persistentCacheDirectory] - Absolute path to a directory which has
* read & write permissions for file operations.
* @param {string} [options.bootstrapFile] - Absolute path of configuration file. This parameter
* when passed along with `liveConfigUpdateEnabled` value will drive the SDK to use the
* configurations of this file to perform feature & property evaluations.
* @param {boolean} [options.liveConfigUpdateEnabled] - live configurations update from the server.
* Set this value to `false` if the new configuration values shouldn't be fetched from the server.
*/
function setContext(collectionId, environmentId, options) {
// when setContext is called more than one time with any of collectionId, environmentId or options
// different from its previous time, cleanup method is invoked.
// don't do the cleanup when setContext is called for the first time.
if ((_collectionId && (_collectionId !== collectionId))
|| (_environmentId && (_environmentId !== environmentId))
|| (_persistentCacheDirectory && (_persistentCacheDirectory !== options.persistentCacheDirectory))
|| (_bootstrapFile && (_bootstrapFile !== options.bootstrapFile))
) {
cleanup();
}
_collectionId = collectionId;
_environmentId = environmentId;
_persistentCacheDirectory = options.persistentCacheDirectory;
_bootstrapFile = options.bootstrapFile;
_liveUpdate = options.liveConfigUpdateEnabled;
if (_persistentCacheDirectory) {
persistentData = FileManager.getFileData(path.join(_persistentCacheDirectory, 'appconfiguration.json'));
// no emitting the event here. Only updating cache is enough
loadConfigurationsToCache(persistentData);
try {
fs.accessSync(_persistentCacheDirectory, fs.constants.W_OK);
} catch (err) {
logger.error(Constants.ERROR_NO_WRITE_PERMISSION);
return;
}
}
if (_bootstrapFile) {
if (_persistentCacheDirectory) {
if (isJSONDataEmpty(persistentData)) {
try {
const bootstrapFileData = FileManager.getFileData(_bootstrapFile);
loadConfigurationsToCache(bootstrapFileData);
emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);
writeToPersistentStorage(bootstrapFileData)
} catch (error) {
logger.error(error);
}
} else {
// only emit the event here. Because, cache is already updated above (line 270)
emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);
}
} else {
const bootstrapFileData = FileManager.getFileData(_bootstrapFile);
loadConfigurationsToCache(bootstrapFileData);
emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);
}
}
if (_liveUpdate) {
checkInternet().then((val) => {
if (!val) {
logger.warning(Constants.NO_INTERNET_CONNECTION_ERROR);
_isConnected = false;
}
});
interval = setInterval(() => {
checkInternet().then((val) => {
if (!val) {
logger.warning(Constants.NO_INTERNET_CONNECTION_ERROR);
_isConnected = false;
} else {
if (!_isConnected) {
_onSocketRetry = false;
fetchFromAPI();
connectWebSocket();
}
_isConnected = true;
}
});
}, 30000); // 30 second
}
fetchConfigurationsData();
}
async function socketActions() {
fetchFromAPI();
}
/**
* Get the Feature object containing all features
*
* @method module:ConfigurationHandler#getFeatures
* @returns {object} Feature object
*/
function getFeatures() {
return _featureMap;
}
/**
* Get the Feature with give Feature Id
*
* @method module:ConfigurationHandler#getFeature
* @param {string} featureId - The Feature Id
* @returns {object|null} Feature object
*/
function getFeature(featureId) {
if (Object.prototype.hasOwnProperty.call(_featureMap, featureId)) {
return _featureMap[featureId];
}
logger.error(`Invalid feature id - ${featureId}`);
return null;
}
/**
* Get the Property object containing all properties
*
* @method module:ConfigurationHandler#getProperties
* @returns {object} Property object
*/
function getProperties() {
return _propertyMap;
}
/**
* Get the Property with give Property Id
*
* @method module:ConfigurationHandler#getProperty
* @param {string} propertyId - The Property Id
* @returns {object|null} Property object
*/
function getProperty(propertyId) {
if (Object.prototype.hasOwnProperty.call(_propertyMap, propertyId)) {
return _propertyMap[propertyId];
}
logger.error(`Invalid property id - ${propertyId}`);
return null;
}
function getSegment(segmentId) {
if (Object.prototype.hasOwnProperty.call(_segmentMap, segmentId)) {
return _segmentMap[segmentId];
}
logger.error(`Invalid segment id - ${segmentId}`);
return null;
}
function evaluateSegment(segmentKey, entityAttributes) {
if (Object.prototype.hasOwnProperty.call(_segmentMap, segmentKey)) {
const segmentObjc = _segmentMap[segmentKey];
return segmentObjc.evaluateRule(entityAttributes);
}
return null;
}
function _parseRules(segmentRules) {
const rulesMap = {};
segmentRules.forEach((rules) => {
rulesMap[rules.order] = new SegmentRules(rules);
});
return rulesMap;
}
function evaluateRules(_rulesMap, entityAttributes, feature, property) {
const resultDict = {
evaluated_segment_id: Constants.DEFAULT_SEGMENT_ID,
value: null,
};
try {
for (let index = 1; index <= Object.keys(_rulesMap).length; index += 1) {
const segmentRule = _rulesMap[index];
if (segmentRule.rules.length > 0) {
for (let level = 0; level < segmentRule.rules.length; level += 1) {
const rule = segmentRule.rules[level];
const { segments } = rule;
if (segments.length > 0) {
for (let innerLevel = 0; innerLevel < segments.length; innerLevel += 1) {
const segmentKey = segments[innerLevel];
if (evaluateSegment(segmentKey, entityAttributes)) {
resultDict.evaluated_segment_id = segmentKey;
if (segmentRule.value === '$default') {
if (feature !== null) {
resultDict.value = feature.enabled_value;
} else {
resultDict.value = property.value;
}
} else {
resultDict.value = segmentRule.value;
}
return resultDict;
}
}
}
}
}
}
} catch (error) {
logger.error(`RuleEvaluation ${error}`);
}
if (feature !== null) {
resultDict.value = feature.enabled_value;
} else {
resultDict.value = property.value;
}
return resultDict;
}
/**
* Records each of feature & property evaluations done by sending it to metering module.
* See {@link module:Metering}
*
* @method module:ConfigurationHandler#recordEvaluation
* @param {string} featureId - The Feature Id
* @param {string} propertyId - The Property Id
* @param {string} entityId - The Entity Id
* @param {string} segmentId - The Segment Id
*/
function recordEvaluation(featureId, propertyId, entityId, segmentId) {
meteObj.addMetering(_guid,
_environmentId,
_collectionId,
entityId,
segmentId,
featureId,
propertyId);
}
/**
* Feature evaluation
*
* @method module:ConfigurationHandler#featureEvaluation
* @param {object} feature - Feature object
* @param {string} entityId - Entity Id
* @param {object} entityAttributes - Entity attributes object
* @returns {boolean|string|number} Feature evaluated value
*/
function featureEvaluation(feature, entityId, entityAttributes) {
let resultDict = {
evaluated_segment_id: Constants.DEFAULT_SEGMENT_ID,
value: null,
};
try {
if (feature.enabled) {
if (!entityAttributes || Object.keys(entityAttributes).length <= 0) {
return feature.enabled_value;
}
if (feature.segment_rules && feature.segment_rules.length > 0) {
const _rulesMap = _parseRules(feature.segment_rules);
resultDict = evaluateRules(_rulesMap, entityAttributes, feature, null);
return resultDict.value;
}
return feature.enabled_value;
}
return feature.disabled_value;
} finally {
recordEvaluation(feature.feature_id, null, entityId, resultDict.evaluated_segment_id);
}
}
/**
* Property evaluation
*
* @method module:ConfigurationHandler#propertyEvaluation
* @param {object} property - Property object
* @param {string} entityId - Entity Id
* @param {object} entityAttributes - Entity attributes object
* @returns {boolean|string|number} Property evaluated value
*/
function propertyEvaluation(property, entityId, entityAttributes) {
let resultDict = {
evaluated_segment_id: Constants.DEFAULT_SEGMENT_ID,
value: null,
};
try {
if (!entityAttributes || Object.keys(entityAttributes).length <= 0) {
return property.value;
}
if (property.segment_rules && property.segment_rules.length > 0) {
const _rulesMap = _parseRules(property.segment_rules);
resultDict = evaluateRules(_rulesMap, entityAttributes, null, property);
return resultDict.value;
}
return property.value;
} finally {
recordEvaluation(null, property.property_id, entityId, resultDict.evaluated_segment_id);
}
}
// Other event listeners
emitter.on(Constants.MEMORY_CACHE_ACTION_SUCCESS, () => {
emitter.emit(Constants.APPCONFIGURATION_CLIENT_EMITTER);
});
// Socket Listeners
emitter.on(Constants.SOCKET_CONNECTION_ERROR, (error) => {
logger.warning(`Connecting to app configuration server failed. ${error}`);
logger.warning(Constants.CREATE_NEW_CONNECTION);
_onSocketRetry = true;
connectWebSocket();
});
emitter.on(Constants.SOCKET_LOST_ERROR, (error) => {
logger.warning(`Connecting to app configuration server lost. ${error}`);
logger.warning(Constants.CREATE_NEW_CONNECTION);
_onSocketRetry = true;
connectWebSocket();
});
emitter.on(Constants.SOCKET_CONNECTION_CLOSE, () => {
logger.warning('server connection closed. Creating a new connection to the server.');
logger.warning(Constants.CREATE_NEW_CONNECTION);
_onSocketRetry = true;
connectWebSocket();
});
emitter.on(Constants.SOCKET_MESSAGE_RECEIVED, (data) => {
logger.log(`Received message from server. ${data}`);
});
emitter.on(Constants.SOCKET_CALLBACK, () => {
socketActions();
});
emitter.on(Constants.SOCKET_MESSAGE_ERROR, () => {
logger.warning('Message received from server is invalid.');
});
emitter.on(Constants.SOCKET_CONNECTION_SUCCESS, () => {
logger.log('Successfully connected to App Configuration server');
if (_onSocketRetry === true) {
socketActions();
}
_onSocketRetry = false;
});
return {
init,
setContext,
getFeature,
getFeatures,
getProperty,
getProperties,
getSegment,
featureEvaluation,
propertyEvaluation,
cleanup,
};
} | [
"configurationRequestHandler (context, request, callback) {\n callback(null);\n }",
"constructor() { \n \n ConfigHash.initialize(this);\n }",
"static create() {\n return new FastHttpMiddlewareHandler();\n }",
"function Configuration(resource) {\n // defining the encoding as utf-8.\n this.ENCODING = 'utf8';\n this.config = this.loadConfigResource(resource); // this function is defined in the below line.\n }",
"config() {\n if (this.isBound(exports.names.APP_SERVICE_CONFIG)) {\n return this.get(exports.names.APP_SERVICE_CONFIG);\n }\n else {\n throw new Error('configuration object not yet loaded!');\n }\n }",
"function Configuration(props) {\n return __assign({ Type: 'AWS::AmazonMQ::Configuration' }, props);\n }",
"function ConfigurationRecorder(props) {\n return __assign({ Type: 'AWS::Config::ConfigurationRecorder' }, props);\n }",
"add_configuration_listener(house_id, args, wait_for_it) {\r\n // just wrap add_listener\r\n var topic = this.add_listener(house_id, \"controller/config\", \"*/*\", \"CONF\", args, wait_for_it)\r\n // if the config is not retained on the gateway, notify controller/config\r\n if (this.__module.gateway_version >= 2) {\r\n // add the configuration to the pending queue\r\n this.pending_configurations.push(args)\r\n // request the configuration files\r\n this.__send_configuration_request(args)\r\n // if not already running, schedule a job for periodically resending configuration requests in case controller/config has not responded\r\n if (this.pending_configurations_job == null) {\r\n this.pending_configurations_job = setInterval(function(this_class) {\r\n return this_class.__resend_configuration_request()\r\n }(this), 2000);\r\n }\r\n }\r\n return topic\r\n }",
"function configFactory(options, config) {\n // validate the input arguments\n const { error } = optionsSchema.validate(options);\n if (error) throw error;\n\n const { client } = config;\n const rootDir = appRootDir.get();\n // webpack configuration\n return {\n devtool: 'cheap-module-eval-source-map',\n // input entry\n entry: {\n // the vendor dll name\n [client.development.vendorDll.variable]: [\n // dependencies required to bundle into vendor dll\n ...client.development.vendorDll.includes,\n ],\n },\n output: {\n // output path\n path: path.resolve(rootDir, client.outputPath),\n // output filename\n filename: client.development.vendorDll.filename,\n // The name of the global variable which the library's\n // require() function will be assigned to\n library: client.development.vendorDll.variable,\n },\n plugins: [\n // webpack dll plugin\n new webpack.DllPlugin({\n // the output json file\n path: path.resolve(rootDir, client.development.vendorDll.manifest),\n // global variable name\n name: client.development.vendorDll.variable,\n }),\n ],\n };\n}",
"function Config(obj) {\n if (!(this instanceof Config)) {\n return new Config(obj)\n }\n\n obj = obj || {}\n\n this.data = null\n this._loadObj(obj)\n}",
"function initConfig (event) {\n let config = null;\n\n if (!fs.existsSync(configPath)) {\n const fd = fs.openSync(configPath, 'w');\n\n const initialConfig = {\n apiServer: '',\n operator: '',\n notificationsEnabled: true,\n };\n\n fs.writeSync(fd, JSON.stringify(initialConfig, null, ' '), 0, 'utf8');\n fs.closeSync(fd);\n }\n\n config = JSON.parse(fs.readFileSync(configPath).toString());\n event.sender.send('config', config);\n}",
"function Config(action) {\n trace(whoAmI,\"Constructor\",true);\n\n var fName = \"cva-create.json\";\n var homeEnv = (utils.isWindows) ? 'USERPROFILE' : 'HOME';\n var homePath = process.env[homeEnv];\n\n // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n // Check that the user's home path can be identified\n // If this fails, then throw toys out of pram, pack up and go home\n // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n if (!homePath || homePath.length == 0) {\n utils.writeToConsole('error',\n [[\"\\nUser home directory cannot be identified!\".error],\n [\"Please set the environment variable \" + homeEnv + \" to a valid location\"]]);\n process.exit(1);\n }\n\n var localConfigFile = path.join(\".\", fName);\n var globalConfigFile = path.join(homePath, fName);\n \n this.configFiles.globalConfig.path = globalConfigFile\n this.configFiles.globalConfig.exists = fs.existsSync(globalConfigFile);\n\n this.configFiles.localConfig.path = localConfigFile;\n this.configFiles.localConfig.exists = fs.existsSync(localConfigFile);\n \n // Does the global config file already exist?\n if (this.configFiles.globalConfig.exists) {\n // Yup, so read that file and merge its contents with values from the prototype.\n // The merge guarantees that all property values exist and have at least a\n // default value\n mergeProperties(\"global\",utils.readJSONFile(this.configFiles.globalConfig.path), this);\n }\n else {\n // Nope, so create a global configuration file\n generateGlobalConfig(this);\n }\n \n // Now read the local configuration file and merge its contents with the global values\n mergeProperties(\"local\",utils.readJSONFile(this.configFiles.localConfig.path), this);\n\n trace(whoAmI,\"Constructor\",false);\n}",
"function getConfiguration() {\n var request = new XMLHttpRequest();\n\n request.onreadystatechange = function() {\n if (request.readyState === 4) {\n\n /*---------- getting app configuration ----------*/\n var appConfiguration = JSON.parse(request.response);\n /*---------- assigning appname or main module ----------*/\n w.appName = appConfiguration.appName;\n /*---------- main redirect url for ui-router default url link ----------*/\n w.defaultUrl = appConfiguration.defaultUrl;\n /*---------- all the modules to load ----------*/\n var modules = appConfiguration.modules;\n\n for (var i = 0; i < modules.length; i++) {\n loadSingleScript(modules[i].name);\n // ===============================\n // saving modules for using\n // in the bootstrap file\n // as dependency\n // =============================== \n w.modules.push(modules[i].name);\n // =================================\n // if modules main files are loaded\n // this is called to load their\n // dependend files\n // =================================\n if ((i + 1) == modules.length) {\n setTimeout(function() {\n loadDependencyFiles(appConfiguration);\n }, 100);\n }\n }\n }\n }\n\n request.open('Get', 'app.json');\n request.send();\n }",
"constructor(config_dir){\n if(fs.existsSync(config_dir)){\n if(typeof require(config_dir) == 'json' || typeof require(config_dir) == 'object'){\n this.config = require(config_dir);\n\n // Load the access token key.\n if(this.config.mode == 'sandbox') this.config.token = this.config.keys.sandbox;\n else if(this.config.mode == 'production') this.config.token = this.config.keys.production;\n\n // Log to console.\n if(this.config.mode == 'sandbox'){\n console.log('[Flip Gocardless] => Running in ' + this.config.mode);\n console.log('[Flip GoCardless] => Loaded configuration files.');\n }\n }\n else throw '[Flip GoCardless] => Invalid config file contents.';\n }\n else throw '[Flip GoCardless] => Invalid config file.';\n }",
"function MockConfigAddon() {\n MockConfigAddon.superclass.constructor.apply(this, arguments);\n }",
"static defaultConfig() {\r\n if (_defaultConfig == null) {\r\n _defaultConfig = new Config(\"./config/etc/config.json\");\r\n }\r\n\r\n return _defaultConfig;\r\n }",
"function ParseConfiguration (err, data)\n{\n if (err)\n return console.log (err);\n\n config = JSON.parse (data);\n\n SetupClient ();\n}",
"constructor() { \n \n S3StorageConfig.initialize(this);\n }",
"function wrs_loadConfiguration() {\r\n if (typeof _wrs_conf_path == 'undefined') {\r\n _wrs_conf_path = wrs_getCorePath();\r\n }\r\n\r\n var httpRequest = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');\r\n var configUrl = _wrs_int_conf_file.indexOf(\"/\") == 0 || _wrs_int_conf_file.indexOf(\"http\") == 0 ? _wrs_int_conf_file : wrs_concatenateUrl(_wrs_conf_path, _wrs_int_conf_file);\r\n httpRequest.open('GET', configUrl, false);\r\n httpRequest.send(null);\r\n\r\n var jsonConfiguration = JSON.parse(httpRequest.responseText);\r\n var variables = Object.keys(jsonConfiguration);\r\n for (var variable in variables) {\r\n window[variables[variable]] = jsonConfiguration[variables[variable]];\r\n }\r\n\r\n // Services path (tech dependant).\r\n wrs_loadServicePaths(configUrl);\r\n\r\n // End configuration.\r\n _wrs_conf_configuration_loaded = true;\r\n if (typeof _wrs_conf_core_loaded != 'undefined') {\r\n _wrs_conf_plugin_loaded = true;\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CODING CHALLENGE 619 Create a function that takes the number of daily average recovered cases recovers, daily average newCases, current activeCases, and returns the number of days it will take to reach zero cases. | function endCorona(recovers, newCases, activeCases) {
return Math.ceil(activeCases / (recovers - newCases));
} | [
"function checkerdex(dates)\n{\n\tvar sum = 0;\n\n\tvar now = dates[dates.length - 1];\n\tfor (var i = 0; i < dates.length; i++)\n\t{\n\t\tvar weight = (rangeMS - (now - dates[i])) / rangeMS;\n\t\tsum += weight * baseScore;\n\t}\n\n\treturn sum;\n}",
"function infectionsByRequestedTimeCalc(\n currentlyInfected,\n noOfDays,\n population\n) {\n const factor = Math.trunc(noOfDays / 3);\n // const infectionsByRequestedTime = Math.min(\n // currentlyInfected * (2 ** factor),\n // population\n // );\n console.log(population);\n const infectionsByRequestedTime = currentlyInfected * (2 ** factor);\n\n return infectionsByRequestedTime;\n}",
"function totalDayWorked(numOfDays,dailyWage){\n if(dailyWage>0) return numOfDays+1;\n return numOfDays;\n}",
"function totalDaysEmpWorked(numOfDays, dailyWage) {\n if (dailyWage > 0) {\n return numOfDays + 1;\n }\n return numOfDays;\n}",
"function insurance(age, size, numofdays){\n let sum = 0;\n if (age < 25) {\n sum += (numofdays * 10) //There is a daily charge of $10 if the driver is under 25\n };\n if (numofdays < 0) {\n return 0 //Negative rental days should return 0 cost.\n };\n if (size === \"economy\") { //car size surcharge \"economy\" $0 \"medium\" $10 \"full-size\" $15.\n sum += 0;\n } else if (size === \"medium\") {\n sum += (numofdays * 10);\n } else {\n sum += (numofdays * 15); //Any other car size NOT listed should come with a same surcharge as the \"full-size\", $15.\n }\n sum += (50 * numofdays); //There is a base daily charge of $50 for renting a car.\n return sum;\n}",
"function calcIntervalEF(card, grade) {\n var oldEF = card.rating.ef,\n newEF = 0,\n nextDate = new Date(today);\n\n card.rating.grade = grade;\n\n if (grade < 3) {\n card.rating.repetition = 0;\n card.rating.interval = 0;\n } else {\n\n newEF = oldEF + (0.1 - (5 - grade) * (0.08 + (5 - grade) * 0.02));\n if (newEF < 1.3) { // 1.3 is the minimum EF\n card.rating.ef = 1.3;\n } else {\n card.rating.ef = newEF;\n }\n\n card.rating.repetition = card.rating.repetition + 1;\n\n switch (card.rating.repetition) {\n case 1:\n card.rating.interval = 1;\n break;\n case 2:\n card.rating.interval = 6;\n break;\n default:\n card.rating.interval = Math.round((card.rating.repetition - 1) * card.rating.ef);\n break;\n }\n }\n\n if (grade === 3) {\n card.rating.interval = 0;\n }\n\n nextDate.setDate(today.getDate() + card.rating.interval);\n card.rating.nextRepetition = nextDate;\n}",
"function currentlyInfectedCalc(reportedCases, type, population) {\n // if (type === severeImpact) {\n // return Math.min(reportedCases * 50, population);\n // }\n // return Math.min(reportedCases * 10, population);\n console.log(population);\n if (type === severeImpact) {\n return reportedCases * 50;\n }\n return reportedCases * 10;\n}",
"function calcDeath(netIncome, existingLifeCover, insertDeathValue, insertIncomeGap, insertMortgage, hideInfo, fadeInMessage, \nhideChart, termVal,twoLives) {\n\t\n\tconsole.log(existingLifeCover);\n\t\n\t//married = state benefit, not married = no state benefit\n\tvar stateBenefit = calculateStateBenefit();\n\tvar mortgagePayment = Number(removeCommaFromNumber($('.output2').html()));\n\t\n\tconsole.log(stateBenefit);\n\t\n\t//no mortgage\n\tif ($('#income-age').val() == 0)\n\t{\n\t\tmortgagePayment = 0;\n\t}\n\t var sumDeath = 0;\t\n\t \n\t var monthlyGap = Number(removeCommaFromNumber(netIncome)) - stateBenefit - mortgagePayment;\n\t var overallTermGap = monthlyGap * 12 * Number(termVal);\n\t \n\t //if single review, not married and have no children lumpum on death is 0 \n\t if($('input[name=about-rel]:checked').val() == 'Single' && !twoLives && $('#radio4').is(':checked')) {\n\t\t sumDeath=0;\n\t\t //console.log('not married and have no children ');\n\t }\n\t else {\n\t\tsumDeath = overallTermGap - Number(removeCommaFromNumber(existingLifeCover));\n\t\tsumDeath = Math.round(sumDeath);\n\t }\n\t if (sumDeath > 0 && sumDeath < minLifeCover) {\n\t\tsumDeath = minLifeCover;\n\t }\t \n\t insertDeathValue.html('€' + addCommas(sumDeath));\n\t insertIncomeGap.html('€' + addCommas(Math.round(monthlyGap)));\n\t insertMortgage.html('€' + $('.output2').html());\n\t $('.state-benefit').html('€' + stateBenefit);\n\t \n\n\t \n\t if ($('#income-age').val() == 0) {\n\t\t$('.mid-slice').addClass('hidden');\n\t }\n\t \n\t else {\n\t\t$('.mid-slice').removeClass('hidden');\n\t }\n\t \n\t\n\t \n\t \n\t //console.log('The existing life cover being calculated for lumpsum on death is ' + addCommas(existingLifeCover));\n\t //console.log('The lumpsum on death is ' + addCommas(sumDeath));\t\t\n\n if (sumDeath <= 0) {\n\t\tinsertDeathValue.html('');\n\t\thideInfo.addClass('hidden');\n\t\tfadeInMessage.removeClass('hidden');\n\t\t$('.death-tick').removeClass('fa-check');\n\t\t$('.death-tick').addClass('fa-times');\n\t\tif($(window).width() >= 768) {\n\t\t$('.quote-box1').insertAfter('.quote-box3');\n\t\t$('.cost-box1').insertAfter('.cost-box3');\n\t\t}\n\t\thideChart.addClass('hidden');\n\t}\t \n\t\n\telse {\n\t\t$('.death-tick').removeClass('fa-times');\n\t\t$('.death-tick').addClass('fa-check');\n\t\thideInfo.removeClass('hidden');\n\t\tfadeInMessage.addClass('hidden');\n\t\thideChart.removeClass('hidden');\n\t}\n\t \n\t//}\n\treturn sumDeath;\n\n}",
"tickDisease(days = 1) {\n this.daysElapsed+=days;\n const newTotals = {\n susceptible: 0,\n infected: 0,\n recovered: 0,\n deceased: 0,\n testsConducted: 0,\n daysLost: 0\n };\n\n // This handles disease progression\n // TODO: cost model\n for (const actor of this.actors) {\n actor.tick(days);\n // Update totals\n switch (actor.status) {\n case ACTOR_STATUS.RECOVERED: { newTotals.recovered++; break; }\n case ACTOR_STATUS.SUSCEPTIBLE: { newTotals.susceptible++; break; }\n case ACTOR_STATUS.INFECTIOUS: { newTotals.infected++; break; }\n case ACTOR_STATUS.EXPOSED: { newTotals.infected++; break; }\n case ACTOR_STATUS.DECEASED: { newTotals.deceased++; break; }\n }\n newTotals.testsConducted+=actor.testsConducted;\n newTotals.daysLost+=actor.daysIsolated;\n }\n this.totals = newTotals;\n }",
"function getDefCasualties(hits) {\n //alert('made it into function'); //debugging alert\n while (hits > 0) {\n if (hits > defBmr) {\n hits -= defBmr;\n defBmr = 0;\n } else if (hits <= defBmr) {\n defBmr -= hits;\n hits = 0;\n }\n if (hits > defInf) {\n hits -= defInf;\n defInf = 0;\n } else if (hits <= defInf) {\n defInf -= hits;\n hits = 0;\n }\n if (hits > defArt) {\n hits -= defArt;\n defArt = 0;\n } else if (hits <= defArt) {\n defArt -= hits;\n hits = 0;\n }\n if (hits > defTnk) {\n hits -= defTnk;\n defTnk = 0;\n } else if (hits <= defTnk) {\n defTnk -= hits;\n hits = 0;\n }\n if (hits > defFtr) {\n hits -= defFtr;\n defFtr = 0;\n } else if (hits <= defFtr) {\n defFtr -= hits;\n hits = 0;\n }\n if(hits > 0 && defInf == 0 && defArt == 0 && defTnk == 0 && defFtr == 0 && defBmr == 0 ){\n hits = 0;\n }\n }\n //alert('Determined Def Casualties'); //debugging alert\n}",
"function getPV(current_cashflow, growth_rate_1, growth_rate_2, discount_rate){\n var pv = 0\n var temp = current_cashflow\n var sum = 0\n for(var i = 0; i < 10; i++){\n var discountFactor = 1 / (1 + discount_rate) ** (i + 1)\n //Before Discount\n if(i < 3)\n temp = temp * growth_rate_1 \n else\n temp = temp * growth_rate_2 \n // console.log(\"temp\", i+1, \": \", temp);\n //After discount\n sum += temp * discountFactor\n // console.log(\"discount\", i+1, \": \", discountFactor);\n // console.log(\"sum \",i+1, \": \",sum)\n }\n pv = sum\n return pv\n}",
"function total_sub_instruction_count_aux(id_of_top_ins, aic_array){\n let result = 0 //this.added_items_count[id_of_top_ins]\n let tally = 1 //this.added_items_count[id_of_top_ins]\n for(let i = id_of_top_ins; true ; i++){\n let aic_for_i = aic_array[i] //this.added_items_count[i]\n if (aic_for_i === undefined) {\n shouldnt(\"total_sub_instruction_count_aux got undefined from aic_array: \" + aic_array)\n }\n result += aic_for_i //often this is adding 0\n tally += aic_for_i - 1\n if (tally == 0) { break; }\n else if (tally < 0) { shouldnt(\"in total_sub_instruction_count got a negative tally\") }\n }\n return result\n}",
"function defineDayCapacities(){\n\tvar l = dateSpan.length;\n\t\n\tvar workSchedule = [];\n\tworkSchedule[0] = U.profiles[Profile].workSchedule.su;\n\tworkSchedule[1] = U.profiles[Profile].workSchedule.mo;\n\tworkSchedule[2] = U.profiles[Profile].workSchedule.tu;\n\tworkSchedule[3] = U.profiles[Profile].workSchedule.we;\n\tworkSchedule[4] = U.profiles[Profile].workSchedule.th;\n\tworkSchedule[5] = U.profiles[Profile].workSchedule.fr;\n\tworkSchedule[6] = U.profiles[Profile].workSchedule.sa;\n\t\n\tvar vacationDays = U.profiles[Profile].vacationDays;\n\tvar numberOfVacationDays = vacationDays.length;\n\n\tfor(i=0;i<l;i++){\n\t\tdateSpan[i].capacity = workSchedule[dateSpan[i].dayNumber];\n\t\t\n\t\tif(i == 0){\n\t\t\t//The first day being set is today; see how much time remains before today is over\n\t\t\tvar timeRemainingBeforeMidnight = (new Date(today.toDateString()).getTime() + 86400000) - (new Date().getTime());\n\t\t\t//Floor milliseconds to nearest full minute amount\n\t\t\ttimeRemainingBeforeMidnight = Math.ceil(timeRemainingBeforeMidnight/60000);\n\t\t\t//Translate minutes to hours\n\t\t\ttimeRemainingBeforeMidnight = timeRemainingBeforeMidnight/60;\n\t\t\t\n\t\t\tif(timeRemainingBeforeMidnight + totalTimeSpentToday < dateSpan[i].capacity){\n\t\t\t\t/*If the timeRemainingBeforeMidnight plus the totalTimeSpentToday is less than the day's capacity \n\t\t\t\t(as defined in the workSchedule), it means there is not enough time left in the day to fit in a \n\t\t\t\tfull work day, so the day's capacity is reduced accordingly.*/\n\t\t\t\tif(!dayCapacityAdjustmentMessageShown && U.hasHadTour == true){ //We don't want to show this when someone first signs up\n\t\t\t\t\tshowMessageBar(1,\"Today's Work Schedule has been altered according to the remaining hours in the day.\");\n\t\t\t\t\tdayCapacityAdjustmentMessageShown = true;\n\t\t\t\t}\n\t\t\t\t//console.log(\"Today's workSchedule says we should have \" + dateSpan[i].capacity + \" hours to work, but there are only \" + timeRemainingBeforeMidnight + \" hours left in the day.\");\n\t\t\t\tdateSpan[i].capacity = timeRemainingBeforeMidnight + totalTimeSpentToday;\n\t\t\t\tconsole.log(\"Today's capacity has been adjusted to \" + Math.floor(dateSpan[i].capacity) + \":\" + dateSpan[i].capacity*60 %60);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t//Check if it is a vacationDay and if so, set its capacity to 0\n\t\tfor(a=0;a<numberOfVacationDays;a++){\n\t\t\tuntestedDate = dateSpan[i].date.toDateString();\n\t\t\tvacationDayToTest = new Date(vacationDays[a]).toDateString();\n\t\t\tif(untestedDate == vacationDayToTest){\n\t\t\t\tdateSpan[i].vacationDay = true;\n\t\t\t\tdateSpan[i].capacity = 0;\n\t\t\t\tbreak;\n\t\t\t}else{\n\t\t\t\tdateSpan[i].vacationDay = false;\n\t\t\t}\n\t\t}\n\t}\n\t//Once the Day Capacities and VacationDay projectStatus are set, flow the projects into the Days\n\t//console.log(\"+ capacity and vacationDay for each Day in the dateSpan has been defined. Now calling flowProjectsIntoDays().\");\n\tflowProjectsIntoDays();\n}",
"calculateNonApreciatedEquity() {\n let yearlyPrinciplePaydown = this.calculatePrinciplePaydown()\n let downpayment = this.calculateDownPayment();\n let equity = []\n for (let i = 1; i <= yearlyPrinciplePaydown.length; i++) {\n let array = yearlyPrinciplePaydown\n let sum = array.slice(0, i).reduce((a, b) => a + b, 0) + downpayment;\n equity.push(Math.floor(sum))\n }\n return equity\n }",
"function calc(income, days, isTuberculosis) {\r\n let compensation = 0.7 * income; // Compensation is 70% of income\r\n let dailyAllowance = (compensation / 30) * 0.8; // There are 30 days in bank month and 20% is the income tax(100% - 20% = 80% = 0.8)\r\n\r\n let total = 0; // Compensation total\r\n let employerDays = 0; // Amount of employer compensated days\r\n let insuranceDays = 0; // Amount of Health Insurance compensated days\r\n let employerComp = 0; // Compensation by employer (euros)\r\n let insuranceComp = 0; // Compensation by insurance (euros)\r\n\r\n const maxEventLength = isTuberculosis ? 240 : 182; // Max Event length based on either the user has or has not tuberculosis\r\n\r\n // Event can't be bigger than max\r\n if(days > maxEventLength) {\r\n alert(\"Days can't be bigger than max allowed!\");\r\n return \"\";\r\n }\r\n\r\n // Get employer and insurance days\r\n if(days < 4) {\r\n total = 0;\r\n }\r\n else if (days >= 4 && days <= 8) {\r\n employerDays = days - 3;\r\n }\r\n else if (days > 8) {\r\n insuranceDays = days - 8;\r\n employerDays = 5;\r\n }\r\n\r\n // Calculate totals\r\n employerComp = employerDays * dailyAllowance;\r\n insuranceComp = insuranceDays * dailyAllowance;\r\n\r\n total = (employerDays + insuranceDays) * dailyAllowance;\r\n\r\n // Return object of data (if all checks passed)\r\n return {\r\n dailyAllowance,\r\n employerDays,\r\n employerComp,\r\n insuranceDays,\r\n insuranceComp,\r\n total,\r\n };\r\n}",
"repeatCount(startGoal, endGoal) {\n var rule = 'FREQ=DAILY;COUNT=';\n var startday = startGoal.slice(3, 5);\n var endday = endGoal.slice(3, 5);\n var days = parseInt(endday, 10) - parseInt(startday, 10) + 1 ;\n rule = rule + days.toString();\n console.log(\"math\", startday, endday, days);\n return rule;\n }",
"compute(filtered = false) {\n let countDownFiles = 0;\n let datasetCount = 0;\n let sumExistenceDate = 0; //exda - Average\n let sumExistenceDiscovery = 0; //exdi Average\n let sumExistenceContact = 0; //exco BOOLEAN MAX\n let sumConformanceLicense = 0; //coli BOOLEAN\n let sumConformanceDateFormat = 0;//coda NUMBER\n let sumConformanceAccess = 0; //coac BOOLEAN\n let sumOpendataOpenFormat = 0;//opfo NUMBER\n let sumOpendataMachineRead = 0; //opma NUMBER\n\n\n const dirPath = `./dados/${this._snapshot}/${this._portalId}/${filtered ? 'filter' : ''}`;\n fs.readdir(dirPath, function (e, files) {\n if (e) {\n console.error(colors.red(e));\n global.log.error(e);\n } else {\n countDownFiles = files.length;\n files.forEach(function (f) {\n if (fs.statSync(path.join(dirPath, f)).isFile()) {\n const regEx = /^datasets-[A-z]+-(.*?).json$/;\n const match = regEx.exec(f);\n if (match != null) {\n datasetCount++;\n fs.readFile(path.join(`./dados/${this._snapshot}/${this._portalId}/metrics/`, `${match[1]}.json`), 'UTF-8', function (e, data) {\n if (e) {\n console.error(`Leitura de ${path.join(dirPath, f)}`, colors.red(e));\n global.log.error(e);\n throw e;\n }\n let metrics = JSON.parse(data);\n sumExistenceDate += metrics.exda;\n sumExistenceDiscovery += metrics.exdi;\n sumExistenceContact += metrics.exco ? 1 : 0;\n sumConformanceLicense += metrics.coli ? 1 : 0;\n sumConformanceDateFormat += metrics.coda;\n sumConformanceAccess += metrics.coac ? 1 : 0;\n sumOpendataOpenFormat += metrics.opfo;\n sumOpendataMachineRead += metrics.opma;\n\n countDownFiles--;\n if (countDownFiles == 0) {\n this._existenceDate = sumExistenceDate / datasetCount;\n this._existenceDiscovery = sumExistenceDiscovery / datasetCount;\n this._existenceContact = sumExistenceContact / datasetCount;\n this._conformanceLicense = sumConformanceLicense / datasetCount;\n this._conformanceDateFormat = sumConformanceDateFormat / datasetCount;\n this._conformanceAccess = sumConformanceAccess / datasetCount;\n this._opendataOpenFormat = sumOpendataOpenFormat / datasetCount;\n this._opendataMachineRead = sumOpendataMachineRead / datasetCount;\n console.log(colors.yellow(this._portalId), `${filtered ? '(filtrado)'.yellow : ''}:`, datasetCount);\n console.log('Existence Date: ', this._existenceDate);\n console.log('Existence Discovery: ', this._existenceDiscovery);\n console.log('Existence Contact: ', this._existenceContact);\n console.log('Conformance License: ', this._conformanceLicense);\n console.log('Conformance Date Format: ', this._conformanceDateFormat);\n console.log('Conformance Access: ', this._conformanceAccess);\n console.log('Opendata Open Format: ', this._opendataOpenFormat);\n console.log('Opendata Machine Read: ', this._opendataMachineRead);\n }\n }.bind(this));\n }\n } else {\n countDownFiles--;\n }\n }.bind(this))\n\n }\n }.bind(this))\n }",
"CalculateReplacements(current_age, current_lifespan, new_age, new_lifespan) {\n var currentReplacements = 0\n if (current_age == 0) {\n currentReplacements = 1 + Math.floor((this._period - this._devswap) / current_lifespan);\n }\n else {\n if ((current_lifespan - current_age) < (this._period - this._devswap)) {\n currentReplacements = Math.ceil(((this._period + this._devswap) - (current_lifespan - current_age)) / current_lifespan)\n }\n }\n\n var newReplacements = 0;\n if (this._keep == 0) {\n if (new_age == 0) {\n newReplacements = 1 + Math.floor((this._period - this._devswap) / new_lifespan);\n }\n else {\n if ((new_lifespan - new_age) < (this._period - this._devswap)) {\n newReplacements = Math.ceil(((this._period + this._devswap) - (new_lifespan - new_age)) / new_lifespan)\n }\n }\n }\n else {\n if (current_age == 0) {\n var x = 0\n if (current_lifespan < (this._period - this._devswap)) {\n x = 1;\n }\n newReplacements = x + Math.round(Math.max(0, (this._period - this._devswap - (current_lifespan - current_age))) / new_lifespan);\n }\n else {\n newReplacements = Math.ceil(Math.max(0, (this._period - this._devswap - (current_lifespan - current_age)) - (new_lifespan - new_age)) / new_lifespan);\n }\n }\n //var currentReplacements = Math.floor((+(this._period) + current_age) / current_lifespan);\n //var newReplacements = Math.floor((+(this._period) - +(this._keep) * (current_lifespan - current_age) + new_age) / new_lifespan);\n var differenceReplacements = newReplacements - currentReplacements;\n\n this._currentReplacements = currentReplacements;\n this._newReplacements = newReplacements;\n this._differenceReplacements = differenceReplacements;\n }",
"_calculateVoisins(nbCases = 10) {\n let currentGroupe = null;\n let totalCases = nbCases * 4;\n // Parcourt les fiches. On enregistre le groupe courant, quand changement, on defini le groupe precedent et calcule le suivant du precedent\n for (let i = 0; i < totalCases + 2; i++) {\n let axe = Math.floor(i / nbCases) % 4;\n let pos = i % totalCases - (axe * nbCases);\n let fiche = GestionFiche.get({\n axe: axe,\n pos: pos\n });\n if (fiche != null && fiche.groupe != null && fiche.isTerrain()) {\n if (currentGroupe == null) {\n // initialisation\n currentGroupe = fiche.groupe;\n }\n if (!currentGroupe.equals(fiche.groupe)) { // Changement de groupe\n fiche.groupe.groupePrecedent = currentGroupe;\n currentGroupe.groupeSuivant = fiche.groupe;\n currentGroupe = fiche.groupe;\n }\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Measures the efficiency of the interaction from 0 to 1. Efficiency is a notion of how well we used the machine's limited resources in service of this interaction. If we used it perfectly, we would get a 1.0. If we used everything that there was to use power, memory, cpu, then we'd get a zero. | get normalizedEfficiency() {
return this.normalizedCpuEfficiency;
} | [
"function speedCalc() {\n\t\t\treturn (0.4 + 0.01 * (50 - invadersAlive)) * difficulty;\n\t\t}",
"function total_efficiency(patients, prop){\n\tvar total_obs = 0\n\tvar\ttotal_req = 0\n\tvar pr = prop\n\tvar ignored = ['Pool','Exit']\n\tif(prop == \"waits\"){\n\t\tpr = \"waits_arr\"\n\t}\n\tpatients.forEach(function(el){\n\t\tif(el.current_ward.name == \"Exit\"){\n\t\t\t//only include discharged patients\n\t\t\tvar arr = []\n\t\t\t//iterate through observed wards\n\t\t\t//can't just slice as pre-fill patients don't have the same \n\t\t\t//pattern of values that should be ignored\n\t\t\tfor (var i = 0; i < el.observed.wards.length; i++) {\n\t\t\t\tif(ignored.indexOf(el.observed.wards[i]) == -1){\n\t\t\t\t\tarr.push(el.observed[pr][i])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar obs = arr.reduce(function(acc, val) { \n\t\t\t\tval = isNaN(val) ? 0 : val\n\t\t\t\treturn acc + val; \n\t\t\t}, 0)\n\t\t\ttotal_obs += obs\n\n\t\t\t//required amount - always exclude last value\n\t\t\tvar req = el.required[prop].reduce(function(acc, val) { \n\t\t\t\tval = isNaN(val) ? 0 : val\n\t\t\t\treturn acc + val; \n\t\t\t}, 0)\n\t\t\ttotal_req += req\n\n\t\t}\n\t})\n\tvar efficiency = (total_req / total_obs) * 100\n\treturn {'obs':total_obs, 'req': total_req, 'efficiency': efficiency, 'excess': total_obs - total_req}\n}",
"speedUp() {\n if(this.score > 30) {\n return 1.8;\n }\n if(this.score > 20) {\n return 1.7;\n }\n if(this.score > 15) {\n return 1.5;\n }\n else if(this.score > 12) {\n return 1.4;\n }\n else if(this.score > 10) {\n return 1.3;\n }\n else if(this.score > 8) {\n return 1.2;\n }\n else if(this.score > 5) {\n return 1.1;\n }\n return 1;\n }",
"get speedVariation() {}",
"function currentlyInfectedCalc(reportedCases, type, population) {\n // if (type === severeImpact) {\n // return Math.min(reportedCases * 50, population);\n // }\n // return Math.min(reportedCases * 10, population);\n console.log(population);\n if (type === severeImpact) {\n return reportedCases * 50;\n }\n return reportedCases * 10;\n}",
"function calcSum(decType: String):Vector2\n{\n\tvar total : int;\n\tvar outlier : int = 0;\n\n\tif (decType == \"flip\"){\n\t\ttotal = health + skill + stability;\n\t\t\n\t\tif ((stability + skill) <10) {outlier = 1;} //always flip; guide has not sufficiently mitigated client weakness\n\t\tif ((stability <= 1) || (skill <= 1)) {outlier = 1;} //always swim ; edge case for testing boats\n\t\tif (skill == 10) {outlier = 2;} //never flip ; escape path for guides to never flip\n\t\t\n\t}\n\telse if(decType == \"swim\"){\n\t\ttotal = health + rollability + roll;\n\t\t\n\t\tif ((rollability + roll) <10) {outlier = 1;} //always swim; guide has not sufficiently mitigated client weakness\n\t\tif ((roll <= 1) || (rollability <= 1)) {outlier = 1;} //always swim; edge case for testing boats\n\t\tif (roll == 10) {outlier = 2;} //never swim ; escape path for guides to never roll\n\n\t}\n\tvar status = new Vector2(total, outlier);\n\treturn status;\n}",
"function calcBonusMental(){\n\t\tvm.resultadoBonusMental = Math.floor(calculaBonus.retornaValorBonus(configuracao.intervaloMental, configuracao.multiplicadorMental, vm.attMental));\n\t}",
"computeDamage (payload) {\n this.hardwareDamage.computeDamage(payload[meetingCategoryDamage.HARDWARE])\n this.softwareDamage.computeDamage(payload[meetingCategoryDamage.SOFTWARE])\n this.journeyDamage.computeDamage(payload[meetingCategoryDamage.JOURNEY])\n\n // Compute the total damage caused by all the components of the meeting thanks to the\n // total damage caused by each category of components.\n this.totalDamage = this.softwareDamage.totalDamage.add(this.hardwareDamage.totalDamage).add(this.journeyDamage.totalDamage)\n }",
"function calcSimilarity(node1, node2) {\r\n\t\t\t\tvar calcedSimilarty = 0, weight = 0;\r\n\t\t\t\tfor (var calcF in calcFunctions)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar cf = calcFunctions[calcF];\r\n\t\t\t\t\tif (cf.weight > 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcalcedSimilarty += cf.func(node1,node2);\r\n\t\t\t\t\t\tweight += cf.weight;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn calcedSimilarty/weight;\r\n\t\t\t}",
"static measure(name, executedFunction) { \n\t\tvar usedTicks = Game.cpu.getUsed();\n\t\texecutedFunction();\n\t\tusedTicks = Game.cpu.getUsed() - usedTicks;\n\t\t\n this._measurements.push( { \n \tname: name,\n \tusedTicks: usedTicks,\n });\n }",
"function calculateEquipmentStat() {\r\n //init\r\n for(let prop in player.additionalStats){player.additionalStats[prop] = 0};\r\n //calculation\r\n for(let prop in player.equipments){\r\n let d = player.equipments[prop];\r\n if(d !== null){\r\n player.additionalStats.atk += d.atk;\r\n player.additionalStats.def += d.def;\r\n player.additionalStats.spd += d.spd;\r\n }\r\n }\r\n}",
"function calculateBonus() {\n return .02 * salary;\n}",
"elapsed() {\n if (this.sumElapsed === 0) {\n console.error('Got level duration as 0; bookkeeping bug.');\n }\n return this.sumElapsed;\n }",
"getNetEnergy() {\n return this.maxEnergy - this.fatigue\n }",
"get bestGuessAtCpuCount() {\n var realCpuCount = tr.b.dictionaryLength(this.cpus);\n if (realCpuCount !== 0)\n return realCpuCount;\n return this.softwareMeasuredCpuCount;\n }",
"function calculate() \n{\n\tif(timecount < 10000) { // 10 secs limit\n\t\t//calculate note persistence as a function of time\n\t\tvar notepersistence = persistence_increase(timecount);\n\t\t\n\t\t//accumulate weights in each Harmonic Center (HC)\n\t\tfor(i = 0; i < resolution; i++) {\n\t\t\tvar next_index = Math.abs((i-resolution) % resolution);\n\t\t\tvar noteweight = scale(notepersistence, 0., 10000., 0., weights[next_index]);\n\t\t\t\n\t\t\thcindex_mod = (hcindex + i) % resolution;\n\t\t\thcw[hcindex_mod][next_index] += noteweight;\n\t\t}\n\t}\n\telse {\n\t\tlimit = true;\n\t}\t\n}",
"getEnergyPercent() {\n return this.getNetEnergy() / this.maxEnergy\n }",
"function check_cpu_utilization(tasks){\n var total_utilization = 0;\n\n for(var i=0;i<tasks.length;i++){\n var task = tasks[i];\n var utilization = task.WCET / task.period;\n\n total_utilization += utilization;\n }\n\n return total_utilization;\n\n}",
"function getMOI(type, speed) {\n\tvar speedScale = 1-(0.26 * speed/100);\n\t//console.log('scale'+speedScale+'speed'+speed);\n\t\n\tvar moi = 0;\n\tif (type == 0) moi = 6.29;\n\telse if (type == 1) moi = 6.29;\n\telse if (type == 2) moi = 5.14;\n\telse if (type == 3) moi = 3.85;\n\telse if (type == 4) moi = 3.85;\n\telse if (type == 5) moi = 4.30;\n\telse if (type == 6) moi = 4.30;\n\telse if (type == 7) moi = 0.00;\n\telse if (type == 8) moi = 0.00;\n\telse if (type == 9) moi = 4.48;\n\telse if (type == 10) moi = 4.58;\n\telse if (type == 11) moi = 4.58;\n\telse if (type == 12) moi = 4.58;\n\telse if (type == 13) moi = 4.48;\n\telse if (type == 14) moi = 4.48;\n\telse if (type == 15) moi = 4.48;\n\telse if (type == 16) moi = 4.58;\n\telse if (type == 17) moi = 4.58;\n\telse if (type == 18) moi = 0.00;\n\telse if (type == 19) moi = 0.00;\n\telse if (type == 20) moi = 4.48;\n\t\n\treturn moi * speedScale;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.