language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | holiday(holiday) {
if(holiday == null || (holiday != "PH" && holiday != "SH" && holiday != "easter")) {
throw Error("Invalid holiday, must be PH, SH or easter");
}
this._start = { holiday: holiday };
this._end = null;
this._type = "holiday";
return this;
} | holiday(holiday) {
if(holiday == null || (holiday != "PH" && holiday != "SH" && holiday != "easter")) {
throw Error("Invalid holiday, must be PH, SH or easter");
}
this._start = { holiday: holiday };
this._end = null;
this._type = "holiday";
return this;
} |
JavaScript | equals(o) {
if(!o instanceof WideInterval) { return false; }
if(this === o) { return true; }
if(o._type == "always") { return this._type == "always"; }
let result = false;
switch(this._type) {
case "always":
result = o._start == null;
break;
case "day":
result =
(
o._type == "day"
&& o._start.month == this._start.month
&& o._start.day == this._start.day
&& (
(o._end == null && this._end == null)
|| (o._end != null && this._end != null && this._end.month == o._end.month && this._end.day == o._end.day)
))
||
(
o._type == "month"
&& o._start.month == this._start.month
&& (this.isFullMonth() && o.isFullMonth())
|| (o._end != null && this._end != null && this._end.month == o._end.month && this.endsMonth() && o.endsMonth())
);
break;
case "week":
result =
o._start.week == this._start.week
&& (o._end == this._end || (this._end != null && o._end != null && o._end.week == this._end.week));
break;
case "month":
result =
(
o._type == "day"
&& this._start.month == o._start.month
&& o.startsMonth()
&& (
(this._end == null && o._end != null && this._start.month == o._end.month && o.endsMonth())
||
(this._end != null && o._end != null && this._end.month == o._end.month && o.endsMonth())
)
)
||
(
o._type == "month"
&& o._start.month == this._start.month
&& (
(this._end == null && o._end == null)
||
(this._end != null && o._end != null && this._end.month == o._end.month)
)
);
break;
case "holiday":
result = o._start.holiday == this._start.holiday;
break;
default:
}
return result;
} | equals(o) {
if(!o instanceof WideInterval) { return false; }
if(this === o) { return true; }
if(o._type == "always") { return this._type == "always"; }
let result = false;
switch(this._type) {
case "always":
result = o._start == null;
break;
case "day":
result =
(
o._type == "day"
&& o._start.month == this._start.month
&& o._start.day == this._start.day
&& (
(o._end == null && this._end == null)
|| (o._end != null && this._end != null && this._end.month == o._end.month && this._end.day == o._end.day)
))
||
(
o._type == "month"
&& o._start.month == this._start.month
&& (this.isFullMonth() && o.isFullMonth())
|| (o._end != null && this._end != null && this._end.month == o._end.month && this.endsMonth() && o.endsMonth())
);
break;
case "week":
result =
o._start.week == this._start.week
&& (o._end == this._end || (this._end != null && o._end != null && o._end.week == this._end.week));
break;
case "month":
result =
(
o._type == "day"
&& this._start.month == o._start.month
&& o.startsMonth()
&& (
(this._end == null && o._end != null && this._start.month == o._end.month && o.endsMonth())
||
(this._end != null && o._end != null && this._end.month == o._end.month && o.endsMonth())
)
)
||
(
o._type == "month"
&& o._start.month == this._start.month
&& (
(this._end == null && o._end == null)
||
(this._end != null && o._end != null && this._end.month == o._end.month)
)
);
break;
case "holiday":
result = o._start.holiday == this._start.holiday;
break;
default:
}
return result;
} |
JavaScript | _timeString(minutes) {
var h = Math.floor(minutes / 60);
var period = "";
var m = minutes % 60;
return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m + period;
} | _timeString(minutes) {
var h = Math.floor(minutes / 60);
var period = "";
var m = minutes % 60;
return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m + period;
} |
JavaScript | sameTime(o) {
if(o == undefined || o == null || o.getTime().length != this._time.length) {
return false;
}
else {
for(let i=0, l=this._time.length; i < l; i++) {
if(!this._time[i].equals(o.getTime()[i])) {
return false;
}
}
return true;
}
} | sameTime(o) {
if(o == undefined || o == null || o.getTime().length != this._time.length) {
return false;
}
else {
for(let i=0, l=this._time.length; i < l; i++) {
if(!this._time[i].equals(o.getTime()[i])) {
return false;
}
}
return true;
}
} |
JavaScript | addWeekday(wd) {
for(let i=0; i < this._date.length; i++) {
this._date[i].addWeekday(wd);
}
} | addWeekday(wd) {
for(let i=0; i < this._date.length; i++) {
this._date[i].addWeekday(wd);
}
} |
JavaScript | addPhWeekday() {
for(let i=0; i < this._date.length; i++) {
this._date[i].addPhWeekday();
}
} | addPhWeekday() {
for(let i=0; i < this._date.length; i++) {
this._date[i].addPhWeekday();
}
} |
JavaScript | addOverwrittenWeekday(wd) {
for(let i=0; i < this._date.length; i++) {
this._date[i].addOverwrittenWeekday(wd);
}
} | addOverwrittenWeekday(wd) {
for(let i=0; i < this._date.length; i++) {
this._date[i].addOverwrittenWeekday(wd);
}
} |
JavaScript | addDate(d) {
//Check param
if(d == null || d == undefined || !d instanceof OhDate) {
throw Error("Invalid parameter");
}
//Check if date can be added
if(this._date.length == 0 || (this._date[0].getWideType() != "always" && this._date[0].sameKindAs(d))) {
this._date.push(d);
}
else {
if(this._date.length != 1 || this._date[0].getWideType() != "always" || !this._date[0].sameWd(d.getWd())) {
throw Error("This date can't be added to this rule");
}
}
} | addDate(d) {
//Check param
if(d == null || d == undefined || !d instanceof OhDate) {
throw Error("Invalid parameter");
}
//Check if date can be added
if(this._date.length == 0 || (this._date[0].getWideType() != "always" && this._date[0].sameKindAs(d))) {
this._date.push(d);
}
else {
if(this._date.length != 1 || this._date[0].getWideType() != "always" || !this._date[0].sameWd(d.getWd())) {
throw Error("This date can't be added to this rule");
}
}
} |
JavaScript | addTime(t) {
if((this._time.length == 0 || this._time[0].get() != "off") && !this._time.contains(t)) {
this._time.push(t);
}
else {
throw Error("This time can't be added to this rule");
}
} | addTime(t) {
if((this._time.length == 0 || this._time[0].get() != "off") && !this._time.contains(t)) {
this._time.push(t);
}
else {
throw Error("This time can't be added to this rule");
}
} |
JavaScript | async function init() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// or files from your local hard drive
// Note: the pose library adds "tmImage" object to your window (window.tmImage)
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
// Convenience function to setup a webcam
const flip = true; // whether to flip the webcam
webcam = new tmImage.Webcam(400, 400, flip); // width, height, flip
await webcam.setup(); // request access to the webcam
await webcam.play();
window.requestAnimationFrame(loop);
// append elements to the DOM
document.getElementById("webcam-container").appendChild(webcam.canvas);
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) { // and class labels
labelContainer.appendChild(document.createElement("div"));
}
let divResult = document.createElement("div");
labelPredicted = labelContainer.appendChild(divResult);
} | async function init() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// or files from your local hard drive
// Note: the pose library adds "tmImage" object to your window (window.tmImage)
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
// Convenience function to setup a webcam
const flip = true; // whether to flip the webcam
webcam = new tmImage.Webcam(400, 400, flip); // width, height, flip
await webcam.setup(); // request access to the webcam
await webcam.play();
window.requestAnimationFrame(loop);
// append elements to the DOM
document.getElementById("webcam-container").appendChild(webcam.canvas);
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) { // and class labels
labelContainer.appendChild(document.createElement("div"));
}
let divResult = document.createElement("div");
labelPredicted = labelContainer.appendChild(divResult);
} |
JavaScript | async function predict() {
// predict can take in an image, video or canvas html element
let detected = false;
const prediction = await model.predict(webcam.canvas);
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + prediction[i].probability.toFixed(2);
labelContainer.childNodes[i].innerHTML = classPrediction;
if(prediction[i].probability.toFixed(2) >= 0.90){
if(i == labels.length - 1)
continue;
const msg = "<pre><br>\t이거다!! " + labels[i] + "</pre>";
labelPredicted.innerHTML = msg;
detected = true;
if(mapIndex != i){
mapIndex = i;
panTo(pos[i].y, pos[i].x);
}
}
}
if(!detected){
const msg = "<pre><br>\t뭘까?</pre>";
labelPredicted.innerHTML = msg;
}
} | async function predict() {
// predict can take in an image, video or canvas html element
let detected = false;
const prediction = await model.predict(webcam.canvas);
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + prediction[i].probability.toFixed(2);
labelContainer.childNodes[i].innerHTML = classPrediction;
if(prediction[i].probability.toFixed(2) >= 0.90){
if(i == labels.length - 1)
continue;
const msg = "<pre><br>\t이거다!! " + labels[i] + "</pre>";
labelPredicted.innerHTML = msg;
detected = true;
if(mapIndex != i){
mapIndex = i;
panTo(pos[i].y, pos[i].x);
}
}
}
if(!detected){
const msg = "<pre><br>\t뭘까?</pre>";
labelPredicted.innerHTML = msg;
}
} |
JavaScript | function notFoundHandler (req, res, next) {
// Check for existence of the method handler.
if (req.resourcePath) {
return next()
}
var notFoundError = new Error(
req.method + ' ' + parseurl(req).pathname +
' does not exist in the RAML for this application'
)
notFoundError.ramlNotFound = true
notFoundError.status = notFoundError.statusCode = 404
return next(notFoundError)
} | function notFoundHandler (req, res, next) {
// Check for existence of the method handler.
if (req.resourcePath) {
return next()
}
var notFoundError = new Error(
req.method + ' ' + parseurl(req).pathname +
' does not exist in the RAML for this application'
)
notFoundError.ramlNotFound = true
notFoundError.status = notFoundError.statusCode = 404
return next(notFoundError)
} |
JavaScript | function retrieveDamsData(){
fetch(API_DAMS)
.then((resp) => resp.json())
.then(function(data) {
//Calling list builder function
populateDetails(data);
})
.catch(function(error) {
console.log(error);
});
} | function retrieveDamsData(){
fetch(API_DAMS)
.then((resp) => resp.json())
.then(function(data) {
//Calling list builder function
populateDetails(data);
})
.catch(function(error) {
console.log(error);
});
} |
JavaScript | function retrieveDamsData() {
fetch(API_DAMS)
.then((resp) => resp.json())
.then(function (data) {
//Calling list builder function
buildDamList(data, dams_list);
})
.catch(function (error) {
console.log(error);
});
} | function retrieveDamsData() {
fetch(API_DAMS)
.then((resp) => resp.json())
.then(function (data) {
//Calling list builder function
buildDamList(data, dams_list);
})
.catch(function (error) {
console.log(error);
});
} |
JavaScript | function retrieveDamsPercentage() {
return fetch(API_PERCENTAGES)
.then((resp) => resp.json())
.then(function (data) {
//Initialising the water quage
var gauge1 = loadLiquidFillGauge("fillgauge1", Math.round(data.totalPercentage * 100));
//Applying the dam water percentages on the table
applyDamPercentages(data.damNamesToPercentage);
})
.catch(function (error) {
console.log(error);
});
} | function retrieveDamsPercentage() {
return fetch(API_PERCENTAGES)
.then((resp) => resp.json())
.then(function (data) {
//Initialising the water quage
var gauge1 = loadLiquidFillGauge("fillgauge1", Math.round(data.totalPercentage * 100));
//Applying the dam water percentages on the table
applyDamPercentages(data.damNamesToPercentage);
})
.catch(function (error) {
console.log(error);
});
} |
JavaScript | function buildDamList(data, containerElement) {
var listItems = [];
//Itterating through data building the list tiles for each dam
data.forEach(element => {
listItems.push(`
<a href="dam_details.html?damName=${element.nameEn}" class="blue-text text-darken-1 collection-item">${element.nameEn}<div class="secondary-content secondary-content-fix">
<div class="progress blue lighten-4">
<div id="${element.nameEn}-perc" class="determinate blue darken-1" style="width: 0%"></div>
</div>
</div></a>
`);
});
containerElement.innerHTML = listItems.join("");
//Calling a function that adds the water pecentage to each dam
retrieveDamsPercentage();
} | function buildDamList(data, containerElement) {
var listItems = [];
//Itterating through data building the list tiles for each dam
data.forEach(element => {
listItems.push(`
<a href="dam_details.html?damName=${element.nameEn}" class="blue-text text-darken-1 collection-item">${element.nameEn}<div class="secondary-content secondary-content-fix">
<div class="progress blue lighten-4">
<div id="${element.nameEn}-perc" class="determinate blue darken-1" style="width: 0%"></div>
</div>
</div></a>
`);
});
containerElement.innerHTML = listItems.join("");
//Calling a function that adds the water pecentage to each dam
retrieveDamsPercentage();
} |
JavaScript | function applyDamPercentages(damPercentages) {
//Itterating through percentages
for (var dam in damPercentages) {
//Finding tile element
var percentageSpan = document.getElementById(dam + '-perc');
//Making the percentage ready
var percentage = Math.round(damPercentages[dam] * 100) + '%';
//Appling the perccentage to each list tile progress bar
percentageSpan.setAttribute("style", "width:" + percentage);
}
} | function applyDamPercentages(damPercentages) {
//Itterating through percentages
for (var dam in damPercentages) {
//Finding tile element
var percentageSpan = document.getElementById(dam + '-perc');
//Making the percentage ready
var percentage = Math.round(damPercentages[dam] * 100) + '%';
//Appling the perccentage to each list tile progress bar
percentageSpan.setAttribute("style", "width:" + percentage);
}
} |
JavaScript | function addRow(year, data, container, scale) {
//Add year row
var newRow = document.createElement('div');
newRow.classList.add('year-row');
//Add boxes into row
var currentRowHTML = [];
//Adding Year box
currentRowHTML.push(`<div class="stat-box"><p class="my-flow-text" style="transform:rotate(-60deg); color:white">${year}</p></div>`);
//Adding stat boxes for each month of the year
data.forEach((number) => {
var scaleForClass = Math.round((number / scale[1]) * 10) / 10;
var roundedNumber = Math.round(number * 10) / 10;
currentRowHTML.push(`<div class="stat-box stat-box-active ${getClass(scaleForClass)}"><p class="my-flow-text" >${roundedNumber}</p></div>`);
});
newRow.innerHTML = currentRowHTML.join("");
container.appendChild(newRow);
} | function addRow(year, data, container, scale) {
//Add year row
var newRow = document.createElement('div');
newRow.classList.add('year-row');
//Add boxes into row
var currentRowHTML = [];
//Adding Year box
currentRowHTML.push(`<div class="stat-box"><p class="my-flow-text" style="transform:rotate(-60deg); color:white">${year}</p></div>`);
//Adding stat boxes for each month of the year
data.forEach((number) => {
var scaleForClass = Math.round((number / scale[1]) * 10) / 10;
var roundedNumber = Math.round(number * 10) / 10;
currentRowHTML.push(`<div class="stat-box stat-box-active ${getClass(scaleForClass)}"><p class="my-flow-text" >${roundedNumber}</p></div>`);
});
newRow.innerHTML = currentRowHTML.join("");
container.appendChild(newRow);
} |
JavaScript | function check_hash(hash) {
if (hash.slice(0, 4) == '0000') {
document.getElementById("finalkey").style.backgroundColor = "#D3D9D9";
document.getElementById("finalkey").style.color = "#424242";
}
else {
document.getElementById("finalkey").style.backgroundColor = "red";
document.getElementById("finalkey").style.color = "whitesmoke";
}
} | function check_hash(hash) {
if (hash.slice(0, 4) == '0000') {
document.getElementById("finalkey").style.backgroundColor = "#D3D9D9";
document.getElementById("finalkey").style.color = "#424242";
}
else {
document.getElementById("finalkey").style.backgroundColor = "red";
document.getElementById("finalkey").style.color = "whitesmoke";
}
} |
JavaScript | function add_block() {
let new_data = document.getElementById("newdata").value;
let block = {
'index': blockchain.length + 1,
'data': new_data,
'nonce': 0,
'prev_hash': SHA256(JSON.stringify(blockchain[blockchain.length - 1])),
}
var mined_block = mine_current_block(block);
block["nonce"] = mined_block[0];
blockchain.push(block);
create_block_design(block, blockchain.length - 1);
} | function add_block() {
let new_data = document.getElementById("newdata").value;
let block = {
'index': blockchain.length + 1,
'data': new_data,
'nonce': 0,
'prev_hash': SHA256(JSON.stringify(blockchain[blockchain.length - 1])),
}
var mined_block = mine_current_block(block);
block["nonce"] = mined_block[0];
blockchain.push(block);
create_block_design(block, blockchain.length - 1);
} |
JavaScript | function mine_current_block(block) {
var new_proof = 1;
var check_proof = false;
var hash = null;
while (check_proof == false) {
var generate_hash_for = {
'index': block["index"],
'data': block["data"],
'nonce': new_proof,
'prev_hash': block["prev_hash"],
};
var encoded_block = JSON.stringify(generate_hash_for, sort_keys = true);
hash = SHA256(encoded_block);
if (hash.slice(0, 4) == '0000') {
check_proof = true;
}
else {
new_proof += 1;
}
}
return [new_proof, hash];
} | function mine_current_block(block) {
var new_proof = 1;
var check_proof = false;
var hash = null;
while (check_proof == false) {
var generate_hash_for = {
'index': block["index"],
'data': block["data"],
'nonce': new_proof,
'prev_hash': block["prev_hash"],
};
var encoded_block = JSON.stringify(generate_hash_for, sort_keys = true);
hash = SHA256(encoded_block);
if (hash.slice(0, 4) == '0000') {
check_proof = true;
}
else {
new_proof += 1;
}
}
return [new_proof, hash];
} |
JavaScript | function mine(index) {
var mined_block = mine_current_block(blockchain[index]);
blockchain[index]["nonce"] = mined_block[0];
document.getElementById("nonce" + index.toString()).value = mined_block[0];
document.getElementById("hash" + index.toString()).innerText = mined_block[1];
change_color(index, mined_block[1]);
if (blockchain.length != index + 1) {
var i;
for (i = index; i < blockchain.length; i++) {
// updated hash of next block
let new_hash = SHA256(JSON.stringify(blockchain[i]));
if (blockchain[i + 1] != undefined) {
blockchain[i + 1]["prev_hash"] = new_hash;
document.getElementById("prev_hash" + (i + 1).toString()).innerText = new_hash;
let curr_hash = SHA256(JSON.stringify(blockchain[i + 1]));
document.getElementById("hash" + (i + 1).toString()).innerText = curr_hash;
change_color(i, new_hash);
change_color(i + 1, curr_hash);
}
document.getElementById("hash" + (i).toString()).innerText = new_hash;
}
}
} | function mine(index) {
var mined_block = mine_current_block(blockchain[index]);
blockchain[index]["nonce"] = mined_block[0];
document.getElementById("nonce" + index.toString()).value = mined_block[0];
document.getElementById("hash" + index.toString()).innerText = mined_block[1];
change_color(index, mined_block[1]);
if (blockchain.length != index + 1) {
var i;
for (i = index; i < blockchain.length; i++) {
// updated hash of next block
let new_hash = SHA256(JSON.stringify(blockchain[i]));
if (blockchain[i + 1] != undefined) {
blockchain[i + 1]["prev_hash"] = new_hash;
document.getElementById("prev_hash" + (i + 1).toString()).innerText = new_hash;
let curr_hash = SHA256(JSON.stringify(blockchain[i + 1]));
document.getElementById("hash" + (i + 1).toString()).innerText = curr_hash;
change_color(i, new_hash);
change_color(i + 1, curr_hash);
}
document.getElementById("hash" + (i).toString()).innerText = new_hash;
}
}
} |
JavaScript | function change_color(index, hash) {
if (hash.slice(0, 4) != '0000') {
document.getElementById("hash" + index.toString()).style.backgroundColor = "red";
document.getElementById("hash" + index.toString()).style.color = "whitesmoke";
}
else{
document.getElementById("hash" + index.toString()).style.backgroundColor = "#CFFED4";
document.getElementById("hash" + index.toString()).style.color = "#424242";
}
} | function change_color(index, hash) {
if (hash.slice(0, 4) != '0000') {
document.getElementById("hash" + index.toString()).style.backgroundColor = "red";
document.getElementById("hash" + index.toString()).style.color = "whitesmoke";
}
else{
document.getElementById("hash" + index.toString()).style.backgroundColor = "#CFFED4";
document.getElementById("hash" + index.toString()).style.color = "#424242";
}
} |
JavaScript | function onLocalTracks(tracks) {
localTracks = tracks;
for (let i = 0; i < localTracks.length; i++) {
console.log('Local track', localTracks[i])
localTracks[i].addEventListener(
JitsiMeetJS.events.track.TRACK_AUDIO_LEVEL_CHANGED,
audioLevel => console.log(`Audio Level local: ${audioLevel}`));
localTracks[i].addEventListener(
JitsiMeetJS.events.track.TRACK_MUTE_CHANGED,
() => console.log('local track muted'));
localTracks[i].addEventListener(
JitsiMeetJS.events.track.LOCAL_TRACK_STOPPED,
() => console.log('local track stopped'));
localTracks[i].addEventListener(
JitsiMeetJS.events.track.TRACK_AUDIO_OUTPUT_CHANGED,
deviceId =>
console.log(
`track audio output device was changed to ${deviceId}`));
if (localTracks[i].getType() === 'video') {
// $('#tracks').append(`<video autoplay='1' id='localVideo${i}' class='-localVideoTrack'/>`);
// localTracks[i].attach($(`#localVideo${i}`)[0]);
// localTracks[i].attach($('#localVideo')[0]);
const localVideo = document.getElementById('localVideo');
localTracks[i].attach(localVideo);
localVideo.style.display = 'block';
} else {
// $('#tracks').append(`<audio autoplay='1' muted='true' id='localAudio${i}' />`);
// localTracks[i].attach($(`#localAudio${i}`)[0]);
localTracks[i].attach(document.getElementById('localAudio'));
}
if (isJoined) {
room.addTrack(localTracks[i]);
}
}
} | function onLocalTracks(tracks) {
localTracks = tracks;
for (let i = 0; i < localTracks.length; i++) {
console.log('Local track', localTracks[i])
localTracks[i].addEventListener(
JitsiMeetJS.events.track.TRACK_AUDIO_LEVEL_CHANGED,
audioLevel => console.log(`Audio Level local: ${audioLevel}`));
localTracks[i].addEventListener(
JitsiMeetJS.events.track.TRACK_MUTE_CHANGED,
() => console.log('local track muted'));
localTracks[i].addEventListener(
JitsiMeetJS.events.track.LOCAL_TRACK_STOPPED,
() => console.log('local track stopped'));
localTracks[i].addEventListener(
JitsiMeetJS.events.track.TRACK_AUDIO_OUTPUT_CHANGED,
deviceId =>
console.log(
`track audio output device was changed to ${deviceId}`));
if (localTracks[i].getType() === 'video') {
// $('#tracks').append(`<video autoplay='1' id='localVideo${i}' class='-localVideoTrack'/>`);
// localTracks[i].attach($(`#localVideo${i}`)[0]);
// localTracks[i].attach($('#localVideo')[0]);
const localVideo = document.getElementById('localVideo');
localTracks[i].attach(localVideo);
localVideo.style.display = 'block';
} else {
// $('#tracks').append(`<audio autoplay='1' muted='true' id='localAudio${i}' />`);
// localTracks[i].attach($(`#localAudio${i}`)[0]);
localTracks[i].attach(document.getElementById('localAudio'));
}
if (isJoined) {
room.addTrack(localTracks[i]);
}
}
} |
JavaScript | function onRemoteTrack(track) {
if (track.isLocal()) {
return;
}
log(`Remote track added: ${track}`, track);
const participant = track.getParticipantId();
if (!remoteTracks[participant]) {
remoteTracks[participant] = [];
}
const idx = remoteTracks[participant].push(track);
// remoteTracks[participant].push(track);
track.addEventListener(
JitsiMeetJS.events.track.TRACK_AUDIO_LEVEL_CHANGED,
audioLevel => console.log(`Audio Level remote: ${audioLevel}`));
track.addEventListener(
JitsiMeetJS.events.track.TRACK_MUTE_CHANGED,
() => console.log('remote track muted'));
track.addEventListener(
JitsiMeetJS.events.track.LOCAL_TRACK_STOPPED,
() => console.log('remote track stopped'));
track.addEventListener(JitsiMeetJS.events.track.TRACK_AUDIO_OUTPUT_CHANGED,
deviceId =>
console.log(
`track audio output device was changed to ${deviceId}`));
// const id = participant + track.getType() + idx;
if (track.getType() === 'video') {
// $('#tracks').append(
// `<video autoplay='1' id='${participant}video${idx}' class='remoteVideoTrack'/>`);
const remoteVideo = document.getElementById('remoteVideo');
track.attach(remoteVideo);
remoteVideo.style.display = 'block';
} else {
const id = `${participant}audio${idx}`;
$('#tracks').append(
`<audio autoplay='1' id='${id}' />`);
log( 'attaching track, id:', id );
track.attach($(`#${id}`)[0]);
// track.attach(document.getElementById('remoteAudio'));
}
if (onRemoteTrackCallbackFunc) {
onRemoteTrackCallbackFunc();
onRemoteTrackCallbackFunc = null;
}
} | function onRemoteTrack(track) {
if (track.isLocal()) {
return;
}
log(`Remote track added: ${track}`, track);
const participant = track.getParticipantId();
if (!remoteTracks[participant]) {
remoteTracks[participant] = [];
}
const idx = remoteTracks[participant].push(track);
// remoteTracks[participant].push(track);
track.addEventListener(
JitsiMeetJS.events.track.TRACK_AUDIO_LEVEL_CHANGED,
audioLevel => console.log(`Audio Level remote: ${audioLevel}`));
track.addEventListener(
JitsiMeetJS.events.track.TRACK_MUTE_CHANGED,
() => console.log('remote track muted'));
track.addEventListener(
JitsiMeetJS.events.track.LOCAL_TRACK_STOPPED,
() => console.log('remote track stopped'));
track.addEventListener(JitsiMeetJS.events.track.TRACK_AUDIO_OUTPUT_CHANGED,
deviceId =>
console.log(
`track audio output device was changed to ${deviceId}`));
// const id = participant + track.getType() + idx;
if (track.getType() === 'video') {
// $('#tracks').append(
// `<video autoplay='1' id='${participant}video${idx}' class='remoteVideoTrack'/>`);
const remoteVideo = document.getElementById('remoteVideo');
track.attach(remoteVideo);
remoteVideo.style.display = 'block';
} else {
const id = `${participant}audio${idx}`;
$('#tracks').append(
`<audio autoplay='1' id='${id}' />`);
log( 'attaching track, id:', id );
track.attach($(`#${id}`)[0]);
// track.attach(document.getElementById('remoteAudio'));
}
if (onRemoteTrackCallbackFunc) {
onRemoteTrackCallbackFunc();
onRemoteTrackCallbackFunc = null;
}
} |
JavaScript | function onConferenceJoined() {
console.log('conference joined!');
isJoined = true;
for (let i = 0; i < localTracks.length; i++) {
room.addTrack(localTracks[i]);
}
log( 'getStartMutedPolicy', room.getStartMutedPolicy() );
} | function onConferenceJoined() {
console.log('conference joined!');
isJoined = true;
for (let i = 0; i < localTracks.length; i++) {
room.addTrack(localTracks[i]);
}
log( 'getStartMutedPolicy', room.getStartMutedPolicy() );
} |
JavaScript | function onConnectionSuccess() {
room = connection.initJitsiConference(roomName, confOptions);
room.on(JitsiMeetJS.events.conference.TRACK_ADDED, onRemoteTrack);
room.on(JitsiMeetJS.events.conference.TRACK_REMOVED, track => {
console.log(`track removed!!!${track}`);
});
room.on(
JitsiMeetJS.events.conference.CONFERENCE_JOINED,
onConferenceJoined);
room.on(JitsiMeetJS.events.conference.USER_JOINED, id => {
console.log('user join');
remoteTracks[id] = [];
});
room.on(JitsiMeetJS.events.conference.USER_LEFT, onUserLeft);
room.on(JitsiMeetJS.events.conference.TRACK_MUTE_CHANGED, track => {
console.log(`${track.getType()}-${track.isMuted()}`);
});
room.on(
JitsiMeetJS.events.conference.DISPLAY_NAME_CHANGED,
(userID, displayName) => console.log(`${userID}-${displayName}`));
room.on(
JitsiMeetJS.events.conference.TRACK_AUDIO_LEVEL_CHANGED,
(userID, audioLevel) => console.log(`${userID}-${audioLevel}`));
room.on(
JitsiMeetJS.events.conference.PHONE_NUMBER_CHANGED,
() => console.log(
`${room.getPhoneNumber()}-${room.getPhonePin()}`));
room.on(
JitsiMeetJS.events.conference.TRACK_MUTE_CHANGED, ()=>{
log('TRACK_MUTE_CHANGED')});
room.on(
JitsiMeetJS.events.conference.START_MUTED_POLICY_CHANGED, ()=>{
log('START_MUTED_POLICY_CHANGED')});
room.on(
JitsiMeetJS.events.conference.STARTED_MUTED, ()=>{
log('STARTED_MUTED ') });
room.join(roomPassword);
} | function onConnectionSuccess() {
room = connection.initJitsiConference(roomName, confOptions);
room.on(JitsiMeetJS.events.conference.TRACK_ADDED, onRemoteTrack);
room.on(JitsiMeetJS.events.conference.TRACK_REMOVED, track => {
console.log(`track removed!!!${track}`);
});
room.on(
JitsiMeetJS.events.conference.CONFERENCE_JOINED,
onConferenceJoined);
room.on(JitsiMeetJS.events.conference.USER_JOINED, id => {
console.log('user join');
remoteTracks[id] = [];
});
room.on(JitsiMeetJS.events.conference.USER_LEFT, onUserLeft);
room.on(JitsiMeetJS.events.conference.TRACK_MUTE_CHANGED, track => {
console.log(`${track.getType()}-${track.isMuted()}`);
});
room.on(
JitsiMeetJS.events.conference.DISPLAY_NAME_CHANGED,
(userID, displayName) => console.log(`${userID}-${displayName}`));
room.on(
JitsiMeetJS.events.conference.TRACK_AUDIO_LEVEL_CHANGED,
(userID, audioLevel) => console.log(`${userID}-${audioLevel}`));
room.on(
JitsiMeetJS.events.conference.PHONE_NUMBER_CHANGED,
() => console.log(
`${room.getPhoneNumber()}-${room.getPhonePin()}`));
room.on(
JitsiMeetJS.events.conference.TRACK_MUTE_CHANGED, ()=>{
log('TRACK_MUTE_CHANGED')});
room.on(
JitsiMeetJS.events.conference.START_MUTED_POLICY_CHANGED, ()=>{
log('START_MUTED_POLICY_CHANGED')});
room.on(
JitsiMeetJS.events.conference.STARTED_MUTED, ()=>{
log('STARTED_MUTED ') });
room.join(roomPassword);
} |
JavaScript | function removeEventListeners() {
console.log('disconnect!');
connection.removeEventListener(
JitsiMeetJS.events.connection.CONNECTION_ESTABLISHED,
onConnectionSuccess);
connection.removeEventListener(
JitsiMeetJS.events.connection.CONNECTION_FAILED,
onConnectionFailed);
connection.removeEventListener(
JitsiMeetJS.events.connection.CONNECTION_DISCONNECTED,
removeEventListeners);
} | function removeEventListeners() {
console.log('disconnect!');
connection.removeEventListener(
JitsiMeetJS.events.connection.CONNECTION_ESTABLISHED,
onConnectionSuccess);
connection.removeEventListener(
JitsiMeetJS.events.connection.CONNECTION_FAILED,
onConnectionFailed);
connection.removeEventListener(
JitsiMeetJS.events.connection.CONNECTION_DISCONNECTED,
removeEventListeners);
} |
JavaScript | function connect(conferenceRoomName, conferenceRoomPassword, onRemoteTrackCallback, onUserLeftCallback) {
onRemoteTrackCallbackFunc = onRemoteTrackCallback;
onUserLeftCallbackFunc = onUserLeftCallback;
JitsiMeetJS.init(initOptions);
roomName = conferenceRoomName;
roomPassword = conferenceRoomPassword;
connection = new JitsiMeetJS.JitsiConnection(null, null, jitsiOptions);
connection.addEventListener(
JitsiMeetJS.events.connection.CONNECTION_ESTABLISHED,
onConnectionSuccess);
connection.addEventListener(
JitsiMeetJS.events.connection.CONNECTION_FAILED,
onConnectionFailed);
connection.addEventListener(
JitsiMeetJS.events.connection.CONNECTION_DISCONNECTED,
removeEventListeners);
JitsiMeetJS.mediaDevices.addEventListener(
JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
onDeviceListChanged);
connection.connect();
// JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.DEBUG);
// JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
// console.log('IO Devices', devices);
// });
JitsiMeetJS.createLocalTracks({devices:['video','audio']})
.then(onLocalTracks)
.catch(error => {
console.warn( 'createLocalTracks error', error);
});
loaded = true;
return true;
} | function connect(conferenceRoomName, conferenceRoomPassword, onRemoteTrackCallback, onUserLeftCallback) {
onRemoteTrackCallbackFunc = onRemoteTrackCallback;
onUserLeftCallbackFunc = onUserLeftCallback;
JitsiMeetJS.init(initOptions);
roomName = conferenceRoomName;
roomPassword = conferenceRoomPassword;
connection = new JitsiMeetJS.JitsiConnection(null, null, jitsiOptions);
connection.addEventListener(
JitsiMeetJS.events.connection.CONNECTION_ESTABLISHED,
onConnectionSuccess);
connection.addEventListener(
JitsiMeetJS.events.connection.CONNECTION_FAILED,
onConnectionFailed);
connection.addEventListener(
JitsiMeetJS.events.connection.CONNECTION_DISCONNECTED,
removeEventListeners);
JitsiMeetJS.mediaDevices.addEventListener(
JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
onDeviceListChanged);
connection.connect();
// JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.DEBUG);
// JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
// console.log('IO Devices', devices);
// });
JitsiMeetJS.createLocalTracks({devices:['video','audio']})
.then(onLocalTracks)
.catch(error => {
console.warn( 'createLocalTracks error', error);
});
loaded = true;
return true;
} |
JavaScript | function restart () {
guessedLetters = []
wordObject = { opportunity: 0 }
repeatObject = {}
wordMagic = []
goodWord = []
displayW = ''
guess = ''
a = ''
b = ''
} | function restart () {
guessedLetters = []
wordObject = { opportunity: 0 }
repeatObject = {}
wordMagic = []
goodWord = []
displayW = ''
guess = ''
a = ''
b = ''
} |
JavaScript | function* logoutFlow() {
while (true) {
yield take(LOGOUT);
yield put({ type: SET_AUTH, newAuthState: false });
yield call(logout);
forwardTo('/');
}
} | function* logoutFlow() {
while (true) {
yield take(LOGOUT);
yield put({ type: SET_AUTH, newAuthState: false });
yield call(logout);
forwardTo('/');
}
} |
JavaScript | function* registerFlow() {
while (true) {
// We always listen to `REGISTER_REQUEST` actions
const request = yield take(REGISTER_REQUEST);
const email = request.data.get('email');
const password = request.data.get('password');
const username = request.data.get('username');
// We call the `authorize` task with the data, telling it that we are registering a user
// This returns `true` if the registering was successful, `false` if not
const wasSuccessful = yield call(authorize, { email, password, username, isRegistering: true });
// If we could register a user, we send the appropiate actions
if (wasSuccessful) {
yield put({ type: SET_AUTH, newAuthState: true }); // User is logged in (authorized) after being registered
forwardTo('/add'); // Go to add page
}
}
} | function* registerFlow() {
while (true) {
// We always listen to `REGISTER_REQUEST` actions
const request = yield take(REGISTER_REQUEST);
const email = request.data.get('email');
const password = request.data.get('password');
const username = request.data.get('username');
// We call the `authorize` task with the data, telling it that we are registering a user
// This returns `true` if the registering was successful, `false` if not
const wasSuccessful = yield call(authorize, { email, password, username, isRegistering: true });
// If we could register a user, we send the appropiate actions
if (wasSuccessful) {
yield put({ type: SET_AUTH, newAuthState: true }); // User is logged in (authorized) after being registered
forwardTo('/add'); // Go to add page
}
}
} |
JavaScript | login(email, password, username) {
if (auth.loggedIn()) return Promise.resolve(true);
// Post a fake request
return post(LOGIN_URL, { email, password, username })
.then((response) => {
// Save token to local storage
localStorage.token = response.data.id;
return Promise.resolve(true);
});
} | login(email, password, username) {
if (auth.loggedIn()) return Promise.resolve(true);
// Post a fake request
return post(LOGIN_URL, { email, password, username })
.then((response) => {
// Save token to local storage
localStorage.token = response.data.id;
return Promise.resolve(true);
});
} |
JavaScript | register(email, password, username) {
// Post a fake request
return post(REGISTER_URL, { email, password, username })
// Log user in after registering
.then(() => auth.login(email, password));
} | register(email, password, username) {
// Post a fake request
return post(REGISTER_URL, { email, password, username })
// Log user in after registering
.then(() => auth.login(email, password));
} |
JavaScript | function checkAuth(store) {
return (nextState, replace) => {
const state = store.getState();
const loggedIn = state.getIn(['auth', 'loggedIn']);
// store.dispatch(clearError());
if (AUTH_PATHS.includes(nextState.location.pathname)) {
if (loggedIn) {
return;
}
if (nextState.location.state && nextState.location.pathname) {
replace(nextState.location.pathname);
} else {
replace(LOGIN_PATH);
}
} else {
if (!loggedIn) {
return;
}
if (nextState.location.state && nextState.location.pathname) {
replace(nextState.location.pathname);
} else {
replace(HOME_PATH);
}
}
};
} | function checkAuth(store) {
return (nextState, replace) => {
const state = store.getState();
const loggedIn = state.getIn(['auth', 'loggedIn']);
// store.dispatch(clearError());
if (AUTH_PATHS.includes(nextState.location.pathname)) {
if (loggedIn) {
return;
}
if (nextState.location.state && nextState.location.pathname) {
replace(nextState.location.pathname);
} else {
replace(LOGIN_PATH);
}
} else {
if (!loggedIn) {
return;
}
if (nextState.location.state && nextState.location.pathname) {
replace(nextState.location.pathname);
} else {
replace(HOME_PATH);
}
}
};
} |
JavaScript | function make2xUrl(url) {
var dotIndex = url.lastIndexOf(".");
var name = url.substr(0, dotIndex);
var ext = url.substr(dotIndex + 1);
return name + "@2x." + ext;
} | function make2xUrl(url) {
var dotIndex = url.lastIndexOf(".");
var name = url.substr(0, dotIndex);
var ext = url.substr(dotIndex + 1);
return name + "@2x." + ext;
} |
JavaScript | function applyValidation(objects){
if(objects.length>0){
objects.each(function(){
$(this).validate({
debug: true,
ignore: [],
validClass:'has-success',
errorClass: 'has-error',
highlight: function(element, errorClass, validClass) {
$(element).parent().addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent().removeClass(errorClass).addClass(validClass);
},
errorPlacement: function(error,element){
}
});
});
}
} | function applyValidation(objects){
if(objects.length>0){
objects.each(function(){
$(this).validate({
debug: true,
ignore: [],
validClass:'has-success',
errorClass: 'has-error',
highlight: function(element, errorClass, validClass) {
$(element).parent().addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent().removeClass(errorClass).addClass(validClass);
},
errorPlacement: function(error,element){
}
});
});
}
} |
JavaScript | function addQueryArgs() {
var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var args = arguments.length > 1 ? arguments[1] : undefined;
var baseUrl = url; // Determine whether URL already had query arguments.
var queryStringIndex = url.indexOf('?');
if (queryStringIndex !== -1) {
// Merge into existing query arguments.
args = Object.assign(Object(qs__WEBPACK_IMPORTED_MODULE_0__["parse"])(url.substr(queryStringIndex + 1)), args); // Change working base URL to omit previous query arguments.
baseUrl = baseUrl.substr(0, queryStringIndex);
}
return baseUrl + '?' + Object(qs__WEBPACK_IMPORTED_MODULE_0__["stringify"])(args);
} | function addQueryArgs() {
var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var args = arguments.length > 1 ? arguments[1] : undefined;
var baseUrl = url; // Determine whether URL already had query arguments.
var queryStringIndex = url.indexOf('?');
if (queryStringIndex !== -1) {
// Merge into existing query arguments.
args = Object.assign(Object(qs__WEBPACK_IMPORTED_MODULE_0__["parse"])(url.substr(queryStringIndex + 1)), args); // Change working base URL to omit previous query arguments.
baseUrl = baseUrl.substr(0, queryStringIndex);
}
return baseUrl + '?' + Object(qs__WEBPACK_IMPORTED_MODULE_0__["stringify"])(args);
} |
JavaScript | function createCollection(proto, objectOnly){
function Collection(a){
if (!this || this.constructor !== Collection) return new Collection(a);
this._keys = [];
this._values = [];
this._hash = {};
this.objectOnly = objectOnly;
//parse initial iterable argument passed
if (a) init.call(this, a);
}
//define size for non object-only collections
if (!objectOnly) {
defineProperty(proto, 'size', {
get: sharedSize
});
}
//set prototype
proto.constructor = Collection;
Collection.prototype = proto;
return Collection;
} | function createCollection(proto, objectOnly){
function Collection(a){
if (!this || this.constructor !== Collection) return new Collection(a);
this._keys = [];
this._values = [];
this._hash = {};
this.objectOnly = objectOnly;
//parse initial iterable argument passed
if (a) init.call(this, a);
}
//define size for non object-only collections
if (!objectOnly) {
defineProperty(proto, 'size', {
get: sharedSize
});
}
//set prototype
proto.constructor = Collection;
Collection.prototype = proto;
return Collection;
} |
JavaScript | function sharedValues() {
var self = this;
return this._values.slice().concat(Object.keys(this._hash).map(function (k) {
return self._hash[k];
}));
} | function sharedValues() {
var self = this;
return this._values.slice().concat(Object.keys(this._hash).map(function (k) {
return self._hash[k];
}));
} |
JavaScript | function dispatchEvent(e) {
var handled = false;
evtHandlers.forEach(function (handlers) {
// get the current screen to world offset
me.game.viewport.localToWorld(0, 0, viewportOffset);
for (var t = 0, tl = changedTouches.length; t < tl; t++) {
// Do not fire older events
if (typeof(e.timeStamp) !== "undefined") {
if (e.timeStamp < lastTimeStamp) {
continue;
}
lastTimeStamp = e.timeStamp;
}
// if PointerEvent is not supported
if (!me.device.pointerEnabled) {
// -> define pointerId to simulate the PointerEvent standard
e.pointerId = changedTouches[t].id;
}
/* Initialize the two coordinate space properties. */
e.gameScreenX = changedTouches[t].x;
e.gameScreenY = changedTouches[t].y;
e.gameWorldX = e.gameScreenX + viewportOffset.x;
e.gameWorldY = e.gameScreenY + viewportOffset.y;
if (handlers.region.floating === true) {
e.gameX = e.gameScreenX;
e.gameY = e.gameScreenY;
} else {
e.gameX = e.gameWorldX;
e.gameY = e.gameWorldY;
}
var region = handlers.region;
var bounds = region.getBounds();
var eventInBounds =
// check the shape bounding box first
bounds.containsPoint(e.gameX, e.gameY) &&
// then check more precisely if needed
(bounds === region || region.containsPoint(e.gameX, e.gameY));
switch (activeEventList.indexOf(e.type)) {
case POINTER_MOVE:
// moved out of bounds: trigger the POINTER_LEAVE callbacks
if (handlers.pointerId === e.pointerId && !eventInBounds) {
if (triggerEvent(handlers, activeEventList[POINTER_LEAVE], e, null)) {
handled = true;
break;
}
}
// no pointer & moved inside of bounds: trigger the POINTER_ENTER callbacks
else if (handlers.pointerId === null && eventInBounds) {
if (triggerEvent(handlers, activeEventList[POINTER_ENTER], e, e.pointerId)) {
handled = true;
break;
}
}
// trigger the POINTER_MOVE callbacks
if (eventInBounds && triggerEvent(handlers, e.type, e, e.pointerId)) {
handled = true;
break;
}
break;
case POINTER_UP:
// pointer defined & inside of bounds: trigger the POINTER_UP callback
if (handlers.pointerId === e.pointerId && eventInBounds) {
// trigger the corresponding callback
if (triggerEvent(handlers, e.type, e, null)) {
handled = true;
break;
}
}
break;
case POINTER_CANCEL:
// pointer defined: trigger the POINTER_CANCEL callback
if (handlers.pointerId === e.pointerId) {
// trigger the corresponding callback
if (triggerEvent(handlers, e.type, e, null)) {
handled = true;
break;
}
}
break;
default:
// event inside of bounds: trigger the POINTER_DOWN or MOUSE_WHEEL callback
if (eventInBounds) {
// trigger the corresponding callback
if (triggerEvent(handlers, e.type, e, e.pointerId)) {
handled = true;
break;
}
}
break;
}
}
});
return handled;
} | function dispatchEvent(e) {
var handled = false;
evtHandlers.forEach(function (handlers) {
// get the current screen to world offset
me.game.viewport.localToWorld(0, 0, viewportOffset);
for (var t = 0, tl = changedTouches.length; t < tl; t++) {
// Do not fire older events
if (typeof(e.timeStamp) !== "undefined") {
if (e.timeStamp < lastTimeStamp) {
continue;
}
lastTimeStamp = e.timeStamp;
}
// if PointerEvent is not supported
if (!me.device.pointerEnabled) {
// -> define pointerId to simulate the PointerEvent standard
e.pointerId = changedTouches[t].id;
}
/* Initialize the two coordinate space properties. */
e.gameScreenX = changedTouches[t].x;
e.gameScreenY = changedTouches[t].y;
e.gameWorldX = e.gameScreenX + viewportOffset.x;
e.gameWorldY = e.gameScreenY + viewportOffset.y;
if (handlers.region.floating === true) {
e.gameX = e.gameScreenX;
e.gameY = e.gameScreenY;
} else {
e.gameX = e.gameWorldX;
e.gameY = e.gameWorldY;
}
var region = handlers.region;
var bounds = region.getBounds();
var eventInBounds =
// check the shape bounding box first
bounds.containsPoint(e.gameX, e.gameY) &&
// then check more precisely if needed
(bounds === region || region.containsPoint(e.gameX, e.gameY));
switch (activeEventList.indexOf(e.type)) {
case POINTER_MOVE:
// moved out of bounds: trigger the POINTER_LEAVE callbacks
if (handlers.pointerId === e.pointerId && !eventInBounds) {
if (triggerEvent(handlers, activeEventList[POINTER_LEAVE], e, null)) {
handled = true;
break;
}
}
// no pointer & moved inside of bounds: trigger the POINTER_ENTER callbacks
else if (handlers.pointerId === null && eventInBounds) {
if (triggerEvent(handlers, activeEventList[POINTER_ENTER], e, e.pointerId)) {
handled = true;
break;
}
}
// trigger the POINTER_MOVE callbacks
if (eventInBounds && triggerEvent(handlers, e.type, e, e.pointerId)) {
handled = true;
break;
}
break;
case POINTER_UP:
// pointer defined & inside of bounds: trigger the POINTER_UP callback
if (handlers.pointerId === e.pointerId && eventInBounds) {
// trigger the corresponding callback
if (triggerEvent(handlers, e.type, e, null)) {
handled = true;
break;
}
}
break;
case POINTER_CANCEL:
// pointer defined: trigger the POINTER_CANCEL callback
if (handlers.pointerId === e.pointerId) {
// trigger the corresponding callback
if (triggerEvent(handlers, e.type, e, null)) {
handled = true;
break;
}
}
break;
default:
// event inside of bounds: trigger the POINTER_DOWN or MOUSE_WHEEL callback
if (eventInBounds) {
// trigger the corresponding callback
if (triggerEvent(handlers, e.type, e, e.pointerId)) {
handled = true;
break;
}
}
break;
}
}
});
return handled;
} |
JavaScript | function handleleftheadertheme() {
$('.theme-color > a.leftheader-theme').on("click", function() {
var lheadertheme = $(this).attr("lheader-theme");
$('.pcoded-navigation-label').attr("menu-title-theme", lheadertheme);
setCookie("menu-title-theme", lheadertheme, 1);
});
} | function handleleftheadertheme() {
$('.theme-color > a.leftheader-theme').on("click", function() {
var lheadertheme = $(this).attr("lheader-theme");
$('.pcoded-navigation-label').attr("menu-title-theme", lheadertheme);
setCookie("menu-title-theme", lheadertheme, 1);
});
} |
JavaScript | function handleactiveitemtheme() {
$('.theme-color > a.active-item-theme').on("click", function() {
var activeitemtheme = $(this).attr("active-item-theme");
$('.pcoded-navbar').attr("active-item-theme", activeitemtheme);
setCookie("active-item-theme", activeitemtheme, 1);
});
} | function handleactiveitemtheme() {
$('.theme-color > a.active-item-theme').on("click", function() {
var activeitemtheme = $(this).attr("active-item-theme");
$('.pcoded-navbar').attr("active-item-theme", activeitemtheme);
setCookie("active-item-theme", activeitemtheme, 1);
});
} |
JavaScript | function handlethemebgpattern() {
$('.theme-color > a.themebg-pattern').on("click", function() {
var themebgpattern = $(this).attr("themebg-pattern");
$('body').attr("themebg-pattern", themebgpattern);
setCookie("themebg-pattern", themebgpattern, 1);
});
} | function handlethemebgpattern() {
$('.theme-color > a.themebg-pattern').on("click", function() {
var themebgpattern = $(this).attr("themebg-pattern");
$('body').attr("themebg-pattern", themebgpattern);
setCookie("themebg-pattern", themebgpattern, 1);
});
} |
JavaScript | function useQueries(createHistory) {
return function (options={}) {
let { stringifyQuery, parseQueryString, ...historyOptions } = options
let history = createHistory(historyOptions)
if (typeof stringifyQuery !== 'function')
stringifyQuery = defaultStringifyQuery
if (typeof parseQueryString !== 'function')
parseQueryString = defaultParseQueryString
function addQuery(location) {
if (location.query == null)
location.query = parseQueryString(location.search.substring(1))
return location
}
function appendQuery(pathname, query) {
let queryString
if (query && (queryString = stringifyQuery(query)) !== '')
return pathname + (pathname.indexOf('?') === -1 ? '?' : '&') + queryString
return pathname
}
// Override all read methods with query-aware versions.
function listenBefore(hook) {
return history.listenBefore(function (location, callback) {
runTransitionHook(hook, addQuery(location), callback)
})
}
function listen(listener) {
return history.listen(function (location) {
listener(addQuery(location))
})
}
// Override all write methods with query-aware versions.
function pushState(state, pathname, query) {
return history.pushState(state, appendQuery(pathname, query))
}
function replaceState(state, pathname, query) {
return history.replaceState(state, appendQuery(pathname, query))
}
function createPath(pathname, query) {
return history.createPath(appendQuery(pathname, query))
}
function createHref(pathname, query) {
return history.createHref(appendQuery(pathname, query))
}
function createLocation() {
return addQuery(history.createLocation.apply(history, arguments))
}
return {
...history,
listenBefore,
listen,
pushState,
replaceState,
createPath,
createHref,
createLocation
}
}
} | function useQueries(createHistory) {
return function (options={}) {
let { stringifyQuery, parseQueryString, ...historyOptions } = options
let history = createHistory(historyOptions)
if (typeof stringifyQuery !== 'function')
stringifyQuery = defaultStringifyQuery
if (typeof parseQueryString !== 'function')
parseQueryString = defaultParseQueryString
function addQuery(location) {
if (location.query == null)
location.query = parseQueryString(location.search.substring(1))
return location
}
function appendQuery(pathname, query) {
let queryString
if (query && (queryString = stringifyQuery(query)) !== '')
return pathname + (pathname.indexOf('?') === -1 ? '?' : '&') + queryString
return pathname
}
// Override all read methods with query-aware versions.
function listenBefore(hook) {
return history.listenBefore(function (location, callback) {
runTransitionHook(hook, addQuery(location), callback)
})
}
function listen(listener) {
return history.listen(function (location) {
listener(addQuery(location))
})
}
// Override all write methods with query-aware versions.
function pushState(state, pathname, query) {
return history.pushState(state, appendQuery(pathname, query))
}
function replaceState(state, pathname, query) {
return history.replaceState(state, appendQuery(pathname, query))
}
function createPath(pathname, query) {
return history.createPath(appendQuery(pathname, query))
}
function createHref(pathname, query) {
return history.createHref(appendQuery(pathname, query))
}
function createLocation() {
return addQuery(history.createLocation.apply(history, arguments))
}
return {
...history,
listenBefore,
listen,
pushState,
replaceState,
createPath,
createHref,
createLocation
}
}
} |
JavaScript | function listenBefore(hook) {
return history.listenBefore(function (location, callback) {
runTransitionHook(hook, addQuery(location), callback)
})
} | function listenBefore(hook) {
return history.listenBefore(function (location, callback) {
runTransitionHook(hook, addQuery(location), callback)
})
} |
JavaScript | validateField(fieldName, value){
let fieldValidationErrors = this.state.formErrors;
let { UserNameValid, EmailValid, ContactValid, ProductNameValid, ProductPriceValid } = this.state
switch(fieldName) {
case 'Email':
if(value === '')
{ fieldValidationErrors.Email = '*This field is must please enter email';
EmailValid = false;
}
else{
EmailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.Email = EmailValid ? '' : '*Email is invalid';
}
break;
case 'UserName':
if(value === '')
{fieldValidationErrors.UserName = '*This field is must please enter name'
UserNameValid = false;
}
else{
UserNameValid = value.length <= 32;
fieldValidationErrors.UserName = UserNameValid ? '': '*Seller Name is too long max size is 32';
}
break;
case 'Contact':
if(value === '')
{fieldValidationErrors.Contact = '*This field is must please enter contact number'
ContactValid = false;
}
else{
ContactValid = value.length === 10;
fieldValidationErrors.Contact = ContactValid ? '': '*Contact Number is not valid';
}
break;
case 'ProductName':
if(value === '')
{fieldValidationErrors.ProductName = '*This field is must please enter Name'
ProductNameValid = false;
}
else{
ProductNameValid = value.length <= 100;
fieldValidationErrors.ProductName = ProductNameValid ? '': '*Product Name is too long max size is 100';
}
break;
case 'ProductPrice':
if(value === ''){
fieldValidationErrors.ProductPrice = '*This field is must please enter Price'
ProductPriceValid = false;
}
else
{
fieldValidationErrors.ProductPrice = '';
ProductPriceValid = true;
}
break;
default:
break;
}
this.setState({formErrors: fieldValidationErrors,
EmailValid: EmailValid,
UserNameValid: UserNameValid,
ContactValid: ContactValid,
ProductNameValid: ProductNameValid,
ProductPriceValid: ProductPriceValid
}, this.validateForm);
} | validateField(fieldName, value){
let fieldValidationErrors = this.state.formErrors;
let { UserNameValid, EmailValid, ContactValid, ProductNameValid, ProductPriceValid } = this.state
switch(fieldName) {
case 'Email':
if(value === '')
{ fieldValidationErrors.Email = '*This field is must please enter email';
EmailValid = false;
}
else{
EmailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.Email = EmailValid ? '' : '*Email is invalid';
}
break;
case 'UserName':
if(value === '')
{fieldValidationErrors.UserName = '*This field is must please enter name'
UserNameValid = false;
}
else{
UserNameValid = value.length <= 32;
fieldValidationErrors.UserName = UserNameValid ? '': '*Seller Name is too long max size is 32';
}
break;
case 'Contact':
if(value === '')
{fieldValidationErrors.Contact = '*This field is must please enter contact number'
ContactValid = false;
}
else{
ContactValid = value.length === 10;
fieldValidationErrors.Contact = ContactValid ? '': '*Contact Number is not valid';
}
break;
case 'ProductName':
if(value === '')
{fieldValidationErrors.ProductName = '*This field is must please enter Name'
ProductNameValid = false;
}
else{
ProductNameValid = value.length <= 100;
fieldValidationErrors.ProductName = ProductNameValid ? '': '*Product Name is too long max size is 100';
}
break;
case 'ProductPrice':
if(value === ''){
fieldValidationErrors.ProductPrice = '*This field is must please enter Price'
ProductPriceValid = false;
}
else
{
fieldValidationErrors.ProductPrice = '';
ProductPriceValid = true;
}
break;
default:
break;
}
this.setState({formErrors: fieldValidationErrors,
EmailValid: EmailValid,
UserNameValid: UserNameValid,
ContactValid: ContactValid,
ProductNameValid: ProductNameValid,
ProductPriceValid: ProductPriceValid
}, this.validateForm);
} |
JavaScript | validateForm(){
const { UserNameValid, EmailValid, ContactValid, ProductNameValid, ProductPriceValid } = this.state
this.setState({
sellerFormValid: UserNameValid && EmailValid && ContactValid,
productFormValid: ProductNameValid && ProductPriceValid
})
} | validateForm(){
const { UserNameValid, EmailValid, ContactValid, ProductNameValid, ProductPriceValid } = this.state
this.setState({
sellerFormValid: UserNameValid && EmailValid && ContactValid,
productFormValid: ProductNameValid && ProductPriceValid
})
} |
JavaScript | function Enemy(enemyType, health, mana, strength, agility, speed) {
// really a base class should be created and inherited from for the different player types instead of using this classType attribute
this.enemyType = enemyType;
this.health = health;
this.mana = mana;
this.strength = strength;
this.agility = agility;
this.speed = speed;
} | function Enemy(enemyType, health, mana, strength, agility, speed) {
// really a base class should be created and inherited from for the different player types instead of using this classType attribute
this.enemyType = enemyType;
this.health = health;
this.mana = mana;
this.strength = strength;
this.agility = agility;
this.speed = speed;
} |
JavaScript | function Buy(name ) {
this.name = name.split('.')[0]; // return array of 2
this.urlImage = `img/${name}`;
this.timeImgDisplay= 0;
this.clkOneachimg = 0;
myObjectArray.push(this);
} | function Buy(name ) {
this.name = name.split('.')[0]; // return array of 2
this.urlImage = `img/${name}`;
this.timeImgDisplay= 0;
this.clkOneachimg = 0;
myObjectArray.push(this);
} |
JavaScript | function fade(opacity) {
return function(d, i) {
svg
.selectAll("path.chord")
.filter(function(d) {
return d.source.index !== i && d.target.index !== i;
})
.transition()
.style("opacity", opacity);
};
} //fade | function fade(opacity) {
return function(d, i) {
svg
.selectAll("path.chord")
.filter(function(d) {
return d.source.index !== i && d.target.index !== i;
})
.transition()
.style("opacity", opacity);
};
} //fade |
JavaScript | function mouseoutChord(d) {
//Hide the tooltip
$(".popover").each(function() {
$(this).remove();
});
//Set opacity back to default for all
svg
.selectAll("path.chord")
.transition()
.style("opacity", opacityDefault);
} //function mouseoutChord | function mouseoutChord(d) {
//Hide the tooltip
$(".popover").each(function() {
$(this).remove();
});
//Set opacity back to default for all
svg
.selectAll("path.chord")
.transition()
.style("opacity", opacityDefault);
} //function mouseoutChord |
JavaScript | function extend(destination, source, deep) {
// JScript DontEnum bug is not taken care of
// the deep clone is for internal use, is not meant to avoid
// javascript traps or cloning html element or self referenced objects.
if (deep) {
if (!fabric.isLikelyNode && source instanceof Element) {
// avoid cloning deep images, canvases,
destination = source;
}
else if (source instanceof Array) {
destination = source.map(function(v) {
return clone(v, deep)
})
}
else if (source instanceof Object) {
for (var property in source) {
if (source.hasOwnProperty(property)) {
destination[property] = clone(source[property], deep)
}
}
}
else {
// this sounds odd for an extend but is ok for recursive use
destination = source;
}
}
else {
for (var property in source) {
destination[property] = source[property];
}
}
return destination;
} | function extend(destination, source, deep) {
// JScript DontEnum bug is not taken care of
// the deep clone is for internal use, is not meant to avoid
// javascript traps or cloning html element or self referenced objects.
if (deep) {
if (!fabric.isLikelyNode && source instanceof Element) {
// avoid cloning deep images, canvases,
destination = source;
}
else if (source instanceof Array) {
destination = source.map(function(v) {
return clone(v, deep)
})
}
else if (source instanceof Object) {
for (var property in source) {
if (source.hasOwnProperty(property)) {
destination[property] = clone(source[property], deep)
}
}
}
else {
// this sounds odd for an extend but is ok for recursive use
destination = source;
}
}
else {
for (var property in source) {
destination[property] = source[property];
}
}
return destination;
} |
JavaScript | function createGanttZoomList(latency) {
var zoomLevelList = new Array(1);
var curZoom = 1;
while (curZoom * 16 < latency) {
curZoom *= 2;
if (curZoom > latency) {
zoomLevelList.push(latency);
}
else {
zoomLevelList.push(curZoom);
}
}
return zoomLevelList;
} | function createGanttZoomList(latency) {
var zoomLevelList = new Array(1);
var curZoom = 1;
while (curZoom * 16 < latency) {
curZoom *= 2;
if (curZoom > latency) {
zoomLevelList.push(latency);
}
else {
zoomLevelList.push(curZoom);
}
}
return zoomLevelList;
} |
JavaScript | function flattenJSON(oldJSON, funcNodeID) {
if (funcNodeID === undefined) {
funcNodeID = -1;
}
var newJSON = [];
if (debugMode)
console.log("JSON IS AN ARRAY ");
for (let i = 0; i < oldJSON.length; i++) {
let node = oldJSON[i];
if (i > 0) {
flattenNode(node, newJSON, funcNodeID, oldJSON[i - 1].id);
}
else {
flattenNode(node, newJSON, funcNodeID, funcNodeID);
}
}
return newJSON;
} | function flattenJSON(oldJSON, funcNodeID) {
if (funcNodeID === undefined) {
funcNodeID = -1;
}
var newJSON = [];
if (debugMode)
console.log("JSON IS AN ARRAY ");
for (let i = 0; i < oldJSON.length; i++) {
let node = oldJSON[i];
if (i > 0) {
flattenNode(node, newJSON, funcNodeID, oldJSON[i - 1].id);
}
else {
flattenNode(node, newJSON, funcNodeID, funcNodeID);
}
}
return newJSON;
} |
JavaScript | function populateSFCInLoopData(loopDataNodes) {
for (let i = 0; i < loopDataNodes.length; i++) {
let sfcDepth = [];
// this id is the one that matched the block.json's id
if (blockJSON.hasOwnProperty(loopDataNodes[i]['id'])) {
let blockNodes = blockJSON[loopDataNodes[i]['id']]['nodes'];
blockNodes.forEach(function (blockNode) {
if (blockNode.hasOwnProperty('children')) {
for (let k = 0; k < blockNode['children'].length; k++) {
// check for stall free clusters
if (blockNode['children'][k]['name'] == 'Exit') {
// TODO: blockJSON needs to have this data so we dont have to parse the details
// TODO: to model SFC the model needs to go 1 level below, may need to add more info
let fifoDepth = parseInt(blockNode['children'][k]['details'][0]['Exit FIFO Depth']);
sfcDepth.push(fifoDepth);
}
}
}
});
}
if (sfcDepth.length > 0) {
loopDataNodes[i]['sfc'] = sfcDepth;
}
}
} | function populateSFCInLoopData(loopDataNodes) {
for (let i = 0; i < loopDataNodes.length; i++) {
let sfcDepth = [];
// this id is the one that matched the block.json's id
if (blockJSON.hasOwnProperty(loopDataNodes[i]['id'])) {
let blockNodes = blockJSON[loopDataNodes[i]['id']]['nodes'];
blockNodes.forEach(function (blockNode) {
if (blockNode.hasOwnProperty('children')) {
for (let k = 0; k < blockNode['children'].length; k++) {
// check for stall free clusters
if (blockNode['children'][k]['name'] == 'Exit') {
// TODO: blockJSON needs to have this data so we dont have to parse the details
// TODO: to model SFC the model needs to go 1 level below, may need to add more info
let fifoDepth = parseInt(blockNode['children'][k]['details'][0]['Exit FIFO Depth']);
sfcDepth.push(fifoDepth);
}
}
}
});
}
if (sfcDepth.length > 0) {
loopDataNodes[i]['sfc'] = sfcDepth;
}
}
} |
JavaScript | function postProcessLimiters(node) {
if (isComponentOrFunctionNode(node))
return;
// Do the first if statement for both starts/ends
let allObjects = [];
if (node.hasOwnProperty("limiter_start_objects"))
allObjects = allObjects.concat(node.limiter_start_objects);
if (node.hasOwnProperty("limiter_end_objects")) {
let limiter_end_objects_values = Object.keys(node.limiter_end_objects).map(function (key) {
return node.limiter_end_objects[key];
});
allObjects = allObjects.concat(limiter_end_objects_values);
}
if (allObjects.length > 0) {
let implicitLimiterDetails = [];
sortArray(allObjects, "partition_start");
if (parseInt(allObjects[0].partition_start) != 0) {
implicitLimiterDetails.push(createImplicitLimiterDetailNode(0, allObjects[0].partition_start));
}
for (let i = 0; i < allObjects.length; i++) {
// Create implicit limiters between stallable points of the block
if (i == allObjects.length - 1) {
if (allObjects[i].partition_start != node.latency)
// Don't create something that spans the whole block - why not? avoid duplicates? I'll add a duplicate checker to addLimiterToNode
// Don't create a probe (start end at the same point)
implicitLimiterDetails.push(createImplicitLimiterDetailNode(allObjects[i].partition_start, node.latency));
//createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.latency);
}
else {
if (allObjects[i].partition_start != allObjects[i + 1].partition_start)
implicitLimiterDetails.push(createImplicitLimiterDetailNode(allObjects[i].partition_start, allObjects[i + 1].partition_start));
//createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.limiter_start_objects[i+1].partition_start);
}
}
// Actually add the limiters
for (let i = 0; i < implicitLimiterDetails.length; i++) {
let implicitLimiterStart = implicitLimiterDetails[i].start;
let implicitLimiterEnd = implicitLimiterDetails[i].end;
//if (node.interleaving > 1) createImplicitLimiter(node, node, parseInt(implicitLimiterStart), parseInt(implicitLimiterEnd), -1, true);
//else
createImplicitLimiter(node, node, parseInt(implicitLimiterStart), parseInt(implicitLimiterEnd));
}
}
// if (node.hasOwnProperty("limiter_start_objects")) {
// let implicitLimiterDetails = [];
// let nodeLimiterStartObjectLength = node.limiter_start_objects.length;
// if (parseInt(node.limiter_start_objects[0].partition_start) != 0) {
// implicitLimiterDetails.push(createImplicitLimiterDetailNode(0, node.limiter_start_objects[0].partition_start));
// }
// for (let i = 0; i < nodeLimiterStartObjectLength; i++) {
// // Create implicit limiters between stallable points of the block
// if (i == node.limiter_start_objects.length - 1 ) {
// if (parseInt(node.limiter_start_objects[i].partition_start) != 0 && node.limiter_start_objects[i].partition_start != node.latency)
// // Don't create something that spans the whole block - why not?
// // Don't create a probe (start end at the same point)
// implicitLimiterDetails.push(createImplicitLimiterDetailNode(node.limiter_start_objects[i].partition_start, node.latency ));
// //createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.latency);
// } else {
// if (node.limiter_start_objects[i].partition_start != node.limiter_start_objects[i+1].partition_start)
// implicitLimiterDetails.push(createImplicitLimiterDetailNode(node.limiter_start_objects[i].partition_start, node.limiter_start_objects[i+1].partition_start ));
// //createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.limiter_start_objects[i+1].partition_start);
// }
// }
// // Actually add the limiters
// for (let i = 0; i < implicitLimiterDetails.length; i++) {
// let implicitLimiterStart = implicitLimiterDetails[i].start;
// let implicitLimiterEnd = implicitLimiterDetails[i].end;
// createImplicitLimiter(node, node, parseInt(implicitLimiterStart), parseInt(implicitLimiterEnd));
// }
// }
// Find the closest start point before each end point, within the same node
if (node.hasOwnProperty("limiter_end_objects")) {
let limiter_end_objects_values = Object.keys(node.limiter_end_objects).map(function (key) {
return node.limiter_end_objects[key];
});
limiter_end_objects_values.forEach(function (endObject) {
let lastStartPoint = 0;
let lastStartLimiterID = "";
if (node.hasOwnProperty("limiter_start_objects")) {
for (let i = 0; i < node.limiter_start_objects.length; i++) {
if (parseInt(node.limiter_start_objects[i].partition_start) > parseInt(endObject.partition_start) && i > 0) {
lastStartPoint = node.limiter_start_objects[i - 1].partition_start;
lastStartLimiterID = node.limiter_start_objects[i - 1].id;
break; // Found the last start point
}
// If a stall point is equal to the end point, then it should use it
if (parseInt(node.limiter_start_objects[i].partition_start) == parseInt(endObject.partition_start)) {
lastStartPoint = node.limiter_start_objects[i].partition_start;
lastStartLimiterID = node.limiter_start_objects[i].id;
break; // Found the last start point
}
}
}
let distanceFromLastStartPoint = parseInt(endObject.partition_start) - parseInt(lastStartPoint);
endObject["distance_from_last_start_point"] = distanceFromLastStartPoint;
endObject["last_start_point"] = lastStartPoint; //lastStartLimiterID; // If this value is empty, use the node's start point
});
}
} | function postProcessLimiters(node) {
if (isComponentOrFunctionNode(node))
return;
// Do the first if statement for both starts/ends
let allObjects = [];
if (node.hasOwnProperty("limiter_start_objects"))
allObjects = allObjects.concat(node.limiter_start_objects);
if (node.hasOwnProperty("limiter_end_objects")) {
let limiter_end_objects_values = Object.keys(node.limiter_end_objects).map(function (key) {
return node.limiter_end_objects[key];
});
allObjects = allObjects.concat(limiter_end_objects_values);
}
if (allObjects.length > 0) {
let implicitLimiterDetails = [];
sortArray(allObjects, "partition_start");
if (parseInt(allObjects[0].partition_start) != 0) {
implicitLimiterDetails.push(createImplicitLimiterDetailNode(0, allObjects[0].partition_start));
}
for (let i = 0; i < allObjects.length; i++) {
// Create implicit limiters between stallable points of the block
if (i == allObjects.length - 1) {
if (allObjects[i].partition_start != node.latency)
// Don't create something that spans the whole block - why not? avoid duplicates? I'll add a duplicate checker to addLimiterToNode
// Don't create a probe (start end at the same point)
implicitLimiterDetails.push(createImplicitLimiterDetailNode(allObjects[i].partition_start, node.latency));
//createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.latency);
}
else {
if (allObjects[i].partition_start != allObjects[i + 1].partition_start)
implicitLimiterDetails.push(createImplicitLimiterDetailNode(allObjects[i].partition_start, allObjects[i + 1].partition_start));
//createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.limiter_start_objects[i+1].partition_start);
}
}
// Actually add the limiters
for (let i = 0; i < implicitLimiterDetails.length; i++) {
let implicitLimiterStart = implicitLimiterDetails[i].start;
let implicitLimiterEnd = implicitLimiterDetails[i].end;
//if (node.interleaving > 1) createImplicitLimiter(node, node, parseInt(implicitLimiterStart), parseInt(implicitLimiterEnd), -1, true);
//else
createImplicitLimiter(node, node, parseInt(implicitLimiterStart), parseInt(implicitLimiterEnd));
}
}
// if (node.hasOwnProperty("limiter_start_objects")) {
// let implicitLimiterDetails = [];
// let nodeLimiterStartObjectLength = node.limiter_start_objects.length;
// if (parseInt(node.limiter_start_objects[0].partition_start) != 0) {
// implicitLimiterDetails.push(createImplicitLimiterDetailNode(0, node.limiter_start_objects[0].partition_start));
// }
// for (let i = 0; i < nodeLimiterStartObjectLength; i++) {
// // Create implicit limiters between stallable points of the block
// if (i == node.limiter_start_objects.length - 1 ) {
// if (parseInt(node.limiter_start_objects[i].partition_start) != 0 && node.limiter_start_objects[i].partition_start != node.latency)
// // Don't create something that spans the whole block - why not?
// // Don't create a probe (start end at the same point)
// implicitLimiterDetails.push(createImplicitLimiterDetailNode(node.limiter_start_objects[i].partition_start, node.latency ));
// //createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.latency);
// } else {
// if (node.limiter_start_objects[i].partition_start != node.limiter_start_objects[i+1].partition_start)
// implicitLimiterDetails.push(createImplicitLimiterDetailNode(node.limiter_start_objects[i].partition_start, node.limiter_start_objects[i+1].partition_start ));
// //createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.limiter_start_objects[i+1].partition_start);
// }
// }
// // Actually add the limiters
// for (let i = 0; i < implicitLimiterDetails.length; i++) {
// let implicitLimiterStart = implicitLimiterDetails[i].start;
// let implicitLimiterEnd = implicitLimiterDetails[i].end;
// createImplicitLimiter(node, node, parseInt(implicitLimiterStart), parseInt(implicitLimiterEnd));
// }
// }
// Find the closest start point before each end point, within the same node
if (node.hasOwnProperty("limiter_end_objects")) {
let limiter_end_objects_values = Object.keys(node.limiter_end_objects).map(function (key) {
return node.limiter_end_objects[key];
});
limiter_end_objects_values.forEach(function (endObject) {
let lastStartPoint = 0;
let lastStartLimiterID = "";
if (node.hasOwnProperty("limiter_start_objects")) {
for (let i = 0; i < node.limiter_start_objects.length; i++) {
if (parseInt(node.limiter_start_objects[i].partition_start) > parseInt(endObject.partition_start) && i > 0) {
lastStartPoint = node.limiter_start_objects[i - 1].partition_start;
lastStartLimiterID = node.limiter_start_objects[i - 1].id;
break; // Found the last start point
}
// If a stall point is equal to the end point, then it should use it
if (parseInt(node.limiter_start_objects[i].partition_start) == parseInt(endObject.partition_start)) {
lastStartPoint = node.limiter_start_objects[i].partition_start;
lastStartLimiterID = node.limiter_start_objects[i].id;
break; // Found the last start point
}
}
}
let distanceFromLastStartPoint = parseInt(endObject.partition_start) - parseInt(lastStartPoint);
endObject["distance_from_last_start_point"] = distanceFromLastStartPoint;
endObject["last_start_point"] = lastStartPoint; //lastStartLimiterID; // If this value is empty, use the node's start point
});
}
} |
JavaScript | function addLimiterToLoopNodes(limiterParentNode, limiterStartParentNode, limiterEndParentNode, limiterStartElement, limiterEndElement, limitedRegionCapacity, checkPreviousIteration, thresholdDelay) {
if (checkPreviousIteration === undefined) {
checkPreviousIteration = false;
}
if (thresholdDelay === undefined) {
thresholdDelay = false;
}
// Sanity check that limiterElement's block parent == node
if (isComponentOrFunctionNode(limiterStartParentNode) || isComponentOrFunctionNode(limiterEndParentNode))
return;
if (!limiterStartParentNode.hasOwnProperty("limiter_start_objects")) {
limiterStartParentNode["limiter_start_objects"] = [];
limiterStartParentNode["limiter_start_objects_map_by_startpoint"] = {};
}
if (!limiterEndParentNode.hasOwnProperty("limiter_end_objects")) {
limiterEndParentNode["limiter_end_objects"] = {};
}
// doesLimiterExist finds a limiter that starts and ends at the exact same places, and updates the capacity to the lower between two options
// Returns true if a duplicate limiter is found/updated
if (doesLimiterExist(limiterStartParentNode, limiterEndParentNode, limiterStartElement, limiterEndElement, limitedRegionCapacity))
return;
let limiterStartObject = {};
let limiterEndObject = {};
limiterStartObject["is_limiter_start"] = true;
limiterStartObject['id'] = limiterStartElement.id;
limiterEndObject["is_limiter_start"] = false;
limiterEndObject['id'] = limiterEndElement.id;
limiterStartObject["limiter_parent_id"] = limiterParentNode.id;
limiterEndObject["limiter_parent_id"] = limiterParentNode.id;
limiterStartObject["check_prev_iter"] = checkPreviousIteration;
limiterEndObject["check_prev_iter"] = checkPreviousIteration;
limiterStartObject["threshold_delay"] = thresholdDelay;
limiterEndObject["threshold_delay"] = thresholdDelay;
// Limiter start needs to know the ID of the limiter end, to gather endpoint encounter data
limiterStartObject["limiter_end_node_id"] = limiterEndParentNode.id;
limiterStartObject["limiter_end_id"] = limiterEndElement.id; // To find the correct element in the limiter_end_objects hash
// Limiter end needs to know the ID of the limiter start, to see if there is a new start encounter it needs to address
limiterEndObject["limiter_start_node_id"] = limiterStartParentNode.id;
limiterEndObject["limiter_start_id"] = limiterStartElement.id; // To find the correct element in the limiter_end_objects hash
limiterStartObject["partition_start"] = limiterStartElement.start;
limiterEndObject["partition_start"] = limiterEndElement.start;
limiterStartObject["limited_region_capacity"] = limitedRegionCapacity;
limiterStartObject["limited_region_num_threads"] = 0; // Initialize to zero, every encounter of the limited region start should increment this
// Not sure if this is necessary:
// I don't love this name
limiterStartObject["partition_start_encounters"] = [];
limiterEndObject["partition_start_encounters"] = [];
if (limiterStartParentNode.id == limiterEndParentNode.id) {
// Limiter is within the same node
// Can calculate its latency
limiterStartObject["latency"] = parseInt(limiterEndElement.start) - parseInt(limiterStartElement.start);
}
else {
limiterStartObject["latency"] = parseInt(limiterStartParentNode.latency) - parseInt(limiterStartElement.start);
}
if (limiterStartObject.latency < 0)
limiterStartObject.latency = 0;
limiterStartParentNode.limiter_start_objects.push(limiterStartObject);
if (!limiterStartParentNode.limiter_start_objects_map_by_startpoint.hasOwnProperty(limiterStartElement.start))
limiterStartParentNode.limiter_start_objects_map_by_startpoint[limiterStartElement.start] = [];
limiterStartParentNode.limiter_start_objects_map_by_startpoint[limiterStartElement.start].push(limiterStartObject);
limiterEndParentNode.limiter_end_objects[limiterEndElement.id] = limiterEndObject;
// Sort limiter objects by partition_start value
sortArray(limiterStartParentNode.limiter_start_objects, "partition_start");
} | function addLimiterToLoopNodes(limiterParentNode, limiterStartParentNode, limiterEndParentNode, limiterStartElement, limiterEndElement, limitedRegionCapacity, checkPreviousIteration, thresholdDelay) {
if (checkPreviousIteration === undefined) {
checkPreviousIteration = false;
}
if (thresholdDelay === undefined) {
thresholdDelay = false;
}
// Sanity check that limiterElement's block parent == node
if (isComponentOrFunctionNode(limiterStartParentNode) || isComponentOrFunctionNode(limiterEndParentNode))
return;
if (!limiterStartParentNode.hasOwnProperty("limiter_start_objects")) {
limiterStartParentNode["limiter_start_objects"] = [];
limiterStartParentNode["limiter_start_objects_map_by_startpoint"] = {};
}
if (!limiterEndParentNode.hasOwnProperty("limiter_end_objects")) {
limiterEndParentNode["limiter_end_objects"] = {};
}
// doesLimiterExist finds a limiter that starts and ends at the exact same places, and updates the capacity to the lower between two options
// Returns true if a duplicate limiter is found/updated
if (doesLimiterExist(limiterStartParentNode, limiterEndParentNode, limiterStartElement, limiterEndElement, limitedRegionCapacity))
return;
let limiterStartObject = {};
let limiterEndObject = {};
limiterStartObject["is_limiter_start"] = true;
limiterStartObject['id'] = limiterStartElement.id;
limiterEndObject["is_limiter_start"] = false;
limiterEndObject['id'] = limiterEndElement.id;
limiterStartObject["limiter_parent_id"] = limiterParentNode.id;
limiterEndObject["limiter_parent_id"] = limiterParentNode.id;
limiterStartObject["check_prev_iter"] = checkPreviousIteration;
limiterEndObject["check_prev_iter"] = checkPreviousIteration;
limiterStartObject["threshold_delay"] = thresholdDelay;
limiterEndObject["threshold_delay"] = thresholdDelay;
// Limiter start needs to know the ID of the limiter end, to gather endpoint encounter data
limiterStartObject["limiter_end_node_id"] = limiterEndParentNode.id;
limiterStartObject["limiter_end_id"] = limiterEndElement.id; // To find the correct element in the limiter_end_objects hash
// Limiter end needs to know the ID of the limiter start, to see if there is a new start encounter it needs to address
limiterEndObject["limiter_start_node_id"] = limiterStartParentNode.id;
limiterEndObject["limiter_start_id"] = limiterStartElement.id; // To find the correct element in the limiter_end_objects hash
limiterStartObject["partition_start"] = limiterStartElement.start;
limiterEndObject["partition_start"] = limiterEndElement.start;
limiterStartObject["limited_region_capacity"] = limitedRegionCapacity;
limiterStartObject["limited_region_num_threads"] = 0; // Initialize to zero, every encounter of the limited region start should increment this
// Not sure if this is necessary:
// I don't love this name
limiterStartObject["partition_start_encounters"] = [];
limiterEndObject["partition_start_encounters"] = [];
if (limiterStartParentNode.id == limiterEndParentNode.id) {
// Limiter is within the same node
// Can calculate its latency
limiterStartObject["latency"] = parseInt(limiterEndElement.start) - parseInt(limiterStartElement.start);
}
else {
limiterStartObject["latency"] = parseInt(limiterStartParentNode.latency) - parseInt(limiterStartElement.start);
}
if (limiterStartObject.latency < 0)
limiterStartObject.latency = 0;
limiterStartParentNode.limiter_start_objects.push(limiterStartObject);
if (!limiterStartParentNode.limiter_start_objects_map_by_startpoint.hasOwnProperty(limiterStartElement.start))
limiterStartParentNode.limiter_start_objects_map_by_startpoint[limiterStartElement.start] = [];
limiterStartParentNode.limiter_start_objects_map_by_startpoint[limiterStartElement.start].push(limiterStartObject);
limiterEndParentNode.limiter_end_objects[limiterEndElement.id] = limiterEndObject;
// Sort limiter objects by partition_start value
sortArray(limiterStartParentNode.limiter_start_objects, "partition_start");
} |
JavaScript | function createLegacyLoopSpecMap() {
// The loopsJSON is structure like user loop hierarchy
let loopSpeculationDict = {};
let loopsToVisitQueue = [];
if (loopsJSON.hasOwnProperty('children')) {
// Top most children is the function
loopsJSON['children'].forEach(function (funcNode) {
if (funcNode.hasOwnProperty('children')) {
// Push all the highest level loop into the queue
funcNode['children'].forEach(function (loopNode) {
loopsToVisitQueue.push(loopNode);
});
}
});
while (loopsToVisitQueue.length > 0) {
let curLoop = loopsToVisitQueue.shift();
if (curLoop.data[0] !== "n/a") {
// Ignore non-real loop. Real loop would Pipeline is either "Yes" or "No"
loopSpeculationDict[curLoop.name] = curLoop.data[2];
}
if (curLoop.hasOwnProperty('children')) {
curLoop['children'].forEach(function (subloop) {
loopsToVisitQueue.push(subloop);
});
}
}
}
return loopSpeculationDict;
} | function createLegacyLoopSpecMap() {
// The loopsJSON is structure like user loop hierarchy
let loopSpeculationDict = {};
let loopsToVisitQueue = [];
if (loopsJSON.hasOwnProperty('children')) {
// Top most children is the function
loopsJSON['children'].forEach(function (funcNode) {
if (funcNode.hasOwnProperty('children')) {
// Push all the highest level loop into the queue
funcNode['children'].forEach(function (loopNode) {
loopsToVisitQueue.push(loopNode);
});
}
});
while (loopsToVisitQueue.length > 0) {
let curLoop = loopsToVisitQueue.shift();
if (curLoop.data[0] !== "n/a") {
// Ignore non-real loop. Real loop would Pipeline is either "Yes" or "No"
loopSpeculationDict[curLoop.name] = curLoop.data[2];
}
if (curLoop.hasOwnProperty('children')) {
curLoop['children'].forEach(function (subloop) {
loopsToVisitQueue.push(subloop);
});
}
}
}
return loopSpeculationDict;
} |
JavaScript | function reanalyzeLimiterStartObject(node, nodeCopy, predecessorEnd) {
// We have a map of limiter starts by startpoint
// Go in order
// For each startpoint, pick max between: all the starts at the startpoint, and <previous max start point> + <distance from that start point>
let previousMaxStartPoint = -1;
let previousMaxStartPartitionStart = -1;
Object.entries(node.limiter_start_objects_map_by_startpoint).forEach(function (limiterStartPointObjects) {
let partitionStart = limiterStartPointObjects[1][0].partition_start;
let maxEncounterPoint = -1;
for (let i = 0; i < limiterStartPointObjects[1].length; i++) {
let limiterStartObject = limiterStartPointObjects[1][i];
if (limiterStartPointObjects[1][i].check_prev_iter == true) {
limiterStartObject = nodeCopy.limiter_start_objects_copy[limiterStartObject.id];
}
let mostRecentStartObjectIndex = limiterStartObject.partition_start_encounters.length - 1;
if (mostRecentStartObjectIndex >= 0) {
let mostRecentStartObjectEncounter = limiterStartObject.partition_start_encounters[mostRecentStartObjectIndex];
maxEncounterPoint = Math.max(parseInt(maxEncounterPoint), parseInt(mostRecentStartObjectEncounter));
}
}
if (previousMaxStartPoint >= 0) {
let previousPointPlusDistance = parseInt(previousMaxStartPoint) + parseInt(partitionStart) - parseInt(previousMaxStartPartitionStart);
maxEncounterPoint = Math.max(parseInt(maxEncounterPoint), parseInt(previousPointPlusDistance));
}
if (partitionStart == 0) {
maxEncounterPoint = Math.max(parseInt(maxEncounterPoint), parseInt(predecessorEnd));
}
for (let i = 0; i < limiterStartPointObjects[1].length; i++) {
let mostRecentStartObjectIndex = limiterStartPointObjects[1][i].partition_start_encounters.length - 1;
if (mostRecentStartObjectIndex >= 0) {
limiterStartPointObjects[1][i].partition_start_encounters[mostRecentStartObjectIndex] = maxEncounterPoint;
}
}
previousMaxStartPoint = maxEncounterPoint;
previousMaxStartPartitionStart = partitionStart;
});
} | function reanalyzeLimiterStartObject(node, nodeCopy, predecessorEnd) {
// We have a map of limiter starts by startpoint
// Go in order
// For each startpoint, pick max between: all the starts at the startpoint, and <previous max start point> + <distance from that start point>
let previousMaxStartPoint = -1;
let previousMaxStartPartitionStart = -1;
Object.entries(node.limiter_start_objects_map_by_startpoint).forEach(function (limiterStartPointObjects) {
let partitionStart = limiterStartPointObjects[1][0].partition_start;
let maxEncounterPoint = -1;
for (let i = 0; i < limiterStartPointObjects[1].length; i++) {
let limiterStartObject = limiterStartPointObjects[1][i];
if (limiterStartPointObjects[1][i].check_prev_iter == true) {
limiterStartObject = nodeCopy.limiter_start_objects_copy[limiterStartObject.id];
}
let mostRecentStartObjectIndex = limiterStartObject.partition_start_encounters.length - 1;
if (mostRecentStartObjectIndex >= 0) {
let mostRecentStartObjectEncounter = limiterStartObject.partition_start_encounters[mostRecentStartObjectIndex];
maxEncounterPoint = Math.max(parseInt(maxEncounterPoint), parseInt(mostRecentStartObjectEncounter));
}
}
if (previousMaxStartPoint >= 0) {
let previousPointPlusDistance = parseInt(previousMaxStartPoint) + parseInt(partitionStart) - parseInt(previousMaxStartPartitionStart);
maxEncounterPoint = Math.max(parseInt(maxEncounterPoint), parseInt(previousPointPlusDistance));
}
if (partitionStart == 0) {
maxEncounterPoint = Math.max(parseInt(maxEncounterPoint), parseInt(predecessorEnd));
}
for (let i = 0; i < limiterStartPointObjects[1].length; i++) {
let mostRecentStartObjectIndex = limiterStartPointObjects[1][i].partition_start_encounters.length - 1;
if (mostRecentStartObjectIndex >= 0) {
limiterStartPointObjects[1][i].partition_start_encounters[mostRecentStartObjectIndex] = maxEncounterPoint;
}
}
previousMaxStartPoint = maxEncounterPoint;
previousMaxStartPartitionStart = partitionStart;
});
} |
JavaScript | function initializeTripCountTreeNode(ownLoopNode, tripCount, parentTCNode) {
if (parentTCNode === undefined) {
parentTCNode = {};
}
let tripCountNode = {};
tripCountNode["trip_count"] = tripCount;
tripCountNode['children'] = {};
tripCountNode['id'] = ownLoopNode.id;
// Checking if parentTCNode == {} or not, proceed if not
if (Object.entries(parentTCNode).length > 0) {
if (!parentTCNode['children'].hasOwnProperty(ownLoopNode.id))
parentTCNode['children'][ownLoopNode.id] = [];
parentTCNode['children'][ownLoopNode.id].push(tripCountNode);
}
if (!tripCountNodeMap.hasOwnProperty(ownLoopNode.id))
tripCountNodeMap[ownLoopNode.id] = [];
tripCountNodeMap[ownLoopNode.id].push(tripCountNode);
} | function initializeTripCountTreeNode(ownLoopNode, tripCount, parentTCNode) {
if (parentTCNode === undefined) {
parentTCNode = {};
}
let tripCountNode = {};
tripCountNode["trip_count"] = tripCount;
tripCountNode['children'] = {};
tripCountNode['id'] = ownLoopNode.id;
// Checking if parentTCNode == {} or not, proceed if not
if (Object.entries(parentTCNode).length > 0) {
if (!parentTCNode['children'].hasOwnProperty(ownLoopNode.id))
parentTCNode['children'][ownLoopNode.id] = [];
parentTCNode['children'][ownLoopNode.id].push(tripCountNode);
}
if (!tripCountNodeMap.hasOwnProperty(ownLoopNode.id))
tripCountNodeMap[ownLoopNode.id] = [];
tripCountNodeMap[ownLoopNode.id].push(tripCountNode);
} |
JavaScript | function fillupTripCountTreeNode(tripCountNode) {
if (Object.entries(tripCountNode['children']) == 0)
return;
let tripCount = tripCountNode.trip_count;
for (let childID in tripCountNode['children']) {
// For every subloop, make sure there are enough trip count nodes
if (parseInt(tripCountNode['children'][childID].length) < tripCount) {
let savedLength = tripCountNode['children'][childID].length;
let lastTCNode = tripCountNode['children'][childID][savedLength - 1];
for (let i = savedLength; i < tripCount; i++) {
tripCountNode['children'][childID].push(lastTCNode); // A bunch of references should be fine...?
}
}
else if (parseInt(tripCountNode['children'][childID].length) > tripCount) {
let savedLength = tripCountNode['children'][childID].length;
for (let i = tripCount; i < savedLength; i++) {
tripCountNode['children'][childID].pop(); // Remove last element
}
} // Do nothing if they're equal
}
for (let childID in tripCountNode['children']) {
for (let i = 0; i < tripCount; i++) {
fillupTripCountTreeNode(tripCountNode['children'][childID][i]);
}
}
} | function fillupTripCountTreeNode(tripCountNode) {
if (Object.entries(tripCountNode['children']) == 0)
return;
let tripCount = tripCountNode.trip_count;
for (let childID in tripCountNode['children']) {
// For every subloop, make sure there are enough trip count nodes
if (parseInt(tripCountNode['children'][childID].length) < tripCount) {
let savedLength = tripCountNode['children'][childID].length;
let lastTCNode = tripCountNode['children'][childID][savedLength - 1];
for (let i = savedLength; i < tripCount; i++) {
tripCountNode['children'][childID].push(lastTCNode); // A bunch of references should be fine...?
}
}
else if (parseInt(tripCountNode['children'][childID].length) > tripCount) {
let savedLength = tripCountNode['children'][childID].length;
for (let i = tripCount; i < savedLength; i++) {
tripCountNode['children'][childID].pop(); // Remove last element
}
} // Do nothing if they're equal
}
for (let childID in tripCountNode['children']) {
for (let i = 0; i < tripCount; i++) {
fillupTripCountTreeNode(tripCountNode['children'][childID][i]);
}
}
} |
JavaScript | function postProcessTripCountTree(outerMostLoopTCNodeArray) {
// For every outermost loop's TCNode:
for (let i = 0; i < outerMostLoopTCNodeArray.length; i++) {
let outerMostTCNode = outerMostLoopTCNodeArray[i];
// Fill up the trip count tree
fillupTripCountTreeNode(outerMostTCNode);
// Go through trip count tree, and populate data in loop nodes
updateLoopNodeTripCounts(outerMostTCNode);
}
} | function postProcessTripCountTree(outerMostLoopTCNodeArray) {
// For every outermost loop's TCNode:
for (let i = 0; i < outerMostLoopTCNodeArray.length; i++) {
let outerMostTCNode = outerMostLoopTCNodeArray[i];
// Fill up the trip count tree
fillupTripCountTreeNode(outerMostTCNode);
// Go through trip count tree, and populate data in loop nodes
updateLoopNodeTripCounts(outerMostTCNode);
}
} |
JavaScript | function initializeTripCounts(loopNodeIDTripCountPairs) {
tripCountNodeMap = {};
let outerMostLoopTCNodeArray = [];
let loopNodesToAnalyze = [];
for (let i = 0; i < loopNodeIDTripCountPairs.length; i++) {
let loopNodeIDTripCountPair = loopNodeIDTripCountPairs[i];
let newLoopNodeTripCountPair = {};
newLoopNodeTripCountPair["loop_node"] = getNodeFromArray(loopNodeIDTripCountPair.loop_node_id, loopDataNodes);
newLoopNodeTripCountPair["trip_count"] = loopNodeIDTripCountPair.trip_count;
loopNodesToAnalyze.push(newLoopNodeTripCountPair);
}
if (loopNodesToAnalyze.length == 0)
loopNodesToAnalyze = loopDataNodes;
// For every provided trip count (initialize to 1 for each)
for (let i = 0; i < loopNodesToAnalyze.length; i++) {
let loopNodeObj = loopNodesToAnalyze[i];
let loopNode = {};
let tripCount = 1; // initialize all loops to trip count 1 if not known
if (loopNodeObj.hasOwnProperty("loop_node") && loopNodeObj.hasOwnProperty("trip_count")) {
loopNode = loopNodeObj.loop_node;
tripCount = loopNodeObj.trip_count;
}
else {
loopNode = loopNodeObj;
let loopNodeTripCount = parseInt(loopNode.tc);
if ((isNaN(loopNodeTripCount) || loopNodeTripCount <= 0) &&
(loopNode.hasOwnProperty('children') && loopNode['children'].length > 1)) {
let loopLatch = getNodeFromArray(loopNode['children'][loopNode['children'].length - 1], loopDataNodes);
loopNodeTripCount = parseInt(loopLatch.tc);
loopNode.tc = loopLatch.tc;
}
if (!isNaN(loopNodeTripCount) && loopNodeTripCount > 0) {
tripCount = loopNodeTripCount;
}
}
// Convert "threshold_no_delay" flag from Loop Attributes to bool, and invert
loopNode["threshold_delay"] = loopNode.tn == "0" ? 1 : 0;
if (loopNode.type != "loop")
continue;
console.log("Initializing Trip Count: " + loopNode.name + ", trip count = " + tripCount);
if (loopNode.ll == 1) {
// Outermost loop, no parent TC node
initializeTripCountTreeNode(loopNode, tripCount);
outerMostLoopTCNodeArray.push(tripCountNodeMap[loopNode.id][0]); // The TCNode that was just created
}
else { // parentTCNode can be fetched using tripCountNodeMap[parentID].last
initializeTripCountTreeNode(loopNode, tripCount, tripCountNodeMap[loopNode.parent_id][tripCountNodeMap[loopNode.parent_id].length - 1]);
}
}
postProcessTripCountTree(outerMostLoopTCNodeArray);
} | function initializeTripCounts(loopNodeIDTripCountPairs) {
tripCountNodeMap = {};
let outerMostLoopTCNodeArray = [];
let loopNodesToAnalyze = [];
for (let i = 0; i < loopNodeIDTripCountPairs.length; i++) {
let loopNodeIDTripCountPair = loopNodeIDTripCountPairs[i];
let newLoopNodeTripCountPair = {};
newLoopNodeTripCountPair["loop_node"] = getNodeFromArray(loopNodeIDTripCountPair.loop_node_id, loopDataNodes);
newLoopNodeTripCountPair["trip_count"] = loopNodeIDTripCountPair.trip_count;
loopNodesToAnalyze.push(newLoopNodeTripCountPair);
}
if (loopNodesToAnalyze.length == 0)
loopNodesToAnalyze = loopDataNodes;
// For every provided trip count (initialize to 1 for each)
for (let i = 0; i < loopNodesToAnalyze.length; i++) {
let loopNodeObj = loopNodesToAnalyze[i];
let loopNode = {};
let tripCount = 1; // initialize all loops to trip count 1 if not known
if (loopNodeObj.hasOwnProperty("loop_node") && loopNodeObj.hasOwnProperty("trip_count")) {
loopNode = loopNodeObj.loop_node;
tripCount = loopNodeObj.trip_count;
}
else {
loopNode = loopNodeObj;
let loopNodeTripCount = parseInt(loopNode.tc);
if ((isNaN(loopNodeTripCount) || loopNodeTripCount <= 0) &&
(loopNode.hasOwnProperty('children') && loopNode['children'].length > 1)) {
let loopLatch = getNodeFromArray(loopNode['children'][loopNode['children'].length - 1], loopDataNodes);
loopNodeTripCount = parseInt(loopLatch.tc);
loopNode.tc = loopLatch.tc;
}
if (!isNaN(loopNodeTripCount) && loopNodeTripCount > 0) {
tripCount = loopNodeTripCount;
}
}
// Convert "threshold_no_delay" flag from Loop Attributes to bool, and invert
loopNode["threshold_delay"] = loopNode.tn == "0" ? 1 : 0;
if (loopNode.type != "loop")
continue;
console.log("Initializing Trip Count: " + loopNode.name + ", trip count = " + tripCount);
if (loopNode.ll == 1) {
// Outermost loop, no parent TC node
initializeTripCountTreeNode(loopNode, tripCount);
outerMostLoopTCNodeArray.push(tripCountNodeMap[loopNode.id][0]); // The TCNode that was just created
}
else { // parentTCNode can be fetched using tripCountNodeMap[parentID].last
initializeTripCountTreeNode(loopNode, tripCount, tripCountNodeMap[loopNode.parent_id][tripCountNodeMap[loopNode.parent_id].length - 1]);
}
}
postProcessTripCountTree(outerMostLoopTCNodeArray);
} |
JavaScript | function buildFPGASummaryInfo() {
// call this at the beginning before the whole document is loaded to save time
isValidInfo = (typeof infoJSON != "undefined") && (infoJSON = tryParseJSON(infoJSON)) !== null && !$.isEmptyObject(infoJSON);
// Error out and documnet to user to recompile
if (!isValidInfo || !infoJSON.hasOwnProperty('compileInfo') || !infoJSON['compileInfo'].hasOwnProperty('nodes') ||
!Array.isArray(infoJSON['compileInfo']['nodes']) || infoJSON['compileInfo']['nodes'].length == 0 || !infoJSON['compileInfo']['nodes'][0].hasOwnProperty('product')) {
VIEWS.SUMMARY.valid = true;
VIEWS.SUMMARY.source = ' Report is invalid!';
var report = REPORT_PANE_HTML;
report += VIEWS.SUMMARY.name + "</div><div class='card-body report-body' onscroll='adjustToWindowEvent()'>";
report += "<div id='area-table-content'></div>";
$("#report-pane")[0].insertAdjacentHTML("beforeend", "<div id=\"report-pane-view" + VIEWS.SUMMARY.value + "\" class=\"report-pane-view-style\"></div>");
report += "</div></div></div>";
$('#report-pane-view' + VIEWS.SUMMARY.value).html(report);
$('#report-pane-view' + VIEWS.SUMMARY.value + ' #area-table-content').html(VIEWS.SUMMARY.source);
return;
}
;
let infoData = infoJSON['compileInfo']['nodes'][0];
setTitle(); // Set page title
product = PRODUCTS[infoData['product']]; // fall back in case compiler did not ouptut it
function_prefix = (product == PRODUCTS.HLS) ? 'Function' : // HLS
'Kernel'; // OpenCL or SYCL
// Populate the info first into a card
summaryElement = document.createElement('div');
summaryElement.id = "accordion";
summaryElement.setAttribute('role', 'tablist');
var compileInfo = new FPGACompileInfo(summaryElement, product);
compileInfo.draw(true);
let summaryTree = new FPGASummaryTree(document.getElementById('tree-list'));
summaryTree.appendChild(compileInfo.getName(), compileInfo.getID());
VIEWS.SUMMARY['tree'] = summaryTree; // add a new object to the SUMMARY VIEW
// Sets the title of the html and returns the product value
function setTitle() {
title = infoData['name'];
$('#titleText').html('Report: ' + title);
}
} | function buildFPGASummaryInfo() {
// call this at the beginning before the whole document is loaded to save time
isValidInfo = (typeof infoJSON != "undefined") && (infoJSON = tryParseJSON(infoJSON)) !== null && !$.isEmptyObject(infoJSON);
// Error out and documnet to user to recompile
if (!isValidInfo || !infoJSON.hasOwnProperty('compileInfo') || !infoJSON['compileInfo'].hasOwnProperty('nodes') ||
!Array.isArray(infoJSON['compileInfo']['nodes']) || infoJSON['compileInfo']['nodes'].length == 0 || !infoJSON['compileInfo']['nodes'][0].hasOwnProperty('product')) {
VIEWS.SUMMARY.valid = true;
VIEWS.SUMMARY.source = ' Report is invalid!';
var report = REPORT_PANE_HTML;
report += VIEWS.SUMMARY.name + "</div><div class='card-body report-body' onscroll='adjustToWindowEvent()'>";
report += "<div id='area-table-content'></div>";
$("#report-pane")[0].insertAdjacentHTML("beforeend", "<div id=\"report-pane-view" + VIEWS.SUMMARY.value + "\" class=\"report-pane-view-style\"></div>");
report += "</div></div></div>";
$('#report-pane-view' + VIEWS.SUMMARY.value).html(report);
$('#report-pane-view' + VIEWS.SUMMARY.value + ' #area-table-content').html(VIEWS.SUMMARY.source);
return;
}
;
let infoData = infoJSON['compileInfo']['nodes'][0];
setTitle(); // Set page title
product = PRODUCTS[infoData['product']]; // fall back in case compiler did not ouptut it
function_prefix = (product == PRODUCTS.HLS) ? 'Function' : // HLS
'Kernel'; // OpenCL or SYCL
// Populate the info first into a card
summaryElement = document.createElement('div');
summaryElement.id = "accordion";
summaryElement.setAttribute('role', 'tablist');
var compileInfo = new FPGACompileInfo(summaryElement, product);
compileInfo.draw(true);
let summaryTree = new FPGASummaryTree(document.getElementById('tree-list'));
summaryTree.appendChild(compileInfo.getName(), compileInfo.getID());
VIEWS.SUMMARY['tree'] = summaryTree; // add a new object to the SUMMARY VIEW
// Sets the title of the html and returns the product value
function setTitle() {
title = infoData['name'];
$('#titleText').html('Report: ' + title);
}
} |
JavaScript | function generateTablesHTML() {
// Populate all the table data: area, summary, loops, fmax/II, verification
// Sets a valid flag in the VIEW
if (VIEWS.hasOwnProperty("AREA_SYS") && VIEWS.AREA_SYS.valid) {
VIEWS.AREA_SYS.source = parseAreaData(areaJSON);
}
if (VIEWS.hasOwnProperty("AREA_SRC") && VIEWS.AREA_SRC.valid) {
VIEWS.AREA_SRC.source = parseAreaData(area_srcJSON);
}
// Two cases: compile (full or -rtl) or Quartus only
if (VIEWS.hasOwnProperty("SUMMARY")) {
let quartusClockSummary = null;
let systemResUtilSumamry = null; // OpenCL and SYCL only because they have BSP
let quartusResUtilSummary = null;
let resourceUtilSummary = null;
let functionSummary = null;
let kernelSummary = null;
let warningSummary = null;
if (VIEWS.SUMMARY.valid)
warningSummary = new FPGAWarningSummary(summaryElement);
if (isValidQuartus && VIEWS.SUMMARY.valid) {
// Display full summary
quartusClockSummary = new FPGAClockFreqSummary(summaryElement, product);
if (product === PRODUCTS.HLS) {
functionSummary = new FPGAFunctionSummary(summaryElement);
}
else { // OpenCL or SYCL
kernelSummary = new FPGAKernelSummary(summaryElement);
systemResUtilSumamry = new FPGAOpenCLResourceSummary(summaryElement, product);
}
quartusResUtilSummary = new FPGAQuartusResourceSummary(summaryElement, product);
resourceUtilSummary = new FPGAResourceEstSummary(summaryElement, product);
}
else if (isValidQuartus) {
// Quartus data and Summary have to be valid at a minimum, but data can be empty
quartusClockSummary = new FPGAClockFreqSummary(summaryElement, product);
quartusResUtilSummary = new FPGAQuartusResourceSummary(summaryElement, product);
}
// Create table of content for summary
let summaryTree = VIEWS.SUMMARY['tree'];
if (functionSummary !== null) {
functionSummary.draw(true);
summaryTree.appendChild(functionSummary.getName(), functionSummary.getID());
}
if (kernelSummary !== null) {
kernelSummary.draw(true);
summaryTree.appendChild(kernelSummary.getName(), kernelSummary.getID());
}
if (quartusClockSummary !== null) {
quartusClockSummary.draw(false);
summaryTree.appendChild(quartusClockSummary.getName(), quartusClockSummary.getID());
}
if (systemResUtilSumamry !== null) {
systemResUtilSumamry.draw(false);
summaryTree.appendChild(systemResUtilSumamry.getName(), systemResUtilSumamry.getID());
}
if (quartusResUtilSummary !== null) {
quartusResUtilSummary.draw(false);
summaryTree.appendChild(quartusResUtilSummary.getName(), quartusResUtilSummary.getID());
}
if (resourceUtilSummary !== null) {
resourceUtilSummary.draw(false);
summaryTree.appendChild(resourceUtilSummary.getName(), resourceUtilSummary.getID());
}
if (warningSummary !== null) {
warningSummary.draw(false);
summaryTree.appendChild(warningSummary.getName(), warningSummary.getID());
}
VIEWS.SUMMARY.source = summaryElement.outerHTML;
}
if (VIEWS.hasOwnProperty('VERIF') && VIEWS.VERIF.valid) {
VIEWS.VERIF.source = parseVerifData(verifJSON);
}
if ((VIEWS.hasOwnProperty('INCREMENTAL') && VIEWS.INCREMENTAL.valid)) {
VIEWS.INCREMENTAL.source = parseIncrementalData(incrementalJSON);
}
} | function generateTablesHTML() {
// Populate all the table data: area, summary, loops, fmax/II, verification
// Sets a valid flag in the VIEW
if (VIEWS.hasOwnProperty("AREA_SYS") && VIEWS.AREA_SYS.valid) {
VIEWS.AREA_SYS.source = parseAreaData(areaJSON);
}
if (VIEWS.hasOwnProperty("AREA_SRC") && VIEWS.AREA_SRC.valid) {
VIEWS.AREA_SRC.source = parseAreaData(area_srcJSON);
}
// Two cases: compile (full or -rtl) or Quartus only
if (VIEWS.hasOwnProperty("SUMMARY")) {
let quartusClockSummary = null;
let systemResUtilSumamry = null; // OpenCL and SYCL only because they have BSP
let quartusResUtilSummary = null;
let resourceUtilSummary = null;
let functionSummary = null;
let kernelSummary = null;
let warningSummary = null;
if (VIEWS.SUMMARY.valid)
warningSummary = new FPGAWarningSummary(summaryElement);
if (isValidQuartus && VIEWS.SUMMARY.valid) {
// Display full summary
quartusClockSummary = new FPGAClockFreqSummary(summaryElement, product);
if (product === PRODUCTS.HLS) {
functionSummary = new FPGAFunctionSummary(summaryElement);
}
else { // OpenCL or SYCL
kernelSummary = new FPGAKernelSummary(summaryElement);
systemResUtilSumamry = new FPGAOpenCLResourceSummary(summaryElement, product);
}
quartusResUtilSummary = new FPGAQuartusResourceSummary(summaryElement, product);
resourceUtilSummary = new FPGAResourceEstSummary(summaryElement, product);
}
else if (isValidQuartus) {
// Quartus data and Summary have to be valid at a minimum, but data can be empty
quartusClockSummary = new FPGAClockFreqSummary(summaryElement, product);
quartusResUtilSummary = new FPGAQuartusResourceSummary(summaryElement, product);
}
// Create table of content for summary
let summaryTree = VIEWS.SUMMARY['tree'];
if (functionSummary !== null) {
functionSummary.draw(true);
summaryTree.appendChild(functionSummary.getName(), functionSummary.getID());
}
if (kernelSummary !== null) {
kernelSummary.draw(true);
summaryTree.appendChild(kernelSummary.getName(), kernelSummary.getID());
}
if (quartusClockSummary !== null) {
quartusClockSummary.draw(false);
summaryTree.appendChild(quartusClockSummary.getName(), quartusClockSummary.getID());
}
if (systemResUtilSumamry !== null) {
systemResUtilSumamry.draw(false);
summaryTree.appendChild(systemResUtilSumamry.getName(), systemResUtilSumamry.getID());
}
if (quartusResUtilSummary !== null) {
quartusResUtilSummary.draw(false);
summaryTree.appendChild(quartusResUtilSummary.getName(), quartusResUtilSummary.getID());
}
if (resourceUtilSummary !== null) {
resourceUtilSummary.draw(false);
summaryTree.appendChild(resourceUtilSummary.getName(), resourceUtilSummary.getID());
}
if (warningSummary !== null) {
warningSummary.draw(false);
summaryTree.appendChild(warningSummary.getName(), warningSummary.getID());
}
VIEWS.SUMMARY.source = summaryElement.outerHTML;
}
if (VIEWS.hasOwnProperty('VERIF') && VIEWS.VERIF.valid) {
VIEWS.VERIF.source = parseVerifData(verifJSON);
}
if ((VIEWS.hasOwnProperty('INCREMENTAL') && VIEWS.INCREMENTAL.valid)) {
VIEWS.INCREMENTAL.source = parseIncrementalData(incrementalJSON);
}
} |
JavaScript | function initializeControlMenu() {
Object.keys(CTRLS).forEach(function (c) {
// don't create controls for source in menu if no file list
if (c === 'SOURCE' && !isValidFileList)
return;
let vTmpDiv = newFPGAElement(document.getElementById('collapse-ctrl'), 'button', 'btn btn-secondary-outline', CTRLS[c].id, '');
vTmpDiv.setAttribute('type', 'button');
vTmpDiv.href = '#';
vTmpDiv.style.backgroundColor = 'white';
// tooltip
vTmpDiv.setAttribute('data-toggle', 'tooltip');
vTmpDiv.setAttribute('data-html', 'true');
vTmpDiv.setAttribute('data-placement', 'bottom');
let toolTipHtml = lookUpTerminology(c, false);
if (toolTipHtml !== '') {
vTmpDiv.title = toolTipHtml;
}
if (CTRLS[c].hasOwnProperty('callback'))
vTmpDiv.addEventListener('click', CTRLS[c].callback);
vTmpDiv = newFPGAElement(vTmpDiv, 'span', 'body glyphicon', CTRLS[c].id + 'Text', CTRLS[c].name);
vTmpDiv.style.color = '#007bff';
// Also add to close button in card
if (c === 'SOURCE')
document.getElementById('close-source').addEventListener('click', CTRLS[c].callback);
else if (c === 'DETAILS')
document.getElementById('close-details').addEventListener('click', CTRLS[c].callback);
});
} | function initializeControlMenu() {
Object.keys(CTRLS).forEach(function (c) {
// don't create controls for source in menu if no file list
if (c === 'SOURCE' && !isValidFileList)
return;
let vTmpDiv = newFPGAElement(document.getElementById('collapse-ctrl'), 'button', 'btn btn-secondary-outline', CTRLS[c].id, '');
vTmpDiv.setAttribute('type', 'button');
vTmpDiv.href = '#';
vTmpDiv.style.backgroundColor = 'white';
// tooltip
vTmpDiv.setAttribute('data-toggle', 'tooltip');
vTmpDiv.setAttribute('data-html', 'true');
vTmpDiv.setAttribute('data-placement', 'bottom');
let toolTipHtml = lookUpTerminology(c, false);
if (toolTipHtml !== '') {
vTmpDiv.title = toolTipHtml;
}
if (CTRLS[c].hasOwnProperty('callback'))
vTmpDiv.addEventListener('click', CTRLS[c].callback);
vTmpDiv = newFPGAElement(vTmpDiv, 'span', 'body glyphicon', CTRLS[c].id + 'Text', CTRLS[c].name);
vTmpDiv.style.color = '#007bff';
// Also add to close button in card
if (c === 'SOURCE')
document.getElementById('close-source').addEventListener('click', CTRLS[c].callback);
else if (c === 'DETAILS')
document.getElementById('close-details').addEventListener('click', CTRLS[c].callback);
});
} |
JavaScript | function initializeNavBar() {
// create a div for each view, and set it to "hidden"; also create
// a menu entry for each view
Object.keys(MENU).forEach(function (m) {
var views = MENU[m];
if (views.hidden !== undefined && !show_hidden)
return;
if (views.view !== undefined) {
// no submenu, the menu is the view
let v = MENU[m].view;
// TODO: Factor these out to initializeViews to allow unittest initializeNavBar
let index = VIEWS[v];
viewHash[index.hash] = v;
addReportColumn(index);
let navButton = document.createElement('a');
navButton.setAttribute('role', 'button');
navButton.innerHTML = index.name;
navButton.setAttribute('data-toggle', 'tooltip');
navButton.setAttribute('data-html', 'true');
navButton.setAttribute('data-placement', 'right');
if (index.valid) {
navButton.className = 'btn btn-outline-primary';
navButton.href = index.hash;
}
else {
navButton.className = 'btn btn-outline-primary disable';
}
// Add tooltip if exist
let toolTipHtml = lookUpTerminology(v, !index.valid);
if (toolTipHtml !== '') {
navButton.title = toolTipHtml;
}
$('#main-menu').append(navButton);
}
else {
// has submenu, add the menu as dropdown
let navDropDownGroup = document.createElement('div');
navDropDownGroup.className = 'dropdown';
let navButton = document.createElement('button');
navButton.className = 'btn btn-outline-primary dropdown-toggle';
navButton.type = 'button';
navButton.setAttribute('data-toggle', 'dropdown');
navButton.innerHTML = views.name;
navDropDownGroup.appendChild(navButton);
let navDropDown = document.createElement('div');
navDropDown.className = 'dropdown-menu';
Object.keys(views.submenu).forEach(function (vkey) {
let v = views.submenu[vkey];
if (v === 'divider') {
let separatorElement = document.createElement('div');
separatorElement.className = 'dropdown-divider';
navDropDown.appendChild(separatorElement);
}
else if (VIEWS[v] !== undefined) {
// Don't add removed views
let index = VIEWS[v];
if (index.name === undefined || index.name === '') {
console.warn('Error! VIEW ' + v + ' has no name.');
return;
}
viewHash[index.hash] = v;
if (index.valid) {
addReportColumn(index);
} // Temporary workaround for incremental since it parses JSON in addReportColumn
let dropDownItem = document.createElement('a');
dropDownItem.id = v;
dropDownItem.innerHTML = index.name;
dropDownItem.setAttribute('data-toggle', 'tooltip');
dropDownItem.setAttribute('data-html', 'true');
dropDownItem.setAttribute('data-placement', 'right');
if (index.valid) {
dropDownItem.className = 'dropdown-item';
dropDownItem.href = index.hash;
}
else {
dropDownItem.className = 'dropdown-item disabled';
dropDownItem.href = '#';
}
let toolTipHtml = lookUpTerminology(v, !index.valid);
if (toolTipHtml !== "") {
dropDownItem.title = toolTipHtml;
}
navDropDown.appendChild(dropDownItem);
}
});
navDropDownGroup.appendChild(navDropDown);
$('#main-menu').append(navDropDownGroup);
}
});
// display the current view
currentPane = '#report-pane-view' + view.value;
$(currentPane).toggle();
} | function initializeNavBar() {
// create a div for each view, and set it to "hidden"; also create
// a menu entry for each view
Object.keys(MENU).forEach(function (m) {
var views = MENU[m];
if (views.hidden !== undefined && !show_hidden)
return;
if (views.view !== undefined) {
// no submenu, the menu is the view
let v = MENU[m].view;
// TODO: Factor these out to initializeViews to allow unittest initializeNavBar
let index = VIEWS[v];
viewHash[index.hash] = v;
addReportColumn(index);
let navButton = document.createElement('a');
navButton.setAttribute('role', 'button');
navButton.innerHTML = index.name;
navButton.setAttribute('data-toggle', 'tooltip');
navButton.setAttribute('data-html', 'true');
navButton.setAttribute('data-placement', 'right');
if (index.valid) {
navButton.className = 'btn btn-outline-primary';
navButton.href = index.hash;
}
else {
navButton.className = 'btn btn-outline-primary disable';
}
// Add tooltip if exist
let toolTipHtml = lookUpTerminology(v, !index.valid);
if (toolTipHtml !== '') {
navButton.title = toolTipHtml;
}
$('#main-menu').append(navButton);
}
else {
// has submenu, add the menu as dropdown
let navDropDownGroup = document.createElement('div');
navDropDownGroup.className = 'dropdown';
let navButton = document.createElement('button');
navButton.className = 'btn btn-outline-primary dropdown-toggle';
navButton.type = 'button';
navButton.setAttribute('data-toggle', 'dropdown');
navButton.innerHTML = views.name;
navDropDownGroup.appendChild(navButton);
let navDropDown = document.createElement('div');
navDropDown.className = 'dropdown-menu';
Object.keys(views.submenu).forEach(function (vkey) {
let v = views.submenu[vkey];
if (v === 'divider') {
let separatorElement = document.createElement('div');
separatorElement.className = 'dropdown-divider';
navDropDown.appendChild(separatorElement);
}
else if (VIEWS[v] !== undefined) {
// Don't add removed views
let index = VIEWS[v];
if (index.name === undefined || index.name === '') {
console.warn('Error! VIEW ' + v + ' has no name.');
return;
}
viewHash[index.hash] = v;
if (index.valid) {
addReportColumn(index);
} // Temporary workaround for incremental since it parses JSON in addReportColumn
let dropDownItem = document.createElement('a');
dropDownItem.id = v;
dropDownItem.innerHTML = index.name;
dropDownItem.setAttribute('data-toggle', 'tooltip');
dropDownItem.setAttribute('data-html', 'true');
dropDownItem.setAttribute('data-placement', 'right');
if (index.valid) {
dropDownItem.className = 'dropdown-item';
dropDownItem.href = index.hash;
}
else {
dropDownItem.className = 'dropdown-item disabled';
dropDownItem.href = '#';
}
let toolTipHtml = lookUpTerminology(v, !index.valid);
if (toolTipHtml !== "") {
dropDownItem.title = toolTipHtml;
}
navDropDown.appendChild(dropDownItem);
}
});
navDropDownGroup.appendChild(navDropDown);
$('#main-menu').append(navDropDownGroup);
}
});
// display the current view
currentPane = '#report-pane-view' + view.value;
$(currentPane).toggle();
} |
JavaScript | function disableInvalidViews() {
Object.keys(VIEWS).forEach(function (v) {
var sel_view = VIEWS[v];
if (sel_view.product != PRODUCTS.ALL && (product === undefined || sel_view.product != product)) {
// view doesn't belong to this product
delete VIEWS[v];
return;
}
if (!sel_view.valid) {
// view is disabled because JSON is invalid
return;
}
// add clickDown and source fields for parsing the JSON data later
sel_view.clickDown = null;
sel_view.source = null;
// Prepend 'Kernel' or 'Component' for different views depending on product
sel_view.name = sel_view.name.replace(PREFIX_PAD, function_prefix);
});
} | function disableInvalidViews() {
Object.keys(VIEWS).forEach(function (v) {
var sel_view = VIEWS[v];
if (sel_view.product != PRODUCTS.ALL && (product === undefined || sel_view.product != product)) {
// view doesn't belong to this product
delete VIEWS[v];
return;
}
if (!sel_view.valid) {
// view is disabled because JSON is invalid
return;
}
// add clickDown and source fields for parsing the JSON data later
sel_view.clickDown = null;
sel_view.source = null;
// Prepend 'Kernel' or 'Component' for different views depending on product
sel_view.name = sel_view.name.replace(PREFIX_PAD, function_prefix);
});
} |
JavaScript | function addReportColumn(reportEnum) {
var report = REPORT_PANE_HTML;
if (reportEnum != VIEWS.GV && reportEnum != VIEWS.LMEM && reportEnum != VIEWS.SCHEDULE && reportEnum != VIEWS.LOOPVIS) {
// Temporary workaround until tables are refactored
$("#report-pane")[0].insertAdjacentHTML("beforeend", "<div id=\"report-pane-view" + reportEnum.value + "\" class=\"report-pane-view-style\"></div>");
$('#report-pane-view' + reportEnum.value).toggle();
}
// bottleneck tree is global to every view
if (vBottleneckTree === undefined) {
vBottleneckTree = new FPGABottleneckTree(document.getElementById('outline-list'));
}
let reportPane, reportBody, reportView;
switch (reportEnum) {
case VIEWS.SUMMARY:
report += reportEnum.name + "</div><div class='card-body report-body' id='report-summary' onscroll='adjustToWindowEvent()'>";
report += "<div id='area-table-content'></div>";
break;
case VIEWS.LOOP:
var vLoopTree = new FPGALoopTree(document.getElementById('tree-list')); // Draw until in the loops view
reportEnum['tree'] = vLoopTree;
return;
case VIEWS.VERIF:
report += reportEnum.name + "</div><div class='card-body report-body' onscroll='adjustToWindowEvent()'>";
report += "<table class='table table-hover areatable' id='area-table-content'></table>";
break;
case VIEWS.AREA_SYS:
reportEnum['tree'] = new FPGAAreaTree(document.getElementById('tree-list')); // Draw until in the loops view
case VIEWS.AREA_SRC:
report += "<table style='width:100%' class='areatable'><tr><td class='panel-heading-text'>";
report += "<span style='font-size:1rem;'>" + reportEnum.name + "</span>";
report += "<br>(area utilization values are estimated)<br>Notation <i>file:X</i> > <i>file:Y</i> indicates a function call on line X was inlined using code on line Y.";
if (VIEWS.AREA_SYS.valid && VIEWS.hasOwnProperty("INCREMENTAL") && VIEWS.INCREMENTAL.valid) {
report += '<br><strong>Note: Area report accuracy may be reduced when performing an incremental compile.</strong>';
}
if (VIEWS.AREA_SYS.valid && !areaJSON.debug_enabled) {
report += '<br><strong>Recompile without <tt>-g0</tt> for detailed area breakdown by source line.</strong>';
}
report += '</td><td>';
report += "<span style='font-size:1rem;float:right'>";
report += "<button id='collapseAll' type='button' class='text-left exp-col-btn'><span class='body glyphicon'></span> Collapse All </button>";
report += "<button id='expandAll' type='button' class='text-left exp-col-btn'><span class='body glyphicon'></span> Expand All </button>";
report += '</span>';
report += '</td></tr></table>';
report += "</div><div class='card-body report-body' id='report-area' onscroll='adjustToWindowEvent()'>";
report += "<table class='table table-hover areatable' id='area-table-content'></table>";
break;
case VIEWS.INCREMENTAL:
if (incrementalJSON.hasOwnProperty('name')) { // This needs to be refactor. Should not be parsing JSON here
report += incrementalJSON.name;
}
else {
report += reportEnum.name;
}
if (incrementalJSON.hasOwnProperty('details')) {
report += '<hr/>';
incrementalJSON.details.forEach(function (d) {
report += '<li>' + d.text + '</li>';
});
}
report += '</div>';
report += "<div class='card-body report-body' onscroll='adjustToWindowEvent()'>";
report += "<table class='table table-hover areatable' id='area-table-content'></table>";
break;
case VIEWS.LMEM:
reportView = document.createElement('div');
reportView.id = 'report-pane-view' + reportEnum.value;
reportView.className = 'report-pane-view-style';
reportBody = addViewerPanel(reportEnum, 'layers-lmem', 'LMEMG');
reportView.appendChild(reportBody);
reportPane = document.getElementById('report-pane');
reportPane.appendChild(reportView);
$('#report-pane-view' + reportEnum.value).toggle();
return;
case VIEWS.GV:
reportView = document.createElement('div');
reportView.id = 'report-pane-view' + reportEnum.value;
reportView.className = 'report-pane-view-style';
reportBody = addViewerPanel(reportEnum, 'layers', 'GVG');
reportView.appendChild(reportBody);
reportPane = document.getElementById('report-pane');
reportPane.appendChild(reportView);
$('#report-pane-view' + reportEnum.value).toggle();
return;
case VIEWS.SCHEDULE:
reportView = document.createElement('div');
reportView.id = 'report-pane-view' + reportEnum.value;
reportView.className = 'report-pane-view-style';
reportBody = addViewerPanel(reportEnum, 'layers', 'SVCBeta');
reportView.appendChild(reportBody);
reportPane = document.getElementById('report-pane');
reportPane.appendChild(reportView);
$('#report-pane-view' + reportEnum.value).toggle();
return;
case VIEWS.LOOPVIS:
reportView = document.createElement('div');
reportView.id = 'report-pane-view' + reportEnum.value;
reportView.className = 'report-pane-view-style';
reportBody = addViewerPanel(reportEnum, 'layers', 'LVAlpha');
reportView.appendChild(reportBody);
reportPane = document.getElementById('report-pane');
reportPane.appendChild(reportView);
$('#report-pane-view' + reportEnum.value).toggle();
return;
}
report += '</div></div></div>';
$('#report-pane-view' + reportEnum.value).html(report);
$('#report-pane-view' + reportEnum.value + ' #area-table-content').html(reportEnum.source);
} | function addReportColumn(reportEnum) {
var report = REPORT_PANE_HTML;
if (reportEnum != VIEWS.GV && reportEnum != VIEWS.LMEM && reportEnum != VIEWS.SCHEDULE && reportEnum != VIEWS.LOOPVIS) {
// Temporary workaround until tables are refactored
$("#report-pane")[0].insertAdjacentHTML("beforeend", "<div id=\"report-pane-view" + reportEnum.value + "\" class=\"report-pane-view-style\"></div>");
$('#report-pane-view' + reportEnum.value).toggle();
}
// bottleneck tree is global to every view
if (vBottleneckTree === undefined) {
vBottleneckTree = new FPGABottleneckTree(document.getElementById('outline-list'));
}
let reportPane, reportBody, reportView;
switch (reportEnum) {
case VIEWS.SUMMARY:
report += reportEnum.name + "</div><div class='card-body report-body' id='report-summary' onscroll='adjustToWindowEvent()'>";
report += "<div id='area-table-content'></div>";
break;
case VIEWS.LOOP:
var vLoopTree = new FPGALoopTree(document.getElementById('tree-list')); // Draw until in the loops view
reportEnum['tree'] = vLoopTree;
return;
case VIEWS.VERIF:
report += reportEnum.name + "</div><div class='card-body report-body' onscroll='adjustToWindowEvent()'>";
report += "<table class='table table-hover areatable' id='area-table-content'></table>";
break;
case VIEWS.AREA_SYS:
reportEnum['tree'] = new FPGAAreaTree(document.getElementById('tree-list')); // Draw until in the loops view
case VIEWS.AREA_SRC:
report += "<table style='width:100%' class='areatable'><tr><td class='panel-heading-text'>";
report += "<span style='font-size:1rem;'>" + reportEnum.name + "</span>";
report += "<br>(area utilization values are estimated)<br>Notation <i>file:X</i> > <i>file:Y</i> indicates a function call on line X was inlined using code on line Y.";
if (VIEWS.AREA_SYS.valid && VIEWS.hasOwnProperty("INCREMENTAL") && VIEWS.INCREMENTAL.valid) {
report += '<br><strong>Note: Area report accuracy may be reduced when performing an incremental compile.</strong>';
}
if (VIEWS.AREA_SYS.valid && !areaJSON.debug_enabled) {
report += '<br><strong>Recompile without <tt>-g0</tt> for detailed area breakdown by source line.</strong>';
}
report += '</td><td>';
report += "<span style='font-size:1rem;float:right'>";
report += "<button id='collapseAll' type='button' class='text-left exp-col-btn'><span class='body glyphicon'></span> Collapse All </button>";
report += "<button id='expandAll' type='button' class='text-left exp-col-btn'><span class='body glyphicon'></span> Expand All </button>";
report += '</span>';
report += '</td></tr></table>';
report += "</div><div class='card-body report-body' id='report-area' onscroll='adjustToWindowEvent()'>";
report += "<table class='table table-hover areatable' id='area-table-content'></table>";
break;
case VIEWS.INCREMENTAL:
if (incrementalJSON.hasOwnProperty('name')) { // This needs to be refactor. Should not be parsing JSON here
report += incrementalJSON.name;
}
else {
report += reportEnum.name;
}
if (incrementalJSON.hasOwnProperty('details')) {
report += '<hr/>';
incrementalJSON.details.forEach(function (d) {
report += '<li>' + d.text + '</li>';
});
}
report += '</div>';
report += "<div class='card-body report-body' onscroll='adjustToWindowEvent()'>";
report += "<table class='table table-hover areatable' id='area-table-content'></table>";
break;
case VIEWS.LMEM:
reportView = document.createElement('div');
reportView.id = 'report-pane-view' + reportEnum.value;
reportView.className = 'report-pane-view-style';
reportBody = addViewerPanel(reportEnum, 'layers-lmem', 'LMEMG');
reportView.appendChild(reportBody);
reportPane = document.getElementById('report-pane');
reportPane.appendChild(reportView);
$('#report-pane-view' + reportEnum.value).toggle();
return;
case VIEWS.GV:
reportView = document.createElement('div');
reportView.id = 'report-pane-view' + reportEnum.value;
reportView.className = 'report-pane-view-style';
reportBody = addViewerPanel(reportEnum, 'layers', 'GVG');
reportView.appendChild(reportBody);
reportPane = document.getElementById('report-pane');
reportPane.appendChild(reportView);
$('#report-pane-view' + reportEnum.value).toggle();
return;
case VIEWS.SCHEDULE:
reportView = document.createElement('div');
reportView.id = 'report-pane-view' + reportEnum.value;
reportView.className = 'report-pane-view-style';
reportBody = addViewerPanel(reportEnum, 'layers', 'SVCBeta');
reportView.appendChild(reportBody);
reportPane = document.getElementById('report-pane');
reportPane.appendChild(reportView);
$('#report-pane-view' + reportEnum.value).toggle();
return;
case VIEWS.LOOPVIS:
reportView = document.createElement('div');
reportView.id = 'report-pane-view' + reportEnum.value;
reportView.className = 'report-pane-view-style';
reportBody = addViewerPanel(reportEnum, 'layers', 'LVAlpha');
reportView.appendChild(reportBody);
reportPane = document.getElementById('report-pane');
reportPane.appendChild(reportView);
$('#report-pane-view' + reportEnum.value).toggle();
return;
}
report += '</div></div></div>';
$('#report-pane-view' + reportEnum.value).html(report);
$('#report-pane-view' + reportEnum.value + ' #area-table-content').html(reportEnum.source);
} |
JavaScript | function addHdlFileToEditor(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status === 0) {
var allText = rawFile.responseText;
// Create the editor if it doesn't exist
if (dot_editor === null) {
var count = $('#editor-pane-nav li').length;
$("#editor-pane-nav").append("<li><a data-target='#file" + count + "'>HDL</a><p></p></li>");
fileIndexMap.HDL = count;
var editor_div = "<div class='tab-pane' id='file" + count + "' style='height:500px;'>";
editor_div += "<div class='well' id='dot_editor_well'></div></div>";
$('#editor-pane .tab-content').append(editor_div);
dot_editor = ace.edit($('#dot_editor_well')[0]);
dot_editor.setTheme('../ace/theme/xcode');
dot_editor.setFontSize(12);
dot_editor.getSession().setUseWrapMode(true);
dot_editor.getSession().setNewLineMode('unix');
fileJSON.push({ 'editor': dot_editor, 'absName': 'HDL', 'name': 'HDL', 'path': 'HDL', 'content': allText });
}
// Set the file content
if (file.endsWith('.vhd')) {
dot_editor.getSession().setMode('../ace/mode/vhdl');
}
else {
dot_editor.getSession().setMode('../ace/mode/verilog');
}
dot_editor.setValue(allText.replace(/(\r\n)/gm, '\n'));
dot_editor.setReadOnly(true);
syncEditorPaneToLine(1, 'HDL');
}
else {
alert('Something went wrong trying to get HDL file', file);
}
}
};
rawFile.send(null);
} | function addHdlFileToEditor(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status === 0) {
var allText = rawFile.responseText;
// Create the editor if it doesn't exist
if (dot_editor === null) {
var count = $('#editor-pane-nav li').length;
$("#editor-pane-nav").append("<li><a data-target='#file" + count + "'>HDL</a><p></p></li>");
fileIndexMap.HDL = count;
var editor_div = "<div class='tab-pane' id='file" + count + "' style='height:500px;'>";
editor_div += "<div class='well' id='dot_editor_well'></div></div>";
$('#editor-pane .tab-content').append(editor_div);
dot_editor = ace.edit($('#dot_editor_well')[0]);
dot_editor.setTheme('../ace/theme/xcode');
dot_editor.setFontSize(12);
dot_editor.getSession().setUseWrapMode(true);
dot_editor.getSession().setNewLineMode('unix');
fileJSON.push({ 'editor': dot_editor, 'absName': 'HDL', 'name': 'HDL', 'path': 'HDL', 'content': allText });
}
// Set the file content
if (file.endsWith('.vhd')) {
dot_editor.getSession().setMode('../ace/mode/vhdl');
}
else {
dot_editor.getSession().setMode('../ace/mode/verilog');
}
dot_editor.setValue(allText.replace(/(\r\n)/gm, '\n'));
dot_editor.setReadOnly(true);
syncEditorPaneToLine(1, 'HDL');
}
else {
alert('Something went wrong trying to get HDL file', file);
}
}
};
rawFile.send(null);
} |
JavaScript | function displayBrowserNotSupportedWarning() {
// create a warning box:
var warningWrapper = $('#report-pane');
// warningWrapper.className = 'warningWrapper';
var warningContainer = document.createElement('div');
warningContainer.className = 'warningContainer';
$(warningWrapper).append(warningContainer);
var title = document.createElement('h2');
title.innerHTML = 'WARNING!';
$(warningContainer).append(title);
var message = document.createElement('div');
message.style.textAlign = 'left';
message.style.marginLeft = '20px';
message.style.marginRight = '20px';
var span1 = document.createElement('span');
span1.innerHTML = 'Your browser is not supported to view the report<br/>' +
'Please use Intel oneAPI IDE.<br/><br/>';
message.appendChild(span1);
$(warningContainer).append(message);
$(warningWrapper).hide().fadeIn(1000);
} | function displayBrowserNotSupportedWarning() {
// create a warning box:
var warningWrapper = $('#report-pane');
// warningWrapper.className = 'warningWrapper';
var warningContainer = document.createElement('div');
warningContainer.className = 'warningContainer';
$(warningWrapper).append(warningContainer);
var title = document.createElement('h2');
title.innerHTML = 'WARNING!';
$(warningContainer).append(title);
var message = document.createElement('div');
message.style.textAlign = 'left';
message.style.marginLeft = '20px';
message.style.marginRight = '20px';
var span1 = document.createElement('span');
span1.innerHTML = 'Your browser is not supported to view the report<br/>' +
'Please use Intel oneAPI IDE.<br/><br/>';
message.appendChild(span1);
$(warningContainer).append(message);
$(warningWrapper).hide().fadeIn(1000);
} |
JavaScript | function collapseDetails() {
toggleDetails();
let vIcon = document.getElementById(CTRLS.DETAILS.id + 'Text');
vIcon.style.color = (CTRLS.DETAILS.collapsed) ? 'lightgray' : '#007bff';
} | function collapseDetails() {
toggleDetails();
let vIcon = document.getElementById(CTRLS.DETAILS.id + 'Text');
vIcon.style.color = (CTRLS.DETAILS.collapsed) ? 'lightgray' : '#007bff';
} |
JavaScript | function collapseAceEditor() {
toggleAceEditor();
let vIcon = document.getElementById(CTRLS.SOURCE.id + 'Text');
vIcon.style.color = (CTRLS.SOURCE.collapsed) ? 'lightgray' : '#007bff';
} | function collapseAceEditor() {
toggleAceEditor();
let vIcon = document.getElementById(CTRLS.SOURCE.id + 'Text');
vIcon.style.color = (CTRLS.SOURCE.collapsed) ? 'lightgray' : '#007bff';
} |
JavaScript | function adjustReportPaneWidth() {
// col width = 2, 5, 5
let vNextWidth;
// editor pane
if (CTRLS.SOURCE.collapsed)
vNextWidth = 'col-sm-12';
else
vNextWidth = 'col-sm-6';
let reportPane = document.getElementById('report-pane');
reportPane.className = reportPane.className.replace(reportPaneWidth, vNextWidth);
reportPaneWidth = vNextWidth;
// Side-bar
if (CTRLS.TREE.collapsed)
vNextWidth = 'col-sm-12';
else
vNextWidth = 'col-sm-10';
reportPane = document.getElementById('viewer-group');
reportPane.className = reportPane.className.replace(viewerGroupWidth, vNextWidth);
viewerGroupWidth = vNextWidth;
} | function adjustReportPaneWidth() {
// col width = 2, 5, 5
let vNextWidth;
// editor pane
if (CTRLS.SOURCE.collapsed)
vNextWidth = 'col-sm-12';
else
vNextWidth = 'col-sm-6';
let reportPane = document.getElementById('report-pane');
reportPane.className = reportPane.className.replace(reportPaneWidth, vNextWidth);
reportPaneWidth = vNextWidth;
// Side-bar
if (CTRLS.TREE.collapsed)
vNextWidth = 'col-sm-12';
else
vNextWidth = 'col-sm-10';
reportPane = document.getElementById('viewer-group');
reportPane.className = reportPane.className.replace(viewerGroupWidth, vNextWidth);
viewerGroupWidth = vNextWidth;
} |
JavaScript | function addViewerPanel(view, layerId, panelId) {
let headerName = view.name;
let paneHeading = document.createElement('div');
paneHeading.className = 'card-header';
paneHeading.innerHTML = headerName;
let entitySpan = document.createElement('span');
entitySpan.className = 'currentEntity';
paneHeading.appendChild(entitySpan);
let buttonSpan = document.createElement('span');
buttonSpan.setAttribute('style', 'float:right');
let buttonDiv = document.createElement('div');
buttonDiv.id = layerId;
buttonSpan.appendChild(buttonDiv);
paneHeading.appendChild(buttonSpan);
let reportBody = document.createElement('div');
reportBody.id = 'report-panel-body';
reportBody.className = 'card';
reportBody.appendChild(paneHeading);
let viewBody = document.createElement('div');
viewBody.id = panelId;
viewBody.className = 'card-body'; // fade in active";
reportBody.appendChild(viewBody);
let idName = view.id;
let reportBodyContainer = document.createElement('div');
reportBodyContainer.id = idName;
reportBodyContainer.className = 'classWithPad';
reportBodyContainer.appendChild(reportBody);
return reportBodyContainer;
} | function addViewerPanel(view, layerId, panelId) {
let headerName = view.name;
let paneHeading = document.createElement('div');
paneHeading.className = 'card-header';
paneHeading.innerHTML = headerName;
let entitySpan = document.createElement('span');
entitySpan.className = 'currentEntity';
paneHeading.appendChild(entitySpan);
let buttonSpan = document.createElement('span');
buttonSpan.setAttribute('style', 'float:right');
let buttonDiv = document.createElement('div');
buttonDiv.id = layerId;
buttonSpan.appendChild(buttonDiv);
paneHeading.appendChild(buttonSpan);
let reportBody = document.createElement('div');
reportBody.id = 'report-panel-body';
reportBody.className = 'card';
reportBody.appendChild(paneHeading);
let viewBody = document.createElement('div');
viewBody.id = panelId;
viewBody.className = 'card-body'; // fade in active";
reportBody.appendChild(viewBody);
let idName = view.id;
let reportBodyContainer = document.createElement('div');
reportBodyContainer.id = idName;
reportBodyContainer.className = 'classWithPad';
reportBodyContainer.appendChild(reportBody);
return reportBodyContainer;
} |
JavaScript | function searchJsonArrayByName(jsonArray, name) {
var res = null;
for (let i = 0; i < jsonArray.length; i++) {
if (jsonArray[i]['name'] === name) {
res = jsonArray[i];
break;
}
;
if (jsonHasChildrenArray(jsonArray[i]))
res = searchJsonArrayByName(jsonArray[i]['children'], name);
if (res)
break; // Return immediately if res is valid. Important for recursion.
}
return res;
} | function searchJsonArrayByName(jsonArray, name) {
var res = null;
for (let i = 0; i < jsonArray.length; i++) {
if (jsonArray[i]['name'] === name) {
res = jsonArray[i];
break;
}
;
if (jsonHasChildrenArray(jsonArray[i]))
res = searchJsonArrayByName(jsonArray[i]['children'], name);
if (res)
break; // Return immediately if res is valid. Important for recursion.
}
return res;
} |
JavaScript | function isFunction(name) {
if (name.match(/\w+:\s+\w+/g))
return true;
else
return false;
} | function isFunction(name) {
if (name.match(/\w+:\s+\w+/g))
return true;
else
return false;
} |
JavaScript | function isBasicBlock(name) {
if (name.match(/(Fused loop |Partially unrolled )?[\w<>]+\.B\d+.*/g))
return true;
else
return false;
} | function isBasicBlock(name) {
if (name.match(/(Fused loop |Partially unrolled )?[\w<>]+\.B\d+.*/g))
return true;
else
return false;
} |
JavaScript | function parseJson(loopBlock, pParentId, json) {
let realName = loopBlock['name'];
let columns = {};
columns['pl'] = loopBlock['pl'];
columns['ii'] = loopBlock['ii'];
columns['af'] = loopBlock['af'];
columns['mi'] = loopBlock['mi'];
columns['lt'] = loopBlock['lt'];
columns['si'] = (json) ? json['data'][2] : "n/a"; // block
// details still comes from old json
columns['brief'] = (json && json.hasOwnProperty('details') && json['details'][0]['type'] === "brief") ?
json['details'][0]['text'] : "";
let noteCall = 'clearDivContent()';
// PATCH: We want to include the json details from loops.json AND the details from loops_attr.json
// Remove when case:14013361689 is implemented!
let detailsJSON = undefined;
if (loopBlock.hasOwnProperty('details')) {
detailsJSON = loopBlock['details'];
}
if (json && json.hasOwnProperty('details') && json.hasOwnProperty('name') && getRealName(json['name']) === realName) {
if (detailsJSON != undefined)
detailsJSON = detailsJSON.concat(json['details']);
else
detailsJSON = json['details'];
}
if (detailsJSON != undefined) {
let detailHTML = getHTMLDetailsFromJSON(detailsJSON, realName);
noteCall = 'changeDivContent(0,' + JSON.stringify(detailHTML) + ')';
}
let debugLoc = null;
if (loopBlock.hasOwnProperty('debug')) {
debugLoc = loopBlock['debug'];
}
let rowId = loopBlock['id'];
// Add Component invocation to name
// name still comes from old json until we unify all the names
let secondaryName = (loopBlock.hasOwnProperty('ci') && loopBlock['ci'] === '1') ? " (Component invocation)" : "";
// Front-end to add type so data is identical in every view
let prefix = '';
if (product === PRODUCTS.HLS) {
// TODO: fix bug where Task is type kernel
if (loopBlock['type'] === 'component') {
prefix = 'Component: ';
}
else if (loopBlock['type'] === 'kernel') {
prefix = 'Task: ';
}
}
else {
if (loopBlock['type'] === 'kernel') {
prefix = 'Kernel: ';
}
}
loopDataRows.push(new FPGADataRow(rowId, prefix + realName + secondaryName, debugLoc, columns, '', pParentId, 0, '', noteCall, ''));
// iterate using loopBlock because it's topologically sorted
if (jsonHasChildrenArray(loopBlock)) {
loopBlock['children'].forEach(function (child) {
if (child['type'] === 'loop') {
let vSubLoopName = child['name'];
if (jsonHasChildrenArray(json)) {
let vSubLoop = null;
// just search immediate children for subloop
for (let i = 0; i < json['children'].length; i++) {
if (vSubLoopName === getRealName(json['children'][i]['name'])) {
vSubLoop = json['children'][i];
break;
}
}
parseJson(child, rowId, vSubLoop);
}
else { // can't find subloop in old loopJSON
parseJson(child, rowId, null);
}
}
else if (vShowBlock) {
parseJson(child, rowId, null);
}
});
}
} | function parseJson(loopBlock, pParentId, json) {
let realName = loopBlock['name'];
let columns = {};
columns['pl'] = loopBlock['pl'];
columns['ii'] = loopBlock['ii'];
columns['af'] = loopBlock['af'];
columns['mi'] = loopBlock['mi'];
columns['lt'] = loopBlock['lt'];
columns['si'] = (json) ? json['data'][2] : "n/a"; // block
// details still comes from old json
columns['brief'] = (json && json.hasOwnProperty('details') && json['details'][0]['type'] === "brief") ?
json['details'][0]['text'] : "";
let noteCall = 'clearDivContent()';
// PATCH: We want to include the json details from loops.json AND the details from loops_attr.json
// Remove when case:14013361689 is implemented!
let detailsJSON = undefined;
if (loopBlock.hasOwnProperty('details')) {
detailsJSON = loopBlock['details'];
}
if (json && json.hasOwnProperty('details') && json.hasOwnProperty('name') && getRealName(json['name']) === realName) {
if (detailsJSON != undefined)
detailsJSON = detailsJSON.concat(json['details']);
else
detailsJSON = json['details'];
}
if (detailsJSON != undefined) {
let detailHTML = getHTMLDetailsFromJSON(detailsJSON, realName);
noteCall = 'changeDivContent(0,' + JSON.stringify(detailHTML) + ')';
}
let debugLoc = null;
if (loopBlock.hasOwnProperty('debug')) {
debugLoc = loopBlock['debug'];
}
let rowId = loopBlock['id'];
// Add Component invocation to name
// name still comes from old json until we unify all the names
let secondaryName = (loopBlock.hasOwnProperty('ci') && loopBlock['ci'] === '1') ? " (Component invocation)" : "";
// Front-end to add type so data is identical in every view
let prefix = '';
if (product === PRODUCTS.HLS) {
// TODO: fix bug where Task is type kernel
if (loopBlock['type'] === 'component') {
prefix = 'Component: ';
}
else if (loopBlock['type'] === 'kernel') {
prefix = 'Task: ';
}
}
else {
if (loopBlock['type'] === 'kernel') {
prefix = 'Kernel: ';
}
}
loopDataRows.push(new FPGADataRow(rowId, prefix + realName + secondaryName, debugLoc, columns, '', pParentId, 0, '', noteCall, ''));
// iterate using loopBlock because it's topologically sorted
if (jsonHasChildrenArray(loopBlock)) {
loopBlock['children'].forEach(function (child) {
if (child['type'] === 'loop') {
let vSubLoopName = child['name'];
if (jsonHasChildrenArray(json)) {
let vSubLoop = null;
// just search immediate children for subloop
for (let i = 0; i < json['children'].length; i++) {
if (vSubLoopName === getRealName(json['children'][i]['name'])) {
vSubLoop = json['children'][i];
break;
}
}
parseJson(child, rowId, vSubLoop);
}
else { // can't find subloop in old loopJSON
parseJson(child, rowId, null);
}
}
else if (vShowBlock) {
parseJson(child, rowId, null);
}
});
}
} |
JavaScript | function newFPGAElement(pParent, pType, pClass, pID, pText) {
let vID = (pID !== undefined && pID) ? pID : 0; // cannot be 0
let vNewElem = document.createElement(pType);
if (pParent)
pParent.appendChild(vNewElem);
if (pClass)
vNewElem.className = pClass;
if (pText !== undefined && pText !== null) {
if (pText.indexOf && pText.indexOf('<') === -1 && pText.indexOf && pText.indexOf('&') !== 0)
vNewElem.appendChild(document.createTextNode(pText));
else
vNewElem.insertAdjacentHTML('beforeend', pText);
}
if (vID)
vNewElem.id = vID;
return vNewElem;
} | function newFPGAElement(pParent, pType, pClass, pID, pText) {
let vID = (pID !== undefined && pID) ? pID : 0; // cannot be 0
let vNewElem = document.createElement(pType);
if (pParent)
pParent.appendChild(vNewElem);
if (pClass)
vNewElem.className = pClass;
if (pText !== undefined && pText !== null) {
if (pText.indexOf && pText.indexOf('<') === -1 && pText.indexOf && pText.indexOf('&') !== 0)
vNewElem.appendChild(document.createTextNode(pText));
else
vNewElem.insertAdjacentHTML('beforeend', pText);
}
if (vID)
vNewElem.id = vID;
return vNewElem;
} |
JavaScript | function createEmptyCard(pParent, pID, pName, pClass) {
let vTmpClass = (pClass) ? pClass + ' ' : '';
var vTmpCard = newFPGAElement(pParent, 'div', vTmpClass + 'card');
vTmpClass = (pClass) ? pClass + '-header ' : '';
var vTmpDiv = newFPGAElement(vTmpCard, 'h7', vTmpClass + 'card-header', pID);
vTmpDiv.setAttribute('role', 'tab');
vTmpDiv = newFPGAElement(vTmpDiv, 'a', 'd-block', 0, pName);
vTmpDiv.className = 'disabled'; // disable this link
pParent.appendChild(vTmpCard);
} | function createEmptyCard(pParent, pID, pName, pClass) {
let vTmpClass = (pClass) ? pClass + ' ' : '';
var vTmpCard = newFPGAElement(pParent, 'div', vTmpClass + 'card');
vTmpClass = (pClass) ? pClass + '-header ' : '';
var vTmpDiv = newFPGAElement(vTmpCard, 'h7', vTmpClass + 'card-header', pID);
vTmpDiv.setAttribute('role', 'tab');
vTmpDiv = newFPGAElement(vTmpDiv, 'a', 'd-block', 0, pName);
vTmpDiv.className = 'disabled'; // disable this link
pParent.appendChild(vTmpCard);
} |
JavaScript | function createTreeCard(pParent, pID, headerName, enableFilter) {
let vID = pID;
let vHeaderID = vID + 'Header';
let vTmpDiv = newFPGAElement(pParent, 'div', 'card', 'report-panel-tree');
let treeHeading = newFPGAElement(vTmpDiv, 'div', 'card-header', vHeaderID, headerName);
if (enableFilter) {
let filterButton = document.createElement('button');
filterButton.className = "btn btn-default btn-sm dropdown-toggle";
filterButton.setAttribute("data-toggle", "dropdown");
// Make the filter button text
let filterButtonText = document.createElement('span');
filterButtonText.className = "body glyphicon";
filterButtonText.innerHTML = "";
filterButton.appendChild(filterButtonText);
filterButtonText = document.createElement('span');
filterButtonText.className = "caret";
filterButton.appendChild(filterButtonText);
// Button and dropdown list
let filterButtonGroup = document.createElement('div');
filterButtonGroup.id = pID + "-button";
filterButtonGroup.className = "btn-group float-right";
filterButtonGroup.appendChild(filterButton);
// Drop down, data will be fill dynamically for each view
let filterDropDown = document.createElement('div');
filterDropDown.id = pID + "-filter";
filterDropDown.className = "dropdown-menu dropdown-menu-right";
filterButtonGroup.appendChild(filterDropDown);
treeHeading.appendChild(filterButtonGroup);
}
vTmpDiv = newFPGAElement(vTmpDiv, 'div', 'tree-body card-body', vID);
} | function createTreeCard(pParent, pID, headerName, enableFilter) {
let vID = pID;
let vHeaderID = vID + 'Header';
let vTmpDiv = newFPGAElement(pParent, 'div', 'card', 'report-panel-tree');
let treeHeading = newFPGAElement(vTmpDiv, 'div', 'card-header', vHeaderID, headerName);
if (enableFilter) {
let filterButton = document.createElement('button');
filterButton.className = "btn btn-default btn-sm dropdown-toggle";
filterButton.setAttribute("data-toggle", "dropdown");
// Make the filter button text
let filterButtonText = document.createElement('span');
filterButtonText.className = "body glyphicon";
filterButtonText.innerHTML = "";
filterButton.appendChild(filterButtonText);
filterButtonText = document.createElement('span');
filterButtonText.className = "caret";
filterButton.appendChild(filterButtonText);
// Button and dropdown list
let filterButtonGroup = document.createElement('div');
filterButtonGroup.id = pID + "-button";
filterButtonGroup.className = "btn-group float-right";
filterButtonGroup.appendChild(filterButton);
// Drop down, data will be fill dynamically for each view
let filterDropDown = document.createElement('div');
filterDropDown.id = pID + "-filter";
filterDropDown.className = "dropdown-menu dropdown-menu-right";
filterButtonGroup.appendChild(filterDropDown);
treeHeading.appendChild(filterButtonGroup);
}
vTmpDiv = newFPGAElement(vTmpDiv, 'div', 'tree-body card-body', vID);
} |
JavaScript | function createHelpTooltip(pText) {
let vNewTitle = document.createElement('a');
vNewTitle.href = "#";
vNewTitle.setAttribute('data-toggle', 'tooltip');
vNewTitle.setAttribute('data-placement', 'left');
vNewTitle.title = pText;
vNewTitle.innerHTML = '(?)';
return vNewTitle;
} | function createHelpTooltip(pText) {
let vNewTitle = document.createElement('a');
vNewTitle.href = "#";
vNewTitle.setAttribute('data-toggle', 'tooltip');
vNewTitle.setAttribute('data-placement', 'left');
vNewTitle.title = pText;
vNewTitle.innerHTML = '(?)';
return vNewTitle;
} |
JavaScript | function scrollToElement(element, parent, extraOffset) {
var vExtraOffset = (extraOffset && parseInt(extraOffset)) ? parseInt(extraOffset) : 0;
$(parent)[0].scrollIntoView(true);
$(parent).animate({
scrollTop: $(parent).scrollTop() + $(element).offset().top - $(parent).offset().top - vExtraOffset
}, {
duration: 'slow',
easing: 'swing'
});
} | function scrollToElement(element, parent, extraOffset) {
var vExtraOffset = (extraOffset && parseInt(extraOffset)) ? parseInt(extraOffset) : 0;
$(parent)[0].scrollIntoView(true);
$(parent).animate({
scrollTop: $(parent).scrollTop() + $(element).offset().top - $(parent).offset().top - vExtraOffset
}, {
duration: 'slow',
easing: 'swing'
});
} |
JavaScript | function flattenNodesHelper(nodeList, parent) {
if (!nodeList)
return;
nodeList.forEach(function (n) {
n['parent'] = parent;
flattenedNodes.set(n['id'], n);
if (n['children']) {
flattenNodesHelper(n['children'], n);
}
});
} | function flattenNodesHelper(nodeList, parent) {
if (!nodeList)
return;
nodeList.forEach(function (n) {
n['parent'] = parent;
flattenedNodes.set(n['id'], n);
if (n['children']) {
flattenNodesHelper(n['children'], n);
}
});
} |
JavaScript | function renderNoGraphForType(graph, title, type, details, message) {
let contentText;
switch (type) {
case 'reg':
contentText = OPT_AS_REG_DIV;
break;
case 'unsynth':
contentText = UNSYNTH_DIV;
break;
case 'untrack':
contentText = UNTRACK_DIV;
break;
case 'no_nodes':
contentText = NO_NODES_DIV;
break;
case 'choose_graph':
contentText = SELECT_GRAPH_DIV;
break;
case 'message':
contentText = GRAPH_MESSAGE_PREFIX + message + GRAPH_MESSAGE_SUFFIX;
break;
default:
contentText = '';
}
$(graph).html(contentText);
changeDetailsPane(details, title);
} | function renderNoGraphForType(graph, title, type, details, message) {
let contentText;
switch (type) {
case 'reg':
contentText = OPT_AS_REG_DIV;
break;
case 'unsynth':
contentText = UNSYNTH_DIV;
break;
case 'untrack':
contentText = UNTRACK_DIV;
break;
case 'no_nodes':
contentText = NO_NODES_DIV;
break;
case 'choose_graph':
contentText = SELECT_GRAPH_DIV;
break;
case 'message':
contentText = GRAPH_MESSAGE_PREFIX + message + GRAPH_MESSAGE_SUFFIX;
break;
default:
contentText = '';
}
$(graph).html(contentText);
changeDetailsPane(details, title);
} |
JavaScript | function contains (...args) {
if (args.length !== 3) {
throw new Error('Helper "contains" needs 2 parameters');
}
const { fn, inverse, hash } = args.pop();
const [ haystack, needle ] = args;
let result;
if (isArray(haystack)) {
result = haystack.includes(needle);
} else if (isString(haystack)) {
if ((hash && hash.regex) || needle instanceof RegExp) {
result = !!haystack.match(new RegExp(needle));
} else {
result = haystack.includes(needle);
}
} else if (isObject(haystack)) {
result = hasOwn(haystack, needle);
} else {
result = false;
}
if (!fn) {
return result || '';
}
return result ? fn() : inverse && inverse();
} | function contains (...args) {
if (args.length !== 3) {
throw new Error('Helper "contains" needs 2 parameters');
}
const { fn, inverse, hash } = args.pop();
const [ haystack, needle ] = args;
let result;
if (isArray(haystack)) {
result = haystack.includes(needle);
} else if (isString(haystack)) {
if ((hash && hash.regex) || needle instanceof RegExp) {
result = !!haystack.match(new RegExp(needle));
} else {
result = haystack.includes(needle);
}
} else if (isObject(haystack)) {
result = hasOwn(haystack, needle);
} else {
result = false;
}
if (!fn) {
return result || '';
}
return result ? fn() : inverse && inverse();
} |
JavaScript | function replace (...args) {
const { fn } = args.pop();
let haystack;
if (fn) haystack = safe.down(fn());
else haystack = String(args.shift());
const needle = args[2] ? new RegExp(args[0]) : args[0];
const replacement = args[1] || '';
const regex = needle instanceof RegExp;
return regex ? haystack.replace(needle, replacement) : haystack.split(needle).join(replacement);
} | function replace (...args) {
const { fn } = args.pop();
let haystack;
if (fn) haystack = safe.down(fn());
else haystack = String(args.shift());
const needle = args[2] ? new RegExp(args[0]) : args[0];
const replacement = args[1] || '';
const regex = needle instanceof RegExp;
return regex ? haystack.replace(needle, replacement) : haystack.split(needle).join(replacement);
} |
JavaScript | function endsWith (...args) {
if (args.length !== 3) {
throw new Error('Helper "endsWith" needs 2 parameters');
}
const { fn, inverse } = args.pop();
const [ haystack, needle ] = args;
let result;
if (isArray(haystack)) {
result = haystack[haystack.length - 1] === needle;
} else if (isString(haystack)) {
result = haystack.endsWith(needle);
} else {
result = false;
}
if (!fn) {
return result || '';
}
return result ? fn() : inverse && inverse();
} | function endsWith (...args) {
if (args.length !== 3) {
throw new Error('Helper "endsWith" needs 2 parameters');
}
const { fn, inverse } = args.pop();
const [ haystack, needle ] = args;
let result;
if (isArray(haystack)) {
result = haystack[haystack.length - 1] === needle;
} else if (isString(haystack)) {
result = haystack.endsWith(needle);
} else {
result = false;
}
if (!fn) {
return result || '';
}
return result ? fn() : inverse && inverse();
} |
JavaScript | function join (...args) {
if (args.length === 1) {
throw new Error('Helper "join" needs at least one parameter');
}
const { fn, inverse, env, hash } = args.pop();
const input = args[0];
const delimiter = args.length === 2 ? args[1] : ', ';
const c = sizeOf(input);
if (!c) return inverse && inverse();
if (!fn) return safeJoin(input, null, delimiter);
var frame = makeContext(input, env, { hash });
return safeJoin(input, (value, key, index) => {
frame.this = value;
frame['@value'] = value;
frame['@key'] = key;
frame['@index'] = index;
frame['@first'] = index === 0;
frame['@last'] = index === c - 1;
return fn(value, frame);
}, delimiter);
} | function join (...args) {
if (args.length === 1) {
throw new Error('Helper "join" needs at least one parameter');
}
const { fn, inverse, env, hash } = args.pop();
const input = args[0];
const delimiter = args.length === 2 ? args[1] : ', ';
const c = sizeOf(input);
if (!c) return inverse && inverse();
if (!fn) return safeJoin(input, null, delimiter);
var frame = makeContext(input, env, { hash });
return safeJoin(input, (value, key, index) => {
frame.this = value;
frame['@value'] = value;
frame['@key'] = key;
frame['@index'] = index;
frame['@first'] = index === 0;
frame['@last'] = index === c - 1;
return fn(value, frame);
}, delimiter);
} |
JavaScript | function mul (...args) {
args.pop();
if (args.length < 2 && !isArray(args[0])) {
throw new Error('Handlebars Helper "mul" needs 2 parameters minimum');
}
args = flatten(args);
const initial = args.shift();
return args.reduce((a, b) => a * b, initial);
} | function mul (...args) {
args.pop();
if (args.length < 2 && !isArray(args[0])) {
throw new Error('Handlebars Helper "mul" needs 2 parameters minimum');
}
args = flatten(args);
const initial = args.shift();
return args.reduce((a, b) => a * b, initial);
} |
JavaScript | _addEntries(rawEntries) {
this._parsedCacheUrls = null;
rawEntries.forEach((rawEntry) => {
this._addEntryToInstallList(
this._parseEntry(rawEntry)
);
});
} | _addEntries(rawEntries) {
this._parsedCacheUrls = null;
rawEntries.forEach((rawEntry) => {
this._addEntryToInstallList(
this._parseEntry(rawEntry)
);
});
} |
JavaScript | _addEntryToInstallList(precacheEntry) {
const entryID = precacheEntry.entryID;
const previousEntry = this._entriesToCache.get(precacheEntry.entryID);
if (!previousEntry) {
// This entry isn't in the install list
this._entriesToCache.set(entryID, precacheEntry);
return;
}
this._onDuplicateInstallEntryFound(precacheEntry, previousEntry);
} | _addEntryToInstallList(precacheEntry) {
const entryID = precacheEntry.entryID;
const previousEntry = this._entriesToCache.get(precacheEntry.entryID);
if (!previousEntry) {
// This entry isn't in the install list
this._entriesToCache.set(entryID, precacheEntry);
return;
}
this._onDuplicateInstallEntryFound(precacheEntry, previousEntry);
} |
JavaScript | async install() {
if (this._entriesToCache.size === 0) {
return;
}
const cachePromises = [];
this._entriesToCache.forEach((precacheEntry) => {
cachePromises.push(
this._cacheEntry(precacheEntry)
);
});
// Wait for all requests to be cached.
return Promise.all(cachePromises);
} | async install() {
if (this._entriesToCache.size === 0) {
return;
}
const cachePromises = [];
this._entriesToCache.forEach((precacheEntry) => {
cachePromises.push(
this._cacheEntry(precacheEntry)
);
});
// Wait for all requests to be cached.
return Promise.all(cachePromises);
} |
JavaScript | async _cacheEntry(precacheEntry) {
const isCached = await this._isAlreadyCached(precacheEntry);
if (isCached) {
return;
}
try {
await this._requestWrapper.fetchAndCache({
request: precacheEntry.getNetworkRequest(),
waitOnCache: true,
cacheKey: precacheEntry.request,
});
return this._onEntryCached(precacheEntry);
} catch (err) {
throw ErrorFactory.createError('request-not-cached', {
message: `Failed to get a cacheable response for ` +
`'${precacheEntry.request.url}': ${err.message}`,
});
}
} | async _cacheEntry(precacheEntry) {
const isCached = await this._isAlreadyCached(precacheEntry);
if (isCached) {
return;
}
try {
await this._requestWrapper.fetchAndCache({
request: precacheEntry.getNetworkRequest(),
waitOnCache: true,
cacheKey: precacheEntry.request,
});
return this._onEntryCached(precacheEntry);
} catch (err) {
throw ErrorFactory.createError('request-not-cached', {
message: `Failed to get a cacheable response for ` +
`'${precacheEntry.request.url}': ${err.message}`,
});
}
} |
JavaScript | async cleanup() {
if (!await caches.has(this._cacheName)) {
// Cache doesn't exist, so nothing to delete
return;
}
const requestsCachedOnInstall = [];
this._entriesToCache.forEach((entry) => {
requestsCachedOnInstall.push(entry.request.url);
});
const openCache = await this._getCache();
const allCachedRequests = await openCache.keys();
const cachedRequestsToDelete = allCachedRequests.filter((cachedRequest) => {
if (requestsCachedOnInstall.includes(cachedRequest.url)) {
return false;
}
return true;
});
return Promise.all(
cachedRequestsToDelete.map((cachedRequest) => {
return openCache.delete(cachedRequest);
})
);
} | async cleanup() {
if (!await caches.has(this._cacheName)) {
// Cache doesn't exist, so nothing to delete
return;
}
const requestsCachedOnInstall = [];
this._entriesToCache.forEach((entry) => {
requestsCachedOnInstall.push(entry.request.url);
});
const openCache = await this._getCache();
const allCachedRequests = await openCache.keys();
const cachedRequestsToDelete = allCachedRequests.filter((cachedRequest) => {
if (requestsCachedOnInstall.includes(cachedRequest.url)) {
return false;
}
return true;
});
return Promise.all(
cachedRequestsToDelete.map((cachedRequest) => {
return openCache.delete(cachedRequest);
})
);
} |
JavaScript | async _getCache() {
if (!this._cache) {
this._cache = await caches.open(this._cacheName);
}
return this._cache;
} | async _getCache() {
if (!this._cache) {
this._cache = await caches.open(this._cacheName);
}
return this._cache;
} |
JavaScript | attachSyncHandler() {
self.addEventListener('sync', (event) => {
if(event.tag === tagNamePrefix + this._queue.queueName) {
event.waitUntil(this.replayRequests());
}
});
} | attachSyncHandler() {
self.addEventListener('sync', (event) => {
if(event.tag === tagNamePrefix + this._queue.queueName) {
event.waitUntil(this.replayRequests());
}
});
} |
JavaScript | async handle({event} = {}) {
assert.isInstance({event}, FetchEvent);
const promises = [];
let timeoutId;
if (this.networkTimeoutSeconds) {
promises.push(new Promise((resolve) => {
timeoutId = setTimeout(() => {
resolve(this.requestWrapper.match({request: event.request}));
}, this.networkTimeoutSeconds * 1000);
}));
}
promises.push(this.requestWrapper.fetchAndCache({request: event.request})
.then((response) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
return response ?
response :
Promise.reject('No response received; falling back to cache.');
})
.catch(() => this.requestWrapper.match({request: event.request}))
);
return Promise.race(promises);
} | async handle({event} = {}) {
assert.isInstance({event}, FetchEvent);
const promises = [];
let timeoutId;
if (this.networkTimeoutSeconds) {
promises.push(new Promise((resolve) => {
timeoutId = setTimeout(() => {
resolve(this.requestWrapper.match({request: event.request}));
}, this.networkTimeoutSeconds * 1000);
}));
}
promises.push(this.requestWrapper.fetchAndCache({request: event.request})
.then((response) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
return response ?
response :
Promise.reject('No response received; falling back to cache.');
})
.catch(() => this.requestWrapper.match({request: event.request}))
);
return Promise.race(promises);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.