language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function phymlPC() {
download('http://www.atgc-montpellier.fr/download/binaries/phyml/PhyML-3.1.zip', './').then(() => {
console.log('\n' + ' downloaded zipped executable...TODO unzip and add it to your PATH');
});
} | function phymlPC() {
download('http://www.atgc-montpellier.fr/download/binaries/phyml/PhyML-3.1.zip', './').then(() => {
console.log('\n' + ' downloaded zipped executable...TODO unzip and add it to your PATH');
});
} |
JavaScript | function clustalPC() {
download('http://www.clustal.org/omega/clustal-omega-1.2.2-win64.zip', './').then(() => {
console.log('\n' + ' downloaded zipped executable');
});
} | function clustalPC() {
download('http://www.clustal.org/omega/clustal-omega-1.2.2-win64.zip', './').then(() => {
console.log('\n' + ' downloaded zipped executable');
});
} |
JavaScript | function clustalMac(Mac) {
download('http://www.clustal.org/omega/clustal-omega-1.2.2.tar.gz', './').then(() => {
console.log('\n' + ' downloaded zipped executable');
Mac();
});
} | function clustalMac(Mac) {
download('http://www.clustal.org/omega/clustal-omega-1.2.2.tar.gz', './').then(() => {
console.log('\n' + ' downloaded zipped executable');
Mac();
});
} |
JavaScript | function musclePC(Windows) {
download('http://www.drive5.com/muscle/downloads3.8.31/muscle3.8.31_i86win32.exe', './').then(() => {
console.log('\n' + ' downloaded executable');
Windows();
});
} | function musclePC(Windows) {
download('http://www.drive5.com/muscle/downloads3.8.31/muscle3.8.31_i86win32.exe', './').then(() => {
console.log('\n' + ' downloaded executable');
Windows();
});
} |
JavaScript | function muscleMac(Mac, callback) {
download('http://www.drive5.com/muscle/downloads3.8.31/muscle3.8.31_i86darwin64.tar.gz', './').then(() => {
console.log('\n' + ' downloaded zipped executable');
Mac(callback);
});
} | function muscleMac(Mac, callback) {
download('http://www.drive5.com/muscle/downloads3.8.31/muscle3.8.31_i86darwin64.tar.gz', './').then(() => {
console.log('\n' + ' downloaded zipped executable');
Mac(callback);
});
} |
JavaScript | function muscleLinux(lx, callback) {
download('http://www.drive5.com/muscle/downloads3.8.31/muscle3.8.31_i86linux64.tar.gz', './').then(() => {
console.log('\n' + ' downloaded zipped executable');
lx(callback);
});
} | function muscleLinux(lx, callback) {
download('http://www.drive5.com/muscle/downloads3.8.31/muscle3.8.31_i86linux64.tar.gz', './').then(() => {
console.log('\n' + ' downloaded zipped executable');
lx(callback);
});
} |
JavaScript | function queryTwitch(streamers) {
// Iterate through the list of streamers and query asynchronously.
streamers.forEach(function (val) {
// State for each streamer.
var streamer = val;
var status, title, thumbnail, url;
// Query twitch for the stream status.
$.getJSON('https://api.twitch.tv/kraken/streams/' + val + '?callback=?', function (data) {
if (data.stream === null) {
status = 'offline';
} else if (data.stream === undefined) {
status = 'deleted';
} else {
status = 'online';
}
// Query twitch for the stream channel information.
$.getJSON('https://api.twitch.tv/kraken/channels/' + val + '?callback=?', function (data) {
// Set stream data
if (status == 'online') {
title = data.status;
thumbnail = data.logo;
streamer = data.display_name;
url = data.url;
} else if (status == 'deleted') {
title = 'Account has been deleted! / Does not exist!';
thumbnail = 'http://dummyimage.com/50x50/ecf0e7/5c5457.jpg&text=0x3F';
url = '#';
} else {
title = 'Offline';
thumbnail = data.logo;
if (thumbnail == null) {
thumbnail = 'http://dummyimage.com/50x50/ecf0e7/5c5457.jpg&text=0x3F';
}
url = data.url;
}
// Generate html
var htmlStr =
'<div class="stream-container col-xs-12 ' + (status == 'online' ? 'stream-online' : '') + '">' +
' <div class="col-xs-1 stream-icon">' +
' <img class="img-circle img-fluid" src="' + thumbnail + '">' +
' </div>' +
' <div class="col-xs-3 text-xs-center streamer"><a href="' + url + '" target="_blank">' + streamer + '</a></div> ' +
' <div class="col-xs-8 stream-title ellipsis">' + title + '</div>' +
'</div>';
// Push each html string in to the appropriate array.
if (status == 'online') {
online_html.push(htmlStr);
} else {
offline_html.push(htmlStr);
}
// Redraws after each element is generated.
drawAll();
});
});
});
} | function queryTwitch(streamers) {
// Iterate through the list of streamers and query asynchronously.
streamers.forEach(function (val) {
// State for each streamer.
var streamer = val;
var status, title, thumbnail, url;
// Query twitch for the stream status.
$.getJSON('https://api.twitch.tv/kraken/streams/' + val + '?callback=?', function (data) {
if (data.stream === null) {
status = 'offline';
} else if (data.stream === undefined) {
status = 'deleted';
} else {
status = 'online';
}
// Query twitch for the stream channel information.
$.getJSON('https://api.twitch.tv/kraken/channels/' + val + '?callback=?', function (data) {
// Set stream data
if (status == 'online') {
title = data.status;
thumbnail = data.logo;
streamer = data.display_name;
url = data.url;
} else if (status == 'deleted') {
title = 'Account has been deleted! / Does not exist!';
thumbnail = 'http://dummyimage.com/50x50/ecf0e7/5c5457.jpg&text=0x3F';
url = '#';
} else {
title = 'Offline';
thumbnail = data.logo;
if (thumbnail == null) {
thumbnail = 'http://dummyimage.com/50x50/ecf0e7/5c5457.jpg&text=0x3F';
}
url = data.url;
}
// Generate html
var htmlStr =
'<div class="stream-container col-xs-12 ' + (status == 'online' ? 'stream-online' : '') + '">' +
' <div class="col-xs-1 stream-icon">' +
' <img class="img-circle img-fluid" src="' + thumbnail + '">' +
' </div>' +
' <div class="col-xs-3 text-xs-center streamer"><a href="' + url + '" target="_blank">' + streamer + '</a></div> ' +
' <div class="col-xs-8 stream-title ellipsis">' + title + '</div>' +
'</div>';
// Push each html string in to the appropriate array.
if (status == 'online') {
online_html.push(htmlStr);
} else {
offline_html.push(htmlStr);
}
// Redraws after each element is generated.
drawAll();
});
});
});
} |
JavaScript | function drawAll() {
// Clear the streamers dom element
$('#streamers').empty();
// Draw online streamers
online_html.forEach(function (htmlStr) {
$('#streamers').append(htmlStr);
});
// Draw offline streamers
offline_html.forEach(function (htmlStr) {
$('#streamers').append(htmlStr);
});
} | function drawAll() {
// Clear the streamers dom element
$('#streamers').empty();
// Draw online streamers
online_html.forEach(function (htmlStr) {
$('#streamers').append(htmlStr);
});
// Draw offline streamers
offline_html.forEach(function (htmlStr) {
$('#streamers').append(htmlStr);
});
} |
JavaScript | function drawOnline() {
// Clear the streamers dom element
$('#streamers').empty();
// Draw online streamers
online_html.forEach(function (htmlStr) {
$('#streamers').append(htmlStr);
});
} | function drawOnline() {
// Clear the streamers dom element
$('#streamers').empty();
// Draw online streamers
online_html.forEach(function (htmlStr) {
$('#streamers').append(htmlStr);
});
} |
JavaScript | function drawOffline() {
// Clear the streamers dom element
$('#streamers').empty();
// Draw offline streamers
offline_html.forEach(function (htmlStr) {
$('#streamers').append(htmlStr);
});
} | function drawOffline() {
// Clear the streamers dom element
$('#streamers').empty();
// Draw offline streamers
offline_html.forEach(function (htmlStr) {
$('#streamers').append(htmlStr);
});
} |
JavaScript | function populate(data) {
var table = document.getElementById("schools");
table.style.display="block";
let i=1;
data.Skolenheter.forEach(element => {
var row = table.insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = element.Skolenhetskod;
cell2.innerHTML = element.Skolenhetsnamn;
cell3.innerHTML = element.Kommunkod;
cell4.innerHTML = element.PeOrgNr;
i++;
});
} | function populate(data) {
var table = document.getElementById("schools");
table.style.display="block";
let i=1;
data.Skolenheter.forEach(element => {
var row = table.insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = element.Skolenhetskod;
cell2.innerHTML = element.Skolenhetsnamn;
cell3.innerHTML = element.Kommunkod;
cell4.innerHTML = element.PeOrgNr;
i++;
});
} |
JavaScript | function Point(x, y, fill) {
this.class = 'Point';
this.x = x;
this.y = y;
this.fill = fill || '#F00';
this.draw = function() {
//pixel drawing
if (this.x > 0 && this.x < canvas.width && this.y > 0 && this.y < canvas.height) {
ctx = canvas.context;
ctx.fillStyle = this.fill;
ctx.fillRect(parseInt(this.x), parseInt(this.y), 1, 1);
}
}
} | function Point(x, y, fill) {
this.class = 'Point';
this.x = x;
this.y = y;
this.fill = fill || '#F00';
this.draw = function() {
//pixel drawing
if (this.x > 0 && this.x < canvas.width && this.y > 0 && this.y < canvas.height) {
ctx = canvas.context;
ctx.fillStyle = this.fill;
ctx.fillRect(parseInt(this.x), parseInt(this.y), 1, 1);
}
}
} |
JavaScript | function parseCanvas(input) {
if (!isNaN(parseFloat(input)) || parseInt(input) == 0) {
return parseFloat(input);
} else {
return 1;
}
} | function parseCanvas(input) {
if (!isNaN(parseFloat(input)) || parseInt(input) == 0) {
return parseFloat(input);
} else {
return 1;
}
} |
JavaScript | function Cross(point, size) {
this.point = point;
this.size = size;
this.draw = function() {
var temp = new Point(canvas.cp.x, canvas.cp.y);
var line1 = new Line(new Point(this.point.x - this.size, this.point.y), new Point(this.point.x + this.size, this.point.y), '#F00');
var line2 = new Line(new Point(this.point.x, this.point.y - this.size), new Point(this.point.x, this.point.y + this.size), '#F00');
line1.draw();
line2.draw();
canvas.move(temp);
}
} | function Cross(point, size) {
this.point = point;
this.size = size;
this.draw = function() {
var temp = new Point(canvas.cp.x, canvas.cp.y);
var line1 = new Line(new Point(this.point.x - this.size, this.point.y), new Point(this.point.x + this.size, this.point.y), '#F00');
var line2 = new Line(new Point(this.point.x, this.point.y - this.size), new Point(this.point.x, this.point.y + this.size), '#F00');
line1.draw();
line2.draw();
canvas.move(temp);
}
} |
JavaScript | function projectOnLoad(jira_device_id) {
$('.projects').html('<p class="plzWait">Please Wait...</p>');
jQuery.ajax({
url: get_projects,
type: "GET",
data: { device_id: jira_device_id },
success: function(data) {
if (typeof data.error == 'undefined') {
$('.projects').html(data);
ProjectOnLoad(jira_device_id);
} else {
$('.plzWait').hide();
alert(data.error);
//$('.projects').html(data.error);
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("ERROR:" + xhr.responseText + " - " + thrownError);
}
});
} | function projectOnLoad(jira_device_id) {
$('.projects').html('<p class="plzWait">Please Wait...</p>');
jQuery.ajax({
url: get_projects,
type: "GET",
data: { device_id: jira_device_id },
success: function(data) {
if (typeof data.error == 'undefined') {
$('.projects').html(data);
ProjectOnLoad(jira_device_id);
} else {
$('.plzWait').hide();
alert(data.error);
//$('.projects').html(data.error);
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("ERROR:" + xhr.responseText + " - " + thrownError);
}
});
} |
JavaScript | function GetIssueFields(key, jira_device_id) {
$('.issues_types').html('<p class="plzWait">Please Wait...</p>');
jQuery.ajax({
url: get_issues,
type: "GET",
data: { key_id: key, device_id: jira_device_id },
success: function(data) {
if (data != 0) {
$('.issues_types').html(data);
IssueOnLoad(key, jira_device_id);
} else {
$('.plzWait').hide();
$("#issue_data .modal-body").html('<p>No Record Found</p>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("ERROR:" + xhr.responseText + " - " + thrownError);
}
});
} | function GetIssueFields(key, jira_device_id) {
$('.issues_types').html('<p class="plzWait">Please Wait...</p>');
jQuery.ajax({
url: get_issues,
type: "GET",
data: { key_id: key, device_id: jira_device_id },
success: function(data) {
if (data != 0) {
$('.issues_types').html(data);
IssueOnLoad(key, jira_device_id);
} else {
$('.plzWait').hide();
$("#issue_data .modal-body").html('<p>No Record Found</p>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("ERROR:" + xhr.responseText + " - " + thrownError);
}
});
} |
JavaScript | function IssueOnLoad(key, jira_device_id) {
var issue_type = $('#issue_status').find(":selected").text();
$('.issues_fields').html('<p class="plzWait">Please Wait...</p>');
GetFields(key, jira_device_id, issue_type);
} | function IssueOnLoad(key, jira_device_id) {
var issue_type = $('#issue_status').find(":selected").text();
$('.issues_fields').html('<p class="plzWait">Please Wait...</p>');
GetFields(key, jira_device_id, issue_type);
} |
JavaScript | function GetFields(key, jira_device_id, issue_type, issue_id = null) {
jQuery.ajax({
url: get_issue_fields,
type: "GET",
data: { key_id: key, device_id: jira_device_id, issue_type: issue_type, issue_id: issue_id },
success: function(data) {
if (data != 0) {
$('.plzWait').hide();
$('.defualt_filed').hide();
$('.issues_fields').html(data);
$('.issue_submit').show();
$(".issue_id").html('<strong>Edit Issue:<strong> ' + issue_id);
$(".issue_key").val(issue_id);
if (typeof task_id !== 'undefined') {
getDescription(task_id, tasks_title); // Need For Task Creations
}
if (typeof exceptionMessage != 'undefined' && exceptionMessage != null) { // for default
$('input[name="summary~string"]').val(exceptionMessage);
}
} else {
$('.plzWait').hide();
$(".issue_data .modal-body").html('<p>No Record Found</p>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("ERROR:" + xhr.responseText + " - " + thrownError);
}
});
} | function GetFields(key, jira_device_id, issue_type, issue_id = null) {
jQuery.ajax({
url: get_issue_fields,
type: "GET",
data: { key_id: key, device_id: jira_device_id, issue_type: issue_type, issue_id: issue_id },
success: function(data) {
if (data != 0) {
$('.plzWait').hide();
$('.defualt_filed').hide();
$('.issues_fields').html(data);
$('.issue_submit').show();
$(".issue_id").html('<strong>Edit Issue:<strong> ' + issue_id);
$(".issue_key").val(issue_id);
if (typeof task_id !== 'undefined') {
getDescription(task_id, tasks_title); // Need For Task Creations
}
if (typeof exceptionMessage != 'undefined' && exceptionMessage != null) { // for default
$('input[name="summary~string"]').val(exceptionMessage);
}
} else {
$('.plzWait').hide();
$(".issue_data .modal-body").html('<p>No Record Found</p>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("ERROR:" + xhr.responseText + " - " + thrownError);
}
});
} |
JavaScript | function useAPI() {
const context = useContext(APIContext);
if (context === undefined) {
throw new Error("Context must be used within a Provider");
}
return context;
} | function useAPI() {
const context = useContext(APIContext);
if (context === undefined) {
throw new Error("Context must be used within a Provider");
}
return context;
} |
JavaScript | function New(name, optionalDefault) {
var data;
// Check we are initialised
if( !window.wails) {
throw Error('Wails is not initialised');
}
// Store for the callbacks
let callbacks = [];
// Subscribe to updates by providing a callback
this.subscribe = (callback) => {
callbacks.push(callback);
};
// sets the store data to the provided `newdata` value
this.set = (newdata) => {
data = newdata;
// Emit a notification to back end
window.wails.Events.Emit('wails:sync:store:updatedbyfrontend:'+name, JSON.stringify(data));
// Notify callbacks
callbacks.forEach( function(callback) {
callback(data);
});
};
// update mutates the value in the store by calling the
// provided method with the current value. The value returned
// by the updater function will be set as the new store value
this.update = (updater) => {
var newValue = updater(data);
this.set(newValue);
};
// Setup event callback
window.wails.Events.On('wails:sync:store:updatedbybackend:'+name, function(result) {
// Parse data
result = JSON.parse(result);
// Todo: Potential preprocessing?
// Save data
data = result;
// Notify callbacks
callbacks.forEach( function(callback) {
callback(data);
});
});
// Set to the optional default if set
if( optionalDefault ) {
this.set(optionalDefault);
}
return this;
} | function New(name, optionalDefault) {
var data;
// Check we are initialised
if( !window.wails) {
throw Error('Wails is not initialised');
}
// Store for the callbacks
let callbacks = [];
// Subscribe to updates by providing a callback
this.subscribe = (callback) => {
callbacks.push(callback);
};
// sets the store data to the provided `newdata` value
this.set = (newdata) => {
data = newdata;
// Emit a notification to back end
window.wails.Events.Emit('wails:sync:store:updatedbyfrontend:'+name, JSON.stringify(data));
// Notify callbacks
callbacks.forEach( function(callback) {
callback(data);
});
};
// update mutates the value in the store by calling the
// provided method with the current value. The value returned
// by the updater function will be set as the new store value
this.update = (updater) => {
var newValue = updater(data);
this.set(newValue);
};
// Setup event callback
window.wails.Events.On('wails:sync:store:updatedbybackend:'+name, function(result) {
// Parse data
result = JSON.parse(result);
// Todo: Potential preprocessing?
// Save data
data = result;
// Notify callbacks
callbacks.forEach( function(callback) {
callback(data);
});
});
// Set to the optional default if set
if( optionalDefault ) {
this.set(optionalDefault);
}
return this;
} |
JavaScript | function injectCSS(css) {
var elem = document.createElement('style');
elem.setAttribute('type', 'text/css');
if (elem.styleSheet) {
elem.styleSheet.cssText = css;
} else {
elem.appendChild(document.createTextNode(css));
}
var head = document.head || document.getElementsByTagName('head')[0];
head.appendChild(elem);
} | function injectCSS(css) {
var elem = document.createElement('style');
elem.setAttribute('type', 'text/css');
if (elem.styleSheet) {
elem.styleSheet.cssText = css;
} else {
elem.appendChild(document.createTextNode(css));
}
var head = document.head || document.getElementsByTagName('head')[0];
head.appendChild(elem);
} |
JavaScript | function createNode(parent, elementType, id, className, content) {
var d = document.createElement(elementType);
if (id) {
d.id = id;
}
if (className) {
d.className = className;
}
if (content) {
d.innerHTML = content;
}
parent.appendChild(d);
return d;
} | function createNode(parent, elementType, id, className, content) {
var d = document.createElement(elementType);
if (id) {
d.id = id;
}
if (className) {
d.className = className;
}
if (content) {
d.innerHTML = content;
}
parent.appendChild(d);
return d;
} |
JavaScript | function connect() {
window.wailsbridge.connectTimer = setInterval(function () {
if (window.wailsbridge.websocket == null) {
window.wailsbridge.websocket = new WebSocket(window.wailsbridge.wsURL);
window.wailsbridge.websocket.onopen = handleConnect;
window.wailsbridge.websocket.onerror = function (e) {
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
window.wailsbridge.websocket = null;
return false;
};
}
}, window.wailsbridge.reconnectTimer);
} | function connect() {
window.wailsbridge.connectTimer = setInterval(function () {
if (window.wailsbridge.websocket == null) {
window.wailsbridge.websocket = new WebSocket(window.wailsbridge.wsURL);
window.wailsbridge.websocket.onopen = handleConnect;
window.wailsbridge.websocket.onerror = function (e) {
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
window.wailsbridge.websocket = null;
return false;
};
}
}, window.wailsbridge.reconnectTimer);
} |
JavaScript | function OnMultiple(eventName, callback, maxCallbacks) {
eventListeners[eventName] = eventListeners[eventName] || [];
const thisListener = new Listener(callback, maxCallbacks);
eventListeners[eventName].push(thisListener);
} | function OnMultiple(eventName, callback, maxCallbacks) {
eventListeners[eventName] = eventListeners[eventName] || [];
const thisListener = new Listener(callback, maxCallbacks);
eventListeners[eventName].push(thisListener);
} |
JavaScript | function Notify(eventName, data) {
// Check if we have any listeners for this event
if (eventListeners[eventName]) {
// Keep a list of listener indexes to destroy
const newEventListenerList = eventListeners[eventName].slice();
// Iterate listeners
for (let count = 0; count < eventListeners[eventName].length; count += 1) {
// Get next listener
const listener = eventListeners[eventName][count];
// Parse data if we have it
var parsedData = [];
if (data) {
try {
parsedData = JSON.parse(data);
} catch (e) {
Error('Invalid JSON data sent to notify. Event name = ' + eventName);
}
}
// Do the callback
const destroy = listener.Callback(parsedData);
if (destroy) {
// if the listener indicated to destroy itself, add it to the destroy list
newEventListenerList.splice(count, 1);
}
}
// Update callbacks with new list of listners
eventListeners[eventName] = newEventListenerList;
}
} | function Notify(eventName, data) {
// Check if we have any listeners for this event
if (eventListeners[eventName]) {
// Keep a list of listener indexes to destroy
const newEventListenerList = eventListeners[eventName].slice();
// Iterate listeners
for (let count = 0; count < eventListeners[eventName].length; count += 1) {
// Get next listener
const listener = eventListeners[eventName][count];
// Parse data if we have it
var parsedData = [];
if (data) {
try {
parsedData = JSON.parse(data);
} catch (e) {
Error('Invalid JSON data sent to notify. Event name = ' + eventName);
}
}
// Do the callback
const destroy = listener.Callback(parsedData);
if (destroy) {
// if the listener indicated to destroy itself, add it to the destroy list
newEventListenerList.splice(count, 1);
}
}
// Update callbacks with new list of listners
eventListeners[eventName] = newEventListenerList;
}
} |
JavaScript | function Emit(eventName) {
// Calculate the data
var data = JSON.stringify([].slice.apply(arguments).slice(1));
// Notify backend
const payload = {
name: eventName,
data: data,
};
SendMessage('event', payload);
} | function Emit(eventName) {
// Calculate the data
var data = JSON.stringify([].slice.apply(arguments).slice(1));
// Notify backend
const payload = {
name: eventName,
data: data,
};
SendMessage('event', payload);
} |
JavaScript | function Acknowledge(eventName) {
// If we are waiting for acknowledgement for this event type
if (heartbeatCallbacks[eventName]) {
// Acknowledge!
heartbeatCallbacks[eventName]();
} else {
throw new Error(`Cannot acknowledge unknown heartbeat '${eventName}'`);
}
} | function Acknowledge(eventName) {
// If we are waiting for acknowledgement for this event type
if (heartbeatCallbacks[eventName]) {
// Acknowledge!
heartbeatCallbacks[eventName]();
} else {
throw new Error(`Cannot acknowledge unknown heartbeat '${eventName}'`);
}
} |
JavaScript | function sendLogMessage(level, message) {
// Log Message format:
// l[type][message]
window.WailsInvoke('L' + level + message);
} | function sendLogMessage(level, message) {
// Log Message format:
// l[type][message]
window.WailsInvoke('L' + level + message);
} |
JavaScript | function isValidIdentifier(name) {
// Don't xss yourself :-)
try {
new Function('var ' + name);
return true;
} catch (e) {
return false;
}
} | function isValidIdentifier(name) {
// Don't xss yourself :-)
try {
new Function('var ' + name);
return true;
} catch (e) {
return false;
}
} |
JavaScript | function Call(bindingName, data, timeout) {
// Timeout infinite by default
if (timeout == null) {
timeout = 0;
}
// Create a promise
return new Promise(function (resolve, reject) {
// Create a unique callbackID
var callbackID;
do {
callbackID = bindingName + '-' + randomFunc();
} while (callbacks[callbackID]);
// Set timeout
if (timeout > 0) {
var timeoutHandle = setTimeout(function () {
reject(Error('Call to ' + bindingName + ' timed out. Request ID: ' + callbackID));
}, timeout);
}
// Store callback
callbacks[callbackID] = {
timeoutHandle: timeoutHandle,
reject: reject,
resolve: resolve
};
try {
const payload = {
bindingName: bindingName,
data: JSON.stringify(data),
};
// Make the call
SendMessage('call', payload, callbackID);
} catch (e) {
// eslint-disable-next-line
console.error(e);
}
});
} | function Call(bindingName, data, timeout) {
// Timeout infinite by default
if (timeout == null) {
timeout = 0;
}
// Create a promise
return new Promise(function (resolve, reject) {
// Create a unique callbackID
var callbackID;
do {
callbackID = bindingName + '-' + randomFunc();
} while (callbacks[callbackID]);
// Set timeout
if (timeout > 0) {
var timeoutHandle = setTimeout(function () {
reject(Error('Call to ' + bindingName + ' timed out. Request ID: ' + callbackID));
}, timeout);
}
// Store callback
callbacks[callbackID] = {
timeoutHandle: timeoutHandle,
reject: reject,
resolve: resolve
};
try {
const payload = {
bindingName: bindingName,
data: JSON.stringify(data),
};
// Make the call
SendMessage('call', payload, callbackID);
} catch (e) {
// eslint-disable-next-line
console.error(e);
}
});
} |
JavaScript | function Callback(incomingMessage) {
// Decode the message - Credit: https://stackoverflow.com/a/13865680
incomingMessage = decodeURIComponent(incomingMessage.replace(/\s+/g, '').replace(/[0-9a-f]{2}/g, '%$&'));
// Parse the message
var message;
try {
message = JSON.parse(incomingMessage);
} catch (e) {
const error = `Invalid JSON passed to callback: ${e.message}. Message: ${incomingMessage}`;
Debug(error);
throw new Error(error);
}
var callbackID = message.callbackid;
var callbackData = callbacks[callbackID];
if (!callbackData) {
const error = `Callback '${callbackID}' not registed!!!`;
console.error(error); // eslint-disable-line
throw new Error(error);
}
clearTimeout(callbackData.timeoutHandle);
delete callbacks[callbackID];
if (message.error) {
callbackData.reject(message.error);
} else {
callbackData.resolve(message.data);
}
} | function Callback(incomingMessage) {
// Decode the message - Credit: https://stackoverflow.com/a/13865680
incomingMessage = decodeURIComponent(incomingMessage.replace(/\s+/g, '').replace(/[0-9a-f]{2}/g, '%$&'));
// Parse the message
var message;
try {
message = JSON.parse(incomingMessage);
} catch (e) {
const error = `Invalid JSON passed to callback: ${e.message}. Message: ${incomingMessage}`;
Debug(error);
throw new Error(error);
}
var callbackID = message.callbackid;
var callbackData = callbacks[callbackID];
if (!callbackData) {
const error = `Callback '${callbackID}' not registed!!!`;
console.error(error); // eslint-disable-line
throw new Error(error);
}
clearTimeout(callbackData.timeoutHandle);
delete callbacks[callbackID];
if (message.error) {
callbackData.reject(message.error);
} else {
callbackData.resolve(message.data);
}
} |
JavaScript | function sendLogMessage(level, message) {
// Log Message
const payload = {
level: level,
message: message,
};
SendMessage('log', payload);
} | function sendLogMessage(level, message) {
// Log Message
const payload = {
level: level,
message: message,
};
SendMessage('log', payload);
} |
JavaScript | function Invoke(message) {
if (window.wailsbridge) {
window.wailsbridge.websocket.send(message);
} else {
window.external.invoke(message);
}
// Also send to listeners
if (listeners.length > 0) {
for (var i = 0; i < listeners.length; i++) {
listeners[i](message);
}
}
} | function Invoke(message) {
if (window.wailsbridge) {
window.wailsbridge.websocket.send(message);
} else {
window.external.invoke(message);
}
// Also send to listeners
if (listeners.length > 0) {
for (var i = 0; i < listeners.length; i++) {
listeners[i](message);
}
}
} |
JavaScript | function InjectCSS(css) {
var elem = document.createElement('style');
elem.setAttribute('type', 'text/css');
if (elem.styleSheet) {
elem.styleSheet.cssText = css;
} else {
elem.appendChild(document.createTextNode(css));
}
var head = document.head || document.getElementsByTagName('head')[0];
head.appendChild(elem);
} | function InjectCSS(css) {
var elem = document.createElement('style');
elem.setAttribute('type', 'text/css');
if (elem.styleSheet) {
elem.styleSheet.cssText = css;
} else {
elem.appendChild(document.createTextNode(css));
}
var head = document.head || document.getElementsByTagName('head')[0];
head.appendChild(elem);
} |
JavaScript | goForward(e) {
e.preventDefault();
// Update the control plane in the global model, save it, and move to the next page
let model = this.props.model.updateIn(this.PATH_TO_CONTROL_PLANE, val => this.state.controlPlane);
this.props.updateGlobalState('model', model, this.props.next);
} | goForward(e) {
e.preventDefault();
// Update the control plane in the global model, save it, and move to the next page
let model = this.props.model.updateIn(this.PATH_TO_CONTROL_PLANE, val => this.state.controlPlane);
this.props.updateGlobalState('model', model, this.props.next);
} |
JavaScript | function loadConfig() {
return fetch('config.json')
.then(response => response.json())
.then((responseData) =>
{
return Object.assign(appConfigs, responseData);
});
} | function loadConfig() {
return fetch('config.json')
.then(response => response.json())
.then((responseData) =>
{
return Object.assign(appConfigs, responseData);
});
} |
JavaScript | function mergeInits(...inits) {
let mergedHeaders = {};
// Combine headers together
for (let init of inits) {
if (init.headers) {
Object.assign(mergedHeaders, init.headers);
}
}
return Object.assign({}, ...inits, {'headers': mergedHeaders});
} | function mergeInits(...inits) {
let mergedHeaders = {};
// Combine headers together
for (let init of inits) {
if (init.headers) {
Object.assign(mergedHeaders, init.headers);
}
}
return Object.assign({}, ...inits, {'headers': mergedHeaders});
} |
JavaScript | function extractResponse(response) {
return response.text()
.then(txt => {
// Attempt to extract the text (and convert from JSON) if possible, even
// if the response was an error, in order to provide that information back to
// the caller
let value;
try {
// JSON.parse is used here instead of response.json because sometimes
// the return value is just text, and it makes the promise chain handling
// overly convoluted to try to use response.json sometimes and response.txt
// when that fails, while at the same time propagating exceptions up when
// the ardana service reports an error.
value = JSON.parse(txt);
} catch (SyntaxError) {
// Unable to convert to json, returning text
value = txt;
}
if (response.ok) {
return value;
} else {
return Promise.reject(new RestError(response.statusText, response.status, value));
}
});
} | function extractResponse(response) {
return response.text()
.then(txt => {
// Attempt to extract the text (and convert from JSON) if possible, even
// if the response was an error, in order to provide that information back to
// the caller
let value;
try {
// JSON.parse is used here instead of response.json because sometimes
// the return value is just text, and it makes the promise chain handling
// overly convoluted to try to use response.json sometimes and response.txt
// when that fails, while at the same time propagating exceptions up when
// the ardana service reports an error.
value = JSON.parse(txt);
} catch (SyntaxError) {
// Unable to convert to json, returning text
value = txt;
}
if (response.ok) {
return value;
} else {
return Promise.reject(new RestError(response.statusText, response.status, value));
}
});
} |
JavaScript | function buildUrl(url) {
return getConfig('shimurl').
then(val => {
if (url.startsWith('http')) {
return url;
} else {
// prepend the shimurl if we receive a URL without a scheme. Note that the incoming
// url may contain a leading / but is not required to.
return val + '/' + url.replace(/^\//, '');
}
});
} | function buildUrl(url) {
return getConfig('shimurl').
then(val => {
if (url.startsWith('http')) {
return url;
} else {
// prepend the shimurl if we receive a URL without a scheme. Note that the incoming
// url may contain a leading / but is not required to.
return val + '/' + url.replace(/^\//, '');
}
});
} |
JavaScript | render() {
let addClass = 'material-icons add-button';
let editClass = 'glyphicon glyphicon-pencil edit-button';
let removeClass = 'glyphicon glyphicon-trash remove-button';
if (this.state.overallMode != MODE.NONE) {
addClass += ' disabled';
editClass += ' disabled';
removeClass += ' disabled';
}
// build the rows in the main table
const rows = this.getRows()
.map((m,idx) => {
return (
<tr key={idx}>
<td>{m.get('name')}</td>
<td>{m.get('network-interfaces', new List()).size}</td>
<td>
<div className='row-action-container'>
<span className={editClass}
onClick={(e) => this.editModel(e, idx)} />
<span className={removeClass}
onClick={(e) => this.setState({activeOverallRow: idx, showRemoveConfirmation: true})} />
</div>
</td>
</tr>);
});
// build the action row at the bottom of the main table
const actionRow = (
<tr key='addModel' className='action-row'>
<td colSpan="3">
<i className={addClass} onClick={this.addModel}>add_circle</i>
{translate('add.interface.model')}
</td>
</tr>
);
let extendedClass = 'extended-one';
let tableWidthClass = 'col-xs-12';
let detailWidthClass = '';
if (this.state.overallMode !== MODE.NONE) {
if (this.state.detailMode === MODE.NONE) {
tableWidthClass = 'col-xs-8 verticalLine';
detailWidthClass = 'col-xs-4';
} else {
extendedClass = 'extended-two';
tableWidthClass = 'col-xs-6 verticalLine';
detailWidthClass = 'col-xs-6 multiple-details';
}
}
return (
<div className={extendedClass}>
<div className={tableWidthClass}>
<table className='table'>
<thead>
<tr>
<th>{translate('interface.model')}</th>
<th>{translate('network.interfaces')}</th>
<th></th>
</tr>
</thead>
<tbody>
{rows}
{actionRow}
</tbody>
</table>
</div>
<div className={detailWidthClass}>
{this.renderModelDetails()}
{this.renderInterfaceDetails()}
</div>
{this.confirmModal()}
</div>
);
} | render() {
let addClass = 'material-icons add-button';
let editClass = 'glyphicon glyphicon-pencil edit-button';
let removeClass = 'glyphicon glyphicon-trash remove-button';
if (this.state.overallMode != MODE.NONE) {
addClass += ' disabled';
editClass += ' disabled';
removeClass += ' disabled';
}
// build the rows in the main table
const rows = this.getRows()
.map((m,idx) => {
return (
<tr key={idx}>
<td>{m.get('name')}</td>
<td>{m.get('network-interfaces', new List()).size}</td>
<td>
<div className='row-action-container'>
<span className={editClass}
onClick={(e) => this.editModel(e, idx)} />
<span className={removeClass}
onClick={(e) => this.setState({activeOverallRow: idx, showRemoveConfirmation: true})} />
</div>
</td>
</tr>);
});
// build the action row at the bottom of the main table
const actionRow = (
<tr key='addModel' className='action-row'>
<td colSpan="3">
<i className={addClass} onClick={this.addModel}>add_circle</i>
{translate('add.interface.model')}
</td>
</tr>
);
let extendedClass = 'extended-one';
let tableWidthClass = 'col-xs-12';
let detailWidthClass = '';
if (this.state.overallMode !== MODE.NONE) {
if (this.state.detailMode === MODE.NONE) {
tableWidthClass = 'col-xs-8 verticalLine';
detailWidthClass = 'col-xs-4';
} else {
extendedClass = 'extended-two';
tableWidthClass = 'col-xs-6 verticalLine';
detailWidthClass = 'col-xs-6 multiple-details';
}
}
return (
<div className={extendedClass}>
<div className={tableWidthClass}>
<table className='table'>
<thead>
<tr>
<th>{translate('interface.model')}</th>
<th>{translate('network.interfaces')}</th>
<th></th>
</tr>
</thead>
<tbody>
{rows}
{actionRow}
</tbody>
</table>
</div>
<div className={detailWidthClass}>
{this.renderModelDetails()}
{this.renderInterfaceDetails()}
</div>
{this.confirmModal()}
</div>
);
} |
JavaScript | areStepsInOrder(currentStateSteps, expectedOrder) {
if(currentStateSteps.length !== expectedOrder.length) {
return false;
}
for(var i = 0; i < currentStateSteps.length; i++) {
if(currentStateSteps[i].name !== expectedOrder[i].name) {
return false;
}
}
return true;
} | areStepsInOrder(currentStateSteps, expectedOrder) {
if(currentStateSteps.length !== expectedOrder.length) {
return false;
}
for(var i = 0; i < currentStateSteps.length; i++) {
if(currentStateSteps[i].name !== expectedOrder[i].name) {
return false;
}
}
return true;
} |
JavaScript | buildElement() {
if (this.state.currentStep === undefined) {
return (<div className="loading-message">{translate('wizard.loading.pleasewait')}</div>);
}
let props = {};
//check if first element
if(this.state.currentStep !== 0) {
props.back = this.stepBack.bind(this);
}
//check for additional steps
if(this.state.currentStep < (this.props.pages.length - 1)) {
props.next = this.stepForward.bind(this);
}
//Pass all global state vars as properties
for (let v of this.globalStateVars) {
props[v] = this.state[v];
}
//Pass the update function as a property
props.updateGlobalState = this.updateGlobalState;
//Pass functions to force a model save and reload
props.saveModel = this.saveModel;
props.loadModel = this.loadModel;
return React.createElement(this.props.pages[this.state.currentStep].component, props);
} | buildElement() {
if (this.state.currentStep === undefined) {
return (<div className="loading-message">{translate('wizard.loading.pleasewait')}</div>);
}
let props = {};
//check if first element
if(this.state.currentStep !== 0) {
props.back = this.stepBack.bind(this);
}
//check for additional steps
if(this.state.currentStep < (this.props.pages.length - 1)) {
props.next = this.stepForward.bind(this);
}
//Pass all global state vars as properties
for (let v of this.globalStateVars) {
props[v] = this.state[v];
}
//Pass the update function as a property
props.updateGlobalState = this.updateGlobalState;
//Pass functions to force a model save and reload
props.saveModel = this.saveModel;
props.loadModel = this.loadModel;
return React.createElement(this.props.pages[this.state.currentStep].component, props);
} |
JavaScript | stepForward(isError) {
//TODO - update state setting logic to accept error states
var steps = this.state.steps, stateUpdates = {};
if(isError) {
steps[this.state.currentStep].stepProgress = STATUS.FAILED;
} else {
steps[this.state.currentStep].stepProgress = STATUS.COMPLETE;
//verify that there is a next page
if (steps[(this.state.currentStep + 1)]) {
//update the next step to inprogress
steps[(this.state.currentStep + 1)].stepProgress = STATUS.IN_PROGRESS;
//prepared to advance to the next page
stateUpdates.currentStep = this.state.currentStep + 1;
}
}
stateUpdates.steps = steps;
//setState is asynchronous, call the persistState function as a callback
this.setState(stateUpdates, this.persistState);
} | stepForward(isError) {
//TODO - update state setting logic to accept error states
var steps = this.state.steps, stateUpdates = {};
if(isError) {
steps[this.state.currentStep].stepProgress = STATUS.FAILED;
} else {
steps[this.state.currentStep].stepProgress = STATUS.COMPLETE;
//verify that there is a next page
if (steps[(this.state.currentStep + 1)]) {
//update the next step to inprogress
steps[(this.state.currentStep + 1)].stepProgress = STATUS.IN_PROGRESS;
//prepared to advance to the next page
stateUpdates.currentStep = this.state.currentStep + 1;
}
}
stateUpdates.steps = steps;
//setState is asynchronous, call the persistState function as a callback
this.setState(stateUpdates, this.persistState);
} |
JavaScript | stepBack(isError) {
//TODO - update state setting logic to accept error states
var steps = this.state.steps, stateUpdates = {};
if(isError) {
steps[this.state.currentStep].stepProgress = STATUS.FAILED;
} else {
steps[this.state.currentStep].stepProgress = STATUS.NOT_STARTED;
}
//verify that there is a previous page
if(steps[(this.state.currentStep - 1)]) {
//update previous step to inprogress
steps[(this.state.currentStep - 1)].stepProgress = STATUS.IN_PROGRESS;
//prepare to go back a page
stateUpdates.currentStep = this.state.currentStep - 1;
}
stateUpdates.steps = steps;
//setState is asynchronous, call the persistState function as a callback
this.setState(stateUpdates, this.persistState);
} | stepBack(isError) {
//TODO - update state setting logic to accept error states
var steps = this.state.steps, stateUpdates = {};
if(isError) {
steps[this.state.currentStep].stepProgress = STATUS.FAILED;
} else {
steps[this.state.currentStep].stepProgress = STATUS.NOT_STARTED;
}
//verify that there is a previous page
if(steps[(this.state.currentStep - 1)]) {
//update previous step to inprogress
steps[(this.state.currentStep - 1)].stepProgress = STATUS.IN_PROGRESS;
//prepare to go back a page
stateUpdates.currentStep = this.state.currentStep - 1;
}
stateUpdates.steps = steps;
//setState is asynchronous, call the persistState function as a callback
this.setState(stateUpdates, this.persistState);
} |
JavaScript | stepTo(stepNumber) {
var steps = this.state.steps, stateUpdates = {};
// sanity check the stepNumber, it must be greater than 0 and less than the current step
if(stepNumber >= 0 && this.state.currentStep > stepNumber) {
let i = this.state.currentStep;
while(i > stepNumber) {
steps[i].stepProgress = STATUS.NOT_STARTED;
i--;
}
steps[stepNumber].stepProgress = STATUS.IN_PROGRESS;
stateUpdates.currentStep = stepNumber;
stateUpdates.steps = steps;
this.setState(stateUpdates, this.persistState);
}
} | stepTo(stepNumber) {
var steps = this.state.steps, stateUpdates = {};
// sanity check the stepNumber, it must be greater than 0 and less than the current step
if(stepNumber >= 0 && this.state.currentStep > stepNumber) {
let i = this.state.currentStep;
while(i > stepNumber) {
steps[i].stepProgress = STATUS.NOT_STARTED;
i--;
}
steps[stepNumber].stepProgress = STATUS.IN_PROGRESS;
stateUpdates.currentStep = stepNumber;
stateUpdates.steps = steps;
this.setState(stateUpdates, this.persistState);
}
} |
JavaScript | async function translationsExport() {
return gulp
.src('src/**/*.ts')
.pipe(nls.createMetaDataFiles())
.pipe(filter(['**/*.nls.json', '**/*.nls.metadata.json']))
.pipe(nls.bundleMetaDataFiles('ms-vscode.powerplatform', '.'))
.pipe(filter(['**/nls.metadata.header.json', '**/nls.metadata.json']))
.pipe(gulp.src(["package.nls.json"]))
.pipe(nls.createXlfFiles("translations-export", translationExtensionName))
.pipe(gulp.dest(path.join("loc")));
} | async function translationsExport() {
return gulp
.src('src/**/*.ts')
.pipe(nls.createMetaDataFiles())
.pipe(filter(['**/*.nls.json', '**/*.nls.metadata.json']))
.pipe(nls.bundleMetaDataFiles('ms-vscode.powerplatform', '.'))
.pipe(filter(['**/nls.metadata.header.json', '**/nls.metadata.json']))
.pipe(gulp.src(["package.nls.json"]))
.pipe(nls.createXlfFiles("translations-export", translationExtensionName))
.pipe(gulp.dest(path.join("loc")));
} |
JavaScript | function inject(/* fn(stores, nextProps) or ...storeNames */ ...storeNames) {
let grabStoresFn
if (typeof arguments[0] === "function") {
grabStoresFn = arguments[0]
return componentClass =>
createStoreInjector(grabStoresFn, componentClass, grabStoresFn.name, true)
} else {
return componentClass =>
createStoreInjector(
grabStoresByName(storeNames),
componentClass,
storeNames.join("-"),
false
)
}
} | function inject(/* fn(stores, nextProps) or ...storeNames */ ...storeNames) {
let grabStoresFn
if (typeof arguments[0] === "function") {
grabStoresFn = arguments[0]
return componentClass =>
createStoreInjector(grabStoresFn, componentClass, grabStoresFn.name, true)
} else {
return componentClass =>
createStoreInjector(
grabStoresByName(storeNames),
componentClass,
storeNames.join("-"),
false
)
}
} |
JavaScript | handleActiveGet(callback) {
this.log.debug('Triggered GET Active');
callback(null, this.active);
} | handleActiveGet(callback) {
this.log.debug('Triggered GET Active');
callback(null, this.active);
} |
JavaScript | handleActiveSet(value, callback) {
this.log.debug('Triggered SET Active:' + value);
var form;
var state_to_change;
if (value) {
if (this.aircon_target_state == Characteristic.TargetHeaterCoolerState.HEAT) {
if (this.aircon_state == Characteristic.CurrentHeaterCoolerState.HEATING) {
callback(null);
return;
}
form = this.heater_form;
state_to_change = Characteristic.CurrentHeaterCoolerState.HEATING;
this.log("Setting state to heat.");
} else if (this.aircon_target_state == Characteristic.TargetHeaterCoolerState.COOL) {
if (this.aircon_state == Characteristic.CurrentHeaterCoolerState.COOLING) {
callback(null);
return;
}
form = this.cooler_form;
state_to_change = Characteristic.CurrentHeaterCoolerState.COOLING;
this.log("Setting state to cool.");
} else if (this.aircon_target_state == Characteristic.TargetHeaterCoolerState.AUTO) {
form = this.auto_form;
state_to_change = Characteristic.CurrentHeaterCoolerState.IDLE;
this.log("Setting state to auto.");
}
} else {
form = this.off_form;
state_to_change = Characteristic.CurrentHeaterCoolerState.IDLE;
this.log("Setting power state to off");
}
this.httpRequestSerialized(this.irkit_host, form, callback, () => {this.active = value; this.aircon_state = state_to_change});
} | handleActiveSet(value, callback) {
this.log.debug('Triggered SET Active:' + value);
var form;
var state_to_change;
if (value) {
if (this.aircon_target_state == Characteristic.TargetHeaterCoolerState.HEAT) {
if (this.aircon_state == Characteristic.CurrentHeaterCoolerState.HEATING) {
callback(null);
return;
}
form = this.heater_form;
state_to_change = Characteristic.CurrentHeaterCoolerState.HEATING;
this.log("Setting state to heat.");
} else if (this.aircon_target_state == Characteristic.TargetHeaterCoolerState.COOL) {
if (this.aircon_state == Characteristic.CurrentHeaterCoolerState.COOLING) {
callback(null);
return;
}
form = this.cooler_form;
state_to_change = Characteristic.CurrentHeaterCoolerState.COOLING;
this.log("Setting state to cool.");
} else if (this.aircon_target_state == Characteristic.TargetHeaterCoolerState.AUTO) {
form = this.auto_form;
state_to_change = Characteristic.CurrentHeaterCoolerState.IDLE;
this.log("Setting state to auto.");
}
} else {
form = this.off_form;
state_to_change = Characteristic.CurrentHeaterCoolerState.IDLE;
this.log("Setting power state to off");
}
this.httpRequestSerialized(this.irkit_host, form, callback, () => {this.active = value; this.aircon_state = state_to_change});
} |
JavaScript | handleCurrentHeaterCoolerStateGet(callback) {
this.log.debug('Triggered GET CurrentHeaterCoolerState');
callback(null, this.aircon_state);
} | handleCurrentHeaterCoolerStateGet(callback) {
this.log.debug('Triggered GET CurrentHeaterCoolerState');
callback(null, this.aircon_state);
} |
JavaScript | handleTargetHeaterCoolerStateGet(callback) {
this.log.debug('Triggered GET TargetHeaterCoolerState');
callback(null, this.aircon_target_state);
} | handleTargetHeaterCoolerStateGet(callback) {
this.log.debug('Triggered GET TargetHeaterCoolerState');
callback(null, this.aircon_target_state);
} |
JavaScript | handleTargetHeaterCoolerStateSet(value, callback) {
this.log.debug('Triggered SET TargetHeaterCoolerState:' + value);
this.aircon_target_state = value;
callback(null);
} | handleTargetHeaterCoolerStateSet(value, callback) {
this.log.debug('Triggered SET TargetHeaterCoolerState:' + value);
this.aircon_target_state = value;
callback(null);
} |
JavaScript | handleCurrentTemperatureGet(callback) {
this.log.debug('Triggered GET CurrentTemperature');
if (this.config.temperature_file) {
this.temperature = parseFloat(fs.readFileSync(this.config.temperature_file));
}
callback(null, this.temperature);
} | handleCurrentTemperatureGet(callback) {
this.log.debug('Triggered GET CurrentTemperature');
if (this.config.temperature_file) {
this.temperature = parseFloat(fs.readFileSync(this.config.temperature_file));
}
callback(null, this.temperature);
} |
JavaScript | handleMuteGet(callback) {
this.log.debug('Triggered GET Mute');
callback(null, this.mute_status);
} | handleMuteGet(callback) {
this.log.debug('Triggered GET Mute');
callback(null, this.mute_status);
} |
JavaScript | handleMuteSet(state, callback) {
this.log.debug('Triggered SET Mute:' + state);
this.httpRequestSerialized(this.irkit_host, this.mute_form);
this.mute_status = state;
callback(null);
} | handleMuteSet(state, callback) {
this.log.debug('Triggered SET Mute:' + state);
this.httpRequestSerialized(this.irkit_host, this.mute_form);
this.mute_status = state;
callback(null);
} |
JavaScript | static async createWithSeed(fromPublicKey, seed, programId) {
const buffer$1 = buffer.Buffer.concat([fromPublicKey.toBuffer(), buffer.Buffer.from(seed), programId.toBuffer()]);
const hash = await sha256(new Uint8Array(buffer$1));
return new PublicKey(buffer.Buffer.from(hash, 'hex'));
} | static async createWithSeed(fromPublicKey, seed, programId) {
const buffer$1 = buffer.Buffer.concat([fromPublicKey.toBuffer(), buffer.Buffer.from(seed), programId.toBuffer()]);
const hash = await sha256(new Uint8Array(buffer$1));
return new PublicKey(buffer.Buffer.from(hash, 'hex'));
} |
JavaScript | static async createProgramAddress(seeds, programId) {
let buffer$1 = buffer.Buffer.alloc(0);
seeds.forEach(function (seed) {
if (seed.length > MAX_SEED_LENGTH) {
throw new Error("Max seed length exceeded");
}
buffer$1 = buffer.Buffer.concat([buffer$1, buffer.Buffer.from(seed)]);
});
buffer$1 = buffer.Buffer.concat([buffer$1, programId.toBuffer(), buffer.Buffer.from('ProgramDerivedAddress')]);
let hash = await sha256(new Uint8Array(buffer$1));
let publicKeyBytes = new BN(hash, 16).toArray(undefined, 32);
if (is_on_curve(publicKeyBytes)) {
throw new Error("Invalid seeds, address must fall off the curve");
}
return new PublicKey(publicKeyBytes);
} | static async createProgramAddress(seeds, programId) {
let buffer$1 = buffer.Buffer.alloc(0);
seeds.forEach(function (seed) {
if (seed.length > MAX_SEED_LENGTH) {
throw new Error("Max seed length exceeded");
}
buffer$1 = buffer.Buffer.concat([buffer$1, buffer.Buffer.from(seed)]);
});
buffer$1 = buffer.Buffer.concat([buffer$1, programId.toBuffer(), buffer.Buffer.from('ProgramDerivedAddress')]);
let hash = await sha256(new Uint8Array(buffer$1));
let publicKeyBytes = new BN(hash, 16).toArray(undefined, 32);
if (is_on_curve(publicKeyBytes)) {
throw new Error("Invalid seeds, address must fall off the curve");
}
return new PublicKey(publicKeyBytes);
} |
JavaScript | static async findProgramAddress(seeds, programId) {
let nonce = 255;
let address;
while (nonce != 0) {
try {
const seedsWithNonce = seeds.concat(buffer.Buffer.from([nonce]));
address = await this.createProgramAddress(seedsWithNonce, programId);
} catch (err) {
nonce--;
continue;
}
return [address, nonce];
}
throw new Error("Unable to find a viable program address nonce");
} | static async findProgramAddress(seeds, programId) {
let nonce = 255;
let address;
while (nonce != 0) {
try {
const seedsWithNonce = seeds.concat(buffer.Buffer.from([nonce]));
address = await this.createProgramAddress(seedsWithNonce, programId);
} catch (err) {
nonce--;
continue;
}
return [address, nonce];
}
throw new Error("Unable to find a viable program address nonce");
} |
JavaScript | function nameWithProperty(name, lo) {
if (lo.property) {
return name + '[' + lo.property + ']';
}
return name;
} | function nameWithProperty(name, lo) {
if (lo.property) {
return name + '[' + lo.property + ']';
}
return name;
} |
JavaScript | function divmodInt64(src) {
const hi32 = Math.floor(src / V2E32);
const lo32 = src - (hi32 * V2E32);
// assert.equal(roundedInt64(hi32, lo32), src);
// assert(0 <= lo32);
return {hi32, lo32};
} | function divmodInt64(src) {
const hi32 = Math.floor(src / V2E32);
const lo32 = src - (hi32 * V2E32);
// assert.equal(roundedInt64(hi32, lo32), src);
// assert(0 <= lo32);
return {hi32, lo32};
} |
JavaScript | encode(src, b, offset) {
if (undefined === offset) {
offset = 0;
}
const firstOffset = offset;
let lastOffset = 0;
let lastWrote = 0;
for (const fd of this.fields) {
let span = fd.span;
lastWrote = (0 < span) ? span : 0;
if (undefined === fd.property) {
/* By construction the field must be fixed-length (because
* unnamed variable-length fields are disallowed when
* encoding). But check it anyway. */
assert(0 < span);
} else {
const fv = src[fd.property];
if (undefined !== fv) {
lastWrote = fd.encode(fv, b, offset);
if (0 > span) {
/* Read the as-encoded span, which is not necessarily the
* same as what we wrote. */
span = fd.getSpan(b, offset);
}
}
}
lastOffset = offset;
offset += span;
}
/* Use (lastOffset + lastWrote) instead of offset because the last
* item may have had a dynamic length and we don't want to include
* the padding between it and the end of the space reserved for
* it. */
return (lastOffset + lastWrote) - firstOffset;
} | encode(src, b, offset) {
if (undefined === offset) {
offset = 0;
}
const firstOffset = offset;
let lastOffset = 0;
let lastWrote = 0;
for (const fd of this.fields) {
let span = fd.span;
lastWrote = (0 < span) ? span : 0;
if (undefined === fd.property) {
/* By construction the field must be fixed-length (because
* unnamed variable-length fields are disallowed when
* encoding). But check it anyway. */
assert(0 < span);
} else {
const fv = src[fd.property];
if (undefined !== fv) {
lastWrote = fd.encode(fv, b, offset);
if (0 > span) {
/* Read the as-encoded span, which is not necessarily the
* same as what we wrote. */
span = fd.getSpan(b, offset);
}
}
}
lastOffset = offset;
offset += span;
}
/* Use (lastOffset + lastWrote) instead of offset because the last
* item may have had a dynamic length and we don't want to include
* the padding between it and the end of the space reserved for
* it. */
return (lastOffset + lastWrote) - firstOffset;
} |
JavaScript | offsetOf(property) {
if ('string' !== typeof property) {
throw new TypeError('property must be string');
}
let offset = 0;
for (const fd of this.fields) {
if (fd.property === property) {
return offset;
}
if (0 > fd.span) {
offset = -1;
} else if (0 <= offset) {
offset += fd.span;
}
}
} | offsetOf(property) {
if ('string' !== typeof property) {
throw new TypeError('property must be string');
}
let offset = 0;
for (const fd of this.fields) {
if (fd.property === property) {
return offset;
}
if (0 > fd.span) {
offset = -1;
} else if (0 <= offset) {
offset += fd.span;
}
}
} |
JavaScript | static from(buffer$1) {
// Slice up wire data
let byteArray = [...buffer$1];
const numRequiredSignatures = byteArray.shift();
const numReadonlySignedAccounts = byteArray.shift();
const numReadonlyUnsignedAccounts = byteArray.shift();
const accountCount = decodeLength(byteArray);
let accountKeys = [];
for (let i = 0; i < accountCount; i++) {
const account = byteArray.slice(0, PUBKEY_LENGTH);
byteArray = byteArray.slice(PUBKEY_LENGTH);
accountKeys.push(bs58.encode(buffer.Buffer.from(account)));
}
const recentBlockhash = byteArray.slice(0, PUBKEY_LENGTH);
byteArray = byteArray.slice(PUBKEY_LENGTH);
const instructionCount = decodeLength(byteArray);
let instructions = [];
for (let i = 0; i < instructionCount; i++) {
const programIdIndex = byteArray.shift();
const accountCount = decodeLength(byteArray);
const accounts = byteArray.slice(0, accountCount);
byteArray = byteArray.slice(accountCount);
const dataLength = decodeLength(byteArray);
const dataSlice = byteArray.slice(0, dataLength);
const data = bs58.encode(buffer.Buffer.from(dataSlice));
byteArray = byteArray.slice(dataLength);
instructions.push({
programIdIndex,
accounts,
data
});
}
const messageArgs = {
header: {
numRequiredSignatures,
numReadonlySignedAccounts,
numReadonlyUnsignedAccounts
},
recentBlockhash: bs58.encode(buffer.Buffer.from(recentBlockhash)),
accountKeys,
instructions
};
return new Message(messageArgs);
} | static from(buffer$1) {
// Slice up wire data
let byteArray = [...buffer$1];
const numRequiredSignatures = byteArray.shift();
const numReadonlySignedAccounts = byteArray.shift();
const numReadonlyUnsignedAccounts = byteArray.shift();
const accountCount = decodeLength(byteArray);
let accountKeys = [];
for (let i = 0; i < accountCount; i++) {
const account = byteArray.slice(0, PUBKEY_LENGTH);
byteArray = byteArray.slice(PUBKEY_LENGTH);
accountKeys.push(bs58.encode(buffer.Buffer.from(account)));
}
const recentBlockhash = byteArray.slice(0, PUBKEY_LENGTH);
byteArray = byteArray.slice(PUBKEY_LENGTH);
const instructionCount = decodeLength(byteArray);
let instructions = [];
for (let i = 0; i < instructionCount; i++) {
const programIdIndex = byteArray.shift();
const accountCount = decodeLength(byteArray);
const accounts = byteArray.slice(0, accountCount);
byteArray = byteArray.slice(accountCount);
const dataLength = decodeLength(byteArray);
const dataSlice = byteArray.slice(0, dataLength);
const data = bs58.encode(buffer.Buffer.from(dataSlice));
byteArray = byteArray.slice(dataLength);
instructions.push({
programIdIndex,
accounts,
data
});
}
const messageArgs = {
header: {
numRequiredSignatures,
numReadonlySignedAccounts,
numReadonlyUnsignedAccounts
},
recentBlockhash: bs58.encode(buffer.Buffer.from(recentBlockhash)),
accountKeys,
instructions
};
return new Message(messageArgs);
} |
JavaScript | static from(buffer$1) {
// Slice up wire data
let byteArray = [...buffer$1];
const signatureCount = decodeLength(byteArray);
let signatures = [];
for (let i = 0; i < signatureCount; i++) {
const signature = byteArray.slice(0, SIGNATURE_LENGTH);
byteArray = byteArray.slice(SIGNATURE_LENGTH);
signatures.push(bs58.encode(buffer.Buffer.from(signature)));
}
return Transaction.populate(Message.from(byteArray), signatures);
} | static from(buffer$1) {
// Slice up wire data
let byteArray = [...buffer$1];
const signatureCount = decodeLength(byteArray);
let signatures = [];
for (let i = 0; i < signatureCount; i++) {
const signature = byteArray.slice(0, SIGNATURE_LENGTH);
byteArray = byteArray.slice(SIGNATURE_LENGTH);
signatures.push(bs58.encode(buffer.Buffer.from(signature)));
}
return Transaction.populate(Message.from(byteArray), signatures);
} |
JavaScript | static decodeInstructionType(instruction) {
this.checkProgramId(instruction.programId);
const instructionTypeLayout = u32('instruction');
const typeIndex = instructionTypeLayout.decode(instruction.data);
let type;
for (const [ixType, layout] of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)) {
if (layout.index == typeIndex) {
type = ixType;
break;
}
}
if (!type) {
throw new Error('Instruction type incorrect; not a SystemInstruction');
}
return type;
} | static decodeInstructionType(instruction) {
this.checkProgramId(instruction.programId);
const instructionTypeLayout = u32('instruction');
const typeIndex = instructionTypeLayout.decode(instruction.data);
let type;
for (const [ixType, layout] of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)) {
if (layout.index == typeIndex) {
type = ixType;
break;
}
}
if (!type) {
throw new Error('Instruction type incorrect; not a SystemInstruction');
}
return type;
} |
JavaScript | static createAccount(params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Create;
const data = encodeData(type, {
lamports: params.lamports,
space: params.space,
programId: params.programId.toBuffer()
});
return new TransactionInstruction({
keys: [{
pubkey: params.fromPubkey,
isSigner: true,
isWritable: true
}, {
pubkey: params.newAccountPubkey,
isSigner: true,
isWritable: true
}],
programId: this.programId,
data
});
} | static createAccount(params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Create;
const data = encodeData(type, {
lamports: params.lamports,
space: params.space,
programId: params.programId.toBuffer()
});
return new TransactionInstruction({
keys: [{
pubkey: params.fromPubkey,
isSigner: true,
isWritable: true
}, {
pubkey: params.newAccountPubkey,
isSigner: true,
isWritable: true
}],
programId: this.programId,
data
});
} |
JavaScript | static transfer(params) {
let data;
let keys;
if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;
data = encodeData(type, {
lamports: params.lamports,
seed: params.seed,
programId: params.programId.toBuffer()
});
keys = [{
pubkey: params.fromPubkey,
isSigner: false,
isWritable: true
}, {
pubkey: params.basePubkey,
isSigner: true,
isWritable: false
}, {
pubkey: params.toPubkey,
isSigner: false,
isWritable: true
}];
} else {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;
data = encodeData(type, {
lamports: params.lamports
});
keys = [{
pubkey: params.fromPubkey,
isSigner: true,
isWritable: true
}, {
pubkey: params.toPubkey,
isSigner: false,
isWritable: true
}];
}
return new TransactionInstruction({
keys,
programId: this.programId,
data
});
} | static transfer(params) {
let data;
let keys;
if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;
data = encodeData(type, {
lamports: params.lamports,
seed: params.seed,
programId: params.programId.toBuffer()
});
keys = [{
pubkey: params.fromPubkey,
isSigner: false,
isWritable: true
}, {
pubkey: params.basePubkey,
isSigner: true,
isWritable: false
}, {
pubkey: params.toPubkey,
isSigner: false,
isWritable: true
}];
} else {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;
data = encodeData(type, {
lamports: params.lamports
});
keys = [{
pubkey: params.fromPubkey,
isSigner: true,
isWritable: true
}, {
pubkey: params.toPubkey,
isSigner: false,
isWritable: true
}];
}
return new TransactionInstruction({
keys,
programId: this.programId,
data
});
} |
JavaScript | static assign(params) {
let data;
let keys;
if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;
data = encodeData(type, {
base: params.basePubkey.toBuffer(),
seed: params.seed,
programId: params.programId.toBuffer()
});
keys = [{
pubkey: params.accountPubkey,
isSigner: false,
isWritable: true
}, {
pubkey: params.basePubkey,
isSigner: true,
isWritable: false
}];
} else {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Assign;
data = encodeData(type, {
programId: params.programId.toBuffer()
});
keys = [{
pubkey: params.accountPubkey,
isSigner: true,
isWritable: true
}];
}
return new TransactionInstruction({
keys,
programId: this.programId,
data
});
} | static assign(params) {
let data;
let keys;
if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;
data = encodeData(type, {
base: params.basePubkey.toBuffer(),
seed: params.seed,
programId: params.programId.toBuffer()
});
keys = [{
pubkey: params.accountPubkey,
isSigner: false,
isWritable: true
}, {
pubkey: params.basePubkey,
isSigner: true,
isWritable: false
}];
} else {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Assign;
data = encodeData(type, {
programId: params.programId.toBuffer()
});
keys = [{
pubkey: params.accountPubkey,
isSigner: true,
isWritable: true
}];
}
return new TransactionInstruction({
keys,
programId: this.programId,
data
});
} |
JavaScript | static createAccountWithSeed(params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;
const data = encodeData(type, {
base: params.basePubkey.toBuffer(),
seed: params.seed,
lamports: params.lamports,
space: params.space,
programId: params.programId.toBuffer()
});
let keys = [{
pubkey: params.fromPubkey,
isSigner: true,
isWritable: true
}, {
pubkey: params.newAccountPubkey,
isSigner: false,
isWritable: true
}];
if (params.basePubkey != params.fromPubkey) {
keys.push({
pubkey: params.basePubkey,
isSigner: true,
isWritable: false
});
}
return new TransactionInstruction({
keys,
programId: this.programId,
data
});
} | static createAccountWithSeed(params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;
const data = encodeData(type, {
base: params.basePubkey.toBuffer(),
seed: params.seed,
lamports: params.lamports,
space: params.space,
programId: params.programId.toBuffer()
});
let keys = [{
pubkey: params.fromPubkey,
isSigner: true,
isWritable: true
}, {
pubkey: params.newAccountPubkey,
isSigner: false,
isWritable: true
}];
if (params.basePubkey != params.fromPubkey) {
keys.push({
pubkey: params.basePubkey,
isSigner: true,
isWritable: false
});
}
return new TransactionInstruction({
keys,
programId: this.programId,
data
});
} |
JavaScript | static nonceInitialize(params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;
const data = encodeData(type, {
authorized: params.authorizedPubkey.toBuffer()
});
const instructionData = {
keys: [{
pubkey: params.noncePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,
isSigner: false,
isWritable: false
}, {
pubkey: SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false
}],
programId: this.programId,
data
};
return new TransactionInstruction(instructionData);
} | static nonceInitialize(params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;
const data = encodeData(type, {
authorized: params.authorizedPubkey.toBuffer()
});
const instructionData = {
keys: [{
pubkey: params.noncePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,
isSigner: false,
isWritable: false
}, {
pubkey: SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false
}],
programId: this.programId,
data
};
return new TransactionInstruction(instructionData);
} |
JavaScript | static nonceAuthorize(params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;
const data = encodeData(type, {
authorized: params.newAuthorizedPubkey.toBuffer()
});
return new TransactionInstruction({
keys: [{
pubkey: params.noncePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: params.authorizedPubkey,
isSigner: true,
isWritable: false
}],
programId: this.programId,
data
});
} | static nonceAuthorize(params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;
const data = encodeData(type, {
authorized: params.newAuthorizedPubkey.toBuffer()
});
return new TransactionInstruction({
keys: [{
pubkey: params.noncePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: params.authorizedPubkey,
isSigner: true,
isWritable: false
}],
programId: this.programId,
data
});
} |
JavaScript | static allocate(params) {
let data;
let keys;
if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;
data = encodeData(type, {
base: params.basePubkey.toBuffer(),
seed: params.seed,
space: params.space,
programId: params.programId.toBuffer()
});
keys = [{
pubkey: params.accountPubkey,
isSigner: false,
isWritable: true
}, {
pubkey: params.basePubkey,
isSigner: true,
isWritable: false
}];
} else {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;
data = encodeData(type, {
space: params.space
});
keys = [{
pubkey: params.accountPubkey,
isSigner: true,
isWritable: true
}];
}
return new TransactionInstruction({
keys,
programId: this.programId,
data
});
} | static allocate(params) {
let data;
let keys;
if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;
data = encodeData(type, {
base: params.basePubkey.toBuffer(),
seed: params.seed,
space: params.space,
programId: params.programId.toBuffer()
});
keys = [{
pubkey: params.accountPubkey,
isSigner: false,
isWritable: true
}, {
pubkey: params.basePubkey,
isSigner: true,
isWritable: false
}];
} else {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;
data = encodeData(type, {
space: params.space
});
keys = [{
pubkey: params.accountPubkey,
isSigner: true,
isWritable: true
}];
}
return new TransactionInstruction({
keys,
programId: this.programId,
data
});
} |
JavaScript | static get chunkSize() {
// Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the
// rest of the Transaction fields
//
// TODO: replace 300 with a proper constant for the size of the other
// Transaction fields
return PACKET_DATA_SIZE - 300;
} | static get chunkSize() {
// Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the
// rest of the Transaction fields
//
// TODO: replace 300 with a proper constant for the size of the other
// Transaction fields
return PACKET_DATA_SIZE - 300;
} |
JavaScript | async confirmTransaction(signature, commitment) {
let decodedSignature;
try {
decodedSignature = bs58.decode(signature);
} catch (err) {
throw new Error('signature must be base58 encoded: ' + signature);
}
assert$1(decodedSignature.length === 64, 'signature has invalid length');
const start = Date.now();
const subscriptionCommitment = commitment || this.commitment;
let subscriptionId;
let response = null;
const confirmPromise = new Promise((resolve, reject) => {
try {
subscriptionId = this.onSignature(signature, (result, context) => {
subscriptionId = undefined;
response = {
context,
value: result
};
resolve(null);
}, subscriptionCommitment);
} catch (err) {
reject(err);
}
});
let timeoutMs = 60 * 1000;
switch (subscriptionCommitment) {
case 'processed':
case 'recent':
case 'single':
case 'confirmed':
case 'singleGossip':
{
timeoutMs = 30 * 1000;
break;
}
}
try {
await promiseTimeout(confirmPromise, timeoutMs);
} finally {
if (subscriptionId) {
this.removeSignatureListener(subscriptionId);
}
}
if (response === null) {
const duration = (Date.now() - start) / 1000;
throw new Error("Transaction was not confirmed in ".concat(duration.toFixed(2), " seconds. It is unknown if it succeeded or failed. Check signature ").concat(signature, " using the Solana Explorer or CLI tools."));
}
return response;
} | async confirmTransaction(signature, commitment) {
let decodedSignature;
try {
decodedSignature = bs58.decode(signature);
} catch (err) {
throw new Error('signature must be base58 encoded: ' + signature);
}
assert$1(decodedSignature.length === 64, 'signature has invalid length');
const start = Date.now();
const subscriptionCommitment = commitment || this.commitment;
let subscriptionId;
let response = null;
const confirmPromise = new Promise((resolve, reject) => {
try {
subscriptionId = this.onSignature(signature, (result, context) => {
subscriptionId = undefined;
response = {
context,
value: result
};
resolve(null);
}, subscriptionCommitment);
} catch (err) {
reject(err);
}
});
let timeoutMs = 60 * 1000;
switch (subscriptionCommitment) {
case 'processed':
case 'recent':
case 'single':
case 'confirmed':
case 'singleGossip':
{
timeoutMs = 30 * 1000;
break;
}
}
try {
await promiseTimeout(confirmPromise, timeoutMs);
} finally {
if (subscriptionId) {
this.removeSignatureListener(subscriptionId);
}
}
if (response === null) {
const duration = (Date.now() - start) / 1000;
throw new Error("Transaction was not confirmed in ".concat(duration.toFixed(2), " seconds. It is unknown if it succeeded or failed. Check signature ").concat(signature, " using the Solana Explorer or CLI tools."));
}
return response;
} |
JavaScript | static decodeInstructionType(instruction) {
this.checkProgramId(instruction.programId);
const instructionTypeLayout = u32('instruction');
const typeIndex = instructionTypeLayout.decode(instruction.data);
let type;
for (const [ixType, layout] of Object.entries(STAKE_INSTRUCTION_LAYOUTS)) {
if (layout.index == typeIndex) {
type = ixType;
break;
}
}
if (!type) {
throw new Error('Instruction type incorrect; not a StakeInstruction');
}
return type;
} | static decodeInstructionType(instruction) {
this.checkProgramId(instruction.programId);
const instructionTypeLayout = u32('instruction');
const typeIndex = instructionTypeLayout.decode(instruction.data);
let type;
for (const [ixType, layout] of Object.entries(STAKE_INSTRUCTION_LAYOUTS)) {
if (layout.index == typeIndex) {
type = ixType;
break;
}
}
if (!type) {
throw new Error('Instruction type incorrect; not a StakeInstruction');
}
return type;
} |
JavaScript | static decodeSplit(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 3);
const {
lamports
} = decodeData(STAKE_INSTRUCTION_LAYOUTS.Split, instruction.data); // @ts-ignore
return {
stakePubkey: instruction.keys[0].pubkey,
splitStakePubkey: instruction.keys[1].pubkey,
authorizedPubkey: instruction.keys[2].pubkey,
lamports
};
} | static decodeSplit(instruction) {
this.checkProgramId(instruction.programId);
this.checkKeyLength(instruction.keys, 3);
const {
lamports
} = decodeData(STAKE_INSTRUCTION_LAYOUTS.Split, instruction.data); // @ts-ignore
return {
stakePubkey: instruction.keys[0].pubkey,
splitStakePubkey: instruction.keys[1].pubkey,
authorizedPubkey: instruction.keys[2].pubkey,
lamports
};
} |
JavaScript | static initialize(params) {
const {
stakePubkey,
authorized,
lockup
} = params;
const type = STAKE_INSTRUCTION_LAYOUTS.Initialize;
const data = encodeData(type, {
authorized: {
staker: authorized.staker.toBuffer(),
withdrawer: authorized.withdrawer.toBuffer()
},
lockup: {
unixTimestamp: lockup.unixTimestamp,
epoch: lockup.epoch,
custodian: lockup.custodian.toBuffer()
}
});
const instructionData = {
keys: [{
pubkey: stakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false
}],
programId: this.programId,
data
};
return new TransactionInstruction(instructionData);
} | static initialize(params) {
const {
stakePubkey,
authorized,
lockup
} = params;
const type = STAKE_INSTRUCTION_LAYOUTS.Initialize;
const data = encodeData(type, {
authorized: {
staker: authorized.staker.toBuffer(),
withdrawer: authorized.withdrawer.toBuffer()
},
lockup: {
unixTimestamp: lockup.unixTimestamp,
epoch: lockup.epoch,
custodian: lockup.custodian.toBuffer()
}
});
const instructionData = {
keys: [{
pubkey: stakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false
}],
programId: this.programId,
data
};
return new TransactionInstruction(instructionData);
} |
JavaScript | static authorize(params) {
const {
stakePubkey,
authorizedPubkey,
newAuthorizedPubkey,
stakeAuthorizationType,
custodianPubkey
} = params;
const type = STAKE_INSTRUCTION_LAYOUTS.Authorize;
const data = encodeData(type, {
newAuthorized: newAuthorizedPubkey.toBuffer(),
stakeAuthorizationType: stakeAuthorizationType.index
});
const keys = [{
pubkey: stakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: SYSVAR_CLOCK_PUBKEY,
isSigner: false,
isWritable: true
}, {
pubkey: authorizedPubkey,
isSigner: true,
isWritable: false
}];
if (custodianPubkey) {
keys.push({
pubkey: custodianPubkey,
isSigner: false,
isWritable: false
});
}
return new Transaction().add({
keys,
programId: this.programId,
data
});
} | static authorize(params) {
const {
stakePubkey,
authorizedPubkey,
newAuthorizedPubkey,
stakeAuthorizationType,
custodianPubkey
} = params;
const type = STAKE_INSTRUCTION_LAYOUTS.Authorize;
const data = encodeData(type, {
newAuthorized: newAuthorizedPubkey.toBuffer(),
stakeAuthorizationType: stakeAuthorizationType.index
});
const keys = [{
pubkey: stakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: SYSVAR_CLOCK_PUBKEY,
isSigner: false,
isWritable: true
}, {
pubkey: authorizedPubkey,
isSigner: true,
isWritable: false
}];
if (custodianPubkey) {
keys.push({
pubkey: custodianPubkey,
isSigner: false,
isWritable: false
});
}
return new Transaction().add({
keys,
programId: this.programId,
data
});
} |
JavaScript | static authorizeWithSeed(params) {
const {
stakePubkey,
authorityBase,
authoritySeed,
authorityOwner,
newAuthorizedPubkey,
stakeAuthorizationType,
custodianPubkey
} = params;
const type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
const data = encodeData(type, {
newAuthorized: newAuthorizedPubkey.toBuffer(),
stakeAuthorizationType: stakeAuthorizationType.index,
authoritySeed: authoritySeed,
authorityOwner: authorityOwner.toBuffer()
});
const keys = [{
pubkey: stakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: authorityBase,
isSigner: true,
isWritable: false
}, {
pubkey: SYSVAR_CLOCK_PUBKEY,
isSigner: false,
isWritable: false
}];
if (custodianPubkey) {
keys.push({
pubkey: custodianPubkey,
isSigner: false,
isWritable: false
});
}
return new Transaction().add({
keys,
programId: this.programId,
data
});
} | static authorizeWithSeed(params) {
const {
stakePubkey,
authorityBase,
authoritySeed,
authorityOwner,
newAuthorizedPubkey,
stakeAuthorizationType,
custodianPubkey
} = params;
const type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
const data = encodeData(type, {
newAuthorized: newAuthorizedPubkey.toBuffer(),
stakeAuthorizationType: stakeAuthorizationType.index,
authoritySeed: authoritySeed,
authorityOwner: authorityOwner.toBuffer()
});
const keys = [{
pubkey: stakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: authorityBase,
isSigner: true,
isWritable: false
}, {
pubkey: SYSVAR_CLOCK_PUBKEY,
isSigner: false,
isWritable: false
}];
if (custodianPubkey) {
keys.push({
pubkey: custodianPubkey,
isSigner: false,
isWritable: false
});
}
return new Transaction().add({
keys,
programId: this.programId,
data
});
} |
JavaScript | static splitWithSeed(params) {
const {
stakePubkey,
authorizedPubkey,
splitStakePubkey,
lamports,
seed,
basePubkey
} = params;
const transaction = new Transaction();
transaction.add(SystemProgram.createAccountWithSeed({
fromPubkey: authorizedPubkey,
newAccountPubkey: splitStakePubkey,
lamports: 0,
seed: seed,
space: this.space,
programId: this.programId,
basePubkey: basePubkey
}));
const type = STAKE_INSTRUCTION_LAYOUTS.Split;
const data = encodeData(type, {
lamports
});
return transaction.add(new TransactionInstruction({
keys: [{
pubkey: stakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: splitStakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: authorizedPubkey,
isSigner: true,
isWritable: false
}],
programId: this.programId,
data
}));
} | static splitWithSeed(params) {
const {
stakePubkey,
authorizedPubkey,
splitStakePubkey,
lamports,
seed,
basePubkey
} = params;
const transaction = new Transaction();
transaction.add(SystemProgram.createAccountWithSeed({
fromPubkey: authorizedPubkey,
newAccountPubkey: splitStakePubkey,
lamports: 0,
seed: seed,
space: this.space,
programId: this.programId,
basePubkey: basePubkey
}));
const type = STAKE_INSTRUCTION_LAYOUTS.Split;
const data = encodeData(type, {
lamports
});
return transaction.add(new TransactionInstruction({
keys: [{
pubkey: stakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: splitStakePubkey,
isSigner: false,
isWritable: true
}, {
pubkey: authorizedPubkey,
isSigner: true,
isWritable: false
}],
programId: this.programId,
data
}));
} |
JavaScript | static publicKeyToEthAddress(publicKey) {
assert$1(publicKey.length === PUBLIC_KEY_BYTES, "Public key must be ".concat(PUBLIC_KEY_BYTES, " bytes but received ").concat(publicKey.length, " bytes"));
try {
return buffer.Buffer.from(keccak_256.update(toBuffer(publicKey)).digest()).slice(-ETHEREUM_ADDRESS_BYTES);
} catch (error) {
throw new Error("Error constructing Ethereum address: ".concat(error));
}
} | static publicKeyToEthAddress(publicKey) {
assert$1(publicKey.length === PUBLIC_KEY_BYTES, "Public key must be ".concat(PUBLIC_KEY_BYTES, " bytes but received ").concat(publicKey.length, " bytes"));
try {
return buffer.Buffer.from(keccak_256.update(toBuffer(publicKey)).digest()).slice(-ETHEREUM_ADDRESS_BYTES);
} catch (error) {
throw new Error("Error constructing Ethereum address: ".concat(error));
}
} |
JavaScript | static createInstructionWithEthAddress(params) {
const {
ethAddress: rawAddress,
message,
signature,
recoveryId
} = params;
let ethAddress;
if (typeof rawAddress === 'string') {
if (rawAddress.startsWith('0x')) {
ethAddress = buffer.Buffer.from(rawAddress.substr(2), 'hex');
} else {
ethAddress = buffer.Buffer.from(rawAddress, 'hex');
}
} else {
ethAddress = rawAddress;
}
assert$1(ethAddress.length === ETHEREUM_ADDRESS_BYTES, "Address must be ".concat(ETHEREUM_ADDRESS_BYTES, " bytes but received ").concat(ethAddress.length, " bytes"));
const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;
const ethAddressOffset = dataStart;
const signatureOffset = dataStart + ethAddress.length;
const messageDataOffset = signatureOffset + signature.length + 1;
const numSignatures = 1;
const instructionData = buffer.Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length);
SECP256K1_INSTRUCTION_LAYOUT.encode({
numSignatures,
signatureOffset,
signatureInstructionIndex: 0,
ethAddressOffset,
ethAddressInstructionIndex: 0,
messageDataOffset,
messageDataSize: message.length,
messageInstructionIndex: 0,
signature: toBuffer(signature),
ethAddress: toBuffer(ethAddress),
recoveryId
}, instructionData);
instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);
return new TransactionInstruction({
keys: [],
programId: Secp256k1Program.programId,
data: instructionData
});
} | static createInstructionWithEthAddress(params) {
const {
ethAddress: rawAddress,
message,
signature,
recoveryId
} = params;
let ethAddress;
if (typeof rawAddress === 'string') {
if (rawAddress.startsWith('0x')) {
ethAddress = buffer.Buffer.from(rawAddress.substr(2), 'hex');
} else {
ethAddress = buffer.Buffer.from(rawAddress, 'hex');
}
} else {
ethAddress = rawAddress;
}
assert$1(ethAddress.length === ETHEREUM_ADDRESS_BYTES, "Address must be ".concat(ETHEREUM_ADDRESS_BYTES, " bytes but received ").concat(ethAddress.length, " bytes"));
const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;
const ethAddressOffset = dataStart;
const signatureOffset = dataStart + ethAddress.length;
const messageDataOffset = signatureOffset + signature.length + 1;
const numSignatures = 1;
const instructionData = buffer.Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length);
SECP256K1_INSTRUCTION_LAYOUT.encode({
numSignatures,
signatureOffset,
signatureInstructionIndex: 0,
ethAddressOffset,
ethAddressInstructionIndex: 0,
messageDataOffset,
messageDataSize: message.length,
messageInstructionIndex: 0,
signature: toBuffer(signature),
ethAddress: toBuffer(ethAddress),
recoveryId
}, instructionData);
instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);
return new TransactionInstruction({
keys: [],
programId: Secp256k1Program.programId,
data: instructionData
});
} |
JavaScript | static createInstructionWithPrivateKey(params) {
const {
privateKey: pkey,
message
} = params;
assert$1(pkey.length === PRIVATE_KEY_BYTES, "Private key must be ".concat(PRIVATE_KEY_BYTES, " bytes but received ").concat(pkey.length, " bytes"));
let privateKey;
if (Array.isArray(pkey)) {
privateKey = Uint8Array.from(pkey);
} else {
privateKey = pkey;
}
try {
const publicKey = publicKeyCreate(privateKey, false).slice(1); // throw away leading byte
const messageHash = buffer.Buffer.from(keccak_256.update(toBuffer(message)).digest());
const {
signature,
recid: recoveryId
} = ecdsaSign(messageHash, privateKey);
return this.createInstructionWithPublicKey({
publicKey,
message,
signature,
recoveryId
});
} catch (error) {
throw new Error("Error creating instruction; ".concat(error));
}
} | static createInstructionWithPrivateKey(params) {
const {
privateKey: pkey,
message
} = params;
assert$1(pkey.length === PRIVATE_KEY_BYTES, "Private key must be ".concat(PRIVATE_KEY_BYTES, " bytes but received ").concat(pkey.length, " bytes"));
let privateKey;
if (Array.isArray(pkey)) {
privateKey = Uint8Array.from(pkey);
} else {
privateKey = pkey;
}
try {
const publicKey = publicKeyCreate(privateKey, false).slice(1); // throw away leading byte
const messageHash = buffer.Buffer.from(keccak_256.update(toBuffer(message)).digest());
const {
signature,
recid: recoveryId
} = ecdsaSign(messageHash, privateKey);
return this.createInstructionWithPublicKey({
publicKey,
message,
signature,
recoveryId
});
} catch (error) {
throw new Error("Error creating instruction; ".concat(error));
}
} |
JavaScript | static fromConfigData(buffer$1) {
const PUBKEY_LENGTH = 32;
let byteArray = [...buffer$1];
const configKeyCount = decodeLength(byteArray);
if (configKeyCount !== 2) return null;
const configKeys = [];
for (let i = 0; i < 2; i++) {
const publicKey = new PublicKey(byteArray.slice(0, PUBKEY_LENGTH));
byteArray = byteArray.slice(PUBKEY_LENGTH);
const isSigner = byteArray.slice(0, 1)[0] === 1;
byteArray = byteArray.slice(1);
configKeys.push({
publicKey,
isSigner
});
}
if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) {
if (configKeys[1].isSigner) {
const rawInfo = rustString().decode(buffer.Buffer.from(byteArray));
const info = JSON.parse(rawInfo);
assert$3(info, InfoString);
return new ValidatorInfo(configKeys[1].publicKey, info);
}
}
return null;
} | static fromConfigData(buffer$1) {
const PUBKEY_LENGTH = 32;
let byteArray = [...buffer$1];
const configKeyCount = decodeLength(byteArray);
if (configKeyCount !== 2) return null;
const configKeys = [];
for (let i = 0; i < 2; i++) {
const publicKey = new PublicKey(byteArray.slice(0, PUBKEY_LENGTH));
byteArray = byteArray.slice(PUBKEY_LENGTH);
const isSigner = byteArray.slice(0, 1)[0] === 1;
byteArray = byteArray.slice(1);
configKeys.push({
publicKey,
isSigner
});
}
if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) {
if (configKeys[1].isSigner) {
const rawInfo = rustString().decode(buffer.Buffer.from(byteArray));
const info = JSON.parse(rawInfo);
assert$3(info, InfoString);
return new ValidatorInfo(configKeys[1].publicKey, info);
}
}
return null;
} |
JavaScript | function lint(options) {
const ext = options.ext ? `--ext ${options.ext}` : "";
const checkCustom = (t) => {
const f = ["", ".json", ".yml", ".yaml", ".js"].find((e) => {
const x = Path.resolve(Path.join(t, `.eslintrc${e}`));
return Fs.existsSync(x);
});
return f !== undefined;
};
//
// group target directories into custom and archetype
// custom - .eslintrc file exist
// archetype - no .eslintrc, use config from archetype
//
const grouped = options.targets.reduce((a, t) => {
(checkCustom(t) ? a.custom : a.archetype).push(t);
return a;
}, { custom: [], archetype: [] });
let promise;
if (grouped.custom.length > 0) {
const cmd = `eslint ${ext} ${grouped.custom.join(" ")}`;
promise = exec(cmd);
}
if (grouped.archetype.length > 0) {
const cmd = `eslint ${ext} --no-eslintrc -c ${options.config} ${grouped.archetype.join(" ")}`;
promise = promise ? promise.then(() => exec(cmd)) : exec(cmd);
}
return promise;
} | function lint(options) {
const ext = options.ext ? `--ext ${options.ext}` : "";
const checkCustom = (t) => {
const f = ["", ".json", ".yml", ".yaml", ".js"].find((e) => {
const x = Path.resolve(Path.join(t, `.eslintrc${e}`));
return Fs.existsSync(x);
});
return f !== undefined;
};
//
// group target directories into custom and archetype
// custom - .eslintrc file exist
// archetype - no .eslintrc, use config from archetype
//
const grouped = options.targets.reduce((a, t) => {
(checkCustom(t) ? a.custom : a.archetype).push(t);
return a;
}, { custom: [], archetype: [] });
let promise;
if (grouped.custom.length > 0) {
const cmd = `eslint ${ext} ${grouped.custom.join(" ")}`;
promise = exec(cmd);
}
if (grouped.archetype.length > 0) {
const cmd = `eslint ${ext} --no-eslintrc -c ${options.config} ${grouped.archetype.join(" ")}`;
promise = promise ? promise.then(() => exec(cmd)) : exec(cmd);
}
return promise;
} |
JavaScript | function generateServiceWorker() {
const NODE_ENV = process.env.NODE_ENV;
const serviceWorkerExists = Fs.existsSync("./service-worker.js");
const serviceWorkerConfigExists = Fs.existsSync("config/sw-precache-config.json");
/**
* Determines whether the fetch event handler is included in the generated service worker code,
* by default value is set to true for development builds set the value to false
*
* https://github.com/GoogleChrome/sw-precache#handlefetch-boolean
*
*/
const cacheRequestFetch = (NODE_ENV !== "production" ? "--no-handle-fetch" : "");
if (serviceWorkerConfigExists) {
// generate-service-worker
return exec(`sw-precache --config=config/sw-precache-config.json --verbose ${cacheRequestFetch}`);
} else if (serviceWorkerExists && !serviceWorkerConfigExists) {
// this is the case when service-worker exists from the previous build but service-worker-config
// does not exist/deleted on purpose for future builds
return shell.rm("-rf", "./service-worker.js");
} else {
// default case
return false;
}
} | function generateServiceWorker() {
const NODE_ENV = process.env.NODE_ENV;
const serviceWorkerExists = Fs.existsSync("./service-worker.js");
const serviceWorkerConfigExists = Fs.existsSync("config/sw-precache-config.json");
/**
* Determines whether the fetch event handler is included in the generated service worker code,
* by default value is set to true for development builds set the value to false
*
* https://github.com/GoogleChrome/sw-precache#handlefetch-boolean
*
*/
const cacheRequestFetch = (NODE_ENV !== "production" ? "--no-handle-fetch" : "");
if (serviceWorkerConfigExists) {
// generate-service-worker
return exec(`sw-precache --config=config/sw-precache-config.json --verbose ${cacheRequestFetch}`);
} else if (serviceWorkerExists && !serviceWorkerConfigExists) {
// this is the case when service-worker exists from the previous build but service-worker-config
// does not exist/deleted on purpose for future builds
return shell.rm("-rf", "./service-worker.js");
} else {
// default case
return false;
}
} |
JavaScript | function toMinorRange(version) {
var regex = /^\d+\.\d+/;
var range = version.match(regex);
if (range) {
return '^' + range[0];
}
else {
var regex = /^\d+\.x/;
var range = version.match(regex);
if (range) {
return range[0];
}
}
return version;
} | function toMinorRange(version) {
var regex = /^\d+\.\d+/;
var range = version.match(regex);
if (range) {
return '^' + range[0];
}
else {
var regex = /^\d+\.x/;
var range = version.match(regex);
if (range) {
return range[0];
}
}
return version;
} |
JavaScript | function toDrupalMajorVersion(version) {
var regex = /^(\d+)\.\d+\.[x\d+]/;
var match = version.match(regex)
if (match) {
return match[1] + '.x';
}
return version;
} | function toDrupalMajorVersion(version) {
var regex = /^(\d+)\.\d+\.[x\d+]/;
var match = version.match(regex)
if (match) {
return match[1] + '.x';
}
return version;
} |
JavaScript | async function fileTreeWalkerAsync (rootDir, callback, logger = defaultLogger) {
const directories = []
// we want to allow the callback to cancel the process
let _abort = false
const abort = () => (_abort = true)
const process = async (subpath) => {
try {
const filesOrDirectories = await fs.readdir(subpath)
// try process all the files in a directory first.
// process files in subpath
while (filesOrDirectories.length > 0) {
const name = filesOrDirectories.pop()
const fullPath = joinPaths(subpath, name)
// we need to ignore the directory before stat as it could fail
// this has a side effect any files with the name of ignored directory is excluded too
if (isIgnoredPath(fullPath)) {
logger.warn(`Ignoring path ${fullPath}`)
continue
}
if (_abort) break
try {
const stat = await fs.stat(fullPath)
if (stat.isDirectory()) {
// ignored files and unix hidden folders
if (isIgnoredDirectory(fullPath)) {
logger.warn(`Ignoring folder ${fullPath}`)
} else {
directories.push(fullPath)
}
} else if (stat.isFile()) {
if (isIgnoredFile(fullPath)) {
logger.info(`Ignoring file ${fullPath}`)
} else {
try {
await callback(null, { filename: fullPath, stat, path: subpath, abort })
} catch (error) {
logger.error('file tree walker callback threw an exception, ignoring', error)
}
}
}
} catch (error) {
logger.error(`Error processing path ${fullPath}, ${error.message}`)
await callback(new FileTreeWalkerPathError(fullPath), {})
}
}
// process each directory
while (directories.length > 0) {
if (_abort) break
const dir = directories.pop()
await process(dir)
}
} catch (error) {
logger.error(`Error processing path ${subpath}, ${error}`)
await callback(new FileTreeWalkerPathError(subpath), {})
}
}
await process(rootDir)
} | async function fileTreeWalkerAsync (rootDir, callback, logger = defaultLogger) {
const directories = []
// we want to allow the callback to cancel the process
let _abort = false
const abort = () => (_abort = true)
const process = async (subpath) => {
try {
const filesOrDirectories = await fs.readdir(subpath)
// try process all the files in a directory first.
// process files in subpath
while (filesOrDirectories.length > 0) {
const name = filesOrDirectories.pop()
const fullPath = joinPaths(subpath, name)
// we need to ignore the directory before stat as it could fail
// this has a side effect any files with the name of ignored directory is excluded too
if (isIgnoredPath(fullPath)) {
logger.warn(`Ignoring path ${fullPath}`)
continue
}
if (_abort) break
try {
const stat = await fs.stat(fullPath)
if (stat.isDirectory()) {
// ignored files and unix hidden folders
if (isIgnoredDirectory(fullPath)) {
logger.warn(`Ignoring folder ${fullPath}`)
} else {
directories.push(fullPath)
}
} else if (stat.isFile()) {
if (isIgnoredFile(fullPath)) {
logger.info(`Ignoring file ${fullPath}`)
} else {
try {
await callback(null, { filename: fullPath, stat, path: subpath, abort })
} catch (error) {
logger.error('file tree walker callback threw an exception, ignoring', error)
}
}
}
} catch (error) {
logger.error(`Error processing path ${fullPath}, ${error.message}`)
await callback(new FileTreeWalkerPathError(fullPath), {})
}
}
// process each directory
while (directories.length > 0) {
if (_abort) break
const dir = directories.pop()
await process(dir)
}
} catch (error) {
logger.error(`Error processing path ${subpath}, ${error}`)
await callback(new FileTreeWalkerPathError(subpath), {})
}
}
await process(rootDir)
} |
JavaScript | async function convertIteratorToCallbackAsync (iterator, cb) {
while (true) {
const nextValue = await iterator.next()
if (cb(nextValue) === false) break
}
} | async function convertIteratorToCallbackAsync (iterator, cb) {
while (true) {
const nextValue = await iterator.next()
if (cb(nextValue) === false) break
}
} |
JavaScript | refresh() {
if (Platform.OS === 'android') {
UIManager.dispatchViewManagerCommand(findNodeHandle(this), 'refresh', []);
}
} | refresh() {
if (Platform.OS === 'android') {
UIManager.dispatchViewManagerCommand(findNodeHandle(this), 'refresh', []);
}
} |
JavaScript | async takeSnap(options = {}) {
const snapshotOptions = new SnapshotOptions(options);
const uri = await MapboxGLSnapshotManger.takeSnap(snapshotOptions);
return uri;
} | async takeSnap(options = {}) {
const snapshotOptions = new SnapshotOptions(options);
const uri = await MapboxGLSnapshotManger.takeSnap(snapshotOptions);
return uri;
} |
JavaScript | function performQuery(modelName, queryString, type) {
return new Ember.RSVP.Promise(function(resolve, reject) {
var connection = new Stardog.Connection();
connection.setEndpoint(config.sparql.endpoint);
connection.setCredentials(
config.sparql.user,
config.sparql.password
);
connection.setReasoning("SL");
if (DEBUG_MODE) console.log("Performing query: ", queryString.replace('\t', '').replace(/\s+/g, ' ').trim());
connection.query({
database: config.sparql.database,
query: queryString,
offset: 0
}, function(data, response) {
if (!data) {
reject({
statusText: 'Die Verbindung zur Datenbank konnte nicht hergestellt werden'
});
}
else {
if (!data.results) {
reject(response);
}
else {
if (DEBUG_MODE) console.log("Got query results: ", data.results.bindings, typeof(data.results.bindings));
var result = {
type: type,
modelName: modelName,
data: data.results.bindings
};
resolve(result);
}
}
});
});
} | function performQuery(modelName, queryString, type) {
return new Ember.RSVP.Promise(function(resolve, reject) {
var connection = new Stardog.Connection();
connection.setEndpoint(config.sparql.endpoint);
connection.setCredentials(
config.sparql.user,
config.sparql.password
);
connection.setReasoning("SL");
if (DEBUG_MODE) console.log("Performing query: ", queryString.replace('\t', '').replace(/\s+/g, ' ').trim());
connection.query({
database: config.sparql.database,
query: queryString,
offset: 0
}, function(data, response) {
if (!data) {
reject({
statusText: 'Die Verbindung zur Datenbank konnte nicht hergestellt werden'
});
}
else {
if (!data.results) {
reject(response);
}
else {
if (DEBUG_MODE) console.log("Got query results: ", data.results.bindings, typeof(data.results.bindings));
var result = {
type: type,
modelName: modelName,
data: data.results.bindings
};
resolve(result);
}
}
});
});
} |
JavaScript | function handleAlreadyExistingTeams() {
$.each($('.btn-edit-remove-team'), function() {
let elemText = $(this).parents('#team_div').find('.btn-edit-team').text().trim();
console.log(elemText)
var newTeamObj = {};
let leagueFullDescription = elemText.substring(elemText.indexOf(' - ') + 6, elemText.length);
newTeamObj.league = globalHandlers.excludePattern(leagueFullDescription, globalHandlers.parentesisCodePattern);
newTeamObj.leagueCode = globalHandlers.extractPattern(leagueFullDescription, globalHandlers.parentesisCodePattern);
newTeamObj.team = elemText.substr(0, elemText.indexOf(' - '))
// if(globalHandlers.teamsHolder.indexOf(newTeamObj) != -1)
globalHandlers.teamsHolder.push(newTeamObj);
})
} | function handleAlreadyExistingTeams() {
$.each($('.btn-edit-remove-team'), function() {
let elemText = $(this).parents('#team_div').find('.btn-edit-team').text().trim();
console.log(elemText)
var newTeamObj = {};
let leagueFullDescription = elemText.substring(elemText.indexOf(' - ') + 6, elemText.length);
newTeamObj.league = globalHandlers.excludePattern(leagueFullDescription, globalHandlers.parentesisCodePattern);
newTeamObj.leagueCode = globalHandlers.extractPattern(leagueFullDescription, globalHandlers.parentesisCodePattern);
newTeamObj.team = elemText.substr(0, elemText.indexOf(' - '))
// if(globalHandlers.teamsHolder.indexOf(newTeamObj) != -1)
globalHandlers.teamsHolder.push(newTeamObj);
})
} |
JavaScript | function requestEndpoint(endpointUri, callback){
const mainApiUrl = url.parse(endpointUri);
const options = new Options(mainApiUrl);
let req = http.request(options, (res) => {
//TODO só 200 nao chega, pode receber 500 por exemplo..
if (res.statusCode >= 500 && res.statusCode <= 505)
return callback(new Error('Server Error'));
if (res.statusCode != 200)
return callback({badStatus: res.statusCode});
res.setEncoding('utf8');
let chunks = [];
res.on("data", (chunk) => chunks.push(chunk));
res.on('error', callback);
res.on("end", () => { callback(null, JSON.parse(chunks.join(" "))); });
});
req.on('error', callback);
req.end();
} | function requestEndpoint(endpointUri, callback){
const mainApiUrl = url.parse(endpointUri);
const options = new Options(mainApiUrl);
let req = http.request(options, (res) => {
//TODO só 200 nao chega, pode receber 500 por exemplo..
if (res.statusCode >= 500 && res.statusCode <= 505)
return callback(new Error('Server Error'));
if (res.statusCode != 200)
return callback({badStatus: res.statusCode});
res.setEncoding('utf8');
let chunks = [];
res.on("data", (chunk) => chunks.push(chunk));
res.on('error', callback);
res.on("end", () => { callback(null, JSON.parse(chunks.join(" "))); });
});
req.on('error', callback);
req.end();
} |
JavaScript | function rootHandler(req, res, next) {
groupMapper.getAll((err, groups) => {
if (err) {
return next(err);
}
res.render('groups_layouts/groups_list_layout', {
groups: groups
});
});
} | function rootHandler(req, res, next) {
groupMapper.getAll((err, groups) => {
if (err) {
return next(err);
}
res.render('groups_layouts/groups_list_layout', {
groups: groups
});
});
} |
JavaScript | function groupHandler(req, res, next) {
groupMapper.get(req.groupName, (err, group) => {
if (err) {
return next(err);
}
res.render('groups_layouts/group_detail', {
groupName: group.name,
teams: group.teams,
nextFixturesAmount: req.nextFixtures,
lastFixturesAmount: req.lastFixtures
});
});
} | function groupHandler(req, res, next) {
groupMapper.get(req.groupName, (err, group) => {
if (err) {
return next(err);
}
res.render('groups_layouts/group_detail', {
groupName: group.name,
teams: group.teams,
nextFixturesAmount: req.nextFixtures,
lastFixturesAmount: req.lastFixtures
});
});
} |
JavaScript | function editGroupPostHandler(req, res, next) {
let newG = new Group(req.body.name, req.body.teams);
groupMapper.update(newG, (err, id) => {
if (err) {
return next(err);
}
console.log(`Inserted a new document with the id ${id}`);
res.status(200).end("/groups/");
});
} | function editGroupPostHandler(req, res, next) {
let newG = new Group(req.body.name, req.body.teams);
groupMapper.update(newG, (err, id) => {
if (err) {
return next(err);
}
console.log(`Inserted a new document with the id ${id}`);
res.status(200).end("/groups/");
});
} |
JavaScript | function GenerateTimeLine_DBus(grouped) {
let intervals = [];
let titles = [];
g_StartingSec = undefined;
// First, turn "content keys" into headers in the flattened layout
const content_keys = Object.keys(grouped);
const keys = Object.keys(grouped);
let sortedKeys = keys.slice();
let interval_idx = 0; // The overall index into the intervals array
for (let x=0; x<content_keys.length; x++) {
const content_key = content_keys[x];
// Per-content key
const grouped1 = grouped[content_key];
const keys1 = Object.keys(grouped1);
let the_header = { "header":true, "title":content_key, "intervals_idxes":[] };
titles.push(the_header);
// TODO: this currently depends on the dbus_timeline_view instance
const collapsed = dbus_timeline_view.HeaderCollapsed[content_key];
for (let i = 0; i < keys1.length; i++) {
// The Title array controls which lines are drawn. If we con't push the header
// it will not be drawn (thus giving a "collapsed" visual effect.)
if (!collapsed) {
titles.push({ "header":false, "title":keys1[i], "intervals_idxes":[interval_idx] });
}
line = [];
for (let j = 0; j < grouped1[keys1[i]].length; j++) {
let entry = grouped1[keys1[i]][j];
let t0 = parseFloat(entry[1]) / 1000.0;
let t1 = parseFloat(entry[8]) / 1000.0;
// Modify time shift delta if IPMI dataset is loaded first
if (g_StartingSec == undefined) {
g_StartingSec = t0;
}
g_StartingSec = Math.min(g_StartingSec, t0);
const outcome = entry[9];
line.push([t0, t1, entry, outcome, 0]);
}
the_header.intervals_idxes.push(interval_idx); // Keep the indices into the intervals array for use in rendering
intervals.push(line);
interval_idx ++;
}
// Compute a set of "merged intervals" for each content_key
let rise_fall_edges = [];
the_header.intervals_idxes.forEach((i) => {
intervals[i].forEach((t0t1) => {
if (t0t1[0] <= t0t1[1]) { // For errored-out method calls, the end time will be set to a value smaller than the start tiem
rise_fall_edges.push([t0t1[0], 0]); // 0 is a rising edge
rise_fall_edges.push([t0t1[1], 1]); // 1 is a falling edge
}
})
});
let merged_intervals = [],
current_interval = [undefined, undefined, 0]; // start, end, weight
rise_fall_edges.sort();
let i = 0, level = 0;
while (i<rise_fall_edges.length) {
let timestamp = rise_fall_edges[i][0];
while (i < rise_fall_edges.length && timestamp == rise_fall_edges[i][0]) {
switch (rise_fall_edges[i][1]) {
case 0: { // rising edge
if (level == 0) {
current_interval[0] = timestamp;
current_interval[2] ++;
}
level ++;
break;
}
case 1: { // falling edge
level --;
if (level == 0) {
current_interval[1] = timestamp;
merged_intervals.push(current_interval);
current_interval = [undefined, undefined, 0];
}
break;
}
}
i++;
}
}
the_header.merged_intervals = merged_intervals;
}
// Time shift
for (let i = 0; i < intervals.length; i++) {
for (let j = 0; j < intervals[i].length; j++) {
let x = intervals[i][j];
x[0] -= g_StartingSec;
x[1] -= g_StartingSec;
}
}
// merged intervals should be time-shifted as well
titles.forEach((t) => {
if (t.header == true) {
t.merged_intervals.forEach((mi) => {
mi[0] -= g_StartingSec;
mi[1] -= g_StartingSec;
})
}
})
dbus_timeline_view.Intervals = intervals.slice();
dbus_timeline_view.Titles = titles.slice();
dbus_timeline_view.LayoutForOverlappingIntervals();
} | function GenerateTimeLine_DBus(grouped) {
let intervals = [];
let titles = [];
g_StartingSec = undefined;
// First, turn "content keys" into headers in the flattened layout
const content_keys = Object.keys(grouped);
const keys = Object.keys(grouped);
let sortedKeys = keys.slice();
let interval_idx = 0; // The overall index into the intervals array
for (let x=0; x<content_keys.length; x++) {
const content_key = content_keys[x];
// Per-content key
const grouped1 = grouped[content_key];
const keys1 = Object.keys(grouped1);
let the_header = { "header":true, "title":content_key, "intervals_idxes":[] };
titles.push(the_header);
// TODO: this currently depends on the dbus_timeline_view instance
const collapsed = dbus_timeline_view.HeaderCollapsed[content_key];
for (let i = 0; i < keys1.length; i++) {
// The Title array controls which lines are drawn. If we con't push the header
// it will not be drawn (thus giving a "collapsed" visual effect.)
if (!collapsed) {
titles.push({ "header":false, "title":keys1[i], "intervals_idxes":[interval_idx] });
}
line = [];
for (let j = 0; j < grouped1[keys1[i]].length; j++) {
let entry = grouped1[keys1[i]][j];
let t0 = parseFloat(entry[1]) / 1000.0;
let t1 = parseFloat(entry[8]) / 1000.0;
// Modify time shift delta if IPMI dataset is loaded first
if (g_StartingSec == undefined) {
g_StartingSec = t0;
}
g_StartingSec = Math.min(g_StartingSec, t0);
const outcome = entry[9];
line.push([t0, t1, entry, outcome, 0]);
}
the_header.intervals_idxes.push(interval_idx); // Keep the indices into the intervals array for use in rendering
intervals.push(line);
interval_idx ++;
}
// Compute a set of "merged intervals" for each content_key
let rise_fall_edges = [];
the_header.intervals_idxes.forEach((i) => {
intervals[i].forEach((t0t1) => {
if (t0t1[0] <= t0t1[1]) { // For errored-out method calls, the end time will be set to a value smaller than the start tiem
rise_fall_edges.push([t0t1[0], 0]); // 0 is a rising edge
rise_fall_edges.push([t0t1[1], 1]); // 1 is a falling edge
}
})
});
let merged_intervals = [],
current_interval = [undefined, undefined, 0]; // start, end, weight
rise_fall_edges.sort();
let i = 0, level = 0;
while (i<rise_fall_edges.length) {
let timestamp = rise_fall_edges[i][0];
while (i < rise_fall_edges.length && timestamp == rise_fall_edges[i][0]) {
switch (rise_fall_edges[i][1]) {
case 0: { // rising edge
if (level == 0) {
current_interval[0] = timestamp;
current_interval[2] ++;
}
level ++;
break;
}
case 1: { // falling edge
level --;
if (level == 0) {
current_interval[1] = timestamp;
merged_intervals.push(current_interval);
current_interval = [undefined, undefined, 0];
}
break;
}
}
i++;
}
}
the_header.merged_intervals = merged_intervals;
}
// Time shift
for (let i = 0; i < intervals.length; i++) {
for (let j = 0; j < intervals[i].length; j++) {
let x = intervals[i][j];
x[0] -= g_StartingSec;
x[1] -= g_StartingSec;
}
}
// merged intervals should be time-shifted as well
titles.forEach((t) => {
if (t.header == true) {
t.merged_intervals.forEach((mi) => {
mi[0] -= g_StartingSec;
mi[1] -= g_StartingSec;
})
}
})
dbus_timeline_view.Intervals = intervals.slice();
dbus_timeline_view.Titles = titles.slice();
dbus_timeline_view.LayoutForOverlappingIntervals();
} |
JavaScript | function extractUsec(line) {
let i0 = line.indexOf('time=');
if (i0 == -1) {
return BigInt(-1);
}
let line1 = line.substr(i0);
let i1 = line1.indexOf(' ');
if (i1 == -1) {
return BigInt(-1);
}
let line2 = line1.substr(5, i1 - 5);
let sp = line2.split('.');
return BigInt(sp[0]) * BigInt(1000000) + BigInt(sp[1]);
} | function extractUsec(line) {
let i0 = line.indexOf('time=');
if (i0 == -1) {
return BigInt(-1);
}
let line1 = line.substr(i0);
let i1 = line1.indexOf(' ');
if (i1 == -1) {
return BigInt(-1);
}
let line2 = line1.substr(5, i1 - 5);
let sp = line2.split('.');
return BigInt(sp[0]) * BigInt(1000000) + BigInt(sp[1]);
} |
Subsets and Splits