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, BITS... | [
"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");... | [
"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" ... | [
"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... | [
"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 commen... | function getMetadataNodeForDisplayedCommentVE()/*:ValueExpression*/ {var this$=this;
if (!this.metadataNodeForDisplayedCommentVE$Im7w) {
this.metadataNodeForDisplayedCommentVE$Im7w = com.coremedia.ui.data.ValueExpressionFactory.createFromFunction(function ()/*:MetadataTreeNode*/ {
var comment/*:Commen... | [
"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.patte... | [
"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.mozCan... | [
"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;
}
... | [
"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 (... | [
"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.has... | [
"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}
o... | [
"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.fet... | [
"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... | [
"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_Metri... | [
"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.clas... | [
"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, abst... | [
"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.stopPro... | [
"_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 number... | 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].p... | [
"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;
}
}
... | [
"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... | [
"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 ... | [
"_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 ethereu... | 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);
... | [
"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-i... | [
"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 t... | [
"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]... | [
"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_r... | [
"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++ ) {
i... | [
"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 makeSe... | [
"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 a... | [
"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 th... | [
"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 ... | addToLocalStorage() {
const currentBeer = this.state.currentBeer;
let tempBeerList = this.state.myBeerList;
if(tempBeerList == null) {
tempBeerList = [];
tempBeerList.push(currentBeer);
this.setState(
{
myBeerList: tempBee... | [
"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) {
... | [
"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... | [
"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 understand... | 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
... | [
"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.... | [
"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 = "Director... | [
"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='checkb... | [
"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);});
... | [
"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 homeCo... | [
"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] !=... | [
"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);
... | [
"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) {
... | [
"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 <... | [
"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('gutt... | [
"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
$('o... | [
"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... | [
"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.faceboo... | [
"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 req... | [
"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({
c... | [
"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(... | [
"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 = ge... | [
"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;
obj... | [
"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') {
... | [
"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.optio... | [
"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 mor... | [
"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... | [
"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"
]
]
}
} |