query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Push a path to the buffer and draw it on the canvas
function pushPath(data){ pathBuffer.push(data) let cvx = document.getElementById('canvas'); let ctx = cvx.getContext('2d'); drawOnCanvas(ctx, data.canvas.width, data.canvas.height, data.paths[0].x1, data.paths[0].y1, data.paths[0].x2, data.paths[0].y2, data.color, data.thickness) }
[ "drawPath() {\n\t\tif (this.drawing) {\n\t\t\trenderingContext.beginPath();\n\t\t\trenderingContext.moveTo(this.previousPos.x, this.previousPos.y);\n\t\t\trenderingContext.lineTo(this.position.x, this.position.y);\n\t\t\trenderingContext.closePath();\n\t\t\trenderingContext.stroke();\n\t\t}\n\t}", "drawPath() {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the motors status moving right
goRight(){ gpio.write(this.motors.leftFront, true); }
[ "function ChangeMotorDirection() {\n\t// swap motor direction\n\tmotorDirection *= -1;\n}", "motionRight() {\n this.speed = this.maxSpeed;\n }", "control_moveRight(){\n\t\tvar spd = 3;\n\t\tthis.acc += 0.1; \n\t\tif(this.acc > spd)\n\t\t\tthis.acc = spd;\n\n\t\tvar mov = vec2.fromAng(this.rotation + Math.PI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the connection protocol with default value.
getProtocolWithDefault(defaultValue) { return super.getAsStringWithDefault("protocol", defaultValue); }
[ "getProtocol() {\n return super.getAsString(\"protocol\");\n }", "getProtocol() {\r\n return this._protocol;\r\n }", "get protocol() {\n this._logService.debug(\"CMMethod.get protocol\");\n\n return this._protocol;\n }", "function YSerialPort_get_protocol()\n {\n if (this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notification channel for node resource
function NodeChannel(BaseChannel, NodeChannelConstant) { //setup and return service var nodeChannelService = { //node retrieve request pubRetrieveConfirmed : pubRetrieveConfirmed, subRetrieveConfirmed : subRetrieveConfirmed, pubRetrieveFailed : pubRetrie...
[ "function notify() {\n connection.send(\"notifyWatching\");\n}", "function notify() {\n connection.send(\"NotifyWatching\")\n}", "function rtcommPresenceNode(n) {\r\n RED.nodes.createNode(this,n);\r\n\t var subtopic = n.subtopic;\r\n this.topic = (n.topic || '/rtcomm/')+'sphere/'+subtopic;\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a function for snippetsWorkspaceEncodedIdNodeIdPut / Identical to &x60;UPDATE /snippets/encoded_id&x60;, except that this endpoint takes an explicit commit revision. Only the snippet&39;s \"HEAD\"/\"tip\" (most recent) version can be updated and requests on all other, older revisions fail by returning a 405 sta...
snippetsWorkspaceEncodedIdNodeIdPut(incomingOptions, cb) { const Bitbucket = require('./dist'); let defaultClient = Bitbucket.ApiClient.instance; // Configure API key authorization: api_key let api_key = defaultClient.authentications['api_key']; api_key.apiKey = incomingOptions.apiKey; // Uncomm...
[ "postUpdate(op, pointer, params) {\n if (typeof op === 'string') {\n op = BlobObj.ops[op];\n }\n\n if (typeof op !== 'number') {\n return Promise.reject(new Error('Blob update op code must be a number or a valid op id string'));\n }\n\n if (op < 0 || op > 255) {\n return Promise.reject...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to update the replay
function updateReplay() { // Filter the events by time and then by options const filteredEvents = sessionEvents.filter(event => checkEvent(event)); const lastEvents = filteredEvents.filter(event => event.timeStamp >= prevTimeStamp); // Update the heat map and click path if (!playing) { heatMap.setData(fi...
[ "function replay() {\n reset();\n startTime();\n toggleModal();\n}", "replayStep() {\n if (this.recorder.endOfTape()) {\n this.emitEndOfReplayTape();\n } else {\n this.setState(this.recorder.replayStep());\n this.emitPositionUpdated(this.getPosition());\n }\n }", "replay () {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes the Listeners, to prevent repositioning of the banner picture
removeListener() { document.getElementById('banner-picture').removeEventListener('mousedown', this.mouseDownHandler); document.removeEventListener('mouseup', this.mouseUpHandler); document.getElementById('banner-picture').removeEventListener('mouseenter', this.mouseEnterHandler); documen...
[ "function remFun(){\n opacityDiv.style.opacity = \"\";\n document.removeEventListener(\"mousemove\" , moveCropper);\n document.removeEventListener(\"mouseup\" , remFun);\n document.removeEventListener(\"mousedown\" , moveCropper);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called on paint. SubGrid has its width so this is the earliest time to configure the TimeAxisViewModel with correct width
onTimelinePaint() { const me = this; if (!me.subGrid.insertRowsBefore) { return; } me.isPainting = true; me.timeAxisViewModel.on({ update: me.onViewModelUpdate, thisObj: me }); // Upon paint we need to pass the forceUpdate flag in case we are sharing the TimAxisViewMode...
[ "recalculateTimes () {\n let max = this.state.times.timeScale * 60;\n let min = this.state.times.timeScale;\n let steps = max / min;\n let percent = this.state.times.timeZoom / 100;\n this.state.times.timePerPixel = this.state.times.timeScale * steps * percent + Math.pow(2, this.state.times...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a question from a room. //TODO catch errors here by promise resolution on remove call or callback
function removeQuestion(roomCode, question_id) { var ref = firebase.database().ref("Rooms/" + roomCode + "/Questions"); ref.child(question_id).remove(); }
[ "removeQuestion(question) {\n const questionID = MentorQuestions.getID(question);\n this._collection.remove({ questionID });\n }", "function removeQuestion() {\n questions.pop();\n}", "function removeQuestion() {\n game.question.splice(qIndex, 1);\n}", "function deleteQuestion() {\n var questionID...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes an AJAX request to the /search endpoint of the API, using the query string that was passed in if successful, updates model.browseItems appropriately and then invokes the callback function that was passed in
function searchMovies(query, callback) { $.ajax({ url: api.root + "/search/movie", data: { api_key: api.token, query: query }, success: function(response) { model.browseItems = response.results; callback(response); } }); }
[ "function performSearch() {\n var url = siteUrl + 'book',\n data = {\n 'quick': $fields.quick.val(),\n 'title': $fields.title.val(),\n 'subtitle': $fields.subtitle.val(),\n 'author': $fields.author.val(),\n 'series': $field...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a random String with the given length. Is needed to generate the Author Ids
function _randomString(len) { // use only numbers and lowercase letters var pieces = []; for(var i=0;i<len;i++) { pieces.push(Math.floor(Math.random()*36).toString(36).slice(-1)); } return pieces.join(''); }
[ "randomString( length ) {\n let lgth = length;\n if ( lgth === undefined ) { lgth = 40; }\n const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n let result = '';\n for ( let i = lgth; i > 0; i -= 1 ) result += chars[ Math.floor( Math.random() * chars.length ) ];\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function removes and event attributes (onerror, onload etc.) from the given html text
function sanitizeText(html) { if (typeof html !== 'string') { return html; } var value = "<div>" + html.replace(/(\s)(on(?:\w+))(\s*=)/, '$1xss-$2$3') + "</div>"; var elems = $($.parseHTML(value, null, false)); elems.find('*').each(function() { sanitizeElement(this); }); return elems.html();...
[ "static removeOnAttributes(html) {\n\t\tArray.from(html.attributes).forEach(attribute => {\n\t\t\tif (attribute.name.toLowerCase().startsWith('on')) {\n\t\t\t\thtml.removeAttribute(attribute.name);\n\t\t\t}\n\t\t});\n\t\tArray.from(html.children).forEach(EmailFrame.removeOnAttributes);\n\t}", "function cleanup(ht...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves handle(s) by a percentage (bool, % to move, [% where handle started, ...], [index in scope_Handles, ...])
function moveHandles ( upward, proposal, locations, handleNumbers ) { var proposals = locations.slice(); var b = [!upward, upward]; var f = [upward, !upward]; // Copy handleNumbers so we don't change the dataset handleNumbers = handleNumbers.slice(); // Check to see which handle is 'leading'. ...
[ "function moveHandles(upward, proposal, locations, handleNumbers) {\n var proposals = locations.slice();\n var b = [!upward, upward];\n var f = [upward, !upward];\n // Copy handleNumbers so we don't change the dataset\n handleNumbers = handleNumbers.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Class destructor. Removes all clients.
destructor() { Object.keys(this.clients).forEach((hash) => { this.removeClient(hash); }); }
[ "deleteAll() {\n this.clients.clear();\n }", "function removeClients(){\n clients = [];\n clientIO.removeClients();\n}", "closeAllClients() {\n this._clients.forEach((client) => {\n client.terminate();\n // clients are being removed from the set in the closing callback\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO : fix the above duplicate references, which exist now for backward compatibility with previouslyh authored code apply find and replace accross the codebase jstr() : public function for stringified objects and arrays (uses pretty print style)
function jstr(obj) { return JSON.stringify(obj); }
[ "_stringify (value) {\n //Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON#Polyfill\n var toString = Object.prototype.toString;\n var hasOwnProperty = Object.prototype.hasOwnProperty;\n var isArray = Array.isArray || function (a) { return toString.call(a) === '[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to parse an INLINE() item from the optimization log, returning the length of the parsed code. Returns 0 if it doesn't match and the line may be user output Returns 1 if it doesn't match and the line should be ignored
function tryParseInline (s) { if (/INLINE/.test(s)) { // Use non greedy match so that INLINE and FUNCTION SOURCE items // on the same line don't interfere, else the INLINE function name // would contain everything up to the ) in FUNCTION SOURCE () const [match, inlinedFn] = /INLINE \((.*?)\)...
[ "_checkInlineCode(start)\n {\n // Note that we need to match the exact number of initial backticks.\n // This allows things like \"```` Start a code block with ``` ````\".\n if (!stateAllowedInState(State.InlineCode, this.currentRun, start))\n {\n return -1;\n }\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the first CCTalkToken in the payload
getNextToken() { //isMoreThen2Bytes //isPossibleCCTalkToken payload => 5 + data.length //hasChecksums //isVerofyedCCTalkToken //!isMoreThen2Bytes preservedDataBuffer //!isPossibleCCTalkToken slice data out next //!hasChecksums ...
[ "function getToken(c) {\n return c >= FIRST_TOKEN && c < FIRST_TOKEN + TOKENS.length ? TOKENS[c - FIRST_TOKEN] : undefined;\n}", "function currToken() {\n\treturn tokens[index];\n}", "get_token() {\n while (this.need_more_tokens()) {\n this.fetch_more_tokens();\n }\n if (this.to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
US14 No more than five siblings should be born at the same time
function US14(fileName) { var data = parseGedcom(fileName); var individualData = data.individualData; var familyData = data.familyData; var noError = true; for (let line = 0; line < data.length; line++) { var lineData = data[line].split(" "); if (lineData[2] === "FAM") { var FID = lineData[1].r...
[ "function born(n) {\n const f = [0, 0, 0, 1, 1, 2, 3, 5];\n if (n <= 7) {\n return f[n];\n }\n return born(n - 2) + born(n - 3) + born(n - 4) + born(n - 5) + born(n - 6)\n}", "function US15(fileName) {\n var data = parseGedcom(fileName);\n var individualData = data.individualData;\n var familyData = dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function postResetPassword makes a POST request to the API endpoint to edit the password of the specified user. Args: None
function postResetPassword() { const validatePasswords = validatePasswordMatch(password, confirmPassword); if (validatePasswords !== true) { setSubmitResult(validatePasswords); setIsError(true); return; } setIsLoading(true); setIsError(false); axios.post(process.env.REACT_APP_A...
[ "async function postResetPassword(req, res) {\n\n if (req.params && req.body.password) {\n\n let password_reset_token = req.params.id;\n let new_password = req.body.password;\n //finding the user\n var user = await User.findOne({\n password_reset_token: password_reset_token,\n password_reset_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get last paragraph in cell
getLastParagraph(cell) { while (cell.nextSplitWidget) { if (cell.nextSplitWidget.childWidgets.length > 0) { cell = cell.nextSplitWidget; } else { break; } } let lastBlock; if (cell.childWidgets.length > 0) { ...
[ "getLastParagraphInLastCell(table) {\n if (table.childWidgets.length > 0) {\n let lastrow = table.lastChild;\n let lastcell = lastrow.lastChild;\n let lastBlock = lastcell.lastChild;\n return this.getLastParagraphBlock(lastBlock);\n }\n return undefin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
decode (public|exported) receive a text and return a emv parsed object
function decode(emvString) { const emvObject = {}; // validate checksum if(!validateChecksum(emvString)){ throw new Error('checksum validation failed.'); }else{ // parse emv string let inputText = emvString; while(inputText.length > 0){ debug.log('inputText',...
[ "function decode(emvString) {\n const emvObject = {};\n // parse emv string\n let inputText = emvString;\n while (inputText.length > 0) {\n debug.log('inputText', inputText);\n let { emvItem, remainingText } = readNext(inputText);\n if (emvItem.id == 52) {\n let translate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the prevButton will only be available to go back one question
function prevQuestion() { // when the previous question renders, remove the prevButton prevFlag = false; // if the user originally clicked the correctAnswer, remove score if (correctAnswer) { correctAnswer = false; score--; } // then go back and render the old questio...
[ "function handlePrevButton() {\n if (currrentQuestionID >= 1 && currrentQuestionID <= questions.length) {\n setCurrrentQuestionID((prevCurrent) => prevCurrent - 1);\n }\n }", "function clickPrevious() {\n if ((currentState.questionNumber--) < 1) {\n alert(\"Error!\");\n }\n\n else {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Appends a task to a chosen note
async function appendTaskToNote() { const taskName = await CommandBar.showInput( 'Type the task name', "Append '%@'...", ); const notes = projectNotesSortedByChanged(); const re = await CommandBar.showOptions( notes.map((n) => n.title), 'Select note to append', ); notes[re.index].appendTodo...
[ "function addTask() {\n Task.addTask(info.newTask);\n info.newTask = \"\";\n }", "function makeTaskNote(se, app, haveSelection) {\n\tvar note = '';\n\n\t/*\n\t// make a CamelCase function Name based on the app identifier\n\tfunctionName = app.bundleIdentifier().toString();\n\tfunctionName = functionName.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To find functions by iterating through the global object enumeration: allowed by: Opera, Mozilla, spidermonkey, rhino not allowed by: IE To read script content: IE and Mozilla have script.text only if no 'src', but have xmlhttp for retrieval. Opera supports script.text sometimes, even if it came from a remote 'src'? Ko...
function jum_parse_window_scripts() { var scripts = jum_get_script_elements(); alert("(jsunit_wrap.js) about to examine " + scripts.length + " scripts for test function names"); var func_names = []; for(var i=0;i<scripts.length;++i) { var script = scripts[i]; //alert("script.src=" + script.src + " scrip...
[ "function _getAllTestFunctions() {\n var testFunctions = Array();\n\n for (var i in window) {\n if (i.indexOf('test_') == 0) {\n testFunctions.push(i);\n }\n }\n\n return testFunctions;\n}", "function globalTestFunctions() {\n // pass context into globalFunctions? \n const g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append trace call() AFTER assignment expressions. Highlight contains entire expression. Bindings include new values.
AssignmentExpression(path) { const { start, end } = path.node; path.insertAfter(createTraceCall({ bindings: getBindingsForScope(path.scope, this.bindings), ...getOffsettedRange(start, end, this.fnOffset), })); }
[ "function BindExpression(node, print) {\n print.plain(node.object);\n this.push(\"::\");\n print.plain(node.callee);\n}", "function BindExpression(node, print) {\n\t print.plain(node.object);\n\t this.push(\"::\");\n\t print.plain(node.callee);\n\t}", "function trace() {\n controllerObj.pushCommand(con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts any number of arguments, and returns the first one that is a string (even an empty string)
function firstString() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (typeof arg === "string") { return arg; } } }
[ "function firstString() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n for (var i = 0; i < args.length; i++) {\n var arg = args[i];\n if (typeof arg === \"string\") {\n return arg;\n }\n }\n}", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
4) Arrays destructivelyRemoveFirstKitten() removes the First kitten from the kittens array:
function destructivelyRemoveFirstKitten(){ kittens.shift(); return kittens; }
[ "function destructivelyRemoveFirstKitten() {\n kittens.shift();\n}", "function destructivelyRemoveFirstKitten() {\n kittens.shift();\n return kittens;\n}", "function destructivelyRemoveFirstKitten () {\n kittens.shift ()\n return kittens\n}", "function destructivelyRemoveFirstKitten(){\n kittens.shif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/Google Maps / / Helper function to check if a number is a float
function isFloat(n){ return parseFloat(n.match(/^-?\d*(\.\d+)?$/))>0; }
[ "function isFloat(value){\n var floatReg = /[0-9]+(\\.[0-9]+)?/g;\n if( value.search(floatReg) != -1 ){\n return true;\n }\n return false;\n}", "function isFloat(num) {\r\n\tif (IsNumber(num)) {\r\n\t\tvar str = num.toString();\r\n\r\n\t\tif (str.indexOf('.') != -1) {\r\n\t\t\treturn true;\r\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preserves the magnitude of a decimal number in a finite field, even if the order of the field is smaller than decStr. decStr split into chunks of size packingSize. Relies on a sensible packing size being provided (ZoKrates uses packingSize = 128).
function decToFieldPreserve(decStr, packingSize) { let bitsArr = []; bitsArr = splitDecToBitsN(decStr.toString(), packingSize.toString()); let decArr = []; // decimal array decArr = bitsArr.map(item => binToDec(item.toString())); return decArr; }
[ "function hexToFieldPreserve(hexStr, packingSize, packets) {\n let bitsArr = [];\n bitsArr = splitHexToBitsN(strip0x(hexStr).toString(), packingSize.toString());\n let decArr = []; // decimal array\n decArr = bitsArr.map(item => binToDec(item.toString()));\n // now we need to add any missing zero elements\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Patch Promise prototype. Usage: patch(Promise.prototype).
function patch(proto) { /** * Invoked whether or not the promise was resolved or rejected. * * Note: it is possible for f to override the value of the promise if it * throws an exception. */ proto.finally = function(f) { return this.then( function(value) { f(); return value }, functio...
[ "function patchV2(Promise, ns) {\n\tvar thenOriginal = Promise.prototype.then.__original;\n\n\t// Patch method\n\tshimmer.wrap(Promise, 'using', function(usingOriginal) {\n\t\treturn function() {\n\t\t\t// Bind `using` callback (last arg)\n\t\t\tvar argIndex = arguments.length - 1,\n\t\t\t\tcallback = arguments[arg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTIONS choose one of five titles on load this is just for fun tbh
function setTitle () { var min = 0; var max = 4; var random = Math.floor(Math.random() * (max - min + 1)) + min; var titleSet = [ "Love it if We Made it", "Another Day in Paradise", "Business of Misdemeanors", "The Poetry is in the Streets", "Truth is only Hearsay", "It Dies in Darkness" ]; ...
[ "function initTitle() {\n var r = Math.round(Math.random() * (titles.length - 1));\n $(\"title\").html(titles[r]);\n}", "function titleDisplaySetup()\n{\n titleDisplay('listMenuRoot', 'listMenuTitles');\n // ADD DIFFERENT TITLE AREAS HERE! Each must have a 'target' area in your page.\n //titleDisplay('otherMenu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loop through the array of focused controller and invoke close() TODO: We must have a way to add exceptions to the list based on the user flow
function closeAllVisibleControllers( ){ try{ for( var i in m_present_controllers ){ if( m_content_container.contains( m_present_controllers[ i ].getDisplayNode() ) ){ m_present_controllers[ i ].close(); } } }catch( e ){ ...
[ "function exit()\n{\n for(var controller in controllers)\n {\n\tcontrollers[controller].exit();\n }\n}", "closeAll() {\n let i = this.openModals.length;\n while (i--) {\n this.openModals[i].close();\n }\n }", "disconnectAll() {\n this.controllers.forEach((controlle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether url starts with a scheme (\w+://)
function hasScheme(url) { const hasSchemeRE = new RegExp('^\\w+://'); return hasSchemeRE.test(url); }
[ "function hasScheme(input) {\n var rscheme = /^(?:[a-z\\u00a1-\\uffff0-9-+]+)(?::|:\\/\\/)/i;\n return !!(rscheme.exec(input) || [])[0];\n }", "function hasScheme(input) {\n var rscheme = /^(?:[a-z\\u00a1-\\uffff0-9-+]+)(?::|:\\/\\/)/i;\n return !!(rscheme.exec(input) || [])[0];\n}", "function hasAllow...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The `playSequence` function, to play a sequence of frames
function playAnimation(sequenceArray) { //Reset any possible previous animations reset(); //Figure out how many frames there are in the range if (!sequenceArray) { startFrame = 0; endFrame = sprite.totalFrames - 1; } else { startFrame = sequenceArray[0]; e...
[ "function playSequence(sequenceArray) {\n if(!sprite.hasStarted){\n\n reset();\n\n startFrame = sequenceArray[0];\n endFrame = sequenceArray[1];\n numberOfFrames = endFrame - startFrame;\n\n //Compensate for two edge cases:\n //1. If the `startFrame` happens to be `0`\n if (sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the config's filename.
static getFileName() { // Can not have abstract static methods, so throw a runtime error. throw new sfdxError_1.SfdxError('Unknown filename for config file.'); }
[ "function _getConfigFilename() {\n return path.join(defines.PROJECT_HOME, CONFIG_FILENAME);\n}", "function getConfigFilename() {\n return configs.find((filename) => {\n return deps_ts_5.existsSync(filename);\n });\n }", "function getConfigFile() {\n let filepath = '/';\n if(flags.CONF...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a link and the corresponding oath tokens from which the user can authorize our backend to retrieve measurements from Withings
getAuthorizeLink() { /* Get oauth token */ return new Promise((resolve, reject) => { axios.get('http://localhost:3000/authorizelink') .then(response => ( resolve({ auth_link: response.data.url, token: response.data.token, ...
[ "getOAuthTemplate () {\n return {\n 'authentication': {\n 'authorizationUrl': '/authentication/v1/authorize',\n 'tokenUrl': '/authentication/v1/gettoken',\n 'refreshTokenUrl': '/authentication/v1/refreshtoken',\n 'scopes': {\n 'data:read': 'The application will be able t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a string to be used as a salt
function generateSalt() { var saltWord = bip39.generateMnemonic(8); var saltHashedBitArray = sjcl.hash.sha256.hash(saltWord); salt = sjcl.codec.base64.fromBits(saltHashedBitArray); }
[ "function getSalt() {\n\tvar salt_clear = \"\";\n\tvar possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\tfor (var i = 0; i < 30; i++) salt_clear += possible.charAt(Math.floor(Math.random() * possible.length));\n\treturn salt_clear;\n}", "function generateSalt() {\n\tvar buf = crypt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compares two date strings in 'yyyymmdd' format returns 1 if ymd1 is later than ymd2 returns 1 if ymd1 is earlier than ymd2 returns 0 of they are the same date
function compareDates(ymd1,ymd2){ // parse var y1 = parseInt(ymd1.slice(0,4)); var m1 = parseInt(ymd1.slice(5,7)); var d1 = parseInt(ymd1.slice(8,10)); var y2 = parseInt(ymd2.slice(0,4)); var m2 = parseInt(ymd2.slice(5,7)); var d2 = parseInt(ymd2.slice(8,10)); // compare years if(y1 > y2){ return 1 } else i...
[ "function date_compare(p_str_date1, p_str_date2) {\n date1 = new Date(ddmmyyyy_to_mmddyyyy(p_str_date1));\n date2 = new Date(ddmmyyyy_to_mmddyyyy(p_str_date2));\n year1 = date1.getFullYear() * 1;\n month1 = date1.getMonth() * 1;\n day1 = date1.getDate() * 1;\n\n year2 = date2.getFullYear() * 1;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the values for the key clientOs, from the Event History Results
@action getAllDeviceTypesFromEventHistoryResult() { return this.getAllValuesForKeyFromJSONObjectArray(this.EventHistoryAPIResult, 'clientOs'); }
[ "async getHistory(key) {\n\n let ledgerkey = this.ctx.stub.createCompositeKey(this.name, State.splitKey(key));\n const resultsIterator = await this.ctx.stub.getHistoryForKey(ledgerkey);\n let results = await this.getAllResults(resultsIterator, true);\n\n return results;\n }", "async...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the Dynamo request to get a pool by name.
function fetchPoolRequest(config, poolName) { return { TableName: config.table, Key: { id: "POOL:" + poolName, env: config.env } }; }
[ "function createPool() {\n return oracledb.createPool(config.db)\n}", "async function createPool() {\n axios\n .get(`http://localhost:5000/pools/${nextEvent.raceID}`)\n .then((res) => {\n // console.log(\"inside create pool\", res);\n if (res.data == null) {\n let pool = {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exercise: Given an array of positive, nonzero integers A and sum T, determine if A has a contiguous subarray that sums to T.
function hasContiguousSumOfT (a, t) { if(!a.length) { return false; } var start = 0, end = 0; var sum = a[0]; while ( end < a.length ) { if (sum === t) { return true; } if (sum < t) { sum += a[++end]; continue; } if (sum > t) { sum -= a[start++]; continue; } } return...
[ "function findSumSubArray(arr, sum) {\n let startI = 0;\n let currentSum = 0;\n\n for (let j = 0; j < arr.length; j++) {\n currentSum += arr[j];\n\n while (currentSum > sum) {\n currentSum -= arr[startI];\n startI++;\n }\n\n if (currentSum === sum) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use .reduce to get the total years of experience from the list of users. Once you get the total of years you can use the result to calculate the average.
function totalExperience(){ let total = users.reduce((accumulator, currentValue) => { console.log(`accumulator: ${accumulator}`); console.log(`currentValue: ${currentValue.yearsOfExperience}`); return accumulator + currentValue.yearsOfExperience; },0) console.log('total ' + total); return total / users.lengt...
[ "function getAverageAge(users) {\n return users.reduce((prev, user) => prev + user.age, 0) / users.length;\n }", "function getAverageAge(users) {\n let average = 0;\n let sum = 0;\n for (let key of users) {\n sum += key.age;\n console.log(sum);\n }\n average = sum / users.length;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We render the activity indicator if necesary
renderActivity() { if (this.state.scanning || (this.state.connected && !this.state.counterIsReaded)) { return( <ActivityIndicator size="large" color={ Utils.Constants.buttonBackgroundColor } style={ {marginTop: 20 } } ...
[ "function _displayIndicator() {\n // Render indicator\n var view = _renderIndicatorPartial();\n \n // Append and add indicator to statusbar\n $(\"#status-indicators\").prepend(view);\n StatusBar.addIndicator(INDICATOR_ID, $(\"#main-window-indicator\"), true);\n \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return any compound properties found in the given element's children.
function getCompoundPropertiesFromChildren( element ) { var properties = {}; $( element ) .children() .filter( "[data-property]" ) .each( function( index, element ) { var $element = Control( element ); var propertyName = $element.attr( ...
[ "children(element) {\n let ret = Mavo.Node.get(element);\n\n if (ret) {\n // Element is a Mavo node\n return [ret];\n }\n\n ret = $$(Mavo.selectors.property, element)\n .map(e => Mavo.Node.get(e))\n .filter(e => !element.contains(e.parentGroup.element)) // D...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds the light to array of lights
AddLight(light) { this._lights.push(light); }
[ "_registerLight(light) {\n this._lights.push(light);\n }", "function connectLight() {\n for (var i = 0; i < lightArray.length; i++) {\n setLights(lightSourceArray[i], lightArray[i]);\n }\n}", "function addLights() {\n var light0 = new BABYLON.PointLight('light0', new BABYLON.Vector...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endregion region PureCloud Gets more information about a PureCloud chat member
function getPureCloudMemberInfo(conversationId, memberId) { return new Promise((resolve, reject) => { let options = { url: `https://api.${PURECLOUD_ENVIRONMENT}/api/v2/webchat/guest/conversations/${conversationId}/members/${memberId}`, method: 'GET', headers: { ...
[ "async function listThreadMembers() {\r\n let pagedAsyncIterableIterator = await chatThreadClient.listMembers();\r\n let next = await pagedAsyncIterableIterator.next();\r\n while (!next.done) {\r\n let user = next.value;\r\n console.log(`User :${user.displayName}`);\r\n next = await pagedAsy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2. Write a function called 'addThree' that adds three numbers together and returns the result
function addThree(num1, num2, num3){ return num1+num2+num3; }
[ "function addThree(num1, num2, num3){\n return num1 + num2 + num3;\n}", "function addThree(num1,num2,num3) {\n return num1+num2+num3;\n}", "function addThree (num1, num2, num3) {\n var result = num1+num2+num3;\n return result;\n}", "function addThree (num1, num2, num3) {\n return (num1 + num2 + num3);\n}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method. Returns a new direction given an old one and the number of degrees you want to rotate.
static directionFromRotation(direction, degrees) { let shift = degrees > 0 ? degrees % 90 + 1 : -(degrees % 90 + 1); let newDir = direction + shift; return newDir < 0 ? newDir + 4 : newDir % 4; }
[ "function rotateDirectionTowards(dir1, dir2, amount){\n\tvar angleDiff = angleDifference(dir1, dir2);//((((dir2 - dir1) % 360) + 540) % 360) - 180;\n return (dir1 + Math.min(amount, Math.max(-amount, angleDiff)) + 360) % 360;\n}", "function rotate(increment){\n\t\trotation += increment;\n\t\t// console.log(\"C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loops over each flavor in function
function forEachFlavor(functionToDo) { var container = document.getElementById('container'); var flavors = container.getElementsByClassName('flavor'); for(var i = 0; i < flavors.length; i++) { functionToDo(flavors[i]); } }
[ "function trackFlavors() {\n for (var i = 0; i < 15; i++) {\n countFlavor('#var-flavors' + String(i), i);\n }\n }", "function extractFlavors() {\n // TODO\n}", "function extractFlavors() {\n var getFlavor = document.getElementsByClassName(\"flavor\");\n var flavorArray = [];\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get cache for type and identifier
function getCache(type, id, key) { if (id && id != -1 && RandomStorage[type] && RandomStorage[type][key+id]) { return RandomStorage[type][key + id]; } else { return null; } }
[ "static getCacheStore(type) {\n // Need to add validations. Also, for now the the cache name to passed\n // exactly as the name of the class (except don't prefix the Cache word.)\n if (type === undefined) return new InMemoryCache();\n let obj = (Function('return new ' + type + \"Cache\"))();\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This injects a meta tag with the name and id of 'mozillaheatmpatabident' with a GUID as the node content. This allows us to unambiguously determine the identity of each tab in the case that heatmap misses some tab manipulation events.
function inject_meta_tabident() { // check if the tag already exists, if it does - short circuit // and return the content var tabident_node = document.getElementById('mozilla-heatmap-tabident'); if (tabident_node) { return tabident_nodes[0].content; } var meta = document.createElement(...
[ "function attachIdentifierToPage(tab, identifier) {\n\tlet worker = tab.attach({\n\t\tcontentScriptFile: DATA.url(\"attach-meta-tag.js\"),\n\t\tonError: function(error) {\n\t\t\treportMessage(\"main.js: \"+error.fileName+\":\"+error.lineNumber+\": \"+error+\"\\nOn \"+tab.url);\n\t\t}\n\t});\n\t\n\tworker.port.emit(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ReplaceNthOccurence() DOESN'T WORK Purpose:Replace a string with another string, but only do it to the Nth occurence of that search string in the original Only one replacement of the searchStr will be done Inputs:the string in which to search, the string we want to replace, the occurence number we are interested in (e....
function ReplaceNthOccurence(original, searchStr, occurNbr, replaceStr) { console.info("ReplaceNthOccurence(): Changing full name from: " + original); var nth = 0; var changedStr = original.replace('/' + searchStr + '/g', function (match) { nth++; return (nth === occurNbr) ? replaceStr : match; }); console.in...
[ "function replaceNth(text, n, oldValue, newValue) {\n const words = text.split('');\n if (n <= 0 || n > words.filter(i => i === oldValue).length) return text;\n let nth = 0;\n return words.map((l) => {\n if (l === oldValue) {\n nth += 1;\n return nth % n === 0 ? newValue : l;\n }\n return l;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search By Age Between
function queryFromUserByAgeBetween(arr, start, end) { return arr.filter(function (ele) { return ((new Date().getFullYear() - new Date(ele.DOB).getFullYear()) > start && (new Date().getFullYear() - new Date(ele.DOB).getFullYear()) < end); }) }
[ "function ageFilter (student) {\n return student.age >= 18 && student.age <= 24;\n }", "function filterAge(minAge, maxAge) {\n return users.filter(function (user) {\n return user.age >= minAge && user.age <= maxAge;\n })\n}", "filterByAge(e) {\t\t\n\t\tdocument.getElementById(\"selected-a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set proper data for each difficulty
function setDifficulty(dif){ if(dif==='easy'){ elementsAroundMines.clear(); clear(); amountOfMines=10; elementsCount=100; difficulty='easy'; drawGame(100, '50vw', '80vh', '10%', '10%', 10, 10); } if(dif==='no...
[ "function set_difficulty(d){\n difficultyLevel = d;\n}", "function setDifficulty(level) {\n switch(level) {\n case 1:\n info.time = 2000;\n info.numberOfWeeds = 9;\n break;\n case 2:\n info.time = 1700;\n info.numberOfWeeds = 7;\n break;\n case 3:\n info.time = 1400...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We can use the Math.floor function to ensure that our calculator discards any remainders in Integer Division. Binary Numbers to Integer Strings To convert a nonbase10 number,num , of radix (r) to a base10 integer string, we use the syntax num.toString(r). The eval Function We can use this function to evaluate a string ...
function evaluate() { var operand = resultdiv.innerHTML.split(operator); resultdiv.innerHTML = Math.floor(eval(parseInt(operand[0],2) + operator + parseInt(operand[1],2) )).toString(2); operator = ''; }
[ "function evaluate(){\n if(operandString2 != \"\" && calculatorOn){\n operand2 = Number(operandString2);\n var result = 0;\n switch(operator){\n case \"plus\":\n result = operand1 + operand2; break;\n case \"minus\":\n result = operand1 - operand2; break;\n case \"times\":\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to remove notification
function removeNotification(ref) { SET.removeElem(SET.$(`body .content .notification-wrap .notification[data-ref="${ref}"`).getParent('notification-wrap')); }
[ "function removeNotification() { \n\tchrome.notifications.getAll(function(cb) {\n\t\tfor(var prop in cb){\n\t\t\tif(cb.hasOwnProperty(prop)) chrome.notifications.clear(prop);\n\t\t}\n\t});\n}", "function removeNotification() {\n\t\t$('.view-controls__results .notification').remove();\n\t}", "function removeNoti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for adding teams to the league
function addTeam(name, skill){ let tempTeam = createTeam(name, skill); leagueTeams.push(tempTeam); }
[ "function addTeams() {\n\n // add existing teams\n dataset.teams.map( addTeam );\n\n // limited number of teams? => add empty teams\n if ( my.max_teams ) {\n var needed = my.max_teams - dataset.teams.length;\n for ( var i = 0; i < needed; i++ )\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to verify the user's attendance.
_onVerifyAttendance(code, callback) { const { attendBooking, booking, validCodes } = this.props if (validCodes.indexOf(code) === -1) { return setTimeout(() => callback('Invalid code'), 1000) } attendBooking(code, booking.workshopID, (err) => { if (err) { return callback(err) ...
[ "markAttendance(username, attendance) {\n let currentStudent = this.findStudent(username);\n if (attendance == 'present') {\n currentStudent.markPresent();\n } else if (attendance == 'absent') {\n currentStudent.markAbsent();\n }\n\n }", "function checkEmployee...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check config properties for expected types / istanbul ignore next: not easy to test
function typeCheckConfig(componentName, config, configTypes) { for (var property in configTypes) { if (Object.prototype.hasOwnProperty.call(configTypes, property)) { var expectedTypes = configTypes[property]; var value = config[property]; var valueType = value && Object(__WEBPACK_IMPORTED_MODULE...
[ "function typeCheckConfig(componentName, config, configTypes) {\n for (const property in configTypes) {\n if (Object.prototype.hasOwnProperty.call(configTypes, property)) {\n const expectedTypes = configTypes[property];\n const value = config[property];\n let val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Type of the Optional decorator / constructor function.
function OptionalDecorator() {}
[ "function OptionalDecorator() { }", "function FunctionType() {\n}", "function createIsRequired(propTypeFn) {\n return (...params) => requireProp(...params) || propTypeFn(...params)\n}", "function DirectiveType(){}", "function isOptionalFunction(fn) {\n\treturn fn === undefined || fn === null || typeof fn =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewTackyboardForm component renders the controlled form for creating a new task.
function NewTackyboardForm({ setShowForm, setTaskboards }) { const INITIAL_VALUES = { _token: localStorage.getItem("_token"), name: "" }; const [formData, setFormData] = useState(INITIAL_VALUES); const handleChange = (evt) => { const { name, value } = evt.target; setFormData(currData => ({ ...currData, [...
[ "function generateTaskForm_(e){\n \n var formData = Utilities.jsonParse(UserProperties.getProperty('activeTask'));\n \n //Render form\n var vPanel = e.createVerticalPanel();\n \n vPanel.add(e.createHidden().setId('taskId').setName('taskId').setValue(formData.taskId));\n \n //vPanel.add(e.createTextBox().se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
input is public_key in base64 output. function checks which player is talking to server, returns 0
function verify_user(req) { var playerNumber = 0; if(player1.public_key_base64 === req.body.public_key_base64) { playerNumber = player1; } else if(player2.public_key_base64 === req.body.public_key_base64) { playerNumber = player2; } return playerNumber; }
[ "isValid (callback) {\n // TODO Needs better checking\n if (this.privKey &&\n this.privKey.public &&\n this.privKey.public.bytes &&\n Buffer.isBuffer(this.pubKey.bytes) &&\n this.privKey.public.bytes.equals(this.pubKey.bytes)) {\n callback()\n } else {\n callback(new Error('Ke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redux form/materialui render address select component
static renderAddressInput({input, label, meta: { touched, error }, children, ...custom }) { return ( <div> <FormControl error={touched && error} fullWidth> <Select native {...input} {...custom} inputProps={{ name: 'ownerAddress', ...
[ "function AccountSelector({ accountName, onChange }) {\n const styles = useStyles();\n const { accounts } = useWalletSelector();\n const [address, setAddress] = useState(\"\");\n const [validationError, setValidationError] = useState(true);\n\n const _onChange = (e) => {\n if(e.target.value.le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
separate a string str into chunks of given length len
function chunkString(str, len) { var _size = Math.ceil(str.length / len), _ret = new Array(_size), _offset; for (var _i = 0; _i < _size; _i++) { _offset = _i * len; _ret[_i] = str.substring(_offset, _offset + len); } return _ret; }
[ "function chunkString(str, len) {\n\tvar _size = Math.ceil(str.length/len),\n\t_ret = new Array(_size),\n\t_offset\n\t;\n\n\tfor (var _i=0; _i<_size; _i++) {\n\t\t_offset = _i * len;\n\t\t_ret[_i] = str.substring(_offset, _offset + len);\n\t}\n\n\treturn _ret;\n}", "function chunkString(str, size) {\r\n const...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If configured, set up the VPCrelated properties Returns the VpcConfig that should be added to the Lambda creation properties.
configureVpc(props) { if ((props.securityGroup || props.allowAllOutbound !== undefined) && !props.vpc) { throw new Error('Cannot configure \'securityGroup\' or \'allowAllOutbound\' without configuring a VPC'); } if (!props.vpc) { if (props.vpcSubnets) { th...
[ "configureVpc(props) {\n var _b;\n if ((props.securityGroup || props.allowAllOutbound !== undefined) && !props.vpc) {\n throw new Error('Cannot configure \\'securityGroup\\' or \\'allowAllOutbound\\' without configuring a VPC');\n }\n if (!props.vpc) {\n return unde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loop to fetch and store account history transactions and associated ranges specific to Steem blockchain
async getAccountHistoryFullSteem(wallet, delayBetweenFetches, latestIdToFetch) { let maxTransactions = 1000 + wallet.blockchain.parameters.transactionCountOffset; // Maximum number of transactions is 1000 - need -1 adjustment for Steem let latestIdToFetchReached = false; // Stops loop when prior transac...
[ "function transactionHistory() {\n\treturn new Promise(function(resolve, reject) {\n\t\tconsole.log(\"w3\", \"start transactionHistory\");\n\t\tvar data = [];\n\t\tvar latestBlockId = web3.eth.getBlock(\"latest\").number;\n\t\twhile (latestBlockId > 0) {\n\t\t\tvar block = web3.eth.getBlock(latestBlockId, true);\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_get(idx): get node at specified idx.
_get(idx) { let count = 0; let currNode = this.head; while (count != idx && currNode !== null) { ++count; currNode = currNode.next; } return currNode; }
[ "getNodeAtIndex(index) {}", "getAt(idx) {\n //Checks for a valid index\n if (idx >= this.length || idx < 0) {\n throw new Error(\"Invalid Index\");\n }\n //uses the _get() method defined above to get the node at that index and then returns its value\n return this._get(idx).val;\n }", "getAt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provide an variable as an argument. It will return a boolean value to let you know if it an array or not.
function isArray(variable) { return Array.isArray(variable); }
[ "function is_array(mixed_var) {\n return typeof(mixed_var) == \"object\" && (mixed_var instanceof Array);\n}", "function is_array( mixed_var ) { \n\t return ( mixed_var instanceof Array );\n\t}", "function isArray(variable){\n if(variable.constructor == Array){\n console.log(\"\\n\\n\\nVariable is ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns A, B, C, D values by specified probabilities
function random() { var num = Math.random(), lastIndex = probabilities.length - 1; s = 0; for (var i = 0; i < lastIndex; ++i) { s += probabilities[i]; if (num < s) { return values[i]; } } return values[lastIndex]; }
[ "function createProbability() {\n let blanks = Array(27).fill('blank');\n let grapes = Array(10).fill('grapes');\n let bananas = Array(9).fill('banana');\n let oranges = Array(8).fill('orange');\n let cherries = Array(5).fill('cherry');\n let bars = Array(3).fill('bar');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
request for hostUnique_ByHits service, calls 'callback' function.
function requestGetUnique_ByHits(query, callback) { // var url = hostUnique + format.queryToURLForm(slotValue_name, slotValue_country, slotValue_region, slotValue_content, slotValue_date, slotValue_solution); // var url = hostUnique_ByHits + format.queryToURLForm(slotValue_name, slotValue_country, slotValue_regio...
[ "function requestGetUnique_CompletedByHits(query, callback) {\n\n//\tvar url = hostUnique + format.queryToURLForm(slotValue_name, slotValue_country, slotValue_region, slotValue_content, slotValue_date, slotValue_solution); \n\n//\tvar url = hostUnique_ByHits + format.queryToURLForm(slotValue_name, slotValue_countr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines if a link is from AddToAny.
function rmlcwrIsAddToAny($link) { if ($link.parent().hasClass('a2a_full_footer') || $link.parent().hasClass('a2a_kit') || $link.hasClass('a2a_i')) { return true; } return false; }
[ "isFromOrAddedByTrustedContact() {\n if (this.isPrivate()) {\n return Boolean(this.get('name')) || this.get('profileSharing');\n }\n const addedBy = this.get('addedBy');\n if (!addedBy) {\n return false;\n }\n const conv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display Web Preview The purpose of this method is to display the preview for a html file. It shows the html window and hides any other display windows. It accepts paramaters for which windows (current or next) to hide/show as well as for the location of the html page to show. CURRENTLY NOT USED, THE PROGRAM DOESN'T ACC...
function displayWebPreview(previewWindowName, filePath, filename) { $("#" + previewWindowName + "SlideWebpage").attr('src', filePath + filename); $("#" + previewWindowName + "SlideWebpage").show(); $("#" + previewWindowName + "SlideImage").hide(); $("#" + previewWindowName + "SlideVideo").hide(); $("#nextEr...
[ "function preview() {\n\t\t\t\n\t\t\t\tif (typeof options.previewHandler === 'function') {\n\t\t\t\t\tpreviewWindow = true;\n\t\t\t\t} else if (options.previewInElement) {\n\t\t\t\t\tpreviewWindow = $(options.previewInElement);\n\t\t\t\t} else if (!previewWindow || previewWindow.closed) {\n\t\t\t\t\n\t\t\t\t\tif (o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: Gets all the quality inspection criteria Called by GET /v1/QAA/rangeValuesForRangeID/:rangeID =>gRangeValuesForRangeId() Input: rangeID Output: returns a promise that has the range values for this rangeID (rangeIdeal, rangeLow, rangeHigh) Time Complexity: O(Async)
function getRangeValuesForRangeId(rangeId) { let ourQuery = `SELECT rangeIdeal, rangeLow, rangeHigh FROM QAA.range_TB WHERE rangeID = ? `; return makeConnection.mysqlQueryExecution(ourQuery, mySqlConfig, rangeId); }
[ "function getRangeVals() {\n var rv = [];\n for (i = 1; i < 11; i++) {\n var rnam = \"range\" + i;\n rv.push(+document.getElementById(rnam).value);\n }\n return rv;\n}", "async function getRangeInfo (){\r\n let rangeInfo = await rp.get({\r\n url:'https://join.reckon.com/test1/r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Object used to delay Waitron.
function WaitronDelay () { this[POOL_NEXT] = null; var started = null; var onEnd = null; this.start = (id, callback) => { if (started && started !== id) { return null; } started = id; onEnd = callback; return this.end; }; this.end = error => { var callback = onEnd; var id = started; onEnd ...
[ "function delay(func, wait) {\n\n}", "static delay(ms) {\n return { type: 'delay', value: ms };\n }", "wait() {\n const time = this;\n\n return Promise.delay(time-Date.now(), this);\n }", "function SetDelay (vv) { Delay = vv; }", "waiter() {\n const waitTime = this.waitTime() + min...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schema plugin Adds validate() to correlation Wraps existing correlation methods to account for validation (i.e., when multiple schemas apply). Adds resolveLinks() to correlation, used as basis for correlation.links() defined in jsonschemahyper plugin. Wraps subschema() Wraps coerce()
function plugin(target){ target.addBinding('validate',validateBinding); target.addBinding('resolveLinks',resolveLinksBinding); target.addBinding('subschema',subschemaBinding); target.addBinding('coerce',coerceBinding); }
[ "function coerceBinding(){\n if (!this.schema || this.instance === undefined) return;\n var self = this\n , ret\n var valid = this.validate( function(schemas){\n ret = buildCoerce.call(self,schemas);\n });\n if (!valid) ret = buildCoerce.call(self,[this.schema]);\n return ret;\n}", "decorateSchema(sch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unseated guest list object control
function UnseatedGuestListControl() { // guest - Guest object this.AddGuestToList = function (guest, table_id) { if (!table_id) table_id = '__default__'; var $table_box = $('.tp-guests__table-box--' + table_id); $table_box.append( '<div><div id="' + guest.GuestID...
[ "unviewListModel(){\n this.currentList = null;\n this.view.viewList(this.currentList); \n }", "removeGuest(guest) {\n var index = this.state.guestList.indexOf(guest);\n var newList = this.state.guestList.slice();\n newList.splice(index, 1);\n this.setState({\n guestL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a new instance of `MapWriter`.
function MapWriter(builderOptions, writerOptions) { var _this = _super.call(this, builderOptions) || this; // provide default options _this._writerOptions = util_1.applyDefaults(writerOptions, { format: "map", wellFormed: false, group: false, verbo...
[ "function MapBuilder() {}", "constructor() {\n this.map\n }", "function createMap() {\n return new MapCtr();\n }", "function createMap(){\n\t\tworldMapInstance = new WorldMap(svg);\n\t}", "constructor(map){\n\t\tthis.map = map;\n\t}", "function Map() {\n if (this instanceof ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
wrap dialog and return content panel.
function wrapDialog(target){ var t = $(target); if (!t.attr('id')) t.attr('id', $.parser.getObjGUID()); t.wrapInner('<div class="dialog-content" targetid="' + t.attr('id') + '"></div>'); var contentPanel = t.children('div.dialog-content'); contentPanel.attr('style', t.attr('styl...
[ "function wrapDialog(target){\r\n\t\tvar t = $(target);\r\n\t\tt.wrapInner('<div class=\"dialog-content\"></div>');\r\n\t\tvar contentPanel = t.find('>div.dialog-content');\r\n\t\t\r\n\t\tcontentPanel.css('padding', t.css('padding'));\r\n\t\tt.css('padding', 0);\r\n\t\t\r\n\t\tcontentPanel.panel({\r\n\t\t\tborder:f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the global instance of [[TextFormatter]]. All classes and instances should reuse this universal text formatter, rather than create their own instance of it.
function getTextFormatter() { if (formatter == null) { formatter = new TextFormatter(); } return formatter; }
[ "function getTextFormatter() {\n if (formatter == null) {\n formatter = new TextFormatter();\n }\n\n return formatter;\n }", "function getTextFormatter() {\n if (formatter == null) {\n formatter = new TextFormatter_TextFormatter();\n }\n return formatter;\n}", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable/Disable Horizontal Scroll bar.
_refreshHorizontalScrollBarVisibility(scrollWidth) { const that = this; that.scrollWidth = scrollWidth; if (!that.computedHorizontalScrollBarVisibility) { that.scrollLeft = 0; } }
[ "function disableHorizontalScroll () {\r\n var scrollEventHandler = function() {\r\n window.scroll(0, window.pageYOffset)\r\n }\r\n window.addEventListener(\"scroll\", scrollEventHandler, false);\r\n }", "function manageHorizontalScroll() {\n var $s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert lat and long into x and y coords
function getXY(lat, lon) { return { cx: lon * 2.6938 + 465.4, cy: lat * -2.6938 + 227.066 }; }
[ "function convertPosToCoords(x,y) {\n x /= map_w\n y /= map_h\n x = (Math.round(x * 10000) / 100).toPrecision(4)\n y = (Math.round(y * 10000) / 100).toPrecision(4)\n return [x,y]\n}", "function gtaCoordToLonLat(x, y)\r\n{\r\n\tvar mapx = x * 0.03;\r\n\tvar mapy = y * 0.03;\r\n\treturn new OpenLayer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check particle position, check mouse position, move the particle, draw the particle
update() { //check if particle is still within particle-js container if (this.x > particles.width || this.x < 0) { this.directionX = -this.directionX; } if (this.y > particles.height || this.y < 0) { this.directionY = -this.directionY; } //check co...
[ "update(){\n // Check if particle is inside canvas limits\n if (this.x > canvas.width || this.x < 0 ) {\n this.directionX = -this.directionX ;\n }\n if (this.y > canvas.height || this.y < 0 ) {\n this.directionY = -this.directionY;\n }\n\n // Check col...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to delete an employee
function deleteEmployee() { }
[ "function deleteEmployee(employee){\n connection.query(`DELETE FROM employees WHERE id = ${employee};`, function(err, res) {\n if (err) {\n throw err;\n }\n else{\n console.log(`${res.affectedRows} record(s) deleted`);\n populateEmployees();\n }\n });\n return;\n}", "function delet...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Spends tokens and burns the selected quantity by subtracting that amount from the output. This function returns a hex string of a transaction, ready to be broadcast to the network.
async burnTokens (burnConfig) { try { // console.log(`utxo: ${util.inspect(utxo)}`) // Expand the config object into separate objects. const { utxo, qty, tokenChangeAddress, bchChangeAddress, walletInfo, tokenUtxos } = burnConfig // ins...
[ "_createswapExactTokensForETHTransaction(\n amountIn,\n amountOutMin,\n recipient,\n WETHContractAddress,\n tokenContractAddressToSell,\n gasPriceGwei) {\n\n let msgData = [];\n\n const methodString = 'swapExactTokensForETH(uint256,uint256,address[],address,uint256)';\n const methodString...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Escape a string for HTML interpolation.
function escape(string) { return ('' + string).replace(htmlEscaper, function(match) { return htmlEscapes[match]; }); }
[ "function htmlEscape(string) {\n return ('' + string).replace(htmlEscaper, function (match) {\n return htmlEscapes[match];\n });\n}", "function escape(string) {\n return ('' + string).replace(htmlEscaper, function(match) {\n return htmlEscapes[match];\n });\n}", "function escape(string) {\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is carried out when the 'Smooth Branch' button is clicked
function smoothBranch() { sharpStoneBank--; branchBank--; smoothBranchBank++; action(1,1,1); advanceTime(); updateDisp(); }
[ "function prepBranch(){\n\tconsole.log(\"Preparing current branch for merging into master...\");\n\t//set this to false to tell docs() not to touch branch prop \n\t//before compiling templates\n\tglobalUpdateBranch = false;\n\t//add FIRST step to update F2.json\n\tbuildSteps.unshift({\n\t\targ: 'updateF2Info', \n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize add subject dialogs and assign them to buttons
function initAddSubjectButtonsAndDialogs() { $(".add_subj_btn").each(function() { var dlg = $(".add_subj_dialog"); $(this).on('click', function() { dlg.dialog('open'); }); }); }
[ "function initAddSubjectButtonsAndDialogs() {\n $(\".add_subj_btn\").each(function() {\n var dlg = $(\".add_subj_dialog\");\n\n $(this).on('click', function() {\n dlg.dialog('open');\n });\n });\n \n}", "function initAddSubjectDialog() {\n // there's only one add subject button\n $(\".add_subj_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
on routes that end in /Roles/:id to update an existing Role
function put(req, res) { let model; Role.forge({id: req.params.id}).fetch({require: true}) .then(doAuth) .then(doUpdate) .catch(errorToNotify); function doAuth(model) { this.model = model; return auth.allowsEdit(req.decoded.id, 'roles', model); // check whether logged user is allowed to Edit this role mo...
[ "async function updateRole(req, res, next) {\n try {\n const role = await Role.findByIdAndUpdate(req.params.id, req.body, {\n new: true,\n });\n res.json(role);\n } catch (error) {\n next(error);\n }\n}", "function editRole(req, res) {\n User.findOneAndUpdate(\n { email: req.body.email },\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates interval display in option bar.
function updateIntervalDisplay(interval) { if (interval < 3600 || interval > 7200000) { return null; } $("#intervalDisplay").html(function () { let spannedInterval = "<span id='spannedInterval'>" + (((interval) / 1000) / 60) + "</span>"; return "Current Interval: " + spannedInterval ...
[ "function updateIntervalInput(type,args,obj) {\n Page.btnSelectInterval.set('label',obj.cfg.getProperty('text'));\n Dom.get('txtInterval').value=obj.value;\n }", "function update () {\n\t\tvar delta = this.time.length();\n\t\tif ( delta < 0 ) {\n\t\t\telements.display.innerHTML = 'Invalid Interv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
mapVirtualToPhysical() does memory management by converting a 17 bit I/D virtual address to a 22 bit physical address. A real PDP 11/70 memory management unit can be enabled separately for read and write for diagnostic purposes. This is handled here by having by having an enable mask (CPU.mmuEnable) which is tested aga...
function mapVirtualToPhysical(virtualAddress, accessMask) { "use strict"; var page, pdr, physicalAddress, errorMask; //var CPU = window.CPU; CPU.displayAddress = virtualAddress & 0xffff; // Remember the 16b virtual address for display purposes if (!(accessMask & CPU.mmuEnable)) { // This access does...
[ "function mapVirtualToPhysical(virtualAddress, accessMask) {\n \"use strict\";\n var page, pdr, physicalAddress, errorMask = 0;\n //var CPU = window.CPU;\n //if (virtualAddress & ~0x1ffff) panic(89); // check VA range\n //if (!accessMask) panic(93); // Must have READ_MODE or WRITE_MODE\n if (!(acc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when a Spark task is ended.
onSparkTaskEnd(data) { this.addData(data.finishTime, this.numActiveTasks); this.numActiveTasks -= 1; this.addData(data.finishTime, this.numActiveTasks); }
[ "onSparkTaskEnd(data) {\n let content;\n if (data.status === 'SUCCESS') {\n content = JobTimeline.createTaskBar(data);\n } else content = `${data.taskId}`;\n this.timelineData3.update({\n id: data.taskId,\n end: new Date(data.finishTime),\n cla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare changed object (which is a forced clone) with existing object and return the delta
function getChangeDelta(obj, old) { if (old) { return getObjectDelta(old, obj); } else { return JSON.parse(JSON.stringify(obj)); } }
[ "function compareData(oldObject) {\n if (oldObject[id] === newObject[id] && JSON.stringify(oldObject) !== JSON.stringify(newObject)) {\n return newObject;\n } else {\n return false;\n }\n }", "_getChangeDelta(obj, old) {\n if (old) {\n return this._getObjectDelta(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is similar to [[nativize]], but takes a [[ReturndataDecoding]]. If there's only one returned value, it will be run through compatibleNativize but otherwise unaltered; otherwise the results will be put in an object. Note that if the ReturndataDecoding is not a [[ReturnDecoding]], this will just return `und...
function nativizeReturn(decoding, options = {}) { const numberFormatter = options.numberFormatter || (x => x); const format = options.format || "ethers"; switch (format) { case "ethers": return ethersCompatibleNativizeReturn(decoding, numberFormatter); } }
[ "function decodeReturnValue(types, msg) {\n const returnValues = IDL.decode(types, Buffer.from(msg));\n switch (returnValues.length) {\n case 0:\n return undefined;\n case 1:\n return returnValues[0];\n default:\n return returnValues;\n }\n}", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the footer with the latest date selection
_refreshFooter() { const that = this; if ((that.viewSections.indexOf('footer') < 0 || that.$.footer.offsetHeight === 0)) { return; } function preFormatDateOutput() { if (that.selectedDates.length === 0) { return ''; } if ...
[ "updateFooter(){\n\t\tif(this.recall(this.dateList)){\n\t\t\tthis.footer.backgroundColor = \"#0AFF0B\";\n\t\t\tSS.style(this.footer, {\"backgroundColor\" : \"#0AFF0B\"});\n\t\t}\n\t\telse {\n\t\t\tSS.style(this.footer, {\"backgroundColor\" : \"#F8F8F8\"});\n\t\t}\n\t}", "function footerDate() {\n const date = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an object with details about the arg/opt in s.
function getOptionOrArg(s) { // Options start with any number of '-'. If the option name is // followed by '=', save everything after it as a value to be used // for that option. var optMatch = (s.match(/^-+(.+?)(?:=(.*))?$/) || [ null, null, null ]); ...
[ "function initOptions( ar ) {\n var oVerb, verb = '', args = ar.slice(), cleanArgs = args.slice(2), oJSON;\n if( cleanArgs.length ) {\n\n // Support case-insensitive sub-commands (build, generate, validate, etc)\n var vidx = _.findIndex( cleanArgs, function(v){ return v[0] !== '-'; });\n if( vi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a small and simple ground plane
function createGroundPlane(width, height) { // create the ground plane var planeGeometry = new THREE.PlaneGeometry(width, height, 10, 10); var planeMaterial = new THREE.MeshStandardMaterial({ map: textureLoader.load("../assets/general/floor-wood.jpg"), side: THREE.DoubleSide, }); var plane = new THREE.M...
[ "addLargeGroundPlane() {\n // create the ground plane\n const planeGeometry = new THREE.PlaneGeometry(1000, 1000)\n const planeMaterial = new THREE.MeshPhongMaterial({\n color: 0xffffff,\n })\n this.groundPlane = new THREE.Mesh(planeGeometry, planeMaterial)\n this.groundPlane.receiveShadow = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filtra um item na tabela
function filtrar() { var input, filter, table, tr, td, i; input = $('#filtrar'); filter = input.val().toUpperCase(); table = $('#tabela'); tr = $('tr'); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName('td')[0]; if (td) { if (td.innerHTML.toUpperCase(...
[ "static filterItems(filterBy, Key) {\n const doneLoading = new Promise((resolve, reject) => {\n filterBy = filterBy.toLowerCase();\n Key = Key.toLowerCase();\n\n switch (filterBy) {\n case 'category':\n filterBy = '.td_Category';\n break;\n\n case 'brand':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes sendmail KILL command
handler_KILL(command, callback) { this._server.logger.info( { tnx: 'kill', cid: this.id, user: (this.session.user && this.session.user.username) || this.session.user }, 'Client tried to invoke KILL' ); this.send...
[ "kill() {\n this.cmd = KILL;\n return this.send();\n }", "function pKill(pid) {\n send({\n name: '+pkill',\n payload: pid\n });\n recv('+pkill-ack', function () {}).wait();\n}", "function broadcastKill(msg) {\n logger (\"starkill \" + msg);\n io.sockets.emit('npckilled', msg)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the id If the element is not yet created, store the value and apply it when the element is created
set id(id) { if (this.#el) this.#el.id = id; else this.#id = id; }
[ "_setElementID() {\n this._log('setElementID');\n\n const that = this,\n $el = that.$el;\n\n if (!$el.attr('id')) {\n $el.attr('id', that.autoIdPrefix + ($('[id|=\"' + that.autoIdPrefix + '\"]').length + 1));\n }\n\n that.settings.elementID = $el.attr('id');\n }", "setID(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to determine if the text in the nnumber box is the right length
function checkNNumberLength() { value = document.getElementById('nNumber').value; if (value.length == 9) { // document.getElementById('nNumber').value = ''; return true; } else { return false; } }
[ "function checkLength(num) {\r\n if (num.toString().length > 7 && num.toString().length < 14) {\r\n $(\"#display\").css(\"font-size\", \"15px\");\r\n //$(\"#display\").css(\"margin-top\", \"174px\");\r\n } else if (num.toString().length > 16) {\r\n num = \"Infinity\";\r\n //$(\"button\").p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }