query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
stores the amount array in localStorage
function setAmount() { localStorage.setItem("amount", JSON.stringify(amount)); //updates the cart }
[ "function saveDuration(number){\r\n durationArray.push(number);\r\n localStorage.setItem(\"durationLocal\", JSON.stringify(durationArray));\r\n}", "function updateLocalStorage() {\n\tlocalStorage.setItem('transactions', JSON.stringify(transactions));\n}", "function setLocalStorage() {//we want to save income,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the description cell to add to row.
function createDescCell(data) { var tabCellTxt = document.createTextNode(data.description); var anchor = document.createElement('a'); anchor.href = data.url; anchor.appendChild(tabCellTxt); var tabCell = document.createElement('td'); tabCell.appendChild(anchor); return tabCell; }
[ "function createDescriptionCol(item) {\n\treturn '<td align=\"left\" class=\"description\">' + item.name + '</td>';\n}", "function createCell(row, content) {\n // insert cell at the end of the row\n var cell = row.insertCell();\n cell.textContent = content;\n}", "function buildInfoTable(rows) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Methods to work with live contract form schema
function LiveContractFormModel() { var typeReg = /#[^#]+$/; this.type = 'live_contract_form'; this.getFieldType = function(field) { var map = {'select-group' : 'group'}; var schema = field.$schema; var type = schema.substring( schema.lastIndexOf('#') + 1 ); ...
[ "function transformXMLToForm(xmlData) {\r\n\tvar jsObj = parser.parse(xmlData, parserOptions)\r\n\tvar form = new SDCForm()\r\n\r\n\tvar traversalStack = []\r\n\tvar getSection = () => {\r\n\t\tvar section = traversalStack.indexOf(\"Section\")\r\n\t\tif(section == -1)\r\n\t\t\treturn -1\r\n\r\n\t\tif(section < trav...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the value at the back of the list.
get back() { return this.get(this.length - 1); }
[ "popBack() {\n const last = this.length - 1;\n const value = this.get(last);\n this._vec.remove(last);\n this._changed.emit({\n type: 'remove',\n oldIndex: this.length,\n newIndex: -1,\n oldValues: [value],\n newValues: []\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
prepends searchTerms[field] with param array and returns compiled object
function prependArrayToSearchTerms(array, field) { var index = 0; var collection = {}; // add array to empty collection for (var i = 0; i < array.length; i++) { collection[index] = array[i]; index++; } // add existing searchTerms to collection var keys = Object.keys(searchTerms[field]); for (v...
[ "function prependObjectToSearchTerms(keys, object, field) {\n var index = 0;\n var collection = {};\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n if (key !== \"count\") {\n // add object value for key to collection\n if (object.hasOwnProperty(key)) {\n collection[index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finds the next position of type M
function findNextM(arr, offset){ if(offset === false) return false for(var i = offset, len = arr.length;i < len;++i){ if(arr[i][0] == 'M') return i } return false }
[ "nextId(position){\n position+=1;\n if(this.machine.length >position){\n return this.machine[position].activity_id\n }\n return -1\n }", "function lookForWhatToMove(key) {\n var coord = \"\";\n for(var r = 0; r < dim_max; r++) {\n for(var c = 0; c < dim_max; c++) {\n if(m[r][c] == 16) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a placeholder cell widget from a raw cell model.
_createPlaceholderCell(model, index) { const contentFactory = this.contentFactory; const editorConfig = this.editorConfig.raw; const options = { editorConfig, model, contentFactory, updateEditorOnShow: false, placeholder: true }...
[ "_createRawCell(model) {\n const contentFactory = this.contentFactory;\n const editorConfig = this.editorConfig.raw;\n const options = {\n editorConfig,\n model,\n contentFactory,\n updateEditorOnShow: false,\n placeholder: false\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To add the given filepath to the given array of Paths if it does not already exist in the array
function addIfUnique( filePath, Paths ){ if( Paths.indexOf( filePath ) === -1 ){ Paths.push( filePath ); } }
[ "function addPath(filePath) {\n if (relativePath) {\n if (inRelativePath(filePath)) {\n const relative = path.relative(relativePath, filePath);\n result.push(relative);\n }\n }\n else {\n result.push(filePath);\n }\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to map field names in attributes and where conditions
function mapOptionFieldNames(options, Model) { if (Array.isArray(options.attributes)) { options.attributes = options.attributes.map(attr => { // Object lookups will force any variable to strings, we don't want that for special objects etc if (typeof attr !== 'string') return attr; // Map attribu...
[ "function filterFields(data, fields, mapping) {\n const filtered = Object.keys(data)\n .filter(function(key) {\n return fields.indexOf(key) >= 0;\n })\n .reduce(function(obj, key) {\n const mapKey = (mapping && mapping[key]) || key;\n obj[mapKey] = data[key];\n return o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normarize Salesforce API host name
function normalizeApiHost(apiHost) { var m = /(\w+)\.(visual\.force|salesforce)\.com$/.exec(apiHost); if (m) { apiHost = m[1] + ".salesforce.com"; } return apiHost; }
[ "getServiceBaseHostURL() {\n let routeInfo = this.store.peekRecord('nges-core/engine-route-information', 1);\n\n //if(!routeInfo) routeInfo = this.store.peekRecord('nges-core/engine-route-information', 2);\n let hostUrl = 'http://' + routeInfo.appCode + '.' + routeInfo.appModuleCode + config.NGES_SERVICE_H...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
region createParticipant this is the only function that should be called internally to create participants (both self and remote)
function createParticipant(options) { extend(options, { ucwa: ucwa, isTabActive: isTabActive.asReadOnly(), contactManager: contactManager }); ...
[ "function createParticipantEvent(participant_ids, hangout_id, timestamp) {\n app.service('participant_events').create(\n {\n participants: participant_ids,\n hangout_id: hangout_id,\n timestamp: timestamp\n }, function(error, data) {\n if (error) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get all users from comments
findUsers(comments) { const users = []; comments.forEach((c) => { users.push(c.name); }); return users; }
[ "function getUsers(req, res){\n\tvar identity_user_id = req.user.sub; // id del usuario logueado\n\tvar page = 1;\n\t\n\tif(req.params.page){\n\t\tpage = req.params.page;\n\t}\n\t\n\tvar itemsPerPage = 5; // numero de usuarios listados por paginas\n\t\n\tuserModel.find().sort('_id').paginate(page, itemsPerPage, (er...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a vscode.Selection object
selection(start, end) { return new vscode.Selection(start, end); }
[ "static fromJSON(json) {\n if (!json || !Array.isArray(json.ranges) || typeof json.primaryIndex != \"number\" || json.primaryIndex >= json.ranges.length)\n throw new RangeError(\"Invalid JSON representation for EditorSelection\");\n return new EditorSelection(json.ranges.map((r) => Selectio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a wrapper rule that freezes the `context` properties.
create(context) { freezeDeeply(context.options); freezeDeeply(context.settings); freezeDeeply(context.parserOptions); return (typeof rule === "function" ? rule : rule.create)(context); }
[ "function wrap (fn) {\n return function () { return fn.apply(this, arguments) }\n}", "function wrap(observable) { return new Wrapper(observable); }", "function needsContextInParams (wrappedFunction) {\n\treturn function (params, callback) {\n\t\tlog.debug(\"Supplied context:\", params.context);\n\t\tif (!param...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to calculate total likes
findTotalLikes() { //Calculate totalLikes and totalDislikes const totalLikesandDisLikes = this.state.quotes.map(quote => ({ ...quote, likes: this.state.likes[quote.id], dislikes: this.state.dislikes[quote.id] })); const totalLikes = totalLikesandDisLikes.reduce((sum, quote) => { return sum + quote["...
[ "findTotalDisLikes() {\n\t\t//Calculate totalLikes and totalDislikes\n\t\tconst totalLikesandDisLikes = this.state.quotes.map(quote => ({\n\t\t\t...quote,\n\t\t\tlikes: this.state.likes[quote.id],\n\t\t\tdislikes: this.state.dislikes[quote.id]\n\t\t}));\n\t\tconst totalDisLikes = totalLikesandDisLikes.reduce((sum, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of all delegates for the given school ID.
getDelegates(schoolID) { return _get('/api/delegates', {school_id: schoolID}); }
[ "function getAllRouteSchoolsBySchoolId(schoolId) {\n var deferred = $q.defer();\n $http({\n url: '/api/RouteSchool/GetAllRouteSchoolsBySchoolId/' + schoolId,\n method: 'GET'\n //headers\n }).success(function (data) {\n defe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
modifico el html del response, para todo input, si tiene id lo dejo, si no tiene le seteo un id y agrego el evento onChange
adaptarHTML(){ debugger; //let boddy = '<div><form><input type="search"/><input type="search" id="BBB"/></form></div>'; DUMMY let boddy = this.state.boddy; let processedHTML = ''; let counter = 1; let $div = $('<div>').html(boddy); ...
[ "function edit_html(variant_cookie, response) {\n const edited = new HTMLRewriter()\n .on('title', new Rewriter(variant_cookie, 'title'))\n .on('h1#title', new Rewriter(variant_cookie, 'h1#title'))\n .on('p#description', new Rewriter(variant_cookie, 'p#description'))\n .on('a#url', new Rewriter(variant_cookie,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to save and update vm jobs inputed by clicking the save button
function saveVmpsJobs() { var data = {}; if ($('#name').val() == '') { $("#errLabel").html('&nbsp;&nbsp;&nbsp;&nbsp; Please enter job name') return false; } if ($('#platforms').val() == null) { $("#errLabel").html('&nbsp;&nbsp;&nbsp;&nbsp; Please select platform(s)') return false; } if ($('...
[ "function editSave() {\n if (!inputValid()) return;\n vm.editObj.id = -3;\n server.addBuoy(vm.editObj).then(function(res) {\n queryBuoys();\n queryBuoyInstances();\n gui.alertSuccess('Buoy added.');\n }, function(res) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert `node` is a Unist node.
function assertNode(node) { if (!node || !string(node.type)) { throw new Error('Expected node, got `' + node + '`') } }
[ "function assertNodeType(node, type) {\n const typedNode = checkNodeType(node, type);\n\n if (!typedNode) {\n throw new Error(`Expected node of type ${type}, but got ` + (node ? `node of type ${node.type}` : String(node)));\n } // $FlowFixMe: Unsure why.\n\n\n return typedNode;\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
vbScript FormatDateTime function: FormatDateTime(date,format) thanks to Rob Eberhardt of Slingshot Solutions for free use of partial versions of the vbScript native Date functions many of these Date functions have been modified from the original author's design
function FormatDateTime(thedate, df) { var vbGeneralDate=0; var vbLongDate=1; var vbShortDate=2; var vbLongTime=3; var vbShortTime=4; var vbYYYYMMDD=5; var vbDDdotMMdotYY=6; var vbDDdotMMdotYYYY=7; var vbYYslashMMslashDD=8; var vbDDslashMMslashYY=9; var vbYYYYhyphenMMhyphenDD=10; var datstr=thedate.toSt...
[ "function date_format(value, format) {\r\n\t\r\n\t//var datetime = (typeof(value)=='object' ? value : new Date(value)), \r\n\t//alert(format);\r\n\tvar result = format;\r\n\tvar datetime = new Date(value); /* (value instanceof Date ? value : new Date(value)),*/\r\n\tresult = result.replace('Y', datetime.getFullYear...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if this is the last one in the opened overlays stack
get _last() { return this === OverlayElement.__attachedInstances.pop(); }
[ "has_next_frame() {\n if(this.frame_idx >= this.frames.length-1) return false;\n else return true;\n }", "isLastRow(): boolean {\n return this.getRowIndex() === this.getHeight() - 1;\n }", "function atTopLevel() {\n return Object.is(topBlock,currentBlock);\n }", "get isLas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
buildRequest Builds a request object for the AWS StepFunctions start() method parameters
function buildStepFunctionRequest(arn, request, name) { const stateMachineArn = `arn:aws:states:${arn.region}:${arn.account}:function:${arn.appName}-${arn.fn}`; let input; if (request.headers) { request.headers["X-Correlation-Id"] = state_1.getCorrelationId(); request.headers["x-calling-func...
[ "internalRequest(request) {\n const transformer = this.getTransformer(request);\n return transformer.transform(currentSuite.get(this), new runtime_1.Runtime());\n }", "function newRequest(data){\n var request = createNewRequestContainer(data.requestId);\n createNewRequestInfo(request, data)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a OAuth2 client based on the current configuration. This client is ready to be loaded with credentials and used.
function getClient() { return new googleapis.auth.OAuth2( config.clientId, config.clientSecret, config.redirectUrl ); }
[ "function initClient() {\n \n const keys = {\n // fill\n };\n\n return new Gdax.AuthenticatedClient(\n keys[\"API-key\"],\n keys[\"API-secret\"],\n keys[\"Passphrase\"],\n keys[\"Exchange-url\"]\n );\n}", "function buildClient(){\n if(!client){\n\n const {acmE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
7. Save company images
async function saveCompanyImages(req, res) { try { const payload = { id: req.params.id, files: req.files, collection: Company, type: "IMAGE_COMPANY", fieldToEdit: "profileImage" }; const resp = await dataBase.saveFiles(payload); return res.status(resp.code).send(resp); ...
[ "function save() {\n\n var image = canvas.toDataURL(\"image/png\");\n //grab the title the user entered\n var title = document.getElementById('nameForm').value;\n //save into collection called sketches, this is found in items.js\n Meteor.call('sketches.insert', title , image);\n console.log(title+...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the links for the given cell into the given graph by requesting the respective data in the serverside (implemented for this demo using the serverfunction)
function load(graph, cell) { if (graph.getModel().isVertex(cell)) { var cx = graph.container.scrollWidth / 2; var cy = graph.container.scrollHeight / 2; // Gets the default parent for inserting new cells. This // is normally the first child of the root (ie. layer 0). var parent = graph.getDefaultParent();...
[ "function renderNetworkGraph(id, path, collection_type, urlParams) {\n var api = (collection_type == 'symbol' ? 'getSymbolLinks' : 'getDieLinks'); \n\n //alert(urlParams);\n $('#' + id).removeClass('hidden');\n $('#' + id).height(600);\n \n $.get(path + 'apis/' + api, $.param(urlParams, true),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that converts the gridInfoMap to populate the gridInfoByField and gridInfoById.
function convertGridInfoMap(){ gridInfoByField = {}; gridInfoById = {}; gridChildrenInfoMap = {}; //-- where is this p property from and why is there only that one property var originalMap = gridInfoMap; if( originalMap.hasOwnProperty( "p" )){ originalMap = originalMap.p; } if( originalMap.metaColumns ...
[ "static mergeColumnInfo(columnInfo, newInfo) {\n columnInfo.primitiveCount += newInfo.primitiveCount;\n columnInfo.objectCount += newInfo.objectCount;\n for (let item of newInfo.sorted) {\n let key = item.key;\n let obj = columnInfo.structure[key];\n if (obj ===...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For EntryWidget. We don't update category in PATCH, so we just need the name, not the pk.
getCategoryName(pk) { let categoryObject = this.state.categories.find(category => category.pk === pk); return categoryObject.category }
[ "get_name_by_id(cat_id){\n const sql = `select category_name, category_id\n from categories\n where category_id = ?`\n return db.raw(sql, cat_id);\n }", "function getDatabaseParameterPutCategory (params, query, body){\r\n\treturn body.category;\r\n}", "get category () {\n\t\tretur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the new/used quantity on hand for a given itemID (the itemID must be on the invoice; if not, a 0 is returned)
function get_quantity(itemID,nu) { var idx = array_search(itemID,qty_itemIDs); if (idx > -1) { var qnew = qty_new_orig[idx]; var qused = qty_used_orig[idx]; if (nu == ITEM_NEW) { return qnew; } else { return qused; } } else { return -1; } }
[ "getTotalItemsById(itemId){\n return this.items[itemId].quntity;\n }", "sell(itemid, quantity)\n {\n var func = \"Inventory.sell\";\n\n if(!this.has(itemid))\n {\n console.warn(func + \": cannot sell an item (\" + itemid + \") we don't have.\");\n return fal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function takes 3 arguments: the age of the renter, the size of the car, and the number days for the rental. The function should return an integer number of the calculated total cost of the rental. Age (integer) : There is a daily charge of $10 if the driver is under 25 Car Size (string) : There may be an additional...
function insurance(age, size, numofdays){ let sum = 0; if (age < 25) { sum += (numofdays * 10) //There is a daily charge of $10 if the driver is under 25 }; if (numofdays < 0) { return 0 //Negative rental days should return 0 cost. }; if (size === "economy") { //car size surcharge "economy" $0 "medi...
[ "function getSurcharge(totalCar)\n {\n let surcharge = 0;\n if (document.getElementById(\"age25\").checked)\n {\n surcharge = totalCar * 1.3\n }\n\n return surcharge;\n }", "function calculateDogAge(age, conversionRate) {\n var dogYears = age * conversionRate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
printLoginStatus(state: LoginState) success > body fail > reason
function printLoginStatus(state) { if ('response' in state) { console.log("" + state.response.body); } else { console.log("" + state.reason); } }
[ "function printLoginStatus(state) {\n if (state.result === 'success') {\n console.log(\"\" + state.response.body);\n }\n else {\n console.log(\"\" + state.reason);\n }\n }", "function login (password) {\n if (password === \"test1234\") {\n return \"Login Su...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses a given simulation_history into timestamps and simulation objects Returns a list of the timestamps for handling
function parseSimulationHistory(simulation_history){ if(simulation_history!==null&&simulation_history!==''){ timestampList=[]; current_simulation_history_list=simulation_history.state; //iterate through all of the states for (var i=0; i<current_simulation_history_list.length; i++){ timestamp=current_simulat...
[ "get stationHistory() {\n this._logger.trace(\"[getter] stationHistory\");\n // XXX: this is just a hacky way of duplicating the array.\n return this._stationHistory.concat([]);\n }", "function retrieveLogs(simulation){\n\t//calls function from localSimulationManager\n\tvar device_list=getAllDeviceObjec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle the team panel button press and assign the player to the team
function OnJoinTeamPressed() { // Get the team id asscociated with the team button that was pressed var teamId = $.GetContextPanel().GetAttributeInt("team_id", -1); // Request to join the team of the button that was pressed Game.PlayerJoinTeam(teamId); }
[ "function handleMenuPlayerClick(e) {\n\t\tvar element = e.currentTarget;\n\t\tvar success = \"\";\n\t\tvar { id, team, position, selectedposition, selectindex } = element.dataset;\n\t\tif (selectedposition == position) {\n\t\t\tif (!element.hasAttribute(\"selected\") && userTeam.count < 15) {\n\t\t\t\t//control sam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks in session storage if the modal was shown before, if it wasn't it is shown. Code for bootstrap modal usage from
function showHowToPlayModal() { const key = 'howToPlayModalDisplayed'; if (!sessionStorage.getItem(key)) { let howToPlayModal = new bootstrap.Modal(document.getElementById('how-to-play-modal')); howToPlayModal.show(); sessionStorage.setItem(key, true); } }
[ "function openModal() {\n\t\t\t//Create timestamp object\n\t\t\tconst timestamp = { session_id: new Date().getTime() };\n\t\t\tconsole.log(timestamp);\n\n\t\t\t//Get and/or set page variation\n\t\t\tlet imgId = '';\n\t\t\tif($cookies.imgValue !== undefined) {\n\t\t\t\timgId = $cookies.imgValue;\n\t\t\t} else {\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Escape a code string
function escapeCodeString(str) { const escapeCodeStringTable = { 39: '\\\'', 34: '\\"', 92: '\\\\', 8: '\\b', 12: '\\f', 10: '\\n', 13: '\\r', 9: '\\t' }; var r = '', c, cr, table; for (var i = 0; i < str.length; i++) { c = str[i]; cr = c.charCodeAt(0); table = escapeCodeStringTable[...
[ "function escape(code){\n \tcode = code\n \t\t//.replace(/[\\s\\t]+/g, '') // �ո���Tab\n .replace(/('|\"|\\\\)/g, '\\\\$1')// ��˫�����뷴б��ת��\n .replace(/\\r/g, '\\\\r')// ���з�ת��(windows + linux)\n .replace(/\\n/g, '\\\\n');\n \treturn outCode + '\"' + code + '\";';\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNZIONE CERCA SERIE Questa funzione cerca una serieTv.
function cercaSerie(query){ // chiamata ajax per interrogare sito TheMovieDb serieTrovate = []; $.ajax({ url: 'https://api.themoviedb.org/3/search/tv?', method: "GET", data: { api_key: api_key, query: query }, ...
[ "if (conv === verdadero) {\n\t\t\t\t\t\t\t\t\tconv = convertidores [conv2];\n\n\t\t\t\t\t\t\t\t// De lo contrario, inserte el tipo de datos intermedio\n\t\t\t\t\t\t\t\t}", "function viewSerie(it) {\n const tmpDicomInstances = dicomList.filter(value => value.serie === it.serie);\n setDicomInstances(t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the option for a particular game element. Then render that game element
setUpGameElement(element, renderer) { this.gameElements[element].options = this.buildList(element, $(this.gameElements[element].editList)); this.renderOptions(this.gameElements[element].options, $('.content', this.gameElements[element].container), this.renderElementOption ); $(this.gameElements[...
[ "renderElementOption(option) {\n return `\n <div class=\"game-element option ${option.element}\" data-element=\"${option.element}\" data-option=\"${option.name}\">\n ${option.name}\n </div>\n <span class=\"score\">score : [${option.score}]</span>\n `...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open the embargo type dialog box. This will work for opening an existing embargo, or adding a new embargo.
function embargoOpenDialogHandler(isNew, id) { if(isNew == null && typeof(isNew) == "undefined") { isNew = false; } if (!isNew) { // Loading an existing type var array_key = -1; for(embargo in jsDataObjects.embargosArray) { if(jsDataObjects.embargosArray[embargo].id == id) { array_key = embargo; ...
[ "expandForTypes(e) {\n e.preventDefault()\n let type = e.target.value\n productTypeManager.update(type)\n productTypeManager.show()\n }", "function openAddEditor(e) {\n\n\t\tvar editorType = e.id.substr(0, e.id.indexOf('-')); \n\t\t//alert( editorType);\n\n\t\tdocument.getElementByI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a Promise that resolves when the element has completed updating. The Promise value is a boolean that is `true` if the element completed the update without triggering another update. The Promise result is `false` if a property was set inside `updated()`. If the Promise is rejected, an exception was thrown during...
get updateComplete() { return this.getUpdateComplete(); }
[ "get isCompleteUpdate() {\n // XXX: Bug 514040: _ums.isCompleteUpdate doesn't work at the moment\n if (this.activeUpdate.patchCount > 1) {\n var patch1 = this.activeUpdate.getPatchAt(0);\n var patch2 = this.activeUpdate.getPatchAt(1);\n\n return (patch1.URL == patch2.URL);\n } else {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
equalsToFloats(x, y, z, w) { return this.x === x && this.y === y && this.z === z && this.w === w; }
[ "equalsToFloats(x, y, z) {\n return this.x === x && this.y === y && this.z === z;\n }", "equals(otherVector) {\n return (otherVector &&\n this.x === otherVector.x &&\n this.y === otherVector.y &&\n this.z === otherVector.z);\n }", "pointsEqual(p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sum up arrays of the same dimensions
function sumArrays(arrays) { var i,j,output = []; arrays.forEach(function(array) { for(i=0;i<array.length;i++) { if(!output[i]) output[i] = []; for(j=0;j<array[0].length;j++) { if(!output[i][j]) output[i][j] = 0; output[i][j] += array[i][j]; } } }); return output; }
[ "function multiDimSum(arr) {}", "function addArrays(array1, array2) {\n let arrayToNumber1 = parseInt(array1.join(''));\n let arrayToNumber2 = parseInt(array2.join(''));\n if (array1 === 'undefined' && array2 === 'undefined') return [];\n if (isNaN(arrayToNumber1)) arrayToNumber1 = 0;\n if (isNaN(a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render history HTML from JSON.
function history_json_to_html(data) { var html = ""; for (var i = 0, len = data.events.length; i < len; i++) { var event = data.events[i]; var type_icon; switch (event.type) { case "future": case "future_series": case "record": type_icon = "images/745_1_11_Vid...
[ "function renderCityHistory() {\n $(\"#cityHistoryList\").html(\"\");\n $(cityHistory).each(function (i) {\n cityListEl = $(\"<a>\", {\n class: \"list-group-item list-group-item-action\",\n }).text(cityHistory[i]);\n $(\"#cityHistoryList\").append(cityListEl);\n });\n }", "function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Biggest swap on ETH until 18 May 2021: 0x6b1594e1a7aa3f2dfa3b00f8913745d961579d7e7e97950364cce11c02459d56 Biggest swap on BSC until 18 May 2021:
async function findLargestSwapOn1InchV3(chainId = 1) { const web3 = getWeb3(chainId) const { routerV3, startBlock } = await get1InchInfos(chainId) const contract = new web3.eth.Contract(routerAbi, routerV3) const params = { filter: (event) => isStableCoins(event.returnValues.dstToken, chainId) || isStableC...
[ "function getApproximateBlockchainHeight(_date, _nettype){\n\n //Szero\n // time of liberty birth 2014-04-18 10:49:53 (1397818193)\n var libertyBirthTime = _nettype == \"Mainnet\" ? 1627060976 : _nettype == \"Testnet\" ? 1627060976 : 1627060976;\n // avg seconds per block in v1\n var secondsPerBlockV...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the zombie direction based on the position of the hero
function zombie_hunt() { if (hero.pos.x === zombie.pos.x) { if(hero.pos.y < zombie.pos.y) { zombie.direction = DIR_UP; } else if (hero.pos.y > zombie.pos.y) { zombie.direction = DIR_DOWN; } } else if (hero.pos.x < zombie.pos.x) { zombie.direction = DIR_LEFT; } else { ...
[ "moveDown(){\n\t\tthis.aimDir = vec2.down();\n\t}", "update(){\n\t\tthis.degrees+=(this.direction%2==0)?1:-1; // Even number clockwise/Uneven number anti-clockwise\n\t\tthis.degrees%=360;//Start count from 0 again, once it degrees goes to 360 or higher\n\t\tthis.x-=this.speed;//Move the bloodcell (on x-axis, righ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================= Funcion que se permite comprobar si hace click en los botones cerrar de la vantana modal donde se carga el audio Si se hace click se elimina el div donde se carga el audio ==============================================
function cerrarVentanaAudio(){ $("#btn_small_cerrar_modal").click(function(){ $("#audio").remove(); //se elimina el div por si hay algun audio cargado }); $("#btn_cerrar_modal").click(function(){ $("#audio").remove(); //se elimina el div por si hay algun audio cargado }); }
[ "function escucharAudio(select){\n var id_select = $(select).attr(\"id\");\n var codigo_inspector = $(select).val();\n var nombre_audio = $('#'+id_select+' option:selected').text(); //tomamos el texto seleccionado\n $(\"#audio\").remove(); //se elimina el div por si hay algun audio cargado\n if (nombre_audio !...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the source of an expression or string.
function source(re) { return (re && re.source) || re; }
[ "function getSource() {\n const queryString = window.location.search;\n const urlParams = new URLSearchParams(queryString);\n const source = (urlParams.get(\"source\"));\n return source;\n}", "get source() {\n \t\t\t\treturn test.stack;\n \t\t\t}", "getValueSource() {\n return this._source;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is used to revoke confirmation
function revokeCustomConfirmationPopup() { hideModel('confermPopUp'); }
[ "function cancelMentorshipRequest() {\n return confirm(\"Are you sure you want to cancel your ongoing Mentorship Request?. No record of your current application will be kept.\");\n}", "function cancelMentorship() {\n return confirm(\"Are you sure you want to cancel mentorship?\");\n}", "function mentorCan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
caches frequently requested songs. If a song is not already cached
function SongProxy() { var songws = new SongWS(); return { getSong: function(songInput) { //cache miss -> add to cache if (!songcache[songInput]) songcache[songInput] = songws.getSong(songInput); return songcache[songInput]; }, getCount: function() { ...
[ "updateSong(){\n return new Promise( (resolve, reject) => {\n this.player.getCurrentRemoteMeta( ({result}) => {\n if( result){\n this._cache = result;\n this._cache.cover = this.player.address + \":\"+ this.player.port + result.artwork_url;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
eslint nounusedvars:0 Callback that will be invoked when owner game is freeze.
freeze() {}
[ "function freeze() {\n var startPosition = locate();\n teleport(startPosition[0], startPosition[1], startPosition[2]);\n Memory.writeFloat(Vector3, 0);\n Memory.writeFloat(ptr(Vector3).add(4), 0);\n Memory.writeFloat(ptr(Vector3).add(8), 0);\n setVelocity(Player.objectInMemory, Vector3);\n}", "f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RECREAT THE MAP CLONES
function recreateMapClones() { jQuery('#mapgyver_holder').removeClass("mapisready"); var mhod = jQuery('#mapgyver_holder .originalmap .originalmap-inner'); mhod.find('.gmnoprint, .gmnoscreen, .gmn, .gm-style, .gm-style-mtc').each(function() { TweenLite.set(jQuery(this),{transformPerspective:7000,rotationY:0...
[ "function createMapClones() {\n \t var clonemapfirst = setInterval(function() {\n\t\t\t\t\tif (jQuery('#mapgyver_holder').hasClass(\"mapisready\")) {\n\t\t\t\t\t\tsetTimeout(function() {\n\t\t\t\t\t\t\trecreateMapClones();\n\t\t\t\t\t\t\tfoldMapHandler();\n\t\t\t\t\t\t},300)\n\t\t\t\t\t\tclearInterval(clonema...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::LookoutMetrics::AnomalyDetector.MetricSet` resource
function cfnAnomalyDetectorMetricSetPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnAnomalyDetector_MetricSetPropertyValidator(properties).assertSuccess(); return { DimensionList: cdk.listMapper(cdk.stringToCloudFormation)(properties.dime...
[ "function CfnAnomalyDetector_MetricSetPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an objec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
append array with length 12
function appendArr(num, arr){ n = arr.length if(n<12){ arr.push(num) } else{ var i = childIsEmpty(arr, -1) if(i === -1){ for(var j = 0;j < 12;j++){ arr[j] = arr[j + 1] } arr[n - 1] = num } else arr[i] = num } }
[ "function array6x6() {\n let m = Array.from({length: 6}, e => Array(6).fill({key:true}));\n // let m = Array.from({length: 6}, e => Array(6).fill(0)); \n return m \n }", "function createArray(len, value) {\n let tmpArray = [];\n for (let i = 0; i < len; i++) {\n tmpArray[i] = value;\n }\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the code outputs of the selected cells.
function clearOutputs(notebook) { if (!notebook.model || !notebook.activeCell) { return; } const state = Private.getState(notebook); each(notebook.model.cells, (cell, index) => { const child = notebook.widgets[index]; if (notebook.isSelectedOrActive(ch...
[ "function clearSelectedStates() {\n _scope.ugCustomSelect.selectedCells = [];\n }", "function clearAllSelection(){\n ds.clearSelection();\n arrDisp.length=0;\n updateSelDisplay();\n updateCurrSelection('','','startIndex',0);\n updateCurrSelection('','','endIndex',0);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure `multer` options for file upload
configureFileUpload(destination) { // Upload files to `dist/.sandbox` by default destination = destination !== null && destination !== void 0 ? destination : path_1.default.join(__dirname, '../.sandbox'); this.bind(keys_1.STORAGE_DIRECTORY).to(destination); const multerOptions = { ...
[ "get ACCEPT_UPLOAD_FILETYPES () { return OVERRIDE_OR_DEFAULT('ACCEPT_UPLOAD_FILETYPES', acceptFiletypes) }", "function createMultipartUpload (req, res, next) {\n // @ts-ignore The `companion` property is added by middleware before reaching here.\n const client = req.companion.s3Client\n const key = conf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop the dice rolling
endRoll() { die.stopRolling(); showGameplayButtons(); }
[ "function stopSession(){\n\t$(\"#roll-area\").off('click', '.columnWrapper input', function(e){\n\t\t//Stop from adding rolls\n\t});\n\t//clearInterval(clockIntVal);\n\tclearInterval(intVal);\n}", "function closeRoll() {\n let countSelected = 0\n\t\tfor(let i = 0 ; i < Object.keys(diceDef).length; i++) {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function below evaluates the ID of the beardGrowthCard clicked in order to determine the numberOfDrops of beard oil used. Then this function updates the text of the h1 element and includes the appropriate numberOfDrops of oil.
function stepTwo(){ var clickedBeardGrowthCard = stepOneCardId; switch(clickedBeardGrowthCard){ case "one": numberOfDrops = "<span class=\"heading__top--highlight\">3-4</span>" break; case "two": numberOfDrops = "<span class=\"heading__top--highlight\">4-6</span>" break; case "th...
[ "function nutritionFacts(id){\n\n\tvar button = document.getElementById(id);\n\tvar itemId = \"item\"+id.slice(3);\n\tvar product = document.getElementById(itemId);\n\n\tif (button.style.background == \"white\"){\n\t\tbutton.style.background = \"#91CB3E\";\n\t\tbutton.innerHTML = prods.find(obj => {return obj.name ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Injects the given bits into the given buffer at the given index. Any bits in the value beyond the length to set are ignored.
function inject(buffer, bitIndex, bitLength, value) { if (bitLength < 0 || bitLength > 32) { throw new Error("Bad value for bitLength."); } var lastByte = Math.floor((bitIndex + bitLength - 1) / 8); if (bitIndex < 0 || lastByte >= buffer.length) { throw new Error("Index out of range."); } // Just ke...
[ "function setBit(number,i) {\n\treturn number | (1 << i);\n}", "function random_with_replacement(bitLength) {\n if (bitLength == null) {\n bitLength = bytes * 8;\n }\n\n var r = random_bit();\n for (var i = 1; i < bitLength; i++) {\n r *= 2;\n r += random_bit();\n }\n return r;\n}", "function Bit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
onclick function for the favorites button that gets added to the top shows favorites section and hides results section
function goToFavoritesClick() { $('.favorites').show(); $('.results').hide(); }
[ "function putFavoritesListOnPage() {\n console.debug(\"putFavoritesListOnPage\");\n\n //hides everything on the page\n hidePageComponents();\n\n // clear favorite list\n $favoriteStoriesList.empty();\n\n // loop through updated favorites list and generate HTML for all favorites\n // append them to DOM\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method to change wingspan
handleWingspanChange(wingspan) { this.setState({wingspan}); }
[ "function inlineTablePstyleSpanChange(inlineTableXpath){\r\n var myDoc = app.activeDocument;\r\n var xmlElements = myDoc.xmlElements[0].evaluateXPathExpression(inlineTableXpath);\r\n var xmlElementsLen = xmlElements.length; //Attributes total count\r\n for(var i=0; i<xm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Value Ref for binned fields
function bin(fieldDef, scaleName, side, offset) { var binSuffix = side === 'start' ? undefined : 'end'; return fieldRef(fieldDef, scaleName, { binSuffix: binSuffix }, offset ? { offset: offset } : {}); }
[ "function binb(x, len) {\n var j, i, l,\n W = new Array(80),\n hash = new Array(16),\n //Initial hash values\n H = [\n new int64(0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Near phase calculation, get the contact point, normal, etc.
function nearPhase(result,si,sj,xi,xj,qi,qj){ var swapped = false; if(si.type>sj.type){ var temp; temp=sj; sj=si; si=temp; temp=xj; xj=xi; xi=temp; temp=qj; qj=qi; qi=temp; swapped = true; } /** * Make a contact object. * @return object * @todo P...
[ "get normal() {\n\n // Check if the face is bound to a mesh and if not throw an error\n if (!this.mesh) throw new Error(`Cannot compute the normal of the face - the face is not bound to a Mesh`);\n\n // Return the normal for the face\n return this.plane.normal;\n }", "function calc_PlaneNormal(p1, p2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is like the search function, however it uses HTML 5 Geolocation to search for tweets in the user's area.
function get_tweets_in_current_area() { foundTweetCount = 0; $("#loading_button").css("display", "inline-block"); // Check if the browser supports HTML 5 Geolocation. if(navigator.geolocation) { // If it does, get the user's current geolocation, and search for tweets in that area. navigator.geolocation.getCurr...
[ "function searchTweets(query){\r\n search(query)\r\n\r\n\r\n function sentimentCheck(msg) {\r\n // dc73ee1d83164ed7a93db8d5afbdb358\r\n // 864addb2a8114d6eb9acd30ff898be52\r\n return new Promise((resolve) => {\r\n\r\n })\r\n }\r\n\r\n function search(){\r\n $.ajax({\r\n u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========================== Toplevel functions ========================== =================== views.delimiters ===================
function $viewsDelimiters(openChars, closeChars, link) { // Set the tag opening and closing delimiters and 'link' character. Default is "{{", "}}" and "^" // openChars, closeChars: opening and closing strings, each with two characters if (!openChars) { return $subSettings.delimiters; } if ($isArray(openChars)) {...
[ "function Separator() { bind.Separator(); }", "get seperator() { return this._seperator }", "function getDelimiter(theForm){\n var retVal;\n var selInd = theForm.Delimiter.selectedIndex;\n\n switch (selInd){\n case 0:\n\t retVal = \"\\t\";\n\t\t break;\n\t case 1:\n\t retVal = \" \";\n\t\t ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the corral canvas.
function setupCorralCanvas() { // Set up the canvas. corralWidth = $("#corral-canvas-wrapper").width(); corralHeight = $("#corral-canvas-wrapper").height(); corralCanvas = document.getElementById("corral-canvas"); corralCanvas.width = corralWidth; corralCanvas.height = corralHeight; // Set up the canvas ...
[ "function setup() {\n createCanvas(windowWidth + canvasEdge, windowHeight + canvasEdge, WEBGL);\n smooth();\n\n initializeStates();\n initializePlanets();\n initializeStars();\n initializeUI();\n initializeSound();\n\n}", "setupCanvas(width, height, rectMargin, rulerSize) {\n\t\tthis.canvas.width = width\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save to tree selectedNode
onNodeSave(){ const treeList = deepcopy(this.props.value.treeList); const {selectedNode} = this.props.value; this.findNode(treeList, selectedNode.id, node => { node.iconUrl = selectedNode.iconUrl; node.priority = selectedNode.priority; node.module = selected...
[ "function setSelectedNode(node) {\n selected_node = node;\n var selectedNodeLabel = d3.select('#edit-pane');\n // update selected node label\n selectedNodeLabel.html(selected_node ? '<strong>' + selected_node.lbl + ': ' + selected_node.wid + '</strong>' : 'No state selected');\n\n }",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The aim of this Kata is to write a function which will reverse the case of all consecutive duplicate letters in a string. That is, any letters that occur one after the other and are identical. If the duplicate letters are lowercase then they must be set to uppercase, and if they are uppercase then they need to be chang...
function reverseCase(string) { var removeDups = /([a-zA-Z])\1+/g; return string.replace(removeDups, convertCase); }
[ "function alternatingCaps(s) {\n\treturn s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]());\n}", "flip(input){\n // Set a temp string\n let output = \"\";\n // Look at each character in the string\n for(let i = 0; i < input.length; i++) {\n // If character is a \"A\", change it to a ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define a key return function that makes sre nodes are matched up using their ID values. Otherwise D3 might color the wrong nodes if the access order changes
function nodeKeyFunction(d) { return d.id }
[ "function highlightNode(d) {\n d3.select(\"#node_\" + d.idx)\n .transition().duration(100)\n .attr(\"r\",sizes[d.idx]*r*1.3)\n .style(\"stroke\",d3.rgb(0,0,0));\n}", "function setColors(n, c) {\n if (n.strokeWidth == '1') {\n if (c == gr1Color){\n var tempindex = zparams.zgroup1.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install global promise rejection handler.
function attachPromiseRejectionHandler() { detachPromiseRejectionFunction = Raygun.Utilities.addEventHandler( window, 'unhandledrejection', promiseRejectionHandler ); }
[ "function promiseRejectionHandler(event) {\n var error = event.reason;\n if (!error && event.detail && event.detail.reason) {\n error = event.detail.reason;\n }\n if (!(error instanceof Error) && event.reason && event.reason.error) {\n error = event.reason.error;\n }\n if (!error) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the line bonus image and a modifiable field for bonus
function getLineBonus(lineNumber, bonusNumber) { var iconPath = ''; switch(window.className) { case 'WARRIOR': switch(lineNumber) { case 0: if(bonusNumber===1) return "Power"; return "Condition Duration"; case 1: if(bonusNumber===1) return "Precision"; return "Condition Damage"; c...
[ "function extraLineFields(options={}) {\n\n var fields = {\n order: {\n hidden: true,\n },\n quantity: {},\n reference: {},\n description: {},\n price: {\n icon: 'fa-dollar-sign',\n },\n price_currency: {\n icon: 'fa-coins',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates all instances of a Card's memo on the page given a card ID and what the memo has been updated to be
updateMemos(id, memoText){ let memos = $(`span[id=memo-${id}]`); for(const memo of memos){ if(memoText!=false){ $(memo).text(`"${memoText}"`); }else{ $(memo).text(""); } } }
[ "getMemo(cardId) {\n if(this.user==false)return false;\n for(const card of this.user.savedCards){\n //console.log(card.cardID+\" vs \"+cardId);\n if(card.cardID == cardId)return card.memo;\n\n }\n return false;\n }", "function editCard(card_id) {\n // conso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When converting XML to JSON, we are not able to infer if something was meant to be a single object or an array (since we don't refer to the schema at that time). This method is invoked to enforce an array structure around a single element. That can make subsequent processing simpler and consistent.
function enforceArray(jsonObj, key) { var elem = jsonObj[key]; if(elem == null) return []; // Is this an array of a single instance? if (elem instanceof Array) { return jsonObj[key];; } else { jsonObj[key] = [jsonObj[key]]; return jsonObj[ke...
[ "getArrayFromPassedElem(elem) {\n // If it's already an array, simply return it.\n if (Array.isArray(elem)) {\n return elem;\n }\n\n // If it is an individual (and valid) value, return that as an array\n if (elem != null && elem !== undefined) {\n return [elem];\n }\n\n // Else, retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Affiche le mot complet
afficherMotComplet() { var mot = this.mot.toString(true).split(''); window.conteneurMot.innerHTML = "Mot : " + mot.join(' '); }
[ "afficherMotIncomplet() {\n var mot = this.mot.toString(false).split('');\n window.conteneurMot.innerHTML = \"Mot : \" + mot.join(' ');\n }", "function renderPorSucursal(){\r\nlet porSucursal=0\r\n for (let i = 0; i < local.sucursal.length; i++) {\r\n let porSucursal= console.log('Total ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a random integer between 0 and the specified exclusive maximum.
function randomInt(exclusiveMax) { return Math.floor(Math.random() * Math.floor(exclusiveMax)) }
[ "function randomValueFromZeroToMax(max) {\n return Math.floor(Math.random() * max);\n}", "function randomInteger(limit){\n\treturn Math.floor(Math.random() * limit);\n}", "function uniformInt(min, max) {\n return min + Math.floor(Math.random() * (max - min + 1));\n }", "function randomInteger(iMin,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is called after DOM objects representing the list of courses are updated.
function updateCourses() { element.find('.courses > .course').each(function (index) { var course = scope.courses[index]; var courseElem = angular.element(this); courseElem.data('id', course.id); courseElem.find('.actions').attr('aria-label', COURSE_ACTIONS_ARIA_...
[ "function fetchAllCoursesAndStoreInDataBase() {\n fetch(\"http://courses.rice.edu/admweb/!SWKSECX.main?term=202020\")\n .then(handleErrors)\n .then((resp) => resp.text()) // Transform the data into text\n .then(xmlString => $.parseXML(xmlString))\n .then(function(data) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove this Model instance's data from the database
async remove() { // TODO: Should delete class itself too? // Ensure model is registered before removing model data assert.instanceOf(this.constructor.__db, DbApi, 'Model must be registered.'); // Ensure this Model instance is stored in database assert.isNotNull(this.__id, 'Model must be stored in ...
[ "async delete() {\n await this.pouchdb.destroy();\n await this.database.removeCollectionDoc(this.dataMigrator.name, this.schema);\n }", "async discard() {\n const tx = this.database.transaction(\n ['states', 'changes', 'contents'], 'readwrite')\n const states = tx.objectS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function append css shims to the head of the page which are needed for old IE versions
function appendLegacyCss(){ $("head").append("<!--[if lte IE 7]><link href='"+host_url+"ie7.css' rel='stylesheet' /><![endif]-->" +"<!--[if lt IE 9]><link href='"+host_url+"ie8.css' rel='stylesheet' /><![endif]-->"); }
[ "function injectHead() {\n if (styles.length > 0 || headScripts.length > 0) {\n console.debug('injecting CSS...');\n var heads = document.getElementsByTagName('head');\n if (heads.length > 0) {\n if (styles.length > 0) {\n var styleBlock = document.createElement('st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a plnkr file for each samples
function createPlnkrFile(plnkrPath) { var files = glob.sync(plnkrPath + '/**', { silent: true }); var plnkr = {}; for (var i = 0; i < files.length; i++) { var fileName = getFileName(files[i]); if (fileName != '') { plnkr[fileName] = fs.readFileSync(files[i], 'utf8'); } ...
[ "function createSample(block) {\n var template = block.kwargs.template;\n var currentTemplate = './templates/' + template;\n var samplePath = './samples/' + template + getSampleId(template);\n // update or create folder for current sample\n if (fs.existsSync(samplePath)) {\n shelljs.rm('-rf', ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert a number to a fraction only if it can be expressed exactly
function _exactFraction(n) { if (isFinite(n)) { var f = math.fraction(n); if (f.valueOf() === n) { return f; } } return n; }
[ "function deciToFraction(n) {\n\n}", "function mixedFraction(s){\n //Split into array of two numbers\n var numbers = s.split('/');\n \n //If denominator of fraction is zero, throw error\n if (numbers[1] === '0') {\n throw \"zero division error\";\n //If numerator of fraction is zero, return 0\n } else i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get number of current active connections
get connectionCount () { return this.connections.size }
[ "function getCurrentVisitorCount () {\n console.log(\"current visitor count requested\", connectionCount)\n return connectionCount;\n }", "function increaseConnectionCount() {\n\t\tconnectionCount++;\n\t\tlogger.info(\"I have %d connections\", connectionCount);\n\t}", "numOfUsers() {\n return Obj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implementation of fetch call with a paramterized input based on adventure ID
async function fetchAdventureDetails(adventureId) { // TODO: MODULE_ADVENTURE_DETAILS // 1. Fetch the details of the adventure by making an API call let url = config.backendEndpoint + `/adventures/detail?adventure=${adventureId}`; try { let res = await fetch(url); let data = await res.json(); return...
[ "function get_details(id){\n console.log(\"You clicked Game ID: \" + id);\n fetch_by_id(id);\n}", "function varifyId(idToVarify) {\n var findId =\n \"https://api.themoviedb.org/3/find/\" +\n idToVarify +\n \"?api_key=\" +\n movieDBApiKey +\n \"&&external_source=imdb_id\";\n fetch(findId)\n ....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
results[] course IDs they are trying to register too
function dbResults(completedCourses = [], registeringTo = []) { let counter = 0; const preReqNotCompleted = []; for (let i = 0; i < registeringTo.length; i += 1) { for (let j = 0; j < completedCourses.length; ) { if (registeringTo[i].dependencies.pre !== completedCourses[j]) { ...
[ "function getTakenCourses() {\n var courseNodes = document.getElementById(\"alreadyTaken\").children;\n var courses = new Array;\n for ( i = 0; i < courseNodes.length; i++) {\n //courses[courseNodes[i].id]=courseNodes[i].innerText;\n courses.push(courseNodes[i].id);\n }\n return courses...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a new decklist entry to the list of decks
function addDecklist() { let newList = qs("#list-wrap ul li:first-child").cloneNode(true); newList.querySelector(".list-title").value = ""; newList.querySelector(".list-link").value = ""; newList.querySelector(".has-primer").checked = false; newList.querySelector(".delete-list").addEventListener("click", dele...
[ "function addDeck({ signal }) {\n const newDeck = { name: formData.name, description: formData.description };\n createDeck(newDeck, signal).then(() => updateDecks(signal));\n }", "add(card) {\n this.cards.push(card);\n }", "function addCard(deck, card, position)\n{\n\t/*\n\t\tposition is an opt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show Add New Location Details Modal
function show_add_new_location_details (detail_type) { $("#modal_title_location_details").html("Add new " + detail_type); $("#location_detail_name_label").html( "Location " + detail_type + " name"); $("#location_detail_type").val(detail_type); $("#location_detail_id").val(""); $("#location_detail_name").val("...
[ "function show_add_new_location () {\n\t\t$(\"#modal_title_location\").html(\"Add New Location\");\n\t\t$(\"#location_id\").val(\"\");\n\t\t$(\"#location_name\").val(\"\");\n\t\t$(\"#location_place\").val(\"\");\n\t\t$(\"#location_building\").val(\"\");\n\t\t$(\"#location_floor\").val(\"\");\n\t\t$(\"#location_info...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate string for an opening xml tag tag: the name of the xml tag attr: hash of attribute namevalue pairs to include raw: additional raw string to include in tag markup
function openTag(tag, attr, raw) { var s = '<' + tag, key, val; if (attr) { for (key in attr) { val = attr[key]; if (val != null) { s += ' ' + key + '="' + val + '"'; } } } if (raw) s += ' ' + raw; return s + '>'; }
[ "function xmlStringFromDocDom(oDocDom, encodeSingleSpaceTextNodes) {\n\tvar xmlString = new String();\n\n\t// if the node is an element node\n\tif (oDocDom.nodeType == 1 && oDocDom.nodeName.slice(0,1) != \"/\") {\n\t\t// define the beginning of the root element and that element's name\n\t\txmlString = \"<\" + oDocD...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method called whenever an <ar tag is found The responses for this type of message will be buttons This method parses out the time delays, message text and button responses Then creates a new message with the time delay and creates buttons for the responses
function buttonResponse(message) { // Stores the matches in the message, which match the regex var matches; // Used to store the new HTML div which will be the button var $input; // send the message to the multi message method to split it up, message will be sent here multiMessage(message); // Regex used t...
[ "function newRecievedMessage(messageText) {\n\n\t// Variable storing the message with the \"\" removed\n\tvar removedQuotes = messageText.replace(/[\"\"]/g,\"\");\n\n\t// update the last message recieved variable for storage in the database\n\tlastRecievedMessage = removedQuotes;\n\n\t// If the message contains a <...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if vector is near a coordinate within a radius.
isNear(pos, rad) { return Math.abs(this.x - pos.x) < rad && Math.abs(this.y - pos.y) < rad; }
[ "function isWithinRadius(centerLat, centerLon, radius, lat, lon) {\n\tlet dist = distance(centerLat, centerLon, lat, lon);\n\treturn (dist <= radius);\n}", "isCircleTooClose(x1,y1,x2,y2){\n // if(Math.abs(x1-x2)<50 && Math.abs(y1-y2)<50)\n // return true;\n // return false; \n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an appropriately IDd table cell for a card/player.
function createPlayerCardCountCell(player, card) { var id = cardId(player.id, card); var count = player.card_counts[card]; if (count == undefined) count = '-'; var cell = $('<td id="' + id + '">' + count + '</td>'); cell.addClass("playerCardCountCol").addClass(player.id); return cell; }
[ "function createTable() {\n var newHtml = '';\n newHtml = newHtml + '<table id=\"chess_board\" style=\"display: none;\">';\n newHtml = newHtml + '<tr>';\n newHtml = newHtml + '<td id=\"0\"><span data-color=\"black\" data-piece=\"tower\" class=\"unmoved black glyphicon glyphicon-tower\"><...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call remote webscript to get login user's cm:person nodeRef and compose URL to the edit page. The URL is relative to "
function getTargetUrl() { var connector = remote.connect("alfresco"); var response = connector.call("/person-node/" + user.id); if (response.status == 200) { var json = JSON.parse(response); return "edit-metadata?nodeRef=workspace://SpacesStore/" + json.nodeId; } return null; }
[ "function goToeditEventPage(owner,docId){\n window.location.href = \"/edit-event1.html?owner=\" + owner + '&docId=' + docId;\n}", "function editProfile() {\n var pageMeta;\n var accountPersonalDataAsset;\n var Content = app.getModel('Content');\n\n if (!request.httpParameterMap.invalid.submitted) {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a car object to the cars array
function addCar(year, make, model, trim, nickname, milage, estMilage, oilWeight, oilType, lastOilChange) { var temp = new carModule("car" + carIter) temp.carYear = year; temp.carMake = capitalizeFirstLetter(make); temp.carModel = model; temp.carTrim = trim; if (!isNaN(nickname)) { temp.title = nickname...
[ "function carPassing(cars, speed){\n let newCar = {\n time: Date.now(),\n speed: speed\n };\n cars.push(newCar);\n return cars;\n}", "function carPassing(cars, speed) {\n cars.push({ time: Date.now(), speed: speed });\n return cars;\n}", "add(card) {\n this.cards.push(card);\n }", "addDr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function flattenFiles (obj, filename, memo) Flattens an object which only has Array keys and is assumed to be a set of AST files.
function flattenFiles(obj, filename, memo) { filename = filename || ''; memo = memo || []; if (Array.isArray(obj)) { if (obj.length) { memo.push.apply(memo, obj.map(function (o) { o.filename = filename; return o; })); } return memo; } return Object.keys(obj) ...
[ "function flatten(file: File, seed = []): File[] {\n\treturn [file, ...values(file.dependencies)\n\t\t.reduce((pool, dependency) => [\n\t\t\t...pool,\n\t\t\t...flatten(dependency, pool)\n\t\t], seed)];\n}", "function normalizeFiles(files) {\n let filez = {};\n for (let file of files) {\n if (typeof f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new `HttpHeaderResponse` with the given parameters.
function HttpHeaderResponse(init) { if (init === void 0) { init = {}; } var _this = _super.call(this, init) || this; _this.type = HttpEventType.ResponseHeader; return _this; }
[ "function constructResponseHeaders(request, response) {\n\n //header array we'll eventually print, plus our own\n let finalHeaders = response.getHeaders();\n\n if (!finalHeaders) {\n finalHeaders = {}\n }\n\n finalHeaders = getSafeResponseHeaders(finalHeaders);\n \n //We look at all the request headers, a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Selects a row. Adds the row to the _bocList_selectedRows array and increments _bocList_selectedRowsLength. bocList: The BocList to which the row belongs. rowBlock: The row to be selected.
function BocList_SelectRow (bocList, rowBlock) { // Add currentRow to list var selectedRows = _bocList_selectedRows[bocList.id]; selectedRows.Rows[rowBlock.SelectorControl.id] = rowBlock; selectedRows.Length++; // Select currentRow rowBlock.Row.className = _bocList_TrClassNameSelected; rowBlock.Se...
[ "function BocList_OnRowClick(bocList, currentRow, selectorControl)\n{\n if (_bocList_isCommandClick)\n {\n _bocList_isCommandClick = false;\n return;\n } \n \n if (_bocList_isSelectorControlLabelClick)\n {\n _bocList_isSelectorControlLabelClick = false;\n return;\n } \n\n var currentRowBlock =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up context/binding listeners and refresh index for bindings by tag
setupTagIndexForBindings() { this.bindingEventListener = ({ binding, operation }) => { if (operation === 'tag') { this.updateTagIndexForBinding(binding); } }; this.tagIndexListener = event => { const { binding, type } = event; if (e...
[ "updateTagIndexForBinding(binding) {\n this.removeTagIndexForBinding(binding);\n for (const tag of binding.tagNames) {\n let bindings = this.bindingsIndexedByTag.get(tag);\n if (bindings == null) {\n bindings = new Set();\n this.bindingsIndexedByTag....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize a BudgetCond into buffer to transport on the network.
function serializeCond(condition: BudgetCond) { switch (condition.type) { case 'timestamp': { const date = serializeTime(condition.when); const from = condition.from.converseToBuffer(); const data = Buffer.alloc(4 + date.length + from.length); data.writeUInt32LE(0, 0); // Condition enum =...
[ "function toByteArray(termObj) {\n // note: if we forget new here, we get:\n // TypeError: this.$set is not a function\n const term = new proto.Par(termObj);\n\n const buf = term.toBuffer();\n return buf;\n }", "function serialize(robot_command) {\n var num_packet = 10;\n var buffer = new ArrayB...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if current content item collides given content item
function checkCollision(contentItem) { var position = Canvas.Mousepointer.position; if (contentItem.collides(position.x, position.y)) { var children = contentItem.getChildren(); var length = children.length; for (var i = 0; i < length; i++) { ...
[ "function getContentItemOnMousePosition() {\r\n // Search through all content items\r\n var length = _contentItems.length;\r\n for (var i = 0; i < length; i++) {\r\n // Check if content item collides\r\n _collidedContentItem = checkCollision(_contentIte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a global example. This example added here will not be used by subcommands.
example(example) { this.globalCommand.example(example); return this; }
[ "async function example(interaction) {\n return interaction.reply({ content: \"this is an exmaple command\" })\n}", "function getHeroExample() {\n const EXAMPLES = getReactComponent('EXAMPLES');\n const exampleNames = Object.keys(EXAMPLES);\n let DefaultHeroExample = exampleNames.length && EXAMPLES[0];\n // ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Multipy an Color4 value by another and return a new Color4 object
multiply(color) { return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a); }
[ "multiplyToRef(color, result) {\n result.r = this.r * color.r;\n result.g = this.g * color.g;\n result.b = this.b * color.b;\n result.a = this.a * color.a;\n return result;\n }", "clone() {\n return new Color4(this.r, this.g, this.b, this.a);\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the premium covers to $scope.extra object
function setPremiumCoverModelValues(data){ if(data.PassengerCoverOpted){ $scope.PremiumCovers.PassengerCoverOpted = true; if(data.PassengerCoverAmount==100000) { $scope.extra.passenger = -50; }else{ ...
[ "function getAdditionalCoverPremium(coverCode, premium) {\n\t\t\t\t\t\tvar coverPremium = RatingConstants.RATE_NA;\n\t\t\t\t\t\tvar coverDetails = isCoverSelected(coverCode);\n\t\t\t\t\t\tif (angular.isDefined(coverDetails)) {\n\t\t\t\t\t\t\tvar coverPremiumDetail = getCoverPremiumDetails(\n\t\t\t\t\t\t\t\t\tcoverC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The directive that defines how the current spot should be displayed
function currentSpotDirective() { return { restrict: 'E', templateUrl: '/app/main/currentSpotTemplate.html', controller: CurrentSpotController, }; }
[ "function currentSpotMarkerDirective(currentSpot) {\n return {\n restrict: 'A',\n link: function (scope, element, attrs) {\n var title = attrs[\"activeTitle\"];\n var menuId = attrs[\"activeMenu\"];\n currentSpot.setCurrentSpot(title, menuId)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Put notes in remote text file
function putNotes(notes) { var request = $http({ method: "PUT", dataType: "text", url: cfg.server_url + cfg.notes_url, data: notes, headers: { "Content-Type": "application/json" } }); request.success(function...
[ "async saveNotesToFile() {\n return await fs.writeFile(\n path.join(__dirname, \"../db/db.json\"),\n JSON.stringify(this.notes)\n );\n }", "function noteWriter(notes) {\n fs.writeFile(\n path.join(__dirname, \"/db/db.json\"),\n JSON.stringify(notes),\n (err) => (err ? console.er...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========================== Functions ========================== /Function retrieves json object from the players currently live streaming and displays on playerList.
function getStreamList(streamPlayerList) { $(".streams").remove(); $(".streamlist").append('<img id="loadingGIF" src="loading.gif" >'); for (var i = 0; i < streamPlayerList.length; i++) { $.getJSON("https://api.twitch.tv/kraken/streams/" + streamPlayerList[i] + "/?callback=?", functi...
[ "broadcastPlayerList() {\n var response = [];\n // prepare the data\n this._players.forEach(p => {\n response.push(p.getPublicInfo());\n });\n // Send to all users\n this.emitToRoom(\"player-list\", response);\n }", "function fillPlayerHeaders() {\n // Ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }