query stringlengths 9 34k | document stringlengths 8 5.39M | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Insert a new paragraph containing the specified text into the specified div node. If present, we set the class attribitue of this div to classAttr. | function insertText(stubDiv, text, classAttr) {
var p = document.createElement('p');
if(classAttr) {
p.setAttribute('class', classAttr);
}
p.innerHTML = text;
stubDiv.appendChild(p);
} | [
"function insertText(stubDiv, text, classAttr) {\n var p = document.createElement('p');\n\n if(classAttr) {\n\tp.setAttribute('class', classAttr);\n }\n\n p.innerHTML = text;\n\n stubDiv.appendChild(p);\n}",
"function addParaToTextDiv(input) {\n $(\"<p>\").text(input).appendTo(\".text-div\");\n}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If `str` is in valid 6digit hex format with prefix, returns an RGB color (with alpha 100). Otherwise returns undefined. | function _hex6(str) {
if ('#' === str[0] && 7 === str.length && /^#[\da-fA-F]{6}$/.test(str)) {
return {
r: parseInt(str.slice(1, 3), 16),
g: parseInt(str.slice(3, 5), 16),
b: parseInt(str.slice(5, 7), 16),
a: MAX_COLOR_ALPHA
};
}
} | [
"function _hex6(str) {\n if ('#' === str[0] && 7 === str.length && /^#[\\da-fA-F]{6}$/.test(str)) {\n return {\n r: parseInt(str.slice(1, 3), 16),\n g: parseInt(str.slice(3, 5), 16),\n b: parseInt(str.slice(5, 7), 16),\n a: MAX_COLOR_ALPHA\n };\n }\n}"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dial to the peer and try to use the most recent Bitswap | _dialPeer (peer, callback) {
// Attempt Bitswap 1.1.0
this.libp2p.dialProtocol(peer, BITSWAP110, (err, conn) => {
if (err) {
// Attempt Bitswap 1.0.0
this.libp2p.dialProtocol(peer, BITSWAP100, (err, conn) => {
if (err) { return callback(err) }
callback(null, conn, BITSWAP100)
})
return
}
callback(null, conn, BITSWAP110)
})
} | [
"async _dialPeer (peer) {\n try {\n // Attempt Bitswap 1.1.0\n return {\n conn: await this.libp2p.dialProtocol(peer, BITSWAP110),\n protocol: BITSWAP110\n }\n } catch (err) {\n // Attempt Bitswap 1.0.0\n return {\n conn: await this.libp2p.dialProtocol(peer, BITSWA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Int, Bool) > String Returns 'walk' if the user should walk and 'drive' if the user should drive to their destination. The user should walk if it is nice weather and the distance is a quarter mile or less. | function walkOrDrive(miles, isNiceWeather) {} | [
"getDirectionBasedOnDistance(distX, distY){\n\n if (Math.abs(distX) > Math.abs(distY)){\n // we have to choose between right and left in normal mode\n\n if(this.state === \"normal\"){\n return (distX > 0) ? \"right\" : \"left\";\n }\n else{\n return (distX > 0) ? \"left\" : \"ri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether or not to load a module, Can be used to show/hide modules for non authenticated users. This can be customized to your own taste. | shouldLoadModule(module, req) {
if (module.requireAuth) {
return req.isAuthenticated();
}
return true;
} | [
"isModuleLoaded() {\n return !!RNSentry;\n }",
"isMainModule(){\r\n return main_module;\r\n }",
"hasModule(path){return!!this.store._modules.get(path);}",
"static isModuleEnabled(state, moduleId) {\n const isModuleEnabled = ConfigurationManager.getPublicValue(state, `idm.pub.${moduleId}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MAC_UpdateFromResponse ========= MAC_SetInfoboxesAndBtns ================ PR20210208 PR20230110 PR20230714 | function MAC_SetInfoboxesAndBtns(response) {
console.log("=== MAC_SetInfoboxesAndBtns =====") ;
// called by MAC_Save and MAC_UpdateFromResponse
// step is increased in MAC_save, response has value when response is back from server
const is_response = (typeof response != "undefined");
console.log("......................step", mod_MAC_dict.step) ;
console.log(" is_response", is_response) ;
console.log(" test_is_ok", mod_MAC_dict.test_is_ok) ;
console.log(" verification_is_ok", mod_MAC_dict.verification_is_ok) ;
// TODO is_reset
const is_reset = mod_MAC_dict.is_reset;
// --- info_container, loader, info_verifcode and input_verifcode
let msg_info_html = null;
let show_loader = false;
let show_input_verifcode = false;
let show_btn_save = false, show_delete_btn = false;
let disable_save_btn = false, save_btn_txt = null;
//++++++++ approve mode +++++++++++++++++
if(mod_MAC_dict.is_approve_mode){
if (mod_MAC_dict.step === 0) {
if (!is_response){
// step 0: when form opens and request to check is sent to server
// text: 'AWP is checking the compensations'
msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.checking_compensations + "...</div>";
show_loader = true;
} else if (response.approve_msg_html) {
msg_info_html = response.approve_msg_html;
// response with checked subjects
// msg_info_txt is in response
show_btn_save = response.test_is_ok;
//PR2023-07-11 was bug in ex4 ep3 temporary let submit again when submitted
if (show_btn_save ){
save_btn_txt = loc.Approve_compensations;
};
if (mod_MAC_dict.has_already_approved) {
show_delete_btn = true;
};
};
} else if (mod_MAC_dict.step === 1) {
// step 1: after clicked on btn Approve_subjects
if (!is_response){
// text: 'AWP is approving the compensations'
msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.approving_compensations + "...</div>";
show_loader = true;
} else if (response.approve_msg_html) {
// step 1: response after clicking on btn Approve_subjects
// response with "We have sent an email with a 6 digit verification code to the email address:"
// msg_info_html is in response.approve_msg_html
msg_info_html = response.approve_msg_html;
};
};
} else {
//++++++++ submit mode +++++++++++++++++
if (mod_MAC_dict.step === 0) {
if (!is_response){
// step 0: when form opens and request to check is sent to server
// text: 'AWP is checking the compensations'
msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.checking_compensations + "...</div>";
show_loader = true;
} else if (response.approve_msg_html) {
msg_info_html = response.approve_msg_html;
// response with checked subjects
// msg_info_txt is in response
// text 'You need a 6 digit verification code to submit the Ex form' is in response
show_btn_save = response.test_is_ok;
//PR2023-07-11 was bug in ex4 ep3 temporary let submit again when submitted
if (show_btn_save ){
save_btn_txt = loc.Request_verifcode;
};
};
} else if (mod_MAC_dict.step === 1) {
// after clicked on btn Request_verificationcode
if (!is_response){
// step 1: when clicked on 'Request verif code
// tekst: 'AWP is sending an email with the verification code'
msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.sending_verifcode + "</div>";
show_loader = true;
} else if (response.approve_msg_html) {
// step 1: response after sending request verificationcode
// response with "We have sent an email with a 6 digit verification code to the email address:"
// msg_info_html is in response.approve_msg_html
msg_info_html = response.approve_msg_html;
show_btn_save = true;
show_input_verifcode = true;
disable_save_btn = !el_MAC_input_verifcode.value;
save_btn_txt = loc.Submit_compensation_form;
};
} else if (mod_MAC_dict.step === 2) {
// step 2: after clicking on btn_save 'Submit Ex form'
if (!is_response){
msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.Creating_comp_form + "...</div>";
show_loader = true;
} else if (response.approve_msg_html) {
msg_info_html = response.approve_msg_html;
if (response.verification_is_ok){
} else {
};
};
};
};
////////////////////////////////////////
el_MAC_info_container.innerHTML = msg_info_html;
add_or_remove_class(el_MAC_info_container, cls_hide, !msg_info_html)
add_or_remove_class(el_MAC_loader, cls_hide, !show_loader)
add_or_remove_class(el_MAC_input_verifcode.parentNode, cls_hide, !show_input_verifcode);
if (show_input_verifcode){set_focus_on_el_with_timeout(el_MAC_input_verifcode, 150); };
// --- show / hide delete btn
add_or_remove_class(el_MAC_btn_delete, cls_hide, !show_delete_btn);
// - hide save button when there is no save_btn_txt
add_or_remove_class(el_MAC_btn_save, cls_hide, !show_btn_save)
// --- disable save button till test is finished or input_verifcode has value
el_MAC_btn_save.disabled = disable_save_btn;
// --- set innerText of save_btn
el_MAC_btn_save.innerText = save_btn_txt;
// --- set innerText of cancel_btn
el_MAC_btn_cancel.innerText = (show_btn_save) ? loc.Cancel : loc.Close;
} | [
"function MAC_UpdateFromResponse(response) {\n console.log(\"==== MAC_UpdateFromResponse ====\");\n console.log(\" response\", response);\n console.log(\" mod_MAC_dict\", mod_MAC_dict);\n console.log(\" mod_MAC_dict.step\", mod_MAC_dict.step);\n\n mod_MAC_dict.test_is_ok ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update d'un madbet (PUT) | function updateMadbet(req, res) {
console.log("UPDATE recu madbet : ");
console.log(req.body);
Madbet.findByIdAndUpdate(
req.body._id,
req.body,
{ new: true },
(err, madbet) => {
if (err) {
console.log(err);
res.send(err);
} else {
res.json({ message: "updated" });
}
// console.log('updated ', madbet)
}
);
} | [
"update(req,res){\r\n res.status(200).json(\r\n {\r\n sucess: true,\r\n messages: 'Estructura base PUT',\r\n errors: null,\r\n data: [{}, {}, {}]\r\n }\r\n );\r\n }",
"update(req,res){\n res.status(200).json(\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ammend today's recorded uptime in the database and add 1 to it | function augmentDate(date, newUptime) {
const connection = mysql.createConnection(database);
connection.connect();
// Update uptime to new value for today's date in the uptime table
connection.query(`UPDATE Uptime SET uptime = '${newUptime}' WHERE date = '${date}'`,
(error, results) => {
if (error) { log.error(error); }
log.silly(`Updated database uptime for ${date}, results: ${JSON.stringify(results)}`);
connection.end();
});
} | [
"function incrementUptime() {\n wifiuptime++;\n systemUptime++;\n}",
"get uptime() {\n return new Date().getTime() - this._startTime.getTime();\n }",
"uptime() {\n if (!this.startupDate) { return 0; }\n return new Date() - this.startupDate;\n }",
"function uptime(value) {\n if((days ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a ValueExpression pointing to the MetadataTreeNode that corresponds to the currently displayed/selected comment. This helps to cope with the asynchronous nature of page loading in the PreviewPanel. As soon as the ValueExpression returns something different than 'undefined' it is possible to highlight the comment in the PreviewPanel. | function getMetadataNodeForDisplayedCommentVE()/*:ValueExpression*/ {var this$=this;
if (!this.metadataNodeForDisplayedCommentVE$Im7w) {
this.metadataNodeForDisplayedCommentVE$Im7w = com.coremedia.ui.data.ValueExpressionFactory.createFromFunction(function ()/*:MetadataTreeNode*/ {
var comment/*:Comment*/ =AS3.as( this$.displayedContributionVE$Im7w.getValue(), com.coremedia.elastic.social.studio.model.Comment);
if (comment) {
var metadataTreeRoot/*:MetadataTreeNode*/ = this$.getMetadataService().getMetadataTree().getRoot();
if (metadataTreeRoot) {
return metadataTreeRoot.findChildrenBy(function (node/*:MetadataTreeNode*/)/*:Boolean*/ {
return node.getProperty(com.coremedia.cms.editor.sdk.preview.MetadataHelper.METADATA_DEFAULT_PROPERTY) === comment;
})[0];
}
}
return undefined;
});
}
return this.metadataNodeForDisplayedCommentVE$Im7w;
} | [
"function nodecommentnodevalue() {\n var success;\n if(checkInitialization(builder, \"nodecommentnodevalue\") != null) return;\n var doc;\n var elementList;\n var commentNode;\n var commentName;\n var commentValue;\n \n var docRef = null;\n if (typeof(this.doc) != 'undefin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We check the failure patterns one by one, to see if any of those appeared on the errors. If they did, we return the associated error | findAnyFailurePattern(patterns) {
const errorsAndOutput = this.errors + this.output;
const patternThatAppeared = patterns.find(pattern => {
return pattern.pattern instanceof RegExp ?
pattern.pattern.test(errorsAndOutput) :
errorsAndOutput.indexOf(pattern.pattern) !== -1;
});
return patternThatAppeared ? patternThatAppeared.errorCode : null;
} | [
"find (api, error) {\n for (let knownError of knownErrors.all) {\n if (typeof knownError.api === \"string\" && !api.name.includes(knownError.api)) {\n continue;\n }\n\n if (typeof knownError.error === \"string\" && !error.message.includes(knownError.error)) {\n continue;\n }\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
end change Movie fullscreen mode | function toggleFullScreen() {
if (!document.mozFullScreen && !document.webkitFullScreen) {
if (video.mozRequestFullScreen) {
video.mozRequestFullScreen();
} else {
video.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else {
document.webkitCancelFullScreen();
}
}
} | [
"function fullscreen(mode) {\n\tif(mode) {\n\t\tfullscreen_start();\n\t} else {\n\t\tfullscreen_end();\n\t}\n}",
"static set macFullscreenMode(value) {}",
"onFullScreen() {\n ViewPresActions.fullscreen(true);\n }",
"static set defaultIsFullScreen(value) {}",
"function makeItFullScreen()\n {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reduce the size of samples by a factor of N by decreasing the sample rate. The output contains a single (average) sample for every N consecutive samples of input. | function compress(N, samples) {
var outSize = Math.floor(samples.length / N);
var out = new Float64Array(outSize);
var rp = 0, wp = 0;
while (wp < outSize) {
var total = 0;
for (var j = 0; j < N; j++) {
total += samples[rp++];
}
out[wp++] = total / N;
}
return out;
} | [
"function downsampled(n, factor) {\n var result = [];\n var v = (factor+1) / 2;\n for (var i=0; i<n; i++) {\n result.push(v);\n v += factor;\n }\n return result;\n }",
"function mvgmn(in_a,n){\n var out_a = []\n for(j=in_a.length;j>0;j--){\n var sli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print lab open page | function printPageLabOpen(lab) {
if ( $.cookie("topo") == undefined ) $.cookie("topo", 'light');
var html = '<div id="lab-sidebar"><ul></ul></div><div id="lab-viewport" data-path="' + lab + '"></div>';
$('#body').html(html);
// Print topology
$.when(printLabTopology(),getPictures()).done( function (rc,pic) {
if ((ROLE == 'admin' || ROLE == 'editor') && LOCK == 0 ) {
$('#lab-sidebar ul').append('<li class="action-labobjectadd-li"><a class="action-labobjectadd" href="javascript:void(0)" title="' + MESSAGES[56] + '"><i class="glyphicon glyphicon-plus"></i></a></li>');
}
$('#lab-sidebar ul').append('<li class="action-nodesget-li"><a class="action-nodesget" href="javascript:void(0)" title="' + MESSAGES[62] + '"><i class="glyphicon glyphicon-hdd"></i></a></li>');
$('#lab-sidebar ul').append('<li><a class="action-networksget" href="javascript:void(0)" title="' + MESSAGES[61] + '"><i class="glyphicon glyphicon-transfer"></i></a></li>');
$('#lab-sidebar ul').append('<li><a class="action-configsget" href="javascript:void(0)" title="' + MESSAGES[58] + '"><i class="glyphicon glyphicon-align-left"></i></a></li>');
$('#lab-sidebar ul').append('<li class="action-picturesget-li"><a class="action-picturesget" href="javascript:void(0)" title="' + MESSAGES[59] + '"><i class="glyphicon glyphicon-picture"></i></a></li>');
if ( Object.keys(pic) < 1 ) {
$('.action-picturesget-li').addClass('hidden');
}
$('#lab-sidebar ul').append('<li><a class="action-textobjectsget" href="javascript:void(0)" title="' + MESSAGES[150] + '"><i class="glyphicon glyphicon-text-background"></i></a></li>');
$('#lab-sidebar ul').append('<li><a class="action-moreactions" href="javascript:void(0)" title="' + MESSAGES[125] + '"><i class="glyphicon glyphicon-th"></i></a></li>');
$('#lab-sidebar ul').append('<li><a class="action-labtopologyrefresh" href="javascript:void(0)" title="' + MESSAGES[57] + '"><i class="glyphicon glyphicon-refresh"></i></a></li>');
$('#lab-sidebar ul').append('<li class="plus-minus-slider"><i class="fa fa-minus"></i><div class="col-md-2 glyphicon glyphicon-zoom-in sidemenu-zoom"></div><div id="zoomslide" class="col-md-5"></div><div class="col-md-5"></div><i class="fa fa-plus"></i><br></li>');
$('#zoomslide').slider({value:100,min:10,max:200,step:10,slide:zoomlab});
//$('#lab-sidebar ul').append('<li><a class="action-freeselect" href="javascript:void(0)" title="' + MESSAGES[151] + '"><i class="glyphicon glyphicon-check"></i></a></li>');
$('#lab-sidebar ul').append('<li><a class="action-status" href="javascript:void(0)" title="' + MESSAGES[13] + '"><i class="glyphicon glyphicon-info-sign"></i></a></li>');
$('#lab-sidebar ul').append('<li><a class="action-labbodyget" href="javascript:void(0)" title="' + MESSAGES[64] + '"><i class="glyphicon glyphicon-list-alt"></i></a></li>');
$('#lab-sidebar ul').append('<li><a class="action-lock-lab" href="javascript:void(0)" title="' + MESSAGES[166] + '"><i class="glyphicon glyphicon-ok-circle"></i></a></li>');
if ( $.cookie("topo") == 'dark' ) {
$('#lab-sidebar ul').append('<li><a class="action-lightmode" href="javascript:void(0)" title="' + MESSAGES[236] + '"><i class="fas fa-sun"></i></a></li>');
} else {
$('#lab-sidebar ul').append('<li><a class="action-nightmode" href="javascript:void(0)" title="' + MESSAGES[235] + '"><i class="fas fa-moon"></i></a></li>');
}
$('#lab-sidebar ul').append('<div id="action-labclose"><li><a class="action-labclose" href="javascript:void(0)" title="' + MESSAGES[60] + '"><i class="glyphicon glyphicon-off"></i></a></li></div>');
$('#lab-sidebar ul').append('<li><a class="action-logout" href="javascript:void(0)" title="' + MESSAGES[14] + '"><i class="glyphicon glyphicon-log-out"></i></a></li>');
$('#lab-sidebar ul a').each(function () {
var t = $(this).attr("title");
$(this).append(t);
})
if ( LOCK == 1 ) {
lab_topology.setDraggable($('.node_frame, .network_frame, .customShape'), false);
$('.customShape').resizable('disable');
}
})
} | [
"function printPageLabOpen(lab) {\n var html =\n '<div id=\"lab-sidebar\"><ul></ul></div><div id=\"lab-viewport\" data-path=\"' +\n lab +\n '\"></div>';\n\n $('#body').html(html);\n\n // Print topology\n printLabTopology();\n\n // Read privileges and set specific actions/elements\n if (ROLE == 'admin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ownership modes: IGNORE: leave user as is REMOVE: remove reference to user OVERWRITE: set user to it | function configureOwnership() {
for (var objectType in metaData) {
//It not iterable, skip
if (!Array.isArray(metaData[objectType])) continue;
//For each object of objectType
for (var obj of metaData[objectType]) {
//Set ownersip, if applicable
if (currentExport.hasOwnProperty("_ownership") && obj.hasOwnProperty("user")) {
if (currentExport._ownership.modeOwner == "REMOVE") {
delete obj.user;
}
else if (currentExport._ownership.modeOwner == "OVERWRITE") {
obj.user = {
"id": currentExport._ownership.ownerId
};
}
}
if (currentExport.hasOwnProperty("_ownership") && obj.hasOwnProperty("lastUpdatedBy")) {
if (currentExport._ownership.modeLastUpdated == "REMOVE") {
delete obj.lastUpdatedBy;
}
else if (currentExport._ownership.modeLastUpdated == "OVERWRITE") {
obj.lastUpdatedBy = {
"id": currentExport._ownership.ownerId
};
}
}
if (currentExport.hasOwnProperty("_ownership") && obj.hasOwnProperty("createdBy")) {
if (currentExport._ownership.modeCreatedBy == "REMOVE") {
delete obj.createdBy;
} else if (currentExport._ownership.modeCreatedBy == "OVERWRITE") {
obj.createdBy = {
"id": currentExport._ownership.ownerId
}
}
}
}
}
} | [
"function setOwnership(doc, previous, options, next) {\n doc._owner = util.adminId\n next()\n}",
"function test_set_ownership_back_to_default() {}",
"function takeOwnership() {\r\n ownerRef.set(sceneSync.clientId);\r\n }",
"updateOwnership()\n {\n this._ow... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper that renders branch information. Allows props to be overriden | branch(props) {
const { required, scrollIntoView } = this.props
return (
<Branch
name={props.name}
label={props.label}
labelSize={props.labelSize}
className={props.className}
help={props.help}
{...props.value || {}}
warning={props.warning}
onUpdate={props.onUpdate}
required={required}
onError={props.onError}
scrollIntoView={scrollIntoView}
>
{props.children}
</Branch>
)
} | [
"function createBranchHTML(branch) {\n\t\tconsole.debug(\"createBranchHTML\");\n\n\t\tbranchContainer = document.createElement(\"div\");\n\t\tvar branchLabel = document.createElement(\"h3\");\n\t\tbranchLabel.style = \"float:left;\";\n\t\tbranchLabel.innerText = \"Branch \" + branch.name;\n\t\tbranchContainer.appen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add listener to burger menu | function addListenerToBurger() {
burger.addEventListener('click', function (e) {
e.preventDefault();
this.classList.toggle('active');
mainMenu.classList.toggle('active');
});
} | [
"function burger() {\n\n let burger = document.querySelector(\".burger\"),\n menu = document.querySelector(\"nav.menu\");\n\n burger.addEventListener(\"click\", ()=>{\n burger.classList.toggle(\"burger--active\")\n menu.classList.toggle(\"menu--active\")\n })\n}",
"function burgerMenu(){\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if a response timeout timer is present for a user in a chat | hasResponseTimeoutTimer(chatUserKey) {
return this.timeoutTimers[chatUserKey] != null;
} | [
"hasPresenceTimeoutTimer(chatUserKey) {\n return this.presenceTimeoutTimers[chatUserKey] != null;\n }",
"function isTimeOut()\n{\t\t\n var ajaxUrl = UrlConfig.BaseUrl + '/ajax/chat/getsystemtime';\n\n\ttry {\n\t $j.ajax({\n\t\t type: \"GET\", \n\t\t url: ajaxUrl,\n\t\t data: \"cid=\" + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main functionality: Fetch codes, handle errors including backoff | fetchCodes(iteration=iterationCurrent) {
if (this.fetchInProgress || !this.signedIn) {
return
}
if (this.lastFetch && this.lastFetch.getTime() + this.backoff > new Date().getTime()) {
// slow down spammy requests
return
}
this.lastFetch = new Date()
this.fetchInProgress=true
let successFunc= iteration == iterationCurrent ? this.updateCodes : this.updatePreFetch
if (iteration == iterationCurrent && this.preFetch !== null) {
successFunc(this.preFetch)
this.fetchInProgress = false
return
}
axios.get(`codes.json?it=${iteration}`)
.then(resp => {
successFunc(resp.data)
this.backoff = 500 // Reset backoff to 500ms
})
.catch(err => {
this.backoff = this.backoff * 1.5 > 30000 ? 30000 : this.backoff * 1.5
if (err.response && err.response.status) {
switch (err.response.status) {
case 401:
this.createAlert('danger', 'Logged out...', 'Server has no valid token for you: You need to re-login.')
this.signedIn = false
this.otpItems = []
break
case 500:
this.createAlert('danger', 'Oops.', `Something went wrong when fetching your codes, will try again in ${Math.round(this.backoff / 1000)}s...`, this.backoff)
break;
}
} else {
console.error(err)
this.createAlert('danger', 'Oops.', `The request went wrong, will try again in ${Math.round(this.backoff / 1000)}s...`, this.backoff)
}
if (iteration === iterationCurrent) {
this.otpItems = []
this.loading = true
}
})
.finally(() => { this.fetchInProgress=false })
} | [
"async function fetch_and_verify(url) {\n // There is no 'normal' end condition for this loop.\n // Instead the loop is only exited with a return or throw:\n // - an 'OK' response returns the response.\n // - an error throws an exception.\n // - a 503 response loops a few times, then throws an exception if the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: isDuplicate Check display table to make sure you don't add a movie multiple times by checking to see if the date, title, and description don't all match | function isDuplicate(row) {
var dup = false;
var title = $(':nth-child(2)',row).html();
var description = $(':nth-child(4)',row).html();
var date = $(':nth-child(5)',row).html();
var dt, ddes, dd;
$("#displayTable").find("tr").each(function() {
dt = $(':nth-child(2)',this).html();
dd = $(':nth-child(5)',this).html();
ddes = $(':nth-child(4)',this).html();
if(title == dt && description == ddes && date == dd){
dup = true;
}
//$(this).children("td:first").html(s);
});
return dup;
} | [
"function isDuplicate(widgetForm,store){\n \t\t\tfor (var x in store) {\n \t\t\t\tif (store[x].title == widgetForm.title) {\n \t\t\treturn true;\n \t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn false;\n \t\t}",
"function isDuplicateDocument() {\n for(var i = 0; i < $scope.meeting.documents.length;... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fixup, rename, and retype action targetTableId to targetCollectionId | function fixActionTargets() {
tables['actions'].forEach(function(row) {
row.targetCollectionId = row._target.slice(0,4)
delete row.targetTableId
})
} | [
"async function remapForeignKeys (tableName, foreignKeysMap, targetDb, sqlPool) {\r\n\r\n if (!foreignKeysMap) {\r\n console.log(tableName + \" has no foreign keys.\"); \r\n return;\r\n }\r\n\r\n const foreignKeys = Object.keys(foreignKeysMap);\r\n if (foreignKeys.length ==- 0) {\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The time elapsed, in seconds, after the request leaves the load balancer until a response from the target is received. | metricTargetResponseTime(props) {
try {
jsiiDeprecationWarnings.print("aws-cdk-lib.aws_elasticloadbalancingv2.ApplicationLoadBalancer#metricTargetResponseTime", "Use ``ApplicationLoadBalancer.metrics.targetResponseTime`` instead");
jsiiDeprecationWarnings.aws_cdk_lib_aws_cloudwatch_MetricOptions(props);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.metricTargetResponseTime);
}
throw error;
}
return this.metrics.targetResponseTime(props);
} | [
"elapsed() {\r\n var _a;\r\n if (this._startTime) {\r\n const endTime = (_a = this._stopTime) !== null && _a !== void 0 ? _a : Date.now();\r\n return endTime - this._startTime;\r\n }\r\n else {\r\n return 0;\r\n }\r\n }",
"_getLapElapsed() {\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts coordinates of one sprite to another. | function spritePointToSprite(point, sprite, toSprite) {
return svgPointToSprite(spritePointToSvg(point, sprite), toSprite);
} | [
"function spritePointToSprite(point, sprite, toSprite) {\n return svgPointToSprite(spritePointToSvg(point, sprite), toSprite);\n }",
"function spritePointToSprite(point, sprite, toSprite) {\r\n return svgPointToSprite(spritePointToSvg(point, sprite), toSprite);\r\n}",
"function sprite (topleft_x, top... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
open the dropdown without visiting parent link | function openDropdown(e){
// if has 'closed' class...
if(hasClass(this, 'closed')){
// prevent link from being visited
e.preventDefault();
// remove 'closed' class to enable link
this.className = this.className.replace('closed', '');
// add 'open' close
this.className = this.className + ' open';
}
} | [
"function domain_toggle() {\n $('.dropdown-submenu a.dropdown-title').on(\"click\", function(d){\n $(this).parent().siblings().children().filter('ul').hide();\n $(this).next('ul').toggle();\n d.stopPropagation();\n d.preventDefault();\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serializes the abstract list styles | serializeAbstractListStyles(writer, listStyles) {
for (let i = 0; i < listStyles.length; i++) {
let abstractList = listStyles[i];
writer.writeStartElement(undefined, 'abstractNum', this.wNamespace);
writer.writeAttributeString(undefined, 'abstractNumId', this.wNamespace, abstractList.abstractListId.toString());
writer.writeStartElement(undefined, 'nsid', this.wNamespace);
writer.writeAttributeString(undefined, 'val', this.wNamespace, this.generateHex());
writer.writeEndElement();
for (let ilvl = 0, cnt = abstractList.levels.length; ilvl < cnt; ilvl++) {
this.serializeListLevel(writer, abstractList.levels[ilvl], ilvl);
}
writer.writeEndElement(); //end of abstractNum
}
} | [
"serializeListInstances(writer, listStyles) {\n for (let i = 0; i < listStyles.length; i++) {\n let list = listStyles[i];\n writer.writeStartElement(undefined, 'num', this.wNamespace);\n writer.writeAttributeString(undefined, 'numId', this.wNamespace, (list.listId + 1).toStri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the repo remote | async setRemote({ url }) {
if (!url) return;
await spawnGit(["remote", "add", "origin", url]);
} | [
"set repo(repo) {\n this._repository = repo\n }",
"function setRepos(repos)\n{ \n repo = repos ;\n}",
"async addRemote() {\n console.log(`git remote add ${this.t262GithubOrg} ${this.t262GithubRemote}`);\n await execCmd(`git remote add ${this.t262GithubOrg} ${this.t262GithubRemote}`, {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Using what we've learned about explicit binding, let's create a 'constructor' function that creates new Order objects for us, with our calculation methods. | function OrderConstructor(amount) {
this.amount = amount;
this.calculateTax = Order.calculateTax;
this.calculateTotal = Order.calculateTotal;
return this;
} | [
"function NewOrderConstructor(amount) {\n this.amount = amount;\n}",
"function Order() {\n _classCallCheck(this, Order);\n\n Order.initialize(this);\n }",
"function Order(customerName,customerPhoneNumber){\n this.name=customerName;\n this.number=customerPhoneNumber;\n}",
"function Order(){\n this... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calendar move event handler | _moveHandler(event) {
const that = this;
if (!JQX.Utilities.Core.isMobile || !that._dragStartDetails || (that.displayModeView === 'list' && that.displayMode !== 'month')) {
return;
}
event.originalEvent.preventDefault();
event.preventDefault();
event.stopPropagation();
const details = { x: Math.round(event.pageX), y: Math.round(event.pageY) };
let step;
if (that.scrollButtonsNavigationMode === 'portrait') {
step = details.y > that._dragStartDetails.y ? -1 * that.months : 1 * that.months;
}
else {
step = details.x < that._dragStartDetails.x ? 1 * that.months : -1 * that.months;
}
const navigationDate = that._getNextDate(step);
if (!navigationDate) {
return;
}
that._dragStartDetails.step = step;
that._dragStartDetails.navigationDate = new Date(navigationDate);
if (!that.hasAnimation) {
return;
}
let animationTarget;
if (that.displayMode !== 'month') {
that.$nextMonthsContainer.addClass('jqx-calendar-date-view-container');
animationTarget = that.$.dateViewContainer;
if (!(that.$.nextMonthsContainer.children[0].value instanceof Date) ||
that.$.nextMonthsContainer.children[1].value.getFullYear() !== navigationDate.getFullYear()) {
that._setDisplayModeContent(navigationDate, that.$.nextMonthsContainer);
}
}
else {
if (that.$nextMonthsContainer.hasClass('jqx-calendar-date-view-container')) {
that.$nextMonthsContainer.removeClass('jqx-calendar-date-view-container');
}
animationTarget = that.$.monthsContainer;
if (!that.$.nextMonthsContainer.children[0]._date || that.$.nextMonthsContainer.children[0]._date.getTime() !== navigationDate.getTime()) {
let nextMonths = that.$.nextMonthsContainer.children;
for (let i = 0; i < nextMonths.length; i++) {
navigationDate.setMonth(that._dragStartDetails.navigationDate.getMonth() + i);
that._setMonth(navigationDate, nextMonths[i], true);
}
}
}
if (step < 0) {
animationTarget.style.order = 3;
that.$.nextMonthsContainer.style.order = 1;
that.$.body[that._animationSettings.scrollSize] = that.$.body[that._animationSettings.scrollMax];
}
else {
animationTarget.style.order = 1;
that.$.nextMonthsContainer.style.order = 3;
that.$.body[that._animationSettings.scrollSize] = 0;
}
const direction = that.scrollButtonsNavigationMode === 'portrait' ? 'y' : 'x';
if (Math.abs(that._dragStartDetails[direction] - details[direction]) > 10) {
that.$.body[that._animationSettings.scrollSize] += -(details[direction] - that._dragStartDetails[direction]) * 2;
}
} | [
"_moveHandler(event) {\n const that = this;\n\n if (!Smart.Utilities.Core.isMobile || !that._dragStartDetails || (that.displayModeView === 'list' && that.displayMode !== 'month')) {\n return;\n }\n\n event.originalEvent.preventDefault();\n event.preventDefault();\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Let's try some sorting. Here is an array with the specific rules. The array has various numbers. You should sort it, but sort it by absolute value in ascending order. For example, the sequence (20, 5, 10, 15) will be sorted like so: (5, 10, 15, 20). Your function should return the sorted list . Precondition: The numbers in the array are unique by their absolute values. Input: An array of numbers . Output: The list or tuple (but not a generator) sorted by absolute values in ascending order. | function absoluteSorting(numbers){
function compare(a, b) {
if (a < 0) a*=(-1);
if (b < 0) b*=(-1);
return a - b;
}
return numbers.sort(compare);
} | [
"function absoluteSorting(arr) {\n\treturn arr.sort((a, b) => {\n\t\treturn Math.abs(a) - Math.abs(b);\n\t});\n}",
"function sort(array) {\n\n}",
"function greatestToLeast(arr) {\n return arr.sort((num1,num2) => {\n //console.log(num1, num2 )\n return (num2 - num1)\n })\n}",
"function grea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/////////////// Use the stripe api to combine products and prices based on unique product id. | async function s() {
const list = []
for (let i = 0; i < packageIDs.length; i++) {
try {
let price_with_product = await stripe.prices.list({
product: packageIDs[i],
expand: ['data.product'],
})
list.push({
product: price_with_product.data[0].product,
price: price_with_product.data[0].unit_amount
});
} catch (err) {
console.error(err);
}
}
return list;
} | [
"getProductPrice(id) {\r\n\t\tlet select = [\"pw_price.id_price\", \"id_currency\", \"id_tax\", \"purchase_net\", \"purchase_gross\", \"purchase_type\", \"wholesale_net\", \"wholesale_gross\", \"wholesale_type\", \"sale_net\", \"sale_gross\", \"sale_type\"];\r\n\t\tlet prepare = db(\"pw_price\");\r\n\t\tlet where =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION: upsert_delta_modified() PURPOSE: The same element can be modified many times within a transaction on same element repeat modifications, only the last one matters if it's not a repeat, push it to delta.modifications | function upsert_delta_modified(me, entry) {
// look for matching modifieds, if found, replace
for (var i = 0; i < me.delta.modified.length; i++) {
var op_path = me.delta.modified[i].op_path;
if (subarray_elements_match(op_path, me.op_path, "K")) {
me.delta.modified[i] = entry;
return;
}
}
me.delta.modified.push(entry);
} | [
"function updateItem(delta) {\n return Item.findOne({\"_id\":delta._id}).then(function(item) {\n let newDescription;\n let newCost;\n let newQuantity;\n if (delta.description) {\n newDescription = delta.description;\n } else {\n newDescription = item.description;\n }\n if (delta.cost... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function$prototype$contramap :: (b > c) ~> (a > b) > (a > c) | function Function$prototype$contramap(f) {
var contravariant = this;
return function(x) { return contravariant (f (x)); };
} | [
"function compare$contramap(f) {\n return Compare((x,y) => this.compare(f(x), f(y)))\n}",
"function Function$prototype$contramap(f) {\n var contravariant = this;\n return function(x) { return contravariant(f(x)); };\n }",
"function mappedAsc(map) {\n\n return function (a, b) {\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getCommandInput Returns editor's command input. | getCommandInput() {
return this.commandInput;
} | [
"function getCommandInput()\n {\n var lastLine = $(_consoleSelector).val().split('\\n')[$(_consoleSelector).val().split('\\n').length-1];\n var lastLineSplit = lastLine.split(_promptSymbol);\n var command = \"\";\n var i; \n\n for(i =1; i < lastLineSplit.length; i ++)\n {\n command = command... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Internal Helper Functions converts the given number to string and pads it to match at least the given length. The pad value is added in front of the string. This padNumber(4, 5, 0) would convert 4 to '00004' | function padNumber(num, length, pad){
num = String(num);
while (num.length < length){
num = String(pad) + num;
}
return num;
} | [
"function pad(number, length){\r\n var str = \"\" + number\r\n while (str.length < length) {\r\n str = '0'+str\r\n }\r\n return str\r\n}",
"function pad(number) \n{ \n\tif(number < 10 && String(number).substr(0,1) == '0')\n\t{\n\t\treturn number;\n\t}\n \n\treturn (number < 10 ? '0' : '') +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns num as a hexadecimal string, padded to length characters by adding leading 0's. | function intToHex(num, length) {
var ret = num.toString(16);
while (ret.length < length) {
ret = '0' + ret;
}
return ret;
} | [
"function hexStr(num, length, prefix) {\n let str = \"\";\n if (prefix === undefined || prefix === true) str += \"0x\";\n else if (prefix === false) str = \"\";\n else str = prefix;\n return str + num\n .toString(16)\n .toUpperCase()\n .padStart(length, \"0\");\n}",
"function t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wrap SocialShare in order to plug into Container necessary tradeoff to deal with class component in the store connector | function SocialShareWrapper (props) {
return html`
<buv-social-share-raw
url='${props.url}'
onShare='${props.onShare}'
display='${props.display}'
></buv-social-share-raw>`;
} | [
"function ShareSDKPlugin () {}",
"function Share(hoodie) {\n var api;\n this.hoodie = hoodie;\n this._open = this._open.bind(this);\n\n // set pointer to Hoodie.ShareInstance\n this.instance = Hoodie.ShareInstance;\n\n // return custom api which allows direct call\n api = this._open;\n $.e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update an adaptive card | async function update_card( p, cardId, card ) {
console.log("Updating card...");
try {
var resp = await p.put(`/team-messaging/v1/adaptive-cards/${cardId}`, card)
}catch (e) {
console.log(e.message)
}
} | [
"async function update_card( cardId, card ) {\n console.log(\"Updating card...\");\n try {\n var resp = await platform.put(`/team-messaging/v1/adaptive-cards/${cardId}`, card)\n }catch (e) {\n\t console.log(e.message)\n\t }\n}",
"function updateCard() {\n\n // 6-1 Create the payload object.\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a text element that can be styled (actually a hidden ), and adds it to the specified node. Also, adds parameters to the element and its style as specified. Returns the new element. | function addStyledText(node, text, style_params, params) {
node.appendChild(document.createElement("span"));
if (params != undefined) {
var index = 1;
while (index < params.length) {
node.lastChild[params[index-1]] = params[index];
index += 2;
}
}
if (style_params != undefined) {
var index = 1;
while (index < style_params.length) {
node.lastChild.style[style_params[index-1]] = style_params[index];
index += 2;
}
}
node.lastChild.appendChild(document.createTextNode(text));
return node.lastChild;
} | [
"function appendTextChild(text, node, element, idname) {\n\n // Check input.\n if ( text === undefined || text === null || node === undefined\n || node === null || element === undefined || element === null) {\n return null;\n }\n\n // Create styled text node.\n var txt = document.createTextNode(text);\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if given commit hash is referenced. | hasCommit(commitHash) {
return this.namesPerCommit.has(commitHash);
} | [
"static isCommitHash(target) {\n return !!target && /^[a-f0-9]{5,40}$/.test(target);\n }",
"async function commitExists(commit) {\n try {\n await execGitCommand(`git cat-file -e \"${commit}^{commit}\"`);\n return true;\n } catch (error) {\n return false;\n }\n}",
"existingCommit(commit) {\n l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge action as found on wit.ai story, returns a js promise with new context | merge({sessionId, context, entities, text}) {
console.log(`Session ${sessionId} received`);
console.log(`The current context is ${JSON.stringify(context)}`);
console.log(`Wit extracted ${JSON.stringify(entities)}`);
// Reset the weather story
// Retrive the location entity and store it in the context field
var loc = firstEntityValue(entities, 'location')
if (loc) {
context.loc = loc
}
// Reset the cutepics story
delete context.borrowrequest
// //Inflight Requests
// var time = firstEntityValue(entities, 'intent')
// if (time) {
// context.time = time
// }
// Retrieve Requests
var borrowrequest = firstEntityValue(entities, 'borrowrequest')
if (borrowrequest) {
context.rawrequest = borrowrequest
}
// Retrieve the category
var category = firstEntityValue(entities, 'category')
if (category) {
context.cat = category
}
// Retrieve the sentiment
var sentiment = firstEntityValue(entities, 'sentiment')
if (sentiment) {
context.feedback = text
context.feedbackSentiment = sentiment
}
return Promise.resolve(context);
} | [
"_deployAction(action) {\n return new Promise(\n (resolve, reject) => {\n let action_name = Object.keys(action)[0];\n let action_info = action[action_name];\n if (action_info === null || typeof(action_info) === \"undefined\") {\n reje... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the resolved handler to the actions set | addResolvedHandler(lifecycle, action, handler) {
const handlers = this.getActionHandlers(lifecycle, action);
if (handlers) {
handlers.add(handler);
}
else {
this.hooks[lifecycle].set(action, new Set([handler]));
}
} | [
"addHandler(handler) {\n this.handlers.push(handler);\n }",
"addActions() {\n this.addAction('index', this.actionIndex);\n this.addAction('submit', this.actionSubmit);\n }",
"add(lifecycle, action, handler) {\n const handlers = this.hooks[lifecycle].get(action);\n if (handlers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that the actual value is within a minimum on the bound of the expected value. All arguments must be in the same units. | function assertLowerBound(expected, actual, bound) {
assert.gte(actual, expected - bound);
} | [
"isMin(value, limit) {\n return parseFloat(value) >= limit;\n }",
"beLessThanOrEqualTo() {\n this._processArguments(arguments);\n return this._assert(\n this._actual <= this._expected,\n '${actual} is less than or equal to ${expected}.',\n '${actual} is not less than or eq... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the stark path based on the layer, application, eth address and a given index. layer is a string representing the operating layer (usually 'starkex'). application is a string representing the relevant application (For a list of valid applications, refer to ethereumAddress is a string representing the ethereum public key from which we derive the stark key. index represents an index of the possible associated wallets derived from the seed. | function getAccountPath(layer, application, ethereumAddress, index) {
const layerHash = hash
.sha256()
.update(layer)
.digest('hex');
const applicationHash = hash
.sha256()
.update(application)
.digest('hex');
const layerInt = getIntFromBits(layerHash, -31);
const applicationInt = getIntFromBits(applicationHash, -31);
// Draws the 31 LSBs of the eth address.
const ethAddressInt1 = getIntFromBits(ethereumAddress, -31);
// Draws the following 31 LSBs of the eth address.
const ethAddressInt2 = getIntFromBits(ethereumAddress, -62, -31);
return `m/2645'/${layerInt}'/${applicationInt}'/${ethAddressInt1}'/${ethAddressInt2}'/${index}`;
} | [
"function queryLayers(index = 0) {\n const layer = searchLayers[index];\n if (layer.type === 'feature') {\n const params = layer.createQuery();\n params.returnGeometry = true;\n params.where = idField\n ? `${idField} = '${feature.attributes[idField]}'`\n : `organizat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Canvas 2D filter backend. | function Canvas2dFilterBackend() {} | [
"function applyFilterInCanvas() {\n tool.filter = currFilter;\n tool.drawImage(img_container, 0, 0, canvas.width, canvas.height);\n tool.filter = \"none\";\n}",
"function filterCanvas(filter)\n{\n\tif (canvas.width > 0 && canvas.height > 0)\n\t{\n\t\tvar imageData = ctx.getImageData(0, 0, canvas.width, canvas.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable submit inputs in the given form | function disableSubmitButtons(form) {
form.find('input[type="submit"]').attr('disabled', true);
form.find('button[type="submit"]').attr('disabled', true);
} | [
"disable () {\n var els = this.formEls,\n i,\n submitButton = this.getSubmitButtonInstance();\n this.setPropertyAll('disabled', true);\n // add disabled css classes\n for (i = 0; i < els.length; i++) {\n els[i].classList.add('disabled');\n }\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check config for embedded flag | function isEmbedded(config) {
return config && (config.embedded === 'always' || config.embedded === 'load');
} | [
"configIsValid(config) {\n return true;\n }",
"function hasControlConfig (control) {\n return control.hasAttribute('vfp:config') || control.getElementsByTagName('vfp:config')[0] != undefined; \n}",
"function checkConfig(){\n for(let i in configuration)\n if(configuration[i]==null)\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Format the given error before it is serialized and sent to the client | function formatError(error) {
const extensions = error.extensions || {};
const originalError = error.originalError || {};
const code = extensions.code || originalError.code;
const headers = originalError.headers || {};
const traceId = extensions.traceId || originalError.traceId || headers['x-trace-id'];
const requestId = extensions.requestId || originalError.requestId || headers['x-request-id'];
// Include the HTTP status code, trace ID and request ID if they exist. These can come from
// the underlying HTTP library such as axios. Including this information in the error for the
// benefit of the client that made the request.
//
// The `extensions` field conforms with the GraphQL format error specification, section 7.1.2
// @see https://graphql.github.io/graphql-spec/June2018/#sec-Errors
// N.B. Need to create a new error in order to avoid any potential read-only issue trying to
// modify the given error
const newError = new Error();
// According to section 7.1.2 of the GraphQL specification, fields `message`, and `path` are
// required. The `locations` field may be included.
newError.message = determineErrorMessage(error);
newError.path = error.path;
if (error.locations) {
newError.locations = error.locations;
}
const newExts = {};
newError.extensions = newExts;
if (code) {
newExts.code = code;
}
if (traceId) {
newExts.traceId = traceId;
}
if (requestId) {
newExts.requestId = requestId;
}
return newError;
} | [
"function formatError() {\r\n\t\terror(format.apply(this, arguments));\r\n\t}",
"function formatError (e) {\n let err = new HttpValidationError();\n if (e.data && e.data.hasOwnProperty('GetFormattedErrors')) {\n err.msgLong = e.data.GetFormattedErrors().map((err) => { return err.message; }).toString();\n } ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`_readObject` reads a quad's object | _readObject(token) {
switch (token.type) {
case 'literal':
// Regular literal, can still get a datatype or language
if (token.prefix.length === 0) {
this._literalValue = token.value;
return this._readDataTypeOrLang;
} // Pre-datatyped string literal (prefix stores the datatype)
else this._object = this._literal(token.value, this._namedNode(token.prefix));
break;
case '[':
// Start a new quad with a new blank node as subject
this._saveContext('blank', this._graph, this._subject, this._predicate, this._subject = this._blank());
return this._readBlankNodeHead;
case '(':
// Start a new list
this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL);
this._subject = null;
return this._readListItem;
case '{':
// Start a new formula
if (!this._n3Mode) return this._error('Unexpected graph', token);
this._saveContext('formula', this._graph, this._subject, this._predicate, this._graph = this._blank());
return this._readSubject;
default:
// Read the object entity
if ((this._object = this._readEntity(token)) === undefined) return; // In N3 mode, the object might be a path
if (this._n3Mode) return this._getPathReader(this._getContextEndReader());
}
return this._getContextEndReader();
} | [
"function readSOR(){\n var SORObj = readFile();\n //reset all the variables and arrays then load them in like this\n if(SORObj!=null){\n var numV=0;\n meshObject.isMostRecent = false;\n objectList.push(new MeshObject(5000));\n objectList[objectList.length-1].alphaKey = 255-(objectList.length); \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a boolean, whether the text includes any content written by the person tweeting. | get written() {
const autoPattern1 = new RegExp("with @Runkeeper.");
return !autoPattern1.test(this.text);
} | [
"function textConsented(){\n if(ecnt==null||ecnt.length==0)\n return false;\n if(ecnt.indexOf(\"text\")>-1||ecnt.indexOf(\"both\")>-1)\n return true;\n else\n return false;\n}",
"static userMentioned(text) {\n\n if(text.includes(\"<@\")) return true;\n return false;\n \n }",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate the male population percounty given the population data | function accumulateFemalePopulationPerCounty(population_arr,counties_arr)
{
const female_population_pre_county = [];
for (let i = 0; i < counties_arr.length; i++)
{
let female = 0;
for (let j = i; j < population_arr.length; j++)
{
if (counties_arr[i] === population_arr[j].county)
{
female += population_arr[j].female;
}
}
female_population_pre_county.push(female);
}
return female_population_pre_county;
} | [
"function accumulateMalePopulationPerCounty(population_arr,counties_arr)\n{\n const male_population_pre_county = [];\n for (let i = 0; i < counties_arr.length; i++)\n {\n let male = 0;\n for (let j = i; j < population_arr.length; j++)\n {\n if (counties_arr[i] === population... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle upload logo functionnality | function handleUploadLogo($, meta_image_frame) {
$('#lc_swp_upload_logo_button').click(function(e) {
e.preventDefault();
openAndHandleMedia($, meta_image_frame, '#lc_swp_logo_upload_value', '#lc_logo_image_preview img', "Choose Custom Logo Image", "Use this image as logo");
});
$('#lc_swp_remove_logo_button').click(function(){
$('#lc_logo_image_preview img').attr('src', '');
$('#lc_swp_logo_upload_value').val('');
})
} | [
"function _uploadLogo() {\n $scope.deleteLogoFlag = true;\n $scope.submitDisable = true;\n serverRequestService.upload($scope.logoImageVar, ADD_EDIT_PROJECT_CTRL_API_OBJECT.uploadDocs, 'doc').then(function(res) {\n if (res) {\n $scope.project.logoImageId = res._id;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds "_ptr" on to the end of type identifiers that might need it; note that this operates on identifiers, not definitions | function regularizeTypeIdentifier(identifier) {
return identifier.replace(/(_(storage|memory|calldata))((_slice)?_ptr)?$/, "$1_ptr" //this used to use lookbehind for clarity, but Firefox...
//(see: https://github.com/trufflesuite/truffle/issues/3068 )
);
} | [
"function restorePtr(identifier) {\n return identifier.replace(/(?<=_(storage|memory|calldata))$/, \"_ptr\");\n }",
"pointer(ptr) {\n\t\tif (!ptr) {\n\t\t\tthis.dword(0x00000000);\n\t\t\treturn;\n\t\t}\n\t\tlet { address = ptr.mem } = ptr;\n\t\tthis.dword(address);\n\t\tif (address > 0) {\n\t\t\tthis.dw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
INPUT: [1,2,3,4,5,6] OUTPUT: 3 COMMENTS: 2+4+6=12, 1+3+5=9, 129=3 INPUT: [3,5,7,9] OUTPUT: 24 INPUT: [2,4,6,8,10] OUTPUT: 30 HINT: Parse each string to number Create two variables for even and odd sum Iterate through all elements in the array with forof loop and check if the number is odd or even Print the difference | function main(inputArray){
let evenSum = 0;
let oddSum = 0;
for(let num of inputArray){
if(num % 2 == 0){
evenSum += num;
}else{
oddSum += num;
}
}
let difference = eveSum - oddSum;
console.log(difference);
} | [
"function sum(str){\n sum_even=0;\n sum_odd=0;\n let len=str.length;\n console.log(len);\n for(let i=0;i<len;i++){\n if(str[i]%2==0)\n sum_even+=parseInt(str[i]);\n else\n sum_odd+=parseInt(str[i]);\n }\n console.log(sum_even); console.log(sum_odd);\n if(sum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check two dates has the same year and month | static isSameYearMonth(dateA, dateB) {
return (
dateA.getFullYear() === dateB.getFullYear()
&& dateA.getMonth() === dateB.getMonth()
);
} | [
"_hasSameMonthAndYear(d1, d2) {\n return !!(d1 && d2 && this._dateAdapter.getMonth(d1) == this._dateAdapter.getMonth(d2) &&\n this._dateAdapter.getYear(d1) == this._dateAdapter.getYear(d2));\n }",
"function isEqualMonth(a, b) {\n if (a == null || b == null) {\n return false\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
slantScale :: Float > Vector > Vector | function slantScale(r, [a, b]) {return [r*a, r*b];} | [
"function scaleVector(v, s) {\n v[0] *= s;\n v[1] *= s;\n return v;\n }",
"static scale(v, s){\n\t\t\treturn new Vector(v.x*s, v.y*s, v.z*s);\n\n\t}",
"function scale( s, v1 ) { return [ s * v1[0], s * v1[1], s * v1[2] ]; }",
"function vScale(a, c) {\n return vec(a.x * c, a.y * c);\n}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Manage the "display all bot commands" command | function manageDisplayAllBotCommand( client, channel, tags ) {
let output = "";
sayWhoseCommands(client, channel, tags);
// Bot Commands Message
output = "Bot Commands: " + displayAllVideo + " | " + displayAllSound + " | " + displayAllBotCommand + " | ";
for ( var i = 0; i < botCommandsJson.length; i++ ) {
if ( checkCommandRights(tags, botCommandsJson[i].commandRight) ) {
if ( ( output.length + botCommandsJson[i].commandString.length + " | ".length ) >= 500 ) {
output = output.slice(0,-3);
client.say(channel,output);
output = "Bot Commands: ";
}
output += botCommandsJson[i].commandString + " | ";
}
}
output = output.slice(0,-3);
client.say(channel,output);
return true;
} | [
"function processShowAllCommands(bot, channelID) {\n const storedMessages = db.get('messages');\n const availableCommands = [];\n for (let message of storedMessages) {\n availableCommands.push(' !' + message.command + ' ');\n }\n\n bot.sendMessage({\n to: channelID,\n message: 'A... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
String > Promise[Any] Makes a PreprocessedView request for the indicated view and returns a promise for the returned data | function requestViewAsync(view, instanceId) {
var params = { viewFileName: view, paramNames: "ImagePrefix", paramValues: getImagePrefix(instanceId) },
cache = !!instanceId;
if (instanceId) {
params.instanceId = instanceId;
}
return makeServiceGetRequestAsync("Forms/PreprocessedView", params, cache);
} | [
"async index ({ request, response, view }) {\n const rawContent = await RawContent.query().fetch()\n return rawContent\n }",
"async patientView (ctx) {\n console.log('CONTROLLER HIT: PatientView::patientView');\n return new Promise ((resolve, reject) => {\n const query = 'SELECT *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a node to the scene and keep its pose updated using the anchorOffset | addAnchoredNode(anchorOffset, node){
this.anchoredNodes.push({
anchorOffset: anchorOffset,
node: node
})
this.scene.add(node)
} | [
"addAnchoredNode(anchor, node){\n\t\tif (!anchor || !anchor.uid) {\n\t\t\tconsole.error(\"not a valid anchor\", anchor)\n\t\t\treturn;\n\t\t}\n\t\tthis._anchoredNodes.set(anchor.uid, {\n\t\t\tanchor: anchor,\n\t\t\tnode: node\n\t\t})\n\t\tnode.anchor = anchor\n\t\tnode.matrixAutoUpdate = false\n\t\tnode.matrix.from... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scrolls an unrendered event into view. Internal function used from scrollResourceEventIntoView. | scrollUnrenderedEventIntoView(resourceRec, eventRec, options = defaultScrollOptions$3) {
if (options.edgeOffset == null) {
options.edgeOffset = 20;
}
const me = this,
scroller = me.timeAxisSubGrid.scrollable,
box = me.getResourceEventBox(eventRec, resourceRec), // TODO: have all "box" type objects use Rectangle
scrollerViewport = scroller.viewport,
targetRect = new Rectangle(box.start, box.top, box.end - box.start, box.bottom - box.top).translate(
scrollerViewport.x - scroller.x,
scrollerViewport.y - scroller.y
),
result = scroller.scrollIntoView(targetRect, Object.assign({}, options, { highlight: false }));
if (options.highlight || options.focus) {
const detatcher = me.on({
eventrepaint({ scheduler, eventRecord, resourceRecord, element }) {
if (eventRecord === eventRec) {
detatcher();
result.then(() => {
options.highlight && DomHelper.highlight(element);
options.focus && element.focus();
});
}
}
});
}
return result;
} | [
"scrollUnrenderedEventIntoView(resourceRec, eventRec, options = defaultScrollOptions$3) {\n // We must only resolve when the event's element has been painted\n // *and* the scroll has fully completed.\n return new Promise(resolve => {\n const me = this,\n // Knock out highlight and focus op... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the request is valid based on the security hash and the destination path received | function isValidCredential(req){
return uploadCredential.isValid(req.query.security_hash, destPath);
} | [
"checkRequestUrl(details) {\n if (details.url === null || details.url.length === 0) {\n return false;\n }\n\n var currentCheckUrl = this.masterURL;\n if (this.redirectURL !== null) {\n currentCheckUrl = this.redirectURL;\n }\n if (currentCheckUrl === null || currentCheckU... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows a down arrow | function showArrowDown(e) {
e.target.childNodes[1].classList.add('fa-long-arrow-alt-down')
e.target.childNodes[1].classList.remove('fa-long-arrow-alt-up')
} | [
"get arrow_downward () {\n return new IconData(0xe5db,{fontFamily:'MaterialIcons'})\n }",
"function downArrow() {\r\n\t\t\t$down_arrow.css({\r\n\t\t\t\t'margin-top': 22,\r\n\t\t\t\topacity: 1\r\n\t\t\t}).delay(100).animate({\r\n\t\t\t\topacity: 0,\r\n\t\t\t\t'margin-top': 40\r\n\t\t\t}, 600, 'swing', downArro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that every course is already in the system. It looks for the "code". It throws an error in case the entity is not found. | async function checkForCoursePresence(entities) {
await updateAndSort("COURSE", Course.getComparator("code"));
entities.forEach((entity) => getCourseIdFromCode(entity.Code));
} | [
"isCourseExist()\n\t{\n\t\tfor (var i = 0; i < courseDB.length; i++) \n\t\t{\n\t\t\tif (courseDB[i].cid === this.cid) \n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}",
"checkNewCourse(courseCode) {\n return __awaiter(this, void 0, void 0, function* ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the specified node in the graph is a subgraph node. A subgraph node is one that contains other nodes. | function isSubgraph(g,v){return!!g.children(v).length} | [
"function isSubgraph(g, v) {\n return g.hasOwnProperty(\"children\") && g.children(v).length;\n}",
"function isSubgraph(g, v) {\n return !!g.children(v).length;\n}",
"function inSubTree(n,p) {\n if(n == p) {\n return true\n } else if(typeof n.parent === 'undefined') {\n return false;\n } else {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomize function which will do the put all the pieces together: randomize the seating list and shuffle it a given number of times, creating a individual seating lists for each course/switch. | function randomize(employeesList, numPlacesPerTable, numTables, numSwitches) {
// 1st step - set some initial variables.
var numGuests = employeesList.length;
var employeesArrays = arrayCreator(employeesList, numSwitches);
var employees = courseIterator(employeesArrays, numGuests);
// 2nd step - randomize the guest list and give output.
var mixed = shuffle(employees[0]);
var courseOne = `For the course no 1: \n`;
var tableNo = 1;
var init = 0;
for (var s = 0; s <= mixed.length-1; s = s+numPlacesPerTable) {
var currentTable = mixed.slice(init+s,s+numPlacesPerTable);
courseOne = courseOne.concat(`Table ${tableNo}: ${currentTable.toString()}. \n`);
tableNo = tableNo + 1;
}
console.log(courseOne);
employees[0] = mixed;
// 3rd step - do the switches.
placeSwitcher(employees, numGuests, numSwitches, numPlacesPerTable, numTables);
} | [
"function generateTrialLists() {\n\t/* Generic counter. Necessary for while loops below. */\n\tvar counter = 0;\n /* Generate interleaved list */\n if (experiment.condition === \"interleaved\") {\n /* Appends a pair of Bruno and Ron paintings, but the order of which is first\n in the pairing is randomize... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the currently selected folder | GetSelectedFolder() {
console.debug(`ContaplusModel::GetSelectedFolder`)
return this.config.get("folder")
} | [
"function GetSelectedDirectory()\n{\n return getSelectedDirectoryURI();\n}",
"function getCurrentFolderObject(){\n\tif(document.getElementById(\"selectedFolder\").children[0].innerHTML === \"Home of \"+folderData.Name){\n\t\treturn folderData;\n\t}\n\treturn searchCurrentFolderObjectRec(folderData.Folders);\n}",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This funcion adds the currentBeer to the local storage First we instantiate a new object from the "currentBeer"state, and then we do the same with the beer list, this is only a temporary variable, its not used outside the function. We then check the temporary beer list if its empty, remember this is a full copy of the "myBeerList"state, so in theory we're checking if the "myBeerList"state is null. If it is null, this means that we have to create an empty array object, push the "currentBeer"object into it and set it as the "myBeerList"state. If we dont do set it as an empty array objece, it will be a null, and the .push()function we perform afterwards will send out an error. If the tempBeerList is not null push the "currentBeer"object into the tempBeerList and set it as the "myBeerList"state | addToLocalStorage() {
const currentBeer = this.state.currentBeer;
let tempBeerList = this.state.myBeerList;
if(tempBeerList == null) {
tempBeerList = [];
tempBeerList.push(currentBeer);
this.setState(
{
myBeerList: tempBeerList
});
} else {
tempBeerList.push(currentBeer);
this.setState(
{
myBeerList: tempBeerList
});
}
localStorage.setItem("myBeerList", JSON.stringify(tempBeerList));
} | [
"loadDatafromLocalStorage(){\n const savedBeerList = localStorage.getItem(\"myBeerList\");\n\n if(savedBeerList !== '') {\n this.setState({\n myBeerList: JSON.parse(savedBeerList)\n });\n }\n\n\n }",
"function updateStorageBeer() {\n var beerString = J... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens a web by id (using POST) | openWebById(webId) {
return this.clone(Site_1, `openWebById('${webId}')`).postCore().then(d => ({
data: d,
web: Web.fromUrl(d["odata.id"] || d.__metadata.uri),
}));
} | [
"function OpenPostExternal(postId){\n shell.openExternal('https://www.wnmlive.com/post/'+postId) ;\n }",
"function openEditPage(id) {\r\n window.open(\"https://myanimelist.net/ownlist/anime/\" + id + \"/edit\", '_blank');\r\n }",
"function openChatSwapplace(id) {\n\n window.location.assig... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function is use to Delete file attachment | function deleteFileAttachment(req, res) {
var toDelete;
if (req.body.isTemp) {
toDelete = {temp_deleted: true};
}
else {
toDelete = {deleted: true};
}
attachmentFile.findOneAndUpdate({_id: req.body.attachmentId}, toDelete).exec(function(err, data) {
if (err) {
res.json({code: Constant.ERROR_CODE, message: err});
} else {
res.json({code: Constant.SUCCESS_CODE, message: Constant.FILE_DELETE, data: data});
}
});
} | [
"function deleteAttachment() {\r\n\tsimpleDialog(langOD27, langOD28,null,null,null,langCancel,\r\n\t\t\"$('#div_attach_upload_link').show();$('#div_attach_download_link').hide();$('#edoc_id').val('');enableAttachImgOption(0);\",langDelete);\r\n}",
"async deleteAttachment() {\n\t\tif (!this.canDeleteAttachment()) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get total value by column Id in data island | function getTotalValue(columnId) {
var result = 0;
var rowid = surchargePointsGrid1.recordset("ID").value;
first(surchargePointsGrid1);
while (!surchargePointsGrid1.recordset.eof) {
var sValue = surchargePointsGrid1.recordset(columnId).value;
if (!isEmpty(sValue) && isSignedInteger(sValue)) {
result = result + parseInt(sValue);
}
next(surchargePointsGrid1);
}
first(surchargePointsGrid1);
selectRow("surchargePointsGrid", rowid);
return result;
} | [
"getValorTotal(){\n var total = 0.0;\n this.itens.forEach(function(item) {\n total += item.getValorTotal();\n });\n\t\treturn total;\n }",
"function getPrecioTotal(){\n var precioTotal = 0;\n $(\"#tabla-detalle tbody tr\").each(function(index){\n var pre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main core dispatcher Receives request and response objects Runs installed middlewares globally or depending of the request information (URI, method, etc) After this runs BundleControllerAction depending of the request information Collects returned response from controlleraction and depending of it's contents understands what to do: 1) if it is regular Response class returned then it should be html/... 2) if it is XMLResponse, JSONResponse, NotFoundResponse etc then perform needed content type 3) if helper function of the controller class was used: this.render(), this.echo(), then ... 4) Controller class will have for sure following methods: getRequest() (getHeaders(), getCookie(s), get..) getResponse() (setHeader(s), setCookie(), set..) 5) Controller can throw exception, then depending of exception we'll set response code and render template | dispatcher(req, res)
{
this.runPreDispatchHooks(req, res);
// TODO: run middlewares arranged by priorities
// TODO: instantiate request and response singletones
// TODO: check what URL and other request information
// TODO: find Bundle-Controller-Action situated for request
// TODO: if not found Bundle-Controller-Action then show 404 page
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
// TODO: post-dispatch hook
} | [
"async dispatch(input) {\n let output;\n try {\n // Execute global request interceptors\n if (this.requestInterceptors) {\n for (const requestInterceptor of this.requestInterceptors) {\n await requestInterceptor.process(input);\n }... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates new frame aligned to right of other | rightOf(other) {
return new Frame(other.origin.x + other.size.width, this.origin.y, this.size.width, this.size.height);
} | [
"rightOf(other) {\n return new Frame(other.origin.x + other.size.width, this.origin.y, this.size.width, this.size.height);\n }",
"leftOf(other) {\n return new Frame(other.origin.x - this.size.width, this.origin.y, this.size.width, this.size.height);\n }",
"leftOf(other) {\n return new Frame(other... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1 is push, 2 is pull and 3 is print min and max | function minMax(arr){
const stack = new MinMaxStack()
let command, int
for(let i = 0, len = arr.length; i < len; i++){
[command, int] = arr[i]
switch(command){
case '1':
console.log('adding ', int)
stack.push(int)
break;
case '2':
console.log('removing ', stack.peak())
stack.pull()
break;
case '3':
console.log('max is: ', stack.currentMax())
console.log('min is: ', stack.currentMin())
break;
default:
console.log('Wrong command')
}
}
} | [
"function getPopRange(input) {\n var mx = document.getElementById('hiPop').innerHTML;\n document.getElementById('popden_range').max = mx;\n var mn = document.getElementById('lowPop').innerHTML;\n document.getElementById('popden_range').min = mn;\n var unit = (mx - mn) / 100;\n document.getElementB... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a JV3 floppy disk file. | function decodeJv3FloppyDisk(binary) {
let error;
const annotations = [];
const sectorInfos = [];
// Read the directory.
let sectorOffset = HEADER_SIZE;
for (let i = 0; i < RECORD_COUNT; i++) {
const offset = i * 3;
if (offset + 2 >= binary.length) {
error = "Directory truncated at entry " + i;
break;
}
const track = binary[offset];
const sector = binary[offset + 1];
const flags = binary[offset + 2];
const sectorInfo = new SectorInfo(track, sector, flags, sectorOffset);
sectorOffset += sectorInfo.size;
if (!sectorInfo.isFree()) {
if (sectorOffset > binary.length) {
error = `Sector truncated at entry ${i} (${sectorOffset} > ${binary.length})`;
break;
}
annotations.push(new ProgramAnnotation_1.ProgramAnnotation("Track " + sectorInfo.track + ", sector " +
sectorInfo.sector + ", " + sectorInfo.flagsToString(), offset, offset + 3));
sectorInfos.push(sectorInfo);
}
}
// Annotate the sectors themselves.
for (const sectorInfo of sectorInfos) {
annotations.push(new ProgramAnnotation_1.ProgramAnnotation("Track " + sectorInfo.track + ", sector " + sectorInfo.sector, sectorInfo.offset, sectorInfo.offset + sectorInfo.size));
}
const writableOffset = RECORD_COUNT * 3;
const writable = binary[writableOffset];
if (writable !== 0 && writable !== 0xFF) {
error = "Invalid \"writable\" byte: 0x" + z80_base_1.toHexByte(writable);
}
const writeProtected = writable === 0;
annotations.push(new ProgramAnnotation_1.ProgramAnnotation(writeProtected ? "Write protected" : "Writable", writableOffset, writableOffset + 1));
return new Jv3FloppyDisk(binary, error, annotations, sectorInfos, writeProtected);
} | [
"function decodeJv3FloppyDisk(binary) {\n let error;\n const annotations = [];\n const sectorInfos = [];\n // Read the directory.\n let sectorOffset = HEADER_SIZE;\n for (let i = 0; i < RECORD_COUNT; i++) {\n const offset = i * 3;\n if (offset + 2 >= binary.length) {\n err... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Used to enable or disable a menu. For example, there could be multiple left menus, but only one of them should be able to be opened at the same time. If there are multiple menus on the same side, then enabling one menu will also automatically disable all the others that are on the same side. | enable(shouldEnable, menuId) {
return _ionic_core__WEBPACK_IMPORTED_MODULE_5__["menuController"].enable(shouldEnable, menuId);
} | [
"function enableMenu(menu) {\n if (menu === \"Sides\") {\n disableAll();\n setToggleSides({ display: \"inline-block\" });\n console.log({ toggleSides })\n } else \n if (menu === \"Appetizers\") {\n disableAll();\n setToggleAppetizers({ disp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
one argument pass dt in loadPopupHoliday function | function loadPopupHoliday(dt){
var full_date,data_header,date,data='';
date=getHoursTime(dt);
month_name=getMonthName(date['month']);
data_header='Your schedule is '+month_name+' '+date['date']+', '+date['year'];
full_date=date['year']+'-'+date['month']+'-'+date['date'];
data += "<label class='checkbox-inline'>";
data += "<input type='radio' value='1' class='schedule' id='schedule' name='schedule'> Holiday";
data += "</label>";
data += "<label class='checkbox-inline'>";
data += "<input type='radio' value='2' class='schedule' id='schedule' name='schedule'> Delete(All ocuurs will be delete)";
data += "</label>";
$('#checkboxGroup').html(data);
$('.date-hidden').val(full_date);
$('#date-header').html(data_header);
$('#calenderModal').modal( 'show' );
} | [
"function get_CalednarPopUpDate(tbName){\n obj=new CalendarPopup_FindCalendar(tbName);\n var date = obj.GetDate();\n return date; \n}",
"static cal_holiday2(jdn) {\r\n\tjdn=Math.round(jdn);\r\n\tvar myt,my,mm,md,mp,mmt,gy,gm,gd;\r\n\tvar yo=ceMmDateTime.j2m(jdn);\r\n\tmyt=yo.myt; my=yo.my; mm = yo.mm;... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
line reader works perfectly fine this takes all the urls and recursively gets the requests on them | function runRequest(lines) {
if (continueRequesting && lines.length > 0) {
var line = lines.pop()
console.log('urls to get: ' + lines.length)
var request = http.get(line, function(res) {
var body = '';
res.on('error', function(err) {
console.log('we got an error!')
console.log(e.message);});
res.on('data', function(chunk) { body += chunk; });
res.on('end', function() {
uniqueURLArray.push(line);
//load the cheerio object
var $ = cheerio.load(body);
//first thing to do is determine the number of pages to link to (there will be a max of 3 pages of info to scrape through and it'd be better to find those pages using cheerio than doing it manually
// the urls are all p2, p3, p4 etc and if we put the first url in there then the rest will follow
var url = $('a.Next').prev().attr('href'); //the sibling of the next button (which is the last page of results)
//console.log(url, line);
if (url != null) {
pgNum = url.replace('.html', '').slice(-2).replace(/[^\d]/g,''); //get the page number
for (var ii = 2; ii <= pgNum; ii++) {
uniqueURLArray.push(url.replace(/(-p(\d+)[.]html)/g, '-p' + ii + '.html'));
}
}
//if the request timed out
if (timeout) {
timeout = false;
console.log(completed_requests, line);
}
//once 5 requests are completed start parsing the data
if (completed_requests++ == 5) {
continueRequesting = true;
//now get the messages
console.log('num urls: ' + uniqueURLArray.length);
var messages = [];
getMessages(uniqueURLArray, messages, uniqueURLArray.length);
//now the messages are all here
//time to filter
}
setTimeout(runRequest(lines), tools.randInt(0,100)); //works with 500-1000
});
});
//request stuff
request.setTimeout(90000, function () {
request.abort();
console.log('request timed out');
timeout = true;
});
request.on('error', function(e) {
console.log(e);
completed_requests++;
});
}
} | [
"async function loadMore(pages, url, line) {\n \n for ( let i = 1; i < pages +1; i++ ) {\n await fetch( url + '&page=' + i, {\n \"method\" : \"GET\",\n \"headers\": headers\n } )\n .then( res => res.json() )\n .then( function( data ) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Figure out component to be shown at root based on user credentials | getHomeComponent() {
const { owner } = this.props;
const credentials = getCredentials(owner);
const onboarding = isOnboarding(credentials);
const signedIn = isSignedIn(credentials);
const isGeneral = isGeneralOwner(credentials);
const isSubscriber = isSubscriberOwner(credentials);
let homeComponent;
if (onboarding) {
homeComponent = () => <Redirect to={{ pathname: '/onboarding' }} />;
} else if (!signedIn) {
homeComponent = Login;
} else if (isSubscriber) {
// Dashboard for both subscriber and subscriber ownrers (subscribers with shares)
homeComponent = SubscriberDashboard;
} else if (isGeneral) {
homeComponent = GeneralDashboard;
}
return homeComponent;
} | [
"render() {\n let loggedin;\n if (window.localStorage.getItem(\"AuthToken\") !== null) {\n loggedin = true;\n } else {\n loggedin = false;\n }\n return <div id=\"parentDiv\">{loggedin ? <PrivateApp /> : <Login />}</div>;\n }",
"function getUserAndShowView() {\n switchVisibleElement('loa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to return true if the given LR(0) item triple is in the given array | function LRItemInArray(array, lr_item) {
for(var a in array) {
var obj = array[a];
// Check that the head and dot position match
if(obj.head === lr_item.head && obj.dotPosition === lr_item.dotPosition) {
// Now compare the body items
var allMatched = true;
for(var b in obj.body) {
if(obj.body[b] !== lr_item.body[b]) {
allMatched = false;
}
}
if(allMatched) {
return true;
}
}
}
return false;
} | [
"function isItemInArray(array, item) {\n for (var i = 0; i < array.length; i++) {\n if (array[i][0] === item[0] && array[i][1] === item[1]) return true\n }\n return false;\n }",
"function includesArray (arr, item) {\n for (let i = 0; i < arr.length; i++) {\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reorder the bus based on all present dependencies. | reorderForDependencies() {
if (this.dependencyLinks.size > 0) {
const actorsAfter = [];
// Temporarily remove all actors that have dependencies
for (const actorAfter of this.dependencyLinks.keys()) {
const dependentPos = this.actors.indexOf(actorAfter);
if (dependentPos >= 0) {
this.actors.splice(dependentPos, 1);
actorsAfter.push(actorAfter);
}
}
// Iteratively append actors based on the first dependency link
// that has all of its dependencies available in the array
while (actorsAfter.length > 0) {
// Find the first actor that has all of its dependencies available.
let activeActorAfterId = -1;
for (let i = 0; i < actorsAfter.length; i++) {
let validLink = true;
for (const dependency of this.dependencyLinks.get(actorsAfter[i])) {
if (this.actors.indexOf(dependency) < 0 && actorsAfter.indexOf(dependency) >= 0) {
validLink = false;
break;
}
}
if (validLink) {
activeActorAfterId = i;
break;
}
}
// If none of the pending links are possible, there must be a cyclic dependency
if (activeActorAfterId < 0) {
throw new Error('Cyclic dependency links detected in bus ' + this.name);
}
// The dependent may not be available (yet), so we don't add it to the array (yet).
const activeActorAfter = actorsAfter.splice(activeActorAfterId, 1)[0];
this.actors.push(activeActorAfter);
}
}
} | [
"reorderForDependencies() {\n if (this.dependencyLinks.size > 0) {\n const actorsAfter = [];\n // Temporarily remove all actors that have dependencies\n for (const actorAfter of this.dependencyLinks.keys()) {\n const dependentPos = this.actors.indexOf(actorAfte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the knot at given index in the knot vector | setKnot(index, knot) {
if (index >= this.knots.shape[0] || index < 0) {
throw new Error('Invalid knot index');
}
if (knot < 0 || knot > 1) {
throw new Error('Invalid knot value');
}
if (index < this.degree + 1) {
if (knot !== 0) {
throw new Error('Clamped knot has to be zero');
}
}
if (index >= (this.knots.shape[0] - this.degree - 1)) {
if (knot !== 1) {
throw new Error('Clamped knot has to be one');
}
}
this.knots.set(index, knot);
} | [
"setKnots(knots) {\r\n if (!this.knots.isShapeEqual(knots)) {\r\n throw new Error('Invalid knot vector length');\r\n }\r\n this.knots = knots;\r\n }",
"__insert (_xKnot, _yKnot, _indx) {\n for (let i = this.__knots - 1; i >= _indx; i--) {\n this.__t[i + 1] = this.__t[i]\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a decimal hours, provides the number of minutes that would match the decimal (using 781 rounding) | function decimalMinutes(t) {
t = Number((t % 1).toFixed(1)); //remove integer portion for easy math
if (t < 0.1) { //0-2
return 0;
} else if (t < 0.2) { //3-8
return 5;
} else if (t < 0.3) { //9-14
return 10;
} else if (t < 0.4) { //15-20
return 15;
} else if (t < 0.5) { //21-26
return 25;
} else if (t < 0.6) { //27-33
return 30;
} else if (t < 0.7) { //34-39
return 35;
} else if (t < 0.8) { //40-45
return 45;
} else if (t < 0.9) { //46-51
return 50;
} else if (t < 1) { //52-59
return 55;
}
} | [
"function calculateHours(hours){\n var minutesFromHours = hours.split(\"h\")\n return minutesFromHours[0]*60\n }",
"function hours_round(h) {\r\n var f = Math.floor(h);\r\n \r\n h = h - f;\r\n h = h * 4.0;\r\n h = Math.round(h) * 0.25;\r\n\r\n return f + h;\r\n}",
"roundHours (hours, in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Activate breakpoints in CodeMirror options, don't overwrite other settings | function activate_cm_breakpoints (cell) {
let cm = cell.code_mirror;
let gutters = cm.getOption('gutters').slice();
if ( $.inArray("CodeMirror-breakpoints", gutters) < 0) {
gutters.push('CodeMirror-breakpoints');
cm.setOption('gutters', gutters);
cm.on('gutterClick', (self, ln, gutter, event) => {
let info = self.lineInfo(ln);
if (info.gutterMarkers) {
// remove has-breakpoint class to the line wrapper
self.removeLineClass(ln, 'text', 'has-breakpoint');
// toggle gutter marker
self.setGutterMarker(ln, "CodeMirror-breakpoints", null);
// skip folds
if (info.gutterMarkers.hasOwnProperty('CodeMirror-foldgutter')) {
console.warn(
"Setting breakpoint on foldable line is not allowed."
);
}
} else {
// breakpoint marker
let marker = document.createElement("div");
marker.innerHTML = "●";
marker.setAttribute('class', 'breakpoint');
// add has-breakpoint class to the line wrapper
self.addLineClass(ln, 'text', 'has-breakpoint');
// toggle gutter marker
self.setGutterMarker(ln, "CodeMirror-breakpoints", marker);
}
// update after delay, pass cell here
setTimeout(() => updateMetadata(cell), params.update_delay);
});
}
} | [
"enableDisableAllBreakpoints() {\n this.breakpointManager.flip();\n }",
"function setBreakpoints() {\n\t\tif (_settings.breakpoints && _matchMediaSupport) {\n\t\t\tvar breakpoints = _settings.breakpoints;\n\n\t\t\t_mqSmall = _mqSmall.replace('%d', breakpoints.sm);\n\t\t\t_mqMedium = _mqMedium.replace('%d', br... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Permet d'afficher des popups | function popup() {
$('[data-popup]').on('click', (event) => {
// Popup cible
const { currentTarget: target } = event;
const popup = $(target).next('.popup');
// Ouvre la popup
popup.toggleClass('active');
// Insertion du data pour charger le contenu uniquement si l'on ouvre la popup
$('object', popup).each((index, object) => {
$(object).attr('data', $(object).data('data'));
});
});
$('.popup button.close, .popup').on('click', (event) => {
const { currentTarget: target } = event;
if ($(target).hasClass('popup') || $(target).hasClass('close')) {
const popup = $(target).closest('.popup');
$(popup).removeClass('active');
// Suppression du data pour stopper le contenu de l'object (vidéo en lecture par exemple)
$('object', popup).each((index, object) => {
$(object).removeAttr('data');
$(object).clone().appendTo($(object).closest('.fluid-container'));
$(object).remove();
});
}
})
} | [
"function initPopups() {\n //ANTES ESTABAN LOS DIVs DE LOS POPUPs\n //YA NO EXISTEN PORQUE CAUSABAN PROBLEMAS\n}",
"function popups_verboten() {\n\t\topen_modul && open_modul.close();\n\t\talert(\"Das Programm kann nicht im richtigen Kontext angezeigt werden. Schalten Sie bitte ggf. den Popup-Blocker aus.\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `BodyProperty` | function CfnWebACL_BodyPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
if (typeof properties !== 'object') {
errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));
}
errors.collect(cdk.propertyValidator('oversizeHandling', cdk.validateString)(properties.oversizeHandling));
return errors.wrap('supplied properties not correct for "BodyProperty"');
} | [
"function CfnWebACL_ResponseInspectionBodyContainsPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of favicons at the given domain with the specified file types | function getFavicons(domain, fileTypes) {
var fav = new Image();
var icons = [];
for(var i = 0; i < fileTypes.length; i++)
{
var path = domain + "favicon." + fileTypes[i];
fav.onload = icons.push(path);
fav.src = path;
}
return icons;
} | [
"function getFavicon(domain, fileTypes) {\n return getFavicons(domain, fileTypes)[0]; // first favicon\n}",
"function filesByMimetype(pattern)\n {\n return m_properties.files.value().filter(function (meta)\n {\n return meta.mimeType.startsWith(pattern);\n })\n .map(fun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends sender action via the Send API | function callSenderActionAPI(sender_psid, action) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"sender_action": action
}
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": process.env.PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
} | [
"sendAction(action) {\n const data = JSON.stringify({\n type: WS_ACTION,\n action\n });\n this.logger.log({\n sender: \"SERVER\",\n playerId: this.playerId,\n data\n });\n this.socket.send(data);\n }",
"send() {\n // Disable send button;\n this.okPressed = tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch stuff from Tumblr | async function doFetch() {
options.verbose && console.error("Fetching from Tumblr");
var baseUrl = options.src + "/api/read?num=" + options.number;
var blog = {
posts: []
};
/**
* Let's fetch
*/
var start = 0;
var total = 1; // Will be set to real value after first request
while (start < total) {
requestUrl = baseUrl + "&start=" + start;
var rawResponse;
try {
options.verbose && console.error("Requesting: %j", requestUrl);
rawResponse = await request(requestUrl);
} catch (err) {
console.error("Got request error: %j", err);
process.exit(1);
}
var jsonResponse;
try {
jsonResponse = await xml2js(rawResponse);
} catch (err) {
console.error("XML Parse error: %j", err);
process.exit(2);
}
/**
* Update total if needed
*/
if (total === 1) {
total = parseInt(jsonResponse.tumblr.posts[0].$.total);
options.verbose && console.error("Total set to ", total);
}
/**
* Update blog title if needed
*/
if (!blog.title) {
blog.title = jsonResponse.tumblr.tumblelog[0].$.title;
}
/**
* Update blog name if needed
*/
if (!blog.name) {
blog.name = jsonResponse.tumblr.tumblelog[0].$.name;
}
// Go through posts
options.verbose && console.error("Going through " + jsonResponse.tumblr.posts[0].post.length + " posts");
for (var postNumber = 0, len = jsonResponse.tumblr.posts[0].post.length; postNumber < len; ++postNumber) {
var origPost = jsonResponse.tumblr.posts[0].post[postNumber];
var post = {};
post.tumblrId = origPost.$.id;
post.postType = origPost.$.type;
post.tumblrUrl = origPost.$.url;
post.tumblrSlug = origPost.$.slug;
post.tags = origPost.tag
blog.posts.push(post);
//console.error("Original post: ", JSON.stringify(origPost, null, 2));
}
start += options.number;
}
options.verbose && console.error("Done Fetching from Tumblr");
return blog;
} | [
"function loadPosts() {\n let queryurl =\n \"https://api.tumblr.com/v2/tagged?api_key=\" + apikey + \"&tag=\";\n queryurl += encodeURI(tagbox.value);\n let postsxhr = new XMLHttpRequest();\n postsxhr.onload = loadedPosts;\n postsxhr.onerror = erroredPosts;\n postsxhr.open(\"GET\", queryurl);\n postsxhr.se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/ Shows website in outer tab. | function showWebsite(p_name, p_url) {
if (v_connTabControl)
$('#modal_about').modal('hide');
v_connTabControl.tag.createWebsiteOuterTab(p_name,p_url);
} | [
"function showWebsite(p_name, p_url) {\n\n\tif (v_connTabControl)\n\t\thideAbout();\n\t\tv_connTabControl.tag.createWebsiteOuterTab(p_name,p_url);\n\n}",
"function show_tab_browse() {\n // console.log(\"show_tab_browse\");\n fill_browse_experiments(experiment_metadata);\n }",
"function openHnTa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grab the URL for a machine by id. | function get_machine_url(db, ts, machineID) {
"use strict";
return [lnt_url_base, "db_" + db, "v4", ts, "machine", machineID].join('/');
} | [
"function getUrlFromId(id, callback){\n\t//Get the url model.\n\tvar urls = require(\"./url.model\");\n\turls.find({id: id}, function(err,url){\n\t\tif(err)\n\t\t\tconsole.log(err);\n\t\telse{\n\t\t\treturn callback(url[0].url);\n\t\t}\n\t});\n}",
"function getMachineInfo(machineID) {\n return fetch(`http://lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new event specified by restaurant, party size, and time | "events.createNewEvent"(
business,
sizeLimit,
appTimeObj,
displayDate,
displayTime
) {
check(displayDate, String);
check(displayTime, String);
if (Meteor.isServer) {
if (!Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
Events.insert({
createAt: Date.now(),
owner: this.userId,
status: "ongoing",
isFull: false,
member: [
{
id: this.userId,
vote: -1
}
],
appTime: appTimeObj,
displayDate: displayDate,
displayTime: displayTime,
restaurantId: business.id,
restaurantUrl: business.url,
restaurantName: business.name,
peopleLimit: sizeLimit
});
}
} | [
"function createEvent() {\n var calendarId = 'primary';\n var start = getRelativeDate(1, 12);\n var end = getRelativeDate(1, 13);\n var event = {\n summary: 'Lunch Meeting',\n location: 'The Deli',\n description: 'To discuss our plans for the presentation next week.',\n start: {\n dateTime: sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ex. 3 A function that takes 3 numbers as parameters. The 3 parameters are called min, max, and target. Return whether target number is between the min and the max (inclusive). | function targetInBetween(min, max, target){
if (target>min && target<max){
return true;
}
else {
return false;
}
} | [
"function arr(min,target,max){\n if(target >= min && target <= max){\n return true; \n } else {\n return false;\n }\n}",
"function rangeCheck(input, min, max) {\r\n return ((input > min) && (input < max));\r\n}",
"function between(min, max, num) {\n return (num >= min && num <= max);\n}"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
========================================== This code makes the about section to flow from one color to another ========================================== | function flowAboutSectionColor() {
let coords = getObjectCoords(aboutSection);
// GC - Green Channel
// BC - Blue Channel
let GCStart = 90;
let BCStart = 61;
let GCEnd = 30;
let BCEnd = 172;
let GCCurrent = normalize(0, -500, GCStart, GCEnd, coords.top);
let BCCurrent = normalize(0, -500, BCStart, BCEnd, coords.top);
aboutSection.css(
"background-color",
`rgb(255, ${GCCurrent}, ${BCCurrent})`
);
} | [
"function updateColors( sectionNumber ) {\n clearAside();\n advanceAside( sectionNumber );\n clearBar();\n advancePBar( sectionNumber );\n}",
"function changeHeadingColor() {\n\tdocument.getElementById(\"heading\").style.backgroundColor = colors[colorIndex];\n\tcolorIndex = (colorIndex + 1) % colors.l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this should implement the task view | function taskView()
{
// set up necessary data
const taskList = $("#tasklist");
const archiveList = $("#archivelist");
const tasks = $("body").data("tasks");
const active = tasks["active"];
const activeKeys = Object.keys(active);
// first, update the tasklist with data from the DOM
const activeList = getIDList("tasklist");
if (activeList.length > 0) // there are already entries in the table
{
for (let i = 0; i < activeKeys.length; i++)
{
if (!activeList.find(element => element === activeKeys[i]))
{
// write the task to the table
addTask(activeKeys[i], active[activeKeys[i]]);
}
}
}
else
{
for (let j = 0; j < activeKeys.length; j++)
{
// write the task to the table
addTask(activeKeys[j], active[activeKeys[j]]);
}
}
// hide the archive
archiveList.hide();
// show the tasklist
taskList.show();
// switch our links around
switchViewLinks("archive");
} | [
"function displayTask() {\n if (tasks.length != 0) { \n panel.refreshTask(tasks[0]);\n } else {\n panel.allTasksDone();\n }\n }",
"viewTasks(){\n for(let i = 0; i < this.tasks.length; i++){\n console.log(`Task : ${this.tasks[i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enter a parse tree produced by AgtypeParserfloatLiteral. | enterFloatLiteral(ctx) {
} | [
"enterFloatLiteral(ctx) {\n\t}",
"exitFloatLiteral(ctx) {\n\t}",
"exitFloatLiteral(ctx) {\n }",
"function updateFloatLabel(node, value) { }",
"SetFloat() {}",
"function floatHandler(id) {\n operatorSelectorCleaner(id);\n createAndAddNewOptions(\"number\", id);\n inputBuilder(\"float\", id);\n}",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render the view. This will set up any subforms that might be available within the form. Returns: RB.FormView: This object, for chaining. | render() {
this._$subforms = this.$('.rb-c-form-fieldset.-is-subform');
if (this._$subforms.length > 0) {
this._setupSubforms();
}
this.setupFormWidgets();
return this;
} | [
"renderForms() {\n for (const form of this._configForms.values()) {\n form.render();\n }\n\n /*\n * Ensure that if the browser sets the value of the <select> upon\n * refresh that we update the model accordingly.\n */\n this.$('#id_avatar_service_id').c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ANIMATION Allows growth and shrinkage for any object in the game Call `startGrowth(...)` or `startShrink(...)` accordingly, on any object, to start growing or shrinking the object. Main game loop invoke `animateGrow` and `animateShrink` which handle incremental grow and shrink updates. | function startGrowth(object, duration, dy, scale) { // TODO: annotate all of these functions
object.animateGrow_isGrowing = true;
object.animateGrow_end_time = duration;
object.animateGrow_end_dy = dy;
object.animateGrow_end_scale = scale;
object.animateGrow_start_y = object.position.y - dy;
object.animateGrow_time = 0;
} | [
"async growAndShrink() {\n await this._temporaryAnimation(this._icon, 'grow-and-shrink', 200);\n }",
"function animate() {\n ctx.clearRect(0, 0, canvasWidth, canvasHeight);\n\n for (var i = 0; i < objects.length; i++) {\n objects[i].move();\n objects[i].draw();\n }\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Private function used by Plotly.moveTraces to check input args | function checkMoveTracesArgs(gd, currentIndices, newIndices) {
// check that gd has attribute 'data' and 'data' is array
if(!Array.isArray(gd.data)) {
throw new Error('gd.data must be an array.');
}
// validate currentIndices array
if(typeof currentIndices === 'undefined') {
throw new Error('currentIndices is a required argument.');
} else if(!Array.isArray(currentIndices)) {
currentIndices = [currentIndices];
}
assertIndexArray(gd, currentIndices, 'currentIndices');
// validate newIndices array if it exists
if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
newIndices = [newIndices];
}
if(typeof newIndices !== 'undefined') {
assertIndexArray(gd, newIndices, 'newIndices');
}
// check currentIndices and newIndices are the same length if newIdices exists
if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {
throw new Error('current and new indices must be of equal length.');
}
} | [
"function checkMoveTracesArgs(gd, currentIndices, newIndices) {\n\n\t // check that gd has attribute 'data' and 'data' is array\n\t if(!Array.isArray(gd.data)) {\n\t throw new Error('gd.data must be an array.');\n\t }\n\n\t // validate currentIndices array\n\t if(typeof currentIndices === 'und... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add `ch` to the current line breaking context, and returns whether a break opportunity exists before `ch`. | breakBefore(ch) {
var value = lineBreakValue(ch.charCodeAt(0));
var breakBefore = breakBetweenLineBreakValues(this._lastLineBreakValue, value);
this._lastLineBreakValue = value;
return breakBefore;
} | [
"advance (line, line_height) {\n let can_push = this.push(line);\n if (can_push){\n return this.createLine(line_height);\n }\n else {\n return false;\n }\n }",
"hasPrecedingCharactersOnLine() {\n const bufferPosition = this.getBufferPosition();\n c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate spinner html element. Spinner html element must follow template from | generateSpinnerElement()
{
let emptyDivKey = Object.keys(this.numberOfEmptyDivForSpinner).find(element => element === this.options.spinnerIcon);
let emptyDivElement = this.generateEmptyDivElement(this.numberOfEmptyDivForSpinner[emptyDivKey]);
this.spinner = `<div style="color: ${this.options.spinnerColor}" class="la-${ this.options.spinnerIcon } la-${this.options.spinnerSize}">${ emptyDivElement }</div>`
} | [
"renderSpinner() {\n const markup = `\n <div class=\"spinner\">\n <div></div>\n <div></div>\n <div></div>\n </div>`;\n\n this._clear();\n this._display(markup);\n }",
"function getSpinner(){\n\treturn '<div style=\"text-align: center\"><i class=\"f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
merge function that takes in an array with a low mid and high to merge on uses a copied array to help merge | function merge(array, copy, low, mid, hi) {
for(var x = low; x <= hi; x++) {
copy[x] = array[x]
}
var i = low,
j = mid+1;
for(var k = low; k <= hi; k++) {
if(i > mid) { array[k] = copy[j++] } // if we have no more in the lower array
else if(j > hi) { array[k] = copy[i++] } // if we have no more in the higher array
else if(copy[j] > copy[i]) { array[k] = copy[i++] }
else { array[k] = copy[j++] }
}
} | [
"static _merge(arr, aux, lo, mid, hi) {\n // Copy to aux[]\n for (let k = lo; k <= hi; k++) {\n aux[k] = arr[k]; \n }\n\n // Merge back to arr[]\n let i = lo;\n let j = mid + 1;\n for (let k = lo; k <= hi; k++) {\n if (i > mid) {\n arr[k] = aux[j++];\n } else if (j > hi) {... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
implement getElementsByAttribute() naive approach: grab all of the elements in the DOM, then looping through all of them and checking attributes faster approach: checking attributes as we grab every element (DFS) refer to dommanipulation.html | function getElementsByAttribute(attr) {
var found = [];
function checkNode(node) {
// check if node has children (remember [] returns true)
if(node && node.getAttribute) {
if(node.getAttribute(attr)) {
found.push(node);
}
if(node.childNodes && node.childNodes.length) {
for(let i = 0; i < node.childNodes.length; i++) {
let ele = node.childNodes[i];
checkNode(ele);
}
}
}
}
checkNode(document.body);
return found;
} | [
"getElementsByAttribute(name, value) {\n return this.getElementsBy(elem => {\n if (elem.hasAttribute(name)) {\n if (value === undefined) {\n return true;\n } else {\n return elem.getAttribute(name) === value;\n }\n }\n return false;\n });\n }",
"functio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |