query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Trap for property access (getting) and method call. | get(target, property, receiver) {
return trap.get(target, property, receiver);
} | [
"set(target, property, value, receiver) {\n const updateWasSuccessful = trap.set(target, property, value, receiver);\n return updateWasSuccessful;\n }",
"function TestCallThrow(callTrap) {\n var f = new Proxy(() => {\n ;\n }, {\n apply: callTrap\n });\n\n (() => f(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n }).x(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n })[\"x\"](11))();\n\n \"myexn\";\n\n (() => Function.prototype.call.call(f, {}, 2))();\n\n \"myexn\";\n\n (() => Function.prototype.apply.call(f, {}, [1]))();\n\n \"myexn\";\n var f = Object.freeze(new Proxy(() => {\n ;\n }, {\n apply: callTrap\n }));\n\n (() => f(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n }).x(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n })[\"x\"](11))();\n\n \"myexn\";\n\n (() => Function.prototype.call.call(f, {}, 2))();\n\n \"myexn\";\n\n (() => Function.prototype.apply.call(f, {}, [1]))();\n\n \"myexn\";\n}",
"set value(_) {\n throw \"Cannot set computed property\";\n }",
"enterPropertyModifier(ctx) {\n\t}",
"function testLookupGetter() {\n var obj = {};\n\n // Getter lookup traverses internal prototype chain.\n Object.defineProperty(Object.prototype, 'inherited', {\n get: function inheritedGetter() {}\n });\n Object.defineProperty(obj, 'own', {\n get: function ownGetter() {}\n });\n print(obj.__lookupGetter__('own').name);\n print(obj.__lookupGetter__('inherited').name);\n\n // An accessor lacking a 'get' masks an inherited getter.\n Object.defineProperty(Object.prototype, 'masking', {\n get: function inheritedGetter() {}\n });\n Object.defineProperty(obj, 'masking', {\n set: function ownGetter() {}\n // no getter\n });\n print(obj.__lookupGetter__('masking'));\n\n // A data property causes undefined to be returned.\n Object.defineProperty(Object.prototype, 'inheritedData', {\n value: 123\n });\n Object.defineProperty(obj, 'ownData', {\n value: 321\n });\n print(obj.__lookupGetter__('ownData'));\n print(obj.__lookupGetter__('inheritedData'));\n\n // Same for missing property.\n print(obj.__lookupGetter__('noSuch'));\n\n // .length and .name\n print(Object.prototype.__lookupGetter__.length);\n print(Object.prototype.__lookupGetter__.name);\n}",
"onPropertyGet(room, property, identifier) {\n return room[property];\n }",
"get(target, prop, receiver) {\n const path = [...this.path, prop];\n const handler = new RpcProxyHandler(this.callHandler, path);\n return new Proxy(async function noop() {}, handler);\n }",
"request(prop) {\n if (typeof this[prop] === 'undefined')\n return null;\n \telse if (typeof this[prop] === 'function')\n return this[prop]();\n \telse\n return this[prop];\n }",
"function attachToGlobal(property, getter) {\n const global_ = typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n typeof global !== 'undefined' ? global : null;\n if (global_ === null)\n throw new Error('Unable to locate global object');\n Object.defineProperty(global_, property, { get: getter });\n }",
"get methodName() {\n return this[_methodName];\n }",
"ensureProperty(obj, prop, value) {\n if (!(prop in obj)) {\n obj[prop] = value;\n }\n }",
"function tryCatch(fn,obj,arg){try{return{type:\"normal\",arg:fn.call(obj,arg)};}catch(err){return{type:\"throw\",arg:err};}}",
"function spyOnGetterValue(object, f) {\n const value = object[f];\n delete object[f];\n object[f] = value;\n return spyOn(object, f);\n}",
"function setGetObjPath(obj, path, value) {\n addLog('setGetObjPath was Triggered');\n if (typeof path == 'string') {\n path = path.split('.');\n obj = obj || scope[path.splice(0, 1)];\n\n if (!obj) {\n return false;\n }\n return setGetObjPath(obj, path, value);\n } else if (path.length === 1 && value !== undefined) {\n obj[path[0]] = value;\n\n return obj;\n } else if (path.length === 0) {\n return obj;\n } else {\n return setGetObjPath(obj[path[0]],path.slice(1), value);\n }\n }",
"createProxy() {\n const self = this;\n this._proxy = new Proxy(console, {\n get: (target, property) => {\n if ( typeof target[property] === 'function' ) {\n return function(args) {\n self.send(property, args);\n return target[property](args);\n }\n }\n },\n });\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}",
"flushedWriteRetainingLock() {\n throw new Error(); // make a stupid call, get a stupid error.\n }",
"exitPropertyModifier(ctx) {\n\t}",
"_trapSpotter(character, trap, effect) {\n // Trap spotter only works with supported character sheets.\n let sheet = getOption('sheet');\n if(!sheet)\n return;\n\n // Use an implementation appropriate for the current character sheet.\n let hasTrapSpotter = getOption('fnHasTrapSpotter');\n\n // Check if the character has the Trap Spotter ability.\n if(hasTrapSpotter) {\n hasTrapSpotter(character)\n .then(hasIt => {\n\n // If they have it, make a secret Perception check.\n // Quit early if this character has already attempted to trap-spot\n // this trap.\n if(hasIt) {\n let trapId = trap.get('_id');\n let charId = trap.get('_id');\n\n // Check for a previous attempt.\n let attempts = state.itsatrapthemepathfinder.trapSpotterAttempts;\n if(!attempts[trapId])\n attempts[trapId] = {};\n if(attempts[trapId][charId])\n return;\n else\n attempts[trapId][charId] = true;\n\n // Make the secret Perception check.\n return this.getPerceptionModifier(character)\n .then(perception => {\n if(_.isNumber(perception))\n return TrapTheme.rollAsync(`1d20 + ${perception}`);\n else\n throw new Error('Trap Spotter: Could not get Perception value for Character ' + charToken.get('_id') + '.');\n })\n .then(searchResult => {\n return searchResult.total;\n })\n .then(total => {\n // Inform the GM about the Trap Spotter attempt.\n sendChat('Trap theme: ' + this.name, `/w gm ${character.get('name')} attempted to notice trap \"${trap.get('name')}\" with Trap Spotter ability. Perception ${total} vs DC ${effect.spotDC}`);\n\n // Resolve whether the trap was spotted or not.\n if(total >= effect.spotDC) {\n let html = TrapTheme.htmlNoticeTrap(character, trap);\n ItsATrap.noticeTrap(trap, html.toString(TrapTheme.css));\n }\n });\n }\n })\n .catch(err => {\n sendChat('Trap theme: ' + this.name, '/w gm ' + err.message);\n log(err.stack);\n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
mPerspective performs the perspective function to both visible and hidden 3D models. All parameters are the same as for perspective(). | function mPerspective() {
perspective(...[...arguments]);
mPage.perspective(...[...arguments]);
} | [
"function setupCameraPerspective() {\n\n\t// image camera -- perpective\n\tcameraPlane = new THREE.PerspectiveCamera( FOV, viewRatio['perspective'], NEAR, FAR );\n\tvar depth = frame.frame_perspective.height/(2*Math.tan((FOV*Math.PI)/(2*180)));\n\tcameraPlane.position.set(0, 0, depth); \n\tcameraPlane.lookAt(new THREE.Vector3(0, 0, 1)); \n\n\t// image camera -- fisheye\n\tcameraPlaneFish = new THREE.PerspectiveCamera( FOV, viewRatio['fisheye'], NEAR, FAR );\n cameraPlaneFish.setLens ( INTRINSIC.f, frame.frame_fisheye.height);\n cameraPlaneFish.position.z = INTRINSIC.f;\n cameraPlaneFish.lookAt(new THREE.Vector3(0, 0, 1)); \n\n\t// perspective camera in 3D\n\tvar viewRatio3D = 1.0;\n\tcameraPerspective = new THREE.PerspectiveCamera( FOV/FOV_SCALE, viewRatio3D, NEAR*(FOV_SCALE), FAR );\n\tcameraPerspective.up.set(0, 0, 1);\n\tcameraPerspective.position.set( POS_PerspectiveCAM.x, POS_PerspectiveCAM.y, POS_PerspectiveCAM.z);\n\tcameraPerspective.updateProjectionMatrix();\n}",
"function camera_perspective_view() {\n camera.rotation.y += Math.PI/4;\n camera.position.x = 2.0;\n camera.position.z = 2.8;\n camera.position.y = 0.6; \n}",
"function configureProjectiveMat() {\n var projectionMat = mat4.create();\n var screenRatio = gl.drawingBufferWidth / gl.drawingBufferHeight;\n mat4.perspective(projectionMat, glMatrix.toRadian(45), screenRatio, 1, 100);\n gl.uniformMatrix4fv(ctx.uProjectionMatId , false , projectionMat);\n}",
"function switchToView(view0)\n{\n\t\n\tview = view0;\n\tvar mode = objController.controlCube.getMode();\n\tif (view == 'perspective') {\n\t\tcontrolHandler.orthographic = false;\n\t\tcontrolsPerspective.enabled = true;\n\t\tcontrolsOrth.enabled = false;\n\t\tobjController.controlCube.enabled = true;\n\n\t\tif (INTERSECTED) {\n\t\t\tshaderMaterial.uniforms.threshold_min.value = INTERSECTED.name.level_min;\n\t\t\tshaderMaterial.uniforms.threshold_max.value = INTERSECTED.name.level_max;\n\t\t}\n\t\telse {\n\t\t\tshaderMaterial.uniforms.threshold_min.value = GROUND_POS.initial.perspective;\n\t\t\tshaderMaterial.uniforms.threshold_max.value = SKY_POS.initial.perspective;\n\t\t}\t\n\n\t\tparas.level_min = shaderMaterial.uniforms.threshold_min.value;\n\t\tparas.level_max = shaderMaterial.uniforms.threshold_max.value;\n\t}\n\n\telse if (view == 'orth') {\n\n\t\t// first find the closest camera\n\t\tvar center = new THREE.Vector3(controlsPerspective.marker3D.matrixWorld.elements[12], \n\t\t\t\t\t\t\t controlsPerspective.marker3D.matrixWorld.elements[13],\n\t\t\t\t\t\t\t controlsPerspective.marker3D.matrixWorld.elements[14]);\n\t\t\n\t\tcontrolHandler.orthographic = true;\n\t\tcontrolsPerspective.enabled = false;\n\t\tcontrolsOrth.enabled = true;\n\t\tobjController.controlCube.enabled = false;\n\n\t\tif (INTERSECTED) {\n\t\t\tshaderMaterial.uniforms.threshold_min.value = INTERSECTED.name.level_min;\n\t\t\tshaderMaterial.uniforms.threshold_max.value = INTERSECTED.name.level_max;\n\t\t}\n\t\telse {\n\t\t\tshaderMaterial.uniforms.threshold_min.value = GROUND_POS.min; //currentPos.height - VERTICAL_HEIGHT_MIN;\n\t\t\tshaderMaterial.uniforms.threshold_max.value = GROUND_POS.max; //currentPos.height + VERTICAL_HEIGHT_MIN;\n\t\t}\n\n\t\tparas.level_min = shaderMaterial.uniforms.threshold_min.value;\n\t\tparas.level_max = shaderMaterial.uniforms.threshold_max.value;\n\t}\n\n\tviewOld = view;\n}",
"setFrontView() {\n\t\t'use strict';\n\t\tvar ratio = 6;\n\t\tvar camera = new THREE.OrthographicCamera(window.innerWidth / - ratio, window.innerWidth / ratio, window.innerHeight / ratio, window.innerHeight / - ratio);\n\n\t\tcamera.position.set(window.innerWidth / - 6, 45, 0); //Camera is set on the position x = -200, y = 45\n\t\tcamera.rotation.y = - (Math.PI / 2); //Camera is rotated 90 degrees (default is xy, we want it looking to yz)\n\t\tcamera.updateProjectionMatrix();\n\t\tthis.camera = camera;\n\t}",
"function setProjection(mesh) {\n let bounds = mesh.extent;\n\n let fov_x = X_FIELD_OF_VIEW * Math.PI / 180,\n fov_y = fov_x / ASPECT_RATIO,\n // Distance required to view entire width/height\n width_distance = bounds.width / (2 * Math.tan(fov_x / 2)),\n height_distance = bounds.height / (2 * Math.tan(fov_y / 2)),\n // Distance camera must be to view full mesh\n camera_z = bounds.near + Math.max(width_distance, height_distance) * 1.1;\n\n let projectionMatrix = MV.perspectiveRad(\n fov_y, ASPECT_RATIO, PERSPECTIVE_NEAR_PLANE, PERSPECTIVE_FAR_PLANE);\n\n\tlet eye = vec3(bounds.midpoint[0],\n bounds.midpoint[1],\n camera_z),\n\t at = bounds.midpoint,\n\t up = vec3(0, 1, 0);\n\n\tvar viewMatrix = MV.lookAt(eye, at, up);\n\n // Add margins around the mesh\n var margins = MV.scalem(0.9, 0.9, 0.9);\n projectionMatrix = MV.mult(margins, projectionMatrix);\n\n gl.uniformMatrix4fv(shader.projectionMatrix,\n false,\n MV.flatten(projectionMatrix));\n\n gl.uniformMatrix4fv(shader.viewMatrix,\n false,\n MV.flatten(viewMatrix));\n}",
"function drawPerspectiveTri(c3d, v0, v1, v2, depth_count)\n {\n var clip = ((v0.z < MIN_Z) ? 1 : 0) +\n ((v1.z < MIN_Z) ? 2 : 0) +\n ((v2.z < MIN_Z) ? 4 : 0);\n if (clip == 0)\n {\n // No verts need clipping.\n drawPerspectiveTriUnclipped(c3d, v0, v1, v2, depth_count);\n return;\n }\n if (clip == 7)\n {\n // All verts are behind the near plane; don't draw.\n return;\n }\n\n var min_z2 = MIN_Z * 1.1;\n var clip2 = ((v0.z < min_z2) ? 1 : 0) +\n ((v1.z < min_z2) ? 2 : 0) +\n ((v2.z < min_z2) ? 4 : 0);\n if (clip2 == 7)\n {\n // All verts are behind the guard band, don't recurse.\n return;\n }\n\n var v01 = bisect(v0, v1);\n var v12 = bisect(v1, v2);\n var v20 = bisect(v2, v0);\n\n if (depth_count)\n {\n depth_count--;\n }\n\n if (1)\n {//xxxxxx\n drawPerspectiveTri(c3d, v0, v01, v20, depth_count);\n drawPerspectiveTri(c3d, v01, v1, v12, depth_count);\n drawPerspectiveTri(c3d, v12, v2, v20, depth_count);\n drawPerspectiveTri(c3d, v01, v12, v20, depth_count);\n return;\n }\n\n switch (clip)\n {\n case 1:\n drawPerspectiveTri(c3d, v01, v1, v2);\n drawPerspectiveTri(c3d, v01, v2, v20);\n drawPerspectiveTri(c3d, v0, v01, v20);\n break;\n case 2:\n drawPerspectiveTri(c3d, v0, v01, v12);\n drawPerspectiveTri(c3d, v0, v12, v2);\n drawPerspectiveTri(c3d, v1, v12, v01);\n break;\n case 3:\n drawPerspectiveTri(c3d, v2, v20, v12);\n drawPerspectiveTri(c3d, v0, v1, v12);\n drawPerspectiveTri(c3d, v0, v12, v20);\n break;\n case 4:\n drawPerspectiveTri(c3d, v0, v1, v12);\n drawPerspectiveTri(c3d, v0, v12, v20);\n drawPerspectiveTri(c3d, v12, v2, v20);\n break;\n case 5:\n drawPerspectiveTri(c3d, v1, v12, v01);\n drawPerspectiveTri(c3d, v0, v01, v12);\n drawPerspectiveTri(c3d, v0, v12, v2);\n break;\n case 6:\n drawPerspectiveTri(c3d, v0, v01, v20);\n drawPerspectiveTri(c3d, v01, v1, v2);\n drawPerspectiveTri(c3d, v01, v2, v20);\n break;\n }\n }",
"setSideView() {\n\t\t'use strict';\n\t\tvar ratio = 6;\n\t\tvar camera = new THREE.OrthographicCamera(window.innerWidth / - ratio, window.innerWidth / ratio, window.innerHeight / ratio, window.innerHeight / - ratio);\n\n\t\tcamera.position.set(0, 45, window.innerHeight / 6); //Camera is set to y = 45 and z = 100\n\t\tcamera.updateProjectionMatrix();\n\t\tthis.camera = camera;\n\n\t}",
"static mxVMult(v,m) {\r\n\t\tvar res = new mVec3(); \r\n\t\tres.x = (v.x * m.M[0]) + (v.y * m.M[4]) + (v.z * m.M[8]) + m.M[12];\r\n\t\tres.y = (v.x * m.M[1]) + (v.y * m.M[5]) + (v.z * m.M[9]) + m.M[13];\r\n\t\tres.z = (v.x * m.M[2]) + (v.y * m.M[6]) + (v.z * m.M[10]) + m.M[14];\r\n\t\treturn res; \r\n\t}",
"setupCamera() {\r\n \r\n var camera = new Camera();\r\n camera.setPerspective(FOV, this.vWidth/this.vHeight, NEAR, FAR);\r\n //camera.setOrthogonal(-30, 30, -30, 30, NEAR, FAR);\r\n camera.setView();\r\n\r\n return camera;\r\n }",
"function gTranslate(x,y,z) {\r\n modelViewMatrix = mult(modelViewMatrix,translate([x,y,z])) ;\r\n}",
"lookAtModel() {\n const box = new THREE.Box3().setFromObject(this.model);\n const size = box.getSize().length();\n const center = box.getCenter();\n\n this.model.position.x += (this.model.position.x - center.x);\n this.model.position.y += (this.model.position.y - center.y);\n this.model.position.z += (this.model.position.z - center.z);\n \n this.camera.near = size / 100;\n this.camera.far = size * 100;\n this.camera.updateProjectionMatrix();\n \n this.camera.position.x = 176270.75252929013;\n this.camera.position.y = -26073.99366690377;\n this.camera.position.z = 39148.29418709834;\n }",
"function uploadModelViewMatrixToShader() \n{\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}",
"parsePerspective(children, indexPerspective)\n {\n \t// default values\n var id=\"\";\n var near=0;\n var far=0;\n var angle=0;\n\n // reads the values from xml file\n id=this.reader.getString(children[indexPerspective],'id');\n near=this.reader.getFloat(children[indexPerspective],'near');\n far=this.reader.getFloat(children[indexPerspective],'far');\n angle=this.reader.getFloat(children[indexPerspective],'angle');\n \n // error handling \n if (!(near != null && !isNaN(near))) {\n near = 0.1;\n this.onXMLMinorError(\"unable to parse value for near plane; assuming 'near = 0.1'\");\n }\n else if (!(far != null && !isNaN(far))) {\n far = 500;\n this.onXMLMinorError(\"unable to parse value for far plane; assuming 'far = 500'\");\n }\n else if (!(angle != null && !isNaN(far))) {\n angle = 30;\n this.onXMLMinorError(\"unable to parse value for angle plane; assuming 'far = 500'\");\n }\n\n if (near >= far)\n return \"'near' must be smaller than 'far'\";\n\n // default values\n var from = [];\n var to = [];\n \n // access to 'from' and 'to'\n var persChildren = children[indexPerspective].children;\n var persNodeNames = [];\n\n for (var i = 0; i < persChildren.length; i++)\n persNodeNames.push(persChildren[i].nodeName);\n \n var fromIndex = persNodeNames.indexOf(\"from\");\n var toIndex = persNodeNames.indexOf(\"to\");\n\n // error handling\n if (fromIndex == -1)\n this.onXMLMinorError(\"from undefined\");\n \n // reading values from the xml related to 'from'\n else {\n var fx = this.reader.getFloat(persChildren[fromIndex], 'x');\n var fy = this.reader.getFloat(persChildren[fromIndex], 'y');\n var fz = this.reader.getFloat(persChildren[fromIndex], 'z');\n from.push(fx); from.push(fy); from.push(fz);\n }\n // error handling\n if (toIndex == -1)\n this.onXMLMinorError(\"to undefined\");\n \n // reading values from the xml related to 'to'\n else {\n var tx = this.reader.getFloat(persChildren[toIndex], 'x');\n var ty = this.reader.getFloat(persChildren[toIndex], 'y');\n var tz = this.reader.getFloat(persChildren[toIndex], 'z');\n to.push(tx); to.push(ty); to.push(tz);\n }\n\n // error handling - check if there aren´t repeated ids\n if (this.perspectives.hasOwnProperty(id))\n this.onXMLMinorError(\"id of perspective duplicated, initial perspective overwritten\");\n \n //save data \n this.perspectives[id] = [angle*degToRad, near, far, from, to];\n\n return id;\n }",
"function setMV() {\r\n gl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(modelViewMatrix) );\r\n normalMatrix = inverseTranspose(modelViewMatrix) ;\r\n gl.uniformMatrix4fv(normalMatrixLoc, false, flatten(normalMatrix) );\r\n}",
"createCamerasAndControls() {\n let width = this.refs.msCanvas.clientWidth, height = this.refs.msCanvas.clientHeight;\n\n // orthographic\n this.orthoCamera = new THREE.OrthographicCamera();\n this.orthoCamera.zoom = 2.5;\n this.orthoCamera.position.set(0, -1, 0.5);\n this.orthoCamera.up.set(0, 0, 1);\n this.orthoCamera.add(new THREE.PointLight(0xffffff, 1));\n this.orthoCamera.name = \"camera\";\n this.updateOrthoCamera(width, height);\n\n this.orthoControls = new OrbitControls(this.orthoCamera, this.renderer.domElement);\n this.orthoControls.enable = false;\n this.orthoControls.screenSpacePanning = true;\n this.orthoControls.minDistance = this.orthoCamera.near;\n this.orthoControls.maxDistance = this.orthoCamera.far;\n this.orthoControls.target0.set(0, 0, 0.5); // setting target0 since controls.reset() uses this... todo: try controls.saveState \n this.orthoControls.addEventListener( 'change', this.renderScene );\n\n // perspective\n const fov = 25; // narrow field of view so objects don't shrink so much in the distance\n const aspect = width / height;\n const near = 0.001;\n const far = 100;\n this.perspCamera = new THREE.PerspectiveCamera(fov, aspect, near, far);\n this.perspCamera.position.set(0, -6, 0.5);\n this.perspCamera.up.set(0, 0, 1);\n this.perspCamera.add(new THREE.PointLight(0xffffff, 1));\n this.perspCamera.name = \"camera\";\n this.updatePerspCamera(width, height);\n \n this.perspControls = new OrbitControls(this.perspCamera, this.renderer.domElement);\n this.perspControls.enable = false;\n this.perspControls.screenSpacePanning = true;\n this.perspControls.minDistance = this.perspCamera.near;\n this.perspControls.maxDistance = this.perspCamera.far;\n this.perspControls.target0.set(0, 0, 0.5); // setting target0 since controls.reset() uses this... todo: try controls.saveState \n this.perspControls.addEventListener( 'change', this.renderScene );\n\n // set default to perspective\n this.camera = this.perspCamera;\n this.controls = this.perspControls;\n this.controls.enable = true;\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}",
"setTopView() {\n\t\t'use strict';\n\t\tvar ratio = 6;\n\t\tvar camera = new THREE.OrthographicCamera(window.innerWidth / - ratio, window.innerWidth / ratio, window.innerHeight / ratio, window.innerHeight / - ratio);\n\n\t\tcamera.position.set(0, window.innerWidth / 6, 0); //Camera is set on position y = 200\n\t\tcamera.lookAt(this.scene.position); //Camera looks at the center of the scene (0, 0, 0)\n\t\tcamera.updateProjectionMatrix();\n\t\tthis.camera = camera;\n\t}",
"function getProjectionMatrix() {\n const projectionMatrix = new Matrix4();\n\n // Use library setPerspective or setOrtho to create a projection matrix depending on param\n if (params.projection === \"perspective\") {\n projectionMatrix.setPerspective(params.fov, canvas.clientWidth / canvas.clientHeight, 0.1, 1000);\n } else {\n projectionMatrix.setOrtho(-1, 1, -1, 1, 0.1, 1000);\n }\n\n return projectionMatrix;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handleSound() If the mouse is moving away from the center of the shape on the X axis, plays the breath in sound. If it gets closer, plays the breath out sound. | handleSound() {
// On the X axis, if the mouse is closer to the center of the shape than it was in the previous frame...
if (this.distanceFromCenterX > mouseX - this.x) {
// Change state to say that the breath in sound is not playing and stop the sound
this.breathInSoundPlaying = false;
this.breathInSound.stop();
// If the breath out sound is not playing, play it and change its state so it wont play every frame
if (!this.breathOutSoundPlaying) {
this.breathOutSound.play();
this.breathOutSoundPlaying = true;
}
}
// On the X axis, if the mouse is farther from the center of the shape than it was in the previous frame...
else if (this.distanceFromCenterX < mouseX - this.x) {
// Change state to say that the breath out sound is not playing and stop the sound
this.breathOutSoundPlaying = false;
this.breathOutSound.stop();
// If the breath in sound is not playing, play it and change its state so it wont play every frame
if (!this.breathInSoundPlaying) {
this.breathInSound.play();
this.breathInSoundPlaying = true;
}
}
} | [
"update(canvas, synth, notes) {\n if(this.x + this.radius > canvas.width || this.x - this.radius < 0) {\n this.dx = -this.dx;\n // LOGIC TO PLAY SOUND GOES HERE\n let note = getNote(notes);\n synth.triggerAttackRelease(note, \"32n\");\n }\n this.x += this.dx;\n if(this.y + this.radius > canvas.height || this.y - this.radius < 0) {\n this.dy = -this.dy;\n // LOGIC TO PLAY SOUND GOES HERE\n let note = getNote(notes);\n synth.triggerAttackRelease(note, \"32n\");\n }\n this.y += this.dy;\n }",
"function draw(){\n\n mCanvas.background(255);\n drawBirdsGraphics();\n\n push();\n\n if(soundWater.isPlaying()){\n drawWaterGraphics();\n push(); \n }\n\n if(soundBell.isPlaying()){\n drawBellGraphics();\n push();\n }\n\n if(soundGlass.isPlaying()){\n drawGlassGraphics();\n push();\n }\n\n if(soundSeller.isPlaying()){\n drawSellerGraphics();\n push();\n }\n\n if(soundGong.isPlaying()){\n drawGongGraphics();\n push();\n }\n\n if(soundGuitar.isPlaying()){\n drawGuitarGraphics();\n push();\n }\n\n if(soundTrafficLight.isPlaying()){\n drawTrafficlightGraphics();\n push();\n }\n\n}",
"_shootSound() {\n if (this._targetPlanet.name === \"blueBig\") {\n Assets.sounds.shootLeft.stop();\n Assets.sounds.shootRight.play();\n } else if (this._targetPlanet.name === \"redBig\") {\n Assets.sounds.shootRight.stop();\n Assets.sounds.shootLeft.play();\n }\n }",
"function playCloseEnoughSound()\n{\n\tvar random = getRandomInteger(0,Math.min((closeEnoughSounds.length - 1), (currentLevel - 1)));\n\tplaySoundIfSoundIsOn(closeEnoughSounds[random]);\n}",
"function mousePressed() {\n // Check if the mouse is in the x range of the target\n if (mouseX > targetX - targetImage.width/2 && mouseX < targetX + targetImage.width/2) {\n // Check if the mouse is also in the y range of the target\n if (mouseY > targetY - targetImage.height/2 && mouseY < targetY + targetImage.height/2) {\n //add in victory music\n winningSound.play();\n gameOver = true;\n }\n }\n}",
"function endSound() {\n winSound.play();\n}",
"function playSoundGameOver() {\n game.sound.play('game_over');\n}",
"function playSoundUh() {\n game.sound.play('uh', 2);\n}",
"function mousePressed() {\n playing = true;\n}",
"function wallDmg(){\n playerHP -= 1;\n if(playerHP < 0){\n if(!explodeSound.isPlaying()){\n explodeSound.play();\n }\n } else {\n if(!crashSound.isPlaying()){\n crashSound.play();\n }\n }\n}",
"function mousePressed() {\n shocked = true;\n}",
"function drawSound(){\r\n\t//drawCtx.clearRect(0, 0, drawCtx.canvas.width, drawCtx.canvas.height);\r\n\tlet circleWidth = 1;\r\n\tlet circleSpacing = 17.5;\r\n\tlet topSpacing = 130;\r\n\r\n\tlet currentHeight;\r\n\r\n\tfor(let i=0; i<audioData.length;i++){\r\n\t\tif (playButton.dataset.playing == \"yes\") currentHeight = (topSpacing-60) + 256-audioData[i];\r\n\t\telse if (currentHeight < (canvasElement.height - 65)) currentHeight + 5;\r\n\t\telse currentHeight = canvasElement.height - 65;\r\n\t\tdrawCtx.save();\r\n\t\tdrawCtx.beginPath();\r\n\t\tdrawCtx.fillStyle = drawCtx.strokeStyle = makeColor(color.red, color.green, color.blue, color.alpha);\r\n\r\n\t\t// draw appropriete shape\r\n\t\tif(circle){\r\n\t\t\tdrawCtx.arc(i * (circleWidth + circleSpacing),currentHeight + 60, 5, 0, Math.PI * 2, false);\r\n\t\t\tdrawCtx.arc(i * (circleWidth + circleSpacing),currentHeight+30, 5, 0, Math.PI * 2, false);\r\n\t\t\tdrawCtx.arc(i * (circleWidth + circleSpacing),currentHeight, 5, 0, Math.PI * 2, false);\r\n\t\t}\r\n\t\telse if(triangle){\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight + 60);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) - 5,currentHeight + 60 - 10);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) + 5,currentHeight + 60 - 10);\r\n\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight+30);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) - 5,currentHeight+30 - 10);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) + 5,currentHeight+30 - 10);\r\n\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),(currentHeight));\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) - 5,currentHeight - 10);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) + 5,currentHeight - 10);\r\n\t\t}\r\n\t\telse if(square){\r\n\t\t\tdrawCtx.rect(i * (circleWidth + circleSpacing),currentHeight + 60, 5, 5);\r\n\t\t\tdrawCtx.rect(i * (circleWidth + circleSpacing),currentHeight+30, 5, 5);\r\n\t\t\tdrawCtx.rect(i * (circleWidth + circleSpacing),currentHeight, 5, 5);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight + 60);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing),currentHeight + 70);\r\n\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight+30);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing),currentHeight+40);\r\n\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing),currentHeight + 10);\r\n\r\n\t\t\tdrawCtx.stroke();\r\n\t\t}\r\n\t\tdrawCtx.closePath();\r\n\t\tdrawCtx.fill();\r\n\t\tdrawCtx.restore();\r\n\t}\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 playsound() {\r\n audio1.play();\r\n }",
"function playSound(sound) {\n if ($('#sound').is(':checked') === true) { //Check if the checkbox 'sound' is checked by the player\n sound.play (); //If so, you can play sounds :). Each sound that needs to be played will trigger this function\n }\n }",
"function createSound(pin, sunset, sunshine) {\n\n // Sound 1 - volume on 0 for fade the song at the start\n let sunsetSound = new Howl({\n src: [sunset.path],\n volume: 0\n });\n \n // Sound 2\n let sunshineSound = new Howl({\n src: [sunshine.path],\n volume: 0\n });\n \n let isPlayed = false;\n \n // When the pin is hover by the mouse\n pin.addEventListener('mouseover', () => {\n \n // Play sound 1 if the sun is up\n if(sunIsUp && !isPlayed) {\n\n if(currentSound != sunsetSound) player.playSound(sunset);\n currentSound = sunsetSound;\n sunsetSound.play();\n currentSound.fade(0, 1, 500);\n isPlayed = true;\n \n // Play sound 2 if the sun us down\n } else if(!sunIsUp && !isPlayed) {\n \n if(currentSound != sunshineSound) player.playSound(sunshine);\n currentSound = sunshineSound;\n sunshineSound.play();\n currentSound.fade(0, 1, 500);\n isPlayed = true;\n \n }\n \n });\n \n // When the mouse leave the pin\n pin.addEventListener('mouseout', () => {\n \n isPlayed = false;\n currentSound.fade(1, 0, 1000);\n \n setTimeout(() => {\n currentSound.stop();\n }, 1000);\n });\n }",
"bossMusic(music) {\n if (this.bossManipulation) {\n if (!music.isPlaying()) { // to avoid repreatly play music\n music.play();\n }\n }\n }",
"makeSound() {\n // if we wanna call the parent method explicitly we could do it like that\n // super.makeSound();\n // more common is to define our own logic\n return 'and another sound'\n }",
"function checkBallWallCollision() {\n // Check for collisions with top or bottom...\n if (ball.y < 0 ) {\n // It hit so reverse velocity\n ball.vy = ball.speed;\n // Play our bouncing sound effect by rewinding and then playing\n // beepSFX.currentTime = 0;\n // beepSFX.play();\n }\n else if (ball.y > height){\n // It hit so reverse velocity\n ball.vy = -ball.speed;\n // Play our bouncing sound effect by rewinding and then playing\n // beepSFX.currentTime = 0;\n // beepSFX.play();\n\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serializes the PNPM Shrinkwrap file | serialize() {
return yaml.safeDump(this._shrinkwrapJson, SHRINKWRAP_YAML_FORMAT);
} | [
"function saveDiagram()\n {\n\n var root = {};\n var xmlSection1 = [];\n var xmlSection2 = [];\n var xmlSection = [];\n var elements = [];\n var connects = [];\n var orders = [];\n\n for (var i in formatting)\n { // save the formatting values\n var item = formatting[i];\n connects.push(\n {\n \"chevronId\": item.chevronId,\n \"X\": item.positionX,\n \"Y\": item.positionY\n });\n }\n for (var i in specializations)\n { // save element flow\n var item = specializations[i];\n orders.push(\n {\n \"sourceId\": item.id,\n \"targetId\": item.successorId\n });\n }\n for (var i in chevrons)\n { // save element details\n var item = chevrons[i];\n\n elements.push(\n {\n\n \"chevronId\": item.chevronId,\n \"chevronName\": item.chevronName,\n \"associatedAsset\": item.processModel\n });\n }\n xmlSection1.push(\n {\n mainProcess: mainProcessName,\n element: elements,\n flow: orders\n });\n xmlSection2.push(\n {\n format: connects\n });\n xmlSection.push(\n {\n chevrons: xmlSection1,\n styles: xmlSection2\n });\n root.xmlSection = xmlSection;\n var savedCanvas = JSON.stringify(root);\n\n var x2js = new X2JS();\n var strAsXml = x2js.json2xml_str(savedCanvas); // convert to xml\n \n\n //ajax call to save value in api\n $.ajax(\n {\n type: \"POST\",\n url: \"/publisher/asts/chevron/apis/chevronxml\",\n data:\n {\n content: strAsXml,\n name: mainProcessName,\n type: \"POST\"\n }\n })\n\n .done(function(result)\n {\n \n });\n\n }",
"export() {\n let data = [];\n let totalAnimationSteps = this.stepCount + 1;\n\n writeUint8(totalAnimationSteps, data);\n \n for (var i = 0; i < totalAnimationSteps; i++) \n {\n\n let totalColorsInCurrentStep = Object.keys(this.colors[i]).length;\n\n if (totalColorsInCurrentStep === 0 && totalAnimationSteps === 0)\n {\n console.log(\"Nothing to export.\")\n return;\n }\n\n writeUint16(totalColorsInCurrentStep, data);\n\n for (const color of Object.keys(this.colors[i])) \n {\n let rgb = hexToRgb(color)\n writeUint8(rgb.r, data)\n writeUint8(rgb.g, data)\n writeUint8(rgb.b, data)\n let ledsWithThisColor = this.getLedsWithColor(i, color);\n writeUint16(ledsWithThisColor.length, data)\n ledsWithThisColor.forEach(elem => {\n writeUint16(elem, data);\n })\n }\n\n\n }\n\n var blob = new Blob(data, { type: \"application/octet-stream\" });\n var blobUrl = URL.createObjectURL(blob);\n window.location.replace(blobUrl);\n\n var fileLink = document.createElement('a');\n fileLink.href = blobUrl\n fileLink.download = \"animation.bin\"\n fileLink.click();\n\n }",
"save(statsFile = Statistics.defaultLocation) {\n fs.writeFileSync(statsFile, JSON.stringify(this));\n }",
"function writeInventory(){\n var inventoryText = '';\n for(var i = 0; i < inventory.length-1; i++){\n inventoryText += inventory[i] + '\\n';\n }\n inventoryText += inventory[inventory.length-1];\n var blob = new Blob([inventoryText], {type: \"text/plain;charset=utf-8\"});\n console.log(inventoryText);\n saveAs(blob, changeFilename(invName, \"_SOLD_\"));\n\n }",
"function IcecastWriteStack(stream, metaint) {\n StreamStack.call(this, stream);\n this.metaint = metaint;\n this.counter = 0;\n this._metadataQueue = [];\n}",
"function output_open()\n//\n// Input: none\n// Output: returns an error code\n// Purpose: writes basic project data to binary output file.\n//\n{\n let j;\n let m;\n let k;\n let x;\n let z;\n let hexdata = ''; // Hexadecimal string that is translated to binary.\n\n // --- open binary output file\n output_openOutFile();\n if ( ErrorCode ) return ErrorCode;\n\n // --- ignore pollutants if no water quality analsis performed\n if ( IgnoreQuality ) NumPolluts = 0;\n else NumPolluts = Nobjects[POLLUT];\n\n // --- subcatchment results consist of Rainfall, Snowdepth, Evap, \n // Infil, Runoff, GW Flow, GW Elev, GW Sat, and Washoff\n NumSubcatchVars = MAX_SUBCATCH_RESULTS - 1 + NumPolluts;\n\n // --- node results consist of Depth, Head, Volume, Lateral Inflow,\n // Total Inflow, Overflow and Quality\n NumNodeVars = MAX_NODE_RESULTS - 1 + NumPolluts;\n\n // --- link results consist of Depth, Flow, Velocity, Volume, //(5.1.013)\n // Capacity and Quality\n NumLinkVars = MAX_LINK_RESULTS - 1 + NumPolluts;\n\n // --- get number of objects reported on\n NumSubcatch = 0;\n NumNodes = 0;\n NumLinks = 0;\n for (j=0; j<Nobjects[SUBCATCH]; j++) if (Subcatch[j].rptFlag) NumSubcatch++;\n for (j=0; j<Nobjects[NODE]; j++) if (Node[j].rptFlag) NumNodes++;\n for (j=0; j<Nobjects[LINK]; j++) if (Link[j].rptFlag) NumLinks++;\n\n /*BytesPerPeriod = sizeof(REAL8)\n + NumSubcatch * NumSubcatchVars * sizeof(REAL4)\n + NumNodes * NumNodeVars * sizeof(REAL4)\n + NumLinks * NumLinkVars * sizeof(REAL4)\n + MAX_SYS_RESULTS * sizeof(REAL4);*/\n BytesPerPeriod = 8\n + NumSubcatch * NumSubcatchVars * 4\n + NumNodes * NumNodeVars * 4\n + NumLinks * NumLinkVars * 4\n + MAX_SYS_RESULTS * 4;\n Nperiods = 0;\n\n SubcatchResults = null;\n NodeResults = null;\n LinkResults = null;\n //SubcatchResults = (REAL4 *) calloc(NumSubcatchVars, sizeof(REAL4));\n //NodeResults = (REAL4 *) calloc(NumNodeVars, sizeof(REAL4));\n //LinkResults = (REAL4 *) calloc(NumLinkVars, sizeof(REAL4));\n SubcatchResults = new Array(NumSubcatchVars);\n NodeResults = new Array(NumNodeVars);\n LinkResults = new Array(NumLinkVars);\n if ( !SubcatchResults || !NodeResults || !LinkResults )\n {\n report_writeErrorMsg(ERR_MEMORY, \"\");\n return ErrorCode;\n }\n\n // --- allocate memory to store average node & link results per period //(5.1.013)\n AvgNodeResults = null; //\n AvgLinkResults = null; //\n if ( RptFlags.averages && !output_openAvgResults() ) //\n { //\n report_writeErrorMsg(ERR_MEMORY, \"\"); //\n return ErrorCode; //\n } //\n\n /*fseek(Fout.file, 0, SEEK_SET);\n k = MAGICNUMBER;\n fwrite(k, sizeof(INT4), 1, Fout.file); // Magic number\n k = VERSION;\n fwrite(k, sizeof(INT4), 1, Fout.file); // Version number\n k = FlowUnits;\n fwrite(k, sizeof(INT4), 1, Fout.file); // Flow units\n k = NumSubcatch;\n fwrite(k, sizeof(INT4), 1, Fout.file); // # subcatchments\n k = NumNodes;\n fwrite(k, sizeof(INT4), 1, Fout.file); // # nodes\n k = NumLinks;\n fwrite(k, sizeof(INT4), 1, Fout.file); // # links\n k = NumPolluts;\n fwrite(k, sizeof(INT4), 1, Fout.file); // # pollutants*/\n // \n \n // Write the data to a hexadecimal string\n k = MAGICNUMBER;\n hexdata = hexdata + toBytes32(k); // Magic number\n k = VERSION;\n hexdata = hexdata + toBytes32(k); // Version number\n k = FlowUnits;\n hexdata = hexdata + toBytes32(k); // Flow units\n k = NumSubcatch;\n hexdata = hexdata + toBytes32(k); // # subcatchments\n k = NumNodes;\n hexdata = hexdata + toBytes32(k); // # nodes\n k = NumLinks;\n hexdata = hexdata + toBytes32(k); // # links\n k = NumPolluts;\n hexdata = hexdata + toBytes32(k); // # pollutants\n\n /////////\n // This may need a little explanation:\n // Prior to this: create a hexadecimal text string var.\n // name the hexadecimal string \"\"hexdata\"\" \n // Use the following function to translate the hexadecimal file into a binary file.\n var byteArray = new Uint8Array(hexdata.match(/.{2}/g).map(e => parseInt(e, 16)));\n\n\n // --- save ID names of subcatchments, nodes, links, & pollutants \n //IDStartPos = ftell(Fout.file);\n // This may go better if I keep on appending hex strings and then only \n // translate to blob when it is imperative.\n IDStartPos = byteArray.length;\n for (j=0; j<Nobjects[SUBCATCH]; j++)\n {\n if ( Subcatch[j].rptFlag ) output_saveID(Subcatch[j].ID, Fout.file);\n }\n for (j=0; j<Nobjects[NODE]; j++)\n {\n if ( Node[j].rptFlag ) output_saveID(Node[j].ID, Fout.file);\n }\n for (j=0; j<Nobjects[LINK]; j++)\n {\n if ( Link[j].rptFlag ) output_saveID(Link[j].ID, Fout.file);\n }\n for (j=0; j<NumPolluts; j++) output_saveID(Pollut[j].ID, Fout.file);\n\n // --- save codes of pollutant concentration units\n for (j=0; j<NumPolluts; j++)\n {\n k = Pollut[j].units;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n }\n\n //InputStartPos = ftell(Fout.file);\n InputStartPos = hexdata.length;\n\n // --- save subcatchment area\n k = 1;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = INPUT_AREA;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n for (j=0; j<Nobjects[SUBCATCH]; j++)\n {\n if ( !Subcatch[j].rptFlag ) continue;\n SubcatchResults[0] = (Subcatch[j].area * UCF(LANDAREA));\n //fwrite(SubcatchResults[0], sizeof(REAL4), 1, Fout.file);\n hexdata = hexdata + toBytes32f(SubcatchResults[0]); \n }\n\n // --- save node type, invert, & max. depth\n k = 3;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n k = INPUT_TYPE_CODE;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = INPUT_INVERT;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = INPUT_MAX_DEPTH;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n for (j=0; j<Nobjects[NODE]; j++)\n {\n if ( !Node[j].rptFlag ) continue;\n k = Node[j].type;\n NodeResults[0] = (REAL4)(Node[j].invertElev * UCF(LENGTH));\n NodeResults[1] = (REAL4)(Node[j].fullDepth * UCF(LENGTH));\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n //fwrite(NodeResults, sizeof(REAL4), 2, Fout.file);\n hexdata = hexdata + toBytes32f(NodeResults[0]); \n hexdata = hexdata + toBytes32f(NodeResults[1]); \n }\n\n // --- save link type, offsets, max. depth, & length\n k = 5;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = INPUT_TYPE_CODE;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = INPUT_OFFSET;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = INPUT_OFFSET;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = INPUT_MAX_DEPTH;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = INPUT_LENGTH;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n\n for (j=0; j<Nobjects[LINK]; j++)\n {\n if ( !Link[j].rptFlag ) continue;\n k = Link[j].type;\n if ( k == PUMP )\n {\n for (m=0; m<4; m++) LinkResults[m] = 0.0;\n }\n else\n {\n LinkResults[0] = (Link[j].offset1 * UCF(LENGTH));\n LinkResults[1] = (Link[j].offset2 * UCF(LENGTH));\n if ( Link[j].direction < 0 )\n {\n x = LinkResults[0];\n LinkResults[0] = LinkResults[1];\n LinkResults[1] = x;\n }\n if ( k == OUTLET ) LinkResults[2] = 0.0;\n else LinkResults[2] = (Link[j].xsect.yFull * UCF(LENGTH));\n if ( k == CONDUIT )\n {\n m = Link[j].subIndex;\n LinkResults[3] = (Conduit[m].length * UCF(LENGTH));\n }\n else LinkResults[3] = 0.0;\n }\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n //fwrite(LinkResults, sizeof(REAL4), 4, Fout.file);\n for (let u=0; u<4; u++) hexdata = hexdata + toBytes32f(LinkResults[u]);\n \n }\n\n // --- save number & codes of subcatchment result variables\n k = NumSubcatchVars;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = SUBCATCH_RAINFALL;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = SUBCATCH_SNOWDEPTH;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = SUBCATCH_EVAP;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = SUBCATCH_INFIL;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = SUBCATCH_RUNOFF;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = SUBCATCH_GW_FLOW;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = SUBCATCH_GW_ELEV;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = SUBCATCH_SOIL_MOIST;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n\n for (j=0; j<NumPolluts; j++) \n {\n k = SUBCATCH_WASHOFF + j;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n }\n\n // --- save number & codes of node result variables\n k = NumNodeVars;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = NODE_DEPTH;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = NODE_HEAD;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = NODE_VOLUME;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = NODE_LATFLOW;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = NODE_INFLOW;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = NODE_OVERFLOW;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n for (j=0; j<NumPolluts; j++)\n {\n k = NODE_QUAL + j;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n }\n\n // --- save number & codes of link result variables\n k = NumLinkVars;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = LINK_FLOW;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = LINK_DEPTH;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = LINK_VELOCITY;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = LINK_VOLUME;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n k = LINK_CAPACITY;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n for (j=0; j<NumPolluts; j++)\n {\n k = LINK_QUAL + j;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n }\n\n // --- save number & codes of system result variables\n k = MAX_SYS_RESULTS;\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n for (k=0; k<MAX_SYS_RESULTS; k++) {\n //fwrite(k, sizeof(INT4), 1, Fout.file);\n hexdata = hexdata + toBytes32(k); \n }\n\n // --- save starting report date & report step\n // (if reporting start date > simulation start date then\n // make saved starting report date one reporting period\n // prior to the date of the first reported result)\n z = ReportStep/86400.0;\n if ( StartDateTime + z > ReportStart ) z = StartDateTime;\n else\n {\n z = Math.floor((ReportStart - StartDateTime)/z) - 1.0;\n z = StartDateTime + z*ReportStep/86400.0;\n }\n //fwrite(z, sizeof(REAL8), 1, Fout.file);\n hexdata = hexdata + z.toString(16); \n k = ReportStep;\n\n /*if ( fwrite(k, sizeof(INT4), 1, Fout.file) < 1)\n {\n report_writeErrorMsg(ERR_OUT_WRITE, \"\");\n return ErrorCode;\n }*/\n hexdata = hexdata + toBytes32(k); \n\n //var byteArray = new Uint8Array(hexdata.match(/.{2}/g).map(e => parseInt(e, 16)));\n //var blob = new Blob([byteArray], {type: 'application/octet-stream'})\n //fout.contents = blob;\n\n Fout.contents = hexdata;\n\n OutputStartPos = hexdata.length;\n if ( Fout.mode == SCRATCH_FILE ) output_checkFileSize();\n return ErrorCode;\n}",
"serialize() {\n // cur level\n let sCurLevel = this.curLevelNum + '';\n // instrs shown\n let sInstructions = 'none';\n if (this.instructionsShown.size > 0) {\n sInstructions = Array.from(this.instructionsShown).join(';');\n }\n // level infos\n let sLevelInfos = 'none';\n if (this.levelInfos.size > 0) {\n let arrLevelInfos = [];\n for (let [n, lvlInfo] of this.levelInfos.entries()) {\n arrLevelInfos.push(n + ':' + lvlInfo.serialize());\n }\n sLevelInfos = arrLevelInfos.join(';');\n }\n return [sCurLevel, sInstructions, sLevelInfos].join('|');\n }",
"output_gram_list() {\n fs.writeFileSync(`ngram_output/${this.n}grams.json`, JSON.stringify(this.gram_list), (err) => {\n if (err) throw err;\n });\n }",
"pack(data) {\n Object.assign(data, {\n dataSetId: Utilities.normalizeHex(data.dataSetId.toString('hex').padStart(64, '0')),\n });\n return data;\n }",
"write(str) {\n Files.write(nodePath.join(Files.gitletPath(), 'objects', Util.hash(str)), str);\n return Util.hash(str);\n }",
"function ExportRules() {\n try {\n //update json for all rules in ruleset\n CurrentRuleSet.updateAll();\n\n CurrentRuleSet.Rules.forEach(rule =>{\n\n //convert ruleset to JSON\n var text = JSON.stringify(rule, null, 3);\n \n var filename = rule.title;\n\n //export/download ruleset as text/json file\n var blob = new Blob([text], {\n type: \"application/json;charset=utf-8\"\n });\n saveAs(blob, filename);\n });\n \n } catch (e) {\n alert(e);\n }\n}",
"writeTree(tree) {\n const treeObject = `${Object.keys(tree).map((key) => {\n if (Util.isString(tree[key])) {\n return `blob ${tree[key]} ${key}`;\n }\n return `tree ${Objects.writeTree(tree[key])} ${key}`;\n }).join('\\n')}\\n`;\n\n return Objects.write(treeObject);\n }",
"saveNetworkToJson(){\n\n // Networksettings into json object\n const networkSetting = this.client.NN.getNetworkSettings();\n // networkSetting['LossChoice'] = ElementHandler.getElementValFromId(\"lossChoice\");\n // networkSetting['OptimizerChoice'] = ElementHandler.getElementValFromId(\"optimizerChoice\");\n // networkSetting['LearningRate'] = ElementHandler.getElementValFromId(\"learningRate\");\n\n // Create blob from dict\n const jsonFile = JSON.stringify(networkSetting, null, 1);\n const blob = new Blob(\n [ jsonFile ],\n {\n type: \"application/json\"\n }\n );\n const downloadUrl = URL.createObjectURL(blob);\n\n // Get filename and set attr.\n const filename = ElementHandler.getElementValFromId(\"jsonFileName\") + \".json\";\n ElementHandler.setAttrById(\"hrefNetworkModal\", \"download\", filename);\n ElementHandler.setAttrById(\"hrefNetworkModal\", \"href\", downloadUrl);\n\n this.hide();\n }",
"saveAsJSON() {\n const bench = this.state.benchInfo;\n for (const benchResult in this.state.benchResults) {\n if (\n (this.state.benchResults[benchResult].hasOwnProperty(\"time\") &&\n this.state.benchResults[benchResult].time != null &&\n this.state.benchResults[benchResult].time != NaN) ||\n (this.state.benchResults[benchResult].hasOwnProperty(\"size\") &&\n this.state.benchResults[benchResult].size != null &&\n this.state.benchResults[benchResult].size != NaN)\n ) {\n console.log(\"bench result :\");\n console.log({ benchResult });\n const description = this.state.benchResults[benchResult].description;\n console.log(\"time : \");\n console.log(this.state.benchResults[benchResult].time);\n console.log(\"size : \");\n console.log(this.state.benchResults[benchResult].size);\n console.log(\"bench : \");\n console.log(this.state.benchResults[benchResult]);\n const time = this.state.benchResults[benchResult].time;\n const size = this.state.benchResults[benchResult].size;\n const id = this.state.benchResults[benchResult].id;\n bench[\"bench\"].push({\n description: description,\n time: time,\n size: Math.trunc(size),\n id: id,\n });\n }\n }\n console.log(bench);\n const dataStr =\n \"data:text/json;charset=utf-8,\" +\n encodeURIComponent(JSON.stringify(bench));\n const downloadAnchorNode = document.createElement(\"a\");\n downloadAnchorNode.setAttribute(\"href\", dataStr);\n downloadAnchorNode.setAttribute(\"download\", \"exportName\" + \".json\");\n document.body.appendChild(downloadAnchorNode);\n downloadAnchorNode.click();\n downloadAnchorNode.remove();\n }",
"function createObjWriter(obj) {\n wasmInternalMemory.memoryToRead = obj;\n var module = new WebAssembly.Instance(webAssemblyModule, importObject);\n return {read_i8: module.exports.read_i8, write_i8: module.exports.write_i8, read_i16: module.exports.read_i16, write_i16: module.exports.write_i16, read_i32: module.exports.read_i32, write_i32: module.exports.write_i32, read_i64: read_i64.bind(null, module.exports.read_i16), write_i64: write_i64.bind(null, module.exports.write_i16), module: module}\n }",
"saveChannels(channels) {\n Jsonfile.spaces = 4;\n Jsonfile.writeFileSync(channelsFile, channels);\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 exportAllCustomData() {\n let customDataObject = {\n cR: customRecipes,\n cI: customIngredients,\n sL: shoppingList,\n p: pantry,\n }\n download(\"menusmith.backup\", JSON.stringify(customDataObject));\n}",
"writeSettings() {\n\n this._settings.set_value(\n Utils.HUELIGHTS_SETTINGS_BRIDGES,\n new GLib.Variant(\n Utils.HUELIGHTS_SETTINGS_BRIDGES_TYPE,\n this._hue.bridges\n )\n );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getIddFromAverage computes Idd using a mapping function onto Idd after computing percentage of current jitter versus averaged jitter | function getIddFromAverage(curr_jitter, jitter_average, g) {
var percent = curr_jitter / jitter_average * 100;
return g(percent);
} | [
"function getIddFromStdDev(curr_jitter, jitter_average, jitter_std_dev, f) {\n\tvar num_std_devs = Math.abs(curr_jitter - jitter_average) / jitter_std_dev;\n\treturn f(num_std_devs);\n}",
"function getIdd(averages, codec) {\n\n\t//NOTE: This only takes the jitter delay of the last packet in the cache for now. Need to figure out a better\n\t//way to compute Ta\n\tfunction computeTa(averages) {\n\t\treturn averages.rtp_jitter_snapshot;\n\t}\n\n\tfunction log10(val) {\n\t \treturn Math.log(val) / Math.LN10;\n\t}\n\tvar Ta = computeTa(averages);\n\tvar Idd = 0;\n\n\tif (Ta > 100) {\n\t\tvar x = log10(Ta/100) / log10(2);\n\t\tvar a = Math.pow(1 + Math.pow(x,6), 1/6);\n\t\tvar b = 3 * Math.pow(1 + Math.pow((x / 3), 6), 1/6);\n\t\tvar c = 2;\n\t\tIdd = 25 * (a - b + c);\n\t} \n\treturn Idd;\n}",
"function calculateMean() {\n var mean = 0;\n for (var j = 0; j < $scope.data2.length; j++) {\n mean = mean + $scope.data2[j].y;\n }\n return mean = ((mean / 24).toFixed(2));\n }",
"average(marks) {}",
"function getValueAt(when, strictlyEarlier){\n\t\t//alert(\"RatingMovingAverage::getValueAt pt a\\r\\n\");\n\t\tif (sumRatings.length == 0){\n\t\t\treturn [new Distribution(0, 0, 0), -1];\n\t\t}\n\t\t\n\t\t//alert(\"RatingMovingAverage::getValueAt pt b\\r\\n\");\n\t\tvar firstRating = sumRatings[0];\n\t\tif(!strictlyChronologicallyOrdered(firstRating.getDate(), when)) {\n \t\t//alert(\"RatingMovingAverage::getValueAt pt c\\r\\n\");\n\t\t\treturn [new Distribution(0, 0, 0), -1];\n\t\t}\n\t\t//alert(\"RatingMovingAverage::getValueAt pt d\\r\\n\");\n\t\t\n\t\tvar latestRatingIndex = getIndexForDate(when, strictlyEarlier);\n\t\t//alert(\"index = \" + latestRatingIndex);\n\t\tvar latestRatingDate = sumRatings[latestRatingIndex].getDate();\n\t\t//alert(\"calculating duration\");\n\t\tvar duration = latestRatingDate.timeUntil(when);\n\t\t//alert(\"constructing new date\");\n\t\tvar oldestRatingDate = latestRatingDate.datePlusDuration(-duration);\n\t\t//alert(\"getting new index\");\n\t\tvar earliestRatingIndex = getIndexForDate(oldestRatingDate, true);\n\t\t//alert(\"array lookups\");\t\t\n\t\tvar latestSumRating = sumRatings[latestRatingIndex];\n\t\tvar latestSumSquaredRating = sumSquaredRatings[latestRatingIndex];\n\t\tvar earliestSumRating = sumRatings[earliestRatingIndex];\n\t\tvar earliestSumSquaredRating = sumSquaredRatings[earliestRatingIndex];\n\t\t\n\t\tvar sumY = 0.0;\n\t\tvar sumY2 = 0.0;\n\t\tvar sumWeight = 0.0;\n\t\t//alert(\"in the middle of RatingMovingAverage::pt e\\r\\n\");\n\t\t\n\t\tif(strictlyChronologicallyOrdered(oldestRatingDate, sumRatings[0].getDate())){\n\t\t\tsumY = latestSumRating.getScore();\n\t\t\tsumY2 = latestSumSquaredRating.getScore();\n\t\t\tsumWeight = latestSumRating.getWeight();\n\t\t}\n\t\telse{\n\t\t\tsumY = latestSumRating.getScore() - earliestSumRating.getScore();\n\t\t\tsumY2 = latestSumSquaredRating.getScore() - earliestSumSquaredRating.getScore();\n\t\t\tsumWeight = latestSumSquaredRating.getWeight() - earliestSumSquaredRating.getWeight();\n\t\t}\n\t\t\n\t\tvar average = sumY/sumWeight;\n\t\tvar stdDev = Math.sqrt((sumY2 - sumY * sumY/sumWeight)/sumWeight);\n\t\tvar result = new Distribution(average, stdDev, sumWeight);\n\t\t\n\t\t//alert(\"done with RatingMovingAverage::getValueAt\\r\\n\");\n\t\treturn [result, latestRatingIndex];\n\t}",
"function meanImpute(sum,nums) {\r\n\tvar mean = sum/nums;\r\n\r\n\tif(typeof mean === \"undefined\")\r\n\t\tmean = 0;\r\n\t\r\n\treturn round(mean,1);\r\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 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}",
"function fromAvg(temp) {\n return (temp >= result.avg && temp <= (result.avg + 5));\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 }",
"function getImagesPixelsAverage(images){\n \n Object.keys(images).forEach(function(index) {\n images[index].colorM = colorPixelsAverage(images[index].img) \n });\n}",
"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}",
"function maxMinAvg(arr){\n var max = arr[0];\n var min = arr[0];\n var avg = null;\n for(i=0;i<arr.length;i++){\n if(arr[i]<min){\n min = arr[i];\n }\n if(arr[i]>max){\n max = arr[i];\n }\n avg+=arr[i];\n }\n var newArr = [max, min, avg/arr.length]\n return newArr;\n}",
"function toAvg(temp) {\n return (temp <= result.avg && temp >= (result.avg - 5));\n}",
"calculateAverageFitness(gen) {\n const x = gen.generation;\n let pop = gen.individuals;\n const y = (pop.reduce((acc, cur) => acc + parseFloat(cur.fitness), 0) / pop.length).toFixed(1); // find average\n return {\n x: x,\n y: y,\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}",
"function averageFollowers(accumulator, currentValue, index) {\n // Write your code here\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 getMedianValue(array) {\n array = array.sort((a, b) => a - b);\n return array.length % 2 !== 0 ? array[Math.floor(array.length / 2)] :\n (array[array.length / 2 - 1] + array[array.length / 2]) / 2;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns list (IDs) of unassigned miners | unassigned() {
return this.minerids.filter(m => !this.minerpool[m]);
// var list = [];
// if(Object.keys(this.minerpool).length == this.minerids.length) return [];
// const assigned = Object.keys(this.minerpool);
// for(var m of this.minerids) {
// if(assigned.indexOf(m) == -1) list.push(m);
// }
// return list;
} | [
"unblockedNodes () {\n const unblocked = []\n\n for (let node = 0; node < this.n; node++) {\n if (!this.isBlocked(node)) unblocked.push(node)\n }\n\n return unblocked\n }",
"function getUnusedCardIDs() {\n //return list\n let r = new Array();\n //copy card ids and add them to r \n cardIDs.forEach(id => {\n r.push(id);\n });\n //for each used cards id subtract it from r\n cardIDsUsed.forEach(id => {\n if (r.includes(id))\n r.splice(r.indexOf(id), 1);\n });\n return r;\n}",
"function getUnassignedTasks() {\n let workspaceId = config.workspaceId;\n let params = {\n \"projects.any\" : config.designRequestProjectId,\n \"assignee.any\" : \"null\",\n \"resource_subtype\": \"default_task\",\n \"fields\": \"gid\",\n \"limit\": 100\n };\n client.tasks.searchInWorkspace(workspaceId, params).then(tasks => {\n randomAssigner(tasks.data);\n });\n}",
"get heads () {\n const heads = {}\n this.miners.forEach(m => {\n const head = this.minersHeads[m]\n if (!heads[head]) {\n heads[head] = 0\n }\n heads[head]++\n })\n return heads\n }",
"function getNotAssignedPackages(){\n var firmwares = Firmwares_Screens_Authorization.find({ \"codeCompany\": Session.get(\"COMPANY_CODE\"), \"screenID\": Session.get(\"SCREEN_ID\") });\n var firmwaresList = [];\n firmwares.forEach(function(doc){\n var pckg = Firmwares_Live.findOne({ \"_id\": doc.firmwareID });\n var package = {\n 'id': doc._id,\n 'name': pckg.name\n }\n firmwaresList.push(package);\n });\n Session.set(\"FirmwaresNotAssignedList\", firmwaresList);\n}",
"getExposedJokerArray() {\n const tileArray = [];\n\n for (let i = 0; i < 4; i++) {\n for (const tileset of this.players[i].hand.exposedTileSetArray) {\n\n // Find unique tile in pong/kong/quint (i.e. non-joker)\n let uniqueTile = null;\n for (const tile of tileset.tileArray) {\n if (tile.suit !== SUIT.JOKER) {\n uniqueTile = tile;\n break;\n }\n }\n\n // For each joker in pong/kong/quint, return the unique tile\n if (uniqueTile) {\n for (const tile of tileset.tileArray) {\n if (tile.suit === SUIT.JOKER) {\n tileArray.push(uniqueTile);\n }\n }\n }\n }\n }\n\n return tileArray;\n }",
"function receptionistAvailable(){\n\tvar receptionists = []\n\tfor (i=0; i<visual.caregivers.length; i++){\n\t\tif (visual.caregivers[i].state == IDLE){\n\t\t\treceptionists.push(i)\n\t\t}\n\t}\n\treturn receptionists;\n}",
"assignTilesEx(excludedIndexes)\n {\n let indices = [];\n while(indices.length<7){\n let pickedIndex =Math.floor((Math.random()*100)%28);\n if(indices.indexOf(pickedIndex)<0 && excludedIndexes.indexOf(pickedIndex)<0)\n {\n indices.push(pickedIndex);\n }\n }\n this.unassignedTilePositions = this.unassignedTilePositions.filter(pos=>indices.indexOf(pos)<0);\n return indices;\n }",
"function setupMines(map){\n \n // Amount of mines required\n var mines = map.mines;\n \n // Array of fields to add mines to\n var fields = map.fields;\n \n for (var n = 0; n < mines; n++ ) {\n \n // Generate a random number to turn into a mine\n var random = Math.floor(Math.random() * (map.size )) + 0;\n\n // If can't be marked as a mine find another random number\n if(!markAsMine(map, random)){\n n--;\n }\n }\n}",
"function revealMines() {\r\n\r\n for (var i = 0; i < gGame.minesLocArr; i++) {\r\n var mineToRevealI = gGame.minesLocArr[i].i;\r\n var mineToRevealJ = gGame.minesLocArr[i].j;\r\n if (!gBoard[mineToRevealI][mineToRevealJ].isShown) {\r\n var elCell = document.getElementsByClassName(`unrevealed cell-${mineToRevealI}-${mineToRevealJ}`);\r\n gBoard[mineToRevealI][mineToRevealJ].isShown = true;\r\n renderCell(elCell, MINE);\r\n }\r\n }\r\n return;\r\n}",
"function get_mine_position(total, mines) {\n\tvar mine_position = [];\n\tvar m = mines;\n\tvar mine_array = [];\n\tfor (var i = 0; i < total; i++) {\n\t\tmine_array.push(i);\n\t}\n\tfor (var i = 0; i < m; i++) {\n\t\tvar position = Math.floor(Math.random() * total);\n\t\ttemp = mine_array[position];\n\t\tmine_array[position] = mine_array[total-1];\n\t\tmine_array[total-1] = temp;\n\t\tmine_position.push(mine_array[total-1]);\n\t\ttotal -= 1;\t\n\t}\n\treturn mine_position;\n}",
"emptySlots(){\n index=this.checkForParkingSlot(undefined,noOfLots,noOfSlots)\n return index\n }",
"get withAssignee() {\n return issues.filter(obj => obj.assignee !== null)\n .map(obj => obj.id);\n }",
"function generateMines(maxNumberOfMines = 5,minRandomNumber,maxRandomNumber){\n var array = [];\n\n while(array.length < maxNumberOfMines) {\n var number = generaRandom(minRandomNumber, maxRandomNumber);\n\n if(!array.includes(number)) {\n array.push(number);\n }\n\n }\n return array;\n\n}",
"function getMinEVs()\n{\n\treturn [\n\t\tparseInt(document.getElementById('hp-min').value),\n\t\tparseInt(document.getElementById('atk-min').value),\n\t\tparseInt(document.getElementById('def-min').value),\n\t\tparseInt(document.getElementById('spa-min').value),\n\t\tparseInt(document.getElementById('spd-min').value),\n\t\tparseInt(document.getElementById('spe-min').value)\n\t];\n}",
"createMatingPool() {\n let matingPool = [],\n limit;\n this.chromosomes.forEach((chromosome, index) => {\n limit = chromosome.fitness * 1000;\n for (let i = 0; i < limit; i++) matingPool.push(index);\n });\n return matingPool;\n }",
"unreachableVariables(){\n const unreachableVariables = [];\n const reachableVariables = this.reachableVariables();\n\n for(let variable of this.variables){\n if(!reachableVariables.includes(variable)){\n unreachableVariables.push(variable);\n }\n }\n\n return unreachableVariables;\n }",
"function setRemainingMines () {\n var remainingMines = mines.map.length - $('.flagged').length,\n text = '';\n\n if (0 > remainingMines) {\n text = String(remainingMines);\n } else if (10 > remainingMines) {\n text = '00' + remainingMines;\n } else if (100 > remainingMines) {\n text = '0' + remainingMines;\n } else {\n alert(\"Error in setRemainingMines\");\n }\n\n $('#remainingMines').text(text);\n }",
"function getOfflineRservers(){\n\tvar sql = \"SELECT rserver_id,ip_address,port,state FROM info_rserver where state <> 1\";\n\tvar rservers = [];\n\texecuteSql(sql, null, \n\t\tfunction(rows){\n\t\t\tif(rows) rservers.push(rows);\n\t\t}, \n\t\tfunction(err){\n\t\t\tconsole.log(\"Error: failed when get offline rservers, \" + err);\n\t\t}\n\t);\n\treturn rservers;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for My Account page The function changePassword uses a Firebase function to attempt to change the user's password | function changePassword(oldPass, newPass) {
//Get the current logged in user
var user = firebase.auth().currentUser;
//If it has been a while, the Firebase needs the user's credentials so get the user's credentials
var credential = firebase.auth.EmailAuthProvider.credential(user.email, oldPass);
//Provide the user's credentials to Firebase
user.reauthenticateAndRetrieveDataWithCredential(credential).then(function () {
// User re-authenticated.
user.updatePassword(newPass).then(function () {
//Let the user know their password was changed and redirect them to their read page
alert("Password changed successfully!");
window.location = "read.html";
}).catch(function (error) {
//Let the user know of the error that occurred from attempting a password change
document.getElementById("error").innerHTML = error;
});
}).catch(function (error) {
//Let the user know of the error that occurred from reauthentication
document.getElementById("error").innerHTML = error;
});
} | [
"function updatePassword(userId, newPassword, callback) {\n var hashedPassword = common.generatePasswordHash(newPassword);\n\n //update password query\n db.query(\"UPDATE LOGIN_CREDENTIALS SET password = $1 WHERE user_id= $2\", {\n bind: [hashedPassword, userId]\n\n }).spread(function () {\n callback('Success'); // Password successfully changed\n\n }).catch(function () {\n callback('Error');\n });\n}",
"function postUpdatePassword(req, res) {\r\n\tif (req.session.uid) {\r\n\t\tvar query = \"UPDATE Users SET password=? WHERE uid=?\";\r\n\t\tdatabase.query(req, res, query, [req.body.password, req.session.uid], ajaxSimplePostCbFcn);\r\n\t}\r\n}",
"function submitPassword() {\n\tvar currentUser = app.sessionDatabase.read();\n\tvar db = app.database.read();\n\tvar oldPassword = currentUser.password;\n\tvar newPassword = document.getElementById(\"newPassword\").value;\n\tvar newPasswordConfirm = document.getElementById(\"newPasswordConfirm\").value;\n\t\n\t// validation: check that the old password is correct\n\tif (document.getElementById(\"oldPassword\").value != oldPassword){\n\t\talert(\"Old password was entered incorrectly.\");\n\t\treturn;\n\t}\n\n\t// validation: check that the same password both times\n\tif (newPassword != newPasswordConfirm){\n\t\talert(\"Please make sure you typed the same password both times.\");\n\t\treturn;\n\t}\n\n\tcurrentUser.password = newPassword;\n\tapp.search.changeUserPassword(currentUser.email, newPassword); // change permanent user password in local storage\n\tapp.sessionDatabase.write(currentUser);\t\t\t\t\t\t // change current user password in session storage\n\t\n\tdocument.getElementById(\"oldPassword\").value = \"\";\n\tdocument.getElementById(\"newPassword\").value = \"\";\n\tdocument.getElementById(\"newPasswordConfirm\").value = \"\";\n\t$('#passwordModal').modal('hide');\n\n}",
"async function newPassword(req, res) {\n try {\n const { token } = req.query;\n const database = res.database;\n const user = await findUserBy(\"tokenPassword\", token, database);\n if (user) {\n const { email } = user;\n const newPassword = createHash();\n await updatetUser(\n user._id,\n {\n email,\n tokenPassword: null,\n tokenValidation: null,\n password: md5(newPassword)\n },\n database\n );\n await sendEmail(\n mailNewPassword({ email, password: newPassword }),\n res.mail\n );\n return res.status(200).send({\n message: \"Password reset. A new password was send to your mail.\"\n });\n } else {\n return res.status(403).send({\n message: \"No account found\"\n });\n }\n\n } catch (err) {\n console.log(\"INTER ERROR\", err.message);\n return res.status(500).send({ error: \"internal server error\" });\n }\n}",
"function changepw(form, password, conf, email=\"testforempty\") {\r\n\t\r\n // Check each field has a value\r\n if ( email.value == '' || password.value == '' || conf.value == '') {\r\n custom_show_message(\"Error\", 'You must provide all the requested details. Please try again', \"alert\");\r\n return false;\r\n }\r\n \r\n\tif(!check_password(password, conf, form)){\r\n\t\treturn false;\r\n\t}\r\n\t\r\n // Create a new element input, this will be our hashed password field. \r\n var p = document.createElement(\"input\");\r\n \r\n // Add the new element to our form. \r\n form.appendChild(p);\r\n p.name = \"p\";\r\n p.type = \"hidden\";\r\n p.value = hex_sha512(password.value);\r\n \r\n // Make sure the plaintext password doesn't get sent. \r\n password.value = \"\";\r\n conf.value = \"\";\r\n\r\n return true;\r\n}",
"function showPass() {\n const password = document.getElementById('password');\n const rePassword = document.getElementById('masterRePassword');\n if (password.type === 'password') {\n password.type = 'text';\n rePassword.type = 'text';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"ON - Password Confirm Input : \" + password.value);\n } else {\n password.type = 'password';\n rePassword.type = 'password';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"OFF - Password Confirm Input : \" + password.value);\n }\n} // show password function",
"_handleChangePasswordSuccess(response)\n {\n Radio.channel('rodan').trigger(RODAN_EVENTS.EVENT__USER_CHANGED_PASSWORD);\n }",
"function changePassword(id) {\n window.location.href = base_url + '/customer/change-password/' + id;\n}",
"static updatePassword(email, password, newEmail = '', newPassword = '', otp = null){\n\t\tlet kparams = {};\n\t\tkparams.email = email;\n\t\tkparams.password = password;\n\t\tkparams.newEmail = newEmail;\n\t\tkparams.newPassword = newPassword;\n\t\tkparams.otp = otp;\n\t\treturn new kaltura.RequestBuilder('adminuser', 'updatePassword', kparams);\n\t}",
"updatePassword(userId, password) {\n return new Promise((resolve, reject) => {\n const url = `${this.apiBase}/auth/passwordRecoveryPerform`;\n const payload = {userId, password };\n\n const requestOpts = this._makeFetchOpts('POST', payload);\n fetch(url, requestOpts).then(response => {\n if (response.ok) {\n response.json().then(user => {\n console.log('user', user);\n this.currentUser = user;\n this._saveUser(user);\n resolve(user);\n });\n } else {\n response.json().then(res => {\n reject(res.message);\n }\n )}\n });\n })\n }",
"'resetLostPassword'(email, password) {\n return setNewPassword(email, password, function(error, result){\n if(error) {\n throw new Meteor.Error(error, message);\n } else {\n return true;\n }\n });\n }",
"function setNewPassword() {\n var Customer, resettingCustomer;\n Customer = app.getModel('Customer');\n\n app.getForm('resetpassword').clear();\n resettingCustomer = Customer.getByPasswordResetToken(request.httpParameterMap.Token.getStringValue());\n\n if (empty(resettingCustomer)) {\n \tresponse.redirect(URLUtils.https('Login-Show', 'TokenExpired', 'TokenError'));\n } else {\n app.getView({\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n }\n}",
"function onConfirmPasswordChange(p) {\n let val = p.target.value;\n setConfirmPassword(val);\n setEnabled(password.length > 0 && name.length > 0 && email.length > 0 && val.length > 0 && number.length==10);\n }",
"function passwordManagerSave(aUsername, aPassword) {\n cal.auth.passwordManagerSave(aUsername, aPassword, aUsername, \"Google Calendar\");\n}",
"async savePassword(values) {\n\t\tconst data = {\n\t\t\tuserId: this.userId,\n\t\t\tcurrentPassword: values.currentPassword,\n\t\t\tpassword: values.password,\n\t\t\tpasswordConfirm: values.passwordConfirm\n\t\t};\n\t\tawait axios.patch('/user/update-password', data, config);\n\t}",
"handleOldpassStringChange(e) {\n this.setState({\n oldPassword: e.target.value,\n });\n }",
"function onCheckPasswordChange(newModel) {\n vm.userCopy.passwordMismatch = vm.userCopy.newPassword != newModel;\n }",
"function passwordReset() {\n app.getForm('requestpassword').clear();\n app.getView({\n ContinueURL: URLUtils.https('Account-PasswordResetForm')\n }).render('account/password/requestpasswordreset');\n}",
"resetPasswordWithPhone(phone, code, newPassword, callback) {\n newPassword = AccountsEx._hashPassword(newPassword);\n callback = ensureCallback(callback);\n Accounts.callLoginMethod({\n methodName: prefix + 'resetPasswordWithPhone',\n methodArguments: [{phone, newPassword, code}],\n userCallback: callback\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks to see if the level is complete. If it is, it stops the music and loads the next level. | function checkforLevelCompletion() {
if(game.globals.zombieGroup.children.length === 0) {
// Stop the current level's track.
this.music.stop();
game.globals.zombieGroup.destroy();
// Load the next level.
if (game.state.current === 'levelOne') {
game.state.start('levelTwo');
}
if (game.state.current === 'levelTwo') {
game.state.start('levelThree');
}
if (game.state.current === 'levelThree') {
game.state.start('victory');
}
}
} | [
"function checkGameEnd()\n{\n // check if player finished the level\n if (player.x > canvas.width && !screen.paused) {\n screen.paused = true;\n saveScoreToDisk();\n\n // check if it's in the final level\n if (currentLevel < levelFiles.length - 1) {\n menu.setState(\"nextlevel\", false);\n screen.state = \"\";\n } else {\n finalSplash.display();\n }\n }\n}",
"loadLevelSALO() {\n g_references.clear();\n g_history.loadLevelFromClipboard().then(function () {\n this.deleteItemsEventsEtc();\n let that = this;\n this._room_canvas.clear();\n that.renderScene();\n }).catch(() => {\n alert(\"Something went wrong while loading your Level Code. Please check your Level Code and try again!\");\n });\n }",
"function advanceLevel(){\n\n\t\t\tjewel.audio.play(\"levelUp\"); //p.306\n\n\t\t\tgameState.level++;\n\t\t\tannounce(\"Level \" + gameState.level);\n\t\t\tupdateGameInfo();\n\t\t\t//level value on gameInfo obj is 0 at beginning of game\n\t\t\tgameState.startTime = Date.now();\n\t\t\tgameState.endTime = jewel.settings.baseLevelTimer *\n\t\t\t\tMath.pow(gameState.level, -0.05 * gameState.level);\n\t\t\tsetLevelTimer(true);\n\t\t\tjewel.display.levelUp();\n\t\t} //end of advanceLevel()",
"function checkComplete() {\r\n if (sectionLoaderState.filesLoaded >= sectionLoaderState.filesToLoad.length) complete();\r\n}",
"function runLevel(level, Display) {\n let display = new Display(document.body, level);\n let state = State.start(level);\n let ending = 1;\n\n return new Promise(resolve => {\n runAnimation(time => {\n state = state.update(time, arrowKeys);\n display.syncState(state);\n\n if (state.status == \"playing\") {\n return true;\n }\n else if (ending > 0) {\n ending -= time;\n return true;\n }\n else {\n display.clear();\n resolve(state.status);\n return false;\n }\n });\n });\n}",
"levelIncrease() {\n\t if (this.theInvaderCounter === 0) {\n\t this.level += 1;\n\t this.levelDisplay += 1;\n\t setTimeout(() => {\n\t this.player1.invadersAllDeadSound();\n\t }, 1000);\n\t this.levelUpEval();\n\t }\n\t }",
"static load()\n {\n // load non-phaser audio elements for pausing and unpausing\n this.pauseAudio = new Audio('assets/audio/sfx/ui/pause.mp3');\n this.resumeAudio = new Audio('assets/audio/sfx/ui/checkpoint.mp3');\n\n var path = game.load.path;\n game.load.path = 'assets/audio/sfx/levels/';\n\n game.load.audio('open_door', 'open_door.mp3');\n game.load.audio('begin_level', '../ui/begin_level.mp3');\n\n game.load.path = path;\n }",
"function playNextLevelSound()\n{\n\tvar random = getRandomInteger(0,(nextLevelSounds.length - 1));\n\tplaySoundIfSoundIsOn(nextLevelSounds[random]);\n}",
"function nextPhase(){\n\n napping = true;\n babiesReturned = true;\n player.sleeping = true;\n trace =0;\n\n naps++; // increment naps taken\n\n if(naps===3){\n // IF ALL NAPS COMPLETE, LEVEL IS OVER\n\n // display continue level text\n currentText = [\n \"the day is over. level complete!\",\n \"click to continue\"\n ];\n setTimeout(function(){currentScreen = \"wakeplayer\";},1000)\n shootTextSequence();\n introSeq =0;\n\n // increment level\n level++\n\n // load next level:\n switch(level){\n case 1: currentLevel = level2; break;\n case 2:\n // if level2 is complete, game over, no more levels\n thankYouText = \"congrats! you have reached the end. thank you for playing.\";\n gameIsOver();\n break;\n }\n // reset naps\n naps =0;\n // load map\n setupLevel(currentLevel);\n }\n else {\n // IF NAPS NOT COMPLETE, LOAD NEXT PHASE\n\n // display continue text\n currentText = [\n \"good job mama ape!\",\n \"time for a nap.\"\n ];\n currentScreen = \"wakeplayer\";\n shootTextSequence();\n introSeq =0;\n traceSpeed = 10;\n\n // increment phase\n currentPhase++;\n\n // enable level in 5 seconds\n setTimeout( function(){\n player.sleeping = false;\n traceSpeed = 0.1;\n }, 5000 );\n\n // copy currentLevel object\n phase = JSON.parse(JSON.stringify(currentLevel));\n\n // add baddies according to level and phase\n switch(level){\n\n // level 1:\n case 0:\n if(currentPhase>=1){ // phase 2\n phase.baddies.push({p:20, x:30, r:300, kit:fB });\n phase.baddies.push({p:6, x:10, r:40, kit:jB });\n phase.baddies.push({p:-1, x:550, r:345, kit:jB });\n if(currentPhase===2){ // phase 3\n phase.baddies.push({p:1, x:0, r:245, kit:fB });\n phase.baddies.push({p:10, x:250, r:245, kit:fB });\n phase.baddies.push({p:10, x:250, r:245, kit:jB });\n };\n }\n break;\n\n // level 2:\n case 1:\n if(currentPhase>=1){ // phase 2\n phase.baddies.push({p:-1, x:1500, r:200, kit:jB });\n phase.baddies.push( {p:3, x:30, r:100, kit:fB });\n phase.baddies.push({p:11, x:30, r:100, kit:fB })\n phase.baddies.push({p:16,x:0,r:250,kit:fB});\n phase.baddies.push({p:6, x:30, r:100, kit:fB })\n\n if(currentPhase===2){ // phase 3\n phase.baddies.push({ p: -1, x:1050, r:500, kit:fB});\n phase.baddies.push({ p: -1, x: 1650, r:500, kit: fB});\n phase.baddies.push({ p: 12, x: 0, r:100, kit: fB});\n phase.baddies.push({ p: 10, x: 0, r:300, kit: fB});\n }\n }\n break;\n }\n\n // load map\n setupLevel(phase);\n }\n}",
"function checkStatus() {\n var allDone = true;\n\n for (var _i2 = 0; _i2 < layers.length; _i2++) {\n if (layers[_i2].loaded === false) {\n allDone = false;\n break;\n }\n }\n\n if (allDone) finish();else setTimeout(checkStatus, 500);\n }",
"function loadLevel(){\n\n\t\t//saveChar(n, r, ge, go, l, t, a);\n\t\tnewLevel++;\n // Next we get to change the background\n //var BG = PIXI.Texture.fromImage(\"res/\" + currentArea.name + \".png\");\n\t\tvar BG = PIXI.Texture.fromImage(currentArea.name + \".png\");\n\t doorOut.tint = 0x999966;\n\n\t\tconsole.log(\"\t\" + newLevel + \" \" + currentArea.name);\n\n\t\t// Gotta reset those chests, jsut gonna make new ones for now, will 'reset' them later.\n \t for(var i = 0; i < 5; i++){\n\n \t chests[i] = new chest(INDEX, i);\n\t chests[i].sprite.position.x = 650; //20 + (90 * i);\n \t chests[i].sprite.position.y = 42 + (80 * i); //50;\n \t stage.addChild(chests[i].sprite);\n \t }\n\t\t\n\t\t// Next we get to change the background\n \t//var BG = PIXI.Texture.fromImage(\"res/\" + currentArea.name + \".png\");\n\t\t//areaBackground.setTexture(BG);\n\t\tareaBackground.texture = BG;\n //stage.addChild(areaBackground);\n\t}",
"static loadBeginning()\n {\n var path = game.load.path;\n\n game.load.path = 'assets/audio/music/';\n game.load.audio('beginning', 'beginning.mp3');\n\n game.load.path = path;\n }",
"function onPlayerReady( data ) {\n\n // Turn down the volume and kick-off a play to force load\n player.bind( SC.Widget.Events.PLAY_PROGRESS, function( data ) {\n // Turn down the volume.\n // Loading has to be kicked off before volume can be changed.\n player.setVolume( 0 );\n // Wait for both flash and HTML5 to play something.\n if( data.currentPosition > 0 ) {\n player.unbind( SC.Widget.Events.PLAY_PROGRESS );\n\n player.bind( SC.Widget.Events.PAUSE, function() {\n player.unbind( SC.Widget.Events.PAUSE );\n\n // Play/Pause cycle is done, restore volume and continue loading.\n player.setVolume( 100 );\n player.bind( SC.Widget.Events.SEEK, function() {\n player.unbind( SC.Widget.Events.SEEK );\n onLoaded();\n });\n // Re seek back to 0, then we're back to default, loaded, and ready to go.\n player.seekTo( 0 );\n });\n player.pause();\n }\n });\n player.play();\n }",
"function resumeGame()\n{\n if (player.life == 0) {\n restartGame();\n return;\n }\n\n // if it's playing, just resume\n if (!screen.paused) {\n screen.state = \"running\";\n return;\n }\n\n // go to next level or restart\n if (currentLevel < levelFiles.length - 1)\n gotoNextLevel();\n else\n restartGame();\n}",
"function checkFinished () {\n console.log(fileLoadCount+\" files loaded\")\n if (fileLoadCount == fileLoadThreshold) {\n console.log(\"basicFileLoader - callback: \"+cFunc.name);\n cFunc();\n }\n }",
"function loadSounds() {\n confirmSound = new Howl({\n src: ['assets/sounds/confirm.ogg'],\n volume: 0.8\n });\n\n selectSound = new Howl({\n src: ['assets/sounds/select.ogg'],\n volume: 0.8\n });\n thudSound = new Howl({\n src: ['assets/sounds/thud.ogg'],\n volume: 0.8\n });\n moveSound = new Howl({\n src: ['assets/sounds/move.ogg'],\n volume: 0.6\n });\n turnSound = new Howl({\n src: ['assets/sounds/turn.ogg'],\n volume: 0.8\n });\n\n music1 = new Howl({\n src: ['assets/sounds/nesmusic1.mp3','assets/sounds/nesmusic1.ogg'],\n// buffer: true,\n loop:true,\n loaded: false,\n onplay: function() {\n },\n onload: function() {\n musicSelectionField.labels[0].alpha = 1;\n this.loaded = true;\n },\n onloaderror: function() {\n musicSelectionField.labels[0].alpha = 0.1;\n }\n\n });\n\n music2 = new Howl({\n src: ['assets/sounds/nesmusic2.mp3','assets/sounds/nesmusic2.ogg'],\n volume: 0.6,\n// buffer: true,\n loop:true,\n loaded: false,\n onplay: function() {\n },\n onload: function() {\n musicSelectionField.labels[1].alpha = 1;\n this.loaded = true;\n },\n onloaderror: function() {\n musicSelectionField.labels[1].alpha = 0.1;\n }\n\n\n });\n\n music3 = new Howl({\n src: ['assets/sounds/nesmusic3.mp3','assets/sounds/nesmusic3.ogg'],\n volume: 0.5,\n// buffer: true,\n loop: true,\n loaded: false,\n onplay: function() {\n },\n onload: function() {\n musicSelectionField.labels[2].alpha = 1;\n this.loaded = true;\n },\n onloaderror: function() {\n musicSelectionField.labels[2].alpha = 0.1;\n }\n\n });\n// music1Fast = music2Fast = music3Fast = music4Fast = music5Fast = music6Fast = undefined;\n // music1Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music2Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music3Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music4Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music5Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music6Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n deathSound = new Howl({\n src: ['assets/sounds/death.ogg'],\n volume: 0.8\n });\n levelUpSound = new Howl({\n src: ['assets/sounds/levelup.ogg'],\n volume: 0.8\n });\n\n lineSound = new Howl({\n src: ['assets/sounds/line.ogg'],\n volume: 0.8\n });\n fourLineSound = new Howl({\n src: ['assets/sounds/fourline.ogg'],\n volume: 0.8\n });\n\n\n musicSelections = [\n {normal:music1,fast:music1},\n {normal:music2,fast:music2},\n {normal:music3,fast:music3},\n ]\n\n\n}",
"function levelUp(){\n let nextlvxp = getxpforlv(player.level + 1);\n while(player.xp > nextlvxp){\n if(player.level != 100){\n player.levelup();\n adddiv_c(\"You leveled up! You are now level \" + player.level + \".\", \"lime\");\n nextlvxp = getxpforlv(player.level + 1);\n } else {\n adddiv(\"You are already max level. You cannot gain any more xp.\");\n break;\n }\n }\n {\n if(player.level != 100){\n let str = separateNum(nextlvxp - player.xp);\n adddiv(str + \" xp till next level.\");\n }\n }\n}",
"pauseMusic() {\n var musicLevel = Math.floor((this.currentLevel + 1) / 2)\n sounds[`level${musicLevel}.mp3`].pause();\n }",
"function playCloseEnoughSound()\n{\n\tvar random = getRandomInteger(0,Math.min((closeEnoughSounds.length - 1), (currentLevel - 1)));\n\tplaySoundIfSoundIsOn(closeEnoughSounds[random]);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
current playback position in milliseconds | function getPlaybackPosition() {
if(jQuery("video")[0]) return Math.floor(jQuery("video")[0].currentTime * 1000);
return null;
} | [
"get seek() {\n return this.api.currentTime()\n }",
"function get_playback_position(session) {\n\tif(session.playing) {\n\t\tconst now = (new Date()).getTime();\n\t\tconst time_playing = now - session.last_play_time;\n\t\treturn session.last_position + time_playing / 1000.0;\n\t} else {\n\t\treturn session.last_position;\n\t}\n}",
"ms () { return this.now() - this.startMS }",
"function updateCurrentTime() {\n video.currentTime = (progress.value * video.duration) / 100;\n}",
"function tick() {\n const canvas = canvasRef.current;\n if (!isPlayingRef.current || !canvas) {\n return;\n }\n const newPosition = (audioContext.currentTime - startTimeRef.current) * playbackRate;\n currentPositionRef.current = newPosition;\n if (newPosition > totalSecs) {\n // stop playing when reached the end or over\n stop();\n updateCanvas();\n return;\n }\n updateCanvas();\n requestAnimationFrame(tick);\n }",
"function time2ViewPos(t) {\n return ~~((t - viewportPosition) / audioBuffer.duration * totalClientWidth);\n}",
"function seekUpdate() {\n\n let seekPosition = 0;\n\n if (!isNaN(curr_track.duration)) {\n seekPosition = curr_track.currentTime * (100 / curr_track.duration);\n\n seek_slider.value = seekPosition;\n\n let currentMinutes = Math.floor(curr_track.currentTime / 60);\n\n let currentSeconds = Math.floor(curr_track.currentTime - currentMinutes * 60);\n\n let durationMinutes = Math.floor(curr_track.duration / 60);\n\n let durationSeconds = Math.floor(curr_track.duration - durationMinutes * 60);\n\n if (currentSeconds < 10) { currentSeconds = \"0\" + currentSeconds; }\n if (durationSeconds < 10) { durationSeconds = \"0\" + durationSeconds; }\n\n if (currentMinutes < 10) { currentMinutes = \"0\" + currentMinutes;}\n if (durationMinutes < 10) { durationMinutes = \"0\" + durationMinutes; } \n\n curr_time.textContent = currentMinutes + \":\" + currentSeconds;\n\n total_duration.textContent = durationMinutes + \":\" + durationSeconds;\n \n }\n}",
"get position() {\n const now = this.now();\n\n const ticks = this._clock.getTicksAtTime(now);\n\n return new _Ticks.TicksClass(this.context, ticks).toBarsBeatsSixteenths();\n }",
"seek(position) {\r\n if (this.isSeeking)\r\n this.progress = position * 100;\r\n }",
"get percent() {\n return Math.max(0, (SongManager.player.currentTime - this.startPoint) / (this.endPoint - this.startPoint));\n }",
"function updateVideoCurrentTime() {\n let curtime = convertSecondsToMinutes(video.currentTime);\n videotime.innerHTML = curtime+' / '+videoduration;\n }",
"seek(delta) {\n const newTime = this.audioTarget.currentTime + delta\n const startTime = this.audioTarget.seekable.start(0)\n const endTime = this.audioTarget.seekable.end(0)\n\n if (newTime < startTime) {\n this.audioTarget.currentTime = startTime\n } else if (newTime > endTime) {\n this.audioTarget.currentTime = endTime\n } else {\n this.audioTarget.currentTime = newTime\n }\n }",
"function getVideoTime() {\n return player.getCurrentTime();\n}",
"liveWindow() {\n const liveCurrentTime = this.liveCurrentTime();\n\n if (liveCurrentTime === Infinity) {\n return Infinity;\n }\n\n return liveCurrentTime - this.seekableStart();\n }",
"function setCurrentTime() {\n\t\tvar total = player.currentTime;\n\t\tcurrentTimeElement.innerHTML = timeFormat(total);\n\t}",
"updateElapsedTime(){\n\t\tthis.props.updateElapsedTime(this.refs.audioElement.currentTime);\n\t}",
"trackLive_() {\n this.pastSeekEnd_ = this.pastSeekEnd_;\n const seekable = this.player_.seekable();\n\n // skip undefined seekable\n if (!seekable || !seekable.length) {\n return;\n }\n\n const newSeekEnd = this.seekableEnd();\n\n // we can only tell if we are behind live, when seekable changes\n // once we detect that seekable has changed we check the new seek\n // end against current time, with a fudge value of half a second.\n if (newSeekEnd !== this.lastSeekEnd_) {\n if (this.lastSeekEnd_) {\n // we try to get the best fit value for the seeking increment\n // variable from the last 12 values.\n this.seekableIncrementList_ = this.seekableIncrementList_.slice(-11);\n this.seekableIncrementList_.push(Math.abs(newSeekEnd - this.lastSeekEnd_));\n if (this.seekableIncrementList_.length > 3) {\n this.seekableIncrement_ = median(this.seekableIncrementList_);\n }\n }\n\n this.pastSeekEnd_ = 0;\n this.lastSeekEnd_ = newSeekEnd;\n this.trigger('seekableendchange');\n }\n\n // we should reset pastSeekEnd when the value\n // is much higher than seeking increment.\n if (this.pastSeekEnd() > this.seekableIncrement_ * 1.5) {\n this.pastSeekEnd_ = 0;\n } else {\n this.pastSeekEnd_ = this.pastSeekEnd() + 0.03;\n }\n\n if (this.isBehind_() !== this.behindLiveEdge()) {\n this.behindLiveEdge_ = this.isBehind_();\n this.trigger('liveedgechange');\n }\n }",
"function timeUpdate() {\n var playPercent = timelineWidth * (music.currentTime / duration);\n playhead.style.marginLeft = playPercent + \"px\";\n if (music.currentTime == duration) {\n pButton.className = \"\";\n pButton.className = \"play\";\n }\n\n var currDuration = music.currentTime; //song is object of audio. song= new Audio();\n\n var sec = new Number();\n var min = new Number();\n currsec = Math.floor(currDuration);\n currmin = Math.floor(currsec / 60);\n currmin = currmin >= 10 ? currmin : '0' + currmin;\n currsec = Math.floor(currsec % 60);\n currsec = currsec >= 10 ? currsec : '0' + currsec;\n\n var maxDuration = duration;\n\n var sec = new Number();\n var min = new Number();\n sec = Math.floor(maxDuration);\n min = Math.floor(sec / 60);\n min = min >= 10 ? min : '0' + min;\n sec = Math.floor(sec % 60);\n sec = sec >= 10 ? sec : '0' + sec;\n\n document.getElementById('song-current-time').innerHTML = currmin + \":\" + currsec + \"/\" + min + \":\" + sec;\n }",
"function setTimestamp_() {\n const currentTime = formatTime_(sketchPlayer.sketch.getCurrentTime());\n const duration = formatTime_(sketchPlayer.sketch.videoDuration());\n $timestamp.text(currentTime + '/' + duration);\n\n // Clear any pending timer, since this function could either be called as the\n // result of an onSeekUpdate update event, or from a previous timer firing.\n clearTimeout(timestampUpdateTimer);\n timestampUpdateTimer = setTimeout(setTimestamp_, 500);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
"Enqueues" a SessionDataUpdate. Assumes sessionDataUpdate is valid. | enqueueUpdate(sessionDataUpdate) {
// If update is a no-op, don't enqueue it.
if (sessionDataUpdate.isNoOp()) {
return;
}
// If "queue" is empty, initialize it.
if (!this.sessionData) {
this.sessionData = new SessionData();
this.mergeStrategyForNextServerUpdate = sessionDataUpdate.mergeStrategy;
}
// Update data in the "queue".
this.sessionData.update(sessionDataUpdate);
// If this was a 'replace' update, set 'replace' as the strategy for the
// next server update, regardless of incoming client updates until then.
if (sessionDataUpdate.mergeStrategy === REPLACE_STRATEGY) {
this.mergeStrategyForNextServerUpdate = REPLACE_STRATEGY;
}
} | [
"update(sessionDataUpdate) {\n if (sessionDataUpdate.isNoOp()) {\n return;\n }\n switch (sessionDataUpdate.mergeStrategy) {\n case SHALLOW_MERGE_STRATEGY:\n this.data = { ...this.data, ...sessionDataUpdate.data };\n break;\n case REPLACE_STRATEGY:\n this.data = sessionDataUpdate.data;\n break;\n }\n }",
"function broadcastSessionUpdate() {\n if (localStorage) {\n localStorage.setItem('sessionUpdate', true);\n localStorage.removeItem('sessionUpdate');\n }\n}",
"touch (sessionId, session, callback) {\n\t\t\tlet now = new Date ();\n\t\t\tlet update = {\n\t\t\t\tupdatedAt: now\n\t\t\t};\n\n\t\t\tif (session && session.cookie && session.cookie.expires) {\n\t\t\t\tupdate.expiresAt = new Date (session.cookie.expires);\n\t\t\t} else {\n\t\t\t\tupdate.expiresAt = new Date (now.getTime () + this.options.expiration);\n\t\t\t}\n\n\t\t\tthis.collection.update ({_id: sessionId}, {$set: update}, {multi: false, upsert: false}, (error, numAffected) => {\n\t\t\t\tif (!error && numAffected === 0) {\n\t\t\t\t\terror = new Error (`Failed to touch session for ID ${JSON.stringify (sessionId)}`);\n\t\t\t\t}\n\n\t\t\t\tcallback (error);\n\t\t\t});\n\t\t}",
"_store() {\n try {\n window.sessionStorage.setItem('playQueue', JSON.stringify(this._array));\n } catch(e) {}\n }",
"_emitServiceStreamDataUpdateEvent ( dataUpdate ) {\n\n super.emit(\n EMITABLE_EVENTS.serviceStreamDataUpdate\n , dataUpdate\n );\n }",
"async updateAuthorChatBotSessionData(author, data) {\n await this.mongoDao.findOneAndUpdate(constants.mongoCollections.chatBotSession, {\n author: author\n }, {\n $set: { ...data\n }\n }, {\n upsert: true\n });\n }",
"update ( data ) {\n this.store.update(data);\n }",
"function sendWebsocketUpdate() {\n io.emit('updateMessages', messageContainer);\n}",
"function onQueue(data) {\n\tif (\"Error\" in data) {\n\t\tonError(data.Error);\n\t} else if (\"Value\" in data) {\n\t\tqueueSize = data.Value.length;\n\t\t$(\"#current-queue>tbody\").empty();\n\t\tfor (i = currentTrack; i < data.Value.length; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t\tfor (i = 0; i < currentTrack; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t}\n}",
"function savedatainsession(id){\n\tvar addeduser = \"\";\n\tif(userExistArray.length != 0){\n\t\tfor(var t=0; t<userExistArray.length; t++){\n\t\t\tif(t == 0){\n\t\t\t\taddeduser = userExistArray[t];\n\t\t\t}else{\n\t\t\t\taddeduser += \",\"+ userExistArray[t];\n\t\t\t}\n\t\t}\n\t}\n\t$('#'+id).empty();\n\tcloseDialog(id);\n\tvar sessionid = seletedSessionId.split(\"__\");\n\tvar url = getURL('Console') + \"action=putConsoleInvitation&query={'MAINCONFIG': [{'user': '\"+globalUserName+\"','addeduser': '\"+addeduser+\"','sessionid': '\"+sessionid[1]+\"'}]}\";\n $.ajax({\n url: url,\n dataType: 'html',\n method: 'POST',\n proccessData: false,\n async:false,\n success: function(data) {\n \tdata = $.trim(data);\n\t\t\tgetActiveUser();\n\t\t}\n });\n\n}",
"function saveFormData(req, data, cb) {\n if (req.session && sessionStore) {\n if (!req.session.orders) { req.session.orders = {}; }\n req.session.orders[data.order_id] = data;\n sessionStore.set(data.session_id, req.session, function(err) {\n return cb(err);\n });\n }\n else return cb(new Error('No session storage to save form data.'));\n }",
"static async putAssetData(ctx, assetKey, assetData) {\n\t\t//Convert input JSON object to buffer and store it to blockchain\n\t\tlet dataBuffer = Buffer.from(JSON.stringify(assetData));\n\t\tawait ctx.stub.putState(assetKey, dataBuffer);\n\t}",
"_updateSessionMetadataOnStart() {\n const sessionMetadata = {\n matchSpectatorInfo: this.sessionData.currentMatchInfo,\n summonerData: this.sessionData.summonerData,\n matchTime: this.sessionData.matchTime,\n status: this.sessionData.status,\n startTime: this.sessionData.startTime,\n };\n GameSessionService.updateSessionMetadata(this.sessionId, sessionMetadata);\n }",
"_registerUpdates() {\n const update = this.updateCachedBalances.bind(this);\n this.accountTracker.store.subscribe(update);\n }",
"storeConfirmedOfferInSession(confirmedOffer) {\n this.storeInSession(KEYS.CONFIRMED_OFFER, confirmedOffer);\n }",
"_handleNextDataEvent() {\n this._processingData = false;\n let next = this._dataEventsQueue.shift();\n if (next) {\n this._onData(next);\n }\n }",
"async setSessionToken(userId, sessionToken) {\n this.internalState.tokens[userId] = sessionToken;\n await this.sync(this.internalState);\n }",
"feedSubmit() {\n sessionStorage.setItem(\"feedsub\",true);\n this.setState({\n feedSub: true\n })\n }",
"async _enqueueUpdate(){// Mark state updating...\nthis._updateState=this._updateState|STATE_UPDATE_REQUESTED;let resolve;const previousUpdatePromise=this._updatePromise;this._updatePromise=new Promise(res=>resolve=res);// Ensure any previous update has resolved before updating.\n// This `await` also ensures that property changes are batched.\nawait previousUpdatePromise;// Make sure the element has connected before updating.\nif(!this._hasConnected){await new Promise(res=>this._hasConnectedResolver=res);}// Allow `performUpdate` to be asynchronous to enable scheduling of updates.\nconst result=this.performUpdate();// Note, this is to avoid delaying an additional microtask unless we need\n// to.\nif(result!=null&&typeof result.then==='function'){await result;}resolve(!this._hasRequestedUpdate);}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
delete Stevens 1.1 I need to take a storeItem object away from the list of items in the cartItems array. 1.2 steps If I click the minus button, then it will take one away from the total quanitity of that item in the cart. 1.3 actions make a function removeButton & add Event Listener (last thing to do) 1.4 within the function removeButton, there needs to a for loop like the addButton, with an if statement, but not as complicated I don't think because we're not starting off with 0, but it will be more complicated, who knows. does there need to be an iffound=true/false? probably not | function removeButton(storeItem, cartItems) {
// console.log(storeItem, cartItems.length)
// I need to do a for loop here to run through the cartItems array
// I need an if/else statement of if quantity is > / >= 2 (when remove button is clicked - include in function?), take away 1 from the quanityt...else remove item from cart
// let quantityDeducted = false
for (let i = 0; i < cartItems.length; i++) {
// I assume, you don't need this - I have been trying to use console.log, but when it doesn't work and I'm stuck I just feel I should just crack on with the exercise just to get it done, otherwise I feel like I am using up time. I need to work on using console.log more effectively...
const cartItem = cartItems[i];
console.log(storeItem, cartItems.length)
if (cartItem.quantity = 0) {
console.log("items that equal 0: ", cartItem)
cartItems.splice(cartitem);
else(cartItem.quantity >= 2)
cartItem.quantity = cartItem.quantity - 1;
}
}
// if (quantityDeducted) {
// const newCartItem = {
// item: storeItem,
// quantity: 1
// };
// cartItems.push(newCartItem);
} | [
"function itemQuantity() {\n let increase = document.querySelectorAll(\"i.fa-plus\");\n let decrease = document.querySelectorAll(\"i.fa-minus\");\n let currentQuantity = 0;\n let currentProduct = \"\";\n\n let foodItems = localStorage.getItem(\"foodsInCart\");\n foodItems = JSON.parse(foodItems);\n\n for (let i = 0; i < increase.length; i++) {\n increase[i].addEventListener(\"click\", () => {\n currentQuantity =\n increase[i].parentElement.querySelector(\"span\").textContent;\n\n currentProduct = increase[\n i\n ].parentElement.parentElement.previousElementSibling.textContent\n .trim()\n .toLowerCase()\n .replace(/ /g, \"_\");\n\n foodItems[currentProduct].inCart += 1;\n cartCounter(foodItems[currentProduct]);\n totalCost(foodItems[currentProduct]);\n localStorage.setItem(\"foodsInCart\", JSON.stringify(foodItems));\n cartContent();\n });\n }\n\n for (let i = 0; i < decrease.length; i++) {\n decrease[i].addEventListener(\"click\", () => {\n currentQuantity =\n decrease[i].parentElement.querySelector(\"span\").textContent;\n\n currentProduct = decrease[\n i\n ].parentElement.parentElement.previousElementSibling.textContent\n .trim()\n .toLowerCase()\n .replace(/ /g, \"_\");\n\n if (foodItems[currentProduct].inCart > 1) {\n foodItems[currentProduct].inCart -= 1;\n cartCounter(foodItems[currentProduct], \"decrease\");\n totalCost(foodItems[currentProduct], \"decrease\");\n localStorage.setItem(\"foodsInCart\", JSON.stringify(foodItems));\n cartContent();\n }\n });\n }\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 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}",
"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 removeBasketItem(event) {\n let buttonClicked = event.target;\n let id = buttonClicked.previousElementSibling.innerText;\n buttonClicked.parentElement.parentElement.remove();\n let itemToRemove = { productId: id }\n basketArrayItemRemove(itemToRemove)\n updateBasketTotal();\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}",
"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 removeFromCart(item){\n if(cart.hasOwnProperty(item)) {\n delete cart[item]\n }\n else{\n console.log(`That item is not in your cart`)\n }\n}",
"function removeFromCart(elem) {\n let favorites = JSON.parse(localStorage.getItem(favoritesKey));\n // get the text of the element to remove\n // this is used for string matching below\n let elemToRemove = JSON.stringify($(elem).parent().parent().html());\n if (favorites) {\n console.log(\"Searching localStorage for\\n\" + elemToRemove);\n // iterate over favorites\n const favoritesLength = favorites.length;\n for (let i = 0; i < favoritesLength; i++) {\n currentFav = JSON.stringify(favorites[i]);\n // check currentFav against element to remove\n if (currentFav == elemToRemove) {\n console.log(\"Found element to remove. Removing...\");\n favorites.splice(i, 1);\n localStorage.setItem(favoritesKey, JSON.stringify(favorites));\n // found the element, nothing left to do, break\n break;\n }\n }\n console.log(\"cart after removing element:\\n\"\n + JSON.parse(localStorage.getItem(favoritesKey)));\n }\n // if the cart was already empty, no action is required.\n // log a warning anyways\n else {\n console.warn(\"attempt to remove from empty cart. no further action needed.\")\n }\n}",
"function onRedeemPressed(isVoucher) {\n numActions++;\n\n var currentDenomination = '$1';\n var currentVoucherID = document.getElementById('vouchertitle').innerText;\n\n if (isVoucher) {\n currentDenomination = document.getElementById('denomination').innerText;\n }\n\n var currentQuantity = document.getElementById('quantity').innerText;\n\n var voucherFound = false;\n\n for (i = 0; i < objectives.length; i++) {\n if (objectives[i].name == currentVoucherID) {\n voucherFound = true;\n if (objectives[i].value == currentDenomination) {\n\n if (objectives[i].quantity == currentQuantity) {\n objectives.splice(i, 1);\n updateObjectives();\n if (objectives.length <= 0) {\n sendTrialCompleteAction();\n myNavigator.pushPage('correct_end.html');\n }\n else {\n myNavigator.resetToPage('rewards.html');\n }\n\n } else {\n ons.notification.toast('Right Voucher but wrong Quantity!', { timeout: 1000, animation: 'fall' });\n sendUserErrorAction(\"Wrong voucher quantity redeemed\");\n }\n\n }\n else {\n ons.notification.toast('Right Voucher but wrong Denomination', { timeout: 1000, animation: 'fall' });\n sendUserErrorAction(\"Wrong voucher denomination redeemed\");\n }\n\n }\n }\n\n if (!voucherFound) {\n ons.notification.toast('Wrong Voucher!', { timeout: 1000, animation: 'fall' });\n sendUserErrorAction(\"Wrong voucher name redeemed\");\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 calculateOrder() {\n var itemOrder = order.getItems();\n // clear orderList \n orderList.innerHTML = '';\n\n itemOrder.forEach(function (item, i) {\n var elem = document.createElement('li');\n elem.classList.add('order__list-item');\n var elemContent = item.name + ' x ' + item.quantity + ', price: ' + parseInt(item.type.price) * parseInt(item.quantity) + ' ' + VALUE_PRICE + ', calories: ' + parseInt(item.type.calories\n ) * parseInt(item.quantity) + ' ' + VALUE_CALORY\n elem.textContent = elemContent\n\n var buttonRemove = document.createElement('button');\n // adding class for future remove handling with event delegation\n buttonRemove.classList.add('js-button-remove');\n // adding data attribute for easy finding element index when removing item\n buttonRemove.setAttribute('data-index', i);\n buttonRemove.textContent = 'X';\n\n elem.appendChild(buttonRemove);\n\n orderList.appendChild(elem);\n });\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 generateCart() {\n // const cartButton = document.querySelector(\".cart-btn\");\n // const closeButton = document.querySelector(\".close-cart\");\n const clearButton = document.querySelector(\".clear-cart\");\n const cartDOM = document.querySelector(\".cart\");\n const cartOverlay = document.querySelector(\".cart-overlay\");\n const cartItems = document.querySelector(\".cart-items\");\n // const cartTotal = document.querySelector(\".cart-total\");\n const cartContent = document.querySelector(\".cart-content\");\n let numberProducts = 1;\n const itemQuantity = document.querySelector(\".item-amount\");\n\n $(\".cart-button\").on(\"click\", function() {\n cartOverlay.classList.add(\"transparentBcg\");\n cartDOM.classList.add(\"showCart\");\n });\n\n $(\".close-cart\").on(\"click\", function() {\n cartOverlay.classList.remove(\"transparentBcg\");\n cartDOM.classList.remove(\"showCart\");\n });\n\n function increaseQuantity() {\n numberProducts++;\n $(itemQuantity).text(numberProducts);\n console.log(numberProducts);\n }\n\n function decreaseQuantity() {\n numberProducts--;\n $(itemQuantity).text(numberProducts);\n console.log(numberProducts);\n }\n\n $(\".fa-chevron-up\").on(\"click\", function() {\n increaseQuantity();\n $(cartItems).text(numberProducts);\n });\n\n $(\".fa-chevron-down\").on(\"click\", function() {\n decreaseQuantity();\n $(cartItems).text(numberProducts);\n });\n\n $(clearButton).on(\"click\", function() {\n $(cartContent).empty();\n });\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}",
"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 deleteStock() {\n rows = getSelectedRowBoxes();\n\n for (var i=rows.length - 1; i >= 0; i--) {\n var prodId = rows[i].parentNode.parentNode.id;\n delete products[prodId];\n products.splice(prodId, 1);\n }\n saveData();\n displayInventory();\n}",
"function setItems(product) {\r\n //8 console.log(\"inside of set Items function\");\r\n //8 console.log(\"my prodcut function is\", product);\r\n //8 this will print inside of my set item function, you will see my product is with the name of the product you clicked on\r\n\r\n //8.3 when ever we click on the set item function. this will check if it exist already some items or not\r\n //8.3 the item you want to get product incart in local sotrage to check if it exist and see if something in our local storage\r\n //8.3 if we are trying to get something from our local storage we type this console.log(\"My cartitems are\", cartitems);\r\n //8.3 this will print in console my cart item are with the name,price.. of the item\r\n //8.3 this is in a json foramt\r\n let cartItems = localStorage.getItem('productsInCart');\r\n //8.4 this is what to pass in from json into javascript object\r\n //8.4 we are updating this json\r\n cartItems = JSON.parse(cartItems);\r\n //8.5 if cart item is equal to null this means something is already in our cart/localstorage\r\n //8.5 then we going to do a check\r\n if (cartItems != null) {\r\n\r\n if (cartItems[product.tag] == undefined) {\r\n //8.7 this is to update my cart item what ever in my local sotrage \r\n cartItems = {\r\n //8.7 grab what ever from my cart items before and then using the rest operator from js\r\n ...cartItems,\r\n //8.7 and then add this new product \r\n [product.tag]: product\r\n }\r\n }\r\n //8.7 this is to incrase 1 is already in there\r\n cartItems[product.tag].inCart += 1;\r\n } else {\r\n //8.1 this is the first time you going to click \r\n product.inCart = 1;\r\n cartItems = {\r\n //8.6 setting the product in cart to be 1\r\n [product.tag]: product\r\n }\r\n }\r\n //8.2 we dont want to pass javascript object. we use JSON.stringify to pass as json object on local sotrage. \r\n //8.2 it will show the name, price ... with incart 1.\r\n localStorage.setItem(\"productsInCart\", JSON.stringify(cartItems));\r\n}",
"function buildCartTable() {\r\n let table = document.getElementById('itemCart');\r\n let tbodyRef = table.getElementsByTagName('tbody')[0];\r\n for (let i = 0; i < this.itemsInCart.length; i++) {\r\n let row = tbodyRef.insertRow(0);\r\n let removeButtonContainer = document.createElement('button');\r\n removeButtonContainer.innerText = 'x';\r\n removeButtonContainer.onclick = function () {\r\n removeRow(i);\r\n };\r\n let spanContainer = document.createElement('span');\r\n spanContainer.innerText = this.itemsInCart[i].name;\r\n row.insertCell(0).append(spanContainer, removeButtonContainer);\r\n\r\n let quantityContainer = document.createElement('div');\r\n quantityContainer.className = 'qty-div';\r\n let minusButton = document.createElement('button');\r\n minusButton.innerText = '-';\r\n minusButton.onclick = function () { minusClick(i); };\r\n let qtyInput = document.createElement('input');\r\n qtyInput.type = 'number';\r\n this.itemsInCart[i].qty !== undefined ? this.itemsInCart[i].qty : this.itemsInCart[i].qty = 1;\r\n qtyInput.value = this.itemsInCart[i].qty !== undefined ? this.itemsInCart[i].qty : 1;\r\n let plusButton = document.createElement('button');\r\n plusButton.innerText = '+';\r\n plusButton.onclick = function () { plusClick(i); };\r\n quantityContainer.append(minusButton, qtyInput, plusButton);\r\n\r\n row.insertCell(1).appendChild(quantityContainer);\r\n\r\n row.insertCell(2).innerHTML = this.itemsInCart[i].price.display;\r\n\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fix links for the tweetdeck.twitter.com website. | function fixTweetDeckLinks() {
// Catch visible links from tweets, quoted tweets and tweets in detail
var selector = ('.tweet-text > .url-ext[data-link-fixed!=1]:not(.is-vishidden), '
+'.quoted-tweet .url-ext[data-link-fixed!=1], '
+'.tweet-detail .url-ext[data-link-fixed!=1]'),
links = $( selector );
$( links ).each(function(){
setUrlToLink(this, this.dataset.fullUrl);
});
} | [
"function fixLinks() {\n // Catch only text links, not pictures and other stuff\n var links = $( '.twitter-timeline-link[data-link-fixed!=1]:not(.media, .u-hidden)' );\n\n $( links ).each(function(){\n setUrlToLink(this, this.dataset.expandedUrl);\n });\n}",
"function fixLinks() {\n for (var a of document.getElementsByTagName(\"a\")) {\n var href = a.href;\n if (href.baseVal) {\n var label = href.baseVal;\n if (label.includes(\"#mjx-eqn\")) {\n label = decodeURIComponent(label.substring(1));\n var eqn = document.getElementById(label);\n if (eqn) {\n var s = eqn.closest(\"section\");\n if (s) {\n a.href.baseVal =\n location.origin + location.pathname + \"#\" + s.id;\n }\n }\n }\n }\n }\n }",
"function setupLinks() {\n $('#channels a').click(function(event){\n var elem = $(event.currentTarget);\n var baseUrl = window.location.href.split('#')[0];\n var newUrl = baseUrl + elem.attr('href');\n location.replace(newUrl);\n location.reload();\n });\n }",
"function updateOldBlogsLinks(request, response, next) {\n\t\tif (request.params.schemeUrl.startsWith('https://blogs.r.ftdata.co.uk/')) {\n\t\t\trequest.params.schemeUrl = request.params.schemeUrl.replace('https://blogs.r.ftdata.co.uk', 'https://blogs.ft.com');\n\t\t\trequest.params.imageUrl = request.params.schemeUrl;\n\t\t} else if (request.params.schemeUrl.startsWith('http://blogs.r.ftdata.co.uk/')) {\n\t\t\trequest.params.schemeUrl = request.params.schemeUrl.replace('http://blogs.r.ftdata.co.uk', 'https://blogs.ft.com');\n\t\t\trequest.params.imageUrl = request.params.schemeUrl;\n\t\t}\n\t\tnext();\n\t}",
"function fixDownloadButton() {\n\t\tlet dlBtn = document.getElementsByClassName('dev-page-download');\n\n\t\tfor(let i = 0; i < dlBtn.length; i++) {\n\t\t\tcleanupLink(dlBtn[i]);\n\n\t\t\tif(debug)\n\t\t\t\tconsole.info(scriptName + ': Removed junk from Download-Button');\n\t\t}\n\t}",
"function ensureLinksHaveTargetInApiIntro() {\n $(\"#intro a\").attr('target', function(i, current) {\n return current || '_self';\n });\n }",
"function cleanUp(text) {\n return text.replace(/(http.*\\s|#\\S+)/g, '').trim();\n }",
"function substituteTwitterUrls(text, urls) {\n var restoredText = text;\n urls.forEach(function (urlObj) {\n log.debug(urlObj);\n log.debug('Substituting ' + urlObj.url + ' -> ' + urlObj.expanded_url);\n restoredText = replaceAll(restoredText, urlObj.url, urlObj.expanded_url);\n });\n return restoredText;\n }",
"function fixRelatedContentURIs(document) {\n function fixBlock(block) {\n if (block.content) {\n block.content.forEach(item => {\n if (item.mdn_url) {\n item.uri = mapToURI(item);\n delete item.mdn_url;\n }\n fixBlock(item);\n });\n }\n }\n document.related_content.forEach(block => {\n fixBlock(block);\n });\n}",
"takeOverLinks() {\n delegate(window.document, \"click\", \"a\", event => {\n if (\n event.button !== 0 ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey\n ) {\n return;\n }\n const link = event.target.closest(\"a\");\n if (\n link.getAttribute(\"href\").charAt(0) === \"#\" ||\n link.host !== window.location.host\n ) {\n return;\n }\n\n if (\n !event.defaultPrevented &&\n !link.hasAttribute(\"data-remote\") &&\n link.protocol.indexOf(\"http\") === 0\n ) {\n event.preventDefault();\n\n // update sidebar links\n if (link.closest(\"aside\")) {\n this.navigate(updateURL(link.href));\n } else {\n this.navigate(link.href);\n }\n }\n });\n }",
"function cleanupLinks(callback) {\n var linkcount = 0, cbcount = 0;\n var links = db.get(\"shortlinks\");\n if (Object.keys(links).length === 0)\n callback();\n else {\n Object.keys(links).forEach(function (link) {\n linkcount++;\n (function (shortlink, location) {\n fs.stat(path.join(paths.files, location), function (error, stats) {\n cbcount++;\n if (!stats || error) {\n delete links[shortlink];\n }\n if (cbcount === linkcount) {\n db.set(\"shortlinks\", links, function () {\n callback();\n });\n }\n });\n })(link, links[link]);\n });\n }\n}",
"function setupBanLink() {\n\tvar a = $(\".banner a\");\n\tvar link = a.attr(\"href\");\n\ta.removeAttr(\"href\");\n\t\n\tif (isPath(homePath)) {\n\t\ta.click(toggleBanner);\n\t} else {\n\t\ta.click(function() {\n\t\t\tanimateLink(link, true);\n\t\t});\n\t}\n}",
"function removeimageurls(tweet) {\n var tweetstext = tweet.text;\n\n if (tweet.entities.media != undefined) {\n //loop through images in the tweet\n $.each(tweet.entities.media, function (index, value) {\n\n var urltoreplace = value.url;\n\n tweetstext = tweetstext.replace(urltoreplace, \"\");\n }\n\n\n );\n }\n\n return tweetstext;\n }",
"function cleanGitHubUrl(url) {\n return url.replace('https://api.github.com', 'https://github.com');\n}",
"function updateURL() {\n const URLelement = elements.get(\"title\").querySelector(\"a\");\n switch (URLelement) {\n case null:\n currentURL = undefined;\n break;\n default:\n const id = URLelement.href.replace(/[^0-9]/g, \"\");\n currentURL = `https://tidal.com/browse/track/${id}`;\n break;\n }\n}",
"function bindConfiguredUrls() {\n\t$('.elearning_link').bind('click', function(event) {\n\t\tevent.preventDefault();\n\t\tswitchContent($(this).attr('href'));\n\t\tupdateURL();\n\t});\n\n\tif (caaersUrl != '') {\n\t\t$('.caaers_link').attr('href', caaersUrl);\n\t} else {\n\t\t$('.caaers_link').bind('click', function(event) {\n\t\t\tevent.preventDefault();\n\t\t\talert('No URL configured for caAERS. Please contact your administrator or manually edit js/config.js.');\n\t\t});\n\t}\n}",
"function loot_fix_sell_links() {\n\n\t$('a[href^=\"javascript:sellEquipmentDialog\"]').each(function(index) {\n\t\tvar values = $.map(this.href.split(\",\"), $.trim);\n\t\tthis.href = \"profile.php?x=1&selectedTab=loot&action=sell&iid=\" + values[1] + \"&cat=\" + values[2] + \"&formNonce=\" + values[5].replace(/'/g, '');\n\t});\n\n}",
"function ConvertUrlToAnchor(s) {\n var description = s;\n var whitespace = \" \";\n var anchortext = \"\";\n var words;\n var splitList = [whitespace, '\\n', '\\r\\n'];\n words = splitString(description, splitList);\n \n var regexp = /^((https?|ftp):\\/\\/|(www|ftp)\\.)[a-z0-9-]+(\\.[a-z0-9-]+)+([\\/?].*)?$/\n var i = 0;\n for (i = 0; i <= words.length; i++) {\n if (words[i] != undefined) {\n var urls = \"\";\n var testregexp = /^((ftp|http|https):\\/\\/|(www|ftp)\\.)[a-z0-9-]+(\\.[a-z0-9-]+)+([\\/?].*)?(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!-\\/]))?$/\n if (testregexp.test(words[i].toString()) == true) {\n urls = '<a target=\"_blank\" href= \\\"' + words[i].toString() + '\\\">' + words[i].toString() + '</a>'\n\n if (i == words.length - 1) {\n description = description.substring(0, description.lastIndexOf(words[i].toString()));\n description = description + urls;\n } else {\n description = description.replace(words[i].toString() + ' ', urls + ' ').replace(words[i].toString() + '\\n', urls + '\\n').replace(words[i].toString() + '\\r\\n', urls + '\\r\\n');\n }\n }\n }\n }\n return description;\n}",
"function resetLink() {\n var instruction = gettext(\"This link will open the default version of this interactive:\");\n var link = window.location.href.split('?', 1)[0].replace(/^\\/+|\\/+$/g, '');\n $(\"#cfg-grammar-link\").html(`${instruction}<br><a target=\"_blank\" href=${link}>${link}</a>`);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: _fnSortAttachListener Purpose: Attach a sort handler (click) to a node Returns: Inputs: object:oSettings dataTables settings object node:nNode node to attach the handler to int:iDataIndex column sorting index function:fnCallback callback function optional | function _fnSortAttachListener ( oSettings, nNode, iDataIndex, fnCallback )
{
$(nNode).bind( 'click.DT', function (e) {
/* If the column is not sortable - don't to anything */
if ( oSettings.aoColumns[iDataIndex].bSortable === false )
{
return;
}
/*
* This is a little bit odd I admit... I declare a temporary function inside the scope of
* _fnBuildHead and the click handler in order that the code presented here can be used
* twice - once for when bProcessing is enabled, and another time for when it is
* disabled, as we need to perform slightly different actions.
* Basically the issue here is that the Javascript engine in modern browsers don't
* appear to allow the rendering engine to update the display while it is still excuting
* it's thread (well - it does but only after long intervals). This means that the
* 'processing' display doesn't appear for a table sort. To break the js thread up a bit
* I force an execution break by using setTimeout - but this breaks the expected
* thread continuation for the end-developer's point of view (their code would execute
* too early), so we on;y do it when we absolutely have to.
*/
var fnInnerSorting = function () {
var iColumn, iNextSort;
/* If the shift key is pressed then we are multipe column sorting */
if ( e.shiftKey )
{
/* Are we already doing some kind of sort on this column? */
var bFound = false;
for ( var i=0 ; i<oSettings.aaSorting.length ; i++ )
{
if ( oSettings.aaSorting[i][0] == iDataIndex )
{
bFound = true;
iColumn = oSettings.aaSorting[i][0];
iNextSort = oSettings.aaSorting[i][2]+1;
if ( typeof oSettings.aoColumns[iColumn].asSorting[iNextSort] == 'undefined' )
{
/* Reached the end of the sorting options, remove from multi-col sort */
oSettings.aaSorting.splice( i, 1 );
}
else
{
/* Move onto next sorting direction */
oSettings.aaSorting[i][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort];
oSettings.aaSorting[i][2] = iNextSort;
}
break;
}
}
/* No sort yet - add it in */
if ( bFound === false )
{
oSettings.aaSorting.push( [ iDataIndex,
oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] );
}
}
else
{
/* If no shift key then single column sort */
if ( oSettings.aaSorting.length == 1 && oSettings.aaSorting[0][0] == iDataIndex )
{
iColumn = oSettings.aaSorting[0][0];
iNextSort = oSettings.aaSorting[0][2]+1;
if ( typeof oSettings.aoColumns[iColumn].asSorting[iNextSort] == 'undefined' )
{
iNextSort = 0;
}
oSettings.aaSorting[0][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort];
oSettings.aaSorting[0][2] = iNextSort;
}
else
{
oSettings.aaSorting.splice( 0, oSettings.aaSorting.length );
oSettings.aaSorting.push( [ iDataIndex,
oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] );
}
}
/* Run the sort */
_fnSort( oSettings );
}; /* /fnInnerSorting */
if ( !oSettings.oFeatures.bProcessing )
{
fnInnerSorting();
}
else
{
_fnProcessingDisplay( oSettings, true );
setTimeout( function() {
fnInnerSorting();
if ( !oSettings.oFeatures.bServerSide )
{
_fnProcessingDisplay( oSettings, false );
}
}, 0 );
}
/* Call the user specified callback function - used for async user interaction */
if ( typeof fnCallback == 'function' )
{
fnCallback( oSettings );
}
} );
} | [
"function aa_tableColumnSort(table,settings)\n{\n\tvar thead = jQuery(table).find('>thead')[0];\n\taa_registerHeaderEvent(thead,'mouseup',clickHandler,'Sort','no dominant');\n\t\n\tfunction clickHandler(e,thead,th) {\n \t var jth = jQuery(th);\n\t if (!thead.LastMouseDown || thead.LastMouseDown.th != th) return;\n\t \n \t\tif (jth.hasClass('sort_ascending'))\t{\n \t\t removeCssClasses(thead);\n \t\t jth.addClass('sort_descending');\n \t\t settings.doSort(th,'descending');\n \t\t} else if (jth.hasClass('sort_descending')) {\n \t\t removeCssClasses(thead);\n \t \t\tsettings.doSort(null);\t// remove the sort\n\t\t} else {\n\t \t\tremoveCssClasses(thead);\n\t \t\tjth.addClass('sort_ascending');\n \t\t settings.doSort(th,'ascending');\n \t\t}\n\t}\n\n\tfunction removeCssClasses(thead)\t{\n\t \tjQuery(thead).find('th').removeClass('sort_ascending').removeClass('sort_descending');\n\t}\n}",
"function sortOn(element, sortColumn)\n{\n\tvar sorter = findSorter(element); // Get the sorter form\n\tif (sorter == null)\n\t{\n\t\talert(\"Couldn't find sorter form\");\n\t\treturn;\n\t}\n\tvar type = sorter.name.substring(6);\n\tvar sortColumnField = sorter[\"sortColumn\" + type];\n\tif (sortColumnField == null)\n\t{\n\t\talert(\"Couldn't find sortColumn hidden field\");\n\t}\n\tsortColumnField.value = sortColumn;\n\tsorter.submit();\n}",
"function addImagesSortButtonHandler() {\r\n // Depricated for new settings\r\n /*\r\n var sort = getImagesSortType();\r\n \r\n //var $el = $(\".options-settings-images-sort-item\"); // Old Settings\r\n var $el = $(\".nav-settings-images-sort > li\"); // New Settings\r\n var $item = $el.filter(\"[data-sort=\" + sort + \"]\");\r\n \r\n //if ($item) $item.addClass(\"active\"); // Old Settings\r\n if(NAVI) NAVI.setTab($item);// New Settings\r\n \r\n if (sort == 0) { //gallery\r\n $(\"#options-settings-images-upload\").css('display', 'none');\r\n } else if (sort == 1) { //your uploads\r\n $(\"#options-settings-images-upload\").css('display', 'block');\r\n }\r\n\r\n $el.on(\"click\", function () {\r\n var $el = $(this);\r\n var val = parseInt($el.attr(\"data-sort\"));\r\n var currentSort = getImagesSortType();\r\n\r\n if (currentSort != val) {\r\n BRW_sendMessage({\r\n command: \"setImagesSortType\",\r\n val: val\r\n });\r\n } //if\r\n });\r\n */\r\n}",
"function addThemesSortButtonHandler() {\r\n // Depricated for new settings\r\n /*\r\n //var $el = $(\".options-settings-themes-sort-item\"); // Old Settings\r\n var $el = $(\".nav-settings-themes-sort > li, [nav=navi-bg-downloaded]\"); // New Settings\r\n var $item = $el.filter(\"[data-sort=\" + getThemesSortType() + \"]\");\r\n \r\n //if ($item) $item.addClass(\"active\"); // Old Settings\r\n if(NAVI && $item.length) NAVI.setTab($item);// New Settings\r\n \r\n $el.on(\"click\", function () {\r\n var $el = $(this);\r\n \r\n var val = parseInt($el.attr(\"data-sort\"));\r\n \r\n if(!val){\r\n if($el.attr(\"nav\") == \"navi-bg-downloaded\") val = 3;\r\n }\r\n \r\n \r\n var currentSort = getThemesSortType();\r\n if (currentSort != val) {\r\n BRW_sendMessage({\r\n command: \"setThemesSortType\",\r\n val: val\r\n });\r\n } //if\r\n });\r\n */\r\n}",
"function addLiveThemesSortButtonHandler() {\r\n // Depricated for new settings\r\n /*\r\n //var $el = $(\".options-settings-live-themes-sort-item\"); // Old Settings\r\n var $el = $(\".nav-settings-live-themes-sort > li\"); // New Settings\r\n \r\n var $item = $el.filter(\"[data-sort=\" + getLiveThemesSortType() + \"]\");\r\n \r\n //if ($item) $item.addClass(\"active\"); // Old Settings\r\n if(NAVI) NAVI.setTab($item);// New Settings\r\n \r\n $el.on(\"click\", function () {\r\n var $el = $(this);\r\n var val = parseInt($el.attr(\"data-sort\"));\r\n var currentSort = getLiveThemesSortType();\r\n\r\n if (currentSort != val) {\r\n BRW_sendMessage({\r\n command: \"setLiveThemesSortType\",\r\n val: val\r\n });\r\n } //if\r\n });\r\n */\r\n}",
"function addTableSorter() {\r\n\t$('#stats-table').tablesorter({\r\n\t\ttheme: 'blue',\r\n\t\ttextExtraction: function (node) {\r\n\t\t\t// remove thousands separator for ordering correctly\r\n\t\t\treturn $(node).text().replace(/\\./g, '');\r\n\t\t}\r\n\t});\r\n\t// Make table cell focusable\r\n\t// http://css-tricks.com/simple-css-row-column-highlighting/\r\n\tif ( $('.focus-highlight').length ) {\r\n\t\t$('.focus-highlight').find('td, th')\r\n\t\t\t.attr('tabindex', '1')\r\n\t\t\t// add touch device support\r\n\t\t\t.on('touchstart', function() {\r\n\t\t\t\t$(this).focus();\r\n\t\t\t});\r\n\t}\r\n}",
"function sortClickHandler(\n\tsortedOnType,\n\tsortedType,\n\tsortFunction,\n\tsortStringAscendingly,\n\tsortStringDescendingly,\n\tsortMenuButton,\n\tsortButton,\n\tsortHeader\n) {\n\tlet filteredList = filter(searchByNameInput.value, partyFilterList, stateFilterList);\n\tif (sortedType === \"firstName\" && !sortHeader) {\n\t\tchamber === \"senate\"\n\t\t\t? app.swapCardNameOrder(\"senateMemberFirstName\")\n\t\t\t: app.swapCardNameOrder(\"houseMemberFirstName\");\n\t}\n\tif (sortedType === \"lastName\" && !sortHeader) {\n\t\tchamber === \"senate\"\n\t\t\t? app.swapCardNameOrder(\"senateMemberLastName\")\n\t\t\t: app.swapCardNameOrder(\"houseMemberLastName\");\n\t}\n\n\tif (sortedOnType) {\n\t\tsortedOn.setSortedOn(\n\t\t\tsortedType,\n\t\t\tsortMenuButton,\n\t\t\tsortButton,\n\t\t\tsortHeader,\n\t\t\tsortStringDescendingly\n\t\t);\n\t\tfilteredList.sort(sortFunction).reverse();\n\t\tupdateVue(filteredList);\n\t} else {\n\t\tsortedOn.setSortedOn(\n\t\t\tsortedType,\n\t\t\tsortMenuButton,\n\t\t\tsortButton,\n\t\t\tsortHeader,\n\t\t\tsortStringAscendingly\n\t\t);\n\t\tfilteredList.sort(sortFunction);\n\t\tupdateVue(filteredList);\n\t}\n}",
"function contextMenuCallback(params, self) {\r\n //sortColumn: headerName,\n //sortDirectionCode: sortDirectionCode\r\n //{event: 'contextMenuClicked', headerName: headerName, sortDirectionCode: item.code}\r\n var column = self.detailData.columns.find(function (h) {\r\n return h.name == params.sortColumn;\r\n });\r\n\r\n //set direction\r\n column.sort.direction = params.sortDirectionCode;\r\n\r\n //set order\r\n setSortOrder(column, self);\r\n\r\n //make context menu disappear\r\n self.contextMenu.isVisible = false;\r\n }",
"function sortDescTable(n) {\n\n\t//if the column to sort is the first one (the \"modifier\" button) : we don't do anything\n\tif (n == 0)\n\t\treturn;\n\n\t//get the ref to the HTML table to order\n\tvar table = document.getElementById(\"ticket-table\");\n\n\t//Get all the sortable rows then put them in an Array\n\tlet sortableRows = getTableStructure();\n\tlet tableRows = Array.from(sortableRows);\n\n\t//Insertion sort algorithm\n\tfor (let i = 1; i < tableRows.length; i++) {\n\n\t\tlet x = tableRows[i];\n\t\tlet tbody1 = tableRows[i][1][1];\n\t\tlet row1 = tbody1.firstElementChild;\n\n\t\tlet j = i;\n\n\t\tlet prevVal = row1.cells[n];\n\n\t\twhile (j > 0 && (prevVal.innerText.toLowerCase() > tableRows[j - 1][1][1].firstElementChild.cells[n].innerText.toLowerCase())) {\n\n\t\t\ttableRows[j] = tableRows[j - 1];\n\t\t\tj--;\n\n\t\t}\n\n\t\ttableRows[j] = x;\n\t}\n\n\t//reorder table according to the sorted array\n\tfor (let i = 1; i < tableRows.length; i++) {\n\n\t\t//As the element are already in the table, it will only move them (not append them again)\n\t\ttable.appendChild(tableRows[i][1][1]);\n\n\t}\n\n}",
"tableListenersOn() {\n this.node.addEventListener(\"click\", this.clickHandler.bind(this));\n }",
"function sortAjax(e) {\n genericAjax();\n}",
"function clicked(){\n sorter(numbers);\n}",
"function sortTable() {\n\t\t\t\t\tsortedBy = $(\"#projects-sort :selected\").text();\n\t\t\t\t\tsortedById = parseInt($(\"#projects-sort\").val());\n\t\t\t\t\tdataTable.order([ [ sortedById, sortOrder ] ]).draw();\n\t\t\t\t}",
"function setSortCardsListeners() {\n\tconst sortMenuButton = document.getElementById(\"sortMenuButton\");\n\tconst sortByFirstName = document.getElementById(\"sortFirstName\");\n\tconst sortByLastName = document.getElementById(\"sortLastName\");\n\tconst sortByParty = document.getElementById(\"sortParty\");\n\tconst sortByState = document.getElementById(\"sortState\");\n\tconst sortBySeniority = document.getElementById(\"sortSeniority\");\n\tconst sortByVotesWith = document.getElementById(\"sortVotesWith\");\n\tconst sortByVotesAgainst = document.getElementById(\"sortVotesAgainst\");\n\tconst sortByDistrict = document.getElementById(\"sortDistrict\");\n\n\tsortByFirstName.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on first name';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on first name';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.firstName,\n\t\t\t\"firstName\",\n\t\t\tsortByFirstNameAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByFirstName,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByLastName.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on last name';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on last name';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.lastName,\n\t\t\t\"lastName\",\n\t\t\tsortByLastNameAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByLastName,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByParty.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on party';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.party,\n\t\t\t\"party\",\n\t\t\tsortByPartyAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByParty,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByState.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on state';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on state';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.state,\n\t\t\t\"state\",\n\t\t\tsortByStateAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByState,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortBySeniority.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-numeric-up\"></i> Sort on seniority';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on seniority';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.seniority,\n\t\t\t\"seniority\",\n\t\t\tsortBySeniorityAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortBySeniority,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByVotesWith.onclick = () => {\n\t\tlet sortStringAscendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-up\"></i> Sort on votes with party';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on votes with party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.partyVotesWith,\n\t\t\t\"partyVotesWith\",\n\t\t\tsortByVotesWithAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByVotesWith,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByVotesAgainst.onclick = () => {\n\t\tlet sortStringAscendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-up\"></i> Sort on votes against party';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on votes against party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.partyVotesAgainst,\n\t\t\t\"partyVotesAgainst\",\n\t\t\tsortByVotesAgainstAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByVotesAgainst,\n\t\t\tundefined\n\t\t);\n\t};\n}",
"listenSort() {\n document.getElementById(\"sortMedias\").addEventListener('change', () => {\n this.render();\n this.listenNewLikes();\n })\n }",
"function buildSortingSublist(options){\n\t \n\t var $ = NS.jQuery;\n\t //get the column header and remove event default ns clicks events\n\t var columns = $('tr' +dicUtilConfig.PRE_MB_CF.MAIL_GRID.ClientTableHeaderId).children();\n\n\t var queryString = window.location.search.substring(1, window.location.search.length);\n\t var objQuery = dicUtilUrl.parseQueryString(queryString);\n\t\n\t var oldOb = objQuery[\"ob\"];\n\t if (oldOb){\n\t\t oldOb = oldOb.split(\" \");\n\t }\n\t dicUtilObj.deleteProperties(objQuery, [\"ob\"]);\n\t var columnSorted = dicUtilObj.toSortArray(dicUtilConfig.MAILBOX.CUSTOM_FIELDS.MAIL_GRID.Columns, function(obj1, obj2){\n\t\t\treturn obj1[obj1.key].Order - obj2[obj2.key].Order; \n\t\t});\n\t\n\t //remove event click\n\t columns.each(function(){\n\t\t var objCol = $(this);\n\t\t objCol.css('cursor', 'pointer');\n\t\t objCol.removeAttr(\"onclick\");\n\t\t var spans = objCol.find(\"div>span\");\n\t\t var span = $(spans[0]);\n\t\t if (spans.length > 0){\n\t\t\t var num = parseInt(span.attr(\"id\").replace(dicUtilConfig.MAILBOX.CUSTOM_FIELDS.MAIL_GRID.Id + \"dir\", \"\"));\n\t\t\t if(num >=0 && num < columnSorted.length){\n\t\t\t\t var configColumn = columnSorted[num];\n\t\t\t\t configColumn = configColumn[configColumn.key];\n\t\t\t\t \n\t\t\t\t if(\"Field\" in configColumn){\n\t\t\t\t\t buildSortingColumn({objQuery:objQuery,\n\t \t\t\t\t\t configColumn:configColumn,\n\t \t\t\t\t\t mailboxType:options.mailboxType,\n\t \t\t\t\t\t oldOb: oldOb,\n\t \t\t\t\t\t objCol:objCol,\n\t \t\t\t\t\t spanDirection: span});\n\t\t\t\t\t \n\t\t\t\t }\n\t\t\t }\n\t\t }\n\t\t \n\t });\n }",
"function addSortableBehavior() {\n $(\"#tasklist > ul\").one().sortable({\n update: function( event, ui ) {\n $(\"#tasklist > ul > li\").each( function (index, elt) {\n var taskId = getTaskId(this);\n var task = TaskList.get(taskId);\n $(this).attr(\"data-taskId\",index);\n task.taskId = index;\n });\n console.log(\"sorting tasks\");\n TaskList.sort(\"taskId\").save();\n }\n });\n}",
"function docEdits_sortWeights()\n{\n //var msg=\"presort -------------\\n\";\n //for (i=0; i<docEdits.editList.length; i++) {\n // msg += i+\":\" +docEdits.editList[i].weight+\"=\"+docEdits.editList[i].text+\"\\n\";\n //}\n //alert(msg);\n\n //shift-sort algorithm. Keeps same-weight chunks together\n for (var i=0; i < docEdits.editList.length-1; i++)\n {\n for (var j=i+1; j < docEdits.editList.length; j++)\n {\n var aType = docEdits.editList[i].weightType;\n var bType = docEdits.editList[j].weightType;\n\n var a = docEdits.editList[i].weightNum;\n var b = docEdits.editList[j].weightNum;\n\n if ((aType == bType && a != null && b != null && a > b)\n || (aType == \"belowHTML\" && bType==\"aboveHTML\"))\n {\n var temp = docEdits.editList[j];\n for (var k=j; k>i; k--)\n {\n docEdits.editList[k] = docEdits.editList[k-1];\n }\n docEdits.editList[i] = temp;\n }\n }\n }\n\n //var msg=\"After pre sort:\\n\";\n //for (i=0; i<docEdits.editList.length; i++) {\n // msg += i+\":\" +docEdits.editList[i].weight+\"=\"+docEdits.editList[i].text+\"\\n\";\n //}\n //alert(msg);\n}",
"function sortCreditUS(col){ \n CCT.index.sortCreditUS(col,gUSCreditEmailUpdated,gUSCreditAmountUpdated,gUSCreditNotesUpdated,sortCreditUSCallBack);\n\n document.getElementById(\"mCreditUSTableDiv\").style.display = 'none';\n errorMessage(\"Sorting ...\",\"CreditUS\",\"Message\");\n document.mForm.mCreditButton.disabled = true; \n }",
"function TableWrapper(table, options) {\n \"use strict\";\n\n var allOptions, opt;\n\n // this tells allows Datatables to sort specially-crafted\n // column values in a special way.\n //\n // The special value is made by taking an arbitrary string,\n // enclosing it in a <span>, and giving that span a title\n // attribute with a numeric value.\n //\n // For example:\n // e.g. <span title=\"12\">12 days of christmas</span>\n // e.g. <span title=\"87\">four score and seven years ago</span>\n //\n // Columns so represented can then be easily sorted by their\n // original numeric value, affording flexibility about the\n // strings inside.\n //\n jQuery.fn.dataTableExt.oSort['title-numeric-desc'] = function(a,b) {\n var x = a.match(/title=\"(-?[0-9\\.]+)/)[1];\n var y = b.match(/title=\"(-?[0-9\\.]+)/)[1];\n x = parseFloat( x );\n y = parseFloat( y );\n return ((x < y) ? -1 : ((x > y) ? 1 : 0));\n };\n\n jQuery.fn.dataTableExt.oSort['title-numeric-asc'] = function(a,b) {\n var x = a.match(/title=\"(-?[0-9\\.]+)/)[1];\n var y = b.match(/title=\"(-?[0-9\\.]+)/)[1];\n x = parseFloat( x );\n y = parseFloat( y );\n return ((x < y) ? 1 : ((x > y) ? -1 : 0));\n };\n\n // The following 2 functions are used for version sorting on TAF.\n // It splits the input strings into multiple chunks of digits and non-digits\n // and then compare these chunk to decide which value precedes the other.\n jQuery.fn.dataTableExt.oSort['taf-version-asc'] = function(a,b) {\n return CompareAlnumVersionString(a,b);\n };\n\n jQuery.fn.dataTableExt.oSort['taf-version-desc'] = function(a,b) {\n var result = CompareAlnumVersionString(a,b);\n return (result * -1);\n };\n\n if (window.VmTAF.newUI) {\n allOptions = {\n bDeferRender:true,\n\n /*\n * Variable: sDom\n * Purpose: Dictate the positioning that the created elements will take\n * Scope: jQuery.dataTable.classSettings\n * Notes:\n * The following options are allowed:\n * 'l' - Length changing\n * 'f' - Filtering input\n * 't' - The table!\n * 'i' - Information\n * 'p' - Pagination\n * 'r' - pRocessing\n * The following constants are allowed:\n * 'H' - jQueryUI theme \"header\" classes\n * 'F' - jQueryUI theme \"footer\" classes\n * The following syntax is expected:\n * '<' and '>' - div elements\n * '<\"class\" and '>' - div with a class\n * Examples:\n * '<\"wrapper\"flipt>', '<lf<t>ip>'\n *//*\n * Without this, tables look a mess in Firefox.\n * See http://datatables.net/forums/comments.php?DiscussionID=1131\n * and http://www.datatables.net/usage/options\n */\n sDom: '<\"H\"Tfr>tS<\"F\"<\"refresh-indicator\">i><\"clear\">',\n iDisplayLength: -1,\n bLengthChange: false,\n asStripeClasses: [\"ui-widget-content\"],\n bJQueryUI: true\n };\n } else {\n // use old settings for old UI\n allOptions = {\n bDeferRender:true,\n sDom: '<\"top\"f>rt<\"bottom\"ilp><\"clear\">',\n bDestroy:$.browser.msie\n };\n }\n\n if (!options || !options.firstColumnSortable) {\n /* Disable sorting on column 0 (usually a checkbox) */\n allOptions.aoColumnDefs = [\n { \"bSortable\": false, \"aTargets\": [0] }\n ];\n }\n\n /* Add/change custom options */\n for (opt in options) {\n if (options.hasOwnProperty(opt)) {\n allOptions[opt] = options[opt];\n }\n }\n\n /*\n * A checkbox in a table header is used to select/unselect\n * all the rows in that table.\n */\n var self=this;\n table.find('.table-row-selector').each(function() {\n $(this).click(function() {\n var check = $(this).is(':checked');\n self.MarkAllRowCheckboxes(check);\n });\n });\n\n this.dataTable = table.dataTable(allOptions);\n this.masterCheckbox = this.dataTable.find('th input:checkbox');\n\n if (window.VmTAF.newUI) {\n // move the table header buttons inside the table\n var wrapper = table.parent().children('.fg-toolbar:first');\n if (wrapper.length) {\n var buttons = table.closest('form').children('.button-row');\n buttons.appendTo(wrapper);\n\n buttons.removeClass('button-row');\n buttons.children('button').button();\n }\n }\n\n table.disableSelection();\n table.show();\n this.tableRowData = [];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the index of an entity with a defined id. | indexOfId(id) {
var Model = this.constructor.classes().model;
var index = 0;
var result = -1;
id = String(id);
while (index < this._data.length) {
var entity = this._data[index];
if (!(entity instanceof Model)) {
throw new Error('Error, `indexOfId()` is only available on models.');
}
if (String(entity.id()) === id) {
result = index;
break;
}
index++;
}
return result;
} | [
"getIndex(id, data){\n for(let i=0; i<data.length; i++){\n if(id === data[i].id){\n return i;\n }\n }\n console.log(\"No match found\");\n return 0;\n }",
"function getExprIndex(id) {\n\t\tlet exprs = Calc.getState().expressions.list;\n\t\treturn exprs.findIndex((elem) => {\n\t\t\treturn elem.id === id;\n\t\t});\n\t}",
"function getOrderIdxById(id) {\n\tif (isNaN(id)) {\n\t\tthrow NaN;\n\t} else {\n\t\tid = Number(id);\n\t}\n\tvar idx = undefined;\n\tfor (var i = 0; i < orders.length; i++) {\n\t\tif (orders[i].id === id) {\n\t\t\tidx = i;\n\t\t}\n\t}\n\treturn idx;\n}",
"posById(id){\n let slot = this._index[id];\n return slot ? slot[1] : -1\n }",
"function getAppIndexById(id) {\n if (!id || typeof id != \"string\") return null;\n \n for (var node = 0; node < apps.length; node++) {\n if (apps[node].id == id) {\n return node;\n }\n }\n return null;\n}",
"function findByTypeAndId(entity, id, callback){\n\n\tif( Database[entity] ){\n\t\tDatabase[entity].find(id).success(callback);\n\t}\n\telse{\n\t\tcallback({err: \"No entity matching the name '\" + entity + \"' was found.\"});\n\t}\n}",
"function getEntityFromElementID(entityID) {\n entityID = entityID.substring(6, entityID.length)\n var entity;\n // Look through all the squares\n for(i = 0; i < squares.length; i++){\n // If it has an entity and that entityElements id is equal to the id we're looking for\n if(squares[i] && squares[i].id == entityID) { \n entity = squares[i];\n break;\n }\n }\n return entity;\n}",
"function findEntry(resultId, db) {\n for (const page of db) {\n if (page.id === resultId) {\n return page;\n }\n }\n return resultId;\n}",
"function getIndexOfId(list, item) {\n return list.map(function(e) {\n return e.ID;\n }).indexOf(item);\n}",
"function indexById(videoId)\n {\n for (var i = 0; i < videoList.length; i++)\n {\n if (videoId == videoList[i].id)\n {\n return i;\n }\n }\n return -1;\n }",
"getIdx(key = this.state.rec_key) {\n return this.state.records.findIndex(rec => rec.key === key);\n }",
"function getId(dbEntity){\n return dbEntity.entity.key.path[0].id ||\n dbEntity.entity.key.path[0].name;\n}",
"function findObject(index) {\n return repository[index];\n }",
"function _index(phrase) {\n\n var indexKey = phrase.substr(0, config.indexDepth).trim();\n if (local.index[indexKey] === undefined) {\n local.index[indexKey] = {};\n }\n\n // Set Id as either the same as the previous equal phrase or\n // max id + 1\n var id = local.index[indexKey][phrase] || (local.phraseId + 1);\n\n // Update max id\n local.phraseId = Math.max(local.phraseId, id);\n\n local.index[indexKey][phrase] = id;\n\n return id;\n }",
"static index(id, shouldUpdate = true){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.shouldUpdate = shouldUpdate;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'index', kparams);\n\t}",
"function getWaypiontIndexByFeatureId(featureId) {\n var wpResult = $('#' + featureId);\n var wpElement;\n if (wpResult) {\n wpElement = wpResult.parent().parent();\n }\n if (wpElement) {\n var wpIndex = wpElement.attr('id');\n if (!isNaN(wpIndex)) {\n return wpIndex;\n } else {\n return null;\n }\n }\n }",
"function getIndObjOfHtmlId(htmlId) {\r\n\r\n for (var i = 0; i < AllHtmlGridIds.length; i++) {\r\n if (AllHtmlGridIds[i] == htmlId)\r\n return CurStepObj.allIndObjs[i];\r\n }\r\n\r\n alert(\"Internal Bug: HtmlID for Index not fuond for id:\" + htmlId);\r\n}",
"function searchForIdInArray(id,array){\n var returnValue;\n var position;\n\n (DEBUG || ALL ) && console.debug(\"Searching for id\",id,\"in\",array);\n for (position = 0; position < array.length; position++) {\n if (array[position].keyID === id) {\n returnValue = array[position];\n (DEBUG || ALL) && console.log(\"found!\");\n break;\n }\n }\n return returnValue;\n }",
"function getUrlLocalModelInd(urlId) {\n for (var i = 0; i < $scope.urls.length; i++) {\n if ($scope.urls[i]._id === urlId) {\n return i;\n }\n }\n return -1;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
End the current session for all callers (asks the server to do it) uses internal_call_id to know what to end, set when you got online | async function endSession() {
updateStatus("Ending Call");
console.log(`Ending session: ${internal_call_id}`);
try {
var res = await fetch("/endSession?room_name=" + internal_call_id);
// basic error handling
if (res.status !== 200) {
console.log(res);
alert("Failed to end your session: " + res.status);
return;
} else {
updateStatus("Call Ended");
}
} catch (error) {
console.log(`failed to end the session ${error}`);
console.log("we'll keep cleaning up though");
}
// clear out any remaining connections
other_callers.forEach(function (caller) {
disconnectEndpoint(caller);
});
} | [
"function endCallback() {\n endIANA(session);\n }",
"function endCall() {\n setMessages([]);\n setChatUsers([]);\n socketRef.current.emit(\"leaveRoom\");\n socketRef.current = null;\n }",
"function stopCall() {\n // quit the current conference room\n bc.quitRoom(room);\n}",
"function endCallback() {\n logger.log('[whois][' + session.getID() + '] whois server connection ended');\n session.clientEnd();\n }",
"endGame() {\n // All timers must be cleared to prevent against server crashes during prematurely ended games.\n if (this.serverState !== undefined) {\n this.serverState.clearTimers();\n clearTimeout(this.currentForcedTimer);\n }\n\n this.serverState = undefined;\n this.playerMap.removeInactivePlayers();\n this.playerMap.doAll((player) => { player.reset(); });\n }",
"abortSession() {\n if (this.isRunning) {\n this.abort = true;\n }\n }",
"function onSessionDestroyed() {\n const session = this[owner_symbol];\n this[owner_symbol] = undefined;\n\n if (session) {\n session[kSetHandle]();\n process.nextTick(emit.bind(session, 'close'));\n }\n}",
"function verify_call_terminate(booking){\n xapi.status.get('Call').then((status) => {\n\n var callbacknumber = status[0].CallbackNumber ;\n callbacknumber = callbacknumber.split(\":\")[1];\n\n console.log(booking.DialInfo.Calls.Call[0].Number);\n\n if(callbacknumber == booking.DialInfo.Calls.Call[0].Number){\n xapi.command('Call Disconnect').catch(e => console.error('Could not end the call but we tried...'));\n }\n\n });\n}",
"function stopHeartbeat() {\n\tGAME_OVER = true;\n\taddMessage(\"Game over! Score: &e0\", \"error\");\n\tdelete_cookie(\"chocolateChipCookie\");\n\tclearInterval(nIntervId);\n}",
"close()\n\t{\n\n\t\tthis._closed = true;\n\n\t\t// Close the protoo Room.\n\t\tthis._protooRoom.close();\n\n\t\t// Emit 'close' event.\n\t\tthis.emit('close');\n\n\t\t// Stop network throttling.\n\t\tif (this._networkThrottled)\n\t\t{\n\t\t\tthrottle.stop({})\n\t\t\t\t.catch(() => {});\n\t\t}\n\t}",
"function hangUp(){\r\n socket.emit(\"end\", ID, self);\r\n fetch(\"/end\", {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({\r\n ID: ID\r\n })\r\n }).then(response => {\r\n response.redirected;\r\n window.location.href = response.url;\r\n });\r\n}",
"function hangUp() {\n if (gPeerConnection == null)\n failTest('hanging up, but no call is active');\n sendToPeer(gRemotePeerId, 'BYE');\n closeCall();\n returnToPyAuto('ok-call-hung-up');\n}",
"function logout() {\n didAbandonGame = true;\n _send(messages.LOGOUT, main.username);\n }",
"async endCall(duration){\n try{\n const _duration = this.callDurationCalculator(duration)\n const setCallHistory = await Axios.post(API_PREFIX+'Users/callEnded',{payload:this.props.navigation.state.params.payload,duration:_duration});\n const {message,status} = setCallHistory.data;\n if(status == \"Success\"){\n toast('history sett')\n }\n }catch(e){\n console.log(e);\n }\n }",
"function end_game(){\n\tsocket.emit(\"leave_game\");\n}",
"function sessiongc() {\n\tsessionmgr.sessiongc();\n}",
"function SCOFinish() {\n\tif ((APIOK()) && g_strAPIInitialized && (g_bFinishDone == false)) {\n\t\tSCOReportSessionTime()\n\t\tvar err = g_objAPI.LMSFinish(\"\");\n\t\tif (err == true || err == \"true\") g_bFinishDone = true;\n\t}\n\treturn (g_bFinishDone + \"\" ) // Force type to string\n}",
"close() {\n // _close will also be called later from the requester;\n this.requester.closeRequest(this);\n }",
"function leave () {\n var session = USERS.get(socket.id)\n\n if (session) {\n USERS.del(socket.id)\n\n debug('leave session', session.id, socket.id)\n\n session.leave(socket)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to process (sort and calculate cummulative volume) | function processData(list, type, desc) {
// Convert to data points
for(var i = 0; i < list.length; i++) {
list[i] = {
value: Number(list[i][0]),
volume: Number(list[i][1]),
}
}
// Sort list just in case
list.sort(function(a, b) {
if (a.value > b.value) {
return 1;
}
else if (a.value < b.value) {
return -1;
}
else {
return 0;
}
});
// Calculate cummulative volume
if (desc) {
for(var i = list.length - 1; i >= 0; i--) {
if (i < (list.length - 1)) {
list[i].totalvolume = list[i+1].totalvolume + list[i].volume;
}
else {
list[i].totalvolume = list[i].volume;
}
var dp = {};
dp["value"] = list[i].value;
dp[type + "volume"] = list[i].volume;
dp[type + "totalvolume"] = list[i].totalvolume;
res.unshift(dp);
}
}
else {
for(var i = 0; i < list.length; i++) {
if (i > 0) {
list[i].totalvolume = list[i-1].totalvolume + list[i].volume;
}
else {
list[i].totalvolume = list[i].volume;
}
var dp = {};
dp["value"] = list[i].value;
dp[type + "volume"] = list[i].volume;
dp[type + "totalvolume"] = list[i].totalvolume;
res.push(dp);
}
}
} | [
"function sortByVol(a,b) {\n if (a.volume < b.volume) {\n return 1;\n }\n else if (a.volume > b.volume) {\n return -1;\n }\n else {\n return 0;\n }\n }",
"function calcForecastVolumeIn(data){\n\t\t\treturn data.forecasts.map(elem=>parseInt(elem.volume_in)).reduce((acc, curr)=>acc+curr);\n\t\t }",
"function findNb(m) {\n // your code\n let volume = 0\n let index = 1\n while (m > volume){\n volume += Math.pow(index,3);\n if (m === volume) return index;\n index ++;\n }\n return (-1);\n}",
"function totalVolume(...boxes) {\n\tlet x = 0;\n\tfor (let i = 0; i < [...boxes].length; i++) {\n\t\tx += ([...boxes][i].reduce((x, i) => x * i));\n\t}\n\treturn x;\n}",
"cost(volume){\n let retVal = this.costs[0];\n switch(this.type){\n case Type.BINNED:\n let idx = -1; // Index of matching volume\n do{ idx++; } while(volume > this.volumes[idx+1] && (idx+1) < this.volumes.length);\n retVal = this.costs[idx];\n break;\n\n case Type.LINEAR:\n if(volume < this.volumes[0]){\n retVal = this.costs[0];\n } else if(volume > this.volumes[this.volumes.length-1]){\n retVal = this.costs[this.volumes.length-1];\n } else{\n let iu = 1; // Upper Index of Range\n while(volume > this.volumes[iu] && iu < this.volumes.length){\n iu++;\n }\n retVal = (volume - volume[iu-1]) * (cost[iu] - cost[iu-1]) / (volume[iu] - volume[iu-1]) + cost[iu-1];\n }\n break;\n\n case Type.NOT_A_TYPE:\n default:\n retVal = 0;\n break;\n }\n\n return retVal;\n }",
"fillPackages(){\n let total = this.totalVolume();\n\n // ?\n\n return [];\n }",
"function volumeDiscount(quantity, volumeBuying, volumePaying) {\n //calcualte the modulus and then th divisior\n return Math.floor(quantity / volumeBuying) * volumePaying + (quantity % volumeBuying);\n}",
"function sortGasses()\n{\n var mixArray = Array();\n var mixTable = document.getElementById(\"addGassesHere\");\n\n if (mixTable.rows.length > 1) {\n for (var i = 0; i < mixTable.rows.length; i++)\n mixArray[i] = Array(mixTable.rows[i].cells[0].innerHTML, // Gas Mix\n mixTable.rows[i].cells[1].innerHTML); // Volume needed\n\n mixArray.sort(byMODhighToLow);\n\n for (var i = 0; i < mixArray.length; i++) {\n mixTable.rows[i].cells[0].innerHTML = mixArray[i][0]; // Gas mix\n mixTable.rows[i].cells[1].innerHTML = mixArray[i][1]; // Volume needed\n }\n }\n return;\n}",
"averageMiddleThreeTimes(arg) {\n // let arr = [this.state.time1, this.state.time2, this.state.time3, this.state.time4, this.state.time5];\n let arr = arg\n if (arr.length > 3) {\n arr.sort((a,b) => a - b) \n let newArray = arr.slice(1, -1)\n // arr.shift()\n // arr.pop()\n return this.averageCubeTime(newArray)\n } else {\n return null\n }\n //need to call averageCubeTime function to get average of three remaining times\n }",
"calcPercentage() {\n return Math.floor((this.volume / 20) * 100) + \"%\";\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 }",
"function subInventory() {\n return stock[i] - order[i][0];\n}",
"function sortBy() {\n //DOM ELEMENTS\n let divCards = gridGallery.children;\n divCards = Array.prototype.slice.call(divCards);\n // CHECK VALUE\n switch (sortByBtn.value) {\n // IF VALUE IS DATE\n case \"date\":\n divCards.sort(function(a, b) {\n if (a.childNodes[0].date < b.childNodes[0].date) {\n return -1;\n } else {\n return 1;\n }\n });\n for (let i = 0; i < divCards.length; i++) {\n gridGallery.appendChild(divCards[i]);\n }\n break;\n // IF VALUE IS POPULARITY\n case \"popularity\":\n divCards.sort(function(a, b) {\n return b.childNodes[3].textContent - a.childNodes[3].textContent;\n });\n for (let i = 0; i < divCards.length; i++) {\n gridGallery.appendChild(divCards[i]);\n }\n break;\n // IF VALUE IS TITLE\n case \"title\":\n divCards.sort(function(a, b) {\n if (a.childNodes[1].textContent < b.childNodes[1].textContent) {\n return -1;\n } else {\n return 1;\n }\n });\n break;\n }\n // REMOVE ELEMENTS\n gridGallery.innerHTML = \"\";\n // ADD ELEMENTS FROM SWITCH CASE'S RESULT\n for (let i = 0; i < divCards.length; i++) {\n gridGallery.appendChild(divCards[i]);\n }\n}",
"function adjustVolume(deltaVolume){\r\n setVol(globalVolume + deltaVolume);\r\n}",
"function calcProductivity(cb) {\n\t\tvar thirtyDays = 30 * 24 * 60 * 60 * 1000;\n\n\t\tstats.members = _.map(stats.members, function (member) {\n\t\t\tvar rank = 0;\n\n\t\t\tif (member.points) {\n\t\t\t\tvar pointDecayPercentage = ((Date.now() - member.lastSat) / thirtyDays) * 10 / 100;\n\t\t\t\trank = (member.points + member.totalUniqueParentsSatFor) * (1 - pointDecayPercentage);\n\t\t\t\trank = rank < 0 ? 0 : rank;\n\t\t\t}\n\n\t\t\tmember.productivityRanking = rank;\n\t\t\treturn member;\n\t\t});\n\n\t\tstats.productiveMembers = _(stats.members)\n\t\t\t.sortBy('productivityRanking')\n\t\t\t.reverse()\n\t\t\t.map(_.partialRight(_.pick, 'memberId', 'productivityRanking'))\n\t\t\t.valueOf();\n\n\t\tcb();\n\t}",
"getVolume() {\r\n return this._muted ? 0 : this._volume;\r\n }",
"function vinculum(number) {\n let numbersub = number;\n let num = number;\n let bararray = [];\n let romanNumeralStr = ''\n\n if (num < 1000) {\n romanNumeralStr += getRoman(num);\n }\n\n while (num > 999) {\n let barnum = 0;\n\n while (num > 999) {\n // Keep track of how many bars need to go over the number\n barnum++;\n num = Math.floor(num / 1000);\n if (num < 1000) {\n let tempStr = getRoman(num);\n romanNumeralStr = romanNumeralStr + tempStr\n let barlen = barnum - 1\n\n // The array holds the bars that go over the roman numerals.\n // The foor loop determines how many dashes are needed to go over the\n // roman numeral.\n for (let i = 0; i < barnum; i++) {\n let line = '-'\n let barstr = line.repeat(romanNumeralStr.length);\n if (bararray.length <= barlen) {\n bararray.push(barstr)\n } else {\n let tempstr = bararray[i]\n bararray[i] = tempstr + barstr;\n }\n }\n }\n }\n\n let total = Math.floor(num) * Math.pow(1000, barnum);\n let tempnum = numbersub - total;\n num = tempnum;\n\n if (num < 1000) {\n let tempStr = getRoman(num);\n romanNumeralStr = romanNumeralStr + tempStr\n }\n }\n\n // This loop puts bars over the roman numeral\n let barfinal = '';\n for (let i = bararray.length - 1; i > -1; i--) {\n barfinal += bararray[i] + '<br>';\n }\n\n romanNumeralStr\n return barfinal + romanNumeralStr;\n}",
"function calcularMediaAritmetica(lista) {\n const sumaLista = lista.reduce(\n function (valorAcumulado = 0, nuevoElemento) {\n return valorAcumulado + nuevoElemento;\n }\n );\n \n const promedioLista = sumaLista / lista.length;\n return promedioLista;\n}",
"averageCubeTime(arg) {\n // let arr = [this.state.time1, this.state.time2, this.state.time3, this.state.time4, this.state.time5];\n let arr = arg\n if (arr.length > 1) {\n let sum = arr.reduce((previous, current) => current += previous);\n let avg = sum / arr.length;\n return avg.toFixed(2)\n } else {\n return arr[0]\n }\n }",
"getActivitiesCal(cal){\n let temp = [];\n let calBurned = 0;\n for(var i=0; i< this.activitiesLog.length; i++){\n if(this.activitiesLog[i].calories >= cal){\n temp.push(this.activitiesLog[i]);\n calBurned += this.activitiesLog[i].calories;\n }\n }\n return {activities: temp, caloriesBurned: calBurned};\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows the Banner (with animation) | function showBanner() {
//choose a perhaps-new explication
displayExplication();
$flap.height($flap.buffer + $explication.height());
$flap.css("top", $topbar.height() - $flap.height());
$banTit.animate({top: $banTit.pos.top, left: $banTit.pos.left, "font-size": $banTit.size},
{duration: dur});
$banSub.animate({path: new $.path.bezier(subGrow), "font-size": $banSub.size}, {duration: dur});
$flap.animate({top: 0}, {easing: "easeOutBack", duration: dur});
$main.animate({top: $flap.height()}, {easing: "swing", duration: dur});
bannered = true;
} | [
"function toggleBanner() {\n\tif (bannered) {\n\t\thideBanner();\n\t\tclearExplication();\n\t} else {\n\t\tshowBanner();\n\t\tsaveExplication();\n\t}\n}",
"function showAnim(anim) {\n\tif (anim != undefined) {\n\t\tvar label = '';\n\t\tvar img = $('<img id=\"animImage\" />')\n\t\timg.attr('src', \"img/ajax-loader-big.gif\");\n\t\timg.attr('alt', 'Animation');\n\t\t\n\t\tswitch(anim) {\n\t\t\tcase \"shuffle\":\n\t\t\t\tlabel = $('<label>' + 'Shuffling cards...' + '</label>');\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tlabel.appendTo( $('#animDiv') );\n\t\timg.appendTo( label );\n\t\t$('#animDiv').attr('class', 'visible');\n\t} else {\n\t\talert(\"An unexpected error ocurred. Please contact Tech Support.\");\n\t\treturn false;\n\t}\n}",
"function hideBanner() {\n\tif ($banSub.filter(\":animated\").length == 0) {\n\t\t// Because of that bug that causes the heights to be all wrong at first, this lets us \n\t\t// have nice heights after animating AND moving (otherwise animations would always be bad from small window\n\t\t// initial conditions).\n\t\t// Want to check that it isn't in the process of animating though when saving the values!\n\t\tsaveBanner();\n\t}\n\t\n\t$banTit.animate({top: $barTit.position().top, left: $barTit.position().left, \"font-size\": $barTit.css(\"font-size\")}, \n\t\t\t{duration: dur});\n\t$banSub.animate({path: new $.path.bezier(subShrink), \"font-size\": $barSub.css(\"font-size\")},\n\t\t\t{duration: dur});\n\t\n\t$flap.animate({top: $topbar.height() - $flap.height()}, \n\t\t\t{easing: 'easeInBack', duration: dur});\n\t$main.animate({top: $topbar.height()}, \n\t\t\t{easing: 'easeInBack', duration: dur});\n\t\n\tbannered = false;\n}",
"showContent () {\n this.loadingWrapper.style.display = 'none'\n this.canvas.style.display = 'block'\n }",
"addInstructionsToDisplay () {\n banner.appendChild(document.createElement('p'))\n .innerHTML = `win by guessing the phrase before losing all of your hearts`;\n }",
"function drawBanner (year) {\n\treturn drawAnImage(arrowSize, svgHeight - arrowSize-barPadding, svgWidth-arrowSize*2, arrowSize, \"../Resources/banners/banner_\"+year+\".png\" );\n}",
"show() {\n var pos = this.body.position;\n var angle = this.body.angle;\n\n push();\n translate(pos.x, pos.y);\n rotate(angle);\n rectMode(CENTER);\n\n drawSprite(this.birdspr);\n /* strokeWeight(1);\n stroke(255);\n fill(127);\n ellipse(0, 0, this.r * 2);\n line(0, 0, this.r, 0);*/\n pop();\n }",
"function setupBanner(){\n\t\n\t/**\n\t * @constructor\n\t * @type {Banner}\n\t */\n\tbanner = new Banner({\n\t\tbanner: '#banner', // String identifying banner id\n\t\tbannerPreloader: '#bannerPreloader', // String identifying banner preloader id\n\t\tbannerNavigation: '#bannerNavigation .button', // String identifying banner navigation buttons\n\t\tbannerPlayback: '#bannerPlayback .button', // String identifying banner playback buttons\n\t\tbannerSlides: '#bannerSlides .slide', // String identifying banner slides\n\t\tlazyLoadNextSlide: false, //if set to true will preload the images for the next slide once it is done with the current\n\t\tduration: 6000, // Integer defining duration of slide playback in milliseconds\n\t\tautoPlay: true, // Boolean indicating whether slide show should auto play\n\t\tshuffle: false, // Shuffle slides and nav\n\t\tnavEvents: false // Runs buttonMouseOver and buttonMouseDown (on the bannerNavigation buttons) on slidechange automatically\n\t});\n\n\tbanner.initialize(); //INIT\n}",
"show(animate) {\n if (animate)\n this.toolbar.show(\"slide\", {direction: \"right\", duration: 300});\n else\n this.toolbar.css(\"display\", \"block\");\n }",
"function initBanner() {\n\tif (!isPath(homePath) && !isPath(\"/\")) {\n\t\tsaveBanner();\n\n\t\t$banTit.css({top: $barTit.position().top, left: $barTit.position().left, \"font-size\": $barTit.css(\"font-size\")});\n\t\t$banSub.css({top: $barSub.position().top, left: $barSub.position().left, \"font-size\": $barSub.css(\"font-size\")});\n\t\t\n\t\t$flap.css({top: -\t$flap.height()});\n\t\t$main.css({top: $topbar.height()});\n\t\t\n\t\tbannered = false;\n\t}\n}",
"function introAnimation() {\n introMenu.animate({\n opacity: 0\n }, 1000, function() {\n introMenu.hide();\n info.show();\n info.animate({\n opacity: 1\n }, 1000);\n });\n}",
"function showBuilder(){\n\tbuilder.style.display = \"inline\";\n\thideButton.innerHTML = \"Hide Builder\";\n}",
"function intro() {\n background(0,0,50);\n\n textFont('Helvetica');\n textSize(18);\n textAlign(CENTER, CENTER);\n fill(255);\n noStroke();\n text('[ click anywhere to start animation ]', width/2,height/2);\n}",
"function displayStrawCup1() {\n image(strawCup1Img, 0, 0, 1000, 500);\n}",
"function happycol_presentation_beginShow(args){\n\t//check for preshow\n\thappycol_enable_controls(args);\n\tif( \n\t\t\n\t\t//list of conditions for a preshow\n\t\targs.lightingDesigner == true \n\t\t\n\t\t){\n\t\thappycol_presentation_preshow(args);\n\t}else{\n\t\thappycol_presentation_theShow(args);\n\t}\n}",
"function showAgent(){\n\t\t\tdocument.getElementById('agent-div').style.display = 'block';\n\t\t\tdocument.getElementById('agent-btn').style.backgroundColor = 'white';\n\t\t\tdocument.getElementById('agent-btn').style.color = 'black';\n\t\t\tdocument.getElementById('owner-div').style.display = 'none';\n\t\t\tdocument.getElementById('user-div').style.display = 'none';\n\t\t\t\n\t\t\tgsap.from(\"#a-name\",0.4,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#a-phone\",0.8,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#a-email\",1.2,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#a-address\",1.6,{opacity:0,ease:Power2.easeInOut,x:-400})\n\n\t\t\tdocument.getElementById('user-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('user-btn').style.color = 'white';\n\t\t\tdocument.getElementById('owner-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('owner-btn').style.color = 'white';\n\t\t}",
"show() {\n\t\tthis.element.style.visibility = '';\n\t}",
"function animateShow(el, script) {\n if ( isString(el) ) {\n el = document.getElementById(el);\n }\n var animId; // id from setInterval()\n var dt = 10; // time interval for animation in ms\n var stage = 0, nstages = Math.floor(script.length / 2);\n var istep = 0, nsteps, op0, op1;\n var setupStage = function() {\n istep = 0;\n nsteps = Math.floor( script[stage*2+1]/dt );\n op0 = script[stage*2];\n op1 = script[stage*2+2];\n el.style.opacity = op0;\n };\n setupStage(stage);\n if ( el.style.display === \"none\" ) {\n el.style.display = \"\"; // show the element if it is hidden\n }\n var showFrame = function() {\n if ( ++istep > nsteps ) { // go to the next stage\n if ( ++stage >= nstages ) {\n // all stages are completed\n clearInterval(animId);\n // hide the element if the last opacity is 0\n if ( op1 <= 0 ) el.style.display = \"none\";\n } else {\n setupStage(stage);\n }\n }\n // set the current opacity\n el.style.opacity = op0 + (op1 - op0)*istep/nsteps;\n };\n animId = setInterval(showFrame, dt);\n}",
"function d_Banner(objName) {\n\tthis.obj = objName;\n\tthis.aNodes = [];\n\tthis.currentBanner = 0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to watch for node insertion (to see if the "invite box" has appeared). | function checkForInviteBox() {
// Get container of invite dialog.
var inviteBoxCheck = document.getElementsByClassName('eventInviteLayout')[0] || document.getElementsByClassName('standardLayout')[0] ||
document.getElementById('fb_multi_friend_selector_wrapper');
// Check for match of inviteBoxCheck, and the TBODY that is later used as an insertion anchor.
if (inviteBoxCheck && inviteBoxCheck.getElementsByTagName('tbody')[0]) {
// Add the button.
addButton(inviteBoxCheck);
// Can not be used at the moment. I have not found a way to re-apply the event handler.
/* Remove node insertion watcher (it's strange, but it needs to be delayed a ms)
window.setTimeout(function () {
window.removeEventListener('DOMNodeInserted', checkForInviteBox, false);
}, 1);
*/
}
} | [
"function watchForLarkGallery () {\n var observer = new MutationObserver(function (mutations) {\n mutations.forEach(function (mutation) {\n if (mutation.addedNodes) {\n theLarkGallery();\n }\n });\n });\n observer.observe(document.body, {\n 'childList': true,\n 'subtree': true\n });\n }",
"function showNodeOrMessage() {\n var update = false;\n status.collection.forEach(function (item) {\n if (item.get(\"id\") === newNode.get(\"id\")) {\n item.set(newNode.attributes);\n update = true;\n }\n });\n if (!update) {\n var folder_id = status.collection.node.get('id'),\n parent_id = newNode.get('parent_id'),\n sub_folder_id = newNode.get('sub_folder_id');\n if (folder_id === parent_id || folder_id === -parent_id) {\n status.collection.add(newNode, {at: 0});\n } else {\n if ( folder_id !== sub_folder_id && sub_folder_id !== 0 ) { //CWS-5155\n var sub_folder = new NodeModel( {id: sub_folder_id }, { connector: status.container.connector, collection: status.collection });\n sub_folder.fetch( { success: function () {\n if ( sub_folder.get('parent_id') === folder_id ) {\n if (status.collection.findWhere({id: sub_folder.get(\"id\")}) === undefined) {\n sub_folder.isLocallyCreated = true;\n status.collection.add(sub_folder, {at: 0});\n }\n }\n // as the workspace got created at different place\n // show message after subFolder added to the nodes table\n successWithLinkMessage();\n }, error: function(err) {\n ModalAlert.showError(lang.ErrorAddingSubfolderToNodesTable);\n successWithLinkMessage();\n }});\n } else {\n // simply show message If the workspace got created\n // in target location (XYZ folder) but created from (ABC folder)\n successWithLinkMessage();\n }\n }\n }\n }",
"function registerHit(node)\n{\n if (node.hit == undefined)\n {\n $.get(\"/hit/\" + node.name, {},\n function(count)\n {\n node.hitCount = count;\n });\n node.hit = true;\n }\n}",
"add(candy, row, col, spawnRow, spawnCol) {\n //Your code here\n \n let vm = this;\n let state = vm.getState();\n if(state == 'FINAL'){\n let candy = candy;\n if(vm.isValidLocation(row, col)){\n let found= vm.getAllCandies().find(function (onSiteCandy){\n return onSiteCandy.ID == candy.ID;\n });\n if(!found) {\n vm.surface[row][col] = candy;\n vm.candies.push(candy);\n vm.sweep();\n vm.boardModification('add', candy, row, col);\n document.body.addEventListener(\"add\", foo.func, {once:true})\n } else return \"candy already on board\";\n } else return \"invalid location passed to function add\";\n } else return \"cannot add candy to board during intermittent state\";\n \n }",
"function isNodeOpen(node) \r\n{\r\n\tfor (i=0; i<openNodes.length; i++)\r\n\t\tif (openNodes[i]==node) return true;\r\n\treturn false;\r\n}",
"function deployFriendListEmptyNotification(){\n try{\n if (invitesFound) {\n document.getElementById(\"TestGift\").innerHTML = \"No Friends Found, But You Have Some Pending Invites!\";\n } else {\n document.getElementById(\"TestGift\").innerHTML = \"No Friends Found! Invite Some Friends With The Button Below!\";\n }\n } catch(err){\n console.log(\"Loading Element Missing, Creating A New One\");\n var liItem = document.createElement(\"LI\");\n liItem.id = \"TestGift\";\n liItem.className = \"gift\";\n if (invitesFound) {\n var textNode = document.createTextNode(\"No Friends Found, But You Have Some Pending Invites!\");\n } else {\n var textNode = document.createTextNode(\"No Friends Found! Invite Some Friends With The Button Below!\");\n }\n liItem.appendChild(textNode);\n userList.insertBefore(liItem, document.getElementById(\"userListContainer\").childNodes[0]);\n }\n\n clearInterval(offlineTimer);\n}",
"isMonitored(node) {\n let monitoredNode = this.monitoredNodes.find(\n monitoredNode => monitoredNode === node.id\n )\n\n if (monitoredNode) {\n return monitoredNode\n }\n }",
"activateNode(node, event) {\n event.stopPropagation();\n if(node == this.getActiveNode()) { this.say(node.el.getAttribute(\"aria-label\")); }\n if(this.isNodeEditable(node) && !(node.el.getAttribute(\"aria-expanded\")==\"false\")\n && !node.el.classList.contains(\"blocks-editing\")) {\n clearTimeout(this.queuedAnnoucement);\n this.queuedAnnoucement = setTimeout(() => { this.say(\"Use enter to edit\"); }, 1250);\n } \n // if there's a selection and the altKey isn't pressed, clear selection\n if((this.selectedNodes.size > 0) && !(ISMAC? event.altKey : event.ctrlKey)) { \n this.clearSelection(); \n }\n this.scroller.setAttribute(\"aria-activedescendent\", node.el.id);\n // if it's not a click, make sure the viewport is scrolled so the node is visible\n if(![\"click\", \"dblclick\"].includes(event.type)) {\n this.cm.scrollIntoView(node.from); // force a CM render\n var {top, bottom, left, right} = node.el.getBoundingClientRect(); // get the *actual* bounding rect\n let offset = this.wrapper.getBoundingClientRect();\n let scroll = this.cm.getScrollInfo();\n top = top + scroll.top - offset.top; \n bottom = bottom + scroll.top - offset.top;\n left = left + scroll.left - offset.left; \n right = right + scroll.left - offset.left;\n this.cm.scrollIntoView({top, bottom, left, right});\n }\n node.el.focus();\n this.focusPath = node.path;\n return true;\n }",
"_watchObjects () {\n const {\n _connections: connections,\n _objects: objects\n } = this\n\n let entered, exited\n function reset () {\n entered = createRawObject()\n exited = createRawObject()\n }\n reset()\n\n function onAdd (items) {\n forEach(items, (item, id) => {\n entered[id] = item\n })\n }\n objects.on('add', onAdd)\n objects.on('update', onAdd)\n\n objects.on('remove', (items) => {\n forEach(items, (_, id) => {\n // We don't care about the value here, so we choose `0`\n // because it is small in JSON.\n exited[id] = 0\n })\n })\n\n objects.on('finish', () => {\n const enteredMessage = !isEmpty(entered) && {\n type: 'enter',\n items: entered\n }\n const exitedMessage = !isEmpty(exited) && {\n type: 'exit',\n items: exited\n }\n\n if (!enteredMessage && !exitedMessage) {\n return\n }\n\n forEach(connections, connection => {\n // Notifies only authenticated clients.\n if (connection.has('user_id')) {\n if (enteredMessage) {\n connection.notify('all', enteredMessage)\n }\n if (exitedMessage) {\n connection.notify('all', exitedMessage)\n }\n }\n })\n\n reset()\n })\n }",
"readyToConnect() {\n add = false;\n }",
"function pingAddCb(e) {\n e.preventDefault();\n var $target = $(this).closest('.target');\n var $parent = $(this).parent();\n var parentId = $target.attr('id'), val = $parent.find(\"input\").val(), createTime = new Date();\n pingTable.insert(PingTree.buildPing(parentId, val , createTime));\n }",
"function addNewGuest() {\n text = input.value;\n if (dataValidation['inputCheck']()) {\n if (dataValidation['existCheck']()) {\n console.log(logTxt['exsistCheckError']);\n dataValidation['exists']();\n } else {\n dataValidation['correct']();\n console.log(logTxt['newGuestAdded'] + text);\n const li = createLI(text);\n ul.appendChild(li);\n updateOnChange();\n }\n } else {\n dataValidation['wrong']();\n }\n}",
"async exists() {\n return $(this.rootElement).isExisting();\n }",
"function initInviteeCreator(){ \r\n\t\t\t$inviteeCreator.on('click', '.add', scope.controller.handleAddClicked);\r\n\t\t}",
"function isNodeEntering(state, interpreter) {\n var updateNeeded = false;\n\n function isSupportedFunctionCall(state) {\n // won't show stepping into and out of member methods (e.g array.slice)\n // because these are built-ins with black-boxed code.\n // User functions may also be object properties, but I am not considering\n // this for this exercise.\n return state.node.type === 'CallExpression' && !state.doneCallee_ && !(state.node.callee && state.node.callee.type === 'MemberExpression');\n }\n\n if (isSupportedFunctionCall(state)) {\n\n var enterNode = {\n name: state.node.callee.name || state.node.callee.id.name,\n parentNode: (0, _lodash.last)(scopeChain) || null,\n paramNames: [],\n interpreterComputedArgs: [],\n // variable information and warnings\n // populated once the interpreter\n // generates scope\n variablesDeclaredInScope: null,\n warningsInScope: new Set(),\n type: 'function',\n status: 'normal'\n };\n\n // set up string tokens for display text\n enterNode.recursion = enterNode.parentNode && enterNode.name === enterNode.parentNode.name;\n enterNode.displayTokens = _DisplayTextHandlerStringTokenizerStringTokenizerJs2['default'].getInitialDisplayTokens(enterNode.name, state.node.arguments, enterNode.parentNode, interpreter);\n enterNode.displayName = _DisplayTextHandlerStringTokenizerStringTokenizerJs2['default'].joinAndFormatDisplayTokens(enterNode.displayTokens, enterNode.recursion);\n\n // the root node carries through information to d3 about overall progress.\n if (nodes.length === 0) {\n enterNode.type = 'root';\n enterNode.errorCount = 0;\n enterNode.status = ''; //d3 manually assigns color to rootNode\n rootNode = enterNode;\n }\n\n // add nodes and links to d3\n nodes.push(enterNode);\n var callLink = getCallLink(enterNode.parentNode, enterNode, 'calling');\n if (callLink) {\n links.push(callLink);\n }\n\n /* Tracking by scope reference allows for\n displaying nested functions and recursion */\n scopeChain.push(enterNode);\n updateNeeded = true;\n }\n return updateNeeded;\n }",
"function watchGameList() {\n\n //watch game added, this happens also on initalization for each game in list\n gameList.on('child_added', function(dataSnapshot) {\n\n // console.log('new game added');\n\n var game = dataSnapshot.ref();\n game.child('name').on('value', function(dataSnapshot) {\n // console.log('user!!!!!!!');\n // console.log(dataSnapshot);\n })\n game.child('info/state').on('value', function(dataSnapshot) {\n\n //watch state switching to over or playing\n if(dataSnapshot.val() == 'over' || dataSnapshot.val() == 'playing') {\n game.child('info/state').off('value');\n handleGameListChange();\n }\n });\n\n handleGameListChange();\n });\n\n //watch game removed\n gameList.on('child_removed', handleGameListChange);\n\n }",
"observePage() {\n if (!this.observer) {\n this.observer = new MutationObserver((mutations) => {\n if (this.handleMutationsTimeout) {\n // Don't handle the mutations yet after all.\n clearTimeout(this.handleMutationsTimeout)\n }\n\n mutations.forEach((mutation) => {\n // Filter mutations to park.\n if (mutation.addedNodes.length) {\n for (const node of mutation.addedNodes) {\n if (!this.walker.skipNode(node)) {\n this.parkedNodes.push(node)\n }\n }\n } else if (!mutation.removedNodes.length && mutation.target) {\n if (!this.walker.skipNode(mutation.target)) {\n this.parkedNodes.push(mutation.target)\n }\n }\n })\n\n // Assuming nothing happens, scan the nodes in 500 ms - after\n // this the page should've been done dealing with the mutations.\n if (this.parkedNodes.length) {\n this.handleMutationsTimeout = setTimeout(this.handleMutations.bind(this), 500)\n }\n })\n }\n\n if (this.observer) {\n this.observer.observe(document.body, {childList: true, subtree: true})\n }\n }",
"function checkForInvites() {\n debug('Checking for repository invites');\n github.users.getRepoInvites({}).then(invites => {\n invites.forEach(invite => {\n debug('Accepting repository invite', invite.full_name);\n github.users.acceptRepoInvite(invite);\n });\n });\n\n debug('Checking for organization invites');\n github.orgs.getOrganizationMemberships({state: 'pending'}).then(invites => {\n invites.forEach(invite => {\n debug('Accepting organization invite', invite.organization.login);\n github.users.editOrganizationMembership({\n org: invite.organization.login,\n state: 'active'\n });\n });\n });\n}",
"markAlive()\n\t{\n\t\tif ( ! this.m_bAlive )\n\t\t{\n\t\t\tthis.m_bAlive = true;\n\t\t\tthis.emit( 'peer_alive' );\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create random lat/long coordinates in a specified radius around a center point | function randomGeo (center, radius) {
var y0 = center.latitude
var x0 = center.longitude
var rd = radius / 111300 // about 111300 meters in one degree
var u = Math.random()
var v = Math.random()
var w = rd * Math.sqrt(u)
var t = 2 * Math.PI * v
var x = w * Math.cos(t)
var y = w * Math.sin(t)
// Adjust the x-coordinate for the shrinking of the east-west distances
var xp = x / Math.cos(y0)
var newlat = y + y0
var newlon = xp + x0
return {
'latitude': newlat.toFixed(5),
'longitude': newlon.toFixed(5),
'distance': distance(center.latitude, center.longitude, newlat, newlon).toFixed(2)
}
} | [
"function getSpawnCoords() {\n\tx = Math.round((Math.random()*(width-3*gridSize)+gridSize)/gridSize)*gridSize;\n\ty = Math.round((Math.random()*(height-3*gridSize)+gridSize)/gridSize)*gridSize;\n\treturn [x, y];\n}",
"function createRandom() {\n let randomCoords = [];\n\n for (let i = 0; i < getRandomInt(100, 500); i++) {\n randomCoords.push([getRandomInt(width), getRandomInt(height)]);\n }\n\n return randomCoords;\n }",
"function generatePointCoordinates(numberOfPoints, sphereRadius) {\n var points = [];\n\n for (var i = 0; i < numberOfPoints; i++) {\n // Calculate the appropriate z increment / unit sphere z coordinate\n // so that we distribute our points evenly between the interval [-1, 1]\n var z_increment = 1 / numberOfPoints;\n var unit_sphere_z = 2 * i * z_increment - 1 + z_increment;\n\n // Calculate the unit sphere cross sectional radius cutting through the\n // x-y plane at point z\n var x_y_radius = Math.sqrt(1 - Math.pow(unit_sphere_z, 2));\n\n // Calculate the azimuthal angle (phi) so we can try to evenly distribute\n // our points on our spherical surface\n var phi_angle_increment = 2.4; // approximation of Math.PI * (3 - Math.sqrt(5));\n var phi = (i + 1) * phi_angle_increment;\n\n var unit_sphere_x = Math.cos(phi) * x_y_radius;\n var unit_sphere_y = Math.sin(phi) * x_y_radius;\n\n // Calculate the (x, y, z) world point coordinates\n x = unit_sphere_x * sphereRadius;\n y = unit_sphere_y * sphereRadius;\n z = unit_sphere_z * sphereRadius;\n\n var point = {\n x: x,\n y: y,\n z: z\n };\n\n points.push(point);\n }\n\n return points;\n}",
"function generatePoints() {\n points = [];\n for (var x = 0; x < width; x = x + width/20) {\n for (var y = 0; y < height; y = y + height/20) {\n var px = x + Math.random() * width/20;\n var py = y + Math.random() * height/20;\n var p = {\n x: px,\n originX: px,\n y: py,\n originY: py\n };\n points.push(p);\n }\n }\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 randomPoint() { return pick(points); }",
"function randomNode(){\n var x = randomize(0, (mapSpace.cols - 1));\n var y = randomize(0, (mapSpace.rows - 1));\n\n return mapSpace.grid[x][y];\n}",
"async seed(parent, {count, minLat, maxLat, minLng, maxLng}, ctx, info) {\n return await Promise.all(\n [...Array(count).keys()].map(async coordinates => {\n await ctx.db.mutation.createLocation(\n {\n data: {\n lat: chance.latitude({min: minLat, max: maxLat}),\n lng: chance.longitude({min: minLng, max: maxLng})\n },\n },\n info\n )\n })\n );\n }",
"function tredify(){\n\tvar mountains;\n\tvar pt = gen_points_in_map(map_dimension, square_dim);\n\tfor (var i=0; i<pt.length; i++){\n\t\tfor (var j=0; j<pt[i].length; j++){\n\t\t\n\t\t\tvar point_selected = pt[i][j];\n\t\t\tif (i===0 && j===0)\n\t\t\t\t//Initial point selected of the third coordinate, i declare the initial point.\n\t\t\t\tpoint_selected[2]=1;\n\t\t\telse{\n\t\t\t\tif (i===0) {\n\t\t\t\t\tpoint_selected[2] = randomizer(pt[i][j-1][2], 1.5);\n\t\t\t\t} \n\t\t\t\telse{\n\t\t\t\t\tpoint_selected[2] = randomizer(pt[i-1][j][2], 1.5);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn pt;\n}",
"function isWithinRadius(centerLat, centerLon, radius, lat, lon) {\n\tlet dist = distance(centerLat, centerLon, lat, lon);\n\treturn (dist <= radius);\n}",
"function turfGenerateRamdomPoints(num, bbox) {\n var points=turf.randomPoint(num, {bbox: bbox});\n return points;\n}",
"function poemCanvasRandomXY() {\n poemCanvasRandomX = random(poemCanvasLeft+50,poemCanvasRight-50);\n poemCanvasRandomY = random(poemCanvasTop+15,poemCanvasBottom-15);\n}",
"function randomMove(radius, opacity){\n\t// Assuming the entire circle is within the limits of the canvas (browser window), the radius must be at least a radius-length within the canvas\n\tvar maxWidth = canvas.width - parseInt(radius);\n\tvar maxHeight = canvas.height - parseInt(radius);\n\tvar minWidth = 0 + parseInt(radius);\n\tvar minHeight = 0 + parseInt(radius);\n\n\t// Generate random (x,y) coordinates\n\tvar newX = Math.floor((Math.random() * (maxWidth - minWidth)) + minWidth);\n\tvar newY = Math.floor((Math.random() * (maxHeight - minHeight)) + minHeight);\n\n\tdrawCircle(newX, newY, radius, pickColor(opacity));\n\tcontext.addHitRegion({id:'newCircle'}); // Distinguish new circles from original ones\n}",
"function myMap() {\r\nlet allcountries = [[61.92410999999999,25.7481511],[-30.559482,\t22.937506],[15.870032,100.992541]];\r\nlet countryselector = [0,1,2];\r\nlet randomselection = countryselector[Math.floor(Math.random() * countryselector.length)];\r\nlet mapProp= {\r\n center:new google.maps.LatLng(allcountries[(randomselection)][0],allcountries[(randomselection)][1]),\r\n zoom:5,\r\n};\r\nlet map=new google.maps.Map(document.getElementById(\"googleMap\"),mapProp);\r\n}",
"function randomMapPos(w,h,ox=0,oy=0){\n\treturn [Math.floor(Math.random()*(w-1))+1, Math.floor(Math.random()*(h-1)+1)];\n}",
"function generateCoordinates () {\n direction = Math.floor(Math.random() * 10) % 2 === 1 ? 'vertical' : 'horizontal'\n locationX = Math.floor(Math.random() * (sizeX - 1))\n locationY = Math.floor(Math.random() * (sizeY - 1))\n if (direction === 'horizontal') {\n if ((locationX + shipSize) >= sizeX) {\n generateCoordinates()\n }\n } else {\n if ((locationY + shipSize) >= sizeY) {\n generateCoordinates()\n }\n }\n }",
"generateDistTrav()\r\n {\r\n var distance = Math.floor((Math.random() * 2) + 1)\r\n console.log(distance + \"m\")\r\n }",
"function setRandomLocation(entity, mapWidth, mapHeight) {\n let padding = 80;\n let isColliding = true;\n entity.x = Math.floor(Math.random() * ((mapWidth - entity.width - padding) - padding + 1)) + padding;\n entity.y = Math.floor(Math.random() * ((mapHeight - entity.height - padding) - padding + 1)) + padding;\n\n if (entity.game.terrain.length === 0) {\n isColliding = false;\n }\n while (isColliding) {\n for (let i = 0; i < entity.game.terrain.length; i++) {\n let other = entity.game.terrain[i];\n isColliding = entity.x < other.x + other.width\n && entity.x + entity.width > other.x\n && entity.y < other.y + other.height\n && entity.y + entity.height > other.y;\n if (isColliding) {\n entity.x = Math.floor(Math.random() * ((mapWidth - entity.width - padding) - padding + 1)) + padding;\n entity.y = Math.floor(Math.random() * ((mapHeight - entity.height - padding) - padding + 1)) + padding;\n }\n\n }\n }\n\n entity.spawnX = entity.x;\n entity.spawnY = entity.y;\n}",
"function generateOval(center, a, b, howManyPoints) {\n if (howManyPoints === void 0) { howManyPoints = 360; }\n // 参数方程\n var theta = 0.0; // in DEG\n var step = 360 / howManyPoints;\n var res = [];\n for (var i = 0; i < howManyPoints; i++) {\n res.push([a * Math.cos(radians(theta)) + center[0], b * Math.sin(radians(theta)) + center[1]]);\n theta += step;\n }\n return res;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize a class symbol information | function serializeClass(symbol) {
var classDetails = serializeSymbol(symbol);
var details = {'@id':classDetails.name, '@type':classDetails.type}
//var prop ={}
symbol.members.forEach((value)=>{
var {name, type} = serializeSymbol(value)
var typeValue = //classDetails.name
details[name] = type
})//.forEachChild(serializeSymbol)
var parentType = symbol.valueDeclaration.parent.classifiableNames
if(parentType.has("WoqlDocument")){
details["@type"] = 'Document'
}
//details.properties = prop
// Get the construct signatures
var constructorType = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);
// var te= constructorType.getConstructSignatures()
/*details.constructors = constructorType
.getConstructSignatures()
.map(serializeSignature);*/
return details;
} | [
"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 }",
"toJSON() {\n var _a;\n return {\n name: this.name,\n parent: (_a = this.parent) === null || _a === void 0 ? void 0 : _a.toJSON(),\n symbols: [\n ...new Set([...this.symbolMap.entries()].map(([key, symbols]) => {\n return symbols.map(x => x.name);\n }).flat().sort())\n ]\n };\n }",
"function SymbolNode(val) {\n this.push(val);\n}",
"dump() {\n\t\tconsole.log(`\\n\"${this.constructor.name}\": ${JSON.stringify(this, null, 4)}`);\n\t}",
"toString() {\n const buffer = [];\n\n // create `class {`\n buffer.push(`class ${this.name} {\\n`);\n\n // check if there are fields items\n if (this.fields.length > 0) {\n // create `constructor(`\n buffer.push(' constructor(');\n\n // loop over fields\n for (let i = 0; i < this.fields.length; i++) {\n // add field name to argurmnet list in constuctor `contructor(arg, `\n buffer.push(this.fields[i].name);\n\n // if i is not equal to length of fields add `,` for next argument\n if (i + 1 !== this.fields.length) {\n buffer.push(', ');\n }\n }\n\n // close arguments brackets for contructor `contructor(arg1, arg2) {`\n buffer.push(') {\\n');\n\n // loop over fields and init each field in contructor\n // this.arg = arg\n for (let field of this.fields) {\n buffer.push(` this.${field.name} = ${field.name};\\n`);\n }\n\n // close constructor function\n buffer.push(' }\\n');\n }\n\n // close class itself\n buffer.push('}');\n\n // return as string\n return buffer.join('');\n }",
"_serialize() {\n return JSON.stringify([\n this._id,\n this._label,\n this._properties\n ]);\n }",
"function IndexedSymbol (i) {\n this.index = i\n}",
"serialize() {\n // cur level\n let sCurLevel = this.curLevelNum + '';\n // instrs shown\n let sInstructions = 'none';\n if (this.instructionsShown.size > 0) {\n sInstructions = Array.from(this.instructionsShown).join(';');\n }\n // level infos\n let sLevelInfos = 'none';\n if (this.levelInfos.size > 0) {\n let arrLevelInfos = [];\n for (let [n, lvlInfo] of this.levelInfos.entries()) {\n arrLevelInfos.push(n + ':' + lvlInfo.serialize());\n }\n sLevelInfos = arrLevelInfos.join(';');\n }\n return [sCurLevel, sInstructions, sLevelInfos].join('|');\n }",
"function serializeSignature(signature) {\n return {\n parameters: signature.parameters.map(serializeSymbol),\n returnType: checker.typeToString(signature.getReturnType()),\n //documentation: ts.displayPartsToString(signature.getDocumentationComment(checker))\n };\n }",
"function visit(node) {\n // Only consider exported nodes\n if (!isNodeExported(node)) {\n return;\n }\n if (ts.isClassDeclaration(node) && node.name) {\n // This is a top level class, get its symbol\n var symbol = checker.getSymbolAtLocation(node.name);\n if (symbol) {\n output.push(serializeClass(symbol));\n }\n // No need to walk any further, class expressions/inner declarations\n // cannot be exported\n }\n else if (ts.isModuleDeclaration(node)) {\n // This is a namespace, visit its children\n ts.forEachChild(node, visit);\n }\n }",
"addSymbol(name, range, type) {\n const key = name.toLowerCase();\n if (!this.symbolMap.has(key)) {\n this.symbolMap.set(key, []);\n }\n this.symbolMap.get(key).push({\n name: name,\n range: range,\n type: type\n });\n }",
"Dump() {\n console.log(\"Turtle params:\", this.currentParams);\n }",
"saveToJSON () {\n\t\tlet digimonJSON = JSON.stringify(this);\n\n\t\treturn digimonJSON;\n\t}",
"debug() {\n this.registerNames.forEach(name => {\n console.log(`${name}: 0x${this.getRegister(name).toString(16).padStart(4, \"0\")}`);\n });\n console.log();\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 }",
"toString() {\n return `${this.constructor.name}( ${this._stack\n .map((rc) => rc.toString())\n .join(', ')} )`;\n }",
"function generateDocumentation(fileNames, options) {\n // Build a program using the set of root file names in fileNames\n //console.log('generateDocumentation')\n var program = ts.createProgram(fileNames, options);\n // Get the checker, we will use it to find more about classes\n var checker = program.getTypeChecker();\n \n var output = [];\n // Visit every sourceFile in the program\n for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {\n var sourceFile = _a[_i];\n if (!sourceFile.isDeclarationFile) {\n // Walk the tree to search for classes\n ts.forEachChild(sourceFile, visit);\n }\n }\n // print out the doc\n fs.writeFileSync(\"./classes_test.json\", JSON.stringify(output, undefined, 4));\n return;\n /** visit nodes finding exported classes */\n function visit(node) {\n //console.log(node.name)\n // Only consider exported nodes\n if (!isNodeExported(node)) {\n return;\n }\n if(ts.isEnumDeclaration(node) && node.name.text){\n \n output.push(serializeEnum(node));\n\n }else if (ts.isInterfaceDeclaration(node)){\n\n //var symbol = checker.getSymbolAtLocation(node.name);\n output.push(serializeEnum(node));\n // console.log(\"isInterfaceDeclaration\", node.name)\n\n }else if (ts.isClassDeclaration(node) && node.name) {\n // This is a top level class, get its symbol symbol.members\n var symbol = checker.getSymbolAtLocation(node.name);\n if (symbol) {\n output.push(serializeClass(symbol));\n }\n // No need to walk any further, class expressions/inner declarations\n // cannot be exported\n }\n else if (ts.isModuleDeclaration(node)) {\n // This is a namespace, visit its children\n ts.forEachChild(node, visit);\n }\n }\n /** Serialize a symbol into a json object */\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 }\n\n function serializeEnum(node){\n var details = {\"@type\":\"Enum\", \"@id\":node.name.text}\n const members = node.members;\n\n node.members.forEach((value)=>{\n var {name, type} = serializeSymbol(value.symbol)\n details[name] = type\n \n })\n return details\n }\n /** Serialize a class symbol information */\n function serializeClass(symbol) {\n \n var classDetails = serializeSymbol(symbol);\n var details = {'@id':classDetails.name, '@type':classDetails.type}\n //var prop ={}\n \n symbol.members.forEach((value)=>{\n var {name, type} = serializeSymbol(value)\n var typeValue = //classDetails.name\n details[name] = type\n \n })//.forEachChild(serializeSymbol)\n \n var parentType = symbol.valueDeclaration.parent.classifiableNames\n \n if(parentType.has(\"WoqlDocument\")){\n details[\"@type\"] = 'Document'\n }\n\n \n //details.properties = prop\n \n // Get the construct signatures\n var constructorType = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);\n // var te= constructorType.getConstructSignatures()\n /*details.constructors = constructorType\n .getConstructSignatures()\n .map(serializeSignature);*/\n return details;\n }\n /** Serialize a signature (call or construct) */\n function serializeSignature(signature) {\n return {\n parameters: signature.parameters.map(serializeSymbol),\n returnType: checker.typeToString(signature.getReturnType()),\n //documentation: ts.displayPartsToString(signature.getDocumentationComment(checker))\n };\n }\n /** True if this is visible outside this file, false otherwise */\n function isNodeExported(node) {\n return ((ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) !== 0 ||\n (!!node.parent && node.parent.kind === ts.SyntaxKind.SourceFile));\n }\n}",
"function maybeQuoteSymbol(symbol) {\n if (symbol.description === undefined) {\n return symbol.toString();\n }\n\n if (/^[a-zA-Z_][a-zA-Z_.0-9]*$/.test(symbol.description)) {\n return symbol.toString();\n }\n\n return `Symbol(${quoteString(symbol.description)})`;\n }",
"SaveMe(graphComponent) {\n // get cytoscape instance\n let cy = graphComponent.getCytoGraph();\n \n const content = {\n nodes: cy.elements(\"node\"),\n edges: cy.elements(\"edge\"),\n minZoom: cy.data(\"minZoom\"),\n\n toString() {\n let Output = \" \";\n for (let i = 0; i < this.nodes.length; i++) {\n Output +=\n this.nodes[i].data(\"name\") +\n \", position: x:\" +\n this.nodes[i].position(\"x\") +\n \", y: \" +\n this.nodes[i].position(\"y\") +\n \" \";\n }\n Output += \", edges: \";\n for (let i = 0; i < this.edges.length; i++) {\n Output += this.edges[i].data(\"name\") + \" \";\n }\n return Output;\n },\n\n freezeEverything() {\n for (let i = 0; i < this.nodes.length; i++) {\n Object.freeze(this.nodes[i]);\n }\n for (let i = 0; i < this.edges.length; i++) {\n Object.freeze(this.edges[i]);\n }\n }\n };\n content.freezeEverything();\n Object.freeze(content);\n return content;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a string name representation of the given PropertyName node | function getNameFromPropertyName(propertyName) {
if (propertyName.type === typescript_estree_1.AST_NODE_TYPES.Identifier) {
return propertyName.name;
}
return `${propertyName.value}`;
} | [
"get propertyName() {}",
"function getJsonName(member) {\n if (!member.selected)\n return '';\n return sp.result(member, 'mappingEntity.name');\n }",
"function extPart_getNodeParamName(partName)\n{\n return dw.getExtDataValue(partName, \"insertText\", \"nodeParamName\");\n}",
"_getSurfaceId (node, propertyName, viewName) {\n if (viewName === 'metadata') {\n return `${node.id}.${propertyName}`\n } else {\n let xpath = node.getXpath().toArray()\n let idx = xpath.findIndex(entry => entry.id === 'body')\n let relXpath\n if (idx >= 0) {\n relXpath = xpath.slice(idx)\n } else {\n relXpath = xpath.slice(-1)\n }\n // the 'trace' is concatenated using '/' and the property name appended via '.'\n return relXpath.map(e => e.id).join('/') + '.' + propertyName\n }\n }",
"function propertyDetails (name) {\n return {\n getter: '_get_' + name,\n setter: '_set_' + name,\n processor: '_process_' + name,\n validator: '_validate_' + name,\n defaultValue: '_default_value_' + name,\n value: '_' + name\n };\n }",
"function getDisplayName(generatorName) {\n // Breakdown of regular expression to extract name (group 3 in pattern):\n //\n // Pattern | Meaning\n // -------------------------------------------------------------------\n // (generator-)? | Grp 1; Match \"generator-\"; Optional\n // (polymer-init)? | Grp 2; Match \"polymer-init-\"; Optional\n // ([^:]+) | Grp 3; Match one or more characters != \":\"\n // (:.*)? | Grp 4; Match \":\" followed by anything; Optional\n return generatorName.replace(/(generator-)?(polymer-init-)?([^:]+)(:.*)?/g, '$3');\n}",
"get timezoneName() {\n let parent = this.parent;\n let n = `${this.name}`;\n while (parent) {\n n = `${parent.name}, ${n}`;\n parent = parent.parent;\n }\n return n;\n }",
"function parseClassPropertyName(classContextId) {\n _expression.parsePropertyName.call(void 0, classContextId);\n}",
"function getJSXName(name) {\n var replacement = acf.isget(acf, 'jsxNameReplacements', name);\n if (replacement) return replacement;\n return name;\n }",
"get nameSuffix() {\n return this.getStringAttribute('name_suffix');\n }",
"function getStorageWindowPropKey(windowId, propKey) {\n return `${windowId}${propKey.slice(0).charAt().toUpperCase()}${propKey.slice(1)}`;\n}",
"function toString ()\n{\n let baleString = \"\";\n let fieldNames = Object.keys(PROPERTIES);\n\n // Loop through the fieldNames and build the string \n for (let name of fieldNames)\n {\n baleString += name + \":\" + this[name] +\";\";\n }\n\n return baleString;\n}",
"function checkEventName(event) {\n if (event.name === null) {\n return '';\n } else {\n return event.name;\n }\n}",
"function genBandName(plasmidId, restricProperty, name, bandStart, bandEnd) {\r\n var eName;\r\n \r\n var nameArray = name.split('-');\r\n if (nameArray.length == 1) {\r\n var enzyme = $.grep(restricProperty, function (d, i) {\r\n return d.name === nameArray[0];\r\n })\r\n eName = enzyme[0].Id + ',' + enzyme[0].Id;\r\n }\r\n if (nameArray.length == 2) {\r\n var enzyme1 = $.grep(restricProperty, function (d, i) {\r\n return d.name === nameArray[0];\r\n })\r\n var enzyme2 = $.grep(restricProperty, function (d, i) {\r\n return d.name === nameArray[1];\r\n })\r\n eName = enzyme1[0].Id + ',' + enzyme2[0].Id;\r\n }\r\n\r\n return plasmidId + \"-\" + eName + \"-\" + bandStart + \"-\" + bandEnd;\r\n}",
"async expandProperty(property) {\n // JavaScript requires keys containing colons to be quoted,\n // so prefixed names would need to written as path['foaf:knows'].\n // We thus allow writing path.foaf_knows or path.foaf$knows instead.\n property = property.replace(/^([a-z][a-z0-9]*)[_$]/i, '$1:');\n\n // Expand the property to a full IRI\n const context = await this._context;\n const expandedProperty = context.expandTerm(property, true);\n if (!ContextUtil.isValidIri(expandedProperty))\n throw new Error(`The JSON-LD context cannot expand the '${property}' property`);\n return namedNode(expandedProperty);\n }",
"function getRuleName(rule){\n if(!rule) return '[NULL RULE]';\n return Array.isArray(rule) ? rule[0].name + (rule.length > 1 ? '..' : '') : rule.name;\n}",
"function encodeName (name) {\n return encode('@' + name)\n}",
"nameFormat(name) {\n return name;\n }",
"function formatName(person){\n\treturn person.fullName;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show output table notes dialog | doShowTableNote (name) {
this.tableInfoName = name
this.tableInfoTickle = !this.tableInfoTickle
} | [
"function displayTable() {\r\n displayOnly(\"#tableOfContents\");\r\n traverseAndUpdateTableHelper();\r\n prepareText(heirarchy.tree[0].sections[0].id);\r\n activePart = 0;\r\n iconEventListeners();\r\n settingsEventListeners();\r\n scrollEventListener();\r\n}",
"function makeOutputHelpRow ( path )\n {\n\tvar content = '<tr class=\"dlHelp vis_help_o1\"><td>' + \"\\n\";\n\tcontent += \"<p>You can get more information about these output blocks and fields \";\n\tcontent += '<a target=\"_blank\" href=\"' + data_url + path + '#RESPONSE\" ';\n\tcontent += 'style=\"text-decoration: underline\">here</a>.</p>';\n\tcontent += \"\\n</td></tr>\";\n\t\n\treturn content;\n }",
"function showNotes() {\n\t\tnotes.forEach(function(note) {\n\t\t\t// first position the notes randomly on the page\n\t\t\tpositionNote(note);\n\t\t\t// now, animate the notes torwards the button\n\t\t\tanimateNote(note);\n\t\t});\n\t}",
"function create_table(name, head, data, need_textbox) {\n\t\n\tif (head[2] == \"aliases\") { //if this is present we know it's about genes not about organisms. \n\t\thead.push(\"Orthologs\");\n\t\tvar link = \"https://www.ncbi.nlm.nih.gov/homologene/?term=\" + name;\n\t\tvar hyperlink = \"<a href=\" + link + \"> orthologs </a>\";\n\t\tdata.push(hyperlink);\n\t}\n\n\n var i=0, rowEl=null,\n\t tableEl = document.createElement(\"table\");\n\t for (i=0; i < head.length; i++) {\n\t\trowEl = tableEl.insertRow(); // DOM method for creating table rows\n\t\trowEl.insertCell().innerHTML = \"<b>\" + head[i] + \"</b>\";\n\t\trowE2 = tableEl.insertRow();\n\t\tif (need_textbox.includes(head[i])) {\n\t\t\trowE2.insertCell().innerHTML= \"<textarea class='output' rows = '4' readonly = 'readonly'>\" + data[i] + \"</textarea>\";\n\t\t}\n\t\telse {\n\t\t\tif (head[i] == \"Orthologs\") {\n\t\t\t\trowE2.insertCell().innerHTML=data[i];\n\t\t\t}\n\t\t\telse{\n\t\t\t\trowE2.insertCell().innerHTML= \"<input class ='output' type='text' name='fname' readonly='readonly' value=\" + data[i] + \">\";\n\t\t\t}\n\t\t}\n\t }\n\tparent.document.getElementById('table_result').innerHTML = \"\";\n\tvar div = parent.document.getElementById('table_result')\n\tdiv.appendChild(tableEl)\n}",
"function displayNotes(note) {\n const { title, body, _id } = note;\n let displayBox = $(\"<div>\");\n displayBox.addClass(\"note-body\");\n let titleDisplay = $(\"<p>\");\n let bodyDisplay = $(\"<p>\");\n let deleteBtn = $(\"<button>\");\n let hr = $(\"<hr>\");\n deleteBtn.addClass(\"note-deleter\");\n deleteBtn.attr(\"id\", _id);\n titleDisplay.text(title || \"No Title\");\n bodyDisplay.text(body);\n deleteBtn.text(\"X\");\n displayBox.append(deleteBtn, titleDisplay, hr, bodyDisplay);\n return displayBox;\n }",
"function showTablePolicy(table, name, options, _) {\n var showPolicySettings = createTablePolicySetting(options);\n showPolicySettings.resourceName = interaction.promptIfNotGiven($('Table name: '), table, _);\n showPolicySettings.policyName = interaction.promptIfNotGiven($('Policy name: '), name, _);\n showPolicySettings.tips = util.format($('Showing the stored access policy %s on the table %s'), showPolicySettings.policyName, showPolicySettings.resourceName);\n\n var policy = StorageUtil.selectPolicy(showPolicySettings, _);\n cli.interaction.formatOutput(policy, function(outputData) {\n StorageUtil.showPolicyResults(outputData);\n });\n }",
"function showHighScoreTable(table) {\n // Show the table\n var node = document.getElementById(\"highscoretable\");\n console.log(node);\n node.style.setProperty(\"visibility\", \"visible\", null);\n\n // Get the high score text node\n var node = document.getElementById(\"highscoretext\");\n node.innerHTML = \"\";\n\n for (var i = 0; i < 10; i++) {\n // If i is more than the length of the high score table exit\n // from the for loop\n if (i >= table.length) break;\n\n // Add the record at the end of the text node\n addHighScore(table[i], node);\n }\n}",
"function showAccountTable() {\r\n actionTable.style.display = 'none';\r\n accountTable.style.display = 'table';\r\n back.style.display = 'inline-block';\r\n}",
"function printOneRecord(orderObject){\r\n deleteTbody();\r\n\r\n var tbody = document.getElementById(\"orders\");\r\n var row = tbody.insertRow(0);\r\n\r\n printCommon(orderObject,row,true);\r\n}",
"function printInfoVoucher(tableInfo, report, docNumber, date, totalPages) {\n\n //Title\n tableRow = tableInfo.addRow();\n tableRow.addCell(getValue(param, \"voucher\", \"chinese\"), \"heading1 alignCenter\", 11);\n\n tableRow = tableInfo.addRow();\n tableRow.addCell(getValue(param, \"voucher\", \"english\"), \"heading2 alignCenter\", 11);\n\n\n //Date and Voucher number\n var d = Banana.Converter.toDate(date);\n var year = d.getFullYear();\n var month = d.getMonth()+1;\n var day = d.getDate();\n\n tableRow = tableInfo.addRow();\n \n var cell1 = tableRow.addCell(getValue(param, \"page\", \"chinese\") + \" \" + currentPage + \" / \" + totalPages, \"\", 1);\n cell1.addParagraph(getValue(param, \"page\", \"english\"), \"\");\n\n var cell2 = tableRow.addCell(\"\", \"alignRight border-top-double\", 1);\n cell2.addParagraph(getValue(param, \"date\", \"chinese\") + \": \");\n\n var cell3 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell3.addParagraph(year, \"text-black\");\n\n var cell4 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell4.addParagraph(getValue(param, \"year\", \"chinese\"), \"\");\n cell4.addParagraph(getValue(param, \"year\", \"english\"), \"\");\n \n var cell5 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell5.addParagraph(month, \"text-black\");\n\n var cell6 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell6.addParagraph(getValue(param, \"month\", \"chinese\"), \"\");\n cell6.addParagraph(getValue(param, \"month\", \"english\"), \"\");\n\n var cell7 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell7.addParagraph(day, \"text-black\");\n\n var cell8 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell8.addParagraph(getValue(param, \"day\", \"chinese\"), \"\");\n cell8.addParagraph(getValue(param, \"day\", \"english\"), \"\");\n\n var cell9 = tableRow.addCell(\"\", \"\", 1); \n cell9.addParagraph(\" \", \"\");\n\n var cell10 = tableRow.addCell(\"\", \"padding-left alignCenter\", 1);\n cell10.addParagraph(getValue(param, \"voucherNumber\", \"chinese\"), \"\");\n cell10.addParagraph(getValue(param, \"voucherNumber\", \"english\"), \"\");\n \n var cell11 = tableRow.addCell(\"\", \"padding-left\", 1);\n cell11.addParagraph(\" \", \"\");\n cell11.addParagraph(docNumber, \"text-black\");\n\n report.addParagraph(\" \", \"\");\n}",
"function addTableRow(task) {\n\t\t//<button type=\"button\" class=\"btn btn-default\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Tooltip on bottom\">Tooltip on bottom</button>\t\n\t\tvar $row = '<tr data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"' \n\t\t\t+ task.details + '\"><td>'\n\t\t\t+ task.number\n\t\t\t\t+'</td><td>'+task.taskName\n\t\t\t\t+'</td><td>'+task.startDate\n\t\t\t\t+'</td><td>'+task.endDate\n\t\t\t\t+'</td><td><p><a href=\"#' \n\t\t\t\t+ task.number + \n\t\t\t\t'\" data-toggle=\"modal\" class=\"btn btn-primary\">expand</a></p></td>'\n\t\t\t+ '<td>' + generateBar(task) + '</td>'\n\t\t\t+ '</tr>';\n\t\t$('.table').append($row);\n\t}",
"function printTable(tableName, caption) {\r\n knex(tableName) // get rows from database\r\n .select()\r\n .then(function(rows) {\r\n console.log(caption + \":\");\r\n // map over the rows\r\n console.log();\r\n rows.map(function(row) {\r\n console.log(row);\r\n })\r\n console.log();\r\n console.log(\"============================\");\r\n console.log();\r\n })\r\n return;\r\n}",
"function WriteTextAreaControl(objname,IsControlRows){\r\n\t\tif( document.all(objname) ){\r\n\t\t\tif(IsControlRows){\r\n\t\t\t\tdocument.all(objname).rows=document.all(objname).value.split(\"\\n\").length+1;\r\n\t\t\t}\r\n\t\t\tdocument.write('<input onclick=\"RowsAdd(document.all(\\''+objname+'\\'));\" type=\"button\" value=\"+\"> <input onclick=\"RowsReduce(document.all(\\''+objname+'\\'));\" type=\"button\" value=\"-\">');\r\n\t\t}\r\n\t}",
"function show_task () {\n\tdocument.getElementById('inp-task').value='';\t\n\thtml = \"\";\n\thtml+= \"<table id='table-design'> <tr> <th>Sr-No </th> <th>Done/panding </th><th>Task-Name</th> <th>Edited Content</th><th>Action</th>\";\n\tfor (var i=0; i<arr_for_task.length; i++) {\n\thtml+=\"<tr> <td>\"+(i+1)+\"</td><td><input type='checkbox' id='doneorpanding(\"+i+\")' onclick='donePend(\"+i+\")'></td><td>\"+arr_for_task[i]+\"</td><td><input type='text' id='edit-content(\"+i+\")' class = 'edit-content'></td><td> <a href='#' onclick='delet(\"+i+\")'> DELETE</a> <a href='#'onclick='edit(\"+i+\")' id='edit'> EDIT</a> </td></tr>\";\n\t}\n\thtml+=\"</table>\";\n\tdocument.getElementById('entered_task').innerHTML = html;\n\tdiv_heading = \"\";\n\tdiv_heading+= \"<div id='head-design' class='head-design' style='padding: 10px;text-align: center;background-color: gray;font-size: 30px;color: white;'> The pending Task are showing Below -------!! </div>\";\n\tdocument.getElementById('head-design').innerHTML=div_heading ;\n}",
"function createStyledTable(){\r\n if (!validateMode()) return;\r\n\r\n if (cl!=null)\r\n { \r\n if (cl.tagName==\"TD\")\r\n obj = cl.parentElement.parentElement.parentElement;\r\n }else{\r\n elem=getEl(\"TABLE\",Composition.document.selection.createRange().parentElement());\r\n\tif(elem!=null) obj = elem;\r\n }\r\n \r\n if (!obj)\r\n {\r\n alert(\"Установите курсор в ячееку таблицы!\");\r\n\r\n }else{\r\n\tdtbl = showModalDialog(\"/images/mifors/ws/w_stable.htm\", tables,\"dialogWidth:250px; dialogHeight:200px; center:1; help:0; resizable:0; status:0\");\r\n\tif(dtbl==null) return;\r\n\tvar xsltTable = new ActiveXObject(\"Microsoft.XMLDOM\");\r\n\txsltTable.async = false;\r\n\txsltTable.load(dtbl);\r\n\tif (xsltTable.parseError.errorCode != 0) {\r\n\t var myErr = xsltTable.parseError;\r\n\t alert(\"You have error \" + myErr.reason);\r\n\treturn;\r\n\t} \r\n\tvar sxmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");\r\n\tsxmlDoc.async=false;\r\n\ttra=new String(obj.outerHTML);\r\n\tstate=0;\r\n\tout=\"\";\r\n\tfor(i=0;i<tra.length;i++){\r\n\t\tch=tra.charAt(i);\r\n\t\tswitch (state){\r\n\t\t\tcase 0:if(ch=='<') state=1; break;\r\n\t\t\tcase 1:if(ch=='>') state=0;\r\n\t\t\t\tif(ch=='=') state=2;break;\r\n\t\t\tcase 2:if(ch!='\"'){ out+='\"'; state=4} else state=3;break;\r\n\t\t\tcase 3:if(ch=='\"') state=1;break;\r\n\t\t\tcase 4:if(ch==' ') {out+='\"';state=1}\r\n\t\t\t\tif(ch=='>') {out+='\"';state=0};break\r\n\t\t}\r\n\t\tout+=ch;\r\n\t}\r\n\tsxmlDoc.loadXML(out);\r\n\tif (sxmlDoc.parseError.errorCode != 0) {\r\n\t var myErr = sxmlDoc.parseError;\r\n\t alert(\"You have error \" + myErr.reason);\r\n\treturn;\r\n\t} \r\n\treplacement=sxmlDoc.transformNode(xsltTable);\r\n\tobj.outerHTML=replacement;\r\n\tComposition.document.recalc();\r\n\tComposition.focus();\r\n }\r\n}",
"function showTestingInstructions(parentDocViewId)\r\n{\r\n\tvar url = \"view\";\r\n url += \"&parentDocViewId=\"+parentDocViewId;\r\n \t // Check for valid record to show the screen(tab).\r\n if(!isValidMaterialQuote(true))\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\tProcess.execute(url, \"testinginstructionsplm.do\");\r\n}",
"function popupTableau()\n{\n var popup = window.open('','name','height=400,width=500');\n \n javaCode = '<script type=\"text\\/javascript\">function insertCode(){';\n javaCode += 'var row = parseInt(document.paramForm.inputRow.value); '\n javaCode += 'var col = parseInt(document.paramForm.inputCol.value); '\n javaCode += 'var bord = parseInt(document.paramForm.inputBorder.value); '\n javaCode += 'var styleHeader = document.paramForm.inputHeader.checked; '\n javaCode += 'var styleLine = document.paramForm.inputLine.checked; '\n javaCode += 'window.opener.generateTableau(col,row,bord,styleHeader,styleLine); '\n javaCode += '}<\\/script>';\n \n popup.document.write('<html><head><title>表格參數</title>');\n popup.document.write('<script type=\"text\\/javascript\" src=\"\\/skins-1.5\\/common\\/wikibits.js\"><!-- wikibits js --><\\/script>');\n popup.document.write('<style type=\"text\\/css\" media=\"screen,projection\">/*<![CDATA[*/ @import \"\\/skins-1.5\\/monobook\\/main.css?5\"; /*]]>*/<\\/style>');\n popup.document.write(javaCode); \n popup.document.write('</head><body>');\n popup.document.write('<p>請輸入想要生成表格的參數:</p>');\n popup.document.write('<form name=\"paramForm\">');\n popup.document.write('行數:<input type=\"text\" name=\"inputRow\" value=\"3\" ><p>');\n popup.document.write('列數:<input type=\"text\" name=\"inputCol\" value=\"3\" ><p>');\n popup.document.write('邊框寬度:<input type=\"text\" name=\"inputBorder\" value=\"1\" ><p>');\n popup.document.write('灰色表頭:<input type=\"checkbox\" name=\"inputHeader\" checked=\"1\" ><p>');\n popup.document.write('灰色斑馬表:<input type=\"checkbox\" name=\"inputLine\" checked=\"1\" ><p>');\n popup.document.write('</form\">');\n popup.document.write('<p><a href=\"javascript:insertCode()\"> 將代碼插入到編輯窗口中</a></p>');\n popup.document.write('<p><a href=\"javascript:self.close()\"> 關閉</a></p>');\n popup.document.write('</body></html>');\n popup.document.close();\n}",
"function initTable(num){\n\n // Filter dataset by OTU id\n var filteredDate=dataset.metadata.filter(sample=>sample.id.toString()===num.toString())[0];\n\n\n // Create an list to store demographic information\n var valueList=Object.values(filteredDate);\n var valueKey=Object.keys(filteredDate);\n var demoInfo=[]\n for (var i=0;i<valueKey.length;i++){\n var element=`${valueKey[i]}: ${valueList[i]}`\n demoInfo.push(element);\n };\n\n // Add Demographic Information table in HTML\n var panel=d3.select(\"#sample-metadata\")\n var panelBody=panel.selectAll(\"p\")\n .data(demoInfo)\n .enter()\n .append(\"p\")\n .text(function(data){\n var number=data.split(\",\");\n return number;\n });\n \n }",
"function addTable(r, c) {\n var b = idoc.body || idoc.find('body')[0];\n $(b).html(table.html(r,c))\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
readonly attribute calIDateTime reminderSignalTime; | get reminderSignalTime()
{
return this._reminderSignalTime;
} | [
"get timeChecked()\r\n\t{\r\n\t\treturn this._timeChecked;\r\n\t}",
"get dateTimeReceived()\n\t{\n\t\treturn this._dateTimeReceived;\n\t}",
"_addDate() {\n const valueLink = this.props.valueLink;\n const value = valueLink.value || {};\n const slots = (value.slots || []).slice();\n const start = this.state.start.getTime();\n const end = start + this.state.duration;\n\n // Store the timeslot state as seconds, not ms\n slots.push([start / 1000, end / 1000]);\n\n value.slots = slots;\n valueLink.requestChange(value);\n }",
"get stampTime()\n\t{\n\t\t//dump(\"get stampTime: title:\"+this.title+\", value:\"+this._calEvent.stampTime);\n\t\treturn this._calEvent.stampTime;\n\t}",
"linkTime() {\n return {\n value: this.state.start.getTime(),\n requestChange: value => this.setState({start: new Date(Number(value))})\n };\n }",
"get reminderMinutesBeforeStart()\n\t{\n\t\treturn this._reminderMinutesBeforeStart;\n\t}",
"get reminderDueBy()\n\t{\n\t\treturn this._reminderDueBy;\n\t}",
"registerReminder() {\n const delayInMs = this.state.reminderDelay * 60000;\n\n navigator.serviceWorker.controller.postMessage({ message: this.state.reminderText, delay: delayInMs });\n\n // todo: get confirmation from sw before clearing vals\n this.setState({ reminderDelay: durations[0], reminderText: '' });\n }",
"get allowNewTimeProposal()\n\t{\n\t\treturn this._allowNewTimeProposal;\n\t}",
"get reminderIsSet()\n\t{\n\t\treturn this._reminderIsSet;\n\t}",
"function LogicNodeTime() {\n\tLogicNode.call(this);\n\tthis.wantsProcessCall = true;\n\tthis.logicInterface = LogicNodeTime.logicInterface;\n\tthis.type = 'LogicNodeTime';\n\tthis._time = 0;\n\tthis._running = true;\n}",
"get dateTimeSent()\n\t{\n\t\treturn this._dateTimeSent;\n\t}",
"setBakingTime() {}",
"calculate() {\n this.times.miliseconds += 1;\n if (this.times.miliseconds >= 100) {\n this.times.seconds += 1;\n this.times.miliseconds = 0;\n }\n if (this.times.seconds >= 60) {\n this.times.minutes += 1;\n this.times.seconds = 0;\n }\n }",
"getExtraTimeslotMinutes() {\n\t\treturn timeSlotMinutes;\n\t}",
"updateCurrentTime () {\n const now = new Date();\n this.hour = now.getHours();\n this.minute = now.getMinutes();\n this.second = now.getSeconds();\n }",
"updateTimeField(timeField) {\n const me = this;\n\n timeField.on({\n change({ userAction, value }) {\n if (userAction && !me.$settingValue) {\n const dateAndTime = me.dateField.value;\n me._isUserAction = true;\n me.value = dateAndTime ? DateHelper.copyTimeValues(dateAndTime, value) : null;\n me._isUserAction = false;\n }\n },\n thisObj : me\n });\n }",
"function cancelAlarm() {\n chrome.alarms.clear(alarmName);\n chrome.browserAction.setBadgeText({\n text: ''\n });\n chrome.notifications.create('reminder', {\n type: 'basic',\n iconUrl: 'img/icon_128.png',\n title: 'Info:',\n message: 'Die Erinnerungen sind jetzt deaktiviert!'\n }, function(notificationId) {});\n\n document.getElementById('delayInMinutes').value = '';\n }",
"pulse_midi_clock() {\n this.midi_clock.send([0xf8]);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is called by the render function and is called on each game tick. It's purpose is to then call the render functions you have defined on your enemy and player entities within app.js | function renderEntities() {
/* Loop through all of the objects within the allEnemies array and call
* the render function you have defined.
*/
allEnemies.forEach(function(enemy) {
enemy.render();
});
player.render();
} | [
"function render() {\n gameController.render();\n\n renderEntities();\n\n gameController.postRender();\n }",
"function render() {\n\t//clear all canvases for a fresh render\n\tclearScreen();\n\t\n\t//draw objects centered in order\n\tfor (let i = 0; i < objects.length; ++i) {\n\t\tdrawCentered(objects[i].imgName,ctx, objects[i].x, objects[i].y,objects[i].dir);\n\t}\n\t\n\t//finally draw the HUD\n\tdrawHUD();\n}",
"function renderObject(){\n renderMonster();\n renderHearts();\n}",
"function render() {\n\n // This array holds the relative URL to the image used\n // for that particular row of the game level.\n var rowImages = [\n 'images/water-block.png', // Top row is water\n 'images/stone-block.png', // Row 1 of 3 of stone\n 'images/stone-block.png', // Row 2 of 3 of stone\n 'images/stone-block.png', // Row 3 of 3 of stone\n 'images/grass-block.png', // Row 1 of 2 of grass\n 'images/grass-block.png' // Row 2 of 2 of grass\n ],\n numRows = 6,\n numCols = 5,\n row, col;\n\n // Loop through the number of rows and columns we've defined above\n // and, using the rowImages array, draw the correct image for that\n // portion of the \"grid\"\n for (row = 0; row < numRows; row++) {\n for (col = 0; col < numCols; col++) {\n /* The drawImage function of the canvas' context element\n * requires 3 parameters: the image to draw, the x coordinate\n * to start drawing and the y coordinate to start drawing.\n * We're using our Resources helpers to refer to our images\n * so that we get the benefits of caching these images, since\n * we're using them over and over.\n */\n ctx.drawImage(Resources.get(rowImages[row]), col * 101, row * 83);\n }\n }\n\n renderEntities();\n\n scoreBoard();\n }",
"function drawEntities() {\n for (let i = 0; i < entities.length; i++) {\n push();\n const entity = entities[i];\n if(entity.position) {\n translate(entity.position.x - camera.x, entity.position.y - camera.y);\n }\n\n if(entity.rotate) {\n rotate(entity.rotate);\n }\n\n if(entity.size && entity.img) {\n image(entity.img, 0, 0);\n } else if (entity.size && entity.color) {\n fill(entity.color);\n rect(\n 0,\n 0,\n entity.size.w,\n entity.size.h,\n );\n } \n pop();\n }\n}",
"function render() {\n\tcontext.clear();\n\n\n\trenderMaze();\n\trenderCharacter(myCharacter);\n\trenderTime();\n\trenderCurrentScore();\n\trenderHighScores();\n}",
"function draw() {\n\n // Cases to handle Game over.\n if (player.dead) {\n Game.over = true;\n staticTexture.gameOver(player.dead);\n }\n else if (enemy.dead) {\n Game.over = true;\n staticTexture.gameOver(player.dead);\n }\n \n // check for player commands\n playerAction();\n\n // Multiple IF to check if it is players turn or Enemy, also if Projectile exist or not.\n if (Game.projectile != null) {\n Game.projectile.draw();\n }\n if (Game.playerTurn == true && Game.projectile != null) {\n if (Game.checkCollision(Game.projectile, enemy)) {\n Game.hit(enemy)\n Game.playerTurn = false;\n }\n }\n if (Game.playerTurn == false) {\n enemy.enemyTurn(player);\n if (Game.checkCollision(Game.projectile, player)) {\n Game.hit(player)\n Game.playerTurn = true;\n }\n }\n if (Game.projectile != null && !Game.checkCollision(Game.projectile, game) && player.firearm == 0) {\n Game.miss();\n }\n for (var i = 0; i < Game.map.length; i++) {\n if (Game.checkCollision(Game.projectile, Game.map[i])) {\n Game.projectile.clear();\n \n staticTexture.clear(Game.map[i])\n Game.map[i] = null;\n Game.miss();\n\n }\n }\n player.draw();\n enemy.draw();\n // If game over, stop callback.\n if (Game.over == false) {\n window.requestAnimationFrame(draw);\n }\n }",
"function boss2_render() {\n simpleEnemy_render.call(this);\n //Issue 66: Rendering the walls.\n if(this.previous === null){\n context.fillRect(0,250,330,350);\n context.fillRect(560,250,240,350);\n }\n}",
"function renderScreen() {\n ship.render()\n for (var rock in rocks.rockList) {\n rocks.rockList[rock].render()\n }\n for (var bullet in bullets.bulletList) {\n bullets.bulletList[bullet].update(screen.width, screen.height);\n bullets.bulletList[bullet].render()\n }\n}",
"onRender() {}",
"render(){\n\t\tif (this.active)\n\t\t{\n\t\t\trequestAnimationFrame(this.render.bind(this));\n\t\t\tif (this.checkFrameInterval())\n\t\t\t{\n\t\t\t\tthis.frameInfo.then = this.frameInfo.now - (this.frameInfo.elapsed % this.frameInfo.fpsInterval);\n\t\t\t\tthis.clearScreen();\n\t\t\t\tthis.draw();\n\t\t\t}\n\t\t}\n\t}",
"draw() {\r\n this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height);\r\n this._ctx.save();\r\n for (let i = 0; i < this._entities.length; i++) {\r\n this._entities[i].draw(this._ctx);\r\n }\r\n this._ctx.restore();\r\n }",
"draw(context) {\n this.fire(\"predraw\", this);\n for (let p of this._particles) {\n p.draw(context);\n }\n this.fire(\"draw\", this);\n }",
"load() {\n log.debug('Entities - load()', this.game.renderer);\n this.game.app.sendStatus('Lots of monsters ahead...');\n\n if (!this.sprites) {\n log.debug('Entities - load() - no sprites loaded yet', this.game.renderer);\n this.sprites = new Sprites(this.game.renderer);\n\n this.sprites.onLoadedSprites(() => {\n log.debug('Entities - load() - sprites done loading, loading cursors');\n this.game.input.loadCursors();\n this.game.postLoad();\n this.game.start();\n });\n }\n\n this.game.app.sendStatus('Yes, you are also a monster...');\n\n if (!this.grids) {\n log.debug('Entities - load() - no grids loaded yet');\n this.grids = new Grids(this.game.map);\n }\n }",
"render() {\n // Render as usual\n super.render();\n\n // render depth map as texture to quad for testing\n // this.renderDepthMapQuad();\n }",
"function render() {\r\n \"use strict\";\r\n\r\n // position objects on the screen\r\n rocket.img.style.left = rocket.x + \"px\";\r\n rocket.img.style.top = rocket.y + \"px\";\r\n\r\n\r\n if (bUfoExplode) {\r\n ufo.img.src = \"images/ExplodeMaybe.png\";\r\n\r\n if (!bExplosionAudio) {\r\n // if we have yet to sound the explosion, do so now.\r\n\r\n /* Again. defaulting to html audio on the page version since I can't get\r\n * the on the fly version to play both .mp3 or .ogg as needed.\r\n * \r\n // set up audio\r\n let myAudio = document.createElement(\"audio\");\r\n myAudio.src = EXPLODE;\r\n */\r\n let myAudio = document.querySelector(\"#ExplosionSound\");\r\n myAudio.currentTime = 0; // sets it to start at beginning of sound track.\r\n console.log(\"src = \" + myAudio.src);\r\n myAudio.volume = 0.5;\r\n myAudio.play();\r\n\r\n bExplosionAudio = true;\r\n }// end if need to sound explosion\r\n\r\n }// end if ufoExplode\r\n\r\n ufo.img.style.top = ufo.y + \"px\";\r\n ufo.img.style.left = ufo.x + \"px\";\r\n ufo.img.style.visibility = \"visible\"; // make sure the ufo shows up or explodes.\r\n\r\n // if not in fireing loop, set torpedo start and actual positions to the ships launch tube.\r\n if (!bTorpFired) {\r\n torpedo.y = (rocket.y + 8);\r\n torpedo.x = (rocket.x + 10);\r\n torpedo.startX = torpedo.x;\r\n torpedo.startY = torpedo.y;\r\n\r\n torpedo.img.style.left = (rocket.x + 10) + \"px\";\r\n torpedo.img.style.top = (rocket.y + 8) + \"px\";\r\n torpedo.img.style.visibility = \"hidden\";\r\n }// end if not in fire torp sequence\r\n\r\n if (bGameEnded) {\r\n // end of game, let player know\r\n clearInterval(timeCheck); // clear timer\r\n rocket.img.style.visibility = \"hidden\"; // hide rocket\r\n ufo.img.style.visibility = \"hidden\"; // hide ufo\r\n FIRE_BTN.disabled = true; // hide and disable fire button\r\n FIRE_BTN.hidden = true;\r\n\r\n document.getElementById(\"endGame\").innerHTML = \"Great Shot! You Got it!\";\r\n document.getElementById(\"GameOver\").innerHTML = \" Game Over!\";\r\n }\r\n\r\n\r\n}// end render",
"updateAndRender(){\n if (this.scene) {\n this.calculateSquareLayout();\n this.updateSquares();\n this.updateYPos();\n this.updateTexture();\n this.updateUniforms();\n this.scene.render();\n }\n }",
"function EngineCore(){\n this.State = new EngineState();\n this.TimeKeeper = new TimeKeeper();\n this.Matrices = {};\n this.MatStack = new Stack();\n this.Shaders = {};\n this.Objects = {};\n this.Textures = {};\n this.ShaderVars = {};\n this.Fonts = {};\n this.Extensions = {};\n this.World = {};\n this.Cameras = [];\n this.AnimPlayer = new AnimPlayer();\n //==============================================================================\n //Initializes the Graphics Engine\n //==============================================================================\n this.init = function(){\n canvas = document.getElementById('WebGL', {antialias:true});\n try{\n gl = canvas.getContext(\"experimental-webgl\");\n //Extensions====================================================================\n this.Extensions.aniso = gl.getExtension(\"EXT_texture_filter_anisotropic\");\n //==============================================================================\n //Event Listeners here==========================================================\n document.addEventListener(\"visibilitychange\", Engine.pause, false);\n //==============================================================================\n this.LoadShaders(['Unlit', 'Lit']);\n this.LoadMeshData(['Monkey']);\n this.LoadExtraTex(['CalibriWhite', 'VerdanaWhite']);\n Engine.Fonts['Calibri'] = new fontInfo('Calibri');\n Engine.Fonts['Verdana'] = new fontInfo('Verdana');\n this.Cameras.push(new Camera(this.Cameras.length));\n this.Cameras[0].transform.position = vec3.fromValues(0,0,3);\n this.Matrices.ModelMatrix = mat4.create();\n this.Matrices.NormalMatrix = mat4.create();\n this.Matrices.MVPMatrix = mat4.create();\n this.Matrices.TempMatrix = mat4.create();\n gl.clearColor(0.3,0.3,0.3,1);\n gl.enable(gl.CULL_FACE);\n gl.enable(gl.DEPTH_TEST);\n this.State.initialized = true;\n doneLoading();\n }\n catch(e){\n canvas.style.display = 'none';\n doneLoading();\n }\n }\n //==============================================================================\n //Draws current frame on canvas\n //Avoid all 'this' references, as this function is part of update which uses callbacks\n //==============================================================================\n this.renderFrame = function(){\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n //Reset matrices\n mat4.identity(Engine.Matrices.ModelMatrix);\n //Set view to current active camera\n Engine.Cameras[Engine.State.ActiveCamera].setView();\n //Push default matrices to top of stack\n Engine.MatStack.push(Engine.Matrices.ModelMatrix);\n Engine.MatStack.push(Engine.Matrices.MVPMatrix);\n\n for (var obj in Engine.World){\n if(Engine.World.hasOwnProperty(obj) && Engine.Shaders[Engine.World[obj].Shader].compiled!=false && Engine.World[obj].initialized){\n //Pop fresh model and mvp Matrices\n Engine.Matrices.MVPMatrix = Engine.MatStack.pop();\n Engine.Matrices.ModelMatrix = Engine.MatStack.pop();\n Engine.MatStack.push(Engine.Matrices.ModelMatrix);\n Engine.MatStack.push(Engine.Matrices.MVPMatrix);\n //Create an alias for the current object\n var obj = Engine.World[obj];\n //Set shader for current object\n gl.useProgram(Engine.Shaders[obj.Shader].Program);\n //Perform per object transformations here\n Engine.evalTransform(obj);\n //Apply perspective distortion\n mat4.multiply(Engine.Matrices.MVPMatrix, Engine.Matrices.MVPMatrix, Engine.Matrices.ModelMatrix);\n //Bind attributes\n gl.bindBuffer(gl.ARRAY_BUFFER, obj.Buffer.position);\n gl.vertexAttribPointer(Engine.Shaders[obj.Shader].Attributes.a_Position, 3, gl.FLOAT, false, 0, 0);\n gl.bindBuffer(gl.ARRAY_BUFFER, obj.Buffer.uv);\n gl.vertexAttribPointer(Engine.Shaders[obj.Shader].Attributes.a_UV, 2, gl.FLOAT, false, 0, 0);\n if(Engine.Shaders[obj.Shader].Attributes.a_Normal >= 0){\n gl.bindBuffer(gl.ARRAY_BUFFER, obj.Buffer.normal);\n gl.vertexAttribPointer(Engine.Shaders[obj.Shader].Attributes.a_Normal, 3, gl.FLOAT, false, 0, 0);\n }\n //Call draw\n obj.draw();\n }}\n }\n //==============================================================================\n //Primary render loop\n //Avoid all 'this' references, as this function uses a callback\n //==============================================================================\n var inter = window.performance.now();\n this.Update = function(){\n var begin = window.performance.now();\n inter = window.performance.now() - inter;\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n //Call any runtime logic here\n frame = requestAnimationFrame(Engine.Update, canvas);\n Engine.renderFrame();\n Engine.TimeKeeper.update();\n Engine.AnimPlayer.update();\n Engine.TimeKeeper.frameTime = (window.performance.now()-begin).toFixed(2);\n Engine.TimeKeeper.interFrameTime = inter.toFixed(2);\n inter = window.performance.now();\n }\n //==============================================================================\n //Download And Compile Shader Code From Server.\n //Shaders must use the (shaderName)_(f/v).glsl naming convention\n //==============================================================================\n this.LoadShaders = function(ShaderNames){\n console.group(\"Shader Loading\");\n ShaderNames.forEach(function(element){\n console.log(\"Requesting Shader: \"+element);\n this.Shaders[element] = new Shader(element);\n }, this);\n console.groupEnd();\n }\n //==============================================================================\n //Download and bind mesh data from server\n //==============================================================================\n this.LoadMeshData = function(MeshNames){\n console.group(\"Mesh Loading\");\n MeshNames.forEach(function(element){\n console.groupCollapsed(\"Mesh: \"+element);\n this.Objects[element] = new Mesh(element);\n this.Objects[element].load();\n console.groupEnd();\n }, this);\n console.groupEnd();\n }\n //==============================================================================\n //Dowload and bind extra textures form server\n //==============================================================================\n this.LoadExtraTex = function(TexNames){\n TexNames.forEach(function(element){\n LoadTex((\"Resources/Textures/\"+element+\".png\"), element, Engine);\n }, this);\n }\n //==============================================================================\n //Pause the engine when window has lost focus\n //==============================================================================\n this.pause = function(){\n if(document.hidden){\n cancelAnimationFrame(frame);\n }\n else{\n Engine.TimeKeeper.lastFrame = window.performance.now();\n requestAnimationFrame(Engine.Update, canvas);\n }\n }\n //==============================================================================\n //Take an object and instance it into the world\n //==============================================================================\n this.Instantiate = function(obj, trans = null){\n var instanceName = (obj.tag)+'.'+((obj.numinstances)++).toString();\n obj.instances.push(instanceName);\n this.World[instanceName] = this.Duplicate(obj, instanceName, trans);\n return instanceName;\n }\n //==============================================================================\n //Duplicate an object. Return duplicate.\n //==============================================================================\n this.Duplicate = function(obj, name, trans){\n var newObj = new Mesh(name);\n newObj.Buffer = obj.Buffer;\n newObj.Textures = obj.Textures;\n if(trans != undefined){newObj.transform.copy(trans);}\n else{newObj.transform.copy(obj.transform);}\n newObj.Shader = obj.Shader;\n newObj.initialized = obj.initialized;\n return newObj;\n }\n //==============================================================================\n //recursive function to evaluate an object's tranform based on its parent\n //==============================================================================\n this.evalTransform = function(obj){\n if(obj.parent != null){\n this.evalTransform(obj.parent);\n }\n obj.transform.applyParent(Engine.Matrices.ModelMatrix);\n obj.transform.apply(Engine.Matrices.ModelMatrix);\n }\n}",
"function weapon_draw(player_obj, wep, render_batch) {\n\tif (wep.actioning == true) {\n\t\t/*ctx.drawImage(\n\t\t\tweapon_sheet, \n\t\t\twep.animations[player_obj.data.dir][wep.atkIndex].x, wep.animations[player_obj.data.dir][wep.atkIndex].y, \n\t\t\twep.animations[player_obj.data.dir][wep.atkIndex].w, wep.animations[player_obj.data.dir][wep.atkIndex].h,\n\t\t\tplayer_obj.data.x-12, player_obj.data.y-16, \n\t\t\twep.animations[player_obj.data.dir][wep.atkIndex].w, wep.animations[player_obj.data.dir][wep.atkIndex].h\n\t\t);*/\n\t\trender_batch.batch.push({\n\t\t\taction: 1,\n\t\t\tsheet: weapon_sheet, \n\t\t\tsheet_x: wep.animations[player_obj.data.dir][wep.atkIndex].x,\n\t\t\tsheet_y: wep.animations[player_obj.data.dir][wep.atkIndex].y, \n\t\t\tsheet_w: wep.animations[player_obj.data.dir][wep.atkIndex].w, \n\t\t\tsheet_h: wep.animations[player_obj.data.dir][wep.atkIndex].h,\n\t\t\tx: player_obj.data.x-12,\n\t\t\ty: player_obj.data.y-16, \n\t\t\tw: wep.animations[player_obj.data.dir][wep.atkIndex].w,\n\t\t\th: wep.animations[player_obj.data.dir][wep.atkIndex].h\n\t\t\t});\n\t}\n\t\n\tif (wep.buffs.indexOf(\"electric\") > -1) {\n\t\tfor (var i=0; i<wep.target_tiles.length; i++) {\n\t\t\tlightning_tile_draw(wep.target_tiles[i]);\n\t\t}\n\t}\n\t\n\tif (show_hitboxes == true) {\n\t\trender_queue.push({\n\t\t\taction: 2, \n\t\t\tcolor: \"red\", \n\t\t\tx: player_obj.data.x+wep.hitbox[player_obj.data.dir][wep.atkIndex].x, \n\t\t\ty: player_obj.data.y+wep.hitbox[player_obj.data.dir][wep.atkIndex].y, \n\t\t\tw: 1, \n\t\t\th: 1\n\t\t});\n\t\trender_queue.push({\n\t\t\taction: 2, \n\t\t\tcolor: \"red\", \n\t\t\tx: player_obj.data.x+wep.hitbox[player_obj.data.dir][wep.atkIndex].x+wep.hitbox[player_obj.data.dir][wep.atkIndex].w, \n\t\t\ty: player_obj.data.y+wep.hitbox[player_obj.data.dir][wep.atkIndex].y, \n\t\t\tw: 1, \n\t\t\th: 1\n\t\t});\n\t\trender_queue.push({\n\t\t\taction: 2, \n\t\t\tcolor: \"red\", \n\t\t\tx: player_obj.data.x+wep.hitbox[player_obj.data.dir][wep.atkIndex].x, \n\t\t\ty: player_obj.data.y+wep.hitbox[player_obj.data.dir][wep.atkIndex].y+wep.hitbox[player_obj.data.dir][wep.atkIndex].h, \n\t\t\tw: 1, \n\t\t\th: 1\n\t\t});\n\t\trender_queue.push({\n\t\t\taction: 2, \n\t\t\tcolor: \"red\", \n\t\t\tx: player_obj.data.x+wep.hitbox[player_obj.data.dir][wep.atkIndex].x+wep.hitbox[player_obj.data.dir][wep.atkIndex].w, \n\t\t\ty: player_obj.data.y+wep.hitbox[player_obj.data.dir][wep.atkIndex].y+wep.hitbox[player_obj.data.dir][wep.atkIndex].h, \n\t\t\tw: 1, \n\t\t\th: 1\n\t\t});\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if there is a live service through ChOP | async function isServiceLive() {
// Fetch the current or next service data
const service = await fetch("https://northlandchurch.online.church/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify({
query: CURRENT_SERVICE_QUERY,
operationName: "CurrentService"
})
})
.then((response) => response.json())
.catch((error) => console.error(error));
// If no service was returned from the API, don't display the countdown
if (!service.data.currentService || !service.data.currentService.id) {
return;
}
// Set the date we're counting down to
const startTime = new Date(service.data.currentService.startTime).getTime();
const endTime = new Date(service.data.currentService.endTime).getTime();
// Create a one second interval to tick down to the startTime
const intervalId = setInterval(function () {
const now = new Date().getTime();
// If we are between the start and end time, the service is live
if (now >= startTime && now <= endTime) {
clearInterval(intervalId);
$(".worship-is-live-text").show();
$('#alert-banner').hide();
return;
}
// Find the difference between now and the start time
const difference = startTime - now;
// Time calculations for days, hours, minutes and seconds
const days = Math.floor(difference / (1000 * 60 * 60 * 24));
const hours = Math.floor(
(difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((difference % (1000 * 60)) / 1000);
// If we are past the end time, clear the countdown
if (difference < 0) {
clearInterval(intervalId);
return;
}
}, 1000);
} | [
"isService() {\n\n return this.type == 'service';\n }",
"function IsServiceRunning(/**string*/ name) /**boolean*/\n{\n\tvar strComputer = \".\";\n\tvar SWBemlocator = new ActiveXObject(\"WbemScripting.SWbemLocator\");\n\tvar objCtx = new ActiveXObject(\"WbemScripting.SWbemNamedValueSet\")\n\tobjCtx.Add(\"__ProviderArchitecture\", 64); \n\tvar objWMIService = SWBemlocator.ConnectServer(strComputer, \"/root/CIMV2\", \"\", \"\", null, null, null, objCtx);\n\t\n\tvar query = \"Select * from Win32_Service\";\n\tif(name)\n\t{\n\t\tquery += \" WHERE Name='\" + name + \"'\";\n\t}\n\tvar colItems = objWMIService.ExecQuery(query);\n\t\n\tvar e = new Enumerator(colItems);\n\tfor(; ! e.atEnd(); e.moveNext())\n\t{\n\t\tLog(e.item().Name + \":\" + e.item().State);\n\t\tif (name) \n\t\t{\n\t\t\tif (e.item().State.toLowerCase() == \"running\")\n\t\t\t{\n\t\t\t\treturn true;\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (name) return false;\n}",
"IsRemoteConfigured() {\n\n }",
"function killServiceWasCalled() {\n return plugin.service === undefined;\n }",
"deviceStatusLive(device) {\n\t\t\tconst difference = this.getTimeDifference(device.updated_at);\n\n\t\t\treturn (difference <= 15);\n\t\t}",
"ifOnline() {\n return new Promise((resolve, reject) => {\n if (this._online) {\n resolve(true);\n }\n });\n }",
"isOnline() {\n return this.worldManager && this.worldManager.isOnline();\n }",
"function procExists(host) {\n return typeof getProc(host) != 'undefined'\n}",
"isOffline () {\n return this.isDown;\n }",
"function CheckActiveXAlive()\n{\n var res = true;\n var obj = GE(AxID);\n if (obj != null)\n {\n try\n {\n //if (obj.IsAlive == 0)\n {\n res = false;\n }\n }\n catch (e)\n {}\n }\n return res;\n}",
"get isSetup() {\n return this.system.hasInstance(this);\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 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 }",
"function isActive() {\n return socket && socket.readyState == WebSocket.OPEN;\n }",
"get isListening() {\n return this.listeners.length > 0;\n }",
"registeredOf(ws) {\n return this.ws === ws;\n }",
"isLocalOnHold() {\n if (this.state !== CallState.Connected) return false;\n if (this.unholdingRemote) return false;\n let callOnHold = true; // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n\n for (const tranceiver of this.peerConn.getTransceivers()) {\n const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }",
"function makeSureDiscoveryServiceIsConnected() {\n return getPairingCode().then((discoveryServicePairingCode) => {\n console.log(`GOT PAIRING CODE: ${discoveryServicePairingCode}`);\n return checkOrPairDevice(discoveryServicePairingCode);\n }).then((correspondent) => {\n const discoveryServiceDeviceAddress = correspondent.device_address;\n\n if (!discoveryServiceAddresses.includes(discoveryServiceDeviceAddress)) {\n discoveryServiceAddresses.push(discoveryServiceDeviceAddress);\n }\n\n if (discoveryServiceAvailabilityCheckingPromise !== null) {\n console.log('ALREADY WAITING FOR THE DISCOVERY SERVICE TO REPLY');\n return discoveryServiceAvailabilityCheckingPromise;\n }\n\n const promise = new Promise((resolve) => {\n const listener = function (message, fromAddress) {\n if (fromAddress === discoveryServiceDeviceAddress) {\n console.log(`THE DISCOVERY SERVICE (${discoveryServiceDeviceAddress}) IS ALIVE`);\n eventBus.removeListener('dagcoin.connected', listener);\n resolve(correspondent);\n }\n };\n\n eventBus.on('dagcoin.connected', listener);\n });\n\n const keepAlive = {\n protocol: 'dagcoin',\n title: 'is-connected'\n };\n\n sendMessageToDevice(discoveryServiceDeviceAddress, 'text', JSON.stringify(keepAlive));\n\n const attempts = 12;\n\n const timeoutMessage = `THE DISCOVERY SERVICE ${discoveryServiceDeviceAddress} DID NOT REPLY AFTER 10 SECONDS`;\n const finalTimeoutMessage = `THE DISCOVERY SERVICE DID NOT REPLY AFTER ${attempts} ATTEMPS`;\n\n const timeoutMessages = { timeoutMessage, finalTimeoutMessage };\n\n discoveryServiceAvailabilityCheckingPromise = promiseService.repeatedTimedPromise(promise, 10000, attempts, timeoutMessages);\n\n // After ten minutes will be needed to make sure the discovery service is connected\n setTimeout(() => {\n discoveryServiceAvailabilityCheckingPromise = null;\n }, 10 * 60 * 1000);\n\n return discoveryServiceAvailabilityCheckingPromise;\n });\n }",
"function pingFromPlant(){\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine the mode for the text editor based on the file extension | function editorMode(name) {
var mode = "xml";
if (extname(name) === ".js") mode = "javascript";
if (extname(name) === ".json") mode = "javascript";
if (extname(name) === ".css") mode = "css";
if (extname(name) === ".txt") mode = "text";
return mode;
} | [
"function txtExtension(fileName) {\n var c = fileName.indexOf(\".\");\n var w = fileName.substring(c + 1, fileName.length);\n if (w != \"txt\") return false;\n return true;\n}",
"function changeMode(){\n\tvar new_mode = $('#mode').val();\n\tedit_session.setMode(\"ace/mode/\"+new_mode);\n}",
"function getModeTitle(){\n if(mode.current == mode.edit) return \"Editing\";\n else if(mode.current == mode.run) return `Round ${round}`;\n else return \"Unknown Mode\";\n}",
"GetCompatibleWithEditor() {}",
"function setTypingMode(_mode) {\n const mode = _mode.toLowerCase();\n\n switch (mode) {\n case \"words (fixed amount)\":\n // Update ui\n document.querySelector(\"#coding-area\").style.display = \"none\";\n document.querySelector(\"#time-count\").style.display = \"none\";\n document.querySelector(\"#language-selected\").style.display = \"none\";\n document.querySelector(\"#typing-area\").style.display = \"inline\";\n document.querySelector(\"#word-count\").style.display = \"inline\";\n\n // Start typing test\n setText();\n showText();\n\n break;\n\n case \"words (against the clock)\":\n // Update ui\n document.querySelector(\"#coding-area\").style.display = \"none\";\n document.querySelector(\"#word-count\").style.display = \"none\";\n document.querySelector(\"#language-selected\").style.display = \"none\";\n document.querySelector(\"#typing-area\").style.display = \"inline\";\n document.querySelector(\"#time-count\").style.display = \"inline\";\n\n // Start typing test\n setText();\n showText();\n\n break;\n\n case \"code snippets\":\n // Update ui\n document.querySelector(\"#typing-area\").style.display = \"none\";\n document.querySelector(\"#word-count\").style.display = \"none\";\n document.querySelector(\"#time-count\").style.display = \"none\";\n document.querySelector(\"#coding-area\").style.display = \"inline\";\n document.querySelector(\"#language-selected\").style.display = \"inline\";\n\n // Start typing test\n setCodeText();\n showCodeText();\n\n break;\n\n default:\n console.error(`Mode ${mode} is undefined`);\n }\n }",
"function isExtension(file, textFile) {\n\n let ext = grabExt(file);\n\n switch (ext.toLowerCase()) {\n case 'html':\n cleanUpHTML(file, textFile);\n break;\n case 'js':\n cleanUpJS(file, textFile);\n break;\n case 'css':\n cleanUpCSS(file, textFile);\n break;\n }\n}",
"function setMode(mode){\n\t\tif(mode !== undefined){\n\t\t\tcm.setOption('mode', mode);\n\t\t\tCodeMirror.autoLoadMode(cm, mode);\n\t\t\t/*var script = 'lib/codemirror/mode/'+mode+'/'+mode+'.js';\n\n\t\t\t$.getScript(script, function(data, success) {\n\t\t\t\tif(success) cm.setOption('mode', mode);\n\t\t\t\telse cm.setOption('mode', 'clike');\n\t\t\t});*/\n\t\t}else{\n\t\t\tcm.setOption('mode', 'clike');\n\t\t}\n\t}",
"async edit(path) {\n\t\tunit.action(\"edit\", path);\n\n\t\tconst extinfo = fs.extinfo(fs.ext(path));\n\n\t\tif (extinfo && extinfo.editor) {\n\t\t\treturn await Application.load(extinfo.editor, path);\n\t\t} else {\n\t\t\treturn await Application.load(fs.extinfo(\"*\").editor, path);\n\t\t}\n\t}",
"isEditor(value) {\n if (!isPlainObject(value)) return false;\n var cachedIsEditor = IS_EDITOR_CACHE.get(value);\n\n if (cachedIsEditor !== undefined) {\n return cachedIsEditor;\n }\n\n var isEditor = typeof value.addMark === 'function' && typeof value.apply === 'function' && typeof value.deleteBackward === 'function' && typeof value.deleteForward === 'function' && typeof value.deleteFragment === 'function' && typeof value.insertBreak === 'function' && typeof value.insertFragment === 'function' && typeof value.insertNode === 'function' && typeof value.insertText === 'function' && typeof value.isInline === 'function' && typeof value.isVoid === 'function' && typeof value.normalizeNode === 'function' && typeof value.onChange === 'function' && typeof value.removeMark === 'function' && (value.marks === null || isPlainObject(value.marks)) && (value.selection === null || Range.isRange(value.selection)) && Node$1.isNodeList(value.children) && Operation.isOperationList(value.operations);\n IS_EDITOR_CACHE.set(value, isEditor);\n return isEditor;\n }",
"switchToWYSIWYG() {\n this.$containerEl.removeClass('te-md-mode');\n this.$containerEl.addClass('te-ww-mode');\n }",
"get onDidChangeActiveTextEditor() {\n return vscode.window.onDidChangeActiveTextEditor;\n }",
"function switch_editor_mode(editorid)\n{\n\tif (AJAX_Compatible)\n\t{\n\t\tvar mode = (vB_Editor[editorid].wysiwyg_mode ? 0 : 1);\n\n\t\tif (vB_Editor[editorid].influx == 1)\n\t\t{\n\t\t\t// already clicked, go away!\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvB_Editor[editorid].influx = 1;\n\t\t}\n\n\t\tif (typeof vBmenu != 'undefined')\n\t\t{\n\t\t\tvBmenu.hide();\n\t\t}\n\n\t\tYAHOO.util.Connect.asyncRequest(\"POST\", 'ajax.php?do=editorswitch', {\n\t\t\tsuccess: do_switch_editor_mode,\n\t\t\ttimeout: vB_Default_Timeout,\n\t\t\targument: [editorid, mode]\n\t\t//\tscope: this\n\t\t}, SESSIONURL\n\t\t\t+ 'securitytoken=' + SECURITYTOKEN\n\t\t\t+ '&do=editorswitch'\n\t\t\t+ '&towysiwyg='\t+ mode\n\t\t\t+ '&parsetype=' + vB_Editor[editorid].parsetype\n\t\t\t+ '&allowsmilie=' + vB_Editor[editorid].parsesmilies\n\t\t\t+ '&message=' + PHP.urlencode(vB_Editor[editorid].get_editor_contents())\n\t\t\t+ (vB_Editor[editorid].ajax_extra ? ('&' + vB_Editor[editorid].ajax_extra) : '')\n\t\t\t+ (typeof vB_Editor[editorid].textobj.form['options[allowbbcode]'] != 'undefined' ? '&allowbbcode=' + vB_Editor[editorid].textobj.form['options[allowbbcode]'].checked : '')\n\t\t);\n\t}\n}",
"function init_wysiwyg_mode(cell) {\n // Check for error states\n if (cell.cell_type !== \"markdown\") console.log(\"ERROR: init_wysiwyg_mode() called on non-text cell: \" + cell.cell_type);\n if (!cell.rendered) cell.render();\n\n // Get the DOM elements\n var textbox = cell.element.find(\".text_cell_render\");\n\n // Special case to remove anchor links before editing\n textbox.find(\".anchor-link\").remove();\n\n // Special case for placeholder text in empty cells\n if (cell.get_text().length === 0) textbox.empty();\n\n // Initialize CKEditor\n var editor = CKEDITOR.replace(textbox[0], {\n height: 250,\n allowedContent: true,\n contentsCss: [CKEDITOR.basePath + 'contents.css', location.origin + Jupyter.contents.base_url + '/static/style/style.min.css'],\n extraPlugins: 'divarea',\n removePlugins: \"magicline\",\n toolbarGroups: [\n { name: 'styles', groups: [ 'styles' ] },\n { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },\n { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },\n { name: 'links', groups: [ 'links' ] },\n { name: 'insert', groups: [ 'insert' ] }\n ]\n });\n\n // Editor settings\n editor.on('instanceReady', function( ev ) {\n editor.setReadOnly(false);\n });\n\n // Attach editor to cell\n cell.element.data(\"editor\", editor);\n\n // Editor keyboard events\n editor.on('focus', function( ev ) {\n Jupyter.notebook.keyboard_manager.disable();\n $(\".cke_top\").show();\n });\n editor.on('blur', function( ev ) {\n Jupyter.notebook.keyboard_manager.enable();\n });\n cell.element.find(\".inner_cell\").dblclick(function(event) {\n is_wysiwyg_mode(cell) ? event.stopPropagation() : {};\n });\n\n // Save editor changes to model\n editor.on('change', function( ev ) {\n $(editor.element.$).find(\".anchor-link\").remove();\n var cellData = editor.getData();\n $(editor.element.$).closest(\".cell\").data(\"cell\").code_mirror.setValue(cellData);\n });\n\n // Change status\n toggle_button_mode(cell);\n }",
"function keyTyped() {\n mode = key;\n}",
"function determineMode() {\n\t\t\tswitch(gleam.campaign.campaign_type) {\n\t\t\t\tcase \"Reward\": return \"undo_all\"; // Instant-win\n\t\t\t\tcase \"Competition\": return \"undo_none\";\t// Raffle\n\t\t\t\tdefault: return \"undo_all\"; // Safest mode to fall back on\n\t\t\t}\n\t\t}",
"get onDidOpenTextDocument() {\n return vscode.workspace.onDidOpenTextDocument;\n }",
"SetCompatibleWithEditor() {}",
"function setEditOrCreateMode(mode)\n {\n $(invoke_button).data(\"mode\", mode)\n \n if (mode == \"0\")\n $(\"#mainHeading\").text(\"Add an Author\")\n else\n $(\"#mainHeading\").text(\"Edit an Author\")\n }",
"function determineFocusMode() {\n (userPreferences.focusMode) ? focusMode() : {};\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get first element from a collection input(s): obj: (collection) collection object from which first element is extracted output(s): object=> first element of the collection => NULL, if there is no first element in the collection OR it is not a collection | function firstCollectionElem(obj){
//get first element, if any
var elem = $(obj).first();
//check if collection is empty (i.e. has no first element)
if( elem.length == 0 ){
//return null if it is empty
return null;
}
//return first element
return elem[0];
} | [
"function lastCollectionElem(obj){\n\t//get first element, if any\n\tvar elem = $(obj).last();\n\t//check if collection is empty (i.e. has no first element)\n\tif( elem.length == 0 ){\n\t\t//return null if it is empty\n\t\treturn null;\n\t}\n\t//return first element\n\treturn elem[0];\n}",
"function findFirstProp(objs, p) {\n for (let obj of objs) {\n if (obj && obj.hasOwnProperty(p)) { return valueize(obj[p]); }\n }\n}",
"function getFirstElement(iterable) {\n var iterator = iterable[Symbol.iterator]();\n var result = iterator.next();\n if (result.done)\n throw new Error('getFirstElement was passed an empty iterable.');\n\n return result.value;\n }",
"function querySingle(selector, el){\r\n\t\treturn queryMultiple(selector, el)[0];\r\n\t}",
"get firstItem() {\n return !this.mainItems ? undefined : this.mainItems[0];\n }",
"function isCollection(obj){\n\treturn typeof obj == \"object\" && obj !== null;\n}",
"peekMin() {\n return this.collection[this.size - 1];\n }",
"function firstVal(arg, func) {\n if(Array.isArray(arg) == Array) {\n func(arr[0], index, arr);\n }\n if(arr.constructor == Object) {\n func(arg[key], key, arg);\n}\n}",
"function zerothItem(arr) {\n\treturn arr[0];\n}",
"function head(arr){\n return arr[0];\n}",
"async getSingleDoc(mongoUri, dbName, coll) {\n const client = await MongoClient.connect(mongoUri, { useNewUrlParser: true});\n const doc = await client.db(dbName).collection(coll).find().toArray().then(docs => docs[0]);\n logger.collectionSingle(doc, dbName, coll);\n client.close();\n }",
"function get_first_img(element) {\r\n return element.getElementsByTagName(\"img\")[0];\r\n}",
"function firstVal(arr, func) {\n func(arr[0], index, arr);\n}",
"add(collection, obj) {\n this.db\n .get(collection)\n .unshift(obj)\n .last()\n .value();\n }",
"function firstListItem() {\n return $(\"ul#pic-list li:first\")\n}",
"function head_2(xs, default0) /* forall<a> (xs : list<a>, default : a) -> a */ {\n return (xs != null) ? xs.head : default0;\n}",
"function getFirstVisibleRect(element) {\n // find visible clientRect of element itself\n var clientRects = element.getClientRects();\n for (var i = 0; i < clientRects.length; i++) {\n var clientRect = clientRects[i];\n if (isVisible(element, clientRect)) {\n return {element: element, rect: clientRect};\n }\n }\n // Only iterate over elements with a children property. This is mainly to\n // avoid issues with SVG elements, as Safari doesn't expose a children\n // property on them.\n if (element.children) {\n // find visible clientRect of child\n for (var j = 0; j < element.children.length; j++) {\n var childClientRect = getFirstVisibleRect(element.children[j]);\n if (childClientRect) {\n return childClientRect;\n }\n }\n }\n return null;\n}",
"findFirst(_value) {\n if (this.head === null && this.tail === null) {\n // no nodes in the list\n return null;\n } else {\n // check each node's value one by one from the beginning of the chain\n let current = this.head;\n while (current.nextNode !== null) {\n if (current.value === _value) return current; // found\n current = current.nextNode;\n }\n return null;\n }\n }",
"function firstOk(results) {\r\n return results.find(isOk) || error(null);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export NetworkSimulator for use by other unittests. | function NetworkSimulator()
{
this._pendingPromises = [];
} | [
"generateNetwork () {\n const nbHidden = this.nodes.filter(node => node.type === 'hidden').length\n const network = new Network(this.nbInput, nbHidden, this.nbOutput)\n return network\n }",
"function generateNetwork() {\n globalInfo = getGlobalInfo()\n \n let connections = new Array()\n genome.forEach(g => {\n let gene = g.split(\".\")\n connections[gene[1]] = [...(connections[gene[1]] ?? []), {out: parseInt(gene[2]), weight: gene[3] / 100, enabled: !!parseInt(gene[4])}]\n })\n\n // Order of inputs and hidden nodes in mask/matrix\n maskOrder = new Array()\n connections.forEach((c, i) => {\n if (c != null) maskOrder.push(i)\n })\n\n // Connection matrix\n networkMatrix = Array.apply(null, Array(maskOrder.length)).map(\n () => Array.apply(null, Array(maskOrder.length)).map(() => 0))\n\n // Output matrix\n outputMatrix = Array.apply(null, Array(maskOrder.length)).map(\n () => Array.apply(null, Array(globalInfo.outputs)).map(() => 0))\n\n // Populating the weights of the matrices\n connections.forEach((n, i) => {\n if (n != null) {\n let inputI = maskOrder.indexOf(i) // Get the ith node's index in the mask\n n.forEach(o => { // for each output of the node\n if (o.enabled) { // If the connection is enabled\n if (o.out < globalInfo.outputs) { // If an output node\n outputMatrix[inputI][o.out] = o.weight\n } else { // Otherwise must be a hidden node\n networkMatrix[inputI][maskOrder.indexOf(o.out)] = o.weight\n }\n }\n })\n }\n })\n\n // Set mask\n // All numbers represented by [real, imaginary]\n mask = maskOrder.map((v) => {\n if (v < (globalInfo.outputs + globalInfo.inputs)) return gpuMult ? [0, 0] : 0\n return gpuMult ? [0, 1] : complex('i')\n })\n\n return {\n networkMatrix,\n outputMatrix,\n maskOrder,\n mask\n }\n }",
"static createSimulation(model) {\n return HttpClient.post(\n `${ENDPOINT}simulations`,\n toSimulationRequestModel(model)\n )\n .map(toSimulationModel)\n .catch(resolveConflict);\n }",
"function simulateMacFirefox() {\n userAgent.MAC = true;\n userAgent.WINDOWS = false;\n userAgent.LINUX = false;\n userAgent.IE = false;\n userAgent.EDGE = false;\n userAgent.EDGE_OR_IE = false;\n userAgent.GECKO = true;\n userAgent.WEBKIT = false;\n}",
"function simulatePlan(){\n simulation();\n}",
"async function initialize() {\n simulator = new Simulator(credentials);\n\n await new Promise((resolve, reject) => {\n simulator\n .on('error', (err) => {\n reject(err);\n })\n .on('connected', () => {\n resolve();\n })\n .connect();\n });\n}",
"saveNetworkToJson(){\n\n // Networksettings into json object\n const networkSetting = this.client.NN.getNetworkSettings();\n // networkSetting['LossChoice'] = ElementHandler.getElementValFromId(\"lossChoice\");\n // networkSetting['OptimizerChoice'] = ElementHandler.getElementValFromId(\"optimizerChoice\");\n // networkSetting['LearningRate'] = ElementHandler.getElementValFromId(\"learningRate\");\n\n // Create blob from dict\n const jsonFile = JSON.stringify(networkSetting, null, 1);\n const blob = new Blob(\n [ jsonFile ],\n {\n type: \"application/json\"\n }\n );\n const downloadUrl = URL.createObjectURL(blob);\n\n // Get filename and set attr.\n const filename = ElementHandler.getElementValFromId(\"jsonFileName\") + \".json\";\n ElementHandler.setAttrById(\"hrefNetworkModal\", \"download\", filename);\n ElementHandler.setAttrById(\"hrefNetworkModal\", \"href\", downloadUrl);\n\n this.hide();\n }",
"async function createSimPolicy() {\n const subscriptionId =\n process.env[\"MOBILENETWORK_SUBSCRIPTION_ID\"] || \"00000000-0000-0000-0000-000000000000\";\n const resourceGroupName = process.env[\"MOBILENETWORK_RESOURCE_GROUP\"] || \"rg1\";\n const mobileNetworkName = \"testMobileNetwork\";\n const simPolicyName = \"testPolicy\";\n const parameters = {\n defaultSlice: {\n id: \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.MobileNetwork/mobileNetworks/testMobileNetwork/slices/testSlice\",\n },\n location: \"eastus\",\n registrationTimer: 3240,\n sliceConfigurations: [\n {\n dataNetworkConfigurations: [\n {\n fiveQi: 9,\n additionalAllowedSessionTypes: [],\n allocationAndRetentionPriorityLevel: 9,\n allowedServices: [\n {\n id: \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.MobileNetwork/mobileNetworks/testMobileNetwork/services/testService\",\n },\n ],\n dataNetwork: {\n id: \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.MobileNetwork/mobileNetworks/testMobileNetwork/dataNetworks/testdataNetwork\",\n },\n defaultSessionType: \"IPv4\",\n maximumNumberOfBufferedPackets: 200,\n preemptionCapability: \"NotPreempt\",\n preemptionVulnerability: \"Preemptable\",\n sessionAmbr: { downlink: \"1 Gbps\", uplink: \"500 Mbps\" },\n },\n ],\n defaultDataNetwork: {\n id: \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.MobileNetwork/mobileNetworks/testMobileNetwork/dataNetworks/testdataNetwork\",\n },\n slice: {\n id: \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.MobileNetwork/mobileNetworks/testMobileNetwork/slices/testSlice\",\n },\n },\n ],\n ueAmbr: { downlink: \"1 Gbps\", uplink: \"500 Mbps\" },\n };\n const credential = new DefaultAzureCredential();\n const client = new MobileNetworkManagementClient(credential, subscriptionId);\n const result = await client.simPolicies.beginCreateOrUpdateAndWait(\n resourceGroupName,\n mobileNetworkName,\n simPolicyName,\n parameters\n );\n console.log(result);\n}",
"async function initTestRunner(){\n\ttry {\n\t\t// Connect web3 with QTUM network\n\t\tconst web3 = await setupNetwork(JANUS_CONFIG);\n\n\t\t// const fundTestAccountResult = await fundTestAccount();\n\n\t\tconst chainId = 'JANUS'\n\t\tconsole.log(`[INFO] - Web3 is connected to the ${JANUS_CONFIG.name} node. Chain ID: ${chainId}`);\n\t\t\n\t\t// Deploy LinkToken or instantiate previously deployed contract\n\t\tconst LinkToken = await setupContract('LinkToken', JANUS_CONFIG, chainId, web3.currentProvider);\n\t\tconsole.log(`[INFO] - Deployed LinkToken contract address in ${JANUS_CONFIG.name} network is: ${LinkToken.address}`);\n\n\t\t// Deploy Oracle or instantiate previously deployed contract\n\t\tconst Oracle = await setupContract('Oracle', JANUS_CONFIG, chainId, web3.currentProvider);\n\t\tconsole.log(`[INFO] - Deployed Oracle contract address in ${JANUS_CONFIG.name} network is: ${Oracle.address}`);\n\n\t\t// Configure Chainlink node\n\t\tconst chainlinkData = await setupChainlinkNode(Oracle.address);\n\n\t\t// Deploy Consumer or instantiate previously deployed contract\n\t\tconst Consumer = await setupContract('Consumer', JANUS_CONFIG, chainId, web3.currentProvider);\n\t\tconsole.log(`[INFO] - Deployed Consumer contract address in ${JANUS_CONFIG.name} network is: ${Consumer.address}`);\n\t\t\n\t\t//const gasEstimate = await Consumer.requestQTUMPrice.estimateGas({from: process.env.HEX_QTUM_ADDRESS})\n\t\t//console.log(\"estimated gas: \", gasEstimate)\n\t\n\t\tConsumer.requestQTUMPrice({from: process.env.HEX_QTUM_ADDRESS, gas: \"0x4c4b40\", gasPrice: \"0x64\"})\n\t\t.then(function(result){\n\t\t\t// Watch for the RequestFulfilled event of the Consumer contract\n\t\t\tConsumer.RequestFulfilled({\n\t\t\t\t'address': Consumer.address,\n\t\t\t\t'topics': [],\n\t\t\t\t'fromBlock':'latest'\n\t\t\t}, function(error, event){\n\t\t\t\tif (!error){\n\t\t\t\t\tif (event.event == 'RequestFulfilled'){\n\t\t\t\t\t\tConsumer.currentPrice().then(function(price){\n\t\t\t\t\t\t\tconst priceNum = web3.utils.hexToNumber(price);\n\t\t\t\t\t\t\tif (priceNum !== 0){\n\t\t\t\t\t\t\t\tconsole.log('[INFO] - Received QTUM price: ' + (priceNum / 100000000) + ' BTC');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tconsole.log(error);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}catch(e){\n\t\tconsole.error('[ERROR] - Test Runner initialization failed:' + e);\n\t}\n}",
"static get network()\n\t{\n\t\treturn network;\n\t}",
"function setNetwork(network) {\n if (network === 'bitcoin') {\n bitcoinNetwork = 'bitcoin';\n }\n else {\n // test network\n bitcoinNetwork = 'testnet';\n }\n}",
"async function copy() {\n for (const outDir of outDirs) {\n const packages = [...defaultPackages]\n if (outDir === 'jest') {\n packages.push(...jestPackages)\n }\n if (outDir === 'jasmine') {\n packages.push(...jasminePackages)\n }\n\n // link node_modules\n for (const packageName of packages) {\n const destination = path.join(__dirname, outDir, 'node_modules', packageName)\n\n const destDir = destination.split(path.sep).slice(0, -1).join(path.sep)\n shelljs.mkdir('-p', destDir)\n shelljs.ln('-s', path.join(ROOT, 'node_modules', packageName), destination)\n }\n\n // link test file\n shelljs.ln('-s', path.join(__dirname, testFile), path.join(__dirname, outDir, testFile))\n\n // copy expect-webdriverio\n const destDir = path.join(__dirname, outDir, 'node_modules', 'expect-webdriverio')\n\n shelljs.mkdir('-p', destDir)\n shelljs.cp('*.d.ts', destDir)\n shelljs.cp('package.json', destDir)\n shelljs.cp('-r', 'types', destDir)\n }\n}",
"function startNetworkAndTest(onSuccess) {\n if (!isNetworkReady()) {\n SimpleTest.waitForExplicitFinish();\n var utils = getNetworkUtils();\n // Trigger network setup to obtain IP address before creating any PeerConnection.\n utils.prepareNetwork(onSuccess);\n } else {\n onSuccess();\n }\n}",
"function runNetworkTest(testFunction) {\n startNetworkAndTest(function() {\n runTest(testFunction);\n });\n}",
"function testUnit() {\n\n return new karmaServer({\n configFile: __dirname + \"/../../test/config/karma.conf.js\"\n })\n .start();\n}",
"function manage_simon() {\n simon.set_drawing_position()\n simon.detect_input()\n simon.display_background()\n simon.display_simon()\n simon.display_led()\n simon.clear_drawing_position()\n}",
"async function main(){\n let [owner] = await ethers.getSigners();\n let nyvUSD = await ethers.getContractAt(\"NYVAsset\",nyvUSDAddress);\n let dai = await ethers.getContractAt(\"ERC20\",daiAddress);\n let usdc = await ethers.getContractAt(\"ERC20\",usdcAddress);\n let umaEuro = await ethers.getContractAt(\"ERC20\",umaEuroAddress);\n let NYVAsset = await ethers.getContractFactory(\"NYVAsset\");\n let SimpleDepositor = await ethers.getContractFactory(\"SimpleDepositor\");\n let NYVExchange = await ethers.getContractFactory(\"NYVExchange\");\n let mockRouter = await ethers.getContractAt(\"UniswapV2Router01\",\"0xf164fC0Ec4E93095b804a4795bBe1e041497b92a\");\n\n let nyvEUR = await NYVAsset.deploy(\"NYVEuro\",\"NVEU\");\n await nyvEUR.deployed();\n let mockEUR = await NYVAsset.deploy(\"MEUR\",\"MEUR\");\n await mockEUR.deployed();\n console.log(\"mockEUR address: \" + mockEUR.address);\n console.log(\"NYVEUR address: \" + nyvEUR.address);\n\n //Deploy MockEURO depositor\n let mockEuroDepositor = await SimpleDepositor.deploy(mockEUR.address,nyvEUR.address,\"0xf164fC0Ec4E93095b804a4795bBe1e041497b92a\",initialTargetBasisPoints);\n await mockEuroDepositor.deployed();\n console.log(\"Mock Euro Depositor Address : \"+mockEuroDepositor.address);\n await mockEuroDepositor.setOperating(true);\n\n //Deploy UMA Euro Depositor\n let umaEuroDepositor = await SimpleDepositor.deploy(umaEuro.address,nyvEUR.address,\"0xf164fC0Ec4E93095b804a4795bBe1e041497b92a\",initialTargetBasisPoints);\n await umaEuroDepositor.deployed();\n console.log(\"UMA Euro Depositor Address : \"+umaEuroDepositor.address);\n await umaEuroDepositor.setOperating(true);\n\n //Deploy DAI depositor\n let daiDepositor = await SimpleDepositor.deploy(dai.address,nyvUSD.address,\"0xf164fC0Ec4E93095b804a4795bBe1e041497b92a\",initialTargetBasisPoints);\n await daiDepositor.deployed();\n console.log(\"Dai Depositor Address : \" +daiDepositor.address);\n await daiDepositor.setOperating(true);\n\n //Deploy USDC depositor\n let usdcDepositor = await SimpleDepositor.deploy(usdc.address,nyvUSD.address,\"0xf164fC0Ec4E93095b804a4795bBe1e041497b92a\",initialTargetBasisPoints);\n await usdcDepositor.deployed();\n console.log(\"USDC Depositor Address : \" +usdcDepositor.address);\n await usdcDepositor.setOperating(true);\n\n let exchange = await NYVExchange.deploy();\n await exchange.deployed();\n //Link Oracle + Authorise the Exchange\n await exchange.setQuoteBaseAggregator(nyvUSD.address,nyvEUR.address,eurusdoracle);\n await exchange.setOperating(true);\n console.log(\"NYVExchange Address : \" +exchange.address);\n \n let grant0 = await nyvUSD.grantRole(MINTER_ROLE,usdcDepositor.address);\n await grant0.wait();\n console.log(\"usdcdepositor is minter\");\n let grant1 = await nyvUSD.grantRole(MINTER_ROLE,daiDepositor.address);\n await grant1.wait();\n console.log(\"daidepositor is minter\");\n let grant2 = await nyvUSD.grantRole(MINTER_ROLE,exchange.address);\n await grant2.wait();\n console.log(\"exchange is nyvusd minter\");\n\n let grant3 = await nyvEUR.grantRole(MINTER_ROLE,mockEuroDepositor.address);\n await grant3.wait();\n console.log(\"mockEuroDepositor is minter\");\n let grant4 = await nyvEUR.grantRole(MINTER_ROLE,umaEuroDepositor.address);\n await grant4.wait();\n console.log(\"umaeurodepositor is minter\");\n let grant5 = await nyvEUR.grantRole(MINTER_ROLE,owner.getAddress());\n await grant5.wait();\n console.log(\"owner can mint euros\");\n let grant6 = await nyvEUR.grantRole(MINTER_ROLE,exchange.address);\n await grant6.wait();\n console.log(\"exchange is nyvEUR minter\");\n\n let grant7 = await nyvEUR.grantRole(BURNER_ROLE,exchange.address);\n await grant7.wait();\n console.log(\"exchange is nyvEUR burner\");\n\n let grant8 = await nyvUSD.grantRole(BURNER_ROLE,exchange.address);\n await grant8.wait();\n console.log(\"exchange is nyvUSD burner\");\n\n let approve0 = await nyvUSD.approve(mockRouter.address,lowLiquidityAmountToAdd.add(mockBankLowLiquidityAmountToAdd));\n await approve0.wait();\n let approve1 = await nyvEUR.approve(mockRouter.address,lowLiquidityAmountToAdd.add(mockBankLowLiquidityAmountToAdd));\n await approve1.wait();\n let approve2 = await dai.approve(mockRouter.address,middleLiquidityAmountToAdd);\n await approve2.wait();\n let approve3 = await umaEuro.approve(mockRouter.address,middleLiquidityAmountToAdd);\n await approve3.wait();\n let approve4 = await usdc.approve(mockRouter.address,mockBankMiddleLiquidityAmountToAdd);\n await approve4.wait();\n let approve5 = await mockEUR.approve(mockRouter.address,mockBankMiddleLiquidityAmountToAdd);\n await approve5.wait();\n\n let mint0 = await nyvUSD.mint(owner.getAddress(),lowLiquidityAmountToAdd.add(mockBankLowLiquidityAmountToAdd));\n await mint0.wait();\n let mint1 = await nyvEUR.mint(owner.getAddress(),lowLiquidityAmountToAdd.add(mockBankLowLiquidityAmountToAdd));\n await mint1.wait();\n let mint2 = await mockEUR.mint(owner.getAddress(),mockBankMiddleLiquidityAmountToAdd);\n await mint2.wait();\n\n await mockRouter.addLiquidity(dai.address,nyvUSD.address,middleLiquidityAmountToAdd,lowLiquidityAmountToAdd,\n middleLiquidityAmountToAdd,lowLiquidityAmountToAdd,\n owner.getAddress(),deposit);\n\n await mockRouter.addLiquidity(umaEuro.address,nyvEUR.address,middleLiquidityAmountToAdd,lowLiquidityAmountToAdd,\n middleLiquidityAmountToAdd,lowLiquidityAmountToAdd,\n owner.getAddress(),deposit);\n\n await mockRouter.addLiquidity(mockEUR.address,nyvEUR.address,mockBankMiddleLiquidityAmountToAdd,mockBankLowLiquidityAmountToAdd,\n middleLiquidityAmountToAdd,lowLiquidityAmountToAdd,\n owner.getAddress(),deposit);\n\n await mockRouter.addLiquidity(usdcAddress,nyvUSD.address,mockBankMiddleLiquidityAmountToAdd,mockBankLowLiquidityAmountToAdd,\n middleLiquidityAmountToAdd,lowLiquidityAmountToAdd,\n owner.getAddress(),deposit);\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}",
"function runUnitTestServer() {\n\n return new karmaServer({\n configFile: __dirname + \"/../../test/config/karma.conf.js\",\n autoWatch: true,\n port: 9999,\n singleRun: false,\n keepalive: true\n })\n .start();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate a new array, log the array, check for win, display array, update money | function generate(){
if (money >= cost){
var arr1 = [Math.floor(Math.random()*3), Math.floor(Math.random()*3), Math.floor(Math.random()*3)];
// console.log(arr1);
check(arr1);
displayIndex(arr1);
update();
profit = money - 1000 + bank;
displayProfit(profit);
highLow();
}
} | [
"function updateTraderOwns(tradeWith) {\n var tradePlayerStuff = \"\";\n var indexTradePlayer = 1;\n\n document.getElementById(\"trade_with\").innerHTML = \"Trade with: \" + tradeWith;\n for (i = 0; i < tiles2.length; i++) {\n if (tradeWith == tiles2[i].ownedBy) {\n //if (tiles2[i].mortgaged == 1) {\n\n tradePlayerStuff += indexTradePlayer + \".\" + tiles2[i].name + \" \";\n tradePlayerStuffArray[indexTradePlayer] = tiles2[i].name;\n indexTradePlayer++;\n //}\n }\n\n }\n document.getElementById(\"trader_player_owns\").innerHTML = \":\" + tradePlayerStuff;\n\n\n\n }",
"burnCards(){\n //Draw a card\n const firstCard = this.drawCard();\n\n //Save the first card\n this.burnedCards.firstCard = firstCard;\n\n //If the card is 10, J, Q, K, A, draw 10 more cards. \n const val = firstCard.actualVal > 0 ? firstCard.actualVal : 10;\n\n //Draw X number of cards where X is the value of the first card\n //Save them to the burned cards array\n for(let i = 1; i <= val; i++){\n this.burnedCards.burnCards.push(this.drawCard());\n }\n }",
"function checkPlayerArray() {\n\tif (arrayJug.length == arrayAI.length && compareArrays(arrayJug, arrayAI) === true) {\n\t\tcontador = contador + 100;\n\t\tscore_elem.innerHTML = \"Score: \" + contador;\n\t\tconsole.log(\"Turno AI\")\n\t\tsetTimeout(function(){\n\t\t\tpaseDeTurno(true);\n\t\t}, 500);\n\t}\n\telse if (arrayJug.length != arrayAI.length && compareArrays(arrayJug, arrayAI) === true) {\n\t\treturn;\n\t}\n\telse {\n\t\tanimacionGmOver()\n\t}\t\n\n}",
"function givepts(target, context) {\r\n\r\n var viewer = context.username;\r\n //console.log(viewer);\r\n var pts = Math.floor((Math.random()+1 ) * 10);\r\n\r\n var i = 0;\r\n while (i <= viewerObj.length) {\r\n if (viewerObj[i] == viewer) {\r\n ptsObj[i] += pts;\r\n console.log(viewer + \" is already in array\");\r\n console.log(ptsObj[i]);\r\n break;\r\n }\r\n else if (i == viewerObj.length) {\r\n viewerObj.push(viewer);\r\n ptsObj.push(pts);\r\n coinObj.push(0);\r\n console.log(viewer + \" has been added to array\");\r\n console.log(ptsObj[i]);\r\n break;\r\n }\r\n i++;\r\n }\r\n\r\n sendMessage(target, context, context.username + ' got ' + pts + ' points. YAY!');\r\n}",
"function fillStatPointsArray(){\n stat_points_per_level.push(0);\n for(var i=1;i<185;i++){\n stat_points_per_level.push(stat_points_per_level[i-1]+calcStatGain(i+1));\n }\n}",
"function crystValues(){\n for (i = 0; i < gemArray.length; i++) {\n gemArray[i] = Math.floor(Math.random() * 12) + 1;\n} \n//prints values of each item\n //console.log(gemArray);\n}",
"function showWinMessage() {\n playerMoney += winnings;\n win.text = winnings;\n resetFruitTally();\n checkJackPot();\n}",
"makeCoin(){\n for (let i = 0; i < this.numberOfCoins; i++){\n this.randX = Math.floor(random(this.mapSize));\n this.randY = Math.floor(random(this.mapSize));\n if (this.gameMap[this.randY][this.randX] === 0) {this.gameMap[this.randY][this.randX] = 4;}\n else {i--;}\n }\n \n }",
"function changeEnough(arrayChange, number) {\n let totalChangeAmountArray = [(Number(arrayChange[0]) * 25), (Number(arrayChange[1]) * 10), (Number(arrayChange[2]) * 5) , (Number(arrayChange[3]) * 1)];\n let totalChangeAmount = 0;\n // this for loops get the total amount of change.\n for (let i =0; i < totalChangeAmountArray.length; i++){\n totalChangeAmount += Number(totalChangeAmountArray[i])\n }\n let currentAmount = Number(number*100);\n if (totalChangeAmount >= currentAmount) {\n if (totalChangeAmountArray[0] > currentAmount){\n currentAmount -= Math.floor(currentAmount / 25) * 25;\n }\n else {\n currentAmount -= (Number(totalChangeAmountArray[0] * 25)) \n }\n if (totalChangeAmountArray[1] > currentAmount){\n currentAmount -= Math.floor(currentAmount / 10) * 10;\n }\n else {\n currentAmount -= (Number(totalChangeAmountArray[1] * 10)) \n }\n if (totalChangeAmountArray[2] > currentAmount){\n currentAmount -= Math.floor(currentAmount / 5) * 5;\n }\n else {\n currentAmount -= (Number(totalChangeAmountArray[2] * 5)) \n }\n if (totalChangeAmountArray[3] > currentAmount){\n currentAmount -= Math.floor(currentAmount / 25) * 1;\n }\n else {\n currentAmount -= (Number(totalChangeAmountArray[3] * 1));\n }\n if (currentAmount === 0){\n return true;\n }\n\n }\n\n else{\n return false;\n }\n return false;\n \n}",
"fillBucket(sortedWishList){\n let bucketAmount = this.bucketTotal\n let paidWishes = []\n for(var i = 0; i < sortedWishList.length; i++){\n bucketAmount -= sortedWishList[i].wishExpense\n paidWishes.push(sortedWishList[i])\n if(bucketAmount == 0){\n console.log(\"Bucket was emptied.\")\n break\n }\n }\n for(var j = 0; j < paidWishes.length; j++){\n console.log(paidWishes[j].doneeName + \"'s wish has been paid.\")\n }\n this.bucketTotal = bucketAmount\n }",
"fnEvaluate (result, betHistory) {\n // function for default baccarat`\n let processed = [];\n let total_lost = 0;\n let total_win = 0;\n let total_bets;\n\n let total_rolling = total_bets = _.reduce(betHistory, (sum, row) => {\n return sum + row.bet_money;\n }, 0);\n\n let payout = 0;\n\n _.forEach(betHistory, (row) => {\n let key = row.bet.replace(\"bet_\", \"\");\n\n // payout pairs\n if (key.indexOf(\"pair\") !== -1 && result.pairs.indexOf(key.replace(\"pair\", \"\")) !== -1) {\n row.win_money = this.multipliers[key] * row.bet_money;\n payout += row.win_money;\n total_win += (row.win_money + row.bet_money)\n }\n\n // payout main bets\n if (key === result.winner) {\n row.win_money = this.multipliers[key] * row.bet_money;\n payout += row.win_money;\n total_win += (row.win_money + row.bet_money)\n }\n\n // return money if bet if result is tie\n if (result.winner == \"tie\" && key !== \"tie\" && key.indexOf(\"pair\") == -1) {\n row.win_money = row.bet_money;\n payout += row.win_money;\n total_rolling -= row.bet_money;\n total_win += row.bet_money\n }\n\n if (!row.win_money) {\n total_lost += row.bet_money;\n }\n\n if (row.win_money) {\n row.win_money += (result.winner == \"tie\" && key !== \"tie\" && key.indexOf(\"pair\") == -1 ? 0 : row.bet_money);\n }\n\n processed.push(row);\n });\n\n return { data : processed, total_rolling, total_bets, payout, total_lost, total_win };\n }",
"function checkTwoCardWin(){ \n let bool = false; \n if((21 == playerTotal[0] || 21 == playerTotal[1]) && (21 != dealerTotal[0] || 21 != dealerTotal[1])){\n // Setup for if player had 21 and dealer does not\n bool = true;\n \n divD2.src = dealer[1][2]; \n dealerCards.innerText = \"Dealer showing a \"+ dealer[1][0]+', '+dealer[0][0];\n console.log(dealerCards.innerText);\n outputDealerPlayerValues();\n let poiAA = parseInt(acnt);\n let poi2AA = parseInt(betAmount);\n let combine = poiAA + 2*poi2AA;\n acnt = combine;\n acntAmnt.innerText = \" Account balence3 : \" + acnt; \n console.log(acntAmnt.innerText); \n } else if((21 != playerTotal[0] || 21 != playerTotal[1]) && (21 == dealerTotal[0] || 21 == dealerTotal[1])){\n // Setup for if dealer has 21 and the player does not\n bool = true;\n divD2.src = dealer[0][2];\n dealerCards.innerText = \"Dealer showing a \"+ dealer[1][0]+', '+dealer[0][0];\n console.log(dealerCards.innerText);\n outputDealerPlayerValues();\n console.log(acntAmnt.innerText);\n startHand.addEventListener('click', beginPlay);\n } else if((21 == playerTotal[0] || 21 == playerTotal[1]) && (21 == dealerTotal[0] || 21 == dealerTotal[1])){\n // Setup for if player and dealer both have 21\n bool = true;\n divD2.src = dealer[0][2];\n dealerCards.innerText = \"Dealer showing a \"+ dealer[1][0]+', '+dealer[0][0];\n console.log(dealerCards.innerText);\n outputDealerPlayerValues();\n let poi = parseInt(acnt);\n let poi2 = parseInt(betAmount);\n let combine = poi + poi2;\n acnt = combine;\n acntAmnt.innerText = \" Account balence2 : \" + acnt;\n console.log(acntAmnt.innerText);\n } \n if(bool != true){ \n // If bool != true, neither the dealer nor player have 21 in their first two cards, so turn\n // the hitHand and stayHand .addEventListener on to continue the hand\n hitHand.addEventListener('click', hitPlay);\n stayHand.addEventListener('click', stayPlay);\n }else{\n // If bool == true, hand is over, turn startHand.addEVentListener on to allow a new hand to be started\n startHand.addEventListener('click', beginPlay);\n } \n}",
"compare() {\n let result1 = this.state.gameplayOne;\n let result2 = this.state.gameplayTwo;\n let win = [...this.state.win];\n\n // Setting arrays which will be filled by true or false since a winning combination is detected in the player's game.\n let tabTrueFalse1 = [];\n let tabTrueFalse2 = [];\n // winningLine may help to know which winning combination is on the set and then have an action on it. To think.\n let winningLine = [];\n\n if (this.state.gameplayOne.length >= 3) {\n tabTrueFalse1 = win.map(elt =>\n elt.every(element => result1.includes(element))\n );\n }\n if (this.state.gameplayTwo.length >= 3) {\n tabTrueFalse2 = win.map(elt =>\n elt.every(element => result2.includes(element))\n );\n }\n\n //Launching youWon()\n tabTrueFalse1.includes(true) ? this.youWon(1) : null;\n tabTrueFalse2.includes(true) ? this.youWon(2) : null;\n }",
"function hasWon(){\n\n //check all the lites to check if they're green. if so add one to the greentilecounter\n $tileArray.each(function (i, value) {\n if($($tileArray[i]).attr('class') === \"green\"){\n greenTileCount ++;\n }\n });\n\n tilesToGo = greenTileCount;\n\n //log valueof greentielcounter at start\n console.log(greenTileCount + \" at start of function\")\n\n // if number of green tiles = the array length then youve won.\n if(greenTileCount == $tileArray.length) {\n $('#welcome').delay(400).fadeIn();\n player1score = turnCounter;\n resetBoard();\n\n addToScoreBoard();\n\n $gridSizeSelector.hide();\n // $welcomeMsg.hide();\n $gridSizeSelector.show(); \n\n $tileArray.each(function(i, value){\n $(this).css({\"background-color\":\"rgba(41,242,44,0.8)\"});\n $(this).delay(1000).fadeOut();\n })\n $p1score.html(\"you've won, big ups! choose next level to play\");\n return true;\n }\n greenTileCount = 0;\n }",
"checkFinished(row, col, player){\n let winningStreak = [];\n\n //Checking for a streak vertically in the column of the inserted token\n let streak = [];\n let streakReached = false;\n for(let i=0; i<this.rows; i++){\n if(this.field[i][col] == player){\n streak.push([i,col]);\n if(streak.length == this.toWin){\n streakReached = true;\n i=this.rows;\n }\n }\n else streak = [];\n }\n if(streakReached) winningStreak = winningStreak.concat(streak);\n\n //Checking for a streak horizontally in the row of the inserted token\n streakReached = false;\n streak = [];\n for(let i=0; i<this.cols; i++){\n if(this.field[row][i] == player){\n streak.push([row,i]);\n if(streak.length == this.toWin) streakReached = true;\n }\n else{\n if(!streakReached) streak = [];\n else i=this.cols;\n }\n }\n if(streakReached) winningStreak = winningStreak.concat(streak);\n\n //Checking for a streak diagonally from top left to bottom right in the\n //line of the inserted token and adding it to the winningStreak Array.\n let spots;\n if(this.rows >= this.cols) spots = this.rows;\n else spots = this.cols;\n winningStreak = winningStreak.concat(this.checkDiagonally(row,col,player,spots,1));\n\n //Checking for a streak diagonally from bottom left to top right in the\n //line of the inserted token and adding it to the winningStreak Array.\n winningStreak = winningStreak.concat(this.checkDiagonally(row,col,player,spots,-1));\n\n if(winningStreak.length >= this.toWin) return winningStreak;\n else if(this.freeLots == 0) return false;\n return null;\n }",
"updateWinners() {\n const winners = [...this.continuing]\n .filter(candidate => this.count[this.round][candidate] >= this.thresh[this.round]);\n if (!winners.length) return; // no winners\n\n const text = this.newWinners(winners);\n this.roundInfo[this.round].winners = text;\n }",
"UPDATE_OPP_ATHLETE_STATISTICS(state) {\n let result = [];\n\n for (let athlete in state.oppRoster) {\n result.push(\n {\n name: state.oppRoster[athlete].name,\n number: state.oppRoster[athlete].number,\n points:0,\n freethrow: 0,\n freethrowAttempt: 0,\n freethrowPercentage:0,\n twopoints: 0,\n twopointsAttempt: 0,\n twopointsPercentage:0,\n threepoints: 0,\n threepointsAttempt: 0,\n threepointsPercentage:0,\n assists: 0,\n blocks: 0,\n rebounds: 0,\n steals: 0,\n turnovers: 0,\n foul: 0\n }\n );\n }\n\n // For each game action, update athlete statistics accordingly.\n for (let index in state.gameActions) {\n let currentAction = state.gameActions[index];\n if (currentAction.team !== \"opponent\") {\n continue;\n }\n let athlete_index = -1;\n for (let athlete in state.oppRoster) {\n if (state.oppRoster[athlete].key == \"athlete-\" + currentAction.athlete_id) {\n athlete_index = athlete;\n break;\n }\n }\n\n // Continue when an athlete has been removed.\n if (athlete_index === -1) {\n continue;\n }\n\n switch (currentAction.action_type) {\n case \"Freethrow\":\n result[athlete_index].freethrow++;\n result[athlete_index].freethrowAttempt++;\n result[athlete_index].points++;\n result[athlete_index].freethrowPercentage=result[athlete_index].freethrow/result[athlete_index].freethrowAttempt*100;\n result[athlete_index].freethrowPercentage=parseFloat(result[athlete_index].freethrowPercentage).toFixed(1);\n break;\n\n case \"FreethrowMiss\":\n result[athlete_index].freethrowAttempt++;\n result[athlete_index].freethrowPercentage=result[athlete_index].freethrow/result[athlete_index].freethrowAttempt*100;\n result[athlete_index].freethrowPercentage=parseFloat(result[athlete_index].freethrowPercentage).toFixed(1);\n break;\n\n case \"2Points\":\n result[athlete_index].twopoints++;\n result[athlete_index].twopointsAttempt++;\n result[athlete_index].points+2;\n result[athlete_index].twopointsPercentage=result[athlete_index].twopoints/result[athlete_index].twopointsAttempt*100;\n result[athlete_index].twopointsPercentage=parseFloat(result[athlete_index].twopointsPercentage).toFixed(1);\n break;\n\n case \"2PointsMiss\":\n result[athlete_index].twopointsAttempt++;\n result[athlete_index].twopointsPercentage=result[athlete_index].twopoints/result[athlete_index].twopointsAttempt*100;\n result[athlete_index].twopointsPercentage=parseFloat(result[athlete_index].twopointsPercentage).toFixed(1);\n break;\n\n case \"3Points\":\n result[athlete_index].threepoints++;\n result[athlete_index].threepointsAttempt++;\n result[athlete_index].points+3;\n result[athlete_index].threepointsPercentage=result[athlete_index].threepoints/result[athlete_index].threepointsAttempt*100;\n result[athlete_index].threepointsPercentage=parseFloat(result[athlete_index].threepointsPercentage).toFixed(1);\n break;\n \n case \"3PointsMiss\":\n result[athlete_index].threepointsAttempt++;\n result[athlete_index].threepointsPercentage=result[athlete_index].threepoints/result[athlete_index].threepointsAttempt*100;\n result[athlete_index].threepointsPercentage=parseFloat(result[athlete_index].threepointsPercentage).toFixed(1);\n break;\n\n case \"Assist\":\n result[athlete_index].assists++;\n break;\n\n case \"Blocks\":\n result[athlete_index].blocks++;\n break;\n\n case \"Steals\":\n result[athlete_index].steals++;\n break;\n\n case \"Rebound\":\n result[athlete_index].rebounds++;\n break;\n\n case \"Turnover\":\n result[athlete_index].turnovers++;\n break;\n\n case \"Foul\":\n result[athlete_index].foul++;\n break;\n\n default:\n break;\n }\n }\n\n state.oppAthleteStatistics = result;\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}",
"function high()\r\n{\r\n for(var i=0;i<highScore.length;i++)\r\n{\r\n var curr = highScore[i];\r\n if(curr.score<point)\r\n {\r\n console.log(chalk.yellowBright('Congratulations! You have Beaten '+ curr.name + \" \" +\"in Avengers Quiz\"));\r\n }\r\n}\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name: resetCopyButton(clickedBtnID) Description: Reset styles all button copy, and add new style to button copied Parameter: clickedBtnID => String Return: None | function resetCopyButton(clickedBtnID) {
var i;
var listButtons = document.getElementsByClassName("btn-copy");
for (i = 0; i < listButtons.length; i++) {
listButtons[i].textContent = "Copy";
listButtons[i].classList.remove("copied");
}
var clickedBtn = document.getElementById(clickedBtnID);
clickedBtn.textContent = "Copied!";
clickedBtn.classList.add("copied");
} | [
"function unhighlightButton(oButton){\r\n oButton.style.backgroundColor = \"\";\r\n oButton.style.color = \"\";\r\n }",
"function resetAddButton() {\n let oldAddButton = id(\"add\");\n var newAddButton = oldAddButton.cloneNode(true);\n oldAddButton.parentNode.replaceChild(newAddButton, oldAddButton);\n }",
"resetCustomColors() {\n this.themeSwitch.removeCustomTheme();\n this.removeFromLocalStorage();\n this.colorButtons.forEach(button => {\n button.style.backgroundColor = ``;\n })\n this.assignColorsToButtonsDataAttribute();\n this.removeFromLocalStorage();\n this.colors = this.themeSwitch.getColors();\n }",
"function resetButtons() {\n hitButton.disabled = true;\n standButton.disabled = true;\n continueButton.disabled = false;\n }",
"function addCopyToClipboardButton() {\n var idPrefix = \"codeId_\";\n var idNumerator = 0;\n\n var codeElementList = document.getElementsByTagName(\"CODE\");\n\n for (var i = 0; i < codeElementList.length; i++) {\n var CODE = codeElementList[i];\n if (typeof CODE.innerText !== 'undefined') {\n var PRE = CODE.parentElement;\n if (PRE.tagName !== 'PRE') continue;\n var id = idPrefix + (++idNumerator);\n var TEXTAREA = createTextArea(id, CODE.innerText);\n var BUTTON = createButton(id);\n PRE.insertBefore(BUTTON, PRE.childNodes[0] || null);\n PRE.append(TEXTAREA);\n }\n }\n}",
"function mouseClickBtnRandom() {\n clickColor =\n \"rgb( \" +\n Math.floor(Math.random() * (0 + 255)) +\n \" \" +\n Math.floor(Math.random() * (0 + 255)) +\n \" \" +\n Math.floor(Math.random() * (0 + 255)) +\n \" )\";\n mouseClickBtn.style.backgroundColor = clickColor;\n clickButton.style.backgroundColor = clickColor;\n\n}",
"function formatProjectButtonsBackground(clickedButton) {\n $('.project-item').each(function() {\n $(this).css(\"background\",\"transparent\");\n })\n\n if (clickedButton != null) {\n clickedButton.css(\"background\", \"linear-gradient( -45deg, #FFDA3B 0%, #DB3C6D 100%)\");\n }\n }",
"function removeVisualiserButton(){\r\n\teRem(\"buttonWaves\");\r\n\teRem(\"buttonBars\");\r\n\teRem(\"buttonBarz\");\r\n\teRem(\"buttonCircleBars\");\r\n\teRem(\"buttonCirclePeaks\");\r\n\tremoveSliderSelector();\r\n}",
"function refreshWidgetAndButtonStatus() {\n var curWidget = self.currentWidget();\n if (curWidget) {\n widgetArray[curWidget.index].isSelected(false);\n self.currentWidget(null);\n }\n self.confirmBtnDisabled(true);\n }",
"function copyBattleToClipboard () {\n $('.copy-button').on('click', function() {\n var copy_link = $(this).closest('.copy-modal').find('.copy-link');\n copy_link.focus();\n copy_link.select();\n document.execCommand('copy');\n });\n}",
"function codeButtons () {\n // get all <code> elements.\n var allCodeBlocksElements = $('div[class^=\"language-\"]');\n allCodeBlocksElements.each(function(i) {\n\t// add a sequentially increasing id to each code block.\n var currentId = \"codeblock\" + (i + 1);\n $(this).attr('id', currentId);\n //define and then add a clipboard button to all code blocks.\n var clipButton = '<button class=\"codebtn\" data-clipboard-target=\"#' + currentId + '\"><img class=\"copybefore\" src=\"https://clipboardjs.com/assets/images/clippy.svg\" width=\"13\" alt=\"Copy to clipboard\"><img class=\"copyafter\" src=\"img/done.svg\" width=\"13\" alt=\"Copy to clipboard\"></button>';\n $(this).append(clipButton);\n });\n//instantiate clipboardjs on the buttons. This controls the copy action.\n new ClipboardJS('.codebtn');\n //switch between clipboard icon to checkmark icon on click.\n $('.codebtn').click(function() {\n $(this).find('.copybefore').hide();\n $(this).find('.copyafter').show();\n });\n}",
"function didPlayerCopy(buttonPressed) { \n\n // if time ran out, update counter and return not copying\n if (buttonPressed === null) {\n numTimeRanOut++;\n return false; \n }\n\n // if the button isn't valid, log warning and set copying to false\n if (!isValidButton(buttonPressed)) {\n console.warn(\"Invalid player choice!\");\n return false; \n }\n\n // at this point only valid button choices should be possible\n // if they tried to copy but don't have enough money, reset their choice to be not copying\n // this shouldn't occur, but is here in case it happens somehow\n if(buttonPressed != 0 && player.money < payToCopy) {\n jsPsych.data.get().filter({'trial_index': jsPsych.progress().current_trial_global - 1}).select('button_pressed').values[0] = 0; \n return false; \n }\n\n // if copying return true, if not copying return false \n if(buttonPressed != 0) return true; \n else return false; \n}",
"function clearAddOnButtons(addOnButtons) {\r\n}",
"function updatePaletteSwatch(button, color)\n{\n if(color) \n button.setAttribute(\"data-color\", color);\n\n button.firstElementChild.style.background = \n button.getAttribute(\"data-color\");\n}",
"function copyShortenLink(copyID) {\n var shortenLinkID = \"shortenLink-\" + copyID;\n var copyBtnID = \"copyBtn-\" + copyID;\n\n var text = document.getElementById(shortenLinkID).innerText;\n var elem = document.createElement(\"textarea\");\n document.body.appendChild(elem);\n elem.value = text;\n elem.select();\n elem.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n document.body.removeChild(elem);\n\n resetCopyButton(copyBtnID);\n}",
"undoButton() {\n this.state.undo();\n }",
"function copyButtonTooltips(dateStr) {\r\n $copyDayBtn.tooltip('dispose');\r\n $copyWeekBtn.tooltip('dispose');\r\n\r\n if (copyBtnActive === 'day') {\r\n $copyDayBtn.attr(\"data-toggle\", \"tooltip\");\r\n $copyDayBtn.attr(\"data-placement\", \"bottom\");\r\n $copyDayBtn.prop('title', dateStr);\r\n $copyDayBtn.tooltip();\r\n } else {\r\n $copyWeekBtn.attr(\"data-toggle\", \"tooltip\");\r\n $copyWeekBtn.attr(\"data-placement\", \"bottom\");\r\n $copyWeekBtn.prop('title', dateStr);\r\n $copyWeekBtn.tooltip();\r\n }\r\n }",
"function mouseMoveBtnRandom() {\n moveColor =\n \"rgb( \" +\n Math.floor(Math.random() * (0 + 255)) +\n \" \" +\n Math.floor(Math.random() * (0 + 255)) +\n \" \" +\n Math.floor(Math.random() * (0 + 255)) +\n \" )\";\n mouseMoveBtn.style.backgroundColor = moveColor;\n moveButton.style.backgroundColor = moveColor;\n}",
"function refreshButtonStyle(button) {\r\r\n $(button).removeClass();\r\r\n\r\r\n var addon = JSON.parse(unescape($(button).data('key')));\r\r\n\r\r\n $(button).addClass(getButtonStyle(addon));\r\t\r // $(button).attr('disabled',true);\r\t\r\n if($(button).attr('class')=='success'){\r\t\r\t$(button).prop('disabled',true); \r\t\r\t}\r\n if (studio.extension.storage.getItem('ERROR') === 'ok') {\r\r\n /// SUCCESS\r\r\n //$(button).text(studio.extension.storage.getItem(addon.name));\r\r\n\r\r\n $(button).off('click');\r\r\n } else {\r\r\n /// ERROR\r\r\n $(button).addClass('error');\r\r\n console.error(studio.extension.storage.getItem('ERROR'));\r\r\n }\r\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a hash of the data. The hash function is SHA512, truncated to first 32 hex characters. | static async hash(data) {
if (! ("subtle" in window.crypto)) {
return undefined;
}
let input = new TextEncoder().encode(data);
let hash = await window.crypto.subtle.digest("SHA-512", input);
let bytes = new Uint8Array(hash);
let hex = Array.from(bytes).map(byte => byte.toString(16).padStart(2, "0")).join("");
return hex.slice(0, 32);
} | [
"function createDataHash(data){\n const hash = crypto.createHash('sha256');\n hash.update(data);\n\n return hash.digest('base64');\n}",
"function hasher(data) {\n var pre_string = data.lastname + data.firstname + data.gender + data.dob + data.drug;\n var hash = '', curr_str;\n\n hash = Sha1.hash(pre_string);\n\n /**\n // Increment 5 characters at a time\n for (var i = 0, len = pre_string.length; i < len; i += 5) {\n curr_str = '';\n\n // Extract 5 characters at a time\n for (var j = 0; j < 5; j++) {\n if (pre_string[i + j]) {\n curr_str += pre_string[i + j]\n }\n }\n\n // Hash the characters and append to hash\n var temp = mini_hash(curr_str); // Get number from the string\n var fromCode = String.fromCharCode(mini_hash(curr_str));\n hash += fromCode;\n\n } */\n\n\n return hash;\n}",
"calculateHash(data, timestamp, previousHash, nonce) {\n return SHA256(JSON.stringify(data) + timestamp + previousHash + nonce).toString();\n }",
"function hash(uuid) {\n var hash = 0, i, chr;\n if (uuid.length === 0) return hash;\n for (i = 0; i < uuid.length; i++) {\n chr = uuid.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n if (hash < 0) {\n hash += 1;\n hash *= -1;\n }\n return hash % constants.localStorage.numBins;\n}",
"function generateHash(string) {\n\treturn crypto.createHash('sha256').update(string + configuration.encryption.salt).digest('hex');\n}",
"function hash52 (str) {\n var prime = fnv_constants[52].prime,\n hash = fnv_constants[52].offset,\n mask = fnv_constants[52].mask;\n\n for (var i = 0; i < str.length; i++) {\n hash ^= Math.pow(str.charCodeAt(i), 2);\n hash *= prime;\n }\n\n return new FnvHash(bn(hash).and(mask), 52);\n }",
"inputHash(input) {\n return \"\";\n }",
"function hashFormData(data) {\n\n var s = data.session_id + '^' +\n MD5HASH + '^' +\n data.x_amount + '^' +\n data.timestamp + '^' +\n dpm.formDataString(data);\n\n return crypto.createHash('md5').update(s).digest('hex');\n }",
"function binb(x, len) {\n var j, i, l,\n W = new Array(80),\n hash = new Array(16),\n //Initial hash values\n H = [\n new int64(0x6a09e667, -205731576),\n new int64(-1150833019, -2067093701),\n new int64(0x3c6ef372, -23791573),\n new int64(-1521486534, 0x5f1d36f1),\n new int64(0x510e527f, -1377402159),\n new int64(-1694144372, 0x2b3e6c1f),\n new int64(0x1f83d9ab, -79577749),\n new int64(0x5be0cd19, 0x137e2179)\n ],\n T1 = new int64(0, 0),\n T2 = new int64(0, 0),\n a = new int64(0, 0),\n b = new int64(0, 0),\n c = new int64(0, 0),\n d = new int64(0, 0),\n e = new int64(0, 0),\n f = new int64(0, 0),\n g = new int64(0, 0),\n h = new int64(0, 0),\n //Temporary variables not specified by the document\n s0 = new int64(0, 0),\n s1 = new int64(0, 0),\n Ch = new int64(0, 0),\n Maj = new int64(0, 0),\n r1 = new int64(0, 0),\n r2 = new int64(0, 0),\n r3 = new int64(0, 0);\n\n if (sha512_k === undefined) {\n //SHA512 constants\n sha512_k = [\n new int64(0x428a2f98, -685199838), new int64(0x71374491, 0x23ef65cd),\n new int64(-1245643825, -330482897), new int64(-373957723, -2121671748),\n new int64(0x3956c25b, -213338824), new int64(0x59f111f1, -1241133031),\n new int64(-1841331548, -1357295717), new int64(-1424204075, -630357736),\n new int64(-670586216, -1560083902), new int64(0x12835b01, 0x45706fbe),\n new int64(0x243185be, 0x4ee4b28c), new int64(0x550c7dc3, -704662302),\n new int64(0x72be5d74, -226784913), new int64(-2132889090, 0x3b1696b1),\n new int64(-1680079193, 0x25c71235), new int64(-1046744716, -815192428),\n new int64(-459576895, -1628353838), new int64(-272742522, 0x384f25e3),\n new int64(0xfc19dc6, -1953704523), new int64(0x240ca1cc, 0x77ac9c65),\n new int64(0x2de92c6f, 0x592b0275), new int64(0x4a7484aa, 0x6ea6e483),\n new int64(0x5cb0a9dc, -1119749164), new int64(0x76f988da, -2096016459),\n new int64(-1740746414, -295247957), new int64(-1473132947, 0x2db43210),\n new int64(-1341970488, -1728372417), new int64(-1084653625, -1091629340),\n new int64(-958395405, 0x3da88fc2), new int64(-710438585, -1828018395),\n new int64(0x6ca6351, -536640913), new int64(0x14292967, 0xa0e6e70),\n new int64(0x27b70a85, 0x46d22ffc), new int64(0x2e1b2138, 0x5c26c926),\n new int64(0x4d2c6dfc, 0x5ac42aed), new int64(0x53380d13, -1651133473),\n new int64(0x650a7354, -1951439906), new int64(0x766a0abb, 0x3c77b2a8),\n new int64(-2117940946, 0x47edaee6), new int64(-1838011259, 0x1482353b),\n new int64(-1564481375, 0x4cf10364), new int64(-1474664885, -1136513023),\n new int64(-1035236496, -789014639), new int64(-949202525, 0x654be30),\n new int64(-778901479, -688958952), new int64(-694614492, 0x5565a910),\n new int64(-200395387, 0x5771202a), new int64(0x106aa070, 0x32bbd1b8),\n new int64(0x19a4c116, -1194143544), new int64(0x1e376c08, 0x5141ab53),\n new int64(0x2748774c, -544281703), new int64(0x34b0bcb5, -509917016),\n new int64(0x391c0cb3, -976659869), new int64(0x4ed8aa4a, -482243893),\n new int64(0x5b9cca4f, 0x7763e373), new int64(0x682e6ff3, -692930397),\n new int64(0x748f82ee, 0x5defb2fc), new int64(0x78a5636f, 0x43172f60),\n new int64(-2067236844, -1578062990), new int64(-1933114872, 0x1a6439ec),\n new int64(-1866530822, 0x23631e28), new int64(-1538233109, -561857047),\n new int64(-1090935817, -1295615723), new int64(-965641998, -479046869),\n new int64(-903397682, -366583396), new int64(-779700025, 0x21c0c207),\n new int64(-354779690, -840897762), new int64(-176337025, -294727304),\n new int64(0x6f067aa, 0x72176fba), new int64(0xa637dc5, -1563912026),\n new int64(0x113f9804, -1090974290), new int64(0x1b710b35, 0x131c471b),\n new int64(0x28db77f5, 0x23047d84), new int64(0x32caab7b, 0x40c72493),\n new int64(0x3c9ebe0a, 0x15c9bebc), new int64(0x431d67c4, -1676669620),\n new int64(0x4cc5d4be, -885112138), new int64(0x597f299c, -60457430),\n new int64(0x5fcb6fab, 0x3ad6faec), new int64(0x6c44198c, 0x4a475817)\n ];\n }\n\n for (i = 0; i < 80; i += 1) {\n W[i] = new int64(0, 0);\n }\n\n // append padding to the source string. The format is described in the FIPS.\n x[len >> 5] |= 0x80 << (24 - (len & 0x1f));\n x[((len + 128 >> 10) << 5) + 31] = len;\n l = x.length;\n for (i = 0; i < l; i += 32) { //32 dwords is the block size\n int64copy(a, H[0]);\n int64copy(b, H[1]);\n int64copy(c, H[2]);\n int64copy(d, H[3]);\n int64copy(e, H[4]);\n int64copy(f, H[5]);\n int64copy(g, H[6]);\n int64copy(h, H[7]);\n\n for (j = 0; j < 16; j += 1) {\n W[j].h = x[i + 2 * j];\n W[j].l = x[i + 2 * j + 1];\n }\n\n for (j = 16; j < 80; j += 1) {\n //sigma1\n int64rrot(r1, W[j - 2], 19);\n int64revrrot(r2, W[j - 2], 29);\n int64shr(r3, W[j - 2], 6);\n s1.l = r1.l ^ r2.l ^ r3.l;\n s1.h = r1.h ^ r2.h ^ r3.h;\n //sigma0\n int64rrot(r1, W[j - 15], 1);\n int64rrot(r2, W[j - 15], 8);\n int64shr(r3, W[j - 15], 7);\n s0.l = r1.l ^ r2.l ^ r3.l;\n s0.h = r1.h ^ r2.h ^ r3.h;\n\n int64add4(W[j], s1, W[j - 7], s0, W[j - 16]);\n }\n\n for (j = 0; j < 80; j += 1) {\n //Ch\n Ch.l = (e.l & f.l) ^ (~e.l & g.l);\n Ch.h = (e.h & f.h) ^ (~e.h & g.h);\n\n //Sigma1\n int64rrot(r1, e, 14);\n int64rrot(r2, e, 18);\n int64revrrot(r3, e, 9);\n s1.l = r1.l ^ r2.l ^ r3.l;\n s1.h = r1.h ^ r2.h ^ r3.h;\n\n //Sigma0\n int64rrot(r1, a, 28);\n int64revrrot(r2, a, 2);\n int64revrrot(r3, a, 7);\n s0.l = r1.l ^ r2.l ^ r3.l;\n s0.h = r1.h ^ r2.h ^ r3.h;\n\n //Maj\n Maj.l = (a.l & b.l) ^ (a.l & c.l) ^ (b.l & c.l);\n Maj.h = (a.h & b.h) ^ (a.h & c.h) ^ (b.h & c.h);\n\n int64add5(T1, h, s1, Ch, sha512_k[j], W[j]);\n int64add(T2, s0, Maj);\n\n int64copy(h, g);\n int64copy(g, f);\n int64copy(f, e);\n int64add(e, d, T1);\n int64copy(d, c);\n int64copy(c, b);\n int64copy(b, a);\n int64add(a, T1, T2);\n }\n int64add(H[0], H[0], a);\n int64add(H[1], H[1], b);\n int64add(H[2], H[2], c);\n int64add(H[3], H[3], d);\n int64add(H[4], H[4], e);\n int64add(H[5], H[5], f);\n int64add(H[6], H[6], g);\n int64add(H[7], H[7], h);\n }\n\n //represent the hash as an array of 32-bit dwords\n for (i = 0; i < 8; i += 1) {\n hash[2 * i] = H[i].h;\n hash[2 * i + 1] = H[i].l;\n }\n return hash;\n }",
"function sha256_update(data, inputLen) {\n var i, index, curpos = 0;\n /* Compute number of bytes mod 64 */\n index = ((count[0] >> 3) & 0x3f);\n var remainder = (inputLen & 0x3f);\n\n /* Update number of bits */\n if ((count[0] += (inputLen << 3)) < (inputLen << 3)) count[1]++;\n count[1] += (inputLen >> 29);\n\n /* Transform as many times as possible */\n for (i = 0; i + 63 < inputLen; i += 64) {\n for (var j = index; j < 64; j++)\n buffer[j] = data.charCodeAt(curpos++);\n sha256_transform();\n index = 0;\n }\n\n /* Buffer remaining input */\n for (var j = 0; j < remainder; j++)\n buffer[j] = data.charCodeAt(curpos++);\n }",
"function hash(text) {\n return crypto.createHash('md5').update(text).digest('hex')\n}",
"function getHash(pw, salt) {\n return crypto.createHash('sha256').update(pw+salt).digest('hex');\n}",
"static Transcript_Hash(...M) {\n return crypto.createHash(HKDF.hashName).update(HKDF.concat(...M)).digest();\n }",
"getHashCode() {\n let hash = this._m[0] || 0;\n for (let i = 1; i < 16; i++) {\n hash = (hash * 397) ^ (this._m[i] || 0);\n }\n return hash;\n }",
"digesting() {}",
"function core_sha1(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - len % 32);\n x[((len + 64 >> 9) << 4) + 15] = len;\n\n var w = Array(80);\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n var e = -1009589776;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n var olde = e;\n\n for (var j = 0; j < 80; j++) {\n if (j < 16) w[j] = x[i + j];\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);\n var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));\n e = d;\n d = c;\n c = rol(b, 30);\n b = a;\n a = t;\n }\n\n a = safe_add(a, olda);\n b = safe_add(b, oldb);\n c = safe_add(c, oldc);\n d = safe_add(d, oldd);\n e = safe_add(e, olde);\n }\n return Array(a, b, c, d, e);\n\n }",
"getHashCode() {\n let hash = this.width || 0;\n hash = (hash * 397) ^ (this.height || 0);\n return hash;\n }",
"function hashFnDef( fn ) {\n\n return fn.toString(); // todo: actually hash this\n\n}",
"@Method\r\n hashPassword(password) {\r\n if (this.salt && password) {\r\n return crypto.pbkdf2Sync(password, new Buffer(this.salt, 'base64'), 10000, 64, 'SHA1').toString('base64');\r\n } else {\r\n return password;\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removed alle antwoorden met resultaat 'NULL!' | function removeNull(data){
data.forEach(data => {
for (let key in data) {
if (data[key] == '#NULL!') {
delete data[key];
}
}
});
return data;
} | [
"_getAreaZero() {\n let newArr = [];\n this.area.map(el => {\n newArr.push(...el)\n });\n\n return newArr.some(el => el === null);\n }",
"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}",
"visitRespect_or_ignore_nulls(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function dnull(c){\n return c==null?'0':c;\n}",
"function emptyTotaalKosten(){\n OverigeKosten = 0;\n OpenbaarVervoer = 0;\n AutoKM = 0;\n AutoEuro = 0;\n Totaal = 0;\n}",
"function trimTrailingNulls(parameters) {\r\n while (isNull(parameters[parameters.length - 1])) {\r\n parameters.pop();\r\n }\r\n return parameters;\r\n }",
"function nullFields()\n{\n\treturn isEmpty(\"#myPattern\") || isEmpty(\"#frameRate\");\n}",
"function toBlank( str ) {\r\n\tif( str == undefined || str == null ) {\r\n\t\treturn \"\";\r\n\t} else {\t\t\r\n\t\treturn str;\r\n\t}\r\n}",
"function propertyNull() {\n\t delete this[name];\n\t }",
"function cleanText(screenplay) {\n // First cycle to remove all blanks\n let _s;\n screenplay.forEach((s, index, array) => {\n _s = s.replace(/\\s\\s+|\\r\\n/g, \"\");\n array[index] = trim(_s);\n array.splice(index, s);\n });\n\n // Second cycle to remove all the empty elements from the array\n // It can be optimized but I couldn't quite manage how to do that\n // (Two forEach are a bit overkill)\n screenplay.forEach((s, index, array) => {\n if (s === \"\") {\n console.log(\"Linea Vuota\");\n array.splice(index, 1);\n }\n });\n}",
"function clearInputEleVals(eles) {\n for(var i = 0; i< eles.length; i++) {\n eles[i].value = null;\n }\n}",
"function emptyYearUren(){\n YearGewerktUren = 0;\n YearOver100Uren = 0;\n YearOver125Uren = 0;\n YearVerlofUren = 0;\n YearZiekteUren = 0;\n YearTotaalUren = 0;\n}",
"function setPluginCompNull(comp)\n\t{\n\t\tif (plugin1Comp == comp) {\n\t\t\tplugin1Comp = null;\n\t\t\tplugin1Val = -1;\n\t\t}\n\t\t\n\t\tif (plugin2Comp == comp) {\n\t\t\tplugin2Comp = null;\n\t\t\tplugin2Val = -1;\n\t\t}\n\t\t\n\t\tevaluate();\n\t}",
"function _cleanSentences() {\n // look for empty tone_categories and set tone_categories to 0 values\n _rankedSentences.forEach(function(item) {\n if (item.tone_categories.length === 0)\n item.tone_categories = TONE_CATEGORIES_RESET.slice(0);\n });\n }",
"desencolar()\r\n {\r\n if(this.primero === this.final)\r\n {\r\n return null;\r\n } \r\n const info = this.elemento[this.primero];\r\n delete this.elemento[this.primero];\r\n this.primero++;\r\n return info;\r\n }",
"function isEmpty() {\n\tif (this.status == 2) return false; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// preskocimo dan, za katerega ne obstaja idmm \n\tif (str2date(this.datum) >= this.parent.getFirstEditDate()) { \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// preverjamo samo podatke, ki jih lahko vnašamo (npr. vnasalec lahko vnaša podatke samo za 3 mesece nazaj: zdaj=junij, vnos=junij, maj, april, marec)\n eval(\"var params = parametri_\" + this.parent.name); \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// parametri\n for (var i = 0; i < params.length; i++) { \n if (this[params[i].name].msr && this[params[i].name].edit()) { \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// če se parameter meri\n if (params[i].name.search(/inter/i) > -1) { \t\t\t\t\t\t\t\t\t// interpolacija pri praznih dnevnih je 0\n if (this[params[i].name].nval && parseInt(this[params[i].name].nval) != 0) return false; \n } \n else if (this[params[i].name].nval) return false; \t\t\t\t\t\t\t\t\t\t// parameter se meri in obstaja vrednost \n } \n }\n if (this.parent.name == \"padavine\" || this.parent.name == \"klima\") {// pojavi - samo klima in padavine\n eval(\"var pojavi = pojavi_\" + this.parent.name); // pojavi\n for (var i = 0; i < pojavi.length; i++)\n\t\t\t\tif (this[pojavi[i].name].msr && this[pojavi[i].name].edit() && this[pojavi[i].name].nval) return false;\n }\n return true; \n }\n return false;\n}",
"function haeRastiKoodit(joukkue) {\n let rastit = joukkue.rastit.slice();\n for (let i = 0; i < rastit.length; i++) {\n for (let j = 0; j < data.rastit.length; j++) {\n if (rastit[i].rasti == data.rastit[j].id + \"\") {\n rastit[i].koodi = data.rastit[j].koodi;\n }\n }\n if (rastit[i].koodi == undefined) {\n rastit[i].koodi = \"0\";\n }\n }\n joukkue.rastit = rastit;\n return joukkue;\n}",
"visitDatatype_null_enable(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function SysFmtNullOrEmptyToString(){}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=======For Checking Decimal Value should be of 3 decimal places.. | function CheckFloat3decimal(resid) {
var num = document.getElementById(resid).value;
var tomatch = /^\d*(\.\d{1,3})?$/;
if (tomatch.test(num)) {
return true;
}
else {
alert("Input error");
document.getElementById(resid).value = "";
document.getElementById(resid).focus();
return false;
}
} | [
"function checkDecimal()\n{\n let re = /^([0-9]*|[0-9]*\\.[0-9]*)$/;\n let number = this.value.trim();\n setErrorFlag(this, re.test(number) && number > 0);\n}",
"function formatDecimal3(val, n) {\n n = n || 2;\n var str = \"\" + Math.round ( parseFloat(val) * Math.pow(10, n) );\n while (str.length <= n) {\n str = \"0\" + str;\n }\n var pt = str.length - n;\n return str.slice(0,pt) + \".\" + str.slice(pt);\n}",
"function checkIfFloat(value) {\r\n if (value.toString().indexOf('.', 0) > -1) {\r\n return parseFloat(value).toFixed(2);\r\n }\r\n else {\r\n return value;\r\n }\r\n}",
"function validate_float(checkprice){\n\nif(/^[+-]?\\d+(\\.\\d+)?$/.test(checkprice)){\n\nreturn true;\n\n}else{\n return false;\n}\n\n}",
"function AcceptDecimal(str) {\n //http://lawrence.ecorp.net/inet/samples/regexp-validate2.php\n str = trim(str);\n var regDecimal = /^[-+]?[0-9]+(\\.[0-9]+)?$/;\n return regDecimal.test(str);\n}",
"function SysFmtRoundDecimal() {}",
"function formatDecimal4(val, n) {\n n = n || 2;\n var str = \"\" + Math.round ( parseFloat(val) * Math.pow(10, n) );\n while (str.length <= n) {\n str = \"0\" + str;\n }\n var pt = str.length - n;\n return str.slice(0,pt) + \".\" + str.slice(pt);\n}",
"function roundThird(value) {\r\n var rem = value % RADIX;\r\n if (rem === 0) {\r\n return value;\r\n }\r\n return value + RADIX - rem;\r\n }",
"function validQuantity(input) {\n return parseInt(input) > 0 && input.toString().indexOf(\".\") === -1;\n }",
"function threeNums(n1, n2, n3){\n let total = (100 + n1 - n2) / n3\n if (total > 25){\n console.log (\"WE HAVE A WINNNA\")\n }\n}",
"function precision_function() {\n var a = 1234567.89876543210;\n document.getElementById(\"precision\").innerHTML = a.toPrecision(10);\n}",
"function checkForDecimal(arr) {\n return arr.length === new Set(arr).size;\n }",
"function is_valid_value() {\n\tvar value = $('#valueInput')[0].value;\n\tvar error = $(\"#errorAlert\");\n\t\n\t// Make sure value contains only numbers and up to one decimal point\n\tvar valid_characters = \"0123456789.\";\t\n\tvar char_result = true;\t\n\tvar point = 0;\n\t\n\t// Check each character for validity, decimal points\n\tfor (var i = 0; i < value.length && char_result == true; i++) {\n\t\tvar temp = value.charAt(i);\n\t\tif (valid_characters.indexOf(temp) == -1) {\n\t\t\tchar_result = false;\n\t\t}\n\t\tif (temp == \".\"){\n\t\t\tpoint++;\n\t\t}\n\t}\n\t// Checks decimal point count\n\tif (point > 1)\n\t\tchar_result = false;\n\t\n\t// Display error in page\n\tif (value.length == 0) {\n\t\terror.innerHTML = \"You must enter a value\";\n\t\treturn false;\n\t}\n\tif(!char_result) {\n\t\terror.innerHTML = \"You can only enter numbers and a decimal point\";\n\t\treturn false;\n\t} else {\n\t\terror.innerHTML = \"\";\n\t\treturn true;\n\t}\n}",
"function financialMfil(numMfil) {\n return Number.parseFloat(numMfil / 1e3).toFixed(3);\n}",
"function formatValore(field)\n{\n\tformatDecimal(field,9,6,true);\n}",
"function isAcceptableFloat(num) {\n const str = num.toString();\n return str.indexOf('.') === str.length - 2;\n}",
"calculateCashOnCash() { return parseFloat((this.calculateCashFlow() / this.calculateTotalCapitalRequired()).toFixed(3)) }",
"function calc() {\n \n if(document.getElementById(\"screen\").value === \"Error\") {\n return;\n }\n \n try {\n if (document.getElementById(\"screen\").value.includes('.')) {\n document.getElementById(\"screen\").value = eval(document.getElementById(\"screen\").value).toFixed(2);\n } else {\n document.getElementById(\"screen\").value = eval(document.getElementById(\"screen\").value);\n }\n calced = true;\n } catch (err) {\n document.getElementById(\"screen\").value = \"Error\";\n calced = true;\n }\n}",
"function isValidUFloat(s) {\n return s.match(/^\\s*([0-9]+(\\.[0-9]*)?|\\.[0-9]+)\\s*$/)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove the ruler from the scene | disableRuler() {
if (this.mRulerEnabled)
this.mSceneController.scene.remove(this.mRulerLine);
this.mRulerEnabled = false;
} | [
"_clearRocketAnimation() {\n this._rocket._tl.clear();\n this.removeChild(this._rocket);\n }",
"function clearScene() {\n var obj;\n for( var i = scene.children.length - 1; i > 3; i--) {\n obj = scene.children[i];\n scene.remove(obj);\n }\n}",
"function removeVisualiserButton(){\r\n\teRem(\"buttonWaves\");\r\n\teRem(\"buttonBars\");\r\n\teRem(\"buttonBarz\");\r\n\teRem(\"buttonCircleBars\");\r\n\teRem(\"buttonCirclePeaks\");\r\n\tremoveSliderSelector();\r\n}",
"onRemovedFromScene() {\n if (this._pixiObject !== null)\n this._pixiContainer.removeChild(this._pixiObject);\n if (this._threeObject !== null) this._threeGroup.remove(this._threeObject);\n }",
"destroy() {\n this.viewport.options.divWheel.removeEventListener('wheel', this.wheelFunction);\n }",
"resetScene() {\n while (this.scene.children.length > 0) {\n this.scene.remove(this.scene.children[0]);\n }\n this.scene.add(this.camera); // camera MUST be added to scene for it's light to work\n this.scene.add(this.ambientLight);\n\n this.pickedObject = undefined;\n this.crystalPosObject = undefined;\n\n this.updateCamera(this.refs.msCanvas.width, this.refs.msCanvas.height, true /*resetPos*/);\n }",
"function onRemoveLine() {\n removeLine()\n renderMeme()\n}",
"destroy()\n {\n //first remove it from the scene.\n this.#scene.remove(this);\n //then destroy all components.\n while(this.#components.length > 0)\n {\n let currentComponent = this.#components.pop();\n currentComponent.destroy();\n }\n }",
"remove () {\r\n // unclip all targets\r\n this.targets().forEach(function (el) {\r\n el.unclip();\r\n });\r\n\r\n // remove clipPath from parent\r\n return super.remove()\r\n }",
"removeLines(lines){\n\t\t//console.log(\"This is removeLines:\",lines);\n\n\t\tvar lines_n = lines.length;\n\t\tfor (var l=0;l<lines_n;l++){\n\t\t\tthis.scene.remove(lines[l]);\n\n\t\t}\n\t\t// lines.forEach( function( item ) { \n\t\t// \tthis.scene.remove( item ) \n\t\t// },this );\n\t}",
"destroy()\n {\n this.parentGroup.removeSprite(this);\n }",
"function clearSlide() {\n if (!whiteboardActive) return;\n if (confirm(\"Delete notes and board on this slide?\")) {\n let strokes = svg.querySelectorAll(\"svg>path\");\n if (strokes) {\n strokes.forEach((stroke) => {\n stroke.remove();\n });\n needToSave(true);\n }\n\n let grid = svg.querySelector(\"svg>rect\");\n if (grid) {\n grid.remove();\n buttonGrid.dataset.active = false;\n needToSave(true);\n }\n\n setWhiteboardHeight(pageHeight);\n }\n }",
"function removeAllLights(){\r\n\r\n\tscene.remove(ambientLight);\r\n\tscene.remove(directionalLight);\r\n\tscene.remove(pointLight);\r\n\r\n}",
"remove() {\n this.floor.itemSprites.removeChild(this.sprite);\n }",
"eraseGuidelines() {\n d3.selectAll('#grid .guideline').remove();\n }",
"removeObject(object) {\n this.scene.remove(object);\n }",
"function removeGrid() {\n const container = document.querySelector('#sketch-container');\n while (container.firstChild) {\n container.removeChild(container.lastChild);\n }\n\n }",
"destroy() {\n _wl_scene_remove_object(this.objectId);\n this.objectId = null;\n }",
"showRuler() {\n if (!this.mRulerEnabled)\n this.mSceneController.scene.add(this.mRulerLine);\n this.mRulerEnabled = true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The ISO 3166 (alpha 2) region code | static get iso3166() {
return 'CY';
} | [
"getRegionCode(){\n\t\treturn this.dataArray[3];\n\t}",
"function getCodeFromLetter(str){\n return str.charCodeAt(0)-96;\n}",
"function assertStateCode(code) {\n if (![\"\", \"at\", \"be\", \"bg\", \"ch\", \"cy\", \"cz\", \"de\", \"dk\", \"ee\", \"es\", \"fi\", \"fr\",\n \"gb\", \"gr\", \"hr\", \"hu\", \"ie\", \"is\", \"it\", \"li\", \"lt\", \"lu\", \"lv\", \"mt\",\n \"nl\", \"no\", \"pl\", \"pt\", \"ro\", \"se\", \"si\", \"sk\", \"tr\", \"mk\"].includes(code)) {\n throw(\"Invalid country code \\\"\" + code + \"\\\".\");\n }\n}",
"function regionFromUrl(url) {\n var matches = url.match(/\\#l(\\d+)(?:-(\\d+))?/i);\n if (!matches) { return; }\n return orderedRegion(matches[1], matches[2] && Number(matches[2]));\n }",
"getRegion(regionName) {\n var regions = this._regions || {};\n return regions[regionName];\n }",
"_aec(code) {\n return String.fromCharCode(27) + \"[\" + code;\n }",
"function timeZoneAbbreviation() {\n\t var abbreviation, date, formattedStr, i, len, matchedStrings, ref, str;\n\t date = new Date().toString();\n\t formattedStr = ((ref = date.split('(')[1]) != null ? ref.slice(0, -1) : 0) || date.split(' ');\n\t if (formattedStr instanceof Array) {\n\t matchedStrings = [];\n\t for (var i = 0, len = formattedStr.length; i < len; i++) {\n\t str = formattedStr[i];\n\t if ((abbreviation = (ref = str.match(/\\b[A-Z]+\\b/)) !== null) ? ref[0] : 0) {\n\t matchedStrings.push(abbreviation);\n\t }\n\t }\n\t formattedStr = matchedStrings.pop();\n\t }\n\t return formattedStr;\n\t }",
"function witCodes() {\n return {\n sq: 'Albanian',\n ar: 'Arabic',\n bn: 'Bengali',\n bs: 'Bosnian',\n bg: 'Bulgarian',\n my: 'Burmese',\n ca: 'Catalan',\n zh: 'Chinese',\n hr: 'Croatian',\n cs: 'Czech',\n da: 'Danish',\n nl: 'Dutch',\n en: 'English',\n et: 'Estonian',\n fi: 'Finnish',\n fr: 'French',\n ka: 'Georgian',\n de: 'German',\n el: 'Greek',\n he: 'Hebrew',\n hi: 'Hindi',\n hu: 'Hungarian',\n id: 'Indonesian',\n is: 'Icelandic',\n it: 'Italian',\n ja: 'Japanese',\n ko: 'Korean',\n la: 'Latin',\n lt: 'Lithuanian',\n mk: 'Macedonian',\n ms: 'Malay',\n no: 'Norwegian',\n fa: 'Persian',\n pl: 'Polish',\n pt: 'Portugese',\n ro: 'Romanian',\n ru: 'Russian',\n sr: 'Serbian',\n sk: 'Slovak',\n sl: 'Slovenian',\n es: 'Spanish',\n sw: 'Swahili',\n sv: 'Swedish',\n tl: 'Tagalog',\n ta: 'Tamil',\n th: 'Thai',\n tr: 'Turkish',\n uk: 'Ukrainian',\n vi: 'Vietnamese',\n }\n}",
"function rd_RemoveMarkers_localize(strVar)\r\n\t{\r\n\t\treturn strVar[\"en\"];\r\n\t}",
"function getCountryFromRegion(region, country) {\n for (var c in region) {\n var countryCurrency = region[c];\n\n if (contains(countryCurrency, country)) {\n return countryCurrency;\n }\n }\n\n return null;\n}",
"function standardizeCountryName(countryName) {\n const possibleMapping = constants.countryMapping.filter(mapping => mapping.possibleNames.indexOf(countryName) >= 0);\n return (possibleMapping.length == 1 ? possibleMapping[0].standardizedName : countryName.toLowerCase());\n}",
"function validateCanadaPostalCode(postalCodeFld) {\r\n if (isEmpty(postalCodeFld.value) || isFieldMasked(postalCodeFld)) {\r\n return \"\";\r\n }\r\n\r\n var postalCodeRegExp = new RegExp(\"^[a-zA-Z]\\\\d[a-zA-Z] \\\\d[a-zA-Z]\\\\d$\");\r\n\r\n if (!postalCodeRegExp.test(postalCodeFld.value)) {\r\n return getMessage(\"ci.entity.message.postalCode.invalid\");\r\n }\r\n return \"\";\r\n}",
"getRegion(region) {\n if (region) {\n return this.promise.resolve(region);\n }\n return this.avRegions\n .getCurrentRegion()\n .then(\n (response) =>\n response && response.data && response.data.regions && response.data.regions[0] && response.data.regions[0].id\n );\n }",
"function validCountryProvided(c) {\n return typeof c === 'string' && c.length < 501;\n}",
"static getCurrencyName(code) {\n let currencyName = this.getPhrase(code, \"CurrencyCode\");\n if (currencyName != \"\" && currencyName.length > 0)\n return currencyName;\n else\n return code;\n }",
"function get_currency_code(str) {\n return str.match(/\\((.*?)\\)/)[1];\n}",
"function getPostalCode(address) {\r\n\tvar firstCommaPos = address.indexOf(\",\");\r\n\tvar lastCommaPos = address.lastIndexOf(\",\", address.length);\r\n\tif (lastCommaPos != firstCommaPos)\r\n\t\treturn address.substring(firstCommaPos + 2, firstCommaPos + 7);\r\n\telse\r\n\t\treturn \"\";\r\n}",
"function getLetterFromCode(num){\n return String.fromCharCode(num+96);\n}",
"function isISO31661Alpha3(value) {\n return typeof value === 'string' && isISO31661Alpha3_1.default(value);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save Core config to Firebase as part of installation | async writeCoreConfig() {
let c = this.get(null, null, true);
let copy = JSON.parse(JSON.stringify(c));
delete(copy.db);
delete(copy.fs);
let db = await Class.i('awy_core_model_db');
await db.rput(copy, 'config');
} | [
"function saveConfiguration () {\n\tJSON.stringify(config).to(SITE_DIR+'config.json');\n}",
"function save() {\n\twriteFile(config, CONFIG_NAME);\n\tglobal.store.dispatch({\n\t\ttype: StateActions.UPDATE_CONFIGURATION,\n\t\tpayload: {\n\t\t\t...config\n\t\t}\n\t})\n}",
"function writeConfig () {\n self._repo.config.set(config, (err) => {\n if (err) return callback(err)\n\n addDefaultAssets()\n })\n }",
"function setupFirebaseConfig(){\n var config = {\n apiKey: \"AIzaSyCYDlrU2O3OT4jaJnaCF5krqCbof67yTWU\",\n authDomain: \"findmefuel-3c346.firebaseapp.com\",\n databaseURL: \"https://findmefuel-3c346.firebaseio.com\",\n storageBucket: \"findmefuel-3c346.appspot.com\",\n messagingSenderId: \"386153049618\"\n };\n firebase.initializeApp(config);\n database = firebase.database();\n }",
"saveConfig() {\n localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.config));\n }",
"async initCoreConfiguration(){\n // try to fetch from localStorage\n let config = JSON.parse(localStorage.getItem('core'));\n let def = {\n 'install_status': null,\n 'module_run_levels': {},\n };\n if ( !config) {\n if (this.get('db/host') !== null) {\n // dont have core config but DB is there\n try {\n let db = await Class.i('awy_core_model_db');\n config = await db.rget('config');\n config = JSON.parse(config) || {};\n //alert(JSON.stringify(config));\n } catch(e){\n // DB connection can't be established\n //alert('CANT GET CORE CONFIG FROM DATABASE');\n config = def; //return;\n }\n } else {\n // dont have core config and DB HOST is missing, we are on initial installation steps\n config = def; //return;\n }\n } else {\n // core config in localStorage\n }\n\n // if found anywhere, add to config and write to localStorage\n if (config !== null) {\n this.add(config, true);\n this.writeLocalStorage('core', config);\n }\n }",
"function touchDbConfigFile() {\n try {\n var stream = fs.createWriteStream(parent_dir + \"/config/db_config.json\");\n stream.write(JSON.stringify({}, null, 2));\n stream.end();\n\n } catch (ee) {\n //error in creating config file\n console.log(ee)\n //console.log(ee,\"s\")\n }\n }",
"static _createConfig() {\n console.log(\"Copying config file\");\n fs.copySync(\"config.dist.json\", \"config.json\");\n }",
"function saveSettings() {\n\n var projectRoot = ProjectManager.getProjectRoot().fullPath;\n var file = FileSystem.getFileForPath(projectRoot + '.ftpsync_settings');\n\n function replacePwd(key, value) {\n if (key === \"pwd\") return undefined;\n return value;\n }\n // if save password is checked, no need to remove pwd from settings\n if (ftpSettings.savepwd === 'checked')\n FileUtils.writeText(file, JSON.stringify(ftpSettings));\n else\n FileUtils.writeText(file, JSON.stringify(ftpSettings, replacePwd));\n }",
"configuring() {\n // creates .yo-rc config file\n this.config.save()\n }",
"function updateSettings(event, payload) {\n fs.writeFile(configPath, JSON.stringify(payload, null, 2), function (err) {\n if (err) return console.log(err);\n event.sender.send('config', payload)\n });\n}",
"function saveConfiguration() {\n console.log(\"saveConfiguration\");\n // save the current configuration in the \"chair\" object\n const chosenColors = view.getChairColors();\n model.updateChairObject(chosenColors);\n // update local storage\n model.updateLocalStarage(\"chair\", model.chair);\n console.log(model.chair);\n}",
"function setupUserConfig() {\n let cfg = path.join(u.dataLoc(), 'cfg.env')\n if(shell.test(\"-f\", cfg)) return\n\n shell.echo(`\\n\\nCreating configuration file...`)\n shell.echo(`# understand/\n# We use environment variables to configure various skills and services.\n# In order to pass the information to the required components we need to\n# set them in this file.\n\n# For Telegram Channel\nTELEGRAM_TOKEN=\n\n# For what-wine skill\nMASHAPE_KEY=\n\n# for AI Artist Skill\nAIARTIST_HOST=\nAIARTIST_PORT=\n`).to(cfg)\n shell.echo(`Please edit this file: ${cfg}`)\n shell.echo(`To add your own TELEGRAM_TOKEN, etc...\\n\\n`)\n}",
"async function _initConfigListeners() {\n const fbRoot = await FBHelper.getRootRefUnlimited();\n const fbConfig = await fbRoot.child(`config/${APP_NAME}`);\n fbConfig.on('value', async (snapshot) => {\n const newConfig = snapshot.val();\n try {\n _parseConfig(newConfig);\n } catch (ex) {\n log.exception(LOG_PREFIX, 'Error parsing config data', ex);\n return;\n }\n try {\n log.log(LOG_PREFIX, `Writing updated config to '${CONFIG_FILE}'.`);\n await fs.writeFile(CONFIG_FILE, JSON.stringify(newConfig, null, 2));\n } catch (ex) {\n log.exception(LOG_PREFIX, 'Unable to write config to disk.', ex);\n }\n });\n const fbCronConfig = await fbRoot.child(`config/${APP_NAME}/rebootCron`);\n fbCronConfig.on('value', (snapshot) => {\n const jobs = snapshot.val() || [];\n _initRebootCron(jobs);\n });\n}",
"createConfigFile() {\n const { _ } = this;\n const json = JSON.stringify(STUB_CONFIG, null, 4);\n write(_.configPath, `${ json }\\n`);\n }",
"saveGameConfig() {\n this.store.set('gameConfig', this.gameConfig);\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}",
"addDummyConfig(config) {\n let data\n if(config) {\n data = config\n } else {\n data = this.state.marketConfig\n }\n\n this.props.Firebase.database().ref('marketConfig/'+this.deviceUuid).set({\n config: data\n })\n }",
"updatePersistedMetadata() {\n this.addon.sourceURI = this.sourceURI.spec;\n\n if (this.releaseNotesURI) {\n this.addon.releaseNotesURI = this.releaseNotesURI.spec;\n }\n\n if (this.installTelemetryInfo) {\n this.addon.installTelemetryInfo = this.installTelemetryInfo;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parseSE bKeepHashTags defaults to false returns se: se.titleNoSE : string se.spent : float se.estimate : float | function parseSE(title, bKeepHashTags) {
var se = { bParsed: false, bSFTFormat: false };
se = parseSE_SFT(title);
// Strip hashtags
if (bKeepHashTags === undefined || bKeepHashTags == false)
se.titleNoSE = se.titleNoSE.replace(/#[\w-]+/, "");
return se;
} | [
"function parseTagSoup(soup, tags)\n {\n /*\n 1) [vendor_length] = read an unsigned integer of 32 bits\n 2) [vendor_string] = read a UTF-8 vector as [vendor_length] octets\n 3) [user_comment_list_length] = read an unsigned integer of 32 bits\n 4) iterate [user_comment_list_length] times {\n 5) [length] = read an unsigned integer of 32 bits\n 6) this iteration's user comment = read a UTF-8 vector as [length] octets\n }\n 7) [framing_bit] = read a single bit as boolean\n 8) if ( [framing_bit] unset or end of packet ) then ERROR\n 9) done.\n\n [http://www.xiph.org/vorbis/doc/v-comment.html]\n */\n\n if (! soup)\n {\n return;\n }\n //console.log(\"Soup: \" + soup.toString(\"utf-8\"));\n //console.log(soup);\n\n // iterate over entries\n var offset = 0;\n var vendorLength = soup[offset] +\n (soup[offset + 1] << 8) +\n (soup[offset + 2] << 16) +\n (soup[offset + 3] << 24);\n //console.log(\"vendor length: \" + vendorLength);\n offset += 4 + vendorLength;\n\n var commentsCount = soup[offset] + \n (soup[offset + 1] << 8) +\n (soup[offset + 2] << 16) +\n (soup[offset + 3] << 24);\n //console.log(\"number of comments: \" + commentsCount);\n offset += 4;\n\n\n var count = 0;\n while (count < commentsCount && offset < soup.length)\n {\n var entrySize = soup[offset] +\n (soup[offset + 1] << 8) +\n (soup[offset + 2] << 16) +\n (soup[offset + 3] << 24);\n offset += 4;\n //console.log(\"size: \" + entrySize + \", offset: \" + offset + \", total: \" + soup.length);\n //console.log(soup.slice(offset, offset + entrySize).toString(\"binary\"));\n\n var entry = soup.slice(offset, offset + entrySize);\n var equalsPos = entry.indexOf(\"=\");\n if (equalsPos !== -1)\n {\n var keySize = equalsPos;\n var valueSize = entrySize - keySize - 1;\n\n var key = entry.slice(0, keySize).toString(\"ascii\");\n key = TAGS_MAP[key] || key;\n var value = entry.slice(keySize + 1, keySize + 1 + valueSize).toString(\"binary\");\n tags[key] = value;\n //console.log(key + \" = \" + value);\n }\n\n offset += entrySize;\n ++count;\n }\n }",
"function addSEFieldValues(s, e, comment) {\n\tvar elemSpent = $(\"#plusCardCommentSpent\");\n\tvar elemEst = $(\"#plusCardCommentEstimate\");\n\tvar sCur = parseSEInput(elemSpent,false);\n\tvar eCur = parseSEInput(elemEst, false);\n\tif (sCur == null)\n\t\tsCur=0;\n\tif (eCur == null)\n\t\teCur=0;\n\ts = parseFixedFloat(s + sCur);\n\te = parseFixedFloat(e + eCur);\n\tif (s == 0)\n\t\ts = \"\";\n\tif (e == 0)\n\t\te = \"\";\n\t$(\"#plusCardCommentDays\").val(g_strNowOption);\n\telemSpent.val(s);\n\telemEst.val(e);\n\t$(\"#plusCardCommentComment\").val(comment);\n\tvar elemEnter = $(\"#plusCardCommentEnterButton\");\n\tvar classBlink = \"agile_box_input_hilite\";\n\telemEnter.focus().addClass(classBlink);\n\tclearBlinkButtonInterval();\n\tg_intervalBlinkButton = setInterval(function () {\n\t\tg_cBlinkButton++;\n\n\t\tif (elemEnter.hasClass(classBlink))\n\t\t\telemEnter.removeClass(classBlink);\n\t\telse {\n\t\t\telemEnter.addClass(classBlink);\n\t\t\tif (g_cBlinkButton > 2) //do it here to it remains yellow\n\t\t\t\tclearBlinkButtonInterval();\n\t\t}\n\t}, 500);\n}",
"function parse_title() {\n\n // Get the title depends on format (paperbacak/hardcover/kindle)\n var title = $('span#productTitle').text();\n if (!title) {\n title = $('span#ebooksProductTitle').text();\n }\n\n var bracket = title.indexOf('(');\n // If title contains brackets then remove as it is not part of title\n if (bracket > 0) {\n // Cut out the actual title and remove trailing space between the\n // actual title and brackets\n title = title.substr(0, bracket - 1);\n }\n return title;\n}",
"function getPriceOnly(text) {\n\tif (text.indexOf(\"stop loss\") > -1) {\n\t\ttext = text.substring(0, text.indexOf(\"stop loss\"));\n\t}\n\treturn text.replace(/[^0-9.]/g, \"\");\n}",
"getSSE() {\n\t\tlet SSE = 0;\n\t\tfor (let n = 0; n < this.numNodes; n++) {\n\t\t\tSSE += Math.pow(this.myError[n], 2);\n\t\t}\n\t\treturn SSE;\n\t}",
"function format_selected_tags (htag)\n { var rx = /<p class=\"stag\" id=\"(.*?)\">{1}/\n tags = '';\n while (match = rx.exec(htag))\n { tags = tags + match[1] +';';\n htag = htag.replace (match[0],''); \n } \n return tags.substring (0,tags.length-1);\n }",
"function parse(str) {\n\tif (str[0] !== '=') {\n\t\treturn;\n\t}\n\ttry {\n\t\tvar list = parser(str.slice(1).trim());\n\t\treturn {\n\t\t\tweights: pluck(list, 0),\n\t\t\tgenes: pluck(list, 1)\n\t\t};\n\t} catch (e) {\n\t\tconsole.log('parsing error', e);\n\t}\n\treturn;\n}",
"function parse_summary() {\n\n var desc_elms = $('iframe#bookDesc_iframe').contents();\n var desc_text_elms = $(desc_elms).find('div#iframeContent').contents();\n var desc_text = $(desc_text_elms).map(function(i, e) {\n if (this.nodeType === 3) { return $(this).text(); }\n else { return $(this).prop('outerHTML'); }\n }).toArray().join('');\n\n return desc_text;\n}",
"function parseDeFile(tsvText, isAuthorDe=false) {\n const deGenes = []\n const tsvLines = tsvText.split(newlineRegex)\n for (let i = 1; i < tsvLines.length; i++) {\n const tsvLine = tsvLines[i]\n if (tsvLine === '') {continue}\n if (!isAuthorDe) {\n // Each element in this array is DE data for the gene in this row\n const [\n index, // eslint-disable-line\n name, score, log2FoldChange, pval, pvalAdj, pctNzGroup, pctNzReference\n ] = tsvLines[i].split('\\t')\n const deGene = {\n score, log2FoldChange, pval, pvalAdj, pctNzGroup, pctNzReference\n }\n Object.entries(deGene).forEach(([k, v]) => {\n // Cast numeric string values as floats\n deGene[k] = parseFloat(v)\n })\n deGene.name = name\n deGenes.push(deGene)\n } else {\n // Each element in this array is DE data for the gene in this row\n const [\n index, // eslint-disable-line\n name, log2FoldChange, qval, mean\n ] = tsvLines[i].split('\\t')\n const deGene = {\n // TODO (SCP-5201): Show significant zeros, e.g. 0's to right of 9 in 0.900\n log2FoldChange: round(log2FoldChange, 3),\n qval: round(qval, 3),\n mean: round(mean, 3)\n }\n Object.entries(deGene).forEach(([k, v]) => {\n // Cast numeric string values as floats\n deGene[k] = parseFloat(v)\n })\n deGene.name = name\n deGenes.push(deGene)\n }\n }\n\n return deGenes\n}",
"function format_tags (tags, nct)\n{ ftags = new Array ();\n for (var i=0;i<tags.length; i++)\n { t = tags[i][0]\n if (t.charAt(3) == ':')\n { t = t.substring(4); }\n var ct = {text:t, weight:parseFloat(tags[i][1]), html:{class: 'cloud_label', value: tags[i][0]}, \n\t handlers:{click:function() { refine_results($(this).attr('value'), true, nct); }}};\n ftags[i] = ct\n }\n return ftags;\n}",
"function parseTags(body) {\n const tagIndex = body.indexOf(\"#\");\n let tags = [];\n if (tagIndex >= 0) {\n tags = body.substring(tagIndex, body.length).split(\"#\");\n tags = tags.reduce((result, tag) => {\n tag = tag.trim();\n if (tag.length > 0) \n result.push(tag);\n return result;\n }, []);\n }\n return tags;\n}",
"function isSaya(msg){\n let arr = msg.querySelectorAll(\"span\");\n //Loop through array\n for (let i = 0; i < arr.length; i++){\n console.log(arr[i]);\n try {\n if (arr[i].attributes[0].nodeValue == \"Saya:\"){\n return true;\n }\n } catch(error){\n continue;\n console.log(error);\n \n }\n }\n return false;\n}",
"parse(_stUrl) {\n Url.parse(_stUrl, true);\n }",
"function baynote_getSummaryFromParagraph() {\n\tvar summary = \"\";\n\tvar paragraphs = document.getElementsByTagName(\"p\");\n\tif (!paragraphs){ return \"\";}\n\t\n\tfor (var i = 0; i < paragraphs.length; i++) {\n\t\tif (!paragraphs[i]){ return \"\";}\n\t\tif (paragraphs[i].innerHTML != \"\") {\n\t\t\tif (summary != \"\"){ summary = summary + \" \";}\n\t\t\tsummary = summary + baynote_removeHtml(paragraphs[i].innerHTML);\n\t\t\tif (summary.length > 180){ summary = summary.substring(0,180);}\n\t\t}\n\t\tif (summary.length > 80){ return summary;}\n\t}\n\treturn summary;\n}",
"function parseEntityTags(md) {\n if ( ! md ) {\n return [];\n }\n\n let tags = [];\n\n // Hook walkTokens and if we see bold or italic anywhere in the tree,\n // note down as a tag.\n let strongs = [];\n let ems = [];\n marked(\n md, \n { \n walkTokens: token => {\n // console.log( token );\n if ( token.type === 'em' ) {\n strongs.push( token.text );\n }\n if ( token.type === 'strong' ) {\n strongs.push( token.text );\n }\n }\n }\n );\n\n // Single array of all bold/italic items => tags.\n tags = strongs.concat(ems);\n\n // Process each tag content to ensure is a single \"word\".\n tags = tags.map(tag => {\n let stripped = tag;\n // strip html entities\n stripped = stripped.replace(/&.+;/g, '');\n // strip nonword chars\n stripped = stripped.replace(/\\W/g, '');\n // console.log( `Saving stripped tag: ${ stripped }`)\n return stripped;\n });\n // console.log(tags);\n\n return tags;\n}",
"function detectStore(dom) {\r\n var site_name = $(dom).find('meta[property=\"og:site_name\"]')!==undefined ? $(dom).find('meta[property=\"og:site_name\"]').attr('content') : null;\r\n if (site_name == null) {\r\n if (/Mage\\.Cookies\\.domain/.test($(dom).text())) {site_name = \"Magento\";}\r\n if (/Amazon\\.com/.test($(dom).find('.nav_last').text())) {site_name = \"Amazon\";}\r\n if ($(dom).find('link[rel^=\"shortcut\"]') && (/demandware/.test($(dom).find('link[rel^=\"shortcut\"]').attr('href')))) {site_name = \"Demandware\";}\r\n if ($(dom).find(\"input[name^=\\\"\\/atg\\/commerce\\\"]\").length>0) {site_name = \"ATGCommerce\";}\r\n }\r\n switch (site_name){\r\n case 'Walmart.com':\r\n return new WalmartParser();\r\n case 'Best Buy':\r\n return new BestBuyParser();\r\n case 'Magento':\r\n return new MagentoParser();\r\n case 'Target':\r\n return new TargetParser();\r\n case 'Amazon':\r\n return new AmazonParser();\r\n case 'Demandware':\r\n return new DemandwareParser();\r\n case 'ATGCommerce':\r\n return new ATGCommerceParser();\r\n default: //magento\r\n return null;\r\n }\r\n}",
"function parseMixed(nest) {\n return (parse, input, fragments, ranges) =>\n new MixedParse(parse, nest, input, fragments, ranges)\n }",
"function parse_ISBN13() {\n\n var prod_details_elms = $('div#detail-bullets table#productDetailsTable div.content ul');\n var isbn_text = $(prod_details_elms).find('li:has(b:contains(\"ISBN-13:\"))').text();\n\n isbn_text = isbn_text.split(' ')[1];\n return isbn_text;\n}",
"get takesValueFormattedTag() {\n return this._memoize('takesValueFormattedTag', () => {\n const takesValueType = 'takesValue'\n for (const ancestor of ParsedHedTag.ancestorIterator(this.formattedTag)) {\n const takesValueTag = replaceTagNameWithPound(ancestor)\n if (this.schema.tagHasAttribute(takesValueTag, takesValueType)) {\n return takesValueTag\n }\n }\n return null\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The grinder is the lever on the side. We might want to update this to be more direct (e.g., pull the lever).. right now you just tap it. This object has methods for making the "colour mixing process" happen. | function makeGrinder(args) {
var layer = new Layer({imageName: "lever"})
layer.touchEndedHandler = function(touchSequence) {
new Sound({name: "beep-boop"}).play()
rotateColors()
afterDuration(0.25, function() {
moveColors()
})
afterDuration(1.50, function() {
dripColors()
})
}
function rotateColors() {
red.rotateBricks()
green.rotateBricks()
blue.rotateBricks()
}
function moveColors() {
red.moveToMixer()
green.moveToMixer()
blue.moveToMixer()
}
function dripColors() {
var bgColor = currentColor()
var totalCount = red.totalCount() + green.totalCount() + blue.totalCount()
var totalDripDuration = 2 // seconds
var timeIntervalBetweenDrips = totalDripDuration / totalCount
for (var counter = 0; counter < totalCount; counter++) {
afterDuration(counter * timeIntervalBetweenDrips, function() {
var drip = new Layer()
var size = 24
drip.size = new Size({width: size, height: size})
drip.cornerRadius = drip.height / 2.0
drip.backgroundColor = bgColor
drip.scale = 0.01
drip.position = new Point({x: args.tap.frameMaxX, y: args.tap.frameMaxY})
drip.animators.scale.target = new Point({x: 1, y: 1})
drip.animators.position.target = new Point({x: args.bowl.x, y: args.bowl.y + 20})
})
}
red.removeAllBricks()
green.removeAllBricks()
blue.removeAllBricks()
}
return layer
} | [
"changeColor() {\n this.currentColor = this.intersectingColor;\n }",
"ColorUpdate(colors) {\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(127, 127, 127, 255));\n colors.push(vec4(10, 10, 10, 210));\n colors.push(vec4(127, 127, 127, 255));\n\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n \n if (Sky.instance.GlobalTime >= 9 && Sky.instance.GlobalTime < 19){\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 255));\n // StreetLamp Light turn off\n // ColorUpdate => Black\n }\n else {\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 255));\n // StreetLamp Light turn on\n // ColorUpdate => Yell Light\n }\n }",
"setRedLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet currentGreenLights = this.config.getDirections()[this.getDirectionIndex()];\n\n // Loop through the greenLights and set the rest to red lights\n\t\tfor (let direction in this.trafficLights) {\n\t\t\tlet elementId = this.trafficLights[direction].name;\n\t\t\tif (currentGreenLights.indexOf(elementId) >= 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.trafficLights[direction].color = TRAFFIC_LIGHT_RED;\n\t\t}\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"function startColor () {\n\t\treturn {\n\t\t\tr: 255,\n\t\t\tg: 255 * Math.random(),\n\t\t\tb: 75\n\t\t};\n\t}",
"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}",
"setFaceColor ( face, RGB) {\n\t\t// debug\n\t\t//console.log(\"atomicGLskyBox(\"+this.name+\")::setFaceColor\");\n\t\tvar r = RGB[0];\n\t\tvar g = RGB[1];\n\t\tvar b = RGB[2];\n\t\t\n\t\t// switch face\n\t\tswitch(face){\n\t\t\tcase \"Front\":\n\t\t\t\tthis.colorsArray[0] =r;\n\t\t\t\tthis.colorsArray[1] =g;\n\t\t\t\tthis.colorsArray[2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[3] =r;\n\t\t\t\tthis.colorsArray[4] =g;\n\t\t\t\tthis.colorsArray[5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[6] =r;\n\t\t\t\tthis.colorsArray[7] =g;\n\t\t\t\tthis.colorsArray[8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[9] =r;\n\t\t\t\tthis.colorsArray[10] =g;\n\t\t\t\tthis.colorsArray[11] =b;\t\t\t\n\t\t\tbreak;\n\n\t\t\tcase \"Back\":\n\t\t\t\tthis.colorsArray[12+0] =r;\n\t\t\t\tthis.colorsArray[12+1] =g;\n\t\t\t\tthis.colorsArray[12+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[12+3] =r;\n\t\t\t\tthis.colorsArray[12+4] =g;\n\t\t\t\tthis.colorsArray[12+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[12+6] =r;\n\t\t\t\tthis.colorsArray[12+7] =g;\n\t\t\t\tthis.colorsArray[12+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[12+9] =r;\n\t\t\t\tthis.colorsArray[12+10] =g;\n\t\t\t\tthis.colorsArray[12+11] =b;\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"Top\":\n\t\t\t\tthis.colorsArray[24+0] =r;\n\t\t\t\tthis.colorsArray[24+1] =g;\n\t\t\t\tthis.colorsArray[24+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[24+3] =r;\n\t\t\t\tthis.colorsArray[24+4] =g;\n\t\t\t\tthis.colorsArray[24+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[24+6] =r;\n\t\t\t\tthis.colorsArray[24+7] =g;\n\t\t\t\tthis.colorsArray[24+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[24+9] =r;\n\t\t\t\tthis.colorsArray[24+10] =g;\n\t\t\t\tthis.colorsArray[24+11] =b;\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"Bottom\":\n\t\t\t\tthis.colorsArray[36+0] =r;\n\t\t\t\tthis.colorsArray[36+1] =g;\n\t\t\t\tthis.colorsArray[36+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[36+3] =r;\n\t\t\t\tthis.colorsArray[36+4] =g;\n\t\t\t\tthis.colorsArray[36+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[36+6] =r;\n\t\t\t\tthis.colorsArray[36+7] =g;\n\t\t\t\tthis.colorsArray[36+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[36+9] =r;\n\t\t\t\tthis.colorsArray[36+10] =g;\n\t\t\t\tthis.colorsArray[36+11] =b;\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"Left\":\n\t\t\t\tthis.colorsArray[48+0] =r;\n\t\t\t\tthis.colorsArray[48+1] =g;\n\t\t\t\tthis.colorsArray[48+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[48+3] =r;\n\t\t\t\tthis.colorsArray[48+4] =g;\n\t\t\t\tthis.colorsArray[48+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[48+6] =r;\n\t\t\t\tthis.colorsArray[48+7] =g;\n\t\t\t\tthis.colorsArray[48+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[48+9] =r;\n\t\t\t\tthis.colorsArray[48+10] =g;\n\t\t\t\tthis.colorsArray[48+11] =b;\n\t\t\tbreak;\t\t\t\t\n\t\t\tcase \"Right\":\n\t\t\t\tthis.colorsArray[60+0] =r;\n\t\t\t\tthis.colorsArray[60+1] =g;\n\t\t\t\tthis.colorsArray[60+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[60+3] =r;\n\t\t\t\tthis.colorsArray[60+4] =g;\n\t\t\t\tthis.colorsArray[60+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[60+6] =r;\n\t\t\t\tthis.colorsArray[60+7] =g;\n\t\t\t\tthis.colorsArray[60+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[60+9] =r;\n\t\t\t\tthis.colorsArray[60+10] =g;\n\t\t\t\tthis.colorsArray[60+11] =b;\n\t\t\tbreak;\t\n\t\t\tcase \"All\":\n\t\t\t\tthis.colorsArray = [\n\t\t\t\t\t// Front face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Back face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Top face \n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Bottom face : floor\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Left face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Right face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t];\t\n\t\t\tbreak;\t\t\n\t\t}\n\t}",
"function passTheColor () {\n//\tDebug.Log(\"Got in passTheColor\");\n//\tDebug.Log(inputUnit);\n\t// If inputWireUnit has a value (Mixxit, pengo, and SaraDT_)\n\tif (inputUnit != null) {\n\t\t// Debug.Log(gameObject.name + \"'s input is \" + inputUnit.name);\n\t\t// make that unit's myColor value into this unit's myColor value\n\t\tmyColor = inputUnit.gameObject.GetComponent.<ColorOfLAdjacent>().myColor;\n\t\trenderer.material.color = myColor;\n\t\t// Debug.Log(renderer.material.GetColor(\"_Color\"));\n\t}\n\n\t// If outputWire has a value\n\tif (outputUnit != null) {\n\t\tDebug.Log(gameObject.name + \"'s output is to \" + outputUnit.name);\n\t\t// make that unit run the same method\n\t\toutputUnit.GetComponent.<ColorOfLAdjacent>().passTheColor();\n\t}\n}",
"blendSide(data, left) {\n let _sideLength = data.data.length\n let _sourceX = left ? 0 : this._imageWidth - BLEND\n let _sourceHeight = this._imageHeight + this._offset\n //let _sourceData = this._ctx.getImageData(0, 0, this._imageWidth, this._imageHeight + this._offset)\n let _sourceData = this._ctx.getImageData(_sourceX, 0, BLEND, _sourceHeight)\n\n let _total = 4 * _sourceHeight * BLEND\n //let _total = 4 * this._imageWidth * BLEND\n let pixels = _total;\n let _weight = 0\n let _wT = BLEND\n /*while (pixels--) {\n _sourceData.data[pixels] = Math.floor(Math.random() * 255) // _currentPixelR + _newPixelR\n //_sourceData.data[_p + 1] = 0 // _currentPixelG + _newPixelG\n //_sourceData.data[_p + 2] = 0 //_currentPixelB + _newPixelB\n //_sourceData.data[_p + 3] = 255 //_currentPixelA + _newPixelA\n }\n this._ctx.putImageData(_sourceData, 0, 0)\n return*/\n\n let i = left ? 0 : _total\n i = 0\n let l = left ? _total : 0\n l = _total\n let _a = left ? 4 : -4\n _a = 4\n for (i; i < l; i += _a) {\n let _weight = 1.\n let _roll = i % _sideLength\n _weight = i % (BLEND * 4) / (BLEND * 4)\n\n if (!left) {\n _weight = 1 - _weight\n //_weight = 0\n }\n\n let _newPixelR = Math.floor(data.data[_roll] * (1 - _weight))\n let _newPixelG = Math.floor(data.data[_roll + 1] * (1 - _weight))\n let _newPixelB = Math.floor(data.data[_roll + 2] * (1 - _weight))\n let _newPixelA = Math.floor(data.data[_roll + 3])\n\n let _currentPixelR = Math.floor(_sourceData.data[i] * _weight)\n let _currentPixelG = Math.floor(_sourceData.data[i + 1] * _weight)\n let _currentPixelB = Math.floor(_sourceData.data[i + 2] * _weight)\n let _currentPixelA = Math.floor(_sourceData.data[i + 3])\n\n _sourceData.data[i] = _newPixelR + _currentPixelR\n _sourceData.data[i + 1] = _newPixelG + _currentPixelG\n _sourceData.data[i + 2] = _newPixelB + _currentPixelB\n _sourceData.data[i + 3] = 255\n }\n /*console.log(_total, _sourceData.data.length);\n for (let i = 0; i < _wT * 4; i += 3) {\n _weight = i / _wT\n for (let j = 0; j < _sourceHeight * 4; j += 4) {\n let _p = i * j\n let _newPixelR = Math.floor(data.data[_p] * (_weight))\n let _newPixelG = Math.floor(data.data[_p + 1] * (_weight))\n let _newPixelB = Math.floor(data.data[_p + 2] * (_weight))\n let _newPixelA = Math.floor(data.data[_p + 3] * (_weight))\n\n let _currentPixelR = Math.floor(_sourceData.data[_p] * (1 - _weight))\n let _currentPixelG = Math.floor(_sourceData.data[_p + 1] * (1 - _weight))\n let _currentPixelB = Math.floor(_sourceData.data[_p + 2] * (1 - _weight))\n let _currentPixelA = Math.floor(_sourceData.data[_p + 3] * (1 - _weight))\n\n\n _sourceData.data[_p] = 255 // _currentPixelR + _newPixelR\n _sourceData.data[_p + 1] = 0 // _currentPixelG + _newPixelG\n _sourceData.data[_p + 2] = 0 //_currentPixelB + _newPixelB\n _sourceData.data[_p + 3] = 255 //_currentPixelA + _newPixelA\n }\n }*/\n this._ctx.putImageData(_sourceData, _sourceX, 0)\n }",
"static Purple() {\n return new Color3(0.5, 0, 0.5);\n }",
"static Purple() {\n return new Color4(0.5, 0, 0.5, 1);\n }",
"function getGearLightShade(x,y,s){\n\tvar result=\"M\"+(x+Math.cos(Math.PI/12)*s/2)+\" \"+(y-Math.sin(Math.PI/12)*s/2)+\",L\"+(x+Math.cos(Math.PI/12)*s/2)+\" \"+(y-Math.sin(Math.PI/12)*s/2+s/12)+\",L\"+(x+Math.cos(Math.PI/12)*s/3)+\" \"+(y-Math.sin(Math.PI/12)*s/3+s/12)+\",L\"+(x+Math.cos(Math.PI/12)*s/3)+\" \"+(y-Math.sin(Math.PI/12)*s/3)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI/12)*s/2)+\" \"+(y-Math.sin(-Math.PI/12)*s/2)+\",L\"+(x+Math.cos(-Math.PI/12)*s/2)+\" \"+(y-Math.sin(-Math.PI/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/2)+\" \"+(y-Math.sin(-Math.PI/4)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/2)+\" \"+(y-Math.sin(-Math.PI/4)*s/2)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*5/12)*s/3)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/3)+\",L\"+(x+Math.cos(-Math.PI*5/12)*s/3)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/3+s/12)+\",S\"+(x+Math.cos(-Math.PI/3)*s/3)+\" \"+(y-Math.sin(-Math.PI/3)*s/3+s/12)+\" \"+(x+Math.cos(-Math.PI/4)*s/3)+\" \"+(y-Math.sin(-Math.PI/4)*s/3+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/3)+\" \"+(y-Math.sin(-Math.PI/4)*s/3)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*5/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/2)+\",L\"+(x+Math.cos(-Math.PI*5/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*7/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*7/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*7/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*7/12)*s/2)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*3/4)*s/3)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/3)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/2)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/2)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/2)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/3)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/3+s/12)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+s/6)+\" \"+y+\",S\"+x+\" \"+(y-s/6)+\" \"+(x-s/6)+\" \"+y+\",A\"+(s/6)+\" \"+(s/6)+\" 1 1 1 \"+(x+s/6)+\" \"+y;\n\t\n\treturn result;\n}",
"changeColorRed() {\n this.planet.loadTexture('planetred');\n this.mini.loadTexture('planetred');\n }",
"displayBrushers(){\r\n\r\n if(!this.audioAnalyser) return;\r\n\r\n this.audioAnalyser.analyser.getByteTimeDomainData(this.audioAnalyser.dataArray);\r\n\r\n let amout;\r\n for (let i = 0; i < this.audioAnalyser.bufferLength; i++) {\r\n\r\n\r\n amout = this.audioAnalyser.dataArray[i]/2;\r\n\r\n if(amout > 80 && Math.random()>0.85){\r\n\r\n if(this.popText[i] ){\r\n this.popText[i].color = `rgb(${this.rgb[0]}, ${this.rgb[1] } , ${this.rgb[2]})`;\r\n this.popText[i].isActif = true;\r\n } \r\n } \r\n\r\n if(amout > 70){\r\n \r\n if(Math.random()>0.995){\r\n this.rgb[0] = Math.floor(Math.random()* 200);\r\n this.rgb[1] = Math.floor(Math.random()* 200 );\r\n this.rgb[2] = Math.floor(Math.random()* 200 );\r\n this.currentVideo.rgb = this.rgb;\r\n \r\n }\r\n\r\n\r\n if(this.brushers[i] && !this.brushers[i].isActive ){\r\n\r\n this.brushers[i].start(); \r\n }\r\n \r\n }\r\n\r\n if(this.brushers[i]){\r\n this.brushers[i].draw();\r\n \r\n }\r\n\r\n if(this.popText[i] && this.popText[i].isActif) this.popText[i].draw();\r\n \r\n \r\n }\r\n\r\n }",
"setGreenLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_GREEN;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"function randLightColor() {\r\n\tvar rC = Math.floor(Math.random() * 256);\r\n\tvar gC = Math.floor(Math.random() * 256);\r\n\tvar bC = Math.floor(Math.random() * 256);\r\n\twhile (Math.max(rC, gC, bC) < 200) {\r\n\t\trC = Math.floor(Math.random() * 256);\r\n\t\tgC = Math.floor(Math.random() * 256);\r\n\t\tbC = Math.floor(Math.random() * 256);\r\n\t}\r\n\treturn tColor(rC, gC, bC, 1.0);\r\n}",
"setYellowLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_YELLOW;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"function updateLookingGlass() {\n\n Main.lookingGlass = new LookingGlass.LookingGlass();\n Main.lookingGlass.slaveTo(Main.messageTray.actor.get_parent());\n}",
"function renderPollinationGlow( pollinationAnimation ) {\n var pa = pollinationAnimation;\n var glowDuration = pa.f1 === pa.f2 ? 240 : 120; \n if ( !pa.pollenPadGlowHasBegun ) {\n pa.f2.clH = C.pg; // changes pollen pad color to temporary glow color\n pa.pollenPadGlowHasBegun = true;\n }\n if ( pa.pollenPadGlowHasBegun && !pa.pollenPadGlowComplete ) {\n pa.f2.clH = Tl.rgbaCs( C.pg, C.pp, pa.f2.clH, glowDuration ); // fades pollen pad color back to normal\n pa.glowIterationCount++;\n if ( pa.glowIterationCount === glowDuration ) { \n pa.pollenPadGlowComplete = true; \n }\n }\n}",
"getYellowLightDuration() {\n\t\treturn YELLOW_LIGHT_DURATION;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return true array of splitted arguments | function splitArguments() {
var splitedArray, ii;
if (!arguments[0]) {
throw new WrongArgumentException("Can't parse arguments, cause it doesn't exist!");
}
splitedArray = new Array();
for (ii = 0; ii < arguments[0].length; ii++) {
splitedArray.push(arguments[0][ii]);
}
return splitedArray;
} | [
"isListMatch(value) {\n if (!value) return false;\n const v = this.isCaseSensitive ? value : value.toLowerCase();\n let isMatch = false;\n for (const value of v.split(',')) {\n const v = value.trim();\n if ((this.re && v.match(this.re) !== null) || this.arg === v) {\n isMatch = true;\n break;\n }\n }\n return this.not ? !isMatch : isMatch;\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 destroyer(arr) {\n // console.log(arr);\n // [ 1, 2, 3, 1, 2, 3 ]\n\n\n // console.log(arguments);\n // [Arguments] { '0': [ 1, 2, 3, 1, 2, 3 ], '1': 2, '2': 3 }\n\n\n // const argsArr = Array.from(arguments);\n // console.log(argsArr)\n // [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ]\n\n \n // ANOTHER WAY TO DO IT\n // const argsArr = [...arguments]; //this is called spreading. We're separating all the arguments using commas.\n // console.log(argsArr)\n // [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ]\n\n const argsArr = [...arguments].slice(1)\n\n const filteredArr = [];\n for (let i = 0; i < arr.length; i++) {\n if (!argsArr.includes(arr[i])) {\n filteredArr.push(arr[i])\n } \n }\n return filteredArr\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 }",
"function separeteAnd(value) {\n if (typeof value == 'boolean') {\n return value\n }\n if (value.indexOf('&&') > 0) {\n let res = value.split('&&')\n return res\n } else if (value.indexOf('&') > 0) {\n let res = value.split('&')\n return res\n } else if (value.indexOf('&&') > 0) {\n let res = value.split('&&')\n return res\n } else if (value.indexOf('&') > 0) {\n let res = value.split('&')\n return res\n }\n return value\n}",
"canExecute(args) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (args.length > 1) {\n\t\t\t\tthis.$errors.failWithoutHelp(\"This command accepts only one argument.\");\n\t\t\t}\n\n\t\t\tif (args.length) {\n\t\t\t\tresolve(true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.$errors.failWithoutHelp(\"You should pass at least one argument to 'hello-world' command.\");\n\t\t});\n\t}",
"function command_array_creator(arr){\n let new_arr = [];\n arr.forEach(str => {\n new_arr.push(command_extractor(str));\n })\n return new_arr;\n //if ['turn off 812,389 through 865,874', 'toggle 205,417 through 703,826'] was given as input\n //the function would return [ [ 'turnoff', [ 812, 389 ], [ 865, 874 ] ], [ 'toggle', [ 205, 417 ], [ 703, 826 ] ] ]\n}",
"static areIdentical(){\n let temp\n\n for(let i = 0; i < arguments.length; i++){\n let argument = arguments[i]\n\n // handle NaN\n if(isNaN(argument.h)) argument.h = argument.h.toString()\n if(isNaN(argument.m)) argument.m = argument.m.toString()\n\n // handle string input\n if(typeof argument.h === \"string\") argument.h = parseInt(argument.h)\n if(typeof argument.m === \"string\") argument.m = parseInt(argument.m)\n\n // if temp is empty -> this is the first argument, store the first temp\n if(!temp){\n temp = argument\n continue\n }\n\n // if the temp and the current argument are not identical, return false\n if(argument.h !== temp.h || argument.m !== temp.m || argument.pm !== temp.pm) return false\n\n // store the current argument as the new temp\n temp = argument\n }\n\n return true\n }",
"function validarArgumentos(args, msg){\n if(process.argv.length !== (2+args)){\n console.log(msg);\n process.exit(2);\n }\n return true;\n}",
"function numbers() {\n return Array.prototype.every.call(arguments, function(argument) {\n return typeof argument === 'number';\n });\n}",
"receivedCall(args, times) {\n const minRequired = times || 1;\n if (args.length === 0 && this.hasEmptyCalls(minRequired)) {\n return true;\n }\n const setupArgs = this.convertArgsToArguments(args);\n let matchCount = 0;\n for (const call of this.calls) {\n const isMatch = this.argumentsMatch(setupArgs, call);\n if (isMatch === true) {\n matchCount++;\n if (matchCount >= minRequired) {\n return true;\n }\n }\n }\n return false;\n }",
"execute(array, before = \"\", after = \"\")\n {\n let output = \"\";\n array.forEach((element, index) => {\n let text = `${before}${element}${after}`\n\n if(index === 0) output += `${text}`;\n else if (index === array.length-1) output += ` and ${text}`\n else output += `, ${text}`\n });\n\n return output;\n }",
"function comeArr(n1, n2, ...other) {\nconsole.log('n1:', n1) // 1\nconsole.log('n2:', n2) // 2\nconsole.log('other:', other) // [ 3, 4 ]\n}",
"function to_bool_arr_cutoff(cutoff){\n return new Function(\"arg\", \"c = \" + cutoff, \"return arg.toString(2).split('').map(elt => elt === '1').slice(0, c);\");\n}",
"isOperationList(value) {\n return Array.isArray(value) && value.every(val => Operation.isOperation(val));\n }",
"_validateAndParseCommandArguments() {\n const validationErrors = this._validateCommandArguments();\n\n if (validationErrors.length > 0) {\n _forEach(validationErrors, (error) => {\n throw error;\n });\n }\n }",
"function allStringsPass(strings, test) {\n // YOUR CODE BELOW HERE //\n // I = array of strings and test function\n // O = Boolean\n // C = ALL strings must pass to return true\n // use for loop to loop through entire array of strings\n // pass strings into test function\n // test with if condition to see if any strings do not pass and return false\n \n for (var i = 0; i < strings.length; i++) { \n var resultTest = test(strings[i]);\n if(resultTest === false) {\n return false;\n }\n }\n return true;\n}",
"getAllArgsToInterpolateSubmobject() {\n let mobjectHierarchies = [];\n for (let mobjectCopy of this.getCopiesForInterpolation()) {\n let hierarchy = mobjectCopy.getMobjectHierarchy();\n let hierarchyMembersWithPoints = hierarchy.filter(\n submob => submob.points().length > 0\n );\n mobjectHierarchies.push(hierarchyMembersWithPoints);\n }\n let argsList = [];\n for (let i = 0; i < mobjectHierarchies[0].length; i++) {\n argsList.push(mobjectHierarchies.map(h => h[i]));\n }\n return argsList;\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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Placement > [InitWorker, ...] Convert the received Placement into an InitWorkerList, with each WorkerPlace in the list converted to the equivalent InitWorker. | function jsonToInitWorkerList(placement) {
return placement.map(jsonToInitWorker);
} | [
"function jsonToInitWorker(workerPlace) {\n let workerRequest = jsonToWorkerRequest(workerPlace[0]);\n return { player: workerRequest.player, x: workerPlace[1], y: workerPlace[2] };\n}",
"placeInitialWorker(existingWorkers) {\n return this.clientRequest(existingWorkers, MessageConverter.initWorkerListToJson,\n MessageConverter.jsonToPlaceRequest);\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 initWorkouts(data) {\n for(let i = 0; i < data.length; i++) {\n createWorkout(data[i]);\n }\n}",
"setupChefWorker() {\n for (let i = this.chefWorkers.length - 1; i >= 0; i--) {\n this.removeChefWorker(this.chefWorkers[i]);\n }\n\n this.addChefWorker();\n this.setupDishWorker();\n }",
"function Placement(props) {\n return __assign({ Type: 'AWS::IoT1Click::Placement' }, props);\n }",
"function placeArmy(army){\n army.forEach(piece => {\n piece.place()\n });\n}",
"function populatePossibleMoves(_callback) {\n // Create new Array instance\n possibleMovesModel = new Array();\n // Query database for list of dbClasses and their success rates and totals\n $.getJSON('/getDBTable', function(data) {\n data.forEach(obj => {\n let id = obj.Id;\n let dLeft = obj.dLeft;\n let dUp = obj.dUp;\n let dRight = obj.dRight;\n let dDown = obj.dDown;\n let dSuccessful = obj.dSuccessful;\n let dTotal = obj.dTotal;\n // Add these classes to possible moves model\n possibleMovesModel.push({id : id, dLeft : dLeft, dUp : dUp, dRight : dRight, dDown : dDown, dSuccessful : dSuccessful, dTotal : dTotal});\n })\n console.log(\"possibleMoves: \");\n console.log(possibleMovesModel);\n _callback(data);\n })\n }",
"get supportedPlacementStrategies() {\n return this.getListAttribute('supported_placement_strategies');\n }",
"function or_place_all_orders()\n{\n\t\n\t//loop for each supplier and place order for only those suppliers which are not placed yet \n\t$.each (supplier_orders_list, function (supplier_id, supplier_order_detail)\n\t{\n\t\tif(typeof(supplier_order_detail)!='undefined')\n\t\t{\n\t\t\tif (!supplier_order_detail.ordered)\n\t\t\t{\n\t\t\t\t//Place order for the supplier\n\t\t\t\t//alert(supplier_id);\n\t\t\t\t//alert(supplier_orders_list[supplier_id].products_list);\n\t\t\t\tor_place_order(supplier_id);\n\t\t\t}\n\t\t}\n\t});\n}",
"function getAllPlacesByState(states, result, callback) {\n\t\n\tvar items_processed = 0;\n\tif (states.length !== 0) {\n\t\t\tstates.map( (state_id) => { \n\n\t\t\t\treqStates(`${API_URL}/states/${state_id}/places`, (json) => {\n\t\t\t\t\titems_processed++;\n\t\t\t\t\tconst places = new Schema('places');\n\t\t\t\t\tlet norm_json = normalize(json, arrayOf(places));\n\t\t\t\t\tconsole.log(\"ta\", norm_json.entities);\n\t\t\t\t\tObject.assign(result.places, norm_json.entities.places);\n\t\t\t\t\tif (items_processed === states.length) {\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t});\n\t\t\t\n\t\t}\n\t\telse {\n\t\t\tcallback();\n\t\t}\n}",
"updateItineraryAndMapByArray(places){\n let newMarkerPositions = [];\n this.setState({placesForItinerary: places});\n places.map((place) => newMarkerPositions.push(L.latLng(parseFloat(place.latitude), parseFloat(place.longitude))));\n this.setState({markerPositions: newMarkerPositions});\n this.setState({reverseGeocodedMarkerPositions: []});\n }",
"initWorker(worker) {\r\n worker.setRetryTime(FATUS_EQ_RETRY_TIME);\r\n worker.setMaxAttempts(FATUS_WRK_RETRY_ATTEMP);\r\n worker.setStackProtection(FATUS_WRK_STACK_TRSHLD);\r\n worker.setReservationTime(FATUS_JOB_RESERV_TIME);\r\n worker.setMaxFails(FATUS_MAX_FAIL);\r\n }",
"function preprocessDelayedWorks() {\n worksById = {};\n\n angular.forEach($scope.works, function (work) {\n worksById[work.id] = work;\n\n work.delayRestricted = {};\n angular.forEach(work.jobs, function (job) {\n if (job.jobs !== undefined) {\n job = job.jobs[0];\n }\n\n var proto = $scope.config.jobsByType[job.type];\n if (proto && proto.delayRestricted) {\n if (proto.delayRestricted['update']) {\n work.delayRestricted['update'] = true;\n }\n if (proto.delayRestricted['delete']) {\n work.delayRestricted['delete'] = true;\n }\n }\n });\n });\n }",
"function jsonToBoard(boardSpec) {\n let workerList = [];\n let initBoard = [];\n\n if (boardSpec.length < constants.BOARD_HEIGHT) {\n let initHeight = boardSpec.length;\n for (let i = 0; i < constants.BOARD_HEIGHT - initHeight; i++) {\n boardSpec.push([0,0,0,0,0,0]);\n }\n }\n\n boardSpec.forEach((r) => {\n if (r.length < constants.BOARD_WIDTH) {\n let initWidth = r.length;\n for (let i = 0; i < constants.BOARD_WIDTH - initWidth; i++) {\n r.push(0);\n }\n }\n })\n\n for (let i = 0; i < boardSpec.length; i++) {\n initBoard.push([]);\n for (let j = 0; j < boardSpec[i].length; j++) {\n if (typeof boardSpec[i][j] === 'number') {\n initBoard[i].push(boardSpec[i][j]);\n } else {\n // TODO: if the rules ever change to allow for more than 9 tiles or 9 workers, we need to change this.\n let height = parseInt(boardSpec[i][j].substring(0, 1));\n let player = boardSpec[i][j].substring(1, boardSpec[i][j].length - 1);\n let id = parseInt(boardSpec[i][j].substring(boardSpec[i][j].length - 1));\n\n // Swap i and j when making a Worker to conform with coordinate logic\n workerList.push(new Worker(j, i, id, player));\n initBoard[i].push(height);\n }\n }\n }\n\n return new Board(null, initBoard, workerList);\n}",
"_assignWorkers() {\n // contains at most the specified number of workers\n let workersToAssign = this._uploadState.idleWorkers.slice(0, this._options.maxConcurrentConnections);\n\n // assign work to all workers\n workersToAssign.forEach((worker) => {\n let nextChunk = chunker.next();\n\n if (nextChunk) {\n this._assignWorkerToChunk(\n idleWorkersCount[i], \n nextChunk, \n this._uploadState.nextChunkNumber++\n );\n }\n });\n }",
"async createWorkers () {\n\n let worker;\n if ( !this.fallback ) {\n\n let workerBlob = new Blob( this.functions.dependencies.code.concat( this.workers.code ), { type: 'application/javascript' } );\n let objectURL = window.URL.createObjectURL( workerBlob );\n for ( let i = 0; i < this.workers.instances.length; i ++ ) {\n\n worker = new TaskWorker( i, objectURL );\n this.workers.instances[ i ] = worker;\n\n }\n\n }\n else {\n\n for ( let i = 0; i < this.workers.instances.length; i ++ ) {\n\n worker = new MockedTaskWorker( i, this.functions.init, this.functions.execute );\n this.workers.instances[ i ] = worker;\n\n }\n\n }\n\n }",
"createWorkers() {\n let me = this,\n config = Neo.clone(NeoConfig, true),\n hash = location.hash,\n key, value;\n\n // remove configs which are not relevant for the workers scope\n delete config.cesiumJsToken;\n\n // pass the initial hash value as Neo.configs\n if (hash) {\n config.hash = {\n hash : DomEvents.parseHash(hash.substr(1)),\n hashString: hash.substr(1)\n };\n }\n\n for ([key, value] of Object.entries(me.workers)) {\n if (key === 'canvas' && !config.useCanvasWorker ||\n key === 'vdom' && !config.useVdomWorker\n ) {\n continue;\n }\n\n try {\n value.worker = me.createWorker(value);\n } catch (e) {\n document.body.innerHTML = e;\n me.stopCommunication = true;\n break;\n }\n\n me.sendMessage(key, {\n action: 'registerNeoConfig',\n data : config\n });\n }\n }",
"static init() {\n\t\tconst oThis = this;\n\t\t// looping over all databases\n\t\tfor (let dbName in mysqlConfig['databases']) {\n\t\t\tlet dbClusters = mysqlConfig['databases'][dbName];\n\t\t\t// looping over all clusters for the database\n\t\t\tfor (let i = 0; i < dbClusters.length; i++) {\n\t\t\t\tlet cName = dbClusters[i],\n\t\t\t\t\tcConfig = mysqlConfig['clusters'][cName];\n\n\t\t\t\t// creating pool cluster object in poolClusters map\n\t\t\t\toThis.generateCluster(cName, dbName, cConfig);\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save current Rules data to local storage ($('body').data('json')). | function saveRules() {
if ($('.stats').length != 0) {
var rulesJSON = getJSONFromRules();
if (rulesJSON == 1)
return 1;
var allJSON = $('body').data('json');
allJSON.forEach(function (e, i, arr) {
// arr is just used for changing values directly!
if (e['feed-name'] == activeFeed) {
e['items'].forEach(function (eItem, iItem, arrItem) {
if (eItem['item-name'] == activeItem) {
arrItem[iItem]['rules'] = rulesJSON;
}
});
arr[i] = e;
}
});
markAsContentChanged();
}
return 0;
/* SINCE ANIMATION TAKES TIME, VERY POSSIBLE THAT ONLY PART OF
THE BLOCK IS SAVED */
} | [
"function saveproxyRule() {\n\tvar rules = {};\n\tvar co = 0;\n\n\t$(\"#proxy_rules_list .proxy_rule_boxes\").each(function() {\n\t\tvar url = stripHTMLTags($(this).find('.url').text());\n\t\tvar proxy_type = stripHTMLTags($(this).find('.proxy_type').prop(\"selectedIndex\"));\n\t\tvar proxy_location = stripHTMLTags($(this).find('.proxy_location').text());\t\t\n\t\tvar proxy_port = stripHTMLTags($(this).find('.proxy_port').text());\t\t\n\n\t\tvar active = stripHTMLTags($(this).find('.active').prop('checked'));\n\t\tvar global = stripHTMLTags($(this).find('.global').prop('checked'));\n\t\tvar caseinsensitive = stripHTMLTags($(this).find('.caseinsensitive').prop('checked'));\n\t\t// prepare the object\n\t\trules[co] = {id: co, url:url, proxy_type:proxy_type, proxy_location:proxy_location, proxy_port:proxy_port, active: active, global:global, caseinsensitive:caseinsensitive}\n\t\tco++;\n\t});\n\t\t\n\tlocalStorage.proxy_rules = JSON.stringify(rules);\n}",
"create(data) {\n console.log('Creating rule')\n data.created = Date.now()\n data.updated = data.created\n data.id = data.created + '_' + uuid.v4()\n let jsonString = JSON.stringify(data)\n safari.extension.settings.setItem('rule_' + data.id, jsonString)\n return this.get(data.id)\n }",
"function ExportRules() {\n try {\n //update json for all rules in ruleset\n CurrentRuleSet.updateAll();\n\n CurrentRuleSet.Rules.forEach(rule =>{\n\n //convert ruleset to JSON\n var text = JSON.stringify(rule, null, 3);\n \n var filename = rule.title;\n\n //export/download ruleset as text/json file\n var blob = new Blob([text], {\n type: \"application/json;charset=utf-8\"\n });\n saveAs(blob, filename);\n });\n \n } catch (e) {\n alert(e);\n }\n}",
"function saveData() {\n var self = this;\n\n try {\n localStorage.setItem(\n self.data.name,\n JSON.stringify(self.getArrayOfData())\n );\n } catch (e) {\n console.error('Local storage save failed!', e);\n }\n\n }",
"saveData() {\n let jsonData = {\n lastTicket: this.lastTicket,\n today: this.today,\n tickets: this.tickets,\n lastFour: this.lastFour\n }\n\n let jsonDataString = JSON.stringify(jsonData);\n \n fs.writeFileSync('./server/data/data.json', jsonDataString);\n }",
"save() {\n undo.push();\n store.content.fromJSON(this.getValue());\n super.save();\n }",
"function saveSchedules() {\n\t\tlocalStorage.setItem(\"aPossibleSchedules\", JSON.stringify(aPossibleSchedules));\n\t}",
"function save_data$(data) {\n logging.warning(\"This function has side effects, move to a version without side effects.\");\n logging.debug(\"Saving JSON in hidden form..\");\n data_hidden_form_jq.val(JSON.stringify(data));\n}",
"async function setRules(){\n const data = {\n add: rules\n }\n const response = await needle('post', rulesURL, data, {\n headers:{\n 'content-type': 'application/json',\n Authorization: `Bearer ${process.env.TWITTER_BEARER_TOKEN}`\n }\n });\n return response.body\n}",
"static persist() {\n let questionsJson = JSON.stringify(questions);\n fs.writeFileSync(storagePath, questionsJson, 'utf-8');\n }",
"function save(){\n const a = JSON.stringify(answers);\n localStorage.setItem(\"answers\", a);\n}",
"save(data) {\r\n console.log('MigratableLocalStorage.save', data);\r\n data = this.migrate(data);\r\n localStorage.setItem(this.key, JSON.stringify(data));\r\n return data;\r\n }",
"saveToStore() {\n localStorage.setItem(STORAGE.TAG, JSON.stringify(this.list));\n }",
"saveAction() {\n if (game.user.isGM) {\n localStorage.setItem('pendingAction', this.toJSON());\n }\n }",
"storeNotifications() {\n try {\n fs.writeJSONSync(path.join(this.dataDir, 'notifications.json'), this.currentNotifications);\n } catch (e) {\n this.log.error(`${this.logPrefix} Could not write notifications.json: ${e.message}`);\n }\n }",
"saveFormData() {\n let formData = { ['form-data']: {} };\n for (let item of this.view.form) {\n if (item.name.length > 0) formData['form-data'][item.name] = item.value;\n }\n localStorage.setItem('form-data', JSON.stringify(formData));\n }",
"function storeCal() {\n localStorage.setItem(\"calEvents\", JSON.stringify(calEvents));\n }",
"save() {\n if (this.properties.saveCallback) {\n this.properties.saveCallback();\n } else if (this.properties.localStorageReportKey) {\n if ('localStorage' in window && window['localStorage'] !== null) {\n try {\n let report = this.getReport();\n // console.log(JSON.stringify(report));\n window.localStorage.setItem(this.properties.localStorageReportKey, JSON.stringify(report));\n this.modified = false;\n } catch (e) {}\n }\n }\n this.updateMenuButtons();\n }",
"function saveBoard() {\n window.localStorage.setItem(\"board\", board.toJSON());\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the NODEs on the GRID | renderNodes() {
const {cellSizeInPx, nodes} = this.props;
if (nodes.length === 0) {
return;
}
const nodeCells = [];
nodes.forEach((node) => {
const {X, Y} = node.Location;
// Calculate grid position in pixels
const radius = (cellSizeInPx / 2) - padding_in_cell;
const cx = ((X+1) * cellSizeInPx - radius) - padding_in_cell;
const cy = ((Y+1) * cellSizeInPx - radius) - padding_in_cell;
nodeCells.push(
<circle
className="node-circle"
cx={cx}
cy={cy}
r={radius}
/>
);
nodeCells.push(
<text
className="node-circle-text"
x={cx}
y={cy}
font-size={this.getFontSize()}
dy=".3em"
>
{node.Value}
</text>
);
});
return nodeCells;
} | [
"function drawCanvasGrid(node){\n\n}",
"function drawGrid() {\n for(let i = 0; i < HEIGHT; i++) {\n // create a new raw\n let raw = $('<div class=\"raw\"></div>');\n // fill the raw with squares\n for(let j = 0; j < WIDTH; j++) {\n raw.append('<div class=\"block\"></div>');\n }\n // append the raw to the grid container to create the grid\n $('#grid-container').append(raw);\n } \n console.log('[GRID] drawn');\n addGridListeners();\n }",
"draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }",
"drawHTMLBoard() {\r\n\t\tfor (let column of this.spaces) {\r\n\t\t\tfor (let space of column) {\r\n\t\t\t\tspace.drawSVGSpace();\r\n\t\t\t}\t\r\n\t\t}\r\n\t}",
"function drawHTMLGrid(node) {\n\t//clear the node first\n\tnode.innerHTML = \"\";\n\n\t//table tr th\n\tlet table = document.createElement(\"table\");\n\t\n\t//insert trs and ths\n\tfor(let i=0;i<9;i++){\n\t\tlet tr = document.createElement(\"tr\");\n\t\ttr.setAttribute(\"id\",\"y\"+i);\n\t\tfor(let j=0;j<9;j++){\n\t\t\tlet td = document.createElement(\"td\");\n\t\t\ttd.setAttribute(\"id\",\"x\"+j+\"y\"+i);\n\t\t\tlet pile;\n\t\t\tlet num = getPile(j,i);\n\t\t\tpile = document.createElement(\"input\");\n\t\t\t//will use css later\n\t\t\tpile.setAttribute(\"autocomplete\",\"off\");\n\t\t\tpile.setAttribute(\"maxlength\",\"1\");\n\t\t\tpile.setAttribute(\"size\",\"2\");\n\t\t\t//if it's a pure num, set the input box to readonly\n\t\t\tif(num > 0){\n\t\t\t\tpile.setAttribute(\"readonly\",\"\");\n\t\t\t\tpile.setAttribute(\"value\",num);\n\t\t\t}\n\t\t\tpile.setAttribute(\"id\",j+\",\"+i);\n\t\t\ttd.append(pile);\t\n\t\t\ttr.append(td);\n\t\t}\n\t\ttable.append(tr);\n\t}\n\tnode.append(table);\n}",
"printNodes() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++) {\n document.writeln(this.nodes[layer][node].number + \" | \");\n }\n document.writeln(\"</br>\");\n }\n document.writeln(\n \"----------------------------------------------------------------</br>\"\n );\n }",
"function renderGrid(ctx) {\n drawGridLines(ctx);\n drawGridCells(ctx, minesweeper.cells );\n}",
"draw(ctx) {\r\n if (this.isDistanced) {\r\n this.distanceGraph();\r\n }\r\n // draw all nodes and store them in grid array\r\n this.nodeList.forEach(node => {\r\n node.draw(ctx);\r\n storeNodeAt(node, node.x, node.y);\r\n });\r\n\r\n // draw all edges\r\n this.edgeList.forEach(edge => {\r\n edge.draw(ctx);\r\n });\r\n\r\n\r\n }",
"function render() {\n\n // This array holds the relative URL to the image used\n // for that particular row of the game level.\n var rowImages = [\n 'images/water-block.png', // Top row is water\n 'images/stone-block.png', // Row 1 of 3 of stone\n 'images/stone-block.png', // Row 2 of 3 of stone\n 'images/stone-block.png', // Row 3 of 3 of stone\n 'images/grass-block.png', // Row 1 of 2 of grass\n 'images/grass-block.png' // Row 2 of 2 of grass\n ],\n numRows = 6,\n numCols = 5,\n row, col;\n\n // Loop through the number of rows and columns we've defined above\n // and, using the rowImages array, draw the correct image for that\n // portion of the \"grid\"\n for (row = 0; row < numRows; row++) {\n for (col = 0; col < numCols; col++) {\n /* The drawImage function of the canvas' context element\n * requires 3 parameters: the image to draw, the x coordinate\n * to start drawing and the y coordinate to start drawing.\n * We're using our Resources helpers to refer to our images\n * so that we get the benefits of caching these images, since\n * we're using them over and over.\n */\n ctx.drawImage(Resources.get(rowImages[row]), col * 101, row * 83);\n }\n }\n\n renderEntities();\n\n scoreBoard();\n }",
"renderPorts(node) {\n var nodeNoodle = node.noodle;\n for (var i in node.core.inPorts)\n nodeNoodle.port.render(node, node.core.inPorts[i]);\n\n for (var i in node.core.outPorts)\n nodeNoodle.port.render(node, node.core.outPorts[i]);\n\n nodeNoodle.node.forEachPort(node.core, nodeNoodle.port.renderVal);\n }",
"colorGrid() {\n for(let i = 0; i < this.columnSize * this.rowSize; i++) {\n if(this.gridArray[i].state == blank) {\n this.gridDOM.children[i].style.backgroundColor = \"#f2f2f2\";\n this.gridDOM.children[i].style.borderColor = \"#959595\";\n } else if(this.gridArray[i].state == unvisited) {\n this.gridDOM.children[i].style.backgroundColor = \"#88FFD1\";\n this.gridDOM.children[i].style.borderColor = \"#3FE1B0\";\n } else if(this.gridArray[i].state == visited) { \n this.gridDOM.children[i].style.backgroundColor = \"#FF848C\";\n this.gridDOM.children[i].style.borderColor = \"#FF505F\";\n } else if(this.gridArray[i].state == start) {\n this.gridDOM.children[i].style.backgroundColor = \"#00DDFF\";\n this.gridDOM.children[i].style.borderColor = \"#0290EE\";\n } else if(this.gridArray[i].state == goal) {\n this.gridDOM.children[i].style.backgroundColor = \"#C588FF\";\n this.gridDOM.children[i].style.borderColor = \"#9059FF\";\n } else if (this.gridArray[i].state == wall) {\n this.gridDOM.children[i].style.backgroundColor = \"black\";\n } else;\n }\n }",
"render() {\n\n\t\tthis._ctx.clearRect(0, 0, this.width, this.height);\n\n\n\t\t// Draw all points\n\t\tthis._points.forEach( p => this.drawPoint(p.x, p.y, p.color) );\n\n\t\t// Draw all lines\n\t\tthis._lines.forEach( line => this.drawLine(line, this.DEFAULT_LINE_COLOR) );\n\n\t\t// Render a grid\n\t\tthis.renderGrid(10);\n\t\t// Render the axes\n\t\tthis.renderAxis();\n\n\t\trequestAnimationFrame(this.render);\n\t}",
"function drawGrid(){\r\n\t\r\n\tfor (var i = 0; i < grid.length; i++){\r\n\t\tfor (var j = 0; j < grid[i].length; j++){\r\n\t\t\t//Set the color to the cell's color\r\n\t\t\tctx.fillStyle = grid[i][j].color;\r\n\t\t\t//Offset each reactangle so that they are drawn in a grid\r\n\t\t\tctx.fillRect(10*i, 10*j, grid[i][j].len, grid[i][j].len);\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n}",
"function nr_basicRenderNode(node,divid,titleid)\n{\n\tvar div = $('#'+divid);\n\tdiv.empty();\n\tvar title = $('#'+titleid);\n\tvar ttext = su_getNodeShortLabel(node);\n\ttitle.text(ttext);\n\tdocument.title=ttext;\n\n\t// loop over properties\n\tparr = su_getNodePropertyAndDisplayNames(node.type,node);\n\tvar len = parr.length;\n\tvar prop = null;\n\tvar disp = null;\n\tvar val = null;\n\tvar row = null;\n\tvar lc = null;\n\tvar rc = null;\n\tfor(var i=0; i<len; i++)\n\t{\n\t\tprop = parr[i][0];\n\t\tdisp = parr[i][1];\n\t\tval = node[prop];\n\t\tif(isEmpty(val)) val = node[prop.toLowerCase()];\n\t\tif(isEmpty(val)) continue;\n\t\t\n\t\trow = $('<div class=\"w3-row\"></div>');\n\t\tlc = $('<div class=\"w3-col s1 w3-theme-d3 w3-center\"><p>'+disp+'</p></div>');\n\t\trc = $('<div class=\"w3-col s5 w3-theme-l3\"><p> '+val+'</p></div>');\n\t\trow.append(lc);\n\t\trow.append(rc);\n\t\tdiv.append(row);\n\t}\n} // end nr_basicRenderNode",
"function createGrid() {\n for (let i = 0; i < width * height; i++) {\n const cell = document.createElement('div')\n grid.appendChild(cell)\n cells.push(cell)\n }\n for (let i = 2; i < 22; i++) {\n rowArray.push(cells.slice(i * 10, ((i * 10) + 10)))\n }\n for (let i = 0; i < 20; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('top')\n }\n for (let i = 10; i < 20; i++) {\n cells[i].classList.remove('top')\n cells[i].classList.add('topline')\n }\n for (let i = 220; i < 230; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('bottom')\n }\n }",
"function printNode(ID) {\n var childArray = new Array(); // store all children of node with ID into childArray[]\n var thisNode; // \"this\"\n for (i=0; i< nodes.length;i++){ // finding all children whose parentID == ID\n if (nodes[i][5] == ID){\n childArray.push(nodes[i]);\n //console.log(ID);\n }\n else if (nodes[i][0] == ID){\n thisNode = nodes[i];\n }\n }\n var numChildren = childArray.length;\n console.log(\"Number of children: \" + numChildren);\n\n var url = \"/story/\" + ID; // this is the url that will link to the edit's unique webpage\n \n // printing the icon and associated up/down votes\n p.image(\"/static/img/icons/doc3.png\", x-(img/2), y-(img/2), img, img)\n .hover(\n function(){\n this.attr({src: \"/static/img/icons/doc3_hovered.png\"});\n },\n function(){\n this.attr({src: \"/static/img/icons/doc3.png\"});\n })\n .attr({cursor: \"pointer\", href: url});\n \n var upVote = thisNode[6];\n var downVote = thisNode[7];\n p.text(x-(img/2.5), y+(img/2.5), upVote).attr({\"font-size\": 30, \"font-weight\": \"bold\", fill: \"#02820B\"});\n p.text(x+(img/2.5), y+(img/2.5), downVote).attr({\"font-size\": 30, \"font-weight\": \"bold\", fill: \"#B71306\"});\n console.log(\"Printed icon\"); // finish printing icon\n \n // if thisNode only has one child, draw a straight line downward to the child node\n if (numChildren == 1){\n y += 100;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n path += \" L \" + x + \" \" + y;\n //path += \" l 0 200\";\n \n printNode(childArray[0][0]);\n y -= 100;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n path += \" M \" + x + \" \" + y;\n }\n\n // if thisNode has multiple children, draw lines at 45-degrees in both directions downward, and if numChildren > 2, spaced equally inward from these outer lines\n else if (numChildren > 1){\n for (i=0; i < numChildren;i++){\n var newI = i;\n var newNum = numChildren;\n var angle = (((newI / (newNum-1))*200)-100);\n x += angle;\n y += 100;\n path += \" L \" + x + \" \" + y;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n console.log(childArray);\n \n printNode(childArray[i][0]);\n x -= angle;\n y -= 100;\n path += \" M \" + x + \" \" + y;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n i = newI;\n }\n }\n \n else if (numChildren == 0){\n console.log(\"No children\");\n return;\n }\n console.log(\"Number of children: \" + numChildren);\n }",
"showGrid(){\n this.Grid = true;\n this.Line = false\n \n }",
"function renderChildAndPartnerLinks() {\n for (const [, persons] of generations)\n for (const person of persons) {\n const personBox = jQuery(\"#box-\" + person.id);\n if (person.children)\n for (const child of person.children)\n drawPath(personBox, jQuery(\"#box-\" + child.id), \"link-child\");\n if (person.partners)\n for (const partner of person.partners)\n drawPartnerPath(personBox, jQuery(\"#box-\" + partner.id));\n }\n}",
"function RenderMainNode(SemTree, i, x, y, Scale) {\n var Html = \"\";\n var X = (SemTree[i].x - XOffset) * Zoom * Scale + x;\n var Y = (SemTree[i].y - YOffset) * Zoom * Scale + y;\n UniqueId += 1;\n if (HighlightNode == i) {\n SVG_SetPen(2);\n } else {\n SVG_SetPen(1);\n }\n if ((HighlightNode == i) || (HighlightNode == -1)) {\n SVG_SetOpacity(1);\n } else {\n SVG_SetOpacity(0.2);\n }\n SVG_SetInk(\"#ff0000\");\n SVG_SetFill(\"#ff0000\");\n Html += SVG_Circle(X, Y, 4);\n SVG_SetInk(\"#000000\");\n if (HighlightNode == i) {\n SVG_SetFill(\"#ffdddd\");\n } else {\n SVG_SetFill(\"#ffffff\");\n }\n Html += SVG_GroupStart(\"noname\" + UniqueId, \"style=\\\"cursor:pointer;\\\" onmousedown=\\\"Highlight(\" + i + \",-1)\\\"\");\n if (HighlightNode == i) {\n Html += SVG_Poly([X, Y, X, Y + 35, X + 100, Y + 35, X + 100, Y + 10, X + 10, Y + 10, X, Y]);\n SVG_SetFontSize(\"18\");\n }\n else {\n Html += SVG_Poly([X, Y, X, Y + 30, X + 100, Y + 30, X + 100, Y + 10, X + 10, Y + 10, X, Y]);\n SVG_SetFontSize(\"15\");\n }\n SVG_SetFont(\"arial\");\n SVG_SetFontRotate(0);\n SVG_SetFontAlign(\"left\");\n Html += SVG_Text(X + 5, Y + 15, SemTree[i].label);\n Html += SVG_GroupClose(\"\");\n return (Html);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Credential issuance is an interactive protocol between a user and an issuer The issuer takes its secret and public keys and user attribute values as input The user takes the issuer public key and user secret as input The issuance protocol consists of the following steps: 1) The issuer sends a random nonce to the user 2) The user creates a Credential Request using the public key of the issuer, user secret, and the nonce as input The request consists of a commitment to the user secret (can be seen as a public key) and a zeroknowledge proof of knowledge of the user secret key The user sends the credential request to the issuer 3) The issuer verifies the credential request by verifying the zeroknowledge proof If the request is valid, the issuer issues a credential to the user by signing the commitment to the secret key together with the attribute values and sends the credential back to the user 4) The user verifies the issuer's signature and stores the credential that consists of the signature value, a randomness used to create the signature, the user secret, and the attribute values NewCredRequest creates a new Credential Request, the first message of the interactive credential issuance protocol (from user to issuer) | function NewCredRequest(sk , IssuerNonce , ipk , rng ) {
// Set Nym as h_{sk}^{sk}
let HSk = ipk.HSk
let Nym = HSk.mul(sk)
// generate a zero-knowledge proof of knowledge (ZK PoK) of the secret key
// Sample the randomness needed for the proof
let rSk = RandModOrder(rng)
// Step 1: First message (t-values)
let t = HSk.mul(rSk) // t = h_{sk}^{r_{sk}}, cover Nym
// Step 2: Compute the Fiat-Shamir hash, forming the challenge of the ZKP.
// proofData is the data being hashed, it consists of:
// the credential request label
// 3 elements of G1 each taking 2*FieldBytes+1 bytes
// hash of the issuer public key of length FieldBytes
// issuer nonce of length FieldBytes
let proofData = new ArrayBuffer(credRequestLabel.length+3*(2*FieldBytes+1)+2*FieldBytes);
let v = new Uint8Array(proofData);
let index = 0
index = appendBytesString(v, index, credRequestLabel)
index = appendBytesG1(proofData, index, t)
index = appendBytesG1(proofData, index, HSk)
index = appendBytesG1(proofData, index, Nym)
index = appendBytes(v, index, IssuerNonce)
v.set(BigToBytes(ipk.Hash),index)
let proofC = HashModOrder(v)
// Step 3: reply to the challenge message (s-values)
let proofS = Modadd(FP256BN.BIG.modmul(proofC, sk, GroupOrder), rSk, GroupOrder) // s = r_{sk} + C \cdot sk
// Done
return {
Nym: Nym,
IssuerNonce: IssuerNonce,
ProofC: proofC,
ProofS: proofS
}
} | [
"function VerCred(cred, sk , ipk ) {\n\t// Validate Input\n\n\t// - parse the credential\n\tlet A = cred.A\n\tlet B = cred.B\n\tlet E = cred.E\n\tlet S = cred.S\n\n\t// - verify that all attribute values are present\n\tfor (i = 0; i < cred.Attrs.length; i++) {\n\t\tif (cred.Attrs[i] == null) {\n\t\t\t//throw Error(\"credential has no value for attribute %s\", ipk.AttributeNames[i])\n\t\t}\n\t}\n\n\t// - verify cryptographic signature on the attributes and the user secret key\n\tlet BPrime = new FP256BN.ECP()\n BPrime.copy(GenG1)\n //BPrime.add(key.Ipk.HSk.mul(sk))\n // BPrime.add(key.Ipk.HRand.mul(S))\n //BPrime.add(Mul2(ipk.HSk,sk,ipk.HRand,S))\n BPrime.add(ipk.HSk.mul2(sk, ipk.HRand, S))\n \n\t// Append attributes\n\t// Use Mul2 instead of Mul as much as possible for efficiency reasones\n\tfor (i = 0; i < Math.floor(cred.Attrs.length/2); i++) {\n\t\tBPrime.add(\n\t\t\t ipk.HAttrs[2*i].mul2(\n\t\t\t\tcred.Attrs[2*i],\n\t\t\t\tipk.HAttrs[2*i+1],\n\t\t\t\tcred.Attrs[2*i+1]\n\t\t\t)\n\t\t)\n }\n \n\t// Check for residue in case len(attrs)%2 is odd\n\tif (cred.Attrs.length % 2 != 0 ){\n\t\tBPrime.add(key.Ipk.HAttrs[cred.Attrs.length-1].mul(cred.Attrs[cred.Attrs.length-1]))\n\t}\n\n\n if (!B.equals(BPrime)) {\n throw Error(\"b-value from credential does not match the attribute values\")\n }\n\n\n\t// Verify BBS+ signature. Namely: e(w \\cdot g_2^e, A) =? e(g_2, B)\n\tlet a = GenG2.mul(E)\n\ta.add(ipk.W)\n\ta.affine()\n\n\tlet left = FP256BN.PAIR.fexp(FP256BN.PAIR.ate(a, A))\n let right = FP256BN.PAIR.fexp(FP256BN.PAIR.ate(GenG2, B))\n \n if (!left.equals(right)) {\n console.log(JSON.stringify(left));\n console.log(JSON.stringify(right));\n throw Error(\"credential is not cryptographically valid\")\n }\n\n\n\n}",
"newAuthorisedCapability (holder, id, type, location, sphere, validFrom, validTo) {\n const subject = {\n id: 'did:caelum:' + this.did + '#issued-' + (id || 0),\n capability: {\n type: type || 'member',\n sphere: (['over18', 'oidc'].includes(type) ? 'personal' : 'professional')\n }\n }\n if (location) subject.capability.location = location\n const credential = {\n '@context': [\n 'https://www.w3.org/2018/credentials/v1',\n 'https://caelumapp.com/context/v1'\n ],\n id: 'did:caelum:' + this.did + '#issued',\n type: ['VerifiableCredential', 'AuthorisedCapability'],\n issuer: 'did:caelum:' + this.did,\n holder: holder,\n issuanceDate: new Date().toISOString(),\n credentialSubject: subject\n }\n return credential\n }",
"function NewSignature(cred , sk , Nym , RNym , ipk , Disclosure , msg , rhIndex , cri , rng ) {\n \n /*\n // Validate inputs\n\tif cred == nil || sk == nil || Nym == nil || RNym == nil || ipk == nil || rng == nil || cri == nil {\n\t\treturn nil, errors.Errorf(\"cannot create idemix signature: received nil input\")\n\t}\n\n\tif rhIndex < 0 || rhIndex >= len(ipk.AttributeNames) || len(Disclosure) != len(ipk.AttributeNames) {\n\t\treturn nil, errors.Errorf(\"cannot create idemix signature: received invalid input\")\n\t}\n\n\tif cri.RevocationAlg != int32(ALG_NO_REVOCATION) && Disclosure[rhIndex] == 1 {\n\t\treturn nil, errors.Errorf(\"Attribute %d is disclosed but also used as revocation handle attribute, which should remain hidden.\", rhIndex)\n\t}\n*/\n\n\t// locate the indices of the attributes to hide and sample randomness for them\n\tHiddenIndices = hiddenIndices(Disclosure)\n\n\t// Generate required randomness r_1, r_2\n\tlet r1 = RandModOrder(rng)\n\tlet r2 = RandModOrder(rng)\n\t// Set r_3 as \\frac{1}{r_1}\n let r3 = new FP256BN.BIG(r1)\n\n\tr3.invmodp(GroupOrder)\n\n\t// Sample a nonce\n\tlet Nonce = RandModOrder(rng)\n\n\t// Parse credential\n\tlet A = cred.A\n\tlet B = cred.B\n let E = cred.E\n let S = cred.S\n\n\t// Randomize credential\n\n\t// Compute A' as A^{r_!}\n\tlet APrime = FP256BN.PAIR.G1mul(A, r1)\n\n\t// Compute ABar as A'^{-e} b^{r1}\n let ABar = FP256BN.PAIR.G1mul(B, r1)\n\tABar.sub(FP256BN.PAIR.G1mul(APrime, E))\n\n\t// Compute B' as b^{r1} / h_r^{r2}, where h_r is h_r\n\tlet BPrime = FP256BN.PAIR.G1mul(B, r1)\n\tlet HRand = ipk.HRand\n\t// Parse h_{sk} from ipk\n\tlet HSk = ipk.HSk\n\n\tBPrime.sub(FP256BN.PAIR.G1mul(HRand, r2))\n\n\t// Compute s' as s - r_2 \\cdot r_3\n\tlet sPrime = Modsub(S, FP256BN.BIG.modmul(r2, r3, GroupOrder), GroupOrder)\n\n\t// The rest of this function constructs the non-interactive zero knowledge proof\n\t// that links the signature, the non-disclosed attributes and the nym.\n\n\t// Sample the randomness used to compute the commitment values (aka t-values) for the ZKP\n\tlet rSk = RandModOrder(rng)\n\tlet re = RandModOrder(rng)\n\tlet rR2 = RandModOrder(rng)\n\tlet rR3 = RandModOrder(rng)\n\tlet rSPrime = RandModOrder(rng)\n\tlet rRNym = RandModOrder(rng)\n\n let rAttrs = new Array(HiddenIndices.length)\n HiddenIndices.forEach(\n (value,i) => {\n rAttrs[i] = RandModOrder(rng)\n }\n )\n\n/*\n\t// First compute the non-revocation proof.\n\t// The challenge of the ZKP needs to depend on it, as well.\n\tprover, err = getNonRevocationProver(RevocationAlgorithm(cri.RevocationAlg))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnonRevokedProofHashData, err = prover.getFSContribution(\n\t\tFP256BN.FromBytes(cred.Attrs[rhIndex]),\n\t\trAttrs[sort.SearchInts(HiddenIndices, rhIndex)],\n\t\tcri,\n\t\trng,\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to compute non-revoked proof\")\n\t}\n*/\n\t// Step 1: First message (t-values)\n\n\t// t1 is related to knowledge of the credential (recall, it is a BBS+ signature)\n let t1 = APrime.mul2(re, HRand, rR2) // A'^{r_E} . h_r^{r_{r2}}\n\n\t// t2: is related to knowledge of the non-disclosed attributes that signed in (A,B,S,E)\n\tlet t2 = FP256BN.PAIR.G1mul(HRand, rSPrime) // h_r^{r_{s'}}\n t2.add(BPrime.mul2(rR3, HSk, rSk)) // B'^{r_{r3}} \\cdot h_{sk}^{r_{sk}}\n\n for (i = 0; i < Math.floor(HiddenIndices.length/2); i++){\n\t\tt2.add(\n\t\t\t// \\cdot h_{2 \\cdot i}^{r_{attrs,i}\n\t\t\tipk.HAttrs[HiddenIndices[2*i]].mul2(\n\t\t\t\trAttrs[2*i],\n\t\t\t\tipk.HAttrs[HiddenIndices[2*i+1]],\n\t\t\t\trAttrs[2*i+1],\n\t\t\t),\n\t\t)\n\t}\n\tif (HiddenIndices.length % 2 != 0 ){\n\t\tt2.add(FP256BN.PAIR.G1mul(ipk.HAttrs[HiddenIndices[HiddenIndices.length-1]], rAttrs[HiddenIndices.length-1]))\n\t}\n\n\t// t3 is related to the knowledge of the secrets behind the pseudonym, which is also signed in (A,B,S,E)\n \tlet t3 = HSk.mul2(rSk, HRand, rRNym) // h_{sk}^{r_{sk}} \\cdot h_r^{r_{rnym}}\n //let t3 = Mul2(HSk,rSk, HRand, rRNym)\n\n\t// Step 2: Compute the Fiat-Shamir hash, forming the challenge of the ZKP.\n\n\t// Compute the Fiat-Shamir hash, forming the challenge of the ZKP.\n\t// proofData is the data being hashed, it consists of:\n\t// the signature label\n\t// 7 elements of G1 each taking 2*FieldBytes+1 bytes\n // one bigint (hash of the issuer public key) of length FieldBytes\n \n\n\n\t// disclosed attributes\n\t// message being signed\n\t// the amount of bytes needed for the nonrevocation proof\n\t//let proofData = new ArrayBuffer( signLabel.lenght+7*(2*FieldBytes+1)+FieldBytes+Disclosure.length+msg.length+ProofBytes[RevocationAlgorithm(cri.RevocationAlg)])\n\tlet proofData = new ArrayBuffer( signLabel.length+7*(2*FieldBytes+1)+FieldBytes+Disclosure.length+msg.length)\n let v = new Uint8Array(proofData);\n let index = 0\n\tindex = appendBytesString(v, index, signLabel)\n index = appendBytesG1(proofData, index, t1)\n\tindex = appendBytesG1(proofData, index, t2)\n\tindex = appendBytesG1(proofData, index, t3)\n\tindex = appendBytesG1(proofData, index, APrime)\n\tindex = appendBytesG1(proofData, index, ABar)\n\tindex = appendBytesG1(proofData, index, BPrime)\n\tindex = appendBytesG1(proofData, index, Nym)\n //index = appendBytes(proofData, index, nonRevokedProofHashData)\n v.set(BigToBytes(ipk.Hash),index);\n\tindex = index + FieldBytes\n v.set(Buffer.from(Disclosure),index);\n\tindex = index + Disclosure.length\n v.set(msg,index);\n\tlet c = HashModOrder(v)\n\n\t// add the previous hash and the nonce and hash again to compute a second hash (C value) \n index = 0\n proofData = proofData.slice(0,2*FieldBytes);\n let v2 = new Uint8Array(proofData);\n\n\tindex = appendBytesBig(proofData, index, c)\n\tindex = appendBytesBig(proofData, index, Nonce)\n\n ProofC = HashModOrder(v2)\n\n // Step 3: reply to the challenge message (s-values)\n ProofSSk = Modadd(rSk, FP256BN.BIG.modmul(ProofC, sk, GroupOrder), GroupOrder) // s_sk = rSK + C . sk\n\n ProofSE = Modsub(re, FP256BN.BIG.modmul(ProofC, E, GroupOrder), GroupOrder) // s_e = re + C . E\n ProofSR2 = Modadd(rR2, FP256BN.BIG.modmul(ProofC, r2, GroupOrder), GroupOrder) // s_r2 = rR2 + C . r2\n\n\n\tlet ProofSR3 = Modsub(rR3, FP256BN.BIG.modmul(ProofC, r3, GroupOrder), GroupOrder) // s_r3 = rR3 + C \\cdot r3\n\tlet ProofSSPrime = Modadd(rSPrime, FP256BN.BIG.modmul(ProofC, sPrime, GroupOrder), GroupOrder) // s_S' = rSPrime + C \\cdot sPrime\n\tlet ProofSRNym = Modadd(rRNym, FP256BN.BIG.modmul(ProofC, RNym, GroupOrder), GroupOrder) // s_RNym = rRNym + C \\cdot RNym\n let ProofSAttrs = new Array(HiddenIndices.length)\n\n\n /*\n\tfor i, j = range HiddenIndices {\n\t\tProofSAttrs[i] = BigToBytes(\n\t\t\t// s_attrsi = rAttrsi + C \\cdot cred.Attrs[j]\n\t\t\tModadd(rAttrs[i], FP256BN.Modmul(ProofC, cred.Attrs[j], GroupOrder), GroupOrder),\n\t\t)\n }*/\n\n HiddenIndices.forEach(\n (j,i) => {\n // s_attrsi = rAttrsi + C \\cdot cred.Attrs[j]\n ProofSAttrs[i] = Modadd(rAttrs[i], FP256BN.BIG.modmul(ProofC, cred.Attrs[j], GroupOrder), GroupOrder); \n }\n )\n // Compute the revocation part\n /*\n\tnonRevokedProof, err = prover.getNonRevokedProof(ProofC)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n*/\n\n\t// We are done. Return signature\n\treturn {\n\t\t\tAPrime: APrime,\n\t\t\tABar: ABar,\n\t\t\tBPrime: BPrime,\n\t\t\tProofC: ProofC,\n\t\t\tProofSSk: ProofSSk,\n\t\t\tProofSE: ProofSE,\n\t\t\tProofSR2: ProofSR2,\n\t\t\tProofSR3: ProofSR3,\n\t\t\tProofSSPrime: ProofSSPrime,\n\t\t\tProofSAttrs: ProofSAttrs,\n\t\t\tNonce: Nonce,\n\t\t\tNym: Nym,\n\t\t\tProofSRNym: ProofSRNym,\n\t//\t\tRevocationEpochPk: cri.EpochPk,\n\t//\t\tRevocationPkSig: cri.EpochPkSig,\n\t//\t\tEpoch: cri.Epoch,\n // NonRevocationProof: nonRevokedProof\n }\n}",
"authenticate({ method, ruri, body }, challenge, cnonce = null /* test interface */)\n {\n this._algorithm = challenge.algorithm;\n this._realm = challenge.realm;\n this._nonce = challenge.nonce;\n this._opaque = challenge.opaque;\n this._stale = challenge.stale;\n\n if (this._algorithm)\n {\n if (this._algorithm !== 'MD5')\n {\n logger.warn('authenticate() | challenge with Digest algorithm different than \"MD5\", authentication aborted');\n\n return false;\n }\n }\n else\n {\n this._algorithm = 'MD5';\n }\n\n if (!this._nonce)\n {\n logger.warn('authenticate() | challenge without Digest nonce, authentication aborted');\n\n return false;\n }\n\n if (!this._realm)\n {\n logger.warn('authenticate() | challenge without Digest realm, authentication aborted');\n\n return false;\n }\n\n // If no plain SIP password is provided.\n if (!this._credentials.password)\n {\n // If ha1 is not provided we cannot authenticate.\n if (!this._credentials.ha1)\n {\n logger.warn('authenticate() | no plain SIP password nor ha1 provided, authentication aborted');\n\n return false;\n }\n\n // If the realm does not match the stored realm we cannot authenticate.\n if (this._credentials.realm !== this._realm)\n {\n logger.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:\"%s\", given:\"%s\"]', this._credentials.realm, this._realm);\n\n return false;\n }\n }\n\n // 'qop' can contain a list of values (Array). Let's choose just one.\n if (challenge.qop)\n {\n if (challenge.qop.indexOf('auth-int') > -1)\n {\n this._qop = 'auth-int';\n }\n else if (challenge.qop.indexOf('auth') > -1)\n {\n this._qop = 'auth';\n }\n else\n {\n // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here.\n logger.warn('authenticate() | challenge without Digest qop different than \"auth\" or \"auth-int\", authentication aborted');\n\n return false;\n }\n }\n else\n {\n this._qop = null;\n }\n\n // Fill other attributes.\n\n this._method = method;\n this._uri = ruri;\n this._cnonce = cnonce || Utils.createRandomToken(12);\n this._nc += 1;\n const hex = Number(this._nc).toString(16);\n\n this._ncHex = '00000000'.substr(0, 8-hex.length) + hex;\n\n // Nc-value = 8LHEX. Max value = 'FFFFFFFF'.\n if (this._nc === 4294967296)\n {\n this._nc = 1;\n this._ncHex = '00000001';\n }\n\n // Calculate the Digest \"response\" value.\n\n // If we have plain SIP password then regenerate ha1.\n if (this._credentials.password)\n {\n // HA1 = MD5(A1) = MD5(username:realm:password).\n this._ha1 = Utils.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`);\n }\n // Otherwise reuse the stored ha1.\n else\n {\n this._ha1 = this._credentials.ha1;\n }\n\n let a2;\n let ha2;\n\n if (this._qop === 'auth')\n {\n // HA2 = MD5(A2) = MD5(method:digestURI).\n a2 = `${this._method}:${this._uri}`;\n ha2 = Utils.calculateMD5(a2);\n\n logger.debug('authenticate() | using qop=auth [a2:\"%s\"]', a2);\n\n // Response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2).\n this._response = Utils.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${ha2}`);\n\n }\n else if (this._qop === 'auth-int')\n {\n // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)).\n a2 = `${this._method}:${this._uri}:${Utils.calculateMD5(body ? body : '')}`;\n ha2 = Utils.calculateMD5(a2);\n\n logger.debug('authenticate() | using qop=auth-int [a2:\"%s\"]', a2);\n\n // Response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2).\n this._response = Utils.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${ha2}`);\n\n }\n else if (this._qop === null)\n {\n // HA2 = MD5(A2) = MD5(method:digestURI).\n a2 = `${this._method}:${this._uri}`;\n ha2 = Utils.calculateMD5(a2);\n\n logger.debug('authenticate() | using qop=null [a2:\"%s\"]', a2);\n\n // Response = MD5(HA1:nonce:HA2).\n this._response = Utils.calculateMD5(`${this._ha1}:${this._nonce}:${ha2}`);\n }\n\n logger.debug('authenticate() | response generated');\n\n return true;\n }",
"requestInvite(){\n let ic = new iCrypto()\n ic.createNonce(\"n\")\n .bytesToHex(\"n\", \"nhex\");\n let request = new Message(self.version);\n let myNickNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.nickname,\n this.session.metadata.topicAuthority.publicKey);\n let topicNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.topicName,\n this.session.metadata.topicAuthority.publicKey);\n request.headers.command = \"request_invite\";\n request.headers.pkfpSource = this.session.publicKeyFingerprint;\n request.headers.pkfpDest = this.session.metadata.topicAuthority.pkfp;\n request.body.nickname = myNickNameEncrypted;\n request.body.topicName = topicNameEncrypted;\n request.signMessage(this.session.privateKey);\n this.chatSocket.emit(\"request\", request);\n }",
"function promptForCredentials(){\n var authFailure = getProperty('authFailure');\n if(authFailure == 'true'){\n clearProperties(); \n }\n \n var username = getProperty('username');\n var password = getProperty('password');\n \n //Promt for credentials\n if(username == null || password == null){\n var ui = SpreadsheetApp.getUi();\n var usernameResponse = ui.prompt('Jira Integration', 'This sheet integrates with Jira!\\n\\n Jira Username?', ui.ButtonSet.OK);\n var passwordResponse = ui.prompt('Jira Integration', 'Jira Password?', ui.ButtonSet.OK);\n \n setProperty('username', usernameResponse.getResponseText());\n setProperty('password', passwordResponse.getResponseText()); \n }\n}",
"function handleSaveCreds() {\n /* To show the progress bar */\n showProgressBar();\n var billerCorpId = null, programId = null, billerCorpAccountId = null;\n var strNick = \"\" + $('#nickName').val();\n var nickname = strNick.replace(/[\\<\\>\\;\\&\\/]/g, '').trim();\n var nickNameLabelId = $('#nickNameSec > label:first').attr('id');\n if(nickNameLabelId) {\n\t billerCorpId = nickNameLabelId.split('_')[0];\n\t programId = nickNameLabelId.split('_')[1] === 'null' ? null : nickNameLabelId.split('_')[1];\n\t billerCorpAccountId = nickNameLabelId.split('_')[2] === 'null' ? null : nickNameLabelId.split('_')[2];\n }\n var request = new Object();\n request.userId = eval(getCookie('userId'));\n request.billerCorpId = billerCorpId ;\n if(programId) {\n \trequest.programId = programId;\n }\n if(billerCorpAccountId) {\n \trequest.billerCorpAccountId = billerCorpAccountId;\n }\n request.applicationId = applicationId;\n request.locale = getCookie(\"locale\");\n request.nickname = nickname;\n request.accountCredentials = new Array();\n var credCount = 0;\n for (var billerCredsId in billerCredElements) {\n var elementObj = billerCredElements[billerCredsId];\n var inputElementValue = replaceUnUsedChar(\"element\" + billerCredsId);/*adding element for bug 4932 \n which is disturbed by bug 4944 now fixed*/\n if (inputElementValue) {\n \trequest.accountCredentials[credCount] = new Object();\n request.accountCredentials[credCount].elementId = billerCredsId;\n /* Checking for PHONE and DATE box type and getting only number from the input field */\n if (elementObj.elementType === \"PHONE_BOX\" || elementObj.elementType === \"DATE_BOX\") {\n if (elementObj.securedFlag) {\n if (!/^[\\\\*]*$/.test(inputElementValue)) {\n inputElementValue = getNumberFromString(inputElementValue);\n }\n } else {\n inputElementValue = getNumberFromString(inputElementValue);\n }\n }\n billerCredsId == 21 ? request.accountCredentials[credCount].value = inputElementValue.toUpperCase() \n \t\t: request.accountCredentials[credCount].value = inputElementValue;\n credCount++;\n } else {\n \tif(bpGetCorpAccountMap[billerCredsId]){\n \t\trequest.accountCredentials[credCount] = new Object();\n request.accountCredentials[credCount].elementId = billerCredsId;\n billerCredsId == 21 ? request.accountCredentials[credCount].value = inputElementValue.toUpperCase() \n \t\t: request.accountCredentials[credCount].value = inputElementValue;\n \t\tcredCount++;\n \t}\n }\n }\n var call_bp_save_biller_corp_acct_creds = new bp_save_biller_corp_acct_creds(request);\n call_bp_save_biller_corp_acct_creds.call();\n}",
"fromQR(qr) {\r\n\r\n // Check the type of the parameter: string, String or UInt8Array\r\n\r\n // Convert to string\r\n\r\n // The QR should start with the context identifier: \"HC1:\"\r\n if (!qr.startsWith(\"HC1:\")) {\r\n // Raise an exception\r\n }\r\n\r\n // Decode from Base45\r\n let coseDeflated = decodeB45(qr.slice(4)) // Skip the context identifier\r\n\r\n // Decompress (inflate) from zlib-compressed\r\n let coseEU = pako.inflate(coseDeflated)\r\n\r\n // Decode the first layer of CVD COSE\r\n let c = new COSE(coseEU)\r\n let cvd_layer1 = c.decode()\r\n\r\n // We should have an array with 4 elements: protected, unprotected, payload and signature\r\n console.log(\"CVD first layer:\", cvd_layer1)\r\n if (cvd_layer1.length != 4) {\r\n // ERROR: raise an exception\r\n }\r\n\r\n // Decode the payload which is a CBOR object\r\n let payload = new COSE(cvd_layer1[2])\r\n payload = payload.cbor2json()\r\n\r\n // Check that is is well-formed: a CBOR Map with 4 elements\r\n // key 1: \"iss\", CBOR type 2 (bstr). Issuer Country Code\r\n // key 6: \"iat\", CBOR type 2 (bstr). Issuance date\r\n // key 4: \"exp\", CBOR type 2 (bstr). Expiration date\r\n // key -260: \"hcert\", CBOR type 5 (map). CVD data depending on the type\r\n if (payload.size != 4) {\r\n // ERROR: raise an exception\r\n }\r\n\r\n // Get the Issuer\r\n let iss = payload.get(1)\r\n console.log(\"Issuer:\", iss)\r\n if (!iss) {\r\n //ERROR: \r\n }\r\n\r\n // Get the Issuance date\r\n let iat = payload.get(6)\r\n console.log(\"Issuance date:\", iat)\r\n\r\n // Get the Expiration date\r\n let exp = payload.get(4)\r\n console.log(\"Issuance date:\", exp)\r\n\r\n // Get the hcert, the envelope for the certificate data\r\n let hcert = payload.get(-260)\r\n console.log(\"Hcert:\", hcert)\r\n\r\n let p = payload\r\n\r\n\r\n return p\r\n\r\n\r\n }",
"function getEncryptedCredentials(adviseLaunchInfo) {\n \n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_GET_CREDENTIALS'));\n \n var pubKey = adviseLaunchInfo.eedPublicKey,\n ticketURL = adviseLaunchInfo.ticketURL;\n \n jQuery.ajax({ url : ticketURL,\n type : \"GET\",\n cache : false,\n success : function(returndata, status, xhr) {\n var urlL = \"../simulationcentral/smaAdviseEncryptedCredentials.jsp?pubKey=\" + pubKey;\n var myData;\n try {\n try {\n myData = String(returndata.documentElement.childNodes[1].textContent);\n } catch (error) {\n var myData1 = String(returndata);\n var sMyData1 = myData1.split('\\n');\n var ticketStr = sMyData1[0].split(\"ticket=\");\n myData = ticketStr[1];\n adviseLaunchInfo.loginTicket = myData;\n }\n } catch (error) {\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_GET_CRED_ERROR'));\n adviseGoBack(\n adviseLaunchInfo.translator.translate('LAUNCH_GET_LT_ERROR') + '<br\\>' + error \n );\n }\n \n if(adviseLaunchInfo.runAs) {\n \n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_ENC_CREDENTIALS'));\n \n pubKey = adviseLaunchInfo.eedPublicKeyDecoded;\n pubKey = pubKey.replace(/(\\r\\n|\\n|\\r)/gm,'');\n \n var encryptor = document.getElementById('encryptor');\n if (encryptor.encryptCredentials) {\n waitForPolymerAndEncrpytCredentials(adviseLaunchInfo);\n } else {\n /*window.addEventListener('polymer-ready', function(){*/\n \twindow.addEventListener('WebComponentsReady', function(){\n waitForPolymerAndEncrpytCredentials(adviseLaunchInfo);\n });\n console.log('Waiting for Polymer to be ready..')\n }\n \n } else {\n \n jQuery.ajax({ url : urlL,\n type : \"POST\",\n data : { 'loginTicket' : adviseLaunchInfo.loginTicket },\n dataType : \"text\",\n success : function(returndata, status, xhr) {\n returndata = emxUICore.trim(returndata);\n adviseLaunchInfo.resourceCredentials = returndata;\n \n if (adviseLaunchInfo.userSelectedStation.length > 0 && \n \t\tadviseLaunchInfo.userSelectedStation !== '{localhost}'){\n \t\n \t// If the user chose to set affinity to a regular station.\n \tcheckLocalStationAndLaunch(adviseLaunchInfo);\n \t\n }\n else{\n \n \t// If the user set affinity to {localhost} or no affinity was set\n // try to submit to localhost\n \tcheckPrivateStationAndLaunch(adviseLaunchInfo);\n \t\n }\n },\n error : function(jqXHR, textStatus, errorThrown) {\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_ENC_CREDENTIALS_ERROR'));\n adviseGoBack(\n adviseLaunchInfo.translator.translate('LAUNCH_ENC_CREDENTIALS_ERROR') + '<br\\>' + errorThrown \n );\n }\n });\n }\n }\n });\n}",
"launch() {\n if (window.self !== window.top) {\n // Begin launch and authorization sequence\n this.JSONRPC.notification('launch');\n\n // We have a specific origin to trust (excluding wildcard *),\n // wait for response to authorize.\n if (this.acls.some((x) => x !== '*')) {\n this.JSONRPC.request('authorizeConsumer', [])\n .then(this.authorizeConsumer)\n .catch(this.emitError);\n\n // We don't know who to trust, challenge parent for secret\n } else if (this.secret) {\n this.JSONRPC.request('challengeConsumer', [])\n .then(this.verifyChallenge)\n .catch(this.emitError);\n\n // acl is '*' and there is no secret, immediately authorize content\n } else {\n this.authorizeConsumer();\n }\n\n // If not embedded, immediately authorize content\n } else {\n this.authorizeConsumer();\n }\n }",
"toDescriptor() {\n return {\n apiVersion: 'v1',\n kind: 'Secret',\n metadata: this.metadata,\n data: Object.entries(this.data).reduce((hash, entry) => {\n const [ key, value ] = entry;\n if (value !== undefined) hash[key] = toBase64(value);\n return hash;\n }, {})\n };\n }",
"async function inspectClaimRequest(decision) {\n //Submit the claim request for inspection by the validators.\n //hashuranceABI = ;\n //hashuranceAddress = ;\n hashurancecontract = await new window.web3.eth.Contract(hashuranceABI, hashuranceAddress);\n response = await hashurancecontract.methods.prepForClaimInspection(policyAddress, decision, reason).send({ from: account });\n console.log(response);\n}",
"async function createSaxionWallet(){\n try{\n //maak de wallet aan\n await indy.createWallet(WALLET_NAME, WALLET_CRED)\n LedgerHandler.walletHandle = await indy.openWallet(WALLET_NAME, WALLET_CRED); \n LedgerHandler.dids = {};\n\n //genereer de did die al op de ledger staat met een seed\n [LedgerHandler.dids.veriynimDid, LedgerHandler.dids.veriynimVerkey] = await indy.createAndStoreMyDid(LedgerHandler.walletHandle, {});\n await makeTrustAnchor(LedgerHandler.dids.veriynimDid, LedgerHandler.dids.veriynimVerkey);\n\n let did = LedgerHandler.dids.veriynimDid;\n let poolHandle = LedgerHandler.poolHandle;\n let walletHandle = LedgerHandler.walletHandle;\n\n //hierna moet er nog een Schema gepubliceert worden.\n console.log(\"send Schema\");\n let [diplomaSchemaId, diplomaSchema] = await indy.issuerCreateSchema(did, 'Saxion-Competentie', '1.0',\n ['naam', 'studentnummer', 'vak', 'cijfer', 'ecs']); \n \n await sendSchema(poolHandle, walletHandle, did, diplomaSchema);\n //je moet de schema weer ophalen wil je het gebruiken\n [, diplomaSchema] = await getSchema(poolHandle, did, diplomaSchemaId);\n\n //maak een cred def aan\n console.log(\"send Cred def\");\n let [diplomaCredDefId, diplomaCredDefJson] = await indy.issuerCreateAndStoreCredentialDef(walletHandle, did, diplomaSchema, 'TAG1', 'CL', '{\"support_revocation\": false}');\n await sendCredDef(poolHandle, walletHandle, did, diplomaCredDefJson);\n\n LedgerHandler.dids.diplomaSchemaId = diplomaSchemaId;\n LedgerHandler.dids.diplomaSchema = diplomaSchema;\n LedgerHandler.dids.diplomaCredDefId = diplomaCredDefId;\n LedgerHandler.dids.diplomaCredDefJson = diplomaCredDefJson;\n }catch(e){\n console.log(\"steward wallet already exists, just opening it\");\n //als deze file bestaat dan moet er ook een wallet zijn.\n let rawdata = fs.readFileSync('dids.json'); \n LedgerHandler.dids = JSON.parse(rawdata); \n LedgerHandler.walletHandle = await indy.openWallet(WALLET_NAME, WALLET_CRED); \n }\n}",
"async function authorize_request(req) {\n await req.sts_sdk.authorize_request_account(req);\n await authorize_request_policy(req);\n}",
"function challenge() {\n var url = spWebService.getWebApiRoot() + '/spapi/data/v1/login/challenge';\n if (spAppSettings.clientVersion) {\n url += \"?clientVersion=\" + spAppSettings.clientVersion; // push up the client version. Used to force a refresh\n }\n \n $http({\n method: 'GET',\n url: url,\n });\n }",
"function Implicit(_a) {\n var xframe = _a.xframe, client_id = _a.client_id, oauth_uri = _a.oauth_uri, _b = _a.state, state = _b === void 0 ? random() : _b, context = _a.context, _c = _a.use_cwt, use_cwt = _c === void 0 ? true : _c, redirect_uri = _a.redirect_uri, _d = _a.document, document = _d === void 0 ? Web.window.document : _d, _e = _a.location, location = _e === void 0 ? Web.window.location : _e;\n // targets[\"login.windows.net/.../?...&redirect_uri=lync.com/xframe\"] = \"lync.com/xframe\"\n var ready, targets = {}, ticket, nonce, attempt = 1;\n function isAuthRequired(rsp) {\n // the impicit auth implementation needs to handle web ticket related error codes\n // because it always exchanges the OAuth token for a web ticket to reduce load on the server\n if (rsp.status == 401)\n return true;\n // sometimes the server doesn't send a 401 with the WWW-Authenticate header,\n // but sends some random errors with the X-MS-Diagnostics header with a certain code:\n // if this happens, the client can send a GET to /ucwa/oauth to get a proper 401 response\n if (rsp.status == 500 || rsp.status == 403) {\n var headers = HttpHeaders(rsp.headers);\n var xmsdiag = XMsDiagnostics(headers.get(Auth.sMSD));\n var code = xmsdiag.code;\n // 500 X-MS-Diagnostics: 28032;reason=\"The web ticket is invalid.\"\n // 500 X-MS-diagnostics: 28033;reason=\"The web ticket has expired.\"\n // 500 X-MS-Diagnostics: 28072;reason=\"The ticket presented could not be verified, a new ticket is required.\"\n // 403 X-MS-diagnostics: 28077;reason=\"Invalid Audience in the web ticket\"\n // 403 X-Ms-diagnostics: 28055;reason=\"The OAuth token is invalid.\";faultcode=\"wsse:FailedAuthentication\"\n return code == 28032 || code == 28033 || code == 28072 || code == 28077 || code == 28055;\n }\n return false;\n }\n function getOAuthURI(rsp) {\n // Currently the OAuth URI is given by the server in a WWW-Authenticate header.\n // There is, however, a more general way of discovering this URI, known as OAuth URI discovery.\n // At the moment this mechanism isn't implemented on the server.\n var headers = HttpHeaders(rsp.headers);\n var bearer = W3A(headers.get(Auth.sW3A))['Bearer'];\n return bearer && bearer.authorization_uri;\n }\n return function sendRequest(req, send) {\n function setAuthAndSend(req, refreshed) {\n if (refreshed === void 0) { refreshed = false; }\n // nonce is needed to use the token in the iframe\n if (nonce)\n req.nonce = nonce;\n // if web ticket is available, it can be used directly\n if (ticket) {\n req.headers = req.headers || {};\n req.headers['Authorization'] = ticket;\n }\n return send(req).then(function (rsp) {\n if (refreshed)\n rsp['webTicketRenewed'] = refreshed;\n return rsp;\n });\n }\n // if the iframe is getting a new access token, wait for it\n return Task.wait(ready).then(function () {\n return setAuthAndSend(req);\n }).then(function (rsp) {\n var wtsvc, src;\n if (!isAuthRequired(rsp))\n return rsp;\n // TODO: Ideally, if the request was sent when the attempt value\n // when we got 401 was smaller than the current value, we may\n // try to resend the request since it may succeed with the new ticket.\n if (ready)\n return sendRequest(req, send);\n ticket = null;\n src = xframe.src();\n // xframe.src serves as a URL of the resource which the client needs to get an access token for.\n // However after receiving the first access token from AAD, xframe.src points to a URL on AAD and\n // thus the next time the client might mistakenly assume that it needs an access token for AAD itself.\n // The client needs to know that the URL on AAD indirectly refers to UCWA and to solve this problem\n // the client has a mapping from xframe.src values to actual URLs of UCWA. \n if (targets[src])\n src = targets[src];\n // to get the access token, the client needs to discover first the OAuth URI\n // and the primary source of this URI is the web ticket service's mex config\n wtsvc = new Auth.WebTicketService(new URI(src).path('').query('').hash('') + '', setAuthAndSend, context);\n // 1. The URI given by UI takes precedence over any URI found elsewhere.\n // 2. If authorization_uri can be found in the 401 response, get it from there.\n // 3. Otherwise get the OAuth URI from the mex config.\n ready = Task.wait(oauth_uri || getOAuthURI(rsp) || wtsvc.getOAuthUrl()).catch(function () {\n // if the URI couldn't be found in mex, use an\n // alternate route: the WWW-Authenticate header\n return setAuthAndSend({\n type: 'GET',\n url: '/ucwa/oauth'\n }).then(function (rsp) {\n return getOAuthURI(rsp);\n });\n }).then(function (url) {\n if (!url)\n throw Exception('OAuthUriMissing', { response: rsp });\n var uri = new URI(url);\n var query = URI.Query(uri.query());\n var target = !redirect_uri ? src :\n new URI(location.href).path(new URI(redirect_uri).path()).query('').hash('') + '';\n // to get a new token, the iframe needs to be redirected to a special URL;\n // this URL is better to be unique every time, as otherwise the xframe may do nothing\n nonce = state + '.' + attempt++;\n query.response_type = 'token';\n query.client_id = client_id;\n query.redirect_uri = target;\n query.resource = new URI(src).path('').query('').hash('') + '';\n query.state = nonce;\n // The prompt=none parameter is supposed to replace the \"X-Frame-Options: Deny\" header with\n // a meaningful error message. However due to a bug in the common AAD endpoint this parameter broke\n // the auth flow. The workaround was to use the tenant-specific endpoint, i.e. to replace /common/ with,\n // let's say, /microsoft.com/ in the AAD URL. By now, the bug should've been fixed. With this parameter,\n // if AAD refuses to give a token, it returns an error message to the redirect_uri and thus the SDK\n // can report an error to the UI. Without the parameter, the sign in never ends in this case.\n query.prompt = 'none';\n uri.query(query + '');\n targets[uri + ''] = src;\n return Task.run(function () {\n // after xframe.src.set is done, an OAuth token will be in the iframe\n return !redirect_uri ? xframe.src.set(uri + '') : new Promise(function (resolve, reject) {\n // another way to get a token is to create an iframe and use it to make\n // the OAuth request with redirect_uri pointing to the current site:\n // this will allow to read the actual iframe's URL with #access_token in it\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n iframe.src = uri + '';\n document.body.appendChild(iframe);\n iframe.onload = function () {\n try {\n // the same origin policy allows to read the iframe's URL if that\n // URL and the current page's URL belong to the same domain: this\n // trick allows to read the access token and discard the <iframe>\n var args = URI.Query(iframe.contentWindow.location.hash.slice(1));\n document.body.removeChild(iframe);\n if (args.error) {\n // ...#error=invalid_resource&error_description=...\n reject(Exception('OAuthFailed', args));\n }\n else {\n // ...#access_token=ABC&token_type=Bearer&state=123\n ticket = args.token_type + ' ' + args.access_token;\n resolve(null);\n }\n }\n catch (err) {\n }\n };\n });\n }).then(function () {\n // to reduce load on the server, the token can be exchanged for a web ticket;\n // if something goes wrong during the exchange, the client should use the token\n return use_cwt && wtsvc.getOAuthPath().then(function (path) {\n // the iframe checks the nonce of every request\n return wtsvc.getWebTicket(path);\n }).then(function (cwt) {\n ticket = cwt;\n }, function (err) {\n // since the error is discarded, this is the only way to tell that the cwt request failed\n debug.log(err);\n ticket = null;\n });\n });\n }).finally(function () {\n ready = null;\n });\n // wait for an access token from AAD and resend the request:\n // if it fails again, let the caller get the error response,\n // as getting a yet another access token won't help\n return Task.wait(ready).then(function () {\n return setAuthAndSend(req, true);\n });\n });\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}",
"static createFromGoogleCredential(googleCredentials) {\n return CallCredentials.createFromMetadataGenerator((options, callback) => {\n let getHeaders;\n if (isCurrentOauth2Client(googleCredentials)) {\n getHeaders = googleCredentials.getRequestHeaders(options.service_url);\n }\n else {\n getHeaders = new Promise((resolve, reject) => {\n googleCredentials.getRequestMetadata(options.service_url, (err, headers) => {\n if (err) {\n reject(err);\n return;\n }\n if (!headers) {\n reject(new Error('Headers not set by metadata plugin'));\n return;\n }\n resolve(headers);\n });\n });\n }\n getHeaders.then(headers => {\n const metadata = new metadata_1.Metadata();\n for (const key of Object.keys(headers)) {\n metadata.add(key, headers[key]);\n }\n callback(null, metadata);\n }, err => {\n callback(err);\n });\n });\n }",
"async prepareCredentials() {\n if (this.env[DEFAULT_ENV_SECRET]) {\n const secretmanager = new SecretManager({\n projectId: this.env.GCP_PROJECT,\n });\n const secret = await secretmanager.access(this.env[DEFAULT_ENV_SECRET]);\n if (secret) {\n const secretObj = JSON.parse(secret);\n if (secretObj.token) {\n this.oauthToken = secretObj;\n } else {\n this.serviceAccountKey = secretObj;\n }\n this.logger.info(`Get secret from SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n return;\n }\n this.logger.warn(`Cannot find SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n }\n // To be compatible with previous solution.\n const oauthTokenFile = this.getContentFromEnvVar(DEFAULT_ENV_OAUTH);\n if (oauthTokenFile) {\n this.oauthToken = JSON.parse(oauthTokenFile);\n }\n const serviceAccountKeyFile =\n this.getContentFromEnvVar(DEFAULT_ENV_KEYFILE);\n if (serviceAccountKeyFile) {\n this.serviceAccountKey = JSON.parse(serviceAccountKeyFile);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the dismiss state. | get dismiss() {
return this.skeleton.dismiss;
} | [
"set dismiss(state) {\n this.skeleton.dismiss = state;\n }",
"canDismiss() {\n return true;\n }",
"attemptDismiss() {\n\t\tif(this.state.currentModal.props.dismissible) this.state.currentModal.props.onDismiss();\n\t}",
"get transitioning() {\n return this._fullyOpened === OpenedState.OPENING || this._fullyOpened === OpenedState.CLOSING;\n }",
"function getActionState()/*:String*/ {\n // Is there a Notification?\n var notification/*:Notification*/ = this.getNotification();\n if (!notification) {\n return this.ACTION_STATE_NOTIFICATION_NOT_ACCESSIBLE;\n }\n\n // If notification is RemoteBean, load and check accessibility.\n if (AS3.is(notification, com.coremedia.ui.data.RemoteBean)) {\n switch (com.coremedia.ui.data.RemoteBeanUtil.isAccessible(AS3.as(notification, com.coremedia.ui.data.RemoteBean))) {\n case undefined: return undefined;\n case false: return this.ACTION_STATE_NOTIFICATION_NOT_ACCESSIBLE;\n }\n }\n return this.ACTION_STATE_EXECUTABLE;\n }",
"function getSoundState()\n {\n return ( lastState.sound !== undefined ) ? lastState.sound : settings.soundOn;\n }",
"async hide(isClosing = true) {\n const $obj = this.$();\n if (this.get('isTransitioning')) return;\n this.set('isClosing', isClosing);\n\n const promise = new Promise((resolve) => {\n $obj.on('hidden.bs.modal', () => {\n resolve();\n });\n });\n this.$().modal('hide');\n return promise;\n }",
"dismissPanel() {\n this.setState({isVisible: false, messages: [], timeoutID: null})\n }",
"get isCancelled() {\n return this._isCancelled;\n }",
"function _getPullHeaderState(instance) {\n \n var state = instance.data('pullHeaderState');\n if (!state) {\n // If unknown : take 'initial' as default\n state = 'initial';\n }\n \n return state;\n }",
"rejectTransaction() {\n stateTransition(this, this.state.onRejectTransaction);\n }",
"static async dismiss() {\n await doAction((alert) => alert.dismiss());\n }",
"function stateReverted() {\n var FlowState = w2ui.propertyForm.record.FlowState;\n var si = getCurrentStateInfo();\n if (si == null) {\n console.log('Could not determine the current stateInfo object');\n return;\n }\n si.Reason = \"\";\n var x = document.getElementById(\"smRevertReason\");\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,\"revert\");\n}",
"function getStateLabel(){\n\t\t/*jshint validthis:true */\n\t\tif (! this.state){\n\t\t\treturn \"off\";\n\t\t}\n\n\t\tvar position = (_dec2bin(this.state).length - 1).toString(),\n\t\t\tlabels = _.invert(this.conditions);\n\n\t\treturn labels[position];\n\t}",
"function getViewState() {\n\t\tfor (var i = 0; i < document.forms.length; i++) {\n\t\t\tvar viewStateElement = document.forms[i][VIEW_STATE_PARAM];\n\n\t\t\tif (viewStateElement) {\n\t\t\t\treturn viewStateElement.value;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"get destroyed() {\n return this.#state === kSocketDestroyed;\n }",
"get state() {\n if (!this._state)\n this.startState.applyTransaction(this);\n return this._state;\n }",
"function hidePaymentNotSelectedModal() {\n return { type: types.PAYMENT_SELECTED };\n}",
"closeContentMetaPreview() {\n this.setState(() => ({ ...CONTENT_META_PREVIEW_BASE_STATE }));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParserlog_file_group. | visitLog_file_group(ctx) {
return this.visitChildren(ctx);
} | [
"visitLog_grp(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitRegister_logfile_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAdd_logfile_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDrop_logfile_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitTrace_file_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitTablespace_logging_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDatabase_file_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitLogging_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSupplemental_log_grp_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitError_logging_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitMove_mv_log_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}",
"visitSupplemental_db_logging(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function SqlParserListener() {\n\tantlr4.tree.ParseTreeListener.call(this);\n\treturn this;\n}",
"visitAdd_mv_log_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function logFileOp(message) {\n events.emit('verbose', ' ' + message);\n}",
"visitError_logging_into_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function parse_PrintStatement(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_PrintStatement()\" + '\\n';\n\tCSTREE.addNode('PrintStatment', 'branch');\n\n\t\n\tmatchSpecChars(' print',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\t\n\tmatchSpecChars('(',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\t\n\tparse_Expr(); \n\t\n\t\n\t\n\tmatchSpecChars (')',parseCounter);\n\t\n\tCSTREE.endChildren();\n\n\tparseCounter = parseCounter + 1;\n\t\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
split accesskey according to | function splitAccesskey(val) {
var t = val.split(/\s+/),
keys = [];
for (var i=0, k; k = t[i]; i++) {
k = k[0].toUpperCase(); // first character only
// theoretically non-accessible characters should be ignored, but different systems, different keyboard layouts, ... screw it.
// a map to look up already used access keys would be nice
keys.push(k);
}
return keys;
} | [
"function FindAccessKeyMarker(/*string*/ text)\r\n {\r\n var lenght = text.Length;\r\n var startIndex = 0; \r\n while (startIndex < lenght)\r\n { \r\n \tvar index = text.IndexOf(AccessKeyMarker, startIndex); \r\n if (index == -1)\r\n return -1; \r\n // If next char exist and different from _\r\n if (index + 1 < lenght && text[index + 1] != AccessKeyMarker)\r\n return index;\r\n startIndex = index + 2; \r\n }\r\n\r\n return -1; \r\n }",
"function Keymap(){\r\n this.map = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\r\n 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'backspace', 'enter', 'shift', 'delete'];\r\n }",
"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 BAKeyEquivalents() {\n\t/** associative array of key asign. { keymark : { aliasName, keyCode, DOMName }, ... }\n\t @type Object @const @private */\n\tthis.keyAlias = {\n\t\t'$' : { aliasName : 'Shift' , keyCode : 16, DOMName : 'shiftKey' }, \n\t\t'%' : { aliasName : 'Ctrl' , keyCode : 17, DOMName : 'ctrlKey' }, \n\t\t'~' : { aliasName : 'Alt' , keyCode : 18, DOMName : 'altKey' }, /* alt (Win), option (Mac) */\n\t\t'&' : { aliasName : 'Meta' , keyCode : 91, DOMName : null }, /* win (Win), command (Mac) (no browsers work this..?) */\n\t\t'#' : { aliasName : 'Enter' , keyCode : 13, DOMName : null },\n\t\t'|' : { aliasName : 'Tab' , keyCode : 9, DOMName : null },\n\t\t'!' : { aliasName : 'Esc' , keyCode : 27, DOMName : null },\n\t\t'<' : { aliasName : '\\u2190' , keyCode : 37, DOMName : null }, /* left */\n\t\t'{' : { aliasName : '\\u2191' , keyCode : 38, DOMName : null }, /* up */\n\t\t'>' : { aliasName : '\\u2192' , keyCode : 39, DOMName : null }, /* right */\n\t\t'}' : { aliasName : '\\u2193' , keyCode : 40, DOMName : null } /* down */\n\t}\n\t/** associative array of key equivalents. { name : { key, aCallBack, aThisObject }, ... }\n\t @type Object @private */\n\tthis.equivalents = {};\n\t/** number of equivalents\n\t @type Number @private */\n\tthis.numOfEquivs = 0;\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 setHotKeys() {\n\tdocument.onkeydown = function(ev) {\n\t\tev = ev||window.event;\n\t\tkey = ev.keyCode||ev.which;\n\t\tif (key == 18 && !ev.ctrlKey) {\t// start selection, skip Win AltGr\n\t\t\t_hotkeys.alt = true;\n\t\t\t_hotkeys.focus = -1;\n\t\t\treturn stopEv(ev);\n\t\t}\n\t\telse if (ev.altKey && !ev.ctrlKey && ((key>47 && key<58) || (key>64 && key<91))) {\n\t\t\tkey = String.fromCharCode(key);\n\t\t\tvar n = _hotkeys.focus;\n\t\t\tvar l = document.getElementsBySelector('[accesskey='+key+']');\n\t\t\tvar cnt = l.length;\n\t\t\t_hotkeys.list = l;\n\t\t\tfor (var i=0; i<cnt; i++) {\n\t\t\t\tn = (n+1)%cnt;\n\t\t\t\t// check also if the link is visible\n\t\t\t\tif (l[n].accessKey==key && (l[n].offsetWidth || l[n].offsetHeight)) {\n\t\t\t\t\t_hotkeys.focus = n;\n\t // The timeout is needed to prevent unpredictable behaviour on IE.\n\t\t\t\t\tvar tmp = function() {l[_hotkeys.focus].focus();};\n\t\t\t\t\tsetTimeout(tmp, 0);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn stopEv(ev);\n\t\t}\n\t\tif((ev.ctrlKey && key == 13) || key == 27) {\n\t\t\t_hotkeys.alt = false; // cancel link selection\n\t\t\t_hotkeys.focus = -1;\n\t\t\tev.cancelBubble = true;\n \t\t\tif(ev.stopPropagation) ev.stopPropagation();\n\t\t\t// activate submit/escape form\n\t\t\tfor(var j=0; j<this.forms.length; j++) {\n\t\t\t\tvar form = this.forms[j];\n\t\t\t\tfor (var i=0; i<form.elements.length; i++){\n\t\t\t\t\tvar el = form.elements[i];\n\t\t\t\t\tvar asp = el.getAttribute('aspect');\n\n\t\t\t\t\tif (!string_contains(el.className, 'editbutton') && (asp && asp.indexOf('selector') !== -1) && (key==13 || key==27)) {\n\t\t\t\t\t\tpassBack(key==13 ? el.getAttribute('rel') : false);\n\t\t\t\t\t\tev.returnValue = false;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (((asp && asp.indexOf('default') !== -1) && key==13)||((asp && asp.indexOf('cancel') !== -1) && key==27)) {\n\t\t\t\t\t\tif (validate(el)) {\n\t\t\t\t\t\t\tif (asp.indexOf('nonajax') !== -1)\n\t\t\t\t\t\t\t\tel.click();\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif (asp.indexOf('process') !== -1)\n\t\t\t\t\t\t\t\tJsHttpRequest.request(el, null, 600000);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tJsHttpRequest.request(el);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tev.returnValue = false;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tev.returnValue = false;\n\t\t\treturn false;\n\t\t}\n\t\tif (editors!==undefined && editors[key]) {\n\t\t\tcallEditor(key);\n\t\t\treturn stopEv(ev); // prevent default binding\n\t\t}\n\t\treturn true;\n\t};\n\tdocument.onkeyup = function(ev) {\n\t\tev = ev||window.event;\n\t\tkey = ev.keyCode||ev.which;\n\n\t\tif (_hotkeys.alt==true) {\n\t\t\tif (key == 18) {\n\t\t\t\t_hotkeys.alt = false;\n\t\t\t\tif (_hotkeys.focus >= 0) {\n\t\t\t\t\tvar link = _hotkeys.list[_hotkeys.focus];\n\t\t\t\t\tif(link.onclick)\n\t\t\t\t\t\tlink.onclick();\n\t\t\t\t\telse\n\t\t\t\t\t\tif (link.target=='_blank') {\n\t\t\t\t\t\t\twindow.open(link.href,'','toolbar=no,scrollbar=no,resizable=yes,menubar=no,width=900,height=500');\n\t\t\t\t\t\t\topenWindow(link.href,'_blank');\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\twindow.location = link.href;\n\t\t\t\t}\n\t\t\treturn stopEv(ev);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n}",
"getAuthMechanisms() {\r\n const extension = this._extensions.find((e) => e.split(' ')[0] === 'AUTH');\r\n if (extension) {\r\n return extension.split(' ').filter((e) => !!e).map((e) => e.trim().toUpperCase()).slice(1);\r\n }\r\n else {\r\n return [];\r\n }\r\n }",
"displayKeyString(shortcutEl, keyMapping) {\n shortcutEl.innerHTML = \"\";\n if (keyMapping) {\n for (const keyString of keyMapping.split(Commands.KEY_SEPARATOR)) {\n const s = document.createElement(\"span\");\n s.innerText = keyString;\n shortcutEl.appendChild(s);\n }\n }\n }",
"function kaTool_redirect_onkeypress(e) {\r\n if (document.kaCurrentTool) {\r\n document.kaCurrentTool.onkeypress(e);\r\n }\r\n}",
"function KeychainAccess() {\n\n}",
"function allowAlphabetAndNumerAndDotAndSlash(e) {\n // Get the ASCII value of the key that the user entered\n var key = (document.all) ? window.event.keyCode : e.which;\n\n if ((key >= 65 && key <= 90) || (key >= 97 && key <= 122) || (key >= 48 && key <= 57) || (key == 8) || (key == 32) || (key == 0) || (key == 45) ||\n (key == 47) || (key == 46))\n // If it was, then allow the entry to continue\n return true;\n else\n // If it was not, then dispose the key and continue with entry\n return false;\n }",
"set surround_key(string){ \n this.key_prefix = string\n this.key_suffix = string\n }",
"function getClientKey() {\n\n }",
"is_special_key(event){\n var allowable_is_special_key = [8,35,36,37,38,39,40,46, 9, 27, 13, 110, 116,115];\n var key = event.which || event.keyCode || event.charCode;\n var is_special = allowable_is_special_key.includes(key);\n //if ctrl+a or alt+a is down do not prevent\n var is_special_a = key === 65 && (event.ctrlKey === true || event.metaKey === true)\n //if meta+shift+a or alt+a is down do not prevent\n var is_special_r = key === 82 && (event.shiftKey === true || event.metaKey === true)\n if(is_special || is_special_a || is_special_r ){\n return true;\n }\n return false;\n }",
"function comprobarAlias(a) {\n var contAlias = a.value;\n var expresionAlias = /^[A-Z,a-z,0-9]{3,14}$/;\n\n if(comprobarExpresion(a, expresionAlias)==true){\n validado[1] = true;\n if(debug){\n console.log(\"Validado 1=> \"+validado[1]);\n }\n }\n}",
"keyForCookie(cookie) {\n const { domain, path, name } = cookie;\n return `${domain};${path};${name}`;\n }",
"function NLNameValueList_onKeyPress(evt, sFieldName, sOptionHelperSuffix)\n{\n var keyCode = getEventKeypress(evt);\n\n if( keyCode == 32 ) // <SPACE>\n {\n // if the user hit <SPACE> find the helper icon which pops-up the options dialog and click it\n var ndAction = document.getElementById(sFieldName + '_helper_' + sOptionHelperSuffix);\n if( ndAction && ndAction.click)\n {\n ndAction.click();\n }\n }\n return true;\n}",
"splitFunctionFromKey (theKey) {\n if (theKey !== null && theKey.indexOf('(') !== -1) { // Must be an aggregate or queryFunction\n let functionKeyPair = theKey.split('('); // Split function and property\n let functionAlias = functionKeyPair[0];\n let fieldName = functionKeyPair[1];\n\n let queryFunction = QueryFunctionEnum.getTypeFromAlias(functionAlias);\n\n log.log('splitFunctionFromKey queryFunction', functionAlias, queryFunction);\n\n if (queryFunction !== null) {\n this.queryFunction = queryFunction;\n this.key = fieldName.replace(')', ''); // Remove closing parenthesis from the key\n } else {\n log.error('Unrecognized function alias used by constraint - ' + functionAlias);\n }\n } else {\n log.info('In splitFunctionFromKey, set this.key = ', theKey);\n this.key = theKey;\n }\n }",
"function insertHotkeyListItem(purpose,key,key_sp){\n\t\t\treturn \"<li tabindex='-2' aria-label='\"+hotkeyTrigger+\" \"+key_sp+\", \"+purpose+\"'>\"\n\t\t\t+\"<span class='ANDI508-code'>\"+key+\"</span> \"\n\t\t\t+purpose+\"</li>\";\n\t\t}",
"function validateKey() {\n if ($(this).val()) {\n if ($(this).val().match(/^[A-Za-z0-9]*$/)) return hideError($(this).parent().children(\".error\"));\n else return validationError($(this).parent().children(\".error\"), i18n.KEY_VALIDATION_MESSAGE)\n }\n else return validationError($(this).parent().children(\".error\"), i18n.EMPTY_KEY_MESSAGE)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParsermodel_rules_clause. | visitModel_rules_clause(ctx) {
return this.visitChildren(ctx);
} | [
"visitModel_rules_element(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitModel_rules_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitValidation_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function buildRules( languageNode )\n{\n\tvar contextList, contextNode, sRegExp, rootNode;\t\n\tvar rulePropList, rulePropNode, rulePropNodeAttributes, ruleList, ruleNode;\n\n\trootNode = languageNode.selectSingleNode(\"/*\");\n\t\n\t// first building keyword regexp\n\tbuildKeywordRegExp( languageNode );\t\n\t\n\tcontextList = languageNode.selectNodes(\"contexts/context\");\n\t// create regular expressions for context\n\tfor (contextNode = contextList.nextNode(); contextNode != null; contextNode = contextList.nextNode())\n\t{\n\t\tsRegExp = buildRuleRegExp( languageNode, contextNode );\n\t\t// add attribute\n\t\tcontextNode.setAttribute( \"regexp\", sRegExp );\t\n\t}\n}",
"visitRelational_expression(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitRelational_operator(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitBuild_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}",
"function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}",
"visitModel_iterate_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitLogical_expression(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitFrom_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitConstraint_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitModel_expression_element(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitTablespace_state_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitTablespace_logging_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCost_matrix_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function ExpressionParser() {\n \t\tthis.parse = function() {\n\t \t\treturn Statement(); \n\t \t}\n \t\t\n//\t\tStatement := Assignment | Expr\t\n\t\tthis.Statement=function() {return Statement();}\n\t \tfunction Statement() {\n\t \t\tdebugMsg(\"ExpressionParser : Statement\");\n\t\n \t var ast;\n \t // Expressin or Assignment ??\n \t if (lexer.skipLookAhead().type==\"assignmentOperator\") {\n \t \tast = Assignment(); \n \t } else {\n \t \tast = Expr();\n \t }\n \t return ast;\n\t \t}\n\t \t\n//\t\tAssignment := IdentSequence \"=\" Expr \n//\t\tAST: \"=\": l:target, r:source\n \t\tthis.Assignment = function() {return Assignment();}\n \t\tfunction Assignment() {\n \t\t\tdebugMsg(\"ExpressionParser : Assignment\");\n \t\t\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) return false;\n \t\t\n \t\t\tcheck(\"=\"); // Return if it's not an Assignment\n \t\t\n \t\t\tvar expr=Expr();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"=\",ident,expr);\n\t \t}\n \t\t\n\n//\t\tExpr := And {\"|\" And} \t\n//\t\tAST: \"|\": \"left\":And \"right\":And\n \t\tthis.Expr = function () {return Expr();}\t\n \t\tfunction Expr() {\n \t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\n \t\t\tvar ast=And();\n \t\t\tif (!ast) return false;\n \t\t\t\t\t\n \t\t\n \t\t\twhile (test(\"|\") && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"|\",ast,And());\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n \t\n//\t\tAnd := Comparison {\"&\" Comparison}\n//\t\tAST: \"&\": \"left\":Comparasion \"right\":Comparasion\t\n\t\tfunction And() {\n \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\tvar ast=Comparasion();\n \t\t\tif (!ast) return false;\n \t\t\t\t\n \t\t\twhile (test(\"&\") && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"&\",ast,Comparasion());\n\t \t\t}\n\t \t\treturn ast;\n\t \t}\n\t \t \t\n// \t\tComparison := Sum {(\"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" | \"in\") Sum}\n//\t\tAST: \"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" : \"left\":Sum \"right\":Sum\n\t\tfunction Comparasion() {\n \t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\tvar ast=Sum();\n\t\t\tif (!ast) return false;\n\t\t\n\t\t\twhile ((test(\"==\") ||\n\t\t\t\t\ttest(\"!=\") ||\n\t\t\t\t\ttest(\"<=\") ||\n\t\t\t\t\ttest(\">=\") ||\n\t\t\t\t\ttest(\"<\") ||\n\t\t\t\t\ttest(\">\")) ||\n\t\t\t\t\ttest(\"in\") &&\n\t\t\t\t\t!eof())\n\t\t\t{\n \t\t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\t\tvar symbol=lexer.current.content;\n\t\t\t\tlexer.next();\n\t \t\t\tast=new ASTBinaryNode(symbol,ast,Sum());\n\t\t\t} \t\n\t\t\treturn ast;\t\n\t \t}\n\t \t\n//\t\tSum := [\"+\" | \"-\"] Product {(\"+\" | \"-\") Product}\n//\t\tAST: \"+1\" | \"-1\" : l:Product\n//\t\tAST: \"+\" | \"-\" : l:Product | r:Product \n \t\tfunction Sum() {\n \t\t\tdebugMsg(\"ExpressionParser : Sum\");\n\t\t\n\t\t\tvar ast;\n\t\t\t// Handle Leading Sign\n\t\t\tif (test(\"+\") || test(\"-\")) {\n\t\t\t\tvar sign=lexer.current.content+\"1\";\n\t\t\t\tlexer.next();\n\t\t\t\tast=new ASTUnaryNode(sign,Product());\t\n\t \t\t} else {\n\t \t\t\tast=Product();\n\t \t\t} \n \t\t\t\n \t\t\twhile ((test(\"+\") || test(\"-\")) && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Sum\");\n \t\t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Product());\t\t\n \t\t\t} \t\n \t\t\treturn ast;\n \t\t}\n\n//\t\tProduct := Factor {(\"*\" | \"/\" | \"%\") Factor} \t\n\t \tfunction Product() {\n\t \t\tdebugMsg(\"ExpressionParser : Product\");\n\n \t\t\tvar ast=Factor();\n \t\t\n\t \t\twhile ((test(\"*\") || test(\"/\") || test(\"%\")) && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : Product\");\n\n\t \t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Factor());\n \t\t\t} \n\t \t\treturn ast;\n \t\t}\n \t\t\n// \t Factor := \t\t[(\"this\" | \"super\") \".\"]IdentSequence [\"(\" [Expr {\",\" Expr}] \")\"]\n//\t\t\t\t\t | \"!\" Expr \n//\t\t\t\t\t | \"(\" Expr \")\" \n//\t\t\t\t\t | Array \n//\t\t\t\t\t | Boolean\n//\t\t\t\t\t | Integer\n//\t\t\t\t\t | Number\n//\t\t\t\t\t | Character\n//\t\t\t\t\t | String \n \t\tfunction Factor() {\n \t\t\tdebugMsg(\"ExpressionParser : Factor\"+lexer.current.type);\n\n\t \t\tvar ast;\n \t\t\n\t \t\tswitch (lexer.current.type) {\n\t \t\t\t\n\t \t\t\tcase \"token\"\t:\n\t\t\t\t//\tAST: \"functionCall\": l:Ident(Name) r: [0..x]{Params}\n\t\t\t\t\tswitch (lexer.current.content) {\n\t\t\t\t\t\tcase \"new\": \n\t\t\t\t\t\t\tlexer.next();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar ident=Ident(true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcheck(\"(\");\n\t\t\t\t\t\t\n \t\t\t\t\t\t\tvar param=[];\n \t\t\t\t\t\t\tif(!test(\")\")){\n \t\t\t\t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\t\t\tparam[i]=Expr();\n \t\t\t\t\t\t\t\t}\n \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 \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\t\t\t\t\tast=new ASTBinaryNode(\"new\",ident,param);\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t\tcase \"this\":\n \t\t\t\t\t\tcase \"super\":\n\t\t\t\t\t\tcase \"constructor\": return IdentSequence();\n \t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n//\t\t\t\tFactor :=\tIdentSequence \t\t\t\t\n \t\t\t\tcase \"ident\":\n \t\t\t\t return IdentSequence();\n \t\t\t\tbreak;\n \t\t\t\t\n// \t\t\tFactor:= \"!\" Expr\t\t\t\n \t\t\t\tcase \"operator\": \n\t \t\t\t\tif (!test(\"!\")) {\n\t \t\t\t\t\terror.expressionExpected();\n\t \t\t\t\t\treturn false;\n \t\t\t\t\t}\n \t\t\t\t\tlexer.next();\n \t\t\t\t\n\t \t\t\t\tvar expr=Expr();\n \t\t\t\t\tast=new ASTUnaryNode(\"!\",expr);\n\t \t\t\tbreak;\n \t\t\t\t\n//\t\t\t\tFactor:= \"(\" Expr \")\" | Array \t\t\t\n \t\t\t\tcase \"brace\"\t:\n \t\t\t\t\tswitch (lexer.current.content) {\n \t\t\t\t\t\t\n// \t\t\t\t\t \"(\" Expr \")\"\n \t\t\t\t\t\tcase \"(\":\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\tast=Expr();\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\tbreak;\n \t\n \t\t\t\t\t\n \t\t\t\t\t\tdefault:\n \t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t \treturn false;\n\t \t\t\t\t\tbreak;\n\t \t\t\t\t}\n\t \t\t\tbreak;\n \t\t\t\n//\t\t\t\tFactor:= Boolean | Integer | Number | Character | String\n//\t\t\t\tAST: \"literal\": l: \"bool\" | \"int\" | \"float\" | \"string\" | \"char\": content: Value \n\t \t\t\tcase \"_$boolean\" \t\t:\t\t\t\n\t \t\t\tcase \"_$integer\" \t\t:\n\t \t\t\tcase \"_$number\" \t\t:\n\t \t\t\tcase \"_$string\"\t\t\t:\t\t\n\t\t\t\tcase \"_$character\"\t\t:\n\t\t\t\tcase \"null\"\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t\tast=new ASTUnaryNode(\"literal\",lexer.current);\n \t\t\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\tbreak;\n\t\t\t\t\n//\t\t\t\tNot A Factor \t\t\t\t \t\t\t\t\n \t\t\t\tdefault: \terror.expressionExpected();\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\treturn false;\n\t \t\t\t\t\t\tbreak;\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n\n \n//\t\tIdentSequence := (\"this\" | \"super\") | [(\"this\" | \"super\") \".\"] (\"constructor\" \"(\" [Expr {\",\" Expr}] \")\" | Ident {{ArrayIndex} | \".\" Ident } [\"(\" [Expr {\",\" Expr}] \")\"]);\n//\t\tAST: \"identSequence\": l: [0..x][\"_$this\"|\"_$super\"](\"constructor\" | Ident{Ident | ArrayIndex})\n// \t\tor AST: \"functionCall\": l:AST IdentSequence(Name), r: [0..x]{Params}\n\t\tthis.IdentSequence=function () {return IdentSequence();};\n \t\tfunction IdentSequence() {\n \t\t\tdebugMsg(\"ExpressionParser:IdentSequence()\");\n \t\t\t\n \t\t\tvar ast=new ASTListNode(\"identSequence\");\n \t\t\tif (test(\"this\") || test(\"super\")) {\n \t\t\t\tast.add({\"type\":\"ident\",\"content\":\"_$\"+lexer.current.content,\"line\":lexer.current.line,\"column\":lexer.current.column});\n \t\t\t\tlexer.next();\n \t\t\t\tif (!(test(\".\"))) return ast;\n \t\t\t\tlexer.next();\n \t\t\t}\n\n\t\t\tvar functionCall=false;\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tast.add({\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column});\n\t\t\t\tlexer.next();\n\t\t\t\tcheck(\"(\");\n\t\t\t\tfunctionCall=true;\n\t\t\t} else {\n \t\t\t\tvar ident=Ident(true);\n \t\t\t\n \t\t\t\tast.add(ident);\n \t\t\t\n \t\t\t\tvar index;\n \t\t\t\twhile((test(\".\") || test(\"[\")) && !eof()) {\n \t\t\t\t\t if (test(\".\")) {\n \t\t\t\t\t \tlexer.next();\n \t\t\t\t\t\tast.add(Ident(true));\n \t\t\t\t\t} else ast.add(ArrayIndex());\n \t\t\t\t}\n \t\t\t\tif (test(\"(\")) {\n \t\t\t\t\tfunctionCall=true;\n \t\t\t\t\tlexer.next();\n \t\t\t\t}\n \t\t\t}\n \t\n \t\t\tif (functionCall) {\t\n\t\t\t\tvar param=[];\n\t\t\t\tif(!test(\")\")){\n \t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\tparam[i]=Expr();\t\t\t\t\t\t\t\n \t\t\t\t\t}\n \t\t\t\t}\t \t\t\t\t\t\t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\tast=new ASTBinaryNode(\"functionCall\",ast,param);\n \t\t\t} \n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tArrayIndex:=\"[\" Expr \"]\"\n //\t\tAST: \"arrayIndex\": l: Expr\n \t\tfunction ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}\n\n//\t\tIdent := Letter {Letter | Digit | \"_\"}\n//\t\tAST: \"ident\", \"content\":Ident\n\t \tthis.Ident=function(forced) {return Ident(forced);}\n \t\tfunction Ident(forced) {\n \t\t\tdebugMsg(\"ExpressionParser:Ident(\"+forced+\")\");\n \t\t\tif (testType(\"ident\")) {\n \t\t\t\tvar ast=lexer.current;\n \t\t\t\tlexer.next();\n \t\t\t\treturn ast;\n \t\t\t} else {\n \t\t\t\tif (!forced) return false; \n \t\t\t\telse { \n \t\t\t\t\terror.identifierExpected();\n\t\t\t\t\treturn SystemIdentifier();\n\t\t\t\t}\n\t\t\t} \t\n \t\t}\n \t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
h: 0360 s: 0100 v: 0100 returns: [ 0255, 0255, 0255 ] | function HSV_RGB (h, s, v) {
var u = 255 * (v / 100);
if (h === null) {
return [ u, u, u ];
}
h /= 60;
s /= 100;
var i = Math.floor(h);
var f = i%2 ? h-i : 1-(h-i);
var m = u * (1 - s);
var n = u * (1 - s * f);
switch (i) {
case 6:
case 0: return [u,n,m];
case 1: return [n,u,m];
case 2: return [m,u,n];
case 3: return [m,n,u];
case 4: return [n,m,u];
case 5: return [u,m,n];
}
} | [
"function rgbToHsv(r, g, b){\n r = r/255, g = g/255, b = b/255;\n var max = Math.max(r, g, b), min = Math.min(r, g, b);\n var h, s, v = max;\n\n var d = max - min;\n s = max == 0 ? 0 : d / max;\n\n if(max == min){\n h = 0; // achromatic\n }else{\n switch(max){\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n h /= 6;\n }\n\n return [h, s, v];\n }",
"function HSL_to_RGB(H, S, L){\n\t\n\tfunction Hue_2_RGB( v1, v2, vH ) //Function Hue_2_RGB\n\t{\n\t if ( vH < 0 )\n\t vH += 1\n\t if ( vH > 1 )\n\t vH -= 1\n\t if ( ( 6 * vH ) < 1 )\n\t return ( v1 + ( v2 - v1 ) * 6 * vH )\n\t if ( ( 2 * vH ) < 1 )\n\t return ( v2 )\n\t if ( ( 3 * vH ) < 2 )\n\t return ( v1 + ( v2 - v1 ) * ( ( 2 / 3 ) - vH ) * 6 )\n\t \n\t return ( v1 )\n\t}\n\t\n\t H = H / 360;\n S = S / 100;\n L = L / 100;\n\t\t\n\tif ( S == 0 ) //HSL values = 0 � 1\n\t{\n\t R = L * 255; //RGB results = 0 � 255\n\t G = L * 255;\n\t B = L * 255;\n\t}\n\telse\n\t{\n\t if ( L < 0.5 )\n\t \t\tvar_2 = L * ( 1 + S );\n\t else\n\t \t\tvar_2 = ( L + S ) - ( S * L );\n\t\n\t var_1 = 2 * L - var_2;\n\t\n\t R = 255 * Hue_2_RGB( var_1, var_2, H + ( 1 / 3 ) );\n\t G = 255 * Hue_2_RGB( var_1, var_2, H );\n\t B = 255 * Hue_2_RGB( var_1, var_2, H - ( 1 / 3 ) );\n\t}\n\t\n\tRGBcolor = {};\n\tRGBcolor.R = parseInt(R);\n\tRGBcolor.G = parseInt(G);\n\tRGBcolor.B = parseInt(B);\n\treturn RGBcolor;\n\t\n}",
"function nm2rgb(h) {\n var wavelength = 380 + h * 400;\n var Gamma = 0.80,\n IntensityMax = 255,\n factor, red, green, blue;\n\n if((wavelength >= 380) && (wavelength < 440)) {\n red = -(wavelength - 440) / (440 - 380);\n green = 0.0;\n blue = 1.0;\n } else if((wavelength >= 440) && (wavelength < 490)) {\n red = 0.0;\n green = (wavelength - 440) / (490 - 440);\n blue = 1.0;\n } else if((wavelength >= 490) && (wavelength < 510)) {\n red = 0.0;\n green = 1.0;\n blue = -(wavelength - 510) / (510 - 490);\n } else if((wavelength >= 510) && (wavelength < 580)) {\n red = (wavelength - 510) / (580 - 510);\n green = 1.0;\n blue = 0.0;\n } else if((wavelength >= 580) && (wavelength < 645)) {\n red = 1.0;\n green = -(wavelength - 645) / (645 - 580);\n blue = 0.0;\n } else if((wavelength >= 645) && (wavelength < 781)) {\n red = 1.0;\n green = 0.0;\n blue = 0.0;\n } else {\n red = 0.0;\n green = 0.0;\n blue = 0.0;\n };\n\n // Let the intensity fall off near the vision limits\n\n if((wavelength >= 380) && (wavelength < 420)){\n factor = 0.3 + 0.7*(wavelength - 380) / (420 - 380);\n } else if((wavelength >= 420) && (wavelength < 701)){\n factor = 1.0;\n } else if((wavelength >= 701) && (wavelength < 781)){\n factor = 0.3 + 0.7*(780 - wavelength) / (780 - 700);\n } else{\n factor = 0.0;\n };\n\n if(red !== 0){\n red = Math.round(IntensityMax * Math.pow(red * factor, Gamma));\n }\n if(green !== 0){\n green = Math.round(IntensityMax * Math.pow(green * factor, Gamma));\n }\n if(blue !== 0){\n blue = Math.round(IntensityMax * Math.pow(blue * factor, Gamma));\n }\n\n return {\n r: red,\n g: green,\n b: blue,\n a: 255\n };\n }",
"function HSBtoRGB(hue, saturation, brightness){\n \n //Normalize input\n let h = hue*(Math.PI/180);\n let s = saturation/100;\n let b = brightness/100;\n \n //Define variables i and f\n let i = Math.floor((3*h)/Math.PI);\n let f = ((3*h)/Math.PI) - i;\n \n //Calculating RGB values\n let p = b * (1 - s);\n let q = b * (1 - (f*s));\n let t = b * (1 - ((1 - f)*s));\n \n switch(i){\n case 0:\n printRGB(b,t,p);\n break;\n case 1:\n printRGB(q,b,p);\n break;\n case 2:\n printRGB(p,b,t);\n break;\n case 3:\n printRGB(p,q,b);\n break;\n case 4:\n printRGB(t,p,b);\n break;\n case 5:\n printRGB(b,p,q);\n break;\n }\n \n //Function that prints result to console\n //Saves on writting repeated code\n function printRGB(r, g , b){\n print(\"HSB(\" + hue + \", \" + saturation + \", \" + brightness + \") = RGB(\" + Math.round(r*255) + \", \" + Math.round(g*255) + \", \" + Math.round(b*255) + \")\");\n }\n}",
"static uint240(v) { return n(v, 240); }",
"function RGBToHSL_optimized(r, g, b) {\r\n\r\n // Note: multiplication is faster than division\r\n const m = 1 / 255;\r\n r *= m;\r\n g *= m;\r\n b *= m;\r\n\r\n // Note: replace the calls to Math.min and Math.max with 3 if statements\r\n let cmin = r;\r\n let cmax = g;\r\n\r\n if (r > g) {\r\n cmin = g;\r\n cmax = r;\r\n }\r\n\r\n if (b < cmin) cmin = b;\r\n if (b > cmax) cmax = b;\r\n\r\n const delta = cmax - cmin;\r\n\r\n let h = 0;\r\n let s = 0;\r\n let l = (cmax + cmin);\r\n\r\n if (delta > 0) {\r\n\r\n switch (cmax) {\r\n case r:\r\n h = (g - b) / delta + (g < b && 6);\r\n break;\r\n case g:\r\n h = (b - r) / delta + 2;\r\n break;\r\n case b:\r\n h = (r - g) / delta + 4;\r\n break;\r\n }\r\n\r\n h *= 60;\r\n\r\n // Note: abs on an f64 is as easy as flipping a bit\r\n s = 100 * delta / (1 - Math.abs(l - 1));\r\n }\r\n\r\n l *= 50;\r\n\r\n return [h, s, l]\r\n}",
"function HSLA_TO_HSVA() {\n var h = this.h();\n var s = this.s();\n var l = this.l();\n var a = this.a();\n\n l *= 2;\n s *= (l <= 1) ? l : 2 - l;\n var v = (l + s) / 2;\n var sv = (2 * s) / (l + s);\n return kolor.hsva(h, sv, v, a);\n }",
"function RGB_to_HSL(R, G, B){\n\t\n\tvar_R = ( R / 255 ); //Where RGB values = 0 � 255\n\tvar_G = ( G / 255 );\n\tvar_B = ( B / 255 );\n\t\n\tvar_Min = Math.min( var_R, var_G, var_B ); //Min. value of RGB\n\tvar_Max = Math.max( var_R, var_G, var_B ); //Max. value of RGB\n\tdel_Max = var_Max - var_Min; //Delta RGB value\n\t\n\tL = ( var_Max + var_Min ) / 2;\n\t\n\tif ( del_Max == 0 ) //This is a gray, no chroma...\n\t{\n\t H = 0; //HSL results = 0 � 1\n\t S = 0;\n\t}\n\telse //Chromatic data...\n\t{\n\t if ( L < 0.5 )\n\t S = del_Max / ( var_Max + var_Min );\n\t else\n\t S = del_Max / ( 2 - var_Max - var_Min );\n\t\n\t del_R = ( ( ( var_Max - var_R ) / 6 ) + ( del_Max / 2 ) ) / del_Max;\n\t del_G = ( ( ( var_Max - var_G ) / 6 ) + ( del_Max / 2 ) ) / del_Max;\n\t del_B = ( ( ( var_Max - var_B ) / 6 ) + ( del_Max / 2 ) ) / del_Max;\n\t\n\t if ( var_R == var_Max )\n\t H = del_B - del_G;\n\t else if ( var_G == var_Max )\n\t H = ( 1 / 3 ) + del_R - del_B;\n\t else if ( var_B == var_Max )\n\t H = ( 2 / 3 ) + del_G - del_R;\n\t\n\t if ( H < 0 )\n\t H += 1;\n\t if ( H > 1 )\n\t H -= 1;\n\t}\n\tHSLcolor = {};\n\tHSLcolor.H = parseInt(H*360);\n\tHSLcolor.S = parseInt(S*100);\n\tHSLcolor.L = parseInt(L*100);\n\treturn HSLcolor;\n}",
"function HSVA_TO_HWB() {\n var h = this.h();\n var s = this.s();\n var v = this.v();\n var a = this.a();\n return kolor.hwb(h, (1 - s) * v, 1 - v, a);\n }",
"function hueChannelData() {\n for (var column = 0, i=-1; column < 360; ++column) {\n var tempColor = {\n h: column,\n s: 100,\n v: 100\n }\n var tempRGBColor = HSVtoRGB(normHSV(tempColor));\n hCImage.data[++i] = Math.round(tempRGBColor.r*255);\n hCImage.data[++i] = Math.round(tempRGBColor.g*255);\n hCImage.data[++i] = Math.round(tempRGBColor.b*255);\n hCImage.data[++i] = 255;\n }\n hCContext.putImageData(hCImage,0,0);\n }",
"function HWB_TO_HSVA() {\n var h = this.h();\n var w = this.w();\n var b = this.b();\n var a = this.a();\n return kolor.hsva(h, 1 - w / (1 - b), 1 - b, a);\n }",
"function hslToHex(h ,s ,l){\n let rgb = Vibrant.Util.hslToRgb(h, s, l);\n let hex = Vibrant.Util.rgbToHex(rgb[0], rgb[1], rgb[2]);\n // console.log(hex)\n return hex;\n}",
"function rgb2hsb(rgb) {\n var hsb = { h: 0, s: 0, b: 0 };\n var min = Math.min(rgb.r, rgb.g, rgb.b);\n var max = Math.max(rgb.r, rgb.g, rgb.b);\n var delta = max - min;\n hsb.b = max;\n hsb.s = max !== 0 ? 255 * delta / max : 0;\n if (hsb.s !== 0) {\n if (rgb.r === max) {\n hsb.h = (rgb.g - rgb.b) / delta;\n } else if (rgb.g === max) {\n hsb.h = 2 + (rgb.b - rgb.r) / delta;\n } else {\n hsb.h = 4 + (rgb.r - rgb.g) / delta;\n }\n } else {\n hsb.h = -1;\n }\n hsb.h *= 60;\n if (hsb.h < 0) {\n hsb.h += 360;\n }\n hsb.s *= 100 / 255;\n hsb.b *= 100 / 255;\n return hsb;\n }",
"function RGBA_TO_HSVA() {\n var r = this.r() / 255;\n var g = this.g() / 255;\n var b = this.b() / 255;\n var a = this.a();\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var diff = max - min;\n var h;\n var s;\n\n if (max === min) {\n h = 0;\n } else if (max === r && g >= b) {\n h = 60 * (g - b) / diff + 0;\n } else if (max === r && g < b) {\n h = 60 * (g - b) / diff + 360;\n } else if (max === g) {\n h = 60 * (b - r) / diff + 120;\n } else { // max === b\n h = 60 * (r - g) / diff + 240;\n }\n\n if (max === 0) {\n s = 0;\n } else {\n s = diff / max;\n }\n\n var v = max;\n return kolor.hsva(h, s, v, a);\n }",
"function redHue() {\n for (var pixel of image.values()) {\n var avg =\n (pixel.getRed() + pixel.getGreen() + pixel.getBlue()) /3;\n if (avg < 128){\n pixel.setRed(2 * avg);\n pixel.setGreen(0);\n pixel.setBlue(0);\n } else {\n pixel.setRed(255);\n pixel.setGreen(2 * avg - 255);\n pixel.setBlue(2 * avg - 255);\n }\n }\n var c2 = document.getElementById(\"c2\");\n var image2 = image;\n image2.drawTo(c2);\n \n \n}",
"static FromInts(r, g, b) {\n return new Color3(r / 255.0, g / 255.0, b / 255.0);\n }",
"function RGBA_TO_HSLA() {\n var r = this.r() / 255;\n var g = this.g() / 255;\n var b = this.b() / 255;\n var a = this.a();\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var diff = max - min;\n var sum = max + min;\n var h;\n var s;\n var l;\n\n if (max === min) {\n h = 0;\n } else if (max === r && g >= b) {\n h = 60 * (g - b) / diff + 0;\n } else if (max === r && g < b) {\n h = 60 * (g - b) / diff + 360;\n } else if (max === g) {\n h = 60 * (b - r) / diff + 120;\n } else { // max === b\n h = 60 * (r - g) / diff + 240;\n }\n\n l = sum / 2;\n\n if (l === 0 || max === min) {\n s = 0;\n } else if (0 < l && l <= 0.5) {\n s = diff / sum;\n } else { // l > 0.5\n s = diff / (2 - sum);\n }\n\n return kolor.hsla(h, s, l, a);\n }",
"function rgbToSix(r) {\n return r / 51;\n}",
"function highlight() {\n\tvar curmins = Math.floor(vid.currentTime / 60);\n var cursecs = Math.floor(vid.currentTime - curmins * 60);\n\nif (cursecs <= 3.50 ) {p[0].style.color=\"orange\";\n\t \tp[0].style.backgoundcolor=\"\";\n\t } else if (cursecs >= 3.50 && cursecs <= 7.53) {\n\t \tp[1].style.color=\"orange\";\n\t \tp[0].style.color=\"\";\n\t } else if (cursecs >= 7.54 && cursecs <= 10.40) {\n\t \tp[2].style.color=\"orange\";\n\t \tp[1].style.color=\"\";\n\t }\n\t else if (cursecs >= 10.41 && cursecs <= 13.90) {\n\t \tp[3].style.color=\"orange\";\n\t \tp[2].style.color=\"\";\n\t }\n\t else if (cursecs >= 13.91 && cursecs <= 17.94) {\n\t \tp[4].style.color=\"orange\";\n\t \tp[3].style.color=\"\";\n\t }\n\t else if (cursecs >= 17.95 && cursecs <= 21.30) {\n\t \tp[5].style.color=\"orange\";\n\t \tp[4].style.color=\"\";\n\t }\n\t else if (cursecs >= 21.31 && cursecs <= 25) {\n\t \tp[6].style.color=\"orange\";\n\t \tp[5].style.color=\"\";\n\t } \n\t else if (cursecs >= 25.30 && cursecs <= 30.92) {\n\t \tp[7].style.color=\"orange\";\n\t \tp[6].style.color=\"\";\n\t } \n\t else if (cursecs >= 31 && cursecs <= 33.30) {\n\t \tp[8].style.color=\"orange\";\n\t \tp[7].style.color=\"\";\n\t }\n\t else if (cursecs >= 33.31 && cursecs <= 38.40) {\n\t \tp[9].style.color=\"orange\";\n\t \tp[8].style.color=\"\";\n\t }\n\t else if (cursecs >= 38.41 && cursecs <= 41) {\n\t \tp[10].style.color=\"orange\";\n\t \tp[9].style.color=\"\";\n\t }\n\t else if (cursecs >= 42 && cursecs <= 45.40) {\n\t \tp[11].style.color=\"orange\";\n\t \tp[10].style.color=\"\";\n\t }\n\t else if (cursecs >= 45.41 && cursecs <= 48.40) {\n\t \tp[12].style.color=\"orange\";\n\t \tp[11].style.color=\"\";\n\t }\n\t else if (cursecs >= 48.41 && cursecs <= 52.30) {\n\t \tp[13].style.color=\"orange\";\n\t \tp[12].style.color=\"\";\n\t }\n\t else if (cursecs >= 52.31 && cursecs <= 56.40) {\n\t \tp[14].style.color=\"orange\";\n\t \tp[13].style.color=\"\";\n\t }\n\t else if (cursecs >= 56.41) {\n\t \tp[15].style.color=\"orange\";\n\t \tp[14].style.color=\"\";\n } \n}",
"custom (mode, speed, ...colors) {\n let ary = [0x99]\n for (var idx = 0; idx < 16; idx++) {\n if (idx < colors.length) {\n ary = ary.concat(colors[idx])\n } else {\n ary = ary.concat([1, 2, 3])\n }\n }\n ary = ary.concat(speed)\n ary = ary.concat(mode + 0x39)\n ary = ary.concat([0xff, 0x66])\n console.log(ary)\n this._sendMessage(ary)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
copyright when copy text page | function copyright() {
//Get the selected text and append the extra info
var selection = window.getSelection(),
website = 'www.binhbatoday.com', //website
pagelink = '. Nguồn từ: ' + website, // text
copytext = selection + pagelink,
newdiv = document.createElement('div');
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
//insert the container, fill it with the extended text, and define the new selection
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
document.body.removeChild(newdiv);
}, 100);
} | [
"function changeCopyRight()\n{\n console.log(\"\\tStart changeCopyRight\");\n var i;\n\n var name = \"\";\n var short = \"\";\n var url = \"\";\n var image = \"\";\n\n console.log(\"\\t\\tOpgegeven licence in config is [\" + respecConfig.licence + \"]\");\n if( respecConfig.licence != null)\n {\n var srch = \"copyright\";\n var tags = document.getElementsByTagName(\"p\");\n for (i = 0; i < tags.length; i++) \n {\n if(tags[i].className = srch)\n {\n console.log(\"\\t\\tclassName [\" + srch + \"] is gevonden\");\n //-- Bepaal welke licentie het moet worden\n switch(respecConfig.licence) \n {\n case \"cc0\":\n name = \"Creative Commons 0 Public Domain Dedication\";\n short = \"CC0\";\n url = \"https://creativecommons.org/publicdomain/zero/1.0/\";\n image = respecParams.urlTools + respecParams.dirBanners + \"CC-Licentie.svg\";\n break;\n\n case \"cc-by\":\n name = \"Creative Commons Attribution 4.0 International Public License\";\n short = \"CC-BY\";\n url = \"https://creativecommons.org/licenses/by/4.0/legalcode\";\n image = respecParams.urlTools + respecParams.dirBanners + \"cc-by.svg\";\n break;\n\n case \"cc-by-nd\":\n name = \"Creative Commons Attribution-NoDerivatives 4.0 International Public License\";\n short = \"CC-BY-ND\";\n url = \"https://creativecommons.org/licenses/by-nd/4.0/legalcode.nl\";\n image = respecParams.urlTools + respecParams.dirBanners + \"cc-by-nd.svg\";\n break;\n\n case \"none\":\n short = \"\";\n tags[i].parentNode.removeChild(tags[i]);\n console.log(\"Class [\" + srch + \"] is verwijderd\");\n break;\n\n default:\n short = \"ERROR\";\n name = \"Copyright error, check config.js : license: \" + respecConfig.licence;\n break;\n }\n\n //-- pas innerHTML aan\n if(short != \"\")\n {\n tags[i].innerHTML = \n '<dl>' + \n '<dt>Rechtenbeleid:</dt>' + \n '<dd>' +\n '<div class=\"copyright\" style=\"margin: 0.25em 0;\">' +\n '<abbr title=\"' + name +'\">' +\n '<a href=\"' + url + '\">' +\n '<img src=\"' + image + '\" alt=\"' + name + '\" width=\"115\" height=\"40\">' +\n '</a>' +\n '</abbr>' +\n '<div style=\"display:inline-block; vertical-align:top\">' +\n '<p style=\"font-size: small;\">' + name + '<br>(' + short +')</p>' +\n '</div>' +\n '</div>' +\n '</dd>' +\n '</dl>';\n console.log(\"\\t\\tclassName [\" + srch + \"] is aangepast naar [\" + short + \"]\");\n } \n break;\n }\n }\n } \n else\n {\n console.log(\"\\tclassName [\" + srch + \"] is NIET aangepast\");\n }\n\n console.log(\"\\tEinde changeCopyRight\");\n}",
"function handleDescriptionCopy() {\n var copyText = document.getElementById(\"part-descriptions\");\n copyText.select();\n copyText.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n setShow(true);\n setalertTitle(\"Copied\");\n setalertText(\"Copied the text: \" + copyText.value);\n setalertIcon(\"fas fa-copy mr-3\");\n setalertColor(\"bg-alert-success\");\n }",
"function output_license_html ()\n {\n\t\tvar output = get_comment_code() + '<a rel=\"license\" href=\"' + license_array['url'] + '\"><img alt=\"Creative Commons License\" border=\"0\" src=\"' + license_array['img'] + '\" class=\"cc-button\"/></a><div class=\"cc-info\">' + license_array['text'] + '</div>';\n\n try {\n if ( $F('using_myspace') )\n {\n\t\t output = '<style type=\"text/css\">body { padding-bottom: 50px;} div.cc-bar { width:100%; height: 40px; ' + position() + ' bottom: 0px; left: 0px; background:url(http://mirrors.creativecommons.org/myspace/'+ style() +') repeat-x; } img.cc-button { float: left; border:0; margin: 5px 0 0 15px; } div.cc-info { float: right; padding: 0.3%; width: 400px; margin: auto; vertical-align: middle; font-size: 90%;} </style> <div class=\"cc-bar\">' + output + '</div>';\n } else if ( $F('using_youtube') ) {\n output = license_array['url'];\n }\n\n } catch (err) {}\n\n insert_html( warning_text + output, 'license_example');\n return output;\n\t}",
"function Copyright() {\n return (\n <Typography variant=\"body2\" color=\"textSecondary\" align=\"center\">\n {'Copyright © '}\n <Link color=\"inherit\" href=\"https://material-ui.com/\">\n Material-UI\n </Link>{' '}\n {new Date().getFullYear()}\n </Typography>\n );\n}",
"function handlePartsListCopy() {\n var copyText = document.getElementById(\"parts-box\");\n copyText.select();\n copyText.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n setShow(true);\n setalertTitle(\"Copied\");\n setalertText(\"Copied the text: \" + copyText.value);\n setalertIcon(\"fas fa-copy mr-3\");\n setalertColor(\"bg-alert-success\");\n }",
"function copyToClipboard() {\n var el = document.createElement('textarea');\n el.value = loremIpsumText.textContent;\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n}",
"async copyTo(page, publish = true) {\n // we know the method is on the class - but it is protected so not part of the interface\n page.setControls(this.getControls());\n // copy page properties\n if (this._layoutPart.properties) {\n if (hOP(this._layoutPart.properties, \"topicHeader\")) {\n page.topicHeader = this._layoutPart.properties.topicHeader;\n }\n if (hOP(this._layoutPart.properties, \"imageSourceType\")) {\n page._layoutPart.properties.imageSourceType = this._layoutPart.properties.imageSourceType;\n }\n if (hOP(this._layoutPart.properties, \"layoutType\")) {\n page._layoutPart.properties.layoutType = this._layoutPart.properties.layoutType;\n }\n if (hOP(this._layoutPart.properties, \"textAlignment\")) {\n page._layoutPart.properties.textAlignment = this._layoutPart.properties.textAlignment;\n }\n if (hOP(this._layoutPart.properties, \"showTopicHeader\")) {\n page._layoutPart.properties.showTopicHeader = this._layoutPart.properties.showTopicHeader;\n }\n if (hOP(this._layoutPart.properties, \"showPublishDate\")) {\n page._layoutPart.properties.showPublishDate = this._layoutPart.properties.showPublishDate;\n }\n if (hOP(this._layoutPart.properties, \"enableGradientEffect\")) {\n page._layoutPart.properties.enableGradientEffect = this._layoutPart.properties.enableGradientEffect;\n }\n }\n // we need to do some work to set the banner image url in the copied page\n if (!stringIsNullOrEmpty(this.json.BannerImageUrl)) {\n // use a URL to parse things for us\n const url = new URL(this.json.BannerImageUrl);\n // helper function to translate the guid strings into properly formatted guids with dashes\n const makeGuid = (s) => s.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/g, \"$1-$2-$3-$4-$5\");\n // protect against errors because the serverside impl has changed, we'll just skip\n if (url.searchParams.has(\"guidSite\") && url.searchParams.has(\"guidWeb\") && url.searchParams.has(\"guidFile\")) {\n const guidSite = makeGuid(url.searchParams.get(\"guidSite\"));\n const guidWeb = makeGuid(url.searchParams.get(\"guidWeb\"));\n const guidFile = makeGuid(url.searchParams.get(\"guidFile\"));\n const site = Site(this);\n const id = await site.select(\"Id\")();\n // the site guid must match the current site's guid or we are unable to set the image\n if (id.Id === guidSite) {\n const openWeb = await site.openWebById(guidWeb);\n const file = await openWeb.web.getFileById(guidFile).select(\"ServerRelativeUrl\")();\n const props = {};\n if (this._layoutPart.properties) {\n if (hOP(this._layoutPart.properties, \"translateX\")) {\n props.translateX = this._layoutPart.properties.translateX;\n }\n if (hOP(this._layoutPart.properties, \"translateY\")) {\n props.translateY = this._layoutPart.properties.translateY;\n }\n if (hOP(this._layoutPart.properties, \"imageSourceType\")) {\n props.imageSourceType = this._layoutPart.properties.imageSourceType;\n }\n if (hOP(this._layoutPart.properties, \"altText\")) {\n props.altText = this._layoutPart.properties.altText;\n }\n }\n page.setBannerImage(file.ServerRelativeUrl, props);\n }\n }\n }\n await page.save(publish);\n return page;\n }",
"function dc_copy_to_clipboard(div) {\n let copyText = document.getElementById(div).innerText;\n //console.log(copyText);\n /* Copy the text inside the text field */\n navigator.clipboard.writeText(copyText);\n}",
"function selectTextAndCopy(containerId) {\n if (wasLastCopied(containerId)) {\n return;\n }\n\n try {\n if (highlightContent(containerId)) {\n if (document.queryCommandSupported(\"copy\")) {\n document.execCommand(\"copy\") && showCurrentCopyAlert(containerId);\n }\n } \n } catch (e) {}\n}",
"copyToClipboard(e){\n e.preventDefault();\n var copyTextarea = document.getElementById('post');\n copyTextarea.select();\n try{\n document.execCommand('copy');\n console.log(\"Post copied succesfully.\");\n }\n catch(err){\n console.log(\"Unable to copy the post. Please, do it manually selecting the text and pressing Crtl + C keys.\");\n console.log(err)\n }\n }",
"function copyTextToClipboard() {\n const textarea = document.createElement(\"textarea\");\n textarea.innerHTML = Key;\n textarea.style.display = \"hidden\";\n document.body.appendChild(textarea);\n textarea.focus();\n textarea.select();\n try {\n document.execCommand(\"copy\");\n document.body.removeChild(textarea);\n generatePopUp(\"Key Copied\")\n } catch (err) {\n generatePopUp(`some error happened: ${err}`);\n }\n\n /*other way for copying in clipboard -->\n\n navigator.clipboard\n .writeText(text)\n .then(() => {\n generatePopUp(\"Key Copied\")\n })\n .catch((err) => generatePopUp(`some error happened: ${err}`)); */\n}",
"function copyToClipboard() {\n const el = document.createElement('textarea');\n el.value = event.target.getAttribute('copy-data');\n el.setAttribute('readonly', '');\n el.style.position = 'absolute';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n}",
"function addCopyright(req, res) {\n // work with crMgmt\n //console.log (\"@debug:addCopyright::\"+ JSON.stringify(req.body));\n console.log (\"file path:\"+ req.files.cpfile.name );\n //console.log (\"file path:\"+ req.files.cpfile.name + \":\" + req.files.cpfile.mimetype + \":\" + req.files.cpfile.data );\n console.log (\"@debug:addCopyright headers is::\"+ JSON.stringify(req.headers));\n console.log (\"@debug:addCopyright req is::\"+ JSON.stringify(req.body));\n console.log (\"-----------------------------------------------------\"); \n console.log (\"@debug:addcopyright body is : \" + req.files.cpfile.data );\n\n var response = crMgmt.copyrightMgmt(req);\n //var response = crMgmt.testMethodCall(req);\n //var response = crMgmt.testing(req);\n\n res.send(response);\n}",
"function renderLicenseSection(license) {\nvar licenseLink = renderLicenseLink(license);\nif (license === 'MIT' || 'Apache' || 'GPLv2') {\n return ('Licensed under the ' + licenseLink)\n} else if (license === 'none') {\n return ('')\n}\n}",
"static coreYearCopy() {\n let el = jQuery('[data-toggle=\"year-copy\"]:not(.js-year-copy-enabled)');\n\n if (el.length > 0) {\n let date = new Date();\n let curYear = date.getFullYear();\n let baseYear = (el.html().length > 0) ? el.html() : curYear;\n\n // Add .js-scroll-to-enabled class to tag it as activated and set the correct year\n el.addClass('js-year-copy-enabled').html(\n (parseInt(baseYear) >= curYear) ? curYear : baseYear + '-' + curYear.toString().substr(2, 2)\n );\n }\n }",
"function copy_text_to_clipboard(text, strip_html){\n if (!text){\n alert(\"No text provided to copy_text_to_clipboard to copy.\");\n return false;\n }\n\n if (window.clipboardData) { // Internet Explorer\n try{\n if (strip_html){\n // You should probably use IE's innerText here instead, and set strip_html\n // to 0. (Already done if we're called from copy_element_to_clipboard.)\n // This is a rudimentary method of accessing the text content while\n // keeping line returns from <br> and <p> elements.\n text = text.replace(/\\s*<BR>\\s*/gi, \"\\r\\n\").replace(/\\s*<P>\\s*/gi, \"\\r\\n\\r\\n\").replace(/<\\/\\w+.*?>/ig, '');\n }\n\n window.clipboardData.setData(\"Text\", text);\n return true;\n\n }catch(e){\n alert('Your browser currently does not support copying to the clipboard.');\n return false;\n }\n }else if (navigator.userAgent.match(/ Gecko/) ) {\n if (!strip_html){\n text = text.replace(/</g, '<');\n }\n\n var tempiframe = document.createElement(\"iframe\");\n tempiframe.setAttribute('width', '1');\n tempiframe.setAttribute('height', '1');\n tempiframe.setAttribute('frameborder', '0');\n tempiframe.setAttribute('scrolling', 'no');\n\n var parent = document.body;\n var myiframe = parent.appendChild(tempiframe);\n\n // Mozilla needs time to recognize iframe. We'll do the\n // rest in this function after a short timeout.\n function finish_copy_text_to_clipboard(){\n myiframe.contentDocument.designMode = \"on\"; // Use Midas editor.\n myiframe.contentDocument.body.innerHTML = text;\n\n var sel = myiframe.contentWindow.getSelection();\n sel.removeAllRanges();\n myiframe.contentWindow.focus();\n var range;\n if (typeof sel != \"undefined\") {\n try {\n range = sel.getRangeAt(0);\n } catch(e) {\n range = myiframe.contentDocument.createRange();\n }\n } else {\n range = myiframe.contentDocument.createRange();\n }\n\n range.selectNodeContents(myiframe.contentDocument.body);\n sel.addRange(range);\n\n try{\n myiframe.contentDocument.execCommand('copy', null, null); // copy data to clipboard\n }catch(e){\n if (confirm(\"Cannot access Cut/Copy/Paste for security reasons. Click OK to get instructions from InfoGears to enable cut/copy/paste in your browser. (Note: A new window will popup. It may popup behind this window.)\")){\n window.open(\"http://www.infogears.com/cgi-bin/infogears/mozilla_firefox_copy_paste\");\n }\n parent.removeChild(myiframe); // the temp iframe is no longer needed\n return false;\n }\n\n parent.removeChild(myiframe); // the temp iframe is no longer needed\n\n return true;\n };\n\n setTimeout(finish_copy_text_to_clipboard, 100); // Mozilla needs time to recognize iframe.\n return true; // This might not be true, because the timeout function may screw up!\n\n }else{\n alert(\"Your browser currently does not support copying to the clipboard. Please upgrade to the latest version of Mozilla FireFox or Internet Explorer\");\n }\n\n return false;\n}",
"function copyShortenLink(copyID) {\n var shortenLinkID = \"shortenLink-\" + copyID;\n var copyBtnID = \"copyBtn-\" + copyID;\n\n var text = document.getElementById(shortenLinkID).innerText;\n var elem = document.createElement(\"textarea\");\n document.body.appendChild(elem);\n elem.value = text;\n elem.select();\n elem.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n document.body.removeChild(elem);\n\n resetCopyButton(copyBtnID);\n}",
"function copy()\n{\n var params = arguments;\n var paramsLength = arguments.length;\n var e = params[0];\n var c = params[paramsLength-1];\n if($(e).length < 1)\n {\n var uniqueid = unique_id();\n var textareaId = \"__temp_textarea__\"+uniqueid;\n var element = $(\"<textarea id='\"+textareaId+\"'></textarea>\");\n element.appendTo('body')\n .each(function(){\n $(this).val(e)\n $(this).select()\n })\n }else\n {\n $(e).select();\n }\n\n try {\n var successful = document.execCommand('copy');\n var msg = successful ? 'successful' : 'unsuccessful';\n console.log('Copying text was ' + msg);\n if($(e).length < 1)\n {\n $(this).remove();\n }\n if(typeof c == 'function')\n {\n c()\n }\n } catch (err) {\n console.error('Oops, unable to copy');\n }\n}",
"function copy(list){\n\t//Empty the background page, add a textarea\n\t$('body').html(\"<textarea></textarea>\");\n\t//For each item in the list, add it to the textarea\n\tfor (var i = 0; i < list.length; i++){\n\t\t$('textarea').append(list[i]);\n\t}\n\t//Select the content to be copied\n\t$('textarea').select();\n\ttry{\n\t\t//Try to cut the data\n\t\tvar success = document.execCommand('cut');\n\t\tif (success){\n\t\t\t//Notify successful cut!\n\t\t\tchrome.notifications.create({'type':'basic','iconUrl':'icon-48.png','title':'Requisitions Copied','message':'Your Halo 5 requisition list has been copied to your clipboard.'});\n\t\t}else{\n\t\t\t//Didn't work, throw an error for the failed message\n\t\t\tthrow 404;\n\t\t}\n\t} catch(err) { \n\t\t//Notify that it failed\n\t\tchrome.notifications.create({'type':'basic','iconUrl':'icon-48.png','title':'Error','message':'Unable to copy the requisition list to your clipboard.'}); \n\t} \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select team to add people to | function selectTeam(team) {
selectedTeam = team;
team.classList.add("select");
const opponent = team == teamA ? teamB : teamA;
if (opponent.classList.contains("select")) {
opponent.classList.remove("select");
}
} | [
"function goToTeamSelection(){\n clientValuesFactory.setActiveWindow(windowViews.selectTeam);\n }",
"function toggleTeam()\n{\n var pickedTeam = $('#teamNum').val() + \" \" + $('#event option:selected').text();\n if($('#list').hasClass('btn-success'))\n {\n userData.teamList.push(pickedTeam)\n changeToRemove();\n }\n else\n {\n removeFromTeamList(pickedTeam);\n changeToAdd();\n } \n setUserData();\n}",
"function addEUTeams(teamDropdown) {\n\t$(teamDropdown).append(createTeamOption('Supa Hot Crew',SHCimg));\n\t$(teamDropdown).append(createTeamOption('SK Gaming',SKimg));\n\t$(teamDropdown).append(createTeamOption('Copenhagen Wolves',CWimg));\n\t$(teamDropdown).append(createTeamOption('Alliance',ALLimg));\n\t$(teamDropdown).append(createTeamOption('Gambit Gaming',GMBimg));\n\t$(teamDropdown).append(createTeamOption('Fnatic',FNCimg));\n\t$(teamDropdown).append(createTeamOption('Millenium',MILimg));\n\t$(teamDropdown).append(createTeamOption('Team ROCCAT',ROCimg));\n\t/* ADD OTHER TEAMS HERE */\n}",
"function addNATeams(teamDropdown) {\n\t$(teamDropdown).append(createTeamOption('Team Solo Mid',TSMimg));\n\t$(teamDropdown).append(createTeamOption('Counter Logic Gaming',CLGimg));\n\t$(teamDropdown).append(createTeamOption('Cloud9 HyperX',C9img));\n\t$(teamDropdown).append(createTeamOption('XDG',XDGimg));\n\t$(teamDropdown).append(createTeamOption('Evil Geniuses',EGimg));\n\t$(teamDropdown).append(createTeamOption('Dignitas',DIGimg));\n\t$(teamDropdown).append(createTeamOption('Team Coast',CSTimg));\n\t$(teamDropdown).append(createTeamOption('Curse Gaming',CRSimg));\n\t$(teamDropdown).append(createTeamOption('LMQ',LMQimg));\n\t$(teamDropdown).append(createTeamOption('compLexity Gaming',COLimg));\n\t/* ADD OTHER TEAMS HERE */\n}",
"function addPerson() {\n const name = personName.value.trim();\n if (name && !persons.includes(name)) {\n persons.push(name);\n const person = new Person(name);\n selectedTeam.appendChild(person);\n }\n personName.value = \"\";\n}",
"function selectTeam(data, config) {\n const constraints = config.constraints;\n const t = config.team_type.team;\n let max_players_from_fav_team = constraints.max;\n if (config.team_type.type === 'balanced')\n max_players_from_fav_team = 6;\n \n let players = [];\n let creditLeft = config.max_credit;\n const team1 = t === 1 ? data.team1 : data.team2;\n const team2 = t !== 1 ? data.team1 : data.team2;\n const fav_team_sorted = t === 1 ? _.cloneDeep(data.t1_sorted) : _.cloneDeep(data.t2_sorted);\n const other_team_sorted = t !== 1 ? _.cloneDeep(data.t1_sorted) : _.cloneDeep(data.t2_sorted);\n let fav_team_count = 0;\n let other_team_count = 0;\n\n let counts = {\n wk: 0,\n ar: 0,\n bt: 0,\n bl : 0,\n }\n let totalPlayersToSelect = constraints.wk[0] + constraints.bt[0] + constraints.ar[0] + constraints.bl[0];\n for (let i = 0; i < fav_team_sorted.length; i++) {\n const p = fav_team_sorted[i];\n if (canSelectPlayer(p, counts, constraints, creditLeft)) {\n players.push(p);\n creditLeft -= p.credit;\n counts[p.role]++;\n fav_team_count++;\n totalPlayersToSelect--;\n }\n if (totalPlayersToSelect === 0 || fav_team_count === max_players_from_fav_team)\n break;\n }\n\n // find what are remaining min players and add from other team\n if (totalPlayersToSelect > 0)\n Object.keys(counts).forEach((k) => {\n if (counts[k] < constraints[k][0]) {\n let ot = addPlayer(k, other_team_sorted, constraints[k][0] - counts[k], creditLeft, players);\n creditLeft = ot.rem_credit;\n other_team_count += ot.added_players || 0;\n if (ot.rem_players === 0) // constraints met update counts\n counts[k] = constraints[k][0]\n }\n })\n \n // need to select remaining players from other team with remaining credits left\n totalPlayersToSelect = 11 - players.length; \n const remPlayers = getMaxPointPlayersUnderCredit(other_team_sorted, creditLeft)\n if (remPlayers && remPlayers.players) {\n other_team_count += remPlayers.players.length;\n if (remPlayers.players.length < totalPlayersToSelect) {\n console.error('[getMaxPointPlayersUnderCredit] could not find remaining players within credit limit')\n }\n }\n // console.log('all players')\n const playing11 = [...players, ...remPlayers.players];\n // console.log(playing11)\n const sortedPlaying11 = _.orderBy(playing11, ['points'], ['desc']);\n // console.log('all players - sorted')\n // console.log(sortedPlaying11)\n const cvc_candidates = _.slice(sortedPlaying11, 0, 2);\n // console.log(cvc_candidates)\n return {\n rem_credit: remPlayers.rem_credit,\n players: playing11,\n cvc_candidates: cvc_candidates,\n counts: counts,\n t1: {\n name: team1.name,\n code: team1.code,\n color: team1.color,\n playingCount: fav_team_count\n },\n t2: {\n name: team2.name,\n code: team2.code,\n color: team2.color,\n playingCount: other_team_count\n },\n }\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 OnJoinTeamPressed() {\n // Get the team id asscociated with the team button that was pressed\n var teamId = $.GetContextPanel().GetAttributeInt(\"team_id\", -1);\n\n // Request to join the team of the button that was pressed\n Game.PlayerJoinTeam(teamId);\n}",
"function addPlayer(team) {\n\tvar container = $('#players-team-'+team);\n\n\t//max. 20 players to prevent database flooding\n\tif(container.children().length >= 20) return;\n\n\tvar last_id = 0;\n\n\tvar spl = container.children().last().attr('id').split(\"-\");\n\n\tlast_id = Number(spl[spl.length-1]);\n\tif(!$.isNumeric(last_id)) {\n\t\tlast_id = 0;\n\t}\n\n\tvar id = last_id+1;\n\n\tvar div = $(document.createElement('div')).addClass('player').addClass('overlay-container').addClass('player-'+team).attr('id', 'player-'+team+'-'+id);\n\n\t//TODO: Set default value to next free number\n\tvar number_html = '<input type=\"number\" class=\"player-number border\">'\n\t$(number_html).appendTo(div);\n\n\tvar name_html = '<input type=\"text\" class=\"player-name border\" placeholder=\"Player Name\" maxlength=\"30\">';\n\t$(name_html).appendTo(div);\n\n\tvar remove_html = '<div class=\"overlay-right border\" onclick=\"removePlayer(\\''+team+'\\', '+id+')\"><i class=\"fa fa-times\"></i></div>'\n\t$(remove_html).appendTo(div);\n\n\tdiv.appendTo(container);\n\n\tresize();\n\tapplyRangeChecks();\n}",
"userSelect(){\n if(this.state.team.length < 6) {\n this.state.team.push(this.props.user);\n this.setState({team:this.state.team});\n }\n\n}",
"createTeam (callback) {\n\t\tlet data = {\n\t\t\tname: RandomString.generate(10)\n\t\t};\n\t\tthis.apiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/companies',\n\t\t\t\tdata: data,\n\t\t\t\ttoken: this.userData[0].accessToken\t// first user creates it\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\tthis.team = response.team;\n\t\t\t\tthis.teamStream = response.streams[0];\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}",
"function getTeam(number) {\n\t\t\t\tfor (var i = 0; i < teams.length; i++) {\n\t\t\t\t\tif (teams[i].number === number) {\n\t\t\t\t\t\treturn teams[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar newTeam = new Team(number);\n\t\t\t\tteams.push(newTeam);\n\t\t\t\treturn newTeam;\n\t\t\t}",
"function makeTeams() {\n for (var i = 0; i < data.players.length; i++) {\n if (data.players[i].team_name === team1Name) {\n team1 = team1.concat(data.players[i]);\n } else {\n team2 = team2.concat(data.players[i]);\n }\n }\n}",
"function pushDetailsInTeams(teams,matches){\n for(let i=0;i<teams.length;i++){\n let name=teams[i].name;\n for(let j=0;j<matches.length;j++){\n if(name==matches[j].t1 || name==matches[j].t2){\n if(name==matches[j].t1 ){\n teams[i].matches.push({\n opponenetTeam:matches[j].t2,\n teamScore:matches[j].team1Score,\n opponentScore:matches[j].team2Score,\n result:matches[j].result\n })\n }else{\n teams[i].matches.push({\n opponenetTeam:matches[j].t1,\n teamScore:matches[j].team2Score,\n opponentScore:matches[j].team1Score,\n result:matches[j].result\n })\n }\n }\n }\n }\n}",
"function setTeamAMDS(newTeamA){\r\n if(currentTeamB !== \"\"){\r\n showMDSDataFromTo(currentSeason[0], currentSeason[currentSeason.length - 1])\r\n if(newTeamA === \"Choose team A...\"){\r\n currentTeamA = \"\"\r\n selectionMDS(currentSeason, null, currentTeamB)\r\n }\r\n else{\r\n selectionMDS(currentSeason, newTeamA, currentTeamB) \r\n }\r\n }else{\r\n currentTeamA = newTeamA\r\n selectionMDS(currentSeason, currentTeamA, null)\r\n }\r\n\r\n}",
"function getDatabaseParameterPostTeamCreateTeam (params, query, body){\r\n\treturn body.team;\r\n}",
"function createTeam(evt, teamName) {\n var divId = \"teamDiv_\" + teamCounter + \"_0\";\n var listId = 'team_' + teamCounter + \"_0\";\n if (teamName == undefined) {\n teamName = \"Team \";\n\n //Add leading zero as requested in CodePlex ticket #695\n if (teamCounter < 10) {\n teamName += \"0\" + teamCounter;\n }\n else {\n teamName += teamCounter;\n }\n }\n var newContent = '<div style=\"display:none;\" id=\"' + divId + '\" class=\"TeamDiv\">' +\n '<input type=\"text\" class=\"TeamNameTextBox\" value=\"' + teamName + '\" />' +\n '<img class=\"RemoveTeamIcon\" src=\"/Content/images/delete_up.png\" alt=\"remove team\" title=\"remove team\" onclick=\"removeTeam(\\'' + divId + '\\')\" />' +\n '<ul id=\"' + listId + '\" class=\"TeamSortable\"></ul>' +\n '</div>';\n if (teamCounter % 3 == 0) {\n newContent += '<div style=\"clear:both;\"></div>';\n }\n $(\"#TeamsDiv\").append(newContent);\n $(\"#\" + listId).sortable({ connectWith: \".TeamSortable\" }).disableSelection();\n $(\"#\" + divId).fadeIn('slow');\n teamCounter++;\n return divId;\n}",
"function selectteam(targeturl){\n //get target from link in lets play button\n var target = document.getElementById(\"lets-play-btn\").getAttribute(\"href\");\n\n //if team is not set already add it to target url\n if (target.indexOf(\"&team=\") == -1){\n document.getElementById(\"lets-play-btn\").setAttribute(\"href\", (target + \"&team=\" + targeturl));\n }\n else\n {\n target = target.substring(0, target.indexOf(\"&team=\")); //cut off unnecessary attributes\n document.getElementById(\"lets-play-btn\").setAttribute(\"href\", (target + \"&team=\" + targeturl));\n }\n}",
"buildTeamBoxes(){\n new TeamBox(this, \"team goes here\", 80, 70).create()\n .setInteractive().on('pointerup', ()=>{\n this.scene.sleep('battle')\n this.scene.launch('switch')\n },this);\n new TeamBox(this, \"enemy team goes here\", 530, 70).create();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ends the game if the bird's current health is zero or less | function updateBird() {
if (bird.healthCurrent <= 0) {
gameLose();
}
} | [
"endGame() {\n if (this.health <= 0) {\n backgroundMusic.stop();\n failSound.play();\n state = \"GAMEOVER\";\n return;\n } else if (this.score >= 40) {\n state = \"GAMEWIN\";\n return;\n }\n }",
"function youDied () {\n if (yourInfo.hp <= 0) {\n console.log(\"You just died. Go pitty yourself and then try again.\")\n process.exit(-1) \n }\n}",
"death () {\r\n this.body.velocity.x = 0\r\n this.dying = true\r\n this.events.onOutOfBounds.add(this.kill, this)\r\n this.game.camera.shake(0.005, 100)\r\n }",
"function end() {\n\t// set GAMEOVER to true\n\tGAME_OVER = true;\n\t// call clear methods\n\tUFO.clear();\n\tBULLET.clear();\n\tBOOM.clear();\n\t// fill the score\n\tscore.textContent = GAME_SCORE;\n\t// show score board\n\tgame.classList.remove('active');\n}",
"_checkHealth() {\n if (this._targetPlanet._rover._healthBar._currentHealth <= 0) {\n this.emit(Play.events.GAME_OVER, { name: this._targetPlanet.name });\n }\n }",
"function checkGameEnd()\n{\n // check if player finished the level\n if (player.x > canvas.width && !screen.paused) {\n screen.paused = true;\n saveScoreToDisk();\n\n // check if it's in the final level\n if (currentLevel < levelFiles.length - 1) {\n menu.setState(\"nextlevel\", false);\n screen.state = \"\";\n } else {\n finalSplash.display();\n }\n }\n}",
"done() {\n // Let's find the screen position of the particle\n let pos = scaleToPixels(this.body.GetPosition());\n // Is it off the bottom of the screen?\n if (pos.y > .69*height + this.r * 2) {\n this.killBody();\n return true;\n }\n return false;\n }",
"decrementPlayerHealth() {\n if (!this.decrementHealthOnCollision) return\n\n this.player.health--\n if (this.player.health <= 0) {\n this.triggerGameOver()\n }\n }",
"function endPhaseConditions(){\r\n\r\n if (killerCountSetup == 0 || userKilled || totalFuel == userScore + computerScore || fuel == 0){\r\n return false;\r\n }\r\n else{\r\n return true;\r\n }\r\n}",
"function wallDmg(){\n playerHP -= 1;\n if(playerHP < 0){\n if(!explodeSound.isPlaying()){\n explodeSound.play();\n }\n } else {\n if(!crashSound.isPlaying()){\n crashSound.play();\n }\n }\n}",
"function endPhase(){\r\n \r\n if (killerCountSetup == 0 || (userScore > computerScore && !userKilled)){\r\n\r\n document.getElementById(\"outcome\").innerHTML = \"User wins with score: \" + userScore;\r\n }\r\n else if(userKilled || computerScore > userScore){\r\n\r\n document.getElementById(\"outcome\").innerHTML = \"Computer wins with score: \" + computerScore;\r\n }\r\n else{\r\n\r\n document.getElementById(\"outcome\").innerHTML = \"Draw between user and computer.\";\r\n }\r\n}",
"function survival() {\n ui.setText(\"EnemyCounter\", \"\");\n if (game.enemiesAlive == 0 && !game.waveActive) {\n waveCooldown();\n } else if (game.waveActive) {\n if (game.enemiesAlive < 10) {\n gameWorld.createEnemy();\n }\n }\n}",
"closeBattle(){\n bossNum++;\n// eventNumber++;\n// eventTextNumber = 0;\n this.game.time.events.add(Phaser.Timer.SECOND * this.closWindowDelay, ()=>{\n this.game.camera.fade(0x000000, 1000);\n this.game.time.events.add(Phaser.Timer.SECOND * this.closWindowDelay, ()=>{\n this.clearEverything(); \n this.game.camera.resetFX();\n enemyStats[bossNum].currentHP = enemyStats[bossNum].currentHP;\n\n \n \n }, this);\n \n }, this);\n \n// music.pause();\n// music.destroy();\n// this.selectMusic();\n\n \n }",
"function enemyMoveHeight() {\n if(isHidden==true){return;}\n if(enemy.offsetTop>=700){\n lives--;\n var audioLifeLost= new Audio(\"lifeLost.wav\");\n audioLifeLost.play();\n LivesDiv.innerHTML=\"lives \"+lives;\n enemy.remove();\n //when the play reaches 0 lives the function is called to end the game\n if(lives<=0){\n gameOver();\n }\n }\n //enemy will keep moving until it has reacher 669px\n else if(enemy.offsetTop<=699){\n enemyPosition++;\n enemy.style.top = enemyPosition + 'px';\n }\n }",
"damaged(amount) {\n if (this.shielded) {\n return;\n }\n\n this.showHealthBar = true;\n\n this.health -= amount;\n if (this.health == 0) {\n this.deathSound.play();\n }\n }",
"humanHitOrStay() {\n while (this.human.HitOrStay()) {\n\n console.clear();\n this.showMoney();\n this.dealer.nextCard.call(this);\n this.displayHandsWhileHitting();\n\n if (this.human.isBusted()) {\n console.clear();\n break;\n }\n\n }\n }",
"function endRound () {\n\t/* check to see how many players are still in the game */\n var inGame = 0;\n var lastPlayer = 0;\n for (var i = 0; i < players.length; i++) {\n if (players[i] && !players[i].out) {\n inGame++;\n lastPlayer = i;\n }\n }\n \n /* if there is only one player left, end the game */\n if (inGame == 1) {\n\t\tconsole.log(\"The game has ended!\");\n\t\t$gameBanner.html(\"Game Over! \"+players[lastPlayer].label+\" won Strip Poker Night at the Inventory!\");\n\t\tgameOver = true;\n \n for (var i = 0; i < players.length; i++) {\n if (HUMAN_PLAYER == i) {\n $gamePlayerCardArea.hide();\n } \n else {\n $gameOpponentAreas[i-1].hide();\n }\n }\n \n\t\thandleGameOver();\n\t} else {\n\t\t$mainButton.html(\"Deal\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n\t}\n\t$mainButton.attr('disabled', false);\n actualMainButtonState = false;\n}",
"function isGameOver() {\r\n\tif (lives <= 0) return true;\r\n\treturn false;\r\n}",
"function checkExplode() {\r\n \"use strict\";\r\n\r\n console.log(\"in checkExplode. Explode = \" + bUfoExplode);\r\n\r\n if (bUfoExplode) {\r\n\r\n render();// make sure explosion is appreciated...\r\n console.log(\"in checkExplode. Setting delay for hidding ufo explosion.\");\r\n \r\n // wait so player can see\r\n wait(EXPLODE_TIMEINTERVAL);\r\n\r\n // now hide ufo since it's been blown up!\r\n ufo.img.style.visibility = \"hidden\";\r\n console.log(\"in checkExplode. past time delay now.\");\r\n bGameEnded = true;\r\n render();\r\n }\r\n}// end check explode"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the FlixStack links from the current page. | function remove_links() {
$('.flixstack-wrapper').hide();
$('.flixstack-wrapper').remove();
} | [
"function removeLinks() {\n links.splice(0,links.length);\n draw();\n}",
"function clear_link(mhc){ \n\t\tvar unlinked = 0;\n\t\tvar aNav = $(mhc);\n\t\tvar a = aNav.getElementsByTagName('a');\n\t\tvar mysplit = window.location.href.split('#')[0];\n\t\tfor(var i=1;i<a.length;i++)\n\t\t\tif(a[i].href == mysplit){\n\t\t\t\tremoveNode(a[i]);\n\n \t\t\tvar unlinked = 1;\n\t\t\t\t}\t\t\t\t\n\t\t\tif (unlinked == 0){\n\t\t\t\tvar newHit = a[0];\n\t\t\t\tnewHit.parentNode.setProperty ('id','active_nav'); \n\t\t\t}\n\t}",
"function removeGhPages()\n{\n console.log(\"\\tStart removeGhPages\");\n\n var i;\n var srch = \"gh-pages\";\n var tags = document.getElementsByTagName(\"a\");\n for (i = 0; i < tags.length; i++) \n {\n if(tags[i].href.indexOf(srch) > -1)\n {\n console.log(\"\\t\\thref [\"+ tags[i].href + \"] is gevonden\");\n tags[i].href = tags[i].href.substring(0, tags[i].href.length - srch.length);\n console.log(\"\\t\\thref [\"+ tags[i].href + \"] is aangepast\");\n break;\n }\n } \n\n console.log(\"\\tEinde removeGhPages\");\n}",
"function unmark( links ) {\r\n\t\t$( links ).each( function( pos, link ) {\r\n\t\t\tunmarkLink( link ); \r\n\t\t} );\r\n\t}",
"cleanOldPage(){\n\t\tif(this.activePage !== undefined){\n\t\t\tthis.activePage.deletePage();\n\t\t\tthis.infoPage.deletePage();\n\t\t}\n\t\tif(this.popUpPage){\n\t\t\tthis.popUpPage.deletePage();\n\t\t}\n\t}",
"function filterLinks() {\r\n\tvar links = div.getElementsByTagName('a');\r\n\tfor (i = links.length - 1; i >= 0; i--) {\r\n\t\tif (links[i].href.match(filterExpression)) {\r\n\t\t\tlinks[i].parentNode.removeChild(links[i]);\r\n\t\t}\r\n\t}\r\n}",
"function remove(){\n body.querySelectorAll(\"a\").forEach(\n (aTag) => {\n if (aTag.getAttribute(\"href\").startsWith(shouldNotStartWith)){\n body.removeChild(aTag);\n }\n }\n )\n}",
"removeLink(startPortal, endPortal) {\n var newLinks = [];\n for (let link_ in this.links) {\n if (!(this.links[link_].fromPortalId == startPortal && this.links[link_].toPortalId == endPortal)) {\n newLinks.push(this.links[link_])\n }\n }\n this.links = newLinks;\n this.cleanAnchorList()\n this.cleanPortalList()\n this.update()\n }",
"function clearHomepage() {\n //TODO Change the homepage from empty context to user defined\n data.getPage(space.homepage.id, function (response) {\n let oldPage = JSON.parse(response);\n\n let updatePage = {\n version: {\n number: oldPage.version.number + 1\n },\n type: \"page\",\n title: oldPage.title,\n body: {\n storage: {\n value: \"\",\n representation: \"storage\"\n }\n }\n };\n data.updatePage(space.homepage.id, updatePage)\n })\n }",
"function clearEmployeeListOnLinkClick() {\n document.querySelector(\"a\").addEventListener(\"click\", function(event) {\n document.querySelector(\".employee-list\").innerHTML = \"\";\n });\n}",
"function unmarkLink( link ) {\r\n\t\t$( link ).removeClass( linkCurrentClass ); \r\n\t}",
"function clean_jekyll() {\n return del([\"./_site\"]);\n}",
"function cleanup() {\n\twriteNavCookie();\n\t\n\tif (blnNS) {\n\t\tdocument.releaseEvents(Event.MOUSEMOVE);\n\t}\n\treturn;\n}",
"function cleanupUi() {\n // Remove all previously displayed posts.\n \n recentPostsSection.getElementsByClassName('posts-container')[0].innerHTML = '';\n userPostsSection.getElementsByClassName('posts-container')[0].innerHTML = '';\n\n // Stop all currently listening Firebase listeners.\n listeningFirebaseRefs.forEach(function(ref) {\n ref.off();\n });\n listeningFirebaseRefs = [];\n}",
"function wppbRemovePageFromUrl( link, page ){\r\n link = link.replace( '/'+page+'/', '/' );\r\n link = wppbRemoveURLParameter( link, 'page' );\r\n return link;\r\n}",
"function cleanupLinks(callback) {\n var linkcount = 0, cbcount = 0;\n var links = db.get(\"shortlinks\");\n if (Object.keys(links).length === 0)\n callback();\n else {\n Object.keys(links).forEach(function (link) {\n linkcount++;\n (function (shortlink, location) {\n fs.stat(path.join(paths.files, location), function (error, stats) {\n cbcount++;\n if (!stats || error) {\n delete links[shortlink];\n }\n if (cbcount === linkcount) {\n db.set(\"shortlinks\", links, function () {\n callback();\n });\n }\n });\n })(link, links[link]);\n });\n }\n}",
"function clearBookmarkFolders() {\n while ($bookmarksList.children.length > 0) {\n $bookmarksList.removeChild($bookmarksList.firstChild);\n }\n }",
"function removePagination() {\n $(\"#pagination\").remove();\n}",
"function clearHighlightsOnPage()\n{\n\tunhighlight(document.getElementsByTagName('body')[0]);\n\tcssstr = \"\";\n\tupdateStyleNode(cssstr);\n\tlastText = \"\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME : checkDeviceStatus AUTHOR : Anna Marie Paulo DATE : March 6, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : validation for config and software device status PARAMETERS : | function checkDeviceStatus(flag, type){
var txt1="";
saveresmain = 1;
if(globalInfoType == "JSON"){
devicesArr = getDevicesNodeJSON();
deviceArr = getDevicesNodeJSON();
}
//if(!checkRunningSanity("saveconfig")){return;}
for(var a=0; a<devicesArr.length; a++){
if(devicesArr[a].DeviceType.toLowerCase()== "dut" && devicesArr[a].Status.toLowerCase() == "reserved"){
startRes(flag, type);
}
else{
if(devicesArr[a].DeviceType.toLowerCase() != "dut"){
txt1 = "Device is not DUT.<br/>";
}if(devicesArr[a].Status.toLowerCase() != "reserved"){
txt1 = "Device should be reserved.<br/>";
}
}
}
if(deviceArr==[] || deviceArr==0){
if(globalDeviceType == "Mobile"){
error("No device on canvas.","Notification");
}else{
alert("No device on canvas.");
}
}
if(txt1 != "" && (deviceArr!=[] || deviceArr!=0)){
if(globalDeviceType == "Mobile"){
error(txt1,"Notification");
}else{
alert(txt1);
}
}
} | [
"function updateStatus(devices, new_status)\n{\n\tfor (var i in new_status )\t\t\t//for each status\n\t{\n\t\tfor(var j in devices)\t\t\t//look for the match ID\n\t\t{\n\t\t\tif( devices[j].deviceID == new_status[i].deviceID )\n\t\t\t{\n\t\t\t\tvar status = devices[j].status;\t\t//access the status array\t\t\t\n\t\t\t\t//running status\n\t\t\t\tstatus.running = typeof(new_status[i].running) ? new_status[i].running : status.running;\n\t\t\t\t//auto on mode settings\n\t\t\t\tif( typeof(new_status[i].autoOn) != 'undefined' )\n\t\t\t\t{\n\t\t\t\t\tstatus.autoOn.enable = typeof(new_status[i].autoOn.enable) ? new_status[i].autoOn.enable : status.autoOn.enable;\n\t\t\t\t\tstatus.autoOn.time = typeof(new_status[i].autoOn.time) ? new_status[i].autoOn.time : status.autoOn.time;\n\t\t\t\t}\n\t\t\t\t//auto off mode settings\n\t\t\t\tif( typeof(new_status[i].autoOff) != 'undefined' )\n\t\t\t\t{\n\t\t\t\t\tstatus.autoOff.enable = typeof(new_status[i].autoOff.enable) ? new_status[i].autoOff.enable : status.autoOff.enable;\n\t\t\t\t\tstatus.autoOff.time = typeof(new_status[i].autoOff.time) ? new_status[i].autoOff.time : status.autoOff.time;\n\t\t\t\t}\n\t\t\t\t//parameter of the device\n\t\t\t\tif(typeof(new_status[i].parameter)!='undefined')\n\t\t\t\t{\n\t\t\t\t\tvar para = new Array();\n\t\t\t\t\tpara = para.concat(new_status[i].parameter);\n\t\t\t\t\t//console.log(para.length);\n\t\t\t\t\tfor( var k=0; k < para.length; k++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tpara[k] = (para[k] != null) ? para[k] : status.parameter[k] ;\n\t\t\t\t\t}\n\t\t\t\t\tstatus.parameter = para;\n\t\t\t\t\t//console.log(status.parameter);\n\t\t\t\t}\n\t\t\t\tbreak;\t\t//get out of the inner loop\n\t\t\t}\n\t\t}\n\t}\n}",
"function checkCommitOptions(){\n\tvar allline = [];\n\tvar devices = getDevicesNodeJSON();\n\n\tfor(var t=0; t<devices.length ; t++){\n\t\tallline = gettargetmap(devices[t].ObjectPath,allline);\n\t}\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n\t\tvar prtArr =[];\n\t\tfor(var s=0;s < devices.length; s++){\n \t \tprtArr = getDeviceChildPort(devices[s],prtArr);\n\t\t}\n }else{\n var devices =devicesArr;\n\t\tvar prtArr= portArr;\n }\n\t\n\tfor(var a=0; a < devices.length;a++){\n\t\tif(devices[a].DeviceType.toLowerCase() == \"testtool\" || devices[a].DeviceType.toLowerCase() == \"dut\" && devices[a].Status.toLowerCase() != \"reserved\"){ \n\t\t\t$(\"#comOpDevSanityTr\").removeAttr(\"style\");\n\t\t\t$(\"#comOpAccSanityTr\").removeAttr(\"style\");\n\t\t\t$(\"#comOpStartResTr\").removeAttr(\"style\");\n\t\t\t$(\"#comOpEndResTr\").removeAttr(\"style\");\n\t\t}else{\n\t\t\t$(\"#comOpDevSanityTr\").css({\"display\":\"none\"});\n\t\t\t$(\"#comOpAccSanityTr\").css({\"display\":\"none\"});\n\t\t\t$(\"#comOpStartResTr\").css({\"display\":\"none\"});\n\t\t\t$(\"#comOpEndResTr\").css({\"display\":\"none\"});\n\n\t\t}\n\t\tif(devices[a].Status.toLowerCase() != \"reserved\" && allline.length > 0){\n\t\t\tif(devices[a].DeviceName == \"\"){\n\t\t\t\t$(\"#comOpConnectivityTr\").removeAttr(\"style\");\n\t\t\t}else{\n\t\t\t\t$(\"#comOpConnectivityTr\").css({\"display\":\"none\"});\n\t\t\t\t$(\"#comOpConnectivity\").prop('checked',false);\n\t\t\t\tfor(var b=0; b < prtArr.length; b++){\n\t\t\t\t\tif(prtArr[b].SwitchInfo != \"\"){\n\t\t\t\t\t\t$(\"#comOpConnectivityTr\").removeAttr(\"style\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(devices[a].Status.toLowerCase() != \"reserved\" && allline.length > 0 && devices[a].Model != \"3750\"){ \n\t\t\tvar dut= 0;var testool= 0;var others= 0;var all= 0;\n\t\t\tfor(var c=0; c < devices.length;c++){\n\t\t\t\tall++;\n\t\t\t\tif(devices[c].DeviceType.toLowerCase() == \"dut\"){\n\t\t\t\t\tdut++;\n\t\t\t\t}else if(devices[c].DeviceType.toLowerCase() == \"testtool\"){\n\t\t\t\t\ttestool++;\n\t\t\t\t}else{\n\t\t\t\t\tothers++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif((dut + testool) == all){\n\t\t\t\t$(\"#comOpLinkSanityTr\").removeAttr(\"style\");\n\t\t\t}else{\n\t\t\t\t$(\"#comOpLinkSanityTr\").css({\"display\":\"none\"});\n\t\t\t}\n\t\t}\n\t\tif(devices[a].Status.toLowerCase() != \"reserved\" && allline.length > 0 && devices[a].Model != \"3750\"){\n\t\t\tvar dut= 0;var testool= 0;var others= 0;var all= 0;var vlanVar =0;var vlansArr=\"\";\n for(var c=0; c < devices.length;c++){\n all++;\n if(devices[c].DeviceType.toLowerCase() == \"dut\"){\n dut++;\n\t\t\t\t}else if(devices[c].DeviceType.toLowerCase() == \"vlan\"){\n\t\t\t\t\tvlansArr = devices[c].ObjectPath;\n\t\t\t\t\tvlanVar++;\n\t\t\t\t}else{\n\t\t\t\t\tothers++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(dut == all || dut >1){\n\t\t\t\tif(vlanVar == 0){\n\t\t\t\t\t$(\"#comOpEnaInterfaceTr\").removeAttr(\"style\");\n\t\t\t\t}else{\n\t\t\t\t\tvar vlanCtr=0;\n\t\t\t\t\tfor(var d=0; d < allline.length; d++){\n\t\t\t\t\t\tvar source = allline[d].Source;\n\t\t\t\t var destination = allline[d].Destination;\n\t\t\t\t var srcArr = source.split(\".\");\n\t\t\t\t\t\tvar srcObj = getDeviceObject2(srcArr[0]);\n\t\t\t\t var dstArr = destination.split(\".\");\n\t\t\t\t\t\tvar dstObj = getDeviceObject2(dstArr[0]);\n\t\t\t\t\t\tif(allline[d].Destination.split(\".\")[0] == vlansArr){\n\t\t\t\t\t\t\tif(srcObj.DeviceType.toLowerCase() == \"dut\"){\n\t\t\t\t\t\t\t\tvlanCtr++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}else if(allline[d].Source.split(\".\")[0] == vlansArr){\n\t\t\t\t\t\t\tif(dstObj.DeviceType.toLowerCase() == \"dut\"){\n\t\t\t\t\t\t\t\tvlanCtr++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(vlanCtr > 1){\n\t\t\t\t\t\t$(\"#comOpEnaInterfaceTr\").removeAttr(\"style\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\t$(\"#comOpEnaInterfaceTr\").css({\"display\":\"none\"});\n\t\t\t}\n\t\t}\n\t}\t\n}",
"function checkDeviceInDbAutoD(){\n\tvar infoType = globalInfoType;\n\tif(globalDeviceType == \"Mobile\"){\n loading('show');\n }\n\n\tif(infoType==\"XML\"){\n\t\tvar urlx = getURL(\"RM\");\n\t\tvar queryS = \"managementip=\"+autoDDevData[0].ManagementIp+\"^\"+\n\t\t\t\"consoleip=\"+autoDDevData[0].ConsoleIp+\"^\"+\n\t\t\t\"hostname=\"+autoDDevData[0].HostName;\n\t}else{\n\t\tvar urlx = getURL(\"ConfigEditor2\",\"JSON\");\n\t\tvar queryS = \"{ 'QUERY' : [{ 'managementip' : '\"+autoDDevData[0].ManagementIp\n\t\t\t+\"', 'consoleip' : '\"+conip+\"', 'hostname' : '\"\n\t\t\t+autoDDevData[0].HostName+\"', 'user': '\"+globalUserName+\"' }] }\";\n\t}\n\n\tvar conip = autoDDevData[0].ConsoleIp+\":\"+autoDDevData[0].ConsolePort;\n\tif(conip==\":\"){conip = \"\";}\n\t\n\t$.ajax({\n\t\turl: urlx,\n\t\tdata : {\n\t\t\t\"action\": \"checkdeviceindb\",\n\t\t\t\"query\": queryS,\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tif(globalDeviceType == \"Mobile\"){\n \t\tloading('hide');\n\t\t }\n\t\t\tif(!data){\n/*\t\t\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t\t\tdoSaveAutoDevice();\n\t\t\t\t}else{\n\t\t\t\t\tdoSaveAutoDeviceMain();\n\t\t\t\t}\t\t\t\n*/\t\t\t\terror(\"Process Failed!\",\"Notification\"); return;\n\t\t\t}\n\t\t\tif(globalInfoType!=\"XML\"){\n\t\t\t\tdata = $.trim(data);\n\t\t\t\tvar dat = data.replace(/'/g,'\"');\n\t\t var dat2 = $.parseJSON(dat);\n\t\t\t\tvar RESULT = dat2.RESULT;\n\t\t\t\tvar Result = RESULT[0].Result\n\n\t\t\t\tif(Result==\"1\"){\n\t\t\t\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t\t\t\tdoSaveAutoDevice();\n\t\t\t\t\t}else{\n\t\t\t\t\t\tdoSaveAutoDeviceMain();\n\t\t\t\t\t}\n\t\t\t\t}else if(Result.match(/already exists in the database/g)){\n\t\t\t\t\t//prompt if update or overwrite\n\t\t\t\t\tconfirmAutoDExec(Result);\n\t\t\t\t}else{\n\t\t\t\t\terror(Result,\"Notification\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tif(data==\"\") {\n\t\t\t\t/*}else if(data.match(/already exists in the database/g)){\n\t\t\t\t\t//prompt if update or overwrite\n\t\t\t\t\tif(flag==\"update\"){\n\t\t\t\t\t\tautoDDevData[0].SaveOption = 'Update';\n\t\t\t\t\t}else if(flag==\"overwrite\"){\n\t\t\t\t\t\tautoDDevData[0].SaveOption = 'Overwrite';\n\t\t\t\t\t}else{return false;}*/\n\t\t\t\t\treturn true;\n\t\t\t\t}else{\n\t\t\t\t\terror(data,\"Notification\")\n\t\t\t\t\treturn false;\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t});\n}",
"function getHardwareConfigDetails() {\n \n let CONTROL_STATUS = {\n 0 : \"ACTIVE STATUS\",\n 1 : \"REAL TIME UPDATE STATUS\",\n 2 : \"FUNCTION HANDLING STATUS\",\n 3 : \"DEVICE FREEZ\",\n 4 : \"DEVICE RISK\",\n 5 : \"ONE TIME OPERATION\",\n 6 : \"DEVICE RESTART\",\n 7 : \"FIREBASE UPDATE\",\n 8 : \"UPDATE DOUT STATUS ON DB\",\n 9 : \"UPDATE DOUTPIN\",\n 10 : \"UPDATE STATUS\",\n 11 : \"DEEP SLEEP STATUS\"\n }\n\n return CONTROL_STATUS\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 }",
"function mainDevMenuValid(sub) {\n\tif(globalInfoType == \"JSON\"){\n devicesArr = getDevicesNodeJSON();\n\t}\n\tif(sub==\"software\"){\n\t\tif(devicesArr ==[] || devicesArr.length == 0){\n\t\t\talertUser(\"No device on canvas\");\n\t\t\treturn;\n\t\t}else{\n\t\t\tfor(var a=0; a<devicesArr.length; a++){\n\t\t\t\tif(devicesArr[a].Status.toLowerCase()==\"reserved\"){\n\t\t\t\t\t$('#toolsSubmenu').hide(1000);\n\t\t\t $('#softwareSubmenu').show();\n\t\t \t $('#menuList').hide();\n\t\t\t\t}else{\n\t\t\t\t\t$('#softwareSubmenu').hide();\n\t\t\t\t\talertUser(\"Device/s should be committed.\");return;\n\t\t\t\t}\n\t\t\t}\n\t\t}return;\n\t}else if(sub==\"configuration\"){\n\t\tif(devicesArr ==[] || devicesArr.length == 0){\n\t\t\talertUser(\"No device on canvas\");\n\t\t\treturn;\n\t\t}else{\n\t\t\tfor(var a=0; a<devicesArr.length; a++){\n\t\t\t\tif(devicesArr[a].Status.toLowerCase()==\"reserved\"){\n\t\t\t\t\t$('#toolsSubmenu').hide();\n\t\t\t\t $('#configurationSubmenu').show();\n\t\t\t\t $('#menuList').hide();\n\t\t\t\t}else{\n\t\t\t\t\t$('#configurationSubmenu').hide();\n\t\t\t\t\talertUser(\"Device/s should be committed.\");return;\n\t\t\t\t}\n\t\t\t}\n\t\t}return;\n\t}else if(sub==\"showActivity\"){\n\t\tif(devicesArr ==[] || devicesArr.length == 0){\n\t\t\talertUser(\"No device on canvas\");\n\t\t\treturn;\n\t\t}else if(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].DeviceSanity.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].AccessSanity.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].Connectivity.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].EnableInterface.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadImageEnable.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadConfigEnable.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].SaveImageEnable.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].SaveConfigEnable.toString() == \"false\"){\n\t\t\talertUser(\"No activity to show\");return;\n\t\t}else{\n\t\t\tfor(var a=0; a<devicesArr.length; a++){\n\t\t\t\tif(devicesArr[a].Status.toLowerCase()==\"reserved\"){\n\t\t\t $('#toolsSubmenu').hide();\n\t\t\t\t $('#showActivitySubmenu').show();\n\t\t\t\t $('#menuList').hide();\n\t\t\t\t}else{\n\t\t\t\t\t$('#showActivitySubmenu').hide();\n\t\t\t\t\talertUser(\"Device/s should be committed.\");return;\n\t\t\t\t}\n\t\t\t}\n\t\t}return;\n\t}else if(sub==\"linksanity\"){\n\t\tif(devicesArr ==[] || devicesArr.length == 0){\n\t\t\talertUser(\"No device on canvas\");\n\t\t\treturn;\n\t\t}else{\n\t\t\tfor(var a=0; a<devicesArr.length; a++){\n\t\t\t\tif(devicesArr[a].Status.toLowerCase()==\"reserved\"){\n\t\t\t\t\t$('#toolsSubmenu').hide();\n\t\t\t $('#linkSanitySubmenu').show();\n\t\t\t $('#menuList').hide();\n\t\t\t\t}else{\n\t\t\t\t\t$('#linkSanitySubmenu').hide();\n\t\t\t\t\talertUser(\"Device/s should be committed.\");return;\n\t\t\t\t}\n\t\t\t}\n\t\t}return;\n\t}else if(sub==\"softwaredevmenu\"){\n\t\tfor(var a=0; a<devicesArr.length; a++){\n\t\t\tif(devicesArr[a].HostName == HostName){\n\t\t\t\tif(devicesArr[a].Status.toLowerCase()==\"reserved\"){\n\t\t\t\t\t$(\"#deviceToolsMenuMain\").hide(500);\n\t\t\t\t $('#softwareDevMenu').show(500);\n\t\t\t\t}else{\n\t\t\t\t\t$('#softwareDevMenu').hide();\n\t\t\t\t\talertUser(\"Device/s should be committed.\");return;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}else if(sub==\"configdevmenu\"){\n\t\tfor(var a=0; a<devicesArr.length; a++){\n\t\t\tif(devicesArr[a].HostName == HostName){\n\t\t\t\tif(devicesArr[a].Status.toLowerCase()==\"reserved\"){\n\t\t\t\t\t$(\"#deviceToolsMenuMain\").hide(500);\n\t\t\t\t $('#configurationDevMenu').show(500);\n\t\t\t\t}else{\n\t\t\t\t\t$('#configurationDevMenu').hide();\n\t\t\t\t\talertUser(\"Device/s should be committed.\");return;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\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 validationinCreatingLink(device,device2){\n\tvar message = \"\";\n\tif(connectedSwitch == true){\n\t\tmessage = device.DeviceName + \" and \" + device2.DeviceName + \" have no port connected on same switch.\";\t\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\terror(message,\"Notification\");\n\t\t}else{\n\t\t\talerts(message);\n\t\t}\n\t}else if(portspeedflag == false && portspeedflag2 == false){\n\t\tmessage = device.DeviceName + \" and \" + device2.DeviceName + \" have no available port with speed of \" + lineSpeed;\t\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\terror(message,\"Notification\");\n\t\t}else{\n\t\t\talerts(message);\n\t\t}\n\t}else if(portspeedflag == false){\n\t\tmessage = device.DeviceName + \" has no available speed of \" + lineSpeed;\t\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\terror(message,\"Notification\");\n\t\t}else{\n\t\t\talerts(message);\n\t\t}\n\t}else if(portspeedflag2 == false){\n\t\tmessage = device2.DeviceName + \" has no available speed of \" + lineSpeed;\t\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\terror(message,\"Notification\");\n\t\t}else{\n\t\t\talerts(message);\n\t\t}\n\t}else if(portflag == false && portflag2){\n\t\tmessage = device.DeviceName + \" and \" + device2.DeviceName + \" have no available ports.\";\t\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\terror(message,\"Notification\");\n\t\t}else{\n\t\t\talerts(message);\n\t\t}\n\t}else if(portflag == false){\n\t\tmessage = device.DeviceName + \" has no available ports.\";\t\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\terror(message,\"Notification\");\n\t\t}else{\n\t\t\talerts(message);\n\t\t}\n\t}else if(portflag2){\n\t\tmessage = device2.DeviceName + \" has no available ports.\";\t\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\terror(message,\"Notification\");\n\t\t}else{\n\t\t\talerts(message);\n\t\t}\n\t}\n}",
"function devSanityData(data){\n\tvar mydata = data;\n\tif(globalInfoType == \"XML\"){\n\t\tvar parser = new DOMParser();\n\t\tvar xmlDoc = parser.parseFromString( mydata , \"text/xml\" );\n\t\tvar row = xmlDoc.getElementsByTagName('MAINCONFIG');\n\t\tvar uptable = xmlDoc.getElementsByTagName('DEVICE');\n\t\tvar lowtable = xmlDoc.getElementsByTagName('STATUS');\n\t}else{\n\t\tdata = data.replace(/'/g,'\"');\n\t\tvar json = jQuery.parseJSON(data);\t\n\t\tif(!json.RESULT){\n\t\t\tvar uptable = json.MAINCONFIG[0].DEVICE;\n\t\t\tvar lowtable = json.MAINCONFIG[0].STATUS;\n\t\t}\n\t}\n\tvar devStat='';\n\tvar devSanityStat='';\n\tif(!json.RESULT){\n\t\tclearTimeout(TimeOut);\n\t\tTimeOut = setTimeout(function(){\n\t\t\tdevSanXML(uptable,lowtable);\n\t\t},5000);\n\t\treturn;\n\t}\n\tdevSanInit();\n\tTimeOut = setTimeout(function(){\n\t\tsanityQuery('deviceSanity');\n\t},5000);\n}",
"function validationTTList(){\n\tvar msgStr = '';\n\tvar ctr = 0;\n\tfor(var x = 0; x < testToolObj.length; x++){\n\t\tif(testToolObj[x].Ports.length == 0){\n\t\t\tctr++;\n\t\t\tif(ctr == 1){\n\t\t\t\tmsgStr = testToolObj[x].DeviceName;\n\t\t\t}else if(ctr == 2 && x == testToolObj.length){\n\t\t\t\tmsgStr += 'and' + testToolObj[x].DeviceName;\n\t\t\t}else if(ctr > 2){\n\t\t\t\tif(x == testToolObj.length){\n\t\t\t\t\tmsgStr += 'and' + testToolObj[x].DeviceName;\n\t\t\t\t}else{\n\t\t\t\t\tmsgStr += ',' + testToolObj[x].DeviceName;\n\t\t\t\t}\n\t\t\t}\n\t\t}\t\n\t}\n\tif(msgStr != ''){\n\t\tvar msg = msgStr + \" has no selected port(s). Do you want to select port(s)?\";\n\t\t$('#msgAlert').empty().append(msg);\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t$.mobile.changePage(\"#warning\", {\n\t\t\t\ttransition: \"flow\",\n\t\t\t\treverse: false,\n\t\t\t\tchangeHash: true\n\t\t\t});\n\t\t}\n\t}else{\t\n\t\t$(\"#testToolPaletteSubTrList\").hide();\n\t\tcreateTestToolObj();\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t$.mobile.changePage(\"#configEditorPage\", {\n\t\t\t\ttransition: \"flow\",\n\t\t\t\treverse: false,\n\t\t\t\tchangeHash: true\n\t\t\t});\n\t\t}\n\t}\n\n}",
"function enableIntInit(){\n\tvar enableStat='';\n\tvar enableSanityStat='';\n\tif(globalInfoType == \"JSON\"){\n \t var devices = getDevicesNodeJSON();\n }else{\n\t var devices =devicesArr;\n }\n\tfor(var i = 0; i < devices.length; i++){\n\t\tenableStat+=\"<tr>\";\n\t\tenableStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].Manufacturer+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].Model+\"</td>\";\n\t\tenableStat+=\"<td>Init</td>\";\n\t\tenableStat+=\"<td>Init</td>\";\n\t\tenableStat+=\"<td>Init</td>\";\n\t\tenableStat+=\"</tr>\";\n\t}\n//2nd Table of Device Sanity\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n var allline =[];\n for(var i = 0; i < devices.length; i++){ // checks if the hitted object is equal to the array\n allline = gettargetmap(devices[i].ObjectPath,allline);\n }\n for(var t=0; t<allline.length; t++){\n\t\tenableSanityStat+=\"<tr>\";\n var source = allline[t].Source;\n var destination = allline[t].Destination;\n var srcArr = source.split(\".\");\n var srcObj = getDeviceObject2(srcArr[0]);\n var dstArr = destination.split(\".\");\n var dstObj = getDeviceObject2(dstArr[0]);\n var portobject = getPortObject2(source);\n var portobject2 = getPortObject2(destination);\n if(portobject.SwitchInfo != \"\" && portobject2.SwitchInfo != \"\"){\t\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td>\"+srcObj.DeviceName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+portobject.PortName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td>\"+dstObj.DeviceName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+portobject2.PortName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\t\t\n\t\t}\n\t\tenableSanityStat+=\"</tr>\";\n\t}\n\t$(\"#enaSanityTableStat > tbody\").empty().append(enableSanityStat);\n\t$(\"#enaSanityTable > tbody\").empty().append(enableStat);\t\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#enableTotalNo').empty().append(devices.length);\n\tif(globalDeviceType==\"Mobile\"){\n\t\t$(\"#enaSanityTableStat\").table(\"refresh\");\n\t\t$(\"#enaSanityTable\").table(\"refresh\");\n\t}\n}",
"function checkdataForConsole(device,devicesArr,data){\n\tdata = data.replace(/'/g,'\"');\n\tvar json = jQuery.parseJSON(data);\n\tvar mainconfig = json.MAINCONFIG[0];\n\tif(mainconfig.PASS != null && mainconfig.PASS != undefined && mainconfig.FAILED != null && mainconfig.FAILED != undefined){\n\t\tvar messageArray = new Array();\n\t\tvar devArray = [];\n\t\tvar devIdArray = [];\n\t\tfor(var f=0; f<mainconfig.FAILED.length; f++){\n\t\t\tvar devId = mainconfig.FAILED[f].DeviceId;\n\t\t\tvar message = mainconfig.FAILED[f].Message;\n\t\t\tvar flag = false;\n\t\t\tfor(var t=0; t<device.length; t++){\n\t\t\t\tif(devId == device[t].DeviceId){\n\t\t\t\t\tdevice.splice(t,1);\n\t\t\t\t\tflag = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!flag){\n\t\t\t\tif ($.inArray(devId,devIdArray) == -1) {\n\t\t\t\t\tdevIdArray.push(devId);\n\t\t\t\t}\t\t\t\t\t\n\t\t\t}\n\t\t\tif ($.inArray(message,messageArray) == -1) {\n\t\t\t\tmessageArray.push(message);\n\t\t\t}\t\t\t\t\t\n\t\t\t\t\n\t\t}\n\t\tfor(var f=0; f<mainconfig.PASS.length; f++){\n\t\t\tvar sessionid = mainconfig.PASS[f].SessionId;\n\t\t\tvar devId = mainconfig.PASS[f].DeviceId;\n\t\t\tfor(var t=0; t<device.length; t++){\n\t\t\t\tif(devId == device[t].DeviceId){\n\t\t\t\t\tdevice[t].SessionId = sessionid;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(messageArray.length){\n\t\t\tvar msg = messageArray.join(\"\") + \".Do you still want to continue?\";\n\t\t\talerts(msg,\"showConsolePopUp(device,devicesArr)\",\"console\");\n\t\t\treturn;\n\t\t}\n\t}else if(mainconfig.PASS != null && mainconfig.PASS != undefined){\n\t\tfor(var f=0; f<mainconfig.PASS.length; f++){\n\t\t\tvar sessionid = mainconfig.PASS[f].SessionId;\n\t\t\tvar devId = mainconfig.PASS[f].DeviceId;\n\t\t\tfor(var t=0; t<device.length; t++){\n\t\t\t\tif(devId == device[t].DeviceId){\n\t\t\t\t\tdevice[t].SessionId = sessionid;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tshowConsolePopUp(device,devicesArr);\n\t}else if(mainconfig.FAILED != null && mainconfig.FAILED != undefined){\n\t\tvar messageArray = new Array();\n\t\tvar devArray = [];\n\t\tvar devIdArray = [];\n\t\tfor(var f=0; f<mainconfig.FAILED.length; f++){\n\t\t\tvar devId = mainconfig.FAILED[f].DeviceId;\n\t\t\tvar message = mainconfig.FAILED[f].Message;\n\t\t\tif ($.inArray(message,messageArray) == -1) {\n\t\t\t\tmessageArray.push(message);\n\t\t\t}\t\t\t\t\t\n\t\t\t\t\n\t\t}\n\t\tif(messageArray.length){\n\t\t\tvar msg = messageArray.join(\"\");\n\t\t\talerts(msg);\n\t\t\treturn;\n\t\t}\n\t}\n}",
"function checkPortOfDeviceList(devPath,action){\n\tif(lineName != \"\" && lineName != null && lineName != undefined && (lineName.toLowerCase() == \"ethernet\" || lineType == \"Any\")){\n\t\tgetPort(devPath,action,\"1000\",\"L1\");\n\t\tif(!portflag && action == \"source\"){\n\t\t\tgetPort(devPath,action,\"10-100\",\"L1\");\n\t\t\tif(!portflag && action == \"source\"){\n\t\t\t\tgetPort(devPath,action,\"10000\",\"L1\");\n\t\t\t\tif(!portflag && action == \"source\"){\n\t\t\t\t\tgetPort(devPath,action,\"40000\",\"L1\");\n\t\t\t\t\tif(!portflag && action == \"source\"){\n\t\t\t\t\t\tgetPort(devPath,action,\"100000\",\"L1\");\n\t\t\t\t\t\tif(!portflag){\n\t\t\t\t\t\tgetPort(devPath,action,\"100000\",\"L2\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(!portflag2 && action == \"destination\"){\n\t\t\tgetPort(devPath,action,\"10-100\",\"L1\");\n\t\t\tif(!portflag2 && action == \"destination\"){\n\t\t\t\tgetPort(devPath,action,\"10000\",\"L1\");\n\t\t\t\tif(!portflag2 && action == \"destination\"){\n\t\t\t\t\tgetPort(devPath,action,\"40000\",\"L1\");\n\t\t\t\t\tif(!portflag2 && action == \"destination\"){\n\t\t\t\t\t\tgetPort(devPath,action,\"100000\",\"L1\");\n\t\t\t\t\t\tif(!portflag2){\n\t\t\t\t\t\t\tgetPort(devPath,action,\"100000\",\"L2\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}else{\n\t\tgetPort(devPath,action,lineSpeed,lineType);\n\t}\n}",
"function enableSanityData(data){\n\tvar enableStat='';\n\tvar enableSanityStat='';\t\n\tvar mydata = data;\n\tif(globalInfoType == \"XML\"){\n\t\tvar parser = new DOMParser();\n\t\tvar xmlDoc = parser.parseFromString( mydata , \"text/xml\" );\n\t\tvar row = xmlDoc.getElementsByTagName('MAINCONFIG');\n\t\tvar uptable = xmlDoc.getElementsByTagName('DEVICE');\n\t\tvar lowtable = xmlDoc.getElementsByTagName('STATUS');\t \n\t}else{\n\t\tdata = data.replace(/'/g,'\"');\n var json = jQuery.parseJSON(data);\n\t\tif(json.MAINCONFIG){\n var uptable = json.MAINCONFIG[0].DEVICE;\n var lowtable = json.MAINCONFIG[0].STATUS;\n }\n\t}\n\tif(json.MAINCONFIG){\n\t\tclearTimeout(TimeOut);\n\t\tTimeOut = setTimeout(function(){\n\t\t\tenableSanXML(uptable,lowtable);\n\t\t},5000);\n\t\treturn;\n\t}\n\tenableIntInit();\n\tTimeOut = setTimeout(function(){\n\t\tsanityQuery('enableint');\n\t},5000);\n}",
"function checkPortTypeMatch(selIndex,leftDevType, leftObjPath){\n\tvar conReturn = false;\n\tvar\tpRightObjPath = $('#deviceRight li').eq(selIndex).attr('data-name');\n\tvar devRightType = $('#deviceRight li').eq(selIndex).attr('portType');\n\tif (leftDevType.toLowerCase() == \"l2\"){\n\t\tconReturn = true;\n\t}\n\tif (leftDevType.toLowerCase() == \"l1\" && devRightType.toLowerCase() == \"l1\"){\n\t\tconReturn = checkPortSpeedIfMatch(leftObjPath,pRightObjPath)\t\n\t}\t\n\tif ((leftDevType.toLowerCase() == \"open\" && devRightType.toLowerCase() == \"l1\") ||(leftDevType.toLowerCase() == \"l1\" && devRightType.toLowerCase() == \"open\")) {\n\t\tconfirmation(\"Are you sure you want to connect \"+leftDevType+\" port to \"+devRightType+\"?\",Notification,\"conReturn = true;\");\n\t}\t\n\treturn conReturn;\n}",
"function checkPortSpeedIfMatch(leftObjPath,rightObjPath){\n\tvar d = rightObjPath.split(\".\");\n\tvar rightDevicePath = d[0];\n\tvar leftSpeed = \"\";\n\tvar rightSpeed =\"\";\n\tvar rightDeviceName = \"\";\n\tvar condition = true;\n\tif(globalInfoType == \"JSON\"){\n\t\tvar pathArr = leftObjPath.split(\".\");\n\t\tvar pathArr2 = rightObjPath.split(\".\");\n\t\tvar json1 = getAllPortOfDevice(pathArr[0]);\n var json2 = getAllPortOfDevice(pathArr2[0]);\n var prtArr = json1.concat(json2);\n }else{\n var prtArr= portArr;\n }\n\tfor(var a=0; a<prtArr.length; a++){\n\t\tif (prtArr[a].ObjectPath == leftObjPath){\n\t\t\tleftSpeed = prtArr[a].Speed;\n\t\t}else if (prtArr[a].ObjectPath\t== rightObjPath){\n\t\t\trightSpeed = prtArr[a].Speed;\n\t\t}\n\t}\t\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor (var q=0; q<devices.length; q++){\n\t\tif (devices[q].ObjectPath == rightObjPath){\n\t\t\trightDeviceName = devices[q].DeviceName;\n\t\t}\n\t}\n\tif (leftSpeed != rightSpeed){\n\t\talert(\"Device \"+rightDeviceName+\" have no speed of \"+leftSpeed);\n\t\tcondition = false;\n\t}\n\treturn condition;\n}",
"function checkLineIfCommited(id){\n\tvar dv = id.split(\"||\");\n\tvar dev1 = dv[0].split(\".\");\n\tvar dev2 = dv[1].split(\".\");\n\tvar device1 = dev1[0];\n\tvar device2 = dev2[0];\n\tvar dev1Condition = false;\n\tvar dev2Condition = false;\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].ObjectPath== device1 && devices[a].Status.toLowerCase() == \"reserved\"){\n\t\t\tdev1Condition = true;\n\t\t}\n\t\tif (devices[a].ObjectPath== device2 && devices[a].Status.toLowerCase() == \"reserved\"){\n\t\t\tdev2Condition = true;\n\t\t}\n\t}\n\tif (dev1Condition == true && dev2Condition == true){\n\t\treturn true;\n\t}else{\n\t\treturn false;\n\t}\n}",
"function checkSetupSuccess() {\n // Conditionals.\n var hasUndefined = false;\n var hasFalse = false;\n // Iterate through global successFactors JSON object.\n for (var key in global.successFactors) {\n if (global.successFactors[key] === undefined) {\n hasUndefined = true;\n break;\n }\n if (global.successFactors[key] === false) {\n console.log('key: ',key);\n hasFalse = true;\n break;\n }\n }\n // If no undefined and no false, print success.\n if (!hasUndefined && !hasFalse) {\n console.log(\"---\\nSetup was a success! Please enjoy MMM-RemoteCompliments!\");\n }\n // If false, let user know and exit.\n if (hasFalse){\n console.log(\"---\\nSomething went wrong with the setup. It is recommended you delete the files created on your Google Drive and try setup again after fixing the above error.\");\n process.exit(1);\n }\n}",
"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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether this pin is currently low. | isLow() {
if (this.mode == 'output') {
return !this.high;
} else if (this.mode == 'input') {
return this.get() === false;
}
return null;
} | [
"isHigh() {\n if (this.mode == 'output') {\n return this.high;\n } else if (this.mode == 'input') {\n return this.get() === true;\n }\n return null;\n }",
"isOnTheWater() {\n return this.y <= 0;\n }",
"function isEnabled() {\n return tray != undefined;\n}",
"isLocalOnHold() {\n if (this.state !== CallState.Connected) return false;\n if (this.unholdingRemote) return false;\n let callOnHold = true; // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n\n for (const tranceiver of this.peerConn.getTransceivers()) {\n const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }",
"writeReady() {\n return !this.highWater;\n }",
"function isRateLimited () {\n return state.rateLimiting.active\n }",
"isSource() {\n return this.mode == 'output' && this.high;\n }",
"static evalReadingGreaterThanOrEqualToZero(context, dict) {\n return (libLocal.toNumber(context, dict.ReadingSim) >= 0);\n }",
"function isStillTap(){\n var max = arrayMax(piezoTrack); piezoTrack = [];\n return (max==undefined || max>config.piezoTreshold);\n}",
"through(threshold) {\n\n\t\tlet d = this.value - threshold\n\t\tlet d_old = this.value_old - threshold\n\n\t\treturn d >= 0 && d_old < 0 ? 1 : d <= 0 && d_old > 0 ? -1 : 0\n\n\t}",
"function isShortsWeather(temperature){\n if (temperature >= 75){\n return true;\n }\n return false;\n}",
"isTrackingMouse() {\n return !!this._mouseTrackingId;\n }",
"function isAboveThreshold(thisAnswer) {\n if (questionObj[\"question-preset\"] == \"NUMERIC_SCALE\") return parseInt(thisAnswer) >= 8;\n if (questionObj[\"question-preset\"] == \"YES_NO_SCALE\") return thisAnswer == \"Yes\";\n return false;\n}",
"get threshold() {\n return (0, _Conversions.gainToDb)(this._gt.value);\n }",
"get busy() {\n\t\treturn this.state == Constants.STATE.BUSY;\n\t}",
"get enableMonitoring() {\n return this.getBooleanAttribute('enable_monitoring');\n }",
"static evalReadingLessThanEqualToZero(context, dict) {\n return (libLocal.toNumber(context, dict.ReadingSim) <= 0);\n }",
"_isHovering() {\n if (this._dock.hover) {\n return true;\n } else {\n return false;\n }\n }",
"get isWeighted() {\n return this._config.isWeighted;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append a new module override at the end of the list | function moduleappend()
{
if(appending == false) {
appending = true;
new Zikula.Ajax.Request(
Zikula.Config.baseURL + "ajax.php?module=doctastic&func=createoverride",
{
onComplete: moduleappend_response
});
}
} | [
"_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 AddAmendListItem(enabled, url, search, replace)\r\n{\r\n amendList.push({ \"enabled\": enabled, \"url\": url, \"search\": search, \"replace\": replace });\r\n}",
"function addNewModule() {\r\n\r\n // Prompt user for the new module name\r\n //\r\n var modname = prompt(\"Name of the new module\", \"Module\");\r\n\r\n // if the user pressed cancel, just return\r\n //\r\n if (!modname)\r\n return;\r\n\r\n if (isExistingModuleOrLibName(modname) || isKeyword(modname)) {\r\n alert(\"Name \" + name + \" already exists!\");\r\n return;\r\n }\r\n\r\n // TODO: Check duplicate module/lib/grid/func name\r\n //\r\n\r\n // Create a new module and init it. Make it the current module\r\n //\r\n initCurModule(modname); // init module\r\n\r\n initMainFunc(DefMainFuncName); // add main function and init it\r\n\r\n initCurStep(); // add and init a step\r\n\r\n changeModule(CurProgObj.curModNum);\r\n}",
"function override(overrides){\r\n return newElementHolderProxy(undefined,overrides)\r\n }",
"function moduleappend_response(req)\n{\n appending = false;\n if (!req.isSuccess()) {\n Zikula.showajaxerror(req.getMessage());\n return;\n }\n var data = req.getData();\n\n // copy new module li from module_1.\n var newmodule = $('module_'+firstmodule).cloneNode(true);\n\n // update the ids. We use the getElementsByTagName function from\n // protoype for this. The 6 tags here cover everything in a single li\n // that has a unique id\n newmodule.id = 'module_' + data.id;\n $A(newmodule.getElementsByTagName('a')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('div')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('span')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('input')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; node.value = ''; });\n $A(newmodule.getElementsByTagName('select')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('button')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('textarea')).each(function(node){ node.id = node.id.split('_')[0] + '_' + data.id; });\n\n // append new module to the module list\n $('modulelist').appendChild(newmodule);\n\n // set initial values in input, hidden and select\n //$('modname_' + data.id).value = data.modname;\n //$('description_' + data.id).value = data.description;\n //$('members_' + data.id).href = data.membersurl;\n\n// Zikula.setselectoption('modulenavtype_' + data.id, data.navtype_disp);\n// Zikula.setselectoption('moduleenablelang_' + data.id, data.enablelang);\n\n // hide cancel icon for new modules\n// Element.addClassName('moduleeditcancel_' + data.id, 'z-hide');\n // update delete icon to show cancel icon\n// Element.update('moduleeditdelete_' + data.id, canceliconhtml);\n\n // update some innerHTML\n// Element.update('moduleid_' + data.id, data.id);\n// Element.update('modulemodname_' + data.id, data.modname);\n// Element.update('modulenavtype_' + data.id, data.navtype_disp);\n// Element.update('moduleenablelang_' + data.id, data.enablelang);\n //Element.update('members_' + data.id, data.membersurl);\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\n // remove class to make edit button visible\n Element.removeClassName('modifyajax_' + data.id, 'z-hide');\n Event.observe('modifyajax_' + data.id, 'click', function(){modulemodifyinit(data.id)}, false);\n\n // turn on edit mode\n allownameedit[data.id] = true;\n enableeditfields(data.id);\n\n // we are ready now, make it visible\n Element.removeClassName('module_' + data.id, 'z-hide');\n new Effect.Highlight('module_' + data.id, { startcolor: '#99ff66', endcolor: '#ffffff' });\n\n\n // set flag: we are adding a new module\n adding[data.id] = 1;\n}",
"function setAlternateAngular() {\n\t\tvar alternateModules = {};\n\n\t\t// This method cannot be called more than once\n\t\tif (alt_angular) {\n\t\t\tthrow Error( \"setAlternateAngular can only be called once.\" );\n\t\t} else {\n\t\t\talt_angular = {};\n\t\t}\n\n\t\t// Make sure that bootstrap has been called\n\t\tcheckAngularAMDInitialized();\n\n\t\t// Createa a copy of orig_angular\n\t\torig_angular.extend( alt_angular, orig_angular );\n\n\t\t// Custom version of angular.module used as cache\n\t\talt_angular.module = function(name, requires) {\n\n\t\t\tif (typeof requires === \"undefined\") {\n\t\t\t\t// Return undefined if module was created using the alt_angular\n\t\t\t\tif (alternateModules.hasOwnProperty( name )) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t} else {\n\t\t\t\t\treturn orig_angular.module( name );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// console.log(\"alt_angular.module START for '\" + name + \"': \",\n\t\t\t\t// arguments);\n\t\t\t\tvar orig_mod = orig_angular.module.apply( null, arguments ), item = {\n\t\t\t\t\tname : name,\n\t\t\t\t\tmodule : orig_mod\n\t\t\t\t};\n\t\t\t\talternate_queue.push( item );\n\t\t\t\talternateModules[name] = orig_mod;\n\t\t\t\treturn orig_mod;\n\t\t\t}\n\t\t};\n\n\t\twindow.angular = alt_angular;\n\t}",
"mark () {\n\t\tthis.module.importedByBundle[ this.originalName ] = true;\n\t\tthis.modifierStatements.forEach( stmt => stmt.mark() );\n\t}",
"function setAlternateAngular() {\n // This method cannot be called more than once\n if (alt_angular) {\n throw Error(\"setAlternateAngular can only be called once.\");\n } else {\n alt_angular = {};\n }\n\n // Make sure that bootstrap has been called\n checkBootstrapped();\n\n // Create a a copy of orig_angular with on demand loading capability\n orig_angular.extend(alt_angular, orig_angular);\n\n // Custom version of angular.module used as cache\n alt_angular.module = function (name, requires) {\n if (typeof requires === \"undefined\") {\n // Return module from alternate_modules if it was created using the alt_angular\n if (alternate_modules_tracker.hasOwnProperty(name)) {\n return alternate_modules[name];\n } else {\n return orig_angular.module(name);\n }\n } else {\n var orig_mod = orig_angular.module.apply(null, arguments),\n item = { name: name, module: orig_mod};\n alternate_queue.push(item);\n orig_angular.extend(orig_mod, onDemandLoader);\n \n /*\n Use `alternate_modules_tracker` to track which module has been created by alt_angular\n but use `alternate_modules` to cache the module created. This is to simplify the\n removal of cached modules after .processQueue.\n */\n alternate_modules_tracker[name] = true;\n alternate_modules[name] = orig_mod;\n \n // Return created module\n return orig_mod;\n }\n };\n \n window.angular = alt_angular;\n }",
"function AddonCompatibilityOverride(aType, aMinVersion, aMaxVersion, aAppID,\n aAppMinVersion, aAppMaxVersion) {\n this.type = aType;\n this.minVersion = aMinVersion;\n this.maxVersion = aMaxVersion;\n this.appID = aAppID;\n this.appMinVersion = aAppMinVersion;\n this.appMaxVersion = aAppMaxVersion;\n}",
"function addModule() {\n $('<section>')\n .attr('id', 'rsw-discord')\n .addClass('rsw-custom-module rail-module')\n .append(\n $('<a>')\n .attr('href', 'https://discord.gg/98hqjRg')\n .append(\n $('<img>')\n .attr('src', 'https://vignette.wikia.nocookie.net/dendro/images/9/94/WikiIcon.png/revision/latest/scale-to-width-down/240?cb=20190217055247')\n ),\n $('<div>')\n .append(\n $('<p>')\n .append(\n 'The Infinite Dendrogram Wiki has an Official Discord Server! Click the button below to join and chat with fellow fans live, or click ',\n $('<a>')\n .attr('href', mw.util.wikiGetlink('Infinite Dendrogram Wiki:Discord_Policy'))\n .text('here'),\n ' to read our chat rules.'\n ),\n $('<a>')\n .attr('href', 'https://discord.gg/98hqjRg')\n .addClass('wds-button')\n .text('Get invite')\n )\n )\n .insertBefore('#wikia-recent-activity');\n }",
"registerModules( modules ) {\n modules.forEach( function( module ) {\n if ( !module instanceof baseModule ) {\n console.log( 'Error trying to attach module to tatty-screen', module.name );\n return;\n }\n\n this.modules.push( module );\n\n if ( module.init ) {\n module.init.call( this, module );\n }\n\n var expose = module.expose( module );\n\n for ( let key in expose ) {\n if ( !this[ key ] && expose.hasOwnProperty( key ) ) {\n this[ key ] = expose[ key ];\n }\n }\n }, this );\n }",
"addKeys () {\n this._eachPackages(function (_pack) {\n _pack.add()\n })\n }",
"function findLifeSupportModule(){\n \n for(var i = 0; i < availableModules.length; i++){\n if(availableModules[i].name == \"life-support\") {\n availableModules[i].enabled = true; //enable the module first\n loadModule(i); //load module into modules array\n }\n }\n}",
"function loadBumpCommand(){\r\n commands.set('modCommands',\"bump \",bump);\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 add(data) {\n // Add new migrated compoennt to lookup\n }",
"function addImportIfNecessary(content, importLine) {\n if (content.includes(importLine)) return content;\n\n // Find where to insert `importLine`. We'll add it either to\n // an existing import * as block or start a new one below the import {TestRunner} block.\n const lines = content.split('\\n');\n let lastImportIndex = 0;\n let onlyHasTestRunnerImports = true;\n for (const [index, line] of lines.entries()) {\n if (line.startsWith('import {')) {\n lastImportIndex = index;\n } else if (line.startsWith('import * as')) {\n lastImportIndex = index;\n onlyHasTestRunnerImports = false;\n }\n }\n\n const linesToInsert = onlyHasTestRunnerImports ? ['', importLine] : [importLine];\n lines.splice(lastImportIndex + 1, 0, ...linesToInsert);\n return lines.join('\\n');\n}",
"function maybe_append_name(interpreter_name) {\n\t var storage_key = self.prefix_name() + '_interpreters';\n\t var names = storage.get(storage_key);\n\t if (names) {\n\t names = JSON.parse(names);\n\t } else {\n\t names = [];\n\t }\n\t if ($.inArray(interpreter_name, names) === -1) {\n\t names.push(interpreter_name);\n\t storage.set(storage_key, JSON.stringify(names));\n\t }\n\t }",
"function loadModule(index) {\n \n //add in the challenge #8\n if(!availableModules[index].essential){\n availableModules[index].essential = true;//change essential property to true\n }\n \n ship.modules.push(availableModules[index]);\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NOTE: The CommandHandler is effectively an abstract base for various handlers including ActionHandler, AccessorHandler and AssertHandler. Subclasses need to implement an execute(seleniumApi, command) function, where seleniumApi is the Selenium object, and command a SeleniumCommand object. | function CommandHandler(type, haltOnFailure, executor) {
this.type = type;
this.haltOnFailure = haltOnFailure;
this.executor = executor;
} | [
"handleCommandEvent (e) {\n if (e == null || e.target == null) { return false }\n var target = $(e.target)\n var parent = target.parent()\n var isCommand = parent.hasClass(Constants.commandClassName)\n var eventType = e.type\n if (eventType === 'click' && isCommand) {\n var commandId = parent.attr('data-sheetmonkey-commandid')\n var pluginID = parent.attr('data-sheetmonkey-pluginid')\n let myCommandIDs = Array.from(this.getMenuCommandsToInsert()).map(cmd => cmd.id)\n\n if (myCommandIDs.indexOf(commandId) >= 0) {\n this.dismissMenu()\n this.D.log('Routing command click to plugin... PluginID:', pluginID, 'CommandID:', commandId)\n this.pluginHost.notifyCommandClicked(pluginID, commandId)\n return true\n } else {\n this.D.log(`Command ${commandId} not mine! myCommandIDs:`, myCommandIDs)\n }\n }\n return false\n }",
"getCommandHandler() {\n const channelToConnHandler = new WeakMap();\n const handler = {\n // Executed upon an error in handling the websocket.\n onError(obj, { channelHandle }) {\n const connHandler = channelToConnHandler.get(channelHandle);\n console.error('Have error', obj);\n if (connHandler.onError) {\n connHandler.onError(obj);\n }\n },\n\n // These hooks are run when the websocket is opened or closed.\n onOpen(obj, meta) {\n const { channelHandle } = meta;\n const send = (objToSend) => E(http).send(objToSend, [channelHandle]);\n const connHandler = makeConnectionHandler(send, meta);\n channelToConnHandler.set(channelHandle, connHandler);\n if (connHandler.onOpen) {\n connHandler.onOpen(obj);\n }\n },\n onClose(obj, { channelHandle }) {\n const connHandler = channelToConnHandler.get(channelHandle);\n channelToConnHandler.delete(channelHandle);\n if (connHandler.onClose) {\n connHandler.onClose(obj);\n }\n },\n onMessage(obj, { channelHandle }) {\n const connHandler = channelToConnHandler.get(channelHandle);\n return connHandler.onMessage(obj);\n },\n };\n return harden(handler);\n }",
"function handleCommand(cmd,argu,id) {\r\n words = argu.split(\" \");\r\n switch(cmd.toLowerCase()) {\r\n case \"yell\":\r\n case \"say\": respond(argu); break; \r\n case \"kick\": kick(id,\"Requested.\"); break;\r\n case \"ban\": ban(id,\"Requested\", argu[1]);\r\n case \"member\": member(id); break;\r\n case \"guest\": guest(id); break;\r\n case \"mod\": mod(id); break;\r\n }\r\n}",
"onMessage (message) {\n if (message.command && message.options) {\n this.executeCommand(message.command, message.options);\n }\n }",
"function Commander(cmd) {\n var command =\n (getOsType().indexOf('WIN') !== -1 && cmd.indexOf('.exe') === -1) ?\n cmd + '.exe' : cmd;\n var _file = null;\n\n // paths can be string or array, we'll eventually store one workable\n // path as _path.\n this.initPath = function(paths) {\n if (typeof paths === 'string') {\n var file = getFile(paths, command);\n _file = file.exists() ? file : null;\n } else if (typeof paths === 'object' && paths.length) {\n for (var p in paths) {\n try {\n var result = getFile(paths[p], command);\n if (result && result.exists()) {\n _file = result;\n break;\n }\n } catch (e) {\n // Windows may throw error if we parse invalid folder name,\n // so we need to catch the error and continue seaching other\n // path.\n continue;\n }\n }\n }\n if (!_file) {\n throw new Error('it does not support ' + command + ' command');\n }\n };\n\n this.run = function(args, callback) {\n var process = Cc['@mozilla.org/process/util;1']\n .createInstance(Ci.nsIProcess);\n try {\n log('cmd', command + ' ' + args.join(' '));\n process.init(_file);\n process.run(true, args, args.length);\n } catch (e) {\n throw new Error('having trouble when execute ' + command +\n ' ' + args.join(' '));\n }\n callback && callback();\n };\n\n /**\n * This function use subprocess module to run command. We can capture stdout\n * throught it.\n *\n * @param {Array} args Arrays of command. ex: ['adb', 'b2g-ps'].\n * @param {Object} options Callback for stdin, stdout, stderr and done.\n *\n * XXXX: Since method \"runWithSubprocess\" cannot be executed in Promise yet,\n * we need to keep original method \"run\" for push-to-device.js (nodejs\n * support). We'll file another bug for migration things.\n */\n this.runWithSubprocess = function(args, options) {\n log('cmd', command + ' ' + args.join(' '));\n var p = subprocess.call({\n command: _file,\n arguments: args,\n stdin: (options && options.stdin) || function(){},\n stdout: (options && options.stdout) || function(){},\n stderr: (options && options.stderr) || function(){},\n done: (options && options.done) || function(){},\n });\n p.wait();\n };\n}",
"send(...args) {\n this._send_handler(...args)\n }",
"function buzzerManageCommand(sessionId, hostId, action) {\n /* eslint-enable no-unused-vars */\n var bac = buzzapi.messageFactory.create(messageConstants.BUZZER_ACTION_COMMAND);\n bac.sessionId = sessionId;\n bac.hostId = hostId;\n bac.action = action;\n\n client.emit(messageConstants.BUZZER_ACTION_COMMAND, bac, function (rm) {\n if (rm.type === messageConstants.ERROR) {\n var err = buzzapi.messageFactory.restore(rm, messageConstants.ERROR);\n alertBootstrap(err.error, 'danger');\n }\n });\n}",
"invokeTriggerHandlers(clickHandler, inputData, resultCallback) {\n // Always add callback methods in order to retrieve the generated message object\n const inputs = [...(inputData || [])];\n inputs.push(resultCallback);\n\n if (typeof clickHandler === 'function') {\n clickHandler.apply(null, inputs);\n } else if (typeof clickHandler === 'string') {\n window.rudderanalytics[clickHandler].apply(null, inputs);\n }\n }",
"function makeCommand(cmdName) {\n return {\n name: cmdName,\n arguments: [\n { id: 'search',\n role: 'object',\n nountype: noun_arb_text,\n label: 'search text'\n },\n ],\n previewUrl: 'http://localhost/webiquity/commands/testCommand.html?cmd=' + cmdName + '&preview={{search}}',\n executeUrl: 'http://localhost/webiquity/commands/testCommand.html?cmd=' + cmdName + '&search={{search}}',\n url: 'http://localhost/webiquity/commands/testCommand.html?cmd=' + cmdName,\n icon: 'http://localhost/webiquity/skin/icons/application_view_list.png'\n }\n}",
"function loadCommandLoader(){\r\n commands = new function() {\r\n var items = {};\r\n items.regularCommands = [\r\n \"'reload\",\r\n \"'resynch\",\r\n \"'toggleFilter\",\r\n \"'toggleAutosynch\",\r\n \"'mute\",\r\n \"'unmute\"\r\n ]; \r\n items.modCommands = [\r\n \"'togglePlaylistLock\",\r\n \"'ready\",\r\n \"'kick \",\r\n \"'ban \",\r\n \"'unban \",\r\n \"'clean\",\r\n \"'remove \",\r\n \"'purge \",\r\n \"'move \",\r\n \"'play \",\r\n \"'pause\",\r\n \"'resume\",\r\n \"'seekto \",\r\n \"'seekfrom \",\r\n \"'setskip \",\r\n \"'banlist\",\r\n \"'modlist\",\r\n \"'save\",\r\n \"'leaverban \",\r\n //commented those so you can't accidently use them\r\n //\"'clearbans\",\r\n //\"'motd \",\r\n //\"'mod \",\r\n //\"'demod \",\r\n //\"'description \",\r\n \"'next\"\r\n ];\r\n items.addOnSettings = [];\r\n items.commandFunctionMap = {};\r\n unsafeWindow.addEventListener (\"message\", \r\n function(event){\r\n try{\r\n var parsed = JSON.parse(event.data);\r\n if(parsed.commandParameters){\r\n items.commandFunctionMap[parsed.commandParameters[0].toLowerCase()](parsed.commandParameters);\r\n }\r\n }catch(err){\r\n\r\n }\r\n }, false);\r\n return {\r\n \"set\": function(arrayName, funcName, func) {\r\n if(funcName[0] !== '$'){\r\n if(arrayName === 'addOnSettings'){\r\n funcName = \"~\"+funcName;\r\n }else{\r\n funcName = \"'\"+funcName;\r\n }\r\n }\r\n items[arrayName].push(funcName);\r\n items.commandFunctionMap[funcName.toLowerCase()] = func;\r\n },\r\n \"get\": function(arrayName) {\r\n return items[arrayName];\r\n },\r\n \"getAll\":function(){\r\n return items;\r\n },\r\n \"execute\":function(funcName, params){\r\n commandExecuted = false;\r\n funcName = funcName.toLowerCase();\r\n if(funcName[0] === '$'){\r\n return;\r\n }\r\n if(items.commandFunctionMap.hasOwnProperty(funcName)){\r\n funcName = funcName;\r\n }\r\n else if(items.commandFunctionMap.hasOwnProperty(funcName+' ')){\r\n funcName = funcName+' ';\r\n }else{\r\n funcName = undefined;\r\n }\r\n if(funcName){\r\n commandExecuted = true;\r\n params[0] = funcName;\r\n unsafeWindow.postMessage(JSON.stringify({ commandParameters: params }),\"*\");\r\n //items.commandFunctionMap[funcName](params);\r\n }\r\n }\r\n };\r\n }; \r\n\r\n $(\"#chat input\").bind(\"keypress\", function(event) {\r\n if (event.keyCode === $.ui.keyCode.ENTER) {\r\n var params = $(this).val().split(' ');\r\n commands.execute(params[0],params);\r\n }\r\n });\r\n}",
"async runDefaultCommand() {\n this.defaultCommand.boot();\n validateCommand_1.validateCommand(this.defaultCommand);\n /**\n * Execute before/after find hooks\n */\n await this.hooks.execute('before', 'find', this.defaultCommand);\n await this.hooks.execute('after', 'find', this.defaultCommand);\n /**\n * Make the command instance using the container\n */\n const commandInstance = this.application.container.make(this.defaultCommand, [\n this.application,\n this,\n ]);\n /**\n * Execute before run hook\n */\n await this.hooks.execute('before', 'run', commandInstance);\n /**\n * Keep a reference to the entry command\n */\n this.entryCommand = commandInstance;\n /**\n * Execute the command\n */\n return commandInstance.exec();\n }",
"function sendCommandToRoboBuoy(command, values)\n{\n $.ajax({\n\t\t\turl: $SCRIPT_ROOT + '/receive_command',\n\t\t\t//data object to send\n\t\t\tdata: {\n\t\t\t\t'command': command,\n\t\t\t\t'values': values\n\t\t\t},\n\t\t\t//this time we're posting to the server\n\t\t\ttype: 'POST',\n\n\t\t\t//log the servers response or error message to the browser's console\n\t\t\tsuccess: function(response) {\n\t\t\t\tconsole.log(response);\n\t\t\t},\n\t\t\terror: function(error) {\n\t\t\t\tconsole.log(error);\n\t\t\t}\n\t\t});\n}",
"function make_external_command({command_info,client_id,ws}) { \n\n //dynamically create the command class here \n class external_command extends base_command { \n\t\n\tconstructor(config) {\n \t super({id : command_info['id']})\n\t this.command_info = command_info //store the info within the command \n\t}\n\t\n\tstatic get_info() { \n\t return command_info \n\t}\n\t//loop read from the external receive channel and emit \n\tasync listen(receive) { \n\t this.log.i(\"Starting listen loop\")\n\t while (true) { \n\t\tlet msg = await receive.shift() //read from the receive channel \n\t\tswitch(msg['type']) { \n\t\t \n\t\tcase 'emit' : \n\t\t this.emit(msg['data'] )\n\t\t break\n\t\t \n\t\tcase 'feedback' : \n\t\t this.feedback(msg['data'] )\n\t\t break\n\t\t \n\t\t \n\t\tcase 'finish' : \n\t\t this.finish({payload : {result: msg['data']['result']},\n\t\t\t\t error : msg['data']['error']})\n\t\t break \n\n\t\tcase 'call_command' : \n\t\t this.log.i(\"Calling command\")\n\t\t this.launch_command(msg['data']) \n\t\t break \n\t\t \n\t\tdefault : \n\t\t this.log.i(\"Unrecognized msg type in listen loop:\")\n\t\t this.log.i(msg)\n\t\t break \n\t\t}\n\t }\n\t}\n\t\n\t// define the relay function \n\trelay(data) { \n\t //append id and instance id\n\t data.id = this.cmd_id.split(\".\").slice(1).join(\".\") //get rid of module name\n\t data.instance_id = this.instance_id \n\t ws.send(JSON.stringify(data)) // send it \n\t}\n\t\n\tasync run() { \n\t let id = this.command_info['id']\n\t \n\t this.log.i(\"Running external command: \" + id )\n\t \n\t //make a new channel \n\t let receive = new channel.channel()\n\t \n\t //update the global clients structure \n\t let instance_id = this.instance_id\n\t add_client_command_channel({client_id,receive,instance_id})\n\n\t \n\t //start the async input loop\n\t this.listen(receive)\n\t \n\t //notify external interface that the command has been loaded \n\t let args = this.args \n\t var call_info = {instance_id,args } \n\t //external interface does not know about the MODULE PREFIX added to ID \n\t call_info.id = id.split(\".\").slice(1).join(\".\") \n\t \n\t let type = 'init_command' \n\t this.relay({type, call_info}) \n\t this.log.i(\"Sent info to external client\")\n\t \n\t //loop read from input channel \n\t this.log.i(\"Starting input channel loop and relay\")\n\t var text \n\t while(true) { \n\t\tthis.log.i(\"(csi) Waiting for input:\")\n\t\t//text = await this.get_input()\n\t\ttext = await this.input.shift() //to relay ABORTS \n\t\tthis.log.i(\"(csi) Relaying received msg to external client: \" + text)\n\t\t//now we will forward the text to the external cmd \n\t\tthis.relay({type: 'text' , data: text})\n\t }\n\t}\n }\n //finish class definition ------------------------------ \n return external_command\n}",
"function callRubyScript(command, handler) {\n\tcommand = makeRubyScript(command);\n\tconsole.log(\"<pre>\"+command+\"</pre>\");\n\treturn callScript(command, handler);\n}",
"function slash(commands, sender) {\n if(_.isArray(commands)) {\n _.each(commands, function(command) {\n slash(command, sender);\n });\n return;\n }\n if(__plugin.canary) {\n if(sender === server) {\n server.consoleCommand(commands);\n } else {\n server.consoleCommand(commands, sender);\n }\n }\n if(__plugin.bukkit) {\n if(!sender) {\n // if sender is not specified assume server console\n server.dispatchCommand(server.consoleSender, commands);\n } else {\n server.dispatchCommand(sender, commands);\n }\n }\n}",
"registerCommand() {\n this._commander\n .command(this.command)\n .description(this.description)\n .action((args, options) => this.action(args, options));\n }",
"function SoCommand(botName) {\n var types = {\n 'jira': 'http://i.imgur.com/Zjwo4.gif',\n 'shame': 'http://i.imgur.com/GVDjO.gif',\n 'flag': 'http://i.imgur.com/oN1Er.gif',\n 'crazy': 'http://i188.photobucket.com/albums/z284/oblongman7/Scrubs/b6488ee3.gif',\n 'notme': 'http://i.imgur.com/V9MavVa.gif',\n 'desperate': 'http://media.tumblr.com/tumblr_lsdhbmlL611qhjgo1.gif',\n 'waiting': 'http://i.imgur.com/aJaBc.gif',\n 'success': 'http://i.imgur.com/AKtqu.gif',\n 'dubious': 'http://i.imgur.com/qX3nQi1.gif',\n 'baddone': 'http://i.imgur.com/LaOykFc.gif',\n 'incredible': 'http://i.imgur.com/D26gL.gif',\n 'deploy': 'http://i1.kym-cdn.com/photos/images/original/000/234/786/bf7.gif'\n };\n\n Command.call(this, {\n 'name': 'so',\n 'author': botName,\n 'matcher': '^so\\\\s(' + Object.keys(types).join('|') + ')$',\n 'action': '$gif',\n 'native': 'true',\n 'help': helpBuilder.build('so', botName,\n '\\tDisplay a gif according to given situation.\\n'\n + '\\tavailable situations: ' + Object.keys(types).join(', ') + '\\n'\n + '\\t➜ so crazy'),\n 'paramsMap': ['$type'],\n 'visible': true,\n 'processors': [{\n 'placeholder': '$gif',\n 'handle': function (message, translated) {\n return types[translated['$type']];\n }\n }]\n });\n}",
"getCommand() {\n return __awaiter(this, void 0, void 0, function* () {\n return this.instruction.command;\n });\n }",
"function commandTrigger() {\n var line = promptText;\n if (typeof config.commandValidate == 'function') {\n var ret = config.commandValidate(line);\n if (ret == true || ret == false) {\n if (ret) {\n handleCommand();\n }\n } else {\n commandResult(ret, \"jquery-console-message-error\");\n }\n } else {\n handleCommand();\n }\n }",
"function postCommand(obj) {\n\n // Get command from DOM element and remove line breaks\n var command = $$(obj).text();\n command = command.replace(/(\\r\\n|\\n|\\r)/gm,\"\"); // Strip newlines\n\n // If we need user input for free-form variable\n if (command.indexOf('_custom input_') > -1) {\n\n var input = prompt(command, \"\");\n if (input != null) {\n command = command.replace('_custom input_',input);\n } else {\n return;\n }\n }\n\n // Remove all non-alphanumeric from JSON command (Alexa only does alpha-numeric\n command = command.replace(/[^a-zA-Z0-9 :]/g, '');\n\n // Send command to jarvis\n // *** NB: Rooted AdBlocker on my Cell Phone sometimes interfers with AJAX requests!!!\n $$.post('../main.php', '{\"request\":{\"type\":\"IntentRequest\",\"intent\":{\"name\":\"DoCommand\",\"slots\":{\"command\":{\"name\":\"command\",\"value\":\"'+command+'\"}}}}}', function (data) {\n var jsonData = JSON.parse(data);\n var toast = myApp.toast(jsonData.response.outputSpeech.text, '', {})\n toast.show(true);\n });\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show the forum topic with the given ID in the center panel | function showForumTopic(topicID)
{
topic = getForumTopicByID(topicID);
if(topic == null)
return;
contents = '<h1>' + topic.title + '</h1>';
participant = getParticipantByID(topic.participantID);
if(participant == null)
contents += '<h2>By: Removed participant</h2>';
else
contents += '<h2>By: ' + participant.name + ' ' + participant.surname + '</h2>';
contents += '<p>' + topic.date + '</p>';
contents += '<p>' + topic.text + '</p>';
contents += '<h2>Replies:</h2>';
contents += '<ul>';
for(reply in topic.replies)
{
participant = getParticipantByID(topic.replies[reply].participantID);
contents += '<li>';
if(participant == null)
contents += '<h2>By: Removed participant</h2>';
else
contents += '<h2>By: ' + participant.name + ' ' + participant.surname + '</h2>';
contents += '<p>' + topic.replies[reply].date + '</p>';
contents += '<p>' + topic.replies[reply].text + '</p>';
contents += '</li>';
}
contents += '</ul>';
//Add the reply textbox
contents += '<h2>Reply:</h2>';
contents += '<textarea id="forum-topic-reply-area"></textarea>';
contents += '<input id="forum-reply-button" type="button" value="Reply" class="submit" onclick="onForumTopicReplyClicked(' + topicID + ')"/>';
document.getElementById("center-panel").innerHTML = contents;
} | [
"function showForum(courseID)\r\n{\r\n course = getCourseByID(courseID);\r\n if(course == null)\r\n return;\r\n var contents = '<h1>Forums: ' + course.name + '</h1>';\r\n topics = getForumTopicsByCourseID(courseID);\r\n contents += '<ul>';\r\n for(topic in topics)\r\n {\r\n participant = getParticipantByID(topics[topic].participantID);\r\n contents += '<li>';\r\n contents += '<h2>' + topics[topic].title + '</h2>';\r\n if(participant == null)\r\n contents += '<h3>By: Removed participant</h3>';\r\n else\r\n contents += '<h3>By: ' + participant.name + ' ' + participant.surname + '</h3>';\r\n contents += '<p>' + topics[topic].date + '</p>';\r\n contents += '<p>' + topics[topic].text + '</p>';\r\n contents += '<input id=\"forum-show-more-button-' + topics[topic].id + '\" type=\"button\" value=\"Show more\" class=\"submit\" onclick=\"onForumShowMoreClicked(' + topics[topic].id + ')\"/>';\r\n contents += '</li>';\r\n }\r\n contents += '</ul>';\r\n contents += '<input class=\"forum-new-topic-button\" type=\"button\" value=\"New topic\" class=\"submit\" onclick=\"onForumNewTopicClicked(' + courseID + ')\"/>';\r\n document.getElementById(\"center-panel\").innerHTML = contents;\r\n}",
"function showUpdateTopic(button_id) {\n var div_id = document.getElementById(button_id).parentNode.id;\n var children = document.getElementById(div_id).childNodes;\n var topic = children[3].textContent;\n var description = children[9].textContent;\n // show form and set the form fields to the values of the topic selected\n updateForm.style.display = \"block\";\n document.getElementById(\"update-item-id\").value = div_id;\n document.getElementById(\"updateForm-topic\").value = topic;\n document.getElementById(\"updateForm-description\").value = description;\n formType = \"updateTopic\";\n}",
"setTopicID( id ) {\n return 'topic-' + parseInt( id );\n }",
"function showDiscussion() {\n console.log(\"showDiscussion() started\");\n var name = current.author ? current.author.name : \"(Yourself)\";\n $(\"#discussion-author\").html(\"\").html(name);\n $(\"#discussion-creationDate\").html(\"\").html(current.message.creationDate);\n $(\"#discussion-likeCount\").html(\"\").html(current.message.likeCount);\n $(\"#discussion-modificationDate\").html(\"\").html(current.message.modificationDate);\n $(\"#discussion-replyCount\").html(\"\").html(current.message.replyCount);\n $(\"#discussion-status\").html(\"\").html(current.message.status);\n $(\"#discussion-subject\").attr(\"value\", current.message.subject);\n $(\"#discussion-text\").html(\"\").html(current.message.content.text);\n $(\"#discussion-viewCount\").html(\"\").html(current.viewCount);\n showOnly(\"discussion-div\");\n}",
"function showForums()\r\n{\r\n var contents = '<h1>Forums</h1>';\r\n contents += '<ul>';\r\n for(course in courses)\r\n {\r\n contents += '<li><a onclick=\"showForum(' + courses[course].id + ')\">' + courses[course].name + '</a></li>';\r\n }\r\n contents += '</ul>';\r\n contents += '<br>';\r\n document.getElementById(\"center-panel\").innerHTML = contents;\r\n}",
"function chooseTopic(){\n\tchoosenTopic = null;\n\t\n\t/**\n\t * Hide the back button and play button\n\t */\n\tvar btn = find(\".back-btn\",document.getElementById(\"controls\"));\n\tbtn = btn[0];\n\tbtn.style.display = \"none\";\n\tbtn = find(\".game-btn\",document.getElementById(\"controls\"));\n\tbtn = btn[0];\n\tbtn.style.display = \"none\";\n\t\n\tgenTopicTiles();\n}",
"function changeCommitteeTopic() {\r\n if (currentTopic === committes[currentCommittee].topics.length - 1) {\r\n currentTopic = 0;\r\n } else {\r\n currentTopic++;\r\n }\r\n document.getElementById(\"committeeTopicText\").innerHTML = committes[currentCommittee].topics[currentTopic];\r\n}",
"function showNewTopicPopup(courseID)\r\n{\r\n var contents = \"\";\r\n contents += '<div class=\"popup new-topic-popup-window\">';\r\n contents += '<h1>Create new topic</h1>';\r\n contents += '<p>Title:</p>';\r\n contents += '<input id=\"new-topic-title-textbox\" type=\"text\"/>';\r\n contents += '<p>Text:</p>';\r\n contents += '<textarea id=\"new-topic-text-area\"></textarea>';\r\n contents += '<input id=\"new-topic-accept-button\" type=\"button\" value=\"Create\" class=\"submit\" onclick=\"onNewTopicAcceptClicked(' + courseID + ')\"/>';\r\n contents += '<input id=\"new-topic-cancel-button\" type=\"button\" value=\"Cancel\" class=\"submit\" onclick=\"onNewTopicCancelClicked(' + courseID + ')\"/>';\r\n contents += '</div>';\r\n\r\n //Add the popup window to the fullscreen popup and show it on screen\r\n document.getElementById('fullscreen-popup').innerHTML = contents;\r\n $('#fullscreen-popup').show();\r\n}",
"function displaytopicInfo() {\n $(\"#topics-view\").empty();\n topic = $(this).attr(\"data-name\");\n queryURL = \"http://api.giphy.com/v1/gifs/search?limit=10&q=\" + topic + \"&api_key=dc6zaTOxFJmzC\";\n\n // Creates AJAX call for the specific topic button being clicked\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).done(function(response) {\n\n for(var i = 0; i < 10; i++){\n \n var classImage = \"image\" + i;\n topicDiv = $(\"<div class = 'topicDisplay'>\");\n rating = response.data[i].rating;\n pOne = $(\"<p>\").text(\"Rating: \" + rating);\n topicDiv.append(pOne);\n imageUrlStill = response.data[i].images.fixed_height_still.url;\n imageUrlAnimate = response.data[i].images.fixed_height.url;\n image = $(\"<img>\").attr(\"src\", imageUrlStill);\n image.addClass(\"gif\");\n image.attr(\"data-state\", \"still\");\n image.attr(\"data-still\", imageUrlStill);\n image.attr(\"data-animate\", imageUrlAnimate);\n topicDiv.append(image);\n $(\"#topics-view\").prepend(topicDiv);\n\n }\n });\n\n }",
"function getTopicInfo()\n\t{\tvar userid= {};\n\t\tvar posts ={};\n\t\t\t\t\t\n\t\t\tPostFactory.getTopicInfo($routeParams, function (result){\t\n\t\t\tif(result){\n\t\t\t\t$scope.topicInfo = result;\n\t\t\t\t//Adding the id of the user who posted the topic to an object to reuse the getClikeduser\n\t\t\t\t//method in userfactory\n\t\t\t\tuserid.id = result._user; \n\t\t\t\t//Reusing userfactory getclickeduser method to get the username of the user who posted the topic\n\t\t\t\tUserFactory.getClickedUser(userid, function (output){\n\t\t\t\t\t $scope.topicInfo.username = output.username;\n\t\t\t\t\t $scope.topicInfo.loggeduser=JSON.parse(localStorage.userinfo);\t//adding the logged in users info to send while saving the post\n\t\t\t\t});\n\t\t\t\t \n\t\t\t}\n\t\t})\n\t}",
"function mswShowSubFAQ(id, openact) {\r\n if (jQuery('#mswfaqcatarea .cat' + id + ' i').attr('class') == 'fa fa-folder-open fa-fw cursor_pointer') {\r\n jQuery('#mswfaqcatarea .cat' + id + ' i').attr('class', 'fa fa-folder fa-fw cursor_pointer');\r\n jQuery('#mswfaqcatarea .sub' + id + ' div').slideUp();\r\n } else {\r\n jQuery('#mswfaqcatarea .mswfaqcatlink i').attr('class', 'fa fa-folder fa-fw cursor_pointer');\r\n jQuery('#mswfaqcatarea .mswfaqsublink div').slideUp();\r\n if (jQuery('#mswfaqcatarea .sub' + id + ' div').length > 0) {\r\n jQuery('#mswfaqcatarea .cat' + id + ' i').attr('class', 'fa fa-folder-open fa-fw cursor_pointer');\r\n switch(openact) {\r\n case 'show':\r\n jQuery('#mswfaqcatarea .sub' + id + ' div').show();\r\n break;\r\n default:\r\n jQuery('#mswfaqcatarea .sub' + id + ' div').slideDown();\r\n break;\r\n }\r\n }\r\n }\r\n}",
"function handleFollowTopic(id, callback) {\n\tappAjax(\n\t\t'/ajax/follow-topic',\n\t\t'post',\n\t\t{id: id},\n\t\t'json',\n\t\tfunction(response) {\n\t\t\tcallback(response);\n\t\t\tif (!response.error) {\n\t\t\t\tconsole.log('success');\n\t\t\t} else {\n\t\t\t\tconsole.log('error');\n\t\t\t}\n\t\t}\n\t);\n}",
"function showAddTopic(){\n // show form and set the form fields to null\n createForm.style.display = \"block\";\n document.getElementById(\"create-topic\").value = \"\";\n document.getElementById(\"create-description\").value = \"\";\n formType = \"addTopic\";\n}",
"function switchMainTo(functId){\n \n if(!createFunct[functId] && functId != \"welcome_note\")\n return;\n $(\"#\"+activeMainId).hide();\n activeMainId=functId+\"_main\";\n if($(\"#\"+functId+\"_main\").length>0)\n $(\"#\"+functId+\"_main\").show();\n else\n createFunct[functId]();\n}",
"function displayHelpMsg(msg) {\n\tExt.getCmp('helpIframe').el.update(msg);\n}",
"function openQuickPanel(courseID) {\n\t\t\t$rootScope.$broadcast('course-selected', courseID);\n\t\t\t$mdSidenav('quick-panel').toggle();\n\t\t}",
"function buildTopicsList() {\n var topicsList = $('<div id=\"tutorial-topic\" class=\"topicsList hideFloating\"></div>');\n\n var topicsHeader = $('<div class=\"topicsHeader\"></div>');\n topicsHeader.append($('<h2 class=\"tutorialTitle\">' + titleText + '</h2>'));\n var topicsCloser = $('<div class=\"paneCloser\"></div>');\n topicsCloser.on('click', hideFloatingTopics);\n topicsHeader.append(topicsCloser);\n topicsList.append(topicsHeader);\n\n $('#doc-metadata').appendTo(topicsList);\n\n resetSectionVisibilityList();\n\n var topicsDOM = $('.section.level2');\n topicsDOM.each( function(topicIndex, topicElement) {\n\n var topic = {};\n topic.id = $(topicElement).attr('id');\n topic.exercisesCompleted = 0;\n topic.sectionsCompleted = 0;\n topic.sectionsSkipped = 0;\n topic.topicCompleted = false; // only relevant if topic has 0 exercises\n topic.jqElement = topicElement;\n topic.jqTitleElement = $(topicElement).children('h2')[0];\n topic.titleText = topic.jqTitleElement.innerText;\n var progressiveAttr = $(topicElement).attr('data-progressive');\n if (typeof progressiveAttr !== typeof undefined && progressiveAttr !== false) {\n topic.progressiveReveal = (progressiveAttr == 'true' || progressiveAttr == 'TRUE');\n }\n else {\n topic.progressiveReveal = docProgressiveReveal;\n }\n\n jqTopic = $('<div class=\"topic\" index=\"' + topicIndex + '\">' + topic.titleText + '</div>');\n jqTopic.on('click', handleTopicClick);\n topic.jqListElement = jqTopic;\n $(topicsList).append(jqTopic);\n\n var topicActions = $('<div class=\"topicActions\"></div>');\n if (topicIndex > 0) {\n var prevButton = $('<button class=\"btn btn-default\">Previous Topic</button>');\n prevButton.on('click', handlePreviousTopicClick);\n topicActions.append(prevButton);\n }\n if (topicIndex < topicsDOM.length - 1) {\n var nextButton = $('<button class=\"btn btn-primary\">Next Topic</button>');\n nextButton.on('click', handleNextTopicClick);\n topicActions.append(nextButton);\n }\n $(topicElement).append(topicActions);\n\n $(topicElement).on('shown', function() {\n // Some the topic can have the shown event triggered but not actually\n // be visible. This visibility check saves a little effort when it's\n // not actually visible.\n if ($(this).is(\":visible\")) {\n var sectionsDOM = $(topicElement).children('.section.level3');\n sectionsDOM.each( function(sectionIndex, sectionElement) {\n updateSectionVisibility(sectionElement);\n })\n }\n });\n\n $(topicElement).on('hidden', function() {\n var sectionsDOM = $(topicElement).children('.section.level3');\n sectionsDOM.each( function(sectionIndex, sectionElement) {\n updateSectionVisibility(sectionElement);\n })\n });\n\n topic.sections = [];\n var sectionsDOM = $(topicElement).children('.section.level3');\n sectionsDOM.each( function( sectionIndex, sectionElement) {\n\n if (topic.progressiveReveal) {\n var continueButton = $(\n '<button class=\"btn btn-default skip\" id=\"' +\n 'continuebutton-' + sectionElement.id +\n '\" data-section-id=\"' + sectionElement.id + '\">Continue</button>'\n );\n continueButton.data('n_clicks', 0);\n continueButton.on('click', handleSkipClick);\n var actions = $('<div class=\"exerciseActions\"></div>');\n actions.append(continueButton);\n $(sectionElement).append(actions);\n }\n\n $(sectionElement).on('shown', function() {\n // A 'shown' event can be triggered even when this section isn't\n // actually visible. This can happen when the parent topic isn't\n // visible. So we have to check that this section actually is\n // visible.\n updateSectionVisibility(sectionElement);\n });\n\n $(sectionElement).on('hidden', function() {\n updateSectionVisibility(sectionElement);\n });\n\n var section = {};\n section.exercises = [];\n var exercisesDOM = $(sectionElement).children('.tutorial-exercise');\n exercisesDOM.each(function(exerciseIndex, exerciseElement) {\n var exercise = {};\n exercise.dataLabel = $(exerciseElement).attr('data-label');\n exercise.completed = false;\n exercise.jqElement = exerciseElement;\n section.exercises.push(exercise);\n });\n\n var allowSkipAttr = $(sectionElement).attr('data-allow-skip');\n var sectionAllowSkip = docAllowSkip;\n if (typeof allowSkipAttr !== typeof undefined && allowSkipAttr !== false) {\n sectionAllowSkip = (allowSkipAttr == 'true' || allowSkipAttr == 'TRUE');\n }\n\n section.id = sectionElement.id;\n section.completed = false;\n section.allowSkip = sectionAllowSkip;\n section.skipped = false;\n section.jqElement = sectionElement;\n topic.sections.push(section);\n\n });\n\n topics.push(topic);\n });\n\n var topicsFooter = $('<div class=\"topicsFooter\"></div>');\n\n var resetButton = $('<span class=\"resetButton\">Start Over</span>');\n resetButton.on('click', function() {\n bootbox.confirm(\"Are you sure you want to start over? (all exercise progress will be reset)\",\n function(result) {\n if (result)\n tutorial.startOver();\n });\n });\n topicsFooter.append(resetButton);\n topicsList.append(topicsFooter);\n\n return topicsList;\n\n }",
"function Discussion(props) {\n return (\n <div className={classes.discussion}>\n <Button size=\"small\" variant=\"outlined\" className={props.topic === 'Nature' ? classes.nature : props.topic === 'Request' ? classes.request : props.topic === 'Walking' ? classes.walking : props.topic === 'Photo' ? classes.photo : props.topic === 'Hint' ? classes.hint : classes.hint}> </Button>\n <div className={classes.disctext}>\n <Link to={`/map?lat=${props.lat}&lng=${props.lng}&discId=${props.id}`} style={{color:\"black\"}}>\n {props.title}\n </Link>\n </div>\n\n <div className={classes.package}>\n <div className={classes.ratingNumber} style={{ fontSize: 25 }}>\n {props.votes}\n </div>\n <div className={classes.deletedisc}>\n <DeleteIcon onClick={e => removeDiscussion(props.id)} />\n </div>\n </div>\n </div>\n\n );\n }",
"function hidePopup() {\n // get the container which holds the variables\n var topicframe = findFrame(top, 'topic');\n\n if (topicframe != null) {\n if (topicframe.openedpopup != 1) {\n if ((topicframe.openpopupid != '') && (topicframe.popupdocument != null)) {\n var elmt = topicframe.popupdocument.getElementById(topicframe.openpopupid);\n if (elmt != null) {\n elmt.style.visibility = 'hidden';\n }\n openpopupid = '';\n }\n }\n\n openedpopup = 0;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
overview image click handler | function overviewImgClick(e){
var i,j,tname,turl,item,c,li,
target = e.target || e.srcElement,
type = default_types_1,
premium;
turl = target.u;
//디폴트 타입에서 필요 li 검색
for (i = 0; i < type.length; i++) {
tname = type[i].n;
if (tname === turl) {
item = type[i];
break;
}
}
if (!item)
return;
// click 된 overview Image Name을 가지고 온다.
item.imgName = target.childNodes[0].innerHTML;
item.over = true;
activeMainLi(item, false);
} | [
"function imageClicked() {\n var currentSource = $(this).attr('src');\n var altSource = $(this).attr('data-src');\n $(this).attr('src', altSource);\n $(this).attr('data-src', currentSource);\n }",
"function menuImageClick() {\n Data.Edit.Mode = EditModes.Image;\n updateMenu();\n}",
"function clickPictures(){\r\n\tvar clickedElement = event.target;\r\n\r\n\tif (clickedElement.tagName === \"IMG\") {\r\n\tmagnifiedImage.src = clickedElement.src; //puts the clicked image into the image source\r\n\t}\t\r\n}",
"function imageLoadedHandler(evt) {\n this.addEventListener('click',function(evt){\n window.open(this.getAttribute('src'),'_blank');\n });\n }",
"onLayerClick() {}",
"function showImage(event) {\n\tresetClassNames(); // Klasu \"selected\" treba da ima onaj link cija je slika trenutno prikazana u \"mainImage\" elementu.\n\t\t\t\t\t // Pre stavljanja ove klase na kliknuti link, treba da sklonimo tu klasu sa prethodno kliknutog linka. To onda\n\t\t\t\t\t // postizemo tako sto sklonimo sve klase sa svih linkova, i time smo sigurni da ce i klasa \"selected\" biti uklonjena.\n\tthis.className = \"selected\"; // Stavljamo klasu \"selected\" na kliknuti link.\n\tmainImage.setAttribute(\"src\", this.getAttribute(\"href\")); // Atribut \"src\" elementa \"mainImage\" menjamo tako da postane jednak \"href\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // atributu kliknutog linka. A kako se u \"href\" atributu linka nalazi putanja\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // ka slici, postavljanjem \"src\" atributa na tu putanju, unutar elementa\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // \"mainImage\" ce se prikazati slika iz linka na koji se kliknulo.\n\tevent.preventDefault(); // Na ovaj nacin sprecavamo defoltno ponasanje browser-a, kojim bi se slika iz linka otvorila zasebno.\n\tscale = 1; // Nakon promene slike treba da vratimo zoom nivo na 1, da novoprikazana slika ne bi bila zumirana.\n\tsetScale(); // Kako smo u liniji iznad promenili vrednost \"scale\" globalne promenljive, potrebno je pozvati funkciju \"setScale\", koja onda\n\t\t\t\t// uzima vrednost promenljive \"scale\" i integrise je u CSS.\n\tleftPos = 0; // Nakon promene slike treba da vratimo sliku u inicijalnu poziciju.\n\tsetPosition(); // Kako smo u liniji iznad promenili vrednost \"leftPos\" globalne promenljive, potrebno je pozvati funkciju \"setPosition\"\n\t\t\t\t // koja onda uzima vrednost promenljive \"leftPos\" i integrise je u CSS.\n}",
"function previewEvents()\n\t{\n\t\tvar current = jQuery(s_selector).find('.item.current');\n\t\tvar node_id = current.attr('node');\n\t\t\n\t\tif (data[node_id] && !data[node_id].video && data[node_id].b_img)\n\t\t{\n\t\t\tjQuery(p_selector).find('img.preview').css('cursor', 'pointer').click(function(event) {\n\t\t\t\tevent = event || window.event;\n\t\t\t\tvar node = event.target || event.srcElement;\n\t\t\t\t\n\t\t\t\tonShowFullImage(node);\n\t\t\t});\n\t\t}\n\t}",
"function setClickHandler(correctCategory,imageCategories) {\n $('#guessOverview').children().click(function (event) {\n buildCategories(event.target.id, correctCategory, imageCategories)\n })\n\n}",
"function PreviewImagesEvent() {\n \n let imagesPreview = document.querySelectorAll('.images-preview > img')\n \n imagesPreview.forEach((img, index) => {\n img.setAttribute('data-index', index)\n\n img.addEventListener('click', event => {\n ContainerImgs.innerHTML = `\n <div class=\"arrow-left arrow-in-main-left\" data-link-on></div>\n <img src=\"${event.target.src}\" data-index=\"${index} \" >\n <div class=\"arrow-right arrow-in-main-right\" data-link-on></div>\n `;\n \n x()\n s()\n \n })\n\n })\n\n }",
"async __detailsButtonClicked(event) {\n try {\n if(!this.$.detailsBtn.classList.contains('entry')) { return; }\n await this.clicked();\n if (!this._cardImg) {\n this._cardImg = this.select('#img', this.$.img);\n } \n const {x, y} = event;\n const image = this._cardImg.getBoundingClientRect(); \n const card = this.$.controls.addSelectedToCard();\n\n this.fire('open-overlay', {\n card,\n id: 'cardDetails',\n image, \n x, \n y, \n isBuylist: this.isBuylist, \n buylistRules: this.buylistRules\n });\n }\n catch (error) {\n if (error === 'click debounced') { return; }\n console.error(error);\n }\n }",
"viewWasClicked (view) {\n\t\t\n\t}",
"function open_overview() {\n\ton_overview=true;\n\toverview_curslide=curslide;\n\t// Add the overlay to blur the background\n\tdocument.body.insertAdjacentHTML('afterbegin','<div id=\"coverlayer\"></div>');\n\tdocument.getElementById('coverlayer').style.opacity='1';\n\tlet slideo=getSlide(curslide);\n\tlet oldpos=slideo.getBoundingClientRect(); // Remember the position of the current slide\n\t// Wrap all slides in new divs to put them in a flexbox layout, and make them thumbnails\n\tfor (let slide of slides) {\n\t\tlet element=document.getElementById(slide['id']);\n\t\tif (element.classList.contains('thumbnail')) continue;\n\t\telement.classList.add('thumbnail');\n\t\tlet wrapper=document.createElement('div');\n\t\twrapper.classList.add('wthumb');\n\t\telement.parentNode.appendChild(wrapper);\n\t\twrapper.appendChild(element);\n\t\twrapper.addEventListener('click',function() {\n\t\t\tclose_overview(getSlideIndex(element.id));\n\t\t});\n\t}\n\tlet nwrapper=document.createElement('div');\n\tnwrapper.id='thumblayer';\n\tlet firstdiv=document.querySelector('body div.wthumb');\n\tfirstdiv.parentNode.insertBefore(nwrapper,firstdiv);\n\tdocument.querySelectorAll('body div.wthumb').forEach(function(element) {\n\t\tnwrapper.appendChild(element);\n\t});\n\tif (slideo.id!='outline') {\n\t\tlet wrapper=slideo.parentNode;\n\t\t// Scroll the overview div so that the current slide is visible\n\t\tlet tl=document.getElementById('thumblayer');\n\t\ttl.scrollTop=tl.offsetTop+wrapper.offsetTop;\n\t\twrapper.style.zIndex='30';\n\t\tlet newpos=wrapper.getBoundingClientRect();\t// Remember the new position of the current slide\n\t\tlet deltal=newpos.left-oldpos.left;\n\t\tlet deltat=newpos.top-oldpos.top;\n\t\tlet deltaw=newpos.width/oldpos.width-1;\n\t\tlet deltah=newpos.height/oldpos.height-1;\n\t\t// Put back the current slide at its original position\n\t\tslideo.classList.remove('thumbnail');\n\t\tslideo.style.position='fixed';\n\t\tslideo.style.transformOrigin='left top';\n\t\tslideo.style.backgroundColor='white';\n\t\tslideo.style.visibility='visible';\n\t\tsetTimeout(function() {\n\t\t\tslideo.classList.add('overview-transition');\n\t\t\t// Animate the transition while blurring the background\n\t\t\tslideo.addEventListener('transitionend',function(event) {\n\t\t\t\tslideo.style.transform=null;\n\t\t\t\tslideo.style.position=null;\n\t\t\t\tslideo.style.transformOrigin=null;\n\t\t\t\tslideo.style.backgroundColor=null;\n\t\t\t\tslideo.style.visibility=null;\n\t\t\t\tslideo.classList.add('thumbnail');\n\t\t\t\tslideo.classList.remove('overview-transition');\n\t\t\t\twrapper.style.zIndex=null;\n\t\t\t},{capture:false,once:true});\n\t\t\tsetTimeout(function() {\n\t\t\t\tslideo.style.transform='translate('+newpos.left+'px, '+newpos.top+'px) scale('+(newpos.width/oldpos.width)+', '+(newpos.height/oldpos.height)+')';\n\t\t\t\tgetSlide(overview_curslide).classList.add('targetted'); // Add a visual style to the targetted slide in the overview\n\t\t\t},20);\n\t\t},20);\n\t}\n}",
"function findImgId(e) {\n setPicId(e.target.id);\n handleShow();\n }",
"function createAdImageEvent(adImage,a_id,position, title) {\n adImage.addEventListener('click', function(e) {\n \t// double click prevention\n\t var currentTime = new Date();\n\t if (currentTime - clickTime < 1000) {\n\t return;\n\t };\n\t clickTime = currentTime; \n\t\tvar page = Alloy.createController(\"itemDetails\",{a_id:a_id,position:position, title:title}).getView(); \n\t \tpage.open();\n\t \tpage.animate({\n\t\t\tcurve: Ti.UI.ANIMATION_CURVE_EASE_IN,\n\t\t\topacity: 1,\n\t\t\tduration: 300\n\t\t});\n });\n}",
"function cardDetail() {\n\n $('.image').click((event) => {\n let id = event.target.id;\n window.location.hash = '#cardDetail/' + id;\n });\n}",
"function openImage() {\n window.open($(this).prop('src'));\n }",
"function maptab_click() {\n\t//get secondary img path from data attribute\n\tvar data = $(\".inner_container\").find(\"img\").attr(\"data-id\");\n\t//get primary (UK) img from src\n\tvar src = $(\".inner_container\").find(\"img\").attr(\"data\");\n\t//map tab event listener\n\t//Test which button was pressed\n\tif($(this).text() === \"UK\") {\n\t\t//set correct src attriube for map\n\t\t$(\".election_map\").attr(\"src\", src);\n\t\t//add and remove active id as required\n\t\t$(\".map_tabs tr:eq(0)\").attr(\"id\", \"active_tab\");\n\t\t$(\".map_tabs tr:eq(1)\").attr(\"id\", \"\");\n\t} else {\n\t\t$(\".election_map\").attr(\"src\", data);\n\t\t$(\".map_tabs tr:eq(1)\").attr(\"id\", \"active_tab\");\n\t\t$(\".map_tabs tr:eq(0)\").attr(\"id\", \"\");\n\t}\n}",
"function imagezIndex(){\n\tvar viewImage = Alloy.createController('imagezIndex', {}).getView();\n\tviewImage.open();\n}",
"function onClickVocabularyImg() {\n\t// Set flag\n\t$('#scenario_vocabulary').val('vocabulary');\n\n\tonOffAreaScenarioVocabulary(CLIENT.ONVOCABULARY);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the page size option is greater than total number of elements (users) disable it | function checkPageSizes() {
let pageSizesToShow = $('#pageSizesToShow').data('pagesizestoshow');
$("#pageSizeSelect option").each(function(i, option) {
if ($.inArray(parseInt(option.value), pageSizesToShow) === -1) {
option.disabled = true;
}
});
} | [
"function trkDisplayPagesNeeded() {\n for(i = 0; i < (trkPagination.length); i++) {\n var loopCurrentPageValue = trkPagination[i].attributes.value.value;\n if(loopCurrentPageValue <= trkNumberOfPagesNeeded) {\n trkPagination[i].style.display = \"flex\";\n } else {\n trkPagination[i].style.display = \"none\";\n }\n }\n}",
"togglePaginationButtons() {\r\n let previousPageNum = this.state.currentPages[0];\r\n let nextPageNum = this.state.currentPages[2];\r\n if (previousPageNum != 0) {\r\n this.setState({disablePrev: false, disableFirst: false});\r\n } else {\r\n this.setState({disablePrev: true, disableFirst: true});\r\n }\r\n if (nextPageNum <= this.state.dataCount && nextPageNum > 1) {\r\n this.setState({disableNext: false, disableLast: false});\r\n } else {\r\n this.setState({disableNext: true, disableLast: true});\r\n }\r\n }",
"function DisallowFieldsPageNext(button_state){\n document.getElementById('fields_next_page').disabled = button_state;\n}",
"perPage(n = 15) {\n return this.addOption('perPage', n);\n }",
"function DisallowRecordsPageNext(button_state){\n document.getElementById('records_next_page').disabled = button_state;\n}",
"_addEllipsisPage () {\n this._addPageNumber(null)\n }",
"set pageSize(size) {\n this._pageSize = size;\n }",
"disabled(action)\n\t{\n\t\tswitch(action)\n\t\t{\n\t\t\tcase 'next':return this.props.currentPage+1>this.pageCount()?true:false;\n\t\t\tcase 'previous':return this.props.currentPage-1<=0?true:false;\n\t\t\tdefault:return true;\n\t\t}\n\t}",
"function disableSizeSlider(){\r\n document.querySelector(\"#arr_sz\").disabled = true;\r\n}",
"function DisallowFieldsPagePrevious(button_state){\n document.getElementById('fields_previous_page').disabled = button_state;\n}",
"function DisallowRecordsPagePrevious(button_state){\n document.getElementById('records_previous_page').disabled = button_state;\n}",
"function trkUpdateNumberOfPagesNeeded() {\n trkFilteredProducts = document.getElementsByClassName(trkDropdownValue);\n trkFilteredProductsAmount = trkFilteredProducts.length;\n trkNumberOfPagesNeeded = Math.ceil(trkFilteredProductsAmount / 12);\n console.log(\"Number of pages needed: \" + trkNumberOfPagesNeeded);\n}",
"_applyLimit() {\n if (!this._page.limit) {\n return;\n }\n var offset;\n if (this._page.offset) {\n offset = this._page.offset;\n } else {\n var page = this._page.page ? this._page.page : 1;\n offset = (page - 1) * this._page.limit;\n }\n this.statement().limit(this._page.limit, offset);\n }",
"paginate({ unlimited = false } = {}) {\r\n const { page: qPage, limit: qLimit, skip: qskip } = this.queryObj;\r\n\r\n const page = qPage * 1 || 1;\r\n let limit = unlimited ? undefined : defaultRecordPerQuery;\r\n if (qLimit)\r\n limit = qLimit * 1 > maxRecordsPerQuery ? maxRecordsPerQuery : qLimit * 1;\r\n const skip = qskip\r\n ? qskip * 1\r\n : (page - 1) * (limit || defaultRecordPerQuery);\r\n\r\n this.query.skip = skip;\r\n this.query.take = limit;\r\n return this;\r\n }",
"get not() {\n return {\n /**\n * Waits for all PageElements managed by PageElementMap not to exist.\n *\n * Throws an error if the condition is not met within a specific timeout.\n *\n * @param opts includes a `filterMask` which can be used to skip the invocation of the `exists` function for\n * some or all managed PageElements and the `timeout` within which the condition is expected to be met\n *\n * If no `timeout` is specified, a PageElement's default timeout is used.\n *\n * @returns this (an instance of PageElementMap)\n */\n exists: (opts = {}) => {\n const { filterMask } = opts, otherOpts = __rest(opts, [\"filterMask\"]);\n return this._node.eachWait(this._node.$, element => element.wait.not.exists(otherOpts), filterMask, true);\n },\n /**\n * Waits for all PageElements managed by PageElementMap not to be visible.\n *\n * Throws an error if the condition is not met within a specific timeout.\n *\n * @param opts includes a `filterMask` which can be used to skip the invocation of the `isVisible` function for\n * some or all managed PageElements and the `timeout` within which the condition is expected to be met\n *\n * If no `timeout` is specified, a PageElement's default timeout is used.\n *\n * @returns this (an instance of PageElementMap)\n */\n isVisible: (opts = {}) => {\n const { filterMask } = opts, otherOpts = __rest(opts, [\"filterMask\"]);\n return this._node.eachWait(this._node.$, element => element.wait.not.isVisible(otherOpts), filterMask, true);\n },\n /**\n * Waits for all PageElements managed by PageElementMap not to be enabled.\n *\n * Throws an error if the condition is not met within a specific timeout.\n *\n * @param opts includes a `filterMask` which can be used to skip the invocation of the `isEnabled` function for\n * some or all managed PageElements and the `timeout` within which the condition is expected to be met\n *\n * If no `timeout` is specified, a PageElement's default timeout is used.\n *\n * @returns this (an instance of PageElementMap)\n */\n isEnabled: (opts = {}) => {\n const { filterMask } = opts, otherOpts = __rest(opts, [\"filterMask\"]);\n return this._node.eachWait(this._node.$, element => element.wait.not.isEnabled(otherOpts), filterMask, true);\n },\n /**\n * Waits for the actual texts of all PageElements managed by PageElementMap not to equal the expected texts.\n *\n * Throws an error if the condition is not met within a specific timeout.\n *\n * @param texts the expected texts supposed not to equal the actual texts\n * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used\n * to check it\n *\n * If no `timeout` is specified, a PageElement's default timeout is used.\n * If no `interval` is specified, a PageElement's default interval is used.\n *\n * @returns this (an instance of PageElementMap)\n */\n hasText: (texts, opts) => {\n return this._node.eachWait(this._node.$, (element, expected) => element.wait.not.hasText(expected, opts), texts);\n },\n /**\n * Waits for all PageElements managed by PageElementMap not to have any text.\n *\n * Throws an error if the condition is not met within a specific timeout.\n *\n * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyText` function for\n * some or all managed PageElements, the `timeout` within which the condition is expected to be met and the\n * `interval` used to check it\n *\n * If no `timeout` is specified, a PageElement's default timeout is used.\n * If no `interval` is specified, a PageElement's default interval is used.\n *\n * @returns this (an instance of PageElementMap)\n */\n hasAnyText: (opts = {}) => {\n const { filterMask } = opts, otherOpts = __rest(opts, [\"filterMask\"]);\n return this._node.eachWait(this._node.$, (element) => element.wait.not.hasAnyText(otherOpts), filterMask, true);\n },\n /**\n * Waits for the actual texts of all PageElements managed by PageElementMap not to contain the expected texts.\n *\n * Throws an error if the condition is not met within a specific timeout.\n *\n * @param texts the expected texts supposed not to be contained in the actual texts\n * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used\n * to check it\n *\n * If no `timeout` is specified, a PageElement's default timeout is used.\n * If no `interval` is specified, a PageElement's default interval is used.\n *\n * @returns this (an instance of PageElementMap)\n */\n containsText: (texts, opts) => {\n return this._node.eachWait(this._node.$, (element, expected) => element.wait.not.containsText(expected, opts), texts);\n },\n /**\n * Waits for the actual direct texts of all PageElements managed by PageElementMap not to equal the expected\n * direct texts.\n *\n * Throws an error if the condition is not met within a specific timeout.\n *\n * A direct text is a text that resides on the level directly below the selected HTML element.\n * It does not include any text of the HTML element's nested children HTML elements.\n *\n * @param directTexts the expected direct texts not supposed to equal the actual direct texts\n * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used\n * to check it\n *\n * If no `timeout` is specified, a PageElement's default timeout is used.\n * If no `interval` is specified, a PageElement's default interval is used.\n *\n * @returns this (an instance of PageElementMap)\n */\n hasDirectText: (directTexts, opts) => {\n return this._node.eachWait(this._node.$, (element, expected) => element.wait.not.hasDirectText(expected, opts), directTexts);\n },\n /**\n * Waits for all PageElements managed by PageElementMap not to have any direct text.\n *\n * Throws an error if the condition is not met within a specific timeout.\n *\n * A direct text is a text that resides on the level directly below the selected HTML element.\n * It does not include any text of the HTML element's nested children HTML elements.\n *\n * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyDirectText` function\n * for some or all managed PageElements, the `timeout` within which the condition is expected to be met and the\n * `interval` used to check it\n *\n * If no `timeout` is specified, a PageElement's default timeout is used.\n * If no `interval` is specified, a PageElement's default interval is used.\n *\n * @returns this (an instance of PageElementMap)\n */\n hasAnyDirectText: (opts = {}) => {\n const { filterMask } = opts, otherOpts = __rest(opts, [\"filterMask\"]);\n return this._node.eachWait(this._node.$, (element) => element.wait.not.hasAnyDirectText(otherOpts), filterMask, true);\n },\n /**\n * Waits for the actual direct texts of all PageElements managed by PageElementMap not to contain the expected\n * direct texts.\n *\n * Throws an error if the condition is not met within a specific timeout.\n *\n * A direct text is a text that resides on the level directly below the selected HTML element.\n * It does not include any text of the HTML element's nested children HTML elements.\n *\n * @param directTexts the expected direct texts supposed not to be contained in the actual direct texts\n * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used\n * to check it\n *\n * If no `timeout` is specified, a PageElement's default timeout is used.\n * If no `interval` is specified, a PageElement's default interval is used.\n *\n * @returns this (an instance of PageElementMap)\n */\n containsDirectText: (directTexts, opts) => {\n return this._node.eachWait(this._node.$, (element, expected) => element.wait.not.containsDirectText(expected, opts), directTexts);\n },\n };\n }",
"function switchPageStatus() {\n if(currPageNo === 1)\n $(\"div#pagination>ul>li#firstPage\").addClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#firstPage\").removeClass(\"disabled\");\n if(currPageNo > 1)\n $(\"div#pagination>ul>li#prevPage\").removeClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#prevPage\").addClass(\"disabled\");\n if(currPageNo < currMaxPage)\n $(\"div#pagination>ul>li#nextPage\").removeClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#nextPage\").addClass(\"disabled\");\n if(currPageNo === currMaxPage)\n $(\"div#pagination>ul>li#lastPage\").addClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#lastPage\").removeClass(\"disabled\");\n }",
"function trkCheckPageOne() {\n if(trkPagination[1].style.display == \"none\") {\n trkPagination[0].style.display = \"none\";\n } else {\n trkPagination[0].style.display = \"flex\";\n }\n}",
"get not() {\n return {\n /**\n * Returns true if all PageElements managed by PageElementMap currently do not exist.\n *\n * @param filterMask can be used to skip the invocation of the `exists` function for some or all managed\n * PageElements\n */\n exists: (filterMask) => {\n return this._node.eachCheck(this._node.$, element => element.currently.not.exists(), filterMask, true);\n },\n /**\n * Returns true if all PageElements managed by PageElementMap are currently not visible.\n *\n * @param filterMask can be used to skip the invocation of the `isVisible` function for some or all managed\n * PageElements\n */\n isVisible: (filterMask) => {\n return this._node.eachCheck(this._node.$, element => element.currently.not.isVisible(), filterMask, true);\n },\n /**\n * Returns true if all PageElements managed by PageElementMap are currently not enabled.\n *\n * @param filterMask can be used to skip the invocation of the `isEnabled` function for some or all managed\n * PageElements\n */\n isEnabled: (filterMask) => {\n return this._node.eachCheck(this._node.$, element => element.currently.not.isEnabled(), filterMask, true);\n },\n /**\n * Returns true if the actual texts of all PageElements managed by PageElementMap currently do not equal the\n * expected texts.\n *\n * @param texts the expected texts supposed not to equal the actual texts\n */\n hasText: (text) => {\n return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.hasText(expected), text);\n },\n /**\n * Returns true if all PageElements managed by PageElementMap currently do not have any text.\n *\n * @param filterMask can be used to skip the invocation of the `hasAnyText` function for some or all managed\n * PageElements\n */\n hasAnyText: (filterMask) => {\n return this._node.eachCheck(this._node.$, (element) => element.currently.not.hasAnyText(), filterMask, true);\n },\n /**\n * Returns true if the actual texts of all PageElements managed by PageElementMap currently do not contain the\n * expected texts.\n *\n * @param texts the expected texts supposed not to be contained in the actual texts\n */\n containsText: (text) => {\n return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.containsText(expected), text);\n },\n /**\n * Returns true if the actual direct texts of all PageElements managed by PageElementMap currently do not equal\n * the expected direct texts.\n *\n * A direct text is a text that resides on the level directly below the selected HTML element.\n * It does not include any text of the HTML element's nested children HTML elements.\n *\n * @param directTexts the expected direct texts supposed not to equal the actual direct texts\n */\n hasDirectText: (directText) => {\n return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.hasDirectText(expected), directText);\n },\n /**\n * Returns true if all PageElements managed by PageElementMap currently do not have any direct text.\n *\n * A direct text is a text that resides on the level directly below the selected HTML element.\n * It does not include any text of the HTML element's nested children HTML elements.\n *\n * @param filterMask can be used to skip the invocation of the `hasAnyDirectText` function for some or all managed\n * PageElements\n */\n hasAnyDirectText: (filterMask) => {\n return this._node.eachCheck(this._node.$, (element) => element.currently.not.hasAnyDirectText(), filterMask, true);\n },\n /**\n * Returns true if the actual direct texts of all PageElements managed by PageElementMap currently do not contain\n * the expected direct texts.\n *\n * A direct text is a text that resides on the level directly below the selected HTML element.\n * It does not include any text of the HTML element's nested children HTML elements.\n *\n * @param directTexts the expected direct texts supposed not to be contained in the actual direct texts\n */\n containsDirectText: (directText) => {\n return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.containsDirectText(expected), directText);\n },\n };\n }",
"function needSplitPageForPlan()//page 5 split page base on rider\n{\n \n \n isNeedSplit = \"NO\";//split data\n appendPage('page5','PDS/pds2HTML/PDSTwo_ENG_Page5.html');\n isNeedSplit = \"YES\";\n appendPage('page5b','PDS/pds2HTML/PDSTwo_ENG_Page5b.html');\n loadInterfacePage();//to check to hide some division\n \n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the root stack resource for the current stack deployment | function getStackResource() {
const { stackResource } = exports.getStore();
return stackResource;
} | [
"get resourceStack() {\n const actionResource = this.actionProperties.resource;\n if (!actionResource) {\n return undefined;\n }\n const actionResourceStack = core_1.Stack.of(actionResource);\n const actionResourceStackEnv = {\n region: actionResourceStack.region,\n account: actionResourceStack.account,\n };\n return sameEnv(actionResource.env, actionResourceStackEnv) ? actionResourceStack : undefined;\n }",
"function getStack() {\n return settings.getStack();\n}",
"function root() {\n return _root; \n }",
"async function getResourceStackAssociation() {\n templates = {};\n\n await sdkcall(\"CloudFormation\", \"listStacks\", {\n StackStatusFilter: [\"CREATE_COMPLETE\", \"ROLLBACK_IN_PROGRESS\", \"ROLLBACK_FAILED\", \"ROLLBACK_COMPLETE\", \"DELETE_FAILED\", \"UPDATE_IN_PROGRESS\", \"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS\", \"UPDATE_COMPLETE\", \"UPDATE_ROLLBACK_IN_PROGRESS\", \"UPDATE_ROLLBACK_FAILED\", \"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS\", \"UPDATE_ROLLBACK_COMPLETE\"]\n }, true).then(async (data) => {\n await Promise.all(data.StackSummaries.map(async (stack) => {\n await sdkcall(\"CloudFormation\", \"getTemplate\", {\n StackName: stack.StackId,\n TemplateStage: \"Processed\"\n }, true).then((data) => {\n template = null;\n try {\n template = JSON.parse(data.TemplateBody);\n templates[stack.StackName] = template;\n } catch(err) {\n console.log(\"Couldn't parse\"); // TODO: yaml 2 json\n }\n });\n }));\n });\n\n console.log(templates);\n}",
"function setRootResource(res) {\n return __awaiter(this, void 0, void 0, function* () {\n const engineRef = getEngine();\n if (!engineRef) {\n return Promise.resolve();\n }\n // Back-compat case - Try to set the root URN for SxS old SDKs that expect the engine to roundtrip the\n // stack URN.\n const req = new engproto.SetRootResourceRequest();\n const urn = yield res.urn.promise();\n req.setUrn(urn);\n return new Promise((resolve, reject) => {\n engineRef.setRootResource(req, (err, resp) => {\n // Back-compat case - if the engine we're speaking to isn't aware that it can save and load root\n // resources, just ignore there's nothing we can do.\n if (err && err.code === grpc.status.UNIMPLEMENTED) {\n return resolve();\n }\n if (err) {\n return reject(err);\n }\n return resolve();\n });\n });\n });\n}",
"static async getStackInfo(stackName) {\n var client = new AWS.CloudFormation();\n var stacks = await client.describeStacks({ StackName: stackName }).promise();\n return stacks['Stacks'][0];\n }",
"get rootWeb() {\n return Web(this, \"rootweb\");\n }",
"function first() {\n return _navigationStack[0];\n }",
"getWorkspaceRootId(success, fail) {\n const token = this.get('tokenHandler').getWholeTaleAuthToken();\n const path = '/collection/WholeTale Workspaces/WholeTale Workspaces';\n let url = `${config.apiUrl}/resource/lookup?path=${path}&test=false`;\n\n let client = new XMLHttpRequest();\n client.open('GET', url);\n client.setRequestHeader(\"Girder-Token\", token);\n client.addEventListener(\"load\", () => {\n if (client.status === 200) {\n const workspacesRoot = JSON.parse(client.responseText);\n success(workspacesRoot._id);\n } else {\n fail(client.responseText);\n }\n });\n client.addEventListener(\"error\", fail);\n client.send();\n }",
"getStackByName(stackName) {\n const artifacts = this.artifacts.filter(a => a instanceof cloudformation_artifact_1.CloudFormationStackArtifact && a.stackName === stackName);\n if (!artifacts || artifacts.length === 0) {\n throw new Error(`Unable to find stack with stack name \"${stackName}\"`);\n }\n if (artifacts.length > 1) {\n // eslint-disable-next-line max-len\n throw new Error(`There are multiple stacks with the stack name \"${stackName}\" (${artifacts.map(a => a.id).join(',')}). Use \"getStackArtifact(id)\" instead`);\n }\n return artifacts[0];\n }",
"function currentKubernetesNamespace() {\n var injector = HawtioCore.injector;\n if (injector) {\n var KubernetesState = injector.get(\"KubernetesState\") || {};\n return KubernetesState.selectedNamespace || Kubernetes.defaultNamespace;\n }\n return Kubernetes.defaultNamespace;\n }",
"function GetRack() {\r\n GetRackWithName(getUrlParameter('id')) ;\r\n}",
"async getRootWeb() {\n const web = await this.rootWeb.select(\"Url\")();\n return Web([this, web.Url]);\n }",
"exportStack() {\n return this.stack.exportStack();\n }",
"getStackArtifact(artifactId) {\n const artifact = this.tryGetArtifactRecursively(artifactId);\n if (!artifact) {\n throw new Error(`Unable to find artifact with id \"${artifactId}\"`);\n }\n if (!(artifact instanceof cloudformation_artifact_1.CloudFormationStackArtifact)) {\n throw new Error(`Artifact ${artifactId} is not a CloudFormation stack`);\n }\n return artifact;\n }",
"function getSiteRoot() {\r\n\tvar url = window.location.protocol + '//' + window.location.host,\r\n\t\tpath = '/Site';\r\n\tif (window.location.pathname.indexOf(path) == 0) {\r\n\t\turl += path\r\n\t}\r\n\treturn url + '/';\r\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 getBranch() {\n return new baseService()\n .setPath('ray', '/company/branch/' + vm.currentBranch)\n .execute()\n .then(function (res) {\n vm.branchName = res.name;\n });\n }",
"function internal_getContainerPath(resourcePath) {\n const resourcePathWithoutTrailingSlash = resourcePath.substring(resourcePath.length - 1) === \"/\"\n ? resourcePath.substring(0, resourcePath.length - 1)\n : resourcePath;\n const containerPath = resourcePath.substring(0, resourcePathWithoutTrailingSlash.lastIndexOf(\"/\")) + \"/\";\n return containerPath;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
looks for duplicate decimals in arr, doesn't allow second decimal | function checkForDecimal(arr) {
return arr.length === new Set(arr).size;
} | [
"function isAvgWhole(arr) {\n\tlet a = 0;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\ta += arr[i];\n\t}\n\t\n\treturn Number.isInteger(a / arr.length);\n}",
"function testcase() {\n var a = new Array(1,2,1);\n if (a.lastIndexOf(2,1.49) === 1 && // 1.49 resolves to 1\n a.lastIndexOf(2,0.51) === -1 && // 0.51 resolves to 0\n a.lastIndexOf(1,0.51) === 0){ // 0.51 resolves to 0\n return true;\n }\n }",
"function differentDigitsNumberSearch(inputArray) {\n let currentNumber;\n let hasUniqueDigits = false;\n \n for(let i = 0; i < inputArray.length; i++) {\n currentNumber = inputArray[i]+'';\n \n for(let digit of currentNumber) {\n if(currentNumber.indexOf(digit) === currentNumber.lastIndexOf(digit)) {\n hasUniqueDigits = true;\n } else {\n hasUniqueDigits = false;\n }\n }\n \n if(hasUniqueDigits) {\n return +currentNumber;\n }\n hasUniqueDigits = false;\n }\n return -1;\n}",
"function CheckFloat3decimal(resid) {\r\n var num = document.getElementById(resid).value;\r\n var tomatch = /^\\d*(\\.\\d{1,3})?$/;\r\n if (tomatch.test(num)) {\r\n return true;\r\n }\r\n else {\r\n alert(\"Input error\");\r\n\r\n document.getElementById(resid).value = \"\";\r\n document.getElementById(resid).focus();\r\n return false;\r\n }\r\n}",
"function checkIfFloat(value) {\r\n if (value.toString().indexOf('.', 0) > -1) {\r\n return parseFloat(value).toFixed(2);\r\n }\r\n else {\r\n return value;\r\n }\r\n}",
"function checkDecimal()\n{\n let re = /^([0-9]*|[0-9]*\\.[0-9]*)$/;\n let number = this.value.trim();\n setErrorFlag(this, re.test(number) && number > 0);\n}",
"function formatResult(num) {\n num = num.toString();\n\n let start = num.indexOf(\".\");\n if (start === -1) return +num;\n\n let repeatNum = num[start];\n let count = 0;\n\n for (let i = start; i < num.length; i++) {\n if (num[i] === repeatNum) {\n count++;\n if (count === 3) {\n return +num.slice(0, start + 2);\n }\n } else {\n start = i;\n repeatNum = num[i];\n count = 1;\n }\n }\n return +num;\n}",
"function sumFractions(arr) {\n\treturn Math.round(arr.map(x => (x[0] / x[1])).reduce((x, i) => x + i));\n}",
"checkForDuplicatesInArray(answersArr) {\n let ans1 = answersArr[0];\n let ans2 = answersArr[1];\n let ans3 = answersArr[2];\n\n if (ans2 === ans1) {\n answersArr[1] = parseInt((ans1 + 1), 10);\n }\n if (ans3 === ans2 || ans3 === ans1) {\n answersArr[2] = parseInt((ans2 + 2), 10);\n }\n\n console.log(`After checkForDuplicates: ${answersArr} | Type of a: ${typeof(answersArr[1])} - Type of b: ${typeof(answersArr[2])}`);\n }",
"function isAcceptableFloat(num) {\n const str = num.toString();\n return str.indexOf('.') === str.length - 2;\n}",
"function validQuantity(input) {\n return parseInt(input) > 0 && input.toString().indexOf(\".\") === -1;\n }",
"function isNumericArray(array) {\n var isal = true;\n for (var i = 0; i < array.length; i++) {\n if (!$.isNumeric(array[i])) {\n isal = false;\n }\n }\n return isal;\n }",
"function fix(inputArr) {\n for (let i = 0; i < inputArr.length; i++) {\n const element = inputArr[i];\n for (let j = i + 1; j < inputArr.length; j++) {\n const element2 = inputArr[j];\n if (element + element2 === 2020) {\n console.log(element * element2)\n }\n }\n }\n}",
"function w3_ext_param_array_match_num(arr, n, func)\n{\n var found = false;\n arr.forEach(function(a_el, i) {\n var a_num = parseFloat(a_el);\n //console.log('w3_ext_param_array_match_num CONSIDER '+ i +' '+ a_num +' '+ n);\n if (!found && a_num == n) {\n //console.log('w3_ext_param_array_match_num MATCH '+ i);\n if (func) func(i, n);\n found = true;\n }\n });\n return found;\n}",
"function expandDecimal(num) {\n return [...String(num)].reduce((acc, e, i) => {\n // If number is zero, ignore it.\n if (Number(e) === 0) return acc;\n\n // Compute the x/y fractional part.\n // <1>\n return [...acc, `${e}/${10 ** i * 10}`];\n }, [])\n .filter(isNotZero);\n}",
"function AcceptDecimal(str) {\n //http://lawrence.ecorp.net/inet/samples/regexp-validate2.php\n str = trim(str);\n var regDecimal = /^[-+]?[0-9]+(\\.[0-9]+)?$/;\n return regDecimal.test(str);\n}",
"function trickyDoubles(n){\n let strNum = n.toString();\n console.log(typeof strNum);\n \n if(strNum.length%2 === 0){\n let sliceLength = strNum.length/2;\n let firstPart = strNum.substr(0, sliceLength);\n let secondPart = strNum.substr(sliceLength, sliceLength);\n \n if(firstPart === secondPart){\n return Number(strNum);\n }\n }\n return strNum * 2;\n}",
"fixedStrings (array, digits = 4) {\n array = this.convertArray(array, Array) // Only Array stores strings.\n return array.map((n) => n.toFixed(digits))\n }",
"function formatDecimalOdds(odds) {\n\tlet updatedOdds = odds/1000;\n\treturn Number.parseFloat(updatedOdds).toFixed(2);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add walls to storage | addWalls(x, y) {
const dir = this.getNeighbours(x, y);
for (let i = 0; i < dir.length; i++) {
// Insert into data structure
this.walls.insert({
x: dir[i][0],
y: dir[i][1],
direction: dir[i][2]
});
}
} | [
"function makeWalls( worldPivot, spaceApart, left, up, right, down, material ) {\n\n\tvar object;\n\tvar box;\n\n\t// right\n\tif ( right ) {\n\n\t\tobject = new THREE.Mesh( new THREE.BoxBufferGeometry( spaceApart, WallLength, WallThickness, 4, 4, 4 ), material );\n\t\tobject.position.set( worldPivot.x, 50, worldPivot.z + spaceApart / 2 );\n\t\tscene.add( object );\n\t\twalls.push( object );\n\n\t\tbox = new THREE.Box3();\n\t\tbox.setFromObject( object );\n\t\twallColliders.push( box );\n\n\t}\n\n\t// up\n\tif ( up ) {\n\n\t\tobject = new THREE.Mesh( new THREE.BoxBufferGeometry( spaceApart, WallLength, WallThickness, 4, 4, 4 ), material );\n\t\tobject.position.set( worldPivot.x + spaceApart / 2, 50, worldPivot.z );\n\t\tobject.rotateY( THREE.Math.degToRad( 90 ) );\n\n\t\tscene.add( object );\n\t\twalls.push( object );\n\n\t\tbox = new THREE.Box3();\n\t\tbox.setFromObject( object );\n\t\twallColliders.push( box );\n\n\t}\n\n\t// left\n\tif ( left ) {\n\n\t\tobject = new THREE.Mesh( new THREE.BoxBufferGeometry( spaceApart, WallLength, WallThickness, 4, 4, 4 ), material );\n\t\tobject.position.set( worldPivot.x, 50, worldPivot.z - spaceApart / 2 );\n\t\tscene.add( object );\n\t\twalls.push( object );\n\n\t\tbox = new THREE.Box3();\n\t\tbox.setFromObject( object );\n\t\twallColliders.push( box );\n\n\t}\n\n\t// down\n\tif ( down ) {\n\n\t\tobject = new THREE.Mesh( new THREE.BoxBufferGeometry( spaceApart, WallLength, WallThickness, 4, 4, 4 ), material );\n\t\tobject.position.set( worldPivot.x - spaceApart / 2, 50, worldPivot.z );\n\t\tobject.rotateY( THREE.Math.degToRad( 90 ) );\n\t\tscene.add( object );\n\t\twalls.push( object );\n\n\t\tbox = new THREE.Box3();\n\t\tbox.setFromObject( object );\n\t\twallColliders.push( box );\n\n\t}\n\n}",
"function syncWalls() {\n\tfor (var w_index = 0; w_index < maze.width; w_index++) {\n\t\tfor (var h_index = 0; h_index < maze.height; h_index++) {\n\t\t\tif (w_index > 0 && maze.cells[w_index-1][h_index].right) {\n\t\t\t\tmaze.cells[w_index][h_index].left = generateWall(w_index*maze.cellWidth - maze.wallWidth/2, h_index*maze.cellHeight, w_index*maze.cellWidth + maze.wallWidth/2, (h_index+1)*maze.cellHeight);\n\t\t\t}\n\t\t\tif (h_index > 0 && maze.cells[w_index][h_index-1].bottom) {\n\t\t\t\tmaze.cells[w_index][h_index].top = generateWall(w_index*maze.cellWidth, h_index*maze.cellHeight - maze.wallWidth/2, (w_index+1)*maze.cellWidth, h_index*maze.cellHeight + maze.wallWidth/2);\n\t\t\t}\n\t\t}\n\t}\n}",
"function DemoWallAndTileManager( imageReader ) {\r\n\t\r\n\tthis.imageReader = imageReader;\r\n\r\n\tthis.catalogue = new Object();\r\n\tthis.catalogue.tiles = new Object();\r\n\tthis.catalogue.walls = new Object();\r\n\r\n\tthis.catalogue.tiles['B'] = new Tile( 64 , 32 , 'khaki' , 'black' , 0 , 32);\r\n\t\r\n\tthis.catalogue.walls['N'] = new Wall( 32 , 48 , this.gfx('wallNS_32x48.png') , this.gfx('wireWallNS_32x48.png') , 32 , 0); \r\n\tthis.catalogue.walls['E'] = new Wall( 32 , 48 , this.gfx('wallWE_32x48.png') , this.gfx('wireWallWE_32x48.png') , 32 , 16); \r\n\tthis.catalogue.walls['W'] = new Wall( 32 , 48 , this.gfx('wallWE_32x48.png') , this.gfx('wireWallWE_32x48.png') ); \r\n\tthis.catalogue.walls['S'] = new Wall( 32 , 48 , this.gfx('wallNS_32x48.png') , this.gfx('wireWallNS_32x48.png') , 0 , 16 ); \r\n\tthis.catalogue.walls['Du'] = new Wall( 32 , 48 , this.gfx('wallDoorUpper_32x48.png') , this.gfx('wireWallNS_32x48.png') , 0 , 16 ); \r\n\tthis.catalogue.walls['Dl'] = new Wall( 32 , 48 , this.gfx('wallDoorUnder_32x48.png') , this.gfx('wireWallNS_32x48.png') , 0 , 16 ); \r\n\r\n}",
"createFeed (context) {\n let ref = db.ref('connections').orderByKey().limitToLast(50)\n\n // watch for changes\n ref.on('value', snapshot => {\n const obj = snapshotToArray(snapshot)\n\n context.commit('setFeed', obj)\n })\n }",
"render_walls() {\n\t\tlet self = this;\n\n // Walls\n _.each( this.walls, function(w){\n \t\n \t// Check to ensure each wall is on it's own area\n \tlet other_walls = _.without( self.walls, w);\n \t_.each(other_walls, function(ow){\n \t\tif( self.collision( w.data.x, w.data.y, w.data.width, w.data.height + 450, ow.data.x, ow.data.y, ow.data.width, ow.data.height) ){\n \t\t\tw.reset();\n \t\t}\n \t});\n\n \t// reset the wall if needed\n \tif( w.data.y > self.canvas.height + w.data.height ){\n \t\tw.reset();\n \t}\n\n \t// update\n \tw.update();\n \t\n });\n\t}",
"function createBrickWall(){\n for(let i=0; i < brickRows; i++){\n brickWall[i]=[];\n for(let j=0; j<brickCols; j++){\n const x = i*(brick.w + brick.padding) +brick.offsetX;\n const y = j*(brick.h + brick.padding) +brick.offsetY;\n brickWall[i][j] = {x, y, ...brick};\n }\n }\n}",
"function prepareWalls() {\n\n // Retrieve the lines from the editor\n linesArray = getLinesFromEditor();\n for (var i = 0; i < linesArray.length; i++) {\n\n // Sets the needed variables\n var line = linesArray[i],\n x1 = line.x1,\n x2 = line.x2,\n y1 = line.y1,\n y2 = line.y2,\n xStart = line.left,\n xStop = line.width,\n zStart = line.top,\n zStop = line.height,\n floorNumber = line.floorNumber,\n material = line.material;\n\n // Checks if the line is drawn from bottom-left corner to top-right corner\n if ((x2 > x1 && y2 < y1) || (x2 < x1 && y2 > y1)) {\n zStart = line.top + line.height,\n zStop = -line.height;\n }\n\n // Refactors the values to match the scene setup\n xStart /= refactor,\n zStart /= refactor,\n xStop /= refactor,\n zStop /= refactor;\n\n // Calls the drawWall method\n drawWall(xStart, zStart, xStop, zStop, floorNumber, material);\n }\n}",
"function addDrinks(args) {\r\n let drink = args[2].toLowerCase();\r\n let url = args[3];\r\n db.get(\"drinks\").push({ drink: drink, gif: url }).write();\r\n}",
"function update_wall(obj) {\n\t\n\tvar play = false;\n\t\n\tif (obj && obj[0] && obj[0].m) {\n\t\tfor (key in obj) {\n\t\t\tif (obj[key].u != user) {\n\t\t\t\tplay = true;\n\t\t\t}\n\t\t\t\n\t\t\t// Change it to me, if its me\n\t\t\tif (obj[key].u == user) {\n\t\t\t\t\tobj[key].u = '<span style=\"color: blue;\">' + user + '</span>';\n\t\t\t}\n\t\t\t\n\t\t\tstr = '<li><span>' + obj[key].t + '</span> <strong>' + obj[key].u + '</strong>' + obj[key].m + '</li>';\n\t\t\t$('#stream').append(str);\n\t\t}\n\t\t\n\t\tif (play) { $.sound.play(sound_file);\t}\n\t}\t\n\t\n\t// Scroll to the bottom of the wall\n\t$(\"#wall\").attr({ scrollTop: $(\"#wall\").attr(\"scrollHeight\") });\n\tset_msg_focus();\n}",
"function saveEvents(eventsHeadding, eventsImg, eventsText) {\n let newEventsRef = eventsRef.push();\n newEventsRef.set({\n eventsHeadding: eventsHeadding,\n eventsImg: eventsImg,\n eventsText: eventsText\n });\n}",
"getWalls(){\n\t\tvar w=this.width;\n\t\tvar h=this.height;\n\t\tvar wt=this.wall_thiccness;\n\n\t\tvar walls=[];\n\t\tif (this.north)walls.push([this.x,this.y,this.width,this.wall_thiccness]);\n\t\tif (this.west) walls.push([this.x,this.y,wt,h]);\n\t\tif(this.east) walls.push([this.x+w,this.y,wt,h]);\n\t\tif(this.south) walls.push([this.x,this.y+h,w+wt,wt]);\n\n\t\treturn walls;\n\t}",
"function addNew() {\r\n const retrievedMaster = localStorage.getItem(`master`);\r\n const retrievedMasterParsed = JSON.parse(retrievedMaster);\r\n retrievedMasterParsed.push([\r\n active.fields[0].e.value,\r\n active.fields[1].e.value,\r\n active.fields[2].e.value,\r\n active.fields[3].e.value,\r\n active.fields[4].e.value,\r\n active.fields[5].e.value,\r\n active.fields[6].e.value,\r\n ]);\r\n localStorage.setItem(\"master\", JSON.stringify(retrievedMasterParsed));\r\n }",
"function saveStoredThings(){\n localStorage.setItem('fronter_fixes_links', links);\n}",
"addMovieToLS(data) {\n const movies = this.getMovieFromLS()\n movies.push(data)\n localStorage.setItem('movies', JSON.stringify(movies))\n }",
"function addStoneItem() {\n // Stone \n stone = new Array();\n stoneTexture = new THREE.TextureLoader().load('../../Assets/images/stone.jpg');\n stoneTexture.wrapS = THREE.RepeatWrapping;\n stoneTexture.wrapT = THREE.RepeatWrapping;\n stoneTexture.repeat.set(1, 1);\n stoneGeometry = new SphereGeometry(0.5, 5, 5);\n stoneMaterial = new PhongMaterial({ map: stoneTexture });\n for (var count = 0; count < 7; count++) {\n stone[count] = new Physijs.BoxMesh(stoneGeometry, stoneMaterial, 1);\n stone[count].receiveShadow = true;\n stone[count].castShadow = true;\n stone[count].name = \"Stone\";\n setStonePosition(stone[count]);\n }\n console.log(\"Added Stone item to the scene\");\n }",
"addWall(x, y, z, dx, dy, dz) {\n let wall = this.gameEngine.physicsEngine.addBox(dx, dy, dz);\n wall.position.set(x, y, z);\n return wall;\n }",
"function addToLocalStorage(note) {\n // Get Notes From Local Storage\n const notes = getNotesFromLocalStorage();\n\n // Add new note to the notes array\n notes.push(note);\n\n // Add New Note To Local Storage\n localStorage.setItem(\"notes\", JSON.stringify(notes));\n}",
"function addMemeToAccount(uid, meme) {\n let topText = meme.topText;\n let bottomText = meme.bottomText;\n let imageURL = meme.backgroundImage;\n let memeUri = meme.memeUri;\n var d = new Date().toString();\n db.ref(\"profile/\" + uid + \"/memes\")\n .push({\n topText: topText,\n bottomText: bottomText,\n backgroundImageURL: imageURL,\n memeUri: memeUri,\n dateCreated: d \n })\n .then(res => {\n console.log(res);\n alert(\"Success\");\n })\n .catch(error => {\n console.log(error.message);\n });\n}",
"function _getNewFeeds() {\n\n let query = {\n tag: 'steemovie',\n limit: 21,\n };\n\n steem.api.getDiscussionsByCreated(query, function (err, result) {\n app.feeds = result;\n\n // Rendering process of image image\n renderingImagePaths(result)\n });\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When component mounts, listRestaurants action is called and reducer is applied to get me restaurant data | componentDidMount() {
this.props.listRestaurants();
} | [
"function mapDispatchToProps(dispatch){\n return {\n getRecipesAction : (searchTerm) => {\n dispatch(getRecipes(searchTerm)) \n }\n }\n }",
"toRestaurant() {\n this.props.handleChangePage('Restaurant', this.props.rest.restId);\n }",
"getMovies() {\n console.log('in get movies');\n this.props.dispatch({\n type: 'FETCH_MOVIES'\n }) \n }",
"static getAllRestaurants() {\r\n return DBHelper.goGet(\r\n DBHelper.RESTAURANT_DB_URL,\r\n \"❗💩 Error fetching all restaurants: \"\r\n );\r\n }",
"function updateRestaurantList(dataList) {\n restaurants = {};\n allRests =[];\n for (i = 0; i < dataList.length; i++) {\n restaurant = JSON.parse(dataList[i]);\n restaurants[restaurant.id] = restaurant;\n }\n if(selfpos != undefined){\n displayRoute(JSON.parse(dataList[0]));\n }\n}",
"componentDidMount() {\n this.props.dispatch(loadDiscounts())\n }",
"componentWillMount() {\n\t\tthis.props.listarAnalisisTipoReferencias(this.props.analisisTipoDatos.analisisTipo.id_analisisTipo)\n\t}",
"function fetchrestaurants() {\n var data;\n $.ajax({\n url: 'https://api.foursquare.com/v2/venues/search',\n dataType: 'json',\n data: 'client_id=LEX5UAPSLDFGAG0CAARCTPRC4KUQ0LZ1GZSB4JE0GSSGQW3A&client_secret=0QUGSWLF4DJG5TM2KO3YCUXUB2IJUCHDNSZC0FUUA3PKV0MY&v=20170101&ll=28.613939,77.209021&query=restaurant',\n async: true,\n }).done(function (response) {\n data = response.response.venues;\n data.forEach(function (restaurant) {\n var foursquare = new Foursquare(restaurant, map);\n self.restaurantList.push(foursquare);\n });\n self.restaurantList().forEach(function (restaurant) {\n if (restaurant.map_location()) {\n google.maps.event.addListener(restaurant.marker, 'click', function () {\n self.selectrestaurant(restaurant);\n });\n }\n });\n }).fail(function (response, status, error) {\n\t\t\tself.queryResult('restaurant\\'s could not load...');\n });\n }",
"updateCurrentRestaurant(restaurant) {\n this.setState({\n currentRestaurant: restaurant,\n redirectTo: ''\n })\n }",
"async renderApp() {\n // Assigning data from localstorage to favouriteFoods array if localstorage has data\n this.favouriteFoods = JSON.parse(localStorage.getItem(\"favFoods\")) || []\n // Taking user data\n await this.getUserInformation()\n // Taking meals data\n await this.getFoods()\n this.searchMeal()\n }",
"static fetchRestaurantReviews(restaurant, callback) {\n\n fetch(DBHelper.REVIEW_URL + \"?restaurant_id=\" + restaurant.id).then((reviewResp) => {\n if (!reviewResp.ok) {\n callback(\"Failed to get the restaurant review json for id: \" + restaurant.id, null);\n } else {\n return reviewResp.json();\n }\n }).then((reviews) => {\n if (reviews) {\n // Creates a full restaurant object before calling a callback.\n restaurant[\"reviews\"] = reviews;\n DBHelper.addReviewsToIDB(reviews);\n callback(null, restaurant);\n // console.log(\"review\", restaurant);\n } else {\n // Has no reviews.\n callback(null, restaurant);\n }\n }).catch(function(error) {\n callback(\"Failed to get the restaurant review json for id: \" + restaurant.id, null);\n });\n\n }",
"constructor(){\n super();\n this.state = {\n locations: CatLocations.cats,\n matchingCats: [],\n }\n }",
"componentDidMount() {\n this.props.getDossiers();\n }",
"componentDidMount() {\n\n if (!this.props.courses) {\n this.props.dispatch(getCourseList());\n }\n\n if (!this.props.sections) {\n this.props.dispatch(getAllSections());\n }\n\n }",
"componentDidMount() {\n const action = { type: 'FETCH_HOP_USAGE' };\n this.props.dispatch(action);\n }",
"loadGroceries() {\n\n var category = this.props.category;\n\n new DietAPI().getGroceries(category).then((data) => {\n this.setState({\n groceries: []\n }, () => {this.setState({groceries : data.foods})});\n })\n }",
"function bookedTrips(state = [], action) {\n switch (action.type) {\n case 'BOOKED_TRIPS_LIST':\n return [...action.bookedTrips];\n case 'ADD_BOOKED_TRIP':\n return [action.bookedTrip, ...state];\n case 'EDIT_BOOKED_TRIP':\n return [...state].filter(trip => trip.id == action.bookedTrip.id)\n default:\n return state;\n }\n}",
"function rootReducer(state = {}, action) {\n return {\n todos: todos(state.todos, action),\n goals: goals(state.goals, action),\n };\n}",
"renderOffers() {\n \n const Offers = this.props.store.offers.map((offer) => {\n if (!offer.JoinRequest) {\n return (\n <CarpoolOffer\n token={this.props.token}\n key={offer._id}\n offerId={offer._id}\n store={new OfferStore(\n offer.CarpoolName,\n offer.SenderID,\n offer.SenderRoute,\n offer.RecieverID,\n offer.RecieverRoute,\n offer.JoinRequest,\n \"\"\n )} />\n );\n } else {\n return (\n <CarpoolOffer\n token={this.props.token}\n key={offer._id}\n offerId={offer._id}\n store={new OfferStore(\n offer.CarpoolName,\n offer.SenderID,\n offer.SenderRoute,\n offer.RecieverID,\n offer.RecieverRoute,\n offer.JoinRequest,\n offer.CarpoolID\n )} />\n );\n }\n\n }\n\n );\n\n if (Offers.length > 0) {\n\n return Offers;\n\n } else {\n\n return (\n <ListItem divider>\n <Avatar>\n <AddIcon />\n </Avatar>\n <ListItemText primary=\"No New Offers to Display\" secondary=\"View your routes to make an offer\" />\n </ListItem>\n );\n\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helpers // TODO: we should bring this out to a images_helper class or something? Generates a random URL with the specified length and a given set of characters | function generateRandomURL(length, chars) {
var output = '';
for (var i = length; i > 0; i--) {
output += chars[Math.round(Math.random() * (chars.length - 1))];
}
return output;
} | [
"function generateURL(id) {\n return `https://picsum.photos/id/${id}/400`;\n }",
"function buildRandomString(length) {\n //declare and initialize a string of the alphabet caracters\n var alphabet = 'abcdefghijklmnopqrstuvwxyz';\n //declare an empty result string\n var resultString = '';\n //REPEAT length times\n for (var i = 0; i <length; i++) {\n //add a random character to the result string\n resultString += alphabet[Math.round(Math.random() * (alphabet.length - 1))];\n }\n //return the result string\n return resultString;\n}",
"function uniqueLinkGen(){\n if(linkGenStore.findOne({'shortURL':short_url})===true){//check if short url is present\n short_url = linkGen.genURL();\n uniqueLinkGen();\n }\n else{\n return short_url;\n }\n }",
"function getRandomShortString() {\n return Math.random().toString(36).slice(-11);\n}",
"function generateRandomString() {\n const arrayOfAlphaNum = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];\n let outputString = \"\";\n\n for (var x = 0; x < 6; x++) {\n let index = Math.round(Math.random() * 61);\n outputString += arrayOfAlphaNum[index];\n }\n\n return outputString;\n}",
"function randomPassword(len){\n\n}",
"function generateIdChar(){\n var elegibleChars = \"abcdefghijklmnopqrstubwxyz\";\n var range = elegibleChars.length;\n var num = Math.floor(Math.random() * range);\n return elegibleChars.charAt(num);\n}",
"function makeid() {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n for (var i = 0; i < 1000; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n return text;\n }\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}",
"randomCharactor() {\n let str = '!@#$%^&*()_+?'\n return str[this.random(str.length)]\n }",
"function generateTestStrings(cnt, len) {\n\tlet test = [];\n\tfor(let i=0; i<cnt; i++) {\n\t\t// generate a string of the specified len\n\t\ttest[i] = getRandomString(len, 0, 65535);\n//\t\ttest[i] = getRandomString(len, 0, 55295);\n\t}\n\treturn test;\n}",
"function random128() {\n var result = \"\";\n for (var i = 0; i < 8; i++)\n result += String.fromCharCode(Math.random() * 0x10000);\n return result;\n}",
"function makeGameId(){\n let result = '';\n let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let charactersLength = characters.length;\n for ( let i = 0; i < 6; i++ ) {\n \tresult += characters.charAt(Math.floor(Math.random() * charactersLength));\n\t}\n\treturn result;\n}",
"function randomPassword(passwordLength){\noutputPassword=''\nfor (i=0;i<passwordLength;i++)\noutputPassword+=randomCharacters.charAt(Math.floor(Math.random()*randomCharacters.length))\n\nif (i < 8 || i > 128){\n alert(\"*ERROR* Your password must be between 8 to 128 characters long\");\n}\nelse {\nreturn outputPassword\n}\n}",
"function getVariantURL(variants) {\n\n let distribution = new Array(variants.length).fill(Number((1/variants.length).toFixed(2)))\n\n const rand = (Math.random() * (variants.length - 1)).toFixed(2)\n let acc = 0\n distribution = distribution.map(weight => (acc = acc + weight))\n return variants[distribution.findIndex(priority => priority > rand)]\n}",
"static async UrlShortener() {\n\n }",
"function randomImageId(){\n var invalidIds = [86, 97, 105, 138, 148, 150, 205, 207, 224, 226, 245, 246, 262, 285, 286, 298, 303, 332, 333, 346, 359, 394, 414, 422, 438, 462, 470, 489, 561, 578, 589, 595, 597, 624, 632, 636, 644, 647, 673, 697, 706, 707, 708, 709, 710, 711, 712, 713, 714, 725, 734, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 759, 761, 762, 763, 771, 801, 812, 843, 850, 854, 895, 897, 917, 920, 956, 963];\n var newId = Math.floor(Math.random() * 1000);\n while(invalidIds.indexOf(newId) !== -1)\n newId = Math.floor(Math.random() * 1000);\n return newId;\n}",
"function randomLength(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min +1)) + min;\n}",
"function generateUID(length) {\n var rtn = '';\n for (let i = 0; i < UID_LENGTH; i++) {\n rtn += ALPHABET.charAt(Math.floor(Math.random() * ALPHABET.length));\n }\n return rtn;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies the value of a property from one object to the other. This is used to copy property values as part of setOption for loggers and appenders. Because loggers inherit property values from their parents, it is important never to create a property on a logger if the intent is to inherit from the parent. Copying rules: 1) if the from property is undefined (for example, not mentioned in a JSON object), the to property is not affected at all. 2) if the from property is null, the to property is deleted (so the logger will inherit from its parent). 3) Otherwise, the from property is copied to the to property. | function copyProperty(propertyName, from, to) {
if (from[propertyName] === undefined) {
return;
}
if (from[propertyName] === null) {
delete to[propertyName];
return;
}
to[propertyName] = from[propertyName];
} | [
"function defineAllProperties(to, from) {\n to.__model__ = to.__model__ || from;\n each(from, function(m,n) {\n try {\n if (to.__model__ !== from)\n to.__model__[n] = m;\n defineProperty(to,n,m);\n } catch (t) {}\n });\n }",
"function MergeRecursive(obj1, obj2) {\n\n for (var p in obj2) {\n try {\n // Property in destination object set; update its value.\n if ( obj2[p].constructor==Object ) {\n obj1[p] = MergeRecursive(obj1[p], obj2[p]);\n \n } else {\n obj1[p] = obj2[p];\n \n }\n \n } catch(e) {\n // Property in destination object not set; create it and set its value.\n obj1[p] = obj2[p];\n \n }\n }\n \n return obj1;\n }",
"function deepExtend(target, source) {\n if (!(source instanceof Object)) {\n return source;\n }\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n var dateValue = source;\n return new Date(dateValue.getTime());\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n for (var prop in source) {\n if (!source.hasOwnProperty(prop)) {\n continue;\n }\n target[prop] = deepExtend(target[prop], source[prop]);\n }\n return target;\n }",
"function ObjectFieldTransfer(from, target) {\n for (const key in from) {\n if (key != \"__proto__\" &&\n Object.prototype.hasOwnProperty.call(from, key)\n && typeof from[key] !== \"function\") {\n const element = from[key];\n target[key] = element;\n }\n }\n}",
"function mergeProperties(fromStr, src, dest) {\n trace(whoAmI,\"mergeProperties\",true);\n var unite = false;\n \n for (var p in src) {\n unite = (utils.isArray(src[p]) && (p === 'pluginList' || p === 'configXmlWidget'));\n\n // The local pluginList and configXmlWidget values must be merged with the\n // global values. In all other cases, the local value overrides the global\n // value\n dest[p] = (unite) ? utils.union(dest[p], src[p]) : src[p];\n }\n\n trace(whoAmI,\"mergeProperties\",false);\n}",
"function set_object_props(obj, from, whitelist) {\n\tvar wl = whitelist.split(\",\");\n\tfor(var i=0; i<wl.length; i++) {\n\t\tvar prop = wl[i];\n\t\tif (undefined !== obj[prop] && undefined !== from[prop]) {\n\t\t\t//console.log(\"WL update prop %s obj:%s -> to %s\", prop, obj[prop], from[prop]);\n\t\t\tobj[prop] = from[prop];\n\t\t}\n\t}\n}",
"function copy_props(props, a, b) {\n\tfor (let p of props)\n\t\tb[p] = a[p]\n}",
"function mergeDiff(prop, a, b) {\n var akeys = Object.keys(a);\n var bkeys = Object.keys(b);\n var diff = _.difference(akeys, bkeys);\n var obj = _.pick(a, diff);\n\n b[prop] = b[prop] || {};\n _.merge(b[prop], obj);\n return b;\n}",
"fillOptions(source, target) {\n // Overrride with settings from user and child class\n function eachRecursive(source, target, level) {\n for (var k in source) {\n // Find variable in default settings\n if (typeof source[k] == \"object\" && source[k] !== null) {\n // If the current level is not defined in the target, it is\n // initialized with empty object.\n if (target[k] === undefined) {\n target[k] = {};\n }\n eachRecursive(source[k], target[k]);\n }\n else {\n // We store each leaf property into the default settings\n target[k] = source[k];\n }\n }\n }\n eachRecursive(source, target);\n }",
"function deepOverride(target, source) {\r\n if (canBeCopied(source)) {\r\n return source === undefined ? target : source;\r\n } else if (Array.isArray(source) || Array.isArray(target)) {\r\n return deepArray(target, source);\r\n } else {\r\n return deepOverrideCore(target, source);\r\n }\r\n}",
"function overwriteObjectUndefineds(obj1, obj2){\n\tfor(var prop in obj2){\n\t\tif(typeof obj1[prop] === 'undefined'){\n\t\t\tobj1[prop] = obj2[prop];\n\t\t}\n\t}\n\t\n\treturn obj1;\n}",
"function transferProperties(onto, label, props) {\n const resolvers = {};\n for (const k of Object.keys(props)) {\n // Skip \"id\" and \"urn\", since we handle those specially.\n if (k === \"id\" || k === \"urn\") {\n continue;\n }\n // Create a property to wrap the value and store it on the resource.\n if (onto.hasOwnProperty(k)) {\n throw new Error(`Property '${k}' is already initialized on target '${label}`);\n }\n let resolveValue;\n let rejectValue;\n let resolveIsKnown;\n let rejectIsKnown;\n let resolveIsSecret;\n let rejectIsSecret;\n let resolveDeps;\n let rejectDeps;\n resolvers[k] = (v, isKnown, isSecret, deps = [], err) => {\n if (err) {\n if (errors_1.isGrpcError(err)) {\n if (debuggable_1.debugPromiseLeaks) {\n console.error(\"info: skipped rejection in transferProperties\");\n }\n return;\n }\n rejectValue(err);\n rejectIsKnown(err);\n rejectIsSecret(err);\n rejectDeps(err);\n }\n else {\n resolveValue(v);\n resolveIsKnown(isKnown);\n resolveIsSecret(isSecret);\n resolveDeps(deps);\n }\n };\n const propString = output_1.Output.isInstance(props[k]) ? \"Output<T>\" : `${props[k]}`;\n onto[k] = new output_1.Output(onto, debuggable_1.debuggablePromise(new Promise((resolve, reject) => {\n resolveValue = resolve;\n rejectValue = reject;\n }), `transferProperty(${label}, ${k}, ${propString})`), debuggable_1.debuggablePromise(new Promise((resolve, reject) => {\n resolveIsKnown = resolve;\n rejectIsKnown = reject;\n }), `transferIsStable(${label}, ${k}, ${propString})`), debuggable_1.debuggablePromise(new Promise((resolve, reject) => {\n resolveIsSecret = resolve;\n rejectIsSecret = reject;\n }), `transferIsSecret(${label}, ${k}, ${propString})`), debuggable_1.debuggablePromise(new Promise((resolve, reject) => {\n resolveDeps = resolve;\n rejectDeps = reject;\n }), `transferDeps(${label}, ${k}, ${propString})`));\n }\n return resolvers;\n}",
"function recursiveMerge(target, src) {\n for (var prop in src) {\n if (src.hasOwnProperty(prop)) {\n if (target.prototype && target.prototype.constructor === target) {\n // If the target object is a constructor override off prototype.\n clobber(target.prototype, prop, src[prop]);\n } else {\n if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {\n recursiveMerge(target[prop], src[prop]);\n } else {\n clobber(target, prop, src[prop]);\n }\n }\n }\n }\n }",
"inherit(property) {\n }",
"addProperties (target) {\n\n // Property getter/setter injection\n this.position.addProperties(target);\n\n // Component references\n target.position = this.position;\n target.scale = this.scale;\n\n return target;\n\n }",
"function copyObject(first, second) {\n\tclearObject(second);\n\t\n\tfor(var k in first) {\n\t\tsecond[k] = first[k];\n\t}\n}",
"function objOverride(base, extension, property) {\n // extension doesn't have property; just return base\n if (extension[property] == null) {\n return;\n }\n // base doesn't have property; copy extension's property (ref copy if obj)\n if (base[property] == null) {\n base[property] = extension[property];\n return;\n }\n // both have property; do per-key copy/override of extension's properties\n // (ref copies if objs)\n for (let key in extension[property]) {\n base[property][key] = extension[property][key];\n }\n}",
"function convertProperty(obj, prop, newProp) {\n if (obj.hasOwnProperty(prop)) {\n obj[newProp] = obj[prop];\n delete obj[prop];\n }\n return obj;\n}",
"function objMerge(obj1, obj2) {\n if ((typeof obj1 != 'object') || (typeof obj2 != 'object')) {\n return;\n }\n \n for (var prop2 in obj2) {\n obj1[prop2] = obj2[prop2];\n }\n \n return obj1;\n}",
"deepAssign(orig,obj) {\n var v;\n for( var key in obj ) {\n v=obj[key];\n if( typeof v===\"object\" ) {\n orig[key]=Array.isArray(v)?[]:{};\n this.deepAssign(orig[key],v);\n } else {\n orig[key]=v;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recomputes and then places each window in its correct position widget > x, y, id | function new_window_fixup() {
var windows = $('.gs-w');
for (var i = 0; i < windows.length; i++) {
$(windows[i]).attr({
'data-col': layout[windows.length-1][i].col(maxCols),
'data-row': layout[windows.length-1][i].row(maxHeight),
'data-sizex': layout[windows.length-1][i].sizex(maxCols),
'data-sizey': layout[windows.length-1][i].sizey(maxHeight)
});
};
gridster.set_dom_grid_height();
gridster.set_dom_grid_width();
} | [
"rearrangeDivs() {\n const margin = 10;\n let twidth = window.innerWidth - this.parent_.offsetLeft;\n // TODO remove this hack\n // If the config is present\n let config = document.getElementById(\"config\");\n if (config !== null) twidth -= config.offsetWidth + 10 + margin;\n\n // Group windows in number needed to fill a row\n const splitter = 20;\n let sizes = [];\n for (let id in this.windows_) {\n let div = this.windows_[id];\n if (div.style.display === \"none\") continue;\n const box = div.getBoundingClientRect();\n const width = box.width + 2 * margin;\n const height = box.height + 2 * margin;\n const num = (twidth / width) | 0;\n if (!sizes[num]) {\n sizes[num] = [];\n }\n sizes[num].push({w: width, h: height, d: div});\n }\n\n // Extract a list of window that fit next to the right most element until we reach its height\n const extract = function(aw, th) {\n let list = [];\n let h = 0;\n for (let i in sizes) {\n for (let e in sizes[i]) {\n let elem = sizes[i][e];\n if (!elem) continue;\n if (elem.w < aw && h + elem.h < th * 1.1) {\n list.push(elem);\n sizes[i][e] = null;\n h += elem.h;\n if (h > th) break;\n }\n }\n if (h > th) break;\n }\n return list;\n }\n // Place an element at a givent place\n const place = function(elem, y, x, aw) {\n elem.style.top = y + \"px\";\n elem.style.left = x + \"px\";\n if (elem.options && elem.options.resize === true) {\n elem.style.width = (aw - 2 * margin) + \"px\";\n elem.click();\n }\n }\n\n // Go through the group one by one and organize the window\n let y = margin;\n for (let i in sizes) {\n if (i <= 0) {\n // Special case for the window that does not fit\n for (let e in sizes[i]) {\n let elem = sizes[i][e];\n place(elem.d, y, margin, twidth);\n y += elem.h;\n }\n } else if (i == 1) {\n // Special case for the window that fit alone (we still try to find another window to fit)\n for (let e in sizes[i]) {\n let elem = sizes[i][e];\n place(elem.d, y, margin);\n const aw = twidth - elem.w;\n const list = extract(aw, elem.h);\n let h = 0;\n for (let d in list) {\n place(list[d].d, y + h, elem.w + margin, aw);\n h += list[d].h;\n }\n y += Math.max(elem.h, h);\n }\n } else {\n // Organize the windows by columns, always add to the smallest one.\n let h = [];\n for (let v = 0; v < i; v++) h.push(0);\n const w = twidth / i;\n for (let e in sizes[i]) {\n let c = h.indexOf(Math.min(...h));\n let elem = sizes[i][e];\n if (!elem) continue;\n place(elem.d, y + h[c], margin + c * w, w);\n h[c] += elem.h;\n }\n let c = h.indexOf(Math.max(...h));\n y += h[c];\n }\n }\n this._resizeWindowManager();\n return true;\n }",
"_resizeWindowManager() {\n const kMargin = 200;\n let required_height = 0;\n let required_width = 0;\n for (let i in this.windows_) {\n const element = this.windows_[i];\n const top = parseInt(element.style.top);\n const left = parseInt(element.style.left);\n if (top > 0 && left > 0) {\n required_height = Math.max(required_height, top + element.offsetHeight);\n required_width = Math.max(required_width, left + element.offsetWidth);\n }\n }\n this.parent_.style.height = (required_height + kMargin) + \"px\";\n this.parent_.style.width = (required_width + kMargin) + \"px\";\n }",
"getPosition(width, height) {\n let twidth = window.innerWidth;\n let config = document.getElementById(\"config\");\n const margin = 10;\n if (config !== null) twidth -= config.offsetWidth + margin;\n\n // Make sure that if width > twidth we place it anyway\n twidth = Math.max(this.parent_.offsetLeft + 1, twidth - width);\n let grid_size = 20;\n let divs = [];\n for (let id in this.windows_) {\n if (this.windows_[id].style.display === \"none\") continue;\n divs.push(this.windows_[id]);\n }\n // Loop through a grid of position until we reach an empty spot.\n for (let y = 0;; y += grid_size) {\n for (let x = this.parent_.offsetLeft; x <= twidth; x += grid_size) {\n let free = true;\n for (let div of divs) {\n const box = div.getBoundingClientRect();\n if (box.top >= margin + y + height) continue;\n if (box.bottom + margin <= y) continue;\n if (box.left >= x + width + margin) continue;\n if (box.right + margin <= x) continue;\n free = false;\n break;\n }\n if (free) return {x: x + margin - this.parent_.offsetLeft, y: y + margin};\n }\n // Increase the speed of the search\n if (y > 100 * grid_size) grid_size += margin;\n }\n }",
"function createWindow() {\n\n windowPanel = $(\"<div></div>\"); //Sliding Window\n windowPanel.addClass(\"swindow\");\n var sfSlot = sfSlots[windowSb];\n var width = sfSlot.outerWidth() * windowSize + windowSize * 10 + 2;\n windowPanel.css(\"width\", width);\n windowPanel.css({\n top: sfSlot.position().top - 10,\n left: sfSlot.position().left,\n position: \"absolute\"\n });\n $(\"#medium\").append(windowPanel);\n}",
"updateDisplay()\n {\n // clip window position\n this.position.x = clamp(\n this.position.x, 0,\n this.window.innerWidth - this.element.clientWidth\n )\n this.position.y = clamp(\n this.position.y, 0,\n this.window.innerHeight - this.element.clientHeight\n - 50 // toolbar\n )\n\n // update rendered position\n this.element.style.left = this.position.x + \"px\"\n this.element.style.top = this.position.y + \"px\"\n\n // get dimensions\n this.outerWidth = this.element.clientWidth\n this.outerHeight = this.element.clientHeight\n this.innerWidth = this.content.clientWidth\n this.innerHeight = this.content.clientHeight\n }",
"function updateHtmlElements() {\n\n // Plot containers\n plotContainers.forEach((c, i) => {\n c.position(bounds[i].west - 1, bounds[i].north - 1);\n c.size(plotSize - 1, plotSize - 1);\n });\n\n // Options panel\n optionsPanel.position(\n 1 + bounds[0].west,\n bounds[0].south + 0.12 * (sketch.height - bounds[0].south)\n );\n optionsPanel.size(\n bounds[1].east - bounds[0].west,\n 0.8 * (sketch.height - bounds[0].south)\n );\n\n }",
"function resetUiBounds()\n {\n // if ui is off the page, relocate it\n var lastPosition = getLastPosition();\n var lastSize = getLastSize();\n var windowWidth = $window.width();\n var windowHeight = $window.height();\n\n // resize alme window\n $almeWindow.css({\n width: windowWidth,\n height: windowHeight\n });\n\n // if ui is open\n if ( lastState.isOpen !== undefined && lastState.isOpen && lastState.layout !== \"sidebar\" )\n {\n prepResize();\n\n // if off the right side of the screen, relcate to right edge\n if ( lastPosition.left + lastSize.uiWidth > windowWidth )\n {\n var newLeft = windowWidth - lastSize.uiWidth;\n $ui.css({\n left: newLeft\n });\n\n // remember new position\n lastState.position.left = newLeft;\n }\n\n // if off left move onto screen\n if ( lastPosition.left < 0 )\n {\n $ui.css({\n left: 0\n });\n }\n\n // if ui is off the top of the page && ui is shorter than window height\n if ( lastPosition.top < 0 && lastSize.uiHeight < windowHeight )\n {\n // set position to top edge\n $ui.css({\n top: 0\n });\n\n // remember new position\n lastState.position.top = 0;\n }\n\n // if ui is off the bottom of the page\n if ( lastPosition.top + lastSize.uiHeight > windowHeight )\n {\n var newTop = windowHeight - lastSize.uiHeight;\n $ui.css({\n top: newTop\n });\n\n // remember new position\n lastState.position.top = newTop;\n }\n }\n }",
"function redrawWidgets() {\n let W = global.WIDGETS;\n global.WIDGETS = {};\n Object.keys(W)\n .sort() // see comment in boot.js\n .sort((a, b) => (0|W[b].sortorder)-(0|W[a].sortorder))\n .forEach(k => {global.WIDGETS[k] = W[k];});\n Bangle.drawWidgets();\n }",
"function updatePosition() {\n\t \n\t\tbox.css({\n\t\t\t'width': ($(element).width() - 2) + 'px',\n\t\t\t'top': ($(element).position().top + $(element).height()) + 'px',\n\t\t\t'left': $(element).position().left +'px'\n\t\t});\n\t}",
"updateTimeWindow(timeWindow){\n var oldWindow = this.timeWindow ;\n this.scaleTimeWindow.setUniform('oldWindow',oldWindow ) ;\n this.scaleTimeWindow.setUniform('newWindow',timeWindow ) ;\n this.timeWindow = timeWindow ;\n this.scaleTimeWindow.render() ;\n this.wA2b.render() ;\n this.hist.setUniform('shift',0) ;\n this.hist.render() ;\n this.wA2b.render() ;\n this.render() ;\n return ;\n }",
"function AbstractWindow(url, p_xo, p_yo, p_wth, p_hgt) {\r\n /* Clase para mostrar la ventana*/\r\n\tthis.classHide = \"iwinContainerHide\";\r\n\t/* Clase para ocultar la ventana*/\r\n\tthis.classShow = \"iwinContainer\";\t\r\n\t/* Atributos */\r\n this.xo = p_xo || 0;\r\n this.yo = p_yo || 0;\r\n this.wth = p_wth || 100;\r\n this.hgt = p_hgt || 100;\r\n this.url = url;\r\n this.created = false;\r\n this.visible = false;\r\n /*HTML Atributes */\r\n this.element = null;\r\n /* Methods */\r\n\t/* This function shows de basedow */\r\n\tthis.show = function() {\r\n\t\t\t\t\t\tthis.show_prev();\r\n\t\t\t\t\t\t/* Se crea la ventana */\r\n\t\t\t\t\t\tthis.element = document.createElement(\"div\");\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tthis.element.appendChild(this.createContent());\r\n\t\t\t\t\t\t/* Se agrega la ventana al cuerpo de la pagina */\r\n\t\t\t\t\t\tdocument.body.appendChild(this.element);\r\n\t\t\t\t\t\tthis.element.className = this.classShow;\t\t\t\t\t\t\r\n\t\t\t\t\t\tthis.locateWindow(this.xo, this.yo, this.wth, this.hgt);\r\n\t\t\t\t\t\tthis.visible = true;\r\n\t\t\t\t\t\tthis.show_next();\r\n\t\t\t\t}\r\n\t\r\n /* This function Hides the basedow */\r\n\tthis.hide =\tfunction() {\t\t\r\n\t\t\t\t\tvar ret = true;\r\n\t\t\t\t\tif (this.onHideStart) eval(this.onHideStart);\r\n\t\t\t\t\tif (ret) {\r\n\t\t\t\t\t\tthis.hide_prev();\r\n\t\t\t\t\t\tthis.element.className = this.classHide;\r\n\t\t\t\t\t\tthis.visible = false;\r\n\t\t\t\t\t\tthis.hide_next();\r\n\t\t\t\t\t\tif (this.onHideEnd) eval(this.onHideEnd);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\tthis.locateWindow =\tfunction (x, y, w, h) {\r\n\t\t\t\t\t\t\t\tthis.wth=w;\r\n\t\t\t\t\t\t\t\tthis.hgt=h;\r\n\t\t\t\t\t\t\t\tthis.xo=x;\r\n\t\t\t\t\t\t\t\tthis.yo=y;\r\n\t\t\t\t\t\t\t\tthis.element.style.left = x + 'px' ;\r\n\t\t\t\t\t\t\t\tthis.element.style.top = y + 'px';\t\r\n\t\t\t\t\t\t\t}\r\n\tthis.determineWidth = \tfunction() {\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tvar w = window.innerWidth\r\n\t\t\t\t\t\t\t\t\t\t|| document.documentElement.clientWidth\r\n\t\t\t\t\t\t\t\t\t\t|| document.body.clientWidth;\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\treturn w;\r\n\t\t\t\t\t\t\t}\r\n\tthis.determineHeight =\tfunction() {\r\n\t\t\t\t\t\t\t\tvar h = window.innerHeight\r\n\t\t\t\t\t\t\t\t\t|| document.documentElement.clientHeight\r\n\t\t\t\t\t\t\t\t\t|| document.body.clientHeight; \r\n\t\t\t\t\t\t\t\treturn h;\r\n\t\t\t\t\t\t\t}\r\n\t/****\r\n\t** Metodos a definir en una clase hijo\r\n\t*****/\r\n\t/* Funcion que genera el contenido de la ventana, debe ser redefinida por las clases herederas para cambiar su funcionamiento \r\n\t* @Abstract\r\n\t*/\r\n\tthis.createContent = \tfunction() { alert(\"Debe redefinir el metodo 'createContent'\");\t}\r\n\t/* Metodos a redefinir en una clase hijo para ejecutar codigo propio antes y despues de la operacion show*/\t\t\t\r\n\tthis.show_prev = function() {}\r\n\tthis.show_next = function() {}\t\r\n\t/* Metodos a redefinir en una clase hijo para ejecutar codigo propio antes y despues de la operacion hide */\t\t\t\r\n\tthis.hide_prev = function() {}\r\n\tthis.hide_next = function() {}\t\r\n\t/**\r\n\t * Eventos que el usuario puede definir para obtener control de la ventana\r\n\t * Si devuelven false, susupende la ejecución del evento. \r\n\t */\r\n\tthis.onHideStart = undefined;\t//Antes de Cerrar (Debe devolver true/false).\r\n\tthis.onHideEnd = undefined;\t//Despues de Cerrar\r\n}",
"function redrawWindowList() {\n\t\tutilsModule.clearChildren(windowListElem);\n\t\tself.windowNames.forEach(function(windowName) {\n\t\t\t// windowName has type str, and is of the form (profile+\"\\n\"+party)\n\t\t\tvar parts = windowName.split(\"\\n\");\n\t\t\tvar profile = parts[0];\n\t\t\tvar party = parts[1];\n\t\t\tvar window = windowData[windowName];\n\t\t\t\n\t\t\t// Create the anchor element\n\t\t\tvar a = utilsModule.createElementWithText(\"a\", party != \"\" ? party : profile);\n\t\t\tvar n = window.numNewMessages;\n\t\t\tif (n > 0) {\n\t\t\t\t[\" (\", n.toString(), \")\"].forEach(function(s) {\n\t\t\t\t\ta.appendChild(utilsModule.createElementWithText(\"span\", s));\n\t\t\t\t});\n\t\t\t}\n\t\t\tutilsModule.setClasslistItem(a, \"nickflag\", window.isNickflagged);\n\t\t\ta.onclick = function() {\n\t\t\t\tself.setActiveWindow(windowName);\n\t\t\t\treturn false;\n\t\t\t};\n\t\t\ta.oncontextmenu = function(ev) {\n\t\t\t\tvar menuItems = [];\n\t\t\t\tif (window.isMuted)\n\t\t\t\t\tmenuItems.push([\"Unmute window\", function() { window.isMuted = false; }]);\n\t\t\t\telse {\n\t\t\t\t\tmenuItems.push([\"Mute window\", function() {\n\t\t\t\t\t\tvar win = window;\n\t\t\t\t\t\twin.isMuted = true;\n\t\t\t\t\t\twin.numNewMessages = 0;\n\t\t\t\t\t\twin.isNickflagged = false;\n\t\t\t\t\t\tredrawWindowList();\n\t\t\t\t\t}]);\n\t\t\t\t}\n\t\t\t\tvar closable = !(profile in connectionData) || (party != \"\" && !(party in connectionData[profile].channels));\n\t\t\t\tvar func = function() { networkModule.sendAction([[\"close-window\", profile, party]], null); };\n\t\t\t\tmenuItems.push([\"Close window\", closable ? func : null]);\n\t\t\t\tif (utilsModule.isChannelName(party) && profile in connectionData) {\n\t\t\t\t\tvar mode = party in connectionData[profile].channels;\n\t\t\t\t\tvar func = function() {\n\t\t\t\t\t\tnetworkModule.sendAction([[\"send-line\", profile, (mode ? \"PART \" : \"JOIN \") + party]], null);\n\t\t\t\t\t};\n\t\t\t\t\tmenuItems.push([(mode ? \"Part\" : \"Join\") + \" channel\", func]);\n\t\t\t\t}\n\t\t\t\tmenuModule.openMenu(ev, menuItems);\n\t\t\t};\n\t\t\t\n\t\t\tvar li = document.createElement(\"li\");\n\t\t\tli.appendChild(a);\n\t\t\tif (party == \"\")\n\t\t\t\tutilsModule.setClasslistItem(li, \"profile\", true);\n\t\t\twindowListElem.appendChild(li);\n\t\t});\n\t\trefreshWindowSelection();\n\t\t\n\t\tvar totalNewMsg = 0;\n\t\tfor (var key in windowData)\n\t\t\ttotalNewMsg += windowData[key].numNewMessages;\n\t\tvar activeWin = self.activeWindow\n\t\tif (activeWin != null) {\n\t\t\tvar s = (activeWin[1] != \"\" ? activeWin[1] + \" - \" : \"\") + activeWin[0] + \" - MamIRC\";\n\t\t\tdocument.title = (totalNewMsg > 0 ? \"(\" + totalNewMsg + \") \" : \"\") + s;\n\t\t\tif (optimizeMobile)\n\t\t\t\tdocument.querySelector(\"#main-screen header h1\").firstChild.data = s;\n\t\t}\n\t}",
"function updateView() {\n // For every square on the board.\n console.log(MSBoard.rows);\n\n for (var x = 0; x < MSBoard.columns; x++) {\n for (var y = 0; y < MSBoard.rows; y++) {\n squareId = \"#\" + x + \"-\" + y;\n // Removes the dynamic classes from the squares before adding appropiate ones back to it.\n $(squareId).removeClass(\"closed open flagged warning\");\n\n square = MSBoard.squares[x][y];\n\n // These questions determine how a square should appear.\n // If no other text is put into a square, a is inserted because otherwise it disturbs the grid.\n // If a square is open, it should be themed as so and also display the number of nearby mines.\n if (square.open && !square.mine) {\n $(squareId).addClass(\"open\");\n $(squareId).html(square.nearbyMines);\n } \n // Flags are displayed only if the square is still closed.\n else if (square.flag && !square.open) {\n $(squareId).addClass(\"closed\");\n $(squareId).html(\"<img src='redFlag.png' class='boardImg flag' /> \")\n } \n // Mines are displayed either if they're open (Either from opening one and losing or during validating) or while the cheat control is pressed.\n else if (square.mine && (square.open || cheating)) {\n $(squareId).addClass(\"warning\");\n $(squareId).html(\"<img src='mine.png' class='boardImg mine' /> \")\n } \n // The HTML is set to a blank space in case there is nothing else to put in the space. \n else if (!square.open && !square.flag) {\n $(squareId).addClass(\"closed\"); \n $(squareId).html(\" \")\n }\n\n }\n }\n\n if (startMenuOn) {\n $(\"#newGameSettings\").css(\"display\", \"block\");\n } else {\n $(\"#newGameSettings\").css(\"display\", \"none\"); \n }\n\n}",
"function handleReposition(old_width, old_height) {\n $(\".handle\").each(function() {\n var x_pct = parseInt($(this).css(\"left\")) / old_width\n var y_pct = parseInt($(this).css(\"top\")) / old_height\n\n var new_x = x_pct * width + \"px\"\n var new_y = y_pct * height + \"px\"\n\n // Reposition each handle\n $(this).css({\n left: new_x,\n top: new_y\n })\n })\n}",
"function arrange () {\n\n // repositioning the buttons for aesthetic reasons\n var controls = document.getElementById(\"controls\");\n controls.style.position = \"absolute\";\n controls.style.left = Width*1.15 + \"px\";\n controls.style.top = 50 + \"px\";\n\n // repositioning the legends for aesthetic reasons\n var legend = document.getElementById(\"legend\");\n legend.style.position = \"absolute\";\n legend.style.left = Width*1.15 + \"px\";\n legend.style.top = 185 + \"px\";\n\n // repositioning the legends for aesthetic reasons\n var info = document.getElementById(\"info\");\n info.style.position = \"absolute\";\n info.style.top = 625 + \"px\";\n\n} // end arrange",
"function setObjectsOrder () {\n\t\twindow.orderArray = [].concat(\n\t\t\toverlay['middle'].object,\n\t\t\twindow.$imageObjects,\n\t\t\twindow.$textObjects,\n\t\t\toverlay['top'].object,\n\t\t\toverlay['bottom'].object,\n\t\t\toverlay['left'].object,\n\t\t\toverlay['right'].object\n\t\t\t);\n\n\t\tfor (var i = 0; i < orderArray.length; i++) {\n\t\t\tcnv.moveTo(orderArray[i], i + 1);\n\t\t\torderArray[i]['zIndex'] = i + 1;\n\t\t}\n\t\tcnv.renderAll();\n\t}",
"function BuildingMenuFunc (windowID : int) {\r\n \r\n var data:Database = GameObject.Find(\"Database\").GetComponent(\"Database\");\r\n \r\n // Added a scroll bar for when there are multiple buildings; need to find a way to disable the panning of the camera while scrolling\r\n scrollPosition = GUI.BeginScrollView (Rect (5,25,toolBarWidth - 25 , toolBarHeight - 50), scrollPosition, Rect (0, 0, toolBarWidth - 75, toolBarHeight + 75), false, true);\r\n \r\n for(var i =0; i<6; i++)\r\n {\r\n \tif(GUI.Button(Rect(5, 20 + (95*i), 90, 90), btnTextureArray[i]))\r\n \t{\r\n \t\tPlaceBuilding.changeBuilding = i;\r\n \t\tshowWindow = false;\r\n \t}\r\n\r\n\t\t\t//Debug.Log(\"Building: at index \" + i);\r\n\t\t\t//GUI.Label(Rect(100, 20 + (95*i), 200, 90 * i), buildingMenuStrings[i]);\r\n\t\t\t\r\n \tGUI.Label(Rect(100, 20 + (95*i), 200, 90), \tdata.buildings[i].buildingName \r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \"\\n\"\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \"INPUT: \" + data.buildings[i].inputName\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \" [\" + data.buildings[i].inputNum + \"]\"\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \"\\n\"\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \"OUTPUT: \" + data.buildings[i].outputName\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \" [\" + data.buildings[i].outputNum + \"]\");\r\n \t\t\t\t\t\t\t\t\t\t\t\r\n\r\n\t\t}\r\n\t\t\r\n\t\tGUI.EndScrollView ();\r\n}",
"update() {\n\n let windows = this._source.getInterestingWindows();\n\n // update, show or hide the quit menu\n if ( windows.length > 0) {\n let quitFromDashMenuText = \"\";\n if (windows.length == 1)\n this._quitfromDashMenuItem.label.set_text(_('Quit'));\n else\n this._quitfromDashMenuItem.label.set_text(__('Quit %d Windows').format(windows.length));\n\n this._quitfromDashMenuItem.actor.show();\n\n } else {\n this._quitfromDashMenuItem.actor.hide();\n }\n\n if(Docking.DockManager.settings.get_boolean('show-windows-preview')){\n\n // update, show, or hide the allWindows menu\n // Check if there are new windows not already displayed. In such case, repopulate the allWindows\n // menu. Windows removal is already handled by each preview being connected to the destroy signal\n let old_windows = this._allWindowsMenuItem.menu._getMenuItems().map(function(item){\n return item._window;\n });\n\n let new_windows = windows.filter(function(w) {return old_windows.indexOf(w) < 0;});\n if (new_windows.length > 0) {\n this._populateAllWindowMenu(windows);\n\n // Try to set the width to that of the submenu.\n // TODO: can't get the actual size, getting a bit less.\n // Temporary workaround: add 15px to compensate\n this._allWindowsMenuItem.width = this._allWindowsMenuItem.menu.actor.width + 15;\n\n }\n\n // The menu is created hidden and never hidded after being shown. Instead, a singlal\n // connected to its items destroy will set is insensitive if no more windows preview are shown.\n if (windows.length > 0){\n this._allWindowsMenuItem.show();\n this._allWindowsMenuItem.setSensitive(true);\n }\n }\n\n // Update separators\n this._getMenuItems().forEach(item => {\n if ('label' in item) {\n this._updateSeparatorVisibility(item);\n }\n });\n }",
"_refresh(){\n this._refreshSize();\n this._refreshPosition();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the supplied entry to the cache and updates the cache size as appropriate. All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer returned by `newChangeBuffer()`. | addEntry(t, e, n) {
const s = e.key,
i = this.docs.get(s),
r = i ? i.size : 0,
o = this.ps(e);
return this.docs = this.docs.insert(s, {
document: e.clone(),
size: o,
readTime: n
}), this.size += o - r, this.Ht.addToCollectionParentIndex(t, s.path.popLast());
} | [
"addEntry (state, args) {\n const cache = state.cache[args.property]\n const turn = state.turns[state.currentTurn]\n turn.push(args.entry)\n\n cache.turn = state.currentTurn\n cache.entryId = args.entry.entryId\n state.entryId++\n }",
"addToCache(key, value) {\n assert.isString(key)\n this._cache[key] = value\n }",
"addEntryView(entryView) {\n const entry = entryView.model;\n\n this._entryViews.push(entryView);\n this._entryViewsByID[entry.id] = entryView;\n this.model.addEntry(entry);\n\n if (this._rendered) {\n entryView.render();\n }\n }",
"function addBodyToCache(state_obj) {\n var added = false;\n\n if (conf.cache < 0) {\n url_cache[state_obj.url] = state_obj.body;\n added = true;\n }\n\n else if (conf.cache > 0) {\n var cache_size = Object.keys(url_cache).length;\n\n if (cache_size < conf.cache) {\n url_cache[state_obj.url] = state_obj.body;\n added = true;\n }\n\n else if (cache_size >= conf.cache) {\n var n = (cache_size - conf.cache) + 1;\n\n if (conf.log) {\n console.log(\"Removing entries from cache: over limit by \"+n+\".\");\n }\n\n for (var o = 0; o < n; o++) {\n var key = Object.keys(url_cache).shift();\n delete url_cache[key];\n }\n }\n }\n\n else {\n if (conf.log) {\n console.log(\"Cache limit is 0. Not adding entry to cache for '\"+state_obj.url+\"'.\");\n }\n }\n\n if (added && conf.log) {\n console.log(\"Adding entry to cache for '\"+state_obj.url+\"'.\");\n console.log(\"Current cache:\");\n console.log(url_cache);\n }\n }",
"static addToCache(uri, texture) {\n if (!RCTPrefetch.cache) {\n RCTPrefetch.cache = {};\n }\n\n const key = RCTPrefetch.uriKey(uri);\n if (!RCTPrefetch.cache[key]) {\n texture.__prefetchKey = key;\n RCTPrefetch.cache[key] = {\n refs: 1,\n texture: texture,\n };\n } else {\n RCTPrefetch.cache[key].refs++;\n }\n }",
"static add(entry, type = null){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'add', kparams);\n\t}",
"function addToCache( distillation ) {\n\n\t\tvar cache = window.localStorage.getItem( \"cache\" );\n\t\tif ( cache == null || cache == \"null\" ) {\n\t\t\tcache = [];\n\t\t}\n\t\telse {\n\t\t\tcache = JSON.parse( cache );\n\t\t\tcache.push( distillation );\n\t\t}\n\n\t\twindow.localStorage.setItem( \"cache\", JSON.stringify( cache ) );\n\t}",
"add(location, {setIndexToHead = true, message} = {}) {\n const newEntry = new Entry(location)\n if (atom.config.get(\"cursor-history.keepSingleEntryPerBuffer\")) {\n const isSameURI = entry => newEntry.URI === entry.URI\n this.entries.filter(isSameURI).forEach(destroyEntry)\n } else {\n const isAtSameRow = entry => newEntry.isAtSameRow(entry)\n this.entries.filter(isAtSameRow).forEach(destroyEntry)\n }\n\n this.entries.push(newEntry)\n\n if (setIndexToHead) {\n this.setIndexToHead()\n }\n if (atom.config.get(\"cursor-history.debug\") && message) {\n this.log(message)\n }\n }",
"function updateCache(id, status, content)\r\n {\r\n // set cache if preview was created\r\n switch (status)\r\n {\r\n // delete cache entry that the request is done again\r\n case STATUS_PENDING:\r\n delete cache[id];\r\n break;\r\n\r\n // cache response\r\n case STATUS_CREATED:\r\n case STATUS_FAILED:\r\n case STATUS_NONE:\r\n default:\r\n cache[id] = content;\r\n break;\r\n }\r\n }",
"function updateCache() {\n request('https://hypno.nimja.com/app', function (error, response, body) {\n if (error) {\n console.log(error);\n }\n var data = JSON.parse(body);\n if (data) {\n cache = data;\n parseCacheForSearchAndLookup();\n }\n });\n}",
"static addContent(entryId, resource){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.resource = resource;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'addContent', kparams);\n\t}",
"function addKeyHit(key) {\n if (debug)\n console.log('varcache: Recorded hit on key: \"' + key + '\".');\n\n hitCount++;\n\n if (typeof hitLog[key] === 'undefined')\n hitLog[key] = [];\n\n hitLog[key].push(new Date());\n}",
"static add(entryDistribution){\n\t\tlet kparams = {};\n\t\tkparams.entryDistribution = entryDistribution;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_entrydistribution', 'add', kparams);\n\t}",
"function addKioskEntry(cacheinfo, atomurl) {\n\tif (isKiosk()) {\n\t\t// kiosk.html is this page\n\t\t// relative ref\n\t\tvar baseurl = location.href;\n\t\tvar ix = baseurl.lastIndexOf('/');\n\t\tif (ix>=0)\n\t\t\tbaseurl = baseurl.substring(0,ix+1);\n\n\t\tindex = entries.length;\n\t\tvar entry = { title: \"Kiosk View\", \n\t\t\t\ticonurl: \"icons/kiosk.png\",\n\t\t\t\ticonpath: \"icons/kiosk.png\",\n\t\t\t\tsummary: \"Browse the same content directly on your device\", \n\t\t\t\tindex: index, \n\t\t\t\tprefix: baseurl, \n\t\t\t\t// note: using baseurl from given atomfile/global for internet fallback\n\t\t\t\tcacheinfo: cacheinfo };\n\t\t// TODO atomfile - is as loaded by kiosk, typically from local file system.\n\t\t// for internet version we know it should be in the same basedir;\n\t\t// but for local it is a file rather than a resource, so we'll need to fix/fiddle this!\n\t\t//var url = \"kiosk.html?f=\"+encodeURIComponent(getExternalUrl(atomurl));\n\t\tvar enc = { url: \"kiosk.html\", mime: \"text/html\", path: \"kiosk.html\", atomurl: atomurl };\n\t\tentry.enclosures = [enc];\n\t\tentry.requiresDevice = [];\n\t\tentries[index] = entry;\n\t\tentry.supportsMime = [];\t\n\t}\n}",
"replaceEntry (state, args) {\n const cache = state.cache[args.property]\n const turn = state.turns[cache.turn]\n let position\n\n turn.forEach(function (entry, index) {\n if (entry.entryId == cache.entryId) {\n position = index\n }\n })\n\n turn.splice(position, 1, args.entry)\n }",
"static add(entry){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'add', kparams);\n\t}",
"static update(id, entry){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.entry = entry;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'update', kparams);\n\t}",
"getEntry(t, e) {\n this.assertNotApplied();\n const n = this.changes.get(e);\n return void 0 !== n ? Ks.resolve(n.document) : this.getFromCache(t, e);\n }",
"_doubleEntriesSizeAndRehashEntries() {\n const entries = this._entries;\n const oldLength = this._entryRange;\n const newLength = oldLength * 2;\n //Reset the values\n this._entries = new Array(newLength);\n this._entryRange = newLength;\n this._spaceTaken = 0;\n for (let entry of entries) {\n if(!entry) {\n //Make sure we skip empty entries\n continue;\n }\n //Re-insert each entry back into the map\n this.addEntry(entry.key, entry.value);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
"A requestpath pathmatches a given cookiepath if at least one of the following conditions holds:" | function pathMatch (reqPath, cookiePath) {
// "o The cookie-path and the request-path are identical."
if (cookiePath === reqPath) {
return true;
}
var idx = reqPath.indexOf(cookiePath);
if (idx === 0) {
// "o The cookie-path is a prefix of the request-path, and the last
// character of the cookie-path is %x2F ("/")."
if (cookiePath.substr(-1) === "/") {
return true;
}
// " o The cookie-path is a prefix of the request-path, and the first
// character of the request-path that is not included in the cookie- path
// is a %x2F ("/") character."
if (reqPath.substr(cookiePath.length, 1) === "/") {
return true;
}
}
return false;
} | [
"function matchPath(ctx) {\n const pathname = parseurl_1.default(ctx).pathname;\n const cookiePath = cookieOptions.path || \"/\";\n if (cookiePath === \"/\") {\n return true;\n }\n if (pathname.indexOf(cookiePath) !== 0) {\n // cookie path not match\n return false;\n }\n return true;\n }",
"function pathsMatch(restrictedPath, path) {\n if (restrictedPath.length !== path.length) {\n return false;\n }\n for(var i = 0; i < restrictedPath.length; i++) {\n if (restrictedPath[i] !== path[i] && restrictedPath[i] !== '*') {\n return false;\n }\n }\n return true;\n }",
"function isPath(path) {\n\treturn path === window.location.pathname.slice(-path.length);\n}",
"isUrlInBasePaths(request) {\n const url = request.url.toLowerCase();\n const path = this.basePaths.find(path => url.startsWith(path));\n return Boolean(path);\n }",
"function isValidObjectPath(path) {\n return path.match(/^(\\/$)|(\\/[A-Za-z0-9_]+)+$/);\n}",
"checkForValidTokenPath(validTokens) {\n const pathName = window.location.pathname.replace('/', '');\n\n if (!pathName) {\n return;\n }\n\n if (validTokens.includes(pathName)) {\n this.getTokenDetails(pathName, this.state.lookupDate);\n }\n else {\n window.history.pushState({}, null, '/');\n this.setState({ renderDashboard: false });\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 }",
"function validatePath(path) {\n if ( path == \"\" ) {\n return 1;\n\t} else if (/^disk[0-2]|disk$/.test(path) == true || /^slot[0-1]$/.test(path) == true || /^NVRAM$/.test(path) == true || /^bootflash$/.test(path) == true || /^flash[0-1]|flash$/.test(path) == true) {\n return 0;\n } else {\n var pathArr = path.split(\"\\/\");\n var isinvalid = 0;\n for (var x = 0 ; x < pathArr.length; x++) {\n if (/^[a-z|A-Z][0-9|a-z|\\-|\\_|A-Z|\\.]+$/.test(pathArr[x]) == false) {\n isinvalid = 1;\n }\n }\n return isinvalid;\n }\n}",
"function checkCookieHost(cookie, host)\n{\n var domainPrefix = \".\";\n if (cookie.host.slice(0, domainPrefix.length) == domainPrefix) {\n if (cookie.host.substring(1) != host) {\n if (host.slice(-cookie.host.length) != cookie.host) {\n return false;\n }\n }\n }\n else {\n if (host != cookie.host) {\n if (0 == host.length) {\n return true;\n }\n return false;\n }\n }\n return true;\n}",
"static checkPathForAllNodes(stationMap, path) {\n const pathSet = new Set(path);\n if (pathSet.size === stationMap.size) {\n console.log('All stations are included in the path');\n } else {\n console.log('There are only ' + pathSet.size + ' stations in the path.');\n }\n }",
"function CfnRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}",
"isPath(value) {\n return Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number');\n }",
"function CfnGatewayRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}",
"function CookieUtilities_surveyCookieExists(cookieType)\n {\n var t = '';\n if (cookieType) t = cookieType;\n \n return (document.cookie.indexOf(SiteRecruit_Config.cookieName + '=' + t) != -1)\n }",
"millPathHasIntersection(millPath, i) {\n return (millPath[0] === i || millPath[1] === i || millPath[2] === i);\n }",
"function isHttpEndpoint(pathname) {\n for (let index in httpEndpoints) {\n if (httpEndpoints[index][0] == pathname) {\n return true;\n }\n }\n return false;\n}",
"redirectIfRolloverActive(path) {\n var onBusinessPage = path.indexOf(Constant.BUSINESS_PORTAL_PATHNAME) === 0;\n var onRolloverPage = path === Constant.ROLLOVER_PATHNAME;\n if (onBusinessPage || onRolloverPage) {\n return;\n }\n\n var { user } = this.props;\n if (!user.district) {\n return;\n }\n\n const districtId = user.district.id;\n Api.getRolloverStatus(districtId).then(() => {\n const status = this.props.lookups.rolloverStatus;\n\n if (status.rolloverActive) {\n this.props.history.push(Constant.ROLLOVER_PATHNAME);\n } else if (status.rolloverComplete) {\n // refresh fiscal years\n Api.getFiscalYears(districtId);\n }\n });\n }",
"function isDelayEndpoint(pathname) {\n for (let index in delayEndpoints) {\n if (delayEndpoints[index][0] == pathname) {\n return true;\n }\n }\n return false;\n}",
"equals(path, another) {\n return path.length === another.length && path.every((n, i) => n === another[i]);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return minimum cost to reach top step after you pay the cost of a given step you can move 1 or 2 steps you can start from zeroeth or 1st step | function min_cost_stairs(costs) {
const priceSums = new Array(costs.length).fill(0);
priceSums[0] = costs[0];
priceSums[1] = costs[1];
for(let i = 2; i < priceSums.length; i++) {
priceSums[i] = costs[i] + Math.min(priceSums[i - 1], priceSums[i - 2]);
}
return Math.min(priceSums[priceSums.length - 1], priceSums[priceSums.length - 2]);
} | [
"function minCostToClimbStairs(n, price) {\n const dp = new Array(n + 1).fill(0);\n dp[0] = 0;\n dp[1] = price[0];\n\n for (let i = 2; i <= n; i++) {\n dp[i] = price[i-1] + Math.min(dp[i - 1], dp[i - 2]);\n }\n\n return dp[n];\n}",
"calculateTravelCost(previous, next) {\n if (next.row !== previous.row && next.col !== previous.col) {\n return 14;\n }\n return 10;\n }",
"getNearestTime (step, time) {\n\t\tlet prev = this.getPreviousTime(step, time);\n\t\tlet next = this.getNextTime(step, time);\n\t\tif (time - prev <= next - time)\n\t\t\treturn prev;\n\t\treturn next;\n\t}",
"addpathcost(q, x) { this.dmin(q, this.dmin(q) + x); }",
"getMincosts() {\n\t\tlet mincost = new Float32Array(this.n+1);\n\t\tlet q = new List(this.n);\n\t\tfor (let r = 1; r <= this.n; r++) {\n\t\t\tif (this.p(r)) continue;\n\t\t\tq.enq(r);\n\t\t\twhile (!q.empty()) {\n\t\t\t\tlet u = q.deq();\n\t\t\t\tmincost[u] = (this.p(u) ? mincost[this.p(u)] : 0)\n\t\t\t\t\t\t\t + this.#dmin[u];\n\t\t\t\tif (this.left(u)) q.enq(this.left(u));\n\t\t\t\tif (this.right(u)) q.enq(this.right(u));\n\t\t\t}\n\t\t}\n\t\treturn mincost;\n\t}",
"docosts1(u,cost) {\n\t\tlet l = this.left(u); let r = this.right(u);\n\t\tlet mc = cost[u];\n\t\tif (l) {\n\t\t\tthis.docosts1(l,cost);\n\t\t\tmc = Math.min(mc, this.#dmin[l]);\n\t\t}\n\t\tif (r) {\n\t\t\tthis.docosts1(r,cost);\n\t\t\tmc = Math.min(mc, this.#dmin[r]);\n\t\t}\n\t\tthis.#dcost[u] = cost[u] - mc;\n\t\tthis.#dmin[u] = mc; // adjust this in second phase\n\t}",
"function calcBestMove(game) {\n var engine = new UCI(STOCK_PATH);\n var deferred = Q.defer();\n\n engine.runProcess().then(function () {\n return engine.uciCommand();\n\n }).then(function (idAndOptions) {\n return engine.isReadyCommand();\n\n }).then(function () {\n return engine.uciNewGameCommand();\n\n }).then(function () {\n return engine.positionCommand(game.fen());\n\n }).then(function () {\n return engine.goInfiniteCommand(console.log);\n\n }).delay(500).then(function () {\n return engine.stopCommand();\n\n }).then(function (bestMove) {\n //TODO: Maybe need to translate this to a correct {to, from} dictionary. Maybe not\n deferred.resolve(bestMove);\n\n return engine.quitCommand();\n\n }).then(function () {\n console.log('Stopped');\n }).fail(function (error) {\n console.log(error);\n deferred.reject(error);\n process.exit();\n }).done();\n\n return deferred.promise;\n}",
"getOrderMinAmount() {\n const { amount, presets } = this.getTier() || {};\n if (isNil(amount) && isNil(presets)) return 0;\n return min(isNil(amount) ? presets : [...(presets || []), amount]);\n }",
"function differenceFromMinimum(costs) {\n var min = costs[1];\n for (var i = 0; i < costs.length; i++) {\n if (costs[i] < min[1]) {\n min = costs[i];\n }\n }\n for (var i = 0; i < costs.length; i++) {\n costs[i] -= min;\n }\n return costs;\n}",
"function findInitialEstimate(x) {\r\n\t\t\r\n\t\t// Until the v0 barely undershoots the goal\r\n\t\tfor (var v0 = Math.ceil(MAX_VEL); v0 - 0.5 >= 0; v0 -= 0.5) {\r\n\t\t\tvar y = f(v0, x);\r\n\t\t\t\r\n\t\t\t// When the error is finally negative\r\n\t\t\tif (y < 0) {\r\n\t\t\t\treturn v0;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t// If nothing works, 9 is good enough\r\n\t\treturn 9;\r\n\t}",
"function smallestCostMerge(t) {\n let cheapestStart = -1;\n let cheapestCost = Infinity;\n let replacement = [];\n\n for (let i = 0; i < t.length - 1; i++) {\n const [startA, endA] = t[i];\n const [startB, endB] = t[i + 1];\n const originalProfit = (endB - startB) + (endA - startA);\n const [BA, AA, BB] = [endB - startA, endA - startA, endB - startB];\n\n if (BA > AA && BA > BB) {\n const cost = originalProfit - BA;\n if (cost < cheapestCost) {\n cheapestStart = i;\n cheapestCost = cost;\n replacement = [startA, endB];\n }\n } else if (AA > BB) {\n const cost = originalProfit - AA;\n if (cost < cheapestCost) {\n cheapestStart = i;\n cheapestCost = cost;\n replacement = [startA, endA];\n }\n } else {\n const cost = originalProfit - BB;\n if (cost < cheapestCost) {\n cheapestStart = i;\n cheapestCost = cost;\n replacement = [startB, endB];\n }\n }\n }\n\n t.splice(cheapestStart, 2, replacement);\n\n return cheapestCost;\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 }",
"bestFirstSearch(){\n var heapOpen = new SortedList(comparer);\n var heapClosed = new SortedList(comparer);\n heapOpen.add(this.frontier);\n while(heapOpen.getCount() > 0){\n ITERATIONS++;\n var V = heapOpen.popFirst();\n MINPRIORITY = V.priority;\n V.generateStates();\n redraw();\n if(V.hash == 87654321){\n this.endPoint = V;\n break;\n }\n for(var i = 0 ; i < V.children.length; i++){\n V.children[i].priority = V.children[i].manhattanHeuristic() + V.children[i].outOfPlaceTilesHeuristic(); \n if(hasBetter(heapOpen,V.children[i].hash, V.children[i].priority)){\n continue;\n }\n if(hasBetter(heapClosed,V.children[i].hash, V.children[i].priority)){\n continue;\n }\n heapOpen.add(V.children[i]);\n }\n heapClosed.add(V);\n }\n heapOpen.clear();\n heapClosed.clear();\n return this.createSolution(this.endPoint);\n }",
"function s(triangle) {\n // find min path sum to bottom\n // for index i, can only move to i or i + 1 of next row\n\n const dp = JSON.parse(JSON.stringify(triangle));\n let n = triangle.length - 2;\n for (let i = n; i >= 0; i--) {\n for (let j = 0; j < dp[i].length; j++) {\n dp[i][j] += Math.min(dp[i + 1][j], Math.min(dp[i + 1][j + 1]));\n }\n }\n return dp[0][0];\n}",
"function findMinMoves(arr){\n //sort array\n let result = 0;\n arr = arr.sort((a,b) => {return a-b});\n // take the middle index element and make other elements equal that by incremeneting\n let midVal = arr[Math.ceil((arr.length-1) /2)];\n for(let i = 0; i < arr.length; i++) {\n result += Math.abs(midVal - arr[i]);\n }\n return result\n}",
"findMinRaiseAmount(lineup, dealer, lastRoundMaxBet, state) {\n if (!lineup || dealer === undefined) {\n throw new Error('invalid params.');\n }\n const lastRoundMaxBetInt = parseInt(lastRoundMaxBet, 10);\n // TODO: pass correct state\n const max = this.getMaxBet(lineup, state);\n if (max.amount === lastRoundMaxBetInt) {\n throw new Error('can not find minRaiseAmount.');\n }\n // finding second highest bet\n let secondMax = lastRoundMaxBetInt;\n for (let i = max.pos + 1; i < lineup.length + max.pos; i += 1) {\n const pos = i % lineup.length;\n const last = (lineup[pos].last) ? this.rc.get(lineup[pos].last).amount.toNumber() : 0;\n if (last > secondMax && last < max.amount) {\n secondMax = last;\n }\n }\n return max.amount - secondMax;\n }",
"function makeBestMove() {\n\t\t\t// look for winning move\n\t\t\t//then findBestCorner();\n\t}",
"function MiniGameChessStart(Depth) {\n\t\n\tvar MinMaxDepth = Depth;\n\t\t\n\t/**\n\t * Finds a random move to make\n\t * @return {string} move to make\n\t */\n\tvar randomMove = function() {\n\t var possibleMoves = game.moves();\n\t var randomIndex = Math.floor(Math.random() * possibleMoves.length);\n\t return possibleMoves[randomIndex];\n\t};\n\n\t/**\n\t * Evaluates current chess board relative to player\n\t * @param {string} color - Players color, either 'b' or 'w'\n\t * @return {Number} board value relative to player\n\t */\n\tvar evaluateBoard = function(board, color) {\n\t // Sets the value for each piece using standard piece value\n\t var pieceValue = {\n\t\t'p': 100,\n\t\t'n': 350,\n\t\t'b': 350,\n\t\t'r': 525,\n\t\t'q': 1000,\n\t\t'k': 10000\n\t };\n\n\t // Loop through all pieces on the board and sum up total\n\t var value = 0;\n\t board.forEach(function(row) {\n\t\trow.forEach(function(piece) {\n\t\t if (piece) {\n\t\t\t// Subtract piece value if it is opponent's piece\n\t\t\tvalue += pieceValue[piece['type']]\n\t\t\t\t\t * (piece['color'] === color ? 1 : -1);\n\t\t }\n\t\t});\n\t });\n\n\t return value;\n\t};\n\n\t/**\n\t * Calculates the best move looking one move ahead\n\t * @param {string} playerColor - Players color, either 'b' or 'w'\n\t * @return {string} the best move\n\t */\n\tvar calcBestMoveOne = function(playerColor) {\n\t // List all possible moves\n\t var possibleMoves = game.moves();\n\t // Sort moves randomly, so the same move isn't always picked on ties\n\t possibleMoves.sort(function(a, b){return 0.5 - Math.random()});\n\n\t // exit if the game is over\n\t if (game.game_over() === true || possibleMoves.length === 0) return;\n\n\t // Search for move with highest value\n\t var bestMoveSoFar = null;\n\t var bestMoveValue = Number.NEGATIVE_INFINITY;\n\t possibleMoves.forEach(function(move) {\n\t\tgame.move(move);\n\t\tvar moveValue = evaluateBoard(game.board(), playerColor);\n\t\tif (moveValue > bestMoveValue) {\n\t\t bestMoveSoFar = move;\n\t\t bestMoveValue = moveValue;\n\t\t}\n\t\tgame.undo();\n\t });\n\n\t return bestMoveSoFar;\n\t}\n\n\t/**\n\t * Calculates the best move using Minimax without Alpha Beta Pruning.\n\t * @param {Number} depth - How many moves ahead to evaluate\n\t * @param {Object} game - The game to evaluate\n\t * @param {string} playerColor - Players color, either 'b' or 'w'\n\t * @param {Boolean} isMaximizingPlayer - If current turn is maximizing or minimizing player\n\t * @return {Array} The best move value, and the best move\n\t */\n\tvar calcBestMoveNoAB = function(depth, game, playerColor,\n\t\t\t\t\t\t\t\t\tisMaximizingPlayer=true) {\n\t // Base case: evaluate board\n\t if (depth === 0) {\n\t\tvalue = evaluateBoard(game.board(), playerColor);\n\t\treturn [value, null]\n\t }\n\n\t // Recursive case: search possible moves\n\t var bestMove = null; // best move not set yet\n\t var possibleMoves = game.moves();\n\t // Set random order for possible moves\n\t possibleMoves.sort(function(a, b){return 0.5 - Math.random()});\n\t // Set a default best move value\n\t var bestMoveValue = isMaximizingPlayer ? Number.NEGATIVE_INFINITY\n\t\t\t\t\t\t\t\t\t\t\t : Number.POSITIVE_INFINITY;\n\t // Search through all possible moves\n\t for (var i = 0; i < possibleMoves.length; i++) {\n\t\tvar move = possibleMoves[i];\n\t\t// Make the move, but undo before exiting loop\n\t\tgame.move(move);\n\t\t// Recursively get the value of this move\n\t\tvalue = calcBestMoveNoAB(depth-1, game, playerColor, !isMaximizingPlayer)[0];\n\t\t// Log the value of this move\n\t\t//console.log(isMaximizingPlayer ? 'Max: ' : 'Min: ', depth, move, value, bestMove, bestMoveValue);\n\n\t\tif (isMaximizingPlayer) {\n\t\t // Look for moves that maximize position\n\t\t if (value > bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t} else {\n\t\t // Look for moves that minimize position\n\t\t if (value < bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t}\n\t\t// Undo previous move\n\t\tgame.undo();\n\t }\n\t // Log the best move at the current depth\n\t //console.log('Depth: ' + depth + ' | Best Move: ' + bestMove + ' | ' + bestMoveValue);\n\t // Return the best move, or the only move\n\t return [bestMoveValue, bestMove || possibleMoves[0]];\n\t}\n\n\t/**\n\t * Calculates the best move using Minimax with Alpha Beta Pruning.\n\t * @param {Number} depth - How many moves ahead to evaluate\n\t * @param {Object} game - The game to evaluate\n\t * @param {string} playerColor - Players color, either 'b' or 'w'\n\t * @param {Number} alpha\n\t * @param {Number} beta\n\t * @param {Boolean} isMaximizingPlayer - If current turn is maximizing or minimizing player\n\t * @return {Array} The best move value, and the best move\n\t */\n\tvar calcBestMove = function(depth, game, playerColor,\n\t\t\t\t\t\t\t\talpha=Number.NEGATIVE_INFINITY,\n\t\t\t\t\t\t\t\tbeta=Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t\t\tisMaximizingPlayer=true) {\n\t // Base case: evaluate board\n\t if (depth === 0) {\n\t\tvalue = evaluateBoard(game.board(), playerColor);\n\t\treturn [value, null]\n\t }\n\n\t // Recursive case: search possible moves\n\t var bestMove = null; // best move not set yet\n\t var possibleMoves = game.moves();\n\t // Set random order for possible moves\n\t possibleMoves.sort(function(a, b){return 0.5 - Math.random()});\n\t // Set a default best move value\n\t var bestMoveValue = isMaximizingPlayer ? Number.NEGATIVE_INFINITY\n\t\t\t\t\t\t\t\t\t\t\t : Number.POSITIVE_INFINITY;\n\t // Search through all possible moves\n\t for (var i = 0; i < possibleMoves.length; i++) {\n\t\tvar move = possibleMoves[i];\n\t\t// Make the move, but undo before exiting loop\n\t\tgame.move(move);\n\t\t// Recursively get the value from this move\n\t\tvalue = calcBestMove(depth-1, game, playerColor, alpha, beta, !isMaximizingPlayer)[0];\n\t\t// Log the value of this move\n\t\t//console.log(isMaximizingPlayer ? 'Max: ' : 'Min: ', depth, move, value, bestMove, bestMoveValue);\n\n\t\tif (isMaximizingPlayer) {\n\t\t // Look for moves that maximize position\n\t\t if (value > bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t alpha = Math.max(alpha, value);\n\t\t} else {\n\t\t // Look for moves that minimize position\n\t\t if (value < bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t beta = Math.min(beta, value);\n\t\t}\n\t\t// Undo previous move\n\t\tgame.undo();\n\t\t// Check for alpha beta pruning\n\t\tif (beta <= alpha) {\n\t\t //console.log('Prune', alpha, beta);\n\t\t break;\n\t\t}\n\t }\n\t // Log the best move at the current depth\n\t //console.log('Depth: ' + depth + ' | Best Move: ' + bestMove + ' | ' + bestMoveValue + ' | A: ' + alpha + ' | B: ' + beta);\n\t // Return the best move, or the only move\n\t return [bestMoveValue, bestMove || possibleMoves[0]];\n\t}\n\n\t// Computer makes a move with algorithm choice and skill/depth level\n\tvar makeMove = function(algo, skill=3) {\n\t // exit if the game is over\n\t if (game.game_over() === true) {\n\t\t//console.log('game over');\n\t\treturn;\n\t }\n\t // Calculate the best move, using chosen algorithm\n\t if (algo === 1) {\n\t\tvar move = randomMove();\n\t } else if (algo === 2) {\n\t\tvar move = calcBestMoveOne(game.turn());\n\t } else if (algo === 3) {\n\t\tvar move = calcBestMoveNoAB(skill, game, game.turn())[1];\n\t } else {\n\t\tvar move = calcBestMove(skill, game, game.turn())[1];\n\t }\n\t // Make the calculated move\n\t game.move(move);\n\t // Update board positions\n\t board.position(game.fen());\n\t}\n\n\t// Computer vs Computer\n\tvar playGame = function(algo=4, skillW=2, skillB=2) {\n\t if (game.game_over() === true) {\n\t\t//console.log('game over');\n\t\treturn;\n\t }\n\t var skill = game.turn() === 'w' ? skillW : skillB;\n\t makeMove(algo, skill);\n\t window.setTimeout(function() {\n\t\tplayGame(algo, skillW, skillB);\n\t }, 250);\n\t};\n\n\t// Handles what to do after human makes move.\n\t// Computer automatically makes next move\n\tvar onDrop = function(source, target) {\n\t // see if the move is legal\n\t var move = game.move({\n\t\tfrom: source,\n\t\tto: target,\n\t\tpromotion: 'q' // NOTE: always promote to a queen for example simplicity\n\t });\n\n\t // If illegal move, snapback\n\t if (move === null) return 'snapback';\n\n\t // Log the move\n\t //console.log(move)\n\n\t // make move for black\n\t window.setTimeout(function() {\n\t\tmakeMove(4, MinMaxDepth);\n\t }, 200);\n\t};\n\n\tvar board,\n\t\tgame = new Chess();\n\n\t// Actions after any move\n\tvar onMoveEnd = function(oldPos, newPos) {\n\t // Alert if game is over\n\t if (game.game_over() === true) {\n\t\t//alert('Game Over');\n\t\t//console.log('Game Over');\n\t }\n\n\t // Log the current game position\n\t //console.log(game.fen());\n\t};\n\n\t// Check before pick pieces that it is white and game is not over\n\tvar onDragStart = function(source, piece, position, orientation) {\n\t if (game.game_over() === true || piece.search(/^b/) !== -1) {\n\t\treturn false;\n\t }\n\t};\n\n\t// Update the board position after the piece snap\n\t// for castling, en passant, pawn promotion\n\tvar onSnapEnd = function() {\n\t board.position(game.fen());\n\t};\n\n\t// Creates the board div\n\tif (document.getElementById(\"DivChessBoard\") == null) {\n\t\tvar div = document.createElement(\"div\");\n\t\tdiv.setAttribute(\"ID\", \"DivChessBoard\");\n\t\tdiv.className = \"HideOnDisconnect\";\n\t\tdiv.style.width = \"600px\";\n\t\tdiv.style.height = \"600px\";\n\t\tdocument.body.appendChild(div);\n\t}\n\n\t// Configure the board\n\tvar cfg = {\n\t draggable: true,\n\t position: 'start',\n\t // Handlers for user actions\n\t onMoveEnd: onMoveEnd,\n\t onDragStart: onDragStart,\n\t onDrop: onDrop,\n\t onSnapEnd: onSnapEnd\n\t}\n\tboard = ChessBoard('DivChessBoard', cfg);\n\n\t// Resets the board and shows it\n\tboard.clear();\n\tboard.start();\n\tgame.reset();\n\tMiniGameChessResize();\n\tMiniGameChessBoard = board;\n\tMiniGameChessGame = game;\n\n}",
"minimax(newBoard, player) {\n let unvisitedCells = newBoard.unvisitedCells();\n\n if (this.checkWinner(newBoard, this.humanPlayer.identifier)) {\n return { score: -10 };\n } else if (this.checkWinner(newBoard, this.computerPlayer.identifier)) {\n return { score: 10 };\n } else if (unvisitedCells.length === 0) {\n return { score: 0 };\n }\n\n let moves = [];\n for (let i = 0; i < unvisitedCells.length; i++) {\n let move = {};\n move.index = newBoard.board[unvisitedCells[i]];\n newBoard.board[unvisitedCells[i]] = player;\n\n if (player === this.computerPlayer.identifier) {\n let result = this.minimax(newBoard, this.humanPlayer.identifier);\n move.score = result.score;\n } else {\n let result = this.minimax(newBoard, this.computerPlayer.identifier);\n move.score = result.score;\n }\n\n newBoard.board[unvisitedCells[i]] = move.index;\n\n moves.push(move);\n }\n\n let bestMove;\n if (player === this.computerPlayer.identifier) {\n let bestScore = -Infinity;\n for (let i = 0; i < moves.length; i++) {\n if (moves[i].score > bestScore) {\n bestScore = moves[i].score;\n bestMove = i;\n }\n }\n } else {\n let bestScore = Infinity;\n for (let i = 0; i < moves.length; i++) {\n if (moves[i].score < bestScore) {\n bestScore = moves[i].score;\n bestMove = i;\n }\n }\n }\n\n return moves[bestMove];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
==================================== Stream Receiver ==================================== | function stream_receiver(payload) {
payload.m.forEach( ( msg, num ) => {
streamary.push(msg);
if (streamary.length > streamlim ) streamary.shift();
} );
} | [
"function onReceiveStream(stream, elementID){\n var video = $('#' + elementID + ' video')[0];\n console.log(video);\n video.src = window.URL.createObjectURL(stream);\n }",
"EnumerateStreams() {\n\n }",
"readStream(){\n redis.consumeFromQueue(config.EVENTS_STREAM_CONSUMER_GROUP_NAME, this.consumerId, 1, config.EVENTS_STREAM_NAME, false, (err, messages) => {\n if (err) {\n this.logger.warn(`Failed to read events. ${err.message}`);\n }\n\n if (messages){\n this.logger.log('Received message from event stream.');\n\n this.processMessages(messages);\n }\n\n setTimeout(()=>{\n this.readStream();\n }, 1000);\n });\n }",
"_read() {\n if (this.index <= this.array.length) {\n //getting a chunk of data\n const chunk = {\n data: this.array[this.index],\n index: this.index\n };\n //we want to push chunks of data into the stream\n this.push(chunk);\n this.index += 1;\n } else {\n //pushing null wil signal to stream its done\n this.push(null);\n }\n }",
"function onStreamActive(stream, handler) {\n stream.once('data', handler)\n}",
"function remoteStreamCallback(e) \n {\n scope.remoteStream = e.stream;\n if(scope.onRemoteStream)\n {\n scope.onRemoteStream(scope.remoteStream);\n }\n }",
"streamHandshakeHandler(msg) {\n\n // Also his only role is to receive the message and log it. It doesn't even\n // do anything useful with it. Gods what a stupid handler.\n console.log(JSON.parse(msg.data));\n\n let start_msg = {\n \"client_id\": this.id,\n \"rover_id\": this.currentRoverId,\n \"cmd\": \"start\"\n };\n\n this.sendStreamMsg(start_msg);\n\n this.player = new jsmpeg(this.stream_socket, {canvas: this.canvas, autoplay: true});\n\n // Call the onopen as if nothing happened\n this.player.initSocketClient.bind(this.player)(null);\n }",
"async function onProcMsg(msg) {\n msg = msg.toString()\n\n // log the stdout line\n this.logLine(msg)\n\n /* \n * STREAMLINK EVENTS\n */\n\n // Handle Streamlink Events: No stream found, stream ended\n\n REGEX_NO_STREAM_FOUND.lastIndex = 0\n REGEX_NO_CHANNEL.lastIndex = 0\n REGEX_STREAM_ENDED.lastIndex = 0\n\n if (REGEX_NO_STREAM_FOUND.test(msg)) {\n ipcServer.ipcSend(\n 'streamlink-event',\n Result.newError(\n `${msg}`,\n '@ StreamlinkInstance stdout'\n )\n )\n\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n return\n \n }\n\n if (REGEX_NO_CHANNEL.test(msg)) {\n ipcServer.ipcSend(\n 'streamlink-event',\n Result.newError(\n `${msg}`,\n '@ StreamlinkInstance stdout'\n )\n )\n\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n return\n }\n\n if (REGEX_STREAM_ENDED.test(msg)) {\n // send streamlink event on stream end event.\n // disabled for now; don't want a toast notification every\n // time a player is closed.\n //\n // ipcServer.ipcSend(\n // 'streamlink-event',\n // Result.newOk(`Stream ${this.channelName} closed`)\n // )\n\n ipcServer.ipcSend('streamlink-stream-closed', this.channelName)\n\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n return\n }\n\n // Handle Streamlink Event: Invalid quality\n\n // match invalid quality option message.\n // use the available qualities list that is printed by streamlink to\n // decide on & launch the closest available stream quality to the user's preference.\n // eg. if available stream qualities are [480p, 720p, 1080p] and user's preference\n // is set to '900p', we'll look through the list, find that 720p is the\n // closest without going over, and attempt to launch at that quality instead of\n // failing to open anything.\n REGEX_STREAM_INVALID_QUALITY.lastIndex = 0\n if (REGEX_STREAM_INVALID_QUALITY.test(msg)) {\n // first, close the existing stream instance\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n\n \n // match available qualities line\n // index 0 is the full match - contains both of the following groups\n // index 1 is group 1, always the string \"Available streams: \"\n // index 2 is group 2, string list of qualities. eg:\n // \"audio_only, 160p (worst), 360p, 480p, 720p60, etc...\"\n REGEX_AVAILABLE_QUALITIES.lastIndex = 0\n let availableQualMatch = REGEX_AVAILABLE_QUALITIES.exec(msg)\n\n // this shouldnt happen, but if it does, for now just fail\n if (availableQualMatch == null) {\n console.error('Err: availableQualMatch is null or undefined; no available quality options to choose from')\n return\n }\n\n // full match (string list of qualities) lives at index 2\n // turn it into an array of quality strings.\n // eg ['audio_only', '160p (worst)', '360p', '480p', '720p60', etc...]\n let availableStrs = availableQualMatch[2].split(', ')\n\n // build arrays of resolutions and framerates out of each quality string.\n // framerates default to 30 if not specified (eg a quality string of '480p'\n // will be represented in the arrays as [480] [30] - the indices will line up)\n let availableResolutions = []\n let availableFramerates = []\n\n availableStrs.forEach(qual => {\n // return the resolution string (match array index 0) if a match is found,\n // otherwise use the number 0 for the resolution and framerate if no match is found.\n\n // This is to turn things like 'audio_only' into an integer that we can easily ignore later,\n // but lets us keep the length and indicies of the availableResolutions array the\n // same as availableStrs so they line up as expected (as we'll need to access data\n // from availableStrs later).\n\n // match resolution string (and framerate string, if available) from quality string.\n // if match is null, no resolution or framerate were found.\n // match index 0 holds resolution string, index 1 holds framerate.\n // \n // example matches:\n // 'audio_only' -> null\n // '480p' -> ['480']\n // '1080p60' -> ['1080', '60']\n let m = qual.match(REGEX_NUMBERS_FROM_QUALITY_STR)\n\n // quality string contains no numbers, default resolution and framerate to 0.\n // we still store values for these unwanted qualities so the indices and\n // lengths of the arrays line up when we read from them later.\n if (m == null) {\n availableResolutions.push(0)\n availableFramerates.push(0)\n return\n }\n\n // match index 0: resolution string is a number\n // convert to int and store in resolutions array\n availableResolutions.push(parseInt(m[0]))\n\n // match index 1: framerate - if exists, convert to int and store; otherwise store 0.\n // unspecified framerate here can probably be assumed to be 30, but use 0 instead; same\n // effect when comparing.\n availableFramerates.push(m[1] ? parseInt(m[1]) : 0)\n })\n\n // get int versions of user's preferred resolution (retrieved from preferences or passed to instance open() call)\n let preferredResInt = parseInt(this.quality.match(REGEX_NUMBERS_FROM_QUALITY_STR)[0])\n let preferredFpsInt = parseInt(this.quality.match(REGEX_NUMBERS_FROM_QUALITY_STR)[1])\n\n // now that we've got an array of available qualities, we int compare our preferred quality\n // against each and determine the closest available option, which we then use when launching the stream.\n //\n // loop over in reverse order (highest to lowest quality) and compare each to preference.\n // Choose the first quality option that's lower than or equal to preferred.\n for (let i = availableResolutions.length - 1; i >= 0; i--) {\n // if target resolution is lower, open stream\n //\n // if target resolution is the same, make sure framerate is lower.\n // This is to avoid, for example, opening a 1080p60 stream if user's\n // preference is 1080p30, while still opening 1080p30 if the preference\n // is 1080p60 (and 1080p60 isnt available for the stream in question).\n // We will still open higher framerates at a lower fps; 720p60 will open when\n // the user preference is 1080p30 if it's the next lowest available quality.\n //\n // We're conservative to avoid poor performance or over-stressing\n // user's machine when they don't want to.\n \n // skip indices of resolution 0\n if (availableResolutions[i] === 0) continue\n if (\n // open this quality if resolution is lower than preference\n availableResolutions[i] < preferredResInt ||\n // open this quality if resolution is the same and fps is lower\n (availableResolutions[i] === preferredResInt &&\n availableFramerates[i] <= preferredFpsInt)\n ) {\n // the index of the current loop through availableResolutions will\n // correspond to the correct quality string in availableStrs\n let newQual = availableStrs[i].split(' ')[0]\n streamManager.launchStream(this.channelName, newQual)\n .catch(console.error)\n return\n }\n }\n\n // if we got here, no qualities could be used.\n // default to \"best\".\n //\n // this is in a timeout, as otherwise the newly opened process closes itself immediately. not sure why yet. \n setTimeout(() => {\n console.log('Could not find a suitable quality that is <= preferred. Defaulting to \"best\".')\n streamManager.launchStream(this.channelName, 'best')\n .catch(console.error)\n }, 1000) // 1 second\n }\n}",
"_addServiceStreamDataListener ( ) {\n\n this.serviceStream.on(\n 'data'\n , this.boundStreamListener\n );\n }",
"function getTwitterStream(keyword) {\n twitter.stream('statuses/filter', {track: keyword}, function (stream) {\n stream.on('data', function (data) {\n //increasing and manipuilating data received from the json object\n numbOfTweets++;\n numbOfFollowers = numbOfFollowers + data.user.followers_count;\n cycleCount++;\n cycleFollow = cycleFollow + data.user.followers_count;\n tweetNames.push(data.user.screen_name);\n tweetContent.push(data.text);\n averageCount = numbOfFollowers/numbOfTweets;\n //emit the new tweet even\n io.sockets.emit('new_tweet', {tweetCount: numbOfTweets, followerCount:numbOfFollowers, tweetNames:tweetNames,tweetContent:tweetContent,averageCount:averageCount});\n });\n //if anything goes wrong error the application\n stream.on('error', function (err) {\n console.log('ERROR');\n console.log(err);\n });\n });\n}",
"destroyStreamData(){\n\t\tthis.buffer = this.buffer.slice(1,this.buffer.length);\n\t}",
"Sr() {\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const t = {};\n t.database = Jn(this.N), this.wr(t);\n }",
"stream() {\n this.log.trace(\"DfuseBlockStreamer.stream()\");\n if (!this.apolloClient) {\n this.apolloClient = this.getApolloClient();\n }\n this.getObservableSubscription({\n apolloClient: this.apolloClient\n }).subscribe({\n start: () => {\n this.log.trace(\"DfuseBlockStreamer GraphQL subscription started\");\n },\n next: (value) => {\n this.onTransactionReceived(value.data.searchTransactionsForward);\n },\n error: (error) => {\n // TODO should we be doing anything else?\n this.log.error(\"DfuseBlockStreamer GraphQL subscription error\", error.message);\n },\n complete: () => {\n // TODO: how to handle completion? Will we ever reach completion?\n this.log.error(\"DfuseBlockStreamer GraphQL subscription completed\");\n }\n });\n }",
"createStream (callback) {\n\t\tlet data = {\n\t\t\ttype: 'channel',\n\t\t\tname: RandomString.generate(10),\n\t\t\tteamId: this.team.id,\n\t\t\tmemberIds: [this.userData[1].user.id]\n\t\t};\n\t\tthis.apiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/streams',\n\t\t\t\tdata: data,\n\t\t\t\ttoken: this.userData[0].accessToken\t// first user creates the team\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\tthis.stream = response.stream;\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}",
"async listen(receive) { \n\t this.log.i(\"Starting listen loop\")\n\t while (true) { \n\t\tlet msg = await receive.shift() //read from the receive channel \n\t\tswitch(msg['type']) { \n\t\t \n\t\tcase 'emit' : \n\t\t this.emit(msg['data'] )\n\t\t break\n\t\t \n\t\tcase 'feedback' : \n\t\t this.feedback(msg['data'] )\n\t\t break\n\t\t \n\t\t \n\t\tcase 'finish' : \n\t\t this.finish({payload : {result: msg['data']['result']},\n\t\t\t\t error : msg['data']['error']})\n\t\t break \n\n\t\tcase 'call_command' : \n\t\t this.log.i(\"Calling command\")\n\t\t this.launch_command(msg['data']) \n\t\t break \n\t\t \n\t\tdefault : \n\t\t this.log.i(\"Unrecognized msg type in listen loop:\")\n\t\t this.log.i(msg)\n\t\t break \n\t\t}\n\t }\n\t}",
"function bufferStream(){\r\n\t\tvar temp = new Array();\r\n\t\tfor(var i = 0; i< userStream.length; i++){\r\n\t\t\tif(userStream[i].refs === undefined){\r\n\t\t\t\tuserStream[i].refs = null;\r\n\t\t\t\ttemp.push(userStream[i].FbId);\r\n\t\t\t\t//R.request('getVideoRefs',{FromFbId: userStream[i].FbId,Type:\"findUsers\"});\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(temp.length > 0){\r\n\t\t\tR.request('getVideoRefs',{FromFbId: temp ,Type:\"findUsers\"});\r\n\t\t}\r\n\t}",
"_next() {\n if (!this._current) {\n if (!this._streams.length) {\n this._enabled = false;\n return this.end();\n }\n this._current = new stream.Readable().wrap(this._streams.shift());\n this._current.on('end', () => {\n this._current = null;\n this._next();\n });\n this._current.pipe(this, { end: false });\n }\n }",
"gr(t) {\n return e => {\n this.Oe.enqueueAndForget(() => this.sr === t ? e() : (k(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), Promise.resolve()));\n };\n }",
"function startStream (response) {\n\n\tchild.send('start'); \n\n\tresponse.writeHead(200, {\"Content-Type\": \"text/json\"});\n\tresponse.end('{\"status\":\"ok\"}');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets or sets the color to use the border of the input group. | get borderColor() {
return brushToString(this.i.g5);
} | [
"function _editTextColor ( /*[Object] event*/ e ) {\n\t\tthis.nextElementSibling.style.borderColor = this.value;\n\t\tvar activeObject = cnv.getActiveObject();\n\t\tif ( this.value && activeObject ) {\n\t\t\tactiveObject.set({fill: this.value});\n\t\t\tcnv.renderAll();\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'fill', activeObject.get('fill') );\n\t\t}\n\t}",
"get networkBorderGroup() {\n return this.getStringAttribute('network_border_group');\n }",
"function f_refectSpEditBorder(){\n // set #sp-taginfo-border-width value.\n var bw = $('#sp-taginfo-border-width');\n var borderWidth = bw.val();\n if(borderWidth.length == 0){\n borderWidth = '1px';\n }\n bw.val(borderWidth);\n\n // set #sp-taginfo-border-color-input value.\n var bc = $('#sp-taginfo-border-color-input');\n var bcp = $('#sp-taginfo-border-color-picker');\n var borderColor = bcp.val().toUpperCase();\n bc.val(borderColor);\n\n // set .spEdit css\n var setCssBorder = '';\n setCssBorder += borderWidth;\n setCssBorder += ' ';\n setCssBorder += $('#sp-taginfo-border-style').val();\n setCssBorder += ' ';\n setCssBorder += borderColor;\n fdoc.find('.spEdit').css('border',setCssBorder);\n }",
"function getInputCSS(foreground, background, borderTop, borderBottom, borderLeft, borderRight)\n{\n\tvar inputCSS = new Object();\n\tinputCSS['color'] = foreground;\n\tinputCSS['background-color'] = background;\n\tinputCSS['border-top'] = '1px solid ' + borderTop;\n\tinputCSS['border-bottom'] = '1px solid ' + borderBottom;\n\tinputCSS['border-left'] = '1px solid ' + borderLeft;\n\tinputCSS['border-right'] = '1px solid ' + borderRight;\n\treturn inputCSS;\n}",
"function getFillColor(mouseIsPressed) {\n return mouseIsPressed ? 0 : 25;\n}",
"function markSuccessInput(input) {\n $(input).css('border-color', '#f0f0f0');\n}",
"getColor() {\n if (this.state.erasing) { // This ensures that upon erase tool selected, clicking will erase label and color\n return null;\n } else {\n return this.colorBarRef.current.state.color;\n }\n }",
"setBorderColour(state, keyString) {\n // Set new hex to the default, then change depending on the string supplied\n let newColour = '#afdffd'\n if(keyString === 'tree') {\n newColour = '#8bcc82'\n }\n else if(keyString === 'wildflower') {\n newColour = '#fddbaf'\n }\n else if(keyString === 'bluebell') {\n newColour = '#b1a8ea'\n }\n state.borderColour = newColour;\n }",
"function changeBorder(image, color){\n\tif (!blnN4){\n\t\timage.style.borderColor = color;\n\t\timage.style.borderWidth = 1;\n\t\timage.style.margin = 0;\n\t}\n\n}",
"function setDrawingColor(event) {\n sketchController.color = this.value;\n}",
"getColor(value) {\n if (undefined == value) { return 'lightgrey'; }\n if (value < 0) {\n return this.negativeColorScale(value);\n } else {\n return this.selectedPosColorScale(value);\n }\n }",
"function clickColor(event) {\n const target = event.target;\n selectedColor = target.style.fill;\n}",
"function selectedColor(color){\n\n color.addEventListener('click', e=>{\n eliminarSeleccion();\n e.target.style.border = '2px solid #22b0b0';\n\n // Agregar color seleccionado al input de color\n document.querySelector('input[name=color]').value = e.target.style.background;\n\n })\n}",
"set strokeColor(color) {\n var hex = STYLE_UTIL.getHexColor(color);\n if (hex) {\n var stroke = SLD.stroke(this._symbolizer);\n stroke.setColor(STYLE_UTIL._filterFactory.literal(hex));\n } else {\n throw new Error(\"Can't determine hex color from strokeColor '\" + color + \"'.\")\n }\n }",
"function addRedBorder(elem){\r\n elem.css(\"border\",`2px ridge ${red}`);\r\n}",
"function getGridBackgroundColorClass() {\n return 'highlighted-' + getGridBackgroundColor();\n }",
"function controlChangeHandler () {\n setColours(this.value);\n }",
"static Magenta() {\n return new Color3(1, 0, 1);\n }",
"parseColorGroup(optional) {\n const res = this.parseStringGroup(\"color\", optional);\n\n if (!res) {\n return null;\n }\n\n const match = /^(#[a-f0-9]{3}|#?[a-f0-9]{6}|[a-z]+)$/i.exec(res.text);\n\n if (!match) {\n throw new ParseError(\"Invalid color: '\" + res.text + \"'\", res);\n }\n\n let color = match[0];\n\n if (/^[0-9a-f]{6}$/i.test(color)) {\n // We allow a 6-digit HTML color spec without a leading \"#\".\n // This follows the xcolor package's HTML color model.\n // Predefined color names are all missed by this RegEx pattern.\n color = \"#\" + color;\n }\n\n return {\n type: \"color-token\",\n mode: this.mode,\n color\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generates captcha text and converts it to image | function Captcha() {
for (var i = 0; i < 6; i++) {
var a = alpha[Math.floor(Math.random() * alpha.length)];
var b = alpha[Math.floor(Math.random() * alpha.length)];
var c = alpha[Math.floor(Math.random() * alpha.length)];
var d = alpha[Math.floor(Math.random() * alpha.length)];
var e = alpha[Math.floor(Math.random() * alpha.length)];
var f = alpha[Math.floor(Math.random() * alpha.length)];
var g = alpha[Math.floor(Math.random() * alpha.length)];
}
captcha_text = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' ' + f + ' ' + g;
document.fonts.load(font)
.then(function() {
tCtx.font = font;
tCtx.canvas.width = tCtx.measureText(captcha_text).width;
tCtx.canvas.height = 40;
tCtx.font = font;
tCtx.fillStyle = '#444';
tCtx.fillText(captcha_text, 0, 20);
var c = document.getElementById("textCanvas");
var ctx = c.getContext("2d");
// Draw lines
for (var i = 0; i < 7; i++) {
ctx.beginPath();
ctx.moveTo(c.width * Math.random(), c.height * Math.random());
ctx.lineTo(c.width * Math.random(), c.height * Math.random());
ctx.strokeStyle = "rgb(" +
Math.round(256 * Math.random()) + "," +
Math.round(256 * Math.random()) + "," +
Math.round(256 * Math.random()) + ")";
ctx.stroke();
}
imageElem.src = tCtx.canvas.toDataURL();
});
} | [
"function vpb_refresh_aptcha()\r\n{\r\n\treturn $(\"#vpb_captcha_code\").val('').focus(),document.images['captchaimg'].src = document.images['captchaimg'].src.substring(0,document.images['captchaimg'].src.lastIndexOf(\"?\"))+\"?rand=\"+Math.random()*1000;\r\n}",
"function initCaptcha() {\n captchaX = Math.floor((Math.random() * 10) + 1);\n captchaY = Math.floor((Math.random() * 10) + 1);\n var no1 = makeNumber(captchaX);\n var no2 = makeNumber(captchaY);\n document.getElementById(\"no1\").innerHTML = no1;\n document.getElementById(\"no2\").innerHTML = no2;\n}",
"function canvasPaint(topTextColor = 'white', bottomTextColor = 'red', transText = 0.5) {\n var elCanvas = document.getElementById('canvas');\n var ctx = canvas.getContext('2d');\n canvas.height = gCanvasHeight;\n canvas.width = gCanvasWidth;\n // ctx.fillStyle = '#0e70d1';\n var img = new Image();\n img.src = gMeme;\n img.onload = function () {\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n // ctx.save();\n ctx.font = gTextFontSize + 'pt David';\n ctx.fillStyle = 'rgba(0,0,0,' + gTransText + ')';\n ctx.fillRect(0, 0, canvas.width, canvas.height / gTopTextHeight);\n ctx.fillRect(0, canvas.height - canvas.height / gBottomTextHeight, canvas.width, canvas.height / gBottomTextHeight);\n // ctx.save();\n ctx.fillStyle = topTextColor;\n ctx.fillText(gInputTopText.toUpperCase(), gTopTextAlign, gTextFontSize + 3);\n ctx.fillStyle = bottomTextColor;\n ctx.fillText(gInputBottomText.toUpperCase(), gBottomTextAlign, canvas.height - 5);\n ctx.font = '10pt Dvaid'\n ctx.fillStyle = '#fff';\n ctx.fillText(\"Noa's & Guy's MemeGenerator\", 10, 300);\n // ctx.restore();\n // ctx.fillStyle = '#fff';\n ctx.save();\n // return ctx\n };\n // var newImg=new Image();\n // newImg.id=\"meme\";\n // memeUrl = canvas.toDataURL();\n // document.getElementById('img_generated').appendChild(newImg);\n // console.log(ctx);\n // return res\n}",
"function drawImgText(elText) {\n drawImage(gCurrImg)\n}",
"function asciiArtAssist(src,size,color,bgColor){\n\t//default values for src, size, color and bgColor\n\tsrc=!src?'none':src;\n\tsize=!size?'inherit':size;\n\tcolor=!color?'#fff':color;\n\tbgColor=!bgColor?'#000':bgColor;\n\tvar slf=window,txtA,F,r9=slf.Math.random().toFixed(9).replace(/\\./g,''),\n\t\tt=slf.document.getElementsByTagName('body')[0],\n\t\tE=slf.document.createElement('textarea');\n\tE.id='asciiA'+r9;\n\tE.style.cssText=\"color: \"+color+\";font-size: \"+size+\";background: url(\\'\"+src+\"\\') \"+bgColor+\" no-repeat;\";\n\ttxtA=t.appendChild(E),t=E=null;\n\t//returned function returns the current value of textarea tag\n\tF=function(){\n\t\treturn document.getElementById('asciiA'+r9).value;\n\t};\n\t//method to close textarea tag\n\tF.close=function(){\n\t\tvar r=document.getElementById('asciiA'+r9);\n\t\tr=r.parentNode.removeChild(r),r=null;\n\t};\n\treturn F;\n}",
"function frankenstein() {\n // Reset the canvas\n saveableContext = saveCanvas.getContext(\"2d\");\n saveCanvas.width=1280;//horizontal resolution (?) - increase for better looking text\n saveCanvas.height=720;\n saveableContext.clearRect(0, 0, saveCanvas.width, saveCanvas.height)\n\n console.log(\"defs running the smoosh together function\")\n //take current canvas and slap on the left hand side \n saveableContext.drawImage(pixelCanvas, 0, 0, saveCanvas.width/2, saveCanvas.height);\n saveableContext.font = saveableContext.font.replace(/\\d+px/, \"44px\");\n\n // parse memText and make it into commaed /n'd form\n //formattedText = addItemEvery(memText, \", \", 22);\n formattedText = memText.match(/.{1,24}/g)\n document.getElementById(\"testspace\").innerHTML = formattedText;\n console.log(formattedText);\n\n //slap parsed text on the right side of the image\n formattedText.forEach(printArrayCanvas);\n console.log(saveCanvas.width/2, saveCanvas.height/2);\n\n \n\n //save to local\n //var image = saveCanvas.toDataURL(\"image/png\").replace(\"image/png\", \"image/octet-stream\"); // here is the most important part because if you dont replace you will get a DOM 18 exception.\n //window.location.href=image;\n download(saveCanvas, formattedText[0]+'.png');\n}",
"function smiley_text(text, smiley_names, width)\r\n{\r\n var smiley_codes = new Array();\r\n for each (var smiley in smiley_names) // Filters valid smileys\r\n {\r\n if (smileys.hasOwnProperty(smiley))\r\n {\r\n smiley_codes.push(smileys[smiley]);\r\n }\r\n }\r\n \r\n text = text.toUpperCase(); // There are only ascii art representations of caps\r\n var res = \"\";\r\n var cur_smiley = 0;\r\n for (var row = 0; row < rows_per_letter; row++)\r\n {\r\n for each (var chr in text)\r\n {\r\n if (!alphabet.hasOwnProperty(chr))\r\n {\r\n continue;\r\n }\r\n\r\n var cur_row = alphabet[chr][row];\r\n for (var i = 0; i < cur_row.length; i++)\r\n {\r\n var spaces = take_while(\" \", cur_row, i);\r\n if (spaces.length > 0)\r\n {\r\n res += get_spacer_img(spaces.length, width);\r\n i += spaces.length - 1;\r\n }\r\n else\r\n {\r\n res += smiley_codes[cur_smiley % smiley_codes.length];\r\n cur_smiley++;\r\n }\r\n }\r\n res += get_spacer_img(1, width); // Spacing between letters\r\n }\r\n res += \"\\n\";\r\n }\r\n return res;\r\n}",
"function textual_emoticon_to_html_emoticon(textual_emoticon_text){\n // example HTML emoticon : '<img src=\"img/ico/mail.png\" class=\"emoticon\" alt=\":mail:\">'\n var mapping = ico_mapping;\n var textual_emoticon_type = textual_emoticon_text.slice(1,-1);\n var src = mapping[textual_emoticon_type];\n // for invalid mappings...\n if(typeof src == 'undefined') return textual_emoticon_text;\n var html = '<img src=\"img/ico/'+src+'\" class=\"emoticon\" alt=\"'+textual_emoticon_text+'\">';\n return html;\n}",
"function recargar_captcha() {\n\tvar url = \"captcha.php\";\n\tvar src = \"\";\n\tvar pars = \"recargar=si\";\n\tvar ajax = new Ajax.Request(url, {\n\t\t//Cuando es sincrono _NO_ se ejecutan los callbacks\n\t\tasynchronous : false,\n\t\tparameters : pars,\n\t\tmethod : \"post\",\t\t\n\t\t//onComplete : procesaRespuesta\t\t\n\t});\n\tfunction procesaRespuesta(resp) {\n\t\tvar text = resp.responseText;\t\n\t\tsrc = text;\n\n\t}\n\tprocesaRespuesta(ajax.transport);\n\treturn src;\n}",
"function correctAnswerHtml() {\n console.log(\"Generating Correct Answer Response\");\n return `\n <br>\n <div class=\"correct-answer\">\n <img src=\"images/correct-answer.jpg\">\n <h2>Great Job! That is correct!</h2>\n </div>\n `\n }",
"function generatePictureHtml(content){\n return \"<a href=\\\"\" + content + \"\\\" target=\\\"_blank\\\">\" + content + \"</l>\" +\n \"<br>\" +\n \"<img class=\\\"chat-photo\\\" src=\\\"\" + content + \"\\\" target=\\\"_blank\\\">\";\n}",
"function validatecaptcha() {\n var cap = $(\"#captcha\").val();\n var cap_hd = $(\"#hd_cap\").val();\n if (cap != cap_hd) {\n $(\"#captcha\").addClass(\"error\");\n $(\"#captchaInfo\").text(\"Enter a valid security code\\n\");\n $(\"#captchaInfo\").addClass(\"error_message_side\");\n\n return false;\n } else {\n $(\"#captcha\").removeClass(\"error\");\n $(\"#captchaInfo\").text(\"\");\n $(\"#captchaInfo\").removeClass(\"error_message_side\");\n return true;\n }\n\n }",
"function makeChar() {\n\tvar probability=points(0,\"\")/hardness;//according to hardness of game\n\tif(typeof alphabets === 'undefined' || alphabets === \"\"){\n\t\tvar index=Math.floor(Math.random() * 5)+2;\n\t\talphabets=words[index][Math.floor(Math.random() * words[index].length)];\n\t\tif(points(0,\"\")===0){\n\t\t\t//showing Hint only for new players\n\t\t\tif(typeof(Storage) !== \"undefined\") {\n\t\t\t\tif(localStorage.getItem(\"score\")===null){\n\t\t\t\t\thint(alphabets);//help player to learn game\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\thint(alphabets);//help player to learn game\n\t\t\t}\n\t\t}\n\t\ttext = alphabets.charAt(0);\n\t\talphabets = alphabets.slice(1);\t\n\t}else if(points(0,\"\") >=bombPoint){\n\t\t\ttext = 'B';\n\t\t\tbombPoint*=3;\n\t}else if(points(0,\"\") >=blockPoint){\n\t\t\ttext = 'N';\n\t\t\tblockPoint*=3;\n\t}else{\n\t\tif(Math.random() <= probability){\n\t\t\t//if propability goes up, game gets harder\n\t\t\ttext = randomChar();\n\t\t}else{\n\t\t\ttext = alphabets.charAt(0);\n\t\t\talphabets = alphabets.slice(1);\n\t\t}\n\t}\n\treturn text;\n}",
"function generateImage(targetImage) {\n if (generateImage){\n var img = document.createElement('img');\n img.setAttribute('src', targetImage);\n var characterAvatar = document.getElementById('bigCharacter');\n characterAvatar.appendChild(img);\n }\n}",
"function graphic(){\r\n let memeImage = document.createElement(\"img\");\r\n memeImage.className = \"memeImage\";\r\n memeImage.src = image.value;\r\n return memeImage;\r\n}",
"function draw2Dkeyboard()\n{\n imageMode(CORNER);\n image(keyboard, width/2 - 2.0*PPCM, height/2 - 1.0*PPCM, 4.0*PPCM, 3.0*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"S\" , width/2 - 1.32*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"Q\" , width/2 - 1.74*PPCM, height/2 + 0.10*PPCM);\n text(\"W\" , width/2 - 1.32*PPCM, height/2 + 0.10*PPCM);\n text(\"E\" , width/2 - 0.89*PPCM, height/2 + 0.10*PPCM);\n text(\"A\" , width/2 - 1.74*PPCM, height/2 + 0.60*PPCM);\n text(\"D\" , width/2 - 0.89*PPCM, height/2 + 0.60*PPCM);\n text(\"Z\" , width/2 - 1.74*PPCM, height/2 + 1.08*PPCM);\n text(\"X\" , width/2 - 1.32*PPCM, height/2 + 1.08*PPCM);\n text(\"C\" , width/2 - 0.89*PPCM, height/2 + 1.08*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"G\" , width/2 + 0.0*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"R\" , width/2 - 0.42*PPCM, height/2 + 0.10*PPCM);\n text(\"T\" , width/2 - 0*PPCM, height/2 + 0.10*PPCM);\n text(\"Y\" , width/2 + 0.42*PPCM, height/2 + 0.10*PPCM);\n text(\"H\" , width/2 + 0.42*PPCM, height/2 + 0.60*PPCM);\n text(\"F\" , width/2 - 0.44*PPCM, height/2 + 0.60*PPCM);\n text(\"V\" , width/2 - 0.42*PPCM, height/2 + 1.08*PPCM);\n text(\"B\" , width/2 - 0*PPCM, height/2 + 1.08*PPCM);\n text(\"N\" , width/2 + 0.42*PPCM, height/2 + 1.08*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"K\" , width/2 + 1.30*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"U\" , width/2 + 0.88*PPCM, height/2 + 0.10*PPCM);\n text(\"I\" , width/2 + 1.30*PPCM, height/2 + 0.10*PPCM);\n text(\"O\" , width/2 + 1.72*PPCM, height/2 + 0.10*PPCM);\n text(\"J\" , width/2 + 0.88*PPCM, height/2 + 0.60*PPCM);\n text(\"P\" , width/2 + 1.72*PPCM, height/2 + 0.60*PPCM);\n text(\"M\" , width/2 + 0.88*PPCM, height/2 + 1.08*PPCM);\n text(\"L\" , width/2 + 1.72*PPCM, height/2 + 1.08*PPCM);\n}",
"onOCRCapture(recogonizedText) {\n console.log('onCapture', recogonizedText);\n this.setState({showCamera: false, showCredentials: Helper.isNotNullAndUndefined(recogonizedText), recogonizedText: recogonizedText});\n }",
"function generateRandomMessage(faceFail, textFail, nsfwFail, nudeOrShirtlessFail, focusFail, celebFail, celebContent) {\n\n\tvar message = \"\";\n\t\n\t// Face check failed\n\tif(faceFail) {\n\t\tvar topGeneralTag = generalTags[0].name;\n\t\n\t\tvar generalMsgs = \n\t\t\t[ \"A \" + topGeneralTag + \" picture for your profile?!?!? Come on!\",\n\t\t\t\t\"Oh great, a \" + topGeneralTag + \". You can do better than that!\",\n\t\t\t\t\"If we wanted to see a \" + topGeneralTag + \" we could just go to Google...\"\n\t\t\t];\n\t\t\t\n\t\tmessage += generalMsgs[(Math.floor((Math.random() * generalMsgs.length)))];\n\t}\n\t\n\t// Text in the picture\n\tif(textFail) {\n\t\tvar textMsgs = \n\t\t\t[ \"Text belongs in text messages and memes, am I right?\",\n\t\t\t\t\"I see some writing on your photo. It says \\\"This shouldn't be your profile picture.\\\"\",\n\t\t\t\t\"We're not supposed to read your profile photo!\"\n\t\t\t];\n\t\t\t\n\t\tif(message != \"\")\n\t\t\tmessage += \" And \" + textMsgs[(Math.floor((Math.random() * textMsgs.length)))].toLowerCase();\n\t\t\t\n\t\telse\n\t\t\tmessage += textMsgs[(Math.floor((Math.random() * textMsgs.length)))];\t\n\t}\n\t\n\t// NSFW failed\n\tif(nsfwFail) {\n\t\tvar nsfwMsgs = \n\t\t\t[ \"Yeah...a little racy for Facebook's code of conduct don't you think?\",\n\t\t\t\t\"It might be better to keep this one offline...\",\n\t\t\t\t\"Mark Zuckerberg would DEFINITELY not approve of this.\"\n\t\t\t];\n\t\t\t\n\t\tif(message != \"\")\n\t\t\tmessage += \" And \" + nsfwMsgs[(Math.floor((Math.random() * nsfwMsgs.length)))].toLowerCase();\n\t\t\t\n\t\telse\n\t\t\tmessage += nsfwMsgs[(Math.floor((Math.random() * nsfwMsgs.length)))];\n\t}\n\t\n\t// Nude Or Shirtless from General Model\n\tif(nudeOrShirtlessFail) {\n\t\tvar nudeShirtlessMsgs = \n\t\t\t[ \"I'm sure your abs are great, but this is a profile picture!\",\n\t\t\t\t\"No shoes. No shirt. No profile picture.\",\n\t\t\t\t\"Save this for your upcoming Abercrombie shoot!\"\n\t\t\t];\n\t\t\t\n\t\tif(message != \"\")\n\t\t\tmessage += \" And \" + nudeShirtlessMsgs[(Math.floor((Math.random() * nudeShirtlessMsgs.length)))].toLowerCase();\n\t\t\t\n\t\telse\n\t\t\tmessage += nudeShirtlessMsgs[(Math.floor((Math.random() * nudeShirtlessMsgs.length)))];\n\t}\n\t\n\t// Focus failed\n\tif(focusFail) {\n\t\tvar focusMsgs = \n\t\t\t[ \"Blurrrrrrrr, it's cold in here! There must be some pixels in the atmosphere.\",\n\t\t\t\t\"Was this taken with a flip phone?\",\n\t\t\t\t\"This should be crisp, like a fall breeze in New York City, or Coco Puffs.\"\n\t\t\t];\n\t\t\t\n\t\tif(message != \"\")\n\t\t\tmessage += \" And \" + focusMsgs[(Math.floor((Math.random() * focusMsgs.length)))].toLowerCase();\n\t\t\t\n\t\telse\n\t\t\tmessage += focusMsgs[(Math.floor((Math.random() * focusMsgs.length)))];\n\t\n\t}\n\t\n\t// Celebrities exist (only)\n\tif(celebFail) {\n\t\tvar celebs = celebContent; // array of celebs\n\t\t\n\t\t// turn this into a sentence\n\t\tvar celebSentence = \n\t\t\tcelebs.reduce(\n \t\t\tfunction(prev, curr, i){ \n \t\t\treturn prev + curr + ((i===celebs.length-2) ? ' and ' : ', ')\n \t\t\t}, '')\n\t\t\t.slice(0, -2);\n\t\n\t\tvar celebMsgs = \n\t\t\t[ \"Umm, no....you should not make \" + capitalize(celebSentence) + \" your profile picture. Unless it's really you \" + capitalize(celebSentence.split(\" \")[0]) + \".\",\n\t\t\t\t\"Whoa....you look JUST like \" + capitalize(celebSentence) + \"!\",\n\t\t\t\t\"\" + capitalize(celebSentence) + \" seems better suited for a Favorite Celebrity section on MySpace.\"\n\t\t\t];\n\t\t\n\t\tif(message != \"\")\n\t\t\tmessage += \" And \" + celebMsgs[(Math.floor((Math.random() * celebMsgs.length)))].toLowerCase();\n\t\t\t\n\t\telse\n\t\t\tmessage += celebMsgs[(Math.floor((Math.random() * celebMsgs.length)))];\n\t}\n\t\n\tif(!faceFail && !textFail && !nsfwFail && !nudeOrShirtlessFail && !focusFail && !celebFail) {\n\t\tvar goodMsgs = \n\t\t\t[ \"Lookin' good there! Get that thing on the interwebs.\",\n\t\t\t\t\"Now THAT is Facebook quality. Wow.\",\n\t\t\t\t\"Booyah!!! A perfect 3 for 3.\",\n\t\t\t\t\"Worthy of many successive slow claps, for sure.\"\n\t\t\t];\n\t\n\t\tmessage = goodMsgs[(Math.floor((Math.random() * goodMsgs.length)))];\n\t}\n\t\n\treturn message;\n}",
"function slapRandomOnTheDOM(imgObject){\n imgObject.message.forEach((m) => {\n let img = document.createElement(\"img\");\n let attr = document.createAttribute(\"src\");\n attr.value = `${m}`\n img.setAttributeNode(attr)\n document.body.append(img);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
eslint nounusedvars: 0 included from index Alerts the user if the browser version is so old, that even the transpiled and polyfilled version is not guaranteed to work. Only an approximation: Using some browser name and versions, may fail to warn or warn incorrectly. | function browserCheckTranspiled()
{
if (
(navigator.sayswho.name === 'Firefox' && navigator.sayswho.version < 50) ||
(navigator.sayswho.name === 'Internet Explorer') ||
(navigator.sayswho.name === 'Chrome' && navigator.sayswho.version < 54)
)
{alert(`Your browser ${navigator.sayswho.name} version ${navigator.sayswho.version} may be outdated. Graph may not work properly.`);}
log.warn("Browser outdated. Graph may not work properly.");
} | [
"function browserCheckNonTranspiled()\n{\n if (\n (navigator.sayswho.name === 'Firefox' && navigator.sayswho.version < 60) ||\n (navigator.sayswho.name === 'Internet Explorer') ||\n (navigator.sayswho.name === 'Chrome' && navigator.sayswho.version < 61)\n )\n {\n const warning = `Your browser ${navigator.sayswho.name} version ${navigator.sayswho.version} may be outdated for the development build. Graph may not work properly. Try using the transpiled production build.`;\n alert(warning);\n log.warn(\"Browser outdated for the development build. Graph may not work properly. Try using the transpiled production build\");\n }\n}",
"showBrowserWarning () {\n let showWarning = false\n let version = ''\n\n // check firefox\n if (window.navigator.userAgent.indexOf('Firefox') !== -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 3).replace(/\\./g, ''))\n\n // lower than 19?\n if (version < 19) showWarning = true\n }\n\n // check opera\n if (window.navigator.userAgent.indexOf('OPR') !== -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 1))\n\n // lower than 9?\n if (version < 9) showWarning = true\n }\n\n // check safari, should be webkit when using 1.4\n if (window.navigator.userAgent.indexOf('Safari') !== -1 && window.navigator.userAgent.indexOf('Chrome') === -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 3))\n\n // lower than 1.4?\n if (version < 400) showWarning = true\n }\n\n // check IE\n if (window.navigator.userAgent.indexOf('MSIE') === -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 1))\n\n // lower or equal than 6\n if (version <= 6) showWarning = true\n }\n\n // show warning if needed\n if (showWarning) $('#showBrowserWarning').show()\n }",
"function oldGlobals() {\n var message = '-- AlgoliaSearch V2 => V3 error --\\n' +\n 'You are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\\n' +\n 'Please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\\n' +\n '-- /AlgoliaSearch V2 => V3 error --';\n\n window.AlgoliaSearch = function() {\n throw new Error(message);\n };\n\n window.AlgoliaSearchHelper = function() {\n throw new Error(message);\n };\n\n window.AlgoliaExplainResults = function() {\n throw new Error(message);\n };\n }",
"function checkMinVersion() {\n const majorVersion = Number(process.version.replace(/v/, '').split('.')[0]);\n if (majorVersion < NODE_MIN_VERSION) {\n $$.util.log('Please run Subscribe with Google with node.js version ' +\n `${NODE_MIN_VERSION} or newer.`);\n $$.util.log('Your version is', process.version);\n process.exit(1);\n }\n}",
"function checkNodeVersionRequiredByLinode() {\n // Versions of Node.js that are recommended for these tests.\n const recommendedNodeVersions = [14];\n\n const versionString = process.version.substr(1, process.version.length - 1);\n const versionComponents = versionString\n .split('.')\n .map((versionComponentString) => {\n return parseInt(versionComponentString, 10);\n });\n\n // Print warning if running a version of Node that is not recommended.\n if (!recommendedNodeVersions.includes(versionComponents[0])) {\n if (recommendedNodeVersions.length > 1) {\n console.warn(\n `You are currently running Node v${versionString}. We recommend one of the following versions of Node for these tests:\\n`\n );\n console.warn(\n `${recommendedNodeVersions\n .map((version) => ` - v${version}.x\\n`)\n .join('')}`\n );\n } else {\n console.warn(\n `You are currently running Node v${versionString}. We recommend Node v${recommendedNodeVersions[0]}.x for these tests.`\n );\n }\n }\n}",
"function checkBrowser(){\n\tvar browserInfo = navigator.userAgent;\n\tif(browserInfo.indexOf(\"Firefox\")!=-1)userBrowser=\"Firefox\";\n\tif(browserInfo.indexOf(\"Chrome\")!=-1)userBrowser=\"Chrome\";\n\tif(browserInfo.indexOf(\"Safari\")!=-1)userBrowser=\"Safari\";\n}",
"function assertBrowserEnv() {\r\n return assert(isBrowser, 'This feature is only available in browser environments');\r\n }",
"function browserNameVersion(){\n let ua = window.navigator.userAgent, tem,\n M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*(\\d+)/i) || [];\n if(/trident/i.test(M[1])){\n tem = /\\brv[ :]+(\\d+)/g.exec(ua) || [];\n return 'IE '+(tem[1] || '');\n }\n if(M[1]=== 'Chrome'){\n tem = ua.match(/\\b(OPR|Edge)\\/(\\d+)/);\n if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');\n }\n M= M[2]? [M[1], M[2]]: [window.navigator.appName, window.navigator.appVersion, '-?'];\n if((tem = ua.match(/version\\/(\\d+)/i))!= null) M.splice(1, 1, tem[1]);\n return M.join('|');\n }",
"function ApiBrowserCheck() {\n //delete GM_log; delete GM_getValue; delete GM_setValue; delete GM_deleteValue; delete GM_xmlhttpRequest; delete GM_openInTab; delete GM_registerMenuCommand;\n if(typeof(unsafeWindow)=='undefined') { unsafeWindow=window; }\n if(typeof(GM_log)=='undefined') { GM_log=function(msg) { try { unsafeWindow.console.log('GM_log: '+msg); } catch(e) {} }; }\n \n var needApiUpgrade=false;\n if(window.navigator.appName.match(/^opera/i) && typeof(window.opera)!='undefined') {\n needApiUpgrade=true; gvar.isOpera=true; GM_log=window.opera.postError; clog('Opera detected...',0);\n }\n if(typeof(GM_setValue)!='undefined') {\n var gsv; try { gsv=GM_setValue.toString(); } catch(e) { gsv='.staticArgs.FF4.0'; }\n if(gsv.indexOf('staticArgs')>0) {\n gvar.isGreaseMonkey=true; gvar.isFF4=false;\n clog('GreaseMonkey Api detected'+( (gvar.isFF4=gsv.indexOf('FF4.0')>0) ?' >= FF4':'' )+'...',0); \n } // test GM_hitch\n else if(gsv.match(/not\\s+supported/)) {\n needApiUpgrade=true; gvar.isBuggedChrome=true; clog('Bugged Chrome GM Api detected...',0);\n }\n } else { needApiUpgrade=true; clog('No GM Api detected...',0); }\n \n gvar.noCrossDomain = (gvar.isOpera || gvar.isBuggedChrome);\n if(needApiUpgrade) {\n //gvar.noCrossDomain = gvar.isBuggedChrome = 1;\n clog('Try to recreate needed GM Api...',0);\n //OPTIONS_BOX['FLASH_PLAYER_WMODE'][3]=2; OPTIONS_BOX['FLASH_PLAYER_WMODE_BCHAN'][3]=2; // Change Default wmode if there no greasemonkey installed\n var ws=null; try { ws=typeof(unsafeWindow.localStorage) } catch(e) { ws=null; } // Catch Security error\n if(ws=='object') {\n clog('Using localStorage for GM Api.',0);\n GM_getValue=function(name,defValue) { var value=unsafeWindow.localStorage.getItem(GMSTORAGE_PATH+name); if(value==null) { return defValue; } else { switch(value.substr(0,2)) { case 'S]': return value.substr(2); case 'N]': return parseInt(value.substr(2)); case 'B]': return value.substr(2)=='true'; } } return value; };\n GM_setValue=function(name,value) { switch (typeof(value)) { case 'string': unsafeWindow.localStorage.setItem(GMSTORAGE_PATH+name,'S]'+value); break; case 'number': if(value.toString().indexOf('.')<0) { unsafeWindow.localStorage.setItem(GMSTORAGE_PATH+name,'N]'+value); } break; case 'boolean': unsafeWindow.localStorage.setItem(GMSTORAGE_PATH+name,'B]'+value); break; } };\n GM_deleteValue=function(name) { unsafeWindow.localStorage.removeItem(GMSTORAGE_PATH+name); };\n } else if(!gvar.isOpera || typeof(GM_setValue)=='undefined') {\n clog('Using temporarilyStorage for GM Api.',0); gvar.temporarilyStorage=new Array();\n GM_getValue=function(name,defValue) { if(typeof(gvar.temporarilyStorage[GMSTORAGE_PATH+name])=='undefined') { return defValue; } else { return gvar.temporarilyStorage[GMSTORAGE_PATH+name]; } };\n GM_setValue=function(name,value) { switch (typeof(value)) { case \"string\": case \"boolean\": case \"number\": gvar.temporarilyStorage[GMSTORAGE_PATH+name]=value; } };\n GM_deleteValue=function(name) { delete gvar.temporarilyStorage[GMSTORAGE_PATH+name]; };\n }\n if(typeof(GM_openInTab)=='undefined') { GM_openInTab=function(url) { unsafeWindow.open(url,\"\"); }; }\n if(typeof(GM_registerMenuCommand)=='undefined') { GM_registerMenuCommand=function(name,cmd) { GM_log(\"Notice: GM_registerMenuCommand is not supported.\"); }; } // Dummy\n if(!gvar.isOpera || typeof(GM_xmlhttpRequest)=='undefined') {\n clog('Using XMLHttpRequest for GM Api.',0);\n GM_xmlhttpRequest=function(obj) {\n var request=new XMLHttpRequest();\n request.onreadystatechange=function() { if(obj.onreadystatechange) { obj.onreadystatechange(request); }; if(request.readyState==4 && obj.onload) { obj.onload(request); } }\n request.onerror=function() { if(obj.onerror) { obj.onerror(request); } }\n try { request.open(obj.method,obj.url,true); } catch(e) { if(obj.onerror) { obj.onerror( {readyState:4,responseHeaders:'',responseText:'',responseXML:'',status:403,statusText:'Forbidden'} ); }; return; }\n if(obj.headers) { for(name in obj.headers) { request.setRequestHeader(name,obj.headers[name]); } }\n request.send(obj.data); return request;\n }; }\n } // end needApiUpgrade\n GM_getIntValue=function(name,defValue) { return parseInt(GM_getValue(name,defValue),10); };\n}",
"function getUnsupportedBrowsersByFeature(feature$$1) {\n\tvar caniuseFeature = features[feature$$1];\n\n\t// if feature support can be determined\n\tif (caniuseFeature) {\n\t\tvar stats = feature(caniuseFeature).stats;\n\n\t\t// return an array of browsers and versions that do not support the feature\n\t\tvar results = Object.keys(stats).reduce(function (browsers, browser) {\n\t\t\treturn browsers.concat(Object.keys(stats[browser]).filter(function (version) {\n\t\t\t\treturn stats[browser][version].indexOf('y') !== 0;\n\t\t\t}).map(function (version) {\n\t\t\t\treturn `${browser} ${version}`;\n\t\t\t}));\n\t\t}, []);\n\n\t\treturn results;\n\t} else {\n\t\t// otherwise, return that the feature does not work in any browser\n\t\treturn ['> 0%'];\n\t}\n}",
"function insistOnInterVer() {\n if (window.console) console.warn(\n 'You are using the MathQuill API without specifying an interface version, ' +\n 'which will fail in v1.0.0. Easiest fix is to do the following before ' +\n 'doing anything else:\\n' +\n '\\n' +\n ' MathQuill = MathQuill.getInterface(1);\\n' +\n ' // now MathQuill.MathField() works like it used to\\n' +\n '\\n' +\n 'See also the \"`dev` branch (2014–2015) → v0.10.0 Migration Guide\" at\\n' +\n ' https://github.com/mathquill/mathquill/wiki/%60dev%60-branch-(2014%E2%80%932015)-%E2%86%92-v0.10.0-Migration-Guide'\n );\n}",
"function requires(version) {\n\tvar s = version.split(\".\");\n\tassert(s.length >= 1);\n\t\n\tvar reqmajor = parseInt(s[0]);\n\tvar reqminor = (s.length >= 2) ? parseInt(s[1]) : 0;\n\tvar reqbuild = (s.length >= 3) ? parseInt(s[2]) : 0;\n\t\n\tvar id = GPSystem.getSystemID();\n\tvar s = id.toString(OID).split(\".\");\n\n\tvar major = parseInt(s[s.length - 4]);\n\tvar minor = parseInt(s[s.length - 3]);\n\tvar build = parseInt(s[s.length - 2]);\n\t\n\tif ((major < reqmajor) ||\n\t ((major == reqmajor) && (minor < reqminor)) ||\n\t ((major == reqmajor) && (minor == reqminor) && (build < reqbuild))) {\n\t\tprint(\"This script uses features only available in version \" + version + \" or later.\");\n\t\tprint(\"It may not run as expected, please update to a more current version.\");\n\t\tGPSystem.wait(1500);\n\t}\n}",
"function spoofBrowser(){\n\t\tif(haveHTMLAll) return;\n\t\tclass HTMLAllCollection{\n\t\t\tconstructor(){ return undefined; }\n\t\t\tvalueOf(){ return undefined; }\n\t\t}\n\t\tHTMLAllCollection.toString = function toString(){ return htmlAllFn; };\n\t\tconst document = {all: new HTMLAllCollection()};\n\t\tglobalThis.HTMLAllCollection = HTMLAllCollection;\n\t\tglobalThis.window = {HTMLAllCollection, document};\n\t\tglobalThis.document = document;\n\t}",
"function verificarBrowser(){\n // Verificando Browser\n if(Is.appID==\"IE\" && Is.appVersion<6 ){\n var msg = \"Este sistema possui recursos não suportados pelo seu Navegador atual.\\n\";\n msg += \"É necessário fazer uma atualização do browser atual para a versão 6 ou superior,\\n\";\n msg += \"ou poderá instalar o Navegador Firefox.\\n\";\n //msg += \"\\nDados do seu Navegador:\";\n //msg += \"\\n Browser:\"+Is.appName+\"\\n ID:\"+Is.appID+\"\\n Versão:\"+Is.appVersion;\n msg += \"\\n Baixar firefox agora?\";\n if(confirm(msg)){\n document.location.replace(\"http://br.mozdev.org/\");\n return false;\n }else{\n return false;\n }\n }else{\n return true;\n }\n}",
"function isGecko() {\n\t\tconst w = window\n\t\t// Based on research in September 2020\n\t\treturn (\n\t\t\tcountTruthy([\n\t\t\t\t'buildID' in navigator,\n\t\t\t\t'MozAppearance' in (document.documentElement?.style ?? {}),\n\t\t\t\t'onmozfullscreenchange' in w,\n\t\t\t\t'mozInnerScreenX' in w,\n\t\t\t\t'CSSMozDocumentRule' in w,\n\t\t\t\t'CanvasCaptureMediaStream' in w,\n\t\t\t]) >= 4\n\t\t)\n\t}",
"static showCookieWarning() {\n return !getLocal('cookie-warning', false);\n }",
"function checkBrowser()\r\n{\r\n\tvar theAgent = navigator.userAgent.toLowerCase();\r\n\tif(theAgent.indexOf(\"msie\") != -1)\r\n\t{\r\n\t\tif(theAgent.indexOf(\"opera\") != -1)\r\n\t\t{\r\n\t\t\treturn \"opera\";\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn \"ie\";\r\n\t\t}\r\n\t}\r\n\telse if(theAgent.indexOf(\"netscape\") != -1)\r\n\t{\r\n\t\treturn \"netscape\";\r\n\t}\r\n\telse if(theAgent.indexOf(\"firefox\") != -1)\r\n\t{\r\n\t\treturn \"firefox\";\r\n\t}\r\n\telse if(theAgent.indexOf(\"mozilla/5.0\") != -1)\r\n\t{\r\n\t\treturn \"mozilla\";\r\n\t}\r\n\telse if(theAgent.indexOf(\"\\/\") != -1)\r\n\t{\r\n\t\tif(theAgent.substr(0,theAgent.indexOf('\\/')) != 'mozilla')\r\n\t\t{\r\n\t\t\treturn navigator.userAgent.substr(0,theAgent.indexOf('\\/'));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn \"netscape\";\r\n\t\t} \r\n\t}\r\n\telse if(theAgent.indexOf(' ') != -1)\r\n\t{\r\n\t\treturn navigator.userAgent.substr(0,theAgent.indexOf(' '));\r\n\t}\r\n\telse\r\n\t{ \r\n\t\treturn navigator.userAgent;\r\n\t}\r\n}",
"function guardTypescriptVersion() {\n if (!semver.satisfies(ts.version, '>=2.4')) {\n throw new Error(`Installed typescript version ${ts.version} is not supported by stryker-typescript. Please install version 2.5 or higher (\\`npm install typescript@^2.5\\`).`);\n }\n}",
"function isUniversalAnalyticsObjectAvailable() {\n if (typeof ga !== 'undefined') {\n return true;\n }\n return false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
disease which affects 1 in 10,000 people 2% false positive rate or 200 in 10,000 people report and validate result | function sim_test_people(run_people){
console.log("\nsim_test_people with %i people", run_people);
expected_disease_count = run_people * odds_for_disease;
expected_false_positive_count = run_people * odds_for_false_positive;
disease_count = 0;
false_positive_count = 0;
for (i=1; i<= run_people; i++){
// simulate for the ith person
patientID = i;
// we are only interested in positive tests
positive_test = lib.roll_dice_with_odds(odds_for_false_positive);
//if the test is positive, compute chance that ith person has disease
has_disease = lib.roll_dice_with_odds(odds_for_disease);
if ((positive_test == true ) && (has_disease == false)){
false_positive_count++;
//positive test and ith person really has disease
}
if (has_disease == true){
disease_count++;
}
}
//console.log("has_disease %b is and positive_test is %b", has_disease, positive_test)
console.log("expected false_positive %i for %i people", expected_false_positive_count, run_people);
console.log("expected disease count of %i for %i people", expected_disease_count, run_people);
console.log("false_positive is %f and true positive is %f", false_positive_count, disease_count);
console.log("chance a positive test reflects real disease is %i disease count in %i false positives",
disease_count, false_positive_count );
console.log("chance of disease on positive test %f ", disease_count / false_positive_count);
console.log("chance of disease on positive test %f as a percentage", ((disease_count / false_positive_count)*100));
//console.log("real disease: ", true_positive);
} | [
"function boredom(staff){\n let result = 0\n let scores = { 'accounts': 1, 'finance': 2, 'canteen': 10, 'regulation': 3, 'trading': 6, 'change': 6,'IS': 8, 'retail': 5,'cleaning': 4,'pissing about': 25 }\n\n for (let item in staff) {\n result += scores[staff[item]]\n }\n\n\n if (result <= 80) {\n return 'kill me now'\n } else if (result > 80 && result < 100) {\n return 'i can handle this'\n } else {\n return 'party time!!'\n }\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}",
"function runReport() {\n checkAnswers();\n calculateTestTime();\n calculateCheckedInputs();\n\n }",
"function testrate(){\n\t\tvar sum = rate[0]+rate[1]+rate[2]+rate[3];\n\t\tif(sum > 100){\n\t\t\talert(\"rate over more than 100%\");\n\t\t}else{\n\t\t\tif(sum <100){\n\t\t\t\talert(\"rate low than 100%\");\n\t\t\t}else{\n\t\t\t\tdrawcircle();\n\t\t\t\tdrawsmallcircle();\n\t\t\t\tdrawnote();\n\t\t\t\tfillvalue();\n\t\t\t}\n\t\t}\n\t}",
"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}",
"attackOutcome (opponentDodge) {\n let successRoll = this.getRandomInt();\n if (successRoll >= opponentDodge){\n return true;\n } else {\n return false;\n }\n }",
"function calculateDamageHitSuccess(defenderSkillAverage, attackerSkillAverage){\n \n var baseHitPottential = getRandomInt(0, 100);\n var deffenderSkillAdvantage = getPercentage(defenderSkillAverage, attackerSkillAverage)-100;\n \n var hitSuccess = baseHitPottential;\n\n \n \n if(deffenderSkillAdvantage > 0){\n if(deffenderSkillAdvantage > 100){\n deffenderSkillAdvantage = 100;\n }\n hitSuccess = hitSuccess - getRandomInt(0, deffenderSkillAdvantage);\n }\n \n return hitSuccess;\n \n}",
"function assessSituation(dangerLevel, saveTheDay, badExcuse){\n if (dangerLevel > 50){\n console.log(badExcuse);\n } else if (dangerLevel >= 10){\n console.log(saveTheDay);\n } else {\n console.log(\"Meh. Hard pass.\");\n }\n}",
"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}",
"function checkDealerHits(){\n if(0 == dealerTotal[1]){\n if(17 > dealerTotal[0]){\n return true;\n }\n return false;\n }else{\n if(17 > dealerTotal[0] && 17 > dealerTotal[1]){\n return true;\n }\n } \n}",
"function exposuresInfections(infectorPerson) {\n\t// console.log(\"exposing for \" + infectorPerson.pod + \"---\" + infectorPerson.indexInPod );\n\tif (infectorPerson.infection.status === \"infected\" && infectorPerson.infection.quarantine!==true ) {\n\t\tlet n;\n\t\tlet exposuresWithDistancing= Math.floor(infectorPerson.fixedCharacteristics.exposuresPerWeek*(1-infectorPerson.fixedCharacteristics.distancingCompliance)); \n\t\tfor (n=0; n<exposuresWithDistancing; n++) {\n\t\t\t// console.log(\"n is \" + n + \" for \" + infectorPerson.pod + \"---\" + infectorPerson.indexInPod);\n// \t\t\tdraw if inPod or out-of pod.\n\t\t\tlet inPodBoolean=Math.random()<infectorPerson.fixedCharacteristics.podIntegrity;\n\t\t\tif (inPodBoolean) {\n\t\t\t\tlet exposurePerson = getRandomPerson({Spec: \"inPod\", requester: infectorPerson});\n\t\t\t\tmaybeInfect(exposurePerson, infectorPerson);\n\t\t\t} else {\n\t\t\t\tlet exposurePerson = getRandomPerson({Spec: \"none\", requester: infectorPerson});\n\t\t\t\tmaybeInfect(exposurePerson, infectorPerson);\n\t\t\t}\n\t\t}\t\t\t\t\n\t}\n}",
"function resultat(dia, mes, any){\n \n var coeficients = A(any) + B(any) + C(any,mes) + D(mes) + E(dia);\n \n var resultat = coeficients;\n \n return resultat%7;\n}",
"getSumOfDssRatios() {\n let sum = 0;\n for (let disease of this.diseases) {\n sum += this.getDssRatio(disease);\n }\n return sum;\n }",
"function companyBotStrategy(trainingData) {\n let time = 0;\n let correctness = 0;\n trainingData.forEach(data => {\n if (data[1] === 1) {\n time += data[0];\n correctness += data[1];\n }\n });\n\n return time / correctness || 0;\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 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 gymnastics() {\n\n /////////////////// DO NOT MODIFY\n let total = 0; //// DO NOT MODIFY\n let scores = []; // DO NOT MODIFY\n /////////////////// DO NOT MODIFY\n\n /*\n * NOTE: The 'total' variable should be representative of the sum of all\n * six of the judges' scores.\n */\n\n /*\n * NOTE: You need to add each score (valid or not) to the 'scores' variable.\n * To do this, use the following syntax:\n *\n * scores.push(firstScore); // your variable names for your scores\n * scores.push(secondScore); // will likely be different than mine\n */\nlet s1\nlet s2\nlet s3\nlet s4\nlet s5\nlet s6\nlet discard = []\nlet out = 0\n s1 = prompt (\"Please enter the first judge's score.\");\n\n while (s1 < 0 || s1 > 10 ) {\n s1 = prompt (\"Invalid number for the first score. Please enter a interger between 0 to 10 for the first score. \");\n }\n s1 = Number(s1);\n scores.push(s1);\n s2 = prompt (\"Please enter the second judge's score.\");\n while (s2 < 0 || s2 > 10 ) {\n s2 = prompt (\"Invalid number for the second score. Please enter a interger between 0 to 10 for the second score. \");\n }\n s2 = Number(s2);\n scores.push(s2);\n\n s3 = prompt (\"Please enter the third judge's score.\");\n while (s3 < 0 || s3 > 10) {\n s3 = prompt (\"Invalid number for the third score. Please enter a interger between 0 to 10 for the third score. \");\n }\n s3 = Number(s3);\n scores.push(s3);\n\n s4 = prompt (\"Please enter the fourth judge's score.\");\n while (s4 < 0 || s4 > 10 ) {\n s4 = prompt (\"Invalid number for the fourth score. Please enter a interger between 0 to 10 for the fourth score. \");\n }\n s4 = Number(s4);\n scores.push(s4);\n\n s5 = prompt (\"Please enter the fifth judge's score.\");\n s5 = Number(s5);\n while (s5 < 0 || s5 > 10 ) {\n s5 = prompt (\"Invalid number for the fifth score. Please enter a interger between 0 to 10 for the fifth score. \");\n }\n s5 = Number(s5);\n scores.push(s5);\n\n s6 = prompt (\"Please enter the sixth judge's score.\");\n while (s6 < 0 || s6 > 10) {\n s6 = prompt (\"Invalid number for the sixth score. Please enter a interger between 0 to 10 for the sixth score. \");\n }\n s6 = Number(s6);\n scores.push(s6);\ndiscard.push(Math.min(...scores));\ndiscard.push(Math.max(...scores));\n out = discard[0] + discard[1]\nlet scoreFinal = (scores.reduce((a,b) => a + b, 0) - out)/(scores.length-2);\n var p = document.getElementById(\"gymnastics-output\");\n p.innerHTML = \"Discarded: \" + discard[0] + \", \" + discard[1]+ \"</br>\";\n p.innerHTML += \"Score: \" + scoreFinal.toFixed(2) ;\n\n /////////////////////////////// DO NOT MODIFY\n check('gymnastics', scores); // DO NOT MODIFY\n /////////////////////////////// DO NOT MODIFY\n}",
"function percentCoveredCalc(claimant){\n\tvar percentage = 0;\n\tvar careType = claimant.visitType;\n\n\tswitch(careType){\n\t\tcase \"Optical\":\n\t\t\tpercentage = 0;\n\t\t\tbreak;\n\t\tcase \"Specialist\":\n\t\t\tpercentage = 10;\n\t\t\tbreak\n\t\tcase \"Emergency\":\n\t\t\tpercentage = 100;\n\t\t\tbreak;\n\t\tcase \"Primary Care\":\n\t\t\tpercentage = 50;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\treturn percentage;\n\n}",
"function friendlyInter(ad) {\n const prob = Math.random();\n if (ad) { // if tweet is an add, make it more likely it was prompted by a friend's interaction\n return prob > 0.5; // if the interaction belongs to an ad (20% of cases), \n // then make 50% of them friend-inspired interactions\n }\n return prob > 0.8;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize all model assets used on `faceapi. Will call the `setupStream` once all models were loaded | setupAssets() {
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri(FACEDETECTATTR.modelsUri),
faceapi.nets.faceExpressionNet.loadFromUri(FACEDETECTATTR.modelsUri)
]).then(() => {
this.setupStream();
});
} | [
"function init() {\n createjs.Ticker.framerate = animateFps;\n Promise.all([Promise.all(initValueProviders()), Promise.all(initAnimates())]).then(() => {\n Promise.all([initWidgets()]).then(() => {\n resolveValueProviders();\n Object.entries(models).forEach(([, model]) => model.init());\n javascript.onBeforeModelRun.forEach(fn => fn());\n Object.entries(models).forEach(([, model]) => model.play());\n Object.entries(widgets).forEach(([, widget]) => widget.updateComponent());\n spinner.hide();\n });\n });\n}",
"async init() {\n this.handleEventHandlers()\n await this.model.load().then(\n res => {\n if (res) {\n this.setupView(res)\n }\n }\n )\n }",
"function init_model () {\n setup_board ();\n setup_houses ();\n setup_clues ();\n}",
"init() {\n\t\tdocument.body.append(this.view);\n\t\tthis.functions.load();\n\t\tthis.Loader.load(async (loader, resources) => {\n\t\t\tlet i = 0;\n\t\t\tfor (const [name, value] of Object.entries(resources)) {\n\t\t\t\tif (loader.rorkeResources[i].options) {\n\t\t\t\t\tconst urls = await this.Loader.splitSpritesheetIntoTiles(\n\t\t\t\t\t\tvalue.data,\n\t\t\t\t\t\tloader.rorkeResources[i].options,\n\t\t\t\t\t);\n\t\t\t\t\tconst textures = urls.map(tile => Texture.from(tile));\n\t\t\t\t\tthis.spritesheets.set(name, {\n\t\t\t\t\t\ttexture: value.texture,\n\t\t\t\t\t\toptions: loader.rorkeResources[i].options,\n\t\t\t\t\t\ttiles: urls,\n\t\t\t\t\t\ttextures,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthis.textures.set(name, value.texture);\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tthis.runCreate();\n\t\t});\n\t}",
"async initialize() {\n this.loadEnv();\n this.loadConfiguration();\n }",
"function init() {\n var test = AppConfig.testPaper;\n DataManager.loadJSON('/test_assets/' + test + '/' + test + '.json')\n .done(function(){\n\n // load assets\n DataManager.setAssetIndexes({ assetIndex: 0, fileIndex: 0 });\n loadAssets('core');\n })\n .fail(function(){\n\n // stop everything and notify user\n var message = {\n header: \"Initialisation Failure\",\n body: \"<div style='width:400px;'>Unable to initialise \" + test + \".json</div>\",\n footer: \"<button class='close'>OK</button>\",\n modal: true\n }\n Modal.showModal(message);\n });\n }",
"async function loadPredictions() {\n if (capture.loadedmetadata) {\n predictions = await blazeFaceModel.estimateFaces(capture.elt);\n }\n}",
"initGameObjets(){\n\t\tlet modele = this.controller.modele;\n\t\t//Init les objets\n\t\tthis.scene.add(modele.table.model);\n\t\tthis.scene.add(modele.environment.model)\n\t\tthis.scene.add(modele.board.model)\t\t\n\t}",
"async init() { }",
"initCameras() {\n this.camera = new CGFcamera(0.4, 0.1, 500, vec3.fromValues(0, 12, -15), vec3.fromValues(0, 10, 0));\n this.interface.setActiveCamera(this.camera);\n }",
"static _initScreenModels() {\n const artistsRepository = new ArtistsRepository();\n const albumsRepository = new AlbumsRepository();\n const songsRepository = new SongsRepository();\n\n this._screenModels = {\n artistsListScreenModel: new ArtistsListScreenModel(artistsRepository),\n artistDetailsScreenModel: new ArtistDetailsScreenModel(artistsRepository),\n albumsListScreenModel: new AlbumsListScreenModel(albumsRepository),\n albumDetailsScreenModel: new AlbumDetailsScreenModel(albumsRepository),\n songsListScreenModel: new SongsListScreenModel(songsRepository)\n }\n }",
"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 }",
"function initializeModel() {\n // We are using a callback function modelReady\n // But you can also use Promises\n classifier = ml5.imageClassifier('MobileNet',modelReady)\n}",
"constructor() { \n \n PatchedVideoSerializerV2.initialize(this);\n }",
"function initTextures() {\n floorTexture = gl.createTexture();\n floorTexture.image = new Image();\n floorTexture.image.onload = function () {\n handleTextureLoaded(floorTexture)\n }\n floorTexture.image.src = \"./assets/grass1.jpg\";\n\n cubeTexture = gl.createTexture();\n cubeTexture.image = new Image();\n cubeTexture.image.onload = function() {\n handleTextureLoaded(cubeTexture);\n }; // async loading\n cubeTexture.image.src = \"./assets/gifft.jpg\";\n}",
"function resources_loaded_callback(){\n\n console.log(\"Resources loaded.\");\n\n show_loader_div(false);\n show_setting_div(true);\n show_canvas_div(true);\n\n // init mesh manager that may be contains some object loaded by model loader.\n EntityMeshManager.init();\n\n\n }",
"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 }",
"async load(callback) {\n this.loadingStart(this.name);\n\n var promises = [];\n if ( this.file ) {\n var scenePromise = VRSPACEUI.assetLoader.loadAsset( this.baseUrl+this.file,\n // onSuccess:\n (url, container, info ) => {\n this.sceneMeshes = container.meshes;\n this.container = container;\n \n // Adds all elements to the scene\n var mesh = container.createRootMesh();\n mesh.name = this.name;\n container.addAllToScene();\n \n this.loaded( this.file, mesh );\n \n },\n // onError:\n exception => this.loadFailed( exception ),\n // onProgress:\n evt => this.loadProgress(evt, this.name)\n );\n promises.push(scenePromise);\n }\n \n if ( this.objectsFile ) {\n var response = await fetch(this.baseUrl+this.objectsFile);\n var json = response.json();\n this.worldObjects = JSON.parse(json);\n }\n \n if ( this.worldObjects ) {\n this.sceneMeshes = [];\n for ( var url in this.worldObjects ) {\n var instances = this.worldObjects[url].instances;\n if ( !url.startsWith(\"/\") ) {\n // relative url, make it relative to world script path\n url = this.baseUrl+url;\n }\n instances.forEach( (instance) => {\n var objPromise = VRSPACEUI.assetLoader.loadAsset(url,\n // callback \n (loadedUrl, container,info,instances)=>{\n if ( instances ) {\n var mesh = obj.instantiatedEntries.rootNodes[0];\n // CHECKME: untested\n var children = mesh.getChildMeshes();\n this.sceneMeshes.push(...children);\n } else {\n // Adds all elements to the scene\n var mesh = container.createRootMesh();\n var pos = loadedUrl.lastIndexOf('/');\n if ( pos >= 0 ) {\n mesh.name = loadedUrl.substring(pos+1);\n }\n container.addAllToScene();\n this.sceneMeshes.push(...container.meshes);\n }\n if ( instance.position ) {\n mesh.position = new BABYLON.Vector3(instance.position.x, instance.position.y, instance.position.z);\n }\n if ( instance.rotation ) {\n mesh.rotation = new BABYLON.Vector3(instance.rotation.x, instance.rotation.y, instance.rotation.z);\n }\n if ( instance.scale ) {\n mesh.scaling = new BABYLON.Vector3(instance.scale.x, instance.scale.y, instance.scale.z);\n }\n this.loaded( loadedUrl, mesh );\n },\n // onError:\n exception => this.loadFailed( exception ),\n // onProgress:\n evt => this.loadProgress(evt, url)\n );\n promises.push(objPromise);\n });\n }\n }\n \n Promise.all(promises).then(() => {\n VRSPACEUI.log(\"World loaded\");\n this.loadingStop(this.name);\n this.collisions(this.collisionsEnabled);\n if ( callback ) {\n callback(this);\n }\n });\n \n return this;\n }",
"setup() {\n this.material = new THREE.ShaderMaterial({\n uniforms: this.uniforms.uniforms,\n fragmentShader: this.shaders.fragment_shader,\n vertexShader: this.shaders.vertex_shader\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FRONTEND TWEAKS ================================================================== add "Go to last reply" link to thread links | function addThreadLastReplyLink(link, submission) {
if ( submission["section"] == "threads" ) {
link.after(' [<a title="Go to last reply" href="'+link.attr("href")+'?vl[page]=LAST&mid=PostsList#PostsListLastPost">»</a>]');
}
} | [
"toggleReplyRequest (threadViewInitiator='NONE', thread={}, activeClass={}, user={}) {\n if (this.replyRequestedByMe) {\n this.replyRequestCount -= 1\n this.replyRequestedByMe = false\n } else {\n this.replyRequestCount += 1\n this.replyRequestedByMe = true\n\n this.logSpotlightAction('REPLY_REQUEST', thread, activeClass, user, threadViewInitiator)\n }\n if (this.id) {\n const token = localStorage.getItem(\"nb.user\");\n const headers = { headers: { Authorization: 'Bearer ' + token }}\n axios.post(`/api/annotations/replyRequest/${this.id}`, { replyRequest: this.replyRequestedByMe }, headers)\n }\n }",
"replyTo() {\n this.env.messaging.discuss.replyToMessage(this);\n }",
"function user_related_question_view(ref_id){\n var reply_type = \"json\";\n var vars = {};\n if (ref_id == '' || ref_id == undefined){\n vars.url = myhost+'/view/user_question_all/';\n vars.content = \"question\";\n } else {\n vars.url = myhost+'/view/user_question_replys/';\n vars.content = \"replys\";\n }\n vars.ref_id = ref_id;\n global.user_agent\n .get(vars.url)\n .set('Content-Type', 'application/json')\n .query({m_id:ref_id, reply_type:reply_type})\n .end(function(err, res){\n if (err) {\n myutil.error(\"== user_related_question_view ==\", err);\n return\n }\n if (res.ok){\n myutil.debug(\"== user_related_question_view ==\");\n var body = res.text;\n //myutil.debug(res.body, res.text);\n //user_related_question_view_not_leave(body, vars);\n var r = JSON.parse(body);\n var data = r.data;\n var i = Math.floor(Math.random()*data.length);\n myutil.info(data.length, i);\n var msg = data[i];// ref_id = msg._id somtime\n vars.msg = msg;\n if (vars.msg == undefined) {vars.msg = {}; vars.msg._id= '';}\n vars.current_status = \"user_related_question_view\";\n decision(vars);\n } else {\n myutil.error(\"== user_related_question_view ==\", err, res.status);\n }\n });\n}",
"function processMessageLinksForFlatView(question) {\n if (question.correctAnswer && !messageOnPage(question.correctAnswer.ID)) {\n question.correctAnswer.useFullURL = true;\n }\n\n question.helpfulAnswers && question.helpfulAnswers.some(\n function(answer) {\n if (!messageOnPage(answer.ID)) {\n answer.useFullURL = true;\n }\n });\n }",
"function _buildNextLink(options, tp){\n\t\t\t\n\t\tif (options.cp == tp) return '';\n\t\tvar optionsPaging = {};\n\t\tdicUtilObj.deepCopyProperty(options, optionsPaging);\n\t\t\n\t\toptionsPaging.cp = parseInt(optionsPaging.cp) + 1;\n\t\treturn '<a id=\"dic-edi-mailbox-next\" href=\"'+dicUtilUrl.buildUrlObjQuery(null, optionsPaging)+'\" aria-label=\"Next\" class=\"navig-next\">'+\n\t \t\t\t'<span class=\"content\" style=\"right: -77px;\">'+\n\t \t\t\t'<b>Next: '+ (parseInt(options.ps, 10) * (optionsPaging.cp - 1)+ 1) + ' - ' + (parseInt(options.ps, 10) * (optionsPaging.cp)) +\n\t \t\t\t '</b>'+\n\t \t\t\t'<span></span>'+\n\t \t\t\t'</span>'+\n\t \t\t'</a>';\n\t\t\n\n\t}",
"function onclickBtnReply(e) {\n e.preventDefault();\n /**\n * handle action on clicking reply button\n * take the input reply and insert it in\n * replies area\n */\n\n /**\n * get the identifier of the comment\n * @type {*|string}\n */\n\n var id = e.currentTarget.id.split(\"-\")[1];\n\n /**\n * Get id of the reply input area\n * @type {string}\n */\n var replyInputId = \"#comment-\" + id + \"-reply-input\";\n\n /**\n * get the input reply area\n * and store it in the reply\n * @type {*|void|jQuery}\n */\n var reply = $(replyInputId).val();\n\n /**\n * Clear the input reply area\n */\n $(replyInputId).val();\n\n\n /**\n * get the number of replies of this comment\n * to give beside prefix\n */\n\n var repliesAreaId = \"#comment-\" + id + \"-repliesArea\";\n /**\n * Get number of childern to determine the number of replies\n * @type {jQuery}\n */\n var count = $(repliesAreaId).children().length;\n\n /**\n * add 1 to the number of replies\n */\n\n let numOfRepliesId = \"#comment-\" + id + \"-numOfReplies\";\n let numOfReplies = parseInt($(numOfRepliesId).text()) + 1;\n $(numOfRepliesId).text(\"\" + numOfReplies);\n\n /**\n *Create replies using the Reply of prototype\n * @type {Reply}\n */\n\n var date = new Date().toJSON().slice(0, 10);\n var obj = new Reply(id, count);\n obj.date = date;\n obj.text = reply;\n obj.creation();\n\n\n /**\n * Make the reply button disabled\n */\n\n\n $(\"#\" + e.currentTarget.id).attr('disabled', 'disabled');\n\n\n}",
"function show_admin_replies(reply_id) {\n\tvar url = \"mgArticle!getAdminReplies.shtml\";\n\tvar data = {replyId:reply_id};\n\t$.post(url, data, function (data) {\n\t\tvar admin_replies = eval(data);\n\t\tvar replies = [];\n\t\tfor (var i = 0; i < admin_replies.length; i++) {\n\t\t\treplies.push(\"<div class='message'><p><a>\" + admin_replies[i].admin.name + \"</a>\\u8bc4\\u8bba\\u8bf4:<span class='reply_content'>\" + admin_replies[i].replyContent + \"</span></p><p style='text-align: right'><a href=\\\"javascript:delete_admin_reply('\" + admin_replies[i].replyId + \"','\" + reply_id + \"')\\\">Delete Reply</a></p></div>\");\n\t\t}\n\t\t$(\"#admin_replies\").html(replies.join(\"\"));\n\t\t$(\"#admin_reply\").modal();\n\t});\n}",
"threadCreated(thread) {\n\t\tconst { history, dispatch } = this.props\n\t\tthis.setState({thread_id: thread.id})\n\t\thistory.push(`/messages/?thread=${thread.id}`)\n\t\tthis.props.threadCreated(thread);\n\t}",
"function topLevelFeed(messages) {\n return _\n .chain(messages)\n .filter(d => !d.value.replyTo)\n .sortBy('change')\n .reverse()\n .value()\n}",
"function threadRedirect( type ) {\n\t\t\tThread.hook( type, function(data){\n\t\t\t\tApp._APP.postMessage({\n\t\t\t\t\ttype: type,\n\t\t\t\t\tdata: data\n\t\t\t\t}, location.origin );\n\t\t\t});\n\t\t}",
"function updateFeedLink() {\n var bounds = map.getPixelBounds(),\n nwTilePoint = new L.Point(\n Math.floor(bounds.min.x / markers.options.tileSize),\n Math.floor(bounds.min.y / markers.options.tileSize)),\n seTilePoint = new L.Point(\n Math.floor(bounds.max.x / markers.options.tileSize),\n Math.floor(bounds.max.y / markers.options.tileSize));\n\n $('#feed_link').attr('href', $.owlviewer.owl_api_url + 'changesets/'\n + map.getZoom() + '/'\n + nwTilePoint.x + '/' + nwTilePoint.y + '/'\n + seTilePoint.x + '/' + seTilePoint.y + '.atom'\n );\n}",
"function showNextTail() {\n if (tailHistory.length == 0) {\n $(\"#no_tiles_msg\").hide();\n }\n if (tails.length > 0 || currentTailIdx < tailHistory.length - 1) {\n currentTailIdx += 1;\n if (currentTailIdx == tailHistory.length) { \n var newTail = popRandomTail();\n tailHistory.push(newTail);\n addTailToHistoryList(newTail);\n }\n showCurrTail();\n }\n}",
"function showForumTopic(topicID)\r\n{\r\n topic = getForumTopicByID(topicID);\r\n if(topic == null)\r\n return;\r\n \r\n contents = '<h1>' + topic.title + '</h1>';\r\n participant = getParticipantByID(topic.participantID);\r\n if(participant == null)\r\n contents += '<h2>By: Removed participant</h2>';\r\n else\r\n contents += '<h2>By: ' + participant.name + ' ' + participant.surname + '</h2>';\r\n contents += '<p>' + topic.date + '</p>';\r\n contents += '<p>' + topic.text + '</p>';\r\n contents += '<h2>Replies:</h2>';\r\n contents += '<ul>';\r\n for(reply in topic.replies)\r\n {\r\n participant = getParticipantByID(topic.replies[reply].participantID);\r\n contents += '<li>';\r\n if(participant == null)\r\n contents += '<h2>By: Removed participant</h2>';\r\n else\r\n contents += '<h2>By: ' + participant.name + ' ' + participant.surname + '</h2>';\r\n contents += '<p>' + topic.replies[reply].date + '</p>';\r\n contents += '<p>' + topic.replies[reply].text + '</p>';\r\n contents += '</li>';\r\n }\r\n contents += '</ul>';\r\n //Add the reply textbox\r\n contents += '<h2>Reply:</h2>';\r\n contents += '<textarea id=\"forum-topic-reply-area\"></textarea>';\r\n contents += '<input id=\"forum-reply-button\" type=\"button\" value=\"Reply\" class=\"submit\" onclick=\"onForumTopicReplyClicked(' + topicID + ')\"/>';\r\n \r\n document.getElementById(\"center-panel\").innerHTML = contents;\r\n}",
"replyAttributionLine() {\n return `On ${this.formattedDate()}, ${this.fromContact().toString()} wrote:`\n }",
"function user_question_view(ref_id){\n var reply_type = \"json\";\n var vars = {};\n if (ref_id == '' || ref_id == undefined){\n vars.url = myhost+'/view/question_all/';\n vars.content = \"question\";\n } else {\n vars.url = myhost+'/view/question_replys/';\n vars.content = \"replys\";\n }\n vars.ref_id = ref_id;\n global.user_agent\n .get(vars.url)\n .set('Content-Type', 'application/json')\n .query({m_id:ref_id, reply_type:reply_type})\n .end(function(err, res){\n if (err) {\n myutil.error(\"== user_question_view ==\", err);\n return\n }\n if (res.ok){\n myutil.debug(\"== user_question_view ==\");\n var body = res.text;\n //myutil.debug(res.body, res.text);\n //user_question_view_not_leave(body, vars);\n var r = JSON.parse(body);\n var data = r.data;\n var i = Math.floor(Math.random()*data.length);\n var msg = data[i];\n vars.msg = msg;\n if (vars.msg == undefined) {vars.msg = {}; vars.msg._id= '';}\n vars.current_status = \"user_question_view\";\n decision(vars);\n } else {\n myutil.error(\"== user_question_view ==\", err, res.status);\n }\n });\n}",
"goToNextNewComment() {\n if (cd.g.autoScrollInProgress) return;\n\n const commentInViewport = Comment.findInViewport('forward');\n if (!commentInViewport) return;\n\n // This will return invisible comments too in which case an error will be displayed.\n const comment = reorderArray(cd.comments, commentInViewport.id)\n .find((comment) => comment.newness && comment.isInViewport(true) !== true);\n if (comment) {\n comment.$elements.cdScrollTo('center', true, () => {\n comment.registerSeen('forward', true);\n this.updateFirstUnseenButton();\n });\n }\n }",
"function goToPost(id, e){\n var url = window.location.href.split('?')[0];\n url += `?location=comments&post=${id}`;\n window.location.href = url;\n}",
"async function postReply(sub, id) {\n\t$('#reply-button-' + id).attr('disabled', true);\n\tvar body = $('#replytext-' + id).val();\n\tconst data = await v4_post('./api/forum.ssjs', {\n\t\tcall: 'post-reply',\n\t\tsub,\n\t\tbody,\n\t\tpid: id\n\t});\n\tif (data.success) {\n\t\t$('#quote-' + id).attr('disabled', false);\n\t\t$('#replybox-' + id).remove();\n\t\tinsertParam('notice', 'Your message has been posted.');\n\t} else {\n\t\t$('#reply-button-' + id).attr('disabled', false);\n\t}\n}",
"function renderAnswerButtons(messageContent, messageId, question) {\n if (question.canManageQuestionState) {\n var helpfulCount = question.numHelpful;\n var maxHelpfulCount = question.totalNumHelpful;\n var helpfulCountRemaining = maxHelpfulCount-helpfulCount;\n var $parentHeader = $j(messageContent).closest('.j-thread-post').find('header');\n var $dotted = $parentHeader.find('.j-dotted-star');\n var button = $j(messageContent).find('.jive-thread-reply-btn');\n\n if ($parentHeader.find('.j-dotted-star').length == 0)\n $parentHeader.append('<span class=\"j-dotted-star j-ui-elem\"/>');\n\n if (button.length == 0) {\n $j(messageContent.append($j(\"<div>\").addClass('jive-thread-reply-btn')));\n button = $j(messageContent).find('.jive-thread-reply-btn');\n }\n\n var $helpfulStar = $parentHeader.find('.j-helpful-star');\n button.empty();\n $dotted.unbind();\n // First two conditionals: answer already marked.\n if (question.correctAnswer && messageId == question.correctAnswer.ID) {\n button.append(jive.discussions.soy.qUnmarkAsCorrect({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-correct-unmark').click(function() {\n questionSourceCallback.unMarkAsCorrect(messageId, that.renderAll);\n return false;\n });\n }\n else if (question.helpfulAnswers && (containsAnswer(question.helpfulAnswers, messageId))) {\n button.append(jive.discussions.soy.qUnmarkAsHelpful({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-helpful-unmark').click(function() {\n questionSourceCallback.unMarkAsHelpful(messageId, that.unMarkAsHelpful.bind(that, $j(button)));\n return false;\n });\n $helpfulStar.click(function(e) {\n questionSourceCallback.markAsCorrect(messageId, that.renderAll);\n e.preventDefault();\n })\n }\n // Answer not marked.\n else {\n if (question.questionState!='resolved' &&\n !(question.helpfulAnswers && (containsAnswer(question.helpfulAnswers, messageId)))) {\n button.append(jive.discussions.soy.qMarkAsCorrect({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-correct').add($helpfulStar).click(function() {\n questionSourceCallback.markAsCorrect(messageId, function(question) {\n that.renderAll(question);\n jive.dispatcher.dispatch(\"trial.updatePercentComplete\");\n });\n return false;\n });\n }\n if (helpfulCountRemaining>0) {\n button.append(jive.discussions.soy.qMarkAsHelpful({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-helpful').add($dotted).click(function() {\n questionSourceCallback.markAsHelpful(messageId, that.markAsHelpful.bind(that, $j(button)));\n return false;\n });\n\n }\n }\n\n\n\n\n\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
hide the ML slider | function disableML( id ) {
$(id).find(".ml").each( function() {
$(this).slider( "disable" );
$(this).addClass(" vis-hide");
});
} | [
"function exitSlider () {\nmainWrapper.style.display = 'none';\n}",
"function hideSliders() {\r\n $('#about-section-slider, #portfolio-section-slider').hide();\r\n}",
"function hideSlider() {\r\n\tvar mydiv = document.getElementById('day-panel');\r\n\tmydiv.style.display = (mydiv.style.display = 'none');\r\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 }",
"function CloseSilder(){\n modelBG.style.display = \"none\";\n modelSlider.style.display = \"none\";\n }",
"function sg_hide_series(){\n\t\t$('#startup-nav-series').hide('slide', {direction: 'left'}, 250).find('.active').removeClass('active'); // slide out of view then remove all active from nav bar\n\t\t$('#sg-series-container').fadeOut(250).removeClass('active').find('.active').removeClass('active'); // and fade out series view then remove all active\n\t}",
"function hideViz() {\n viz.hide();\n}",
"hide() {\n\t\tthis.element.style.visibility = 'hidden';\n\t}",
"_hide() {\n this._updateTriggerWidth();\n if (this._settings.get_boolean('dock-fixed')) {\n return;\n }\n\n if (this._isHovering() || (this._hoveringDash && !Main.overview._shown)) {\n return;\n }\n\n let intellihideAction = this._settings.get_enum('intellihide-action');\n if (!Main.overview._shown && intellihideAction == IntellihideAction.SHOW_FULL && !this._autohideStatus) {\n return;\n }\n\n let overviewAction = this._settings.get_enum('overview-action');\n if (Main.overview._shown && overviewAction == OverviewAction.SHOW_FULL && !this._autohideStatus) {\n return;\n }\n\n // Only hide if dock is shown, is showing, or is partially shown\n if (this._dockState == DockState.SHOWN || this._dockState == DockState.SHOWING || this._slider.slidex > 0) {\n this._removeAnimations();\n\n // If the dock is shown, wait this._settings.get_double('show-delay') before hiding it;\n // otherwise hide it immediately.\n let delay = 0;\n if (this._dockState == DockState.SHOWN)\n delay = this._settings.get_double('hide-delay');\n\n if (Main.overview._shown && Main.overview.viewSelector._activePage == Main.overview.viewSelector._workspacesPage) {\n this._animateOut(this._settings.get_double('animation-time'), delay, false);\n } else {\n this._animateOut(this._settings.get_double('animation-time'), delay, this._autohideStatus);\n }\n }\n }",
"function unhide()\r\n{\r\n if (document.querySelector('.pumpkin').style.visibility == \"visible\")\r\n {\r\n document.querySelector('.pumpkin').style.visibility = \"hidden\";\r\n }\r\n else\r\n {\r\ndocument.querySelector('.pumpkin').style.visibility = \"visible\";\r\n }\r\n}",
"function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }",
"function hideAxis() {\n g.select('.x.axis')\n .transition().duration(500)\n .style('opacity', 0);\n }",
"hideControls_() {\n this.overlay_.setAttribute('i-amphtml-lbg-fade', 'out');\n this.controlsMode_ = LightboxControlsModes.CONTROLS_HIDDEN;\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 div_hide_learn() {\n\t\tdocument.getElementById('ghi').style.display = \"none\";\n\t}",
"hide() {\n\t\tlet _ = this\n\n\t\t_.timepicker.overlay.classList.add('animate')\n\t\t_.timepicker.wrapper.classList.add('animate')\n\t\tsetTimeout(function () {\n\t\t\t_._switchView('hours')\n\t\t\t_.timepicker.overlay.classList.add('hidden')\n\t\t\t_.timepicker.overlay.classList.remove('animate')\n\t\t\t_.timepicker.wrapper.classList.remove('animate')\n\n\t\t\tdocument.body.removeAttribute('mdtimepicker-display')\n\n\t\t\t_.visible = false\n\t\t\t_.input.focus()\n\n\t\t\tif (_.config.events && _.config.events.hidden)\n\t\t\t\t_.config.events.hidden.call(_)\n\t\t}, 300)\n\t}",
"function hideColorWheel() {\n\t\tctrPicker.background.classList.remove('sli-page-shade-show');\n\t\t\n\t\tCPicker.result.value.setHSV(\n\t\t\tCPicker.markers.hue[0].angle,\n\t\t\tCPicker.markers.satv[0].sat,\n\t\t\tCPicker.markers.satv[0].val,\n\t\t\tctrPicker.alphaSlider.value\n\t\t);\n\t\tCPicker.dispatcher.dispatchEvent(CPicker.onChange);\n\t}",
"updateHandleVisibility() {\n if (!this.slider.target) {\n return;\n }\n\n const handle = this.slider.target.getElementsByClassName('noUi-origin');\n\n if (this.state.current >= this.state.start && this.state.current <= this.state.end) {\n handle[0].classList.remove('is-off-timeline');\n this.slider.set(this.state.current);\n } else {\n handle[0].classList.add('is-off-timeline');\n }\n }",
"function hideLanding() {\r\n let videoBox = document.getElementById('video-box');\r\n let textBar = document.getElementById('text-bar');\r\n let explainerBox = document.getElementById('explainer-box');\r\n let buttonBox = document.getElementById('btn-holder');\r\n let footBox = document.getElementById('foot-holder');\r\n let equalSign = document.getElementById('equal')\r\n \r\n videoBox.classList.add('hidden');\r\n textBar.classList.add('hidden');\r\n explainerBox.classList.add('hidden');\r\n buttonBox.classList.add('hidden');\r\n footBox.classList.add('hidden');\r\n equalSign.classList.add('hidden')\r\n hideChildElements(videoBox)\r\n hideChildElements(textBar)\r\n hideChildElements(explainerBox)\r\n hideChildElements(buttonBox)\r\n hideChildElements(footBox);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
// Private functions // // /////////////////////////// Register item index as active index to the list. | function _registerIndex() {
if (angular.isUndefined(lumx.parentController)) {
return;
}
lumx.parentController.activeItemIndex = $element.index(`.${CSS_PREFIX}-list-item`);
} | [
"function DDLightbarMenu_AddItemHotkey(pIdx, pHotkey)\n{\n\tif ((typeof(pIdx) == \"number\") && (pIdx >= 0) && (pIdx < this.items.length) && (typeof(pHotkey) == \"string\") && (this.items[pIdx].hotkeys.indexOf(pHotkey) == -1))\n\t\tthis.items[pIdx].hotkeys += pHotkey;\n}",
"function setNextItemActive() {\n var items = getItems();\n\n var activeItem = document.getElementsByClassName(\"active\")[0];\n var nextElement = activeItem.nextElementSibling;\n\n if (!nextElement) {\n nextElement = items[0];\n }\n\n changeActiveState(activeItem, nextElement);\n}",
"function getItemIndex(item) {\n return item.parent()\n .find(opts['ui-model-items'])\n .index(item);\n }",
"_updateItemIndexContext() {\r\n const viewContainer = this._nodeOutlet.viewContainer;\r\n for (let renderIndex = 0, count = viewContainer.length; renderIndex < count; renderIndex++) {\r\n const viewRef = viewContainer.get(renderIndex);\r\n const context = viewRef.context;\r\n context.count = count;\r\n context.first = renderIndex === 0;\r\n context.last = renderIndex === count - 1;\r\n context.even = renderIndex % 2 === 0;\r\n context.odd = !context.even;\r\n context.index = renderIndex;\r\n }\r\n }",
"changeIndex(index) {\n // if the item the user clicks on is already the current item, then this item ceases to be the current item (and thus we hide the corresponding buttons)\n // if the item the user clicks on is not the current item, then this item becomes the current item (and thus we show the corresponding buttons)\n this.currentIndex == index ? this.currentIndex = undefined : this.currentIndex = index;\n }",
"updateItemColors(index, val){\n console.log(index);\n this.setState({\n activeFilter: index\n })\n this.props.updateAttributeToShow(val)\n }",
"_activateNextList(list) {\n const nextIndex = list.index + 1;\n if (this.lists.length > nextIndex) {\n this._clearActiveList();\n this._cascadeReset(list);\n const nextList = this._findNextEditableListByIndex(list.index);\n this._setActiveList(nextList);\n this.enableList(nextList.element);\n this.requestData();\n } else {\n this.submit();\n }\n }",
"setActiveItem() {\n const items = this._items, left = this._activeIndex - 1, right = this._activeIndex + 1;\n // if there is only one carousel-item then there won't be any right or left-item.\n if (items.length === 1) {\n items.eq(0).removeClass('left-item right-item');\n return;\n }\n this._indicators.find('>.active').removeClass('active');\n this._indicators.find('> li').eq((items.length + this._activeIndex) % items.length).addClass('active');\n items.filter('.active').removeClass('active');\n items.addClass('left-item');\n items.eq((items.length + left) % items.length).addClass('left-item').removeClass('right-item');\n items.eq((items.length + this._activeIndex) % items.length).removeClass('left-item right-item').addClass('active');\n items.eq((items.length + right) % items.length).addClass('right-item').removeClass('left-item');\n }",
"_setActiveList(list)\n {\n this.activeList = list;\n }",
"setIndex(index) {\n\t\tthis.index = index;\n\t}",
"function indexChanged(index) {\n actions.setTabSelected(index);\n setIndex(index);\n }",
"getActiveIndex() {\n return this.activeIndex;\n }",
"function advanceIndex(){\n if (activeIndex>=(peopleArray.length-1) ){\n oldActiveIndex=activeIndex;\n activeIndex=0;\n }else {\n oldActiveIndex=activeIndex;\n activeIndex++;\n }\n}",
"addItem() {\n this.setState({\n itemCount: this.state.itemCount + 1\n });\n }",
"function getNextActiveItemId(moveAmount, baseIndex, itemCount, defaultActiveItemId) {\n if (moveAmount < 0 && (baseIndex === null || defaultActiveItemId !== null && baseIndex === 0)) {\n return itemCount + moveAmount;\n }\n\n var numericIndex = (baseIndex === null ? -1 : baseIndex) + moveAmount;\n\n if (numericIndex <= -1 || numericIndex >= itemCount) {\n return defaultActiveItemId === null ? null : 0;\n }\n\n return numericIndex;\n}",
"function selectActiveForIndex(index){\n\tlet elm = document.getElementsByClassName('item-active')[index];\n\n\tif(elm){\n\t\t//Identificador del activo\n\t\tlet id_active = elm.getAttribute('data-active');\n\n\t\t//Se actualiza el activo\n\t\tport.postMessage({name:\"update_trading_params\", data:{current_active:id_active}});\n\n\t\tasset_selected = true;\n\t\tbtn_higher.disabled = false;\n\t\tbtn_higher_minimized.disabled = false;\n\t\tbtn_lower.disabled = false;\n\t\tbtn_lower_minimized.disabled = false;\n\n\t\tbtn_higher.classList.remove('disabled');\n\t\tbtn_higher_minimized.classList.remove('disabled');\n\t\tbtn_lower.classList.remove('disabled');\n\t\tbtn_lower_minimized.classList.remove('disabled');\n\n\t\t//Todos los activos de la pantalla\n\t\telm_actives = document.getElementsByClassName('item-active');\n\n\t\tfor(let i = 0; i < elm_actives.length; i++){\n\t\t\telm_actives[i].classList.remove('bg-warning');\n\t\t}\n\n\t\telm.classList.add('bg-warning');\n\n\t\trequestSyncDataTrading();\n\t}\n}",
"function setActiveExamID(index)\n{\n //The true index of an exam in the array list is interpreted through exam type (active, unreleased, released)\n // A A A U U R R R\n //The 3rd active exam is 2 = 0 + 2\n //The 2nd unreleased exam is 4 = 3 + 1\n //The 2nd released exam is 6 = 3 + 2 + 1\n var padding = 0;\n if(activeExamType >= 4)\n padding = 0;\n else if(padding >= 1)\n padding = homeInfo[1].filter((a) => a['status'] == 4).length;\n else\n padding = homeInfo[1].filter((a) => a['status'] == 4 || a['status'] == 3 || a['status'] == 2 || a['status'] == 1).length;\n activeExamID = \"\\'\" + homeInfo[1][padding + index]['id'] + \"\\'\";\n \n}",
"function DDLightbarMenu_SetItemHotkey(pIdx, pHotkey)\n{\n\tif ((typeof(pIdx) == \"number\") && (pIdx >= 0) && (pIdx < this.items.length) && (typeof(pHotkey) == \"string\"))\n\t\tthis.items[pIdx].hotkeys = pHotkey;\n}",
"get activeManifestIndex() {\n if (this.manifest && this.manifest.items && this.activeId) {\n for (var index in this.manifest.items) {\n if (this.manifest.items[index].id === this.activeId) {\n return parseInt(index);\n }\n }\n }\n return -1;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Labs categories list | function getLabsCategories() {
var getLabsCategoriesUrl;
getLabsCategoriesUrl = constantData.SERVER_ADDRESS + apiUrl.categories.CATEGORIES + '/lab';
return serverApi.getData(getLabsCategoriesUrl,true);
} | [
"function getCategories(cv){\n\t'use strict';\n\tvar arr = [];\n\tfor(var i=0; i<cv.category.length; i++){\n\t\tarr.push(cv.category[i].title);\n\t}\n\treturn arr;\n}",
"function getAllCateogorie () {\n return categorie;\n}",
"function fetchcategories() {\n API.getCategories().then(res => {\n const result = res.data.categories;\n console.log(\"RESULT: \", result);\n // alert(result[1].name);\n if (res.data.success == false) {\n } else {\n\n setFetchedCategories(res.data.categories);\n }\n }).catch(error => console.log(\"error\", error));\n }//end of fetch categories from backend",
"function getCategoryList(category) {\n var catList = [];\n self.features.forEach(function(feat, index, array) {\n if (! mrlUtil.arrayContains(catList, feat.category)) {\n catList.push(feat.category);\n }\n });\n return catList;\n }",
"function CategoryList() {\n\tthis.categories = [];\n\tthis.addCategory = addCategory;\n\tthis.removeCategory = removeCategory;\n\tthis.displayWebsites = displayWebsites;\n}",
"function getAssignedCategoriesForAccordionMenu(cat){\r\n var assignedCategoriesPOPStageArray = null; // this stores array of the specialized assigned Categories for speicalized users to be work on in case of ParallelizedOPStage\r\n var assignedCategoryList = new Array(); // this stores the array/list of assigned categories medical hierachy list only for filtered accordion menu only\r\n\r\n if(assignedCategoriesForParallelizedOPStage != null)\r\n assignedCategoriesPOPStageArray = assignedCategoriesForParallelizedOPStage.split(',');\r\n\r\n var count = -1;\r\n if(assignedCategoriesPOPStageArray != null){\r\n // it will check from total categories\r\n for( k = 0; k < cat.length; k++) {\r\n // then will check and populate for primary assigned categories\r\n for( j = 0; j < assignedCategoriesPOPStageArray.length; j++) {\r\n if(cat[k].name == assignedCategoriesPOPStageArray[j].trim() && cat[k].level == 1) {\r\n count++;\r\n assignedCategoryList[count] = cat[k];\r\n break;\r\n }\r\n }\r\n // then will check and populate the assigend subcategories\r\n for(var l = 0; l < assignedCategoryList.length; l++) {\r\n if(cat[k].parentid == assignedCategoryList[l].id) {\r\n count++;\r\n assignedCategoryList[count] = cat[k];\r\n break;\r\n }\r\n }\r\n }\r\n return assignedCategoryList; \r\n }\r\n}",
"function getCategories(setText){\r\n var request = gapi.client.youtube.videoCategories.list({\r\n part: 'snippet',\r\n regionCode: 'US',\r\n });\r\n request.execute( function(response){\r\n //if network error, let user know without the option to try loading \r\n //new comments, because we have no categories to choose from \r\n if( response.code == -1 ){\r\n noConnectionError(false);\r\n }\r\n //otherwise, continue\r\n else{\r\n //if setText argument is true, then display the default text to the user\r\n //once the categories are loaded \r\n if( setText ){\r\n commentP.textContent = 'Read random comments from YouTube. Click the \"New\" button to get started!';\r\n commentP.classList.remove('loading');\r\n loadIcon.classList.remove('animate-loader');\r\n collectedData.currentlyLoading = false;\r\n }\r\n\r\n //loop through the returned categories \r\n for (var i=0; i<response.items.length ; i++){\r\n //categories without assignable as true, won't have any videos,\r\n //so for categories that are 'assignable'\r\n if (response.items[i].snippet.assignable === true){\r\n //store category id in 'list' array\r\n collectedData.categories.list.push(response.items[i]);\r\n //create object property for category id, and populate it with\r\n //default 'unloaded' object\r\n //this will hold videos for this category in future\r\n collectedData.categories[response.items[i].id] = {list: [], loaded: false};\r\n }\r\n }\r\n //store the fact that the categories have been loaded\r\n collectedData.categories.loaded = true;\r\n }\r\n });\r\n}",
"function getCheckedCategories() {\n let availableategories = document.getElementsByClassName('filter-checkbox');\n let checkedCategories = [];\n for (let j = 0; j < availableategories.length; ++j) {\n if (availableategories[j].checked == true) {\n checkedCategories.push(availableategories[j].value);\n }\n }\n return checkedCategories;\n}",
"function getListOfContentsOfAllcategories(categories) {\r\n $scope.dlListOfContentsOfAllcategories = [];\r\n var sortField = 'VisitCount';\r\n var sortDirAsc = false;\r\n\r\n if (categories instanceof Array) {\r\n categories.filter(function(category) {\r\n var dlCategoryContent = {};\r\n dlCategoryContent.isLoading = true;\r\n dlCategoryContent = angular.extend(Utils.getListConfigOf('pubContent'), dlCategoryContent);\r\n $scope.dlListOfContentsOfAllcategories.push(dlCategoryContent);\r\n\r\n pubcontentService.getContentsByCategoryName(category.name, sortField, sortDirAsc, dlCategoryContent.pagingPageSize).then(function(response) {\r\n if (response && response.data) {\r\n var contents = new EntityMapper(Content).toEntities(response.data.Contents);\r\n var category = new Category(response.data.Category);\r\n var totalCount = response.data.TotalCount;\r\n\r\n dlCategoryContent.items = contents;\r\n dlCategoryContent.headerTitle = category && category.title || '';\r\n dlCategoryContent.headerRightLabel = totalCount + '+ articles';\r\n dlCategoryContent.pagingTotalItems = totalCount;\r\n dlCategoryContent.footerLinkUrl = [dlCategoryContent.footerLinkUrl, category && category.name].join('/');\r\n dlCategoryContent.tags = pubcontentService.getUniqueTagsOfContents(contents);\r\n } else {\r\n resetContentList(dlCategoryContent);\r\n }\r\n dlCategoryContent.isLoading = false;\r\n }, function() {\r\n resetContentList(dlCategoryContent);\r\n });\r\n });\r\n }\r\n\r\n function resetContentList(dlCategoryContent) {\r\n dlCategoryContent.items = new EntityMapper(Content).toEntities([]);\r\n dlCategoryContent.headerRightLabel = '0 articles';\r\n dlCategoryContent.pagingTotalItems = 0;\r\n dlCategoryContent.tags = [];\r\n dlCategoryContent.isLoading = false;\r\n }\r\n }",
"get category () {\n\t\treturn this._category;\n\t}",
"getCategories(reflection) {\n const categories = new Set();\n function extractCategoryTags(comment) {\n if (!comment)\n return;\n (0, utils_1.removeIf)(comment.blockTags, (tag) => {\n if (tag.tag === \"@category\") {\n categories.add(models_1.Comment.combineDisplayParts(tag.content).trim());\n return true;\n }\n return false;\n });\n }\n extractCategoryTags(reflection.comment);\n for (const sig of reflection.getNonIndexSignatures()) {\n extractCategoryTags(sig.comment);\n }\n if (reflection.type?.type === \"reflection\") {\n extractCategoryTags(reflection.type.declaration.comment);\n for (const sig of reflection.type.declaration.getNonIndexSignatures()) {\n extractCategoryTags(sig.comment);\n }\n }\n categories.delete(\"\");\n for (const cat of categories) {\n if (cat in this.boosts) {\n this.usedBoosts.add(cat);\n reflection.relevanceBoost =\n (reflection.relevanceBoost ?? 1) * this.boosts[cat];\n }\n }\n return categories;\n }",
"function getSites() {\n\tconst categories = getCategories();\n\n\tfor (category in categories) {\n\t\tlet category_card = document.getElementById(category);\n\t\tconst category_sites = {};\n\t\tfor (site in categories[category]) {\n\t\t\tfor (hotkey in categories[category][site]) {\n\t\t\t\tlet link = categories[category][site][hotkey];\n\t\t\t\tsites[hotkey] = link;\n\t\t\t\tcategory_sites[site] = link;\n\t\t\t}\n\t\t}\n\t\tfor (category_site in category_sites) {\n\t\t\tconst link = category_sites[category_site];\n\t\t\tcategory_card.innerHTML += `<li><a href=${link}>${category_site}</a></li>`;\n\t\t}\n\t}\n}",
"function appendCatList(list) {\n\t\tlet parsedList = JSON.parse(list);\n\n\t\tfor (let i = 0; i < parsedList.length; i++) {\n\t\t\tlet name = parsedList[i].name;\n\t\t\tlet note = parsedList[i].note;\n\t\t\tlet catLI = $(\"<li></li>\").text(name + ' - ' + note);\n\t\t\tcatUL.append(catLI);\n\t\t};\n\t}",
"getCategoryMap() {\n var result = new utils.Map();\n var user = this.getAccount();\n var onlyAttentionSet = this.options_.onlyAttentionSet;\n this.data_.forEach(function(cl) {\n var attention\n if (onlyAttentionSet !== config.OPTION_DISABLED) {\n attention = cl.getCategoryFromAttentionSet(user);\n } else {\n attention = cl.getCategory(user);\n }\n if (!result.has(attention)) {\n result.put(attention, []);\n }\n var cls = result.get(attention);\n if (!cls.includes(cl)) {\n cls.push(cl);\n }\n });\n return result;\n }",
"getYouTubeCategories() {\n axios.get(`https://www.googleapis.com/youtube/v3/videoCategories?part=snippet®ionCode=us&key=AIzaSyB_q0TEto5sFJBMzgqPB8uGFkzByakfoJI`)\n .then(response => {\n this.setState({\n youtubeVideoCategory: response.data.items\n })\n })\n }",
"formatResultCategories() {\n this.resultData.violations.forEach(item => {\n $('#violations ul').append(this.getResultItemHtml(item));\n });\n\n this.resultData.passes.forEach(item => {\n $('#passes ul').append(this.getResultItemHtml(item, 'pass'));\n });\n\n this.resultData.incomplete.forEach(item => {\n $('#incomplete ul').append(this.getResultItemHtml(item));\n });\n }",
"function loadCategory (url) {\n\t$.getJSON( url + '/main_page/build_category', function(data){\n\t\t// console.log(data);\n\t\t// console.log(data[1].type);\n\t\t// console.log(data.length);\n\n\t\t// ALL VIDEOS\n\t\tvar outputVideo = '';\n\t\tfor (var i=0; i < data.length; i++) {\n\t\t\toutputVideo += generateVideoTags(data[i],url);\n\t\t};\n\n\t\t// CATEGORIES\n\t\tvar outputType = \"<p class=\\\"lead\\\"></p><div id=\\\"category\\\" class=\\\"list-group\\\">\";\n\t\toutputType += \"<a href=\\\"nominations.html\\\" class=\\\"list-group-item\\\" style=\\\"color:red\\\">Athlete Nominations</a>\";\n\t\toutputType += \"<a href=\\\"all_type.html\\\" class=\\\"list-group-item\\\">Trending</a>\";\n\t\toutputType += \"<a href=\\\"\" + data[0].type + \".html\\\" class=\\\"list-group-item\\\">\" + data[0].type + \"</a>\";\n\t\tfor (var i=1; i < data.length; i++) {\n\t\t\tif(data[i].type != data[i-1].type){\n\t\t\t\toutputType += \"<a href=\\\"\"+ data[i].type +\".html\\\" class=\\\"list-group-item\\\">\";\n\t\t\t\toutputType += data[i].type;\n\t\t\t\toutputType += \"</a>\";\n\t\t\t}\n\t\t}\n\t\t\toutputType += \"</div>\";\n\t\t\t// console.log(outputVideo);\n\n\t\t\t// LOAD\n\t\t\t$('#list_category').html(outputType);\n\t\t\t$('#list_video').html(outputVideo);\n\t\t\t\n\t\t$('#list_category').mouseenter(loadVideoByCategory(data, url));\n\t\n\t}) // getJSON end \n}",
"function extract(url) {\n var index = url.lastIndexOf(\"category\");\n var cat = '';\n for(index+=9;index < url.length && url[index] != '/';index++) {\n cat += url[index];\n }\n return cat;\n }",
"function getEmojisByCategory(){\n\tlet listOfEmojisPerCategory;\n\tif(categorySelect.value === 'all'){\n\t\tlistOfEmojisPerCategory = listOfEmojis;\n\t\trenderHTML(listOfEmojisPerCategory);\n\t}else\n\t\tlistOfEmojisPerCategory = searchEmoji(categorySelect.value, 'category');\n\treturn listOfEmojisPerCategory;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats all the current cookies in the CookieJar as a string that can be set as the response Cookie header. | toHeader() {
return Object.keys(this.cookies)
.reduce((cookieString, cookieKey) => {
let cookieValue = this.get(cookieKey);
return cookieString + `;${cookieKey}=${cookieValue}`;
}, '')
.replace(';', '');
} | [
"function getAllCookies() {\n const cookiesString = document.cookie || '';\n const cookiesArray = cookiesString.split(';')\n .filter(cookie => cookie !== '')\n .map(cookie => cookie.trim());\n\n // Turn the cookie array into an object of key/value pairs\n const cookies = cookiesArray.reduce((acc, currentValue) => {\n const [key, value] = currentValue.split('=');\n const decodedValue = decodeURIComponent(value); // URI decoding\n acc[key] = decodedValue; // Assign the value to the object\n return acc;\n }, {});\n\n return cookies || {};\n}",
"function getCookies()\n {\n var retPromise = q.defer();\n\n var options = {\n url: REST_URL,\n method: \"GET\",\n };\n request(options, function(error, response, body) {\n // console.log(\"Response: \", response);\n\n console.log(\"Cookies: \".green,response.headers['set-cookie']);\n var cookies = (response.headers['set-cookie']).toString();\n var jsessionid = cookies.split(';');\n jsessionid = jsessionid[0];\n console.log(\"My Cookie:\",jsessionid);\n\n var options = {\n url: BASE_URL+ jsessionid,\n method: \"POST\"\n };\n request(options, function(error, response, body) {\n retPromise.resolve(body);\n });\n // console.log(\"Response Body: \".yellow,body);\n });\n\n return retPromise.promise;\n }",
"function GetAllCookies() {\n \n if (document.cookie === \"\") {\n document.getElementById(\"cookies\").innerHTML = (\"<p style='color: #ff0000;padding-bottom: 15px;'>\" + \"There are no cookies on this page!\" + \"</p>\");\n \n } else {\n document.getElementById(\"cookies\").innerHTML = (\"<p style='color: #000;'>\" + \"These are the cookies on this page:\" + \"</p>\" + \"<p class='utm-values'>\" + document.cookie + \"</p>\");\n }\n }",
"keyForCookie(cookie) {\n const { domain, path, name } = cookie;\n return `${domain};${path};${name}`;\n }",
"function getXsyCookie(){\n let matcher = RegExp(/(xsy_[a-z]+_[a-z]+=[^;]+;)/, 'g');\n let aCookies = [], sCookies = document.cookie, cookie;\n console.log('find all the cookies');\n while((cookie = matcher.exec(sCookies)) != null){\n console.log(cookie[1]);\n aCookies.push(cookie[1]);\n }\n\n console.log(aCookies.join(''));\n return aCookies.join('');\n }",
"function allCookiesList(){\n var cookiesStrings = document.cookie.split(\"; \");\n var cookies2D = [];\n var counter = 0;\n cookiesStrings.forEach(function(cookieItem){\n var cookieNameAndValue = cookieItem.split(\"=\");\n cookies2D[counter] = {\n cookieKey: cookieNameAndValue[0], \n cookieValue: cookieNameAndValue[1]\n };\n counter++;\n });\n return cookies2D;\n}",
"static clearCookie() {\n var cookies = document.cookie.split(\";\");\n\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i];\n var eqPos = cookie.indexOf(\"=\");\n var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;\n if (name.trim().toLowerCase() == 'voting-username')\n document.cookie = name + \"=;expires=Thu, 01 Jan 1970 00:00:00 GMT\";\n }\n \n }",
"function getCookieInfo () {\n // return the contact cookie to be used as an Object\n return concurUtilHttp.getDeserializedQueryString($.cookie('concur_contact_data'));\n }",
"function cookieFromFilterpanel(){\n var ch = [];\n if ($j('.shop-filter-panel .filter-toggle').hasClass(\"open\")){\n ch.push(true);\n }\n\n $j.cookie(\"filterpanelCookie\", ch.join(','));\n}",
"async function propagateBrowserCookieValues() {\n\n let zitiCookies = await ls.getWithExpiry(zitiConstants.get().ZITI_COOKIES);\n if (isNull(zitiCookies)) {\n zitiCookies = {}\n }\n\n // Obtain all Cookie KV pairs from the browser Cookie cache\n\tlet browserCookies = Cookies.get();\n\tfor (const cookie in browserCookies) {\n\t\tif (browserCookies.hasOwnProperty( cookie )) {\n\t\t\tzitiCookies[cookie] = browserCookies[cookie];\n\t\t}\n\t}\n\n await ls.setWithExpiry(zitiConstants.get().ZITI_COOKIES, zitiCookies, new Date(8640000000000000));\n}",
"_initCookies() {\n\n const KEY = window.btoa('' + Math.random() * Math.random() * Math.random() * Math.PI),\n COOKIE = new Cookies(),\n PREFIX = 'default-wid';\n // expire cookie a month from now\n let expDate = new Date(Date.now());\n expDate.setDate(expDate.getDate() + 30);\n COOKIE.set(PREFIX, KEY, { path : '/', expires : expDate });\n }",
"function setCookie(){\r\n\tvar items = document.getElementsByClassName(\"list-group-item\");\r\n\tvar itemText = new Array();\r\n\tfor (var i = 0; i < items.length; i++){\r\n\t\titemText[i] = items[i].id;\r\n\t}\r\n\tdocument.cookie = \"items=\" + itemText.join(\"|\");\r\n}",
"function encodeCookie(o, key) {\n try {\n if (key == null) { return null; }\n o.time = Math.floor(Date.now() / 1000); // Add the cookie creation time\n const iv = Buffer.from(crypto.randomBytes(12), 'binary'), cipher = crypto.createCipheriv('aes-256-gcm', key.slice(0, 32), iv);\n const crypted = Buffer.concat([cipher.update(JSON.stringify(o), 'utf8'), cipher.final()]);\n return Buffer.concat([iv, cipher.getAuthTag(), crypted]).toString('base64').replace(/\\+/g, '@').replace(/\\//g, '$');\n } catch (e) { return null; }\n}",
"function writeCookies(hostname, cookies) {\n getCurrentTabUrl(function(url) {\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i];\n\n chrome.cookies.remove({\n \"url\": url,\n \"name\": cookie.name\n });\n chrome.cookies.set({\n \"url\": url,\n \"name\": cookie.name,\n \"value\": cookie.value,\n \"domain\": cookie.domain,\n \"path\": cookie.path,\n \"secure\": cookie.secure,\n \"httpOnly\": cookie.httpOnly,\n \"expirationDate\": cookie.expirationDate,\n \"storeId\": cookie.storeId\n });\n }\n });\n\n chrome.tabs.getSelected(null, function(tab) {\n var code = 'window.location.reload();';\n chrome.tabs.executeScript(tab.id, {code: code});\n });\n}",
"function cookieGetSettings() {\n return JSON.parse($.cookie(cookie));\n }",
"function saveToCookies()\n{\n const THREE_YEARS_IN_SEC = 94670777;\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"player_id\",\n \"value\": MY_ID,\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC) });\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"whitelisted_ids_length\",\n \"value\": WHITELISTED_IDS.length.toString(),\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC)});\n for (let index = 0; index < WHITELISTED_IDS.length; index++) {\n const WHITELISTED_ID = WHITELISTED_IDS[index];\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"whitelisted_id\"+index.toString(),\n \"value\": WHITELISTED_ID.toString(),\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC) });\n }\n}",
"function getCookieOptions() {\n let cookieOpt = {\n httpOnly: true\n };\n if (opt.cookieDomain) {\n cookieOpt.domain = opt.cookieDomain;\n }\n if (opt.secure) {\n cookieOpt.secure = true;\n }\n if (opt.cookiePath) {\n cookieOpt.path = opt.cookiePath;\n }\n if (opt.sameSite) {\n cookieOpt.sameSite = typeof opt.sameSite === 'string' ? opt.sameSite : true;\n }\n return cookieOpt;\n }",
"function setCookie( /* String */name, /* String */value) {\n\tvar date = new Date();\n\tdate.setFullYear(date.getFullYear() + 20);\n\t$.cookies.del(\"felix-webconsole-\" + name);\n\t$.cookies.set(\"felix-webconsole-\" + name, value, {\n\t\texpiresAt : date,\n\t\tpath : appRoot\n\t});\n}",
"function writeCookie(name, value)\n{\n var expire = \"\";\n expire = new Date((new Date()).getTime() + 24 * 365 * 3600000);\n expire = \"; expires=\" + expire.toGMTString();\n document.cookie = name + \"=\" + escape(value) + expire;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set leverage for symbol | async leverage(params) {
if (!params.hasOwnProperty('leverage')) {
params['leverage'] = "20";
}
var schema = {
stub: { required: 'string', format: 'lowercase', },
symbol: { required: 'string', format: 'uppercase', },
type: { required: 'string', format: 'lowercase', oneof: ['cross', 'isolated'] },
leverage: { required: 'string', format: 'lowercase', },
}
if (!(params = this.utils.validator(params, schema))) return false;
this.initialize_exchange(params);
const stub = params.stub
var result = await this.exchange[stub].execute('leverage',params);
if ((result !== false) && (result.result !== 'error')) {
this.output.success('leverage_set', [params.symbol, params.leverage.toLowerCase().replace('x',''), params.type])
} else {
this.output.error('leverage_set', params.symbol)
}
} | [
"set price(value) {\n this._price = 80;\n }",
"set metallic(value) {}",
"SetTurtle(num) {\n if (num == 1) { this.turtleToughness = -1; this.turtleCapacity = 1; this.capacity += this.turtleCapacity; }\n if (num == 2) { this.turtleToughness = -1; this.turtleCapacity = 2; this.capacity += -1 + this.turtleCapacity; }\n if (num == 3) { this.turtleToughness = -2; this.turtleCapacity = 4; this.capacity += -2 + this.turtleCapacity; }\n }",
"hunt() {\n this.food += 2\n }",
"set softwareDamage (softwareDamage) {\n this._softwareDamage = softwareDamage\n }",
"setBundlingStrength(strength) {\n this.bundleStrength = strength;\n }",
"function adjustInit (luckySign, luckModifier) {\n var adjust = 0;\n if (luckySign.luckySign != undefined && luckySign.luckySign === \"Speed of the Cobra\"){\n adjust = luckModifier;\n }\n\treturn adjust;\n}",
"set speedVariation(value) {}",
"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 increaseCostofSubsequentMultiplierPurchase(){\r\n widgetMaker.multiplierCost = widgetMaker.multiplierCost * 1.1;\r\n }",
"function set_spawn_rate(entity_name) {\n if (altitude <= altitude_checkmark) {\n return;\n }\n altitude_checkmark += ALTITUDE_CHUNK;\n var rate_delta = 1;\n\n var entity = ENTITY_VALUE_MAP[entity_name];\n\n if (entity.DIPLOMACY === DIPLOMACY.OBSTACLE) {\n // obstacles get more frequent\n entity.SPAWN_RATE = Math.max(\n entity.SPAWN_RATE - rate_delta, entity.RATE_CAP);\n } else if (entity.DIPLOMACY === DIPLOMACY.POWERUP) {\n // powerups start at a high rate and lose frequency\n entity.SPAWN_RATE = Math.min(\n entity.SPAWN_RATE + rate_delta, entity.RATE_CAP);\n } else if (entity.DIPLOMACY === DIPLOMACY.NEUTRAL) {\n // do nothing\n }\n}",
"function changeFruitPrice (fruit) {\n\tvar priceAdj = 0;\n\t//randomly chooses a value between -50 and 50\n\tpriceAdj = randomNumber(-50,50);\n\t//turns it in to cents\n\tpriceAdj /= 100;\n\tconsole.log(\"priceAdj\", priceAdj);\n\tfruit.price +=priceAdj;\n\t//prevents the fruit price from going above 9.99 and below .50\n\tif (fruit.price > 9.99) {\n\t\tfruit.price = 9.99;\n\t} else if (fruit.price < 0.50) {\n\t\tfruit.price = 0.50;\n\t}\n\tvar price = '#' + fruit.name + \"Price\";\n\t$(price).text(fruit.price.toFixed(2));\n}",
"getPrice() {\n return this.beveragePrice;\n }",
"applyDiscount(discount) {\n this.discount = discount;\n this.beveragePrice *= (1 - discount);\n }",
"changeStockPrices(state) {\n state.stocks.forEach(stock => {\n stock.price = Math.round(stock.price * (1 + Math.random() - 0.5));\n });\n }",
"trendingMeanReverted(event) {\n document.getElementById(\"StartPrice\").value = \"21.00\";\n document.getElementById(\"msPerSec\").value = \"15\";\n document.getElementById(\"numLiq\").value = \"100\";\n document.getElementById(\"numInf\").value = \"50\";\n document.getElementById(\"numMom\").value = \"50\";\n document.getElementById(\"numPStar\").value = \"3\";\n document.getElementById(\"FracOfDay\").value = \"1\";\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 }",
"burnFuel(){\n this.fuel -=1;\n }",
"function setSpeed(s)\r\n{\r\n \r\n ballSpeed = s;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParsermodify_column_clauses. | visitModify_column_clauses(ctx) {
return this.visitChildren(ctx);
} | [
"visitModify_mv_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitColumn_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAdd_modify_drop_column_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitModel_column_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAdd_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDrop_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSubstitutable_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAdd_mv_log_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAlter_collection_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitRename_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitColumn_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitColumn_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitParen_column_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitVirtual_column_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitModifier_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitModel_column_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitColumn_based_update_set_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function _addColumn(){\n self._visitingAlter = true;\n var table = self._queryNode.table;\n self._visitingAddColumn = true;\n var result='ALTER TABLE '+self.visit(table.toNode())+' ADD '+self.visit(alter.nodes[0].nodes[0]);\n for (var i= 1,len=alter.nodes.length; i<len; i++){\n var node=alter.nodes[i];\n assert(node.type=='ADD COLUMN',errMsg);\n result+=', '+self.visit(node.nodes[0]);\n }\n self._visitingAddColumn = false;\n self._visitingAlter = false;\n return [result];\n }",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates spot objects from JSON responses. | function createSpots(spotRes) {
const spots = [];
for (const spot in spotRes) {
if (spotRes.hasOwnProperty(spot)) {
// Check if there are coordinates, and if there are comments. Set to default values if none.
const latitude = spotRes[spot].latitude === undefined ? null : spotRes[spot].latitude;
const longitude = spotRes[spot].longitude === undefined ? null : spotRes[spot].longitude;
let comments = spotRes[spot].comments;
if (comments === undefined) {
comments = [];
}
// Create a new spot
const newSpot = new Spot(
spotRes[spot].name,
spotRes[spot].information,
spotRes[spot].address,
spotRes[spot].area,
spotRes[spot].country,
spotRes[spot].image,
latitude,
longitude,
spot,
spotRes[spot].userId,
spotRes[spot].likes,
spotRes[spot].dislikes,
comments);
spots.push(newSpot);
}
}
return spots;
} | [
"function loadResponse(){\n var APODObject = JSON.parse(this.response)\n APODList.push(APODObject)\n}",
"function getSongs(Query) {\n var spotify = new Spotify(LiriTwitterBOT.spotify);\n if (!Query) {\n Query = \"what's+my+age+again\";\n };\n spotify.search({ type: 'track', query: Query }, function(err, data) {\n if ( err ) {\n console.log('Error occurred: ' + err);\n return;\n }\n console.log(data);\n // Do something with 'data' \n });\n\n // var queryURL = 'https://api.spotfiy.com/v1/search?q=' + query + '&limit=5&type=track';\n // request(queryURL, function(err, response, body) {\n // if (err) {\n // console.log(err);\n // };\n // body = JSON.parse(body);\n // console.log(body);\n // for (var i = 0; i < body.tracks.items.length; i++) {\n // logObject = input + \", \" + query + \", \" + body.tracks.items[i].artists[0].name + \", \" + body.tracks.items[i].name\n // body.tracks.items[i].name + \", \" + body.tracks.items[i].preview_url + \", \" + body.tracks.items[i].album.name + \"\\n\";\n // }; //end of loop\n // writeLog(logObject);\n // });\n}",
"async loadFromJSON(JSONs) {\n if(JSONs) {\n let JSONObj = JSONs.JSONItems\n for (let i = 0; i < JSONObj.length; i++) {\n let product = new Product(JSONObj[i].id, JSONObj[i].name, JSONObj[i].price, JSONObj[i].image);\n for (let j = 0; j < JSONObj[i].count; j++) {\n await this.addItem(product);\n }\n }\n }\n }",
"function getTopSpots() {\n \tvar defer = $q.defer();\n \t// $http.get('topspots.json').then(\n $http.get('http://localhost:50180/api/TopSpots').then(\n \t\tfunction(response) {\n // Return data from source\n \t\t\tconsole.log(response.data);\n defer.resolve(response.data);\n \t\t},\n \t\tfunction(err) {\n // Return error\n \t\t\tconsole.log(err);\n defer.reject(\"An unexpected error occured.\");\n \t\t}\n \t\t);\n \t\treturn defer.promise;\n }",
"function createJSON(items) {\n return {\n readings: items.map(element => {\n return {point: element, consumption: Math.floor(Math.random() * 5)}\n })\n }\n}",
"function constructResponseJson() {\n return response = {\n \"response\" : {\n \"head\" : {\n \"id\" : \"123123\"\n },\n \"payload\" : {}\n }\n };\n }",
"function zomatoApi(r) {\n $(\"#answersDiv\").empty();\n $(\"#question\").empty();\n $(\"#apiDiv\").empty();\n fetch(\n \"https://developers.zomato.com/api/v2.1/search?entity_id=280&entity_type=city&q=\" +\n r,\n {\n headers: {\n \"user-key\": \"504af04e6861c274d55e91c18d40ac0d\"\n }\n }\n )\n .then(function(response) {\n console.log(response);\n return response.json();\n })\n .then(function(data) {\n console.log(data);\n var restaurants = data.restaurants;\n\n var i = 0;\n var p = 4;\n restloop();\n $(\"#more\").on(\"click\", function(event) {\n event.preventDefault();\n $(\"#apiDiv\").empty();\n i += 4;\n p = i + 4;\n restloop();\n });\n function restloop() {\n for (i; i < p; i++) {\n console.log(restaurants[0].restaurant.name);\n console.log(restaurants[0].restaurant.events_url);\n console.log(restaurants[0].restaurant.average_cost_for_two);\n console.log(restaurants[0].restaurant.location.locality);\n\n var mainDiv = $(\"<div>\");\n mainDiv.addClass(\"col-md-3\");\n mainDiv.attr(\"id\", \"randCard\");\n var restName = $(\"<h5>\");\n restName.text(restaurants[i].restaurant.name);\n $(mainDiv).append(restName);\n\n var restImg = $(\"<img>\");\n restImg.attr(\"src\", restaurants[i].restaurant.featured_image);\n restImg.attr(\"class\", \"card-img-top\");\n restImg.attr(\"id\", \"randImg\");\n $(mainDiv).append(restImg);\n\n var restLocation = $(\"<p>\");\n restLocation.text(restaurants[i].restaurant.location.locality);\n $(mainDiv).append(restLocation);\n\n var restPrice = $(\"<p>\");\n restPrice.text(\n \"Average cost for 2: $\" +\n restaurants[i].restaurant.average_cost_for_two\n );\n $(mainDiv).append(restPrice);\n\n var restUrl = $(\"<button>\");\n restUrl.addClass(\"btn btn-outline-info\");\n restUrl.addClass(\"moreInfo\");\n restUrl.text(\"More Info!\");\n $(mainDiv).append(restUrl);\n $(\".moreInfo\").on(\"click\", function() {\n window.location = restaurants[i].restaurant.events_url;\n });\n\n $(\"#apiDiv\").append(mainDiv);\n }\n }\n });\n}",
"function proccessResults() {\n // console.log(this);\n var results = JSON.parse(this.responseText);\n if (results.list.length > 0) {\n resetData();\n for (var i = 0; i < results.list.length; i++) {\n geoJSON.features.push(jsonToGeoJson(results.list[i]));\n }\n drawIcons(geoJSON);\n }\n }",
"function createMarkers(result) {\n // console.log(result); \n for (var i=0; i < result.length; i++) {\n\n var latLng = new google.maps.LatLng (result[i].lot_latitude, result[i].lot_longitude); \n\n var marker = new google.maps.Marker({\n position: myLatlng,\n title: result [i].lot_name,\n customInfo: {\n name: result[i].lot_name,\n address: result[i].lot_address,\n available: result[i].spot_id\n };\n });\n\n// To add the marker to the map, call setMap();\nmarker.setMap(map);\n\ncreateMarkers(result);\n };\n }",
"function getParkingSpotsBySpace(spaceId) {\n\n\tspots = \n\n\tjQuery.ajax({\n\t\turl: \"http://10.10.20.6/apigw/devnetlabapi/cdp/v1/devices/parking?UserKey=500109&SensorCustomerKey=500050&AppKey=CDP-App\", \n\t\ttype: \"POST\",\n\t\tdata: JSON.stringify({\n\t\t \"Query\": {\n\t\t \"Find\": {\n\t\t \"ParkingSpot\": {\n\t\t \"parkingSpaceId\": spaceId\n\t\t }\n\t\t }\n\t\t }\n\t\t}),\n\t\tbeforeSend: function(xhr) {\n\t\t\txhr.setRequestHeader('WSO2-Authorization', 'oAuth Bearer 32b37facf21b4deadc93a261e2dc4f2');\n\t\t\txhr.setRequestHeader('Authorization', 'Bearer 9sY1mKjZgJDa0yw3LHBdaJetU68y');\n\t\t\txhr.setRequestHeader('Accept', 'application/json');\n\t\t\txhr.setRequestHeader('Content-Type', 'application/json');\n\t\t},\n\t\tsuccess: function(data){\n\t\t\tvar result = [];\n\n\t\t\tspots = data['Find']['Result'];\n\n\t\t\tconsole.log(spots.length);\n\n\t\t\tfor(var i=0; i < spots.length; i++) {\n\t\t\t\tvar spot = spots[i]['ParkingSpot'];\n\t\t\t\tvar sid = spot['sid'];\n\t\t\t\tvar label = spot['label']\n\t\t\t\tvar occupied = spot['state']['occupied'];\n\n\t\t\t\tresult.push({\"sid\": sid, \"label\": label, \"occupied\": occupied});\n\t\t\t}\n\n\t\t\tconsole.log(JSON.stringify(result));\n\t\t\t//console.log();\n\t\t}, \n\t\terror: function(error) {\n\t\t\talert(\"error happend!\");\n\t\t\talert(error);\n\t\t}\n\t});\n}",
"function getStreamingServicesTvSeason(\n imdbId,\n entertainmentType,\n entertainmentType2,\n seasonNum\n) {\n var movieServicesLookupUrl =\n \"https://api.themoviedb.org/3/\" +\n entertainmentType +\n \"/\" +\n imdbId +\n \"/\" +\n entertainmentType2 +\n \"/\" +\n seasonNum +\n \"providers?api_key=42911e57fe3ba092d02b0df7293493b3\";\n fetch(movieServicesLookupUrl)\n .then(function (response) {\n return response.json();\n })\n .then(function (data) {\n console.log(data);\n // console.log(Object.keys(data.results.US));\n // console.log(Object.keys(data.results.US).includes(\"flatrate\"));\n console.log(Object.keys(data.results));\n services = [];\n obj.services = [];\n if (Object.keys(data.results).length == 0) {\n obj.services[0] = { name: \"No streaming services\" };\n } else if (Object.keys(data.results.US).includes(\"flatrate\")) {\n for (var j = 0; j < data.results.US.flatrate.length; j++) {\n services[j] = data.results.US.flatrate[j].provider_name;\n var logoPath = data.results.US.flatrate[j].logo_path;\n var networkLogo = getNetworkLogo(logoPath);\n switch (services[j]) {\n case \"IMDB TV Amazon Channel\":\n obj.services[j] = { name: services[j], url: imdbUrl, logo: networkLogo };\n break;\n case \"Hulu\":\n obj.services[j] = { name: services[j], url: huluUrl, logo: networkLogo };\n break;\n case \"fuboTV\":\n obj.services[j] = { name: services[j], url: fuboTvUrl, logo: networkLogo };\n break;\n case \"Netflix\":\n obj.services[j] = { name: services[j], url: netflixUrl, logo: networkLogo };\n break;\n case \"Apple TV Plus\":\n obj.services[j] = { name: services[j], url: appleTvPlusUrl, logo: networkLogo };\n break;\n case \"YoutubeTV\":\n obj.services[j] = { name: services[j], url: YoutubeTvUrl, logo: networkLogo };\n break;\n case \"HBO Max\":\n obj.services[j] = { name: services[j], url: HBOMaxUrl, logo: networkLogo };\n break;\n case \"HBO Now\":\n obj.services[j] = { name: services[j], url: HBONowUrl, logo: networkLogo };\n break;\n case \"DIRECTV\":\n obj.services[j] = { name: services[j], url: DirecTvUrl, logo: networkLogo };\n break;\n case \"Disney Plus\":\n obj.services[j] = { name: services[j], url: disneyPlusUrl, logo: networkLogo };\n break;\n case \"TNT\":\n obj.services[j] = { name: services[j], url: tntUrl, logo: networkLogo };\n break;\n case \"TBS\":\n obj.services[j] = { name: services[j], url: tbsUrl, logo: networkLogo };\n break;\n case \"tru TV\":\n obj.services[j] = { name: services[j], url: truTvUrl, logo: networkLogo };\n break;\n case \"Paramount+ Amazon Channel\":\n obj.services[j] = { name: services[j], url: paramountPlusUrl, logo: networkLogo };\n break;\n case \"CBS\":\n obj.services[j] = { name: services[j], url: cbsUrl, logo: networkLogo };\n break; \n case \"Sling TV\":\n obj.services[j] = { name: services[j], url: slingTvUrl, logo: networkLogo };\n break; \n case \"Spectrum On Demand\":\n obj.services[j] = { name: services[j], url: spectrumOnDemandUrl, logo: networkLogo };\n break; \n case \"Peacock Premium\":\n obj.services[j] = { name: services[j], url: peacokPremiumUrl, logo: networkLogo };\n break; \n case \"Funimation Now\":\n obj.services[j] = { name: services[j], url: funimationNowUrl, logo: networkLogo };\n break; \n case \"Adult Swim\":\n obj.services[j] = { name: services[j], url: adultSwimUrl, logo: networkLogo };\n break; \n default:\n obj.services[j] = { name: data.results.US.flatrate[j].provider_name, url: \" \", logo: networkLogo };\n break;\n }\n }\n } else {\n obj.services[0] = { name: \"No streaming services in US\" };\n }\n console.log(services);\n console.log(obj);\n renderMovieCard(obj);\n });\n}",
"extractValidObjects(responseJson) {\n let objectList = [];\n for (let i = 0; i < responseJson.value.length && objectList.length < maxSearchResults; i++) {\n if (\n this.isValidUrl(responseJson.value[i].PrimaryImageUrl) &&\n this.isValidUrl(responseJson.value[i].LinkResource)\n ) {\n // Extract all objects with a valid image and resource Urls\n objectList.push(responseJson.value[i]);\n }\n }\n return objectList;\n }",
"function filmRequest (){\n var response = JSON.parse( this.responseText );\n var films = response.results;\n\n for( var filmNum = 0; filmNum < films.length; filmNum++ ){\n\n var currentFilm = films[ filmNum ];\n\n var filmTitleContainer = document.createElement( 'h2' );\n filmTitleContainer.className = 'filmTitle';\n filmTitleContainer.innerHTML = currentFilm.title;\n\n var planetTitleContainer = document.createElement( 'h3' );\n planetTitleContainer.className = 'planetTitle';\n planetTitleContainer.innerHTML = 'Planets';\n filmTitleContainer.appendChild( planetTitleContainer );\n\n var planetsContainer =document.createElement( 'ul' );\n planetsContainer.className = 'filmPlanets';\n\n var planetArray = currentFilm.planets;\n for( var planetNum = 0; planetNum < planetArray.length; planetNum++ ){\n\n planetDivMaker( planetsContainer, planetArray[ planetNum ] );\n\n\n filmTitleContainer.appendChild( planetsContainer );\n }\n var filmListTarget = document.getElementById( 'filmList' );\n filmListTarget.appendChild( filmTitleContainer );\n }\n}",
"function getGooglePlacesData2(results, status) {\n //\n if (status == google.maps.places.PlacesServiceStatus.OK) {\n //\n for (var i = 0, l = results.length; i < l; i++) {\n //\n placesObj = {\n id: \"\",\n name: \"\",\n status: \"\",\n openNow: \"\",\n rating: \"\",\n userRatingTotal: \"\",\n priceLevel: \"\",\n photos: [],\n types: [],\n };\n //\n // Place data\n //\n placesObj.id = results[i].place_id;\n placesObj.name = results[i].name;\n placesObj.status = results[i].business_status;\n // placesObj.openNow = results[i].opening_hours.isOpen;\n placesObj.rating = results[i].rating;\n placesObj.userRatingTotal = results[i].user_ratings_total;\n placesObj.priceLevel = results[i].price_level;\n //\n // Photos\n //\n for (var j = 0, m = results[i].photos.length; j < m; j++) {\n //\n photoObj = {\n url: \"\",\n };\n //\n photoObj.url = results[i].photos[j].html_attributions[0];\n //\n placesObj.photos.push(photoObj);\n //\n }\n //\n // Types\n //\n for (var k = 0, n = results[i].types.length; k < n; k++) {\n //\n typeObj = {\n name: \"\",\n };\n //\n typeObj.name = results[i].types[k];\n //\n placesObj.types.push(typeObj);\n //\n }\n //\n places.push(placesObj);\n //\n }\n //\n renderGooglePlacesData();\n //\n }\n //\n}",
"function callStackAPI() {\n $.ajax({\n url: urlStack,\n method: \"GET\"\n }).then(function (response) {\n for (var i = 0; i < 5; i++) {\n var qstnObject = {};\n var keywordURL = \"\";\n var keywordTitle = \"\";\n qstnObject.keywordURL = response.items[i].link;\n qstnObject.keywordTitle = response.items[i].title;\n questionsArray.push(qstnObject);\n }\n showQuestions(questionsArray);\n })\n}",
"function fetchOpeningMoviesFromRottenTomatoes() {\n console.log('fetching opening movies from rotten tomatoes');\n \n http.get('http://api.rottentomatoes.com/api/public/v1.0/lists/movies/opening.json?apikey=' + rottenTomatoesApiKey, function (res) {\n var data = '';\n \n res.on('data', function (chunk) {\n data += chunk;\n });\n \n res.on('end', function () {\n data = JSON.parse(data);\n saveMovies(data.movies).then(function (movies) {\n openingMovies = movies;\n });\n });\n });\n}",
"function processJSON( data ) { \r\n \r\n // this will be used to keep track of row identifiers\r\n var next_row = 1;\r\n \r\n // iterate matches and add a row to the result table for each match\r\n $.each( data.matches, function(i, item) {\r\n var row_id = 'result_row_' + next_row++;\r\n \r\n // append new row to end of table\r\n $('<tr/>', { \"id\" : row_id } ).appendTo('tbody');\r\n\r\n });\r\n \r\n // show results section that was hidden\r\n $('#results').show();\r\n}",
"function processResponseForPopular(responseText) {\n let response = JSON.parse(responseText);\n\n if (response.results.length > 0) {\n var movieDiv1 = document.getElementById('popularCardGroup1');\n var movieDiv2 = document.getElementById('popularCardGroup2');\n var movieDiv3 = document.getElementById('popularCardGroup3');\n var movieDiv4 = document.getElementById('popularCardGroup4');\n\n for (var i = 0; i < 12; i++) {\n let movie = response.results[i];\n let cardDiv = createMovieCard(movie);\n\n if (i <= 2)\n movieDiv1.appendChild(cardDiv);\n else if (i > 2 && i <= 5)\n movieDiv2.appendChild(cardDiv);\n else if (i > 5 && i <= 8)\n movieDiv3.appendChild(cardDiv);\n else if (i > 8 && i <= 11)\n movieDiv4.appendChild(cardDiv);\n }\n }\n}",
"jsonParser(photos){\n let farmIds = [];\n let serverIds = [];\n let ids = [];\n let secretIds = [];\n\n photos.forEach(element => {\n farmIds.push(element.farm);\n serverIds.push(element.server);\n ids.push(element.id);\n secretIds.push(element.secret);\n});\n this.imageLinkBuilder(farmIds,serverIds,ids,secretIds);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor allows for one passenger initialization using singleton pattern sets up connections and creates user object | function Passenger(options) {
if (!_singleton) {
this.config = $.extend(true, {}, DEFAULTS, options); // overrides config defaults
this.setupConnections();
this.user = {};
_singleton = this;
}
return _singleton;
} | [
"async init() {\r\n await Managers.findOne({username: this.username}, function(error, manager) {\r\n if(error) {\r\n console.log(error);\r\n return;\r\n }\r\n else {\r\n this.production = manager.production; \r\n this.powerPlantStatus = manager.powerPlantStatus; \r\n this.electricityPrice = manager.electricityPrice;\r\n this.marketRatio = manager.marketRatio;\r\n this.bufferRatio = manager.bufferRatio;\r\n this.bufferBatteryCapacity = manager.bufferBatteryCapacity;\r\n this.bufferBattery = new BufferBattery(this.username, manager.bufferBatteryCapacity, config.managerBatteryMaxCapacity);\r\n this.blackoutList = manager.blackoutList;\r\n console.log(\"Initialized manager\");\r\n }\r\n }.bind(this)).exec();\r\n }",
"constructor(userProfileObj){\n this._user = userProfileObj.user || userProfileObj._user || {};\n this._userConnections = userProfileObj.userConnections || userProfileObj._userConnections || []; \n }",
"constructor() {\n super();\n //for adapters\n this.services = {};\n //for registry\n this.data = { pwd: process.env.PWD };\n }",
"constructor() { \n BaseResponse.initialize(this);MailThreadOneAllOf.initialize(this);\n MailThreadOne.initialize(this);\n }",
"function init(input_params) {\n\tvar input_args = input_params.toString().match(/\\S+/g);\n\t//console.log('input_args: ' + input_args);\n\tvar params = ['',''].concat(input_args);\n\t//console.log('client disconnected');\n\tvar d = domain.create();\n\td.on('error', function(err) {\n\t\tconsole.error(\"EXCEPTION IN USER SERVICE APPLICATION:\");\n\t\tconsole.error(\"Error Object:\");\n\t\tutil.inspect(err,{showHidden: true, depth: 1}).split(/\\r?\\n/)\n\t\t .forEach(function(s) {console.error(s)});\n\t\tconsole.error(\"Stack trace:\");\n\t\terr.stack.toString().split(/\\r?\\n/)\n\t\t .forEach(function(s) {console.error(s)});\n\t\t// Unload user service application module if possible.\n\t\tif (err.domain && err.domain.service_dir) {\n\t\t\tvar mainModuleFile = require.resolve(err.domain.service_dir);\n\t\t\tunified_service.unrequire(mainModuleFile);\n\t\t}\n\t});\n\td.run(function() {\n\t\tbootstrap.parse(loadAndStart, params);\n\t});\n}",
"function init(){\n controllerInit(routerInitModel);\n serviceAuthorizeOps(globalEmitter,'admin',globalDataAccessCall);\n serviceAuthenticate(globalEmitter,'user',globalDataAccessCall);\n genericDataAccess(dataAccessInitModel);\n}",
"constructor(firstName, lastName, username, password, guid)\n\t{\n\t\tthis.guid = guid;\n\t\tthis.username = username;\n\t\tthis.firstName = firstName;\n\t\tthis.lastName = lastName;\n\t\tthis.password = password;\n\t\tthis.preferences = new UserPreferences();\n\t}",
"constructor() {\n this.router = express.Router(); // eslint-disable-line new-cap\n this.logger = new Logger();\n this.contr = new Controller();\n }",
"connect(){\n // add a session\n App.core.use(bodyParser.urlencoded({extended: true}));\n App.core.use(bodyParser.json());\n App.core.use(cookieParser());\n\n // init store\n this.config.store = new sessionStore({\n database: App.db.connection, // there will be stablished connection in lazyLoad mode\n sessionModel: App.db.models.sessions,\n transform: function (data) {\n return data;\n },\n ttl: (60 * 60 * 24),\n autoRemoveInterval: (60 * 60 * 3)\n });\n\n // run session \n App.core.use(session(this.config));\n }",
"constructor(){\n \n // If class already instatiated, return the initial instance\n if (typeof this.instance === 'object') {\n return this.instance;\n }\n\n // Load Firebase modules and config files\n var firebase = require(\"firebase\"); \n var firebaseConfig = require('./../firebase.json');\n var firebaseAdmin = require(\"firebase-admin\");\n var firebaseAdminConfig = require('./../firebase.admin.json');\n\n // Instantiate key class properties\n this.firebase = firebase.initializeApp(firebaseConfig);\n this.firebaseAdmin = firebaseAdmin.initializeApp({\n credential: firebaseAdmin.credential.cert(firebaseAdminConfig),\n storageBucket: firebaseConfig.storageBucket,\n });\n this.storage = firebaseAdmin.firestore();\n this.bucket = firebaseAdmin.storage().bucket();\n\n // Store first instance, and return it\n this.instance = this;\n return this;\n }",
"constructor() {\r\n ObjectManager.instance = this;\r\n\r\n }",
"function handle_user_init_reg(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}",
"init(actor) {\n this.host = actor\n }",
"constructor() { \n \n VpcPeeringConnection.initialize(this);\n }",
"async created () {\n // Create a new instance of OIDC client using members of the given options object\n this.oidcClient = new Oidc.UserManager({\n userStore: new Oidc.WebStorageStateStore(),\n authority: options.authority,\n client_id: options.client_id,\n redirect_uri: redirectUri,\n response_type: options.response_type,\n scope: options.scope\n })\n\n try {\n // If the user is returning to the app after authentication..\n if (\n window.location.hash.includes('id_token=') &&\n window.location.hash.includes('state=') &&\n window.location.hash.includes('expires_in=')\n ) {\n // handle the redirect\n await this.handleRedirectCallback()\n onRedirectCallback()\n }\n } catch (e) {\n this.error = e\n } finally {\n // Initialize our internal authentication state\n this.user = await this.oidcClient.getUser()\n this.isAuthenticated = this.user != null\n this.loading = false\n }\n }",
"constructor() { \n \n MozuTenantContractsTenant.initialize(this);\n }",
"constructor() { \n \n MailParticipant.initialize(this);\n }",
"function UserMessageProcessor(serverConfig, effigy, dbConn, connTracker,\n _logger) {\n this.serverConfig = serverConfig;\n this.effigy = effigy;\n this.store = new $ustore.UserBehalfDataStore(effigy.rootPublicKey,\n dbConn);\n this.connTracker = connTracker;\n this._logger = _logger;\n}",
"constructor() { \n \n StakingLedger.initialize(this);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read the email file indicated for the test | readEmailFile (callback) {
const inputFile = this.emailFile + '.eml';
let path = Path.join(process.env.CSSVC_BACKEND_ROOT, 'inbound_email', 'test', 'test_files', inputFile);
FS.readFile(
path,
'utf8',
(error, emailData) => {
if (error) { return callback(error); }
this.emailData = emailData;
callback();
}
);
} | [
"async onStopSending(msgId, status, msg, returnFile) {\n ok(returnFile.exists(), \"createRFC822Message should create a mail file\");\n let content = await IOUtils.read(returnFile.path);\n content = String.fromCharCode(...content);\n ok(\n content.includes(\"Subject: Test createRFC822Message\\r\\n\"),\n \"Mail file should contain correct subject line\"\n );\n ok(\n content.includes(\n \"createRFC822Message is used by nsImportService \\xe4\\xe9\"\n ),\n \"Mail file should contain correct body\"\n );\n do_test_finished();\n }",
"function parseEmail(email) {\n return new Promise(function (resolve, reject) {\n var mailparser = new MailParser();\n var chunks = [];\n var chunklength = 0;\n\n // create messageStream\n var messageStream = client.createMessageStream(email.UID);\n\n // fetch a part of data\n messageStream.on(\"data\", function (chunk) {\n // push chunk to chunks\n chunks.push(chunk);\n chunklength += chunk.length;\n });\n\n // all data fetched\n messageStream.on(\"end\", function () {\n // concatenate to Buffer and convert to string\n var body = Buffer.concat(chunks);\n var emailStr = body.toString();\n\n // send the email source to the parser\n mailparser.end(emailStr);\n });\n\n mailparser.on(\"end\", function (mail_object) {\n resolve(mail_object);\n });\n\n // if error\n //reject(\"Error\");\n });\n }",
"readText() {\n const filePath = this._fullname;\n const text = fs.readFileSync(filePath, 'utf-8');\n return text;\n }",
"async getLastEmail() {\n // makes debugging very simple\n // console.log('Getting the last email')\n\n try {\n const connection = await imaps.connect(emailConfig)\n\n // grab up to 50 emails from the inbox\n await connection.openBox('INBOX')\n const searchCriteria = ['1:50', 'UNDELETED']\n const fetchOptions = {\n bodies: [''],\n }\n const messages = await connection.search(searchCriteria, fetchOptions)\n // and close the connection to avoid it hanging\n connection.end()\n\n if (!messages.length) {\n // console.log('Cannot find any emails')\n return null\n } else {\n // console.log('There are %d messages', messages.length)\n // grab the last email\n const mail = await simpleParser(\n messages[messages.length - 1].parts[0].body,\n )\n // console.log(mail.subject)\n // console.log(mail.text)\n\n\n // and returns the main fields\n return {\n subject: mail.subject,\n text: mail.text,\n html: mail.html,\n }\n }\n } catch (e) {\n // and close the connection to avoid it hanging\n // connection.end()\n\n console.error(e)\n return null\n }\n }",
"function load_emails(mailbox) {\n fetch('/emails/'+mailbox)\n .then(response => response.json())\n .then(emails => {\n // Print out emails to correct mailbox\n emails.forEach(function(item) {\n if (item.read != true) {\n document.querySelector('#emails-view').innerHTML += `<div id=\"email-view-mail\"><button class=\"btn btn-outline-dark\" onclick=\"open_email(${item.id})\"><span id=\"inbox-sender\"><strong>${item.sender}</strong></span></button> <span id=\"inbox-subject\">${item.subject}</span> <span id=\"inbox-timestamp\">${item.timestamp}</span></div>`\n } else {\n document.querySelector('#emails-view').innerHTML += `<div id=\"email-read-mail\"><button class=\"btn btn-outline-dark\" onclick=\"open_email(${item.id})\"><span id=\"inbox-sender\"><strong>${item.sender}</strong></span></button> <span id=\"inbox-subject\">${item.subject}</span> <span id=\"inbox-timestamp\">${item.timestamp}</span></div>`\n }\n });\n });\n}",
"readAttachment(){\n return new Promise((resolve, reject) => {\n\n //attachment url \n // GET https://graph.microsoft.com/v1.0/users/{userid}/messages/{msgid}/attachments/\n this.options.url=this.prop_recv.url+ this.prop_recv.accountId + '/messages/' + this.messageId + '/attachments/';\n\n request(this.options, function (error, response) {\n if (error) throw new Error(error);\n //console.log(\"Attachment -\" + response.body);\n resolve(response);\n });\n });\n }",
"function parseUnicodeTestFile() {\n console.log(\"parse unicode test file\");\n fs.readFile(__dirname + '/data/unicode_test.rtf', 'utf8', function(err, data) {\n if (err) { console.log('error: ' + err); }\n let rtfParser = new RTFParser(data, standardIgnoreList);\n\n rtfParser.parse(function(result) {\n assert.equal(57, result.length);\n });\n });\n}",
"async reload() {\n\t\t\n\t\t// try to create the queue directory if it does not yet exist\n\t\tif (!(await SMTPUtil.exists(this.config.queueDir))) {\n\t\t\tawait SMTPUtil.mkdirp(this.config.queueDir);\n\t\t}\n\t\t\n\t\t// read all queued mails from the queue dir\n\t\tlet files = await SMTPUtil.readDir(this.config.queueDir);\n\t\t\n\t\t// load all files\n\t\tfor (let file of files) {\n\t\t\t\n\t\t\t// skip files that are not ending on .meta.info\n\t\t\tif (file.split('.')[2] !== 'info') continue;\n\t\t\n\t\t\t// resolve the full path to the file\n\t\t\tlet infoFile = path.join(this.config.queueDir, file);\n\t\t\n\t\t\ttry {\n\t\t\t\t\n\t\t\t\t// parse the file contents and schedule it\n\t\t\t\tlet content = await SMTPUtil.readFile(infoFile);\n\t\t\t\tlet mail = JSON.parse(content);\n\t\t\t\tthis.queue.schedule(0, mail);\n\t\t\t\t\n\t\t\t} catch (ex) {\n\t\t\t\t\n\t\t\t\t// failed to read or parse the file\n\t\t\t\tthrow new Error(`Failed to parse mail stats from file \"${infoFile}\": ${ex.message || ex}`);\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t}",
"function getEmail() {\n $http.get('/mail/messages').then(function(response) {\n if (response.data) {\n console.log('mail data', response.data);\n $scope.allMessageInfo = response.data.items;\n $scope.allMessages = [];\n $scope.allMessageInfo.forEach(function(item, index) {\n\n $http.post('/mail/messages/item', item).then(function(response1) {\n\n $scope.message = response1.data;\n console.log('job id from email: ', $scope.message['X-Mailgun-Variables']);\n //console.log($scope.message);\n var matches = $scope.message.Subject.match(/\\[(.*?)\\]/);\n\n if (matches) {\n var id = matches[1];\n console.log(\"submatch\", id);\n if (item.event == 'stored') {\n\n console.log('message matched to subject', $scope.message);\n $scope.messageObject = {\n message: $scope.message['stripped-text'],\n timestamp: item.timestamp * 1000,\n username: $scope.message.sender,\n msgType: 'received'\n };\n $http.put('/chats/' + id, $scope.messageObject).then(function(req, res) {\n $scope.messageContainer = {};\n });\n\n }\n }\n\n });\n\n });\n\n } else {\n console.log('error');\n }\n });\n }",
"function setUpMailerAndGo() {\n\tvar passwordPromise = promptly.password('Enter your email password: ', { replace: '*' });\n\n\tpasswordPromise.then(function(password) {\n\t\tvar transportSetup = config.smtp;\n\t\ttransportSetup.auth.pass = password;\n\t\tmailer = nodemailer.createTransport(transportSetup);\n\n\t\tmailer.verify(function(error, success) {\n\t\t\tif (error) {\n\t\t\t\tconsole.error(error);\n\t\t\t} else {\n\t\t\t\tconsole.log('Successfully connected to SMTP server\\n');\n\t\t\t\treadCsvAndIterate();\n\t\t\t}\n\t\t});\n\t});\n}",
"function parseFile() {\n if (file === \"\") file = \"test.txt\";\n try { \n\tvar data = fs.readFileSync(file, 'utf8');\n\treturn data.split('\\n');\n } catch(e) {\n\tconsole.log('Error:', e.stack);\n }\n\n}",
"function setEmailContent(maildata)\n{\n /*\n Check with Joi if all the mandatory data is available\n Choose the appropriate template based on mailOccassion\n default email type is html\n load the html template based on the occasion and replace the required name, etc...\n */ \n let mailDetails;\n switch (maildata.mailOccasion)\n {\n case 'usercreation':\n console.log('Mail Occasion : ' + maildata.mailOccasion);\n let htmlStr = file.readFileSync(conf.get('templates.userCreation'), 'utf-8');\n //console.log('sendMail - htmlStr: ', htmlStr);\n let replacedStr = htmlStr.replace(/#cusName/i, maildata.cusName);\n replacedStr = replacedStr.replace(/#userName/i, maildata.to);\n replacedStr = replacedStr.replace(/#welcomeUrl/i, maildata.url);\n mailDetails = \n {\n from: uName,\n to: maildata.to,\n subject: mailSub,\n html: replacedStr\n } \n //console.log('sendMail - mailDetails: ', mailDetails);\n //attachments: [{filename: 'nandhi.png', path: conf.get('templates.userCrePic'), cid: 'nandhi@lor' }]\n return mailDetails; \n case 'repsubscribe':\n console.log('Mail Occasion : ' + maildata.mailOccasion);\n mailDetails = \n {\n from: uName,\n to: maildata.to,\n subject: mailSub,\n html: maildata.htmlContent,\n attachments: \n [{filename: maildata.fileName, path: maildata.path, contentType: maildata.contentType }]\n //[{filename: 'rep.pdf', path: '../convertedPdf/test3.pdf', contentType: 'application/pdf' }]\n }\n return mailDetails;\n case 'custom':\n console.log('Mail Occasion : ' + maildata.mailOccasion);\n mailDetails = \n {\n from: uName,\n to: maildata.to,\n subject: maildata.subject,\n html: maildata.htmlContent\n }\n return mailDetails;\n case 'default': \n console.log('Mail Occasion : ' + maildata.mailOccasion);\n return mailDetails;\n }\n}",
"function getPriorityUnreadEmails() {\n let priorityUnreadEmails = [];\n\n // priority inbox unread emails\n const priorityInboxUnread = GmailApp.getPriorityInboxUnreadCount();\n Logger.log(\"Priority inbox unread : \" + priorityInboxUnread);\n\n // new priority inbox emails\n if (priorityInboxUnread) {\n // retrieves all priority inbox unread threads\n const allPriorityInboxUnreadThreads = GmailApp.getPriorityInboxThreads(0, priorityInboxUnread);\n\n allPriorityInboxUnreadThreads.forEach((priorityInboxUnreadThread) => {\n let unreadEmailMessage = \"\";\n\n // gets the messages in priotiry inbox unread thread\n const messages = priorityInboxUnreadThread.getMessages();\n\n messages.forEach((message) => {\n\n // gets the sender of this message\n const sender = extractEmails(message.getFrom());\n\n // check sender is priority contact list\n const isPriorityContact = priorityContactListEmails.includes(sender);\n\n // new inbox is my contact list emails and unread\n if (isPriorityContact && message.isUnread) {\n // sender\n Logger.log(\"New Inbox Email From My Contact List : \" + sender);\n unreadEmailMessage += \"\\n\\n📥New email from : \" + sender;\n\n // email subject\n const emailSubject = message.getSubject();\n Logger.log(\"Email Subject :\" + emailSubject);\n unreadEmailMessage += \"\\n\\n🏷️Subject : \" + emailSubject;\n\n // email contents with replaces all 3 types of line breaks with single line break (\\n) and more white space with single white space\n const emailContents = message.getPlainBody().replace(/(\\r\\n|\\n|\\r)+/g, \"\\n\").replace(/( )+/g,\" \");\n Logger.log(\"Email Content :\" + emailContents);\n\n if (emailContents.length < 300) {\n unreadEmailMessage += \"\\n\\n📋Contents : \" + emailContents;\n } else {\n unreadEmailMessage += \"\\n\\n📋Contents : \" + emailContents.slice(0, 300) + \"...\";\n }\n\n // email attatchments\n const attatchments = message.getAttachments();\n if (attatchments.length !== 0) {\n // get attachment file url for download\n const attachmentFileUrls = saveAttachmentFiles(attatchments, attachmentFolderId);\n\n attachmentFileUrls.forEach(fileUrl => unreadEmailMessage += \"\\n\\n🔗Attachment File : \" + fileUrl);\n }\n\n // marks the message as read\n message.markRead();\n\n // stars the message\n message.star();\n\n // reloads this message and associated state from Gmail\n message.refresh();\n\n // reply to sender\n message.reply(\"Got your message, Thank you.✌️\\n\\n\" + \"Chaiyachet ✌️\\n\\n\" + \"This email is auto-generated. Please do not reply.\");\n }\n\n // add messages for send to line notify\n if (unreadEmailMessage !== \"\") {\n priorityUnreadEmails.push(unreadEmailMessage);\n }\n })\n })\n } else {\n Logger.log(\"📥 No new priority inbox unread ✌️\");\n }\n\n return priorityUnreadEmails;\n}",
"contentFor(page) {\n\t\tlet reader = this.readers[page.extension];\n\t\tlet pathToFile = this.pathToPageContent(page);\n\n\t\tlet content = '';\n\t\tif (typeof reader.readFile !== 'undefined') {\n\t\t\tcontent = reader.readFile(pathToFile);\n\t\t} else {\n\t\t\tcontent = fs.readFileSync(pathToFile, 'utf8');\n\t\t}\n\n\t\tif (!reader) {\n\t\t\tthrow new Error(`No reader for file extension '${page.extension}'`)\n\t\t} else if (typeof reader.read !== 'function') {\n\t\t\tthrow new Error(`Reader for file extension '${page.extension}' has no read method`);\n\t\t}\n\n\t\treturn reader.read(content);\n\t}",
"function readAndParseFile (file)\n{\n\tvar whichFile = doActionEx\t('DATA_READFILE',file, 'FileName', file,'ObjectName',gPRIVATE_SITE, \n\t\t\t\t\t\t\t\t'FileType', 'txt');\n\treturn (doActionEx('PAR_PARSE_BUFFER','Result', 'document', whichFile));\n}",
"function setupTestAccounts() {\n\n const UNITTEST_ACCT_NAME = \"Enigmail Unit Test\";\n const Cc = Components.classes;\n const Ci = Components.interfaces;\n\n // sanity check\n let accountManager = Cc[\"@mozilla.org/messenger/account-manager;1\"].getService(Ci.nsIMsgAccountManager);\n\n\n function reportError() {\n return \"Your profile is not set up correctly for Enigmail Unit Tests\\n\" +\n \"Please ensure that your profile contains exactly one Account of type POP3.\\n\" +\n \"The account name must be set to '\" + UNITTEST_ACCT_NAME + \"'.\\n\" +\n \"Alternatively, you can simply delete all accounts except for the Local Folders\\n\";\n }\n\n function setIdentityData(ac, idNumber, idName, fullName, email, useEnigmail, keyId) {\n\n let id;\n\n if (ac.identities.length < idNumber - 1) throw \"error - cannot add Identity with gaps\";\n else if (ac.identities.length === idNumber - 1) {\n id = accountManager.createIdentity();\n ac.addIdentity(id);\n }\n else {\n id = ac.identities.queryElementAt(idNumber - 1, Ci.nsIMsgIdentity);\n }\n\n id.identityName = idName;\n id.fullName = fullName;\n id.email = email;\n id.composeHtml = true;\n id.setBoolAttribute(\"enablePgp\", useEnigmail);\n\n if (keyId) {\n id.setIntAttribute(\"pgpKeyMode\", 1);\n id.setCharAttribute(\"pgpkeyId\", keyId);\n }\n }\n\n function setupAccount(ac) {\n let is = ac.incomingServer;\n is.downloadOnBiff = false;\n is.doBiff = false;\n is.performingBiff = false;\n is.loginAtStartUp = false;\n\n setIdentityData(ac, 1, \"Enigmail Unit Test 1\", \"John Doe I.\", \"user1@enigmail-test.net\", true, \"ABCDEF0123456789\");\n setIdentityData(ac, 2, \"Enigmail Unit Test 2\", \"John Doe II.\", \"user2@enigmail-test.net\", true);\n setIdentityData(ac, 3, \"Enigmail Unit Test 3\", \"John Doe III.\", \"user3@enigmail-test.net\", false);\n setIdentityData(ac, 4, \"Enigmail Unit Test 4\", \"John Doe IV.\", \"user4@enigmail-test.net\", true);\n }\n\n for (let acct = 0; acct < accountManager.accounts.length; acct++) {\n let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);\n if (ac.incomingServer.type !== \"none\") {\n if (ac.incomingServer.type !== \"pop3\" || ac.incomingServer.prettyName !== UNITTEST_ACCT_NAME) {\n throw reportError();\n }\n }\n }\n\n let configured = 0;\n\n // try to configure existing account\n for (let acct = 0; acct < accountManager.accounts.length; acct++) {\n let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);\n if (ac.incomingServer.type !== \"none\") {\n setupAccount(ac);\n ++configured;\n }\n }\n\n // if no account existed, create new account\n if (configured === 0) {\n let ac = accountManager.createAccount();\n let is = accountManager.createIncomingServer(\"dummy\", \"localhost\", \"pop3\");\n is.prettyName = UNITTEST_ACCT_NAME;\n ac.incomingServer = is;\n setupAccount(ac);\n }\n}",
"readVuefile (filePath, savePath, err, data) {\n if (err) {\n this._clientPool.sendTransformFailedNotify(err)\n } else {\n this._clientPool.sendTransformSuccessNotify([])\n let oreoMessage = JSON.stringify(createOreoMessage('weex', data, '', path.parse(filePath).base, filePath, path.parse(filePath).base))\n this._clientPool.sendAllClientMessage(oreoMessage)\n }\n }",
"function ParseiCalFeed(){\n log.info('Parse ical file');\n ical.fromURL(config.icalurl, {}, ParseiCalData);\n //ParseiCalData('',ical.parseFile('/home/jimshoe/dev/makerslocal/eventwitter/calendar.ics.test'));\n}",
"function getAttachmentData( data )\n{\n\t// Get list of raw attachments. First index is previous portion of raw message,\n\t// so length is one less than array length.\n\tlet rawAttachments = data.split( \"Content-Disposition: attachment;\" );\n\tlet numAttachments = rawAttachments.length - 1;\n\n\t// Create array to hold string contents and file titles.\n\tlet contents = [];\n\tlet titles = [];\n\n\tlet rawAttachment;\n\tlet i, j;\n\n\tfor( i = 1; i <= numAttachments; i++ )\n\t{\n\t\t// Verify that an attachment exists. Break if it doesn't.\n\t\tif( rawAttachments[ i ] === undefined )\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\n\n\t\t// Get portion of raw message relating to the 'ith' \n\t\t// attachment then get lines of raw attachment.\n\t\tlet rawAttachmentLines = rawAttachments[ i ].split( \"\\n\" );\n\n\n\t\t// The second line contains the filename in the format 'filename=\"<filename>\"'.\n\t\t// Parse this out to get the filename.\n\t\tlet filename = rawAttachmentLines[ 1 ].substring( 11, rawAttachmentLines[ 1 ].length - 2 );\n\t\t\n\n\t\t// Only add the file if it is a share, tag-x-x, or k-x-x.\n\t\tif( /(share|tag-[0-9]+-[0-9]+|k-[0-9]+-[0-9]+)/.exec( filename ) )\n\t\t{\n\t\t\t// Get Base64 content from raw message by looping through the attachment lines.\n\t\t\t// First three lines are blank line, filename, and blank line. So we must skip those\n\t\t\t// before parsing the rest of the text (i.e., start at j = 3).\n\t\t\tlet content = \"\";\n\t\t\tfor( j = 3; j <= rawAttachmentLines.length - 1; j++ )\n\t\t\t{\n\t\t\t\t// Boundary in raw message with attachment begins with fourteen hyphens.\n\t\t\t\t// If line begins with this, then stop parsing and break out of loop.\n\t\t\t\tif( rawAttachmentLines[ j ].startsWith( \"--------------\" ) ) break;\n\n\n\t\t\t\t// Add current line to content.\n\t\t\t\tcontent += rawAttachmentLines[ j ];\n\t\t\t}\n\n\n\t\t\t// Attachment area ends with an extra newline.\n\t\t\t// This needs to be removed before decryption.\n\t\t\tcontent = content.substring( 0, content.length - 1 );\n\n\n\n\t\t\tcontents.push( content );\t// Store the current content string.\n\t\t\ttitles.push( filename );\t// Store the current filename.\n\t\t}\n\t}\n\n\treturn [ contents, titles ];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Places farm by point on the map, adds a path to farm | function generateFarm( stateMap, x, y, style ) {
var shiftX = Math.floor( (Math.random() - 0.5)*FARM_DIST );
var shiftY = (shiftX < 0 ) ? (FARM_DIST + shiftX) : (FARM_DIST - shiftX);
var farmX = x + shiftX;
var farmY = y + shiftY;
// Create windy path between castle and farm (using A*)
var success = false;
while ( !success ) {
var pathmap = new Array( MAP_SIZE );
for ( var row = 0; row < MAP_SIZE; row++ ) {
pathmap[row] = new Array( MAP_SIZE );
for ( var col = 0; col < MAP_SIZE; col++ ) {
pathmap[row][col] = 0;
}
}
success = buildPath( x, y, farmX, farmY, pathmap );
}
pathmap = success;
// Convert path into tiles on map
stateMap = setPathStyles( stateMap, pathmap, "free" );
stateMap[farmY][farmX] = {
type: "farm", style: Math.floor(Math.random() * 4), solid: false,
style: style,
};
return stateMap;
} | [
"function addLocation()\r\n{\r\n let newWaypoint = currentRoute.routeMarker.getPosition();\r\n currentRoute.waypoints.push(newWaypoint);\r\n currentRoute.displayPath();\r\n}",
"function dreamFlightPath(x, y, zx, zy, colour) {\n var ax = 200 + x;\n var ay = 700 + (y - 150);\n var bx = 255 + (zx - 100);\n var by = 500 + (zy - 400);\n controls = \tmap.set(\n \t\tmap.circle(x, y, 15).attr('fill', '#fff'), map.circle(zx, zy, 15).attr('fill', '#FFFFFF'));\n dreamliner = map.circle(x, y, 10).attr({\n stroke: \"none\",\n fill: colour\n });\n var path = [[\"M\", x, y], [\"C\", ax, ay, bx, by, zx, zy]];\n dreamFlightPath = map.path(path).attr({\n stroke: colour,\n \"stroke-width\": 4,\n \"stroke-linecap\": \"round\",\n \"stroke-opacity\": 0.2\n });\n }",
"function route2Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations2.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations2.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations2.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations2.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}",
"function route1Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}",
"function drawFlights(summary, airportCode) {\n // referenced www.tnoda.com\n\n if (airportCode) {\n summary = summary.filter(item => {\n return (item.arrival === airportCode || item.departure === airportCode)\n });\n }\n\n const flights = groups.flights;\n // flights.attr(\"opacity\", 1);\n\n const path = d3.geoPath(projection);\n const planeScale = d3.scaleSqrt()\n .domain(d3.extent(summary, d => d.flights))\n .range([0.3, 2]);\n\n\n function fly(departure, arrival, flightCount) {\n\n var route = flights.append(\"path\")\n .datum({ type: \"LineString\", coordinates: [departure, arrival] })\n .attr(\"class\", \"route\")\n .attr(\"d\", path);\n\n var plane = flights.append(\"path\")\n .attr(\"class\", \"plane\")\n .attr(\"d\", \"m25.21488,3.93375c-0.44355,0 -0.84275,0.18332 -1.17933,0.51592c-0.33397,0.33267 -0.61055,0.80884 -0.84275,1.40377c-0.45922,1.18911 -0.74362,2.85964 -0.89755,4.86085c-0.15655,1.99729 -0.18263,4.32223 -0.11741,6.81118c-5.51835,2.26427 -16.7116,6.93857 -17.60916,7.98223c-1.19759,1.38937 -0.81143,2.98095 -0.32874,4.03902l18.39971,-3.74549c0.38616,4.88048 0.94192,9.7138 1.42461,13.50099c-1.80032,0.52703 -5.1609,1.56679 -5.85232,2.21255c-0.95496,0.88711 -0.95496,3.75718 -0.95496,3.75718l7.53,-0.61316c0.17743,1.23545 0.28701,1.95767 0.28701,1.95767l0.01304,0.06557l0.06002,0l0.13829,0l0.0574,0l0.01043,-0.06557c0,0 0.11218,-0.72222 0.28961,-1.95767l7.53164,0.61316c0,0 0,-2.87006 -0.95496,-3.75718c-0.69044,-0.64577 -4.05363,-1.68813 -5.85133,-2.21516c0.48009,-3.77545 1.03061,-8.58921 1.42198,-13.45404l18.18207,3.70115c0.48009,-1.05806 0.86881,-2.64965 -0.32617,-4.03902c-0.88969,-1.03062 -11.81147,-5.60054 -17.39409,-7.89352c0.06524,-2.52287 0.04175,-4.88024 -0.1148,-6.89989l0,-0.00476c-0.15655,-1.99844 -0.44094,-3.6683 -0.90277,-4.8561c-0.22699,-0.59493 -0.50356,-1.07111 -0.83754,-1.40377c-0.33658,-0.3326 -0.73578,-0.51592 -1.18194,-0.51592l0,0l-0.00001,0l0,0z\");\n\n transition(plane, route, flightCount);\n }\n\n function transition(plane, route, flightCount) {\n const l = route.node().getTotalLength();\n // console.log(route.node())\n plane.transition()\n .duration(l * 50)\n .attrTween(\"transform\", delta(route.node(), flightCount))\n .on(\"end\", () => { route.remove(); })\n .remove();\n }\n\n function delta(arc, flightCount) {\n var l = arc.getTotalLength();\n\n return function(i) {\n return function(t) {\n\n var p = arc.getPointAtLength(t * l);\n\n var t2 = Math.min(t + 0.05, 1);\n var p2 = arc.getPointAtLength(t2 * l);\n\n var x = p2.x - p.x;\n var y = p2.y - p.y;\n var r = 90 - Math.atan2(-y, x) * 180 / Math.PI;\n var s = Math.min(Math.sin(Math.PI * t) * 0.7, 0.3) * 1.3;\n\n // let s;\n // if (t <= 0.5) {\n // s = (l /300) * ((planeScale(flightCount) / 0.5) * t) + 0.2;\n // } else {\n // s = (l /300) * ((planeScale(flightCount) / 0.5) * (1 - t)) + 0.2;\n // };\n\n return `translate(${p.x}, ${p.y}) scale(${s}) rotate(${r})`;\n }\n }\n }\n\n let i = 0;\n window.refreshIntervalId = setInterval(function() {\n if (i > summary.length - 1) {\n i = 0;\n }\n var pair = summary[i];\n\n // fly(summary);\n fly(pair.departure_coords, pair.arrival_coords, pair.flights);\n\n i++;\n }, 150);\n\n}",
"function tweetFlightPath(x, y, zx, zy, colour) {\n var ax = 200 + x;\n var ay = 700 + (y - 150);\n var bx = 255 + (zx - 100);\n var by = 500 + (zy - 400);\n controls = \tmap.set(\n \t\tmap.circle(x, y, 15).attr('fill', '#fff'), map.circle(zx, zy, 15).attr('fill', '#FFFFFF'));\n tweetliner = map.circle(x, y, 10).attr({\n stroke: \"none\",\n fill: colour\n });\n var path = [[\"M\", x, y], [\"C\", ax, ay, bx, by, zx, zy]];\n tweetFlightPath = map.path(path).attr({\n stroke: colour,\n \"stroke-width\": 4,\n \"stroke-linecap\": \"round\",\n \"stroke-opacity\": 0.2\n });\n }",
"function addPremadeRoutes() {\n layerToAdd.forEach((tablica, index) => {\n var url = 'https://api.mapbox.com/directions/v5/mapbox/driving/' + tablica + '?geometries=geojson&steps=true&&access_token=' + mapboxgl.accessToken;\n var req = new XMLHttpRequest();\n req.responseType = 'json';\n req.open('GET', url, true);\n req.onload = function () {\n var jsonResponse = req.response;\n var coords = jsonResponse.routes[0].geometry;\n console.log(coords);\n // add the route to the map\n addRoute(coords);\n };\n req.send();\n function addRoute(coords) {\n // check if the route is already loaded\n let color = \"\";\n if (index === 0) color = '#e68580';\n if (index === 1) color = '#329999';\n if (index === 2) color = '#db9000';\n addRouteToTheMap(\"route\" + index, coords, color, 0.8);\n map.setLayoutProperty(\"route\" + index, 'visibility', 'none');\n };\n })\n }",
"function addPointsToPath(point){\r\n path.push(point);\r\n $('#coordinates-container').html('');\r\n \r\n for(var i = 0; i < path.length; i++){\r\n $('#coordinates-container').html($('#coordinates-container').html() + 'x: ' + path[i].x + ' y: ' + path[i].y + '<br/>');\r\n }\r\n}",
"addSegment(segment) {\n this.segments.push(segment)\n segment.points.forEach(function (point) {\n point.paths.push(this)\n }, this)\n }",
"function resolveMaze(){\n tryMaze(positionFixe);\n traceRoad(chemin_parcouru,\"color2\");\n traceRoad(tabVisite);\n\n}",
"function addPlane(data) {\n //create latitude and longitude\n var lls = new google.maps.LatLng(parseFloat(data[\"latitude\"]), parseFloat(data[\"longitude\"]));\n\n //var image = \"http://wz5.resources.weatherzone.com.au/images/widgets/nav_trend_steady.gif\";\n\n var image = imgs[(Math.round(data[\"heading\"] / 10) % 36).toString()]; //\"http://abid.a2hosted.com/plane\" + Math.round(data[\"heading\"] / 10) % 36 + \".gif\";\n //create the marker, attach to map\n var m = new google.maps.Marker({\n position: lls,\n map: map,\n icon: image\n });\n\n m.addListener('click', function() {\n //if clicked then show info\n hideHoverWindow();\n selected_plane = data[\"id\"];\n showSelectedInfo();\n });\n\n\n m.addListener('mouseover', function() {\n //only if no airport is clicked upon, then show the hover for this\n showHoverWindow(prettifyPlaneData(data));\n\n //Get origin and destination locations\n for (var j = 0; j < latest_json[0].length; j++) {\n if (latest_json[0][j][\"id\"] === data[\"depairport_id\"]) {\n d_coord = {lat: latest_json[0][j][\"latitude\"], lng: latest_json[0][j][\"longitude\"]};\n }\n if (latest_json[0][j][\"id\"] === data[\"arrairport_id\"]) {\n a_coord = {lat: latest_json[0][j][\"latitude\"], lng: latest_json[0][j][\"longitude\"]};\n }\n }\n //Current plane position\n var plane_coord = {\n lat: parseFloat(data[\"latitude\"]),\n lng: parseFloat(data[\"longitude\"])\n };\n var flightPlanCoordinates = [d_coord];\n\n for (var j = 0; j < data[\"detailedroute\"].length; j++) {\n var tmppush = {\n lat: parseFloat(data[\"detailedroute\"][j][1]),\n lng: parseFloat(data[\"detailedroute\"][j][2])\n };\n\n var added_plane = false;\n //See if plane is in a box from prev location to curr location\n //if so, a line to it should be drawn\n var prev_point_lat = flightPlanCoordinates[flightPlanCoordinates.length - 1]['lat'];\n var prev_point_lng = flightPlanCoordinates[flightPlanCoordinates.length - 1]['lng'];\n var curr_point_lat = tmppush['lat'];\n var curr_point_lng = tmppush['lng'];\n\n //Define Bounding Box, we will check if plane is within this box!\n var latLogBox = {\n ix : (Math.min(prev_point_lng, curr_point_lng)) - 0,\n iy : (Math.max(prev_point_lat, curr_point_lat)) + 0,\n ax : (Math.max(prev_point_lng, curr_point_lng)) + 0,\n ay : (Math.min(prev_point_lat, curr_point_lat)) - 0\n };\n\n if ((plane_coord.lat <= latLogBox.iy && plane_coord.lat >= latLogBox.ay) && (latLogBox.ix <= plane_coord.lng && plane_coord.lng <= latLogBox.ax) && added_plane === false) {\n //Plane is within bounds, let try pushing it\n added_plane = true;\n flightPlanCoordinates.push(plane_coord);\n }\n flightPlanCoordinates.push(tmppush);\n }\n\n //add arrival airport coordinates\n flightPlanCoordinates.push(a_coord);\n\n\n flightPath = new google.maps.Polyline({\n path: flightPlanCoordinates,\n geodesic: false,\n strokeColor: '#0000FF',\n strokeOpacity: 1.0,\n strokeWeight: 2,\n map: map\n });\n });\n\n m.addListener('mouseout', function() {\n //if nothing has been clicked on, then hide the info window (ALSO SEE CONFIGURE FUNCTION FOR CLICK EVENT LISTERNERS!)\n flightPath.setMap(null);\n $(\".hoverwindow\").css(\"display\", \"none\");\n });\n //add current marker to airports array\n planes.push(m);\n\n //Update online table\n $(\"#tablefilterpilot tbody\").append(\"<tr><td class='hidden'>\" + data['id'] + \"</td><td class='hidden'>\" + data['airline_name'] + \"</td><td><a href=\\\"#\\\" onclick=\\\"centerMap(\"+data['id']+\", 2)\\\">\"+data['callsign']+\"</a></td><td>\"+data['real_name']+\"</td><td>\"+data['depairport']+\"</td><td>\"+data['arrairport']+\"</td></tr>\");\n}",
"function switchFloor(floor, el) {\n changeSVGFloor(floor.substring(5));\n $('#' + floor, el).show(0, function() {\n $(el).trigger('wayfinding:floorChanged', { map_id: floor });\n });\n\n //turn floor into mapNum, look for that in drawing\n // if there get drawing[level].routeLength and use that.\n\n var i, level, mapNum, pathLength;\n\n if (drawing) {\n mapNum = -1;\n\n for (i = 0; i < maps.length; i++) {\n if (maps[i] === floor) {\n mapNum = i;\n break;\n }\n }\n\n level = -1;\n\n for (i = 0; i < drawing.length; i++) {\n if (drawing[i].floor === mapNum) {\n level = i;\n break;\n }\n }\n\n if (level !== -1) {\n pathLength = drawing[level].routeLength;\n\n // these next three are potentially redundant now\n $(drawing[level].path, el).attr('stroke-dasharray', [pathLength, pathLength]);\n $(drawing[level].path, el).attr('stroke-dashoffset', pathLength);\n $(drawing[level].path, el).attr('pathLength', pathLength);\n $(drawing[level].path, el).attr('stroke-dashoffset', pathLength);\n\n $(drawing[level].path, el).animate({svgStrokeDashOffset: 0}, pathLength * options.path.speed); //or move minPath to global variable?\n }\n }\n } //function switchFloor",
"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}",
"function onMouseDrag(event) {\n path.add(event.point);\n\n }",
"makePath(places) {\n let path = places.map(\n x => ({lat: Number(x.latitude), lng: Number(x.longitude)})\n );\n if (places.length > 0) {\n path.push({lat: Number(places[0].latitude), lng: Number(places[0].longitude)});\n }\n return path;\n }",
"function addRouteMarkers() {\n\n // Add start location\n map.addMarker({\n lat: startLocation[0],\n lng: startLocation[1],\n title: \"Start Location: \" + startLocation[2],\n icon: \"images/start.png\"\n });\n\n // Add end location\n if (endLocation != startLocation) {\n map.addMarker({\n lat: endLocation[0],\n lng: endLocation[1],\n title: \"End Location: \" + endLocation[2],\n icon: \"images/end.png\"\n });\n }\n\n // Add all path markers\n for (var i = 0; i < path.length; i++) {\n map.addMarker({\n lat: path[i][0],\n lng: path[i][1],\n title: path[i][2],\n icon: markers[i],\n infoWindow: {\n content: \"<p>\" + path[i][2] + \"</p><p><input onclick='search([\" + path[i][0] + \",\" + path[i][1] + \"], \\\"\\\")'\" + \" type='button' value='Search Nearby'></p>\" + \n \"<span id='marker' class='delete' onclick='cancelStopMarker(\\\"\" + path[i][2] + \"\\\")'><img src='images/cancel.png' alt='cancel' /></span>\"\n }\n });\n }\n\n fitMap();\n}",
"function setGraticule(map, path){\n //create graticule generator\n var graticule = d3.geoGraticule()\n .step([8, 8]); //place graticule lines every 5 degrees of longitude and latitude\n //create graticule background\n var gratBackground = map.append(\"path\")\n .datum(graticule.outline())//bind graticule background\n .attr(\"class\", \"gratBackground\") //assign class for style\n .attr(\"d\", path); //project graticule\n\n //create graticule lines\n var gratLines = map.selectAll(\".gratLines\") //select graticule elements that will be created\n .data(graticule.lines()) //bind graticule lines to each element that will be created\n .enter()\n .append(\"path\") //append each element to the svg as a path element\n .attr(\"class\", \"gratLines\") //assign class for styling\n .attr(\"d\", path);\n }",
"dijkstraHandler(indoorDestination, indoorDestinationFloor) {\n const updatedDirectionPath = {};\n const [waypoints, graphs, floors] = this.indoorDirectionHandler(\n indoorDestination, indoorDestinationFloor\n );\n\n if (waypoints.length > 0) {\n const paths = dijkstraPathfinder.dijkstraPathfinder(waypoints, graphs);\n\n for (let i = 0; i < paths.length; i++) {\n updatedDirectionPath[floors[i]] = paths[i];\n }\n }\n this.setState({\n indoorDirectionsPolyLine: updatedDirectionPath,\n showDirectionsModal: false,\n showPolyline: true\n });\n }",
"constructPath(cameFrom, goal) {\n let path = this.board.getNeighborTiles(goal[0], goal[1]);\n let pos = goal;\n while (pos !== null) {\n path.unshift(pos);\n pos = cameFrom[pos]; // set the pos to prev pos\n }\n\n return path;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invokes `interceptor` with the `obj` and then returns `obj`. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. | function tap(obj, interceptor) {
interceptor(obj);
return obj;
} | [
"function chain$($el, obj){\n forOwn(obj, function(method, args){\n if (isPlainObject(args)) {\n chain$($el, args);\n }\n else {\n $el[method].apply($el, [].concat(args));\n }\n });\n }",
"function LazyChain(obj) {\n var isLC = (obj instanceof LazyChain);\n\n this._calls = isLC ? fns.cat(obj._calls, []) : [];\n this._target = isLC ? obj._target : obj;\n}",
"function methodInterceptor(proceed, invocation) {\n var result = proceed();\n var time = invocation.executionEndDate - invocation.executionStartDate;\n winstonLogger.info(\"object=\" + invocation.objectName\n + \"; method=\" + invocation.methodName\n + \"; time=\" + time);\n}",
"function AspectOnSuccess(target, aspect)\r\n{\r\n\r\n\treturn Aspect(target, aspect, function() {\r\n\t\t\tvar val = target.apply(arguments.caller, arguments);\r\n\t\t\taspect(arguments, val);\r\n\t\t\treturn val;\r\n\t\t});\r\n\r\n\t\r\n}",
"enterConstructorInvocation(ctx) {\n\t}",
"upsert(obj) {\n return __awaiter(this, void 0, void 0, function* () {\n let inv = yield this.invoke();\n try {\n return inv.upsert(obj);\n }\n finally {\n inv.close();\n }\n });\n }",
"function mapObject(object, fn) {\n return Object.keys(object).reduce(function(result, key) {\n result[key] = fn(object[key]);\n return result;\n }, object);\n}",
"function tryCatch(fn,obj,arg){try{return{type:\"normal\",arg:fn.call(obj,arg)};}catch(err){return{type:\"throw\",arg:err};}}",
"function optimisticGet(get, injectInto, withPropertyName) {\n get.then(function (response) {\n injectInto[withPropertyName] = response.data;\n return response;\n });\n }",
"function createPerformer(obj) {\n if (!obj._hash) {\n console.log('No hash on obj, returning null');\n return;\n }\n \n if (_performersHash[obj._hash]) {\n console.log(obj, 'has already been seen');\n return;\n }\n\n Utils.middleware(obj);\n\n _performersHash[obj._hash] = obj;\n obj.shared ? _performers.unshift(obj) : _performers.push(obj);\n}",
"get(target, property, receiver) {\n return trap.get(target, property, receiver);\n }",
"function spyOnGetterValue(object, f) {\n const value = object[f];\n delete object[f];\n object[f] = value;\n return spyOn(object, f);\n}",
"function Spy(obj,fn,cb){\n\tvar original = obj[fn];\n\tobj[fn] = function(){\n\t\tcb();\n\t\tobj[fn] = original;\n\t\treturn original.apply(this,arguments);\n\t}\n}",
"function resolve(obj, accessors, thisvar) {\n\teachOwn(obj, function (key, value) {\n\t\t// If the value is an accessor, generate the accessor function.\n\t\t// This applies filters and listeners too.\n\t\tif (proxyFlag(value, 'accessor')) {\n\t\t\tobj[key] = accessors[key] = generate(value, thisvar, key);\n\t\t\n\t\t// If the value isn't an accessor but is a TubuxProxy,\n\t\t// set the property to the proxy's value.\n\t\t} else if (proxyFlag(value)) {\n\t\t\tobj[key] = value._value;\n\t\t}\n\t});\n\treturn accessors;\n}",
"function AspectBefore(target, aspect)\r\n{\r\n\treturn Aspect(target, aspect, function() {\r\n\t\t\taspect(arguments);\r\n\t\t\tvar val = target.apply(target, arguments);\r\n\t\t\treturn val;\r\n\t\t});\r\n}",
"static applyTo({\n target,\n obj,\n hideEffects = true,\n instantEffects = [],\n isOnlyMutual = false,\n ...options\n }) {\n let { effectsByPriority } = options;\n if (!effectsByPriority) {\n effectsByPriority = this.getEffectsResultFor({\n ...options,\n obj: target,\n instantEffects,\n isOnlyMutual,\n });\n }\n\n Object.defineProperty(obj, 'effects', {\n value: effectsByPriority,\n configurable: true,\n enumerable: !hideEffects,\n });\n\n const modifier = this.isReduce ? -1 : 1;\n\n _(effectsByPriority).pairs().forEach(([priority, effects]) => {\n _(effects).pairs().forEach(([affect, affectEffects]) => {\n const effectValue = affectEffects.reduce(\n (sum, effect) => sum + effect.value,\n 0,\n );\n\n if (affect === 'damage') {\n if (!(obj.weapon && obj.weapon.damage)) {\n return;\n }\n } else if (affect === 'life') {\n if (!(obj.health && obj.health.armor)) {\n return;\n }\n } else if (obj[affect] === undefined) {\n return;\n }\n\n if (affect === 'damage') {\n const { damage } = obj.weapon;\n if (priority % 2 === 1) {\n damage.min += effectValue * modifier;\n damage.max += effectValue * modifier;\n } else {\n damage.min += Math.floor(damage.min * (0.01 * effectValue)) * modifier;\n damage.max += Math.floor(damage.max * (0.01 * effectValue)) * modifier;\n }\n } else if (affect === 'life') {\n const { health } = obj;\n if (priority % 2 === 1) {\n health.armor += effectValue * modifier;\n } else {\n health.armor += (Math.floor(health.armor * (0.01 * effectValue)) * modifier);\n }\n } else if (priority % 2 === 1) {\n // eslint-disable-next-line no-param-reassign\n obj[affect] += effectValue * modifier;\n } else if (affect === 'time') {\n const resultedValue = (Math.abs(effectValue) + 100) * 0.01;\n\n if ((this.isReduce && effectValue >= 0) || (!this.isReduce && effectValue < 0)) {\n // eslint-disable-next-line no-param-reassign\n obj[affect] = Math.ceil(obj[affect] / resultedValue);\n } else {\n // eslint-disable-next-line no-param-reassign\n obj[affect] = Math.ceil(obj[affect] * resultedValue);\n }\n } else {\n // eslint-disable-next-line no-param-reassign\n obj[affect] += Math.floor(obj[affect] * (0.01 * effectValue)) * modifier;\n }\n });\n });\n\n return obj;\n }",
"function wrap(observable) { return new Wrapper(observable); }",
"enterMethodInvocation_lf_primary(ctx) {\n\t}",
"enterMethodModifier(ctx) {\n\t}",
"function resolveClaimAbout(sbj, predicate, obj, ...ctx) {\n\n setOrAppendValue(sbj, predicate, obj);\n\n if (ctx && ctx.length > 0) {\n let namespace = `@ns:${ctx[0]}`;\n let namespaced = sbj[namespace];\n if (!namespaced || !(namespaced instanceof Object)) {\n namespaced = !!namespaced ? { value: namespaced } : {};\n sbj[namespace] = namespaced;\n }\n\n resolveClaimAbout(namespaced, predicate, obj, ...ctx.slice(1));\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
callback function of clicked event on checkboxlabel checks or unchecks the checkbox which belongs to this checkboxlabel but only if no recording is happening | function clickedOnCheckboxLabel(data) {
if (!viewModel.recordingTimeoutHandle()) // only allow toggling of checkbox if currently not recording
{
data.isChecked(!data.isChecked());
}
} | [
"function handleCheck(e) {\n\t\tsetIsComplete(e.target.checked)\n\t}",
"function handleCheckboxLabelClick(checkboxId, event) {\n var checkbox = jQuery(\"#\" + checkboxId);\n if (!checkbox.prop(\"disabled\")) {\n if (jQuery(event.target).is(\"input, select, textarea, option\")) {\n if (!checkbox.prop(\"checked\")) {\n checkbox.prop(\"checked\", true);\n checkbox.change();\n }\n }\n else if (jQuery(event.target).is(\"a, button\")) {\n //do nothing\n }\n else {\n if (checkbox.prop(\"checked\")) {\n checkbox.prop(\"checked\", false);\n checkbox.change();\n }\n else {\n checkbox.prop(\"checked\", true);\n checkbox.change();\n }\n }\n }\n}",
"function actuallyCheckCheckbox(p_e)\n{\n\tvar target = (p_e.target) ? p_e.target : p_e.srcElement;\n\t\n\tif (typeof target.defaultChecked != 'undefined')\n\t{\n\t\ttarget.defaultChecked = target.checked;\n\t}\n}",
"unCheck(){\n //let { $input, $label } = PRIVATE.get(this);\n\n PRIVATE.get(this).$input.checked = false;\n markChoiceField.call(this);\n //domRemoveClass($label, CSS_MS_IS_CHECKED);\n }",
"handleCheckboxChange(friendId, event){\n this.setState({ checkboxChecked: event.target.checked});\n if(event.target.checked)\n this.props.addFriendToInviteList(friendId);\n else\n this.props.removeFriendFromInviteList(friendId);\n }",
"function onlyOneCheckboxListener(dataTable) {\n $('tbody input.check_item', dataTable).live(\"change\", function(){\n var checked = $(this).is(':checked');\n $('td', dataTable).removeClass('markrowchecked');\n $('input.check_item:checked', dataTable).removeAttr('checked');\n $(\"td\", $(this).closest('tr')).addClass('markrowchecked')\n $(this).attr('checked', checked);\n });\n}",
"slaveCheckboxChanged() {\n const allCheckboxesLength = document.querySelectorAll(\n \"input[name='employee']\"\n ).length;\n const checkedCheckboxesLength = document.querySelectorAll(\n \"input[name='employee']:checked\"\n ).length;\n\n let masterCheckbox = document.querySelector(\"input[name='all']\");\n masterCheckbox.checked = allCheckboxesLength === checkedCheckboxesLength;\n\n // make button visible if any checkbox is checked\n this.setState({\n masterCheckboxVisibility: Boolean(checkedCheckboxesLength),\n });\n }",
"function NLCheckboxOnChange(fld)\n{\n if (!fld)\n\t\treturn;\n\t// make sure the input and the custom checkbox image on the parent span is in sync\n\tvar span = getNLCheckboxSpan(fld);\n if (span)\n {\n if (fld.checked)\n span.className = span.className.replace('_unck', '_ck');\n else\n span.className = span.className.replace('_ck', '_unck');\n }\n}",
"function NLCheckboxOnClick(span)\n{\n var origSpanClass = span.className;\n\tvar inpt = null;\n\n\t// Find the input.\n for (var i=0; i<span.childNodes.length; i++)\n {\n \tif (span.childNodes[i].type == 'checkbox')\n {\n \tinpt = span.childNodes[i];\n break;\n }\n\t}\n\n if (!inpt || inpt.disabled)\n\t\treturn;\n\n\tif (inpt.type == 'checkbox' && inpt.checked) {\n //it was checked, now switch it to unchecked.\n\t span.className = span.className.replace('_ck', '_unck');\n\t\tinpt.checked = false;\n\t}\n\telse {\n //it was unchecked, now switch it to checked.\n\t span.className = span.className.replace('_unck', '_ck');\n\t\tinpt.checked = true;\n\t}\n\n inpt.focus();\n\n // call the input checkbox and check to make sure that onclick succeeded and didn't change back the checked status\n\tvar origChecked = inpt.checked;\n\tif (inpt.onclick)\n inpt.onclick();\n\tvar newChecked = inpt.checked;\n\n //if the onlick event changed back the checked status, revert back the span className also.\n if (origChecked != newChecked)\n \tspan.className = origSpanClass;\n else if (inpt.onchange)\n \tinpt.onchange();\n}",
"onCheckChanged(name){\n\t\tthis.state.onChecked(name);\n\t}",
"function handlecheckBox() {\n // This will give us the selected Box (parent node, to delete the whole canvasBox) (\"count-xx\")\n var selectedBox = this.parentNode.id;\n\n // Now see if you need to add/or remove selectedBox to imageSelected array\n if (this.checked === true) {\n // If it's checked, then add to imageSelected\n imageSelected.push(selectedBox);\n } else {\n // If not selected, then remove ID from imageSelected\n var boxIndex = imageSelected.indexOf(selectedBox);\n imageSelected.splice(boxIndex, 1);\n }\n}",
"_handleCheckboxContainerClick(e) {\n const checkbox = dom(e.target).querySelector('input');\n if (!checkbox) { return; }\n checkbox.click();\n }",
"cleanCheckboxSelection() {\n this.context.state.ingredients.forEach((igd) => {\n if(document.getElementById('igdID_' + igd.id) != null) {\n const checkbox = document.getElementById('igdID_' + igd.id);\n if(checkbox.checked) {\n checkbox.checked = false;\n }\n }\n });\n this.context.disableAllPreviewImg();\n }",
"function toggleCheckboxes(event) {\r\n\r\n var table = event.delegateTarget;\r\n $(table).find('.cb_export').prop('checked', !$(table).find('.cb_export').prop('checked'));\r\n }",
"function alert_state() {\n var cb = document.getElementById('add_marker_CBX');\n \n console.log(cb.checked);\n}",
"function MortgageDischargeReceivedChange(chkBox) {\n\n try {\n\n var chkMortgageDischargeReceived = ((chkBox === undefined) || (chkBox == null)) ? document.getElementById('chkMortgageDischargeReceived') : chkBox;\n\n var selected = (chkMortgageDischargeReceived != null) ? chkMortgageDischargeReceived.checked : null;\n\n if (selected != null) {\n\n var callerId = getRespondeeControlId('cbMortgageDischargeReceived');\n\n var caller = eval(callerId);\n\n if ((caller !== undefined) && (caller != null)) {\n\n if (typeof (caller.Callback) == 'function') {\n\n caller.Callback(selected);\n\n } else if ((caller.control !== undefined) && (caller.control != null) && (typeof (caller.control.Callback) == 'function')) {\n\n caller.control.Callback(selected);\n }\n }\n\n }\n\n if (chkMortgageDischargeReceived != null) {\n\n chkMortgageDischargeReceived.style.display = 'inline-block';\n }\n\n } catch (err) {\n\n alert(RespondeeScriptFileName + '. Control: chkMortgageDischargeReceived. Error: ' + err.description);\n }\n\n}",
"function checkCheckBox(cb){\r\n\treturn cb.checked;\r\n}",
"function clearCheckbox(_betlineObj) {\n try {\n for (var i = 1; i < _betlineObj.length; i++) {\n var checkboxID = (_betlineObj[i].CHECKBOXID)\n if (!$.isNullOrEmpty(checkboxID)) {\n $(\"#\" + checkboxID).click();\n }\n }\n }\n catch (e) {\n $(\".codds input:checked\").each(function() {\n $(this).click();\n $(this).blur();\n });\n }\n}",
"function checkbox($this, o){\n \n var $label, $checkbox, isSelected;\n //option firstCheckAll \n //[1=checks all checkboxes] \n //[2=checks only firs checkbox but works like all are checked - default option]\n //[false=normal behavior]\n \n //if option firstCheckAll==1\n if(o.firstCheckAll==1){\n \t\n $checkbox=$this.next(\".\"+o.prefix+\"checklist\").find(\"li:not(:first-child) input[type=checkbox]\");\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child input[type=checkbox]\").change(function() {\n \n if($(this).is(\":checked\")){\n \t\n $this.find('option').each(function(){\n $(this).attr(\"selected\", \"selected\");\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:not(:first-child) input[type=checkbox]\").each(function(){\n $(this).prop(\"checked\", true); \n window.console.log($(this)); \n });\n $label=$this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child\").text();\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html($label);\n isSelected=true;\n } else {\n $this.find('option').each(function(){\n $(this).removeAttr(\"selected\");\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\"input[type=checkbox]\").each(function(){\n $(this).prop(\"checked\", false);\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html(\"\");\n isSelected=false;\n }\n \n\t\t\t//provides a callback for first element click and transports the select selector and a boolean for selected checkbox\n o.first($this, isSelected);\n });\n //else if option firstCheckAll=2\n } else if(o.firstCheckAll==2){\n \n $checkbox=$this.next(\".\"+o.prefix+\"checklist\").find(\"li:not(:first-child) input[type=checkbox]\");\n \n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child input[type=checkbox]\").change(function() {\n isSelected=false;\n if(!$(this).is(\":checked\") && $checkbox.find(\":checked\").length === 0) {\n \n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html(\"\");\n isSelected=false;\n } else {\n $this.find('option:not(:first-child)').each(function(){\n $(this).removeAttr(\"selected\");\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:not(:first-child) input[type=checkbox]\").each(function(){\n $(this).prop(\"checked\", false);\n });\n $label=$this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child\").text();\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html($label);\n isSelected=true;\n }\n //provides a callback for first element click and transports the select selector and a boolean for selected checkbox\n o.first($this, isSelected);\n }); \n // else i define the normal behavior \n } else {\n $checkbox=$this.next(\".\"+o.prefix+\"checklist\").find(\"input[type=checkbox]\");\n }\n \n // for each checkbox created \n $checkbox.each(function(){\n \t// i listen when the checkbox change value\n $(this).change(function(){\n var $selector=$(this);\n var $value=$selector.val();\n \n \n // if the user checked the checkbox \n if($selector.is(\":checked\")){\n $this.find('option[value=\"' + $value + '\"]').attr(\"selected\", \"selected\");\n // if is the first checkbox and the firstCheckAll option is set\n if(o.firstCheckAll==2 || o.firstCheckAll==1) {\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child input[type=checkbox]\").prop(\"checked\", false);\n }\n // else if unchecked the checkbox\n } else {\n $this.find('option[value=\"' + $value + '\"]').removeAttr(\"selected\");\n // if is the first checkbox and the firstCheckAll option is set\n if(o.firstCheckAll==2 || o.firstCheckAll==1) {\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child input[type=checkbox]\").prop(\"checked\", false);\n }\n }\n \n //if i used some optgroups [does'nt work with the option checkedOnTop set to true]\n if(o.optgroup===true) {\n $label=\"\";\n $this.next().find('input:checked').each(function(){\n if($label!==\"\"){\n $label+=\", \"+$(this).parent().text();\n } else {\n $label+=$(this).parent().text();\n }\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html($label);\n //else if is a plain selectbox\n } else {\n $label=\"\";\n $this.next().find('input:checked').each(function(){\n if($label!==\"\"){\n $label+=\", \"+$(this).parent().text();\n } else {\n $label+=$(this).parent().text();\n }\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html($label);\n }\n //provides a callback for the change event, transports the checkbox selector and the checkbox value\n o.change($selector, $value);\n });\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a DIV element that enclosed a Show/Hide anchor and embeds the endnote display in an PRE inside an inner div. | function majaxMakeEndnoteDisplay(doc, labelText, showText, hideText, preclass)
{
var p = doc.createElement("PRE");
if (preclass != undefined)
p.className = preclass;
var ptext = this.endnote;
p.appendChild(doc.createTextNode(ptext));
var innerdiv = doc.createElement("DIV");
innerdiv.style.display = 'none';
innerdiv.appendChild(p);
var a = doc.createElement("A");
var t = doc.createTextNode(showText);
a.appendChild(t);
a.setAttribute("href", "javascript:;");
var oc = function (event) {
var label;
if (innerdiv.style.display == "block") {
innerdiv.style.display = "none";
label = showText;
} else {
innerdiv.style.display = "block";
label = hideText;
}
a.removeChild(a.firstChild);
var t = doc.createTextNode(label);
a.insertBefore(t, a.firstChild);
return false;
};
// a.onclick seems to not work in FF 1.5.0.4
// and IE does not have addEventListener
if (a.addEventListener)
a.addEventListener("click", oc, false);
else
a.onclick = oc;
var outerdiv = doc.createElement("DIV");
outerdiv.appendChild(a);
var s;
s = doc.createElement("SPAN");
s.innerHTML = " " + labelText;
outerdiv.appendChild(s);
outerdiv.appendChild(innerdiv);
return outerdiv;
} | [
"function displayNotes(note) {\n const { title, body, _id } = note;\n let displayBox = $(\"<div>\");\n displayBox.addClass(\"note-body\");\n let titleDisplay = $(\"<p>\");\n let bodyDisplay = $(\"<p>\");\n let deleteBtn = $(\"<button>\");\n let hr = $(\"<hr>\");\n deleteBtn.addClass(\"note-deleter\");\n deleteBtn.attr(\"id\", _id);\n titleDisplay.text(title || \"No Title\");\n bodyDisplay.text(body);\n deleteBtn.text(\"X\");\n displayBox.append(deleteBtn, titleDisplay, hr, bodyDisplay);\n return displayBox;\n }",
"function showNote(anchor, position, html) {\n\n let note = document.createElement('div');\n note.className = \"note\";\n note.innerHTML = html;\n document.body.append(note);\n\n positionAt(anchor, position, note);\n}",
"function showembed(){\n document.getElementById('hideembed').style.visibility=\"hidden\";\n document.getElementById('hideembed').style.display=\"none\";\n document.getElementById('showembed').style.display=\"block\";\n document.getElementById('showembed').style.visibility=\"visible\";\n document.getElementById('embed').innerHTML=\"<a style=\\\"cursor:pointer;\\\" onClick=\\\"hideembed()\\\"><img src=\\\"addons/mw_eclipse/skin/images/icons/icon_share.png\\\" align=\\\"absmiddle\\\" /> Share / Embed<\\/a>\";\n\n}",
"function getNoteTemplate(noteObj, noteTemplate) {\n noteDiv = noteMaker(noteObj, noteTemplate).firstChild;\n content.insertBefore(noteDiv, content.childNodes[0]);\n noteDiv.classList.add('show');\n noteDiv.classList.remove('hide');\n }",
"function createShowHtml(show) {\n return `<div class=\"col s6 m4 l3\">\n <div class=\"card showCard hoverable clickable blue accent-2\">\n <div class=\"card-image showImage\">\n <img src=\"${show.showImage}\" alt=\"${show.showName} image\">\n </div>\n <div class=\"card-content showCardContent center white-text bold\">\n <p>${show.showName}</p>\n <p class=\"showId hide\">${show.id}</p>\n </div>\n </div>\n </div>`;\n}",
"function show_diy_note()\n{\n\tvar current_step = $(\".chalk_player video\").attr(\"data-diy-step\");\n\t/*pause video*/\n\tcp_mediaPlayer.pause();\n\t/*show note*/\n\t$(\".chalk_player .diy_wrapper .content_wrapper,.chalk_player .diy_wrapper .diy_content[data-diy-step='\"+current_step+\"'],.chalk_player .diy_wrapper .steps_container\").removeClass(\"hidden\");\n\t$(\".chalk_player video\").attr(\"data-diy-step-show\",\"1\");\n}",
"function showBuilder(){\n\tbuilder.style.display = \"inline\";\n\thideButton.innerHTML = \"Hide Builder\";\n}",
"function showNoteScreen(){\n $(\"#note-screen\").show();\n }",
"function audioContentHideShow(nodeId)\r\n{\r\n $(\"#audio_contents\"+nodeId).toggle();\r\n}",
"function setupNoteField(note) {\n // Save the markdown and render the content.\n var html = note.html();\n if (typeof html === 'undefined') html = '';\n note.data('noteContent', html.replace(/<br>/g,'\\n'));\n note.html(render(html));\n activateTooltips(note);\n\n note.click(function(e) {\n if (e.target.tagName.toLowerCase() === 'textarea') {\n return;\n }\n\n // If the target is the div, they are going from display --> edit.\n if (e.target.tagName.toLowerCase() !== 'button') {\n var interval = setInterval(function() {\n // If we can find a textarea, they must have clicked to edit the text field.\n // So, we want to display the markdown content.\n if (note.find('textarea')) {\n clearInterval(interval);\n if (note.data('noteContent') === 'Click to add note') {\n note.find('textarea').val('');\n } else {\n note.find('textarea').val(note.data('noteContent'));\n }\n }\n }, 50);\n } \n\n // Otherwise, they are going from edit --> display.\n else {\n var textarea = note.find('textarea');\n var str = textarea.val().replace(/\\n/g,'\\n');\n textarea.html(str);\n var interval = setInterval(function() {\n // Keep waiting until there is no text area. Then, save the changed markdown\n // value to the data. Also re-render the note.\n if (note.find('textarea').length === 0) {\n clearInterval(interval);\n note.data('noteContent', note.html().replace(/<br>/g,'\\n'));\n note.html(render(note.html()));\n activateTooltips(note);\n }\n }, 50);\n } \n });\n }",
"function shownewalbum(){\n document.getElementById('hidenewalbum').style.visibility=\"hidden\";\n document.getElementById('hidenewalbum').style.display=\"none\";\n document.getElementById('shownewalbum').style.display=\"block\";\n document.getElementById('shownewalbum').style.visibility=\"visible\";\n document.getElementById('photoalbum').innerHTML=\"<a style=\\\"cursor:pointer;\\\" onClick=\\\"hidenewalbum()\\\">Hide Create New Album<\\/a>\";\n\n}",
"function renderNotes(){\n $('#new-note-btn').show();\n $(\"#new-note-hr\").show();\n $(\"#note-index-container\").css('height', '');\n clearNotesDisplay(\"notes\");\n raw_notes.forEach(function(note){\n $(\".note-index\").append('<div class=\"note-tile btn btn-block transition-quick\" data-id=' + note[\"id\"] + '>' + trimTitle(note[\"title\"], titleDisplayLen) + '</div>');\n });\n addTileListener();\n}",
"function renderNote(note, notesDiv) {\n const noteDiv = document.createElement(\"div\");\n noteDiv.classList.add(\"note\");\n noteDiv.setAttribute(\"data-id\", note.id)\n notesDiv.appendChild(noteDiv);\n\n // Retrieve data\n const title = note.title;\n const desc = note.desc;\n const date = note.date;\n const time = note.time;\n const priority = note.priority;\n\n // Create DOM elements for data\n\n // Title\n const noteTitle = document.createElement(\"p\");\n noteTitle.classList.add(\"note-title\");\n noteTitle.innerHTML = title;\n noteDiv.appendChild(noteTitle);\n\n if(new Date().toISOString().split(\"T\")[0] <= date) {\n // Add clock fa icon showing how much time until the note's date!\n const clockIcon = document.createElement(\"div\");\n noteTitle.appendChild(clockIcon);\n clockIcon.classList.add(\"fas\", \"fa-clock\");\n clockIcon.innerHTML = \"\"\n clockIcon.style.color = getColorByPriority(priority);\n clockIcon.style.fontSize = \"22px;\"\n }\n\n \n // Hidden div containing rest of the info about this note\n const noteInfo = document.createElement(\"div\");\n noteInfo.classList.add(\"note-info\")\n noteInfo.style.display = \"none\";\n noteDiv.appendChild(noteInfo);\n\n // Description\n const noteDescDiv = document.createElement(\"div\");\n noteDescDiv.classList.add(\"note-desc-div\");\n const noteDesc = document.createElement(\"p\");\n noteDescDiv.appendChild(noteDesc);\n noteDesc.classList.add(\"note-desc\");\n noteDesc.innerHTML = desc;\n noteInfo.appendChild(noteDescDiv);\n\n // Date\n if(date !== \"\") {\n const notedate = document.createElement(\"p\");\n notedate.classList.add(\"note-date\");\n notedate.innerHTML = date;\n noteInfo.appendChild(notedate);\n }\n\n // Time\n if(time !== \"\") {\n const noteTime = document.createElement(\"p\");\n noteTime.classList.add(\"note-time\");\n noteTime.innerHTML = time;\n noteInfo.appendChild(noteTime);\n }\n\n // Edit button at the bottom\n const editBtn = document.createElement(\"btn\")\n noteInfo.appendChild(editBtn);\n editBtn.classList.add(\"btn\", \"btn-sm\", \"btn-danger\", \"btn-outline-white\")\n editBtn.innerHTML = \"Edit Note\";\n\n // Add event listener to that button\n\n editBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n\n const noteDiv = e.target.parentElement.parentElement;\n // const noteId = noteDiv.getAttribute(\"data-id\");\n\n // Remove note's child elements\n Array.from(noteDiv.children).forEach(child => {\n child.remove()\n })\n\n // And render edit form in place of it\n renderEditNote(noteDiv, title, desc, date, time, priority);\n\n })\n \n\n // Toggle between showing noteInfo when clicking on a note (WITH FADE ANIMATION)\n noteDiv.addEventListener(\"click\", () => {\n if(noteInfo.style.display !== \"block\") {\n\n noteInfo.style.opacity = 0;\n noteInfo.style.display = \"block\";\n setTimeout(() => {\n noteInfo.style.opacity = 1;\n }, 100)\n } else {\n noteInfo.style.opacity = 0;\n setTimeout(() => {\n noteInfo.style.display = \"none\"; \n }, 500)\n }\n })\n\n \n // Set note's background color according to priority!\n const divColor = getColorByPriority(priority);\n noteDiv.style.cssText = `background-color: ${divColor}`;\n\n // Add delete button for note!\n const deleteNote = document.createElement(\"div\");\n deleteNote.classList.add(\"delete-note\", \"fas\", \"fa-times\");\n noteDiv.appendChild(deleteNote);\n\n // Add event listener for the button!\n deleteNote.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n if (confirm(\"Are you sure you want to delete this note? This action cannot be undone!\")) {\n const note = e.target.parentElement;\n const notes = e.target.parentElement.parentElement;\n\n const projectId = notes.getAttribute(\"data-id\");\n const noteId = note.getAttribute(\"data-id\");\n\n\n db.collection('Users')\n .doc(auth.currentUser.uid)\n .collection(\"Projects\")\n .doc(projectId)\n .collection(\"Notes\")\n .doc(noteId)\n .delete()\n .then(() => {\n location.reload();\n });\n \n }\n });\n \n }",
"function showAndDisplay(thing, elem){\n\t$(elem).append(thing).addClass(\"show\", function(){\n\t\t$(this).removeClass(\"hide\");\n\t});\n\n}",
"function Note() {\n\tvar self = this;\n\t\n\t// create main div for the sticky\n\tvar stickyDiv = document.createElement('div');\n\tstickyDiv.className = 'note';\n\t\n\t// see prototype definition\n\tstickyDiv.addEventListener('mousedown', function(e) { \n\t\treturn self.onMouseDown(e)\n\t}, false\t);\n\t\n\t// see prototype definition\n\tstickyDiv.addEventListener('click', function() {\n\t\treturn self.onNoteClick()\n\t}, false\t);\n\t\n\tself.note = stickyDiv;\n\t\n\t// create a div for the close button & append to main div\n\tvar closeBtn = document.createElement('div');\n\tcloseBtn.className = 'closebutton';\n\tcloseBtn.addEventListener('click',\tfunction(event) {\n\t\treturn self.close(event)\n\t}, false\t);\n\tstickyDiv.appendChild(closeBtn);\n\t\n\t// create a div for the edit field & append to main div\n\tvar edit = document.createElement('div');\n\tedit.className = 'edit';\n\tedit.setAttribute('contenteditable', true);\n\tedit.addEventListener('keyup', function() {\n\t\treturn self.onKeyUp()\n\t}, \tfalse);\n\tstickyDiv.appendChild(edit);\n\tself.editField = edit;\n\t\n\t// create a div for the timestamp & append to main div\n\tvar ts = document.createElement('div');\n\tts.className = 'timestamp';\n\tts.addEventListener('mousedown', function(e) {\n\t\treturn self.onMouseDown(e)\n\t}, false);\n\tstickyDiv.appendChild(ts);\n\tself.lastModified = ts;\n\t\n\tdocument.body.appendChild(stickyDiv);\n\treturn self;\n}",
"function showNotes() {\n\t\tnotes.forEach(function(note) {\n\t\t\t// first position the notes randomly on the page\n\t\t\tpositionNote(note);\n\t\t\t// now, animate the notes torwards the button\n\t\t\tanimateNote(note);\n\t\t});\n\t}",
"function toggleHelpInline(obj, a_id) {\n\tvar content = document.getElementById(obj);\n\tvar opener = document.getElementById(a_id);\n\t\n\ticonState = opener.lastChild.alt;\n\ticonState = iconState.replace(\"Collapse\",\"\");\n\ticonState = iconState.replace(\"Expand\",\"\");\n\t\n\t\tif (content.style.display != \"none\" ) {\n\t\t\tcontent.style.display = 'none';\n\t\t\topener.lastChild.alt = 'Expand' + iconState;\n\t\t\topener.focus();\n\t\t} else {\n\t\tcontent.style.display = '';\n\t\t\topener.lastChild.alt = 'Collapse' + iconState;\n\t\t}\n\t\n}",
"function notebookStructure(){\n return '<section><div class=\"container\"><div class=\"timeline\"><div class=\"timeline-hline\"></div>'+notebook_content+'</div></div></section>'\n}",
"function footnoteLinks(containerID,targetID) { if (!document.getElementById || !document.getElementsByTagName || !document.createElement) return false; if (!document.getElementById(containerID) || !document.getElementById(targetID)) return false; var container = document.getElementById(containerID); var target = document.getElementById(targetID); var h2 = document.createElement('h2'); addClass.apply(h2,['printOnly']); var h2_txt = document.createTextNode('Links'); h2.appendChild(h2_txt); var coll = container.getElementsByTagName('*'); var ol = document.createElement('ol'); addClass.apply(ol,['printOnly']); var myArr = []; var thisLink; var num = 1; for (var i=0; i<coll.length; i++) { var thisClass = coll[i].className; if ( (coll[i].getAttribute('href') || coll[i].getAttribute('cite')) && (thisClass == '' || thisClass.indexOf('ignore') == -1)) { thisLink = coll[i].getAttribute('href') ? coll[i].href : coll[i].cite; var note = document.createElement('sup'); addClass.apply(note,['printOnly']); var note_txt; var j = inArray.apply(myArr,[thisLink]); if ( j || j===0 ) { note_txt = document.createTextNode(j+1);} else { var li = document.createElement('li'); var li_txt = document.createTextNode(thisLink); li.appendChild(li_txt); ol.appendChild(li); myArr.push(thisLink); note_txt = document.createTextNode(num); num++;} note.appendChild(note_txt); if (coll[i].tagName.toLowerCase() == 'blockquote') { var lastChild = lastChildContainingText.apply(coll[i]); lastChild.appendChild(note);} else { coll[i].parentNode.insertBefore(note, coll[i].nextSibling);} } } target.appendChild(h2); target.appendChild(ol); addClass.apply(document.getElementsByTagName('html')[0],['noted']); return true;}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function for horse name=================== | function isHorseName(str){
check="`~!@#$%^*()_+=|{}[];:/<>?"+"\\"+"\""+"\"";
f1=1;
for(j=0;j<str.length;j++){
if(check.indexOf(str.charAt(j))!=-1){
f1=0;}}
if(f1==0){return true;}
else{return false;}
} | [
"function hoofdletters(tekst) {\n return tekst.toUpperCase(); // dit is alles\n}",
"function pHName(pH) {\n\treturn pH < 7 && pH >= 0 ? \"acidic\" : pH > 7 && pH <= 14 ? \"alkaline\" : pH === 7 ? \"neutral\" : 'invalid';\n}",
"function Morse(letra)\n{\n var codificacion;\n\n /* SOLUCION BRUTA\n switch(letra)\n {\n \tcase \"A\":\n \t\tcodificacion=\"·-\";\n \t\tbreak;\n \tcase \"B\":\n \t\tcodificacion=\"-···\";\n \t.....\n }*/\n //USANDO ARRAY A B C D E F\n var tabla=[\"·-\",\"-···\",\"-·-·\",\"-··\",\"·\",\"··-·\"];\n var letraA=\"A\";\n var posicion=letra.charCodeAt()-letraA.charCodeAt();\n \n\n codificacion=tabla[posicion];\n \n\n return codificacion;\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}",
"function getNeptunCode() {\n if ($(\"#upTraining_topname\").size() > 0) {\n const input = $(\"#upTraining_topname\").text();\n return input.substring(input.indexOf(\" - \") + 3).toUpperCase();\n }\n}",
"function halfnhalf(helloWorld){\r\n let cap = helloWorld.slice(0, Math.floor(helloWorld.length / 2)).toUpperCase()\r\n let low = helloWorld.slice(Math.floor(helloWorld.length) / 2).toLowerCase()\r\n let caplow = cap.concat(low)\r\n console.log(caplow)\r\n}",
"get horseProfile_Overview_HorseName() {return browser.element(\"//android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup/android.widget.TextView[1]\");}",
"function betHorses(){ \r\n if(bet == 1) bet = 'horse1'; \r\n if(bet == 2) bet = 'horse2';\r\n if(bet == 3) bet = 'horse3';\r\n if(bet == 4) bet = 'horse4';\r\n}",
"function kebabToSnake(str){\r\n\t// while(str.indexOf(\"-\") > 0) {\r\n\t// \tstr = str.replace(\"-\", \"_\");\r\n\t// }\r\n\treturn str.replace(/-/g, \"_\");\r\n\r\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 }",
"_getInitial(name) {\n return name[0].toUpperCase();\n }",
"function getNamePiece(){\n\tvar pieces = ['el', 'li', 'tat', 'io', 'on', 'fa', 'ill', 'eg', 'aer', 'shi', 'lys', 'and',\n\t'whi', 'dus', 'ney', 'bal', 'kri', 'ten', 'dev', 'ep', 'tin', 'ton', 'ri', 'mynn', 'ben', 'la', 'sam',\n\t'hag', 'is', 'ya', 'tur', 'pli', 'ble', 'cro', 'stru', 'pa', 'sing', 'rew', 'lynn', 'lou', 'ie', 'zar',\n\t'an', 'ise', 'tho', 'vag', 'bi', 'en', 'fu', 'dor', 'nor', 'ei', 'zen', 'is', 'val', 'zon',\n\t'lu', 'tur', 'op', 'sto', 'ep', 'tha', 'dre', 'ac', 'ron'];\n\treturn pieces[Math.floor((Math.random() * pieces.length) + 1)-1];\n}",
"function horse1(){\n document.getElementById(\"displayComment\").innerHTML = \"Your horse has been set lose.\";\n horse.play();\n}",
"function convertLetter(letter){\n if(letter==='r')return 'ROCK ';\n if(letter==='p')return 'PAPER';\n return 'SCISSOR';\n}",
"function makeName() {\n let prefixArr = [];\n let suffixArr = [];\n let name;\n\n if (mySpecies.length < 1) return; // Don't make a name if there are no traits\n // Populate the prefix and suffix arrays\n for ( let i = 0; i < mySpecies.length; i ++ ) {\n for ( let j = 0; j < mySpecies[i].prefixes.length; j ++ ) {\n prefixArr.push(mySpecies[i].prefixes[j]);\n }\n for ( let k = 0; k < mySpecies[i].suffixes.length; k ++ ) {\n suffixArr.push(mySpecies[i].suffixes[k]);\n }\n }\n // Get random values from the prefix and suffix arrays\n let pre1 = getRandom(prefixArr);\n let pre2;\n let suf = getRandom(suffixArr);\n if (mySpecies.length <= 2) {\n name = pre1 + suf;\n } else {\n let pre2 = getRandom(prefixArr);\n // Ensure unique prefixes\n while ( pre2 == pre1 ) {\n pre2 = getRandom(prefixArr);\n }\n name = pre1 + pre2 + suf;\n }\n name = name.charAt(0).toUpperCase() + name.slice(1);\n document.getElementById(\"name\").innerHTML = name;\n}",
"function getSchoolname(schoolName) {\n return schoolName.replace(\"-\", \"-<br>\")\n}",
"ucName() {\n return this.name.substr(0,1).toUpperCase() + this.name.substr(1);\n }",
"function findFirstLetter(word){\n\treturn word[0].toUpperCase();\n}",
"function kebabToCamel(s) {\r\n return s.replace(/(\\-\\w)/g, function (m) { return m[1].toUpperCase(); });\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
I check to see if the given param is still the given value. | function isParam( paramName, paramValue ) {
// When comparing, using the coersive equals since we may be comparing
// parsed value against non-parsed values.
if (
params.hasOwnProperty( paramName ) &&
( params[ paramName ] == paramValue )
) {
return( true );
}
// If we made it this far then param is either a different value; or,
// is no longer available in the route.
return( false );
} | [
"function hasParamChanged( paramName, paramValue ) {\r\n\r\n // If the param value exists, then we simply want to use that to compare\r\n // against the current snapshot.\r\n if ( ! ng.isUndefined( paramValue ) ) {\r\n\r\n return( ! isParam( paramName, paramValue ) );\r\n\r\n }\r\n\r\n // If the param was NOT in the previous snapshot, then we'll consider\r\n // it changing.\r\n if (\r\n ! previousParams.hasOwnProperty( paramName ) &&\r\n params.hasOwnProperty( paramName )\r\n ) {\r\n\r\n return( true );\r\n\r\n // If the param was in the previous snapshot, but NOT in the current,\r\n // we'll consider it to be changing.\r\n } else if (\r\n previousParams.hasOwnProperty( paramName ) &&\r\n ! params.hasOwnProperty( paramName )\r\n ) {\r\n\r\n return( true );\r\n\r\n }\r\n\r\n // If we made it this far, the param existence has not change; as such,\r\n // let's compare their actual values.\r\n return( previousParams[ paramName ] !== params[ paramName ] );\r\n\r\n }",
"function isAudioParam(arg) {\n return (0, _standardizedAudioContext.isAnyAudioParam)(arg);\n}",
"function getBooleanParameter( param )\n{\n return getParameter( param ) == \"T\";\n}",
"function haveParamsChanged( paramNames ) {\r\n\r\n for ( var i = 0, length = paramNames.length ; i < length ; i++ ) {\r\n\r\n if ( hasParamChanged( paramNames[ i ] ) ) {\r\n\r\n // If one of the params has changed, return true - no need to\r\n // continue checking the other parameters.\r\n return( true );\r\n\r\n }\r\n\r\n }\r\n\r\n // If we made it this far then none of the params have changed.\r\n return( false );\r\n\r\n }",
"function foo(a,b) {\n \n // Now, deleting 'a' directly should fail\n // because 'a' is direct reference to a function argument;\n var d = delete a;\n return (d === false && a === 1);\n }",
"function delete_parameter(p) {\n return (delete p);\n}",
"function isParameter(node) {\n\t return node.kind() == \"Parameter\" && node.RAMLVersion() == \"RAML08\";\n\t}",
"function check(oval, nval) {\n if (oval !== undefined) {\n if (oval != nval) {\n throw Error(\"Values don't match\");\n }\n }\n return nval;\n}",
"static checkParamsValidity (channel) {\n const { clientId, clientSecret, serviceId } = channel\n channel.phoneNumber = channel.phoneNumber.split(' ').join('')\n\n if (!clientId) { throw new BadRequestError('Parameter is missing: Client Id') }\n if (!clientSecret) { throw new BadRequestError('Parameter is missing: Client Secret') }\n if (!serviceId) { throw new BadRequestError('Parameter is missing: Service Id') }\n if (!channel.phoneNumber) { throw new BadRequestError('Parameter is missing: Phone Number') }\n\n return true\n }",
"parametersChanged() {\n let arr = Object.entries(this.parameters)\n let res = arr.map(item=>{\n return this.prevParameters[item[0]] == item[1]\n }).find(item=>!item)\n\n this.prevParameters = {...this.parameters}\n return !res\n }",
"hasParameter(logicalId, props) {\n const matchError = (0, parameters_1.hasParameter)(this.template, logicalId, props);\n if (matchError) {\n throw new Error(matchError);\n }\n }",
"function myFunction(person, age, name){\n let equalAge = age == person.age; //if the age of the object is equal to the second parameter\n let notEqualName = name != person.name; // if the name of the object is Not equal to the third par\n \n if(equalAge && notEqualName){\n return true;\n }else{\n return false;\n }\n}",
"function isArgUsedInFunc(fcallexpr, arg) {\r\n\r\n // First find the called function object\r\n //\r\n var ind = getFuncIdByName(CurModObj, fcallexpr.str);\r\n var fO = CurModObj.allFuncs[ind];\r\n\r\n var argpos = arg + 1; // in header, 0th arg is ReturnValue \r\n var gid = fO.allSteps[FuncHeaderStepId].allGridIds[argpos];\r\n\r\n // Go thru all steps of the function and see whether this grid is used\r\n //\r\n for (var s = FuncHeaderStepId + 1; s < fO.allSteps.length; s++) {\r\n\r\n var stepO = fO.allSteps[s];\r\n\r\n for (var g = 0; g < stepO.allGridIds.length; g++) {\r\n\r\n if (stepO.allGridIds[g] == gid)\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}",
"function hasObjectChanged(value, state) {\n var json = angular.toJson(value || \"\");\n var oldJson = state.json;\n state.json = json;\n return !oldJson || json !== oldJson;\n }",
"function comprobarVacio(campo){\r\n\t//Obtenemos el valor que contiene el campo\r\n\tvar valor = campo.value;\r\n\t//Comprobamos si el campo esta vacio(true) o no(false)\r\n\tif( valor==\"\" ){\r\n\t\treturn true;\t\t\r\n\t}\r\n\t//No es vacio retornamos false\r\n\telse{\r\n\t\treturn false;\r\n\t}\r\n}",
"function checkParameters(command, parameters) {\r\n\tif (Object.keys(commandConfig.getParameters(command)).length == 0 && parameters.length == 0) {\r\n\t\treturn true;\r\n\t}\r\n\tif (Object.keys(commandConfig.getParameters(command)).length == 0 && parameters.length > 0) {\r\n\t\tconsole.log(`* ` + command + ` expected no parameters but found ` + parameters.length + `. --- Running Anyways`);\r\n\t\treturn true;\r\n\t}\r\n\texpected = Object.keys(commandConfig.getParameters(command));\r\n\tif (parameters.length != expected.length) {\r\n\t\tconsole.log(`* Incorrect number of parameters for command ` + command);\r\n\t\treturn false;\r\n\t}\r\n\tfails = 0;\r\n\tfor (i = 0; i < parameters.length; i++) {\r\n\t\tif (expected[i] == \"int\" && !(Number(parameters[i]) != NaN && Number(parameters[i]) % 1 === 0.0)) {\r\n\t\t\tconsole.log(`* ` + command + ` expected an int at index ` + i);\r\n\t\t\tfails++;\r\n\t\t}\r\n\t\tif (expected[i] == \"float\" && Number(parameters[i] == NaN)) {\r\n\t\t\tconsole.log(`* ` + command + ` expected a float at index ` + i);\r\n\t\t\tfails++;\r\n\t\t}\r\n\t\tif (expected[i] == \"boolean\" && (parameters[i] != 'false' || parameters[i] != 'true')) {\r\n\t\t\tconsole.log(`* ` + command + ` expected a boolean at index ` + i);\r\n\t\t\tfails++;\r\n\t\t}\r\n\t\t// Theoretically, anything that short circuits the first half of the previous checks SHOULD be an expected string\r\n\t}\r\n\treturn fails == 0;\r\n}",
"function notNullish(value) {\n return value !== null && value !== undefined;\n}",
"isValue() {\n return false;\n }",
"function noFlags(){\n return (typeof(p) == typeof(v));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make json telemetry object | function GetTelemetryObj() {
var myJSON = {
"utc": 0,
"soc": 0,
"soh": 0,
"speed": 0,
"car_model": CAR_MODEL,
"lat": 0,
"lon": 0,
"elevation": 0,
"ext_temp": 0,
"is_charging": 0,
"batt_temp": 0,
"voltage": 0,
"current": 0,
"power": 0
};
return myJSON;
} | [
"function createOutputJsonInstance()\n{\n\tvar output = \n\t\t{\n\t\t\t\"status\": null,\n\t\t\t\"message\": null,\n\t\t\t\"data\": null\n\t\n\t\t}\n\n\treturn output;\n\n}",
"async sendToTelemetry() {\n let reporter;\n try {\n reporter = await telemetry_1.default.create({\n project: PROJECT,\n key: APP_INSIGHTS_KEY,\n userId: this.telemetry.getCLIId(),\n waitForConnection: true,\n });\n }\n catch (err) {\n const error = err;\n debuger_1.debug(`Error creating reporter: ${error.message}`);\n // We can't do much without a reporter, so clear the telemetry file and move on.\n await this.telemetry.clear();\n return;\n }\n try {\n const events = await this.telemetry.read();\n for (const event of events) {\n const eventType = ts_types_1.asString(event.type) || telemetry_2.default.EVENT;\n const eventName = ts_types_1.asString(event.eventName) || 'UNKNOWN';\n delete event.type;\n delete event.eventName;\n if (eventType === telemetry_2.default.EVENT) {\n event.telemetryVersion = debuger_1.version;\n // Resolve orgs for all events.\n event.orgId = await this.getOrgId(false, ts_types_1.asString(event.orgUsername));\n event.devHubId = await this.getOrgId(true, ts_types_1.asString(event.devHubUsername));\n // Usernames are GDPR info, so don't log.\n delete event.orgUsername;\n delete event.devHubUsername;\n reporter.sendTelemetryEvent(eventName, event);\n }\n else if (eventType === telemetry_2.default.EXCEPTION) {\n const error = new Error();\n // We know this is an object because it is logged as such\n const errorObject = event.error;\n delete event.error;\n Object.assign(error, errorObject);\n error.name = ts_types_1.asString(errorObject.name) || 'Unknown';\n error.message = ts_types_1.asString(errorObject.message) || 'Unknown';\n error.stack = ts_types_1.asString(errorObject.stack) || 'Unknown';\n reporter.sendTelemetryException(error, event);\n }\n }\n }\n catch (err) {\n const error = err;\n debuger_1.debug(`Error reading or sending telemetry events: ${error.message}`);\n }\n finally {\n try {\n // We are done sending events\n reporter.stop();\n }\n catch (err) {\n const error = err;\n debuger_1.debug(`Error stopping telemetry reporter: ${error.message}`);\n }\n finally {\n // We alway want to clear the file.\n await this.telemetry.clear();\n }\n }\n }",
"function toJson(o) { return JSON.stringify(o); }",
"saveToJSON () {\n\t\tlet digimonJSON = JSON.stringify(this);\n\n\t\treturn digimonJSON;\n\t}",
"toJSON() {\n const name = this._name;\n const index = this._index;\n const cols = this._columns;\n const series = this._data;\n\n let indexedBy;\n if (this._times) {\n indexedBy = \"time\";\n } else if (this._timeRanges) {\n indexedBy = \"timerange\";\n } else if (this._indexes) {\n indexedBy = \"index\";\n }\n\n const points = series.map((value, i) => {\n const data = [];\n if (this._times) {\n const t = this._times.get(i);\n data.push(t.getTime());\n } else if (this._timeRanges) {\n const tr = this._timeRanges.get(i);\n data.push([tr[0], tr[1]]);\n } else if (this._indexes) {\n const index = this._indexes.get(i);\n data.push(index);\n }\n cols.forEach((column) => {\n data.push(value.get(column));\n });\n return data;\n }).toJSON();\n\n // The JSON output has 'time' as the first column\n const columns = [indexedBy];\n cols.forEach((column) => {\n columns.push(column);\n });\n\n let result = {\n name\n };\n\n if (index) {\n result.index = index.toString();\n }\n\n result = _.extend(result, {\n columns,\n points\n });\n\n result = _.extend(result, this._meta.toJSON());\n\n return result;\n }",
"formatData() {\n let formattedData = [[\n { type: 'date', label: 'Time' },\n 'CPU Usage',\n 'Memory Usage',\n ]];\n let unformattedData = this.state.telemetry\n unformattedData.map(data => {\n return formattedData.push([\n new Date(parseInt(data.M.timestamp.S) * 1000),\n parseFloat(data.M.cpuUsage.N),\n parseFloat(data.M.memUsage.N),\n ])\n });\n this.setState({\n telemetry: formattedData\n })\n }",
"static payloader(command, payload) {\n var data = {\n \"command\": String(command),\n \"payload\": String(payload)\n }\n\n data = JSON.stringify(data)\n return data\n }",
"function createJSON(items) {\n return {\n readings: items.map(element => {\n return {point: element, consumption: Math.floor(Math.random() * 5)}\n })\n }\n}",
"function getMessage(){\n const myTimestamp = getTimestamp();\n const msg = {};\n msg['level'] = getRandomLogLevel();\n msg['time'] = new Date().getMilliseconds();\n msg['content'] = `Now is ${myTimestamp}`;\n return JSON.stringify(msg);\n}",
"constructor() {\n\t\tthis._prettyJson = false;\n\t}",
"toJSON() {\n return JSON.stringify(\n this.configuration,\n function(key, val) {\n return (typeof val === 'function') ? val.toString() : val;\n }\n );\n }",
"static serializeToJs(unit) {\n if (!unit.isLoaded) {\n throw new Error(\"serializeToJs can be used on loaded units only!\");\n }\n const serializer = new JavaScriptSerializer(unit);\n serializer.schedule(unit);\n return serializer.source();\n }",
"toMap() {\n let m = {\n ts: this.ts,\n value: this.value\n };\n\n if (this.count !== 1) {\n m['count'] = this.count;\n }\n\n if (this.status) {\n m['status'] = this.status;\n }\n\n return m;\n }",
"function getJson([...lists], [...schedule]) {\n return JSON.stringify({\n lists: lists.map(list => {\n const walks = [];\n\n // Denormalize for serializing\n list.walks.forEach(walk => walks.push(+walk.id));\n\n return Object.assign({}, list, { walks });\n }),\n schedule: schedule.reduce((p, [walk, times]) => {\n p[+walk.id] = [...times];\n return p;\n }, {}),\n });\n}",
"saveAsJSON() {\n const bench = this.state.benchInfo;\n for (const benchResult in this.state.benchResults) {\n if (\n (this.state.benchResults[benchResult].hasOwnProperty(\"time\") &&\n this.state.benchResults[benchResult].time != null &&\n this.state.benchResults[benchResult].time != NaN) ||\n (this.state.benchResults[benchResult].hasOwnProperty(\"size\") &&\n this.state.benchResults[benchResult].size != null &&\n this.state.benchResults[benchResult].size != NaN)\n ) {\n console.log(\"bench result :\");\n console.log({ benchResult });\n const description = this.state.benchResults[benchResult].description;\n console.log(\"time : \");\n console.log(this.state.benchResults[benchResult].time);\n console.log(\"size : \");\n console.log(this.state.benchResults[benchResult].size);\n console.log(\"bench : \");\n console.log(this.state.benchResults[benchResult]);\n const time = this.state.benchResults[benchResult].time;\n const size = this.state.benchResults[benchResult].size;\n const id = this.state.benchResults[benchResult].id;\n bench[\"bench\"].push({\n description: description,\n time: time,\n size: Math.trunc(size),\n id: id,\n });\n }\n }\n console.log(bench);\n const dataStr =\n \"data:text/json;charset=utf-8,\" +\n encodeURIComponent(JSON.stringify(bench));\n const downloadAnchorNode = document.createElement(\"a\");\n downloadAnchorNode.setAttribute(\"href\", dataStr);\n downloadAnchorNode.setAttribute(\"download\", \"exportName\" + \".json\");\n document.body.appendChild(downloadAnchorNode);\n downloadAnchorNode.click();\n downloadAnchorNode.remove();\n }",
"toJSON() {\n return {\n latitude: this._lat,\n longitude: this._long\n };\n }",
"function exerciseToJSON() {\n //get data from form\n const routineName = routineNameRef.current.value\n const numberOfRounds = numberOfRoundsRef.current.value\n const restBetweenRounds = restBetweenRoundsRef.current.value\n\n //put data into a JSON\n routineJSON.RoutineName = routineName\n routineJSON.NumberOfRounds = numberOfRounds\n routineJSON.RestBetweenRounds = restBetweenRounds\n routineJSON.ExerciseList = exerciseList.toString()\n\n //send JSON to backend with a function call\n console.log( JSON.stringify( routineJSON ) )\n\n //Display confirmation message\n window.alert( \"Congratulations, you have saved a new workout routine!\" )\n\n //Clear Form\n clearForm()\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 constructResponseJson() {\n return response = {\n \"response\" : {\n \"head\" : {\n \"id\" : \"123123\"\n },\n \"payload\" : {}\n }\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
System menus must be explicitly created on OS X, see nodewebkit documentation: | function createSystemMenuForOSX()
{
if ('darwin' == OS.platform())
{
try
{
var appName = getApplicationName()
var win = GUI.Window.get()
var nativeMenuBar = new GUI.Menu({ type: 'menubar' })
nativeMenuBar.createMacBuiltin(appName)
win.menu = nativeMenuBar;
}
catch (ex)
{
window.console.log('Error creating OS X menubar: ' + ex.message);
}
}
} | [
"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}",
"createAppMenu () {\n Menu.setApplicationMenu(appMenu.build(this.appMenuSelectors, []))\n appMenu.bindHiddenShortcuts(this.appMenuSelectors)\n }",
"function createMenus() {\n // build application menus\n const appName = electron.app.getName()\n\n const menuTemplate = [{\n label: appName,\n submenu: [{\n label: `About ${appName}`,\n role: 'about'\n }, {\n type: 'separator'\n }, {\n label: 'Quit',\n click: _ => {\n app.quit()\n },\n accelerator: 'CommandOrControl+Q'\n }, {\n label: 'Open Dev tools',\n click: _ => {\n mainWindow.openDevTools();\n }\n }]\n }]\n\n const menu = Menu.buildFromTemplate(menuTemplate)\n Menu.setApplicationMenu(menu)\n}",
"function ShowExampleAppMainMenuBar() {\r\n if (BeginMainMenuBar()) {\r\n if (BeginMenu(\"File\")) {\r\n ShowExampleMenuFile();\r\n EndMenu();\r\n }\r\n if (BeginMenu(\"Edit\")) {\r\n if (MenuItem(\"Undo\", \"CTRL+Z\")) ;\r\n if (MenuItem(\"Redo\", \"CTRL+Y\", false, false)) ; // Disabled item\r\n Separator();\r\n if (MenuItem(\"Cut\", \"CTRL+X\")) ;\r\n if (MenuItem(\"Copy\", \"CTRL+C\")) ;\r\n if (MenuItem(\"Paste\", \"CTRL+V\")) ;\r\n EndMenu();\r\n }\r\n EndMainMenuBar();\r\n }\r\n }",
"function simulateMacSafari3() {\n userAgent.MAC = true;\n userAgent.WINDOWS = false;\n userAgent.LINUX = false;\n userAgent.IE = false;\n userAgent.EDGE = false;\n userAgent.EDGE_OR_IE = false;\n userAgent.GECKO = false;\n userAgent.WEBKIT = true;\n userAgent.VERSION = '525';\n}",
"function simulateMacFirefox() {\n userAgent.MAC = true;\n userAgent.WINDOWS = false;\n userAgent.LINUX = false;\n userAgent.IE = false;\n userAgent.EDGE = false;\n userAgent.EDGE_OR_IE = false;\n userAgent.GECKO = true;\n userAgent.WEBKIT = false;\n}",
"function simulateLinuxFirefox() {\n userAgent.MAC = false;\n userAgent.WINDOWS = false;\n userAgent.LINUX = true;\n userAgent.IE = false;\n userAgent.EDGE = false;\n userAgent.EDGE_OR_IE = false;\n userAgent.GECKO = true;\n userAgent.WEBKIT = false;\n}",
"function createContextMenus() {\n // These are the permissions we need\n const permissions = { permissions: ['contextMenus'] };\n\n // Check to see if we already have them.\n chrome.permissions.contains(permissions, yes => {\n // If we have them, then create the context menu\n if (yes) {\n return _createContextMenus();\n }\n\n // Let's ask the User then\n return chrome.permissions.request(permissions, granted => {\n // If the User granted it, then add the Context Menu\n if (granted) {\n return _createContextMenus();\n }\n });\n });\n}",
"function showIconAddMenu() {\n var apps = FPI.apps.all, i, bundle, sel, name;\n clearinnerHTML(appList);\n showHideElement(appList, 'block');\n appList.appendChild(createDOMElement('li', 'Disable Edit', 'name', 'Edit'));\n\n for (i = 0; i < apps.length; i++) {\n bundle = apps[i].bundle;\n sel = FPI.bundle[bundle];\n name = sel.name;\n appList.appendChild(createDOMElement('li', name, 'name', bundle));\n }\n}",
"function initDesktopMenu() {\n\t\tif(window.desktopCapable) {\n\t\t\tcurScrollTop = window.pageYOffset;\n\t\t\tif(window.responsiveState !== 'mobile' && $active.length) {\n\t\t\t\twindow.requestAnimationFrame(function () {\n\t\t\t\t\treturn setIndicator($active[0]);\n\t\t\t\t});\n\t\t\t}\n $window.smartresize(function(){\n setIndicator($active[0])\n });\n\t\t}\n\t\tonPageLoad();\n\t}",
"function mainMenu() {\n console.clear();\n mainMenuVisual();\n mainMenuOption();\n}",
"function createMenu () {\n\tconst template = require('./data/menu.json');\n\tmenu = Menu.buildFromTemplate(template);\n\tMenu.setApplicationMenu(menu);\n}",
"function updateNsMenu(){\n\t\tvar ns = new Dict();\n\t\tns.clear();\n\t\tns.parse(JSON.stringify(namespaces));\n\t\t\n\t\tvar keys = ns.getkeys();\n\t\tkeys = arrayCheck(keys);\n\n\t\tnsMenu.message(\"clear\");\n\n\t\tfor(var i = 0; i < keys.length; i++){\n\t\t\tnsMenu.message(\"append\", String(keys[i]));\n\t\t}\n\t}",
"BuildMenuButton(){\n // Menu bar Translucide\n NanoXSetMenuBarTranslucide(true)\n // clear menu button left\n NanoXClearMenuButtonLeft()\n // clear menu button right\n NanoXClearMenuButtonRight()\n // clear menu button setttings\n NanoXClearMenuButtonSettings()\n // Show name in menu bar\n NanoXShowNameInMenuBar(false)\n }",
"function testShowMenuWithActionsOpensContextMenu() {\n sendContextMenu('#file-list');\n assertFalse(contextMenu.hasAttribute('hidden'));\n}",
"_overrideGnomeShellFunctions() {\n let self = this;\n\n // Hide normal Dash\n if (this._settings.get_boolean('hide-dash')) {\n // Hide normal dash\n Main.overview.dash.hide();\n Main.overview.dash.set_width(1);\n }\n\n // Change source of swarm animation to shortcuts panel apps button\n if (self._settings.get_boolean('show-shortcuts-panel') && self._settings.get_boolean('shortcuts-panel-appsbutton-animation')) {\n GSFunctions['BaseAppView_doSpringAnimation'] = AppDisplay.BaseAppView.prototype._doSpringAnimation;\n AppDisplay.BaseAppView.prototype._doSpringAnimation = function(animationDirection){\n this._grid.opacity = 255;\n this._grid.animateSpring(\n animationDirection,\n self._shortcutsPanel._appsButton);\n };\n }\n\n // Hide normal workspaces thumbnailsBox\n Main.overview._overview._controls._thumbnailsSlider.opacity = 0;\n\n // Override WorkspaceSwitcherPopup _show function to prevent popup from showing when disabled\n GSFunctions['WorkspaceSwitcherPopup_show'] = WorkspaceSwitcherPopup.WorkspaceSwitcherPopup.prototype._show;\n WorkspaceSwitcherPopup.WorkspaceSwitcherPopup.prototype._show = function() {\n if (self._settings.get_boolean('hide-workspace-switcher-popup')) {\n return false;\n } else {\n let ret = GSFunctions['WorkspaceSwitcherPopup_show'].call(this);\n return ret;\n }\n };\n\n // Extend LayoutManager _updateRegions function to destroy/create workspace thumbnails when completed.\n // NOTE1: needed because 'monitors-changed' signal doesn't wait for queued regions to update.\n // We need to wait so that the screen workspace workarea is adjusted before creating workspace thumbnails.\n // Otherwise when we move the primary workspace to another monitor, the workspace thumbnails won't adjust for the top panel.\n // NOTE2: also needed when dock-fixed is enabled/disabled to adjust for workspace area change\n GSFunctions['LayoutManager_updateRegions'] = Layout.LayoutManager.prototype._updateRegions;\n Layout.LayoutManager.prototype._updateRegions = function() {\n let workArea = Main.layoutManager.getWorkAreaForMonitor(Main.layoutManager.primaryIndex);\n let ret = GSFunctions['LayoutManager_updateRegions'].call(this);\n // SANITY CHECK:\n if (self._refreshThumbnailsOnRegionUpdate) {\n self._refreshThumbnailsOnRegionUpdate = false;\n if (this._settings)\n self._refreshThumbnails();\n } else {\n if (self._workAreaWidth) {\n let widthTolerance = workArea.width * .01;\n let heightTolerance = workArea.height * .01;\n if (self._workAreaWidth < workArea.width-widthTolerance || self._workAreaWidth > workArea.width+widthTolerance) {\n self._refreshThumbnails();\n } else if (self._workAreaHeight < workArea.height-heightTolerance || self._workAreaHeight > workArea.height+heightTolerance) {\n self._refreshThumbnails();\n }\n } else {\n self._refreshThumbnails();\n }\n }\n return ret;\n };\n\n // Override geometry calculations of activities overview to use workspaces-to-dock instead of the default thumbnailsbox.\n // NOTE: This is needed for when the dock is positioned on a secondary monitor and also for when the shortcuts panel is visible\n // causing the dock to be wider than normal.\n GSFunctions['WorkspacesDisplay_updateWorkspacesActualGeometry'] = WorkspacesView.WorkspacesDisplay.prototype._updateWorkspacesActualGeometry;\n WorkspacesView.WorkspacesDisplay.prototype._updateWorkspacesActualGeometry = function() {\n if (!this._workspacesViews.length)\n return;\n\n let [x, y] = this.get_transformed_position();\n let allocation = this.allocation;\n let width = allocation.x2 - allocation.x1;\n let height = allocation.y2 - allocation.y1;\n\n let spacing = Main.overview._overview._controls.get_theme_node().get_length('spacing');\n let monitors = Main.layoutManager.monitors;\n\n // Get Dash monitor index\n let dashMonitorIndex = this._primaryIndex;\n let dashMultiMonitor = false;\n if (DashToDock) {\n if (DashToDock.dockManager) {\n dashMonitorIndex = DashToDock.dockManager._preferredMonitorIndex;\n dashMultiMonitor = DashToDock.dockManager._settings.get_boolean('multi-monitor');\n } else {\n dashMonitorIndex = DashToDock.dock._settings.get_int('preferred-monitor');\n if (dashMonitorIndex < 0 || dashMonitorIndex >= Main.layoutManager.monitors.length) {\n dashMonitorIndex = this._primaryIndex;\n }\n }\n }\n\n // Get thumbnails monitor index\n let preferredMonitorIndex = self._settings.get_int('preferred-monitor');\n let thumbnailsMonitorIndex = (Main.layoutManager.primaryIndex + preferredMonitorIndex) % Main.layoutManager.monitors.length ;\n\n // Iterate through monitors\n for (let i = 0; i < monitors.length; i++) {\n\n let geometry = { x: monitors[i].x, y: monitors[i].y, width: monitors[i].width, height: monitors[i].height };\n\n // Adjust index to point to correct dock\n // Only needed when using DashToDock.dockManager\n let idx;\n if (i == dashMonitorIndex || dashMultiMonitor) {\n idx = 0;\n } else if (i < dashMonitorIndex) {\n idx = i + 1;\n }\n\n // Adjust width for dash\n let dashWidth = 0;\n let dashHeight = 0;\n let monitorHasDashDock = false;\n if (DashToDock) {\n if (DashToDock.dockManager) {\n if (DashToDock.dockManager._allDocks[0]) {\n if (i == dashMonitorIndex || dashMultiMonitor) {\n monitorHasDashDock = true;\n if (DashToDock.dockManager._allDocks[idx]._position == St.Side.LEFT ||\n DashToDock.dockManager._allDocks[idx]._position == St.Side.RIGHT) {\n dashWidth = DashToDock.dockManager._allDocks[idx]._box.width + spacing;\n }\n if (DashToDock.dockManager._allDocks[idx]._position == St.Side.TOP ||\n DashToDock.dockManager._allDocks[idx]._position == St.Side.BOTTOM) {\n dashHeight = DashToDock.dockManager._allDocks[idx]._box.height + spacing;\n }\n }\n }\n } else {\n if (i == dashMonitorIndex) {\n monitorHasDashDock = true;\n if (DashToDockExtension.hasDockPositionKey) {\n if (DashToDock.dock._position == St.Side.LEFT ||\n DashToDock.dock._position == St.Side.RIGHT) {\n dashWidth = DashToDock.dock._box.width + spacing;\n }\n if (DashToDock.dock._position == St.Side.TOP ||\n DashToDock.dock._position == St.Side.BOTTOM) {\n dashHeight = DashToDock.dock._box.height + spacing;\n }\n } else {\n dashWidth = DashToDock.dock._box.width + spacing;\n }\n }\n }\n } else {\n if (!self._settings.get_boolean('hide-dash') &&\n i == this._primaryIndex) {\n dashWidth = Main.overview._overview._controls._dashSlider.getVisibleWidth() + spacing;\n }\n }\n\n // Adjust width for workspaces thumbnails\n let thumbnailsWidth = 0;\n let thumbnailsHeight = 0;\n let monitorHasThumbnailsDock = false;\n if (i == thumbnailsMonitorIndex) {\n monitorHasThumbnailsDock = true;\n let fixedPosition = self._settings.get_boolean('dock-fixed');\n let overviewAction = self._settings.get_enum('overview-action');\n let visibleEdge = self._triggerWidth;\n if (self._settings.get_boolean('dock-edge-visible')) {\n visibleEdge = self._triggerWidth + DOCK_EDGE_VISIBLE_WIDTH;\n }\n if (self._position == St.Side.LEFT ||\n self._position == St.Side.RIGHT) {\n if (fixedPosition) {\n thumbnailsWidth = self.actor.get_width() + spacing;\n } else {\n if (overviewAction == OverviewAction.HIDE) {\n thumbnailsWidth = visibleEdge;\n } else if (overviewAction == OverviewAction.SHOW_PARTIAL) {\n thumbnailsWidth = self._slider.partialSlideoutSize;\n } else {\n thumbnailsWidth = self.actor.get_width() + spacing;\n }\n }\n }\n if (self._position == St.Side.TOP ||\n self._position == St.Side.BOTTOM) {\n if (fixedPosition) {\n thumbnailsHeight = self.actor.get_height() + spacing;\n } else {\n if (overviewAction == OverviewAction.HIDE) {\n thumbnailsHeight = visibleEdge;\n } else if (overviewAction == OverviewAction.SHOW_PARTIAL) {\n thumbnailsHeight = self._slider.partialSlideoutSize;\n } else {\n thumbnailsHeight = self.actor.get_height() + spacing;\n }\n }\n }\n }\n\n // Adjust x and width for workspacesView geometry\n let controlsWidth = dashWidth + thumbnailsWidth;\n if (DashToDock && DashToDockExtension.hasDockPositionKey) {\n if (DashToDock.dockManager) {\n if (DashToDock.dockManager._allDocks[0]) {\n // What if dash and thumbnailsbox are both on the same side?\n if ((monitorHasDashDock && DashToDock.dockManager._allDocks[idx]._position == St.Side.LEFT) &&\n (monitorHasThumbnailsDock && self._position == St.Side.LEFT)) {\n controlsWidth = Math.max(dashWidth, thumbnailsWidth);\n geometry.x += controlsWidth;\n } else {\n if (monitorHasDashDock && DashToDock.dockManager._allDocks[idx]._position == St.Side.LEFT) {\n geometry.x += dashWidth;\n }\n if (monitorHasThumbnailsDock && self._position == St.Side.LEFT) {\n geometry.x += thumbnailsWidth;\n }\n }\n if ((monitorHasDashDock && DashToDock.dockManager._allDocks[idx]._position == St.Side.RIGHT) &&\n (monitorHasThumbnailsDock && self._position == St.Side.RIGHT)) {\n controlsWidth = Math.max(dashWidth, thumbnailsWidth);\n }\n }\n } else {\n // What if dash and thumbnailsbox are both on the same side?\n if ((monitorHasDashDock && DashToDock.dock._position == St.Side.LEFT) &&\n (monitorHasThumbnailsDock && self._position == St.Side.LEFT)) {\n controlsWidth = Math.max(dashWidth, thumbnailsWidth);\n geometry.x += controlsWidth;\n } else {\n if (monitorHasDashDock && DashToDock.dock._position == St.Side.LEFT) {\n geometry.x += dashWidth;\n }\n if (monitorHasThumbnailsDock && self._position == St.Side.LEFT) {\n geometry.x += thumbnailsWidth;\n }\n }\n if ((monitorHasDashDock && DashToDock.dock._position == St.Side.RIGHT) &&\n (monitorHasThumbnailsDock && self._position == St.Side.RIGHT)) {\n controlsWidth = Math.max(dashWidth, thumbnailsWidth);\n }\n }\n } else {\n if (this.get_text_direction() == Clutter.TextDirection.LTR) {\n if (monitorHasThumbnailsDock && self._position == St.Side.LEFT) {\n controlsWidth = Math.max(dashWidth, thumbnailsWidth);\n geometry.x += controlsWidth;\n } else {\n geometry.x += dashWidth;\n }\n } else {\n if (monitorHasThumbnailsDock && self._position == St.Side.RIGHT) {\n controlsWidth = Math.max(dashWidth, thumbnailsWidth);\n } else {\n geometry.x += thumbnailsWidth;\n }\n }\n }\n geometry.width -= controlsWidth;\n\n // Adjust y and height for workspacesView geometry for primary monitor (top panel, etc.)\n if (i == this._primaryIndex) {\n geometry.y = y;\n if (height > 0)\n geometry.height = height;\n }\n\n\n // What if dash and thumbnailsBox are not on the primary monitor?\n let controlsHeight = dashHeight + thumbnailsHeight;\n if (DashToDock && DashToDockExtension.hasDockPositionKey) {\n if (DashToDock.dockManager) {\n if (DashToDock.dockManager._allDocks[0]) {\n if ((monitorHasDashDock && DashToDock.dockManager._allDocks[idx]._position == St.Side.TOP) &&\n (monitorHasThumbnailsDock && self._position == St.Side.TOP)) {\n controlsHeight = Math.max(dashHeight, thumbnailsHeight);\n geometry.y += controlsHeight;\n } else {\n if (monitorHasDashDock && DashToDock.dockManager._allDocks[idx]._position == St.Side.TOP) {\n geometry.y += dashHeight;\n }\n if (monitorHasThumbnailsDock && self._position == St.Side.TOP) {\n geometry.y += thumbnailsHeight;\n }\n }\n if ((monitorHasDashDock && DashToDock.dockManager._allDocks[idx]._position == St.Side.BOTTOM) &&\n (monitorHasThumbnailsDock && self._position == St.Side.BOTTOM)) {\n controlsHeight = Math.max(dashHeight, thumbnailsHeight);\n }\n }\n } else {\n if ((monitorHasDashDock && DashToDock.dock._position == St.Side.TOP) &&\n (monitorHasThumbnailsDock && self._position == St.Side.TOP)) {\n controlsHeight = Math.max(dashHeight, thumbnailsHeight);\n geometry.y += controlsHeight;\n } else {\n if (monitorHasDashDock && DashToDock.dock._position == St.Side.TOP) {\n geometry.y += dashHeight;\n }\n if (monitorHasThumbnailsDock && self._position == St.Side.TOP) {\n geometry.y += thumbnailsHeight;\n }\n }\n if ((monitorHasDashDock && DashToDock.dock._position == St.Side.BOTTOM) &&\n (monitorHasThumbnailsDock && self._position == St.Side.BOTTOM)) {\n controlsHeight = Math.max(dashHeight, thumbnailsHeight);\n }\n }\n } else {\n if (monitorHasThumbnailsDock && self._position == St.Side.TOP) {\n geometry.y += thumbnailsHeight;\n }\n }\n geometry.height -= controlsHeight;\n\n this._workspacesViews[i].setMyActualGeometry(geometry);\n }\n };\n\n // This override is needed to prevent calls from updateWorkspacesActualGeometry bound to the workspacesDisplay object\n // without destroying and recreating Main.overview.viewSelector._workspacesDisplay.\n // We replace this function with a new setMyActualGeometry function (see below)\n // TODO: This is very hackish. We need to find a better way to accomplish this\n GSFunctions['WorkspacesViewBase_setActualGeometry'] = WorkspacesView.WorkspacesViewBase.prototype.setActualGeometry;\n WorkspacesView.WorkspacesViewBase.prototype.setActualGeometry = function(geom) {\n //GSFunctions['WorkspacesView_setActualGeometry'].call(this, geom);\n return;\n };\n\n // This additional function replaces the WorkspacesView setActualGeometry function above.\n // TODO: This is very hackish. We need to find a better way to accomplish this\n WorkspacesView.WorkspacesViewBase.prototype.setMyActualGeometry = function(geom) {\n this._actualGeometry = geom;\n this._syncActualGeometry();\n };\n\n this._overrideComplete = true;\n }",
"static onSelect() {\n const node = Navigator.byItem.currentNode;\n if (MenuManager.isMenuOpen() || node.actions.length <= 1 ||\n !node.location) {\n node.doDefaultAction();\n return;\n }\n\n ActionManager.instance.menuStack_ = [];\n ActionManager.instance.menuStack_.push(MenuType.MAIN_MENU);\n ActionManager.instance.actionNode_ = node;\n ActionManager.instance.openCurrentMenu_();\n }",
"function ShowDemoWindow(parent, init)\n{\n var window = two.ui.window(parent, 'ImGui Demo', two.WindowState.Default | two.WindowState.Menu);\n\n var body = two.ui.scrollable(window.body);\n //var scrollsheet = two.ui.scroll_sheet(window.body);\n //var body = scrollsheet.body;\n\n if(window.menu)\n {\n menubar = window.menu;\n\n var menu = two.ui.menu(menubar, 'Menu').body\n if(menu)\n {\n //ShowExampleMenuFile();\n }\n\n theme_menu(menubar);\n\n var menu = two.ui.menu(menubar, 'Examples').body\n if(menu)\n {\n //two.ui.menu_option(menu, 'Main menu bar', '', show_app_main_menu_bar);\n //two.ui.menu_option(menu, 'Console', '', show_app_console);\n //two.ui.menu_option(menu, 'Log', '', show_app_log);\n //two.ui.menu_option(menu, 'Simple layout', '', show_app_layout);\n //two.ui.menu_option(menu, 'Property editor', '', show_app_property_editor);\n //two.ui.menu_option(menu, 'Long text display', '', show_app_long_text);\n //two.ui.menu_option(menu, 'Auto-resizing window', '', show_app_auto_resize);\n //two.ui.menu_option(menu, 'Constrained-resizing window', '', show_app_constrained_resize);\n //two.ui.menu_option(menu, 'Simple overlay', '', show_app_simple_overlay);\n //two.ui.menu_option(menu, 'Manipulating window titles', '', show_app_window_titles);\n //two.ui.menu_option(menu, 'Custom rendering', '', show_app_custorendering);\n //two.ui.menu_option(menu, 'Documents', '', show_app_documents);\n }\n\n var help = two.ui.menu(menubar, 'Help').body\n if(help)\n {\n //two.ui.menu_option(help, 'Metrics', '', show_app_metrics);\n //two.ui.menu_option(help, 'Style Editor', '', show_app_style_editor);\n //two.ui.menu_option(help, 'About Dear ImGui', '', show_app_about);\n }\n }\n\n //two.ui.labelf(body, 'dear imgui says hello. (%s)', '1.0'); //IMGUI_VERSION);\n //two.ui.Spacing();\n\n var help = two.ui.expandbox(body, 'Help').body\n if(help)\n {\n two.ui.label(help, 'PROGRAMMER GUIDE:');\n two.ui.bullet(help, 'Please see the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!');\n two.ui.bullet(help, 'Please see the comments in imgui.cpp.');\n two.ui.bullet(help, 'Please see the examples/ in application.');\n two.ui.bullet(help, 'Enable io.ConfigFlags |= NavEnableKeyboard for keyboard controls.');\n two.ui.bullet(help, 'Enable io.ConfigFlags |= NavEnableGamepad for gamepad controls.');\n two.ui.separator(help);\n\n two.ui.label(help, 'USER GUIDE:');\n ShowUserGuide(help);\n }\n\n var config = two.ui.expandbox(body, 'Configuration').body\n if(config)\n {\n }\n\n if(init)\n {\n this.no_titlebar = false;\n this.no_scrollbar = false;\n this.no_menu = false;\n this.no_move = false;\n this.no_resize = false;\n this.no_collapse = false;\n this.no_close = false;\n this.no_nav = false;\n this.no_background = false;\n this.no_bring_to_front = false;\n }\n \n var opts = two.ui.expandbox(body, 'Window options').body\n if(opts)\n {\n row0 = two.ui.row(opts);\n two.ui.field_bool(row0, 'No titlebar', this.no_titlebar, true);\n two.ui.field_bool(row0, 'No scrollbar', this.no_scrollbar, true);\n two.ui.field_bool(row0, 'No menu', this.no_menu, true);\n\n row1 = two.ui.row(opts);\n two.ui.field_bool(row1, 'No move', this.no_move, true);\n two.ui.field_bool(row1, 'No resize', this.no_resize, true);\n two.ui.field_bool(row1, 'No collapse', this.no_collapse, true);\n\n row2 = two.ui.row(opts);\n two.ui.field_bool(row2, 'No close', this.no_close, true);\n two.ui.field_bool(row2, 'No nav', this.no_nav, true);\n two.ui.field_bool(row2, 'No background', this.no_background, true);\n\n row3 = two.ui.row(opts);\n two.ui.field_bool(row3, 'No bring to front', this.no_bring_to_front, true);\n }\n\n}",
"function eventMenuAddSignature(){\n\tif(module.addSigMenuItems.length > 0){\n\t\tvar posX = dhtml.getElementLeft(dhtml.getElementById(\"addsignature\"));\n\t\tvar posY = dhtml.getElementTop(dhtml.getElementById(\"addsignature\"));\n\t\tposY += dhtml.getElementById(\"addsignature\").offsetHeight;\n\t\twebclient.menu.buildContextMenu(module.id, \"addsignature\", module.addSigMenuItems, posX, posY);\n\t}else{\n\t\talert(_(\"No signatures\"));\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If sheet has additional info, loop and format it | function getAddedInfo(addedInfo){
var header = sheet.getRange(1, 7, 1, lastColumn - 6).getValues();
header = [].concat.apply([], header);
var formatAddedInfo = '<br />';
for (i = 0; i < addedInfo.length; i++){
if (addedInfo[i] != ""){
if (Date.parse(addedInfo[i])) {
if (addedInfo[i].getYear() == 1899) {
addedInfo[i] = addedInfo[i].toLocaleTimeString();
addedInfo[i].slice(0, addedInfo[i].length - 4);
} else {
addedInfo[i] = addedInfo[i].toLocaleDateString();
}
}
formatAddedInfo = formatAddedInfo + '<br />' +
header[i] + ': ' + addedInfo[i];
}
}
return formatAddedInfo;
} | [
"function archiveTask(){\n var style = SpreadsheetApp.newTextStyle()\n //.setForegroundColor(\"red\")\n .setFontSize(11)\n //.setBold(true)\n //.setUnderline(true)\n .build();\n var archived_task={};\n var archives={};\n \n for(var [i,name] in archives_name){\n archived_task[name]=[];\n archives[name]=SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);\n }\n //console.log(archived_task);\n var priority_sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"priority_queue\"); \n var all_priority_range = priority_sheet.getDataRange();\n var all_priority_data = all_priority_range.getValues();\n var new_priority_data = [];\n var cols = all_priority_range.getNumColumns();\n var rows = all_priority_range.getNumRows();\n var currentTime=new Date();\n \n for(i=1;i<rows;i++){//read all tasks for processing\n var current_row=all_priority_data[i];\n var data_type=current_row[column_index[\"task type\"]];\n var ending_time=current_row[column_index[\"ending time\"]];\n if(ending_time && data_type) {//find a task needed to be archived \n current_row.splice(column_index[\"task type\"],1);\n archived_task[data_type].push(current_row); \n }\n else{\n new_priority_data.push(current_row);\n }\n }\n \n for (var key in archives) {//archive all tasks into corresponding archives\n // check if the property/key is defined in the object itself, not in parent\n \n if (archives.hasOwnProperty(key)) {\n var value=archives[key];\n var archive_rows=value.getDataRange().getNumRows();\n var archive_cols=value.getDataRange().getNumColumns();\n var tasks=archived_task[key];\n if(tasks.length>0){\n //console.log(tasks);\n value.getRange(archive_rows+1,1,tasks.length,tasks[0].length).setValues(tasks);\n value.getRange(archive_rows+1,1,tasks.length,tasks[0].length).setTextStyle(style);\n }\n }\n }\n \n priority_sheet.getRange(2,1,rows,cols).clear();\n priority_sheet.getRange(2,1,rows,cols).setTextStyle(style);\n priority_sheet.getRange(2, 1, new_priority_data.length, new_priority_data[0].length).setValues(new_priority_data); \n \n var eventCal=CalendarApp.getCalendarById(\"impanyu@gmail.com\");\n for (var key in archives) {//writes archived tasks into calendar\n var tasks=archived_task[key];\n for([i,task] in tasks){\n var starting_time=task[column_index[\"starting time\"]];\n var ending_time=task[column_index[\"ending time\"]];\n var task_name=\"\";\n var link=task[column_index[\"link\"]-1];\n var task_info=\"info: \"+task[column_index[\"task info\"]-1];\n if(link) task_info+=\"\\nlink: \"+link;\n if(task[column_index[\"task group\"]-1]) task_name+=task[column_index[\"task group\"]-1]+\" \";\n task_name+=task[column_index[\"task name\"]-1];\n console.info(starting_time);\n eventCal.createEvent(task_name, starting_time, ending_time,{description:task_info});\n }\n }\n}",
"function updateSpreadsheet(results, spreadsheetId) { // results is returned from getResults()\r\n let days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];\r\n\r\n // Open spreadsheet\r\n let availabilitiesSpreadsheet = SpreadsheetApp.openById(spreadsheetId);\r\n for (i = 0; i < results.length; i++) {\r\n // Use the responses from the student to find the day of the week they selected for the appointment\r\n let appointmentTimeInfo = results[i][3]; // Format: '2021-02-04 15:00'\r\n let appointmentDate = new Date(appointmentTimeInfo);\r\n let appointmentDay = appointmentDate.getDay() - 1; // Subtract 1 because it starts week at Sunday\r\n \r\n // Go to the corresponding sheet on the availabilities spreadsheet\r\n let sheetName = days[appointmentDay];\r\n let availabilitiesSheet = availabilitiesSpreadsheet.getSheetByName(sheetName);\r\n\r\n // Go to the right column based on the time (time is along the top)\r\n let appointmentTime = parseInt(appointmentTimeInfo.substring(11,13)) - 15; // Subtract 15 to account for time past noon\r\n let columnns = ['B', 'C', 'D', 'E'];\r\n let column = columnns[appointmentTime];\r\n let row = 0;\r\n\r\n // Go to the right row (based on the tutor name, as names are down the left side)\r\n let tutorName = results[i][6];\r\n let tutorNames = availabilitiesSheet.getRange('A:A').getValues();\r\n for (j = 0; j < tutorNames.length; j++) {\r\n if (tutorNames[j] == tutorName) {\r\n row = (j + 1).toString(); // Rows start at 1\r\n }\r\n }\r\n\r\n // Color in the correct cell red\r\n let appointmentCell = availabilitiesSheet.getRange(column + row).setBackground('red');\r\n }\r\n}",
"function createMRSPatientSheet(){ \r\n \r\n const currentSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();\r\n const currentSheet = currentSpreadSheet.getActiveSheet();\r\n const currentRange = currentSheet.getActiveRange().getValues();\r\n \r\n const sheetsAmount = currentRange.length;\r\n \r\n // Demande de confirmation\r\n const ui = SpreadsheetApp.getUi();\r\n const result = ui.alert(\r\n \"Générer fiche(s) patient(s)\",\r\n `Voulez-vous générer ${sheetsAmount} fiche(s) patient(s).`,\r\n ui.ButtonSet.YES_NO);\r\n\r\n // Process the user's response.\r\n if (result == ui.Button.NO) {\r\n return;\r\n }\r\n \r\n const localTemplate = importPatientSheetTemplate(currentSpreadSheet);\r\n localTemplate.setName(Utilities.formatDate(new Date(), \"GMT+1\", \"yyyy-MM-dd\") + \"-temporary-template\");\r\n \r\n const rangeToUpdate = \"B2:B12\";\r\n const templateValues = localTemplate.getRange(rangeToUpdate).getValues();\r\n \r\n for (let key in currentRange)\r\n {\r\n const row = currentRange[key]; \r\n\r\n const sheetName = row[0];\r\n \r\n const newSheet = currentSpreadSheet.insertSheet(sheetName, {template: localTemplate}); \r\n copySheetRangeProtectionWarnings(localTemplate,newSheet);\r\n \r\n const templateValuesCopy = Array.from(templateValues);\r\n \r\n templateValuesCopy[0][0] = row[1];\r\n templateValuesCopy[2][0] = row[2];\r\n templateValuesCopy[3][0] = row[3];\r\n templateValuesCopy[5][0] = row[4];\r\n templateValuesCopy[6][0] = row[5];\r\n templateValuesCopy[7][0] = row[6];\r\n templateValuesCopy[9][0] = row[7];\r\n templateValuesCopy[10][0] = row[8];\r\n \r\n newSheet.getRange(rangeToUpdate).setValues(templateValuesCopy)\r\n \r\n currentSpreadSheet.toast(`La fiche patient ${sheetName} a été générée`,\"Fiche générée\");\r\n }\r\n \r\n currentSpreadSheet.deleteSheet(localTemplate)\r\n \r\n patientSheetsGenerated();\r\n \r\n}",
"function customerMedDetails()\n{\n var sheet = getSheetByName(\"Customer_List\");\n var data = sheet.getDataRange();\n var last_row = sheet.getLastRow();\n var last_column = sheet.getLastColumn();\n// var allData = data.getValues();\n\n var date = Utilities.formatDate(new Date(), \"GMT+5.30\", \"dd/MM/yyyy 00:00:00\"); // Today's Date\n \n var allData=\"\";\n var excelDate;\n var rangeCount = 0;\n var x;\n //Logger.log(\"\\n last_row : \"+last_row);\n \n for(var i=2;i<=last_row;i++){\n\n var manualCellDate = data.getCell(i,9).getValue();\n var automaticCellDate = data.getCell(i,10).getValue();\n \n Logger.log(\"manualCellDate value is: \"+manualCellDate+\"\\n\"+\"automaticCellDate value is: \"+automaticCellDate )\n if(manualCellDate=\"\"){\n excelDate = formatDate(automaticCellDate); //Product finishing Date\n }else{\n excelDate = formatDate(manualCellDate); //Product finishing Date\n }\n \n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// var range = sheet.getRange(2, last_row, 1, last_column)\n// \n// Logger.log(\"Value: \"+data.getCell(i,2).getValue()+\" : \" +range.isPartOfMerge());\n// \n// var numRows = range.getNumRows();\n// \n// if(data.getCell(i,2).getValue() != \"\"){\n// var valueIs = \"\"+data.getCell(i,2).getValue();\n// rangeCount++;\n// var x = i; //got the cell value of the first merge cell\n// //Logger.log(\"x is: \"+x);\n// }else{\n// \n// }\n// Logger.log(\"x is: \"+x);\n// //Logger.log(\"rangeCount is: \"+rangeCount);\n// \n////**************************************************************************************************************************\n \n if(date > excelDate)\n {\n ////////////////////////////////////////////////////////////////////////////\n// //var expiredRow = range.getValue();\n// var cell = i.getCurrentCell();\n// var expiredRow = cell.getRow();\n// Logger.log(\"expiredRow: \"+expiredRow);\n// console.log(\"expiredRow: \"+expiredRow);\n ///*************************************************************************\n var medicinesData;\n \n var shopkeeper_email;\n var customer_name,customer_mobile_number,customer_address,shopkeeper_name,shopkeeper_mobile;\n var count = 0;\n \n for(j=0; j<i ;j++){\n medicinesData = data.getCell(i, 1).getValue()+\"\";\n customer_name = data.getCell(i, 2).getValue();\n customer_mobile_number = \"\"+data.getCell(i, 3).getValue();\n }\n allData = allData + \"\\n\"+\"o \"+medicinesData+\" : \"+customer_name+\" : \"+customer_mobile_number ;\n \n if(count == 0){\n shopkeeper_email = data.getCell(i, 13).getValue();\n \n customer_name = data.getCell(i, 2).getValue();\n customer_mobile_number = \"\"+data.getCell(i, 3).getValue();\n customer_address = data.getCell(i, 12).getValue();\n shopkeeper_name = data.getCell(i, 15).getValue();\n \n shopkeeper_mobile = \"\"+data.getCell(i, 14).getValue();\n count++;\n }\n }\n }\n ////////////////////////////////////////////////////////////////////////////\n \n ///*************************************************************************\n \n //Logger.log(\"All finished medicines : \"+medicines);\n var emailMsg = prepareMsgForEmail(shopkeeper_name,customer_name,allData,customer_mobile_number,customer_address);\n //Logger.log(\"\\n emailMsg : \"+emailMsg); \n \n var rows = sheet.getLastRow()\n var cols = sheet.getLastColumn()\n var dataRange = sheet.getRange(2,1,rows-1,cols) //getRange(startRow,startColumn,endRow,endColumn)\n var data = dataRange.getValues();\n \n var to = shopkeeper_email;\n \n sendEmail(to,'Customer Medicine Finished !',emailMsg);\n \n var textMsg = prepareTextMsg(shopkeeper_name,customer_name);\n //Logger.log(\"\\n textMsg : \"+textMsg); \n // Logger.log(shopkeeper_mobile);\n sendSMS(shopkeeper_mobile,textMsg);\n \n// SpreadsheetApp.flush();\n}",
"function UpdateAlerts(Log){\n var spreadSheet = SpreadsheetApp.openById(spreadSheetID); ///Open the spreadsheet\n var alertsSheet = spreadSheet.getSheetByName(\"Alerts\"); ///Get the Settings sheet\n var settings = alertsSheet.getRange(3,1,alertsSheet.getLastRow(),1);\n var nextRow = alertsSheet.getLastRow() + 1; ///Get next row after the last row\n \n ///Add all other Header + Data pairs from the received Log JSON\n for each (var key in Object.keys(Log)){\n var match = settings.createTextFinder(key).matchEntireCell(true).findNext(); ///lookup the alert limit row for each Log key\n if(match == null){ ///If settings row does not exists\n alertsSheet.getRange(nextRow, 1).setValue(key); ///Insert key in first Key column \n var rule = SpreadsheetApp.newDataValidation().requireValueInList(['YES', 'NO']).build();\n alertsSheet.getRange(nextRow, 4).setDataValidation(rule); ///Add YES/NO options for Triggered column\n alertsSheet.getRange(nextRow, 4).setHorizontalAlignment(\"right\");\n nextRow++;\n } \n }\n}",
"function generateSpreadsheet() {\n var fileName = DocumentApp.getActiveDocument().getName()+\"_data\";\n var spreadsheet = SpreadsheetApp.create(fileName); \n var documentProperties = PropertiesService.getDocumentProperties();\n var annotations = JSON.parse(documentProperties.getProperty('ANNOTATIONS'));\n var annotations_type = JSON.parse(documentProperties.getProperty('ANNOTATIONS_TYPE')); \n var links = JSON.parse(documentProperties.getProperty('LINKS')); \n var types = Object.keys(annotations_type);\n \n /* First type */ \n spreadsheet.getActiveSheet().setName(types[0]);\n for (var i = 0; i < annotations_type[types[0]].attributes.length; i++) {\n var attributeName = annotations_type[types[0]].attributes[i].name;\n spreadsheet.getSheetByName(types[0]).getRange(1,i+1).setValue(attributeName);\n for (var j = 0; j < annotations[types[0]].length; j++) { \n spreadsheet.getSheetByName(types[0]).getRange(j+2,1+i).setValue(annotations[types[0]][j][attributeName]);\n }\n }\n /* Saving of the links in the last column */\n var indexLastColumn = annotations_type[types[0]].attributes.length;\n spreadsheet.getSheetByName(types[0]).getRange(1,indexLastColumn+1).setValue(\"links\");\n for (var j = 0; j < annotations[types[0]].length; j++) { \n var currentID = annotations[types[0]][j][\"id\"];\n if(links[currentID] != undefined) {\n var linksToString = \"\";\n for (var k = 0; k < links[currentID].length; k++) {\n if(linksToString == \"\") {\n linksToString = links[currentID][k][\"target\"];\n }\n else {\n linksToString = linksToString +\",\" + links[currentID][k][\"target\"];\n }\n }\n spreadsheet.getSheetByName(types[0]).getRange(j+2,1+indexLastColumn).setValue(linksToString);\n }\n } \n \n /* Other types */\n for (var i = 1; i < types.length; i++) {\n spreadsheet.insertSheet(types[i]);\n for (var j = 0; j < annotations_type[types[i]].attributes.length; j++) { \n var attributeName = annotations_type[types[i]].attributes[j].name;\n spreadsheet.getSheetByName(types[i]).getRange(1,j+1).setValue(attributeName);\n for (var k = 0; k < annotations[types[i]].length; k++) { \n spreadsheet.getSheetByName(types[i]).getRange(k+2,1+j).setValue(annotations[types[i]][k][attributeName]);\n }\n }\n /* Saving of the links in the last column */\n var indexLastColumn = annotations_type[types[i]].attributes.length;\n spreadsheet.getSheetByName(types[i]).getRange(1,1+indexLastColumn).setValue(\"links\");\n for (var j = 0; j < annotations[types[i]].length; j++) { \n var currentID = annotations[types[i]][j][\"id\"];\n if(links[currentID] != undefined) {\n var linksToString = \"\";\n for (var k = 0; k < links[currentID].length; k++) {\n if(linksToString == \"\") {\n linksToString = links[currentID][k][\"target\"];\n }\n else {\n linksToString = linksToString +\",\" + links[currentID][k][\"target\"];\n }\n }\n spreadsheet.getSheetByName(types[i]).getRange(j+2,1+indexLastColumn).setValue(linksToString);\n }\n }\n }\n}",
"function setTixInformation(tixChecker, SheetNum, assignedVal, colNum){\n // Number of Rows in corresponding SHEET\n var data = SheetNum.getDataRange().getValues();\n var ticketColumn = getColIndexByName(\"Ticket Shortlink\", sheet);\n // For debug purposes\n //Logger.log(\"Getting Matches to: \" + tixChecker );\n //Logger.log(\"Other Sheet: \" + SheetNum.getName());\n //Logger.log(\"assignedVal: \" + assignedVal);\n //Logger.log(\"colNum: \" + colNum);\n \n for (var i = 1; i < data.length; i++){\n if (data[i][ticketColumn-1] == (tixChecker)){ \n Logger.log(\"Assigned Value: \" + assignedVal);\n SheetNum.getRange(i+1, colNum).setValue(assignedVal); \n Logger.log(\"SheetNum: \" + SheetNum);\n \n // Below is just setting the colors for the different assigned values\n if(assignedVal.equals(\"Resolved\")) {\n SheetNum.getRange(i+1,1,1, colNum + 2).setBackground(colorGrey);\n }\n else if (assignedVal.equals(\"New\")) SheetNum.getRange(i+1, 1,1,colNum +2).setBackground(colorWhite);\n else if (assignedVal.equals(\"Assigned\")) {\n SheetNum.getRange(i+1, 1,1,colNum+1).setBackground(colorWhite); \n SheetNum.getRange(i+1,colNum+1).setBackground(colorRed);\n }else SheetNum.getRange(i+1,colNum).setBackground(colorWhite);\n \n return;\n }\n }\n}",
"fetchEverything() {\n const datasheet = _spreadsheet.data.sheets[0] // we could ask the user as a parameter what sheet he wants\n\n for (let i = 0; i < datasheet.properties.gridProperties.rowCount - 1; i++) {\n try {\n const rowDataValues = datasheet.data[0].rowData[i + 1].values\n \n const mapKey = rowDataValues[0].formattedValue\n let mapValue\n try { mapValue = JSON.parse(rowDataValues[1].formattedValue) } catch (e) { mapValue = rowDataValues[1].formattedValue }\n\n _keyRowNumbers.push(mapKey)\n super.set(mapKey, mapValue)\n } catch(e) {}\n }\n }",
"function onEdit(e) {\n var sheet = SpreadsheetApp.getActiveSheet();\n // cell must have a value, be only one row, and be from the first sheet\n if( e.range.getValue() && (e.range.getNumRows() == 1) && sheet.getIndex() == 1) {\n //Logger.log( e.range.getValue() );\n var value = e.range.getValue(),\n spread_sheet_name = SpreadsheetApp.getActiveSpreadsheet().getName();\n e.range.setValue(value.toLowerCase());\n\n var url = 'http://library2.udayton.edu/api/getInventoryData/item_barcode.php?'\n + 'barcode=' + value;\n var result = UrlFetchApp.fetch(url); \n var json_data = JSON.parse(result.getContentText());\n \n //make sure we have data back ...\n if(json_data) {\n if (json_data.call_number_norm) {\n e.range.offset(0,1).setValue('=\\\"' + json_data.call_number_norm.toUpperCase() + '\\\"');\n }\n //escape all double quotes\n if (json_data.best_title) {\n e.range.offset(0,2).setValue('=\\\"' + json_data.best_title.replace(/\"/g, '\"\"') + '\\\"');\n }\n e.range.offset(0,3).setValue('=\\\"' + json_data.location_code + '\\\"');\n e.range.offset(0,4).setValue('=\\\"' + json_data.item_status_code + '\\\"');\n }\n \n if(json_data.due_gmt != null) {\n e.range.offset(0,5).setValue('=\\\"' + json_data.due_gmt.substring(0, json_data.due_gmt.length - 3) + '\\\"');\n }\n else {\n e.range.offset(0,5).setValue('=\\\"\\\"');\n }\n \n e.range.offset(0,6).setValue('=\\\"' + Utilities.formatDate(new Date(), \"GMT-4:00\", \"yyyy-MM-dd' 'HH:mm:ss\") + '\\\"');\n e.range.offset(0,7).setValue(e.range.getRow());\n e.range.offset(0,8).setValue(spread_sheet_name);\n \n } //end if\n} //end function onEdit()",
"function UpdateSettings(Settings){\n Logger.log(Settings); ///Log the received data on the console output \n var spreadSheet = SpreadsheetApp.openById(spreadSheetID); ///Open the spreadsheet\n var settingsSheet = spreadSheet.getSheetByName(\"Settings\"); ///Get the Settings sheet\n var settings = settingsSheet.getRange(3,1,settingsSheet.getLastRow(),1);\n var nextRow = settingsSheet.getLastRow() + 1; ///Get next row after the last row\n \n ///Add all other Header + Data pairs from the received Log JSON\n for each (var key in Object.keys(Settings)){\n var match = settings.createTextFinder(key).matchEntireCell(true).findNext(); ///lookup the alert limit row for each Log key\n if(match == null){ ///If settings row does not exists\n settingsSheet.getRange(nextRow, 1).setValue(key); ///Insert key in first column \n settingsSheet.getRange(nextRow, 2).setValue(Settings[key]); ///Insert value in second column\n nextRow++;\n } \n else\n {\n settingsSheet.getRange(match.getRow(), 2).setValue(Settings[key]); ///Update value in second column\n }\n }\n}",
"function writeBidChanges()\t{\n //open spreadsheet by url\n var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);\n // fetch the sheet for DC_PPC Bidding\n var sheet = spreadsheet.getSheetByName('KeywordsBids');\n \n //create a variable for today to time stamp when we ran report\n var now = new Date();\n var myDate = Utilities.formatDate(now, \"CST\", \"yyyyMMdd\");\n\t \n //write to sheet (append)\n for (var i = 0; i < bidChangesArray.length; i++) {\n sheet.appendRow(\n\t[myDate,\n\tbidChangesArray[i].CampaignName, \n\tbidChangesArray[i].AdGroupName,\n\tbidChangesArray[i].Text,\n\tbidChangesArray[i].MaxCpc,\n\tbidChangesArray[i].QualityScore,\n\tbidChangesArray[i].TopOfPageCpc,\n\tbidChangesArray[i].Impressions,\n\tbidChangesArray[i].Clicks,\n\tbidChangesArray[i].AveragePosition,\n\tbidChangesArray[i].AverageCpc,\n\tbidChangesArray[i].NewCpc,\n\tbidChangesArray[i].BidType]\n\t);\n }\n}",
"function updateSheetStatus(newStatus){\n // - clear sheet information\n _CURRENT_SHEET_STATUS.clear();\n \n // - append a status to the sheet\n _CURRENT_SHEET_STATUS.appendRow([\"STATUS\", newStatus]);\n _CURRENT_SHEET_STATUS.appendRow([\"LAST_START_TIME\", _CURRENT_START_TIME]);\n _CURRENT_SHEET_STATUS.appendRow([\"NEXT_START_TIME\", _CURRENT_END_TIME]);\n \n // - if done, hide the sheet\n if (newStatus == \"DONE\") {\n _CURRENT_SHEET_STATUS.hideSheet()\n \n // - else, show the sheet\n } else {\n _CURRENT_SHEET_STATUS.showSheet()\n \n }\n}",
"function scanSheet(upload) {\n upload = (typeof upload == 'undefined' ? true : upload);\n\n var statusCol = 0;\n var epicCol = statusCol + 3;\n var titleCol = statusCol + 5;\n var hoursCol = statusCol + 12;\n\n var startRow = 10;\n\n var hours = [];\n\n var startTime = new Date();\n Logger.log(\"Started scanning sheet for Harvest \" + (upload ? \"uploads\" : \"hour updates\") + \" at:\" + startTime);\n var error = checkControlValues();\n if (error != \"\") {\n Browser.msgBox(\"ERROR:Values in the Controls sheet have not been set. Please fix the following error:\\n \" + error);\n return;\n }\n\n var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(ScriptProperties.getProperty(\"sheetName\"));\n\n var successCount = 0;\n var partialCount = 0;\n var rows = sheet.getDataRange().getValues();\n\n for (var i = startRow ; i < rows.length ; i++) {\n var currentRow = rows[i];\n\n // Only process if there is a card title and an epic.\n if (currentRow[titleCol].trim() != \"\" && currentRow[epicCol] != \"\") {\n r = i + 1;\n\n currentTime = new Date();\n\n Logger.log(\"Row \" + r + \":\" + currentTime);\n\n if (currentTime.valueOf() - startTime.valueOf() >= 330000) { // 5.5 minutes - scripts time out at 6 minutes\n Browser.msgBox(\"NOTICE: Script was about to time out so it has been terminated gracefully . \" + (!upload ? successCount + \" tasks were uploaded successfully.\" : \"\"));\n return;\n }\n\n if (upload) {\n var status = currentRow[statusCol];\n\n if (status == \".\") { // Row already processed.\n Logger.log(\"Ignoring row \" + r + \". Status column indicates already imported.\");\n } else if (status == \"x\") {\n Browser.msgBox(\"ERROR: Row \" + r + \" indicates that it was partially created the last time this script was run. Ask the developer about what may have caused this.\");\n return;\n } else if (status == \"\") { // Status cell empty. Import row.\n\n var statusCell = sheet.getRange(r, statusCol + 1, 1, 1);\n\n // Indicate that this row has begun importing.\n statusCell.setValue(\"x\");\n\n partialCount++;\n\n createProjectTask(currentRow[titleCol]);\n\n // Indicate that this row has been exported.\n statusCell.setValue(\".\");\n\n SpreadsheetApp.flush();\n partialCount --;\n successCount ++;\n }\n } else {\n if (currentRow[hoursCol] > 0) {\n hours.push([currentRow[titleCol], currentRow[hoursCol]]);\n } else {\n Logger.log(\"Ignoring row \" + r + \". No hours found.\");\n }\n }\n }\n }\n\n if (!upload) {\n\n return hours;\n } else {\n Browser.msgBox( successCount + \" Harvest tasks were uploaded successfully. Adding hours...\");\n updateProjectTaskHours();\n return;\n }\n}",
"async function getInfoAboutSpreadSheet() {\n try {\n return googleSheetsDocument.getInfoAsync();\n } catch (error) {\n console.log(\"Get information error\", error);\n }\n}",
"function sendEmailToPerson() {\n dataInit();\n callSheetConfig();\n var tmp = []\n var today = new Date();\n for (var i = 1; i < data1.length; i++){\n for (var j=1; j < data.length; j++){\n var slicesstring = data[j][4].slice(-7,-5);\n var stringYear = data[j][4].slice(-4);\n if(data1[i][2] == data[j][2] && (today.getMonth()+1) == slicesstring && today.getFullYear() == stringYear){\n tmp.push([data[0][3] + \": \"\n + data[j][3] + \"\\t\" + data[0][4] + \": \" + data[j][4] + \"\\t\" + data[0][5] + \": \" + data[j][5] + '\\n']); \n }\n }\n if (tmp.length === 0){\n var emailAddress = data1[i][2]\n var message = dataconfig[1][1] + '\\n' + 'No day off'\n var subject = dataconfig[1][0];\n MailApp.sendEmail(emailAddress, subject, message)\n tmp =[];\n }\n else{\n var emailAddress = data1[i][2]\n var message = dataconfig[1][1] + '\\n' + tmp\n var subject = dataconfig[1][0];\n MailApp.sendEmail(emailAddress, subject, message)\n tmp =[];\n }\n }\n}",
"function fcnCopyStandingsSheets(ss, shtConfig, RspnWeekNum, AllSheets){\n\n var shtIDs = shtConfig.getRange(17,7,20,1).getValues();\n var ssLgStdIDEn = shtIDs[4][0];\n var ssLgStdIDFr = shtIDs[5][0];\n \n // Open League Player Standings Spreadsheet\n var ssLgEn = SpreadsheetApp.openById(shtIDs[4][0]);\n var ssLgFr = SpreadsheetApp.openById(shtIDs[5][0]);\n \n // Match Report Form URL\n var FormUrlEN = shtConfig.getRange(19,2).getValue();\n var FormUrlFR = shtConfig.getRange(22,2).getValue();\n \n // League Name\n var Location = shtConfig.getRange(3,9).getValue();\n var LeagueTypeEN = shtConfig.getRange(13,2).getValue();\n var LeagueNameEN = Location + ' ' + LeagueTypeEN;\n var LeagueTypeFR = shtConfig.getRange(14,2).getValue();\n var LeagueNameFR = LeagueTypeFR + ' ' + Location;\n \n // Sheet Initialization\n var rngSheetInitializedEN = shtConfig.getRange(34,5);\n var SheetInitializedEN = rngSheetInitializedEN.getValue();\n var rngSheetInitializedFR = shtConfig.getRange(35,5);\n var SheetInitializedFR = rngSheetInitializedFR.getValue();\n \n // Number of Players\n var NbPlayers = shtConfig.getRange(11,2).getValue();\n var LeagueWeekLimit = shtConfig.getRange(83, 2).getValue();\n var WeekSheet = RspnWeekNum + 1;\n \n // Function Variables\n var ssMstrSht;\n var ssMstrShtStartRow;\n var ssMstrShtMaxRows;\n var ssMstrShtNbCol;\n var ssMstrShtData;\n var ssMstrStartDate;\n var ssMstrEndDate;\n var NumValues;\n var ColValues;\n var SheetName;\n \n var ssLgShtEn;\n var ssLgShtFr;\n var WeekGame;\n \n // Loops through tabs 0-9 (Standings, Cumulative Results, Week 1-8)\n for (var sht = 0; sht <= 9; sht++){\n ssMstrSht = ss.getSheets()[sht];\n SheetName = ssMstrSht.getSheetName();\n \n if(sht == 0 || sht == 1 || sht == WeekSheet || AllSheets == 1){\n ssMstrShtMaxRows = ssMstrSht.getMaxRows();\n \n // Get Sheets\n ssLgShtEn = ssLgEn.getSheets()[sht];\n ssLgShtFr = ssLgFr.getSheets()[sht];\n \n // If sheet is Standings\n if (sht == 0) {\n ssMstrShtStartRow = 6;\n ssMstrShtNbCol = 7;\n }\n \n // If sheet is Cumulative Results or Week Results\n if (sht == 1) {\n ssMstrShtStartRow = 5;\n ssMstrShtNbCol = 13;\n }\n \n // If sheet is Cumulative Results or Week Results\n if (sht > 1 && sht <= 9) {\n ssMstrShtStartRow = 5;\n ssMstrShtNbCol = 11;\n }\n \n // Set the number of values to fetch\n NumValues = ssMstrShtMaxRows - ssMstrShtStartRow + 1;\n \n // Get Range and Data from Master\n ssMstrShtData = ssMstrSht.getRange(ssMstrShtStartRow,1,NumValues,ssMstrShtNbCol).getValues();\n \n // And copy to Standings\n ssLgShtEn.getRange(ssMstrShtStartRow,1,NumValues,ssMstrShtNbCol).setValues(ssMstrShtData);\n ssLgShtFr.getRange(ssMstrShtStartRow,1,NumValues,ssMstrShtNbCol).setValues(ssMstrShtData);\n \n // Hide Unused Rows\n if(NbPlayers > 0){\n ssLgShtEn.hideRows(ssMstrShtStartRow, ssMstrShtMaxRows - ssMstrShtStartRow + 1);\n ssLgShtEn.showRows(ssMstrShtStartRow, NbPlayers);\n ssLgShtFr.hideRows(ssMstrShtStartRow, ssMstrShtMaxRows - ssMstrShtStartRow + 1);\n ssLgShtFr.showRows(ssMstrShtStartRow, NbPlayers);\n }\n \n // Week Sheet \n if (sht == WeekSheet){\n Logger.log('Week %s Sheet Updated',sht-1);\n ssMstrStartDate = ssMstrSht.getRange(3,2).getValue();\n ssMstrEndDate = ssMstrSht.getRange(4,2).getValue();\n ssLgShtEn.getRange(3,2).setValue('Start: ' + ssMstrStartDate);\n ssLgShtEn.getRange(4,2).setValue('End: ' + ssMstrEndDate);\n ssLgShtFr.getRange(3,2).setValue('Début: ' + ssMstrStartDate);\n ssLgShtFr.getRange(4,2).setValue('Fin: ' + ssMstrEndDate);\n }\n \n // If the current sheet is greater than League Week Limit, hide sheet\n if(sht > LeagueWeekLimit + 1){\n ssLgShtEn.hideSheet();\n ssLgShtFr.hideSheet();\n }\n }\n \n // If Sheet Titles are not initialized, initialize them\n if(SheetInitializedEN != 1){\n // Standings Sheet\n if (sht == 0){\n Logger.log('Standings Sheet Updated');\n // Update League Name\n ssLgShtEn.getRange(4,2).setValue(LeagueNameEN + ' Standings')\n ssLgShtFr.getRange(4,2).setValue('Classement ' + LeagueNameFR)\n // Update Form Link\n ssLgShtEn.getRange(2,5).setValue('=HYPERLINK(\"' + FormUrlEN + '\",\"Send Match Results\")'); \n ssLgShtFr.getRange(2,5).setValue('=HYPERLINK(\"' + FormUrlFR + '\",\"Envoyer Résultats de Match\")'); \n }\n \n // Cumulative Results Sheet\n if (sht == 1){\n Logger.log('Cumulative Results Sheet Updated');\n WeekGame = ssMstrSht.getRange(2,3,3,1).getValues();\n ssLgShtEn.getRange(2,3,3,1).setValues(WeekGame);\n ssLgShtFr.getRange(2,3,3,1).setValues(WeekGame);\n \n // Loop through Values in columns K and M to translate each value\n // Column K (11)\n ColValues = ssLgShtFr.getRange(ssMstrShtStartRow, 11, NumValues, 1).getValues();\n for (var row = 0 ; row < NumValues; row++){\n if (ColValues[row][0] == 'Active') ColValues[row][0] = 'Actif';\n if (ColValues[row][0] == 'Eliminated') ColValues[row][0] = 'Éliminé';\n }\n ssLgShtFr.getRange(ssMstrShtStartRow, 11, NumValues, 1).setValues(ColValues);\n \n // Loop through Values in columns K and M to translate each value\n // Column M (13)\n ColValues = ssLgShtFr.getRange(ssMstrShtStartRow, 13, NumValues, 1).getValues();\n for (var row = 0 ; row < NumValues; row++){\n if (ColValues[row][0] == 'Yes') ColValues[row][0] = 'Oui';\n if (ColValues[row][0] == 'No') ColValues[row][0] = 'Non';\n }\n ssLgShtFr.getRange(ssMstrShtStartRow, 13, NumValues, 1).setValues(ColValues);\n }\n \n // Set Initialized Value to Config Sheet to skip this part\n if(sht == 9) {\n rngSheetInitializedEN.setValue(1);\n rngSheetInitializedFR.setValue(1);\n }\n }\n }\n}",
"function getVerificationStatus(idNumber){\n // Get data of Service Org spreadsheet\n \n // ADD UNIQUE SPREADSHEET ID OF VERIFICATION DATA DOCUMENT.\n var serviceOrgSheet = SpreadsheetApp.openById('1o6cdcAuP9aZ5d-Ducg2b-1prFAnqx5G3qNhahUT95wc').getActiveSheet();\n \n var verificationData = getRowsData(serviceOrgSheet);\n// Logger.log(verificationData);\n // Use ID number to find instance of that ID number \n // Get range of the column in which ID numbers are located\n for (var i = 0; i < verificationData.length; i++){\n var index = verificationData[i].serviceIdNumber;\n var verificationStatus = sheet.getRange((index), 19, 1);\n if (verificationData[i].emailSent == ''){\n Logger.log(verificationData[i].verification);\n \n var emailSent = serviceOrgSheet.getRange((i+2), 4, 1);\n var emailBody;\n var emailSubject;\n \n if (verificationData[i].verification == \"Yes\"){\n // Mark the approval request sheet with \"Verified\" or \"Denied\"\n \n verificationStatus.setValue('Verified'); \n emailBody = '<head><body>'\n + '<img style=\"height:100px;width:100px;\" src=\"http://salesian.schoolwires.net/cms/lib03/CA02001206/Centricity/Domain/2/SHS%20Seal%20New%20600x600.jpg\"><br/>'\n + '<p>' + approvalRequest[index].name + ',</p>'\n + '<p>' + approvalRequest[index].contactPerson + ' has verified the details of your Christian Service Hour submission.</p>'\n + '<p>Here are the details of your submission:</p>'\n + '<ul>'\n + '<li><b>Service ID Number: ' + verificationData[i].serviceIdNumber + '</b></li>'\n + '<li>Date of Service: ' + approvalRequest[index].dateOfService + '</li>'\n + '<li>Hours of Service: ' + approvalRequest[index].hoursOfService + '</li>'\n + '<li>Service Organization: ' + approvalRequest[index].serviceOrganization + '</li>'\n + '<li>Contact Name: ' + approvalRequest[index].contactPerson + '</li>'\n + '<li>Description of Service: ' + approvalRequest[index].description + '</li></ul><br>' \n + '<p>Your Theology teacher will review your Christian Service Hour submission for approval shortly.</p>'\n + '</body></html>';\n emailSubject = approvalRequest[index].contactPerson + ' has verified your Christian Service Hour submission.';\n \n MailApp.sendEmail({\n to: approvalRequest[idNumber].username,\n subject: emailSubject,\n htmlBody: emailBody,\n });\n }\n else {\n verificationStatus.setValue('Denied');\n emailBody = '<head><body>'\n + '<img style=\"height:100px;width:100px;\" src=\"http://salesian.schoolwires.net/cms/lib03/CA02001206/Centricity/Domain/2/SHS%20Seal%20New%20600x600.jpg\"><br/>'\n + '<p>' + approvalRequest[index].name + ',</p>'\n + '<p>Your recent Christian Service Hour submission has been denied by your service organization.</p>'\n + '<p>Here are the details of your submission:</p>'\n + '<ul>'\n + '<li><b>Service ID Number: ' + verificationData[i].serviceIdNumber + '</b></li>'\n + '<li>Date of Service: ' + approvalRequest[index].dateOfService + '</li>'\n + '<li>Hours of Service: ' + approvalRequest[index].hoursOfService + '</li>'\n + '<li>Service Organization: ' + approvalRequest[index].serviceOrganization + '</li>'\n + '<li>Contact Name: ' + approvalRequest[index].contactPerson + '</li>'\n + '<li>Description of Service: ' + approvalRequest[index].description + '</li></ul><br>' \n + '<p>Please contact your service organization for further details and then resubmit a new Christian Service Hour request.</p>'\n + '</body></html>';\n emailSubject = 'Your Christian Service Hour submission has been denied.';\n \n MailApp.sendEmail({\n to: approvalRequest[idNumber].username,\n subject: emailSubject,\n htmlBody: emailBody,\n });\n }\n\n emailSent.setValue('Sent');\n \n }\n else {\n Logger.log(\"Try Again.\");\n if (verificationData[i].verification == \"Yes\"){\n // Mark the approval request sheet with \"Verified\" or \"Denied\"\n \n verificationStatus.setValue('Verified'); \n }\n }\n }\n}",
"function insertMember(name, index)\n{\n //Contact Sheet\n contact_sheet.insertRowsBefore(2 + (index * 3), 3);\n var color_cells = contact_sheet.getRange(4 + (index * 3), 1, 1, 7);\n color_cells.setBackground(\"#E0E0E0\");\n var cell = contact_sheet.getRange(2 + (index * 3), 1);\n cell.setValue(name);\n \n //Advancement Sheet\n advancement_sheet.insertRowsBefore(6 + (index * 2), 2)\n var color_cells = advancement_sheet.getRange(7 + (index * 2), 1, 1, advancement_sheet.getMaxColumns());\n color_cells.setBackground(\"#E0E0E0\");\n color_cells = advancement_sheet.getRange(6 + (index * 2), 2, 1, 5);\n color_cells.clearFormat();\n color_cells = advancement_sheet.getRange(6 + (index * 2), 8, 1, 12);\n color_cells.clearFormat();\n color_cells = advancement_sheet.getRange(6 + (index * 2), 21, 1, 13);\n color_cells.clearFormat();\n var cell = advancement_sheet.getRange(6 + (index * 2), 1);\n cell.setValue(name);\n \n //Attendance Sheet\n attendance_sheet.insertRowsBefore(4 + (index * 2), 2);\n var color_cells = attendance_sheet.getRange(5 + (index * 2), 1, 1, attendance_sheet.getMaxColumns());\n color_cells.setBackground(\"#E0E0E0\");\n color_cells = attendance_sheet.getRange(4 + (index * 2), 2, 1, attendance_sheet.getMaxColumns());\n color_cells.clearFormat();\n var cell = attendance_sheet.getRange(4 + (index * 2), 1);\n cell.setValue(name);\n \n //Service Sheet\n service_sheet.insertRowsBefore(6 + (index * 2), 2);\n var color_cells = service_sheet.getRange(7 + (index * 2), 1, 1, service_sheet.getMaxColumns());\n color_cells.setBackground(\"#E0E0E0\");\n color_cells = service_sheet.getRange(6 + (index * 2), 2, 1, service_sheet.getMaxColumns() - 2);\n color_cells.clearFormat();\n var cell = service_sheet.getRange(6 + (index * 2), 1);\n cell.setValue(name);\n \n //Dues Sheet\n dues_sheet.insertRowsBefore(5 + (index * 2), 2);\n var color_cells = dues_sheet.getRange(6 + (index * 2), 1, 1, dues_sheet.getMaxColumns());\n color_cells.setBackground(\"#E0E0E0\");\n color_cells = dues_sheet.getRange(5 + (index * 2), 2, 1, dues_sheet.getMaxColumns());\n color_cells.clearFormat();\n var cell = dues_sheet.getRange(5 + (index * 2), 1);\n cell.setValue(name);\n}",
"function ProcessExcel(data) {\n //Read the Excel File data.\n var workbook = XLSX.read(data, {\n type: 'binary'\n });\n\n //Fetch the name of First Sheet.\n var firstSheet = workbook.SheetNames[0];\n //Read all rows from First Sheet into an JSON array.\n \tvar excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);\n //Add the data rows from Excel file.\n for (var i = 0; i < excelRows.length; i++) {\n //first row needs to be fill out with words item and definition, otherwise this will not work\n currentDeck.addCard(excelRows[i].item, excelRows[i].definition);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives the permutation of all possible pathMatch()es of a given path. The array is in longesttoshortest order. Handy for indexing. | function permutePath(path) {
if (path === '/') {
return ['/'];
}
if (path.lastIndexOf('/') === path.length-1) {
path = path.substr(0,path.length-1);
}
var permutations = [path];
while (path.length > 1) {
var lindex = path.lastIndexOf('/');
if (lindex === 0) {
break;
}
path = path.substr(0,lindex);
permutations.push(path);
}
permutations.push('/');
return permutations;
} | [
"function getPermutations(array) { //not recursive but hey\n\tif (!array.length) return [];\n\tlet results = [[array.shift()]];\n\twhile (array.length) {\n\t\tlet currNum = array.shift();\n\t\tlet tempResults = [];\n\t\tfor (let i = 0; i < results.length; i++) {\n\t\tlet resultsCopy = results.slice();\n\t\t\tfor (let j = 0; j <= results[i].length; j++) {\n\t\t\t\tlet resultsCopy = results[i].slice();\n\t\t\t\tresultsCopy.splice(j, 0, currNum);\n\t\t\t\ttempResults.push(resultsCopy);\n\t\t\t}\n\t\t}\n\t\tresults = tempResults.slice();\n\t}\n\treturn results;\n}",
"function permutations(inputStr, sharedCache = {}) {\n if (inputStr.length < 2) {\n return [inputStr];\n }\n if (sharedCache[inputStr]) return sharedCache[inputStr];\n\n const allPermutations = [];\n\n for (let i = 0; i < inputStr.length; i++) {\n const char = inputStr[i];\n\n // skip the char if its duplicated\n if (i > 0 && inputStr[i] === inputStr[i - 1]) continue;\n\n let remainingChars = \"\";\n for (let j = 0; j < inputStr.length; j++) {\n if (j !== i) remainingChars += inputStr[j];\n }\n\n // get all permutations of the remaining items\n const remainingPermutations = permutations(remainingChars, sharedCache);\n\n // add the char to the beginning of each permutation\n for (let j = 0; j < remainingPermutations.length; j++) {\n allPermutations.push(char + remainingPermutations[j]);\n }\n }\n sharedCache[inputStr] = allPermutations;\n return allPermutations;\n}",
"function permutationEquation(p) {\n // 정답을 담을 변수 선언\n const answer = [];\n // 주어진 배열을 순회하면서\n for (let i = 0; i < p.length; i++) {\n // x은 1부터 n까지이기에\n // 일단 x값에 해당하는 index를 찾는다.\n const xIndex = p.findIndex(item => item === i + 1);\n // x값에 해당하는 순서(1부터 세기에 index+1)와 같은 index를 찾는다.\n const matchSequence = p.findIndex(item => item === xIndex + 1) + 1;\n // 정답에 넣어준다.\n answer.push(matchSequence);\n }\n // 정답 출력\n return answer;\n}",
"resolveAll(items, pathArray) {\n this._subgraph_by_id = {};\n this._subgraph = [];\n const finals = this.resolve(items, pathArray, true);\n return [ finals, this._subgraph ];\n }",
"function possibileTrees(str){\n let possibilities=[]\n\n function recursive(str){\n for(let i=0;i<=str.length;i++){\n let sliced = str.slice(0,str.length-i) + str.slice((str.length-i+1), str.length)\n if(!possibilities.includes(sliced)&&sliced) possibilities.push(sliced)\n }\n }\n recursive(str)\n //This is recursive because it continuously increases the length of the possibilities each\n //time the function is run, until it reaches the end.\n for(let i=0;i<possibilities.length;i++){\n recursive(possibilities[i])\n }\n return possibilities\n }",
"function permutations(cmaps, used, l) {\r\n\t\t\t\tif (cmaps.length == 0 || l >= mat.length) {\r\n\t\t\t\t\treturn cmaps;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvar rvmaps = [];\r\n\t\t\t\tfor(var r = 0; r < mat[l].length; ++r) {\r\n\t\t\t\t\tif (!used[r] && mat[l][r].length > 0) {\r\n\t\t\t\t\t\tused[r] = true;\r\n\t\t\t\t\t\tvar parms = permutations(mergeMappings(cmaps, mat[l][r]), used, l + 1);\r\n\t\t\t\t\t\trvmaps = rvmaps.concat(parms);\r\n\t\t\t\t\t\tused[r] = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn rvmaps;\r\n\t\t\t}",
"function getMatchArray(grid){\n let length = grid.length;\n\n\n \n // for horizontal and vertical match cases\n let horArr = [];\n let verArr = [];\n for(let i=0; i<length; i++){\n let horTemp = [];\n let verTemp = [];\n for(let j=0; j<length; j++){\n horTemp.push([i, j]);\n verTemp.push([j, i]);\n }\n horArr.push(horTemp);\n verArr.push(verTemp);\n }\n // for horizontal and vertical match cases\n\n\n \n // for diagonal match cases\n let sum = length - 1;\n let diagArr = [];\n let diag1Temp = [];\n let diag2Temp = [];\n for(let i=0; i<length; i++){\n for(let j=0; j<length; j++){\n if(i===j) diag1Temp.push([i,j]);\n if(i+j === sum) diag2Temp.push([i,j]);\n }\n }\n diagArr.push(diag1Temp, diag2Temp);\n // for diagonal match cases\n\n\n\n return [...horArr, ...verArr, ...diagArr];\n}",
"function MatrixPath(strArr) { // 0 = up, 1 = down, 2 = left, 3 = right\n let count = [], visited = [];\n for (var i=0; i<strArr.length; i++) {\n for (var j=0; j<strArr[i].length; j++) {\n var row = strArr[i];\n if ((row[j - 1] === \"1\" || row[j + 1] === \"1\") && row[j] === \"0\") {\n strArr[i] = row.substr(0, j) + \"2\" + row.substr(j + 1);\n }\n }\n }\n findPath(strArr, 0, 0, -1, count, visited);\n if (count.length === 0) {\n return \"not possible\";\n } else if (count.indexOf(-1) !== -1) {\n return \"true\";\n } else {\n return count.length;\n }\n}",
"findPaths(fromNavNode, toNavNode) {\r\n\t\tlet walkingPaths = [[fromNavNode]];\r\n\t\tlet rtn = [];\r\n\r\n\t\twhile( walkingPaths.length > 0 ) {\r\n\t\t\tlet curPath = walkingPaths.pop();\r\n\t\t\tlet curNode = curPath[curPath.length-1].node;\r\n\t\t\tlet noRoute = false;\r\n\t\t\twhile( !noRoute && curNode != toNavNode ) {\r\n\t\t\t\tlet connections = curNode.connections.filter( connection => !curPath.includes(connection) );\r\n\t\t\t\tif ( connections.length > 0 ) {\r\n\t\t\t\t\tfor( let i = 1; i < connections.length; i++ ) {\r\n\t\t\t\t\t\tlet newPath = curPath.slice();\r\n\t\t\t\t\t\tnewPath.push(connections[i]);\r\n\t\t\t\t\t\twalkingPaths.push(newPath);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcurPath.push(connections[0]);\r\n\t\t\t\t\tcurNode = connections[0].node;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tnoRoute = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif ( !noRoute ) {\r\n\t\t\t\trtn.push(curPath);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn rtn;\r\n\t}",
"function choosePattern() {\n patternSet = new Set([]);\n while (patternSet.size < 4) {\n var patternItem = Math.floor(Math.random() * maxItems + 1);\n patternSet.add(patternItem);\n }\n pattern = Array.from(patternSet);\n }",
"function reduce_path(full_path){\n let partial_path = [];\n if(full_path.length === 11){\n partial_path = full_path.slice(0,9); \n }else{\n partial_path = full_path.slice(0,10);\n };\n return partial_path;\n}",
"function pathSolver(path) {\n return path;\n}",
"function sortPaths(paths){\n\n var output = [];\n //add the first path untouched\n paths[0].isProcessed = true;\n output.push(paths[0]);\n\n var currentPath = paths[0];\n //process all unprocessed paths\n \n while(paths.filter(p=>p.isProcessed).length < paths.length)\n {\n var positionAfterDraw = currentPath.mustBeReversed ? currentPath.startPoint : currentPath.endPoint;\n\n //calculate the distance from current position to start and end points of all unprocessed paths\n var unprocessed = paths.filter(p=> !p.isProcessed);\n unprocessed.forEach(p=>{\n p.startPointDistance = distanceBetween(positionAfterDraw, p.startPoint);\n p.endPointDistance = distanceBetween(positionAfterDraw, p.endPoint);\n });\n\n var pathWithClosestStartPoint = unprocessed.sort((a,b)=> a.startPointDistance > b.startPointDistance)[0];\n var pathWithClosestEndPoint = unprocessed.sort((a,b)=> a.endPointDistance > b.endPointDistance)[0];\n\n if(pathWithClosestEndPoint.endPointDistance < pathWithClosestStartPoint.startPointDistance)\n {\n currentPath = pathWithClosestEndPoint;\n currentPath.mustBeReversed = true;\n }\n else\n {\n currentPath = pathWithClosestStartPoint;\n }\n\n currentPath.isProcessed = true;\n output.push(currentPath);\n\n }\n\n return output;\n}",
"function findSubPath (path) {\n var path_length = path.length;\n var subPathList = [];\n var i = 0;\n while (i < path.length - 2) {\n subPathList.push(path.slice(i, i + 3));\n i = i + 2;\n };\n return subPathList;\n}",
"equalCommands (pathArray) {\r\n var i, il, equalCommands;\r\n\r\n pathArray = new PathArray(pathArray);\r\n\r\n equalCommands = this.length === pathArray.length;\r\n for (i = 0, il = this.length; equalCommands && i < il; i++) {\r\n equalCommands = this[i][0] === pathArray[i][0];\r\n }\r\n\r\n return equalCommands\r\n }",
"function permutations(iterable, r) {\n var pool, n, x, indices, cycles, poolgetter, cleanExit, _iteratorNormalCompletion9, _didIteratorError9, _iteratorError9, _iterator9, _step10, i, j, _ref2, p, q;\n\n return _regenerator[\"default\"].wrap(function permutations$(_context15) {\n while (1) {\n switch (_context15.prev = _context15.next) {\n case 0:\n pool = Array.from(iterable);\n n = pool.length;\n x = r === undefined ? n : r;\n\n if (!(x > n)) {\n _context15.next = 5;\n break;\n }\n\n return _context15.abrupt(\"return\");\n\n case 5:\n indices = Array.from((0, _builtins.range)(n));\n cycles = Array.from((0, _builtins.range)(n, n - x, -1));\n\n poolgetter = function poolgetter(i) {\n return pool[i];\n };\n\n _context15.next = 10;\n return indices.slice(0, x).map(poolgetter);\n\n case 10:\n if (!(n > 0)) {\n _context15.next = 54;\n break;\n }\n\n cleanExit = true;\n _iteratorNormalCompletion9 = true;\n _didIteratorError9 = false;\n _iteratorError9 = undefined;\n _context15.prev = 15;\n _iterator9 = (0, _builtins.range)(x - 1, -1, -1)[Symbol.iterator]();\n\n case 17:\n if (_iteratorNormalCompletion9 = (_step10 = _iterator9.next()).done) {\n _context15.next = 36;\n break;\n }\n\n i = _step10.value;\n cycles[i] -= 1;\n\n if (!(cycles[i] === 0)) {\n _context15.next = 25;\n break;\n }\n\n indices = indices.slice(0, i).concat(indices.slice(i + 1)).concat(indices.slice(i, i + 1));\n cycles[i] = n - i;\n _context15.next = 33;\n break;\n\n case 25:\n j = cycles[i];\n _ref2 = [indices[indices.length - j], indices[i]], p = _ref2[0], q = _ref2[1];\n indices[i] = p;\n indices[indices.length - j] = q;\n _context15.next = 31;\n return indices.slice(0, x).map(poolgetter);\n\n case 31:\n cleanExit = false;\n return _context15.abrupt(\"break\", 36);\n\n case 33:\n _iteratorNormalCompletion9 = true;\n _context15.next = 17;\n break;\n\n case 36:\n _context15.next = 42;\n break;\n\n case 38:\n _context15.prev = 38;\n _context15.t0 = _context15[\"catch\"](15);\n _didIteratorError9 = true;\n _iteratorError9 = _context15.t0;\n\n case 42:\n _context15.prev = 42;\n _context15.prev = 43;\n\n if (!_iteratorNormalCompletion9 && _iterator9[\"return\"] != null) {\n _iterator9[\"return\"]();\n }\n\n case 45:\n _context15.prev = 45;\n\n if (!_didIteratorError9) {\n _context15.next = 48;\n break;\n }\n\n throw _iteratorError9;\n\n case 48:\n return _context15.finish(45);\n\n case 49:\n return _context15.finish(42);\n\n case 50:\n if (!cleanExit) {\n _context15.next = 52;\n break;\n }\n\n return _context15.abrupt(\"return\");\n\n case 52:\n _context15.next = 10;\n break;\n\n case 54:\n case \"end\":\n return _context15.stop();\n }\n }\n }, _marked14, null, [[15, 38, 42, 50], [43,, 45, 49]]);\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 }",
"function rockPaperPermutation(roundCount) {\n var results = [];\n var options = ['r','p','s'];\n if (roundCount) {\n var recurse = function(combo) {\n if (combo.length === roundCount) {\n results.push(combo);\n return;\n }\n for (var i = 0; i < options.length; i++) {\n recurse(combo + options[i]);\n }\n }\n recurse('');\n }\n return results;\n}",
"function patternMap(f,a) {\n var result = [], i; // Create a new Array\n for (i = 0; i < a.length; i++)\n// result = result.concat(down(a[i],i,a));\n result = result.concat(f(a[i],i,a));\n return result;\n}",
"getSubAnagrams(letters) {\n if(typeof letters !== 'string') {\n throw(`Expected string letters, received ${typeof letters}`);\n }\n\n if(letters.length < PERMS_MIN_LEN) {\n throw(`getSubAnagrams expects at least ${PERMS_MIN_LEN} letters`);\n }\n\n return permutations(letters, trie, {\n type: 'sub-anagram',\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return 0 if there is a match of different positions of mtchString, 1 otherwise. | function match(item, mtchString) {
const arr = [];
arr.push(`${mtchString} `);
arr.push(` ${mtchString} `);
arr.push(` ${mtchString}.`);
arr.push(` ${mtchString}-`);
arr.push(`${mtchString}- `);
arr.push(`-${mtchString} `);
arr.push(`-${mtchString}`);
arr.push(`-${mtchString}.`);
arr.push(`${mtchString}:`);
arr.push(` ${mtchString}:`);
for(let i = 0; i < arr.length; i++) {
if(item.indexOf(arr[i]) > -1) return 0;
}
return -1;
} | [
"function naiveString(str1,str2){\n var count = 0;\n for(var i = 0;i <str1.length;i ++){\n for(var j = 0;j <str2.length;j ++){\n if(str1[i + j] != str2[j]){\n break;\n }\n if(j === str2.length - 1){\n //console.log(str2.length );\n console.log(\"found one\");\n count ++;\n }\n }\n }\n return count;\n}",
"function GetMatches(targetPattern, dnaString, maxMisMatches){\n\n\tvar targetKmerLength = targetPattern.length; //casting for correct behavior\n\t\n\t//get all Kmers\n\tvar loopLength = dnaString.length - targetKmerLength + 1;//do loop length calculatiion here as it is faster then recalculating for each loop itteration\n\tvar matchedIndexes = ''; \n\tfor (var i = 0; i < loopLength; i++) {\n\t\tvar upperBound = targetKmerLength+i;\n\t\tvar tempKmer = dnaString.substring(i,upperBound).toString();\n\t\tif(matchesWithInMargin(tempKmer, targetPattern, maxMisMatches))\n\t\t\t//console.log('match at index: '+ i +' ');\n\t\t\tmatchedIndexes += i +' ';\n\t};\n\t//console.log('Done');\n\treturn matchedIndexes;\n}",
"function characterMatch(submitted_string, template_string) {\r\n var j = 0,\r\n consecutive_match = false,\r\n num_consec_matches = 0,\r\n submitted_character, template_character;\r\n \r\n // iterate through submitted_string\r\n for(var i = 0; i < submitted_string.length; i++) {\r\n submitted_character = submitted_string.charAt(i);\r\n // do not compare blank characters\r\n if (!isBlank(submitted_character)) {\r\n var character_match = false;\r\n // keep iterating through template_string until match is found or end of string\r\n while (j < template_string.length && !character_match) {\r\n template_character = template_string.charAt(j);\r\n // do not compare blank characters\r\n if (!isBlank(template_character)) {\r\n character_match = (template_character == submitted_character);\r\n console.log(character_match + \" \" + template_character + \" \" + submitted_character);\r\n j++;\r\n \r\n // add to num consec if already consecutive\r\n if (consecutive_match) {\r\n if (character_match) {\r\n num_consec_matches++;\r\n } else {\r\n consecutive_match = false;\r\n }\r\n }\r\n // start tracking consecutive_match if character matches\r\n else if (character_match) {\r\n consecutive_match = true;\r\n }\r\n } else {\r\n j++;\r\n }\r\n }\r\n }\r\n }\r\n \r\n // match, but too few consecutive matches\r\n if (character_match && num_consec_matches / submitted_string.length < CONSEC_PERCENT) {\r\n console.log(\"too few consecutive matches\");\r\n return false;\r\n }\r\n // match\r\n else if (character_match) {\r\n console.log(\"characters matched\");\r\n return true;\r\n }\r\n // no match\r\n else {\r\n console.log(\"characters not matched\");\r\n return false;\r\n }\r\n}",
"function FindMotif(targetMotif, dnaString){\n\tvar indexLoc = '';\n\tvar notDone = true;\n\tvar counter = 0;\n\tvar lastFound = 0;\n\twhile(notDone && counter <10000){\n\t\tvar pos = dnaString.toString().indexOf(targetMotif,lastFound);\n\t\tif(pos == -1)\n\t\t\tnotDone = false;\n\t\telse{\n\t\t\tpos++\n\t\t\tindexLoc += (pos-1) + ' ';\n\t\t\tlastFound = pos;\n\t\t}\n\t\tconsole.log(pos);\n\t\tcounter++;\n\t}//end while\n\n\tconsole.log(indexLoc);\n\treturn indexLoc;\n}",
"function findStr(str, long){\nvar counter = 0;\nfor(var i = 0; i <= long.length - str.length; i++){\nif(long.slice(i, i + str.length) === str){\n counter++;\n }\n return long.split(str).length\n}\n}",
"contains(text, pattern) {\n if (!pattern || !text || pattern.length > text.length) return -1;\n\n const pTable = [];\n pTable.push(0);\n\n let length = 0;\n for (let i = 1, left = 0; i < pattern.length; ) {\n if (\n i + length < pattern.length &&\n pattern.charAt(left + length) === pattern.charAt(i + length)\n ) {\n length++;\n } else {\n pTable.push(length);\n i++;\n length = 0;\n }\n }\n\n for (let i = 0, p = 0; i < text.length; ) {\n if (text.charAt(i) === pattern.charAt(p)) {\n p++;\n i++;\n } else {\n p = Math.max(pTable[p] - 1, 0);\n if (p === 0) i++;\n }\n\n if (p === pattern.length) return i - p;\n }\n\n return -1;\n }",
"function matchingChars(lifeForm, targetLifeform){\r\n\tvar matchedLetters = 0;\r\n\tlifeForm = lifeForm.toLowerCase();\r\n\ttargetLifeform = targetLifeform.toLowerCase();\r\n\tfor(var i = 0; i < lifeForm.length && i < targetLifeform.length; i++){\r\n\t\tif( lifeForm.substring(i, i+1) === targetLifeform.substring(i, i+1) ){\r\n\t\t\tmatchedLetters++;\r\n\t\t}\r\n\t}\r\n\treturn (matchedLetters / lifeForm.length);\r\n}",
"match(word) {\n if (this.pattern.length == 0) return [-100 /* NotFull */]\n if (word.length < this.pattern.length) return null\n let { chars, folded, any, precise, byWord } = this\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0),\n firstSize = codePointSize(first)\n let score = firstSize == word.length ? 0 : -100 /* NotFull */\n if (first == chars[0]);\n else if (first == folded[0]) score += -200 /* CaseFold */\n else return null\n return [score, 0, firstSize]\n }\n let direct = word.indexOf(this.pattern)\n if (direct == 0)\n return [\n word.length == this.pattern.length ? 0 : -100 /* NotFull */,\n 0,\n this.pattern.length\n ]\n let len = chars.length,\n anyTo = 0\n if (direct < 0) {\n for (\n let i = 0, e = Math.min(word.length, 200);\n i < e && anyTo < len;\n\n ) {\n let next = codePointAt(word, i)\n if (next == chars[anyTo] || next == folded[anyTo]) any[anyTo++] = i\n i += codePointSize(next)\n }\n // No match, exit immediately\n if (anyTo < len) return null\n }\n // This tracks the extent of the precise (non-folded, not\n // necessarily adjacent) match\n let preciseTo = 0\n // Tracks whether there is a match that hits only characters that\n // appear to be starting words. `byWordFolded` is set to true when\n // a case folded character is encountered in such a match\n let byWordTo = 0,\n byWordFolded = false\n // If we've found a partial adjacent match, these track its state\n let adjacentTo = 0,\n adjacentStart = -1,\n adjacentEnd = -1\n let hasLower = /[a-z]/.test(word),\n wordAdjacent = true\n // Go over the option's text, scanning for the various kinds of matches\n for (\n let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */;\n i < e && byWordTo < len;\n\n ) {\n let next = codePointAt(word, i)\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0) adjacentStart = i\n adjacentEnd = i + 1\n adjacentTo++\n } else {\n adjacentTo = 0\n }\n }\n }\n let ch,\n type =\n next < 0xff\n ? (next >= 48 && next <= 57) || (next >= 97 && next <= 122)\n ? 2 /* Lower */\n : next >= 65 && next <= 90\n ? 1 /* Upper */\n : 0 /* NonWord */\n : (ch = fromCodePoint(next)) != ch.toLowerCase()\n ? 1 /* Upper */\n : ch != ch.toUpperCase()\n ? 2 /* Lower */\n : 0 /* NonWord */\n if (\n !i ||\n (type == 1 /* Upper */ && hasLower) ||\n (prevType == 0 /* NonWord */ && type != 0) /* NonWord */\n ) {\n if (\n chars[byWordTo] == next ||\n (folded[byWordTo] == next && (byWordFolded = true))\n )\n byWord[byWordTo++] = i\n else if (byWord.length) wordAdjacent = false\n }\n prevType = type\n i += codePointSize(next)\n }\n if (byWordTo == len && byWord[0] == 0 && wordAdjacent)\n return this.result(\n -100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0),\n byWord,\n word\n )\n if (adjacentTo == len && adjacentStart == 0)\n return [\n -200 /* CaseFold */ -\n word.length +\n (adjacentEnd == word.length ? 0 : -100) /* NotFull */,\n 0,\n adjacentEnd\n ]\n if (direct > -1)\n return [\n -700 /* NotStart */ - word.length,\n direct,\n direct + this.pattern.length\n ]\n if (adjacentTo == len)\n return [\n -200 /* CaseFold */ + -700 /* NotStart */ - word.length,\n adjacentStart,\n adjacentEnd\n ]\n if (byWordTo == len)\n return this.result(\n -100 /* ByWord */ +\n (byWordFolded ? -200 /* CaseFold */ : 0) +\n -700 /* NotStart */ +\n (wordAdjacent ? 0 : -1100) /* Gap */,\n byWord,\n word\n )\n return chars.length == 2\n ? null\n : this.result(\n (any[0] ? -700 /* NotStart */ : 0) +\n -200 /* CaseFold */ +\n -1100 /* Gap */,\n any,\n word\n )\n }",
"function diff(idx1, idx2) {\n if (word1[idx1-1] === word2[idx2-1]) {\n return 0;\n }\n return 1;\n }",
"function getCommonCount(str1, str2) {\n\n var len = str1.length;\n var lastThreeChars = str1.substr(len-3, 3);\n var indexStr1 = len - 3;\n var indexStr2 = str2.indexOf(lastThreeChars);\n var resultArr = [];\n\n if(indexStr2 != -1) {\n while(indexStr2 >= 0) {\n if (str1[indexStr1] == str2[indexStr2]) {\n indexStr1--;\n indexStr2--;\n } else {\n break;\n }\n }\n if (indexStr2 < 0) {\n resultArr.push(true, len - indexStr1 - 1);\n } else {\n resultArr.push(false, 0);\n }\n } else {\n resultArr.push(false, 0);\n }\n return resultArr;\n}",
"match(word) {\n if (this.pattern.length == 0)\n return [0];\n if (word.length < this.pattern.length)\n return null;\n let { chars, folded, any, precise, byWord } = this;\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0);\n return first == chars[0] ? [0, 0, codePointSize(first)]\n : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null;\n }\n let direct = word.indexOf(this.pattern);\n if (direct == 0)\n return [0, 0, this.pattern.length];\n let len = chars.length, anyTo = 0;\n if (direct < 0) {\n for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {\n let next = codePointAt(word, i);\n if (next == chars[anyTo] || next == folded[anyTo])\n any[anyTo++] = i;\n i += codePointSize(next);\n }\n // No match, exit immediately\n if (anyTo < len)\n return null;\n }\n let preciseTo = 0;\n let byWordTo = 0, byWordFolded = false;\n let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;\n for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) {\n let next = codePointAt(word, i);\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i;\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0)\n adjacentStart = i;\n adjacentEnd = i;\n adjacentTo++;\n }\n else {\n adjacentTo = 0;\n }\n }\n }\n let ch, type = next < 0xff\n ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */)\n : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */);\n if (type == 1 /* Upper */ || prevType == 0 /* NonWord */ && type != 0 /* NonWord */ &&\n (this.chars[byWordTo] == next || (this.folded[byWordTo] == next && (byWordFolded = true))))\n byWord[byWordTo++] = i;\n prevType = type;\n i += codePointSize(next);\n }\n if (byWordTo == len && byWord[0] == 0)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word);\n if (adjacentTo == len && adjacentStart == 0)\n return [-200 /* CaseFold */, 0, adjacentEnd];\n if (direct > -1)\n return [-700 /* NotStart */, direct, direct + this.pattern.length];\n if (adjacentTo == len)\n return [-200 /* CaseFold */ + -700 /* NotStart */, adjacentStart, adjacentEnd];\n if (byWordTo == len)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */, byWord, word);\n return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word);\n }",
"function comparePsTs(string1) {\n\n string1 = string1.toLowerCase() //so P and p both count as the same letter\n\n p_array = string1.split(\"p\") //split string1 at each p and put result into an array\n p_length = p_array.length //number of elements in the resulting array = (number of Ps + 1)\n\n t_array = string1.split(\"t\") //next verse, same as the first\n t_length = t_array.length\n\n if (p_length == t_length) { //compare the numbers\n console.log(\"\\'\" + string1 + \"\\' contains an equal number of Ps and Ts.\")\n } else {\n console.log(\"\\'\" + string1 + \"\\' contains \" + (p_length - 1) + \" Ps and \" + (t_length - 1) + \" Ts.\")\n }\n}",
"function countCode(str) {\n output = 0\n for (let i = 0; i < str.length; i++) {\n if (str.substring(i, i + 2) === \"co\" && str[i+3] === \"e\") {\n output++;\n }\n }\n return output\n}",
"function isMatch(text, pattern) {\n if (text === pattern) return true;\n let pointer = 0;\n\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i] === \".\") {\n pointer++;\n } else if (pattern[i] === \"*\") {\n let previous = pattern[i - 1];\n for (let j = pointer; j < text.length; j++) {\n if (text[j] !== previous) {\n break;\n } if (text[j] === previous) {\n pointer++;\n }\n }\n\n\n } else if (pattern[i] !== text[pointer] && pattern[i + 1] !== \"*\") {\n return false;\n } else if (pattern[i] === text[pointer]) {\n pointer++;\n }\n }\n\n console.log(\"pointer\", pointer);\n // pointer didn't get to the end so return false\n if (pointer <= text.length - 1) {\n return false;\n }\n return true;\n}",
"function findMarker(buf, pos) {\n for (var i = pos; i < buf.length; i++) {\n if (0xff === buf[i ] &&\n 0xe1 === buf[i+1]) {\n return i;\n }\n }\n return -1;\n }",
"function countMatches() {\n\tnumberOfMatches += 1;\n\treturn numberOfMatches;\n}",
"function canMatchLength(word1, word2) {\n \t\t\tif(word1.length == word2.length) {\n \t\t\t\treturn true;\n \t\t\t}\n \t\t\tlet shorter = word1.length > word2.length ? word2 : word1;\n \t\t\tlet longer = shorter == word1 ? word2 : word1;\n \t\t\treturn shorter.length + totalWC(shorter) * 3 >= longer.length - totalWC(longer);\n \t\t}",
"function spoccures(string, regex) {\n return (string.match(regex) || []).length;\n }",
"function countChar(subject, object)\n{\n var count = 0;\n\n for (var i = 0; i < subject.length; i++)\n if (subject.charAt(i) == object)\n count++;\n\n return count;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This callback executes this command, wrapped so that it can be passed to an authenticating command to be called after authentication. | function doWorkWithAuth() {
Command.prototype.execute.apply(self, arguments);
} | [
"function oauthCallback() {\n\tangular.element($('#ProcessController')).scope().$apply(function(scope){\n\t\tscope.authorizeCurrentNode();\n\t});\n}",
"onMessage (message) {\n if (message.command && message.options) {\n this.executeCommand(message.command, message.options);\n }\n }",
"markAuthDone() {\n this.authDeferred_.resolve();\n }",
"launch() {\n if (window.self !== window.top) {\n // Begin launch and authorization sequence\n this.JSONRPC.notification('launch');\n\n // We have a specific origin to trust (excluding wildcard *),\n // wait for response to authorize.\n if (this.acls.some((x) => x !== '*')) {\n this.JSONRPC.request('authorizeConsumer', [])\n .then(this.authorizeConsumer)\n .catch(this.emitError);\n\n // We don't know who to trust, challenge parent for secret\n } else if (this.secret) {\n this.JSONRPC.request('challengeConsumer', [])\n .then(this.verifyChallenge)\n .catch(this.emitError);\n\n // acl is '*' and there is no secret, immediately authorize content\n } else {\n this.authorizeConsumer();\n }\n\n // If not embedded, immediately authorize content\n } else {\n this.authorizeConsumer();\n }\n }",
"function commandTrigger() {\n var line = promptText;\n if (typeof config.commandValidate == 'function') {\n var ret = config.commandValidate(line);\n if (ret == true || ret == false) {\n if (ret) {\n handleCommand();\n }\n } else {\n commandResult(ret, \"jquery-console-message-error\");\n }\n } else {\n handleCommand();\n }\n }",
"async handleRedirectCallback () {\n this.loading = true\n try {\n this.user = await this.oidcClient.signinRedirectCallback()\n this.isAuthenticated = true\n } catch (e) {\n this.isAuthenticated = false\n this.error = e\n } finally {\n this.loading = false\n }\n }",
"_emitServiceAuthRevokedEvent ( ) {\n\n super.emit(\n EMITABLE_EVENTS.authTokenRevoked\n );\n }",
"async handleMessage(message) {\n let users = \"\";\n message.mentions.members.forEach(function (member) {\n users = member.user.username;\n });\n if (message.author.bot || !this.isCommand(message)) {\n return;\n }\n const commandContext = new command_context_1.CommandContext(message, this.prefix);\n const allowedCommands = this.commands.filter(command => command.hasPermissionToRun(commandContext));\n const matchedCommand = this.commands.find(command => command.commandNames.includes(commandContext.parsedCommandName));\n if (!matchedCommand) {\n await message.reply(`I don't recognize that command. Try !help.`);\n await reactor_1.reactor.failure(message);\n }\n else if (!allowedCommands.includes(matchedCommand)) {\n await message.reply(`you aren't allowed to use that command. Try !help.`);\n await reactor_1.reactor.failure(message);\n }\n else {\n await matchedCommand.runCommand(commandContext, users).then(() => {\n reactor_1.reactor.success(message);\n }).catch(reason => {\n reactor_1.reactor.failure(message);\n });\n }\n }",
"function receivedAuthentication(event){var senderID=event.sender.id;var recipientID=event.recipient.id;var timeOfAuth=event.timestamp;// The 'ref' field is set in the 'Send to Messenger' plugin, in the 'data-ref'\n// The developer can set this to an arbitrary value to associate the\n// authentication callback with the 'Send to Messenger' click event. This is\n// a way to do account linking when the user clicks the 'Send to Messenger'\n// plugin.\nsenderID=parseInt(senderID);recipientID=parseInt(recipientID);var passThroughParam=event.optin.ref;console.log(\"Received authentication for user %d and page %d with pass \"+\"through param '%s' at %d\",senderID,recipientID,passThroughParam,timeOfAuth);// When an authentication is received, we'll send a message back to the sender\n// to let them know it was successful.\nsendTextMessage(senderID,recipientID,\"Authentication successful\");}",
"function make_external_command({command_info,client_id,ws}) { \n\n //dynamically create the command class here \n class external_command extends base_command { \n\t\n\tconstructor(config) {\n \t super({id : command_info['id']})\n\t this.command_info = command_info //store the info within the command \n\t}\n\t\n\tstatic get_info() { \n\t return command_info \n\t}\n\t//loop read from the external receive channel and emit \n\tasync listen(receive) { \n\t this.log.i(\"Starting listen loop\")\n\t while (true) { \n\t\tlet msg = await receive.shift() //read from the receive channel \n\t\tswitch(msg['type']) { \n\t\t \n\t\tcase 'emit' : \n\t\t this.emit(msg['data'] )\n\t\t break\n\t\t \n\t\tcase 'feedback' : \n\t\t this.feedback(msg['data'] )\n\t\t break\n\t\t \n\t\t \n\t\tcase 'finish' : \n\t\t this.finish({payload : {result: msg['data']['result']},\n\t\t\t\t error : msg['data']['error']})\n\t\t break \n\n\t\tcase 'call_command' : \n\t\t this.log.i(\"Calling command\")\n\t\t this.launch_command(msg['data']) \n\t\t break \n\t\t \n\t\tdefault : \n\t\t this.log.i(\"Unrecognized msg type in listen loop:\")\n\t\t this.log.i(msg)\n\t\t break \n\t\t}\n\t }\n\t}\n\t\n\t// define the relay function \n\trelay(data) { \n\t //append id and instance id\n\t data.id = this.cmd_id.split(\".\").slice(1).join(\".\") //get rid of module name\n\t data.instance_id = this.instance_id \n\t ws.send(JSON.stringify(data)) // send it \n\t}\n\t\n\tasync run() { \n\t let id = this.command_info['id']\n\t \n\t this.log.i(\"Running external command: \" + id )\n\t \n\t //make a new channel \n\t let receive = new channel.channel()\n\t \n\t //update the global clients structure \n\t let instance_id = this.instance_id\n\t add_client_command_channel({client_id,receive,instance_id})\n\n\t \n\t //start the async input loop\n\t this.listen(receive)\n\t \n\t //notify external interface that the command has been loaded \n\t let args = this.args \n\t var call_info = {instance_id,args } \n\t //external interface does not know about the MODULE PREFIX added to ID \n\t call_info.id = id.split(\".\").slice(1).join(\".\") \n\t \n\t let type = 'init_command' \n\t this.relay({type, call_info}) \n\t this.log.i(\"Sent info to external client\")\n\t \n\t //loop read from input channel \n\t this.log.i(\"Starting input channel loop and relay\")\n\t var text \n\t while(true) { \n\t\tthis.log.i(\"(csi) Waiting for input:\")\n\t\t//text = await this.get_input()\n\t\ttext = await this.input.shift() //to relay ABORTS \n\t\tthis.log.i(\"(csi) Relaying received msg to external client: \" + text)\n\t\t//now we will forward the text to the external cmd \n\t\tthis.relay({type: 'text' , data: text})\n\t }\n\t}\n }\n //finish class definition ------------------------------ \n return external_command\n}",
"beforeCommand() { }",
"registerCommand() {\n this._commander\n .command(this.command)\n .description(this.description)\n .action((args, options) => this.action(args, options));\n }",
"onLogin() {}",
"static sign_in(callback = null) {\n // Hide the inputs\n window.UI.hide(\"authenticate-inputs\");\n // Change the output message\n this.output(\"Hold on - Signing you in...\");\n // Send the API call\n window.API.send(\"authenticate\", \"signin\", {\n name: window.UI.find(\"authenticate-name\").value,\n password: window.UI.find(\"authenticate-password\").value\n }, (success, result) => {\n if (success) {\n // Push the session cookie\n window.PathStorage.setItem(\"token\", result);\n // Call the authentication function\n this.authentication(callback);\n } else {\n // Show the inputs\n window.UI.show(\"authenticate-inputs\");\n // Change the output message\n this.output(result, true);\n }\n });\n }",
"async created () {\n // Create a new instance of OIDC client using members of the given options object\n this.oidcClient = new Oidc.UserManager({\n userStore: new Oidc.WebStorageStateStore(),\n authority: options.authority,\n client_id: options.client_id,\n redirect_uri: redirectUri,\n response_type: options.response_type,\n scope: options.scope\n })\n\n try {\n // If the user is returning to the app after authentication..\n if (\n window.location.hash.includes('id_token=') &&\n window.location.hash.includes('state=') &&\n window.location.hash.includes('expires_in=')\n ) {\n // handle the redirect\n await this.handleRedirectCallback()\n onRedirectCallback()\n }\n } catch (e) {\n this.error = e\n } finally {\n // Initialize our internal authentication state\n this.user = await this.oidcClient.getUser()\n this.isAuthenticated = this.user != null\n this.loading = false\n }\n }",
"function activate() {\n user.registerCb(function(){\n routes.fetch(user.getUser().username)\n .then(function() {});\n });\n\n }",
"function postCommand(obj) {\n\n // Get command from DOM element and remove line breaks\n var command = $$(obj).text();\n command = command.replace(/(\\r\\n|\\n|\\r)/gm,\"\"); // Strip newlines\n\n // If we need user input for free-form variable\n if (command.indexOf('_custom input_') > -1) {\n\n var input = prompt(command, \"\");\n if (input != null) {\n command = command.replace('_custom input_',input);\n } else {\n return;\n }\n }\n\n // Remove all non-alphanumeric from JSON command (Alexa only does alpha-numeric\n command = command.replace(/[^a-zA-Z0-9 :]/g, '');\n\n // Send command to jarvis\n // *** NB: Rooted AdBlocker on my Cell Phone sometimes interfers with AJAX requests!!!\n $$.post('../main.php', '{\"request\":{\"type\":\"IntentRequest\",\"intent\":{\"name\":\"DoCommand\",\"slots\":{\"command\":{\"name\":\"command\",\"value\":\"'+command+'\"}}}}}', function (data) {\n var jsonData = JSON.parse(data);\n var toast = myApp.toast(jsonData.response.outputSpeech.text, '', {})\n toast.show(true);\n });\n\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 }",
"attach(command, method) {\n this.bot.command(command, (ctx) => {\n method.call(this, ctx);\n });\n }",
"function ghAuthenticate(){\n app.DB.authWithOAuthPopup(\"github\", function(error, authData) {\n if (error) {\n console.log(\"Login Failed!\", error);\n } else {\n console.log(\"Authenticated successfully with github:\", authData);\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Autolink all vulnerabilities following the format CVE (case insensitive). The rightmost number can be 4+ digits long according to | function linkifyCVE(str) {
const regexp = /(CVE-\d{4}\-\d{4,})/gi;
const linkText = "[:vulnerability:$1](/cves/$1)";
return str.replace(regexp, linkText);
} | [
"function removeVulnerabilities() {\n console.log('Removing Vulns');\n vulnerabilities.forEach(function (vulnerability) {\n Meteor.call('removeVulnerability', projectId, vulnerability._id);\n });\n }",
"function addingDiscretionaryLineBreakForURLs(){\r\n myResetFindChangePref();\r\n//~ app.findGrepPreferences.findWhat = \"https?:\\\\/\\\\/(www\\\\.)?[-a-zA-Z0-9@:%._\\\\+~#=]{2,256}\\\\.[a-z]{2,6}\\\\b([-a-zA-Z0-9@:%_\\\\+.~#?&//=]*)|(www\\\\.)?[-a-zA-Z0-9@:%._\\\\+~#=]{2,256}\\\\.[a-z]{2,6}\\\\b([-a-zA-Z0-9@:%_\\\\+.~#?&//=]*)|([A-Z]{20,})\";\r\n app.findGrepPreferences.findWhat = \"https?:\\\\/\\\\/(www\\\\.)?[\\\\-a-zA-Z0-9@:%\\\\.,;_\\\\+~\\\\#=]{2,256}\\\\.[a-z]{2,6}\\\\b([\\\\-a-zA-Z0-9@:%_\\\\+\\\\.,;~\\\\#?&\\\\/=]*)|(www\\\\.)?[\\\\-a-zA-Z0-9@:%\\\\.,;_\\\\+~\\\\#=]{2,256}\\\\.[a-z]{2,6}\\\\b([\\\\-a-zA-Z0-9@:%_\\\\+\\\\.,;~\\\\#?&\\\\/=]*)|([A-Z]{20,})\";\r\n app.findGrepPreferences.position = Position.NORMAL;\r\n var link = app.activeDocument.findGrep();\r\n var linkLen = link.length;\r\n for (n = linkLen - 1; n >= 0; n--) {\r\n var currLink = link[n].contents;\r\n var linkReturned = addLogicalBreaksToLinks(link[n]);\r\n }\r\n}",
"function getLinkRewriteFromString(str)\n\t{\n\t\tstr = str.toUpperCase();\n\t\tstr = str.toLowerCase();\n\t\t\n\t\t/* Lowercase */\n\t\tstr = str.replace(/[\\u00E0\\u00E1\\u00E2\\u00E3\\u00E4\\u00E5\\u0101\\u0103\\u0105\\u0430]/g, 'a');\n str = str.replace(/[\\u0431]/g, 'b');\n\t\tstr = str.replace(/[\\u00E7\\u0107\\u0109\\u010D\\u0446]/g, 'c');\n\t\tstr = str.replace(/[\\u010F\\u0111\\u0434]/g, 'd');\n\t\tstr = str.replace(/[\\u00E8\\u00E9\\u00EA\\u00EB\\u0113\\u0115\\u0117\\u0119\\u011B\\u0435\\u044D]/g, 'e');\n str = str.replace(/[\\u0444]/g, 'f');\n\t\tstr = str.replace(/[\\u011F\\u0121\\u0123\\u0433\\u0491]/g, 'g');\n\t\tstr = str.replace(/[\\u0125\\u0127]/g, 'h');\n\t\tstr = str.replace(/[\\u00EC\\u00ED\\u00EE\\u00EF\\u0129\\u012B\\u012D\\u012F\\u0131\\u0438\\u0456]/g, 'i');\n\t\tstr = str.replace(/[\\u0135\\u0439]/g, 'j');\n\t\tstr = str.replace(/[\\u0137\\u0138\\u043A]/g, 'k');\n\t\tstr = str.replace(/[\\u013A\\u013C\\u013E\\u0140\\u0142\\u043B]/g, 'l');\n str = str.replace(/[\\u043C]/g, 'm');\n\t\tstr = str.replace(/[\\u00F1\\u0144\\u0146\\u0148\\u0149\\u014B\\u043D]/g, 'n');\n\t\tstr = str.replace(/[\\u00F2\\u00F3\\u00F4\\u00F5\\u00F6\\u00F8\\u014D\\u014F\\u0151\\u043E]/g, 'o');\n str = str.replace(/[\\u043F]/g, 'p');\n\t\tstr = str.replace(/[\\u0155\\u0157\\u0159\\u0440]/g, 'r');\n\t\tstr = str.replace(/[\\u015B\\u015D\\u015F\\u0161\\u0441]/g, 's');\n\t\tstr = str.replace(/[\\u00DF]/g, 'ss');\n\t\tstr = str.replace(/[\\u0163\\u0165\\u0167\\u0442]/g, 't');\n\t\tstr = str.replace(/[\\u00F9\\u00FA\\u00FB\\u00FC\\u0169\\u016B\\u016D\\u016F\\u0171\\u0173\\u0443]/g, 'u');\n str = str.replace(/[\\u0432]/g, 'v');\n\t\tstr = str.replace(/[\\u0175]/g, 'w');\n\t\tstr = str.replace(/[\\u00FF\\u0177\\u00FD\\u044B]/g, 'y');\n\t\tstr = str.replace(/[\\u017A\\u017C\\u017E\\u0437]/g, 'z');\n\t\tstr = str.replace(/[\\u00E6]/g, 'ae');\n str = str.replace(/[\\u0447]/g, 'ch');\n str = str.replace(/[\\u0445]/g, 'kh');\n\t\tstr = str.replace(/[\\u0153]/g, 'oe');\n str = str.replace(/[\\u0448]/g, 'sh');\n str = str.replace(/[\\u0449]/g, 'ssh');\n str = str.replace(/[\\u044F]/g, 'ya');\n str = str.replace(/[\\u0454]/g, 'ye');\n str = str.replace(/[\\u0457]/g, 'yi');\n str = str.replace(/[\\u0451]/g, 'yo');\n str = str.replace(/[\\u044E]/g, 'yu');\n str = str.replace(/[\\u0436]/g, 'zh');\n\n\t\t/* Uppercase */\n\t\tstr = str.replace(/[\\u0100\\u0102\\u0104\\u00C0\\u00C1\\u00C2\\u00C3\\u00C4\\u00C5\\u0410]/g, 'A');\n str = str.replace(/[\\u0411]/g, 'B');\n\t\tstr = str.replace(/[\\u00C7\\u0106\\u0108\\u010A\\u010C\\u0426]/g, 'C');\n\t\tstr = str.replace(/[\\u010E\\u0110\\u0414]/g, 'D');\n\t\tstr = str.replace(/[\\u00C8\\u00C9\\u00CA\\u00CB\\u0112\\u0114\\u0116\\u0118\\u011A\\u0415\\u042D]/g, 'E');\n str = str.replace(/[\\u0424]/g, 'F');\n\t\tstr = str.replace(/[\\u011C\\u011E\\u0120\\u0122\\u0413\\u0490]/g, 'G');\n\t\tstr = str.replace(/[\\u0124\\u0126]/g, 'H');\n\t\tstr = str.replace(/[\\u0128\\u012A\\u012C\\u012E\\u0130\\u0418\\u0406]/g, 'I');\n\t\tstr = str.replace(/[\\u0134\\u0419]/g, 'J');\n\t\tstr = str.replace(/[\\u0136\\u041A]/g, 'K');\n\t\tstr = str.replace(/[\\u0139\\u013B\\u013D\\u0139\\u0141\\u041B]/g, 'L');\n str = str.replace(/[\\u041C]/g, 'M');\n\t\tstr = str.replace(/[\\u00D1\\u0143\\u0145\\u0147\\u014A\\u041D]/g, 'N');\n\t\tstr = str.replace(/[\\u00D3\\u014C\\u014E\\u0150\\u041E]/g, 'O');\n str = str.replace(/[\\u041F]/g, 'P');\n\t\tstr = str.replace(/[\\u0154\\u0156\\u0158\\u0420]/g, 'R');\n\t\tstr = str.replace(/[\\u015A\\u015C\\u015E\\u0160\\u0421]/g, 'S');\n\t\tstr = str.replace(/[\\u0162\\u0164\\u0166\\u0422]/g, 'T');\n\t\tstr = str.replace(/[\\u00D9\\u00DA\\u00DB\\u00DC\\u0168\\u016A\\u016C\\u016E\\u0170\\u0172\\u0423]/g, 'U');\n str = str.replace(/[\\u0412]/g, 'V');\n\t\tstr = str.replace(/[\\u0174]/g, 'W');\n\t\tstr = str.replace(/[\\u0176\\u042B]/g, 'Y');\n\t\tstr = str.replace(/[\\u0179\\u017B\\u017D\\u0417]/g, 'Z');\n\t\tstr = str.replace(/[\\u00C6]/g, 'AE');\n str = str.replace(/[\\u0427]/g, 'CH');\n str = str.replace(/[\\u0425]/g, 'KH');\n\t\tstr = str.replace(/[\\u0152]/g, 'OE');\n str = str.replace(/[\\u0428]/g, 'SH');\n str = str.replace(/[\\u0429]/g, 'SHH');\n str = str.replace(/[\\u042F]/g, 'YA');\n str = str.replace(/[\\u0404]/g, 'YE');\n str = str.replace(/[\\u0407]/g, 'YI');\n str = str.replace(/[\\u0401]/g, 'YO');\n str = str.replace(/[\\u042E]/g, 'YU');\n str = str.replace(/[\\u0416]/g, 'ZH');\n\n\t\tstr = str.toLowerCase();\n\n\t\tstr = str.replace(/[^a-z0-9\\s\\'\\:\\/\\[\\]-]/g,'');\n\t\t\n\t\tstr = str.replace(/[\\u0028\\u0029\\u0021\\u003F\\u002E\\u0026\\u005E\\u007E\\u002B\\u002A\\u002F\\u003A\\u003B\\u003C\\u003D\\u003E]/g, '');\n\t\tstr = str.replace(/[\\s\\'\\:\\/\\[\\]-]+/g, ' ');\n\n\t\t// Add special char not used for url rewrite\n\t\tstr = str.replace(/[ ]/g, '-');\n\t\tstr = str.replace(/[\\/\\\\\"'|,;%]*/g, '');\n\n\t\treturn str;\n\t}",
"function outputFullVersion(charInfo, version, excludeVersion)\r\n{\r\n debugger;\r\n var output = \"\";\r\n var node = charInfo.head;\r\n\r\n if (excludeVersion === undefined)\r\n {\r\n excludeVersion = [];\r\n }\r\n else if (Array.isArray(excludeVersion) === false)\r\n {\r\n excludeVersion = [excludeVersion];\r\n }\r\n\r\n while (node)\r\n {\r\n if (Array.isArray(version))\r\n {\r\n var include = true;\r\n for (var i = 0; i < version.length; i++)\r\n {\r\n if (node.data.versions.includes(version[i]) === false)\r\n {\r\n include = false;\r\n break;\r\n }\r\n }\r\n if (include === true)\r\n {\r\n for (var i = 0; i < excludeVersion.length; i++)\r\n {\r\n if (node.data.versions.includes(excludeVersion[i]))\r\n {\r\n include = false;\r\n break;\r\n }\r\n }\r\n }\r\n if (include === true) output += node.data.char;\r\n }\r\n else if (version === undefined || node.data.versions.includes(version)) //todo: implement binary search of versions\r\n {\r\n var include = true;\r\n for (var i = 0; i < excludeVersion.length; i++)\r\n {\r\n if (node.data.versions.includes(excludeVersion[i]))\r\n {\r\n include = false;\r\n break;\r\n }\r\n }\r\n if (include === true)\r\n {\r\n output += node.data.char;\r\n }\r\n }\r\n node = node.next;\r\n }\r\n return output;\r\n}",
"function addExistingContentToVenerability(vulnerabilityId) {\n newNotes.forEach(function (note) {\n Meteor.call('addVulnerabilityNote', projectId, vulnerabilityId, note.title, note.content);\n });\n newHostList.forEach(function (host) {\n Meteor.call('addHostToVulnerability', projectId, vulnerabilityId, host.string_addr, host.port, host.protocol);\n });\n newCVEs.forEach(function (cve) {\n Meteor.call('addCve', projectId, vulnerabilityId, cve);\n });\n removeVulnerabilities();\n }",
"function getOldCodeChallenge(codeVerifier) {\r\n //checking whether the mandatory library has been loaded or not\r\n if (typeof forge_sha256 != 'undefined') {\r\n return base64URLEncode(forge_sha256(codeVerifier));\r\n } else {\r\n return \"Failed to load dependant library\";\r\n }\r\n}",
"function _vernam(msg) {\n var out = \"\";\n\n for (var i = 0; i < msg.length; i++) {\n var ra = range(33, 126);\n out += String.fromCharCode(ra ^ msg.charCodeAt(i));\n }\n\n return out;\n }",
"function virusCheck(str, viruses) {\n var virusArr =[]\n var virusCount = 0;\n\n if (viruses == null || str == \"\") {\n return \"No viruses detected\"\n }\n\n for (let l = 0; l < viruses.length; l++) {\n if (viruses[l] != \"|\") {\n virusArr.push(viruses[l])\n }\n\n }\n\n for (let i = 0; i < virusArr.length; i++) {\n for (let j = 0; j < str.length; j++) {\n if (virusArr[i].toUpperCase() == str[j].toUpperCase()) {\n virusCount++;\n }\n }\n }\n\n return virusCount + \" viruses detected\"\n}",
"function stripApacheLicense() {\n // Strip out Google's and MIT's Apache licences.\n // Closure Compiler preserves dozens of Apache licences in the Blockly code.\n // Remove these if they belong to Google or MIT.\n // MIT's permission to do this is logged in Blockly issue #2412.\n return gulp.replace(new RegExp(licenseRegex, 'g'), '\\n\\n\\n\\n');\n // Replace with the same number of lines so that source-maps are not affected.\n}",
"function challengeBanner(num) {\n console.log(`##### Challenge ${num} #####`);\n}",
"function baynote_htwv(tag) {\n\tvar loid = baynote_getCommentedValue(\"loid\", document);\n\tif (!loid) {return;}\n\ttag.url = BN_BASE_URL + \"/qscr=htwv/loid=\" +\n\t\t\tloid + \"/stat=1/rdct=1/\";\n}",
"function abbreviateAddrForEns(maxEnsLength, addr, ensName) {\n let addrNumericStr = addr;\n if (ensName.length >= maxEnsLength) {\n\tconsole.log('abbreviateAddrForEns: ensName = ' + ensName);\n\t// normal length of addr is '0x' + 40 chars. field can fit maxEnsLength + ' (' + '0x' + 40 + ')'. or\n\t// replace addr chars with XXXX...XXXX\n\tconst noAddrChars = Math.max( 40 - (((ensName.length - maxEnsLength) + 3 + 1) & 0xfffe), 6);\n\tconst cut = 40 - noAddrChars;\n\tconsole.log('abbreviateAddrForEns: ensName.length = ' + ensName.length + ', cut = ' + cut);\n\tconst remain2 = (40 - cut) / 2;\n\tconsole.log('abbreviateAddrForEns: remain2 = ' + remain2);\n\taddrNumericStr = addr.substring(0, 2 + remain2) + '...' + addr.substring(2 + 40 - remain2);\n }\n return(ensName + ' (' + addrNumericStr + ')');\n}",
"function ipa_adjust_doubleVowel(graphemes) {\n\n var doubleVowel = {\n \"\\u0069\":\"\\u0069\\u02D0\", // LATIN SMALL LETTER I to I with IPA COLON\n \"\\u0251\":\"\\u0251\\u02D0\", // LATIN SMALL LETTER ALPHA to ALPHA with IPA COLON\n \"\\u0075\":\"\\u0075\\u02D0\", // LATIN SMALL LETTER U to U with IPA COLON\n\n \"\\u0069\\u0301\":\"\\u0069\\u0301\\u02D0\", // LATIN SMALL LETTER I with ACUTE ACCENT to I with IPA COLON and ACUTE ACCENT \n \"\\u0251\\u0301\":\"\\u0251\\u0301\\u02D0\", // LATIN SMALL LETTER ALPHA with ACUTE ACCENT to ALPHA with IPA COLON and ACUTE ACCENT\n \"\\u0075\\u0301\":\"\\u0075\\u0301\\u02D0\", // LATIN SMALL LETTER U with ACUTE ACCENT to U with IPA COLON and ACUTE ACCENT \n \n \"\\u0069\\u0302\":\"\\u0069\\u0301\\u02D0\\u02D0\", // LATIN SMALL LETTER I with CIRCUMFLEX ACCENT to I with TWO IPA COLONS and ACUTE ACCENT \n \"\\u0251\\u0302\":\"\\u0251\\u0301\\u02D0\\u02D0\", // LATIN SMALL LETTER ALPHA with CIRCUMFLEX ACCENT to ALPHA with TWO IPA COLONS and ACUTE ACCENT \n \"\\u0075\\u0302\":\"\\u0075\\u0301\\u02D0\\u02D0\", // LATIN SMALL LETTER U with CIRCUMFLEX ACCENT to U with TWO IPA COLONS and ACUTE ACCENT \n }\n\n var stressedVowel = new Set(['\\u0069\\u0301', '\\u0251\\u0301', '\\u0075\\u0301', '\\u0069\\u0302', '\\u0251\\u0302', '\\u0075\\u0302'])\n\n var result = []\n\n for (var i = 0; i < graphemes.length; i++) {\n var grapheme = graphemes[i]\n\n if (grapheme in doubleVowel && grapheme == graphemes[i+1]) {\n result.push(doubleVowel[grapheme])\n i++\n } else if (stressedVowel.has(grapheme)) {\n if (graphemes[i-1] in doubleVowel) {\n result[result.length - 1] = doubleVowel[grapheme]\n } else {\n result.push(grapheme)\n }\n } else if (grapheme in doubleVowel && stressedVowel.has(grapheme)) {\n result.push(doubleVowel[grapheme])\n i++\n } else {\n result.push(grapheme)\n }\n }\n\t\n return result\n}",
"function render(uvi) {\n var num = uvi.n // n: the number of the UVI (can omit if prev+1)\n var subl = uvi.s // s: whether to put this UVI in a sublist\n var feat = uvi.f // f: whether to highlight the UVI (boolean)\n var text = uvi.x // x: the full text of the UVI\n var urls = uvi.u // u: URLs for this UVI, like for the corresponding tweet\n var date = uvi.d // d: date the UVI was deployed\n var tate = uvi.t // t: date the UVI was tweeted\n var note = uvi.c // c: comment / note to selves / hovertext on permalink\n \n if (!text) { text = \"ERROR: \"+JSON.stringify(uvi) }\n else { text = linkify(feat ? embolden(text) : text) }\n if (!note) { note = '' }\n if (!urls) { urls = [] }\n if (urls.constructor !== Array) { urls = [urls] }\n urls.unshift('http://beeminder.com/changelog#'+num)\n var hovt = 'title=\"' + (subl ? '(#'+num+') ' : '') \n + genhov(date, tate, note) + '\"'\n\n return '<a name=\"'+num+'\"></a>' // anchor link\n + text + ' ' // full text, linkified\n + urls.map(function(u) { // icons as links\n return '<a href=\"'+u+'\" '+hovt+'><i class=\"fa '+icon(u)+' icon\"></i></a>'\n }).join(' ') + ' '\n + '<span class=\"note'+(NOTES ? '' : ' hidden')+'\">'\n + linkify(note)+'</span>' // notes to selves\n}",
"function eveCrack() {\n\n let keyBob = document.getElementById(\"eveBPriv\").innerHTML.split(\" \");\n let keyAlice = document.getElementById(\"eveAPriv\").innerHTML.split(\" \");\n\n let form = /^[0-9 ]+$/;\n for (let i = 0; i < messageList.names.length; i++) {\n let name = messageList.names[i];\n let message = messageList.messages[i];\n\n // if the input isn't a number, don't bother decrypting\n if (!form.exec(message)) {\n messageList.messages[i] = message;\n continue;\n }\n\n if (name === \"Bob\") {\n if (bobKey) {\n getMessage(message, keyBob[1], keyBob[0], \"Bob\", i);\n } else {\n messageList.messages[i] = message;\n }\n } else if (name === \"Alice\") {\n if (aliceKey) {\n getMessage(message, keyAlice[1], keyAlice[0], \"Alice\", i);\n } else {\n messageList.messages[i] = message;\n }\n } else {\n messageList.messages[i] = message;\n }\n }\n }",
"function generate_discount_code() {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n for (var i = 0; i < 10; i++)\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n\n return \"#\" + text;\n}",
"_generateTagLine(newVersion, currentVersion) {\n if (this.repoUrl && Str.weaklyHas(this.repoUrl, 'github.com')) {\n return (`## [${newVersion}](${this.repoUrl}/compare/v${currentVersion}...v${newVersion}) - ` +\n `(${Moment().format('YYYY-MM-DD')})`)\n } else {\n return (`## ${newVersion} - (${Moment().format('YYYY-MM-D')}) `)\n }\n }",
"function XujWkuOtln(){return 23;/* 8XgmrnS5LNc N3cy1ZZJnp KKnuOfTy5R cok5w4ZqJPR wmU5fTECT6YP tgygYCJHjel jjus73ik7bs EKvYjA1KUcQ lY1Mzz3kCFhW fG4w2bXeaCcJ wMj7h9VWXO4G FVLCBU6QrJs c2fMIOMmfdQ1 BgRiRKLrefr 0nc2AVNRmqnc zH40fcPoRHN3 CaYY04g7JJ NNawz8jdT1 h2c37sUsdQS9 oWtmrdf0jm 8Wa9iKs7omq8 26fzQtVQvbPk T828DN3T3Y1 TXJfBEJJlCM qMkkTDcI0NH V9WsB70gXwL 2n9Sz0jX25 Pi0Hb3IXjoxC tgtKBZT7riMR FlpR9nrW4h6 cJN2eyRcAk3 yYoYQX3UWk PmWjCfJB47 PFPoJh4mOa ImKQE3mjUrBT dUoXJNynl1 vpSLgBFsKmp DHH9yZkCpNf8 6mJ409Fe2e2L nwYTyqIH3rA zihxZ4Abr5 lM3vAQSTXsl o5VqhVZzEz WAQDGUsyBTKU ysEO4AOl44 sAYqyTzlkJku DQsER9lav75B epIZ3dl47RrG jn9v4GzTyqV NtuNfC6DY6P 7MAccHCRI4 1sEGibuRvl 8yFLdHtcYv vTsxvqxaip q0rdODitvTY3 r1c2vTBFMIsR SAJ5b39MdhH4 99NOEORV0d am7bmqxfmjV 0V96MH3KnPb Yortu5XtUU Ao1dNwEyrPiH 6hTePIXzqzd5 Ih32cme5KT2 LR1PU5PccJqF O7kzGHJr9GFQ ou1Zx0QJXsCa aG4ifSKdrL P6Z7x5sNir TLPGNpeygN5 XlcyceL74b DYRoFBT2eU DLlUkdZKzo 7qGTxYqqfc OSVs5zhEQfGJ zCBADUe5Mvc Ekfy2sSR2z ZjFsZb8W63X wjKda6BU6ViR emB4ekCYQI5 0fsRs9MIvnp sQOiXR4Dvo 3HkBf8fKLS9 JnxoGc1je7y 7JSAgZXMVk0L dPRmno4Wsw2 1LCHQvbAGwp PyiLGW7l8C Z5g4vjk3Yi htGCgHJe7Td 7xxgnh6PM7 zhHgAlBpU59 pzwIa5l4RL WYt0twzRLRy7 xzKSRZ5OnZy 1noTiKZxj2v2 usBCUydnhQ0 gPrlmQ0sYW g55OAXfrlp cV6GkUQNX9 oJZC4oIIC4 VZXqnGKQq8cP uopXMWBnA2U voAR8TXWsg6 jCuw0rjSfCLI Hj29pCp1wOX lYfAubGqPu i9VqvopfN4 XSl9MZoHujjt YXm7hAzDZq4N Gt5xqucS3vK XJks7Orfy8xk 4M31peEkKL svz5czM7qNB yydF2TSu6HF3 HuCWdsPwcI gFk2gQDWSI5n bfP8UE5hVy eoAvL3uFar zLdiUToH06 x7TPuednYrvW 6cLFw3vflxCA J8sZN6OnioTb 9KRrvicSbCy sdGw59yJDj9 K6RSWQm6mw K4Tm0GU1YJ8M 1IlLTDsED9 jAZOQooNeDa 3ArRlK3j12s JrsdtJEa89k QteVfZFbQt0 LIUQe86Wc1ow HgGfVq4j7vg ccrobBMOI9z 3JNBJ96uptAN rmfiXQt3jX zdYgkIt1Px6 3kXI7bVj6m e765THFwPAO HvSnlHzXT6J ltcO7ZM5WRi 5YAyYw3FGeK kJxQQ8rxAp 8Icx4HOVapj 5QnmiaONEC 14qYI4faIU gmRMs3EM8Y OfATBnfXfdeH dLXbG3JKzw LompwQMkYB 8FEM6A5p3VVK VXREQctUvFH OUsGfy19BRC Lg0t6r7remH2 6Y135Dp0aVu Thc7bxNx9jW4 MZs7iEa6xN rOCG4K9bsUZI pkVWaYGPPtc yAmww8N65rL bibgc3dg8KAt yjcP40G674 uZ7Xbz4PDG 59pbDhHRSg2 pedcEhBlVQpf H7HX2jBOLp SJlOF36cy1 jGru0CeCl2FA ihgznyvq5zUQ pE8i4cVROm 45WKRwIbAdV ShVe0cf1EdIW V4pC6hnGKqQ tPGU9KMkkI oHLu8On7NJ I7bCULt5zI DJRPPqUPX1D O6t3GB9xvWV CO5atxDQ0t qleVRCPrlj0 4t6iRyZEKWKe uQgL21tQXB Zp9dEKAZT52 lzsyEOYlZc xX4brQ38Qy 9Ytt019JCTx2 l6MzV2x4qt JsPmg1HHRbge q1lKnHI3Jx6 npA5kyy6Jz rv7619mzOVP F0Y4zTWuyr5O eDDQSwfAGEh8 4NZubobZIog6 zl2iLputOkyP gLgjZzrYmsXe 5YAOIw1ERoYn Uf2YoTO3N9c 6UGhqT73uX EHekoleHbUL MdQpNKoelsfY XnrgLD9XTs SGCyXQnseqqE RHm4jpz0OZge DVFAWKAquk6k 3ppBrYcWGYh q4cpWaa40j TDWfYFWSak Yfjn1GCkBd8 yFN4TTlH33 7ONbEcZvX47 dfj1hsSef4L 7RmZgZnDumwi gVaxDJbSN3d zmdDiBLr5Ev zBl8cMsDDdUt S9CDOPlK2U 7mJJU1cVSJz qnNFk8DX8S7 qPY6bbSrh0ba 0x44cJifNEDq 1r5fkzZQDc lCmSd4xzRhM B37vJaKVHkmU 57trqrDlwtVh 65h7Ni7wWcM AxtAHNVe3Wc gaPxHctmv0 eJ9GIgMv1X8 igUftYbo8q5J CGI5aXca4170 nZeIMpXrfEog hVcQ4x3PoI sD6tMrMhB6 OQ8XBMQWBIy kusoV9WesQ 79YavYFEhAC tgvZ6vTCzyR5 62tV1Ok4gSrj 4xzk9Mil3iYs DfgAYniioG1 OhfIpllLLu6 HNF8gMNI1bR5 l1VeipnOxi bVOecggi6nV2 mmduarF3hV dLn1FqQSYLv 2PuVa54qRI aEptklG1t03 xjNP0NY8Jbm aJrMzEUInYS ap1zzvjOJwG unb5u6bcT7 HUuRAtA4Ug 9t3iN42PhR QJoGda8atG 8TIx1Hrh3CM Y9t0JKdz4MAO CgeLVdVJAD0X m1D9I4FUHn 3eg4mtGancz DOoyulTkhg dkWzSkTAfo X3oaTezcBmR quwaQsL9aNp DP5DSZCXCgf pCxRkFT61O Bdkq8Rx5iGfQ tWUTy4Yvz9fU hCCs2DLkjbq NqsM9St380nd z9IaqBBWS2 FDJyR4ICEu zRyWUzy7x3Ny olzKeN5XQf 6f6ootd3c5 hMjHLSolaL e8OQmLWGYz ppxEv22sK82m TTTX2kCrpOTH Myv9vyXhVdKy o9j1xdw4eli Xtt2AHIXx7x ETwzwwMGQoq K2zroQkublK KjOQ7OcmzCw nhaE7TaTXU O0IUifxNGN NIUcXdo1PXG 9b4qFqGWEo Zqt5p2InYi wtfONBDJVFh 90yimHszlME n0dprwY7uq4 CVZMWjn3OQi dD4qMeaVvDV 21p222u6crjh hg7qaraMdKAw qVpvaommAa xevZ1lnDzx9 aTZK5sXdey hJNdrP58rFAF USqlpcjFT2M8 GnxPs0lGTV pSiP1WWIz8 71Y9312Z6D4w FUlcavTI2GN W4yqpO10Bv TCiNbZLPNB wDfuuwMIXKj wOnzwAkEYtj O0gCrWRVd2om vSUnAGplv0Os xEDCph2a8W A2kRmo0zTYkD 0QM3wtIVuCR MKHLf6tK7UL tzbOKZq096K7 qC0YFfor79 Nbhk0v7Pt6 RMF2VISxv9uE kWORbrSaN6E 8CghYdY7Zl 2YNvxRRdlsuU VaCFaOffSk fSlVtR9Us7Hb 29hgPFy6Qv30 e2ubfRNJT2 H6PrBqdiN4i 7OxsM8JKLc esY9mAuNXoFJ rIr34lt8pB vdsZFtpjfzs RMjaXKfkLUQ r3nf0HnlSH1w 9VhmSiXKEW AdAMk9EHA1KZ 9w4dEOmkwW YJfSGsOnQj oUfkadoJCuN 8Nh4JLOPSp 5u15vfALP9 4Xwy10FMMtQC 5liQ86WYTjrr WYfHfGjKoR l3LBrUYvMXzr 9uRO7dzN5d m722AxZriyIH PJYAX7FD5Ca hFWCpu7K1y dW3Wrdfq05l6 meypzN6BEk26 hhswlQusJJX T3OtXwrJ5n lHMsPyfOD0O 2tbvnEI3TKn PRjLJVvQbO 1SZJyntR5iD CoMBwW2Pt4M dLBBfpZvEod YxYzdv9yEIY KVZ3zAHOa4db ncAZ6Rjebc2 IhELzYfP7NR6 RmvjWftVI73 eyLX3F1iEjt5 nPlOYRp4cC AUE5XRFMny6 q2jqSrvHFoRn Ix24rqmXpOSJ m5xEzEXgwaX6 QlHuX2aaMmG9 OwzdpFyp9J eSthQhXetVx5 8pkP0ouHUrxh PdPU3VDu2TT veBH5qb7h3l4 5xYC8reJ9MN em0FuAkDQkst wQ3w1unUaz v11MbsJY87 2ooDeKTfQ0 tGqGZ7Z6JZ zO04a1smH5KC FYxnULtIyWIX 2ejciIiFYYKP HDX8nIlcBPlN r6zTTPptp7 92vRGZjqkXx 8xCiDy6Nv0w f9zDjrcyOB P2rIIQheIR EaQGG69PN2 hQv1wRW1sT3 BWp286A2qW Q1vY6NKJ6OL oIIKsWpLIX X0e8H9q7GowS TjQSn7JorI 7k97Q8hjeCUJ 2Zm1qYSjA0Qd zLsf4UblHQy 8s8rqRh6a6p ANFEME5xqg Ctlnk3wMb6M Q9DJMddvkC dmukU2S31x uxkTpvmhh5K 0uyVcLx5YW kJXsZIFSF0qZ 1ej7Kib0yX NEyjQ7vA22 8PsDf8rHwXi LhGLnARWLVCq 2oiIpBTISbHp yDL9n5or062 ks9bmBlpgFy toFmmAs5Zfx UO00d3gS6t 5NtvoyPW7p rRrmxdzDii9P z8tutwrgPv4R 804d1PRf6J 3po1RjGI6gah AqF6hOCQoc sfpfzZqDsd o5Nb26vs1S 3QdxmWLKLI K9EOqWgfw1s XxSndMATMb0K YIgR6Z5OaF2 RJKPqIdvXU jxQeF6zi4h joGuaqEiA3 TPxaUodM6h RHVZNlfuV9hz 32QnLZi8Ub 90GsHuYxIG EXen6uBEgFqw bb4pbWWH73R 9yj1w5srTP NpBac5c47i duTgLo6aoP nkQahJ4BR3F C1PpiMT0N72E t1yNttSYZAV voxjlm8fV1B 3zdvfzwX2360 DElst863Ooh 7pDbLoggZeGj GJeOy3QzcW5 ElGjJ1hOeza y9LNf865I5Bm IXONlKM0wa hZZviNDs9bfW gInPzn5bI8 AfS7FewNLj yOrbgjA3GdB 5diClgBRSkL KKC37B26Vn w5u7ncsXAG 9tEyXHJtuXwq Oblohi5DtO i9ObpExpE9Yb aIvWMxOYBU0 oFA1mSwM4I HT6YgiODhDC bjo45v9j3Po5 ipT5O5n1oxq UGTuKBQ7QF I7GYUuInAKk DJ3OZL0Gon8X 6M4Jie7Fzx1 wbrOUl10OH n9ClRrpSLqjX FAp7TlayGijr 8X808BJO0r4H sdPfkZO3LSFq Hmn3vi3xi4AK QiEkReUYOtG URY9Mdn1YQBi QeRmQ3f6pd usskpqCxrU58 YfpGgFARTwPY QJSzkQGXvP4 8HNxmDCAcarX pjb02GMQ0S hWcNCRd4nD MC162F0xYbv V1J6dW4EfxoE oatT1E664i9 hDtL9JsQTG TPFZyWTvaN2 MoxQ2FGH8p5 qz4GuJrVTAX Ah9IOgMp8De ilDSN2wfKiIg 8Sy3A6o39Vbu 7ILvQG5oyP QbCGnZEKqVB 70kIYeVOUP CWSj240lXT mwv3QqwiVE9S FAtycb7NUhA4 gl1GoM4t15rq ab2VmkwJ2VfB KxrR9zikqou PMaYszd62BR7 QiAUWy4nJRT JYQ4FBHjukI VFoF5fu9cpNA T0PFhvXuyl HakyXKs3IKGV Y2ZEJIj5nRKV MYUCyOJxMGH qyD5tLDd1b nHqyZqG48Q LTCaWaKZpJ6 ZRJkQaYn6L0 hAJ2R9Ls1fFQ vinKUV9UzV tM8ZPwrwdlH GkFElRX8bx kk1MpSNAFScV eU9rUDgIjPNL aFsWF1gFb6 trGin3Ut7iJg 4u1xdpdDOm7 sfu7glt8Z3 AWaJXABeXFr3 Zuzc2pHFwD6n RzebkuJxdSE Etok5d4IfB3O uxG6Vcv7OsKK YR3sRIS6Wh9 KcNzNzI7I6x pfvIXSB13Rrz 5iGI3eRYU4 WsNVRf9fvFV5 i4RagWOiSj QGRNX0GpcMc LzAHLwfXSapL gjHSXJSRhN jNuQGsG7Yy3 lLVmlU8CWrk kMvojcN92N EcPM7JqzvGPl ajjD3Yg8E7a4 ecyT21bJ790D GG140ynTTa PO3bKFK4q0Pe 17pYV6XQK94A D1ynPGNr4HeM ffG6ivwxol1B NgqqN81WLUO6 809StKpE7eKZ WlAr05ZVwn 9GdmPt62mNFI fo7zjFHR2q C3lmugrtbp m3sygl2jbit 4UvBwRKCMC EV2aego5yt lT9t98NfwO 2MADGrLsq5QZ yt8EtExdOJhc YhIKjwH0vXhY XtSBKXQRBTSe OKRrkltSuyuh wMMjy07nsy7O TwI0Uzev75Ij 9AHYYbdqo0uT aAWIiIcNIoY 5feNXcXHWJ Sx9nla0UoXW4 BPByKvcnxN8 XfTWlVxxvHN QRnrYtjbTk3z tMWXEoEjYYM FVKkvd1ciU 4KPlPe1cyfNU PE2Xk4k0NFHb esd9eN3ljHjt gs1nF2OAzw DWjFp6FTNtYb tft1GTOsK7 4X8RlnL3uXZ YHgc7UW25BJ mkSS663MRB 44N3A8DG9Zx RShroIrmXg34 kFIbwq89iC 92BZxpFHID JYvwfN664yl4 vMydv3pl3zNF eytjZQMhNd3C b3lUIV9q8e BS771tbw8Rn ouAKByIWK1 1JMfWW0fuG cK66nWy6y4Yg DbFXbHIr9xBf YC8AhGMda9 jkfEOJfKCdi HAtkiEFv4MJK kwAHCS6BsGPL OiDluZItEhT lGkBuX3K8mu JYmQ2622nWB vUjbz52KKF8 ulJD1VU9O9Yx Kp8Pwj6m6y wPbXOHxgs2 U4Rzc3XMguct zJG8aPDdvrG yqyLrKebBGfD VgQAVfteNz jQjCE2acvz lIGja8TKTO YdkwD1KfVL2K FtgVEbkNZ10 ZDEoyzwmFq SoCMeozf7X irNhQ5x13sG uhMhZA2d2s8d 8Sav3ZtZWa ynQn6rlIHS 4ZHk6DAf19a cqlRGiPUDM gLFyYEJs6mI Ur0v1jfPUEhG sHFNbBf3FX whYTqPmBySG IiPnxa2IVJ TCOgAfPrtz BF4OlIu7IO SFRafml3dfI u2qz9SwPk3A QLRwRXHqdZ EmRAlk74call 03yfj6cHxHMC 3cUJatSeYm MeiwnjJsow aPttmDNIb0fI IL0rKWiakeM NoNhGfq8Went NgpNb98FDnW JeuqlUxcyv EED7WTLvKC qud6VUf8qP0l RkOeb3huhu 59FqpUu8lP1 dgPDaxBNAsg hOi8VhfINsS JDDUv3aUx7EM 2zPYKdGVcV2 D7CHL881Fq jWNoGpDb0W9q Gs7S1pXQfd u56LnsECW3d PKAVLfZyWouC Hne5oVamp1 M9PlVhKVbn YJYuQrO3hZtS uKkFyvjJLw oBikJ0alZ5we xiMhOZiNAzr NxWyhA3O8qL cQHk799mbLx QN9TZUd7Z86O IJHfWr72RJ o8uKxAkf3q WA27onQkw23 FRzJjcBt41 mimwmG3GjF b6kG1ujuaWs 4FCbN0xsmsU 0A83yxCDZS YtAxQXTquzb omnTijYhWc KbI0fKN3Iba bfMSRkpD2j3F uYrw9CJ37D uecuufjADS6 6FyEHSSHD3 CutorAfw6oh QVJrilm4Wli fOjJl548Uwqp ycrEtWSJhC ggNAMcvxLg 9RvfYPIXlVk csPjfFbI8x9 4kbKQKG6gt EY4fh367qKHV Ju1BsINxGyhL m61m8CXFh7 K4hniXF3gKP mp9nq5qhRMD tyjthfIzoN RdGMXNTTbaZE PHB0rIbySt 9cFYZtW4yCt alWyi8UgpR9 YX6s9F5egVhg ytHGVAskcJ7 dqxH99UX0Q ns0pwcsQcYxo PEnmc3y64a KCzMFW7RQJFl ANtUyiwZ74A Bl0qHq55iF 05HYo6OB1WqA OY8nj14O7Ezy odcHTeghiyO 7XQbVcgvgwv QcRYP59FCkmg mvT2lNuG8Xlz 31ecp8RBDFy dEG0rp2E5VjQ kaLYShFTHje tFoUcF2KFv ROq5ocOHrnLH bUBh36omju3 ILWiTinm1t 3WTIRx6GenVz Ls9GQj4cqY MoicUf86vcbq oac9pmSYrrus e6LGkBRUXEy 799rAGBTMBRE 8cqABpge21i frs7j4Cpy8 MCxJHLqtLDp6 o5LCsT2ev8Qn uggsUVzMnqb AYrYaNtOlE hMNCifkUzMS OwYtQttbvpgg ivtKDhwkg2i EiYcYHVkUi uAwwTYOET4DR Bynz5J20wz paKWTlPId8G3 BmM0bgj9yrgd 0mCJL3SDWl tpuIeozvYgD abAL8KDqvV XlQ9URd98Fak CMYuNzSVK74 XLVYIo6CaJ yt3TF0isQX Nu5hAlWWekBg nrMKFFGCQL5 SgzWCb50H5os XGPN6j5LueQ tXGjp3fcMH YO7mCVcRt6d pXoKYecS5D Ky7p2Zrdza QExoR1G0yF dL73Jq9psnW xQcN3ansbgon ETAXknxTAp uZ9Zhw0zDYXy L9hTiJJtYf 0Lc5TR3qZlH fSQ9mO3puOlY 9JFYUvU1mV Lmj0zcT6iR pDSg0v3ulma nFuL3MTgZpy7 HkUgVvKZJ4sB HC0TS5XmacU nWrANScCCa1g 6B0wWlYfS6 zxg0s7Nix1 o1qEVLakxFw 8Z3DgEIuM55 AUI5hOeNGc ftgzT53wDTjq h82aPQp2n4 wJxOyEqKqQ K4rbvVRFRG dDTnPwjk73I0 fxL4LJ2GNuT NsjZNKhDsgd obMzVGWRgU ydlL83HD48PT oiuBSSInNqR oSIuXWkKGv6y 9P7zl5mYmJ 3Ao6V1QWbv vO8DZYvfMbmQ 2RnjDElfCf CptzUiY4PBC vRmKTBwkL7T goCcA9i7Oq ti1fv8IT1Z5 A1SEpXqJAFSM Kht8JrLx4v 8pTjbUfec7k xqLH4AnS5R 7a61Cqouzq WEvoQHdmbt 0ht1fbE2OMIv e3B8NmroTn Pd7aHuREDK hdx8jtcKPL JwW57R4WObC CGpVuhruKSAz 9r4w9up9VL gT4ibqo2Cu 84WdHb0TCD gOCW7xvYnnk wOMwyqC39N3W y5YWlndrajyr BdzUyI7rC8AW leV6BksXJy0 CRkKhKDlcBj CBkIxfbhEgBy IC8lafc2eC iPgyHbUO5cV deACeffXr1PK wP7hKos4cQJ LpWpdtVcDlZj q8iqP9fwIyUx 70JvjIY0Vv vhpVu5hk41Pa znS4ZSJjBo jogmAezS1RXZ NxRX9QZxCm DqtMxn5SLtn hKoqu6Qe2ee kKvmlGkjiof fk2WdxH52dz J9zkj5Cohv bMF8LGNgTE7z 0j4nuW4eMnH gf2OYGF3RsD X44Nx7daXu wnr4oqAv1Y4A w7NgarFZOFv vNXOsJUAmFE7 rsbyl0MKXM zUkIEfBWDR HkBzyPG1dtv FzT4d2q8SwS k5lr9YwauR 6K5ep2uloWH 4WrEUzIUjf BlxslQfwSI JhemdHdU5Pn e2Lg9fDvbb MQqRK6AEqug YcNDWS2A4xXr YtX86wXg5MN XClEdpalvX UlqzqUrZTmEF qSab9Vj6xAPE OsnosR2b5V RM71V9C4Rs kM1WancCOop hBh8BM1rKM xyn6jivWFoeo GLG4kcVAILLz OyETjWybby vSmP1mJTa1qs GxwZC6qNuu56 JffsHIcen6ZT 5g41XoR2tN cj5rsmAT3gb 5WNhudV6hV ZgzBe3ZiDlV mNv3e5BliW NWgCNlD6lwGI XhjOrKXM9T Dbdjdgoo4c1N iZF48bUgc8WH X8ZSxdwacw ziCTSDobKYjk lMzJbUpcB5N GNWH56MRjrnC Up1evZqRSeb O8o9RqRd47YJ 0jP5oSTlme Fp4dWs465G d2tJwKnM2l1r vYqvEu82auc PYA9uAPj83f izQnxixw4yto ZSeWuJcagZ tCiSSLhEdEf2 vOlSVMNXVL RMLvAeQL5Ng HUlTZS6TJNb KsWSPepd9yf hrgWNAS4oER kSFCwuni5v YxAbsLjTju iwn0QWfhs49I AST1LnQC0AD ICtwnCnr81B lL8x2E3zIu3 flgFaGERq7 bpugHcPtZdc inIfcm7tpAZu gDDBhhF5TenX 9Yzfomzyj1FJ kv424PxmkVK LzGiLycw5wM zcYpPg8hif AcfIBY88kIa 7VIEoHFli6 IaDP8jJwsxEW YezS6JMteK7A N3Lqs4fdwSM1 MAzJkplaTtAc FFNGbg0tAuXD my9NVGQBBEm9 WkWeLU2CEmD IStFmshnxD Mjcon25cuZ8 xXtqSU49a9F UnuFHLvS2vN 358cghv4Oj zkOHwTCUza ur20sE5u0iDo oKqNlBy2nDC H0un1giqYAEI A2rVI7NpsCt 8QCljhwt9M 2icsBGuYvR6 vzyFB89c9H e5ispRRXh3vK 5MeiMhZorFv IU0jxa8Kft lmLf3aVhRU RrmXXDGPV6g i1wmkAP3Ly5 21XvxFnekwh l0aHKiXdt11 5zU28YhjYG vWIWUVBoX2 sZrYa3Q4gb VHAVUItODd cMYUfAz8MNG UPKxJRqcSa 0kKb9q0WrFWS KXSxgsL61Xdk lONxQ7BqnoD kam9RNs5z37 JmVLNXF8L6w ADuVVs1MZsU cXYiZVFl1p W7LfxJPtnkJ SBelJkA5jdaY FcPUnZ6foN 5DRbTWjoo6 xjUDHDAlYaT OHHER5sDM6P 1KnXO9YVxmx 672sG31kJoZ UvJXcwnm0pE qjlcAQvMiG 3gNeD76ZwN L78GRD0LjXE QW0wxBvLh6dj QtPdeCMi9aie uZspaiRM9z ZA8sZYIUKb ykNVq9WsQQ1X V4EPzcFbqEt eTBQIHA3xwmE HGVKTi7Gbg 6LOuV2Ij0I PEtwkuzFxr KYgujtcBeByM 1ZKjNXhK6xf kWZv6PkKqWX iG6PdP0R4Da 37Brx1DIzTTe h641mdBm67no H6yY03PNXkZ e7lblSYqnKe 9oEmMG7Ev0 6q1xJBlwj6 aAywUEYMyL WZy76Nf7ueP fMaRaSc2K47 LsP8gp3GAlV wUuAV8OiiM m9HlNUFzLjc RqSaX9Gi2zj bgGorUTOLJ Rv5MJpl6sVFp 0zFOyESAeAO nQhmgisigWMq xbaScF8jPk0 3tqtAzusQn OMm9EDzT2fd yKKaNcgtqr RaoXNym9QJR h5bUJZqkPU quQWbvjSshym LtEpeeXA2Sz 8mcmUCEXCx2S ffYsyyO5yib 2DStt2SC77e9 t24FvKQbNpwb g4ZXQd9ZXk WuuLpaEGrTrf vqc0YuBqZEq xB3WniM3SD 9Q4OEqP6LV Yu9ZzS17Xyzz JW46gDnStpFT pr5oqC8LFMx jgtPzHEjjf wLHX2KIl7HRz qo8Mrx7xVA 1sFuIDmDSUJ2 IByqa5EQCLk 8tezEQDThSf 1J33dViasr2P mt4oKaqJNi 5WDEme9vZwi0 8Ar1whHXxPS Nqs5MzvnWV ekWjXqE9NN 2UFh7366V7z j5AKfXAXrIFw 73Ye2aIaXz0 ORTm8pO7gei 2MEXhQkYwTb 1qUrU8dKjq Zg5WXT48fB OdMKZRefaA K8jkGWhaaws 5NjY3c6bVuB1 YYMzKrsde8Yz syVbampAG52q RBONsK18TWk xxicRDZT83n JwTrrxpqhxK WYPSywJOG8 ePOfnQmZh1tO DQmihAsjeti tfEaD22thIOL 1wJkhjM258j kGM5On4RGg QsiumtMVEP MwmDsVT4IAH ci9DV4Bqag09 l6qFLt3hvTt sa5LBaWB6fmd QYzVsuB8dI3 puWctW5e3dm 5I9nWD0mo7u jcOpdbuxQ2vf tYUcR4Ppc4C6 VT39bqvboYRO U1wtH0scH4o sJSnNv9p8lz wAjX5vI8nZ 9bODKvEnRu8 BW5HsGOx7D9S EZjlPMcLPts2 wFvqUAxbhQ LdN9QinG4sxx zC8HmmmBz8bl Pi6MrrqQjVp QcH2KfvWSU Sro57SDHdu Tb6XrifBzMD7 1bht5wfFNKX R4tCVnKSbrSS DbYSHIWbeh AI0QhImG61B cJ1fYjMxaP2Z JEbtfFmsls 80UljUhN1ZMs cNplwKzjUl3 AUYaMtuIYLy BSkaQMpxvaBH DIVtSg6MZc G2LjnRN6kt A1HlvaDJvWJw qDja4Dvo9K gG6GQuIXUndn AqEQd4hl496 Erdn8qDB4bmB C3CBIH6aGBeD a4Qysl6ndi0 fFAz0p7Asx u6EWxL357BJ VARWcoTsEnhR 70uCrFPFmW lZy7RK0zCbDj dALfggZCFgJ GJzVdPnC67Ql ZFL2MNhxbR PXlCpvDFCU ORmjzpVzIj R08zOVB3FD 5Gz1F2wqe0 YiT8ygcy3ftz x4baoPNyUNx doIK26b2tEH 9hchgd1FmWe KkcskjPt5D vwILxcm2Ng4 yIB6sWMZHO gWLzMQQHkwx FxfO0C9EvWXj 03dVurSrsRKq Pg0bELButal O6TqZt6Wzz pCVvZGoP9x0 f5UG4zenytT kysmolOmKesE i9jkRm8cXnbW SZeU9aAMd3M R9bQilQMPw2 2pApTgohKth wcCOi9FIzHa 1pKcySfIV8h fGHHlwHLmIG 8tNWzQ7Xfars Sj4bsQhVoU aUcyBaAVowNX EJrlLw6gUs Ei75R3ZuTfdA 6LXfuUpBsdh HJbsCelTBM MDtEub3TEJ45 YVF7edy7gpkv pXzAjhkYeJ1 h0FsDSKiP4g5 1IPO4gRz4Ztq fxjpaoiwCJd 3jzUt10kwy rP00J0gjroH6 QPxLJO5zscM fKduBoK8mb cMEApRvJ1L zPtTa3JeG4 DChHszVK7ir yBH9fOMtZNOb f1W8LN2YsUH VBPXEJ7BrCs IKrtBMvcGJx n4lfZzopUULP 5iDFwLiHBCz Gr0E6K2poCY 3BDHVVaBsYF K7guOrjULcuC DehTOIij7Ywd sOrm5VMmJSZ0 RphB8JSUcY GcNXYNjTtdb3 4PIXH0CNXRci UlZSk3CbNdM wYiKQTJrz50 Qd4Mnaq8os p6LBFggPcTo1 UoOGRRACw0w2 khZAThUEWIE uJJBkXinahoW N4UXsjFhFM 3y9lXJJ6aLZY BaCGbMmvC1d0 gSayMUfQFF FppDlXDpVqG BQ6WSk0MSn WXrSM9VzGPk Ljl3MCReaw kc8hpsYriQw8 JKU2vfLYEnJ X9mMy7yJfmOD talNHICbQMG g0cVg1rlFM 9zRpRTVK85 52BiXrqHdtF UuNENqv0QK nF5FUHR8ei RS7KeYFr9P WwvILhOAhn8 bM7GED3gE3O RXv7SjxAMaG ZlpvqX6TN4BK SnfyrWLaBV7 wHT0kDQjnE MuadnoTk3O dOKGCKFbVfo pmxsBZXPW04 iJf7hNhM0T pWNUouQD1B oMqbDsFrDh6 iiKBbgYNbof7 qxWGZd4LKHNV duHE2XA0i4k djEnsclGQfXf IQJusWLmXuz aZVjTc3LS1e ilZE9Sm14MTV QXBBB3pIHW4M s5MutksOvH */}",
"function changeUppercase(str)\n{\n if(str==\"\" || eval(str)==0)\n return \"\\u96f6\";\n \n if(str.substring(0,1) == \"-\")\n { \n if(eval(str.substring(1)) < 0.01)\n return \"\\u91d1\\u989d\\u6709\\u8bef!!\";\n else\n str = str.substring(1);\n }\n \n var integer_part=\"\";\n var decimal_part=\"\\u6574\";\n var tmpstr=\"\";\n var twopart=str.split(\".\");\n \n //\\u5904\\u7406\\u6574\\u578b\\u90e8\\u5206\\uff08\\u5c0f\\u6570\\u70b9\\u524d\\u7684\\u6574\\u6570\\u4f4d\\uff09\n var intlen=twopart[0].length;\n \n if (intlen > 0 && eval(twopart[0]) != 0)\n {\n var gp=0;\n var intarray=new Array();\n \n while(intlen > 4)\n {\n intarray[gp]=twopart[0].substring(intlen-4,intlen);\n gp=gp+1;\n intlen=intlen-4;\n }\n \n intarray[gp]=twopart[0].substring(0,intlen);\n \n for(var i=gp;i>=0;i--)\n {\n integer_part=integer_part+every4(intarray[i])+pubarray3[i];\n }\n\n integer_part=replace(integer_part,\"\\u4ebf\\u4e07\",\"\\u4ebf\\u96f6\");\n integer_part=replace(integer_part,\"\\u5146\\u4ebf\",\"\\u5146\\u96f6\");\t\n\n while(true)\n {\n if (integer_part.indexOf(\"\\u96f6\\u96f6\")==-1)\n break;\n\n integer_part=replace(integer_part,\"\\u96f6\\u96f6\",\"\\u96f6\");\n }\n \n integer_part=replace(integer_part,\"\\u96f6\\u5143\",\"\\u5143\");\n\n /*\\u6b64\\u5904\\u6ce8\\u91ca\\u662f\\u4e3a\\u4e86\\u89e3\\u51b3100000\\uff0c\\u663e\\u793a\\u4e3a\\u62fe\\u4e07\\u800c\\u4e0d\\u662f\\u58f9\\u62fe\\u4e07\\u7684\\u95ee\\u9898\\uff0c\\u6b64\\u6bb5\\u7a0b\\u5e8f\\u628a\\u58f9\\u62fe\\u4e07\\u622a\\u6210\\u4e86\\u62fe\\u4e07\n tmpstr=intarray[gp];\n \n if (tmpstr.length==2 && tmpstr.charAt(0)==\"1\")\n {\n intlen=integer_part.length;\n integer_part=integer_part.substring(char_len,intlen);\n }\n */\n }\n \n //\\u5904\\u7406\\u5c0f\\u6570\\u90e8\\u5206\\uff08\\u5c0f\\u6570\\u70b9\\u540e\\u7684\\u6570\\u503c\\uff09\n tmpstr=\"\";\n if(twopart.length==2 && twopart[1]!=\"\")\n {\n if(eval(twopart[1])!=0)\n {\n decimal_part=\"\";\n intlen= (twopart[1].length>2) ? 2 : twopart[1].length;\n \n for(var i=0;i<intlen;i++)\n {\n tmpstr=twopart[1].charAt(i);\n decimal_part=decimal_part+pubarray1[eval(tmpstr)]+pubarray4[i];\n }\n \n decimal_part=replace(decimal_part,\"\\u96f6\\u89d2\",\"\\u96f6\");\n decimal_part=replace(decimal_part,\"\\u96f6\\u5206\",\"\");\n \n if(integer_part==\"\" && twopart[1].charAt(0)==0)\n {\n intlen=decimal_part.length;\n decimal_part=decimal_part.substring(char_len,intlen);\n }\n }\n }\n \n tmpstr=integer_part+decimal_part;\n \n return tmpstr;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate Reset Password Code | validateResetPasswordCode(params, cb, errorCb) {
const url = `${endpoint}/password/reset/validate`;
client.post(url, params)
.then((response) => {
if (cb) {
cb(response.data);
}
})
.catch((e) => {
if (errorCb) {
errorCb(e);
}
});
} | [
"function verifyPasswordResetCode(auth, actionCode, continueUrl) {\n auth.verifyPasswordResetCode(actionCode).then(function(email) {\n window.frames['embeddedpage'].contentDocument.getElementById('account').innerText = email;\n }).catch(function(err) {\n alert ('Expired or invalid link, please try again.');\n console.log (err);\n });\n}",
"function validatePassword() {\n const password = input.password;\n const confirmPassword = input.repassword;\n if (password.value === confirmPassword.value) {\n confirmPassword.setCustomValidity('');\n } else {\n confirmPassword.setCustomValidity('Passwords Don\\'t Match');\n }\n}",
"function sendResetPasswordRequest() {\n if (validateInputFieldOfResetArea()) {\n /* To show the progress bar */\n showProgressBar();\n\n $('#new_pwd').removeClass(\"error_red_border\");\n $('#re_new_pwd').removeClass(\"error_red_border\");\n /* Used for Disable the button and coming from utility.js */\n disableButton(\"reset_pwd\");\n \n var request = {};\n request.userId = user_auth_obj.userId;\n request.applicationId = applicationId;\n request.locale = getCookie(\"locale\");\n request.newPassword = $('#re_new_pwd').val();\n \n var call_user_reset_pwd = new user_reset_pwd(request);\n call_user_reset_pwd.call();\n }\n}",
"function validateLosePwdOne(form) {\r\n var flag = validateField(\"#j_username\", /.{1,100}$/, usernameErrormsg, true);\r\n flag = flag && validateField(\"#j_checkcode\", /^[A-Za-z0-9]{5}$/, checkcodeErrormsg, false);\r\n flag = flag && validateField(\"#j_smscode\", /^[0-9]{6}$/, smscodeErrormsg, false);\r\n\r\n return flag;\r\n}",
"function validateInputFieldOfResetArea() {\n var element1 = $('#new_pwd').val();\n var element2 = $('#re_new_pwd').val();\n\n if (element1 == '') {\n $('#re_new_pwd').removeClass(\"error_red_border\");\n showErrorMessageofFieldValidation(messages['login.alert.newPwd'], 'new_pwd', 'wrong_resetpwd');\n /* Used for enable the button and coming from utility.js */\n enableButton(\"reset_pwd\");\n } else if (element2 == '') {\n $('#new_pwd').removeClass(\"error_red_border\");\n showErrorMessageofFieldValidation(messages['login.alert.rePwd'], 're_new_pwd', 'wrong_resetpwd');\n /* Used for enable the button and coming from utility.js */\n enableButton(\"reset_pwd\");\n } else if (element1 != element2) {\n showErrorMessageofFieldValidation(messages['login.alert.validateNewPwd'], 'new_pwd', 'wrong_resetpwd');\n /* Used for enable the button and coming from utility.js */\n enableButton(\"reset_pwd\");\n $('#re_new_pwd').removeClass(\"error_red_border\");\n $('#new_pwd').val(\"\");\n $('#re_new_pwd').val(\"\");\n return false;\n } else {\n return true;\n }\n}",
"function VerificationPwd() {\n const pwd = document.getElementById(\"pwd\");\n const LMINI = 8; // DP LMINI = longueur minimale du mot de passe\n\n //DP si le mot de passe comporte moins de 8 lettres alors erreur\n if (pwd.value.length < LMINI) {\n console.log(\"longueur pwd NOK\", pwd.value.length);\n return false;\n } else {\n console.log(\"longueur pwd OK\", pwd.value.length);\n return true;\n }\n}",
"function resetForm(resetCode) {\n var logindata = document.getElementById(\"userlogin\");\n switch (resetCode){\n case 0:\n // Reset all fields (usernmae, passwords, and major)\n logindata.elements[0].value = '';\n logindata.elements[3].value = 'default';\n case 1:\n // Reset \"password\" and \"confirm password\" fields\n logindata.elements[1].value = '';\n case 2:\n // Reset just \"confirm password\" field\n logindata.elements[2].value = '';\n return;\n default:\n // log invalid resetCode input and return\n console.log('#resetForm: Invalid resetCode ' + resetCode);\n return;\n }\n}",
"function passwordReset() {\n app.getForm('requestpassword').clear();\n app.getView({\n ContinueURL: URLUtils.https('Account-PasswordResetForm')\n }).render('account/password/requestpasswordreset');\n}",
"function onConfirmPasswordChange(p) {\n let val = p.target.value;\n setConfirmPassword(val);\n setEnabled(password.length > 0 && name.length > 0 && email.length > 0 && val.length > 0 && number.length==10);\n }",
"function checkValid() {\n\tif(!document.getElementById(\"email\").value.match(/\\S+@\\S+\\.\\S+/)){\n\t\tif (document.getElementById(\"email\").value != \"\") {\n\t\t\talert(\"Email Format is wrong!\")\n\t\t\treturn false;\n\t\t} \n\t}\n\tif (!document.getElementById(\"phone_number\").value.match(\"^\\\\d{3}-\\\\d{3}-\\\\d{4}$\")) {\n\t\tif (document.getElementById(\"phone_number\").value != \"\") {\n\t\t\talert(\"Phone Format is wrong!\")\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (!document.getElementById(\"zipcode\").value.match(\"^\\\\d{5}$\")) {\n\t\tif (document.getElementById(\"zipcode\").value != \"\") {\n\t\t\talert(\"Zipcode Format is wrong!\")\n\t\t\treturn false;\n\t\t}\n\t}\n\tvar password = document.getElementById(\"password\")\n\tvar password2 = document.getElementById(\"password2\")\n\tif (password.value == \"\" && password2.value != \"\") {\n\t\talert(\"Password is empty !\")\n\t\treturn false;\n\t} else if (password2.value == \"\" && password.value != \"\"){\n\t\talert(\"Confirmation Password is empty !\")\n\t\treturn false;\n\t}\n\treturn true;\n}",
"async handleGeneratePasswordResetCode (req, res) {\n const self = this;\n const userId = req.decoded.userId\n const password = req.body.password;\n\n let baseUser;\n let code;\n let email;\n\n try {\n baseUser = await self.models.BaseUser.findOne({ where: { user_id: userId }});\n email = baseUser.user_email;\n\n try {\n // Verify that the password is correct.\n await self.models.BaseUser.prototype.checkPassword(email, password)\n }\n\n catch (err) {\n return res.status(400).json({ message: 'Password doesnt match.' })\n }\n\n self.Crypto.randomBytes(20, (err, buf) => {\n if (err) return res.status(500).json({err: err.toString() })\n code = buf.toString('hex');\n self.Redis.addPasswordResetCode(email, code);\n return res.status(200).json({ code: code });\n })\n }\n\n catch (err) {\n console.log(err);\n return res.status(500).json({\n message: 'Could not generate a password reset code'\n })\n }\n }",
"resetPasswordWithPhone(phone, code, newPassword, callback) {\n newPassword = AccountsEx._hashPassword(newPassword);\n callback = ensureCallback(callback);\n Accounts.callLoginMethod({\n methodName: prefix + 'resetPasswordWithPhone',\n methodArguments: [{phone, newPassword, code}],\n userCallback: callback\n })\n }",
"function setNewPassword() {\n var Customer, resettingCustomer;\n Customer = app.getModel('Customer');\n\n app.getForm('resetpassword').clear();\n resettingCustomer = Customer.getByPasswordResetToken(request.httpParameterMap.Token.getStringValue());\n\n if (empty(resettingCustomer)) {\n \tresponse.redirect(URLUtils.https('Login-Show', 'TokenExpired', 'TokenError'));\n } else {\n app.getView({\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n }\n}",
"function VerificationConfirmation() {\n const confirmation = document.getElementById(\"confirmation\");\n const pwd = document.getElementById(\"pwd\");\n const LMINI = 8; // DP LMINI = longueur minimale du mot de passe\n\n //DP si le mot de passe comporte moins de 8 lettres et que la confirmation est differente au mot de passe alors erreur\n if ((confirmation.value.length < LMINI) || (confirmation.value !== pwd.value)) {\n console.log(\"longueur confirmation NOK\", pwd.value.length, confirmation.value.length);\n return false;\n } else {\n console.log(\"longueur confirmation OK\", pwd.value.length, confirmation.value.length);\n return true;\n }\n}",
"function validatePassword(pswd) {\n if (pswd.length >= MinPassLength && hasAlpha(pswd) && hasNum(pswd)) {\n return true;\n }\n\n return false;\n }",
"function lengthError() {\n const passwordLength = document.getElementById(\"passwordLength\");\n if (\n passwordLength.value < 8 ||\n passwordLength.value > 128 ||\n isNaN(passwordLength.value)\n ) {\n alert(\"Error: Password must have between 8 and 128 characters.\");\n } else {\n checkboxError();\n }\n}",
"async onForgotPassPressed() {\n this.setState({isForgotPassPressed: true});\n // remove the password field\n this.setState({showPassField: false});\n //send 6 digit code to email through forgot password route\n const authToken = await getAuthToken();\n await request\n .post(`${REACT_APP_API_URL}/signin/forgot`)\n .set(\"authorization\", authToken)\n .send({\n data: {\n email: this.state.emailInput,\n },\n })\n .then(res => {\n //show code\n this.setState({showCode: true});\n })\n .catch(err => {\n console.log(err);\n });\n }",
"validate(value){\n if(validator.isEmpty(value)){\n throw new Error('Password cannot be empty buddy!')\n }\n if(value.toLowerCase().includes('password')){\n throw new Error('Password contains \"password\" buddy! Try something by your own!') \n }\n if(!validator.isByteLength(value,{min:7})){\n throw new Error('Password cannt have length less than 7,buddy!')\n }\n }",
"function validateForgotPasswordEmail(email, id) {\n removeError(id);\n $.get(\"../../php/common/getData.php?table=user&column=email&value=\" + email, function (data, status) {\n if (data === 'false') {\n isForgotPasswordEmail = false;\n errorToggle(id, \"Email not exits!\", true);\n } else {\n isForgotPasswordEmail = true;\n errorToggle(id, \"Looks Good!\", false);\n }\n let regex = /^([a-zA-Z0-9_\\.\\-\\+])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;\n\n if(!regex.test(email)) {\n errorToggle(id, \"Invalid Email!\", true);\n isForgotPasswordEmail = false;\n }else{\n isForgotPasswordEmail = true;\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
API calls associated with SiteWhere device assignments. Create a device assignment. | function createDeviceAssignment(axios$$1, payload) {
return restAuthPost(axios$$1, 'assignments/', payload);
} | [
"function createMeasurementsForAssignment(axios$$1, token, payload) {\n return restAuthPost(axios$$1, 'assignments/' + token + '/measurements', payload);\n }",
"function createDevice(data) {\n var device = new models[\"Device\"](),\n deviceData = networkInfo.device[0];\n\n $.each(deviceData, function(key, value) {\n if (key !== \"value\") {\n device.set(key, value);\n }\n });\n\n return device;\n}",
"function createLocationForAssignment(axios$$1, token, payload) {\n return restAuthPost(axios$$1, 'assignments/' + token + '/locations', payload);\n }",
"create(req, res) {\n const userId = req.param('userId');\n\n if(req.token.id !== userId) {\n return res.fail('You don\\'t have permission to do this.');\n }\n\n const allowedParams = [\n 'type', 'name', 'context', 'uuid'\n ];\n\n const applianceData = lodash.pick(req.body, allowedParams);\n ApplianceService.createForUser(userId, applianceData)\n .then(res.success)\n .catch(res.fail);\n }",
"function getDeviceAssignment(axios$$1, token) {\n return restAuthGet(axios$$1, 'assignments/' + token);\n }",
"async function addNewDrive() {\n const driveName = document.getElementById(\"drive-name\").value\n const userPermissionList = generatePermissionList()\n const data = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n info: {\n drivePath: path,\n driveName: driveName,\n permissionList: userPermissionList,\n }\n })\n }\n const response = await fetch('/api/newDrive', data)\n completedSetup()\n}",
"function createDeviceType(axios$$1, payload) {\n return restAuthPost(axios$$1, '/devicetypes', payload);\n }",
"function construct_device(devices_data, device_type){\n var device_data = get_device_data(devices_data, device_type);\n var device_map = {};\n return construct_device_inner(devices_data, device_data, device_map, '/');\n}",
"async function accountsCreateOrUpdate() {\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 = { location: \"eastus\" };\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}",
"function addDevice(data) {\n try {\n if (data.id === \"SenseMonitor\" || data.id === 'solar') { //The monitor device itself is treated differently\n deviceList[data.id] = data;\n } else {\n\n //Ignore devices that are hidden on the Sense app (usually merged devices)\n if (data.tags.DeviceListAllowed == \"false\"){\n return 0\n }\n\n tsLogger(\"Adding New Device: (\" + data.name + \") to DevicesList...\");\n let isGuess = (data.tags && data.tags.NameUserGuess && data.tags.NameUserGuess === 'true');\n let devData = {\n id: data.id,\n name: (isGuess ? data.name.trim() + ' (?)' : data.name.trim()),\n state: \"unknown\",\n usage: -1,\n currentlyOn: false,\n recentlyChanged: true,\n lastOn: new Date().getTime()\n };\n\n if (data.id !== \"SenseMonitor\") {\n devData.location = data.location || \"\";\n devData.make = data.make || \"\";\n devData.model = data.model || \"\";\n devData.icon = data.icon || \"\";\n if (data.tags) {\n devData.mature = (data.tags.Mature === \"true\") || false;\n devData.revoked = (data.tags.Revoked === \"true\") || false;\n devData.dateCreated = data.tags.DateCreated || \"\";\n }\n }\n deviceList[data.id] = devData;\n deviceIdList.push(data.id);\n }\n } catch (error) {\n tsLogger(error.stack);\n }\n\n}",
"function assignRoomsToEquipment(drawingController) {\n var controller = View.controllers.get('assetDrawingConfigController'),\n eqId = controller.eqId;\n var dataSource = View.dataSources.get('abEqRm_ds');\n var hierarchy_delim = Ab.view.View.preferences.hierarchy_delim;\n var selectedRooms = drawingController.selectedAssets['rm'],\n blId = drawingController.buildingId,\n flId = drawingController.floorId;\n var bl_fl = blId + hierarchy_delim + flId;\n for (var i = 0; i < selectedRooms.length; i++) {\n var bl_fl_rm = bl_fl + hierarchy_delim + selectedRooms[i];\n var restriction = new Ab.view.Restriction();\n restriction.addClause('eq_rm.eq_id', eqId);\n restriction.addClause('eq_rm.bl_fl_rm', bl_fl_rm);\n var record = dataSource.getRecord(restriction);\n if (record.isNew) {\n record.setValue('eq_rm.eq_id', eqId);\n record.setValue('eq_rm.bl_fl_rm', bl_fl_rm);\n record.setValue('eq_rm.bl_id', blId);\n record.setValue('eq_rm.fl_id', flId);\n record.setValue('eq_rm.rm_id', selectedRooms[i]);\n dataSource.saveRecord(record);\n }\n }\n drawingController.svgControl.getAddOn('InfoWindow').setText(String.format(getMessage('afterAssignedRooms'), eqId));\n}",
"function setDeviceInformation(devPath,model,src,manufac,ostyp,prdfmly,ipadd,prot,hostnme,devtype){\n//\tvar devtype = getDeviceType(model);\n\tif(manufac){\n\t\tvar manu = manufac;\n\t}else{\n\t\tvar manu = getManufacturer(model);\n\t}\n\tvar myPortDev = [];\n\tif(globalInfoType == \"JSON\"){\n\t\tsetDevicesInformationJSON(\"\",devtype,devPath,model,model,\"\",\"\",ostyp,\"\",\"\",\"\",\"\",hostnme,\"new\",\"\",\"\",ipadd,\"\",\"\",\"\",\"Exclusive\",imgXPos,imgYPos,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",manu,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",prdfmly,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",window['variable' + dynamicDomain[pageCanvas] ],\"\",\"\",\"\",\"\",src,myPortDev,\"\",\"\");\n\t\tsetDevicesChildInformationJSON(\"\",\"\",\"\",\"\",\"\",\"\",devPath,\"\",\"\",devPath,\"\",\"\",model,model,manu,\"\",\"\",\"\",hostnme,\"new\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",prot,\"\",\"\",\"\");\n\t}else{\n\t\tstoreDeviceInformation(\"\",devtype,devPath,model,model,\"\",\"\",ostyp,\"\",\"\",\"\",\"\",hostnme,\"new\",\"\",\"\",ipadd,\"\",\"\",\"\",\"Exclusive\",imgXPos,imgYPos,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",manu,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",prdfmly,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",window['variable' + dynamicDomain[pageCanvas] ],\"\",\"\",\"\",\"\",src,myPortDev,\"\",\"\");\n\n\t\tstoreChildDevicesInformation(\"\",\"\",\"\",\"\",\"\",\"\",devPath,\"\",\"\",devPath,\"\",\"\",model,model,manu,\"\",\"\",\"\",hostnme,\"new\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",prot,\"\",\"\",\"\");\n\t}\n}",
"static createTenant() {\n return HttpClient.post(`${TENANT_MANAGER_ENDPOINT}tenant`);\n }",
"function syncUsersDevicesMeds (req, res, next) {\n const inputSettings = req.body;\n inputSettings.type = 'syncUsersDevicesMeds';\n const validatedSettings = validateSettings(inputSettings);\n if (!_.isEmpty(validatedSettings.err)) {\n res.json(400, {\n message: 'Invalid settings entered',\n success: false,\n errors: validatedSettings.err,\n });\n return next(false);\n }\n\n const { dataBridgeUrl, destHcUrl, guid } = validatedSettings;\n let url = `${dataBridgeUrl}/Patient?_revinclude=Device:patient&_revinclude=MedicationRequest:subject`;\n url = guid ? `${url}&_id=${guid}` : url;\n\n fetch(url)\n .then((res) => {\n if (res.status === 200) {\n return res.json();\n }\n res.json(422, { message: `Data bridge sends invalid status code: ${res.status}`, success: false });\n return next(false);\n })\n .then((fhirData) => {\n const transformFhirDataToHcSettings = {\n type: 'transformFhirDataToHc',\n requiredFields: ['piis', 'piis_demographics', 'phis_myDevices', 'phis_myMedications'],\n entries: fhirData.entry,\n };\n const transformFhirDataToHcProcessor = pumpProcessorProvider.getPumpProcessor(transformFhirDataToHcSettings);\n return transformFhirDataToHcProcessor.processSettings();\n })\n .then((hcUsersData) => {\n const syncUsersDevicesMedsSettings = {\n type: 'syncUsersDevicesMeds',\n destHcUrl,\n hcUsersData,\n };\n const syncUsersDevicesMedsProcessor = pumpProcessorProvider.getPumpProcessor(syncUsersDevicesMedsSettings);\n return syncUsersDevicesMedsProcessor.processSettings();\n })\n .then((message) => {\n res.json(200, { message, success: true });\n return next(true);\n })\n .catch((err) => {\n res.json(500, { err, success: false });\n return next(false);\n });\n}",
"function deleteDeviceAssignment(axios$$1, token, force) {\n var query = '';\n if (force) {\n query += '?force=true';\n }\n return restAuthDelete(axios$$1, 'assignments/' + token + query);\n }",
"function listDeviceAssignmentHistory(axios$$1, token, options, paging) {\n var query = randomSeedQuery();\n query += options.includeDevice ? '&includeDevice=true' : '';\n query += options.includeCustomer ? '&includeCustomer=true' : '';\n query += options.includeArea ? '&includeArea=true' : '';\n query += options.includeAsset ? '&includeAsset=true' : '';\n if (paging) {\n query += '&' + paging;\n }\n return restAuthGet(axios$$1, 'devices/' + token + '/assignments' + query);\n }",
"function updateDevice(device, payload){\n device.user_id = payload.user_id;\n device.uuid = payload.uuid;\n device.os_id = payload.os_id;\n device.createdAt = payload.createdAt;\n device.modifiedAt = Date.now();\n device.model = payload.model;\n}",
"function attachDevice(deviceId, client, jwt) {\n // [START attach_device]\n // const deviceId = 'my-unauth-device';\n const attachTopic = `/devices/${deviceId}/attach`;\n console.log(`Attaching: ${attachTopic}`);\n let attachPayload = '{}';\n if (jwt && jwt !== '') {\n attachPayload = `{ 'authorization' : ${jwt} }`;\n }\n\n client.publish(attachTopic, attachPayload, {qos: 1}, err => {\n if (!err) {\n shouldBackoff = false;\n backoffTime = MINIMUM_BACKOFF_TIME;\n } else {\n console.log(err);\n }\n });\n // [END attach_device]\n}",
"static addStation(req, res) {\n const { name, location, host, port, SSHUsername, SSHHostPath, inchargeEmail, inchargeName } = req.body;\n Station.create({ name, location, host, port, SSHUsername, inchargeEmail, inchargeName, SSHHostPath },\n (err, obj) => {\n if (err) return res.status(400).json(err);\n return res.json(obj);\n });\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.