query stringlengths 9 34k | document stringlengths 8 5.39M | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
This is the placePicker function that does all the work! | function placePicker (whoComes, howMuch, whatDo) {
//This is the big honkin' array that houses the choices
var choiceList = [
{
"placeName": "Broad St Diner",
"numPeople": "me",
"pricePoint": "low",
"activityType": "dinner"
},
{
"placeName": "Midtown III",
"numPeople": "me",
"pricePoint": "low",
"activityType": "dinner"
},
{
"placeName": "Oregon Diner",
"numPeople": "me",
"pricePoint": "low",
"activityType": "dinner"
},
{
"placeName": "Teri's",
"numPeople": "we",
"pricePoint": "low",
"activityType": "dinner"
},
{
"placeName": "Silk City",
"numPeople": "we",
"pricePoint": "low",
"activityType": "dinner"
},
{
"placeName": "Tom Jones Restaurant",
"numPeople": "we",
"pricePoint": "low",
"activityType": "dinner"
},
{
"placeName": "South Street Diner",
"numPeople": "us",
"pricePoint": "low",
"activityType": "dinner"
},
{
"placeName": "Melrose Diner",
"numPeople": "us",
"pricePoint": "low",
"activityType": "dinner"
},
{
"placeName": "West Chester Diner",
"numPeople": "us",
"pricePoint": "low",
"activityType": "dinner"
},
{
"placeName": "Penrose Diner",
"numPeople": "me",
"pricePoint": "mid",
"activityType": "dinner"
},
{
"placeName": "Darling's Diner",
"numPeople": "me",
"pricePoint": "mid",
"activityType": "dinner"
},
{
"placeName": "Aki",
"numPeople": "me",
"pricePoint": "mid",
"activityType": "dinner"
},
{
"placeName": "The Continental",
"numPeople": "we",
"pricePoint": "mid",
"activityType": "dinner"
},
{
"placeName": "The Cantina",
"numPeople": "we",
"pricePoint": "mid",
"activityType": "dinner"
},
{
"placeName": "El Rey",
"numPeople": "we",
"pricePoint": "mid",
"activityType": "dinner"
},
{
"placeName": "SideCar",
"numPeople": "us",
"pricePoint": "mid",
"activityType": "dinner"
},
{
"placeName": "Trolley Car Cafe",
"numPeople": "us",
"pricePoint": "mid",
"activityType": "dinner"
},
{
"placeName": "Marathon",
"numPeople": "us",
"pricePoint": "mid",
"activityType": "dinner"
},
{
"placeName": "Morimoto",
"numPeople": "me",
"pricePoint": "high",
"activityType": "dinner"
},
{
"placeName": "Parc",
"numPeople": "me",
"pricePoint": "high",
"activityType": "dinner"
},
{
"placeName": "Fork",
"numPeople": "me",
"pricePoint": "high",
"activityType": "dinner"
},
{
"placeName": "Le Bec Fin",
"numPeople": "we",
"pricePoint": "high",
"activityType": "dinner"
},
{
"placeName": "LaCroix",
"numPeople": "we",
"pricePoint": "high",
"activityType": "dinner"
},
{
"placeName": "Los Catrines Tequilas",
"numPeople": "we",
"pricePoint": "high",
"activityType": "dinner"
},
{
"placeName": "Koo Zee Doo",
"numPeople": "us",
"pricePoint": "high",
"activityType": "dinner"
},
{
"placeName": "Chima Brazilian Steakhouse",
"numPeople": "us",
"pricePoint": "high",
"activityType": "dinner"
},
{
"placeName": "Butcher and Singer",
"numPeople": "us",
"pricePoint": "high",
"activityType": "dinner"
},
{
"placeName": "El Bar",
"numPeople": "me",
"pricePoint": "low",
"activityType": "drinks"
},
{
"placeName": "Locust Bar",
"numPeople": "me",
"pricePoint": "low",
"activityType": "drinks"
},
{
"placeName": "The Druid's Keep",
"numPeople": "me",
"pricePoint": "low",
"activityType": "drinks"
},
{
"placeName": "The Dive Bar",
"numPeople": "we",
"pricePoint": "low",
"activityType": "drinks"
},
{
"placeName": "McGillin's",
"numPeople": "we",
"pricePoint": "low",
"activityType": "drinks"
},
{
"placeName": "Paddy's",
"numPeople": "we",
"pricePoint": "low",
"activityType": "drinks"
},
{
"placeName": "Kung Fu Necktie",
"numPeople": "us",
"pricePoint": "low",
"activityType": "drinks"
},
{
"placeName": "Tattoed Mom",
"numPeople": "us",
"pricePoint": "low",
"activityType": "drinks"
},
{
"placeName": "JR's South Philly",
"numPeople": "us",
"pricePoint": "low",
"activityType": "drinks"
},
{
"placeName": "Graffiti Bar",
"numPeople": "me",
"pricePoint": "mid",
"activityType": "drinks"
},
{
"placeName": "Eulogy",
"numPeople": "me",
"pricePoint": "mid",
"activityType": "drinks"
},
{
"placeName": "Fergie's",
"numPeople": "me",
"pricePoint": "mid",
"activityType": "drinks"
},
{
"placeName": "Tria",
"numPeople": "we",
"pricePoint": "mid",
"activityType": "drinks"
},
{
"placeName": "National Mechanics",
"numPeople": "we",
"pricePoint": "mid",
"activityType": "drinks"
},
{
"placeName": "P.O.P.E.",
"numPeople": "we",
"pricePoint": "mid",
"activityType": "drinks"
},
{
"placeName": "Prohibition",
"numPeople": "us",
"pricePoint": "mid",
"activityType": "drinks"
},
{
"placeName": "Monk's",
"numPeople": "us",
"pricePoint": "mid",
"activityType": "drinks"
},
{
"placeName": "Good Dog",
"numPeople": "us",
"pricePoint": "mid",
"activityType": "drinks"
},
{
"placeName": "Emmanuelle",
"numPeople": "me",
"pricePoint": "high",
"activityType": "drinks"
},
{
"placeName": "Jamonera",
"numPeople": "me",
"pricePoint": "high",
"activityType": "drinks"
},
{
"placeName": "Tinto",
"numPeople": "me",
"pricePoint": "high",
"activityType": "drinks"
},
{
"placeName": "The Ranstead Room",
"numPeople": "we",
"pricePoint": "high",
"activityType": "drinks"
},
{
"placeName": "Bar Ferdinand",
"numPeople": "we",
"pricePoint": "high",
"activityType": "drinks"
},
{
"placeName": "XIX",
"numPeople": "we",
"pricePoint": "high",
"activityType": "drinks"
},
{
"placeName": "Voltage Cafe",
"numPeople": "us",
"pricePoint": "high",
"activityType": "drinks"
},
{
"placeName": "Xochitl",
"numPeople": "us",
"pricePoint": "high",
"activityType": "drinks"
},
{
"placeName": "Cuba Libre",
"numPeople": "us",
"pricePoint": "high",
"activityType": "drinks"
},
{
"placeName": "Union Transfer",
"numPeople": "me",
"pricePoint": "low",
"activityType": "activity"
},
{
"placeName": "Johnny Brenda's",
"numPeople": "me",
"pricePoint": "low",
"activityType": "activity"
},
{
"placeName": "The Rusty Nail",
"numPeople": "me",
"pricePoint": "low",
"activityType": "activity"
},
{
"placeName": "Magic Gardens",
"numPeople": "we",
"pricePoint": "low",
"activityType": "activity"
},
{
"placeName": "Philly Improv Theater",
"numPeople": "we",
"pricePoint": "low",
"activityType": "activity"
},
{
"placeName": "ComedySportz",
"numPeople": "we",
"pricePoint": "low",
"activityType": "activity"
},
{
"placeName": "The Legendary Dobbs",
"numPeople": "us",
"pricePoint": "low",
"activityType": "activity"
},
{
"placeName": "Danger Danger",
"numPeople": "us",
"pricePoint": "low",
"activityType": "activity"
},
{
"placeName": "The Grape Room",
"numPeople": "us",
"pricePoint": "low",
"activityType": "activity"
},
{
"placeName": "The Tin Angel",
"numPeople": "me",
"pricePoint": "mid",
"activityType": "activity"
},
{
"placeName": "The Troc",
"numPeople": "me",
"pricePoint": "mid",
"activityType": "activity"
},
{
"placeName": "Ritz Bourse",
"numPeople": "me",
"pricePoint": "mid",
"activityType": "activity"
},
{
"placeName": "Lucky Strike",
"numPeople": "we",
"pricePoint": "mid",
"activityType": "activity"
},
{
"placeName": "World Cafe Live",
"numPeople": "we",
"pricePoint": "mid",
"activityType": "activity"
},
{
"placeName": "Club Polaris",
"numPeople": "we",
"pricePoint": "mid",
"activityType": "activity"
},
{
"placeName": "Shampoo/Nocturne",
"numPeople": "us",
"pricePoint": "mid",
"activityType": "activity"
},
{
"placeName": "North Bowl",
"numPeople": "us",
"pricePoint": "mid",
"activityType": "activity"
},
{
"placeName": "Barcade",
"numPeople": "us",
"pricePoint": "mid",
"activityType": "activity"
},
{
"placeName": "The Actor's Center",
"numPeople": "me",
"pricePoint": "high",
"activityType": "activity"
},
{
"placeName": "Tower Theatre",
"numPeople": "me",
"pricePoint": "high",
"activityType": "activity"
},
{
"placeName": "Stay Home and Burn Money",
"numPeople": "me",
"pricePoint": "high",
"activityType": "activity"
},
{
"placeName": "Rumor",
"numPeople": "we",
"pricePoint": "high",
"activityType": "activity"
},
{
"placeName": "Kimmel Center",
"numPeople": "we",
"pricePoint": "high",
"activityType": "activity"
},
{
"placeName": "Opera Philadelphia",
"numPeople": "we",
"pricePoint": "high",
"activityType": "activity"
},
{
"placeName": "Skirmish Paintball",
"numPeople": "us",
"pricePoint": "high",
"activityType": "activity"
},
{
"placeName": "Laser Pink Floyd",
"numPeople": "us",
"pricePoint": "high",
"activityType": "activity"
},
{
"placeName": "Get in the Van! We're going to Burning Man!",
"numPeople": "us",
"pricePoint": "high",
"activityType": "activity"
}
];
//This is the area that choices get pushed to
//This is also what resets the array, because it lives inside the function
var deciderArray = [];
//This is how for loops work
var i = 0;
for (i=0; i < choiceList.length; i++) {
//This takes the passed variables and passes them through this big fat equation
if ((choiceList[i].numPeople == whoComes) && (choiceList[i].pricePoint == howMuch) && (choiceList[i].activityType == whatDo)) {
//This is the array that gets populated by the previous equation
deciderArray.push(choiceList[i].placeName);
}
}
//console.log(deciderArray);
//This randomizes your decisions for you
var decision = deciderArray[Math.floor(Math.random() * deciderArray.length)];
//This returns your decision!
//console.log(decision);
$("<p>" + decision + "</p>").appendTo("#decisionDiv");
} | [
"function handleEditPlace() {\n\t$('main').on('click','.edit-place-button', function(event) {\n\t\tconst placeId = $(this).data('id');\n\t\tconst tripId = $(this).data('trip');\n\t\tshowPlaceDetailsToEdit(tripId, placeId);\n\t})\n}",
"function autoCompleteForPickupLocation(element){\r\t\tvar inputPickupLocation =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns true if the given tiles are neighbors | function isNeighbors(tile1, tile2) {
var left1 = parseInt(window.getComputedStyle(tile1).left);
var top1 = parseInt(window.getComputedStyle(tile1).top);
var left2 = parseInt(window.getComputedStyle(tile2).left);
var top2 = parseInt(window.getComputedStyle(tile2).top);
if (Math.abs(left1 + top1 - left2 - top2) == 100) {
return true;
} else {
return false;
}
} | [
"isNeighbor(tile1, tile2) {\n if (tile1 == tile2) { return false; } //a tile cannot be a neighbor to itself\n if (tile1.y == tile2.y && tile1.x == tile2.x-1) { return this.NEIGHBOR_RIGHT; }\n if (tile1.y == tile2.y && tile1.x == tile2.x+1) { return this.NEIGHBOR_LEFT; }\n\n let odd = til... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stores debugging data for this property binding on first template pass. This enables features like DebugElement.properties. | function savePropertyDebugData(tNode, lView, propName, tData, nativeOnly) {
var lastBindingIndex = lView[BINDING_INDEX] - 1;
// Bind/interpolation functions save binding metadata in the last binding index,
// but leave the property name blank. If the interpolation delimiter is at the 0
// index, we know that this is our first pass and the property name still needs to
// be set.
var bindingMetadata = tData[lastBindingIndex];
if (bindingMetadata[0] == INTERPOLATION_DELIMITER) {
tData[lastBindingIndex] = propName + bindingMetadata;
// We don't want to store indices for host bindings because they are stored in a
// different part of LView (the expando section).
if (!nativeOnly) {
if (tNode.propertyMetadataStartIndex == -1) {
tNode.propertyMetadataStartIndex = lastBindingIndex;
}
tNode.propertyMetadataEndIndex = lastBindingIndex + 1;
}
}
} | [
"getPropertyDetail() {\n return {\n propertyData: PropertyDataStore.currentPropertyDetail\n };\n }",
"function init() {\n angular.forEach(railsBindings, function(value, key) {\n railsData[key] = toResource(value);\n });\n }",
"track() {\n const snapShot = () => {\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An exception class to be instantiated when a provided index is out of bounds | function IndexOutOfBoundsException(index){
this.value = index;
this.message = 'is out of bounds.';
this.toString = function(){
return this.value + ' ' + this.message;
};
} | [
"function checkIndex(inputs, index) {\n if (!isValidIndex(inputs, index))\n throw new Error(`Expected an array index < ${inputs.length}, got ${index}`);\n}",
"function offsetShouldThrowOnInvalidElement() {\n expect(() => {\n element.offset(\"invalid\")\n }).toThrow(\n new TypeError(\"Invalid ele... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Actual update of content. Doesn't fade out old content because that's done in the displayNextPerson function which then calls this in a callback from that fadeOut method | function displayUpdate() {
var person = peopleArray[index];
var newXposition = Math.random() * (document.documentElement.clientWidth - 360);
var newYposition = Math.random() * (document.documentElement.clientHeight - 300);
$content = $('.container').add('#speechArrow');
$($content).hide();
$('.container').html("<p class=\"shoutout\">\"" + person.shoutout + "\"</p><p class=\"name\"> -- " + person.name + "</p>");
$('.container').css('left', newXposition);
$('.container').css('top', newYposition);
$('#speechArrow').css('left', newXposition + 40);
$('#speechArrow').css('top', newYposition - 0);
$($content).fadeIn({
queue: false
});
} | [
"function displayNextPerson(next) {\n // console.log('displayNextPerson called with index', index);\n\n if (next) { // update index to next person in the array\n // if we're at the end of the array, loop back around to the front\n if (index == peopleArray.length - 1) {\n index = 0;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the profiler row | getProfilerRow(request) {
return this.application.profiler.create('http:request', {
request_id: request.id(),
url: request.url(),
method: request.method(),
});
} | [
"get row() {\n return INDEX2ROW(getTop()) + 1;\n }",
"function row(numRow) {\n return numRow * ROW + ROW_OFFSET;\n}",
"profilerData() {\n return {\n type: this.relation.type,\n model: this.relation.model.name,\n pivotTable: this.relation.pivotTable,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read programmed reminder info | function handleReadRoutineReminderInfo() {
// Payload base
var localBasePayload = fbBasePayload;
var senderID = getSenderID();
var reminderURL = routine;
return admin.database().ref('pazienti/' + senderID + '/promemoria/routine/').once('value').then((snapshot) => {
let reminders = snapshot.val();
console.log('snapshot.val() : ' + JSON.stringify(reminders));
if(reminders !== null) {
let i;
let elements = [];
for (i=0; i < reminders.length; i++) {
let thDescription = snapshot.child(i.toString() + '/descrizione').val();
let thRipetizione = snapshot.child(i.toString() + '/ripetizione').val();
let thTime = function () {
let time = snapshot.child(i.toString() + '/orario').val();
return time.slice(11, 13);
};
let giorni = snapshot.child(i.toString() + '/giorni').val();
let title = thDescription + ': ' + thRipetizione + ' volte a settimana';
let subtitle = 'Giorni: ' + giorni + '\n' + 'Alle ore ' + thTime();
elements[i] = element(title, reminderURL, subtitle);
localBasePayload.facebook.attachment.payload.elements[i] = elements[i];
}
agent.add(new Payload('FACEBOOK', localBasePayload, {rawPayload: true, sendAsMessage: true}));
} else {
let question = 'Non mi hai parlato delle tue routine. Vuoi aggiungerle?';
let suggestions = [
"Routine",
'Più tardi',
"No grazie",
"Cancella"
];
setSuggestions(question, suggestions, senderID);
}
});
} | [
"function checkReminder(){\n\tfor (i = 0; i < timesAdvices.length; i++) {\n\t\t\tif (currentTime >= timesAdvices[i] && currentTime >= herinneringsTijd && currentTime < timesAdvices[i+1] && dietAdviceValues[i] == false && herinnering == true) {\n\t\t\t\t\n\t\t\t\tif (dietAdviceNames[i] == advies) {\n\t\t\t\t\t//set ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check current state of TuneGenie player | function checkTuneGeniePlayerState(e) {
if (e === true) {
log('TuneGenie Player is streaming.');
me.start();
return true;
}
log('TuneGenie Player has stopped.');
me.stop();
return false;
} | [
"function is_playing() {\n return player.getPlayerState() == 1;\n}",
"function checkGame(){\n\t\tif(victoryCondition){console.log(\"You Won!\");}else{ console.log(\"You lose!\");}\n\t}",
"checkKingsStatus(player){\n\t\tlet tile = this.boardMatrix[player.figureList.King[0].positionY][player.figureList.King[0]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Alters the query string used by the presentlydisplayed page so that it is suitable for use by the next or previous record in the result set. This will typically be by advancing or reducing the start value of the query, though special considerations apply when the first or last record is reached. | function buildSolrQueryLinkString(direction, querystring, position, total, rows){
var offset = jQuery(document).getUrlParam("start") / 1;
position = position / 1;
total = total / 1;
rows = rows / 1;
var new_offset = offset;
var new_position = position;
if(direction == "next"){
if(position + 1 == total){
new_rows = 2;
}
else{
new_rows = 3;
}
new_position += 1;
if(position != 0) new_offset += 1;
}
else{ // i.e., if direction = "prev"
if(position - 1 == 0){
new_rows = 2;
new_offset = 0;
}
else{
new_offset -= 1;
new_rows = 3;
}
new_position -= 1;
}
var reOffset = new RegExp("start=" + offset);
var reRows = new RegExp("rows=" + rows);
querystring = querystring.replace(reOffset, "start=" + new_offset);
querystring = querystring.replace(reRows, "rows=" + new_rows);
querystring = querystring + "&p=" + new_position;
querystring = querystring + "&t=" + jQuery(document).getUrlParam("t");
querystring = querystring.replace(/[&]?q=\*:\*/, "");
if(jQuery(document).getUrlParam("q") != null && jQuery(document).getUrlParam("q") != ""){
querystring = querystring + "&q=" + jQuery(document).getUrlParam("q");
}
return querystring;
} | [
"function updateQueryString() {\n\tsessionStorage[\"query\"] = \"start=\" + sessionStorage[\"start\"] + \"&end=\" + sessionStorage[\"end\"] + \"&pipeline=\" + sessionStorage[\"pipeline\"] + \"&datacen=\" + sessionStorage[\"datacen\"] + \"&network=\" + sessionStorage[\"network\"] + \"&farm=\" + sessionStorage[\"farm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate random category Six | function randomCategorySix(myCategories) {
let category = myCategories[Math.floor(Math.random() * myCategories.length)];
var element = document.getElementById('game-card-title-5');
element.innerHTML = category.title;
var element = document.getElementById('game-card-description-5');
element.innerHTML = category.description;
document.querySelector('#x-button-5').style = 'display: inline';
} | [
"function randomCategoryFour(myCategories) {\n let category = myCategories[Math.floor(Math.random() * myCategories.length)];\n\n var element = document.getElementById('game-card-title-3');\n element.innerHTML = category.title;\n var element = document.getElementById('game-card-description-3');\n element.innerH... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TASK: copyIcons Copies all of the material design icon resources files | function copyIcons() {
return gulp.src('app/style/icon_font/*.*')
.pipe(getStreamOutput('css', 'icon_font'));
} | [
"function copyiOSIcons(dir) {\n console.log('Copying iOS icons ...');\n let copyPromises = [];\n ['', '_2x', '_3x'].forEach((version) => {\n let imageset = (program.color === 'black')? getIcFilename() : getIcFilename(null, program.color);\n let color = (program.color === 'black')? '': '_white';\n let si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fixValue returns the passed value multiplied by the difficulty setting defined by the currentTab | function fixValue(value) {
var multiplyer;
if (scope.currentTab == 1) {
multiplyer = 1;
}
if (scope.currentTab == 2) {
multiplyer = 1.5;
}
if (scope.currentTab == 3) {
multiplyer = 2;
}
if (scope.currentTab == 4) {
multiplyer = 3;
}
var retval = Math.round(value * multiplyer);
if (retval == 0) {
return null;
}
return retval;
} | [
"function performDifficultyAction(){\r\n\tDifficultyValue++;\r\n\tif (DifficultyValue > DifficultyRightValue){\r\n\t\tDifficultyValue = DifficultyLeftValue;\r\n\t}\t\t\r\n}",
"set speedVariation(value) {}",
"getSettingValue(setting) { return this.settings_().getValue(`limits/${setting}`); }",
"attemptNewValue... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the variables other then the name and department in order to start a new research Check the validty of the name Call the getEstablishments() function of the getEstablishmentsSrv service await for the results before computing the retrieved data | apisCall() {
// Reset the variables other then the name and department in order to start a new research
$scope.view.establishments.tooMuchResults = false;
$scope.view.establishments.searchSuccess = false;
$scope.view.establishments.resultsBeforeFiltering = 0;
$scope.view.establishments.resultsTable = [];
// Call the getEstablishments() function of the getEstablishmentsSrv service
// Use what the stringNormalize() function of the stringFormatingSrv service returns as the establishment's name
EstablishmentSrv.getAllEstablishments($scope.view.establishments.name, $scope.view.establishments.department)
.then(
(response) => {
$scope.view.establishments.tooMuchResults = response.tooMuchResults;
$scope.view.establishments.resultsTable = response.resultsTable;
$scope.view.establishments.resultsBeforeFiltering = response.resultsBeforeFiltering;
$scope.view.establishments.searchSuccess = true;
},
(error) => {
$scope.view.errorMsg = error;
$scope.view.establishments.searchSuccess = true;
$scope.view.establishments.resultsTable = [];
},
);
} | [
"establishmentsSearch() {\n $scope.view.errorMsg = '';\n\n // We check the validity of the name\n if ($scope.nameUnvalidity()) {\n return;\n }\n\n // If the current searched establishment name is the same as the previous searched one\n if ($scope.view.establishment... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles the state when we're currently in the mention's text chars | function stateMentionTextChar(stateMachine, char) {
if (isMentionTextChar(char)) ;
else if (alphaNumericAndMarksRe.test(char)) {
// Char is invalid for a mention text char, not a valid match.
// Note that ascii alphanumeric chars are okay (which are tested
// in the previous 'if' statement, but others are not)
remove(stateMachines, stateMachine);
}
else {
captureMatchIfValidAndRemove(stateMachine);
}
} | [
"function isMentionTextChar(char) {\n return mentionTextCharRe.test(char);\n }",
"function stateHashtagTextChar(stateMachine, char) {\n if (isHashtagTextChar(char)) ;\n else {\n captureMatchIfValidAndRemove(stateMachine);\n }\n }",
"function emoji... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Funcion para calcular la fecha de primer pago de las comisiones sabiendo cuanto segundos tiene un dia, calcularemos los de 90 y se los aplicaremos a la fecha actual. | function fechaPago() {
var fechaActual = new Date();
var dia1 = new Date(2010, 1, 1);
var dia2 = new Date(2010, 1, 2);
var diferenciaDia = ((dia2 - dia1) * 90);
//Laura: tendrás que sumar los milisegundos de 90 días, no se puede mezclar fechas con números
var fechaPago = new Date(diferenciaDia - fechaActual);
//Laura: el formato es DD/MM/YYYY
alert("Fecha de primer pago de comisiones: \n" + fechaPago.toLocaleDateString());
} | [
"function fecha() {\n var a = new Date(2001, 2, 1);//valor1 para calcular el paso de 90 dias\n var b = new Date(2001, 4, 30);//valor2 para calcular el paso de 90 dias \n var x = a.getTime();//valor1 en tiempo transcurrido desde la epoca de unix\n var y = b.getTime();//valor2 en tiempo transcurrido desde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return K8s descriptor representation. | toDescriptor() {
return {
apiVersion: 'v1',
kind: 'Secret',
metadata: this.metadata,
data: Object.entries(this.data).reduce((hash, entry) => {
const [ key, value ] = entry;
if (value !== undefined) hash[key] = toBase64(value);
return hash;
}, {})
};
} | [
"function cfnAnomalyDetectorJsonFormatDescriptorPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAnomalyDetector_JsonFormatDescriptorPropertyValidator(properties).assertSuccess();\n return {\n Charset: cdk.stringToCloudFormation(prop... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the classname from the id of the link | function getClassFromId( startId ) {
console.log( '...startId', startId );
var arr = startId.split( '-' );
arr.pop();
var startClass = arr.join( '-' );
console.log( '...startClass', startClass );
return startClass;
} | [
"function ajax_getClassName( element ) {\r\n if (ie4 && browser != \"Opera\" && ! ie8)\r\n return (element.getAttribute(\"className\"));\r\n else return (element.getAttribute(\"class\"));\r\n}",
"function CLASS_SELECTOR(className)\n{\n return \".\" + className;\n}",
"function getClassByLearnerId(i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set active state for a bullet | function setActiveBulletClass() {
for (var i = 0; i < bullets.length; i++) {
if (slides[i].style['transform'] == 'translateX(0px)') {
bullets[i].classList.add('active');
}
}
} | [
"function removeActiveBulletClass() {\n for (var i = 0; i < bullets.length; i++) {\n bullets[i].classList.remove('active');\n }\n }",
"function updateBullets() {\n\t\tif (bullet.isActive) {\n\t\t\tbullet.vx += Math.cos(toRadians(bullet.angle)) * bullet.speed;\n\t\t\tbullet.vy += Math.sin(toRadians(bul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set async content into component's container and emits the current event. | function setAsyncContent(event) {
that._content.innerHTML = event.response;
/**
* Event emitted when the content change.
* @event ch.Content#contentchange
* @private
*/
that.emit('_contentchange');
/**
* Event emitted if the content is loaded successfully.
* @event ch.Content#contentdone
* @ignore
*/
/**
* Event emitted when the content is loading.
* @event ch.Content#contentwaiting
* @example
* // Subscribe to "contentwaiting" event.
* component.on('contentwaiting', function (event) {
* // Some code here!
* });
*/
/**
* Event emitted if the content isn't loaded successfully.
* @event ch.Content#contenterror
* @example
* // Subscribe to "contenterror" event.
* component.on('contenterror', function (event) {
* // Some code here!
* });
*/
that.emit('content' + event.status, event);
} | [
"async onBegin() {\n\t}",
"contentChanged(prev, next) {\n if (this.proxy instanceof HTMLOptionElement) {\n this.proxy.textContent = this.textContent;\n }\n this.$emit(\"contentchange\", null, { bubbles: true });\n }",
"registerEvents() {\n\t\t\tthis.container = this.getContain... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
addNextWord() Add next word to be displayed | function addNextWord() {
let words = controller.words.split(", "),
nextWord = words[controller.currentWordIndex]
// Create Points
pnts = createPoints(nextWord)
// Add Word
drawingLetters = new Letter(nextWord, pnts)
if (words.length - 1 > controller.currentWordIndex) {
controller.currentWordIndex++
} else {
controller.currentWordIndex = 0
}
} | [
"function nextWord() {\n\n //Agrega la siguiente palabra en un string, seguido por un espacio\n text.text = text.text.concat(line[wordIndex] + \" \");\n\n //Avanza el indice de la palabra\n wordIndex++;\n\n //Si es la ultima palabra...\n if (wordIndex === line.length)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the z component of the cross product between vectors BC and BA. | function crossProductZ( pointA, pointB, pointC)
{
var bX = pointB.x;
var bY = pointB.y;
return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));
} | [
"function getZ(x, y) {\n // We assume that the plane equation is up-to-date\n // with the current polygon.\n return -(A * x + B * y + D) / C;\n }",
"static Cross(left, right) {\n const result = Vector3.Zero();\n Vector3.CrossToRef(left, right, result);\n return r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The following scenario will help understanding why links are needed. Component A has a dependency B. (for instance, in a.js there is a require statement to 'b.js'). While importing component A, it knows about the B dependency and it saves it under 'dependencies' directory of A. The problem is that the above require is broken, because 'b.js' is not in the same place where it was originally. This function solves this issue by creating the 'b.js' file in the original location and points to the new location under 'dependencies' of A. It does the link generation in two steps. step 1: "componentsLinks", it generates links to all imported components. target: imported components. source: dependencies. step 2: "dependenciesLinks", it generates links to all dependencies of the imported components. target: dependencies. source: other dependencies. this step is not needed when the imported components don't have dependencies, or when the dependencies were installed as npm/yarn packages. | function getComponentsDependenciesLinks(
componentDependencies: ComponentWithDependencies[],
consumer: ?Consumer,
createNpmLinkFiles: boolean,
bitMap: BitMap
): DataToPersist {
const componentsDependenciesLinks = new DataToPersist();
const linkedComponents = new BitIds();
const componentsToLink = getComponentsToLink();
addLinksForComponents();
addLinksForDependencies();
return componentsDependenciesLinks;
function getComponentsToLink(): ComponentWithDependencies[] {
return componentDependencies.reduce((acc, componentWithDeps) => {
const component = componentWithDeps.component;
const componentMap = bitMap.getComponent(component.id);
component.componentMap = componentMap;
if (componentMap.origin === COMPONENT_ORIGINS.AUTHORED) {
logger.debug(
`writeComponentsDependenciesLinks, ignoring a component ${component.id.toString()} as it is an author component`
);
return acc;
}
return acc.concat(componentWithDeps);
}, []);
}
function addLinksForComponents() {
componentsToLink.forEach((componentWithDeps: ComponentWithDependencies) => {
const component = componentWithDeps.component;
if (linkedComponents.has(component.id)) return;
// it must be IMPORTED. We don't pass NESTED to this function
logger.debug(`writeComponentsDependenciesLinks, generating links for ${component.id.toString()}`);
const componentsLinks = getComponentLinks({
consumer,
component,
dependencies: componentWithDeps.allDependencies,
createNpmLinkFiles,
bitMap
});
componentsDependenciesLinks.merge(componentsLinks);
linkedComponents.push(component.id);
});
}
function addLinksForDependencies() {
componentsToLink.forEach((componentWithDeps: ComponentWithDependencies) => {
if (!componentWithDeps.component.dependenciesSavedAsComponents) return;
componentWithDeps.allDependencies.forEach((dep: Component) => {
if (linkedComponents.has(dep.id)) return;
// We pass here the componentWithDeps.dependencies again because it contains the full dependencies objects
// also the indirect ones
// The dep.dependencies contain only an id and relativePaths and not the full object
const dependencies = componentWithDeps.allDependencies;
dependencies.push(componentWithDeps.component);
const dependencyLinks = getComponentLinks({
consumer,
component: dep,
dependencies,
createNpmLinkFiles,
bitMap
});
componentsDependenciesLinks.merge(dependencyLinks);
linkedComponents.push(dep.id);
});
});
}
} | [
"function getComponentLinks({\n consumer,\n component,\n dependencies,\n createNpmLinkFiles,\n bitMap\n}: {\n consumer: ?Consumer,\n component: Component,\n dependencies: Component[], // Array of the dependencies components (the full component) - used to generate a dist link (with the correct extension)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves all root components associated with a DOM element, directive or component instance. Root components are those which have been bootstrapped by Angular. | function getRootComponents(elementOrDir) {
return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(getRootContext(elementOrDir).components);
} | [
"getProvidedComponents() {\n const registeredExternalComponents = this.getRegisteredExternalComponents();\n const providedComponents = [];\n registeredExternalComponents.forEach((appExternalComponents) => {\n Array.from(appExternalComponents.values()).forEach((externalComponent) => {... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get url and retuen an array of names thet also have the urls type | async function getType(url) {
const response = await axios.get(url);
const data = await response;
const namesByTypeArr = [];
for (let pokemon of data.data.pokemon) {
namesByTypeArr.push(pokemon.pokemon.name);
}
buildNameList(namesByTypeArr);
} | [
"getUrl (name) {\n name = name.name ? name.name : name\n return this.urls[name]\n }",
"function getUrlReferences(References) {\n return References ? References.filter(ref => ref.startsWith(\"http\")).map(ref => ({type: \"URL\", value: ref})) : [];\n}",
"function anchor_type_list()\n{\n var anchor_type_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an arbitrarily long ray, starting at the player position, through the specified angle. Check if this ray intersets any walls. If it does, return the point at which it intersects the closest wall. Otherwise, return the point at which it intersects the edge of the stage. | function checkRayIntersection(ctx, angle) {
// Create a ray from the light to a point on the circle
var ray = new Phaser.Line(globals.player.x, globals.player.y,
globals.player.x + Math.cos(angle) * 1000,
globals.player.y + Math.sin(angle) * 1000);
// Check if the ray intersected any walls
var intersect = ctx.getWallIntersection(ray, walls);
// Save the intersection or the end of the ray
if (intersect) {
return intersect;
} else {
return ray.end;
}
} | [
"function checkClosestWall(ctx, angle, closestWall) {\n // Create a ray from the light to a point on the circle\n var ray = new Phaser.Line(globals.player.x, globals.player.y,\n globals.player.x + Math.cos(angle) * 1000,\n globals.player.y + Math.sin(angle) * 1000);\n // C... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ask the user a question, repeat until all presidents have been asked about | function askQuestion() {
inquirer.prompt([
{
type: "input",
message: questionArray[count].partial,
name: "answer"
}
]).then(function(resp) {
// The answer was correct
if (resp.answer.toLowerCase() === questionArray[count].cloze.toLowerCase()) {
console.log("Correct");
score++; // Increase score
}
// The answer was incorrect
else {
console.log("Incorrect");
console.log("The correct answer was " + questionArray[count].cloze)
}
count++;
// If there are more presidents left, ask another question
if (count < questionArray.length) {
askQuestion();
}
// Otherwise the game is over, display final score
else {
console.log("Quiz over. You got " + score + "/" + questionArray.length + " correct.");
}
})
} | [
"function promptAnotherAction() {\n inquirer.prompt([\n // Prompt user for yes or no\n {\n type: \"confirm\",\n message: \"Would you like to perform another action?\",\n name: \"anotherAction\",\n },\n ]).then(function (inquirerResponse) {\n // If y... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switch between displaying help and data, updating button to match. | function toggle_info() {
toggle_button = document.getElementById("dialogue_toggle");
if(toggle_button.innerHTML=="Show Help"){
show_help();
toggle_button.innerHTML = "Show Data";
} else {
toggle_button.innerHTML = "Show Help";
build_data();
}
} | [
"function toggleHelp () {\n if (domClass.contains(\"helpUnderlay\", \"help-isVisible\")) {\n closeHelp();\n } else {\n openHelp();\n }\n }",
"function processHelpState() {\n oresult.bhelp = true;\n bok = true;\n sstate = '';\n }",
"function t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Class to manage map chunks. Chunks (at this time) are 50 squares tall by 50 squares wide. Whenever a new chunk is generated that is a neighbor of another existing chunk, it will generate boimepoints for all shared edges, so the map is more seamless | constructor(chunkxpos, chunkypos) {
if(typeof chunklist[chunkypos] === 'undefined') {
console.log('Generating 1d array...');
chunklist = [];
chunklist[chunkypos] = [];
}
if(typeof chunklist[chunkypos][chunkxpos] === 'undefined') {
console.log('Generating 2d array...');
chunklist[chunkypos] = [];
}
chunklist[chunkypos][chunkxpos] = this;
this.map = [];
for(let y=0; y<chunksize; y++) {
this.map[y] = [];
for(let x=0; x<chunksize; x++) {
this.map[y][x] = new maptile(this, x, y);
} }
this.biomepoints = [];
// Now check to see if there are any neighboring chunks to use for generating biomepoints
// start with the top direction
if((typeof chunklist[chunkypos-1] != 'undefined') && (typeof chunklist[chunkypos-1][chunkxpos] != 'undefined')) {
// At this point, we can assume that chunklist[y-1][x] is another mapchunk. Run across its bottom edge and generate new biomepoints
console.log('New chunk has a northern neighbor');
let sourcechunk = chunklist[chunkypos-1][chunkxpos];
let lastcolormatch = -1;
let lastpoint = 0;
for(let x=0; x<chunksize; x++) {
if(sourcechunk.map[chunksize][x].tile == lastcolormatch) {
lastpoint.stretchcount++; // Same color as last square. Expand that point's range
}else{
if(lastpoint!=0) { // Finished with this biomepoint - but we need to wrap that one up.
lastpoint.x = Math.floor(lastpoint.stretchcount/2);
lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}];
}
lastpoint = new biomepoint(this, x, 0, sourcechunk.map[chunksize][x].tile);
this.biomepoints.push(lastpoint);
lastpoint.stretchcount = 1;
lastcolormatch = lastpoint.c;
}
}
// We will also need to adjust the last new biomepoint
lastpoint.x = Math.floor(lastpoint.stretchcount/2);
lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}];
}
// now do the bottom direction
if((typeof chunklist[chunkypos+1] != 'undefined') && (typeof chunklist[chunkypos+1][chunkxpos] != 'undefined')) {
console.log('New chunk has a southern neighbor');
let sourcechunk = chunklist[chunkypos+1][chunkxpos];
let lastcolormatch = -1;
let lastpoint = 0;
for(let x=0; x<chunksize; x++) {
if(sourcechunk.map[0][x].tile == lastcolormatch) {
lastpoint.stretchcount++;
}else{
if(lastpoint!=0) { // adjust the last point
lastpoint.x = Math.floor(lastpoint.stretchcount/2);
lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}];
}
lastpoint = new biomepoint(this, x, chunksize, sourcechunk.map[0][x].tile);
this.biomepoints.push(lastpoint);
lastpoint.stretchcount = 1;
lastcolormatch = lastpoint.c;
}
}
lastpoint.x = Math.floor(lastpoint.stretchcount/2);
lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}];
}
// left side... we can assume that chunklist[chunkypos] already exists
if(typeof chunklist[chunkypos][chunkxpos-1] != 'undefined') {
console.log('New chunk has a western neighbor');
let sourcechunk = chunklist[chunkypos][chunkxpos-1];
let lastcolormatch = -1;
let lastpoint = 0;
for(let y=0; y<chunksize; y++) {
if(sourcechunk.map[y][chunksize].tile == lastcolormatch) {
lastpoint.stretchcount++;
}else{
if(lastpoint!=0) {
lastpoint.y = Math.floor(lastpoint.stretchcount/2);
lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}];
}
lastpoint = new biomepoint(this, 0, y, sourcechunk.map[y][chunksize].tile);
this.biomepoints.push(lastpoint);
lastpoint.stretchcount = 1;
lastcolormatch = lastpoint.c;
}
}
lastpoint.y = Math.floor(lastpoint.stretchcount/2);
lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}];
}
// right side
if(typeof chunklist[chunkypos][chunkxpos+1] != 'undefined') {
console.log('New chunk has an eastern neighbor');
let sourcechunk = chunklist[chunkypos][chunkxpos+1];
let lastcolormatch = -1;
let lastpoint = 0;
for(let y=0; y<chunksize; y++) {
if(sourcechunk.map[y][0].tile == lastcolormatch) {
lastpoint.stretchcount++;
}else{
if(lastpoint!=0) {
lastpoint.y = Math.floor(lastpoint.stretchcount/2);
lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}];
}
lastpoint = new biomepoint(this, chunksize, y, sourcechunk.map[y][0].tile);
this.biomepoints.push(lastpoint);
lastpoint.stretchcount = 1;
lastcolormatch = lastpoint.c;
}
}
lastpoint.y = Math.floor(lastpoint.stretchcount/2);
lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}];
}
// With all the sides considered, we can now generate points for inside the chunk
let count = Math.floor(chunksize * chunksize / mapkinddensity);
console.log('We have '+ count +' new points to generate');
for(let i=0; i<count; i++) {
this.biomepoints.push(new biomepoint(this, Math.floor(Math.random()*(chunksize-2))+1, Math.floor(Math.random()*(chunksize-2))+1, Math.floor(Math.random()*4)+1));
}
// With all our biomepoints generated, we can start filling in our area, until they are all finished.
while(this.biomepoints.length>0) {
for(let i=0; i<this.biomepoints.length; i++) {
//console.log('Processing point '+ i +" of "+ this.biomepoints.length);
//console.log(this.biomepoints[i].x);
if(this.biomepoints[i].advance()==0) {
this.biomepoints.splice(i, 1); // This one has no work left. Remove it
i--; // Also, back up the iterator, so we will still see the next one in line
}
}
}
} | [
"function BlockMap(gameMapWidth, gameMapHeight, blockSize) {\n if (gameMapWidth === undefined || gameMapHeight === undefined || blockSize === undefined)\n throw new Error('Invalid dimensions for block map');\n\n Object.defineProperties(this,\n {gameMapWidth: MiscUtils.makeConstantDescriptor(gameMapW... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Records headings and keywords inside rendered page into this.headings and this.keywords respectively | collectHeadingsAndKeywords(pageContent) {
this.collectHeadingsAndKeywordsInContent(pageContent, null, false, []);
} | [
"collectHeadingsAndKeywords() {\n const $ = cheerio.load(fs.readFileSync(this.pageConfig.resultPath));\n this.collectHeadingsAndKeywordsInContent($(`#${CONTENT_WRAPPER_ID}`).html(), null, false, []);\n }",
"collectHeadTags() {\n let tags = {};\n let currentHandlerInfos = this.router.targetState.route... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a worker to solve an instance using one metaheuristic | _createWorker(text) {
if (typeof Worker === "undefined") {
this.view.log("Sorry, your browser does not support workers.");
return;
}
var self = this;
this.view.log("Executing algorithm...");
this.webWorker = new Worker("js/GAPSolverWorker.js?v=2");
this.webWorker.postMessage(text);
this.webWorker.postMessage(this.algorithm);
this.webWorker.onmessage = function (event) {
self.solution = event.data;
Object.setPrototypeOf(self.solution, GAPSolution.prototype);
Object.setPrototypeOf(self.solution.getInstance(), GAPInstance.prototype);
self.computing = false;
if (self.solution.isFeasible()) {
self.view.log("Done: solution has cost " + self.solution.getCost());
self.view.log(self.solution);
self._updateViewButtons(self.view, false, true);
} else {
self.view.log("Sorry, could not find a feasible solution!");
self._updateViewButtons(self.view, false, false);
}
};
} | [
"addWorker(){\r\n if(this.workerPool.length<FATUS_MAX_WORKER){\r\n let worker = new FatusWorker(this);\r\n this.initWorker(worker);\r\n this.workerPool.push(worker);\r\n console.log(MODULE_NAME + ': new worker created %s',worker.name);\r\n worker.run();\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns the correction mode on and off. | function setCorrectionMode(correctionModeOn) {
scoreBoard.correctionModeOn = correctionModeOn;
} | [
"deactivateSpellchecker () {\n this.enabled = false\n this.isProviderAvailable = false\n ipcRenderer.invoke('mt::spellchecker-set-enabled', false)\n }",
"function toggleHints(){\r\n\tif (GameStateScript.HintsOn()){\r\n\t\tGameStateScript.setHints(false);\r\n\t}else{\r\n\t\tGameStateScript.setHints(true)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates database entry and moves the old file into the archive. | function updateDbEntryAndMove(sFileNameOld, sFileNameNew, fCallback) {
// update database entry
var sSql = esc("UPDATE datasets SET file_name = %Q WHERE file_name = %Q;",
sFileNameNew, sFileNameOld);
postgres.query(sSql, function(oErr, oResult) {
if(oErr) {fCallback(oErr);}
// move old file to the archive
fs.rename(
path.join(config.app.dataset_root_path, sFileNameOld),
path.join(config.app.dataset_root_path, "A", sFileNameOld),
function(oErr) {
if(oErr) {fCalllback(oErr);}
fCallback();
});
});
} | [
"function updateFileData(data) {\n if (data.field === 'name') {\n data.newObj.path = uploadPath + data.newObj.name + data.file.extension;\n dbSrvc.update(fileCollection, data);\n renameFileToSystem(data.file.path, data.newObj.path);\n } else {\n dbSrvc.updat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the prefab being used by this pool. | function GetPrefab() : GameObject {
return prefab;
} | [
"function getPool(name='_default'){\n // pool exists ?\n if (name in _pools){\n return _pools[name];\n }else{\n throw new Error('Unknown pool <' + name + '> requested');\n }\n}",
"function getParticleFromPool() {\n for (var i = 0, l = particles.length; i < l; i++) {\n if (!particles[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cancels an edit operation, blanking out all input values found in editItem, then switching its display w/ dispItem. Uses cbTbl for traversing the DOM | function cancelEditOp(editItem, dispItem, opt_setid) {
switchItem2(editItem, dispItem);
var editwrapper = document.getElementById(editItem);
var inputElems = cbTbl.findNodes(editwrapper,
function (node) {
return node.nodeName.toLowerCase() == 'input' &&
(!node.type || node.type.toLowerCase() != 'hidden') &&
node.value;
});
for (var i = 0; i < inputElems.length; ++i) {
var inputElem = inputElems[i];
var newVal = '';
if (inputElem.id) {
var origElem = document.getElementById(inputElem.id + '.orig');
newVal = (origElem && origElem.value) ? origElem.value : newVal;
}
inputElems[i].value = newVal;
}
set_isset(false, opt_setid);
} | [
"function cancelEdit() {\n var currentBurger = $(this).data(\"burger\");\n if (currentBurger) {\n $(this).children().hide();\n $(this).children(\"input.edit\").val(currentBurger.text);\n $(this).children(\"span\").show();\n $(this).children(\"button\").show();\n }\n }",
"function can... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates days based on seconds. | function calculateDays(seconds) {
return Math.floor(seconds / 3600 / 24);
} | [
"function getDaysPassed() {\n const oneDayInMilliseconds = 24*60*60*1000; // hours*minutes*seconds*milliseconds\n let firstDateUTC = lastSyncDateInGolfIslandTime;\n let currentDate = new Date();\n let diffDays = Math.floor(Math.abs((firstDateUTC.getTime() - currentDate.getTime())/(oneDayInMilliseconds))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the Bixi JSON string retrieved and parses it to place the Bixi pins on the map | function LoadBixiePins(data) {
$.each(data.stationBeanList, function(index, value) {
var pin = generatePinTemplate(value, "Bixie");
pin.extras = value;
Microsoft.Maps.Events.addHandler(pin, 'click', displayBixieModal);
map.entities.push(pin);
});
} | [
"loadFromJSON (digimonObject) {\n\t\t//let digimonObject = JSON.parse(digimonJSON);\n\n\t\tfor (let property in digimonObject) {\n\t\t\tthis[property] = digimonObject[property];\n\t\t}\n\t\t\n\t\tDigimonData.extraMovementDiscount(this.qualityFlags['movementDiscount'], this.stageIndex >= ChampionIndex);\n\n\t\t/*if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update or create the current fund in infos | async upsertFundInInfos(fund) {
const name = 'cgpFund';
const info = await infosDAL.findByName(name);
if (info) {
await infosDAL.update(info.id, {
value: fund,
});
} else {
await infosDAL.create({
name,
value: fund,
});
}
} | [
"static dynamicIncomeUpdate() {\n let storedIncome = Storage.getIncome()\n let storedExpenses = Storage.getExpenses()\n const incomes = storedIncome\n const expenses = storedExpenses;\n\n updateUI.updateTransaction(incomes, expenses)\n }",
"function updateUiData(info){\n con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function gonna return fave in this shape : id > user_id that you're faving fullname > photo > added_at > you_fave > boolean | define if you're faving this profile | function faves({ _doc: {created_at, from: { _id, profile }}}) {
return {
id: _id,
fullname: profile.fullname,
photo: profile.photo,
added_at: created_at,
}
} | [
"static filterApptUserData(user) {\n return {\n name: user.name,\n email: user.email,\n phone: user.phone,\n uid: user.uid,\n id: user.id,\n photo: user.photo,\n type: user.type,\n };\n }",
"function showOtherUser(){\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load image previews for all uploads. | loadPreviews () {
this.files.map(file => {
if (!file.previewData && window && window.FileReader && /^image\//.test(file.file.type)) {
const reader = new FileReader()
reader.onload = e => Object.assign(file, { previewData: e.target.result })
reader.readAsDataURL(file.file)
}
})
} | [
"function initPreviews()\r\n {\r\n // remove all previous events\r\n removeEventHandlers();\r\n\r\n // attach click events\r\n var $prev = $qtip.find(\".ilPreviewTooltipPrev\");\r\n var $next = $qtip.find(\".ilPreviewTooltipNext\");\r\n var $i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if point is between min and max | function isPointBetween(point, min, max) {
if(point > min && point < max)
return true;
return false;
} | [
"function check(min, max, target) {\n if (target > min && target < max) {\n return true;\n \n } else {\n \n return false;\n }\n}",
"function between(i, min, max) {//check if int provided is within provided range. https://alvinalexander.com/java/java-method-integer-is-between-a-rang... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the _pako object. TODO: lazyloading this object isn't the best solution but it's the quickest. The best solution is to lazyload the worker list. See also the issue 446. | _createPako() {
const params = {
raw: true,
level: this._pakoOptions.level || -1 // default compression
};
this._pako = this._pakoAction === 'Deflate' ? new Deflate(params) : new Inflate(params);
this._pako.onData = (data) => {
this.push({
data: data,
meta: this.meta
});
};
} | [
"async createWorkers () {\n\n let worker;\n if ( !this.fallback ) {\n\n let workerBlob = new Blob( this.functions.dependencies.code.concat( this.workers.code ), { type: 'application/javascript' } );\n let objectURL = window.URL.createObjectURL( workerBlob );\n for ( le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Async fn always returns a Promise | async function asyncFunc() {
return 123;
} | [
"async(fn) {\n return (req, res, next) => {\n fn(req, res, next).then(data => {\n // On success, save the result of the Promise in req.data.\n req.data = data\n next()\n }).catch(error => {\n // On error, pass error to the next error middleware.\n next(error)\n }... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modified version of the Google listEvents from Takes in a feed and the div ID to build an unordered list as a child of the div | function listGcalEvents(root, divId,calName,calHref) {
var feed = root.feed;
var events = document.getElementById(divId);
if (events.childNodes.length > 0) {
events.removeChild(events.childNodes[0]);
}
var eventContent = document.createElement('div');
eventContent.className = 'widget_content widget_cal';
// create a new ordered list
var ol = document.createElement('ol');
ol.className = "widget_calItems";
// loop through each event in the feed
for (var i = 0; i < feed.entry.length; i++) {
var entry = feed.entry[i];
var title = entry.title.$t;
var startDate = entry['gd$when'][0].startTime;
var endDate = entry['gd$when'][0].endTime;
// get the URL to link to the event
for (var linki = 0; linki < entry['link'].length; linki++) {
if (entry['link'][linki]['type'] == 'text/html' &&
entry['link'][linki]['rel'] == 'alternate') {
var entryLinkHref = entry['link'][linki]['href'];
}
}
//Take link data and build li
li = usfDateLi(title, entryLinkHref, formatGCalTime(startDate), formatGCalTime(endDate));
// append the list item onto the unordered list
ul.appendChild(li);
}
var calHeader = document.createElement('h2');
var calHeaderSpan = document.createElement('span');
var calHeaderLink = document.createElement('a');
var loadingElem = document.getElementById('calLoading');
calHeader.className = "widget_name";
var linkText = document.createTextNode(calName);
calHeaderLink.href = calHref;
calHeaderLink.appendChild(linkText);
calHeaderSpan.appendChild(calHeaderLink);
calHeader.appendChild(calHeaderSpan);
//loadingElem.parentNode.removeChild(loadingElem);
events.innerHTML = '';
events.appendChild(calHeader);
events.appendChild(eventContent);
eventContent.appendChild(ol);
} | [
"function usfDateLi(title, entryLinkHref, objStartDate, objEndDate) {\n\t\tvar objStartDateNum = objStartDate.dayNumber();\n\t\tvar objEndDateNum = objEndDate.dayNumber();\n\n\t\tvar li = document.createElement('li');\n\t\tli.className = \"widget_calItem\";\n\t\t\n\t\tvar eventContainer = li;\n\t\t\n\t\t// if we ha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate if two courses conflict | function conflicted(course1, course2){
return (shareDays(course1, course2) && (course1.start_time <= course2.end_time && course1.start_time >= course2.start_time ||
course2.start_time <= course1.end_time && course2.start_time >= course1.start_time ||
course1.start_time <= course2.start_time && course1.end_time >= course2.end_time ||
course2.start_time <= course1.start_time && course2.end_time >= course1.end_time));
} | [
"function combineCourse(courses, s_courses) {\n if (courses.length == 0) {\n return false;\n } else if (s_courses.length == 0) {\n return courses;\n } else {\n var result = new Array;\n result = s_courses;\n for ( i = 0; i < courses.length; i++) {\n var f = 0;\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers breakpointspecific config. Note that we do do not use the swiper breakpoint config as it does not support changing all swiper options. Instead we reinit the whole swiper when necessary. | registerBreakpointConfig() {
// See GalleryFsMobileScroll.registerBreakpointConfig() for an example.
} | [
"function handleResponsive() {\n app.ResponsiveBreakpoints.register_event(\n '0-768',\n 'module-0-768',\n self.setup0_768.bind(self) // using es5-shim.js\n )\n\n app.ResponsiveBreakpoints.register_event(\n '768-+',\n 'module-768up',\n self.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
var ids = ["payType","payName","payMoney:money","payWay","inBank","bankWay"]; return myCheckOnlyById(ids); | function myCheckOnlyById(ids){
//var ids = ["payType","payName","payMoney:money","payWay","inBank","bankWay"];
for(var i=0; i<ids.length; i++){
var id = ids[i];
if(typeof id == "function"){
return id();
}else{
var fIndex = id.indexOf(":");
if(fIndex > 0){
var checkType = id.substring(fIndex+1, id.length);
id = id.substring(0,fIndex); //如果checkType为function,那么id为对应的function name
if(checkType.toLowerCase() == "money"){
var value = $("#" + id).val();
if(!isMoney(value)){
var sugg = $("#"+id).parent().prev().text();
if(sugg != ""){
sugg = trim(sugg);
var index = sugg.indexOf("*");
if(index > -1){
sugg = sugg.substring(index+1, sugg.length);
}
}
showTip(sugg + "不合规则");
$("#" + id).focus();
$("#" + id).val("");
return false;
}
}else if(checkType.toLowerCase() == "mail"){
var value = $("#" + id).val();
if(!isMail(value)){
var sugg = $("#"+id).parent().prev().text();
if(sugg != ""){
sugg = trim(sugg);
var index = sugg.indexOf("*");
if(index > -1){
sugg = sugg.substring(index+1, sugg.length);
}
}
showTip(sugg + "不合规则");
$("#" + id).focus();
$("#" + id).val("");
return false;
}
}else if(checkType.toLowerCase() == "phone"){
var value = $("#" + id).val();
if(!isPhone(value)){
var sugg = $("#"+id).parent().prev().text();
if(sugg != ""){
sugg = trim(sugg);
var index = sugg.indexOf("*");
if(index > -1){
sugg = sugg.substring(index+1, sugg.length);
}
}
showTip(sugg + "不合规则");
$("#" + id).focus();
$("#" + id).val("");
return false;
}
}else if(checkType.toLowerCase() == "number"){
var value = $("#" + id).val();
if(value=="" || isNaN(value)){
var sugg = $("#"+id).parent().prev().text();
if(sugg != ""){
sugg = trim(sugg);
var index = sugg.indexOf("*");
if(index > -1){
sugg = sugg.substring(index+1, sugg.length);
}
}
showTip(sugg + "不合规则");
$("#" + id).focus();
$("#" + id).val("");
return false;
}
}else{
alert("没有" + checkType + ",这种检查类型");
}
}else{
var value = $("#" + id).val();
//处理easyui 日期控件的值
try{
value = $("#" + id).datebox('getValue');
}catch(e){
}
if(value == ""){
var sugg = $("#"+id).parent().prev().text();
if(sugg != ""){
sugg = trim(sugg);
var index = sugg.indexOf("*");
if(index > -1){
sugg = sugg.substring(index+1, sugg.length);
}
}
showTip(sugg + "不能为空");
$("#" + id).focus();
return false;
//return sugg + "不能为空";
}
}
}
}
return true;
} | [
"function multiEnableById(ids) {\r\n for (var i = 0; i < ids.length; i++) {\r\n var obj = getObj(ids[i]);\r\n if (obj != null) obj.disabled = false;\r\n }\r\n}",
"function getAccountIds (accountsByType) { /* function logic */ }",
"checkID(id){\n for (var i = 0; i < this.player_list.length... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For choose to copy trial Given buttonPressed, which should be from the choose to copy trial, deals with conditional logic and returns whether the player is copying (boolean) assumes self = button 0 | function didPlayerCopy(buttonPressed) {
// if time ran out, update counter and return not copying
if (buttonPressed === null) {
numTimeRanOut++;
return false;
}
// if the button isn't valid, log warning and set copying to false
if (!isValidButton(buttonPressed)) {
console.warn("Invalid player choice!");
return false;
}
// at this point only valid button choices should be possible
// if they tried to copy but don't have enough money, reset their choice to be not copying
// this shouldn't occur, but is here in case it happens somehow
if(buttonPressed != 0 && player.money < payToCopy) {
jsPsych.data.get().filter({'trial_index': jsPsych.progress().current_trial_global - 1}).select('button_pressed').values[0] = 0;
return false;
}
// if copying return true, if not copying return false
if(buttonPressed != 0) return true;
else return false;
} | [
"function copyBattleToClipboard () {\n $('.copy-button').on('click', function() {\n var copy_link = $(this).closest('.copy-modal').find('.copy-link');\n copy_link.focus();\n copy_link.select();\n document.execCommand('copy');\n });\n}",
"unsuccessfulCopy () {\n this.labelTarget.innerHTML = 'Press... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send some keys to the console. The first parameter can be either a string or an array of keys. If noenter is set to true it won't send a final send signal | function cmd(s, noenter) {
for (var i = 0; i < s.length; i++) {
var key = s[i];
if (key == '\n') {
console.sendKey('enter');
}
else if (key == '\r') {
// do nothing.
} else {
console.sendKey(key);
}
}
if (!noenter) {
console.sendKey('enter');
}
return false;
} | [
"function emitKeySequence(keys) {\r\n var i;\r\n for (i = 0; i < keys.length; i++)\r\n emitKey(keys[i], 1);\r\n for (i = keys.length - 1; i >= 0; i--)\r\n emitKey(keys[i], 0);\r\n}",
"function enterobs(e){\n if(e.which == 13 && !e.shiftKey){\n $('#pubob').click();\n e.preventDefault();\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the predicted length of an declaration node when printed minified. this doenst factor in comments that migth be removd or preserved | function getDeclarationLen(decl) {
// "property" + "!important" + ":" + ";"
var len = decl.property.length + (decl.important ? 12 : 2)
walk(decl.value.parts)
function walk(parts, inFn) {
parts.forEach((part, i, parts) => {
if (i !== 0 && !inFn && parts[i-1].type !== "Percentage" && part.type !== "Operator")
len++
if (part.type === "Dimension")
len += part.val.length + part.unit.length
else if (part.type === "Number")
// val also includes potential epsilon
len += part.val.length
else if (part.type === "Percentage")
len += part.val.length + 1
else if (part.type === "Identifier")
len += part.name.length
else if (part.type === "Operator")
len += 3
else if (part.type === "Function") {
len += part.name.length + 2
walk(part.arguments, true)
}
})
}
return len
} | [
"function length () {\r\n return this.node.getComputedTextLength()\r\n}",
"function getDependencySize(dependencyDump) {\n var numeric = dependencyDump.numerics[SIZE_NUMERIC_NAME];\n if (numeric === undefined)\n return 0;\n shouldDefineSize = true;\n return numeric.value;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a function that is used as a submit event handler on form elements that have children affected by this polyfill | function makeSubmitHandler(form) {
return function () {
// Turn off placeholders on all appropriate descendant elements
disablePlaceholders(form);
};
} | [
"function submitElement(element) {\r\n while (element != null) {\r\n if (element.tagName.toLowerCase() == \"form\") {\r\n Utils.fireHtmlEventAndConditionallyPerformAction(element, \"submit\", function() {element.submit();});\r\n return {statusCode: 0};\r\n }\r\n element = element.parentNode;\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter de l'attribut motDePasse motDePasse: nouveau mot de passe | setMotDePasse(motDePasse) {
this.motDePasse = motDePasse;
} | [
"function setPassword(personalSentence, password)\n{\n return (personalSentence + ' ' + password);\n}",
"function Password(){\r\n this.word = 'pass';\r\n this.seed = 1;\r\n }",
"function onConfirmPasswordChange(p) {\n let val = p.target.value;\n setConfirmPassword(val);\n setEnabled(p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats the size of a view and infers what prefix/unit to show. This formatting follows IGV's conventions regarding range display: "1 bp", "101 bp", "1,001 bp", "1,001 kbp", ... | function formatRange(viewSize: number): {prefix: string, unit: string} | [
"function formatFileSize (size)\n{\n var oneKB = 1024;\n var oneMB = (1024 * 1024);\n \n var fileSize = parseFloat(size);\n if(isNaN(fileSize))\n return \"\";\n \n if (fileSize < oneKB)\n return fileSize + \" B\";\n if (fileSize > oneMB)\n return (fileSize / oneMB).toFix... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function will accept the input div collection & give back the necessary details back. | function getRequiredSwarDetails(inputDivCollection) {
/// This object will contain all the required details that are deduced from the UI
/// and add them to differenct properties.
/*
1. First the Name property.
2. time in milliseconds.
3. delaytime for each note deduced from the UI.
*/
var requiredSwarDetails = {};
var time = document.getElementsByClassName('time');
//console.info(time[0].getBoundingClientRect().width);
//// Get the details for the one input box.
var swarDescDiv = getSwarDivDetails(inputDivCollection[0]);
var widthOfSingleRuler = time[0].getBoundingClientRect().width;
for(var i = 0; i < inputDivCollection.length; i++ ) {
requiredSwarDetails["swar"+i] = {};
var currentInputSwar = inputDivCollection[i].getBoundingClientRect();
// Getting the name of the Swar.
requiredSwarDetails["swar"+i].name = inputDivCollection[i].textContent;
//// How long the swar will be played.
requiredSwarDetails["swar"+i].timeOfPlay = Number((currentInputSwar.width / widthOfSingleRuler * 1000).toFixed(2));
///// The delay of each swar.
requiredSwarDetails["swar"+i].delayTime = Number(((currentInputSwar.left - (swarDescDiv.right + 1)) / widthOfSingleRuler * 1000).toFixed(2));
}
requiredSwarDetails.length = inputDivCollection.length;
return requiredSwarDetails;
} | [
"function retrieveSwarsFromUI(inputDivCollection) {\n\tvar notation = {};\n\tvar leftSwarDiv;\n\t//inputDivCollection\n\tfor( var i = 0 ; i < inputDivCollection.length; ++i) {\n\t\tnotation[\"inputDiv\"+(i+1)] = {};\n\t\tnotation[\"inputDiv\"+(i+1)].name = inputDivCollection[i].previousElementSibling.textContent;\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a deep copy of a script coverage. | function cloneScriptCov(scriptCov) {
const functions = [];
for (const functionCov of scriptCov.functions) {
functions.push(cloneFunctionCov(functionCov));
}
return {
scriptId: scriptCov.scriptId,
url: scriptCov.url,
functions,
};
} | [
"function cloneFunctionCov(functionCov) {\r\n const ranges = [];\r\n for (const rangeCov of functionCov.ranges) {\r\n ranges.push(cloneRangeCov(rangeCov));\r\n }\r\n return {\r\n functionName: functionCov.functionName,\r\n ranges,\r\n isBlockCoverage: functionCov.isBlockCover... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows uploading spinner for replacing media items | function uploadingReplaceMedia() {
if (editMediaFormComplete() == true) {
$("#uploadingSpinnerContainer").show();
$("#cancelButton").hide();
$("#submitButton").hide();
$("#removeVideoButton").hide();
}
} | [
"function addLoading( up, file, $ul )\n\t{\n\t\t$ul.removeClass('hidden').append( \"<li id='\" + file.id + \"'><div class='pi-image-uploading-bar'></div><div id='\" + file.id + \"-throbber' class='pi-image-uploading-status'></div></li>\" );\n\t}",
"handleUpload() {\n if (!this.bShowUploadSection) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a patch containing only the data changes (and the contact id) | function patchContact(contact) {
var patch = { id: contact.id };
if (rnd(-10)) {
if (addInPatch(patch, contact, 'firstname', faker.name.firstName())) {
addInPatch(patch, contact, 'homeemail', createEmailAddress(contact.firstname, contact.lastname));
addInPatch(patch, contact, 'workemail', createEmailAddress(contact.firstname, contact.lastname, createDomainName(contact.company)));
}
}
else if (rnd(-10)) {
addInPatch(patch, contact, 'homeemail', rnd(-3) ? null : createEmailAddress(contact.firstname, contact.lastname));
}
if (rnd(-10)) {
addInPatch(patch, contact, 'homephone', rnd(-3) ? null : faker.phone.phoneNumber());
}
if (rnd(-10)) {
addInPatch(patch, contact, 'avatar', rnd(-3) ? null : faker.image.imageUrl());
}
if (rnd(-10)) {
addInPatch(patch, contact, 'homeaddress', rnd(-3) ? null : createAddress());
}
// updates professional data
if (rnd(-10)) {
var companyName = rnd(-3) ? null : faker.company.companyName();
addInPatch(patch, contact, 'company', companyName);
// nullifies the professional data
if (companyName === null) {
addInPatch(patch, contact, 'workwebsite', null);
addInPatch(patch, contact, 'workemail', null);
addInPatch(patch, contact, 'workaddress', null);
addInPatch(patch, contact, 'workphone', null);
}
// updates the otherwise
else {
// builds the domain name
var domainname = createDomainName(contact.company);
if (addInPatch(patch, contact, 'workwebsite', rnd(-3) ? null : 'www.' + domainname)) {
addInPatch(patch, contact, 'workemail', rnd(-3) ? null : createEmailAddress(contact.firstname, contact.lastname, domainname));
}
if (rnd(-5)) {
addInPatch(patch, contact, 'workaddress', rnd(-3) ? null : createAddress(contact.company));
}
if (rnd(-5)) {
addInPatch(patch, contact, 'workphone', rnd(-3) ? null : faker.phone.phoneNumber());
}
if (rnd(-8)) {
addInPatch(patch, contact, 'workaddress', rnd(-3) ? null : createAddress(contact.company));
}
}
}
return patch;
} | [
"function sendPatch(patchContent, buttonID) {\n\t\t\n\t{\n\t\tpatchContent = typeof patchContent !== 'undefined' ? patchContent : Date();\n\t}\n\t\n if (gistContents !== 'undefined') {\n \n \tvar tmpContents = gistContents['files']['savedURL.md']['content'];\n \tvar newContents = \"\\n\" + tmpContents + patchCo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a Webpack configuration that compiles staticrenderpages.js, a Node module that will build HTML pages. | function createWebpackConfigStatic(
batfishConfig: BatfishConfiguration
): Promise<webpack$Configuration> {
return createWebpackConfigBase(batfishConfig).then(baseConfig => {
const staticConfig: webpack$Configuration = {
entry: {
static: path.join(__dirname, '../webpack/static-render-pages.js')
},
output: {
filename: './static-render-pages.js',
libraryTarget: 'commonjs2'
},
target: 'node',
externals: {
// These modules are required by static-render-pages and don't play
// nice when Webpack tries to compile them, or we know they can be
// loaded in Node.
'uglify-js': 'uglify-js',
mkdirp: 'mkdirp',
react: 'react',
'react-dom': 'react-dom'
},
plugins: [
// Ensure that all files will be grouped into one file,
// even if they would otherwise be split into separate chunks.
// Separate chunks serve no purpose in the static build: we need all
// the information at once.
new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 })
],
devtool: 'source-map',
node: {
console: false,
global: false,
process: false,
__filename: false,
__dirname: false,
Buffer: false,
setImmediate: false
}
};
if (batfishConfig.webpackStaticIgnore) {
_.set(staticConfig, 'module.rules[0]', {
test: batfishConfig.webpackStaticIgnore,
loader: 'ignore-loader'
});
}
let config = webpackMerge(baseConfig, staticConfig);
if (batfishConfig.webpackConfigStaticTransform) {
config = batfishConfig.webpackConfigStaticTransform(config);
}
return config;
});
} | [
"function generateWebpackConfigForCanister(name, info) {\n if (typeof info.frontend !== 'object') {\n return;\n }\n const outputRoot = path.join(__dirname, output, name);\n const inputRoot = __dirname;\n const entry = path.join(inputRoot, info.frontend.entrypoint);\n return {\n mode: \"production\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the user language (given by the navigator or as URL search parameter | getUserLanguage( general=true ){
var urlParams = new URLSearchParams(window.location.search)
var lang = urlParams.get('lang')
if( lang === undefined || lang === null ) lang = window.navigator.language
if( general ) lang = lang.split('-')[0]
return lang
} | [
"function getLanguage(){\n\tvar lang=document.getElementById(\"language\").value;\n\tswitch(lang){\n\t\tcase \"C\":\n\t\t\tlang=1;\n\t\t\tbreak;\n\t\tcase \"C++\":\n\t\t\tlang=2;\n\t\t\tbreak;\n\t\tcase \"Java\":\n\t\t\tlang=3;\n\t\t\tbreak;\n\t\tcase \"Python\":\n\t\t\tlang=5;\n\t\t\tbreak;\n\t}\n\treturn lang;\n}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether the given month is enabled. | shouldEnableMonth(month) {
const activeYear = this.dateAdapter.getYear(this.activeDate);
if (month === undefined || month === null ||
this.isYearAndMonthAfterMaxDate(activeYear, month) ||
this.isYearAndMonthBeforeMinDate(activeYear, month)) {
return false;
}
if (!this.dateFilter) {
return true;
}
const firstOfMonth = this.dateAdapter.createDate(activeYear, month);
// If any date in the month is enabled count the month as enabled.
for (let date = firstOfMonth; this.dateAdapter.getMonth(date) === month; date = this.dateAdapter.addCalendarDays(date, 1)) {
if (this.dateFilter(date)) {
return true;
}
}
return false;
} | [
"function calenderMonthIsCurrentMonth(){\n if(data.current_date.year == data.calendar.year && data.current_date.month == data.calendar.month){\n return true;\n } else {\n return false;\n }\n}",
"function dateUsed(monthyear, array) {\n for (k = 0; k < array.length; k++) {\n if (mon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enter a parse tree produced by KotlinParserenumClassBody. | enterEnumClassBody(ctx) {
} | [
"enterEnumEntries(ctx) {\n\t}",
"enterEnumConstantList(ctx) {\n\t}",
"constructor(options) {\n /// @internal\n this.typeNames = [\"\"];\n /// @internal\n this.typeIDs = Object.create(null);\n /// @internal\n this.prop = new tree_es[\"c\" /* NodeProp */]();\n this... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
8) shiftNTimes(array, numShifts) Modify array so it is "left shifted" n times so shiftNTimes(array[6, 2, 5, 3], 1) changes the array argument to [2, 5, 3, 6] and shiftNTimes([6, 2, 5, 3], 2) changes the array argument to [5, 3, 6, 2]. You must modify the array argument by changing the parameter named nums inside method shiftNTimes. A change to nums inside the method shiftNTimes changes the argument. Do not return anything. shiftNTimes([1, 2, 3, 4, 5, 6, 7], 3 ) modifies the array to [4, 5, 6, 7, 1, 2, 3] shiftNTimes( [1, 2, 3], 5) modifies the array to [3, 1, 2] shiftNTimes( [3], 5) modifies the array to (3) Precondition: numShifts > 0 Precondition: integerArray has integers onlt. We do not test for strings or floats. | function shiftNTimes(integerArray, numShifts) {
while (numShifts) {
var shiftedIndex = integerArray.shift();
integerArray.push(shiftedIndex);
numShifts--;
}
} | [
"shift_args(n, m, s){\n for(var i = n; i >= 0; i--){\n this.index_set(s, i+m+1, this.index(s, i));\n }\n return s-m-1;\n }",
"function shift(arr) {\n var len = arr.length;\n if (len === 0) return undefined;\n var out = arr[0];\n\n for (var i = 0; i < len - 1; i++) { arr[i] = arr[i + 1]; }\n ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create philippines VAT Report object and add it to mainPanel | function phpVATReport(params) {
if (params) {
var VATReportObject = Wtf.getCmp(params.reportID);
if (VATReportObject == null) {
VATReportObject = new Wtf.account.phpVATReport({
title: Wtf.util.Format.ellipsis(params.title),
tabTip: params.titleQtip,
id: params.reportID,
closable: true,
border: false,
params: params,
layout: 'fit',
iconCls: 'accountingbase receivepaymentreport'
});
Wtf.getCmp('as').add(VATReportObject);
}
Wtf.getCmp('as').setActiveTab(VATReportObject);
Wtf.getCmp('as').doLayout();
}
} | [
"function ciniki_sapos_invoicereports() {\n\n this.taxreport = new M.panel('Tax Report', 'ciniki_sapos_invoicereports', 'taxreport', 'mc', 'large', 'sectioned', 'ciniki.sapos.invoicereports.taxreport');\n this.taxreport.year = null;\n this.taxreport.quarter = 0;\n this.taxreport.data = {};\n this.tax... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Zero out the top bits in the last 32bit words of the IV | function zeroIVBits(iv) {
// "We zero-out the top bit in each of the last two 32-bit words
// of the IV before assigning it to Ctr"
// — http://web.cs.ucdavis.edu/~rogaway/papers/siv.pdf
iv[iv.length - 8] &= 0x7f;
iv[iv.length - 4] &= 0x7f;
} | [
"function zeroDecipher(key, data) {\n\treturn decompress(sjcl.decrypt(key, data));\n}",
"static int256(v) { return n(v, -256); }",
"zero () {\n this.#secret.zero()\n }",
"static uint192(v) { return n(v, 192); }",
"static bytes28(v) { return b(v, 28); }",
"static uint248(v) { return n(v, 248); }",
"s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper to ensure path1 and path2 are roughly equal | function approximatelyEqual(path1, path2) {
// convert to numbers and letters
const path1Items = pathToItems(path1);
const path2Items = pathToItems(path2);
const epsilon = 0.001;
if (path1Items.length !== path2Items.length) {
return false;
}
for (let i = 0; i< path1Items.length; i++) {
if (typeof path1Items[i] === 'string' && path1Items[i] !== path2Items[i]) {
return false;
}
// otherwise it's a number, check if approximately equal
if (Math.abs(path1Items[i] - path2Items[i]) > epsilon) {
return false;
}
}
return true;
} | [
"equals(path, another) {\n return path.length === another.length && path.every((n, i) => n === another[i]);\n }",
"compare(path, another) {\n var min = Math.min(path.length, another.length);\n\n for (var i = 0; i < min; i++) {\n if (path[i] < another[i]) return -1;\n if (path[i] > ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a path DOM element, return a list of path segments | function convert(element) {
let segments = [],
pathSegList = element.pathSegList
let prev = pathSegList[0]
for (let i = 1; i < pathSegList.length; i++) {
let cur = pathSegList[i]
segments.push(converters[cur.pathSegType](prev, cur))
prev = cur
}
return segments
} | [
"pathList(){\n let pathList = []\n let current = this\n while(current){\n if(current.pathId()) pathList.unshift(current.pathId())\n current = current.parent\n }\n return pathList\n }",
"function findSubPath (path) {\n var path_length = path.length;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
build the quiz by loopng through xml data | function generateQuiz() {
quizAnswers = [];
quizContent = "<div class=\"main2-banner-title\">Quiz " + currentQuiz + "</div>";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
else {
}
};
xhttp.open("GET", "data.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
document.getElementById("Main2-container").innerHTML = "";
//gets the collection of the unit, gets the html element at entry 0 (units are all unique), then gets
//collection with all elements in unit with the entry name MultipleChoice
//var quizData = xmlDoc.getElementsByTagName("Unit")[currentQuiz-1].getElementsByTagName("MultipleChoice"); //quizData is a html collection
var quizData = xmlDoc.getElementsByTagName("Quiz")[0].getElementsByTagName("Unit")[currentQuiz-1].getElementsByTagName("MultipleChoice");
//id will take the from: q0A q0B, etc...
//name will take the form: q0 q1 q2......
for (let i = 0; i < quizData.length; i++) {
quizContent = quizContent + "<div><p>" + (i + 1) + ". " + quizData[i].getElementsByTagName("Question")[0].childNodes[0].nodeValue + "</p><ul><li>" + "A) <input type=\"radio\" name=\"q" + i + "\" id=\"q" + i + "A\">" +
quizData[i].getElementsByTagName("A")[0].childNodes[0].nodeValue + "</li><li>" + "B) <input type=\"radio\" name=\"q" + i + "\" id=\"q" + i + "B\">" + quizData[i].getElementsByTagName("B")[0].childNodes[0].nodeValue + "</li><li>" +
"C) <input type=\"radio\" name=\"q" + i + "\" id=\"q" + i + "C\">" + quizData[i].getElementsByTagName("C")[0].childNodes[0].nodeValue + "</li><li>" + "D) <input type=\"radio\" name=\"q" + i + "\" id=\"q" + i + "D\">" + quizData[i].getElementsByTagName("D")[0].childNodes[0].nodeValue + "</li></ul></div>";
quizAnswers[i] = quizData[i].getElementsByTagName("Answer")[0].childNodes[0].nodeValue;
}
document.getElementById("Main2-container").innerHTML = quizContent;
//xmlDoc.getElementsByTagName("bodyParagraph")[1].childNodes[0].nodeValue; //get data of second body paragraph
}
} | [
"function quizSetUp() {\n for (i = 0; i < questionArray.length; i++) {\n question.textContent = questionArray[i];\n answer1.textContent = A1[i];\n answer2.textContent = A2[i];\n answer3.textContent = A3[i];\n answer4.textContent = A4[i];\n return;\n}}",
"function initialise (quizz){\n if (... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
eslintenable mod_path_worker_sort_weighted sort 2D path weighted todo: more efficient sort | function sortWeightedPath (path, pathOrder, mergeDistance, orderWeight, sequenceWeight) {
if (path.length <= 1) { return path }
var newpath = []
if (sequenceWeight > 0) {
var x0 = path[0][path[0].length - 1][X]
var y0 = path[0][path[0].length - 1][Y]
newpath[newpath.length] = path[0]
path.splice(0, 1)
pathOrder.splice(0, 1)
var endpath = path[path.length - 1]
path.splice(path.length - 1, 1)
pathOrder.splice(pathOrder.length - 1, 1)
} else {
x0 = path[path.length - 1][path[path.length - 1].length - 1][X]
y0 = path[path.length - 1][path[path.length - 1].length - 1][Y]
newpath[newpath.length] = path[path.length - 1]
path.splice(path.length - 1, 1)
pathOrder.splice(pathOrder.length - 1, 1)
endpath = path[0]
path.splice(0, 1)
pathOrder.splice(0, 1)
}
while (path.length > 0) {
var dmin = Number.MAX_VALUE
var wmin = Number.MAX_VALUE
for (var seg = 0; seg < path.length; ++seg) {
var x1 = path[seg][0][0]
var y1 = path[seg][0][1]
var d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)
var w = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0) + orderWeight * pathOrder[seg] + sequenceWeight * (seg / path.length)
if (w < wmin) {
wmin = w
dmin = d
var segmin = seg
}
}
x0 = path[segmin][path[segmin].length - 1][X]
y0 = path[segmin][path[segmin].length - 1][Y]
if (Math.sqrt(dmin) <= mergeDistance) { newpath[newpath.length - 1] = newpath[newpath.length - 1].concat(path[segmin]) } else { newpath[newpath.length] = path[segmin] }
path.splice(segmin, 1)
pathOrder.splice(segmin, 1)
}
newpath[newpath.length] = endpath
return newpath
} | [
"function sort_by_weight(a,b){ // a and b are lifter id's\n\tvar lift_attempt = state.current.lift + \"_\" + state.current.attempt;\n\tvar lift_attempt_next = state.current.lift + \"_\" + (Number(state.current.attempt)+1);\n\tvar awn = Number(state.lifter_info[a][lift_attempt_next]);\n\tvar bwn = Number(state.lifte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populate the search box with a given $searchterm. This calls /search/, ADD LOADING ... HERE (fix) | function populateSearchBox(searchterm) {
var newrow = '<tr ><td id="loading_dots_text" style="text-align: right;" width="60%"></td><td id="loading_dots" style="text-align:left;"></td></tr>';
$('#search-table').append(newrow);
dots_id = setInterval(animateDots, 500);
$.get("/search/", {query: searchterm},
function(data){
clearInterval(dots_id);
fillSearchBox(data);
}
);
} | [
"function callAjaxSearch() {\n\n searchTerm = $(settings.input).val();\n\n //No term - clear results\n if (searchTerm == \"\") {\n\n clear();\n resetPage();\n updateUI();\n\n\n }\n //Different term than last time - c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function gets the username and password via the DOM passes data to the testAccount function | function validateAccount() {
let uName = document.getElementById('username').value;
let pword = document.getElementById('password').value;
testAccount(uName, pword);
} | [
"static login() {\n const doc = navigationDocument.documents[navigationDocument.documents.length - 1]\n const e = doc.getElementsByTagName('textField').item(0)\n const user = encodeURIComponent(e.getAttribute('data-username'))\n const pass = encodeURIComponent(e.getFeature('Keyboard').text)\n\n const... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Server response callback for setting a question active. | function setQuestionActiveCallback(data, status) {
if(status == "success"){
var questionID = data.responseJSON.questionId;
displayStopButton(questionID);
$('[questionid="'+questionID+'"]').find('.playBtnGroup').addClass('active');
$("#presentTab").click();
}
} | [
"function setQuestionInactiveCallback(data, status) {\n\tif(status == \"success\"){\n\t\tvar questionID = data.responseJSON.questionId;\n\t\tdisplayPlayButton(questionID);\n\t\t$('[questionid=\"'+questionID+'\"]').find('.playBtnGroup').removeClass('active');\n\n\t\t// FIXME: Need to actually request and update the ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a function that proxies to the given method name on the globals console object. The proxy will also detect if the console doesn't exist and will appropriately noop. This allows support for IE9, which doesn't have a console if the developer tools are not open. | function consoleProxy(method) {
return function () {
if (console) {
console[method].apply(console, arguments);
}
};
} | [
"createProxy() {\n const self = this;\n this._proxy = new Proxy(console, {\n get: (target, property) => {\n if ( typeof target[property] === 'function' ) {\n return function(args) {\n self.send(property, args);\n return target[property](args);\n }\n }... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find Pets with Customer BY ID | async findOneWithCustomer(req, res, next) {
let pet;
const { id } = req.params;
try {
pet = await petFacade.findOneWithCustomer({
where: { id },
include: ["customer"]
});
} catch (e) {
return next(e);
}
res.send(pet);
} | [
"async findAllWithCustomer(req, res, next) {\n let pets;\n try {\n pets = await petFacade.findAllWithCustomer({\n where: {},\n include: [\"customer\"]\n });\n } catch (e) {\n return next(e);\n }\n res.send(pets);\n }",
"async getBagItemsByCustomerId(req, res) {\n co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds our milestones object | function buildMilestones(actions) {
const available = {
event: "ui_prompts",
handle: "availSurvival",
values: []
};
const unavailable = {
event: "ui_prompts",
handle: "unavailSurvival",
values: []
};
const prevent = {
event: "ui_prompts",
handle: "preventSurvival",
values: []
};
actions.forEach((item, index) => {
if (item.available) {
available.values.push(index + 1);
} else if (item.title_tip.includes("prevent")) {
prevent.values.push(index + 1);
} else {
unavailable.values.push(index + 1);
}
});
const milestones = [available, unavailable, prevent];
return milestones;
} | [
"function getMilestones(callBack) {\n\t\tpost('/components/' + config.component + '/root/milestones', {}, function(resultObj) { \n\t\t\tobj.config.milestones = resultObj; // save milestones to the local config obj\n\t\t\tif (typeof callBack == 'function') callBack();\n\t\t});\n\t}",
"getPublicMilestones() {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Agrega un Invitado a la listade invitados | function agregarInvitado(){
var tablaLength = obtenTablaLength("invitado_table");
var id = tablaLength+1;
var objeto = generaObjetoInvitados();
var renglon = creaRenglonInvitados(objeto, id);
agregaRenglon(renglon, "invitado_table");
} | [
"function sendInvites(json, statusText) {\n\t$(\"table.team tr:last\").after(json.members_html);\n for (i = 0; i < json.members_ids.length; i++) {\n\t\t$(\"#member_\"+ json.members_ids[i]).highlightFade({start: '#FFFF99', speed: 2000});\n\t $(\"#member_\"+ json.members_ids[i] +\" a.tip\").link_tips();\n\t};\n\t$(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accepts an array of errors and returns the first error message. | function firstMessage(errors) {
if (!Array.isArray(errors) || errors.length === 0) return null;
var error = errors[0];
if (error.message) {
return error.message;
} else {
return error;
}
} | [
"function MultiError(errors)\n\t{\n\t\tmod_assertplus.array(errors, 'list of errors');\n\t\tmod_assertplus.ok(errors.length > 0, 'must be at least one error');\n\t\tthis.ase_errors = errors;\n\t\n\t\tVError.call(this, {\n\t\t 'cause': errors[0]\n\t\t}, 'first of %d error%s', errors.length, errors.length == 1 ? '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
leftPad by timrwood LeftPad created to added leading zeros to pinCode if needed | function leftPad(pinCode, targetLength) {
var count = pinCode.length;
var output = pinCode;
while (count < targetLength) {
output = '0' + output;
count++;
}
return output;
} | [
"function padPartial(iotaAreaCode) {\r\n let padded = iotaAreaCode;\r\n if (padded.length < 8) {\r\n padded = padded + \"A\".repeat(8 - padded.length);\r\n }\r\n if (padded.length < 9) {\r\n padded = `${padded}9`;\r\n }\r\n return padded;\r\n}",
"function zeroPad(val, width) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For internal use. Encode the blob in format specified | _encodeBlob(blob = iCrypto.pRequired("_encodeBlob"),
encoding = iCrypto.pRequired("_encodeBlob")){
let self = this;
if (!this.encoders.hasOwnProperty(encoding)){
throw "_encodeBlob: Invalid encoding: " + encoding;
}
return self.encoders[encoding](blob)
} | [
"encodeData(type, value) {\n return this.getEncoder(type)(value);\n }",
"function Blob(repository, obj) {\n this.repository = repository;\n _immutable(this, obj).set(\"id\").set(\"data\");\n }",
"writeTree(tree) {\n const treeObject = `${Object.keys(tree).map((key) => {\n if (Util... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the recommended portion of food for each dog and add it to the dogs property | function calcRecommendedFood(dogsArr) {
dogsArr.forEach(function (dog) {
dog.recommendedFood = (dog.weight ** 0.75 * 28).toFixed(2);
});
} | [
"totalFood() {\n return this.passengers.reduce((accumulator, passenger) => accumulator + passenger.food, 0)\n \n }",
"function calculateFoodData(preferences, restrictions, guestCount) {\n prefPercentage = [];\n var occurences = findOccurences(preferences);\n var uniqueRestrictions = rest... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to handle the response from clicking on the 'Create Activity' button Return back to the original form and display the status message | function handleCreateActivityResponse(status) {
if (status.errCode === 1){
window.location = '/?methodType=createActivity&errCode=' + status.errCode;
} else if (status.errCode === 6){
//missing required parameter
var errMsg = 'Error: ' + status.message;
if (status.message == 'null time1') {
errMsg = 'Error: Null Start Time';
} else if (status.message == 'null time2') {
errMsg = 'Error: Null End Time';
}
$('#missingParams').html(errMsg);
$('#missingParams').show();
$('body').scrollTop(0);
//window.location = '/#create_activity_page?errCode=' + status.errCode;
}
// window.location = '/';
} | [
"function activityAddClicked() {\n\tvar addedActivity = document.getElementById(\"newactivity\").value;\n\t\n\tif (addedActivity==\"\") {\n\t\talert(\"Can't add an empty activity.\");\n\t} else {\n\t\tdoesActivityExist(addedActivity,function(result) {\n\t\t\tif (result) {\n\t\t\t\talert(\"This activity already exis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
==================== Notify Security =================== | function alertSecurity() {
var txt;
if (confirm("Are you sure to notify Security?")) {
alert("Already notified Security.");
} else {
alert("Canceled to notify Security!");
}
} | [
"notify(number) {\n\n\t\t\tif (Notification.permission == \"granted\") {\n\n\t\t\t\tlet notification = new Notification('InstaCop V2', {\n\t\t\t\t\ticon: this.pidImg,\n\t\t\t\t\tbody: this.config.style + ' stock: ' + number + ' available.'\n\t\t\t\t});\n\n\t\t\t\tnotification.onclick = function() {\n\t\t\t\t\tthis.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
addItemToOrder(Name,count,price): IN: Name name of menu item count used for tracking multiples of same item, example burger: 2 price price of the item PURPOSE: add the clicked menu item to the order. create an html element for the item under orderArea. OUT: nothing, however html item element is created in view | function addItemToOrder(Name,count,price){
orderTotal += parseFloat(price);
var itemName = Name+'-'+count || Name;//legacy, don't really need ||
var newItem = document.createElement("p");
newItem.setAttribute('id',itemName);
document.getElementById('orderArea').appendChild(newItem);
$('#'+itemName).html(Name.toUpperCase() +' $'+price);
$('#orderTotal').html('Total: $'+orderTotal.toFixed(2));//force two decimal spots
} | [
"function createItem(id,parentDiv,price){\n\tvar nm = id.substring(id.lastIndexOf(ElementId_Spacer)+1);\n\tvar newItem = document.createElement(\"p\");\n\tnewItem.setAttribute('class','item');\n\tnewItem.setAttribute('id',id);\n\tnewItem.setAttribute('value',price);\n\tnewItem.setAttribute('name',nm);\n\tdocument.g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts new unstyled block. Initially inspired from but changed so that the split + block type reset amounts to only one change in the undo stack. | insertNewUnstyledBlock(editorState) {
const selection = editorState.getSelection();
let newContent = Modifier.splitBlock(
editorState.getCurrentContent(),
selection,
);
const blockMap = newContent.getBlockMap();
const blockKey = selection.getStartKey();
const insertedBlockKey = newContent.getKeyAfter(blockKey);
const newBlock = blockMap
.get(insertedBlockKey)
.set('type', BLOCK_TYPE.UNSTYLED);
newContent = newContent.merge({
blockMap: blockMap.set(insertedBlockKey, newBlock),
});
return EditorState.push(editorState, newContent, 'split-block');
} | [
"resetBlockWithType(editorState, newType, newText) {\n const contentState = editorState.getCurrentContent();\n const selectionState = editorState.getSelection();\n const key = selectionState.getStartKey();\n const blockMap = contentState.getBlockMap();\n const block = blockMap.get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Combines the binding value and a factory for an animation player. Used to bind a player to an element template binding (currently only `[style]`, `[style.prop]`, `[class]` and `[class.name]` bindings supported). The provided `factoryFn` function will be run once all the associated bindings have been evaluated on the element and is designed to return a player which will then be placed on the element. | function bindPlayerFactory(factoryFn, value) {
return new BoundPlayerFactory(factoryFn, value);
} | [
"function keyhandlerBindingFactory(keyCode) {\n return {\n init: function(element, valueAccessor, allBindingsAccessor, data, bindingContext) {\n var wrappedHandler, newValueAccessor;\n\n // wrap the handler with a check for the enter key\n wrappedHandler = function(data, event... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the total cost of a profession | async function getProfessionTotalCost (url) {
let content = await fetch.single(url, { type: 'text' })
let $ = cheerio.load(content)
// Get the first defined cost, that's the total cost
let html = $('dd').eq(2).html()
// Replace and split the icons for gold, silver and copper
html = html.replace(/<span.+?<\/span>/g, '###')
html = html.split('###')
// Get a copper cost and return it
return cleanGoldArray(html)
} | [
"function calculateTotalCost(pricePerNight, noOfDays) {\n let obj = {}\n obj[\"cents\"] = pricePerNight * noOfDays;\n obj[\"dollars\"] = convertCentsToDollars(pricePerNight * noOfDays);\n return obj;\n}",
"function aggregateTotalCost(cost) {\n\n let totalGreenSum = 0;\n let totalGreySum = 0;\n\n Object.val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FadeInTransition class changes slides by fading in new slide. This class can be removed if effect is not used. | function FadeInTransition() {} | [
"function mFade() {\n\tgetId('t' + currTact).classList.add(\"faded\");\n}",
"function MM_effectAppearFade(targetElement, duration, from, to, toggle)\n{\n\tSpry.Effect.DoFade(targetElement, {duration: duration, from: from, to: to, toggle: toggle});\n}",
"function Transition() {}",
"performSlide() {\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
take a start angle in deg, an end angle in deg, and a number and provide an evenly spaced array of radians between the start and end | function tween(start, end, number) {
let interval = (end - start) / number
const degrees = []
for (let i = 1; i <= number; i++) {
degrees.push(start + interval * i)
}
return degrees.map(d => (d * Math.PI) / 180)
} | [
"function createArrayFromNumberSequence ( start, end ) {\n\tvar result;\n\n\tif ( typeof start === 'number' && typeof end === 'number' && start <= end ) {\n\t\tresult = Array.apply(null, { length: ( end - start + 1 ) } )\n\t\t\t.map(Number.call, Number)\n\t\t\t.map( function( i ) { return i + start; } );\n\t} else ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
console.log(filterProducts('A', arrOfProducts)) console.log(filterProducts('S', arrOfProducts)) No. 4 | function printProducts(products){
for(let i = 10; i < 36; i++){
let letter = i.toString(36)
letter = letter.toUpperCase()
let filteredProducts = filterProducts(letter, products)
if (filteredProducts.length > 0) {
console.log('===' + letter + '===')
for(let j = 0; j < filteredProducts.length; j++){
if (filteredProducts.length - 1 === j){
console.log(filteredProducts[j] + '\n')
} else {
console.log(filteredProducts[j])
}
}
}
}
} | [
"function getProduct(identifier, filter) {\n var productsFiltered = [];\n $(\".productlist\").empty();\n\n//uit 'products' worden de key en de value gehaald (key = 1 record en value de waarden die erin zitten)\n//als de array met de meegegeven 'soort' gelijk is aan de filter 'soortnaam' wordt de decorateProdu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read global YUI, extract internal modulenames and whitelist them | function readGlobalYUI(callback) {
console.log("reading global ENV from yui.js [" + YUIVersion + "]");
http.request({
host : "yui.yahooapis.com",
path : "/" + YUIVersion + "/build/yui/yui.js"
}, function(resp){
var _yuiRaw = "";
resp.on('data', function(data){
_yuiRaw += data;
});
resp.on('end', function(){
whiteList = findYUIAdd(esprima.parse(_yuiRaw, {tokens : true}).body);
setTimeout(callback, 1000);
});
}).end();
} | [
"function getMyY() {\r\n if (typeof(myY) != \"undefined\" && myY != null) {\r\n //alert('myY was set, returning.');\r\n return myY;\r\n } else {\r\n //alert('no myY, creating and returning.');\r\n // Create global YUI3 instance\r\n myY = YUI({ filter:'raw' });\r\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the conversation state for the given user in the database. | async function __handleFlowUpdateConversationState (flow, recUser) {
const database = this.__dep(`database`);
let changes;
// If we get this far with a basic flow and no prompt, then the conversation flow is finished.
if (flow.definition.type === `basic` && !flow.definition.prompt) {
changes = {
'conversation.previousStepUri': recUser.conversation.currentStepUri,
'conversation.currentStepUri': null,
'conversation.waitingOnPrompt': false,
};
}
// Otherwise, update the user record to mark that we're on this flow.
else {
changes = {
'conversation.previousStepUri': recUser.conversation.currentStepUri,
'conversation.currentStepUri': flow.uri,
'conversation.waitingOnPrompt': Boolean(flow.definition.prompt),
};
}
await database.update(`User`, recUser, changes);
} | [
"setUserUpdateStatus( state, status ){\n state.userUpdateStatus = status;\n }",
"updateUserToShell() {\n const user = this.authService.readUserFromSessionStorage();\n this.postMessageToShell(MessageType.user, user);\n }",
"SET_USER(state, data) {\n state.user.data = data;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
muestra la modal para Crear un Usuario | function modalUsuario() {
$("#agregarUsuario").modal();
} | [
"function inserirUsuario() {\n if ($scope.novoUsuario.Id > 0) {\n atualizarModelUsuario();\n\n } else {\n inserirModelUsuario();\n }\n }",
"function handleCreateAccount() {\n\t$('.open-create-account').on('click', event => {\n\t\t$('.Welcome').... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function should update the custom arrays on page load and on form submission | function updateStorageArrays() {
//checking if there is existing previous form data in local storage
if (!localStorage.getItem("form-data")) {
return;
}
//clearing the custom array so they can be "refilled" with what is in the local storage
siteStorage = JSON.parse(localStorage.getItem("form-data"));
customOneArray = [];
customTwoArray = [];
for (var i = 1; i <= 6; i++) {
if (siteStorage["name" + i] !== "" && siteStorage["name" + i] !== undefined) {
var pair = [];
pair.push(siteStorage["name" + i]);
pair.push(siteStorage["url" + i]);
if (i < 4) {
customOneArray.push(pair);
} else {
customTwoArray.push(pair);
}
}
}
} | [
"function store() {\n customs.push(custom); //stores custom arrays\n custom = {\n name: \"\",\n opt: [] //clears custom array to get new things\n };\n}",
"function fillSavedInputs() {\n const getFieldByName = name => $(`#id_${name}`);\n\n for (const fieldName in DOM.orderFieldData) { // Ignore ESL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modal Action Handler: User | function modal_user_action(action, username) {
switch(action) {
case "add":
if(confirm("ยืนยันการเพิ่มบัญชีผู้ใช้งาน")) {
$.post(current_web_location + "/services/user_add.php", {
user_name: $("#modal-user-input-username").val(),
user_type: $("#modal-user-input-usertype").val(),
valid_to: $("#modal-user-input-validuntil").val(),
return_type: "TEXT"
}, function(data, status) {
system_display_dialog(data);
if(data.includes("สำเร็จ")) {
refresh_user_list();
$("#modal-user").modal("toggle");
}
});
}
break;
case "edit":
if(confirm("ยืนยันการแก้ไขบัญชีผู้ใช้งาน")) {
$.post(current_web_location + "/services/user_edit.php", {
user_name: $("#modal-user-input-username").val(),
user_type: $("#modal-user-input-usertype").val(),
valid_to: $("#modal-user-input-validuntil").val(),
return_type: "TEXT"
}, function(data, status) {
system_display_dialog(data);
if(data.includes("สำเร็จ")) {
refresh_user_list();
$("#modal-user").modal("toggle");
}
});
}
break;
case "delete":
if(confirm("ยืนยันลบผู้ใช้ " + username)) {
$.post(current_web_location + "/services/user_delete.php", {
user_name: username,
return_type: "TEXT"
}, function(data, status) {
system_display_dialog(data);
if(data.includes("สำเร็จ")) {
refresh_user_list();
}
});
}
break;
}
} | [
"showModal(user) {\n this.modalContainer.style.display = \"inherit\";\n this.updateModalInfo(user);\n }",
"function onUserModify() {\n\talert(\"You try to modify a user\");\n\twindow.location.href = \"#user-list\";\n}",
"editUser( id ) {\n fluxUserManagementActions.editUser( id );\n }",
"function s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Publish a story to the user's own wall | function publishStory() {
FB.ui({
method: 'feed',
name: 'Test',
caption: 'Restaurant',
description: 'Tasty restaurant',
link: 'http://apps.facebook.com/mobile-start/',
picture: 'http://www.facebookmobileweb.com/hackbook/img/facebook_icon_large.png',
actions: [{ name: 'Get Started', link: 'http://apps.facebook.com/mobile-start/' }],
},
function(response) {
alert('successfully posted to FB page and wall');
});
} | [
"function publishStoryFriend() {\n randNum = Math.floor ( Math.random() * friendIDs.length ); \n\n var friendID = friendIDs[randNum];\n \n console.log('Opening a dialog for friendID: ', friendID);\n \n FB.ui({\n method: 'feed',\n to: friendID,\n name: 'I\\'m using the Hackbook web app',\n caption:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split the gherkin content from TestRail into lines | formatLinesFromTestrail(testcase) {
const arr = this.getGherkinFromTestcase(testcase).replace(/[\r]/g, '').split('\n')
.map(Function.prototype.call, String.prototype.trim)
.map((line) => {
// replace ” by "
return line.replace(/”/g, '"');
})
.map((line) => {
// remove extra spaces
// convert the first character to uppercase
return line.replace(/^(Given|When|Then|And)\s+(\w)/i, (match, first, second) => {
return first.charAt(0).toUpperCase() + first.slice(1) + ' ' + second.toUpperCase();
});
})
.filter((line) => line.length > 0 && line.indexOf('Scenario:') !== 0)
// replace line like: |:header1|:header2| by |header1|header2|
.map((line) => {
if (line[0] !== '|') {
return line;
}
return line.replace(/\|:/g, '|');
});
// insert a blank line before Examples
for (let i = arr.length - 1; i > 0; i--) {
if (arr[i].indexOf('Examples') === 0) {
arr.splice(i, 0, '');
}
}
return this.replaceMultiPipesTables(arr);
} | [
"pushTestCaseToTestRail(testcase, gherkin) {\n const gherkinSteps = gherkin.split('\\n')\n .slice(3)\n .map(Function.prototype.call, String.prototype.trim);\n const customGherkin = this.formatter.replaceTablesByMultiPipesTables(gherkinSteps.join('\\n'));\n if (testcase.cus... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SC is setcode in decimal. This handles all possible combinations. | function fSetcode(obj, sc) {
var val = obj.setcode,
hexA = val.toString(16),
hexB = sc.toString(16);
if (val === sc || parseInt(hexA.substr(hexA.length - 4), 16) === parseInt(hexB, 16) || parseInt(hexA.substr(hexA.length - 2), 16) === parseInt(hexB, 16) || (val >> 16).toString(16) === hexB) {
return true;
} else {
return false;
}
} | [
"getCategoryIndex(cs, ss) {\n let v, i, o, s = 1 << cs[0] | 1 << cs[1] | 1 << cs[2] | 1 << cs[3] | 1 << cs[4];\n for (i = -1, v = o = 0; i < 5; i++, o = Math.pow(2, cs[i] * 4)) {\n v += o * ((v / o & 15) + 1);\n }\n v = v % 15 - ((s / (s & -s) == 31) || (s == 0x403c) ? 3 : 1);... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get recent tracks, possible to switch user and the limit | function getRecentTracks(currentPage = 1, user = 'denniswegereef', limit = 19) {
const key = '558413ce30002869acf1d2e2d9c2047b',
url = 'http://ws.audioscrobbler.com/2.0/'
let currentUser = 'dennis'
const totalRequest = `${url}?method=user.getrecenttracks&user=${user}&api_key=${key}&format=json&page=${currentPage}&extended=1&limit=${limit}`
let promise = new Promise((resolve, reject) => {
fetch(totalRequest)
.then(res => res.json())
.then(res => resolve(res))
.catch(err => {
reject(err)
})
})
return promise
} | [
"async retrieveUserTopTracks() {\n let topTracks = await this.spotify.getMyTopTracks();\n const features = await this.getAudioFeatures(topTracks.body.items);\n return features;\n }",
"getBoughtTracks () {\n return music.getBoughtTracks().then((response) => {\n return response.data\n })\n }",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CODING CHALLENGE 535 Given a sandwich (as an array), return an array of fillings inside the sandwich. This involves ignoring the first and last elements. | function getFillings(sandwich) {
return sandwich.slice(1, -1);
} | [
"function makeSandwich(ingredients, flavour) {\n\tconst a = [];\n\tfor (let i = 0; i < ingredients.length; i++) {\n\t\tif (ingredients[i] === flavour) {\n\t\t\ta.push(\"bread\");\t\t\t\n\t\t\ta.push(ingredients[i]);\n\t\t\ta.push(\"bread\");\n\t\t} else {\n\t\t\ta.push(ingredients[i]);\n\t\t}\n\t}\n\treturn a;\n}",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a new marker object that consist of the coordinates, the formatted address, and info window | newMarker(addressCoord, addressPretty){
console.log(addressPretty)
let contentString = `
<div id="content>
<div id="siteNotice">
</div>
<h1 id="firstHeading" class="firstHeading">Current Location:</h1>
<div id="bodyContent">
${addressPretty}
</div>
</div>`;
let infowindow = new google.maps.InfoWindow({
content: contentString
});
this.markerList.push({
address: addressPretty,
location: addressCoord,
infoWindow: infowindow
});
this.initMap();
} | [
"function createMarker(point, narrative) {\n\t var marker = new GMarker(point,{draggable: false, bouncy: false});\n\t GEvent.addListener(marker, \"click\", function() {\n\t marker.openInfoWindowHtml(narrative);\n\t }); \n\treturn marker;\n}",
"function markerFactory(latitude, longitude, title, message) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
createTitleScreenBackground function creates a 2D array for holing the background of the title screen, it creates a collum of objects that is an array within an array of rows, thus filling the entire screen. This all happens once at the start of the program (see setup) | function createTitleScreenBackground() {
for (var i = 0; i < 10; i++) {
titleBackground[i] = [];
for (var j = 0; j < 8; j++) {
titleBackground[i][j] = new TitleBackground(Math.floor(random(0, width)), Math.floor(random(0, height)), random(1, 5));
}
}
} | [
"function drawBackground() {\n image(imgBackground, width / 2, height / 2); // dimensions: 100 X 56\n\n // table for tray\n rectMode(CORNER);\n fill(\"#B8F4FA\"); // light blue\n rect(0, height - 30, width, 30);\n\n image(imgTray, trayX, trayY); // tray dimensions: 130 X 78\n\n displayScore();\n drawStack... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=============================== CHECKING THE CUBE'S COMPLETION | function checkCube() {
//===============================
var check = false;
// Check each color
for(face in colorMap) {
// Check each sticker from that color
$(".color-"+colorMap[face]).each(function() {
// If the sticker isn't on the right face for its color
// Then the cube hasn't been solved yet
check = $(this).hasClass("pyramid-"+face);
return check;
});
if(!check) break;
}
return check;
} | [
"function checkUEC(targetBlock) {\n if (targetBlock.id.equals('mekanism:ultimate_energy_cube')) {\n if (!!targetBlock.entityData.EnergyContainers[0]) {\n if (!!targetBlock.entityData.EnergyContainers[0].stored) {\n if (targetBlock.entityData.EnergyContainers[0].stored == 4096000000) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |