query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
utility function to compose multiple composers at once.
function composeAll() { for (var _len = arguments.length, composers = Array(_len), _key = 0; _key < _len; _key++) { composers[_key] = arguments[_key]; } return function (BaseComponent) { if ((0, _.getDisableMode)()) { return _common_components.DummyComponent; } if (BaseComponent === null || BaseComponent === undefined) { throw new Error('Curry function of composeAll needs an input.'); } var FinalComponent = BaseComponent; composers.forEach(function (composer) { if (typeof composer !== 'function') { throw new Error('Composer should be a function.'); } FinalComponent = composer(FinalComponent); if (FinalComponent === null || FinalComponent === undefined) { throw new Error('Composer function should return a value.'); } }); FinalComponent.__OriginalBaseComponent = BaseComponent.__OriginalBaseComponent || BaseComponent; var stubbingMode = (0, _.getStubbingMode)(); if (!stubbingMode) { return FinalComponent; } // return the stubbing mode. var ResultContainer = function ResultContainer(props) { // If there's an stub use it. if (ResultContainer.__composerStub) { var data = ResultContainer.__composerStub(props); var finalProps = (0, _extends3.default)({}, props, data); return _react2.default.createElement(FinalComponent.__OriginalBaseComponent, finalProps); } // if there's no stub, just use the FinalComponent. var displayName = FinalComponent.displayName || FinalComponent.name; return _react2.default.createElement( 'span', null, '<' + displayName + ' />' ); }; (0, _utils.inheritStatics)(ResultContainer, FinalComponent); return ResultContainer; }; }
[ "function composeAll() {\n for (var _len = arguments.length, composers = Array(_len), _key = 0; _key < _len; _key++) {\n composers[_key] = arguments[_key];\n }\n\n return function (BaseComponent) {\n if (BaseComponent === null || BaseComponent === undefined) {\n throw new Error('Curry function of composeAll needs an input.');\n }\n\n var finalComponent = BaseComponent;\n composers.forEach(function (composer) {\n if (typeof composer !== 'function') {\n throw new Error('Composer should be a function.');\n }\n\n finalComponent = composer(finalComponent);\n\n if (finalComponent === null || finalComponent === undefined) {\n throw new Error('Composer function should return a value.');\n }\n });\n\n return finalComponent;\n };\n}", "function composeAll() {\n\t for (var _len = arguments.length, composers = Array(_len), _key = 0; _key < _len; _key++) {\n\t composers[_key] = arguments[_key];\n\t }\n\t\n\t return function (BaseComponent) {\n\t if ((0, _.getDisableMode)()) {\n\t return _common_components.DummyComponent;\n\t }\n\t\n\t if (BaseComponent === null || BaseComponent === undefined) {\n\t throw new Error('Curry function of composeAll needs an input.');\n\t }\n\t\n\t var FinalComponent = BaseComponent;\n\t composers.forEach(function (composer) {\n\t if (typeof composer !== 'function') {\n\t throw new Error('Composer should be a function.');\n\t }\n\t\n\t FinalComponent = composer(FinalComponent);\n\t\n\t if (FinalComponent === null || FinalComponent === undefined) {\n\t throw new Error('Composer function should return a value.');\n\t }\n\t });\n\t\n\t FinalComponent.__OriginalBaseComponent = BaseComponent.__OriginalBaseComponent || BaseComponent;\n\t\n\t var stubbingMode = (0, _.getStubbingMode)();\n\t\n\t if (!stubbingMode) {\n\t return FinalComponent;\n\t }\n\t\n\t // return the stubbing mode.\n\t var ResultContainer = function ResultContainer(props) {\n\t // If there's an stub use it.\n\t if (ResultContainer.__composerStub) {\n\t var data = ResultContainer.__composerStub(props);\n\t var finalProps = (0, _extends3.default)({}, props, data);\n\t\n\t return _react2.default.createElement(FinalComponent.__OriginalBaseComponent, finalProps);\n\t }\n\t\n\t // if there's no stub, just use the FinalComponent.\n\t var displayName = FinalComponent.displayName || FinalComponent.name;\n\t return _react2.default.createElement(\n\t 'span',\n\t null,\n\t '<' + displayName + ' />'\n\t );\n\t };\n\t\n\t (0, _utils.inheritStatics)(ResultContainer, FinalComponent);\n\t\n\t return ResultContainer;\n\t };\n\t}", "function compose(){\n var fs = Array.prototype.slice.call(arguments, 0, arguments.length);\n return function(){\n\tvar inArgs = Array.prototype.slice.call(arguments, 0, arguments.length);\n\tvar i = fs.length-1;\n\tvar res = fs[i].apply(null, inArgs);\n\ti = i - 1;\n\tfor(; i>=0; i = i - 1){\n\t \n\t res = fs[i](res);\n\t}\n\treturn res;\n }\n}", "function compose(...fns) {\n return fns.reduce(function(f, g) {\n return function(...args) {\n return f(g(...args))\n }\n })\n}", "function compose(...funcs) {\n return (...args) => {\n const initialValue = funcs[funcs.length - 1].apply(null, args);\n const leftFuncs = funcs.slice(0, -1);\n return leftFuncs.reduceRight((composed, f) => f(composed), initialValue);\n };\n}", "function compose(...fns) {\n const n = fns.length;\n\n return function $compose(...args) {\n $compose.callees = [];\n\n let $args = args;\n\n for (let i = n - 1; i >= 0; i -= 1) {\n const fn = fns[i];\n\n assert(\n typeof fn === 'function',\n `Invalid Composition: ${ordinal(n - i)} element in a composition isn't a function`,\n );\n\n $compose.callees.push(fn.name);\n $args = [fn.call(null, ...$args)];\n }\n\n return $args[0];\n };\n}", "function compose(...functions) {\n return function (...args) {\n const lastFn = functions.pop();\n return functions\n .slice(0, -1)\n .reduceRight(\n (composed, currentFn) => currentFn(composed),\n lastFn(...args)\n );\n };\n}", "function createComposedLayout(...layouters) {\n if (layouters.length === 0) {\n return noopLayout;\n }\n\n const composedLayout = (layout, containerFrame) => {\n return layouters.reduce((intermediateLayout, layouter) => layouter(intermediateLayout, containerFrame), layout);\n };\n\n return composedLayout;\n}", "function compose() {\n var funcs = Array.apply(null, arguments);\n var len = funcs.length;\n if(len >= 2) {\n throw new Error('composition requires at least 2 arguments');\n }\n return function (val) {\n var either = funcs[len - 1](val);\n switch(either.type) {\n case _EitherType.LEFT:\n case _EitherType.PENDING:\n return either;\n default: // _EitherType.RIGHT\n for(var i = len - 2; i >= 0; i--) {\n either = funcs[i](either.data);\n if(either.type !== _EitherType.RIGHT) {\n break;\n }\n }\n return either;\n }\n };\n}", "function compose(mixins, separateArguments) {\n if (separateArguments === void 0) { separateArguments = false; }\n // Constructor function that will be called every time a new composed object is created.\n var ctor = function () {\n var _this = this;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n if (separateArguments) {\n // Call each construction function with respective arguments.\n _.zip(mixins, args).forEach(function (_a) {\n var mixin = _a[0], mixinArgs = _a[1];\n mixin.apply(_this, mixinArgs);\n });\n }\n else {\n // Call the constructor function of all the mixins, in order.\n mixins.forEach(function (mixin) {\n mixin.apply(_this, args);\n });\n }\n };\n // Add all mixins properties and methods to the constructor prototype for all\n // created objects to have them.\n mixins.forEach(function (mixin) {\n extend(ctor.prototype, mixin.prototype);\n });\n return ctor;\n}", "function compose(...fns) {\n return (...args) => {\n const result = reduceRight((memo, fn) => {\n return [fn(...memo)];\n }, args, fns);\n\n return result[0];\n };\n}", "function composeMutuallyExc(...listFn) {\n console.log(listFn);\n listFn.forEach(fn => {\n //console.log(\"calling\", fn);\n fn;\n })\n}", "function processComposers (composers) {\n let arrOfComposers = [];\n for (let composer in composers) {\n\t\t\tif (composer !== \"Traditional,\") {\n\t\t\t\t\tarrOfComposers.push(Object.assign(composers[composer],{composer: composer}));\n\t\t\t}\n }\n return arrOfComposers;\n}", "function composeHandlers() {\n var handlers = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n handlers[_i] = arguments[_i];\n }\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return handlers.forEach(function (handler) { return handler.apply(void 0, args); });\n };\n}", "function compose() {\n\t\tvar functions = arguments;\n\t\tvar steps = functions.length;\n\n\t\treturn function () {\n\t\t\tvar value = arguments;\n\t\t\tvar n = steps;\n\n\t\t\t/**\n\t\t\t * Apply the functions in reverse order, storing the return value\n\t\t\t * of each application into an array to be used as the argument for\n\t\t\t * the next application.\n\t\t\t */\n\t\t\twhile (--n >= 0) {\n\t\t\t\tvalue = [functions[n].apply(this, value)];\n\t\t\t}\n\n\t\t\treturn value[0];\n\t\t};\n\t}", "function compose(...args){\n if(args.length === 0){\n throw new Error(\"compose() function should have at least one parameter\"); \n }\n return function (x){\n if(typeof args[args.length - 1] !== 'function'){\n throw new Error(\"parameters of compose() can only be functions\");\n }\n let result = args[args.length - 1](x);\n for(let i = args.length - 2; i >= 0; i--){\n if(typeof args[i] !== 'function'){\n throw new Error(\"parameters of compose() can only be functions\");\n }\n result = args[i](result);\n }\n return result;\n }\n}", "function composeModules(...modules) {\n return new ContainerModule(bind => {\n modules.forEach(x => x.registry(bind));\n });\n}", "function composeHandlers () {\n var actionName;\n var i;\n var inputHandlers = arguments;\n var outputHandlers;\n\n outputHandlers = {};\n for (i = 0; i < inputHandlers.length; i++) {\n for (actionName in inputHandlers[i]) {\n if (actionName in outputHandlers) {\n // Initial compose/merge functions into arrays.\n if (outputHandlers[actionName].constructor === Array) {\n outputHandlers[actionName].push(inputHandlers[i][actionName]);\n } else {\n outputHandlers[actionName] = [outputHandlers[actionName],\n inputHandlers[i][actionName]];\n }\n } else {\n outputHandlers[actionName] = inputHandlers[i][actionName];\n }\n }\n }\n\n // Compose functions specified via array.\n for (actionName in outputHandlers) {\n if (outputHandlers[actionName].constructor === Array) {\n outputHandlers[actionName] = composeFunctions.apply(this, outputHandlers[actionName])\n }\n }\n\n return outputHandlers;\n}", "function composeHandlers() {\n var actionName;\n var i;\n var inputHandlers = arguments;\n var outputHandlers;\n\n outputHandlers = {};\n for (i = 0; i < inputHandlers.length; i++) {\n for (actionName in inputHandlers[i]) {\n if (actionName in outputHandlers) {\n // Initial compose/merge functions into arrays.\n if (outputHandlers[actionName].constructor === Array) {\n outputHandlers[actionName].push(inputHandlers[i][actionName]);\n } else {\n outputHandlers[actionName] = [outputHandlers[actionName], inputHandlers[i][actionName]];\n }\n } else {\n outputHandlers[actionName] = inputHandlers[i][actionName];\n }\n }\n }\n\n // Compose functions specified via array.\n for (actionName in outputHandlers) {\n if (outputHandlers[actionName].constructor === Array) {\n outputHandlers[actionName] = composeFunctions.apply(this, outputHandlers[actionName]);\n }\n }\n\n return outputHandlers;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finite State Machine used to change Scenes
function changeScene() { // Launch various scenes switch (scene) { case config.Scene.MENU: // show the MENU scene stage.removeAllChildren(); menu = new scenes.Menu(); currentScene = menu; console.log("Starting MENU Scene"); break; case config.Scene.END: // show the END scene stage.removeAllChildren(); end = new scenes.End(); currentScene = end; console.log("Starting END Scene"); break; case config.Scene.INSTRUCTION: // show the END scene stage.removeAllChildren(); instruction = new scenes.Instruction(); currentScene = instruction; console.log("Starting INSTRUCTION Scene"); break; case config.Scene.LEVEL1: // show the LEVEL1 scene stage.removeAllChildren(); level1 = new scenes.levelOne(); currentScene = level1; console.log("Starting LEVEL 1 Scene"); break; case config.Scene.LEVEL1END: // show the LEVEL1END scene stage.removeAllChildren(); level1end = new scenes.levelOneEnd(); currentScene = level1end; console.log("Starting LEVEL 1 Scene"); break; case config.Scene.LEVEL1CHANGE: // show the LEVEL1CHANGE scene stage.removeAllChildren(); level1change = new scenes.levelOneChange(); currentScene = level1change; console.log("Starting LEVEL 1 Scene"); break; case config.Scene.LEVEL2: // // show the LEVEL2 scene stage.removeAllChildren(); level2 = new scenes.levelTwo(); currentScene = level2; console.log("Starting LEVEL 2 Scene"); break; case config.Scene.LEVEL2CHANGE: // show the LEVEL1CHANGE scene stage.removeAllChildren(); level2change = new scenes.LevelTwoChange(); currentScene = level2change; console.log("Starting LEVEL 2 Scene"); break; case config.Scene.LEVEL3: // show the LEVEL3 scene stage.removeAllChildren(); level3 = new scenes.levelThree(); currentScene = level3; console.log("Starting LEVEL 3 Scene"); break; case config.Scene.WIN: // show the LEVEL3 scene stage.removeAllChildren(); win = new scenes.Win(); currentScene = win; console.log("Starting winning scene"); break; } console.log(currentScene.numChildren); }
[ "function changeScene() {\n // Launch various scenes\n switch (scene) {\n case config.Scene.MENU:\n // show the MENU scene\n stage.removeAllChildren();\n menu = new scenes.Menu();\n currentScene = menu;\n console.log(\"Starting MENU Scene\");\n break;\n case config.Scene.INSTRUCTION:\n // show the INSTRUCTION scene\n stage.removeAllChildren();\n instruction = new scenes.Instruction();\n currentScene = instruction;\n console.log(\"Starting INSTRUCTION Scene\");\n break;\n case config.Scene.LEVEL1:\n // show the LEVEL1 scene\n stage.removeAllChildren();\n level1 = new scenes.Level1();\n currentScene = level1;\n console.log(\"Starting LEVEL1 Scene\");\n break;\n case config.Scene.LEVEL2:\n // show the LEVEL2 scene\n stage.removeAllChildren();\n level2 = new scenes.Level2();\n currentScene = level2;\n console.log(\"Starting LEVEL2 Scene\");\n break;\n case config.Scene.LEVEL3:\n // show the LEVEL3 scene\n stage.removeAllChildren();\n level3 = new scenes.Level3();\n currentScene = level3;\n console.log(\"Starting LEVEL3 Scene\");\n break;\n case config.Scene.END:\n // show the END scene\n stage.removeAllChildren();\n end = new scenes.End();\n currentScene = end;\n console.log(\"Starting END Scene\");\n break;\n case config.Scene.VICTORY:\n // show the END scene\n stage.removeAllChildren();\n victory = new scenes.Victory();\n currentScene = victory;\n console.log(\"Starting VICTORY Scene\");\n break;\n }\n}", "function changeScene() {\n // Launch various scenes\n switch (scene) {\n case config.Scene.MENU:\n // show the MENU scene\n stage.removeAllChildren();\n menu = new scenes.Menu();\n currentScene = menu;\n console.log(\"Starting MENU Scene\");\n break;\n case config.Scene.INSTRUCTIONS:\n // show the INSTRUCTION scene\n stage.removeAllChildren();\n instructions = new scenes.Instructions();\n currentScene = instructions;\n console.log(\"Starting INSTRUCTIONS Scene\");\n break;\n case config.Scene.PLAY:\n // show the PLAY scene\n stage.removeAllChildren();\n play = new scenes.Play();\n currentScene = play;\n console.log(\"Starting PLAY Scene\");\n break;\n case config.Scene.GAMEOVER:\n // show the GAMEOVER scene\n stage.removeAllChildren();\n gameOver = new scenes.GameOver();\n currentScene = gameOver;\n console.log(\"Starting GAMEOVER Scene\");\n break;\n }\n //console.log(currentScene.numChildren);\n}", "function changeScene() {\n // Launch various scenes\n switch (scene) {\n case config.Scene.MENU:\n // show the MENU scene\n stage.removeAllChildren();\n menu = new scenes.Menu();\n currentScene = menu;\n console.log(\"Starting MENU Scene\");\n break;\n case config.Scene.SLOT_MACHINE:\n // show the PLAY scene\n stage.removeAllChildren();\n slotMachine = new scenes.SlotMachine();\n currentScene = slotMachine;\n console.log(\"Starting SLOT_MACHINE Scene\");\n break;\n case config.Scene.GAME_OVER:\n // show the GAME OVER scene\n stage.removeAllChildren();\n gameOver = new scenes.GameOver();\n currentScene = gameOver;\n console.log(\"Starting GAME_OVER Scene\");\n break;\n }\n}", "function changeScene() {\n // Launch various scenes\n switch (scene) {\n case config.Scene.MENU:\n // show the MENU scene\n stage.removeAllChildren();\n menu = new scenes.Menu();\n currentScene = menu;\n console.log(\"Starting MENU Scene\");\n break;\n case config.Scene.SLOT_MACHINE:\n // show the PLAY scene\n stage.removeAllChildren();\n slotMachine = new scenes.SlotMachine();\n currentScene = slotMachine;\n console.log(\"Starting SLOT_MACHINE Scene\");\n break;\n case config.Scene.GAME_OVER:\n // show the game OVER scene\n stage.removeAllChildren();\n gameOver = new scenes.GameOver();\n currentScene = gameOver;\n console.log(\"Starting GAME_OVER Scene\");\n break;\n }\n console.log(currentScene.numChildren);\n}", "function changeScene() {\n // Launch various scenes\n switch (scene) {\n case config.Scene.MENU:\n // show the MENU scene\n stage.removeAllChildren();\n menu = new scenes.Menu();\n currentScene = menu;\n console.log(\"Starting MENU Scene\");\n break;\n case config.Scene.INSTRUCTIONS:\n // show the Instructions scene\n stage.removeAllChildren();\n instructions = new scenes.Instructions();\n currentScene = instructions;\n console.log(\"Starting INSTRUCTIONS Scene\");\n break;\n case config.Scene.LEVEL01:\n // show the PLAY scene\n stage.removeAllChildren();\n level01 = new scenes.Level01();\n currentScene = level01;\n console.log(\"Starting LEVEL 0.5 Scene\");\n break;\n case config.Scene.LEVEL1:\n // show the PLAY scene\n stage.removeAllChildren();\n level1 = new scenes.Level1();\n currentScene = level1;\n console.log(\"Starting LEVEL 1 Scene\");\n break;\n case config.Scene.LEVEL12:\n // show the PLAY scene\n stage.removeAllChildren();\n level12 = new scenes.Level12();\n currentScene = level12;\n console.log(\"Starting LEVEL 1.5 Scene\");\n break;\n case config.Scene.LEVEL2:\n // show the PLAY scene\n stage.removeAllChildren();\n level2 = new scenes.Level2();\n currentScene = level2;\n console.log(\"Starting LEVEL 2 Scene\");\n break;\n case config.Scene.LEVEL23:\n // show the PLAY scene\n stage.removeAllChildren();\n level23 = new scenes.Level23();\n currentScene = level12;\n console.log(\"Starting LEVEL 2.5 Scene\");\n break;\n case config.Scene.LEVEL3:\n // show the PLAY scene\n stage.removeAllChildren();\n level3 = new scenes.Level3();\n currentScene = level3;\n console.log(\"Starting LEVEL 3 Scene\");\n break;\n case config.Scene.END:\n // show the END scene\n stage.removeAllChildren();\n end = new scenes.End();\n currentScene = end;\n console.log(\"Starting END Scene\");\n break;\n case config.Scene.WIN:\n // show the WIN scene\n stage.removeAllChildren();\n win = new scenes.Win();\n currentScene = win;\n console.log(\"Starting WIN Scene\");\n break;\n case config.Scene.GAMEOVER:\n // show the GAME OVER scene\n stage.removeAllChildren();\n gameover = new scenes.GameOver();\n currentScene = gameover;\n console.log(\"Starting GameOver Scene\");\n break;\n }\n console.log(currentScene.numChildren);\n}", "function changeScene() {\n // Launch various scenes\n switch (scene) {\n case config.Scene.MENU:\n // show the MENU scene\n stage.removeAllChildren();\n menu = new scenes.Menu();\n currentScene = menu;\n console.log(\"Starting MENU Scene\");\n break;\n case config.Scene.HELP:\n // show the HELP scene\n stage.removeAllChildren();\n help = new scenes.Help();\n currentScene = help;\n console.log(\"Starting HELP Scene\");\n break;\n case config.Scene.PLAY:\n // show the PLAY scene\n stage.removeAllChildren();\n play = new scenes.Play();\n currentScene = play;\n console.log(\"Starting PLAY Scene\");\n break;\n case config.Scene.END:\n // show the END scene\n stage.removeAllChildren();\n end = new scenes.End();\n currentScene = end;\n console.log(\"Starting END Scene\");\n break;\n }\n console.log(currentScene.numChildren);\n}", "function changeScene() {\n // Launch various scenes\n switch (scene) {\n case config.Scene.INTRO:\n // show the MENU scene\n stage.removeAllChildren();\n intro = new scenes.Intro();\n currentScene = intro;\n console.log(\"Starting INTRO Scene\");\n break;\n case config.Scene.INTRO2:\n // show the MENU scene\n stage.removeAllChildren();\n intro2 = new scenes.Intro2();\n currentScene = intro2;\n console.log(\"Starting INTRO2 Scene\");\n break;\n case config.Scene.INTRO3:\n // show the MENU scene\n stage.removeAllChildren();\n intro3 = new scenes.Intro3();\n currentScene = intro3;\n console.log(\"Starting INTRO3 Scene\");\n break;\n case config.Scene.INTRO4:\n // show the MENU scene\n stage.removeAllChildren();\n intro4 = new scenes.Intro4();\n currentScene = intro4;\n console.log(\"Starting INTRO4 Scene\");\n break;\n case config.Scene.GAME:\n // show the MENU scene\n stage.removeAllChildren();\n game = new scenes.Game();\n currentScene = game;\n console.log(\"Starting GAME Scene\");\n break;\n //LEFT_FOREST**************************************\n case config.Scene.LEFT_FOREST:\n // show the PLAY scene\n stage.removeAllChildren();\n leftForest = new scenes.LeftForest();\n currentScene = leftForest;\n console.log(\"Starting LEFT_FOREST Scene\");\n break;\n case config.Scene.FIGHT_LEFT:\n // show the MENU scene\n stage.removeAllChildren();\n fightLeft = new scenes.FightLeft();\n currentScene = fightLeft;\n console.log(\"Starting FIGHT_LEFT Scene\");\n break;\n case config.Scene.FINISH_ALL_LEFT:\n // show the MENU scene\n stage.removeAllChildren();\n fightAllLeft = new scenes.FightAllLeft();\n currentScene = fightAllLeft;\n console.log(\"Starting FINISH_ALL_LEFT Scene\");\n break;\n case config.Scene.FINISH_HALF_LEFT:\n // show the MENU scene\n stage.removeAllChildren();\n fightHalfLeft = new scenes.FightHalf();\n currentScene = fightHalfLeft;\n console.log(\"Starting FINISH_HALF_LEFT Scene\");\n break;\n case config.Scene.BOSS_FIGHT_LEFT1:\n // show the MENU scene\n stage.removeAllChildren();\n bossFightLeft1 = new scenes.BossFightLeft1();\n currentScene = bossFightLeft1;\n console.log(\"Starting BOSS_FIGHT_LEFT1 Scene\");\n break;\n case config.Scene.BOSS_FIGHT_LEFT2:\n // show the MENU scene\n stage.removeAllChildren();\n bossFightLeft2 = new scenes.BossFightLeft2();\n currentScene = bossFightLeft2;\n console.log(\"Starting BOSS_FIGHT_LEFT2 Scene\");\n break;\n case config.Scene.SAVE_PRINCESS:\n // show the MENU scene\n stage.removeAllChildren();\n savePrincess = new scenes.SavePrincess();\n currentScene = savePrincess;\n console.log(\"Starting SAVE_PRINCESS Scene\");\n break;\n case config.Scene.RUN_FIGHT_LEFT:\n // show the MENU scene\n stage.removeAllChildren();\n runFightLeft = new scenes.RunFightLeft();\n currentScene = runFightLeft;\n console.log(\"Starting RUN_FIGHT_LEFT Scene\");\n break;\n case config.Scene.RUN_FIND_WAY_LEFT:\n // show the MENU scene\n stage.removeAllChildren();\n runFindWayLeft = new scenes.RunFindWayLeft();\n currentScene = runFindWayLeft;\n console.log(\"Starting RUN_FIND_WAY_LEFT Scene\");\n break;\n case config.Scene.RUN_LEFT:\n // show the MENU scene\n stage.removeAllChildren();\n runLeft = new scenes.RunLeft();\n currentScene = runLeft;\n console.log(\"Starting RUN_LEFT Scene\");\n break;\n //RIGHT_FOREST***************************************\n case config.Scene.RIGHT_FOREST:\n // show the game OVER scene\n stage.removeAllChildren();\n rightForest = new scenes.RightForest();\n currentScene = rightForest;\n console.log(\"Starting RIGHT_FOREST Scene\");\n break;\n case config.Scene.FIGHT_RIGHT:\n // show the MENU scene\n stage.removeAllChildren();\n fightRight = new scenes.FightRight();\n currentScene = fightRight;\n console.log(\"Starting FIGHT_RIGHT Scene\");\n break;\n case config.Scene.FINISH_ALL_RIGHT:\n // show the MENU scene\n stage.removeAllChildren();\n fightAllRight = new scenes.FightAllRight();\n currentScene = fightAllRight;\n console.log(\"Starting FINISH_ALL_RIGHT Scene\");\n break;\n case config.Scene.FINISH_HALF_RIGHT:\n // show the MENU scene\n stage.removeAllChildren();\n fightHalfRight = new scenes.FightHalfRight();\n currentScene = fightHalfRight;\n console.log(\"Starting FINISH_HALF_RIGHT Scene\");\n break;\n case config.Scene.FINISH_HALF_RIGHT_FAIL:\n // show the MENU scene\n stage.removeAllChildren();\n fightHalfRightFail = new scenes.FightHalfRightFail();\n currentScene = fightHalfRightFail;\n console.log(\"Starting FINISH_HALF_RIGHT_FAIL Scene\");\n break;\n case config.Scene.BOSS_FIGHT_RIGHT1:\n // show the MENU scene\n stage.removeAllChildren();\n bossFightRight1 = new scenes.BossFightRight1();\n currentScene = bossFightRight1;\n console.log(\"Starting BOSS_FIGHT_RIGHT1 Scene\");\n break;\n case config.Scene.BOSS_FIGHT_RIGHT2:\n // show the MENU scene\n stage.removeAllChildren();\n bossFightRight2 = new scenes.BossFightRight2();\n currentScene = bossFightRight2;\n console.log(\"Starting BOSS_FIGHT_RIGHT2 Scene\");\n break;\n case config.Scene.BOSS_FIGHT_RIGHT3:\n // show the MENU scene\n stage.removeAllChildren();\n bossFightRight3 = new scenes.BossFightRight3();\n currentScene = bossFightRight3;\n console.log(\"Starting BOSS_FIGHT_RIGHT3 Scene\");\n break;\n case config.Scene.RUN_RIGHT:\n // show the MENU scene\n stage.removeAllChildren();\n runRight = new scenes.RunRight();\n currentScene = runRight;\n console.log(\"Starting RUN_RIGHT Scene\");\n break;\n case config.Scene.RUN_FIGHT_RIGHT:\n // show the MENU scene\n stage.removeAllChildren();\n runFightRight = new scenes.RunFightRight();\n currentScene = runFightRight;\n console.log(\"Starting RUN_FIGHT_RIGHT Scene\");\n break;\n case config.Scene.RUN_FIND_WAY_RIGHT:\n // show the MENU scene\n stage.removeAllChildren();\n runFindWayRight = new scenes.RunFindWayRight();\n currentScene = runFindWayRight;\n console.log(\"Starting RUN_FIND_WAY_RIGHT Scene\");\n break;\n }\n console.log(currentScene.numChildren);\n}", "function changeState(state) {\n switch (state) {\n case constants.START_STATE:\n stateChanged = false;\n start = new states.Start();\n currentStateFunction = start;\n break;\n case constants.INSTRUCTIONS_STATE:\n stateChanged = false;\n instructions = new states.Instructions();\n currentStateFunction = instructions;\n break;\n case constants.STAGE1_STATE:\n stateChanged = false;\n stage1 = new states.Stage1();\n currentStateFunction = stage1;\n break;\n case constants.STAGE1BOSS_STATE:\n stateChanged = false;\n stage1Boss = new states.Stage1Boss();\n currentStateFunction = stage1Boss;\n break;\n case constants.STAGE2_STATE:\n stateChanged = false;\n stage2 = new states.Stage2();\n currentStateFunction = stage2;\n break;\n case constants.STAGE3_STATE:\n stateChanged = false;\n stage3 = new states.Stage3();\n currentStateFunction = stage3;\n break;\n case constants.STAGE3BOSS_STATE:\n stateChanged = false;\n stage3Boss = new states.Stage3Boss();\n currentStateFunction = stage3Boss;\n break;\n case constants.GAME_OVER_STATE:\n stateChanged = false;\n gameOver = new states.GameOver();\n currentStateFunction = gameOver;\n break;\n case constants.GAME_OVER_SPOTTED_STATE:\n stateChanged = false;\n spottedGameOver = new states.SpottedGameOver();\n currentStateFunction = spottedGameOver;\n break;\n case constants.WIN_STATE:\n stateChanged = false;\n win = new states.Win();\n currentStateFunction = win;\n break;\n }\n}", "function FSM() {}", "change(name) {\n const params = {}\n this.currentScene.exit() //exit old scene\n this.currentScene = this.getScene(name)\n this.currentScene.enter(params) //enter new scene\n }", "function stateChange(){\n //Start of simulation\n if(state === `start`){\n startScreen();\n }\n //End the simulation\n if(state === `end`){\n endScreen();\n }\n}", "scene_switch(scene) {\n //prev_scene = this;\n next_scene = scene;\n //this.next_scene.place_inventory();\n this.scene.switch(next_scene);\n this.reconstruct_keybinds(next_scene);\n }", "static _changeToNextScene() {\r\n if (this._scene) this._terminateCurrentScene();\r\n this._scene = this._nextScene, this._nextScene = null;\r\n if (this._scene) this._createCurrentScene();\r\n if (this._exiting) this.terminate();\r\n }", "function state() { }", "function startGame() {\n sceneId = 1;\n nodeId = 1;\n populateTextContainer();\n loadScene();\n handleActionClicks(); \n fadeImage();\n}", "swapScenes(sceneData){\n this.setState({currentScene: sceneData});\n }", "function startGame() {\n state = {}\n showTextNode(1)\n}", "stateMachine() {\n switch (this.state) {\n case 'START':\n this.start();\n break;\n case 'UPDATE_CONFIGS':\n this.update_Configs();\n break;\n case 'WAIT_AP_RESPONSE':\n this.wait_AssertPlayers_response();\n break;\n case 'PROCESS_PIECE':\n this.client.requestCurrentPlayerBot();\n if(this.newTimer){\n this.newTimer = false;\n this.view.startTimer();\n }\n this.state = 'WAIT_CPB_RESPONSE';\n break;\n case 'WAIT_CPB_RESPONSE':\n this.checkOverTime();\n this.wait_CurrentPlayerBot_response();\n break;\n case 'REQUEST_VALID_CELLS':\n this.request_validCells();\n this.checkOverTime();\n break;\n case 'WAIT_VP_RESPONSE':\n this.wait_validCells_response();\n break;\n case 'SELECT_CELL':\n this.checkOverTime();\n this.selectCell();\n break;\n case 'REQUEST_PLAY_P':\n this.client.requestPlay([this.view.board.selectedCell.column, this.view.board.selectedCell.line, this.selectedPiece.color])\n this.state = 'WAIT_PP_RESPONSE';\n break;\n case 'REQUEST_PLAY_B':\n this.client.requestBotPlay(this.model.level);\n this.state = 'WAIT_PB_RESPONSE';\n break;\n case 'WAIT_PP_RESPONSE':\n this.wait_HumanPlay_response();\n break;\n case 'WAIT_PB_RESPONSE':\n this.wait_BotPlay_response();\n this.checkOverTime();\n break;\n case 'WAIT_ANIMATION_END':\n this.view.stopTimer();\n this.wait_AnimationEnd();\n break;\n case 'WAIT_UNDO':\n this.wait_Undo();\n break;\n case 'WAIT_SP_RESPONSE':\n this.wait_SwitchPlayers_response();\n break;\n case 'WAIT_SP_TIMER':\n this.wait_SwitchPlayers_timer();\n break;\n case 'CHANGE_PLAYER':\n this.view.marker.switchPlayer();\n this.scene.update_CameraRotation();\n this.newTimer = true;\n this.state = 'PROCESS_PIECE';\n this.check_Reset();\n break;\n case 'GAME_OVER':\n this.check_GameMovie();\n this.check_Reset();\n break;\n case 'GAME_MOVIE' :\n this.view_GameMovie();\n break;\n case 'WAIT_GM_1st_ANIMATION_END' :\n this.wait_GM_1st_AnimationEnd();\n break;\n case 'WAIT_GM_ANIMATION_END' :\n this.wait_GM_AnimationEnd();\n break;\n case 'WAIT_GM_CAMERA_ANIMATION_END' :\n this.wait_GM_Camera_AnimationEnd();\n break;\n case 'SMALL_WAIT':\n this.small_Wait();\n break;\n }\n\n }", "function sceneManager () {\n switch (scene) {\n case \"titleScreen\":\n // scene = \"introScene\";\n // touchToContinue();\n break;\n \n\n case \"intro\":\n displayText = grammar.flatten(\"#opening#\");\n // touchToContinue();\n backgroundAudio(\"play\");\n displayText = textFilter(displayText);\n scene = \"sceneOne\";\n break;\n \n\n case \"sceneOne\":\n continueButton.hide();\n userInput();\n displayText = grammar.flatten(\"#sceneOne#\");\n displayText = textFilter(displayText);\n scene = \"questionOne\";\n break;\n\n case \"sceneTwo\":\n displayText = grammar.flatten(\"#sceneThree#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneThree\";\n break;\n \n case \"sceneThree\":\n displayText = grammar.flatten(\"#sceneFour#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneFour\";\n break;\n\n case \"sceneFour\":\n displayText = grammar.flatten(\"#sceneFive#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneFive\";\n break;\n\n case \"sceneFive\":\n continueButton.hide();\n input.show();\n displayText = grammar.flatten(\"#questionFour#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"questionFour\";\n break;\n\n case \"sceneSix\":\n displayText = grammar.flatten(\"#sceneSeven#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneSeven\";\n break;\n\n case \"sceneSeven\":\n displayText = grammar.flatten(\"#sceneEight#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneEight\";\n break;\n\n case \"sceneEight\":\n displayText = grammar.flatten(\"#sceneNine#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneNine\";\n break;\n\n case \"sceneNine\":\n displayText = grammar.flatten(\"#sceneTen#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneTen\";\n break;\n\n case \"sceneTen\":\n displayText = grammar.flatten(\"#endingOne#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText += \"\\n\" + \"\\n\" + \"Run\";\n displayText = textFilter(displayText);\n scene = \"endingOne\";\n break;\n\n case \"endingOne\":\n displayText = grammar.flatten(\"#endingTwo#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText += \"\\n\" + \"\\n\" + \"GET OUT NOW\";\n displayText = textFilter(displayText);\n scene = \"endingTwo\";\n break;\n\n case \"endingTwo\":\n continueButton.hide();\n input.show();\n displayText = grammar.flatten(\"#endingQuestion#\");\n // wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"endingQuestion\";\n break;\n\n case \"endingThree\":\n continueButton.hide();\n saveStoryButton();\n displayText = grammar.flatten(\"#endingFour#\");\n displayText = textFilter(displayText);\n // wholeStory += displayText + \"\\n\" + \"\\n\";\n // scene = \"endingFour\";\n break;\n\n case 6:\n displayText = grammar.flatten(\"#dreamSequence#\");\n scene = 7;\n break;\n\n case 7:\n continueButton.hide();\n displayText = grammar.flatten(\"#beginning#\");\n saveStoryButton();\n break;\n\n case 50:\n displayText = grammar.flatten(\"#warning#\");\n scene = 51;\n break;\n\n case 51:\n displayText = grammar.flatten(\"#warning.capitalize#\");\n scene = 52;\n break;\n\n case 52:\n displayText = grammar.flatten(\"#warning.capitalizeAll#\");\n scene = 53;\n break;\n \n default:\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the output data display based on the current value of gaOutputData.
function updateOutputDataDisplay() { console.log('updateOutputDataDisplay'); var s = ''; for (var i = 0; i < gaOutputData.length; i++) { var obj = gaOutputData[i]; s += (obj.value + '=' + obj.count + ', '); } $('#output-data').text(s); }
[ "function updateOutputData() {\n outputData = unformatNum(getOutput());\n // Lines to remove initial emoji etc\n if(isNaN(outputData)) {\n setOutput(this.id);\n setCalculation(\"\");\n }\n //Clear rather than append if last button was =\n else if (sumDone == true) {\n outputData = this.id;\n setOutput(outputData);\n sumDone = false;\n }\n //Append\n else {\n outputData = outputData + this.id;\n setOutput(outputData);\n }\n}", "function updateOutputDataFooter() {\n console.log('updateOutputDataFooter');\n $('#output-data-footer').text('Total nodes: ' + gaOutputData.length);\n}", "function updateOutput()\n{\n\t$(\"#output\").text(currentOutput);\n}", "function updateOutput() {\n let o = {\n vertices: vertices,\n edges: edges\n };\n qsl(\"#txt_output1\").value = JSON.stringify(o);\n }", "function updateInputDataDisplay() {\n console.log('updateInputDataDisplay');\n\n var s = '';\n for (var i = 0; i < gaInputData.length; i++) {\n s += (gaInputData[i] + ', ');\n }\n\n $('#input-data').text(s);\n}", "function clearOutputData() {\n console.log('clearOutputData');\n gaOutputData = [];\n updateOutputDataDisplay();\n}", "function updateInputDataFooter() {\n console.log('updateInputDataFooter');\n $('#input-data-footer').text('Total ' + DATATYPE_NAME[gDataType] + 's: ' + gaInputData.length);\n}", "function updateDisplay()\n {\n //We need to build a string to show. The first item is the current running total:\n var string = runningTotal;\n\n //Then we add the operator if they have pressed this\n if(hasPressedOperator)\n string += \" \" + currentOperator;\n \n //And finally we add the right operand, the value to add when equals is pressed.\n if(hasPressedOperand)\n string += \" \" + currentOperand;\n \n //We then simply set the value of the output field to the string we built\n document.getElementById(\"output\").value = string;\n }", "update() {\n //update output\n var text = this.transform(os.hostname());\n this.output.full_text = text;\n this.output.short_text = text;\n\n //emit updated event to i3Status\n this.emit('updated', this, this.output);\n }", "update() {\n //update output\n var text;\n var avg = os.loadavg()[0];\n var percentage = avg / this.ncpu;\n\n if (this.showPercentage) {\n text = (percentage*100).toFixed(0) + '%';\n } else {\n text = avg.toFixed(2);\n }\n\n this.output.full_text = text;\n this.output.short_text = text;\n\n //block is urgent if warning is enabled and avg is greater the cpu count\n this.output.urgent = this.warning && avg > this.ncpu;\n\n //emit updated event to i3Status\n this.emit('updated', this, this.output);\n }", "update() {\n\t\tthis.output = this.tempOutput;\n\t}", "function updateDisplay() {\n if (view == 'assignments') {\n $('#graded-items').hide();\n\n $('#assignments').show();\n $('.assignment-progress-bar').show();\n updateAssignments((a) => {\n assignments = a;\n displayAssignments(assignments);\n });\n } else if (view == 'gradedItems') {\n $('#assignments').hide();\n $('.assignment-progress-bar').hide();\n\n $('#graded-items').show();\n updateGradedItems((g) => {\n gradedItems = g;\n displayGradedItems(gradedItems);\n });\n }\n }", "function updateMap() {\n\t\n\tvar sel_option = $(\"input[name=dataDisplayOption]:checked\").val();\n\t\n\t// ignore func call if the setting was not changed\n\tif (sel_option == c_display_option) { return; }\n\t\n\t// clear the map of the old overlays\n\tclearMap();\n\t\n\t// save the new display option\n\tc_display_option = sel_option;\n\t\n\t// plot the data all over again\n\tplotAllData();\n\t\n}", "update_outputs() { }", "function display_update()\n{\n\t// Process forecast into chart input.\n\tvisualization_data = process_forecast(forecast);\n\t// Update chart visuals.\n\tvisualize(visualization_data, display_mode);\n}", "function updateDisplay() {\n document.getElementById('display').innerHTML = output;\n}", "function updateOutput(){\n\t\tval = editor.getValue();\n\t\tif (ide == \"st3\"){\n\t\t\t// format for Sublime Text\n\t\t\toutput.session.setMode(\"ace/mode/html\") // Sublime text format for snippets\n\t\t\toutput.session.setUseWorker(false) // disables error\n\t\t\toutput.setValue(formatSublime())\n\t\t\toutput.clearSelection();\n\t\t}\n\t\telse if (ide == \"vsc\"){\n\t\t\t// format for VS Code\n\t\t\toutput.session.setMode(\"ace/mode/python\") // VS Code format for snippets\n\t\t\tcode = formatVSCode()\n\t\t\toutput.setValue(code)\n\t\t\toutput.clearSelection();\n\t\t}\n\t}", "function update_distribution_plot() {\n\tvar inlet_dataset = [];\n\tvar outlet_dataset = [];\n\tvar ticks = [];\n\tdata_table.forEach(function (row, index) {\n\t\tif(typeof (row) !== 'object')\n\t\t\treturn;\n\t\tinlet_dataset.push([index, row.inlet_psd_percentage]);\n\t\toutlet_dataset.push([index, row.outlet_psd]);\n\t\tticks.push([index, row.avg_dp]);\n\t});\n\n\tvar xaxis = distribution_plot.getAxes().xaxis;\n\txaxis.options.ticks = ticks;\n\n\tdistribution_plot.setData([{\n\t\tlabel: \"Inlet PSD (%)\",\n\t\tdata: inlet_dataset,\n\t\tbars: {\n\t\t\talign: \"right\",\n\t\t\tbarWidth: 0.4,\n\t\t}\n\t}, {\n\t\tlabel: \"Outlet PSD (%)\",\n\t\tdata: outlet_dataset,\n\t\tbars: {\n\t\t\talign: \"left\",\n\t\t\tbarWidth: 0.4\n\t\t},\n\t}]);\n\tdistribution_plot.setupGrid();\n\tdistribution_plot.draw();\n}", "redrawOutputs() {\n for (let g of this.glissOutputs) g.redrawPosition();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert grayscale jsfeat image to p5 rgba image usage: dst = jsfeatToP5(src, dst)
function jsfeatToP5(src, dst) { if (!dst || dst.width != src.cols || dst.height != src.rows) { dst = createImage(src.cols, src.rows); } var n = src.data.length; dst.loadPixels(); var srcData = src.data; var dstData = dst.pixels; for (var i = 0, j = 0; i < n; i++) { var cur = srcData[i]; dstData[j++] = cur; dstData[j++] = cur; dstData[j++] = cur; dstData[j++] = 255; } dst.updatePixels(); return dst; }
[ "function jsfeatToP5(src, dst) {\n if(!dst || dst.width != src.cols || dst.height != src.rows) {\n dst = createImage(src.cols, src.rows);\n }\n var n = src.data.length;\n dst.loadPixels();\n var srcData = src.data;\n var dstData = dst.pixels;\n for(var i = 0, j = 0; i < n; i++) {\n var cur = srcData[i];\n dstData[j++] = cur;\n dstData[j++] = cur;\n dstData[j++] = cur;\n dstData[j++] = 255;\n }\n dst.updatePixels();\n return dst;\n}", "function grayscale(__src)\n{\n var h = __src.h,\n w = __src.w;\n var dst = new RGBAImage(w, h);\n var data = dst.data,\n data2 = __src.data;\n var pix1, pix2, pix = w * h * 4;\n while (pix){\n data[pix -= 4] = data[pix1 = pix + 1] = data[pix2 = pix + 2] = (data2[pix] * 299 + data2[pix1] * 587 + data2[pix2] * 114) / 1000;\n data[pix + 3] = data2[pix + 3];\n }\n return dst;\n}", "function grayscale(src){\nvar canvas = document.createElement('canvas');\nvar ctx = canvas.getContext('2d');\nvar imgObj = new Image();\nimgObj.src = src;\ncanvas.width = imgObj.width;\ncanvas.height = imgObj.height;\nctx.drawImage(imgObj, 0, 0);\nvar imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);\nfor(var y = 0; y < imgPixels.height; y++){\nfor(var x = 0; x < imgPixels.width; x++){\nvar i = (y * 4) * imgPixels.width + x * 4;\nvar avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;\nimgPixels.data[i] = avg;\nimgPixels.data[i + 1] = avg;\nimgPixels.data[i + 2] = avg;\n}\n}\nctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);\nreturn canvas.toDataURL();\n}", "function grayscaleIe(src){\n\t\t\t\tvar canvas = document.createElement('canvas');\n\t\t\t\tvar ctx = canvas.getContext('2d');\n\t\t\t\tvar imgObj = new Image();\n\t\t\t\timgObj.src = src;\n\t\t\t\tcanvas.width = imgObj.width;\n\t\t\t\tcanvas.height = imgObj.height; \n\t\t\t\tctx.drawImage(imgObj, 0, 0); \n\t\t\t\tvar imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);\n\t\t\t\tfor(var y = 0; y < imgPixels.height; y++){\n\t\t\t\t\tfor(var x = 0; x < imgPixels.width; x++){\n\t\t\t\t\t\tvar i = (y * 4) * imgPixels.width + x * 4;\n\t\t\t\t\t\tvar avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;\n\t\t\t\t\t\timgPixels.data[i] = avg; \n\t\t\t\t\t\timgPixels.data[i + 1] = avg; \n\t\t\t\t\t\timgPixels.data[i + 2] = avg;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);\n\t\t\t\treturn canvas.toDataURL();\n\t\t\t}", "function grayscaleIe(src){\n\t\t\tvar canvas = document.createElement('canvas');\n\t\t\tvar ctx = canvas.getContext('2d');\n\t\t\tvar imgObj = new Image();\n\t\t\timgObj.src = src;\n\t\t\tcanvas.width = imgObj.width;\n\t\t\tcanvas.height = imgObj.height; \n\t\t\tctx.drawImage(imgObj, 0, 0); \n\t\t\tvar imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);\n\t\t\tfor(var y = 0; y <imgPixels.height; y++){\n\t\t\t\tfor(var x = 0; x <imgPixels.width; x++){\n\t\t\t\t\tvar i = (y * 4) * imgPixels.width + x * 4;\n\t\t\t\t\tvar avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;\n\t\t\t\t\timgPixels.data[i] = avg; \n\t\t\t\t\timgPixels.data[i + 1] = avg; \n\t\t\t\t\timgPixels.data[i + 2] = avg;\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);\n\t\t\treturn canvas.toDataURL();\n\t\t}", "function grayscaleIe(element) {\n \n var src = element.src;\n $(element).addClass('disabled');\n var canvas = document.createElement('canvas');\n var ctx = canvas.getContext('2d');\n var imgObj = new Image();\n imgObj.src = src;\n canvas.width = imgObj.width;\n canvas.height = imgObj.height;\n ctx.drawImage(imgObj, 0, 0);\n var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);\n for (var y = 0; y < imgPixels.height; y++) {\n for (var x = 0; x < imgPixels.width; x++) {\n var i = (y * 4) * imgPixels.width + x * 4;\n var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;\n imgPixels.data[i] = avg;\n imgPixels.data[i + 1] = avg;\n imgPixels.data[i + 2] = avg;\n }\n }\n ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);\n return canvas.toDataURL();\n }", "function grayscaleIe(element) {\n\n var src = element.src;\n $(element).addClass('disabled');\n var canvas = document.createElement('canvas');\n var ctx = canvas.getContext('2d');\n var imgObj = new Image();\n imgObj.src = src;\n canvas.width = imgObj.width;\n canvas.height = imgObj.height;\n ctx.drawImage(imgObj, 0, 0);\n var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);\n for (var y = 0; y < imgPixels.height; y++) {\n for (var x = 0; x < imgPixels.width; x++) {\n var i = (y * 4) * imgPixels.width + x * 4;\n var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;\n imgPixels.data[i] = avg;\n imgPixels.data[i + 1] = avg;\n imgPixels.data[i + 2] = avg;\n }\n }\n ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);\n return canvas.toDataURL();\n }", "function applyGrayscale() \n{ \n var filter = 'grayscale(100%)';\n setFilter(filter);\n}", "function grayscaleToJit(value) {\n var t = ((value - 127.0) / 255.0) * 2.0;\n var result = {};\n result.r = clamp(1.5 - Math.abs(2.0 * t - 1.0), 0, 1);\n result.g = clamp(1.5 - Math.abs(2.0 * t), 0, 1);\n result.b = clamp(1.5 - Math.abs(2.0 * t + 1.0), 0, 1);\n return result;\n}", "set grayscale(value) {}", "grayscale() {\n var ctx = canvas.getContext('2d');\n var imgPixels = ctx.getImageData(0, 0, 48, 48);\n for(var y = 0; y < imgPixels.height; y++){\n for(var x = 0; x < imgPixels.width; x++){\n var i = (y * 4) * imgPixels.width + x * 4;\n var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;\n imgPixels.data[i] = avg;\n imgPixels.data[i + 1] = avg;\n imgPixels.data[i + 2] = avg;\n }\n }\n ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);\n return canvas.toDataURL();\n }", "function grayScaleImage(src) {\n var canvas = document.createElement('canvas');\n var ctx = canvas.getContext('2d');\n var imgObj = new Image();\n imgObj.src = src;\n canvas.width = imgObj.width;\n canvas.height = imgObj.height;\n ctx.drawImage(imgObj, 0, 0);\n var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);\n for (var y = 0; y < imgPixels.height; y++) {\n for (var x = 0; x < imgPixels.width; x++) {\n var i = (y * 4) * imgPixels.width + x * 4;\n var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;\n imgPixels.data[i] = avg;\n imgPixels.data[i + 1] = avg;\n imgPixels.data[i + 2] = avg;\n }\n }\n ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);\n return canvas.toDataURL();\n}", "get grayscale() {}", "function getDominantColor(image){var width=image.width,height=image.height;var PIXELS_FROM_EDGE=11;var canvas=document.createElement('canvas');canvas.width=width;canvas.height=height;var context=canvas.getContext('2d');context.drawImage(image,0,0,width,height);var transparentPixels=false;var colors=[];var outlyingColors=[];var outlyingColorsList=JSON.stringify([[255,255,255],[0,0,0]]);/*\n Iterate through edge pixels and get the average color, then conditionally\n handle edge colors and transparent images\n */for(var x=0;x<PIXELS_FROM_EDGE;x+=1){for(var y=0;y<PIXELS_FROM_EDGE;y+=1){var pixelData=context.getImageData(x,y,1,1).data;if(pixelData[3]<255){// alpha pixels\ntransparentPixels=true;break;}var color=[pixelData[0],// r\npixelData[1],// g\npixelData[2]];var colorList=JSON.stringify(color);if(outlyingColorsList.includes(colorList)){outlyingColors.push(color);}else{colors.push(color);}}}if(outlyingColors.length>colors.length){colors=outlyingColors;}if(transparentPixels){return'';}var colorMap=quantize__WEBPACK_IMPORTED_MODULE_13___default()(colors,5);var _Array$from=Array.from(colorMap.palette()[0]),_Array$from2=_slicedToArray(_Array$from,3),r=_Array$from2[0],g=_Array$from2[1],b=_Array$from2[2];return\"rgb(\".concat(r,\",\").concat(g,\",\").concat(b,\")\");}", "function generateGrayscaleImage(image) {\n var canvas = document.getElementById(\"grayscale-image\");\n canvas.width = image.width;\n canvas.height = image.height;\n var ctx = canvas.getContext('2d');\n var originalData = getImageData(image);\n var imageData = ctx.createImageData(image.width, image.height);\n var color = 0;\n var i = 0;\n\n for(i=0; i < imageData.data.length; i+=4) {\n if(originalData.data[i+3] !== 255) {\n color = 255; // Transparency is considered as not carved\n } else {\n color = originalData.data[i]; // Assuming R = G = B\n }\n imageData.data[i] = color;\n imageData.data[i+1] = color;\n imageData.data[i+2] = color;\n imageData.data[i+3] = 255;\n }\n\n ctx.putImageData(imageData, 0, 0);\n grayscaleImage.src = canvas.toDataURL(\"img/png\");\n}", "function convertCanvasToJit(canvas) {\n // get image data\n var ctx = canvas.getContext('2d');\n var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n\n // update image data\n for (var i = 0; i < imageData.data.length; i += 4) {\n var color = grayscaleToJit(imageData.data[i + 1]); // get green value\n imageData.data[i + 0] = color.r * 255;\n imageData.data[i + 1] = color.g * 255;\n imageData.data[i + 2] = color.b * 255;\n imageData.data[i + 3] = 255;\n }\n\n // update context\n ctx.putImageData(imageData, 0, 0);\n}", "function grayscaleCanvas(image) {\n\tfor (var x = 0; x < image.data.length; x+=4) {\n\t var pixel = getPixel1(image, x);\n\n\t var luminance = 0.2126 * pixel[0] + 0.7152 * pixel[1] + 0.0722 * pixel[2];\n\t pixel[0] = luminance;\n\t pixel[1] = luminance;\n\t pixel[2] = luminance;\n\n\t setPixel1(image, pixel, x);\n\t}\n\treturn image;\n}", "grayscale() {\n this.addEffect(new Effects.Grayscale());\n }", "function to_jet() {\n\t\tvar feed = mesh_feed[this];\n\t\tvar ctx = feed.context2d,\n\t\t\tmetadata = feed.canvas.metadata,\n\t\t\trange = 255.0;\n\n\t\tif(metadata.c==='raw'){\n\t\t\tmetadata.data = new window.Float32Array(metadata.data);\n\t\t\tfeed.canvas.width = metadata.dim[1];\n\t\t\tfeed.canvas.height = metadata.dim[0];\n\t\t\trange = 5.0;\n\t\t}\n\n\t\tvar data = metadata.data,\n\t\t\tdlen = data.length,\n\t\t\timgdata = ctx.getImageData(0, 0, feed.canvas.width, feed.canvas.height),\n\t\t\tidata = imgdata.data,\n\t\t\tlen = idata.length,\n\t\t\tfourValue,\n\t\t\ti = 0,\n\t\t\tdatum;\n\n\t\t//console.log(metadata.data);\n\t\tvar w = feed.canvas.width,\n\t\t\th = feed.canvas.height;\n\t\tfor(var u = 0; u<w; u+=1){\n\t\t\tfor(var v = 0; v<h; v+=1){\n\t\t\t\tdatum = data[u*h + v];\n\t\t\t\t//datum = data[v*w + u];\n\t\t\t\tfourValue = 4 - 4 * max(0, min(datum / range, 1));\n\t\t\t\tidata[i] = 255 * min(fourValue - 1.5, 4.5 - fourValue);\n\t\t\t\tidata[i + 1] = 255 * min(fourValue - 0.5, 3.5 - fourValue);\n\t\t\t\tidata[i + 2] = 255 * min(fourValue + 0.5, 2.5 - fourValue);\n\t\t\t\tidata[i + 3] = 255;\n\t\t\t\ti += 4;\n\t\t\t}\n\t\t}\n\n\t\tctx.putImageData(imgdata, 0, 0);\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`_encodeIriOrBlank` represents an IRI or blank node
_encodeIriOrBlank(entity) { // A blank node or list is represented as-is if (entity.termType !== 'NamedNode') { // If it is a list head, pretty-print it if (this._lists && entity.value in this._lists) entity = this.list(this._lists[entity.value]); return 'id' in entity ? entity.id : '_:' + entity.value; } // Escape special characters var iri = entity.value; if (escape.test(iri)) iri = iri.replace(escapeAll, characterReplacer); // Try to represent the IRI as prefixed name var prefixMatch = this._prefixRegex.exec(iri); return !prefixMatch ? '<' + iri + '>' : !prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]; }
[ "_encodeIriOrBlank(entity) {\n // A blank node or list is represented as-is\n if (entity.termType !== 'NamedNode') {\n // If it is a list head, pretty-print it\n if (this._lists && (entity.value in this._lists))\n entity = this.list(this._lists[entity.value]);\n return 'id' in entity ? entity.id : '_:' + entity.value;\n }\n // Escape special characters\n var iri = entity.value;\n if (N3Writer_escape.test(iri))\n iri = iri.replace(escapeAll, characterReplacer);\n // Try to represent the IRI as prefixed name\n var prefixMatch = this._prefixRegex.exec(iri);\n return !prefixMatch ? '<' + iri + '>' :\n (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]);\n }", "_encodeIriOrBlank(entity) {\n // A blank node or list is represented as-is\n if (entity.termType !== 'NamedNode') {\n // If it is a list head, pretty-print it\n if (this._lists && (entity.value in this._lists))\n entity = this.list(this._lists[entity.value]);\n return 'id' in entity ? entity.id : `_:${entity.value}`;\n }\n let iri = entity.value;\n // Use relative IRIs if requested and possible\n if (this._baseMatcher && this._baseMatcher.test(iri))\n iri = iri.substr(this._baseLength);\n // Escape special characters\n if (N3Writer_escape.test(iri))\n iri = iri.replace(escapeAll, characterReplacer);\n // Try to represent the IRI as prefixed name\n const prefixMatch = this._prefixRegex.exec(iri);\n return !prefixMatch ? `<${iri}>` :\n (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]);\n }", "_encodeIriOrBlank(entity) {\n // A blank node or list is represented as-is\n if (entity.termType !== 'NamedNode') {\n // If it is a list head, pretty-print it\n if (this._lists && (entity.value in this._lists))\n entity = this.list(this._lists[entity.value]);\n return 'id' in entity ? entity.id : `_:${entity.value}`;\n }\n let iri = entity.value;\n // Use relative IRIs if requested and possible\n if (this._baseIRI && iri.startsWith(this._baseIRI))\n iri = iri.substr(this._baseIRI.length);\n // Escape special characters\n if (escape.test(iri))\n iri = iri.replace(escapeAll, characterReplacer);\n // Try to represent the IRI as prefixed name\n const prefixMatch = this._prefixRegex.exec(iri);\n return !prefixMatch ? `<${iri}>` :\n (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]);\n }", "_encodeIriOrBlank(entity) {\n // A blank node or list is represented as-is\n if (entity.termType !== 'NamedNode')\n return 'id' in entity ? entity.id : '_:' + entity.value;\n // Escape special characters\n var iri = entity.value;\n if (escape.test(iri))\n iri = iri.replace(escapeAll, characterReplacer);\n // Try to represent the IRI as prefixed name\n var prefixMatch = this._prefixRegex.exec(iri);\n return !prefixMatch ? '<' + iri + '>' :\n (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]);\n }", "function blankNode() {\n\treturn rdf.blankNode(utility.generateBlankID());\n}", "_escape (iri) {\n // More of a sanity check, really\n if (!iri || !/^\\w+:[^<> ]+$/.test(iri))\n throw new Error(`Invalid IRI: ${iri}`);\n return iri;\n }", "function null2xml_(doc, input) {\n return helperXmlRpc.createNode(doc, 'nil');\n }", "function isIRI (entity) {\n if (typeof entity !== 'string')\n return false;\n else if (entity.length === 0)\n return true;\n else {\n const firstChar = entity[0];\n return firstChar !== '\"' && firstChar !== '_';\n }\n }", "function _labelBlankNodes(issuer, element) {\n if(types.isArray(element)) {\n for(let i = 0; i < element.length; ++i) {\n element[i] = _labelBlankNodes(issuer, element[i]);\n }\n } else if(graphTypes.isList(element)) {\n element['@list'] = _labelBlankNodes(issuer, element['@list']);\n } else if(types.isObject(element)) {\n // relabel blank node\n if(graphTypes.isBlankNode(element)) {\n element['@id'] = issuer.getId(element['@id']);\n }\n\n // recursively apply to all keys\n const keys = Object.keys(element).sort();\n for(let ki = 0; ki < keys.length; ++ki) {\n const key = keys[ki];\n if(key !== '@id') {\n element[key] = _labelBlankNodes(issuer, element[key]);\n }\n }\n }\n\n return element;\n}", "function _labelBlankNodes(issuer, element) {\n if(_isArray(element)) {\n for(var i = 0; i < element.length; ++i) {\n element[i] = _labelBlankNodes(issuer, element[i]);\n }\n } else if(_isList(element)) {\n element['@list'] = _labelBlankNodes(issuer, element['@list']);\n } else if(_isObject(element)) {\n // relabel blank node\n if(_isBlankNode(element)) {\n element['@id'] = issuer.getId(element['@id']);\n }\n\n // recursively apply to all keys\n var keys = Object.keys(element).sort();\n for(var ki = 0; ki < keys.length; ++ki) {\n var key = keys[ki];\n if(key !== '@id') {\n element[key] = _labelBlankNodes(issuer, element[key]);\n }\n }\n }\n\n return element;\n}", "function isIRI (entity) {\n if (typeof entity !== 'string')\n return false;\n else if (entity.length === 0)\n return true;\n else {\n var firstChar = entity[0];\n return firstChar !== '\"' && firstChar !== '_';\n }\n }", "function _getAdjacentBlankNodeName(node, id) {\n return (node.type === 'blank node' && node.value !== id ? node.value : null);\n }", "function UINode(R, node, nodeDict) {\n this.node = node; // underlying node\n this.nodeDict = nodeDict; // id -> Node\n\n this.paper = R;\n this.shape = null; // raphael element\n}", "_encodeObject(object) {\n return object.termType === 'Literal' ? this._encodeLiteral(object) : this._encodeIriOrBlank(object);\n }", "function paddingBlankHTML(node) {\n if (!isVoid(node) && !nodeLength(node)) {\n node.innerHTML = blankHTML;\n }\n }", "function _nullCoerce() {\n return '';\n}", "function isBlankNode(obj) {\n return isTerm(obj) && 'termType' in obj && obj.termType === 'BlankNode';\n}", "function paddingBlankHTML(node) {\n if (!isVoid(node) && !nodeLength(node)) {\n node.innerHTML = blankHTML;\n }\n }", "function isBlankNode(object) {\n\n var blankNode = false;\n\n var datasetBase = configuration.getProperty(\"datasetBase\");\n\n var uriAux = object.uri.substr(datasetBase[0].length);\n\n if (uriAux.startsWith(\"nodeID:/\")){\n\n var matchesCount = uriAux.split(\"/\").length - 1;\n\n if (matchesCount == 1){\n uriAux = uriAux.substr(0,7) + \"/\" + uriAux.substr(7);\n }\n\n object.uri = uriAux;\n\n blankNode = true;\n }\n\n return blankNode;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate Transfer transaction creation with provided message
validate() { var _a; if (((_a = this.message) === null || _a === void 0 ? void 0 : _a.type) === message_1.MessageType.PersistentHarvestingDelegationMessage) { if (this.mosaics.length > 0) { throw new Error('PersistentDelegationRequestTransaction should be created without Mosaic'); } else if (!/^[0-9a-fA-F]{264}$/.test(this.message.payload)) { throw new Error('PersistentDelegationRequestTransaction message is invalid'); } } }
[ "function verifyCreateTransfer(tx, value, creator) {\n for (let l of tx.logs) {\n if (l.event === 'TransferSingle') {\n assert(l.args._operator === creator);\n // This signifies minting.\n assert(l.args._from === zeroAddress);\n if (value > 0) {\n // Initial balance assigned to creator.\n // Note that this is implementation specific,\n // You could assign the initial balance to any address..\n assert(l.args._to === creator);\n assert(l.args._value.eq(value));\n } else {\n // It is ok to create a new id w/o a balance.\n // Then _to should be 0x0\n assert(l.args._to === zeroAddress);\n assert(l.args._value.eq(0));\n }\n return l.args._id;\n }\n }\n assert(false, 'Did not find initial Transfer event');\n }", "function verifyCreateTransfer(tx, value, creator) {\n for (let l of tx.logs) {\n if (l.event === 'TransferSingle') {\n assert(l.args._operator === creator);\n // This signifies minting.\n assert(l.args._from === zeroAddress);\n if (value > 0) {\n // Initial balance assigned to creator.\n // Note that this is implementation specific,\n // You could assign the initial balance to any address..\n assert(l.args._to === creator, 'Creator mismatch');\n assert(l.args._value.toNumber() === value, 'Value mismatch');\n } else {\n // It is ok to create a new id w/o a balance.\n // Then _to should be 0x0\n assert(l.args._to === zeroAddress);\n assert(l.args._value.eq(0));\n }\n return l.args._id;\n }\n }\n assert(false, 'Did not find initial Transfer event');\n }", "validate() {\n if (this.message.type === MessageType_1.MessageType.PersistentHarvestingDelegationMessage) {\n if (this.mosaics.length > 0) {\n throw new Error('PersistentDelegationRequestTransaction should be created without Mosaic');\n }\n else if (!/^[0-9a-fA-F]{208}$/.test(this.message.payload)) {\n throw new Error('PersistentDelegationRequestTransaction message is invalid');\n }\n }\n }", "function prepareTransaction() {\r\n let amountInt=0;\r\n if (amount.value == \"\") {\r\n amount.focus();\r\n return false;\r\n }\r\n amountInt = parseInt(amount.value);\r\n \r\n if (recipient == \"\") {\r\n recipient.focus();\r\n return false;\r\n }\r\n let recipientAdr = recipient.value;\r\n\r\n let pubkey = publickey.value;\r\n if (pubkey == \"\") {\r\n publickey.focus();\r\n return false;\r\n }\r\n let prvkey = privatekey.value;\r\n if (prvkey == \"\") {\r\n privatekey.focus();\r\n return false;\r\n }\r\n\r\n let ts = _getTimestamp();\r\n let due = network.value === 'T' ? 60 : 24 * 60;\r\n let deadline = ts + due * 60;\r\n const payload = \"4e454d20415049204578616d706c657320666f72206c6561726e696e67\"; //NEM API Examples for learning \r\n const fee = 500000;\r\n const typeTx = 257;\r\n let data = {\r\n \"transaction\": {\r\n \"timeStamp\": _getTimestamp(),\r\n \"amount\": amountInt,\r\n \"fee\": fee,\r\n \"recipient\": recipientAdr,\r\n \"type\": typeTx,\r\n \"deadline\": deadline,\r\n \"message\": {\r\n \"payload\": payload,\r\n \"type\": 1\r\n },\r\n \"version\": _getVersion(1),\r\n \"signer\": pubkey,\r\n \"mosaics\": []\r\n },\r\n \"privateKey\": prvkey\r\n };\r\n\r\n _doPost('/transaction/prepare-announce', data);\r\n }", "_constructTransfer(senderPublicKey, recipientCompressedKey, amount, message, due, mosaics, mosaicsFee) {\n let timeStamp = helpers.createNEMTimeStamp();\n let version = mosaics ? this.CURRENT_NETWORK_VERSION(2) : this.CURRENT_NETWORK_VERSION(1);\n let data = this.CREATE_DATA(TransactionTypes.Transfer, senderPublicKey, timeStamp, due, version);\n let msgFee = this._Wallet.network === Network.data.Testnet.id && this._DataBridge.nisHeight >= 572500 && message.payload.length ? Math.max(1, Math.floor((message.payload.length / 32) + 1)) : message.payload.length ? Math.max(1, Math.floor(message.payload.length / 2 / 16)) * 2 : 0;\n let fee = mosaics ? mosaicsFee : this._Wallet.network === Network.data.Testnet.id && this._DataBridge.nisHeight >= 572500 ? helpers.calcMinFee(amount / 1000000) : Math.ceil(Math.max(10 - (amount / 1000000), 2, Math.floor(Math.atan((amount / 1000000) / 150000.0) * 3 * 33)));\n let totalFee = (msgFee + fee) * 1000000;\n let custom = {\n 'recipient': recipientCompressedKey.toUpperCase().replace(/-/g, ''),\n 'amount': amount,\n 'fee': totalFee,\n 'message': message,\n 'mosaics': mosaics\n };\n let entity = $.extend(data, custom);\n return entity;\n }", "createValidObject(message) {\n\n let messageOriginal = this.responseObject(message.address)\n\n mempoolValid[message.address] =\n // the registerStar variable true signals to the user that data has user is authorized\n // to send the star data in the next step 3.\n { registerStar:true,\n status: {\n address: message.address,\n requestTimeStamp: mempool[message.address],\n message: messageOriginal.message,\n // The below time information shows the current time left to add the star data prior to\n // timeout of the mempool starting from the step 1 validate request.\n validationWindow: messageOriginal.validationWindow,\n messageSignature: true\n }\n }\n return mempoolValid[message.address];\n }", "createTransaction({ recipient, amount, chain }) {\n if (chain) {\n this.balance = Wallet.calculateBalance({\n chain,\n address: this.publicKey,\n })\n }\n\n if (amount > this.balance) {\n throw new Error('Amount exceeds balance')\n }\n\n return new Transaction({ senderWallet: this, recipient, amount })\n }", "checkTransaction(transaction) {\n for (let key in transaction) {\n if (allowedTransactionKeys.indexOf(key) === -1) {\n abstract_signer_lib_esm_logger.throwArgumentError(\"invalid transaction key: \" + key, \"transaction\", transaction);\n }\n }\n let tx = Object(properties_lib_esm[\"shallowCopy\"])(transaction);\n if (tx.from == null) {\n tx.from = this.getAddress();\n }\n return tx;\n }", "static newTransaction(senderWallet, recipient, amount) {\n // console.log(transaction);\n\n // check if balance is available to make the transaction\n if (amount > senderWallet.balance) {\n console.log(`Amount: ${amount} exceeds the balance.`);\n return;\n }\n\n // then push it to the outputs of the list of transactions.\n return Transaction.transactionWithOutputs(senderWallet, [\n {\n amount: senderWallet.balance - amount,\n address: senderWallet.publicKey\n },\n { amount, address: recipient }\n ]);\n\n // console.log(\"trnsaction output\", transaction.outputs);\n\n // if (Transaction.verifyTransaction(transaction, senderWallet)) {\n // return transaction;\n // } else {\n // console.log(\"Data might have been tempered\");\n // }\n }", "checkTransaction(transaction) {\n for (const key in transaction) {\n if (allowedTransactionKeys$1.indexOf(key) === -1) {\n logger$2.throwArgumentError(\"invalid transaction key: \" + key, \"transaction\", transaction);\n }\n }\n const tx = shallowCopy(transaction);\n if (tx.from == null) {\n tx.from = this.getAddress();\n }\n else {\n // Make sure any provided address matches this signer\n tx.from = Promise.all([\n Promise.resolve(tx.from),\n this.getAddress()\n ]).then((result) => {\n if (result[0].toLowerCase() !== result[1].toLowerCase()) {\n logger$2.throwArgumentError(\"from address mismatch\", \"transaction\", transaction);\n }\n return result[0];\n });\n }\n return tx;\n }", "createTransactionFromDTO(dto, common){\n let configTransaction = nem.model.objects.create(\"transferTransaction\")(this.getOptinConfig().NIS.configAddress, 0, dto.toMessage());\n // Prepare with Signer and Network\n configTransaction = nem.model.transactions.prepare(\"transferTransaction\")(\n common,\n configTransaction,\n this._Wallet.network\n );\n return new Promise( (resolve) => {\n nem.com.requests.chain.time(this._Wallet.node).then( time => {\n configTransaction.timeStamp = Math.floor(time.receiveTimeStamp / 1000);\n configTransaction.deadline = configTransaction.timeStamp + 60 * 60;\n resolve(configTransaction);\n });\n });\n }", "function Transaction(data) {\n\tif (typeof data !== \"object\") {\n\t\tdata = {}\n\t}\n\tif (data.senderPublicKey == null || typeof data.senderPublicKey != 'object' || typeof data.senderPublicKey.length == 'undefined')\n\t\tthrow new Error('Transaction: data.senderPublicKey mast be array');\n\n\tthis.deadline = data.deadline || null;\n\tthis.senderPublicKey = data.senderPublicKey || null;\n\tthis.recipientId = data.recipientId || null;\n\tthis.amount = data.amount || 0;\n\tthis.fee = data.fee || null;\n\tthis.referencedTransactionId = data.referencedTransactionId || null;\n\tthis.type = typeof data.type !== \"undefined\" ? data.type : null;\n\tthis.height = data.height || null;\n\tthis.blockId = data.blockId || null;\n\t//this.block = data.block || null;\n\tthis.signature = data.signature || null;\n\tthis.timestamp = data.timestamp || null;\n\t//this.attachment = data.attachment || null;\n\tthis.id = data.id || null;\n\tthis.null = null;\n\tthis.senderId = data.senderId || null;\n\tthis.hash = data.hash || null;\n\tthis.confirmations = data.confirmations || 0;\n\n\tthis.version = data.version;\n\tthis.blockTimestamp = data.blockTimestamp;\n\tthis.fullHash = data.fullHash;\n\tthis.ecBlockHeight = data.ecBlockHeight;\n\tthis.ecBlockId = data.ecBlockId;\n\n\tif (typeof this.senderPublicKey == \"string\") {\n\t\tthis.senderPublicKey = new Buffer(this.senderPublicKey, \"hex\")\n\t}\n\tif (typeof this.recipientId == \"string\") {\n\t\tthis.recipientId = Utils.stringToLong(this.recipientId)\n\t}\n\tif (typeof this.referencedTransactionId == \"string\") {\n\t\tthis.referencedTransactionId = Utils.stringToLong(this.referencedTransactionId)\n\t}\n\tif (typeof this.type == \"string\" || typeof this.type == \"number\") {\n\t\tthis.type = TransactionType.findTransactionType(this.type, 0)\n\t}\n\tif (typeof this.blockId == \"string\") {\n\t\tthis.blockId = Utils.stringToLong(this.blockId)\n\t}\n\tif (typeof this.signature == \"string\") {\n\t\tthis.signature = new Buffer(this.signature, \"hex\")\n\t}\n\tif (typeof this.id == \"string\") {\n\t\tthis.id = Utils.stringToLong(this.id)\n\t}\n\tif (typeof this.senderId == \"string\") {\n\t\tthis.senderId = Utils.stringToLong(this.senderId)\n\t}\n\tif (typeof this.hash == \"string\") {\n\t\tthis.hash = new Buffer(this.hash, \"hex\")\n\t}\n\n\n\tvar list = {};\n\tif ((this.attachment = data.attachment) != null) {\n\t\tlist.add(this.attachment);\n\t}\n\tif ((this.message = data.message) != null) {\n\t\tlist.add(this.message);\n\t}\n\tif ((this.encryptedMessage = data.encryptedMessage) != null) {\n\t\tlist.add(this.encryptedMessage);\n\t}\n\tif ((this.publicKeyAnnouncement = data.publicKeyAnnouncement) != null) {\n\t\tlist.add(this.publicKeyAnnouncement);\n\t}\n\tif ((this.encryptToSelfMessage = data.encryptToSelfMessage) != null) {\n\t\tlist.add(this.encryptToSelfMessage);\n\t}\n\tthis.appendages = list; //Collections.unmodifiableList(list);\n\tvar appendagesSize = 0;\n\tfor (var appendage in this.appendages) {\n\t\tappendagesSize += appendage.GetSize();\n\t}\n\tthis.appendagesSize = appendagesSize;\n\n\tif (typeof data.height == 'undefined')\n\t\tthis.height = 2000000000 //Integer.MAX_VALUE\n\telse\n\t\tthis.height = data.height;\n\tthis.blockId = data.blockId;\n\t//this.Block =\n\tthis.signature = data.signature;\n\tthis.timestamp = parseInt(data.timestamp);\n\tif (typeof data.blockTimestamp == 'undefined')\n\t\tthis.blockTimestamp = -1\n\telse\n\t\tthis.blockTimestamp = data.blockTimestamp;\n\t//this.Attachment =\n\tthis.id = data.id;\n\tthis.stringId = null;\n\tthis.senderId = data.senderId;\n\tthis.fullHash = data.fullHash; // fullHash == null ? null : Convert.toHexString(fullHash);\n\n\t/*\n\tif ((timestamp == 0 && Arrays.equals(senderPublicKey, Genesis.CREATOR_PUBLIC_KEY))\n\t\t\t? (deadline != 0 || feeNQT != 0)\n\t\t\t: (deadline < 1 || feeNQT < Constants.ONE_NXT)\n\t\t\t|| feeNQT > Constants.MAX_BALANCE_NQT\n\t\t\t|| amountNQT < 0\n\t\t\t|| amountNQT > Constants.MAX_BALANCE_NQT\n\t\t\t|| type == null) {\n\t\tthrow new NxtException.NotValidException(\"Invalid transaction parameters:\\n type: \" + type + \", timestamp: \" + timestamp\n\t\t\t\t+ \", deadline: \" + deadline + \", fee: \" + feeNQT + \", amount: \" + amountNQT);\n\t}\n\t*/\n\n\tif (this.attachment == null || type != this.attachment.GetTransactionType()) {\n\t\tthrow new Error(\"Invalid attachment \" + this.attachment + \" for transaction of type \" + this.type);\n\t}\n\n\tif (!this.type.HasRecipient()) {\n\t\tif (this.recipientId != null || this.GetAmount() != 0) {\n\t\t\tthrow new Error(\"Transactions of this type must have recipient == Genesis, amount == 0\");\n\t\t}\n\t}\n\n\tfor (var i in this.appendages) {\n\t\tvar appendage = appendages[i];\n\t\tif (!appendage.VerifyVersion(this.version)) {\n\t\t\tthrow new Error(\"Invalid attachment version \" + appendage.GetVersion() +\n\t\t\t\t\t\" for transaction version \" + this.version);\n\t\t}\n\t}\n\n\treturn this;\n}", "checkTransaction(transaction) {\n for (const key in transaction) {\n if (allowedTransactionKeys.indexOf(key) === -1) {\n logger$f.throwArgumentError(\"invalid transaction key: \" + key, \"transaction\", transaction);\n }\n }\n const tx = shallowCopy(transaction);\n if (tx.from == null) {\n tx.from = this.getAddress();\n }\n else {\n // Make sure any provided address matches this signer\n tx.from = Promise.all([\n Promise.resolve(tx.from),\n this.getAddress()\n ]).then((result) => {\n if (result[0].toLowerCase() !== result[1].toLowerCase()) {\n logger$f.throwArgumentError(\"from address mismatch\", \"transaction\", transaction);\n }\n return result[0];\n });\n }\n return tx;\n }", "checkTransaction(transaction) {\n for (const key in transaction) {\n if (allowedTransactionKeys.indexOf(key) === -1) {\n logger.throwArgumentError(\"invalid transaction key: \" + key, \"transaction\", transaction);\n }\n }\n const tx = (0,lib_esm/* shallowCopy */.DC)(transaction);\n if (tx.from == null) {\n tx.from = this.getAddress();\n }\n else {\n // Make sure any provided address matches this signer\n tx.from = Promise.all([\n Promise.resolve(tx.from),\n this.getAddress()\n ]).then((result) => {\n if (result[0].toLowerCase() !== result[1].toLowerCase()) {\n logger.throwArgumentError(\"from address mismatch\", \"transaction\", transaction);\n }\n return result[0];\n });\n }\n return tx;\n }", "checkTransaction(transaction) {\n for (const key in transaction) {\n if (allowedTransactionKeys.indexOf(key) === -1) {\n logger$e.throwArgumentError(\"invalid transaction key: \" + key, \"transaction\", transaction);\n }\n }\n const tx = shallowCopy(transaction);\n if (tx.from == null) {\n tx.from = this.getAddress();\n }\n else {\n // Make sure any provided address matches this signer\n tx.from = Promise.all([\n Promise.resolve(tx.from),\n this.getAddress()\n ]).then((result) => {\n if (result[0] !== result[1]) {\n logger$e.throwArgumentError(\"from address mismatch\", \"transaction\", transaction);\n }\n return result[0];\n });\n }\n return tx;\n }", "static isValidTransaction(transaction) {\n // ... Verifica que una transaccion no sea entero y menor a cero\n const isValid = (TransactionProcessor.isValidAmount(transaction) && \n TransactionProcessor.isValidBrand(transaction) &&\n TransactionProcessor.isValidCurrency(transaction) &&\n TransactionProcessor.isValidID(transaction)); //!Number.isInteger(transaction.amount) && (transaction.amount >= 0);\n\n return isValid;\n }", "async function should_fail_transferfromto(senderaccount, receiveraccount, amount) {\n \n console.log('should fail transfering', amount,'ETI from senderaccount', senderaccount.address, 'to receiveraccount', receiveraccount.address);\n await truffleAssert.fails(EticaReleaseMiningInstance.transfer(receiveraccount.address, web3.utils.toWei(amount, 'ether'), {from: senderaccount.address}));\n console.log('as expected failed to transfer', amount,'ETI from senderaccount', senderaccount.address, 'to receiveraccount', receiveraccount.address);\n\n }", "createTransaction({ receiver, amount, chain }) {\n\n //if a chain is passed in and definied.\n if (chain) {\n this.balance = Wallet.calculateBalance({\n chain,\n address: this.publicKey\n });\n }\n\n //if the amount is greater than what left in the wallet balance. Throw error\n if (amount > this.balance) {\n throw new Error('Amount exceeds balance');\n }\n\n //Return a instance of a transaction class.\n return new Transaction({ senderWallet: this, receiver, amount });\n }", "function checkMessageValidity( err, result ) {\n if( err ) {\n reportError( err );\n return;\n }\n if( !result || !result[0] ) {\n reportError( 'the source practice of this message is not valid, no metaprac.', 400 );\n return;\n }\n\n var\n transfer;\n\n if( patientreg.transfer ) {\n transfer = patientreg.transfer;\n } else {\n reportError( 'invalid transfer message', 400 );\n Y.log( 'there is no transfer request for this transfer message', 'error', NAME );\n return;\n }\n\n if( transfer.source !== message.practiceId || transfer.target !== message.target ||\n transfer.eTAN !== message.eTAN ) {\n reportError( 'invalid transfer message', 400 );\n Y.log( 'the transfer message is not associated with the registered transfer', 'error', NAME );\n return;\n }\n\n try {\n hash = crypto.createHash( 'md5' ).update( JSON.stringify( content ) ).digest( 'hex' );\n } catch( e ) {\n Y.doccirrus.utils.reportErrorJSON( ac, 400, 'Invalid Data: Could not calculate hash: ' + e );\n }\n\n // get the target practice\n Y.doccirrus.mongodb.runDb( {\n user: user,\n model: 'metaprac',\n query: {customerIdPrac: message.target},\n options: {},\n callback: getTargetPatientreg\n } );\n } //checkMessageValidity" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert a cell into an array of cells based on 'r' cell reference, if a cell already exists with the same 'r' cell reference, overwrite it (only if 'allowOverwrite' = true)
function insertOrOverwriteCell(cells, newCell, allowOverwrite, allowMerge, overwriteSharedStrings, sharedStrings) { var parseCol = CellRefUtil.parseCellRefColumn; var cellIdx = parseCol(newCell.r); // if an existing cell has the same index, overwrite it (if allowed), return var findIdx = getCellIndex(cells, cellIdx); if (findIdx > -1) { if (overwriteSharedStrings) { if (sharedStrings == null) { throw new Error("cannot overwrite shared strings without shared string table"); } _lookupAndOverwriteSharedStrings(sharedStrings, cells[findIdx], newCell); } if (allowOverwrite) { cells[findIdx] = newCell; } else if (allowMerge) { cells[findIdx] = _mergeCells(cells[findIdx], newCell); } return cells[findIdx]; } // if this cell has a lower index than any of the existing cells, insert it at the beginning of the array, return if (cellIdx < parseCol(cells[0].r)) { cells.unshift(newCell); return cells[0]; } // idx = cells.length, so if no insertion point found, add to end of array var idx = cells.length; var insert = true; // search for a point between two cells where this cell index should be for (var i = 0, size = cells.length - 1; i < size; i++) { if (parseCol(cells[i].r) <= cellIdx && parseCol(cells[i + 1].r) > cellIdx) { if (parseCol(cells[i].r) == cellIdx) { idx = i; insert = false; } else { idx = i + 1; insert = true; } break; } } // if an insert point was found, insert and shift remaining cells up by one in the array if (insert) { for (var i = cells.length - 1; i >= idx; i--) { cells[i + 1] = cells[i]; } cells[idx] = newCell; return newCell; } // else, an overwrite point was found else { if (overwriteSharedStrings) { if (sharedStrings == null) { throw new Error("cannot overwrite shared strings without shared string table"); } _lookupAndOverwriteSharedStrings(sharedStrings, cells[findIdx], newCell); } if (allowOverwrite) { cells[idx] = newCell; } else if (allowMerge) { cells[idx] = _mergeCells(cells[idx], newCell); } return cells[idx]; } }
[ "function insertOrOverwriteRow(rows, newRow, allowOverwrite) {\n if (allowOverwrite === void 0) { allowOverwrite = false; }\n var rowNum = newRow.r;\n // if an existing row has the same row number, overwrite it (if allowed), return\n var rowIdx = getRowIndex(rows, rowNum);\n if (rowIdx > -1) {\n if (allowOverwrite) {\n rows[rowIdx] = newRow;\n }\n return;\n }\n // if this row has a lower row number than any of the existing cells, insert it at the beginning of the array, return\n if (rowNum < rows[0].r) {\n rows.unshift(newRow);\n return;\n }\n // idx = rows.length, so if no insertion point found, add to end of array\n var idx = rows.length;\n var insert = true;\n // search for a point between two rows where this row number should be\n for (var i = 0, size = rows.length - 1; i < size; i++) {\n if (rows[i].r <= rowNum && rows[i + 1].r > rowNum) {\n if (rows[i].r == rowNum) {\n idx = i;\n insert = false;\n }\n else {\n idx = i + 1;\n insert = true;\n }\n break;\n }\n }\n // if an insert point was found, insert and shift remaining rows up by one in the array\n if (insert) {\n for (var i = rows.length - 1; i >= idx; i--) {\n rows[i + 1] = rows[i];\n }\n rows[idx] = newRow;\n }\n // else, an overwrite point was found\n else if (allowOverwrite) {\n rows[idx] = newRow;\n }\n }", "function insert_cell(rowObject,cell_number,cell_data){\n var cell_id = rowObject.insertCell(cell_number);\n cell_id.innerHTML = cell_data;\n}", "function addArrayItem(a,o,r){\r\n\t\tfor(var i=0,len=a.length; i<len; i++){\r\n\t\t\tif (a[i][o] == r[o]){return;}\r\n\t\t}\r\n\t\ta.push(r);\r\n\t}", "function setCell(column, row, value) {\n var s = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = s.getSheetByName('Data');\n //sheet.appendRow([column, row, value]);\n sheet.getRange(getSheetTranslation(column)+row).setValue(value);\n}", "function addArrayItem(a,o,r){\n\t\tfor(var i=0,len=a.length; i<len; i++){\n\t\t\tif (a[i][o] == r[o]){return;}\n\t\t}\n\t\ta.push(r);\n\t}", "addCell (newCell) {\n this.boardCells[[newCell.getRow(), newCell.getCol()]] = newCell\n }", "function setCell(x,y, value, cellList){\n var cell = getCell(x,y, cellList);\n cell.value = value;\n if(value == undefined){\n\n cell.potential = [1,2,3,4,5,6,7,8,9];\n }\n else {\n\n cell.potential = [value];\n }\n\n\n}", "updateByRow(row, item) {\n const range = this.sheet.getRange(row, 1, 1, item.length);\n range.setValues([item]);\n }", "function add_to_coleman_sheet(data_row, coleman_to_do_sheet, coleman_exclude_arr,row_index, main_sheet, existing_tracking_nums, indexes, coleman_exclude_accounts){\n\n\n var indexActualIssues = indexes.indexActualIssues\n var indexInSirum = indexes.indexInSirum\n var indexColemanTracking = indexes.indexColemanTracking\n var indexResolved = indexes.indexHumanIssues\n var indexColoradElig = indexes.indexCOFwd\n var indexState = indexes.indexState\n var indexFacility = indexes.indexFacilityName\n \n \n var date_string = Utilities.formatDate(new Date(), \"GMT-07:00\", \"MM/dd/yyyy\")\n \n if(((data_row[indexInSirum].toString().toLowerCase().indexOf(\"coleman sheet\") == -1) && (data_row[indexInSirum].toString().indexOf(\"AdlR\") == -1)) //not already there\n && (data_row[indexColemanTracking].toString().trim().length > 0) //there is a tracking number populated in column R\n && (data_row[indexColemanTracking].toString().toLowerCase().indexOf(\"#no\") == -1) //there is a tracking number populated in column R\n && (data_row[indexColemanTracking].toString().toLowerCase().indexOf(\"#crnorecord\") == -1) //this note is not in column R\n && (coleman_exclude_arr.indexOf(data_row[indexState].toString().trim()) == -1) //not a state we want to exclude \n && (coleman_exclude_accounts.indexOf(data_row[indexFacility].toString().toLowerCase().trim()) == -1) //not a facility we don't wanna include\n && (((data_row[indexActualIssues].toString().trim().length > 0) && (data_row[indexResolved].toString().toLowerCase().indexOf(\"resolv\") > -1)) \n || (data_row[indexActualIssues].toString().replace(/;This should have gone to Coleman. Row ID: \\d{0,9}/g,\"\").trim().length == 0))\n && ((data_row[indexColoradElig].toString().length == 0) || (data_row[indexColoradElig].toString().indexOf(\"ineligible\") > -1))){\n Logger.log(\"PASSED TESTS\")\n var facility = data_row[indexFacility]\n var tracking_nums = data_row[indexColemanTracking].toString().trim()\n if(tracking_nums.length < 6){\n tracking_nums = (\"000000\"+tracking_nums).slice(-6);\n }\n \n if(existing_tracking_nums.indexOf(tracking_nums) == -1){\n coleman_to_do_sheet.appendRow([\"\",\"\",\"\",\"\",\"\",facility + \" \" + tracking_nums,facility,tracking_nums])\n main_sheet.getRange((row_index+1), (indexInSirum+1)).setValue(\"On coleman sheet \" + date_string)\n existing_tracking_nums.push(tracking_nums)\n } else {\n main_sheet.getRange((row_index+1), (indexInSirum+1)).setValue(\"ALREADY ON COLEMAN SHEET\")\n }\n }\n \n return existing_tracking_nums\n}", "addNeighborCellsToCandidates(r, c) {\n for (let dr = -1; dr < 2; dr++) {\n for (let dc = -1; dc < 2; dc++) {\n let rr = r + dr\n , cc = c + dc\n if (!checkr(rr) || !checkr(cc) || (rr === r && cc === c) || this.tiles[rr][cc].taken !== undefined) {\n continue\n }\n let pi = this.findCandidate(rr, cc)\n if (pi === -1) {\n let pp = new Cell(rr,cc,1)\n this.candidates.push(pp)\n //check opposite cell\n let ro = r - dr\n , co = c - dc\n if (checkr(ro) && checkr(co)) {\n if (this.tiles[ro][co].taken === undefined) {\n let poi = this.findCandidate(ro, co)\n if (poi === -1) {\n let po = new Cell(ro,co,1)\n pp.peers.push(po)\n po.peers.push(pp)\n this.candidates.push(po)\n } else {\n //opposite cell already candidates\n let po = this.candidates[poi]\n pp.peers.push(po)\n po.peers.push(pp)\n po.incrWeight()\n //increase po's weight\n }\n } else if (this.tiles[ro][co].taken !== this.tiles[r][c].taken) {\n pp.decrWeight();\n }\n }\n }\n }\n }\n }", "function pushCell(cell)\n{\n drawCells.push(cell);\n}", "extendCell(cell) {\n\t\t\n\t}", "insert(index, cell) {\r\n // Set the internal data structures.\r\n this._cellMap.set(cell.id, cell);\r\n this._cellOrder.insert(index, cell.id);\r\n }", "function addCell(content, whichRow, whichKind, array){\r\n\tvar cell = document.createElement(whichKind);\r\n\tcell.innerHTML = content;\r\n\twhichRow.appendChild(cell);\r\n\tarray.push(cell);\r\n\tcell.id = \"newCell\" + (array.length - 4);\r\n}", "function insertCell(j, newRow, text) { \n\tlet newCell = newRow.insertCell(j);\n\tlet newText = document.createTextNode(text);\n\tnewCell.appendChild(newText);\n}", "insert(index, cell) {\n // Set the internal data structures.\n this._cellMap.set(cell.id, cell);\n this._cellOrder.insert(index, cell.id);\n }", "function placeWalkable(row, col)\n{\n if((row!=myRover.position[0] && col!=myRover.position[1]) || (row!=mySecondRover.position[0] && col!=mySecondRover.position[1]))\n {\n grid[row][col]=1;\n }\n else {\n console.log(\"Impossible to customize this cell, there is a rover on it\");\n }\n}", "addToRow(i, r)\n {\n this.matrix[i].addRow(r);\n }", "placeInEmptyCell(f) {\n for (let r = 0; r < this.rowCount; r++) {\n let row = this.data[r];\n for (let c = 0; c < this.colCount; c++) {\n let cell = row[c];\n if (!cell) {\n this.data[r][c] = {'x':r,'y':c,'formula':f}\n return;\n } else if (!cell.formula) {\n this.data[r][c].formula = f;\n return;\n }\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the names of the first 10 courses the user has access to. If no courses are found an appropriate message is printed.
function listCourses() { console.log('It is hitting listCourses') var request = gapi.client.classroom.courses.list({ pageSize: 10 }); request.execute(function(resp) { var courses = resp.courses; appendPre('Courses:'); if (courses.length > 0) { for (i = 0; i < courses.length; i++) { var course = courses[i]; appendPre(course.name) } } else { appendPre('No courses found.'); } }); }
[ "function GetCourseName(num, cjo) {\r\n\tvar courses_jo = cjo.courses;\r\n\tfor(var i in courses_jo) {\r\n\t\tif(num == courses_jo[i].course_number &&\r\n\t\t\tcourses_jo[i].subject == \"CMP SCI\")\r\n\t\t\treturn courses_jo[i].course_name;\r\n\t}\r\n\treturn \"No CMP SCI Course with that course number\";\r\n}", "function listCourses() {\r\n\t\tgapi.client.classroom.courses.list({\r\n\t\t\tpageSize: 10\r\n\t\t}).then(function(response) {\r\n\t\t\tvar courses = response.result.courses;\r\n\t\t\tappendPre('Courses:');\r\n\t\t\tif(courses.length > 0) {\r\n\t\t\t\tfor(i = 0; i < courses.length; i++) {\r\n\t\t\t\t\tvar course = courses[i];\r\n\t\t\t\t\tappendPre(course.name)\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tappendPre('No courses found.');\r\n\t\t\t}\r\n\t\t});\r\n\t}", "function user_courses() {\n var content = $(\"#usercourses-container\");\n if(!content.length) {\n return;\n }\n var paging = $(\"#content-loader\").children(),\n tab = content.data('tab'),\n url = '/ajax/user/' + window.$_URL.username + '/' + tab;\n\n _paginate(url, {}, \"\", content, paging, function(data){\n if(data.content.length == 0) {\n return '<div class=\"empty-box\"><p>' + window.i18n.courses_none + '</p></div>';\n }\n return data.content.join('')\n + '<div class=\"course-box is-empty\"></div>'\n + '<div class=\"course-box is-empty\"></div>'\n + '<div class=\"course-box is-empty\"></div>';\n });\n}", "function printCourse (c) {\n if (c != null) {\n var reqs = \"\";\n for (var i = 0; i < c.pre_reqs.length; i++) {\n if (i != c.pre_reqs.length-1) reqs += c.pre_reqs[i] + \", \";\n else reqs += c.pre_reqs[i] + \"\";\n }\n console.log(c.properties\n + \"\\n[NAME: \" + c.name\n + \"] -- [TITLE: \" + c.title\n + \"] -- [ID: \" + c.id\n + \"] -- [DEPARTMENT: \" + c.department\n + \"]\\n[PRE_REQUISITES: \" + reqs\n + \"]\\n\\n\");\n }\n}", "function displayInterestedCourses(){\n\n}", "function displayTopCourses(){\n\n}", "function listCourses() {\n var courses = [];\n var pageToken = null;\n var optionalArgs = {\n pageToken: pageToken,\n pageSize: 100\n };\n while (true) {\n var response = Classroom.Courses.list(optionalArgs);\n var courses = response.courses;\n if (!pageToken) {\n break;\n }\n }\n if (courses.length === 0) {\n Logger.log(\"No courses found.\");\n } else {\n Logger.log(\"Courses:\");\n for (course in courses) {\n Logger.log('%s (%s)', courses[course].name, courses[course].id);\n }\n }\n}", "function displayRecommendedCourses(){\n\n}", "async function displayCourses(){\n try{\n const coorses= await getCourseDetails();\n console.log(`Details of Required Courses:\\n${coorses}`);\n }catch(err){\n console.log(`Error in displaying course details: ${err}`)\n }\n}", "function displayCurrentCourses(){\n\n}", "function courses() {\n var content = $(\"#courses-container\"),\n paging = $(\"#content-loader\").children();\n\n _paginate('/ajax/courses', {\n lang: window.$_URL.currentLang,\n cat : window.$_URL.currentCat,\n q : window.$_GET.q\n }, (window.$_GET.q ? \"?q=\" + encodeURIComponent(window.$_GET.q) : \"\"), content, paging, function(data, current_page) {\n if(data.content.trim() == \"\" && current_page == 1) {\n return '<div class=\"empty-box\"><p>' + window.i18n.courses_none + '</p></div>';\n } else {\n return data.content;\n }\n });\n}", "function VerifyCourses(category) {\n if (category.length === 0) {\n noCourses = \" No courses listed |\"\n }\n}", "function printcourses(courselist){\n var courselisthtml = document.createElement('ul');\n\n for (var i = 0; i < courselist.length; i++){\n // Create the list item:\n var item = document.createElement('li');\n // Set its contents:\n item.appendChild(document.createTextNode(courselist[i].name));\n item.appendChild(document.createTextNode(' ('));\n item.appendChild(document.createTextNode(courselist[i].course_type.name));\n item.appendChild(document.createTextNode(') '));\n item.appendChild(document.createTextNode(courselist[i].institution.name));\n\n // Check if the course is recent/maintained\n // use the \"Updated\" value: historic if updated ealier than 2019.\n if (parseInt(courselist[i].updated.substring(4,0)) < 2019) {\n item.appendChild(document.createTextNode(' ('));\n item.appendChild(document.createTextNode('historic'));\n item.appendChild(document.createTextNode(') '));\n }\n\n // add a more... text in span and set class for styling\n var itemSpan = document.createElement('span');\n itemSpan.appendChild(document.createTextNode(' more...'));\n itemSpan.setAttribute(\"class\", 'moreText');\n item.appendChild(itemSpan);\n // add a tooltip to the list item\n var itemTip = document.createElement('span');\n itemTip.appendChild(document.createTextNode('Click for more information on course and matching literature from external sources.'))\n itemTip.setAttribute(\"class\", 'courseTipText')\n itemSpan.appendChild(itemTip)\n // set html attributes for list item\n item.setAttribute(\"id\", ''.concat('cid-', courselist[i].id));\n item.setAttribute(\"class\", 'courseEntry');\n item.setAttribute(\"onclick\", ''.concat('openCourseModul(',courselist[i].id,')'));\n // Add it to the list:\n courselisthtml.appendChild(item);\n }\n return courselisthtml;\n}", "function showTextCourses(rawData) {\r\n\t var rowStrings = rawData.split(/[\\n\\r]+/);\r\n var headings = [\"Course ID\",\"Course Name\",\"Credits\",\"Duration(Yr)\",\"Leader\", \" \"];\r\n var rows = new Array(rowStrings.length-1);\r\n for(var i=1; i<rowStrings.length; i++) {\r\n rows[i-1] = rowStrings[i].split(\"##\");\r\n }\r\n if(rows.length == 1) {\r\n\t\tif($(\"#paging\").val() == 0)\r\n\t\t\treturn showNoResults();\r\n\t\telse\r\n\t\t\tprevious();\r\n }\r\n rows = checkBlankRows(rows);\r\n var table = getTable(headings, rows);\r\n \r\n pagingFunction(rows);\r\n \r\n if(rows.length > 0) {\r\n \t$(\"#hideResultsName\").show();\r\n }\r\n $(\"#course-name-results\").html(table);\r\n $(\"#course-name-results\").show();\r\n\t setOnClickUpdateJSON();\r\n\t setOnClickDelete();\r\n\t}", "function compsciCoursesDisplay() {\r\n refreshDisplayScreen();\r\n document.getElementById(\"computersciHeading\").innerHTML = \"Computer Science Departmet Courses\"; /*this display the heading of the page*/\r\n document.getElementById(\"courses\").style.display = \"block\";\r\n getCompsciCoursesList();\r\n}", "function displayCourseInfo(data, course_id) {\r\n // console.log(\"COURSE INFO DISPLAYED\");\r\n displayStudents(data[\"students\"], course_id);\r\n}", "function getCourseByName() {\n\n}", "showStudents() {\n if (this.students.length === 0) {\n console.log(`${this.name} has no students yet!`);\n } else {\n const teacherStudentsNames = this.students.map(s => s.name);\n console.log(`${this.name} students:\\n ${teacherStudentsNames}\\n`);\n }\n }", "function showMajors(){\n\n majorOfStudent={};\n\n for(let student of students){\n name = student.name;\n major = findDepartment[student.courses[0]]; // temporary major\n depCounter={}; // keep count of departments for each student\n depSize=0;\n for(let course of student.courses){\n\n currDep = course.substring(0,3);\n if(currDep===\"THR\") currDep=\"FAR\";\n // [DEBUG] console.log(course);\n if(!depCounter[currDep]){\n depCounter[currDep]=1;\n }\n else{\n depCounter[currDep]+=1;\n if(depCounter[currDep]>depSize){\n depSize = depCounter[currDep];\n majorOfStudent[name] = currDep; // map to the major\n }\n }\n }\n if(depSize<2) {\n majorOfStudent[name] = \"Not enough courses for major\";\n }\n }\n console.log(\"Showing majors of each student...\");\n for (let student of students) {\n console.log(\" > \"+ student.name + \" | \" + majorOfStudent[student.name]);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the URL for the carousel page.
function getCarouselUrl(page) { carouselStr = new String(CAROUSEL_URL); carouselStr = carouselStr.replace('/x/', '/'+page+'/'); carouselStr = carouselStr.replace('y.ajax', Math.floor(Math.random()*10) + '.ajax'); return carouselStr; }
[ "function getCurrentSlideLink() {\r\n return window.location.href;\r\n}", "static async getURL() {\n url = await driver.getDriver().execute(`return document.URL`)\n logger.info('Current page URL: [ ' + url + ' ]')\n return url\n }", "get url() {\n\t\tif (this.path != '')\n\t\t\treturn `${this.host}/${this.path}/${this.document}`;\n\t\telse\n\t\t\treturn `${this.host}/${this.document}`;\n\t}", "function getSlotImageURL() {\n\tvar imageURL = URLgenerator.getUrlForContentSlot(request.httpParameterMap);\n\n\tISML.renderTemplate('cloudinary/renderimageurl', {\n\t\timageURL: imageURL\n\t});\n}", "getURL() { return Abstract.baseURL + this.url; }", "getNextPageUrl() {\n if (this.hasMorePages) {\n return this.getUrl(this.currentPage + 1);\n }\n return null;\n }", "get slideshowURL()\n {\n let args = this._dataSource.args;\n args.hash.set(\"slideshow\", \"first\");\n args.hash.set(\"view\", \"illust\");\n return args;\n }", "getUrl() {\n if (!this._url) {\n this._url = new URL(location + \"\");\n }\n\n return this._url;\n }", "getURL() { return Work.baseURL + this.url; }", "getPageUrl(){\n return this.url;\n }", "getUrl() {\n let url = ''\n let pageConfig = Config.pages[this.page] || {}\n\n if(this.isBlogPost) {\n url = `${Config.siteUrl}/${this.post.frontmatter.path}`\n }\n else {\n url = pageConfig.url || Config.siteUrl\n }\n\n return url\n }", "getPageLink() {\n\t\t\tif (cur.module === \"public\") {\n\t\t\t\treturn cur.options.public_link;\n\t\t\t} else if (cur.module === \"groups\") {\n\t\t\t\tconst { loc } = cur.options.loc;\n\n\t\t\t\tif (loc) return `/${loc}`;\n\n\t\t\t\treturn `/club${cur.options.group_id}`;\n\t\t\t}\n\t\t}", "function Utils_GetPageURL() {\n\treturn $(location).attr('href');\n}", "function getUrl(targetPage) {\n var buildPath = Handlebars.helpers.getBuildPath();\n var currentPage = Handlebars.helpers.getPagePath();\n var path = require('path');\n\n // dirname doesn't have a trailing slash, so add one\n currentPage = (currentPage + '/').replace('//', '');\n targetPage = (targetPage + '/').replace('//', '');\n\n if (buildPath && typeof buildPath === 'string') {\n currentPage = currentPage.replace(buildPath, '');\n targetPage = targetPage.replace(buildPath, '');\n }\n\n return path.relative(currentPage, targetPage);\n }", "function getUrl(){\n\t\treturn document.navigation.href;\t\t\t\t\t\t\t\t\t//RETURNING CURRENT TAB URL\n\t}", "function buildPageUrl() {\n var currLocation = \"\";\n currLocation += $location.protocol();\n currLocation += '://';\n currLocation += $location.host();\n var port = $location.port();\n if (port !== '80') {\n currLocation += ':';\n currLocation += port;\n }\n currLocation += $location.path();\n return currLocation;\n }", "getURL() { return this.url; }", "getURL() {\n return Meteor.absoluteUrl(UploadFS.config.storesPath + '/' + this.name, {\n secure: UploadFS.config.https\n });\n }", "function getViewLink(pageData) {\n return `https://benja-johnny.github.io/urlpages/${pageData}`;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
since there is an error, make allFormsValid false create a paragraph element with a class of error, and errorIndication text make the text colour red insert the paragraph after the invalid form
function addErrorIndication(errorIndication, elem) { allFormsValid = false; var errorPara = document.createElement("p"); var node = document.createTextNode(errorIndication); errorPara.appendChild(node); errorPara.className = 'error'; errorPara.style.color = 'red'; elem.parentNode.insertBefore(errorPara, elem.nextSibling); }
[ "function validateErrors(err) {\n if (err) {\n var d = document.getElementById(\"dialog2\");\n var validation = document.createElement(\"div\");\n validation.id = \"validation\";\n validation.style = \"color:red;\";\n validation.innerText = err;\n d.appendChild(validation);\n }\n}", "function drawRegistrationError() {\r\n var container = document.getElementById('welcome');\r\n container.innerHTML = \"<span class='error'>Registration form couldn't load!</span>\" + container.innerHTML;\r\n}", "function puterrors(error) {\n\tvar errBox = document.getElementById(\"reg-body\");\n\t// set the error box border to solid (from unset/hidden)\n\terrBox.style.borderStyle = \"solid\";\n\t// create a br (line break) element\n\tvar br = document.createElement(\"br\");\n\tvar br2 = document.createElement(\"br\");\n\t//check if there have been any previous errors. If not, create a \"Errors:\" headlines\n\tvar check = document.getElementById(\"errHead\");\n\tif (!check) {\n\t\tvar h4 = document.createElement(\"h4\");\n\t\th4.id = \"errHead\";\n\t\tvar errText = document.createTextNode(\"Errors:\");\n\t\th4.appendChild(errText);\n\t\terrBox.appendChild(h4);\n\t\t//add a line break after the headline\n\t\terrBox.appendChild(br);\n\t}\n\t//create a text node for the error message\n\tvar textNode = document.createTextNode(error);\n\t//add the error message to the error box\n\terrBox.appendChild(textNode);\n\t//add a line break after each error\n\terrBox.appendChild(br2);\n}", "function showErr() {\n var err = document.getElementById(\"error\");\n err.style.display = \"block\"; //Toggle css display on \n err.innerHTML = \"*All fields required\"; //Add & display error message\n}", "function validaFormNewProdotto(){\n\t\tvar Nome = document.getElementById(\"new_nome\").value;\n\t\tvar Desc = document.getElementById(\"new_descrizione\").value;\n\t\tvar Prezzo = document.getElementById(\"new_prezzo\").value;\n//Svuoto gli errori del nome\n\t\tvar Form = document.getElementById('l_nome').innerHTML;\n\t\tvar Form = Form.replace('<span class=\"error\">Nome obbligatorio <\\/span>', \"<!-- errore_nome -->\");\n\t\tdocument.getElementById('l_nome').innerHTML = Form;\n\n//Svuoto gli errori della descrizione\n\t\tvar Form = document.getElementById('l_descrizione').innerHTML;\n\t\tvar Form = Form.replace('<span class=\"error\">Descrizione obbligatoria <\\/span>', \"<!-- errore_descrizione -->\");\n\t\tdocument.getElementById('l_descrizione').innerHTML = Form;\n\n//Svuoto gli errori del prezzo\n\t\tvar Form = document.getElementById('l_prezzo').innerHTML;\n\t\tvar Form = Form.replace('<span class=\"error\">Prezzo obbligatorio</span>', \"<!-- errore_prezzo -->\");\n\t\tdocument.getElementById('l_prezzo').innerHTML = Form;\n\tvar check = true;\n\n\t//Svuoto gli errori dei caratteri vietati\n\tvar Form = document.getElementById('inizioForm').innerHTML;\n\tvar Form = Form.replace('<span class=\"error\">Non sono ammessi i caratteri \"&gt;\", \"&lt;\" ed \";\"<\\/span>', \"<!-- errore_caratteri -->\");\n\tdocument.getElementById('inizioForm').innerHTML = Form;\n\n\t//Controllo se sono presenti caratteri vietati\n\tif(Nome.indexOf(\"<\") >= 0 || Nome.indexOf(\">\") >= 0 || Nome.indexOf(\";\") >= 0 ||\n\t Desc.indexOf(\"<\") >= 0 || Desc.indexOf(\">\") >= 0 || Desc.indexOf(\";\") >= 0 ||\n\t Prezzo.indexOf(\"<\") >= 0 || Prezzo.indexOf(\">\") >= 0 || Prezzo.indexOf(\";\") >= 0){\n\tvar Form = document.getElementById('inizioForm').innerHTML;\n\tvar Form = Form.replace(\"<!-- errore_caratteri -->\",'<span class=\"error\">Non sono ammessi i caratteri \"&gt;\", \"&lt;\" ed \";\"<\\/span>');\n\tdocument.getElementById('inizioForm').innerHTML = Form;\n\tcheck = false;\n\t}\n\n\n\tif(Nome == \"\" || Nome == \"undefined\"){\n\t\tvar Form = document.getElementById('l_nome').innerHTML;\n\t\tvar Form = Form.replace(\"<!-- errore_nome -->\",'<span class=\"error\">Nome obbligatorio <\\/span>');\n\t\tdocument.getElementById('l_nome').innerHTML = Form;\n\t\tcheck = false;\n\t}\n\tif(Desc == \"\" || Desc == \"undefined\"){\n\t\tvar Form = document.getElementById('l_descrizione').innerHTML;\n\t\tvar Form = Form.replace(\"<!-- errore_descrizione -->\",'<span class=\"error\">Descrizione obbligatoria <\\/span>');\n\t\tdocument.getElementById('l_descrizione').innerHTML = Form;\n\t\tcheck = false;\n\t}\n\tif(Prezzo == \"\" || Prezzo == \"undefined\"){\n\t\tvar Form = document.getElementById('l_prezzo').innerHTML;\n\t\tvar Form = Form.replace(\"<!-- errore_prezzo -->\",'<span class=\"error\">Prezzo obbligatorio</span>');\n\t\tdocument.getElementById('l_prezzo').innerHTML = Form;\n\t\tcheck = false;\n\t}\n\treturn check;\n}", "function fieldValidationFail(formElement,messages,dataTypes,result){\n\t\n\t//Add ARIA\n\tjQuery(formElement).attr('aria-invalid','true');\n \n\t// get message object\n\tvar jQuerymessage=getMessageObj(formElement);\n\t \n\t//build the text of the actual message\n\tvar messageText=\"* \";\n\tfor(var i=0;i<messages.length;i++){\n\t\tmessageText+=messages[i]+\" *\";\n\t \n\t}\n\t \n\t//If it isn't already showing, display the message\n\tif(jQuerymessage.find('span.'+messageClass).length==0||jQuerymessage.find('span.'+messageClass).text()!=messageText){\n\t\tjQuerymessage.html(\"<span class='\"+messageClass+\"' style='display:none' role='alert'>\"+messageText+\"\");\n\t\tjQuerymessage.find('span.'+messageClass).fadeIn('slow');\n\t}\n \n \n \n}", "function show_validation_message() {\n var desc = this.nextElementSibling;\n if(this.validity.valid) {\n\tdesc.textContent = desc.dataset.desc;\n\tdesc.dataset.color = '';\n } else {\n\tdesc.textContent = this.validationMessage;\n\tif(this.value === '')\n\t desc.textContent = printf(\n\t\t_('%1 cannot be empty.'),\n\t\tthis.placeholder\n\t );\n\tdesc.dataset.color = 'err';\n }\n}", "function invalid(element,msg){\n\t\t\telement.insertAdjacentHTML(\"afterend\",\n\t\t\t'<div class=\"error\">'+msg+'</div>')\n\t\t\tisValid = false;\n\t\t}", "function displayHTMLErrors(f, errorInfo)\n {\n var errorHTML = \"<div class='msg-correcao'>\" + options.errorTextIntro + \"</div>\";\n for (var i=0; i<errorInfo.length; i++)\n {\n errorHTML += options.errorHTMLItemBullet + errorInfo[i][1] + \"<br />\";\n styleField(errorInfo[i][0], i==0);\n }\n\n if (errorInfo.length > 0)\n {\n\t$(f).find(\".\" + options.errorTargetElementId).css(\"display\", \"block\");\n\t$(f).find(\".\" + options.errorTargetElementId).html(errorHTML);\n\t\n /*$(\".\" + options.errorTargetElementId).css(\"display\", \"block\");\n $(\".\" + options.errorTargetElementId).html(errorHTML);*/\n\t\n return false;\n }\n\n return true;\n }", "formValidation(validState, labelText, inputElement, errorMsg)\n\t{\n\n\t\tif(!validState())\n\t\t{\n\t\t\t\n\t\t\treturn printError(labelText, inputElement, errorMsg);\n\t\t\t\n\t\t}\n\n\t\telse \n\t\t{\n\t\t\t\n\t\t\treturn printNeutral(labelText, inputElement);\t\n\t\t\t\n\t\t}\n\n\n\n\t}", "validate() {\n const errorId = `error_for_${this.#id}`;\n\n $(\"#\" + errorId).remove();\n\n if (this.isValid) {\n return;\n }\n\n const newErrorNode = $(\"<span/>\", {\n id: errorId,\n class: \"errorHint\",\n text: this.#validator.error,\n });\n\n newErrorNode.insertBefore(this.element);\n }", "function displayErrors(errors, form) {\n\n errors.forEach(function (error) {\n $(form).find(\"input[name=\" + error.input + \"]\")\n .after('<div style=\"color: red\" class=\"error\"><strong>' + error.message + '</strong></div>');\n });\n}", "function addError(){\nfor (var i = 0; i < error.length; i++) {\n error[i].innerHTML=\"Required\";\n }\n}", "function displayFieldsetError(legend, errMsg) {\n\tlegend.insertAdjacentHTML('beforeend', `<span class=\"error sm-error\"><br>${errMsg}</span>`);\n}", "function styleFailedFields() {\n for (let fieldName in fieldValidity) {\n if (fieldName === 'activities' && !fieldValidity.activities) {\n showActivitiesAsInvalid();\n } else if (!fieldValidity[fieldName]) {\n showFieldAsInvalid('#' + fieldName);\n }\n }\n}", "function renderFormErrors(errors) {\n const div = document.createElement('div');\n if (errors) {\n for (i = 0; i < errors.length; i++) {\n const p = document.createElement('p')\n p.innerHTML = errors[i];\n div.append(p);\n }\n }\n return div;\n}", "function appendError()\n\n {\n\n if ( label == null || typeof label.innerHTML == 'undefined' ) return;\n\n if ( typeof label.original == 'undefined' )\n\n label.original = label.innerHTML;\n\n label.innerHTML = label.original + \" - \" + emsg.toHTML();\n\n }", "function invalidInput(append, id, error, originalID, form) {\r\n\t\t\t\tif (append) {\r\n\t\t\t\t\t$(id).append(\"<p class='\" + originalID + \"'>\" + \"<img src='images/cancel.svg' style='height: 14px; width: 14x' />\" + \" \" + originalID.toUpperCase() + \": \" + error +\"<br /></p>\");\r\n\t\t\t\t} else {\r\n\t\t\t\t\t$('#' + form + \" \" + id).after(\"<span class='warningMsg'>\" + \"<img src='images/cancel.svg' style='height: 14px; width: 14x' />\" + \" \" + error + \"</span>\");\r\n\t\t\t\t}\r\n\t\t\t}", "function colorErrorFields() {\r\n $j(document).ready(function() {\r\n $j(\"span.error\").next().addClass('validationError'); \r\n });\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform any work necessary to start application load manifest from url display splash screen create external application manager download any assets for external applications create MainSystem create our first application using application manager
startApp() { const manifest = this.manifest; logger.debug('main->startApp'); const splashScreenImage = this.getManifestEntry('splashScreenImage'); if (splashScreenImage) { const manifestTimeout = this.getManifestEntry('splashScreenTimeout'); MainWindowProcessManager.showSplashScreen(splashScreenImage, manifestTimeout) .catch(err => logger.error(`Unable to load splash screen ${err}`)); } // https://docs.microsoft.com/en-us/windows/desktop/shell/appids this.app.setAppUserModelId(this.getManifestEntry('startup_name.name') || 'sea'); this.app.manifest = manifest; PermissionsManager.setDefaultPermissions(manifest.electronAdapter.permissions); MainWindowProcessManager.setManifest(manifest); manifest.main.icon = manifest.main.applicationIcon; logger.log(`APPLICATION LIFECYCLE: Starting main application ${manifest.main.name}`); MainWindowProcessManager.createWindowProcess(manifest.main, manifest, null, (err, res) => { if (err) logger.error(`Failed to start main application ${err}`); logger.log('APPLICATION LIFECYCLE: Main application started.'); }); this.setContentSecurityPolicy(); this.setupChromePermissionsHandlers(); }
[ "function manifestStartup() {\n // Fixed Controllers\n startupClipboard(); // manifest_clipboard.js\n startControlBar(); // manifest_controlBar.js\n\n\n // Manifest Sheets\n list_manifestsheets();\n\n\n // Run Jumper and Manifest Routines\n //routinesJumpers();\n routinesManifestSheet();\n\n\n // Disable Selection\n doSelectDisable();\n\n // Startup Version Checking\n loopVersionCheck();\n\n // Autocomplete\n compile_jumperlist_names();\n activateAutoComplete();\n}", "function initApp() {\r\n var startUpInfo;\r\n MemoryMatch.setPlatform();\r\n startUpInfo = \"Loading \" + MemoryMatch.getAppInfo();\r\n if (MemoryMatch.debugMode) {\r\n MemoryMatch.debugLog(startUpInfo);\r\n } else {\r\n console.log(startUpInfo);\r\n }\r\n\r\n // Listeners for all possible cache events\r\n\r\n var cache = window.applicationCache;\r\n if (cache != null) {\r\n cache.addEventListener('cached', MemoryMatch.logCacheEvent, false);\r\n cache.addEventListener('checking', MemoryMatch.logCacheEvent, false);\r\n cache.addEventListener('downloading', MemoryMatch.logCacheEvent, false);\r\n cache.addEventListener('error', MemoryMatch.logCacheEvent, false);\r\n cache.addEventListener('noupdate', MemoryMatch.logCacheEvent, false);\r\n cache.addEventListener('obsolete', MemoryMatch.logCacheEvent, false);\r\n cache.addEventListener('progress', MemoryMatch.logCacheEvent, false);\r\n cache.addEventListener('updateready', MemoryMatch.logCacheEvent, false);\r\n }\r\n if (document.getElementById(MemoryMatch.loaderElement) != null) {\r\n // show canvas under loader so we can implement a loadbar until we get everything setup for EaselJS to take over\r\n document.getElementById(MemoryMatch.loaderElement).style.display = \"block\";\r\n document.getElementById(MemoryMatch.stageCanvasElement).style.display = \"block\";\r\n }\r\n\r\n // Determine canvas size, it will determine which assets need to be loaded\r\n MemoryMatch.isDesiredOrientationWhenLoadStarted = MemoryMatch.isDesiredOrientation();\r\n MemoryMatch.setCanvasSize(null);\r\n MemoryMatch.loadAllAssets(false);\r\n\r\n //runTests(); // run unit tests\r\n}", "function initTaskLauncher(){\n\t\"use strict\";\n\tif (typeof tizen !== 'undefined') {\n\t\ttry {\n\t\t\t//Update the topbar icon\n\t\t\tif(tizen.application.getCurrentApplication().appInfo.packageId == \"JLRPOCX001\")\n\t\t\t\t$(\"#homeScreenIcon\").attr('src', '/DNA_common/images/tizen.png');\n\t\t\telse\n\t\t\t\t$(\"#homeScreenIcon\").attr('src', '/DNA_common/images/homescreen_icon.png');\n\n\t\t\t// get the installed applications list\n\t\t\ttizen.application.getAppsInfo(onTaskInfoSuccess, function(err) {\n\t\t\t\t// Workaround due to https://bugs.tizen.org/jira/browse/TIVI-2018\n\t\t\t\twindow.setTimeout(function() {\n\t\t\t\t\tinitTaskLauncher();\n\t\t\t\t}, 1000);\n\n\t\t\t\tonError(err);\n\t\t\t});\n\t\t} catch (exc) {\n\t\t\tconsole.error(exc.message);\n\t\t}\n\t}\n}", "function LaunchProgram(application, url, args) {\n OverlayScreenForLaunch()\n $.ajax({\n url: \"/Action/Launch?name=\" + application + (args == null ? \"\" : \"&args=\" + encodeURIComponent(args)),\n success: function (data) {\n window.location = url;\n },\n error: function (xhr, ajaxOptions, thrownError) {\n RemoveScreenOverlay()\n },\n cache: false\n });\n}", "function initializeMobileFabricInAppInit() {\n kony.print(\" ########## Entering into initializeMobileFabricInAppInit ########## \");\n if (kony.net.isNetworkAvailable(constants.NETWORK_TYPE_ANY)) {\n kony.application.showLoadingScreen(\"loadskin\", \"Initializing the app !!!\", constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true, {\n enableMenuKey: true,\n enableBackKey: true,\n progressIndicatorColor: \"ffffff77\"\n });\n mobileFabricConfiguration.konysdkObject = new kony.sdk();\n mobileFabricConfiguration.konysdkObject.init(mobileFabricConfiguration.appKey, mobileFabricConfiguration.appSecret, mobileFabricConfiguration.serviceURL, initializeMobileFabricInAppInitSuccess, initializeMobileFabricFailure);\n } else alert(\"Network unavailable. Please check your network settings. \");\n kony.print(\" ########## Exiting out of initializeMobileFabricInAppInit ########## \");\n}", "function onLaunchSuccess() {\n\t\"use strict\";\n\tconsole.log(\"App launched succesfully...\");\n\t//tizen.application.getCurrentApplication().hide();\n}", "async function loadApp() {\n await setupApp();\n}", "function _initial_setup_app_init(){\n\t\t\t//initial setup config of our App\n\t\t\tneatFramework.utils_module_disable_context_menu(); // disable the context menu on all devices (desktop | mobile)\n\t\t\tneatFramework.utils_module_get_device_type(); // get current browsing device type\n\t\t\tneatFramework.utils_module_support_fullscreen(); // check if the current browsing device support fullscreen\n\t\n\t\t\tneatFramework.utils_module_support_history_api();\n\t\t\t//debug\n\t\t\tneatFramework.utils_module_read_current_history_stack();\n\t\n\t\t\t//ios specific parts of the init\n\t\t\tneatFramework.iOS_module_handle_standalone_status_bar_spacer();\n\t\t\tneatFramework.iOS_module_handle_fullscreen_support();\n\t\t\tneatFramework.iOS_module_disable_elastic_scrolling();\n\t\t\tneatFramework.iOS_module_setup_custom_scroll('longHeightContent');\n\t\t}", "loadManifest() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const { application } = (yield this.applicationService.detail(`${this.state.app.contextPath}/manifest`)).data;\n this.state.app.manifest = application;\n this.loadDefaultOptions();\n }\n catch (ex) {\n throw ex;\n }\n });\n }", "function initializeMobileFabricInAppInit()\n{ \n\tkony.print (\" ########## Entering into initializeMobileFabricInAppInit ########## \");\n\tif (kony.net.isNetworkAvailable(constants.NETWORK_TYPE_ANY))\n\t{\n\t\tkony.application.showLoadingScreen(\"loadskin\",\"Initializing the app !!!\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN , true,true,{enableMenuKey:true,enableBackKey:true, progressIndicatorColor : \"ffffff77\"});\n\t\tmobileFabricConfiguration.konysdkObject = new kony.sdk();\n\t\tmobileFabricConfiguration.konysdkObject.init(mobileFabricConfiguration.appKey,mobileFabricConfiguration.appSecret,mobileFabricConfiguration.serviceURL,initializeMobileFabricInAppInitSuccess,initializeMobileFabricFailure); \n\t}\n\telse\n\t\talert (\"Network unavailable. Please check your network settings. \");\n\tkony.print (\" ########## Exiting out of initializeMobileFabricInAppInit ########## \");\n}", "function prepareApp() {\n // we might get an error, but the getDemoData function will handle it \n // for us...\n Alloy.Globals.insights.updating.app = true;\n \n generateLastUpdatedTimer();\n\n // show loader on applciation start\n loader.bg.add(loader.largeIndicator);\n if (!OS_ANDROID) { $.appWin.add(loader.bg); } // #ATEMP: not yet supported on Android...\n\n // GET APP AND USER DATA...\n // we need to get user data first in-case there is a need to refresh persisted data...\n app.state.properties.app = lib.client.app.getAppData();\n\n // #VPC support\n Alloy.Globals.insights.state.customDomain = app.state.properties.app.customDomain || null;\n\n getDemoData(function(error) {\n Alloy.Globals.insights.updating.app = false;\n\n prepareUI();\n\n // we open the apen window a little later... #TODO\n if (OS_IOS) {\n $.appWin.open();\n }\n });\n \n}", "function manageStartup(enable) {\n let appLauncher = new AutoLaunch({\n // Change this to the name of the application or what\n // should appear in the startup menu.\n name: 'BB'\n });\n if (enable) {\n appLauncher.isEnabled().then(function(enabled){\n if(enabled) return;\n return appLauncher.enable();\n }).then(function(err){\n // If you want to remove all console output, remove lines that contain \"console.error(err)\"\n if (err !== undefined) console.error(err);\n });\n } else {\n appLauncher.isEnabled().then(function(enabled){\n if(!enabled) return;\n return appLauncher.disable();\n }).then(function(err){\n if (err !== undefined) console.error(err);\n }); \n }\n}", "function loadSplashScreen(){\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tgenerateFramework(\"splash\", generatePage)\n\t\t\t\t\t},1500);\n\t\t\t\tsetTimeout(initialisePage, 4000);\n\t\t}", "function LaunchNewProgram(application, args, url) {\n OverlayScreenForLaunch()\n $.ajax({\n url: \"/Action/Launch?detach=yes&name=\" + application + \"&args=\" + encodeURIComponent(args),\n success: function (data) {\n window.location = url;\n },\n error: function (xhr, ajaxOptions, thrownError) {\n RemoveScreenOverlay()\n },\n cache: false\n });\n}", "async createApp () {\n const tasks = new Listr([\n {\n title: 'Ensure installation directory is empty',\n task: () => this.ensureEmptyInstallPath()\n },\n {\n title: 'Crafting your application',\n task: () => this.craftApp()\n },\n {\n title: 'Installing application dependencies',\n task: () => this.installAppDependencies()\n },\n {\n title: 'Initializing application setup',\n task: () => Promise.resolve()\n }\n ])\n\n await tasks.run()\n }", "function loadApplication() {\n console.log(\"Application Loaded.\");\n showMainMenu();\n}", "function doAppConfig(){\r\n\tvar params = {\"handle\":'',\"type\":\"application\",\"class\":\"appconfig\",\"do\":\"start\",\"title\":\"Par&aacute;metros de la empresa\",\"width\":\"750\",\"height\":\"500\",\"closable\":true,\"modal\":true };\r\n\texecuteApplication(params);\r\n}", "function initializeApp() {\r\n createLoader();\r\n getCategoryInfo(activeTab);\r\n}", "function runStartUpTasks() \n{\n\n\tif ($.os.ios || app.use_positioning)\t\n\t\tshowLoadingDialog(\"weather\", translate(\"Positioning location\"));\n\t\n if (getCachedWeatherdata()!==false)\n useCachedForecast();\n\n locateUser();\n updateWarnings();\n startTracking();\n \n // Wait 10 seconds to update bulletins\n \n if (window.location.hostname!=\"m.fmi.fi\")\n setTimeout(updateAppInfo, 10000); \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates HTML markup for link to restart a ProcessingStep.
createRestartProcessingStepLink(id, dataTable) { 'use strict'; const imageLink = $.otp.createAssetLink('redo.png'); return `<a id="restartProcessingStepLink" onclick="$.otp.workflows.restartProcessingStep(${id}, '${dataTable}');" href="#" title="Restart"> <img src="${imageLink}"/> </a>`; }
[ "function gameRestartFragment()\n{\n\ttextSize(100);\n\ttext(\"GAMEOVER\", width/2, height/2);\n\ttextAlign(CENTER, CENTER);\n\n\t//resetBtn = createButton('RESET');\n \t//resetBtn.position(width/2 - 70, height/2 + 100);\n \t//resetBtn.mousePressed(mousePressed);\n}", "function replaceStep(){\n d3.select('#step_instructions').text(recipe.instructions[currStepId].text);\n //Determine button opacity\n if (currStepId == recipe.instructions.length-1){\n d3.select('#next')\n .style('opacity', '.2');\n } else if (currStepId == 0){\n d3.select('#back')\n .style('opacity', '.2');\n d3.select('#next')\n .style('opacity', '1');\n } else if (currStepId == 1){\n d3.select('#back')\n .style('opacity', '1');\n } else if (currStepId == recipe.instructions.length-2){\n d3.select('#next')\n .style('opacity', '1'); \n }\n}", "function goNext() {\n element.parentNode.removeChild(document.getElementById('tooltip' + currentStep.id));\n $(element).css('border', '');\n if (parseInt(stepIndex) < 0) return;\n currentStep = steps.find(e => e.id == stepIndex);\n element = $(currentStep.action.selector)[$(currentStep.action.selector).length - 1];\n placeToolTip();\n}", "restart() \n\t{\n\t\t// notify we're restarting\n\t\tnotify(\"story restarting\", {story: this}, this.outerdiv);\n\n\t\t// clear everything\n\t\tthis.clear(this.options[\"hidelength\"]);\n\n\t\t// reset the story\n\t\tthis.ink.ResetState();\n\t\t\n\t\t// and start it from the beginning\n\t\tthis.continue();\n\t}", "function nextButtonAction() {\n\n if (stepNumber == 12) return null\n document.getElementById(\"mainContainerDiv\").innerHTML = '';\n\n\n let newStepNumber = stepNumber + 1;\n let newStepName = \"Step \" + newStepNumber;\n let navRoute = \"?Steps=\" + newStepNumber;\n window.history.pushState(null, null, navRoute);\n loadStepsData(newStepName, newStepNumber);\n\n}", "function terminationBadge(){\n injectDOM('div', 'terminateCycle', 'cycleSteps', {'style':'background-color:#222222'});\n injectDOM('button', 'newCommand', 'terminateCycle', {\n 'class' : 'navLink',\n 'innerHTML' : 'New Command',\n 'type' : 'button',\n 'onclick' : function(){\n createCycleStep(window.cyclePointer.helpMessage);\n document.getElementById('cycleContent'+window.cyclePointer.nCycleSteps).setAttribute('class', 'delayCycleContent') \n window.cyclePointer.nCycleSteps++;\n askForCycleDeploy();\n }\n });\n}", "restartProcessingStep(id, selector) {\n 'use strict';\n\n $.post($.otp.createLink({\n controller: 'processes',\n action: 'restartStep',\n id\n }), (data) => {\n $.otp.infoMessage(data.success);\n $(selector).dataTable().fnDraw();\n });\n }", "function renderBackLinkToPharma() {\n var html = '<div class=\"safetyBackLinkSection\">' +\n '<span>Back to </span>' +\n '<span class=\"tabNametoGo\"> Pharma </span>' +\n '<span> tab </span>' +\n '</div>';\n // var html = ` <div class=\"cpbackbtn\">\n // <a href=\"{{pathFor 'Pharma/RWEBenchmark'}}\" class=\"compareDrugbackbtn\"><span class=\"compareDrugbackbtnIcon\"><i class=\"fa fa-chevron-left\" aria-hidden=\"true\"></i></span>Back To Pharma</a>\n // </div>`;\n\n $('#safetyLinkToBack').html();\n $('#safetyLinkToBack').html(html);\n\n assignEventToBackPharmaLink();\n}", "restart() {\n // Restart button properties\n this.restartButton = {\n x: width / 2,\n y: height / 2 + 50,\n w: 200,\n h: 100,\n tl: 15,\n tr: 15,\n bl: 15,\n br: 15,\n textSize: 35,\n fillColor: color(255, 64, 99)\n }\n push();\n noStroke();\n rectMode(CENTER);\n fill(this.restartButton.fillColor);\n rect(this.restartButton.x, this.restartButton.y, this.restartButton.w, this.restartButton.h, this.restartButton.tl, this.restartButton.tr, this.restartButton.br, this.restartButton.bl);\n fill(255);\n textSize(this.restartButton.textSize);\n textAlign(CENTER);\n text(\"RESTART\", this.restartButton.x, this.restartButton.y + 10);\n pop();\n }", "restart() {\n // Restart button properties\n this.restartButton = {\n x: 200,\n y: height - 100,\n w: 150,\n h: 80,\n tl: 15,\n tr: 15,\n bl: 15,\n br: 15,\n textSize: 25,\n fillColor: color(255, 64, 99)\n }\n push();\n noStroke();\n rectMode(CENTER, CENTER);\n fill(this.restartButton.fillColor);\n rect(this.restartButton.x, this.restartButton.y, this.restartButton.w, this.restartButton.h, this.restartButton.tl, this.restartButton.tr, this.restartButton.br, this.restartButton.bl);\n fill(255);\n textSize(this.restartButton.textSize);\n textAlign(CENTER, CENTER);\n text(\"RESTART\", this.restartButton.x, this.restartButton.y);\n pop();\n }", "function make_step(title, instruction, video) {\n\tinstruction = '<li><span class=\"instructiontitle\">'+title+':</span> ' + instruction;\n\tif(video != null) {\n\t\tinstruction = instruction +' (<a href=\"javascript:show_video(\\''+video+'\\')\">'+str_show_me+'</a>)';\n\t}\n\tinstruction = instruction + '</li>'\n\treturn instruction;\n}", "function _renderLastStep() {\n\t\t\tvar $parsed_step = $('<div class=\"wow-wizard-last-step\"><h1>Thanks for using WowWizard!</h1><p>We\\'ve got all your information. Will reach you soon.</p><a href=\"#\">RETURN HOME</a></div>');\n\t\t\treturn $parsed_step;\n\t\t}", "function _generateInterruptedInstanceHTML(interruptedInstance) {\n \n var instance = interruptedInstance.interruptedInstance;\n var definition = instance.definition;\n \n var result = 'Definition ' + definition.name + ' [Version ' + definition.id.version + ']<br/>'\n + 'Instance-ID ' + instance.id + '<br/>'\n + '<a href=\"#\" class=\"show-full-svg-artifact\">'\n + '<div rel=\"#svg-artifact-full-overlay\">Open as SVG</div>'\n + '</a>';\n \n return result;\n}", "function setMessage(current_step) {\n $(\"#whatIsNext\").html(step[current_step]);\n}", "function renderFinalPage () {\n //variable to store html elements\n let finalPage = `<div class=\"content\">\n <h2>Finished!</h2>\n <p>Your final score is ${store.score}/5. Press the Button below to restart the quiz!</p>\n <button id=\"restart\">Restart</button> \n </div>`;\n return finalPage;\n }", "restartstepone() {\n this.restart();\n this.begin();\n }", "function restart() {\n state = 'title';\n}", "function generateStartPage() {\n const assets = getAssets('startPage');\n return `<div class=\"row\">\n <div class=\"col-6\">\n <img src=\"${assets.startImg}\" alt=\"${assets.startImg}\">\n </div>\n <div class=\"col-6\">\n <p>${assets.startMsg}</p>\n <button type=\"button\" class=\"btnStartQuiz\">Begin Quiz</button>\n </div>\n </div>`;\n}", "function _previousStep() {\n if(this._currentStep == 0)\n return;\n\n _showElement.call(this, this._introItems[--this._currentStep].element);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
submit storyboard Called when you click the green check mark button. We gather all the information needed for the server to create a new storyboard, and send it in a nice JSON object to the server.
function submitStoryboard() { /* // If the user hasn't logged in yet, we kindly request they login if (!login.loggedIn) { $("#loginbox").data('function', 'submitStoryboard'); $("#loginbox").dialog('open'); // break out. We'll be back because of the loginbox's calling mechanism return; } */ // if the description area is hidden, and it doesn't have any contents, // open it up and prompt the user to add a description. // if (!$("#description").is(":visible") && $("#storyboardDescription").val() === "") { // toggleDescription(); // // determine focus based on if the user has set a title already // // if they have, choose the description, if they haven't, the title // if ($("#storyboardTitle").val() === "") { // $("#storyboardTitle").focus(); // } else { // $("#storyboardDescription").focus(); // } // // break out, we don't want to submit a storyboard without a title // return; // } // check that a title has been set // now 10% more idiot proof. if ($("#storyboardTitle").val().trim() === "") { $("#storyboardTitle").focus(); return; } /* The server is expecting this: storyboard = { playbackSessionID: < playback session id >, developerGroupID: < dev group id >, name: < storyboard name >, description: < storyboard description >, clips: [ < array of clip IDs > ] } */ var clips = []; $("#timeline .clip").each(function(i, clip) { clips.push($(clip).attr('clipid')); }); var storyboard = { //playbackSessionID: sessionID, //developerGroupID: login.group, name: $("#storyboardTitle").val(), description: $("#storyboardDescription").val(), clips: clips, }; $.post('/storyboard/new/sessionID/' + getPlaybackSessionId(), { storyboard: JSON.stringify(storyboard) }, function(data) { // do something with that information... // open a new window and play the storyboard // playStoryboard(data.storyboardID); window.location = "playback.html?storyboardID=" + data.storyboardID + "&sessionID=" + getPlaybackSessionId(); } ).fail(function() { console.log(storyboard); }); }
[ "function createNewStoryFromSubmit() {\n console.debug(\"createNewStoryFromSubmit\");\n hidePageComponents();\n $submitForm.show();\n\n // getNewStoryData();\n\n $submitForm.trigger(\"reset\")\n\n // $submitForm.on(\"submit\", await storyList.addStory(currentUser.username, {title, author, url}));\n\n\n\n\n\n\n\n}", "async function submitStory() {\n\n let form = $storyForm;\n let newStory = {\n title: `${form[0][0].value}`,\n author: `${form[0][1].value}`,\n url: `${form[0][2].value}`\n }\n\n\n let result = await storyList.addStory(currentUser, newStory);\n $storyForm.slideUp(\"slow\");\n $storyForm.trigger(\"reset\");\n let markUp = generateStoryMarkup(result, []);\n let $markUp = $(markUp);\n $allStoriesList.prepend(markUp)\n}", "function createStory() {\r\n\r\n\tif (!user) {\r\n displayAlertMessage('Failed to post. User not logged in.')\r\n return;\r\n }\r\n if (storylocation == null) {\r\n displayAlertMessage('Failed to post. You must select a location.')\r\n return;\r\n }\r\n\r\n $('#story-publish-button').text('Posting...').attr('disabled','disabled');\r\n\r\n\tstory = newStoryObj(map);\r\n\t//set new story title\r\n\tstory.setTitle(\"story_\" + user.domainUser.numberId + \"_\" + new Date().getTime());\r\n\t//set location\r\n\tstory.setLocation(storylocation);\r\n\tstory.setLocationName(storylocation.name);\r\n\t//set summary\r\n\tstory.setSummary(getStoryText($('.lg-container .story-summary')));\r\n\t//set labels\r\n\tstory.setLabels(getStoryTextLabels($('.lg-container .story-summary')[0]));\r\n //setArticle\r\n if (article) {\r\n\t\tstory.setArticle(article.title,\r\n\t\t\t\t\t\tarticle.description,\r\n\t\t\t\t\t\tarticle.imageUrl,\r\n\t\t\t\t\t\twebUrl,\r\n article.date,\r\n article.source,\r\n article.author)\r\n\t}\r\n\r\n\tstory.setPublished(true);\r\n //save story on server\r\n\tstud_createStory(story.domainStory,function(st){\r\n\t\t//upload story pics\r\n\t\tif (saveimagefile) {\r\n\t\t\tuploadStoryImage(st.id,function(thumbnail) {\r\n\t\t\t\tst.thumbnail = thumbnail;\r\n postingFinished(st);\r\n\t\t\t},\r\n function() {\r\n postingError();\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\t//publish\r\n postingFinished(st);\r\n\t\t}\r\n\t},\r\n function() {\r\n postingError();\r\n });\r\n}", "function createStory() {\r\n\r\n\tif (!user) {\r\n displayAlertMessage('Failed to post. User not logged in.')\r\n return;\r\n }\r\n if (storylocation == null) {\r\n displayAlertMessage('Failed to post. You must select a location.')\r\n return;\r\n }\r\n\r\n $('#story-publish-button').text('Posting...').attr('disabled','disabled');\r\n\r\n\tstory = newStoryObj(map);\r\n\t//set new story title\r\n\tstory.setTitle(\"story_\" + user.domainUser.numberId + \"_\" + new Date().getTime());\r\n\t//set location\r\n\tstory.setLocation(storylocation);\r\n\tstory.setLocationName(storylocation.name);\r\n\t//set summary\r\n\tstory.setSummary(getStoryText($('.lg-container .story-summary')));\r\n\t//set labels\r\n\tstory.setLabels(getStoryTextLabels($('.lg-container .story-summary')[0]));\r\n //setArticle\r\n if (article) {\r\n\t\tstory.setArticle(article.title,\r\n\t\t\t\t\t\tarticle.description,\r\n\t\t\t\t\t\tarticle.imageUrl,\r\n\t\t\t\t\t\twebUrl,\r\n article.date,\r\n article.source,\r\n article.author)\r\n\t}\r\n\tif (collection.published == 0)\r\n\t\tstory.setPublished(false);\r\n\telse\r\n\t\tstory.setPublished(true);\r\n //save story on server\r\n\tstud_createStoryOnCollection(collection.id,story.domainStory,function(st){\r\n\t\t//upload story pics\r\n\t\tif (saveimagefile) {\r\n\t\t\tuploadStoryImage(st.id,function(thumbnail) {\r\n\t\t\t\tst.thumbnail = thumbnail;\r\n postingFinished(st);\r\n\t\t\t},\r\n function() {\r\n postingError();\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\t//publish\r\n postingFinished(st);\r\n\t\t}\r\n\t},\r\n function() {\r\n postingError();\r\n });\r\n}", "submit(storyState) {\n\t\t// submit story\n\t\tconst { setLoadState, stories, updateStories, showPopup } = this.props;\n\t\tsetLoadState(true);\n\t\tsendAuthenticated('/api/stories', storyState, res => {\n\t\t\tsetLoadState(false);\n\t\t\tif (res.error) {\n\t\t\t\treturn this.showErrMsg(res.error);\n\t\t\t\t// return alert(`Please correct the following errors:\\n${res.error.join('\\n')}`);\n\t\t\t}\n\t\t\tupdateStories(stories.concat([res.newStory]));\n\t\t\tshowPopup(['Success', 'thumbs-up', 'Story submitted successfully. Thanks for contributing!']);\n\t\t\tbrowserHistory.push('/');\n\t\t})\n\t}", "async function submitAndShowNewStory(evt) {\n //grab values from form\n //call .addStory using values\n //put new Story on page\n console.log(evt);\n evt.preventDefault();\n let author = $(\"#author\").val();\n let title = $(\"#title\").val();\n let url = $(\"#url\").val();\n console.log(author, title, url);\n let newStory = await storyList.addStory(currentUser, { author, title, url })\n let newStoryHtml = generateStoryMarkup(newStory);\n $allStoriesList.prepend(newStoryHtml);\n // putStoriesOnPage();\n // location.reload();\n}", "async function submitNewStory(evt) {\n evt.preventDefault();\n let author = $(\"#author-name\").val();\n let title = $(\"#story-title\").val();\n let url = $(\"#story-url\").val();\n \n let story = {author, title, url};\n let newStory = await storyList.addStory(currentUser, story);\n \n currentUser.ownStories.push(newStory)\n\n const $story = generateStoryMarkup(newStory);\n $allStoriesList.prepend($story);\n $submitForm.hide();\n}", "async function submitNewStory(evt) {\n evt.preventDefault();\n\n const storyTitle = $(\"#title-field\").val();\n const storyAuthor = $(\"#author-field\").val();\n const storyURL = $(\"#url-field\").val();\n\n let newStory = await storyList.addStory(\n currentUser,\n { title: storyTitle, author: storyAuthor, url: storyURL }\n );\n\n $allStoriesList.prepend(generateStoryMarkup(newStory));\n}", "async function submitStory(evt) {\n evt.preventDefault();\n\n const author = $(\"#author-name\").val();\n const title = $(\"#story-title\").val();\n const url = $(\"#story-url\").val();\n\n // updates API\n let newStory = await storyList.addStory(currentUser, { author, title, url });\n\n // updates local memory\n storyList.stories.unshift(newStory);\n\n // updates DOM\n putStoriesOnPage();\n}", "function submitStoryClick() {\n hidePageComponents();\n $(\"#story-author, #story-title, #story-url\").val('');\n $storyForm.show();\n $allStoriesList.before($storyForm);\n}", "async function handleStorySubmit(evt) {\n console.debug(\"handleStorySubmit\");\n evt.preventDefault();\n // get form input data\n const title = $('#title-input').val();\n const author = $('#author-input').val();\n const url = $('#url-input').val();\n // get user info\n const username = currentUser.username;\n // create story object\n const storyObj = {username, title, author, url};\n\n const story = await storyList.addStory(currentUser, storyObj);\n const newStoryMarkup = generateStoryMarkup(story);\n $allStoriesList.prepend(newStoryMarkup);\n $ownStories.prepend(newStoryMarkup);\n $storyForm.hide();\n putStoriesOnPage();\n}", "async function handleStoryFormSubmit(evt) {\n evt.preventDefault();\n\n let storyInput = {\n title: $(\"#story-title\").val(),\n author: $(\"#story-author\").val(),\n url: $(\"#story-url\").val()\n }\n const newStory = await storyList.addStory(currentUser, storyInput); // generate markup and prepend;\n // console.log(\"newStory\", newStory)\n\n const newStoryMarkup = generateStoryMarkup(newStory);\n // console.log(typeof newStoryMarkup)\n // console.log(newStoryMarkup.html())\n\n $allStoriesList.prepend(newStoryMarkup);\n $allStoriesList.show();\n\n // console.log(newStory);\n\n $storyForm.hide();\n}", "function submit() {\n\tpostJSON(\"submit\",JSON.stringify(Balls().animationStack));\n}", "async function submitStoryOnNav(evt) {\n console.debug(\"submitStoryOnNav\", evt);\n hidePageComponents();\n $allStoriesList.show();\n\n let title = $(\"#create-title\").val();\n let author = $(\"#create-author\").val();\n let url = $(\"#create-url\").val();\n\n // wrapper to handle the api functionality\n await storyList.addStory(currentUser, {\n title,\n author,\n url,\n });\n\n // erases submit form upon sending\n $submitForm.trigger(\"reset\");\n}", "submit() {\n const final = this.toString();\n kolmafia_1.print(`Submitting macro: ${final}`);\n return kolmafia_1.visitUrl('fight.php?action=macro&macrotext=' + kolmafia_1.urlEncode(final), true, true);\n }", "async function addUserStorySubmission(e) {\n e.preventDefault();\n\n const postTitle = $('#post-title').val(); \n const postAuthor = $('#post-author').val(); \n const postURL = $('#post-URL').val(); \n\n const storyData = {title: `${postTitle}`, author: `${postAuthor}`, url: `${postURL}`}\n\n //API\n const story = await storyList.addStory(currentUser, storyData);\n //USER\n currentUser.ownStories.unshift(story);\n //HTML generation\n const $story = generateStoryMarkup(story);\n $allStoriesList.prepend($story);\n \n $submitForm.trigger(\"reset\");\n $submitForm.hide();\n \n $allStoriesList.show();\n}", "function saveCreation(){\r\n\t\tlet space = document.getElementById(\"space\").innerHTML; // Gets the space\r\n\t\tif(space == \"\"){ // If the space is empty\r\n\t\t\t// Make the message visible\r\n\t\t\tdocument.getElementById(\"message\").style.visibility = \"visible\";\r\n\r\n\t\t\t// Put an error message on the page\r\n\t\t\tdocument.getElementById(\"message\").innerHTML = \"Cannot Save an Empty Canvas\"; \r\n\r\n\t\t\t// Change the class name to display a red background\r\n\t\t\tdocument.getElementById(\"message\").className = \"red\";\r\n\t\t}\r\n\t\telse{ // If the space has shapes, post the creation\r\n\t\t\tconst message = {space: space\r\n\t\t\t\t}; // Gets the space with all the shapes\r\n\t\t\tconst fetchOptions = { // Sends the post with the name and comment\r\n\t\t\t\tmethod : 'POST',\r\n\t\t\t\theaders : {\r\n\t\t\t\t\t'Accept': 'application/json',\r\n\t\t\t\t\t'Content-Type' : 'application/json'\r\n\t\t\t\t},\r\n\t\t\t\tbody : JSON.stringify(message) // Send the message\r\n\t\t\t\t};\r\n\r\n\t\t\tlet url = \"https://moveableshapes.herokuapp.com/\"; // Call the host for the post\r\n\t\t\tfetch(url, fetchOptions)\r\n\t\t\t\t.then(checkStatus)\r\n\t\t\t\t.then(function(responseText) {\r\n\r\n\t\t\t\t\t// Adds the response text to the message\r\n\t\t\t\t\tdocument.getElementById(\"message\").innerHTML = responseText;\r\n\r\n\t\t\t\t\t// Makes the message visible\r\n\t\t\t\t\tdocument.getElementById(\"message\").style.visibility = \"visible\";\r\n\r\n\t\t\t\t\t// Changes the class to set a green background\r\n\t\t\t\t\tdocument.getElementById(\"message\").className = \"green\";\r\n\r\n\t\t\t\t})\r\n\t\t\t\t.catch(function(error) { // Catch the error\r\n\t\t\t\t\tconsole.log(error);\r\n\t\t\t\t});\r\n\t\t}\r\n\t}", "function saveCurrentBoard(){\n\t//get what the board currently looks like and PUT it in the DB\n\tvar initial_setup = getCurrentLayout();\n\t//figure out what board I am saving (exercise or practice)\n\tvar save_to_table = $(location).attr('href').split('/')[3];\n\t//build field name for table I am saving to\n\tvar start_field = save_to_table.slice(0, -1) + '[start]';\n\t//get which exercise I am working with (the id of it) so I can use it later on teh ajax call\n\tvar id = $(\"#board\").data('id')\n\t//build the URL I am sending data to\n\tvar url_field = '/' + save_to_table + '/' + id;\n\n\t//create the json as a string for the field and data that will be passed in the ajax call\n\t//var dataObj = \"{\\\"\" + start_field + \"\\\":\\\"\" + initial_setup +\"\\\" }\" ;\n\tvar dataObj = {};\n\tdataObj[start_field] = initial_setup;\n\t//convert the json string into json\n\t//dataObj = jQuery.parseJSON(dataObj);\n\n $.ajax({\n \turl: url_field,\n \ttype: 'PUT',\n \tdata: dataObj,\n\t\tdataType: 'json'\n\t});\n}", "function newStory(){\n\n var $formNewStory = $(\"#newStoryForm\"),\n inputTitle = $formNewStory.find( 'input[id=\"inputTitle\"]' ).val(),\n inputAuthor = $formNewStory.find( 'input[id=\"inputAuthor\"]' ).val(),\n inputDescription = $formNewStory.find( 'textarea[id=\"inputDescription\"]' ).val(),\n inputLayoutStyle = $formNewStory.find( 'select[id=\"inputLayoutStyle\"]' ).val(),\n inputLayoutSize = $formNewStory.find( 'select[id=\"inputLayoutSize\"]' ).val(),\n action = \"newStory\",\n url = \"controller.php\";\n\n //Send the data using post\n var posting = $.post( url, { \n action: action, \n inputTitle: inputTitle,\n inputAuthor: inputAuthor,\n inputDescription: inputDescription,\n inputLayoutStyle: inputLayoutStyle,\n inputLayoutSize: inputLayoutSize\n } );\n\n //Put the results in a div\n posting.done(function(data) {\n $(\"#mainStoryContent\").empty().append(data);\n configureColumns();\n });\n $('#newStoryModal').modal('hide');\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: createButton creates an individual button Parameters: URL path to image position: x x position y y position frameSize: width frame width height frame height animBounds: out mouse off button start start frame end end frame over mouse on button start start frame end end frame down clicking the button start start frame end end frame fn function to call
function createButton(UID, assetQueue, cm, position, frameSize, animBounds, fn) { // TODO: Replace this animation stuff with animation class var buttonImg = assetQueue.getResult(UID); var buttonSheet = new createjs.SpriteSheet({ images: [buttonImg], frames: {width: frameSize.width, height:frameSize.height, regX: frameSize.width/2, regY: frameSize.height/2}, animations: { out: [animBounds.out.start, animBounds.out.end, "out"], over: [animBounds.over.start, animBounds.over.end, "over"], down: [animBounds.down.start, animBounds.down.end, "down"] } }); var buttonSprite = new createjs.Sprite(buttonSheet, "out"); buttonSprite.x = position.x; buttonSprite.y = position.y; var btnHelper = new createjs.ButtonHelper(buttonSprite, "out", "over", "down", true); buttonSprite.addEventListener("click", fn); buttonSprite.buttonFn = fn; return buttonSprite; }
[ "makeButton() {\n //Align Sprite\n rectMode(CENTER);\n //Create Button Sprite At Position\n this.sprite = createSprite(\n width / 2,\n (height - this.size) / this.max * (this.y + 1),\n this.size * 3,\n this.size * 1.5);\n //Bind Sprite onMouseReleased to Function\n this.sprite.onMouseReleased = this.onClick;\n //Add Image to Sprite\n this.sprite.addImage(this.img);\n //Set Default Scale (backup)\n this.sprite.scale = 1;\n //Debug if Enabled\n this.sprite.debug = GameManager.settings.debug;\n }", "function create_button(func, title, width, height, src, img_id) {\n\n var img, button;\n img = document.createElement('img');\n img.width = width;\n img.height = height;\n /* Set the button style to not pushed */\n set_button_img_style(img,0);\n img.style.marginLeft = \"2px\";\n img.style.marginRight = \"2px\";\n img.src = src;\n img.id = img_id;\n button = document.createElement('a');\n button.title = title;\n \n button.addEventListener('click',\n func, \n true);\n button.appendChild(img);\n \n return button;\n}", "function createArrowButton(x, name, direction) {\n let scaling = 0.5;\n let normal = new createjs.Bitmap(queue.getResult(\"orangeBtn\")).set({\n scaleX: scaling, scaleY: scaling\n });\n let imgHeight = normal.image.height * scaling;\n let hover = new createjs.Bitmap(queue.getResult(\"yellowBtn\")).set({\n scaleX: scaling, scaleY: scaling\n });\n if (\"right\" === direction) {\n normal.rotation = 180;\n normal.y += imgHeight;\n hover.rotation = 180;\n hover.y += imgHeight;\n }\n let button = new createjs.Container().set({\n x: x,\n y: CANVAS_HEIGHT - imgHeight - 10,\n name: name\n });\n button.addChild(normal);\n button.cursor = 'pointer';\n button.mouseChildren = false;\n button.mouseEnabled = true;\n\n button.on('mouseover', e => {\n button.removeAllChildren();\n button.addChild(hover);\n });\n button.on('mouseout', e => {\n button.removeAllChildren();\n button.addChild(normal);\n });\n button.disable = () => {\n button.alpha = 0.5;\n button.mouseEnabled = false;\n };\n button.enable = () => {\n button.alpha = 1.0;\n button.mouseEnabled = true;\n }\n return button;\n}", "_createButton() {\n this._button = new Sprite.from(\"replayButton\");\n this._button.name = \"replayButton\";\n this._button.anchor.set(0.5);\n this._button.interactive = true;\n this._button.buttonMode = true;\n this._button.on(\"click\", () => {\n this.emit(Win.events.REPLAY);\n });\n this._button.y = 330;\n this.addChild(this._button);\n }", "function createNativeHTMLButton(x, y, width, height, urlImage, id, title, rectId) {\n // create the button\n var button = document.createElement('a');\n button.id = id;\n button.href = '#';\n button.className = 'tri-button';\n button.style.display = 'block';\n button.style.backgroundImage = 'url(' + urlImage +')';\n button.style.backgroundColor = 'white';\n /*var button = document.createElement('input');\n button.id = id;\n button.type = 'image';\n button.src = urlImage;\n if (title){\n\t button.title = title;\n }*/\n \n // create an IFRAME shim for the button\n var iframeShim = document.createElement('iframe');\n iframeShim.id = \"iframe_\" + id;\n iframeShim.frameBorder = 0;\n iframeShim.scrolling = 'no';\n iframeShim.src = (navigator.userAgent.indexOf('MSIE 6') >= 0) ?\n '' : 'javascript:void(0);';\n\n // position the button and IFRAME shim\n var pluginRect = getElementRect(document.getElementById(rectId));\n button.style.position = iframeShim.style.position = 'absolute';\n button.style.left = iframeShim.style.left = (pluginRect.left + x) + 'px';\n button.style.top = iframeShim.style.top = (pluginRect.top + y) + 'px';\n button.style.width = iframeShim.style.width = 0 + 'px';//width + 'px';\n button.style.height = iframeShim.style.height = 0 + 'px';//height + 'px';\n \n button.initialWidth = width + 'px';\n button.initialHeight = height + 'px';\n \n // set up z-orders\n button.style.zIndex = 10;\n iframeShim.style.zIndex = button.style.zIndex - 1;\n \n /*if (functionOnclick){\n\t\t // set up click handler\n\t addDomListener(button, 'click', function(evt) {\n\t\t\tfunctionOnclick();\n\t\t if (evt.preventDefault) {\n\t\t evt.preventDefault();\n\t\t evt.stopPropagation();\n\t\t }\n\t\t return false;\n\t });\n }*/\n \n // add the iframe shim and button\n document.body.appendChild(button);\n document.body.appendChild(iframeShim);\n}", "function __createDashBoardButton(){\n\t\t// Buttons creation\n\t\tvar btnImg = new CAAT.Foundation.SpriteImage().initialize(\n\t\t\t\tgame._director.getImage('buttons'), 2, 3 \n\t\t\t); \n\t\t//Go btn creation and add Events\n\t\tvar b1= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 0, 0, 1, 0, function(button) {\t\t\t\t\t\n\t\t\t\t\tgame.goBtnMouseDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], Number(buttonXYPos[0][1])+100);\t\t\t\n\t\t//Reset btn creation and add Events\n\t\tvar b2= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 4, 4, 5, 4, function(button) {\n\t\t\t\t\tgame.resetBtnMouseDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], Number(buttonXYPos[0][2])+100);\n\t\t\n\t\tdashBG.addChild( b1 );\n\t\tdashBG.addChild( b2 );\t\n\t}", "function createButtons() {\n\t//PAGINA 2\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p2',\n\t\tcoords \t\t: {x:187,y:179},\n\t\tposition \t: 'pa',\n\t\theader \t\t: 'TWISTED',\n\t\tsubheader \t: 'floor lamp',\n\t\tprice \t\t: '$249',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/lighting/floor-lights/23355408/twisted-floor-lamp-150cm-natural-finish/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p2',\n\t\tcoords \t\t: {x:318,y:254},\n\t\tposition \t: 'pa',\n\t\theader \t\t: 'ANDERSEN',\n\t\tsubheader \t: '3 seat sofa',\n\t\tprice \t\t: '$1699',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/sofas/fabric-sofas/23361362/andersen-mkii-3-seat-sofa-napa-stone/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p2',\n\t\tcoords \t\t: {x:427,y:347},\n\t\tposition \t: 'pd',\n\t\theader \t\t: 'SLIPPER',\n\t\tsubheader \t: 'chair',\n\t\tprice \t\t: '$399',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/sofas/fabric-armchairs/23365506/slipper-chair-chevron-taupe/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\t//PAGINA 3\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p3',\n\t\tcoords \t\t: {x:190,y:209},\n\t\tposition \t: {x:79,y:-79},\n\t\tsize \t\t: 292,\n\t\theader \t\t: 'RETRO',\n\t\tsubheader \t: 'chair',\n\t\tprice \t\t: '$599',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/sofas/fabric-armchairs/23364592/retro-chair-arena-neptune/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p3',\n\t\tcoords \t\t: {x:338,y:324},\n\t\tposition \t: {x:-204,y:17},\n\t\tsize \t\t: 186,\n\t\theader \t\t: 'TUKANA',\n\t\tsubheader \t: 'cushion',\n\t\tprice \t\t: '$39.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/soft-furnishings/scatter-cushions/23392113/tukana-cushion-45x45cm-multi/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\n\t//PAGINA 4\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p4',\n\t\tcoords \t\t: {x:200,y:281},\n\t\tposition \t: 'pa',\n\t\theader \t\t: 'DECKHAUS',\n\t\tsubheader \t: '9 piece package',\n\t\tprice \t\t: '$1299',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/outdoor/outdoor-tables/23395688/deckhaus-9-piece-outdoor-package-natural/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p4',\n\t\tcoords \t\t: {x:420,y:347},\n\t\tposition \t: 'pd',\n\t\tspecialSize\t: 'size_a',\n\t\theader \t\t: 'WEEKENDER STRIPE',\n\t\tsubheader \t: 'cushion',\n\t\tprice \t\t: '$29.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/outdoor-living/outdoor-softs/23381803/weekender-stripe-cushion-50x50cm-red/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\t//PAGINA 5\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p5',\n\t\tcoords \t\t: {x:177,y:190},\n\t\tposition \t: {x:-130,y:75},\n\t\tspecialSize\t: 'size_b',\n\t\tsize \t\t: 256,\n\t\theader \t\t: 'BRUNCH',\n\t\tsubheader \t: '3 piece dining package',\n\t\tprice \t\t: '$799',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/outdoor/outdoor-tables/23394438/brunch-3-piece-dining-package-flame/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p5',\n\t\tcoords \t\t: {x:307,y:335},\n\t\tposition \t: {x:2,y:-148},\n\t\tsize \t\t: 186,\n\t\theader \t\t: 'IMPRESSIONS',\n\t\tsubheader \t: 'set of 4 bowls',\n\t\tprice \t\t: '$39.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/tableware/dinnerware/23392342/impressions-bowls-set-of-4-mixed-pattern/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\n\t//PAGINA 6\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p6',\n\t\tcoords \t\t: {x:363,y:158},\n\t\tposition \t: 'pc',\n\t\theader \t\t: 'INDUSTRY',\n\t\tsubheader \t: 'ceiling pendant',\n\t\tprice \t\t: '$149',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/lighting/ceiling-lights/23308442/industry-ceiling-pendant-black/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p6',\n\t\tcoords \t\t: {x:90,y:287},\n\t\tposition \t: 'pa',\n\t\tspecialSize\t: 'size_b',\n\t\theader \t\t: 'URBAN',\n\t\tsubheader \t: 'extension dining table',\n\t\tprice \t\t: '$1799',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/dining/dining-tables/23262706/urban-extension-dining-table-190250x100-naturalgrey/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p6',\n\t\tcoords \t\t: {x:344,y:372},\n\t\tposition \t: 'pd',\n\t\theader \t\t: 'LAURENT',\n\t\tsubheader \t: 'dining chair',\n\t\tprice \t\t: '$149',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/dining/dining-chairs/23164628/laurent-dining-chair-white/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\t//PAGINA 7\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p7',\n\t\tcoords \t\t: {x:174,y:193},\n\t\tposition \t: {x:-133,y:75},\n\t\tsize \t\t: 266,\n\t\theader \t\t: 'SIGNATURE',\n\t\tsubheader \t: 'extension table',\n\t\tprice \t\t: '$1199',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/signature/dining/23358379/signature-extension-dining-table-white/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p7',\n\t\tcoords \t\t: {x:286,y:338},\n\t\tposition \t: {x:-193,y:10},\n\t\tsize \t\t: 150,\n\t\theader \t\t: 'JUPITER',\n\t\tsubheader \t: 'dining chair',\n\t\tprice \t\t: '$59',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/dining/dining-chairs/23351110/jupiter-dining-chair-teal/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\n\t//PAGINA 8\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p8',\n\t\tcoords \t\t: {x:302,y:312},\n\t\tposition \t: 'pc',\n\t\theader \t\t: 'Christmas',\n\t\tsubheader \t: 'Tabletop',\n\t\tprice \t\t: 'from $7.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/christmas/christmas-tabletop/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p8',\n\t\tcoords \t\t: {x:449,y:311},\n\t\tposition \t: 'pc',\n\t\theader \t\t: 'FRITZ',\n\t\tsubheader \t: 'dining chair',\n\t\tprice \t\t: '$129',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/dining/dining-chairs/23162365/fritz-dining-chair-white/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p8',\n\t\tcoords \t\t: {x:362,y:425},\n\t\tposition \t: 'pc',\n\t\theader \t\t: 'CARPENTERS',\n\t\tsubheader \t: 'dining table',\n\t\tprice \t\t: '$1499',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/dining/dining-tables/23154926/carpenters-dining-table-220x100cm-natural/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\t//PAGINA 9\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p9',\n\t\tcoords \t\t: {x:199,y:203},\n\t\tposition \t: {x:112,y:-108},\n\t\tsize \t\t: 310,\n\t\theader \t\t: 'MODE',\n\t\tsubheader \t: 'mug',\n\t\tprice \t\t: '$3.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/tableware/coffee-tea/23389793/mode-mug-bone-china-yellowgrey/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p9',\n\t\tcoords \t\t: {x:350,y:356},\n\t\tposition \t: {x:-195,y:-16},\n\t\tsize \t\t: 180,\n\t\tspecialSize\t: 'size_a',\n\t\theader \t\t: 'SUMMER PINEAPPLE',\n\t\tsubheader \t: 'statue',\n\t\tprice \t\t: '$19.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/decorator-accents/bowls-accessories/23376885/summer-pineapple-22cm/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\n\t//PAGINA 10\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p10',\n\t\tcoords \t\t: {x:189,y:159},\n\t\tposition \t: 'pa',\n\t\theader \t\t: 'BAKERS',\n\t\tsubheader \t: 'storage unit',\n\t\tprice \t\t: '$199',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/living/bookshelves-wall-units/23276710/bakers-storage-unit/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p10',\n\t\tcoords \t\t: {x:202,y:314},\n\t\tposition \t: 'pa',\n\t\tspecialSize\t: 'size_b',\n\t\theader \t\t: 'AKI',\n\t\tsubheader \t: 'queen quilt cover set',\n\t\tprice \t\t: '$99',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/bedroom/quilt-covers-bedspreads/23378285/aki-queen-quilt-cover-set-blue/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p10',\n\t\tcoords \t\t: {x:448,y:310},\n\t\tposition \t: 'pc',\n\t\theader \t\t: 'HARRY',\n\t\tsubheader \t: 'sofabed',\n\t\tprice \t\t: '$999',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/sofas/recliners-and-sofabeds/23395824/harry-sofa-bed-lennox-graphite/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\t//PAGINA 11\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p11',\n\t\tcoords \t\t: {x:214,y:220},\n\t\tposition \t: {x:84,y:-168},\n\t\tsize \t\t: 316,\n\t\theader \t\t: 'SLEEPOVER',\n\t\tsubheader \t: 'sofa bed 1.5 seat',\n\t\tprice \t\t: '$799',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/sofas/recliners-and-sofabeds/23278349/sleepover-sofa-bed-15-seat-dexter-ketchup/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p11',\n\t\tcoords \t\t: {x:302,y:370},\n\t\tposition \t: {x:-183,y:-10},\n\t\tsize \t\t: 122,\n\t\theader \t\t: 'JUKE',\n\t\tsubheader \t: 'vessel large',\n\t\tprice \t\t: '$59.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/decorator-accents/vessels/23380189/juke-vessel-large-reactive-blue/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\n\t//PAGINA 12\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p12',\n\t\tcoords \t\t: {x:126,y:152},\n\t\tposition \t: 'pb',\n\t\tspecialSize\t: 'size_b',\n\t\theader \t\t: 'ENTERTAIN',\n\t\tsubheader \t: '4 piece cheese knife set ',\n\t\tprice \t\t: '$19.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/christmas/23385641/entertain-4-piece-cheese-knife-set/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p12',\n\t\tcoords \t\t: {x:327,y:140},\n\t\tposition \t: 'pc',\n\t\theader \t\t: 'GLITTER',\n\t\tsubheader \t: 'bowl large',\n\t\tprice \t\t: '$29.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/christmas/23385153/glitter-bowl-large-glass-silver/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p12',\n\t\tcoords \t\t: {x:412,y:257},\n\t\tposition \t: 'pc',\n\t\theader \t\t: 'WHISK',\n\t\tsubheader \t: 'string lights',\n\t\tprice \t\t: '$29.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/christmas/23382244/whisk-string-lights-77m-white/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'hotspot',\n\t\tpage \t\t: 'p12',\n\t\tcoords \t\t: {x:251,y:367},\n\t\tposition \t: 'pb',\n\t\tspecialSize\t: 'size_b',\n\t\theader \t\t: 'WISH',\n\t\tsubheader \t: 'cocktail glass set of 4',\n\t\tprice \t\t: '$39.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/christmas/23389380/wish-cocktail-glass-set-of-4/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\t//PAGINA 13\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p13',\n\t\tcoords \t\t: {x:283,y:278},\n\t\tposition \t: {x:-223,y:38},\n\t\tsize \t\t: 258,\n\t\theader \t\t: 'ENTERTAIN',\n\t\tsubheader \t: 'oil & vinegar set',\n\t\tprice \t\t: '$49.95',\n\t\turl \t\t: 'http://www.freedom.com.au/homewares/christmas/23385580/entertain-oil--vinegar-set-naturalwhite/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\tcreateButton({\n\t\ttype \t\t: 'radial',\n\t\tpage \t\t: 'p13',\n\t\tcoords \t\t: {x:146,y:169},\n\t\tposition \t: {x:56,y:-81},\n\t\tsize \t\t: 154,\n\t\theader \t\t: 'Freedom',\n\t\tsubheader \t: 'Gift Card',\n\t\tprice \t\t: '',\n\t\turl \t\t: 'http://www.freedom.com.au/furniture/gift-ideas/gift-card/23243118/gift-card-online/?utm_source=totallyher&utm_medium=flipbook&utm_campaign=GRFX'\n\t});\n\n}", "function __createDashBoardButton(){\n\t\t// Buttons creation\n\t\tvar btnImg = new CAAT.Foundation.SpriteImage().initialize(\n\t\t\t\tgame._director.getImage('buttons'), 2, 3 \n\t\t\t); \n\t\t//Go btn creation and add Events\n\t\tvar b1= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 0, 0, 1, 0, function(button) {\t\t\t\t\t\n\t\t\t\t\tgame.goBtnMDownHandler();\t\t\t\t\t\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], buttonXYPos[0][1]);\t\n\t\t//Pause btn creation and add Events\n\t\tvar b2= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 2, 2, 3, 2, function(button) {\n\t\t\t\t\tgame.pauseBtnMDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], buttonXYPos[0][3]);\n\t\t\n\t\t//Reset btn creation and add Events\n\t\tvar b3= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 4, 4, 5 ,4 , function(button) {\n\t\t\t\t\tgame.resetBtnMDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], buttonXYPos[0][2]);\t \n\t\tdashBG.addChild( b1 );\n\t\tdashBG.addChild( b2 );\n\t\tdashBG.addChild( b3 );\t\n\t}", "function __createDashBoardButton(){\n\t\t// Buttons creation\n\t\tvar btnImg = new CAAT.Foundation.SpriteImage().initialize(\n\t\t\t\tgame._director.getImage('buttons'), 2, 3 \n\t\t\t); \n\t\t//Go btn creation and add Events\n\t\tvar b1= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 0, 0, 1, 0, function(button) {\t\t\t\t\t\n\t\t\t\t\tgame.goBtnMDownHandler();\t\t\t\t\t\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], buttonXYPos[0][1]);\t\n\t\t//Reset btn creation and add Events\n\t\tvar b3= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 4, 4, 5 ,4 , function(button) {\n\t\t\t\t game.resetBtnMDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], buttonXYPos[0][2]);\t \n\t\t//Pause btn creation and add Events\n\t\tvar b2= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 2, 2, 3, 2, function(button) {\n\t\t\t\t\tgame.pauseBtnMDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], buttonXYPos[0][3]);\n\t\t\n\t\tdashBG.addChild( b1 );\n\t\tdashBG.addChild( b2 );\n\t\tdashBG.addChild( b3 );\t\t\n\t}", "function __createDashBoardButton(){\n\t\t// Buttons creation\n\t\tvar btnImg = new CAAT.Foundation.SpriteImage().initialize(\n\t\t\t\tgame._director.getImage('buttons'), 2, 3 \n\t\t\t); \n\t\t//Go btn creation and add Events\n\t\tvar b1= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 0, 0, 1, 0, function(button) {\t\t\t\t\t\n\t\t\t\t\tgame.goBtnMDownHandler();\t\t\t\t\t\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], buttonXYPos[0][1]);\t\n\t\t//Reset btn creation and add Events\n\t\tvar b3= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 4, 4, 5 ,4 , function(button) {\n\t\t\t\t\tgame.resetBtnMDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], buttonXYPos[0][2]);\t \n\t\t//Pause btn creation and add Events\n\t\tvar b2= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 2, 2, 3, 2, function(button) {\n\t\t\t\t\tgame.pauseBtnMDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], buttonXYPos[0][3]);\n\t\t\n\t\t//dashBG.addChild( b1 );\n\t\t//dashBG.addChild( b2 );\n\t\tdashBG.addChild( b3 );\t\n\t}", "function __createDashBoardButton(){\n\t\t// Buttons creation\n\t\tvar btnImg = new CAAT.Foundation.SpriteImage().initialize(\n\t\t\t\tgame._director.getImage('buttons'), 2, 3 \n\t\t\t); \n\t\t//Go btn creation and add Events\n\t\tvar b1= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 0, 0, 1, 0, function(button) {\t\t\t\t\t\n\t\t\t\t\tgame.goBtnMDownHandler();\t\t\t\t\t\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], Number(buttonXYPos[0][1]) + 70);\t\n\t\t//Reset btn creation and add Events\n\t\tvar b3= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 4, 4, 5 ,4 , function(button) {\n\t\t\t\t\tgame.resetBtnMDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], Number(buttonXYPos[0][2]) + 70);\t \n\t\t//Pause btn creation and add Events\n\t\tvar b2= new CAAT.Foundation.Actor().setAsButton(\n\t\t\t\tbtnImg.getRef(), 2, 2, 3, 2, function(button) {\n\t\t\t\t\tgame.pauseBtnMDownHandler();\n\t\t\t\t}\n\t\t\t).\n\t\t\tsetLocation(buttonXYPos[0][0], Number(buttonXYPos[0][3]) + 70);\n\t\t\n\t\tdashBG.addChild( b1 );\n\t\tdashBG.addChild( b2 );\n\t\tdashBG.addChild( b3 );\t\n\t}", "function startButton() {\n let buttonWidth = 500;\n let buttonHeight = 200;\n let leftSide = width / 2 - buttonWidth / 2;\n let rightSide = leftSide + buttonWidth;\n let topSide = height / 2 - buttonHeight / 2 + 150;\n let bottomSide = topSide + buttonHeight;\n\n noStroke();\n\n if (mouseX >= leftSide &&\n mouseX <= rightSide &&\n mouseY >= topSide &&\n mouseY <= bottomSide) {\n\n fill(0, 140, 174);\n\n if (mouseIsPressed) {\n background(intro);\n state = 2;\n }\n }\n else {\n fill(0, 45, 72);\n }\n rect(leftSide, topSide, buttonWidth, buttonHeight, 20);\n buttonText();\n}", "addButton(text, imageUrl, onPointerDown) {\n var width = this.makeRoomForMore();\n \n var button = new BABYLON.GUI.HolographicButton(text+\"Button\");\n this.guiManager.addControl(button);\n button.imageUrl = imageUrl;\n button.text=text;\n button.position = new BABYLON.Vector3(this.elements.length*width/2,0,0);\n button.scaling = new BABYLON.Vector3( this.buttonSize, this.buttonSize, this.buttonSize );\n button.mesh.parent = this.rowRoot;\n this.elements.push(button);\n this.controls.push(button);\n button.backMaterial.alpha = this.alpha;\n this.rescaleHUD();\n if ( onPointerDown ) {\n button.onPointerDownObservable.add( (vector3WithInfo) => onPointerDown(button, vector3WithInfo) );\n }\n if ( text ) {\n this.speechInput.addCommand(text, () => {\n // execute click callback(s) on visible button\n this.activateButton(button);\n });\n }\n return button;\n }", "function createBtns(_x, _y) { \n console.log(\"createBtns: x = \" + _x + \", y = \" + _y);\n \n const BTNCOL = 'rgb(0, 204, 0)';\n const BTNW = 100;\n const BTNH = 70;\n const GAP = 15;\n const FONTSIZE = '18px';\n \n // create LOGIN button\n btnLogin = createButton('login');\n btnLogin.position(_x, _y);\n btnLogin.size(BTNW, BTNH);\n btnLogin.style('background-color', color(BTNCOL));\n btnLogin.style('font-size', FONTSIZE);\n btnLogin.mousePressed(login);\n \n // create READ ALL button\n btnReadAll = createButton('read ALL');\n btnReadAll.position(btnLogin.x, btnLogin.y + \n btnLogin.height + 3 *GAP);\n btnReadAll.size(BTNW, BTNH);\n btnReadAll.style('background-color', color(BTNCOL));\n btnReadAll.style('font-size', FONTSIZE);\n btnReadAll.mousePressed(readAll);\n \n // create READ A RECORD button\n btnReadRec = createButton('read rec');\n btnReadRec.position(btnReadAll.x, btnReadAll.y + \n btnReadAll.height + GAP);\n btnReadRec.size(BTNW, BTNH);\n btnReadRec.style('background-color', color(BTNCOL));\n btnReadRec.style('font-size', FONTSIZE);\n btnReadRec.mousePressed(readRec);\n \n // create WRITE button\n btnWrite = createButton('write rec');\n btnWrite.position(btnReadRec.x, btnReadRec.y + \n btnReadRec.height + GAP);\n btnWrite.size(BTNW, BTNH);\n btnWrite.style('background-color', color(BTNCOL));\n btnWrite.style('font-size', FONTSIZE);\n btnWrite.mousePressed(writeRec);\n \n // create logout button\n btnLogout = createButton('logout');\n btnLogout.position(btnWrite.x, btnWrite.y + \n btnWrite.height + 3 * GAP);\n btnLogout.size(BTNW, BTNH);\n btnLogout.style('background-color', color(BTNCOL));\n btnLogout.style('font-size', FONTSIZE);\n btnLogout.mousePressed(logout);\n}", "function createButtons(){\n addButtton(\"PLAY\");\n addButtton(\"PAUSE\");\n addButtton(\"STOP\");\n}", "function addBackButton(){\n\tbackArrow = new createjs.Bitmap(imgqueue.getResult(\"left\"));\n\tbackArrow.x = 40;\n\tbackArrow.y = 40;\n\tbackArrow.addEventListener(\"click\", prvClck);/*BUG*/\t// Including this following line of code will cause the images to display\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// but will prevent all event listeners from functioning.\n\tcontainer.addChild(backArrow);\n\tcontainer.setChildIndex(backArrow, 1);\n\t\n\tbackShape = new createjs.Shape();\n\tbackShape.graphics.beginFill(\"#ffffff\").drawRoundRect(0, 0, 270, IMAGE_HEIGHT - 140, 30); // Original orange color: #ff8c00\n\t//prvShape.graphics.beginStroke(\"#000000\").setStrokeStyle(3).drawRoundRect(0, 0, 270, IMAGE_HEIGHT - 140, 30);\n\tbackShape.x = 40;\n\tbackShape.y = 40;\n\tbackShape.alpha = 0.01;\n\t//prvShape.shadow = new createjs.Shadow(\"#000000\", 5, 5, 10);\n\tbackShape.addEventListener(\"click\", prvClck);\n\t\n\tcontainer.addChild(backShape);\n\tcontainer.setChildIndex(backShape, 1);\n\t\n}", "function RectButtonn(x_position, y_position, height, width, action)\r\n{\r\n var graphics = new PIXI.Graphics();\r\n graphics.beginFill(0xFFFFFF, 1); // Color and opacity\r\n graphics.lineStyle(2, 0x414141, 1);\r\n graphics.drawRect(x_position, y_position, width, height);\r\n graphics.endFill();\r\n graphics.interactive = true;\r\n graphics.on('mouseover', onHoverOver) // When mouse hovers over the button, it calls onHoverOver() function\r\n .on('mouseout', onHoverOff)\r\n .on('pointerdown', onSelect)\r\n .on('pointerdown', nextActivity)\r\n .on('pointerdown', removeLastStroke)\r\n .on('pointerdown', makeButtonAppear);\r\n graphics.alpha = 0.5;\r\n graphics.assignAction(action);\r\n buttonArray[buttonArray.length] = graphics;\r\n app.stage.addChild(graphics);\r\n}", "function create() {\n var button = this.add.sprite(400, 300, \"new-game\");\n button.setInteractive({ useHandCursor: true });\n\n button.on(\"pointerover\", function () {\n this.setFrame(1);\n });\n button.on(\"pointerout\", function () {\n this.setFrame(0);\n });\n\n button.on(\"pointerdown\", function(){\n console.log(\"Start the new game already!\");\n });\n}", "function createButton(imgSrc, callback, ...args) {\n const button = document.createElement(\"button\");\n button.onclick = function() {callback(...args)};\n\n const img = document.createElement(\"img\");\n img.className = \"buttonPicture\";\n img.src = imgSrc;\n\n button.appendChild(img);\n return button;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return metadata for a specific asset assocated with token
async function getIonAssetMetadata(accessToken, assetId) { Object(_utils_assert__WEBPACK_IMPORTED_MODULE_0__["default"])(accessToken, assetId); const url = `${CESIUM_ION_URL}/${assetId}/endpoint`; const headers = {Authorization: `Bearer ${accessToken}`}; const response = await fetch(url, {headers}); if (!response.ok) { throw new Error(await Object(_loaders_gl_core__WEBPACK_IMPORTED_MODULE_1__["_getErrorMessageFromResponse"])(response)); } return await response.json(); }
[ "async getMetaData(token){\n\t\tlet toRet;\n\t\tawait window.ConnectClass.getCardMeta(token).then((metaData) => {\n\t\t\ttoRet = {\"price\": window.web3.utils.fromWei(metaData.price), \"cardId\" : window.web3.utils.toUtf8(metaData.cardId)};\n\t\t});\n\t\treturn toRet;\n\t}", "async fetchMetadata (_collectionId, _assetId) {\n const { address } = constant.opensea.collections[_collectionId]\n\n const res = await fetch(`https://api.opensea.io/api/v1/asset/${address}/${_assetId}`, {\n headers: {\n 'x-api-key': constant.opensea.api_key,\n 'Content-Type': 'application/json'\n }\n })\n\n if (!res.ok) {\n throw new Error('OpenSea did not return proper metadata: ' + res.statusText)\n }\n\n const { name, description, image_url, image_thumbnail_url, image_original_url, animation_original_url, external_link, background_color, traits } = await res.json()\n\n return {\n name,\n description,\n image: image_original_url,\n image_preview: image_url,\n image_thumbnail: image_thumbnail_url,\n animation_url: animation_original_url,\n external_link,\n background: !background_color ? undefined : '#' + background_color,\n attributes: traits\n }\n }", "async fetchMetadata2 (_collectionId, _assetId) {\n const res = await fetch(`${config.OPENSEA_API}/asset/${_collectionId}/${_assetId}`, {\n headers: {\n 'x-api-key': constant.opensea.api_key,\n 'Content-Type': 'application/json'\n }\n })\n\n if (!res.ok) {\n throw new Error('OpenSea did not return proper metadata: ' + res.statusText)\n }\n\n const { name, description, image_url, image_original_url, animation_url, animation_original_url, image_preview_url, image_thumbnail_url, external_link, background_color, traits, asset_contract } = await res.json()\n\n return {\n name,\n description,\n image: image_original_url || image_url,\n image_preview: image_preview_url,\n image_thumbnail: image_thumbnail_url,\n animation_url: animation_original_url || animation_url,\n external_url: external_link,\n background_color,\n attributes: traits,\n contract_name: asset_contract.name\n }\n }", "function getAsset(axios, token, format) {\n var query = randomSeedQuery();\n if (format) {\n query += addFilter(format.includeAssetType, \"includeAssetType\");\n }\n return restAuthGet(axios, \"assets/\" + token + query);\n}", "parseMetadataItemData(metaAtom) {\n let tagKey = metaAtom.header.name;\n return metaAtom.readAtoms(this.tokenizer, child => {\n switch (child.header.name) {\n case \"data\": // value atom\n return this.parseValueAtom(tagKey, child);\n case \"name\": // name atom (optional)\n return this.tokenizer.readToken(new AtomToken.NameAtom(child.dataLen)).then(name => {\n tagKey += \":\" + name.name;\n });\n case \"mean\": // name atom (optional)\n return this.tokenizer.readToken(new AtomToken.NameAtom(child.dataLen)).then(mean => {\n // console.log(\" %s[%s] = %s\", tagKey, header.name, mean.name);\n tagKey += \":\" + mean.name;\n });\n default:\n return this.tokenizer.readToken(new Token.BufferType(child.dataLen)).then(dataAtom => {\n this.addWarning(\"Unsupported meta-item: \" + tagKey + \"[\" + child.header.name + \"] => value=\" + dataAtom.toString(\"hex\") + \" ascii=\" + dataAtom.toString(\"ascii\"));\n });\n }\n }, metaAtom.dataLen);\n }", "async function getMetaData () {\n\n var options = {\n uri: config.creds.identityMetadata,\n json: true\n };\n \n const result = await rp(options);\n\n return result;\n\n}", "function getAssetType(axios, token, format) {\n var query = randomSeedQuery();\n return restAuthGet(axios, \"assettypes/\" + token + query);\n}", "function getAsset(store, token, format) {\n var axios = createCoreApiCall(store);\n var api = API.Assets.getAsset(axios, token, format);\n return loaderWrapper(store, api);\n}", "getMetadataContent(identifier) {\n var uniqueIdentifier = identifier || 'InformationM'; \n \n let url = \"https://archive.org/metadata/\" + uniqueIdentifier;\n\n return fetch(url)\n .then(function(response) {\n return response.json();\n })\n .then(function(data) {\n return data;\n });\n }", "function testAsset(token) {\n createAsset(token, \"test\", function (isSuccess, resData) {\n printMapObject('testAsset createAsset', resData)\n\n getAssetById(token, resData['id']['id'], function (isSuccess, resData) {\n if (isSuccess) {\n printMapObject('testAsset getAssetById', resData)\n } else {\n console.log('testAsset getAssetById fail')\n }\n })\n\n getAssetByName(token, resData['name'], function (isSuccess, resData) {\n if (isSuccess) {\n printMapObject('testAsset getAssetByName', resData)\n } else {\n console.log('testAsset getAssetByName fail')\n }\n })\n\n deleteAssetById(token, resData['id']['id'], function (isSuccess) {\n console.log('testAsset deleteAssetById isSuccess ' + isSuccess)\n })\n })\n}", "tokenMetadata (request) {\n return this._gatewayRequest('get', '/api/token/' + request.token, request)\n }", "getMetaData(data) {\n return [{\n description: data.description,\n license_code: data.license.code,\n license_text: data.license.text,\n license_url: data.license.url,\n sources: data.sources\n }];\n }", "function getAssetType(store, token, format) {\n var axios = createCoreApiCall(store);\n var api = API.AssetTypes.getAssetType(axios, token, format);\n return loaderWrapper(store, api);\n}", "getMetadata () {\n\n let metadata_url = `//dev.virtualearth.net/REST/V1/Imagery/Metadata/${this.type}?output=json&include=ImageryProviders&key=${this.key}`;\n\n return new Promise( (resolve, reject) => {\n fetch(metadata_url).then( (response) => {\n return response.json();\n }).then( (data) => {\n let imageUrl = data.resourceSets[0].resources[0].imageUrl;\n\n if (location.protocol === 'https:') {\n imageUrl = imageUrl.replace(/^http:/gi, 'https:');\n }\n\n this.metadata = {\n imageUrl : imageUrl,\n imageUrlSubdomains : data.resourceSets[0].resources[0].imageUrlSubdomains\n };\n\n resolve( this.metadata );\n }).catch( (error) => {\n throw new Error('Failed to get Bing Maps metadata from dev.virtualearth.net.', error);\n reject();\n });\n });\n }", "metadata(actorId) {\n return this.metaIndex[actorId]\n }", "get metadata(){\r\n\t\treturn this.store.metadata(this.path) }", "async ReadAsset(ctx, key) {\n const value = await ctx.stub.getState(key); // get the asset from chaincode state\n if (!value) {\n throw new Error(`The asset ${key} does not exist`);\n }\n return value;\n }", "getMetadata (mediaId) {\n if (!mediaId) {\n throw new Error('{mediaId} argument must be specified');\n }\n\n const requestOptions = _.merge({}, this._api.requestOptions, {\n method: 'GET',\n uri: `${this._baseUrl}/${mediaId}/metadata`\n });\n\n return this._api.makeRequest(requestOptions);\n }", "getMetadata(entity) {\n return this.entityMetadatas.findByTarget(entity);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the process event handlers, which could allow a worker to hold open the process
unbindProcessSignals() { process.removeListener('SIGINT', this._signalHandlers.SIGINT); process.removeListener('SIGTERM', this._signalHandlers.SIGTERM); }
[ "_deregisterProcessSignalHandlers() {\n HANDLED_PROCESS_SIGNAL_EVENTS.forEach(signal => {\n process.listeners(signal).map(handler => process.off(signal, handler));\n });\n }", "unsubscribeFromProcessSignals() {\n if (!this.shutdownCleanupRef) {\n return;\n }\n this.activeShutdownSignals.forEach(signal => {\n process.removeListener(signal, this.shutdownCleanupRef);\n });\n }", "_detachFromProcess(instance) {\n process.removeListener('exit', instance._endSelf);\n process.removeListener('SIGINT', instance._endSelf);\n process.removeListener('SIGTERM', instance._endSelf);\n process.removeListener('SIGQUIT', instance._endSelf);\n process.removeListener('SIGHUP', instance._endSelf);\n process.removeListener('SIGBREAK', instance._endSelf);\n }", "static clearWorkerThreadEventHandlers () {\n WORKER_CHANNELS.forEach(channel => {\n ipcMain.removeAllListeners(channel)\n })\n }", "_cleanup() {\n if (this._pythonProcess) {\n this._pythonProcess.removeAllListeners();\n this._pythonProcess = null;\n }\n }", "function unregister() {\n if (!applicationCurrent) {\n return;\n }\n applicationCurrent.stop();\n\n EVENTS.forEach(function (event) {\n process.removeListener(event, currentHandlers[event]);\n });\n\n applicationCurrent = null;\n currentHandlers = {};\n}", "function removeEvents() {\n node.removeEventListener('load', onResolve);\n node.removeEventListener('error', onReject);\n }", "detachEvents() {\n var event, handler;\n\n for (event in this.windowHandlers) {\n handler = this.windowHandlers[event];\n\n if (handler.bound) {\n handler.bound = false;\n window.removeEventListener(event, handler.listener, handler.useCapture);\n }\n }\n\n for (event in this.eventEmitterHandlers) {\n handler = this.eventEmitterHandlers[event];\n\n if (handler.bound) {\n handler.bound = false;\n eventEmitter.off(event, handler.listener);\n }\n }\n }", "cleanupEventHandlers() {\n if (document) {\n document.removeEventListener('keydown', this.keyDownHandler, true);\n document.removeEventListener('mousemove', this.mouseMoveHandler);\n }\n }", "freeListeners() {\n if (this.exe) {\n this.exe.removeAllListeners('error');\n this.exe.removeAllListeners('exit');\n this.exe.removeAllListeners('message');\n }\n if (this.rlStdout) {\n this.rlStdout.removeAllListeners('line');\n }\n if (this.rlStderr) {\n this.rlStderr.removeAllListeners('line');\n }\n }", "function unsubscribeAll(){uninstallGlobalHandler();handlers=[];}", "_unbindHandlers() {\n\t\tthis._tabs.forEach(tab => {\n\t\t\tif (tab._events && tab._events.length) {\n\t\t\t\ttab._events.forEach(e => tab.removeEventListener(e.type, e.func));\n\t\t\t}\n\t\t\tdelete tab._events;\n\t\t});\n\t}", "unhandle() {\n if (this._handler) {\n process.removeListener(this._event, this._handler);\n this._handler = null;\n [...this._store.values()]\n .forEach(stream => this.logger.stream.unpipe(stream));\n }\n }", "function cleanupKeyListeners()\r\n {\r\n for(var i=0;i<winArray.length;i++) //for all window objects in array\r\n winArray[i].document.removeEventListener(\"keydown\",keyStart,false) //Remove key down listener to document object\r\n\r\n document.removeEventListener(\"unload\",cleanupKeyListeners,false) //Remove window unload listener\r\n }", "removeAll () {\n this.pool.forEach(item => {\n const { node, event, handler } = item;\n\n node.removeEventListener(event, handler);\n });\n\n this.pool.length = 0;\n }", "clearEventHandlers() {\n for (const [eventName, listeners] of this.eventHandlers) {\n listeners.forEach(listener => {\n this.bot.off(eventName, listener);\n });\n }\n this.eventHandlers.clear();\n }", "reset () {\n this.pool = this.pool.reduce((pool, event) => {\n event.context.removeEventListener(event.name, event.handler)\n return pool\n }, [])\n }", "function unsubscribeAll() {\n uninstallGlobalHandler();\n handlers = [];\n }", "__uninstall () {\n events.forEach(event => {\n window.removeEventListener(event, this.$handlers[event])\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Section Caption Props Section Text Props
get sectionText() { return this._sectionText.elements; }
[ "function SectionTitle(props) {\n const classes = props.classes;\n\n return (\n <Typography\n variant=\"subheading\"\n align=\"center\"\n className={classes.title}\n >\n {props.title.toUpperCase()}\n </Typography>\n );\n}", "renderCaptions() {\r\n return ((this.captionTitle || this.captionEyebrow || this.captionSubtitle) && h(\"div\", { class: this.captionPosition },\r\n this.captionEyebrow && h(\"p\", { class: \"dxp-title-eyebrow dxp-font-size-lg\" }, this.captionEyebrow),\r\n this.captionTitle && h(\"h3\", { class: \"dxp-title-1\" }, this.captionTitle),\r\n h(\"p\", { class: this.captionSubtitle ? 'description dxp-hidden-xs-only' : 'description' }, this.captionSubtitle)));\r\n }", "renderCaptions() {\n return ((this.captionTitle || this.captionEyebrow || this.captionSubtitle) && h(\"div\", { class: this.captionPosition }, this.captionEyebrow && h(\"p\", { class: \"dxp-title-eyebrow dxp-font-size-lg\" }, this.captionEyebrow), this.captionTitle && h(\"h3\", { class: \"dxp-title-1\" }, this.captionTitle), h(\"p\", { class: this.captionSubtitle ? 'description dxp-hidden-xs-only' : 'description' }, this.captionSubtitle)));\n }", "renderCaption() {\n if (this.props.caption) {\n return (\n <p style={{width: '100%', textAlign: 'center', fontStyle: 'italic', lineHeight: '30px', padding: '5px', margin: 0}}>\n { this.props.caption }\n </p>\n )\n }\n }", "function Skills(props) {\n return (\n <section role=\"region\" className=\"resume-section\">\n <header>\n <h2 className=\"section-title\">Skills</h2>\n </header>\n <p><strong>{props.theInfo[0].category}</strong> | {props.theInfo[0].details}</p>\n <p><strong>{props.theInfo[1].category}</strong> | {props.theInfo[1].details}</p>\n <p><strong>{props.theInfo[2].category}</strong> | {props.theInfo[2].details}</p>\n </section>\n );\n}", "function Caption() {\n return (\n <div id=\"caption\">\n <p>VIDEO MANAGEMENT AND INTEGRATED SUPPORT SYSTEM</p>\n </div>\n );\n}", "function createTextContent(el, section) {\n //Set h4's\n el.children[0].textContent = siteContent['main-content'][`${section}-h4`];\n\n //Set p's\n el.children[1].textContent = siteContent['main-content'][`${section}-content`];\n}", "function displaySection(section) {\n var displayName = {\n 'vitals': 'vital signs',\n 'results': 'test results',\n 'social': 'social history'\n };\n if (displayName[section]) {\n return displayName[section];\n } else {\n return section;\n }\n }", "function Education(props) {\n return (\n <section role=\"region\" className=\"resume-section\">\n <header>\n <h2 className=\"section-title\">Education</h2>\n </header>\n <p><strong>{props.theInfo[0].title}</strong><br/>{props.theInfo[0].details}</p>\n <p><strong>{props.theInfo[1].title}</strong><br/>{props.theInfo[1].details}</p>\n </section>\n );\n}", "function _sectionTitle(){\r\n\t\t\treturn sectionTitle;\r\n\t\t}", "function getSectionTitle(title) {\n // section title layout\n return title;\n}", "function customizeCaption() {\n var captionText = \n \"Circle sizes represent rates of water withdrawals by county. \";\n if(waterUseViz.interactionMode === 'tap') {\n captionText = captionText +\n \"Tap in the legend to switch categories. \" +\n \"Tap a state to zoom in, then tap a county for details.\";\n } else {\n captionText = captionText +\n \"Hover over the map for details. Click a button to switch categories. \" +\n \"Click a state to zoom in, and click the same state to zoom out.\";\n }\n \n d3.select('#map-caption p')\n .text(captionText);\n}", "function SectionDetails() {\n this.m_sSectionName = ''; // section name\n this.m_nCount = 0; // count to hold number of prods belong to this\n this.m_nCumulativeCount = 0; // all product counts including current and sub sections\n this.m_arrSubSectionIds = new Array(); // sub section IDs\n this.m_bHideAlways = false; // hide always?\n}", "function renderTitle(section) {\n const title = document.querySelector('.form-title');\n title.innerHTML = section.getAttribute('section-name');\n}", "function Section(){}", "function Experience(props) {\n return (\n <section role=\"region\" className=\"resume-section\">\n <header>\n <h2 className=\"section-title\">Professional Experience</h2>\n </header>\n <p><strong>{props.theInfo[0].title}</strong><br/>{props.theInfo[0].details}</p>\n <p><strong>{props.theInfo[1].title}</strong><br/>{props.theInfo[1].details}</p>\n </section>\n );\n}", "function InfoSection() {\n\treturn (\n\t\t<InfoSectionContainer>\n\t\t\t<InfoSectionH1>What we provide</InfoSectionH1>\n\t\t\t<InfoSectionContent>\n\t\t\t\t{InfoData.map((data, index) => {\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<InfoItem key={index}>\n\t\t\t\t\t\t\t<Illustration key={index} src={data.img} size=\"150\"></Illustration>\n\t\t\t\t\t\t\t<InfoP>{data.text}</InfoP>\n\t\t\t\t\t\t</InfoItem>\n\t\t\t\t\t)\n\t\t\t\t})}\n\t\t\t</InfoSectionContent>\n\t\t</InfoSectionContainer>\n\t)\n}", "get caption() {\n if (this.props.caption) {\n return <caption>{ this.props.caption }</caption>;\n }\n\n return null;\n }", "function Section(parent, heading) {\n this._parent = parent;\n this._heading = heading;\n this._items = [];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtiene los cupones por industria
function getCuponesPorIndustria(idIndustria){ }
[ "function irComputadores() {\n // Eliminar la clase Activa de los enlaces y atajos\n eliminarClaseActivaEnlances(enlaces, 'activo');\n eliminarClaseActivaEnlances(atajosIcons, 'activo-i');\n // Añadimos la clase activa de la seccion de Coputadores en los enlaces y atajos\n añadirClaseActivoEnlaces(enlaceComputadores, 'activo');\n añadirClaseActivoEnlaces(atajoComputadores, 'activo-i');\n // Crear contenido de la Seccion\n crearContenidoSeccionComputadores();\n // Abrir la seccion \n abrirSecciones();\n}", "function establecerOficinas() {\n //Limpiar lista\n $paginaOficinas.find(\" > .app-content .oficina-item\").remove();\n //La plantilla\n var $plantilla = $paginaOficinas.find(\" > .app-content .oficina-item-plantilla\");\n //Agregar cada oficina\n for (var i = 0; i < oficinas.length; i++) {\n //Clonar plantilla\n var $elem = $plantilla.clone().removeClass(\"oficina-item-plantilla hide\").addClass(\"oficina-item\");\n var oficina = oficinas[i];\n //Establecer datos de la oficina\n $elem.data(\"oficina\", oficina);\n $elem.find(\".unidad\").html(oficina.unidad);\n $elem.find(\".direccion\").html(oficina.direccion);\n $elem.find(\".responsable\").html(oficina.responsable);\n //Agregar el elemento a la lista, insertándolo después de la plantilla (que está oculta)\n $elem.insertAfter($plantilla);\n }\n }", "function SeleccionadoOficinas() {\n MuestraObj(caracteristicas);\n MuestraObj(caracteristicasOficinas);\n MuestraObj(estado);\n MuestraObj(extrasOficinas);\n MuestraObj(precioInmuebles);\n MuestraObj(btnEjecutarConsulta);\n OcultaObj(subTipoViviendas);\n OcultaObj(subTipoLocales);\n OcultaObj(subTipoTerrenos);\n OcultaObj(antiguedadViviendas);\n OcultaObj(caracteristicasViviendas1);\n OcultaObj(caracteristicasViviendas2);\n OcultaObj(caracteristicasViviendas3);\n OcultaObj(caracteristicasLocales);\n OcultaObj(caracteristicasTerrenos1);\n OcultaObj(caracteristicasTerrenos2);\n OcultaObj(caracteristicasTerrenos3);\n OcultaObj(caracteristicasTrasteros);\n OcultaObj(caracteristicasGarajes1);\n OcultaObj(caracteristicasGarajes2);\n OcultaObj(caracteristicasGarajes3);\n OcultaObj(extrasViviendas);\n OcultaObj(extrasHabitaciones);\n OcultaObj(extrasLocales);\n OcultaObj(extrasTerrenos);\n OcultaObj(extrasTrasteros);\n OcultaObj(extrasGarajes);\n OcultaObj(precioVentaViviendasDesde);\n OcultaObj(precioVentaViviendasHasta);\n OcultaObj(precioAlquilerViviendasDesde);\n OcultaObj(precioAlquilerViviendasHasta);\n OcultaObj(precioAlquilerHabitacionesDesde);\n OcultaObj(precioAlquilerHabitacionesHasta);\n OcultaObj(precioVentaLocalesDesde);\n OcultaObj(precioVentaLocalesHasta);\n OcultaObj(precioAlquilerLocalesDesde);\n OcultaObj(precioAlquilerLocalesHasta);\n OcultaObj(precioVentaTerrenosDesde);\n OcultaObj(precioVentaTerrenosHasta);\n OcultaObj(precioAlquilerTerrenosDesde);\n OcultaObj(precioAlquilerTerrenosHasta);\n OcultaObj(precioVentaTrasterosDesde);\n OcultaObj(precioVentaTrasterosHasta);\n OcultaObj(precioAlquilerTrasterosDesde);\n OcultaObj(precioAlquilerTrasterosHasta);\n OcultaObj(precioVentaGarajesDesde);\n OcultaObj(precioVentaGarajesHasta);\n OcultaObj(precioAlquilerGarajesDesde);\n OcultaObj(precioAlquilerGarajesHasta);\n if (btnComprar.checked) {\n MuestraObj(precioVentaOficinasDesde);\n MuestraObj(precioVentaOficinasHasta);\n OcultaObj(precioAlquilerOficinasDesde);\n OcultaObj(precioAlquilerOficinasHasta);\n }\n if (btnAlquilar.checked) {\n MuestraObj(precioAlquilerOficinasDesde);\n MuestraObj(precioAlquilerOficinasHasta);\n OcultaObj(precioVentaOficinasDesde);\n OcultaObj(precioVentaOficinasHasta);\n }\n }", "function carregaOpcoesUnidadeSuporte(){\n\tcarregaTipoGerencia();\t\n\tcarregaTecnicos();\n\tcarregaUnidadesSolicitantes();\t\n\tcarregaEdicaoTipos();//no arquivo tipoSubtipo.js\n\tcarregaComboTipo();//no arquivo tipoSubtipo.js\n}", "imprimirVehiculos() {\n\t\tthis.vehiculos.forEach(vehiculo => {\n\t\t\tif (vehiculo.puertas) {\n\t\t\t\tconsole.log(`Marca: ${vehiculo.marca} // Modelo: ${vehiculo.modelo} // Puertas: ${vehiculo.puertas} // Precio: $${this.formatearPrecio(vehiculo.precio)}`)\n\t\t\t}\n\t\t\tif (vehiculo.cilindrada) {\n\t\t\t\tconsole.log(`Marca: ${vehiculo.marca} // Modelo: ${vehiculo.modelo} // Cilindrada: ${vehiculo.cilindrada}cc // Precio: $${this.formatearPrecio(vehiculo.precio)}`)\n\t\t\t}\n\t\t});\n\t}", "function carregaUnidadesSolicitantes(){\n\tvar unidade = DWRUtil.getValue(\"comboUnidade\"); \n\tcarregarListaNaoSolicitantes();\n\tcarregarListaSolicitantes();\n}", "function cargarCgg_res_beneficiarioCtrls(){\n if(inInfoPersona.CRPER_CODIGO_AUSPICIANTE != undefined && inInfoPersona.CRPER_CODIGO_AUSPICIANTE.length>0){\n if(inInfoPersona.CRPJR_CODIGO.length>0)\n {\n txtCrper_codigo.setValue(inInfoPersona.CRPJR_RAZON_SOCIAL);\n tmpAuspiciantePJ = inInfoPersona.CRPJR_CODIGO;\n txtCrpjr_representante_legal.setValue(inInfoPersona.CRPER_NOMBRE_AUSPICIANTE);\n tmpAuspiciante= inInfoPersona.CRPER_CODIGO_AUSPICIANTE;\n rdgTipoAuspiciante.setValue('rdgTipoAuspiciante',TypeAuspiciante.JURIDICA);\n }\n else\n {\n txtCrper_codigo.setValue(inInfoPersona.CRPER_NOMBRE_AUSPICIANTE);\n tmpAuspiciante= inInfoPersona.CRPER_CODIGO_AUSPICIANTE;\n rdgTipoAuspiciante.setValue('rdgTipoAuspiciante',TypeAuspiciante.NATURAL);\n }\n }\n }", "procCriou() {\n\t\tControladorJogo.pers.procObjCriadoColideTiros(this);\n\t\tthis.procVerifColisaoPersInimEstatico();\n\t}", "function SeleccionadoHabitaciones() {\n OcultaObj(subTipoViviendas);\n OcultaObj(subTipoLocales);\n OcultaObj(subTipoTerrenos);\n OcultaObj(antiguedadViviendas);\n OcultaObj(caracteristicas);\n OcultaObj(extrasViviendas);\n OcultaObj(extrasOficinas);\n OcultaObj(extrasLocales);\n OcultaObj(extrasTerrenos);\n OcultaObj(extrasTrasteros);\n OcultaObj(extrasGarajes);\n OcultaObj(precioVentaViviendasDesde);\n OcultaObj(precioVentaViviendasHasta);\n OcultaObj(precioAlquilerViviendasDesde);\n OcultaObj(precioAlquilerViviendasHasta);\n OcultaObj(precioVentaOficinasDesde);\n OcultaObj(precioVentaOficinasHasta);\n OcultaObj(precioAlquilerOficinasDesde);\n OcultaObj(precioAlquilerOficinasHasta);\n OcultaObj(precioVentaLocalesDesde);\n OcultaObj(precioVentaLocalesHasta);\n OcultaObj(precioAlquilerLocalesDesde);\n OcultaObj(precioAlquilerLocalesHasta);\n OcultaObj(precioVentaTerrenosDesde);\n OcultaObj(precioVentaTerrenosHasta);\n OcultaObj(precioAlquilerTerrenosDesde);\n OcultaObj(precioAlquilerTerrenosHasta);\n OcultaObj(precioVentaTrasterosDesde);\n OcultaObj(precioVentaTrasterosHasta);\n OcultaObj(precioAlquilerTrasterosDesde);\n OcultaObj(precioAlquilerTrasterosHasta);\n OcultaObj(precioVentaGarajesDesde);\n OcultaObj(precioVentaGarajesHasta);\n OcultaObj(precioAlquilerGarajesDesde);\n OcultaObj(precioAlquilerGarajesHasta);\n if (btnComprar.checked) {\n alert(\"No hay habitaciones en venta.\");\n OcultaObj(estado);\n OcultaObj(extrasHabitaciones);\n OcultaObj(precioInmuebles);\n OcultaObj(btnEjecutarConsulta);\n }\n if (btnAlquilar.checked) {\n MuestraObj(precioAlquilerHabitacionesDesde);\n MuestraObj(precioAlquilerHabitacionesHasta);\n MuestraObj(estado);\n MuestraObj(extrasHabitaciones);\n MuestraObj(precioInmuebles);\n MuestraObj(btnEjecutarConsulta);\n }\n }", "function irTransferencias() {\n // Eliminar la clase Activa de los enlaces y atajos\n eliminarClaseActivaEnlances(enlaces, 'activo');\n eliminarClaseActivaEnlances(atajosIcons, 'activo-i');\n // Añadimos la clase activa de la seccion de transferencias generales en los enlaces y atajos\n añadirClaseActivoEnlaces(enlaceTransferencias, 'activo');\n añadirClaseActivoEnlaces(atajoTransferencias, 'activo-i');\n // Crear contenido de la Seccion\n crearContenidoSeccionTransferencias();\n // Abrir la seccion \n abrirSecciones();\n}", "generaColas() {\n for (let i = 0; i < this.escritorios.length; i++) {\n this.colas.push(new cola_service_1.default(this.escritorios[i]));\n }\n }", "function iniciarListaBusqueda(){\n var ciclos = selectDatoErasmu();\n for(var aux = 0, help = 0 ; aux < erasmu.length ; aux++){\n if(ciclos.indexOf(erasmu[aux].ciclo) != -1){\n crearListErasmu(erasmu[aux]);\n }\n }\n}", "function poblacionesProvincia(c){\n\t\n\ti_poblacion=\"\";\t \n\tif (c!=2){for (var b=0;b<=7;b++){provinciaListar(b,0)}}\n\t\telse {provinciaListar(2,1);provinciaListar(3,1);provinciaListar(4,1);provinciaListar(5,1);provinciaListar(6,1);provinciaListar(7,1)}\n\t\t\n\treturn i_poblacion;\n}", "atualizaCentroideX() {\r\n if (this.centroidesX.length <= 0) {\r\n this.centroidesX[0] = this.eixoX[this.indice1];\r\n for (let i = 1; i < this.grupos; i++) {\r\n this.centroidesX[i] = this.eixoX[this.indice2];\r\n }\r\n } else {\r\n for (let i = 0; i < this.grupos; i++) {\r\n this.centroidesX[i] = this.mediaGrupoX(\r\n this.grupoID_Anterior,\r\n i\r\n );\r\n }\r\n }\r\n }", "function CorrigePericias() {\n for (var chave in tabelas_pericias) {\n var achou = false;\n for (var i = 0; i < gEntradas.pericias.length; ++i) {\n var entrada_pericia = gEntradas.pericias[i];\n if (entrada_pericia.chave == chave) {\n achou = true;\n break;\n }\n }\n if (!achou) {\n gEntradas.pericias.push({ 'chave': chave, pontos: 0 });\n }\n }\n}", "function _sacarOpciones(){\n for(var i=0;i<MARC_OBJECT_ARRAY.length;i++){\n var subcampos_array = MARC_OBJECT_ARRAY[i].getSubCamposArray();\n for(var s=0;s<subcampos_array.length;s++){\n if(subcampos_array[s].opciones){//si esta definido...\n if(subcampos_array[s].opciones.length > 0){\n //elimino la propiedad opciones, para enviar menos info al servidor\n subcampos_array[s].opciones= [];\n }\n }\n }\n }\n}", "function obtenerDatosSucursal(){\n cxcService.getCpcSucursalByIdSucursal({},{},atributosPerfil['sucursalPredeterminada'],serverConf.ERPCONTA_WS, function (response) {\n //exito\n console.info(\"emisionFacturaContrato: Sucursal preestablecida\",response.data);\n //$scope.sucursal = response.data;\n $scope.facturaEmitidaPojo.cpcFacturaEmitida.cpcDosificacion.cpcSucursal = response.data;\n //si la sucursal predeterminada no es la casa matriz obtener datos de la casa matriz\n if( $scope.facturaEmitidaPojo.cpcFacturaEmitida.cpcDosificacion.cpcSucursal .numeroSucursal>0) {\n $scope.mostrar.datosSucursal=true;\n obtenerCasaMatriz();\n }\n }, function (responseError) {\n //error\n });\n }", "function irComputadoresIcon() {\n // Eliminar la clase Activa de los enlaces y atajos\n eliminarClaseActivaEnlances(enlaces, 'activo');\n eliminarClaseActivaEnlances(atajosIcons, 'activo-i');\n // Añadimos la clase activa de la seccion de Coputadores en los enlaces y atajos\n añadirClaseActivoEnlaces(enlaceComputadores, 'activo');\n añadirClaseActivoEnlaces(atajoComputadores, 'activo-i');\n // Crear contenido de la Seccion\n crearContenidoSeccionComputadores();\n // Abrir la seccion \n abrirSecciones();\n}", "function fetchCuisines() {\n DBHelper.fetchCuisines((error, cuisines) => { // eslint-disable-line no-undef\n if (error) { // Got an error!\n console.error(error);\n } else {\n main.cuisines = cuisines;\n IndexDBHelper.storeCuisines(cuisines); // eslint-disable-line no-undef\n resetCuisines();\n fillCuisinesHTML();\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create guards for a variable declaration statement.
function createVariableGuards(node) { var genericTypes = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var guards = []; node.declarations.forEach(function (declaration) { if (declaration.id.typeAnnotation) { guards.push(createVariableGuard(declaration.id, extractAnnotationTypes(declaration.id.typeAnnotation), genericTypes)); } }); return guards.filter(identity); }
[ "function createVariableGuards (node : Object, genericTypes: Array = []) : Array<Object> {\n let guards = []\n node.declarations.forEach(declaration => {\n if (declaration.id.typeAnnotation) {\n guards.push(createVariableGuard(declaration.id, extractAnnotationTypes(declaration.id.typeAnnotation), genericTypes));\n }\n })\n return guards.filter(identity);\n }", "function isDeclareVariableStatement(path) {\n return path.isVariableDeclaration() && path.node.declare === true;\n}", "enterVariable_declaration(ctx) {\n\t}", "function parseVarDeclStatement() {\n CST.addBranchNode(\"VariableDeclarationStatement\");\n if (match([\"T_typeInt\", \"T_typeString\", \"T_typeBoolean\"], false, false)) {\n parseID();\n log(\"Variable Declaration\");\n }\n else {\n errorlog(\"Parse Error - Expected type declaration 'int', 'string' or 'boolean', got \" + tokens[currentToken].tokenName);\n }\n CST.backtrack();\n}", "function checkVariableLikeDeclaration(node) {\n checkDecorators(node);\n checkSourceElement(node.type);\n // For a computed property, just check the initializer and exit\n // Do not use hasDynamicName here, because that returns false for well known symbols.\n // We want to perform checkComputedPropertyName for all computed properties, including\n // well known symbols.\n if (node.name.kind === 143 /* ComputedPropertyName */) {\n checkComputedPropertyName(node.name);\n if (node.initializer) {\n checkExpressionCached(node.initializer);\n }\n }\n if (node.kind === 175 /* BindingElement */) {\n if (node.parent.kind === 173 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */ && !ts.isInAmbientContext(node)) {\n checkExternalEmitHelpers(node, 4 /* Rest */);\n }\n // check computed properties inside property names of binding elements\n if (node.propertyName && node.propertyName.kind === 143 /* ComputedPropertyName */) {\n checkComputedPropertyName(node.propertyName);\n }\n // check private/protected variable access\n var parent = node.parent.parent;\n var parentType = getTypeForBindingElementParent(parent);\n var name = node.propertyName || node.name;\n var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name));\n markPropertyAsReferenced(property);\n if (parent.initializer && property) {\n checkPropertyAccessibility(parent, parent.initializer, parentType, property);\n }\n }\n // For a binding pattern, check contained binding elements\n if (ts.isBindingPattern(node.name)) {\n ts.forEach(node.name.elements, checkSourceElement);\n }\n // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body\n if (node.initializer && ts.getRootDeclaration(node).kind === 145 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {\n error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);\n return;\n }\n // For a binding pattern, validate the initializer and exit\n if (ts.isBindingPattern(node.name)) {\n // Don't validate for-in initializer as it is already an error\n if (node.initializer && node.parent.parent.kind !== 214 /* ForInStatement */) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/undefined);\n checkParameterInitializer(node);\n }\n return;\n }\n var symbol = getSymbolOfNode(node);\n var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol));\n if (node === symbol.valueDeclaration) {\n // Node is the primary declaration of the symbol, just validate the initializer\n // Don't validate for-in initializer as it is already an error\n if (node.initializer && node.parent.parent.kind !== 214 /* ForInStatement */) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/undefined);\n checkParameterInitializer(node);\n }\n } else {\n // Node is a secondary declaration, check that type is identical to primary declaration and check that\n // initializer is consistent with type associated with the node\n var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));\n if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) {\n error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType));\n }\n if (node.initializer) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/undefined);\n }\n if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {\n error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));\n error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));\n }\n }\n if (node.kind !== 148 /* PropertyDeclaration */ && node.kind !== 147 /* PropertySignature */) {\n // We know we don't have a binding pattern or computed name here\n checkExportsOnMergedDeclarations(node);\n if (node.kind === 225 /* VariableDeclaration */ || node.kind === 175 /* BindingElement */) {\n checkVarDeclaredNamesNotShadowed(node);\n }\n checkCollisionWithCapturedSuperVariable(node, node.name);\n checkCollisionWithCapturedThisVariable(node, node.name);\n checkCollisionWithCapturedNewTargetVariable(node, node.name);\n checkCollisionWithRequireExportsInGeneratedCode(node, node.name);\n checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);\n }\n }", "function checkVariableLikeDeclaration(node) {\n checkDecorators(node);\n if (!ts.isBindingElement(node)) {\n checkSourceElement(node.type);\n }\n // JSDoc `function(string, string): string` syntax results in parameters with no name\n if (!node.name) {\n return;\n }\n // For a computed property, just check the initializer and exit\n // Do not use hasDynamicName here, because that returns false for well known symbols.\n // We want to perform checkComputedPropertyName for all computed properties, including\n // well known symbols.\n if (node.name.kind === 145 /* ComputedPropertyName */) {\n checkComputedPropertyName(node.name);\n if (node.initializer) {\n checkExpressionCached(node.initializer);\n }\n }\n if (node.kind === 177 /* BindingElement */) {\n if (node.parent.kind === 175 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) {\n checkExternalEmitHelpers(node, 4 /* Rest */);\n }\n // check computed properties inside property names of binding elements\n if (node.propertyName && node.propertyName.kind === 145 /* ComputedPropertyName */) {\n checkComputedPropertyName(node.propertyName);\n }\n // check private/protected variable access\n var parent = node.parent.parent;\n var parentType = getTypeForBindingElementParent(parent);\n var name = node.propertyName || node.name;\n var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name));\n markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/undefined, /*isThisAccess*/false); // A destructuring is never a write-only reference.\n if (parent.initializer && property) {\n checkPropertyAccessibility(parent, parent.initializer, parentType, property);\n }\n }\n // For a binding pattern, check contained binding elements\n if (ts.isBindingPattern(node.name)) {\n if (node.name.kind === 176 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {\n checkExternalEmitHelpers(node, 512 /* Read */);\n }\n ts.forEach(node.name.elements, checkSourceElement);\n }\n // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body\n if (node.initializer && ts.getRootDeclaration(node).kind === 147 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {\n error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);\n return;\n }\n // For a binding pattern, validate the initializer and exit\n if (ts.isBindingPattern(node.name)) {\n // Don't validate for-in initializer as it is already an error\n if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) {\n var initializerType = checkExpressionCached(node.initializer);\n if (strictNullChecks && node.name.elements.length === 0) {\n checkNonNullType(initializerType, node);\n } else {\n checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/undefined);\n }\n checkParameterInitializer(node);\n }\n return;\n }\n var symbol = getSymbolOfNode(node);\n var type = convertAutoToAny(getTypeOfSymbol(symbol));\n if (node === symbol.valueDeclaration) {\n // Node is the primary declaration of the symbol, just validate the initializer\n // Don't validate for-in initializer as it is already an error\n if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/undefined);\n checkParameterInitializer(node);\n }\n } else {\n // Node is a secondary declaration, check that type is identical to primary declaration and check that\n // initializer is consistent with type associated with the node\n var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));\n if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType) && !(symbol.flags & 67108864 /* JSContainer */)) {\n errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType);\n }\n if (node.initializer) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/undefined);\n }\n if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {\n error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));\n error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));\n }\n }\n if (node.kind !== 150 /* PropertyDeclaration */ && node.kind !== 149 /* PropertySignature */) {\n // We know we don't have a binding pattern or computed name here\n checkExportsOnMergedDeclarations(node);\n if (node.kind === 227 /* VariableDeclaration */ || node.kind === 177 /* BindingElement */) {\n checkVarDeclaredNamesNotShadowed(node);\n }\n checkCollisionWithCapturedSuperVariable(node, node.name);\n checkCollisionWithCapturedThisVariable(node, node.name);\n checkCollisionWithCapturedNewTargetVariable(node, node.name);\n checkCollisionWithRequireExportsInGeneratedCode(node, node.name);\n checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);\n }\n }", "function checkVariableLikeDeclaration(node) {\n checkDecorators(node);\n if (!ts.isBindingElement(node)) {\n checkSourceElement(node.type);\n }\n // JSDoc `function(string, string): string` syntax results in parameters with no name\n if (!node.name) {\n return;\n }\n // For a computed property, just check the initializer and exit\n // Do not use hasDynamicName here, because that returns false for well known symbols.\n // We want to perform checkComputedPropertyName for all computed properties, including\n // well known symbols.\n if (node.name.kind === 145 /* ComputedPropertyName */) {\n checkComputedPropertyName(node.name);\n if (node.initializer) {\n checkExpressionCached(node.initializer);\n }\n }\n if (node.kind === 177 /* BindingElement */) {\n if (node.parent.kind === 175 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) {\n checkExternalEmitHelpers(node, 4 /* Rest */);\n }\n // check computed properties inside property names of binding elements\n if (node.propertyName && node.propertyName.kind === 145 /* ComputedPropertyName */) {\n checkComputedPropertyName(node.propertyName);\n }\n // check private/protected variable access\n var parent = node.parent.parent;\n var parentType = getTypeForBindingElementParent(parent);\n var name = node.propertyName || node.name;\n var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name));\n markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.\n if (parent.initializer && property) {\n checkPropertyAccessibility(parent, parent.initializer, parentType, property);\n }\n }\n // For a binding pattern, check contained binding elements\n if (ts.isBindingPattern(node.name)) {\n if (node.name.kind === 176 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {\n checkExternalEmitHelpers(node, 512 /* Read */);\n }\n ts.forEach(node.name.elements, checkSourceElement);\n }\n // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body\n if (node.initializer && ts.getRootDeclaration(node).kind === 147 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {\n error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);\n return;\n }\n // For a binding pattern, validate the initializer and exit\n if (ts.isBindingPattern(node.name)) {\n // Don't validate for-in initializer as it is already an error\n if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) {\n var initializerType = checkExpressionCached(node.initializer);\n if (strictNullChecks && node.name.elements.length === 0) {\n checkNonNullType(initializerType, node);\n }\n else {\n checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined);\n }\n checkParameterInitializer(node);\n }\n return;\n }\n var symbol = getSymbolOfNode(node);\n var type = convertAutoToAny(getTypeOfSymbol(symbol));\n if (node === symbol.valueDeclaration) {\n // Node is the primary declaration of the symbol, just validate the initializer\n // Don't validate for-in initializer as it is already an error\n if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined);\n checkParameterInitializer(node);\n }\n }\n else {\n // Node is a secondary declaration, check that type is identical to primary declaration and check that\n // initializer is consistent with type associated with the node\n var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));\n if (type !== unknownType && declarationType !== unknownType &&\n !isTypeIdenticalTo(type, declarationType) &&\n !(symbol.flags & 67108864 /* JSContainer */)) {\n errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType);\n }\n if (node.initializer) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined);\n }\n if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {\n error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));\n error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));\n }\n }\n if (node.kind !== 150 /* PropertyDeclaration */ && node.kind !== 149 /* PropertySignature */) {\n // We know we don't have a binding pattern or computed name here\n checkExportsOnMergedDeclarations(node);\n if (node.kind === 227 /* VariableDeclaration */ || node.kind === 177 /* BindingElement */) {\n checkVarDeclaredNamesNotShadowed(node);\n }\n checkCollisionWithCapturedSuperVariable(node, node.name);\n checkCollisionWithCapturedThisVariable(node, node.name);\n checkCollisionWithCapturedNewTargetVariable(node, node.name);\n checkCollisionWithRequireExportsInGeneratedCode(node, node.name);\n checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);\n }\n }", "function isVarDeclaration(declarationList, typescript) {\n return declarationList.flags !== typescript.NodeFlags.Const && declarationList.flags !== typescript.NodeFlags.Let;\n}", "function createVariableGuard (id: Object, types: Array<Object|string>, genericTypes: Array = []) {\n if (types.indexOf('any') > -1 || types.indexOf('mixed') > -1) {\n return null;\n }\n const test = createIfTest(id, types, genericTypes);\n if (!test) {\n return null;\n }\n return t.ifStatement(\n test,\n t.throwStatement(\n t.newExpression(\n t.identifier(\"TypeError\"),\n [t.binaryExpression(\"+\",\n t.literal(`Value of variable '${id.name}' violates contract, expected ${createTypeNameList(types)} got `),\n createReadableTypeName(id)\n )]\n )\n )\n );\n }", "function is_var_definition(stmt) {\r\n return is_tagged_object(stmt, \"var_definition\");\r\n}", "VariableStatement() {\n this._eat('let');\n const declarations = this.VariableDeclarationsList();\n this._eat(';');\n return {\n type: 'VariableStatement',\n declarations,\n };\n }", "function validarVariableDeclarada(variableDecl){\n\tif(consultarTipoDatoVariable(variableDecl) != null){\n\t\terrores.push(ERROR_VARIABLE_YA_DECLARADA.replace(\"%1%\", variableDecl ));\n\t\treturn false;\n\t}else{\n\t\treturn true;\n\t}\n}", "function parseVarDecl() {\n // preemptively\n var typeToken = tokenStream[0];\n var idToken = tokenStream[1];\n \n var varDeclToken = new Token();\n varDeclToken.type = ST_DECLARATION;\n varDeclToken.line = typeToken.line;\n \n // token field is a special token here since this does not\n // really have a source code token associated with it\n AST.addNode('VarDecl', 'branch', varDeclToken);\n \n if(parseType() && parseId('declared')) {\n // see if new variable declaration is in the symbol table\n if(! symbolTable.addIdentifier(idToken, typeToken)) {\n var line = idToken.line;\n var error = line + \" : Redeclared Identifier \" + idToken.value;\n \n if(errors[line] === undefined) {\n errors[line] = new Array();\n }\n \n // Store error\n errors[line].push(error);\n \n // log error\n log(error, 'error');\n }\n \n AST.endChildren();\n \n return true;\n } else {\n return false;\n }\n }", "function createVariableGuard(id, types) {\n var genericTypes = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2];\n\n if (types.indexOf('any') > -1 || types.indexOf('mixed') > -1) {\n return null;\n }\n var test = createIfTest(id, types, genericTypes);\n if (!test) {\n return null;\n }\n return t.ifStatement(test, t.throwStatement(t.newExpression(t.identifier(\"TypeError\"), [t.binaryExpression(\"+\", t.literal('Value of variable \\'' + id.name + '\\' violates contract, expected ' + createTypeNameList(types) + ' got '), createReadableTypeName(id))])));\n }", "enterVariableClause(ctx) {\n\t}", "function visitVariableStatement(node){if(!shouldHoistVariableDeclarationList(node.declarationList)){return ts.visitNode(node,destructuringAndImportCallVisitor,ts.isStatement);}var expressions;var isExportedDeclaration=ts.hasModifier(node,1/* Export */);var isMarkedDeclaration=hasAssociatedEndOfDeclarationMarker(node);for(var _i=0,_a=node.declarationList.declarations;_i<_a.length;_i++){var variable=_a[_i];if(variable.initializer){expressions=ts.append(expressions,transformInitializedVariable(variable,isExportedDeclaration&&!isMarkedDeclaration));}else{hoistBindingElement(variable);}}var statements;if(expressions){statements=ts.append(statements,ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)),node));}if(isMarkedDeclaration){// Defer exports until we encounter an EndOfDeclarationMarker node\nvar id=ts.getOriginalNodeId(node);deferredExports[id]=appendExportsOfVariableStatement(deferredExports[id],node,isExportedDeclaration);}else{statements=appendExportsOfVariableStatement(statements,node,/*exportSelf*/false);}return ts.singleOrMany(statements);}", "static isVariableStatement(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.VariableStatement;\r\n }", "function variableDeclarationHasPattern(node) {\n\t\t for ( /*istanbul ignore next*/var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {\n\t\t /*istanbul ignore next*/\n\t\t var _ref2;\n\t\n\t\t if (_isArray) {\n\t\t if (_i >= _iterator.length) break;\n\t\t _ref2 = _iterator[_i++];\n\t\t } else {\n\t\t _i = _iterator.next();\n\t\t if (_i.done) break;\n\t\t _ref2 = _i.value;\n\t\t }\n\t\n\t\t var declar = _ref2;\n\t\n\t\t if (t.isPattern(declar.id)) {\n\t\t return true;\n\t\t }\n\t\t }\n\t\t return false;\n\t\t }", "function zipDeclare(vars, values) {\n\tif (!vars) return [];\n\tvalues = values || [];\n\tif (vars.length < 1) return [];\n\n\treturn [{\n\t\ttype: \"VariableDeclaration\",\n\t\tkind: \"var\",\n\t\tdeclarations: vars.map(function (varName, index) {\n\t\t\treturn {\n\t\t\t\ttype: \"VariableDeclarator\",\n\t\t\t\tid: identifier(varName),\n\t\t\t\tinit: values[index] || null\n\t\t\t};\n\t\t})\n\t}];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create client according to type.
createClient() { switch (this.config.type) { case 'azureBlob': return new __1.AzureBlobClient(this.config); default: throw new Error(`NotImplemented`); } }
[ "createClient(type, json) {\n return Client.create(this.companyId, this.id, type, json)\n }", "static build(type, config, bot) {\n return __awaiter(this, void 0, void 0, function* () {\n // Initialize the object.\n let client;\n // Depending on the requested type, we build the appropriate client.\n switch (type) {\n // Create a DiscordClient if the type is Discord.\n case ClientType_1.ClientType.Discord: {\n client = new DiscordClient_1.DiscordClient(bot, config);\n break;\n }\n // Create a TwitchClient if the type is Discord.\n case ClientType_1.ClientType.Twitch: {\n client = new TwitchClient_1.TwitchClient(bot, config);\n }\n // // Create a SlackClient if the type is Discord.\n // Case ClientType.Slack: {\n // Client = new SlackClient(config, bot);\n // Break;\n // }\n }\n // Bridge a connection to the application for the client.\n yield client.bridge();\n // Run build tasks for client.\n yield client.build();\n // Make sure database collection exists for this client for the given bot.\n yield Gestalt_1.Gestalt.createCollection(`/bots/${bot.id}/clients/${client.type}`);\n // Make sure database collection exists for permissions in this client.\n yield Gestalt_1.Gestalt.createCollection(`/bots/${bot.id}/clients/${client.type}`);\n // Initialize i18n database collection for this client if it doesn't already exist.\n yield Gestalt_1.Gestalt.createCollection(`/i18n/${bot.id}/clients/${client.type}`);\n // Return the client.\n return client;\n });\n }", "function createClientType() {\n log.info(\"create client\");\n // [ -Events- ]\n // error - when there's a problem with a received message\n // open - when the connection is open\n // close - when the connection is closed\n // message - when there's a message from the hub\n // [ -Constructor- ]\n function Client() {\n log.info(\"instantiate client\");\n // get non-ambiguous this\n var self = this;\n // Call parent constructor\n Client.super_.call(self);\n // Internal structures\n self._transport = undefined;\n self._txRegistry = {};\n self._lastTxId = 0;\n self._txLimit = 1000;\n self._state = \"NOT_OPENED\";\n self._messageDispatch = {\n distribution: self._handleDistribution.bind(self),\n published: self._handlePublication.bind(self),\n subscribed: self._handleSubscription.bind(self),\n unsubscribed: self._handleUnsubscription.bind(self),\n };\n // state listeners\n self.once(\"open\", function handleOpened() {\n self._state = \"OPEN\";\n }).once(\"close\", function handleClosed() {\n self._state = \"CLOSED\";\n });\n // constructor - return undefined\n return undefined;\n }\n // [ -Inheritance- ]\n util.inherits(Client, events.EventEmitter);\n // [ -Private API- ]\n // check state for OPEN\n Client.prototype._checkState = function clientCheckState() {\n if (this._state !== \"OPEN\") {\n throw new VError(\"Nonsensical to call before 'open' or after 'close' events\");\n }\n return this;\n };\n // get a transaction ID\n Client.prototype._getTxID = function clientGetTxID() {\n var txid;\n // try the last txid + 1 first\n var candidate = this._lastTxId + 1;\n // try to get a txid until we get one, or we've failed _txLimit times\n // (this means we have _txLimit txid's already assigned)\n var tries = 0;\n while (txid === undefined && tries < this._txLimit) {\n tries++;\n candidate %= this._txLimit;\n if (this._txRegistry[candidate] === undefined) {\n txid = candidate;\n } else {\n candidate++;\n }\n }\n // catch the error exit\n if (txid === undefined) {\n throw new VError(\"Cannot issue a transaction ID - too many outstanding transactions (%d)\", this._txLimit);\n }\n // set the last txid and return it to the caller\n this._lastTxId = txid;\n return txid;\n };\n // register a transaction ID\n Client.prototype._registerTxID = function clientRegisterTxID(txid, cb) {\n this._txRegistry[txid] = cb;\n // allow chaining\n return this;\n };\n // retire a transaction ID\n Client.prototype._retireTxID = function clientRetireTxID(txid) {\n delete this._txRegistry[txid];\n // allow chaining\n return this;\n };\n // handle publication message\n Client.prototype._handlePublication = function clientHandlePublication(messageObj) {\n log.info(\"client handle publication\");\n // validate message\n var error = validateProperties(\n messageObj,\n \"published message from transport layer\",\n ['type', 'message', 'channel', 'number', 'transactionID'],\n []\n );\n // FIXME - message should be JSON\n // FIXME - channel should be string\n // FIXME - number should be a number\n // FIXME - txid should be number\n // FIXME - need a test for no tx callback (on purpose)\n if (error) { this.emit('error', error); return null; }\n var transactionCallback = this._txRegistry[messageObj.transactionID];\n if (transactionCallback) {\n transactionCallback(null, messageObj.message, messageObj.channel, messageObj.number);\n this._retireTxID(messageObj.transactionID);\n } else {\n this.emit('error', new VError(\"received a message with an unrecognized transaction ID: %j\", messageObj));\n }\n // allow chaining\n return this;\n };\n // handle subscription message\n Client.prototype._handleSubscription = function clientHandleSubscription(messageObj) {\n log.info(\"client on subscribed\");\n var error = validateProperties(\n messageObj,\n \"subscribed message from transport layer\",\n ['type', 'pattern', 'number', 'transactionID'],\n []\n );\n // FIXME - pattern should be regex\n // FIXME - number should be a number\n if (error) { this.emit('error', error); return null; }\n var transactionCallback = this._txRegistry[messageObj.transactionID];\n if (transactionCallback) {\n log.debug(\"calling tx callback with\", messageObj.pattern, messageObj.number);\n transactionCallback(null, messageObj.pattern, messageObj.number);\n this._retireTxID(messageObj.transactionID);\n } else {\n this.emit('error', new VError(\"received a message with an unrecognized transaction ID: %j\", messageObj));\n }\n // allow chaining\n return this;\n };\n // handle unsubscription message\n Client.prototype._handleUnsubscription = function clientHandleUnsubscription(messageObj) {\n log.info(\"client on unsubscribed\");\n var error = validateProperties(\n messageObj,\n \"unsubscribed message from transport layer\",\n ['type', 'pattern', 'number', 'transactionID'],\n []\n );\n // FIXME - pattern should be regex\n // FIXME - number should be a number\n if (error) { this.emit('error', error); return null; }\n var transactionCallback = this._txRegistry[messageObj.transactionID];\n if (transactionCallback) {\n transactionCallback(null, messageObj.pattern, messageObj.number);\n this._retireTxID(messageObj.transactionID);\n } else {\n this.emit('error', new VError(\"received a message with an unrecognized transaction ID: %j\", messageObj));\n }\n // allow chaining\n return this;\n };\n // handle distributions\n Client.prototype._handleDistribution = function clientDistribute(messageObj) {\n log.info(\"client on distribution\");\n var error = validateProperties(\n messageObj,\n \"distribution message from transport layer\",\n ['type', 'message', 'channel', 'match'],\n []\n );\n // FIXME - message should be JSON\n // FIXME - channel should be string\n // FIXME - match should be a regex\n if (error) { this.emit('error', error); return null; }\n this.emit('message', messageObj.message, messageObj.channel, messageObj.match);\n // allow chaining\n return this;\n };\n // handle messages from the transport layer\n Client.prototype._handleMessage = function clientHandleMessage(messageObj) {\n log.info(\"client handle message\", this._id, messageObj);\n // parse the message type and respond accordingly\n var handler = this._messageDispatch[messageObj.type];\n if (handler === undefined) {\n this.emit('error', new VError(\"No dispatcher found for message type (%s) (%j)\", messageObj.type, messageObj));\n } else {\n handler(messageObj);\n }\n // allow chaining\n return this;\n };\n // [ -Public API- ]\n // get/set the limit for the max number of client-initiated\n // transactions in flight simultaneously\n Client.prototype.txLimit = function clientTxLimit(limit) {\n if (limit) {\n this._txLimit = limit;\n }\n return this._txLimit;\n };\n // subscribe a subscriber\n Client.prototype.subscribe = function clientSubscribe(pattern, cb) {\n log.info(\"client subscribe\", this._transport._id, pattern);\n // get a non-ambiguous \"this\"\n var self = this;\n // check state\n this._checkState();\n // get a transaction id\n var txid;\n try {\n txid = self._getTxID();\n } catch (e) {\n callback(cb)(new VError(e, \"cannot subscribe - no transaction ID available.\"));\n // early return because we don't want to execute anything else,\n // and js has no try/catch/else\n return self;\n }\n self._registerTxID(txid, callback(cb));\n // send subscription request\n self._transport.send({\n type: 'subscription',\n 'pattern': pattern,\n transactionID: txid,\n }, function handleCompletion(error) {\n // if there's an error, need to retire the TXID early.\n // assumes a send error means the message was not sent,\n // and there's not going to be a corresponding response.\n if (error) {\n self._retireTxID(txid);\n cb(error);\n }\n return null;\n });\n // allow chaining of calls\n return self;\n };\n // unsubscribe a pattern\n Client.prototype.unsubscribe = function clientUnsubscribe(pattern, cb) {\n log.info(\"client unsubscribe\", this._transport._id, pattern);\n // get a non-ambiguous \"this\"\n var self = this;\n // check state\n this._checkState();\n // get a transaction id\n var txid;\n try {\n txid = self._getTxID();\n } catch (e) {\n callback(cb)(new VError(e, \"cannot unsubscribe - no transaction ID available.\"));\n return self;\n }\n self._registerTxID(txid, callback(cb));\n // send unsubscription request\n self._transport.send({\n type: 'unsubscription',\n 'pattern': pattern,\n transactionID: txid,\n }, function handleCompletion(error) {\n // if there's an error, need to retire the TXID early.\n // assumes a send error means the message was not sent,\n // and there's not going to be a corresponding response.\n if (error) {\n self._retireTxID(txid);\n callback(cb)(error);\n }\n return null;\n });\n // allow chaining\n return self;\n };\n // publish to subscribers\n Client.prototype.publish = function clientPublish(message, channel, cb) {\n log.info(\"client publish\", this._transport._id, message);\n var self = this;\n // check state\n this._checkState();\n // get a transaction id\n var txid;\n try {\n txid = self._getTxID();\n } catch (e) {\n callback(cb)(new VError(e, \"cannot publish - no transaction ID available.\"));\n return self;\n }\n self._registerTxID(txid, callback(cb));\n // send publication request\n self._transport.send({\n type: 'publication',\n 'message': message,\n 'channel': channel,\n transactionID: txid,\n }, function handleCompletion(error) {\n // if there's an error, need to retire the TXID early.\n // assumes a send error means the message was not sent,\n // and there's not going to be a corresponding response.\n if (error) {\n self._retireTxID(txid);\n callback(cb)(new VError(error, \"Error sending to hub\"));\n }\n return null;\n });\n // allow chaining\n return self;\n };\n // close a transport object\n Client.prototype.close = function clientClose() {\n log.info(\"client close\");\n if (this._state !== \"OPEN\") {\n throw new VError(\"Cannot close a client which is not open\");\n }\n this._transport.close();\n // it doesn't make sense to do anything with the object after this,\n // so return null\n return null;\n };\n // connect to listening client\n Client.prototype.connect = function clientConnect(url, cb) {\n log.info(\"client connect\");\n // only allow this to be called once on the object\n if (this._transport) {\n // throw immediately - this is programmer error\n throw new VError(\"'connect' has already been called on this client.\");\n }\n // add cb to listeners\n if (cb) {\n this.on('open', cb);\n }\n // open a new transport connection\n this._transport = new ActualTransportClient();\n this._transport.connect(url);\n // proxy some events\n this._transport.on('open', this.emit.bind(this, 'open'));\n this._transport.on('close', this.emit.bind(this, 'close'));\n // handle messages from transport\n this._transport.on('message', this._handleMessage.bind(this));\n // it doesn't make sense to do anything with the object until connect\n // calls back, so return null\n return null;\n };\n // return a new Client\n return Client;\n}", "static createClientApi(profile) {\n if (! profile) {\n profile = serverconfig.mode.value;\n }\n\n const factoryApiSettings = serverconfig.factory[profile].client;\n return new factoryApiSettings.typeClass(factoryApiSettings.opts);\n }", "function createType(type) {\n return new Promise((fullfill, reject) => {\n ARGS.type = type;\n client.create(ARGS, (err, res) => {\n if(err) {\n LOG.info(\"Unable to create type %s, because of %s\", type, err);\n reject(err); \n } else {\n LOG.info(\"type %s created.\", type);\n fullfill(res);\n } \n });\n }); \n}", "_createNewClient() {\n if (this.client) {\n this.client.off(\"tokensUpdated\", this._onTokensUpdated);\n }\n this._onTokensUpdated = () => {\n this.updateTokens(this.client.accessToken, this.client.refreshToken, false);\n };\n this._client = new MyButtercupClient(this._clientID, this._clientSecret, this.accessToken, this.refreshToken);\n this._client.on(\"tokensUpdated\", this._onTokensUpdated);\n /**\n * On client updated\n * @event MyButtercupDatasource#updatedClient\n * @type {Object}\n */\n this.emit(\"updatedClient\", this._client);\n }", "function createClient(req, res, next) {\n let body = req.body\n model.createClient(body).then( data => {\n res.status(200).json({ data })\n })\n}", "function createClient() {\n return new L4.ClientEndpoint();\n}", "createClient(callback) {\n request.post(config.agave.url + 'clients/v2', {\n headers: {\n Authorization: userAuth\n },\n body: {\n clientName: client.config.name,\n description: client.config.clientDescription\n }\n }, callback);\n }", "create(type) {\n switch (type) {\n case (\"Base\" /* Base */):\n return new IgxTransactionService();\n ;\n default:\n return new IgxBaseTransactionService();\n }\n }", "static async getRpcByType(type)\n\t{\n\t\ttry {\n\t\t\tassert(typeof type === 'string');\n\n\t\t\t// TODO: Cache this.\n\t\t\tconst rpcs = await InternalAPI.get('ffrpc/list', {\n\t\t\t\tqueryString: { type }\n\t\t\t});\n\n\t\t\t// Random RPCs index\n\t\t\tconst rpcIndex = getRandomInteger(0, rpcs.length - 1);\n\n\t\t\t// Creating FFRPCClient object and returning it.\n\t\t\treturn new FFRPCClient(rpcs[rpcIndex]);\n\t\t}\n\t\tcatch(err) {\n\t\t\tthrow err;\n\t\t}\n\t}", "get client() {\n return setupClientType('default');\n }", "function newClientModel(typeName) {\n return context._newClientModel(typeName);\n }", "function buildClient(){\n if(!client){\n\n const type = getAuthType();\n const appId = getAppId();\n const endpoints = getEndpoints();\n const easEndpoint = getEasUrl();\n const kasEndpoint = getKasUrl();\n const acmEndpoint = getAcmUrl();\n\n const clientConf = {\n email: getUser(),\n easEndpoint: easEndpoint || endpoints.easEndpoint, \n kasEndpoint: kasEndpoint || endpoints.kasEndpoint, \n acmEndpoint: acmEndpoint || endpoints.acmEndpoint\n };\n\n if(appId){\n clientConf.appId = appId;\n }\n \n client = new Virtru.Client(clientConf);\n }\n\n return client;\n}", "create(type) {\n switch (type) {\n case (\"Base\" /* Base */):\n return new IgxHierarchicalTransactionService();\n ;\n default:\n return new IgxBaseTransactionService();\n }\n }", "function createClient() {\n\treturn Asana.Client.create({\n\t\tclientId: clientId,\n\t\tclientSecret: clientSecret,\n\t\tredirectUri: global.config.get(\"asana.redirect_uri\")\n\t});\n}", "function createClient() {\n var opt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n return new __WEBPACK_IMPORTED_MODULE_0_react_apollo__[\"ApolloClient\"](Object.assign({\n reduxRootSelector: function reduxRootSelector(state) {\n return state.apollo;\n }\n }, __WEBPACK_IMPORTED_MODULE_1_kit_config__[\"a\" /* default */].apolloClientOptions, opt));\n}", "function newService(type){\n\n if(type === \"Shower\"){\n var service = new Service(\"Shower\", \"15.00\", \"30\");\n }\n else if(type === \"Hair Cut\"){\n var service = new Service(\"Hair Cut\", \"50.00\", \"120\");\n }\n else if(type === \"Toenail Trim\"){\n var service = new Service(\"Toenail\", \"25.00\", \"60\");\n }\n else if(type === \"Full Service\"){\n var service = new Service(\"Full Service\", \"90.00\", \"240\");\n } \n\n return service;\n\n }", "function create(transport, config)\n{\n switch (transport) {\n case 'mqtt':\n return require('./silhouette-client-mqtt').create(config);\n case 'iothub':\n return require('./silhouette-client-iothub').create(config);\n default:\n // Raise some kind of error\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize defaults for the generator. Adds middleware for renaming dest files and parsing frontmatter, and an engine for rendering ERBstyle templates (like lodash/underscore templates: ``) This is wrapped in a function so we can export it on the `.init` property in case you need to call it directly in your generator. This also returns an options object created from merging generator options, instance options, and defaults, so you can override this if necessary.
function init(app, config, options) { app.use(utils.conflicts()); // merge `config` object onto options if (!config.isApp) { app.option(config); } var defaults = { engine: '*', dest: app.cwd, collection: 'templates' }; var opts = utils.extend(defaults, app.options); app.use(utils.defaults); // ensure the `templates` collection exists. This doesn't really // need to be done, but it allows the generator to be used with // verb and assemble with no additional config if (typeof app[opts.collection] === 'undefined') { app.create(opts.collection, opts); } // remove or rename template prefixes before writing files to the file system app.preWrite(/\.js$/, function(file, next) { file.basename = file.basename.replace(/^_/, '.').replace(/^\$/, ''); next(); }); return opts; }
[ "function setupDefaultOptions(options) {\r\n\tif(!options)\r\n\t\toptions = {};\r\n\tif(!options.extensions)\r\n\t\toptions.extensions = [\"\", \".js\"];\r\n\tif(!options.loaders)\r\n\t\toptions.loaders = [];\r\n\tif(!options.postfixes)\r\n\t\toptions.postfixes = [\"\"];\r\n\tif(!options.loaderExtensions)\r\n\t\toptions.loaderExtensions = [\".node-loader.js\", \".loader.js\", \"\", \".js\"];\r\n\tif(!options.loaderPostfixes)\r\n\t\toptions.loaderPostfixes = [\"-node-loader\", \"-loader\", \"\"];\r\n\tif(!options.paths)\r\n\t\toptions.paths = [];\r\n\tif(!options.modulesDirectorys)\r\n\t\toptions.modulesDirectorys = [\"node_modules\"];\r\n\tif(!options.alias)\r\n\t\toptions.alias = {};\r\n\tif(!options.postprocess)\r\n\t\toptions.postprocess = {};\r\n\tif(!options.postprocess.normal)\r\n\t\toptions.postprocess.normal = [];\r\n\tif(!options.postprocess.context)\r\n\t\toptions.postprocess.context = [];\r\n\treturn options;\r\n}", "init(options) {\n if (options && typeof options === 'object') {\n defaultOptions = updateOptions(defaultOptions, options);\n }\n }", "async configure(options) {\n const settings = {};\n settings.debug = options.debug || false;\n Object.freeze(settings);\n this.settings = settings;\n this.plugins = this.createPlugins(options.plugins);\n this[INIT](true);\n }", "function withDefaultConfig(parserOpts) {\n if (parserOpts === void 0) { parserOpts = exports.defaultParserOpts; }\n return withCompilerOptions(defaultOptions, parserOpts);\n}", "initDefaultConfig_ts() {\n\t\tconst match = MixEasyConfMatch.get('ts');\n\t\tconst tsConfig = new MixEasyStructureConfig('ts')\n\t\t\t.setMixCallbackName(match.callback)\n\t\t\t.setDestinationRep(match.destination)\n\t\t\t.setOutputExtension(match.extension)\n\t\t\t.allFilesStartingWithLowerCaseAreEntryPoints();\n\t\tthis.addProcessConfig(tsConfig);\n\n\t\treturn tsConfig;\n\t}", "setupApp() {\n this.app = express();\n if (this.config.bodyParserOptions.json) {\n this.app.use(bodyParser.json(this.config.bodyParserOptions.json));\n }\n if (this.config.bodyParserOptions.raw) {\n this.app.use(bodyParser.raw(this.config.bodyParserOptions.raw));\n }\n if (this.config.bodyParserOptions.text) {\n this.app.use(bodyParser.text(this.config.bodyParserOptions.text));\n }\n if (this.config.bodyParserOptions.urlencoded) {\n this.app.use(bodyParser.urlencoded(this.config.bodyParserOptions.urlencoded));\n }\n this.app.use(cookieParser(this.config.cookieParserOptions));\n this.app.use(morgan(this.config.morganOptions));\n this.app.use(compression(this.config.compressionOptions));\n }", "setupApp() {\n this.app = express()\n if (this.config.bodyParserOptions.json) {\n this.app.use( bodyParser.json(this.config.bodyParserOptions.json) )\n }\n if (this.config.bodyParserOptions.raw) {\n this.app.use( bodyParser.raw(this.config.bodyParserOptions.raw) )\n }\n if (this.config.bodyParserOptions.text) {\n this.app.use( bodyParser.text(this.config.bodyParserOptions.text) )\n }\n if (this.config.bodyParserOptions.urlencoded) {\n this.app.use( bodyParser.urlencoded(this.config.bodyParserOptions.urlencoded) )\n }\n this.app.use( cookieParser(this.config.cookieParserOptions) )\n this.app.use( morgan(this.config.morganOptions) )\n this.app.use( compression(this.config.compressionOptions) )\n }", "__initTemplateEngine() {\n this.templateEngine = _dot2.default.process({ templateSettings: { strip: false }, path: 'views/' });\n }", "function Configuration(options) {\n if (options === undefined) {\n throw new Error(\"No options provided.\");\n }\n\n if (options.templateEngine === undefined) {\n throw new Error(\"No template engine provided.\");\n }\n else {\n this.templateEngine = options.templateEngine;\n }\n\n if (options.configFile === undefined) {\n throw new Error(\"No configuration file provided.\");\n }\n else {\n this.configFilePath = path.resolve(options.configFile);\n }\n\n if (options.bootstrapFile === undefined) {\n throw new Error(\"No bootstrap file provided.\");\n }\n else {\n this.bootstrapFilePath = path.resolve(options.bootstrapFile);\n }\n\n if (options.outputFile === undefined) {\n throw new Error(\"No output file provided.\");\n }\n else {\n this.outputFilePath = path.resolve(options.outputFile);\n }\n\n this.msb = {};\n }", "configure(options) {\n // base config\n const config = Object.assign({}, exports.defaultConfig, { watchDirs: getDefaultWatchDirs(options) });\n const cwd = options.cwd || config.cwd;\n const configFile = options.configFile || config.configFile;\n const pkgInfo = utils.getPkgInfo(cwd);\n config.framework = options.framework || exports.defaultConfig.framework;\n // read from package.json\n if (pkgInfo.egg) {\n mergeConfig(config, pkgInfo.egg.tsHelper);\n }\n // read from local file\n mergeConfig(config, utils.requireFile(utils.getAbsoluteUrlByCwd(configFile, cwd)));\n debug('%o', config);\n // merge local config and options to config\n mergeConfig(config, options);\n debug('%o', options);\n // resolve config.typings to absolute url\n config.typings = utils.getAbsoluteUrlByCwd(config.typings, cwd);\n this.config = config;\n }", "function GeneralOptions(initializer){ // default constructor\n //properties\n //verboseLevel = 1\n //warningLevel = 1\n //comments = 1 // 0=>no comments, 1=>source line & source comments 2=>add \"compiled by...\"\n\n //ifdef PROD_C\n //target =\"c\"\n //outDir = 'generated/c'\n //else\n //target =\"js\"\n //outDir = 'generated/js'\n //end if\n\n //debugEnabled = undefined\n //perf=0 // performace counters 0..2\n //skip = undefined\n //generateSourceMap = true //default is to generate sourcemaps\n //single = undefined\n //compileIfNewer = undefined //compile only if source is newer\n //browser =undefined //compile js for browser environment (instead of node.js env.)\n //es6: boolean //compile to js-EcmaScript6\n\n //defines: array of string = []\n //includeDirs: array of string = []\n\n //projectDir:string = '.'\n //mainModuleName:string = 'unnamed'\n\n //storeMessages: boolean = false\n\n //literalMap: string // produce \"new Class().fromObject({})\" on \"{}\"\" instead of a js object\n // activate with: 'lexer options object literal is Foo'. A class is required to produce C-code\n\n //version: string\n\n //now: Date = new Date()\n this.verboseLevel=1;\n this.warningLevel=1;\n this.comments=1;\n this.target=\"js\";\n this.outDir='generated/js';\n this.debugEnabled=undefined;\n this.perf=0;\n this.skip=undefined;\n this.generateSourceMap=true;\n this.single=undefined;\n this.compileIfNewer=undefined;\n this.browser=undefined;\n this.defines=[];\n this.includeDirs=[];\n this.projectDir='.';\n this.mainModuleName='unnamed';\n this.storeMessages=false;\n this.now=new Date();\n for(prop in initializer) if (initializer.hasOwnProperty(prop)) this[prop]=initializer[prop];}", "constructor(inputNodes, destDir = \"\", options = {}) {\n super(inputNodes, {\n name: \"ElmCompiler\",\n annotation: \"broccoli-elm\",\n persistentOutput: false,\n cacheInclude: [/.*\\.elm$/],\n cacheExclude: []\n });\n\n this.destDir = destDir;\n let useDebug = process.env.EMBER_ENV != \"production\";\n let optimize = process.env.EMBER_ENV == \"production\";\n this.options = Object.assign(\n {\n debug: useDebug,\n optimize: optimize\n },\n optionDefaults,\n options\n );\n }", "init () {\n this.addGenerator ('application/pdf', PdfGenerator)\n this.addGenerator ('defaultGenerator', DefaultGenerator)\n this.addGenerator ('text/plain | text/csv', TxtGenerator)\n this.addGenerator ('image/jpeg | image/gif | image/png | image/jpg', ImgGenerator)\n }", "__initTemplateEngine() {\n this.templateEngine = Dot.process( { templateSettings: { strip: false }, path: 'views/' } );\n }", "function preInitialize(options) {\n\tthis.app = options.app;\n\tthis.layoutTemplate = options.layoutTemplate;\n\tthis.startExpressApp = options.startExpressApp;\n\tthis.dataStore = options.dataStore;\n}", "setOptions(options) {\n this.root = options.root;\n this.srcDir = options.srcDir;\n this.appName = options.appName;\n this.appDir = options.appDir;\n this.vendorSassCode = {\n ltr: '',\n rtl: '',\n };\n\n this.compiled = {\n ltr: '',\n rtl: '',\n };\n\n this.currentStyleCode = {\n ltr: '',\n rtl: '',\n };\n\n this.filesList = {\n ltr: [],\n rtl: [],\n };\n\n this.paths = [\n this.srcDir + '/common/scss/',\n this.appDir + '/scss/',\n this.root + '/node_modules/',\n ];\n\n this.outputDirectory = `${this.root}/public/${this.appName}/css/`;\n\n if (options.direction) {\n this.setDirection(direction);\n }\n }", "function configuration(override) {\n var res = __assign({}, exports.DefaultConfig);\n if (override.src)\n Object.assign(res.src, override.src);\n if (override.dest)\n Object.assign(res.dest, override.dest);\n if (override.bundle)\n Object.assign(res.bundle, override.bundle);\n if (override.page) {\n if (override.page.title)\n Object.assign(res.page.title, override.page.title);\n if (override.page.favicon)\n res.page.favicon = override.page.favicon;\n if (override.page.meta)\n res.page.meta = override.page.meta;\n if (override.page.fonts)\n res.page.fonts = override.page.fonts;\n if (override.page.scripts)\n res.page.scripts = override.page.scripts;\n if (override.page.stylesheets)\n res.page.stylesheets = override.page.stylesheets;\n if (override.page.post)\n res.page.post = override.page.post;\n }\n if (override.dev)\n Object.assign(res.dev, override.dev);\n if (override.theme)\n res.theme = override.theme;\n if (override.markdown) {\n Object.assign(res.markdown, override.markdown);\n if (override.markdown.customComponents)\n res.markdown.BlockQuote = marked_1.quotedComponents(override.markdown.customComponents);\n }\n if (override.tocMarkdown) {\n Object.assign(res.tocMarkdown, override.tocMarkdown);\n if (override.tocMarkdown.customComponents)\n res.markdown.BlockQuote = marked_1.quotedComponents(override.tocMarkdown.customComponents);\n }\n if (override.misc)\n res.misc = override.misc;\n return res;\n}", "init () {\n\t\t// support json encoded bodies\n\t\tthis.app.use(express.json());\n\n\t\t// support encoded bodies\n\t\tthis.app.use(bodyParser.urlencoded({ extended: true }));\n\n\t\t// Static routing for public files\n\t\tthis.app.use(\"/\", express.static(path.join(__dirname, \"..\", \"..\", \"public-frontend\")));\n\n\t\t// API routing\n\t\tCONFIG.api.forEach((api, i) => {\n\t\t\tconst apiRouter = require(`./${api.path}`);\n\t\t\tif (api.default) {\n\t\t\t\tthis.app.use(\"/api\", apiRouter);\n\t\t\t}\n\t\t\tthis.app.use(`/api/v${api.version}`, apiRouter);\n\t\t\tprint(`Created API route v${api.version}`);\n\t\t});\n\t}", "function setDefaults(definition){providerConfig.optionsFactory=definition.options;providerConfig.methods=(definition.methods||[]).concat(EXPOSED_METHODS);return provider;}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if filename ends with '.zip'
function isZip(filename) { // last 4 characters in filename let ss = filename.slice(filename.length-4, filename.length); return ss === '.zip'; }
[ "function isZipFile(file) {\n\treturn file.name.endsWith(\".zip\") || file.type === 'application/zip';\n}", "function checkIfZip(name) {\n var ok=false;\n try {\n var regexp=/^.*\\.([^\\.]*)$/m;\n var x=name.match(regexp);\n var ext=x[1].toLowerCase();\n ok = ext==\"zip\";\n }\n catch(e){}\n if(!ok)\n alert(\"Now is a good time to read the documentation and to find out what files can be uploaded!\");\n return ok;\n}", "function hasExtension(fileName, extensionList) {\n for (let extension of extensionList) {\n if (endsWith(fileName, extension)) {\n return true\n }\n }\n return false\n}", "function isZipFile(req, res, callback) {\n if (!file.originalname.match(/\\.zip$/))\n return callback(\n new Error(\"File uploaded is not in the zip format.\"),\n false\n );\n\n return callback(null, true);\n}", "function checkNewExt(filename, oldExtLen, newExt) {\n return newExt.length > oldExtLen && filename.endsWith(newExt);\n}", "function hasFileExt(url) {\n var filename = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('?'));\n return filename.lastIndexOf('.') >= 0;\n}", "function hasFileExt(url)\n{\n var filename = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('?'));\n return filename.lastIndexOf('.') >= 0;\n}", "function filenameCheck(string) {\n return /\\.([A-Za-z0-9]{3})$/.test(string.slice(-4));\n}", "function checkZip(filename)\n{\n var obj = new ActiveXObject(\"Ionic.Zip.ComHelper\");\n return obj.IsZipFile(filename);\n}", "function needsExt(pathname) {\n const lastSegment = pathname.substring(pathname.lastIndexOf('/'))\n return (lastSegment.indexOf('.') === -1)\n}", "function isJournalFile(filename) {\n return re.test(filename);\n}", "function checkFileExt(filename){\n var splitname = filename.split(\".\");\n var ext = splitname[splitname.length-1].toLowerCase();\n var allowtypes = [\"jpg\", \"png\", \"gif\", \"bmp\"]\n if(allowtypes.includes(ext)){\n return true;\n }\n return false;\n\n}", "hasExtension(fileName) {\n return (new RegExp('(' + appConstants.actionPicture.extensions.join('|').replace(/\\./ig, '\\\\.') + ')$')).test(fileName) ||\n (new RegExp('(' + appConstants.actionPicture.extensions.join('|').replace(/\\./ig, '\\\\.') + ')$')).test(fileName.toLowerCase());\n }", "function isMetaFile(name){\n\treturn name.endsWith(\"-meta.xml\");\n}", "function fileIsDirectory(filename) {\n\treturn getFileExtension(filename) == null;\n}", "function extension (expectedExtension, filename) {\n\t verify(low.unemptyString(expectedExtension), 'missing expected extension', expectedExtension);\n\t verify(low.unemptyString(filename), 'missing filename', filename);\n\t var reg = new RegExp('.' + expectedExtension + '$');\n\t return reg.test(filename)\n\t}", "function isDotFile(fileName) {\n var parts = fileName.split(\".\");\n if (parts.length < 1) {\n return false;\n }\n\n if (parts[parts.length - 1] === \"dot\") {\n return true;\n }\n\n return false;\n}", "function validateFile(name){\n let validExtensions = [\"mp3\"]; // valid extensions\n let extension = name.substring(name.lastIndexOf(\".\")+1).toLowerCase();\n return validExtensions.includes(extension);\n}", "function isExtensionValid(filename) {\n var valid = false;\n\n extensions.forEach(function(extension) {\n if(Path.extname(filename) === extension) valid = true;\n });\n\n return valid;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method changes the Threshold button (% > abs > % ...)
function changeBtnThresholType() { $('#btn-threshold-type').off().on('click', function() { if($(this).val() === 'percentage') { $(this).val("absolute"); $(this).text("abs") } else { $(this).val("percentage"); $(this).text("%") } }); }
[ "function setThresholdBar() {\n var slider = document.getElementById(\"myRange\");\n var output = document.getElementById(\"demo\");\n output.innerHTML = slider.value;\n drawThresholdLine();\n\n slider.oninput = function() {\n output.innerHTML = this.value;\n minionObject.threshold_limit=this.value;\n drawThresholdLine();\n //check if the value did not cross the set threshold\n checkpost();\n }\n }", "updateToxicityRange() {\n this.setToxicityThreshold_(this.toxicityRangeElement.value);\n this.toxicityThresholdElement_.textContent =\n `${(this.toxicityThreshold * 100).toFixed(2)}%`;\n }", "function updateThreshold(n,i,val){\n\tsensors[n].triggers[i].level = val;\n\tdocument.getElementById('tThresh' + n + \"_\" + i).value = val;\n\tdocument.getElementById('thresh' + n + \"_\" + i).value = val;\n}", "changeSensitivity(gamepad) {\n if (this.sensitivity < 1 && gamepad.buttons[12].pressed) {\n this.sensitivity = parseFloat((this.sensitivity += 0.01).toFixed(2));\n }\n if (this.sensitivity > 0.1 && gamepad.buttons[13].pressed) {\n this.sensitivity = parseFloat((this.sensitivity -= 0.01).toFixed(2));\n }\n }", "function changeThreshold() {\n threshold = map(mouseX, 0, width, 0, 175);\n print(\"Threshold is now: \" + threshold);\n}", "function adjustValue(value, threshold) {\n if (value < threshold) {\n return 255 - value;\n }\n else {\n return value;\n }\n}", "decreaseThres() {\n let newThres = this.state.threshold - 5;\n this.setState({threshold : newThres});\n }", "showPixelsOnTopOfLowerTreshold(canvasObject, t1, n) {\n if (canvasObject.domPixelsOnTopOfLowerTreshold != null) {\n canvasObject.domPixelsOnTopOfLowerTreshold.innerHTML = `Jumlah pixel pada ${canvasObject.stringTitle.toLowerCase()} dengan nilai pixel >= lower treshold (${t1}) adalah : ${n} pixel`;\n }\n }", "_setValuePercent() {\n const dif = ((this.value - this.min) / (this.max - this.min)) * 100;\n this.el.style.setProperty('--valuePercent', `${dif}%`);\n }", "function updateThreshold(event) {\n let newThreshold\n\n expressionThreshold = parseInt(event.target.value)\n\n adjustedExpressionThreshold = Math.round(expressionThreshold/10 - 4)\n const thresholds = window.originalHeatmapThresholds\n const numThresholds = thresholds.length\n ideoConfig.heatmapThresholds = []\n\n // If expressionThreshold > 1,\n // increase thresholds above middle, decrease below\n // If expressionThreshold < 1,\n // decrease thresholds above middle, increase below\n for (let i = 0; i < numThresholds; i++) {\n if (i + 1 > numThresholds/2) {\n newThreshold = thresholds[i + adjustedExpressionThreshold]\n } else {\n newThreshold = thresholds[i - adjustedExpressionThreshold]\n }\n ideoConfig.heatmapThresholds.push(newThreshold)\n }\n inferCNVIdeogram = new Ideogram(ideoConfig)\n}", "function levelChange() {\n if (mediumSpeed) {\n $(\"#level-change-button\").text(\"Medium Style\");\n intervalTime = 70;\n mediumSpeed = false;\n } else {\n $(\"#level-change-button\").text(\"Hard Style\");\n intervalTime = 140;\n mediumSpeed = true;\n }\n}", "function tipPercentButtonsWithoutRounding(buttonPercent) {\n // Set percent to the button's value\n document.getElementById('tipPercent').value = buttonPercent;\n // Calculate\n calculationsWithoutRounding();\n}", "adjust(delta) {\n let brightness = this.brightness + delta;\n brightness = Math.min(Math.max(brightness, 0), 1);\n this.brightness = brightness;\n }", "function updateAmplitudeThresholdingLabel () {\n\n const amplitudeThreshold = convertAmplitudeThreshold(amplitudeThresholdingSlider.getValue() / amplitudeThresholdingSlider.getAttribute('max'));\n\n amplitudeThresholdingLabel.textContent = 'Amplitude threshold of ';\n\n switch (amplitudeThresholdingScaleIndex) {\n\n case AMPLITUDE_THRESHOLD_SCALE_PERCENTAGE:\n\n amplitudeThresholdingLabel.textContent += amplitudeThreshold.percentage + '%';\n break;\n\n case AMPLITUDE_THRESHOLD_SCALE_16BIT:\n\n amplitudeThresholdingLabel.textContent += amplitudeThreshold.amplitude;\n break;\n\n case AMPLITUDE_THRESHOLD_SCALE_DECIBEL:\n\n amplitudeThresholdingLabel.textContent += amplitudeThreshold.decibels + ' dB';\n break;\n\n }\n\n amplitudeThresholdingLabel.textContent += ' will be used when generating T.WAV files.';\n\n}", "function changeBrightness(id_val, id_img) {\n var val = $(id_val).text();\n\n var brightness;\n if (val === 0){\n brightness = 17;\n }\n if (val < 11) {\n brightness = 25;\n }\n else if (val > 10 && val < 30) {\n brightness = 30;\n }\n else {\n brightness = val;\n }\n\n var brightness_img = 'brightness(' + brightness + '%)';\n $(id_img).css({\n 'filter' : brightness_img,\n '-webkit-filter' : brightness_img,\n '-moz-filter' : brightness_img,\n '-o-filter' : brightness_img,\n '-ms-filter' : brightness_img,\n });\n}", "function showThresholds() {\n // setup logging menu\n var menu;\n var thresholdsMenu = {\n \"\": {\n title: /*LANG*/\"Thresholds\"\n },\n /*LANG*/\"< Back\": () => showMain(2),\n /*LANG*/\"Max Awake\": {\n value: settings.maxAwake / 6E4,\n step: 10,\n min: 10,\n max: 120,\n wrap: true,\n noList: true,\n format: v => v + /*LANG*/\"min\",\n onchange: v => {\n settings.maxAwake = v * 6E4;\n writeSetting();\n }\n },\n /*LANG*/\"Min Consecutive\": {\n value: settings.minConsec / 6E4,\n step: 10,\n min: 10,\n max: 120,\n wrap: true,\n noList: true,\n format: v => v + /*LANG*/\"min\",\n onchange: v => {\n settings.minConsec = v * 6E4;\n writeSetting();\n }\n },\n /*LANG*/\"Deep Sleep\": {\n value: settings.deepTh,\n step: 1,\n min: 30,\n max: 200,\n wrap: true,\n noList: true,\n onchange: v => {\n settings.deepTh = v;\n writeSetting();\n }\n },\n /*LANG*/\"Light Sleep\": {\n value: settings.lightTh,\n step: 10,\n min: 100,\n max: 400,\n wrap: true,\n noList: true,\n onchange: v => {\n settings.lightTh = v;\n writeSetting();\n }\n },\n /*LANG*/\"Reset to Default\": () => {\n settings.maxAwake = defaults.maxAwake;\n settings.minConsec = defaults.minConsec;\n settings.deepTh = defaults.deepTh;\n settings.lightTh = defaults.lightTh;\n writeSetting();\n showThresholds();\n }\n };\n\n // display info/warning prompt or menu\n if (thresholdsPrompt) {\n thresholdsPrompt = false;\n E.showPrompt(\"Changes take effect from now on, not retrospective\", {\n title: /*LANG*/\"Thresholds\",\n buttons: {\n /*LANG*/\"Ok\": 0\n }\n }).then(() => menu = E.showMenu(thresholdsMenu));\n } else {\n menu = E.showMenu(thresholdsMenu);\n }\n }", "function tipPercentButtonsWithRounding(buttonPercent) {\n // Set percent to the button's value\n document.getElementById('tipPercent').value = buttonPercent;\n // Run calculations with rounding.\n calculatePercentWithRounding();\n}", "function percButton() {\n setOperation(percentButton.textContent);\n screen.textContent = operate(currentOperation, firstOperand)\n shouldResetScreen = false;\n currentOperation = null;\n}", "function changeOpacity(bool) {\n const step = .2, min = 0, max = 1;\n let current = heatmap.get('opacity');\n let newValue = toggleUpDown(bool, current, step, min, max);\n let rounded = round(newValue, 1);\n\n heatmap.set('opacity', rounded);\n document.getElementById(\"opacityNum\").innerText = rounded;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find NPCs by ID
function npcById (id) { for (var i = 0; i < npcs.length; i++) { if (npcs[i].id === id) { return npcs[i]; } } return undefined; }
[ "function findplayerbyid (id) {\n\tfor (var i = 0; i < enemies.length; i++) {\n\t\tif (enemies[i].player.name == id) {\n\t\t\treturn enemies[i]; \n\t\t}\n\t}\n}", "function npcInRoom (id) {\n var roomNPCs = [];\n for (var i = 0; i < npcs.length; i++) {\n if (npcs[i].roomid === id) {\n roomNPCs.push(npcs[i]);\n }\n }\n\n return roomNPCs;\n\n}", "function getPokemonById(id) {\n return pokemonData.find(function(pokemon) {\n return pokemon.id == id;\n });\n}", "function findPlayerById(id) {\n for (let i = 0; i < players.length; i++) {\n if (players[i].id == id) {\n return players[i];\n }\n }\n return null;\n}", "function playerById(id) {\n\tvar i;\n\tfor (i = 0; i < remotePlayers.length; i++) {\n\t\tif (remotePlayers[i].get(\"id\") == id)\n\t\t\treturn remotePlayers[i];\n\t}\n\t\n\treturn false;\n}", "function playerById(id) {\n\tvar i;\n\tfor (i = 0; i < remotePlayers.length; i++) {\n\t\tif (remotePlayers[i].id == id)\n\t\t\treturn remotePlayers[i];\n\t}\n\n return false;\n}", "function findMember(id) {\n for (var j = 0; j < teams.length; j++) {\n team = teams[j];\n for (var i = 0; i < team.members.length; i++) {\n if (team.members[i].id == id) {\n return team.members[i];\n } else {\n // console.log(\"no such member!\" + name);\n }\n }\n }\n }", "function findActor(id)\n{\n var index;\n for (index in actors) {\n if (actors[index].id == id) {\n return actors[index];\n }\n }\n}", "function playerById(id) {\r\n\tvar i;\r\n\tfor (i = 0; i < players.length; i++) {\r\n\t\tif (players[i].getID() == id)\r\n\t\t\treturn players[i];\r\n\t};\r\n\t\r\n\treturn false;\r\n}", "function zombieById(id){\n\tvar i = 0;\n\tvar notFound = true;\n\twhile(notFound && i < window.enemies.length){\n\t\tif(enemies[i].getid() == id){\n\t\t\treturn enemies[i];\n\t\t};\n\n\t\ti++;\n\t};\n\t//returns false if the zombie isn't found \n\treturn false;\n}", "findNode(id) {\n for (let node of this.nodes) {\n if (node.getID() == id) {\n return node;\n }\n }\n }", "find(id) {\n this.refresh();\n if(id) {\n return this.naclList.find(element => {\n return element.id === id;\n }); \n }else {\n return this.naclList;\n }\n }", "static findByID(id) {\n return rooms.get(id);\n }", "static find(id) {\n\t\tlet promiseFind = new Parse.Promise();\n\n\t\tlet query = new Parse.Query(Mentor);\n\t\tquery.get(id).then(function(mentor) {\n\t\t\tpromiseFind.resolve(mentor);\n\t\t}, function(err) {\n\t\t\tpromiseFind.reject(err);\n\t\t});\n\n\t\treturn promiseFind;\n\t}", "function getPlayer(id) {\n for (let player of players) {\n if (player.id == id) {\n return player;\n }\n }\n\n return null;\n}", "function playerByObjectId(id) {\n\tvar i;\n\tfor (i = 0; i < remotePlayers.length; i++) {\n\t\tif (remotePlayers[i].objectId == id)\n\t\t\treturn remotePlayers[i];\n\t};\n\t\n\treturn false;\n}", "getAlivePlayers(id) {\n return this.getRoom(id).players.filter((player) => player.alive === true);\n }", "function findNPC(name) {\n\tfor (var i = 0; i < npcArray.length; i++) {\n\t\tif (name.text == npcArray[i].name + \" the \" + npcArray[i].occupation) {\n\t\t\treturn npcArray[i];\n\t\t}\n\t}\n}", "function actions_find(id) {\n for(var i=0; i<actions.length; i++) {\n if(actions[i].id == id || actions[i].name == id) {\n return actions[i];\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert func to PackedFunc
toPackedFunc(func) { if (this.isPackedFunc(func)) return func; return this.createPackedFuncFromCFunc(this.wrapJSFuncAsPackedCFunc(func)); }
[ "toPackedFunc(func) {\n\t if (this.isPackedFunc(func))\n\t return func;\n\t return this.createPackedFuncFromCFunc(this.wrapJSFuncAsPackedCFunc(func));\n\t }", "isPackedFunc(func) {\n\t // eslint-disable-next-line no-prototype-builtins\n\t return typeof func == \"function\" && func.hasOwnProperty(\"_tvmPackedCell\");\n\t }", "isPackedFunc(func) {\n // eslint-disable-next-line no-prototype-builtins\n return typeof func == \"function\" && func.hasOwnProperty(\"_tvmPackedCell\");\n }", "function toFunc(fun) {\n if (isPseudoFunc(fun)) {\n return markFuncFreeze(function applier(var_args) {\n return callPub(fun, 'apply', [USELESS, Array.slice(arguments, 0)]);\n });\n }\n return asFunc(fun);\n }", "async pack (value) {\n if (typeof value === 'function') {\n return {\n type: 'function',\n data: value._spec || {name: value.name},\n location: this.location\n }\n } else {\n return super.pack(value)\n }\n }", "function transform_function(func) {\n if (ends_with_underscore(func.name)) {\n function_vars = {}\n idents.push_callback()\n func.name = strip_underscore(func.name)\n func.params.push(idents.callback.value)\n func.body.children.push({\n type: RETURN,\n implicit: true,\n })\n func.body.children = transform_statements(func.body.children)\n idents.pop_callback()\n }\n}", "function wrapRenderPlaceFunction(\n func\n) {\n if (typeof func === 'string') {\n return () => func;\n }\n return func;\n}", "function expand(f) {\n\t\t// check for some meta-data on the function to see if it's a normal function\n\t\t// or a composer chain\n\t\tif(f.__IS_COMPOSER__) { return f() }\n\t\treturn f;\n\t}", "function wrap(func, wrapper) {\n return modules_partial(wrapper, func);\n}", "function serializeFunction(func, args) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!args) {\n args = {};\n }\n const exportName = args.exportName || \"handler\";\n const serialize = args.serialize || (_ => true);\n const isFactoryFunction = args.isFactoryFunction === undefined ? false : args.isFactoryFunction;\n const functionInfo = yield closure.createFunctionInfoAsync(func, serialize);\n return serializeJavaScriptText(functionInfo, exportName, isFactoryFunction);\n });\n}", "function toEs6(func) {\n let str = func.toString();\n let index = str.indexOf('(');\n let rstr = slicestring(str, index)[1];\n index = rstr.indexOf(')');\n let funcarr = slicestring(rstr, index - 1);\n let args = funcarr[0];\n index = funcarr[1].indexOf(')');\n let content = slicestring(funcarr[1], index)[1];\n let funcstr = '(' + args + ')=>' + content;\n let minfuncstr = minify(funcstr);\n return minfuncstr;\n}", "function applyf(binFunc) {\n // return binFunc;\n return function(x) {\n return function(y) {\n return binFunc(x, y);\n }\n }\n} // dang", "function toFn(f) {\r\n\treturn isFn(f) ? f : undefined;\r\n}", "function convertSubscribe(fn) {\n return function subscribe(operation, variables, cacheConfig) {\n return __webpack_require__(89).fromLegacy(function (observer) {\n return fn(operation, variables, cacheConfig, observer);\n }).map(function (value) {\n return convertToExecutePayload(operation, variables, value);\n });\n };\n}", "function stack_fun(fun){\n return function(arg_stack){\n arg_stack.unshift.apply(arg_stack, to_array_box(fun.apply(this, arg_stack.splice(0, fun.length))).reverse());\n }\n }", "function convertSubscribe(fn) {\n return function subscribe(operation, variables, cacheConfig) {\n return __webpack_require__(111).fromLegacy(function (observer) {\n return fn(operation, variables, cacheConfig, observer);\n }).map(function (value) {\n return convertToExecutePayload(operation, variables, value);\n });\n };\n}", "function compose(funcA, funcB) {\n return function \n}", "function liftf(fn){\n return function buffalo(x){ // arrow funcs are anonymous funcs\n return function wings(y){\n return fn(x,y)\n }\n }\n}", "function Pack(){}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect the voice connection.
connect() { if (this.status !== Constants.VoiceStatus.RECONNECTING) { if (this.sockets.ws) throw new Error('There is already an existing WebSocket connection.'); if (this.sockets.udp) throw new Error('There is already an existing UDP connection.'); } if (this.sockets.ws) this.sockets.ws.shutdown(); if (this.sockets.udp) this.sockets.udp.shutdown(); this.sockets.ws = new VoiceWebSocket(this); this.sockets.udp = new VoiceUDP(this); const { ws, udp } = this.sockets; ws.on('error', err => this.emit('error', err)); udp.on('error', err => this.emit('error', err)); ws.on('ready', this.onReady.bind(this)); ws.on('sessionDescription', this.onSessionDescription.bind(this)); ws.on('startSpeaking', this.onStartSpeaking.bind(this)); }
[ "connect() {\n this.emit('debug', `Connect triggered`);\n if (this.status !== VoiceStatus.RECONNECTING) {\n if (this.sockets.ws) throw new Error('WS_CONNECTION_EXISTS');\n if (this.sockets.udp) throw new Error('UDP_CONNECTION_EXISTS');\n }\n\n if (this.sockets.ws) this.sockets.ws.shutdown();\n if (this.sockets.udp) this.sockets.udp.shutdown();\n\n this.sockets.ws = new VoiceWebSocket(this);\n this.sockets.udp = new VoiceUDP(this);\n\n const { ws, udp } = this.sockets;\n\n ws.on('debug', msg => this.emit('debug', msg));\n udp.on('debug', msg => this.emit('debug', msg));\n ws.on('error', err => this.emit('error', err));\n udp.on('error', err => this.emit('error', err));\n ws.on('ready', this.onReady.bind(this));\n ws.on('sessionDescription', this.onSessionDescription.bind(this));\n ws.on('startSpeaking', this.onStartSpeaking.bind(this));\n\n this.sockets.ws.connect();\n }", "connect() {\n if (!this.voiceChannel)\n throw new RangeError(\"No voice channel has been set.\");\n this.state = \"CONNECTING\";\n this.manager.options.send(this.guild, {\n op: 4,\n d: {\n guild_id: this.guild,\n channel_id: this.voiceChannel,\n self_mute: this.options.selfMute || false,\n self_deaf: this.options.selfDeafen || false,\n },\n });\n this.state = \"CONNECTED\";\n return this;\n }", "connect() {\n if (this.status !== Constants.VoiceStatus.RECONNECTING) {\n if (this.sockets.ws) throw new Error('There is already an existing WebSocket connection.');\n if (this.sockets.udp) throw new Error('There is already an existing UDP connection.');\n }\n\n if (this.sockets.ws) this.sockets.ws.shutdown();\n if (this.sockets.udp) this.sockets.udp.shutdown();\n\n this.sockets.ws = new VoiceWebSocket(this);\n this.sockets.udp = new VoiceUDP(this);\n\n const { ws, udp } = this.sockets;\n\n ws.on('error', err => this.emit('error', err));\n udp.on('error', err => this.emit('error', err));\n ws.on('ready', this.onReady.bind(this));\n ws.on('sessionDescription', this.onSessionDescription.bind(this));\n ws.on('speaking', this.onSpeaking.bind(this));\n }", "connect() {\n if (this.dead) return;\n if (this.ws) this.reset();\n if (this.attempts >= 5) {\n this.emit('debug', new Error(`Too many connection attempts (${this.attempts}).`));\n return;\n }\n\n this.attempts++;\n\n /**\n * The actual WebSocket used to connect to the Voice WebSocket Server.\n * @type {WebSocket}\n */\n this.ws = new WebSocket(`wss://${this.voiceConnection.authentication.endpoint}`);\n this.ws.onopen = this.onOpen.bind(this);\n this.ws.onmessage = this.onMessage.bind(this);\n this.ws.onclose = this.onClose.bind(this);\n this.ws.onerror = this.onError.bind(this);\n }", "async function connect() {\n try {\n const connection = await client.channels.cache.get(config.voiceChannelID).join();\n listen(connection);\n } catch (err) {\n console.log(err);\n }\n}", "async function connect(message){\n\n //Store the voice channel of the user as a variable, so we can pass it to bot2 later.\n var voiceC = message.member.voiceChannel;\n\n //Check if the user is in a voice channel\n if(!message.member.voiceChannel)\n {\n message.reply(\"You need to join a voice channel\");\n }\n else{\n //Join the voice channel of the user\n voiceC.join().then(async connection =>\n {\n\n console.log(\"Connected\")\n\n //This creates the receiver that will grab the user's voice data\n const receiver = connection.createReceiver();\n \n //Grab the user's voice data and create the Opus stream.\n const stream = receiver.createOpusStream(message.member.user)\n\n //Instantate bot2 and pass the stream and the voice channel as parameters\n const speakerbot = new bot2(stream, voiceC)\n console.log(\"bot2 initialized\")\n\n }).catch(console.error)\n }\n}", "onConnect() {\n this.logger('CONNECTED');\n // this.rtcSend({ type: 'text', data: 'From Web' });\n this.uiCommunicator('RtcConnectedEvent');\n this.socketEmit(this.signals.rtcConnected, this.connId);\n this.tryTurn = false;\n this.socketDisconnect();\n }", "connect() {\n\t\tthis._communicator.connect();\n\t}", "function connect() {\n\t\t\n\t\t_client.connect();\n\t\t\n\t}", "authenticate() {\n this.sendVoiceStateUpdate();\n this.connectTimeout = this.client.setTimeout(() => this.authenticateFailed('VOICE_CONNECTION_TIMEOUT'), 15000);\n }", "function connect() {\n\t\t\tlog(\"Establishing connection...\");\n\t\t\tvoxAPI.connect();\n\t\t}", "connect() {\n if (this.pc != null) return;\n\n ICE.getServers(iceServers => {\n let pc = new RTCPeerConnection({iceServers}, {\n optional: [\n {DtlsSrtpKeyAgreement: true}\n ]\n });\n pc.onicecandidate = this._handleIceCandidate.bind(this);\n pc.onnegotiationneeded = this._handleNegotiationNeeded.bind(this);\n pc.oniceconnectionstatechange = this._handleIceConnectionStateChange.bind(this);\n pc.onsignalingstatechange = this._handleSignalingStateChange.bind(this);\n pc.onaddstream = this._handleAddStream.bind(this);\n pc.onremovestream = this._handleRemoveStream.bind(this);\n this.pc = pc;\n if (this.stream) {\n pc.addStream(this.stream);\n }\n this._createLocalOffer((mode, streams) => {\n // Store this so when the remote SDP arrives the variables when it was\n // created are used to generate the remote description args.\n this._answerRemoteDescriptionArgs = ['answer', mode, streams];\n });\n this._iceGatheringTimeout = setTimeout(this._handleIceGatheringTimeout.bind(this), 5000);\n });\n }", "function connect() {\n log(\"Establishing connection...\");\n voxAPI.connect();\n if (mode == 'webrtc' && voxAPI.isRTCsupported()) {\n dialog = new BootstrapDialog({\n title: 'Camera/Microphone access',\n message: 'Please click Allow to allow access to your camera and microphone',\n closable: false \n });\n dialog.open(); \n }\n}", "static openConnection(options={},callback){return TcHmi.System.Services.tcSpeechManager.openConnection(options,callback)}", "function connectAudioServer() {\n socket = new WebSocket(AUDIO_ENDPOINT);\n socket.onopen = socketConnected;\n socket.onerror = socketError;\n socket.onmessage = socketMessage;\n }", "async connect() {\n await this._mav.connect();\n await this._startTelemetry();\n\n this._cxnState = ConnectionState.IDLE;\n }", "openConnection() {\n this.privServiceRecognizer.connect();\n }", "Connect(Variant, Variant, Variant, Variant) {\n\n }", "function connect() {\n\n\t\tconst presentationURL = deck.getConfig().url;\n\n\t\tconst url = typeof presentationURL === 'string' ? presentationURL :\n\t\t\t\t\t\t\t\twindow.location.protocol + '//' + window.location.host + window.location.pathname + window.location.search;\n\n\t\t// Keep trying to connect until we get a 'connected' message back\n\t\tconnectInterval = setInterval( function() {\n\t\t\tspeakerWindow.postMessage( JSON.stringify( {\n\t\t\t\tnamespace: 'reveal-notes',\n\t\t\t\ttype: 'connect',\n\t\t\t\tstate: deck.getState(),\n\t\t\t\turl\n\t\t\t} ), '*' );\n\t\t}, 500 );\n\n\t\twindow.addEventListener( 'message', onPostMessage );\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialization that runs on popup startup defers session validation to async while popup loads to give general case user quicker startup
function popupInit() { popupLoadPrefs(function () { loadData(function (data) { if (data === "No Data") { console.log("No data to display."); } else { buildPopup(data); } popupHookListeners(); popupValidateSession(data); }); }); return; }
[ "function popupInit() {\n\tpopupLoadPrefs(function () {\n\t\tloadData(function (data) {\n\n\t\t\tif (data === \"No Data\") {\n\t\t\t\tconsole.log(\"No data to display.\");\n\n\t\t\t} else {\n\t\t\t\tbuildPopup(data);\n\t\t\t}\n\t\t\thookListeners();\n\t\t\tvalidateSession(data);\n\t\t});\n\t});\n\t\n\treturn;\n}", "function setupInit() {\n document.getElementsByTagName( 'body' )[0].innerHTML = internationalize( document.getElementsByTagName( 'body' )[0].innerHTML );\n\n var theForm = document.getElementById( 'optionForm' ),\n user = document.getElementById( 'username' ),\n pass = document.getElementById( 'password' ),\n auth;\n\n user.value = storage( 'username' ) || \"\";\n pass.value = storage( 'password' ) || \"\";\n\n theForm.addEventListener( 'submit', function ( e ) {\n storage( 'username', user.value );\n storage( 'password', pass.value );\n isAuthenticated( {\n 'force': true,\n 'isAuthed': function () {\n notify( {\n 'el': theForm,\n 'msg': chrome.i18n.getMessage( 'successfulAuth' ),\n 'type': \"success\",\n 'callback': function () { window.close(); }\n } );\n clearPopup();\n },\n 'notAuthed': function () {\n notify( {\n 'el': theForm,\n 'msg': chrome.i18n.getMessage( 'failedAuth' ),\n 'type': \"failure\"\n } );\n setPopup();\n },\n 'error': function () {\n notify( {\n 'el': theForm,\n 'msg': chrome.i18n.getMessage( 'errorAuth' ),\n 'type': \"failure\"\n } );\n setPopup();\n }\n } );\n e.preventDefault(); e.stopPropagation();\n return false;\n } );\n }", "function popupValidateSession(data) {\n\tsessionIsValid(function (valid_session) {\n\t\tif (valid_session && data !== \"No Data\") {\n\t\t\t// session is fine, popup is probably already loaded\n\t\t} else {\n\t\t\tpopupHandleInvalidSession(data);\n\t\t}\n\t});\n}", "function initSignInPopup() {\n \n $(document).ready(function() {\n \n $('#signin-popup').popup({\n transition: 'all 0.3s'\n });\n \n });\n}", "function init(){\n if(window.vivaldiWindowId){\n chrome.windows.getCurrent(window => {\n if(!window.incognito){\n chrome.storage.local.set({\n \"LONM_SESSION_AUTOSAVE_LAST_WINDOW\": window.vivaldiWindowId\n }, () => {\n setInterval(triggerAutosave, CURRENT_SETTINGS[\"LONM_SESSION_AUTOSAVE_DELAY_MINUTES\"]*60*1000);\n });\n }\n if(CURRENT_SETTINGS[\"LONM_SESSION_SAVE_PRIVATE_WINDOWS\"] && window.incognito){\n chrome.storage.local.set({\n \"LONM_SESSION_AUTOSAVE_LAST_PRIV_WINDOW\": window.vivaldiWindowId\n }, () => {\n setInterval(triggerAutosavePrivate, CURRENT_SETTINGS[\"LONM_SESSION_AUTOSAVE_DELAY_MINUTES\"]*60*1000);\n });\n }\n chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {\n if (changeInfo.url === SETTINGSPAGE) {\n modSettingsPage();\n }\n })\n });\n } else {\n setTimeout(init, 500);\n }\n }", "function initSessionRoutine() {\n // since user has successfully logged in hide login modal and\n // show logout button, also hide login and signup buttons\n console.log(\"in initSession Routine()\");\n $(\"#at-login\").modal(\"hide\");\n $(\".session-logout\").show();\n $(\"#modalLogin\").hide();\n $(\"#modalSignup\").hide();\n\n }", "function InitializeStaticSessionContent() {\n\n GetStepsList();\n GetSettings();\n PopulateStepToStartList();\n //PopulateVoiceList();\n\n }", "function initPage() {\n // var lockedOutTime = localStorage.getItem() \n // here we'll get our locked out time from local storage and decide if we're still locked out or not\n let lockedOutStatus = getLockedOutStatus();\n //console.log (lockedOutStatus);\n if (lockedOutStatus) {\n atrributedSites();\n $('#badRequestPopup').show();\n return;\n }\n atrributedSites();\n }", "init() {\n const authenticators = this.getAuthenticators();\n // perform this check first, if we're autologging in we don't render a dom\n setTimeout(() => {\n if (!!authenticators.autoLoginAuthenticator) {\n this.isAutologin = true;\n this.loginUser(authenticators.autoLoginAuthenticator);\n this.activeAuthenticator = authenticators.autoLoginAuthenticator;\n }\n else {\n // check for existing session and resume if possible\n this.attemptSessionLogin(authenticators.availableAuthenticators);\n if (!this.renderConfig) {\n throw new Error(\"Render Configuration is required when no auto login authenticator is provided\");\n }\n const { containerElement, buttonStyleOverride = false } = this\n .renderConfig;\n this.dom = new UALJsDom_1.UALJsDom(this.loginUser, authenticators.availableAuthenticators, containerElement, buttonStyleOverride);\n this.dom.generateUIDom();\n }\n }, 500);\n }", "function initKeepSession() {\n const cdt = $(\"#hfCountDownTime\");\n let timeout = 120;\n if (cdt.size() > 0) {\n const cdto = parseInt(cdt.val(), 10);\n if (cdto > 60) {\n timeout = cdto;\n }\n }\n const keepAlive = function () {\n window.setTimeout(() => {\n const pages = [\"inbox\", \"0303\", \"0401\", \"0203\", \"0206\"];\n const page = pages[Math.floor(Math.random() * pages.length)];\n $.ajax({\n url: `main.aspx?ismenuclick=true&ctrl=${page}`,\n });\n keepAlive();\n }, timeout * 1000 - 30000 - Math.floor(Math.random() * 30000));\n };\n keepAlive();\n\n window.setInterval(() => {\n utils.runEval(() => {\n window.ShowModal = function () {};\n clearTimeout(window.timerID);\n clearTimeout(window.timerID2);\n window.sessionEndDate = null;\n });\n if ($(\"#npuStatus\").size() === 0) {\n $(\"#upTraining_lblRemainingTime\").html(\n `<span id=\"npuStatus\" style=\"font-weight: normal\">` +\n `<a href=\"https://github.com/solymosi/npu\" target=\"_blank\">Neptun PowerUp!</a> ` +\n `v${GM.info.script.version}` +\n `</span>`\n );\n }\n }, 1000);\n}", "intitialize() {\n new Promise((res, rej) => {\n // get currentTab to set message tabId --> sender in background message listener doesn't contain tab.id from popup scripts\n chrome.tabs.query({ active: true, currentWindow: true }, res);\n }).then((tabs) => {\n this.tabId = tabs[0].id\n return new Promise((res, rej) => {\n this.sendMessage({ type: \"getPopupState\", tabId: this.tabId }, (response) => {\n this.showState(response);\n res();\n })\n })\n }).then(() => {\n this.forcePluginCheckboxElement.addEventListener(\"change\", () => {\n this.sendMessage({\n type: \"setPopupState\",\n tabId: this.tabId,\n message: {\n forcePlugin: this.forcePluginCheckboxElement.checked\n }\n },\n () => {\n });\n });\n })\n }", "async init() {\n\t\t// Open the Starbucks app sign in page\n\t\tawait this.driver.get('https://app.starbucks.com/account/signin')\n\t\t// Block this aync thread/wait for user to sign in\n\t\t// await this.driver.wait(until.elementLocated(By.xpath('//*[@id=\"content\"]/div[2]/div/div/div/div/div[1]/div/div/div[3]/span/a')))\n\t}", "function checkPopup() { \n if (loginPopupWindow !== null && loginPopupWindow.closed) {\n new Ajax.WLRequest(REQ_PATH_GET_USER_INFO, { \n onSuccess : onGetUserInfoSuccess,\n onFailure : onGetUserInfoFailure,\n timeout : getAppProp(WL.AppProp.WLCLIENT_TIMEOUT_IN_MILLIS)\n }); \n }\n }", "_ready() {\n this.__menubarIcon(this.app.state.ui.menubar.base)\n if (this.app.env.isExtension) {\n this.app.setState({ui: {visible: false}})\n // A connection between the popup script and the background\n // is made. A new connection means the popup just opened, while\n // a closing connecting means that the popup closed.\n browser.runtime.onConnect.addListener((port) => {\n this.app.setState({ui: {visible: true}})\n for (let moduleName of Object.keys(this.app.plugins)) {\n if (this.app.plugins[moduleName]._onPopupAction) {\n this.app.plugins[moduleName]._onPopupAction('open')\n }\n }\n\n // Triggered when the popup closes.\n port.onDisconnect.addListener((msg) => {\n // Remove any overlay when the popup closes.\n this.app.setState({ui: {overlay: null, visible: false}})\n for (let moduleName of Object.keys(this.app.plugins)) {\n if (this.app.plugins[moduleName]._onPopupAction) {\n this.app.plugins[moduleName]._onPopupAction('close')\n }\n }\n })\n })\n } else {\n // There is no concept of a popup without an extension.\n // However, the event tis still triggered to start timers\n // and such that rely on the event.\n this.app.setState({ui: {visible: true}})\n for (let moduleName of Object.keys(this.app.plugins)) {\n if (this.app.plugins[moduleName]._onPopupAction) {\n this.app.plugins[moduleName]._onPopupAction('open')\n }\n }\n }\n }", "function init(callback){\n\tchrome.storage.local.get('SessionListKey', function(result){\t\n\t\tconsole.log(\"-------INIT-------\");\n\t\tconsole.log(result);\n\t\tif(result.SessionListKey === undefined){\n\t\t\tconsole.log(\"-------INIT--undefined-------\");\n\t\t\tvar sessionList = new SessionList();\n\t\t\tconsole.log(sessionList);\n\t\t\tchrome.storage.local.set({'SessionListKey':sessionList},function(){\n\t\t\t\tconsole.log(\"-------INIT--SET-------\");\n\t\t\t\tconsole.log(sessionList);\n\t\t\t\ttoggleIcon(function(){\n\t\t\t\t\tif(callback){\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t});\n}", "function init_setup_from_session() {\n\tvar username, serveraddr;\n\n\tusername = sessionStorage.getItem(\"username\");\n\tserveraddr = sessionStorage.getItem(\"serveraddr\");\n\n\tif (username && username !== \"\") {\n\t\t$(\"#username\").val(username);\n\t}\n\n\tif (serveraddr && serveraddr !== \"\") {\n\t\t$(\"#serveraddr\").val(serveraddr);\n\t}\n}", "init() {\n browser.runtime.onMessage.addListener(this.sendCSRsToPopup.bind(this));\n }", "function initPopup() {\n\tconsole.log(\"Popup initialization...\");\n\t\n\t//Add click listeners\n\tdocument.querySelector('#sayThanks').addEventListener('click', sayThanksForAllPostsWithHiddenLinks);\n\tdocument.querySelector('#downloadVisible').addEventListener('click', downloadByInternalLinks);\n\tdocument.querySelector('#openExternal').addEventListener('click', openExternalLinks);\n\tdocument.querySelector('#aboutLink').addEventListener('click', showAboutPage);\n\tdocument.querySelector('#allPagesCheckBox').addEventListener('click', setPagesDataOnCheckboxClick);\n\n\tchrome.tabs.query({currentWindow: true, active: true}, function (tabs) {\n\t\tcurrTabId = tabs[0].id;\n\t\tconsole.log(\"Current tab ID: \" + currTabId);\n\t\t\n\t\tconsole.log(\"Sending request to the content script to get init data...\");\n\t\tchrome.tabs.sendMessage(currTabId,{message: INIT_DATA_MSG}, function (response){\n\t\t\tconsole.log(\"Got a response from content script\");\n\t\t\tconsole.log(JSON.stringify(response));\n\t\t});\n\t});\n}", "function showLoginDialog() {\n if ($rs.isCommonPageLoaded) {\n BaseService.handleSessionTimeOut();\n } else {\n $rs.$watch(':: isCommonPageLoaded', function (nv) {\n if (nv) {\n BaseService.handleSessionTimeOut();\n }\n });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that get building list by company and user
function getBuildingListByUserAndCompany(uid, data) { return new Promise((resolve, reject) => { adminWebModel.getBuildingListByUserAndCompany(data).then((result) => { if (result) { let token = jwt.sign({ uid: uid }, key.JWT_SECRET_KEY, { expiresIn: timer.TOKEN_EXPIRATION }) resolve({ code: code.OK, message: '', data: { 'token': token, 'buildinglist': result } }) } }).catch((err) => { if (err.message === message.INTERNAL_SERVER_ERROR) reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} }) else reject({ code: code.BAD_REQUEST, message: err.message, data: {} }) }) }) }
[ "function getBuildingListByCompany(req, res) {\n let userId = req.decoded.uid\n let data = req.body\n adminService.getBuildingListByCompany(userId, data).then((result) => {\n res.json(result)\n }).catch((err) => {\n res.json(err)\n })\n}", "function getBuildingListByCompany(uid, data) {\n return new Promise((resolve, reject) => {\n adminWebModel.getBuildingListByCompany(data.companyID).then((result) => {\n if (result) {\n let token = jwt.sign({ uid: uid }, key.JWT_SECRET_KEY, {\n expiresIn: timer.TOKEN_EXPIRATION\n })\n \n resolve({ code: code.OK, message: '', data: { 'token': token, 'buildinglist': result } })\n }\n }).catch((err) => {\n if (err.message === message.INTERNAL_SERVER_ERROR)\n reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} })\n else\n reject({ code: code.BAD_REQUEST, message: err.message, data: {} })\n })\n })\n }", "function getCompanyAndCompanyList(user, isSuperAdmin, companyId, successCallback, errorCallback){\n if(isSuperAdmin){\n var companyQueryObject = new Parse.Query(\"Company\");\n\n if(!companyId || companyId == user.get('company').id){ // requested company and current user's company is the same or no company id is sent\n companyQueryObject.limit(1000);\n companyQueryObject.find().then(function(companyList){\n companyList = commonUtils.sortObjectsByName(companyList);\n for(var companyIndex in companyList){\n if(companyList[companyIndex].id == user.get('company').id){\n successCallback(companyList[companyIndex], companyList)\n }\n }\n }, errorCallback);\n }\n else {\n companyQueryObject.include(\"most_understood_personality\", \"least_understood_personality\", \"highest_pq_user\");\n companyQueryObject.find().then(function(companyList){\n companyList = commonUtils.sortObjectsByName(companyList);\n var company = _.find(companyList, function(companyObject){\n return companyObject.id == companyId\n });\n company == company || user.get(\"company\");\n successCallback(company, companyList);\n }, errorCallback);\n }\n }\n else{\n user.get(\"company\").fetch(successCallback, errorCallback);\n }\n }", "static async getCompanies(filter) {\n if(filter){\n let res = await this.request(`companies`, {name: filter})\n return res.companies;\n } else {\n let res = await this.request(`companies`);\n return res.companies;\n }\n }", "function list(req, res) {\n var data = req.query;\n data.userId = req.user.sub;\n data.githubName = req.user.nickname;\n\n githubApi.userOrganisations(req.user).then(function (githubOrgs) {\n return [githubOrgs, findAccounts({'$or': [\n {paidBy: data.userId, status: consts.active},\n {owner: {'$in': githubOrgs}, status: consts.active}\n ]}, '-_id owner paidBy plan nextBillingDate')];\n }).spread(function (githubOrgs, paidOrgs) {\n var orgs = mergeLists(paidOrgs, githubOrgs);\n console.log(orgs);\n return res.send(orgs);\n }).catch(function (err) {\n err.message = 'Error getting billings for ' + data.githubName;\n console.error(err.body, err.message);\n return res.status(500).send(err);\n });\n}", "static async getCompanies(params = '') {\n let res = await this.request(`companies`, { search: params });\n return res.companies;\n }", "function getCompanyList(uid, data) {\n return new Promise((resolve, reject) => {\n adminWebModel.getCompanyList(data).then((result) => {\n if (result) {\n let token = jwt.sign({ uid: uid }, key.JWT_SECRET_KEY, {\n expiresIn: timer.TOKEN_EXPIRATION\n })\n \n resolve({ code: code.OK, message: '', data: { 'token': token, 'totalpage': Math.ceil(result.count / Number(data.row_count)), 'companylist': result.rows } })\n }\n }).catch((err) => {\n if (err.message === message.INTERNAL_SERVER_ERROR)\n reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} })\n else\n reject({ code: code.BAD_REQUEST, message: err.message, data: {} })\n })\n })\n }", "static getCompanies({ user_guid }) {\n return new Promise((resolve, reject) => {\n db.query(\n `SELECT name, id, purpose, description, financial FROM company WHERE user_guid=$1`,\n [user_guid],\n (error, response) => {\n if (error) return reject(error);\n if (response.rows.length) {\n resolve({companies: response.rows, message: `${response.rows.length} companies were retrieved`})\n } else {\n resolve({companies: [], message: 'No companies were found'})\n }\n })\n })\n }", "function getUserBuildings() {\n $.ajax({\n type: \"GET\",\n url: '/buildingsRefs',\n success: function(response) {\n var buildings = response.buildings\n populateUserBuildings(buildings)\n },\n error: function(error) {\n alert('An error occurred please refresh or login again')\n }\n });\n}", "function getBuildingList() {\n\t\tfetch(`${HTTP_SERVER}/buildings/list.json`,{\n\t\t\tmethod: 'GET',\n\t\t\tContentType: 'json'\n\t\t})\n\t\t.then(function(res) {\n\t\t\t// This return the header call of the function, not the data.\n\t\t\treturn res.json();\n\t\t})\n\t\t.then(function(data){\n\t\t\t// The data is here:\n\t\t\tfetchedData.buildingTypeList = data;\n\t\t\twindow.console.log('Got the Building Type');\n\t\t\tgetNeiborhoodCode();\n\t\t})\n\t\t.catch(function(ex) {\n\t\t\t// Fail to fetch so keep using the default value.\n\t \twindow.console.log('parsing failed', ex);\n\t \tgetNeiborhoodCode();\n\t \t})\n\t}", "static async getCompanies(filter) {\n\n /** GET /companies/ =>\n * { companies: [ { handle, name, description, numEmployees, logoUrl }, ...] }\n * Can filter on provided search filters:\n * - minEmployees\n * - maxEmployees\n * - nameLike (will find case-insensitive, partial matches)\n * Authorization required: none\n */\n let res = await this.request(`companies${filter}`);\n\n return res.companies;\n }", "async function getCompanyOptions(token, userType, userName) {\r\n const cps = await getCompanies(token, userType, userName)\r\n var companyOptions = []\r\n for (let i = 0; i < cps.length; i++) { \r\n companyOptions.push({\r\n value: cps[i],\r\n label: cps[i]}) \r\n }\r\n return companyOptions\r\n }", "function getBuildings(res, mysql, context, searched, filters_name, filters_arr, complete){\n if (searched === 0){\n var default_search =\"\";\n name_query = default_search.replace(\";\",\"\");\n var inserts = ['[0-9]*', 0, Math.pow(2,127), 'industrial','residential','commercial', 0, Math.pow(2,127)];\n }\n else{\n name_query = filters_name.replace(\";\",\"\");//protect against stopping query\n var inserts;\n inserts = filters_arr;\n if (filters_arr[3] === \"-\" && filters_arr[0] === \"-\"){\n inserts = ['[0-9]*', inserts[1], inserts[2], 'industrial','residential','commercial', inserts[6], inserts[7]];\n }\n else if (filters_arr[0] === \"-\") {\n inserts[0] = '[0-9]*';\n }\n else if (filters_arr[3] === \"-\") {\n inserts[3] = ['industrial'];\n inserts[4] = ['residential'];\n inserts[5] = ['commercial'];\n }\n }\n var sql = \"SELECT building_id, building_name, energy_company_name, b_square_feet, build_date, _function, energy_consumption FROM building \"\n + \"INNER JOIN energy_company ON building.energy_company_id = energy_company.energy_company_id \"\n + \"AND building.energy_company_id REGEXP ?\"\n +\" AND (b_square_feet>=? AND b_square_feet<=?) AND building_name LIKE '%\"+name_query+\"%' AND _function IN (?, ?, ?) AND (energy_consumption>=? AND energy_consumption<=?)\";\n mysql.pool.query(sql, inserts, function(error, results, fields){\n if(error){\n res.write(JSON.stringify(error));\n res.end();\n }\n context.buildings = results;\n complete();\n });\n }", "function getObjs_Buildings(){\n\n // retrieve data from table: buildings\n con.query(\"SELECT * FROM buildings WHERE name = ?\",user_name, function(err, result){\n if(err) throw err;\n var building=result[0];\n for(var i=1; i<=25;i++){\n buildings_info.push(result[0][i]);\n }\n })\n // retreive data from table: objects\n con.query(\"SELECT * FROM objects WHERE name = ?\",user_name, function(err, result){\n if(err) throw err;\n var count=0;\n var number=result[0].amount;\n for(var i=1; i<=25;i++){\n if(result[0][i]!=null){\n count=count+1;\n objs_info.push(result[0][i]);\n }\n if(count==number){\n break;\n }\n }\n })\n}", "function getCompanyQuery() {\n getData(getCompanyParams);\n}", "static async getCompanies(search) {\n const res = await this.request(`companies`, { search });\n return res.companies;\n }", "static async getCompanies(query = \"\") {\n let res;\n \n if (query) {\n res = await this.request(`companies`, { name: query });\n } else {\n res = await this.request(`companies`);\n }\n \n return res.companies;\n }", "listByBuilding(room,callback) {\r\n\r\n let db = database.getDB();\r\n let query = { building: room };\r\n let proj= {_id: 0, ist_id: 1}; //to return only id's\r\n db.collection(\"users\").find(query, {projection : proj}).toArray(function(err, docs) {\r\n //returns all users\r\n return callback(err,docs);\r\n });\r\n\r\n }", "static async getCompanies(search) {\n\t\t/** On the backend, our `Company` model has a query that filters\n\t\t * the data we receive back, if `search` is passed into the parameters\n\t\t */\n\t\tlet res = await this.request('companies', { search });\n\t\treturn res.companies;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove the last data line
popDataLine() { this.linesData.pop(); }
[ "popDataLine() {\n this.linesData.pop();\n }", "function deleteLastLine() {\n $('.line:last').remove();\n }", "function removeLastPolyLine() {\n currentPolyLines.pop();\n}", "function reset() {\n var line = false;\n while (line = lines.pop()) {\n line.remove();\n }\n }", "function dataRightOut() {\r\n dataList.removeChild(dataList.lastElementChild);\r\n dataArray.pop();\r\n}", "function removeLastBlankLine (hints) {\n for (var i = hints.length - 1; i >= 0; i--) {\n var text = hints[i].text;\n if(text.charAt(text.length - 1) === '\\n' || text.charAt(text.length - 1) === '\\r\\n'){\n hints[i].text = text.substr(0, text.length - 1);\n }\n }\n return hints;\n }", "_popLineFromData() {\n const endIndex = this.data.indexOf(HD_PROTOCOL_LINE_TERM, this.dataFromIndex)\n if (endIndex == -1) {\n return null\n } else {\n const result = this.data.slice(this.dataFromIndex, endIndex)\n const newFromIndex = endIndex + HD_PROTOCOL_LINE_TERM.length\n if (newFromIndex >= this.data.length) {\n this.data = ''\n this.dataFromIndex = 0\n } else {\n this.dataFromIndex = newFromIndex\n }\n // return result with protocol prefix striped off\n return result.replace(HD_PROTOCOL_PREFIX, '')\n }\n }", "function deleteLast() {\n let screenText = screen.text();\n screenText = screenText.slice(0,-1);\n screen.text(screenText);\n }", "function getLastLine(lineData) {\n let lastLine = \"\";\n for (let i = 0; i < lineData.length; i++) {\n const thisLine = lineData[i];\n\n if (thisLine !== \"\") lastLine = thisLine;\n }\n\n return lastLine;\n}", "_removeSpacesAfterLastNewline() {\n // var lastNewlineIndex = this.buf.lastIndexOf(\"\\n\");\n // if (lastNewlineIndex === -1) {\n // return;\n // }\n //\n // var index = this.buf.buf.length - 1;\n // while (index > lastNewlineIndex) {\n // if (this.buf.buf[index] !== \" \") {\n // break;\n // }\n //\n // index--;\n // }\n //\n // if (index === lastNewlineIndex) {\n // this.buf.buf = this.buf.buf.substring(0, index + 1);\n // }\n }", "function delLast() {displayValue.length > 1 ?\n\tdisplayValue = displayValue.slice(0,-1) : displayValue = 0;\n\tupdateDisplay()\n}", "function removeUnnecessaryData(line, next) {\n const newData = line.replace(/^\\w+\\s?/, '');\n\n next(null, newData ? newData : undefined);\n}", "removeLastRow() {\n this._rows.pop().remove();\n if (this.lastRow) {\n this._svg.height(this.lastRow.ry2 + 20);\n }\n }", "clearToLastMarker() {\n const markerIdx = this.entries.indexOf(MARKER);\n if (markerIdx >= 0) {\n this.entries.splice(0, markerIdx + 1);\n }\n else {\n this.entries.length = 0;\n }\n }", "handleLastInsertedLineValues()\n {\n if(this.clearNewLines)\n {\n // clear new fields\n $('.line-change-info:last').find('input').each(function(){\n $(this).val('');\n })\n }\n else\n {\n // do nothing, leave copied values\n }\n }", "removeDataLines() {\n this._linesData = [];\n }", "removeDataLines() {\n this._linesData = [];\n }", "function deleteLastOutputRow() {\n\tvar table = document.getElementById(\"output\");\n\ttable.deleteRow(NUM_HEADER_ROWS);\n}", "removeLastTag() {\n if (!this.input.length && this.deleteOnBackspace) {\n this.removeTag(this.tags.length - 1);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the PKCS1 RSA encryption of "text" as an evenlength hex string
function RSAEncrypt(text) { var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); if (m == null) return null; var c = this._doPublic(m); if (c == null) return null; var h = c.toString(16); if ((h.length & 1) == 0) return h; else return "0" + h; }
[ "function RSAEncrypt(text) {\n var m=pkcs1pad2(text,(this.n.bitLength()+7)>>3);\n if(m==null) return null;\n var c=this.doPublic(m);\n if(c==null) return null;\n var h=c.toString(16);\n if((h.length&1)==0) return h;else return \"0\"+h;\n }", "encrypt(text) {\n\t\tvar m = this.pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);\n\t\tif (m == null) return null;\n\n\t\tvar c = this.doPublic(m);\n\t\tif (c == null) return null;\n\n\t\tvar h = c.toString(16);\n\t\tif ((h.length & 1) == 0) return h;\n\t\telse return \"0\" + h;\n\t}", "function RSAEncrypt(text) {\n var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);\n if (m == null) return null;\n var c = this.doPublic(m);\n if (c == null) return null;\n var h = c.toString(16);\n if ((h.length & 1) == 0) return h;\n else return \"0\" + h;\n }", "function RSAEncrypt(text) {\n var m = pkcs1pad2(text, this.n.bitLength() + 7 >> 3);\n if (m == null) return null;\n var c = this.doPublic(m);\n if (c == null) return null;\n var h = c.toString(16);\n if ((h.length & 1) == 0) return h;else return \"0\" + h;\n }", "function RSAEncrypt(text) {\n var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);\n if (m == null) return null;\n var c = this.doPublic(m);\n if (c == null) return null;\n var h = c.toString(16);\n if ((h.length & 1) == 0) return h; else return \"0\" + h;\n }", "function RSAEncrypt(text) {\n var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);\n if (m == null) return null;\n var c = this.doPublic(m);\n if (c == null) return null;\n var h = c.toString(16);\n if ((h.length & 1) == 0) return h;\n else return \"0\" + h;\n }", "function RSAEncrypt(text) {\r\n var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);\r\n if(m == null) return null;\r\n var c = this.doPublic(m);\r\n if(c == null) return null;\r\n var h = c.toString(16);\r\n if((h.length & 1) == 0) return h; else return \"0\" + h;\r\n }", "function RSAEncrypt (text) {\n var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3)\n if (m == null) return null\n var c = this.doPublic(m)\n if (c == null) return null\n var h = c.toString(16)\n if ((h.length & 1) == 0) return h\n else return '0' + h\n}", "function RSAEncrypt(text)\n{\n var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);\n if (m == null) return null;\n var c = this.doPublic(m);\n if (c == null) return null;\n var h = c.toString(16);\n if ((h.length & 1) == 0) return h;\n else return \"0\" + h;\n}", "function RSAEncryptEx(text,padType,padLen) {\n\t\n var m;\n switch (padType)\n {\n\tcase 1:\n\t\tm = pkcs1pad1(text,padLen);\n\t\tbreak;\n\t\n\tcase 2:\n\t\tm = pkcs1pad2(text,padLen);\n\t\tbreak;\n\t\n\tdefault:\n\t\treturn null;\n }\n \n if(m == null) return null;\n var c = this.doPublic(m);\n if(c == null) return null;\n var h = c.toString(16);\n if((h.length & 1) == 0) return h; else return \"0\" + h;\n}", "function encrypt(text) {\n\tvar cipher = crypto.createCipher(encryptAlgorithm, secret)\n\tvar crypted = cipher.update(text,'utf8','hex')\n\tcrypted += cipher.final('hex');\n\treturn crypted;\n}", "function encodeRSA(text, cipher) {\n return cipher.encrypt(text, 'base64');\n}", "pkcs1pad2(s, n) {\n\t\tif (n < s.length + 11) { // TODO: fix for utf-8\n\t\t\tconsole.error(\"Message too long for RSA\");\n\t\t\treturn null;\n\t\t}\n\t\tvar ba = new Array();\n\t\tvar i = s.length - 1;\n\t\twhile (i >= 0 && n > 0) {\n\t\t\tvar c = s.charCodeAt(i--);\n\t\t\tif (c < 128) { // encode using utf-8\n\t\t\t\tba[--n] = c;\n\t\t\t} else if ((c > 127) && (c < 2048)) {\n\t\t\t\tba[--n] = (c & 63) | 128;\n\t\t\t\tba[--n] = (c >> 6) | 192;\n\t\t\t} else {\n\t\t\t\tba[--n] = (c & 63) | 128;\n\t\t\t\tba[--n] = ((c >> 6) & 63) | 128;\n\t\t\t\tba[--n] = (c >> 12) | 224;\n\t\t\t}\n\t\t}\n\t\tba[--n] = 0;\n\t\tvar rng = new SecureRandom();\n\t\tvar x = new Array();\n\t\twhile (n > 2) { // random non-zero pad\n\t\t\tx[0] = 0;\n\t\t\twhile (x[0] == 0) rng.nextBytes(x);\n\t\t\tba[--n] = x[0];\n\t\t}\n\t\tba[--n] = 2;\n\t\tba[--n] = 0;\n\t\treturn new BigInteger(ba);\n\t}", "encrypt_rsa(key, text) {\n\t\treturn encrypted = key.encrypt(text, 'base64');\n\t}", "function pkcs1pad1(s,n) {\n \n if(n < s.length + 11) {\n\talert(\"Message too long for RSA\");\n\treturn null;\n }\n \n var ba = new Array();\n\n ba[--n] = 0; // as if adding null to the string to be padded\n\n var i = s.length - 1;\n while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--);\n ba[--n] = 0;\n \n while(n > 2) { \n\tba[--n] = 0xFF;\n }\n ba[--n] = 1;\n ba[--n] = 0;\n \n return new BigInteger(ba);\n}", "function _signText(text) {\n\tvar sign = crypto.createSign(\"RSA-SHA1\");\n\tsign.update(text, \"utf8\");\n\treturn sign.sign(ownCertificate.key, \"base64\");\n}", "function _rsapem_privateKeyToPkcs1HexString(rsaKey) {\n var result = _rsapem_derEncodeNumber(0);\n result += _rsapem_derEncodeNumber(rsaKey.n);\n result += _rsapem_derEncodeNumber(rsaKey.e);\n result += _rsapem_derEncodeNumber(rsaKey.d);\n result += _rsapem_derEncodeNumber(rsaKey.p);\n result += _rsapem_derEncodeNumber(rsaKey.q);\n result += _rsapem_derEncodeNumber(rsaKey.dmp1);\n result += _rsapem_derEncodeNumber(rsaKey.dmq1);\n result += _rsapem_derEncodeNumber(rsaKey.coeff);\n\n var fullLen = _rsapem_encodeLength(result.length / 2);\n return '30' + fullLen + result;\n}", "function _rsapem_privateKeyToPkcs1PemString() {\n return hex2b64(_rsapem_privateKeyToPkcs1HexString(this));\n}", "encryptByPublicKey(plainText) {\n const encryptBuff = publicEncrypt({\n key: this.getPublicKey(),\n padding: constants.RSA_PKCS1_PADDING\n }, Buffer.from(plainText))\n return encryptBuff.toString('base64');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO get Assets for trust in orderBook
getTrustedAssets() { let image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQIAAAECCAYAAAAVT9lQAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAACKFJREFUeNrs3T1yG8kZBuBe2YEz0pkzwJkzMHRG+ATUDaAbcG8A3YBHAJ3ZEbjZOiJ0AlAnIPYEoDJn9HRxYEEUqSWJv+n+nqeqi9JulQqYnnnZ/U1PT0oAAAAAAAAAAAAAAAAAAAAAAI/85BBUo9e0ftNOmnbc/rnf/r/Vf3uLRduyu6bdtH++Wfv7F4dfELB/g/biXrVhBz7TbC0YZm14/KarBAHbvfCHa+24kM9914bCKhw+6UpBwOuctRf9+7Uhfg1mbbtq2mfdDE//5r9o2rJp9wHabdMmbehBaEdNGzVtHuTif64t21AYOCWIpBfst/9rRwrnbUhCtQEwcbG/apTQc9ogALR7gUANNYCxC1kgENdZO991AW+/XaghUMI04NrFupcawrnTjS4aJXcC9t1y6LrtSGdqAVMX5UHb2GnIIQ3UAjo1OlBM5CBTARdg92oHp05N9uXCRWeqQOx6gMVB5aw7gJ2EwNwFVlSbJ2sOEAKaMEAIaMIAIaAJA4SAJgzYAncH6mxTpzYvZZ2AW4sEZ8VgjDZyqtvO/Dn52YEbhyGE/O6FYQq+tbogeLo4mEOg71CEcdOGQdhXt/3BOfCdfzXt7w5DKH9p2p+a9h+HAnUBLewTi6YGX/XaIeKxQxHWIj28VDbcFMHU4Kv8Lr6/OQyh5V8C/00BX9ZqRPB1SnDpMNDqp2CvdDcieLhL8Gt6KBbBKgj+HekLv9Pn6aO6AI/kV9GHKhxGnxrkAuHCec8TZk37hyCIYdqmfwQ37cl904bf4nfmwavfiMN2qLz6GUn+zp8SVcsneoSHavJr17b1yG0eQeU3C0V5LNtDSQHU+kqy/H6Fcdr98/aDFOMRbe9IMBoobi//Q2zfXft7Hm2JXnltoLZNNg694855qvOdj7culzr1KhsFdOl5+kGlYXDmsqnPpKIQ6OIbgGsMA0XDyhxVcpLOU7dfA15bGCxdOnUZJSMBBVmPKH8n2rMGl+lhE4pSlbSt1mqx0rCScycfexuXKBIqWr3RbSUjgrlLqA6lb01+Uehxr2mK4KUoFSj5N9Nt4SdhLQuOqq0TRHkMORfX+gV//g+p7O2zLis5j4YJ04J0uFWDNajhdmK1r0mLMiIoOcl/rqQPrir4DjawKVjJdwtqWtF2VkmdgEKVvIiotkdgBYGpgWnBK81SfTvpzir4DqeCQBDs02WFfeHFsoLgYPWBfoGfOy9n/WeF/bFwyQmCQzgp9HNfVdofNYwIjgWBIBAEm490nFOCQH3ghX6ptD8+JwSB9H6RmdMSQbA9R4XO5wSB/hEE5nKCAEEgCNxrRxBsVYnTgkUq+3FjBEHnDAsNAhAEwakPmLoJgi0rsUZwV/lFNKjgO3wRBGoEftvE6xNTA9iyoambINinUp8Z/1R5EJwkBAFGBEYEgoDYcqGw9BrBnSCAzXyo4DtUW8ytNQg8bNQ97wVBd/2x4iCYOck6I29l3i/8OyyS5d+wkRrefTituYPUCNi1fCt3WMH3mOlKeLuS30K93ga6Et5mXEkILHUlvM2gkhCo7R2UagTsTd4v8rKi73OlS+H1phWNBu7bYANeYVJZCEx0KbzOqLIQyO1Mt0LsELjVrRA7BHIb61qIWRNYXzugSAiBQ0CREF4g/6acVxwCufV0MzxvECAE1AbgB87auXPNIaA2AD8wrjwAVm2kq+HpesA0SAhc626IWQ9YnxIoEMIjowD1gPV2rsvhWxeBAqD6/QjhLfWA62AhcJvcJYBv6gG3wUJgmexFCGHrAR4xhkfOAwaA9QKwZiIEQAgIAQgqwpODQgCEgBAAIfD9LUIhAIFrAtYJQPAQyKMfDxFBK+I6gUmybBj+7yxgCHiKENb0Uqxlw/m7nup2+FakOwTXpgLwvXGgELDjMDzhNMXZR8CtQXhGhD0FpqYCEHdKYJUg/I7a7xJYIAQvUPPqwQvdCy8bDdQ6FbCdGAQeDZgKQPDRgGcFIPhowLMC8EpHqZ47BeoB8EajZAMRCK+GB4ssFYYN1FAknCdFQdjIhRAASp4WqAlA8GmBEOigdw5Bkd4X/Nl/btpnXQibmyYPD0F4JS4imus22J5BoaMBdQE1ArbopMDP/FFdALartPUDt7rMiAAjgo+6rPt+cgiKc1/QZ1007a+6zIiA7Sptxx6jAdiBkl5estRdRgTsRr+gz3qpuwQBgkAQCAJ25LiQz7lI1g0IAnamlFuHV7pKEMDMIRAEcOMQCAJiu2vabw6DIMBoAEEACAJAEACCABAEgCAABAEgCABBAAgCQBAA5bKLcVny24K6vjlJfujIpiQAAAAAAAAAAAAAAAAAAAAAAKWzQ1H9jpo2bNpJ+zO1f17f6Wi29vOm/fnFoYPyL/7zps2bdv/GNm//jSOHE8rSa9qkacsNAuBxW7b/Zs/hhe4bbzkAngqEscMM3TTYcArwlinDwGGH7hjteBTwo9HByOGHboTA/YGbMIDgISAMQAgIAziUwYFqAi9pCoiwJ/OOhkBut8niI9i5cYdDYNWsM4Ad6hUQAqtmBSLsyKSgIJjoLti+o4JCwKigUO8cgs774DMDXb5T8KM7CMCW9AoMAdMDUwO2bFjwZ3+v+wQBguBE9wkCtqPvs7MPNi/ttvxcwXGhn/2uaX/WhYKAzd07vzA1AAQBIAgAQUB6KLiBIAjupuDPPtN9goDtWBjNIAgwIkAQUPTFJAhgi/IjvR5DxogguCufGShxTwJ7EcAOTAsKgWvdBbsxKCgITnUX7E4JW5rbyhx2LG9rvuxwCCyTV57BXpx2OAjOdA/sTxffgeidhxC8XqAuAMHDQAhA8GnChcMP3ZGLdPu8m7BMCoPQSfm23T5WH06TW4TQefn24nXazbJhKwahMHlJ8mTDKcOy/TcEQABeQBFjlDBsWz89/yqyRdtmbfvk0AEAAAAAAAAAAAAAAAAAAAAABPY/AQYAy0Q5AZlICSYAAAAASUVORK5CYII="; let site = 'Smartland.io'; let tokenName = "SLT"; let newArray = this.setFullList(); let trustlines = this.props.trustlines.map(asset => ( { code: asset.code, issuer: asset.issuer, //TODO get data from StellarTools AssetUid() value: AssetUid(asset), //TODO get data from Asset.js getAssetString() text: `${asset.code} | ${site} \n ${asset.issuer}`, image: AssetComponent.setNewData(image) })).map(trustline => { newArray.forEach((newItem) => { let value = newItem.value.split(':'); let text= newItem.text.split(' '); if (trustline.code === value[0] && trustline.issuer === value[1]) { trustline.text = text[0]+" "+text[1]+" "+text[2]+" "+text[3]+" "+text[4].substring(0,9)+"..."+text[4].substring(text[4].length-9,text[4].length); trustline.image = AssetComponent.setNewData(newItem.image); } }); return trustline; }); trustlines.filter(v=> { return v.issuer }); let addNotTrustlines = newArray.filter(arrayItem=>{ trustlines.forEach((trustline) => { let value = arrayItem.value.split(':'); if (trustline.code === value[0] && trustline.issuer === value[1]) { arrayItem.filter = true } }); if(arrayItem.filter ||arrayItem.value==='XLM:null'){ return false; }else{ return true; } }); let toDelete = new Set(['XLM']); let newTrustlinesArray = trustlines.filter(obj => !toDelete.has(obj.code)); newTrustlinesArray.unshift(newTrustlinesArray.splice(newTrustlinesArray.findIndex(elt => elt.code === 'SLT'), 1)[0]); this.base.trustLinesLength = addNotTrustlines.length; // this.getDropdownList(this.base.trustLinesLength); newTrustlinesArray.push(...addNotTrustlines); return newTrustlinesArray; // return trustlines.filter(v=> { // return v.issuer // }) }
[ "get Assets() {}", "function getAssets() { return _assets; }", "getOwnAssets() {\n const ownImages = {}\n for (const version of this._options.versions) {\n ownImages[version] = this._assets.hasOwnProperty(version)\n }\n return ownImages\n }", "async getAssets() {\n if(!this.assetsArray) {\n try {\n const assetsPageRequest = await this.sbClient.get(`spaces/${this.spaceId}/assets`, {\n per_page: 100,\n page: 1\n })\n const pagesTotal = Math.ceil(assetsPageRequest.headers.total / 100)\n const assetsRequests = []\n for (let i = 1; i <= pagesTotal; i++) {\n assetsRequests.push(\n this.sbClient.get(`spaces/${this.spaceId}/assets`, {\n per_page: 100,\n page: i\n })\n )\n }\n const assetsResponses = await Promise.all(assetsRequests)\n this.assetsArray = assetsResponses.map(r => r.data.assets).flat()\n } catch (err) {\n console.error('✖ Error fetching the assets. Please double check the source space id.')\n }\n }\n return this.assetsArray\n }", "get mainAsset() {}", "function getAllAssets(){\n //get all assets\n ModulesService.getAllModuleDocs('assets').then(function(assets){ \n //store to array\n $scope.assets = assets;\n })\n .catch(function(error){\n FlashService.Error(error);\n }).finally(function() {\n\t\t\t\t$scope.loading = false;\n\t\t\t});\n }", "get IncludeLibraryAssets() {}", "async QueryAssetsByOwner(ctx, owner) {\n\t\tlet queryString = {};\n\t\tqueryString.selector = {};\n\t\tqueryString.selector.docType = 'asset';\n\t\tqueryString.selector.owner = owner;\n\t\treturn await this.GetQueryResultForQueryString(ctx, JSON.stringify(queryString)); //shim.success(queryResults);\n\t}", "async getAssets() {\n this.stepMessage('2', `Fetching assets from source space.`)\n try {\n const assets_page_request = await this.storyblok.get(`spaces/${this.source_space_id}/assets`, {\n per_page: 100,\n page: 1\n })\n const pages_total = Math.ceil(assets_page_request.headers.total / 100)\n const assets_requests = []\n for (let i = 1; i <= pages_total; i++) {\n assets_requests.push(\n this.storyblok.get(`spaces/${this.source_space_id}/assets`, {\n per_page: 100,\n page: i\n })\n )\n }\n const assets_responses = await Promise.all(assets_requests)\n this.assets_list = assets_responses.map(r => r.data.assets).flat().map((asset) => asset.filename)\n this.stepMessageEnd('2', `Fetched assets from source space.`)\n } catch (err) {\n this.migrationError('Error fetching the assets. Please double check the source space id.')\n }\n }", "async getAssets (obj, args, { user } ) {\n logger.trace('getAssets entry', user);\n const assets = await _wallet.getAssets(user)\n logger.trace('getAssets exit', assets);\n // return list of assets for a tenant\n return assets;\n }", "retrieveAllAssets() {\n return this.assetModel\n .retrieve()\n .then((asset) => asset).catch((error) => Promise.resolve({\n error\n }));\n }", "async GetAllAssets(ctx) {\n const allResults = [];\n // range query with empty string for startKey and endKey does an open-ended query of all assets in the chaincode namespace.\n const iterator = await ctx.stub.getStateByRange('', '');\n let result = await iterator.next();\n while (!result.done) {\n const strValue = Buffer.from(result.value.value.toString()).toString('utf8');\n let record;\n try {\n record = JSON.parse(strValue);\n } catch (err) {\n console.log(err);\n record = strValue;\n }\n allResults.push({ Key: result.value.key, Record: record });\n result = await iterator.next();\n }\n return JSON.stringify(allResults);\n }", "function getAssets() {\n axios\n .get(process.env.REACT_APP_API_URL + \"/assets\")\n .then((res) => {\n setAssets(res.data);\n // console.log(res.data);\n })\n .catch((err) => {\n console.log(\"Error listing the assets\");\n });\n }", "function getAssetList() {\r\n let url = API_URL + 'assets/' + '?key=' + API_KEY;\r\n return fetchAssets(url);\r\n}", "loadExternalAssets() {\n\t\txmlSignature = `<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><cache></cache>`;\n\n\t\t// Load local keyword definition file\n\t\t// TODO\n\n\t\t// Load kwdb\n\t\tatom.notifications.addInfo(`Loading KWDB file...`);\n\t\tmyself.fileIO.loadAndParseXMLFile(atom.config.get('LSL-Tools.pathToKwdbFile'), \"KWDB file\", false).then((kwdb) => {\n\t\t\tmyself.kwdbFile = kwdb.file;\n\t\t\tmyself.kwdbDom = kwdb.dom;\n\t\t});\n\n\t\t// Load slwiki cache file\n\t\tatom.notifications.addInfo(`Loading SLWiki cache file...`);\n\t\tmyself.fileIO.loadAndParseXMLFile(atom.config.get('LSL-Tools.pathToSLWikiCacheFile'), \"SLWiki cache file\", true, xmlSignature).then((slwikiCache) => {\n\t\t\tmyself.slwikiCacheFile = slwikiCache.file;\n\t\t\tmyself.slwikiCacheDom = slwikiCache.dom;\n\t\t});\n\t}", "function GroupAssets() {\n\n\tvar assets = {};\n\n\tassets.cta = new createjs.Bitmap(queue.getResult(\"cta\"));\n\tassets.frameOneText = new createjs.Bitmap(queue.getResult(\"frameOneText\"));\n\tassets.frameTwoText = new createjs.Bitmap(queue.getResult(\"frameTwoText\"));\n\tassets.skyKidsLogoLg = new createjs.Bitmap(queue.getResult(\"skyKidsLogoLg\"));\n\tassets.frameThreeText = new createjs.Bitmap(queue.getResult(\"frameThreeText\"));\n\tassets.frameThreeRelText = new createjs.Bitmap(queue.getResult(\"frameThreeRelText\"));\n\n\treturn assets;\n}", "assetsInStage(stage) {\n const assets = new Map();\n for (const stack of stage.stacks) {\n for (const asset of stack.assets) {\n assets.set(asset.assetSelector, asset);\n }\n }\n return Array.from(assets.values());\n }", "function storeAssets(pRawAssets, pAssets) {\n var i;\n for (i = 0; i < pRawAssets.length; i++) {\n\n var item = pRawAssets[i];\n\n switch (item.type) {\n\n case \"json\":\n var ssdata = JSON.parse(item.result.toString());\n var key;\n for (key in ssdata) {\n if (ssdata.hasOwnProperty(key)) {\n var spData = ssdata[key];\n pAssets[key + \"SpriteSheet\"] = new createjs.SpriteSheet(spData);\n }\n }\n\n break;\n\n case \"image\":\n pAssets[item.id + \"Img\"] = item.result;\n break;\n }\n }\n }", "function getAssets(p, platform) {\n return getAllElements(p, platform, 'asset');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ObjectTypeExtension : extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition extend type Name ImplementsInterfaces? Directives[Const] extend type Name ImplementsInterfaces
function parseObjectTypeExtension(lexer) { var start = lexer.token; expectKeyword(lexer, 'extend'); expectKeyword(lexer, 'type'); var name = parseName(lexer); var interfaces = parseImplementsInterfaces(lexer); var directives = parseDirectives(lexer, true); var fields = parseFieldsDefinition(lexer); if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { throw unexpected(lexer); } return { kind: Kind.OBJECT_TYPE_EXTENSION, name: name, interfaces: interfaces, directives: directives, fields: fields, loc: loc(lexer, start) }; }
[ "parseObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('type');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n\n if (\n interfaces.length === 0 &&\n directives.length === 0 &&\n fields.length === 0\n ) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: _kinds_mjs__WEBPACK_IMPORTED_MODULE_3__[\"Kind\"].OBJECT_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields,\n });\n }", "parseObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('type');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n return this.node(start, {\n kind: _kinds.Kind.OBJECT_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields\n });\n }", "parseObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('type');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n\n if (\n interfaces.length === 0 &&\n directives.length === 0 &&\n fields.length === 0\n ) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.OBJECT_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields,\n });\n }", "parseObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword(\"extend\");\n this.expectKeyword(\"type\");\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n return this.node(start, {\n kind: Kind.OBJECT_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields\n });\n }", "function parseObjectTypeExtension(lexer) {\n var start = lexer.token;\n expectKeyword(lexer, 'extend');\n expectKeyword(lexer, 'type');\n var name = parseName(lexer);\n var interfaces = parseImplementsInterfaces(lexer);\n var directives = parseDirectives(lexer, true);\n var fields = parseFieldsDefinition(lexer);\n\n if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {\n throw unexpected(lexer);\n }\n\n return {\n kind: kinds[\"Kind\"].OBJECT_TYPE_EXTENSION,\n name: name,\n interfaces: interfaces,\n directives: directives,\n fields: fields,\n loc: parser_loc(lexer, start)\n };\n}", "function parseObjectTypeExtension(lexer) {\n var start = lexer.token;\n expectKeyword(lexer, 'extend');\n expectKeyword(lexer, 'type');\n var name = parseName(lexer);\n var interfaces = parseImplementsInterfaces(lexer);\n var directives = parseDirectives(lexer, true);\n var fields = parseFieldsDefinition(lexer);\n\n if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {\n throw unexpected(lexer);\n }\n\n return {\n kind: _kinds.Kind.OBJECT_TYPE_EXTENSION,\n name: name,\n interfaces: interfaces,\n directives: directives,\n fields: fields,\n loc: loc(lexer, start)\n };\n}", "parseInputObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('input');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const fields = this.parseInputFieldsDefinition();\n\n if (directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: _kinds_mjs__WEBPACK_IMPORTED_MODULE_3__[\"Kind\"].INPUT_OBJECT_TYPE_EXTENSION,\n name,\n directives,\n fields,\n });\n }", "parseInputObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('input');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const fields = this.parseInputFieldsDefinition();\n\n if (directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n name,\n directives,\n fields,\n });\n }", "parseInputObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword(\"extend\");\n this.expectKeyword(\"input\");\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const fields = this.parseInputFieldsDefinition();\n if (directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n return this.node(start, {\n kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n name,\n directives,\n fields\n });\n }", "parseInputObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('input');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const fields = this.parseInputFieldsDefinition();\n if (directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n return this.node(start, {\n kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION,\n name,\n directives,\n fields\n });\n }", "function parseInputObjectTypeExtension(lexer) {\n var start = lexer.token;\n expectKeyword(lexer, 'extend');\n expectKeyword(lexer, 'input');\n var name = parseName(lexer);\n var directives = parseDirectives(lexer, true);\n var fields = parseInputFieldsDefinition(lexer);\n\n if (directives.length === 0 && fields.length === 0) {\n throw unexpected(lexer);\n }\n\n return {\n kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n name: name,\n directives: directives,\n fields: fields,\n loc: loc(lexer, start)\n };\n}", "function parseInputObjectTypeExtension(lexer) {\n var start = lexer.token;\n expectKeyword(lexer, 'extend');\n expectKeyword(lexer, 'input');\n var name = parseName(lexer);\n var directives = parseDirectives(lexer, true);\n var fields = parseInputFieldsDefinition(lexer);\n if (directives.length === 0 && fields.length === 0) {\n throw unexpected(lexer);\n }\n return {\n kind: _kinds.INPUT_OBJECT_TYPE_EXTENSION,\n name: name,\n directives: directives,\n fields: fields,\n loc: loc(lexer, start)\n };\n}", "function parseInputObjectTypeExtension(lexer) {\n var start = lexer.token;\n expectKeyword(lexer, 'extend');\n expectKeyword(lexer, 'input');\n var name = parseName(lexer);\n var directives = parseDirectives(lexer, true);\n var fields = parseInputFieldsDefinition(lexer);\n if (directives.length === 0 && fields.length === 0) {\n throw unexpected(lexer);\n }\n return {\n kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION,\n name: name,\n directives: directives,\n fields: fields,\n loc: loc(lexer, start)\n };\n}", "parseInterfaceTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('interface');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n\n if (\n interfaces.length === 0 &&\n directives.length === 0 &&\n fields.length === 0\n ) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: _kinds_mjs__WEBPACK_IMPORTED_MODULE_3__[\"Kind\"].INTERFACE_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields,\n });\n }", "function interfaceExtension(type) {\n if (type.parent !== 'Object') {\n if (type.parent !== 'Any' || type.parent === 'Any' && type.properties !== []) {\n return ` extends ${tse(type.definition.derivedFrom)}`;\n }\n return '';\n }\n return '';\n}", "function parseInterfaceTypeExtension(lexer) {\n var start = lexer.token;\n expectKeyword(lexer, 'extend');\n expectKeyword(lexer, 'interface');\n var name = parseName(lexer);\n var directives = parseDirectives(lexer, true);\n var fields = parseFieldsDefinition(lexer);\n\n if (directives.length === 0 && fields.length === 0) {\n throw unexpected(lexer);\n }\n\n return {\n kind: Kind.INTERFACE_TYPE_EXTENSION,\n name: name,\n directives: directives,\n fields: fields,\n loc: loc(lexer, start)\n };\n}", "parseInterfaceTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword(\"extend\");\n this.expectKeyword(\"interface\");\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n return this.node(start, {\n kind: Kind.INTERFACE_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields\n });\n }", "parseInterfaceTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('interface');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n return this.node(start, {\n kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields\n });\n }", "parseInterfaceTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('interface');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n\n if (\n interfaces.length === 0 &&\n directives.length === 0 &&\n fields.length === 0\n ) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.INTERFACE_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields,\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[Clear all data structures used internally for labels]
clearAllLabelData() { // clear lines for (let i = this._.lineGroup.children.length - 1; i >= 0; --i) { const line = this._.lineGroup.children[i]; this._.lineGroup.remove(line); } // clear sprites for (let i = this._.spriteGroup.children.length - 1; i >= 0; --i) { const sprite = this._.spriteGroup.children[i]; this._.spriteGroup.remove(sprite); } // clear sprite planes for (let i = this._.spritePlaneGroup.children.length - 1; i >= 0; --i) { const splane = this._.spritePlaneGroup.children[i]; this._.spritePlaneGroup.remove(splane); } // clear spheres for (let i = this._.sphereGroup.children.length - 1; i >= 0; --i) { const sphere = this._.sphereGroup.children[i]; this._.sphereGroup.remove(sphere); } // clear icons this._.scene.remove(this._.iconSpriteGroup); this._.scene.remove(this._.iconCircleGroup); // clear other structures this._.labelSet.clear(); this._.spritePlaneToLabelMap = {}; this._.sphereToLineMap = {}; this._.sphereToLabelMap = {}; // no selected label anymore this._.selectedLabel = null; this.draggingSelectedLabel = false; }
[ "function clear() {\r\n\tif (labelArray.length) {\r\n\t\tlabelArray.splice(0, labelArray.length);\r\n\t\tlabelMem.splice(0, labelMem.length);\t\t\r\n\t}\r\n}", "function clearAllLabels() {\r\n knn.clearAllLabels();\r\n updateCounts();\r\n}", "function clearAllLabels() {\n // knn.clearAllLabels();\n // updateCounts();\n}", "function clearLabels(){\n\tcontextFrameLayer.clearLayers();\n\tn_labels = 0;\n}", "function clearAllLabels() {\n\tknnClassifier.clearAllLabels();\n\tupdateCounts();\n}", "function clearAllLabels() {\n classifier.clearAllClasses();\n updateCounts();\n}", "function clearAllLabels() {\n knnClassifier.clearAllLabels();\n updateCounts();\n}", "function _clearLabels() {\n\n var entitiesToRemove = new Array();\n\n var i = 0;\n\n for (i = 0; i < map.entities.getLength(); i++) {\n\n var label = map.entities.get(i);\n\n if (label.IsLabel) {\n entitiesToRemove.push(label);\n }\n }\n\n $.each(entitiesToRemove, function () {\n map.entities.pop(this);\n });\n }", "_removeUnusedLabels() {\n // remove any labels that are not being used\n this._removeLabels(this.data.length);\n }", "function clearAllLabels() {\n if (knnClassifier.getNumLabels() <= 0) {\n console.error('There is no examples in any label');\n return;\n }\n knnClassifier.clearAllLabels();\n updateCounts();\n}", "function clearAllLabels() {\r\n if (knnClassifier.getNumLabels() <= 0) {\r\n console.error('There is no examples in any label');\r\n return;\r\n }\r\n knnClassifier.clearAllLabels();\r\n updateCounts();\r\n}", "function clearLabel(label) {\n knnClassifier.clearLabel(label);\n updateCounts();\n}", "function clearLabel() {\n}", "@autobind\n clearLabels() {\n if(this.labels){\n for (var i=0; i<this.labels.length; i++) {\n this.labels[i].innerHTML = \"\";\n this.labelDots[i].removeAttribute('style');\n }\n }\n }", "removeLabel() {\n this._label = null;\n }", "clearAxisLabel() {\n this.axisLabels = [];\n this.tooltipLabels = [];\n this.dateTimeAxisLabelInterval = [];\n this.labelValue = [];\n }", "function resetDataStructures(){\n arrayOfDivs = [];\n mapOfData = {};\n}", "function clear_deleted_text_labels () {\n utils.draw_an_object(this.sel, '#text-labels', '.text-label',\n this.text_labels, 'text_label_id', null, null,\n function (sel) { sel.remove() })\n}", "function clearGraph(){\n $('.nodeLabel').remove();\n graphics.release();\n g.clear();\n\n gNodesDisplayed = [];\n nodesToBeLinked = {};\n childrenNodes = [];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
trim space and comma uu.split.comma split commas
function uusplitcomma(source) { // @param String: ",,, ,,A,,,B,C,, " // @return Array: ["A", "B", "C"] return source.replace(uusplit._MANY_COMMAS, ","). replace(uusplit._TRIM_SPACE_AND_COMMAS, "").split(","); }
[ "function commaSplit(val) {\n return val.split(/,\\s*/);\n}", "function mySplit(textToSplit) {\n while (textToSplit.indexOf(\", \") !== -1)\n textToSplit = textToSplit.replace(\", \", \",\");\n while (textToSplit.indexOf(\" \") !== -1)\n textToSplit = textToSplit.replace(\" \", \",\");\n}", "function split(val) {\n ret = val.split( /,\\s*/ );\n if (ret[0] == \"\")\n ret = [];\n return ret;\n}", "function removeCommaHelper(sequent) {\n sequent = sequent.replace(/,/g, \" \");\n sequent = sequent.replace(/ +/g, \" \");\n sequent = (sequent.length != 0) ? sequent.split(\" \") : [];\n return sequent.filter(function (elem) { return elem != \"\"; });\n}", "function splitByComma(input) {\n var result = [];\n\n input.split(',').forEach(function(element) {\n element = element.trim();\n if (element) {\n result.push(element);\n }\n });\n return result;\n}", "function splitComma(str) { return _.split(str, \",\"); }", "function autocompleteSplit(val) {\n\treturn val.split(/,\\s*/);\n}", "function splitByComma( value ) {\n\t\tvar result = [];\n\t\t\n\t\t// Only process string if its entered and not empty.\n\t\tif ( value && value.trim().length > 0 ) {\n\t\t\t// Split string and remove empty values.\n\t\t\tresult = value.split( /\\s?,\\s?/ ).filter( function( item ) {\n\t\t\t\treturn item.length > 0;\n\t\t\t} );\n\t\t}\n\t\t\n\t\treturn result;\n\t}", "function splitCommas(words){\n console.log(\"Splitting commas\");\n var splitList = words.split(\", \");\n\n return splitList;\n }", "function onChangeTrimInValue(value){\n\tvar splitSpace = value.replace(/^[,\\s]+|[,\\s]+$/g, '');\n\tsplitSpace = splitSpace.replace(/\\s*,\\s*/g, \",\").trim();\n\tsplitSpace = splitSpace.replace(/,+/g, \",\").trim();\n\tvar str_lead = splitSpace.replace(/^,/, \"\");\n\tvar str = str_lead.replace(/,\\s*$/, \"\");\n\treturn doTrim(str);\n}", "function stripCommas(v) {\n\tv = new String(v);\n\twhile(v.match(/\\,/)) {\n\t\tv = v.replace(',','');\n\t}\n\treturn v;\n}", "_splitBetter(string) {\n // TODO: Not supported in V8 yet. Bring this back once it does.\n // string = string.trim().replaceAll(', ', ',');\n \n string = string.trim().split(', ').join(',');\n if ( string.includes(',') ) {\n return string.split(',');\n } else if ( string.includes(' ') ) {\n return string.split(' ');\n } else {\n throw Error('Param doesn\\'t seem to be a colour.');\n return '';\n }\n }", "function trimComma(s){\n let len = s.length\n if(len > 0) s = s.substring(0, len-2)\n return s\n}", "function removeCommasBetweenCoords(arr){\n var newArr= arr[0].replace(/,(?=\\()/g,\" \");\nnewArr= newArr.split(\" \");\nreturn newArr; \n \n \n}", "separateRemove(number) {\n number = number.replace(/,\\s?/g, \"\");\n return Number(number)\n }", "function splitAndTrim (str) {\n if (typeof str !== 'string') {\n return [];\n }\n var delimiters = /[ ,;]/;\n return str.split(delimiters).map(n => parseFloat(n)).filter(isFinite);\n}", "function splitListStrUsingComma(sourceStr) {\n var array = sourceStr.length === 0 ? [] : sourceStr.split(',').map(function(v) {\n return v.trim();\n });\n\n return array;\n }", "function removeCommaSpaces(string) {\n for (i = 0; i < string.length; i++) {\n if (string[i] == \",\") {\n if (string[i + 1] == \" \") {\n string = string.replace(', ', ',');\n }\n }\n }\n return string;\n}", "function splitter()\n{\n\tdetails=info.split(\",\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a decompressed stream, given an encoding.
function decompressed(req, encoding) { switch (encoding) { case 'identity': return req; case 'deflate': return req.pipe(_zlib2.default.createInflate()); case 'gzip': return req.pipe(_zlib2.default.createGunzip()); } throw (0, _httpErrors2.default)(415, 'Unsupported content-encoding "' + encoding + '".'); }
[ "function decompressed(req, encoding) {\n switch (encoding) {\n case 'identity':\n return Either_1.right(req);\n case 'deflate':\n return Either_1.right(req.pipe(zlib_1.default.createInflate()));\n case 'gzip':\n return Either_1.right(req.pipe(zlib_1.default.createGunzip()));\n }\n return Either_1.left(http_errors_1.default(415, `Unsupported content-encoding \"${encoding}\".`));\n}", "function decompressStream(stream, headers) {\n var transferEncoding = headers.get('Transfer-Encoding');\n var contentEncoding = headers.get('Content-Encoding');\n if (contentEncoding === 'deflate' || transferEncoding === 'deflate') {\n return stream.pipe(Zlib.createInflate());\n }if (contentEncoding === 'gzip' || transferEncoding === 'gzip') {\n return stream.pipe(Zlib.createGunzip());\n }return stream;\n}", "function decompressStream(stream, headers) {\n const transferEncoding = headers.get('Transfer-Encoding');\n const contentEncoding = headers.get('Content-Encoding');\n if (contentEncoding === 'deflate' || transferEncoding === 'deflate') return stream.pipe(Zlib.createInflate());\n if (contentEncoding === 'gzip' || transferEncoding === 'gzip') return stream.pipe(Zlib.createGunzip());\n return stream;\n}", "function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }", "async decompress(streaming) {\n\n if (!decompress_fns[this.algorithm]) {\n throw new Error(this.algorithm + ' decompression not supported');\n }\n\n await this.packets.read(decompress_fns[this.algorithm](this.compressed), {\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n }, streaming);\n }", "function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }", "function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }", "function decompress(proxyRes, contentEncoding) {\n let _proxyRes = proxyRes;\n let decompress;\n switch (contentEncoding) {\n case 'gzip':\n decompress = zlib.createGunzip();\n break;\n case 'br':\n decompress = zlib.createBrotliDecompress();\n break;\n case 'deflate':\n decompress = zlib.createInflate();\n break;\n default:\n break;\n }\n if (decompress) {\n _proxyRes.pipe(decompress);\n _proxyRes = decompress;\n }\n return _proxyRes;\n}", "static decode_stream(u8_stream, opt) {\n return new this().decode_stream(u8_stream, opt)}", "decompress() {\n\t\tif (!this.raw) {\n\t\t\tthis.readRaw();\n\t\t}\n\t\tlet buff = this.raw;\n\t\tif (this.compressed) {\n\n\t\t\t// Important! In Simcity 4 DBPF files, compressed subfiles are \n\t\t\t// always prefixed with the total size! We can discard this.\n\t\t\tbuff = decompress(buff.slice(4));\n\n\t\t}\n\t\treturn buff;\n\t}", "function decode(src) {\n var stream = new IOStream(src)\n return RansDecodeStream(stream, 0)\n}", "function ungzipStream(rawstream) {\n return (rawstream ? rawstream.pipe(ZL.createGunzip()) : undefined);\n}", "function inflate() {\n var push = inflateStream(onEmit, onUnused);\n var more = true;\n var chunks = [];\n var b = bodec.create(1);\n\n return { write: write, recycle: recycle, flush: flush };\n\n function write(byte) {\n b[0] = byte;\n push(null, b);\n return more;\n }\n\n function recycle() {\n push.recycle();\n more = true;\n }\n\n function flush() {\n var buffer = bodec.join(chunks);\n chunks.length = 0;\n return buffer;\n }\n\n function onEmit(err, item) {\n if (err) throw err;\n if (item === undefined) {\n // console.log(\"onEnd\");\n more = false;\n return;\n }\n chunks.push(item);\n }\n\n function onUnused(chunks) {\n if (chunks[0].length) throw new Error(\"Extra data after deflate\");\n more = false;\n }\n}", "function decodeStream() {\n var ins = new PassThrough\n var outs = new PassThrough({ objectMode: true })\n var ubs = new ubjson.Stream(ins)\n pipeUBS(ubs, outs)\n return duplexify.obj(ins, outs)\n}", "function contentEncoding() {\n return async function (req, next) {\n if (req.headers.has(\"Accept-Encoding\"))\n return next();\n req.headers.set(\"Accept-Encoding\", zlib_1.createBrotliDecompress ? \"gzip, deflate, br\" : \"gzip, deflate\");\n const res = await next();\n const enc = res.headers.get(\"Content-Encoding\");\n // Unzip body automatically when response is encoded.\n if (enc === \"deflate\" || enc === \"gzip\") {\n res.$rawBody = res.stream().pipe(zlib_1.createUnzip());\n }\n else if (enc === \"br\") {\n if (zlib_1.createBrotliDecompress) {\n res.$rawBody = res.stream().pipe(zlib_1.createBrotliDecompress());\n }\n else {\n throw new EncodingError(res, \"Unable to support Brotli decoding\");\n }\n }\n else if (enc && enc !== \"identity\") {\n throw new EncodingError(res, `Unable to decode \"${enc}\" encoding`);\n }\n return res;\n };\n}", "function LZ4_uncompress (input, options) {\n\tvar output = []\n\tvar decoder = new Decoder(options)\n\n\tdecoder.on('data', function (chunk) {\n\t\toutput.push(chunk)\n\t})\n\n\tdecoder.end(input)\n\n\treturn Buffer.concat(output)\n}", "function test5() {\n var fs = require(\"fs\");\n var zlib = require('zlib');\n// Decompress the file input.txt.gz to input.txt\n fs.createReadStream('input.txt.gz')\n .pipe(zlib.createGunzip())\n .pipe(fs.createWriteStream('input.txt'));\n console.log(\"File Decompressed.\");\n}", "function tinf_uncompress(source,dest){var d=new Data(source,dest);var bfinal,btype,res;do{/* read final block flag */bfinal=tinf_getbit(d);/* read block type (2 bits) */btype=tinf_read_bits(d,2,0);/* decompress block */switch(btype){case 0:/* decompress uncompressed block */res=tinf_inflate_uncompressed_block(d);break;case 1:/* decompress block with fixed huffman trees */res=tinf_inflate_block_data(d,sltree,sdtree);break;case 2:/* decompress block with dynamic huffman trees */tinf_decode_trees(d,d.ltree,d.dtree);res=tinf_inflate_block_data(d,d.ltree,d.dtree);break;default:res=TINF_DATA_ERROR;}if(res!==TINF_OK)throw new Error('Data error');}while(!bfinal);if(d.destLen<d.dest.length){if(typeof d.dest.slice==='function')return d.dest.slice(0,d.destLen);else return d.dest.subarray(0,d.destLen);}return d.dest;}", "uncompress() {\n\t\tif (!fs.existsSync(Path.resolve('./jndb.dat'))) {\n\t\t\tthrow new Error('jndb.dat doesnt exist to extract data from');\n\t\t}\n\t\tthis['debug']('[debug][uncompress] uncompressing data');\n\t\tconst data = fs.readFileSync(Path.resolve('./jndb.dat'));\n\t\tlet buff = zlib.gunzipSync(data);\n\t\treturn new CompressedJSON(buff);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Let's do a harder exercise. In this code, your function receives a parameter data. You must modify the code below based on the following rules: Your function must always return a promise If data is not a number, return a promise rejected instantly and give the data "error" (in a string) If data is an odd number, return a promise resolved 1 second later and give the data "odd" (in a string) If data is an even number, return a promise rejected 2 seconds later and give the data "even" (in a string)
function job(data) { return new Promise((resolve, reject) => { if (isNaN(data)) { reject("error"); } if (data % 2 === 0) { setTimeout(() => { reject("even"); }, 2000); } else { setTimeout(() => { resolve("odd"); }, 1000); } }); }
[ "function evenOddTest (num) {\n\treturn new Promise(\n\t\t(resolve, reject) => {\n\t\t\t\n\t\t\tif( num % 2 == 0 )\n\t\t\t\treturn resolve(num * num);\n\t\t\telse\n\t\t\t\treturn reject('Odd number input');\n\t\t}\n\t);\n}", "function testNumber (number){\r\n \r\n return new Promise ((resolve,reject) =>{\r\n if (number <=10){\r\n setTimeout(()=>{\r\n resolve ('Success')\r\n },2000)\r\n }\r\n setTimeout(()=>{\r\n reject('Rejected')\r\n },2000)\r\n \r\n \r\n })\r\n }", "function checkOddNumberHandler(input) {\n\n var defer = $q.defer(); //instantiating a promise obj.\n\n //$timeout() method to delay 1 second.\n $timeout(function() {\n if (isNumberOdd(input)) {\n defer.resolve('Yes, an odd number');\n } else {\n defer.reject('Not an odd number');\n }\n }, 1000);\n return defer.promise;\n }", "function isEven(num) {\n return new Promise( (resolve, reject) => {\n if (Number.isInteger(num)) {\n if ( num % 2 == 0 ) {\n resolve(true)\n } else {\n resolve(false)\n }\n } else {\n reject(\"Number is not integer\")\n }\n })\n}", "function stepTwo(data) {\n \n console.log(\"Step two with data: \" + data);\n \n if (data !== true && data !== \"true\") {\n return new Promise(function(resolve, reject) {\n reject(new Error(\"Well that didn't work\"));\n });\n } else {\n return new Promise(function(resolve, reject) {\n resolve(process.argv[3] ? process.argv[3] : \"good\");\n });\n }\n}", "function ten(num) {\n return new Promise ((resolve,reject)=>{\n if (num > 10) {\n \n resolve(`right ${num} greater then 10`);\n } else {\n reject (`wrong, ${num} less then ten`);\n }\n }); \n}", "function myFunc (num){\r\n\r\n if(num>10){\r\n return Promise.resolve(num)\r\n }\r\n else{\r\n return Promise.reject(num)\r\n }\r\n\r\n}", "function doubleAfter2Seconds(x) {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n console.log('doubleAfter2Seconds for x =', x)\n if (typeof x === 'number') {\n resolve(x * 2);\n } else {\n reject('error nih')\n }\n }, 2000);\n });\n}", "function squarNumber(num) {\n return new Promise(async (resolve, reject) => {\n if(num % 2 == 0){\n resolve(num*num);\n }else{\n reject('Error, you have passed odd number')\n }\n\n });\n }", "function isNumberGreaterThanTen(num) {\n const myPromise = new Promise(function (resolve,reject) {\n if(num>10) {\n resolve(\"cool!\");\n }\n else {\n reject(\"boooo\");\n }\n });\n return myPromise;\n}", "function newFunc(num) {\n return new Promise((resolve, reject) => {\n if (num > 10) {\n setTimeout(() => {\n resolve('greater')\n }, 1000)\n } else {\n reject('smaller than number')\n }\n })\n}", "function example10() {\n console.log(\"Example 10\");\n async function f() {\n let res = await successfulPromise(1);\n alert(res);\n if (res) {\n res = await rejectedPromise(2).catch(reason => {\n console.log(\"Reason reject: \", reason);\n let shouldIContinue = false;\n // handle and decide if to continue the chain\n return shouldIContinue;\n });\n }\n /*\n based on the result of the previous call decide what to do \n */\n alert(res);\n if (res) {\n res = await successfulPromise(3);\n alert(res);\n } else {\n res = await successfulPromise(4);\n alert(res);\n }\n res = await successfulPromise(5);\n alert(res);\n }\n f();\n}", "function for_retrying() {\n return new Promise((resolve, reject) => {\n var value = Math.random();\n if (value < 0.1) {\n console.log('Test promise resolves. We are done.');\n resolve(value);\n } else {\n console.log(`Test promise rejects with value ${value}.`);\n reject(new Error(`Random resolve fail.`));\n }\n });\n }", "function testNum(x) {\n var prom = new es6_promise_1.Promise(function (resolve, reject) {\n if ((x) > 10) {\n resolve(' >10');\n }\n else\n reject('<=10');\n });\n return prom;\n}", "function messageFunction(num) {\n let a = num % 2;\n if (a === 0) {\n return 'even number';\n } else {\n return 'odd number';\n }\n}", "function tripleAfterThreeSeconds(number) {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n let tripled = number * 3;\n console.log(tripled);\n return resolve(tripled);\n }, 3000);\n });\n}", "function evenOrOdd (num) {\n \n if(num % 2 === 0) {\n return 'even';\n } else if(!(Number.isInteger(num))) {\n return 'Not a valid number!';\n } else {\n return 'odd';\n }\n}", "function promise(v){\n if(typeof v !== 'number') return Promise.reject({\n Error: 'error de tipografia',\n TipoError: v\n })\n\n return new Promise((res, reject) => {\n setTimeout(() => {\n res(/*`el valor ingresado es ${v} y su cuadrado es ${v * v}`*/\n {\n v,\n resultado: v * v\n }\n )\n }, Math.random() * 1000)\n })\n\n}", "function compareToTen(num){\n\tp=new Promise((resolve,reject)=>{\n\t\tif(num>=50){\n\t\t\tresolve(num+\" is greater than/equal to 50,Sucess!\")\n\t\t}else {\n\t\t\treject (num + \" is less than 50,Fail!\")\n\t\t}\n\t\t\n\t})\nreturn p\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to extract magnetic declination
function getMagDec() { if (document.solarCalc.trueMag[1].checked) { magDec=document.solarCalc.mDec.value; if (document.solarCalc.decEastWest[1].checked) { sign=-1; } else { sign=1; } magDec=magDec*sign; } else { magDec=0*1; } return magDec; }
[ "static getMagvar(lat, lon) {\n return GeoMath.magneticModel.declination(0, lat, lon, 2020);\n }", "magnetometer() {\n this.setup();\n\n //\n // taken from https://github.com/pimoroni/enviro-phat/pull/31/commits/78b1058e230c88cc5969afa210bb5b97f7aa3f82\n // as there is no real counterpart to struct.unpack in js\n //\n // in order to read multiple bytes the high bit of the sub address must be asserted\n this._mag[X] = twos_comp(this.i2c_bus.read_word_data(this.addr, OUT_X_L_M|0x80), 16);\n this._mag[Y] = twos_comp(this.i2c_bus.read_word_data(this.addr, OUT_Y_L_M|0x80), 16);\n this._mag[Z] = twos_comp(this.i2c_bus.read_word_data(this.addr, OUT_Z_L_M|0x80), 16);\n\n return new Vector(this._mag)\n }", "function magnetization() {\n let M = 0;\n for (let x = activeLeft; x <= activeRight; x++) {\n for (let y = activeTop; y <= activeBottom; y++) {\n M += lattice[x][y];\n }\n }\n return M / N; \n}", "function magBearing(Bearing, declination) {\n let magBearing = Number(Bearing) + declination;\n if (magBearing < 0) {\n magBearing = 360 + magBearing;\n } else if (magBearing > 360) {\n magBearing = magBearing - 360;\n }\n return magBearing;\n}", "function magneticFieldCalcualtion() {\n\t/** \n Magnetic field displayed on the Guass meter,\n B=C*2267*10-4 \n Where ‘B’ is the applied Magnetic field and ‘C’ is the current from the current source \n */\n\tmagnetic_field = current_value * 2267 * Math.pow(10, -4);\n\tmagneticfield_container.getChildByName(\"gaussianVal\").text = magnetic_field.toFixed(3);\n\n}", "magnetic() {\n const raw = this.read_mag_raw();\n return raw.map((x) => {\n return x * this._mag_mgauss_lsb / 1000.0;\n });\n }", "function magnetization() {\n let M = 0;\n for (let x = 0; x < gridSize; x++) {\n for (let y = 0; y < gridSize; y++) {\n M += lattice[x][y];\n }\n }\n return M / N; \n}", "read_mag_raw() {\n // Read the magnetometer\n const buff = this._read_bytes(_MAGTYPE, 0x80 | _LSM9DS1_REGISTER_OUT_X_L_M, 6);\n return struct.unpack_from('<hhh', buff.slice(0, 6));\n }", "magnitudeRead() {\n return this.readReg16(AS5048.MAGNMSB_REG);\n }", "get forceMagnitude() {}", "function declination(nday) {\n const Rdc = nday * 360 / 365; // earth orbit deviation (2)\n return (0.33281 - 22.984 * cosd(Rdc) - 0.3499 * cosd(2 * Rdc)\n - 0.1398 * cosd(3 * Rdc) + 3.7872 * sind(Rdc)\n + 0.03205 * sind(2 * Rdc) + 0.07187 * sind(3 * Rdc));\n}", "function fV_get_device_acceleration_magnitude(){\n\tvar magnitude = Math.sqrt((DEVICE_ACCELERATION.x * DEVICE_ACCELERATION.x) + (DEVICE_ACCELERATION.y * DEVICE_ACCELERATION.y) + (DEVICE_ACCELERATION.z * DEVICE_ACCELERATION.z)) \n\treturn magnitude;\n}", "function getFatMass() {\n var fm;\n if (isMale()) {\n fm = 0.988 * getBMI() + 0.242 * w + 0.094 * a - 30.18;\n } else {\n fm = 0.988 * getBMI() + 0.344 * w + 0.094 * a - 30.18;\n }\n return fm;\n }", "function magnetDetected() {\n rotation++\n}", "function dipoleMoment() {\n\n // Declare local variables\n var i;\n var dx, dy, dz, dipole;\n var DEBYE = 4.8032;\n var molecule = Mol();\n var numatoms=molecule[0].numatoms;\n\n // Calculate x,y,z components of dipole vector\n dx = 0.0;\n dy = 0.0;\n dz = 0.0;\n for ( i=1; i <= numatoms; i++ ) {\n dx += molecule[i].x * molecule[i].charge;\n dy += molecule[i].y * molecule[i].charge;\n dz += molecule[i].z * molecule[i].charge;\n }\n\n // Calculate length of dipole vector and scale to Debye units\n dipole = DEBYE * Math.sqrt(dx*dx+dy*dy+dz*dz);\n\n // Finished with dipoleMoment routine\n return dipole;\n }", "function MetroNM(){\r\n return Mnm*1e+9;\r\n}", "get displacement() {\n return this.material.uniforms.displacement.value;\n }", "function meter_to_feet(mtr)\n{\n\tif (mtr>0) {\n\t var feet=Math.round(((mtr*39.370079)/12)*100)/100;\n\t return feet;\n\t}\n\telse\n\t\treturn false;\n}//function", "constructor(gdLatitudeDeg, gdLongitudeDeg, altitudeMeters, timeMillis) {\n // The magnetic field at a given point, in nonoteslas in geodetic\n // coordinates.\n this.mX;\n this.mY;\n this.mZ;\n\n // Geocentric coordinates -- set by computeGeocentricCoordinates.\n this.mGcLatitudeRad = null;\n this.mGcLongitudeRad = null;\n this.mGcRadiusKm = null;\n\n const EARTH_REFERENCE_RADIUS_KM = 6371.2;\n\n // These coefficients and the formulae used below are from:\n // NOAA Technical Report: The US/UK World Magnetic Model for 2010-2015\n const G_COEFF = [\n [ 0.0 ],\n [ -29496.6, -1586.3 ],\n [ -2396.6, 3026.1, 1668.6 ],\n [ 1340.1, -2326.2, 1231.9, 634.0 ],\n [ 912.6, 808.9, 166.7, -357.1, 89.4 ],\n [ -230.9, 357.2, 200.3, -141.1, -163.0, -7.8 ],\n [ 72.8, 68.6, 76.0, -141.4, -22.8, 13.2, -77.9 ],\n [ 80.5, -75.1, -4.7, 45.3, 13.9, 10.4, 1.7, 4.9 ],\n [ 24.4, 8.1, -14.5, -5.6, -19.3, 11.5, 10.9, -14.1, -3.7 ],\n [ 5.4, 9.4, 3.4, -5.2, 3.1, -12.4, -0.7, 8.4, -8.5, -10.1 ],\n [ -2.0, -6.3, 0.9, -1.1, -0.2, 2.5, -0.3, 2.2, 3.1, -1.0, -2.8 ],\n [ 3.0, -1.5, -2.1, 1.7, -0.5, 0.5, -0.8, 0.4, 1.8, 0.1, 0.7, 3.8 ],\n [ -2.2, -0.2, 0.3, 1.0, -0.6, 0.9, -0.1, 0.5, -0.4, -0.4, 0.2, -0.8, 0.0 ]\n ];\n\n const H_COEFF = [\n [ 0.0 ],\n [ 0.0, 4944.4 ],\n [ 0.0, -2707.7, -576.1 ],\n [ 0.0, -160.2, 251.9, -536.6 ],\n [ 0.0, 286.4, -211.2, 164.3, -309.1 ],\n [ 0.0, 44.6, 188.9, -118.2, 0.0, 100.9 ],\n [ 0.0, -20.8, 44.1, 61.5, -66.3, 3.1, 55.0 ],\n [ 0.0, -57.9, -21.1, 6.5, 24.9, 7.0, -27.7, -3.3 ],\n [ 0.0, 11.0, -20.0, 11.9, -17.4, 16.7, 7.0, -10.8, 1.7 ],\n [ 0.0, -20.5, 11.5, 12.8, -7.2, -7.4, 8.0, 2.1, -6.1, 7.0 ],\n [ 0.0, 2.8, -0.1, 4.7, 4.4, -7.2, -1.0, -3.9, -2.0, -2.0, -8.3 ],\n [ 0.0, 0.2, 1.7, -0.6, -1.8, 0.9, -0.4, -2.5, -1.3, -2.1, -1.9, -1.8 ],\n [ 0.0, -0.9, 0.3, 2.1, -2.5, 0.5, 0.6, 0.0, 0.1, 0.3, -0.9, -0.2, 0.9 ]\n ];\n\n const DELTA_G = [\n [ 0.0 ],\n [ 11.6, 16.5 ],\n [ -12.1, -4.4, 1.9 ],\n [ 0.4, -4.1, -2.9, -7.7 ],\n [ -1.8, 2.3, -8.7, 4.6, -2.1 ],\n [ -1.0, 0.6, -1.8, -1.0, 0.9, 1.0 ],\n [ -0.2, -0.2, -0.1, 2.0, -1.7, -0.3, 1.7 ],\n [ 0.1, -0.1, -0.6, 1.3, 0.4, 0.3, -0.7, 0.6 ],\n [ -0.1, 0.1, -0.6, 0.2, -0.2, 0.3, 0.3, -0.6, 0.2 ],\n [ 0.0, -0.1, 0.0, 0.3, -0.4, -0.3, 0.1, -0.1, -0.4, -0.2 ],\n [ 0.0, 0.0, -0.1, 0.2, 0.0, -0.1, -0.2, 0.0, -0.1, -0.2, -0.2 ],\n [ 0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.1, 0.0 ],\n [ 0.0, 0.0, 0.1, 0.1, -0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.1, 0.1 ]\n ];\n\n const DELTA_H = [\n [ 0.0 ],\n [ 0.0, -25.9 ],\n [ 0.0, -22.5, -11.8 ],\n [ 0.0, 7.3, -3.9, -2.6 ],\n [ 0.0, 1.1, 2.7, 3.9, -0.8 ],\n [ 0.0, 0.4, 1.8, 1.2, 4.0, -0.6 ],\n [ 0.0, -0.2, -2.1, -0.4, -0.6, 0.5, 0.9 ],\n [ 0.0, 0.7, 0.3, -0.1, -0.1, -0.8, -0.3, 0.3 ],\n [ 0.0, -0.1, 0.2, 0.4, 0.4, 0.1, -0.1, 0.4, 0.3 ],\n [ 0.0, 0.0, -0.2, 0.0, -0.1, 0.1, 0.0, -0.2, 0.3, 0.2 ],\n [ 0.0, 0.1, -0.1, 0.0, -0.1, -0.1, 0.0, -0.1, -0.2, 0.0, -0.1 ],\n [ 0.0, 0.0, 0.1, 0.0, 0.1, 0.0, 0.1, 0.0, -0.1, -0.1, 0.0, -0.1 ],\n [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ]\n ];\n\n const BASE_TIME = (new Date(2010, 1, 1)).getTime();\n\n const MAX_N = G_COEFF.length; // Maximum degree of the coefficients.\n\n // The ratio between the Gauss-normalized associated Legendre functions and\n // the Schmid quasi-normalized ones. Compute these once staticly since they\n // don't depend on input variables at all.\n const SCHMIDT_QUASI_NORM_FACTORS = GeomagneticField.computeSchmidtQuasiNormFactors(MAX_N);\n\n // We don't handle the north and south poles correctly -- pretend that\n // we're not quite at them to avoid crashing.\n gdLatitudeDeg = Math.min(90.0 - 1e-5, Math.max(-90.0 + 1e-5, gdLatitudeDeg));\n\n this.computeGeocentricCoordinates(gdLatitudeDeg, gdLongitudeDeg, altitudeMeters);\n\n // Note: LegendreTable computes associated Legendre functions for\n // cos(theta). We want the associated Legendre functions for\n // sin(latitude), which is the same as cos(PI/2 - latitude), except the\n // derivate will be negated.\n const legendre = new LegendreTable(MAX_N - 1, Math.PI / 2.0 - this.mGcLatitudeRad);\n\n // Compute a table of (EARTH_REFERENCE_RADIUS_KM / radius)^n for i in\n // 0..MAX_N-2 (this is much faster than calling Math.pow MAX_N+1 times).\n let relativeRadiusPower = new Array(MAX_N + 2);\n relativeRadiusPower[0] = 1.0;\n relativeRadiusPower[1] = EARTH_REFERENCE_RADIUS_KM / this.mGcRadiusKm;\n\n for (let i = 2; i < relativeRadiusPower.length; ++i) {\n relativeRadiusPower[i] = relativeRadiusPower[i - 1] * relativeRadiusPower[1];\n }\n\n // Compute tables of sin(lon * m) and cos(lon * m) for m = 0..MAX_N --\n // this is much faster than calling Math.sin and Math.com MAX_N+1 times.\n let sinMLon = new Array(MAX_N);\n let cosMLon = new Array(MAX_N);\n sinMLon[0] = 0.0;\n cosMLon[0] = 1.0;\n sinMLon[1] = Math.sin(this.mGcLongitudeRad);\n cosMLon[1] = Math.cos(this.mGcLongitudeRad);\n\n for (let m = 2; m < MAX_N; ++m) {\n // Standard expansions for sin((m-x)*theta + x*theta) and\n // cos((m-x)*theta + x*theta).\n let x = m >> 1;\n sinMLon[m] = sinMLon[m-x] * cosMLon[x] + cosMLon[m-x] * sinMLon[x];\n cosMLon[m] = cosMLon[m-x] * cosMLon[x] - sinMLon[m-x] * sinMLon[x];\n }\n\n let inverseCosLatitude = 1.0 / Math.cos(this.mGcLatitudeRad);\n let yearsSinceBase = (timeMillis - BASE_TIME) / (365 * 24 * 60 * 60 * 1000);\n\n // We now compute the magnetic field strength given the geocentric\n // location. The magnetic field is the derivative of the potential\n // function defined by the model. See NOAA Technical Report: The US/UK\n // World Magnetic Model for 2010-2015 for the derivation.\n let gcX = 0.0; // Geocentric northwards component.\n let gcY = 0.0; // Geocentric eastwards component.\n let gcZ = 0.0; // Geocentric downwards component.\n\n for (let n = 1; n < MAX_N; n++) {\n for (let m = 0; m <= n; m++) {\n // Adjust the coefficients for the current date.\n let g = G_COEFF[n][m] + yearsSinceBase * DELTA_G[n][m];\n let h = H_COEFF[n][m] + yearsSinceBase * DELTA_H[n][m];\n // Negative derivative with respect to latitude, divided by\n // radius. This looks like the negation of the version in the\n // NOAA Techincal report because that report used\n // P_n^m(sin(theta)) and we use P_n^m(cos(90 - theta)), so the\n // derivative with respect to theta is negated.\n gcX += relativeRadiusPower[n+2]\n * (g * cosMLon[m] + h * sinMLon[m])\n * legendre.mPDeriv[n][m]\n * SCHMIDT_QUASI_NORM_FACTORS[n][m];\n // Negative derivative with respect to longitude, divided by\n // radius.\n gcY += relativeRadiusPower[n+2] * m\n * (g * sinMLon[m] - h * cosMLon[m])\n * legendre.mP[n][m]\n * SCHMIDT_QUASI_NORM_FACTORS[n][m]\n * inverseCosLatitude;\n // Negative derivative with respect to radius.\n gcZ -= (n + 1) * relativeRadiusPower[n+2]\n * (g * cosMLon[m] + h * sinMLon[m])\n * legendre.mP[n][m]\n * SCHMIDT_QUASI_NORM_FACTORS[n][m];\n }\n }\n\n // Convert back to geodetic coordinates. This is basically just a\n // rotation around the Y-axis by the difference in latitudes between the\n // geocentric frame and the geodetic frame.\n let latDiffRad = (gdLatitudeDeg * Math.PI / 180) - this.mGcLatitudeRad;\n this.mX = gcX * Math.cos(latDiffRad) + gcZ * Math.sin(latDiffRad);\n this.mY = gcY;\n this.mZ = - gcX * Math.sin(latDiffRad) + gcZ * Math.cos(latDiffRad);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an FS SDK client for the given environment.
function getFSClient(environment){ var config = { client_id: 'a02j00000098ve6AAA', redirect_uri: document.location.origin + '/', environment: environment }, token = Cookies.get(environment + '-token'); if(token){ config.access_token = token; } return new FamilySearch(config); }
[ "async forEnvironment(environment, mode) {\n const env = await this.resolveEnvironment(environment);\n const creds = await this.obtainCredentials(env.account, mode);\n return new sdk_1.SDK(creds, env.region, this.sdkOptions);\n }", "createClient( config = defaultConfig ) {\n const options = {\n space: config.CONTENTFUL_SPACE_ID,\n accessToken: config.CONTENTFUL_ACCESS_TOKEN\n }\n\n let client\n try {\n client = contentful.createClient( options )\n } catch ( error ) {\n throw new Error( 'Couldn\\'t create Contentful client. Probably some environment variables are missing.' )\n }\n\n return client\n }", "async function createApiClient() {\n const credentialsFilePath = './credentials.json';\n if (!fs.existsSync(credentialsFilePath)) {\n throw new Error(`${credentialsFilePath} not found`);\n }\n\n // Change this to a key in credentials.json after creating api keys\n log.info(`Creating api client against stack=${stackToUse}`);\n const credentials = JSON.parse(fs.readFileSync(credentialsFilePath));\n const credsToUse = credentials[stackToUse];\n if (!credsToUse) {\n throw new Error(`No credentials for stack=${stackToUse} in ${credentialsFilePath}`);\n }\n\n const apiClient = new ApiKeyClient(credsToUse.url, credsToUse.accessKey, credsToUse.secretKey);\n apiClient.companyId = credsToUse.companyId;\n return apiClient;\n}", "function sdkClientMethodFactory(params) {\n var log = params.settings.log;\n var clientInstance = (0, sdkClient_1.sdkClientFactory)(params);\n return function client() {\n if (arguments.length > 0) {\n throw new Error('Shared Client not supported by the storage mechanism. Create isolated instances instead.');\n }\n log.debug(constants_1.RETRIEVE_CLIENT_DEFAULT);\n return clientInstance;\n };\n}", "function initializeClientApp(){\n let ClientApp = window.purecloud.apps.ClientApp;\n let envParam = urlParams.get(ENV_QUERY_PARAM);\n\n if(!envParam){\n envParam = localStorage.getItem('clientAppEnvironment') || 'mypurecloud.com';\n }\n vonageClientApp = new ClientApp({ pcEnvironment: envParam });\n localStorage.setItem('clientAppEnvironment', envParam);\n}", "function createClient() {\n return new L4.ClientEndpoint();\n}", "function sdkClientFactory(params, isSharedClient) {\n var sdkReadinessManager = params.sdkReadinessManager, syncManager = params.syncManager, storage = params.storage, signalListener = params.signalListener, settings = params.settings, telemetryTracker = params.telemetryTracker, uniqueKeysTracker = params.uniqueKeysTracker;\n return (0, objectAssign_1.objectAssign)(\n // Proto-linkage of the readiness Event Emitter\n Object.create(sdkReadinessManager.sdkStatus), \n // Client API (getTreatment* & track methods)\n (0, clientInputValidation_1.clientInputValidationDecorator)(settings, (0, client_1.clientFactory)(params), sdkReadinessManager.readinessManager), \n // Sdk destroy\n {\n destroy: function () {\n // record stat before flushing data\n if (!isSharedClient)\n telemetryTracker.sessionLength();\n // Stop background jobs\n syncManager && syncManager.stop();\n var flush = syncManager ? syncManager.flush() : Promise.resolve();\n return flush.then(function () {\n // Cleanup event listeners\n sdkReadinessManager.readinessManager.destroy();\n signalListener && signalListener.stop();\n // Release the API Key if it is the main client\n if (!isSharedClient)\n (0, apiKey_1.releaseApiKey)(settings.core.authorizationKey);\n if (uniqueKeysTracker)\n uniqueKeysTracker.stop();\n // Cleanup storage\n return storage.destroy();\n });\n }\n });\n}", "function createClient() {\n\treturn Asana.Client.create({\n\t\tclientId: clientId,\n\t\tclientSecret: clientSecret,\n\t\tredirectUri: global.config.get(\"asana.redirect_uri\")\n\t});\n}", "function createClient({ headers }) {\n return new ApolloClient({\n cache: new InMemoryCache(),\n link: errorLink.concat(createUploadLink({ uri: `http://localhost:4000` })),\n uri: `http://localhost:4000`,\n request: operation => {\n operation.setContext({\n fetchOptions: {\n credentials: \"include\"\n },\n headers\n });\n }\n });\n}", "function ClientFactory(config) {\n return new stormpath.Client(\n new stormpathConfig.Loader([\n new configStrategy.ExtendConfigStrategy(config)\n ])\n );\n}", "async function createClient() {\r\n let auth0Client = await createAuth0Client({\r\n domain: config.domain,\r\n client_id: config.clientId,\r\n });\r\n\r\n return auth0Client;\r\n}", "createClient(callback) {\n request.post(config.agave.url + 'clients/v2', {\n headers: {\n Authorization: userAuth\n },\n body: {\n clientName: client.config.name,\n description: client.config.clientDescription\n }\n }, callback);\n }", "createClient() {\n switch (this.config.type) {\n case 'azureBlob': return new __1.AzureBlobClient(this.config);\n default: throw new Error(`NotImplemented`);\n }\n }", "function createClient() {\n return Asana.Client.create({\n clientId: clientId,\n clientSecret: clientSecret,\n redirectUri: redirect_uri\n });\n}", "function createEnvironment() {\n\tvar environment = {\n\t};\n\n\treturn environment;\n}", "function clientFactory() {\n // we use promisify in order to encapsulate node-style callbacks\n // into more cleaner JS Promises\n\n return solr.createClient({\n host: process.env.SOLR_HOST,\n port: process.env.SOLR_PORT,\n core: process.env.SOLR_CORE,\n solrVersion: 6.5,\n });\n}", "async function createClient(configPath) {\n let auth = new google.auth.GoogleAuth({\n keyFile: configPath,\n scopes,\n });\n\n return google.sheets({\n auth,\n version: 'v4',\n });\n}", "static async build(globalOptions) {\n // Make the client\n const iotClient = new IotClient(globalOptions);\n // Set the client up\n await iotClient.setup();\n // Return the client\n return iotClient;\n }", "async function createClient({ email, key } = {}) {\n let jwtClient = new google.auth.JWT(email, null, key, scopes);\n await jwtClient.authorize();\n return google.sheets({\n auth: jwtClient,\n version: 'v4'\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively convert the BN tree to HTML BN = BookmarkNode to "print" to HTML Returns: a String
function BN_toHTML (BN) { let html; let type = BN.type; if (type == "folder") { html = "<DL><DT>"+BN.title+"</DT>"; let children = BN.children; if (children != undefined) { let len = children.length; for (let i=0 ; i<len ;i++) { html += "<DD>"+BN_toHTML(children[i])+"</DD>"; } } html += "</DL>"; } else if (type == "bookmark") { html = "<A HREF=\""+BN.url+"\">"+BN.title+"</A>"; } else { html = "<HR>"; } return(html); }
[ "function BN_toPlain (BN, indent = \"\") {\r\n let plain;\r\n let type = BN.type;\r\n if (type == \"folder\") {\r\n\tplain = indent+BN.title;\r\n\tlet children = BN.children;\r\n\tif (children != undefined) {\r\n\t let len = children.length;\r\n\t for (let i=0 ; i<len ;i++) {\r\n\t\tplain += \"\\n\"+BN_toPlain(children[i], indent + \"\\t\");\r\n\t }\r\n\t}\r\n }\r\n else if (type == \"bookmark\") {\r\n\tplain = indent+BN.url;\r\n }\r\n else {\r\n\tplain = indent+\"--------------------\";\r\n }\r\n return(plain);\r\n}", "function formatNode (tree, node, indent) {\n let str = ''\n for (let char in node.children) {\n const childNode = node.children[char]\n let end = tree.right\n if (childNode.end !== undefined) end = childNode.end\n const substr = tree.text.slice(childNode.start, end + 1).join('')\n str += ' '.repeat(indent) + childNode.id + '. \"' + substr + '\" | ' + childNode.start + '-' + end\n if (childNode.link) {\n str += ' -> ' + childNode.link.id\n }\n str += '\\n' + formatNode(tree, childNode, indent + 3)\n }\n return str\n}", "function render(tree)\r\n{\r\n s = \"\";\r\n\r\n if (tree == null || tree.type == \"unkn\")\r\n return \"\";\r\n\r\n // Innovative head-recursion.\r\n if (tree.type == \"tag\")\r\n {\r\n s += bb(tree.c)[0]; // Opening html tag.\r\n s += render(tree.child); // Down.\r\n s += bb(tree.c)[1]; // Closing html tag.\r\n s += render(tree.next); // Forward.\r\n }\r\n else if (tree.type == \"text\")\r\n s += ( tree.c + render(tree.next) );\r\n return s;\r\n}", "function visTreeHtml(n) {\n if (isLeaf(n)) {\n return ['<br/>chr = [', n.chr, '], freq = ', n.freq];\n }\n\n return ['<ul><li>freq = ', n.freq, '</li><li>left', \n visTreeHtml(n.left), '</li><li>right',\n visTreeHtml(n.right), '</li></ul>'];\n}", "function toHTML(node) {\n const rootNode = tree.createDocumentFragment();\n tree.appendChild(rootNode, node);\n return parser.serialize(rootNode);\n}", "function printTree(html) {\r\n html = html.match(/<[a-z]+|<\\/[a-z]+>|./ig);\r\n if (!html) return '';\r\n var indent = '\\n', tree = [];\r\n for (var i = 0; i < html.length; i += 1) {\r\n var token = html[i];\r\n if (token.charAt(0) === '<') {\r\n if (token.charAt(1) === '/') { //dedent on close tag\r\n indent = indent.slice(0,-2);\r\n if (html[i+1] && html[i+1].slice(0,2) === '</') //but maintain indent for close tags that come after other close tags\r\n token += indent.slice(0,-2);\r\n }\r\n else { //indent on open tag\r\n tree.push(indent);\r\n indent += ' ';\r\n }\r\n\r\n token = token.toLowerCase();\r\n }\r\n\r\n tree.push(token);\r\n }\r\n return tree.join('').slice(1);\r\n}", "function convertTreeToText(tree){\n var children=$(tree).children();\n if (children.length){ \n $.each(children, function(){\n /* append node name */\n if(this.nodeName==\"SPAN\" && this.attributes['class'] && this.attributes['class'].nodeValue==\"nodeName\"){\n if(this.innerText==\"br\") new_xml += \"<br/\";\n else new_xml+= \"<\"+this.innerText;\n /* store node names in array to use for closing tags */\n arr.push(this.innerText);\n }\n /* append attribute name */\n else if(this.nodeName==\"SPAN\" && this.attributes['class'] && this.attributes['class'].nodeValue==\"attributeName\"){\n new_xml+= \" \"+this.innerText;\n return true;\n }\n /* append attribute value */\n else if(this.nodeName==\"SPAN\" && this.attributes['class'] && this.attributes['class'].nodeValue==\"attributeValue\"){\n new_xml+= '=\"'+this.innerText+'\"';\n return true;\n }\n /* if addAttribute button then close the tag */\n else if(this.nodeName==\"IMG\" && this.attributes['class'] && this.attributes['class'].nodeValue==\"addAttribute\"){\n new_xml+= '>';\n return true;\n }\n /* append node text */\n else if(this.nodeName==\"LI\" && this.attributes['class'] && this.attributes['class'].nodeValue==\"nodeText\"){\n new_xml+= this.innerText;\n return true;\n }\n /* if node has any child, call function for that child */\n if(this.nodeName!=\"DIV\" || (this.nodeName=='LI' && this.attributes['class'] && this.attributes['class'].nodeValue!=\"emptyText\")){\n convertTreeToText(this);\n }\n })\n /* add the closing tag using node name values in arr */\n if ($(tree).prop('nodeName')==\"LI\"){\n if($(tree).prop('firstChild').className=='nodeText'){\n new_xml += $(tree).prop('firstChild').innerText;\n }\n if(arr[arr.length-1]==\"br\") arr.pop();\n else new_xml += \"</\"+arr.pop()+\">\";\n }\n }\n}", "function displayTreeBN (BN) {\n if ((options.trashEnabled && options.trashVisible)\n\t || (BN.inBSP2Trash != true)\n\t ) { // Don't display BNs in BSP2 trash, except on debug\n\tinsertBookmarkBN(BN);\n\n\t// If there are children, recursively display them\n\tlet children;\n\tif ((BN.type == \"folder\") && ((children = BN.children) != undefined)) {\n\t let len = children.length;\n\t for (let i=0 ; i<len ; i++) {\n\t\tdisplayTreeBN(children[i]);\n\t }\n\t}\n }\n}", "postPrint()\r\n {\r\n var tree = ''\r\n\r\n function postorder(node)\r\n {\r\n if(node != null) \r\n { \r\n postorder(node.left)\r\n postorder(node.right)\r\n tree += node.data + '->'\r\n }\r\n }\r\n\r\n postorder(this.root)\r\n console.log(tree)\r\n }", "function asHTML(node){\n\n\tif (isTextNode(node)){\n\t\treturn escapeHTML(node.nodeValue);\n\t} else if (node.childNodes.length == 0){\n\t\treturn \"<\" + node.nodeName + \"/>\";\n\t} else {\n\t\treturn \"<\" + node.nodeName + \">\" +\n\t\t\t\t\t\tmap(asHTML, node.childNodes).join(\"\") +\n\t\t\t\t\t\t\"</\" +node.nodeName + \">\";\n\t}\n\n}", "function BN_copy (BN) {\r\n let node = new BookmarkNode (BN.id, BN.type, BN.level, BN.parentId, BN.dateAdded, BN.protect, \r\n\t \t\t\t\t\t\t BN.title, BN.faviconUri, BN.fetchedUri, BN.url,\r\n\t \t\t\t\t\t\t undefined, BN.dateGroupModified,\r\n\t \t\t\t\t\t\t BN.inBSP2Trash, BN.trashDate, BN.unmodifiable);\r\n let children = BN.children;\r\n if (children != undefined) {\r\n\tlet len = children.length;\r\n\tlet nodeChildren = node.children = new Array (len);\r\n\tlet j = 0;\r\n\tfor (let i=0 ; i<len ; i++) {\r\n\t nodeChildren[j++] = BN_copy(children[i]);\r\n\t}\r\n }\r\n return(node);\r\n}", "function nodesToHTML(nodes) {\n return '\\n<ul>' + nodes.reduce(reduceNodesToHTML) + '</ul>\\n';\n}", "toString() {\n return Strophe.serialize(this.nodeTree);\n }", "function DOMtoString(document_root) {\n var html = '',\n node = document_root.firstChild;\n while (node) {\n switch (node.nodeType) {\n case Node.ELEMENT_NODE:\n html += node.innerText;\n break;\n case Node.TEXT_NODE:\n html += node.innerText;\n break;\n case Node.CDATA_SECTION_NODE:\n //html += '<![CDATA[' + node.nodeValue + ']]>';\n break;\n case Node.COMMENT_NODE:\n //html += '<!--' + node.nodeValue + '-->';\n break;\n case Node.DOCUMENT_TYPE_NODE:\n // (X)HTML documents are identified by public identifiers\n //html += \"<!DOCTYPE \" + node.name + (node.publicId ? ' PUBLIC \"' + node.publicId + '\"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' \"' + node.systemId + '\"' : '') + '>\\n';\n break;\n }\n node = node.nextSibling;\n }\n return html;\n}", "prePrint()\r\n {\r\n var tree = ''\r\n\r\n function preorder(node)\r\n {\r\n if(node != null) \r\n { \r\n tree += node.data + '->'\r\n preorder(node.left)\r\n preorder(node.right)\r\n }\r\n }\r\n\r\n preorder(this.root)\r\n console.log(tree)\r\n }", "function netHTML (buffer, sb) {\r\n\tvar articulated = netUnidecodes (buffer, new Array(), false);\r\n\tif (articulated.length == 0) {sb.push('<span>'); sb.push(buffer);}\r\n\telse {\r\n\t\tsb.push('<span title=\"'); sb.push(buffer); sb.push('\">');\r\n\t\tfor (var i=0, L=articulated.length; i < L; i++)\r\n\t\t\tnetHTML(articulated[i], sb);\r\n\t}\r\n\tsb.push('</span>');\r\n\treturn sb\r\n}", "function renderBookmarksAsHTML( bookmarks ) {\n var container = document.querySelector('.bookmark-container');\n\n bookmarks.map( createBookmarkHTML ).forEach(function( bookmarkHTML ){\n container.innerHTML += bookmarkHTML;\n });\n}", "function processNode(node) {\n if (node.tagName !== 'BR' && node.tagName !== 'HR' && node.tagName !== 'IMG' && node.innerHTML.length === 0)\n setContent(node, '');\n else if (node.tagName === 'P' || node.tagName === 'DIV')\n setContent(node, '\\n\\n' + node.innerHTML + '\\n');\n else if (node.tagName === 'BR')\n setContent(node, '\\n\\n');\n else if (node.tagName === 'HR')\n setContent(node, '\\n***\\n');\n else if (node.tagName === 'H1')\n setContent(node, '\\n# ' + nltrim(node.innerHTML) + '\\n');\n else if (node.tagName === 'H2')\n setContent(node, '\\n## ' + nltrim(node.innerHTML) + '\\n');\n else if (node.tagName === 'H3')\n setContent(node, '\\n### ' + nltrim(node.innerHTML) + '\\n');\n else if (node.tagName === 'H4')\n setContent(node, '\\n#### ' + nltrim(node.innerHTML) + '\\n');\n else if (node.tagName === 'H5')\n setContent(node, '\\n##### ' + nltrim(node.innerHTML) + '\\n');\n else if (node.tagName === 'H6')\n setContent(node, '\\n###### ' + nltrim(node.innerHTML) + '\\n');\n else if (node.tagName === 'B' || node.tagName === 'STRONG')\n setContent(node, '**' + nltrim(node.innerHTML) + '**');\n else if (node.tagName === 'I' || node.tagName === 'EM')\n setContent(node, '_' + nltrim(node.innerHTML) + '_');\n else if (node.tagName === 'A')\n setContent(node, '[' + nltrim(node.innerHTML) + '](' + nltrim(node.href) + (node.title ? ' \"' + nltrim(node.title) + '\"' : '') + ')');\n else if (node.tagName === 'IMG')\n setContent(node, '![' + (node.alt ? nltrim(node.alt) : '') + '](' + nltrim(node.src) + (node.title ? ' \"' + nltrim(node.title) + '\"' : '') + ')');\n else if (node.tagName === 'BLOCKQUOTE') \n node.outerHTML = '\\n\\n' + prefixBlock('> ', trim(node.textContent)) + '\\n\\n';\n else if (node.tagName === 'UL' || node.tagName === 'OL') \n setContent(node, '\\n\\n' + node.innerHTML + '\\n\\n');\n else if (node.tagName === 'CODE') {\n if (node._bfs_parent.tagName == 'PRE') \n setContent(node, prefixBlock(' ', node.innerHTML) + '\\n');\n else\n setContent(node, '`' + nltrim(node.innerHTML) + '`');\n } else if (node.tagName === 'LI') {\n if (node._bfs_parent.tagName === 'OL') \n setContent(node, '1. ' + trim(prefixBlock(' ', trim(node.innerHTML), true)) + '\\n\\n');\n else\n setContent(node, '- ' + trim(prefixBlock(' ', trim(node.innerHTML), true)) + '\\n\\n');\n } else \n setContent(node, node.innerHTML);\n }", "function breadthTraverse(tree) {\n\tlet buffer = \"\";\n\tif(tree == null) {\n\t\treturn buffer;\n\t}\n\tlet temp = tree;\n\tlet height = 0;\n\twhile(temp != null) {\n\t\ttemp = temp.left;\n\t\t++height;\n\t}\n\tfor(let i = 1; i <= height; ++i) {\n\t\tbuffer += printLevel(tree, i) + \"<br />\";\n\t}\n\treturn buffer;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function will grab a random animal and a random breakfast item and make a meal. it will then tweet out that meal
function breakFast(){ var test = animals(); var breakfast = bf[Math.floor(Math.random()*bf.length)]; var bfjuice = animals(); var temp = m.drinkTemp[Math.floor(Math.random()*m.drinkTemp.length)]; params = { status: 'today for breakfast @realdonaldtrump is having ' + test + '-dick ' + breakfast + ' with a tall glass of '+ temp + " "+ bfjuice + ' urine' } T.post('statuses/update', params, function(err, data, response){ if(err){ console.log(err) } console.log("post successfull!") }) }
[ "function breakFast(){ \n var test = animals();\n var breakfast = bf[Math.floor(Math.random()*bf.length)];\n const params = {\n status: 'today for breakfast @realdonaldtrump is having ' + test + '-dick ' + breakfast \n }\n whChef.post('statuses/update', params);\n}", "function makeMeal() {\n const numItems = 1 + Math.floor((Math.random() * 4)); //Determine how many food items\n const meal = [];\n for (let i = 0; i < numItems; i++) {\n const itemID = Math.floor(Math.random() * foodsList.length);\n const servings = Math.floor(Math.random() * 4) + 1;\n meal.push([\n foodItems[itemID],\n servings\n ]);\n }\n return meal;\n}", "generateRandomMeal() {\n const appetizer = this.getRandomDishFromCourse('appetizers');\n const main = this.getRandomDishFromCourse('mains');\n const dessert = this.getRandomDishFromCourse('desserts');\n const totalPrice = appetizer.price + main.price + dessert.price;\n return `Your random meal:\\n\\nAppetizer:\\t${appetizer.name}\\nMain:\\t\\t${main.name}\\nDessert:\\t${dessert.name}\\n\\nTotal price:\\t${totalPrice}`;\n }", "generateRandomMeal() {\r\n let appetizer = this.getRandomDishFromCourse('appetizers');\r\n let main = this.getRandomDishFromCourse('mains');\r\n let dessert = this.getRandomDishFromCourse('desserts');\r\n let price = appetizer.price + main.price + dessert.price;\r\n return `Your $${price} meal consists of : ${appetizer.name}, ${main.name} and ${dessert.name}.`\r\n }", "generateRandomMeal() {\r\n const appetizer = this.getRandomDishFromCourse(\"appetizers\"); // Variable to store a random appetizer from the array\r\n const main = this.getRandomDishFromCourse(\"mains\"); // Variable to store a random main from the array\r\n const dessert = this.getRandomDishFromCourse(\"desserts\"); // Variable to store a random dessert from the array\r\n const totalPrice = appetizer.price + main.price + dessert.price; // Variable to hold the total cost of the randomized meal\r\n return `Your meal is ${appetizer.name}, ${main.name}, and ${dessert.name}. The total price is ${totalPrice}.`; // Returns a three course meal with total price\r\n }", "function randomBones() \n{\n tedNumber = Math.floor(Math.random() * 101) + 19;\n\n matureTeddy= Math.floor(Math.random()*12)+1;\n sillyTeddy=Math.floor(Math.random()*12)+1;\n taxiTeddy=Math.floor(Math.random()*12)+1;\n bearTeddy=Math.floor(Math.random()*12)+1;\n\n}", "function getRandomMeal() {\n const getMeal = async () => {\n const singleMeal = await getRandom();\n if (singleMeal) setMeal(singleMeal);\n setStatus(true);\n };\n getMeal();\n }", "generateRandomMeal() {\n let appetizer = menu.getRandomDishFromCourse(\"appetizers\");\n let main = menu.getRandomDishFromCourse(\"mains\");\n let dessert = menu.getRandomDishFromCourse(\"desserts\");\n let totalPrice = appetizer.price + main.price + dessert.price;\n return `Your appetizer (${appetizer.name}), main course (${main.name}), and dessert (${dessert.name}) will cost $${totalPrice} plus tax. A 20% gratuity is appreciated. `;\n }", "function hunt(traveler) {\n let huntSuccess = ((getRandomIntInclusive(0, 1)) * 100);\n console.log(huntSuccess);\n traveler.setFood(huntSuccess);\n }", "function pickRandomTweet() {\n\t\t\t\t\t// Store tweetNumber so we can change which bird is highlighted\n\t\t\t\t\ttweetNumber = Math.floor(Math.random() * fakeTweets.length);\n\t\t\t\t\tconsole.log(tweetNumber)\n\t\t\t\t\tvar randomTweet = fakeTweets[tweetNumber];\n\t\t\t\t\t// Log the random tweet. Finished app should display the Tweet on-screen instead\n\t\t\t\t\tconsole.log(randomTweet);\n\t\t\t\t\t//displayTweet(randomTweet);\n\n\t\t\t\t}", "async function getRandomMeal() {\n \n const resp = await fetch(\"https://www.themealdb.com/api/json/v1/1/random.php\");\n \n const respData = await resp.json();\n const randomMeal = respData.meals[0];\n\n console.log(randomMeal);\n\n addMeal(randomMeal, true);\n}", "function hunt(traveler){\n let prey = Math.floor(Math.random() * 10) + 1;\n console.log(\"hunt \" + prey);\n if (prey % 2==0) {\n traveler.food = traveler.getFood() + 100;\n console.log(\"hunt new food: \" + traveler.getFood());\n }\n }", "async function getRandomMeal() {\n\tconst response = await fetch(apiURL);\n\tconst responseJson = await response.json();\n\n\tconst { meals } = responseJson;\n\tconst theMeal = meals[0];\n\n\tdisplayMeal(theMeal);\n}", "function eat() {\n var lastFoodIndex = this.food.length;\n var randoFoodIndex = Math.floor(Math.random()*(lastFoodIndex - 0) + 0);\n var foodEaten = this.food[randoFoodIndex];\n\n console.log(this.name + ' ate ' + foodEaten);\n}", "function getRandomMeal(){\n // clear meals and heading\n mealsEl.innerHTML = '';\n resultHeading.innerHTML = '';\n\n fetch(`https://themealdb-service.herokuapp.com/menu/meal/random`)\n .then(res => res.json())\n .then(data =>{\n const meal = data.meals[0];\n\n addMealToDOM(meal);\n })\n }", "function trade(){\n\tday++;\n\teatFood();\n\tchangeWeather();\n\tvar canTrade = 1;\n\tvar tradeAmt = [0,0];\n\tvar tradeItem = [\"\",\"\"];\n\tvar rand = [0,0];\n\tvar randPart = [0,0];\n\t//If 1 then someone wants to trade\n\tif(Math.floor(Math.random() * (2))){\n\t\tvar i;\n\t\t//Generating the trade offer\n\t\tfor(i = 0; i < 2; i++){\n\t\t\trand[i] = Math.floor(Math.random() * (5)) + 1;\n\t\t\tif(i == 1){\n\t\t\t\tif(rand[1] == rand[0]){if(rand[1] == 5) rand[1]--; else rand[1]++;}\n\t\t\t}\n\t\t\tif(rand[i] == FOOD) {tradeAmt[i] = 100; tradeItem[i] = \"pounds of food\"; if(i == 0 && job == \"Merchant\") tradeAmt[i] += 50;}\n\t\t\telse if(rand[i] == BAIT) {tradeAmt[i] = 200; tradeItem[i] = \"bait\"; if(i == 0 && job == \"Merchant\") tradeAmt[i] += 100;}\n\t\t\telse if(rand[i] == OXEN) {tradeAmt[i] = 1; tradeItem[i] = \"ox\"; if(i == 0 && job == \"Merchant\") tradeAmt[i]++;}\n\t\t\telse if(rand[i] == CLOTHING) {tradeAmt[i] = 2; tradeItem[i] = \"sets of clothing\"; if(i == 0 && job == \"Merchant\") tradeAmt[i] += 2;}\n\t\t\telse if(rand[i] == PARTS){\n\t\t\t\trandPart[i] = Math.floor(Math.random() * (3))\n\t\t\t\tif(randPart[i] == WHEEL) {tradeAmt[i] = 1; tradeItem[i] = \"wagon wheel\"; if(i == 0 && job == \"Merchant\") tradeAmt[i]++;}\n\t\t\t\telse if(randPart[i] == AXLE) {tradeAmt[i] = 1; tradeItem[i] = \"wagon axle\"; if(i == 0 && job == \"Merchant\") tradeAmt[i]++;}\n\t\t\t\telse if(randPart[i] == TONGUE) {tradeAmt[i] = 1; tradeItem[i] = \"wagon tongue\"; if(i == 0 && job == \"Merchant\") tradeAmt[i]++;}\n\t\t\t}\n\t\t}\n\t\t//Make sure you have enough to trade\n\t\tif(rand[1] == PARTS){if(parts[randPart[1]] < 1) canTrade = 0;}\n\t\telse if(supplies[rand[1]] < tradeAmt[1]) canTrade = 0;\n\t\tvar t = \"<p>A fellow traveler would like to offer you \" + tradeAmt[0] + \" \" + tradeItem[0] + \" for \" + tradeAmt[1] + \" \" + tradeItem[1];\n\t\tif(canTrade) t += \".<br>Do you accept the offer?</p> <button id='acceptTrade' class='button'>Yes</button><br><button id='back' class='button'>No</button>\";\n\t\telse t += \",<br>but you do not have the supplies to trade.</p> <button id='back' class='button'>Back</button>\";\n\t\tdocument.getElementsByClassName(\"container\")[0].innerHTML = t;\n\t}\n\t//No one wants to trade\n\telse{\n\t\tdocument.getElementsByClassName(\"container\")[0].innerHTML = \"<p>There is no trade offer today.</p><button id='back' class='button'>Back</button>\"\n\t}\n\t$(\"#acceptTrade\").click(function() {$(this).unbind(); $(\"#back\").unbind(); tradeAccept(rand, tradeAmt, randPart);});\n\t$(\"#back\").click(function(){$(this).unbind(); $(\"#acceptTrade\").unbind(); locationInfo();});\n}", "function randomTaunt()\r\n{ \r\n\tif( getTP() > 1 ) { \r\n\t\tsay(randomCitation()); \r\n\t} \r\n}", "function randomAnimal() { return randomPick( animals ); }", "function getRandomMeal() {\n\n // Ajax call to TheMealDB API for a random meal\n $.ajax({\n url: \"https://www.themealdb.com/api/json/v1/1/random.php\",\n method: \"GET\"\n }).then(function(response) {\n\n // Gets the random meal out of the returned array\n var randomMeal = response.meals[0];\n\n // Runs the renderMealCard() method with the random meal\n renderMealCard(randomMeal);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show the agent typing
function agentTyping(data) { logger.debug("agentTyping", data); if (data.agentTyping) { $(jqe(lpChatID_lpChatAgentType)).css("visibility","visible"); } else { $(jqe(lpChatID_lpChatAgentType)).css("visibility", "hidden"); } }
[ "function showTypingStatus() {\r\n\r\n\t//dnp test\r\n\t//const user_data = $('#user_data')[0];\r\n\t// const un = getUserData('loggedusername');\r\n\t// const ui = getUserData('loggeduserid');\r\n\t// const tu = getUserData('touserid');\r\n\t// const tn = getUserData('tousername');\r\n\t// setUserData({\r\n\t// \tattr: 'test',\r\n\t// \tvalue: 'doug'\r\n\t// });\r\n\t// const test = getUserData('hey');\r\n\r\n\tloadTypingStatus(ds.loggedUserId, ds.toUserId);\r\n\r\n\t// $('li.contact.active').each(function () {\r\n\t// \tvar to_user_id = $(this).attr('data-touserid');\r\n\t// \tconst tu = getUserData('loggeduserid');\r\n\r\n\t// \t// dnp get status of typing\r\n\r\n\r\n\r\n\t// });\r\n}", "typedReply() {\n this.get('queuedForTyping').forEach(msg => this.send(\"popup\", msg));\n }", "function typeAreYouSure() {\n $(\"#scene\").typed({\n strings: [areYouSureText],\n typeSpeed: 200,\n loop: false,\n contentType: 'html',\n showCursor: false,\n callback: areYouSurePrompt\n })\n}", "function typeIt() {\n clearCanvas();\n disableCanvas();\n $(settings.typed, context).show();\n $(settings.drawIt, context).bind('click.signaturepad', function (e) {\n e.preventDefault();\n drawIt();\n });\n $(settings.typeIt, context).unbind('click.signaturepad');\n $(settings.typeIt, context).bind('click.signaturepad', function (e) {\n e.preventDefault();\n });\n $(settings.output, context).val('');\n $(settings.drawIt, context).removeClass(settings.currentClass);\n $(settings.typeIt, context).addClass(settings.currentClass);\n $(settings.sig, context).removeClass(settings.currentClass);\n $(settings.drawItDesc, context).hide();\n $(settings.clear, context).hide();\n $(settings.typeItDesc, context).show();\n }", "function startTyping() {\n var options = {\n strings: [\n \"mobile applications\",\n \"websites\",\n \"electronics\",\n \"your life easier\"\n ],\n typeSpeed: 35,\n backSpeed: 35,\n startDelay: 1000,\n backDelay: 1000\n };\n\n new Typed(\"#what-i-do span\", options);\n}", "runShowTypingState() {\n // TODO: figure out if this has to be run on up/down\n if (this.get('shouldShowTypingState')) {\n this.set('showTypingState', true);\n run.later(this, () => {\n this.set('showTypingState', false);\n }, this.get('typingStateTimeout'));\n }\n }", "function typeIt() {\n clearCanvas();\n disableCanvas();\n $(settings.typed, context).show();\n\n $(settings.drawIt, context).bind('click.signaturepad', function(e) { e.preventDefault(); drawIt(); });\n $(settings.typeIt, context).unbind('click.signaturepad');\n $(settings.typeIt, context).bind('click.signaturepad', function(e) { e.preventDefault(); });\n\n //$(settings.output, context).val('');\n updateOutputField('');\n\n $(settings.drawIt, context).removeClass(settings.currentClass);\n $(settings.typeIt, context).addClass(settings.currentClass);\n $(settings.sig, context).removeClass(settings.currentClass);\n\n $(settings.drawItDesc, context).hide();\n $(settings.clear, context).hide();\n $(settings.typeItDesc, context).show();\n }", "function typeWriter() {\n typebutton.style.display = \"none\";\n if (i < txt.length) {\n document.getElementById(\"demo\").innerHTML += txt.charAt(i);\n i++;\n setTimeout(typeWriter, speed);\n }\n //else{\n //console.log(\"finished typing\");\n //timer = setTimeout(gawdWaiting, 9000);\n }", "function timVineTypes(){\n\t var typingObject;\n\t var typePosition = 0;\n\t var theTypingTextArray = $scope.timVineJokes.line.split(\"\");\n\t var typingNow = function(){\n\n\t\t $scope.right.text += theTypingTextArray[typePosition];\n\t\t typePosition++;\n\t\t if (typePosition >= theTypingTextArray.length){ typePosition = 0; }\n\t\t document.getElementById('previewScroll').scrollTop = 9999999;\n\t\t document.getElementById('chatHook').scrollTop = 9999999;\n\t\t document.getElementById('rightText').scrollTop = 9999999;\n\t\t typingObject = $timeout(typingNow,80); \n\n\t }\n\t typingNow();\n\n }", "function type() {\n const text = words[wordIndex].getAttribute(\"data-text\");\n textArray = text.split(\"\");\n output.innerHTML = \"\";\n typing();\n}", "function showChatTyping() {\n document.getElementById('typing').style.display = 'block';\n}", "function showTypingStarted(member) {\n\n if (CURRENT_USER_ID == tc.currentChannel.attributes.localId) {\n $scope.typing = tc.currentChannel.attributes.travellerName + ' is typing ...';\n } else {\n $scope.typing = tc.currentChannel.attributes.localName + ' is typing ...';\n }\n\n $timeout(function() {\n console.log('no more typing')\n $scope.typing = ''\n }, 5000);\n\n $scope.$apply();\n }", "static _printTypes () {\n this.types.forEach(type => {\n compose(\n console.log,\n chalk.yellow,\n padLeft(2, ' '),\n bullet\n )(type)\n })\n console.log()\n }", "typeAnimation(){\n\t\t//preserve a copy of all the text we're about to display incase we need to save\n\t\tthis.saveCopy();\n\t\t\n\t\tFileManager.writing = false; \n\t\t\n\t\t//figure out how fast we want to type the screen based on how much content needs typing \n\t\tvar letters = 0;\n\t\tfor (i=0; i< this.state.toShowText.length; i++){\t\t\t \n\t\t\tletters += this.state.toShowText[i].text.length;\n\t\t}\n\t\tvar scale = Math.floor(letters/20);\n\t\tif(scale < 1){\n\t\t\tscale = 1;\n\t\t}\n\t\t\n\t\t\n\t\t//do the actual typing\n\t\tthis.typeAnimationActual(scale);\n\t\t\n\t}", "function display(){\n console.log(chalk.yellow.underline.bold(\"Please use one of the following commands:\"))\n console.log(chalk.blue('\\tconcert-this')+\" to find the bands in the town\")\n console.log(chalk.blue('\\tspotify-this-song') + \" to get the song details\")\n console.log(chalk.blue('\\tmovie-this')+ \" to movie details\")\n console.log(chalk.blue('\\tdo-what-it-says') + \" to allow LIRI talk to to random.txt\")\n console.log(chalk.blue('\\tq') + \" to quit the terminal\\n\")\n}", "show(){\r\n console.table(this.words);\r\n }", "function keyPressed() {\n typewriter.typewrite(`Friends, Romans, Countryfolk...`, 100, 100);\n}", "function showHint () {\n var hintText = '';\n var p;\n for (p in word) {\n if(hintArr[p] === undefined) {\n hintText += '_ ';\n } else {\n hintText += word[p] + ' ';\n }\n }\n\n hint.innerHTML = hintText;\n }", "displayHint() {\n\t\tthis.hints = ['cyberpunk movie', 'green reptiles', 'waka waka waka','street figher',\n\t\t\t\t\t\t'tv show','alien ship','time travel', 'jet fighter',\n\t\t\t\t\t\t'highlander', 'computer', 'mercury', 'turtles',\n\t\t\t\t\t\t'song', 'anime', 'director', 'toy maker',\n\t\t\t\t\t\t'china town', 'anime cyberpunk', 'mechs', 'mj', \n\t\t\t\t\t\t'romantic comedy', 'kessel run', 'doctor', 'sith', 'jake ryan']\n\n\t\tthis.activeHint = this.hints[this.currentPhraseIndex];\n\t\tdocument.getElementsByClassName('hint')[0].innerText = 'Hint: ' + this.activeHint;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provides a synchronizer for an executer lambda that executes a known number of asynchronous tasks. The executor function is in charge of filling in the provided array with nonnull values, and once the array is completely nonnull, the callback function is called. executor Takes in an array that is numAsyncTasks long and is initialized with a null for each entry. It must divide the work up in such a way that all entries become non null at some point in the future. callback Takes in the array that the executor completely filled with nonnull values.
function synchronize(numAsyncTasks, executor, callback) { const nnAT = numAsyncTasks; const synchronizationArray = new Array(nnAT).map(e => null); for (let i = 0; i < nnAT; i++) synchronizationArray[i] = null; // Pass the reference to the synchronization array to the executor executor(synchronizationArray); // Check that the array is not entirely null to execute the callback let syncTimeoutID = -1; const checkFinished = () => { let ready = true; for (let i = 0; i < nnAT; i++) { if (synchronizationArray[i] === null) { ready = false; break; } } if (ready) callback(synchronizationArray); else syncTimeoutID = setTimeout(checkFinished, 0); }; // Initialize the synchronization check. setTimeout(checkFinished, 0); }
[ "function executor(tasks){\n \n if(tasks.length ==0){\n console.log(\"empty task list, can't run executor\");\n return;\n }\n let task = tasks.shift();\n let callback = function(err, data){\n if(err!==null){\n console.log(\"some error, stopping now\", err);\n return; \n }\n console.log(\"successful task\", data);\n if(tasks.length>0){\n task = tasks.shift();\n task(callback);\n }\n };\n \n task(callback);\n}", "static async asyncMap(array, callback) {\n for (let i in array) array[i] = await callback(array[i])\n return array\n }", "function forEachMT(array, func) {\r\n\tvar pool = java.util.concurrent.ForkJoinPool.commonPool();\r\n\tvar runnableFactory = function(element) {\r\n\t\treturn function() {\r\n\t\t\tfunc(element);\r\n\t\t};\r\n\t};\r\n\r\n\tvar tasks = [];\r\n\tfor (var i=0; i<array.length; i++) {\r\n\t\tvar runnable = runnableFactory(array[i]);\r\n\t\tvar task = pool[\"submit(Runnable)\"](runnable);\r\n\t\ttasks.push(task);\r\n\t}\r\n\r\n\tvar exception = null;\r\n\tfor (var i in tasks) {\r\n\t\ttry {\r\n\t\t\ttasks[i].join();\r\n\t\t} catch (e) {\r\n\t\t\texception = e;\r\n\t\t\tfor (var j in tasks) tasks[j].cancel(true);\t\t\t\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (exception != null) throw exception;\r\n}", "async function asyncForEach(array, callback) { for (let index = 0; index < array.length; index++) { await callback(array[index], index, array); } }", "async asyncForEach(array, callback) {\n for (let index = 0; index < array.length; index++) {\n await callback(array[index], index, array);\n }\n }", "function mapAsync(arr, done, cb) {\n\tif( !arr || arr.length == 0 ) done() \n\tvar f, funcs, i, k, v;\n\tfuncs = [];\n\ti = 0;\n\tfor (k in arr) {\n\t v = arr[k];\n\t f = function(i, v) {\n\t\treturn function() {\n\t\t var e, error;\n\t\t try {\n\t\t\tif (funcs[i + 1] != null) {\n\t\t\t return cb(v, i, funcs[i + 1]);\n\t\t\t} else {\n\t\t\t return cb(v, i, done);\n\t\t\t}\n\t\t } catch (error) {\n\t\t\te = error;\n\t\t\treturn done(new Error(e));\n\t\t }\n\t\t};\n\t };\n\t funcs.push(f(i++, v));\n\t}\n\treturn funcs[0]()\n}", "function asyncAll (\n\t array ,\n\t fn ,\n\t callback \n\t) {\n\t if (!array.length) { return callback(null, []); }\n\t var remaining = array.length;\n\t var results = new Array(array.length);\n\t var error = null;\n\t array.forEach(function (item, i) {\n\t fn(item, function (err, result) {\n\t if (err) { error = err; }\n\t results[i] = ((result ) ); // https://github.com/facebook/flow/issues/2123\n\t if (--remaining === 0) { callback(error, results); }\n\t });\n\t });\n\t}", "function forEachAsync2(arr, cb) {\n arr.forEach(function () {\n setTimeout(cb, 0)\n });\n}", "function asyncValues (values) {\n var index = 0\n return function (end, callback) {\n setImmediate(function () {\n if (end) {\n callback(end)\n } else {\n if (index < values.length) {\n callback(null, values[index++])\n } else {\n callback(true)\n }\n }\n })\n }\n}", "function funcArray_CallSync_Actual( funcArray, ix, arrayDoneFunc )\n{\n if ( ix >= funcArray.length )\n {\n if ( arrayDoneFunc )\n {\n arrayDoneFunc( ) ;\n }\n return ;\n }\n\n // isolate the function from array of functions.\n var func = funcArray[ix];\n\n // call the function. the signature of the function is func( doneFunc )\n // when the function completes it calls the callback function. The callback\n // then does a recursive call to run this function to call the next function\n // in the funcArray.\n func( function()\n {\n ix = ix + 1 ;\n funcArray_CallSync_Actual( funcArray, ix, arrayDoneFunc ) ;\n });\n}", "forEachConcurrently (callback, context) {\n const promise = this.then(async function (array) {\n const promises = array.map(callback, context)\n await Promise.all(promises)\n return array\n })\n return PromisedArray.fromPromise(promise)\n }", "function asyncMap(array, mapFunc, callback) {\n if (!callback) callback = function(){};\n\n var newArray = array.slice(0);\n var toFinish = 0;\n\n // empty object\n if (newArray.length == 0) {\n callback(null, newArray);\n return;\n }\n\n for (let i = 0; i < newArray.length; ++i) {\n toFinish += 1;\n mapFunc(newArray[i], i, newArray, function(i, error, result) {\n toFinish -= 1;\n if (error) {\n callback(error);\n callback = function(){};\n } else {\n newArray[i] = result;\n\n if (toFinish <= 0) {\n callback(null, newArray);\n }\n }\n }.bind(null, i));\n }\n}", "function executeHandlers (arr, context, params, callback) {\n async.forEach(arr, function (fn, cb) {\n fn.call(context, params, cb);\n }, callback);\n}", "function executeParallel(op, arr, iter, cb) {\n\tvar chunkSize = Math.floor(arr.length / numCPUs),\n\t\tworker,\n\t\titerStr,\n\t\ttask,\n\t\toffset,\n\t\ti;\n\t\n\t// Lazy initialization\n\tinit();\n\t\n\t// Check params\n\tif (!cb) {\n\t\tthrow Error('Expected callback');\n\t}\t\n if (arr == null) {\n\t\tcb(null, []);\n\t\treturn;\n\t}\n\tif (!Array.isArray(arr)) {\n\t\tcb(Error('Expected array'));\n\t\treturn;\n\t}\n\tif (typeof iter !== 'function') {\n\t\tcb(Error('Expected iterator function'));\n\t\treturn;\n\t}\n\tif (!isValidOP(op)) {\n\t\tcb(Error('Expected valid operation but got ' + op));\n\t\treturn;\n\t}\n\t\n\t\n\titerStr = iter.toString(); //Serialize iter\n\t\n\tfor (i = 0; i < workers.length; i++) {\n\t\tworker = workers[i];\n\t\toffset = chunkSize * i;\n\n\t\ttask = {\n\t\t\ttype: 'func',\n\t\t\top: op,\n\t\t\tdata: (i === workers.length - 1 ? arr.slice(offset) : arr.slice(offset, offset + chunkSize)), // Partition arr\n\t\t\titer: iterStr,\n\t\t\tcontext: {\n\t\t\t\tpartition: i,\n\t\t\t\tjobID: jobID\n\t\t\t}\n\t\t};\n\t\t\n\t\t// Send task to worker\n\t\t// worker.send(task);\n\t\tbuffer.add(task);\n\t}\n\tdispatchWorkItems();\t\n\n\t// Store job\n\tjobs[jobID] = {\n\t\ttype: 'func',\n\t\tresult: [],\n\t\tcbCount: 0,\n\t\tcb: cb\n\t};\n\t\n\t// Increase jobID\n\tjobID++;\n}", "function runSeries(tasks, callback) {\n var logger = require('get-log')('get-flow.runSeries');\n if (!tasks || tasks.length === 0) {\n if (logger.isDebugEnabled()) {\n logger.debug('Illegal argument, you must provide a not empty task list.');\n }\n return;\n }\n // Retrieve all the main arguments, they will be passed to the first task\n var firstTaskArgs = Array.prototype.slice.call(arguments, 1);\n // First argument, the 'exception', will be null\n firstTaskArgs[0] = null;\n // 'runTask' function manage each task execution, both sync and async\n var runTask = function (ex) {\n // Exit on exception\n if (ex) {\n logger.error(\"Exception occurs: %s\", ex.stack);\n callback(ex);\n return;\n }\n // Retrieve all the arguments\n var taskArgs = Array.prototype.slice.call(arguments);\n // Take the current task if any\n var currentTask = tasks[0];\n // Check if still there is a task to run like there's no tomorrow... :)\n if (currentTask) {\n // Prepare to the next\n tasks.shift();\n // Check if the task first argument name is 'callback'\n var isAsync = retrieveArgumentNames(currentTask)[0] == 'callback';\n if (logger.isDebugEnabled()) logger.debug('Run %s task \\'%s\\'..',\n (isAsync ? 'ASYNC' : 'SYNC'), currentTask.name);\n // ASynchronous Task\n if (isAsync) {\n // First argument will be the callback wrapper to run the next task\n taskArgs[0] = runTask;\n // Run the current async task\n currentTask.apply(this, taskArgs);\n }\n // Synchronous Task\n else {\n try {\n // Discard the 'exception' first argument\n taskArgs.shift();\n // Run the current sync task\n var result = currentTask.apply(this, taskArgs);\n // Run the next task passing the current task result\n runTask(null, result);\n } catch (exc) {\n // Pass the exception to the task runner\n runTask(exc);\n }\n }\n } else {\n callback.apply(this, taskArgs);\n }\n };\n // run first task\n runTask.apply(this, firstTaskArgs);\n}", "function funcArray_CallSync( funcArray, arrayDoneFunc )\n{\n funcArray_CallSync_Actual( funcArray, 0, arrayDoneFunc ) ;\n}", "async function asyncFilter(array, callback) {\n const fail = Symbol()\n return (await Promise.all(array.map(async item => (await callback(item)) ? item : fail))).filter(i => i !== fail)\n}", "function awaitAndReduce(iterable, callbackfn, initialValue) {\n var iterable_1, iterable_1_1;\n return __awaiter(this, void 0, void 0, function* () {\n var e_1, _a;\n // TODO: make initialValue optional (overloads or conditional types?)\n let accumulator = initialValue;\n try {\n for (iterable_1 = __asyncValues(iterable); iterable_1_1 = yield iterable_1.next(), !iterable_1_1.done;) {\n const value = iterable_1_1.value;\n accumulator = callbackfn(accumulator, value);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) yield _a.call(iterable_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return accumulator;\n });\n}", "function execCallback(callback, callbackParamArray) {\n\n if (callbackParamArray)callback.apply(this, callbackParamArray);\n else callback();\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assign student data at current indexId to global currentStudent variable
function makeStudent() { currentStudent = studentsObject.sigmanauts[indexId]; }
[ "function setIndividualStudent(student) {\n\t\t\t\t\t\t\tvar data = filterDataByStudent(jsonData, student);\n\t\t\t\t\t\t\t$scope.individualStudent = ((data[0] !== null) && (data[0] !== undefined)) ? data[0]\n\t\t\t\t\t\t\t\t\t: null;\n\t\t\t\t\t\t}", "function setStudentId(student) {\n /* current code that sets the vm.student object's properties by 'student' object passed from html */\n vm.student = {\n Id: student.Id,\n FirstName: student.FirstName,\n LastName: student.LastName,\n ClientId: student.ClientId,\n CacheDB: student.CacheDB,\n ClientDB: student.ClientDB\n };\n\n /* once vm.student is set, set the rootScope for the current student for styling on <li> tabs */\n $rootScope.CurrentStudent = student;\n\n /* call the activate event, send the vm.student object and routeParams.pageMode which is the view that the page currently shows */\n activate(vm.student, $routeParams.pageMode);\n //activate($rootScope.CurrentStudent, $routeParams.pageMode);\n }", "function editStudent(index, student) {\n students[index] = student;\n}", "'SET_STUDENTS' (state, studentData) {\n \n state.studentListData = studentData;\n \n }", "function populateStudent(i) {\n Student.get($scope.group.studentList[i].id).then(function(response) {\n $scope.group.studentList[i] = response.data;\n });\n }", "function updateStudent(student) {\n\n}", "updateStudent() {\n\n\t}", "function getStudent(index) {\n if (index < 0 || index > studentList.length - 1) {\n return null;\n }\n return studentList[index];\n }", "function nextStudent() {\n if (indexId < studentsObject.sigmanauts.length - 1) {\n indexId ++; //increment indexId if < total student in studentsObject\n } else {\n indexId = 0; //if at end of array, set indexId back to 0\n }\n makeStudent(); //reassign new student to currentStudent\n appendToDom(); //add info from currentStudent to DOM\n resetTimer(); //reset timer :)\n moveCarousel();\n }", "function studentSelected(listElement, index) {\n if(!savedList[currentStudentIndex]){\n // clicked another student without saving, save student's data to database\n }\n // if (!listElement.classList.contains(\"approved\")) {\n // console.log('HERE')\n // }\n \n selectedStudentElement = listElement;\n currentStudentElement.classList.remove(\"selected\");\n listElement.classList += \" selected\";\n\n currentStudentIndex = index;\n currentStudentElement = listElement;\n currentStudentData = listOfStudents[index];\n \n \n\n populateData();\n}", "'NEW_STUDENT' (state, { studentName, studentGrades}) {\n \n // Grabs the id of the last student in the array and adds one to it\n let newId = state.studentListData.data.slice(-1)[0]._id + 1;\n\n // Pushes new data into studentListData array\n state.studentListData.data.push({\n\n _id: newId,\n\n name: studentName,\n\n grades: studentGrades,\n\n });\n \n }", "function addID(student) {\n student.id = studentsNumber;\n studentsNumber++;\n}", "assignStudentToMentor(id, newData) {\r\n let flag = true;\r\n let output = {};\r\n let message = \"\";\r\n let selectedMentor = data[1].mentors.filter((m) => m.id == id);\r\n // console.log(\"new\", newData);\r\n let selectedStudent = data[0].students.filter((s) => {\r\n return s.name == newData.student;\r\n });\r\n console.log(\"selected stud\", selectedStudent);\r\n \r\n //If student already has a mentor throw an error\r\n if (selectedStudent[0].mentor) {\r\n flag = false;\r\n message = \"Student already has a mentor : \" + selectedStudent[0].mentor;\r\n }\r\n \r\n //If not, assign the student to the mentor\r\n if (flag) {\r\n //Updating mentors\r\n for (let i in data[1].mentors) {\r\n if (data[1].mentors[i].id == id) {\r\n data[1].mentors[i].studs.push(newData.student);\r\n output = data[1].mentors[i];\r\n }\r\n }\r\n //Updating students\r\n for (let i in data[0].students) {\r\n if (data[0].students[i].name == newData.student) {\r\n data[0].students[i].mentor = selectedMentor[0].name;\r\n }\r\n }\r\n console.log(output);\r\n return output;\r\n } else {\r\n return { error: message };\r\n }\r\n }", "function setStudentID(ID) {\n localStorage.setItem(\"ID\", ID); // store with id = \"ID\"\n }", "addStudent(student) {\n this.sectionNameSpace.studentList.push(student);\n }", "function studentId(student) {\n return student._id;\n }", "static pushStudent(student) {\n // retrieve existing students\n const students = Storage.getStudents();\n // push student to existing array\n students.push(student);\n // restore students in local storage\n localStorage.setItem('students', JSON.stringify(students));\n }", "selectStudentHandler(event){\n\t\tconst studentId = event.currentTarget.getAttribute('value');\n\t\tthis.viewSingleStudent(studentId);\n\t}", "function updateStudent() {\n studentString = JSON.stringify(Student.all);\n localStorage.setItem(\"studentinfo\", studentString);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that adds notifications about issue events to the DOM
function notifications (data) { let status = '' switch (data.action) { case data.action = 'opened': status = 'New Issue' break case data.action = 'edited': status = 'Issue edited' break case data.action = 'created': status = 'New Comment' break case data.action = 'deleted': status = 'Comment removed' break case data.action = 'closed': status = 'Issue closed' break case data.action = 'reopened': status = 'Issue reopened' break default: console.log('You was not prepared for this event man!') } const notification = document.querySelector('#notification') const div = document.createElement('div') const ul = document.createElement('ul') const a = document.createElement('a') div.setAttribute('class', 'issue-card') a.setAttribute('href', '#') a.setAttribute('class', 'close-btn') a.textContent = 'X' let headline = addLiElement('Notification') let issue = addLiElement('# ' + data.issueNr) let action = addLiElement('Event: ' + status) let title = addLiElement('Title: ' + data.title) let user = addLiElement('User: ' + data.user) ul.appendChild(headline) ul.appendChild(issue) ul.appendChild(action) ul.appendChild(title) ul.appendChild(user) div.appendChild(a) div.appendChild(ul) notification.appendChild(div) a.addEventListener('click', closeBtn => { a.parentNode.parentNode.removeChild(a.parentNode) }) }
[ "function addNotificationElements() {\n\tconst SPAN = document.createElement(\"span\");\n\tSPAN.className = \"dhqol-notif-ready\";\n\tSPAN.style = \"display:inline-block\";\n\tSPAN.appendChild(document.createElement(\"img\"));\n\tSPAN.children[0].className = \"image-icon-50\";\n\tSPAN.appendChild(document.createElement(\"span\"));\n\n\tlet notificationNode = document.getElementById(\"notifaction-area\");\n\tlet refNode = notificationNode.children[0] || null;\n\n\t// Create our new notification span elements\n\tlet furnaceElement = SPAN.cloneNode(true);\n\tfurnaceElement.id = \"dhqol-notif-furnace\";\n\tfurnaceElement.children[0].setAttribute(\"src\", \"images/silverFurnace.png\");\n\tlet woodCuttingElement = SPAN.cloneNode(true);\n\twoodCuttingElement.id = \"dhqol-notif-woodcutting\";\n\twoodCuttingElement.children[0].setAttribute(\"src\", \"images/icons/woodcutting.png\");\n\tlet farmingElement = SPAN.cloneNode(true);\n\tfarmingElement.id = \"dhqol-notif-farming\";\n\tfarmingElement.children[0].setAttribute(\"src\", \"images/icons/watering-can.png\");\n\tlet combatElement = SPAN.cloneNode(true);\n\tcombatElement.id = \"dhqol-notif-combat\";\n\tcombatElement.children[0].setAttribute(\"src\", \"images/icons/combat.png\");\n\tlet rowBoatElement = SPAN.cloneNode(true);\n\trowBoatElement.id = \"dhqol-notif-rowboat\";\n\trowBoatElement.children[0].setAttribute(\"src\", \"images/rowBoat.png\");\n\tlet canoeElement = SPAN.cloneNode(true);\n\tcanoeElement.id = \"dhqol-notif-canoe\";\n\tcanoeElement.children[0].setAttribute(\"src\", \"images/canoe.png\");\n\tlet vialElement = SPAN.cloneNode(true);\n\tvialElement.id = \"dhqol-notif-vial\";\n\tvialElement.children[0].setAttribute(\"src\", \"images/vialOfWater.png\");\n\tvialElement.setAttribute(\"onclick\", \"window.openTab('brewing');\");\n\tvialElement.oncontextmenu = function() {\n\t\tdrinkMonitoredPotions();\n\t\treturn false;\n\t};\n\n\t// Insert our new elements into the document\n\tnotificationNode.insertBefore(furnaceElement, refNode);\n\tnotificationNode.insertBefore(woodCuttingElement, refNode);\n\tnotificationNode.insertBefore(farmingElement, refNode);\n\tnotificationNode.insertBefore(combatElement, refNode);\n\tnotificationNode.insertBefore(rowBoatElement, refNode);\n\tnotificationNode.insertBefore(canoeElement, refNode);\n\tnotificationNode.insertBefore(vialElement, refNode);\n}", "function registerClickEventHandlers() {\n $(\"#createIssue\").click(function () {\n createIssue();\n });\n\n $(\"#viewIssue\").click(function () {\n viewIssue();\n });\n}", "function IssueEvent() {\n _classCallCheck(this, IssueEvent);\n\n IssueEvent.initialize(this);\n }", "function notificationEvents() {\n notifications[eNotificationType.InstrumentEdited] = new delegate();\n notifications[eNotificationType.InstrumentEdited].Add(onInstrumentModified);\n\n notifications[eNotificationType.MinDealGroupEdited] = new delegate();\n notifications[eNotificationType.MinDealGroupEdited].Add(onMinDealGroupModified);\n }", "function addToDom(notification) {\n\t// create elements to be added\n\t// var wrapper = createCollapsibleWrapper(notification);\n\tvar notificationContainer = document.createElement(\"pre\");\n\tvar notificationElement = document.createElement(\"code\");\n\n\t// attach to each other\n\tnotificationContainer.appendChild(notificationElement);\n\t// wrapper.appendChild(notificationContainer);\n\n\t// set up new element\n\tnotificationElement.classList.add(\"json\");\n\tnotificationElement.innerHTML = JSON.stringify(notification, null, 4);\n\t// notificationContainer.classList.add(\"hidden\"); // commented out until the wrapper is used again\n\n\t// add to DOM\n\teventList = document.getElementById(\"list\");\n\teventList.appendChild(notificationContainer);\n\n\t// activate highlighting\n\thljs.highlightBlock(notificationElement);\n}", "listenForAnyIssueUpdates() {\n console.debug('listen for any issue updates');\n this.issueService\n .issueUpdatesForWatchListListener()\n .subscribe((data) => {\n const { issueId, field, message, watchList } = data;\n console.debug('issue update listener:', data);\n if (watchList.includes(this.userId)) {\n // current user is in the watchlist ,show notification\n const notification = this.toast.info(`${message}`, 'Issue Updated');\n // observer function when notification is clicked - show the updated issueId\n notification.onTap.subscribe(() => {\n // fetch all the issues\n // this.filterIssues(this.userId, 'all', 'status', this.name);\n this.viewSingleIssue(issueId, 'notification');\n });\n }\n });\n }", "function printIssue(e) {\r\n\tconst issueDesc = document.getElementById('issueDescription').value;\r\n\tconst issueAssignedTo = document.getElementById('issueAssignedTo').value;\r\n\r\n\tif (issueDesc == '' && issueAssignedTo == '') {\r\n\t\talertNotification('empty-both', 'block');\r\n\t\tsetTimeout(clearNotification, 3000);\r\n\t} else if (issueDesc == '') {\r\n\t\talertNotification('empty-desc', 'block');\r\n\t\tsetTimeout(clearNotification, 3000);\r\n\t} else if (issueAssignedTo == '') {\r\n\t\talertNotification('empty-assign', 'block');\r\n\t\tsetTimeout(clearNotification, 3000);\r\n\t} else {\r\n\t\tsubmitIssue(e);\r\n\t}\r\n\te.preventDefault();\r\n}", "function appendToNotifications(doc)\n{\n doc.find(newNotificationSelector).parent().each(function ()\n {\n formatNoti($(this));\n $(this).click(function () { chrome.runtime.sendMessage({ event: { cat: \"Click\", type: \"Notification\" } }); });\n $(\"#notifications\").append($(this))\n .append($(\"<div>\", { class: \"seperator\" }));\n });\n}", "function issueEvents(issue, comments) {\r\n\tvar issueUrlEvents = issue.url + \"/events\";\r\n\tif (verbose)\r\n\t\tconsole.log(\"Issues Events URL: \" + issueUrlEvents);\r\n\t\r\n\tgetLoop(issueUrlEvents, 1, [], \r\n\t\t\tfunction(events) { formatIssue(issue, comments, events); }); \r\n\t\r\n}", "function buildCalendar(issues) {\n var calendarEl = document.getElementById('calendar');\n var events = issues.map(issue => {\n return {\n id: issue.key,\n groupId: issue.assignee,\n title: issue.key,\n start: issue.duedate,\n color: issue.category,\n assignee: issue.assignee,\n tip: \"By clicking on issue you can see the details and data subject will get notified\"\n }\n })\n console.log(\"Issues within buildCalendar: \" + JSON.stringify(issues));\n\n var calendar = new FullCalendar.Calendar(calendarEl, {\n initialView: 'dayGridMonth',\n initialDate: '2021-01-07',\n headerToolbar: {\n left: 'prev,next today',\n center: 'title',\n right: 'dayGridMonth,timeGridWeek,timeGridDay'\n },\n events: events,\n eventClick: function (info) {\n console.log(\"This is the assignee from event: \" + info.event.groupId + \", key: \" + info.event.id);\n directRequest(info.event.groupId, info.event.id);\n window.open('http://localhost:2990/jira/browse/'+info.event.id,'_blank')\n },\n });\n\n calendar.render();\n\n console.log(\"Calendar has been built\");\n}", "function noIssues() {\n // add paragraph\n let p = document.createElement('p');\n p.textContent = 'No issues at the moment.';\n window.issues.appendChild(p);\n }", "static findAndLinkifyJiraIssues() {\n const logTableNodes = document.querySelectorAll('#table-tsitems td.htsItemStyle div.hts_object');\n const hasTextNodes = (p) => Array.from(p.childNodes).find(n => n.nodeType === 3);\n Array.from(logTableNodes)\n .filter(hasTextNodes)\n .forEach(node => this.replaceIssueByLink(node));\n }", "function _displayNotification() {\n \n // If does not exist\n if ($.find(\"#main-window-warning\").length === 0) {\n \n // Get views\n var view = _renderNotificationView(),\n contentDiv = $($($.find(\".main-view\")[0]).find(\".content\")[0]);\n \n // Add notification to content\n contentDiv.first().prepend(view);\n \n // Add listeners\n $(\"#main-window-warning\").click(function () {\n _removeNotification();\n });\n \n // Resize editor to make the status bar reappear\n _resizeEditor(true);\n }\n }", "constructor() { \n \n IssueEvent.initialize(this);\n }", "function setupNotificationMessages() {\n var elems = document.querySelectorAll(\".notification\");\n for (var i = 0; i < elems.length; i++) {\n var closeBtn = elems[i].querySelector(\".notification__close-btn\");\n if (closeBtn != null) {\n onClickRemoveElement(closeBtn, elems[i])\n }\n }\n}", "function _onChangeIssueInfo(evt){\n _requestUpdateIssue(evt);\n }", "onNotification(notification) {}", "_initHtml() {\n jQuery('#notifyButtonHtml').on('click', (event) => {\n event.preventDefault();\n jQuery.notify(\n {\n title: '<strong>Bold Title</strong> ',\n message: 'Acorn is created by <a href=\"https://themeforest.net/user/coloredstrategies\" target=\"_blank\">ColoredStrategies</a>',\n },\n {type: 'primary', icon_type: 'image'},\n );\n });\n }", "function push_some_notification() {\n monitoredItem.simulateMonitoredItemAddingNotification();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used above, for joining possibly empty strings with pluses
function fancyJoin(a,b) { if (a == "") { return b; } else if (b == "") { return a; } else { return a+"+"+b; } }
[ "function joinNotEmpty(items, sep) {\n var str =\"\";\n for (var i= 0; i < items.length; ++i) {\n var item = items[i];\n if (item != null && item != \"\") {\n if (str.length != 0) str+=sep;\n str+=item;\n }\n }\n return str;\n}", "function fancyJoin ( a, b )\n{\n if (a == \"\") { return b; }\t\n else if (b == \"\") { return a; }\n else { return a+\"+\"+b; }\n}", "function fancyJoin(a,b) {\r\n if (a == \"\") { return b; }\t\r\n else if (b == \"\") { return a; }\r\n else { return a+\"+\"+b; }\r\n}", "function fancyJoin(a, b) {\n\tif (a == \"\") { return b; }\n\telse if (b == \"\") { return a; }\n\telse { return a + \"+\" + b; }\n}", "function _join(seperator, ...strs) {\n return strs.filter((s) => !!s).join(seperator);\n }", "function implode_compact(glue, pieces) {\n if (pieces.length == 0) {\n return;\n }\n var result = pieces[0];\n for (var i = 1; i < pieces.length; i++) {\n if (pieces[i] != '') {\n result += glue + pieces[i];\n }\n }\n return result;\n}", "function _englishJoin(arr) {\n if (arr.length == 0) {\n return \"\";\n } else if (arr.length == 1) {\n return \"\" + arr[0];\n } else if (arr.length == 2) {\n return arr.join(\" and \");\n } else {\n return arr.slice(0, arr.length - 1).join(\", \") + \", and \" + arr[arr.length - 1];\n }\n}", "function joinLetters(letters) {\n const v = [...letters];\n return v.map((a) => (a.length > 1 || !a.length ? `(${a})` : a)).join('');\n}", "function join(maybeArray, separator) {\n return maybeArray\n ? maybeArray\n .filter(x => x)\n .join(separator || \"\")\n : \"\";\n }", "function join(maybeArray, separator) {\n return maybeArray ? maybeArray.filter(function (x) {\n return x;\n }).join(separator || '') : '';\n }", "function join(maybeArray, separator) {\n\t return maybeArray ? maybeArray.filter(function (x) {\n\t return x;\n\t }).join(separator || '') : '';\n\t}", "function joinWith(a, glue) {\n return (a) ? a.join(glue) : \"\";\n}", "function joinCharsNoFirst(str1,str2){\n\tif(str1.length > 1) str1 = str1.substr(1);\n\tif(str2.length>1) str2 = str2.substr(1);\n\treturn str1.concat(str2);\n}", "function prepend_space(sb) {\n if ( (!sb.isEmpty()) && (sb.lastChar() != \" \")) {\n sb.append(\" \");\n }\n }", "function maybeJoinWithSpaces(v) {\n return is.maybe.array(\n v,\n joinWithSpaces,\n otherwiseReturnEmptyString);\n}", "function String$empty() {\n return '';\n }", "function join(array) {\n var str = '';\n\n for (var i = 0; i < array.length; i++) {\n if (array[i] !== null) {\n var cur = array[i];\n var valid = isFinite(cur);\n if (valid) {\n str += cur;\n }\n }\n}\n return str;\n}", "function badCharacterZeroWidthJoiner(context) {\n const charCode = 8205;\n return {\n character({ chr, i }) {\n if (chr.charCodeAt(0) === charCode) {\n context.report({\n ruleId: badChars.get(charCode),\n message: \"Bad character - ZERO WIDTH JOINER.\",\n idxFrom: i,\n idxTo: i + 1,\n fix: {\n ranges: [[i, i + 1]], // just delete it\n },\n });\n }\n },\n };\n}", "function concatenate(arr) {\n if (arr.length > 0) {\n return arr.join('');\n } else {\n return '';\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
nav always stay center animation
function navAnimtion() { var scrollWidth = $(".fairies-nav").width(); var ulWidth = $(".fairies-nav ul").width(); var liLeft = $(".fairies-nav li.active").position().left; var liWidth = $(".fairies-nav li.active").outerWidth(true); $(".fairies-nav ul").removeAttr('class'); if (liLeft + liWidth < scrollWidth / 2) { $(".fairies-nav ul").css("left", "0"); } else if (ulWidth - (liLeft + liWidth) < scrollWidth / 2) { var liLeftLast = $(".fairies-nav li:last").position().left; var ulLeftEnd = (liLeftLast + liWidth - scrollWidth) / scrollWidth * 100; if (ulLeftEnd < 0) { $(".fairies-nav ul").css("left", "0"); } else { $(".fairies-nav ul").css("left", -ulLeftEnd + "%"); } } else { var ulLeft = (liLeft + liWidth / 2 - scrollWidth / 2) / scrollWidth * 100; $(".fairies-nav ul").css({ left: -ulLeft + "%" }); } }
[ "function animateNav(){\n\tvar tl = new TimelineMax()\n\t.staggerTo('.project-nav li', .5, {ease:Back.easeIn.config(2.7), y:-25, opacity:0}, .1)\n\t.set('.top-slant', {y:-250})\n\t.set('.bottom-slant', {y:1024});\n\treturn tl;\n}", "function pageTransition(){\n // Problem: css animationen nicht stapelbar (Plugin: http://labs.bigroomstudios.com/libraries/animo-js )\n // animation: none --> elemets jump back to start\n\n var atomOffset;\n var $wrapper = jQuery('.wrapper');\n var wrapperWidth = ($wrapper.width()/2) + $wrapper.offset().left; // calculate center of wrapper pane\n var wrapperHeight= $wrapper.height()/2;\n\n $overlay.animate({ opacity: 0}, 500);\n jQuery('img.logo, span.button').animate({\n height: ($(this).height()*0),\n width: ($(this).width()*0),\n \"font-size\": 0,\n opacity: 0\n }, 500, function(){\n $atom.each(function(){\n atomOffset = jQuery(this).offset();\n\n // calculate vector\n VecX = wrapperWidth - atomOffset.left;\n VecY = wrapperHeight - atomOffset.top;\n\n normalizeVector();\n\n jQuery(this).animate({\n position: \"relative\",\n top: 1000*-VecY,\n left: 1000*-VecX\n }, 1000, function(){\n window.location = '#/menu';\n });\n });\n\n });\n\n}", "function moveToCenter() {\n $._resetToCenter();\n}", "function moveStatMenuToCenter()\n{\n $(\"#div_statMenu\").animate({\n //top: setPositionElementInCenter(div_StatisticMenu).y\n top: \"-200px\"\n }, 2000, function() {\n // Animation complete.\n $(\"#div_statMenu\").animate({\n opacity: 0\n }, 1000);\n });\n \n //div_StatisticMenu.style.opacity = 0;\n}", "function animation() {\n\n if (Npos == 60) { // une fois atteint la hauteur souhaitée,\n clearInterval(Nrun); // arrêt du Nrun, donc de l'appel de animation\n }\n else { // tant que la hauteur souhaitée n'est pas atteinte\n Npos = Npos+6; // la variable augment de 6px\n Nopacity = Nopacity + 0.1; // la variable augment de 0,1\n navbar.css('top',-60+Npos+'px');\n navbar.css('opacity', Nopacity); // ce qui est répercuté sur l'objet\n }\n}", "function changeNavPos() {\n if (activeSlide === slides.length - 1) {\n navBar.classList.add(\"for-contact-slide\");\n logo.classList.add(\"dissappear\");\n setTimeout(() => {\n logo.style.zIndex = -200;\n }, 400);\n } else {\n navBar.classList.remove(\"for-contact-slide\");\n logo.style.zIndex = 1000;\n logo.classList.remove(\"dissappear\");\n }\n}", "function moverIzquierda() {\n if (!slider.is(':animated')) {\n $('#slider .slide:last').insertBefore('#slider .slide:first');\n slider.css('margin-left', '-105.6%');\n slider.animate({\n marginLeft: '-43%'\n },700, function () {\n resetInterval()\n });\n \n }\n }", "function pageNav() {\n jQuery(document).on(\"click\", \".we-slider .slider-nav span\", function () {\n parentWidth = jQuery(this).parents(\".we-slider\").width();\n slider = jQuery(this).parents(\".we-slider\").find(\".slider\");\n jQuery(this).addClass(\"active\");\n jQuery(this).parents(\".we-slider\").find(\".slider-nav \").find(\"span\").not(jQuery(this)).removeClass(\"active\");\n activeIndex = jQuery(this).index();\n leftValue = parentWidth * activeIndex;\n slider.stop(true, true).animate({\"margin-left\": \"-\" + leftValue + \"px\"}, 600);\n });\n}", "function menuAni(){\r\n //First, i make sure the elements doesn't have the classes so that i can add later(triggering the animation)\r\n $(\"#menu\").removeClass(\"rotate-center\");\r\n $(\"#navmenu\").removeClass(\"slide-in-left\");\r\n\r\n //If the links are NOT visible (menu is deactivated)\r\n if(!$(\"#navmenu\").is(\":visible\")){\r\n\r\n //If its resolution is lower than 550px\r\n if($(window).width()<550){\r\n //Before the links are displayed, remove the title\r\n $(\".header-title\").fadeOut(200);\r\n //Fix the margin for <550px && >400px to centralize the links\r\n $(\"#navmenu\").css({\"margin-right\":\"3em\"});\r\n //If its resolution is lower than 400px\r\n if($(window).width()<400){\r\n //Fix the margin for <400px to centralize the links\r\n $(\"#navmenu\").css({\"margin-right\":\"2em\"});\r\n }\r\n }\r\n //Add the class to the hamburger icon, triggering the animation\r\n $(\"#menu\").addClass(\"rotate-center\");\r\n //After 200ms, add the class to the links container, triggering the animation\r\n $(\"#navmenu\").delay(200).addClass(\"slide-in-left\");\r\n //The menis is not visible so it has to be faded in\r\n $(\"#navmenu\").fadeIn(400);\r\n\r\n //If the links ARE visible (menu is activated)\r\n }else if($(\"#navmenu\").is(\":visible\")){\r\n //If its resolution is lower than 550px\r\n if($(window).width()<550){\r\n //Show the title since the links are getting out\r\n $(\".header-title\").fadeIn(400);\r\n //Fix the margin for default to centralize the links\r\n $(\"#navmenu\").css({\"margin-right\":\"0\"})\r\n };\r\n //Add the class to the hamburger icon, triggering the animation\r\n $(\"#menu\").addClass(\"rotate-center\");\r\n //Hide the links\r\n $(\"#navmenu\").fadeOut(1).hide(100);\r\n }\r\n\r\n}", "function checkNavPos() {\n const elementOffset = $('.navbar').offset().top;\n const topOfWindow = $(window).scrollTop();\n const distance = (elementOffset - topOfWindow);\n const showLogo = distance < 1;\n\n if (showLogo) {\n $(\"#first-nav-item\").stop().animate({'margin-left': '60px'});\n $(\"#nav-logo-anim\").stop().fadeIn();\n } else {\n $(\"#nav-logo-anim\").stop().fadeOut();\n $(\"#first-nav-item\").stop().animate({'margin-left': '0'});\n }\n}", "function centeredNavBottomBarInit() {\r\n\t\t\t\t\t\r\n\t\t\t\t\tif ($('#header-outer[data-format=\"centered-menu-bottom-bar\"]').length > 0) {\r\n\t\t\t\t\t\tcenteredNavBottomBarReposition();\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t}", "function centeredNavBottomBarReposition() {\r\n \r\n var $headerSpan9 = $('#header-outer[data-format=\"centered-menu-bottom-bar\"] header#top .span_9');\r\n var $headerSpan3 = $('#header-outer[data-format=\"centered-menu-bottom-bar\"] header#top .span_3');\r\n var $secondaryHeader = $('#header-secondary-outer');\r\n \r\n var $logoLinkClone = $headerSpan3.find('#logo').clone();\r\n if($logoLinkClone.is('[data-supplied-ml=\"true\"]')) {\r\n $logoLinkClone.find('img:not(.mobile-only-logo)').remove();\r\n }\r\n //trans\r\n $logoLinkClone.find('img.starting-logo').remove();\r\n \r\n \r\n if($secondaryHeader.length > 0) {\r\n $secondaryHeader.addClass('centered-menu-bottom-bar');\r\n } \r\n \r\n \r\n if($('#header-outer[data-condense=\"true\"]').length > 0) {\r\n $headerSpan9.prepend($logoLinkClone);\r\n } \r\n }", "function centerFunction()\n {\n\n // How far down the page are we?\n var scrollBottom = window.pageYOffset + $(window).height();\n\n //How tall is the page?\n var pageHeight = $(\"#main\").height();\n\n // If we have scrolled beyond the header...\n if (window.pageYOffset > 288) {\n // ... and beyond the footer\n if (scrollBottom > (pageHeight + 900)) {\n // We don't overlap the nav over the footer\n scrollItem.classList.remove(\"fix-nav\");\n }\n else {\n // If we are not at the footer yet, fix nav....\n scrollItem.classList.add(\"fix-nav\");\n // And if we are at responsive desktop size, center the nav\n if ($(window).width() < 1680 && $(window).width() > 1036) {\n $(scrollItem).center();\n }\n }\n } else {\n // If we're still at the top of the page\n scrollItem.classList.remove(\"fix-nav\");\n }\n }", "function makeNavInView() {\n\t\t\tlet currentItem = $( '.sticky__nav-item.is-active' );\n\t\t\tlet winW = $( window ).width();\n\t\t\tif ( winW > 799 && currentItem.length > 0 ) {\n\t\t\t\tcurrentItem[ 0 ].scrollIntoView(\n\t\t\t\t\t{\n\t\t\t\t\t\tblock: 'center',\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t}", "function centeredNavBottomBarReposition() {\n\t\t\n\t\tvar $headerSpan9 = $('#header-outer[data-format=\"centered-menu-bottom-bar\"] header#top .span_9');\n\t\tvar $headerSpan3 = $('#header-outer[data-format=\"centered-menu-bottom-bar\"] header#top .span_3');\n\t\tvar $secondaryHeader = $('#header-secondary-outer');\n\t\t\n\t\tvar $logoLinkClone = $headerSpan3.find('#logo').clone();\n\t\tif($logoLinkClone.is('[data-supplied-ml=\"true\"]')) {\n\t\t\t$logoLinkClone.find('img:not(.mobile-only-logo)').remove();\n\t\t}\n\t\t//trans\n\t\t$logoLinkClone.find('img.starting-logo').remove();\n\t\t\n\n\t\tif($secondaryHeader.length > 0) {\n\t\t\t$secondaryHeader.addClass('centered-menu-bottom-bar');\n\t\t} \n\t\t\n\t\t\n\t\tif($('#header-outer[data-condense=\"true\"]').length > 0) {\n\t\t\t$headerSpan9.prepend($logoLinkClone);\n\t\t} \n\t}", "function nav(){\n\t$('.nav').onePageNav({\n\t currentClass: 'current',\n\t changeHash: false,\n\t scrollSpeed: 750,\n\t scrollThreshold: 0.5,\n\t filter: '',\n\t easing: 'swing',\n\t begin: function() {\n\t //I get fired when the animation is starting\n\t },\n\t end: function() {\n\t //I get fired when the animation is ending\n\t },\n\t scrollChange: function($currentListItem) {\n\t //I get fired when you enter a section and I pass the list item of the section\n\t }\n\t});\n}", "function setAnchorsAnimations() {\n $('.main-nav__item a').click(function (e) {\n $('html, body').animate({\n scrollTop: $($(this).attr('href')).offset().top - HEADER_SIZE\n }, 500);\n $('.main-nav__item a').removeClass('active');\n $(e.currentTarget).toggleClass('active');\n return false;\n });\n}", "function scrollNav() {\n $(document).bind('scroll', function () {\n if ($(document).scrollTop() > 130) {\n $('nav').addClass('fixed');\n } else {\n $('nav').removeClass('fixed');\n }\n });\n} //anima, all'interno delle sezioni, degli shape in base ai movimenti del mouse", "function navbar_enter() {\n var $mainNavItem_width = $(this).width();\n var $mainNavItem_left = $(this).position().left;\n\n navBarAni($mainNavItem_width, $mainNavItem_left, 450);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pseudo code for what I could not finish function for getting the score on click for the submit button
function getScore(score) { $(".submit").on("click", function(){ //see what was selected $( "input[type=radio]:checked" ).val(); //if something was selected, add one to answered questions if (":checked", "true") { questionsAnswered++; //check to see if selected answers are correct if (questionsAnswered.val([i]) === correctAnswers[i]) { score++; } } else { questionsNotAnswered++; } }) }
[ "function submitScore(){\n saveScore();\n hideResult();\n showScoreBoard();\n}", "function userSubmit() {\n\n if ($(\"#userTriviaGuess\").val() === \"\") {\n $(\"#userTriviaGuess\").val(0);\n }\n\n let tomatoScoreUnfiletered = scoreArray[counter];\n let tomatoScoreFiltered = tomatoScoreUnfiletered.replace(\"%\", \"\");\n let tomatoScore = parseInt(tomatoScoreFiltered);\n let userGuessFiltered = $(\"#userTriviaGuess\").val().trim();\n let userGuess = parseInt(userGuessFiltered);\n let questionScore = Math.abs(tomatoScore - userGuess);\n // console.log(questionScore + \"Question Score\");\n totalScore = totalScore + questionScore;\n\n gameStart();\n }", "function handleSubmitScoreClick() {\n let initials = inpInitialsEl.value.trim();\n if (initials.length < 2) {\n alert(\"Initials must be at least 2 characters\");\n return;\n }\n addHighScore(initials, timeRemaining);\n handleViewHigh();\n}", "function submit_score() {\n high_scores.push(document.getElementById(\"initials\").value + \" \" + score);\n view_high_scores();\n }", "function submitScore() {\n var scoreInfo = getScoreInfo();\n if (scoreInfo) {\n var xhttp = new XMLHttpRequest();\n\n xhttp.onreadystatechange = function() {\n if (xhttp.readyState === 4 && xhttp.status === 200) {\n //CLEAR MENU & ALERT IT WAS SUCCESSFUL. -> play again button\n getScoreboard();\n //ddSuccessNotification();\n // TODO: add submission confirmation to scoreboard.\n } else if (xhttp.readyState === 4 && xhttp.status !== 200) {\n //addErrorNotification(); // TODO: add error notification to scoreboard.\n //TODO: change error handling\n }\n };\n\n xhttp.open(\n \"POST\",\n \"https://cyber-space.liammahoney.me/score\",\n true\n );\n xhttp.send(JSON.stringify(scoreInfo));\n }\n }", "function SubmitAndScoreDialog() {\r\n}", "function submitscore() {\n // Make the url\n var url = '/add/' + wordinput.value() + '/' + scoreinput.value();\n // Use loadJSON\n loadJSON(url, submitted);\n\n function submitted(result) {\n // Just look at the reply in the console\n console.log(result);\n }\n }", "function submitScore() {\n // Get name\n playerName = $(\"#playerName\").val()\n\n // Ajax submit score\n $.ajax({\n url: \"updateScore.php\",\n data: {score:gameScore, name:playerName},\n type: \"GET\",\n success:function() {getScoreList()}\n })\n // Clear submit score\n $(\"#nameInput\").empty()\n $(\"button\").prop(\"disabled\", false)\n }", "function calculateFormScore() {\r\n\r\n //higligt selected values from previously submitted entry\r\n $(\"input:hidden[name$='_hidden']\").each(function() { // only chose hidden inputs with postfix _hidden\r\n \r\n // aquire form category\r\n var category = $(this).attr(\"name\");\r\n category = category.replace(\"_hidden\", \"\");\r\n\r\n // update score calculation overview\r\n var score = 0; // category score\r\n score = roundToDecimalPlace(calculateCategory(category), 2);\r\n var scoreDiv = '#' + category + '_score';\r\n\r\n $(scoreDiv).html(\"Einkunn - \" + score); // display the score on the page\r\n $(scoreDiv).attr(\"data-score\", score); // store the score\r\n \r\n // always finish by calculating current total score\r\n var totalScore = performScoreCalculation();\r\n $('#totalScoreHeader').html(\"Heildarskor - \" + totalScore);\r\n $('input[name=totalScoreHidden]').val(totalScore);\r\n });\r\n }", "function submitscore() {\n // Make the url\n var url = '/add/' + wordinput.value() + '/' + scoreinput.value();\n // Use loadJSON\n loadJSON(url, submitted);\n function submitted(result) {\n // Just look at the reply in the console\n console.log(result);\n }\n }", "function evalMultiAnswer(qnId,answer,maxMarks){\n var userInput = false;\n var question = getElement(qnId); \n var multiAnsInputs = question.getElementsByTagName(\"input\");\n var score = 0;\n var ansCorArray = answer.split(\" \");\n var optScore = maxMarks/ansCorArray.length;\n for(var i=0; i<multiAnsInputs.length; i++){\n if(multiAnsInputs[i].type == \"checkbox\" ){\n if(multiAnsInputs[i].checked == true){\n userInput = true;\n var imgResultId = multiAnsInputs[i].id + 'fdbkimg'; //make id to display the check mark\n\t\t\t\t\n var found = false;\n for(var j=0; j<ansCorArray.length; j++){\n //to check that the are these ids same? \n if(multiAnsInputs[i].id == ansCorArray[j]){ \n found = true; // if ids are same than we set found true \n }\n }\n if(found == true){\n score += optScore;\n getElement(imgResultId).innerHTML = \"<img src='images/correct.gif'>\"; \n //qnCurrScore += 1;\n }else{\n score -= optScore;\n getElement(imgResultId).innerHTML = \"<img src='images/incorrect.gif'>\"; \n //qnInCurrScore += 1;\n }\n }\n }\n }\n //return score\n //return userInput \n //If we done like above two comment line, the score will return in that time also when the userInput is return null because score is returning from outside of loop and userInput null defined the inside the loop here now the score return only when the userInput is not null it means user clicked, and userInput run onlyWhen if userInput is null that means user check nothing and do submit\n if(userInput == true){\n for(var j=0; j<multiAnsInputs.length; j++){\n multiAnsInputs[j].disabled=true;\n } \n return score;\n }else{\n return null; //the null is define here instead above at else condtion because the check box is more than one\n }\n}", "function submitScore(score) {\n window.setScore(score);\n window.setAppView(\"setScore\");\n}", "insertScoreInput() {\n // Create submission button\n this.insertButton(DOM.buttonsdivid, DOM.showgradebuttonid, \"Submit for Grade\", () => this.grademodal.show());\n\n this.createGradeSubmit();\n\n document.getElementById(DOM.gradeformid).addEventListener(\"submit\", e => this.submitForGrade(e));\n }", "function listenForClick() {\n $('#quiz-form').submit( function (event) {\n event.preventDefault();\n let submittedAnswer = $('input[name=radGroup]:checked', '#quiz-form').val();\n clearForm();\n\n if (submittedAnswer == currentState.answer) {\n currentState.userCorrect++;\n showFeedbackPage(true, currentState);\n }\n else {\n showFeedbackPage(false, currentState);\n currentState.userWrong++;\n }\n });\n\n $('.js-next').click(currentState, clickNext);\n $('.js-previous').click(currentState, clickPrevious);\n $('.js-startover').click(currentState, startOver);\n}", "function CalculateScore(){\n\t\tvar score = 0;\n\t\tif(choices1[choices1.length - 1] === questions[c].correctOp.toString()){\n\t\t\tscore += 25;\n\t\t};\n\t\tif(choices2[choices2.length - 1] === questions[b].correctOp.toString()){\n\t\t\tscore += 25;\n\t\t};\n\t\tif(choices3[choices3.length - 1] === questions[a].correctOp.toString()){\n\t\t score += 25;\n\t\t}; \n\t\tif(choices4[choices4.length - 1] === questions[d].correctOp.toString()){\n\t\t\tscore += 25;\n\t\t};\n\t\tconsole.log(score);\n\t\t $('#score').text('Your score is ' + score);\n\t\treturn score;\n\n\t}", "function ifAnswerCorrect(){\n userAnswerFeedbackCorrect();\n updateScore();\n}", "function submitScore(score, game, action, error) {\n getAjax(\"/scoreboard/request\", function(request) {\n if(request !== \"error\") {\n let object = JSON.parse(request);\n let value = 345 + parseInt(score) * parseInt(object.y) + parseInt(object.z) - 345;\n postAjax(\"/scoreboard/submit\", {\n \"key\": object.x,\n \"value\": value,\n \"game\": game\n }, function(submit){\n action(submit);\n });\n } else {\n error();\n }\n });\n}", "function submitScore(score, game, action, error) {\r\n getAjax(\"/scoreboard/request\", function(request) {\r\n if(request !== \"error\") {\r\n let object = JSON.parse(request);\r\n let value = 345 - parseInt(score) * parseInt(object.y) + parseInt(object.z) - 345;\r\n postAjax(\"/scoreboard/submit\", {\r\n \"key\": object.x,\r\n \"value\": value,\r\n \"game\": game\r\n }, function(submit){\r\n action(submit);\r\n });\r\n } else {\r\n error();\r\n }\r\n });\r\n}", "function submitScore(score, game, action, error) {\r\n getAjax(\"/scoreboard/request\", function(request) {\r\n if(request !== \"error\") {\r\n let object = JSON.parse(request);\r\n let value = 345 + parseInt(score) * parseInt(object.y) + parseInt(object.z) - 345;\r\n postAjax(\"/scoreboard/submit\", {\r\n \"key\": object.x,\r\n \"value\": value,\r\n \"game\": game\r\n }, function(submit){\r\n action(submit);\r\n });\r\n } else {\r\n error();\r\n }\r\n });\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Represents a grid of fillin bubbles. json_init: JSON // initialization values that come from a JSON file update_init: JSON // initialization values that come from updating the field
function BubbleField(json_init, update_init) { GridField.call(this, json_init, update_init); /* Set all bubble attributes. */ this.field_type = 'bubble'; this.grid_class = 'bubble_div'; this.data_uri = "bubbles"; this.cf_advanced = {flip_training_data : false}; this.cf_map = {empty : false}; if (json_init) { this.param = json_init.param; this.type = json_init.type; this.grid_values = json_init.grid_values; } else { // set the class of the grid elements this.ele_class = ($("#bubb_size").val() == 'small') ? 'bubble_small' : ($("#bubb_size").val() == 'medium') ? 'bubble_med' : 'bubble_large'; // set the bubble type this.type = $("#bubb_type").val(); // set param according to the type if (this.type == 'tally') { this.param = $("#num_row_bubbles").val() * $("#num_col_bubbles").val(); } else if (this.type == 'select1') { this.param = 'yes_no'; } else if (this.type == 'select_many') { this.param = 'many'; // TODO: find out what this value should actually be } else { console.log("error, unsupported bubble type"); } // bubble size this.element_width = ($("#bubb_size").val() == 'small') ? BUBBLE_SMALL : ($("#bubb_size").val() == 'medium') ? BUBBLE_MEDIUM : BUBBLE_LARGE; this.element_height = ($("#bubb_size").val() == 'small') ? BUBBLE_SMALL : ($("#bubb_size").val() == 'medium') ? BUBBLE_MEDIUM : BUBBLE_LARGE; // set bubble values grid_values = []; $(".grid_value").each(function() { grid_values.push($(this).val()); }); this.grid_values = grid_values; // checking whether there is a duplicate value or not is_value_valid(this.grid_values); } }
[ "function GridField(json_init, update_init, field_group) {\n\tthis.$grid_div = $('<div/>');\n\tthis.$grid_div.data(\"obj\", this);\n\t\n\tif (json_init) {\n\t\tthis.order = json_init.order;\n\t\tthis.num_rows = json_init.num_rows;\n\t\tthis.num_cols = json_init.num_cols;\n\t\tthis.margin_top = json_init.margin_top;\n\t\tthis.margin_bottom = json_init.margin_bottom;\n\t\tthis.margin_left = json_init.margin_left;\n\t\tthis.margin_right = json_init.margin_right;\n\t\tthis.element_height = json_init.element_height;\n\t\tthis.element_width = json_init.element_width;\n\t\tthis.ele_class = json_init.ele_class;\n\t\tthis.$grid_div.css({top: rem(json_init.top), \n\t\t\t\t\t\t\tleft: rem(json_init.left), \n\t\t\t\t\t\t\tzIndex: json_init.zIndex});\n\t\tthis.border_width = json_init.border_width;\n\t\tthis.name = json_init.name;\n\t\tthis.displayText = json_init.displayText;\n\t\t//this.field_priority = json_init.field_priority; making change here\n\t\tthis.verify = json_init.verify;\n\t} else {\n\t\tif (update_init) {\n\t\t\t// invoked from Update Field button\n\t\t\tthis.$grid_div.css({top: rem(update_init.top), \n\t\t\t\t\t\t\tleft: rem(update_init.left), zIndex: update_init.zIndex});\n\t\t} else {\n\t\t\tthis.$grid_div.css({top: rem(0), left: rem(0), zIndex: globZIndex.getZ()});\n\t\t\tglobZIndex.incrZ();\n\t\t}\n\t\t\n\t\t// margin values\n\t\tthis.margin_top = parseInt($(\"#margin_top\").val());\n\t\tthis.margin_bottom = parseInt($(\"#margin_bottom\").val());\n\t\tthis.margin_left = parseInt($(\"#margin_left\").val());\n\t\tthis.margin_right = parseInt($(\"#margin_right\").val());\n\t\t\n\t\t// number of rows\n\t\tthis.num_rows = $(\"#num_row\").val();\n\t\t\n\t\t// number of columns\n\t\tthis.num_cols = $(\"#num_col\").val();\n\t\t\n\t\t// set border with\n\t\tthis.border_width = $(\"#border_width\").val();\n\t\t\n\t\t// set other field attributes\n\t\tthis.order = $(\"#order\").val();\n\t\tthis.name = $(\"#field_name\").val();\n\t\tthis.displayText = $(\"#field_display_text\").val();\n\t\t//.field_priority = $(\"#field_priority\").val(); changing here\n\t\t//.verify = $(\"#verified\").val();\n\t\tif ($(\"#verified\").val() == \"\") {\n this.verify = \"Yes\";\n\t\t} else {\n\t\t\tthis.verify = $(\"#verified\").val();\n\t\t}\n\t}\n}", "fillGrid(object) {\n\n for (var column = 0; column < this.columns; column++) {\n\n let thisColumn = [];\n for (var row = 0; row < this.rows; row++) {\n\n let filledGrid = new object(column, row, this.gridSpacing);\n thisColumn[row] = filledGrid;\n\n }\n\n this.grid[column] = thisColumn;\n\n }\n }", "function updateJSON(){\n\tJsonObject = {\"hexGrid\" : [] };\n\tfor(var x = 0; x<COASTALDEFENDER.g;x++){\n\t\tJsonObject[\"hexGrid\"].push([]);\n\t\tfor(var y = 0; y<COASTALDEFENDER.i;y++){\n\t\t\tJsonObject[\"hexGrid\"][x].push({\n\t\t\t\t\"xCord\" : x,\n\t\t\t\t\"yCord\" : y,\n\t\t\t\t\"terrain\" : newGrid.grid[x][y].terrain,\n\t\t\t\t\"modified\" : '',\n\t\t\t\t\"hasLine\" : newGrid.grid[x][y].hasLine,\n\t\t\t});\n\t\t\n\t\t}\n\t}\n\treturn JsonObject;\n}", "createInitialGrid() {\n let gridArray = [];\n for(let row = 0; row < this.gridData.getSize(); row++){\n for(let col = 0; col < this.gridData.getSize(); col++){\n let cell = new Cell(row, col);\n gridArray.push(cell);\n }\n }\n\n this._setInitialValues(gridArray);\n }", "initialState(json) {\n let size, puzzle, result;\n ({ size, puzzle } = json);\n result = { rows: [], trees: {}, treeCount: 0 };\n for (let i = 0; i < size; i++) {\n let row = { cols: [], index: i };\n for (let j = 0; j < size; j++) {\n let col = {\n row: i,\n col: j,\n park: puzzle[i][j],\n value: \"\",\n };\n row.cols.push(col);\n result.trees[[i, j].toString()] = false;\n }\n result.rows.push(row);\n }\n return result;\n }", "init() {\n this.prepareGrid();\n this.configureCells();\n }", "constructor() {\n this.grid = [[], [], []]; \n // alt: rows/ cols\n this.size = 3; \n \n }", "function initialHeatmaps(){\r\n setupHeatmap(jsonData.length);\r\n setupGlbHeatmap();\r\n}", "setup(jsonEntry) {\n this.name = jsonEntry.name;\n this.altNames = jsonEntry.altNames;\n this.iconName = jsonEntry.iconName;\n this.visible = jsonEntry.visible;\n this.priority = jsonEntry.priority;\n this.iconMinLevel = jsonEntry.iconMinLevel;\n this.iconMaxLevel = jsonEntry.iconMaxLevel;\n this.textMinLevel = jsonEntry.textMinLevel;\n this.textMaxLevel = jsonEntry.textMaxLevel;\n switch (jsonEntry.stackMode) {\n case \"yes\":\n this.stackMode = harp_datasource_protocol_1.PoiStackMode.Show;\n break;\n case \"no\":\n this.stackMode = harp_datasource_protocol_1.PoiStackMode.Hide;\n break;\n case \"parent\":\n this.stackMode = harp_datasource_protocol_1.PoiStackMode.ShowParent;\n break;\n default:\n }\n }", "constructor(foodJson)\n {\n this.x = foodJson[\"x\"];\n this.y = -foodJson[\"y\"]; // drawing coordinates have down as positive y\n this.radius = foodJson[\"radius\"];\n //this.q = siteJson[\"q_value\"];\n }", "function fillInitCells(currentGrid) {\n const totalStartNodes = currentGrid.params.node.totalStart\n for (let i = 1; i <= totalStartNodes; i++) {\n const cellCoor = selectRandomCell(currentGrid.totalColumns, currentGrid.totalRows);\n currentGrid.grid.columns[cellCoor.column][cellCoor.row].color = rangedRandomRGB(currentGrid.params);\n currentGrid.grid.columns[cellCoor.column][cellCoor.row].opacity = 1;\n currentGrid.totalCellsFilled += 1\n currentGrid.fillableCells = currentGrid.fillableCells.concat(getSurrEmpties(currentGrid.grid.columns, cellCoor))\n }\n return currentGrid\n}", "fetchGrid(url, obj) {\n fetch(url).then(function(response) {\n return response.json()\n }).then(function(data) {\n let newGrid = data.cells\n let width = newGrid.length\n let height = newGrid[0].length\n\n obj.setWidth(width)\n obj.setHeight(height)\n obj.board.grid = obj.board.createGrid()\n obj.board.resultGrid = obj.board.createGrid()\n\n for(let col = 0; col < obj.width; col++) {\n for(let row = 0; row < obj.height; row++) {\n obj.board.grid[col][row] = newGrid[col][row]\n }\n }\n game.createTable()\n game.render()\n console.log(game.getWidth())\n console.log(game.getHeight())\n $('width').val(game.getWidth())\n $('height').val(game.getHeight())\n }).catch(function() {\n console.error(\"Error fetching.\")\n })\n }", "function loadData() {\n let bubbleData = data['bubbles'];\n for (let i = 0; i < bubbleData.length; i++) {\n // Get each object in the array\n let x = bubbleData[i].x;\n let y = bubbleData[i].y;\n let diameter = bubbleData[i].diameter;\n let name = bubbleData[i].name;\n let r = bubbleData[i].r;\n let g = bubbleData[i].g;\n let b = bubbleData[i].b;\n let e = bubbleData[i].e;\n let t = bubbleData[i].Total_States\n\n // Put object in array\n bubbles.push(new Bubble(x, y, t, diameter, name, r, g, b, e,));\n }\n}", "makeGridCorrectLayer() {\n return {\n id: 'change-grid',\n type: 'fill',\n source: {\n type: 'geojson',\n data: this.squareGridGeoJSON\n },\n layout: {},\n paint: {\n 'fill-color': [\n 'match',\n ['get', 'v'],\n 1, this.selectedBox,\n /* other */ this.defaultGreyBox\n ],\n 'fill-opacity': 0.5\n }\n };\n }", "constructGrid() {\n\t\tthis.grid = [];\n\n\t\tfor (let i = 0; i < this.x; i++) {\n\t\t\tthis.grid.push([]);\n\t\t\tfor (let b = 0; b < this.y; b++) {\n\t\t\t\tthis.grid[i].push(new Block({x: i, y: b}, this));\n\t\t\t}\n\t\t}\n\t}", "export() {\n const json = {}\n // saves the grid size and grid as a list\n json.size = [this.sizex,this.sizey]\n json.grid = []\n this._grid.forEach(ycol => {\n ycol.forEach(tile => {\n if (tile.size[0] != 0 && tile.size[1] != 0) {\n // saves only the nessary details to the file; emtpy tiles are ingroned\n json.grid.push({\n position:tile.position,\n size:tile.size,\n logo:tile.logo,\n inverted:tile.inverted,\n state:tile.state\n })\n }\n })\n })\n saveJSON(json,'nodeMap.json',true)\n }", "init() {\n //Add style class to info box\n this.container.getElementById('info-box').classList.add(this.color);\n\n //Add data content\n this.container.getElementById('i1t').innerHTML = this.data[1].title;\n this.container.getElementById('i1p').innerHTML = this.data[1].percentage;\n this.container.getElementById('i1v').innerHTML = this.data[1].value;\n\n this.container.getElementById('i2t').innerHTML = this.data[2].title;\n this.container.getElementById('i2p').innerHTML = this.data[2].percentage;\n this.container.getElementById('i2v').innerHTML = this.data[2].value;\n }", "function gotData(data) {\n\n console.log(data); // Print the data in the console\n\n // iterate through the array of data and create an object and push it on an array called bubbles\n for (let i = 0; i < data.length; i++) {\n bubbles.push(new Bubble(data[i].Name, data[i].Main, data[i].Side)); // THESE Name and Shape need to match your column names in your spreadsheet!\n }\n \n}", "function loadData() {\n let bubbleData = data['bubbles'];\n for (let i = 0; i < bubbleData.length; i++) {\n // Get each object in the array\n let bubble = bubbleData[i];\n // Get a position object\n let position = bubble['position'];\n // Get x,y from position\n let x = position['x'];\n let y = position['y'];\n\n // Get diameter and label\n let diameter = bubble['diameter'];\n let label = bubble['label'];\n\n // Put object in array\n bubbles.push(new Bubble(x, y, diameter, label));\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
B. For debugging: Output array contents to alert box
function showArray(array) { var text = ""; for (j = 0; j < array.length; j++) { text += "\n" + array[j]; } return alert(text); }
[ "function showArray(output) {\n var text = \"\";\n for (j = 0; j < output.length; j++) {\n text += \"\\n\" + output[j];\n }\n return alert(text);\n}", "function debugArray(array) {\r\n\tvar txt = '';\r\n\tfor(i=0 ; i<array.length ; i++) {\r\n\t\tfor(j=0 ; j<array[i].length ; j++) {\r\n\t\t\tif(array[i][j])\r\n\t\t\t\ttxt += array[i][j];\r\n\t\t\telse\r\n\t\t\t\ttxt += 'X';\r\n\t\t\ttxt += ' ';\r\n\t\t}\r\n\t\ttxt += \"\\n\";\r\n\t}\r\n\talert(txt);\r\n}", "function logArrayContents(array){\n\t\"use strict\";\n\tfor(var i=0;i<array.length;i++){\n\t\tconsole.log(array[i]);\n\t}\n}", "function PrintArrayVals(arr){\n}", "function dumpArray(array) {\n console.log('[');\n array.forEach(function(value){\n console.log(' ' + value);\n });\n console.log(']');\n}", "function printArrayAsString(myArray){\r\n \r\n}", "function displaySelectedArrays() {\n console.log(confirmUppercase());\n console.log(confirmLowercase());\n console.log(confirmNumbers());\n console.log(confirmSymbols());\n}", "printEntryArray() {\r\n console.log(this._entry_array);\r\n }", "function show_alert(info) {\n var text = \"\";\n for(i = 0; i < info.length; i++) {\n text += info[i] + \"\\n\";\n }\n alert(text);\n}", "function PrintArrayVals(arr){\n\tfor (var i=0; i<arr.length; i++){\n\t\tconsole.log(arr[i])\n\t}\n}", "function log_array(a){\n\tfor(var i = 0; i < a.length; i++){\n\t\tconsole.log(a[i]);\n\t}\n}", "function print_array(array){\n\tfor(var i =0; i< array.length; i++){\n\t\tconsole.log(array[i]);\n\t}\n}", "function showArray(array) {\n document.write('[');\n //document.write(array.toString());\n /*\n * array.toString() does this without the spaces between elements\n */\n for (var index = 0; index < array.length; ++index) {\n document.write(array[index]);\n if (index < array.length - 1)\n document.write(\", \");\n }\n document.write(']');\n putline();\n}", "function printArrayVals(arr){\n\tfor(var idx = 0; idx < arr.length; idx++){\n\t\tconsole.log(\"arr[\", idx, \"]=\", arr[idx])\n\t}\n}", "function emergency_print(){\r\n\tdocument.write(MAIN_ARRAY);\r\n}", "function alertJsFileVersionArray() {\n\tvar text = \"Loaded scripts:\";\n\tfor (var id = 0; id < jsVersionArray.length; id++) {\n\t\tfor (var elem in jsVersionArray[id]) {\n\t\t\tif (elem == 'file') text += '\\n'+jsVersionArray[id][elem];\n\t\t\telse text += '\\n\\t'+elem+\"=\"+jsVersionArray[id][elem];\n\t\t}\n\t}\n\talert(text);\n}", "function printArrayValues(array) {\n // YOUR CODE BELOW HERE //\n //Input- loop\n //Output- values of the Array\n //Constraints-use a loop to iterate over Array and console.log(valuesOfArray)\n //Edge Cases-console.log() its values\n \n \n for(var i=0; i<array.length; i++) {\n console.log(array[i]);\n }\n}", "function arrValuePrinter(array) {\n\tvar result = \"\";\n\tfor (var i=0; i<array.length; i++) {\n\t\tresult += array[i] + \" \";\n\t}return result;\n}", "function debugArrayPrint(arr) {\n\t\tvar output = '';\n\t\tfor (var j = 0; j < arr.length; j++) {\n\t\t\tfor (var p = 0; p < arr[j].length; p++) {\n\t\t\t\toutput += String(arr[j][p]);\n\t\t\t}\n\t\t\toutput += \"\\n\";\n\t\t}\n\t\tconsole.log(output);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate the Title and Message for the changeConfModal / Requires: / type: code representing the type of change to be confirmed / elem: clicked element originating the popChangeConfModal() call eslintdisablenextline nounusedvars
function popChangeConfModal(type, elem) { // Set modal title let title = 'Confirmation Required'; // Set modal message based on type let message; switch (type) { case 'sa': // Single answer message = 'If you disable multiple choice, all existing multiple ' + 'choice options for this question will be deleted.'; break; case 'mc': // Multiple Choice message = 'If you enable multiple choice, existing answer data for ' + 'this question will be deleted.'; break; case 'rq': // Remove question message = 'Are you sure you wish to delete this question?'; break; case 'rr': // Remove round message = 'If you delete this round, all associated questions will ' + 'also be deleted.'; break; case 'dq': // Delete quiz message = 'If you delete this quiz, all associated rounds and ' + 'questions will also be deleted.'; break; case 'ce': // Cancel edit message = 'All unsaved changes will be lost.'; break; case 'cn': // Cancel new message = 'This quiz will not be created, and any content added to ' + 'this form will be lost.'; break; case 'rm': // Remove multiple choice option message = 'Are you sure you wish to delete this multiple choice ' + 'option?'; break; default: return; } // If type is not rq or rm, append 'Do you wish to continue?' to the message if (type !== 'rq' && type !== 'rm') { message += '<br><br>Do you wish to continue?'; } // display the title $('#modalTitle').html(title); // display the message $('#modalMessage').html(message); // Set the removeActionParams global object removeActionParams = {type, elem}; // Get the MaterializeCSS Modal instance for the changeConfModal let instance = M.Modal. getInstance(document.querySelector('#changeConfModal')); // Open the modal instance.open(); }
[ "function ModConfirmOpen(mode) {\n console.log(\" ----- ModConfirmOpen ----\")\n console.log(\"mode\", mode)\n //modes are \"copy_scores\" and \"undo_submitted\" (not in use)\n // only used to copy scores to grade page\n\n mod_dict = {mode: mode, is_test: true, show_modal: false};\n\n let hide_save_btn = false, has_selected_item = false;\n let msg_html = \"\";\n let header_text = null;\n let btn_save_txt = loc.Save, btn_cancel_txt = loc.Cancel;\n\n if (permit_dict.permit_submit_exam && permit_dict.requsr_same_school) {\n if (mode === \"copy_scores\"){\n mod_dict.show_modal = true;\n\n header_text = loc.Copy_wolf_scores_to_grades;\n\n if (loc.examperiod_caption && setting_dict.sel_examperiod) {\n header_text += \" - \" + loc.examperiod_caption[setting_dict.sel_examperiod];\n };\n\n // --- put text in modal form\n let dep_lvl_str = setting_dict.sel_depbase_code;\n if (setting_dict.sel_dep_level_req){\n const lvl_str = (setting_dict.sel_lvlbase_pk) ? setting_dict.sel_lvlbase_code : loc.All_levels;\n dep_lvl_str += \" - \" + lvl_str;\n }\n const subject_name = (setting_dict.sel_subject_pk) ?\n (setting_dict.sel_subject_name) ? setting_dict.sel_subject_name : \"---\" : loc.All_subjects;\n\n msg_html = [\"<p>\", loc.Wolf_scores_willbe_copied, \"</p>\",\n\n \"<ul><li>\", dep_lvl_str, \"</li>\",\n \"<li>\", subject_name, \"</li></ul>\",\n\n \"<p>\", loc.Only_submitted_exams_willbe_copied, \"<br>\",\n loc.Existing_scores_willbe_overwritten, \"<br>\",\n loc.except_when_approved, \"</p>\",\n\n \"<p>\", loc.Do_you_want_to_continue, \"</p>\"].join(\"\");\n\n add_or_remove_class(document.getElementById(\"id_mod_confirm_size\"),\"modal-lg\", true, \"modal-md\");\n\n ModConfirmSave();\n\n } else if (mode === \"undo_submitted\"){\n\n header_text = loc.Remove_submitted_from_exam;\n\n const tblName = \"grades\";\n const selected_pk = setting_dict.sel_grade_exam_pk;\n\n // --- lookup data_dict in data_rows\n const data_rows = grade_exam_rows;\n const [index, found_dict, compare] = b_recursive_integer_lookup(data_rows, \"id\", selected_pk);\n const data_dict = (!isEmpty(found_dict)) ? found_dict : null;\n\n console.log(\" data_dict\", data_dict)\n if (isEmpty(data_dict)){\n b_show_mod_message_html(loc.No_exam_selected);\n\n } else if (!data_dict.ce_exam_id){\n b_show_mod_message_html(loc.Candidate_has_no_exam);\n } else if (!data_dict.ce_exam_published_id){\n b_show_mod_message_html(loc.Wolf_scores_not_published);\n\n\n } else {\n // --- create mod_dict\n\n\n mod_dict.show_modal = true;\n\n mod_dict.examyear_pk = setting_dict.sel_examyear_pk;\n mod_dict.depbase_pk = setting_dict.sel_depbase_pk;\n mod_dict.mapid = data_dict.mapid;\n mod_dict.grade_pk = data_dict.id;\n\n mod_dict.subject_pk = data_dict.subj_id;\n mod_dict.subj_name_nl = data_dict.subj_name_nl;\n mod_dict.exam_name = data_dict.exam_name;\n mod_dict.fullname = data_dict.fullname;\n mod_dict.student_pk = data_dict.student_id;\n\n //console.log(\"mod_dict\", mod_dict);\n // --- put text in modal form\n\n msg_html = [\"<p class='pb-2'>\", loc.Submitted_will_be_removed_from_exam, \"</p><p>\",\n \"&emsp;\", mod_dict.exam_name, \"<br>\",\n \"&emsp;\", mod_dict.subj_name_nl, \"<br>\",\n \"&emsp;\", mod_dict.fullname, \"</p><p class='py-2'>\",\n loc.Do_you_want_to_continue, \"</p>\"].join(\"\");;\n\n btn_save_txt = !has_selected_item ? loc.OK : loc.Yes_remove ;\n btn_cancel_txt = (has_selected_item) ? loc.No_cancel : loc.Close;\n\n };\n };\n\n if(mod_dict.show_modal){\n el_confirm_header.innerText = header_text;\n\n el_confirm_msg_container.classList.remove(\"border_bg_invalid\", \"border_bg_valid\");\n el_confirm_msg_container.innerHTML = msg_html;\n\n el_confirm_btn_save.innerText = btn_save_txt;\n add_or_remove_class (el_confirm_btn_save, \"btn-outline-danger\", false, \"btn-primary\");\n add_or_remove_class (el_confirm_btn_save, cls_hide, hide_save_btn);\n\n el_confirm_btn_cancel.innerText = btn_cancel_txt;\n\n // set focus to cancel button\n setTimeout(function (){\n el_confirm_btn_cancel.focus();\n }, 500);\n\n // show modal\n $(\"#id_mod_confirm\").modal({backdrop: true});\n };\n }; // if (permit_dict.permit_crud && permit_dict.requsr_role_admin )\n\n }", "function initChangeConfModal() {\n\n /* Callback function on modal close */\n const resetModal = () => {\n // If the removeActionParams global object exec parameter is false...\n // eslint-disable-next-line no-unused-vars\n if (!removeActionParams.exec) {\n // Confirmation was denied...\n switch (removeActionParams.type) {\n case 'sa': // Single answer\n // Check the .quizMulti checkbox\n $(removeActionParams.elem).prop('checked', true);\n break;\n case 'mc': // Multiple choice\n // Uncheck the .quizMulti checkbox\n $(removeActionParams.elem).prop('checked', false);\n break;\n default:\n }\n }\n\n // Clear the removeActionParams global\n removeActionParams = \"\";\n\n // Clear the modal title text\n $('#modalTitle').html(\"Title\");\n\n // Clear the modal message text\n $('#modalMessage').html(\"Message\");\n };\n\n // Initialise MaterializeCSS Modal\n M.Modal.init(document.querySelector('#changeConfModal'), {\n onCloseEnd: resetModal,\n preventScrolling: true\n });\n}", "function openConfimrationMsgPopup(confirmationMsg) {\n\t $(\"#confirmationMsgModalBody\").text(confirmationMsg);\t\n\t $(\"#confirmationMsgmodel\").modal(\"show\");\t\n }", "toggleConfirmChangesButton() {\n\t\tif ( ! this.props.isEditing ) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet settingsMapping = {\n\t\t\tanonymizeIP: 'anonymizeIP',\n\t\t\tselectedAccount: 'accountID',\n\t\t\tselectedProperty: 'propertyID',\n\t\t\tselectedProfile: 'profileID',\n\t\t\tselectedinternalWebProperty: 'internalWebPropertyID',\n\t\t\tuseSnippet: 'useSnippet',\n\t\t\tampClientIDOptIn: 'ampClientIDOptIn',\n\t\t\ttrackingDisabled: 'trackingDisabled',\n\t\t};\n\n\t\t// Prevent saving if \"setup account\" is chosen.\n\t\tif ( '-1' === this.state.selectedAccount ) {\n\t\t\tsettingsMapping = {};\n\t\t}\n\n\t\ttoggleConfirmModuleSettings( 'analytics', settingsMapping, this.state );\n\t}", "function ModConfirm_Cesuur_Nterm_Open(mode, el_input) {\n console.log(\" ----- ModConfirm_Cesuur_Nterm_Open ----\")\n if (permit_dict.permit_crud && permit_dict.requsr_role_admin) {\n let hide_save_btn = false, has_selected_item = false;\n\n // --- put text in modal form\n const msg_list = [];\n if (mode === \"cesuur\"){\n msg_list.push( [\"<p class='pb-2'>\", loc.Enter_cesuur_01,\n (mod_dict.cesuur) ? mod_dict.cesuur : '-',\n loc.Enter_cesuur_02, \"</p><p>\",\n \"&emsp;\", mod_dict.exam_name, \"</p><p class='py-2'>\",\n loc.Enter_cesuur_03, \"</p>\"].join(\"\")\n );\n } else if (mode === \"nterm\"){\n msg_list.push( [\"<p class='pb-2'>\", loc.Enter_nterm_01,\n (mod_dict.nterm) ? mod_dict.nterm : '-',\n loc.Enter_cesuur_02, \"</p><p>\",\n \"&emsp;\", mod_dict.exam_name, \"</p><p class='py-2'>\",\n loc.Enter_cesuur_03, \"</p>\"].join(\"\")\n );\n }\n msg_list.push(\"<p>\" + loc.Do_you_want_to_continue + \"</p>\")\n const msg_html = msg_list.join(\"\");\n\n const header_text = (mode === \"nterm\") ? loc.Enter_nterm : loc.Enter_cesuur;\n const btn_cancel_txt = loc.No_cancel;\n const btn_save_txt = loc.Yes_save;\n\n el_confirm_header.innerText = header_text;\n el_confirm_loader.classList.add(cls_visible_hide);\n el_confirm_msg_container.classList.remove(\"border_bg_invalid\", \"border_bg_valid\");\n el_confirm_msg_container.innerHTML = msg_html;\n\n el_confirm_btn_save.innerText = btn_save_txt;\n add_or_remove_class (el_confirm_btn_save, \"btn-outline-danger\", false, \"btn-primary\");\n add_or_remove_class (el_confirm_btn_save, cls_hide, false);\n el_confirm_btn_cancel.innerText = btn_cancel_txt;\n\n // set focus to cancel button\n setTimeout(function (){\n el_confirm_btn_cancel.focus();\n }, 500);\n\n // show modal\n $(\"#id_mod_confirm\").modal({backdrop: true})\n\n };\n }", "function ModConfirm_PartexCheck_Open() {\n console.log(\" ----- ModConfirm_PartexCheck_Open ----\")\n\n // --- create mod_dict\n mod_dict = {mode: \"remove_partex\"};\n\n const data_dict = mod_MEX_dict.partex_dict[mod_MEX_dict.sel_partex_pk];\n const partex_name = (data_dict) ? data_dict.name : \"-\";\n\n const msg_html = [\"<p class=\\\"p-2\\\">\", loc.All_partex_willbe_removed, \"<br>\",\n loc.except_for_selected_exam, \" '\", partex_name, \"'.\",\n \"</p><p class=\\\"p-2\\\">\", loc.Do_you_want_to_continue, \"</p>\"].join(\"\")\n el_confirm_msg_container.innerHTML = msg_html;\n\n el_confirm_header.innerText = loc.Remove_partial_exams;\n el_confirm_loader.classList.add(cls_visible_hide);\n el_confirm_msg_container.classList.remove(\"border_bg_invalid\", \"border_bg_valid\");\n el_confirm_btn_save.innerText = loc.Yes_remove;\n add_or_remove_class(el_confirm_btn_save, \"btn-outline-secondary\", true, \"btn-primary\")\n\n el_confirm_btn_cancel.innerText = loc.No_cancel;\n\n// set focus to cancel button\n setTimeout(function (){\n el_confirm_btn_cancel.focus();\n }, 500);\n\n// show modal\n $(\"#id_mod_confirm\").modal({backdrop: true});\n\n }", "function launchConfEmailModal() {\n var html = HtmlService.createHtmlOutputFromFile('resendConfM')\n .setWidth(350)\n .setHeight(105);\n SpreadsheetApp.getUi() \n .showModalDialog(html, '🤖 Resending confirmation...');\n}", "function createUI() {\n function prop(title, type, id) {\n return { title, type, id };\n }\n\n let modalProps = [\n prop('\"Show Tags\" button', 'toggle', 'showTags'),\n prop('Custom Style', 'toggle', 'style'),\n prop('\"Google It\" button', 'toggle', 'searchBtn'),\n ];\n\n // Create the actual nodes based on the props\n modalProps = modalProps.map(p => {\n if (p.type == 'toggle') {\n let wrapper = dom.element('div');\n\n let checkbox = dom.element('input', { \n type: 'checkbox',\n checked: config[p.id],\n id: p.id,\n });\n dom.on(checkbox, 'change', () => {\n // Update property value when the checkbox is toggled\n config[p.id] = checkbox.checked;\n save();\n });\n\n let label = dom.element('label', { innerText: p.title });\n label.setAttribute('for', p.id);\n\n wrapper.appendChild(checkbox);\n wrapper.appendChild(label);\n return wrapper;\n }\n });\n\n // Create the modal and its children\n let modalInner = dom.element('div', { className: 'cfpp-modal-inner' , children: modalProps });\n modalInner.append('Refresh the page to apply changes'); // TODO: not this\n\n let modalBg = dom.element('div', { className: 'cfpp-modal-background' });\n dom.on(modalBg, 'click', closeUI); // clicking on the background closes the UI\n\n let modal = dom.element('div', { \n className: 'cfpp-config cfpp-modal cfpp-hidden',\n children: [ modalBg, modalInner ]\n });\n\n // Create the button that shows the modal\n let modalBtn = dom.element('a', { \n className: 'cfpp-config-btn', \n innerText: \"[++]\"\n });\n dom.on(modalBtn, 'click', ev => {\n ev.preventDefault();\n modal.classList.remove('cfpp-hidden');\n });\n\n // Append the created elements to the DOM\n document.body.appendChild(modal);\n dom.$('.lang-chooser').children[0].prepend(modalBtn);\n\n // TODO: Jesus fucking Christ I need a unified .css file for everything\n // FIXME: what am I doing\n // PRIORITY: highest\n let style = `\n .cfpp-hidden {\n display: none;\n opacity: 0;\n transition: opacity 0.3s;\n }\n\n .cfpp-config-btn {\n font-size: 22px !important;\n cursor: pointer;\n }\n\n .cfpp-modal {\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n z-index: 101;\n }\n .cfpp-modal-background {\n position: absolute;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: #00000087;\n }\n .cfpp-modal-inner {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 60vw;\n max-height: 80vh;\n background: white;\n padding: 2em;\n border-radius: 6px;\n overflow: auto;\n }\n .cfpp-config-inner>div {\n margin-bottom: 0.5em;\n }\n\n .cfpp-config label {\n margin-left: 0.5em;\n }\n `;\n document.body.appendChild(dom.element('style', {\n innerHTML: style\n }));\n}", "function OpenConfirmation(c, p, m, lb, me, fc) {\n\n var arrParam = [];\n var arrParameters = new Array();\n var vlp;\n if (typeof c != \"undefined\" && c != null) {\n p = $.trim(p);\n if (p && p != null)\n arrParam = p.split(\" \");\n $.each(arrParam, function (ind, namep) {\n namep = $.trim(namep);\n vlp = c.attr(namep);\n if (typeof vlp != 'undefined' && vlp != null)\n arrParameters.push(vlp);\n });\n }\n\n BootstrapDialog.show({\n title: 'Mensaje de Confirmaci&oacute;n',\n type: BootstrapDialog.TYPE_PRIMARY,\n message: m,\n buttons: [{\n label: lb,\n cssClass: 'btn btn-primary',\n icon: 'fa fa-check',\n hotkey: 13,\n autospin: true,\n action: function (dialogConfirm) {\n dialogConfirm.enableButtons(false);\n dialogConfirm.setClosable(false);\n dialogConfirm.getModalBody().html(me);\n var efunction = window[fc];\n if (arrParameters.length > 0)\n efunction(dialogConfirm, arrParameters.join());\n else\n efunction(dialogConfirm);\n }\n }, {\n label: 'Cancelar',\n cssClass: 'btn btn-danger',\n icon: 'fa fa-times',\n action: function (dialogConfirm) {\n dialogConfirm.close();\n }\n }]\n });\n}", "function setParameters(params) {\n var modal = getModal();\n\n var $title = modal.querySelector('h2'),\n $text = modal.querySelector('p'),\n $cancelBtn = modal.querySelector('button.cancel'),\n $confirmBtn = modal.querySelector('button.confirm');\n\n // Title\n $title.innerHTML = (params.html) ? params.title : escapeHtml(params.title).split(\"\\n\").join(\"<br>\");\n\n // Text\n $text.innerHTML = (params.html) ? params.text : escapeHtml(params.text || '').split(\"\\n\").join(\"<br>\");\n\n if (params.text) {\n show($text);\n }\n\n //Custom Class\n if (params.customClass) {\n addClass(modal, params.customClass);\n modal.setAttribute('data-custom-class', params.customClass);\n } else {\n // Find previously set classes and remove them\n var customClass = modal.getAttribute('data-custom-class');\n removeClass(modal, customClass);\n modal.setAttribute('data-custom-class', \"\");\n }\n\n // Icon\n hide(modal.querySelectorAll('.sa-icon'));\n if (params.type) {\n var validType = false;\n for (var i = 0; i < alertTypes.length; i++) {\n if (params.type === alertTypes[i]) {\n validType = true;\n break;\n }\n }\n if (!validType) {\n logStr('Unknown alert type: ' + params.type);\n return false;\n }\n\n var typesWithIcons = ['success', 'error', 'warning', 'info'];\n var $icon;\n\n if (!Array.prototype.indexOf){\n Array.prototype.indexOf = function(elt /*, from*/)\n {\n var len = this.length >>> 0;\n\n var from = Number(arguments[1]) || 0;\n from = (from < 0)\n ? Math.ceil(from)\n : Math.floor(from);\n if (from < 0)\n from += len;\n\n for (; from < len; from++)\n {\n if (from in this &&\n this[from] === elt)\n return from;\n }\n return -1;\n };\n }\n\n\n if (typesWithIcons.indexOf(params.type) !== -1) {\n $icon = modal.querySelector('.sa-icon.' + 'sa-' + params.type);\n show($icon);\n }\n\n var $input = getInput();\n\n // Animate icon\n switch (params.type) {\n\n case \"success\":\n addClass($icon, 'animate');\n addClass($icon.querySelector('.sa-tip'), 'animateSuccessTip');\n addClass($icon.querySelector('.sa-long'), 'animateSuccessLong');\n break;\n\n case \"error\":\n addClass($icon, 'animateErrorIcon');\n addClass($icon.querySelector('.sa-x-mark'), 'animateXMark');\n break;\n\n case \"warning\":\n addClass($icon, 'pulseWarning');\n addClass($icon.querySelector('.sa-body'), 'pulseWarningIns');\n addClass($icon.querySelector('.sa-dot'), 'pulseWarningIns');\n break;\n\n case \"input\":\n case \"prompt\":\n $input.setAttribute('type', params.inputType);\n addClass(modal, 'show-input');\n setTimeout(function() {\n $input.focus();\n $input.addEventListener ? $input.addEventListener('keyup', swal.resetInputError) : $input.attachEvent('onkeyup', swal.resetInputError);\n }, 400);\n break;\n }\n }\n\n // Custom image\n if (params.imageUrl) {\n var $customIcon = modal.querySelector('.sa-icon.sa-custom');\n\n $customIcon.style.backgroundImage = 'url(' + params.imageUrl + ')';\n show($customIcon);\n\n var _imgWidth = 80,\n _imgHeight = 80;\n\n if (params.imageSize) {\n var dimensions = params.imageSize.toString().split('x');\n var imgWidth = dimensions[0];\n var imgHeight = dimensions[1];\n\n if (!imgWidth || !imgHeight) {\n logStr(\"Parameter imageSize expects value with format WIDTHxHEIGHT, got \" + params.imageSize);\n } else {\n _imgWidth = imgWidth;\n _imgHeight = imgHeight;\n }\n }\n $customIcon.setAttribute('style', $customIcon.getAttribute('style') + 'width:' + _imgWidth + 'px; height:' + _imgHeight + 'px');\n }\n\n // Show cancel button?\n modal.setAttribute('data-has-cancel-button', params.showCancelButton);\n if (params.showCancelButton) {\n $cancelBtn.style.display = 'inline-block';\n } else {\n hide($cancelBtn);\n }\n\n // Show confirm button?\n modal.setAttribute('data-has-confirm-button', params.showConfirmButton);\n if (params.showConfirmButton) {\n $confirmBtn.style.display = 'inline-block';\n } else {\n hide($confirmBtn);\n }\n\n // Edit text on cancel and confirm buttons\n if (params.cancelButtonText) {\n $cancelBtn.innerHTML = escapeHtml(params.cancelButtonText);\n }\n if (params.confirmButtonText) {\n $confirmBtn.innerHTML = escapeHtml(params.confirmButtonText);\n }\n\n if (params.confirmButtonColor) {\n // Set confirm button to selected background color\n $confirmBtn.style.backgroundColor = params.confirmButtonColor;\n\n // Set box-shadow to default focused button\n setFocusStyle($confirmBtn, params.confirmButtonColor);\n }\n\n // Allow outside click?\n modal.setAttribute('data-allow-ouside-click', params.allowOutsideClick);\n\n // Done-function\n var hasDoneFunction = (params.doneFunction) ? true : false;\n modal.setAttribute('data-has-done-function', hasDoneFunction);\n\n if (!params.animation) { // No animation\n modal.setAttribute('data-animation', 'none');\n } else if (typeof(params.animation) === \"string\") {\n modal.setAttribute('data-animation', params.animation); // Custom animation\n } else {\n modal.setAttribute('data-animation', 'pop');\n }\n\n // Close timer\n modal.setAttribute('data-timer', params.timer);\n }", "function promptModal(modalDOM, titleDOM, bodyDOM, cancelText, confirmText, confirmFn) {\n dom(modalDOM, '.modal-header').innerHTML = titleDOM.outerHTML\n dom(modalDOM, '.modal-body').innerHTML = bodyDOM.outerHTML\n if (cancelText != null) dom(modalDOM, '.modal-footer [data-my-btn-type=\"cancel\"]').innerText = cancelText\n dom(modalDOM, '[data-my-btn-type=\"confirm\"]').innerText = confirmText\n dom(modalDOM, '[data-my-btn-type=\"confirm\"]').onclick = confirmFn\n}", "toggleConfirmChangesButton() {\n\t\tif ( ! this.props.isEditing ) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst settingsMapping = {\n\t\t\toptimizeID: 'optimizeID',\n\t\t\tampExperimentJSON: 'ampExperimentJSON',\n\t\t};\n\n\t\ttoggleConfirmModuleSettings( 'optimize', settingsMapping, this.state );\n\t}", "function ModConfirmSave() {\n console.log(\" --- ModConfirmSave --- \");\n console.log(\"mod_dict: \", mod_dict);\n\n let close_modal = false;\n\n if (mod_dict.mode === \"validate_subj_composition\"){\n // --- upload changes\n const upload_dict = {\n student_pk: mod_dict.student_pk,\n subj_dispensation: mod_dict.new_subj_dispensation\n };\n UploadChanges(upload_dict, urls.url_validate_subj_composition);\n close_modal = true;\n\n } else if (mod_dict.mode === \"delete_cluster\"){\n MCL_delete_cluster(mod_MCL_dict.sel_cluster_dict);\n close_modal = true;\n\n // - enable save btn\n if (el_MCL_btn_save){el_MCL_btn_save.disabled = false};\n\n } else if ([\"prelim_ex1\", \"prelim_ex4\"].includes(mod_dict.mode)){\n const el_modconfirm_link = document.getElementById(\"id_modconfirm_link\");\n if (el_modconfirm_link) {\n\n const href_str = (mod_dict.mode === \"prelim_ex4\") ? urls.url_download_ex4 : urls.url_download_ex1;\n el_modconfirm_link.setAttribute(\"href\", href_str);\n el_modconfirm_link.click();\n\n // show loader\n el_confirm_loader.classList.remove(cls_visible_hide)\n // close modal after 5 seconds\n //setTimeout(function (){ $(\"#id_mod_confirm\").modal(\"hide\") }, 5000);\n close_modal = true;\n };\n } else if ([\"has_exemption\", \"has_sr\", \"has_reex\", \"has_reex03\"].includes(mod_dict.mode)){\n\n // --- change icon, before uploading\n // don't, because of validation on server side\n // add_or_remove_class(mod_dict.el_input, \"tickmark_1_2\", new_value, \"tickmark_0_0\");\n// --- upload changes\n const upload_dict = {\n student_pk: mod_dict.stud_pk,\n studsubj_pk: mod_dict.studsubj_pk\n };\n upload_dict[mod_dict.fldName] = mod_dict.new_value;\n UploadChanges(upload_dict, urls.url_studsubj_single_update);\n\n close_modal = true;\n\n } else if ([\"is_extra_nocount\", \"is_extra_counts\", \"is_thumbrule\"].includes(mod_dict.mode)){\n\n // --- change icon, before uploading\n // when validation on server side fails, the old value is reset by RefreshDataRowItem PR2022-05-27\n // updated_studsubj_rows must contain ie err_fields: ['has_reex']\n add_or_remove_class(mod_dict.el_input, \"tickmark_1_2\", mod_dict.new_value, \"tickmark_0_0\");\n\n// --- upload changes\n const upload_dict = {\n student_pk: mod_dict.data_dict.stud_id,\n studsubj_pk: mod_dict.data_dict.studsubj_id\n };\n upload_dict[mod_dict.mode] = mod_dict.new_value;\n UploadChanges(upload_dict, urls.url_studsubj_single_update);\n close_modal = true;\n };\n\n// --- hide modal\n if(close_modal) {\n $(\"#id_mod_confirm\").modal(\"hide\");\n }\n } // ModConfirmSave", "function ClaimGuideConfirmInitiate() {\n /* HTMl code for the Claim Guide Confirmation module */\n $.showCustomModal('Initiate Claim Guide?', \"The claim guide system has noticed that you are new or relatively new to our wiki! While this is completely optional, would you like to enable our claim guide? With our claim guide, we aim to provide a method to guide new users through creating their first claim. If you follow along the guide, your claim should have everything that's necessary in order to ensure that your claim gets approved as quickly as possible. That way, new users will be less intimidated by our claim guidelines and they can get right onto roleplay.<br /><br /> \\\n <i>This script is written by <a href='/wiki/User:Kevin_Mo' title='User:Kevin Mo'>Kevin Mo</a>. To report any bugs or issues with the claim guide, please message <a href='/wiki/User_talk:Kevin_Mo' title='User:Kevin Mo'>Kevin</a>.</i><br /> \\\n <div style='float:right; font-size:65%;'>Ver. 1.0.0 (2016-4-10)</div>\", {\n id: 'claim-guide-initiate-confirmation',\n width: 300,\n buttons: [{\n message: 'Yes',\n defaultButton: true,\n handler: function() {\n /* When the \"Yes\" button is pressed, the Claim Guide Module is closed and function executes. */\n $('#claim-guide-initiate-confirmation').closeModal();\n ClaimGuideInitiate();\n }\n }, {\n id: 'startButton',\n message: 'No',\n handler: function () {\n /* When the \"No\" button is pressed, the Claim Guide Module is closed and function is terminated. */\n $('#claim-guide-initiate-confirmation').closeModal();\n return;\n }\n }]\n });\n }", "function checkInboundChangeDescription() { \n js_modal('modal_container_2', 'app/changeInboundDescriptionText'); \n}", "setUpModalConfig() {\n\t\tthis.modal.default.disclaimer = this.modal.default.target - this.modal.default.reached;\n\t\tthis.modal.progressBar = this.modal.container.find('.progressbar-progress-ev');\n\t\tthis.modal.el.reached = this.modal.container.find('.progressbar-val-ev');\n\t\tthis.modal.el.target = this.modal.container.find('.target-val-ev');\n\t\tthis.modal.el.disclaimer = this.modal.container.find('.disclaimer-val-ev');\n\t}", "function updateConfirmation () {\n team_form.setConfirmationMessage(confirmation)\n }", "toggleConfirmChangesButton() {\n\t\tif ( ! this.props.isEditing ) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet settingsMapping = {\n\t\t\tselectedContainer: 'containerID',\n\t\t\tselectedContainerAMP: 'ampContainerID',\n\t\t\tselectedAccount: 'accountID',\n\t\t\tuseSnippet: 'useSnippet',\n\t\t};\n\n\t\t// Disable the confirmation button if necessary conditions are not met.\n\t\tif ( ! this.canSaveSettings() ) {\n\t\t\tsettingsMapping = {};\n\t\t}\n\n\t\ttoggleConfirmModuleSettings( 'tagmanager', settingsMapping, this.state );\n\t}", "function popUpModalPrompt(header, message, instruction, buttonText) {\r\n\tif (typeof header==\"string\") $('#message').children('h2').first().text(header);\r\n\tif (typeof message==\"string\") $('#message').children('p').first().text(message);\r\n\tif (typeof instruction==\"string\") $('#message').children('p').last().text(instruction);\r\n\tif (typeof buttonText==\"string\") $('#message').children('button').first().text(buttonText);\r\n\t$('#prompt').overlay().load();\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Highlight leave game button
function highlightLeaveButton() { $('.game button[name="leave_game"]').effect('highlight', {}, 1000); window.setTimeout(highlightLeaveButton, 3000); }
[ "function onLeaveGameBtClick(event)\n{\n\t// Join the lobby\n\tjoinLobbyRoom();\n\n\t// Remove Game Popup\n\tremoveGamePopUp();\n}", "function onLeaveGameBtClick(event)\n{\n\t// Join the lobby\n\tjoinLobbyRoom();\n}", "function addLeaveButton() {\n\n // use template for team button\n self.ccm.helper.setContent( team_elem.querySelector( '.button' ), self.ccm.helper.html( my.html.leave, {\n\n icon: my.icon.leave,\n caption: my.text.leave,\n click: function () {\n\n // show loading icon\n loading( true );\n\n // remove user from member list\n delete team.members[ user.id ];\n\n // unlimited number of teams and leaved team is now empty? => remove leaved team\n if ( !my.max_teams && isEmptyTeam( team ) ) dataset.teams.splice( i , 1 );\n\n // update team building dataset\n my.data.store.set( dataset, function () {\n\n // should events be logged? => log the leaving of the team\n if ( self.logger ) self.logger.log( 'leave', { team: team.key } );\n\n // (re)render own content\n self.start();\n\n } );\n\n }\n\n } ) );\n\n }", "function endGame() {\n gameStarted = false;\n background('Black');\n fill(255)\n text(\"GAME OVER\", width / 2, height /2);\n cursor();\n \n tryAgainButton = createButton(\"Try Again?\");\n tryAgainButton.position(width / 2 - ((width / 4) / 2), height * 0.7);\n tryAgainButton.size(width /4, height / 8);\n tryAgainButton.mousePressed(tryAgain);\n \n}", "function LeaveButtonClick() {\n\n\t// If the wait option was clicked, we skip 2 minutes\n\tif (LeaveIcon == \"Wait\")\n\t\tif ((MouseX >= 1125) && (MouseX <= 1200) && (MouseY >= 600) && (MouseY <= 675))\n\t\t\tCurrentTime = CurrentTime + 120000;\n\n\t// If the leave option was clicked, we return to the previous screen\n\tif ((LeaveIcon == \"Leave\") && (LeaveScreen != \"\"))\n\t\tif ((MouseX >= 1125) && (MouseX <= 1200) && (MouseY >= 600) && (MouseY <= 675))\n\t\t\tSetScene(LeaveChapter, LeaveScreen);\n\n}", "deactivate() {\r\n this.setTextColor(INACTIVE_BUTTON_TEXT_COLOR);\r\n }", "gameOver() {\n this.disableButton(ROLL_DICE_BUTTON_ID);\n this.disableButton(END_TURN_BUTTON_ID);\n this.isGameOver = true;\n }", "_onLeaveButton() {\n this.dispatchEvent(new Event(this._leaveEvent));\n }", "function loseGame() {\n wordBlank.textContent = \"GAME OVER\";\n loseCounter++\n startButton.disabled = false;\n setLosses()\n }", "function tileOnLeave(id){\n currentTileId = null;\n if(currentGameState == \"Placing Ships\"){\n dehighlightShips(id);\n }\n else if(currentGameState == \"Playing\"){\n //DO NOTHING\n }\n else if(currentGameState == \"Waiting\"){\n //DO NOTHING\n }\n else if(currentGameState == \"Finished\"){\n //DO NOTHING\n }\n}", "greyOut() {\r\n this.domElement.classList.add(BUTTON_INACTIVE_CLASS);\r\n this.domElement.classList.remove(BUTTON_ACTIVE_CLASS);\r\n }", "function tileEnemyOnLeave(id){\n currentTileIdEnemy = null;\n if(currentGameState == \"Placing Ships\"){\n //DO NOTHING\n }\n else if(currentGameState == \"Playing\"){\n if(myTurn){\n dehighlightLocation(id);\n }\n }\n else if(currentGameState == \"Waiting\"){\n //DO NOTHING\n }\n else if(currentGameState == \"Finished\"){\n //DO NOTHING\n }\n}", "function OnMouseExit()\n{\n\tbackToMain.color = Color.white;\n\tselectSprite.enabled = false;\n\tselected = false;\n}", "gameOver(){\r\n const overlay = document.querySelector('#overlay');\r\n const overlayHeading = document.querySelector('#overlay .title');\r\n const overlayButton = document.querySelector('#overlay #btn__reset');\r\n overlay.className = \"lose\";\r\n overlay.style.display = \"\";\r\n overlayHeading.textContent = \"Better luck next time\";\r\n overlayButton.textContent = \"Try Again\";\r\n overlayButton.className = \"button_lose\";\r\n }", "function run_MouseLeave(){\n $(this).css(\"background-color\", \"lightblue\");\n }", "function leaveGame() {\n console.log(\"Leaving game...\");\n channelLeaveGame();\n }", "gamepadHoverOut() {\n }", "toggleLeaveButton() {\n if (this.isGameStart) {\n this.leaveRoomBtn.disable();\n this.leaveRoomBtn.setVisibility(false);\n }\n else {\n this.leaveRoomBtn.enable();\n this.leaveRoomBtn.setVisibility(true);\n }\n }", "function buttonLeaveHandler() {\n log('Leaving room...');\n activeRoom.disconnect();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A statistic can contain a label to help provide context for the presented value.
function StatisticLabel(props) { var children = props.children, className = props.className, label = props.label; var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()('label', className); var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__["b" /* getUnhandledProps */])(StatisticLabel, props); var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__["c" /* getElementType */])(StatisticLabel, props); return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement( ElementType, __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }), __WEBPACK_IMPORTED_MODULE_1_lodash_isNil___default()(children) ? label : children ); }
[ "function formatDataLabel(attr, val) {\n switch (attr) {\n case \"population\":\n return (val / 1000).toLocaleString(\"en-US\") + \"K\";\n case \"illiteracy\":\n default:\n return val + \"%\";\n }\n}", "function StatisticLabel(props) {\n var children = props.children,\n className = props.className,\n label = props.label;\n\n var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()('label', className);\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5__lib__[\"b\" /* getUnhandledProps */])(StatisticLabel, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5__lib__[\"c\" /* getElementType */])(StatisticLabel, props);\n\n return __WEBPACK_IMPORTED_MODULE_4_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_1_lodash_isNil___default()(children) ? label : children\n );\n}", "function StatisticLabel(props) {\n var children = props.children,\n className = props.className,\n label = props.label;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()('label', className);\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"b\" /* getUnhandledProps */])(StatisticLabel, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* getElementType */])(StatisticLabel, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? label : children\n );\n}", "function StatisticLabel(props) {\n var children = props.children,\n className = props.className,\n label = props.label;\n\n var classes = (0, _classnames2.default)('label', className);\n var rest = (0, _lib.getUnhandledProps)(StatisticLabel, props);\n var ElementType = (0, _lib.getElementType)(StatisticLabel, props);\n\n return _react2.default.createElement(ElementType, (0, _extends3.default)({}, rest, { className: classes }), _lib.childrenUtils.isNil(children) ? label : children);\n}", "function myLabelFunc(label) {\n return 'y = ' + label;\n }", "function labelFn(label) {\n return 'y = ' + label;\n }", "function label_for_usage(val) {\n switch (val) {\n case 'data': \n return 'data file';\n case 'save': \n return 'save file';\n case 'transcript': \n return 'transcript';\n case 'command': \n return 'command script';\n default:\n return 'file';\n }\n}", "function labelFn (label) {\n return 'y = ' + label;\n }", "function StatisticValue(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n text = props.text;\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"a\" /* useKeyOnly */])(text, 'text'), 'value', className);\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"b\" /* getUnhandledProps */])(StatisticValue, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* getElementType */])(StatisticValue, props);\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(ElementType, __WEBPACK_IMPORTED_MODULE_0__babel_runtime_helpers_extends___default()({}, rest, {\n className: classes\n }), __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children);\n}", "function StatisticValue(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n text = props.text;\n\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"a\" /* useKeyOnly */])(text, 'text'), 'value', className);\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"b\" /* getUnhandledProps */])(StatisticValue, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* getElementType */])(StatisticValue, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function StatisticValue(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n text = props.text;\n\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"C\" /* useKeyOnly */])(text, 'text'), 'value', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"s\" /* getUnhandledProps */])(StatisticValue, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getElementType */])(StatisticValue, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function StatisticValue(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n text = props.text;\n\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"B\" /* useKeyOnly */])(text, 'text'), 'value', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(StatisticValue, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(StatisticValue, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "get label() {\n\n // return the human friendly string\n return this[label];\n }", "get labelText () {\n let t = \"?\";\n let c = this;\n // one of: null, value, multivalue, subclass, lookup, list, range, loop\n if (this.ctype === \"subclass\"){\n t = \"ISA \" + (this.type || \"?\");\n }\n else if (this.ctype === \"list\" || this.ctype === \"value\") {\n t = this.op + \" \" + this.value;\n }\n else if (this.ctype === \"lookup\") {\n t = this.op + \" \" + this.value;\n if (this.extraValue) t = t + \" IN \" + this.extraValue;\n }\n else if (this.ctype === \"multivalue\" || this.ctype === \"range\") {\n t = this.op + \" \" + this.values;\n }\n else if (this.ctype === \"null\") {\n t = this.op;\n }\n\n return (this.ctype !== \"subclass\" ? \"(\"+this.code+\") \" : \"\") + t;\n }", "getLabelFromBMI() {\n let label = ''\n\n if (this.bmi >= 25) {\n label = 'overweight'\n } else if (this.bmi >= 18.5 && this.bmi < 25) {\n label = 'normal'\n } else {\n label = 'underweight'\n }\n\n return label\n }", "function evalBucketStat(pluginObj, stats, stat, warningThreshold, criticalThreshold) {\n var statPath = 'op.samples.' + stat;\n var sample = _.get(stats, statPath);\n if (!_.isEmpty(sample)) {\n\n var mean = _.mean(sample);\n var min = _.min(sample);\n var max = _.max(sample);\n var perfData = {\n label: stat,\n min: min,\n max: max,\n value: mean,\n uom: '',\n };\n pluginObj.addPerfData(perfData);\n\n if (criticalThreshold\n && isAtThreshold(pluginObj, pluginObj.states.CRITICAL, perfData, criticalThreshold)) {\n } else if (warningThreshold\n && isAtThreshold(pluginObj, pluginObj.states.WARNING, perfData, warningThreshold)) { \n }\n\n return perfData;\n \n } else {\n pluginObj.addMessage(pluginObj.states.CRITICAL, statPath + ' not found.'); \n }\n}", "\n ()\n { return this.facet_c.label__s() }", "set _label(value){Helper$2.UpdateInputAttribute(this,\"label\",value)}", "function displayStat(id, type, time, stat, label){\n if(time === \"current\"){\n displayCurrentStats(id, type, stat, label);\n }\n else{\n displayHistoricalStats(id, stat);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes an array of names and groups them into arrays of length size
function group(names, size){ const output = []; while(names.length > 0){ const group = names.splice(0, size); output.push(group); } return output; }
[ "function breakIntoChunks(names) {\n var newArray = [];\n\n for (var i = 0; i < names.length; i += 4) {\n newArray.push(names.slice(i, i + 4))\n }\n return newArray\n}", "function group(names,n){\n var extra = names.length % n;\n var minSize = (names.length - extra)/n;\n\n //console.log(minSize + \" : \" + extra);\n //names = shuffle(names);\n var groups = [];\n for(var i=0; i<n; i++){\n groups[groups.length] = [];\n }\n\n var count = 0;\n\n var cap = 0;\n var pointer = -1;\n\n for(i=0;i<names.length;i++){\n if(cap <= 0){\n pointer++;\n var cap = minSize;\n if(extra > 0){\n cap++;\n extra--;\n }\n }\n var end = groups[pointer].length;\n groups[pointer][end] = names[i];\n cap--;\n }\n //console.log(\"Split into \" + n);\n return groups;\n}", "function group(arr) {\n let groups = [], i = 0;\n while (i < arr.length) {\n let group = [];\n do {\n group.push(arr[i++]);\n } while (arr[i] === group[0])\n groups.push(group);\n }\n return groups;\n}", "function groupArrayByGivenField(array, name) {\n result = array.reduce(function (r, a) {\n r[a.event[name]] = r[a.event[name]] || [];\n r[a.event[name]].push(a);\n return r;\n }, Object.create(null));\n\n return result;\n}", "function reorganize(array){\n\tvar factorGroups = [];\n\tfor(var i=0;i<array.length;i++){\n\t\t// i: First index.\n\t\t// j: Opposite index.\n\t\tvar j = array.length - 1 - i;\n\t\tif(i>j) break;\n\t\tfactorGroups.push([array[i],array[j]]);\n\t}\n\treturn factorGroups;\n}", "function createGroups(arr, numGroups) {\n\tconst perGroup = Math.ceil(arr.length / numGroups);\n\n\treturn new Array(numGroups)\n\t\t.fill('')\n\t\t.map((_, i) => arr.slice(i * perGroup, (i + 1) * perGroup));\n}", "function group_array(a, size) {\n var out = [];\n\n for (var i = 0; i < a.length; i += size) {\n out.push(a.slice(i, i + size));\n }\n\n return out;\n}", "function sortGroups(numGroups) {\n var tempArrayOfNames = [];\n for (var i = 0; i < arrayOfNames.length; i++) {\n tempArrayOfNames[i] = arrayOfNames[i]\n }\n shuffle(tempArrayOfNames);\n groupArray = [];\n for (var i = 0; i < numGroups; i++) {\n groupArray[i] = [];\n }\n\n //while loop checks to be sure after each pass through placing names, there are more names to be placed into groups\n while (tempArrayOfNames.length > 0) {\n for (var i = 0; i < numGroups; i++) {\n //checks to be sure mid while loop that there are still names to be placed\n if (tempArrayOfNames.length > 0) {\n groupArray[i].push(tempArrayOfNames.shift());\n }\n }\n }\n return groupArray;\n }", "function detected_names_reduction(detected_names) {\n const new_array = [];\n detected_names.forEach((name) => {\n if (!new_array.includes(name)) {\n new_array.push(name);\n }\n });\n return new_array;\n}", "function makePairs(names) {\n\tlet result = [];\n\tlet pairs = [];\n\n\twhile(names.length > 1) {\n\t\tpairs.push(names.pop());\n\t\tpairs.push(names.pop());\n\t\tresult.push(pairs);\n\t\tpairs = [];\n\t}\n\n\tif (names.length) {\n\t\tresult.push([names.pop()])\n\t}\n\n\treturn result;\n}", "function groupMaker(arr, size) {\n console.log(arr);\n if (arr.length === size + 1) {\n return [arr];\n }\n let groups = [];\n // // set up group buckets based on number of students\n for (let i = 0; i < Math.ceil(arr.length / size); i++) {\n groups.push([]);\n }\n // console.log(\"groups\")\n // console.log(groups);\n // let currentGroup = [];\n // let numGroups = Math.ceil(arr.length/size);\n // console.log('total groups:', numGroups)\n arr.forEach((student, idx) => {\n console.log((idx + 1) % groups.length);\n groups[(idx + 1) % groups.length].push(student);\n // currentGroup.push(student);\n // console.log(student)\n // if(currentGroup.length===size){\n // groups.push(currentGroup);\n // currentGroup = [];\n // }\n });\n // //hack for uneven final group\n // if(currentGroup.length > 0) {\n // groups.push(currentGroup);\n // }\n return groups;\n}", "function groupThePeople(groupSizes) {\n let groups = {};\n let result = [];\n for (let i = 0; i < groupSizes.length; i++) {\n let tar = groupSizes[i];\n if (tar === 1) {\n result.push([i]);\n continue;\n }\n if (!groups[tar]) {\n groups[tar] = [];\n groups[tar].push(i);\n } else {\n groups[tar].push(i);\n if (groups[tar].length === tar) {\n result.push(groups[tar]);\n groups[tar] = [];\n }\n }\n }\n return result;\n}", "function groupBy(array, funkShun) {\n var groups = {}\n array.forEach(function(element) {\n var resultOfFunkShun = funkShun(element);\n if (!(resultOfFunkShun in groups)) {\n groups[resultOfFunkShun] = [];\n };\n groups[resultOfFunkShun].push(element)\n });\n return groups;\n}", "function groupPeople(arr) {\n 'use strict';\n\n return arr.reduce(function(result, item) {\n if (!result[item.firstName[0]]) {\n result[item.firstName[0]] = [];\n }\n result[item.firstName[0]].push(item);\n return result;\n }, {});\n}", "function randomGroups(arr) {\n const arrays = [];\n\n for(let i = 0; i < arr.length; i += 2) {\n arrays.push(arr.slice(i, i+2));\n }\n}", "function generateGroups(array,grpNum){\n\tvar i = 0;\n\tvar j = 0;\n\tvar groupArray = [];\n\tvar groups = {};\n\n // we start at 0 to split group, and you want to go up to the group number element, and defining the window of your group size\n // i defines the starting index of the slice, you want to increment i by the grpNum\n // j is the loop number, the ending index is always equal to grpNum+grpNum*j \n\tfor (i = 0;i<array.length;i+=grpNum){\n\t\t\n\t // this slices the group array for whatever grpNum you are trying to size\t\n\t\tgroupArray.push(array.slice(i,grpNum+grpNum*j));\n\t\tj++;\n\t\t};\n\t\n // if the last array in the group array contains 1 person it will be pushed to the previous array so no one works alone. \t\n\tif (groupArray[groupArray.length-1].length == 1){\n\t\tgroupArray[groupArray.length-2].push(groupArray[groupArray.length-1][0]);\n\t\tgroupArray.pop();\n\t}\n\n\treturn groupArray;\n}", "function group(array, size) {\n let copy = [...array];\n\n let numberOfSubarrays = Math.ceil(array.length / size)\n\n let result = Array.from({ length: numberOfSubarrays }).map(el => []);\n\n while (copy.length > 0) {\n result.forEach(subarray => {\n if (copy.length > 0)subarray.push(copy.shift());\n });\n }\n\n return result;\n\n}", "function create_groups() {\n var array = [];\n for (var i = 0; i < trainees.length; i++) {\n array.push(i);\n }\n array = shuffle(array);\n var groups = [];\n for (var i = 0; i < num_groups; i++) {\n var group = [];\n var num_in_group = parseInt(array.length/(num_groups-i));\n for (var j = 0; j < num_in_group; j++) {\n group.push(array.pop());\n }\n groups.push(group);\n }\n return groups;\n}", "function splitLetter() {\n for (var h = 0; h < nameLength; h++) {\n splitArray.push(chosenGame[h]);\n }\n return splitArray;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to add a :+1: to the PR. May be on code diff, so trigger the comment tab first, then post the comment.
function plusOne() { // Could be on one of the non-comment tabs, so get on to the first tab first $('.js-pull-request-tab')[0].click(); // Populate the comment $('textarea').val(':+1:'); // Submit the form $('.js-new-comment-form').submit(); }
[ "_onAddCommentClicked() {\n const comment = this.model.createGeneralComment(\n undefined,\n RB.UserSession.instance.get('commentsOpenAnIssue'));\n\n this._generalCommentsCollection.add(comment);\n this._bodyBottomView.$el.show();\n this._commentViews[this._commentViews.length - 1]\n .inlineEditorView.startEdit();\n\n return false;\n }", "function askToTestPr(account, pull_request) {\n superagent.post(pull_request._links.comments)\n .set('Authorization', 'token ' + account.accessToken)\n .send({\n body: 'Should this PR be tested?'\n })\n .end(function (res) {\n if (res.status !== 201) {\n console.warn('Unexpected response to comment creation.', res.status, res.text)\n }\n })\n}", "async afterStatus({ data }) {\n if (data.state !== 'failure') {\n return;\n }\n\n const { user } = this.context.payload.pull_request;\n\n const comment = this.context.issue({\n body: `\nUh oh!\n\nLooks like this PR has some conflicts with the base branch, @${ user.login }.\n\nPlease bring your branch up to date as soon as you can.\n `,\n });\n\n await this.context.github.issues.createComment(comment);\n }", "function addBrewNote() {\n dataService.post(commentsUrl, vm.comment)\n .success(function (data) {\n vm.detail.public_comments.unshift(data);\n\n // Close the brew note form\n $(\".brew-form\").toggleClass(\"hidden\");\n });\n\n // Reset the brew note form data\n vm.comment = {};\n }", "function addcomment() {\r\n}", "function add_note(part)\n{\n\t//if(DEBUG){post('add_note', part.num, '\\n');}\n\tpart.obj.addnote.message('bang');\n}", "function addComment (name1, body1, date1, commentArray) {\r\n\r\n let newComment = {\r\n name: name1,\r\n body: body1,\r\n date: date1,\r\n }\r\n commentArray.unshift(newComment);\r\n}", "function addRemediationItemComment(id, btnName, btnText, title) {\n var params = {\n remediationItemId : id\n };\n \n // prevent the okay button from being clicked multiple times.\n var clicked = false;\n\n var windowUrl = CONTEXT_PATH + \"/workitem/remediationItemCommentPanel.jsf?\" + Ext.Object.toQueryString(params);\n\n SailPoint.confirm( {\n url : windowUrl,\n options : {\n method : 'get'\n }\n }, {\n windowParameters : {\n className : 'sailpoint',\n title : title\n },\n okLabel : btnText,\n cancelLabel : \"#{msgs.button_cancel}\",\n ok : function(win) {\n // Make sure the user can't double click the ok button.\n if (!clicked) {\n clicked = true;\n Ext.getDom(btnName).click();\n return false;\n }\n },\n cancel : function(win) {\n SailPoint.NavigationHistory.back();\n Ext.getDom('editForm:id').value = workItemId;\n return true;\n },\n callback : function() {\n Ext.getDom('editForm:id').value = id;\n },\n buttonAlign : 'center'\n } );\n}", "async addLabelToPr(pr, label) {\n this.logger.verbose.info(`Creating \"${label}\" label to PR ${pr}`);\n const result = await this.github.issues.addLabels({\n issue_number: pr,\n owner: this.options.owner,\n repo: this.options.repo,\n labels: [label],\n });\n this.logger.veryVerbose.info(\"Got response from addLabels\\n\", result);\n this.logger.verbose.info(\"Added labels on Pull Request.\");\n return result;\n }", "function postVoteStarted(pullreq) {\n console.log('TRACE: postVoteStarted');\n getVoteStartedComment(pullreq, function(err, comment) {\n if(err) return console.error('error in postVoteStarted:', err);\n if(comment) {\n // we already posted the comment\n started[pullreq.number] = true;\n return;\n }\n\n gh.issues.createComment({\n user: config.user,\n repo: config.repo,\n number: pullreq.number,\n body: voteStartedComment + pullreq.head.sha\n\n }, function(err, res) {\n if(err) return console.error('error in postVoteStarted:', err);\n started[pullreq.number] = true;\n console.log('Posted a \"vote started\" comment for pull request #' + pullreq.number);\n\n // Tweet vote started\n Twitter.postTweet('Vote started for pull request #' + pullreq.number + ': https://github.com/canterbot/canterbot/pull/' + pullreq.number);\n\n // determine whether I like this pull request or not\n var score = sentiment(pullreq.title + ' ' + pullreq.body).score;\n if (score > 1) {\n // I like this pull request, let's vote for it!\n gh.issues.createComment({\n user: config.user,\n repo: config.repo,\n number: pullreq.number,\n body: ':+1:'\n });\n } else if (score < -1) {\n // Ugh, this pull request sucks, boooo!\n gh.issues.createComment({\n user: config.user,\n repo: config.repo,\n number: pullreq.number,\n body: ':-1:'\n });\n } // otherwise it's meh, so I don't care\n });\n });\n }", "async addCommentAndLabel({ auto, prOrIssue, isIssue = false, isPrerelease = false, releases, }) {\n // leave a comment with the new version\n const urls = releases.map((release) => this.options.message === defaultOptions.message\n ? `[\\`${release.data.name || release.data.tag_name}\\`](${release.data.html_url})`\n : release.data.name);\n const message = this.createReleasedComment(isIssue, urls.join(\", \"));\n await auto.comment({ message, pr: prOrIssue, context: \"released\" });\n // add a `released` label to a PR\n const labels = await auto.git.getLabels(prOrIssue);\n if (isPrerelease) {\n if (!labels.includes(this.options.prereleaseLabel)) {\n await auto.git.addLabelToPr(prOrIssue, this.options.prereleaseLabel);\n }\n }\n else if (!labels.includes(this.options.label)) {\n await auto.git.addLabelToPr(prOrIssue, this.options.label);\n if (labels.includes(this.options.prereleaseLabel)) {\n await auto.git.removeLabel(prOrIssue, this.options.prereleaseLabel);\n }\n }\n }", "onCommentOnPullRequest(id, options = {}) {\n const rule = this.onEvent(id, options);\n rule.addEventPattern({ detailType: ['CodeCommit Comment on Pull Request'] });\n return rule;\n }", "function addNewComment() {\n vm.isAddComment = true;\n }", "function commentOnIssue(client, name, number, message) {\n var url = '/repos/' + name + '/issues/' + number + '/comments';\n var req = client.postAsync(url, { body: message });\n return req;\n}", "addCustomComment() {\n const comment = createDupeComment()\n const dupeCheck = this.handleDupeCheck(comment)\n\n // if -1, comment is unique and is added to state\n if(dupeCheck === -1) {\n this.setState({\n comments: [...this.state.comments, comment]\n })\n }\n }", "async afterStatus({ data }) {\n if (data.state !== 'failure') {\n return;\n }\n\n const branch = this.branchIssue || 'task/ABC-123';\n const { user } = this.context.payload.pull_request;\n\n const comment = this.context.issue({\n body: `\nHi there @${ user.login }! It looks like the title of this PR doesn't quite match our guidelines. \n\nMake sure your PR titles follow the format of \\`<Jira Issue> <Description>\\`\n\nFor example: \\`${ branch } Adds contact form to the homepage\\`\n `,\n });\n\n await this.context.github.issues.createComment(comment);\n }", "function processPullRequest(pullreq) {\n console.log('TRACE: processPullRequest');\n var voteResults = tallyVotes(pullreq);\n // only make a decision if we have the minimum amount of votes\n console.log('only make a decision if we have the minimum amount of votes');\n console.log('voteResults.total = ' + voteResults.total);\n console.log('MIN_VOTES = ' + MIN_VOTES);\n if (voteResults.total < MIN_VOTES) return;\n\n // vote passes if yeas > nays\n var passes = decideVoteResult(voteResults.positive, voteResults.negative);\n\n gh.issues.createComment({\n user: config.user,\n repo: config.repo,\n number: pullreq.number,\n body: voteEndComment(passes, voteResults.positive, voteResults.negative, voteResults.nonStarGazers)\n }, noop);\n\n if(passes) {\n mergePullRequest(pullreq, noop);\n } else {\n closePullRequest(pullreq, noop);\n }\n }", "function addPreviousComments(newpath) {\n\n try {\n fetch(\"https://camagru-ik.cf/api/post/get_comments.php\", {\n method: \"POST\",\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n },\n body: JSON.stringify({ filename: newpath }),\n })\n .then((res) => res.text())\n .then((data) => {\n if (data == '{\"message\":\"No Comments Found\"}') {\n //console.log('Comments Not Found');\n\n } else {\n addCommentBlocks(data);\n }\n });\n } catch (error) {\n //console.log(error);\n }\n\n }", "async _addToGitHub(label) {\n let params = Util.commonParams();\n params.issue_number = this._prNum;\n params.labels = [];\n params.labels.push(label.name);\n\n await GH.addLabels(params);\n\n label.markAsAdded();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the first ARIA label defined by the collective.
function getCollectiveAriaLabel(collective) { var labels = collective.elements.map(function (element) { return element.getAttribute('aria-label'); }); // Would prefer to use Array.prototype.find here, but IE 11 doesn't have it. var nonNullLabels = labels.filter(function (label) { return label != null; }); return nonNullLabels[0]; }
[ "function getCollectiveAriaLabel(collective) {\n let labels = collective.elements.map(element => element.getAttribute('aria-label'));\n // Would prefer to use Array.prototype.find here, but IE 11 doesn't have it.\n let nonNullLabels = labels.filter(label => label != null);\n return nonNullLabels[0];\n}", "function grabTextFromAriaLabelledbyReferences(element) {\n var ids = $.trim($(element).attr(\"aria-labelledby\"));//get the ids to search for\n var idsArray = ids.split(\" \"); //split the list on the spaces, store into array. So it can be parsed through one at a time.\n var accumulatedText = \"\";//this variable is going to store what is found. And will be returned\n var referencedId, referencedElement, referencedElementText;\n //Traverse through the array\n for (var x = 0; x < idsArray.length; x++) {\n //Can the aria list id be found somewhere on the page?\n if (idsArray[x] !== \"\") {\n referencedElement = document.getElementById(idsArray[x]);\n referencedElementText = \"\";\n if ($(referencedElement).attr(\"aria-label\")) { //Yes, this id was found and it has an aria-label\n referencedElementText += andiUtility.formatForHtml($(referencedElement).attr(\"aria-label\"));\n } else if ($(referencedElement).html() !== undefined) { //Yes, this id was found and the reference contains something\n referencedElementText += andiUtility.formatForHtml(andiUtility.getVisibleInnerText(referencedElement, true));\n }\n //Add to accumulatedText\n accumulatedText += referencedElementText + \" \";\n }\n }\n return $.trim(accumulatedText);\n }", "get label() {\n\n // return the human friendly string\n return this[label];\n }", "_getPanelAriaLabelledby() {\n if (this.ariaLabel) {\n return null;\n }\n const labelId = this._getLabelId();\n return this.ariaLabelledby ? labelId + ' ' + this.ariaLabelledby : labelId;\n }", "function getA11yLabel(props, labelId) {\n const ariaLabelledBy = props.ariaLabelledBy || props['aria-labelledby'];\n return ariaLabelledBy ? { 'aria-labelledby': `${labelId} ${ariaLabelledBy}` } :\n { 'aria-label': props.ariaLabel || props['aria-label'] };\n}", "get computedAriaLabelledBy() {\n const ariaValues = [];\n\n if (this.ariaLabelledBy) {\n ariaValues.push(this.ariaLabelledBy);\n }\n\n return normalizeAriaAttribute(ariaValues);\n }", "function getAccessibleNameAria (element) {\n var name;\n\n name = getAttributeIdRefsValue(element, 'aria-labelledby');\n if (name.length) return name;\n\n name = getAttributeValue(element, 'aria-label');\n if (name.length) return name;\n\n return '';\n }", "function getScreenReaderText() {\n return element[0].getAttribute('aria-label');\n }", "_getPanelAriaLabelledby() {\n var _a;\n if (this.ariaLabel) {\n return null;\n }\n const labelId = (_a = this._parentFormField) === null || _a === void 0 ? void 0 : _a.getLabelId();\n const labelExpression = (labelId ? labelId + ' ' : '');\n return this.ariaLabelledby ? labelExpression + this.ariaLabelledby : labelId;\n }", "function grab_label(element){\n\t\tif(page_using_label && !$(element).is(\"label\")){\n\t\t\t//Page is using labels and this element is not a label\n\t\t\tvar labelNestedText = grab_labelNested(element);\n\t\t\tvar labelForText = grab_labelFor(element);\n\t\t\tvar labelText = false;\n\n\t\t\tif(labelNestedText!==false)\n\t\t\t\tlabelText = labelNestedText;\n\t\t\telse if(labelForText!==false)\n\t\t\t\tlabelText = labelForText;\n\t\t\t\t\n\t\t\tif(labelText!==false){\n\t\t\t\tif(labelText==\"\"){\n\t\t\t\t\tlabelText = addToEmptyComponentList(\"label\");\n\t\t\t\t}\n\t\t\t\telse if(andi_data.ignoreLabel!=\"true\"){\n\t\t\t\t\tnamerFound = true;\n\t\t\t\t\tlabelText = laser.createLaserTarget(\"label\",andiElementIndex,formatForHtml(labelText));\n\t\t\t\t}\n\t\t\t\taccessibleComponentsTotal++;\n\t\t\t\treturn labelText;\n\t\t\t}\n\t\t}\n\t\treturn \"\";\n\t}", "function getLabel(name) {\n\tname = name.split(\"___\")[0];\n\treturn $(\"[for='\"+name+\"']\").html();\n}", "_updateAriaLabel() {\n var displayable = this.getTopDisplayable();\n if (displayable && !dvt.Agent.deferAriaCreation())\n displayable.setAriaProperty('label', this.getAriaLabel());\n }", "function fnGetSAPLabel(oListItemContext, sAttributeName) {\n\t\treturn oListItemContext.getProperty(\"/#SEPMRA_C_PD_ProductType/\" + sAttributeName + \"/@sap:label\");\n\t}", "function label(attrs) /* (attrs : attrs) -> string */ {\n return attrs.label;\n}", "getLabel() {\n return this._label;\n }", "_getTriggerAriaLabelledby() {\n if (this.ariaLabel) {\n return null;\n }\n let value = this._getLabelId() + ' ' + this._valueId;\n if (this.ariaLabelledby) {\n value += ' ' + this.ariaLabelledby;\n }\n return value;\n }", "\n ()\n { return this.facet_c.label__s() }", "_getTriggerAriaLabelledby() {\n var _a;\n if (this.ariaLabel) {\n return null;\n }\n const labelId = (_a = this._parentFormField) === null || _a === void 0 ? void 0 : _a.getLabelId();\n let value = (labelId ? labelId + ' ' : '') + this._valueId;\n if (this.ariaLabelledby) {\n value += ' ' + this.ariaLabelledby;\n }\n return value;\n }", "function getAccessibleLabelForUnit(unit) {\n const match = ALL_CSS_UNITS.find(item => item.value === unit);\n return match !== null && match !== void 0 && match.a11yLabel ? match === null || match === void 0 ? void 0 : match.a11yLabel : match === null || match === void 0 ? void 0 : match.value;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in a percent and sets it to a presetIndex
function getPresetIndex(percent) { return Math.round(percent/100 * (scope.presetValues.length - 1)); }
[ "function percentFromPresetIndex(index) {\n return index / (scope.presetValues.length - 1) * 100;\n }", "function usePresetPercent(percent) {\n return Math.round(percent / 100 * (scope.presetValues.length-1)) / (scope.presetValues.length - 1) * 100;\n }", "setPercent(percent) { this._behavior('set percent', percent); }", "function seekToPercent(percent) {\n //Prevent seeking if there is no song loaded\n if (!sa.nodes.sourceNode || !sa.nodes.sourceNode.buffer)\n return;\n\n //Get the song length\n let songLength = getAudioLength();\n //Get the offset (in seconds) based on the percentage\n let offset = app.utils.map(app.utils.clamp(percent, 0.0, 100.0), 0.0, 100.0, 0.0, songLength);\n //After calculating the point in the song to seek to, seek to that time\n seekToTime(offset);\n }", "_setValuePercent() {\n const dif = ((this.value - this.min) / (this.max - this.min)) * 100;\n this.el.style.setProperty('--valuePercent', `${dif}%`);\n }", "fromIndextoPercentage() {\n this.setState(state => ({\n percentage: ((state.currentVerbIdx + 1) / VERBS_ORDERED.length) * 100\n }));\n }", "adjustByPercent() {\n const { x: maxX, y: maxY } = this.max()\n\n this.setPosition({\n x: maxX * this.data.xPercent,\n y: maxY * this.data.yPercent,\n })\n }", "function getColor(index, percent = 0) {\n let color = palette[index % 1530].color;\n let newColor = shadeRGBColor(color, percent);\n return newColor;\n }", "function setMeter(fraction) {\n var percent = fraction * 100;\n if(percent <= 100) {\n meter.setProgress(percent);\n }\n}", "function seekChange() {\n // percent modifyer is just to make sure the gradient breakboint is not visible outside the thumb\n var percent = Number(document.querySelector('.seek input').value)\n document.getElementById('progress').style.background = 'linear-gradient(to right, #41b6e6CC 0%, #41b6e6CC ' + ( percent < 50 ? percent+0.5 : percent-0.5 ) + '%, #d3d3d3 ' + ( percent < 50 ? percent+0.5 : percent-0.5 ) + '%, #d3d3d3 100%)'\n document.getElementById('progress').setAttribute('title',percent+'%')\n}", "function setSongPosition(percent) {\n executeInGoogleMusic(\"setPosition\", { percent: percent });\n }", "function shiftValue(value, percentage) {\n let x = value + value * percentage / 100;\n if (x > 100) {\n x = 100;\n } else if (x <= 0) {\n x = 0\n }\n return x;\n}", "function setPercents() {\n\t\tfor (i = 0; i < skill.length; i++) {\n\t $('#skills ul li' + '#' + skill[i].name).css( {width: skill[i].percent} );\n\t }\n\t}", "function addOffset(n, percentage) {\n if (percentage < 0 || percentage > 100) {return;}\n \n var offset = n * (percentage / 100);\n \n return n + ((Math.random() * (2 * offset)) - offset);\n}", "function setVolume(percentage) {\n activeSong.volume = percentage;\n\n var percentageOfVolume = activeSong.volume / 1;\n var percentageOfVolumeSlider = document.getElementById('volumeMeter').offsetWidth * percentageOfVolume;\n\n document.getElementById('volumeStatus').style.width = Math.round(percentageOfVolumeSlider) + \"px\";\n }", "function changeSpeed(percent) {\n speed = max_speed * percent;\n offset_increment = edge_pixels*(speed/edge_pixels);\n //console.log(offset_increment);\n}", "function addOffset(n, percentage) {\n if (percentage < 0 || percentage > 100) {return;}\n\n var offset = n * (percentage / 100);\n\n return n + ((Math.random() * (2 * offset)) - offset);\n}", "function qodefInitToCounterProgressBar(progressBar, $percentage){\n\t\tvar percentage = parseFloat($percentage),\n\t\t\tpercent = progressBar.find('.qodef-pb-percent');\n\t\t\n\t\tif(percent.length) {\n\t\t\tpercent.each(function() {\n\t\t\t\tvar thisPercent = $(this);\n\t\t\t\tthisPercent.css('opacity', '1');\n\t\t\t\t\n\t\t\t\tthisPercent.countTo({\n\t\t\t\t\tfrom: 0,\n\t\t\t\t\tto: percentage,\n\t\t\t\t\tspeed: 1000,\n\t\t\t\t\trefreshInterval: 50\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t}", "function scroll_to_percent(){\n perc = parseInt(Private.cordx_slider1);\n idx_perc = Math.round(( (Private.frames + Private.padding) - (Private.step * Private.frame_rate * (Private.window_width-1))) * perc / 100);\n idx = idx_perc - idx_perc % (Private.step * Private.frame_rate) + 1; // to scroll always exactly as the selected step\n scroll_to(idx);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to be called when content.size and display.size change. the following need to be done: we decide if we need sliders based on new content.size and current frame.size update sliders' sizes. sliders are supposed to fit into the frame. update max sliders' max values. max values represent on content.size update sliders' thumbsize if there's an expected min thumbsize, ensure we don't set it below min
function onChange() { // decide if we need sliders based on new content size. default is they are hidden // we update both h and v sliders even when only content.width is changed as it's possible that both sliders // will hide/show based on the change in content.width alone hslider.hide = true; vslider.hide = true; if (content.width > display.width) hslider.hide = false; if (content.height > display.height) vslider.hide = false; if ((content.width > display.width - t) && (content.height > display.height)){ hslider.hide = false; } if ((content.height > display.height - t) && (content.width > display.width)){ vslider.hide = false; } // now that we know which slider(v/s) is enabled, update their sizes // we set a rule that sliders will try to fill container.size. e.g. if vslider is hidden, hslider.height = container.height // both h and s sliders to be updated as it's possible that both slides will hide/show based on change in content.width alone //if (!hslider.hide){ hslider.width = w - (vslider.hide? 0 : t); } //if (!vslider.hide){ vslider.height = h - (hslider.hide? 0 : t); } hslider.width = hslider.hide? 0: (w - (vslider.hide? 0 : t)); vslider.height = vslider.hide? 0 : (h - (hslider.hide? 0 : t)); // set slider's min/max. max value is calculated as the value difference between content size and display size. // the excess size of content will be the scroll size of slider. if content size < display size, max < 0 but slider class will // handle this properly and fix the thumbsize and its position to ensure no undesired behavior occurs // since both h and s sliders might have hide/show from this change, update max for both sliders vslider.min = 0; // min = 0, default. hslider.min = 0; // min = 0, default. vslider.max = content.height - display.height + (hslider.hide? 0 : t); hslider.max = content.width - display.width + (vslider.hide? 0 : t); // we want thumbsize to be based on ratio between content.size and frame.size. slider size is expected to fill frame size // but if both sliders (h and v), slider.size = frame.size - slider.t // since both v and h sliders might have changed their sizes, we update both thumbsize vslider.thumbsize = display.height / content.height * (vslider.height - (hslider.hide? 0 : t)); hslider.thumbsize = display.width / content.width * (hslider.width - (vslider.hide? 0 : t)); // let's set min value for thumbsize, 32, because if content.size is too big, thumbsize will be too small to click. if (vslider.thumbsize < 32) vslider.thumbsize = 32; if (hslider.thumbsize < 32) hslider.thumbsize = 32; }
[ "function setSize() {\n $('.video__slider').css({\n 'height': (getSize() * 0.58) - 10\n });\n\n $('.video__slider__list').css({\n 'width': getSize() * slider.length,\n 'background' : 'black'\n });\n\n $('.video__slider__item').css({\n 'width': getSize()\n });\n }", "function setSliderSize(axis) {\n if (axis === \"Y\") { // algorithm for vertical slider\n if (sliderHeightPrimary === \"auto\") { // if slider size is \"auto\", start calculation\n // ratio factor of container and wrapper heights\n var selfWrapperRatioY;\n \n // calculations, considering...\n if (isTextArea === false) { // ... type of object is regular block\n selfWrapperRatioY = self.clientHeight / ((wrapper.offsetHeight + selfPadding.top + selfPadding.bottom) / 100);\n } else { // ... type of object is textarea\n selfWrapperRatioY = self.clientHeight / ((textAreaBlock.scrollHeight + selfPadding.top + selfPadding.bottom) / 100);\n }\n \n // slider size must be rounded, to prevent fractional numbers\n sliderHeight = Math.round(sliderFieldY / 100 * selfWrapperRatioY);\n \n // slider size cant't be less, then minimal size\n // P.S. if container contain to much content, this case save slider from collapse\n if (sliderHeight < sliderSizeMin) {\n sliderHeight = sliderSizeMin;\n }\n }\n \n // collapse slider, if content occupy not all space of container\n if (sliderHeight >= sliderFieldY) {\n sliderHeight = 0;\n }\n \n // finaly, set calculated size\n sliderY.style.height = sliderHeight + \"px\";\n } else if (axis === \"X\") { // algorithm for horizontal slider\n if (sliderWidthPrimary === \"auto\") {\n // ratio factor of container and wrapper widths\n var selfWrapperRatioX;\n \n // calculations, considering...\n if (isTextArea === false) { // ... type of object is regular block\n selfWrapperRatioX = self.clientWidth / ((wrapper.offsetWidth + selfPadding.left + selfPadding.right) / 100);\n } else { // ... type of object is textarea\n selfWrapperRatioX = self.clientWidth / ((textAreaBlock.scrollWidth + selfPadding.left + selfPadding.right) / 100);\n }\n \n // slider size must be rounded, to prevent fractional numbers\n sliderWidth = Math.round(sliderFieldX / 100 * selfWrapperRatioX);\n \n // slider size cant't be less, then minimal size\n // P.S. if container contain to much content, this case save slider from collapse\n if (sliderWidth < sliderSizeMin) {\n sliderWidth = sliderSizeMin;\n }\n }\n \n // collapse slider, if content occupy not all space of container\n if (sliderWidth >= sliderFieldX) {\n sliderWidth = 0;\n }\n \n // finaly, set calculated size\n sliderX.style.width = sliderWidth + \"px\";\n }\n }", "function onSizeChange(){\n\t\t\t\n\t\tplaceSlider();\n\t\t\t\t\n\t}", "function changeSliderSize() {\n\t\t\twrapperA.css({\n\t\t\t\twidth: itemsA.length * (sliderWidth + 2 * sliderMargin) + \"vw\",\n\t\t\t\tmarginLeft: getWrapperMargin() + \"vw\"\n\t\t\t});\n\t\t\t\n\t\t\titemsA.css({\n\t\t\t\twidth: sliderWidth + \"vw\",\n\t\t\t\theight: sliderHeight + \"em\",\n\t\t\t\tmargin: \"0 \" + sliderMargin + \"vw\"\n\t\t\t});\n\t\t}", "onResize() {\n var sizes = document.getElementById('demogl').getBoundingClientRect();\n\n this.sliders.forEach(function(slider) {\n slider.max = sizes[slider.getAttribute('data-size')];\n this.onSliderChange({ target: slider });\n }, this);\n }", "onResize() {\n var sizes = document\n .getElementById('demogl')\n .getBoundingClientRect();\n\n this.sliders.forEach(function(slider) {\n slider.max = sizes[slider.getAttribute('data-size')];\n this.onSliderChange({ target: slider });\n }, this);\n }", "onSliderResized() {\n }", "function onUpdateThumbSize()\n\t{\n\t\tif (ats)\n\t\t{\n\t\t\t// update thumbsize. make sure it's not too small or it will be too small to click\n\t\t\tscrollbar.thumbsize = scrollbar.min / scrollbar.max * h;\n\t\t\tif (scrollbar.thumbsize < ts) scrollbar.thumbsize = ts;\n\t\t}\n\t\telse scrollbar.thumbsize = ts;\n\t}", "function sliderResizeLogic() {\n let newOptions;\n if (onMobile()) {\n newOptions = {\n fixedHeight: 0,\n fixedWidth: 0,\n };\n } else {\n newOptions = {\n fixedHeight: 400,\n fixedWidth: \"40%\",\n };\n }\n //Only re-render if something has changed\n if (newOptions !== slider.options) {\n slider.options = newOptions;\n sliderRefresh(slider);\n }\n}", "function setDimensions() {\n let max_radius = parseInt(radius_slider[\"slider\"].max, 10),\n max_height = parseInt(barHeight_slider[\"slider\"].max, 10),\n cWidth = (max_radius + max_height + 5) * 2;\n\n // The 20 is to verify that cWidth can satify first iteration of while loop\n // need to better handle this\n if (cWidth + 20 <= CANVAS_WIDTH) {\n while (cWidth <= CANVAS_WIDTH) {\n max_height += 5;\n max_radius += 5;\n cWidth = (max_radius + max_height + 5) * 2;\n }\n } else if (cWidth - 20 >= CANVAS_WIDTH) {\n while (cWidth >= CANVAS_WIDTH) {\n max_height -= 5;\n max_radius -= 5;\n\n cWidth = (max_radius + max_height + 5) * 2;\n }\n }\n\n // Update each Input Range\n updateRadiusSlider(max_radius);\n updateBarHeightSlider(max_height);\n updateNumBarSlider(max_radius);\n}", "_changeSliderSize() {\n\t\t\t\tlet width = this.model.get('width'),\n\t\t\t\t\theight = this.model.get('height');\n\n\t\t\t\tthis.$el.css({width, height});\n\t\t\t}", "function updateSliderWidthAndHeight() {\n slider._width = $slider.width();\n slider._height = $slider.height();\n }", "onSliderResized() {\n }", "function updateGallerySize() {\n\t\tif (active) {\n\t\t\t//showMsg('updateGallerySize()');\n\t\t\tvar windowSize = getWindowGeometry();\n\t\t\t// Save the new sizes\n\t\t\twindowWidth = windowSize.width;\n\t\t\twindowHeight = windowSize.height;\n\t\t\t//galleryElement.style.width = windowWidth + pxStr;\n\t\t\t//galleryElement.style.width = windowWidth + pxStr;\n\t\t\t//thumbnailElement.style.width = windowWidth + pxStr;\n\t\t\tgalleryElement.style.height = windowHeight + pxStr;\n\n\t\t\t// Have potensial error but becouse not even time the varitables is accesible....\n\t\t\tif (elements[galleryIndex]) {\n\t\t\t\t// If current element is exist/set/not undefined then scrol to them and update item size\n\t\t\t\tthumbnailVisibleCount = floor((windowWidth - (thumbnailListLeft * 2)) / thumbnailListItemWidht);\n\t\t\t\tscrollThumbnailToView();\n\t\t\t\tupdateItemSize();\n\t\t\t}\n\t\t}\n\t}", "function updateSize() {\n\n sideSize = sizeSlider.value();\n\n while ( pyramids.length ) pyramids.pop();\n\n fillArray();\n\n}", "function onUpdateSliderState()\n\t{\n\t\t// check if sliders are needed since content.size has changed. \n\t\tvar x = true; \n\t\tvar y = true; \n\t\tif (xslider.max > w) x = false; \n\t\tif (yslider.max > h) y = false; \n\t\tif ((xslider.max > w - t) && (yslider.max > h)){ x = false; } \n\t\tif ((yslider.max > h - t) && (xslider.max > w)){ y = false; } \t\t\n\n\t\t// update state only if it change so event handler fires up only if state change\n\t\tif (x != xslider.hide) xslider.hide = x;\n\t\tif (y != yslider.hide) yslider.hide = y;\n\t}", "function setSizes() {\n slideWidth = $sliderViewport.width() / self.settings.items;\n $sliderItems.add($clonedSliderItems).css('width', slideWidth);\n $slider.css('width', slideWidth * (slideCount + self.settings.cloneItems*2 + 1));\n }", "function sizeScrollbar() {\n var remainder = scrollContent.width() - scrollPane.width();\n var proportion = remainder / scrollContent.width();\n var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );\n scrollbar.find( \".ui-slider-handle\" ).css({\n width: handleSize,\n \"margin-left\": -handleSize / 2\n });\n handleHelper.width( \"\" ).width( scrollbar.width() - handleSize );\n }", "function sizeScrollbar() {\n\n\t\t\t\t\tlet remainder = $scrollContent.width() - $scrollPane.width();\n\t\t\t\t\tif (remainder < 0) {\n\t\t\t\t\t\tremainder = 0;\n\t\t\t\t\t}\n\t\t\t\t\tlet proportion = remainder / $scrollContent.width();\n\t\t\t\t\tlet handleSize = $scrollPane.width() - (proportion * $scrollPane.width());\n\t\t\t\t\t$scrollbar.parent().find('.ui-slider-handle').css({\n\t\t\t\t\t\twidth: handleSize,\n\t\t\t\t\t\t'margin-left': -handleSize / 2\n\t\t\t\t\t});\n\t\t\t\t\thandleHelper.width('').width($scrollbar.width() - handleSize);\n\t\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function for setting text in InstructionLabel and then adjusting scroll to make sure text is visible
function setInstructions(instructions) { $("#Instructions").html(instructions); $("#Instructions").adjustScroll(); }
[ "updateLabelText() { }", "function MessagesBtnClick() {\n frmScrollSPA.lblScroll1.text = \"Solutions for your customers, employees, vendors and partners.Configurable, Extensible with Universal Integration.Stunning User Experience.Support for All Technologies and Devices.\";\n}", "function newsFeedBtnClick() {\n frmScrollSPA.lblScroll1.text = \"KonyOne's device detection database and heuristics identifies all browser categories from the most basic through different levels of HTML, CSS and JavaScript support, to all of the various HTML5-capable browsers in smartphones, tablets and the desktop. Depending on the type of browser, the user will be served markup, style and/or script appropriate and acceptable to their device, ensuring a solid experience and optimum UI.\";\n}", "function homeBtnClick() {\n frmScrollSPA.lblScroll1.text = \"KonyOne provides a world-class development environment and mobile middleware for both business & consumer applications. KonyOne incorporates industry - tested scalability and supports every technology and deployment option available today - including truly native apps on all native OSs, thousands of devices including those with HTML5 capable browser, Single Page Applications, Wrappers, Hybrids, and traditional URL-based applications.\";\n}", "function MessagesBtnClick()\n{\n\tfrmScrollSPA.lblScroll1.text = \"Solutions for your customers, employees, vendors and partners.Configurable, Extensible with Universal Integration.Stunning User Experience.Support for All Technologies and Devices.\";\n}", "setLabelText(t){this.labelText=t}", "function newsFeedBtnClick()\n{\n\tfrmScrollSPA.lblScroll1.text = \"KonyOne's device detection database and heuristics identifies all browser categories from the most basic through different levels of HTML, CSS and JavaScript support, to all of the various HTML5-capable browsers in smartphones, tablets and the desktop. Depending on the type of browser, the user will be served markup, style and/or script appropriate and acceptable to their device, ensuring a solid experience and optimum UI.\";\n}", "function xTextRefresh() {\n xText.attr(\n \"transform\",\n \"translate(\" +\n ((width - labelLength) / 2 + labelLength) +\n \", \" +\n (height - margin - textPadBottom) +\n \")\"\n );\n}", "function xTextRefresh() {\n xText.attr(\n \"transform\",\n \"translate(\" +\n ((width - labelWidth) / 2 + labelWidth) +\n \", \" +\n (height - margin - tPadBot) +\n \")\"\n )\n}", "function setLabelPos() {\r\n $(\".codeLabel\").css(\"left\", $(\".codeContainer\").width()/2);\r\n}", "function homeBtnClick()\n{\n\tfrmScrollSPA.lblScroll1.text = \"KonyOne provides a world-class development environment and mobile middleware for both business & consumer applications. KonyOne incorporates industry - tested scalability and supports every technology and deployment option available today - including truly native apps on all native OSs, thousands of devices including those with HTML5 capable browser, Single Page Applications, Wrappers, Hybrids, and traditional URL-based applications.\";\n}", "function scrollText() {\r\n\tthesaurusData.y = -sb.value;\r\n}", "_showInfoLabel(text) {\n\n // Clear any pending timeouts.\n if (this._infoLabelTimeoutA) {\n GLib.source_remove(this._infoLabelTimeoutA);\n this._infoLabelTimeoutA = null;\n }\n if (this._infoLabelTimeoutB) {\n GLib.source_remove(this._infoLabelTimeoutB);\n this._infoLabelTimeoutB = null;\n }\n\n // Show the given text.\n this._builder.get_object('info-label').label = text;\n\n // Re-initialize the info label; this will make it show the next tip after a couple of\n // seconds.\n this._initInfoLabel();\n }", "updateLabelText() {\n\t\tlet vString = FormatUtils.valueToString(this.targetValue, this.#nbDigitsInt, this.#nbDigitsFloat);\n\t\tthis.domLabel.innerHTML = `(${vString} / ${this.#targetMaxString})`;\n\t}", "function updateInstructions() {\n $(\".instructionPane\").html(instructionHTML);\n }", "updateLabel() {\n this.text = this._text;\n }", "function setupInstructions() {\n // Create and style a div to contain instructions\n instructionsDiv = createDiv();\n instructionsDiv.id(\"infotext\");\n instructionsDiv.style(\"width\", infoArea.w * 0.75 + \"px\");\n instructionsDiv.style(\"padding\", 25 + \"px\");\n instructionsDiv.position(infoArea.left, 25);\n // Create a span as a child element to hold text itself\n instructionsText = createSpan(alarmInstructions);\n instructionsText.parent(instructionsDiv);\n instructionsText.style(\"font-family\", \"LemonMilk\");\n instructionsText.style(\"font-size\", 1.5 + \"em\");\n instructionsText.style(\"line-height\", \"175%\");\n}", "function toolbar_item_setlabel(strToolBarID, strToolBarItemID , strLabel, aDoc)\r\n{\r\n\tvar eDiv = aDoc.getElementById(\"tbi_\" + strToolBarItemID);\r\n\tif(eDiv!=null)\r\n\t{\r\n\t\tvar pos = eDiv.childNodes[0].rows[0].childNodes.length-1;\r\n\t\tapp.setElementText(eDiv.childNodes[0].rows[0].childNodes[pos],\" \"+strLabel);\r\n\t}\r\n}", "function xTextRefresh(){\nxText.attr(\"transform\",\n \"translate(\" +\n ((svgWidth - labelArea)/2 +labelArea) + \",\" +\n (svgHeight - margin +textPadBot) + \")\"\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List names of installed Loggers as string
static list() { var i, ix, len, lgr, msg, ref; msg = ""; ref = this._loggers; for (ix = i = 0, len = ref.length; i < len; ix = ++i) { lgr = ref[ix]; if (ix > 0) { msg += ", "; } msg += lgr.modName; } return msg; }
[ "function list () {\n\tprettyLog('log', 'INSTALLED COMPONENTS: ' + installed_components.sort().join(', '));\n}", "function defaultLoggers() {\n return [\n {\n name: /.*/,\n level: 'error',\n target: defaultImplementation(),\n }\n ];\n}", "function getPluginString() {\n var s = \"\";\n var plugins = navigator.plugins;\n for (var i = 0; i < plugins.length; i++) {\n s = s + plugins[i].name + \",\";\n s = s + plugins[i].filename + \",\";\n s = s + plugins[i].version + \";\";\n if (debug)\n s = s + \"<br/>\";\n }\n return s;\n}", "function getEnabledLogTypes() {\n const strTypes = (process.env.MOCHA_WEBDRIVER_LOGTYPES == null) ? \"browser,driver\" :\n process.env.MOCHA_WEBDRIVER_LOGTYPES;\n const types = strTypes.split(',')\n .map((val) => val.trim().toLowerCase())\n .filter((val) => val);\n for (const t of types) {\n if (!exports.logTypes.includes(t)) {\n throw new Error(`LogType ${t} invalid`);\n }\n }\n return types;\n}", "list() {\n var entries = getRegistryEntries();\n var counter = 0;\n console.log(\"Registered devsuites:\\n\");\n entries.map(entry => {\n counter++;\n\n console.log(counter + \") \" + entry.name + \": \" + entry.directory);\n })\n }", "function getRegisteredThemeNames() {\n let names = _.keys(CheckItOut.themes.registeredImplementations);\n names.sort();\n return names;\n }", "registered() {\n return this.names.keys();\n }", "get LEVELS() {\n var ll = LatticeLogs;\n return [ll.LOG, ll.WARN, ll.ERROR, ll.INFO, ll.TRACE];\n }", "get loggerRegistry() {\n return this._loggerRegistry;\n }", "function listPlugins() {\n return Object.keys(pluginRegistry);\n}", "list() {\n\t\treturn Object.keys(this._plugins);\n\t}", "getHandlerNames() {\n if (typeof this.room._trappedRoomManager === `undefined`) {\n return [];\n }\n\n let handlerNames = [];\n\n for (let pluginId of\n Object.getOwnPropertyNames(this.room._trappedRoomManager.handlers)) {\n handlerNames = handlerNames.concat(Object.getOwnPropertyNames(\n this.room._trappedRoomManager.handlers[pluginId]));\n }\n\n return [...new Set(handlerNames)];\n }", "ListAvailableServices() {\n let url = `/dbaas/logs`;\n return this.client.request('GET', url);\n }", "function listPlugins() {\n\tlogger.entry(\"pluginLoader.listPlugins\");\n\t\n\tvar pluginNames = Object.keys(plugins);\n\t\n\tlogger.exit(\"pluginLoader.listPlugins\", pluginNames);\n\treturn pluginNames;\n}", "function logAllNames() {\n chrome.storage.sync.get(null, (items) => {\n if(items !== undefined && Object.keys(items).length !== 0) {\n console.log('Packages in storage:');\n for(var item in items) {\n console.log(item);\n }\n }\n });\n}", "function getVendorArray() {\n return Object.keys(global.pkg.browser);\n}", "logTypes() {\n return {\n debug: 'Debug',\n info: 'Info',\n notice: 'Notice',\n warning: 'Warning',\n alert: 'Alert',\n critical: 'Critical',\n emergency: 'Emergency',\n timeout: 'Timeout',\n error: 'Error',\n };\n }", "function getMockServiceNames() {\n return Object.keys(mockTraces);\n}", "drivers() {\n console.log('List of available drivers');\n for (let id in Mep.Config.get('Drivers')) {\n console.log(id);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a game from the game array
static deleteGame(id) { delete activeGames[id]; }
[ "function removeGame(id) {\n listGames.splice(id, 1);\n console.log(\"Destroying game number \"+ id);\n}", "handleOnClick_btRemoveGame(e) {\n let { selectedGame, games } = store.getState();\n\n for (let i = 0; i < games.length; i++)\n if (games[i] === selectedGame) {\n games.splice(i, 1);\n break;\n }\n\n this.setSelectedGameToFirst();\n }", "function removeGame(game) {\n\n console.log(\"[SRVSOCKET]: removing game with id : \" + game.gameIndex);\n delete SHIPS.games[game.gameIndex];\n SHIPS.activeGames--;\n console.log(\"[SRVSOCKET]: number of games: \" + SHIPS.games.length + \" (created) | \" + SHIPS.activeGames + \" (active)\");\n\n }", "deleteGame(id) {\n let i = this.index.findIndex(index => index === id);\n this.index.splice(i, 1);\n delete this.collection[id];\n }", "deleteGame(id) {\n let i = this.collectionIndex.findIndex(index => index === id);\n if (i !== -1) {\n this.collectionIndex.splice(i, 1);\n delete this.collection[id];\n delete this.timers[id];\n }\n }", "function deleteGame(id) {\n console.log('deleting game' + id);\n for (var i = 0; i < games.length; i++) {\n if (games[i].id === id) {\n console.log('deleting games[' + i + ']');\n games.splice(i, 1);\n break;\n }\n }\n ws.broadcast('game over', { id: id });\n}", "function deleteGame(game) {\n client.collection(\"games\", function(error, games) {\n if (error) throw error;\n games.remove({id: game.id}, function(error) {\n if (error) throw error;\n phoneCodeGen.return(game.code);\n delete game;\n console.log(\"successfully removed game from the database\");\n });\n });\n}", "function remove() {\n console.log(game.question);\n\n game.question.splice((current),1);\n game.industry.splice((current),1);\n game.correctAnswer.splice((current),1);\n game.wrongChoice1.splice((current),1);\n game.wrongChoice2.splice((current),1);\n game.wrongChoice3.splice((current),1);\n game.pix.splice((current),1);\n console.log(game.question);\n\n}", "deleteGame(gameId) {\n console.log(\"Game was deleted\");\n this.GameList.delete(gameId);\n }", "removeGame(id) {\n let index = this.games.findIndex((g) => id === g.id);\n if (index) {\n this.games.splice(index, 1);\n this.websocketService.removeGame(id);\n console.log(`Removed game with id ${id}.`);\n }\n }", "function deleteAllGames() {\n currentGames = {};\n}", "removeFromGame() {\r\n // remove word from array of words\r\n var newArray = []\r\n // newArray = newArray.concat(this.wordsArray.slice(0,this.currentPosition))\r\n newArray = newArray.concat(this.wordsArray.slice(1,this.wordsArray.length))\r\n\r\n // set new wordsArray and nWords in array\r\n this.nWords--;\r\n this.wordsArray = newArray\r\n }", "removeGame(hostId) {\n let game = this.getGame(hostId)\n\n if (game) {\n this.games = this.games.filter((game) => game.hostId !== hostId)\n }\n return game\n }", "function DeleteGame(gameid)\n{ \n // var gomap = maps.get(gameid)\n // var game = games.get(gameid)\n \n // var gameStopInfo = new GameStopInfo(gameid, game.Winer)\n \n // for(var playerid of game.CurrentPlayers)\n // {\n // players.delete(playerid)\n // var playergo = gomap.get(\"player_\"+playerid)\n // if(!!playergo)\n // {\n // SaveUserInfo(playerid, playergo.Score) \n // gameStopInfo.Players.push(playerid + \":\" + playergo.Score) \n // }\n // }\n\n\n var game = games.get(gameid)\n var playerList = new Array()\n\n var startIndex = 0\n var endIndex = game.CurrentPlayers.length-1\n for (var i = 0; i < game.CurrentPlayers.length; i++) {\n if (game.CurrentPlayers[i].role === game.Winer) {\n var playerInfo = new GameResultInfo(game.CurrentPlayers[i].Userid, \"+20\")\n\n playerList[startIndex++] = playerInfo;\n }\n else\n {\n var playerInfo = new GameResultInfo(game.CurrentPlayers[i].Userid, \"-5\")\n playerList[endIndex--] = playerInfo;\n }\n }\n\n\n\n \n var channel = channels.get(gameid)\n channel.pushMessage('onStop', playerList);\n \n // games.delete(gameid) \n // channels.delete(gameid)\n // maps.delete(gameid)\n}", "function handleGameDelete() {\n var currentGame = $(this)\n .parent()\n .parent()\n .data(\"game\");\n deleteGame(currentGame.id);\n }", "function deleteGame(id) {\n API.deleteGame(id)\n .then((res) => loadGames())\n .catch((err) => console.log(err));\n }", "remove() {\n this.game.remove(this);\n }", "deleteLastPlayed() {\n if (this.lastPlayed || this.lastPlayed.length != 0) {\n for (let i = 0; i < this.lastPlayed.length; i++) {\n this.lastPlayed[i].destroy(this.scene);\n }\n }\n }", "async deleteGame(game, userInfo) {\n const exists = await this.getOneGame(game, userInfo)\n\n if (!exists) {\n throw new BadRequest('This is not the game you are looking for')\n }\n await dbContext.Questions.deleteMany({ gameId: game })\n return await dbContext.Games.findByIdAndDelete(game)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates new frame aligned to bottom of other
bottomOf(other) { return new Frame(this.origin.x, other.origin.y + other.size.height, this.size.width, this.size.height); }
[ "bottomOf(other) {\n return new Frame(this.origin.x, other.origin.y + other.size.height, this.size.width, this.size.height);\n }", "topOf(other) {\n return new Frame(this.origin.x, other.origin.y - this.size.height, this.size.width, this.size.height);\n }", "topOf(other) {\n return new Frame(this.origin.x, other.origin.y - this.size.height, this.size.width, this.size.height);\n }", "putBottom(b, xOffset = 0, yOffset = 0) {\n let a = this;\n b.x = (a.x + a.halfWidth - b.halfWidth) + xOffset;\n b.y = (a.y + a.height) + yOffset;\n }", "putBottom(b, xOffset = 0, yOffset = 0) {\n let a = this\n b.x = (a.x + a.halfWidth - b.halfWidth) + xOffset\n b.y = (a.y + b.height) + yOffset\n }", "centerVerticalOf(other) {\n return new Frame(this.origin.x, other.origin.y + (other.size.height - this.size.height) / 2, this.size.width, this.size.height);\n }", "set bottom(bottom) {\n this._frame.origin.y = bottom - this.height;\n }", "function BottomEdge() {\n $( \"#target\" ).animate({paddingTop:\"+=310px\"});\n }", "centerVerticalOf(other) {\n return new Frame(this.origin.x, other.origin.y + (other.size.height - this.size.height) / 2, this.size.width, this.size.height);\n }", "rightOf(other) {\n return new Frame(other.origin.x + other.size.width, this.origin.y, this.size.width, this.size.height);\n }", "rightOf(other) {\n return new Frame(other.origin.x + other.size.width, this.origin.y, this.size.width, this.size.height);\n }", "function frame() {\n if (bottom < newBottom) {\n bottom = bottom + factorBottom\n side = side + factorSide\n elem.style.bottom = bottom + 'px';\n elem.style.right = side + 'px';\n clickable = false; // During the move, clickable is false so no card can be clicked during the movement\n } else {\n\t clearInterval(id);\n moveBack();\n }\n }", "_updatePosFromBottom() {\n this._topLeft = this._bottomRight.$subtract(this._size);\n this._updateCenter();\n }", "growToBottom(){\n let yDiff = this.sheet.dataFrame.corner.y - this.selectionFrame.corner.y;\n if(this.selectionFrame.isAtBottom(this.selectionFrame.cursor)){\n yDiff = this.sheet.dataFrame.corner.y - this.selectionFrame.origin.y;\n }\n let diff = [0, yDiff];\n let toPoint = this.applyToOppositeCorner(diff);\n this.selectionFrame.fromPointToPoint(\n this.selectionFrame.cursor,\n toPoint,\n false\n );\n }", "leftOf(other) {\n return new Frame(other.origin.x - this.size.width, this.origin.y, this.size.width, this.size.height);\n }", "bottom() {\n\t\tconst newYSlots = this.ySlots*2\n\t\tconst newY = this.y*2+1\n\t\treturn new Tile(this.x,newY,this.xSlots,newYSlots,this.xSize,this.ySize)\n\t}", "set BottomCenter(value) {}", "putTop(b, xOffset = 0, yOffset = 0) {\n let a = this;\n b.x = (a.x + a.halfWidth - b.halfWidth) + xOffset;\n b.y = (a.y - b.height) + yOffset;\n }", "leftOf(other) {\n return new Frame(other.origin.x - this.size.width, this.origin.y, this.size.width, this.size.height);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove all subs objects from the subscriptions map (after a disconnect for example)
function clearSubs() { var subsDiv = document.getElementById("subscriptions"); for (var topic in subscriptions) { if (subscriptions.hasOwnProperty(topic)) { // remove row... subsDiv.removeChild(subscriptions[topic].div); // remove from data structure delete subscriptions[topic]; subCount--; } } }
[ "removeAllSubscriptions() {\n for (const key in this.subscriptions) {\n if (this.subscriptions[key]) {\n this.subscriptions[key].unsubscribe();\n delete this.subscriptions[key];\n }\n }\n }", "clearPersistedSubsList() {\n for (let [k, v] of persist.subsList) {\n service.unsubscribe(k);\n }\n persist.removeAllSubsListStorage();\n }", "unsubAll () {\n this._subscribers.clear()\n }", "function unsubscribeAll(conn){\n\tfor (var service in subscriptions){\n\t\tvar index = subscriptions[service].indexOf(conn);\n\t\tif (index>-1)\n\t\t\tsubscriptions[service].splice(index, 1);\n\t}\n}", "unsubscribeAll() {\n _subscriptions.set(this, []);\n }", "async function clearSubscriptions() {\n const subscriptions = await getSubscriptions();\n subscriptions.data.map((subscription) => {\n deleteSubscription(subscription.id);\n });\n}", "unlistenAll() {\n const subjects = this.subjects;\n const keys = Object.keys(subjects);\n\n keys.forEach(key => {\n subjects[key].dispose();\n });\n\n this.subjects = {};\n }", "function unsubscribeAll() {\n // guard: do not try to unsubscribe if client has not yet been connected\n if (!session) {\n logError(\"Error from unsubscribeAll(), session not connected\");\n reject();\n } // unsubscribe from all topics on client\n\n\n Object.keys(subscriptions).map(function (topicFilter, _) {\n return unsubscribe(topicFilter);\n });\n }", "unsubscribe() {\n try {\n for (const id of this.map.keys()) {\n this.unsubscribeProvider(id);\n }\n } finally {\n this.map.clear();\n }\n }", "stopAllSubscriptions() {\n var self = this;\n self.subscriptions.forEach(({url, hub, _id}) => {\n self.unsubscribe(_id);\n });\n self.subscriptions.forEach( (sub) => sub.unsub.wait());\n }", "removeAllSubscriptions() {\n return __awaiter(this, void 0, void 0, function* () {\n const allSubs = this.getSubscriptions().slice();\n const allSubPromises = allSubs.map((sub) => this.removeSubscription(sub));\n const allRemovedSubs = yield Promise.all(allSubPromises);\n return allRemovedSubs.map(({ error }, i) => {\n return {\n data: { subscription: allSubs[i] },\n error,\n };\n });\n });\n }", "unsubscribeAll() {\n const all = this.subscriptions.getAll()\n for (const { event, type, id, handler } of all) {\n this.unsubscribe(event, type, id, handler)\n }\n }", "unsubscribeAll() {\r\n this._observers = [];\r\n }", "unsubscribeall (topicname){\r\n\t\tif( topicname == undefined ){\r\n\t\t\tfor( var tn in this.subscriptions )\r\n\t\t\t\tfor( var cbi in this.subscriptions[tn] )\r\n\t\t\t\t\tglobals.PubSub.unsub(tn,this.subscriptions[tn][cbi]) ;\r\n\t\t\tthis.subscriptions = {} ;\r\n\t\t} else {\r\n\t\t\tfor( var cbi in this.subscriptions[topicname] )\r\n\t\t\t\tglobals.PubSub.unsub(topicname,this.subscriptions[topicname][cbi]) ;\r\n\t\t\tdelete this.subscriptions[topicname] ;\r\n\t\t}\r\n\t}", "function cleanUpSubscriptions() {\n console.log('cleaning up subscriptions...');\n serviceBusService.listSubscriptions(topicName, function (error, subs, response) {\n if (!error) {\n console.log('found ' + subs.length + ' subscriptions');\n for (var i = 0; i < subs.length; i++) {\n // if there are more than 100 messages on the subscription, assume the edge node is down \n if (subs[i].MessageCount > 100) {\n console.log('deleting subscription ' + subs[i].SubscriptionName);\n serviceBusService.deleteSubscription(topicName, subs[i].SubscriptionName, function (error, response) {\n if (error) {\n console.log('error:deleteSubscription\\n' + JSON.stringify(error));\n }\n });\n }\n //console.log(JSON.stringify(subs[i]));\n }\n } else {\n console.log('error::getTopicSubscriptions\\n' + JSON.stringify(error));\n }\n setTimeout(cleanUpSubscriptions, 60000);\n });\n}", "unsubscribeAll() {\n this._observers = [];\n }", "clear() {\n this._subscriptions.splice(0, this._subscriptions.length);\n }", "clear() {\r\n this._subscriptions.splice(0, this._subscriptions.length);\r\n }", "static unsubscribeAll() {\n this._subscriptions = this._subscriptions || [];\n\n this._subscriptions.forEach((subscription) => {\n if (subscription.dispose) {\n // Rx\n subscription.dispose();\n } else {\n // Bacon, Kefir\n subscription[0].offValue(subscription[1]);\n }\n });\n this._subscriptions = [];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cut edges along crossings/tjunctions
function cutEdges(floatPoints, edges, crossings, junctions, useColor) { //Convert crossings into tjunctions by constructing rational points var ratPoints = [] for(var i=0; i<crossings.length; ++i) { var crossing = crossings[i] var e = crossing[0] var f = crossing[1] var ee = edges[e] var ef = edges[f] var x = solveIntersection( ratVec(floatPoints[ee[0]]), ratVec(floatPoints[ee[1]]), ratVec(floatPoints[ef[0]]), ratVec(floatPoints[ef[1]])) if(!x) { //Segments are parallel, should already be handled by t-junctions continue } var idx = ratPoints.length + floatPoints.length ratPoints.push(x) junctions.push([e, idx], [f, idx]) } //Sort tjunctions function getPoint(idx) { if(idx >= floatPoints.length) { return ratPoints[idx-floatPoints.length] } var p = floatPoints[idx] return [ rat(p[0]), rat(p[1]) ] } junctions.sort(function(a, b) { if(a[0] !== b[0]) { return a[0] - b[0] } var u = getPoint(a[1]) var v = getPoint(b[1]) return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1]) }) //Split edges along junctions for(var i=junctions.length-1; i>=0; --i) { var junction = junctions[i] var e = junction[0] var edge = edges[e] var s = edge[0] var t = edge[1] //Check if edge is not lexicographically sorted var a = floatPoints[s] var b = floatPoints[t] if(((a[0] - b[0]) || (a[1] - b[1])) < 0) { var tmp = s s = t t = tmp } //Split leading edge edge[0] = s var last = edge[1] = junction[1] //If we are grouping edges by color, remember to track data var color if(useColor) { color = edge[2] } //Split other edges while(i > 0 && junctions[i-1][0] === e) { var junction = junctions[--i] var next = junction[1] if(useColor) { edges.push([last, next, color]) } else { edges.push([last, next]) } last = next } //Add final edge if(useColor) { edges.push([last, t, color]) } else { edges.push([last, t]) } } //Return constructed rational points return ratPoints }
[ "deleteCutEdges() {\n this._computeNextCWEdges();\n this._findLabeledEdgeRings();\n\n // Cut-edges (bridges) are edges where both edges have the same label\n this.edges.forEach(edge => {\n if (edge.label === edge.symetric.label) {\n this.removeEdge(edge.symetric);\n this.removeEdge(edge);\n }\n });\n }", "function cutEdges(floatPoints, edges, crossings, junctions, useColor) {\n\n //Convert crossings into tjunctions by constructing rational points\n var ratPoints = []\n for(var i=0; i<crossings.length; ++i) {\n var crossing = crossings[i]\n var e = crossing[0]\n var f = crossing[1]\n var ee = edges[e]\n var ef = edges[f]\n var x = solveIntersection(\n ratVec(floatPoints[ee[0]]),\n ratVec(floatPoints[ee[1]]),\n ratVec(floatPoints[ef[0]]),\n ratVec(floatPoints[ef[1]]))\n if(!x) {\n //Segments are parallel, should already be handled by t-junctions\n continue\n }\n var idx = ratPoints.length + floatPoints.length\n ratPoints.push(x)\n junctions.push([e, idx], [f, idx])\n }\n\n //Sort tjunctions\n function getPoint(idx) {\n if(idx >= floatPoints.length) {\n return ratPoints[idx-floatPoints.length]\n }\n var p = floatPoints[idx]\n return [ rat(p[0]), rat(p[1]) ]\n }\n junctions.sort(function(a, b) {\n if(a[0] !== b[0]) {\n return a[0] - b[0]\n }\n var u = getPoint(a[1])\n var v = getPoint(b[1])\n return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1])\n })\n\n //Split edges along junctions\n for(var i=junctions.length-1; i>=0; --i) {\n var junction = junctions[i]\n var e = junction[0]\n\n var edge = edges[e]\n var s = edge[0]\n var t = edge[1]\n\n //Check if edge is not lexicographically sorted\n var a = floatPoints[s]\n var b = floatPoints[t]\n if(((a[0] - b[0]) || (a[1] - b[1])) < 0) {\n var tmp = s\n s = t\n t = tmp\n }\n\n //Split leading edge\n edge[0] = s\n var last = edge[1] = junction[1]\n\n //If we are grouping edges by color, remember to track data\n var color\n if(useColor) {\n color = edge[2]\n }\n\n //Split other edges\n while(i > 0 && junctions[i-1][0] === e) {\n var junction = junctions[--i]\n var next = junction[1]\n if(useColor) {\n edges.push([last, next, color])\n } else {\n edges.push([last, next])\n }\n last = next\n }\n\n //Add final edge\n if(useColor) {\n edges.push([last, t, color])\n } else {\n edges.push([last, t])\n }\n }\n\n //Return constructed rational points\n return ratPoints\n}", "function cutEdges (floatPoints, edges, crossings, junctions, useColor) {\n var i, e\n\n // Convert crossings into tjunctions by constructing rational points\n var ratPoints = floatPoints.map((p) => [\n rat(p[0]),\n rat(p[1])\n ])\n for (i = 0; i < crossings.length; ++i) {\n var crossing = crossings[i]\n e = crossing[0]\n var f = crossing[1]\n var ee = edges[e]\n var ef = edges[f]\n var x = solveIntersection(\n ratVec(floatPoints[ee[0]]),\n ratVec(floatPoints[ee[1]]),\n ratVec(floatPoints[ef[0]]),\n ratVec(floatPoints[ef[1]]))\n if (!x) {\n // Segments are parallel, should already be handled by t-junctions\n continue\n }\n var idx = floatPoints.length\n floatPoints.push([ratToFloat(x[0]), ratToFloat(x[1])])\n ratPoints.push(x)\n junctions.push([e, idx], [f, idx])\n }\n\n // Sort tjunctions\n junctions.sort(function (a, b) {\n if (a[0] !== b[0]) {\n return a[0] - b[0]\n }\n var u = ratPoints[a[1]]\n var v = ratPoints[b[1]]\n return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1])\n })\n\n // Split edges along junctions\n for (i = junctions.length - 1; i >= 0; --i) {\n var junction = junctions[i]\n e = junction[0]\n\n var edge = edges[e]\n var s = edge[0]\n var t = edge[1]\n\n // Check if edge is not lexicographically sorted\n var a = floatPoints[s]\n var b = floatPoints[t]\n if (((a[0] - b[0]) || (a[1] - b[1])) < 0) {\n var tmp = s\n s = t\n t = tmp\n }\n\n // Split leading edge\n edge[0] = s\n var last = edge[1] = junction[1]\n\n // If we are grouping edges by color, remember to track data\n var color\n if (useColor) {\n color = edge[2]\n }\n\n // Split other edges\n while (i > 0 && junctions[i - 1][0] === e) {\n var junction = junctions[--i]\n var next = junction[1]\n if (useColor) {\n edges.push([last, next, color])\n } else {\n edges.push([last, next])\n }\n last = next\n }\n\n // Add final edge\n if (useColor) {\n edges.push([last, t, color])\n } else {\n edges.push([last, t])\n }\n }\n\n // Return constructed rational points\n return ratPoints\n}", "function cutEdges (floatPoints, edges, crossings, junctions, useColor) {\n var i, e\n\n // Convert crossings into tjunctions by constructing rational points\n var ratPoints = floatPoints.map(function(p) {\n return [\n rat(p[0]),\n rat(p[1])\n ]\n })\n for (i = 0; i < crossings.length; ++i) {\n var crossing = crossings[i]\n e = crossing[0]\n var f = crossing[1]\n var ee = edges[e]\n var ef = edges[f]\n var x = solveIntersection(\n ratVec(floatPoints[ee[0]]),\n ratVec(floatPoints[ee[1]]),\n ratVec(floatPoints[ef[0]]),\n ratVec(floatPoints[ef[1]]))\n if (!x) {\n // Segments are parallel, should already be handled by t-junctions\n continue\n }\n var idx = floatPoints.length\n floatPoints.push([ratToFloat(x[0]), ratToFloat(x[1])])\n ratPoints.push(x)\n junctions.push([e, idx], [f, idx])\n }\n\n // Sort tjunctions\n junctions.sort(function (a, b) {\n if (a[0] !== b[0]) {\n return a[0] - b[0]\n }\n var u = ratPoints[a[1]]\n var v = ratPoints[b[1]]\n return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1])\n })\n\n // Split edges along junctions\n for (i = junctions.length - 1; i >= 0; --i) {\n var junction = junctions[i]\n e = junction[0]\n\n var edge = edges[e]\n var s = edge[0]\n var t = edge[1]\n\n // Check if edge is not lexicographically sorted\n var a = floatPoints[s]\n var b = floatPoints[t]\n if (((a[0] - b[0]) || (a[1] - b[1])) < 0) {\n var tmp = s\n s = t\n t = tmp\n }\n\n // Split leading edge\n edge[0] = s\n var last = edge[1] = junction[1]\n\n // If we are grouping edges by color, remember to track data\n var color\n if (useColor) {\n color = edge[2]\n }\n\n // Split other edges\n while (i > 0 && junctions[i - 1][0] === e) {\n var junction = junctions[--i]\n var next = junction[1]\n if (useColor) {\n edges.push([last, next, color])\n } else {\n edges.push([last, next])\n }\n last = next\n }\n\n // Add final edge\n if (useColor) {\n edges.push([last, t, color])\n } else {\n edges.push([last, t])\n }\n }\n\n // Return constructed rational points\n return ratPoints\n}", "function cutEdge (hds,he) {\n\tvar prev = hds.halfedge [he.prv];\n\tvar result = hds.splitFace (prev,he);\n\thds.toggleBorder (result, true);\n}", "cut (cuttingLine) {\n let debug = false || (!!geom._flags['geom.Polygon.cut.debug'])\n\n if (debug) {\n console.log('cutShape:')\n // Vertices\n console.log(' vertices:')\n let verticesstr = ''\n for (let i = 0; i < this.edges.length; i++) {\n verticesstr += (i > 0 ? ', ' : '') + 'v' + i + ':(' + this.edges[i].x1() + ', ' + this.edges[i].y1() + ')'\n }\n console.log(' ' + verticesstr)\n // Edges\n console.log(' edges.length = ' + this.edges.length)\n let edgeLengths = ''\n for (let i = 0; i < this.edges.length; i++) {\n edgeLengths += (i > 0 ? ', ' : '') + this.edges[i].length()\n }\n console.log(' edge lengths = ' + edgeLengths)\n console.log(' cutting line = ' + cuttingLine.toString())\n }\n\n // Find intersections\n let intersections = []\n for (let i = 0; i < this.edges.length; i++) {\n let edge = this.edges[i]\n if (debug) console.log(' edge(' + i + ') = ' + edge.toString())\n // let intersections_i = edge.intersect(cuttingLine)\n // for (let j = 0; j < intersections_i.length; j++) {\n // let intersection = intersections_i[j]\n let intersectionResult = edge.intersect(cuttingLine)\n // if (debug) console.log(' intersection = ' + (intersection != null ? intersection.toString() : null))\n if (intersectionResult.getNumberOfIntersections() === 1) {\n let intersection = intersectionResult.getIntersections()[0]\n let ok = true\n let verticesIntersectionCheck = true\n if (ok) {\n // Exclude the intersection that only touch on the vertex from exterior.\n if (geom.Util.epsilonEquals(intersection.x(), edge.x1()) && geom.Util.epsilonEquals(intersection.y(), edge.y1())) {\n // if (debug) console.log(' >>>1')\n let prevEdge = this.edges[(i > 0 ? i - 1 : this.edges.length - 1)]\n if (cuttingLine.onSameSide(prevEdge.x1(), prevEdge.y1(), edge.x2(), edge.y2())) {\n let interiorAngles = this.getInteriorAngles()\n if (interiorAngles[i] < Math.PI) {\n if (debug) console.log(' touch on vertices (a) - dropped')\n ok = false\n }\n else {\n // Skip the vertices intersection check to keep the intersections on both edges in order to prevent odd number of intersections.\n // But an edge may be split into two edges that need to combine again.\n verticesIntersectionCheck = false\n }\n }\n }\n }\n if (ok) {\n // Exclude the intersection that only touch on the vertex from exterior.\n if (geom.Util.epsilonEquals(intersection.x(), edge.x2()) && geom.Util.epsilonEquals(intersection.y(), edge.y2())) {\n // if (debug) console.log(' >>>2')\n let nextEdgeIdx = (i < this.edges.length - 1 ? i + 1 : 0)\n let nextEdge = this.edges[nextEdgeIdx]\n if (cuttingLine.onSameSide(edge.x1(), edge.y1(), nextEdge.x2(), nextEdge.y2())) {\n let interiorAngles = this.getInteriorAngles()\n if (interiorAngles[nextEdgeIdx] < Math.PI) {\n if (debug) console.log(' touch on vertices (b) - dropped')\n ok = false\n }\n else {\n // Skip the vertices intersection check to keep the intersections on both edges in order to prevent odd number of intersections.\n // But an edge may be split into two edges that need to combine again.\n verticesIntersectionCheck = false\n }\n }\n }\n }\n if (ok) {\n if (geom.Util.epsilonEquals(intersection.x(), cuttingLine.x1()) && geom.Util.epsilonEquals(intersection.y(), cuttingLine.y1())) {\n let Vi = cuttingLine.getVector().negate() // The vector is pointing to the edge.\n let Ve = edge.getVector()\n let crossProduct = Ve.cross(Vi)\n // console.log('Ve x Vi = ' + crossProduct.toString())\n let direction = crossProduct.get(2)\n if (geom.Util.epsilonEquals(direction, 0)) {\n if (debug) console.log(' XXX - dropped')\n ok = false\n }\n else {\n direction = (direction < 0 ? -1 : 1)\n if (this.isClockwise()) direction = -direction\n if (direction < 0) {\n if (debug) console.log(' start of cutting line touch on edge from exterior - dropped')\n ok = false\n }\n }\n }\n }\n if (ok) {\n if (geom.Util.epsilonEquals(intersection.x(), cuttingLine.x2()) && geom.Util.epsilonEquals(intersection.y(), cuttingLine.y2())) {\n let Vi = cuttingLine.getVector() // The vector is pointing to the edge.\n let Ve = edge.getVector()\n let crossProduct = Ve.cross(Vi)\n // console.log('Ve x Vi = ' + crossProduct.toString())\n let direction = crossProduct.get(2)\n if (geom.Util.epsilonEquals(direction, 0)) {\n if (debug) console.log(' YYY - dropped')\n ok = false\n }\n else {\n direction = (direction < 0 ? -1 : 1)\n if (this.isClockwise()) direction = -direction\n if (direction < 0) {\n if (debug) console.log(' end of cutting line touch on edge from exterior - dropped')\n ok = false\n }\n }\n }\n }\n if (ok) {\n if (verticesIntersectionCheck) {\n // If the intersection intersects on one edge end, it must intersects on the neighbour's edge end, include only one of them.\n // (Include only the intersection that intersects on the start of the edge in this case.)\n if (geom.Util.epsilonEquals(intersection.x(), edge.x2()) && geom.Util.epsilonEquals(intersection.y(), edge.y2())) {\n if (debug) console.log(' intersection at the end of line - dropped')\n ok = false\n }\n }\n }\n if (ok) {\n intersections.push({\n intersection: intersection,\n edge: edge,\n edgeIndex: i\n })\n }\n }\n }\n if (debug) {\n let intersectionstr = '['\n for (let i = 0; i < intersections.length; i++) {\n intersectionstr += (i > 0 ? ', ' : '') + intersections[i].intersection.toString()\n }\n intersectionstr += ']'\n console.log('intersections: ' + intersectionstr)\n }\n if ((intersections.length % 2) === 1) {\n // console.log('Exception : Odd number of intersections - ' + intersections.length + '.')\n throw new Error('Exception : Odd number of intersections - ' + intersections.length + '.')\n /*\n for (let i = 0; i < intersections.length; i++) {\n console.log(' ' + intersections[i].intersection.toString() + ' on edge ' + intersections[i].edgeIndex + ': ' + intersections[i].edge.toString())\n }\n */\n }\n\n let newShapes = null\n if (intersections.length > 0 && (intersections.length % 2) === 0) {\n // Sort intersections\n intersections.sort(function (p1, p2) {\n let d1 = geom.Util.distance(cuttingLine.x1(), cuttingLine.y1(), p1.intersection.x(), p1.intersection.y())\n let d2 = geom.Util.distance(cuttingLine.x1(), cuttingLine.y1(), p2.intersection.x(), p2.intersection.y())\n let cmpValue = (d1 - d2)\n if (cmpValue === 0) {\n cmpValue = (p1.edgeIndex - p2.edgeIndex)\n }\n return cmpValue\n })\n\n newShapes = []\n let edgesList = [this.edges]\n // console.log('intersections.length = ' + intersections.length)\n for (let i = 0; i < intersections.length; i += 2) {\n let p1 = intersections[i]\n let p2 = intersections[i + 1]\n // console.log('p1', p1, 'p2', p2)\n\n let nextEdgesList = []\n for (let j = 0; j < edgesList.length; j++) {\n let subEdges = edgesList[j]\n\n let edgeIndex1 = -1\n let edgeIndex2 = -1\n for (let e = 0; e < subEdges.length; e++) {\n if (edgeIndex1 === -1 && subEdges[e] === p1.edge) {\n edgeIndex1 = e\n }\n else\n if (edgeIndex2 === -1 && subEdges[e] === p2.edge) {\n edgeIndex2 = e\n }\n if (edgeIndex1 > -1 && edgeIndex2 > -1) break\n }\n if (edgeIndex1 === -1 || edgeIndex2 === -1) {\n console.log('Exception : edgeIndex1=' + edgeIndex1 + ', edgeIndex2=' + edgeIndex2)\n }\n\n let edgeIndexItr = null\n\n // console.log('edgeSet1:')\n let edgeSet1 = []\n let moreIntersections1 = false\n edgeSet1.push(new geom.LineEdge(p1.intersection.x(), p1.intersection.y(), p2.intersection.x(), p2.intersection.y()))\n edgeIndexItr = new util.IntegerIterator(edgeIndex2, edgeIndex1, 0, subEdges.length - 1)\n while (edgeIndexItr.hasNext()) {\n let e = edgeIndexItr.next()\n if (e === edgeIndex2) {\n if (e === edgeIndex1) { // Intersects the same edge two times. Impossible for striaght line.\n }\n else {\n let edge = new geom.LineEdge(p2.intersection.x(), p2.intersection.y(), subEdges[e].x2(), subEdges[e].y2())\n if (edge.length() > 0) {\n edgeSet1.push(edge)\n }\n }\n }\n else\n if (e === edgeIndex1) {\n let edge = new geom.LineEdge(subEdges[e].x1(), subEdges[e].y1(), p1.intersection.x(), p1.intersection.y())\n if (edge.length() > 0) {\n edgeSet1.push(edge)\n }\n }\n else {\n edgeSet1.push(subEdges[e])\n if (!moreIntersections1) {\n for (let k = 0; k < intersections.length; k++) {\n if (intersections[k].edge === subEdges[e]) {\n moreIntersections1 = true\n break\n }\n }\n }\n }\n }\n // console.log('edgeSet1 = ' + edgeSet1)\n\n let edgeSet2 = []\n let moreIntersections2 = false\n edgeSet2.push(new geom.LineEdge(p2.intersection.x(), p2.intersection.y(), p1.intersection.x(), p1.intersection.y()))\n edgeIndexItr = new util.IntegerIterator(edgeIndex1, edgeIndex2, 0, subEdges.length - 1)\n while (edgeIndexItr.hasNext()) {\n let e = edgeIndexItr.next()\n if (e === edgeIndex1) {\n if (e === edgeIndex2) { // Intersects the same edge two times. Impossible for striaght line.\n }\n else {\n let edge = new geom.LineEdge(p1.intersection.x(), p1.intersection.y(), subEdges[e].x2(), subEdges[e].y2())\n if (edge.length() > 0) {\n edgeSet2.push(edge)\n }\n }\n }\n else\n if (e === edgeIndex2) {\n let edge = new geom.LineEdge(subEdges[e].x1(), subEdges[e].y1(), p2.intersection.x(), p2.intersection.y())\n if (edge.length() > 0) {\n edgeSet2.push(edge)\n }\n }\n else {\n edgeSet2.push(subEdges[e])\n if (!moreIntersections2) {\n for (let k = 0; k < intersections.length; k++) {\n if (intersections[k].edge === subEdges[e]) {\n moreIntersections2 = true\n break\n }\n }\n }\n }\n }\n // console.log('edgeSet2 = ' + edgeSet2)\n\n // console.log('moreIntersections1=' + moreIntersections1 + ', moreIntersections2=' + moreIntersections1)\n if (!moreIntersections1) {\n if (edgeSet1.length > 2) {\n newShapes.push(new geom.Polygon(edgeSet1))\n }\n }\n else {\n nextEdgesList.push(edgeSet1)\n }\n if (!moreIntersections2) {\n if (edgeSet2.length > 2) {\n newShapes.push(new geom.Polygon(edgeSet2))\n }\n }\n else {\n nextEdgesList.push(edgeSet2)\n }\n }\n edgesList = nextEdgesList\n }\n }\n\n return newShapes\n }", "function shiftDoubleEdges(selection){\n\t\tresetGraphCodes();\n\t\tvar up = new Array();\n\t\tvar down = new Array();\n\t\tselection.each(function(d){//d = each vertex once.\n\t\t\tfor(i=0; i<d.edges.length; i++){\n\t\t\t\tvar edge = d.edges[i];\n\t\t\t\t//console.log(\"on edge: \"+edge.returnKey());\n\t\t\t\tif(edge.code!==1){\n\t\t\t\t\tvar filteredEdges = d3.selectAll('.e'+edge.from).filter('.e'+edge.to);\n\t\t\t\t\tif(filteredEdges[0].length > 1){\n\t\t\t\t\t\t//This line does not support multigraphs.\n\t\t\t\t\t\t//You should feel bad if you're using a multigraph anyway.\n\t\t\t\t\t\tfilteredEdges.data()[0].code = 1;\n\t\t\t\t\t\tfilteredEdges.data()[1].code = 1;//Magically changes the base Edge object! Woot woot!\n\t\t\t\t\t\tup.push(filteredEdges[0][0]);//Do not ask\n\t\t\t\t\t\tdown.push(filteredEdges[0][1]);//how the sausage is made\n\t\t\t\t\t}\n\t\t\t\t\tedge.code = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\td3.selectAll(up).each(function(d){\n\t\t\tvar curLine = d3.select(this); console.log(curLine.attr(\"x1\"));\n\t\t\t\n\t\t\tvar from = [curLine.select('.shaft').attr(\"x1\"), curLine.select('.shaft').attr(\"y1\")];\n\t\t\tvar to = [curLine.select('.shaft').attr(\"x2\"), curLine.select('.shaft').attr(\"y2\")];\n\t\t\tvar vector = getOrthogonalUnitSlope(from, to);\n\t\t\t\n\t\t\tvar translationStatement = [\"translate(\",-5*vector[0],\",\",-5*vector[1],\")\"].join(\"\");\n\t\t\tcurLine.attr(\"transform\", translationStatement);\n\t\t});\n\t\td3.selectAll(down).each(function(d){\n\t\t\tvar curLine = d3.select(this);\n\t\t\t\n\t\t\tvar from = [curLine.select('.shaft').attr(\"x1\"), curLine.select('.shaft').attr(\"y1\")];\n\t\t\tvar to = [curLine.select('.shaft').attr(\"x2\"), curLine.select('.shaft').attr(\"y2\")];\n\t\t\tvar vector = getOrthogonalUnitSlope(from, to);\n\t\t\t\n\t\t\tvar translationStatement = [\"translate(\",-5*vector[0],\",\",-5*vector[1],\")\"].join(\"\");\n\t\t\tcurLine.attr(\"transform\", translationStatement);\n\t\t});\n\t}", "cutEdge(edgeID){\n\t\treturn P_PRIVATES.get(this).dualGraph.tryApplyCut(edgeID);\n\t}", "function cutBorderAppropiately( positionAndFeatureDireciton ) {\n let position = positionAndFeatureDireciton.position;\n let featureDirection = positionAndFeatureDireciton.featureDirection;\n const k = position.toArray().toString();\n const bothBorderElements = mapPositionToBorderingObject.get( k );\n const bothDirections = [bothBorderElements[0].userData, bothBorderElements[1].userData]\n\n for(let i = 0; i < bothBorderElements.length; i++){\n const objBox = bothBorderElements[i];\n const gap = -0.3;\n const remainingThickness = borderThickness * 0.1;\n\n switch(objBox.userData) {\n case 'top':\n if(bothDirections.indexOf('left') != -1)\n moveVertices(objBox, -gap, remainingThickness, 0, 2, 1, 3, 'x', 'z');\n else\n moveVertices(objBox, gap, remainingThickness, 5, 7, 4, 6, 'x', 'z');\n break;\n case 'bottom':\n if(bothDirections.indexOf('left') != -1)\n moveVertices(objBox, -gap, -remainingThickness, 1, 3, 0, 2, 'x', 'z');\n else\n moveVertices(objBox, gap, -remainingThickness, 4, 6, 5, 7, 'x', 'z');\n break;\n case 'left':\n if(bothDirections.indexOf('top') != -1)\n moveVertices(objBox, -gap, remainingThickness, 0, 2, 5, 7, 'z', 'x');\n else\n moveVertices(objBox, gap, remainingThickness, 1, 3, 4, 6, 'z', 'x');\n break;\n case 'right':\n if(bothDirections.indexOf('top') != -1)\n moveVertices(objBox, -gap, -remainingThickness, 5, 7, 0, 2, 'z', 'x');\n else\n moveVertices(objBox, gap, -remainingThickness, 4, 6, 1, 3, 'z', 'x');\n break;\n }\n }\n\n\n function moveVertices(boxObject, gap, remainingThickness, id1, id2, id3, id4, dimension1, dimension2) {\n let vertices = boxObject.geometry.vertices;\n vertices[id1][dimension1] = gap;\n vertices[id2][dimension1] = gap;\n vertices[id3][dimension1] = gap;\n vertices[id4][dimension1] = gap;\n vertices[id3][dimension2] = remainingThickness;\n vertices[id4][dimension2] = remainingThickness;\n boxObject.geometry.vertices = vertices;\n }\n\n function cutOppositeBorder( direction ) {\n let neighborsCorner = new Neighbors( position, featureDirection ); \n let i = 0;\n while( !thisArg.voxelGrid.isFreeAtPosition( neighborsCorner[ direction ].position ) ){\n neighborsCorner[ direction ].goOne();\n i++;\n }\n if( i > 0) {\n const k = neighborsCorner[ direction ].position.toArray().toString();\n let objBoxNeighbors = new Neighbors(neighborsCorner[ direction ].position, featureDirection);\n const objBox = mapPositionToBorderingObject.get( k );\n\n const gap = -0.4;\n const remainingThickness = borderThickness * 0.1;\n // remove the opposite border element depending on the directions of the inner corner\n // therefore it also important to \n switch(objBox.userData) {\n case 'top':\n if(bothDirections.indexOf('left') != -1) {\n moveVertices(objBox, -gap, remainingThickness, 0, 2, 1, 3, 'x', 'z');\n const k = objBoxNeighbors.right.position.toArray().toString();\n let otherObjBox = mapPositionToBorderingObject.get( k );\n moveVertices(otherObjBox, gap, remainingThickness, 5, 7, 4, 6, 'x', 'z');\n }\n else {\n moveVertices(objBox, gap, remainingThickness, 5, 7, 4, 6, 'x', 'z');\n const k = objBoxNeighbors.left.position.toArray().toString();\n let otherObjBox = mapPositionToBorderingObject.get( k );\n moveVertices(otherObjBox, -gap, remainingThickness, 0, 2, 1, 3, 'x', 'z');\n }\n break;\n case 'bottom':\n if(bothDirections.indexOf('left') != -1) {\n moveVertices(objBox, -gap, -remainingThickness, 1, 3, 0, 2, 'x', 'z');\n const k = objBoxNeighbors.right.position.toArray().toString();\n let otherObjBox = mapPositionToBorderingObject.get( k );\n moveVertices(otherObjBox, gap, -remainingThickness, 4, 6, 5, 7, 'x', 'z');\n }\n else {\n moveVertices(objBox, gap, -remainingThickness, 4, 6, 5, 7, 'x', 'z');\n const k = objBoxNeighbors.left.position.toArray().toString();\n let otherObjBox = mapPositionToBorderingObject.get( k );\n moveVertices(otherObjBox, -gap, -remainingThickness, 1, 3, 0, 2, 'x', 'z');\n }\n break;\n case 'left':\n if(bothDirections.indexOf('top') != -1) {\n moveVertices(objBox, -gap, remainingThickness, 0, 2, 5, 7, 'z', 'x');\n const k = objBoxNeighbors.bottom.position.toArray().toString();\n let otherObjBox = mapPositionToBorderingObject.get( k ); \n moveVertices(otherObjBox, gap, remainingThickness, 1, 3, 4, 6, 'z', 'x');\n }\n else {\n moveVertices(objBox, gap, remainingThickness, 1, 3, 4, 6, 'z', 'x');\n const k = objBoxNeighbors.top.position.toArray().toString();\n let otherObjBox = mapPositionToBorderingObject.get( k ); \n moveVertices(otherObjBox, -gap, remainingThickness, 0, 2, 5, 7, 'z', 'x');\n }\n break;\n case 'right':\n if(bothDirections.indexOf('top') != -1) {\n moveVertices(objBox, -gap, -remainingThickness, 5, 7, 0, 2, 'z', 'x');\n const k = objBoxNeighbors.bottom.position.toArray().toString();\n let otherObjBox = mapPositionToBorderingObject.get( k );\n moveVertices(otherObjBox, gap, -remainingThickness, 4, 6, 1, 3, 'z', 'x');\n }\n else{\n moveVertices(objBox, gap, -remainingThickness, 4, 6, 1, 3, 'z', 'x');\n const k = objBoxNeighbors.top.position.toArray().toString();\n let otherObjBox = mapPositionToBorderingObject.get( k );\n moveVertices(otherObjBox, -gap, -remainingThickness, 5, 7, 0, 2, 'z', 'x');\n }\n break;\n }\n }\n };\n\n [ 'top', 'bottom', 'left', 'right' ].forEach( cutOppositeBorder );\n\n }", "function removeCutSegments(coords) {\n if (!touchesEdge(coords)) return coords;\n var coords2 = [];\n var a, b, c, x, y;\n var skipped = false;\n coords.pop(); // remove duplicate point\n a = coords[coords.length-1];\n b = coords[0];\n for (var ci=1, n=coords.length; ci <= n; ci++) {\n c = ci == n ? coords2[0] : coords[ci];\n if (!c) continue; // undefined c could occur in a defective path\n if ((skipped || isEdgeSegment(a, b)) && isEdgeSegment(b, c)) {\n // skip b\n // console.log(\"skipping b:\", ci, a, b, c)\n skipped = true;\n } else {\n if (skipped === true) {\n skipped = false;\n }\n coords2.push(b);\n a = b;\n }\n b = c;\n }\n if (coords2.length > 0) {\n coords2.push(coords2[0].concat()); // close the path\n }\n // TODO: handle runs that are split at the array boundary\n return coords2;\n }", "function smoothenMesh (mesh, cutDepth) {\n mesh = mergeVertices(mesh.cells, mesh.positions)\n const nodeGraph = createNodeGraph(mesh)\n const clippingPlanes = []\n for (const vertex of Object.keys(nodeGraph)) {\n const vertexNormal = [0, 0, 0]\n const curPt = mesh.positions[vertex]\n const neighborCount = nodeGraph[vertex].length\n const neighborVectors = nodeGraph[vertex].map(neighbor => vec3.subtract([], mesh.positions[neighbor], curPt))\n for (const vec of neighborVectors) {\n vec3.scaleAndAdd(vertexNormal, vertexNormal, vec, 1 / neighborCount)\n }\n vec3.normalize(vertexNormal, vertexNormal)\n const nonZeroDots = neighborVectors.map(vec => vec3.dot(vec, vertexNormal)).filter(d => d !== 0)\n const greaterThanZeroDots = nonZeroDots.map(d => d > 0)\n // if the dot products of the average vector with all the vectors have the same sign, the points are on the \"same side\" and it is concave\n const isConcaveVertex = greaterThanZeroDots.length === 0 || greaterThanZeroDots.length === nonZeroDots.length\n if (!isConcaveVertex) continue\n let shortestNormal = null\n let shortestNormalLength = Infinity\n for (const vec of neighborVectors) {\n if (vec3.squaredLength(vec) < shortestNormalLength) {\n shortestNormalLength = vec3.squaredLength(vec)\n shortestNormal = vec\n }\n }\n const cutLeng = vec3.dot(vertexNormal, vec3.scale([], shortestNormal, cutDepth))\n const pointOnPlane = vec3.scaleAndAdd([], curPt, vertexNormal, cutLeng)\n const planeNormal = vertexNormal\n clippingPlanes.push({ pointOnPlane, planeNormal })\n }\n for (const { planeNormal, pointOnPlane } of clippingPlanes) {\n // TODO: alter this mesh so it just has the related cells to cut (we don't want to accidentally cut other parts of the mesh here)\n const [mesh1, mesh2] = clipMeshWithPlane(mesh, planeNormal, pointOnPlane)\n mesh = mesh1 // mesh1.cells.length > mesh2.cells.length ? mesh1 : mesh2\n }\n return mesh\n}", "collapseAdjacentEdges() {\n let needsLoop = true;\n while (needsLoop) {\n needsLoop = false;\n for (let i = 0; i < this.vertices.length; i++) {\n const vertex = this.vertices[i];\n if (vertex.incidentHalfEdges.length === 2) {\n const aEdge = vertex.incidentHalfEdges[0].edge;\n const bEdge = vertex.incidentHalfEdges[1].edge;\n let aSegment = aEdge.segment;\n let bSegment = bEdge.segment;\n const aVertex = aEdge.getOtherVertex(vertex);\n const bVertex = bEdge.getOtherVertex(vertex);\n assert && assert(this.loops.length === 0);\n\n // TODO: Can we avoid this in the inner loop?\n if (aEdge.startVertex === vertex) {\n aSegment = aSegment.reversed();\n }\n if (bEdge.endVertex === vertex) {\n bSegment = bSegment.reversed();\n }\n if (aSegment instanceof Line && bSegment instanceof Line) {\n // See if the lines are collinear, so that we can combine them into one edge\n if (aSegment.tangentAt(0).normalized().distance(bSegment.tangentAt(0).normalized()) < 1e-6) {\n this.removeEdge(aEdge);\n this.removeEdge(bEdge);\n aEdge.dispose();\n bEdge.dispose();\n js_arrayRemove(this.vertices, vertex);\n vertex.dispose();\n const newSegment = new Line(aVertex.point, bVertex.point);\n this.addEdge(new ops_Edge(newSegment, aVertex, bVertex));\n needsLoop = true;\n break;\n }\n }\n }\n }\n }\n }", "disableCornerCutting() {\n this.allowCornerCutting = false;\n }", "enableCornerCutting() {\n this.allowCornerCutting = true;\n }", "function remove_edges(startX, startY, endX, endY, startID, endID) {\n //remove edge drawing\n contextPerm.globalCompositeOperation = \"xor\";\n contextPerm.beginPath();\n contextPerm.moveTo(startX, startY);\n contextPerm.lineTo(endX, endY);\n contextPerm.lineWidth = 4;\n contextPerm.strokeStyle = 'white';\n contextPerm.stroke();\n contextPerm.closePath();\n contextPerm.globalCompositeOperation = \"source-over\";\n\n //draw nodes over where line was erased\n contextPerm.beginPath();\n contextPerm.arc(startX, startY, radius, 0, 2 * Math.PI);\n contextPerm.fillStyle = colorFind(startID, false);\n contextPerm.fill();\n contextPerm.lineWidth = 1;\n contextPerm.strokeStyle = colorFind(startID, false);\n contextPerm.stroke();\n contextPerm.closePath();\n\n contextPerm.beginPath();\n contextPerm.arc(endX, endY, radius, 0, 2 * Math.PI);\n contextPerm.fillStyle = colorFind(endID, false);\n contextPerm.fill();\n contextPerm.strokeStyle = colorFind(endID, false);\n contextPerm.stroke();\n contextPerm.closePath();\n}", "removeEdge(g,e){\n\n }", "function cutWedge(wedge, low, high) {\n // istanbul ignore next\n if (DEBUG_CUTWEDGE) {\n debugLog(`cut ${wedgeToString(wedge)} ${rangeToString(low, high)}`);\n }\n let ret;\n if (low <= wedge.low) {\n if (high >= wedge.high) {\n // wedge is entirely occluded, remove it\n ret = [];\n }\n else if (high >= wedge.low) {\n // low part of wedge is occluded, trim it\n wedge.low = high;\n ret = [wedge];\n }\n else {\n // cut doesn't reach the wedge\n ret = [wedge];\n }\n }\n else if (high >= wedge.high) {\n if (low <= wedge.high) {\n // high part of wedge is occluded, trim it\n wedge.high = low;\n ret = [wedge];\n }\n else {\n // cut doesn't reach the wedge\n ret = [wedge];\n }\n }\n else {\n // middle part of wedge is occluded, split it\n const nextWedge = {\n low: high,\n high: wedge.high,\n };\n wedge.high = low;\n ret = [wedge, nextWedge];\n }\n // istanbul ignore next\n if (DEBUG_CUTWEDGE) {\n debugLog(`--> ${wedgesToString(ret)}`);\n }\n return ret;\n}", "function cutProblem(pointsToCut) {\n\n // sort array by y coordinate\n pointsToCut.sort(function (a, b) {\n return b[1] - a[1];\n });\n\n // we draw an horizontal line every 2 points\n // I count ghosts and ghostbusters above the line\n // If I have the same number of ghost and ghostbuster, I can cut it\n // pointsToCut.length - 2 : no need to test the last couple of points\n // it is always true, but it does not solve our problem\n var numGhost = 0;\n var numHunter = 0;\n for (var i = 0; i < pointsToCut.length - 2; i += 2) {\n if (pointsToCut[i][2] == 0) {\n numGhost++; // one more ghost\n } else {\n numHunter++; // one more ghostHunter\n }\n\n if (pointsToCut[i + 1][2] == 0) {\n numGhost++; // one more ghost\n } else {\n numHunter++; // one more ghostHunter\n }\n\n if (numGhost == numHunter) {\n // I find my line\n break;\n }\n }\n\n // We can cut the plane here\n // index of the first point to wait for calculation\n var tempIndex = i + 2;\n\n // Note: we can have a problem, if the next point e.g. pointsToCut[i+1] have the same Y that pointsToCut[i]\n // in this case the points are aligned and we can not accept the solution.\n // amelioration: if it does not works change orientation of the line\n\n // another subset scan\n gCurrentSubset++;\n\n // Y of the line we draw on the screen. The Y is between the last point and the next one\n var yLine = pointsToCut[tempIndex][1] + (pointsToCut[tempIndex - 1][1] - pointsToCut[tempIndex][1]) / 2;\n // we save the Y value of the line\n gLinesCut.push(yLine);\n\n // we mark the points that we do not scan\n for (i = tempIndex; i < pointsToCut.length; i++) {\n pointsToCut[i].fl = 2 + gCurrentSubset;\n }\n\n // we return the points that we can use for graham scan\n var tempArray = [];\n\n for (i = 0; i < pointsToCut.length; i++) {\n if (pointsToCut[i].fl == 0) {\n tempArray.push(pointsToCut[i]);\n }\n }\n return (tempArray);\n\n\n }", "junction() {\n if(this.graph.unclean) { this.graph.clean(); }\n return this.graph.junctions.slice().filter(function(junction) {\n return junction.origin === this;\n },this).shift();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete all of the listings created by this user
async deleteMany(req, res) { const { userId } = req.query; const deletedListings = await Listing.remove({ publisher_id: { $in: [userId] }, }); res.send(deletedListings); }
[ "function deleteAllAnimeFromUserList() {\n db.transaction((tx) => {\n tx.executeSql(\"delete from userlist\", [], () => {\n console.log(\"useDB: Deleted all anime from userlist in database!\");\n });\n });\n dispatch(clearUserData());\n }", "function deleteFromListing() {\n var $programRow = $('#programNameTable .selected');\n var progs = [];\n for (var i = 0; i < $programRow.length; i++) {\n progs.push({\n name : $programRow[i].children[0].textContent,\n owner : $programRow[i].children[1].textContent\n });\n }\n for (var i = 0; i < progs.length; i++) {\n var prog = progs[i];\n LOG.info('deleteFromList ' + prog.name + ' signed in: ' + userState.id);\n if (prog.owner === userState.accountName) {\n PROGRAM.deleteProgramFromListing(prog.name, function(result, progName) {\n UTIL.response(result);\n if (result.rc === 'ok') {\n MSG.displayInformation(result, \"MESSAGE_PROGRAM_DELETED\", result.message, progName);\n PROGRAM.refreshList(showPrograms);\n }\n });\n } else {\n PROGRAM.deleteShare(prog.name, prog.owner, function(result, progName) {\n UTIL.response(result);\n if (result.rc === 'ok') {\n MSG.displayInformation(result, \"MESSAGE_PROGRAM_DELETED\", result.message, progName);\n PROGRAM.refreshList(showPrograms);\n }\n });\n }\n }\n $('.modal').modal('hide');\n }", "deleteAll() {\n realm.write(() => {\n const user = realm.objects('User');\n realm.delete(user);\n });\n }", "function deleteAll() {\n localStorage.clear()\n leads = []\n render(leads)\n}", "function deletingUsers() {\n deleteUserBtns = document.querySelectorAll('.get-users__delete');\n deleteUserBtns.forEach(elem => {\n elem.addEventListener('click', function() {\n let li = elem.closest('li');\n let login = li.innerText;\n if (users.indexOf(login) >= 0) {\n users.splice(users.indexOf(login), 1);\n }\n li.remove();\n // console.log(users);\n });\n });\n }", "function deleteListing(req, res) {\r\n pool.query(`DELETE FROM herkbath.listings WHERE listings_id = ${req.params.id}`, (err, listings) => {\r\n if (err) {\r\n res.sendStatus(500);\r\n } else {\r\n res.header('Content-Type', 'application/json');\r\n res.sendStatus(204);\r\n }\r\n });\r\n}", "function removeListing(i) {\r\n listings[i].ref.remove();\r\n}", "function deleteList() {\n var WELCOME_SPREADSHEET_ID = '1GD5UBfEcWwxopL3pS7t4MIjFWFzk_NsPXT24T1JxVa8';\n var NAMES_AND_USERNAMES_SHEET_NAME = 'NamesAndUserNames';\n \n var welcomeSpreadsheet = SpreadsheetApp.openById(WELCOME_SPREADSHEET_ID);\n // Clears all values and formatting from the sheet.\n var namesAndUsernamesSheet = welcomeSpreadsheet.getSheetByName(NAMES_AND_USERNAMES_SHEET_NAME);\n namesAndUsernamesSheet.clear();\n namesAndUsernamesSheet.getBandings().forEach(function (banding) {\n banding.remove();\n });\n}", "function deleteUserFromList(deleteUser){\n\t\tvar userToDelete;\n\t\tfor(var i = 0; i< userlist.length; i++){\n\t\t\tuserToDelete = userlist[i]\n\t\t\tif(userToDelete==deleteUser){\n\t\t\t\tuserlist.splice(i,1);\n\t\t\t}\n\t\t}\n\t}", "removeAll(req, res) {\n const userId = req.session.user.id;\n Location.destroy({\n where: { userId },\n })\n .then((response) => {\n // Remove all locations from session\n let newUser = {\n ...req.session.user,\n locations: [],\n };\n req.session.user = newUser;\n res.sendStatus(200);\n })\n .catch((err) => {\n res.send(err);\n });\n }", "function deleteList()\n{\n\tremoveAllGrocery(deleteListCallback);\n}", "function clearUserList() {\n // delete all user names\n $('#users tbody tr').remove();\n}", "function purgeUsers(){\n\tfor(var courseName in queues) {\n \tconsole.log(queues[courseName].courseData.name);\n \tqueues[courseName].courseData.queue.forEach(function (user) {\n\t\tconsole.log(user.name);\n\t\t\tremoveUser(courseName, user);\n\t\t})\n\t}\n}", "async deleteAll() {\n try {\n await this.connection('user_musics').delete();\n } catch (error) {\n throw error;\n }\n }", "function clear() {\n listings = [ ];\n}", "function removeUserFromList(user, manual_remove=false) {\n console.log(\"removeUserFromList:\" + user);\n $(\"a.user[user='\"+ user +\"']\").parent().remove();\n console.log(users);\n var user_index = users.indexOf(parseInt(user))\n users.splice(user_index, 1);\n console.log(\"Users list after remove: \" + user);\n // if currentRecipient leaves the room, you can't write anymore\n if (user == currentRecipient){\n //if (!manual_remove) {\n //drawMessage(message=\"L'utente ha abbandonato la chat\",\n //user_fullname='BOT',\n //from_bot=true);\n //messageList.animate({scrollTop: messageList.prop('scrollHeight')});\n //}\n disableInput();\n }\n //currentRecipient = null;\n console.log(users);\n}", "optOutTrackingAndDeleteUser() {\n var time = new Date();\n this._sendRequest({ type: 'user_del' }, time);\n this.optOutTracking();\n }", "function deleteUserFromUserList(sNick){\n\n\t// find and delete\n\tfor (let i = userList.length - 1; i >= 0; i--) {\n\t\tif (userList[i] === sNick) {\n\t\t\tuserList.splice(i, 1);\n\t\t\t// break; //<-- Uncomment if only the first term has to be removed\n\t\t}\n\t}\n\tio.emit(\"update users list\", userList);\n\n}", "function removeListingOrphans() {\n var starListing, prospect;\n starListing = shl.Listing.find({\n all: true,\n order: 'id DESC'\n });\n if (starListing.length > 0) {\n for (id in starListing) {\n Ti.API.info('Listing = ' + JSON.stringify(starListing[id]));\n if (starListing[id].id != null) {\n prospect = shl.Prospect.find(starListing[id].prospect_id);\n if (prospect == false) {\n starListing[id].destroy();\n }\n }\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
xTable, Copyright 2007 Michael Foster (CrossBrowser.com) Part of X, a CrossBrowser Javascript Library, Distributed under the terms of the GNU LGPL
function xTable(sTableId, sRoot, sCC, sFR, sFRI, sRCell, sFC, sFCI, sCCell, sTC, sCellT) { var i, ot, cc=null, fcw, frh, root, fr, fri, fc, fci, tc; var e, t, tr, a, alen, tmr=null; ot = xGetElementById(sTableId); // original table if (!ot || !document.createElement || !document.appendChild || !ot.deleteCaption || !ot.deleteTHead) { return null; } fcw = xWidth(ot.rows[1].cells[0]); // get first column width before altering ot frh = xHeight(ot.rows[0]); // get first row height before altering ot root = document.createElement('div'); // overall container root.className = sRoot; fr = document.createElement('div'); // frozen-row container fr.className = sFR; fri = document.createElement('div'); // frozen-row inner container, for column headings fri.className = sFRI; fr.appendChild(fri); root.appendChild(fr); fc = document.createElement('div'); // frozen-column container fc.className = sFC; fci = document.createElement('div'); // frozen-column inner container, for row headings fci.className = sFCI; fc.appendChild(fci); root.appendChild(fc); tc = document.createElement('div'); // table container, contains ot tc.className = sTC; root.appendChild(tc); if (ot.caption) { cc = document.createElement('div'); // caption container cc.className = sCC; cc.appendChild(ot.caption.firstChild); // only gets first child root.appendChild(cc); ot.deleteCaption(); } // Create fr cells (column headings) a = ot.rows[0].cells; alen = a.length; for (i = 1; i < alen; ++i) { e = document.createElement('div'); e.className = sRCell; t = document.createElement('table'); t.className = sCellT; tr = t.insertRow(0); tr.appendChild(a[1]); e.appendChild(t); fri.appendChild(e); } if (ot.tHead) { ot.deleteTHead(); } // Create fc cells (row headings) a = ot.rows; alen = a.length; for (i = 0; i < alen; ++i) { e = document.createElement('div'); e.className = sCCell; t = document.createElement('table'); t.className = sCellT; tr = t.insertRow(0); tr.appendChild(a[i].cells[0]); e.appendChild(t); fci.appendChild(e); } ot = ot.parentNode.replaceChild(root, ot); tc.appendChild(ot); resize(); root.style.visibility = 'visible'; xAddEventListener(tc, 'scroll', onScroll, false); xAddEventListener(window, 'resize', onResize, false); function onScroll() { xLeft(fri, -tc.scrollLeft); xTop(fci, -tc.scrollTop); } function onResize() { if (!tmr) { tmr = setTimeout( function() { resize(); tmr=null; }, 500); } } function resize() { var sum = 0, cch = 0, w, h; // caption container if (cc) { cch = xHeight(cc); xMoveTo(cc, 0, 0); xWidth(cc, xWidth(root)); } // frozen row xMoveTo(fr, fcw, cch); xResizeTo(fr, xWidth(root) - fcw, frh); xMoveTo(fri, 0, 0); xResizeTo(fri, xWidth(ot), frh); // frozen col xMoveTo(fc, 0, cch + frh); xResizeTo(fc, fcw, xHeight(root) - cch); xMoveTo(fci, 0, 0); xResizeTo(fci, fcw, xHeight(ot)); // table container xMoveTo(tc, fcw, cch + frh); xWidth(tc, xWidth(root) - fcw - 1); xHeight(tc, xHeight(root) - cch - frh - 1); // size and position fr cells a = ot.rows[0].cells; e = xFirstChild(fri, 'div'); for (i = 0; i < a.length; ++i) { xMoveTo(e, sum, 0); w = xWidth(e, xWidth(a[i])); h = xHeight(e, frh); sum += w; xResizeTo(xFirstChild(e, 'table'), w, h);////////// e = xNextSib(e, 'div'); } // size and position fc cells sum = 0; a = ot.rows; e = xFirstChild(fci, 'div'); for (i = 0; i < a.length; ++i) { xMoveTo(e, 0, sum); w = xWidth(e, fcw); h = xHeight(e, xHeight(a[i])); sum += h; xResizeTo(xFirstChild(e, 'table'), w, h);////////// e = xNextSib(e, 'div'); } onScroll(); } // end resize } // end xTable
[ "function renderTable(extElement) {\n\n var createClickHandler =\n function (rowIndex) {\n return function () {\n extElement.Data.SelectRow(rowIndex);\n };\n };\n\n // Data.SelectValuesInColumn(columnIdx, values, toggle, isFinal)\n var createClickHandler2 =\n function (colIdx, values) {\n return function () {\n extElement.Data.SelectTextsInColumn(colIdx, true, values)\n }\n }\n\n while (extElement.Element.firstChild) extElement.Element.removeChild(extElement.Element.firstChild);\n var mytable = document.createElement(\"table\");\n mytable.style.width = \"100%\";\n var noCols = extElement.Data.HeaderRows[0].length;\n var tablebody = document.createElement(\"tbody\");\n for (var r = 0; r < extElement.Data.HeaderRows.length; r++) {\n var row = document.createElement(\"tr\");\n for (var c = 0; c < noCols; c++) {\n var cell = document.createElement(\"td\");\n cell.innerHTML = extElement.Data.HeaderRows[r][c].text;\n row.appendChild(cell);\n }\n tablebody.appendChild(row);\n }\n for (var r = 0; r < extElement.Data.Rows.length; r++) {\n var row = document.createElement(\"tr\");\n for (var c = 0; c < noCols; c++) {\n var cell = document.createElement(\"td\");\n\n var cellValue = extElement.Data.Rows[r][c].text;\n cell.innerHTML = cellValue;\n //cell.innerHTML = extElement.Data.Rows[r][c].text;\n\n //cell.onclick = createClickHandler(r);\n cell.onclick = createClickHandler2(c, cellValue);\n\n row.appendChild(cell);\n }\n tablebody.appendChild(row);\n }\n mytable.appendChild(tablebody);\n extElement.Element.appendChild(mytable);\n}", "function insertXHeader() {\n var xrow = table.insertRow(0),\n xhead = xrow.insertCell(0);\nxhead.setAttribute('class', 'headings');\nxhead.innerHTML = document.getElementsByTagName('tspan')[2].innerHTML;\nxhead.colSpan = ncol;\n}", "function activateCrossTable (divId, xtab)\n{\n var gho_client = document.getElementById(divId);\n if (gho_client == null) {\n throw \"Crosstable container \\\"\" + divId + \"\\\" div not found.\";\n }\n\n var crosstable = document.getElementById(\"crosstable\");\n if (crosstable == null) {\n throw \"Source crosstable not found.\";\n }\n\n /*\n * calculate the size of the bounding box that encompasses the pivot cells\n * The width and height are initially set to 1 and increased by 1 additional\n * pixel at every step to account for a one pixel border around the cell.\n */\n\n var pivotcell_width = 1;\n var pivotcell_height = 1;\n var pivotcell = document.getElementById(\"pivotcell\");\n if (pivotcell != null) {\n pivotcell_height += pivotcell.clientHeight + 1;\n }\n for (var q = 0; q < 10; q++) {\n var pc = document.getElementById(\"pivotcell_\" + q);\n if (pc != null) {\n pivotcell_width += pc.clientWidth + 1;\n if (q == 0) {\n pivotcell_height += pc.clientHeight + 1;\n }\n } else {\n break;\n }\n }\n\n crosstable.style.position = \"absolute\";\n crosstable.style.top = \"0px\";\n crosstable.style.backgroundColor = \"#FFFFFF\";\n crosstable.style.width = gho_client.clientWidth + \"px\"; \n crosstable.firstChild.style.width = gho_client.clientWidth + \"px\"; \n\n var controls = document.createElement(\"DIV\");\n controls.id = \"crosstable_controls\";\n controls.className = \"controls\";\n controls.style.overflow = \"hidden\";\n controls.style.position = \"absolute\";\n controls.style.top = \"0px\";\n\n //var ctrl_html = \"<a href=\\\"javascript:filterShow();\\\">filter table</a> | <a href=\\\"javascript:filterClear();filterApply();\\\">reset table</a> | <a href=\\\"javascript:mxtb_activate('\" + divId + \"')\\\">Mobile view</a>\";\n // var ctrl_html = \"<a href=\\\"javascript:filterShow();\\\">filter table</a> | <a href=\\\"javascript:filterClear();filterApply();\\\">reset table</a> | \";\n var ctrl_html = \"<fieldset class=\\\"buttonbar\\\"><ul>\";\n ctrl_html += \"<li><a href=\\\"#\\\" onclick=\\\"filterShow()\\\">Filter table</a></li>\";\n ctrl_html += \"<li> | <li>\";\n ctrl_html += \"<li><a href=\\\"#\\\" onclick=\\\"filterClear();filterApply()\\\">Reset table</a></li>\";\n ctrl_html += \"<li> | <li>\";\n\n ctrl_html += \"<li>\" + mkCompleteDownloadDropdown(xtab) + \"</li>\";\n ctrl_html += \"<li> | <li>\";\n if (BlobCheck()) {\n ctrl_html += \"<li><select onchange=\\\"downloadData(this.value);this.selectedIndex=0;\\\">\";\n ctrl_html += \"<option selected=\\\"selected\\\" disabled=\\\"disabled\\\" value=\\\"\\\">Download this table</option>\";\n ctrl_html += \"<option value=\\\"csv\\\">CSV Crosstable</option>\";\n ctrl_html += \"<option value=\\\"xml\\\">Simplified XML</option>\";\n ctrl_html += \"<option value=\\\"json\\\">Simplified JSON</option>\";\n ctrl_html += \"</select></li>\";\n\n// ctrl_html += \" | <a class=\\\"control\\\" href=\\\"javascript:downloadData('csv')\\\">CSV table</a> | <a href=\\\"javascript:downloadData('xml')\\\">XML (simple)</a> | <a href=\\\"javascript:downloadData('json')\\\">JSON (simple)</a>\";\n } else {\n ctrl_html += \"Update your browser to the latest version to download filtered table data\";\n }\n ctrl_html += \"</ul></fieldset>\";\n controls.innerHTML = ctrl_html;\n gho_client.appendChild(controls);\n\n crosstable.style.top = controls.clientHeight + \"px\";\n \n var crosstable_horizontal_axis = crosstable.cloneNode(true);\n crosstable_horizontal_axis.style.zIndex = 900;\n crosstable_horizontal_axis.id = \"crosstable_horizontal_axis\";\n crosstable_horizontal_axis.style.overflow = \"hidden\";\n crosstable_horizontal_axis.style.top = controls.clientHeight + \"px\";\n gho_client.appendChild(crosstable_horizontal_axis);\n\n var crosstable_vertical_axis = crosstable.cloneNode(true);\n crosstable_vertical_axis.style.zIndex = 900;\n crosstable_vertical_axis.id = \"crosstable_vertical_axis\";\n crosstable_vertical_axis.style.overflow = \"hidden\";\n crosstable_vertical_axis.style.top = controls.clientHeight + \"px\";\n gho_client.appendChild(crosstable_vertical_axis);\n\n// Create the pivot cell for the table - this will be the top left\n// corner - it doesnt move when the axes/table are scrolled\n//\n var crosstable_pivotcell = crosstable.cloneNode(true);\n crosstable_pivotcell.id = \"crosstable_pivotcell\"\n crosstable_pivotcell.style.position = \"absolute\";\n crosstable_pivotcell.style.overflow = \"hidden\";\n crosstable_pivotcell.style.top = controls.clientHeight + \"px\";\n crosstable_pivotcell.style.zIndex = 1000;\n crosstable_pivotcell.style.width = pivotcell_width + \"px\";\n crosstable_pivotcell.style.height = pivotcell_height + \"px\"; \n gho_client.appendChild(crosstable_pivotcell);\n\n\n\n var viewHeight = gho_client.clientHeight;\n\n\n// Construct the details box to show footnotes and additional\n// metadata for a given fact. Height is fixed, but the width\n// is variable based on available space.\n\n var detail = document.createElement(\"div\");\n detail.style.height = \"200px\";\n detail.style.width = (gho_client.clientWidth * 4 / 5) + \"px\";\n detail.id = \"crosstable_detail\";\n detail.style.overflowY = \"hidden\";\n detail.style.overflowX = \"hidden\";\n detail.style.position = \"fixed\";\n detail.style.zIndex = \"3500\";\n detail.style.display = \"none\";\n gho_client.appendChild(detail);\n\n /*\n * The width and height of the headers are increased by 2 pixels to also include\n * the borders\n */\n\n //crosstable.style.height = (gho_client.clientHeight - controls.clientHeight) + \"px\";\n crosstable.style.width = gho_client.clientWidth + \"px\";\n crosstable_pivotcell.style.height = pivotcell_height + \"px\";\n crosstable_pivotcell.style.width = pivotcell_width + \"px\";\n crosstable_horizontal_axis.style.height = pivotcell_height + \"px\";\n crosstable_horizontal_axis.style.width = gho_client.clientWidth + \"px\";\n crosstable_vertical_axis.style.width = pivotcell_width + \"px\";\n// crosstable_vertical_axis.style.height = (gho_client.clientHeight - controls.clientHeight) + \"px\";\n\n // Create the navigation arrows that will allow the user to slide the table left \n // and right. The arrows will only appear when the mouse cursor is inside the \n // crosstable.\n\n var right_arrow = document.createElement(\"DIV\");\n right_arrow.id = \"arrow_right\";\n right_arrow.className = \"scroll right\";\n right_arrow.style.float = \"right\";\n right_arrow.style.left = (gho_client.clientWidth - 49) + \"px\";\n\n var left_arrow = document.createElement(\"DIV\");\n left_arrow.id = \"arrow_left\";\n left_arrow.className = \"scroll left\";\n left_arrow.style.float = \"left\";\n //left_arrow.style.left = \"inherit\";\n\n/*\n var arrows = document.createElement(\"DIV\");\n arrows.id = \"arrows\";\n arrows.style.top = \"300px\";\n arrows.style.width = gho_client.clientWidth + \"px\";\n arrows.className = \"scroll arrows\";\n arrows.appendChild(left_arrow);\n arrows.appendChild(right_arrow);\n gho_client.appendChild(arrows);\n*/\n gho_client.appendChild(left_arrow);\n gho_client.appendChild(right_arrow);\n\n // Position the horizontal scroll arrows so that they appear centered between \n // the bottom of the horizontal axis, and the bottom edge of the table, if\n // visible, or the bottom of the viewport if the table extends beyond it.\n\n var h = window.innerHeight ||\n document.documentElement.clientHeight ||\n document.body.clientHeight;\n var r_xt = crosstable.getBoundingClientRect(); \n var r_cha = crosstable_horizontal_axis.getBoundingClientRect();\n var bottom = Math.min((r_xt.bottom),h);\n// var bottom = Math.min((r_xt.top + r_xt.y),h);\n// arrows.style.top = (top + Math.max((bottom - top - arrows.clientHeight)/2,0) ) + \"px\";\n left_arrow.style.top = (r_cha.top + Math.max((bottom - left_arrow.clientHeight)/2,0) ) + \"px\";\n// left_arrow.style.left = r_xt.x + \"px\";\n left_arrow.style.left = r_xt.left + \"px\";\n right_arrow.style.top = (r_cha.top + Math.max((bottom - right_arrow.clientHeight)/2,0) ) + \"px\";\n //right_arrow.style.left = (r_xt.x + r_xt.width - 49) + \"px\";\n right_arrow.style.left = (r_xt.right - 49) + \"px\";\n\n // Show the arrows when the mouse cursor is in the crosstable\n\n gho_client.onmouseover = function() {\n left_arrow.style.display = \"block\";\n right_arrow.style.display = \"block\";\n };\n\n gho_client.onmouseout = function() {\n left_arrow.style.display = \"none\";\n right_arrow.style.display = \"none\";\n };\n\n // Slide the cross table to the left when the user clicks and holds down\n // the mouse over the left arrow\n\n left_arrow.onmousedown = function() {\n var pid = setInterval(function() {\n var p = Math.max(0,crosstable.scrollLeft - 10);\n crosstable.scrollLeft = p;\n crosstable_horizontal_axis.scrollLeft = p;\n },25);\n left_arrow.onmouseup = function() {\n clearInterval(pid);\n }\n };\n\n // Slide the cross table to the right when the user clicks and holds down\n // the mouse over the right arrow\n\n right_arrow.onmousedown = function() {\n var pid = setInterval(function() {\n var p = Math.min(gho_client.clientWidth,crosstable.scrollLeft + 10);\n crosstable.scrollLeft = p;\n crosstable_horizontal_axis.scrollLeft = p;\n },25);\n right_arrow.onmouseup = function() {\n clearInterval(pid);\n }\n };\n\n}", "function TTtable(id, data, objects, keys, rowTitles, tableTitle, titles, split){\n var i, j, k, n, nContentRows, cellContent;\n\n injectDOM('table', id+'table', id, {'class':'TTtab', 'style':'border-collapse:collapse'});\n injectDOM('colgroup', id+'colgroup', id+'table', {});\n for(i=0; i<split.length-1; i++){\n injectDOM('col', id+'colSpace'+i, id+'colgroup', {'span':keys.length+1});\n injectDOM('col', id+'col'+i, id+'colgroup', {'style':'border-left:1px solid white;', 'span':'1'});\n }\n\n\n if(tableTitle != ''){\n injectDOM('tr', id+'tableTitleRow', id+'table', {});\n injectDOM('td', id+'tableTitle', id+'tableTitleRow', {'innerHTML':tableTitle, 'colspan':(1+keys.length)*split.length});\n }\n\n injectDOM('tr', id+'tableHeaderRow', id+'table', {});\n for(k=0; k<split.length; k++){\n for(j=0; j<titles.length; j++){\n injectDOM('td', id+'headerCell'+j+'col'+k, id+'tableHeaderRow', {\n 'style' : 'padding-left:'+( (j==0 && k!=0) ? 25:10 )+'px; padding-right:'+( (j==titles.length-1) ? 25:10 )+'px;',\n 'innerHTML' : titles[j]\n });\n }\n }\n \n nContentRows = Math.max.apply(null, split);\n\n //build table:\n for(i=0; i<nContentRows; i++){\n //rows\n injectDOM('tr', id+'row'+i, id+'table', {});\n //cells\n for(j=0; j<titles.length*split.length; j++){\n injectDOM('td', id+'row'+i+'cell'+j, id+'row'+i, {\n 'style' : 'padding:0px; padding-right:'+( (j%(titles.length+1)==0 && j!=0) ? 25:10 )+'px; padding-left:'+( (j%titles.length == 0 && j!=0) ? 25:10 )+'px'\n });\n //if(j%(keys.length+1)==keys.length && j!=titles.length*split.length-1 ){\n // document.getElementById(id+'row'+i+'cell'+j).setAttribute('style', 'border-right:1px solid white');\n //}\n }\n }\n\n //fill table:\n n=0;\n\n for(i=0; i<split.length; i++){\n for(j=0; j<split[i]; j++){\n document.getElementById(id+'row'+j+'cell'+(titles.length*i)).innerHTML = rowTitles[n];\n for(k=0; k<keys.length; k++){\n\n if(typeof data[objects[n]][keys[k]] == 'string')\n cellContent = data[objects[n]][keys[k]];\n else\n cellContent = data[objects[n]][keys[k]].toFixed(window.parameters.tooltipPrecision);\n if(cellContent == 0xDEADBEEF) cellContent = '0xDEADBEEF'\n document.getElementById(id+'row'+j+'cell'+(1+titles.length*i+k)).innerHTML = cellContent;\n }\n n++;\n }\n }\n\n}", "function Table() {}", "function createjQueryGraphicsTable() {\n return \"<table style=\\\"width: 100%\\\" id=\\\"androidtable\\\" class=\\\"tablesorter\\\"><thead>\t<tr>\\n\" +\n\"\t\t<th class=\\\"header\\\">Name</th>\\n\" +\n\"\t\t<th class=\\\"header\\\">enathu</th>\\n\" +\n\"\t\t<th class=\\\"header\\\">jjoe64</th>\\n\" +\n\"\t\t<th class=\\\"header\\\">zeickan</th>\\n\" +\n\"\t\t<th class=\\\"header\\\">vezquex</th>\\n\" +\n\"\t\t<th class=\\\"header\\\">zmyaro</th>\\n\" +\n\"\t</tr>\\n\" +\n\"</thead><tbody>\t<tr>\\n\" +\n\"\t\t<td>Dark</td>\\n\" +\n createCrossCheckTd(false,true,false,true,true) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Light</td>\\n\" +\n createCrossCheckTd(true,true,true,true,true) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Button</td>\\n\" +\n createCrossCheckTd(true,true,true,true,true) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Text field</td>\\n\" +\n createCrossCheckTd(true,true,true,true,false) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Checkbox</td>\\n\" +\n createCrossCheckTd(true,true,false,true,true) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Radio button</td>\\n\" +\n createCrossCheckTd(true,true,false,true,true) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Slider</td>\\n\" +\n createCrossCheckTd(true,true,true,false,false) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Toggle button</td>\\n\" +\n createCrossCheckTd(true,true,true,true,false) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Text</td>\\n\" +\n createCrossCheckTd(true, true, true, true, true) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Tabs</td>\\n\" +\n createCrossCheckTd(false,false,true,true,false) +\n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Drop down</td>\\n\" +\n createCrossCheckTd(true,true,false,true,true) + \n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Screenshot</td>\\n\" +\n createScreenshotTd(\"enathu\", \"jjoe64\", \"zeickan\", \"vezquex\", \"zmyaro\") + \n\"\t</tr>\\n\" +\n\"\t<tr>\\n\" +\n\"\t\t<td>Download</td>\\n\" +\n createDownloadTd(\"https://github.com/enathu/jqmobile-android-holo-light-theme\", \"https://github.com/jjoe64/jquery-mobile-android-theme\", \"https://github.com/zeickan/Holo-Holo-Theme\", \"http://vezquex.com/projects/holo-css/index.html\", \"https://github.com/zmyaro/holo-web\") +\n\"\t</tr>\\n\" +\n\"</tbody></table>\";\n}", "function xTableHeaderFixed(fixedContainerId, fixedTableClass, fakeBodyId, tableBorder, thBorder)\r\n{\r\n // Private Property\r\n var tables = [];\r\n // Private Event Listener\r\n function onEvent(e) // handles scroll and resize events\r\n {\r\n e = e || window.event;\r\n var r = e.type == 'resize' ? true : false;\r\n for (var i = 0; i < tables.length; ++i) {\r\n scroll(tables[i], r);\r\n }\r\n }\r\n // Private Methods\r\n function scroll(t, bResize)\r\n {\r\n if (!t) { return; }\r\n var fhc = xGetElementById(fixedContainerId); // for IE6\r\n var fh = xGetElementById(t.fixedHeaderId);\r\n var thead = t.tHead;\r\n var st, sl, thy = xPageY(thead);\r\n /*@cc_on\r\n @if (@_jscript_version == 5.6) // IE6\r\n st = xGetElementById(fakeBodyId).scrollTop;\r\n sl = xGetElementById(fakeBodyId).scrollLeft;\r\n @else @*/\r\n st = xScrollTop();\r\n sl = xScrollLeft();\r\n /*@end @*/\r\n var th = xHeight(t);\r\n var tw = xWidth(t);\r\n var ty = xPageY(t);\r\n var tx = xPageX(t);\r\n var fhh = xHeight(fh);\r\n if (bResize) {\r\n xWidth(fh, tw + 2*tableBorder);\r\n var th1 = xGetElementsByTagName('th', t);\r\n var th2 = xGetElementsByTagName('th', fh);\r\n for (var i = 0; i < th1.length; ++i) {\r\n xWidth(th2[i], xWidth(th1[i]) + thBorder);\r\n }\r\n }\r\n xLeft(fh, tx - sl);\r\n if (st <= thy || st > ty + th - fhh) {\r\n if (fh.style.visibility != 'hidden') {\r\n fh.style.visibility = 'hidden';\r\n fhc.style.visibility = 'hidden'; // for IE6\r\n }\r\n }\r\n else {\r\n if (fh.style.visibility != 'visible') {\r\n fh.style.visibility = 'visible';\r\n fhc.style.visibility = 'visible'; // for IE6\r\n }\r\n }\r\n }\r\n function init()\r\n {\r\n var i, tbl, h, t, con;\r\n if (null == (con = xGetElementById(fixedContainerId))) {\r\n con = document.createElement('div');\r\n con.id = fixedContainerId;\r\n document.body.appendChild(con);\r\n }\r\n for (i = 0; i < tables.length; ++i) {\r\n tbl = tables[i];\r\n h = tbl.tHead;\r\n if (h) {\r\n t = document.createElement('table');\r\n t.className = fixedTableClass;\r\n t.appendChild(h.cloneNode(true));\r\n t.id = tbl.fixedHeaderId = 'xtfh' + i;\r\n con.appendChild(t);\r\n }\r\n else {\r\n tables[i] = null; // ignore tables with no thead\r\n }\r\n }\r\n con.style.visibility = 'hidden'; // for IE6\r\n }\r\n // Public Method\r\n this.unload = function()\r\n {\r\n for (var i = 0; i < tables.length; ++i) {\r\n tables[i] = null;\r\n }\r\n };\r\n // Constructor Code\r\n var i, lst;\r\n if (arguments.length > 5) { // we've been passed a list of IDs and/or Element objects\r\n i = 5;\r\n lst = arguments;\r\n }\r\n else { // make a list of all tables\r\n i = 0;\r\n lst = xGetElementsByTagName('table');\r\n }\r\n for (; i < lst.length; ++i) {\r\n tables[i] = xGetElementById(lst[i]);\r\n }\r\n init();\r\n onEvent({type:'resize'});\r\n /*@cc_on\r\n @if (@_jscript_version == 5.6) // IE6\r\n xAddEventListener(fakeBodyId, 'scroll', onEvent, false);\r\n @else @*/\r\n xAddEventListener(window, 'scroll', onEvent, false);\r\n /*@end @*/\r\n xAddEventListener(window, 'resize', onEvent, false);\r\n} // end xTableHeaderFixed", "function itemTable() { }", "function TableTop() {\n}", "function TablesList() {}", "function drawTable(){\n\n}", "function xTableCursor(id, inh, def, hov, sel) // object prototype\r\n{\r\n var tbl = xGetElementById(id);\r\n if (tbl) {\r\n xTableIterate(tbl, init);\r\n }\r\n function init(obj, isRow)\r\n {\r\n if (isRow) {\r\n obj.className = def;\r\n obj.onmouseover = trOver;\r\n obj.onmouseout = trOut;\r\n }\r\n else {\r\n obj.className = inh;\r\n obj.onmouseover = tdOver;\r\n obj.onmouseout = tdOut;\r\n }\r\n }\r\n this.unload = function() { xTableIterate(tbl, done); };\r\n function done(o) { o.onmouseover = o.onmouseout = null; }\r\n function trOver() { this.className = hov; }\r\n function trOut() { this.className = def; }\r\n function tdOver() { this.className = sel; }\r\n function tdOut() { this.className = inh; }\r\n}", "function xTableCursor2(id, hov, sel) // object prototype\r\n{\r\n var tbl = xGetElementById(id);\r\n if (tbl) {\r\n xTableIterate(tbl, init);\r\n }\r\n function init(obj, isRow)\r\n {\r\n if (isRow) {\r\n obj.onmouseover = trOver;\r\n obj.onmouseout = trOut;\r\n }\r\n else {\r\n obj.onmouseover = tdOver;\r\n obj.onmouseout = tdOut;\r\n }\r\n }\r\n this.unload = function() { xTableIterate(tbl, done); };\r\n function done(o) { o.onmouseover = o.onmouseout = null; }\r\n function trOver() { this.className += \" \" + hov; }\r\n function trOut() { this.className = this.className.replace(hov,\"\"); }\r\n function tdOver() { this.className += \" \" + sel; }\r\n function tdOut() { this.className = this.className.replace(sel,\"\"); }\r\n}", "function insertColumnHeadingsRow(theResultsTable) {\r\n\t\r\n theResultsTable.innerHTML = \"<tr><th>Item Number</th><th>Item Description</th><th>Item Stock Amount</th></tr>\";\r\n}", "function userTable() { }", "function xTableCursor(id, inh, def, hov, sel) // object prototype\n{\n var tbl = xGetElementById(id);\n if (tbl) {\n xTableIterate(tbl, init);\n }\n function init(obj, isRow)\n {\n if (isRow) {\n obj.className = def;\n obj.onmouseover = trOver;\n obj.onmouseout = trOut;\n }\n else {\n obj.className = inh;\n obj.onmouseover = tdOver;\n obj.onmouseout = tdOut;\n }\n }\n this.unload = function() { xTableIterate(tbl, done); };\n function done(o) { o.onmouseover = o.onmouseout = null; }\n function trOver() { this.className = hov; }\n function trOut() { this.className = def; }\n function tdOver() { this.className = sel; }\n function tdOut() { this.className = inh; }\n}", "function xdrTableElement(tableElem, xdr) {\r\n return tableElem;\r\n }", "function repaint_exp_table(ecore, aid, table_div){\n\n // First, lets get the headers that we'll need by poking the\n // model and getting all of the possible categories.\n var cat_list = [];\n each(ecore.get_nodes(), function(enode, enode_id){\n\teach(enode.types(), function(in_type){\n\t cat_list.push(in_type.category());\n\t});\n });\n // Dedupe list.\n var tmph = bbop_core.hashify(cat_list);\n cat_list = us.keys(tmph);\n\n // If we actually got something, render the table. Otherwise,\n // a message.\n if( us.isEmpty(cat_list) ){\n\n\t// Add to display.\n\tjQuery(table_div).empty();\n\tjQuery(table_div).append('<p><h4>no instances</h4></p>');\n\n }else{\n\n\t// Sort header list according to known priorities.\n\tcat_list = cat_list.sort(function(a, b){\n\t return aid.priority(b) - aid.priority(a);\n\t});\n\n\t// Convert the ids into readable headers.\n\tvar nav_tbl_headers = [];\n\teach(cat_list, function(cat_id){\n\t var hdrc = [\n\t\taid.readable(cat_id),\n\t\t'&uarr;&darr;'\n\t ];\n\t nav_tbl_headers.push(hdrc.join(' '));\n\t});\n\n\tvar nav_tbl =\n\t new bbop.html.table(nav_tbl_headers, [],\n\t\t\t\t{'generate_id': true,\n\t\t\t\t 'class': ['table', 'table-bordered',\n\t\t\t\t\t 'table-hover',\n\t\t\t\t\t 'table-condensed'].join(' ')});\n\n\t//each(ecore.get_nodes(),\n\teach(ecore.edit_node_order(), function(enode_id){\n\t var enode = ecore.get_node(enode_id);\n\n\t // Now that we have an enode, we want to mimic the order\n\t // that we created for the header (cat_list). Start by\n\t // binning the types.\n\t var bin = {};\n\t each(enode.types(), function(in_type){\n\t\tvar cat = in_type.category();\n\t\tif( ! bin[cat] ){ bin[cat] = []; }\n\t\tbin[cat].push(in_type);\n\t });\n\n\t // Now unfold the binned types into the table row\n\t // according to the sorted order.\n\t var table_row = [];\n\t each(cat_list, function(cat_id){\n\t\tvar accumulated_types = bin[cat_id];\n\t\tvar cell_cache = [];\n\t\teach(accumulated_types, function(atype){\n\t\t var tt = type_to_span(atype, aid);\n\t\t cell_cache.push(tt);\n\t\t});\n\t\ttable_row.push(cell_cache.join('<br />'));\n\t });\n\t nav_tbl.add_to(table_row);\n\t});\n\n\t// Add to display.\n\tjQuery(table_div).empty();\n\tjQuery(table_div).append(nav_tbl.to_string());\n\n\t// Make it sortable using the plugin.\n\tjQuery('#' + nav_tbl.get_id()).tablesorter();\n }\n}", "function xfmtTable(inlineContext) /* (inlineContext : inlineContext) -> ((context : inlineContext, head : list<common/row>, body : list<common/row>, colattrs : list<common/attrs>, attrs : common/attrs) -> string) */ {\n return inlineContext.xfmtTable;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the merge request can be submitted
checkAvailability() { if(!this.sourceBranch || !this.toBranch) { this.title = ''; this.available = false; return; } $.getJSON(app.getUri('h-gitter-repo-merge-request-availability', { repoId : this.repoId, from : this.sourceBranch, to : this.toBranch })) .done((response) => { this.available = response.available; this.title = response.title; }); }
[ "async function checkMergeable() {\n\tif (github.pr.mergeable_state === 'dirty') {\n\t\tlabelsToAdd.add(Label.MERGE_CONFLICTS);\n\t} else {\n\t\t// assume it has no conflicts\n\t\tlabelsToRemove.add(Label.MERGE_CONFLICTS);\n\t}\n}", "async _checkMergePreconditions() {\n this._log(\"checking merge preconditions\");\n\n await this._checkActive();\n\n // yes, _checkStagingPreconditions() has checked the same message\n // already, but our _criteria_ might have changed since that check\n if (!this._commitMessage)\n throw this._exLabeledFailure(\"commit message is now considered invalid\", Config.failedDescriptionLabel());\n\n // yes, _checkStagingPreconditions() has checked this already, but\n // humans may have changed the PR stage since that check, and our\n // checking code might have changed as well\n if (this._draftPr())\n throw this._exObviousFailure(\"became a draft\");\n\n // TODO: unstage only if there is competition for being staged\n\n // yes, _checkStagingPreconditions() has checked approval already, but\n // humans may have changed their mind since that check\n if (!this._approval.granted())\n throw this._exObviousFailure(\"lost approval\");\n if (this._approval.grantedTimeout())\n throw this._exObviousFailure(\"restart waiting for objections\");\n\n if (this._prStatuses.failed())\n throw this._exObviousFailure(\"new PR branch tests appeared/failed after staging\");\n\n if (!this._prStatuses.final())\n throw this._exSuspend(\"waiting for PR branch tests that appeared after staging\");\n\n assert(this._prStatuses.succeeded());\n\n await this._processStagingStatuses();\n }", "function isMergeCommit() {\n return github.context.eventName === 'push' && github.context.payload.head_commit !== undefined\n}", "function isPullRequest () {\n return /.+\\/merge|head/.test(env.VCS_ROOT_BRANCH)\n}", "function isPullRequest(v) {\n return v.targetBranches !== undefined;\n }", "manageApprovalStatus() { return this.approvalUrl().length > 0; }", "requestAccepted(request){\n return (request.status == 'accepted' && request.Project.state_id == 1) || (request.accepted_proposal == 'accepted');\n }", "function isPullRequest(v) {\n return v.targetBranches !== undefined;\n}", "function canSubmit () {\n for (const [field] of Object.entries(formErrors)) {\n if (!readyForSubmit(field)) return false\n }\n\n if (formData.sets.length === 0) return false\n\n return true\n }", "async function isMergeJobTypeBlocked(config) {\n\n let runningInParalell = false;\n\n if (config.BLOCKJOBTYPE) { // only do test if the job is using a resource that cannot run in paralell\n\n\n let strapiRequestURL = config.STRAPIURI + MERGEJOB_DATASET + \"?blockJobType=\" + config.BLOCKJOBTYPE + \"&jobStatus=\" + MERGEJOB_RUNNING;\n let data = \"none\"\n let result;\n\n try {\n result = await axios.get(strapiRequestURL, {\n headers: {\n Authorization: `Bearer ${config.STRAPI_APIKEY}`,\n 'Content-Type': 'application/json'\n }\n });\n data = result.data;\n\n }\n catch (e) {\n let logTxt = \"1.9 isMergeJobTypeBlocked catch error :\" + JSON.stringify(e) + \" =>result is:\" + JSON.stringify(result);\n console.error(logTxt);\n debugger\n }\n\n if (data.length > 0) {\n runningInParalell = true;\n }\n\n\n }\n\n return runningInParalell;\n\n}", "function isAPullRequest(body) {\n return body && ('pull_request' in body);\n}", "function checkSubmissionStatus(token, resourceLocation, publishMode) {\n const statusMsg = `Submission status for \"${resourceLocation}\"`;\n const requestParams = {\n url: exports.ROOT + resourceLocation + \"/status\",\n method: \"GET\",\n };\n return request\n .performAuthenticatedRequest(token, requestParams)\n .then(function (body) {\n /* Once the previous request has finished, examine the body to tell if we should start a new one. */\n if (!body.status.endsWith(\"Failed\")) {\n var msg = statusMsg + body.status;\n console.debug(statusMsg + body.status);\n console.log(msg);\n /* In immediate mode, we expect to get all the way to \"Published\" status.\n * In other modes, we stop at \"Release\" status. */\n return (body.status == \"Published\" ||\n (body.status == \"Release\" && publishMode != \"Immediate\"));\n }\n else {\n console.error(statusMsg + \" failed with \" + body.status);\n console.error(\"Reported errors: \");\n for (var i = 0; i < body.statusDetails.errors.length; i++) {\n var errDetail = body.statusDetails.errors[i];\n console.error(\"\\t \" + errDetail.code + \": \" + errDetail.details);\n }\n throw new Error(COMMIT_FAILED_MSG);\n }\n })\n .catch((err) => {\n console.log(err);\n throw new Error(COMMIT_FAILED_MSG);\n });\n}", "mergeInProgress(): Boolean {\n\t\tconst file = path.join(this.cwd, '.git', 'MERGE_HEAD');\n\t\treturn fs.existsSync(file);\n\t}", "function canSubmitForm()\n{\n return !isOriginDecodePending && !isDestinationDecodePending && !isDirectionsPending;\n}", "canRequest() {\n return this.requestQueue.size < this.requestQueueSize;\n }", "checkSharing() {\n if(this.state.incomingPods.length !== 0 || this.state.outgoingPods.length !== 0 )\n return true;\n }", "async function validateReadyToPublish() {\n try {\n await execWrapper(`git fetch`);\n let { stdout: gitStatus } = await execWrapper(`git status`);\n let [, branchName] = gitStatus.match(/On branch ([\\w-./]+)/);\n const isUpToDate =\n gitStatus.search(/Your branch is up-to-date with 'origin\\/master'./) > -1;\n const isClean =\n gitStatus.search(/nothing to commit, working tree clean/) > -1;\n if (branchName !== \"master\") {\n console.log(\n `Current Branch is ${branchName}. You must publish from master`\n );\n process.exit();\n } else if (!isUpToDate) {\n console.log(\"local is not up to date with origin/master\");\n process.exit();\n } else if (!isClean) {\n console.log(\"Uncommitted local changes detected.\");\n process.exit();\n }\n } catch (err) {\n console.log(`Failed with:\\n ${err}`);\n process.exit();\n }\n}", "canSubmit () {\r\n return this.form\r\n ? this.props.edit && this.props.hasChanged && this.form.checkValidity()\r\n : false\r\n }", "function canGit(sel){\n var canGit = false,\n\t\tisGit = false,\n\t\t//getResource function coming from customTools.js\n resource = getResource(sel[0].phash);\n // Only query if we are at the root level\n // If it is not at the root level resource will return false\n if (resource) {\n $.ajax({\n type: 'POST',\n url : \"php/createGitRepo.php\",\n data : {\n resource : resource,\n site : sel[0].name,\n type : 'query'\n },\n async : false,\n dataType : 'json'\n }).done(function (data) {\n canGit = data[\"canGit\"];\n\t\t\tisGit = data[\"isGit\"];\n }).fail(function (jqxhr, textStatus, error) {\n // do something when fail\n var err = textStatus + ', ' + error;\n console.log(\"Request Failed: \" + err);\n });\n }\n return (canGit && !isGit);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is this Interval entirely covered by the union of the ranges? The ranges parameter must be sorted by range.start
isCoveredBy(ranges: Interval[]): boolean { var remaining = this.clone(); for (var i = 0; i < ranges.length; i++) { var r = ranges[i]; if (i && r.start < ranges[i - 1].start) { throw 'isCoveredBy must be called with sorted ranges'; } if (r.start > remaining.start) { return false; // A position has been missed and there's no going back. } remaining.start = r.stop + 1; if (remaining.length() <= 0) { return true; } } return false; }
[ "function checkOverlappingRange(range)\r\n{\r\n range.isTested = true; // mark this interval\r\n \r\n var sortedIntervals = []; // sorted by start point\r\n\r\n disjointIntervals.forEach(function(interval,id) {\r\n sortedIntervals.push(interval);\r\n });\r\n\r\n sortedIntervals.push(range);\r\n \r\n sortedIntervals.sort(function(a,b) {\r\n if(a.isTested) {\r\n if(a.endValue == b.startValue)\r\n return (!a.endOpen && !b.startOpen) ? 1 : -1;\r\n else\r\n return a.endValue - b.startValue;\r\n } else if(b.isTested) {\r\n if(a.startValue == b.endValue)\r\n return (!b.endOpen && !a.startOpen) ? -1 : 1;\r\n else\r\n return a.startValue - b.endValue;\r\n } else {\r\n if(a.startValue == b.startValue)\r\n // open after closed (true after false)\r\n return a.startOpen - b.startOpen;\r\n else\r\n return a.startValue - b.startValue;\r\n }\r\n });\r\n\r\n // find the 'range' interval and check whether it is disjoint from\r\n // interval before it (if any). If it is, check whether\r\n // getCoveringIntervalId() returned undefined. If they are not disjoint,\r\n // check whether the ID of the interval before 'range' is the\r\n // id returned by getCoveringIntervalId().\r\n\r\n var rangePos;\r\n \r\n for(var i = 0, l = sortedIntervals.length ; i < l ; ++i) {\r\n if(sortedIntervals[i].isTested) {\r\n rangePos = i;\r\n break;\r\n }\r\n }\r\n\r\n var overlappingId = undefined;\r\n var overlapping = undefined;\r\n \r\n if(rangePos > 0) {\r\n var tested = sortedIntervals[rangePos];\r\n var previous = sortedIntervals[rangePos - 1];\r\n\r\n if(previous.endValue > tested.startValue ||\r\n (previous.endValue == tested.startValue &&\r\n !previous.endOpen && !tested.startOpen)) {\r\n overlappingId = previous.id;\r\n overlapping = previous;\r\n }\r\n }\r\n \r\n \r\n var coveringId =\r\n testPairwiseDisjoint.getCoveringIntervalId(range.startValue,\r\n range.startOpen,\r\n range.endValue,\r\n range.endOpen);\r\n\r\n console.log(\"testing covering of range\", range.string, \"which is\",\r\n overlappingId === undefined ? \"\" : \"not\", \"disjoint\");\r\n\r\n var coveringInterval;\r\n\r\n if(coveringId !== undefined) {\r\n for(var i = 0, l = sortedIntervals.length - 1 ; i < l ; ++i) {\r\n if(sortedIntervals[i].id == coveringId) {\r\n coveringInterval = sortedIntervals[i];\r\n break;\r\n }\r\n }\r\n }\r\n \r\n if(overlappingId != coveringId) {\r\n console.log(\"range\", range.string, \"claimed to be covered by \",\r\n coveringId,\r\n (coveringId === undefined) ? \"\" : coveringInterval,\r\n \"but is covered by\", overlappingId, overlapping);\r\n return false;\r\n }\r\n\r\n return true;\r\n}", "overlaps (begins, ends) { return this.begins() < ends && this.ends() > begins }", "inRanges(results, ranges) {\n var i, j, k, len, min, pass, ref, result;\n pass = true;\n switch (false) {\n case !(this.isArray(results) && this.isArray(ranges)):\n min = Math.min(results.length, ranges.length); // Ony apply the ranges we ga\n for (i = j = 0, ref = min; (0 <= ref ? j < ref : j > ref); i = 0 <= ref ? ++j : --j) {\n pass = pass && this.inRange(results[i], ranges[i]);\n }\n break;\n case !this.isArray(results):\n for (k = 0, len = results.length; k < len; k++) {\n result = results[k];\n pass = pass && this.inRange(results, ranges);\n }\n break;\n default:\n pass = false;\n }\n return pass;\n }", "isRangeBookable(start, end) {\n const { reservedSet } = this.state;\n for (let i = start; i <= end; i += 1) {\n if (reservedSet.has(i)) {\n return false;\n }\n }\n return true;\n }", "overlaps(dat_range){\n if (!(dat_range.start && dat_range.end)){\n console.error(\"dat_range items must all respond to a method called 'start' and 'end', this dat_range was:\", dat_range);\n }\n return this.contains_exclusive(dat_range.end) || this.contains_exclusive(dat_range.start) || this.during(dat_range);\n }", "isOverlapping(otherRange) {\n let thisFirst = this.getFirst();\n let thisLast = this.getLast();\n let otherFirst = otherRange.getFirst();\n let otherLast = otherRange.getLast();\n return (thisLast.isGreaterThan(otherFirst) && thisLast.isLessThanOrEquals(otherLast) && thisFirst.isLessThan(otherFirst)\n ||\n otherLast.isGreaterThan(thisFirst) && otherLast.isLessThanOrEquals(thisLast) && otherFirst.isLessThan(thisFirst));\n }", "intersects(range) {\n return this._max >= range.min && range.max >= this._min;\n }", "function checkDisjointRange(range)\r\n{\r\n var sortedIntervals = []; // sorted by start point\r\n\r\n disjointIntervals.forEach(function(interval,id) {\r\n sortedIntervals.push(interval);\r\n });\r\n\r\n sortedIntervals.push(range);\r\n \r\n sortedIntervals.sort(function(a,b) {\r\n if(a.startValue == b.startValue)\r\n // open after closed (true after false)\r\n return a.startOpen - b.startOpen;\r\n else\r\n return a.startValue - b.startValue;\r\n });\r\n\r\n // check whether each sorted intervals ends before the next one starts\r\n\r\n var areDisjoint = true;\r\n \r\n for(var i = 0, l = sortedIntervals.length - 1 ; i < l ; ++i) {\r\n\r\n var first = sortedIntervals[i];\r\n var second = sortedIntervals[i+1];\r\n\r\n if(first.endValue < second.startValue ||\r\n (first.endValue == second.startValue &&\r\n (first.endOpen || second.startOpen)))\r\n continue; // do not overlap\r\n\r\n areDisjoint = false;\r\n break;\r\n }\r\n\r\n console.log(\"testing range\", range.string, \"which is\",\r\n areDisjoint ? \"\" : \"not\", \"disjoint\");\r\n \r\n if(areDisjoint !== testPairwiseDisjoint.isDisjointRange(range.startValue,\r\n range.startOpen,\r\n range.endValue,\r\n range.endOpen)) {\r\n console.log(\"range\", range.string, \"claimed to be \",\r\n !areDisjoint ? \"\" : \"not\",\r\n \"disjoint\", \"while are actually\",\r\n areDisjoint ? \"\" : \"not\", \"disjoint\");\r\n return false;\r\n }\r\n\r\n return true;\r\n}", "function rangeIncludes(a, b) {\n\t var rangeIsIncluded = compareRangeBoundaryPoints(a, \"start\", b, \"start\") <= 0 && compareRangeBoundaryPoints(a, \"end\", b, \"end\") >= 0;\n\t return rangeIsIncluded;\n\t}", "function rangesOverlap(a, b) {\n\t // Two ranges do *not* overlap iff one ends before the other begins.\n\t var rangesDoNotOverlap = compareRangeBoundaryPoints(a, \"end\", b, \"start\") < 0 || compareRangeBoundaryPoints(b, \"end\", a, \"start\") < 0;\n\t return !rangesDoNotOverlap;\n\t}", "function rangesIntersect(range1, range2) {\r\n var from1 = range1[0];\n var to1 = range1[1];\r\n var from2 = range2[0];\n var to2 = range2[1];\r\n return !(CodeMirror.cmpPos(to1, from2) < 0 || CodeMirror.cmpPos(from1, to2) > 0);\r\n }", "function findEmptyRangesBetweenRanges(inRanges, opt_totalRange) {\n if (opt_totalRange && opt_totalRange.isEmpty) opt_totalRange = undefined;\n\n var emptyRanges = [];\n if (!inRanges.length) {\n if (opt_totalRange) emptyRanges.push(opt_totalRange);\n return emptyRanges;\n }\n\n inRanges = inRanges.slice();\n inRanges.sort(function (x, y) {\n return x.min - y.min;\n });\n if (opt_totalRange && opt_totalRange.min < inRanges[0].min) {\n emptyRanges.push(tr.b.Range.fromExplicitRange(opt_totalRange.min, inRanges[0].min));\n }\n\n inRanges.forEach(function (range, index) {\n for (var otherIndex = 0; otherIndex < inRanges.length; ++otherIndex) {\n if (index === otherIndex) continue;\n var other = inRanges[otherIndex];\n\n if (other.min > range.max) {\n // |inRanges| is sorted, so |other| is the first range after |range|,\n // and there is an empty range between them.\n emptyRanges.push(tr.b.Range.fromExplicitRange(range.max, other.min));\n return;\n }\n // Otherwise, |other| starts before |range| ends, so |other| might\n // possibly contain the end of |range|.\n\n if (other.max > range.max) {\n // |other| does contain the end of |range|, so no empty range starts\n // at the end of this |range|.\n return;\n }\n }\n if (opt_totalRange && range.max < opt_totalRange.max) {\n emptyRanges.push(tr.b.Range.fromExplicitRange(range.max, opt_totalRange.max));\n }\n });\n return emptyRanges;\n }", "function OverlappingRanges(arr) {\n var arr1 = [];\n var arr2 = [];\n var count = 0;\n for (var i = arr[0]; i <= arr[1]; i++) {\n arr1.push(i);\n }\n for (var j = arr[2]; j <= arr[3]; j++) {\n arr2.push(j);\n }\n arr2.forEach(function(el) {\n if (arr1.includes(el)) {\n count++;\n }\n })\n return count >= arr[4] ? true : false;\n}", "function rangesOverlap(a, b) {\n // Two ranges do *not* overlap iff one ends before the other begins.\n var rangesDoNotOverlap = compareRangeBoundaryPoints(a, \"end\", b, \"start\") < 0 || compareRangeBoundaryPoints(b, \"end\", a, \"start\") < 0;\n return !rangesDoNotOverlap;\n}", "intersectsRange(start, end) {\n // is the test range start inside?\n if (start >= this.start && start < this.end) {\n return true;\n }\n // is the test range end inside?\n if (end > start && end <= this.end) {\n return true;\n }\n return false;\n }", "function rangesOverlap(minA, maxA, minB, maxB) {\n 'use strict';\n return minA <= maxB && maxA >= minB;\n}", "rangeOverlap(range1, range2){\n return (range1.min < range2.min && range1.max > range2.min)\n || (range1.min < range2.max && range1.max > range2.max)\n || (range1.min > range2.min && range1.max < range2.max)\n || (range1.min < range2.min && range1.max > range2.max);\n }", "subtractRanges(ranges) {\r\n let idx1 = 0;\r\n const newRanges = this.ranges.filter((r) => {\r\n let idx = ranges.ranges.indexOf(r, idx1);\r\n if (idx != -1) {\r\n idx1 = idx; // take advantage of the fact the ranges are sorted\r\n return false; // discard\r\n }\r\n else\r\n return true; // keep\r\n });\r\n return DisjointRangeSet.makeFromSortedRanges(newRanges);\r\n }", "intersect(ranges) {\n const out = [];\n if (ranges.length == 0)\n return out;\n const end = ranges[ranges.length-1].end;\n let i = this._find(ranges[0].start), j = 0;\n while (i < this.ranges.length && j < ranges.length) {\n if (this.ranges[i].start >= end)\n break;\n if (IntervalMap.overlap(this.ranges[i], ranges[j])) {\n // Found a match.\n out.push(this.ranges[i]);\n i++;\n } else if (this.ranges[i].start < ranges[j].start) {\n i++;\n } else {\n j++;\n }\n }\n return out;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Optionally confine search to map extent
function setSearchExtent (){ if (dom.byId('chkExtent').checked === 1) { geocoder.activeGeocoder.searchExtent = map.extent; } else { geocoder.activeGeocoder.searchExtent = null; } }
[ "function centersearchfeature(xmax, xmin, ymax, ymin)\n{ \nmap.zoomToExtent(new OpenLayers.Bounds(xmin, ymin, xmax, ymax).transform(map.displayProjection, map.projection));\n}", "function setSearchExtent (){\n if (dom.byId('chkExtent').checked === 1) {\n geocoder.activeGeocoder.searchExtent = app.map.extent;\n } else {\n geocoder.activeGeocoder.searchExtent = null;\n }\n }", "function setSearchExtent() {\n if (dom.byId(\"chkExtent\").checked === 1) {\n geocoder.activeGeocoder.searchExtent = app.map.extent;\n } else {\n geocoder.activeGeocoder.searchExtent = null;\n }\n }", "function SetMapExtent() {\n\tmap.getExtent();\n\tvar curBounds = map.getExtent();\n\tbounds = curBounds.transform(googleMercator, wgs84);\n\t//console.log(bounds);\n}", "function setViewerExtent(ext){\n if (ext == 'tz'){\n map.setMaxBounds(tanbounds);\n map.fitBounds(tanbounds);\n map.setMinZoom(5);\n map.setZoom(5);\n }else if (ext == 'global'){\n map.setMaxBounds(globalbounds);\n map.fitBounds(globalbounds);\n map.setZoom(2);\n map.setMinZoom(2);\n }else{\n console.log(\"extent identifier not found\");\n } \n}", "function SetMapExtent() {\n\tmap.getExtent();\n\tvar curBounds = map.getExtent();\n\tbounds = curBounds.transform(googleMercator, wgs84);\n}", "function _getSearchExtent() {\n var searchExtent, mapExtent;\n if (isWebMap) {\n searchExtent = webmapExtent;\n } else {\n mapExtent = responseObject.DefaultExtent.split(',');\n searchExtent = new esri.geometry.Extent(parseFloat(mapExtent[0]), parseFloat(mapExtent[1]), parseFloat(mapExtent[2]), parseFloat(mapExtent[3]), map.spatialReference);\n }\n return searchExtent;\n}", "function fitLayerExtent(){\n var fitEdgeRate=0.1;\n var myExtent=layer.getSource().getExtent();\n var xFit=myExtent[2]-myExtent[0];\n var yFit=myExtent[3]-myExtent[1];\n if(xFit<=100 || yFit<=100){\n locateMe();\n return;\n }\n myExtent[0]-=xFit*fitEdgeRate;\n myExtent[2]+=xFit*fitEdgeRate;\n myExtent[1]-=yFit*fitEdgeRate;\n myExtent[3]+=yFit*fitEdgeRate;\n console.log(myExtent);\n map.getView().fit(myExtent);\n}", "function zoomToAddressResults() {\n this.theMap.fitBounds(self.layerSearch.getBounds());\n // var layerSearchResults = this.theMap.getLayersByName(this.SEARCH)[0];\n // var resultBounds = layerSearchResults.getDataExtent();\n // this.theMap.zoomToExtent(resultBounds);\n // if (this.theMap.getZoom() > 14) {\n // this.theMap.zoomTo(14);\n // }\n }", "function locate() {\r\n mymap.locate({setView: false, maxZoom: 20});\r\n}", "function zoomToAddressResults() {\n\t\t\tvar layerSearchResults = this.theMap.getLayersByName(this.SEARCH)[0];\n\t\t\tvar resultBounds = layerSearchResults.getDataExtent();\n\t\t\tthis.theMap.zoomToExtent(resultBounds);\n\t\t\tif (this.theMap.getZoom() > 14) {\n\t\t\t\tthis.theMap.zoomTo(14);\n\t\t\t}\n\t\t}", "function locate() {\n mymap.locate({\n setView: true,\n maxZoom: defaultZoom\n });\n}", "function fit_markers_to_map(){ \n map.fitBounds(bounds);\n }", "function zoomExtent() {\n let bounds = new google.maps.LatLngBounds();\n for (let i = 0; i < markers.length; i++) {\n if (markers[i].visible) {\n bounds.extend(markers[i].getPosition());\n }\n }\n\n map.fitBounds(bounds);\n}", "function geocodeSearch(searchStr) {\n //var bbox = ol.proj.transform($.OLMAP.view.calculateExtent($.OLMAP.map.getSize()),\n // 'EPSG:3857', 'EPSG:4326').toString(),\n var bbox = map.getExtent().toBBOX();\n var center = map.getCenter().transform(\n map.getProjectionObject(), //4326\n new OpenLayers.Projection(\"EPSG:3857\")\n );\n var distance = map.getExtent().transform(\n map.getProjectionObject(), new OpenLayers.Projection(\"EPSG:3857\")\n ).getWidth();\n var url = 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates' +\n '?SingleLine=' + searchStr +\n '&f=json' +\n '&location=' + center +\n '&distance=' + distance + // '3218.69' = 2 meters\n //'&outSR=102100'+ // web mercator\n //'&searchExtent='+bbox+\n //'&outFields=Loc_name'+\n '&maxLocations=1';\n var parser = new OpenLayers.Format.GeoJSON();\n var req = window.superagent;\n req.get(url, function(response){\n var responseJson = JSON.parse(response.text);\n var searchExt = responseJson.candidates[0].extent;\n var extent = new OpenLayers.Bounds(searchExt.xmin, searchExt.ymin, searchExt.xmax, searchExt.ymax);\n map.zoomToExtent(extent);\n });\n}", "_isInExtent(extent) {\n const map = this.getMap();\n const mapExtent = map.getExtent();\n const intersection = mapExtent.intersection(new maptalks.Extent(extent));\n if (intersection) {\n return true;\n } else\n return false;\n }", "function locate() {\nmap.locate({setView: true, maxZoom: 16});\n}", "function onMapBoundsChanged() {\n console.log(\"Change search box bounds\");\n var bounds = map.getBounds();\n searchBox.setBounds(bounds);\n }", "initializeMapBounds() {\n // these are the more limiting maxbounds for texas\n // const maxBounds = [[25.7, -107], [36.8, -93.2]]\n const maxBounds = [[23.5, -112.6], [41, -83]]\n const center = this.map.getCenter()\n const newCenter = {lat: center.lat, lng: center.lng}\n if (center.lat < maxBounds[0][0]) {\n newCenter.lat = maxBounds[0][0]\n }\n if (center.lat > maxBounds[1][0]) {\n newCenter.lat = maxBounds[1][0]\n }\n if (center.lng < maxBounds[0][1]) {\n newCenter.lng = maxBounds[0][1]\n }\n if (center.lng > maxBounds[1][1]) {\n newCenter.lng = maxBounds[1][1]\n }\n if (newCenter.lat !== center.lat || newCenter.lng !== center.lng) {\n this.map.panTo(newCenter, {\n animate: true\n })\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calcular CHI teniendo como entrada la tabla_de_contingencia (frecuencias observadas) y usandola para genarar la tabla de frencuencias espedas
function calcular_chi2_calculado(tabla_de_contingencia) { let frecuencias_esperadas = generar_frecuencias_esperadas(tabla_de_contingencia); let sumatoria = 0; for (let i = 0; i < tabla_de_contingencia.length; i++) { // sumatoria para chi calculado usando la formula de sumatoria for (let j = 0; j < tabla_de_contingencia[0].length; j++) { sumatoria += (Math.pow(tabla_de_contingencia[i][j] - frecuencias_esperadas[i][j], 2) / frecuencias_esperadas[i][j]) } } return Number(sumatoria.toFixed(2)); // toFixed redondea a dos decimales }
[ "function calcular_chi2_calculado(tabla_de_datos) {\n let tabla_de_contingencia = generar_tabla_de_contingencia(tabla_de_datos);\n let frecuencias_esperadas = generar_frecuencias_esperadas(tabla_de_datos);\n let sumatoria = 0;\n for (let i = 0; i < tabla_de_contingencia.length; i++) { // sumatoria para chi calculado usando la formula de sumatoria\n for (let j = 0; j < tabla_de_contingencia[0].length; j++) {\n sumatoria += (Math.pow(tabla_de_contingencia[i][j] - frecuencias_esperadas[i][j], 2) / frecuencias_esperadas[i][j])\n }\n }\n return Number(sumatoria.toFixed(2)); // toFixed redondea a dos decimales\n}", "function calcular_chi2_calculado_formula(tabla_de_datos) {\n let n = tabla_de_datos.length * tabla_de_datos[0].length;\n let tabla_de_contingencia = generar_tabla_de_contingencia(tabla_de_datos);\n let a = tabla_de_contingencia[0][0];\n let b = tabla_de_contingencia[0][1];\n let c = tabla_de_contingencia[1][0];\n let d = tabla_de_contingencia[1][1];\n\n let dividendo = ( n * Math.pow( ( Math.abs(a*d - b*c) - (n/2) ), 2) ); // dividendo de la formula\n let divisor = ( a + b ) * ( c + d ) * ( a + c ) * ( b + d ); // divisor de la formula\n let chi2 = dividendo / divisor; // division realizada\n return chi2;\n}", "function crearFactura(miventa, misdetalles) {\n var conten = document.getElementById(\"ridefac\");\n var numcomprobante = document.getElementById(\"numfac\").innerHTML;\n var nuevocomp = numcomprobante.replace('###', miventa[0].NUMERO_COM);\n\n var contenido = '<div class=\"card\" style=\"width: 20rem;\">' +\n '<div class=\"card-body\">' +\n '<div><center> <b> FARMACIA COMUNITARIA PUYO </b></center> </div>' +\n ' <center><div>' + document.getElementById(\"rucfac\").innerHTML + ' </div> </center>' +\n ' <center><div>' + document.getElementById(\"direccionfac\").innerHTML + ' </div> </center>' +\n '<div id=\"numfac\">FACTURA: ' + nuevocomp + '</div>' +\n '<div>Fecha: ' + miventa[0].FECHA_VEN + ' Codigo: ' + miventa[0].ID_VEN + '</div>' +\n '<div>Ruc/Ci: ' + document.getElementById(\"RUC\").value + '</div>' +\n '<div>Cliente:<b> ' + document.getElementById(\"nombrescl\").innerHTML + '</b></div>' +\n '<div>Dirección:' + document.getElementById(\"dirtel\").innerHTML + '</div>' +\n '<table class=\"table table-sm\">' +\n '<tr style=\"font-size: smaller;\">' +\n '<th>Descripción</th>' +\n '<th>Cantidad</th>' +\n '<th>Pre.Uni</th>' +\n '<th>Pre.Total</th>' +\n '</tr> <tbody>';\n //ID_DET_VEN, ID_PRO, ID_VEN, CANTIDAD_PRO, PRECIO_VEN, AHORRO, SUBTOTAL, DESCRIPCION_PRO\n for (let i = 0; i < misdetalles.length; i++) {\n var fila = '<tr style=\"font-size: smaller;\">' +\n '<td>' + misdetalles[i].DESCRIPCION_PRO + '</td>' +\n '<td>' + misdetalles[i].CANTIDAD_PRO + '</td>' +\n '<td>' + misdetalles[i].PRECIO_VEN + '</td>' +\n '<td>' + misdetalles[i].SUBTOTAL + '</td>' +\n '</tr>';\n contenido += fila;\n\n }\n\n contenido += '</tbody>' +\n '</table>' +\n '<table class=\"table table-sm\" style=\"font-size: smaller;\">' +\n '<tr>' +\n ' <td class=\"datosv\">Valor</td>' +\n '<td class=\"datosv\">' + document.getElementById(\"valorfac\").innerHTML + '</td>' +\n '</tr>' +\n '<tr>' +\n\n '<td class=\"datosv\">Descuentos</td>' +\n '<td class=\"datosv\">' + document.getElementById(\"descfac\").innerHTML + '</td>' +\n '</tr>' +\n '<tr>' +\n\n '<td class=\"datosv\">Subtotal</td>' +\n '<td class=\"datosv\">' + document.getElementById(\"subsubtotal\").innerHTML + '</td>' +\n '</tr>' +\n '<tr>' +\n\n '<td class=\"datosv\">tarifa '+ toFixedTrunc(iva*100,0)+'%</td>' +\n '<td class=\"datosv\">' + document.getElementById(\"tar12\").innerHTML + '</td>' +\n '</tr>' +\n\n '<tr>' +\n\n '<td class=\"datosv\">Tarifa 0%</td>' +\n '<td class=\"datosv\">' + document.getElementById(\"tar0\").innerHTML + '</td>' +\n '</tr>' +\n '<tr>' +\n\n '<td class=\"datosv\">IVA</td>' +\n ' <td class=\"datosv\">' + document.getElementById(\"valoriva\").innerHTML + '</td>' +\n '</tr>' +\n ' <tr>' +\n\n '<th>TOTAL</th>' +\n '<th>' + document.getElementById(\"total\").innerHTML + '</th>' +\n '</tr>' +\n ' </table>' +\n ' <hr>' +\n '<div class=\"datosv\" style=\"font-size: smaller;\">Paga con:' + document.getElementById(\"recibe\").value + ' '+ document.getElementById(\"cambio\").innerHTML +' </div>' +\n '<div class=\"datosv\" style=\"font-size: smaller;\">Atendido por:' + document.getElementById(\"h6UserName\").innerHTML + ' </div>' +\n ' <div class=\"datosv\" style=\"font-size: smaller;\">' + document.getElementById(\"cajadesc\").innerHTML + '</div>' +\n ' <div class=\"datosv\" style=\"font-size: smaller;\">Total de articulos vendidos:' + totalArticulosVendidos() + '</div> ' +\n '</div>' +\n '</div>';\n document.getElementById(\"ridefac\").innerHTML = contenido;\n}", "function tabla_resultados_insidencias() {\n var resultados = comparar_ckl_insidencias(),cuestionario;\n var si = 0, no = 0, na = 0;\n var contador = 0,suma=0;\n $.each(resultados, function (index, datos) {\n var tabla = $('<tr class=\"resultado_ckl_t\"></tr>');\n if (index == 0) {\n tabla.append($(\"<th >#</th>\").css({ 'background-color': '#93E2FA', 'width': '40px', 'font-size': '18px' }));\n tabla.append(($(\"<th class='criterio_cuestion' ></th>\").append(datos.cuestionario)).css({ 'background-color': '#93E2FA', 'width': '70%', 'font-size': '18px' }));\n tabla.append($(\"<th >CUMPLIO</th>\").css({ 'background-color': '#93E2FA', 'width': '90px', 'font-size': '18px' }));\n cuestionario = datos.cuestionario;\n $('.tablaRespuestas').append(tabla);\n tabla = $('<tr class=\"resultado_ckl_t\"></tr>');\n }\n if (cuestionario == datos.cuestionario) {\n tabla.append(($(\"<td class='id'></td>\").append((index + 1)).css({ \"width\": \"40px\" })));\n tabla.append(($(\"<td class='criterio_cuestion'></td>\").append(datos.observaciones)).css({ \"width\": \"70%\", \"text-align\": \"left\" }));\n tabla.append(($(\"<td class='respuesta'></td>\").append((cumple(datos.respuesta)))).css({ \"width\": \"90px\", \"text-align\": \"center\" }));\n $('.tablaRespuestas').append(tabla);\n tabla = $('<tr class=\"resultado_ckl_t\"></tr>');\n }\n else if (cuestionario != datos.cuestionario) {\n tabla.append($(\"<th >#</th>\").css({ 'background-color': '#93E2FA', 'width': '40px', 'font-size': '18px' }));\n tabla.append(($(\"<th class='criterio_cuestion' ></th>\").append(datos.cuestionario)).css({ 'background-color': '#93E2FA', 'width': '70%', 'font-size': '18px' }));\n tabla.append($(\"<th >CUMPLIO</th>\").css({ 'background-color': '#93E2FA', 'width': '90px', 'font-size': '18px' }));\n cuestionario = datos.cuestionario;\n $('.tablaRespuestas').append(tabla);\n tabla = $('<tr class=\"resultado_ckl_t\"></tr>');\n tabla.append(($(\"<td class='id'></td>\").append((index + 1)).css({ \"width\": \"40px\" })));\n tabla.append(($(\"<td class='criterio_cuestion'></td>\").append(datos.observaciones)).css({ \"width\": \"70%\", \"text-align\": \"left\" }));\n tabla.append(($(\"<td class='respuesta'></td>\").append((cumple(datos.respuesta)))).css({ \"width\": \"90px\", \"text-align\": \"center\" }));\n $('.tablaRespuestas').append(tabla);\n tabla = $('<tr class=\"resultado_ckl_t\"></tr>');\n }\n });\n var tabla = $('<tr class=\"resultado_ckl_t\"></tr>');\n tabla.append($(\"<th >#</th>\").css({ 'background-color': '#93E2FA', 'width': '40px', 'font-size': '18px' }));\n tabla.append(($(\"<th class='criterio_cuestion' ></th>\").append(\"CUMPLIO TOTAL\")).css({ 'background-color': '#93E2FA', 'width': '70%', 'font-size': '18px' }));\n tabla.append($(\"<th ></th>\").append(Math.round((suma / contador) * 100) + \"%\").css({ 'background-color': 'rgb(20,120,240)', 'width': '90px', 'font-size': '18px' }));\n\n $('.tablaRespuestas').append(tabla);\n \n //funcion que comprueba si cumplio\n function cumple(dato) {\n if (dato == 1) {\n contador++, suma ++,si++;\n return \"SI\"; \n }\n else if (dato == 0) {\n contador++, no ++;\n return \"NO\";}\n else if (dato == 2) {\n na ++;\n return \"NA\";\n }\n else return \"--\"\n }\n $(\"#cuadro_resultado_total_si\").val(si), $(\"#cuadro_resultado_total_no\").val(no), $(\"#cuadro_resultado_total_na\").val(na);\n $(\"#cuadro_resultado_total_porcentual\").val(Math.round((suma / contador) * 100))\n\n}//fin", "function tablaDatosCapa(event, atributos)\n{\n var tabla = '';\n var valores = event.target.feature.properties;\n\n tabla += '';\n tabla += '<table class=\"tablaDatosLugar\">';\n for (var i = 0; i < atributos.length; i++) \n {\n var elRotulo = atributos[i]['rotulo'];\n var elValor = valores[atributos[i]['nom_campo']];\n elValor = (elValor !== null) ? elValor : '';\n \n switch(atributos[i]['orden'])\n {\n case 'float': elValor = parseFloat(elValor);\n elValor = elValor.toFixed(2);\n break;\n default: break;\n }\n \n tabla += '<tr class=\"renglonTablaDatosLugar\">';\n tabla += '<td class=\"celdaTablaDatosLugar rotuloCelda\" style=\"text-align:right\">' + (elRotulo) + '<td>';\n tabla += '<td class=\"celdaTablaDatosLugar\" style=\"text-align:right\">' + '&nbsp;&nbsp;' + '<td>';\n tabla += '<td class=\"celdaTablaDatosLugar\" style=\"text-align:left\">' + (elValor) + ' ' + ((atributos[i]['simbolos'] === null) ? '' : atributos[i]['simbolos']) + '<td>';\n tabla += '<tr>';\n }\n tabla += '</table>';\n \n return tabla;\n}", "function esCIF(campo,cadena){\n\tvar primeraLetra;\n\tvar ultimaLetra;\n\tvar suma;\n\tvar suma2;\n\tvar act;\n\tvar i;\n\tvar tabla;\n\tvar error = \"\";\n\t\n\t//compruebo que la primera letra sea del tipo aceptado\n\tprimeraLetra = cogeLetra(cadena,0);\n\tultimaLetra = cogeLetra(cadena,8);\n\ttabla = \"ABCDEFGHJKLMNPQRSUVWXYZ\";\n\n\ttablaEspecial = \"CKLMNPQRSW\";\n\tif (tabla.indexOf(primeraLetra)==-1) error = \"la primera letra no es valida\";\n\telse if ((primeraLetra == \"X\")||(primeraLetra == \"Y\")||(primeraLetra == \"Z\")){\n\t\t//para el caso de CIF que empiecen por X,Y o Z es lo mismo que un NIF que empieza por 0,1 o 2 Respectivamente\n\t\terror = error +esNIF(campo,cadena);\n\t} else {\n\t\t//para el resto de casos...realizo la suma de pares e impares y todo eso.\n\t\tsuma = valorLetra(cadena,2)+valorLetra(cadena,4)+valorLetra(cadena,6);\n\t\tfor(i=0\n\t\t\t;i<4;i++){\n\t\t\tact = valorLetra(cadena,2*i+1)*2;\n\t\t\tif (act>=10) act = act - 9;\t\t\t\t//-10 +1\n\t\t\tsuma = suma + act;\n\t\t}\n\t\tsuma = 10 - (suma % 10);\n/*\n\t\tsuma = valorLetra(cadena,2)+valorLetra(cadena,4)+valorLetra(cadena,6);\n\t\tsuma2 = 0;\n\t\tfor(i=0;i<4;i++){\n\t\t\tact = valorLetra(cadena,2*i+1)*2;\n\t\t\tsuma2 = suma2 + act;\n\t\t\tif (suma2>=10) suma2 = suma2 - 9;\t\t\t\t//-10 +1\n\t\t}\n\t\tif (suma2>=10) suma2 = suma2 - 9;\t\t\t\t//-10 +1\n\t\tsuma = suma + suma2;\n\t\tsuma = 10 - (suma % 10);\n*/\t\n\t\t//comprobacion del digito de control para varios casos\n\t\tif (tablaEspecial.indexOf(primeraLetra)!=-1){\n\t\t\t//caso de organismos autonomos\n\t\t\tif (ultimaLetra!=String.fromCharCode(64+suma))\n\t\t\t\terror = error + \"CIF incorrecto, deberia acabar en \"+String.fromCharCode(64+suma);\n\t\t} else {\n\t\t\t//el resto de casos\n\t\t\tsuma = suma % 10;\n\t\t\t//alert(ultimaLetra+\" \"+suma);\n\t\t\tif (ultimaLetra!=suma.toString())\n\t\t\t\terror = error + \"CIF incorrecto, deberia acabar en \"+suma;\n\t\t}\n\t}\n\t\n\tif (error!=\"\") error = \"Campo \"+campo+\" = \"+cadena+\", \"+error+\"\\n\";\n\treturn error;\n}", "function affiche_Tableau_factures(){\n filtre_Tableau_factures();\n taille_tableau_content = taille_tableau_content_page['facture'];\n var current_tableau = Tableau_factures_filter;\n var strname = 'facture';\n var strnamebdd = 'facture';\n var stridentificateur = new Array('ref','total_price_HT','total_price_TTC','statut');\n affiche_Tableau_content(current_tableau, strname, strnamebdd, stridentificateur);\n supp_affiche_Tableau_factures();\n}", "function geraTabela(){\r\n // obtencao do carro selecionado, separando o mesmo em um vetor, onde será pega somente uma posição\r\n var sCarro = document.getElementById('carSelecao').value.split('-');\r\n // obtendo somente o valor da quantidade de carro\r\n var iQtd = document.getElementById('qtd').value;\r\n\r\n // obtendo tabela pré-pronta\r\n var eTabela = document.getElementById('miniTabela');\r\n //criando uma linha e realizando a insercao da mesma na tabela\r\n var eTr = document.createElement('tr');\r\n eTabela.appendChild(eTr);\r\n\r\n var eTd1 = document.createElement('td');\r\n eTd1.setAttribute(\"class\", \"linha\");\r\n //setando o somente o carro na td\r\n eTd1.innerHTML = sCarro[1];\r\n eTr.appendChild(eTd1);\r\n\r\n var eTd2 = document.createElement('td');\r\n // setando a quantidade na td de quantidade\r\n eTd2.innerHTML = iQtd;\r\n eTd2.setAttribute(\"class\", \"linha\");\r\n eTr.appendChild(eTd2);\r\n\r\n var eTd3 = document.createElement('td');\r\n // realizando a multiplicao da quantidade pelo preco do carro\r\n eTd3.innerHTML = 'R$' + parseInt(sCarro[2])*iQtd + ' Reais';\r\n eTd3.setAttribute(\"class\", \"linha\");\r\n eTr.appendChild(eTd3);\r\n // incrementando a quantidade total de pedidos de carros\r\n fTotal += parseInt(sCarro[2])*iQtd;\r\n var eTotal = document.getElementById('total');\r\n eTotal.setAttribute('value', fTotal);\r\n}", "function tablaCoS(data){\n var tabuladoCoS = '<table class=\"striped tablaArmada\"><thead><tr>';\n var cabezera = false;\n console.log(data);\n for (var i = 0; i < data.Coberturas.length; i++) {\n\n //tomamos las cabezeras, años del primer dato\n if(!cabezera){\n tabuladoCoS += '<th> Entidad Federativa </th>';\n for (var j = 0; j < data.Coberturas[i].ValorDato.length; j++) {\n if(data.Coberturas[i].ValorDato[j].Leyenda_ser == '' || data.Coberturas[i].ValorDato[j].Leyenda_ser == null){\n tabuladoCoS += '<th>' + data.Coberturas[i].ValorDato[j].AADato_ser + '</th>';\n }else{\n tabuladoCoS += '<th>' + data.Coberturas[i].ValorDato[j].Leyenda_ser + '</th>';\n }\n\n }//fin for j\n cabezera = true;\n }\n\n tabuladoCoS += '</tr></thead><tr><td>' + '<span style=\"display:none;\">'+data.Coberturas[i].ClaveCobGeo_cg+ '</span>' + data.Coberturas[i].Descrip_cg +'</td>';\n for (var j = 0; j < data.Coberturas[i].ValorDato.length; j++) {\n if(data.Coberturas[i].ValorDato[j].Dato_Formato == \"\"){\n tabuladoCoS += '<td style=\"text-align:right;\"> '+ data.Coberturas[i].ValorDato[j].NoDatos.Codigo_nd +' </td>';\n }else{\n tabuladoCoS += '<td style=\"text-align:right;\">' + data.Coberturas[i].ValorDato[j].Dato_Formato + '</td>';\n }\n }//fin for j\n tabuladoCoS += '</tr>';\n }//fin for i\n tabuladoCoS += '</table>';\n\n //$('#tabla').html(tabuladoCoS);\n return tabuladoCoS;\n}//fin funcion", "function calculaCostePeriferico(tableId,perif){\n\ttry {\n\t\ttable = document.getElementById('mitabla_' + perif);\n\t\tvar rowCount = table.rows.length;\n\t\tvar coste_ref = 0;\n\t\tvar costeTotal = 0;\n\n\t\tfor(var i=1; i<rowCount; i++) {\n\t\t\tvar row = table.rows[i];\n\t\t\tcoste_ref = parseFloat(row.cells[10].childNodes[0].nodeValue);\n\t\t\tcoste_ref = coste_ref * 100;\n\t\t\tcoste_ref = Math.round(coste_ref) / 100;\n\t\t\tcosteTotal = costeTotal + coste_ref;\n\t\t}\n\t\treturn costeTotal;\n\t}\n\tcatch(e) {\n\t\talert(e);\n\t}\n}", "function afficherSac(){\t\n\tif(!affiche){\n\t\taffiche=true;\n\t\tlet texte=\"<table id=tableInventaire><tr>\";\n\t\tlet compteur=0;\n\t\tlet a;\n\t\tfor(let p in sac){\n\t\t\ta=espace(p);\n\t\t\tcompteur++;\n\t\t\ttexte+=\"<td id='\"+a+\"'>\"+sac[p]+\"</td>\";\n\t\t}\n\t\tfor(let i=compteur;i<8;i++){\n\t\t\ttexte+=\"<td id='vide'></td>\";\n\t\t}\n\t\ttexte+=\"</tr></table>\";\n\t\ttexte+=\"<button id=fermerInventaire onClick='deAfficherSac()'>Fermer l'inventaire</button>\"\n\t\tdocument.getElementById(instanceEnCours+'Text').innerHTML+=texte;\n\t} \n}", "function damePrecioKitConHeredadas(table){\n\tvar array_ids = new Array();\n\tvar array_piezas = new Array();\n\n\tvar rowCount = table.rows.length;\n\tvar id_ref;\n\tvar piezas;\n\n\t// Empezamos en la primera fila obviando la fila de encabezado\n\tfor(var i=1; i<rowCount; i++) {\n\t\tvar j=i-1;\n\t\tvar row = table.rows[i];\n\t\tid_ref = row.cells[0].childNodes[0].nodeValue;\n\t\tpiezas = row.cells[5].childNodes[0].nodeValue;\n\n\t\tarray_ids[j] = id_ref;\n\t\tarray_piezas[j] = piezas;\n\t}\n\n\t// Llamada asincrona para obtener el coste total del componente con sus ref. heredadas\n\tvar respuesta = (function () {\n\t\tvar respuesta = null;\n\t\t$.ajax({\n\t\t\tdataType: \"json\",\n\t\t\turl: \"../ajax/basicos/referencias.php?comp=calcularCosteReferenciasHeredadas\",\n\t\t\tdata: \"ids=\" + array_ids + \"&piezas=\" + array_piezas,\n\t\t\ttype: \"GET\",\n\t\t\tasync: false,\n\t\t\tsuccess: function (data) {\n\t\t\t\trespuesta = data;\n\t\t\t}\n\t\t});\n\t\treturn respuesta;\n\t})();\n\n\tvar precio = respuesta;\n\treturn precio;\n}", "function correlation(info)\n{\n table = document.getElementById(\"co\");\n //lista de posibilidades\n var events = new Array;\n for (let i = 0; i < info.length; i++) {\n //Evento actual\n list = info[i].events;\n //si o no ardilla\n bool = info[i].squirrel;\n for (let j = 0; j < list.length; j++) {\n var e = list[j];\n //Si es ardilla \n if(bool)\n {\n //creacion objeto nuevo\n e = {name: e, t: 1, f:0,co:0};\n }\n else\n {\n e = {name: e, t: 0, f:1,co:0};\n }\n //buscando si ya se adjunto el elemento en la lista\n original = events.find(r => r.name==e.name);\n if(original!=undefined)\n {\n //actualiszando variables\n original.t += e.t;\n original.f += e.f;\n }\n //añadiendo nuevo elemento a la lista\n else\n {\n \n events.push(e);\n }\n \n }\n }\n totalF = 85;\n totalT = 5;\n //calculando MCC\n for (let i = 0; i < events.length; i++) {\n fn = events[i].f;\n tn = totalF - fn;\n tp = events[i].t;\n fp = totalT - tp;\n mcc = (tp*tn - fp*fn)/(Math.sqrt((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn)))\n events[i].co = mcc;\n }\n events.sort((b,a)=> a.co-b.co);\n for (let i = 0; i < events.length; i++) {\n table.insertRow(i+1);\n table.rows[i+1].insertCell(0);\n table.rows[i+1].insertCell(1);\n table.rows[i+1].insertCell(2);\n\n table.rows[i+1].cells[0].innerHTML = i+1;\n table.rows[i+1].cells[1].innerHTML = events[i].name;\n table.rows[i+1].cells[2].innerHTML = events[i].co;\n \n }\n}", "function impostaTabellaTipoOperazioniCassa() {\n var tableId = \"#tabellaTipoGiustificativo\";\n var zero = 0;\n var opts = {\n bServerSide: true,\n sServerMethod: \"POST\",\n sAjaxSource : \"risultatiRicercaTipoGiustificativoAjax.do\",\n bPaginate: true,\n bLengthChange: false,\n iDisplayLength: 10,\n bSort: false,\n bInfo: true,\n bAutoWidth: true,\n bFilter: false,\n bProcessing: true,\n bDestroy: true,\n oLanguage: {\n sInfo: \"_START_ - _END_ di _MAX_ risultati\",\n sInfoEmpty: \"0 risultati\",\n sProcessing: \"Attendere prego...\",\n sZeroRecords: \"Non sono presenti risultati di ricerca secondo i parametri inseriti\",\n oPaginate: {\n sFirst: \"inizio\",\n sLast: \"fine\",\n sNext: \"succ.\",\n sPrevious: \"prec.\",\n sEmptyTable: \"Nessun tipo giustificativo disponibile\"\n }\n },\n fnPreDrawCallback: function () {\n // Mostro il div del processing\n $(tableId + \"_processing\").parent(\"div\")\n .show();\n },\n // Chiamata al termine della creazione della tabella\n fnDrawCallback: function () {\n var records = this.fnSettings().fnRecordsTotal();\n var testo = (records === 0 || records > 1) ? (records + \" Risultati trovati\") : (\"1 Risultato trovato\");\n $('#id_num_result').html(testo);\n // Nascondo il div del processing\n $(tableId + \"_processing\").parent(\"div\")\n .hide();\n },\n aoColumnDefs: [\n {aTargets: [0], mData: function(source) {\n return source.codice || \"\";\n }},\n {aTargets: [1], mData: function(source) {\n return source.tipologiaGiustificativo && source.tipologiaGiustificativo.descrizione || \"\";\n }},\n {aTargets: [2], mData: function(source) {\n return source.descrizione || \"\";\n }},\n {aTargets: [3], mData: function(source) {\n return source.statoOperativoTipoGiustificativo && source.statoOperativoTipoGiustificativo.descrizione || \"\";\n }},\n {aTargets: [4], mData: function(source) {\n return source.importo !== undefined && source.importo.formatMoney() || \"\";\n }},\n {aTargets: [5], mData: function(source) {\n return (source.percentualeAnticipoTrasferta || zero).formatMoney();\n }},\n {aTargets: [6], mData: function(source) {\n return (source.percentualeAnticipoMissione || zero).formatMoney();\n }},\n {aTargets: [7], mData: function(source) {\n var res = \"\";\n if(cassaInStatoValido && source.statoOperativoTipoGiustificativo.descrizione === \"Valido\") {\n res = \"<div class='btn-group'>\"\n + \"<button data-toggle='dropdown' class='btn dropdown-toggle'>Azioni<span class='caret'></span></button>\"\n + \"<ul class='dropdown-menu pull-right'>\"\n + \"<li><a class='aggiornaTipo'>aggiorna</a></li>\"\n + \"<li><a class='annullaTipo'>annulla</a></li>\"\n + \"</ul>\"\n + \"</div>\";\n }\n return res;\n }, fnCreatedCell: function(nTd, sData, oData) {\n $(nTd).addClass(\"tab_Right\")\n .find(\"a.aggiornaTipo\")\n .substituteHandler(\"click\", function() {\n apriCollapseAggiornamento(oData);\n })\n .end()\n .find(\"a.annullaTipo\")\n .substituteHandler(\"click\", function() {\n apriModaleAnnullamento(oData);\n });\n }}\n ]\n };\n divRisultati.slideDown();\n $(tableId).dataTable(opts);\n }", "function fasesTableContentAll() {\n const total = faseConteo.fase1 + faseConteo.fase2;\n const faseUno = parseFloat(Math.round(((faseConteo.fase1 / total) * 100) * 100) / 100).toFixed(2);\n const faseDos = parseFloat(Math.round(((faseConteo.fase2 / total) * 100) * 100) / 100).toFixed(2);\n faseTableDetail.classList.add(alineacionCentro);\n faseTableDetail.children[0].children[1].textContent = faseConteo.fase1;\n faseTableDetail.children[0].children[2].textContent = faseUno + \" %\";\n faseTableDetail.children[1].children[1].textContent = faseConteo.fase2;\n faseTableDetail.children[1].children[2].textContent = faseDos + \" %\";\n faseTableDetail.children[2].children[1].textContent = total;\n faseTableDetail.children[2].children[2].textContent = \"100 %\";\n}", "listadoSaldoConductor(){\r\n let sTabla = '<table border=\"1\">';\r\n\r\n sTabla += \"<thead><tr>\";\r\n sTabla += \"<th>NIF</th>\";\r\n sTabla += \"<th>Saldo pendiente</th>\";\r\n sTabla += \"</tr></thread>\";\r\n\r\n // ABRE body tabla\r\n sTabla += \"<tbody>\";\r\n\r\n let oConductor = this.personas.filter(oP => oP instanceof Conductor);\r\n \r\n for(let i = 0; i<oConductor.length; i++){\r\n let saldo = 0;\r\n\r\n let multasPendientes = this.multas.filter(oP => oP.NIFConductor == oConductor[i].NIF && oP.pagada == false);\r\n\r\n if(multasPendientes.length != 0){\r\n sTabla += \"<tr><td>\"+oConductor[i].NIF;\r\n \r\n for(let j = 0; j<multasPendientes.length; j++){\r\n\r\n if(multasPendientes[j] instanceof Leve && multasPendientes[j].bonificada ==true){\r\n saldo += multasPendientes[j].importe - (multasPendientes[j].importe*0.25);\r\n }else{\r\n \r\n saldo += multasPendientes[j].importe;\r\n }\r\n \r\n }\r\n sTabla += \"</td><td>\"+saldo+\" €</td></tr>\";\r\n\r\n }\r\n }\r\n sTabla += \"</tbody><table>\";\r\n \r\n return sTabla;\r\n }", "function calcular_chi2_critico(tabla_de_contingencia, alpha) {\n let grado_de_libertad = calcular_grado_libertad(tabla_de_contingencia);\n if (grado_de_libertad > 5) {\n // si se quiere usar la tabla para calculo de chi completa deben ser agregados los valores en la tabla chi criticos\n alert(\"La tabla de chi critico actual, solo admite grado de libertad menores o iguales que 5\"); \n return 0;\n } else {\n return tabla_chi_criticos[alpha][grado_de_libertad];\n }\n}", "fecharCompra() {\n let total = 0;\n\n // 20% de desconto para novos clientes\n if (this.novoCliente) {\n total = this.valorTotal * 0.8;\n // desconto de XX% do cupom \n } else if (this.cupom) {\n total = this.valorTotal * (1 - this.cupom);\n // 5% de desconto para compras acima de 100 reais\n } else if (this.valorTotal > 100) {\n fintotalal = this.valorTotal * 0.95;\n };\n\n return this.valorTotal = total.toFixed(2);;\n }", "function impostaTabellaOperazioniCassa() {\n var tableId = \"#tabellaOperazioneCassa\";\n var zero = 0;\n var opts = {\n bServerSide: true,\n sServerMethod: \"POST\",\n sAjaxSource : \"risultatiRicercaOperazioneCassaAjax.do\",\n bPaginate: true,\n bLengthChange: false,\n iDisplayLength: 10,\n bSort: false,\n bInfo: true,\n bAutoWidth: true,\n bFilter: false,\n bProcessing: true,\n bDestroy: true,\n oLanguage: {\n sInfo: \"_START_ - _END_ di _MAX_ risultati\",\n sInfoEmpty: \"0 risultati\",\n sProcessing: \"Attendere prego...\",\n sZeroRecords: \"Non sono presenti risultati di ricerca secondo i parametri inseriti\",\n oPaginate: {\n sFirst: \"inizio\",\n sLast: \"fine\",\n sNext: \"succ.\",\n sPrevious: \"prec.\",\n sEmptyTable: \"Nessuna operazione di cassa disponibile\"\n }\n },\n fnPreDrawCallback: function () {\n // Mostro il div del processing\n $(tableId + \"_processing\").parent(\"div\")\n .show();\n },\n // Chiamata al termine della creazione della tabella\n fnDrawCallback: function () {\n var records = this.fnSettings().fnRecordsTotal();\n var testo = (records === 0 || records > 1) ? (records + \" Risultati trovati\") : (\"1 Risultato trovato\");\n $('#id_num_result').html(testo);\n // Nascondo il div del processing\n $(tableId + \"_processing\").parent(\"div\")\n .hide();\n },\n aoColumnDefs: [\n {aTargets: [0], mData: function(source) {\n return source.dataOperazione && formatDate(source.dataOperazione) || \"\";\n }},\n {aTargets: [1], mData: function(source) {\n return source.tipoOperazioneCassa && source.tipoOperazioneCassa.tipologiaOperazioneCassa && source.tipoOperazioneCassa.tipologiaOperazioneCassa.descrizione || \"\";\n }},\n {aTargets: [2], mData: function(source) {\n return source.tipoOperazioneCassa && source.tipoOperazioneCassa.descrizione || \"\";\n }},\n \n {aTargets: [3], mData: function(source) {\n return source.modalitaPagamentoCassa && source.modalitaPagamentoCassa.descrizione || \"\";\n }},\n {aTargets: [4], mData: function(source) {\n return source.statoOperativoOperazioneCassa && source.statoOperativoOperazioneCassa.descrizione || \"\";\n }},\n {aTargets: [5], mData: function(source) {\n var number = source.importo || zero;\n return number.formatMoney();\n }, fnCreatedCell: function(nTd) {\n $(nTd).addClass(\"tab_Right\");\n }},\n {aTargets: [6], mData: function(source) {\n var res = \"\";\n var aggiornaAbilitato = source.statoOperativoOperazioneCassa && (source.statoOperativoOperazioneCassa.codice === \"P\" || source.statoOperativoOperazioneCassa.codice === \"D\");\n var annullaAbilitato = source.statoOperativoOperazioneCassa && source.statoOperativoOperazioneCassa.codice === \"P\";\n if(azioniAbilitate && annullaAbilitato) {\n res = \"<div class='btn-group'>\"\n + \"<button data-toggle='dropdown' class='btn dropdown-toggle'>Azioni<span class='caret'></span></button>\"\n + \"<ul class='dropdown-menu pull-right'>\";\n if(aggiornaAbilitato){\n res += \"<li><a class='aggiornaOperazioneCassa'>aggiorna</a></li>\";\n }\n res += \"<li><a class='annullaOperazioneCassa'>annulla</a></li>\"\n + \"</ul>\"\n + \"</div>\";\n }\n return res;\n }, fnCreatedCell: function(nTd, sData, oData) {\n $(nTd).addClass(\"tab_Right\")\n .find(\"a.aggiornaOperazioneCassa\")\n .substituteHandler(\"click\", function() {\n apriCollapseAggiornamento(oData);\n })\n .end()\n .find(\"a.annullaOperazioneCassa\")\n .substituteHandler(\"click\", function() {\n apriModaleAnnullamento(oData);\n });\n }}\n ]\n };\n divRisultati.slideDown();\n $(tableId).dataTable(opts);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update the appearance of the reset button depending on whether the graph has been filtered
function updateReset() { d3.select("div.reset") .style("opacity", function() { if (filtered) { return 1; } else { return 0.4; } }) .style("width", function() { if (filtered) { return "60px"; } else { return "35px"; } }) }
[ "function reset(){\n setInitialCondition(compute,renderer);\n}", "function filterReset() {\n for(const btn of filterBtns) {\n btn.classList.add('active');\n }\n conditionsToShow = allConditions.slice(); // reset conditionToShow\n const filter = ['match', ['get', 'condition'], conditionsToShow, true, false];\n map1.setFilter('tree-heatmap', filter);\n map1.setFilter('tree-dots', filter);\n}", "function displayResetFilter(){\n \n resetSearchButton.css({\"visibility\":\"visible\"});\n \n if( regionInput.val() === \"*\" && periodInput.val() === \"*\" && $(topicsElement).val() === null ) {\n \n resetSearchButton.css({\"visibility\":\"hidden\"});\n \n }\n \n }", "resetFilter() {\n this.buttons.dateButton.innerHTML = Config.ALL_DATES;\n this.buttons.facultyButton.innerHTML = Config.ALL_FACULTIES;\n this.buttons.categoryButton.innerHTML = Config.ALL_CATEGORIES;\n this.buttons.orderButton.innerHTML = Config.ORIGINAL_ORDER;\n this.buttons.resetCategoryFilterButton.classList.add(\"hidden\");\n this.buttons.resetFacultyFilterButton.classList.add(\"hidden\");\n this.buttons.resetDateFilterButton.classList.add(\"hidden\");\n this.buttons.resetOrderFilterButton.classList.add(\"hidden\");\n }", "function filterResetClick() {\n // console.log('filterResetClick');\n\n PageData.Controls.Brightness.value =\n PageData.Controls.Brightness.defaultValue;\n PageData.Controls.Contrast.value =\n PageData.Controls.Contrast.defaultValue;\n PageData.Controls.Hue.value =\n PageData.Controls.Hue.defaultValue;\n PageData.Controls.Saturation.value =\n PageData.Controls.Saturation.defaultValue;\n\n filterChange();\n}", "function toggleReset(chart, id) {\n var filters = chart.filters();\n var t = document.getElementById(id);\n var this_script = $('#'+id).data('reset-script');\n if (filters.length) {\n t.innerHTML = \"<a href=\" + this_script + \">[reset]</a>\";\n }\n else {\n t.innerHTML = '';\n }\n }", "function ToggleResetFilters() {\n var activeFiltersCountries = $('.filter-bar-country').find('.filter-button.button-active');;\n\t\tvar activeFiltersLevels = $('.filter-bar-level').find('.filter-button.button-active');\n \tvar activeFilters = $.merge(activeFiltersCountries, activeFiltersLevels);\n \tvar activeFiltersWindSeason = $('.filter-bar-windseason').find('.filter-button.button-active');;\n \tactiveFilters = $.merge(activeFilters, activeFiltersWindSeason);\n \tvar activeFiltersWindForecast = $('.filter-bar-windforecast').find('.filter-button.button-active');;\n \tactiveFilters = $.merge(activeFilters, activeFiltersWindForecast);\n \tvar activeFiltersTravelers = $('.filter-bar-travelers').find('.filter-button.button-active');\n activeFilters = $.merge(activeFilters, activeFiltersTravelers);\n if ( $('.search-text-field').val() ) {\n \tactiveFilters = $.merge(activeFilters, $('.search-text-field'));\n }\n \n \tif ( activeFilters.length == 0 ) { \n \t\t$( \".reset-filters\" ).hide();\n \t} else {\n \t\t$( \".reset-filters\" ).show();\n $( \".reset-filters\" ).css('display', 'flex');\n \t}\n \n}", "function setFilterResetButton(buttonID) {\r\n d3.select(buttonID)\r\n .on(\"click\", resetClickHandler);\r\n }", "function addResetButton() {\n resetButton.innerHTML = \"Reset\";\n resetButton.className = 'filter-button-reset';\n filterSection.insertBefore(resetButton, filterSection.firstChild);\n\n function uncheckFilters() {\n let checkedLists = [].slice.call(document.querySelectorAll('.facet-value'));\n\n for (let i = 0; i < checkedLists.length; i++) {\n checkedLists[i].setAttribute('data-checked', false);\n }\n }\n\n function removeCheckedClass() {\n let checkboxes = [].slice.call(document.querySelectorAll('.plp-checkbox'));\n\n for (let i = 0; i < checkboxes.length; i++) {\n checkboxes[i].classList.remove('checked');\n }\n }\n\n // Uncheck checkboxes & remove querystring\n resetButton.addEventListener('click', function() {\n uncheckFilters();\n removeCheckedClass();\n window.history.pushState(null, '', currentUrl);\n location.reload();\n })\n }", "function update(){\r\n if (graph == \"Brightness\" & painter != null & painter != \"\"){\r\n d3.selectAll(\"svg\")\r\n .remove()\r\n brightplot()\r\n }\r\n else if (graph == \"Color Usage\" & painter != null & painter != \"\"){\r\n d3.selectAll(\"svg\")\r\n .remove()\r\n colorplot()\r\n }\r\n}", "filterReset() {\n\t\tthis.hiddenMarkers.removeAll();\n\t\tthis.markers.forEach((marker) => {\n\t\t\tmarker.setVisible(false);\n\t\t});\n\t}", "function clear() {\r\n d3.select(\"#timelapse-chart\").remove();\r\n d3.select(\"#pause-button\").node().innerHTML = \"Pausar\";\r\n d3.select(\"#filters-div-container\").attr(\"class\", \"hidden\");\r\n}", "function postRedrawCallbackFunc(){\n //If no filter exist, should reset the clear flag of Scatter Plot.\n if(!dcHasFilters()){\n StudyViewInitScatterPlot.setclearFlag(false);\n }\n }", "function resetFilters() {\n for (var i = 0; i < allMarkerObjects.length; i++) {\n allMarkerObjects[i].setVisible(true);\n }\n}", "function reset() {\n title.style.display = null; // Reset to CSS\n resetButton.style.display = \"none\";\n \n currentRanges = null;\n currentKey = null;\n display(initialColors.map(x => x.color));\n}", "function handleResetBtn() {\n var dt = s.widgets.table.dataTable;\n if (dt.page.info().recordsTotal > dt.page.info().recordsDisplay) {\n if (!$(c.FILTER.BUTTONS.RESET).length) {\n $(c.FILTER.BUTTONS.CONTAINER).append('<button id=\"items-reset\" class=\"btn btn-default\"><i class=\"fa fa-refresh\"></i></button>')\n }\n } else {\n $(c.FILTER.BUTTONS.RESET).remove();\n }\n }", "function resetButton(happinessData, qualityDataset) {\n\td3.select(\"#buttonDiv\")\n\t\t.append(\"div\")\n\t\t.attr(\"id\", \"option\")\n\td3.select(\"#option\")\n\t\t.append(\"input\")\n\t\t.attr(\"class\", \"btn btn-info btn-sm\")\n\t\t.attr(\"id\", \"button\")\n\t\t.attr(\"name\", \"updateButton\")\n\t\t.attr(\"type\", \"button\")\n\t\t.attr(\"value\", \"Reset Scatterplot\")\n\n\tdocument.getElementById(\"button\").addEventListener(\"click\", function() {\n\t\tmakeScatterPlot(happinessData, qualityDataset)\n\t}, false)\n}", "function resetGraph() {\n …\n displayGraph(bars);\n }", "function resetButton() {\n\t$('#textboxAbsolute').val(\"excluded\");\n\t$('#textboxAbsolute').css(\"background-color\", \"#FFFFFF\");\n\t$('#expressionLevelSlider').val(0);\n\t\n\t// get name of tissue we're adjusting\n\tvar tissue = $('#setLevel-tissueName').text()\n\t\n\t// figure out which index number that corresponds to in allTissues\n\tvar index = findIndexByKeyValue(allTissues, 'tissue', tissue);\n\t\n\t// reset the value and color in allTissues to null\n\tallTissues[index].value = \"excluded\";\n\tallTissues[index].color = \"#FFFFFF\";\n\t\n\t// update the color on the svg shape \n\tchangeFillColor(tissue, \"#FFFFFF\");\n\tsaveExpressionLevel();\n\tcloseCurrentTooltip();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
restoreRange restore lately range
restoreRange() { if (this.lastRange) { this.lastRange.select(); this.focus(); } }
[ "function restoreRange(editor) {\n if (editor.range) {\n if (ie)\n editor.range[0].select();\n else if (iege11)\n getSelection(editor).addRange(editor.range[0]);\n }\n }", "function restoreRange(serialized) {\n var range = document.createRange();\n range.setStart(serialized.startContainer, serialized.startOffset);\n range.setEnd(serialized.endContainer, serialized.endOffset);\n\n var sel = window.getSelection();\n sel.removeAllRanges();\n sel.addRange(range);\n}", "function editor_tools_restore_range()\n{\n if (editor_tools_textarea_range != null)\n {\n editor_tools_textarea_range.select();\n editor_tools_textarea_range = null;\n }\n}", "restoreLastValidRangeIfNeeded() {}", "function restoreRange(editor) {\n if (ie && editor.range)\n editor.range[0].select();\n }", "function restoreEditableSelection(range) {\n if (range) {\n if (window.getSelection) {\n sel = window.getSelection();\n sel.removeAllRanges();\n sel.addRange(range);\n } else if (document.selection && range.select) {\n range.select();\n }\n }\n }", "restoreLastSelection() {\n if (this.range_backup) {\n this.range = this._adjustSelection(\n {\n node: [this.range_backup.startContainer, this.range_backup.endContainer],\n position: [this.range_backup.startOffset, this.range_backup.endOffset]\n });\n let sel = window.getSelection();\n let range = document.createRange();\n range.setStart(this.range.startContainer, this.range.startOffset);\n range.setEnd(this.range.endContainer, this.range.endOffset);\n sel.removeAllRanges();\n sel.addRange(range);\n }\n }", "_resetRange() {\n let prevRange = this._range;\n delete this._range;\n let range = this.range;\n if (!range.isEqual(prevRange)) {\n this._rangeDidChange();\n }\n }", "restoreState() {\n\t\tif (!isNone(get(this, '__saveState'))) {\n\t\t\tsetStart(this, get(this, '__saveState.start'));\n\t\t\tsetEnd(this, get(this, '__saveState.end'));\n\t\t\tthis.setSelected(get(this, '__saveState.selectedId'));\n\t\t}\n\t}", "restore() {\n\t\t\tthis._r.restore();\n\t\t}", "resetValueAndRange() {\n this.setValueAndRange(this.initialValue, this.rangeProperty.initialValue);\n }", "resetValueAndRange() {\n this.setValueAndRange( this.initialValue, this.rangeProperty.initialValue );\n }", "restoreState() {\n this.current = Object.assign({}, this.savedState.current)\n this.waiting = Object.assign({}, this.savedState.waiting)\n this.vdu.cursor.restoreState(this.savedState.cursor)\n }", "restoreSelection() {\n\t\tconst selection = window.getSelection();\n\t\tselection.removeAllRanges();\n\t\tselection.addRange(this.selecton);\n\t}", "restore() {\n\t\t\t\tthis.position = this.savedStates.pop();\n\t\t\t}", "function invertRange(range) {\n var start = $type.getValue(range.start);\n var end = $type.getValue(range.end);\n return {\n start: 1 - end,\n end: 1 - start\n };\n}", "function selectionRestore() {\n if (savedSelection) {\n rangy.restoreSelection(savedSelection);\n savedSelection = false;\n }\n}", "function invertRange(range) {\n var start = getValue(range.start);\n var end = getValue(range.end);\n return { start: 1 - end, end: 1 - start };\n}", "_popRange() {\n this._ranges.pop();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the set of currently tracked path refs of the editor.
pathRefs(editor) { var refs = PATH_REFS.get(editor); if (!refs) { refs = new Set(); PATH_REFS.set(editor, refs); } return refs; }
[ "pathRefs(editor) {\n var refs = PATH_REFS.get(editor);\n if (!refs) {\n refs = /* @__PURE__ */ new Set();\n PATH_REFS.set(editor, refs);\n }\n return refs;\n }", "references() {\n const { path, refs } = this.referenceWalk(this);\n if (path !== undefined) {\n refs.add(path);\n }\n return Array.from(refs);\n }", "pointRefs(editor) {\n var refs = POINT_REFS.get(editor);\n\n if (!refs) {\n refs = new Set();\n POINT_REFS.set(editor, refs);\n }\n\n return refs;\n }", "function getReferencedByPaths(state,referencedFilePath){return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(),function(_a){var filePath=_a[0],referencesInFile=_a[1];return referencesInFile.has(referencedFilePath)?filePath:undefined;}));}", "rangeRefs(editor) {\n var refs = RANGE_REFS.get(editor);\n\n if (!refs) {\n refs = new Set();\n RANGE_REFS.set(editor, refs);\n }\n\n return refs;\n }", "getSelectedFilePatches() {\n return this.refEditor.map(editor => {\n const patches = new Set();\n for (const range of editor.getSelectedBufferRanges()) {\n for (const row of range.getRows()) {\n const patch = this.props.multiFilePatch.getFilePatchAt(row);\n patches.add(patch);\n }\n }\n return patches;\n }).getOr(new Set());\n }", "pointRefs(editor) {\n var refs = POINT_REFS.get(editor);\n if (!refs) {\n refs = /* @__PURE__ */ new Set();\n POINT_REFS.set(editor, refs);\n }\n return refs;\n }", "function getReferencedByPaths(state, referencedFilePath) {\n return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {\n var filePath = _a[0], referencesInFile = _a[1];\n return referencesInFile.has(referencedFilePath) ? filePath : undefined;\n }));\n }", "rangeRefs(editor) {\n var refs = RANGE_REFS.get(editor);\n if (!refs) {\n refs = /* @__PURE__ */ new Set();\n RANGE_REFS.set(editor, refs);\n }\n return refs;\n }", "function getReferencedByPaths(state, referencedFilePath) {\n return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {\n var filePath = _a[0],\n referencesInFile = _a[1];\n return referencesInFile.has(referencedFilePath) ? filePath : undefined;\n }));\n }", "pathRef(editor, path) {\n var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};\n var {\n affinity = \"forward\"\n } = options;\n var ref2 = {\n current: path,\n affinity,\n unref() {\n var {\n current\n } = ref2;\n var pathRefs = Editor.pathRefs(editor);\n pathRefs.delete(ref2);\n ref2.current = null;\n return current;\n }\n };\n var refs = Editor.pathRefs(editor);\n refs.add(ref2);\n return ref2;\n }", "pathRef(editor, path) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var {\n affinity = 'forward'\n } = options;\n var ref = {\n current: path,\n affinity,\n\n unref() {\n var {\n current\n } = ref;\n var pathRefs = Editor.pathRefs(editor);\n pathRefs.delete(ref);\n ref.current = null;\n return current;\n }\n\n };\n var refs = Editor.pathRefs(editor);\n refs.add(ref);\n return ref;\n }", "getAllLocators() {\n return this.nextReferences.getAllLocators();\n }", "async getDependentPaths() {\n return [];\n }", "function getPathsOnCanvas(){\n var lay = paper.project.activeLayer;\n var paths = [];\n if(lay) getPathsOnCanvas_sub(paths, lay);\n return paths;\n }", "getLookupPaths() {\n return this.lookups.map(lookup => lookup.path.path());\n }", "getAllDependantsOf(path) {\n const result = new Set();\n this._getAllDependantsOf(path, new Set(), result);\n return result;\n }", "findReferences() {\n const ret = new Set();\n function recurse(node) {\n for (const reference of node.references) {\n ret.add({ source: node.host, reference });\n }\n for (const child of node.children) {\n recurse(child.node);\n }\n }\n recurse(this);\n return Array.from(ret);\n }", "get path() {\n var _a;\n return ((_a = this.parentNode) === null || _a === void 0 ? void 0 : _a.path) ? [...this.parentNode.path, this] : [this];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name: PredictionLink Description: The PredictionLink class is used to estimate the rating that will be given to another song (or category) based on an attribute of another song (or category)
function PredictionLink(passedVal1, passedVal2){ //alert("constructing predictionLink\r\n"); /* public function */ this.initializeDecreasing = initializeDecreasing; this.initializeIncreasing = initializeIncreasing; this.update = update; this.guess = guess; //private variables var inputData = passedVal1; var outputData = passedVal2; //alert("constructing Scatterplot\r\n"); var plot = new ScatterPlot(); //alert("constructing DateTime\r\n"); var latestUpdateTime = new DateTime(); var numChanges = 0.0; //message("making prediction link part 1\r\n"); // check whether this link is predicting something from its own past history if (inputData.getOwnerName().equalTo(outputData.getOwnerName())) { //message("making prediction link part 2\r\n"); // check whether this link is using the participation history if (inputData.isAParticipationMovingAverage()) { //message("making prediction link part 3\r\n"); // If we get here then we're predicting the score of a Candidate based // on its past frequency. Usually, if something has happened a lot recently // then it will be boring in the future //this.initializeDecreasing(); } else { // If we get here then we're predicting the score of a Candidate based // on its current score. If we start with a small amount of suspicion that it will // be positively correlated then we may save the user lots of time // We use a small weight, though, so it's easy to overpower this.initializeIncreasing(); } } //public function function initializeDecreasing(){ //message("making prediction link part 4\r\n"); var intensity = 1; var numPoints = 40; var i = 0; var score = 0.0; var duration = 0.0; for (i = 0; i < numPoints; i++){ /*duration = i*1500.0; intensity = 1.0/duration; score = Math.sqrt(duration) / 250.0; */ duration = i * 1500; intensity = 1 / duration; score = i / numPoints; // add some extra variation to show that we aren't sure about this if (i % 2 == 0) score = (1 + score) / 2; else score = score / 2; plot.addDataPoint(new Datapoint(intensity, score, 1)); } numChanges = numChanges + numPoints; } function initializeIncreasing(){ plot.addDataPoint(new Datapoint(0, 0, 1)); plot.addDataPoint(new Datapoint(1, 1, 1)); numChanges += 2; } // updates the scatterplot with any new data that it hadn't yet // requested from the MovingAverage that it tries to estimate function update(){ //alert("PredictionLink::update\r\n"); var newPoints = inputData.getCorrelationsFor(outputData, latestUpdateTime); //alert("back in PredictionLink::update\r\n"); if (newPoints[0].length > 0){ var i=0; //alert("plot adding datapoints\r\n"); for (i = 0; i < newPoints[0].length; i++) { plot.addDataPoint(newPoints[0][i]); } latestUpdateTime = outputData.getLatestDate(); numChanges = numChanges + newPoints[1]; //alert("plot done adding datapoints\r\n"); } } // compute a distribution that represents the expected deviation from the overall mean function guess(when){ //alert("PredictionLink::guess"); var input = inputData.getCurrentValue(when, false); var middle = plot.predict(input.getMean()); message("x ="+input.getMean()); message("middle = " + middle.getMean()); var leftOneStdDev = plot.predict(input.getMean() - input.getStdDev()); message(" left = " + leftOneStdDev.getMean()); var rightOneStdDev = plot.predict(input.getMean() + input.getStdDev()); message(" right = " + rightOneStdDev.getMean()); //alert("PredictionLink::guess pt2"); var stdDevA = (rightOneStdDev.getMean() - leftOneStdDev.getMean()) / 2.0; var stdDevB = middle.getStdDev(); var stdDev = Math.sqrt(stdDevA * stdDevA + stdDevB * stdDevB); //alert("PredictionLink::guess pt3"); //var weight = numChanges - 1.0; var weight = numChanges; if (weight < 0.0){ weight = 0.0; } var stdDev2; if (numChanges > 0) stdDev2 = .5 / numChanges; else stdDev2 = 0.5; var result = new Distribution(middle.getMean(), stdDev + stdDev2, weight); //alert("PredictionLink::guess pt4"); return result; } }
[ "function PredPrediction(pred, alt) {\n this.alt = alt;\n this.pred = pred;\n return this;\n}", "function PredPrediction(pred, alt) {\n\tthis.alt = alt;\n\tthis.pred = pred;\n\treturn this;\n}", "function PredPrediction(pred, alt) {\r\n this.alt = alt;\r\n this.pred = pred;\r\n return this;\r\n }", "function LinkInfo(json) {\n Model.call(this, json, {\n 'approvalCode': $string\n });\n}", "updateLinkWeight() {\n var j, len, link, ref, ref1, ref2;\n ref = this.links;\n for (j = 0, len = ref.length; j < len; j++) {\n link = ref[j];\n link.weight = (ref1 = (ref2 = this.data.turns.find((turn) => {\n return turn.participant === link.source;\n })) != null ? ref2.turns : void 0) != null ? ref1 : 0;\n }\n }", "function SongAttributes(title, artist, featured_artists, album, release_year,\n genre, duration, available_on) {\n this.title = title;\n this.artist = artist;\n this.featured_artists = featured_artists;\n this.album = album;\n this.release_year = release_year;\n this.genre = genre;\n this.duration = duration;\n this.available_on = available_on;\n this.describeSong = function () {\n console.log(\"The title of my favourite song is \" + this.title);\n console.log(\"by \" + artist + \".\");\n console.log(\"The featured artists are \" + this.featured_artists[0] + \", \"\n + this.featured_artists[1] + \", \" + this.featured_artists[2]+ \", and \"\n + this.featured_artists[3] + \".\");\n console.log(\"It was released in the album \" + this.album);\n console.log(\"in the year \",this. release_year);\n console.log(\"The genre is \" + this.genre + \".\");\n console.log(\"It lasts for \", this.duration, \"and\");\n console.log(\"it's available on \" + this.available_on + \".\\n\");\n };\n }", "function linkData(data) {\n this.source = parseInt(data['sourceIdx']);\n this.target = parseInt(data['targetIdx']);\n if ('value' in data) {\n this.value = parseFloat(data['value']);\n } else {\n this.value = 3;\n }\n if ('relation' in data) {\n this.relation = data['relation'];\n }\n}", "function VolaryPixelLink()\n{\n\t//this.id = undefined;\n\tAVolaryModel.call(this);\n\t\n\tthis.target = undefined;\n\tthis.chaser = undefined;\n\n\tthis.deltaPosition = \n\t{\n\t\tx : undefined,\n\t\ty : undefined\n\t};\n}", "link(input, output, config) {\n var index = this.output(output);\n var relationships = this.input(input);\n if (config) {\n if (!isNaN(config.value)) {\n // Set to specific value\n relationships[index] = config.value;\n } else if (!isNaN(config.change)) {\n // Strengthen/weaken link\n relationships[index] *= config.change;\n if (relationships[index] > 1) {\n // When above max divide everything by 10\n for (var i = 0; i < relationships.length; i++) {\n relationships[i] /= 10;\n }\n }\n }\n }\n return this;\n }", "get conceptIndexLink(): LinkModel {\n return this.links.getLinkByKey(\"concepts\");\n }", "function genLinkWeight(){\n links.forEach(function(link){\n if(linkWeightMap.has(JSON.stringify(link))){\n linkWeightMap.set(JSON.stringify(link),(linkWeightMap.get(JSON.stringify(link)) + 1)) // Increment counter\n } else {\n linkWeightMap.set(JSON.stringify(link), 1); // Add to map with a base value of 1\n }\n });\n}", "function CrossLinkData( crossLinkDataInputFormat, options ) { // crossLinkData\n\t\n\t// From Server Side\n\tthis.peptideData1 = crossLinkDataInputFormat.peptideData1;\n\tthis.crossLinkPos1 = crossLinkDataInputFormat.crossLinkPos1;\n\tthis.peptideData2 = crossLinkDataInputFormat.peptideData2;\n\tthis.crossLinkPos2 = crossLinkDataInputFormat.crossLinkPos2;\n\tthis.linkerMass = crossLinkDataInputFormat.linkerMass;\n\tthis.cleavedLinkerMass = crossLinkDataInputFormat.cleavedLinkerMass; // Only on Some Linkers, passed in from Proxl XML file on Linker, User chooses which one to use\n\t\n\t// Added on client side:\n\t\n\t// Which peptide number is the primary peptide and getting the main display\n\tthis.currentPeptideNumber = crossLinkDataInputFormat.currentPeptideNumber;\n\t\n\tif ( this.currentPeptideNumber != 1 && this.currentPeptideNumber != 2 ) {\n\t\t\n\t\tthrow \"this.currentPeptideNumber is NOT VALID since it is not '1' or '2'\"; \n\t}\n\t\n\t// Create Peptide object for other peptide for getting the mass\n\n\t\n\tvar peptideData = null;\n\t\n\tif ( this.currentPeptideNumber == 1 ) {\n\t\t\n\t\tpeptideData = this.peptideData2;\n\t} else {\n\t\t\n\t\tpeptideData = this.peptideData1;\n\t}\n\t\n\tvar otherPeptide = \n\t\tnew Peptide(peptideData.sequence,\n\t\t\t\toptions.staticMods /* staticModifications */, \n\t\t\t\tpeptideData.variableMods /* varModifications */, \n\t\t\tundefined /* ntermModification */, \n\t\t\tundefined /* ctermModification */, \n\t\t\tundefined /* maxNeutralLossCount */, \n\t\t\tundefined /* loopLinkData */, \n\t\t\tundefined /* crossLinkData */,\n\t\t\tpeptideData.label);\n\t\n\t// From \"options\" defaults:\n// ntermMod: 0, // additional mass to be added to the n-term\n// ctermMod: 0, // additional mass to be added to the c-term\n// maxNeutralLossCount: 1,\n\n\n\t\n\tthis.otherPeptide = otherPeptide;\n\t\n\t//\tpeptideData# = { sequence: , variableMods: [ ] }\n}", "getPredictionId(prediction) {\n return prediction.id;\n }", "function predict(){\n clarifai.predict('http://farm3.static.flickr.com/2161/2141620332_2b741028b3.jpg', 'beard', cb).then(\n promiseResolved,\n promiseRejected \n );\n}", "function onLinkRated() {\r\n\tvar taskIdx = selectedTaskIdx();\r\n\tvar search = getSearch(taskIdx, gCurrentSearch.query);\r\n\tif (search) {\r\n\t\tvar link = getLink(search, gCurrentSearch.url);\r\n\t\tif (link) {\r\n\t\t\tvar rating = this.id == \"helpful_button\" ? HELPFUL_RATING : UNHELPFUL_RATING;\r\n\t\t\taddLinkRated(taskIdx, search.query, link.url, link.title, rating, true);\r\n\t\t\tupdateSearchHistory();\r\n\t\t\tswitchToSearch();\r\n\t\t}\r\n\t}\r\n}", "async createLink () {\n\t\tconst thing = this.codemark || this.review || this.codeError;\n\t\tconst type = (\n\t\t\t(this.codemark && 'c') ||\n\t\t\t(this.review && 'r') ||\n\t\t\t(this.codeError && 'e')\n\t\t);\n\t\tconst attr = (\n\t\t\t(this.codemark && 'codemarkId') ||\n\t\t\t(this.review && 'reviewId') ||\n\t\t\t(this.codeError && 'codeErrorId')\n\t\t);\n\t\tconst linkId = UUID().replace(/-/g, '');\n\t\tthis.url = this.makePermalink(linkId, this.isPublic, thing.teamId, type);\n\t\tconst hash = this.makeHash(thing, this.markers, this.isPublic, type);\n\n\t\t// upsert the link, which should be collision free\n\t\tconst update = {\n\t\t\t$set: {\n\t\t\t\tteamId: thing.teamId,\n\t\t\t\tmd5Hash: hash,\n\t\t\t\t[attr]: thing.id\n\t\t\t}\n\t\t};\n\n\t\tconst func = this.request.data.codemarkLinks.updateDirectWhenPersist ||\n\t\t\tthis.request.data.codemarkLinks.updateDirect;\t// allows for migration script\n\t\tawait func.call(\n\t\t\tthis.request.data.codemarkLinks,\n\t\t\t{ id: linkId },\n\t\t\tupdate,\n\t\t\t{ upsert: true }\n\t\t);\n\t}", "function updateLink(p) {\n var d = p.data()[0];\n var u = d.src.data()[0], v = d.dst.data()[0];\n var [x1, y1] = u.center();\n var [x2, y2] = v.center();\n var a = Math.atan2(y1 - y2, x2 - x1);\n [x1, y1] = u.border(a);\n [x2, y2] = v.border(a + PI);\n p.select(\"path\").attr(\"d\", pathLinspace(x1, y1, x2, y2, 15));\n p.select(\"line\").attr(\"x1\", x1).attr(\"x2\", x2)\n\t.attr(\"y1\", y1).attr(\"y2\", y2);\n if (d.lbl)\n\tp.select(\"foreignObject\")\n\t.attr(\"x\", (x1 + x2) * .5 - 30.)\n\t.attr(\"y\", (y1 + y2) * .5 - 13);\n}", "function construct_prediction_url(data){\n return \"<REMOVED>\" \n + \"?predict_char=true\"\n + \"&predict_level=\" + data.predict_level\n + \"&predict_vocation=\" + data.predict_vocation\n + \"&predict_world=\" + data.predict_world\n + \"&predict_melee=\" + data.predict_melee\n + \"&predict_dist=\" + data.predict_dist\n + \"&predict_mlevel=\" + data.predict_mlevel;\n}", "function predict(imageUrl) {\n clarifaiApp.models.predict(Clarifai.GENERAL_MODEL, imageUrl).then(\n function(response) {\n console.log(\"Image: \" + imageUrl);\n\n // If the response in not Ok, just return.\n if (response.status.description !== \"Ok\") {\n console.log(\"Invalid response\");\n console.log(response);\n return;\n }\n\n for (var i = 0; i < response.outputs.length; i++) {\n var output = response.outputs[i];\n var concepts = output.data.concepts;\n if (concepts === undefined) {\n console.log(\"Invalid output\");\n console.log(output);\n continue;\n }\n // Loop over all the concepts present in the image and\n // store them in the DB.\n for (var ci = 0; ci < concepts.length; ci++) {\n var concept = concepts[ci];\n storeInDB(concept);\n }\n }\n },\n function(err) {\n console.error(err);\n }\n );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
picture API phonegap, see more at
function getPicture() { navigator.camera.getPicture(getPictureSuccess, getPictureError, { resQual: 50, destinationType: Camera.DestinationType.FILE_URI, correctOrientation: true }) }
[ "function pictureRetrieve(device){\r\n\tvar myJSONP = new Request.JSONP({\r\n \turl: 'http://www.ifixit.com/api/0.1/device/' + device.device,\r\n \tcallbackKey: 'jsonp',\r\n \tonComplete: function(data){\r\n \t // the request was completed.\r\n \t //Check if image exists, if not placeholder\r\n \t if (data.image.text !== undefined){\r\n \t \taddTo(device.device,data.image.text + \".thumbnail\");\r\n \t\t} else {\r\n \t\t\taddTo(device.device,'http://www.ifixit.com/Misc/fist.png');\r\n \t\t}\r\n \t}\r\n\t}).send();\r\n}", "function takePicture() {\n navigator.camera.getPicture(\n function(uri) {\n var img = document.getElementById('camera_image');\n img.style.visibility = \"visible\";\n img.style.display = \"block\";\n img.src = uri;\n document.getElementById('camera_status').innerHTML = \"Picture Taken Successfully\";\n },\n function(e) {\n console.log(\"Error getting picture: \" + e);\n document.getElementById('camera_status').innerHTML = \"Error getting picture.\";\n },\n { quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});\n }", "function addTodoPicture() {\n navigator.camera.getPicture(addTodo, function () {\n alert('Failed to get camera.');\n }, {\n quality: 50,\n destinationType: Camera.DestinationType.DATA_URL,\n targetWidth: 100,\n targetHeight: 100\n });\n}", "function takePic() {\n console.log('click');\n navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });\n}", "function cameraImportPicture() {\n // try to get image from photo library\n navigator.camera.getPicture(onSuccess, onFail, { quality: 50,\n destinationType: Camera.DestinationType.FILE_URI,\n sourceType: Camera.PictureSourceType.PHOTOLIBRARY\n });\n \n function onSuccess(imageURL) {\n // hide error message (if displayed)\n var error = document.getElementById('errorinfo');\n error.style.display = \"none\";\n \n // display image\n var image = document.getElementById('imgSelected');\n image.src = imageURL;\n image.style.display = \"block\";\n }\n \n function onFail(message) {\n // display error message\n var error = document.getElementById('errorinfo');\n error.style.display = \"block\";\n error.innerHTML = message;\n }\n \n}", "function onPictureError() {\r\n}", "function takephoto() {\n navigator.camera.getPicture(onSuccess, onFail, {\n quality: 100,\n correctOrientation: true,\n });\n}", "function takePicOfTheUser() {\n}", "function PictureSourceType() {}", "function upload_picture(uploader_phone, picture_url, stream_id, tinyPicture_url, caption)\n{\n\tvar API_URL = \"http://75.101.134.112/stream/1.0/api/upload_picture.php?uploader_phone=\" + uploader_phone + \"&picture_url=\" + picture_url + \"&stream_id=\" + stream_id + \"&tinyPicture_url\" + tinyPicture_url + \"&caption=\" + caption;\n\tconsole.log(API_URL);\n\n\t$.getJSON(API_URL, function (data) \n\t{\n\t\tconsole.log(data);\n\t});\n}", "function obtenerFotoPerfil(){\n FB.api('/me/picture?width=325&height=325', function(responseI) {\n var profileImage = responseI.data.url;\n var fbid=jQuery(\"#pictureP\").val(profileImage);\n\n\n //console.log(profileImage);\n });\n}", "function get_picture_metadata(picture_id, viewer_phone)\n{\n\tvar API_URL = \"http://75.101.134.112/stream/1.0/api/get_picture_metadata.php?picture_id=\" + picture_id + \"&viewer_phone=\" +viewer_phone;\n\tconsole.log(API_URL);\n\n\t$.getJSON(API_URL, function (data) \n\t{\n\t\tconsole.log(data);\n\t});\n}", "function getImage() {\n // Retrieve image file location from specified source\n \n\tnavigator.camera.getPicture(abrirProfFotoSubir, function(message) {\n\t\t\tnavigator.notification.alert('Error al recuperar una imagen',okAlert,'MIA','Cerrar');\n },{\n quality: 50,\n destinationType: navigator.camera.DestinationType.FILE_URI,\n sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY\n }\n );\n \n \n\n }", "getPicture(type) {\n this.loading = true;\n if (window.cordova) {\n // if on device use native plugins\n this.commonService\n .getPictures(type)\n .then((imageData) => {\n this.uploadImage(imageData);\n })\n .catch((err) => this.failPromise(err));\n }\n else {\n // if on device use browser file upload\n this.fileInputButton.nativeElement.click();\n }\n }", "function createPictureFromMedia()\n {\n if (config.type !== 'video') {\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height); \n } else {\n ctx.drawImage(source[0], 0, 0, canvas.width, canvas.height); \n }\n \n result = canvas[0].toDataURL('image/'+config.pictureFormat, config.quality);\n\n //Callback function with parameters\n if ($.isFunction(config.callback)) {\n config.callback.call(this, {url: result, name: config.pictureName, extension: config.pictureFormat, fullPictureName: config.pictureName+'.'+config.pictureFormat});\n } \n }", "function getPicture(url) {\n\t// body..\n\tvar picture = {};\n\tpicture.OverlayUrl = url;\n\tpicture.x = 0;\n\tpicture.y = 0;\n\tpicture.w = 60;\n\tpicture.h = 60;\n\tpicture.img = document.createElement(\"img\");\n\tpicture.img.src = url;\n\tpicture.img.onload = function(){ // 影像載入後,執行裡面的內容\n\t\tdrawImageOnCanvas(picture.img,picture.x,picture.y,picture.w,picture.h);\n\t}\n\tpicture.OverlayImage = gapi.hangout.av.effects.createImageResource(picture.OverlayUrl);\n\tpicture.Overlay = picture.OverlayImage.createOverlay({\n\t\t'scale': {\n\t\t\t'magnitude': 0.125,\n\t\t\t'reference': gapi.hangout.av.effects.ScaleReference.WIDTH\n\t\t}\n\t});\n \tpicture.Overlay.setPosition(picture.x,picture.y);\n\tpicture.Overlay.setVisible(true);\n\tpictureArray.push(picture);\n}", "function capturarImagemFachada(){\n navigator.camera.getPicture(capturarSuccessFachada, capturarFail,\n {\n destinationType : Camera.DestinationType.FILE_URI,\n sourceType : Camera.PictureSourceType.CAMERA\n });\n}", "function getUrlPic(picture) { return \"url(\"+host+picture+\")\"; }", "function setPicture(picture){\n\t\tdocument.getElementById(\"myImg\").src = picture;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively expand segment groups for all the child outlets
expandChildren(ngModule, routes, segmentGroup) { // Expand outlets one at a time, starting with the primary outlet. We need to do it this way // because an absolute redirect from the primary outlet takes precedence. const childOutlets = []; for (const child of Object.keys(segmentGroup.children)) { if (child === 'primary') { childOutlets.unshift(child); } else { childOutlets.push(child); } } return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(childOutlets) .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["concatMap"])(childOutlet => { const child = segmentGroup.children[childOutlet]; // Sort the routes so routes with outlets that match the segment appear // first, followed by routes for other outlets, which might match if they have an // empty path. const sortedRoutes = sortByMatchingOutlets(routes, childOutlet); return this.expandSegmentGroup(ngModule, sortedRoutes, child, childOutlet) .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])(s => ({ segment: s, outlet: childOutlet }))); }), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["scan"])((children, expandedChild) => { children[expandedChild.outlet] = expandedChild.segment; return children; }, {}), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["last"])()); }
[ "expandChildren(injector, routes, segmentGroup) {\n // Expand outlets one at a time, starting with the primary outlet. We need to do it this way\n // because an absolute redirect from the primary outlet takes precedence.\n const childOutlets = [];\n for (const child of Object.keys(segmentGroup.children)) {\n if (child === 'primary') {\n childOutlets.unshift(child);\n } else {\n childOutlets.push(child);\n }\n }\n return (0,rxjs__WEBPACK_IMPORTED_MODULE_1__.from)(childOutlets).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.concatMap)(childOutlet => {\n const child = segmentGroup.children[childOutlet];\n // Sort the routes so routes with outlets that match the segment appear\n // first, followed by routes for other outlets, which might match if they have an\n // empty path.\n const sortedRoutes = sortByMatchingOutlets(routes, childOutlet);\n return this.expandSegmentGroup(injector, sortedRoutes, child, childOutlet).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.map)(s => ({\n segment: s,\n outlet: childOutlet\n })));\n }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_20__.scan)((children, expandedChild) => {\n children[expandedChild.outlet] = expandedChild.segment;\n return children;\n }, {}), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_21__.last)());\n }", "expandChildren(ngModule, routes, segmentGroup) {\n // Expand outlets one at a time, starting with the primary outlet. We need to do it this way\n // because an absolute redirect from the primary outlet takes precedence.\n const childOutlets = [];\n for (const child of Object.keys(segmentGroup.children)) {\n if (child === 'primary') {\n childOutlets.unshift(child);\n }\n else {\n childOutlets.push(child);\n }\n }\n return (0,rxjs__WEBPACK_IMPORTED_MODULE_1__.from)(childOutlets)\n .pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.concatMap)(childOutlet => {\n const child = segmentGroup.children[childOutlet];\n // Sort the routes so routes with outlets that match the segment appear\n // first, followed by routes for other outlets, which might match if they have an\n // empty path.\n const sortedRoutes = sortByMatchingOutlets(routes, childOutlet);\n return this.expandSegmentGroup(ngModule, sortedRoutes, child, childOutlet)\n .pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.map)(s => ({ segment: s, outlet: childOutlet })));\n }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_9__.scan)((children, expandedChild) => {\n children[expandedChild.outlet] = expandedChild.segment;\n return children;\n }, {}), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.last)());\n }", "expandChildren(ngModule, routes, segmentGroup) {\n // Expand outlets one at a time, starting with the primary outlet. We need to do it this way\n // because an absolute redirect from the primary outlet takes precedence.\n const childOutlets = [];\n for (const child of Object.keys(segmentGroup.children)) {\n if (child === 'primary') {\n childOutlets.unshift(child);\n }\n else {\n childOutlets.push(child);\n }\n }\n return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__[\"from\"])(childOutlets)\n .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"concatMap\"])(childOutlet => {\n const child = segmentGroup.children[childOutlet];\n // Sort the routes so routes with outlets that match the the segment appear\n // first, followed by routes for other outlets, which might match if they have an\n // empty path.\n const sortedRoutes = sortByMatchingOutlets(routes, childOutlet);\n return this.expandSegmentGroup(ngModule, sortedRoutes, child, childOutlet)\n .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"map\"])(s => ({ segment: s, outlet: childOutlet })));\n }), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"scan\"])((children, expandedChild) => {\n children[expandedChild.outlet] = expandedChild.segment;\n return children;\n }, {}), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"last\"])());\n }", "expandChildren(ngModule, routes, segmentGroup) {\n return waitForMap(segmentGroup.children, (childOutlet, child) => this.expandSegmentGroup(ngModule, routes, child, childOutlet));\n }", "processChildren(config, segmentGroup) {\n const children = [];\n for (const childOutlet of Object.keys(segmentGroup.children)) {\n const child = segmentGroup.children[childOutlet];\n // Sort the config so that routes with outlets that match the one being activated appear\n // first, followed by routes for other outlets, which might match if they have an empty path.\n const sortedConfig = sortByMatchingOutlets(config, childOutlet);\n const outletChildren = this.processSegmentGroup(sortedConfig, child, childOutlet);\n if (outletChildren === null) {\n // Configs must match all segment children so because we did not find a match for this\n // outlet, return `null`.\n return null;\n }\n children.push(...outletChildren);\n }\n // Because we may have matched two outlets to the same empty path segment, we can have multiple\n // activated results for the same outlet. We should merge the children of these results so the\n // final return value is only one `TreeNode` per outlet.\n const mergedChildren = mergeEmptyPathMatches(children);\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n // This should really never happen - we are only taking the first match for each outlet and\n // merge the empty path matches.\n checkOutletNameUniqueness(mergedChildren);\n }\n sortActivatedRouteSnapshots(mergedChildren);\n return mergedChildren;\n }", "processChildren(injector, config, segmentGroup) {\n return (0,rxjs__WEBPACK_IMPORTED_MODULE_1__.from)(Object.keys(segmentGroup.children)).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.concatMap)(childOutlet => {\n const child = segmentGroup.children[childOutlet];\n // Sort the config so that routes with outlets that match the one being activated\n // appear first, followed by routes for other outlets, which might match if they have\n // an empty path.\n const sortedConfig = sortByMatchingOutlets(config, childOutlet);\n return this.processSegmentGroup(injector, sortedConfig, child, childOutlet);\n }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_20__.scan)((children, outletChildren) => {\n if (!children || !outletChildren) return null;\n children.push(...outletChildren);\n return children;\n }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_23__.takeWhile)(children => children !== null), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_24__.defaultIfEmpty)(null), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_21__.last)(), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.map)(children => {\n if (children === null) return null;\n // Because we may have matched two outlets to the same empty path segment, we can have\n // multiple activated results for the same outlet. We should merge the children of\n // these results so the final return value is only one `TreeNode` per outlet.\n const mergedChildren = mergeEmptyPathMatches(children);\n if (NG_DEV_MODE$6) {\n // This should really never happen - we are only taking the first match for each\n // outlet and merge the empty path matches.\n checkOutletNameUniqueness(mergedChildren);\n }\n sortActivatedRouteSnapshots(mergedChildren);\n return mergedChildren;\n }));\n }", "function mergeTrivialChildren(s) {\n if (s.numberOfChildren === 1 && s.children[_PRIMARY_OUTLET]) {\n var c = s.children[_PRIMARY_OUTLET];\n return new _UrlSegmentGroup(s.segments.concat(c.segments), c.children);\n }\n\n return s;\n }", "function mergeTrivialChildren(s) {\n if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {\n var c = s.children[PRIMARY_OUTLET];\n return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);\n }\n\n return s;\n }", "function mergeTrivialChildren(s) {\n if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {\n var c = s.children[PRIMARY_OUTLET];\n return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);\n }\n\n return s;\n }", "updateSegmentGroup(rootNode, oldSegmentGroup, newSegmentGroup) {\n const queue = [];\n let currentTree = rootNode;\n while (currentTree) {\n Object.keys(currentTree.children).forEach((outletName) => {\n if (currentTree.children[outletName] === oldSegmentGroup) {\n if (newSegmentGroup) {\n currentTree.children[outletName] = newSegmentGroup;\n }\n else {\n delete currentTree.children[outletName];\n }\n }\n queue.push(currentTree.children[outletName]);\n });\n currentTree = queue.shift();\n }\n }", "function mergeTrivialChildren(s) {\n if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {\n var c = s.children[PRIMARY_OUTLET];\n return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);\n }\n\n return s;\n}", "function flattenAreaPaths(){\n loadedAreaPaths\n .forEach(function(areaPath,parentIndex){\n if(areaPath.hasChildren){\n var parentAreaPathName=areaPath.name;\n var j = 1;\n if(areaPath.children!==undefined){\n areaPath.children.forEach(function(childAreaPath){\n //set the name child area path name\n childAreaPath.name = parentAreaPathName+\"\\\\\"+childAreaPath.name;\n //insert the child area path in the parent area path\n loadedAreaPaths.splice((parentIndex + j),0,childAreaPath);\n j = j + 1;\n });\n //make the children flag false to prevent a stack overflow\n areaPath.hasChildren = false;\n\n //and then nulify the children\n areaPath.children = undefined;\n\n //recursively call method so as to flatten the array\n flattenAreaPaths();\n }\n }\n });\n }", "function mergeTrivialChildren(s) {\n if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {\n const c = s.children[PRIMARY_OUTLET];\n return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);\n }\n return s;\n}", "function expandSuperGroups(group, groups) {\n for (var i in groups) {\n // For all Groups\n for (var j = 0; j < groups[i].layers.length; j++) {\n // And all their layers\n if (groups[i].layers[j].name === group.name) {\n // If the layer is the one to be expanded\n expandLayer(groups[i], j, group); // Expand the Layer\n j = 0; // Need to go back to be sure not to skip Layers\n }\n }\n }\n}", "function EBX_GroupHavingChildren() {}", "assignSubSegments() {\n this.forEach((phdrA)=>{\n this.forEach((phdrB)=>{\n if(phdrB == phdrA)\n return;\n if((phdrB.p_offset+phdrB.p_filesz)>(phdrA.p_offset+phdrA.p_filesz))\n return;\n let dist = phdrB.p_offset - phdrA.p_offset;\n if(dist < 0)\n return;\n if(phdrA.parentSegment && (phdrA.parentSegment==phdrB))\n return;\n if(phdrB.parentSegment) {\n // Check existing parent segment has closer offset\n if(dist > (phdrB.p_offset - phdrB.parentSegment.p_offset))\n return;\n // Remove from existing parent segment\n phdrB.parentSegment.subSegments.splice(phdrB.parentSegment.subSegments.indexOf(phdrB),1);\n }\n phdrB.parentSegment = phdrA;\n phdrA.subSegments.push(phdrB);\n });\n });\n }", "split() {\n const center = this.aabb.center;\n const octants = [[],[],[],[],[],[],[],[]];\n\n const midX = center[0], midY = center[1], midZ = center[2];\n\n let vec, child;\n for (let i = 0, children = this.children, len = children.length; i < len; ++i) {\n child = children[i];\n vec = child.aabb.center;\n octants[((vec[0] < midX) << 2) + ((vec[1] < midY) << 1) + (vec[2] < midZ)].push(child);\n }\n\n const splitGroups = [];\n \n for (let i = 0, len = octants.length, octant; i < len, octant = octants[i]; ++i) {\n if (octant.length > 0) {\n const group = new SplitGroup(this, {}, octant);\n group.parent = this;\n splitGroups.push(group);\n }\n }\n\n this.children = splitGroups;\n }", "function expandAll() {\n expand(root);\n //root.children.forEach(expand);\n update(root);\n }", "expandAllRows() {\r\n const that = this;\r\n\r\n if (!that.hasAttribute('hierarchy') || that.grouping) {\r\n return;\r\n }\r\n\r\n function expand(siblings) {\r\n for (let i = 0; i < siblings.length; i++) {\r\n const sibling = siblings[i];\r\n\r\n if (sibling.leaf) {\r\n continue;\r\n }\r\n\r\n if (sibling.children) {\r\n expand(sibling.children);\r\n }\r\n\r\n if (!sibling.expanded) {\r\n that.expandRow(sibling.$.id);\r\n }\r\n }\r\n }\r\n\r\n expand(that.dataSource.boundHierarchy);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endregion region Relations Initializes model relations. Called from store when adding a record.
initRelations() { const me = this, relations = me.constructor.relations; if (!relations) return; // TODO: feels strange to have to look at the store for relation config but didn't figure out anything better. // TODO: because other option would be to store it on each model instance, not better... me.stores.forEach((store) => { if (!store.modelRelations) store.initRelations(); // TODO: not at all tested for multiple stores, can't imagine it works as is const relatedRecords = []; store.modelRelations && store.modelRelations.forEach((config) => { relatedRecords.push({ related: me.initRelation(config), config }); }); store.updateRecordRelationCache(me, relatedRecords); }); }
[ "initRelations() {\n const me = this,\n relations = me.constructor.relations;\n if (!relations) return; // TODO: feels strange to have to look at the store for relation config but didn't figure out anything better.\n // TODO: because other option would be to store it on each model instance, not better...\n\n me.stores.forEach(store => {\n if (!store.modelRelations) store.initRelations(); // TODO: not at all tested for multiple stores, can't imagine it works as is\n\n const relatedRecords = [];\n store.modelRelations && store.modelRelations.forEach(config => {\n relatedRecords.push({\n related: me.initRelation(config),\n config\n });\n });\n store.updateRecordRelationCache(me, relatedRecords);\n });\n }", "initRelation() {\n _object.hasMany(version)\n version.belongsTo(_object)\n }", "constructor() { \n \n ItemRelations.initialize(this);\n }", "setRelations () {\n this.config.hasMany.forEach(relation => {\n this[relation] = app.model(relation, false).belongsTo(this)\n })\n }", "loadRelations() {\n this.__loadRelations();\n }", "setRelations () {\n this[hasMany].forEach(relation => {\n this[relation] = (new Blueprint(relation)).belongsTo(this)\n })\n }", "defineRelation() {\n if (this.definition.type === relation_types_1.RelationTypes.one2one\n || this.definition.type === relation_types_1.RelationTypes.one2n) {\n this.relation = {};\n }\n else {\n this.relation = [];\n }\n }", "_initHasManyRelations() {\n const relations = this.constructor.hasMany;\n if (_.isObject(relations)) {\n for (let name in relations) {\n const relation = relations[name];\n const foreignKey = (relation.foreignKey || s.decapitalize(this.constructor.modelName) + 'Id');\n const model = this.constructor._getModel(relation, name);\n if (model === null) {\n continue;\n }\n Object.defineProperty(this, name, {\n get: () => {\n return this.constructor.scope({\n model: model.name,\n selector: {\n [foreignKey]: this.id\n },\n });\n },\n writeable: false,\n });\n }\n }\n }", "constructor() { \n \n GroupRelations.initialize(this);\n }", "constructor() { \n \n CampaignRelations.initialize(this);\n }", "function init() {\n console.log(\"initting\")\n // Create tables\n filesystem.readdirSync(pathToModels).forEach(function(name){\n var object = require(\".\" + pathToModels + \"/\" + name);\n var options = object.options || {}\n var modelName = name.replace(/\\.js$/i, \"\");\n models[modelName] = sequelize.define(modelName, object.model, options);\n if(\"relations\" in object){\n relationships[modelName] = object.relations;\n }\n });\n\n // Create relationships\n for(var name in relationships){\n var relation = relationships[name];\n for(var relName in relation){\n var related = relation[relName];\n //console.log(related)\n models[name][relName](models[related]);\n }\n }\n }", "_addRelationPropertyFields() {\n for (const rel of this._relationships) {\n switch (rel.type) {\n case 'oto':\n relations_1.relations.addOne2One(rel);\n break;\n case 'otm':\n relations_1.relations.addOne2Many(rel);\n break;\n case 'mtm':\n relations_1.relations.addMany2Many(rel);\n break;\n default:\n throw Error(`Unknown relation type: ${rel.type}`);\n }\n }\n }", "constructor() { \n \n OrganizationRelationship.initialize(this);\n }", "constructor() { \n \n EventResourceAllOfRelationships.initialize(this);\n }", "static associate(models) {\n // define association here\n // this.hasMany(models.StepIngredient);\n this.belongsTo(models.Recipe);\n }", "constructor() { \n \n TagRelations.initialize(this);\n }", "static associate(models) {\n // define association here\n this.belongsTo(models.RecipeCategory);\n this.belongsTo(models.Recipe);\n }", "constructor() { \n \n CampaignRelationsItems.initialize(this);\n }", "constructor() { \n \n PresenterRelations.initialize(this);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Agrega orden por columna y tipo de orden
function agregarOrden(columna, tipo) { return ' ORDER BY p.' + columna + ' ' + tipo; }
[ "function ConverteValorColunas(data, type, row)\n {\n //console.log(data);\n //console.log('type: ' + type);\n //console.log(typeof data);\n\n if (typeof data !== 'string') {\n if (typeof data === 'boolean')\n return (data) ? 'Ativo' : 'Inativo';\n else\n return data; \n } else\n {\n\n // var checagem = Date.parse(data);\n if (/^[\\d]{4}-[\\d]{2}-[\\d]{2}/.test(data))\n return moment(data).format('DD/MM/YYYY');\n else\n return data;\n\n }\n }", "type(o) {\n if (o === true) return type;\n if (isString(o)) {\n if (columnTypes[o]) {\n type = columnTypes[o](sample);\n return column;\n } else {\n throw new Error('unknown column type: ' + o);\n }\n }\n return type.name();\n }", "function getColumnaEntradas(columnas, tipoTablaJugadores) {\r\n\t\t\tswitch (tipoTablaJugadores) {\r\n\t\t\t\tcase TABLA_PLANTILLA_PROPIA: return columnas[11];\r\n\t\t\t\tcase TABLA_PLANTILLA_AJENA: return columnas[12];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_PROPIA: return columnas[12];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_AJENA: return columnas[10];\r\n\t\t\t}\r\n\t\t}", "function getColumnaEdad(columnas, tipoTablaJugadores) {\r\n\t\t\tswitch (tipoTablaJugadores) {\r\n\t\t\t\tcase TABLA_PLANTILLA_PROPIA: return columnas[4];\r\n\t\t\t\tcase TABLA_PLANTILLA_AJENA: return columnas[5];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_PROPIA: return columnas[3];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_AJENA: return columnas[3];\r\n\t\t\t}\r\n\t\t}", "function getColumnaRemate(columnas, tipoTablaJugadores) {\r\n\t\t\tswitch (tipoTablaJugadores) {\r\n\t\t\t\tcase TABLA_PLANTILLA_PROPIA: return columnas[9];\r\n\t\t\t\tcase TABLA_PLANTILLA_AJENA: return columnas[10];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_PROPIA: return columnas[10];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_AJENA: return columnas[8];\r\n\t\t\t}\r\n\t\t}", "function _getColumnType(k, v) {\n\n var reDate = /(^\\d{1,4}[\\.|\\\\/|-]\\d{1,2}[\\.|\\\\/|-]\\d{1,4})(\\s*(?:0?[1-9]:[0-5]|1(?=[012])\\d:[0-5])\\d\\s*[ap]m)?$/;\n\n if(k==='id') {\n return 'id';\n }\n else if(_.endsWith(k, '_id')) {\n return 'foreign-key';\n }\n else {\n switch(typeof v) {\n case 'object':\n if(Array.isArray(v)) {\n return 'array';\n }\n return 'object';\n case 'string':\n if(v.length>150) {\n return 'text';\n }\n else if(reDate.test(v)) {\n return 'date';\n }\n return 'string';\n default:\n return typeof v;\n } // switch\n }\n\n }", "function renderColumnaBecario(data, type, full, meta) {\n // tablaBecariosDirigidos.registros[data.becarioId] = data;\n return '<td>' +\n '<a ng-click=\"setVariable('+'&#39;'+'consultaInformesBecariosDirigidosGet'+'&#39;'+', busqueda)\" ui-sref=\"InformeBecarioDetails({id: ' + data.becarioId + '})\" title=\"Detalles\">'\n + data.claveBecario + ' - '\n + data.nombreBecario +\n '</a>'\n '</td>'\n }", "function getColumnaAgresividad(columnas, tipoTablaJugadores) {\r\n\t\t\tswitch (tipoTablaJugadores) {\r\n\t\t\t\tcase TABLA_PLANTILLA_PROPIA: return columnas[12];\r\n\t\t\t\tcase TABLA_PLANTILLA_AJENA: return columnas[13];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_PROPIA: return columnas[13];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_AJENA: return columnas[11];\r\n\t\t\t}\r\n\t\t}", "function getColumnaMediaReal(columnas, tipoTablaJugadores) {\r\n\t\t\tswitch (tipoTablaJugadores) {\r\n\t\t\t\tcase TABLA_PLANTILLA_PROPIA: return columnas[16];\r\n\t\t\t\tcase TABLA_PLANTILLA_AJENA: return columnas[16];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_PROPIA: return columnas[16];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_AJENA: return columnas[14];\r\n\t\t\t}\r\n\t\t}", "columnInfo() {\n const column = this.single.columnInfo;\n\n // The user may have specified a custom wrapIdentifier function in the config. We\n // need to run the identifiers through that function, but not format them as\n // identifiers otherwise.\n const table = this.client.customWrapIdentifier(this.single.table, identity);\n\n return {\n sql: `\n select \n rlf.rdb$field_name as name,\n fld.rdb$character_length as max_length,\n typ.rdb$type_name as type,\n rlf.rdb$null_flag as not_null\n from rdb$relation_fields rlf\n inner join rdb$fields fld on fld.rdb$field_name = rlf.rdb$field_source\n inner join rdb$types typ on typ.rdb$type = fld.rdb$field_type\n where rdb$relation_name = '${table}'\n `,\n output(resp) {\n const [rows, fields] = resp;\n\n const maxLengthRegex = /.*\\((\\d+)\\)/;\n const out = reduce(\n rows,\n function (columns, val) {\n const name = val.NAME.trim();\n columns[name] = {\n type: val.TYPE.trim().toLowerCase(),\n nullable: !val.NOT_NULL,\n // ATSTODO: \"defaultValue\" não implementado\n // defaultValue: null,\n };\n\n if (val.MAX_LENGTH) {\n columns[name] = val.MAX_LENGTH;\n }\n\n return columns;\n },\n {}\n );\n console.log('Resultado columnInfo', { out, column });\n return (column && out[column]) || out;\n },\n };\n }", "function getType(column){\n var n = 0\n var d = 0\n for (i=1;i<column.length;i++) {\n // console.log(typeof column[i])\n if(isNaN(column[i])&&!isNaN(Date.parse(column[i]))){\n d=d+1\n }\n if(!isNaN(Number(column[i]))){\n n=n+1\n }\n }\n if(n==column.length-1){\n return \"Numeric\"\n }else{\n if(d==column.length-1){\n return \"Date\"\n }else{\n return \"Varchar\"\n }\n }\n}", "function getColumnTable(tabla){\n columns = {\n \"beneficiarios\" : [\n {\"column\":\"tipoDocumento_abr\", \"label\":\"Tipo documento\"},\n {\"column\":\"numeroDocumento\", \"label\":\"N&uacute;mero documento\"}, \n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"fechaNacimiento\", \"label\":\"Fecha nacimiento\"},\n {\"column\":\"direccion\", \"label\":\"Direcci&oacute;n\"},\n {\"column\":\"accion\", \"label\":\"Acci&oacute;n\"}\n ],\n \"beneficiarios_prod\" : [\n {\"column\":\"aplica\", \"label\":\"\"},\n {\"column\":\"tipoDocumento_abr\", \"label\":\"Tipo documento\"},\n {\"column\":\"numeroDocumento\", \"label\":\"Numero documento\"}, \n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"fechaNacimiento\", \"label\":\"Fecha nacimiento\"},\n {\"column\":\"direccion\", \"label\":\"Direcci&oacute;n\"},\n {\"column\":\"tarifa\", \"label\":\"Tarifa mensual\", \"format\":\"miles\"}\n ],\n \"programacion\" : [\n {\"column\":\"fechahora\", \"label\":\"Fecha y hora\"},\n {\"column\":\"comando\", \"label\":\"Comando\"},\n {\"column\":\"accion\", \"label\":\"Acciones\"}\n ],\n \"1\" : [\n {\"column\":\"identificacion\", \"label\":\"Identificaci&oacute;n\"},\n {\"column\":\"nombre\", \"label\":\"Nombre\"}, \n {\"column\":\"telefono\", \"label\":\"Tel&eacute;fono\"},\n {\"column\":\"email\", \"label\":\"Correo el&eacute;ctronico\"},\n {\"column\":\"direccion\", \"label\":\"Direcci&oacute;n\"}, \n {\"column\":\"login\", \"label\":\"Login\"}, \n {\"column\":\"rol\", \"label\":\"rol\"},\n {\"column\":\"estado\", \"label\":\"Estado\"},\n {\"column\":\"editar\", \"label\":\"Editar\"},\n {\"column\":\"activar\", \"label\":\"Activar\"},\n {\"column\":\"eliminar\", \"label\":\"Desactivar\"} \n ], \n \"2\" : [\n {\"column\":\"identificacion\", \"label\":\"Nit\"},\n {\"column\":\"nombre\", \"label\":\"Nombre\"},\n {\"column\":\"telefono\", \"label\":\"Tel&eacute;fono\"},\n {\"column\":\"email\", \"label\":\"Correo el&eacute;ctronico\"},\n {\"column\":\"direccion\", \"label\":\"Direcci&oacute;n\"}, \n {\"column\":\"login\", \"label\":\"Login\"},\n {\"column\":\"rol\", \"label\":\"rol\"}, \n {\"column\":\"estado\", \"label\":\"Estado\"},\n {\"column\":\"editar\", \"label\":\"Editar\"}, \n {\"column\":\"activar\", \"label\":\"Activar\"},\n {\"column\":\"eliminar\", \"label\":\"Desactivar\"} \n ],\n \"pedido\" : [\n {\"column\":\"cancelar\", \"label\":\"Accion\"}, \n {\"column\":\"codigo\", \"label\":\"Codigo\"},\n {\"column\":\"nombre\", \"label\":\"Nombre\"},\n {\"column\":\"valor\", \"label\":\"Valor\", \"format\":\"miles\"},\n {\"column\":\"cantidad\", \"label\":\"Cantidad\", \"format\":\"numero\"},\n {\"column\":\"subtotal\", \"label\":\"Subtotal\", \"format\":\"miles\"},\n {\"column\":\"impuesto\", \"label\":\"Impuesto\", \"format\":\"miles\"},\n {\"column\":\"descuento\", \"label\":\"Descuento\", \"format\":\"miles\"},\n {\"column\":\"promo_nombre\", \"label\":\"Promoci&oacute;n\"},\n {\"column\":\"promo_descuento\", \"label\":\"Descuento promoci&oacute;n\", \"format\":\"miles\"},\n {\"column\":\"total\", \"label\":\"Total\", \"format\":\"miles\"}\n ],\n \"gestion_pedidos\" : [\n {\"column\":\"codigo\", \"label\":\"Codigo\"},\n {\"column\":\"usuario_nombre\", \"label\":\"Usuario\"},\n {\"column\":\"subtotal\", \"label\":\"Subtotal\", \"format\":\"miles\"},\n {\"column\":\"impuesto\", \"label\":\"Impuesto\", \"format\":\"miles\"},\n {\"column\":\"descuento\", \"label\":\"Descuento\", \"format\":\"miles\"},\n {\"column\":\"promo_descuento\", \"label\":\"Promoci&oacute;n\", \"format\":\"miles\"},\n {\"column\":\"total\", \"label\":\"Total\", \"format\":\"miles\"},\n {\"column\":\"detalle\", \"label\":\"Detalle\"},\n {\"column\":\"confirmar\", \"label\":\"Confirmar\"},\n {\"column\":\"cancelar\", \"label\":\"Cancelar\"}\n ],\n \"promo_producto\":[\n {\"column\":\"cod_producto\", \"label\":\"Codigo\"},\n {\"column\":\"nom_producto\", \"label\":\"Nombre\"},\n {\"column\":\"valor_descuento\", \"label\":\"Descuento\"},\n {\"column\":\"dia_aplica\", \"label\":\"D&iacute;a\"},\n {\"column\":\"hora_inicial\", \"label\":\"Hora inicio\"},\n {\"column\":\"hora_final\", \"label\":\"Hora fin\"},\n {\"column\":\"descripcion\", \"label\":\"Descripcion\"} \n ],\n \"factura_venta\":[\n {\"column\":\"codigo\", \"label\":\"Codigo\"},\n {\"column\":\"nombre_usuario\", \"label\":\"Nombre Usuario\"},\n {\"column\":\"impuesto\", \"label\":\"Impuesto\", \"format\":\"miles\"},\n {\"column\":\"descuento\", \"label\":\"Descuento\", \"format\":\"miles\"},\n {\"column\":\"promocion\", \"label\":\"Promocion\", \"format\":\"miles\"},\n {\"column\":\"subtotal\", \"label\":\"Sub total\", \"format\":\"miles\"},\n {\"column\":\"total\", \"label\":\"Total\", \"format\":\"miles\"},\n {\"column\":\"fecha_creacion\", \"label\":\"Fecha creaci&oacute;n\"} \n ],\n \"beneficiarios_cotiza\" : [ \n {\"column\":\"tipoNroId\", \"label\":\"Identificación\"},\n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"des_parentesco\", \"label\":\"Parantesco\"},\n {\"column\":\"soporte_eps\", \"label\":\"Soporte EPS\"},\n {\"column\":\"salud\", \"label\":\"Declaración de salud\"},\n {\"column\":\"nombreProducto\", \"label\":\"Producto\"}\n ],\n \"beneficiarios_cotiza2\" : [ \n {\"column\":\"tipoNroId\", \"label\":\"Identificación\"},\n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"des_parentesco\", \"label\":\"Parantesco\"},\n {\"column\":\"soporte_eps\", \"label\":\"Soporte EPS\"}, \n {\"column\":\"nombreProducto\", \"label\":\"Producto\"}\n ],\n \"realizar_pago\" : [\n {\"column\":\"producto\", \"label\":\"Producto\"},\n {\"column\":\"afiliados\", \"label\":\"Afiliados\"}, \n {\"column\":\"tarifa\", \"label\":\"Tarifa mensual\", \"format\":\"miles\"}\n ],\n \"beneficiarios_contrato\" : [\n {\"column\":\"tipoDocumento_abr\", \"label\":\"Tipo de identificación\"},\n {\"column\":\"numeroDocumento\", \"label\":\"Número de identificación\"}, \n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"telefono\", \"label\":\"Teléfono\"},\n {\"column\":\"correo\", \"label\":\"Correo electrónico\"},\n {\"column\":\"tarifaProducto\", \"label\":\"Tarifa mensual\"}\n ],\n \"Contactos\" : [\n {\"column\":\"lugar\", \"label\":\"Lugar\"},\n {\"column\":\"telefono\", \"label\":\"Número de Telefono\"},\n {\"column\":\"lugar2\", \"label\":\"Lugar\"},\n {\"column\":\"telefono2\", \"label\":\"Número de Telefono\"}\n ]\n };\n\n return columns[tabla];\n \n}", "function getColumnTable(tabla){\ncolumns = {\n \"permisos_campo_rol\" : [\n {\"column\":\"nom_tabla\", \"label\":\"Tabla\"},\n {\"column\":\"nom_campo\", \"label\":\"Campo\"}, \n {\"column\":\"ch_estado\", \"label\":'Estado <br><input type=\"checkbox\" id=\"chcAll\">', \"attribs\":'class=\"center_th\"', \"attribs_head\":'class=\"center_th\"'}\n ],\n \"observacion_persona\" : [\n {\"column\":\"documento_ovp\", \"label\":\"Documento\"},\n {\"column\":\"nombre_ovp\", \"label\":\"Nombre\"},\n {\"column\":\"cargo_ovp\", \"label\":\"Cargo\"},\n {\"column\":\"quitar\", \"label\":'Quitar'}\n ],\n \"reporte_terreno\": [\n {\"column\":\"predial_terreno\", \"label\":\"No. Predial\"},\n {\"column\":\"nombre_proyecto\", \"label\":\"Nombre Proyecto\"},\n {\"column\":\"codigonal\", \"label\":\"Código Nacional\"},\n {\"column\":\"calidad_bien\", \"label\":\"Calidad del Bien\"},\n {\"column\":\"direccion_oficial\", \"label\":\"Dirección Oficial\"},\n {\"column\":\"tipo_bien\", \"label\":\"Tipo de Bien\"},\n {\"column\":\"barrio\", \"label\":\"Barrio\"},\n {\"column\":\"comuna\", \"label\":\"Comuna\"},\n {\"column\":\"n_folio\", \"label\":\"No. Folio\"},\n {\"column\":\"modo_adquisicion\", \"label\":\"Modo Adquisición\"},\n {\"column\":\"dependencia\", \"label\":\"Organismo\"},\n {\"column\":\"nombrecomun_p\", \"label\":\"Nombre Común\"},\n {\"column\":\"tipo_documento\", \"label\":\"Tipo de Documento\"},\n {\"column\":\"numero_documento\", \"label\":\"Número de Documento\"},\n {\"column\":\"fecha_doc\", \"label\":\"Fecha Documento\"},\n {\"column\":\"notaria_doc\", \"label\":\"Notaría\"},\n {\"column\":\"area_cesion\", \"label\":\"Área Cesión\"},\n {\"column\":\"area_actual\", \"label\":\"Área Actual\"},\n {\"column\":\"area_sicat\", \"label\":\"Área Sicat\"},\n {\"column\":\"area_terreno\", \"label\":\"Área en SAP\"}\n ]\n };\n\n return columns[tabla];\n\n}", "_updateColumnTypes(soqlRow) {\n var undefinedColumns = this.columns.filter((c) => c.ctype === 'null');\n if (!undefinedColumns.length) return;\n\n var definedSoqlCols = soqlRow.filter((c) => c.ctype !== 'null');\n //We want the set of columns that are defined for the value, but are not defined\n //for the layer. These are the columns that we will replace in the layer.\n var toAdd = definedSoqlCols.filter((valCol) => {\n return _.find(undefinedColumns, (col) => valCol.rawName === col.rawName);\n });\n\n if (toAdd.length === 0) return;\n\n this.columns = renameColumns(this.columns.map((col) => {\n var valCol = _.find(toAdd, (newCol) => newCol.rawName === col.rawName);\n var newCol;\n if (valCol) {\n newCol = new valCol.constructor(valCol.rawName);\n this.log.debug(`Replacing old undefined column ${valCol.rawName} with new ${valCol.constructor.name} column`);\n }\n return newCol || col;\n }));\n }", "function ComputeColumnDataType ()\n\t{\n\tfor (var i=0; i<this.Columns.length; i++) \n\t\t{\n\t\t\n\t\tthis.Columns[i].type = \"numeric\";\n\n\t\tfor (var j=0; j<this.Lines.length; j++) \n\t\t\t{\n\t\t\tif (!IsNumeric (this.Lines[j][i].data))\n\t\t\t\t{\n\t\t\t\tthis.Columns[i].type = \"text\";\n\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\t// make sure we don't have any comma separators for appropriate sorting\t\t\t\t\n\t\t\t\tthis.Lines[j][i].data = removestr (this.Lines[j][i].data, \",\");\n\t\t\t\t}\n\t\t\t}\t\t\n\t\t}\n\t}", "function Column_CHAR() {}", "function getColumnaPase(columnas, tipoTablaJugadores) {\r\n\t\t\tswitch (tipoTablaJugadores) {\r\n\t\t\t\tcase TABLA_PLANTILLA_PROPIA: return columnas[8];\r\n\t\t\t\tcase TABLA_PLANTILLA_AJENA: return columnas[9];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_PROPIA: return columnas[9];\r\n\t\t\t\tcase TABLA_CEDIDOS_PLANTILLA_AJENA: return columnas[7];\r\n\t\t\t}\r\n\t\t}", "_field(column) {\n var matches = column.type.match(/(\\w+)(?:\\(([\\d,]+)\\))?/);\n var field = {};\n field.type = matches[1];\n field.length = matches[2];\n field.use = field.type;\n\n if (field.length) {\n var length = field.length.split(',');\n field.length = Number.parseInt(length[0]);\n if (length[1]) {\n field.precision = Number.parseInt(length[1]);\n }\n }\n\n field.type = this.dialect().mapped(field);\n return field;\n }", "function columnNormalizer (column, dialect) {\n\n var typeString\n var typeOfColumn = typeof column\n if (typeOfColumn === 'string') {\n typeString = column\n column = {\n type: {\n name: typeString\n }\n }\n } else if (typeOfColumn !== 'object' || column === null) {\n column = {}\n } else {\n if (typeof column.type === 'string') {\n typeString = column.type\n column.type = {\n name: typeString\n }\n } else {\n delete column.type\n }\n } \n\n if (!column.type) {\n return column\n }\n var type = column.type\n type.name = typeString = typeString.trim().toUpperCase()\n\n var arr = type.name.match(/^([A-Z\\s]+)\\s*(?:\\(([0-9,\\s]+)\\))?$/i)\n\n if(arr === null) {\n return column\n }\n\n var t\n if (arr[1] && (t = dialect.types[arr[1]])) {\n type.name = dialect.types[arr[1]].name\n\n if (t.range === undefined) t.range = [0,0]\n\n arr[2] = arr[2] ? arr[2].split(',').map(function(e) { return parseInt(e) }) : []\n if (t.range[0] <= arr[2].length && arr[2].length <= t.range[1]) {\n type.params = arr[2]\n } else {\n type.name = typeString\n }\n } else {\n type.name = typeString\n }\n\n return column\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if this collection is accessed over a network connection. readonly attribute boolean isRemote;
get isRemote() { //exchWebService.commonAbFunctions.logInfo("exchangeAbFolderDirectory: isRemote\n"); return true; }
[ "_isRemoteCollection() {\n // XXX see #MeteorServerNull\n return this._connection && this._connection !== Meteor.server;\n }", "_isRemoteCollection() {\n // XXX see #MeteorServerNull\n return this._connection && this._connection !== Meteor.server;\n }", "static get isRemoteConnected() {}", "isConnected() {\n return Boolean(this.client);\n }", "isConnected() {\n return this.transport.isConnected();\n }", "isReachable() {\n\t\treturn (this.connectionState === CONSTANTS.CONNECTION_STATE.CONNECTED);\n\t}", "is_connected() {\n return this.connected\n }", "function hasNetworkConnection() {\n\tif(navigator && navigator.connection && typeof(Connection) != \"undefined\") {\n\t\t// under cordova with network information plugin\n\t\treturn navigator.connection.type != Connection.NONE;\n\t} else {\n\t\t// without cordova or network information plugin\n\t\treturn true;\n\t}\n}", "get isBoundToVpc() {\n return !!this._connections;\n }", "get reachable() {\n\t\treturn this.reachability.length > 0;\n\t}", "isConnected() {\n return !!this.remoteStream;\n }", "async isConnected() {\n try {\n const res = await this.provider.rawCall('getnetworkinfo');\n return typeof res === 'object';\n } catch (err) {\n return false;\n }\n }", "isLocalServer(ip = this.get('serverIp')) {\n return ip === 'localhost' || ip === '127.0.0.1';\n }", "get connectionStatus() {\n return this._isConnected;\n }", "function isRemote(db) {\n\t if (typeof db._remote === 'boolean') {\n\t return db._remote;\n\t }\n\t /* istanbul ignore next */\n\t if (typeof db.type === 'function') {\n\t guardedConsole('warn',\n\t 'db.type() is deprecated and will be removed in ' +\n\t 'a future version of PouchDB');\n\t return db.type() === 'http';\n\t }\n\t /* istanbul ignore next */\n\t return false;\n\t}", "function checkNetworkServices()\n{\n return (Titanium.Network.online) ? true : false;\n}", "function isCommunicating () {\n\n return communicating;\n\n}", "isConnected() {\n return this.connectionState() === 'open';\n }", "function currentNetwork() {\n return connectedNetwork;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to properly format output of a object property or array key takes key, value, and level of nesting
function genPropOutput( key, val, level ){ // set level to 0 if not found level = level || 0; // indent 4 spaces per level of nesting for( var i = 0; i < level; i++ ){ cOutput += ' '; } // check value type, only accept strings, numbers, objects and arrays switch( typeof val ){ // if its a string or number, just output directly case 'string' : case 'number' : cOutput += key + ' : ' + val + '\r\n'; break; // if its an array or object, start a new level by recursing into this function case 'object' : cOutput += key + ' ¬ ' + '\r\n'; if( val.length ){ for( var j = 0; j < val.length; j++ ){ genPropOutput( j + 1, val[j], level + 1 ); } } else{ for( k in val ){ genPropOutput( k, val[k], level + 1 ); } } break; } }
[ "function printObjectProperties(val, config, indentation, depth, refs, printer) {\n var result = '';\n var keys = getKeysOfEnumerableProperties(val);\n\n if (keys.length) {\n result += config.spacingOuter;\n var indentationNext = indentation + config.indent;\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var name = printer(key, config, indentationNext, depth, refs);\n var value = printer(val[key], config, indentationNext, depth, refs);\n result += indentationNext + name + ': ' + value;\n\n if (i < keys.length - 1) {\n result += ',' + config.spacingInner;\n } else if (!config.min) {\n result += ',';\n }\n }\n\n result += config.spacingOuter + indentation;\n }\n\n return result;\n }", "function formatProperty(property, output) {\n output.push(\" /**\\n\");\n output.push(property.desc.replace(/^( )?/gm, \" * \"));\n output.push(\"\\n\");\n output.push(\" */\\n\");\n output.push(\" \" + property.name + \": \" + (property.type || \"any\") + \";\\n\");\n}", "function printObjectProperties(val, config, indentation, depth, refs, printer) {\n var result = '';\n var keys = _Object$keys(val).sort();\n var symbols = getSymbols(val);\n\n if (symbols.length) {\n keys = keys.filter(function (key) {\n return !isSymbol(key);\n }).concat(symbols);\n }\n\n if (keys.length) {\n result += config.spacingOuter;\n\n var indentationNext = indentation + config.indent;\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var name = printer(key, config, indentationNext, depth, refs);\n var value = printer(val[key], config, indentationNext, depth, refs);\n\n result += indentationNext + name + ': ' + value;\n\n if (i < keys.length - 1) {\n result += ',' + config.spacingInner;\n } else if (!config.min) {\n result += ',';\n }\n }\n\n result += config.spacingOuter + indentation;\n }\n\n return result;\n }", "function appendProperty(formattedSchema, property, _nestingLevel) {\n let nestingLevel = _nestingLevel;\n const propertyKey = property[0];\n const propertyValue = property[1];\n\n if (propertyValue.meta && (propertyValue.meta.deprecated || propertyValue.meta.hidden)) {\n return;\n }\n\n formattedSchema.push({\n name: nestingLevel\n ? `<subpropertyAnchor><inlineCode>${propertyKey}</inlineCode></subpropertyAnchor>`\n : `#### \\`${propertyKey}\\``,\n description: createDescription(property),\n nestingLevel,\n });\n\n nestingLevel++;\n\n if (propertyValue.properties) {\n Object.entries(propertyValue.properties).forEach(subproperty => {\n appendProperty(formattedSchema, subproperty, nestingLevel);\n });\n } //Note: sub-properties are sometimes nested within \"items\"\n else if (propertyValue.items && propertyValue.items.properties) {\n Object.entries(propertyValue.items.properties).forEach(subproperty => {\n appendProperty(formattedSchema, subproperty, nestingLevel);\n });\n }\n}", "function nestedStringify(obj) {\n if (!isObject(obj)) {\n return JSON.stringify(obj);\n }\n\n return Object.keys(obj).reduce(function (acc, key, i, arr) {\n acc += util.format('\\n \"%s\": %s', key, JSON.stringify(obj[key]));\n if (i !== arr.length - 1) {\n acc += ',';\n }\n\n return acc;\n }, '{') + '\\n }';\n}", "function json_exploder(json_input,loop){\n\n\tvar json_output = \"<dl>\";\n\tvar i;\n\tvar x;\n\n\t// we may have only a string - this should fix it\n\tif (typeof(json_input)==\"string\"){\n\t\treturn json_input;\n\t}\n\t\n\tfor (x in json_input){\n\tlogMessage(typeof(json_input[x]));\n\n\t\tif (typeof(json_input[x]) == \"object\" && json_input[x] !== null){\n\n\t\t\tfor (i=0;i<loop;i++){ json_output +=\"&nbsp; \"; } // indent\n\n\t\t\tif (x != \"0\"){\n\t\t\t\tjson_output += \"<span style='text-decoration:underline; margin-top:5px; display:inline-block;'>\" + x + \"</span>\";\n\t\t\t}\n\t\t\tjson_output += json_exploder(json_input[x],loop+1);\n\t\t\tjson_output += \"\";\n\n\t\t} else if (typeof(json_input[x])== \"string\") {\n\t\t\tfor (i=1;i<loop;i++){\n\t\t\t\tjson_output +=\"&nbsp; \";\n\t\t\t}\n\t\t\tjson_output += \"\" + x.camelCaseToRegular() + \": \" + json_input[x] + \"<br />\";\n\t\t}\n\t}\n\treturn json_output + \"</dl>\";\n}", "function stringify(obj) {\n // This variable will hold the entire stringified input\n let key = '';\n\n // If the input is an array\n if (Array.isArray(obj)) {\n key += 'A'; // Add 'A' to `key` to signify the object is an array\n // Iterate the array\n for (const elm of obj) {\n // This variable will hold the stringified array\n const item = \n // If the element is an object, make a recursive call\n typeof elm === 'object' \n ? stringify(elm)\n : // If the element is a primitive, we don't need to do anything special\n `${elm}`;\n\n // Concatenate the stringified array to the stringbuilder\n key += item;\n }\n }\n // If the input is an object\n else {\n key += 'O';\n // Traverse the object\n for (const k in obj) {\n const item =\n typeof obj[k] === 'object'\n ? `${k}${stringify(obj[k])}` // ${k} = preserve the key that holds the object\n : `${k}${obj[k]}`;\n key += item;\n }\n }\n\n return key;\n}", "function pretty(obj, space) {\n if (space == null) space = 4;\n var backslashN = '\\n';\n var indent = '',\n subIndents = '';\n if (typeof space == 'number') {\n for (var i = 0; i < space; i++) {\n indent += ' ';\n }\n } else if (typeof space == 'string') {\n indent = space;\n }\n function str(obj) {\n var jsType = Object.prototype.toString.call(obj);\n if (jsType.match(/object (String|Date|Function|JSON|Math|RegExp)/)) {\n return JSON.stringify(String(obj));\n } else if (jsType.match(/object (Number|Boolean|Null)/)) {\n return JSON.stringify(obj);\n } else if (jsType.match(/object Undefined/)) {\n return JSON.stringify('undefined');\n } else {\n if (jsType.match(/object (Array|Arguments|Map|Set)/)) {\n if (jsType.match(/object (Map|Set)/)) {\n // function and type in js es6 or above\n obj = Array.from(obj);\n }\n var partial = [];\n subIndents = subIndents + indent;\n var len = obj.length;\n for (var i = 0; i < len; i++) {\n partial.push(str(obj[i]));\n }\n var result =\n len == 0\n ? '[]'\n : indent.length\n ? '[' +\n backslashN +\n subIndents +\n partial.join(',' + backslashN + subIndents) +\n backslashN +\n subIndents.slice(indent.length) +\n ']'\n : '[' + partial.join(',') + ']';\n subIndents = subIndents.slice(indent.length);\n return result;\n } else if (\n jsType.match(\n /object (Object|Error|global|Window|HTMLDocument)/i\n ) ||\n obj instanceof Error\n ) {\n var partial = [];\n subIndents = subIndents + indent;\n var ownProps = Object.getOwnPropertyNames(obj);\n // Object.keys returns obj's own enumerable property names(no use for...in loop because including inherited enumerable properties from obj's prototype chain\n // Object.getOwnPropertyNames = Object.keys + obj's own non-enumerable property names\n var len = ownProps.length;\n for (var i = 0; i < len; i++) {\n partial.push(\n str(ownProps[i]) +\n (indent.length ? ': ' : ':') +\n str(obj[ownProps[i]])\n );\n }\n var result =\n len == 0\n ? '{}'\n : indent.length\n ? '{' +\n backslashN +\n subIndents +\n partial.join(',' + backslashN + subIndents) +\n backslashN +\n subIndents.slice(indent.length) +\n '}'\n : '{' + partial.join(',') + '}';\n subIndents = subIndents.slice(indent.length);\n return result;\n } else {\n return JSON.stringify(String(obj));\n }\n }\n }\n function decycle(obj) {\n // the function can solve circular structure like JSON.decycle, the return value can be decoded by JSON.retrocycle(JSON.parse())\n var arrParents = [];\n return (function derez(obj, path) {\n var jsType = Object.prototype.toString.call(obj);\n if (\n jsType.match(\n /object (String|Date|Function|JSON|Math|RegExp|Number|Boolean|Null|Undefined)/\n )\n ) {\n return obj;\n } else {\n if (jsType.match(/object (Array|Arguments|Map|Set)/)) {\n var len = arrParents.length;\n for (var i = 0; i < len; i++) {\n // arr like [obj, '$']\n var arr = arrParents[i];\n if (obj === arr[0]) {\n return { $ref: arr[1] };\n }\n }\n arrParents.push([obj, path]);\n var newObj = [];\n if (jsType.match(/object (Map|Set)/)) {\n // function and type in js es6 or above\n obj = Array.from(obj);\n }\n var length = obj.length;\n for (var i = 0; i < length; i++) {\n newObj[i] = derez(obj[i], path + '[' + i + ']');\n }\n return newObj;\n } else {\n var len = arrParents.length;\n for (var i = 0; i < len; i++) {\n // arr like [obj, '$']\n var arr = arrParents[i];\n if (obj === arr[0]) {\n return { $ref: arr[1] };\n }\n }\n arrParents.push([obj, path]);\n var newObj = {};\n var ownProps = Object.getOwnPropertyNames(obj);\n var length = ownProps.length;\n for (var i = 0; i < length; i++) {\n newObj[ownProps[i]] = derez(\n obj[ownProps[i]],\n path + '[' + JSON.stringify(ownProps[i]) + ']'\n );\n }\n return newObj;\n }\n }\n })(obj, '$');\n }\n return str(decycle(obj));\n}", "function EZformatObjectProcess(obj, name, opts, local)\n\t{\n\t\t//----- Determine data type and other properties used for displaying\n\t\tvar i, e, html, idx, key, note, value, results;\n\n\t\t//NOTE: use opts object for global data updated at all recurrsion level\n\t\t//\t\tuse local for data passed to down to recursive calls but not changed or returned\n\n\t\tvar formatOpts = '.formatOpts'.ov(local, [])\n\t\tformatOpts = EZ.toArray(formatOpts, ',');\n\t\t\n\t\t//----- Make copy of local data\n\t\tvar local = {\t\t\t\t\t\t\t\t\t\n\t\t\tdepth: '.depth'.ov(local, 0),\n\t\t\tdotName: '.dotName'.ov(local, ''),\n\t\t\tisArray: '.isArray'.ov(local, false),\n\t\t\tformatOpts: formatOpts\n\t\t}\n\t\t\n\t\t// local legacy variables previously passed as arguments\n\t\tvar depth = local.depth;\n\t\tvar isArray = local.isArray;\n\t\t\n\t\t//---------------------------------------------------------------------------\n\t\t//***** If Not object -- addend formatted value and bail -- depth==0 ?? *****\n\t\t//------------------------------------------------------------\n\t\tif ('object function'.indexOf(typeof obj) == -1 || (depth==0 && obj == null))\n\t\t{\n\t\t\tif (depth != 0) debugger;\n\t\t\thtml = getValue(obj);\n\t\t\tif (opts.htmlformat && depth == 0)\n\t\t\t\thtml = '<span class=\"top\" id=\"EZ_' + opts.hashTime + '_0\">' \n\t\t\t\t\t + html + '</span>\\n';\n\t\t\treturn appendText(html);\n\t\t}\n\t\t\n\t\tvar spaces = EZ.constant.spaces.substring(0, depth*opts.indentsize);\n\t\tvar spacesPlus = spaces + EZ.constant.spaces.substring(0,opts.indentsize);\n\t\tvar spacesPlusPlus = spacesPlus + EZ.constant.spaces.substring(0,opts.indentsize);\n\t\t\n\t\tvar isDone = false;\n\t\tvar isHTML = false;\n\t\tvar isEmpty = true;\n\t\tvar type = obj ? EZ.getFunctionParts(obj.constructor)[1] : '';\n\t\tvar processedObj = '';\n\t\t\n\t\tvar isArrayElement = (isArray && !isNaN(name))\t//if recursive call \n\t\tisArray = local.isArray = false;\n\t\tif (EZ.isArrayLike(obj))\n\t\t{\n\t\t\tisArray = local.isArray = true;\n\t\t\ttype = type || (EZ.isArray(obj) ? type + ' array' : 'arraylike object');\n\t\t}\n\t\telse if (obj && obj.constructor == Function)\n\t\t\ttype = (type + ' function').trim();\n\t\t\n\t\telse if (obj.childNodes != EZ.undefined)\n\t\t{\n\t\t\tisHTML = true;\n\t\t\ttype = type || 'html element';\n\t\t}\n\t\ttype = type.trim();\n\n\t\t//------------------------------------------------------------\n\t\t//----- headings for top level Array, Object ot html element\n\t\t//------------------------------------------------------------\n\t\tif (depth == 0)\t\t\n\t\t{\nopts.depth = -1;\nappendCollapse(depth, '');\n\t\t\t\n\t\t\tlocal.dotName = name;\n\t\t\tvar heading = name;\n\t\t\tif (!name || typeof name == 'object') \n\t\t\t{\n\t\t\t\tname = '';\n\t\t\t\tlocal.dotName = type;\n\t\t\t}\n\t\t\tnote = type == 'Array' ? ' [length: ' + obj.length + ']' : ''\n\t\t\theading += '(' + type + ')' + note + ': ';\n\t\t\t\n\t\t\tif (opts.htmlformat)\n\t\t\t\tappendText('<span class=\"top\" id=\"EZ_' + opts.hashTime + '_0\">' \n\t\t\t\t\t\t + heading + '</span>\\n');\n\t\t\telse\n\t\t\t\tappendText(heading + '\\n');\n\t\t\tappendText('\\n');\n\t\t}\n\t\t//--------------------------------------------------------------------\n\t\t//----- depth > 0: headings for embedded Array, Array item, Object ot html element\n\t\t//--------------------------------------------------------------------\n\t\telse\n\t\t{\n\t\t\tif (depth <= 1 && !opts.collapse) appendText('\\n');\n\t\t\t\n\t\t\tappendCollapse(depth, spaces.substr(1));\n\t\t\t\n\t\t\tappendText('#' + (++opts.objectSeqno) + '#');\n\t\t\topts.objectDepth[opts.objectSeqno] = depth;\n\t\t\t\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\t//----- for Array items . . .\n\t\t\t\tif (isArrayElement)\n\t\t\t\t{\n\t\t\t\t\tlocal.dotName = local.dotName + '[' + name + ']';\n\t\t\t\t\t\n\t\t\t\t\tnote = '';\t\t\n\t\t\t\t\tif (isHTML)\n\t\t\t\t\t{\t\t\t\t\t\t\t//if text or similar node, bail after heading\t\n\t\t\t\t\t\tif ('.nodeType'.ov(obj) == EZdisplayObject.HTML_TEXT_NODE)\n\t\t\t\t\t\t{\t\t\t\t\t\t//if text node show text and length\n\t\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\t\tvar text = '.textContent'.ov(obj);\n\t\t\t\t\t\t\ttext = !text ? '' : text.replace(/\\s+/g, ' ').trim();\n\t\t\t\t\t\t\tnote = !text ? ' ' + EZdisplayObject.B_MARKER\n\t\t\t\t\t\t\t\t : ':' + \n\t\t\t\t\t\t\t\t (\n\t\t\t\t\t\t\t\t\t text.length < EZdisplayObject.HTML_TEXT_MAXLINE\n\t\t\t\t\t\t\t\t\t ? text \n\t\t\t\t\t\t\t\t\t : text.substr(0,EZdisplayObject.HTML_TEXT_MAXLINE) \n\t\t\t\t\t\t\t\t\t + EZdisplayObject.MORE_MARKER\n\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t + '[' + text.length + ']';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (!obj.attributes)\n\t\t\t\t\t\t\tisDone = true;\n\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\tappendText('[' + name + ']' \n\t\t\t\t\t\t\t + (type ? ' (' + type + ')' :'') \n\t\t\t\t\t\t\t + note + '\\n');\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t//----- for non-Array items . . .\n\t\t\t\tappendText(' ');\n\t\t\t\tname = EZstripConfigPath(name);\n\t\t\t\tlocal.dotName = local.dotName + '.' + name;\n\n\t\t\t\tnote = (isArray) ? ' [length:' + obj.length + ']' : ''; \n\t\t\t\tappendText(name + ' (' + type + ')' + note + ':\\n');\n\t\t\t\tif (isDone) break;\n\t\t\t\t\n\t\t\t\t//----- check if maxobject depth reached\n\t\t\t\tif (depth >= opts.maxdepth) \n\t\t\t\t{\n\t\t\t\t\tappendText(spacesPlusPlus + EZdisplayObject.MORE_MARKER);\n\t\t\t\t\tappendText('> maxdepth [' + opts.maxdepth + ']\\n');\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//----- check if called to process unique object\n\t\t\t\tif (obj.constructor != document.body.style.constructor)\n\t\t\t\t{\n\t\t\t\t\tprocessedObj = opts.processedObjects[obj];\n\t\t\t\t\tif (processedObj)\n\t\t\t\t\t{\n\t\t\t\t\t\t//========== object already processed ==========\\\\\n\t\t\t\t\t\tprocessedObj.count++;\n\t\t\t\t\t\tnote = spacesPlus + '...repeat of:<a href=\"#' \n\t\t\t\t\t\t\t + opts.hashTime + '_' + processedObj.seqno + '\">' \n\t\t\t\t\t\t\t + processedObj.name + '</a>'\n\t\t\t\t\t\t\t + (opts.showseqno ? ' [' + processedObj.seqno + ']' : '')\n\t\t\t\t\t\t\t + '\\n';\n\t\t\t\t\t\tappendText(note);\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t//===============================================//\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t//============ 1st time object processed ============\\\\\n\t\t\t\t\topts.processedObjects[obj] = {\n\t\t\t\t\t\tname: local.dotName, \n\t\t\t\t\t\tseqno: opts.objectSeqno, \n\t\t\t\t\t\tparentSeqno: parentSeqno,\n\t\t\t\t\t\tcount: 0\n\t\t\t\t\t};\n\t\t\t\t\topts.objectChildNodes[opts.objectSeqno] = parentSeqno\n\t\t\t\t\topts.parentSeqno[opts.objectSeqno] = parentSeqno\n\t\t\t\t\t//===================================================//\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\topts.first = false;\n\t\topts.dotName = local.dotName;\t\t//save for exception reporting\t\t\n\t\tif (isDone)\n\t\t\t return appendCollapse(depth);\n//\t\telse if (depth > 0)\n//\t\t\tappendCollapse(depth)\n\t\t\n\t\tif (opts.quit) \t\t\t\t//safety for unexpected\n\t\t\treturn '...quit ' + local.dotName + '...\\n';\t\n\t\t\n\t\t//-----------------------------------------------------------------------\n\t\t// For each Array item, Object property, html attribute or childNode. . .\n\t\t//------------------------------------------------------------------------\n\t\twhile (true)\n\t\t{\n\t\t\t//=============\\\\\n\t\t\t// HTML elements\\\\\n\t\t\t//===============\\\\\n\t\t\tif (isHTML)\n\t\t\t{\t\n\t\t\t\tEZdisplayObject.HTML_ATTRIBUTES.some(function(attr)\n\t\t\t\t{\n\t\t\t\t\t//var format = EZdisplayObject.HTML_ATTRIBUTES_MAXLINE.indexOf(key) == -1 ? ''\n\t\t\t\t\t//\t\t : 'maxlength:' + EZdisplayObject.HTML_TEXT_MAXLINE;\n\t\t\t\t\tif (attr != 'parent')\n\t\t\t\t\t\tformatItem(attr);\t//, format);\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tvalue = '.parentNode.outerHTML'.ov(obj, '');\n\t\t\t\t\t\tvalue = value.matchPlus(/(<.*?>)/)[1];\n\t\t\t\t\t\tif (value)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (value.length > EZdisplayObject.HTML_TEXT_MAXLINE)\n\t\t\t\t\t\t\t\tvalue = value.substr(0,EZdisplayObject.HTML_TEXT_MAXLINE) + '...';\n\t\t\t\t\t\t\tvalue = displayEncode(value);\n\t\t\t\t\t\t\tformatItem(attr, 'value', value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (opts.quit) return true;\n\t\t\t\t});\n\t\t\t\tif (opts.quit) break;\n\t\t\t\t\n\t\t\t\tfor (var attr=0; attr<obj.attributes.length; attr++)\n\t\t\t\t{\n\t\t\t\t\tformatItem(obj.attributes[attr].name, 'attr');\n\t\t\t\t\tif (opts.quit) break;\n\t\t\t\t}\n\t\t\t\tif (obj.style)\n\t\t\t\t\tformatItem('style', 'ignoreBlank');\n\t\t\t\t\n\t\t\t\tif ('.childNodes.length'.ov(obj))\n\t\t\t\t\tformatItem('childNodes');\n\t\t\t\t\n\t\t\t\tisEmpty = false;\n\t\t\t\tbreak;;\n\t\t\t}\n\t\t\t\n\t\t\t//============\\\\\n\t\t\t// Array items \\\\\n\t\t\t//==============\\\\\n\t\t\tif (isArray)\n\t\t\t{\n\t\t\t\tfor (var idx=0; (idx<obj.length && idx<opts.maxitems); idx++)\n\t\t\t\t{\n\t\t\t\t\tformatItem(idx);\n\t\t\t\t\tif (opts.quit) break;\n\t\t\t\t}\n\t\t\t\tif (obj.length > opts.maxitems)\n\t\t\t\t\tappendText( spacesPlusPlus + EZdisplayObject.MORE_MARKER\n\t\t\t\t\t\t\t + (obj.length - opts.maxitems) + ' more array item(s)\\n');\n\t\t\t}\n\t\t\tif (opts.quit) break;\n\t\t\t\n\t\t\t//==================\\\\\n\t\t\t// Object properties \\\\\n\t\t\t//====================\\\\\n\t\t\tfor (var key in obj)\n\t\t\t{\n\t\t\t\tif (!obj.hasOwnProperty || !obj.hasOwnProperty(key)) continue;\n\t\t\t\tif (isArray\t\t\t\t\t\t//skip Array properties for Arrays\n\t\t\t\t&& (key == 'length' || (!isNaN(key) && key < obj.length))) continue;\n\t\t\t\t\n\t\t\t\tformatItem(key, 'object');\t//process property\n\t\t\t\t\n\t\t\t\tif (opts.quit) break;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t//____________________________________________________________________________________\n\t\t/**\n\t\t *\tformatItem() -- called for each Array item, Object porperty or html attributes\n\t\t *\tIf item obj[key] if Array or Object, formatObject is recurusively called.\n\t\t *\t\t\t\n\t\t *\tARGUMENTS:\n\t\t *\t\tkey\t\tArray index, Object property or html attribute -- designated by format\n\t\t *\t\t\t\n\t\t *\t\tformat \t(string) 'attr' html attribute -- SEE switch below for current fotmats\n\t\t *\t\t\t\t(string) 'ignoreBlank' html element style properties\n\t\t */\n\t\tfunction formatItem(key, format, value)\n\t\t{\n\t\t\tformat = formatOpts.concat(EZ.toArray(format, ','));\n\t\t\t\n\t\t\t// process OBJECT properties typeof object or function -- except null \n\t\t\t// (excluding: html el attribute -- including childnodes and styles)\n\t\t\tif (obj[key] != null\n\t\t\t&& !/(attr|value)/.test(format)\n\t\t\t&& 'object function'.indexOf(typeof obj[key]) != -1)\n\t\t\t{\n\t\t\t\tif (overLimit()) return false;\n\t\t\t\t\n\t\t\t\t//if (typeof(key) == 'function' && skipPrototype(key,Function)) return;\n\t\t\t\tif (typeof(obj[key]) == 'function')\n\t\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t//simple formatting by getValue()\n\t\t\t\t\tif (obj[key].constructor == RegExp) return;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//***********************************************************************************\n\t\t\t\t//===================================================================================\n\t\t\t\tEZformatObjectProcess(obj[key], key, opts, \n\t\t\t\t\t\n\t\t\t\t\tEZ.merge([], local, {depth: depth+1, formatOpts: format\n\t\t\t\t\t\t\t\t /* isArray: local.isArray && format.indexOf('object') != -1 */\n\t\t\t\t}));\n\t\t\t\t//===================================================================================\n\t\t\t\t//***********************************************************************************\n\t\t\t\t\n\t\t\t\topts.firstObject = false;\n\t\t\t\topts.lastTypeObject = true;\n\t\t\t\tisEmpty = false;\n\t\t\t}\n\t\t\t// process NON-OBJECT element within obj\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (!format.length) format = [''];\t//force one pass thru forEachFormatOption()\n\t\t\t\tif (format.some(function forEachFormatOption(fmt)\n\t\t\t\t{\n\t\t\t\t\tswitch(fmt)\n\t\t\t\t\t{\n\t\t\t\t\t\tcase 'attr': \t\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvalue = obj.getAttribute(key) ;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//if (skipPrototype(key)) return;\t\t\t//if not displaying prototype variables\n\t\t\t\t\t\t\tif (isArray && isArrayElement && !isHTML) \n\t\t\t\t\t\t\t\tappendText(spaces);\t\t\t\t\t// extra indentation for array objects\n\t\t\t\t\t\t\tvalue = obj[key];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'ignoreBlank': \t\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!value && value !== 0) return true; \n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'value':\n\t\t\t\t\t\t\tvalue = value;\t\t\t\t\t//debugger placeholder\n\t\t\t\t\t}\n\t\t\t\t}))\n\t\t\t\t{\n\t\t\t\t\treturn false;\t// ' ' + EZdisplayMarker('all values blank');\t\t\n\t\t\t\t}\n\t\t\t\tvalue = getValue(value, format) \t\t\t\t//determine non-object value\n\t\t\t\t\n\t\t\t\tif (isArray && !isArrayElement)\n\t\t\t\t\tkey = spacesPlus.substr(1) + '[' + key + ']'\n\t\t\t\telse\n\t\t\t\t\tkey = spacesPlus + key\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//apply indent to all lines\n\t\t\t\tvalue = (value + '').replace(/\\n/gm,'\\n'+spacesPlusPlus);\n\t\t\t\t\n\t\t\t\t//-----------------------------------------------------------------------------\n\t\t\t\tappendText(key + ': ' + value + '\\n');\n\t\t\t\t//-----------------------------------------------------------------------------\n\n\t\t\t\topts.lastTypeObject = false;\n\t\t\t\tisEmpty = false;\n\t\t\t}\n\t\t}\n\n\t\t//-----------------------------------------------------------------------------\n\t\t//Done iterating at current level if nothing displayed, indicate why\n\t\t//-----------------------------------------------------------------------------\n\t\tif (isEmpty)\t\t\t\t\t\t\t//empty object (must test after function test above)\n\t\t{\n\t\t\tnote = formatOpts.indexOf('ignoreBlank') != -1 \n\t\t\t\t ? 'all values blank' \n\t\t\t\t : 'no elements';\n\t\t\tappendText(spacesPlus + EZdisplayMarker(note) + '\\n');\n\t\t}\n\t\telse \n\t\t{\n\t\t\t// extra indentation for array objects\n\t\t\tif (isArray) appendText(spaces);\n\n\t\t\t// special values: null, function, empty\n\t\t\tif (obj === null)\t\t\t\t\t\t\t//null object\n\t\t\t\tappendText(spacesPlus + EZdisplayObject.MARKER + 'null' + EZdisplayObject.MARKER + '\\n');\n\n\t\t\telse if (obj.constructor == Function)\t\t//function (just show name and paramters)\n\t\t\t{\n\t\t\t\tresults = obj.toString().match(/function\\s*(\\w*)\\s*\\(([^\\)]*)\\)/);\n\t\t\t\tif (results)\n\t\t\t\t\tappendText(spacesPlus + results[0] + '...\\n');\n\t\t\t\telse\t\t\t\t\t\t\t\t\t//name not found (should not get here)\n\t\t\t\t\tappendText(spacesPlus + EZdisplayObject.MARKER+ 'unknown function' + EZdisplayObject.MARKER);\n\t\t\t\topts.lastTypeObject = false;\n\t\t\t}\n\t\t}\n\t\t//===================\n\t\treturn appendCollapse(depth);\n\t\t//===================\n\t\t// remove last newline (it gets added by caller)\n\t\t//EZdisplayObject.display = EZdisplayObject.display.substring(0,EZdisplayObject.display.length-1);\n\t\t//____________________________________________________________________________________\n\t\t/*\n\t\t*\tReturn true if not displaying any more nested objects.\n\t\t*/\n\t\tfunction overLimit()\n\t\t{\n\t\t\tif (opts.objectCount++ < opts.maxobjects) return false;\n\t\t\t\n\t\t\tvar msg = opts.maxobjects + ' objects displayed';\n\t\t\tif (opts.maxprompt)\n\t\t\t{\n\t\t\t\tif (confirm(msg + '\\n\\nDisplay more?'))\n\t\t\t\t{\n\t\t\t\t\topts.objectCount = 0;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tappendText(spacesPlus + EZdisplayObject.MORE_MARKER + msg + '\\n');\n\t\t\topts.quit = true;\n\t\t\treturn true;\n\t\t}\n\t\t//____________________________________________________________________________________\n\t\t/*\n\t\t*\tReturn true if not displaying prototype functions or variables.\n\t\t*\ttype (optional: Function if checking for Function constructor\n\t\t*/\n\t\tfunction skipPrototype(el,type)\n\t\t{\n\t\t\tvar status = false;\n\n\t\t\t//js error from EZupdateFieldList trace after EZclearlist(...)\n\t\t\tif (!opts.showprototype\n\t\t\t&& obj && el && obj[el]\n\t\t\t&& obj[el].constructor\n\t\t\t&& obj[el].constructor.prototype)\n\t\t\t{\n\t\t\t\tif (type && type == Function\n\t\t\t\t&& obj[el].constructor.prototype.constructor == type)\n\t\t\t\t\tstatus = true;\n\n\t\t\t\t//else if (!type && obj[el].constructor.prototype == el)\n\t\t\t\telse if (!type\n\t\t\t\t&& (obj.constructor != Array || isNaN(el))\t//added so array[0] displays\n\t\t\t\t&& obj[el].constructor.prototype == el)\n\t\t\t\t\tstatus = true;\n\t\t\t}\n\t\t\treturn status;\n\t\t}\n\t\t//____________________________________________________________________________________\n\t\t/*\n\t\t*\tdetermine non-object value\n\t\t*/\n\t\tfunction getValue(value, format)\n\t\t{\n\t\t\tvar maxline = '.maxline'.ov(format, opts.maxline);\n\t\t\t\n\t\t\tvar type = typeof(value);\n\t\t\tif (type === 'undefined')\n\t\t\t\tvalue = EZdisplayObject.U_MARKER;\n\n\t\t\telse if (value === '')\n\t\t\t\tvalue = EZdisplayObject.B_MARKER;\n\n\t\t\telse if (value === null)\n\t\t\t\tvalue = EZdisplayObject.N_MARKER;\n\n\t\t\telse if (value === true)\n\t\t\t\tvalue = EZdisplayObject.T_MARKER;\n\n\t\t\telse if (value === false)\n\t\t\t\tvalue = EZdisplayObject.F_MARKER;\n\t\t\t\n\t\t\telse if (type != 'string')\n\t\t\t\tvalue += EZdisplayObject.EOL_MARKER;\n\t\t\t\n\t\t\telse if (value.indexOf(EZdisplayObject.MORE_MARKER) == -1)\n\t\t\t{\t\t\t\t\t\t\t//\". . . [23]\"\n\t\t\t\tvalue = EZstripConfigPath(value);\n\t\t\t\tif (value.length > (opts.maxline + 10))\n\t\t\t\t{\n\t\t\t\t\tvalue = getValueString(value.substr(0,maxline)) \n\t\t\t\t\t\t + EZdisplayObject.MORE_MARKER\n\t\t\t\t\t\t + ' [' + value.length + ']';\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvalue = getValueString(value,format)\n\t\t\t\t\t\t + (!opts.showstrlength ? ''\n\t\t\t\t\t\t : ' [' + value.length + ']');\n\t\t\t\t}\n\t\t\t}\n\t\t\t//----- if legacy type\n\t\t\tif (opts.showtype && !isHTML)\n\t\t\t\tvalue = '(' + type + '): ' + value\n\t\t\t\t\t + (typeof(value) == 'string' \n\t\t\t\t\t && value.indexOf(EZdisplayObject.MORE_MARKER) == -1 ? ''\n\t\t\t\t\t : EZdisplayObject.EOL_MARKER);\n\t\t\t\n\t\t\treturn value;\n\t\t\t\t\n\t\t}\n\t\t//____________________________________________________________________________________\n\t\t/*\n\t\t*\tdisplay string as: \"...\", '...' or :...EOL\n\t\t*/\n\t\tfunction getValueString(value,format)\n\t\t{\n\t\t\t//var isValue = EZ.toArray(format, ',').indexOf('value') != -1;\n\t\t\tif (isHTML)\n\t\t\t{\n\t\t\t\treturn value \n\t\t\t\t\t + (value.right(3) == '...' ? ''\n\t\t\t\t\t : EZdisplayObject.EOL_MARKER);\n\t\t\t}\n\t\t\tif (opts.showtype)\n\t\t\t\treturn value;\n\t\t\t\t\n\t\t\treturn value.indexOf('\"') == -1 ? '\"' + value + '\"'\n\t\t\t\t : value.indexOf(\"'\") == -1 ? \"'\" + value + \"'\"\n\t\t\t\t : value + EZdisplayObject.EOL_MARKER;\n\t\t}\n\t\t//____________________________________________________________________________________\n\t\t/*\n\t\t*\tEncode html tags when using html formatting\n\t\t*/\n\t\tfunction displayEncode(value)\n\t\t{\n\t\t\treturn value.replace(/</, '&lt;');\n\t\t}\n\t}", "function formatItem(key, format, value)\n\t\t{\n\t\t\tformat = formatOpts.concat(EZ.toArray(format, ','));\n\t\t\t\n\t\t\t// process OBJECT properties typeof object or function -- except null \n\t\t\t// (excluding: html el attribute -- including childnodes and styles)\n\t\t\tif (obj[key] != null\n\t\t\t&& !/(attr|value)/.test(format)\n\t\t\t&& 'object function'.indexOf(typeof obj[key]) != -1)\n\t\t\t{\n\t\t\t\tif (overLimit()) return false;\n\t\t\t\t\n\t\t\t\t//if (typeof(key) == 'function' && skipPrototype(key,Function)) return;\n\t\t\t\tif (typeof(obj[key]) == 'function')\n\t\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t//simple formatting by getValue()\n\t\t\t\t\tif (obj[key].constructor == RegExp) return;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//***********************************************************************************\n\t\t\t\t//===================================================================================\n\t\t\t\tEZformatObjectProcess(obj[key], key, opts, \n\t\t\t\t\t\n\t\t\t\t\tEZ.merge([], local, {depth: depth+1, formatOpts: format\n\t\t\t\t\t\t\t\t /* isArray: local.isArray && format.indexOf('object') != -1 */\n\t\t\t\t}));\n\t\t\t\t//===================================================================================\n\t\t\t\t//***********************************************************************************\n\t\t\t\t\n\t\t\t\topts.firstObject = false;\n\t\t\t\topts.lastTypeObject = true;\n\t\t\t\tisEmpty = false;\n\t\t\t}\n\t\t\t// process NON-OBJECT element within obj\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (!format.length) format = [''];\t//force one pass thru forEachFormatOption()\n\t\t\t\tif (format.some(function forEachFormatOption(fmt)\n\t\t\t\t{\n\t\t\t\t\tswitch(fmt)\n\t\t\t\t\t{\n\t\t\t\t\t\tcase 'attr': \t\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvalue = obj.getAttribute(key) ;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//if (skipPrototype(key)) return;\t\t\t//if not displaying prototype variables\n\t\t\t\t\t\t\tif (isArray && isArrayElement && !isHTML) \n\t\t\t\t\t\t\t\tappendText(spaces);\t\t\t\t\t// extra indentation for array objects\n\t\t\t\t\t\t\tvalue = obj[key];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'ignoreBlank': \t\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!value && value !== 0) return true; \n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'value':\n\t\t\t\t\t\t\tvalue = value;\t\t\t\t\t//debugger placeholder\n\t\t\t\t\t}\n\t\t\t\t}))\n\t\t\t\t{\n\t\t\t\t\treturn false;\t// ' ' + EZdisplayMarker('all values blank');\t\t\n\t\t\t\t}\n\t\t\t\tvalue = getValue(value, format) \t\t\t\t//determine non-object value\n\t\t\t\t\n\t\t\t\tif (isArray && !isArrayElement)\n\t\t\t\t\tkey = spacesPlus.substr(1) + '[' + key + ']'\n\t\t\t\telse\n\t\t\t\t\tkey = spacesPlus + key\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//apply indent to all lines\n\t\t\t\tvalue = (value + '').replace(/\\n/gm,'\\n'+spacesPlusPlus);\n\t\t\t\t\n\t\t\t\t//-----------------------------------------------------------------------------\n\t\t\t\tappendText(key + ': ' + value + '\\n');\n\t\t\t\t//-----------------------------------------------------------------------------\n\n\t\t\t\topts.lastTypeObject = false;\n\t\t\t\tisEmpty = false;\n\t\t\t}\n\t\t}", "function __formatObject()\t\t\t\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 //full functionality\n\t\t\t//-------------------------------------------------------------------------------------\n\t\t\tif (EZ.format.formatObject)\treturn EZ.format.formatObject.apply(this, args);\t\n\t\t\t//-------------------------------------------------------------------------------------\n\t\t\tvar str = value.constructor.prototype.toString.call(value)\t\t//limited functionality\n\t\t\tif (maxchars && str > maxchars)\t\t\n\t\t\t\treturn (value instanceof Array) ? '[]' : '{}';\t\t\t\n\t\t}", "function json_exploder(json_input,loop){\n\n\tvar json_output = \"<dl>\";\n\tvar i;\n\tvar x;\n\n\t// we may have only a string - this should fix it\n\tif (typeof(json_input)==\"string\"){\n\t\treturn json_input;\n\t}\n\t\n\tfor (x in json_input){\n\tlogMessage(typeof(json_input[x]));\n\n\t\tif (typeof(json_input[x]) == \"object\" && json_input[x] !== null){\n\n\t\t\tfor (i=0;i<loop;i++){ json_output +=\"&nbsp; \"; } // indent\n\n\t\t\tif (x != \"0\"){\n\t\t\t\tjson_output += \"<span style='text-decoration:underline; margin-top:5px; display:inline-block;'>\" + x + \"</span>\";\n\t\t\t}\n\t\t\tjson_output += json_exploder(json_input[x],loop+1);\n\t\t\tjson_output += \"\";\n\n\t\t} else if (typeof(json_input[x])== \"string\") {\n\t\t\tfor (i=1;i<loop;i++){\n\t\t\t\tjson_output +=\"&nbsp; \";\n\t\t\t}\n\t\t\tjson_output += \"\" +x + \": \" + json_input[x] + \"<br />\";\n\t\t}\n\t}\n\treturn json_output + \"</dl>\";\n}", "static writeObjectHTML(obj) {\n\t\tvar result = '';\n\t\tObject.keys(obj).forEach(function(key,index) {\n\t\t\tresult += \"<div> <b>\" + DataWriter.getKeyString(key) + '</b> : ';\n\t\t\tif(obj[key] instanceof Object) {\n\t\t\t\t// Recursive call to the method, if there's a nested object, with bootstrap class ml-3 for indentation\n\t\t\t\tresult += \"<div class='ml-3'>\" + DataWriter.writeObjectHTML(obj[key]) + \"</div>\";\n\t\t\t} else {\n\t\t\t\tresult += obj[key];\n\t\t\t}\n\t\t\tresult += '<br> </div>';\n\t\t});\n\t\treturn result;\n\t}", "function printObject(obj) {\n\tconst ind = ' '\n\tlet output = ''\n\tif (!(obj instanceof Array)) {\n\t\tObject.keys(obj).forEach(function (key) {\n\t\t\toutput += '\\n '+key+': '+printValueType(obj[key])+','\n\t\t})\n\t\toutput = '{\\n '+output.slice(0,-1).trim()+'\\n}'\n\t} else {\n\t\tobj.forEach(function (num, i) {\n\t\t\toutput += '\\n '+printValueType(obj[i])+','\n\t\t})\n\t\toutput = '[\\n '+output.slice(0,-1).trim()+'\\n]'\n\t}\n\tif (output.length < 50) output = output.replace(/\\s+/g, ' ')\n\treturn output\n\t\t.split('\\n')\n\t\t.map(function (s) {return ind + s})\n\t\t.join('\\n')\n\t\t.trim()\n}", "function dump(arr,level) {\nvar dumped_text = \"\";\nif(!level) level = 0;\n\n//The padding given at the beginning of the line.\nvar level_padding = \"\";\nfor(var j=0;j<level+1;j++) level_padding += \" \";\n\nif(typeof(arr) == 'object') { //Array/Hashes/Objects\n for(var item in arr) {\n var value = arr[item];\n \n if(typeof(value) == 'object') { //If it is an array,\n dumped_text += level_padding + \"'\" + item + \"' ...\\n\";\n dumped_text += dump(value,level+1);\n } else {\n dumped_text += level_padding + \"'\" + item + \"' => \\\"\" + value + \"\\\"\\n\";\n }\n }\n} else { //Stings/Chars/Numbers etc.\n dumped_text = \"===>\"+arr+\"<===(\"+typeof(arr)+\")\";\n}\nreturn dumped_text;\n}", "function dump(v, howDisplay, recursionLevel) {\n howDisplay = (typeof howDisplay === 'undefined' || howDisplay == '' || howDisplay == 'text') ? \"none\" : howDisplay;\n recursionLevel = (typeof recursionLevel !== 'number') ? 1 : recursionLevel;\n\n\n var vType = typeof v;\n var out = vType;\n\n switch (vType) {\n case \"number\":\n /* there is absolutely no way in JS to distinguish 2 from 2.0\n so 'number' is the best that you can do. The following doesn't work:\n var er = /^[0-9]+$/;\n if (!isNaN(v) && v % 1 === 0 && er.test(3.0))\n out = 'int';*/\n case \"boolean\":\n out += \": \" + v;\n break;\n case \"string\":\n out += \"(\" + v.length + '): \"' + v + '\"';\n break;\n case \"object\":\n //check if null\n if (v === null) {\n out = \"null\";\n\n }\n //If using jQuery: if ($.isArray(v))\n //If using IE: if (isArray(v))\n //this should work for all browsers according to the ECMAScript standard:\n else if (Object.prototype.toString.call(v) === '[object Array]') { \n out = 'array(' + v.length + '): {\\n';\n for (var i = 0; i < v.length; i++) {\n out += repeatString(' ', recursionLevel) + \" [\" + i + \"]: \" + \n dump(v[i], \"none\", recursionLevel + 1) + \"\\n\";\n }\n out += repeatString(' ', recursionLevel) + \"}\";\n }\n else { //if object \n sContents = \"{\\n\";\n cnt = 0;\n for (var member in v) {\n //No way to know the original data type of member, since JS\n //always converts it to a string and no other way to parse objects.\n sContents += repeatString(' ', recursionLevel) + \" \" + member +\n \": \" + dump(v[member], \"none\", recursionLevel + 1) + \"\\n\";\n cnt++;\n }\n sContents += repeatString(' ', recursionLevel) + \"}\";\n out += \"(\" + cnt + \"): \" + sContents;\n }\n break;\n }\n\n if (howDisplay == 'body' || howDisplay == 'html') {\n var pre = document.createElement('pre');\n pre.innerHTML = out;\n document.body.appendChild(pre)\n }\n else if (howDisplay == 'alert') {\n alert(out);\n }\n\n return out;\n}", "async function formatting(object: Object, func: Function, key: string, extra_info: ?Object) {\n const path = key.split('.');\n const last = path[path.length - 1];\n const results = [...Utils.find_popvalue_with_path(object, path)];\n const outer_objects = [...Utils.find_popvalue_with_path(object, path, true)];\n if (results.length > 0) {\n for (const i in results) {\n const result = results[i];\n const outer_object = outer_objects[i];\n outer_object[last] = await func(result, object, key, extra_info);\n }\n }\n return object;\n}", "if (typeof obj[i] == \"object\") { \n if (parent) { dumpProps(obj[i], parent + \".\" + i); } else { dumpProps(obj[i], i); }\n }", "function dump(arr,level) {\n var dumped_text = \"\";\n if(!level) level = 0;\n\t\n //The padding given at the beginning of the line.\n var level_padding = \"\";\n for(var j=0;j<level+1;j++) level_padding += \" \";\n\t\n if(typeof(arr) == 'object') { //Array/Hashes/Objects \n for(var item in arr) {\n var value = arr[item];\n\t\t\t\n if(typeof(value) == 'object') { //If it is an array,\n dumped_text += level_padding + \"'\" + item + \"' ...\\n\";\n dumped_text += dump(value,level+1);\n } else {\n dumped_text += level_padding + \"'\" + item + \"' => \\\"\" + value + \"\\\"\\n\";\n }\n }\n } else { //Stings/Chars/Numbers etc.\n dumped_text = \"===>\"+arr+\"<===(\"+typeof(arr)+\")\";\n }\n return dumped_text;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start the timer for a length determined by the difficulty. Easy > 60 second turn. Medium > 30 second turn. Hard > 15 second turn.
function timerStart () { var sec; if (difficulty === 1) { sec = 60; document.getElementById('time').innerHTML = '∞'; } else if (difficulty === 2) { sec = 30; } else { sec = 15; } if (sec <= 30) { timer = setInterval(function () { document.getElementById('time').innerHTML = sec.toString(); sec--; if (sec < 0) { clearInterval(timer); updateScore(-1); if (multiplayer) { turn = !turn; if (turn) { document.getElementById('player').innerHTML = '2'; } else { document.getElementById('player').innerHTML = '1'; } } document.getElementById('time-background').style.display = 'block'; document.getElementById('time-content').style.display = 'block'; } }, 1000); } }
[ "function startChallengeTimer() {\n // Set the global 'challengeRunning' variable state to on\n showPrompt();\n if (timerState === TIMER_STATES.PAUSED) {\n disableStartButton();\n }\n\n timerState = TIMER_STATES.ACTIVE;\n unSelectAllTimerButtons();\n\n // Get the selected time, turn it into a date object\n let challengeLengthMinutes = $('#timer .minutes').text();\n let challengeLengthSeconds = $('#timer .seconds').text();\n\n // Fast timer for dev purposes\n // let challengeLengthMinutes = 0;\n // let challengeLengthSeconds = 3;\n\n // start the timer based on what's already on the clock\n let challengeLength = new Date( Date.parse( new Date() ) + ( 1 * 1 * challengeLengthMinutes * 60 * 1000 ) + ( 1 * 1 * challengeLengthSeconds * 1000 ) );\n\n // If the challenge is 60m or greater, subtract a second so that the minutes doesn't show '00' in the first second\n if( challengeLengthMinutes >= 60 ) {\n challengeLength.setSeconds( challengeLength.getSeconds() - 1 );\n }\n\n // Call the start timer function\n initializeClock('timer', challengeLength);\n\n // Get the time remaining\n function getTimeRemaining(endtime) {\n let total = Date.parse(endtime) - Date.parse(new Date());\n let seconds = Math.floor((total / 1000) % 60);\n let minutes = Math.floor((total / 1000 / 60) % 60);\n return {\n total,\n minutes,\n seconds\n };\n }\n\n // Function to start the clock\n function initializeClock(id, endtime) {\n clearAllIntervals();\n $('.workoutman--animated').show();\n $('.workoutman--still').hide();\n\n let clock = document.getElementById(id);\n let minutesEl = clock.querySelector('.minutes');\n let secondsEl = clock.querySelector('.seconds');\n\n function updateClock() {\n let t = getTimeRemaining(endtime);\n minutesEl.innerHTML = ('0' + t.minutes).slice(-2);\n secondsEl.innerHTML = ('0' + t.seconds).slice(-2);\n\n if (t.total <= 0) {\n window.clearInterval(timeInterval);\n // $('.timesup').removeClass('hide');\n // $('.illo--animated').hide();\n // $('.illo--still').show();\n showOutOfTime();\n }\n }\n updateClock();\n let timeInterval = setInterval(updateClock, 1000);\n activeIntervals.push(timeInterval)\n }\n}", "function start(){\n\t\t//prompt to start?\n\t\ttimeLeft = setTimeLeft;\n\t\tscore = 0;\n\t\ttimerLoop = setInterval(function() {timerTic() }, 1000);\n\t\tmoleUpLoop = setInterval(function() {moleUp() }, 1000);\n\t\tconsole.log(\"timer started at \",timeLeft,\" \",activeGame);\n\t\t\n\t}", "function startTimer() {\n //set initial timer counter\n $timer.text();\n //set timer 3 minutes interval\n let interval = gameTimeInterval;\n stopTimer();\n gameTimeIntervalId = setInterval(function () {\n interval--;\n if (interval < 0) {\n gameOver(true);\n stopTimer();\n return;\n }\n if (interval >= 0) {\n //update game context time\n gameContext.time = interval;\n const minutes = Math.floor(interval / 60);\n const seconds = interval % 60;\n const time = `${minutes}m ${seconds}s`;\n //update game timer DOM\n $timer.text(time);\n }\n }, 1000);\n}", "function startTimer() {\n if (typeof gameDurationTimer === \"undefined\" && !checkForWinningCondition()) {\n gameDurationTimer = setInterval(keepTrackOfGameDuration, 1000);\n }\n}", "function startHardTimedGame() {\n closePopUps();\n clearAll();\n borisUpHard();\n setInterval(countDownTimer,1000);\n setTimeout(() => timeUp = true, 30000);\n }", "function startTimer() {\n secondsRemaining = parseInt(qs(\"#menu-view select\").value);\n updateDisplayedTime();\n\n timerId = setInterval(advanceTimer, 1000);\n }", "function timerSetup() {\n // MINIGAME 1: 35sec\n if (minigame1) {\n timer = 35;\n }\n // MINIGAME 2: 5sec\n else if (minigame2) {\n timer = 5;\n }\n}", "function startEasyDifficulty() {\n setRefreshRate(250);\n startGame();\n}", "function startTimer () {\n\t\ttime=30;\n\t\tintervalID = setInterval(timer, 1000);\n\n\t}", "function goToTimeTrial( difficulty ){\n\n\tconsole.log(\"MenuManager: \" + difficulty);\n\tgoToGame( TIME_TRIAL, difficulty );\n\n}", "function timer() {\r\n\t\t/* This condition must be true to end the game */\r\n\t\tif ( rugaStates.length == 11 ) {\r\n\t\t\t// Switch off the timer\r\n\t\t\tplayGame = false;\r\n\t\t\t\r\n\t\t\t// End the game\r\n\t\t\tendGame();\r\n\t\t}\r\n\t\t\r\n\t\t/* Timing for when the game is started */\r\n\t\tif ( playGame ) {\r\n\t\t\tscoreTimeout = setTimeout( function() {\r\n\t\t\t\t// Post increment the time spent\r\n\t\t\t\ttimeSpent++;\r\n\t\t\t\t\r\n\t\t\t\t// Display the time spent as the score\r\n\t\t\t\tscore.attr({ text: \"Score: \" + timeSpent });\r\n\t\t\t\t\r\n\t\t\t\t// Adjust the difficulty\r\n\t\t\t\tchallenge.setTimeSpent(timeSpent)\r\n\t\t\t\t\r\n\t\t\t\t// Compute how much time is left\r\n\t\t\t\ttimeEnd = challenge.getTimeLimit() - countdown;\r\n\t\t\t\r\n\t\t\t\t// Display the time left\r\n\t\t\t\ttime.attr({ text: \"Time: \" + timeEnd });\r\n\t\t\t\t\r\n\t\t\t\t// Post increment the countdown variable\r\n\t\t\t\tcountdown++;\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t/* Once the countdown timer is at 0 */\r\n\t\t\t\tif ( timeEnd <= 0 ) {\r\n\t\t\t\t\t// Set the time end to 0\r\n\t\t\t\t\ttimeEnd = 0;\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Reset the countdown\r\n\t\t\t\t\tcountdown = 0;\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Remove the cow instance\r\n\t\t\t\t\tcow.remove();\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Add the state to the list of rugaStates\r\n\t\t\t\t\trugaStates.push( selectedState );\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Display the number of states lost\r\n\t\t\t\t\tinstruction.attr({ text: \"States Lost: \" + rugaStates.length });\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Remove the state name\r\n\t\t\t\t\tstateName.remove();\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Change the colour of the path\r\n\t\t\t\t\tcolourPath( pathString );\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Display a new cow instance\r\n\t\t\t\t\tdisplayCow();\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Call the timer again\r\n\t\t\t\ttimer();\r\n\t\t\t}, 1000 );\r\n\t\t}\r\n\t}", "function startTimer() {\n if(timerStart == true) {\n seconds++;\n\n if(seconds == 60) {\n minutes++;\n seconds = 0;\n }\n if(minutes == 60) {\n hours++;\n minutes = 0;\n }\n\n if(minutes >= 1 && minutes < 2) {\n timer.style.color = \"orange\";\n }\n else if(minutes >= 2) {\n timer.style.color = \"red\";\n }\n else {\n timer.style.color = \"green\";\n }\n\n timer.textContent = hours + \":\" + minutes + \":\" + seconds;\n\n setTimeout(startTimer,1000);\n }\n}", "function startTimer() {\n //pegar os valores do data-time do botao que foi clicado e transformar em int\n const seconds = parseInt(this.dataset.time);\n timer(seconds);\n}", "function startChallenge() {\n clearTimer();\n currentTime = CHALLENGE_TIME;\n toggleChallengeControls();\n updateChallengeText();\n timerID = setInterval(updateChallengeTimer, SECOND);\n }", "function startTimer() {\r\n if (validNumber(duration)) {\r\n createTimer(duration);\r\n } else {\r\n displayWarning();\r\n }\r\n }", "increaseDifficulty() {\n const difficultyIncreaseTime = 10000;\n\n if (new Date() - this.baseTime >= difficultyIncreaseTime) {\n this.gameSpeed = this.gameSpeed * 0.8;\n this.removeInterval(this.interval);\n this.startInterval(this.render, this.gameSpeed);\n this.baseTime = new Date();\n }\n }", "function startTimer_Full() {\n if (!limit_Full) {\n limit_Full = 600; // 10 minutes default\n }\n if (group=='') {\n group = exerciseOptions[Math.floor(Math.random() * 3)];\n }\n timePassed_Full = 0;\n timeLeft_Full = limit_Full;\n clearInterval(timerInterval_Full);\n document.getElementById(\"full-timer-label\").innerHTML = formatTime(\n timeLeft_Full\n );\n go = 1;\n if (exerciseList.length!=1) {\n exerciseList =[];\n exerciseTime = 0;\n document.getElementById(\"exercises\").innerHTML = formatExercises();\n }\n startTimer(5);\n timerInterval_Full = setInterval(() => {\n if (go==1 && now!=\"LET\\'S BEGIN\") {\n document.getElementById(\"full-timer-label\").innerHTML = formatTime(\n timeLeft_Full\n );\n if (timeLeft_Full <= 0) {\n onTimesUp_Full();\n }\n timePassed_Full = timePassed_Full += 1;\n timeLeft_Full = limit_Full - timePassed_Full;\n\n }\n }, 1000);\n}", "function clock() {\n let time = id(\"time\");\n let minutes = 0;\n seconds = 0;\n if(unlimited()) {\n timer = setInterval(() => {\n seconds++;\n if(seconds >= MIN) {\n minutes++;\n seconds-= MIN;\n }\n displayTime(time, minutes);\n }, SEC);\n } else {\n let timeVal = parseInt(id(\"menu-view\").querySelector(\"select\").value);\n minutes = Math.floor(timeVal / MIN);\n displayTime(time, minutes);\n timer = setInterval(() => {\n seconds--;\n if((minutes + seconds) < 0) {\n seconds = 0;\n displayTime(time, 0);\n endGame();\n } else if(seconds < 0) {\n minutes--;\n seconds = MIN + seconds;\n }\n displayTime(time, minutes);\n }, SEC);\n }\n }", "function runTimer(){\n\tlet currentTime = leadingZero(timer[0])+\":\"+leadingZero(timer[1])+\":\"+leadingZero(timer[2]);\n\ttheTimer.innerHTML = currentTime;\n\ttimer[3]++;\n\n\ttimer[0] = Math.floor((timer[3]/100)/60);\n\ttimer[1] = Math.floor((timer[3]/100)-(timer[0]*60));\n\ttimer[2] = Math.floor(timer[3]-(timer[1]*100)-(timer[0]*6000));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EXAMPLE 2 Make a promisebased function for reading properties from window
function readPropertyFromWindow (propertyName) { return new Promise(function (resolve) { workerProof( function (propName, callback) { callback(window[propName]); }, { args: propertyName, multipleCallbacks: false, callback: resolve } ); }) }
[ "read (thing, name) {\n var getValue = function (resolve, reject) {\n \tconst uri = thing.uri + \"/properties/\" + name;\n \t\n \tconst opts = {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\theaders: {\n\t\t\t\t\t'Accept': 'application/json'\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n \tfetch(uri, opts).then(response => {\n \t\tif (response.ok) {\n \t\t\t//console.log(\"got value \");\n \t\t\tresolve(response.json());\n \t\t} else\n \t\t\tthrow(new Error(\"property is unknown or unreadable\"));\n \t}).catch(err => {\n \t\tconsole.log(\"couldn't get property \" + name);\n \t\treject(err);\n \t});\n };\n \n return new Promise(function (resolve, reject) {\n getValue(resolve, reject);\n });\n }", "read (thing, name) {\n var getValue = function (resolve, reject) {\n \tconst uri = thing.uri + \"/properties/\" + name;\n \t\n \tconst opts = {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\theaders: {\n\t\t\t\t\t'Accept': 'application/json',\n\t\t\t\t\t'Authorization': `Bearer ${this.jwt}`\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n \tfetch(uri, opts).then(response => {\n \t\tif (response.ok) {\n \t\t\t//console.log(\"got value \");\n \t\t\tresolve(response.json());\n \t\t} else\n \t\t\tthrow(new Error(\"property is unknown or unreadable\"));\n \t}).catch(err => {\n \t\tconsole.log(\"couldn't get property \" + name);\n \t\treject(err);\n \t});\n };\n \n return new Promise(function (resolve, reject) {\n getValue(resolve, reject);\n });\n }", "read (thing, name) {\n\t\tlet server = this;\n let getValue = function (resolve, reject) {\n \tconst uri = thing.uri + \"/properties/\" + name;\n \t\n \tconst opts = {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': `Bearer ${server.jwt}`,\n\t\t\t\t\t'Accept': 'application/json'\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n \tfetch(uri, opts).then(response => {\n \t\tif (response.ok) {\n \t\t\t//console.log(\"got value \");\n \t\t\tresolve(response.json());\n \t\t} else\n \t\t\tthrow(new Error(\"property is unknown or unreadable\"));\n \t}).catch(err => {\n \t\tconsole.log(\"couldn't get property \" + name);\n \t\treject(err);\n \t});\n };\n \n return new Promise(function (resolve, reject) {\n getValue(resolve, reject);\n });\n }", "getProperty(p) { // promise\n assert(_.isString(p), \"property name must be a string\");\n return this.call(\"getProperty\", null, p);\n }", "static get() {\n return store[kPromise];\n }", "static get() {\n return store[kPromise];\n }", "function getVars() {\r\n return new Promise((resolve, reject) => {\r\n let xhr = new XMLHttpRequest();\r\n xhr.open(\"GET\", \"/vars\");\r\n xhr.addEventListener(\"load\", () => {\r\n resolve(JSON.parse(xhr.responseText));\r\n });\r\n xhr.addEventListener(\"error\", () => {\r\n reject(\"Error retrieving variables from server\");\r\n });\r\n xhr.send();\r\n });\r\n}", "function usFunction(value) {\r\n console.log(value);\r\n}//promise function used for setTimeout", "function makeWindowHelpers(window) {\n let {clearTimeout, setTimeout} = window;\n\n // Call a function after waiting a little bit\n function async(callback, delay) {\n let timer = setTimeout(function() {\n stopTimer();\n callback();\n }, delay);\n\n // Provide a way to stop an active timer\n function stopTimer() {\n if (timer == null)\n return;\n clearTimeout(timer);\n timer = null;\n unUnload();\n }\n\n // Make sure to stop the timer when unloading\n let unUnload = unload(stopTimer, window);\n\n // Give the caller a way to cancel the timer\n return stopTimer;\n }\n\n // Replace a value with another value or a function of the original value\n function change(obj, prop, val) {\n let orig = obj[prop];\n obj[prop] = typeof val == \"function\" ? val(orig) : val;\n unload(function() obj[prop] = orig, window);\n }\n\n return {\n async: async,\n change: change,\n };\n}", "async function loadCurrentWindowInfo() {\n const win = await browser.windows.getCurrent()\n this.state.private = win.incognito\n this.state.windowId = win.id\n}", "GetActiveTabData() {\n return new Promise(Resolve => {\n chrome.tabs.query(\n { active: true, currentWindow: true }, \n (tabs) => { \n Resolve({ \n url: tabs[0].url,\n height: tabs[0].height,\n width: tabs[0].width\n }); \n }\n );\n });\n }", "async function callGetProcessMemoryInfo() {\n let process_func_list = \"\";\n for (var key in window.process) {\n if (typeof window.process[key] === 'function') {\n process_func_list = process_func_list += `${key}, `;\n }\n }\n document.getElementById('process-functions').appendChild(document.createTextNode(process_func_list))\n let memoryUsage;\n try {\n memoryUsage = await window.process.getProcessMemoryInfo();\n console.log('memory usage', memoryUsage);\n } catch(e) {\n console.log('error', e);\n document.getElementById('error').appendChild(document.createTextNode(e))\n }\n\n}", "function loadGlobal(){\n if(typeof global.Promise !== 'undefined'){\n return {\n Promise: global.Promise,\n implementation: 'global.Promise'\n }\n }\n return null\n}", "function getJsVar()\n{\n for (var prop in window)\n {\n try\n {\n window[prop].getClass();\n return window[prop]; \n }\n catch(err)\n {\n //console.log(err);\n }\n }\n console.log(\"Could not find JS interface\");\n return null;\n}", "function PromiseUtils() {}", "function obtenerValorPropertyBag(keyProperty, funcionEjecutarFinalizar) {\n var propertiesBag;\n var valorProperty;\n\n SP.SOD.executeFunc(\"sp.js\", \"SP.ClientContext\", function () {\n var ctx = new SP.ClientContext.get_current();\n var web = ctx.get_web();\n propertiesBag = web.get_allProperties();\n ctx.load(propertiesBag);\n\n ctx.executeQueryAsync(function () {\n var valorProperty = obtenerPropertyBag(propertiesBag, keyProperty);\n funcionEjecutarFinalizar(valorProperty);\n }, function (sender, args) { });\n });\n}", "async function getCustomPropertiesFromJSFile(from) {\n const object = await import(from);\n return getCustomPropertiesFromObject(object);\n}", "function getProperty(propertyName){\n return PropertiesService.getScriptProperties().getProperty(propertyName);\n}", "function GetWindowPropertyByBrowser_(win, getters) {\n try {\n if (BR_IsSafari()) {\n return getters.dom_(win);\n } else if (!window.opera &&\n \"compatMode\" in win.document &&\n win.document.compatMode == \"CSS1Compat\") {\n return getters.ieStandards_(win);\n } else if (BR_IsIE()) {\n return getters.ieQuirks_(win);\n }\n } catch (e) {\n // Ignore for now and fall back to DOM method\n }\n\n return getters.dom_(win);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get transaction explorer base url for nonethereum blockchain
static getBlockChainExplorerUrl(coin, hash) { if (OtherCoins[coin] && OtherCoins[coin].explorer) { if (hash) { return OtherCoins[coin].explorer.replace('[[txHash]]', hash); } return OtherCoins[coin].explorer; } return ''; }
[ "function transactionUrl (networkName, txHash) {\n const insightUrl = config.get('insightUrl')\n return `${insightUrl}/tx/${txHash}`\n}", "function getTreeUrl() {\n return url_1.URLExt.join(getBaseUrl(), getOption('treeUrl'));\n }", "getExplorerUrls() {\n let networks = this.getNetworks();\n let networkObject = {};\n\n for (let walletCoin of Object.keys(this.getCoins())) {\n for (let networkCoin in networks) {\n if (walletCoin === networkCoin) {\n networkObject[walletCoin] = networks[walletCoin].explorer.url;\n }\n }\n }\n\n return networkObject;\n }", "function getBaseUrl() {\r\n\tvar base;\r\n\r\n\tif (getURLParameter($(parent.location).attr('href'), \"base\") != null) {\r\n\t\tbase = getURLParameter($(parent.location).attr('href'), \"base\");\r\n\t} else {\r\n\r\n\t\tif (window.location.protocol == 'http:' || window.location.protocol == 'https:')\r\n\t\t\tbase = window.location.protocol + \"//\" + window.location.host;\r\n\t\telse\r\n\t\t\tbase = window.location.host;\r\n\t}\r\n\r\n\treturn base;\r\n}", "function getBlockchainUrl(id, merged) {\n if (merged && blockchainExplorerMerged) {\n return blockchainExplorerMerged.replace('{symbol}', mergedStats.config.symbol.toLowerCase()).replace('{id}', id);\n } else {\n return blockchainExplorer.replace('{symbol}', lastStats.config.symbol.toLowerCase()).replace('{id}', id);\n }\n}", "function createEtherscanIoUrl(type,hashOrNumber){\n\n // For TestRPC - this URL will have no meaning as the\n // Etherscan.io will not know about the Tx Hash\n\n var url = etherscanBaseUrl;\n if(type === 'tx'){\n url += 'tx/'+hashOrNumber;\n } else if(type === 'block'){\n url += 'block/'+hashOrNumber;\n } else if(type === 'address'){\n url += 'address/'+hashOrNumber;\n }\n return url;\n}", "function _getWebcomBaseUrl() {\n\t\tif (_datastore) {\n\t\t\treturn _datastore.toString();\n\t\t}\n\t\treturn undefined;\n\t}", "function getBaseURL(){\n\treturn stripSearch(self.location.href);\n}", "function getBaseURL()\n{\n var pageURL = document.location.href;\n var urlArray = pageURL.split(\"/\");\n var BaseURL = urlArray[0]+\"//\"+urlArray[2]+\"/\";\n //Dev environments have the installation sitting in a separate folder\n if(urlArray[2] == 'localhost:8888' || urlArray[2] == '0.0.0.0')\n {\n\t\tBaseURL = BaseURL+'clout-dev/dev-v1.3.2-web/';\n }\n return BaseURL;\n}", "function getBaseUrl(){\n return baseUrl;\n }", "getExplorerURL(token_id) {\n if (!token_id) {\n return 'https://simpleledger.info';\n } else {\n return `https://simpleledger.info/token/${token_id}`;\n }\n }", "function createEtherscanIoUrl(type,hashOrNumber){\n\n var etherscanBaseUrl='https://ropsten.etherscan.io/';\n\n var url = etherscanBaseUrl;\n if(type === 'tx'){\n url += 'tx/'+hashOrNumber;\n } else if(type === 'block'){\n url += 'block/'+hashOrNumber;\n } else if(type === 'address'){\n url += 'address/'+hashOrNumber;\n }\n return url;\n}", "getExplorerURL(address) {\n if (!address) {\n return 'https://bloks.io/';\n } else {\n // make this go to actual token page\n // (instead of account page) in the future\n return `https://bloks.io/account/${address}`;\n }\n }", "function getClosestBaseUrl( ele ) {\r\n\t\t// Find the closest page and extract out its url.\r\n\t\tvar url = $( ele ).closest( \".ui-page\" ).jqmData( \"url\" ), base = documentBase.hrefNoHash;\r\n\r\n\t\tif ( !url || !path.isPath( url ) ) {\r\n\t\t\turl = base;\r\n\t\t}\r\n\r\n\t\treturn path.makeUrlAbsolute( url, base );\r\n\t}", "function getBaseUrl() {\n var baseUrl = getOption('baseUrl');\n if (!baseUrl || baseUrl === '/') {\n baseUrl = (typeof location === 'undefined' ?\n 'http://localhost:8888/' : location.origin + '/');\n }\n return url_1.URLExt.parse(baseUrl).toString();\n }", "function getBaseUrl(){\n return window.location.href.replace(/\\?.*/,'');\n}", "generateUrl(blockhash) {\n return `https://blockchain.info/rawblock/${blockhash}?cors=true&format=json`;\n }", "function baseUrl(uri){ return websiteRoot+uri; }", "get __effectiveBaseUrl() {\n return this.baseUrl\n ? this.constructor.__createUrl(\n this.baseUrl,\n document.baseURI || document.URL\n ).href.replace(/[^\\/]*$/, '')\n : '';\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
because of the way the network is created, nodes are created first, and links second, so the lines were on top of the nodes, this just reorders the DOM to put the svg:g on top
function keepNodesOnTop() { $(".nodeStrokeClass").each(function( index ) { var gnode = this.parentNode; gnode.parentNode.appendChild(gnode); }); }
[ "function draw_tree(nodes){\n var graph = svg.append('g').attr('id', 'graph');\n var link = graph.selectAll('.g')\n .data(nodes.descendants().slice(1).reverse())\n .enter().append('g')\n var paths = link.append(\"path\")\n .attr(\"class\", \"link\")\n .attr(\"d\", function(d) {\n return \"M\" + d.x + \",\" + d.y\n + \"C\" + d.x + \",\" + (d.y + d.parent.y) / 2\n + \" \" + d.parent.x + \",\" + (d.y + d.parent.y) / 2\n + \" \" + d.parent.x + \",\" + d.parent.y;\n })\n .attr('stroke-linecap', 'round')\n .attr('style', function(d) {return 'fill:None;stroke:'\n + get_link_color(d.data.values) + ';stroke-width:' \n + path_width(d.data.values) + ';'});\n\n var arrows = link.filter(function (d) {\n return path_width(d.data.values) > 1;}).append(\"path\")\n .attr('class', 'arrowhead')\n .attr('stroke-linecap', 'round')\n .attr(\"d\", function(d) {\n width = path_width(d.data.values);\n return \"M\" + (d.x - width/1.5) + \",\" + d.y\n + \"L\" + d.x + \",\" + (d.y + width)\n + \"L\" + (d.x + width/1.5) + \",\" + d.y;})\n .style(\"fill\", function (d) {\n return get_link_color(d.data.values);})\n .style('stroke', 'white')\n .style('stroke-width', function(d){\n return path_width(d.data.values)/5});\n return link;\n }", "render_() {\n // Select the links.\n const link = this.linkGroup_.selectAll('line').data(this.links_);\n // Add new links.\n link.enter().append('line').attr('stroke-width', 1);\n // Remove dead links.\n link.exit().remove();\n\n // Select the nodes, except for any dead ones that are still transitioning.\n const nodes = Array.from(this.nodes_.values());\n const node =\n this.nodeGroup_.selectAll('g:not(.dead)').data(nodes, d => d.id);\n\n // Add new nodes, if any.\n if (!node.enter().empty()) {\n const drag = d3.drag();\n drag.on('start', this.onDragStart_.bind(this));\n drag.on('drag', this.onDrag_.bind(this));\n drag.on('end', this.onDragEnd_.bind(this));\n\n const newNodes = node.enter().append('g').call(drag);\n const circles = newNodes.append('circle').attr('r', 9).attr(\n 'fill', 'green'); // New nodes appear green.\n newNodes.append('image')\n .attr('x', -8)\n .attr('y', -8)\n .attr('width', 16)\n .attr('height', 16);\n newNodes.append('title');\n\n // Transition new nodes to their chosen color in 2 seconds.\n circles.transition()\n .duration(2000)\n .attr('fill', d => d.color)\n .attr('r', 6);\n }\n\n // Give dead nodes a distinguishing class to exclude them from the selection\n // above. Interrupt any ongoing transitions, then transition them out.\n const deletedNodes = node.exit().classed('dead', true).interrupt();\n\n deletedNodes.select('circle')\n .attr('r', 9)\n .attr('fill', 'red')\n .transition()\n .duration(2000)\n .attr('r', 0)\n .remove();\n\n // Update the title for all nodes.\n node.selectAll('title').text(d => d.title);\n // Update the favicon for all nodes.\n node.selectAll('image').attr('href', d => d.iconUrl);\n\n // Update and restart the simulation if the graph changed.\n if (!node.enter().empty() || !node.exit().empty() ||\n !link.enter().empty() || !link.exit().empty()) {\n this.simulation_.nodes(nodes);\n this.simulation_.force('link').links(this.links_);\n\n this.restartSimulation_();\n }\n }", "function redrawNodes() {\n for(var i=0;i<Object.keys(node_list).length;i++) {\n var node = node_list[Object.keys(node_list)[i]];\n createNode('node', node.node_pos_x, node.node_pos_y, node_width, node_height, redraw=true, Object.keys(node_list)[i].substr(4, Object.keys(node_list)[i].length));\n }\n\n for(var i=0;i<line_node_connection_list.length;i++) {\n d3.select('#charts').insert(\"line\", \".first-g + *\") // insert line right after .first-g element\n .attr(\"x1\", line_node_connection_list[i].line_pos_x1)\n .attr(\"y1\", line_node_connection_list[i].line_pos_y1)\n .attr(\"x2\", line_node_connection_list[i].line_pos_x2)\n .attr(\"y2\", line_node_connection_list[i].line_pos_y2)\n .attr(\"class\", \"connector_line\");\n }\n\n // redraw lines from node_list\n /*for(var i=0;i<Object.keys(node_list).length;i++) {\n\n var child_node_id = Object.keys(node_list)[i];\n\n console.log(\"child_node_id: \"+child_node_id);\n console.log(\"input_context: \"+node_list[child_node_id].in_ctx);\n\n if(node_list[child_node_id].in_ctx.length > 0) {\n for(var j=0;j<node_list[child_node_id].in_ctx.length;j++) {\n var parent_node_id = node_list[child_node_id].in_ctx[j];\n console.log(\"parent_node_id: \"+parent_node_id);\n for(var k=0;k<node_list[child_node_id].connected_lines.length;k++) {\n console.log(\"connected with(node_list[child_node_id].connected_lines[k].connected_with): \"+node_list[child_node_id].connected_lines[k].connected_with);\n if(node_list[child_node_id].connected_lines[k].connected_with == parent_node_id) {\n console.log('inside if....');\n x = node_list[child_node_id].connected_lines[k].connected_end.x;\n y = node_list[child_node_id].connected_lines[k].connected_end.y;\n\n console.log(\"connected_end x: \"+ x);\n console.log(\"connected_end y: \"+ y);\n\n if(x == 'x1' && y == 'y1') {\n line = d3.select('#charts').insert(\"line\", \".first-g + *\") // insert line right after .first-g element\n .attr(\"x1\", node_list[child_node_id].node_pos_x + 50)\n .attr(\"y1\", node_list[child_node_id].node_pos_y)\n .attr(\"x2\", node_list[parent_node_id].node_pos_x + 50)\n .attr(\"y2\", node_list[parent_node_id].node_pos_y + 100)\n .attr(\"class\", \"connector_line\")\n .attr(\"id\", node_list[child_node_id].connected_lines[k].id);\n } else if(x == 'x2' && y == 'y2') {\n line = d3.select('#charts').insert(\"line\", \".first-g + *\") // insert line right after .first-g element\n .attr(\"x1\", node_list[parent_node_id].node_pos_x + 50)\n .attr(\"y1\", node_list[parent_node_id].node_pos_y + 100)\n .attr(\"x2\", node_list[child_node_id].node_pos_x + 50)\n .attr(\"y2\", node_list[child_node_id].node_pos_y)\n .attr(\"class\", \"connector_line\")\n .attr(\"id\", node_list[child_node_id].connected_lines[k].id);\n }\n break;\n }\n }\n }\n }\n }*/\n}", "function xmlNetwork2Svg(networkData) {\n\n // alert(networkData.maxY);\n // create svg network\n var svgHeight = networkData.maxY-networkData.minY;\n var svgWidth = networkData.maxX-networkData.minX;\n var scaleWidth = 2000/svgWidth;\n\n // alert(svgHeight +\",\"+svgWidth);\n // var scaleFactorWidth = document.getElementById(appenedElmentId).offsetWidth/svgWidth;\n // var scaleFactorHeight = document.getElementById(appenedElmentId).offsetHeight/svgHeight;\n var networkSvg = createSvg(\"svg\",{\"id\":\"svgNetwork\",\n \"width\":\"100%\",// svgWidth,\n \"height\": \"100%\",//svgHeight,\n // \"width\": svgWidth,\n // \"height\": svgHeight,\n \"viewBox\":\"0 0 \" +svgWidth*scaleWidth+ \" \"+svgHeight*scaleWidth,\n // \"transform\":\"scale(\"+winX/svgWidth+\",\"+winX/svgWidth+\")\",\n // \"preserveAspectRatio\":\"xMinYMin meet\",\n \"xmlns\":\"http://www.w3.org/2000/svg\",\n \"xmlns:xlink\":\"http://www.w3.org/1999/xlink\",\n //\"transform\":\"scale(\"+scaleFactorWidth+\",\"+scaleFactorHeight+\")\",\n // \"viewbox\":\"0 0 400 400\",\n // \"preserveAspectRatio\":\"xMidYMid meet\"\n });\n\n\n // networkSvg.setAttribute(\"transform\",1000);\n // networkSvg.setAttribute(\"height\",800);\n // create backgroud color\n var backGround = createSvg(\"rect\",{\"id\":\"backGround\",\n // \"x\":0,//-svgWidth*.05,\n // \"y\":0,//-svgHeight*.05,\n \"width\":\"100%\",//svgWidth,\n \"height\":\"100%\",//svgHeight,\n // \"width\":svgWidth,\n // \"height\":svgHeight,\n \"viewBox\":\"0 0 \" +svgWidth*scaleWidth+ \" \"+svgHeight*scaleWidth,\n // \"transform\":\"scale(\"+winX/svgWidth+\",\"+winX/svgWidth+\")\",\n // \"preserveAspectRatio\":\"xMinYMin meet\",\n \"fill\":\"#000000\"});\n // var networkGroup = document.createElement('networkGroup');\n networkSvg.append(backGround);\n\n for (var link in networkData.links){\n // console.log(links[link].fromNode)\n var fromX = (networkData.nodes[networkData.links[link].fromNode].x-networkData.minX);\n var fromY = (networkData.nodes[networkData.links[link].fromNode].y-networkData.minY);\n var toX = (networkData.nodes[networkData.links[link].toNode].x-networkData.minX);\n var toY = (networkData.nodes[networkData.links[link].toNode].y-networkData.minY);\n // console.log(link+fromX+\", \"+fromY+\" ; \"+toX+\", \"+toY);\n var tempLine = createSvg(\"line\",{\"id\":link,\"x1\":fromX*scaleWidth,\"y1\":fromY*scaleWidth,\"x2\":toX*scaleWidth,\"y2\":toY*scaleWidth,\"stroke\":\"orange\",\"stroke-width\":.3});\n // networkGroup.append(tempLine);\n networkSvg.append(tempLine);\n }\n return networkSvg;\n}", "function updateNodesAndLinks() {\n if (paths_loaded) {\n paths_loaded = false;\n d3.selectAll(\"path\").remove();\n }\n\n links\n .attr(\"x1\", function (d) {\n return d.source.x;\n })\n .attr(\"y1\", function (d) {\n return d.source.y;\n })\n .attr(\"x2\", function (d) {\n return d.target.x;\n })\n .attr(\"y2\", function (d) {\n return d.target.y;\n });\n\n nodes\n .attr(\"transform\", function (d) {\n return \"translate(\" + d.x + \",\" + d.y + \")\";\n });\n}", "function redraw() {\r\n\r\n\t// Stroke width for new edges depends on model\r\n\tconst linkStrokeWidth = (d, i) => {\r\n\t\tswitch(model) {\r\n\t\t\tcase \"comFr\":\r\n\t\t\tcase \"barab\":\r\n\t\t\tcase \"minor\":\r\n\t\t\t\treturn nodes.length == initNodes ? 1 : 2;\r\n\t\t\tcase \"gilbert\":\r\n\t\t\t\treturn 2;\r\n\t\t\tcase \"wattsA\":\r\n\t\t\t\treturn globalIter == 0 ? 1 : 2;\r\n\t\t\tcase \"wattsB\":\r\n\t\t\t\treturn 1;\r\n\t\t\tdefault:\r\n\t\t\t\tconsole.log(\"Wrong model in linkStrokeWidth: \" + model)\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t// Colors for newly drawn edges depend on model\r\n\tconst linkStroke = (d, i) => {\r\n\t\tswitch(model) {\r\n\t\t\tcase \"comFr\":\r\n\t\t\tcase \"barab\":\r\n\t\t\tcase \"minor\":\r\n\t\t\t\treturn nodes.length == initNodes ? \"black\" : \"red\";\r\n\t\t\tcase \"gilbert\":\r\n\t\t\t\treturn \"red\";\r\n\t\t\tcase \"wattsA\":\r\n\t\t\t\treturn globalIter == 0 ? \"black\" : \"red\";\r\n\t\t\tcase \"wattsB\":\r\n\t\t\t\treturn \"black\";\r\n\t\t\tdefault:\r\n\t\t\t\tconsole.log(\"Wrong model in linkStroke: \" + model)\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t// Update link visuals i.e. add new edges to html\r\n\tlink = link.data(links)\r\n\t\t.enter()\r\n\t\t.append(\"line\")\r\n\t\t.attr(\"class\", \"link\")\r\n\t\t.styles({\"stroke-width\": linkStrokeWidth, stroke: linkStroke})\r\n\t\t.merge(link);\r\n\r\n\t// For the wattsB model, recolor the rewired edge\r\n\tif (model == \"wattsB\") {\r\n\t\tlink.filter((d, i, list) => { return i == globalIter-1; }).styles({\"stroke-width\": 2, stroke: \"red\"});\r\n\t}\r\n\r\n\t// Transition new edges into normal style\r\n\tlink.filter((d, i, list) => { \r\n\t\t\tswitch(model) {\r\n\t\t\t\tcase \"wattsA\":\r\n\t\t\t\tcase \"barab\":\r\n\t\t\t\tcase \"minor\":\r\n\t\t\t\tcase \"gilbert\":\r\n\t\t\t\t\treturn i > list.length - initPartners - 1;\r\n\t\t\t\tcase \"comFr\":\r\n\t\t\t\t\treturn i > globalIter;\r\n\t\t\t\tcase \"wattsB\":\r\n\t\t\t\t\treturn i == globalIter - 1;\r\n\t\t\t}\r\n\t\t}).transition()\r\n\t\t.duration(refreshRate)\r\n\t\t.styles({\"stroke-width\": 1, stroke: \"black\"});\r\n\r\n\t// Update node visuals\r\n\t// Delete all nodes, then draw the old visuals anew (to get the transition effect)\r\n\tsvgNetwork.selectAll(\".node\").remove();\r\n\tnode = svgNetwork.selectAll(\".node\").data(oldNodes)\r\n\t\t.enter()\r\n\t\t.append(\"circle\")\r\n\t\t.attrs({class: \"node\", r: radius})\r\n\t\t.style(\"stroke\", \"black\")\r\n\t\t.style(\"fill\", d => { \r\n\t\t\tswitch(model) {\r\n\t\t\t\tcase \"comFr\":\r\n\t\t\t\tcase \"wattsA\":\r\n\t\t\t\tcase \"wattsB\":\r\n\t\t\t\tcase \"gilbert\":\r\n\t\t\t\tcase \"barab\":\r\n\t\t\t\t\treturn color(radius(d));\r\n\t\t\t\tcase \"minor\":\r\n\t\t\t\t\treturn color(d.group);\r\n\t\t\t\tdefault:\r\n\t\t\t\t\treturn \"black\";\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t// Redefine color scale for the current nodes and chart bars\r\n\tsetColorScale();\r\n\r\n\t// Apply the radius and color transition from previous step to current step\r\n\tnode.data(nodes)\r\n\t\t.transition()\r\n\t\t.duration(refreshRate)\r\n\t\t.attr(\"r\", d => { return radius(d); })\r\n\t\t.style(\"fill\", d => { \r\n\t\t\tswitch(model) {\r\n\t\t\t\tcase \"comFr\":\r\n\t\t\t\tcase \"wattsA\":\r\n\t\t\t\tcase \"wattsB\":\r\n\t\t\t\tcase \"gilbert\":\r\n\t\t\t\tcase \"barab\":\r\n\t\t\t\t\treturn color(radius(d));\r\n\t\t\t\tcase \"minor\":\r\n\t\t\t\t\treturn color(d.group);\r\n\t\t\t\tdefault:\r\n\t\t\t\t\treturn \"black\";\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t// Add the new node\r\n\tnode = node.data(nodes).enter().append(\"circle\")\r\n\t\t.attrs({class: \"node\", r: radius, id: \"new\"})\r\n\t\t.styles({stroke: \"black\", fill: \"red\"})\r\n\t\t.merge(node);\r\n\r\n\tnode.attrs({cx: d => { return model == \"wattsB\" || model == \"wattsA\" ? d.x : null; }, \r\n\t\t\t\tcy: d => { return model == \"wattsB\" || model == \"wattsA\" ? d.y : null; }});\r\n\r\n\t// Clone nodes to safe last iteration\r\n\toldNodes = nodes.map(d => Object.assign({}, d));\r\n\r\n\t// Transition new node into normal style (filters for last element)\r\n\tnode.filter((d, i, list) => { return i === list.length - 1; })\r\n\t\t.transition()\r\n\t\t.duration(refreshRate)\r\n\t\t.style(\"fill\", d => { \r\n\t\t\tswitch(model) {\r\n\t\t\t\tcase \"comFr\":\r\n\t\t\t\tcase \"wattsA\":\r\n\t\t\t\tcase \"wattsB\":\r\n\t\t\t\tcase \"gilbert\":\r\n\t\t\t\tcase \"barab\":\r\n\t\t\t\t\treturn color(radius(d));\r\n\t\t\t\tcase \"minor\":\r\n\t\t\t\t\treturn color(d.group);\r\n\t\t\t\tdefault:\r\n\t\t\t\t\treturn \"black\";\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t// Reapply force on nodes and links\r\n\tif (model != \"wattsB\" && model != \"wattsA\") {\r\n\t\tforce.nodes(nodes);\r\n\t\tforce.force(\"link\").links(links);\r\n\t}\r\n\r\n\t// Progress in bottom right corner\r\n\tsvgNetwork.selectAll(\".counter\").remove();\r\n\tcounter = counter.data([{t: \"Number of nodes\", num: nodes.length}, \r\n\t\t\t\t\t\t\t{t: \"Number of links: \", num: links.length},\r\n\t\t\t\t\t\t\t{t: \"Average degree: \", num: avgDegree()}]);\r\n\tcounter.enter()\r\n\t\t.append(\"text\")\r\n\t\t.attrs({class: \"counter\", x: 10, y: (d,i) => { return heightNetwork - 10*(i+1); }})\r\n\t\t.styles({\"font-family\": \"sans-serif\", \"font-size\": \"11px\"})\r\n\t\t.text(d => { return \"\" + d.t + \": \" + d.num; });\r\n\r\n\t// Redraw the chart\r\n\tupdateChart();\r\n\r\n\t// Refresh force time\r\n\tforce.alpha(1).restart();\r\n}", "function drawNetwork(authNet) {\n\t\tvar force = d3.layout.force()\n\t\t\t//.gravity(-0.1)\n\t\t\t.linkDistance(50)\n\t\t\t.charge(-400)\n\t\t\t//.friction(0.8)\n\t\t\t.size([width, height]);\n\t\t\n\t\tforce\n\t\t\t.nodes(authNet.nodes)\n\t\t\t.links(authNet.links)\n\t\t\t.start();\n\t\t\n\t\tvar tooltip = d3.tip()\n\t\t\t.attr(\"class\", \"d3-tip\")\n\t\t\t.offset([0, -20])\n\t\t\t.html(function (d) {\n\t\t\t\tvar pubsHtml = \"<ul>\";\n\t\t\t\td.pubs.forEach(element => {\n\t\t\t\t\tpubsHtml += \"<li>\" + gPub_info[element.value].bib.title + \"</li>\"\n\t\t\t\t})\n\t\t\t\treturn pubsHtml + \"</ul>\";\n\t\t\t})\n\t\t\t.style(\"background-color\", \"#f8f9fa\")\n\t\t\t.style(\"text-align\", \"left\")\n\t\t\t.style(\"box-sizing\", \"border-box\");\n\t\t\n\t\tsvg.call(tooltip);\n\t\t\n\t\tvar link = svg.selectAll(\".link\")\n\t\t\t.data(authNet.links)\n\t\t\t.enter().append(\"line\")\n\t\t\t.attr('class', 'link')\n\t\t\t.attr(\"stroke-width\", function (d) {\n\t\t\t\treturn (d.weight*1);\n\t\t\t})\n\t\t\t.style('stroke', 'blue')\n\t\t\t.style(\"stroke-opacity\", 0.6)\n\t\t\t.on(\"mouseover\", function (d) {\n\t\t\t\ttooltip.show(d, this);\n\t\t\t})\n\t\t\t.on(\"mouseout\", function (d) {\n\t\t\t\ttooltip.hide(d, this);\n\t\t\t});\n\t\t\n\t\tvar drag = force.drag()\n\t\t\t.on(\"dragstart\", dragstart);\n\t\t\n\t\tvar node = svg.selectAll(\".node\")\n\t\t\t.data(authNet.nodes)\n\t\t\t.enter().append(\"g\")\n\t\t\t.attr(\"class\", \"node\")\n\t\t\t.on(\"dblclick\", dblclick)\n\t\t\t.call(drag);\n\t\t\t//.call(force.drag);\n\t\t\n\t\tnode.append(\"image\")\n\t\t\t.attr(\"xlink:href\", function (d) { \n\t\t\t\treturn gAuth_info[d.id].url_picture\n\t\t\t})\n\t\t\t.attr(\"x\", -15)\n\t\t\t.attr(\"y\", -15)\n\t\t\t.attr(\"width\", 30)\n\t\t\t.attr(\"height\", 30);\n\t\t\n\t\tnode.append(\"a\")\n\t\t\t.attr(\"target\",\"_blank\")\n\t\t\t.attr(\"href\", function (d) { \n\t\t\t\treturn \"https://scholar.google.com/citations?user=\"+d.id;\n\t\t\t})\n\t\t\t.append(\"text\")\n\t\t\t.attr(\"dx\", -25)\n\t\t\t.attr(\"dy\", 30)\n\t\t\t.text(function (d) { return gAuth_info[d.id].name });\n\t\t\n\t\tforce.on(\"tick\", function () {\n\t\t\tlink.attr(\"x1\", function (d) { return d.source.x; })\n\t\t\t\t.attr(\"y1\", function (d) { return d.source.y; })\n\t\t\t\t.attr(\"x2\", function (d) { return d.target.x; })\n\t\t\t\t.attr(\"y2\", function (d) { return d.target.y; });\n\n\t\t\tnode.attr(\"transform\", function (d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\t\t});\n\n\n\t\tfunction dblclick(d) {\n\t\t\td3.select(this).classed(\"fixed\", d.fixed = false);\n\t\t}\n\n\t\tfunction dragstart(d) {\n\t\t\td3.select(this).classed(\"fixed\", d.fixed = true);\n\t\t}\n\t}", "function updateSVG() {\n //update links\n linkGroup = linkGroup.data(actorLinks);\n\n // remove old links\n linkGroup.exit().remove();\n\n linkGroup = linkGroup.enter().append('svg:path')\n .attr('class', 'link')\n //~ .style('marker-start', function(d) { return d.source.actor == \"target\" ? 'url(#start-arrow)' : ''; })\n //~ .style('marker-end', function(d) { return d.target.actor == \"target\" ? 'url(#end-arrow)' : ''; })\n .style('marker-start', function (d) {\n if (!d.rev) {\n return d.source.actor == \"target\" ? 'url(#start-arrow)' : '';\n }\n return 'url(#start-arrow)';\n })\n .style('marker-end', function (d) {\n if (!d.rev) {\n return d.target.actor == \"target\" ? 'url(#end-arrow)' : '';\n }\n return 'url(#end-arrow)';\n })\n .style('stroke', function (d) {\n if (d.rev) {\n return '#00cc00';\n }\n return '#000';\n })\n .on('mousedown', function (d) {\t\t\t\t\t\t\t//delete link\n //~ var obj1 = JSON.stringify(d);\n //~ console.log(\"link: \" + obj1);\n //~ for(var j = 0; j < actorLinks.length; j++) {\t\t//this removes the links on click\n //~ if(obj1 === JSON.stringify(actorLinks[j])) {\n //~ actorLinks.splice(j,1);\n //~ }\n //~ }\n for (let x = 0; x < actorLinks.length; x++) {\n if (d.dup && actorLinks[x].target == d.source && actorLinks[x].source == d.target) {\n actorLinks[x].dup = false;\n }\n\n if (actorLinks[x].source == d.source && actorLinks[x].target == d.target) {\n actorLinks.splice(x, 1);\n }\n }\n updateAll();\n })\n .merge(linkGroup);\n\n\n //now update nodes\n nodeGroup = nodeGroup.data(actorNodes, function (d) {\n return d.actorID;\n });\n\n nodeGroup.exit().remove();\t\t//remove any nodes that are not part of the display\n\n //define circle for node\n\n nodeGroup = nodeGroup.enter().append(\"g\").attr(\"id\", function (d) {\n return d.name.replace(/\\s/g, '') + \"Group\";\n }).call(node_drag)\n .each(function (d) {\n d3.select(this).append(\"circle\").attr(\"class\", \"actorNode\").attr(\"r\", actorNodeR)\n .style('fill', function (d) {\n return d.nodeCol;\n })\n .style('opacity', \"0.5\")\n .style('stroke', pebbleBorderColor)\n .style(\"pointer-events\", \"all\")\n .on(\"contextmenu\", function (d) {\t\t//begins drag line drawing for linking nodes\n d3.event.preventDefault();\n d3.event.stopPropagation();\t\t//prevents mouseup on node\n\n originNode = d;\n\n drag_line.style('marker-end', function () {\t\t//displays arrow in proper direction (source->target and target->source)\n if (d.actor == \"source\")\n return 'url(#end-arrow)';\n else\n return '';\n })\n .style('marker-start', function () {\n if (d.actor == \"target\")\n return 'url(#start-arrow)';\n else\n return '';\n })\n .classed('hidden', false).attr('d', 'M' + originNode.x + ',' + originNode.y + 'L' + originNode.x + ',' + originNode.y);\n\n actorSVG.on('mousemove', lineMousemove);\n })\n .on(\"mouseup\", function (d) {\t\t\t//creates link\t\t//for some reason, this no longer fires\n d3.event.stopPropagation();\t\t//prevents mouseup on svg\n createLink(d);\n nodeClick(d);\n mousedownNode = null;\n })\n .on(\"mousedown\", function (d) {\t\t//creates link if mouseup did not catch\n createLink(d);\n nodeClick(d);\n })\n .on(\"mouseover\", function (d) {\t\t//displays animation for visual indication of mouseover while dragging and sets tooltip\n if (dragSelect && dragSelect != d && dragSelect.actor == d.actor) {\n d3.select(this).transition().attr(\"r\", actorNodeR + 10);\n dragTarget = d;\n dragTargetHTML = this;\n }\n\n if (!dragStarted) {\n tooltipSVG.html(d.name).style(\"display\", \"block\");\n tooltipSVG.transition().duration(200).style(\"opacity\", 1);\n }\n })\n .on(\"mouseout\", function (d) {\t\t//display animation for visual indication of mouseout and resets dragTarget variables\n d3.select(this).transition().attr(\"r\", actorNodeR);\n dragTarget = null;\n dragTargetHTML = null;\n\n tooltipSVG.transition().duration(200).style(\"opacity\", 0).style(\"display\", \"none\");\t\t//reset tooltip\n })\n .on(\"mousemove\", function (d) {\t\t//display tooltip\n if (!dragStarted)\n tooltipSVG.style(\"display\", \"block\").style(\"left\", (d.x + 350) + \"px\").style(\"top\", (d.y) + \"px\");\n });\n\n d3.select(this).append('svg:text').attr('x', 0).attr('y', 15).attr('class', 'id').text(function (d) {\t//add text to nodes\n if (d.name.length > 12)\n return d.name.substring(0, 9) + \"...\";\n else\n return d.name;\n });\n })\n .merge(nodeGroup);\n\n\n //performs on \"click\" of node, shows actor selection on node click; call moved to mousedown because click() did not fire for Chrome\n function nodeClick(d) {\n window[currentTab + \"CurrentNode\"].group = [...filterSet[currentTab][\"full\"]];\n $(\"#\" + d.actor + \"TabBtn\").trigger(\"click\");\n\n if (window[currentTab + \"CurrentNode\"] !== d) {\t\t\t//only update gui if selected node is different than the current\n\n window[currentTab + \"CurrentNode\"] = d;\n filterSet[currentTab][\"full\"] = new Set(d.group);\n\n //update gui\n updateGroupName(d.name);\n clearChecks();\n document.getElementById(currentTab + \"ShowSelected\").checked = true;\n showSelected(document.getElementById(currentTab + \"ShowSelected\"));\n }\n }\n\n //creates link between nodes\n function createLink(d) {\n if (d3.event.which == 3) {\t//mouse button was right click, so interpret as user wants to create another line instead\n return;\n }\n\n if (!originNode)\t\t\t\t//if no origin node is selected then return\n return;\n\n drag_line.classed('hidden', true).style('marker-end', '');\t\t//hide drag line\n\n // check for drag-to-self and same actor to actor (source to source)\n destNode = d;\n if (destNode === originNode || destNode.actor == originNode.actor) {\n resetMouseVars();\n return;\n }\n\n //here link is now made\n const actualSource = originNode.actor == \"source\" ? originNode : destNode;\t//choose the node that is a source\n const actualTarget = destNode.actor == \"target\" ? destNode : originNode;\n\n const linkExist = actorLinks.filter(function (linkItem) {\n return (linkItem.source == actualSource && linkItem.target == actualTarget);\n })[0];\n\n if (linkExist) {\n //link exists for source -> target, check if origin is a target and link does not exist yet\n if (originNode.actor == \"target\" && !(actorLinks.filter(function (linkItem) {\n return (linkItem.source == actualTarget && linkItem.target == actualSource);\n })[0])) {\n actorLinks[actorLinks.indexOf(linkExist)].dup = true;\n actorLinks.push(new linkObj(actualTarget, actualSource, true, true));\n updateAll();\n }\n }\n else {\n //add link\n actorLinks.push(new linkObj(actualSource, actualTarget, false, false));\n updateAll();\n }\n\n //~ console.log(\"links:\");\n //~ for (var x = 0; x < actorLinks.length; x ++) {\n //~ console.log(actorLinks[x].source.name + \"\\t\" + actorLinks[x].target.name);\n //~ }\n //~ console.log(\"end links\");\n\n resetMouseVars();\n }\t//end of createLink()\n\n //update all names of nodes - changeID and actorID are not updated on name change to save room for other changes; probably unneccesary for a normal user (unlikely they will perform so many changes)\n actorSVG.selectAll(\"text\").text(function (d) {\n if (d.name.length > 12)\n return d.name.substring(0, 9) + \"...\";\n else\n return d.name;\n });\n}", "function render_graph() {\n var width,\n height,\n padding,\n radius,\n draw,\n circle,\n i,\n j,\n n,\n deg,\n group,\n group2,\n pathGroup,\n label,\n label2,\n line,\n id;\n\n width = 400;\n height = 400;\n padding = 20;\n\n n = 15;\n deg = 0;\n\n while (nodes.length < n) {\n id = Math.floor(Math.random() * Math.pow(2, 6));\n if (!nodes.includes(id)) {\n nodes.push(id);\n }\n }\n nodes.sort((a, b) => a - b);\n\n draw = SVG(\"graph\");\n draw.size(width, height);\n radius = width / 2 - padding * 2;\n\n pathGroup = draw.group();\n pathGroup.attr(\"id\", \"kademlia-paths\");\n group = draw.group();\n group.translate(width / 2, height / 2);\n group.attr(\"id\", \"kademlia-nodes\");\n group2 = draw.group();\n group2.attr(\"id\", \"kademlia-labels\");\n\n // Create the nodes.\n for (i = 0; i < n; i++) {\n var dataId = binaryPrefix + dec2bin(nodes[i]);\n\n // Draw node circle\n circle = draw.circle(40);\n circle.fill(noSelectedGraphNodeColor);\n deg += 360 / n;\n circle.cx(0).cy(-radius);\n circle.attr(\"transform\", \"rotate(\" + deg + \")\");\n circle.attr(\"node-id\", nodes[i]);\n circle.attr(\"data-id\", dataId);\n group.add(circle);\n graphNodes.push(circle);\n\n var pos1 = getPos(draw.native(), circle.native());\n\n // Display node ID in binary\n label = draw.plain(dec2bin(nodes[i]));\n label.x(pos1.x - label.native().getBBox().width / 2);\n label.y(pos1.y - 20);\n label.attr(\"data-id\", dataId);\n label.attr(\"font-family\", \"Roboto\");\n group2.add(label);\n\n // Display node ID in decimal\n label2 = draw.plain(\"(\" + nodes[i].toString() + \")\");\n label2.x(pos1.x - label2.native().getBBox().width / 2);\n label2.y(pos1.y - 2);\n label2.attr(\"data-id\", dataId);\n label2.attr(\"font-family\", \"Roboto\");\n group2.add(label2);\n\n circle.mouseover(onNodeMouseOver);\n circle.mouseout(onNodeMouseOut);\n circle.click(onNodeClicked);\n label.mouseover(onNodeMouseOver);\n label.mouseout(onNodeMouseOut);\n label.click(onNodeClicked);\n label2.mouseover(onNodeMouseOver);\n label2.mouseout(onNodeMouseOut);\n label2.click(onNodeClicked);\n }\n\n // Draw the paths\n for (i = 0; i < n; i++) {\n for (j = i + 1; j < n; j++) {\n var startPos = getPos(draw.native(), graphNodes[i].native());\n var endPos = getPos(draw.native(), graphNodes[j].native());\n line = draw.line(startPos.x, startPos.y, endPos.x, endPos.y);\n line.stroke({\n color: noSelectedLightColor,\n width: 1,\n linecap: \"round\"\n });\n line.addClass(graphNodes[i].attr(\"data-id\"));\n line.addClass(graphNodes[j].attr(\"data-id\"));\n pathGroup.add(line);\n graphEdges.push(line);\n }\n }\n }", "createLayout(graph) {\n\n //call to superclass\n this.setHeightAndWidth(graph);\n\n // Prepare to render the graph.\n let self = this;\n\n // get data in format of an object with 2 arrays of nodes and edges\n let dataset = this.graphToNodesAndEdges(graph);\n\n // establish force-directed layout\n let force = d3.layout.force()\n .nodes(dataset.nodes)\n .links(dataset.edges)\n .size([self.width, self.height])\n .linkDistance([self.linkDistance])\n .charge([self.charge])\n .theta(self.theta)\n .gravity(self.gravity)\n .start();\n\n /*render the objects*/\n\n // Create groups to hold the edges.\n this.edges = this.graphGroup.selectAll(\"g.edge\")\n .data(dataset.edges)\n .enter()\n .append(\"line\")\n .attr('marker-end', 'url(#arrowhead)')\n .style(\"stroke\", \"#ccc\")\n .style(\"pointer-events\", \"none\");\n\n this.edgePaths = this.graphGroup.selectAll(\"g.edgepath\")\n .data(dataset.edges)\n .enter()\n .append('path');\n\n // Create groups that will hold the nodes.\n this.nodeGroup = this.graphGroup.append(\"g\")\n .classed(\"nodeGroup\", true);\n\n //set up highlighting for nodes\n this.nodes = this.nodeGroup.selectAll(\"g.node\")\n .data(dataset.nodes)\n .enter()\n .append(\"g\")\n .classed(\"node\", true)\n .call(force.drag);\n\n //this.nodes.append(\"rect\")\n // .attr(\"rx\", self.rx)\n // .attr(\"ry\", self.ry)\n // .attr({\"height\": self.nodeHeight})\n // .attr({\"width\": self.nodeWidth});\n\n //node text\n this.nodeLabels = this.nodes.append(\"foreignObject\")\n .attr(\"width\", \"4em\")\n .attr(\"height\", \"2em\")\n .classed(\"node\", true);\n\n this.nodeLabels.append(\"xhtml:div\")\n .classed(\"path-list-node\", true)\n .html(function (d) {\n return d.name + (d.label ? \"<br>\" + d.label : \"\")\n }\n );\n\n\n //this.nodeLabels.append(\"tspan\")\n // .text(function (d) {\n // return d.name;\n // })\n // .attr(\"x\", self.nodeWidth / 2);\n //\n //this.nodeLabels.append(\"tspan\")\n // .text(function (d) {\n // return d.name;\n // })\n // .attr(\"dy\", \"1.2em\")\n // .attr(\"x\", self.nodeWidth / 2);\n\n //arrowheads\n this\n .graphGroup\n .append(\n 'defs'\n ).append(\n 'marker'\n )\n .attr({\n 'id': 'arrowhead',\n 'viewBox': '-0 -5 10 10',\n 'refX': 30,\n 'refY': 0,\n 'orient': 'auto',\n 'markerWidth': 10,\n 'markerHeight': 10,\n 'xoverflow': 'visible'\n })\n\n .append(\n 'svg:path'\n )\n .attr(\n 'd'\n ,\n 'M 0,-5 L 10 ,0 L 0,5'\n )\n .attr(\n 'fill'\n ,\n '#ccc'\n )\n .attr(\n 'stroke'\n ,\n '#ccc'\n )\n ;\n\n\n let\n accessor = function (d) {\n return d.id;\n };\n this\n .addHoverCallbacks(\n this\n .nodeGroup\n ,\n \"g.node\"\n ,\n accessor\n )\n ;\n\n //force functions\n force\n .on(\n \"tick\"\n ,\n function () {\n\n self.edges.attr({\n \"x1\": function (d) {\n return d.source.x;\n },\n \"y1\": function (d) {\n return d.source.y;\n },\n \"x2\": function (d) {\n return d.target.x;\n },\n \"y2\": function (d) {\n return d.target.y;\n }\n });\n\n self.nodes.attr(\"transform\", function (d) {\n //return \"translate(\" + (graph.node(d).x-self.nodeWidth/2) + \",\" + (graph.node(d).y-self.nodeHeight/2) + \")\";\n return \"translate(\" + (d.x - self.nodeWidth / 2) + \",\" + (d.y - self.nodeHeight / 2) + \")\";\n });\n\n\n self.edgePaths.attr('d', function (d) {\n var path = 'M ' + d.source.x + ' ' + d.source.y + ' L ' + d.target.x + ' ' + d.target.y;\n return path\n });\n\n }\n )\n ;\n\n }", "function initLineGraph(){\n if(lg){\n lg.remove();\n }\n lg = d3.select(\"#line-graph\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n}", "function makeGraph() {\n let numNodes = document.querySelector(\"#numNodes\").value;\n\n d3.selectAll(\"g\").remove();\n\n //Call generate graph to update global graph object with\n //new nodes and edges us geometric graph model\n genGeomGraph(numNodes, 120);\n\n makeNetwork();\n}", "function drawLinks()\n{\n link.attr(\"x1\", function(d) { return isNaN(d.source.x)?defaultX:d.source.x; })\n .attr(\"y1\", function(d) { return isNaN(d.source.y)?defaultY:d.source.y; })\n .attr(\"x2\", function(d) { return isNaN(d.target.x)?defaultX:d.target.x; })\n .attr(\"y2\", function(d) { return isNaN(d.target.y)?defaultY:d.target.y; });\nif (curvedLinks){\n\tlink.attr(\"d\", function(d) {\n\t\tvar even=d.source.id%2;\n\t\tvar intermediateX=d.source.x+((even==0)?1:-1)*(100);\n\t\t//console.log(d.source.name+\":\"+d.target.name+\" intermediateX: \"+intermediateX);\n\t\t//console.log(even+\":\"+d);\n\t linkOrientation=linkOrientation*-1;\t\n return \"M\" + d.source.x + \",\" + d.source.y\n + \"S\" + intermediateX + \",\" + d.source.y\n + \" \" + d.target.x + \",\" + d.target.y;\n });\n}\n}", "function drawGraph(links, svg, div_name) {\n\tif (svg) { // Remove old drawing.\n\t\tsvg.selectAll(\"*\").remove();\n\t\tsvg.remove();\n\t}\n\tvar nodes = {};\n\t// Compute the distinct nodes from the links.\n\tlinks.forEach(function(link) {\n\t\tlink.source = nodes[link.source] || (nodes[link.source] = {\n\t\t\tname : link.source\n\t\t});\n\t\tlink.target = nodes[link.target] || (nodes[link.target] = {\n\t\t\tname : link.target\n\t\t});\n\t});\n\tvar force = d3.layout.force().nodes(d3.values(nodes)).links(links).size(\n\t\t\t[ DIV_WIDTH, DIV_HEIGHT ]).linkDistance(60).charge(-300).on(\"tick\",\n\t\t\ttick).start();\n\tsvg = d3.select(div_name).append(\"svg\").attr(\"viewBox\",\n\t\t\t\"0 0 \" + DIV_WIDTH + \" \" + DIV_HEIGHT);\n\t// Add links to svg.\n\tvar link = svg.selectAll(\".link\").data(force.links()).enter()\n\t\t\t.append(\"line\").attr(\"class\", \"link\");\n\t// Add nodes to svg.\n\tvar node = svg.selectAll(\".node\").data(force.nodes()).enter().append(\"g\")\n\t\t\t.attr(\"class\", \"node\").on(\"mouseover\", mouseover).on(\"mouseout\",\n\t\t\t\t\tmouseout).call(force.drag);\n\tnode.append(\"circle\").attr(\"r\", 10);\n\tnode.append(\"text\").attr(\"x\", 12).attr(\"dy\", \".35em\").text(function(d) {\n\t\treturn d.name;\n\t});\n\n\tfunction tick() {\n\t\tnode.attr(\"transform\", function(d) {\n\t\t\t// If the graph is graph1, then store its x and y positions.\n\t\t\tif (div_name.localeCompare(GRAPH1_DIV_NAME) == 0) {\n\t\t\t\tgraph1_x[d.name] = d.x;\n\t\t\t\tgraph1_y[d.name] = d.y;\n\t\t\t} else {\n\t\t\t\t// Set graph 2 nodes to same position as graph 1.\n\t\t\t\tif (graph1_x[d.name] == undefined) { // There is a node in\n\t\t\t\t\t// graph 2 not in graph\n\t\t\t\t\t// 1.\n\t\t\t\t\td.x = Math.random()*DIV_WIDTH;\n\t\t\t\t\td.y = Math.random()*DIV_HEIGHT;\n\t\t\t\t\tgraph1_x[d.name] = d.x;\n\t\t\t\t\tgraph1_y[d.name] = d.y;\n\t\t\t\t} else {\n\t\t\t\t\td.x = graph1_x[d.name];\n\t\t\t\t\td.y = graph1_y[d.name];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn \"translate(\" + d.x + \",\" + d.y + \")\";\n\t\t});\n\t\tlink.attr(\"x1\", function(d) {\n\t\t\treturn d.source.x;\n\t\t}).attr(\"y1\", function(d) {\n\t\t\treturn d.source.y;\n\t\t}).attr(\"x2\", function(d) {\n\t\t\treturn d.target.x;\n\t\t}).attr(\"y2\", function(d) {\n\t\t\treturn d.target.y;\n\t\t});\n\t}\n\n\tfunction mouseover() {\n\t\td3.select(this).select(\"circle\").transition().duration(750).attr(\"r\",\n\t\t\t\t16);\n\t}\n\n\tfunction mouseout() {\n\t\td3.select(this).select(\"circle\").transition().duration(750)\n\t\t\t\t.attr(\"r\", 8);\n\t}\n\t// Update svg of each graph.\n\tif (div_name.localeCompare(GRAPH1_DIV_NAME) == 0) {\n\t\tsvg1 = svg;\n\t} else {\n\t\tsvg2 = svg;\n\t}\n\tfirstDraw = 0;\n}", "createLinkNodes() {\n const radius = this.r;\n let mouseDownRecently = false;\n let nodeDragData = {};\n let dragging = false;\n let mouseUpRecently = false;\n\n this.linkNode = this.d3Graph.selectAll(null)\n .data(this.nodes.slice(0, 8))\n .enter()\n .append('g');\n\n this.linkNode\n .append('circle')\n .attr('class', 'linkCircle')\n .attr('r', radius)\n .attr('border', 'none')\n .attr('outline', 'none')\n .style('cursor', 'pointer')\n .attr('fill', d => `url(#${d.name})`)\n .on('mouseenter', function freeze(d) {\n // Freeze the node and enlarge it\n // (the if statement is just a bug fix to ensure the drag feature works as desired)\n if (!dragging && !mouseUpRecently) {\n d.frozen = true;\n d.vxs = d.vx;\n d.vys = d.vy;\n d.r = radius * 1.085;\n d3.select(this)\n .transition()\n .duration(210)\n .attr('r', radius * 1.085);\n\n d3.select(this.parentNode).select('.icon')\n .transition()\n .duration(210)\n .attr('width', z => z.width * 1.14)\n .attr('height', z => z.height * 1.14)\n .attr('x', z => (-z.width / 2) * 1.14)\n .attr('y', z => (-z.height / 2) * 1.14);\n }\n })\n .on('mouseleave', function unFreeze(d) {\n if (d.frozen && !dragging) {\n // Unfreeze the node and return to it's stored velocity\n d.frozen = false;\n d.vx = d.vxs;\n d.vy = d.vys;\n // Reset the circle and icon to their unfrozen state\n d.r = radius;\n d3.select(this)\n .transition()\n .duration(210)\n .attr('r', radius);\n\n d3.select(this.parentNode).select('.icon')\n .transition()\n .duration(210)\n .attr('width', z => z.width)\n .attr('height', z => z.height)\n .attr('x', z => -z.width / 2)\n .attr('y', z => -z.height / 2);\n }\n })\n .call(d3.drag()\n .on('start', (d) => {\n dragging = true;\n\n // Capture data from the drag start\n this.getMouse();\n nodeDragData = {\n startX: d.x,\n startY: d.y,\n difX: this.mouseX - d.x,\n difY: this.mouseY - d.y,\n };\n\n // mouseDownRecently is used on mouse up/ drag end to help determine\n // if the user's intention was to click or drag\n mouseDownRecently = true;\n setTimeout(() => {\n mouseDownRecently = false;\n }, 500);\n })\n .on('drag', (d) => {\n // Update node position on drag\n this.getMouse();\n d.x = this.mouseX - nodeDragData.difX;\n d.y = this.mouseY - nodeDragData.difY;\n })\n .on('end', function endDrag(d) {\n dragging = false;\n\n // Helps fix bug where upon drag release the mouse would\n // enter the node again causing it to freeze\n mouseUpRecently = true;\n setTimeout(() => {\n mouseUpRecently = false;\n }, 100);\n\n // Unfreeze the node and calculate a velocity based on the direction/speed of the drag\n d.frozen = false;\n d.vx = (d.x - d.lx) / 10;\n d.vy = (d.y - d.ly) / 10;\n\n while (Math.abs(d.vx) + Math.abs(d.vy) > 30) {\n d.vx /= 1.3;\n d.vy /= 1.3;\n }\n\n // Reset the circle and icon to their unfrozen state\n d.r = radius;\n d3.select(this)\n .transition()\n .duration(0)\n .attr('r', radius);\n\n d3.select(this.parentNode).select('.icon')\n .transition()\n .duration(0)\n .attr('width', z => z.width)\n .attr('height', z => z.height)\n .attr('x', z => -z.width / 2)\n .attr('y', z => -z.height / 2);\n\n // Open link if the user's intention was most likely\n // a click and not a drag (based on if mouse was\n // down recently, and if drag distance was short)\n if (mouseDownRecently && Math.abs(nodeDragData.startX - d.x) < 10\n && Math.abs(nodeDragData.startY - d.y) < 10) {\n window.open(d.link, d.link === 'mailto:will@willchristman.com' ? '_self' : '_blank');\n }\n }));\n\n // Add an icon to the node\n this.linkNode.append('svg:image')\n .attr('class', 'icon')\n .attr('xlink:href', d => pathToImgs(`./${d.name}.svg`, true))\n .attr('width', d => d.width)\n .attr('height', d => d.height)\n .attr('x', d => -d.width / 2)\n .attr('y', d => -d.height / 2)\n .style('-webkit-touch-callout', 'none')\n .style('-webkit-user-select', 'none')\n .style('-khtml-user-select', 'none')\n .style('-moz-user-select', 'none')\n .style('-ms-user-select', 'none')\n .style('-o-user-select', 'none')\n .style('user-select', 'none')\n .style('opacity', 0.95)\n .style('pointer-events', 'none');\n }", "function initForceLayout(){\n\tsvg = d3.select('#viz')\n\t\t.append('svg')\n\t\t.attr('width', width)\n\t\t.attr('height', height);\n\tforce = d3.layout.force()\n\t .nodes(nodes)\n\t .links(links)\n\t .size([width, height])\n\t .linkDistance(400)\n\t .charge(-500)\n\t .on('tick', tick)\n\n\t// define arrow markers for graph links\n\tsvg.append('svg:defs').append('svg:marker')\n\t .attr('id', 'end-arrow')\n\t .attr('viewBox', '0 -5 10 10')\n\t .attr('refX', 6)\n\t .attr('markerWidth', 3)\n\t .attr('markerHeight', 3)\n\t .attr('orient', 'auto')\n\t .append('svg:path')\n\t .attr('d', 'M0,-5L10,0L0,5')\n\t .attr('fill', '#000');\n\t\n\tsvg.append('svg:defs').append('svg:marker')\n\t .attr('id', 'start-arrow')\n\t .attr('viewBox', '0 -5 10 10')\n\t .attr('refX', 4)\n\t .attr('markerWidth', 3)\n\t .attr('markerHeight', 3)\n\t .attr('orient', 'auto')\n\t .append('svg:path')\n\t .attr('d', 'M10,-5L0,0L10,5')\n\t .attr('fill', '#000');\n\t\n\t// line displayed when dragging new nodes\n\tdrag_line = svg.append('svg:path')\n\t .attr('class', 'link dragline hidden')\n\t .attr('d', 'M0,0L0,0');\n\t// handles to link and node element groups\n\tpath = svg.append('svg:g').selectAll('path'),\n\tcircle = svg.append('svg:g').selectAll('g');\n\t\n\tsvg.on('mousedown', createNode)\n\t .on('mousemove', mousemove)\n\t .on('mouseup', mouseup);\n\td3.select(\"#viz\")\n\t .on('keydown', keydown)\n\t .on('keyup', keyup);\n\trestart();\t\n}", "function renderSVG_() {\r\n d = parseData_(gData_.getData());\r\n gBindData_ = d[\"nodes\"];\r\n gLinkData_ = d[\"links\"];\r\n var arr = gBindData_;\r\n\r\n var elementContainer =\r\n\r\n gSVG_.selectAll(\".node_link\").remove();\r\n\r\n var glinkPath = gSVG_.selectAll(\".node_link\")\r\n .data(gLinkData_);\r\n\r\n var shape = gSVG_.selectAll(\".element\").data(arr);\r\n var shapeEnter = shape.enter();\r\n var shapeExit = shape.exit();\r\n gNodeEnter_ = shapeEnter;\r\n gNodeUpdate_ = shape;\r\n gNodeExit_ = shapeExit;\r\n\r\n\r\n glinkPath.enter().append(\"path\")\r\n .attr(\"class\", \"node_link\")\r\n .attr(\"data-from\", function(d) {\r\n return d.from;\r\n })\r\n .attr(\"data-to\", function(d) {\r\n return d.to;\r\n })\r\n .attr(\"id\", function(d) {\r\n return elementID_[\"pathId\"](d.from + '_' + d.to);\r\n })\r\n .attr(\"d\", function(d) {\r\n return d.pathData;\r\n });\r\n\r\n var g = gNodeEnter_.append(\"g\")\r\n .attr(\"data-shape-type\", function(d) {\r\n return d.type;\r\n })\r\n .attr(\"class\", function(d) {\r\n if (gCurrentSelectedData_ == d) return \"element current\";\r\n return \"element\";\r\n })\r\n .attr(\"id\", function(d) {\r\n return elementID_[\"elementId\"](dataFactory_.getId(d));\r\n })\r\n .each(function(d) {\r\n shapeFactory_[\"render\"](d, d3.select(this));\r\n });\r\n\r\n gNodeExit_.transition().remove();\r\n\r\n if (refreshCallback_)\r\n refreshCallback_();\r\n }", "function renderSVG_() {\r\n d = parseData_(gData_);\r\n gBindData_ = d[\"nodes\"];\r\n gLinkData_ = d[\"links\"];\r\n var arr = gBindData_;\r\n\r\n var shape = gSVG_.selectAll(\".element\").data(arr);\r\n var shapeEnter = shape.enter();\r\n var shapeExit = shape.exit();\r\n gNodeEnter_ = shapeEnter;\r\n gNodeUpdate_ = shape;\r\n gNodeExit_ = shapeExit;\r\n\r\n var g = gNodeEnter_.append(\"g\")\r\n .attr(\"data-shape-type\", function(d) {\r\n return d.type;\r\n })\r\n .attr(\"class\", function(d) {\r\n if (gCurrentSelectedData_ == d) return \"element current\";\r\n return \"element\";\r\n })\r\n .attr(\"id\", function(d) {\r\n return elementID_[\"generate\"](dataFactory_.getId(d));\r\n })\r\n .each(function(d) {\r\n shapeFactory_[\"render\"](d, d3.select(this));\r\n });\r\n\r\n gNodeExit_.transition().remove();\r\n\r\n var link = gSVG_.selectAll(\".node_link\")\r\n .data(gLinkData_)\r\n .enter().append(\"path\")\r\n .attr(\"class\", \"node_link\")\r\n .attr(\"d\", polylineData_);\r\n }", "function restart() {\n link.remove()\n link = g.selectAll('.link')\n .data(vis_link)\n .enter().append('g')\n .attr('class', 'link')\n line = link.append('line')\n .attr(\"stroke\", \"black\")\n .style('stroke-width', '1px')\n\n node.remove()\n node = g.selectAll('.node')\n .data(vis_node)\n .enter().append('g')\n .attr(\"class\", \"node\");\n\n node.call(d3.drag()\n .on(\"start\", dragstarted)\n .on(\"drag\", dragged)\n .on(\"end\", dragended));\n\n bubble = node.append('circle')\n .attr('r', function (d) {\n return Math.max(MAX_BUBBLE_RADIUS, r(d.count));\n })\n .style(\"stroke\", function (d) {\n if (common_node.includes(d.name)) {\n return \"#81c781\"//common node\n }\n else if (d.id.indexOf('subTopic')> -1) {\n return \"#DCDCDC\"//sub topic\n }\n else {\n return \"pink\"//main topic\n }\n })\n .style(\"fill\", function (d) {\n if (common_node.includes(d.name)) {\n return \"#81c781\"//common node\n }\n else if (d.id.indexOf('subTopic')> -1) {\n return \"#DCDCDC\"//sub topic\n }\n else {\n return \"white\"//main topic\n }\n })\n .style('stroke-width', function (d) {\n if (common_node.includes(d.name)) {\n return \"4px\"//common node\n }\n else if (d.id.indexOf('subTopic')> -1) {\n return \"4px\"//sub topic\n }\n else {\n return \"10px\"//main topic\n }\n })\n\n text = node.append('text')\n .text(function (d) {\n return d.name\n })\n .attr(\"text-anchor\", \"middle\")\n .style('fill', function (d) {\n if (common_node.includes(d.name)) {\n return \"black\"//common node\n }\n else if (d.id.indexOf('subtopic')> -1) {\n return \"black\"//sub topic\n }\n else {\n return \"darkred\"//main topic\n }\n })\n .style('font-size', function (d) {\n if (d.id.indexOf('subTopic') > -1) {\n return \"12px\"\n } else {\n return \"16px\"\n }\n })\n .attr(\"pointer-events\", \"none\");\n\n bubble.on(\"click\", update_data);\n\n\n bubble.on(\"contextmenu\", d3.contextMenu(menu));\n\n simulation.nodes(vis_node);\n simulation.alpha(1).restart();\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
input: route and swap indices output: swapped route
function twoOptSwap(route, i, k) { var diff = ((k)-i)/2; //console.log("i: ", i, "\tk: ", k, "\tlenRoute: ", route.length, "\tdiff: ",diff); //make sure i & k values are valid if (diff>(route.length)/2) { console.log("difference between k and i is larger than array size."); return } diff = Math.floor(diff); var add = 0; for (var index = i; index<(i+diff); index++) { var temp = route[index]; route[index] = route[k-add]; route[k-add] = temp; add++ } return route; }
[ "function twoOptSwap(route, i, k)\n{\n\tvar diff = ((k)-i)/2;\n\t//console.log(\"i: \", i, \"\\tk: \", k, \"\\tlenRoute: \", route.length, \"\\tdiff: \",diff);\n\t//make sure i & k values are valid\n\tif (diff>(route.length)/2)\n\t{\n\t\tconsole.log(\"difference between k and i is larger than array size.\");\n\t\treturn\n\t}\n\tdiff = Math.floor(diff);\n\tvar add = 0;\n\tfor (var index = i; index<(i+diff); index++)\n\t{\n\t\tvar temp = route[index];\n\t\troute[index] = route[k-add];\n\t\troute[k-add] = temp;\n\t\tadd++\n\t}\n\treturn route;\n}", "function two_opt_reversed(route,i,k) {\t\r\n\t\r\n // Temporary copy of the input route \r\n\tlet copy = route.slice();\r\n\r\n\t// Reverse the section of the reverse between i and k\r\n\tfor (let x = i-1, z=k-1; x < k; x++) {\t\r\n\t\troute[z] = copy[x];\r\n\t\tz--;\r\n\t}\t\t\r\n\treturn route;\t\r\n}", "swapNodes(idx1, idx2) {\n const VALS = this.values;\n\n const temp = VALS[idx1];\n VALS[idx1] = VALS[idx2];\n VALS[idx2] = temp;\n }", "_swapIndices(i1: number, i2: number): void {\n const temp = this._values[i1];\n this._values[i1] = this._values[i2];\n this._values[i2] = temp;\n }", "swapPositions(swapPos) {\r\n let zeroPos = this.zeroPosition();\r\n\r\n this.values[zeroPos] = this.values[swapPos];\r\n this.values[swapPos] = 0;\r\n this.numId = this.countId();\r\n this.estimatedDistance = this.countEstimatedDistance();\r\n }", "reverse() {// TODO: Fix flight plan indexes after reversal\n // this._waypoints.reverse();\n }", "function swapDiagonal(meshData, ind_triA, ind_triB)\n{\n var triangles = meshData.tri;\n var adjacency = meshData.adj;\n var vert2tri = meshData.vert_to_tri;\n\n //Find the node index of the outer vertex in each triangle\n const outernode_triA = adjacency[ind_triA].indexOf(ind_triB);\n const outernode_triB = adjacency[ind_triB].indexOf(ind_triA);\n\n //Indices of nodes after the outernode (i.e. nodes of the common edge)\n const outernode_triA_p1 = (outernode_triA + 1) % 3;\n const outernode_triA_p2 = (outernode_triA + 2) % 3;\n\n const outernode_triB_p1 = (outernode_triB + 1) % 3;\n const outernode_triB_p2 = (outernode_triB + 2) % 3;\n\n //Update triangle nodes\n triangles[ind_triA][outernode_triA_p2] = triangles[ind_triB][outernode_triB];\n triangles[ind_triB][outernode_triB_p2] = triangles[ind_triA][outernode_triA];\n\n //Update adjacencies for triangle opposite outernode\n adjacency[ind_triA][outernode_triA] = adjacency[ind_triB][outernode_triB_p1];\n adjacency[ind_triB][outernode_triB] = adjacency[ind_triA][outernode_triA_p1];\n\n //Update adjacency of neighbor opposite triangle A's (outernode+1) node\n const ind_triA_neigh_outerp1 = adjacency[ind_triA][outernode_triA_p1];\n if (ind_triA_neigh_outerp1 >= 0)\n {\n const neigh_node = adjacency[ind_triA_neigh_outerp1].indexOf(ind_triA);\n adjacency[ind_triA_neigh_outerp1][neigh_node] = ind_triB;\n }\n\n //Update adjacency of neighbor opposite triangle B's (outernode+1) node\n const ind_triB_neigh_outerp1 = adjacency[ind_triB][outernode_triB_p1];\n if (ind_triB_neigh_outerp1 >= 0)\n {\n const neigh_node = adjacency[ind_triB_neigh_outerp1].indexOf(ind_triB);\n adjacency[ind_triB_neigh_outerp1][neigh_node] = ind_triA;\n }\n\n //Update adjacencies for triangles opposite the (outernode+1) node\n adjacency[ind_triA][outernode_triA_p1] = ind_triB;\n adjacency[ind_triB][outernode_triB_p1] = ind_triA;\n\n //Update vertex to triangle connectivity, if data structure exists\n if (vert2tri.length > 0)\n {\n //The original outernodes will now be part of both triangles\n vert2tri[triangles[ind_triA][outernode_triA]].push(ind_triB);\n vert2tri[triangles[ind_triB][outernode_triB]].push(ind_triA);\n\n //Remove triangle B from the triangle set of outernode_triA_p1\n let local_ind = vert2tri[triangles[ind_triA][outernode_triA_p1]].indexOf(ind_triB);\n vert2tri[triangles[ind_triA][outernode_triA_p1]].splice(local_ind, 1);\n\n //Remove triangle A from the triangle set of outernode_triB_p1\n local_ind = vert2tri[triangles[ind_triB][outernode_triB_p1]].indexOf(ind_triA);\n vert2tri[triangles[ind_triB][outernode_triB_p1]].splice(local_ind, 1);\n }\n}", "function swapDiagonal(meshData, ind_triA, ind_triB)\n {\n var triangles = meshData.tri;\n var adjacency = meshData.adj;\n var vert2tri = meshData.vert_to_tri;\n\n //Find the node index of the outer vertex in each triangle\n var outernode_triA = adjacency[ind_triA].indexOf(ind_triB);\n var outernode_triB = adjacency[ind_triB].indexOf(ind_triA);\n\n //Indices of nodes after the outernode (i.e. nodes of the common edge)\n var outernode_triA_p1 = (outernode_triA + 1) % 3;\n var outernode_triA_p2 = (outernode_triA + 2) % 3;\n\n var outernode_triB_p1 = (outernode_triB + 1) % 3;\n var outernode_triB_p2 = (outernode_triB + 2) % 3;\n\n //Update triangle nodes\n triangles[ind_triA][outernode_triA_p2] = triangles[ind_triB][outernode_triB];\n triangles[ind_triB][outernode_triB_p2] = triangles[ind_triA][outernode_triA];\n\n //Update adjacencies for triangle opposite outernode\n adjacency[ind_triA][outernode_triA] = adjacency[ind_triB][outernode_triB_p1];\n adjacency[ind_triB][outernode_triB] = adjacency[ind_triA][outernode_triA_p1];\n\n //Update adjacency of neighbor opposite triangle A's (outernode+1) node\n var ind_triA_neigh_outerp1 = adjacency[ind_triA][outernode_triA_p1];\n if (ind_triA_neigh_outerp1 >= 0)\n {\n var neigh_node = adjacency[ind_triA_neigh_outerp1].indexOf(ind_triA);\n adjacency[ind_triA_neigh_outerp1][neigh_node] = ind_triB;\n }\n\n //Update adjacency of neighbor opposite triangle B's (outernode+1) node\n var ind_triB_neigh_outerp1 = adjacency[ind_triB][outernode_triB_p1];\n if (ind_triB_neigh_outerp1 >= 0)\n {\n var neigh_node = adjacency[ind_triB_neigh_outerp1].indexOf(ind_triB);\n adjacency[ind_triB_neigh_outerp1][neigh_node] = ind_triA;\n }\n\n //Update adjacencies for triangles opposite the (outernode+1) node\n adjacency[ind_triA][outernode_triA_p1] = ind_triB;\n adjacency[ind_triB][outernode_triB_p1] = ind_triA;\n\n //Update vertex to triangle connectivity, if data structure exists\n if (vert2tri.length > 0)\n {\n //The original outernodes will now be part of both triangles\n vert2tri[triangles[ind_triA][outernode_triA]].push(ind_triB);\n vert2tri[triangles[ind_triB][outernode_triB]].push(ind_triA);\n\n //Remove triangle B from the triangle set of outernode_triA_p1\n var local_ind = vert2tri[triangles[ind_triA][outernode_triA_p1]].indexOf(ind_triB);\n vert2tri[triangles[ind_triA][outernode_triA_p1]].splice(local_ind, 1);\n\n //Remove triangle A from the triangle set of outernode_triB_p1\n local_ind = vert2tri[triangles[ind_triB][outernode_triB_p1]].indexOf(ind_triA);\n vert2tri[triangles[ind_triB][outernode_triB_p1]].splice(local_ind, 1);\n }\n }", "function swapDiagonal(meshData, ind_triA, ind_triB) {\n const triangles = meshData.tri;\n const adjacency = meshData.adj;\n const vert2tri = meshData.vert_to_tri;\n\n //Find the node index of the outer vertex in each triangle\n const outernode_triA = adjacency[ind_triA].indexOf(ind_triB);\n const outernode_triB = adjacency[ind_triB].indexOf(ind_triA);\n\n //Indices of nodes after the outernode (i.e. nodes of the common edge)\n const outernode_triA_p1 = (outernode_triA + 1) % 3;\n const outernode_triA_p2 = (outernode_triA + 2) % 3;\n\n const outernode_triB_p1 = (outernode_triB + 1) % 3;\n const outernode_triB_p2 = (outernode_triB + 2) % 3;\n\n //Update triangle nodes\n triangles[ind_triA][outernode_triA_p2] = triangles[ind_triB][outernode_triB];\n triangles[ind_triB][outernode_triB_p2] = triangles[ind_triA][outernode_triA];\n\n //Update adjacencies for triangle opposite outernode\n adjacency[ind_triA][outernode_triA] = adjacency[ind_triB][outernode_triB_p1];\n adjacency[ind_triB][outernode_triB] = adjacency[ind_triA][outernode_triA_p1];\n\n //Update adjacency of neighbor opposite triangle A's (outernode+1) node\n const ind_triA_neigh_outerp1 = adjacency[ind_triA][outernode_triA_p1];\n if (ind_triA_neigh_outerp1 >= 0) {\n const neigh_node = adjacency[ind_triA_neigh_outerp1].indexOf(ind_triA);\n adjacency[ind_triA_neigh_outerp1][neigh_node] = ind_triB;\n }\n\n //Update adjacency of neighbor opposite triangle B's (outernode+1) node\n const ind_triB_neigh_outerp1 = adjacency[ind_triB][outernode_triB_p1];\n if (ind_triB_neigh_outerp1 >= 0) {\n const neigh_node = adjacency[ind_triB_neigh_outerp1].indexOf(ind_triB);\n adjacency[ind_triB_neigh_outerp1][neigh_node] = ind_triA;\n }\n\n //Update adjacencies for triangles opposite the (outernode+1) node\n adjacency[ind_triA][outernode_triA_p1] = ind_triB;\n adjacency[ind_triB][outernode_triB_p1] = ind_triA;\n\n //Update vertex to triangle connectivity, if data structure exists\n if (vert2tri.length > 0) {\n //The original outernodes will now be part of both triangles\n vert2tri[triangles[ind_triA][outernode_triA]].push(ind_triB);\n vert2tri[triangles[ind_triB][outernode_triB]].push(ind_triA);\n\n //Remove triangle B from the triangle set of outernode_triA_p1\n let local_ind = vert2tri[triangles[ind_triA][outernode_triA_p1]].indexOf(ind_triB);\n vert2tri[triangles[ind_triA][outernode_triA_p1]].splice(local_ind, 1);\n\n //Remove triangle A from the triangle set of outernode_triB_p1\n local_ind = vert2tri[triangles[ind_triB][outernode_triB_p1]].indexOf(ind_triA);\n vert2tri[triangles[ind_triB][outernode_triB_p1]].splice(local_ind, 1);\n }\n}", "function swap(arr, index1, index2) {\n // implementation\n}", "_reverseIndexOrder() {\n const coordIndicesSize = this._coordIndices.length;\n if (coordIndicesSize % 3 !== 0)\n return;\n if (coordIndicesSize !== this._tmpTexIndices.length && this._tmpTexIndices.length !== 0)\n return;\n\n for (let i = 0; i < coordIndicesSize; i += 3) {\n const i1 = i + 1;\n const i2 = i + 2;\n const third = this._coordIndices[i2];\n this._coordIndices[i2] = this._coordIndices[i1];\n this._coordIndices[i1] = third;\n\n const thirdIndex = this._tmpTexIndices[i2];\n this._tmpTexIndices[i2] = this._tmpTexIndices[i1];\n this._tmpTexIndices[i1] = thirdIndex;\n }\n }", "function swap(items, firstIndex, secondIndex) {\n\n var temp = items[firstIndex];\n items[firstIndex] = items[secondIndex];\n items[secondIndex] = temp;\n\n }", "function swap(A, indexA, indexB) {\n var temp = A[indexA];\n A[indexA] = A[indexB];\n A[indexB] = temp;\n}", "function swapAddresses() {\r\n\r\n\t// Get old address values\r\n\tvar fromAddress = document.getElementById('originAddress').value;\r\n\tvar toAddress = document.getElementById('destinationAddress').value;\r\n\r\n\t// Swap them\r\n\tdocument.getElementById('originAddress').value = toAddress;\r\n\tdocument.getElementById('destinationAddress').value = fromAddress;\r\n\r\n\t// Get directions if appropriate\r\n\tif (fromAddress != '' && toAddress != '') {\r\n\t\tclearDirections();\r\n\t\tgetDirections(currentDirectionsMode);\r\n\t}\r\n}", "function swapValues(arr, idx1, idx2) {\n\n }", "function routeCleanup (route) {\n // tip: Point.clone() does not work, thus the use of gfactory\n // also to compose new point objects based on route metadata\n var gfactory = new jsts.geom.GeometryFactory();\n\n // go through the transitions and clean up non-matching ends, which form visible breaks where the segments don't really touch\n // effectively, fudge the last point of the previous trail to be the same as the first point of next, so they will overlap\n for (var i=0, l=route.length-2; i<=l; i++) {\n var thisstep = route[i];\n var nextstep = route[i+1];\n\n // if the distance between the two points is quite close, don't bother; the topology is destined for a significant cleanup which will solve many of them\n var dx = thisstep.lastpoint.distance(nextstep.firstpoint);\n if (dx < 0.0001) continue;\n\n // clone the next segment's starting point, append it to our linestring; don't forget to update our lastpoint\n // this is way off API, modifying the geometry in place\n var newpoint = gfactory.createPoint(nextstep.firstpoint.coordinates.coordinates[0]);\n if (DEBUG) console.log([ 'patching gap', thisstep.debug, nextstep.debug, newpoint ]);\n thisstep.geom.geometries[0].points.coordinates.push(newpoint.coordinates.coordinates[0]);\n thisstep.lastpoint = newpoint;\n }\n\n // go through the transitions and generate a directions attribute by comparing the azimuth of the old path and the new path\n // - human directions with the name \"Turn right onto Schermerhorn Ct\"\n // - simplified directions fitting a domain \"R\"\n // - latlong of this step-segment's lastpoint vertex for the location of this transition\n //\n // add to the final point a transition as well, so caller doesn't need to scramble with \"if not segment.transition\"\n\n for (var i=0, l=route.length-2; i<=l; i++) {\n var thisstep = route[i];\n var nextstep = route[i+1];\n\n // find the azimuth (compass heading) of the two paths, and the difference between the azimuths, thus the turning\n // the azimuth of the line's overall bent (firstpoint to lastpoint) is easily thrown off by curves characteristic of trails\n // the azimuth of the very first or last vertex-pair, is too sensitive to very tiny variations when drawing shapes e.g. hand jitters\n // so try the azimuth of the last 3 such pairs, if that many exist\n\n var thispoints = thisstep.geom.getCoordinates().slice(-3);\n var this_last = thispoints[ thispoints.length-1 ], this_prev = thispoints[0];\n\n var nextpoints = nextstep.geom.getCoordinates().slice(0, 3);\n var next_first = nextpoints[0], next_second = nextpoints[nextpoints.length-1];\n\n var thislon2 = this_prev.x, thislat2 = this_prev.y, thislon1 = this_last.x, thislat1 = this_last.y;\n var nextlon2 = next_first.x, nextlat2 = next_first.y, nextlon1 = next_second.x, nextlat1 = next_second.y;\n\n var thisaz = (180 + rad2deg(Math.atan2(Math.sin(deg2rad(thislon2) - deg2rad(thislon1)) * Math.cos(deg2rad(thislat2)), Math.cos(deg2rad(thislat1)) * Math.sin(deg2rad(thislat2)) - Math.sin(deg2rad(thislat1)) * Math.cos(deg2rad(thislat2)) * Math.cos(deg2rad(thislon2) - deg2rad(thislon1)))) ) % 360;\n var nextaz = (180 + rad2deg(Math.atan2(Math.sin(deg2rad(nextlon2) - deg2rad(nextlon1)) * Math.cos(deg2rad(nextlat2)), Math.cos(deg2rad(nextlat1)) * Math.sin(deg2rad(nextlat2)) - Math.sin(deg2rad(nextlat1)) * Math.cos(deg2rad(nextlat2)) * Math.cos(deg2rad(nextlon2) - deg2rad(nextlon1)))) ) % 360;\n var angle = Math.round(nextaz - thisaz);\n if (angle > 180) angle = angle - 360;\n if (angle < -180) angle = angle + 360;\n if (DEBUG) console.log([ 'turning', thisstep.debug, nextstep.debug, thisaz, nextaz, angle ]);\n\n var turntype = TRANSITION_CODES.OTHER;\n if (angle >= -30 && angle <= 30) turntype = TRANSITION_CODES.STRAIGHT;\n else if (angle >= 31 && angle <= 60) turntype = TRANSITION_CODES.RIGHT_SOFT;\n else if (angle >= 61 && angle <= 100) turntype = TRANSITION_CODES.RIGHT_TURN;\n else if (angle >= 101) turntype = TRANSITION_CODES.RIGHT_HARD;\n else if (angle <= -30 && angle >= -60) turntype = TRANSITION_CODES.LEFT_SOFT;\n else if (angle <= -61 && angle >= -100) turntype = TRANSITION_CODES.LEFT_TURN;\n else if (angle <= -101) turntype = TRANSITION_CODES.LEFT_HARD;\n\n thisstep.transition = {\n lat: thisstep.lastpoint.coordinates.coordinates[0].y, // wow, no method for this?\n lng: thisstep.lastpoint.coordinates.coordinates[0].x, // wow, no method for this?\n title: thisstep.title + ' to ' + nextstep.title,\n code: turntype.code,\n title: turntype.text + nextstep.title,\n };\n }\n\n var thisstep = route[route.length-1];\n thisstep.transition = {\n lat: thisstep.lastpoint.coordinates.coordinates[0].y, // wow, no method for this?\n lng: thisstep.lastpoint.coordinates.coordinates[0].x, // wow, no method for this?\n code: TRANSITION_CODES.ARRIVE.code,\n title: TRANSITION_CODES.ARRIVE.text,\n };\n\n // metadata: the actually-requested starting latlng and target latlng\n route.wanted_start = gfactory.createPoint(new jsts.geom.Coordinate(route.start_segment.wanted_lng, route.start_segment.wanted_lat));\n route.wanted_end = gfactory.createPoint(new jsts.geom.Coordinate(route.target_segment.wanted_lng, route.target_segment.wanted_lat));\n\n // metadata: the closest point latlng and the closest distance, to our starting and ending segment\n // they already have these from findNearest() but let's formalize them into the output\n route.closest_point_start = gfactory.createPoint(new jsts.geom.Coordinate(route.start_segment.closest_lng, route.start_segment.closest_lat));\n route.closest_point_end = gfactory.createPoint(new jsts.geom.Coordinate(route.target_segment.closest_lng, route.target_segment.closest_lat));\n route.closest_distance_start = route.start_segment.closest_distance;\n route.closest_distance_end = route.target_segment.closest_distance;\n\n // and Bob's your uncle\n return route;\n}", "swap(first_index, second_index) {\r\n let temp = this.state.cards[first_index];\r\n this.state.cards[first_index] = this.state.cards[second_index];\r\n this.state.cards[second_index] = temp;\r\n }", "function swap(array, posA, posB) {\n var temp = array[posA]; \n array[posA] = array[posB]; \n array[posB] = temp; \n }", "function swapItems(arr,index1,index2){\n temp=arr[index1];\n arr[index1]=arr[index2];\n arr[index2]=temp;\n return arr;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Intercepts tags from markup and handles the way they resolve in react Internal links will update history (so they don't refresh the page) External links open new tabs
function handleClick(e) { if (e.target.nodeName === "A") { e.preventDefault(); console.log("markdown link click") if (e.target.href) { const url = new URL(e.target.href); //if it is an internal link, push to history so page doesnt refresh if (url.hostname.indexOf(".hotter.com") > -1 || url.hostname === "localhost" || url.hostname.indexOf("hotter-amplience-poc.herokuapp.com") > -1) { history.push(e.target.pathname); } else { //otherwise open new tab window.open(url.href, "_blank") } } } }
[ "function modifyAnchorTags(caller) {\n var tagParts, currentStateLink, isSamePage, pathHashCount;\n if (caller === \"modalPopupCtrl.pageContent\" || ctrl.currentLink === undefined) {\n currentStateLink = [];\n }\n else {\n currentStateLink = ctrl.currentLink.split('/');\n }\n $(ctrl.anchorTags).each(function (index) {\n if (ctrl.anchorTags[index].hasAttribute('href')) {\n var isExternalLink = ctrl.anchorTags[index].getAttribute('href').indexOf('http');\n if (isExternalLink === -1) {\n if (ctrl.anchorTags[index].getAttribute('href').indexOf('Page?$filter=contains(Title') !== -1) {\n $(ctrl.anchorTags[index]).attr('class', 'removed-link');\n var splittedArray = ctrl.anchorTags[index].getAttribute('href').split(\"'\");\n var pageTitle = null;\n if (splittedArray[1]) {\n pageTitle = splittedArray[1];\n }\n var docId = null;\n if (splittedArray[3]) {\n docId = splittedArray[3];\n }\n DocumentService.getAllPages(\"$filter=contains(tolower(Title),tolower('\" + pageTitle + \"')) and DocumentCode eq '\" + docId + \"'\")\n .then(function (result) {\n if (result.value.length > 0) {\n var popupData = '';\n var currentReleasePage = $.grep(result.value, function (e) { return e.ReleaseId === $rootScope.release; });\n if (currentReleasePage.length === 0) {\n if (result.value.length > 1) {\n popupData = createPopupData(result.value, index, caller);\n angular.element(ctrl.anchorTags[index]).attr('id', 'linktag' + index);\n angular.element(ctrl.anchorTags[index]).attr('data-toggle', 'dropdown');\n angular.element(ctrl.anchorTags[index]).attr('aria-haspopup', 'true');\n angular.element(ctrl.anchorTags[index]).attr('aria-expanded', 'false');\n $(ctrl.anchorTags[index]).wrap('<div style=\\\"display:inline-block;\\\" class=\\\"dropdown\\\"></div>');\n var linkText = angular.element(ctrl.anchorTags[index]).html();\n angular.element(ctrl.anchorTags[index]).html(linkText + \" <span class=\\\"caret\\\"></span> \");\n angular.element(popupData).insertAfter(ctrl.anchorTags[index]);\n } else {\n currentReleasePage = result.value[0];\n }\n } else {\n currentReleasePage = currentReleasePage[0];\n }\n if (caller === \"modalPopupCtrl.pageContent\") {\n if (popupData === '') {\n $(ctrl.anchorTags[index]).on(\"click\", function () {\n $rootScope.reloadPopUpOnLnkClk(currentReleasePage.Id);\n }\n );\n var buttonNewTab = window.document.createElement('a');\n angular.element(buttonNewTab).attr('href', '' + ctrl.docCenterUrl + '#/docHome/document/' + currentReleasePage.DocumentId +\n '/page/' + currentReleasePage.Id + '');\n angular.element(buttonNewTab).attr('target', '_blank');\n var spanNewTab = window.document.createElement('span');\n angular.element(buttonNewTab).append(' ');\n angular.element(buttonNewTab).append(spanNewTab);\n angular.element(buttonNewTab).insertAfter(ctrl.anchorTags[index]);\n }\n }\n else {\n $(ctrl.anchorTags[index]).on(\"click\", function () {\n if (popupData === '') {\n ctrl.changeState(currentReleasePage.DocumentId, currentReleasePage.Id, null);\n }\n });\n }\n $(ctrl.anchorTags[index]).removeAttr(\"class\");\n $(ctrl.anchorTags[index]).attr('style', 'cursor: pointer;');\n }\n });\n $(ctrl.anchorTags[index]).removeAttr('href');\n return;\n }\n tagParts = ctrl.anchorTags[index].getAttribute('href').split('/');\n isSamePage = ctrl.anchorTags[index].getAttribute('issamepage');\n pathHashCount = ctrl.anchorTags[index].getAttribute('isPathHavingHash');\n if (tagParts.length > 0) {\n ctrl.items = tagParts[tagParts.length - 1].split('#');\n // Check if the link is in the same page.\n if (currentStateLink[currentStateLink.length - 1] === ctrl.items[0] || isSamePage === \"true\") {\n if (ctrl.items.length > 1) {\n (function (anchorId) {\n $(ctrl.anchorTags[index]).on(\"click\", function () {\n ctrl.goToHeading(anchorId);\n });\n }(ctrl.items[1]));\n }\n $(ctrl.anchorTags[index]).removeAttr('issamepage');\n\n } else {\n var documentId, pageId, achId;\n documentId = tagParts[2];\n pageId = ctrl.items[0];\n achId = ctrl.items[1];\n if (pathHashCount && parseInt(pathHashCount, 10) > 0) {\n if (ctrl.items.length > parseInt(pathHashCount, 10) + 1) {\n achId = ctrl.items[ctrl.items.length - 1];\n var pageIdArray = ctrl.items.slice(0, ctrl.items.length - 1);\n pageId = pageIdArray.join('#');\n } else {\n pageId = ctrl.items.join('#');\n achId = null;\n }\n $(ctrl.anchorTags[index]).removeAttr('isPathHavingHash');\n }\n $(ctrl.anchorTags[index]).on(\"click\", function () {\n ctrl.changeState(documentId, pageId, achId);\n });\n }\n $(ctrl.anchorTags[index]).attr('style', 'cursor: pointer;');\n $(ctrl.anchorTags[index]).removeAttr(\"class\");\n $(ctrl.anchorTags[index]).removeAttr('href');\n }\n } else {\n $(ctrl.anchorTags[index]).attr('target', '_blank');\n }\n }\n });\n }", "function tagClick() {\n\n var reg_pattern = '((?:^#)' + $(this).text() + '$)|((?:^#)' + $(this).text() + '\\/)|([\\/]' + $(this).text() + '((?=\\/)|$))';\n var re_this = new RegExp(reg_pattern,'g');\n var tagexistsalready = re_this.test(window.location.hash);\n\n\tif(window.location.hash) {\n\t\tif(tagexistsalready) {\n\t\t\t//remove the tag from window.location.hash\n\t\t\tvar ourhash = window.location.hash;\n\t\t\twindow.location.hash = ourhash.replace(re_this, \"\");\n\t\t} else\n \t\twindow.location.hash = window.location.hash + \"/\" + $(this).text();\t\t\t\t//add this to it as #existing/this\n\t} else {\n \twindow.location.hash = window.location.hash + $(this).text();\n }\n\n return false;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//this stops the rest of the click event happening (i.e. the url ressetting to the actual href (just the one tag) of the link)\n}", "function onTagAReplasing() {\n printInElement('', true);\n var text = '<p>Please visit <a href=\"http://academy.telerik. com\">our site</a> to choose a training course. Also visit <a href=\"www.devbg.org\">our forum</a> to discuss the courses.</p>';\n var index = text.indexOf(\"<a\");\n\n printInElement(\"Before: \" + text + \"\\n\");\n while (index > -1) {\n text = text.replace('<a href=\"', '[URL=');\n text = text.replace('\">', ']');\n text = text.replace(\"</a>\", \"[/URL]\");\n index = text.indexOf(\"<a\", index + 1);\n }\n\n printInElement(\"After: \"+ text);\n}", "function intercept_links(selector) {\n $(selector).click(function(e) {\n var url = $(this).prop('href');\n\n //don't intercept external links or ones forced off\n if (this.host != location.host || $(this).hasClass(\"ext-link\") || $(this).attr(\"data-lightbox\")) {\n return;\n }\n\n //prevent link from clicking through\n e.preventDefault();\n\n //if we're linking to something on the same page\n if (this.protocol == location.protocol &&\n this.host == location.host &&\n this.pathname == location.pathname &&\n this.search == location.search) {\n \n //scoll to new anchor if one exists\n if (this.hash !== '' && this.hash !== '#') {\n\n //push new history state\n if (this.hash != location.hash) {\n history.pushState({url: url}, document.title, url);\n }\n\n //scroll to anchor\n window.scrollTo(0, $(this.hash).offset().top);\n }\n\n //don't do anything else if on the same page\n return;\n }\n\n //push new history state if link is valid\n history.pushState({url: url}, document.title, url);\n load_new_page(url);\n\n //clicking on a link should scroll to top\n //browser forward/back maintain scrolling positions\n window.scrollTo(0, 0);\n\t});\n}", "interceptLinks(hash) {\n\t\tvar t = this;\n\t\tdocument.body.addEventListener('onmouseover', function (e) {\n\t\t\t// ensure link\n\t\t\t// use shadow dom when available if not, fall back to composedPath()\n\t\t\t// for browsers that only have shady\n\t\t\tlet el = e.target;\n\n\t\t\tlet eventPath =\n\t\t\t\te.path || (e.composedPath ? e.composedPath() : null);\n\n\t\t\tif (eventPath) {\n\t\t\t\tfor (let i = 0; i < eventPath.length; i++) {\n\t\t\t\t\tif (!eventPath[i].nodeName) continue;\n\t\t\t\t\tif (eventPath[i].nodeName.toUpperCase() !== 'A') continue;\n\t\t\t\t\tif (!eventPath[i].href) continue;\n\n\t\t\t\t\tel = eventPath[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// allow skipping handler\n\t\t\tif (el.hasAttribute('native')) return;\n\n\t\t\t// check if the link is a navigation/relative link\n\t\t\tvar check = window.PineconeRouter.validLink(el, hash);\n\t\t\tif (!check.valid) return;\n\t\t\tif (t.settings.preloaded.path == check.link) return;\n\n\t\t\twindow.setTimeout(function () {\n\t\t\t\tfetch(check.link)\n\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\treturn response.text();\n\t\t\t\t\t})\n\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\tt.settings.preloaded.path = path;\n\t\t\t\t\t\tt.settings.preloaded.content = response;\n\t\t\t\t\t});\n\t\t\t}, t.settings.preloadTime);\n\t\t});\n\t}", "function interceptClickEvent(e) {\n var href;\n var target = e.target || e.srcElement;\n if (target.tagName === 'A') {\n href = target.getAttribute('href');\n var isLocal = href != null && href.startsWith('/');\n\n //put your logic here...\n if (isLocal) {\n location.hash = href;\n\n var anchorSearch = RegExp(/[\\/\\w]+(\\?\\w+=\\w*(&\\w+=\\w*))?#(\\w+)/g).exec(href);\n if (anchorSearch != null && anchorSearch[3] != null) {\n setImmediate(function () {\n var anchorElem = document.getElementById(anchorSearch[3]);\n anchorElem && anchorElem.scrollIntoView();\n });\n }\n\n //tell the browser not to respond to the link click\n e.preventDefault();\n }\n }\n }", "function interceptClickEvent(e) {\n var href;\n var target = e.target || e.srcElement;\n if (target.tagName === 'A') {\n href = target.getAttribute('href');\n let isLocal = href != null && href.startsWith('/');\n\n //put your logic here...\n if (isLocal) {\n location.hash = href;\n\n let anchorSearch = RegExp(/[\\/\\w]+(\\?\\w+=\\w*(&\\w+=\\w*))?#(\\w+)/g).exec(href);\n if (anchorSearch != null && anchorSearch[3] != null) {\n setTimeout(() => {\n let anchorElem = document.getElementById(anchorSearch[3]);\n anchorElem && anchorElem.scrollIntoView();\n }, 1);\n }\n\n //tell the browser not to respond to the link click\n e.preventDefault();\n }\n }\n }", "function interceptClickEvent(e) {\n var href;\n var target = e.target || e.srcElement;\n if (target.tagName === 'A') {\n href = target.getAttribute('href');\n var isLocal = href != null && href.startsWith('/');\n\n //put your logic here...\n if (isLocal) {\n location.hash = href;\n\n var anchorSearch = RegExp(/[\\/\\w]+(\\?\\w+=\\w*(&\\w+=\\w*))?#(\\w+)/g).exec(href);\n if (anchorSearch != null && anchorSearch[3] != null) {\n setTimeout(function () {\n var anchorElem = document.getElementById(anchorSearch[3]);\n anchorElem && anchorElem.scrollIntoView();\n }, 1);\n }\n\n //tell the browser not to respond to the link click\n e.preventDefault();\n }\n }\n }", "linksHandler() {\n\t\t\treplaceLinks(this.content, (href) => {\n\t\t\t\tthis.emit(EVENTS.CONTENTS.LINK_CLICKED, href);\n\t\t\t});\n\t\t}", "function handler(ev, eventArgs) {\n\t\tonDataLinkedTagChange.call(linkCtx, ev, eventArgs);\n\t\t// If the link expression uses a custom tag, the onDataLinkedTagChange call will call renderTag, which will set tagCtx on linkCtx\n\t}", "linksHandler() {\n\t\treplaceLinks(this.content, (href) => {\n\t\t\tthis.emit(EVENTS.CONTENTS.LINK_CLICKED, href);\n\t\t});\n\t}", "_scanLinks() {\n const self = this;\n const DOMNode = ReactDOM.findDOMNode(self);\n let foundElements = [];\n const reactI13n = self._getReactI13n();\n const scanTags = (self.props.scanLinks && self.props.scanLinks.tags) || DEFAULT_SCAN_TAGS;\n if (!DOMNode) {\n return;\n }\n self._subI13nComponents = [];\n\n // find all links\n scanTags.forEach((tagName) => {\n const collections = DOMNode.getElementsByTagName(tagName);\n if (collections) {\n foundElements = foundElements.concat(arrayFrom(collections));\n }\n });\n\n // for each link\n // 1. create a i13n node\n // 2. bind the click event\n // 3. fire created event\n // 4. (if enabled) create debug node for it\n foundElements.forEach((element) => {\n const I13nNodeClass = reactI13n.getI13nNodeClass() || I13nNode;\n const i13nNode = new I13nNodeClass(self._i13nNode, {}, true, reactI13n.isViewportEnabled());\n i13nNode.setDOMNode(element);\n const subThis = {\n props: {\n href: element.href,\n follow: true\n },\n getI13nNode: function getI13nNodeForScannedNode() {\n return i13nNode;\n }\n };\n\n subThis._shouldFollowLink = self._shouldFollowLink.bind(subThis);\n subThis.executeI13nEvent = self.executeI13nEvent.bind(self);\n\n self._subI13nComponents.push({\n componentClickListener: listen(element, 'click', clickHandler.bind(subThis)),\n debugDashboard: IS_DEBUG_MODE ? new DebugDashboard(i13nNode) : null,\n domElement: element,\n i13nNode\n });\n self._getReactI13n().execute('created', { i13nNode });\n });\n }", "onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab) {\n return originalTarget;\n }", "function interceptClickEvent(routerState$) {\n return (e) => { \n let target = e.target || e.srcElement; \n if (target.tagName === 'A') { \n let href = target.getAttribute('href'); \n let isLocal = href && href.startsWith('/'); \n let isAnchor = href && href.startsWith('#'); \n \n if (isLocal || isAnchor) { \n let {anchor, route, query} = parseLink(href); \n if (route === undefined) { \n route = routerState$.value.route; \n } \n pushRoute(routerState$, {route, query, anchor}); \n //tell the browser not to respond to the link click \n e.preventDefault();\n } \n }\n }\n}", "function bind_tag_click(event) {\n if (matchesReferers(event.target)) {\n remove_tag( event.target );\n }\n}", "addLinkEvents() {\n for (let link of document.getElementsByTagName('a')) {\n let oldUrl = link.getAttribute('href');\n let hashPos = oldUrl.indexOf('#');\n\n if (hashPos === -1) {\n link.href = '#' + oldUrl;\n }\n\n // link.addEventListener('click', (event) => {\n // event.preventDefault();\n // router.navigate(link.getAttribute('href'));\n // return false;\n // });\n }\n }", "addClickEventOnLinks() {\n let links = [];\n if (this.LinksToTriggerTag.tagName.toLowerCase() === 'a') {\n links = document.querySelectorAll(`a:not(.ribs-no-ajax)${this.LinksToTriggerClassString}`);\n } else {\n links = this.LinksToTriggerTag.querySelectorAll('a:not(.ribs-no-ajax)');\n }\n\n links.forEach((element) => {\n element.addEventListener('click', event => this.triggerLinkClick(event))\n });\n }", "function interceptClickEvent(e) {\n var href;\n var target = e.target || e.srcElement;\n if ((target.tagName === 'A') && (target.href != \"\")) { // Check that href is not empty (like in the case of tabs)\n href = target.getAttribute('href');\n\n if (true) {\n bodyWrapper.classList.add('fade');\n masthead.classList.add('fade');\n siteNavigationOverlay.classList.add('fade');\n //tell the browser not to respond to the link click\n e.preventDefault();\n // navigate to the link after the transion has ended\n bodyWrapper.addEventListener(\"transitionend\", function(e) { window.location.href = href; });\n }\n }\n }", "function onClickTag(e)\n{\n\tif (!e) var e = window.event;\n\tvar theTarget = resolveTarget(e);\n\tvar popup = Popup.create(this);\n\tvar tag = this.getAttribute(\"tag\");\n\tvar title = this.getAttribute(\"tiddler\");\n\tif(popup && tag)\n\t\t{\n\t\tvar tagged = store.getTaggedTiddlers(tag);\n\t\tvar titles = [];\n\t\tvar li,r;\n\t\tfor(r=0;r<tagged.length;r++)\n\t\t\tif(tagged[r].title != title)\n\t\t\t\ttitles.push(tagged[r].title);\n\t\tvar lingo = config.views.wikified.tag;\n\t\tif(titles.length > 0)\n\t\t\t{\n\t\t\tvar openAll = createTiddlyButton(createTiddlyElement(popup,\"li\"),lingo.openAllText.format([tag]),lingo.openAllTooltip,onClickTagOpenAll);\n\t\t\topenAll.setAttribute(\"tag\",tag);\n\t\t\tcreateTiddlyElement(createTiddlyElement(popup,\"li\"),\"hr\");\n\t\t\tfor(r=0; r<titles.length; r++)\n\t\t\t\t{\n\t\t\t\tcreateTiddlyLink(createTiddlyElement(popup,\"li\"),titles[r],true);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\tcreateTiddlyText(createTiddlyElement(popup,\"li\",null,\"disabled\"),lingo.popupNone.format([tag]));\n\t\tcreateTiddlyElement(createTiddlyElement(popup,\"li\"),\"hr\");\n\t\tvar h = createTiddlyLink(createTiddlyElement(popup,\"li\"),tag,false);\n\t\tcreateTiddlyText(h,lingo.openTag.format([tag]));\n\t\t}\n\tPopup.show(popup,false);\n\te.cancelBubble = true;\n\tif (e.stopPropagation) e.stopPropagation();\n\treturn(false);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LOADING MORE POSTS ON THE FEED/HOME PAGE
function grabFeedPosts() { $.ajax(`/poem/fetchmore/4?page=${$page}`, { type:'GET', error:function(data) { console.log(data.responseText); }, success:function(data) { $poemscontainer.append(data); if($spanmore.text().trim() == $('.poem').length) { $loaderbody.remove(); } else { $loaderbody.hide(); } $page++; } }) }
[ "function moreFeed()\n\t{\n\t\tpostsToView += 10;\t\n\t\tonRequestBlogs();\n\t}", "function handleLoadMore(){\n if(hasMore && blogs.length ==20){\n setPageNumber(pageNumber+1)\n }\n }", "loadMore(e) {\n e.preventDefault();\n this.loadMoreNum += 10;\n if (this.loadMoreNum <= this.state.defaultPosts.length) {\n this.setState({\n posts: this.state.defaultPosts.slice(0, this.loadMoreNum)\n }, this.hideMoreLinks);\n } else {\n this.setState({\n posts: this.state.defaultPosts.slice(0, this.state.defaultPosts.length)\n }, this.hideMoreLinks);\n }\n /** Hide more links from Wordpress*/\n this.hideMoreLinks();\n }", "function fetchMorePosts()\n\t{\n\t\tsetTimeout(function(){\n\t\t\t\t$loaderbody.show();\n\t\t}, 3000)\n\n\t\tsetTimeout(function() {\n\n\t\t\tif($urlDeterminer)\n\t\t\t{\n\t\t\t\tgrabTypePosts();\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tgrabFeedPosts();\n\t\t\t}\n\n\t\t}, 6000)\n\t}", "function displayTenMore() {\n if (!firstPageDisplayed) {\n firstPageDisplayed = parseInt(((postsStartPosition+10)/10), 10);\n }\n postsStartPosition = postsStartPosition+10;\n showPosts(10);\n }", "loadMorePosts() {\n const { loadMorePosts, currentGallery, postsByCategory } = this.props\n const { lastItemFetchedId } = postsByCategory.currentGallery\n loadMorePosts(currentGallery, lastItemFetchedId)\n }", "function nextPage(){\n console.log(\"load more has been clicked\")\n ++posts_page;\n fetchPosts();\n}", "function load_following_posts() {\n document.querySelector('#form-view').style.display = 'block';\n document.querySelector('#post-list').style.display = 'block';\n document.querySelector('#post-list').innerHTML = '';\n document.querySelector('#profile-view').style.display = 'none'; \n document.querySelector('#profile-view').innerHTML = ''; \n\n fetch('/followed_posts')\n .then(response => response.json())\n .then(posts => {\n paginate_posts(posts);\n });\n}", "function nineline_load_more_entries() {\n\t\t\t/**\n\t\t\t * Load more posts on click\n\t\t\t */\n\t\t\t$( '#load-more' ).click( function() {\n\t\t\t\tevent.preventDefault();\n\t\t\t\t\n\t\t\t\t$( '.processed' ).hide(); // Hide all the currently showed posts\n\t\t\t\tpage++; // Indicate that a seperate set of posts are being loaded\n\t\t\t\t\n\t\t\t\ttable = create2DArray( wholeWidth + 1 ); // Reset the table so can layout posts again\n\t\t\t\t\n\t\t\t\tnineline_layout_entries();\n\t\t\t});\t\n\t\t\t\n\t\t\t/**\n\t\t\t * Load the last page of posts\n\t\t\t */\n\t\t\t$( '#prev' ).click( function() {\n\t\t\t\tevent.preventDefault();\n\t\t\t\t\n\t\t\t\tpage--;\n\t\t\t\t\n\t\t\t\t/**\n\t\t\t\t * Find all the entries and hide/show the relevant ones\n\t\t\t\t */\n\t\t\t\t$( '.entry' ).each( function() {\n\t\t\t\t\tif( $( this ).attr( 'data-page' ) == ( page ) ) {\n\t\t\t\t\t\t$( this ).show( 'slow' );\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$( this ).hide( 'slow' );\n\t\t\t\t\t}\t\n\t\t\t\t});\n\t\t\t});\n\t\t}", "function loadMorePostsSubController(e) {\n let currentLoaderElement = e.target.closest(`.${DOMstrings.posts.loadMore}`);\n \n mainView.hideLoaderElement(currentLoaderElement);\n\n appState.session.postsPage++;\n renderPosts(appState.session.postsPage);\n}", "function displayTen() {\n firstPageDisplayed = false;\n hideAllPosts();\n showPosts(10);\n}", "function loadMoreJokes() {\n requestNext10RedditJokes();\n}", "handleLoadMorePosts() {\n\t\t\t// Get page no from data attribute of load-more button.\n\t\t\tconst page = this.loadMoreBtn.data( 'page' );\n\t\t\tif ( ! page ) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst newPage = parseInt( page ) + 1; // Increment page count by one.\n\n\t\t\t$.ajax( {\n\t\t\t\turl: this.ajaxUrl,\n\t\t\t\ttype: 'post',\n\t\t\t\tdata: {\n\t\t\t\t\tpage: page,\n\t\t\t\t\taction: 'load_more',\n\t\t\t\t\tajax_nonce: this.ajaxNonce,\n\t\t\t\t},\n\t\t\t\tsuccess: ( response ) => {\n\t\t\t\t\tif ( 0 === parseInt( response ) ) {\n\t\t\t\t\t\tthis.loadMoreBtn.remove();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.loadMoreBtn.data( 'page', newPage );\n\t\t\t\t\t\t$( '#load-more-content' ).append( response );\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\terror: ( response ) => {\n\t\t\t\t\t// console.log( response );\n\t\t\t\t},\n\t\t\t} );\n\t\t}", "function loadedPosts(e) {\n //don't clear if the url's got a timestamp marker in it, indicating \"load more posts\"\n if (e.target.responseURL.search(\"&before=\") < 0) postgrid.innerHTML = \"\";\n //console.log(e.target.response);\n let json = JSON.parse(e.target.response);\n let postdelay = 0;\n for (const post of json.response) {\n switch (post.type) {\n case \"photo\":\n //console.log(\"creating photo post\");\n createPhotoPost(post, postdelay);\n break;\n case \"text\":\n //console.log(\"creating text post\");\n createTextPost(post, postdelay);\n break;\n default:\n //console.log(String.toString(post));\n break;\n }\n postdelay += 0.1;\n pagetimestamp = post.timestamp;\n }\n removeErrors();\n loaderbutton.style.display = \"block\";\n}", "loadPosts(){\n\t\tlet lst=this.state.posts.length;\n\t\tfetch(\"/visitor/get/\"+lst,\n\t\t{\n\t\t\tmethod:\"GET\",\n\t\t\theaders:{\"Content-Type\":\"application/json\"},\n\t\t}).then((resp)=>resp.json()).then((resp)=>{\n\t\t\t\n\t\t\tthis.updateProps([\"posts\"],[resp]);\n\t\t}).catch((err)=>{\n\t\t\tconsole.log(\"something went wrong\");\n\t\t\tconsole.log(err);\n\t\t});\n\t}", "function loadMoreArticles() {\n if (! fetchedArticles || fetchedArticles.length == 0) {\n $.get({\n url: articlesJsonUrl,\n data: null,\n success: onGetArticles,\n dataType: 'json',\n });\n }\n else {\n displayMoreArticles();\n }\n }", "function loadPosts() {\n API.getPosts(session.get()._id)\n .then(res =>\n setPosts(res.data)\n )\n .catch(err => console.log(err));\n }", "function loadRecent() {\n if (paginationOptions.pageFirst > 0) {\n paginationOptions.pageFirst = 0;\n }\n viewsOptions.page = paginationOptions.pageFirst;\n\n return retreiveArticles(viewsOptions);\n }", "function fetchMorePosts() {\n const localPage = page + 1;\n return fetchPosts(localPage)\n .then(results => {\n const newPosts = [...posts, ...results];\n setPosts(newPosts);\n })\n .catch(error => {\n setIsError(true);\n Logger.error(error);\n })\n .finally(() => {\n setIsFetching(false);\n setPage(localPage);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
moveToFront(PixelLayer) Moves a PixelLayer to the front of the canvas
function moveToFront(p){ p.moveToFront(); var uuid = p.uuid(); for(var i = 0; i < _pixelLayers.length; i++){ if(_pixelLayers[i].uuid() === uuid){ _pixelLayers.splice(i,1); _pixelLayers.unshift(p); break; } } }
[ "goToFront() {\n // This should only ever be used for sprites // used by compiler\n if (this.renderer) {\n // Let the renderer re-order the sprite based on its knowledge\n // of what layers are present\n this.renderer.setDrawableOrder(this.drawableID, Infinity, StageLayering.SPRITE_LAYER);\n }\n\n this.runtime.setExecutablePosition(this, Infinity);\n }", "function layerFront(e) {\n\n currentcanvas.bringToFront(selectedObject);\n selectedObject.setCoords();\n currentcanvas.renderAll();\n}", "function layerFront(e) {\n\n canvas.bringToFront(selectedObject);\n selectedObject.setCoords();\n canvas.renderAll();\n}", "function bringToFront() {\n canvas.bringToFront(canvas.getActiveObject());\n}", "function bringToFront(){\n console.log(\"Bring To Front\")\n image = canvas.getActiveObject();\n if (image) canvas.bringToFront(image)\n}", "bringToFront () {\n let layers = this.computedSortedLayers\n for (let index = 0; index < layers.length; ++index) {\n let layer = layers[index]\n layer.window.zIndex = startingZIndex + index\n }\n // this window gets highest zIndex\n this.zIndex = startingZIndex + layers.length\n }", "setToFront (e) {\n this.callback()\n this.setFocus()\n let index = new Date().getTime() / 1000\n this.container.style.zIndex = Math.floor(index) // largest integer less than or equal to a given number\n }", "setFront(){\n\t\tthis.cursor = this.front;\n\t}", "function move_canvas_to_top(canvas_id) {\n $(\"#layer\" + canvas_id).insertBefore($(\"#detector\"));\n}", "function moveLineToBack() {\n\n backLayer.image(lineLayer, 0, 0);\n backAndImageLayer.image(lineLayer, 0, 0);\n lineLayer.clear();\n}", "function showFrontInDOM() {\r\n $('.frontPoint').remove();\r\n front.all().forEach(function (point, index) {\r\n $('<div/>', {\r\n 'class': 'frontPoint'\r\n }).css('-webkit-transform', 'translate(' + point.x + 'px, ' + point.y + 'px)')\r\n .html(String(index))\r\n .appendTo('.tiles-container');\r\n });\r\n }", "function bringForward() {\n canvas.bringForward(canvas.getActiveObject());\n}", "bringToFront(){let zIndex='';const frontmost=OverlayElement.__attachedInstances.filter(o=>o!==this).pop();if(frontmost){const frontmostZIndex=frontmost.__zIndex;zIndex=frontmostZIndex+1;}this.style.zIndex=zIndex;this.__zIndex=zIndex||parseFloat(getComputedStyle(this).zIndex);}", "_makeCurrLayerOnion(canvas){\n canvas.style.opacity = .92; // apply onion skin to current canvas \n canvas.style.zIndex = 0;\n }", "function setupFront() {\n\n frontSizeX = windowWidth / 1.5;\n frontSizeY = windowHeight / 1.5;\n\n imageMode(CORNER);\n frontOpacity = 255; // make front visible in the beginning\n tint(255, frontOpacity); // use tint() to control front image's opacity\n image(front, 0, 0, frontSizeX, frontSizeY);\n\n rectMode(CENTER); // create a button to start game\n fill(252, 219, 3, frontOpacity - 50);\n rect(frontSizeX - 300, frontSizeY / 2, 160, 50); // adjust the button position based on frontSize\n\n textSize(12); // set text within the button\n fill(255, frontOpacity);\n text(\"Enter The Pyramids\", frontSizeX - 354, frontSizeY / 2);\n}", "function moveSelectedToFront(){\n\t\t\tif (selectedGraphic && selectedGraphic.getDojoShape()) {\n\t\t\t\tselectedGraphic.getDojoShape().moveToFront();\n\t\t\t\tconsole.log(\"Moved item to front\");\n\t\t\t}\n\t\t}", "popFront() {\n \tif (this.poses.length > 0) {\n \t\tthis.poses.shift();\n \t\t// TODO: shift drawing instructions rather than doing it all over\n \t\tthis.graphics.clear();\n \t\tthis.graphics.setStrokeStyle(this.strokeSize);\n \t\tthis.graphics.beginStroke(this.strokeColor);\n \t\tthis.graphics.lineTo(this.poses[0].position.x / this.scaleX, this.poses[0].position.y / -this.scaleY);\n \t\tfor (var i=1; i<this.poses.length; ++i) {\n \t\t\tthis.graphics.lineTo(this.poses[i].position.x / this.scaleX, this.poses[i].position.y / -this.scaleY);\n \t\t}\n \t}\n }", "function bringToFront () {\n lGroup.eachLayer(function(l){\n l.bringToFront();\n });\n }", "setAsBackground(shouldSet = true) {\n /* Pushes back in Z Index */\n canvas.style.zIndex = shouldSet ? '-99' : '0';\n\n /* Position Absolutely */\n canvas.style.position = shouldSet ? 'absolute' : 'relative';\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filters mouse events so an event is fired only if the mouse moved. filters out mouse events that occur when mouse is stationary but the elements under the pointer are scrolled.
function installFilteredMouseMove(element) { element.bind("mousemove", function (e) { var lastpos = lastMousePosition; if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) { $(e.target).trigger("mousemove-filtered", e); } }); }
[ "function installFilteredMouseMove(element){element.on(\"mousemove\",function(e){var lastpos=lastMousePosition;(lastpos===undefined||lastpos.x!==e.pageX||lastpos.y!==e.pageY)&&$(e.target).trigger(\"mousemove-filtered\",e)})}", "function installFilteredMouseMove(element){element.on(\"mousemove\",function(e){var lastpos=lastMousePosition;if(lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY){$(e.target).trigger(\"mousemove-filtered\",e);}});}", "function installFilteredMouseMove(element) {\nelement.bind(\"mousemove\", function (e) {\n var lastpos = lastMousePosition;\n if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {\n $(e.target).trigger(\"mousemove-filtered\", e);\n }\n });\n }", "function installFilteredMouseMove(element) { // 206\n element.on(\"mousemove\", function (e) { // 207\n var lastpos = lastMousePosition; // 208\n if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) { // 209\n $(e.target).trigger(\"mousemove-filtered\", e); // 210\n } // 211\n }); // 212\n } // 213", "function installFilteredMouseMove(element) {\n\t element.on(\"mousemove\", function (e) {\n var lastpos = lastMousePosition;\n if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {\n $(e.target).trigger(\"mousemove-filtered\", e);\n }\n });\n }", "function onMouseMoveCaptured(tracker,event){handleMouseMove(tracker,event);$.stopEvent(event);}", "function ignorePendingMouseEvents() { ignore_mouse = guac_mouse.touchMouseThreshold; }", "function mouseMoved() {\n\tvar mouseDidMove = (document.lastPointerX != document.pointerX || document.lastPointerY != document.pointerY);\n\t// somehow the mouse could be in a new place\n\tif (mouseDidMove || document.userScrolling) {\n // Animate anything that will change based on mouse position\n // In this case let's move the elastic boxes\n\t\thandleBoxes(document.pointerX, document.pointerY)\n\n // Reset movement indicators\n\t\tdocument.userScrolling = false;\n\t\tdocument.lastPointerX = document.pointerX;\n\t\tdocument.lastPointerY = document.pointerY;\n\t}\n}", "function onMouseMoveCaptured( tracker, event ) {\n handleMouseMove( tracker, event );\n $.stopEvent( event );\n }", "function mousemoveEvents(e) {\n if (isSuggestion(e) && !autoScrolled) {\n unselect(selectedLi);\n selectedLi = getSelectionMouseIsOver(e);\n select(selectedLi);\n }\n\n mouseHover = true;\n autoScrolled = false;\n }", "function removeMouseMove(){\r\n var fakeScroller = document.querySelector(\"#avoidScroll\");\r\n if(fakeScroller){\r\n if (document.addEventListener) {\r\n fakeScroller.removeEventListener('mousemove', MouseMoveHandler, false); //IE9, Chrome, Safari, Oper\r\n } else {\r\n fakeScroller.detachEvent(\"onmousemove\", MouseMoveHandler); //IE 6/7/8\r\n }\r\n }\r\n }", "function mouseMoveHandler(event){\n\t\t\tif(event.pageX == null && event.clientX != null){\n\t\t\t\tvar de = document.documentElement, b = document.body;\n\t\t\t\tlastMousePos.pageX = event.clientX + (de && de.scrollLeft || b.scrollLeft || 0);\n\t\t\t\tlastMousePos.pageY = event.clientY + (de && de.scrollTop || b.scrollTop || 0);\n\t\t\t}else{\n\t\t\t\tlastMousePos.pageX = event.pageX;\n\t\t\t\tlastMousePos.pageY = event.pageY;\n\t\t\t}\n\t\t\t\n\t\t\tvar offset = overlay.cumulativeOffset();\n\t\t\tvar pos = {\n\t\t\t\tx: xaxis.min + (event.pageX - offset.left - plotOffset.left) / hozScale,\n\t\t\t\ty: yaxis.max - (event.pageY - offset.top - plotOffset.top) / vertScale\n\t\t\t};\n\t\t\t\n\t\t\tif(options.mouse.track && selectionInterval == null){\t\t\t\t\n\t\t\t\thit(pos);\n\t\t\t}\n\t\t\t\n\t\t\ttarget.fire('flotr:mousemove', [event, pos]);\n\t\t}", "updateMouseMoveEvents() {\n this.updateEventsContainer('mouse-move');\n }", "function mouseDoesntMoved() {\n return mouseX === instantMouseX && mouseY === instantMouseY;\n}", "_subscribeToMouseMoves() {\n this._ngZone.runOutsideAngular(() => {\n fromEvent(this._menu.nativeElement, 'mousemove')\n .pipe(filter((_, index) => index % MOUSE_MOVE_SAMPLE_FREQUENCY === 0), takeUntil(this._destroyed))\n .subscribe((event) => {\n this._points.push({ x: event.clientX, y: event.clientY });\n if (this._points.length > NUM_POINTS) {\n this._points.shift();\n }\n });\n });\n }", "function temporarilyIgnoreMouseEvents()\n {\n // Set the variable\n vm.ignoreMouseEvents = true;\n\n // Cancel the previous timeout\n $timeout.cancel(vm.mouseEventIgnoreTimeout);\n\n // Set the timeout\n vm.mouseEventIgnoreTimeout = $timeout(function ()\n {\n vm.ignoreMouseEvents = false;\n }, 250);\n }", "function filterPrimaryPointer(eventHandler){return function(event){var isMouseEvent=event instanceof MouseEvent;var isPrimaryPointer=!isMouseEvent||isMouseEvent&&event.button===0;if(isPrimaryPointer){eventHandler(event);}};}", "function filterScroll() {\n\tvar thisFilter = $('.team-filter-scroll');\n\tvar thisFilterUl = thisFilter.find('ul');\n\tvar thW = 0;\n\t\n\tthisFilterUl.find('li').each(function(){\n\t\tthW+=$(this).outerWidth();\n\t});\n\tthisFilter.mousemove(function(e){\n\t\tvar blW = thisFilter.outerWidth();\n\t\tif(thW > blW){\n\t\t\tvar offset = thisFilter.offset();\n\t\t\tvar mX = e.pageX - offset.left;\n\t\t\tvar mM = (thW-blW)*mX/blW;\n\t\t\tthisFilterUl.css({marginLeft:-mM});\n\t\t}\n\t});\n}", "function onMouseMove(e) {\n if (_cursorOverScrollBar(e)) {\n e.currentTarget.children[1].style.pointerEvents = 'none';\n } else {\n e.currentTarget.children[1].style.pointerEvents = 'auto';\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the configuration panel from the local storage. The last configuration stored
function get_config_panel(config_name){ if(config_name=="") config_name=getUrlVars()["config_name"]; //console.log(localStorage.gpio_config); if (localStorage.getItem("gpio_config:"+config_name) === null){ create_first_configuration(); config_name="default"; } var rows = localStorage.getItem("gpio_config:" + config_name).split("\n"); $.each(rows, function( index, value ) { var data = value.split(";"); //console.log(data[1]); $('#'+data[0]+"_config").val(data[1]); $('#'+data[0]+'_type').val(data[2]); }); }
[ "function getConfig() {\n return JSON.parse(localStorage.getItem('bpmConfig'));\n}", "static load() { return JSON.parse(window.localStorage.getItem('settings')) || {}; }", "function getLocalConfig(strKey){\n\treturn window.localStorage.getItem(strKey);\n}", "_read() {\n try {\n if (!localStorage[this._keyName]) {\n return;\n }\n this._localConfig = JSON.parse(localStorage[this._keyName]);\n } catch (error) {\n console.warn(\"Unable to read configuration from localStorage:\", error);\n }\n }", "function getCurrentConfig() {\n chrome.storage.sync.get(defaultConfig, (config) => {\n if (!chrome.runtime.lastError) {\n // removeIf(!allowDebug)\n console.debug(\"config.js loaded.\");\n console.debug(\"Setting config from storage: %o\", config);\n // endRemoveIf(!allowDebug)\n for (let key in config) {\n _config[key] = config[key];\n let input = document.getElementById(key);\n if (!input) {\n // removeIf(!allowDebug)\n _config.doDebug &&\n console.debug(\n '--> Skipped config option \"%s\" with no control.',\n key\n );\n // endRemoveIf(!allowDebug)\n continue;\n }\n if (input.type === \"checkbox\") {\n input.checked = config[key];\n if (key === \"useDarkTheme\") {\n document.body.classList.toggle(\"theme-dark\", input.checked);\n // removeIf(!allowDebug)\n _config.doDebug &&\n console.debug(\n \"--> document.body class: %s\",\n document.body.className\n );\n // endRemoveIf(!allowDebug)\n } else if (key === \"isEnabled\") {\n setEnabledStateUi(input.checked);\n }\n // removeIf(!allowDebug)\n _config.doDebug &&\n console.debug(\n \"--> %s checkbox %s.\",\n input.checked ? \"Checked\" : \"Unchecked\",\n key\n );\n // endRemoveIf(!allowDebug)\n } else if (key === \"checkInterval\") {\n input.value = \"\" + config[key];\n // removeIf(!allowDebug)\n _config.doDebug &&\n console.debug(\"--> %s set to %s.\", key, input.value);\n // endRemoveIf(!allowDebug)\n }\n } // end for (let key in config).\n } else {\n console.info(\n \"Couldn't initialize config from storage: %s\",\n chrome.runtime.lastError.message\n );\n } // end chrome.storage.sync.get() error handler.\n });\n}", "async function getCurrentConfig() {\n let config;\n try {\n config = await browser.storage.sync.get(defaultConfig);\n // removeIf(!allowDebug)\n logDebug(\"config.js loaded.\");\n logDebug(\"Setting config from storage: %o\", config);\n // endRemoveIf(!allowDebug)\n for (let key in config) {\n let input = document.getElementById(key);\n if (!input) {\n // removeIf(!allowDebug)\n logDebug('--> Skipped option \"%s\" with no control.', key);\n // endRemoveIf(!allowDebug)\n continue;\n }\n if (input.type === \"checkbox\") {\n input.checked = config[key];\n if (key === \"useDarkTheme\") {\n document.body.classList.toggle(\"theme-dark\", input.checked);\n // removeIf(!allowDebug)\n logDebug(\"--> document.body classes: %s\", document.body.className);\n // endRemoveIf(!allowDebug)\n } else if (key === \"isEnabled\") {\n setEnabledStateUi(input.checked);\n }\n // removeIf(!allowDebug)\n logDebug(\n \"--> %s checkbox %s.\",\n input.checked ? \"Checked\" : \"Unchecked\",\n key\n );\n // endRemoveIf(!allowDebug)\n } else if (key === \"checkInterval\") {\n input.value = \"\" + config[key];\n // removeIf(!allowDebug)\n logDebug(\"--> %s set to %s.\", key, input.value);\n // endRemoveIf(!allowDebug)\n }\n } // end for (let key in config).\n } catch (error) {\n console.info(\"Couldn't initialize config from storage: %s\", error);\n }\n}", "function readConfigurationFromLocalStorage(){\n console.log(\"Reading configuration from local storage\");\n for (var attrib in configuration)\n {\n delete configuration[attrib];\n }\n for (var i = 0; i < localStorage.length; i++)\n {\n var key = localStorage.key(i);\n console.log(\"Reading value for \" + key);\n var value = localStorage.getItem(key);\n configuration[key] = value;\n }\n for (var key2 in configuration)\n {\n console.log(\"Config[\" + key2 + \"]=\" + configuration[key2]);\n }\n}", "function store_config_panel(config_name){\n\t//if(config_name==\"\")\n\t//\tconfig_name=getUrlVars()[\"config_name\"];\n\tvar data=\"\"\n\tconsole.log(\"store_config_panel \"+config_name);\n\t$('.gpio_name').each(function(index){ \n\t\tvar name= $(this).attr('id');\t \n\t\tname=name.replace(\"_config\", \"\");\n\t\tvar value= $(this).val();\t \n\t\tvar type = $('#'+name + '_type option:selected').text();\n\t\tdata+=name + ';'+value+';'+type+'\\n';\n\t\t\n\t\t//sendCommand(command);\n\t\t});\t\n\tlocalStorage.setItem(\"gpio_config:\"+config_name, data);\n\tconsole.log(localStorage.getItem(\"gpio_config:\"+config_name));\n\tsetUrlVars(\"config_name\", config_name);\n}", "function loadConfig() {\n const configAsString = localStorage.getItem(\"readerConfig\");\n try {\n const config = JSON.parse(configAsString);\n return config;\n } catch (e) {\n return {};\n }\n}", "static getConfig() {\n if (API.configCache == null) {\n API.configCache = $.get(\"serve_config.json\");\n }\n return API.configCache;\n }", "function readConfig() {\n let config = {};\n try {\n // Unfortunately Edge does not allow localStorage access for file:// urls\n const serializedConfig = localStorage.getItem(storageKey);\n config = JSON.parse(serializedConfig || '{}');\n }\n catch (err) {\n console.error(err);\n }\n return config;\n }", "function load_config(){\n S.config = K.config.fetch();\n return S.config;\n }", "get config() {\n this._cachedConfig = this._cachedConfig || getConfig();\n return this._cachedConfig;\n }", "function loadExtSettings() {\n extSettings = JSON.parse(localStorage.getItem(\"perpectiveGridSettings\"));\n }", "function getStoredPanelArray() {\n let previouslyopenpanels = JSON.parse(localStorage.getItem(\"panels\"));\n if ( previouslyopenpanels === null ) {\n panelArray = [];\n } else {\n panelArray = previouslyopenpanels;\n\n // iterate over array and show panels previously left open\n panelArray.forEach(function(element) {\n $panel = jQuery(\".scs-c-step-nav__steps\").find(\"#\" + element);\n $panel.toggleClass(\"js-hidden\");\n $panel.parent(\".scs-c-step-nav__step\").find(\".js-toggle-link\").html(\"hide\");\n\n // change button text\n showAllPanels = !showAllPanels;\n jQuery(\".js-step-controls-button\").html(showAllPanels ? \"Hide All\" : \"Show All\").end();\n\n\n });\n }\n}", "function getSettings(){\n if(localStorage.getItem('settings') !== null){\n settings = JSON.parse(localStorage.getItem('settings'));\n }\n}", "getLocalConfig() {\n return this.localConfig;\n }", "function lsd_cachedConfig() {\n\tif( lsd_config._cached ) {\n\t\treturn lsd_config;\n\t}\n\tthrow \"Invalid call : Config is not yet loaded / cached\";\n}", "static getConfig() {\n return this._getCurrentPlatform().getConfig();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get building by ID
getOne(buildingId, callback) { const query = "SELECT * FROM IntelliDoorDB.dbo.Buildings WHERE buildingId = @buildingId;"; const idParam = { name: 'buildingId', type: TYPES.NVarChar, value: buildingId }; sqlDB.sqlGet(query, idParam, function(error, result) { if(error) { callback(error, result); } else { callback(null, result); } }); }
[ "find(id) {\n return this.buildings.find((i) => i.id === id || i.email === id);\n }", "function getBuildingByName(name) {\n\tfor (i = 0; i < buildings.length; i++) {\n\t\tif (buildings[i].name == name) {\n\t\t\treturn buildings[i];\n\t\t}\n\t}\n\n\t// No building exists with given name\n\treturn null;\n}", "function getBuildIDForBuildBetaDetail(api, id) {\n return api_1.GET(api, `/buildBetaDetails/${id}/relationships/build`)\n}", "function findNameById(id) {\n for (var i = 0; i < buildings.length; ++i) {\n if (buildings[i].id === parseInt(id)) {\n return buildings[i].name;\n }\n }\n return \"\";\n }", "getDoorById(id = 0){\r\n return this.state.doors.filter(door => door.id === id)[0];\r\n }", "function getRoomById(id) {\n for (let i = 0; i < rooms.length; i++) {\n const room = rooms[i];\n if (room.id == id) {\n return room;\n }\n }\n return null;\n}", "getBuild(buildId) {\n const build = new build_1.Build(this.client, buildId);\n return build;\n }", "function getBuildBetaDetailsResourceIDForBuild(api, id) {\n return api_1.GET(api, `/builds/${id}/relationships/buildBetaDetail`)\n}", "function getBuildingDetails(id){\n\tcurrentBuildingId = id;\n\tvar json = '{\"id\":\"'+id+'\"}';\n\t$.ajax({type: \"POST\", url: \"/ajax.php\", data: \"&method=getBuildingDetails&params=\"+json,\n\t\terror: function(){\n\t\t\talert(\"An error occurred...!\");\n\t\t\treturn false;\t\t\t\n\t\t},\n\t\ttimeout: function(){\t\t\t\n\t\t\talert(\"Error: Server timeout\");\n\t\t\treturn false;\t\t\n\t\t}\n\t}).done(function( content ) {\t\n\t\t//content is encoded as JSON object\n\t\t//alert(content);\n\t\tvar obj = jQuery.parseJSON(content);\n\t\t\n\t\tbuildBuildingDetails(obj);\n\t\t\n\t});\n}", "getJobFromId(id) {\n console.log()\n return this.state.jobList.find((elm) => elm._id === id);\n }", "function get_single_cargo(id){\n console.log(\"inside get_single_cargo: \" + id);\n const key = datastore.key([CARGO, parseInt(id,10)]);\n return datastore.get(key).then( result => {\n var cargo = result[0];\n cargo.id = id; //Add id property to ship\n return cargo;\n }).catch( err => {\n console.log(\"ERR\");\n return false;\n });\n}", "Get(id) {\n\t\treturn this.obj.filter(function(o){return o.id == id;})[0];\n\t}", "static findByID(id) {\n return rooms.get(id);\n }", "BedById (root, { id }) {\n return getBedsByQuery( {id: Number(id)} );\n }", "function getRoomById(id)\n{\n var i = rooms.findIndex(function(room) {\n return room.id == id\n })\n\n return (i == -1) ? null : rooms[i]\n}", "static async getById(id) {\n const res = await db.query(\n `SELECT * \n FROM rooms\n WHERE id = $1`,\n [id]\n );\n const room = res.rows[0];\n if (!room) throw new NotFoundError(`No room with ID: ${id}`);\n return room;\n }", "function findJobById (id) {\r\n return state.jobs.find(job => job.id === id);\r\n}", "function getRoomByID(id)\n\t\t {\n\t\t\t\tvar deferred = $q.defer();\n\t\t\t\tvar room = _.findWithProperty( cache, \"id\", id );\n\n\t\t\t\tif ( room ) {\n\t\t\t\t\tdeferred.resolve( ng.copy( room ) );\n\t\t\t\t} else {\n\t\t\t\t\tdeferred.reject();\n\t\t\t\t}\n\t\t\t\treturn( deferred.promise );\n\t\t\t}", "async getUserBuilding() {\n\t\tif (this._isRootInstance) {\n\t\t\tlet closestBuilding;\n\t\t\ttry {\n\t\t\t\tawait this._getGeoLocation();\n\t\t\t\tlet buildingsForGeoLocation = await this._getBuildingsForGeoLocation();\n\t\t\t\tclosestBuilding = this._getClosestBuilding(buildingsForGeoLocation);\n\t\t\t} catch (error) {\n\t\t\t\tclosestBuilding = null;\n\t\t\t\tthis._clearGeoLocationPromise();\n\t\t\t}\n\t\t\tlet userBuilding;\n\t\t\tif (closestBuilding != null) {\n\t\t\t\tuserBuilding = closestBuilding;\n\t\t\t} else {\n\t\t\t\ttry { \n\t\t\t\t\tuserBuilding = await this._getUserPrimaryBuilding();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tuserBuilding = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn userBuilding && userBuilding._id ? userBuilding : null;\n\t\t} else {\n\t\t\treturn this._rootInstance.getUserBuilding();\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PRIVATE Allocates the destination coordenates of the connection at the middle point of the destination port.
function allocateDestination() { this.destinationX = this.destinationPort.x + 3 + this.destinationPort.ne.x; this.destinationY = this.destinationPort.y + 3 + this.destinationPort.ne.y; if (this.originX != null && this.originY != null) { this.allocate(); } }
[ "function allocateOrigin() {\n\t\tthis.originX = this.originPort.x + 3 + this.originPort.ne.x;\n\t\tthis.originY = this.originPort.y + 3 + this.originPort.ne.y;\n\t\tif (this.destinationX != null && this.destinationY != null) {\n\t\t\tthis.allocate();\n\t\t}\n\t}", "function allocateConnection() {\n\t\tif (document.getElementById(this.id) != null) {\n\t\t\tdocument.getElementById(MAP).removeChild(document.getElementById(this.id));\n\t\t}\n\t\tthis.points = this.originX + \",\" + this.originY + \" \";\n\t\tif (this.middlePoint == LEFT_CORNER) {\n\t\t\tvar x = Math.min(this.originX, this.destinationX);\n\t\t\tvar y = x == this.originX ? this.destinationY : this.originY;\n\t\t\tthis.points += x + \",\" + y + \" \";\n\t\t} else if (this.middlePoint == RIGHT_CORNER) {\n\t\t\tvar x = Math.max(this.originX, this.destinationX);\n\t\t\tvar y = x == this.originX ? this.destinationY : this.originY;\n\t\t\tthis.points += x + \",\" + y + \" \";\n\t\t}\n\t\tthis.points += this.destinationX + \",\" + this.destinationY;\n\t\tthis.write();\n\t}", "function SetDestinations() {\r\n\tmeDestination = new Vector(canvasWidth + actorSize, -actorSize);\r\n\tthemDestination = new Vector(-actorSize, canvasHeight + actorSize);\r\n}", "function allocatePort(numberOfPortsAtSameSide, position) {\n\t\tvar n = eval(numberOfPortsAtSameSide);\n\t\tvar pos = eval(position);\n\t\tif (this.side == TOP) {\n\t\t\tthis.x = Math.floor(this.ne.width / (n + 1) * pos);\n\t\t\tthis.y = -3;\n\t\t} else if (this.side == LEFT) {\n\t\t\tthis.x = -3;\n\t\t\tthis.y = Math.floor(this.ne.height / (n + 1) * pos);\n\t\t} else if (this.side == RIGHT) {\n\t\t\tthis.x = this.ne.width - 2;\n\t\t\tthis.y = Math.floor(this.ne.height / (n + 1) * pos);\n\t\t} else if (this.side == BOTTOM) {\n\t\t\tthis.x = Math.floor(this.ne.width / (n + 1) * pos);\n\t\t\tthis.y = this.ne.height - 2;\n\t\t}\n\t\tdocument.getElementById(this.id).style.left = this.x;\n\t\tdocument.getElementById(this.id).style.top = this.y;\n\t\tif (this.connection.originPort == this) {\n\t\t\tthis.connection.allocateOrigin();\n\t\t} else {\n\t\t\tthis.connection.allocateDestination();\n\t\t}\n\t}", "getConnectionPoints() {\n let startBound = this.startNode.getBounds()\n let endBound = this.endNode.getBounds()\n let startCenterX = (startBound.x + startBound.width) / 2\n let startCenterY = (startBound.y + startBound.height) / 2\n let endCenterX = (endBound.x + endBound.width) / 2\n let endCenterY = (endBound.y + endBound.height) / 2\n return [startNode.getConnectionPoint(endCenterX, endCenterY),\n endNode.getConnectionPoint(startCenterX, startCenterY)] \n }", "getConnectionArguments(destination, destinationIndex, toParam) {\n const connectTarget = toParam ? destination[toParam] : destination;\n // we use modulo for channel distribution\n // in case we're connecting to more nodes than we have channels\n const fromChannel = destinationIndex % this.props.channelCount;\n // normally we expect to connect to the first channel of each destination\n // but this can be overriden\n const toChannel = !isNaN(this.props.connectToChannel) ? this.props.connectToChannel : 0;\n\n return [ connectTarget ].concat(toParam ? [] : [ fromChannel, toChannel ]);\n }", "_count_ports_workaround ()\n\t{\n\t\t// first we fill this._poss with just the ports\n\t\tthis._patch.split(\"\\n\").forEach((line)=>{\n\t\t\tlet m = line.match(/^#X connect (.*);$/);\n\t\t\tif (!m) return;\n\t\t\tlet d = m[1].split(\" \");\n\t\t\tlet source = parseInt(d[0]);\n\t\t\tlet outlet = parseInt(d[1]);\n\t\t\tlet target = parseInt(d[2]);\n\t\t\tlet inlet = parseInt(d[3]);\n\n\t\t\tlet source_poss = this._poss[source];\n\t\t\tsource_poss.ooff[outlet] = null;\n\t\t\tthis._poss[source] = source_poss;\n\n\t\t\tlet target_poss = this._poss[target];\n\t\t\ttarget_poss.ioff[inlet] = null;\n\t\t\tthis._poss[target] = target_poss;\n\t\t});\n\n\t\t// then we calculate their positions (for connect line)\n\t\t// NOTE: the bbox has to be already filled!\n\t\tthis._poss.forEach((poss)=>{\n\t\t\tlet l = poss.ioff.length;\n\t\t\tlet w = poss.bbox.width / l;\n\t\t\tposs.ioff.forEach((_, i)=>{\n\t\t\t\tlet p = 0;\n\t\t\t\tif (l > 1 && i == l-1) {\n\t\t\t\t\tp = poss.bbox.width;\n\t\t\t\t} else if (i > 0) {\n\t\t\t\t\tp = (w * i) + (w / 2);\n\t\t\t\t}\n\t\t\t\tposs.ioff[i] = p;\n\t\t\t});\n\t\t\tl = poss.ooff.length;\n\t\t\tw = poss.bbox.width / l;\n\t\t\tposs.ooff.forEach((_, i)=>{\n\t\t\t\tlet p = 0;\n\t\t\t\tif (l > 1 && i == l-1) {\n\t\t\t\t\tp = poss.bbox.width;\n\t\t\t\t} else if (i > 0) {\n\t\t\t\t\tp = (w * i) + (w / 2);\n\t\t\t\t}\n\t\t\t\tposs.ooff[i] = p;\n\t\t\t});\n\t\t});\n\t}", "function allocateNePorts() {\n\t\tvar topPortList = new List();\n\t\tvar leftPortList = new List();\n\t\tvar rightPortList = new List();\n\t\tvar bottomPortList = new List();\n\t\tfor (var i = 0; i < this.ports.getLength(); i++) {\n\t\t\tvar port = this.ports.get(i);\n\t\t\tport.calculateCoords();\n\t\t\tif (port.side == TOP) {\n\t\t\t\ttopPortList.add(port, false);\n\t\t\t} else if (port.side == LEFT) {\n\t\t\t\tleftPortList.add(port, false);\n\t\t\t} else if (port.side == RIGHT) {\n\t\t\t\trightPortList.add(port, false);\n\t\t\t} else if (port.side == BOTTOM) {\n\t\t\t\tbottomPortList.add(port, false);\n\t\t\t}\n\t\t}\n\t\tfor (var i = 0; i < topPortList.getLength(); i++) {\n\t\t\ttopPortList.get(i).allocate(topPortList.getLength(), i+1);\n\t\t}\n\t\tfor (var i = 0; i < leftPortList.getLength(); i++) {\n\t\t\tleftPortList.get(i).allocate(leftPortList.getLength(), i+1);\n\t\t}\n\t\tfor (var i = 0; i < rightPortList.getLength(); i++) {\n\t\t\trightPortList.get(i).allocate(rightPortList.getLength(), i+1);\n\t\t}\n\t\tfor (var i = 0; i < bottomPortList.getLength(); i++) {\n\t\t\tbottomPortList.get(i).allocate(bottomPortList.getLength(), i+1);\n\t\t}\n\t}", "setDestination(x, y){ \n this.destination = getPoint(x,y);\n }", "connect(destination) {\n [\n this.lowpassNode,\n this.highpassNode,\n this.volTrackingNode,\n this.vmNode,\n this.gainNode,\n this.whiteNoise,\n this.pulseNode,\n this.oscNode\n ].reduce((prev, cur) => (cur ?\n (cur.connect(prev), cur) :\n prev), destination);\n }", "function OverlayConnectionPosition() {}", "function Connection(port1, port2) {\n\t\tif (port1.ne.id > port2.ne.id) {\n\t\t\tthis.originPort = port2;\n\t\t\tthis.destinationPort = port1;\n\t\t} else {\n\t\t\tthis.originPort = port1;\n\t\t\tthis.destinationPort = port2;\n\t\t}\n\t\tthis.originPort.setConnection(this);\n\t\tthis.destinationPort.setConnection(this);\n\t\tthis.originX = null;\n\t\tthis.originY = null;\n\t\tthis.destinationX = null;\n\t\tthis.destinationY = null;\n\t\tthis.color = \"#003366\";\n\t\tthis.weight = 1;\n\t\tthis.points = null;\n\t\tthis.middlePoint = null;\n\t\tthis.onClickAction = null;\n\t\tthis.popupListItems = new List();\n\t\tthis.id = CONNECTION + connectionsCounter++;\n\t\tthis.allocateOrigin = allocateOrigin;\n\t\tthis.allocateDestination = allocateDestination;\n\t\tthis.allocate = allocateConnection;\n\t\tthis.setMiddlePoint = setConnectionMiddlePoint;\n\t\tthis.write = writeConnection;\n\t\tthis.setColor = setConnectionColor;\n\t\tthis.setWeight = setConnectionWeight;\n\t\tthis.setClickAction = setConnectionClickAction;\n\t\tthis.addPopupListItem = addConnectionPopupListItem;\n\t\tthis.showPopupMenuAt = showConnectionPopupMenu;\n\t\tthis.updatePopupMenu = updateConnectionPopupMenu;\n\t\tthis.executeAction = executeActionOnRightClickedConnection;\n\t\tthis.remove = removeConnection;\n\t\tthis.addPopupListItem(null, \"Angle to the left\", LEFT_CORNER);\n\t\tthis.addPopupListItem(null, \"Angle to the right\", RIGHT_CORNER);\n\t}", "function ConnectedPosition() {}", "setDestinationCoordinates(coords)\n {\n this._destinationCoordinates = coords;\n }", "function OverlayConnectionPosition() { }", "function calculateCoords(node_origin, node_destination) {\n // calculate center of rectangles\n var origin_x = parseInt(node_origin.attr(\"x\")) + (node_origin.attr(\"width\")/2),\n origin_y = parseInt(node_origin.attr(\"y\")) + (node_origin.attr(\"height\")/2),\n destination_x = parseInt(node_destination.attr(\"x\")) + (node_destination.attr(\"width\")/2),\n destination_y = parseInt(node_destination.attr(\"y\")) + (node_destination.attr(\"height\")/2);\n\n var multiplier = 1;\n if (origin_x == destination_x) {\n\t// if destination is higher than origin,\n\t// destination plus height\n\t// origin minus height\n\t// else switched\n\tmultiplier = destination_y > origin_y ? 1 : -1;\n\n\treturn {\n\t 'origin_x': origin_x,\n\t 'origin_y': origin_y + (multiplier) * (parseInt(node_origin.attr(\"height\")/2) ),\n\t 'destination_x': destination_x,\n\t 'destination_y': destination_y + (multiplier * -1) * (parseInt(node_destination.attr(\"height\")/2))\n\t};\n }\n else if (origin_y == destination_y) {\n\t multiplier = destination_x > origin_x ? 1 : -1;\n\n\treturn {\n\t 'origin_x': origin_x + (multiplier) * (parseInt(node_origin.attr(\"width\")/2) ),\n\t 'origin_y': origin_y,\n\t 'destination_x': destination_x + (multiplier * -1) * (parseInt(node_destination.attr(\"width\")/2)),\n\t 'destination_y': destination_y\n\t};\n }\n else {\n\t multiplier = destination_x > origin_x ? 1 : -1;\n\t var multiplier_y = destination_y > origin_y ? 1 : -1;\n\n\t var a = Math.abs(destination_x - origin_x);\n\t var b = Math.abs(destination_y - origin_y);\n\n\t var b_1 = parseInt(node_origin.attr(\"height\")) / 2;\n\t var a_1 = b_1 / (b / a);\n\n\t var b_2 = parseInt(node_destination.attr(\"height\")) / 2;\n\t var a_2 = b_2 / (b / a)\n\n\t return {\n\t 'origin_x': a_1 * (multiplier) + origin_x,\n\t 'origin_y': b_1 * (multiplier_y) + origin_y,\n\t 'destination_x': a_2 * (multiplier * -1) + destination_x,\n\t 'destination_y': b_2 * (multiplier_y * -1) + destination_y\n\t };\n }\n}", "function ConnectedPosition() { }", "getConnectionPoints()\n {\n let startBounds = this.start.getBounds()\n let endBounds = this.end.getBounds()\n let startCenter = new Point()\n\t startCenter.setPoint(startBounds.getCenterX(), startBounds.getCenterY())\n let endCenter = new Point()\n\t endCenter.setPoint(endBounds.getCenterX(), endBounds.getCenterY())\n let l = new Line()\n\t l.setPoints(this.start.getConnectionPoint(endCenter), this.end.getConnectionPoint(startCenter))\n\t return l\n }", "function generateConnections() {\n\n var count = worldCities.length;\n var airports = [];\n var flights = [];\n var minDistance = 200;\n var maxDistance = 7000;\n var maxConnections = 300;\n var total = 0;\n \n for (var i = 0; i < count; i++) {\n var connections = [];\n\n var origin = worldCities[i];\n \n for (var ii = 0; ii < count; ii++)\n {\n var dest = worldCities[ii];\n \n if (origin.City != dest.City &&\n origin.Population > dest.Population &&\n origin.Country == \"US\" &&\n dest.Country == \"US\") {\n\n var hasConnection = false;\n var distance = calcGeoDistance(origin, dest);\n if (distance > minDistance &&\n distance < maxDistance) {\n\n if (origin.Population > 3000000 &&\n dest.Population > 500000 && distance < maxDistance) {\n hasConnection = true;\n }\n // optional code to add more connections\n //if (origin.Population > 1000000 &&\n // dest.Population > 250000 && distance < maxDistance * 0.75) {\n // hasConnection = true;\n //}\n //if (origin.Population > 500000 &&\n // dest.Population > 100000 && distance < maxDistance * 0.5) {\n // hasConnection = true;\n //}\n }\n if (hasConnection) {\n var path = [];\n path = calcGeoPath(origin, dest);\n connections.push(path);\n airports.push(dest);\n total++;\n }\n }\n }\n if (connections.length > 0) {\n \n flights.push({ city: origin, points: connections });\n airports.push(origin);\n }\n if (total > maxConnections) break;\n }\n worldConnections = flights;\n worldAirports = airports;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the closest element to 'e' that has class "classname"
function closest( e, classname ) { if( classie.has( e, classname ) ) { return e; } return e.parentNode && closest( e.parentNode, classname ); }
[ "function closest( e, classname ) {\n if( classie.has( e, classname ) ) {\n return e;\n }\n return e.parentNode && closest( e.parentNode, classname );\n }", "function closest( e, classname ) {\n\t\tif( classie.has( e, classname ) ) {\n\t\t\treturn e;\n\t\t}\n\t\treturn e.parentNode && closest( e.parentNode, classname );\n\t}", "function closest( e, classname ) {\n\t\tif( $(e).hasClass(classname) ) {\n\t\t\treturn e;\n\t\t}\n\t\treturn e.parentNode && closest( e.parentNode, classname );\n\t}", "function closest(e, classname) {\n\tif ($(e).hasClass(classname)) {\n\t\treturn e;\n\t}\n\treturn e.parentNode && closest(e.parentNode, classname);\n}", "function closest(e, classname) {\n if ($(e).hasClass(classname)) {\n return e;\n }\n return e.parentNode && closest(e.parentNode, classname);\n }", "static getClosest(el, klass) {\n if (el == null)\n return null;\n let curEl = el;\n while (curEl != null) {\n if (Dom.hasClass(curEl, klass))\n return curEl;\n curEl = curEl.parentElement;\n }\n return null;\n }", "function closestByClass(el, classToFind) {\n while (!el.classList.contains(classToFind)) {\n el = el.parentNode;\n if (!el) {\n return null;\n }\n }\n return el;\n }", "function closest(el, selector) {\n while (el) {\n if (selectorMatches(el, selector)) {\n break;\n }\n el = el.parentElement;\n }\n return el;\n}", "function closest(el, selector){\n\tvar tmpEl = el;\n\t\n\t// use \"!=\" for null and undefined\n\twhile (tmpEl != null && tmpEl !== document){\n\t\tif (matchesFn.call(tmpEl,selector)){\n\t\t\treturn tmpEl;\n\t\t}\n\t\ttmpEl = tmpEl.parentElement;\t\t\n\t}\n\treturn null;\n}", "function closest ( element, selector ) {\n\n var parent = null;\n\n while ( element !== null ) {\n\n parent = element.parentElement;\n\n if ( parent !== null && elementMatches( parent, selector ) ) {\n\n return parent;\n\n }\n\n element = parent;\n\n }\n\n return null;\n\n }", "closest(el, selector) {\n let parent = el.parentElement;\n while(parent) {\n if (this.matches(parent, selector)) {\n break;\n }\n parent = parent.parentElement;\n }\n\n return parent;\n }", "function get_parent_owner_by_class(oEle, strClass)\r\n{\r\n\tif (oEle.className==strClass) return oEle;\r\n\r\n\tif (oEle.parentNode)\r\n\t{\r\n\t\treturn get_parent_owner_by_class(oEle.parentNode, strClass);\r\n\t}\r\n\treturn null;\r\n}", "function findRelated(e,value,name,relative)\n{\n\tname = name || \"tagName\";\n\trelative = relative || \"parentNode\";\n\tif(name == \"className\") {\n\t\twhile(e && !jQuery(e).hasClass(value)) {\n\t\t\te = e[relative];\n\t\t}\n\t} else {\n\t\twhile(e && e[name] != value) {\n\t\t\te = e[relative];\n\t\t}\n\t}\n\treturn e;\n}", "function clickInsideElement( e, className ) {\r\n var el = e.srcElement || e.target;\r\n \r\n if ( el.classList.contains(className) ) {\r\n return el;\r\n } else {\r\n while ( el = el.parentNode ) {\r\n if ( el.classList && el.classList.contains(className) ) {\r\n return el;\r\n }\r\n }\r\n }\r\n \r\n return false;\r\n}", "function findRelated(e, value, name, relative) {\n name = name || \"tagName\";\n relative = relative || \"parentNode\";\n if (name == \"className\") {\n while (e && !jQuery(e).hasClass(value)) {\n e = e[relative];\n }\n } else {\n while (e && e[name] != value) {\n e = e[relative];\n }\n }\n return e;\n}", "function findParentClass(elem, parentClassName) {\n while (elem && elem.className != parentClassName) { elem = elem.parentNode; }\n return elem;\n}", "closest(selector) {\n let isFind = false;\n let $parentEl = this.getFirstEl().parentElement;\n while (!isFind) {\n if ($parentEl === null || $parentEl === void 0 ? void 0 : $parentEl.matches(selector)) {\n isFind = true;\n this.$elItems = [$parentEl];\n return this;\n }\n else {\n $parentEl = $parentEl.parentElement;\n }\n if ($parentEl.matches('html')) {\n isFind = true;\n return undefined;\n }\n }\n //return $parentEl;\n }", "getMainElementFormTarget(e) {\n let elem;\n if(e.target.classList.contains(\"mydiv\")) {\n elem = e.target;\n } else {\n elem = e.target.closest(\"div.mydiv\");\n } \n return elem;\n }", "function clickInsideElement(e, className) {\n let el = e.target\n\n if (el.classList.contains(className)) {\n return el\n } else {\n while ((el = el.parentNode)) {\n if (el.classList && el.classList.contains(className)) {\n return el\n }\n }\n }\n\n return false\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map through all todos, and replace the text of the todo with the specified id
editTodo(id, updatedText) { this.todos = this.todos.map(todo => todo.id === id ? { id: todo.id, text: updatedText, complete: todo.complete } : todo ); this._changeList(this._currentTab); }
[ "editTodo(id, updatedText) {\n this.todos = this.todos.map(todo =>\n todo.id === id ? { id: todo.id, text: updatedText, complete: todo.complete } : todo\n )\n }", "editTodo(id, updatedText) {\n this.todos = this.todos.map(todo =>\n todo.id === id\n ? { id: todo.id, text: updatedText, complete: todo.complete }\n : todo\n );\n }", "editTodo(id, updatedText) {\n this.todos = this.todos.map((todo) =>\n (todo.id === id ? { id: todo.id, text: updatedText, complete: todo.complete } : todo));\n this.onTodoListChanged(this.todos);\n }", "editTodo(id, updatedText) {\n this.todos = this.todos.map(todo => \n todo.id === id ? { id: todo.id, text: updatedText, complete: todo.complete } : todo\n );\n\n this.onTodoListChanged(this.todos);\n }", "editTodo(id, updatedText) {\n this.todos = this.todos.map(todo =>\n todo.id === id\n ? { id: todo.id, text: updatedText, complete: todo.complete }\n : todo\n );\n\n this._commit(this.todos);\n }", "editTodo(id, updatedText) {\n this.todos = this.todos.map(todo =>\n todo.id === id ? { id: todo.id, text: updatedText, complete: todo.complete } : todo\n )\n this._commit(this.todos)\n }", "function updateTodoText(todosList, id, newText) {\n for (const todo of todosList) {\n if (todo.id === id) {\n todo.text = newText;\n return true;\n }\n if (todo.children.length > 0) {\n if (updateTodoText(todo.children, id, newText)) {\n return true;\n }\n }\n }\n return false;\n}", "editTodo(id, newTitle) {\n console.log('edit todo');\n var todoToEditIndex = todoList.findIndex(obj => obj.id == id);\n todoList[todoToEditIndex].title = newTitle;\n }", "toggleTagOnSelectedTodos(tagId) {\n this.selectedTodos.map(todo => {\n this.toggleTagOnTodo(tagId, todo);\n });\n }", "update(newText, id){\n var notes = this.state.notes.map(\n note => (note.id !== id) ?\n note :\n {\n ...note,\n note: newText\n }\n )\n this.setState({notes})\n }", "function updateTodoList() {\n listOfHTML = thingsToDo.map(turnTodoItemIntoHTML)\n document.querySelector(`#todo-list-items`).innerHTML = listOfHTML\n}", "update(newText, id){\n var notes=this.state.notes.map(\n note =>(note.id !== id) ? note\n :\n {\n ...note,\n note: newText\n }\n )\n this.setState({notes})\n }", "function toggleTodo (todoID) {\n const foundTD = todos.find(todoEl => todoEl.id === todoID)\n\n if (foundTD) {\n foundTD.completed = !foundTD.completed\n saveTodos()\n }\n}", "EDIT_TODO (state, todo) {\r\n let todos = state.todos\r\n let index = _.findIndex(todos, {id:todo.id});\r\n todos[index] = todo\r\n // todos.splice(index, 1)\r\n state.todos = todos\r\n // state.newTodo = todo.title\r\n }", "async editTodo(id, todo){\n \n // update the todo in the database\n const result = await Todo.replaceOne({\n _id: id\n }, {\n title: todo.title,\n date: todo.date,\n type: todo.type,\n description: todo.description\n });\n \n // return result\n return result;\n\n }", "editTodo(id, newTitle) {\n const todo = this.findTodo(id);\n if(todo) {\n todo.title = newTitle;\n return todo;\n }\n }", "toggleTagOnTodo(tagId, todo) {\n const index = todo.tags.indexOf(tagId);\n if (index !== -1) {\n todo.tags.splice(index, 1);\n }\n else {\n todo.tags.push(tagId);\n }\n this.updateTodo(todo);\n }", "function editTodo(e) {\n // with the value of its index(its position on the todosArray\n const position = parseInt(e.target.id, 10);\n // Todos has an input and label elements.\n // label id are created by concatinating `position`\n // and string `label`.\n const labelId = `.label${position}`;\n // eslint-disable-next-line\n const oldElement = document.querySelector(labelId);\n const parentNode = oldElement.parentNode;\n // Create an input element with the attributes below\n // eslint-disable-next-line\n const inputElement = document.createElement('textarea');\n inputElement.setAttribute('class', 'change-todo materialize-textarea');\n inputElement.setAttribute('id', `textarea${position}`);\n // Replace the child node label with input so\n // that we can edit the todoContent.\n const todoContent = todosArray[position];\n inputElement.value = todoContent.todoContent;\n parentNode.replaceChild(inputElement, oldElement);\n // eslint-disable-next-line\n const changeTodoInput = document.querySelector('.change-todo');\n changeTodoInput.addEventListener('keypress', (event) => {\n const key = event.which || event.charCode;\n const index = position;\n const newTodoContent = event.target.value;\n const todoObject = { todoContent: newTodoContent, completed: false };\n if (key === 13 && event.target.value.length > 2) {\n todosArray.splice(index, 1, todoObject);\n renderTodos(todos, todosArray);\n }\n });\n}", "function editLocalStorage(editTodoId,todo){\n \n let items = getLocalStorage();\n\n items.map((item) => {\n \n if(item.id === editTodoId)\n {\n item.value = todo;\n }\n });\n\n localStorage.setItem('list',JSON.stringify(items));\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isEmail(field) Returns true if value contains a correct email address
function isEmail(fld) { if(!fld.value.length || fld.disabled) return true; // blank fields are the domain of requireValue var emailfmt = /(^['_A-Za-z0-9-]+(\.['_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.(([A-Za-z]{2,3})|(aero|coop|info|museum|name))$)|^$/; if(!emailfmt.test(fld.value)) return false; return true; }
[ "function isEmail(field){\r\n\tre = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/; // regular expression that checks for valid email adress notation\r\n\tif(re.test(field.value)) {\r\n\t\treturn true;\r\n\t} else {\r\n\t\treturn false;\r\n\t}\r\n}", "function isEmail(value) {\n if (notEmpty(value)) {\n if (typeof value !== 'string')\n value = value.toString();\n return regexpr_1.email.test(value);\n }\n return false;\n}", "function arq_isEmail(fieldId, fieldAlias)\r\n{\r\n var fieldObject = document.getElementById(fieldId);\r\n var msg = \"El campo \" + fieldAlias + \" no es un Email valido\";\r\n\r\n if (fieldObject && fieldObject.value && fieldObject.value.length > 0)\r\n {\r\n if (/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/.test(fieldObject.value))\r\n {\r\n _arq_insertValidationMsg(fieldId, msg);\r\n }\r\n }\r\n}", "function isValidEmail(uField) {\n var lResult = false;\n var lcValue = getFieldValue(uField);\n var lnIndex = 1;\n var lnDotFound = 0;\n var lnAtFound = 0;\n var lnFirstAtPos = 0;\n var lnLastDotPos = 0;\n var lnIllegalCharsFound = 0;\n while(lnIndex<=lcValue.length) {\n if(\" !#$%^&*()+={}|\\][:;'\\\"?/><,~`\".indexOf(lcValue.charAt(lnIndex)) > 0) {\n lnIllegalCharsFound = lnIllegalCharsFound + 1;\n }\n if(lcValue.charAt(lnIndex)==\"@\") {\n lnAtFound = lnAtFound + 1;\n if(lnFirstAtPos == 0) {\n lnFirstAtPos = lnIndex;\n }\n }\n if(lcValue.charAt(lnIndex)==\".\") {\n lnDotFound = lnDotFound + 1;\n lnLastDotPos = lnIndex;\n }\n lnIndex = lnIndex + 1;\n }\n if((lnAtFound == 1) && (lnDotFound>0) && (lnIllegalCharsFound==0)) {\n if (lnFirstAtPos < lnLastDotPos) {\n lResult = true;\n } else {\n lResult = false;\n }\n }\n else {\n lResult = false;\n }\n return lResult;\n}", "validateUserEmailField(pUserEmail) {\n let validUserEmailField = true;\n var re = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n if (!pUserEmail || pUserEmail === '' || !re.test(pUserEmail)) {\n validUserEmailField = false;\n }\n return validUserEmailField;\n }", "function isEmail(theObj)\n\t\t\t{ \n\t\t\t\tif(theObj == null)\n\t\t\t\t\treturn false;\n\t\t\t\t\n\t\t\t\tvar theValue = theObj.value;\n\t\t\t\tvar vEmail = theValue;\n\t\t\t\tvar pattern = /^([a-zA-Z0-9_-])+(\\.[a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\\.[a-zA-Z0-9_-])+/;\n  \t\t\treturn pattern.test(vEmail);   \n  \t\t\t}", "function validateEmailField(){\n const emailField = document.querySelector('#mail');\n const email = emailField.value;\n const emailLabel = document.querySelector(\"label[for='mail']\");\n\n\n return validateInputWithLabelAndField(emailField, email, emailLabel,!email.match(/[a-z0-9._-]+@[a-z]+.com/)\n , 'Email:', 'Must be a valid email address');\n }", "function IsThisAnEmail(email)\n{ \n return /^\\S+@\\S+\\.\\S+$/.test(email)\n}", "function validateEmail(element) {\n\t\tvar value = element.val();\n\t\tvar atpos = value.indexOf(\"@\");\n\t\tvar dotpos = value.lastIndexOf(\".\");\n\t\tif (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= value.length) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}", "function FS_CheckEmail(formName, formField, formLabel) \r\n{\r\n var s = formName.elements[formField.name].value;\r\n \r\n // test using regular expression\r\n if (!(/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/.test(s)))\r\n {\r\n\t\talert(FS_FmtMsg(FS_MsgNotEmailFormat, formLabel));\r\n\t\tformField.focus();\r\n\t\treturn false;\r\n }\t\r\n\r\n return true;\r\n}", "function isEmail(arg) {\n const re = /\\S+@\\S+\\.\\S+/;\n return re.test(arg);\n}", "function ValidaEmail(field) {\r\n\t\tusuario = field.value.substring(0, field.value.indexOf(\"@\"));\r\n\t\tdominio = field.value.substring(field.value.indexOf(\"@\")+ 1, field.value.length);\r\n\t\t \r\n\t\tif (!((usuario.length >=1) &&\r\n\t\t\t(dominio.length >=3) && \r\n\t\t\t(usuario.search(\"@\")==-1) && \r\n\t\t\t(dominio.search(\"@\")==-1) &&\r\n\t\t\t(usuario.search(\" \")==-1) && \r\n\t\t\t(dominio.search(\" \")==-1) &&\r\n\t\t\t(dominio.search(\".\")!=-1) && \r\n\t\t\t(dominio.indexOf(\".\") >=1)&& \r\n\t\t\t(dominio.lastIndexOf(\".\") < dominio.length - 1))) {\r\n\r\n\t\t\talert(\"O e-mail informado possui formato invalido.\\nFavor informar novamente!\");\r\n\t\t\tfield.value=\"\";\r\n\t\t}\r\n\t}", "validateEmail() {\n\n var emailId = this.state.userdata.email;\n if (/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/.test(emailId))\n {\n return (true)\n }\n return (false)\n }", "function isEmail(obj){\r\n\treturn isString(obj) && obj.match(/\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b/ig);\r\n}", "function emailIsValid(email) {\r\n return /\\S+@\\S+\\.\\S+/.test(email);\r\n}", "emailIsValid(email) {\n return /\\S+@\\S+\\.\\S+/.test(email);\n }", "function isEmail(obj) {\n if (isString(obj)) {\n return obj.match(/\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b/ig);\n }\n else {\n return false;\n }\n}", "function emailValidate() {\n const regex = /\\S+@\\S+\\.\\S+/;\n const test = regex.test(email.value);\n showOrHideHint(email, test, \"Email address must be formatted correctly\");\n return test;\n}", "function isEmail(obj) {\n\tif (isString(obj)) {\n\t\treturn obj.match(/\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b/ig);\n\t}\n\telse {\n\t\treturn false;\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
end of function processParcel() / validNumberAboveZero() Purpose: verify if the number is valid, is a number, and is greater then zero Parameters: number in input Returns: true if number is valid, false if invalid
function validNumberAboveZero(inputNumber){ inputNumber = inputNumber.replace(/\s+/,""); inputNumber = inputNumber.replace(/\,+/,"."); if(isNaN(parseFloat(+inputNumber))){ return false; } if(parseFloat(+inputNumber)<=0){ return false; } return true; }
[ "function isValidParcelNumber(numberStr) {\n\n // If provided numberStr is not representing an integer return false ..\n if (!Number.isInteger(+numberStr)) return false;\n\n // Returns true if numberStr is representing value greater or equal to 0. Otherwise return false.\n return numberStr >= 0;\n}", "function validNumber(value) {\n const intNumber = Number.isInteger(parseFloat(value));\n const sign = Math.sign(value);\n\n if (intNumber && (sign === 1)) {\n return true;\n } else {\n return 'Please use whole non-zero numbers only.';\n }\n}", "function is_valid_number()\r\n{\r\n\treturn isValidNumber.apply(this, arguments)\r\n}", "function positiveNumberValidator(value) {\n\treturn _.isNumber(value) && value >= 0\n}", "function validNumber(n) {return ( n != 0.0 && !isNaN(parseFloat(n))); }", "function lessThanOrEqualToZero(num) {\nvar num;\n if(num > 0){\n return false;\n }\n return true;\n}", "function lessThanOrEqualToZero(num) {\n if (num <= 0) {\n return true;\n } else {\n return false;\n }\n} //end function", "isValidNumber(value) {\n if(isNaN(parseInt(value))) return false;\n\n if(value === 0 || value > 9) return false;\n\n return true;\n }", "laneNumberValidator(v) {\n if (v === \"\") { return true; }\n let valid = true;\n if (! Number.isInteger(v)) {\n valid = /^[1-8]$/.test(trimmed(v));\n }\n return valid;\n }", "isZero($number) {\n return $number === 0;\n }", "function validInput(input) {\n return isInteger(input) && input > 0\n}", "function validateInput(value) {\n\tvar integer = Number.isInteger(parseFloat(value));\n\tvar sign = Math.sign(value);\n\n\tif (integer && (sign === 1)) {\n\t\treturn true;\n\t} else {\n\t\tconsole.log('Please enter a whole non-zero number.');\n\t\tpromptPurchase()\n\n\t}\n}", "function lessThanOrEqualToZero(num) {\n if(num <= 0){\n return true;\n } else{\n return false;\n }\n}", "isNumberValid(number) {\n return typeof number !== 'undefined' && null !== number && !isNaN(number);\n }", "function flatNumIsValid() {\n let flatRegEx = /[0-9]{1,3}/;\n return flatNum.value != \"\" && flatRegEx.test(flatNum.value);\n }", "function validaNumero(valorIngresado){\r\n if(valorIngresado == \"\" || valorIngresado == null){\r\n console.log(\"El valor ingresado es nulo\");\r\n return false;\r\n }else{\r\n if(isNaN(valorIngresado)){\r\n console.log(\"El valor ingresado no es un numero\");\r\n return false;\r\n }else{\r\n if(parseInt(valorIngresado) < 0){\r\n console.log(\"Numero negativo\");\r\n alert(\"El valor ingresado no puede ser menor a 0\");\r\n return false;\r\n }else{\r\n return true; \r\n } \r\n } \r\n }\r\n}", "function lessThanOrEqualToZero(num) {\n if(num <= 0){\n return true\n } else{\n return false\n }\n}", "function isValidNumber (value) {\n\treturn !Number.isNaN(utils.number(value));\n}", "function isNumberInRange(number){\n\n if(number>0 && number<10){\n return true;\n }else{\n return false;\n \n }\n\n\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find states with only one action, a reduction
function findDefaults(states) { var defaults = {}; states.forEach(function (state, k) { var i = 0; for (var act in state) { if ({}.hasOwnProperty.call(state, act)) i++; } if (i === 1 && state[act][0] === 2) { // only one action in state and it's a reduction defaults[k] = state[act]; } }); return defaults; } // resolves shift-reduce and reduce-reduce conflicts
[ "function reduceSingle(reducer, state, action) {\r\n return reducer(state, action);\r\n }", "stateFor(action) {\n let stores = Object.keys(this.stores)\n .filter(key => Store.taskFor(this.stores[key], action))\n\n return stores.reduce((memo, key) => {\n memo[key] = this.get(key)\n return memo\n }, {})\n }", "function do_reductions( s )\n{\n\tvar n, i, j, ex, act, output_warning, item_set;\n\tvar reds = [];\n\tvar max = 0, count;\n\n\tfor( n = 0; n < 2; n++ )\n\t{\n\t\tif( !n )\n\t\t\titem_set = states[ s ].kernel;\n\t\telse\n\t\t\titem_set = states[ s ].epsilon;\n\n\t\t// Do the reductions\n\t\tfor( i = 0; i < item_set.length; i++ )\n\t\t{\n\t\t\tif( item_set[i].dot_offset == productions[item_set[i].prod].rhs.length )\n\t\t\t{\n\t\t\t\tfor( j = 0; j < item_set[i].lookahead.length; j++ )\n\t\t\t\t{\n\t\t\t\t\toutput_warning = true;\n\n\t\t\t\t\tex = get_table_entry( states[s].actionrow,\n\t\t\t\t\t\t\titem_set[i].lookahead[j] );\n\n\t\t\t\t\tact = ex;\n\t\t\t\t\tif( ex == void(0) )\n\t\t\t\t\t{\n\t\t\t\t\t\tact = -1 * item_set[i].prod;\n\n\t\t\t\t\t\tstates[s].actionrow = add_table_entry( states[s].actionrow,\n\t\t\t\t\t\t\titem_set[i].lookahead[j], act );\n\n\t\t\t\t\t\treduces++;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tvar warning\t= \"\";\n\t\t\t\t\t\tif( ex > 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//Shift-reduce conflict\n\n\t\t\t\t\t\t\t//Is there any level specified?\n\t\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].level > 0\n\t\t\t\t\t\t\t\t|| productions[ item_set[i].prod ].level > 0 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//Is the level the same?\n\t\t\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].level ==\n\t\t\t\t\t\t\t\t\tproductions[ item_set[i].prod ].level )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//In case of left-associativity, reduce\n\t\t\t\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].assoc\n\t\t\t\t\t\t\t\t\t\t\t== ASSOC_LEFT )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//Reduce\n\t\t\t\t\t\t\t\t\t\tact = -1 * item_set[i].prod;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t//else, if nonassociativity is set,\n\t\t\t\t\t\t\t\t\t//remove table entry.\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].assoc\n\t\t\t\t\t\t\t\t\t\t\t== ASSOC_NOASSOC )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tremove_table_entry( states[s].actionrow,\n\t\t\t\t\t\t\t\t\t\t\t\titem_set[i].lookahead[j] );\n\n\t\t\t\t\t\t\t\t\t\t_warning(\n\t\t\t\t\t\t\t\t\t\t\t\"Removing nonassociative symbol '\" +\n\t\t\t\t\t\t\t\t\t\t\tsymbols[item_set[i].lookahead[j]].label +\n\t\t\t\t\t\t\t\t\t\t\t\t\"' in state \" + s );\n\n\t\t\t\t\t\t\t\t\t\toutput_warning = false;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//If symbol precedence is lower production's\n\t\t\t\t\t\t\t\t\t//precedence, reduce\n\t\t\t\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].level <\n\t\t\t\t\t\t\t\t\t\t\tproductions[ item_set[i].prod ].level )\n\t\t\t\t\t\t\t\t\t\t//Reduce\n\t\t\t\t\t\t\t\t\t\tact = -1 * item_set[i].prod;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\twarning = \"Shift\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//Reduce-reduce conflict\n\t\t\t\t\t\t\tact = ( ( act * -1 < item_set[i].prod ) ?\n\t\t\t\t\t\t\t\t\t\tact : -1 * item_set[i].prod );\n\n\t\t\t\t\t\t\twarning = \"Reduce\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\twarning += \"-reduce conflict on symbol '\" +\n\t\t\t\t\t\t\tsymbols[item_set[i].lookahead[j]].label +\n\t\t\t\t\t\t\t\t\"' in state \" + s;\n\t\t\t\t\t\twarning += \"\\n Conflict resolved by \" +\n\t\t\t\t\t\t\t( ( act <= 0 ) ? \"reducing with production\" :\n\t\t\t\t\t\t\t\t\"shifting to state\" ) + \" \" +\n\t\t\t\t\t\t\t( ( act <= 0 ) ? act * -1 : act );\n\n\t\t\t\t\t\tif( output_warning )\n\t\t\t\t\t\t\t_warning( warning );\n\n\t\t\t\t\t\tif( act != ex )\n\t\t\t\t\t\t\tupdate_table_entry( states[s].actionrow,\n\t\t\t\t\t\t\t\titem_set[i].lookahead[j], act );\n\t\t\t\t\t}\n\n\t\t\t\t\t//Remember this reduction, if there is any\n\t\t\t\t\tif( act <= 0 )\n\t\t\t\t\t\treds.push( act * -1 );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t\tJMM 16.04.2009\n\t\tFind most common reduction\n\t*/\n\tstates[ s ].def_act = -1; //Define no default action\n\n\t//Are there any reductions? Then select the best of them!\n\tfor( i = 0; i < reds.length; i++ )\n\t{\n\t\tfor( j = 0, count = 0; j < reds.length; j++ )\n\t\t\tif( reds[j] == reds[i] )\n\t\t\t\tcount++;\n\t\tif( max < count )\n\t\t{\n\t\t\tmax = count;\n\t\t\tstates[ s ].def_act = reds[ i ];\n\t\t}\n\t}\n\n\t//Remove all default reduce action reductions, if they exist.\n\tif( states[s].def_act >= 0 )\n\t{\n\t\tdo\n\t\t{\n\t\t\tcount = states[s].actionrow.length;\n\n\t\t\tfor( i = 0; i < states[s].actionrow.length; i++ )\n\t\t\t\tif( states[s].actionrow[i][1] == states[s].def_act * -1 )\n\t\t\t\t\tstates[s].actionrow.splice( i, 1 );\n\t\t}\n\t\twhile( count != states[s].actionrow.length );\n\t}\n}", "nextStates(state) {\n let result = [];\n for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) {\n if (this.data[i] == 65535 /* End */) {\n if (this.data[i + 1] == 1 /* Next */)\n i = pair(this.data, i + 2);\n else\n break;\n }\n if ((this.data[i + 2] & (65536 /* ReduceFlag */ >> 16)) == 0) {\n let value = this.data[i + 1];\n if (!result.some((v, i) => (i & 1) && v == value))\n result.push(this.data[i], value);\n }\n }\n return result;\n }", "nextStates(state) {\n let result = [];\n for (let i = this.stateSlot(state, 1 /* ParseState.Actions */);; i += 3) {\n if (this.data[i] == 65535 /* Seq.End */) {\n if (this.data[i + 1] == 1 /* Seq.Next */)\n i = pair(this.data, i + 2);\n else\n break;\n }\n if ((this.data[i + 2] & (65536 /* Action.ReduceFlag */ >> 16)) == 0) {\n let value = this.data[i + 1];\n if (!result.some((v, i) => (i & 1) && v == value))\n result.push(this.data[i], value);\n }\n }\n return result;\n }", "function computeNextState(state, action) {\n return mapValues(stores,\n (store, key) => {\n const nextStoreState = store(state[key], action);\n invariant(\n nextStoreState != null,\n 'State returned by %s is null or undefined.',\n key\n );\n return nextStoreState;\n }\n );\n }", "getBestAction(state) {\n var actions = this.model.predict(state).arraySync()[0];\n var action = actions.indexOf(Math.max(...actions));\n return action;\n }", "function find_successors(state) {\n ++helper_expand_state_count; //Keep track of how many states are expanded (DO NOT REMOVE!)\n \n let successors=[];\n const actions = {\n 1: [-1, 0],\n 2: [1, 0],\n 3: [0, -1],\n 4: [0, 1]\n }\n\n const blankPosition = find_blank(state);\n\n for (var i = 1; i < 5; i++) {\n // clone state\n let newState = {\n grid : state.grid.map(x => x.slice(0)) \n };\n\n // Generate new blank position using available actions\n newBlankPosition = [\n blankPosition[0] + actions[i][0],\n blankPosition[1] + actions[i][1]\n ]\n\n // If new move is valid, generate new state and add it to successors\n if (is_valid_position(newBlankPosition)) {\n valAtNewPosition = newState.grid[newBlankPosition[0]][newBlankPosition[1]]\n newState.grid[newBlankPosition[0]][newBlankPosition[1]] = 0;\n newState.grid[blankPosition[0]][blankPosition[1]] = valAtNewPosition;\n \n successors.push({\n actionID : i,\n resultState : newState\n });\n }\n }\n \n\n return successors;\n}", "function findDefaults (states) {\n var defaults = {};\n states.forEach(function (state, k) {\n var i = 0;\n for (var act in state) {\n if ({}.hasOwnProperty.call(state, act)) i++;\n }\n\n if (i === 1 && state[act][0] === 2) {\n // only one action in state and it's a reduction\n defaults[k] = state[act];\n }\n });\n\n return defaults;\n}", "function find_successors(state) {\n ++helper_expand_state_count; //Keep track of how many states are expanded\n \n let successors=[];\n\n if(state.position>0) {\n successors.push({\n actionID : 1,\n resultState : {\n dirt : state.dirt.slice(0) /*clone*/,\n position : state.position-1\n }\n });\n }\n if(state.position<1) {\n successors.push({\n actionID : 2,\n resultState : {\n dirt : state.dirt.slice(0) /*clone*/,\n position : state.position+1\n }\n });\n }\n if(state.dirt[state.position]>0) {\n let newdirt=state.dirt.slice(0);\n --newdirt[state.position];\n successors.push({\n actionID : 3,\n resultState : {\n dirt : newdirt,\n position : state.position\n }\n });\n }\n \n return successors;\n}", "function breadth_first_search(initial_state) {\r\n let open = []; //See push()/pop() and unshift()/shift() to operate like stack or queue\r\n //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\r\n let closed = new Set(); //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\r\n\r\n let actions = [];\r\n let states = [];\r\n /*placing the intial state into open set*/\r\n open.push(initial_state);\r\n\r\n while(open.length >0){\r\n var state_var = open.shift();\r\n var aug_state;\r\n if(state_var==initial_state){\r\n //defining augmented states\r\n aug_state ={\r\n predecessor: null,\r\n state: state_var,\r\n action: null\r\n };\r\n }else{\r\n //set it to state_var\r\n aug_state = state_var;\r\n }\r\n if(!closed.has(state_to_uniqueid(aug_state.state))){\r\n if(!is_goal_state(aug_state.state)){\r\n let sucs = find_successors(aug_state.state);\r\n for(let ind=0;ind<sucs.length;ind++){\r\n let x = Object.assign({},aug_state);\r\n x.predecessor = aug_state;\r\n x.state = sucs[ind].resultState;\r\n x.action = sucs[ind].actionID;\r\n open.push(x);\r\n }\r\n closed.add(state_to_uniqueid(aug_state.state));\r\n }else{\r\n break;\r\n }\r\n }else{\r\n continue;\r\n }\r\n }\r\n if(is_goal_state(aug_state.state)){\r\n helper_eval_state_count--;\r\n states.unshift(aug_state.state);\r\n actions.unshift(aug_state.action);\r\n while(aug_state.predecessor != null){\r\n aug_state = aug_state.predecessor;\r\n states.unshift(aug_state.state);\r\n actions.unshift(aug_state.action);\r\n }\r\n states.shift();\r\n actions.shift();\r\n\r\n return{\r\n actions: actions,\r\n states: states\r\n };\r\n }else{\r\n return null;\r\n }\r\n /***Your code for breadth-first search here***/\r\n\r\n /*\r\n Hint: In order to generate the solution path, you will need to augment\r\n the states to store the predecessor/parent state they were generated from\r\n and the action that generates the child state from the predecessor state.\r\n \r\n\t For example, make a wrapper object that stores the state, predecessor and action.\r\n\t Javascript objects are easy to make:\r\n\t\tlet object={\r\n\t\t\tmember_name1 : value1,\r\n\t\t\tmember_name2 : value2\r\n\t\t};\r\n \r\n Hint: Because of the way Javascript Set objects handle Javascript objects, you\r\n will need to insert (and check for) a representative value instead of the state\r\n object itself. The state_to_uniqueid function has been provided to help you with\r\n this. For example\r\n let state=...;\r\n closed.add(state_to_uniqueid(state)); //Add state to closed set\r\n if(closed.has(state_to_uniqueid(state))) { ... } //Check if state is in closed set\r\n */\r\n \r\n //So you need to start coding here. Don't do it above the hints it will confuse you\r\n /***Your code to generate solution path here***/\r\n\r\n //define these its used throughout\r\n \r\n //OR\r\n\r\n //No solution found\r\n return null;\r\n}", "function reduceMany(reducer, state, actions) {\r\n for (var i = 0, n = actions.length; i < n; ++i) {\r\n state = reducer(state, actions[i]);\r\n }\r\n return state;\r\n }", "function update(state, action) {\n\t// // We're not using prune for now, so we might as well comment it out\n\t// let newState = action.prune ? prune(state, action.prune) : state;\n\t// return action.state ? merge(newState, action.state) : newState;\n\treturn merge(state, action.state);\n}", "function do_reductions( item_set, s )\n{\n\tvar i, j, ex, act, output_warning;\n\tfor( i = 0; i < item_set.length; i++ )\n\t{\n\t\tif( item_set[i].dot_offset == productions[item_set[i].prod].rhs.length )\n\t\t{\n\t\t\tfor( j = 0; j < item_set[i].lookahead.length; j++ )\n\t\t\t{\n\t\t\t\toutput_warning = true;\n\n\t\t\t\tex = get_table_entry( states[s].actionrow,\n\t\t\t\t\t\titem_set[i].lookahead[j] );\n\n\t\t\t\tact = ex;\n\t\t\t\tif( ex == void(0) )\n\t\t\t\t{\n\t\t\t\t\tstates[s].actionrow = add_table_entry( states[s].actionrow,\n\t\t\t\t\t\titem_set[i].lookahead[j], -1 * item_set[i].prod );\n\t\t\t\t\t\t\n\t\t\t\t\treduces++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvar warning\t= new String();\n\t\t\t\t\tif( ex > 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\t//Shift-reduce conflict\n\n\t\t\t\t\t\t//Is there any level specified?\n\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].level > 0\n\t\t\t\t\t\t\t|| productions[ item_set[i].prod ].level > 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//Is the level the same?\n\t\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].level ==\n\t\t\t\t\t\t\t\tproductions[ item_set[i].prod ].level )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//In case of left-associativity, reduce\n\t\t\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].assoc\n\t\t\t\t\t\t\t\t\t\t== ASSOC_LEFT )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//Reduce\n\t\t\t\t\t\t\t\t\tact = -1 * item_set[i].prod;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t//else, if nonassociativity is set,\n\t\t\t\t\t\t\t\t//remove table entry.\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].assoc\n\t\t\t\t\t\t\t\t\t\t== ASSOC_NOASSOC )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tremove_table_entry( states[s].actionrow,\n\t\t\t\t\t\t\t\t\t\t\titem_set[i].lookahead[j] );\n\n\t\t\t\t\t\t\t\t\t_warning(\n\t\t\t\t\t\t\t\t\t\t\"Removing nonassociative symbol '\"\n\t\t\t\t\t\t\t\t\t\t + symbols[item_set[i].lookahead[j]].label + \"' in state \" + s );\n\n\t\t\t\t\t\t\t\t\toutput_warning = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//If symbol precedence is lower production's\n\t\t\t\t\t\t\t\t//precedence, reduce\n\t\t\t\t\t\t\t\tif( symbols[item_set[i].lookahead[j]].level <\n\t\t\t\t\t\t\t\t\t\tproductions[ item_set[i].prod ].level )\n\t\t\t\t\t\t\t\t\t//Reduce\n\t\t\t\t\t\t\t\t\tact = -1 * item_set[i].prod;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\twarning = \"Shift\";\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t//Reduce-reduce conflict\n\t\t\t\t\t\tact = ( ( act * -1 < item_set[i].prod ) ?\n\t\t\t\t\t\t\t\t\tact : -1 * item_set[i].prod );\n\t\t\t\t\t\t\n\t\t\t\t\t\twarning = \"Reduce\";\n\t\t\t\t\t}\n\n\t\t\t\t\twarning += \"-reduce conflict on symbol '\" + symbols[item_set[i].lookahead[j]].label + \"' in state \" + s;\n\t\t\t\t\twarning += \"\\n Conflict resolved by \" +\n\t\t\t\t\t\t\t\t( ( act <= 0 ) ? \"reducing with production\" : \"shifting to state\" )\n\t\t\t\t\t\t\t\t\t+ \" \" + ( ( act <= 0 ) ? act * -1 : act );\n\n\t\t\t\t\tif( output_warning )\n\t\t\t\t\t\t_warning( warning );\n\n\t\t\t\t\tif( act != ex )\n\t\t\t\t\t\tupdate_table_entry( states[s].actionrow,\n\t\t\t\t\t\t\titem_set[i].lookahead[j], act );\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n}", "function getState(arr, filterVal){\n return (arr === filterVal)\n}", "successors(state) {\n var actions = this.actions(state),\n successors = actions.map(a => this.successor(a, _.clone(state)));\n return _.zip(actions, successors);\n }", "function reduce(currState, { type, payload }){\n return (type in actions) ? actions[type](currState, payload) : currState;\n }", "getAction() {\n if (this.exploration > Math.random()) {\n var action = Math.random() < 0.5 ? 0 : 1;\n } else {\n var state = this.getState();\n action = this.getBestAction(state);\n }\n\n return action;\n }", "function findPossibleActions(){\n let index = qTable.findIndex(element => element.state.x === currentState.x && element.state.y === currentState.y);\n let qValues = qTable[index];\n let possibleActions = [];\n for(let action in qValues){\n if(action === 'state') continue;\n if(qValues[action] === undefined) continue;\n possibleActions.push(action);\n }\n return possibleActions\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
options.socket: The Asyngular client socket to use to sync the model state. options.type: The resource type. options.id: The resource id. options.fields: An array of fields names required by this model.
function AGModel(options) { AsyncStreamEmitter.call(this); this.socket = options.socket; this.type = options.type; this.id = options.id; this.fields = options.fields; this.defaultFieldValues = options.defaultFieldValues; this.agFields = {}; this.value = { ...this.defaultFieldValues, id: this.id }; this.active = true; this.passiveMode = options.passiveMode || false; this.fields.forEach((field) => { let agField = new AGField({ socket: this.socket, resourceType: this.type, resourceId: this.id, name: field, passiveMode: this.passiveMode }); this.agFields[field] = agField; this.value[field] = null; (async () => { for await (let event of agField.listener('error')) { this.emit('error', event); } })(); (async () => { for await (let event of agField.listener('change')) { this.value[event.field] = event.newValue; this.emit('change', { resourceType: this.type, resourceId: this.id, resourceField: event.field, oldValue: event.oldValue, newValue: event.newValue }); } })(); }); }
[ "function SCModel(options) {\n Emitter.call(this);\n\n this.socket = options.socket;\n this.type = options.type;\n this.id = options.id;\n this.fields = options.fields;\n this.scFields = {};\n this.value = {\n id: this.id\n };\n\n this._triggerModelError = (err) => {\n // Throw error in different stack frame so that error handling\n // cannot interfere with a reconnect action.\n setTimeout(() => {\n if (this.listeners('error').length < 1) {\n throw err;\n } else {\n this.emit('error', err);\n }\n }, 0);\n };\n\n this._handleSCFieldError = (err) => {\n this._triggerModelError(err);\n };\n\n this._handleSCFieldChange = (event) => {\n this.value[event.field] = event.newValue;\n this.emit('change', {\n resourceType: this.type,\n resourceId: this.id,\n resourceField: event.field,\n oldValue: event.oldValue,\n newValue: event.newValue\n });\n };\n\n this.fields.forEach((field) => {\n let scField = new SCField({\n socket: this.socket,\n resourceType: this.type,\n resourceId: this.id,\n name: field\n });\n this.scFields[field] = scField;\n this.value[field] = null;\n scField.on('error', this._handleSCFieldError);\n scField.on('change', this._handleSCFieldChange);\n });\n}", "sync(method, model, options={}) {\n return Backbone.sync.call(this, method, model, _.defaults({\n error: xhr => {\n RB.storeAPIError(xhr);\n\n if (_.isFunction(options.error)) {\n options.error(xhr);\n }\n }\n }, options));\n }", "_handleEventModelSync(options)\n {\n if (options.model && options.model.constructor.name === 'Workflow')\n {\n this._workflow = options.model;\n }\n }", "_handleCommandResourceSave(options)\n {\n options.resource.save(options.fields, {patch: true, success: (model) => Radio.channel('rodan-client-core').trigger(Events.EVENT__RESOURCE_SAVED, {resource: model})});\n }", "sync(options={}) {\n return this._sync(options)\n }", "function sync(method, model, options) {\n var url;\n\n // Requested URL\n if (model.url) {\n if (typeof model.url === 'string') {\n url = model.url;\n } else {\n url = model.url();\n }\n }\n\n if (method === 'read' && url) {\n var request = requests[url];\n if (request) {\n request.then(\n // Success\n function(data) {\n // Delete from requests so that subsequent requests go through\n // Backbone original sync method\n delete requests[url];\n\n var method = options.reset ? 'reset' : 'set';\n model[method](data);\n\n if (options && options.success) {\n options.success(data);\n }\n\n model.trigger('sync', model, data, options);\n },\n // Error\n function(data, xhr) {\n if (options && options.error) {\n options.error(xhr);\n }\n\n model.trigger('error', model, xhr, options);\n }\n );\n return request;\n } else {\n // No request found for URL, use the original sync method\n return BackboneSync(method, model, options);\n }\n } else {\n // Not a GET or no URL, use the original sync method\n return BackboneSync(method, model, options);\n }\n }", "function BaseCRUD(options) {\n this.createEnabled = true;\n this.readEnabled = true;\n this.patchEnabled = true;\n this.updateEnabled = true;\n this.deleteEnabled = false;\n\n // Following two member variables should be assigned in concrete definition\n // of CRUD class.\n this.modelClass = undefined;\n this.key = undefined;\n this.socket = options.socket;\n this.handshake = options.handshake;\n // By default, broadcast event all client.\n this.exceptMe = false;\n\n /*\n * FIXME: Is this necessary for CRUD? \n * In the original crud.js, this variable is used never.\n */\n // The user's session id is found in the handshake\n this.sessionID = this.handshake.sessionID;\n }", "function BaseCRUD(options) {\n this.createEnabled = true;\n this.readEnabled = true;\n this.patchEnabled = true;\n this.updateEnabled = true;\n this.deleteEnabled = false;\n\n // Following two member variables should be assigned in concrete definition\n // of CRUD class.\n this.modelClass = undefined;\n this.key = undefined;\n this.socket = options.socket;\n this.handshake = options.handshake;\n // By default, broadcast event all client.\n this.exceptMe = false;\n\n /*\n * FIXME: Is this necessary for CRUD?\n * In the original crud.js, this variable is used never.\n */\n // The user's session id is found in the handshake\n this.sessionID = this.handshake.sessionID;\n }", "function sync(method, model, options) {\n\tvar url = options.url || _.result(model, 'url')\n\t\t, apiPrefix = getAPIPrefix()\n\t\t, httpMethod = methodMap[method];\n\n\tif(_.isUndefined(url)) {\n\t\tthrow new Error('No url present for syncing!', model, options);\n\t}\n\n\tif(url.substr(0, apiPrefix.length) === apiPrefix) {\n\t\turl = url.substr(apiPrefix.length);\n\t}\n\n\tvar apiRouteCallback = this.apiRoutes[httpMethod][url]\n\t\t, apiResult\n\t\t, error;\n\n\tif(_.isUndefined(apiRouteCallback)) {\n\t\tthrow new Error('Could not resolve API route: ' + url);\n\t}\n\n\ttry {\n\t\tapiResult = apiRouteCallback();\n\t} catch(err) {\n\t\terror = err;\n\t}\n\n\tif(!error) {\n\t\tif(options.success) { options.success(apiResult); }\n\t} else {\n\t\tif(options.error) { options.error(error); }\n\t}\n}", "syncVoiceModelStatus() {}", "function Resource(options) {\n events.EventEmitter.call(this);\n\n var _state = options.state;\n\n this.getState = function () { return _state; };\n\n this.setState = function (state, delay) {\n\n var emit = this.emit.bind(this);\n\n if (typeof delay == 'undefined') {\n\n changeState(); // synchronous\n\n } else {\n\n if (typeof delay == 'number') {\n emit('delay', delay, changeState);\n } else { // delay should be a stream\n emit('delay', delay.read(), delayCallback);\n }\n\n }\n\n return this;\n\n function changeState() {\n var newState = typeof state == 'function' ? state(_state) : state;\n if (newState !== _state) {\n var oldState = _state;\n _state = newState;\n emit('change', newState, oldState);\n }\n }\n\n function delayCallback() {\n changeState();\n emit('delay', delay.read(), delayCallback);\n }\n\n };\n\n }", "async setRelationData(type) {\n const {model} = this.options;\n\n const data = this.data[this.options.name];\n switch (type) {\n case 'ADD':\n data[this.options.fKey] = this.data[this.options.key];\n return model.add(data);\n case 'UPDATE':\n return model.where({\n [this.options.fKey]: this.data[this.options.key]\n }).update(data);\n case 'DELETE':\n return model.where({\n [this.options.fKey]: this.data[this.options.key]\n }).delete();\n }\n }", "function helpers_sync(method, model, options = {}) {\n const type = methodMap[method]; // Default JSON-request options.\n\n const params = {\n type: type,\n dataType: 'json'\n }; // Ensure that we have a URL.\n\n if (!options.url) {\n params.url = lodash_es_result(model, 'url') || urlError();\n } // Ensure that we have the appropriate request data.\n\n\n if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {\n params.contentType = 'application/json';\n params.data = JSON.stringify(options.attrs || model.toJSON(options));\n } // Don't process data on a non-GET request.\n\n\n if (params.type !== 'GET') {\n params.processData = false;\n } // Pass along `textStatus` and `errorThrown` from jQuery.\n\n\n const error = options.error;\n\n options.error = function (xhr, textStatus, errorThrown) {\n options.textStatus = textStatus;\n options.errorThrown = errorThrown;\n if (error) error.call(options.context, xhr, textStatus, errorThrown);\n }; // Make the request, allowing the user to override any Ajax options.\n\n\n const xhr = options.xhr = ajax(lodash_es_assignIn(params, options));\n model.trigger('request', model, xhr, options);\n return xhr;\n}", "sync() {\n const schema = new Hydrator().sync(this, this.model.schema);\n this.model.schema = schema;\n return new ActionGenerator({\n type: ['model', this.model.name, 'read'],\n value: this\n });\n }", "save(key, val, options) {\n // Handle both `\"key\", value` and `{key: value}` -style arguments.\n let attrs;\n if (key == null || typeof key === 'object') {\n attrs = key;\n options = val;\n } else {\n (attrs = {})[key] = val;\n }\n\n options = { validate: true, parse: true, ...options };\n const wait = options.wait;\n\n // If we're not waiting and attributes exist, save acts as\n // `set(attr).save(null, opts)` with validation. Otherwise, check if\n // the model will be valid when the attributes, if any, are set.\n if (attrs && !wait) {\n if (!this.set(attrs, options)) return false;\n } else if (!this._validate(attrs, options)) {\n return false;\n }\n\n // After a successful server-side save, the client is (optionally)\n // updated with the server-side state.\n const success = options.success;\n const attributes = this.attributes;\n options.success = (resp) => {\n // Ensure attributes are restored during synchronous saves.\n this.attributes = attributes;\n let serverAttrs = options.parse ? this.parse(resp, options) : resp;\n if (wait) serverAttrs = { ...attrs, ...serverAttrs };\n if (serverAttrs && !this.set(serverAttrs, options)) return false;\n if (success) success.call(options.context, this, resp, options);\n this.trigger('sync', this, resp, options);\n };\n wrapError(this, options);\n\n // Set temporary attributes if `{wait: true}` to properly find new ids.\n if (attrs && wait) this.attributes = { ...attributes, ...attrs };\n\n const method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';\n if (method === 'patch' && !options.attrs) options.attrs = attrs;\n const xhr = this.sync(method, this, options);\n\n // Restore attributes.\n this.attributes = attributes;\n\n return xhr;\n }", "function addSyncForModel(method, model, opt) {\n\tvar DB = new SQLite('_alloy_');\n\tvar mId = String(model.id);\n\tvar mTable = model.config.adapter.collection_name;\n\n\t// Insert the new sync call\n\tDB.table(exports.config.syncTableName)\n\t.insert({\n\t\ttimestamp: Util.now(),\n\t\tm_id: mId,\n\t\tm_table: mTable,\n\t\tmethod: method,\n\t\tmodel: JSON.stringify(model ? model.toJSON() : {}),\n\t\toptions: JSON.stringify(opt || {})\n\t})\n\t.run();\n}", "function BaseSync (options) {\n this.init(options);\n}", "vModelSync () {\n if (this.noSync) return\n this.$emit('input', this.formDataCompose())\n }", "$onInit() {\n this.TypeService.getTypes()\n .then(response => {\n this.typesAsyncData = response;\n this.socket.syncUpdates('type', this.typesAsyncData);\n })\n .catch(this.handleFormErrors.bind(this));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to check if country code match our checklist
function countryMatch(checkList, trackedCountry) { return checkList.indexOf(trackedCountry) > -1; }
[ "function country_check(country){\n\tfor (var i = 0; i < ufo_data.length; i++){\n\t\tif (ufo_data[i].country === country){\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function checkSameCountry(team1, team2){\n\tvar id1 = teamID[team1];\n\tvar id2 = teamID[team2];\n\n\tif(id1.indexOf(\"NZ\")!=-1 && id2.indexOf(\"NZ\")!=-1){\n\t\treturn true;\n\t}\n\telse if(id1.indexOf(\"AUS\")!=-1 && id2.indexOf(\"AUS\")!=-1){\n\t\treturn true;\n\t}\n\telse{\n\t\treturn false;\n\t}//end if\n}", "function passCitizenshipLookup(countryArr) {\n if (sanctionedCountryList.indexOf(countryArr[0]) !== -1 || sanctionedCountryList.indexOf(countryArr[1]) !== -1 || sanctionedCountryList.indexOf(countryArr[2]) !== -1) {\n return false;\n }\n return true;\n}", "function checkCountry() {\r\n\tlet country = document.getElementById(\"country_id\");\r\n\tlet name = country.value;\r\n\r\n\tlet valid = !name || name.length === 0 || countryList.includes(name.trim());\r\n\tif (!valid) {\r\n\t\tcountry.setCustomValidity(\"You must give an existing country (or none)\");\r\n\t} else {\r\n\t\tcountry.setCustomValidity(\"\");\r\n\t}\r\n}", "function _checkCountry(bupa, relevantCountry) {\n let address = bupa.toBusinessPartnerAddress\n return (address && (address.length > 0) && (address[0].country === relevantCountry))\n}", "function matchCountries(countryCode) {\r\n\r\n for (i = 0; i < countriesNames.length; i++) {\r\n\r\n if (countryCode == String(countriesNames[i].id))\r\n return i\r\n }\r\n }", "function containsCountry(list, item) {\n return list.some(function (el) {\n return el === item;\n });\n}", "function isValidPostalCode(code, country) {\n // debug.info( 'isValidPostalCode', code, country );\n code = $.trim(code);\n var format = getPostalCodeRegexMatrix(country);\n if (format) {\n if (code.length < parseInt(format.minlen)) {\n return false;\n }\n if (code.length > parseInt(format.maxlen)) {\n return false;\n }\n var re = new RegExp(format.regex);\n return re.test(code);\n }\n //getPostalCodeRegexMatrix will check the country as a key in the map postal_code_matrix, so for these countries which doesn't have postal code, we need to return true\n else if (format == '') {\n return true;\n }\n else {\n debug.log('No country found')\n return true;\n }\n}", "function getCountryCode(country){\r\n var out_country=countryCode.find(o => (o.Alpha2 === country || o.Alpha3 === country || o.Num === country));\r\n if(out_country) {\r\n return out_country.Alpha2;\r\n }\r\n else {\r\n return country;\r\n }\r\n }", "function validateCountry(c) {\n\t\t\tif(getLegalAge(c)>0) return true;\n\t\t\telse return false;\n\t\t}", "function countryFilter(value) { \n return (value.Country == checkedCountries[0]\n || value.Country == checkedCountries[1]\n || value.Country == checkedCountries[2]);\n}", "function addCountryCode(country) {\n\t\t\tvar found = false;\n\t\t\tif (country) {\n\t\t\t\tcountryCodes.forEach(function (value) {\n\t\t\t\t\tif (value == country) {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tif (!found) {\n\t\t\t\t\tcountryCodes.push(country)\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t}", "function checkCountryState() {\n if (country== -1) {\n country = \"any\";\n };\n if (cityStates === undefined || cityStates == \"\") {\n cityStates = \"any\";\n }\n }", "function check_special(zm, from, fz, to, tz)\n{\n var fc = find_country(from);\n var tc = find_country(to);\n\n // Zones must match?\n if (fz != tz) { return 0; }\n\n if (zm == null) { return 0; }\n if (zm[0] == -10) {\n /* Match single country only */\n if (fc != tc) { return 0; }\n if (matchlist(zm[1], fc) == -1) {\n return 0;\n }\n return 1;\n }\n if (zm[0] == -11) {\n /* Match either country */\n if (matchlist2(zm[1], from, fc) == -1) {\n return 0;\n }\n if (matchlist2(zm[1], to, tc) == -1) {\n return 0;\n }\n return 1;\n }\n return 0;\n}", "function postalCodeCheck(postal_code)\r\n{ \r\n var pattern_ca = /([ABCEGHJKLMNPRSTVWXYZ]\\d){3}/i;\r\n var pattern_usa = /^[0-9]{5}(?:-[0-9]{4})?$/;\r\n\r\n if((postal_code.length < 5) || (postal_code.length > 12))\r\n { \r\n return false;\r\n }\r\n\r\n if(pattern_ca.test(postal_code))\r\n { \r\n return true;\r\n }\r\n else if (pattern_usa.test(postal_code))\r\n { \r\n return true;\r\n } \r\n else\r\n {\r\n return false;\r\n }\r\n}", "function isValidPostalCode(LangCountryPair, PostalCode)\t\r\n{\r\n\tvar CountryID;\r\n\tif (LangCountryPair.indexOf(\"_\") != -1)\r\n\t\tCountryID = LangCountryPair.split(\"_\")[1];\r\n\telse\r\n\t\tCountryID = LangCountryPair;\r\n\r\n\tpostal = new Array();\r\n\tPostalCode = PostalCode.toUpperCase();\r\n\r\n\tpostal['AX'] = /^[0-9]{5}$/;\r\n\tpostal['AL'] = /^[0-9]{4}$/;\r\n\tpostal['DZ'] = /^[0-9]{5}$/;\r\n\tpostal['AD'] = /^(AD)[0-9]{3}$/;\r\n\tpostal['AR'] = /^([A-HJ-TP-Z]{1}\\d{4}[A-Z]{3}|[a-z]{1}\\d{4}[a-hj-tp-z]{3})$/;\r\n\tpostal['AM'] = /^[0-9]{4}$/;\r\n\tpostal['AC'] = /^(ASCN 1ZZ)$/;\r\n\tpostal['AU'] = /^[0-9]{4}$/;\r\n\tpostal['AT'] = /^[0-9]{4}$/;\r\n\tpostal['AZ'] = /^(AZ)[0-9]{4}$/;\r\n\tpostal['BD'] = /^[0-9]{4}$/;\r\n\tpostal['BB'] = /^(BB)[0-9]{5}$/;\r\n\tpostal['BY'] = /^[0-9]{6}$/;\r\n\tpostal['BE'] = /^[0-9]{4}$/;\r\n\tpostal['BR'] = /^[0-9]{5}([-]{0,1}[0-9]{3}){0,1}$/;\r\n\t//postal['BR'] = /^[0-9]{5}$/;\r\n\tpostal['IO'] = /^(BIQQ 1ZZ)$/;\r\n\tpostal['VG'] = /^(VG)[0-9]{4}$/;\r\n\tpostal['BN'] = /^[A-Z]{2}[0-9]{4}$/;\r\n\tpostal['BG'] = /^[0-9]{4}$/;\r\n\tpostal['KH'] = /^[0-9]{5}$/;\r\n\tpostal['CV'] = /^[0-9]{4}$/;\r\n\tpostal['CL'] = /^[0-9]{3}[-]{0,1}[0-9]{4}$/;\r\n\tpostal['CN'] = /^[0-9]{6}$/;\r\n\r\n// teik: change postal code requirement from 32dddd to dddddd for columbia\r\n//\t\tpostal['CO'] = /\\b(32)[0-9]{4}\\b/;\r\n\tpostal['CO'] = /^[0-9]{6}$/;\r\n\r\n\tpostal['CR'] = /^[0-9]{5}$/;\r\n\tpostal['HR'] = /^[0-9]{5}$/;\r\n\tpostal['CY'] = /^[0-9]{4}$/;\r\n\tpostal['CZ'] = /^[0-9]{3}( ){0,1}[0-9]{2}$/;\r\n\tpostal['DK'] = /^[0-9]{4}$/;\r\n\tpostal['EC'] = /^(EC)[0-9]{6}$/;\r\n\tpostal['EE'] = /^[0-9]{5}$/;\r\n\tpostal['FK'] = /^(BIQQ 1ZZ)$/;\r\n\tpostal['FI'] = /^[0-9]{5}$/;\r\n\tpostal['FR'] = /^[0-9]{5}$/;\r\n\tpostal['GE'] = /^[0-9]{4}$/;\r\n\tpostal['DE'] = /^[0-9]{5}$/;\r\n\tpostal['GR'] = /^[0-9]{5}$/;\r\n\tpostal['GG'] = /^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[0-9][ABD-HJLNP-UW-Z]{2}|(GIR\\ 0AA)|(SAN\\ TA1)|(BFPO\\ (C\\/O\\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\\ 1ZZ))$/;\r\n\tpostal['HU'] = /^[0-9]{4}$/;\r\n\tpostal['IS'] = /^[0-9]{3}$/;\r\n\tpostal['IN'] = /^[0-9]{3}( ){0,1}[0-9]{3}$/;\r\n\tpostal['ID'] = /^[0-9]{5}$/;\r\n\tpostal['IR'] = /^[0-9]{5}(-)[0-9]{5}$/;\r\n\tpostal['IQ'] = /^[0-9]{5}$/;\r\n\tpostal['IL'] = /^[0-9]{5}$/;\r\n\tpostal['IT'] = /^[0-9]{5}$/;\r\n\tpostal['JP'] = /^[0-9]{3}[-]{0,1}[0-9]{4}$/;\r\n\tpostal['JE'] = /^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[0-9][ABD-HJLNP-UW-Z]{2}|(GIR\\ 0AA)|(SAN\\ TA1)|(BFPO\\ (C\\/O\\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\\ 1ZZ))$/;\r\n\tpostal['KZ'] = /^[0-9]{6}$/;\r\n\tpostal['LV'] = /^(LV-)[0-9]{4}$/;\r\n\tpostal['LI'] = /^[0-9]{4}$/;\r\n\tpostal['LT'] = /^[0-9]{5}$/;\r\n\tpostal['LU'] = /^[0-9]{4}$/;\r\n\tpostal['MY'] = /^[0-9]{5}$/;\r\n\tpostal['MT'] = /^[A-Z]{3}[0-9]{4}$/;\r\n\tpostal['MX'] = /^[0-9]{5}$/;\r\n\tpostal['MD'] = /^(MD)(-){0,1}[0-9]{4}$/;\r\n\tpostal['MC'] = /^(980)[0-9]{2}$/;\r\n\tpostal['ME'] = /^[0-9]{5}$/;\r\n\tpostal['MA'] = /^[0-9]{5}$/;\r\n\tpostal['NL'] = /^[0-9]{4}( ){0,1}[A-Z]{2}$/;\r\n\tpostal['NZ'] = /^[0-9]{4}$/;\r\n\tpostal['NI'] = /^[0-9]{6}$/;\r\n\tpostal['NO'] = /^[0-9]{4}$/;\r\n\tpostal['PA'] = /^[0-9]{6}$/;\r\n\tpostal['PH'] = /^[0-9]{4}$/;\r\n\tpostal['PN'] = /^(PCRN 1ZZ)$/;\r\n\tpostal['PL'] = /^[0-9]{2}[-]{0,1}[0-9]{3}$/;\r\n\tpostal['PT'] = /^[0-9]{4}[ -]{0,1}[0-9]{3}$/;\r\n\tpostal['PR'] = /^[0-9]{5}$/;\r\n\tpostal['RO'] = /^[0-9]{6}$/;\r\n\tpostal['RU'] = /^[0-9]{6}$/;\r\n\tpostal['SM'] = /^[0-9]{5}$/;\r\n\tpostal['RS'] = /^[0-9]{5}$/;\r\n\tpostal['SG'] = /^[0-9]{6}$/;\r\n\tpostal['SK'] = /^[0-9]{3}( ){0,1}[0-9]{2}$/;\r\n\tpostal['SI'] = /^[0-9]{4}$/;\r\n\tpostal['ZA'] = /^[0-9]{4}$/;\r\n\tpostal['GS'] = /^(SIQQ 1ZZ)$/;\r\n\tpostal['KR'] = /^[0-9]{3}(-){0,1}[0-9]{3}$/;\r\n\tpostal['ES'] = /^[0-9]{5}$/;\r\n\tpostal['LK'] = /^[0-9]{5}$/;\r\n\tpostal['SE'] = /^[0-9]{3}( ){0,1}[0-9]{2}$/;\r\n\tpostal['CH'] = /^[0-9]{4}$/;\r\n\tpostal['TW'] = /^[0-9]{3}$/;\r\n\tpostal['TH'] = /^[0-9]{5}$/;\r\n\tpostal['TR'] = /^[0-9]{5}$/;\r\n\tpostal['TC'] = /^[0-9]{5}$/;\r\n\tpostal['UA'] = /^[0-9]{5}$/;\r\n\tpostal['VA'] = /^[0-9]{5}$/;\r\n\tpostal['VN'] = /^[0-9]{6}$/;\t\r\n\t\r\n\tpostal['IM'] = /^(IM)[0-9]{1,2}[0-9][A-Z]{2}$/;\r\n\tpostal['CA'] = /^[ABCEGHJKLMNPRSTVXY][0-9][A-Z][0-9][A-Z][0-9]$/;\r\n\tpostal['GB'] = /^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[0-9][ABD-HJLNP-UW-Z]{2}|(GIR\\ 0AA)|(SAN\\ TA1)|(BFPO\\ (C\\/O\\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\\ 1ZZ))$/;\r\n\tpostal['US'] = /^[0-9]{5}(?:-[0-9]{4})?$/;\r\n\r\n\t// Rules\r\n\t// 1. country blank, postalcode blank - fail, no country\r\n\t// 2. country blank, postalcode filled - fail, no country\r\n\t// 3. country filled, postalcode blank - depends on regex\r\n\t// 4. country filled, postalcode filled - depends on regex\r\n\t\r\n\t// if no country was passed in, we fail the check, rule 1 and 2\r\n\tif (CountryID == \"\") return false;\r\n\t\r\n\t// if we cannot find the country, regex will be empty and we will pass for all cases\r\n\tregex = postal[CountryID.toUpperCase()];\r\n if (regex == undefined) regex = \"\"\r\n \r\n\t// strip all the spaces from PostalCode\r\n\tPostalCode = PostalCode.replace(/ /g,'');\r\n\t// assume we pass until we fail\r\n\tretcode = true;\r\n if (PostalCode != \"\")\r\n {\r\n // rule 4\r\n\t if (PostalCode.search(regex) == -1)\r\n\t {\r\n\t\t // postal code has failed the regex\r\n\t\t retcode = false;\t\t\t \r\n\t }\r\n\t}\r\n\telse\r\n\t{\t\t \r\n\t // if regex is not empty and postal code is empty, we must fail\r\n\t // rule 3\r\n\t if (regex != \"\") retcode = false;\r\n\t}\r\n\t\r\n\tExpectedResult = 9;\r\n\tif (ExpectedResult != 9)\r\n\t{\r\n\t if (ExpectedResult == 0)\r\n\t if (retcode != false)\r\n\t \talert(PostalCode + \"\\r\\nCountry: \" + CountryID + \", Regex: \" + regex + \"\\r\\n\\r\\nDid not meet expected result of FALSE\");\r\n\t \r\n\t if (ExpectedResult != 0)\r\n\t if (retcode != true)\r\n\t alert(PostalCode + \"\\r\\nCountry: \" + CountryID + \", Regex: \" + regex + \"\\r\\n\\r\\nDid not meet expected result of TRUE\");\r\n\t \r\n alert(\"End of IsValidPostal\\r\\nPostalCode : \" + PostalCode + \"\\r\\nCountry: \" + CountryID);\r\n }\r\n \r\n /*\r\n // test cases supposed to pass\r\n isValidPostalCode(\"GB\", \"E16 1SW\")\r\n isValidPostalCode(\"GB\", \"E161SW\")\r\n isValidPostalCode(\"GB\", \"E161SW \")\r\n isValidPostalCode(\"GB\", \"E161SW \")\r\n isValidPostalCode(\"GB\", \" E161SW\")\r\n isValidPostalCode(\"GB\", \"E1 61SW\")\r\n isValidPostalCode(\"US\", \"12345\")\r\n isValidPostalCode(\"PT\", \"7777-777\",1)\r\n isValidPostalCode(\"KR\", \"999999\",1)\r\n isValidPostalCode(\"KR\", \"999-999\",1)\r\n isValidPostalCode(\"KR\", \"999 999\",1)\r\n isValidPostalCode(\"IM\", \"IM 2 2 2 A A\",1)\r\n isValidPostalCode(\"IM\", \"IM 2 2 A A\",1)\r\n \r\n isValidPostalCode(\"PT\", \"777-7777\",0)\r\n isValidPostalCode(\"CA\", \"A1A 2A2\",1)\r\n isValidPostalCode(\"CA\", \"A1A2A2 \",1)\r\n isValidPostalCode(\"CA\", \"A1A2A 2 \",1)\r\n\r\n isValidPostalCode(\"IM\", \"IM222 AA\",1)\r\n isValidPostalCode(\"IM\", \"IM22 AA\",1)\r\n isValidPostalCode(\"IM\", \"IM222AA\",1)\r\n isValidPostalCode(\"IM\", \"IM22AA\",1)\r\n isValidPostalCode(\"IM\", \"IM2 2 2 AA\",1)\r\n isValidPostalCode(\"IM\", \"IM22 AA\",1)\r\n isValidPostalCode(\"IM\", \"IM22 2AA\",1)\r\n isValidPostalCode(\"IM\", \"IM22 AA\",1)\r\n isValidPostalCode(\"IM\", \"IM 2 2 2 A A\",1)\r\n isValidPostalCode(\"IM\", \"IM 2 2 A A\",1)\r\n \r\n // test cases supposed to fail\r\n isValidPostalCode(\"SG\", \"This message must pop up\", 1)\r\n */\r\n \t\r\n\treturn retcode;\t \r\n}", "function isCanada(country) {\n let c = country.toUpperCase();\n return ((c == 'CANADA') || (c == 'CA') || (c == 'CAN'));\n}", "function validateCountry() {\n const countryInput = document.getElementById('country');\n const country = countryInput.value;\n // validates if the country is a real country\n if (!countryNames.includes(country)) {\n // notify user if not a valid country\n countryInput.classList.add('invalid');\n countryInput.setCustomValidity('Country does not exist.');\n countryInput.reportValidity();\n }\n countryInput.classList.remove('invalid');\n countryInput.setCustomValidity('');\n countryInput.reportValidity();\n}", "function isCountry( countryName ) {\n for (var i = 0; i < noOfCountries; i++) {\n if( countryName.toUpperCase() == countriesAndContinents[i].country)\n return true;\n }\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
THE MAIN FUNCTION CALL call the sparql endpoint and do the query
function do_sparql_query(resource_iri){ //console.log(resource_iri); //var header_container = document.getElementById("browser_header"); if (resource_iri != "") { //resource = "https://w3id.org/oc"+"/corpus/"+resource_iri; //initialize and get the browser_config_json browser_conf_json = browser_conf; var category = _get_category(resource_iri); //build the sparql query in turtle format var sparql_query = _build_turtle_prefixes() + _build_turtle_query(browser_conf_json.categories[category].query); //since its a resource iri we put it between < > //var global_r = new RegExp("[[VAR]]", "g"); //sparql_query = sparql_query.replace(global_r, resource_iri); sparql_query = sparql_query.replace(/\[\[VAR\]\]/g, resource_iri); //console.log(sparql_query); //use this url to contact the sparql_endpoint triple store var query_contact_tp = String(browser_conf_json.sparql_endpoint)+"?query="+ encodeURIComponent(sparql_query) +"&format=json"; //call the sparql end point and retrieve results in json format $.ajax({ dataType: "json", url: query_contact_tp, type: 'GET', success: function( res_data ) { //console.log(res_data); _build_page(res_data, category); } }); } }
[ "function sparql_query(endpoint, queryProcessor){\n\tvar querypart = \"query=\" + escape(queryProcessor.query);\n\t// Get our HTTP request object.\n\tvar xmlhttp = getHTTPObject();\n\t//Include POST OR GET\n\txmlhttp.open('POST', endpoint, true); \n\txmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n\txmlhttp.setRequestHeader(\"Accept\", \"application/sparql-results+json\");\t\n\txmlhttp.onreadystatechange = function() {\n\t\tif(xmlhttp.readyState==4 ){\n\t\t\tif(xmlhttp.status==200){\t\t\t\t\n\t\t\t\t//Request accept\t\t\t\t\n\t\t\t\tvar resultAsJson=eval('(' + xmlhttp.responseText + ')');\n\t\t\t\tfor(var i = 0; i< resultAsJson.results.bindings.length; i++) {\n\t\t\t\t\tqueryProcessor.process(resultAsJson.results.bindings[i]);\n\t\t\t\t}\n\t\t\t\tqueryProcessor.flush();\n\t\t\t} else {\n\t\t\t\t// Some kind of error occurred.\n\t\t\t\t\talert(\"Sparql query error: \" + xmlhttp.status + \" \"\n\t\t\t\t\t\t+ xmlhttp.responseText);\n\t\t\t}\n\t\t}\t\n\t}\n\txmlhttp.send(querypart);\n}", "function sparqlQuery(q, callback){\n\tvar pref = 'PREFIX movie:<http://data.linkedmdb.org/resource/movie/>'\n\t\t+ 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>'\n\t\t+ 'PREFIX foaf: <http://xmlns.com/foaf/0.1/>'\n\t\t+ 'PREFIX dc: <http://purl.org/dc/terms/>';\n\tvar url = 'http://data.linkedmdb.org/sparql?query='+encodeURIComponent(pref+q);\n\tvar yql = 'http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent('select * from xml where url=\"'+url+'\"')+'&format=json';\n\t$.ajax({\n\t\turl: yql,\n\t\tdataType: 'jsonp',\n\t\tjsonp: 'callback',\n\t\tjsonpCallback: callback\n\t});\n}", "function query() {\n\tclear();\n\thylarWorker.postMessage({\n\t\taction: \"query\",\n\t\tquery: document.getElementById(\"sparql\").value\n\t})\n}", "function sparqlQuery() {\n $(\"#errorPanel\").addClass('hidden');\n $(\"#infoPanel\").addClass('hidden');\n $(\"#results\").addClass('hidden');\n $(\"#noResultPanel\").addClass('hidden');\n var ISEARCH = document.getElementById('isearch').value;\n var SSEARCH = document.getElementById('ssearch').value;\n var ASEARCH = document.getElementById('asearch').value;\n var RSEARCH = document.getElementById('search-result').value;\n if (ISEARCH != '' || SSEARCH != '' || ASEARCH != '') {\n if(STORAGETYPE === \"SEEK\"){\n var query = \n \"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \" +\n \"PREFIX dcterms: <http://purl.org/dc/terms/> \" +\n \"PREFIX jerm: <http://jermontology.org/ontology/JERMOntology#> \" +\n \"SELECT DISTINCT (COALESCE(?fileurl, \\\"NA\\\") as ?fileurl) (COALESCE(?filetitle, \\\"NA\\\") as ?filetitle) ?investigation ?study ?assay WHERE {\" +\n \"?i dcterms:title ?investigation ; \" +\n \"rdf:type jerm:Investigation .\" +\n \"?i jerm:itemProducedBy ?projectid . \" +\n \"?projectid dcterms:title ?project . \" +\n \"?i jerm:hasPart ?studyid . \" +\n \"?studyid dcterms:title ?study . \" +\n \"?studyid jerm:hasPart ?assayid . \" +\n \"?assayid dcterms:title ?assay . \" +\n \"OPTIONAL {\" +\n \"?fileurl jerm:isPartOf ?assayid . \" + \n \"?fileurl dcterms:title ?filetitle .\" +\n \"}\" +\n \"FILTER regex(?investigation, '\" + ISEARCH + \"', 'i') . \" +\n \"FILTER regex(?study, '\" + SSEARCH + \"', 'i') . \" +\n \"FILTER regex(?assay, '\" + ASEARCH + \"', 'i') . \" +\n \"FILTER (!regex(?assay, '__result__', 'i')) . \" +\n \"FILTER (!regex(?fileurl, 'samples', 'i')) . \" +\n \"}\";\n } \n }\n if (RSEARCH != '') {\n var query = \n \"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \" +\n \"PREFIX dcterms: <http://purl.org/dc/terms/> \" +\n \"PREFIX jerm: <http://jermontology.org/ontology/JERMOntology#> \" +\n \"SELECT DISTINCT ?assayid (?assay AS ?result_assay) ?investigation ?study ?date WHERE {\" +\n \"?i dcterms:title ?investigation ; \" +\n \"rdf:type jerm:Investigation .\" +\n \"?i jerm:itemProducedBy ?projectid . \" +\n \"?projectid dcterms:title ?project . \" +\n \"?i jerm:hasPart ?studyid . \" +\n \"?studyid dcterms:title ?study . \" +\n \"?studyid jerm:hasPart ?assayid . \" +\n \"?assayid dcterms:title ?assay . \" +\n \"?assayid dcterms:created ?date . \" +\n \"?file jerm:isPartOf ?assayid . \" + \n \"?file dcterms:title ?filetitle . \" +\n \"FILTER regex(?study, '\" + RSEARCH + \"', 'i') .\" +\n \"FILTER regex(?assay, '__result__', 'i')} ORDER BY DESC(?date)\";\n }\n var isValueMissing = false;\n if (ISEARCH === '' && SSEARCH === '' && ASEARCH === '' && RSEARCH === '') {\n var errorMessage = (\"<strong>Input error : \" +\n \"</strong>Please enter a value \")\n isValueMissing = true;\n $(\"#errorPanel\").html(errorMessage);\n $(\"#errorPanel\").removeClass('hidden');\n return false;\n }\n if (!isValueMissing) {\n $('#process').buttonLoader('start');\n console.log(\"SPARQL query \\n\" + query);\n var service = encodeURI(SPARQL_ENDPOINT + query + '&format=json').\n replace(/#/g, '%23').replace('+', '%2B');\n $(\"#infoPanel\").html(\n '<strong>Info :</strong> Some queries take more time to process,' +\n 'thanks for being patient');\n $.ajax({\n url: service, dataType: 'jsonp', success: function (result) {\n document.getElementById('isearch').value = '';\n document.getElementById('ssearch').value = '';\n document.getElementById('asearch').value = '';\n document.getElementById('search-result').value = ''; \n if (ASEARCH != '') {\n SEARCH_ASSAY = ASEARCH;\n } else {\n try {\n result.results.bindings.forEach(function (value) {\n SEARCH_ASSAY = value.assay.value;\n });\n } catch (error) {\n console.log('No value');\n SEARCH_ASSAY = '';\n }\n }\n fillTable(result);\n },\n error: function (xhr) {\n alert(\"An error occured: \" + xhr.status + \" \" +\n xhr.statusText);\n }\n });\n }\n}", "function sparqlConstructQuery(query, endpoint, svg, table) {\n // Construct the request and initialise the response string.\n var parameters = \"query=\" + encodeURI(query);\n var request = new XMLHttpRequest();\n var response = \"\";\n var quads = [];\n\n // Set up a POST request with JSON-LD response.\n request.open('POST', endpoint, true);\n request.onreadystatechange = function() {\n // Get response and build visualisation (graph).\n if (this.readyState == 4) {\n if (this.status == 200) {\n try {\n response = JSON.parse(this.responseText);\n displayGraphJson(response, endpoint, svg, table);\n } catch (err) {\n displayConstructError(table);\n }\n } else {\n alert(\"Error in response: \" + request.status + \" \" +\n request.responseText);\n }\n }\n };\n request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n request.setRequestHeader(\"Accept\", \"application/ld+json\");\n request.send(parameters);\n}", "function sparqlSelectQuery(query, endpoint, target) {\n // Construct the request and initialise the response string.\n var parameters = \"query=\" + encodeURI(query);\n var request = new XMLHttpRequest();\n var response = \"\";\n\n // Set up a POST request with JSON response.\n request.open('POST', endpoint, true);\n request.onreadystatechange = function() {\n // Get response and build visualisation (table).\n if (this.readyState == 4) {\n if (this.status == 200) {\n console.log(this.responseText);\n try {\n response = JSON.parse(this.responseText);\n displayTableJson(response, target);\n } catch (err) {\n displaySelectError(target);\n }\n } else {\n alert(\"Error in response: \" + request.status + \" \" +\n request.responseText);\n }\n }\n };\n request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n request.setRequestHeader(\"Accept\", \"application/sparql-results+json\");\n request.send(parameters);\n}", "async query(db = '', sparql = '') {\n // 请求字符串居然有顺序要求。。。\n const queryTemplate = this.basicTemplate(\n 'query',\n `db_name=${db}&format=json&sparql=${sparql}`\n );\n\n return await request({\n uri: queryTemplate,\n method: 'GET',\n json: true\n });\n }", "function executeQuery(){\r\n\treadRequest(urlBuilder.getSearchURL());\r\n}", "function testAskQuery( endpoint, testcase, query, expected, failureMessage) {\r\n\r\n\t\t//define the callback object\r\n\t\tvar callback = {\r\n\t\t\tsuccess: genericAskQueryResponseSuccess(testcase, expected, failureMessage),\r\n\t\t\tfailure: genericResponseFailure(testcase)\r\n\t\t};\r\n\t\t\r\n\t\t// define SPARQL query & URL\r\n\t\tquery = sparqlns + query;\t\r\n\t\t\r\n var url = endpoint + \"?output=json&query=\" + escape(query);\r\n \r\n log(\"Unescaped query: \"+query);\r\n \r\n var method = \"GET\";\r\n\t\t\r\n\t\tlog(\"Make the request to \"+url);\r\n\t\tvar request = YAHOO.util.Connect.asyncRequest(method, url, callback, null);\r\n\t\t\r\n\t\tlog(\"Suspend the test runner\");\r\n\t\ttestcase.wait();\r\n\t\r\n}", "function sparqlquery(){\n\tvar queryStr = $(\"#SPARQLqueryBuilder .SPARQLTextArea\").val();\t\n\tvar sparqlFormatIndex = $(\"#SPARQLFormat\").prop(\"selectedIndex\");\n\tvar elems = $(\"#fed_of_queries_instances\")[0].getElementsByTagName(\"input\");\n for(var i = 0; i < elems.length; i++) {\n \tif(elems[i].checked == true)\n \t{\n \t\telems[i].setAttribute(\"checked\",\"checked\");\n \t}else\n \t{\n \t\telems[i].removeAttribute('checked');\n \t}\n }\n\tvar fedOfQueries = $(\"#fed_of_queries_instances\").html()\n\texecute_sparql_query(queryStr, sparqlFormatIndex, fedOfQueries);\n}", "function queryRegulationPml(regId){\n var regOwl=regNames[regId]+\".owl\";\n\n var sparqlRegulationPml=\"PREFIX foaf: <http://xmlns.com/foaf/0.1/> \\r\\n\"+ \n \"PREFIX oboro: <http://obofoundry.org/ro/ro.owl#> \\r\\n\"+ \n \"PREFIX pmlp: <http://inference-web.org/2.0/pml-provenance.owl#>\\r\\n\"+ \n \"PREFIX pmlj: <http://inference-web.org/2.0/pml-justification.owl#>\\r\\n\"+ \n \"select ?srcUrl ?downloadTime ?infEng ?convertTime ?user\\r\\n\"+ \n \"where {\\r\\n\"+ \n \"graph <http://sparql.tw.rpi.edu/semantaqua/water-regulations/provenance> {\\r\\n\"+ \n \"<\"+regOwl+\"> pmlp:hasReferenceSourceUsage ?su1.\\r\\n\"+\n \"?su1 pmlp:hasSource ?csvfile.\\r\\n\"+ \n \"?su1 pmlp:hasUsageDateTime ?convertTime.\\r\\n\"+ \n \"?infStep1 pmlj:hasSourceUsage ?su1.\\r\\n\"+ \n \"?infStep1 pmlj:hasInferenceEngine ?infEng.\\r\\n\"+ \n \"?infStep1 oboro:has_agent ?agt .\\r\\n\"+ \n \"?user foaf:holdsAccount ?agt .\\r\\n\"+ \n \"?csvfile pmlp:hasReferenceSourceUsage ?su2.\\r\\n\"+ \n \"?su2 pmlp:hasSource ?srcfile.\\r\\n\"+ \n \"?srcfile pmlp:hasReferenceSourceUsage ?su3.\\r\\n\"+ \n \"?su3 pmlp:hasSource ?srcUrl.\\r\\n\"+ \n \"?su3 pmlp:hasUsageDateTime ?downloadTime.\\r\\n\"+ \n \"}}\";\n //alert(sparqlRegulationPml);\n\n $.ajax({type: \"GET\",\n url: provServiceagent,\n data: \"query=\"+encodeURIComponent(sparqlRegulationPml),\n dataType: \"xml\", \n success: processRegulationPml,\n \terror: function (jqXHR, textStatus, errorThrown){\n\t\t\t\t\t\talert(jqXHR.status+\", \"+textStatus+\", \"+ errorThrown);\n \t}\n });\n}", "function executeQuery() {\n\t// query object\n\tvar query = new Object();\n\t// with an array of facets for processing results\n\tquery.facetsA = new Array();\n\t// array of sparql variables\n\tvar variableA = new Array();\n\t// array of triple patterns\n\tvar triplePA = new Array();\n\t\n\t// set the root facet\n\tvar rootFacet = processFacet($(\"#\"+Composer.composerId+\" ul.facet\").first(),\"X\");\n\trootFacet.optional = false;\n\tquery.facetsA.push(rootFacet);\n\t\n\t// get the relevant info for constructing the query\n\tvar rootType = getType($(\"#\"+Composer.composerId).attr(\"typeId\"));\n\tvar outlinks = getOutgoingLinks(rootType.id);\n\tvar inlinks = getIncomingLinks(rootType.id);\n\tvar templinks = getTemplateLinks(rootType.id);\n\t\n\t// get the facets \n\t$(\"#\"+Composer.composerId+\" div.facet\").each(function(ind) {\n\t\tif ( !$(this).hasClass('ui-collapsible-collapsed') ) {\t\t\t\n\t\t\tvar facet = processFacet($(this),\"X\"+ind);\n\t\t\tquery.facetsA.push(facet);\n\t\t}\n\t});\n\n\t// process each facet (root type and property-types)\n\t$.each(query.facetsA, function(j,facet) {\n\t\t// get type\n\t\tvar type = getType(facet.typeId);\n\t\t// variable\n\t\tvar varname = '?'+facet.id;\t\t\n\t\t\n\t\t// include sparql variable and displayable label\n\t\tvariableA.push(varname);\n\t\t\n\t\t// if optional... (opening)\n\t\tif ( parameters.optional && facet.optional )\n\t\t\ttriplePA.push('OPTIONAL { ');\n\t\t\n\t\t// type restriction 28-apr-2016 *****\n\t\ttriplePA.push(varname+' a <'+type.uri+'> .');\n\t\t\n\t\t// links modified 28-apr-2016 ***** \n\t\tif (facet.id !== rootFacet.id) {\n\t\t\tvar auxA = new Array();\n\t\t\t\n\t\t\t// different strategy depending on the hidePropertiesMode\n\t\t\tif (parameters.hidePropertiesMode) {\n\t\t\t\t$.each(outlinks, function(i,el) {\n\t\t\t\t\tif (el.target === type.id || isSuperClassOf(el.target, type.id)) {\n\t\t\t\t\t\tvar property = getObjectProperty(el.propId);\n\t\t\t\t\t\tvar triple = '?'+rootFacet.id+' <'+property.uri+'> '+varname;\n\t\t\t\t\t\t// avoid repetitions\n\t\t\t\t\t\tif (!existsElement(triple, auxA))\n\t\t\t\t\t\t\tauxA.push(triple);\n\t\t\t\t\t}\n\t\t\t\t}); \n\t\t\t\t$.each(inlinks, function(i,el) {\n\t\t\t\t\tif (el.source === type.id || isSuperClassOf(el.source, type.id)) {\t\t\t\t\n\t\t\t\t\t\t//auxA.push(varname+' <'+property.uri+'> ?'+rootFacet.id);\n\t\t\t\t\t\tvar property = getObjectProperty(el.propId);\n\t\t\t\t\t\tvar triple = varname+' <'+property.uri+'> ?'+rootFacet.id;\n\t\t\t\t\t\t// avoid repetitions\n\t\t\t\t\t\tif (!existsElement(triple, auxA))\n\t\t\t\t\t\t\tauxA.push(triple);\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t$.each(templinks, function(i,el) {\n\t\t\t\t\tif (el.target === type.id || isSuperClassOf(el.target, type.id)) {\n\t\t\t\t\t\tvar property = getTemplateProperty(el.propId);\n\t\t\t\t\t\tvar template = property.template;\n\t\t\t\t\t\t// set source and target\n\t\t\t\t\t\tvar auxtemp = {};\n\t\t\t\t\t\tauxtemp.source = '?'+rootFacet.id;\n\t\t\t\t\t\tauxtemp.target = varname;\n\t\t\t\t\t\t// apply moustache templating for the source and target\t\t\t\t\t\n\t\t\t\t\t\tvar triple = Mustache.render(template, auxtemp);\n\t\t\t\t\t\t// avoid repetitions\n\t\t\t\t\t\tif (!existsElement(triple, auxA))\n\t\t\t\t\t\t\tauxA.push(triple);\t\t\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// obtain property from the facet data\n\t\t\t\tvar prop = getObjectProperty(facet.propId);\t\n\t\t\t\t// check if the property-type is outgoing, incoming or both\t\n\t\t\t\t$.each(outlinks, function(i,el) {\n\t\t\t\t\tif (el.target === type.id || isSuperClassOf(el.target, type.id)) {\n\t\t\t\t\t\tvar auxprop = getObjectProperty(el.propId);\n\t\t\t\t\t\tif (prop.id === auxprop.id) {\n\t\t\t\t\t\t\tvar triple = '?'+rootFacet.id+' <'+prop.uri+'> '+varname;\n\t\t\t\t\t\t\t// avoid repetitions\n\t\t\t\t\t\t\tif (!existsElement(triple, auxA))\n\t\t\t\t\t\t\t\tauxA.push(triple);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}); \n\t\t\t\t$.each(inlinks, function(i,el) {\n\t\t\t\t\tif (el.source === type.id || isSuperClassOf(el.source, type.id)) {\n\t\t\t\t\t\tvar auxprop = getObjectProperty(el.propId);\n\t\t\t\t\t\tif (prop.id === auxprop.id) {\n\t\t\t\t\t\t\tvar triple = varname+' <'+prop.uri+'> ?'+rootFacet.id;\n\t\t\t\t\t\t\t// avoid repetitions\n\t\t\t\t\t\t\tif (!existsElement(triple, auxA))\n\t\t\t\t\t\t\t\tauxA.push(triple);\n\t\t\t\t\t\t}\t\t\t\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (prop === undefined) // it's a template property\n\t\t\t\t\tprop = getTemplateProperty(facet.propId);\t\n\t\t\t\t$.each(templinks, function(i,el) {\n\t\t\t\t\tif (el.target === type.id || isSuperClassOf(el.target, type.id)) {\n\t\t\t\t\t\tvar auxprop = getTemplateProperty(el.propId);\n\t\t\t\t\t\tif (prop.id === auxprop.id) {\n\t\t\t\t\t\t\tvar template = prop.template;\n\t\t\t\t\t\t\t// set source and target\n\t\t\t\t\t\t\tvar auxtemp = {};\n\t\t\t\t\t\t\tauxtemp.source = '?'+rootFacet.id;\n\t\t\t\t\t\t\tauxtemp.target = varname;\n\t\t\t\t\t\t\t// apply moustache templating for the source and target\t\t\t\t\t\n\t\t\t\t\t\t\tvar triple = Mustache.render(template, auxtemp);\n\t\t\t\t\t\t\t// avoid repetitions\n\t\t\t\t\t\t\tif (!existsElement(triple, auxA))\n\t\t\t\t\t\t\t\tauxA.push(triple);\n\t\t\t\t\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\t// check number of possible links\n\t\t\tif (auxA.length == 1) {\n\t\t\t\t// common case\n\t\t\t\ttriplePA.push(auxA[0]+' .');\n\t\t\t}\n\t\t\telse if (auxA.length > 1) {\n\t\t\t\t// UNION case...\n\t\t\t\tvar triple = '{ '+ auxA[0];\n\t\t\t\tfor (var ind =1; auxA.length > ind; ind++)\n\t\t\t\t\ttriple += ' } UNION { '+auxA[ind];\n\t\t\t\ttriple += ' } .';\n\t\t\t\ttriplePA.push(triple);\n\t\t\t}\n\t\t}\t\t\t\n\t\t\n\t\t// only do this if there is a displayable property (not false)\n\t\tif (type.display) {\t\t\n\t\t\t// treat displayable variable case if not included in the restrictions...\n\t\t\tvar displayProp = getDatatypeProperty(type.display); \n\t\t\tif (!containsValueArray(displayProp.id, \"propId\", facet.literalA)) {\n\t\t\t\t// include variable and triple\n\t\t\t\tvariableA.push('?'+facet.display.id);\n\t\t\t\ttriplePA.push(varname+' <'+displayProp.uri+'> ?'+facet.display.id+' .');\n\t\t\t}\n\t\t}\n\t\t\t\t\t\n\t\t// literal restrictions and variable names\n\t\t$.each(facet.literalA, function(i, litrest) {\n\t\t\tvar dataProp = getDatatypeProperty(litrest.propId);\n\t\t\tvar litVal = getLiteralValue(facet.typeId, litrest.propId);\n\t\t\tlitrest.label = multilingual( dataProp.label );\n\t\t\tvar litvar = '?'+litrest.id;\n\t\t\t// triples\n\t\t\tswitch(litrest.uiType) {\n\t\t\t\tcase 'literalSet':\n\t\t\t\t\t// 14-apr-2016: changed to match literals with string datatype\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tvar triple = '';\n\t\t\t\t\tif (litrest.lang != undefined)\n\t\t\t\t\t\ttriple = varname+' <'+dataProp.uri+'> \"'+litrest.value\n\t\t\t\t\t\t\t+'\"@'+litrest.lang+' .';\n\t\t\t\t\telse {\n\t\t\t\t\t\t//triple = varname+' <'+dataProp.uri+'> \"'+litrest.value+'\" .';\n\t\t\t\t\t\ttriple = '{{'+varname+' <'+dataProp.uri+'> \"'+litrest.value+'\" .}\\n' \n\t\t\t\t\t\t\t+ 'UNION\\n'\n\t\t\t\t\t\t\t+ '{'+varname+' <'+dataProp.uri+'> \"'+litrest.value+'\"^^<http://www.w3.org/2001/XMLSchema#string> .}}';\n\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\ttriplePA.push(triple);\n\t\t\t\t\tlitvar = '(str(\"'+litrest.value+'\") AS ?'+litrest.id+')';\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'range':\n\t\t\t\t\ttriplePA.push(varname+' <'+dataProp.uri+'> '+litvar+' .');\n\t\t\t\t\tif ( litVal.transform == undefined ) {\n\t\t\t\t\t\ttriplePA.push('FILTER ('+litvar+' >= '+litrest.min+')');\n \t\t\ttriplePA.push('FILTER ('+litvar+' <= '+litrest.max+')');\n \t\t}\n \t\telse {\n \t\t\ttriplePA.push('FILTER ('+litVal.transform+'('+litvar+') >= '+litrest.min+')');\n \t\t\ttriplePA.push('FILTER ('+litVal.transform+'('+litvar+') <= '+litrest.max+')');\n\t }\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'datetimerange':\n\t\t\t\t\ttriplePA.push(varname+' <'+dataProp.uri+'> '+litvar+' .');\n\t\t\t\t\ttriplePA.push('FILTER ('+litvar+' >= \"'+litrest.min+'\"^^<http://www.w3.org/2001/XMLSchema#dateTime>)');\n \t\ttriplePA.push('FILTER ('+litvar+' <= \"'+litrest.max+'\"^^<http://www.w3.org/2001/XMLSchema#dateTime>)');\n\t\t\t\t\tbreak;\t\n\t\t\t\tcase 'string':\n\t\t\t\t\tswitch(litVal.dataType) {\n\t\t\t\t\t\tcase 'langString':\n\t\t\t\t\t\tcase 'string':\n\t\t\t\t\t\t\ttriplePA.push(varname+' <'+dataProp.uri+'> '+litvar+' .');\n\t\t\t\t\t\t\ttriplePA.push('FILTER regex('+litvar+', \"'+litrest.value+'\",\"i\")');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'integer':\n\t\t\t\t\t\t\ttriplePA.push(varname+' <'+dataProp.uri+'> '+litrest.value+' .');\n\t\t\t\t\t\t\tlitvar = '('+litrest.value+' AS ?'+litrest.id+')';\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\ttriplePA.push(varname+' <'+dataProp.uri+'> '+litvar+' .');\n\t\t\t\t\t\t\ttriplePA.push('FILTER ('+litVal.transform+'('+litvar+') = '+litrest.value+')');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'checkbox':\n\t\t\t\t\tvar auxA = new Array();\n\t\t\t\t\ttriplePA.push(varname+' <'+dataProp.uri+'> '+litvar+' .');\n\t\t\t\t\t$.each(litrest.values, function(i, cv) {\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tswitch(litVal.dataType) {\n\t\t\t\t\t\t\tcase 'langString':\n\t\t\t\t\t\t\tcase 'string':\n\t\t\t\t\t\t\t\tauxA.push(varname+' <'+dataProp.uri+'> \"'+cv+'\"');\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'integer':\n\t\t\t\t\t\t\t\tauxA.push(varname+' <'+dataProp.uri+'> '+cv);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tauxA.push(litVal.transform+'('+litvar+') = '+cv);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tswitch(litVal.dataType) {\n\t\t\t\t\t\tcase 'langString':\n\t\t\t\t\t\tcase 'string':\n\t\t\t\t\t\tcase 'integer':\n\t\t\t\t\t\t\tif (auxA.length == 1) \t\t\t\t\t\n\t\t\t\t\t\t\t\ttriplePA.push(auxA[0]+' .');\n\t\t\t\t\t\t\telse if (auxA.length > 1) {\n\t\t\t\t\t\t\t\t// UNION case...\n\t\t\t\t\t\t\t\tvar triple = '{ '+ auxA[0];\n\t\t\t\t\t\t\t\tfor (var ind =1; auxA.length > ind; ind++)\n\t\t\t\t\t\t\t\t\ttriple += ' } UNION { '+auxA[ind];\n\t\t\t\t\t\t\t\ttriple += ' } .';\n\t\t\t\t\t\t\t\ttriplePA.push(triple);\n\t\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tif (auxA.length == 1) \t\t\t\t\t\n\t\t\t\t\t\t\t\ttriplePA.push('FILTER ('+auxA[0]+')');\n\t\t\t\t\t\t\telse if (auxA.length > 1) {\n\t\t\t\t\t\t\t\t// UNION case...\n\t\t\t\t\t\t\t\tvar triple = 'FILTER ( '+ auxA[0];\n\t\t\t\t\t\t\t\tfor (var ind =1; auxA.length > ind; ind++)\n\t\t\t\t\t\t\t\t\ttriple += ' || '+auxA[ind];\n\t\t\t\t\t\t\t\ttriple += ' )';\n\t\t\t\t\t\t\t\ttriplePA.push(triple);\n\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\tbreak;\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t\tbreak;\t\n\t\t\t\tcase 'optional':\n\t\t\t\t\ttriplePA.push('OPTIONAL {'+varname+' <'+dataProp.uri+'> '+litvar+' }');\t\t\t\t\n\t\t\t\t\tbreak;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t}\t\n\t\t\t// include name \n\t\t\tvariableA.push(litvar);\n\t\t});\n\t\n\t\t// if optional... (closing)\n\t\tif ( parameters.optional && facet.optional )\n\t\t\ttriplePA.push('} ');\n\t\t\n\t\t// only do this if there is a displayable property (not false)\n\t\tif (type.display) {\t\t\n\t\t\t// remove displayable restriction, if necessary\n\t\t\tif (containsValueArray(displayProp.id, \"propId\", facet.literalA)) {\n\t\t\t\t// get element\n\t\t\t\tvar displit = getElement(displayProp.id, \"propId\", facet.literalA);\n\t\t\t\tvar index = facet.literalA.indexOf(displit);\n\t\t\t\t// remove\n\t\t\t\tfacet.literalA.splice(index, 1);\n\t\t\t}\t\t\n\t\t}\t\t\n\t});\n\t\n\t// sparql base url\n\tquery.sparqlBase = parameters.sparqlBase;\n\t\n\t// sparql query\n\tquery.sparql = 'SELECT DISTINCT';\n\tfor (var i=0;i<variableA.length;i++)\n\t\tquery.sparql += ' '+variableA[i];\n\tquery.sparql += ' \\nWHERE { \\n';\n\n // include triple patterns\n\tfor (var i=0;i<triplePA.length;i++)\n\t\tquery.sparql += triplePA[i]+' \\n';\n\n\tquery.sparql += '}';\n\t// add LIMIT to the query\n\tquery.sparql += '\\nLIMIT '+parameters.sparqlLIMIT;\n\t// request results\n\tshowResults(query);\t\n}", "processQuery(form) {\n let data;\n if (typeof form !== \"undefined\")\n data = this.getFormData(form);\n if (data.uri !== null && data.uri.length == 0) {\n alert('You must provide a SPARQL Endpoint!');\n return;\n }\n if (data.query !== null && data.query.trim().length == 0) {\n alert('You must provide a query!');\n return;\n }\n data[\"id\"] = new Date().getTime();\n // selectedQuery = data.id;\n this.tune(data);\n this.sendRequest(data);\n this.query.params = data.params;\n }", "function sparqlUpdate (query, callback) {\n var sparqlURL = SPARQL_ENDPOINT + \"?update=\" + encodeURIComponent(query);\n\n request.post({\n url: sparqlURL,\n }, function (error, response, body) {\n if (error) {\n console.error(error);\n }\n\n console.log(body);\n callback();\n });\n}", "function Query () {}", "async queryExecute() {\n this.smartapi_edges = [];\n Object.keys(this.edges).map(edge => {\n this.smartapi_edges = [...this.smartapi_edges, ...this.edges[edge].smartapi_edges];\n });\n let executor = new call_api(this.smartapi_edges);\n await executor.query();\n this.query_result = executor.result;\n let at = new annotate(this.query_result, {})\n await at.annotateNGD();\n this.query_result = at.queryResult;\n this.query_result = this.filterResponse(this.query_result)\n\n }", "async sendRequest(values) {\n const url = this.protocol + this.hostname + \"/sparql\"; // local server\n const data = {\n 'query': values,\n 'dataset': this.page\n };\n try {\n await fetch(url, {\n method: 'POST',\n body: JSON.stringify(data)\n }).then(response => {\n if (!response.ok) {\n throw new Error(`${response.status}: ${response.statusText}`);\n }\n else {\n return response.text();\n }\n }).then(text => {\n if (text.startsWith('Virtuoso')) {\n // Syntax error message\n window.alert(text);\n }\n else if (text.startsWith('<')) {\n const html = new DOMParser().parseFromString(text, 'text/html').body.childNodes[0];\n alert(html.textContent);\n }\n else {\n this.getResult(text, values);\n }\n }).catch(error => {\n console.log(error);\n alert(error);\n this.hideLoading();\n this.enableButton();\n });\n }\n catch (_a) {\n error => console.log(error);\n }\n }", "function SparqlQueryAdapter() {\n\n var self = this;\n\n // Override of SparqlRoute.handleResponse\n this.handleResponse = function(responseString, requestParams, sparqlEndpoint) {\n\n // Initiate main workflow\n return Q()\n .then(function () {\n if (!_.startsWith(responseString, '{')) {\n throw new ToasterError(\"Invalid SPARQL endpoint response, possibly due to FUP limits.\", 500, responseString);\n }\n return responseString;\n })\n .then(function (r) {\n return JSON.parse(responseString);\n })\n .then(function (r) {\n return self.applyAdvancedContext(r);\n })\n .then(function (r) {\n return self.applyContext(r);\n })\n .then(function (r) {\n return self.reconstructComplexObjects(r);\n })\n .then(function (r) {\n return self.processPrefixedProperties(r, sparqlEndpoint);\n })\n .then(function (r) {\n return self.prepareResponse(r, requestParams);\n })\n .then(function (r) {\n return self.processModel(r);\n });\n\n };\n\n // Converts @type properties to string - Virtuoso bug fix\n this.fixRDFType = function(response) {\n if (!_.has(response, \"@graph\"))\n return response;\n\n var graph = response[\"@graph\"];\n _.each(response[\"@graph\"], function(item) {\n if (_.has(item, \"@type\")) {\n var type = item[\"@type\"];\n if (_.isArray(type)) {\n item[\"@type\"] = _.map(type, function(t) {\n if (_.isObject(t) && _.has(t, '@id')) {\n return t['@id'];\n } else {\n return t;\n }\n })\n }\n }\n });\n\n return response;\n };\n\n // Applies context to JSON-LD Virtuoso response using JSONLD library\n this.applyAdvancedContext = function(response) {\n var context = this.getAdvancedContext();\n if (!context) {\n return response;\n }\n\n response = self.fixRDFType(response);\n\n var p = jsonld.promises();\n return p.compact(response, this.getAdvancedContext(), config.queryAdapter.compactOptions)\n .then(function(response) {\n return self.fixJSONLDType(response);\n });\n };\n\n // Converts @type properties to array - jsonld bug fix\n this.fixJSONLDType = function(response) {\n if (!_.has(response, \"@graph\"))\n return response;\n\n var graph = response[\"@graph\"];\n _.each(response[\"@graph\"], function(item) {\n if (_.has(item, \"@type\") && !_.isArray(item[\"@type\"])) {\n item[\"@type\"] = [item[\"@type\"]];\n }\n });\n\n return response;\n };\n\n // Renames URIs as keys in objects with defined values\n this.applyContext = function(response) {\n var context = this.getContext();\n\n if (!context || !_.has(response, \"@graph\")) {\n return response;\n }\n\n function RenameKey(object ) {}\n\n context = _.invert(context);\n\n response[\"@graph\"] = _.map(response[\"@graph\"], function(object) {\n return _.mapKeys(object, function(value, originalKey) {\n if (_.has(context, originalKey)) {\n return context[originalKey];\n }\n return originalKey;\n });\n });\n\n return response;\n\n };\n\n // Converts list of response graph objects into one complex object based on @id\n this.reconstructComplexObjects = function(response) {\n\n if (!this.getReconstructComplexObjects()) // do not reconstruct\n return response;\n\n var objects = {};\n\n _.each(response[\"@graph\"], function(object) {\n objects[object[\"@id\"]] = {\n data: object,\n isLinked: false\n };\n });\n\n // find links among graph objects\n _.each(response[\"@graph\"], function(object) {\n var currentId = object['@id'];\n _.each(object, function(values, key) {\n if (key.indexOf(\"@\") == 0)\n return; // RDF-specific property\n _.each(values, function(value, index) {\n if (_.has(objects, value) && value != currentId) { // link to another object\n values[index] = objects[value].data;\n objects[value].isLinked = true;\n }\n else if (_.isObject(value) && value[\"@id\"] && _.has(objects, value[\"@id\"]) && value[\"@id\"] != currentId) {\n values[index] = objects[value[\"@id\"]].data;\n objects[value[\"@id\"]].isLinked = true;\n }\n });\n });\n });\n\n response[\"@graph\"] = [];\n\n // only include non-linked nodes in final response\n _.each(objects, function(object) {\n if (!object.isLinked)\n response[\"@graph\"].push(object.data);\n });\n\n return response;\n };\n\n // Applies data model to response\n this.processModel = function(response) {\n\n var model = this.getModel();\n\n if (!model) // do not apply model\n return response;\n\n var typeCheckers = {\n string: _.isString,\n number: _.isNumber,\n boolean: _.isBoolean,\n array: _.isArray,\n object: _.isPlainObject\n };\n\n var typeConverters = {\n string: function(v) { return String(v); },\n number: function(v) { return Number(v); },\n boolean: function(v) { return Boolean(v); },\n array: function(v) { return [v]; },\n object: function(v) { return { value: v }; }\n };\n\n function checkType(value, type) {\n if (!_.isFunction(typeCheckers[type])) {\n throw new Error(\"Invalid type of data provided in JSON-LD model: \" + type);\n }\n return(typeCheckers[type](value));\n }\n\n function processModelKey(key, spec, object) {\n if (!_.has(object, key)) {\n object[key] = spec[1];\n } else if (!checkType(object[key], spec[0])) {\n // basic converters\n if (spec[0] == 'array') {\n object[key] = typeConverters['array'](object[key]); // literal to array\n } else if (spec[0] == 'object') {\n object[key] = typeConverters['object'](object[key]); // literal to object\n } else if (checkType(object[key], 'array')) {\n if (object[key].length > 0) {\n object[key] = typeConverters[spec[0]](object[key][0]); // array to literal\n } else {\n object[key] = spec[1]; // default value\n }\n } else {\n object[key] = typeConverters[spec[0]](object[key]); // convert whatever it is remaining\n }\n }\n }\n\n function processModelPart(objects, model) {\n var keys = _.keys(model);\n _.forEach(objects, function(object) {\n _.forEach(keys, function(key) {\n if (_.isString(model[key][0])) {\n // processing key\n processModelKey(key, model[key], object);\n } else {\n // next level\n if (!_.isPlainObject(model[key][0])) {\n throw new Error(\"Invalid JSON-LD model specification for key: \" + key);\n }\n if (_.isArray(object[key])) {\n processModelPart(object[key], model[key][0]); // standard processing\n } else if (_.isPlainObject(object[key])) {\n processModelPart([object[key]], model[key][0]); // expand to array\n } else {\n // different value than expected or empty, replace with default value\n object[key] = model[key][1]; //\n }\n }\n });\n var trailingKeys = _.difference(_.keys(object), keys); // omit unwanted fields\n _.each(trailingKeys, function(key) {\n delete object[key];\n })\n })\n }\n\n processModelPart(response[\"@graph\"], model);\n\n return response;\n };\n\n // Shortens long URIs in defined properties\n this.processPrefixedProperties = function(response, sparqlEndpoint) {\n\n if (!this.getReplacePrefixes() || !_.isArray(response[\"@graph\"])) // do not apply prefixed properties\n return response;\n\n var deferred = Q.defer();\n\n prefixesManager.getReplacer(sparqlEndpoint)\n .then(function(replacer) {\n\n var processed = [];\n\n var prefixArray = function(objects, processed) {\n _.each(objects, function(obj) {\n if (_.isObject(obj)) {\n var newObj = {};\n processed.push(newObj);\n prefixObject(obj, newObj);\n } else {\n processed.push(obj); // scalar type\n }\n })\n };\n\n var prefixObject = function(obj, newObj) {\n _.each(obj, function(values, predicate) {\n if (predicate == '@id') {\n newObj['@id'] = replacer.contract(values);\n } else if (predicate == '@type') {\n if (_.isArray(values)) {\n newObj['@type'] = _.map(values, function (value) {\n if (_.isPlainObject(value)) {\n return { '@id': replacer.contract(value['@id']) }\n }\n return replacer.contract(value);\n });\n } else {\n newObj['@type'] = [ replacer.contract(values) ];\n }\n } else {\n if (!_.startsWith(predicate, '@')) {\n predicate = replacer.contract(predicate);\n }\n if (_.isArray(values)) {\n var newArray = [];\n newObj[predicate] = newArray;\n prefixArray(values, newArray);\n } else {\n newObj[predicate] = values;\n }\n }\n });\n };\n\n prefixArray(response['@graph'], processed);\n\n response[\"@graph\"] = processed;\n\n deferred.resolve(response);\n\n })\n .done();\n\n return deferred.promise;\n };\n}", "function showSPARQL() {\n\n\t// read selected type from selectlist\n\tvar loc = document.getElementById(\"formtypes\");\n\tformtype = loc.options[loc.selectedIndex].text;\n\n\tif (formtype == \"alle\") {\n\t\t// add query to form\n\t\td3.select(\"#query\").attr(\"value\", \"SELECT ?s ?p ?o WHERE {?s ?p ?o}\").html(\"SELECT ?s ?p ?o WHERE {?s ?p ?o}\");\n\t}\n\n\t// read matchin query from json\n\t$.getJSON(\"../json/\" + formtype + \".json\", function(json) {\n\t\tvar subjecttype = json.subjecttype;\n\n\t\t// TODO: read predicates from JSON and put them in the query\n\t\t// add query to form\n\t\td3.select(\"#query\").attr(\"value\", \"SELECT ?s WHERE {?s rdf:type \" + subjecttype + \"}\").html(\"SELECT ?s WHERE {?s rdf:type \" + subjecttype + \" }\");\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns index of first different element in two sorted arrays
function firstDiff(A, B) { for (var i = 0; i < Math.min(A.length, B.length); i++) { if (A[i] !== B[i]) { return i; } } return -1; }
[ "function getIndexOfFirstDifference(a, b, equal) {\n for (var i = 0; i < a.length && i < b.length; i++) {\n if (!equal(a[i], b[i])) {\n return i;\n }\n }\n return undefined;\n}", "function getIndexOfFirstDifference(a, b, equal) {\n for (let i = 0; i < a.length && i < b.length; i++) {\n if (!equal(a[i], b[i])) {\n return i;\n }\n }\n return undefined;\n }", "function findExtraIndex(arr1, arr2) {\n let index = 0;\n let left = 0;\n let right = arr2.length - 1;\n while (left <= right) {\n let mid = Math.floor((left + right) / 2);\n if (arr2[mid] === arr1[mid]) {\n left = mid + 1;\n } else {\n index = mid;\n right = mid - 1;\n }\n }\n return index;\n}", "function compareIndexValues(a, b) {\n if (a[1] === b[1]) {\n return 0;\n }\n else {\n return (a[1] > b[1]) ? -1 : 1;\n }\n}", "function indexOfDiffereces(a, b) {\n if (a === b) return -1;\n var\n i = 0,\n aLength = a.length,\n bLength = b.length\n ;\n while (i < aLength) {\n if (i < bLength && a[i] === b[i]) i++;\n else return i;\n }\n return i === bLength ? -1 : i;\n }", "function findMissing(arr1, arr2) {\n let res = 0;\n arr1.sort(function(a, b) {\n return a - b;\n })\n arr2.sort(function(a, b) {\n return a - b;\n })\n for (let i = 0; i < arr1.length; i++) {\n if (arr1[i] !== arr2[i]) {\n res = arr1[i];\n break;\n }\n }\n return res;\n\n}", "function nextElement(arr1, arr2){\n let solution = new Array(arr1.length).fill(-1)\n\n for(let i = 0; i<arr1.length; i++){\n let index = arr2.indexOf(arr1[i])\n\n for(let j=index; j<arr2.length; j++){\n if(arr2[j] > arr1[i]){\n solution[i] = arr2[j]\n break\n }\n }\n }\n\n return solution\n}", "function posCompare(a, b) {\n const yDiff = a[1] - b[1];\n if (yDiff !== 0) return yDiff;\n return a[0] - b[0];\n}", "function relativeCompareArray(first, second) {\n\t\tvar eq = true;\n\t\tfor (var i in first) {\n\t\t\tif (i >= second.length) {\n\t\t\t\t// exeed second array length, stop\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (first[i] !== second[i]) {\n\t\t\t\t// found different element, stop\n\t\t\t\teq = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn eq;\n\t}", "function arrayCompare(arr1, arr2) {\n arr1 = arr1.filter(onlyUnique);\n arr2 = arr2.filter(onlyUnique);\n let itemsInCommon = 0;\n for (let i = 0; i < arr1.length; i++) {\n if (arr2.indexOf(arr1[i]) != -1) itemsInCommon += 1;\n }\n return itemsInCommon;\n }", "function secondApproach(firstArray,secondArray,target){\n for(let i =0; i<firstArray.length;i++){\n let searchTarget = target - firstArray[i];\n let searchResult = doBinarySearch(secondArray,searchTarget); \n if(searchResult.success){\n return {searchResult,firstArrayIndex : i,firstArrayValue : firstArray[i]}\n }\n \n } \n\n}", "function compareArrays(array1, array2) {\n var len = Math.min(array1.length, array2.length),\n lengthDiff = Math.abs(array1.length - array2.length),\n diffs = 0,\n i;\n for (i = 0; i < len; i++) {\n if (~ ~array1[i] !== ~ ~array2[i]) {\n diffs++;\n }\n }\n return diffs + lengthDiff;\n }", "function findBoth (a, b) {\n\tif (a instanceof Array !==true || a.length === 0 || \n typeof a == 'undefined' || a == null || \n b instanceof Array !==true || b.length === 0 || \n typeof b == 'undefined' || b == null) {\n throw 'Invalid Input';\n }\n for (var i=0; i<a.length; i++) {\n if (typeof a[i] !== 'number' || a[i]%1 !== 0) {\n throw 'Invalid Input';\n }\n }\n for (var j=0; j<b.length; j++) {\n if (typeof b[j] !== 'number' || b[j]%1 !== 0) {\n throw 'Invalid Input';\n }\n }\n a.sort(function(a,b){return a-b});\n b.sort(function(a,b){return a-b});\n var result =[];\n\twhile (a.length>0 && b.length>0) {\n\t\tif (a[0]<b[0]) {\n\t\t\ta.shift();\n\t\t} else if (a[0]>b[0]) {\n\t\t\tb.shift();\n\t\t} else {\n\t\t\tresult.push(a.shift());\n\t\t\tb.shift();\n\t\t}\n\t}\n return result;\n}", "function compareArrays(array1, array2) {\n var len = Math.min(array1.length, array2.length),\n lengthDiff = Math.abs(array1.length - array2.length),\n diffs = 0,\n i;\n for (i = 0; i < len; i++) {\n if (~~array1[i] !== ~~array2[i]) {\n diffs++;\n }\n }\n return diffs + lengthDiff;\n }", "function smartInter(arrA, arrB) {\n var inter = [];\n for(var i = 0; i < arrA.length; i++) {\n for(var j = 0; j < arrB.length; j++) {\n if(arrA[i] == arrB[j] || $.contains(arrA[i], arrB[j])) {\n if(inter.indexOf(arrA[i]) < 0) {\n inter.push(arrA[i]);\n }\n }\n }\n }\n return inter;\n}", "static cmparray(a1, a2) {\n\t\tfor(var i = 0; i < a1.length; i++) {\n\t\t\tif (a1[i] > a2[i]) {\n\t\t\t\treturn 1;\n\t\t\t} else if (a1[i] < a2[i]) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}", "function compareArrays(array1, array2) {\n var len = Math.min(array1.length, array2.length),\n lengthDiff = Math.abs(array1.length - array2.length),\n diffs = 0,\n i;\n for (i = 0; i < len; i++) {\n if (~~array1[i] !== ~~array2[i]) {\n diffs++;\n }\n }\n return diffs + lengthDiff;\n }", "function smallestDifference(arrayOne, arrayTwo) {\n \n\t// sort arrays in place increasing order\n\tarrayOne.sort((a,b) => a - b);\n\tarrayTwo.sort((a,b) => a - b);\n\t\n\tlet pair = [];\n\t\n\t// use two pointers starting at begin of both arrays\n\tlet l = 0;\n\tlet r = 0;\n\t\n\t// create var to track smallestDiff\n\tlet smallestDiff = +Infinity;\n\t\n\t// loop through arrays until either empty\n\twhile (l < arrayOne.length && r < arrayTwo.length) {\n\t\tlet num1 = arrayOne[l];\n\t\tlet num2 = arrayTwo[r];\n\t\t\n\t\t// calculate absolute delta\n\t\tlet absDiff = Math.abs(num1 - num2);\n\t\t\n\t\t// exit if absolute delta == 0\n\t\tif (absDiff === 0) return [num1, num2];\n\t\t\n\t\t// update smallestDiff\n\t\tif (absDiff < smallestDiff) { \n\t\t\tsmallestDiff = absDiff;\n\t\t\tpair = [ num1, num2 ];\n\t\t}\n\t\t\n\t\t// increment pointer of smallest of two nums\n (num1 < num2) ? l++ : r++;\n\t}\n\t\n\treturn pair;\n}", "function findSmallestDifference(arr1, arr2) {\n\tarr1.sort((x,y) => x - y);\n\tarr2.sort((x,y) => x - y);\n\tlet point1 = arr1.length - 1;\n\tlet point2 = 0;\n\tlet point3 = arr1.length + arr2.length;\n\tlet min = Math.abs(arr1[point1] - arr2[0]);\n\n\tlet difference1 = Math.NEGATIVE_INFINITY;\n\tlet difference2 = Math.NEGATIVE_INFINITY;\n\twhile(point3 > 0) {\n\t\tdifference1 = Math.abs(arr1[point1] - arr2[point2 + 1]);\n\t\tdifference2 = Math.abs(arr1[point1 - 1] - arr2[point2]);\n\t\tconsole.log(difference1, difference2)\n\t\tif(difference1 < difference2 && min > difference1) {\n\t\t\tmin = difference1;\n\t\t\tpoint2++;\n\t\t} else if (difference2 < difference1 && min > difference2) {\n\t\t\tmin = difference2;\n\t\t\tpoint1--;\n\t\t} else {\n\t\t\treturn[arr1[point1], arr2[point2]]\n\t\t\tbreak;\n\t\t}\n\t\tpoint3--;\n\t} \n\treturn min;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }