query stringlengths 9 34k | document stringlengths 8 5.39M | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Locked up cash amount (withdrawal request) | function LockWithdrawAmount(token, ca_id, base_amount, bit_amount, id_card, name, us_account_id, suc_func, error_func) {
let api_url = 'us_withdraw_quest.php',
post_data = {
'token': token,
'ca_id': ca_id,
'base_amount': base_amount,
'bit_amount': bit_amount,
... | [
"function withdraw (account, amount) {\n account.balance -= amount;\n}",
"loadAtmCash(amount) {\n if (this.auth()) {\n if (this.currentUser.type === \"admin\") {\n this.cash += amount;\n console.log('ATM account credited to' + amount);\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTIONS BELOW //// / Move Item change location of item with parentId and slotId | function moveItem(tmpList, body) {
item.resetOutput();
let output = item.getOutput();
// -> Move item to diffrent place - counts with equiping filling magazine etc
//cartriges handler start
if (body.to.container === 'cartridges') {
let tmp_counter = 0;
for (let item_ammo in tmpList.d... | [
"move (itemId, folderId, portalOpts) {\n const args = this.addOptions({ itemId, folderId }, portalOpts);\n\n return moveItem(args)\n .catch(handleError);\n }",
"moveItem(fromStack, toStack, thisMoveCounter){\n toStack.add_item(fromStack.top_item())\n fromStack.remove_item()\n $(toStack.id).prep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
putting values into fav table from local storage, on opening web application | function fillFavTable () {
//debugger;
$("#favTableBody").empty();
if (typeof(Storage) !== "undefined") {
for (i = 0; i < localStorage.length; i++) {
var obj = JSON.parse (localStorage.getItem(localStorage.key(i)));
var changeStr = obj... | [
"function createFavTable() {\n var favoriteDiv = document.getElementById('favorites');\n /* Remove old table before new table */\n var favTableOld = document.getElementById('fav_table');\n if (favTableOld !== null) {\n favoriteDiv.removeChild(favTableOld);\n }\n if (localStorage.length >= 1) {\n /*Rem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
==================================================================================================== ==================================================================================================== Large image popup box title filler. (Modal product title filler.) Applied page [/contents/productpage.php] Written by ... | function modalTitleFiller(){
var productname = $('.product-name>h2').text();
$('#myModalLabel').text(productname);
} | [
"function htmlPopup(){\r\n var p01 = $('<div id=\"popup-image\"><div class=\"table\"><div class=\"table-cell\"><div id=\"inner-popup\"><a id=\"close-poup\" href=\"#\"><i class=\"fa fa-times\"></i></a><img id=\"img-popup\" src=\"\" /></div></div></div></div>');\r\n $(p01).appendTo('#wrapper').hide().fa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function gets you a 'unique' string in the form of the number of milliseconds since 1970 January 1st. It can be appended to a URL which will then always be unique to the webserver/caching mechanism. This pretty stupid trick has to be performed in order to prevent IE from never actually carrying out AJAX calls more... | function uniqueString() {
return "&sUnique=" + new Date().getTime();
} | [
"function generate_unique_number(){\n var current_date = (new Date()).valueOf().toString();\n var random = Math.random().toString();\n return generate_hash(current_date + random);\n}",
"function url_force_reload(url) { \n var date_now = new Date();\n return url + '?v=' + date_now.getTime(); \n}",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The following method expands or collapses the specified section of the application. If the value of 'action' is 'show', then it is expanded. Otherwise, its state is toggled. | function showHideSection ( section_id, action )
{
// If we are forcing or toggling the section to expanded then execute the necessary steps.
// The triangle marker corresponding to the section has the same name but prefixed with
// 'm'.
if ( ! visible[section_id] || (action && action == 'show') )
{
... | [
"function showHideHelp ( section_id, action )\n {\n\t// If the help text is visible and we're either hiding or toggling, then do so.\n\t\n\tif ( visible['help_' + section_id] && ( action == undefined || action == \"hide\" ) )\n\t{\n\t setElementSrc('q' + section_id, \"/JavaScripts/img/hidden_help.png\");\n\t ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function generates a form containing a row of images (each 25x25), which when deselected are emptyImage, and selected are fullImage. Under each image is an entry of optionNames, and the first defaultValue of them are selected. When a user makes a selection (some number of the images), the number of images the user... | function moonStars(ratingname, defaultValue, emptyImage, fullImage,Image_size, optionNames,course_id)
{
//Generate the actual form of images
document.write("<form name=\""+ratingname+course_id+"form\" class=\"Rating_item\" >");
for(count=1; count< optionNames.length+1; count=count+1)
{
document.write("<input ... | [
"function getImage(){\n\tvar radioButtons = document.getElementsByName(\"meme-select\");\n\tfor(var i = 0; i < radioButtons.length; i++){\n\t\tif(radioButtons[i].checked){\n\t\t\tdocument.getElementById(\"image\").src = radioButtons[i].value;\n\t\t}\n\t}\n}",
"function recommendations() {\r\n\tdisplayResult(\"gen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
now create some sample people | function createSamplePersons() {
var personsDS = Entity.Stores.get(DemoApp.Person);
var p1 = DemoApp.Person.create({
id:123,
firstName:"Aaron",
lastName:"Bourne",
DOB:new Date()
});
personsDS.add(p1);
var serialized = p1.serialize();
personsDS.add(DemoApp.Person.c... | [
"async generateSampleUsers() {\n // Create an arbitrary number of user details and add them to an array\n for (let newUsersNumber = 0; newUsersNumber < this.totalNumberOfUsers; newUsersNumber++) {\n this.allUsers.push(\n {\n username: faker.name.firstName(),\n company: fake... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name of tool to use to terminate the chain. | finishToolName() {
return "Final Answer";
} | [
"toolFor(toolName) {\n for (let tool of Array.from(this.tools)) {\n if (tool.toolName === toolName) { return tool; }\n }\n return alert(`Tool ${toolName} not found`);\n }",
"exitDelegationSpecifier(ctx) {\n\t}",
"function getActiveTool() {\n\t\t\treturn getToolByName($toolbox.find('.active').data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
finds the courses of the given student. | findStudentCourses(courseArray){
let studentCourseList = [];
for(let courseName of courseArray){
studentCourseList.push(this.courses.get(courseName));
}
return studentCourseList;
} | [
"getCourseIDs(studentID) {\n const courseInstanceDocs = CourseInstances.find({ studentID }).fetch();\n const courseIDs = courseInstanceDocs.map((doc) => doc.courseID);\n return _.uniq(courseIDs);\n }",
"function listCourses() {\n gapi.client.classroom.courses.list({\n pageSize: 10\n }).then(functio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CODING CHALLENGE 832 Wild Roger is tasked with shooting down 6 bottles with 6 shots as fast as possible. Here are the different types of shots he could make: He could use one pistol to shoot a bottle with a "Bang!" in 0.5 seconds. Or he could use both pistols at once with a "BangBang!" to shoot two bottles in 0.5 secon... | function rogerShots(arr) {
return arr.filter(x => x === "BangBang!" || x === 'Bang!').map(x => x = 0.5).reduce((x, i) => x + i);
} | [
"function typeOfShoot(randomNumberBtw0And1 = Math.random()) {\n // On average their are 110 shoots per game\n // 20 are FT -> 20 / 110 = 18,18%\n // 30 are 3pts -> 30 / 110 = 27,27%\n // 60 are 2pts -> 60 / 110 = 54,54%\n //const probaFT = divide(20, 110);\n const proba3pts = divide(30, 110);\n const proba2p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Passes the current goal's id upwards to ProgressController to initiate marking the specific goal complete. Triggered on user selecting the 'Edit Goal' option from a goal's dropdown menu. | function markGoalComplete() {
props.markGoalComplete(props.goalId);
} | [
"function editGoal() {\n\t\tprops.editTask(props.goalId);\n\t}",
"function markGoalActive() {\n\t\tprops.markGoalActive(props.goalId);\n\t}",
"async function setNewGoal(userID, goalID) {\n // Error check\n let cleanUser = checkStr(userID);\n let cleanGoal = checkStr(goalID);\n let userObj, goalObj;\n try {... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
member function _jumpParticles() private creates a particle effect when the player jumps | _jumpParticles(){
var c = this.getCol();
for(var i = 10; i > 0; i -= 1){
var p = new particle(c.position.x + Math.random() * c.size.x, c.bottom());
p.setRandVel(Math.random() * 10, -Math.PI, 0);
p.vel = p.vel.minus(this.vel);
p.add();
}
} | [
"createPointerMoveEffect()\n {\n let effect = this.add.particles('glow').createEmitter({\n x: 400,\n y: 300,\n speed: { min: 0, max: 0 },\n angle: { min: 0, max: 180 },\n scale: { start: 1, end: 0, ease: 'Quart.easeOut' },\n alpha: { start:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates DMAC Mask field of Ethernet. | validateDmacMask() {
let regex = /^[a-fA-F0-9]{4}\.[a-fA-F0-9]{4}\.[a-fA-F0-9]{4}$/;
if (regex.test(this.state.dmacMask.replace(/^\s+|\s+$/g, ""))) {
let mask = this.state.dmacMask.toString().replace(/^\s+|\s+$/g, "");
let mask1 = mask.replace(/\./g, "");
let mask2 = mask1.replace(/^0+/, "");
... | [
"validateSmacMask() {\n let regex = /^[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}$/;\n if (regex.test(this.state.smacMask.replace(/^\\s+|\\s+$/g, \"\"))) {\n let mask = this.state.smacMask.toString().replace(/^\\s+|\\s+$/g, \"\");\n let mask1 = mask.replace(/\\./g, \"\");\n let mask2 = mas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete events before a given day(s) ago. | async deleteBefore(days) {
console.log(`== Try to delete data before ${days} day(s) ago ==`);
// Convert days into seconds.
const seconds = days * 24 * 60 * 60;
// Calculate the maximum timestamp (in seconds) that allows events to
// live.
const maxTimestamp = Date.now()... | [
"function deletePastVacationDays(){\n\tvar l = U.profiles.length;\n\t//console.log(\"We have \" + l + \" profiles to check.\");\n\tfor(i=0;i<l;i++){\n\t\t//Attend to vacationDays in each profile\n\t\tvar v = U.profiles[i].vacationDays.length;\n\t\t//console.log(\"====>The profile \" + U.profiles[i].profileName + \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clear dataresult attribute in displaybar | function clearResult() {
$(".display-bar").data("result", "");
} | [
"function clearDisplay(val){\n\t\tprimaryOutput.innerHTML = \"\";\t\n\t\tif (val === \"AC\") {\n\t\t\ttotal = 0;\n\t\t\tsecondaryOutput.innerHTML = \"\";\n\t\t\tsecondaryOutput.style.right = \"0px\";\n\t\t\tlastOperator.length = 0;\n\t\t}\n\t}",
"function clearCurrentAnalysisResults() {\n // clear the result ite... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the index of a uniform block | getUniformBlockIndex(blockName) {
return this.gl.getUniformBlockIndex(this.handle, blockName);
} | [
"function getIndex(vertex, uv) {\n const attributeIndex = floor(frame / 2);\n const vertexIndex = vertex;\n const frameIndex = frame % 2;\n const uvIndex = uv;\n return attributeIndex * FRAME_UV_ATTRIBUTE_SIZE_PER_FRAME + vertexIndex * FRAME_UVS_PER_ATTRIBUTE *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the ok button action | function setOkButtonAction(action) {
$okButton.unbind('click');
$okButton.click(action);
} | [
"okAction() {\n if (this.attrs.okAction) {\n get(this, 'okAction')();\n }\n this.send('closeDialog');\n }",
"function setOkButtonTitle(name) {\n\t\t$okButton.html(name);\n\t}",
"function doMsgBtnOK() {\n\tconsole.log(\"Something went very awry with the message box Okay button.\");\n}",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function adds a new diary entry to an old list of diary entries private function, access is possibe only from fileReader.js journalEntries is an array of old diary entries newEntry is a new diary entry entryDate is date returns an array of all the user diary entries, new diary entry is included | function makeDiaryItemList(journalEntries, newEntry, entryDate, subject) {
var d = new Date(); //current time
var entryId = d.getTime(); // current time in milliseconds
console.log(entryId);
var entryTexts = journalEntries;
var subject = subject;
var newEntryText = { "date": entryDate, "su... | [
"function journalEntry(entryDate, conceptLearned, journalText, mood) {\n const newEntry = {\n date: `${entryDate}`,\n concept: `${conceptLearned}`,\n entry: `${journalText}`,\n mood: `${mood}`,\n };\n return newEntry;\n}",
"function addEntry(events, didITurnIntoASquirrel){\n journal.push({\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove type bindings from this import, leaving the rest of the import intact. Return true if this import was ONLY types, and thus is eligible for removal. This will bail out of the replacement operation, so we can return early here. | removeTypeBindings() {
this.tokens.copyExpectedToken(_types.TokenType._import);
if (
this.tokens.matchesContextual(_keywords.ContextualKeyword._type) &&
!this.tokens.matchesAtIndex(this.tokens.currentIndex() + 1, [_types.TokenType.comma]) &&
!this.tokens.matchesContextualAtIndex(this.tokens.cu... | [
"removeImportAndDetectIfType() {\n this.tokens.removeInitialToken();\n if (\n this.tokens.matchesContextual(_keywords.ContextualKeyword._type) &&\n !this.tokens.matches1AtIndex(this.tokens.currentIndex() + 1, _types.TokenType.comma) &&\n !this.tokens.matchesContextualAtIndex(this.tokens.current... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns array of counts for each title at a given company | function getRoleCount(company) {
const data = { company_name: company };
fetch('/api/jobTitles', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((data) => {
return data.json();
})
.then((res) ... | [
"function domainCounts(counts) {\n let output = {}; //{ google.com: 900, com: 900}\n\n for (let i = 0; i < counts.length; i++) {\n let splitCounts = counts[i].split(','); // [ \"60\", \"mail.yahoo.com\"]\n let count = splitCounts[0];\n let host = splitCounts[1];\n\n if (output[host]) {\n output[h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inlined / shortened version of `kindOf` from | function miniKindOf(val) {
if (val === void 0) return 'undefined';
if (val === null) return 'null';
var type = typeof val;
switch (type) {
case 'boolean':
case 'string':
case 'number':
case 'symbol':
case 'function':
{
return type;
}
}
if (Array.isArray(val)) return... | [
"function isTextual(type, value) {\n return t.logicalExpression(\"||\", t.binaryExpression(\"===\", type, t.stringLiteral(\"number\")), t.logicalExpression(\"||\", t.binaryExpression(\"===\", type, t.stringLiteral(\"string\")), t.logicalExpression(\"&&\", t.binaryExpression(\"===\", type, t.stringLiteral(\"object\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the webGL context has returned an error | isErrorState() {
const gl = this.gl;
return gl === null || gl.getError() !== gl.NO_ERROR;
} | [
"get isError() {\n return (this.flags & 4) /* NodeFlag.Error */ > 0\n }",
"isErrored() {\n return !!this.keycatError;\n }",
"function glShaderCompileError(error) {\n addError(error);\n}",
"function validate(src, type) {\n // uniforms don't get validated by glsl\n if (type ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete Generic SAML Identity Provider | deleteIdentityprovidersGeneric() {
return this.apiClient.callApi(
'/api/v2/identityproviders/generic',
'DELETE',
{ },
{ },
{ },
{ },
null,
['PureCloud OAuth'],
['application/json'],
['application/json']
);
} | [
"deleteIdentityprovidersOkta() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/identityproviders/okta', \n\t\t\t'DELETE', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}",
"deleteIdentity... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
updateUIDisplay() Change the text in the password textarea to reflect the new parameters (called from updatePassRequirements()) | function updateUIDisplay(){
// The default password text is a message that describe the password constraints
// We have to store it as an array so that we can figure out which element is the
// penultimate one and then add the word "and" after it. Ugh.
var msg=["A password of length "+passLength];
i... | [
"function displayPassword(msg, okFn, textInputPassword, initCoords) {\n\t//removeEventListeners();\n\tmessageDiv.style.display = \"none\";\n\tvar pwdBtnOK = document.getElementById('pwdBtnOK');\n\tvar pwdBtnCancel = document.getElementById('pwdBtnCancel');\n\tvar pwdBtnSkip = document.getElementById('pwdBtnSkip');\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Meghan Cullen 04 September 2019 Uses p5's set of shape and colour functions to draw a head and body Wearing my favorite black sweater and crossing my eyes, a trait of Meghan that is familiar and unique setup() Draws a beautiful face on the canvas and puts hair and a sweater on it! | function setup() {
// Set up the canvas and makes the background into a green colour - Meghan's favorite color
createCanvas(500,500);
noStroke();
background(0,190,0);
fill(0,220,0);
rect(50,50,400,400);
fill(0,260,0)
rect(100,100,300,300);
//Creating the Hair in the Back of the head using Ellipses
no... | [
"function setup() {\n\tcreateCanvas(800, 700);\n\tengine = Engine.create();\n\tworld = engine.world;\n\n paper = new PaperBall(30,100,40);\n ground = new Ground(400,690,800,60);\n\n\n\t\n \n}",
"function setup() {\n createCanvas(700, 500);\n dinoStegosaurus = new Dino(200, 200, 5, 40, 87, 83, 65, 68, 16, din... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
requests the oEmbed html | function getOEmbed (tweet) {
// oEmbed request params
var params = {
"id": tweet.id_str,
"maxwidth": MAX_WIDTH,
"hide_thread": true,
"omit_script": true
};
// request data
twitter.get(OEMBED_URL, params, function (err, data, resp) {
tweet.oEmbed = data;
oEmbedT... | [
"function getInnerContent() {\n if (curOpt.url) {\n return '<iframe src=\\'' + curOpt.url + '\\' horizontalscrolling=\\'no\\' verticalscrolling=\\'no\\' width=\\'' + curOpt.width + '\\' height=\\'' + curOpt.height + '\\' frameBorder=\\'0\\'></iframe>';\n } else if (curOpt.selector) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches the pipe registry for a pipe with the given name. If one is found, returns the pipe. Otherwise, an error is thrown because the pipe cannot be resolved. | function getPipeDef$1(name, registry) {
if (registry) {
for (var i = registry.length - 1; i >= 0; i--) {
var pipeDef = registry[i];
if (name === pipeDef.name) {
return pipeDef;
}
}
}
throw new Error("The pipe '" + name + "' could not be fou... | [
"function selectRandomPipe(pipes) {\n const randomPipe = Math.floor(Math.random() * pipes.length);\n const pipe = pipes[randomPipe];\n if (pipe === lastPipe) {\n return selectRandomPipe(pipes);\n }\n lastPipe = pipe;\n return pipe;\n }",
"function getPool(name='_default'){\n // pool exi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper Method for Assigning Load info. ///////////////////////////////////// varString is what it's being stored to varInfo is what is being stored. HINT:! Use. HTML instead of .TEXT for span goodies! Use .TEXT for plain text! | function saveLoadString(varString, varInfo)
{
$(varInfo).html(varString.html());
} | [
"function get_variable_display(instrPtr, variableLoc, objData) { \n var varName = variableLoc.name\n var varLoc = variableLoc.value\n\n // resolve structs that are split between registers\n if (objData[varName] && variableLoc.hasOwnProperty('var_offset') && variableLoc['var_offset'] != null) {\n var offset ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Link sheet measures with time segments in the waveform. This creates DIV overlays on the score sheet for click interaction and acts as placeholders for the smaller wave segments. | function Waveform2Score(wave_start, wave_end, measure_start, measure_end) {
var wavesegment_options = {
container: '#waveform',
waveColor: '#dddddd',
progressColor: '#3498db',
loaderColor: 'purple',
cursorColor: '#e67e22',
cursorWidth: 1,
selectionColor: '#d0e... | [
"function draw_arm_selection_history_all_algorithm(data, algorithm_number) {\n var title = \"Arm Play History of Algorithm \" + list_Algorithms_name[algorithm_number]\n var y_title = \"Percentage\"\n var String_title = [title, y_title]\n var canvas_div = create_canvas_div()\n var arm_number = 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that checks if div="results" is empty or not. If results div is empty, then let a user know that there is no search result. | function checkResults() {
if( $('#results').is(':empty') ) {
displayRestaurantsError("No restaurants were found in your area");
}
} | [
"function noResultAlert() {\n const noResultAlertContainer = document.createElement('p');\n noResultAlertContainer.className = 'no-result';\n noResultAlertContainer.textContent = \"Your search returned no results.\";\n pageContainer.appendChild(noResultAlertContainer);\n noResultAlertContainer.style.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create 3d object for target | function create3DTarget(target) {
let loader = new THREE.TextureLoader();
let planetSize = .5;
loader.load(`./assets/img/targets/${target.name}.jpg`, (texture) => {
let geom = new THREE.SphereGeometry(planetSize, 30, 30);
let mat = (target.name == 'Sun') ? new THREE.MeshBasicMaterial({map: t... | [
"function Object3D() {\n _super.call(this);\n this._castShadows = true;\n this.matrix = new Trike.Matrix4();\n this.worldMatrix = new Trike.Matrix4();\n this.disposed = false;\n this._modelViewMatrix = new Trike.Matrix4();\n this._normalMa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: _fnNodeToDataIndex Purpose: Take a TR element and convert it to an index in aoData Returns: int:i index if found, null if not Inputs: object:s dataTables settings object node:n the TR element to find | function _fnNodeToDataIndex( s, n )
{
var i, iLen;
/* Optimisation - see if the nodes which are currently visible match, since that is
* the most likely node to be asked for (a selector or event for example)
*/
for ( i=s._iDisplayStart, iLen=s._iDisplayEnd ; i<iLen ; i++ )
{
if ( s.aoData[... | [
"function _nodeIndex(node) {\n\t\t// \n\t\tif (!node.parentNode) return 0;\n\t\t// \n\t\tvar nodes = node.parentNode.childNodes,\n\t\t\tindex = 0;\n\t\t// \n\t\twhile (node != nodes[index]) ++index;\n\t\t// \n\t\treturn index;\n\t}",
"getRowIndex(): number {\n const { table, row } = this;\n const ro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows you to add a entry vendor task. | static add(entryVendorTask){
let kparams = {};
kparams.entryVendorTask = entryVendorTask;
return new kaltura.RequestBuilder('reach_entryvendortask', 'add', kparams);
} | [
"static update(id, entryVendorTask){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.entryVendorTask = entryVendorTask;\n\t\treturn new kaltura.RequestBuilder('reach_entryvendortask', 'update', kparams);\n\t}",
"static updateJob(id, entryVendorTask){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkpa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the proper path style (bends, straight, T, etc.) for a given pathmap | function setPathStyles( stateMap, pathmap, type ) {
for ( var row = 0; row < MAP_SIZE; row++ ) {
for ( var col = 0; col < MAP_SIZE; col++ ) {
if ( pathmap[row][col] == 0 ) continue;
if ( type == "free" ) {
if ( stateMap[row][col].type != "path" ) {
stateMap[row][col].type = "grass";
stateMap[row]... | [
"function setGraticule(map, path){\n //create graticule generator\n var graticule = d3.geoGraticule()\n .step([8, 8]); //place graticule lines every 5 degrees of longitude and latitude\n //create graticule background\n var gratBackground = map.append(\"path\")\n .da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resize the result bar to fit within the button and be proportional to all votes. | resizeResult() {
if (this.props.showResults === true && this.state.resultsWidth === 0) {
setTimeout(() => {
this.setState({
resultsWidth: (this.props.answerCount / this.props.highestAnswerCount) * 100,
});
}, 20);
}
} | [
"function adjustSizes() {\n var selectHeight = poemList.length * 15;\n var newHeight = Math.max(350, selectHeight);\n selectBar.setSize(maxWidth, newHeight);\n $(selectBar.canvas).parent().height(\"350px\");\n $(\"poem\").height(maxHeight);\n}",
"function resizeDisplay(answer){\n if (answer.toSt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loop through and apply all registered matchers to the string. If a match is found, create a React element, and build a new array. This array allows React to interpolate and render accordingly. | applyMatchers(
string: string,
parentConfig: NodeConfig,
): string | React$Node[] {
const elements = [];
const { props } = this;
let matchedString = string;
let parts = {};
this.matchers.forEach((matcher) => {
const tagName = matcher.asTag().toLowerCase();
const config = this.... | [
"regexAll (text, array) {\n for (const i in array) {\n let regex = array[i][0]\n const flags = (typeof regex === 'string') ? 'g' : undefined\n regex = new RegExp (regex, flags)\n text = text.replace (regex, array[i][1])\n }\n return text\n }",
"r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the parent folder, if available | get parentFolder() {
return Folder(this, "parentFolder");
} | [
"function parentDir (path) {\n var lastSlash = path.lastIndexOf('/');\n return lastSlash > 0 ? path.substring(0, lastSlash + 1) : undefined;\n }",
"get parent() {\n return new Path(this.parentPath);\n }",
"parent(root, path) {\n var parentPath = Path.parent(path);\n var p = Node$1.get(root,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
displays if we are in demo mode | function demoMessage()
{
let chk_val = $('#demomode').is(":checked");
if(chk_val === true)
{
$('#demoModeMsg').html('DEMO MODE')
}
else
{
$('#demoModeMsg').html('')
}
} | [
"function demoInitialize() {\n document.title = \"Visia\"\n // create the demo instance\n var demo = new Demo()\n demo.init()\n // register the callback that is called when all module contexts are created\n MLABApp.setModuleContextsReadyCallback(demo.moduleContextsReady)\n}",
"function ShowDemoWindow(p_open... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Swap the compare popup spans inner html and classes | function swapSpanCompareHtml(spanId1, spanId2, showCompare) {
debug("swapSpanCompareHtml("+spanId1+"," + spanId2 + ","+(showCompare?'true':'false')+")");
if(showCompare) return;
var charSlotNamesJQ;
var html;
if(spanId1 == null || spanId2 == null) return;
var lbCharslot1 = $("[id ^=lb_charslot_][id $="+s... | [
"function swapSpanHtml(spanId1, spanId2) {\r\n\tvar html1 = $(\"#\"+spanId1).html();\r\n\tvar html2 = $(\"#\"+spanId2).html();\r\n\t$(\"#\"+spanId1).html(html2);\r\n\t$(\"#\"+spanId2).html(html1);\r\n\t\r\n\t// Make sure the drop location equipment details has been rendered\r\n\t$(\"#\"+spanId2).qtip('toggle', true... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CONCATENATED MODULE: ./lib/getReleaseNotes.js Action entry function. Gets the release notes for use in a GitHub release. Works for both monorepos and polyrepos. | async function getReleaseNotes() {
const { releaseVersion, repoUrl, workspaceRoot } = parseEnvironmentVariables();
const rawRootManifest = await (0,dist.getPackageManifest)(workspaceRoot);
const rootManifest = (0,dist.validatePackageManifestVersion)(rawRootManifest, workspaceRoot);
let releaseNotes;
... | [
"function getReleaseNotes() {\n if (!opts.notes) {\n return\n }\n\n if (!existsSync(config.changelogPath)) {\n if (!config.quiet)\n console.log(\n chalk.red.bold(\n 'Create a CHANGELOG.md if you want a Release Notes in your Github Project'\n )\n )\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
populates the gallery info | function popGallInfo() {
for (let g of gallery) {
if (g.GalleryID == gallID) {
document.querySelector('#galleryName').textContent = g.GalleryName;
document.querySelector('#galleryNative').textContent = g.GalleryNativeName;
document.querySelector('... | [
"function addToGallery() {\n library.forEach(book => displayBooks(book));\n updateStats();\n library.splice(0, library.length);\n form.reset();\n}",
"function populateGallery(list, prepend) {\n console.log(\"populateGallery\");\n for (const student of list) {\n const encodedStudentData = createStudentDat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
baynote_urlFactory Construct a meaningful, useable URL from the current page context. Sets baynote_tag.url to that constructed URL. | function baynote_urlFactory(tag) {
var currentUrl = window.location.href;
// Keep "daily" pages and htx scripts as is
if (currentUrl.indexOf("expedia.com/daily/") != -1 || currentUrl.indexOf(".htx") != -1) {
tag.url = currentUrl;
return;
}
// Get the qscr value
var qscrValue = baynote_getQscrValue();
//... | [
"createURL(baseURL, parameters) { return createURL(baseURL, parameters); }",
"function makeUrl(){\r\n var url = location.origin + location.pathname +\r\n '?cid=' + collectedData.currentComment;\r\n return url;\r\n}",
"overrideUrl(iUrl) {\n return iUrl;\n }",
"function baynote_addURLParam(url... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set possible variations e4 | function set_variations() {
html = display_board.print_variations_html();
variation_element.innerHTML = html;
} | [
"function flavour1(){\n flavourSelect=[\"flavour1\", 100];\n }",
"function showScaleVariants(pvn) {\n if (pvn === NODO) { restoreExtra(); return;} // no slot\n if (slots.length < 2) return;\n\n //if (saveExtraObjects) return; // in case of repeating keydown\n var genes = ((saveExtraObjects &... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that deletes a site by ID | function DeleteSite(id) {
baseRequest.delete("sites/" + id, function(err, res, body) {
if (err) {
console.log(err);
} else if (!err && res.statusCode == 200) {
out = JSON.parse(body);
console.log(out);
} else {
console.log("HTTP Status Code: " ... | [
"async delete() {\n const site = await Site(this, \"\").select(\"Id\")();\n const q = Site([this, this.parentUrl], \"_api/SPSiteManager/Delete\");\n await spPost(q, request_builders_body({ siteId: site.Id }));\n }",
"function deleteWebsite(req, res)\n {\n var wid = req.params.web... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a DataUrl like `data:image/jpeg;name=hindenburg.jpg;base64,` using given base64 content, mimeType and fileName. | function base64ToUrl(base64, mimeType, fileName) {
return "data:" + mimeType + (fileName ? ";name=" + fileName : '') + ";base64," + base64;
} | [
"base64Image(imagePath) {\n\t\tconst base64Content = readFileSync(imagePath).toString('base64')\n\t\treturn `data:image/jpeg;base64,${base64Content}`\n\t}",
"function makeDataURI(image) {\n if (image.mime && image.data) {\n image.data = 'data:' + image.mime\n + ';base64,' + image.data;\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
4. Write a function that takes an integer minutes and converts it to seconds. | function convert(minutes) {
var seconds = minutes * 60;
return seconds
} | [
"function secConverter(min)\n{\n return min*60;\n}",
"function convertToSecs(minutes, seconds) {\r\r\n return minutes * 60 + seconds * 1;\r\r\n}",
"function calculateMinutes (seconds) {\n return Math.floor(seconds / 60) % 60;\n}",
"function convertMinutesToSeconds(timeToConvert) {\n var minutes = timeTo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether the input is invalid based on the native validation. | _isBadInput() {
// The `validity` property won't be present on platform-server.
let validity = this._elementRef.nativeElement.validity;
return validity && validity.badInput;
} | [
"validateInputs() {\n\t\tif(isNaN(this.billAmount) || this.billAmount <= 0 || this.totalPerson == 0) return false;\n\t\treturn true;\n\t}",
"function validateInput() {\n\tvar valid = false;\n\tvar maxPins = 0;\n\tif (!((pins==0)||(pins==\"1\")||(pins==2)||(pins==3)||(pins==4)||(pins==5)||(pins==6)||(pins==7)||(pi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a push notification using gcm to the given device ids Payload: see interface Options: see NOTE: when sending to a single device, it will resolve when sent or reject when failed. When sending to multiple devices, it will reject only when server could not be contacted, and resolve with an array of status for each d... | send(ids, notification, payload, options) {
if (typeof ids === 'string' && ids) {
ids = [ids];
} else if (!(ids instanceof Array) || ids.length === 0) {
return Promise.reject(thorin.error('PUSH.SEND', 'At least one device is required'));
}
return new Promise((resolve, reject) => ... | [
"sendPushNotification (apiKey, title, message, payload, filter) {\n\n // check if apiKey is string\n if (typeof apiKey != \"string\" || apiKey.length <= 0)\n {\n this.emit(\"error\", new Error(\"No valid API Key given :'\"+ apiKey +\"'\"));\n }\n\n // check if title is ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utilize GDN as edge cache for serving reads & writes. Following is the behavior of the main() method: 1. For First time reads, Gets data from OriginDB. Populates GDN transparently. 2. For subsequent reads from same region, Serves data from the GDN directly. 3. For subsequent reads from other regions, Serves data from t... | async function main() {
// Login to GDN and Create cache (if not exists)
fabric = new Fabric(fed_url)
await fabric.login(guest_email, guest_password)
await fabric.useFabric(geo_fabric)
const cache = new Cache(fabric)
//Clean Cache from previous runs
await cache.purge(keys);
// Use Macrometa GDN as Ca... | [
"function cacheDns () {\n self.getServerTime(function(err) {\n if(!err) {\n calculateTimeDiff();\n } else {\n syncTime();\n }\n });\n }",
"function fetchFromCache(neLat, neLng, swLat, swLng, type, season) {\n\tvar neLat_floor = Math.floor(neLat);\n\tvar neLng_floor = Math.floor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure that a given value is a Named Node. If the given parameter is a Named Node already, it will be returned asis. If it is a string, it will check whether it is a valid IRI. If not, it will throw an error; otherwise a Named Node representing the given IRI will be returned. | function asNamedNode(iri) {
if (!internal_isValidUrl(iri)) {
throw new ValidUrlExpectedError(iri);
}
if (isNamedNode(iri)) {
return iri;
}
return DataFactory.namedNode(iri);
} | [
"is(name) {\n if (typeof name == 'string') {\n if (this.name == name) return true\n let group = this.prop(dist_NodeProp.group)\n return group ? group.indexOf(name) > -1 : false\n }\n return this.id == name\n }",
"toNODE() {\n switch (this._type) {\n cas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If harry eats special food a varibale is changed to yes and setTimeOut is started. After 9 seconds the setTimeout its disabled and the same variable is turnded to 'no' | function removeSpecialVoldemortClass(){
if (didHarryEatSpecialFood === 'yes'){
didHarryEatSpecialFoodDelayTimer = setTimeout(()=> {
didHarryEatSpecialFood = 'no'
}, 9000)
didHarryEatSpecialFoodDelayTimer = null
console.log(didHarryEatSpecialFood)
}
} | [
"function filthyCheater(tickSpeed,noImNot)\n{\n //Putting default values\n if (typeof noImNot === undefined) {noImNot=false;};\n if ((typeof tickSpeed === undefined)||(tickSpeed < 1)) {tickSpeed=25;}\n\n //Stop the clicking already, we'll start again soon enough\n clearInterval(autoClickerCheck);\n\n //This i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots crime markers from crimeDamage.js onto the map. Assigns a popup to each point. They are plotted as divIcons to improve performance given the large volume of data. | function plotPoints() {
if (typeof pointMarkerLayer !== 'undefined') {
pointMarkerLayer.addTo(mymap);
} else {
pointMarkerLayer = new L.layerGroup();
for (id in crimDamage) {
var markerLocation = new L.LatLng(crimDamage[id].lat, crimDamage... | [
"function createMarkers(div) {\n div.each(function() {\n j.push({\n type: 'Feature',\n \"geometry\": {\n \"type\": \"Point\",\n // of note: for some reason that lat/long need to be reversed here such that it is long/lat\n \"coordinates\": [this['dataset']['long'], t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a new ``int48`` type for %%v%%. | static int48(v) { return n(v, -48); } | [
"function toAInt(v) {\n\tif (!(v instanceof AInt))\n\t\treturn new AInt(v);\n\treturn v;\n}",
"static int128(v) { return n(v, -128); }",
"static int24(v) { return n(v, -24); }",
"function encode_int(v) {\n if (!(v instanceof BigInteger) ||\n v.compareTo(BigInteger.ZERO) < 0 ||\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switches single date on/off | function toggleSingleDate(setCheckedTo){
document.getElementById('singleDate').checked=setCheckedTo;
} | [
"function toggleNight(){\n\tif (nightMode) {\n\t\tnightMode = false;\n\t} else {\n\t\tnightMode = true;\n\t}\n}",
"function handleDiliveryDateChange(e) {\n setDeliveryDate(e.target.value)\n setDrawer(false)\n }",
"function clockOnlyOnToggle() {\n \n if (clockTracker === 0 && optionsTracker === 0 && too... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find recipe by user ID | function findRecipeByUser(userId) {
return RecipeModel.find({ username: username });
} | [
"getRecipeByUserId(knex, userLoginToken) {\n return knex\n .select('id')\n .select('recipe_name')\n .select('recipe_image_link')\n .select('serving_size')\n .select('total_calories')\n .select('cook_time')\n .select('cooking_instruc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A slave for websocket server: overlord. | function WebsocketSlave() {
// IP of the master
this.ip = 'localhost:1337';
// Socket connection
this.connection = null;
// Reconnect if connection fails?
this.enableReconnect = false;
// The time in ms between every reconnect
this.reconnectInterval = 5000;
// Are we trying to reconnect already?
... | [
"function openLobby(){\n\n\tlet update = {};\n\tupdate.method = 'openLobby';\n\tsocket.emit('player-update', update);\n}",
"function masterServer_ConnectWithRequestType(msgType) {\n var wsProtocol = window.location.protocol === \"https:\" ? \"wss://\" : \"ws://\";\n var wsPort = wsProtocol == \"wss://\" ? 7501 ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Browser specific loadImplementation. Always uses `window.Promise` To register a custom implementation, must register with `Promise` option. | function loadImplementation(){
if(typeof window.Promise === 'undefined'){
throw new Error("any-promise browser requires a polyfill or explicit registration"+
" e.g: require('any-promise/register/bluebird')")
}
return {
Promise: window.Promise,
implementation: 'window.Promise'
}
} | [
"function assignPromiseEngine(engine) {\n NativePromise = engine;\n}",
"function loadAsync() {\n if (handlersIn.load) {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callHandler(handlersIn.load, transformE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Body Detect get body detect form. | function getBodyDetectForm(serviceId, sessionKey) {
let str = '';
// body
str += '<h1>BODY</h1>';
// -------------------------------------------------------
// get,register,unregister
str += '<div>';
str += ' <input data-icon=\"search\" onclick=\"doHumanDetectBodyGet(\'' +
serviceId + '... | [
"function GetBody() {\n const context = React.useContext(SinglepostContext)\n if (context) {\n return context.data.body.map(bodyString => {\n\n if (bodyString.includes(\"(CODE)\")) {\n const splitBodyString = bodyString.split(\"(CODE)\");\n return <Page la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for drawing team details table | function drawTeamDetailsTable(result) {
let table = document.getElementById('team-details');
let tableBody = document.getElementsByTagName('tbody');
let tr = document.createElement('tr');
tableBody[0].appendChild(tr);
for (let i = 0; i < result.length; i++) {
/** adding new table row... | [
"function drawGroupResultsDetailsTable(result) {\r\n let table = document.getElementById('group-results-details');\r\n let tableBody = document.getElementsByTagName('tbody');\r\n let tr = document.createElement('tr');\r\n tableBody[0].appendChild(tr);\r\n\r\n /** getting all rows */\r\n for (let i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
N.B. loadImageHtml is broken on IE8 for images that require resizing, due to the missing HTML5 canvas element and naturalWidth/naturalHeight properties on image elements. This is currently not a problem because the HTMLbased renderers (WebGL and CSS) do not work on IE8 anyway for lack of CSS transforms support. It coul... | function loadImageHtml(url, rect, done) {
var img = new Image();
// Allow cross-domain image loading.
// This is required to be able to create WebGL textures from images fetched
// from a different domain. Note that setting the crossorigin attribute to
// 'anonymous' will trigger a CORS preflight for cross-... | [
"static prepareImageElement(imageSource){if(imageSource instanceof HTMLImageElement){return imageSource;}if(typeof imageSource==='string'){return BrowserCodeReader$1.getMediaElement(imageSource,'img');}if(typeof imageSource==='undefined'){const imageElement=document.createElement('img');imageElement.width=200;image... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gcd(s1,s2) :: Int > Int > Int | function h$ghcjsbn_gcd_ss(s1, s2) {
h$ghcjsbn_assertValid_s(s1, "gcd_ss s1");
h$ghcjsbn_assertValid_s(s2, "gcd_ss s2");
var a, b, r;
a = s1 < 0 ? -s1 : s1;
b = s2 < 0 ? -s2 : s2;
if(b < a) {
r = a;
a = b;
b = r;
}
while(a !== 0) {
r = b % a;
b = a;
a = r;
}
h$ghcjsbn_assertVa... | [
"function coprime(a, b)\n{\n if (__gcd(a, b) === 1)\n console.log(\"1\");\n else\n console.log(\"0\"); \n}",
"function compGCD(firstRank,secondRank){\n let curBoolean = false;\n let firstCDs = ranksMap.get(firstRank);\n let secondCDs = ranksMap.get(secondRank);\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats the color as RRGGBBAA If 'compact' is set, colors without transparancy will be printed as RRGGBB | function formatHexA(color, compact) {
if (compact === void 0) { compact = false; }
if (compact && color.rgba.a === 1) {
return Color.Format.CSS.formatHex(color);
}
return "#" + _toTwoDigitHex(color.rgba.r) + _toTwoDigitHex(color.rgba.g)... | [
"static forceColor() {\n chalk_1.default.level = 1; // `1` - Basic 16 colors support.\n }",
"function _g_scr_color() { \n\tvar sc=\"\";\n\tif (self.screen) {\n\t\tsc=screen.colorDepth+\"-bit\";\n\t}\n\treturn sc;\n}",
"function toRGBString (color) {\n\t\treturn color.r.toFixed(0) + ', ' + color.g.toFi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find y between yl and yh in the same ratio of x between xl, xh simple straight line interpolation. | function interpolate(x, xl, xh, yl, yh) {
var r = 0;
if ( x >= xh ) {
r = yh;
} else if ( x <= xl ) {
r = yl;
} else if ( (xh - xl) < 1.0E-8 ) {
r = yl+(yh-yl)*((x-xl)/1.0E-8);
} else {
r = yl+(yh-yl)*((x-xl)/(xh-xl));
}
return r;
} | [
"interpolateY(x) { // input x (real-number)\n var index = this.bisection(x);\n \n if(this.arySrcX[index] === x)\n return this.arySrcY[index];\n else\n return this.doCubicSpline(x, index);\n }",
"function linear_interpolate(x, x0, x1, y0, y1){\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
These functions query logger data | function queryLoggerData(starttime,endtime,doOnSuccess) {
if(endtime!="now")
$.couch.db("dripline_logged_data").view("log_access/all_logged_data", {
startkey: starttime,
endkey: endtime,
success: function(data) {
doOnSuccess(data); },
error: function(data) {
document.getElementById("error_div").innerHTM... | [
"getLogs() {\n if (this.auth()) {\n if (this.currentUser.type === \"admin\") {\n console.log(\"Saved logs: \");\n for (let i = 0; i < this.logs.length; i++) {\n console.log(this.logs[i]);\n }\n }... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Purposely sideeffectish method to ensure "transaction.test" inherits data from the "transaction". Necessary when a test is skipped/failed to contain transaction information that is otherwise missing. | ensureTestStructure(transaction) {
transaction.test.request = transaction.request;
transaction.test.expected = transaction.expected;
transaction.test.actual = transaction.real;
transaction.test.errors = transaction.errors;
transaction.test.results = transaction.results;
} | [
"failTransaction(transaction, reason) {\n transaction.fail = true;\n\n this.ensureTransactionErrors(transaction);\n if (reason) {\n transaction.errors.push({ severity: 'error', message: reason });\n }\n\n if (!transaction.test) {\n transaction.test = this.createTest(transaction);\n }\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert value at the end and sift up | insert(value){
this.data.push(value);
this.siftUp(this.data.length-1)
} | [
"insertAfter(value, newVal) {\n let current = this.head;\n\n while(current) {\n if (current.value === value) {\n let node = new Node(newVal);\n node.next = current.next;\n current.next = node;\n return;\n } \n current = current.next;\n }\n }",
"function insertX... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
KeyboardEvent handler to hide the tooltip on Escape key press | function hideOnEscapeKey(e) {
if (e.which === 27) {
hideTooltipBind();
}
} | [
"handleEscapeKey (event) {\n\t\tif (event.which === ESCAPE_KEY_CODE) {\n\t\t\tthis.hideMenu();\n\t\t}\n\t}",
"function handleEscKeyboardPress() {\n $(document).keyup(function(event) {\n if (event.keyCode === 27) {\n exitSection();\n }\n });\n }",
"function closeOnEscape(event){\n //find ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Based on an optimized c++ solution in This CubicPoly class could be used for reusing some variables and calculations, but for three.js curve use, it could be possible inlined and flatten into a single function call which can be placed in CurveUtils. | function CubicPoly() {} | [
"static CreateCubicBezier(v0, v1, v2, v3, nbPoints) {\n // tslint:disable-next-line:no-parameter-reassignment\n nbPoints = nbPoints > 3 ? nbPoints : 4;\n const bez = new Array();\n const equation = (t, val0, val1, val2, val3) => {\n const res = (1.0 - t) * (1.0 - t) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select mxport as input source | selectInputSourceMxport() {
this._selectInputSource("i_mxport");
} | [
"selectInputSourceMplay() {\n this._selectInputSource(\"i_mplay\");\n }",
"selectInputSourceNet() {\n this._selectInputSource(\"i_net\");\n }",
"function setPortObject(port,action){\n\tif(action == \"source\"){\n\t\tportspeedflag = true;\n\t\tportflag = true;\n\t\tsourcePath = port.ObjectPat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clears out any selected rows. Called after a download. | function clearSelectedRows() {
var tblRows = contentTbl.fnGetNodes(),
tblRow,
numRows = tblRows.length;
for (var i = 0; i < numRows; i++) {
tblRow = $(tblRows[i]);
if ($(tblRow).hasClass('selected')) {
$(tblRow).removeClass('selected');
}
}
} | [
"function clearAllSelection(){\n ds.clearSelection();\n arrDisp.length=0;\n updateSelDisplay();\n updateCurrSelection('','','startIndex',0);\n updateCurrSelection('','','endIndex',0);\n}",
"function clear() {\n $('.tablesorter tbody tr').remove();\n $('.tablesorter').trigger('updateAll');\n}",
"function ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
toggles directions on and off in mapbox | function toggleDirections() {
$("#toggleDirections").on("click", (event) => {
event.preventDefault();
if (STORE.nav !== true) {
addNav();
STORE.nav = true;
} else {
removeNav();
STORE.nav = false;
}
});
} | [
"function toggleSnap() {\n if (snapping == 'on') {\n snapping = 'off'\n }\n else {\n snapping = 'on'\n }\n}",
"function ToggleSnapping(){\n\tSnapping = !Snapping;\n}//ToggleSnapping",
"function toggleTrialMap() {\n\tvar map = $('#g_map');\n\t\n\t// hide\n\tif (map.is(':visible')) {\n\t\tvar link_offse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Begins generating schedules given an array of course IDs. | function startGenerating(_aCourseIDs, _fUpdateStatusCallback) {
aCourseIDs = _aCourseIDs;
fUpdateStatusCallback = _fUpdateStatusCallback;
// Empty the current indices and schedule array
aCurrentIndices = [];
aCurrentSchedule = [];
// Empty the possible s... | [
"function scheduleCourse(iCourseID) {\n if (iCourseID >= aCourseIDs.length) {\n // We are out of courses to schedule - great!\n // Make a 1-dimensional array out of the 2-dimensional current schedule array\n var aPossibleSchedule = [];\n var sPossibleSchedule = \"\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper method to append a score to a table | function appendScore(ourScore, theirScore) {
if (ourScore == undefined) {
ourScore = 0;
}
if (theirScore == undefined) {
theirScore = 0;
}
var innerHtml = "<table>" +
"<tr><td>" + dataManager.game.ourTeamName + ":</td><td>" + ourScore + "</td></tr>" +
"<tr><td>" + dataManager.game.theirTeamName +... | [
"function updateLeaderboard(data) {\n\n // Remove previous scores\n $('.score_row').remove();\n\n for (var i = 0; i < 10; i++) {\n\n if (data.player_rank == i) {\n\n $('#leaderboard table tr:last').after('<tr class=\"score_row user_score\"><td>' + (i + 1) + '</td><td>You</td><td>' + data.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the webpart information associated with this definition | get webpart() {
return SPInstance(this, "webpart");
} | [
"getPart(part) {\n return this._parts.get(part);\n }",
"get pathPart() {\n return this.getStringAttribute('path_part');\n }",
"open() {\n return spPost(WebPartDefinition(this, \"OpenWebPart\"));\n }",
"delete() {\n return spPost(WebPartDefinition(this, \"DeleteWebP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Default values for styles | function defaultStyles(){
return {
classes: {
'with-3d-shadow': true,
'with-transitions': true,
'gallery': false
},
... | [
"_initStyles() {\n const styles = this.constructor.styles !== undefined ? this.constructor.styles : this.styles();\n if (!styles) { return }\n this.styleSheet = new ScreenStyle(styles, this.id);\n }",
"cramp() {\n return styles[cramp[this.id]];\n }",
"init(state){\n\t\t\tstat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
========================================================================// preverjanje urla in dolocanje imena postaje ======================================================================== | function checkUrl(objname, postaja, tip, datumz, datumk) {
var today = new Date();
var maxdate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
if (str2date(datumz).valueOf() >= maxdate.valueOf() || str2date(datumk).valueOf() >= maxdate.valueOf()) {
throw "OBRAVNAVAJO SE LAHKO SAMO PODATKI... | [
"function postaviPitanje() {\n\t\t//zavisno od nivoa generise se pitanje razlicite tezine\n\t\t//tezina se mijenja nakon svakog petog pitanja\n\t\tif (nivo <=4) {\n\t\t\tpostavljenoPitanje = generisiPitanje(1, 5);\n\t\t} else if (nivo > 4 && nivo <= 9) {\n\t\t\tpostavljenoPitanje = generisiPitanje(5, 15);\n\t\t} el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create URL references from the vulnerability references | function getUrlReferences(References) {
return References ? References.filter(ref => ref.startsWith("http")).map(ref => ({type: "URL", value: ref})) : [];
} | [
"function linkifyCVE(str) {\n const regexp = /(CVE-\\d{4}\\-\\d{4,})/gi;\n const linkText = \"[:vulnerability:$1](/cves/$1)\";\n return str.replace(regexp, linkText);\n}",
"_createUrls () {\n\t\tvar urls = {};\n\n\t\t//set up all the urls required\n\t\turls.idea = '/' + this.props.idea.idea_id + '/';\n\t\turls... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns number of milliseconds in the `count` of time `unit`. Available units: "millisecond", "second", "minute", "hour", "day", "week", "month", and "year". | function getDuration(unit, count) {
if (!_utils_Type__WEBPACK_IMPORTED_MODULE_0__["hasValue"](count)) {
count = 1;
}
return timeUnitDurations[unit] * count;
} | [
"ms () { return this.now() - this.startMS }",
"function timestampWithMs() {\n return Date.now() / 1000;\n}",
"function calcDistance(text, unit) {\n if (unit === 'character') {\n return getCharacterDistance(text);\n } else if (unit === 'word') {\n return getWordDistance(text);\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility function to rebuild a default template dropdown. | function TKR_rebuildDefaultTemplateMenu(menuID) {
var defaultTemplateName = $(menuID).value;
var parentEl = $(menuID);
while (parentEl.childNodes.length)
parentEl.removeChild(parentEl.childNodes[0]);
for (var i = 0; i < TKR_templateNames.length; i++) {
if (TKR_templateNames[i] != TKR_DELETED_PROMPT_NA... | [
"function TKR_rebuildTemplateMenu() {\n var parentEl = $('template_menu');\n while (parentEl.childNodes.length)\n parentEl.removeChild(parentEl.childNodes[0]);\n for (var i = 0; i < TKR_templateNames.length; i++) {\n if (TKR_templateNames[i] != TKR_DELETED_PROMPT_NAME) {\n var option = TKR_createC... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the word in 'value' under the cursor position | function currentWord(value, position) {
var [i, j] = currentWordPosition(value, position);
return value.slice(i, j);
} | [
"function getWordOnPosition(pos) {\n\tvar editableDiv = document.getElementById(\"inputTextarea\");\n\tvar curPos = getCaretPositionInDiv(editableDiv);\n\tsetCaretPositionInDiv(editableDiv, pos);\n\tvar word = getCurrentWord();\n\tsetCaretPositionInDiv(editableDiv, curPos);\n\treturn word;\n}",
"function getClick... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dispose of the set and the items it contains. Notes Items are disposed in the order they are added to the set. | dispose() {
if (this.isDisposed) {
return;
}
this.isDisposed = true;
this.items.forEach((item) => {
item.dispose();
});
this.items.clear();
} | [
"function ItemSet() {\r\n/**\r\n * @type Object\r\n * @private\r\n */\r\n\tthis._contents = {};\r\n}",
"function clearSetsList() {\n while ($setsArea.firstChild !== $createNewElem) {\n $setsArea.removeChild($setsArea.firstChild);\n }\n }",
"function Set() {\n this._items = [];... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Composite points is the union of segment change points; it gives the set of segments that need to be compared. | getCompositePoints() {
function getPoints(j){
var points = [];
var segs = j.getSegments();
for(var s of segs) {
points.push(s.getStart());
points.push(s.getEnd());
}
return points;
}
var p1 = getPoint... | [
"function insertCutPoints(unfilteredPoints, arcs) {\n var data = arcs.getVertexData(),\n xx0 = data.xx,\n yy0 = data.yy,\n nn0 = data.nn,\n i0 = 0,\n i1 = 0,\n nn1 = [],\n srcArcTotal = arcs.size(),\n map = new Uint32Array(srcArcTotal),\n points = filterSortedCutPoints(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Format a range of prices | function formatPriceRange(price_min, price_max, options={}) {
var p_min = price_min || price_max;
var p_max = price_max || price_min;
var quantity = 1;
if ('quantity' in options) {
quantity = options.quantity;
}
if (p_min == null && p_max == null) {
return null;
}
p_... | [
"function setPriceRange(list) {\n let min = Infinity;\n let max = -Infinity;\n list.forEach(hotel => {\n const price = parseFloat(hotel.price);\n if (price > max) max = price;\n if (price < min) min = price;\n });\n\n //Set minimum and maximum pric... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates firing elevation (in PR mils) from a distance vector, and an elevation given in meters. | function calcualteBarrelElevation(distanceXY, distanceZ) {
const v0 = 150; // speed of the mortar rounds in m/s
const ag = -15; // shell acceleration in m/s^2
// We simply solve a quadratic formula to get the firing angle
const a = 0.5 * ag * (distanceXY ** 2) / (v0 ** 2); // prettier-ignore
const b = distan... | [
"function GetElevationfromPoint(results) {\n LoadingPicture.addClass(\"hidden\");\n elevation = results[0].value.features[0].attributes.RASTERVALU;\n $(\"#MinimumElevation\").val(Math.floor(elevation));\n }",
"function updateElevation() {\n if (markers.length > 1) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make the URL lower case. | function lower(req, res, next) {
req.url = req.url.toLowerCase();
next();
} | [
"function lower(text) {\n return text.toLowerCase();\n }",
"function lowercase(value) {\n return String(value).toLowerCase();\n}",
"function camelize(name, forceLower){\n if (firstDefined(forceLower, false)) {\n name = name.toLowerCase();\n }\n return name.replace(/\\-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make ghost block at xyz | function createGhostAt(x, y, z) {
const next = new CustomBlock(x, y, z);
next.block
.addClass("ghost")
.appendTo($scene);
ghost = next;
} | [
"ghostBlockCollide(block, ghost) {\n block.hp -= 0.1;\n }",
"spawnBlock(x, y) {\n let block = new Block(this, x, y);\n }",
"function Plugin_LogicSeparatingBlock()\n\t{\n\t\tthis._tmpPos = new (PhysicsCore.b2Vec2)();\n\t}",
"standingBlock() {\n\t\tthis.updateState(KEN_SPRITE_POSITION.standi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility function to get next month of given date | function getNextMonth(date) {
var year = date.getFullYear()
var month = date.getMonth()
if(month < 11) {
return new Date(year, month + 1, 1, 0, 0, 0, 0)
} else {
return new Date(year + 1, 0, 1, 0, 0, 0, 0)
}
} | [
"function getNextMonth() {\n var now = new Date();\n var current = new Date();\n if (now.getMonth() == 11) {\n current = new Date(now.getFullYear() + 1, 0, 1);\n } else {\n current = new Date(now.getFullYear(), now.getMonth() + 1, 1);\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check or Uncheck All team CheckBox | function selectAllTeamMenuCheckBox(){
if(document.getElementById('teamMenuSelectAllId').checked==true){
document.getElementById('teamMenuAddId').checked=true;
document.getElementById('teamMenuViewId').checked=true;
document.getElementById('teamMenuUpdateId').checked=true;
document.getElementById('teamMenuDel... | [
"function uncheckAll(name) {\r\n\tsetCheckboxState(name, false);\r\n}",
"function selectAllTargetandGoalMenuCheckbox(){\n\tif(document.getElementById('targetandGoalMenuSelectAllId').checked==true){\n\t\tdocument.getElementById('targetandGoalMenuAddId').checked=true;\n\t\tdocument.getElementById('targetandGoalMenu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get food produced by farmers | function getFarmersFoodGain() {
return Math.floor(_varibale.foodGain.farmer * _varibale.other.tf * _varibale.population.farmers);
} // get food consumed by farmers | [
"function getFoodInfo(meal_id, unirest, callback)\n\t{\n let foodData = {};\n foodData[\"mid\"] = meal_id;\n console.log(`Getting info for ${meal_id}`)\n\t\tunirest.get(`https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/${meal_id}/information?includeNutrition=true`)\n\t\t.header(\"X-Rapid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When we process a product action event, Amplitude has a very specific way of sending events to them: 1. Send a summary event with event attributes from the MP event. a. Add a key of `products` with a value of JSON.stringify(productArray). b. Add a key of mparticle_amplitude_should_split with a value of `false`. 2. Dete... | function processTemporaryProductAction(
unexpandedCommerceEvent,
expandedEvents
) {
var summaryEvent, isRefund, isPurchase, isMPRevenueEvent;
isRefund =
unexpandedCommerceEvent.ProductAction.ProductActionType ===
mParticle.ProductActionType.Refund;
is... | [
"function onLowestDeliveryVariationSelected() {\n var $this = $(this);\n var event_data = {\n 'event': 'UniversalEvent',\n 'eventCategory': 'Products',\n 'eventAction': 'clicked express',\n 'eventLabel': ''\n };\n var product_data = shopAnalytics.getProductsData($(shopAnalytics.produ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retrieves the text contents of a optional param element or document body | function getDocumentText(element) {
element = $(element) || $("body");
var params = { "text": "", "trim": true };
// iterate through all children of body element
if (element.length > 0) {
var children = element[0].childNodes;
for (var i = 0; i < children.length; i++) {
var child = children[i];
... | [
"function $textContent(elem, val){ \n elem = $O(elem);\n var tc = '';\n\n if(typeof elem.textContent !== 'undefined'){\n if(typeof val === 'string'){\n elem.textContent = val;\n }\n tc = elem.textContent;\n }\n else{\n if(typeof val === 'string'){\n elem.innerText = val;\n }... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MULTIPLY calculates the product of two numbers. | function MULTIPLY() {
for (var _len10 = arguments.length, values = Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
values[_key10] = arguments[_key10];
}
// Return `#NA!` if 2 arguments are not provided.
if (values.length !== 2) {
return error$2.na;
}
// decompose values into a and b.
var... | [
"function product (a, b){\n return a*b;\n}",
"function multiplicacion(a, b) {\n //tu codigo debajo\n let resultado = a * b;\n return resultado;\n}",
"function mulb(a, b) {\n return a * b;\n}",
"function multiply(a, b, c) {\n const result = multiply_curried(a)(b)(c);\n return result;\n}",
"function... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse from the filter format 'dd/mm/yyyy' (Turkish culture) | function parseDateFromFilter(strDate) {
// var parts = strDate.split(' ');
// return new Date(parts[2], parts[1] - 1, parts[0]);
return new Date(strDate);
} | [
"function parseDate(val) {\r\n var preferEuro = (arguments.length == 2) ? arguments[1] : false;\r\n generalFormats = new Array('y-M-d', 'MMM d, y', 'MMM d,y', 'y-MMM-d', 'd-MMM-y', 'MMM d', 'd MMM yyyy', 'dd MMM yyyy');\r\n monthFirst = new Array('M/d/y', 'M-d-y', 'M.d.y', 'MMM-d', 'M/d', 'M-d');\r\n da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper methods to Manage Service Worker: register a new Service Worker; track Service Worker installation progress, when new worker is installed call an updateReady function; show confirmation window to a user when a new version of Service Worker is available; Credits: | function ManageServiceWorker() {
this.registerServiceWorker = function() {
let manageServiceWorker = this;
navigator.serviceWorker.register('/sw.js')
.then(function(reg) {
if (!navigator.serviceWorker.controller) {
return;
}
if (reg.waiting) {
manageServiceWorker.updateReady(reg.waiting... | [
"async register_service_worker() {\n\n\t\t// Solicita la aceptación de notificaciones\n\t\tconst push_permission = (reg) => {\n\t\t\tif (Notification.permission == 'default' || navigator.serviceWorker.controller) this.sw_notification_permission(reg);\n\t\t}\n\n\t\t// Callback al recibir un mensaje desde el service ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if number is disarium | function disariumNumber(n){
let arr = (""+n).split('');
let num = 0;
arr.forEach((e,i)=>{
num += Math.pow(Number(e),(i+1));
});
if(num == n){
return "Disarium !!";
}
return "Not !!";
} | [
"function isNumber() {\n\t\tif (screenDown.innerHTML.charCodeAt(screenDown.innerHTML.length-1)>47&&screenDown.innerHTML.charCodeAt(screenDown.innerHTML.length-1)<58) {\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}",
"function isNaN(x)\n\t {\n\t \treturn x !== x;\n\t }",
"function lhopi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by Python3Parserxor_expr. | visitXor_expr(ctx) {
console.log("visitXor_expr");
let length = ctx.getChildCount();
let value = this.visit(ctx.and_expr(0));
for (var i = 1; i * 2 < length; i = i + 1) {
if (ctx.getChild(i * 2 - 1).getText() === "^") {
value = {
typ... | [
"visitNot_test(ctx) {\r\n console.log(\"visitNot_test\");\r\n if (ctx.NOT() !== null) {\r\n return {\r\n type: \"UnaryExpression\",\r\n operator: \"not\",\r\n operand: this.visit(ctx.not_test()),\r\n };\r\n } else {\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array with permissions for each and every parameter value. For example: ``` _unwindPermission('/articles?var1=foo1,foo2&var2=foo3,foo4:read,update'); // [ // "/articles?var1=foo1&var2=foo3:read,update", // "/articles?var1=foo1&var2=foo4:read,update", // "/articles?var1=foo2&var2=foo3:read,update", // "/artic... | _unwindParameters(permission) {
const perm = new URLPermission(permission);
const params = perm.parameters();
if (!params) return [perm]; // Simply return, nothing to unwind
// Recursive function that returns an array with one object for each unique
// path in the `params` object.
const unwind ... | [
"function filterPermissionsByRestrictedAccessHandler(context, entityTypeId, entityId, permissions, operationMsg) {\n if (context.user.restrictedAccessHandler) {\n const originalOperations = permissions;\n if (context.user.restrictedAccessHandler.permissions) {\n const entityPerms = conte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a formatted value for a cell | formatValue(cell){
var component = cell.getComponent(),
params = typeof cell.column.modules.format.params === "function" ? cell.column.modules.format.params(component) : cell.column.modules.format.params;
function onRendered(callback){
if(!cell.modules.format){
cell.modules.format = {};
}
cell... | [
"priceFormatter(cell, row) {\n\t\treturn `$${cell}`;\n\t}",
"function cellValue(activeRange,row,col) {\n var row = row;\n var col = col;\n var range = activeRange;\n var cell = range.getCell(row,col).getValue();\n Logger.log(\"cellValue: \" + cell);\n return cell;\n}",
"function formatValore(field)\n{\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts preview boxes into the DOM tree within each article tag. | function eachPreview(idx, elem) {
var span = $(elem);
// Set up the button that will show the image preview
var expandButton = $('<a class="gelbooru-preview">+</div>');
expandButton
.css({
'position': 'absolute',
'right': 0,
'top': 0,
'width': '20px',
'height': '20px',
'padding': 0,
'text-... | [
"function createPreview() {\n var createdNewElement = createItemElement(images[0]);\n createdNewElement.setAttribute(\"id\", \"preview\");\n return createdNewElement;\n}",
"_initMarkdownAndPreviewSection() {\n this.$mdEditorContainerEl = this.$containerEl.find('.te-md-container .te-editor');\n th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |