query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Create a function to setup initial quiz screen html and show button that will start the quiz
function initialScreen() { $("body").html(`<div class = "jumbotron text-center"><div class = "Quiz"> <h1 class = title>State Capitals Trivia Quiz!</h1><br><button id = startButton>Play</button></div>`) $("#startButton").on("click", function(){ $("body").html(`<div class = "jumbotron text...
[ "function initiateQuiz() {\n startQuiz();\n renderFirstQuestion();\n answerChoice();\n renderNextQuestion();\n}", "function startQuiz() {\n // clear the start-view page when start-button is clicked\n $(\".score-and-question\").show();\n updateQuestion();\n generateForm();\n\n generateQuestion(STO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SET IDs IN DOM TO GLOBAL VARIABLES
function IDsToVars(){ var allElements = document.getElementsByTagName("*"); for (var q = 0; q<allElements.length; q++){ var el = allElements[q]; if (el.id){ window[el.id]=document.getElementById(el.id); } } }
[ "function idsToVars() {\n\t\t[].slice.call(document.querySelectorAll('*')).forEach(function(el) {\n\t\t\tif (el.id) window[el.id] = document.getElementById(el.id);\n\t\t});\n\t}", "function idsToVars() {\n [].slice.call(document.querySelectorAll('*')).forEach(function(el) {\n if (el.id) window[el.id] = docume...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor (low level) and fields Creates a new QR Code with the given version number, error correction level, data codeword bytes, and mask number. This is a lowlevel API that most users should not use directly. A midlevel API is the encodeSegments() function.
function QrCode( // The version number of this QR Code, which is between 1 and 40 (inclusive). // This determines the size of this barcode. version, // The error correction level used in this QR Code. errorCorrectionLevel, dataCodewords, msk) { (0,_babel_runtime_helpers_esm_classCallCheck__WEB...
[ "constructor(\n // The version number of this QR Code, which is between 1 and 40 (inclusive).\n // This determines the size of this barcode.\n version, \n // The error correction level used in this QR Code.\n errorCorrectionLevel, dataCodewords, \n // The index of the mask ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the...
function $tTA8$var$fixedtables(state) { if ($tTA8$var$virgin) { var sym; $tTA8$var$lenfix = new $tTA8$var$utils.Buf32(512); $tTA8$var$distfix = new $tTA8$var$utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { ...
[ "function constructFixedTables() {\n\t\tvar lengths = new Array();\n\t\t// literal/length table\n\t\tfor(var symbol = 0; symbol < 144; symbol++) lengths[symbol] = 8;\n\t\tfor(; symbol < 256; symbol++) lengths[symbol] = 9;\n\t\tfor(; symbol < 280; symbol++) lengths[symbol] = 7;\n\t\tfor(; symbol < FIXLCODES; symbol+...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
contract: bridge contract prover: eprover/hprover
constructor(web3, contract, prover) { this.web3 = web3; this.contract = contract; this.prover = prover; }
[ "async function deployContract(){\n\n let abiPath = path.join(__dirname + '/bin/DataStorageEvent.abi');\n let binPath = path.join(__dirname + '/bin/DataStorageEvent.bin');\n\n console.log(chalk.green(abiPath));\n console.log(chalk.green(binPath));\n\n let abi = fs.readFileSync(abiPath);\n // let bin = '0x' + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make the timeline draggable
function _dragableTimeline() { var selected = null, x_pos = 0, x_elem = 0; // Will be called when user starts dragging an element function _drag_init(elem) { selected = elem; x_elem = x_pos - selected.offsetLeft; } // Will be called when user dragging an element function _move_elem(e) { ...
[ "function _dragableTimeline() {\n\n\t\t\tvar selected = null, x_pos = 0, x_elem = 0;\n var lastX;\n var directionRight = true;\n\n\t\t\t// Will be called when user starts dragging an element\n\t\t\tfunction _drag_init(elem, e) {\n if (e.targetTouches) {\n var touch = e.targetTouches[0];\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a Slate model to a Tag representation
function parse(model, options) { const object = isPseudoLeafRecord(model) ? 'leaf' : model.object const parser = PARSERS[object] if (!parser) { throw new Error(`Unrecognized Slate model ${object}`) } if (object === 'value') { if (model.annotations.size > 0) { model = applyAnnotationMarks(model...
[ "function parse(model: SlateModel, options: Options): Tag[] {\n const object = model.object || model.kind;\n const parser = PARSERS[object];\n if (!parser) {\n throw new Error(`Unrecognized Slate model ${object}`);\n }\n return parser(model, options);\n}", "function parse(model: SlateModel, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the toplevel node that contains the node before this one.
function topLevelNodeBefore(node, top) { while (!node.previousSibling && node.parentNode != top) { node = node.parentNode; } return topLevelNodeAt(node.previousSibling, top); }
[ "function topLevelNodeBefore(node, top) {\n while (!node.previousSibling && node.parentNode != top)\n node = node.parentNode;\n return topLevelNodeAt(node.previousSibling, top);\n }", "get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the helper method to validate the length of gRPC match array when it is specified.
function validateGrpcMatchArrayLength(metadata) { const MIN_LENGTH = 1; const MAX_LENGTH = 10; if (metadata && (metadata.length < MIN_LENGTH || metadata.length > MAX_LENGTH)) { throw new Error(`Number of metadata provided for matching must be between ${MIN_LENGTH} and ${MAX_LENGTH}, got: ${metadata....
[ "function validateHttpMatchArrayLength(headers, queryParameters) {\n const MIN_LENGTH = 1;\n const MAX_LENGTH = 10;\n if (headers && (headers.length < MIN_LENGTH || headers.length > MAX_LENGTH)) {\n throw new Error(`Number of headers provided for matching must be between ${MIN_LENGTH} and ${MAX_LENG...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the button grid
function initButtonGrid() { const buttons = document.querySelectorAll(".button-grid div"); buttons.forEach( button => { button.style.gridArea = button.id; // Set grid placement button.classList.add("button"); // Add button class button.classList.add(keys[keyIndexById(button.id)].type); /...
[ "function initButtons(){\n const createBtn = document.getElementById('Create');\n createBtn.addEventListener('click',updateGrid);\n const resetBtn = document.getElementById('Reset');\n resetBtn.addEventListener('click',resetGrid);\n}", "init() {\n this.prepareGrid();\n this.confi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getFilterCars2(); / $eq $ne $gt $gte $lt $lte $in $nin
async function getFilterPriceCars(){ //Podemos Filtrar const cars = await Car //Buscamos los que tenga el precio 2000 justos //.find({price: 2000}) //Ahora buscamos entre 2000 y 10000 y el resto no los queremos. .find({price: {$gte: 2000, $lt: 10000}}) console.log(cars) }
[ "function searchFilterPipe(cars) {\n let search_query = document.getElementById(\"car_search_input\").value;\n\n let flt_cars = []\n console.log(\"Searchig for \", search_query)\n if (search_query == undefined || search_query == null || search_query == \"\" || search_query == \"undefined\") {\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=================================================================== from vm/interpreter/qq/UnquoteSplicing.java ===================================================================
function UnquoteSplicing() { }
[ "function Unquote() {\r\n}", "get BackQuote() {}", "unscramble(s) {\n let r = '', p;\n\n while (s.length > 51){\n p = s.substring(0, 50);\n s = s.substring(50);\n r = r + this.obfusc50(p);\n }\n r = r + s;\n // now undo substitution obfuscation\n r = r.replace(/Kcl/g, '| x').re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw and check to see if pellets were eaten.
function handlePellets(){ for (var i = 0; i < pellets.length; i++){ fill(120, 255, 120); ellipse(pellets[i].x, pellets[i].y, pellets[i].r * 2, pellets[i].r * 2); if (blob.eats(pellets[i].x, pellets[i].y, pellets[i].r)){ pellets.splice(i, 1); } } }
[ "function drawPellets() {\n\t//draw the pellets\n\tcontext.fillStyle=\"#BBFF00\";\n\tfor (var i = 0; i < pellets.length; ++i) {\n\t\tcontext.fillRect(pellets[i].x - pellets[i].width/2, pellets[i].y - pellets[i].height/2,pellets[i].width,pellets[i].height);\n\t}\n}", "function check(){\r\n\tvar pellet = document.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
kind may be `const` or `let` Both are experimental and not in the specification yet. see and
function parseConstLetDeclaration(kind) { var declarations; delegate.markStart(); expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind)); }
[ "function parseConstLetDeclaration(kind) {\n\t var declarations, marker = markerCreate();\n\t\n\t expectKeyword(kind);\n\t\n\t declarations = parseVariableDeclarationList(kind);\n\t\n\t consumeSemicolon();\n\t\n\t return markerApply(marker, delegate.createVariableDeclaration(decla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback called when the 'quantity' subproperty is created/changed
@onValuesChanged("quantity", ["insert", "modify"]) changeQuantity(value) { eventLog.push("Quantity changed: " + value); }
[ "setQuantity(newQuantity) {\n this.quantity = newQuantity;\n }", "setQuantity(quantity) {\n this.quantity = quantity;\n }", "function updateQuantity(event) {\n setQuantity(event.target.value);\n }", "handleQuantityChange(event) {\n const productId = event.detail.productId;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculating the support reactions at the 2 support nodes using moments
function calculateSupportReactions(){ //calculate support reactions, and otherwise 0 if the car is completely out of the bridge and not touching the supports E.supportA.setForce(-1*Math.abs(E.crane_length/E.crane_height*E.loadedPin.external_force[1]),Math.abs(E.loadedPin.external_force[1]),Grid.canvas); E.supportB.s...
[ "chooseActions(edge, n1, n2) {\n let inst = this;\n let actions = this.model.selectedActions;\n let stroke = \"gray\";\n let lineWidth = 1;\n edge.act = null;\n var h = n1.happiness;\n //console.log(\"edge\", n1, h, n2);\n if (n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a package of game data.
function getGameDataPackage() { Android.test("creating package..."); return gameString(startingJSON); }
[ "function newGameData() {\n var data = {\n 'area': 'shore',\n 'inventory': {\n 'items' : {},\n 'weapons' : {},\n 'armors' : {},\n 'helmets' : {},\n 'boots' : {}\n },\n 'visibleSkills': [],\n 'defeatedMonsters': {},\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
spicchio di sfera di "gradi" radianti, ruotato di alpha, traslato di trasla (opzionale)
function sfera (r,gradi,alpha,trasla) { if (trasla === undefined) { trasla = []; }; var tx = trasla[0] || 0; var ty = trasla[1] || 0; var tz = trasla[2] || 0; var funzione = function (p) { var a = p[0] * PI/2; var b = alpha + p[1] * gradi; return [tx + r * COS(a) * SIN(b),ty + r * COS(a) *...
[ "function conversion_grados_radianes(nombre_unidad, valor_unidad){\n var varRadianes, varGrados;\n valor_unidad = valor_unidad.replace(\",\", \".\");\n if(isNaN(valor_unidad)){\n alert(\"Por favor ingresa un valor numérico, gracias!\");\n document.getElementsByTagName(\"input\")[0].value = \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log('participants at useEffect in Call.js line 25:', callObject.participants())
function handleNewParticipantsState(event) { //debugger // event.participant.owner = true if event.participant.local AND user.is_admin? if (event) { event.participant.owner = true } console.log('callObject.partis @ handlenewparticipants:', callObject.participants()) // event...
[ "get activeParticipants () {\n return this.participants.filter(p => p.status === CallParticipantStatus.ACTIVE)\n }", "function resolvePendingCalls(participantDict) {\n console.log(\"Participant list arrived from the server.\");\n\n // Store the names of participants you received from the server.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets the color (of the disk in the) cell and its state when filled
setFilled(color) { this.filled = true; this.color = color; }
[ "fillUncolored()\n {\n console.log(\"Original Color: \", this.state.bgColor);\n if (this.state.bgColor === \"white\" || this.state.bgColor === \"\")\n {\n this.fillCell();\n console.log(\"New Color: \", this.state.bgColor);\n }\n }", "function setFill(){\n if (black === 0) {\n fill(255);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reverses the order of the players array
function swapPlayers(playersArray) { playersArray.unshift(playersArray.pop()); }
[ "reverseInvaders() {\n let index = 0;\n for (let invader of this.invaders) {\n this.invaders[index].reverse();\n this.invaders[index].position.y += 50;\n index++;\n }\n }", "function down(index) {\r\n if (user_player_arr.length > 1 && index < ((user_player...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return Firebase cache ref for the given ip address
function ipCacheRef(ip) { var fbkey = ip.replace(/\./g, '-'); var url = process.env.FBIO_GEOCACHE_URL + "/" + fbkey; return new Firebase(url); }
[ "function refFromURL(db, url) {\n db = _firebaseUtil.getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (!db._repo.repoInfo_.isCustomHost() && repoInf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set whether collection is enabled for this ID.
function setAnalyticsCollectionEnabled(analyticsId, enabled) { window["ga-disable-" + analyticsId] = !enabled; }
[ "function setAnalyticsCollectionEnabled(analyticsId, enabled) {\n window[\"ga-disable-\" + analyticsId] = !enabled;\n }", "function setAnalyticsCollectionEnabled(analyticsId, enabled) {\n window[\"ga-disable-\" + analyticsId] = !enabled;\n}", "function setAnalyticsCollectionEnabled(initializati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removeWidget called by the handleDrop func removes widget with id from origin which is either RightPanel or canvas.
removeWidget(id, origin){ let addOrPanelRemove; if (origin === 'Canvas'){ addOrPanelRemove = this.state.canvasWidgets; } else { addOrPanelRemove = this.state.rightPanelWidgets; } const newState = addOrPanelRemove.filter( el => el.widgetId !== id ); return ne...
[ "handleDropRender(id, origin, target){\n if ( origin === target){\n return false;\n }\n let newCanvasWidget;\n let newRightPanelWidget;\n if ( origin === 'Canvas'){\n newCanvasWidget = this.removeWidget(id, origin);\n newRightPanelWidget = this.addWidget(id, target);\n }\n el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
You need to cook pancakes, but you are very hungry. As known, one needs to fry a pancake one minute on each side. What is the minimum time you need to cook n pancakes, if you can put on the frying pan only m pancakes at a time? n and m are positive integers between 1 and 1000.
function cookPancakes(n, m) { return (m > n * 2 || n === 1) ? 2 : Math.ceil(n * 2 / m ); }
[ "function chocolateFeast(n, c, m) {\n var numberOfWrappers, numberOfChoclates;\n\n numberOfWrappers = numberOfChoclates = Math.floor(n / c);\n\n while (numberOfWrappers >= m) {\n var freeBars = Math.floor(numberOfWrappers / m);\n if (freeBars > 0) {\n numberOfChoclates += freeBars;\n numberOfWrap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions scrape CL, call the other functions to make and post the markov chain this is the function we call to make magic happen
function gen_markov() { // Scrape CL missed connections headlines request('http://austin.craigslist.org/mis/', function(error, response, body) { var final_text = []; if (!error && response.statusCode == 200) { var $ = cheerio.load(body); // Scrape the response HTML according to craigslist's (inc...
[ "function callCreate() {\n\n multiMarkov.createMarkov(myval);\n\n\n}", "function processUrl(inputUrl){ \n axios\n .get(inputUrl)\n .then(function(resp){ \n let mm = new MarkovMachine(resp.data);\n console.log(mm.makeText(numWords=50));\n })\n .catch(function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ECMA262 13.4 Empty Statement
function parseEmptyStatement(node) { expect(';'); return node.finishEmptyStatement(); }
[ "function parseEmptyStatement(node) {\n expect(';');\n return node.finishEmptyStatement();\n }", "static isEmptyStatement(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.EmptyStatement;\r\n }", "visitEmptyStatement_(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
WEEKDAY_BEFORE Return Julian date of given weekday (0 = Sunday) in the seven days ending on jd.
function weekday_before(weekday, jd) { return jd - jwday(jd - weekday); }
[ "function weekday_before(weekday, jd)\n{\n return jd - jwday(jd - weekday);\n}", "function weekday_before(weekday, jd){\n return jd - jwday(jd - weekday);\n}", "function dayOfWeek( julian ){\n\n\treturn (julian+1)%7;\n\n}", "function findWeekStart(d, firstWeekday) {\n firstWeekday = parseIntDec(first...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main public function that is called to parse the XML string and return a root element object
function Xparse(src) { var frag = new _frag(); // remove bad \r characters and the prolog frag.str = _prolog(src); // create a root element to contain the document var root = new _element(); root.name="ROOT"; // main recursive function to process the xml frag = _compile(frag); // all done, le...
[ "function parseXML(xmlStr){\n var xmlDocumentNode = $.parseXML(xmlStr).documentElement;\n rootNode = copyTree(xmlDocumentNode, null, 0);\n firstWalk(rootNode);\n secondWalk(rootNode, rootNode.mod);\n calculateCoordinates2D(rootNode);\n calculateCoordinates3D(rootNode);\n renderTree(rootNode);\n printTree(ro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make the game history into a list, draw on the constant set at the start gameHistory Applies to playerMove and cpuMove
function drawHistory() { let historyElement = document.getElementById("history"); let displayString = ""; for (let i = 0; i < gameHistory.length; i++) { displayString += "<li>" + gameHistory[i].playerMove + " vs " + gameHistory[i].cpuMove + "</li>"; } historyElement.innerHTML...
[ "function getHistory() {\n let result = ''\n for (let m = 0; m < game.moves.length; ++m) {\n result += outerCell(game.moves[m])\n }\n return { firstPlayer: outerPlayer(game.startPlayer), moves: result }\n}", "renderHistory() {\n const boards = this.state.boards;\n const moves = bo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
redo Canvas Changes This function will redo all of the changes made to the canvas and increase the variable canvasHistoryPointer by one so that it will point at the current canvas state Source for the idea of this method:
function redo_Canvas_Change(){ // Checks to see whether the we can go forward one step if(canvasHistoryPointer+1 < canvasHistory.length){ canvasHistoryPointer++; postCardCanvasContext.putImageData(canvasHistory[canvasHistoryPointer].image, 0, 0); } // If we can't go forward any further then chan...
[ "function undo_Canvas_Change(){\n\t\t // Checks to see whether the we can go back one step\n\t\t if(canvasHistoryPointer >= 1){\n\t\t\t canvasHistoryPointer--;\n\t\t\t postCardCanvasContext.putImageData(canvasHistory[canvasHistoryPointer].image, 0, 0);\n\t\t }\n\t\t \n\t\t // If we can't go back any further then ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fix clearType problems in ie6 by setting an explicit bg color (otherwise text slides look horrible during a fade transition)
function clearTypeFix($slides) { debug('applying clearType background-color hack'); function hex(s) { s = parseInt(s, 10).toString(16); return s.length < 2 ? '0' + s : s; } function getBg(e) { for (; e && e.nodeName.toLowerCase() != 'html'; e = e.paren...
[ "function clearTypeFix($slides) {\r\n\tdebug('applying clearType background-color hack');\r\n\tfunction hex(s) {\r\n\t\ts = parseInt(s,10).toString(16);\r\n\t\treturn s.length < 2 ? '0'+s : s;\r\n\t};\r\n\tfunction getBg(e) {\r\n\t\tfor ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {\r\n\t\t\tvar v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Watch set user offline
function watchSetUserOffline(action) { var roomId, authedUser, uid; return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function watchSetUserOffline$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: roomId = action.payload.roomId; ...
[ "function toDoUserOffline() {\n for (var i = 0; i < fakeUsers.length; i++) {\n if (fakeUsers[i].id === getCurrentUser().id) {\n fakeUsers[i].online = false;\n updateStorage();\n return;\n }\n }\n }", "function setOffline(){\n\tsoc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find class name for method
function find_method(method, node){ var result = ""; var class_name = ""; if (node.type === "class"){ class_name = node.start_statement; class_name = class_name.match(/class\s+([a-zA-Z_-]+)/)[1]; } for (var i in node.children){ var child = node.children[i]; ...
[ "function findClass() {}", "getClassName() {\n return this.constructor\n .className;\n }", "function getClassName(obj) {\n\tvar c = obj.constructor.toString();\n\treturn c.substring(c.indexOf('function ')+9, c.indexOf('('));\n}", "getClassName(ast) {\n logging.taskInfo(this.constructor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates dataset of summed integers of a given size
function create_dataset(size) { let data = []; for (let i = 0; i < size; i++) { let input = utils.create_random_array(2, 0, 100); let label = f(input[0], input[1]); data.push([input, label]); } return data; }
[ "function setsize(dataset, size)\n{\n // random variante\n\tif (dataset.length == 0)\n\treturn []\n\n var final_set = []\n _(size).times(function(n){ \n final_set.push(_.sample(dataset, 1)[0])\n });\n\n return final_set\n \n /*var cur_size = dataset.length\n \n if (size > cur_size)\n {\n _(Math.ce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
routine to set the selected value in an option list.
function set_selected_option (what, set_val) { var last =what.length -1; var index; for (index=0; index<what.length; index++) { if (what[index].value == set_val) { what.selectedIndex = index; } } }
[ "function set_selected(p_obj, p_value) {\n for (i = 0; i < p_obj.options.length; i++) {\n if (p_obj.options[i].value == p_value) {\n p_obj.options[i].selected = true;\n break;\n }\n }\n}", "function setSelectValue() {\n var values = (hasMultiple) ? $select.val() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a function that takes a string and an integer of i and creates a new array of length i where each value is equal to the string passed in myFunction('sunshine', 3) => ['sunshine', 'sunshine', 'sunshine']; Put your answer below
function myFunction(str, i) { var arr = []; for (j = 0; j < i; j++) { arr[j] = str; } }
[ "function myFunction(word, integer){\n const myArray = []\n for(let i = 0; i < integer; i++){\n myArray.push(word);\n }\n return myArray;\n\n}", "function myFunction(string, num1){\n var array = [];\n for(i = 0; i < num1; i++)\n array.push(string);\n return array;\n}", "function myFunction(st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the amount of a price in a given currency. If the amount for the currency is not defined in the price object it will be computer from the euro amount.
function getAmountInCurrency(price, currency, convertFromEuro) { return currency in price ? price[currency] : convertFromEuro(price["eur"], currency); }
[ "function getAmountInCurrency(price, currency, convertFromEuro) {\n return currency in price ?\n price[currency] :\n convertFromEuro(price[\"eur\"], currency);\n }", "toDecimal(currency) { return priceToDecimal(this.value(currency)); }", "function toCents(priceEur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Horizontal direction to the right
*directionHorizontalRight() { yield this.sendEvent({ type: 0x03, code: 0x00, value: 255 }); }
[ "function directionLeftToRight() {\n currentOffset.x = -50;\n offsetX = -1;\n\n if (fromLeftBottom) {\n currentOffset.y = -(backgroundSize.y - contentSize.y) + 60;\n offsetY = 1;\n fromLeftBottom = false;\n }\n else {\n currentOffset.y =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force selectionChange when editable was focused. Similar to hack in selection.js~620.
function onEditableFocus() { // Gecko does not support 'DOMFocusIn' event on which we unlock selection // in selection.js to prevent selection locking when entering nested editables. if ( CKEDITOR.env.gecko ) this.editor.unlockSelection(); // We don't need to force selectionCheck on Webkit, because on Webki...
[ "_updateFocus() {\n\t\tif ( this.isFocused ) {\n\t\t\tconst editable = this.selection.editableElement;\n\n\t\t\tif ( editable ) {\n\t\t\t\tthis.domConverter.focus( editable );\n\t\t\t}\n\t\t}\n\t}", "selectFocused(){this._focusedField.selectItem()}", "updateSelection(mustRead = false, fromPointer = false) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
"returns the longest side of each set of triangle data
function getLongestSides(triangles) { if (!triangles) throw new Error("triangles is required"); //take each item in array and put in decreasing number order using .sort, return first index using slice function sortNumber(a, b) { return b - a; } let sortNums = triangles.map(n => n.sort(sortNumber)[0]); ...
[ "function calcLongestSide(a,b)\n{\n\treturn Math.sqrt((a*a) + (b*b));\n}", "function maximumPerimeterTriangle(sticks) {\n let max = -1;\n return sticks\n .sort((a, b) => a - b)\n .reduce(\n (acc, curr, idx) => {\n if (idx + 2 < sticks.length) {\n if (curr + sticks[idx + 1] > sticks[id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the simulation to be evening
evening() { this.time.setHours(17); }
[ "function _updateSimulation() {\n\n _updateTime(balls);\n _updatePositions(balls);\n _updateInfections(balls);\n\n _drawBackground();\n\n for(var i = 0; i < balls.length; ++i) {\n _drawBall(balls[i]);\n };\n\n document.getElementById(\"current_day_badge\").innerHTML = \"Day \" + currentDay;\n\n if(0 === ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the component has an ngModel controller, unregister it when the scope is destroyed.
$onDestroy () { if (this[NG_MODEL_CTRL]) { this[FORM_CONTROLLER].$unregisterControl(this); } }
[ "function deregisterScope(model, $scope) {\n\t\t\tmodel = angular.isArray(model) ? model : [model];\n\t\t\tangular.forEach(model, function (m) {\n\t\t\t\tRepositoryService.get(m.className()).deregisterModel(m, $scope);\n\t\t\t});\n\t\t}", "$onDestroy() {\n this.scope = null;\n }", "$onDestroy() {\n this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for each reward save multiple shipping options
function saveShippingOption(reward, rewardID) { var shipping = $scope.campaign.rewards[$scope.campaign.rewards.indexOf(reward)].shipping; angular.forEach(shipping, function(obj) { if (obj.shipping_option_type_id == 1) { delete obj.country_id; } //for each shipping options use post/put...
[ "async addReward(values) {\n\t\tconst data = {\n\t\t\trequestId: this.requestId,\n\t\t\tfavourType: values.favourType,\n\t\t\tquantity: values.quantity\n\t\t};\n\t\tawait axios.patch('/request/add-reward', data, config);\n\t}", "function multiShippingAddresses() {\n var multiShippingForm = app.getForm('multish...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given Array of alternate Ext namespaces builds list of patterns for detecting Ext.define: ["Ext","Foo"] > ["Ext.define", "Ext.ClassManager.create", "Foo.define", "Foo.ClassManager.create"]
function build_ext_define_patterns(namespaces) { var mappedNamespaced = _.map(namespaces, function(ns) { [ns + ".define", ns + ".ClassManager.create"] }); return _.flatten(mappedNamespaced); }
[ "function detect_ext_define(cls, ast) {\n // defaults\n cls[\"extends\"] = \"Ext.Base\";\n cls[\"requires\"] = [];\n cls[\"uses\"] = [];\n cls[\"alternateClassNames\"] = [];\n cls[\"mixins\"] = [];\n cls[\"aliases\"] = [];\n cls[\"members\"] = [];\n cls[\"code_type\"] = \"ext_define\";\n \n each_pair_in_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print ClassBody, collapses empty blocks, prints body.
function ClassBody(node, print) { this.push("{"); if (node.body.length === 0) { print.printInnerComments(); this.push("}"); } else { this.newline(); this.indent(); print.sequence(node.body); this.dedent(); this.rightBrace(); } }
[ "function ClassBody(node, print) {\n this.push(\"{\");\n if (node.body.length === 0) {\n print.printInnerComments();\n this.push(\"}\");\n } else {\n this.newline();\n\n this.indent();\n print.sequence(node.body);\n this.dedent();\n\n this.rightBrace();\n }\n}", "function printTopBlock() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper function to get path of a demo image
function image(relativePath) { return "img/core-img/" + relativePath; }
[ "getPath() {\n let path = '' + this.theme+'-images'+ '/';\n return path;\n }", "function image(relativePath) {\n\treturn \"../../images/\" + relativePath;\n}", "function getImagePath(src) {\n const index = src.indexOf(twelvety.dir.images)\n const position = index >= 0 ? index + tw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a PointString3d from points.
static create(...points) { const result = new PointString3d(); result.addPoints(points); return result; }
[ "static createPoints(points) {\n const ps = new PointString3d();\n ps._points = PointHelpers_1.Point3dArray.clonePoint3dArray(points);\n return ps;\n }", "function Point3D(x, y, z) {\r\n this.x = x;\r\n this.y = y;\r\n this.z = z;\r\n}", "function toTHREE(points) {\r\n var cp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
defines a namespace object. This hides a "privates" object on object under the "key" namespace
function defineNamespace(object, namespace) { var privates = Object.create(object), base = object.valueOf; Object.defineProperty(object, 'valueOf', { value: function valueOf(value) { if (value !== namespace || this !== object) { return base....
[ "function S_namespace (pre){ // if this is the first then the pre will be null\n this._map = new Map()\n this._pre = pre //pre could be another S_namespace instance or NULL\n}", "setNamespace(namespace){this._namespace=namespace;return this;}", "function setNamespace(_namespace){\n namespace = getNamespace...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function translate() that will translate a text into "Rovarspraket". That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
function translate(phrase){ var newPhrase = ""; for (count=0; count<phrase.length; count++){ newPhrase = newPhrase + phrase[count]; if (!isVowel(phrase[count]) && phrase[count] !== " "){ newPhrase = newPhrase + "o" + phrase[count]; } } return newPhrase; }
[ "function translate(text) {\n var newText = '';\n for (var i = 0; i < text.length; i++) {\n if (text === ('a' || 'e' || 'i' || 'o' || 'u')) {\n return text[i];\n } else {\n return (text[i] + \"o\" + text[i])\n }\n }\n}", "function translate(phrase){\n\tvar newst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
dialogElements all dialogs have elements define the controls of the dialog.
static get dialogElements() { SuiLayoutDialog._dialogElements = typeof(SuiLayoutDialog._dialogElements) !== 'undefined' ? SuiLayoutDialog._dialogElements : [{ smoName: 'applyToPage', parameterName: 'applyToPage', defaultValue: -1, control: 'SuiDropdownComponent', label:...
[ "static get dialogElements() {\n SuiLayoutDialog._dialogElements = typeof(SuiLayoutDialog._dialogElements) !== 'undefined' ? SuiLayoutDialog._dialogElements :\n [{\n smoName: 'pageSize',\n parameterName: 'pageSize',\n defaultValue: SmoScore.pageSizes.letter,\n control: 'SuiDropdo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a single frame (1/60s NTSC, 1/50s PAL).
runFrame() { const cpu = this.cpu; const ppu = this.ppu; const apu = this.apu; while (!ppu.frameEnded) { cpu.tick(); ppu.tick(); ppu.tick(); ppu.tick(); if (this.tickAPU) { apu.tick(); } this.tickAPU = !this.tickAPU; } ppu.frameEnded = false;...
[ "function drawLoop(){\n // Reset to beginning after reaching final frame\n if (Globals.frame > Globals.totalFrames) { Globals.frame = 0;}\n\n // Update range, draw simulation at that frame, and increment counter\n $(\"#simulatorFrameRange\").val(Globals.frame)\n \n // Assign a keyframe if the current frame is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getEmailSentUI shows the "email sent" page.
function getEmailSentUI() { fetch('/api/emailSent', { method: 'GET' }).then(response => response.text()) .then(res => { var mainBody = document.getElementById('main-body'); mainBody.innerHTML = res; selectIcon('home'); }); }
[ "function onEmailSent() {\n this.notifyAll(new Event(Config.DOWNLOAD_POPUP_VIEW.EVENT.EMAIL_SENT, {\n insertedEmail: this.emailInput.value,\n }));\n}", "function showEmail() {\n\tconst emailHTML = '<a href=\"mailto:contact@oxfordopenfreshers.online\">contact@oxfordopenfreshers.online</a>';\n\t$('.info-email'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that overrides the default copy behavior. We get the selection and use it, dispose of this registered command (returning to the default editor.action.clipboardCopyAction), invoke
function overriddenClipboardCopyAction(textEditor, edit, params) { //use the selected text that is being copied here getCurrentSelectionEvents(); //dispose of the overridden editor.action.clipboardCopyAction- back to default copy behavior clipboardCopyDisposable.dispose(); //execute the default ed...
[ "copySelection() {\n let selectedText = window.getSelection().toString();\n let preparedText = this._prepareTextForClipboard(selectedText);\n atom.clipboard.write(preparedText);\n }", "copyCommand() {\n if (this.selectedKeywords.count > 0) {\n return clipboardCopyPlainText(this.getSelections...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the input into an array of teams and into key value pairs of cities and scores. Returns null in case of a parsing error.
function parseInput( input_text ){ teams = []; scores = {}; cities = {}; const rows = input_text.split( "\n" ); if( rows.length < 2 ) return null; for( let i = 0; i < rows.length; i++ ){ console.log( "row = " + rows[i] ); if( ro...
[ "parseForTeamsAndScores() {\n let skipIndexes = 0;\n\n // For every index in inputString, find groups of alphabetic letters\n // that correspond to team names. Additionally, find groups of numbers\n // that correspond to scores. Push both of these to arrays within the.\n // class....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by AgtypeParsertypeAnnotation.
enterTypeAnnotation(ctx) { }
[ "enterAgType(ctx) {\n }", "enterType_declaration(ctx) {\n\t}", "function TypeofTypeAnnotation(node, print) {\n\t this.push(\"typeof \");\n\t print.plain(node.argument);\n\t}", "function TypeofTypeAnnotation(node, print) {\n this.push(\"typeof \");\n print.plain(node.argument);\n}", "enterSubtype_decl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the game board
function createBoard() { const board = document.querySelector('.game'); const rows = document.createElement('tr'); //Create the head row rows.setAttribute('id', 'HeaderRow'); rows.classList.add('row'); rows.addEventListener('click', (e) => { gamePlay(e); }); //Create the header column and append to header r...
[ "function createBoard() {\n board = new Gameboard(6,5);\n for (let i = 0; i < board.width; i++) {\n for (let j = 0; j < board.height; j++) {\n if (gameState.level < 6 )\n {\n createLevel1(board, i, j);\n }\n else {\n createLevel6(board, i, j);\n }\n }\n }\n placeBoar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FragmentName : Name but not `on`
function parseFragmentName(parser) { if (parser.token.value === 'on') { throw unexpected(parser); } return parseName(parser); }
[ "parseFragmentName() {\n if (this._lexer.token.value === 'on') {\n throw this.unexpected();\n }\n\n return this.parseName();\n }", "parseFragmentName() {\n if (this._lexer.token.value === 'on') {\n throw this.unexpected();\n }\n return this.parseName();\n }", "parseFragmentName() {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
expand first level if the tree has only one item visible
function treeExpandFirstLevel(tree) { if ($('#node-groups-tree li.folder').length == 1) { var itemId = $('#node-groups-tree li.folder').attr('id'); tree.open_node(itemId); } }
[ "expandNodeRecursive(){this._selectedField.expandRecursive()}", "_expandItemsByDefault(collapseBeforehand) {\n const that = this;\n\n if (that._menuItemsGroupsToExpand.length === 0 && !collapseBeforehand ||\n that.mode !== 'tree' && !that._minimized) {\n return;\n }\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deleting using both class_id and subject_id
static async deleteByboth(class_id, subject_id) { this.class_id = class_id this.subject_id = subject_id this.result = await pool.query( 'DELETE FROM subject_combination_tbl WHERE class_id =$1 AND subject_id = $2', [class_id, subject_id] ) return this.result.rowCount }
[ "function deleteSubject(req, res) {\n Subject.findByIdAndRemove(ObjectID(req.params.id), (err, subject) => {\n if (err) {\n res.send(err);\n }\n res.json({ message: `${subject.name} deleted` });\n });\n}", "function deleteSubject(subjectId) {\n return SubjectCollection.findByIdAndDelete(subject...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To collect droped users
drop(e) { this.setState({ selectedUsers: [ ...this.state.selectedUsers, // keeping old records ...this.state.users.filter( u => u.uuid === e.dataTransfer.getData("item") //filtering current droped record ) ] }); }
[ "visitDropUser(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "dropUser(name) {\n const drop = this.query({name: name});\n\n UserStore.signOutUser(drop);\n\n this.users = this.users.filter(user => user.name !== drop.name);\n this.updateUsersFile();\n }", "getRemovedUsers () {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the basic instruments using Gibberish
function createInstruments (Gibberish) { // The actual instruments const kick = new Gibberish.Kick({ decay: 0.2 }).connect() const snare = new Gibberish.Snare({ snappy: 1.5 }).connect() const hat = new Gibberish.Hat({ amp: 1.5 }).connect() const conga = new Gibberish.Conga({ amp: 0.25, freq: 400 }).connect() ...
[ "function setupInstruments () {\n\n // Initialise Gibber\n Gibber.init();\n\n // Create our drums loop, at 1/8 note length\n // x = kick\n // o = snare\n // * = hihat closed\n // - = hihat open (I think?)\n // . = nothing\n var drums = EDrums('x.o.x*o.x.oxx-o.',1/8);\n var bassSynth = Mono('bass').note.se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
==== create the rooms ==== load everything from the configuration and wire the properties into real files.
function setupRooms () { var roomConfig = game.gameData.room; // split the options from the rest of the settings object: _options = roomConfig.options; delete roomConfig.options; // save the variables from the options: currentRoom = _options.currentRoom; // make rooms from the rest of the array: for ...
[ "setupRooms() {\n\t\tconst startingRoom = sessionStorage.ta\n\t\t\t? JSON.parse(sessionStorage.ta).rooms\n\t\t\t: 'Lobby';\n\t\tconst roomsStateConfig = {\n\t\t\troom: {\n\t\t\t\tvalue: startingRoom,\n\t\t\t\ttriggers: [],\n\t\t\t},\n\t\t};\n\n\t\tthis.rooms = {};\n\t\tObject.keys(ROOMS.default).forEach((room) => {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates HTML for the favorite button
function generateFavoriteButton(user, story) { const isFavorite = user.isFavorite(story); const heartType = isFavorite ? 'fas' : 'far'; return `<div class="favorite"> <i class="${heartType} fa-heart"></i> </div>`; }
[ "function viewFavorites(favorite) {\n $(\"<h4 class='favorites-title'>\" + favorite.data().firstName + \"</h4>\").appendTo(\".favorites-body\");\n $(\"<p class='favorites-text'> Email: \" + favorite.data().email + \"</p>\").appendTo(\".favorites-body\");\n $(\"<p class='favorites-text'> Phone: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get each asset tag for the given plugin
function getAssets(p, platform) { return getAllElements(p, platform, 'asset'); }
[ "get assetNames() {}", "function getAllPluginVersions() {\n developer.Api('/plugins/' + FS__API_PLUGIN_ID + '/tags.json', 'GET', [], [], function (e) {\n logResponse(e, developer);\n });\n}", "getTags() {\n const tagList = [];\n for (const tag in this.tagDictionary) {\n tagList.pus...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A command where perform(), undo(), redo() all update the order bar. Intended to be augmented onto other commands that modify the order bar.
function updateOrderBarCommand () { return new Command(updateOrderBar,updateOrderBar,updateOrderBar); }
[ "execute(command) {\r\n command.execute();\r\n this.commandStack.push(command);\r\n this.redoStack = [];\r\n \r\n }", "function goUpdateUndoEditMenuItems()\n{\n goUpdateCommand('cmd_undo');\n goUpdateCommand('cmd_redo');\n}", "undo() {\r\n if (this.commandStack.length == 0)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if enemy has dead
isDead (){ if (this.health <= 0){ this.dead(); return true; } return false; }
[ "checkDeath(enemy) {\n const yBottomCheck = this.colliderPosY + this.colliderY > enemy.colliderPosY && this.colliderPosY + this.colliderY < enemy.colliderPosY + enemy.colliderY;\n const yTopCheck = this.colliderPosY > enemy.colliderPosY && this.colliderPosY < enemy.colliderPosY + enemy.colliderY;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
uploads the track GPX file and displays it on the map. NO route recalculation! required HTML5 file api
function handleUploadTrack(file) { ui.showImportRouteError(false); //clean old track from map (at the moment only one track is supported) map.clearMarkers(map.TRACK); if (file) { if (!window.FileReader) { // File APIs are not supported, e.g. IE ui.showImportRouteError(true); } else { ...
[ "function loadGPXFileIntoGoogleMap(map, filepath, altLatLong) {\n $.ajax({url: filepath,\n dataType: \"xml\",\n success: function (data) {\n var parser = new GPXParser(data, map);\n\n parser.setTrackColour(\"blue\"); // Set the track line colour\n parser.setTrackWidth(6); /...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inline the contents of the html document returned by the link tag's href at the location of the link tag and then remove the link tag. If the link is a `lazyimport` link, content will not be inlined.
_inlineHtmlImport(linkTag) { return __awaiter(this, void 0, void 0, function* () { const isLazy = dom5.getAttribute(linkTag, 'rel').match(/lazy-import/i); const importHref = dom5.getAttribute(linkTag, 'href'); const resolvedImportUrl = this.bundler.analyzer.urlResolver.resolv...
[ "function removeLink() {\n var selection,\n $link;\n\n // Aloha's unlink command only removes the href attribute, but\n // if there are other attributes, the anchor element is not\n // removed - we must do that manually\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
goes through the token list checks if there are active buy/sell orders places orders if no active orders found all orders have an expiration block based on the orderLife value so we don't have to bother to cancel them
async sendOrders() { var currentBlock = await EtherMiumApi.getCurrentBlockNumber(); try { for (let token of this.tokensList) { var found_buy_order = false; var found_sell_order = false; // check if there active orders var orders = await EtherMiumApi.getMyTokenOrders(token[0]); for (let ...
[ "function checkActiveOrders(orders) {\n // TODO if cllosed - close\n if (!tradingIsClosed) {\n orders = JSON.parse(orders);\n let isNoOrders = _.isEmpty(orders);\n \n let sellOrders = _.filter(orders[CURRENCY_PAIR], { type: 'sell' });\n let buyOrders = _.filter(orders[CURRENCY_PAIR], { type: 'buy' })...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse Solr search results into HTML
function parseSolrResults(resultJson) { var docs = resultJson["response"]["docs"]; var html = []; for (var i = 0; i < docs.length; i++) { var doc = docs[i]; var row = "slide name: " + doc["ppt_name"]+" slide page: " + doc["slide_number"] + " with title: "+doc["title_text"]+"<br>"; ...
[ "function parseSolrResults(resultJson) {\n var docs = resultJson[\"response\"][\"docs\"];\n var html = [];\n for (var i = 0; i < docs.length; i++) {\n var doc = docs[i];\n var names = doc[\"origin\"].join(\", \") + \" \";\n var date = \"(Published \" + doc[\"datePublished\"].slice(0, 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns object with x,y coordinates of donut chart label
function labelPosition(ctx, v) { ctx.font="300 14px Open Sans, sans-serif"; var l = new Object(); l.x = [0,0,0]; l.y = []; for(var i=0, len=v.length; i<len; i++) { var radPos = 0; if (i == 0) { radPos = 2-(v[0]/2); } else { radPos = 2-(v[i]/2+v[i-1]/2); } l.x[i] = (graphWidth/2+Math.cos(radPos*Math...
[ "determine_label(x, y) {\n if (x == 0) return [\"left\", 5, 5];\n if (x == scopeList[this.id].layout.width) return [\"right\", -5, 5];\n if (y == 0) return [\"center\", 0, 13];\n return [\"center\", 0, -6];\n }", "calcTextPosition() {\n let coords = this.circle.calcOCoords();...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A triangulation is collinear if all its triangles have a nonnull area
function collinear(d) { const { triangles , coords } = d; for(let i = 0; i < triangles.length; i += 3){ const a = 2 * triangles[i], b = 2 * triangles[i + 1], c = 2 * triangles[i + 2], cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1]) - (coords[b] - coords[a]) * (coords[c + 1] - coords[a...
[ "function collinear$1(d) {\n const {triangles, coords} = d;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = 2 * triangles[i],\n b = 2 * triangles[i + 1],\n c = 2 * triangles[i + 2],\n cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
6. Creating pairs example input: [a,b,c,d] 4 example output: 'a, b', 'b, c', 'c, d' input of size n n n or n^2 O(n^2) > polynomial complexity
function createPairs(arr) { for (let i = 0; i < arr.length; i++) { // O(n) for (let j = i + 1; j < arr.length; j++) { // O(n^2) console.log(arr[i] + ", " + arr[j]); } } }
[ "function createPairs(arr) {\n for (let i = 0; i < arr.length; i++) { // O(n)\n for(let j = i + 1; j < arr.length; j++) { // O(n)\n console.log(arr[i] + ', ' + arr[j] ); // O(1)\n }\n }\n}", "function createPairs(arr) {\n for (let i = 0; i < arr.length; i++) { // --> polynomial O(n^2) quadratic\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Special handling for hue switch commands
function handleHueSwitch(msg, lightNames) { switch (msg.payload.button) { case 1000: case 1001: case 1002: msg.payload = { on: true, red: 255, green: 255, blue: 255, bri: 100 }; node.status({ fill...
[ "set enableHue(value) {}", "get enableHue() {}", "function swatchHueClickHandler(e) {\n var swatchList = document.getElementsByClassName('swatch');\n [].forEach.call(swatchList, function(el) {\n el.classList.remove('active');\n });\n e.target.classList.add('active');\n \n hsl = [\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current score
function getScore() { return parseInt(currentScore); }
[ "function getScore() {\n return currentScore;\n}", "function getScore() {\n return score;\n }", "function getScore() {\n\treturn 0;\n}", "function getScore() {\n\t\treturn 0.0; //dummy\n\t}", "getScore() {\n\t\treturn this.score;\n\t}", "function getScore(){\n return score\n}", "function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function gets array of images from artist's gallery
async function getImages() { var gallery = await getGallery(); var featured = []; for (var i = 0; i < 5; i++) { featured.push(gallery.results[i].thumbs[1].src); } return featured; }
[ "function genImagesFromGallery() {\n fullImageUrls = []\n var allImages = myJQ(\".tm-gallery-view__thumbnail\");\n if (allImages) {\n allImages.each(function(index,value) {\n var imageUrl = value.src.replace(\"64x64m\",\"plus\");\n console.log(\"img imageUrl=\" + imageUrl);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If user edits one of the TinyMCE fields, call formStateChanged for that tab.
setTinyListener(){ var form = this $(document).bind('laevigata:tinymce:change', null, (e) => form.formStateChanged('.about-my-etd')); }
[ "function setChanged (){\n\tformModified = true;\n}", "formChanged() {}", "function textareaChange() {\n // Mark flag if edit operation is made\n $('#right-code').bind('input propertychange', function() {\n modal_edit = 1;\n })\n $('#left-code').bind('input propertychange'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setNumber_blockBased Input: 1 <= i, j, i_block, j_block <= 3 1 <= n <= 9 Results: None Side Effects: change this.numbers, this.candidates
setNumber_blockBased(i_block, j_block, i, j, n){ this.setNumber((i_block-1)*3+i, (j_block-1)*3+j, n); }
[ "setCandidate_blockBased(i_block, j_block, i, j, n){\r\n this.setCandidate((i_block-1)*3+i, (j_block-1)*3+j, n);\r\n }", "setCandidate(i, j, n){\r\n const I = i-1;\r\n const J = j-1;\r\n const N = n-1;\r\n\r\n const n_bit = 1<<N;\r\n this.candidates[I*9 + J] |= n_bit;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize a seneca entity to a structure accepted by dynamo and removes seneca attributes via .data$.
function serializeEntity(entity) { return attributes.wrap(entity.data$(false)); }
[ "function makeRawEntity(entity) {\n if (entity.entityAspect != null) {\n delete entity.entityAspect;\n }\n}", "function scrubEntity(entity) {\n\tentity = JSON.parse(JSON.stringify(entity));\n\n\tif (_.isFunction(entity.data$)) {\n\t\tentity = entity.data$();\n\t}\n\n\t/*eslint-disable */\n\tif (entit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using cast() saves having to type Vec.of so many times:
static cast(...args) { return args.map(x => Vec.from(x)); }
[ "function castToArray(val) {\n val = val || [];\n val = Array.isArray(val) ? val : (val == null ? [] : [val]);\n return val;\n}", "function FieldTypes_getCastValues() {\r\n\tvar retArray = new Array();\r\n\tvar temp;\r\n\r\n\tfor (var i in FieldTypes.castingHash) {\r\n\t\ttemp = FieldTypes.castDBType(FieldType...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given object is an instance of LicenseConfiguration. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.
static isInstance(obj) { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === LicenseConfiguration.__pulumiType; }
[ "function _isObject(configurationObject) {\n\n // init\n var valid, validProperties, configurationProperties;\n\n // Check if configuration object\n valid = typeof configurationObject === 'object';\n configurationProperties = ['info', 'information', 'warn', 'warning', 'scs', 'success', 'includeLo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when clicking on a given $linkClicked the modal $modalToOpen is shown
function modalAlerts ($linkClicked, $modalToOpen) { $($linkClicked).on('click', function (e) { $($modalToOpen).modal('show') $(this).tooltip('hide') }) }
[ "function showModals($linkClicked , $modalToShow)\n {\n //Check if there's a checked checkbox and preserve state\n /*var boxes = $(linkClicked).parent().find('input')\n if( boxes.length > 0 )\n {\n for (var i = 0; i < boxes.length; i++) \n {\n if($...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change Select All Close Time
function selectAllCloseingTime(){ var closetimehrs = $("#restaurant_delivery_mon_close_hr").val(); var closetimemins = $("#restaurant_delivery_mon_close_min").val(); var closetimesess = $("#restaurant_delivery_mon_close_sess").val(); if( (closetimehrs == "") || (closetimemins == "") ){ $("#resS...
[ "function selectAllCloseingTime(){\n\t\t\n\t\tvar closetimehrs = $(\"#restaurant_delivery_mon_close_hr\").val();\n\t\tvar closetimemins = $(\"#restaurant_delivery_mon_close_min\").val();\n\t\tvar closetimesess = $(\"#restaurant_delivery_mon_close_sess\").val();\n\t\t\n\t\tif( closetimehrs == \"\" || closetim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
UHelpUNIFACE : proc statement help
function UHelpUNIFACE(which) { w = window.open(which, "UnifaceHelpWindow", "scrollbars=yes,resizable=yes,width=300,height=150"); if (uTestBrowserNS()) { w.focus(); } }
[ "function uciCmd(cmd){\n console.log(\"[INPUT] UCI: \" + cmd);\n engine.postMessage(cmd);\n }", "function ShowUsage( )\r\n{\r\n EnterFunction( arguments );\r\n\r\n /*\r\n * see if we were asked for help\r\n */\r\n if( g_oMessages.szCmdOpts.indexOf( \"?\" ) == -1 )\r\n {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the general comment
function saveGeneralComment(sync, successCallback, errorCallback) { var gradeable = getGradeable(); if ($('#extra-general')[0].style.display === "none") { //Nothing to save so we are fine if (typeof(successCallback) === "function") { successCallback(); } return; ...
[ "saveComment() {\n let comment = get(this, 'comment');\n\n this.sendAction('saveComment', comment);\n }", "function saveGeneralComment(sync, successCallback, errorCallback) {\n var gradeable = getGradeable();\n\n if ($('#extra-general')[0].style.display === \"none\") {\n //Nothing to sav...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A wrapper object around a Leaflet layer object that is used for defining layer control behavior. layer: The layer object to be controlled (REQUIRED). name: The caption that should be used to display the layer in the layer control (REQUIRED). groupName: If more than one LayerControlItem is given the same groupName, they...
function LayerControlItem(layer, name, groupName, base, labelable) { this.layer = layer; this.name = name; this.groupName = groupName || name; this.base = !!base; this.labelable = !!labelable; }
[ "function addBasicLayer(layer) {\r\n var thisLayer = null;\r\n if (layer.objects)\r\n thisLayer = L.geoJson(layer.objects.features);\r\n else if (layer.tiles)\r\n thisLayer = L.tileLayer(layer.tiles, { id: layer.name });\r\n // else.. add other types of layers\r\n if (thisLayer != null)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function clears the memory of the calculator
function clearMemory(){ $values.innerText=0; numberIsClicked=false; operatorIsClicked=false; equalsToIsClicked=false; myoperator=""; numberOfOperand=0; }
[ "function clearCalculator() {\n calculator.displayNumber = '0';\n calculator.operator = null;\n calculator.firstNumber = null;\n calculator.waitingForSecondNumber = false;\n}", "function clearCalculator() {\n calculator.displayNumber = \"0\";\n calculator.operator = null;\n calculator.firstNumber =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add api version header to endpoint operation
function addApiVersionHeader(endpointRequest) { var api = endpointRequest.service.api; var apiVersion = api.apiVersion; if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) { endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion; } }
[ "function addApiVersionHeader(endpointRequest) {\n\t var api = endpointRequest.service.api;\n\t var apiVersion = api.apiVersion;\n\t if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) {\n\t endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion;\n\t }\n\t}", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a Movement into the Movement List
addMovement(e) { e.preventDefault(); let movement = { id: new Date(), description: this.state.description, amount: this.state.amount }; this.setState({ movements: [...this.state.movements, movement] }); this.setState({ description: '', amount: 0 }); }
[ "function addMove(){\n return data.push(newMove());\n }", "function Add(unit : GameObject){\n\tunit.GetComponent(UnitControl).hasMoved = true;\n\tunits[TotalUnitCount] = unit;\n\tTotalUnitCount++;\n\tUnitsMoved++;\n}", "addMove() {\n\t\tif (Math.ceil(this.allMoves / this.players.length) == 1) {\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function Reveal cell if there no bomb around
function reveal(_index) { if (!$cell[_index].classList.contains('cell-bomb')) { $cell[_index].classList.add('secure'); _index = parseInt($cell[_index].getAttribute('data-index')) - 1; if (!$cell[_index + 1].classList.contains('cell-bomb')) { $cell[_index + 1].classList.add('secure'); if (b...
[ "function expandShown(elCell, i, j) {\n var cell = gBoard[i][j];\n // CR: if (cell.isMarked || cel.isShown) rutern Will be better\n if (cell.isMarked === true) return;\n if (cell.isShown === true) return;\n if (cell.isBomb === true) {\n gameOver();\n // CR: there is no need to return, \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Example: filterPalindromes([ "word", "Ana", "race car" ]) output: [ "Ana", "race car" ]
function filterPalindromes (words) { // Write your code here, and // return your final answer. let output = [] for (let i = 0; i < words.length; i++){ let word = words[i].length - 1 if (words[i][0].toLowerCase() === words[i][word].toLowerCase()){ output.push(words[i]) } } return output }
[ "function filterPalindromes (words) {\n let palindromesArr = [];\n for ( let i = 0; i < words.length; i++ ) {\n let flip = words[i].split('').reverse().join('');\n flip = flip.toLowerCase().split(' ').join('');\n console.log(flip);\n if ( flip === words[i].toLowerCase().split(' ').join('') ) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function that recusively compares newNode with curr to place in the BST O(logn) if balanced
_insertNode(curr, newNode){ if(newNode.data <= curr.data){ // if newNode <= curr then Go or Insert Left if(curr.left === null){ curr.left = newNode; this.nodeCount++; }else{ this._insertNode(curr.left,newNode); } }else{ ...
[ "insertRecursively(val, currNode = this.root) {\n const addingNode = new Node(val);\n if (!this.root) {\n this.root = addingNode;\n return this;\n }\n\n if (val < currNode.val) {\n if (!currNode.left) {\n currNode.left = addingNode;\n return this;\n }\n this.insert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns report rows based on query. Returns rowarray only contains keyvalues
function getReportRows(query) { var rows = []; var report = AdWordsApp.report(query); var rowsIterator = report.rows(); while ( rowsIterator.hasNext() ) { rows.push( rowsIterator.next() ); } return rows; }
[ "get keyRows() {\n return (this.rows || [])\n .map((row, index) => ({ [this.keyField]: index + '', ...row }))\n .map(row => ({ ...Table.BASIC_ROW_CONFIG, ...row, ...{ _identity: row[this.keyField] } }));\n }", "get rows(){\n //Bah, I hate declaring variables up here, but got...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method updates the angle between the angle between the mouse and the centre of the slider when a click is detected.
handleClick(e) { this.updateAngles(e); }
[ "updateAngles(e) {\n var currX = e.pageX;\n var currY = e.pageY;\n var angleInRadians = Math.atan2(currY - this.state.sliderCentreY, currX - this.state.sliderCentreX);\n var angleInDegrees = (Math.round((180 / Math.PI) * angleInRadians) + Constants.MAX_DEG - Constants.ANGLE_OFFSET_DEG) %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store JSON object into the current context with a given id
set(id, object){ localStorage.setItem(`${this.state.context}-${id}`, JSON.stringify(object)); }
[ "function modJson(id, newEntry) {\n json.id = newEntry\n}", "function saveTaskData(id, obj)\n{\n const data = $(\"body\").data();\n const activeTasks = data.tasks.active;\n activeTasks[id] = obj;\n}", "function addToJSON(obj) {\n jsonInput[obj.id] = obj.value;\n}", "function setContext(id) {\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for selected seats
function updateSelectedSeats() { if(ticketPrice == 800) { showCoachType.innerText = "AC Normal" } else if(ticketPrice == 1200) { showCoachType.innerText = "AC Business" } else if(ticketPrice == 400) { showCoachType.innerText = "Non AC" } const selectedSeats = document.queryS...
[ "function selectSeat (event) {\n // Check if a free seat was clicked\n if (event.target.classList.contains('seat') &&\n !event.target.classList.contains('occupied')) {\n \n // Remove if exists a class or add it if it doesnt exists\n event.target.classList.toggle('selected');\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Task 5: As corporate wants to add more and more flavors to their lineup, they've realized that they need to remove flavors based on flavor name, as opposed to just arbitrarily removing the first or last flavor. Your task is to get an index by flavor name, and remove that flavor from the array. Your function should acce...
function removeFlavorByName(array, string) { string = array.indexOf(string); array.splice(string, 1); return array; }
[ "function removeFlavorByName(originalFlavors, flavor){\n // for-in loop to check for specified flavor only for indices in the array\n for(let index in originalFlavors) {\n // If we find the specified flavor, use the corresponding index to splice it out of the array\n if(originalFlavors[index] ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Requests the NetworkHealthState and updates the page.
requestNetworkHealth_() { this.networkHealth_.getHealthSnapshot().then(result => { this.networkHealthState_ = result.state; }); }
[ "function updateHealthDisplay(){\n healthDisplay.html(userHealth);\n}", "function getStatusAndUpdate() {\n console.info('Fetching status');\n var errorMsg = 'Error fetching status from monitor app';\n app.xhr.open('get', app.urls.api + '/status/', true);\n app.xhr.onreadystatechange = function () {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a button to confirm note changes
function createBtnConfirm() { let btnConfirm = document.createElement("button"); btnConfirm.className = "note-button note-button-bottom"; btnConfirm.addEventListener("click", function () { saveNotesToLocalStorage(); }); btnConfirm.appendChild(createImgConfirm()); return btnConfirm; }
[ "function closeNewNote() {\n \n const addNotebtn = document.createElement('button')\n addNotebtn.id = 'add-note-btn'\n addNotebtn.name = 'add-note'\n addNotebtn.innerText = '+ create a new note'\n\n const newNote = document.querySelector('div.new_note')\n newNote.parentElement.replaceChild(addN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }