query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Formats the vote button to indicate that vote is possible
function formatToVote(){ votedStatus = false; $('#vote').html('Yay Curricula!').addClass('btn-success').removeClass('btn-default'); }
[ "_vote () {\n\t\tif(isUserAuthed()) {\n\t\t\t//update our state to show the different button state\n\t\t\tthis.setState({voted: !this.state.voted});\n\n\t\t\tvar newVoteCount = this.state.vote_count;\n\t\t\t//increment/decrement vote count\n\t\t\tif(this.state.voted) {\n\t\t\t\tnewVoteCount = newVoteCount - 1;\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode an IOTA Area Code into a location.
function decode(iotaAreaCode) { const olc = open_location_code_typescript_1.default.decode(toOpenLocationCode(padPartial(iotaAreaCode))); return { latitude: olc.latitudeCenter, longitude: olc.longitudeCenter, codePrecision: olc.codeLength, latitudeLow: olc.latitudeLo, ...
[ "function toOpenLocationCode(iotaAreaCode) {\r\n if (!validation_1.isValid(iotaAreaCode)) {\r\n throw new Error(\"The iotaAreaCode is not valid\");\r\n }\r\n return internal_1.iacToOlcInternal(iotaAreaCode);\r\n}", "function setAirportDecode() {\n var apt;\n\n $WT.find('.tsAp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reveals the board completely when winnig cannot render bug
function revealBoard(board) { for (var i = 0; i < board.length; i++) { for (var j = 0; j < board.length; j++) { if (!gBoard[i][j].isShown) { var cellContent; var elCell = document.getElementsByClassName(`unrevealed cell-${i}-${j}`); if (board...
[ "function renderLocalBoard() {\n if(victory) {\n for(let i=0;i<9;i++) {\n localBoardPops[i].visible = false;\n }\n return;\n }\n\n if(currentBoard == -1) {\n localBoard.setTexture(resources[\"res/BoardGray.svg\"].texture);\n for(i=0;i<9;i++) {\n loca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if any key on the keyboard is pressed, a stroke will be drawn around the circles left arrow and right arrow will change the size of the circles up arrow and down arrow will change the dominant colors
function keyPressed() { if (keyCode == 32) { if (strokeToggle) { stroke(0); } else { noStroke(); } strokeToggle = !strokeToggle; } if (keyCode == LEFT_ARROW) { circleSize = circleSize - 10; } if (keyCode == RIGHT_ARROW) { circleSize = circleSize + 10; } if (keyCode == U...
[ "function keyPressed() {\n switch (key) {\n case 'C':\n drawCos = !drawCos;\n break;\n case 'S':\n drawSin = !drawSin;\n break;\n case 'T':\n drawTan = !drawTan;\n break;\n }\n}", "function draw2Dkeyboard()\n{\n imageMode(CORNER);\n image(keyboard, width/2 - 2.0*PPCM, he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handleImgLinkClicked: prevent default scroll to top emit event to send current restaurant to restaurantDetails so it can be displayed
function handleImgLinkClicked(event) { console.log('handleImgLinkClicked'); event.preventDefault(); pubSub.emit('showDetailsView', localSearchResultData[currentSearchResultIndex-1]); }
[ "function viewMoreHandler(event){\n\t\tvar target = $(event.currentTarget).find('a:visible').attr('id');\n\t\tif(target === \"viewMoreLink\") {\n\t\t\tshowLanding(partnerLandingGridLimit, partnerDetails.length, true);\t\n\t\t\t$('#viewMoreLink').hide();\n\t\t\t$('#viewLessLink').show();\n\t\t} else {\n\t\t\tviewLes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sort the series data in increasing order.
function sortData(series) { var d; for (var i=0; i<series.length; i++) { d = series[i].data; if (series[i]._stackAxis == 'x') { d.sort(function(a,b){ var ret = a[1] - b[1]; if (ret) { ...
[ "argsort(ascending = true) {\n const sortedIndex = this.sort_values(ascending);\n const sf = new Series(sortedIndex.index);\n return sf;\n }", "getData () {\n return this._data.sort((a, b) => b[this._sortColumn] - a[this._sortColumn])\n }", "function sortDataByAverage() {\n sorted...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles change of messages on this thread cache. This is useful to refresh nonmain caches that are currently displayed when the main cache receives updates. This is necessary because only the main cache is aware of changes in real time.
_onMessagesChanged() { if (!this.thread) { return; } if (this.thread.mainCache !== this) { return; } for (const threadView of this.thread.threadViews) { if (threadView.threadCache) { threadVie...
[ "displayMessageChanged(aFolder, aSubject, aKeywords) {\n // Hide previous stale message to prevent brief threadpane selection and\n // content displayed mismatch, on both folder and tab changes.\n let browser = getMessagePaneBrowser();\n if (browser && browser.contentDocument && browser.contentDocument....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add exoclick videoslide script
function exoclick_videoslide_load() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.src = 'https://a.exdynsrv.com/video-slider.js'; ga.onload(exoclick_videoslide_init); var s = document.getElementsByTagName('body')[0]; s.insertBefore(ga, s.firstChild); }
[ "function clickMovieArrow(e) {\r\n $(e).click((event)=>{\r\n let target = $(event.target);\r\n if(target.is('.movie-next')) {\r\n showMovieSlides(1);\r\n } else {\r\n showMovieSlides(-1);\r\n }\r\n });\r\n}", "function displayMovieLightbox(e) { \r\n $(e).click...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The AWS::ApiGateway::DocumentationVersion resource creates a snapshot of the documentation for an Amazon API Gateway API entity. For more information, see Representation of API Documentation in API Gateway in the API Gateway Developer Guide. Documentation:
function DocumentationVersion(props) { return __assign({ Type: 'AWS::ApiGateway::DocumentationVersion' }, props); }
[ "function DocumentationPart(props) {\n return __assign({ Type: 'AWS::ApiGateway::DocumentationPart' }, props);\n }", "function DocBookHandler(version)\n{\n // Add members to DocBookHandler type\n this.fDocBookVersion = version;\n this.fRootElemName = \"article\";\n this.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sorts an array of objects by the selected key (descending);
function sortByKeyDesc(array, key) { return array.sort(function(a, b) { let x = a[key]; let y = b[key]; return ((x > y) ? -1 : ((x < y) ? 1 : 0)); }); }
[ "function sortKeysDescending (array) {\n var keys = keys = Object.keys(array)\n return keys.sort(function (a, b) { return array[b] - array[a] })\n }", "function sortArrayOfObjects (arr, key) {\n for (item in arr){\n if (typeof arr[item][key] === \"string\"){ //check if values are strings so we ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a [transaction](state.Transaction) that updates this / state. Any number of [transaction specs](state.TransactionSpec) / can be passed. The [changes](state.TransactionSpec.changes) (if / any) of each spec are assumed to start in the _current_ document / (not the document produced by previous specs), and its / [s...
update(...specs) { return resolveTransaction(this, specs, true); }
[ "update(transactions) {\n if (this.updateState != 0 /* Idle */)\n throw new Error(\"Calls to EditorView.update are not allowed while an update is in progress\");\n this.updateState = 2 /* Updating */;\n let state = this.state;\n for (let tr of transactions) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the months array
setMonths(state) { let months = ["01","02","03","04","05","06","07","08","09","10","11","12"] this.commit("setMonths", months) }
[ "function CP_setMonthNames() {\r\n for (var i = 0; i < arguments.length; i++) { this.monthNames[i] = arguments[i]; }\r\n this.copyMonthNamesToWindow();\r\n}", "function CP_setMonthAbbreviations() {\r\n for (var i = 0; i < arguments.length; i++) { this.monthAbbreviations[i] = arguments[i]; }\r\n this.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs an `HttpHandler` that applies interceptors to a request before passing it to the given `HttpBackend`. Use as a factory function within `HttpClientModule`.
function interceptingHandler(backend, interceptors = []) { if (!interceptors) { return backend; } return interceptors.reduceRight((next, interceptor) => new HttpInterceptorHandler(next, interceptor), backend); }
[ "static create() {\n return new FastHttpMiddlewareHandler();\n }", "function createRequestListener(path) {\n\treturn function(request, response) {\n\t\tvar httpRequest;\n\t\t\n\t\t// Create the right request for the HTTP method. Works similar\n\t\t// to Factory Pattern.\n\t\tswitch (request.method) {\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to create the deck. Refactored from best hand algo
static createDeck() { for (let i = 0; i < 4; i++) { for (let j = 1; j <= 7; j++) { let obj = { suit: i, value: j }; deck.push(obj); } } }
[ "function generateDeck(){\n // Generate a card number holder so we never re-use cards\n for(i=0;i<52;i++){\n app.unpickedCards.push({cardNumber:i});\n }\n\n var suits = [\n { name:'S','display':'Spades'},\n { name:'H','display':'Hearts'},\n { name:'D','display':'Diamonds'},\n { name:'C','display'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EGE: 1/6/14, createMap function based on FindArcGISUserInGroup,
function createMap(extent) { console.log("Function createMap called"); sessionStorage.clear(); // var data = portalUser.credential; // token = data.token; arrSubjectGroups = []; var popup = new esri.dijit.Popup({ fillSymbol: new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymb...
[ "function createMap() {\n currentTerritory= viewerOptions.territory || 'FXX';\n // viewer creation of type <Geoportal.Viewer>\n // création du visualiseur du type <Geoportal.Viewer>\n // HTML div id, options\n territoriesViewer[currentTerritory]= new Geoportal.Viewer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an identifier, this function goes around the AST to determine whether we should consider it a string literal, on a besteffort basis. It is an approximation, but should never have false positives.
function isUnderlyingValueAStringLiteral(identifier, tc) { // The identifier references a value, and we try to follow the trail: if we // find a variable declaration for the identifier, and it was declared as a // const (so we know it wasn't altered along the way), then the value used // in the declarat...
[ "function validLiteral(node) {\n if (node && node.type === 'Literal' && typeof node.value === 'string') {\n return true;\n }\n return false;\n}", "function isIdentifier (s) {\n \treturn /^[a-z]+$/.test(s);\n}", "_isLiteral(tokenType) {\n return (\n tokenType === \"NUMBER\" ||\n toke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Problem 1. Increase array members Write a script that allocates array of 20 integers and initializes each element by its index multiplied by 5. Print the obtained array on the console.
function index5() { var arr = [], i, n = 20; for (i = 0; i < n; i += 1) { arr[i] = i * 5; } document.getElementById('result').innerHTML = ' ' + arr; }
[ "function main() {\n Array.SIZE_RATIO = 3;\n\n // Create an instance of the Array class\n let arr = new Array();\n\n // -------Drill 2-------\n // Add an item to the array\n arr.push(3);\n arr.push(5);\n arr.push(15);\n arr.push(19);\n arr.push(45);\n arr.push(10);\n\n // console.log(\"line 24:\", arr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT update a Thought
updateThought({ params, body }, res) { Thought.findOneAndUpdate({ _id: params.id }, body, { new: true, runValidators: true }) .select('-__v') .then(thoughtData => { if (!thoughtData) { res.status(404).json({ message: 'No Thought found with that ID.' })...
[ "updateThoughts({ params, body }, res) {\n Thoughts.findOneAndUpdate({ _id: params.id }, body, { new: true, runValidators: true })\n .then(dbThoughtsData => {\n if (!dbThoughtsData) {\n res.status(404).json({ message: 'No thoughts with this ID. ' });\n return;\n }\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new metric value. This maybe one of the following: ``` new Metric('metric'); new Metric('metric', 10); new Metric('category', 'metric'); new Metric('category', 'metric', 10); ``` String values would need to use the three argument version. Date values are converted to timestamps.
function Metric() { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.category = null; this.metric = null; this.value = null; var length = args.length; if (length > 0 && args[0] inst...
[ "function put(value, op, cb) {\n\n if (typeof value !== 'number') {\n // TODO throw error\n }\n\n var ts\n op = op || {}\n\n if (typeof op === 'function') {\n cb = op\n op = {}\n ts = ISODateString(new Date())\n } else if (typeof op === 'string') {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Task para gerar o scieloarticle.js
function processScieloArticleJs(){ return src(target_src['js']['scielo-article']) .pipe(concat(output['js']['scielo-article'])) .pipe(sourceMaps.init()) .pipe(stripDebug()) .pipe(uglify()) .pipe(sourceMaps.write('../maps')) .pipe(dest(output['js']['folder'])); }
[ "async function transformToTLJson() {\n var timelineJson = {}\n timelineJson.events = [];\n // list of slide objects (each slide is an event)\n\n //wikiDate is in iso-8601 format \n function parseDate(wikiDate) {\n var wdate = new Date(wikiDate);\n\n return {\n year: wdate.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_bindDraggableForDay This method binds mouse events for draggable selection in Day Matrix
function _bindDraggableForWeek() { var isMouseDown = false, isActive; $("#matrix td") .mousedown(function(e) { isMouseDown = true; columnID = this.id.split('-')[1]; $(this).toggleClass("active"); isActive = $(this).hasClass("active"); /...
[ "function _bindDraggableForDay() {\n var isMouseDown = false,\n isActive;\n $(\"#matrix td\")\n .mousedown(function(e) {\n var all = document.querySelectorAll('td.active'),\n first = '',\n last = '',\n rowID;\n for(var i = 0; i <...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LIGHTBOXES Lightbox Constructor & Prototype Definitions / Lightbox required params are: selector: the css selector for this lightbox
function LightBox(selector, options) { this.selector = selector; this.is_fixed = options.is_fixed || false; this.dark_background = options.dark_background || false; this.black_overlay = options.black_overlay || false; this.white_overlay = options.white_overlay || false; this.is_nested = false; ...
[ "function LightboxViewer(images) {\n // TODO (Gavin): sanity check data\n\n // Lightbox State\n this.state = 'off';\n this.domId = \"lb-background\";\n // Keep track of the current image\n this.currentImageIndex = undefined;\n // Keep track of events\n this.eventHandlers = [];\n this.imag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inform all those domains in cart with the new information taken by the registry.
function update_domains_in_cart (fqdn, target) { if(fundamental_vars.toCart.indexOf(fqdn) > -1){ //If while the user was searching this domains was taken the cart should be updated and show a notification. if(target.find('.cart-button').hasClass('taken')) { fundamental_vars.toCart = $.gr...
[ "function addProxys() {\n\t\t\t\tvar $proxyReturnEmail = $('.email-details').clone();\n\t\t\t\t$proxyReturnEmail.find('input').attr('id', 'awa-return-email-form');\n\n\t\t\t\tvar $proxyNewEmail = $('.email-details').clone();\n\t\t\t\t$proxyNewEmail.find('input').attr('id', 'awa-new-email-form');\n\n\t\t\t\t$('.emai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if /nick was entered
function checkUsernameChange(data){ data.toLowerCase(); var result = data.match(/\/nick/i); if(result === null || result.length!=1) return false; else return true; }
[ "function handleUsername() {\r\n\r\n // we extract the last.fm username from the form\r\n const username = document.forms.enterUsername.elements.username.value;\r\n\r\n // we first check if the username field is empty\r\n if (username === '') {\r\n alert('Please enter a last.fm username');\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the attributes for a new Todo item.
newAttributes() { return { title: this.$input.val().trim(), order: Todos.nextOrder(), completed: false }; }
[ "function tasks_array_customize_item(item) {\n item['sub_project'] = sub_project_from_task(item) //item_name.split(\":\")[0].trim()\n item['duration'] = duration_from_task_dictionary(item)\n item['cost'] = task_cost_calculation(item)\n item[\"DT_RowId\"] = item.id;\n return item\n}", "function crea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Func: getXMLDocument() Desc: Gets an XML Document Return: An Xml document
function getXMLDocument(){ var xDoc=null; if( document.implementation && document.implementation.createDocument ){ xDoc=document.implementation.createDocument("","",null);//Mozilla/Safari }else if (typeof ActiveXObject != "undefined"){ var msXmlAx=null; try{ msXmlAx=new...
[ "function DOMToString(doc) {\n\tvar xml = null;\n\ttry {\n\t\t//Most modern browsers\n\t\tvar ser = new XMLSerializer();\n\t\txml = ser.serializeToString(doc);\n\t} catch (e) {\n\t\t//Older IE\n\t\txml = doc.xml;\n\t}\n\t\n\treturn xml;\n}", "function xmlStringFromDocDom(oDocDom, encodeSingleSpaceTextNodes) {\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggles the window related to the clicked marker and initializes its content
toggleWindow(marker,infoWindow) { // If it is already associated to the marker and thus open, closes it and removes // animations if(infoWindow.marker === marker) { infoWindow.marker = null; marker.setAnimation(null); infoWindow.close(); } else { // else, sets its mar...
[ "function openMarkers(){\n infoWindow.setContent(info);\n animation();\n infoWindow.open(map,marker)\n }", "function myclick(i) {\n gmarkers[i].openInfoWindowHtml(htmls[i]);\n }", "openInfoWindow() {\n myMap.closeTempInfoWindow();\n PermMarker.permInfoWindow.open(this);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log(multBy3(3)) console.log(multBy3(2)) console.log(multBy3(1)) 2. write a function where you divde the variable by 4
function divBy4(num){ return num/4 }
[ "function complicatedMath(n1,n2,n3,n4){\n return (n1+n2) % (n3-n4)\n}", "function multiFourAndReturn(n1,n2,n3,n4){\n return n1*n2*n3*n4\n}", "function mult(n){\n var mult=0;\n for (var i = 1; i < n; i++) {\n mult =mult+mult*i;\n }\n \n return mult ;\n }", "function multThree() {\n\tfor ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculate createMapOverlay(map, routeData) To be completed
function createMapOverlay(map, routeData) { // create a new route overlay for the specified data var routeOverlay = new T5.ShapeLayer(); /* TODO: put instruction markers back on the route - maybe markers if (routeData.instructions) { var instructions = routeD...
[ "function addOverlay() { \n imgOverlay.setMap(map);\n}", "function createMap(){\n\n // Add place searchbar to map\n L.Control.openCageSearch(options).addTo(map);\n\n // Add zoom control (but in top right)\n L.control.zoom({\n position: 'topleft'\n }).addTo(map);\n\n // build easy bar fr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fill in notepad description element
function fillNotepadDesc() { var npdescContent = [ '<span id="np-desc-textarea" class="break-word" contenteditable="true" spellcheck="false" data-placeholder="'+ locale.notepad.desc_placeholder +'"></span>', '<span id="np-desc-label"><span id="np-desc-char">'+ charSplitter.countGraphemes($('#np-desc-textarea').tex...
[ "setDescription(description) {\n this.description = description;\n }", "updateDescription(newDesc) {\n this.description = newDesc;\n }", "function set_content_tiny_description(p_content)\r\n{\r\n\t// Hide to user the textarea\r\n\tdocument.getElementById('edit_etape').style.visibility = 'hid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate random project object for random user
function generateProject() { const user = faker.random.arrayElement(user_data); const project = { projectId: faker.random.uuid(), authorId: user.id, title: faker.random.words(), description: faker.lorem.sentences(3, 1), url: faker.internet.url(), creationDate: fak...
[ "function ClientProject(name, companyName) {\n this.name = name;\n this.companyName = companyName;\n\n this.frontReq = getRandomNum(10, 60);\n this.clientReq = getRandomNum(10, 60);\n this.serverReq = getRandomNum(10, 60);\n console.log(\"Project created! \");\n}", "function generateVisit() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PlotStationPath pots individual stations & enters them into the SVG DOM stations is the full array of station data (on the station[idx] is used here, but is passed through to GenColor() idx is the element index in the stations array to be plotted chanWidth is the width of a 20MHz channel channels may differ in x coordi...
function PlotStationPath(stations, idx, chanWidth, tier, container) { var spath=""; var signal_height = GetHeightFromSignal(stations[idx][3]); var channel_center = GetChannelCenter(GetChannelInfo(stations[idx][1])); var chanSpread = chanWidth * 0.8125; /* 16.25MHz utilized / 20MHz */ var chanSpreadW = 0; var lead...
[ "function GenerateLabels(stations, ChSignalHigh) {\n\tvar container;\n\tfor (var i = 0; i<ChSignalHigh.length; i++) {\n\t\tif (ChSignalHigh[i][3] > -120) {\n\t\t\tvar chassL=\"M\" + GetChannelCenter(ChSignalHigh[i][1])+\",\"+GetHeightFromSignal(ChSignalHigh[i][3])\n\t\t\t\t\t\t+\"l0,\"+(GetHeightFromSignal(-120)-Ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a random timestamp over the course of 3 months
function generateTimestamp() { let currentTime = 1513196237428; let threeMonths = 7776000000; return currentTime + Math.round(Math.random() * threeMonths); }
[ "function generateDate(){\n var year = 2005 + Math.floor(Math.random()*11)\n var month = Math.ceil(Math.random()*12)\n if(month<10){\n month = \"0\" + month.toString()\n }\n var day = Math.ceil(Math.random()*25)\n if(day<10){\n day = \"0\" + day.toString()\n }\n return `${year}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a value indicating whether the creep is in the work room.
get atWork () { return this.room.name === this._mem.rooms.work; }
[ "get workRoom () {\n if (this._cache.workRoom !== undefined) {\n return this._cache.workRoom;\n }\n this._cache.workRoom = Empire.getRoom(this._mem.rooms.work);\n return this._cache.workRoom;\n }", "getCheckCompanyCode() {\n\t\t\n\t\tvar flag = true;\n\t\tconsole.log(\"co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The root of the router state.
get root() { return this._routerState.root; }
[ "function root() {\n return _root; \n }", "function getRootPathname() {\n let pathname,\n pathRoot,\n indEnd\n\n pathname = window.location.pathname;\n\n if (pathname === '/') {\n pathRoot = pathname;\n } else {\n indEnd = pathname.indexOf('/', 1);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove the Node contain given item,return true or false
function remove(item) { var removePosPrev = this.findPrev(item); var removePos = this.find(item); if (removePosPrev == -1) { return false; } else if (removePos.next.element == "head") { removePosPrev.next = this.head; return true; } else { removePosPrev.next = removePos.next;...
[ "function yank_node(nodeId){\n\tvar toYank = document.getElementById(nodeId);\n\tif(toYank){\n\t\tvar container = toYank.parentNode;\n\t\tcontainer.removeChild(toYank);\n\t}\n\treturn (toYank)?false:true;\n}", "removeNode(value){\n if(this.includes(value)){\n\n let currentNode = this.head;\n while(cu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
While the user drags the mouse, points are added to the path at the position of the mouse:
function onMouseDrag(event) { path.add(event.point); }
[ "function mouseMoved(){\n if(selected !== null){\n selLine[0] = digraph.vertices[selected]['x'];\n selLine[1] = digraph.vertices[selected]['y'];\n selLine[2] = mouseX;\n selLine[3] = mouseY;\n }\n}", "function onMouseUp(event) {\n\n // When the mouse is released, simplify it:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: RTCElement.getElementType DESCRIPTION: Retrieve the element type. ARGUMENTS: none RETURNS: string element type
function RTCElement_getElementType() { return this.elementType; }
[ "function RTCElement_getElementString()\n{\n return this.elementString;\n}", "function extPart_getPartType(groupName, partName)\n{\n var retVal = \"\";\n\n if (groupName)\n {\n retVal = dw.getExtDataValue(groupName, \"groupParticipants\", partName, \"partType\");\n }\n\n return retVal;\n}", "getType ()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create core_tickData_ table query
async createTable(params) { try { const query = `CREATE TABLE IF NOT EXISTS core_tickData_${params.feed} ( id UUID, ca timestamp, date timestamp, symbol text, price double, volume int, ...
[ "async create(params) {\n try {\n const newCore_tickData = `INSERT INTO core_tickData_${params.feed} (id, ca ,symbol ,date ,price ,volume) \n VALUES (UUID(),'${params.date}', '${params.symbol}', '${params.date}', ${params.price}, ${params.volume} )`;\n return await this._core.DBM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the distribution version of package json
async function generatePackageJson() { const original = require('../package.json') const result = { name: original.name, author: original.author, version: original.version, license: original.license, description: original.description, main: './index.js', dependencies: Object.entries(orig...
[ "async function update_package_jsons() {\n const pkg = JSON.parse(fs.readFileSync(\"./package.json\"));\n pkg.version = NEW_VERSION;\n const pkg_json = `${JSON.stringify(pkg, undefined, 4)}\\n`;\n fs.writeFileSync(\"../package.json\", pkg_json);\n const packages = {};\n for (const ws of pkg.worksp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write some file details for files older than a specified date to a new sheet.
function test_getFilesOlderThan() { var ss = SpreadsheetApp.getActiveSpreadsheet(), shName = 'OldFiles', sh = ss.insertSheet(), // 'July 28, 2014', months are 0-11 in JS testDate = new Date(2014, 8, 23); oldFiles = getFilesOlderThan(testDate); sh.setName(shName); oldFiles.forEach( ...
[ "function getFilesOlderThan(cutoffDate) {\n var fileIt = DriveApp.getFiles(),\n filesOlderThan = [],\n file;\n while(fileIt.hasNext()) {\n file = fileIt.next();\n Logger.log(file);\n if(file.getDateCreated() < cutoffDate) {\n filesOlderThan.push(file);\n }\n }\n return filesOlderThan;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper Functions Filter options menu compare two arrays to return only array with noninclusive cards
function filterMe(array, cards) { return array.filter(function (ele) { return !cards.includes(ele); }); }
[ "filterShops(prod) {\n if(!prod.length) {\n this.shops = this.shops.map(el => { \n el.active = true;\n return el;\n });\n return this.shops;\n }\n\n const filteredShops = this.shops.filter(el => prod.every(product => ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=============== = iPhone loop = ===============
function iphoneLoop () { var x = 1; var max = 6; setInterval(function () { $("#iphone-" + x).fadeOut(500); x++; if (x > max) { x = 1; }; $("#iphone-" + x).delay(1000).fadeIn(500); }, 6000); }
[ "function myLoop() {\n\n setTimeout(function() {\n\n // Start and set the frequency and log corresponding details\n osc.start();\n osc.freq(swipeFreqs[freqI]);\n console.log(swipeFreqs[freqI]);\n console.log(thisSentance.charAt(freqI));\n\n // Now add to I to iterate through the loo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We start with custom code here! Dev facilities, for flattening, simplifying, and easier ES3 code createElement wrapper that lets you use child: instead of children: for singlechild elements We don't have to turn varargs children to props here! Preact is cool, so it lets us do that by itself
function createElement() { var props = arguments[1]; if ( // Props is an object and not null typeof props === 'object' && props !== null // It sets child: but no children: && 'child' in props && !('ch...
[ "render() {\n // parenthesis is not required but makes it nice to put things on new lines:\n return (\n <div>\n <h1>Hello World render methods</h1> <b>bold child </b>\n </div>\n );\n }", "function mountChildren(children, parentDOM, parentElement) {\n if (children && typeof children.m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a link to the index.html head tag
function addHeadLink(tree, project, link) { const { indexPath, src } = getIndexHtmlContent(tree, project); if (src.indexOf(link) === -1) { const node = getTag(tree, src, 'head'); const insertion = new change_1.InsertChange(indexPath, node.startOffset, link); const recorder = tree.beginUp...
[ "injectFontAwesome() {\n const firstLinkTagInHead = document.querySelector(\"head link\");\n const fontAwesomeCss = document.createElement(\"link\");\n fontAwesomeCss.setAttribute(\"rel\", \"stylesheet\");\n fontAwesomeCss.setAttribute(\"href\", \"https://use.fontawesome.com/releases/v5....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the location of the selected bus
function busLocation() { var selector = document.getElementById("busline"); var route_name = selector[selector.selectedIndex].text; var xhttp = new XMLHttpRequest(); xhttp.open("GET", "https://data.foli.fi/siri/vm/", true); xhttp.onreadystatechange = function () { if (xhttp.readyState === 4...
[ "function showLocation(evt) {\r\n // console.log(\"show\");\r\n //get mapPoint from event\r\n //The map is in web mercator - modify the map point to display the results in geographic\r\n var mp = esri.geometry.webMercatorToGeographic(evt.mapPoint);\r\n //display mouse coordinates\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the X position of the click.
function getClickX(input) { return ((input.offsetX / getCanvas().width()) * viewWidth) + viewX; }
[ "getPageX() {\n return this.__event.pageX || 0;\n }", "pos_x() {\n return(this.pos.x);\n }", "positionOnTimeline(posX) {\n let rect = this.timelineNode.getBoundingClientRect();\n let posClickedX = posX - rect.left + this.timelineNode.scrollLeft;\n return posClickedX;\n }", "funct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Metodo para realizar un fetch, recibe como parametros el metodo necesitado, la ruta requeridad y si es necesario un token y los datos a enviar
async hacerFetch (metodo, ruta, data, token) { const url = this.url + '/' + ruta; //Concatenamos la ruta dada como parametro con la url let config = { method: `${metodo}`, mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: {...
[ "_postWithToken(url, token) {\n return fetch(url, {\n method: 'POST',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({token: token})\n });\n }", "function quickFetch(url, func, param){\n fetch(url)\n .then(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setContrast: Alter the contrast of the magnified view.
setContrast(contrast) { this._contrast.r = contrast.r; this._contrast.g = contrast.g; this._contrast.b = contrast.b; if (this._magShaderEffects) this._magShaderEffects.setContrast(this._contrast); }
[ "function changeContrast(value) {\n Caman(\"#photo\", imgUrl, function (test) {\n if (value == 0) {\n this.revert();\n }\n console.log(value - previousValue);\n this.contrast(value - previousValue);\n previousValue = value;\n this.render();\n });\n}", "function changeContrast(data, level)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Centre an element absolutely.
function centreElement(element) { var newTopPosition = (($(window).height() - element.outerHeight()) / 2) + 'px'; var newLeftPosition = (($(window).width() - element.outerWidth()) / 2) + 'px'; element.css({'position': 'absolute', 'top': newTopPosition, 'left': newLeftPosition}); }
[ "function $Center(elemId){\n\n var elem = $O(elemId);\n\n var elemDimensions = size(elem);\n var elemWidth = parseInt(elemDimensions.width) || parseInt(getStyleValue(elem, 'width')); \n var elemHeight = parseInt(elemDimensions.height) || parseInt(getStyleValue(elem, 'height'));\n var bDimensions = Br...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Represents a lotto draw.
function Lotto() { /** * The participants */ this.participants = []; /** * Add a participant. * @param participant The participant. * @param tickets The number of tickets held by the participant. */ this.add = function(participant, tickets) { this.participants.push({ participant, tickets }...
[ "function cloth(t, r, b, d, w, i) {\n this.class = t\n this.fabric = r\n this.height = b\n this.fitting = d\n this.color = w\n this.print = i\n}", "function drawCollectable(t_collectable)\n{\n\t\t// Draw collectable items\n\t\tfill('#5398BA');\n\t\ttriangle(t_collectable.x_pos, t_collectable.y_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Params: A hashable object This method determines if the object x is in the hashTable Returns true if found and false otherwise
contains(x) { let contains=false; if(x instanceof Hashable) { let i=this.evaluatePosition(x); if(this.#_arrayOfll[i].search(x)!=null) { contains=true; } } else { throw new Err...
[ "exists(objectHash) {\n return objectHash !== undefined\n && fs.existsSync(nodePath.join(Files.gitletPath(), 'objects', objectHash));\n }", "contains (data, size = data.length) {\n for (let i = 0; i < this.nHashes; i++) {\n const idx = hash(i, this.nHashes, data, size) % this.nBits\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleans up any cached element dimensions that we don't need after dragging has stopped.
_cleanupCachedDimensions() { this._boundaryRect = this._previewRect = undefined; this._parentPositions.clear(); }
[ "resetResize() {\n\t\tconst {\n\t \tisResizing\n\t } = resizeState;\n\n\t if (isResizing) {\n\t \tassign(resizeState, resizeDefaults);\n\t\t removeClass(this.container, RESIZE_CLASS);\n\t\t removeListener(document, 'mousemove', resizeState.listener);\n\t }\n\t \n\t}", "clear() {\n // Wipe out the DOM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts the main game. Get's the randomized array of bricks, creates and prints the game to the container.
function playGame() { var tiles = getBricksArray(); gameBoard = printGameScreen(tiles); container.appendChild(gameBoard); }
[ "function run(){\n\n console.log(\"Attempting Setup\");\n stage = new PIXI.Stage(0x66FF99);\n canvas = document.getElementById(\"game\");\n renderer = PIXI.autoDetectRenderer(800, 300,{view: canvas});\n document.body.appendChild(renderer.view);\n\n\tmain_menu();\n\tconsole.log(\"G...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that creates the email JSON. partner = the email to or from cc = the email cc subject = the email subject emailText = the email email compose text read = used to say whether the email was read or not. used for BOLD returns the JSON created.
function createEmailJSON (partner, cc, subject, emailText, read) { return {"conversationPartner" : partner, "cc" : cc, "subject" : subject, "emailText" : emailText, "read" : read}; }
[ "function saveWithEmail(data, cb) {\n actions.log('saveWithEmail=' + JSON.stringify(data));\n actions.check(data, ['_diag', 'diagStart', 'diagEnd'\n\n , 'diags', 'address', 'price'\n ], (err, r) => {\n if (err) return cb(err, r);\n //\n orderExists(data, (err, r) => {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
inserts a new user
function insert(user) { return dataBase('users').insert(user) }
[ "function signup(userData){\n console.log(\"creating new user \"+userData.id);\n return User.create(userData)\n }", "function signUp(username, password){\n users.insert({username,password,Balance:1500});\n }", "function saveUser(username, password) {\n\n //This newUserRef allows for a NEW user t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Emit messages from the evented logger buster.console through the test runner
function logger(runner) { B.console.on("log", function (msg) { runner.emit("log", msg); }); }
[ "function setupConsoleLogging() {\n (new goog.debug.Console).setCapturing(true);\n}", "_log() {\n let args = Array.prototype.slice.call(arguments, 0);\n\n if (!args.length) {\n return;\n }\n\n if (args.length > 1)\n this.emit('log', args.join(', '));\n els...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Indicates whether Change in dropdown selected value / was due to a Manual Click / or due to System properties of dropdown
function ChangeHandler() { PreviousSelectIndex = SelectIndex; /* Contains the Previously Selected Index */ SelectIndex = document.forms[0].lstDropDown.options.selectedIndex; /* Contains the Currently Selected Index */ if ((PreviousSelectIndex == (document.forms[0].lstDropDown.opt...
[ "function shouldShowFromDefaultWarning() {\n return $scope.item.from_default && $scope.getCurrentTextValue() == $scope.values.saved;\n }", "function checkFormState (){\n\t\tif (formModified && showUnsavedChangesPopup)\n\t\t\treturn 'There are unsaved changes';\n\t}", "function fnChangeHandler_A(getdro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set up a beforeUpdate lifecycle hook to hash the password before a user object is updated in the database
async beforeUpdate(updatedUserData) { updatedUserData.password = await bcrypt.hash(updatedUserData.password, 10); return updatedUserData; }
[ "hashPasswordHook(next) {\r\n if (this.password && this.isModified('password')) {\r\n this.salt = crypto.randomBytes(16).toString('base64');\r\n this.password = this.hashPassword(this.password);\r\n }\r\n\r\n next();\r\n }", "static beforeCreate(user) {\n conso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a camera id in the ServerStatus (e.g. for checking if a camera of the configuation is actually available)
function findCam(serverState,cam_id) { retVal = false; $.each(serverState().CamList(),function(i,item) { if (item.cam_id() == cam_id) { retVal = true; } }); return retVal; }
[ "function findMic(serverState,mic_id) {\n retVal = false;\n $.each(serverState().MicList(),function(i,item) {\n if (item.mic_id() == mic_id) {\n retVal = true;\n }\n });\n return retVal;\n}", "function findCameraDeviceByPanelAsync(panel) {\n var deviceInfo = null;\n // G...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is similar to the update method in the Screen class. It expects to be updated regularly. It simply limits the object from going outside of the set bounds and updates every contained object within this object. param deltaTime: the time that has passed between the last call and the current call. param maxX: the high...
update(deltaTime, maxX, maxY) { if(this.x + this.width > maxX) { this.x = maxX - this.width; } if(this.x < 0) { this.x = 0; } if(this.y + this.height > maxY) { this.y = maxY - this.height; } if(this.y ...
[ "update(x,y){\n\n if (x > 0 & x < width){\n if(y > 0 & y < height/2){\n //if(!this.nearWall()){\n this.pos.x= x;\n this.pos.y= y;\n for (var i = 0; i < this.rays.length;i++) {\n this.rays[i].update(this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to check cookie values for Login form input fields
function checkCookie(){ // remove jwt createCookie("jwt", "", 1); var usrName = accessCookie("username"); var usrPssword = accessCookie("usrpassword"); if (usrName!=""){ document.getElementById('inputUsername').value = usrName; document.getElementById('inputPassword').value = usrPssword; } }
[ "function loggedInCheck() {\n // ajax call to check that user has a valid, i.e. non-expired, login cookie\n // if cookie is valid, show logged in user controls\n var loggedIn = true;\n if ( loggedIn ) {\n showUserControls();\n }\n else {\n hideUserControls();\n }\n}", "function getCookieLogin() {\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a lifeform mutates there is a 5% chance it's char length will change and a 5% chance any given character will change
function mutate(lifeform){ // Add a letter if( Math.random() > 0.3 ){ // 30% var offset = Math.floor( Math.random() * (lifeform.length + 1) ) ; lifeform = lifeform.split(""); lifeform.splice(offset, 1, lifeform[offset] + randLetter() ); return lifeform.join(""); } // Change a letter else if( Math....
[ "function makeChar() {\n\tvar probability=points(0,\"\")/hardness;//according to hardness of game\n\tif(typeof alphabets === 'undefined' || alphabets === \"\"){\n\t\tvar index=Math.floor(Math.random() * 5)+2;\n\t\talphabets=words[index][Math.floor(Math.random() * words[index].length)];\n\t\tif(points(0,\"\")===0){\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Usando solo estructuras de control para ello. Devuelves 1 si a es mayor que b Devuelves 1 si a es menor que b Devuelves 0 si a es igual b
function quienEsMayor(a,b){ let resultado; if(a>b){ resultado = 1; }else if(a<b){ resultado = -1; }else if(a == b){ resultado = 0; } return resultado; }
[ "function Logical (type, ax, bx) {\n var result = {value: null, // the result of the Logical operation\n diff : 0, // number of bits that are different between ax and bx\n change : 0, // estimate of the number of bits that need to be changed to get to eaither ax or bx from .value\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show notification that user cannot set password for the conference because server doesn't support that.
function notifyPasswordNotSupported () { console.warn('room passwords not supported'); APP.UI.messageHandler.showError( "dialog.warning", "dialog.passwordNotSupported"); }
[ "get shouldDeferMessageDisplayUntilAfterServerConnect() {\n let passwordPromptRequired = false;\n\n if (Services.prefs.getBoolPref(\"mail.password_protect_local_cache\")) {\n passwordPromptRequired = this.view.displayedFolder.server\n .passwordPromptRequired;\n }\n\n return passwordPromptReq...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserobject_properties.
visitObject_properties(ctx) { return this.visitChildren(ctx); }
[ "visitColumn_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitPhysical_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitObject_type_col_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSqlj_object_type(ctx) {\n\t return this.visitChildren(ctx);\n\t}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allocate data arrays for the entire program OR clear them if they have already been allocated
function allocOrClearDataArrays4Prog() { for (var m = 0; m < CurProgObj.allModules.length; m++) { var mO = CurProgObj.allModules[m]; for (var f = 0; f < mO.allFuncs.length; f++) { var fO = mO.allFuncs[f]; allocDataArrays4CurFunc(fO); } } }
[ "function clearMemory(){ memory = [] }", "function clear() {\n\t\tgenerations = [];\n\t\tfittest = [];\n\t}", "function allocDataArraysOfStep(fO, sO) {\r\n\r\n // create/init arrays for all grids in a step\r\n //\r\n for (var id = 0; id < sO.allGridIds.length; id++) {\r\n\r\n var gId = sO.allGri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks to see if the player's answer in the input box matches the country data attibute. also runs several other functions once it has been determined whether or not the answer is correct. var playerFlags uses a ternary operator assigns a value to a variable based on some condition. is called in the addSumbit function ...
function checkAnswer (index) { var userAnswer = countryInputs[index].value.toLowerCase(); var playerFlags = index > 3 ? player2Flags : player1Flags; if (userAnswer === playerFlags[index % 4].country) { updateScores(); replaceFlag(index); resetInput(); switchTurn(); disableInput...
[ "function confirmChoice(){\n\n if (confirmUpper == true){\n addInpass += passUpper;\n }\n if (confirmLower == true){\n addInpass += passLower;\n }\n if (confirmNum == true){\n addInpass += passNum;\n }\n if (confirmSym == true){\n addInpass += passSym;\n }\n// console logged to see if the \"if\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a description for a debug adapter running as a socket based server.
function DebugAdapterServer(port, host) { this.port = port; this.host = host; }
[ "_createDebuggerConnectionWSServer(): ws$WebSocketServer {\n const wss = new WS.Server({\n noServer: true,\n perMessageDeflate: false,\n });\n // $FlowFixMe[value-as-type]\n wss.on('connection', async (socket: WS, req) => {\n try {\n const query = url.parse(req.url || '', true).que...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
var bcrypt = require('./bCrypt');
function encryptPassword(pwd) { //var bcrypt = require('bcryptjs'); var salt = bcrypt.genSaltSync(10); var hash = bcrypt.hashSync(pwd, salt); return hash; }
[ "checkPassword(password) {\n return bcrypt.compare(password, this.password_hash)\n }", "function deriveKey(secret, salt, spec, callback) {\n crypto.pbkdf2(secret,\n salt,\n spec.iterations,\n spec.derived_key_length,\n spec.hash,\n ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility that wraps the ubiquitous "don't resolve if not on same page" logic. The `_promise` property is accessed because the thenable returned by ConditionalPromise does not chain with `catch` in the expected way
function resolveOnlyIfOnSamePage(promises, store) { const ident = x => x; return ConditionalPromise.all(promises) .only(samePageCheckGenerator(store), ident, ident)._promise; }
[ "function liftWithGuard(promise, guard) {\n return promise.then(function (data) {\n return new DummyPromise(function (resolve, reject) {\n if (guard(data)) {\n resolve(data);\n }\n else {\n reject(data);\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filterFunction() checks the value of key and compare it with the given input. It returns true if the value matches the given input else returns false.
function filterFunction(obj, key, value){ if(obj[key] === value) { return true; } else { return false; } }
[ "function filterBy(field, value) {\n return function(d) {\n return d[field] === value;\n };\n }", "function filter_dict_by_subkey(dict,subkey,filter_type,filter_val)\n{\n\tvar dict_as_arr = [];\n\tfor (var key in dict)\n\t{\n\t\tvar value = dict[key][subkey];\n\t\tif (value == null)\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
languageSwitch is triggered when language button is clicked, and this function triggers the dialog box by using ref keyword.
languageSwitch(changedLanguage) { if(this.state.language.lang !== changedLanguage) { this.setState({changedLang: changedLanguage}) this.setState({dialog: true}) } }
[ "function languageChangeHandler() {\n if (document.getElementById('selectLanguage').value == \"en\") {\n //alert('selected value is english');\n transliterationControl.disableTransliteration();\n //return;\n } else {\n //enableTransliteration()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This code draws a line from a specified keypoint. The coude is from A function to draw ellipses over the detected keypoints
function drawKeypoints() { // Loop through all the poses detected for (let i = 0; i < min(poses.length, 1); i++) { // For each pose detected, loop through all the keypoints for (let j = 0; j < poses[i].pose.keypoints.length; j++) { // A keypoint is an object describing a body part (like rightArm or le...
[ "_drawLines(keypoint) {\n if (keypoint.indexLabel < 0) return;\n if (!this._edges.hasOwnProperty(keypoint.indexLabel)) return;\n\n let otherIndices = this._edges[keypoint.indexLabel];\n otherIndices.forEach(i => {\n let k2 = this._labelled[i];\n if (!k2) return;\n\n let edge = [keypoint.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the lobby with the given name
function getLobbyWithName(name) { const found = lobbies.find(lobby => lobby.name == name); if (found) return found; else throw 'There is no lobby with that name.'; }
[ "function getLobbyFromName(lobbyname) {\n for (var i = 0; i < lobbies.length; i++) {\n if (lobbies[i].name === lobbyname) {\n return lobbies[i];\n }\n }\n return null;\n}", "function getGame(lobby) {\n return games.find(game => game.lobby === lobby);\n}", "function getLobbyWithPlayer(username, ho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows a confirmation message that checks if the user really wants to delete a poll.
function confirmDelete(id) { var r = confirm("Are you sure?"); if (r == true) { window.location = 'delete_poll.php?id=' + id; } else { return; } }
[ "function confirmDelete(data) {\n var policyId = data.id;\n var policyName = \"\";\n\n // Determines the policy's name by checking the list\n for (var i = 0; i < policyList.length; i++) {\n if (policyId === policyList[i].id) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save and Publish response data
function saveAndPublishResponse(resp) { resContainer.innerHTML = publishAsText(resp); lastReqResponse = resp; localStorage.setItem('lastReqResponse', JSON.stringify(resp)); }
[ "function saveAndPublishUserData(resp) {\n user.name = resp.data.name;\n user.email = resp.data.email;\n user.id = resp.data._id;\n localStorage.setItem('user', JSON.stringify(user)); \n}", "function storeRespond(method, url, data, headers, params) {\n\n\t\t\t// Get a random header\n\t\t\tvar head...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert the type of a value
function assertType(value,type){var valid;var expectedType=getType(type);if(expectedType==='String'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='string');}else if(expectedType==='Number'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='number');}else i...
[ "valueMatchesType(value) {\n return typeof value === this.valueType\n }", "static _type_assert (type, expected_type) {\r\n var _types = { number: 1, string: \"s\", object: {} };\r\n if ((!_types[expected_type]) && (typeof type != typeof _types[expected_type])) {\r\n throw new Error('T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`applyContainer` performs an operation on the container and its views as specified by `action` (insert, detach, destroy) Inserting a Container is complicated by the fact that the container may have Views which themselves have containers or projections.
function applyContainer(renderer, action, lContainer, renderParent, beforeNode) { ngDevMode && assertLContainer(lContainer); var anchor = lContainer[NATIVE]; // LContainer has its own before node. var native = unwrapRNode(lContainer); // An LContainer can be created dynamically on any node by injecting ...
[ "_onAppliedUpdate(view, metadata) {\n if (view && _.isFunction(view.afterApplyUpdate)) {\n view.afterApplyUpdate(metadata);\n }\n }", "_onApplyingUpdate(view, metadata) {\n if (view && _.isFunction(view.beforeApplyUpdate)) {\n view.beforeApplyUpdate(metadata);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Init Background Images Parallax
function initBackgroundImages() { const self = this; if (!self.options.enableMouseParallax) { return; } const $parallaxImages = $('.nk-main .bg-image').parent().add($('.nk-main .bg-image')); // fix for Jarallax $parallaxImages.css('transform', 'translate3d(0,0,0)'); self.parallax...
[ "function initImageParallax() {\n const parallaxSections = gsap.utils.toArray(\".with-parallax\");\n parallaxSections.forEach((section) => {\n const img = section.querySelector(\"img\");\n\n gsap.to(img, {\n yPercent: 20,\n ease: \"none\",\n scrollTrigger: {\n trigger: section,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the flowcell with the new library name
updateFlowcell(flowcellPosition, libraryName) { this.$emit('updateFlowcell', flowcellPosition, libraryName) }
[ "updateLibraryList(libraryName, assignedToFlowcell) {\n this.$emit('updateLibraryList', libraryName, assignedToFlowcell)\n }", "function updateDef(){\n\tinstDef.setparse(\"METADATA\", metaDict.stringify());\n\tinstDef.setparse(\"DATA\", dataDict.stringify());\n}", "function changeListNameInAppData(event...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
append an empty card if there's no search category inputted
function append_empty_searches(){ const empty = '<div class="selectedCard" id="Mirisola\'s"><div id="empty_info"><p id="r_name">Please select a Category!</p></div></div>' console.log("appending...."); $('#underLid').append(empty); }
[ "function displayMsgIfNoCategory() {\n\tif ($('#categories').find('li').length == 0) {\n\t\t$('#no-category').show();\n\t\t$('#catadd-name').focus();\n\t}\n}", "clearSearchResults() {\n if (this.state.filter.length > 0) {\n this.fetchConsumerComplaintList()\n this.props.history.push(`/home/consumers?...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public function `less`. Returns true if `lhs` is a number less than `rhs`, false otherwise.
function less (lhs, rhs) { return number(lhs) && lhs < rhs; }
[ "function less (data, value) {\n return number(data) && data < value;\n }", "lt(other) {\n return this.boolOps(other, \"lt\");\n }", "function lessThanNumber(number) {\n if (base > number) {\n return true;\n } else {\n return false;\n }\n }", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get clients by id
function getClientById(id){ var count = users.length; var client = null; for(var i=0;i<count;i++){ if(users[i].userId==id){ client = users[i]; break; } } return client; }
[ "function getClient(id) {\n for (var i = 0; i < clients.length; i++) {\n if (clients[i].clientID == id) {\n return clients[i].clientName;\n }\n }\n}", "function getClientByID(id) {\n\tfor (var c in clients) {\n\t\tif (clients[c].player.id === id) {\n\t\t\treturn clients[c];\n\t\t}\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get character entity for HTML and Attribute encoding
function getCharEntity(ch) { return charEntities[ch] || (charEntities[ch] = "&#" + ch.charCodeAt(0) + ";"); }
[ "function FCKXHtml_GetEntity( character ){\n\tvar sEntity = FCKXHtmlEntities.Entities[ character ];\n\tif(sEntity != null){\n\t\treturn '#?-:' + sEntity + ';' ;\n\t}\n\telse if(sEntity == null && character.charCodeAt(0) == 160){\n\t\tsEntity = 'nbsp';\n\t\treturn '#?-:' + sEntity + ';' ;\n\t}\n\treturn character;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET SINGLE BOOK BY SLUG
async getSingleBookBySlug(parent,args,ctx,info){ const book = await ctx.db.query.book({ where : {slug: args.slug} },info); if(!book) throw new Error("Book Not Exist"); return book; }
[ "function findNeedle(obj, title) {\n\t var returnKey = -1;\n\t\n\t $.each(obj, function(key, info) {\n\t if (info.title == title) {\n\t returnKey = key;\n\t return false; \n\t }; \n\t });\n\t\n\t return bookArray[returnKey]; \n\t}", "function findByIsbn(isbn){...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search function, returns a address array given a string
function getAddress(str){ var max = 0, count = 0,index; str = str.toUpperCase(); for(let i = 0; i < result.length;i++){//for all results count = 0; for(let j = 0; j < str.length;j++) if(result[i][2][j] == str[j]) count++; if(count >= max){ ...
[ "function searchArray(input, array){\n //creates new RegExp\n //g = flag to make search global, i means ignore case\n let regex = new RegExp(input, 'gi');\n //filters by matching strings\n \n //match can only be used on strings\n let result = array.filter(current => current.matc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a new ECDSA private key on a given curve.
function generateECDSA(curve) { var parts = []; var key; if (CRYPTO_HAVE_ECDH) { /* * Node crypto doesn't expose key generation directly, but the * ECDH instances can generate keys. It turns out this just * calls into the OpenSSL generic key generator, and we can * read its output happily without doin...
[ "function generateECDSA(curve) {\n\t\tvar parts = [];\n\t\tvar key;\n\t\n\t\tif (CRYPTO_HAVE_ECDH) {\n\t\t\t/*\n\t\t\t * Node crypto doesn't expose key generation directly, but the\n\t\t\t * ECDH instances can generate keys. It turns out this just\n\t\t\t * calls into the OpenSSL generic key generator, and we can\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fungsinya untuk menentukan apakah sebuah data dalam sebuah array memenuhi kriteria tertentu fungsi ini akan mereturn nilai true jika semua datanya sesuai kriteria / Method every() dan some() memiliki fungsi yang mirip. Keduanya samasama bertugas untuk menentukan apakah data dalam sebuah array memenuhi kriteria tertentu...
function contoh(){ let produk = [ {name : "aple", type : "PC"}, {name : "asus", type: "laptop"}, {name : "acer", type : "laptop"} ]; hasil = produk.every(product=>product.type=== "laptop"); //ini akan menampilkan false karena tidak semua type laptop, sedangkan syarat dari every() s...
[ "checkPomodoros(){\r\n return this.data.pomodoros.every((pomodoro) => {\r\n return pomodoro.status !== \"none\";\r\n });\r\n }", "function dataUpdate() {\n if(filterData.length > 0) {\n data = [];\n filterData.map(row => {\n data.push({\n brand: row.Brand,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate random distance travalled
generateDistTrav() { var distance = Math.floor((Math.random() * 2) + 1) console.log(distance + "m") }
[ "static cauchyRand() {\n return Math.tan(Math.PI * (Math.random() - 0.5));\n }", "function calculateNewTargetPossition(originValue)\r\n {\r\n return originValue + (Math.random() < 0.5 ? -Math.random() : Math.random()) * settings.nodeMovementDistance;\r\n }", "function ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that should never be called but is used to check that every enum value is handled using TypeScript's 'never' type.
function assertNever(theValue) { throw new Error("Unhandled case for value: '".concat(theValue, "'")); }
[ "static never () {\n return new Signal(always)\n }", "function NOT(value) {\n return value !== true && value !== false && value !== 1 && value !== 0 ? error$2.value : !value;\n}", "static checkEnum(a, enumeration) {\n\t\tconst valid = Object.values(enumeration);\n\t\tif (a === undefined) {\n\t\t\treturn;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a math library
function loadMathLibrary(pO) { var mM = new ModuleObj("Math"); // Set current module object to this module. This is necessary for // creating expressions. As a result the expressions in this library // get seq numbers starting from 1. See description at ModuleObj. // // VERIFY: TODO: ...
[ "function loadLibModules(pO) {\r\n\r\n // Create math library\r\n //\r\n loadMathLibrary(pO);\r\n\r\n loadFileInputLibrary(pO);\r\n\r\n loadFileOutputLibrary(pO);\r\n\r\n loadSystemLibrary(pO);\r\n\r\n loadMatrixLibrary(pO);\r\n\r\n loadTempSensorLibrary(pO);\r\n\r\n // TODO: load other l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
va chercher les infos d'OSM
async function fetchOSMData(bounds) { let response = await axios.get('https://api.openstreetmap.org/api/0.6/map?bbox=' + bounds.bottomLeft.lon + ',' + bounds.bottomLeft.lat + ',' + bounds.topRight.lon + ',' + bounds.topRight.lat); let elements = response.data.elements; let filteredElements = []; if (el...
[ "function showAllInfo(data) {\n $(\".info_section\").empty();\n if (verifyTeleportDataNotEmpty(data)) {\n const firstCity = data._embedded[`city:search-results`][0];\n showTeleportCityInfo(firstCity);\n showWikipediaInfo(firstCity[`matching_full_name`]);\n } \n else {\n displayNoSear...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 387 The function skipTooMuchSugarDrinks() takes in an array of drinks. Make sure the function only returns an array of drinks with no sugar in it or a little bit of sugar. Drinks that contain too much sugar (in this challenge) are: Cola Fanta
function skipTooMuchSugarDrinks(drinks) { return drinks.filter(x => x !== 'cola' && x !== 'fanta'); }
[ "function unlucky13(nums) {\n return nums.filter(num => num % 13);\n}", "function Drink(teaType, toppingsList, milkOption){\n \"use strict\";\n \n this.teaType = teaType;\n this.toppingsList = toppingsList.slice();\n this.milkOption = milkOption;\n}", "function calcSkip() {\n skipper = Math.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Static Methods Creates a new foreign schema from the given foreign key metadata.
static create(metadata) { return new ForeignKeySchema(metadata.name, metadata.columnNames, metadata.referencedColumnNames, metadata.referencedTableName, metadata.onDelete); }
[ "function resolveHasOneMetadata(relationMeta) {\n if (!type_resolver_1.isTypeResolver(relationMeta.target)) {\n const reason = 'target must be a type resolver';\n throw new errors_1.InvalidRelationError(reason, relationMeta);\n }\n if (relationMeta.keyTo) {\n // The explict cast is nee...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ISECT[] moves point p to the InterSECTion of two lines 0x0F
function ISECT(state) { var stack = state.stack; var pa0i = stack.pop(); var pa1i = stack.pop(); var pb0i = stack.pop(); var pb1i = stack.pop(); var pi = stack.pop(); var z0 = state.z0; var z1 = state.z1; var pa0 = z0[pa0i]; var pa1 = z0[pa1i]; var pb0 = z1[pb0i];...
[ "function formatIntersectingSegment(x, y, i, j, xx, yy) {\n if (xx[i] == x && yy[i] == y) {\n return [i, i];\n }\n if (xx[j] == x && yy[j] == y) {\n return [j, j];\n }\n return i < j ? [i, j] : [j, i];\n}", "function segmentSegmentIntersection( [ x1, y1 ], [ x2, y2 ], [ x3, y3 ], [ x4, y4 ] ) {\n\tret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: Delete the $SyncDoc under $service.
function deleteSyncDoc(service, SyncDoc) { service .documents(SyncDoc) .remove() .then(response => { // console.log(response); console.log("== deleteSyncDoc =="); }) .catch(error => { console.log(error); }); }
[ "function updateSyncDoc(service, SyncDoc) {\n service\n .documents(SyncDoc)\n .update({\n data: { temperature: 30,\n humidity: 20 },\n })\n .then(response => {\n console.log(response);\n// console.log(\"== deleteSyncDoc ==\");\n})\n .catch(error => {\n console.log(error...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
READ Book Issue records
function readBookIssueRecords() { $.get("ajax/BooksIssue/readRecords.php", {}, function (data, status) { $(".records_content").html(data); }); }
[ "function ReadingList()\n{\n\n var book={};\n\n book.read = 0;\n book.unread = 0;\n book.toRead = [];\n book.currentRead = undefined;\n book.readBooks = [];\n book.addBook = addBook;\n book.finishCurrentBook = finishCurrentBook;\n return book;\n }", "function getBookInfo() {\n GoogleB...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update star counter on DOM
updateStarCount(){ $(`#starCount${this.playerId}`).html(`${this.starCount}`); }
[ "function increaseMoveCounter( )\n {\n moves.textContent = ++moveCounter;\n starRating( );\n }", "function updateGenerationCounter() {\n \t\t$('#generation span').html(++generation);\n \t}", "function incMoves() {\n mvs = mvs + 1;\n counter.textContent = 'moves ' + mvs;\n starRating();\n}", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The id of the user that initiated the request
get requestingUserId() { if (this.initiatedByMe) { return this._client.getUserId(); } else { return this.otherUserId; } }
[ "function setUserID(){\n if(isNew){\n spCookie = getSpCookie(trackerCookieName);\n getLead(isNew, spCookie, appID);\n }\n }", "function getUserId(node) {\n return node.parentNode.id;\n}", "function getUserId(req) {\n try {\n const token = req.headers['authorization']; //it is UserId ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }