query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Sorters Update waitingQueue based on Priority NonPreemptive & Preemptive
sortPriority() { this.waitingQueue = this.waitingQueue.sort(function(jobA, jobB) { if(jobA.getPriorityLevel() > jobB.getPriorityLevel()) return -1; if(jobA.getPriorityLevel() < jobB.getPriorityLevel()) return 1; return 0; }); }
[ "sortShortest() {\n this.waitingQueue = this.waitingQueue.sort(function(jobA, jobB) {\n if(jobA.getBurstsRemaining() < jobB.getBurstsRemaining)\n return -1;\n if(jobA.getBurstsRemaining() > jobB.getBurstsRemaining())\n return 1;\n return 0;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the id of a file in this directory with the given name
getFileId(name) { let matches = this.entries.filter(e => e.name === name); if (matches.length > 0) { return matches[0]; } else { return null; } }
[ "function getFileID(filepath){\r\n for(i in files){\r\n if(files[i].path == filepath) return files[i].id;\r\n }\r\n return undefined;\r\n}", "async function pathToId(path) {\n\tvar components = path.split(\"/\");\n\tvar folderName = components[components.length-2];\n\tvar folder = await searchFol...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
main function to build any dive segment
function build_dive_segment(levels_segment_arr , levels_mix_segment_arr){ var rate_asc = document.getElementById("opt_rate_asc"); var rate_asc_idx = rate_asc.options[rate_asc.selectedIndex].value; var rate_dsc = document.getElementById("opt_rate_dsc"); var rate_dsc_idx = rate_dsc.options[rate_dsc.selectedInde...
[ "function SegmentBase() {\n}", "function doSegmentDemo() {\n appendHeading(\"Segment\");\n let qr;\n let segs;\n const QrCode = qrcodegen.QrCode; // Abbreviation\n const QrSegment = qrcodegen.QrSegment; // Abbreviation\n // Illustration \"silver\"\n const silver0 =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the preemit diagnostics.
getPreEmitDiagnostics(sourceFile) { const compilerDiagnostics = typescript_1.ts.getPreEmitDiagnostics(this.program.compilerObject, sourceFile == null ? undefined : sourceFile.compilerNode); return compilerDiagnostics.map(d => this.compilerFactory.getDiagnostic(d)); }
[ "createDiagnostics() {\r\n if (!this.isStmRunning())\r\n return;\r\n let diagnostics = [];\r\n for (let error of this.stm.getErrors()) {\r\n diagnostics.push({ message: AnnotatedText_1.textToDisplayString(error.message),\r\n range: error.range,\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
METHOD TO FIND SIZE IN SIZES
getSize(name) { let size = this._data.sizes.find(s => s.name === name); return size; // for (let i = 0; i < this._data.sizes.length; i++) { // if (this._data.sizes[i].name === name) { // return this._data.sizes[i]; // } // } }
[ "function size(found) {\n return sizes[found] || 1;\n }", "function getSize() {\n return this.size;\n}", "allSizes() {\n return _.chain(this.poms).pluck('sizes').first().value();\n }", "definedSizes() {\n const { infoResponse } = this.props;\n if (!(infoResponse && infoResponse.json &...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect event to toggle auto update y axis
_initAutoUpdateYCheckbox(startValue){ const graph = this; $(this.htmlIds.yAutoUpdate).click(function(){ graph.autoUpdateYAxis = this.checked; }); this.autoUpdateYAxis = startValue; $(this.htmlIds.yAutoUpdate).prop('checked', startValue); }
[ "function onYAxisChange(value){\n\n}", "function updateMainY(axis) {\n // handle dynamic data\n plottingApp.editSeries = axis;\n $(\"#updateEdit\").click();\n }", "function updateYAxis() {\n yScale.domain(yState);\n yAxisG.transition()\n .ease(d3.easePoly)\n .duration(750)\n .call(d3.axisLe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables, or disables, "dark mode" of the web page. Uses a cookie to remember user's choice.
function toggleDarkMode() { var option = readCookie("darkmode"); var optionReverse = "true"; var stylesheet = document.getElementById("sitestyle"); var styleName = "/static/groundfloor/css/dark"; if (option === "true") { optionReverse = "false"; styleName = "/static/groundfloor/css/...
[ "function toggleDarkMode() {\n if(getCookie(\"darkMode\") == \"false\"){\n setCookie(\"darkMode\", \"true\", 43200);\n } else {\n setCookie(\"darkMode\", \"false\", 43200);\n }\n preSetStyle();\n postSetStyle();\n}", "function enableDarkMode() {\n btnDarkMode.checked = true;\n docum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_populateModifier If the destination contains a modifier start and end, copy and paste it.
_populateModifier(srcSelector, destSelector, staff) { // If this is the ending point of a staff modifier, paste the modifier const mod = this._findPlacedModifier(srcSelector); if (mod) { mod.endSelector = JSON.parse(JSON.stringify(destSelector)); mod.attrs.id = VF.Element.newID(); staff.ad...
[ "_populateModifier(srcSelector, destSelector, staff) {\n const mod = this._findPlacedModifier(srcSelector);\n if (mod && this.score) {\n // Don't copy modifiers that cross staff boundaries outside the source staff b/c it's not clear what\n // the dest staff should be\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Default Configurator for most Substance apps If you need appspecific API's just extend and configure your custom configurator.
function Configurator() { AbstractConfigurator.call(this); }
[ "function Configurator (options, context) {\n this.options = options;\n this.context = context;\n}", "constructor(configType = '') {\n if (configType === 'heroku')\n this.config = HerokuAppConfig;\n else\n this.config = TestAppConfig;\n\n\n this.init();\n }", "static Configurators() {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
= Description Starts polling an app instance (and its components). = Parameters +_appId+:: The unique id of the app. +_priority+:: The app priority.
startApp(_appId, _priority) { if (typeof _priority === 'undefined') { _priority = this.defaultPriority; } this.__appPriorities[_appId] = _priority; this.busyApps[_appId] = false; }
[ "reniceApp(_appId, _priority) {\n this.__appPriorities[_appId] = _priority;\n }", "addApp(_app, _priority) {\n let _appId;\n if (this.freeAppIds.length > 0) {\n _appId = this.freeAppIds.shift();\n this.__apps[_appId] = _app;\n }\n else {\n this.__apps.push(_app);\n _appId = thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an array containing the order of probabilites to an array containing the order of probabilites and a corresponding abstract configuration. ['a','b','c',...] > [['a','0010'], ['b','1020'], ['c','2010'],...]
function convert(order, stimuli){ /* Since we ordered our stimuli alphabetically, all a's range from 0-7, b's from 8-15, and c's from 16-23. Critical for probabilties recieved from order. */ var a=0, b=8, c=16; var temp = []; for (var i=0; i<experiment.stimuli; i++){ var stim = order.pop(); if (stim === "a"...
[ "function chooseArr(options, probstr) {\n var probs = probArr(options, probstr);\n var choose_array = [];\n var outdex;\n for (var i = 0; i < options.length; i++) {\n outdex = probs[i];\n while (outdex > 0) {\n choose_array.push(options[i]);\n outdex--;\n }\n }\n return choose_array;\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is called once the Google Data JavaScript library has been loaded. It creates a new AnalyticsService object, adds a click handler to the authentication button and updates the button text depending on the status.
function init() { myService = new google.gdata.analytics.AnalyticsService('gaExportAPI_acctSample_v2.0'); scope = 'https://www.google.com/analytics/feeds'; var button = document.getElementById('_ga_authButton'); // Add a click handler to the Authentication button. button.onclick = function() { // Test if...
[ "function init() {\n myService = new google.gdata.analytics.AnalyticsService('charts_sample');\n scope = 'https://www.google.com/analytics/feeds';\n var button = document.getElementById('authButton');\n\n // Add a click handler to the Authentication button.\n button.onclick = function() {\n // Test if the u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the string representation of the point.
toString() { return `${Point.name} [x=${this.x},y=${this.y}]`; }
[ "toString() {\n return `${Point.name} [x=${this.x},y=${this.y}]`;\n }", "function pointToString(p) {\n const rv = pointToBigInt(p).toString();\n gPointStrings.set(rv, p);\n return rv;\n}", "function getPointString(tileImagePoint) {\n\tvar x = tileImagePoint.x,\n\t\ty = tileImagePoint.y,\n\t\tz = ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads CMI data from a JSON object.
function loadFromJSON(json, CMIElement) { if (!_self.isNotInitialized()) { console.error("loadFromJSON can only be called before the call to LMSInitialize."); return; } CMIElement = CMIElement || "cmi"; for (var key in json) { if (json.hasOwnProperty(key) && json[key]) ...
[ "function loadFromJSON(json, CMIElement) {\n if (!_self.isNotInitialized()) {\n console.error(\"loadFromJSON can only be called before the call to Initialize.\");\n return;\n }\n\n CMIElement = CMIElement || \"cmi\";\n\n for (var key in json) {\n if (json.hasOwnProperty(key)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
grab the first heading and if it is just "Name" then try to find the actual function the document is talking about
function findMainHeading({ headings, rawMarkdownBody }) { const firstHeading = first(headings).value if (firstHeading !== 'Name') { return firstHeading } // get the first paragraph after until a dash which is where the definition starts and them function name ends return rawMarkdownBody.split('# Name')[...
[ "function parseNameSectionFunctions() {\n var functionNames = [];\n var numberOfFunctionsu32 = readU32();\n var numbeOfFunctions = numberOfFunctionsu32.value;\n eatBytes(numberOfFunctionsu32.nextIndex);\n\n for (var i = 0; i < numbeOfFunctions; i++) {\n var indexu32 = readU32();\n var index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to generate random grid
function randomGrid() { if (generate) return const randGrid = new Array(cols).fill(null) .map(() => new Array(rows).fill(null) .map(() => Math.floor(Math.random() * 2))); setGrid(randGrid) genCount.current = 0 }
[ "function randomCells() {\n setGen(0);\n setCells(createGrid(60, 60, true).cells);\n setTranslate({translateX:0,translateY:0});\n setSize(10);\n }", "function generateRandomWorld(n) {\n let grid = [];\n for (let i = 0; i < n; i++) {\n let line = [];\n for (let j = 0; j < n; j++) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that loads the database table, displays the table in the console using easytable npm, and starts the inquirer npm
function loadDBTable() { connection.query('SELECT * FROM products', function(err, res) { if (err) throw err; tablePrint(res); inquirerStart(); }); }
[ "function showTable() {\n connection.query(\"SELECT * FROM products\", function (err, results) {\n if (err) throw err;\n console.log(\"\\n\");\n console.table(results);\n })\n inquirer.prompt([\n {\n type: \"confirm\",\n message: \"PRESS ENTER WHEN YOU ARE FINISHED LOOKING AT OUR INVENTORY....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Conditionally include organisation finance questions based on the organisation start date. New organisations will not have produced annual accounts yet so will not have this information.
function stepOrganisationFinances() { return new Step({ title: localise({ en: 'Organisation finances', cy: 'Cyllid y sefydliad', }), fieldsets: [ { legend: localise({ en: 'Organisation...
[ "function isUserInExperiment() {\n return current_date <= ( signup_date + eligibility_period );\n}", "function includeIfOrganisationType(type, fields) {\n const organisationType = get('organisationType')(data);\n return organisationType === type ? fields : [];\n }", "function toggleCalendar(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imprimir de Mayor a Menor
imprimirMayorAMenor() { this.vehiculos.sort((v1, v2) => { return v2.precio - v1.precio }) console.log('Vehiculos ordenados de mayor a menor:') this.vehiculos.forEach(vehiculo => { console.log(`${vehiculo.marca} ${vehiculo.modelo}`) }); }
[ "function notaMayorMenor(){\n mayorMenor(estudiantes);\n}", "moverAbajo(){\n this.salaActual.jugador = false;\n this.salaActual = this.salaActual.abajo;\n this.salaActual.entradaAnteriorSala = posicionSala.abajo;\n this.salaActual.jugador = true;\n\n }", "function actionOnClick...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TradeExists returns true when trade with given ID exists in world state.
async TradeExists(ctx, id) { const tradeJSON = await ctx.stub.getState(id); return tradeJSON && tradeJSON.length > 0; }
[ "exists(id) {\n return this.entries.hasOwnProperty(id);\n }", "async OrderExists(ctx, id) {\n const OrderJSON = await ctx.stub.getState(id);\n return OrderJSON && OrderJSON.length > 0;\n }", "async HiringContractExists(ctx, id) {\n const hireJSON = await ctx.stub.getState(id);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new ApiKey. The integration key.
function ApiKey() { _classCallCheck(this, ApiKey); ApiKey.initialize(this); }
[ "constructor() { \n \n ApiKey.initialize(this);\n }", "function createApiKey() {\n return client.newKeys.create()\n .then(newKey => newKey)\n .catch((err) => { throw new Error(err.details) });\n }", "function createApiKey() {\n return client.newKeys.create()\n .then(ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the info from an SFax ping, puts together an API request to them, and process the full info for a given fax
function get_barcode_info(fax_id,api_key,token){ var url = "https://api.sfaxme.com/api/InboundFaxInfo?token=" + encodeURIComponent(token) + "&apikey=" + encodeURIComponent(api_key) + "&FaxId=" + encodeURIComponent(fax_id) try{ var res = JSON.parse(UrlFetchApp.fetch(url).getContentText()) return extract_fax_...
[ "function extract_fax_info(sfax_response_obj){\n //var sfax_response_obj = JSON.parse('{\"inboundFaxItem\":{\"FaxId\":\"2190401201000980691\",\"Pages\":\"4\",\"ToFaxNumber\":\"18557916085\",\"FromFaxNumber\":\"5302731333\",\"FromCSID\":\"2731333\",\"FaxDateUtc\":\"4/1/2019 8:10:18 PM\",\"FaxSuccess\":\"1\",\"Barco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the cart is empty
isEmpty(cart) { return Common.emptyObject(cart); }
[ "function isShoppingCartEmpty() {\n if (shoppingCart.length == 0) {\n return true;\n }\n\n return false;\n}", "isCartEmpty() {\n //check if user active\n if (this.navService.isUserActive) {\n //check user items\n return !!this.navService.items.length;\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert a pitch period, and determine how much input to copy directly.
function insertPitchPeriod( samples, position, speed, period) { var newSamples; if(speed < 0.5) { newSamples = Math.floor(period*speed/(1.0 - speed)); } else { newSamples = period; remainingInputToCopy = Math.fl...
[ "function skipPitchPeriod(\r\n samples,\r\n position,\r\n speed,\r\n period)\r\n {\r\n var newSamples;\r\n\r\n if(speed >= 2.0) {\r\n newSamples = Math.floor(period/(speed - 1.0));\r\n } else {\r\n newSamples = period;\r\n remainin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add Stats Object to the Scene
function addStatsObject() { stats = new Stats(); stats.setMode(0); stats.domElement.style.position = 'absolute'; stats.domElement.style.left = '0px'; stats.domElement.style.top = '0px'; document.body.appendChild(stats.domElement); }
[ "function addStatsObject() {\n stats = new Stats();\n stats.setMode(0);\n stats.domElement.style.position = 'absolute';\n stats.domElement.style.left = '0px';\n stats.domElement.style.top = '0px';\n document.body.appendChild( stats.domElement );\n }", "function add_sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle onclick for option 1 button
function doOption1Click() { //Update vote total for this button doVoteTotal("optRadio1"); }
[ "function clickOptiontoSelect(){\n\n}", "function doOption2Click()\r\n{\r\n\t//Update vote total for this button\r\n\tdoVoteTotal(\"optRadio2\");\r\n}", "function Clickfunction(o) {\n let option = document.getElementById(o);\n\n if (o == \"option1\") {\n option.addEventListener(\"click\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles when bottom line animation ends, performing actions that must wait for animations to finish.
handleBottomLineAnimationEnd() { // We need to wait for the bottom line to be entirely transparent // before removing the class. If we do not, we see the line start to // scale down before disappearing if (!this.isFocused_ && this.bottomLine_) { this.bottomLine_.deactivate(); } }
[ "handleBottomLineAnimationEnd() {\n const bottomLine = this.adapter_.getBottomLineFoundation();\n // We need to wait for the bottom line to be entirely transparent\n // before removing the class. If we do not, we see the line start to\n // scale down before disappearing\n if (!this.isFocused_ && bott...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
enableEnter is accessible in the whole page scope.
function enableEnter(event) { if (event.keyCode == 13) { event.preventDefault(); // ezpConsole.partOverride.retrieveParts(); console.log('test gbl'); // split_pane_jsDES(event); // spl_false; // split_pane_js(false); // console.log(spl_false); split_pa...
[ "_enableEnterHandling() {\n\t\tconst editor = this.editor;\n\t\tconst model = editor.model;\n\t\tconst enterCommand = editor.commands.get( 'enter' );\n\n\t\tif ( !enterCommand ) {\n\t\t\treturn;\n\t\t}\n\n\t\tenterCommand.on( 'execute', () => {\n\t\t\tconst position = model.document.selection.getFirstPosition();\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getters and Setters for "state" of the addon stored in the background.
function _setStateOfAddon(key,value){ _state = value; }
[ "function UIState() {}", "get state() { return this._state; }", "function setExtensionState() {\n if ( isDisabled )\n removePeriodicChange();\n else\n initPeriodicChange();\n\n updateBrowserActionIcon();\n}", "function getState() {\n return state;\n }", "_updateItemS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if mobile version is being used, makes sure desktop items are hidden and mobile items are shown
function mobileSetUp () { $('.hiddenMobile').hide() $('.viewMobile').show() }
[ "function desktopSetUp () {\n $('.hiddenMobile').show()\n $('.viewMobile').hide()\n }", "function desktopSetUp()\n {\n $('.hiddenMobile').show();\n $('.viewMobile').hide();\n }", "function mobileToDesktop() {\n if (window.innerWidth > 700) {\n if (mobile_links.style....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls the getSites() function just before the component is mounted.
componentWillMount() { this.getSites(); }
[ "beforeMount() {\n this.service = new PipelinesService(this.endpoint);\n\n this.fetchPipelines();\n\n eventHub.$on('refreshPipelines', this.fetchPipelines);\n }", "function init() {\n websiteService.findAllWebsitesForUser(vm.userId)\n .then(function (websites) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parameters textNodeArray: An array of nodes in which the text to be wrapped. wrapElem: The element in which the matched string to be wrapped. matchesArray: An array of matches results to corresponding nodes in textNodeArray. Return values countArray: An array of the amount of matches.
async function wrapMatchedTextInNodesWithMatches(textNodeArray, wrapElem, matchesArray) { return Promise.all(textNodeArray.map((textNode, index) => { return wrapMatchedTextInNodeWithMatches(textNode, wrapElem, matchesArray[index]); })); }
[ "async function wrapMatchedTextInNodeWithMatches(textNode, wrapElem, matches) {\n return new Promise((resolve, _) => {\n let newNodes = [];\n let text = textNode.data;\n let lastIndex = 0;\n for (let match of matches) {\n if (lastIndex < match.index) {\n let ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executed when mouse leaves the editor container element
function onContainerMouseleave(e) { // publish fileEditor.hDev.publish('mouse-position-change', { f: fileEditor.filepath, p: {}, c: null, astNode: false }); }
[ "function on_mouse_leave() {}", "function mouseLeave(e){\n const container = e.target.getStage().container();\n container.style.cursor = \"default\";\n }", "_afterMouseLeaveHook() { }", "mouseLeave() {\n this.sendAction();\n }", "function _handleFrameMouseOut() {\n\t\t// Hide the highli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates through children that are "valid elements". The provided forEachFunc(child, index) will be called for each leaf child with the index reflecting the position relative to "valid components".
function forEach(children, func) { var index = 0; __WEBPACK_IMPORTED_MODULE_0_react___default.a.Children.forEach(children, function (child) { if (__WEBPACK_IMPORTED_MODULE_0_react___default.a.isValidElement(child)) func(child, index++); }); }
[ "function forEach(children, func) {\n var index = 0;\n react_default.a.Children.forEach(children, function (child) {\n if (react_default.a.isValidElement(child)) func(child, index++);\n });\n}", "function forEach(children, func) {\n var index = 0;\n react__WEBPACK_IMPORTED_MODULE_0___default.a.Children.fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter down/up to tasks containing text entered by the user
function filterTasks(e) { const tasks = Array.from(taskList.children); // Only perform filtering if the task list is populated with 1+ task items if (tasks.length > 0) { if (e.target.value !== ''){ // Loop through each task in the list, showing only those tasks with titles containing // the text ...
[ "function filterTasks(e) {\n let filterTasks = [];\n let keyword = filter.value.toLowerCase();\n //tasks.filter((keyword) => keyword.toLowerCase().indexOf(query.toLowerCase()) !== -1);\n tasks.forEach((task) => {\n if (task.name.indexOf(keyword)) {\n filterTasks.add(task);\n }\n });\n displayText(f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets box coordinates [ x, y, width, height ]
getBoxCoords(_id) { const [x, y] = this.getPosition(_id); const [w, h] = this.getSize(_id); return [x, y, w, h]; }
[ "function boxPosition(x, y){\n x = parseInt(x);\n y = parseInt(y);\n var startPoint = [x, y];\n return startPoint;\n}", "function getBox(o){return{xMin:o.position.x,xMax:o.position.x+o.width,yMin:o.position.y,yMax:o.position.y+o.height};}", "getVisibleBoxCoords(_id, _noOwnScroll) {\n const [x, y] = this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load all files inside a given directory and add them to the list.
function loadDir(dir) { var elements = dir.getFiles(); for(var i in elements) { allElements.push(elements[i]); } }
[ "function list_files (dir, callback) {\n //console.log('list_files:', dir);\n fs.readdir(path.join(root, dir), function (err, files) {\n if (err) {\n console.error('error reading directory ' + path.join(root, dir));\n callback(err);\n }\n if (files.length === 0) {\n callbac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A cmp function for determining which segments should take visual priority DOES NOT WORK ON INVERTED BACKGROUND EVENTS because they have no eventStartMS/eventDurationMS
function compareSegs(seg1, seg2) { return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1) ...
[ "function segmentCompare(a, b) {\n\t\treturn _segmentCompare(a, b) // sort by dimension\n\t\t\t|| (a.event.start - b.event.start) // if a tie, sort by event start date\n\t\t\t|| (a.event.title || \"\").localeCompare(b.event.title) // if a tie, sort by event title\n\t}", "function compareSegs(seg1, seg2) {\n\tretu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If make "transform"(x/y/scaleX/scaleY/orient/originX/originY) transition between two path elements that have different hierarchy, before we retrieve the "from" props, we have to calculate the local transition of the "oldPath" based on the parent of the "newPath". At present, the case only happend in "morphing". Without...
function calcOldElLocalTransformBasedOnNewElParent(oldEl, newEl) { if (!oldEl || oldEl === newEl || oldEl.parent === newEl.parent) { return oldEl; } // Not sure oldEl is rendered (may have "lazyUpdate"), // so always call `getComputedTransform`. var tmpM = tmpTransformable.trans...
[ "function calcOldElLocalTransformBasedOnNewElParent(oldEl, newEl) {\n if (!oldEl || oldEl === newEl || oldEl.parent === newEl.parent) {\n return oldEl;\n } // Not sure oldEl is rendered (may have \"lazyUpdate\"),\n // so always call `getComputedTransform`.\n\n\n var tmpM = tmpTransformable.transform || (tmpT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show panel of artifact
function showArtifactPanel() { clear() this.style.background = '#8ed41f'; artifact_panel.style.display = 'block'; gId('textarea_artifact').focus(); }
[ "showPanel() {\n if (this._isDisposed) {\n return;\n }\n this._onAction.emit('show-panel');\n }", "function show() {\n return {\n type: actionTypes_1.default.ShowPanel,\n showPanel: true\n };\n}", "show_project_panel_research(){\n thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will open the modal that will show the batch delete confirm message
function openBatchDeleteModal() { var deleteObjects = [] ctrl.checkBox.forEach(function(testcase, index){ if(!ctrl.showError){ if(testcase){ deleteObjects.push(ctrl.data.testcases[index].name) } } ...
[ "function openBatchDeleteModal() {\n var deleteObjects = []\n ctrl.checkBox.forEach(function(project, index){\n if(!ctrl.showError){\n if(project){\n deleteObjects.push(ctrl.data.projects[index].name)\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change coin value up or down
changeValue(dir, coin) { if (dir === 1) { this.props.incrementValue(coin); } else { this.props.decrementValue(coin); } }
[ "gainTwoCoins() {\n this.coins += 2;\n }", "function coinClick(number){\n\tif(clickUpgrades >= 1){\n\tcoins = coins + (number * (clickUpgrades * 2));\n\t} else {\n\tcoins = coins + number\n\t};\n\tdocument.getElementById(\"coins\").innerHTML = coins;\n}", "gainOneCoin() {\n this.coins += 1;\n }", "gai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handleSocketConnect() Called by ServerComms.js file to allow the panel to init itself once the socket has been established. Intention is to allow panel to update its state from the server
function handleSocketConnect() { setPanelStatus("Panel Ready"); var panelBackground = svgDocument.getElementById("panelBackground"); if(panelBackground != null) { setStyleSubAttribute(panelBackground, "fill", connectedBackgroundColor); } // Now that we are connected, try to upd...
[ "connectToSocket() {\n\n\t\t//return;\n\n\t\tif (server.socketConnection == true) {\n\t\t\treturn;\n\t\t}\n\n\t\tserver.socketConnection = true;\n\n\t\tcl(\"setting up socketIO\");\n\t\tvar socket = io('https://www.doentry.com/')\n\n\t\tsocket.on('realTimeSyncStarted', function(data){\n\t\t\tcl(\"Connected to socke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns if a given user has a game on their list Returns a Promise
async function hasGame(username, game_name) { // Get the game ID var game = await gamesdb.get(game_name); var game_id = game.id; // Check if the user has the game var query = { username: username, games: { $elemMatch: { $eq: game_id } } }; return await userModel.exists...
[ "static isGameUser(user, game) {\n return new Promise((resolve, reject) => {\n this.findAll(\"game\", game)\n .then((gameUsers) => {\n if (gameUsers.length === 0) { \n return resolve(false); \n }\n\n gameUsers.map(gameUser => {\n if(gameUser.user === u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get all beer Events
function getBeerEvents() { $scope.beerEvents = []; beeroundService.getBreweryEvent($rootScope.userSettings).then(result => { result.map(event => { if(event.start > $scope.today){ $scope.beerEvents.push(event) } }); }); }
[ "async Events_all() {\n let uri = \"type=events&param=list\";\n return await this.domoticzCall(uri);\n }", "function getAllEvents() {\n var request = gapi.client.calendar.events.list({\n 'calendarId': CALENDAR_ID,\n 'timeMin': (new Date(2016, 1, 4)).toISOString(),\n// ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implement a method to replace all spaces with "%20";
function replacespcaes(str) { return str.replace(" ", "%20") }
[ "function replaceSpaceFunny(str) {\r\n\treturn str.replace(/ /gi, \"%20\");\r\n}", "function urlify(string){\n return string.replaceAll(\" \", \"%20\");\n }", "function URLify(input) {\r\n return input.replace(/\\s/g, \"%20\");\r\n}", "function replaceWhitespaceRegex(str) {\n return str.replace(/\\s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function for setting up the year slider, required by JQueryUI to attach handlers also sets up the play button used for stepping through the available years of the data set
function setYearSlider() { var handleA = $(".year-rate-slider"); var slider = $('.year-slider').slider({ create: function (e, ui) { handleA.text(2000); }, slide: function (e, ui) { handleA.text(ui.value); year = ui.value; applyFilter() ...
[ "function initYearSlider() {\n\n // Continually update the label...\n $(\"#year-slider\").slider().on('change', function (event) {\n if (event.value != $(\"#year-value\").text()) {\n $(\"#year-value\").text(event.value);\n index.update();\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(Very) Rudementary XML parser for getting a specified attribute value of given XML tag (This has to be done as there is no 'document' object in this Javascript environment)
function getXmlAttrVal(xml, tag, attrName) { var re = new RegExp('<' + tag + '(\\s+|\\s[^>]+\\s)' + attrName + '\\s*=\\s*"([^"]+)"[^>]*\/>', 'im'); var parts = re.exec(xml); if (parts && parts.length == 3) return decodeXML(parts[2]); else return ''; }
[ "function getXmlAttrVal(xml, tag, attrName) {\n\tvar re = new RegExp('<' + tag + '(\\\\s+|\\\\s[^>]+\\\\s)' + attrName + '\\\\s*=\\\\s*\"([^\"]+)\"[^>]*\\/>', 'im');\n\tvar parts = re.exec(xml);\n\n\tif (parts && parts.length == 3)\n\t\treturn parts[2];\n\telse\n\t\treturn '';\n}", "function getAttribute(tag, att...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the current metrics to the logger.
logMetrics() { logger.info(`# of files indexed: ${this._filesIndexed}`); logger.info(`# of directories indexed: ${this._directoriesIndexed}`); logger.info(`# of unknown files: ${this._unknownCount}`); const endTimer = process.hrtime(this._startTimer); logger.info(`Execution time...
[ "function saveAll() {\n metrics.keys().forEach(function (key) {\n save(key, metrics.get(key).values());\n });\n }", "saveMeasurements() {\n this.exportToJsonFile(this.log);\n }", "function save() {\n var now = Date.now();\n var recentLog = {};\n Object.keys(timelog.recentLog).fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========= RefreshDatarowItem ================ PR20200816 PR20200930 PR20210621 PR20220304 PR20230104
function RefreshDatarowItem(tblName, field_setting, update_dict, data_rows) { console.log(" --- RefreshDatarowItem ---"); //console.log("tblName", tblName); console.log("field_setting", field_setting); console.log("update_dict", update_dict); console.log("update_dict.err_fields"...
[ "function RefreshDatarowItem(tblName, field_setting, data_rows, update_dict) {\n console.log(\" --- RefreshDatarowItem ---\");\n //console.log(\"tblName\", tblName);\n console.log(\"update_dict\", update_dict);\n\n if(!isEmpty(update_dict)){\n const field_names = field_settin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add selected users to the array
function addToArrUsr(){ selectedUsers.length = 0; [].forEach.call(users,function (user) { const selectStatus = user.querySelector('span'); if (selectStatus.classList.contains('user-select')) { selectedUsers.push(selectStatus.innerHTML); } }); return selectedUsers; }
[ "function addSelectedUser(user) {\n vm.selected.push(user);\n }", "function updateUserSelect(){\n\t$(TO_USER_SELECT).empty();\n\tfor(var index in users){\n\t\t$(TO_USER_SELECT).append(createUserRow(users[index]));\n\t}\n}", "function userSelected(user){\n selectedUsers.push(user)\n updateSelecte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Highlight and unhighlight page numbers in pagination Unhighlight the currently highlighted page link Highlight the page link specified by parameter pageNum
function setActivePageNumber( paginationUL, pageNum ) { let link, newClass; for ( let pageLI of paginationUL.children ) { link = pageLI.querySelector('a'); newClass = ''; // un-highlight currently highlighted page# (maybe) if ( link.className === 'active' ) newClass = ''; // highlight the page# ...
[ "function setActivePaginationLink(pageNum){\n $('ul.pagination a').removeClass('active');\n $('ul.pagination a').eq(pageNum - 1).addClass('active');\n}", "function highlightPageNumber(pageNo) {\n angular.forEach(angular.element('#pager li'), function(li) {\n if (angular.element(li).tex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the delete click, identifies item to delete using id Could be added to deleteTask function
function handleDelete() { console.log('delete click'); taskToDelete = $(this).data("id"); deleteTask(taskToDelete); }
[ "function handleDeleteTaskClicked() {\n var taskId = getElementTaskId(this);\n sendTaskDeletion(taskId);\n}", "function deleteHandler() {\n console.log(\"clicked delete button in tasks\");\n deleteTask($(this).data(\"id\"))\n} // end deleteHandler", "function deleteButtonClicked(event)\n{\n const...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
David Eberly's algorithm for finding a bridge between hole and outer polygon
static findHoleBridge(hole, outerNode) { var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; // find a segment intersected by a ray from the hole's leftmost point to the left; // segment's endpoint with lesser x will be potential connection point do { if (hy <= p....
[ "function findHoleBridge( hole, outerNode ) {\n \n var p = outerNode,\n hx = hole.x,\n hy = hole.y,\n qx = - Infinity,\n m;\n \n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Drops all the connections from the channel, removes the channel
close() { // Remove the channel from all its connections this.connections.forEach((connection) => { this.unbind(connection); }); // Remove the channel from the host this._host._channels.delete(this._name); // Emit close event this.emit('close'); }
[ "clearChannels() {\n for (let channel of this.channels) {\n channel.deleteChannel();\n }\n }", "async disconnect() {\n if (this._channel) await this._channel.close();\n if (this._confirmChannel) await this._confirmChannel.close();\n if (this._connection){ \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to trigger a outgoing handler for every buffer in outgoing. Stop when concurrency reaches.
async triggerOutgoingHandlers() { let buffer; do { if (this.executingOutgoingHandlers >= this.concurrency) { return; } buffer = this.outgoing.shift(); if (buffer) { this.triggerOutgoingHandler(buffer); } ...
[ "async triggerOutgoingHandler(buffer) {\n const bufferLength = buffer.size;\n this.executingOutgoingHandlers++;\n this.offset += bufferLength;\n try {\n await this.outgoingHandler(() => buffer.getReadableStream(), bufferLength, this.offset - bufferLength);\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deserialize a binary message to a Kernel Message.
function deserializeBinary(buf) { var data = new DataView(buf); // read the header: 1 + nbufs 32b integers var nbufs = data.getUint32(0); var offsets = []; if (nbufs < 2) { throw new Error('Invalid incoming Kernel Message'); } for (var i = 1; i <= nbufs; i++) { offsets.push(d...
[ "function deserializeBinary(buf) {\n let data = new DataView(buf);\n // read the header: 1 + nbufs 32b integers\n let nbufs = data.getUint32(0);\n let offsets = [];\n if (nbufs < 2) {\n throw new Error('Invalid incoming Kernel Message');\n }\n for (let i = 1; i <= nbufs; i++) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current transaction index (used for testing)
getCurrentTransactionIndex() { return this.currentTransactionIndex; }
[ "function getIndex() {\n return internal.index;\n }", "function getActiveIndex() {\n return parseInt(config.active_index);\n }", "function returnIndex() {\n\t return index;\n\t }", "function getActiveIndex() {\n return parseInt(_config2.default.active_index);\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Free Available Agent from DB;
function getFreeAvailableAgent(mclient, role, depts, calltransfer, client, mediatype, customerWebValueCode) { var dbobj = dbinterface.initialize(); console.log("Getting value in getFreeAvailableAgent" + customerWebValueCode); var conn = dbinterface.connectDB(dbobj, customerWebValueCode); var str; i...
[ "async getFreeAgents() {\n try {\n const results = await this.makeAPIrequest(this.freeAgents());\n return results.fantasy_content.league.players;\n } catch (err) {\n this.handleError(err, \"getFreeAgents\");\n }\n }", "getPlayerDetailsByFreeAgentPromise(){\n return this.GetPromise(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display Podcasts by Filter
function displayPodcasts(filter) { $.map(filter, function(x, i) { var podcast_id = x.podcast_id; var podcast_category = x.podcast_category.toLowerCase(); var podcast_image = x.podcast_image; var podcast_title = x.podcast_title; var podcast_desc = x.podcast_description.slice(0,50); ...
[ "getPodcasts() {\n\t\tthis.setState({\n\t\t\tisStarted: true,\n\t\t\tisLoading: true,\n\t\t\tselectedTime: this.state.userTime,\n\t\t})\n\n const { genre, genreString, userTime, offset } = this.state;\n const len_min = 4;\n const len_max = parseInt(userTime) + 5;\n\n listenApi(\"search\", {\n q: ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the global charicteristicdetailstosamples dictionary.
function set_chars_details_to_samples() { // Reset chars_to_samples = {}; chars_details_to_samples = {}; for (var id in proj.samples) { var sample = proj.samples[id]; for (var char in sample.meta.chars) { var detail = sample.meta.chars[char]; // Deal with chars_details_to_samples first ...
[ "function sample_characteristics_init() {\n samples_tab_active();\n}", "set defaultSampleSettings(value) {}", "SetOverrideSampleSettings() {}", "function SamplerMap() {\n }", "set humanoidOversampling(value) {}", "ClearSampleSettingOverride() {}", "function setSamples() {\n var currCpus = os....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that create new issues and adds it to the DOM
function createNewIssue (data) { const issues = document.querySelector('#issues') const divClone = document.querySelector('#issue-card') const template = document.importNode(divClone, true) template.querySelector('.issueId').setAttribute('id', data.id) template.querySelector('.issueNr').textContent = `# ${da...
[ "function createIssue() {\n // POST /repos/:owner/:repo/issues\n\n const baseURL = 'https://api.github.com'\n let url = `${baseURL}/repos/jpkim921/js-ajax-fetch-lab/issues`;\n\n// we're grabbing the issue title and body from the webpage throught the DOM\n let postData = {\n title: document.getElementById('ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes a file. Can optionally throw if the file doesn't exist. Behind the scenes it uses `fs.unlinkSync()`.
static deleteFile(filePath, options) { FileSystem._wrapException(() => { options = Object.assign(Object.assign({}, DELETE_FILE_DEFAULT_OPTIONS), options); try { fsx.unlinkSync(filePath); } catch (error) { if (options.throwIfNotExist...
[ "function deleteFile(path)\n{\n\tfs.unlink(path, (err) => {\n\t\tif (err) {\n\t\t\t// Log some type of error here, but I don\\'t have a logging module\n\t\t}\n\t});\n}", "function delFile(file){\r\n if(fs.existsSync(file)){\r\n fs.unlink(file, (err) => {\r\n if(err){\r\n console.log(err);\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Look up a single project and return a promise that resolves to both the project and the current user's role.
getProjectAndRole({ projectId, projectName, mutation = false }) { const query = { deleted: false, }; if (projectId) { query._id = new ObjectId(projectId); } else if (projectName) { query.name = projectName; } else { return Promise.reject(new BadRequest('no-project-id')); ...
[ "currentUserRole() {\n const currentProject = self.currentProject();\n if (!currentProject) {\n return null;\n }\n\n const projectUser = currentProject.projectUser(self.currentUser().id());\n if (projectUser) {\n return 'Admin';\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor for EmojiKeyword: Instance of either EmojiKeyword, EmojiKeywordDeleted
constructor(args) { super(); args = args || {} this.CONSTRUCTOR_ID = 0xd5b3b9f9; this.SUBCLASS_OF_ID = 0x6612a53e; this.keyword = args.keyword; this.emoticons = args.emoticons; }
[ "function Keyword(name) {\n this.name = name\n}", "function kw(name,options){if(options===void 0)options={};options.keyword=name;return keywords[name]=new TokenType(name,options);}", "function kw(name,options){if(options===void 0)options={};options.keyword=name;return keywordTypes[name]=new TokenType(name,op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a rule exists for that breakpoint.
function _doesRuleExist( breakpoint ) { return _getRulePositionByBreakpoint( breakpoint ) >= 0 && typeof _getRulePositionByBreakpoint( breakpoint ) === "number"; }
[ "function ruleExists(ruleId) {\n return ruleIds.has(ruleId);\n}", "function _getRulePositionByBreakpoint( rules, breakpoint ) {\n\t\t\tif ( typeof rules === \"undefined\" ) {\n\t\t\t\trules = _settings.rules;\n\t\t\t}\n\t\t\tfor ( var i = 0; i < rules.length; i++ ) {\n\t\t\t\tif ( rules[ i ].breakpoint === bre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function insertPTTable: Parameters: table: indexes of table limits (DOCS, BEGIN, END) table_counters: tables counters for each sheet in the PTTables col2_data: data of column 2 of current sheet col3_data: data of column 3 of current sheet group_sheet: sheet into which table is going to be inserted num_of_items: total n...
function insertPTTable(table, table_counters, col2_data, col3_data, group_sheet, num_of_items) { //Logger.log(table); var g_lastRow = group_sheet.getLastRow(); var group_name = group_sheet.getName(); if (table["ALREADY_EXISTS"]) { // Do something: just update num_of_items //Logg...
[ "function maketable() {\r\n\t\r\n\tfulltable.length=0;\r\n\tfor (i=0;i<MBCdata.length;i++) {\r\n\t\t// each row is the scout record\r\n\t\tvar arr = [];\r\n\t\tfor (var j=0;j<uniqlist.length;j++) {\r\n\t\t\tarr[j]=0;\r\n\t\t}\r\n\t\tfor (var k=0; k<MBCdata[i].mbLst.length;k++) {\r\n\t\t\tarr[MBCdata[i].mbLst[k].pos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
split url into sub categories and return the pages
function urlSplit(pUrl){ if(pUrl.indexOf("https:") > -1){ pUrl = pUrl.split('www.').pop(); } else { pUrl = pUrl.split('http://').pop(); } var urlArr = pUrl.split('/'); var domains = urlArr[0].split('.'); urlArr.splice(0,1); var pages = urlArr; console.log("URL: " + pUrl); console.log("Domain...
[ "function splitUrlCategory(srUrl) {\n let matches = srUrl.match(/(.+?)\\/(.+)/);\n return {category: matches[1], url: matches[2]};\n}", "static parseCategories(response, title) {\n try {\n let categories = new Array();\n let pages = response.query.pages;\n for (let p in p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert WGS84 Coord to scaled geocentric cartesian coordinate
function WGS84ToCartesian(lng, lat, elv) { var result = []; var lngRad = lng * Math.PI / 180.0; var latRad = lat * Math.PI / 180.0; var sinlat = Math.sin(latRad); var coslat = Math.cos(latRad); var sinlong = Math.sin(lngRad); var coslong = Math.cos(lngRad); var Rn = 6378137.0 / Math.sqrt(1.0-0.0...
[ "function convertSPToWGS84(uX, uY) { // Copied from scopi! How about that!\n var sqrt = window.Math.sqrt, pow = window.Math.pow,\n atan = window.Math.atan, sin = window.Math.sin,\n abs = window.Math.abs,\n part1 = undefined,\n rho = undefined, theta = undefined, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a color hue to an HTML color string (with prefix). This implementation ignores all components of `color` except hue.
function getFullColorString(color) { return "#" + hsv2hex(color.h, MAX_COLOR_SATURATION, MAX_COLOR_VALUE); }
[ "function getFullColorString(color) {\n return \"#\" + hsv2hex(color.h, MAX_COLOR_SATURATION, MAX_COLOR_VALUE);\n}", "function getFullColorString(color) {\n return \"#\" + hsv2hex_1.hsv2hex(color.h, consts_1.MAX_COLOR_SATURATION, consts_1.MAX_COLOR_VALUE);\n }", "function hslString(){\n\t\tvar h = ci...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encrypt value with optional expiration and purpose
encrypt(value, expiresAt, purpose) { /** * Using a random string as the iv for generating unpredictable values */ const iv = helpers_1.string.generateRandom(16); /** * Creating chiper */ const cipher = crypto_1.createCipheriv(this.algorithm, this.crypt...
[ "encrypt (value) {\n if (!this.cryptr) throw new Error('No secret was supplied for Crypter')\n return this.cryptr.encrypt(value)\n }", "encrypt(value){\n const salt = this.get('salt')\n return crypto.createHmac('sha512', salt)\n .update(value)\n .digest('hex')\n }", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We need to set the nodeHeight to calculate offsets.
function setNodeHeight(nodesView) { nodeHeight = nodesView.children().first().children('.dvs-node-inner-wrapper').height(); }
[ "updateHeight(newHeight) {\n\t\t\t\t\tif(this.relativeHeight >= newHeight)\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\tconst delta = newHeight - this.relativeArea.height;\n\t\t\t\t\tthis.relativeArea.height = newHeight;\n\t\t\t\t\tif(this.nodeArea != null)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.nodeArea.height += delta;\n\t\t\t\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that entering a child menu cancels the dismiss timer for the submenu.
testEnteringChildCancelsDismiss() { const submenu = new SubMenu('submenu'); submenu.isInDocument = functions.TRUE; submenu.addItem(new MenuItem('submenu item 1')); menu.addItem(submenu); mockClock = new MockClock(true); submenu.getMenu().setVisible(true); // This starts the dismiss timer. ...
[ "function mmCancelCloseTime() {\n if (closeTimer) {\n window.clearTimeout(closeTimer);\n\tcloseTimer = null;\n }\n if (menuParent) {\n menuParent.className = 'sel';\n }\n}", "function handleCloseMenu() {\n timeoutRef.current = setTimeout(() => {\n setMenu(false);\n }, 250);\n }", "_closeSu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the extents of the data for a specific indicator. Extents are are the bounds of our data. For example, the array [1,2,3,4] has the extent [1,4]. In order to get a consistent extent for our scale (that won't shift as we change years,) we need to go through all the years and all the countries and find the min ...
function calcExtents(data, indicator) { // first find all the data points for a specific indicator across // all countries and join them into one array. var allValues = data.map(function(country) { return country[indicator]; }).reduce(function(values, current) { return values.concat(_.compact(current))...
[ "function calcExtents(data, indicator) {\n\n // first find all the data points for a specific indicator across\n // all countries and join them into one array.\n var allValues = data.map(function(player) {\n return player[indicator];\n });\n\n // now go through all the data points and find the e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
append a text message (ChatBubbleComponent under the hood) to the chat log
async appendText(person, text) { await this.appendComponent(new ChatBubble({ person, text, onClick: this.handleTextClick })) }
[ "function pushLog(text) {\r\n\tchatLog.push(text);\r\n\tconsole.log(text);\r\n}", "function appendToChatLog(message){\n\tlet chatLog = $('#chatLog')[0];\n\tchatLog.append(message);\n\tscrollToBottomOfChatLog();\n}", "function logText() {\n //Instantiating chat history inside chatLog\n let textToBeSent = d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the connection from the list of incoming and outgoint connections
unregisterConnection(connection) { this.incomingConnections = this.incomingConnections.filter(element => { return element.id !== connection.id; }); this.outgoingConnections = this.outgoingConnections.filter(element => { return element.id !== connection.id; }); this.updateDependentActio...
[ "function removeConnection() {\n\t\tthis.originPort.remove();\n\t\tthis.destinationPort.remove();\n\t\tdocument.getElementById(MAP).removeChild(document.getElementById(this.id));\n\t}", "handleRemoveConnection() {\n\n let connection = this.getInstance().getActiveConnection();\n let index = this.connections....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when a components root VNode is also a component, we can run into issues this will recursively look for vNode.parentNode if the VNode is a component
function updateParentComponentVNodes(vNode, dom) { if (vNode.flags & 28 /* Component */) { var parentVNode = vNode.parentVNode; if (parentVNode) { parentVNode.dom = dom; updateParentComponentVNodes(parentVNode, dom); } } }
[ "function updateParentComponentVNodes(vNode, dom) {\n\t if (vNode.flags & 28 /* Component */) {\n\t var parentVNode = vNode.parentVNode;\n\t if (parentVNode) {\n\t parentVNode.dom = dom;\n\t updateParentComponentVNodes(parentVNode, dom);\n\t }\n\t }\n\t}", "functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method used to update book count
reloadBookCount() { this.getNumberOfAvailableBooks(); }
[ "function editBook(newBook) {\n newBook.pageCount = newBook.pageCount * .75\n}", "function updateBookNumbers ( book, index ) {\r\n book[bookNumberProperty] = index;\r\n}", "readNewBook() {\n this.numBooksRead++;\n }", "updateCount() {\n\t\tvar count;\n\t\tcount = [this.decks[\"new\"].length, this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log(getgencat()); return those employee who has age greater than 40
function getempbyage(){ let agfactor = company.student.filter((ag)=>{ return ag.Age >40; }) return agfactor; }
[ "function employeeAges(employee) {\n var olderThan25 = []\n employee.forEach(element => {\n if (element.age > 25) {\n olderThan25.push(element)\n }\n\n });\n return olderThan25\n}", "function ageFilter (student) {\n return student.age >= 18 && student.age <= 24;\n }"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
main & side compare height
function comHeight() { $('.f_main,.f_side').height('auto'); var main_h = $('.f_main').height(), side_h = $('.f_side').height(); $('.f_main,.f_side').css({ 'minHeight': Math.max(main_h, side_h) }); }
[ "function sortByHeight() {}", "function eqtHeight(side_length) {\n return side_length * Math.sqrt(3) / 2\n}", "function findMainPanelHeights (){\n\t\t// find uniq mainPanels id\n\t\t//self.mainPanels=[];\n\t\tself.elem.forEach(function(item) {\n\t\t\tif (self.mainPanels.indexOf(item.panMainId)==-1) {\n\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extends list of nodes with extra functionality.
function extendNodes(){ if(!nodes) return; $.extend(nodes, { 'bind' : bind, 'parent' : parent, 'children' : children, 'index' : index, 'css' : css }); }
[ "function extend_nodes (new_nodes) {\n if (this.enable_search) {\n for (var node_id in new_nodes) {\n var node = new_nodes[node_id]\n if (node.node_type !== 'metabolite') {\n continue\n }\n this.search_index.insert('n' + node_id,\n { 'name': node.bigg_id,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function addresses the often fidly problem of date manipulation minVal and maxVal are in epoch time, while min and max are the regular domain as strings. You should use min and max for the domain.
function getTimeDomain(data) { return data.reduce((acc, row) => { const epochTime = (new Date(row.date)).getTime(); return { minVal: Math.min(epochTime, acc.minVal), maxVal: Math.max(epochTime, acc.maxVal), min: epochTime < acc.minVal ? row.date : acc.min, max: epochTime > acc.maxVal ?...
[ "function getTimeDomain(data) {\r\n return data.reduce((acc, row) => {\r\n const epochTime = (new Date(row.date)).getTime();\r\n return {\r\n minVal: Math.min(epochTime, acc.minVal),\r\n maxVal: Math.max(epochTime, acc.maxVal),\r\n min: epochTime < acc.minVal ? row.date : acc.min,\r\n max...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logarithm of a rigid body transform from a quaternion and translation The log is returned as a matrix See section 3.2
function log(quat, translation) { // XYZ is imaginary vector part and W is real scalar part var quatVector = new THREE.Vector3(quat.x, quat.y, quat.z); var quatVectorMag = quatVector.length(); var theta, A, B, C, D, axisAngle; if (quatVectorMag < 0.0001) { theta = 0; A = 1.0; ...
[ "function linearToLog(position) {\n return (1 / 15) * Math.pow(16, position) - (1 / 15);\n}", "function Logarithm() {\r\n}", "function exp(m, t)\n{\n // Pick out the omega (axis-angle vector) and u from the log-matrix\n var omega = new THREE.Vector3(m.elements[6], m.elements[8], m.elements[1]);\n va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets an image URL for the given scale.
getImageUrl(scale) { // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style return this._data[`image_url_${scale}x`]; }
[ "function getImgUrl(img_id) {\n var url = libs.portal.imageUrl({\n id: img_id,\n scale: 'square(250)'\n });\n return url\n }", "getTexture(scale) {\n return null;\n }", "function getImgUrl() {\n return loadFromStorage('img')\n}", "getImageUrl(img, size = 25...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load Submissions from JSON into ES
async function loadSubmissions () { const promises = [] submissions.forEach((submission) => { const record = { index: config.get('esConfig.ES_INDEX'), type: config.get('esConfig.ES_TYPE'), id: submission.id, body: _.extend({ resource: 'submission' }, submission) } promises.push(e...
[ "function ingest(jsonObj){\r\n\t//do the following while a counter, \r\n\t//starting at 1 (one) less the length of an array decrements\r\n\t//until the counter reaches 0 (zero)\r\n\t//this is so that the most recent update is the first on the list.\r\n\tfor (var n = jsonObj.feed.entry.length -1; n >= 0; n--){\r\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that the cursor is never moved outside the visible area of the canvas
function validatePosition(){ if (cursorPos.x < 0){ cursorPos.x = 0; } if (cursorPos.x + img.width > canvasCrosshair.width){ cursorPos.x = canvasCrosshair.width - img.width; } if (cursorPos.y < 0){ cursorPos.y = 0; } if (cursorPos.y +img.height > canvasCrosshair.hei...
[ "out_of_canvas() {\n if (this.x > width || this.y > height){\n return true;\n }\n if (this.x <0 || this.y <0) {\n return true;\n }\n else{\n return false;\n }\n }", "checkForCursorVisibility() {\n this.showCaret();\n }", "hi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates a style (pass in the css rules as a string parameter)
function updateStyle(css) { if ("string" != typeof css) css = ''; $('#PortableCSSPad-live-style').replaceWith('<style id="PortableCSSPad-live-style">' + css + '</style>'); }
[ "function updateStyle(css) {\n\t\tif ('string' !== typeof css) {\n\t\t\tcss = $textarea.val();\n\t\t}\n\t\t$liveStyle.text(css);\n\t}", "function setStyle(val){\n var params = {\n 'STYLES': val\n };\n pipeline.getSource().updateParams(params);\n}", "_processCss(jstObj, css) {\n if (css) {\n jst.st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turns a layerId into a Layer model from the redis cache if found otherwise returns null
async function getLayer(layerId) { const { id, url, label, date_created, imagery_date, imagery_end_date, srcType, layerType, category, source, bounds, yield_default, asset, } = await redis.hgetallAsync(`layer:${layerId}`); return { id: Number(id), url: ...
[ "function getLayer(id) {\n // look for the matching layer, and return when found\n for (var ii = 0; ii < layerCount; ii++) {\n if (layers[ii].getId() == id) {\n return layers[ii];\n } // if\n } // for\n \n return null;\n }", "function getL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the status of the caches, e.g. they are ready (empty)
function checkCaches(){ return getKeys(CACHE).length || getKeys(SOLVED).length; }
[ "async function check_cached() {\n console.info('check_cached()');\n\n all_base64 = {};\n\n // Leave all_num_cached as undefined while waiting for the cache\n // transactions to prevent the progress message from temporarily\n // claiming the cache is empty when it might not be.\n let cache = await caches.open...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Destroys all settings file instances that have no listeners
async destroySettingsFiles() { const promises = Object.values(this.settings).map(async (settingsFile) => { return (await settingsFile).destroy(); }); await Promise.all(promises); }
[ "_destroy() {\n this._debouncedSave.cancel();\n\n this.removeListener(Settings.Events.CREATE, this._onCreate);\n this.removeListener(Settings.Events.CHANGE, this._onChange);\n this.removeListener(Settings.Events.SAVE, this._onSave);\n this.removeListener(Settings.Events.ERROR, this._onError);\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hides/Shows header psuedoel prevents bg image from showing below footer on overscrolls
function toggleHeaderBgImg() { let winToTop = $(window).scrollTop(), headerHt = $('header').height(); if(winToTop > headerHt * 2) { $('header').addClass('remove'); } else { $('header').removeClass('remove'); } }
[ "function hideHeader() {\r\n let scrollPos = $(window).scrollTop();\r\n let windowWidth = $(window).width();\r\n\r\n //Check Window Location and width\r\n if (scrollPos < 50 && windowWidth > 924) {\r\n //Hide Background\r\n $(\"#navContainer\").addClass(\"clBackground\");\r\n } else {\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolve the promise returned by `requestAmountOfFreeDiskSpace()`. Can only be called once for the lifetime of the handler.
resolveRequestAmountOfFreeDiskSpace( ticks, defaultIndex, isLowSpaceAvailable) { this.resolveRequestAmountOfFreeDiskSpace_( {ticks, defaultIndex, isLowSpaceAvailable}); }
[ "checkStorageQuota() {\n\n return new Promise((resolve, reject) => {\n\n if (this._availableQuota && this._usage) {\n return resolve(availableSpace(this._usage, this._availableQuota));\n }\n\n if (navigator) {\n\n navigator.storage.estimate().then((estimate) => {\n this._ava...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add to history of measurements Inputs: index/value pairs Returns: integer time of measurement
function AddToHistory(i,vals) { var d = new Date(); var t = Math.ceil(d.getTime()/1000); var entry; if (!history.length) { entry = history[0] = []; historyTime = t; } else { // add entries up to this time if necessary while (historyTime < t) { ++historyTim...
[ "function update_elapsed(index, time) {\n var history = document.getElementById(\"history\");\n var elapsed = history.rows[history.rows.length - 1].insertCell(4);\n var elapsed_time = new Date(time - time_started);\n var elapsed_text = document.createTextNode(watch_repr(elapsed_time));\n elapsed.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name:offlinePushNotificationiPhoneCallback Author:Kony Purpose:Callback function for the push message recieving event while offline.
function offlinePushNotificationiPhoneCallback(msg, actionId) { kony.print("************ JS offlinePushNotificationCallback() called *********"); alert("Message: " + msg["alert"]); kony.print("\n received push:-" + JSON.stringify(msg)); kony.print(msg); }
[ "function offlinePushNotificationCallback(msg){\n kony.print(\"************ JS offlinePushNotificationCallback() called *********\");\n kony.print(msg);\n kony.store.setItem(\"isNewOfflineNotification\", true);\n// if(msg[\"content-available\"]!=1)\n// alert(\"Message: \"+msg[\"content\"]);\n// else{\n//...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To set updated values in the MaskedTextBox.
function setMaskValue(val) { if (this.mask && val !== undefined && (this.prevValue === undefined || this.prevValue !== val)) { this.maskKeyPress = true; setElementValue.call(this, this.promptMask); if (val !== '' && !(val === null && this.floatLabelType === 'Never' && this.placeholder)) { ...
[ "function applyMask() {\n setElementValue.call(this, this.promptMask);\n setMaskValue.call(this, this.value);\n}", "#masking() {\n\t\tthis.#evaluateMask()\n\t\tthis.input.value = Mask.masking(this.input.value, this.mask)\n\t}", "updateMask() {\n\t\tthis.get('mask').toLowerCase() === 'regex'\n\t\t\t&& this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the user clicking on the continue button. If they were correct then it starts the next round, else it sends them to the game over page.
function continueReponse() { // Check if the answer text says 'CORRECT' to determine the next step. if (dataContainers.answer.innerText == "CORRECT") { getStat(); } else { saveScore(); window.location.href = "/gameover.html"; } }
[ "function continueRound() {\n trackPlayerResponse();\n addClickable();\n }", "function continueGame() {\n\n // Get the next question.\n var nextQuestion = quizQuestions.getNext();\n\n // End the game if we have run out of questions.\n if( !nextQuestion ) {\n endGame();\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
7. Get Code Execution Create JITCodeObject
function makeJITCompiledFunction() { function target(x) { return x; } for (var i = 0; i < 1000; i++) { target(i); } return target; }
[ "getData(){\n let output=compilerCode\n return output;\n }", "function jitExpression(def,context,sourceUrl,preStatements){// The ConstantPool may contain Statements which declare variables used in the final expression.\n// Therefore, its statements need to precede the actual JIT operation. The final statem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort by 1st value
function sortByFirstVal(a, b) { if (a[0] < b[0]) return -1; if (a[0] > b[0]) return 1; return 0; }
[ "function sortByNumberOneAscending(first, second) {\n return first.numberOne - second.numberOne;\n}", "function sortByIndex1(a, b) {\n\tif (a[1] === b[1]) {\n\t\treturn 0;\n\t}\n\telse {\n\t\treturn (a[1] < b[1]) ? 1 : -1; // largest to smallest\n\t}\n}", "function sortBySecondVal(a, b) {\n if (a[1]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add platforms to the game
function addPlatforms() { platforms = game.add.physicsGroup(); // logo platforms.create(745, 0, 'logo'); // platforms platforms.create(70, 117, 'platform'); platforms.create(440, 100, 'platform'); platforms.create(150, 210, 'platform'); platforms.create(755, 200, 'platform'); platforms.create(30, 400,...
[ "function addPlatforms() {\n platforms = game.add.physicsGroup();\n platforms.create(450, 550, 'platform');\n platforms.create(100, 550, 'platform');\n platforms.create(300, 450, 'platform');\n platforms.create(250, 150, 'platform');\n platforms.create(50, 300, 'platform');\n platforms.create(150, 250, 'plat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns super cookiesets which are: 1. Have maximum '1's but are not tested so far. 2. Are not supersets of verified accountcookiesets. 3. Already notverified to be accountsupercookiesets. Returned supercookiesets are tested by dropping cookies marked by '1'. If the user is LOGGEDOUT, then we need to investigate permut...
function generate_super_cookiesets(url, tot_cookies, verified_strict_account_decimal_cookiesets, verified_account_super_decimal_cookiesets, verified_non_account_super_decimal_cookiesets, x) { var my_super_decimal_cookiesets = []; var my_super_binary_cookiesets = []; var r...
[ "function generate_super_cookiesets_efficient(url,\n\t\t\t\t\t x,\n\t\t\t\t\t tot_cookies, \n\t\t\t\t\t verified_strict_account_decimal_cookiesets,\n\t\t\t\t\t verified_account_super_decimal_cookiesets,\n\t\t\t\t\t verified_non_account_super_decimal_cookiesets) {\n var my_super_decimal_cookie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }