query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Apply filter to collections list and to collections filters
function applyCollectionsFilter(block, filter, filters$1) { const keyword = filter.keyword.trim(); const hasFilters = filters$1 !== null && filters$1.filterType === 'categories'; const filtersList = filters$1; if (keyword === '') { // Empty if (hasFilters) { // Enable ...
[ "function myFilter(collection, pred){\n result = [];\n for (var i = 0; i < collection.length; i++){\n if (pred(collection[i])){\n result.push(collection[i]);\n }\n };\n return result;\n}", "function FilterListUtil() {}", "filter(collection, condition) {\n if (!assert.isDefined(collection, \"sp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles a restored webgl context
handleContextRestored() { this.renderer.runners.contextChange.run(this.gl); }
[ "function webGL_ContextRestored(context)\n{\n console.log('Rendering context was restored.');\n createGraphicsResources();\n}", "handleWebGLContextRestored() {\n }", "handleContextRestored()\n {\n this.renderer.runners.contextChange.run(this.gl);\n }", "function webGL_ContextLost(context)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add to HTML price attributes for calculating cost
function renderAttrPrice(){ var size = document.querySelectorAll('.card-settings-sizes input') let y = -1; let price=[ // paper, frame, canvas // 30х40 // 40х50 // 50х70 [600, 950, 800], [650, 1100, 950], [700, 1400, 1100] ]; let attr = ['p','f','c'] size.forEach(element => { y++ f...
[ "function add_price(attr_price) {\n lumise.cart.price.attr = attr_price;\n if(lumise.cart.price.color == 0) return;\n var origin_price = lumise.cart.price.base + lumise.cart.price.attr + lumise.cart.price.color;\n var total_price = lumise.cart.price.base * lumise.cart.price.attr * lumise...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this will take whatever token is passed and get its vValue, be it a raw number and its number or a variable and its number converts bin, oct, & hex to their numerical equivalents
function convertTokenToValue(token){ var value; var instr, result, opToken; opToken = token[0]; //array of 1, but its simpler to just convert to 1 token instr = opToken.id; var index, tempHold; var isNeg = false; if(opToken.id.charAt(0) === "-"){ isNeg =true; opToken.id ...
[ "function getTokenValue(token)\n{\n if(isInteger(token))\n return parseInt(token);\n else if(isString(token))\n \treturn token;\n else if(isReservedWord(token))\n \treturn token.replace(/\"/g, \"\"); // A reserved word's value is the word w/out the double-quotes\n else if(isSymbol(token))\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load forget password page
function forget_password(){ localStorage.setItem("time","1000"); localStorage.setItem("link","password_reset.html"); window.open('loading.html',"_self"); }
[ "async getresetPWPage() {\n const token = this.ctx.query.token;\n this.ctx.redirect(`http://${this.config.dns.host}:${this.config.dns.port}/public/resetPW.html?token=${token}`);\n }", "onPasswordsClick_() {\n PasswordManagerImpl.getInstance().recordPasswordsPageAccessInSettings();\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shared by several of the expectState helper methods
function expectStatesSharedUnsettled(ae) { expect(ae.isFinished).toBe(false); expect(ae.isSettled).toBe(false); expect(ae.isRejected).toBe(false); expect(ae.isCanceled).toBe(false); expect(ae.isFailed).toBe(false); expect(ae.isDone).toBe(false); expect(ae.result...
[ "async function assertState(state) {}", "beforeChangeMachineState () {\n }", "act(state){\n\n }", "getState() {\n throw new Error('The state gathering logic is not implemented');\n }", "async function expectedState(token, stateChanges, accounts, name) {\n let state = {}\n switch (name) {\n case...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the map to a canvas using the leafletImage plugin, then convert the canvas to an image string. Append the image string for the bucket to the provided container.
function captureMapBucketImage(mapObject, bucketId, imagesContainer, totalImageCount) { leafletImage(mapObject, function(err, canvas){ // here you can use img for drawing to canvas and handling ///var testString = canvas.toDataURL(); processCanvasToImageContainer(canvas, bucketId, 0, imagesC...
[ "function processCanvasToImageContainer(canvas, bucketId, pageIndex, imagesContainer, totalImageCount) {\n var encodingPrefix = \"base64,\";\n\n try {\n var myImage = canvas.toDataURL();\n var contentStartIndex = myImage.indexOf(encodingPrefix) + encodingPrefix.length;\n imagesContainer[b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot path if any
plot(d) { var track = this.track(); var pathArray = null; if (track) { pathArray = track.plot(d); } return d == null ? pathArray : this; }
[ "plot(d){var track=this.track(),pathArray=null;if(track){pathArray=track.plot(d)}return null==d?pathArray:this}", "plot(d) {\n const track = this.track()\n let pathArray = null\n\n if (track) {\n pathArray = track.plot(d)\n }\n\n return d == null ? pathArray : this\n }", "plot(d) {\n con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
simpleCreate(db.UserVehicle, user_vehicle_list, "user vehicles");
function simpleCreate(DB, object_list, name) { DB.deleteMany({}, (err, objects) => { DB.create(object_list, (err, objects) => { if (err) { return console.log("err", err); } console.log("deleted all", name); console.log("created", objects.length, name); }); }); }
[ "createVehicle(vehicle, success, fail) {\n api.shared().post('/vehicles', vehicle)\n .then(function(response) {\n success(response.data);\n })\n .catch(function(error) {\n console.log(error.response)\n fail(error.response.data);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hides question 1 and displays question 2
function question2() { document.getElementById("question1").style.display = "none"; document.getElementById("question2").style.display = "block"; }
[ "function hideQuestion() {\n $(\"#question0\").hide();\n $(\"#question1\").hide();\n $(\"#question2\").hide();\n }", "function question2() {\n document.getElementById(\"question1\").style.display = \"none\";\n document.getElementById(\"question2\").style.display = \"inline-block\";\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a new instance of the [UriComponent](xref:adaptiveexpressions.UriComponent) class.
constructor() { super(expressionType_1.ExpressionType.UriComponent, UriComponent.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); }
[ "function uri ( href )\r\n\t\t {\r\n\t\t\tvar $this\t= this ;\r\n\r\n\t\t\t// Uri components\r\n\t\t\tthis. __components\t\t= \r\n\t\t\t {\r\n\t\t\t\tanchor\t\t\t: undefined,\t\t// Anchor part\r\n\t\t\t\tdirectory\t\t: undefined,\t\t// Directory after domain name, not including the page\r\n\t\t\t\thost\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: the function below do not adds to the functionality of the game, it only saves the manual efforts and provides scope for scalability of the game this function makes a list of tile indices. the list is need for assigning unqiue indices to the tiles
function mkTileIndice(){ var tileIndice = [] for(var i = 0; i < GAME_SIZE; i++) tileIndice.push(i); return tileIndice; }
[ "getPixelCoordsFromTileIndex(i) {\n return {\n x: (i % this.width.tiles) * this.tileSize,\n y: Math.floor(i / this.width.tiles) * this.tileSize\n };\n }", "function updateTiles(){\r\n let temp = [...gameBoard[0], ...gameBoard[1], ...gameBoard[2], ...gameBoard[3]];\r\n for (let i = 0; i < te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
on click handler for deleting a headline
function headline_delete() { // grab the .data element of the headline to delete var axe_it = $(this).parents(".card").data(); $.ajax( { method: "DELETE", url: "/api/headlines/" + axe_it._id }).then(function(data) { // re-render if deleted if (data) { init...
[ "function handleArticleDelete() {\n\n var articleToDelete = $(this).parents('.article-holder').data();\n\n $.ajax({\n method:'DELETE',\n url:'/api/headlines/' + articleToDelete._id\n }).then(function(data) {\n\n if(data.ok){\n\n initPage();\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check to see if there are two ships of the same color
function checkForDuplicates(board) { console.log('checkForDuplicates invoked'); colorsAlreadySeen = []; for (let i = 0; i < board.length; i++) { let color = board[i].color; let cardType = board[i].type; // If there ARE two ships of the same color, trigger the modal if (car...
[ "isColor() {\r\n const suitedCards = this.getSuitHandArray();\r\n const uniqueSuitedCards = [...new Set(suitedCards)];\r\n return (uniqueSuitedCards.length == 1);\r\n }", "function notSameColor(pos1, pos2) {\r\n var piece1 = board[pos1[0]][pos1[1]];\r\n var piece2 = board[pos2[0]][pos2[1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to force the series expiration for these tests
async function forceExpiration() { await poheth.methods.forceExpiration().send({ from: sellerAddress }); const expired = await poheth.methods.hasExpired().call(); expired.should.be.true; }
[ "checkExpiration() {\n let currentIndex = Object.keys(this.data)[0];\n if (Date.now() > currentIndex) this.clear();\n }", "checkExpiration() {\n const interval = Number(this.options.refreshInterval);\n if (interval) {\n const time = getTime(-interval);\n this.invalidate(time);\n }\n }",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if user has enabled twofa
async twoFaState(req, res) { let twoFaQuery = `SELECT "twofaenabled" FROM users WHERE id = ${req.body.userId}` let enabled = await db.query(twoFaQuery); res.send(enabled[0].twofaenabled); }
[ "get hasTwitter() {\n return this._data.twitter_connected;\n }", "async verify({ user, otp, config }) {\n const api = config('api');\n\n yub.init(api.otp.yubikey.clientId, api.otp.yubikey.secretKey);\n // check if the user has configured an OTP\n const userOTP = await getUser...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
5 2. This function should accept 1 parameter and return the exact same thing. This type of function is called a noop as in (no operation)
function noOp(param) { return param; }
[ "function noOp(parameter) {\n\n return parameter;\n\n}", "function test2(x, y) {\n if (x) { return x; } else { }\n}", "function test2 (a) {\n test1 (0, 1);\n}", "function test4(x, y) {\n return x;\n if (x) { return x; } else { return x; }\n}", "function returnTwo() {\n return 2;\n}", "function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the size of the nodes.
function changeNodeSize(value) { graph.style.nodes_size = value graph.nodes .selectAll('circle') .attr('r', value) }
[ "function changeNodeSize() {\n // recompute the normalization\n var range = _nodeSizeAccessor.getRange();\n _nodeSizeScale.domain([range.min,range.max])\n\n _nodeSizeAccessor.cacheAllValues();\n\n //Redraw all graphics\n _nodeData.forEach(function(d) {\n d.size =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
catnum is the category number for the remote unit.
function checkAndChooseRemoteUnits(catnum) { if (remoteAdd != null) { toggleRemoteAdd(null); return; } else { deselect(); removePointer(); pointerLoc = 0; insertPointer(); toggleRemoteAdd(pointerUnit, catnum); return; } }
[ "function getNumberCategories() {\r\n settings = {\r\n url: \"https://\" + baseURL + \"/api/v2/admins/\" + adminId + \"/categories\",\r\n method: \"GET\",\r\n async: false\r\n };\r\n $.ajax(settings).done(function (response) {\r\n currentCategories = response.TotalRecords;\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SHIFT removes node from the beginning of the list
shift(){ if(!this.head) return undefined; let current = this.head; this.head = current.next; console.log("SHIFT - true"); this.length -= 1; if(this.length === 0){ this.head = null; this.tail = null; } return current; }
[ "shift(){\n var current = this.head;\n this.head= current.next;\n current.next= null;\n this.length--;\n return current.val;\n }", "shift(){\n if(this.head === null) return undefined;\n let old_head = this.head;\n if(this.length === 1){ // if length is 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an interface and its containing file by the interface name
getInterfaceFileLink(ifaceName, containingNamespace) { const lowerName = ifaceName === null || ifaceName === void 0 ? void 0 : ifaceName.toLowerCase(); const ifaceMap = this.getInterfaceMap(); let iface = ifaceMap.get(util_1.util.getFullyQualifiedClassName(lowerName, containingNamespace === null...
[ "getInterface(ifaceName, containingNamespace) {\n var _a;\n return (_a = this.getInterfaceFileLink(ifaceName, containingNamespace)) === null || _a === void 0 ? void 0 : _a.item;\n }", "readGameInterface() {\n\n\t\tconst file = this.archive.get( \"war3mapSkin.txt\" );\n\t\tif ( file ) return new I...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sending an accept message to the server, when the user accepts an incoming call
function accept(){ var connectToUser = $callerName.innerHTML; console.log(connectToUser + ' call accepted'); socket.emit('accept',connectToUser); $caller.style.display = 'none'; $acceptButtons.style.display = 'none'; // $mediaSelection.style.display = "none"; $ringingSound.pause(); }
[ "function answerCall() {\n phone.state = PhoneState.CallAccepted;\n log(\"Accepting incoming call from \" + phone.name);\n if (phone.conn) {\n phone.conn.accept();\n }\n}", "function acceptRequest() {\n replyRequest('ACCEPTED');\n}", "accept (call, callback) {\r\n var self = this;\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepares an Opus packet for playback. This includes attaching metadata to it and encrypting it. It will be stored within the instance, and can be played by dispatchAudio().
prepareAudioPacket(opusPacket) { const state = this.state; if (state.code !== NetworkingStatusCode.Ready) return; state.preparedPacket = this.createAudioPacket(opusPacket, state.connectionData); return state.preparedPacket; }
[ "createAudioPacket(opusPacket, connectionData) {\n const packetBuffer = Buffer.alloc(12);\n packetBuffer[0] = 0x80;\n packetBuffer[1] = 0x78;\n const { sequence, timestamp, ssrc } = connectionData;\n packetBuffer.writeUIntBE(sequence, 2, 2);\n packetBuffer.writeUIntBE(times...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether a given path lies on the perimeter of the rectangle
onPerimeter(v1, v2, delta=.0001) { const dx = Math.abs(Math.abs(v1.x) - this.sizeX) const dy = Math.abs(Math.abs(v1.y) - this.sizeY) const rDx = Math.abs(v1.x - v2.x) const rDy = Math.abs(v1.y - v2.y) return (rDx < delta && dx < delta) || (rDy < delta && dy < delta) }
[ "function isOnPerimeter() {\n var head = _.first(blocks);\n var dim = getScreenGridDim();\n return (head.x === 0 || head.y === 0 || head.x === dim.numCols - 1 || head.y === dim.numRows - 1);\n }", "function checkPointInPath (pos,_path){\n for (point of _path){\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces the placeholders of the matched mappingKey url to create the complete partial help content path.
function getPartialHelpContentPath(replacedMappingPath, variablesToReplaceCamel) { if (mappingPathExists(replacedMappingPath)) { return replacePlaceholder(inlineHelpMapping[replacedMappingPath], variablesToReplaceCamel); } return ''; }
[ "function adjustFragments(key) {\n var entry = emeRegistryReferencesDefinitions[key];\n var fragment = entry.fragment;\n var anchor = \"\";\n var anchorStart = fragment.indexOf('#');\n if (anchorStart !== -1) {\n anchor = fragment.substring(anchorStart);\n fragment = fragment....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Begins polling to determine when pending stylesheets have finished loading in WebKit. Polling stops when all pending stylesheets have loaded or after 10 seconds (to prevent stalls).
function pollWebKit() { var css = pending.css, i; if (css) { i = styleSheets.length; // Look for a stylesheet matching the pending URL. while (--i >= 0) { if (styleSheets[i].href === css.urls[0]) { finish('css'); break; } } pollCount += 1; ...
[ "function pollWebKit() {\r\n var css = pending, i;\r\n\r\n if (css) {\r\n i = styleSheets.length;\r\n\r\n // Look for a stylesheet matching the pending URL.\r\n while (--i >= 0) {\r\n if (styleSheets[i].href === css.urls[0]) {\r\n finish();\r\n break;\r\n }\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
magicBar class should have no knowledge of the Actor or Level classes to keep it decoupled
function MagicBar(config){ this.controller = config.controller; this.mp = config.mp; this.x = config.x; this.y = config.y; this.maxWidth = config.maxWidth; this.height = config.height; this.magic = this.mp; }
[ "function setupAmmoBar() {\n // Get user's opacity preference\n let desiredOpacity = getCSSProperty(\"--dynahud-opacity-ammo-bar\");\n if (desiredOpacity < 1) {\n UIF.hud.onHUDVisible(() => {\n waitForSelector(\".awesome-crosshair--ammo\").then((ammoBar) => {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add all items from_array to_array
array_add_items(from_array, to_array) { for (let i = 0; i < from_array.length; i++) { to_array.push(from_array[i]); } }
[ "function appendAllTo(array, items) {\n return array.push.apply(array, items), array;\n }", "function appendAllTo(array, items) {\n\t return array.push.apply(array, items), array;\n\t }", "function appendAllTo(array, items) {\r\n return array.push.apply(array, items), array;\r\n }", "static ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the cloning of ArrayBuffer objects, as specified in the W3C spec.
function _handleArrayBufferClone(buf) { var dst = new ArrayBuffer(buf.byteLength); for (var i = 0, l = buf.byteLength; i < l; i++) { dst[i] = buf[i]; } return dst; }
[ "static _cloneArrayBuffer(source) {\n // Array.apply method of turning an ArrayBuffer into a normal\n // array is very fast (around 5ms for 250K) but\n // doesn't work in WebKit with arrays longer than about 125K\n // if(source.length > 1)\n // {\n // return Array.apply( [], source );\n // }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For every subtitles in the submitted array that needs it, downloads the underlying file using its 'Url' property and saves the resulting string into an 'AsBlob' property.
function downloadSubs (subsArray, callback) { var downloadFailures = []; // This part will be called after we've tried to download all subtitles var finishIfAllDownloaded = _.after(subsArray.length, function(){ // Filter out subs that failed to download var downloadedSub...
[ "async download() {\n const posterURLs = this.getPosterURLs();\n const subtitlesURLs = this.getSubtitlesUrls();\n\n this.downloading = true;\n this.saveToCache([...posterURLs, ...subtitlesURLs]);\n this.runIDBDownloads();\n }", "function uploadSubs (subsArray, callback) {\n // Collect data ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtiene los chatstories de los usuario que sigue un determinado usuario.
function getFeedByUserName(req, res) { let userName = req.params.userName; User.findOne({login: userName}, 'siguiendo', function (err, usu) { if (err) { res.status(400).send('Ha ocurrido un error'); } else if (!usu) { res.status(200).send('No se ha encontrado el usuario'); } else if (usu) {...
[ "function getAllUsers() {\n\t\tchatIds = sortByKey(chatIds, 'name');\n\t\t//alert(JSON.stringify(chatIds));\n\t\tvar v,count = 0;\n\t\t\t\tvar topbar = '<section class=\"module\">\\\n\t\t \\\n\t\t <ol class=\"discussion\">';\n\t\t\n\t\t\t\tvar bottombar = ' </ol>\\\n\t\t \\\n\t\t</section>';\n\t\t\t\tfor (v in ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the paragraph has toc style.
isTocStyle(paragraph) { let style = paragraph.paragraphFormat.baseStyle; return (style !== undefined && (style.name.toLowerCase().indexOf('toc') !== -1)); }
[ "isHeadingStyle(para) {\n let style = para.paragraphFormat.baseStyle;\n if (style !== undefined) {\n return isNullOrUndefined(this.tocStyles[style.name]) ? false : true;\n }\n return false;\n }", "function hasAutoToc(tree) {\n if (tree.children.length < 3) {\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates and initializes a new ContentLoader instance.
function createContentLoader(args) { args = args || {}; args.applicationName = defaultValue(args.applicationName, 'default'); args.platformName = defaultValue(args.platformName, 'generic'); args.version = defaultValue(args.version, 'lates...
[ "setupLoader() {\n var self = this;\n var opts = {\n value : self.value,\n attributes : self.attributes\n };\n\n // Check Assets Types\n if (typeof self.value == 'function') {\n self.loader = new FunctionLoader(opts);\n }\n else if (t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets or sets the highlight color of selected contents.
get highlightColor() { return this.highlightColorIn; }
[ "function colorSelected() {\n var node = this.selection.getNode();\n return standardizeColor(Element.getStyle(node, 'color'));\n }", "function backgroundColorSelected() {\n var node = this.selection.getNode();\n return standardizeColor(Element.getStyle(node, 'backgroundColor'));\n }", "get selecti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to specialize the edge drawing for MyClass. Overwrite or comment out / delete
drawVertex2D(pixp1) { // to specialize the edge drawing for MyClass. Overwrite or comment out / delete if (this.selected) stroke(this.selectcolor); else stroke(this.color2D); strokeWeight(10); point(pixp1.x, pixp1.y); // you might want to change this }
[ "showEdge() {\n if(Edge.activeEdges.find(element => element === this)) {\n this.sketch.stroke(100, 100, 100);\n } else {\n this.sketch.stroke(10, 10, 10, 220)\n }\n if (this.edgeType == 'co' || this.edgeType == 'ea' ||this.edgeType == 'la' || this.from.component.typ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build the consumed energy object based on scheduled devices
calculatePrice(scheduledDevices) { let totalPrice = 0.0; const pricePerDevice = {}; for (let hour = 0; hour <= 23; hour++) { const rate = this.powerplan.getRate(hour); let subtotal = 0; let power = 0; for (let i = 0; i < scheduledDevices.length; ...
[ "compute(eVals) {\n const v = {}\n\n // Battery Capacity[MWh]\n v['Battery Capacity [MWh]'] =\n eVals['Base Energy Requirement [MW]'] *\n (HOURS_PER_DAY * (1 - eVals['Planned Capacity Factor']))\n\n // Round Trip Efficiency\n v['Round Trip Efficiency'] = this.tech['Efficiency (Thermal or Ro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt 4: Create a function named alphaOrder that returns a passed string with letters in alphabetical order.
function alphaOrder(alpha) { alpha = alpha.toLowerCase(); return alpha.split('').sort().join(''); }
[ "function alphabetizeLetters( string ){\n\n}", "function alphaOrder(str) {\n\treturn str.split(\"\").sort().join(\"\");\n}", "function alphabet(){\n\tvar newAlpha = input.value;\n\tvar alphaInput = newAlpha.split(\"\").sort().join(\"\");\n\t\n\tconsole.log(alphaInput);\n\tdomText.innerHTML += \"<div> Your strin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pull from the remote
async pull() { const remote = await spawnGit(["config", "--get", "remote.origin.url"]); if (!remote.length) return this.sendMessage({ type: "remoteNotConfigured" }); await spawnGit(["pull"]); }
[ "pull(remote, branch, _) {\n Files.assertInRepo();\n Config.assertNotBare();\n Gitlet.fetch(remote, branch);\n return Gitlet.merge('FETCH_HEAD');\n }", "executeGitPull() {\n this.state.gitApi.pull(this.props.currentFileBrowserPath)\n .then(response => {\n if (response.cod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
splits the chosenGame into an array with individual characters
function splitLetter() { for (var h = 0; h < nameLength; h++) { splitArray.push(chosenGame[h]); } return splitArray; }
[ "function startGame () {\n selectCharacter = charOffice[Math.floor(Math.random() * charOffice.length)];\n lettersinName = selectCharacter.split(\"\");\n numBlanks = lettersinName.length;\n \n //Resets\n wrongGuess = [];\n guessLeft = 15;\n blanksAndSuccess = [];\n\n //Populate blanks and ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper function of String::replace without considering of head/tail bookmarks nodes.
function replace(str, regexp, replacement) { var headBookmark = '', tailBookmark = ''; str = str.replace(/(^<span[^>]+_ke_bookmark.*?\/span>)|(<span[^>]+_ke_bookmark.*?\/span>$)/gi, function (str, m1, m2) { m1 && ( headBookmark = m1 ); m2 && ( tai...
[ "function replace( str, regexp, replacement ) {\n\t\tvar headBookmark = '',\n\t\t\ttailBookmark = '';\n\n\t\tstr = str.replace( /(^<span[^>]+data-cke-bookmark.*?\\/span>)|(<span[^>]+data-cke-bookmark.*?\\/span>$)/gi, function( str, m1, m2 ) {\n\t\t\tm1 && ( headBookmark = m1 );\n\t\t\tm2 && ( tailBookmark = m2 );\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merges the defaults set in the typeDefaults and subtypeDefaults into the appModel part
function mergeTypeDefaults(part) { part.type = _.get(part, 'type', appLib.appModel.metaschema.type.default); const defaults = _.get(appLib.appModel, ['typeDefaults', 'fields', part.type], {}); _.mergeWith(part, defaults, doNotOverwrite); if (_.has(part, 'subtype')) { const subtypeDefault...
[ "function mergeTypeDefaults(part, coerceDefaultType) {\n if (!part.type) {\n if (!coerceDefaultType) {\n return;\n }\n part.type = appLib.appModel.metaschema.type.default;\n }\n\n // Merging into new object because of _.mergeWith(part, defaults, someCustomFunc) forces to handle revers...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the collector associated with this menu.
createCollector() { // Checks Permissions (not possible in DM). if (!this.isDM) { if (!this.channel.permissionsFor(this.bot).has('READ_MESSAGE_HISTORY')) throw new ReactionMenuError('Missing READ_MESSAGE_HISTORY permission!'); if (!this.channel.permissionsFor(this.bot).has('MANAGE_MESSAGES')) throw new Reacti...
[ "createCollector() {\n\t\tconst filter = (reaction, user) => (this.emojis.includes(reaction.emoji.name) || this.emojis.includes(reaction.emoji.id)) && user.id === this.memberId;\n\t\tconst collector = this.message.createReactionCollector(filter, { time: this.timeout });\n\n\t\tcollector.on('collect', async reaction...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Get Generated Player Props by Team / / Year of the season and the season type. If no season type is provided, then the default is regular season. Examples: 2018REG, 2018PRE, 2018POST / Week of the season. Valid values are as follows: Preseason 0 to 4, Regular Season 1 to 17, Postseason 1 to 4. Example: 1, 2, etc / Ab...
getGeneratedPlayerPropsByTeamPromise(season, week, team){ var parameters = {}; parameters['season']=season; parameters['week']=week; parameters['team']=team; return this.GetPromise('/v3/nfl/odds/{format}/PlayerPropsByTeam/{season}/{week}/{team}', parameters); }
[ "getGeneratedPlayerPropsByWeekPromise(season, week){\n var parameters = {};\n parameters['season']=season;\n parameters['week']=week;\n return this.GetPromise('/v3/nfl/odds/{format}/PlayerPropsByWeek/{season}/{week}', parameters);\n }", "function GamesPerWeek(season, week, type, gam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a year range from the decade the current year is in.
function createYearRange(current){ var i, j, result = []; for(i = floor(current / 10) * 10, j = floor(current / 10 + 1) * 10; i < j; ++i) { result.push(i); } return result; }
[ "nextDecade() {\n return new YearRangeModel(this.year + 10);\n }", "currentDecade() {\n return new YearRangeModel(new Date().getFullYear());\n }", "generateYearRange() {\n const remainder = this.year % YEARS_TO_DISPLAY;\n const floor = this.year - remainder;\n const ceil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Created a function to display a GIF after answering a question
function displayGIF(status,correctAnswer) { if(status === "win") { $(".triviaText").html(` <p>Congrats you chose correctly!</p> <p>The correct answer was ${correctAnswer}</p> <img src="${randomImage()}"/> `) } else if (status === "lose") { $(".triviaText"...
[ "function runGif(){\n $(\"#answers\").append(\"<img src=\" + pick.gif + \">\");\n nextQuestion.push(pick);\n triviaQuestions.splice(index,1);\n\n // Stop GIF from running //\n\n var hideGif = setTimeout(function(){\n $(\"#answers\").empty();\n timer= 20;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts a matrix into a graph/node representation
matrixToGraph(matrix) { let g = new Graph() let nodeMatrix = new Array(matrix.length) for (let i = 0; i < matrix.length; i++) { nodeMatrix[i] = new Array(matrix[0].length) } for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[0].length; j+...
[ "function fromMatrix(matrix) {\r\n return matrix.reduce(function (rowAcc, data, row) {\r\n return data.reduce(function (colAcc, cell, column) {\r\n return cell ? set({ row: row, column: column }, cell, colAcc) : colAcc;\r\n }, rowAcc);\r\n }, EMPTY);\r\n}", "buildFromData(adjacency_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts the userinputted string into an array of regexes
function formatText(string) { var outputArray = []; string.split("\n").forEach(function(url) { outputArray.push(new RegExp(url)); }); return outputArray; }
[ "static matchAll (string, regexp) {\r\n let matches = [];\r\n\r\n string.replace(regexp, () => {\r\n let arr = [].slice.call(arguments, 0);\r\n let extras = arr.slice(-2);\r\n arr.index = extras[0];\r\n arr.input = extras[1];\r\n matches.push(arr);\r\n });\r\n\r\n return matches...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
exportResults Exports Results (table listings) to CSV
function exportResults() { var filename = 'HM-BusinessLicenseResults_' + (new Date()).getTime() + '.csv'; var charset = "utf-8"; var items; if (results.length <= 0){ items = convertToCSV(businesses); } else { items = convertToCSV(results); } var blob = new Blob([items], { type: "text/csv...
[ "function exportAsCSV() {\n let csvData = '';\n csvData += 'Title,Test Type,Input Count,Output Count\\n';\n csvData += `${getTestTitle()},${testMode},${inputCount},${outputCount}\\n\\n\\n`;\n csvData += $('table').eq(0).table2CSV();\n csvData += '\\n\\n';\n $('table').slice(1).each(function (group...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TANK OBJECT has name, code store, dead/alive, program counter, xcell coord, ycell coord, id mapping to its sprite
function Tank (name, x, y, instructions) { this.name = name; this.type = 0; this.code = instructions; this.labels = {}; this.alive = true; this.pc = 0; this.x = x; this.y = y; this.orientation = 0; this.system = { "variables" : Array.apply(null, Array(32)).map(function () {}), "target" : undefined, "...
[ "function tile(x, y, type, status, parentBoard) { \n this.x = x;\n this.y = y;\n this.type = type;\n this.status = status;\n this.bombCount = 0;\n}", "constructor() {\n super();\n this._size = new Vector(40, 17);\n this._className = ItemClass.TANK;\n this._shotInterval = 800;\n this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
operations refers to fetch image as 'getObject' or upload image as 'putObject' Improvement To be done / 1. Bucket Policy change, specified domains allowed only 2. Make dynamic dir path prefix by providing into mutation it self, so that every client will have their folder in bucket it self, which will be containing thei...
function getSignedUrl(filename, filetype, foldername, operation) { const folderName = foldername; const params = { Bucket: 'gsg-image-uploads', Key: `${folderName}/` + filename, Expires: 604800 }; if(operation==='putObject'){ params['ContentType'] = filetype; } retu...
[ "putObject(image) {\n const params = {\n Bucket: image.bucketName,\n Key: image.fileName,\n Body: image.data,\n Metadata: { \"img-processed\": \"true\" },\n ContentType: image.headers.ContentType,\n ACL: im...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
refresh the story list
function refreshStoryList(){ if (document.getElementById('storyResults')!=null) document.getElementById('storyResults').innerHTML=''; }
[ "function update_story_list() {\n\t$('#story_list').empty();\n\t$.post('/student/stories-request', function (result) {\n\t\tif (result == 'EMPTY_RESULT') {\n\t\t\t$('#story_list').append($('<p>', { text: \"You haven't started any stories yet!\" }));\n\t\t}\n\t\telse {\n\t\t\tfor (item in result) {\n\t\t\t\tvar stor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows the modal for user to select which member to add
function addMemberModal(id) { $('#addModal').modal('show'); document.getElementById("addMemberButton").onclick = () => addMember(id); document.getElementById("parentGroupEmailAdd").innerHTML = groups[groups.findIndex(elem => elem.id == id)].email; // add all groups and users as options var memberOp...
[ "function addFriendModal() {\n $('#addFriendModal').modal('show');\n }", "function showNewMemberMenu(rm) {\n console.log('Add a new member.');\n let name = readlineSync.question(' Name: ');\n let email = readlineSync.question(' Email: ');\n let zip = readlineSync.question(' Zip Code: ');\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
atualiza os centroides dos eixos x
atualizaCentroideX() { if (this.centroidesX.length <= 0) { this.centroidesX[0] = this.eixoX[this.indice1]; for (let i = 1; i < this.grupos; i++) { this.centroidesX[i] = this.eixoX[this.indice2]; } } else { for (let i = 0; i < this.gr...
[ "function atualizaCentroideX() {\r\n if (centroidesX.length <= 0) {\r\n centroidesX[0] = eixoX[0];\r\n for (let i = 1; i < grupos; i++) {\r\n centroidesX[i] = eixoX[eixoX.length - 1 - i];\r\n }\r\n } else {\r\n for (let i = 0; i < grupos; i++) {\r\n centroides...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name: BottomEdge() Purpose: the purpose of this function is to slide the picture down Parameters: N/A Return: N/A
function BottomEdge() { $( "#target" ).animate({paddingTop:"+=310px"}); }
[ "function goBottom() \r\r\n{\r\r\n scrollInit();\r\r\n\tthis.moveIt(0,oCont.clipHeight-this.clipHeight) ;\r\r\n}", "CantGoOverBottom() {\r\n if (this.y >= this.bottomBoundary) {\r\n this.y = this.bottomBoundary;\r\n }\r\n }", "checkBottomEdge() {\n if (this.position > (p5.height - ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a new SP.FieldLocation to the collection
addLocation(title, properties) { const props = { FieldTypeKind: 33 }; return this.add(title, "SP.FieldLocation", extend(props, properties)); }
[ "addElementToDocument(kmlDoc, parent, name, value) {\n if (name === 'Features') {\n value.forEach((feature) => {\n const featureType = Object.keys(feature)[0];\n this.addElementToDocument(kmlDoc, parent, featureType, feature[featureType]);\n });\n } else {\n const element = kmlDoc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load schemas local to FIWARE Data Model (that should be named using schema.json pattern)
loadLocalSchemas(fullPath) { let files; if (fullPath !== '.') { files = getFiles(fullPath + path.sep + '*-schema.json'); } else { files = getFiles('*-schema.json'); } debug('*loadLocalSchemas* - files: ' + files); return files; }
[ "function loadSchemas() {\n /*schemasIds.forEach((schemaId) => {\n const schema = require('../schemas/' + schemaId);\n schemas.push(schema);\n schemasById[schemaId] = schema;\n });*/\n }", "loadSchemas() {\n const schemadir = '@adobe/helix-pipeline/src/schemas'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assets When a vm is present (instance creation), we need to do a threeway merge between constructor options, instance options and parent options.
function mergeAssets(parentVal,childVal,vm,key){var res=Object.create(parentVal||null);if(childVal){"development"!=='production'&&assertObjectType(key,childVal,vm);return extend(res,childVal);}else{return res;}}
[ "function mergeAssets(parentVal,childVal,vm,key){var res=Object.create(parentVal || null);if(childVal){'development' !== 'production' && assertObjectType(key,childVal,vm);return extend(res,childVal);}else {return res;}}", "function mergeAssets(parentVal,childVal,vm,key){var res=Object.create(parentVal||null);if(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method works on a specific object, represented by id "strObjID". The method retrieves the element with the given ID from the DOM, and then extracts the player ID from the video object. Then, it removes the video object from the page's DOM and stores its location in the page in a global dictionary variable (this wi...
function makeMobileCompatible(strObjID, videoTagID){ //our video object (which we need to remove) var vidObj = document.getElementById(strObjID); //extract the playerID of this video object before deleting it var vidPlayerID = getParamValueForVidObject(vidObj, 'playerID'); var programmedVideo = getParamValueForV...
[ "function getVideoObj(videoID) {\n\tvar videoObj;\n\tstate.videos.forEach(function(video) {\n\t\tif(video.id.videoId == videoID) {\n\t\t\tvideoObj = video;\n\t\t\treturn;\n\t\t};\n\t});\n\treturn videoObj;\n}", "function PickNewVideo(iVideoInfo, iAutoPlay, iQuote, iPageObjectIds)\r\r\n{\r\r\n DebugLn(\"PickNewVi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notifies listeners only if the user is current
_notifyListenersIfCurrent(user) { if (user === this.currentUser) { this.notifyAuthListeners(); } }
[ "_notifyListenersIfCurrent(user) {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }", "function _userStatusNotify() {\n $rootScope.$broadcast('user:updated', user);\n }", "authListener(){\n Firebase.auth().onAuthStateChanged((user) => { if(user !== null){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
global Excel, Office, console Delete the sample worksheet with sales table
async function deleteSampleWorkSheet() { return Excel.run(async context => { context.workbook.worksheets.getItemOrNullObject("Sample").delete(); }); }
[ "function deletingrow(){\n temp--;\n var spread = $(\"#ss\").wijspread(\"spread\");\n spread.useWijmoTheme = true;\n spread.tabStripVisible(false);\n spread.showHorizontalScrollbar(false);\n spread.showVerticalScrollbar(false);\n\n var sheet = spread.getActiveSheet();\n sheet.isPaintSuspend...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if this dialog is in private browsing mode.
function inPrivateBrowsingMode() { return PrivateBrowsingUtils.isWindowPrivate(window); }
[ "get privateBrowsingEnabled PBS_get_privateBrowsingEnabled() {\n return this._inPrivateBrowsing;\n }", "isPrivate() {\n\t\t\tif (cur.module === \"profile\") return CONTEXT.isPrivateUser();\n\t\t\telse {\n\t\t\t\tconst altItem = CONTEXT.getCurrentAltItem();\n\n\t\t\t\t// we never can know for sure\n\t\t\t\tif ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function called when user clicks "Edit View" button
function editView(element) { var viewIndex = indexInClass(element, document.getElementsByClassName("tabContent")[currentViewingTab]) var currentView = config.tabs[currentViewingTab].views[viewIndex] var type = currentView.class var typeName = type.replace(/(Depiction)|(View)/g,""); createAlert( ...
[ "showEditView() {\n this.state = FIELD_STATE.EDIT;\n this.update();\n }", "function Edit() {}", "function editSelected(){\n // todo \n }", "function editClicked() {\n edit = true;\n}", "function handleEditClick() {\n _isEditOpen = true;\n _$editButton.hide();\n _$view.hide()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete all videos no track
function delete_video_notrack(){ $('#delete').on('click', function (e) { $('.close').click(); e.preventDefault(); $("#sitem-table tbody").html(''); $("#csv_export button").attr('disabled','disabled').css('cursor','not-allowed'); retu...
[ "function deleteAllVideoElements() {\n $('#videos').empty();\n const contextOptions = document.getElementById('contextOptions');\n if (contextOptions) contextOptions.style.display = 'none';\n clearContext();\n}", "deleteVideo(video){\n \tif(video){\n \t\tdeleteFromArray(video, this.videos);\n \t\tdeleteFro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
href: A URL or a local path TODO: download SVG files asynchronously (currently, files are downloaded synchronously, which is obviously undesirable)
function getSvgContent(href) { var content; if (href.indexOf('http') === 0) { content = fetchFileSync(href); } else if (require$1('fs').existsSync(href)) { content = require$1('fs').readFileSync(href, 'utf8'); } else { stop("Invalid SVG location:", href); } return content; }
[ "generateSVGDownloadLinks() {\n\n var svg_header = '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>';\n\n document.getElementById('map-download').href = \"data:image/svg+xml;base64,\" + window.btoa(svg_header + document.getElementById('map-area').innerHTML);\n document.getElementBy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unlinks user from socket upon Google sign out.
function googleSignoutSuccess() { const self = this; console.log(`${self.socket.user.username} signed out.`); self.socket.user = { accountSK: null, username: null }; Broadcast.lobbyRefresh(self.socket); }
[ "function google_logout() {\n var auth2 = gapi.auth2.getAuthInstance();\n auth2.signOut().then(function () {\n console.log('User signed out of google on app.');\n });\n}", "function googleAuthSignOut(){\n\tvar auth2 = gapi.auth2.getAuthInstance();\n auth2.signOut().then(function () {\n \taut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sprite A css Sprite: sheet is the spritesheet which this object will be using to render the sprite. So sheetX and sheetY is the top left hand corner of the area we're grabbing. dx and dy are used optionally to place the sprite offcenter
function Sprite(x, y, sheet, sheetX, sheetY, width, height, dx, dy, maskRect){ this.x = x; this.y = y; this.sheetX = sheetX; this.sheetY = sheetY; this.width = width; this.height = height; this.dx = dx || 0; this.dy = dy || 0; this.div = document.createElement("div"); this.div.style.backgroundImage ...
[ "function Sprite(x, y, sheet, sheetX, sheetY, width, height, dx, dy){\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.sheetX = sheetX;\n\t\tthis.sheetY = sheetY;\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.dx = dx || 0;\n\t\tthis.dy = dy || 0;\n\t\tthis.div = document.createElement(\"div\");\n\t\tthis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create rows for the roles form.
function create_row(user_id) { id_list = roles.concat(["user", "remove"]); for (i in id_list) { var last_row_td = $('#roles-last-row-' + id_list[i]); if(last_row_td.attr("class") == "table-row-bottom") last_row_td.attr("class", "table-row-general"); last_row_td.attr("id", ""); } var row = $('<tr...
[ "function createRoleTable() {\n\tvar token = getClientStore().token;\n\tsessionStorage.token = token;\n\ttotalRecordsize = retrieveRoleRecordCount();\n\tif (totalRecordsize == 0) {\n\t\tobjCommon.displayEmptyMessageInGrid(getUiProps().MSG0231, \"Role\");\n\t\t$(\"#chkSelectall\").attr('checked', false);\n\t\t$(\"#c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles chat messages from Telegram. We should identify commands and handle them We should respond for the commands we dd not process or do not understand
function telegramHandler(event, context) { if(!event["body"]["message"] || !event["body"]["message"]["text"]) { return context.succeed({}); // Meh } var command = parseCommand(event["body"]["message"]["text"]); handleCommand(command, event["body"]["message"]["chat"]["id"], function(message) { return tel...
[ "function onMessage (data) {\n if (data.subtype != null) {\n return;\n }\n\n if (data.user === slack.user) {\n return;\n }\n\n var response = commands.handle(data.text);\n if (response == null || response === false) {\n return;\n }\n\n server.send('respond.message', {\n channel: data.channel,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Our general strategy is this: All collapsible buttons are set to not flex and live in the "quickfilterbarcollapsiblebuttons" hbox. This provides us with a nice minimum size. All flexy widgets have some minimum size configured. When the bar starts to overflow we save off the (minimum) size of the bar so that once it get...
onOverflow() { // If we are already collapsed, there is nothing more to do. if (this._buttonLabelsCollapsed) { return; } let quickFilterBarBox = document.getElementById( "quick-filter-bar-main-bar" ); let collapsibleButtonBox = document.getElementById( "quick-filter-bar-collap...
[ "onWindowResize() {\n // nothing to do here if the buttons are not collapsed\n if (!this._buttonLabelsCollapsed) {\n return;\n }\n\n let quickFilterBarBox = document.getElementById(\n \"quick-filter-bar-main-bar\"\n );\n // the client width is how big it actually is (thanks to overflow:h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
// // // // // // // // // // CHALLENGE SOLUTION METHODS // // // // // // // // // returns the value at the middle index of the list
middle() { let index = this.size - 1 if(index % 2 === 0) { // size is even return this.get(Math.floor(index * .5)) } // size is odd return this.get((index * .5) + 1) }
[ "function getMiddle(list) {\n list= [10,30,50,70,90,110];\n let middleNumber= 0;\n numLength =list.length;\n if(numLength%2===0){\n middleNumber=(list[numLength/2-1]+list[numLength/2])/2;\n } else{ \n answer =list[(numLength-1)/2];\n }\n document.getElementById(\"showArray\").innerHTML= middleNumber; \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redraws the points on the minimap where notes are located.
function redrawMinimap() { miniClear(0); for (let i = 0; i <= tracks.length; i++) { let index = i; if (i === selectedTrack) continue; if (i === tracks.length) index = selectedTrack; // Draw the selected track last for (let j = 0; j < tracks[index].notes.length; j++) { if (!level.noteGroups[index].isVisible...
[ "function redrawPath() {\n //Clear the path\n while (path.getPath().getLength()) {\n path.getPath().pop();\n }\n //Then redraw\n for (var markerName in markers) {\n path.getPath().push(markers[markerName].getPosition());\n }\n}", "function refresh()\n\t{\n\t\t// clear lines\n\t\tfo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return signed JWT from student data.
function createToken(student) { let payload = { username: student.username }; return jwt.sign(payload, SECRET); }
[ "function simpleJWT(){\n const secretKey= 'secretKey'; //secret key que será usada en el token\n const claims={ //contenido del JWT playload\n userName:'The user name'\n }\n //generamos el jwt\n const token =jwt.sign(claims,secretKey);\n console.log(token);\n}", "function signJWT () {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
spawn enemies multipul enemies on a delay
function spawnMultipulEnemies() { if (enemies.length <= numberOfEnemies && deadEnemies <= numberOfEnemies){ if (newEnemySpawn.isDone() ) { enemies.push(new Enemy (enemyX, enemyY, pathToFollow, cellHeight, cellWidth, enemyHealth)); newEnemySpawn.reset(); } } for(let i = 0; i < enemies.length...
[ "spawnNewEnemies() {\n const seconds = 10;\n if (this.enemySpawnCounter >= seconds * 1000) {\n console.log(\"remove timer\");\n this.enemySpawnCounter = 0;\n this.enemyTimer.remove(false);\n this.enemySpawnConfig.delay -= 50;\n if (this.enemySpawn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initiates countdown clock Page 'Weekend'
function ctd () { var note = $('#note'), ts = new Date.today().next().saturday(); console.log( "Countdown time set for: "+new Date.today().next().saturday() ); // if((new Date()) > ts){ // // The new year is here! Count towards something else. // // Notice the *1000 at the end - time must be in milliseconds ...
[ "function countDown(stop_d, stop_h, stop_m) {\r\n var stopMilli = weekTimeToMilliseconds(stop_d,\r\n stop_h,\r\n stop_m);\r\n var nowObject = new Date();\r\n var nowMilli = weekTimeToMilliseconds(nowObject.getDay(),\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to set the given key if the key in the given object matches the given type
function setIf( obj, key, type ){ if( typeof obj[key] === type ) Settings[key] = obj[key]; }
[ "function setIfInstance( obj, key, type ){\n\t\t\tif( obj[key] instanceof type || obj[key] === null ) Settings[key] = obj[key];\n\t\t}", "function setRuntimeType(obj, type) {\n obj[_runtimeType] = type;\n }", "function changeKeyByID(objectID, theKey, value) {\n myLibrary.forEach(Object => {\n if (Object...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merges an overflow sequence with a key sequence.
function mergeOverflows(keySequences, overflowKeySequences) { var overflowSequenceLen = overflowKeySequences.length; var overflowSequence = (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__spreadArrays)(overflowKeySequences).pop(); var newKeySequences = (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__spreadArrays)(keySequen...
[ "function addSequences(sequence, allowedKeys, remainingLength, keySequences) {\n if (remainingLength <= 0) {\n keySequences.push(sequence);\n } else {\n for (var i = 0; i < allowedKeys.length; i++) {\n addSequences(sequence + allowedKeys[i], allowedKeys,\n remainingLength ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
elimina los textos tachado y tornillo del numero
function eliminarTextosNumeros(item){ item = String(item); item = item.replace("tachados-", ""); item = item.replace("tornillo-", ""); return item; }
[ "function eliminaPuntoSeparatore(thisElem) \r\n{\r\n var childs = thisElem.childNodes.length; //numero di nodi figli di ciascuna sezione passata come parametro\r\n for (var j = 0; j < childs; j++)\r\n if ((typeof(thisElem.childNodes[j]) != \"undefined\") && (thisElem.childNodes[j].nodeName == \"#text\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to parse json and return it. Returns defaultValue if parse fails or the parsed data is not of same type as defaultValue.
tryParseJson(json, defaultValue = []) { try { const parsedJson = JSON.parse(json); if (typeof parsedJson !== typeof defaultValue) { return defaultValue; } return parsedJson; } catch(e) { return defaultValue; } ...
[ "function parseJSON(json, fallback) {\n try { return JSON.parse(json) || fallback; } catch (e) { return fallback; }\n}", "function parseJSON(value) {\n return value === 'undefined'\n ? undefined\n : // JSON.parse() doesn't accept non-string values, this is why we pass empty\n // strin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove the old deck.
function removeDeck() { const elements = document.getElementsByClassName("deck"); while (elements.length > 0) elements[0].remove(); }
[ "function deck_delete() {\n\tg_decks.splice(g_ui.deckIdx, 1);\n\n\tlet selectedIdx = g_ui.deckIdx - 1;\n\tif (selectedIdx < 0)\n\t\tselectedIdx = 0;\n\t\t\n\tdeck_list_update();\n\tdeck_select_by_index(selectedIdx);\n\n\tlocal_store_decks_save();\n}", "function removeFromDeck(deck, card) {\n\n}", "deleteCard() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Attempts to run dhcpcd on the interface to get us an IP address
function dhcp () { return new Promise(function(resolve, reject) { execDHCP(function(err, stdout, stderr) { if (err) { wifi.error("There was an unknown error enabling dhcp" + err); reject(err); } else { // Com...
[ "getIPAddress() {\r\n var interfaces = require('os').networkInterfaces();\r\n for (var devName in interfaces) {\r\n var iface = interfaces[devName];\r\n \r\n for (var i = 0; i < iface.length; i++) {\r\n var alias = iface[i];\r\n if (alias.family === 'IPv4' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the additional list of entities to be highlighted.
function updateAdditionalHighlight() { let entsAdd = []; // list of entities units to be highlighted let entsRemove = []; let highlighted = g_Selection.toList(); for (let ent in g_Selection.highlighted) highlighted.push(g_Selection.highlighted[ent]); if (g_ShowGuarding) // flag the guarding entities ...
[ "function updateHighlights(){\n\t\tfor(i=0; i < Highlights.length; i++){\n\t\t\th = Highlights[i];\n\t\t\tif (h != null){\n\t\t\t\tcontext.font = h.font;\n\t\t\t\tcontext.fillStyle = h.color + h.alpha + \")\";\n\t\t\t\tcontext.fillText(h.text,h.xLocation,h.yLocation);\n\t\t\t\th.xLocation += h.xDeslocation;\n\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a TraitTree returns a text summary describing the result.
function getSummary(tree) { // return the array and put into description section return assemble(tree); }
[ "function calculateStatistics(tree){\n\tvar statistics = \"\";\n\tvar passRate = (tree.totalPass/tree.totalTests)*100;\n\tif(Number.isNaN(passRate)){\n\t\tpassRate = 0;\n\t}\n\tvar passRateRound = Math.round(passRate);\n\n\tvar dynamicTotal = sumAllInformationByClass(SCENARIO_TEST_TOTAL_CSS_CLASS);\n\tvar dynamicPa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
D2 EVLRN test cases
function GetTestCase_EVLRN () { var testCases = []; for (EV = 1; EV < 4; EV++) { if (EV == 1) event = '00000000'; if (EV == 2) event = '00000001'; if (EV == 3) event = 'FFFFFFFF'; for (EVindex = 1; EVindex < 4; EVindex++) { if (EVindex == 1) eventIndex = 0; if (EVindex == 2) eventIndex = 1; ...
[ "function GetTestCase_NENRD () {\n\t\tvar testCases = [];\n\t\tfor (NN = 1; NN < 4; NN++) {\n\t\t\tif (NN == 1) nodeNumber = 0;\n\t\t\tif (NN == 2) nodeNumber = 1;\n\t\t\tif (NN == 3) nodeNumber = 65535;\n\t\t\tfor (Eindex = 1; Eindex < 4; Eindex++) {\n\t\t\t\tif (Eindex == 1) eventIndex = 0;\n\t\t\t\tif (Eindex ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Event after catch error in mp4box
onMp4BoxError (err) { console.error(err) }
[ "function onYTPlayerError(event) {\n $(document).trigger('videoDone');\n }", "function onPlayerError(event) {\n console.log('error code:', event.data);\n playCurrentVideo(nextVideo);\n }", "videoError (err) {console.log('video player error: ', err)}", "function onMediaError(e) {\n console.lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
here we make use of the ref system in react, which allows us to get a direct reference to an html element that has been rendered to the page once this renders to the page, we can get a direct reference to it by using this.refs.map
render() { return <div ref="map" />; }
[ "render() {\n return <div ref=\"map\" />;\n }", "render () {\n return <div ref=\"map\"/>;\n }", "render() {\n return (\n <div className=\"map\">\n <div className=\"leafletMount\" ref={(c) => { this.mapRef = c; }} />\n </div>\n );\n }", "function refMap(el) {\n ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback for toggling the Presentation mode. Simply hide the unwanted elements with jQuery.
function togglePresentation(){ if($('#runButton').is(":hidden")){ // Presentation mode is being turned off // Automatically decrease previously increased font size editorFontSize -= 10; $('.CodeMirror').css('font-size', editorFontSize + 'px'); // Show hidden elements $('#runButton').show(); ...
[ "function enableHideInternal() {\n $el.find(\".hide-internal\").css(\"display\", \"\");\n }", "hidePreview() {}", "function hide() {\n\tthis.owner.el.style.display = 'none';\n}", "function presentationSingle() {\n $('#presentation').modal('hide');\n\n if (presentationMode) {\n singleLayoutOff...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetching the searched Question
function fetchQuestion() { const result = QuestionModel.findAll({ attributes: ["id", "Question"], where: { ["Question"]: { [Op.like]: `%${searchString}%`, }, }, }); return result; }
[ "function findQuestion(query){\t\n\tfor(var prop in datastore){\n\t\tvar index = prop.indexOf(query);\n\t\tif(index >= 0){\n\t\t\treturn prop;\n\t\t}\n\t}\n\tvar no_answer;\n\treturn no_answer;\n}", "function getQuestion() {\n var questionNum = $('#qNumber').text();\n var question = _.findWhere(envision.det...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resign, with the resigning player determined from iAmRed.
function resign() { // Update the timing properties if we're using time control. var moveEnd = new Date().getTime(); if (stats.timeControl != -1) { if (stats.future[0] == "r") { stats.redTime -= moveEnd - stats.moveStart; } else { stats.bluTime -= moveEnd - stats.moveStart...
[ "function resign(ev) {\n let user_id = window.userID;\n let channel = ev.data.global_channel;\n // only the player has button.\n channel.push(\"resign\", {\n user_id: user_id,\n game_id: ev.data.game_id\n })\n .receive('ok', (msg) => {\n // nothing need to do in fact.\n window.location...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adding a new business
add(req, res) { return businesses .create({ name: req.body.name, description: req.body.description, category: req.body.category, link: req.body.link }) .then((result) => res.status(201).send(result)) .catch((error) => res.status(400).send(error)) }
[ "function addBusiness(email, surveyName, target, problem, solution, cost, successCb){\n //check to see if business exists, if not, create\n var Business = Parse.Object.extend(\"Business\");\n var query = new Parse.Query(Business);\n query.equalTo(\"surveyName\", surveyName);\n query.count({\n su...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the simulated cellular radio status
get radioStatus(){ return this.cellularRadio; }
[ "function GetSIMStatus() {\n var SIMStatus = 0;\n var result = syncRequest({cmd :'modem_main_state'});\n if(!result) {\n return SIMStatus;\n } \n switch(result.modem_main_state)\n {\n case \"modem_init_complete\":\n case \"modem_imsi_waitnck\":\n SIMStatus = 1;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper to build the text response for charging status.
function buildChargingStatus(charging) { let response = ""; if (charging.BatteryStatusRecords.BatteryStatus.BatteryChargingStatus == "NOT_CHARGING") { response += "Your car is not on charge."; } else { response += "Your car is on charge."; } return response; }
[ "function buildChargingStatus(charging) {\n\tlet response = \"\";\n\tif(charging.BatteryStatusRecords.BatteryStatus.BatteryChargingStatus == \"NOT_CHARGING\") {\n\t\tresponse += \"Your car is not on charge.\";\n\t} else {\n\t\tresponse += \"Your car is on charge.\";\n\t}\n\t\n\treturn response;\n}", "function bui...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether the file should be skipped
function isSkipFile( data ) { return /\/_[^\/]*$/.test( data.path ); }
[ "shouldSkipSource(sourcePath) {\n const status = this.getSkipStatus(sourcePath);\n if (typeof status === 'boolean') {\n return status;\n }\n if (this.matchesSkipFilesPatterns(sourcePath)) {\n return true;\n }\n return undefined;\n }", "function sk...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change to update mode for employee
function employeeUpdateMode(employeeId) { $.get("?action=edit&employeeId=" + employeeId, function(resp) { var employeeName = resp.employeeName; var employeeDept = resp.employeeDept; if(employeeName != null && employeeDept != null) { $('#employee_back').show(); $('#employeeBtn').html("Update Employee"); ...
[ "set updateMode(value) {}", "function updateEmployee() {\n\n}", "function updateEmployeeRole() {\n console.log(\"employee role updated\"); \n\n}", "toggleEditMode() {\n\t\tthis.setEditMode(!this.model.get('edit'));\n\t}", "toggleEditMode() {\n if (this.editMode === true) {\n this.disableEditM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inspects the tiles in each column and updates model accordingly.
function parseColumnTiles() { scope.$apply(function () { var layout = scope.layout; if (singleColumnMode) { layout.one_column_layout = parseTileOrder(column1); } else { ...
[ "function parseColumnTiles() {\n $scope.$apply(function () {\n var layout = vm.layout;\n\n if (singleColumnMode) {\n layout.one_column_layout = parseTileOrder(column1);\n } else {\n layout.two_colum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start the GSM Module
function Start_Gsm() { answer="OK"; console.log("GSM Starting.."); pinMode(C0,"output"); digitalPulse(C0,1,2000); Send_Command("AT\r\n",500,function(){Set_SMS_Mode(); }); }
[ "start() {\n return new Promise((resolve, reject) => {\n this.buildModemInterface().then((serial_port) => {\n this.serial = serial_port;\n resolve();\n }).catch((err) => {\n reject(err);\n });\n })\n }", "function Set_SMS_Mode() {\n answer=\"OK\";\n console.log(\"Setti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AJAX loading of submissions for each student
function loadSubmissions() { function ajaxDone() { // There's just one ajax call when the page loads } // alert('Found ' + window.terms.length + ' terms for this faculty member.'); for (term of window.CST.terms) { for (student of term.students) { getSubmissionsByStudent(term.course_id, term.co...
[ "function loadSubmissions() {\n // Don't let user refresh data while it's already loading\n // const btn = document.getElementById(\"btnLoadData\");\n // if (btn) {\n // btn.disabled = true;\n // }\n\n // How many AJAX calls will it take to load the page?\n var targetAjaxCount = 0;\n for (term of window....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
What happens when a user clicks on the reservation canvas? Currently we just turn green seats into red ones
function clickOnReservationCanvas(e) { var ctx = contextReservation; //get seat number var seat = getSeatFromClick(e); if(seat.row < 0 || seat.column < 0 || seat.row >= rows || seat.column >= cols){ return; } //draw red seat over the green one var posx = seatOffsetX + seat.column * seat_free.width; var pos...
[ "function selectSeat(e){\n\t\te = event.target;\n\t\tseats.forEach(function(seat) {\n\t\t\tif (e.innerText == seat.number && seat.status==='a') {\n\t\t\t\tseat.status = 's';\n\t\t\t} else if (e.innerText == seat.number && seat.status==='s') {\n\t\t\t\tseat.status = 'a';\n\t\t\t}\n\t\t})\n\t\tif ($(this).hasClass('a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
odtworzenie Video w Modalu
function playVideoInModal() { player = videojs('modalVideo'); player.ready( function() { player.currentTime(5); player.volume(0.5); player.play(); }); // event zakończenia filmu player.on('ended', function() { modal.classList.remove('modalOpen'); player.dispose(); }); }
[ "function videoModal(){\n $(\"#what-we-do-modal\").on(\"show.bs.modal\", function(){\n if (availablePlayer) window.player.playVideo();\n });\n \n $(\"#what-we-do-modal\").on(\"hide.bs.modal\", function(){\n if (availablePlayer) window.player.pauseVideo();\n });...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of the actions starting at the provided time parameter.
function getActionsStartingAt(time){ var result = []; var actions = currentActions; for(var i in actions){ var action = actions[i]; if( action.start == time ){ result.push(action); } } return result; }
[ "static get actions() {\n let actions = [];\n\n for (let [title, minutes] of Object.entries(Minutes.#$list)) {\n minutes += \"\\n\\n\";\n let pattern = /^(?:@|AI\\s+)(\\w+):?\\s+([\\s\\S]*?)(\\n\\n|$)/gm;\n let match = pattern.exec(minutes);\n\n while (match) {\n actions.push({\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
from task > All vehicles should have speed and propulsion units create vehicle abstract object
function Vehicle(speed,propulsionUnits) { this.speed=speed; this.propulsionUnits = propulsionUnits; }
[ "function Vehicle() {}", "function vehicle(type, len, width, u, v, speedLong, speedLat, mixedModel){\n //console.log(\"vehicle: in vehicle cstr: type=\",type);\n\n\n this.type=type;\n this.len=len; // car length[m]\n this.width=width; // car width[m]\n this.u=u; // arc length [m]\n this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }