query stringlengths 9 34k | document stringlengths 8 5.39M | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
create java set sample data for Property | function makeJavaSetSampleDataForProperty() {
var dtoJavaVarName = 'cdtdtl';
var setDtoDataWithJava = '';
for (var i = 1; i < gValuesOfRange.length; i++) {
/** set common var in column range*/
if (!setCommonVar(i)) {
return '';
}
if (cPhysicalNameOfColumn == '') {
break;
}
setDtoDataWithJava += dtoJavaVarName + ".set" + cJavaPropertyNameFirstCharUpperCase + "(";
setDtoDataWithJava += makeDataSampleWithJava(cTypeVal);
setDtoDataWithJava += ');' + newLine;
}
return setDtoDataWithJava;
} | [
"function getPropertyData(property) {\n const hexValues = (property.multiple\n ? property.examples\n : [property.examples[0]]\n ).map(x => x.data_component);\n\n return hexValues.reduce((acc, hex) => {\n const dataComponent = [\n PROPERTY_DATA_ID,\n ...hexToUint8Array(\n hexToUint8Array... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
after name you can add arguments for rooms to conect this to in the form (room, direction, locationOnWall) | function Room (name, type) {
this.name = name;
this.type = type;
this.roomLinks = new Array(); //items in form [Room, direction, xoryvalue]
if (arguments.length === 5) {
this.linkRooms(arguments[2], arguments[3], arguments[4]);
} else
if (arguments.length > 2) {
throw 'wrong number of arguments';
}
allRooms[this.name] = this;
} | [
"function Room (name) {\n\tthis.name = name;\n\tthis.saveData = new Array();\n\tthis.roomLinks = new Array(); //items in form [Room, direction, xoryvalue]\n\tif (arguments.length === 4) {\n\t\tthis.linkRooms(arguments[1], arguments[2], arguments[3]);\n\t} else \n\tif (arguments.length > 1) {\n\t\tthrow 'wrong numbe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create div with specifed className that contains a p tag | function createDiv(className, content) {
let pTag = document.createElement('p');
let divTag = document.createElement('div');
pTag.textContent = content;
divTag.classList.add(className);
divTag.appendChild(pTag);
// console.log(divTag);
return divTag;
} | [
"createParagraph(className, content) {\n const p = document.createElement(\"p\");\n p.className = className;\n p.innerHTML = content;\n return p;\n }",
"function createParagraph(text, className){\r\n //creating paraghraph element\r\n var paragraph = document.createElement(\"p\");\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
plays the animation regarless of previous state | play(){this.__stopped=!0;this.toggleAnimation()} | [
"continue() {\n this.currentAnimation.isPlaying = true;\n this.currentAnimation.finishedSingleLoop = false;\n }",
"play() {\n\t\tthis.animActions.forEach( action => action.play() );\n\t\tthis.isPlaying = true;\n\t}",
"play() {\n this.__stopped = true;\n this.toggleAnimation();\n }",
"resume() {\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
funcion que se encarga de cargar el contenido de las bandejas a la hora de seleccionar una tab | function cargarContenidoTab(event, ui){
//Seteo el cookie de la tab seleccionada
setCookIGDoc("IGDocBandejaNuevaForm", ui.newPanel.index()-1, "CookieBandeja");
//Cargo la tab seleccionada
switch(ui.newPanel.index()-1){
case 0:
//alert("#tabs-1");
cargarBandFormularios();
break;
case 1:
cargarBandejaReservados();
break;
case 2:
//alert("#tabs-3");
cargarBandejaFinalizados();
break;
case 3:
cargarBandejaMarcadas();
case 4:
cargarBandejaParaFirmar();
break;
}
} | [
"function cargarContenidoTab(event, ui){\n\n\t//Seteo el cookie de la tab seleccionada\n\tsetCookIGDoc(\"IGDocBandejaNuevaDoc\", ui.newPanel.index()-1, \"CookieBandeja\");\n\n\t//Cargo la tab seleccionada\n\n\t\n\tswitch(parseInt(ui.newPanel.index()-1)){\n\t\tcase 0:\n\t\t\tcargarBandejaBorradores();\n\t\t\tbreak;\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
invert:list>list Invierte los elementos de una lista invert([1,2,3])>[3,2,1] invert([3,2,1])>[1,2,3] | function invert(list) {
if(length(list)==0) {
return [];
} else {
return cons(last(list),invert(pop(list)));
}
} | [
"function invert(list) {\r\n if(length(list)==0) {\r\n return [];\r\n } else {\r\n return cons(last(list),invert(pop(list)));\r\n }\r\n}",
"function invertir(list) {\n if(longitud(list)==0){\n return [];\n } else {\n return cons(last(list),invertir(pop(list)));\n }\n}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a PermissionPrompt for a nsIContentPermissionRequest for the GeoLocation API. | function GeolocationPermissionPrompt(request) {
this.request = request;
} | [
"function askPermission() {\n geolocation.requestAuthorization();\n }",
"function geoLocationAskPermission() {\r\n if (navigator.geolocation) {\r\n navigator.geolocation.getCurrentPosition(geoLocationHandler);\r\n }\r\n}",
"function askPermissionForLoc(agent){\n\tconst conv = agent.conv(); \n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applicationlevel logout: we simply discard the token. | function logout() {
tokenStore['igtoken'] = undefined;
} | [
"function logout() {\n fetch(REVOKE_TOKEN_URL + accessToken)\n .then(logoutUserOnWebapp);\n}",
"async logout() {\n\t\tthis.setToken(null);\n\t}",
"function logout() {\n token = null;\n localStorage.removeItem('userToken');\n }",
"logout(){\n\t\tthis.fetch(`${root}/api/auth/logout`... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
chr1 is current byte chr2 is the next byte to process. looks ahead. | function codesForChar(chr1, chr2, currcs) {
var result = [];
var shifter = -1;
if (charCompatible(chr1, currcs)) {
if (currcs == CODESET.C) {
if (chr2 == -1) {
shifter = SET_CODEB;
currcs = CODESET.B;
}
else if (chr2 != -1 && !charCompatible(chr2, currcs)) {
// need to check ahead as well
if (charCompatible(chr2, CODESET.A)) {
shifter = SET_CODEA;
currcs = CODESET.A;
}
else {
shifter = SET_CODEB;
currcs = CODESET.B;
}
}
}
}
else {
// if there is a next char AND that next char is also not compatible
if (chr2 != -1 && !charCompatible(chr2, currcs)) {
// need to switch code sets
switch (currcs) {
case CODESET.A:
shifter = SET_CODEB;
currcs = CODESET.B;
break;
case CODESET.B:
shifter = SET_CODEA;
currcs = CODESET.A;
break;
}
}
else {
// no need to shift code sets, a temporary SHIFT will suffice
shifter = SET_SHIFT;
}
}
// ok some type of shift is nessecary
if (shifter != -1) {
result.push(shifter);
result.push(codeValue(chr1));
}
else {
if (currcs == CODESET.C) {
// include next as well
result.push(codeValue(chr1, chr2));
}
else {
result.push(codeValue(chr1));
}
}
barc.currcs = currcs;
return result;
} | [
"function consumeSeq2(scanner, ch1, ch2) {\n const { pos } = scanner;\n if (scanner.eat(ch1) && scanner.eat(ch2)) {\n return true;\n }\n scanner.pos = pos;\n return false;\n }",
"function bocu1Decode(buffer, start, end) {\r\n\tvar b, c, t;\r\n\tvar prev, count;\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a key signature, returns the tonic of the major key | function majorTonicFromKeySignature(sig) {
if (typeof sig === "number") {
return transposeFifths("C", sig);
}
else if (typeof sig === "string" && /^b+|#+$/.test(sig)) {
return transposeFifths("C", accToAlt(sig));
}
return null;
} | [
"function majorTonicFromKeySignature(sig) {\n if (typeof sig === \"number\") {\n return (0, _note.transposeFifths)(\"C\", sig);\n } else if (typeof sig === \"string\" && /^b+|#+$/.test(sig)) {\n return (0, _note.transposeFifths)(\"C\", (0, _core.accToAlt)(sig));\n }\n\n return null;\n}",
"function major... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
======== moduleInstances ======== Determines what modules are added as nonstatic submodules | function moduleInstances(inst)
{
let dependencyModule = [];
// Pull in dependency modules
const radioScriptModuleInst = radioScript.moduleInstances(inst);
const securityScriptModuleInst = securityScript.moduleInstances(inst);
const oadScriptModuleInst = oadScript.moduleInstances(inst);
dependencyModule = dependencyModule.concat(radioScriptModuleInst);
dependencyModule = dependencyModule.concat(securityScriptModuleInst);
dependencyModule = dependencyModule.concat(oadScriptModuleInst);
// Pull module for ti_154stack_config.h generation
if(inst.project !== "coprocessor")
{
dependencyModule.push({
name: "ti154stackModule",
moduleName: "/ti/ti154stack/ti154stack_config_mod.js"
});
}
return(dependencyModule);
} | [
"function modules(inst)\n{\n const dependencyModule = [];\n\n // Pull in static dependency modules\n dependencyModule.push({\n name: \"multiStack\",\n displayName: \"Multi-Stack Validation\",\n moduleName: \"/ti/common/multi_stack_validate\",\n hidden: true\n });\n\n depen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the first route to the map | setupRoute(route) {
this.mapRoutes.push(new MapRoute(route));
} | [
"function initMap() {\n if ($(\"#map\").length) {\n var route = $(\"#map\").data(\"route\");\n var center = route[route.length / 2];\n var trail_head = route[0];\n\n var map = new google.maps.Map(document.getElementById('map'), {\n zoom: 13,\n center: center,\n mapTypeId: google.maps.Map... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move text position to previous paragraph inside table | moveToPreviousParagraphInTable(selection) {
let previousParagraph;
let currentPara = this.currentWidget.paragraph;
if (currentPara.isInsideTable) {
previousParagraph = selection.getPreviousSelectionCell(currentPara.associatedCell);
}
else {
previousParagraph = selection.getPreviousParagraphBlock(currentPara);
}
if (isNullOrUndefined(previousParagraph)) {
return;
}
this.currentWidget = previousParagraph.childWidgets[previousParagraph.childWidgets.length - 1];
this.offset = this.currentWidget.getEndOffset() + 1;
} | [
"moveToNextParagraphInTable() {\n let paragraph = this.currentWidget.paragraph;\n let nextParagraph = (paragraph.isInsideTable) ? this.selection.getNextSelectionCell(paragraph.associatedCell) :\n this.selection.getNextParagraphBlock(paragraph);\n if (isNullOrUndefined(nextParagraph))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pops up tooltip that gives the user a custom message for 2 seconds input:Bootstrap tooltip element The message you want to display in the tooltip | function newPopupMsg(element, msg) {
$.when($(element).attr('data-original-title', msg))
.then($(element).tooltip('show'))
.then(window.setTimeout(function () {
$(element).tooltip('hide');
}, 2000));
} | [
"function updateTooltipMessage(message) {\n // Update the tooltip for the next time it mouses in/out\n tooltipMessage = message;\n}",
"function makeTooltip(element, message) {\n $(element).tooltipster({\n content: message,\n })\n}",
"function flashTooltip(el, text) {\n var prevText = $(el).attr(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
a helper function to arrang the days of each week in a month // | function arrangDays(month, day) {
//-------------------------------------------------------------------------------//
//------------------------------------- Week One --------------------------------//
//-------------------------------------------------------------------------------//
if (day >= 1 && day <= 7) {
//-------------------- cheks if jan contains a prorities----------------------//
if (month.hasOwnProperty('Week1')) {
month.Week1.tatal += 1;
//------------------------- week 1 and have a value for thisday then add 1
month.Week1.days[day - 1] += 1;
}
}
//-------------------------------------------------------------------------------//
//------------------------------------- Week tow --------------------------------//
//-------------------------------------------------------------------------------//
if (day > 7 && day <= 14) {
//-------------------- cheks if jan contains a prorities----------------------//
if (month.hasOwnProperty('Week2')) {
month.Week2.tatal += 1;
//------------------------- week 2 and have a value for thisday then add 1
month.Week2.days[day - 8] += 1;
}
}
//---------------------------------------------------------------------------------//
//------------------------------------- Week three --------------------------------//
//---------------------------------------------------------------------------------//
if (day > 14 && day <= 22) {
//-------------------- cheks if jan contains a prorities-------------------------//
if (month.hasOwnProperty('Week3')) {
month.Week2.tatal += 1;
//------------------------- week 3 and have a value for thisday then add 1
month.Week3.days[day - 15] += 1;
}
}
//---------------------------------------------------------------------------------//
//------------------------------------- Week three --------------------------------//
//---------------------------------------------------------------------------------//
if (day > 22 && day <= 31) {
//-------------------- cheks if jan contains a prorities-------------------------//
if (month.hasOwnProperty('Week4')) {
month.Week2.tatal += 1;
//------------------------- week 4 and have a value for thisday then add 1
month.Week4.days[day - 22] += 1;
//------------------------- week 4 and dose not have this a value for thisday then =1
}
}
} | [
"function days() {\n const week = [];\n for (let i=0; i<=6; i++) {\n const mondayy = new Date(monday());\n week.push({[i]: new Date(mondayy.setDate(mondayy.getDate() + i))})\n }\n}",
"monthdates(year, month, extraWeek = false) {\n let date = new Date(year, month, 1);\n let day... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
lets find all the endpoints for the given context id | function findEndpoints(contextId) {
var answer = [];
var contextFolder = Camel.getCamelContextFolder(workspace, contextId);
if (contextFolder) {
var endpoints = (contextFolder["children"] || []).find(function (n) { return "endpoints" === n.title; });
if (endpoints) {
angular.forEach(endpoints.children, function (endpointFolder) {
var entries = endpointFolder ? endpointFolder.entries : null;
if (entries) {
var endpointPath = entries["name"];
if (endpointPath) {
var name = tidyJmxName(endpointPath);
var link = Camel.linkToBrowseEndpointFullScreen(contextId, endpointPath);
answer.push({
contextId: contextId,
path: endpointPath,
name: name,
tooltip: "Endpoint",
link: link
});
}
}
});
}
}
return answer;
} | [
"discoverEndpoints() {\n // Get all endpoints folders\n const path = this.settings.endpointsPath;\n const endpoints = this.getPaths(path);\n this.info(`* Discovering Endpoints...(${endpoints.length} founds)`);\n\n endpoints.forEach(endpoint => {\n this.configureEndpoint(path, endpoint);\n });... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
move text position to next paragraph inside table | moveToNextParagraphInTable() {
let paragraph = this.currentWidget.paragraph;
let nextParagraph = (paragraph.isInsideTable) ? this.selection.getNextSelectionCell(paragraph.associatedCell) :
this.selection.getNextParagraphBlock(paragraph);
if (isNullOrUndefined(nextParagraph)) {
return;
}
this.currentWidget = nextParagraph.childWidgets[nextParagraph.childWidgets.length - 1];
this.offset = this.currentWidget.getEndOffset() + 1;
} | [
"moveToPreviousParagraphInTable(selection) {\n let previousParagraph;\n let currentPara = this.currentWidget.paragraph;\n if (currentPara.isInsideTable) {\n previousParagraph = selection.getPreviousSelectionCell(currentPara.associatedCell);\n }\n else {\n pre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns array of Locale objects parsing the gen_list file nlsDir folder containing file "gen_list" | function initLocalesList(nlsDir)
{
var listFileName = nlsDir + "\\gen_list";
if (!fso.FileExists(listFileName))
{
WScript.StdErr.WriteLine("Generate: Fatal error: "
+ "File "+ listFileName + " does not exist");
WScript.Quit(3);
}
var ForReading = 1;
var stream = fso.OpenTextFile(listFileName, ForReading);
if (!stream)
{
WScript.StdErr.WriteLine("Generate: Fatal error: "
+ "Cannot open file "+ listFileName);
WScript.Quit(3);
}
var arrLocales = new Array();
while (!stream.AtEndOfStream)
{
var line = stream.ReadLine();
var name = line.replace(new RegExp("^\([^ ]*\) *\([^ ]*\)"),
"$1\.$2")
.replace(new RegExp("\([^.]*\)\(.euro\)\([^ ]*\)"),
"$1$3@euro")
.replace(new RegExp("\([^.]*\)\(.cyrillic\)\([^ ]*\)"),
"$1$3@cyrillic");
var pos = name.indexOf(" ");
if (0 <= pos)
name = name.substr(0, pos);
var srcname = name.replace(new RegExp("\([^.]*\)\.\([^@]*\)\(.*\)"),
"$1$3")
.replace("@", ".");
var cmname = name.replace(new RegExp("\([^.]*\)\.\([^@]*\)\(.*\)"),
"$2");
arrLocales.push(new Locale(name, cmname, srcname));
}
return arrLocales;
} | [
"function initLocaleList (context) {\n\tcontext._locales = [];\n\tfs.readdirSync(context._directory).forEach(function(file) {\n\t\tif (file.indexOf(context._fileExtension) >= 0) {\n\t\t\tvar localeName = path.basename(file, context._fileExtension);\n\t\t\tcontext._locales.push(localeName);\n\t\t}\n\t});\n}",
"fun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the coordinates of the center for this item. | get center() {
return GeoJsonUtils.getCenter(this.item);
} | [
"function getCenter() {\n var center = {\n x : this.width / 2,\n y : this.height / 2\n };\n return center;\n }",
"get centerX() { return this._x + (this.width / 2); }",
"get center() {\n return new (0, _math.Point)(this.worldScreenWidth / 2 - this.x / this.sc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the number of images in a folder the hard way, assuming that we do not know ahead of time Name your images like img1.png, img2.png etc... Use the fetch API to make http request to the server, returns a promise that can be fulfilled or rejected | function getImages(num, count) {
fetch(`/img/img-${num}.png`)
.then((res) => {
if (res.ok) {
console.log(`The number of images is ${count}`);
arr.push(count);
console.log(arr.length);
console.log(res);
// Display the number of images in the folder in a paragraph
imgTxt.innerHTML = `There are ${count} images in the folder`;
} else throw new Error("There was a problem with getting the image");
})
.catch((err) => console.log(err));
} | [
"function countImages() {\n let files = _listImages()\n return files.length\n}",
"static getCount() {\n\t\treturn db.query('SELECT COUNT(id) FROM images')\n .then(res => {\n return res.rows[0].count;\n });\n }",
"function getFSImageCount() {\n\t\tvar countImages = fs.readdirSync(PATH_IMAGES)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a env variable that is a number | function parseEnvNumber(key) {
const value = Number(process.env[key]);
if (Number.isNaN(value) || value < 0) {
return undefined;
}
return value;
} | [
"function nodeNum() {\n let num = process.env.ELIFE_NODE_NUM\n if(num) {\n num = parseInt(num)\n if(isNaN(num)) {\n showErr(\"Environment variable ELIFE_NODE_NUM is not a valid number\")\n return 0\n }\n } else {\n num = 0\n }\n return num\n}",
"fun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Controller for the custom recipe dialog | function DialogController($scope, $mdDialog, recipe) {
$scope.recipe = recipe;
//Returns an array of the nicely formatted strings of the recipes ingredients
$scope.getStringIngredients = function () {
var results = [];
$scope.recipe.ingredients.forEach(function (ingredient) {
var s = ingredient.quantity + " " + ingredient.name;
s += ingredient.notes.length == 0 ? "" : (" (" + ingredient.notes + ")");
results.push(s);
});
return results;
};
//Formats the specified recipe's courses into a comma separated string
$scope.getCourseList = function () {
var list = ""
for (var i = 0; i < $scope.recipe.courses.length; i++) {
list += $scope.recipe.courses[i];
if (i != ($scope.recipe.courses.length - 1)) {
list += ", ";
}
}
return list;
};
//Formats the specified recipe's cuisines into a comma separated string
$scope.getCuisineList = function () {
var list = ""
for (var i = 0; i < $scope.recipe.cuisines.length; i++) {
list += $scope.recipe.cuisines[i];
if (i != ($scope.recipe.cuisines.length - 1)) {
list += ", ";
}
}
return list;
};
$scope.hide = function () {
$mdDialog.hide();
};
$scope.cancel = function () {
$mdDialog.cancel();
};
} | [
"function handleRecipes()\n{\n requestAndDisplayRecipePreferences();\n\n addNewRecipe();\n\n deleteRecipe();\n\n editRecipe();\n\n}",
"clickedAddRecipe() {\n this.openEditorCallback();\n }",
"function handleRecipeView () {\n recipeDetails.empty();\n console.log('handle view recipe function... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove the info box | function removeInfoBox() {
var info = $('div.info');
if (info.length)
info.remove();
showing_tooltip = false;
} | [
"function clear_info_box() {\n $('#info-contents').html('');\n $('#info-title').text('');\n $('#info-clear-btn').hide();\n $('#goto-source-btn').hide();\n}",
"function hideInformationBox() {\n informationBox.style('display', 'none');\n }",
"clearInfoPane() {\r\n $(\"#info\").html(\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attach a document to an editor. | function attachDoc(cm, doc) {
if (doc.cm) { throw new Error("This document is already in use.") }
cm.doc = doc;
doc.cm = cm;
estimateLineHeights(cm);
loadMode(cm);
setDirectionClass(cm);
cm.options.direction = doc.direction;
if (!cm.options.lineWrapping) { findMaxLine(cm); }
cm.options.mode = doc.modeOption;
regChange(cm);
} | [
"attachEditor(editor) {\n this.editor = editor\n }",
"function attachDoc(cm, doc) {\n\t\t if (doc.cm) throw new Error(\"This document is already in use.\");\n\t\t cm.doc = doc;\n\t\t doc.cm = cm;\n\t\t estimateLineHeights(cm);\n\t\t loadMode(cm);\n\t\t if (!cm.options.lineWrapping) findMaxLi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Init Command Terminate Dialog | function terminateCommand() {
hideAllDialogs();
isIncidentRunning = false;
var t1 = (new Date()).getTime();
var elapsed = parseInt(t1 - t0);
var elapsedSec = parseInt((elapsed / 1000) % 60);
var elapsedMin = parseInt((elapsed / (1000 * 60)) % 60);
var elapsedHr = parseInt((elapsed / (1000 * 60 * 60)) % 60);
var secStr = (elapsedSec < 10) ? ("0" + elapsedSec) : elapsedSec;
var minStr = (elapsedMin < 10) ? ("0" + elapsedMin) : elapsedMin;
var hrStr = (elapsedHr < 10) ? ("0" + elapsedHr) : elapsedHr;
if (elapsedHr > 0) {
$("#cmd_term_label").html("Command terminated at: " + hrStr + ":" + minStr + ":" + secStr);
} else {
$("#cmd_term_label").html("Command terminated at: " + minStr + ":" + secStr);
}
showDialog(0, 0, "#resume_dialog")();
saveCookieState();
archiveCurrentInc();
} | [
"static EndGUI() {}",
"onMnuQuitClick() {\n\t\tapp.quit();\n\t}",
"function createExitDialog() {\n var cancelToolFactory = new OO.ui.ToolFactory();\n var cancelToolGroupFactory = new OO.ui.ToolGroupFactory();\n var cancelToolbar = new OO.ui.Toolbar(cancelToolFactory, cancelToolGroupFactory);\n\n /**... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Special Check for Radio Button,Checkbox,Select | function check_special(Element)
{
if($(Element).is("input:radio"))
{
var Name=$(Element).attr("name");
if($("[name="+Name+"]").attr("required")=="true" || $("[name="+Name+"]").attr("required")=="1")
{
if($(":checked[name="+Name+"]").length==0)
{
var Message="Please select at least {1} options(s).";
display_msg(Element,Message,"required");
return false;
}
else
{
display_msg(Element,'',"required");
return true;
}
}
}
else if($(Element).is("input:checkbox"))
{
var Name=$(Element).attr("name");
var Result;
if($("[name="+Name+"]").attr("minlength")!=-1)
{
if($(":checked[name="+Name+"]").length<$("[name="+Name+"]").attr("minlength"))
{
var Message="Please check at least {"+$("[name="+Name+"]").attr("minlength")+"} options(s).";
display_msg(Element,Message,"minlength");
Result=false;
}
else
{
display_msg(Element,'',"minlength");
Result=true;
}
}
if($("[name="+Name+"]").attr("maxlength")!=-1)
{
if($(":checked[name="+Name+"]").length>$("[name="+Name+"]").attr("maxlength"))
{
Result=false;
}
else
{
Result=true;
}
}
return Result;
}
else if($(Element).is("select"))
{
if($(Element).attr("required")!=null)
{
if($(Element).attr("required")=="true" || $(Element).attr("required")=="1")
{
if($(Element).val().length>0)
{
display_msg(Element,'',"required");
return true;
}
else
{
var Message="Please select the option from select box.";
display_msg(Element,Message,"required");
return false;
}
}
}
}
} | [
"checked(a, b) {\r\n return b.nodeName.toLowerCase() === 'input' && ['checkbox', 'radio'].includes(b.type) && !!b.checked\r\n }",
"function checked(val) {\n\tif (val == 1) {\n\t\treturn ' checked=\"yes\"';\n\t}\n\treturn '';\n}",
"function activer_checkbox()\n{\n /*$('input:checkbox').iCheck({\n c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert json into a Room | static _parse(i, rooms, json, mapParams) {
let room = new Room(
i,
json.x * MIN_SIZE,
json.y * MIN_SIZE,
json.w * MIN_SIZE,
json.h * MIN_SIZE,
mapParams
);
if(json.l) {
room._connect(rooms[i - 1], Corridor._parse(json.l, mapParams));
}
if(json.a) {
room._connect(rooms[i - room._params.size], Corridor._parse(json.a, mapParams));
}
room._rendererName = json.r;
return room;
} | [
"static from(json) {\n let parsedJson;\n if ((typeof json) === \"string\"){\n parsedJson = JSON.parse(json);\n\n } else {\n parsedJson = json;\n }\n return new LessonBean(parsedJson.id, parsedJson.groupId, parsedJson.subjectId, parsedJson.teacherId);\n }"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
10 Guessing Game Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number. If the user input matches with guess number, the program will display a message "Good Work" otherwise display a message "Not matched" HINT: Use Math.ceil() and Math.random() | function guessing_game(guess) {
var num = Math.ceil(Math.random() * 10);
if (guess == num)
alert('Good Work');
else
alert('Not matched, the number was ' + num);
} | [
"function guessing_game(guess) {\n // Get a random integer from 1 to 10 inclusive\n- console.log(\"matched or unmatched?\");\n+ var temp = Math.ceil((Math.random() * 10) + 1);;\n+ if(temp==guess)\n+ {\n+ console.log(\"Suceess you have guessed it right!\");\n+ }",
"function guessNumber(){\nvar programN... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Don't emit readable right away in sync mode, because this can trigger another read() call => stack overflow. This way, it might trigger a nextTick recursion warning, but that's not so bad. | function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}} | [
"_read() {\n this._readingPaused = false;\n setImmediate(this._onReadable.bind(this));\n }",
"_read() {\r\n\t\tthis._readingPaused = false\r\n\t\tsetImmediate(this._onReadable.bind(this))\r\n\t}",
"function modRead() {\n\t\t\t\t\treturn write(read());\n\t\t\t\t}",
"function NodeReadable(tsReadable, opt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows a blank screen with a centered crosshair that will save a webcam snapshot and download all eyetracking data after an elapsed 2.5 sec. | function show_final_crosshair() {
var canvas = document.getElementById("canvas-overlay");
darken_canvas();
draw_fixation_cross(canvas.width * 0.5, canvas.height * 0.5, canvas);
setTimeout(function() {
// functions from calibration_data.js:
save_webcam_frame();
download_csv();
finish_experiment();
}, 2500);
} | [
"function show_webcam_debrief() {\n create_general_instruction(\n \"Almost done!\",\n 'On the next screen, please look at the crosshair in the center. We will ' +\n 'save a photo from your webcam to help us determine how lighting and other ' +\n 'conditions affected the quality of our eye-tracking soft... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Red Hat Bugzilla Reports Controllers | function RedHatBugzillaReportCtrl($scope, bugzillaApi) {
$scope.model = {};
$scope.errorMessage = '';
$scope.successMessage = '';
$scope.createBugzillaReport = createBugzillaReport;
function createBugzillaReport() {
$scope.$broadcast('show-errors-check-validity');
if ($scope.reportForm.$invalid) {
return;
}
bugzillaApi.addBugzilla($scope.model)
.success(function(data) {
$scope.model = {}
$scope.successMessage = 'Report added successfully';
})
.error(function(errorInfo, status) {
$scope.errorMessage = 'An error ocurred: ' + errorInfo.message;
})
}
} | [
"function createBugReport() {\n keylogger(\"click\", \"add\");\n printSomething(keylogArray);\n\n function bugReportAlertUser() {\n alert(\"Bug Report copied to clipboard.\");\n }\n bugReportAlertUser();\n printCommands();\n }",
"function getBugList() {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
newMnemonic will return a string consisting of the mnemonic words for the given entropy. If the provide entropy is invalid, an error will be returned. | newMnemonic(entropy) {
let entropyBitLength = entropy.length * 8;
let checksumBitLength = entropyBitLength / 32
let sentenceLength = (entropyBitLength + checksumBitLength) / 11
let err = validateEntropyBitSize(entropyBitLength)
if (err != null) {
throw err;
}
// Add checksum to entropy
entropy = this.addChecksum(entropy)
// Break entropy up into sentenceLength chunks of 11 bits
// For each word AND mask the rightmost 11 bits and find the word at that index
// Then bitshift entropy 11 bits right and repeat
// Add to the last empty slot so we can work with LSBs instead of MSB
// entropy as an int so we can bitmask without worrying about bytes slices
let entropyInt = new bn(entropy);
// Slice to hold words in
let words = [];
// Throw away big int for AND masking
let word = new bn(0);
for (let i = sentenceLength - 1; i >= 0; i--) {
// Get 11 right most bits and bitshift 11 to the right for next time
word = entropyInt.and(last11BitsMask);
//
entropyInt = entropyInt.div(rightShift11BitsDivider);
// Get the bytes representing the 11 bits as a 2 byte slice
let wordBytes = this.padByteSlice(word.toArray(), 2);
// Convert bytes to an index and add that word to the list
let index = new bn(wordBytes)
words[i] = wordList[index]
}
return words.join(" ");
} | [
"static entropyToMnemonic(entropy) {\r\n if (!Bip39._wordlist) {\r\n Bip39.setWordList(english, \" \");\r\n }\r\n if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {\r\n throw new Error(`The length of the entropy is invalid, it should be a multipl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This calculates the node positions for all the nodes inside of the nodesData | function calculateNodePositions(nodesView, nodesData)
{
nodesView.children().each(function(index, child)
{
var cid = $(child).data('node-cid');
var node = nodesData[cid];
var body = nodesView.closest('body');
// groups have nested nodes inside of them
if (node.binding === 'group')
{
for (var i = 0; i < node.data.length; i++)
{
console.log('here');
var current = node.data[i];
current.position = getCoordinatesForNode(current, body);
}
}
node.position = getCoordinatesForNode(node, body);
node.position.side = getSideForNode(node.position);
});
} | [
"function computeNodePosition(data){\n\t\t\tlet pos = [0,0]; \n\t\t\tif(data.data.name === \"Crimes\"){\t\t\t\t\t\n\t\t\t\treturn pos;\n\t\t\t}\n\t\t\tpos = labelarc.centroid(data);\n\t\t\treturn pos; \n\t\t}",
"async _calcCoordinates(dataNodes) {\n let distScale = scaleLinear().range([... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compiler runtime helper for creating dynamic slots object | function createSlots(slots, dynamicSlots) {
for(let i = 0; i < dynamicSlots.length; i++){
const slot = dynamicSlots[i];
// array of dynamic slot generated by <template v-for="..." #[...]>
if (_shared.isArray(slot)) for(let j = 0; j < slot.length; j++)slots[slot[j].name] = slot[j].fn;
else if (slot) // conditional single slot generated by <template v-if="..." #foo>
slots[slot.name] = slot.fn;
}
return slots;
} | [
"function createSlots(slots,dynamicSlots){for(let i=0;i<dynamicSlots.length;i++){const slot=dynamicSlots[i];// array of dynamic slot generated by <template v-for=\"...\" #[...]>\n\tif(isArray(slot)){for(let j=0;j<slot.length;j++){slots[slot[j].name]=slot[j].fn;}}else if(slot){// conditional single slot generated by... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively convert the BN tree to plain text, with indentation BN = BookmarkNode to "print" to plain text indent = String, leading part before printed string and before tab indented folder contents Returns: a String | function BN_toPlain (BN, indent = "") {
let plain;
let type = BN.type;
if (type == "folder") {
plain = indent+BN.title;
let children = BN.children;
if (children != undefined) {
let len = children.length;
for (let i=0 ; i<len ;i++) {
plain += "\n"+BN_toPlain(children[i], indent + "\t");
}
}
}
else if (type == "bookmark") {
plain = indent+BN.url;
}
else {
plain = indent+"--------------------";
}
return(plain);
} | [
"function formatNode (tree, node, indent) {\n let str = ''\n for (let char in node.children) {\n const childNode = node.children[char]\n let end = tree.right\n if (childNode.end !== undefined) end = childNode.end\n const substr = tree.text.slice(childNode.start, end + 1).join('')\n str += ' '.repea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
total score has to match with random number the computer gave us user wins; if the total score isn't (more than) random number user losses; | function checkWinsLosses() {
if (score === random) {
wins++;
$("#wins").text(wins);
reset();
} else if (score > random) {
losses++;
$("#losses").text(losses);
reset();
}
} | [
"function totalscore(){\n\tif(randomnumber === generatedScore) {\n\t\twin();\n\t\t\n\t\t}\n\telse if (randomnumber < generatedScore) {\n\t\tlose();\n\t\t\n\t\t}\n\n\n\n\t\n\t}",
"function compareScore(){\n \n\n \n // compare random number and totalsccore\n if(randomNum === totalScore){\n w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
INTERNAL typeguard: does not extensively check, if obj is an alternative RecognitionResult, but only if it "could" be a alternitve RecognitionResult | function _isAlternativeRecognitionResult(obj) {
return obj && typeof obj === 'object';
} | [
"function ItalyDlFrontRecognizerResult(nativeResult) {\n RecognizerResult.call(this, nativeResult.resultState);\n \n /** \n * The address of the front side of the Italy Dl owner. \n */\n this.address = nativeResult.address;\n \n /** \n * The date Of Birth of the front side of the Italy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load Mega Menu Posts | function cscoLoadMenuPosts( menuItem ) {
var dataCat = menuItem.children( 'a' ).data( 'cat' ),
dataType = menuItem.children( 'a' ).data( 'type' ),
dataNumberposts = menuItem.children( 'a' ).data( 'numberposts' ),
menuContainer,
postsContainer;
// Containers.
if ( menuItem.hasClass( 'cs-mega-menu-has-category' ) ) {
menuContainer = menuItem;
postsContainer = menuContainer.find( '.cs-mm-posts' );
} else {
menuContainer = menuItem.closest( '.sub-menu' );
postsContainer = menuContainer.find( '.cs-mm-posts[data-cat="' + dataCat + '"]' );
}
// Set Active.
menuContainer.find( '.menu-item, .cs-mm-posts' ).removeClass( 'active-item' );
menuItem.addClass( 'active-item' );
if ( postsContainer ) {
postsContainer.addClass( 'active-item' );
}
// Check Loading.
if ( menuItem.hasClass( 'cs-mm-loading' ) || menuItem.hasClass( 'cs-mm-loaded' ) ) {
return false;
}
// Check Category.
if ( !dataCat || typeof dataCat === 'undefined' ) {
return false;
}
// Check Container.
if ( !postsContainer || typeof postsContainer === 'undefined' ) {
return false;
}
// Create Data.
var data = {
'cat': dataCat,
'type': dataType,
'per_page': dataNumberposts
};
// Get Results.
$.ajax( {
url: csco_mega_menu.rest_url,
type: 'GET',
data: data,
global: false,
async: true,
beforeSend: function() {
menuItem.addClass( 'cs-mm-loading' );
postsContainer.addClass( 'cs-mm-loading' );
},
success: function( res ) {
if ( res.status && 'success' === res.status ) {
// Set the loaded state.
menuItem.addClass( 'cs-mm-loaded' );
postsContainer.addClass( 'cs-mm-loaded' );
// Check if there're any posts.
if ( res.content && res.content.length ) {
$( res.content ).imagesLoaded( function() {
// Append Data.
postsContainer.html( res.content );
} );
}
}
},
complete: function() {
menuItem.removeClass( 'cs-mm-loading' );
postsContainer.removeClass( 'cs-mm-loading' );
}
} );
} | [
"function cscoLoadMenuPosts( menuItem ) {\n\t\tvar dataCat = menuItem.children( 'a' ).data( 'cat' ),\n\t\t\tdataNumberposts = menuItem.children( 'a' ).data( 'numberposts' ),\n\t\t\tloading = false,\n\t\t\tmenuContainer,\n\t\t\tpostsContainer;\n\n\t\t// Containers.\n\t\tif ( menuItem.hasClass( 'csco-mega-menu-catego... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
search function containing results of query to blockstack core node/ app index file | _blockstackSearch(query){
console.log('bssearch');
return null;
} | [
"function luceneIndexSearch() {\n stompClient.send(\"/app/lucene/search\", {});\n}",
"function employeesSearch() {\n connection.query(\"SELECT * FROM employeeTracker_db.employee\",\n function(err, res) {\n if (err) throw err\n console.table(res)\n runSearch()\n })\n}",
"function performSearch(req... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines optimized coordinates for each node in a network | function setCoordinates() {
var grid_size = optimizeToGrid(nodes.length);
//Create 2D array
var coord_array = [];
for (i = 0; i < nodes.length; i++) {
coord_array[i] = [];
var x_coord = (i % grid_size[0]);
var y_coord = (Math.floor(i / grid_size[0]));
coord_array[i][0] = x_coord;
coord_array[i][1] = y_coord;
}
return coord_array;
} | [
"getPossibleWeightLocations() {\r\n\t\t// Update each node's max depth.\r\n\t\tthis.updateDepths();\r\n\t\t\r\n\t\t// Stores all possible new weight locations\r\n\t\tlet posWeights = [];\r\n\t\t\r\n\t\t// Iterate over every node in the network\r\n\t\tfor (let n1 of this.nodes) {\r\n\t\t\t// Iterate over every input... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
================================================================== Take two compositeconstraints and combine them, creating a new composite constraint containing every valid combination of the original methods. | function addConstraints(compA, compB, cgraph) {
// Calculate all the individual constraints going into this multi-constraint
var allcids = u.arraySet.unionKnownDisjoint(compA.cids, compB.cids);
var compC = new CompositeConstraint(allcids);
var compmidsA = compA.getMethodIds();
var compmidsB = compB.getMethodIds();
// Every combination of method from A with method from B
for (var a = compmidsA.length - 1; a >= 0; --a) {
var compmidA = compmidsA[a];
for (var b = compmidsB.length - 1; b >= 0; --b) {
var compmidB = compmidsB[b];
// Calculate all the individual methods which would be combined
var allmids = u.arraySet.unionKnownDisjoint(compA.getPrimitiveIdsForMethod(compmidA), compB.getPrimitiveIdsForMethod(compmidB));
// Make a graph of all the methods
var mgraph = new g.Digraph();
cgraph.variables().forEach(mgraph.addNode, mgraph);
allmids.forEach(function (mid) {
var inputs = cgraph.inputsForMethod(mid);
var outputs = cgraph.outputsForMethod(mid);
mgraph.addNode(mid);
inputs.forEach(mgraph.addEdgeTo(mid));
outputs.forEach(mgraph.addEdgeFrom(mid));
});
// Check the graph to see if this is valid combination
if (isValidCompositeMethod(mgraph, allmids.reduce(u.stringSet.build, {}))) {
compC.addMethod(allmids);
}
}
}
return compC;
} | [
"function mergeConstraints(cons1, cons2) {\n var merged = cons1;\n for (var name in cons2.mandatory) {\n merged.mandatory[name] = cons2.mandatory[name];\n }\n merged.optional.concat(cons2.optional);\n return merged;\n}",
"function CompositeConstraint(cids) {\n // Mapping from ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
updates number of guess | function updateCount(guess) {
count += 1;
$('#count').text(count);
} | [
"increaseGuessCounter() {\n this.guessCount = this.guessCount + 2;\n }",
"function updateGuessCounter() {\n $(\"#guess-counter\").html(getGuessesCount());\n }",
"function updateGuessCount(){\n remainingGuesses--;\n $(\"#remainingGuesses\").text(remainingGuesses);\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all platforms that a project is currently capable of running. | function getSupportedPlatforms(projectRoot, exp) {
const platforms = [];
if (Modules_1.projectHasModule('react-native', projectRoot, exp)) {
platforms.push('ios', 'android');
}
if (Modules_1.projectHasModule('react-native-web', projectRoot, exp)) {
platforms.push('web');
}
return platforms;
} | [
"function platformList() {\n return Object.keys(platforms)\n}",
"function findPlatforms (projectPath) {\n const platforms = Object.keys(PLATFORMS)\n return Promise.all(\n platforms\n // (platform) => Promise<Boolean>\n .map((platform) => exists(getPlatformPath(projectPath, platform)))\n )\n //... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An element that consists of a single, fullwidth image imgone options: 0: image URL | function buildImageOne(options) {
html += `<img src="${options[0]}" class="img-one"
`;
} | [
"function zoto_minimal_image(options) {\n\toptions = merge({\n\t\t'thumb_size': 16\n\t\t}, options || {});\n\tthis.$uber(options);\n\tthis.image = IMG({}); \n\tthis.el = DIV({'class': \"minimal_item\"}, this.image);\n}",
"function ELEMENT_IMAGE$static_(){ThumbnailImage.ELEMENT_IMAGE=( ThumbnailImage.BLOCK.createE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function checkvoucher() retrieves the Voucher value entered by the user. The function checks to make sure that every entry consists of four letters followed by three numbers. The function also checks for commas if multiple Vouchers exist. | function checkvoucher(){
vouc = document.forms["censusform"]["voucher"].value;
if (vouc == null || vouc == "") {
return;
}
regex = /^[a-zA-Z]{4}[,\d{3}]+$/
if (!new RegExp(regex).test(vouc)) {
alert("Please format your entry correctly, for example, \"BTTP179\" or use commas to seperate multiple IDs.");
document.getElementById("voucher").style.border = "2px solid red";
}
else {
document.getElementById("voucher").style.border = "";
}
} | [
"function validateVoucher(ruc, voucher_number) {\n var rows = $(\".total\").parent();\n var voucher_number_detail = [];\n $.each(rows, function(index) {\n if (ruc === $(this).find(\".ruc\").html())\n voucher_number_detail[index] = $(this).find(\".voucher_number\").html... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an instance of the session guard | makeSessionGuard(mapping, config, provider, ctx) {
const { SessionGuard } = require('../Guards/Session');
return new SessionGuard(mapping, config, this.getEmitter(), provider, ctx);
} | [
"getSession() {\n for (const observer of this.observers) {\n if (observer instanceof Session) {\n return observer;\n }\n }\n return undefined;\n }",
"getSession() {\n if (!this.ctx.session) {\n throw new utils_1.Exception('\"@adonisjs/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
filterM :: (Alternative m, Monad m) => (a > Boolean, m a) > m a . . Filters its second argument in accordance with the given predicate. . . This function is derived from [`of`](of), [`chain`](chain), and . [`zero`](zero). . . See also [`filter`](filter). . . ```javascript . > filterM(x => x % 2 == 1, [1, 2, 3]) . [1, 3] . . > filterM(x => x % 2 == 1, Cons(1, Cons(2, Cons(3, Nil)))) . Cons(1, Cons(3, Nil)) . . > filterM(x => x % 2 == 1, Nothing) . Nothing . . > filterM(x => x % 2 == 1, Just(0)) . Nothing . . > filterM(x => x % 2 == 1, Just(1)) . Just(1) . ``` | function filterM(pred, m) {
var M = m.constructor;
var z = zero(M);
return chain(function(x) { return pred(x) ? of(M, x) : z; }, m);
} | [
"function filterM(pred, m) {\n var M = m.constructor;\n var e = empty(M);\n return chain(function(x) { return pred(x) ? of(M, x) : e; }, m);\n }",
"function filter(list, predicateFn) {\n\n}",
"function filter() {}",
"filter(predicateFn){const name=this._constructChainName(\"Filter\");const transform... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the transform transition duration, including the delay, of an element in milliseconds. | function getTransformTransitionDurationInMs(element) {
var computedStyle = getComputedStyle(element);
var transitionedProperties = parseCssPropertyValue(computedStyle, 'transition-property');
var property = transitionedProperties.find(function (prop) {
return prop === 'transform' || prop === 'all';
}); // If there's no transition for `all` or `transform`, we shouldn't do anything.
if (!property) {
return 0;
} // Get the index of the property that we're interested in and match
// it up to the same index in `transition-delay` and `transition-duration`.
var propertyIndex = transitionedProperties.indexOf(property);
var rawDurations = parseCssPropertyValue(computedStyle, 'transition-duration');
var rawDelays = parseCssPropertyValue(computedStyle, 'transition-delay');
return parseCssTimeUnitsToMs(rawDurations[propertyIndex]) + parseCssTimeUnitsToMs(rawDelays[propertyIndex]);
} | [
"function getTransformTransitionDurationInMs(element) {\n const computedStyle = getComputedStyle(element);\n const transitionedProperties = parseCssPropertyValue(computedStyle, 'transition-property');\n const property = transitionedProperties.find(prop => prop === 'transform' || prop === 'all');\n // If... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the index of group with given Id. Returns 1 if not found. | function findGroup(groupId) {
for (var g = 0; g < ctrl.groups.length; g++) {
if (ctrl.groups[g].id === groupId)
return g;
}
return -1;
} | [
"getGroupPosition(id) {\n\n for (var i = 0; i < this.groups.length; i++) {\n\n if (this.groups[i].id == id) {\n\n return i;\n }\n }\n alert('ERROR: Group position not found');\n return;\n }",
"function getOpsGroupI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the given actorName to the set of readyActors. If there are any readyCallbacks attached to that actorName, it will sequentially fire them (regardless of whether any errors are thrown). | function addReadyActor(actorName) {
readyActors.add(actorName);
const callbacks = readyCallbacks.get(actorName);
if (callbacks) {
callbacks.forEach(cb => {
try {
cb();
}
catch (e) {
console.error(e);
}
});
readyCallbacks.set(actorName, new Set());
}
} | [
"async function waitFor(actorName) {\n await new Promise(async (resolve, reject) => {\n let ready = false;\n const callback = () => {\n ready = true;\n resolve();\n };\n onActorReady(actorName, callback);\n await sleep(5000);\n offActorReady(actorNa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
optional wrapper class to use for source if the source object is a complex one. | function SourceWrapper(animatableSourceElement, sourceObjData)
{
this.animatableSourceElement = animatableSourceElement;
this.sourceObjData = sourceObjData;
//this should return the animatable object.
this.getAnimatableElement = function()
{
return this.animatableSourceElement;
};
this.getSourceObjectData = function()
{
return this.sourceObjData;
};
} | [
"static create (source) {\n switch (source.type) {\n case 'TopoJSONTileSource':\n return new TopoJSONTileSource(source);\n case 'MapboxFormatTileSource':\n return new MapboxFormatTileSource(source);\n case 'GeoJSONSource':\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PAYE calculation being 30% of net pay net pay is therefore gross pay less PAYE | function paye() {
var grossPay = 1000000
var perc = 30 / 100
var tax = grossPay * perc
var netPay = grossPay - tax
console.log(netPay)
} | [
"repaymortage() {\n if (this.canrepaymortage()) {\n this.owner.payAmmount((this.pricetopay[0] / 2) * 1.10);\n }\n }",
"function getPaye(grossPay) {\n gp = grossPay; // assign gross pay value to function variable\n paye = 0; // initialise PAYE value\n fl = 235000; // firs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the appearance of the Navbar | function updNav () {
let pos = [
window.pageYOffset,
document.documentElement.scrollTop,
document.body.scrollTop
]
let nav = document.getElementById("navbar");
let themeColor = {
'setting': document.getElementById('theme_color'),
'background': document.getElementById('theme_color_bg').content,
'theme': document.getElementById('theme_color_tm').content
};
if(pos[1] > 0 || pos[2] > 0 || pos[3] > 0) {
nav.setAttribute("data-at-top", false);
themeColor.setting.content = themeColor.theme;
}
else {
nav.setAttribute("data-at-top", true);
themeColor.setting.content = themeColor.background;
}
} | [
"function navbarStyle() {\n\t\tif($(window).scrollTop() > 0) {\n\t\t\t$navbar.removeClass('border-bottom border-info').addClass('bg-dark');\n\t\t} else {\n\t\t\t$navbar.addClass('border-bottom border-info').removeClass('bg-dark');\n\t\t}\n\t}",
"function changeNavBarForAnimation() {\n $('nav').css('background-co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DataCell of ListIt rows. | function DataCell() {
this.data = "";
} | [
"function cells(row) /* (row : row) -> list<cell> */ {\n return row.cells;\n}",
"getRowData(i) {\n return this._dataSource[i];\n }",
"addRows() {\n if (this._data.constructor !== Array)\n throw TypeError('data property of table is not an array');\n\n this._data.forEach((item) => {\n\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls the transfer function on the solidity contract Returns a promise containing the tx receipt of the transfer | transfer(fromNode, toNode, kardId) {
console.log("Transferring kard: (" + kardId + "), from: " + fromNode + ", to: " + toNode);
return this.getAddress(toNode).then((toAddress) => {
return this.getAddress(fromNode).then((fromAddress) => {
return this.getLastBlock(fromNode).then(lastBlock => {
console.log("Transferring kard: (" + kardId + "), from: " + fromAddress + ", to: " + toAddress);
let config = Promise.all(this.getConfig(fromNode));
return config.then( response => {
let web3 = response[0];
let contract = response[1];
// TODO: consider estimating gas for this tx instead of relying on the last block
// This relies on specifying the from address so that the node we're
// talking to can check that it owns the address and sign the tx
console.log("Calling transfer function on solidity contract");
return contract.methods.transfer(toAddress, kardId).send({ from: fromAddress, gas: lastBlock.gasLimit });
});
})
})
});
} | [
"function transfer(){\n\tprompt.get(['to','stake','memo'], (err,result)=>{\n\tif (err){return onErr(err);}\n try{\n (async () => {\n \t\t\tconst resu = await api.transact({\n \t\t\t\tactions:[{\n \t \t\t\t\taccount: 'eosio.token',\n \t \t\t\t\tname: 'transfer',\n \t \t\t\t\tauthorization:[{\n \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load player1 and player2 win to index.htm | function loadStatus() {
document.getElementById("player-1-name").innerHTML = player1.getSymbol() + " won";
document.getElementById("player-1-win").innerHTML = player1win;
document.getElementById("player-2-name").innerHTML = player2.getSymbol() + " won";
document.getElementById("player-2-win").innerHTML = player2win;
} | [
"function playing(){\n\tvar option = \"width=650, height=450, resizeable=no, scrollbars=yes, left=220, top=50\";\t\n\tpopupPlayer = window.open(\"\", \"Player\", option);\n\t\n\t$.get(\"/player/webplayer\", function(){\n\t\tpopupPlayer.location =\"/player/webplayer\";\n\t});\n\t\n}",
"function playGameMulti() {\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
UpdateCharts updates every chart except for the eclude chart with the provided arguments | function UpdateCharts(exclude, args) {
for ([key, value] of Object.entries(args)) {
CurrentFilters[key] = value
}
console.log(CurrentFilters)
// Copy the CurrentFilters because otherwise the chart type
// ends up in the current filters, breaking visualizations
var cf = $.extend(true, {}, CurrentFilters)
// Apply filters on every chart except for the excluded one
ChartList.forEach(chart => {
if (chart.chart != exclude) {
chart.update(cf)
}
});
} | [
"function update_existing_charts() {\n var dataTime = getDataTimes();\n console.log(\"NEW DATE: update_existing_charts: \" + dataTime.starttime + \" to \" +\n\t\tdataTime.endtime);\n var endDate = makeDate(dataTime.endtime);\n var startDate = makeDate(dataTime.starttime);\n // Time zone offset is in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all child nodes where func(child) == true | function getChildNodes(node, func)
{
var rv = [];
for (var i = 0; i < node.childNodes.length; i++)
{
var child = node.childNodes[i];
if (func(child))
rv.push(child);
}
return rv;
} | [
"someChildren(callback) {\n return this.childElements.some(visit);\n function visit(node) {\n if (callback(node)) {\n return true;\n }\n else {\n return node.childElements.some(visit);\n }\n }\n }",
"everyChildren(ca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method blocks some annoying default actions that we prefer not to happen :) | function blockDefaultActions( ) {
resetData( );
var b = document.getElementsByTagName( "body" )[0],
handler = function( e ) {
return Events.cancel( e );
};
Events.attach( b, "selectstart", handler );
Events.attach( b, "dragstart", handler );
} | [
"function tii_stopDefaultAction (event)\n{\n\tevent.returnValue = false;\n\tif (typeof event.preventDefault != 'undefined')\n\t{\n\t\tevent.preventDefault ();\n\t}\n}",
"preventDefault() {\n this._defaultAction = false;\n }",
"function stopDefaultAction(ev) {\r\n\tif (!ev) ev = window.event;\r\n\t(ev.stopPr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
replace common battle info | function replaceBattleInfo(obj) {
// no allies
obj.innerHTML=obj.innerHTML.replace(/(no allies)/g,"无同盟");
//12 allies
obj.innerHTML=obj.innerHTML.replace(/(\d*)( allies)/g,"$1 同盟");
//Resistance war
obj.innerHTML=obj.innerHTML.replace(/(Resistance war)/g,"起义战斗");
//Subsidies:
obj.innerHTML=obj.innerHTML.replace(/(Subsidies:)/g,"赏金:");
// //: none
// allElements.innerHTML=allElements.innerHTML.replace(/(: none)/g,":无");
// //: 0.02 USD for 1.000 dmg
// allElements.innerHTML=allElements.innerHTML.replace(/(: )([0-9.]+) (\w*)( for )/g,":$2 $3" 每);
} | [
"function replaceBattleInfo(obj) {\r\n // no allies \r\n obj.innerHTML=obj.innerHTML.replace(/(no allies)/g,\"Pas d'alliés\");\r\n //12 allies\r\n obj.innerHTML=obj.innerHTML.replace(/(\\d*)( allies)/g,\"$1 alliés\");\r\n //Resistance war\r\n obj.innerHTML=obj.innerHTML.re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the global element definition and merges each known element with the global, e.g. to assign global attributes. | resolveGlobal() {
/* skip if there is no global elements */
if (!this.elements["*"])
return;
/* fetch and remove the global element, it should not be resolvable by
* itself */
const global = this.elements["*"];
delete this.elements["*"];
/* hack: unset default properties which global should not override */
delete global.tagName;
delete global.void;
/* merge elements */
for (const [tagName, entry] of Object.entries(this.elements)) {
this.elements[tagName] = this.mergeElement(global, entry);
}
} | [
"function cacheGlobalElements() {\n\n // Create a tag to element map.\n cache.globalElements = new Map()\n\n // getElements() is new so don't assume its there.\n if (endPointTransceiver.serverSupports(\"getElements\")) {\n\n return endPointTransceiver.getElements(\"?globals=true\").then(\n results => re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Highlight marker by changing marker picture | function highlightMarker(marker) {
isHighlighted = true;
var image = {
url: 'img/marker.png',
origin: new google.maps.Point(0, 0),
scaledSize: new google.maps.Size(50, 50)
};
marker.setIcon(image);
} | [
"function highlightMarkers(e){\n var layer = e.target;\n var iconElem = L.DomUtil.get(layer._icon);\n iconElem.style.border=\"4px #00ffff solid\";\n iconElem.style.height=\"38px\";\n iconElem.style.width=\"38px\";\n iconElem.style.marginTop=\"-19px\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refresh Data clears the table and reset everything | function refreshData(){
$('#abHeader').nextAll().remove(); // clears table rows
$('#abErrorsLog ul').empty(); // clears errors log
refreshCycle = 0; // reset refresh cycle control
itemIds = [];
itemSince = null;
loadData();
} | [
"function resetData(){\n tbody.text(\"\")\n loadTable()\n }",
"function resetAndRefillTable(){\n resetDatabase();\n dynamicTableFillUp();\n}",
"function resetData() {\n\n // Prevent the page from refreshing\n d3.event.preventDefault();\n \n // Clear the displayed data\n tbody.html(\"\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We've defined a function countOnline which accepts one argument (a users object). Use a for...in statement within this function to loop through the users object passed into the function and return the number of users whose online property is set to true. An example of a users object which could be passed to countOnline is shown below. Each user will have an online property with either a true or false value. | function countOnline(usersObj) {
// Only change code below this line
let count = 0
for (var user in usersObj){
if (usersObj[user].online ==true){
count += 1
}
}
return count
// Only change code above this line
} | [
"function countOnline(usersObj) {\n let result = 0;\n for (let user in usersObj) {\n if (usersObj[user].online === true) {\n result ++;\n }\n }\n return result;\n}",
"function countOnline(usersObj) {\n let count = 0;\n for (let user in usersObj){\n //console.log(usersObj[user][\"online\"]);\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns resolved promise if resume() was called, rejected otherwise. | resumeCalled() {
return new Promise((resolve, reject) => {
this.resume_called_ = resolve;
});
} | [
"_waitResume() {\n return new Promise(resolve => {\n if (!this._paused) resolve();\n\n this._emitter.once('_resume', () => resolve());\n });\n }",
"async resume() {\n return this.queue.resume();\n }",
"function resume (actual, override) {\n if (!this.paused) {\n throw new Error('R... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize Handsontable after the component has mounted. | componentDidMount() {
const newSettings = this.settingsMapper.getSettings(this.props);
this.hotInstance = new Handsontable(document.getElementById(this.id), newSettings);
} | [
"componentDidMount() {\n const newSettings = this.hotSettingsMapper.getSettings(this.props);\n this.hotInstance = new Handsontable(document.getElementById(this.root), newSettings);\n }",
"function init() {\n\t\t\ttableData = null;\n\t\t\tbindEvents();\n\t\t\taddDomEvents();\n\t\t\tconsole.log('table module... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clicking the SafeClick button will mark a random covered cell (for a few seconds) that is safe to click (does not contain a MINE). | function onSafeButtonClicked() {
if (!gSafeButtonClicks || gIsSafeButtonClicked || gIsGodMode || !gGame.isOn) return //no clicka or already active
const availableCells = []
gIsSafeButtonClicked = true
var elCell = null
//random cells
for (var i = 0; i < gLevel.size; i++) {
for (var j = 0; j < gLevel.size; j++) {
var cell = gBoard[i][j]
if (!cell.isMine && !cell.isShown && !cell.isMarked) {
availableCells.push({ pos: { i, j } })
}
}
}
//no cells
if (!availableCells.length) {
gIsSafeButtonClicked = false
return
}
var cell = availableCells[getRandomInt(0, availableCells.length)]
console.log(gBoard[cell.pos.i][cell.pos.j], "safe click")
elCell = document.getElementById(`${cell.pos.i},${cell.pos.j}`)
elCell.classList.add("safe")
gSafeButtonClicks--
renderAvailableClicks()
setTimeout(() => {
elCell.classList.remove("safe")
gIsSafeButtonClicked = false
}, 2500);
} | [
"function safeClick() {\n if(!gGame.isOn)return\n if (gSafeAvailable ===0)return\n var safeCells = getSafeCells(gBoard)\n var randIdx = getRandomCell(safeCells)\n var cellI =safeCells[randIdx].i\n var cellJ =safeCells[randIdx].j\n var elCell = document.querySelector(`[data-i=\"${cellI}\"][data-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This one is for the end of the hook, it directly comes after the onHookStart A hook is the same as a 'normal' step, so use the update step | onHookEnd(payload) {
payload.state = payload.error ? payload.state : _constants.PASSED;
return this.updateStepStatus(payload);
} | [
"_addedHook() {}",
"preUpdate() {}",
"calculateUpdates() {\n\t\tthis.stage.step();\n\t}",
"onHookStart(payload) {\n // There is always a scenario, take the last one\n const currentSteps = this.getCurrentScenario().steps;\n payload.state = _constants.PENDING;\n payload.keyword = _utils.default.cont... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new datapoint to the graph | function addDataPoint() {
// add a new data point to the dataset
// var now = vis.moment();
// dataset.add({
// x: now,
// y: y(now / 1000)
// });
// remove all data points which are no longer visible
//var range = graph2d.getWindow();
//var interval = range.end - range.start;
// var oldIds = dataset.getIds({
// filter: function (item) {
// return item.x < range.start - interval;
// }
// });
//dataset.remove(oldIds);
//setTimeout(addDataPoint, DELAY);
} | [
"add(datapoint) {\n\t\tvar d;\n\t\tif (! (datapoint instanceof Datapoint)) {\n\t\t\td = new Datapoint(datapoint);\n\t\t} else {\n\t\t\td = datapoint;\n\t\t}\n\t\tthis.datapoints[d.id] = d;\n\t\tthis.sendNotifications('add', d.id);\n\t}",
"addPoint(point) {\n this.dataset.push(point);\n this.draw();\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that takes a checkerId, finds the king checker that is exactly 24 spaces into the checker list, and places that king checker where the regular checker is. Then it makes the regular checker hidden and the king checker hidden. | function kingAPiece(row, col, checkerId) {
if (!document.getElementById(checkerId).classList.contains("king")) {
var index = findCheckerIndex(checkerId);
document.getElementById(checkerId).style.display = "none";
occupiedArray[row][col] = checkerArray[index + 24];
occupiedArray[row][col].style.display = "initial";
placeChecker(row, col, occupiedArray[row][col].id);
}
} | [
"function check_king_movement(id, k, king) {\n let i = 0 // first check for id+j*k then id-j*k\n while (i < 2) {\n // check for downward id's w.r.t. board\n for (j = id + k; j <= 88; j += k) {\n dot = document.getElementById(\"\" + String(j))\n\n // check if id is available... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert image template function. | function TinyMCE_advanced_getInsertImageTemplate()
{
var template = new Array();
template['file'] = 'image.htm?src={$src}';
template['width'] = 340;
template['height'] = 280;
// Language specific width and height addons
template['width'] += tinyMCE.getLang('lang_insert_image_delta_width', 0);
template['height'] += tinyMCE.getLang('lang_insert_image_delta_height', 0);
return template;
} | [
"function TinyMCE_advimage_getInsertImageTemplate() {\n var template = new Array();\n\n template['file'] = '../../plugins/advimage/image.htm';\n template['width'] = 380;\n template['height'] = 380; \n\n // Language specific width and height addons\n template['width'] += tinyMCE.getLang('lang_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deselects the task focused by the cursor. eslintdisablenextline nounusedvars | function deselect() {
deselectTask(requireCursor());
} | [
"function deselect() {\n var cursor = getCursor();\n if (cursor) {\n deselectTask(cursor);\n } else {\n warn(\"No cursor, so can't deselect.\");\n }\n }",
"function deselectTasks()\n{\n // de-select the currently selected task\n const currentlySelected = document.querySelector(\".task... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
comparar distancias dadas coordenadas del clapp y del show | function cerca (posicion1, posicion2) {
var distancia;
// debugger;
distancia = Math.pow((Math.pow(posicion1.latitud - posicion2.latitud, 2) + Math.pow(posicion1.longitud - posicion2.longitud,2)), 0.5);
console.log(distancia);
return distancia <= distancia_max;
} | [
"function compareCoord(c1, c2) {\n // return c1.equals(c2);\n var dist = c1.distanceTo(c2);\n console.log(\"DISTANCE: \", dist);\n return dist < 50;\n}",
"function compareDistances(one, two, lat, lng) { \n\tvar lat1 = parseFloat(getParkAttribute(one, \"Latitude\"));\n\tvar lng1 = parseFloat(getParkAtt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn a job and array of build numbers into a list of build links. | function buildNumbersToHtml(job, buildNumbers, test) {
var buildCount = builds.count(job);
var pct = buildNumbers.length / builds.count(job);
var out = `Failed in ${Math.round(pct * 100)}% (${buildNumbers.length}/${buildCount}) of builds: <ul>`;
for (let number of buildNumbers) {
out += '\n<li>' + buildToHtml(builds.get(job, number), test);
}
out += '\n</ul>';
return out;
} | [
"linkJobs(appId, jobs) {\n var elems = [];\n for (var i = 0; i < jobs.length; i++) {\n var jobId = jobs[i];\n var elem = (\n <span key={jobId}>\n <Link to={`/apps/${appId}/jobs/${jobId}`}>{jobId}</Link>\n <span>{(i < jobs.length - 1) ? \", \" : \"\"}</span>\n </span>\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function typing_effect_subfunc is a subfunction to be called with test | function typing_effect_subfunc(caption,boxed,end,captionLength) {
audio_cursor.play();
boxed.html(caption.substr(0, captionLength++));
if(captionLength < caption.length+1 ) {
setTimeout(function() {typing_effect_subfunc(caption,boxed,end,captionLength);},100);
//setTimeout('typero(caption,boxed)', 100);
} else if (end==false){
boxed.html(caption+'<br\>');
//captionLength = 0;
//caption = '';
//console.log("was here1");
}
else{
//boxed.html(caption+'<br\>');
//captionLength = 0;
//caption = '';
//console.log("was here2");
}
} | [
"function typingEffect() {\n\n const typedElements = document.querySelectorAll('[data-typed]');\n\n setTyped(typedElements[0], {\n strings: ['Deebov', 'Dilshod', 'Deebov'],\n typeSpeed: 80,\n backSpeed: 20,\n cursorChar: '_',\n startDelay: 0,\n backDelay: 3000,\n loop: true\n });\n\n setTyp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert an alert to a rocket.chat message | _convert_alert(request) {
const alert = request.content.alerts[0];
return {
content: {
channel: this._channel(request),
text: `${alert.annotations.identifier}: ${alert.labels.job} is ${alert.status}`,
attachments: [{
// author_name: alert.labels.instance,
// title: `${alert.labels.alertname}:${alert.labels.service_name}`,
color: this._color(alert.status),
text: `\
*alert name:* ${alert.labels.alertname}
*instance:* ${alert.annotations.identifier}
*severity:* ${alert.labels.severity}
*message:* ${this._get_alert_msg(alert)}
*desc:* ${alert.annotations.description}
`
}]
}
}
} | [
"function formatAlertMsg(tgtWin)\n{\n if ( typeof AlertMsg == \"string\" &&\n AlertMsg == \"updateOK\" ) {\n AlertMsg = msgtext(\"Save_Successful\");\n if ( typeof ahdtop.saveAckMsgNum == \"number\" &&\n ahdtop.saveAckMsgNum > 0 ) {\n if ( typeof ahdtop.saveAckMsgObjectName == \"string\" &... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function handles the creation of the built in XMLHTTP Object. If other browsers need to be supported, just this function needs to be changed. | function CreateXMLHTTP()
{
var returnObject = null;
if (window.ActiveXObject)
{
if (objType != ''){try{returnObject = new ActiveXObject(objType);}catch(x){}}
else
{
try{returnObject = new ActiveXObject('MSXML2.XMLHTTP.4.0'); objType = 'Msxml2.XMLHTTP.4.0';}catch(x){}
if (returnObject == null)
{
try{returnObject = new ActiveXObject('MSXML2.XMLHTTP.3.0'); objType = 'MSXML2.XMLHTTP.3.0';}catch(x){}
}
if (returnObject == null)
{
try{returnObject = new ActiveXObject('MSXML2.XMLHTTP'); objType = 'MSXML2.XMLHTTP';}catch(x){}
}
if (returnObject == null)
{
try{returnObject = new ActiveXObject('Microsoft.XMLHTTP'); objType = 'Microsoft.XMLHTTP';}catch(x){}
}
}
}
else
{
try{returnObject = new XMLHttpRequest();}catch(x){}
}
return returnObject;
} | [
"function createXMLHTTPObject()\n{\n var xmlHttp;\n\n // get the non-IE (non-ActiveX) version of the xml http object\n // if the object hasn't been acquired yet\n if(xmlHttp == null && typeof XMLHttpRequest !== 'undefined')\n {\n xmlHttp = new XMLHttpRequest();\n }\n\n return xmlHttp;\n}",
"fun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Corrects form values due to selected diskType. By default, shows info for selected SAS. | function changeDiskType(diskType) {
initPrices();
initSliders(false);
price.Calculate();
} | [
"function setDSFields() {\n var selectedVal = $(\"#type input:radio:checked\").val();\n $('.generic_input, .relational_input, .introspect_input').hide();\n \n // show appropriate data source type inputs, if needed.\n //\n if (selectedVal == DS_TYPE_GENERIC) {\n $('.generic_input').show();\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs a given query for search results, adds scores to the results and calls the callback with an ordered and limited list of the results. Note that the query must have a column called 'matchingString', which will be used for scoring. Moreover, to work with the jQuery autocomplete, either the query or the callback should: 1. Add a 'data' field. 2. Add a 'value' field. 3. Wrap the results in an objections under the key 'suggestions'. An array of additional bindings can be used, with its parameters starting at $2. | function search(query, searchString, likeSearch, limit, additionalBindings, callback) {
var searchParameter = likeSearch ? '%' + searchString + '%' : searchString;
db.query(query, {
bind: [searchParameter].concat(additionalBindings)
})
.spread(function (results, metadata) {
scoreResults(searchString, 'matchingString', results);
sortResults(results);
limitResults(limit, results);
callback(results);
});
} | [
"function scoreResults(query, searchField, results) {\n results.forEach(function (result) {\n result.score = scoreString(query.toLowerCase(), result[searchField].toLowerCase());\n });\n}",
"execute(callback: (SearchResult[]) => void) {\n this.strategy.search(\n this.term,\n results => {\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a random gene if prop='all', creates one random property otherwise | function create_gene(prop) {
let candle_values = [5, 10, 15, 240];
let properites = {
//here add the indicators and the ranges you want to handle
//in this case my strategy wants to test RSI ranges
demashort: randomExt.integer(30, 10),
demalong: randomExt.integer(60, 20),
treshold: randomExt.float(0.01, 1),
"candleSize": candle_values[randomExt.integer(3, 0)],
};
// console.log(properites);
if (prop === 'all')
return properites;
else {
return properites[prop];
}
} | [
"function getRandomPropertyVal(prop){\n if(prop.vals){\n var index = getRandomNumber(prop.vals.length);\n return prop.vals[index];\n }\n }",
"mutate() {\n let geneToMutate = Math.floor(Math.random() * this.data.length);\n this.data[geneToMutate] = this.createRandomGene();\n }",
"function... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save menu state before each unload so that state is preserved when changing files or when reloading the page. | function persistMenuState() {
let items = document.querySelectorAll('.group-name');
let state = JSON.parse(sessionStorage.getItem(MENU_STATE_KEY));
items.forEach(item => {
let isOpen = item.getAttribute('open');
console.log(isOpen);
state[item.id] = isOpen === '' && true;
});
sessionStorage.setItem(MENU_STATE_KEY, JSON.stringify(state));
} | [
"function saveGlobalState() {\n if (getApp()[stateKey]) {\n // 返回了多层页面时,中间页面也会执行unload,但不能保存state\n return\n }\n getApp()[stateKey] = toJS(globalState)\n}",
"function saveState () {\n var path = window.location.pathname,\n historyRemoves = [];\n\n if (allowSave !== true || !ExtL.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a colormap for display. The following is an example. | function createColormap(label, labels) {
return (label) ?
colormap.create("single", {
size: labels.length,
index: labels.indexOf(label)
}) :
[[255, 255, 255],
[226, 196, 196],
[64, 32, 32]].concat(colormap.create("hsv", {
size: labels.length - 3
}));
} | [
"function colormap(n) {\n var cmap = new Array(n);\n for (i = 0; i < n; i++) {\n cmap[i] = 'hsl(' + i*360/n + \", 75%, 50%)\";\n }\n \n return cmap;\n}",
"function colormap(v) {\n const n = arbre.length / 6;\n const i = Math.min(Math.max(Math.floor(v * arbre.length / 6), 0), n - 1);\n // each bin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[ Header Builder Element Sidebar ] | function HB_Element_Sidebar() {
$( '.hb-sidebar .icon-sidebar' ).click( function() {
// Add class active
$(this).closest( '.hb-sidebar' ).addClass( 'active' );
$( 'html' ).addClass( 'no-scroll' );
} );
$( '.hb-sidebar .content-sidebar > .overlay' ).click( function() {
// Remove class active
$(this).closest( '.hb-sidebar' ).removeClass( 'active' );
$( 'html' ).removeClass( 'no-scroll' );
} );
} | [
"function SidebarHeader({\n sidebarName\n}) {\n const {\n enableComplementaryArea\n } = (0,external_wp_data_namespaceObject.useDispatch)(store);\n\n const openMenuSettings = () => enableComplementaryArea(SIDEBAR_SCOPE, SIDEBAR_MENU);\n\n const openBlockSettings = () => enableComplementaryArea(SIDEBAR_SCOPE,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add reset btn to rootElement as first element. Use bgScript to clear the element List on reset btn click. Only clear the list when elementList is nonnull. | function addResetBtn(rootElement, bgScript) {
let resetBtn = document.createElement("button");
resetBtn.textContent = "Reset";
resetBtn.style.position = "absolute";
resetBtn.style.top = "20px";
resetBtn.style.left = "300px";
resetBtn.style.border = "none";
resetBtn.style.padding = "10px 15px";
resetBtn.style.cursor = "pointer";
resetBtn.style.backgroundColor = "#e4e4e4";
resetBtn.addEventListener("mouseenter", (event) => {
if ( bgScript.elementList().length > 0 ) {
event.target.style.backgroundColor = "#c3c3c3";
} else {
event.target.style.cursor = "default";
}
});
resetBtn.addEventListener("mouseleave", (event) => {
// Set to default state on mouse leave.
event.target.style.backgroundColor = "#e4e4e4";
event.target.style.cursor = "pointer";
});
resetBtn.addEventListener("click", () => {
if ( bgScript.elementList().length > 0 ) {
bgScript.clear();
clearPage( rootElement );
}
});
rootElement.appendChild(resetBtn);
} | [
"function removeResetButton() {\n if (orderedList.childNodes.length === 0) {\n // Get the reset button by id and remove it from the dom\n var removeResetButton = document.getElementById(\"resetButton\");\n captionSection.removeChild(removeResetButton);\n }\n }",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load LCCS and connect a room | function startLCCS(swfName,roomURL, userName, password) {
connectSession = new ConnectSession(swfName);
if (roomURL) {
connectSession.roomURL = roomURL;
}else {
$.error("Please provide a LCCS room URL");
}
var auth = new Object();
if (userName) {
auth.userName = userName;
} else {
$.error("Please provide a userName");
}
if (password) {
auth.password = password;
}
connectSession.authenticator = auth;
connectSession.addEventListener("synchronizationChange",this);
connectSession.login();
} | [
"static load_all() {\n server.log(\"Loading rooms...\", 2);\n\n server.modules.fs.readdirSync(server.settings.data_dir + '/rooms/').forEach(function(file) {\n if (file !== 'room_connections.json') {\n var data = server.modules.fs.readFileSync(server.settings.data_dir +\n '/rooms/' + file,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to decrypt given cipher text and key | function decryptCaesarCipher(input, key){
//variable to hold end result
var result = '';
//parse key to integer
key = parseInt(key);
//bring key down if too large to work with alphabet ASCII characters
while (key > 26){
key /= 2;
key = Math.round(key);
}
//for each letter in ciphertext
for (var i = 0; i < input.length;i++){
//convert to charCode
var tempChar = input.charCodeAt([i]);
//if uppercase letter
if (tempChar >= 97 && tempChar <= 122){
//if wrap around needed for decipher
if(tempChar-key < 97){
tempChar-=key;
tempChar=96-tempChar;
tempChar=122-tempChar;
}else{
tempChar -= key;
}
//if lowercase letter
}else if (tempChar >= 65 && tempChar <= 90){
//if wrap around needed for cipher
if(tempChar-key < 65){
tempChar-=key;
tempChar=64-tempChar;
tempChar=90-tempChar;
}else{
tempChar-=key;
}
}
//convert deciphered charcode into string and add to result
tempChar = String.fromCharCode(tempChar);
result+= tempChar;
}
//return result after deciphered
return result;
} | [
"function decrypt(ciphertext, key) {\r\n return processToStr(ciphertext, key, -1);\r\n}",
"function Decrypt_Text(ciphertext, keystr) {\n if (keystr.length == 0) {\n alert(\"Please specify a key with which to decrypt the message.\");\n return \"\";\n }\n if (ciphertext.length == 0) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies all the saved arguments (from saveArgs) to the startup file so that when the box reboots, the arguments are executed. | function prepareArgsForReboot() {
const deferred = q.defer();
let startupScripts;
let startupCommands;
let startupCommandsChanged;
const STARTUP_DIR = '/config/';
const STARTUP_FILE = `${STARTUP_DIR}startup`;
const REBOOT_SIGNAL = ipc.signalBasePath + signals.REBOOT;
if (!fs.existsSync(STARTUP_DIR)) {
logger.debug('No /config directory. Skipping.');
deferred.resolve();
return deferred.promise;
}
try {
startupCommands = fs.readFileSync(STARTUP_FILE, 'utf8');
} catch (err) {
logger.warn('Error reading starup file.');
deferred.reject(err);
return deferred.promise;
}
try {
startupScripts = fs.readdirSync(REBOOT_SCRIPTS_DIR);
} catch (err) {
logger.warn('Error reading directory with reboot args.');
deferred.reject(err);
return deferred.promise;
}
// Make sure there's a new line at the end in case we add anything
startupCommands += EOL;
// If we just rebooted, make sure the REBOOT signal file is deleted
// so scripts don't think we need to reboot again
if (startupCommands.indexOf(REBOOT_SIGNAL) === -1) {
startupCommandsChanged = true;
startupCommands += `rm -f ${REBOOT_SIGNAL}${EOL}`;
}
startupScripts.forEach((script) => {
const fullPath = REBOOT_SCRIPTS_DIR + script;
if (startupCommands.indexOf(fullPath) === -1) {
startupCommandsChanged = true;
startupCommands += `if [ -f ${fullPath} ]; then${EOL}`;
startupCommands += ` ${fullPath} &${EOL}`;
startupCommands += `fi${EOL}`;
startupCommands += EOL;
}
});
if (startupCommandsChanged) {
try {
fs.writeFileSync(STARTUP_FILE, startupCommands);
} catch (err) {
logger.warn('Failed writing startup file', STARTUP_FILE, err);
}
}
deferred.resolve();
return deferred.promise;
} | [
"static boot() {\n if (this.booted) {\n return;\n }\n this.booted = true;\n Object.defineProperty(this, 'args', { value: [] });\n Object.defineProperty(this, 'flags', { value: [] });\n if (!this.hasOwnProperty('settings')) {\n Object.defineProperty(thi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility function for creating bearer authoriztion Http header (e.g. for use with JWT) | static getBearerAuthHeader(token) {
return { Authorization: 'Bearer ' + token };
} | [
"static getApiAuthHeader() {\n return {'authorization': `bearer ${Auth.getToken()}`};\n }",
"function createAuthHeader(accessToken) {\n var header = new Headers();\n header.append('Authorization', 'Bearer ' + accessToken);\n return header;\n }",
"getAuthorizationHeader() {\n const accessT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(private) constructor with start and end angles in radians. Use explicitly named static methods to clarify intent and units of inputs: createStartEndRadians (startRadians:number, endRadians:number) createStartEndDegrees (startDegrees:number, endDegrees:number) createStartEnd (startAngle:Angle, endAngle:Angle) createStartSweepRadians (startRadians:number, sweepRadians:number) createStartSweepDegrees (startDegrees:number, sweepDegrees:number) createStartSweep (startAngle:Angle, sweepAngle:Angle) | constructor(startRadians = 0, endRadians = 0) { this._radians0 = startRadians; this._radians1 = endRadians; } | [
"static createStartEndRadians(startRadians = 0, endRadians = 2.0 * Math.PI, result) {\n result = result ? result : new AngleSweep();\n result.setStartEndRadians(startRadians, endRadians);\n return result;\n }",
"static createStartEndDegrees(startDegrees = 0, endDegrees = 360, result) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removeSelectedOptions(select_object) Remove all selected options from a list (Thanks to Gene Ninestein) | function removeSelectedOptions(from) {
if (!hasOptions(from)) { return; }
if (from.type=="select-one") {
from.options[from.selectedIndex] = null;
}
else {
for (var i=(from.options.length-1); i>=0; i--) {
var o=from.options[i];
if (o.selected) {
from.options[i] = null;
}
}
}
from.selectedIndex = -1;
} | [
"function removeSelectedOptions(from) { \n\tfor (var i=(from.options.length-1); i>=0; i--) { \n\t\tvar o=from.options[i]; \n\t\tif (o.selected) { \n\t\t\tfrom.options[i] = null; \n\t\t\t} \n\t\t} \n\tfrom.selectedIndex = -1; \n\t}",
"function removeSelectedOptions(from) { \n\tif (!hasOptions(from)) { return; }\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate hashCount indexes, one index per [0, size) it uses the double hashing technique to generate the indexes | function getIndices(element, size, hashCount, seed) {
if (seed === undefined) {
seed = getDefaultSeed();
}
var arr = [];
for (var i = 1; i <= hashCount; i++) {
var hashes = hashTwice(element, true, seed + size % i);
arr.push(doubleHashing(i, hashes.first, hashes.second, size));
}
if (arr.length !== hashCount)
throw new Error('report this, please, shouldnt be of different size');
return arr;
} | [
"getIndexes(element, size, hashCount, seed) {\n if (seed === undefined) {\n seed = getDefaultSeed();\n }\n const arr = [];\n const hashes = this.hashTwice(element, seed);\n for(let i = 0; i < hashCount; i++){\n arr.push(this.doubleHashing(i, hashes.first, has... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
submits the season3 coach file | function submitS3CoachFile(){
coach_file_text = document.getElementById("coachfiletext");
coach_file_text.value = season3coachfile;
submitRCoachFile()
} | [
"function submitS5CoachFile(){\n coach_file_text = document.getElementById(\"coachfiletext\");\n coach_file_text.value = season5coachfile;\n submitRCoachFile()\n}",
"async function submit () {\n const problemFile = fs.readFileSync(CLI.filepath, `utf-8`)\n const ext = path.extname(CLI.filepath)\n const numbe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Created By: Andriy Bovtenko Description: Clones the first row of the schedule table, alters attribute values and appends the modified clone after last row | function AddScheduleRow(scheduleControls, caller) {
//using weekcounter to set id, name attributes and the control's Row property
//this is to maintain unique values beyond removal and re-addition of rows and will produce values beyond the number of actual rows //abovtenko
weekCounter++;
var tBody = $('#' + scheduleControls[0].ID).closest('tbody');
var firstRow = tBody.find('tr:first'); //used as a model
var lastRow = tBody.find('tr:last');
var rowClone = firstRow.clone();
var newScheduleControls = [];
rowClone.attr('id').replace(/\d$/, weekCounter);
rowClone.find('td > input, td > div > input')
.each(function () {
var id = this.id;
var oldObject = scheduleControls.filter(function (control) {
return control.ID == id;
});
var newID = $(this).attr('id') + '-' + weekCounter;
var newName = $(this).attr('name').replace(/\d$/, weekCounter);
$(this).attr('id', newID);
$(this).attr('name', newName);
$(this).val('');
if ($(this).hasClass('date')) {
//will not init without removing class :hasDatepicker
InitializeDatepicker($(this).removeClass('hasDatepicker'));
}
var controlObject = $.extend({}, oldObject[0]);
controlObject.ID = $(this).attr('id');
controlObject.ControlName = $(this).attr('name');
controlObject.Row = weekCounter;
controlObject.Value = '';
newScheduleControls.push(controlObject);
});
rowClone.append($('<td class="remove_button_container"><button class="btn btn-default remove-week">X</button></td>'));
//$('.earning_details_table tbody tr:nth-child(1)').append($('<td></td>'));
//$('.earning_details_table thead tr:last').append($('<th></th>'));
//this check is neccessary for schedule population, since first week values will still be empty
if ($('[name^=WeekStart]:last').data('iso-date') != '') {
var nextStart = new moment($('[name^=WeekStart]:last').data('iso-date'), 'YYYY-MM-DD').subtract(7, 'd');
var nextEnd = new moment(nextStart).add(6, 'd');
var weekStart = rowClone.find('[name^=WeekStart]');
var weekEnd = rowClone.find('[name^=WeekEnd]');
SetIsoDateFormat(weekStart, nextStart._i);
SetIsoDateFormat(weekEnd, nextEnd._i);
}
rowClone.insertAfter(lastRow);
rowClone.find('.date').trigger('change');
UpdateTableRowNumbers(tBody);
if (tBody.find('tr').length == 4)
caller.attr('disabled', 'disabled');
return newScheduleControls;
} | [
"function cloneRow(table) {\n\n //copy last row in table\n var row = angular.copy(table.matrix[table.matrix.length - 1]);\n //set new name for every field in row.\n for (var i = 0; i < row.length; i++) {\n row[i].name = generateName(OdsComponentType.ITEM);\n for (var j ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a gradient function that, when given an integer, returns a hex color string. The defaultFillValue will be given the defaultFill color, different from the linear scale. | function gradientBuilder(defaultFill, fromColor, toColor, step, domain, defaultFillValue = 1) {
// sets start and stop values for linear scale
var start = domain[0] + step,
stop = domain[1];
// builds a linear scale with the domain and colors
var linearColor = d3.scale.linear().domain([start, stop]).range([fromColor, toColor]);
// sets the 'value: color' combination not following the linear scale
var colorDomain = [defaultFillValue],
colorRange = [defaultFill];
for (var i = 0; i < stop; i += step) {
// offsets colors and values by 1 step size
colorDomain.push(i + 2 * step);
colorRange.push(linearColor(i + step));
};
return d3.scale.threshold().domain(colorDomain).range(colorRange);
} | [
"function makeGradientString(l) {\n var spansZero = (l.lowValue > 0 && l.highValue < 0),\n gradientString,\n zeroPercent;\n gradientString = \"0-\" + l.lowColor + \"-\";\n zeroPercent = getZeroLocation(l);\n if (zeroPercent !== \"noZero\") {\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves options to chrome.storage | function save_options() {
chrome.storage.sync.set({
payWallOption: payWallOption.checked,
adRemovalOption: adRemovalOption.checked,
trumpOption: trumpOption.checked,
trumpNameOption: trumpNameOption.value.toLowerCase(),
yoHeaderOption: yoHeaderOption.checked,
yoSuffixOption: yoSuffixOption.value.toLowerCase(),
}, function() {
closeButton.setAttribute('disabled','disabled');
statusSpan.textContent = 'Options saved...';
const currentWindow = window;
setTimeout(function() {
currentWindow.close();
}, 1000);
});
} | [
"function saveOptions(){\n\tchrome.storage.sync.set({ options: options })\n}",
"function saveOptions() {\n var saveObject = {};\n // Loops over all options and adds the current value to the chrome storage.\n for (var i = 0; i < options.length; i++) {\n saveObject[options[i]] = optionsElement(i).pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
= Description Registers or releases event listening for doubleClick events depending on the value of the flag argument. = Parameters +_state+:: Set the doubleClick event listening on/off (true/false) for the component instance. = Returns +self+ | setDoubleClickable(_state) {
this.events.doubleClick = _state;
this.setEvents();
return this;
} | [
"function run_on_double_click(d) {\n clickedOnce = false;\n clearTimeout(timerClickedOnce);\n ConsoleLog(\"doubleclick\");\n dblclick(d);\n }",
"function jsDblClick() {\n if (!clicked) {\n clicked = true;\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search events in the city by keyword | async searchEventsByKeyword(keyword, cityCode) {
const url = 'events/search-extended'
var params = { q: keyword, city: cityCode}
try {
const res = await this.axiosClient.get(url, {params})
return _.map(res.data, r => _.pick(r, ['title', 'uuid']))
}
catch (err) {
console.error(err)
}
} | [
"function eventsByCity(event) {\n getFootprint().then(footprint => {\n cityPayload = {\n city: {\n city: this.options[this.selectedIndex].getAttribute('value'),\n country: 'ca'\n },\n footprint: footprint,\n limit: limit\n }\n\n post(cityPayload).then(response => {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a method that takes the node with the smallest value and moves it to the front of the linked list | moveMinToFront(){
if(this.isEmpty() || this.head.next == null){ // if the list is empty or only 1 element long, then there's nothing to do
return this;
}
let min = this.head; // we'll start by assuming our head is the smallest value
let minPrev = null; // we'll need to keep track of the minimum's previous node
let runner = this.head; // and of course our runner
while(runner.next != null){ // loop through everything
if(runner.next.value < min.value){ // if the next node's value is smaller than the min
min = runner.next; // we'll set the min node to that next node
minPrev = runner; // and the minPrev to the current runner
}
runner = runner.next;
}
if(minPrev == null) { // if minPrev is still null, then the first node is already the smallest node
return this;
}
// otherwise
minPrev.next = min.next; // let's set minPrev's .next to min's .next
min.next = this.head; // set min.next to the head of the list (putting it at the front)
this.head = min; // and assign the head to now be the min node
return this;
} | [
"moveMinToFront() {\n\t\tvar runner = this.head;\n\t\tvar min = this.head.value;\n\t\tvar track_prev = this.head.value;\n\t\tvar min_node = this.head;\n\t\tvar previous = this.head;\n\t\n\t\twhile (runner != null) {\n\t\t\tif (runner.value < min) {\n\t\t\t\tmin = runner.value;\n\t\t\t\tmin_node = runner;\n\t\t\t\tp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The menu for configuring which apps can be fast loaded | function showFastLoadMenu() {
E.showMenu();
E.showAlert(/*LANG*/"WARNING! Only enable fast loading for apps that use widgets.").then(() => {
E.showMenu({
'': {
'title': 'Shortcuts',
'back': showMainMenu
},
'Top first': {
value: config.fastLoad.shortcuts[0],
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.shortcuts[0] = value;
saveSettings();
}
},
'Top second': {
value: config.fastLoad.shortcuts[1],
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.shortcuts[1] = value;
saveSettings();
}
},
'Top third': {
value: config.fastLoad.shortcuts[2],
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.shortcuts[2] = value;
saveSettings();
}
},
'Top fourth': {
value: config.fastLoad.shortcuts[3],
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.shortcuts[3] = value;
saveSettings();
}
},
'Bottom first': {
value: config.fastLoad.shortcuts[4],
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.shortcuts[4] = value;
saveSettings();
}
},
'Bottom second': {
value: config.fastLoad.shortcuts[5],
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.shortcuts[5] = value;
saveSettings();
}
},
'Bottom third': {
value: config.fastLoad.shortcuts[6],
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.shortcuts[6] = value;
saveSettings();
}
},
'Bottom fourth': {
value: config.fastLoad.shortcuts[7],
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.shortcuts[7] = value;
saveSettings();
}
},
'Swipe up': {
value: config.fastLoad.swipe.up,
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.swipe.up = value;
saveSettings();
}
},
'Swipe down': {
value: config.fastLoad.swipe.down,
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.swipe.down = value;
saveSettings();
}
},
'Swipe left': {
value: config.fastLoad.swipe.left,
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.swipe.left = value;
saveSettings();
}
},
'Swipe right': {
value: config.fastLoad.swipe.right,
format: value => value ? 'Fast' : 'Slow',
onchange: value => {
config.fastLoad.swipe.right = value;
saveSettings();
}
}
});
})
} | [
"function showShortcutMenu() {\n //Builds the shortcut options\n let shortcutOptions = [\n { name: 'Nothing', val: false },\n { name: 'Launcher', val: '#LAUNCHER' },\n ];\n\n let infoFiles = storage.list(/\\.info$/).sort((a, b) => {\n if (a.name < b.name)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to return Time Difference Replacement to IRD Function Name: "TimeDifference" Return value type: INTEGER. The returned value is the result of subtracting First Time from Second Time. First Time and Second Time are thought of as moments specified in milliseconds. If First Time is greater than Second Time, it is presumed that Second Time occurs on the day following First Time, therefore 24 hours (86,400,000 milliseconds) are added to Second Time before the subtraction. | function irdTimeDifference(firstTime,secondTime)
{
var endResult = 0;
if(firstTime!= null && secondTime!=null){
endResult = secondTime - firstTime;
if(firstTime>secondTime){
endResult = endResult + 86400000;
}
}
return endResult;
} | [
"function timeDiff(time1, time2) {\n return DMath.fixHour(time2- time1);\n}",
"function GetTimeDifference(time1, time2) {\n\n var clockDifference = 0;\n\n var startTime = time1.split(\" \");\n var endTime = time2.split(\" \");\n\n if (startTime[1] != endTime[1]) clockDifference += 12;\n\n var st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |