language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function OnAppModeChanged() {
title_open_file.style.display = 'none';
title_capture.style.display = 'none';
if (radio_open_file.checked) {
title_open_file.style.display = 'block';
}
if (radio_capture.checked) {
title_capture.style.display = 'block';
}
} | function OnAppModeChanged() {
title_open_file.style.display = 'none';
title_capture.style.display = 'none';
if (radio_open_file.checked) {
title_open_file.style.display = 'block';
}
if (radio_capture.checked) {
title_capture.style.display = 'block';
}
} |
JavaScript | function OnCaptureModeChanged() {
let x = select_capture_mode;
let i = capture_info;
let desc = '';
switch (x.value) {
case 'live':
desc = 'Live: read BMC\'s dbus-monitor console output directly';
g_capture_mode = 'live';
break;
case 'staged':
desc =
'Staged, IPMI only: Store BMC\'s dbus-monitor output in a file and transfer back for display';
g_capture_mode = 'staged';
break;
case 'staged2':
desc =
'Staged, DBus + IPMI: Store BMC\'s busctl output in a file and transfer back for display';
g_capture_mode = 'staged2';
break;
}
i.textContent = desc;
} | function OnCaptureModeChanged() {
let x = select_capture_mode;
let i = capture_info;
let desc = '';
switch (x.value) {
case 'live':
desc = 'Live: read BMC\'s dbus-monitor console output directly';
g_capture_mode = 'live';
break;
case 'staged':
desc =
'Staged, IPMI only: Store BMC\'s dbus-monitor output in a file and transfer back for display';
g_capture_mode = 'staged';
break;
case 'staged2':
desc =
'Staged, DBus + IPMI: Store BMC\'s busctl output in a file and transfer back for display';
g_capture_mode = 'staged2';
break;
}
i.textContent = desc;
} |
JavaScript | OnMouseDown(iter = 1) {
// If hovering over an overflowing triangle, warp to the nearest overflowed
// request on that line
if (this.MouseState.hoveredVisibleLineIndex >= 0 &&
this.MouseState.hoveredVisibleLineIndex < this.Intervals.length &&
this.MouseState.hoveredSide != undefined) {
const x = this.VisualLineIndexToDataLineIndex(this.MouseState.hoveredVisibleLineIndex);
if (x == undefined) return;
const line = this.Intervals[x[0]];
if (this.MouseState.hoveredSide == 'left') {
for (let i = line.length - 1; i >= 0; i--) {
if (line[i][1] <= this.LowerBoundTime) {
this.BeginWarpToRequestAnimation(line[i]);
// TODO: pass timeline X to linked view
break;
}
}
} else if (this.MouseState.hoveredSide == 'right') {
for (let i = 0; i < line.length; i++) {
if (line[i][0] >= this.UpperBoundTime) {
// TODO: pass timeline X to linked view
this.BeginWarpToRequestAnimation(line[i]);
break;
}
}
}
}
let tx = this.MouseXToTimestamp(this.MouseState.x);
let t0 = Math.min(this.HighlightedRegion.t0, this.HighlightedRegion.t1),
t1 = Math.max(this.HighlightedRegion.t0, this.HighlightedRegion.t1);
if (this.MouseState.x > LEFT_MARGIN) {
// If clicking on the horizontal scroll bar, start panning the viewport
if (this.MouseState.hoveredSide == "top_horizontal_scrollbar" ||
this.MouseState.hoveredSide == "bottom_horizontal_scrollbar") {
this.MouseState.pressed = true;
this.MouseState.begin_drag_x = this.MouseState.x;
this.MouseState.begin_LowerBoundTime = this.LowerBoundTime;
this.MouseState.begin_UpperBoundTime = this.UpperBoundTime;
} else if (tx >= t0 && tx <= t1) {
// If clicking inside highlighted area, zoom around the area
this.BeginSetBoundaryAnimation(t0, t1);
this.Unhighlight();
this.IsCanvasDirty = true;
this.linked_views.forEach(function(v) {
v.BeginSetBoundaryAnimation(t0, t1, 0);
v.Unhighlight();
v.IsCanvasDirty = false;
});
} else { // If in the timeline area, start a new dragging action
this.MouseState.hoveredSide = 'timeline';
this.MouseState.pressed = true;
this.HighlightedRegion.t0 = this.MouseXToTimestamp(this.MouseState.x);
this.HighlightedRegion.t1 = this.HighlightedRegion.t0;
this.IsCanvasDirty = true;
}
} else if (this.MouseState.x < SCROLL_BAR_WIDTH) { // Todo: draagging the scroll bar
const THRESH = 4;
if (this.MouseState.y >= this.ScrollBarState.y0 - THRESH &&
this.MouseState.y <= this.ScrollBarState.y1 + THRESH) {
this.MouseState.pressed = true;
this.MouseState.drag_begin_y = this.MouseState.y;
this.MouseState.drag_begin_title_start_idx = this.VisualLineStartIdx;
this.MouseState.hoveredSide = 'scrollbar';
}
}
// Collapse or expand a "header"
if (this.MouseState.x < LEFT_MARGIN &&
this.MouseState.hoveredVisibleLineIndex != undefined) {
const x = this.VisualLineIndexToDataLineIndex(this.VisualLineStartIdx + this.MouseState.hoveredVisibleLineIndex);
if (x != undefined) {
const tidx = x[0];
if (this.Titles[tidx] != undefined && this.Titles[tidx].header == true) {
// Currently, only DBus pane supports column headers, so we can hard-code the DBus re-group function (rather than to figure out which pane we're in)
this.HeaderCollapsed[this.Titles[tidx].title] = !(this.HeaderCollapsed[this.Titles[tidx].title]);
OnGroupByConditionChanged_DBus();
}
}
}
} | OnMouseDown(iter = 1) {
// If hovering over an overflowing triangle, warp to the nearest overflowed
// request on that line
if (this.MouseState.hoveredVisibleLineIndex >= 0 &&
this.MouseState.hoveredVisibleLineIndex < this.Intervals.length &&
this.MouseState.hoveredSide != undefined) {
const x = this.VisualLineIndexToDataLineIndex(this.MouseState.hoveredVisibleLineIndex);
if (x == undefined) return;
const line = this.Intervals[x[0]];
if (this.MouseState.hoveredSide == 'left') {
for (let i = line.length - 1; i >= 0; i--) {
if (line[i][1] <= this.LowerBoundTime) {
this.BeginWarpToRequestAnimation(line[i]);
// TODO: pass timeline X to linked view
break;
}
}
} else if (this.MouseState.hoveredSide == 'right') {
for (let i = 0; i < line.length; i++) {
if (line[i][0] >= this.UpperBoundTime) {
// TODO: pass timeline X to linked view
this.BeginWarpToRequestAnimation(line[i]);
break;
}
}
}
}
let tx = this.MouseXToTimestamp(this.MouseState.x);
let t0 = Math.min(this.HighlightedRegion.t0, this.HighlightedRegion.t1),
t1 = Math.max(this.HighlightedRegion.t0, this.HighlightedRegion.t1);
if (this.MouseState.x > LEFT_MARGIN) {
// If clicking on the horizontal scroll bar, start panning the viewport
if (this.MouseState.hoveredSide == "top_horizontal_scrollbar" ||
this.MouseState.hoveredSide == "bottom_horizontal_scrollbar") {
this.MouseState.pressed = true;
this.MouseState.begin_drag_x = this.MouseState.x;
this.MouseState.begin_LowerBoundTime = this.LowerBoundTime;
this.MouseState.begin_UpperBoundTime = this.UpperBoundTime;
} else if (tx >= t0 && tx <= t1) {
// If clicking inside highlighted area, zoom around the area
this.BeginSetBoundaryAnimation(t0, t1);
this.Unhighlight();
this.IsCanvasDirty = true;
this.linked_views.forEach(function(v) {
v.BeginSetBoundaryAnimation(t0, t1, 0);
v.Unhighlight();
v.IsCanvasDirty = false;
});
} else { // If in the timeline area, start a new dragging action
this.MouseState.hoveredSide = 'timeline';
this.MouseState.pressed = true;
this.HighlightedRegion.t0 = this.MouseXToTimestamp(this.MouseState.x);
this.HighlightedRegion.t1 = this.HighlightedRegion.t0;
this.IsCanvasDirty = true;
}
} else if (this.MouseState.x < SCROLL_BAR_WIDTH) { // Todo: draagging the scroll bar
const THRESH = 4;
if (this.MouseState.y >= this.ScrollBarState.y0 - THRESH &&
this.MouseState.y <= this.ScrollBarState.y1 + THRESH) {
this.MouseState.pressed = true;
this.MouseState.drag_begin_y = this.MouseState.y;
this.MouseState.drag_begin_title_start_idx = this.VisualLineStartIdx;
this.MouseState.hoveredSide = 'scrollbar';
}
}
// Collapse or expand a "header"
if (this.MouseState.x < LEFT_MARGIN &&
this.MouseState.hoveredVisibleLineIndex != undefined) {
const x = this.VisualLineIndexToDataLineIndex(this.VisualLineStartIdx + this.MouseState.hoveredVisibleLineIndex);
if (x != undefined) {
const tidx = x[0];
if (this.Titles[tidx] != undefined && this.Titles[tidx].header == true) {
// Currently, only DBus pane supports column headers, so we can hard-code the DBus re-group function (rather than to figure out which pane we're in)
this.HeaderCollapsed[this.Titles[tidx].title] = !(this.HeaderCollapsed[this.Titles[tidx].title]);
OnGroupByConditionChanged_DBus();
}
}
}
} |
JavaScript | function outputDiagnostics(diagnostic) {
var prefix = " ";
var output = prefix + "---\n";
output += prefix + yaml.safeDump(diagnostic).split("\n").join("\n" + prefix);
output += "...\n";
return output;
} | function outputDiagnostics(diagnostic) {
var prefix = " ";
var output = prefix + "---\n";
output += prefix + yaml.safeDump(diagnostic).split("\n").join("\n" + prefix);
output += "...\n";
return output;
} |
JavaScript | function loadIgnoreFile(filePath) {
var exclusions = [],
text;
if (filePath) {
// Read .eslintignore file
try {
text = fs.readFileSync(filePath, "utf8");
try {
// Attempt to parse as JSON (deprecated)
exclusions = JSON.parse(text);
} catch (e) {
// Prefer plain text, one path per line
exclusions = text.split("\n");
}
} catch (e) {
/* istanbul ignore next Error handling doesn't need tests*/
throw new Error("Could not load local " + ESLINT_IGNORE_FILENAME + " file: " + filePath);
}
}
return exclusions;
} | function loadIgnoreFile(filePath) {
var exclusions = [],
text;
if (filePath) {
// Read .eslintignore file
try {
text = fs.readFileSync(filePath, "utf8");
try {
// Attempt to parse as JSON (deprecated)
exclusions = JSON.parse(text);
} catch (e) {
// Prefer plain text, one path per line
exclusions = text.split("\n");
}
} catch (e) {
/* istanbul ignore next Error handling doesn't need tests*/
throw new Error("Could not load local " + ESLINT_IGNORE_FILENAME + " file: " + filePath);
}
}
return exclusions;
} |
JavaScript | function loadConfig(filePath) {
var config = {};
if (filePath) {
try {
config = yaml.safeLoad(stripComments(fs.readFileSync(filePath, "utf8")));
} catch (e) {
console.error("Cannot read config file:", filePath);
console.error("Error: ", e.message);
}
}
return config;
} | function loadConfig(filePath) {
var config = {};
if (filePath) {
try {
config = yaml.safeLoad(stripComments(fs.readFileSync(filePath, "utf8")));
} catch (e) {
console.error("Cannot read config file:", filePath);
console.error("Error: ", e.message);
}
}
return config;
} |
JavaScript | function checkBlock() {
var blockProperties = arguments;
return function(node) {
[].forEach.call(blockProperties, function(blockProp) {
var block = node[blockProp], previousToken, curlyToken;
block = node[blockProp];
if(block && block.type === "BlockStatement") {
previousToken = context.getTokenBefore(block);
curlyToken = context.getFirstToken(block);
if (previousToken.loc.start.line !== curlyToken.loc.start.line) {
context.report(node, OPEN_MESSAGE);
}
}
});
};
} | function checkBlock() {
var blockProperties = arguments;
return function(node) {
[].forEach.call(blockProperties, function(blockProp) {
var block = node[blockProp], previousToken, curlyToken;
block = node[blockProp];
if(block && block.type === "BlockStatement") {
previousToken = context.getTokenBefore(block);
curlyToken = context.getFirstToken(block);
if (previousToken.loc.start.line !== curlyToken.loc.start.line) {
context.report(node, OPEN_MESSAGE);
}
}
});
};
} |
JavaScript | function checkIfStatement(node) {
var tokens;
checkBlock("consequent", "alternate")(node);
if (node.alternate && node.alternate.type === "BlockStatement") {
tokens = context.getTokensBefore(node.alternate, 2);
if (style === "1tbs") {
if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
context.report(node.alternate, CLOSE_MESSAGE);
}
} else if (style === "stroustrup") {
if (tokens[0].loc.start.line === tokens[1].loc.start.line) {
context.report(node.alternate, CLOSE_MESSAGE_STROUSTRUP);
}
}
}
} | function checkIfStatement(node) {
var tokens;
checkBlock("consequent", "alternate")(node);
if (node.alternate && node.alternate.type === "BlockStatement") {
tokens = context.getTokensBefore(node.alternate, 2);
if (style === "1tbs") {
if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
context.report(node.alternate, CLOSE_MESSAGE);
}
} else if (style === "stroustrup") {
if (tokens[0].loc.start.line === tokens[1].loc.start.line) {
context.report(node.alternate, CLOSE_MESSAGE_STROUSTRUP);
}
}
}
} |
JavaScript | function checkSwitchStatement(node) {
var tokens;
if(node.cases && node.cases.length) {
tokens = context.getTokensBefore(node.cases[0], 2);
if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
context.report(node, OPEN_MESSAGE);
}
} else {
tokens = context.getLastTokens(node, 3);
if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
context.report(node, OPEN_MESSAGE);
}
}
} | function checkSwitchStatement(node) {
var tokens;
if(node.cases && node.cases.length) {
tokens = context.getTokensBefore(node.cases[0], 2);
if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
context.report(node, OPEN_MESSAGE);
}
} else {
tokens = context.getLastTokens(node, 3);
if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
context.report(node, OPEN_MESSAGE);
}
}
} |
JavaScript | function escapeSpecialCharacters(message) {
message = message || "";
var pairs = {
"&": "&",
"\"": """,
"'": "'",
"<": "<",
">": ">"
};
return message.replace(/[&"'<>]/g, function(c) {
return pairs[c];
});
} | function escapeSpecialCharacters(message) {
message = message || "";
var pairs = {
"&": "&",
"\"": """,
"'": "'",
"<": "<",
">": ">"
};
return message.replace(/[&"'<>]/g, function(c) {
return pairs[c];
});
} |
JavaScript | function checkJSDoc(node) {
var jsdocNode = context.getJSDocComment(node),
functionData = fns.pop(),
hasReturns = false,
hasConstructor = false,
params = Object.create(null),
jsdoc;
// make sure only to validate JSDoc comments
if (jsdocNode) {
try {
jsdoc = doctrine.parse(jsdocNode.value, {
strict: true,
unwrap: true,
sloppy: true
});
} catch (ex) {
if (/braces/i.test(ex.message)) {
context.report(jsdocNode, "JSDoc type missing brace.");
} else {
context.report(jsdocNode, "JSDoc syntax error.");
}
return;
}
jsdoc.tags.forEach(function(tag) {
switch (tag.title) {
case "param":
if (!tag.type) {
context.report(jsdocNode, "Missing JSDoc parameter type for '{{name}}'.", { name: tag.name });
}
if (!tag.description) {
context.report(jsdocNode, "Missing JSDoc parameter description for '{{name}}'.", { name: tag.name });
}
if (params[tag.name]) {
context.report(jsdocNode, "Duplicate JSDoc parameter '{{name}}'.", { name: tag.name });
} else {
params[tag.name] = 1;
}
break;
case "return":
case "returns":
hasReturns = true;
if (!requireReturn && !functionData.returnPresent && tag.type.name !== "void" && tag.type.name !== "undefined") {
context.report(jsdocNode, "Unexpected @" + tag.title + " tag; function has no return statement.");
} else {
if (!tag.type) {
context.report(jsdocNode, "Missing JSDoc return type.");
}
if (tag.type.name !== "void" && !tag.description) {
context.report(jsdocNode, "Missing JSDoc return description.");
}
}
break;
case "constructor":
hasConstructor = true;
break;
}
// check tag preferences
if (prefer.hasOwnProperty(tag.title)) {
context.report(jsdocNode, "Use @{{name}} instead.", { name: prefer[tag.title] });
}
});
// check for functions missing @returns
if (!hasReturns && !hasConstructor) {
if (requireReturn || functionData.returnPresent) {
context.report(jsdocNode, "Missing JSDoc @returns for function.");
}
}
// check the parameters
var jsdocParams = Object.keys(params);
node.params.forEach(function(param, i) {
var name = param.name;
if (jsdocParams[i] && (name !== jsdocParams[i])) {
context.report(jsdocNode, "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", {
name: name,
jsdocName: jsdocParams[i]
});
} else if (!params[name]) {
context.report(jsdocNode, "Missing JSDoc for parameter '{{name}}'.", {
name: name
});
}
});
}
} | function checkJSDoc(node) {
var jsdocNode = context.getJSDocComment(node),
functionData = fns.pop(),
hasReturns = false,
hasConstructor = false,
params = Object.create(null),
jsdoc;
// make sure only to validate JSDoc comments
if (jsdocNode) {
try {
jsdoc = doctrine.parse(jsdocNode.value, {
strict: true,
unwrap: true,
sloppy: true
});
} catch (ex) {
if (/braces/i.test(ex.message)) {
context.report(jsdocNode, "JSDoc type missing brace.");
} else {
context.report(jsdocNode, "JSDoc syntax error.");
}
return;
}
jsdoc.tags.forEach(function(tag) {
switch (tag.title) {
case "param":
if (!tag.type) {
context.report(jsdocNode, "Missing JSDoc parameter type for '{{name}}'.", { name: tag.name });
}
if (!tag.description) {
context.report(jsdocNode, "Missing JSDoc parameter description for '{{name}}'.", { name: tag.name });
}
if (params[tag.name]) {
context.report(jsdocNode, "Duplicate JSDoc parameter '{{name}}'.", { name: tag.name });
} else {
params[tag.name] = 1;
}
break;
case "return":
case "returns":
hasReturns = true;
if (!requireReturn && !functionData.returnPresent && tag.type.name !== "void" && tag.type.name !== "undefined") {
context.report(jsdocNode, "Unexpected @" + tag.title + " tag; function has no return statement.");
} else {
if (!tag.type) {
context.report(jsdocNode, "Missing JSDoc return type.");
}
if (tag.type.name !== "void" && !tag.description) {
context.report(jsdocNode, "Missing JSDoc return description.");
}
}
break;
case "constructor":
hasConstructor = true;
break;
}
// check tag preferences
if (prefer.hasOwnProperty(tag.title)) {
context.report(jsdocNode, "Use @{{name}} instead.", { name: prefer[tag.title] });
}
});
// check for functions missing @returns
if (!hasReturns && !hasConstructor) {
if (requireReturn || functionData.returnPresent) {
context.report(jsdocNode, "Missing JSDoc @returns for function.");
}
}
// check the parameters
var jsdocParams = Object.keys(params);
node.params.forEach(function(param, i) {
var name = param.name;
if (jsdocParams[i] && (name !== jsdocParams[i])) {
context.report(jsdocNode, "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", {
name: name,
jsdocName: jsdocParams[i]
});
} else if (!params[name]) {
context.report(jsdocNode, "Missing JSDoc for parameter '{{name}}'.", {
name: name
});
}
});
}
} |
JavaScript | function promptUser() {
console.log("Enter Manager's information.")
return inquirer
.prompt([
{
type: "input",
message: "Enter Manager Name:",
name: "name",
},
{
type: "input",
message: "Enter Manager ID:",
name: "id",
}, {
type: "input",
message: "Enter Manager Email:",
name: "email",
},
{
type: "input",
message: "Enter Office Number:",
name: "officeNumber",
},
])
.then(function (info) {
const manager = new Manager(
info.name,
info.id,
info.email,
info.officeNumber
);
employees.push(manager);
})
.then(function addEmployee() {
console.log("Enter new Employee's information.")
return inquirer
.prompt([
{
type: "list",
message: "Select Employee Role:",
name: "role",
choices: ["Engineer", "Intern"],
},
])
.then(function (input) {
switch (input.role) {
case "Engineer":
return inquirer
.prompt([
{
type: "input",
message: "Enter Employee Name:",
name: "name",
},
{
type: "input",
message: "Enter Employee ID:",
name: "id",
},
{
type: "input",
message: "Enter Employee Email:",
name: "email",
},
{
type: "input",
message: "Enter Github:",
name: "github",
},
{
type: "list",
message: "Add another team member?",
name: "answer",
choices: ["Yes", "No"],
},
])
.then(function (info) {
const engineer = new Engineer(
info.name,
info.id,
info.email,
info.github
);
employees.push(engineer);
switch (info.answer) {
case "Yes":
return addEmployee();
case "No":
return;
}
});
case "Intern":
return inquirer
.prompt([
{
type: "input",
message: "Enter Employee Name:",
name: "name",
},
{
type: "input",
message: "Enter Employee ID:",
name: "id",
},
{
type: "input",
message: "Enter Employee Email:",
name: "email",
},
{
type: "input",
message: "Enter School:",
name: "school",
},
{
type: "list",
message: "Add another team member?",
name: "answer",
choices: ["Yes", "No"],
},
])
.then(function (info) {
const intern = new Intern(
info.name,
info.id,
info.email,
info.school
);
employees.push(intern);
switch (info.answer) {
case "Yes":
return addEmployee();
case "No":
return;
}
});
}
});
});
} | function promptUser() {
console.log("Enter Manager's information.")
return inquirer
.prompt([
{
type: "input",
message: "Enter Manager Name:",
name: "name",
},
{
type: "input",
message: "Enter Manager ID:",
name: "id",
}, {
type: "input",
message: "Enter Manager Email:",
name: "email",
},
{
type: "input",
message: "Enter Office Number:",
name: "officeNumber",
},
])
.then(function (info) {
const manager = new Manager(
info.name,
info.id,
info.email,
info.officeNumber
);
employees.push(manager);
})
.then(function addEmployee() {
console.log("Enter new Employee's information.")
return inquirer
.prompt([
{
type: "list",
message: "Select Employee Role:",
name: "role",
choices: ["Engineer", "Intern"],
},
])
.then(function (input) {
switch (input.role) {
case "Engineer":
return inquirer
.prompt([
{
type: "input",
message: "Enter Employee Name:",
name: "name",
},
{
type: "input",
message: "Enter Employee ID:",
name: "id",
},
{
type: "input",
message: "Enter Employee Email:",
name: "email",
},
{
type: "input",
message: "Enter Github:",
name: "github",
},
{
type: "list",
message: "Add another team member?",
name: "answer",
choices: ["Yes", "No"],
},
])
.then(function (info) {
const engineer = new Engineer(
info.name,
info.id,
info.email,
info.github
);
employees.push(engineer);
switch (info.answer) {
case "Yes":
return addEmployee();
case "No":
return;
}
});
case "Intern":
return inquirer
.prompt([
{
type: "input",
message: "Enter Employee Name:",
name: "name",
},
{
type: "input",
message: "Enter Employee ID:",
name: "id",
},
{
type: "input",
message: "Enter Employee Email:",
name: "email",
},
{
type: "input",
message: "Enter School:",
name: "school",
},
{
type: "list",
message: "Add another team member?",
name: "answer",
choices: ["Yes", "No"],
},
])
.then(function (info) {
const intern = new Intern(
info.name,
info.id,
info.email,
info.school
);
employees.push(intern);
switch (info.answer) {
case "Yes":
return addEmployee();
case "No":
return;
}
});
}
});
});
} |
JavaScript | async function load() {
await loadWeb3();
window.contract = await loadContract();
} | async function load() {
await loadWeb3();
window.contract = await loadContract();
} |
JavaScript | function notify(message) {
console.log(message);
const parser = new DOMParser();
const dom = parser.parseFromString(message.dom, "text/html");
if (dom.documentElement.nodeName === "parsererror") {
console.error("error while parsing");
}
const article = createReadableVersion(dom);
console.log(article);
convertArticleToMarkdown(article, message.source).then((markdown) =>
downloadMarkdown(markdown, article)
);
} | function notify(message) {
console.log(message);
const parser = new DOMParser();
const dom = parser.parseFromString(message.dom, "text/html");
if (dom.documentElement.nodeName === "parsererror") {
console.error("error while parsing");
}
const article = createReadableVersion(dom);
console.log(article);
convertArticleToMarkdown(article, message.source).then((markdown) =>
downloadMarkdown(markdown, article)
);
} |
JavaScript | componentDidMount() {
axios
.get("http://localhost:5000/record/")
.then((response) => {
const record = response.data;
const { page, size } = this.state;
const currPage = paginate(record, page, size);
const totalAmount = record.reduce((acc, curr)=>{
let cur =curr.cashflow_amount
return acc + Number(cur);
}, 0)
console.log("total:", totalAmount);
this.setState({
...this.state,
record,
currPage,
totalAmount,
});
});
} | componentDidMount() {
axios
.get("http://localhost:5000/record/")
.then((response) => {
const record = response.data;
const { page, size } = this.state;
const currPage = paginate(record, page, size);
const totalAmount = record.reduce((acc, curr)=>{
let cur =curr.cashflow_amount
return acc + Number(cur);
}, 0)
console.log("total:", totalAmount);
this.setState({
...this.state,
record,
currPage,
totalAmount,
});
});
} |
JavaScript | componentWillUnmount() {
this.setState = (state,callback)=>{
return;
};
} | componentWillUnmount() {
this.setState = (state,callback)=>{
return;
};
} |
JavaScript | deleteRecord(id) {
axios
.delete("http://localhost:5000/" + id)
.then((response) => {
console.log(response.data);
});
this.setState({
record: this.state.records.filter((el) => el._id !== id),
});
} | deleteRecord(id) {
axios
.delete("http://localhost:5000/" + id)
.then((response) => {
console.log(response.data);
});
this.setState({
record: this.state.records.filter((el) => el._id !== id),
});
} |
JavaScript | render() {
const { page, size, currPage, totalAmount } = this.state;
return (
<div class="container-fluid" style={{ marginTop: 20 }}>
<div class="row">
<div class="col-12">
<div class="col-sm" role="alert" style={{fontWeight: "bold"}}>Total Balance: {totalAmount}</div>
<table class="table">
<thead class="thead-dark">
<tr>
<th>Concept</th>
<th>Amount</th>
<th>Date</th>
<th>Type</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{currPage &&
(
currPage.data.map((currentrecord, i) => {
return(
<tr key={currentrecord.id}>
<td style={{fontWeight: "bold"}}>{currentrecord.cashflow_concept}</td>
<td>{currentrecord.cashflow_amount}</td>
<td>{currentrecord.cashflow_date}</td>
<td>{currentrecord.cashflow_type}</td>
<td>
<Link to={"/edit/" + currentrecord._id}>Edit</Link> |
<Link to={"/delete/" + currentrecord._id}>Delete</Link>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
<div>
<div class="container-fluid" style={{ marginTop: 20 }}>
<div class="col-12">
<div class="col-sm" role="alert">page: {page}</div>
<div class="col-sm" role="alert">size: {size}</div>
</div>
</div>
<div class="container-fluid" style={{ marginTop: 20 }}>
<label class="col-12" for="inputGroupSelect01">Rows view options</label>
<select class="custom-select" id="inputGroupSelect01" name="size" id="size" onChange={this.handleChange}>
<option class="input-group mb-3" aria-label="Third group" selected>Choose...</option>
<option value="5">Five</option>
<option value="10">Ten</option>
<option value="20">Twenty</option>
</select>
</div>
</div>
</div>
<div class="btn-group mr-2" role="group" aria-label="Third group" style={{ marginTop: 20 }}>
<button type="button" class="btn btn-primary" onClick={this.previousPage}>Previous Page</button>
<button type="button" class="btn btn-secondary" onClick={this.nextPage}>Next Page</button>
</div>
</div>
);
} | render() {
const { page, size, currPage, totalAmount } = this.state;
return (
<div class="container-fluid" style={{ marginTop: 20 }}>
<div class="row">
<div class="col-12">
<div class="col-sm" role="alert" style={{fontWeight: "bold"}}>Total Balance: {totalAmount}</div>
<table class="table">
<thead class="thead-dark">
<tr>
<th>Concept</th>
<th>Amount</th>
<th>Date</th>
<th>Type</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{currPage &&
(
currPage.data.map((currentrecord, i) => {
return(
<tr key={currentrecord.id}>
<td style={{fontWeight: "bold"}}>{currentrecord.cashflow_concept}</td>
<td>{currentrecord.cashflow_amount}</td>
<td>{currentrecord.cashflow_date}</td>
<td>{currentrecord.cashflow_type}</td>
<td>
<Link to={"/edit/" + currentrecord._id}>Edit</Link> |
<Link to={"/delete/" + currentrecord._id}>Delete</Link>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
<div>
<div class="container-fluid" style={{ marginTop: 20 }}>
<div class="col-12">
<div class="col-sm" role="alert">page: {page}</div>
<div class="col-sm" role="alert">size: {size}</div>
</div>
</div>
<div class="container-fluid" style={{ marginTop: 20 }}>
<label class="col-12" for="inputGroupSelect01">Rows view options</label>
<select class="custom-select" id="inputGroupSelect01" name="size" id="size" onChange={this.handleChange}>
<option class="input-group mb-3" aria-label="Third group" selected>Choose...</option>
<option value="5">Five</option>
<option value="10">Ten</option>
<option value="20">Twenty</option>
</select>
</div>
</div>
</div>
<div class="btn-group mr-2" role="group" aria-label="Third group" style={{ marginTop: 20 }}>
<button type="button" class="btn btn-primary" onClick={this.previousPage}>Previous Page</button>
<button type="button" class="btn btn-secondary" onClick={this.nextPage}>Next Page</button>
</div>
</div>
);
} |
JavaScript | onChangecashflowConcept(e) {
this.setState({
cashflow_concept: e.target.value,
});
} | onChangecashflowConcept(e) {
this.setState({
cashflow_concept: e.target.value,
});
} |
JavaScript | onSubmit(e) {
e.preventDefault();
// When post request is sent to the create url, axios will add a new record(newcashflow) to the database.
const newcashflow = {
cashflow_concept: this.state.cashflow_concept,
cashflow_amount: this.state.cashflow_amount,
cashflow_date: this.state.cashflow_date,
cashflow_type: this.state.cashflow_type,
};
axios
.post("http://localhost:5000/record/add", newcashflow)
.then((res) => console.log(res.data));
// We will empty the state after posting the data to the database
this.setState({
cashflow_concept: "",
cashflow_amount: "",
cashflow_date: "",
cashflow_type: "",
});
} | onSubmit(e) {
e.preventDefault();
// When post request is sent to the create url, axios will add a new record(newcashflow) to the database.
const newcashflow = {
cashflow_concept: this.state.cashflow_concept,
cashflow_amount: this.state.cashflow_amount,
cashflow_date: this.state.cashflow_date,
cashflow_type: this.state.cashflow_type,
};
axios
.post("http://localhost:5000/record/add", newcashflow)
.then((res) => console.log(res.data));
// We will empty the state after posting the data to the database
this.setState({
cashflow_concept: "",
cashflow_amount: "",
cashflow_date: "",
cashflow_type: "",
});
} |
JavaScript | render() {
return (
<div class="container" style={{ marginTop: 20 }}>
<h3>Create New Record</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Concept: </label>
<input
type="text"
className="form-control"
value={this.state.cashflow_concept}
onChange={this.onChangecashflowConcept}
/>
</div>
<div className="form-group">
<label>Amount: </label>
<input
type="text"
className="form-control"
value={this.state.cashflow_amount}
onChange={this.onChangecashflowAmount}
/>
</div>
<div className="form-group">
<label>Date: </label>
<input
type="text"
className="form-control"
value={this.state.cashflow_date}
onChange={this.onChangecashflowDate}
/>
</div>
<div className="form-group">
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="radio"
name="priorityOptions"
id="priorityLow"
value="Income"
checked={this.state.cashflow_type === "Income"}
onChange={this.onChangecashflowType}
/>
<label className="form-check-label">Income</label>
</div>
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="radio"
name="priorityOptions"
id="priorityMedium"
value="Out"
checked={this.state.cashflow_type === "Out"}
onChange={this.onChangecashflowType}
/>
<label className="form-check-label">Out</label>
</div>
</div>
<div className="form-group">
<input
type="submit"
value="Create movement"
className="btn btn-primary"
/>
</div>
</form>
</div>
);
} | render() {
return (
<div class="container" style={{ marginTop: 20 }}>
<h3>Create New Record</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Concept: </label>
<input
type="text"
className="form-control"
value={this.state.cashflow_concept}
onChange={this.onChangecashflowConcept}
/>
</div>
<div className="form-group">
<label>Amount: </label>
<input
type="text"
className="form-control"
value={this.state.cashflow_amount}
onChange={this.onChangecashflowAmount}
/>
</div>
<div className="form-group">
<label>Date: </label>
<input
type="text"
className="form-control"
value={this.state.cashflow_date}
onChange={this.onChangecashflowDate}
/>
</div>
<div className="form-group">
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="radio"
name="priorityOptions"
id="priorityLow"
value="Income"
checked={this.state.cashflow_type === "Income"}
onChange={this.onChangecashflowType}
/>
<label className="form-check-label">Income</label>
</div>
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="radio"
name="priorityOptions"
id="priorityMedium"
value="Out"
checked={this.state.cashflow_type === "Out"}
onChange={this.onChangecashflowType}
/>
<label className="form-check-label">Out</label>
</div>
</div>
<div className="form-group">
<input
type="submit"
value="Create movement"
className="btn btn-primary"
/>
</div>
</form>
</div>
);
} |
JavaScript | function load(domain) {
openableToolbox = false
setStatus("⌛", "Loading saved data...")
toolsBtn.innerHTML = "⌛"
editor.setTheme("ace/theme/monokai")
editor.setShowPrintMargin(false)
editor.setFontSize("14px")
// Make the editor read-only until it's ready
editor.setReadOnly(true)
// Save current domain
selectedDomain = domain
// Load saved data for this domain
chrome.storage.sync.get(null, (scripts) => {
const setContent = (code) => {
code = decompress(code)
lastContent = code
editor.session.setValue(code)
}
let isDefault = true
if (scripts[domain] !== undefined) {
setContent(scripts[domain])
editor.gotoLine(Infinity, Infinity)
isDefault = false
} else if (domain === "<prelude>") {
setContent(DEFAULT_PRELUDE)
} else if (domain === "<generic>") {
setContent(DEFAULT_GENERIC)
} else if (domain === currentDomain) {
setContent(DEFAULT_DOMAIN_SCRIPT)
} else {
setContent("")
}
editor.setReadOnly(false)
editor.focus()
console.debug("Loaded script for domain: " + domain)
setStatus("✔️" + (isDefault ? "🗑️" : ""), "Loaded saved script")
toolsBtn.innerHTML = "🛠️"
openableToolbox = true
})
} | function load(domain) {
openableToolbox = false
setStatus("⌛", "Loading saved data...")
toolsBtn.innerHTML = "⌛"
editor.setTheme("ace/theme/monokai")
editor.setShowPrintMargin(false)
editor.setFontSize("14px")
// Make the editor read-only until it's ready
editor.setReadOnly(true)
// Save current domain
selectedDomain = domain
// Load saved data for this domain
chrome.storage.sync.get(null, (scripts) => {
const setContent = (code) => {
code = decompress(code)
lastContent = code
editor.session.setValue(code)
}
let isDefault = true
if (scripts[domain] !== undefined) {
setContent(scripts[domain])
editor.gotoLine(Infinity, Infinity)
isDefault = false
} else if (domain === "<prelude>") {
setContent(DEFAULT_PRELUDE)
} else if (domain === "<generic>") {
setContent(DEFAULT_GENERIC)
} else if (domain === currentDomain) {
setContent(DEFAULT_DOMAIN_SCRIPT)
} else {
setContent("")
}
editor.setReadOnly(false)
editor.focus()
console.debug("Loaded script for domain: " + domain)
setStatus("✔️" + (isDefault ? "🗑️" : ""), "Loaded saved script")
toolsBtn.innerHTML = "🛠️"
openableToolbox = true
})
} |
JavaScript | function loadingError(msg) {
editor.session.setValue(`ERROR: ${msg}`)
setStatus("❌", msg)
editor.setReadOnly(true)
if (editor.renderer.$cursorLayer) {
editor.renderer.$cursorLayer.element.style.display = "none"
}
} | function loadingError(msg) {
editor.session.setValue(`ERROR: ${msg}`)
setStatus("❌", msg)
editor.setReadOnly(true)
if (editor.renderer.$cursorLayer) {
editor.renderer.$cursorLayer.element.style.display = "none"
}
} |
JavaScript | function onChange() {
if (isSaving) {
pendingUpdate = true
}
setStatus("⌛", "Saving changes...")
const code = editor.session.getValue()
const conclude = (status, end) => {
setStatus(...status)
isSaving = false
if (pendingUpdate) {
pendingUpdate = false
setTimeout(() => onChange(), 1)
resolve()
}
end()
}
return new Promise((resolve, reject) => {
saveDomainScript(selectedDomain, code)
.then((status) => conclude(status, resolve))
.catch((status) => conclude(status, reject))
})
} | function onChange() {
if (isSaving) {
pendingUpdate = true
}
setStatus("⌛", "Saving changes...")
const code = editor.session.getValue()
const conclude = (status, end) => {
setStatus(...status)
isSaving = false
if (pendingUpdate) {
pendingUpdate = false
setTimeout(() => onChange(), 1)
resolve()
}
end()
}
return new Promise((resolve, reject) => {
saveDomainScript(selectedDomain, code)
.then((status) => conclude(status, resolve))
.catch((status) => conclude(status, reject))
})
} |
JavaScript | function computeSaving(domain, code) {
return new Promise((resolve) => {
// Don't save empty scripts
if (code.length === 0) {
return resolve({
action: "remove",
status: ["✔️🗑️", `Saved changes (removed script from storage since it is empty)`],
})
}
// Don't save default scripts
if (
(domain === "<prelude>" && code === DEFAULT_PRELUDE) ||
(domain === "<generic>" && code === DEFAULT_GENERIC) ||
(domain !== "<prelude>" && domain !== "<generic>" && code === DEFAULT_DOMAIN_SCRIPT)
) {
resolve({
action: "remove",
status: ["✔️🗑️", `Saved changes (removed script from storage since it is equivalent to the default script)`],
})
}
console.debug(`[${domain}] Compressing code (${(code.length / 1024).toFixed(2)}) Kb...`)
const compressed = COMPRESSION_HEADER + LZString.compressToUTF16(code)
// No worry about a potential division by zero here as a non-empty code cannot be empty once compressed
const ratio = (code.length / compressed.length).toFixed(1)
console.debug(`[${domain}] Compressed to ${(code.length / 1024).toFixed(2)} Kb (ratio = ${ratio})`)
if (ratio < 1) {
console.debug(
ratio === 1
? `[${domain}] Ratio is 1, so there is no point to keeping the compressed version.`
: `[${domain}] Ratio is negative so the original code will be stored directly instead.`
)
}
resolve(
ratio > 1
? {
action: "save",
content: compressed,
status: [
"✔️📦",
`Saved changes (${sizeInKB(code.length)} plain, ${sizeInKB(
compressed.length
)} compressed, ratio = ${ratio}`,
],
}
: // Use uncompressed version if compressed version is larger
{
action: "save",
content: code,
status: ["✔️", `Saved changes (${sizeInKB(code.length)})`],
}
)
})
} | function computeSaving(domain, code) {
return new Promise((resolve) => {
// Don't save empty scripts
if (code.length === 0) {
return resolve({
action: "remove",
status: ["✔️🗑️", `Saved changes (removed script from storage since it is empty)`],
})
}
// Don't save default scripts
if (
(domain === "<prelude>" && code === DEFAULT_PRELUDE) ||
(domain === "<generic>" && code === DEFAULT_GENERIC) ||
(domain !== "<prelude>" && domain !== "<generic>" && code === DEFAULT_DOMAIN_SCRIPT)
) {
resolve({
action: "remove",
status: ["✔️🗑️", `Saved changes (removed script from storage since it is equivalent to the default script)`],
})
}
console.debug(`[${domain}] Compressing code (${(code.length / 1024).toFixed(2)}) Kb...`)
const compressed = COMPRESSION_HEADER + LZString.compressToUTF16(code)
// No worry about a potential division by zero here as a non-empty code cannot be empty once compressed
const ratio = (code.length / compressed.length).toFixed(1)
console.debug(`[${domain}] Compressed to ${(code.length / 1024).toFixed(2)} Kb (ratio = ${ratio})`)
if (ratio < 1) {
console.debug(
ratio === 1
? `[${domain}] Ratio is 1, so there is no point to keeping the compressed version.`
: `[${domain}] Ratio is negative so the original code will be stored directly instead.`
)
}
resolve(
ratio > 1
? {
action: "save",
content: compressed,
status: [
"✔️📦",
`Saved changes (${sizeInKB(code.length)} plain, ${sizeInKB(
compressed.length
)} compressed, ratio = ${ratio}`,
],
}
: // Use uncompressed version if compressed version is larger
{
action: "save",
content: code,
status: ["✔️", `Saved changes (${sizeInKB(code.length)})`],
}
)
})
} |
JavaScript | function saveDomainScript(domain, code) {
return new Promise(async (resolve, reject) => {
function callback() {
if (chrome.runtime.lastError) {
const errMsg = `Failed to save changes: ${chrome.runtime.lastError.message}`
console.error(`[${domain}] Failed to save changes`, chrome.runtime.lastError)
reject(["❌", errMsg])
} else {
console.debug(
action === "remove"
? `[${domain}] Removed script from storage`
: `[${domain}] Saved script to storage (${(content.length / 1024).toFixed(2)} Kb)`
)
resolve(status)
}
}
const { action, content, status } = await computeSaving(selectedDomain, code)
if (action === "remove") {
chrome.storage.sync.remove(selectedDomain, callback)
} else {
chrome.storage.sync.set({ [selectedDomain]: content }, () => callback())
}
})
} | function saveDomainScript(domain, code) {
return new Promise(async (resolve, reject) => {
function callback() {
if (chrome.runtime.lastError) {
const errMsg = `Failed to save changes: ${chrome.runtime.lastError.message}`
console.error(`[${domain}] Failed to save changes`, chrome.runtime.lastError)
reject(["❌", errMsg])
} else {
console.debug(
action === "remove"
? `[${domain}] Removed script from storage`
: `[${domain}] Saved script to storage (${(content.length / 1024).toFixed(2)} Kb)`
)
resolve(status)
}
}
const { action, content, status } = await computeSaving(selectedDomain, code)
if (action === "remove") {
chrome.storage.sync.remove(selectedDomain, callback)
} else {
chrome.storage.sync.set({ [selectedDomain]: content }, () => callback())
}
})
} |
JavaScript | function startupFetchInternal(uri) {
return new Promise((resolve) => {
fetch(uri)
.then((response) =>
response
.text()
.then((text) => resolve(text))
.catch(() => loadingError(`Failed to decode text response from internal URI '${uri}'`))
)
.catch(() => loadingError(`Failed to fetch internal URI '${uri}'`))
})
} | function startupFetchInternal(uri) {
return new Promise((resolve) => {
fetch(uri)
.then((response) =>
response
.text()
.then((text) => resolve(text))
.catch(() => loadingError(`Failed to decode text response from internal URI '${uri}'`))
)
.catch(() => loadingError(`Failed to fetch internal URI '${uri}'`))
})
} |
JavaScript | function download(filename, content) {
// A link must be created in order to download the blob we'll create in an instant
const a = document.createElement("a")
// Ensure the link is not visible
a.style.display = "none"
document.body.appendChild(a)
// Create a blob containing our content
const blob = new Blob([content], { type: "octet/stream" })
const url = window.URL.createObjectURL(blob)
a.href = url
a.download = filename
// Download it
a.click()
// Revoke it to avoid keeping it in memory uselessly
window.URL.revokeObjectURL(url)
// Remove the link
a.remove()
} | function download(filename, content) {
// A link must be created in order to download the blob we'll create in an instant
const a = document.createElement("a")
// Ensure the link is not visible
a.style.display = "none"
document.body.appendChild(a)
// Create a blob containing our content
const blob = new Blob([content], { type: "octet/stream" })
const url = window.URL.createObjectURL(blob)
a.href = url
a.download = filename
// Download it
a.click()
// Revoke it to avoid keeping it in memory uselessly
window.URL.revokeObjectURL(url)
// Remove the link
a.remove()
} |
JavaScript | function upload() {
return new Promise((resolve, reject) => {
const uploadBtn = document.createElement("input")
uploadBtn.setAttribute("type", "file")
uploadBtn.style.display = "none"
uploadBtn.addEventListener(
"change",
() => {
const file = uploadBtn.files[0]
if (!file) {
reject()
} else {
uploadBtn.remove()
resolve(file)
}
},
false
)
document.body.appendChild(uploadBtn)
uploadBtn.click()
})
} | function upload() {
return new Promise((resolve, reject) => {
const uploadBtn = document.createElement("input")
uploadBtn.setAttribute("type", "file")
uploadBtn.style.display = "none"
uploadBtn.addEventListener(
"change",
() => {
const file = uploadBtn.files[0]
if (!file) {
reject()
} else {
uploadBtn.remove()
resolve(file)
}
},
false
)
document.body.appendChild(uploadBtn)
uploadBtn.click()
})
} |
JavaScript | function readUploadedFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.addEventListener("load", () => {
if (reader.result.length > 1024 * 1024) {
reject(new Error("file exceeds 1 MB"))
} else {
resolve(reader.result)
}
})
reader.addEventListener("error", (err) => reject(err))
reader.readAsText(file)
})
} | function readUploadedFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.addEventListener("load", () => {
if (reader.result.length > 1024 * 1024) {
reject(new Error("file exceeds 1 MB"))
} else {
resolve(reader.result)
}
})
reader.addEventListener("error", (err) => reject(err))
reader.readAsText(file)
})
} |
JavaScript | function decompress(content) {
if (!content.startsWith(COMPRESSION_HEADER)) {
return content
}
console.debug(`Decompressing ${(content.length / 1024).toFixed(2)} Kb of data...`)
let decompressed = LZString.decompressFromUTF16(content.substr(COMPRESSION_HEADER.length))
console.debug("Done!")
return decompressed
} | function decompress(content) {
if (!content.startsWith(COMPRESSION_HEADER)) {
return content
}
console.debug(`Decompressing ${(content.length / 1024).toFixed(2)} Kb of data...`)
let decompressed = LZString.decompressFromUTF16(content.substr(COMPRESSION_HEADER.length))
console.debug("Done!")
return decompressed
} |
JavaScript | async function importAll(scripts) {
const toSave = {}
const toDel = []
for (const domain of Reflect.ownKeys(scripts)) {
const { action, content } = await computeSaving(domain, scripts[domain])
if (action === "remove") {
toDel.push(domain)
} else {
toSave[domain] = content
}
}
await new Promise((resolve) => chrome.storage.sync.remove(toDel, resolve))
const delError = chrome.runtime.lastError
await new Promise((resolve) => chrome.storage.sync.set(toSave, resolve))
const saveError = chrome.runtime.lastError
return new Promise((resolve, reject) => {
if (delError || saveError) {
reject({ delError, saveError })
} else {
resolve({ removed: toDel, saved: toSave })
}
})
} | async function importAll(scripts) {
const toSave = {}
const toDel = []
for (const domain of Reflect.ownKeys(scripts)) {
const { action, content } = await computeSaving(domain, scripts[domain])
if (action === "remove") {
toDel.push(domain)
} else {
toSave[domain] = content
}
}
await new Promise((resolve) => chrome.storage.sync.remove(toDel, resolve))
const delError = chrome.runtime.lastError
await new Promise((resolve) => chrome.storage.sync.set(toSave, resolve))
const saveError = chrome.runtime.lastError
return new Promise((resolve, reject) => {
if (delError || saveError) {
reject({ delError, saveError })
} else {
resolve({ removed: toDel, saved: toSave })
}
})
} |
JavaScript | async function exportAll() {
const scripts = await new Promise((resolve) => chrome.storage.sync.get(null, resolve))
const exportable = {}
for (const key of Reflect.ownKeys(scripts)) {
exportable[key] = decompress(scripts[key])
}
download("injector-scripts.json", JSON.stringify(exportable, null, 4))
} | async function exportAll() {
const scripts = await new Promise((resolve) => chrome.storage.sync.get(null, resolve))
const exportable = {}
for (const key of Reflect.ownKeys(scripts)) {
exportable[key] = decompress(scripts[key])
}
download("injector-scripts.json", JSON.stringify(exportable, null, 4))
} |
JavaScript | function fetchInternal(uri) {
return new Promise((resolve, reject) => {
// 1. Fetch the URI
fetch(uri)
.then((response) =>
response
// 2. Get its body as plain text
.text()
.then((text) => {
const size = (text.length / 1024).toFixed(2)
console.debug(`Successfully loaded internal URI '${uri}' (${size} Kb)`)
resolve(text)
})
.catch(() => {
console.error(`Failed to decode text response from internal URI '${uri}'`)
reject()
})
)
.catch(() => {
console.error(`Failed to fetch internal URI '${uri}'`)
reject()
})
})
} | function fetchInternal(uri) {
return new Promise((resolve, reject) => {
// 1. Fetch the URI
fetch(uri)
.then((response) =>
response
// 2. Get its body as plain text
.text()
.then((text) => {
const size = (text.length / 1024).toFixed(2)
console.debug(`Successfully loaded internal URI '${uri}' (${size} Kb)`)
resolve(text)
})
.catch(() => {
console.error(`Failed to decode text response from internal URI '${uri}'`)
reject()
})
)
.catch(() => {
console.error(`Failed to fetch internal URI '${uri}'`)
reject()
})
})
} |
JavaScript | function decompress(content) {
if (!content.startsWith(COMPRESSION_HEADER)) {
return content
}
return LZString.decompressFromUTF16(content.substr(COMPRESSION_HEADER.length))
} | function decompress(content) {
if (!content.startsWith(COMPRESSION_HEADER)) {
return content
}
return LZString.decompressFromUTF16(content.substr(COMPRESSION_HEADER.length))
} |
JavaScript | function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 10001, //< Default Max Timeout is 10s
start = new Date().getTime(),
condition = false,
interval = setInterval(function () {
if ((new Date().getTime() - start < maxtimeOutMillis) && !condition) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof testFx === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if (!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
console.log("");
typeof onReady === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 100); //< repeat check every 100ms
} | function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 10001, //< Default Max Timeout is 10s
start = new Date().getTime(),
condition = false,
interval = setInterval(function () {
if ((new Date().getTime() - start < maxtimeOutMillis) && !condition) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof testFx === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if (!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
console.log("");
typeof onReady === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 100); //< repeat check every 100ms
} |
JavaScript | function tick(digit) {
var $digits = this.find('ul'),
data = this.data();
if(!data.vals || $digits.length == 0) {
if(data.intervalId) {
clearTimeout(data.intervalId);
this.data('intervalId', null);
}
if(data.callback) {
data.callback();
}
return;
}
if(digit == undefined) {
digit = data.iSec;
}
var n = data.vals[digit],
$ul = $digits.eq(digit),
$li = $ul.children(),
step = data.countdown ? -1 : 1;
$li.eq(1).html(n);
n += step;
if(digit == data.iSec) {
var tickTimeout = data.tickTimeout,
timeDiff = $.now() - data.ttStartTime;
data.sec += step;
tickTimeout += Math.abs(data.seconds - data.sec) * tickTimeout - timeDiff;
data.intervalId = setTimeout(function() { tick.call(me); }, tickTimeout);
}
if(n < 0 || n > data.limits[digit]) {
if(n < 0) {
n = data.limits[digit];
if(digit == data.iHour && data.displayDays > 0 && digit > 0 && data.vals[digit-1] == 0) // fix for hours when day changing
n = 3;
}
else {
n = 0;
}
if(digit > 0) {
tick.call(this, digit-1);
}
}
$li.eq(0).html(n);
var me = this;
if($.support.transition) {
$ul.addClass('transition');
$ul.css({top:0});
setTimeout(function() {
$ul.removeClass('transition');
$li.eq(1).html(n);
$ul.css({top:"-"+ data.height +"px"});
if(step > 0 || digit != data.iSec) {
return;
}
if(data.sec == data.countdownAlertLimit) {
$digits.parent().addClass('timeTo-alert');
}
if(data.sec === 0) {
$digits.parent().removeClass('timeTo-alert');
if(data.intervalId) {
clearTimeout(data.intervalId);
me.data('intervalId', null);
}
if(typeof data.callback === 'function') {
data.callback();
}
}
}, 410);
}
else {
$ul.stop().animate({top:0}, 400, digit != data.iSec ? null : function() {
$li.eq(1).html(n);
$ul.css({top:"-"+ data.height +"px"});
if(step > 0 || digit != data.iSec) {
return;
}
if(data.sec == data.countdownAlertLimit) {
$digits.parent().addClass('timeTo-alert');
}
else if(data.sec == 0) {
$digits.parent().removeClass('timeTo-alert');
if(data.intervalId) {
clearTimeout(data.intervalId);
me.data('intervalId', null);
}
if(typeof data.callback === 'function') {
data.callback();
}
}
});
}
data.vals[digit] = n;
} | function tick(digit) {
var $digits = this.find('ul'),
data = this.data();
if(!data.vals || $digits.length == 0) {
if(data.intervalId) {
clearTimeout(data.intervalId);
this.data('intervalId', null);
}
if(data.callback) {
data.callback();
}
return;
}
if(digit == undefined) {
digit = data.iSec;
}
var n = data.vals[digit],
$ul = $digits.eq(digit),
$li = $ul.children(),
step = data.countdown ? -1 : 1;
$li.eq(1).html(n);
n += step;
if(digit == data.iSec) {
var tickTimeout = data.tickTimeout,
timeDiff = $.now() - data.ttStartTime;
data.sec += step;
tickTimeout += Math.abs(data.seconds - data.sec) * tickTimeout - timeDiff;
data.intervalId = setTimeout(function() { tick.call(me); }, tickTimeout);
}
if(n < 0 || n > data.limits[digit]) {
if(n < 0) {
n = data.limits[digit];
if(digit == data.iHour && data.displayDays > 0 && digit > 0 && data.vals[digit-1] == 0) // fix for hours when day changing
n = 3;
}
else {
n = 0;
}
if(digit > 0) {
tick.call(this, digit-1);
}
}
$li.eq(0).html(n);
var me = this;
if($.support.transition) {
$ul.addClass('transition');
$ul.css({top:0});
setTimeout(function() {
$ul.removeClass('transition');
$li.eq(1).html(n);
$ul.css({top:"-"+ data.height +"px"});
if(step > 0 || digit != data.iSec) {
return;
}
if(data.sec == data.countdownAlertLimit) {
$digits.parent().addClass('timeTo-alert');
}
if(data.sec === 0) {
$digits.parent().removeClass('timeTo-alert');
if(data.intervalId) {
clearTimeout(data.intervalId);
me.data('intervalId', null);
}
if(typeof data.callback === 'function') {
data.callback();
}
}
}, 410);
}
else {
$ul.stop().animate({top:0}, 400, digit != data.iSec ? null : function() {
$li.eq(1).html(n);
$ul.css({top:"-"+ data.height +"px"});
if(step > 0 || digit != data.iSec) {
return;
}
if(data.sec == data.countdownAlertLimit) {
$digits.parent().addClass('timeTo-alert');
}
else if(data.sec == 0) {
$digits.parent().removeClass('timeTo-alert');
if(data.intervalId) {
clearTimeout(data.intervalId);
me.data('intervalId', null);
}
if(typeof data.callback === 'function') {
data.callback();
}
}
});
}
data.vals[digit] = n;
} |
JavaScript | function callPlayer( iframe, func, args ) {
var message = JSON.stringify({
"event": "command",
"func": func,
"args": args || []
});
if ( iframe.src.indexOf( "youtube.com/embed" ) !== -1) {
iframe.contentWindow.postMessage( message, "*" );
}
} | function callPlayer( iframe, func, args ) {
var message = JSON.stringify({
"event": "command",
"func": func,
"args": args || []
});
if ( iframe.src.indexOf( "youtube.com/embed" ) !== -1) {
iframe.contentWindow.postMessage( message, "*" );
}
} |
JavaScript | function radii(props) {
var r = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var _ref = props || {},
rounded = _ref.rounded,
pill = _ref.pill,
circle = _ref.circle;
var borderRadius = void 0;
if (rounded === true) {
borderRadius = r;
} else if (rounded === false) {
borderRadius = 0;
}
if (typeof rounded === 'string') {
var obj = {
top: r + 'px ' + r + 'px 0 0',
right: '0 ' + r + 'px ' + r + 'px 0',
bottom: '0 0 ' + r + 'px ' + r + 'px',
left: r + 'px 0 0 ' + r + 'px'
};
borderRadius = obj[rounded] || null;
}
if (pill || circle) {
borderRadius = 99999;
}
if (typeof borderRadius === 'undefined') {
return {};
} else {
return { borderRadius: borderRadius };
}
} | function radii(props) {
var r = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var _ref = props || {},
rounded = _ref.rounded,
pill = _ref.pill,
circle = _ref.circle;
var borderRadius = void 0;
if (rounded === true) {
borderRadius = r;
} else if (rounded === false) {
borderRadius = 0;
}
if (typeof rounded === 'string') {
var obj = {
top: r + 'px ' + r + 'px 0 0',
right: '0 ' + r + 'px ' + r + 'px 0',
bottom: '0 0 ' + r + 'px ' + r + 'px',
left: r + 'px 0 0 ' + r + 'px'
};
borderRadius = obj[rounded] || null;
}
if (pill || circle) {
borderRadius = 99999;
}
if (typeof borderRadius === 'undefined') {
return {};
} else {
return { borderRadius: borderRadius };
}
} |
JavaScript | function loadPageInMain(url) {
if (loopingAction){
window.clearInterval(loopingAction);
loopingAction = null;
}
loadPage($('#page_content'), url, true, function(response, status, xhr){
if ( status == "error" ) {
$('#page_content').html('Error');
$('#page_content').html(response);
}
});
} | function loadPageInMain(url) {
if (loopingAction){
window.clearInterval(loopingAction);
loopingAction = null;
}
loadPage($('#page_content'), url, true, function(response, status, xhr){
if ( status == "error" ) {
$('#page_content').html('Error');
$('#page_content').html(response);
}
});
} |
JavaScript | function postHtml(uriToPost) {
$.ajax({
url : uriToPost,
type : 'POST',
dataType: 'html',
success : replaceDocument,
error: replaceDocument
});
} | function postHtml(uriToPost) {
$.ajax({
url : uriToPost,
type : 'POST',
dataType: 'html',
success : replaceDocument,
error: replaceDocument
});
} |
JavaScript | async function retryTxn(n, max, client, operation, callback) {
await client.query("BEGIN;");
while (true) {
n++;
if (n === max) {
throw new Error("Max retry count reached.");
}
try {
await operation(client, callback);
await client.query("COMMIT;");
return;
} catch (err) {
if (err.code !== "40001") {
return callback(err);
} else {
console.log("Transaction failed. Retrying transaction.");
console.log(err.message);
await client.query("ROLLBACK;", () => {
console.log("Rolling back transaction.");
});
await new Promise((r) => setTimeout(r, 2 ** n * 1000));
}
}
}
} | async function retryTxn(n, max, client, operation, callback) {
await client.query("BEGIN;");
while (true) {
n++;
if (n === max) {
throw new Error("Max retry count reached.");
}
try {
await operation(client, callback);
await client.query("COMMIT;");
return;
} catch (err) {
if (err.code !== "40001") {
return callback(err);
} else {
console.log("Transaction failed. Retrying transaction.");
console.log(err.message);
await client.query("ROLLBACK;", () => {
console.log("Rolling back transaction.");
});
await new Promise((r) => setTimeout(r, 2 ** n * 1000));
}
}
}
} |
JavaScript | async function initTable(client, callback) {
let i = 0;
while (i < accountValues.length) {
accountValues[i] = await uuidv4();
i++;
}
const insertStatement =
"INSERT INTO accounts (id, balance) VALUES ($1, 1000), ($2, 250), ($3, 0);";
await client.query(insertStatement, accountValues, callback);
const selectBalanceStatement = "SELECT id, balance FROM accounts;";
await client.query(selectBalanceStatement, callback);
} | async function initTable(client, callback) {
let i = 0;
while (i < accountValues.length) {
accountValues[i] = await uuidv4();
i++;
}
const insertStatement =
"INSERT INTO accounts (id, balance) VALUES ($1, 1000), ($2, 250), ($3, 0);";
await client.query(insertStatement, accountValues, callback);
const selectBalanceStatement = "SELECT id, balance FROM accounts;";
await client.query(selectBalanceStatement, callback);
} |
JavaScript | async function transferFunds(client, callback) {
const from = accountValues[0];
const to = accountValues[1];
const amount = 100;
const selectFromBalanceStatement =
"SELECT balance FROM accounts WHERE id = $1;";
const selectFromValues = [from];
await client.query(
selectFromBalanceStatement,
selectFromValues,
(err, res) => {
if (err) {
return callback(err);
} else if (res.rows.length === 0) {
console.log("account not found in table");
return callback(err);
}
var acctBal = res.rows[0].balance;
if (acctBal < amount) {
return callback(new Error("insufficient funds"));
}
}
);
const updateFromBalanceStatement =
"UPDATE accounts SET balance = balance - $1 WHERE id = $2;";
const updateFromValues = [amount, from];
await client.query(updateFromBalanceStatement, updateFromValues, callback);
const updateToBalanceStatement =
"UPDATE accounts SET balance = balance + $1 WHERE id = $2;";
const updateToValues = [amount, to];
await client.query(updateToBalanceStatement, updateToValues, callback);
const selectBalanceStatement = "SELECT id, balance FROM accounts;";
await client.query(selectBalanceStatement, callback);
} | async function transferFunds(client, callback) {
const from = accountValues[0];
const to = accountValues[1];
const amount = 100;
const selectFromBalanceStatement =
"SELECT balance FROM accounts WHERE id = $1;";
const selectFromValues = [from];
await client.query(
selectFromBalanceStatement,
selectFromValues,
(err, res) => {
if (err) {
return callback(err);
} else if (res.rows.length === 0) {
console.log("account not found in table");
return callback(err);
}
var acctBal = res.rows[0].balance;
if (acctBal < amount) {
return callback(new Error("insufficient funds"));
}
}
);
const updateFromBalanceStatement =
"UPDATE accounts SET balance = balance - $1 WHERE id = $2;";
const updateFromValues = [amount, from];
await client.query(updateFromBalanceStatement, updateFromValues, callback);
const updateToBalanceStatement =
"UPDATE accounts SET balance = balance + $1 WHERE id = $2;";
const updateToValues = [amount, to];
await client.query(updateToBalanceStatement, updateToValues, callback);
const selectBalanceStatement = "SELECT id, balance FROM accounts;";
await client.query(selectBalanceStatement, callback);
} |
JavaScript | async function deleteAccounts(client, callback) {
const deleteStatement = "DELETE FROM accounts WHERE id = $1;";
await client.query(deleteStatement, [accountValues[2]], callback);
const selectBalanceStatement = "SELECT id, balance FROM accounts;";
await client.query(selectBalanceStatement, callback);
} | async function deleteAccounts(client, callback) {
const deleteStatement = "DELETE FROM accounts WHERE id = $1;";
await client.query(deleteStatement, [accountValues[2]], callback);
const selectBalanceStatement = "SELECT id, balance FROM accounts;";
await client.query(selectBalanceStatement, callback);
} |
JavaScript | function storeProducts() {
let stringifiedProducts = JSON.stringify(productArray);
console.log(stringifiedProducts);
localStorage.setItem('product', stringifiedProducts);
} | function storeProducts() {
let stringifiedProducts = JSON.stringify(productArray);
console.log(stringifiedProducts);
localStorage.setItem('product', stringifiedProducts);
} |
JavaScript | function socketSubscriberPublishUser() {
return {
type: SOCKET_SUBSCRIBER_PUBLISH_USER,
};
} | function socketSubscriberPublishUser() {
return {
type: SOCKET_SUBSCRIBER_PUBLISH_USER,
};
} |
JavaScript | function socketSubscriberPublishUserFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_PUBLISH_USER_FAILURE,
};
} | function socketSubscriberPublishUserFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_PUBLISH_USER_FAILURE,
};
} |
JavaScript | function socketSubscriberPublishUserSuccess({ userId, userToken }) {
return {
payload: { userId, userToken },
type: SOCKET_SUBSCRIBER_PUBLISH_USER_SUCCESS,
};
} | function socketSubscriberPublishUserSuccess({ userId, userToken }) {
return {
payload: { userId, userToken },
type: SOCKET_SUBSCRIBER_PUBLISH_USER_SUCCESS,
};
} |
JavaScript | function socketSubscriberSubscribeActionsFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_SUBSCRIBE_ACTIONS_FAILURE,
};
} | function socketSubscriberSubscribeActionsFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_SUBSCRIBE_ACTIONS_FAILURE,
};
} |
JavaScript | function socketSubscriberSubscribeActionsSuccess() {
return {
type: SOCKET_SUBSCRIBER_SUBSCRIBE_ACTIONS_SUCCESS,
};
} | function socketSubscriberSubscribeActionsSuccess() {
return {
type: SOCKET_SUBSCRIBER_SUBSCRIBE_ACTIONS_SUCCESS,
};
} |
JavaScript | function socketSubscriberSubscribeSession({ sessionId }) {
return {
payload: { sessionId },
type: SOCKET_SUBSCRIBER_SUBSCRIBE_SESSION,
};
} | function socketSubscriberSubscribeSession({ sessionId }) {
return {
payload: { sessionId },
type: SOCKET_SUBSCRIBER_SUBSCRIBE_SESSION,
};
} |
JavaScript | function socketSubscriberSubscribeSessionFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_SUBSCRIBE_SESSION_FAILURE,
};
} | function socketSubscriberSubscribeSessionFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_SUBSCRIBE_SESSION_FAILURE,
};
} |
JavaScript | function socketSubscriberSubscribeSessionSuccess({
sessionId,
sessionIsLivestream,
sessionTimestamp,
sessionTopic,
sessionUsername,
}) {
return {
payload: {
sessionId,
sessionIsLivestream,
sessionTimestamp,
sessionTopic,
sessionUsername,
},
type: SOCKET_SUBSCRIBER_SUBSCRIBE_SESSION_SUCCESS,
};
} | function socketSubscriberSubscribeSessionSuccess({
sessionId,
sessionIsLivestream,
sessionTimestamp,
sessionTopic,
sessionUsername,
}) {
return {
payload: {
sessionId,
sessionIsLivestream,
sessionTimestamp,
sessionTopic,
sessionUsername,
},
type: SOCKET_SUBSCRIBER_SUBSCRIBE_SESSION_SUCCESS,
};
} |
JavaScript | function socketSubscriberSubscribeUsersFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_SUBSCRIBE_USERS_FAILURE,
};
} | function socketSubscriberSubscribeUsersFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_SUBSCRIBE_USERS_FAILURE,
};
} |
JavaScript | function socketSubscriberSubscribeUsersSuccess() {
return {
type: SOCKET_SUBSCRIBER_SUBSCRIBE_USERS_SUCCESS,
};
} | function socketSubscriberSubscribeUsersSuccess() {
return {
type: SOCKET_SUBSCRIBER_SUBSCRIBE_USERS_SUCCESS,
};
} |
JavaScript | function socketSubscriberUnpublishUser() {
return {
type: SOCKET_SUBSCRIBER_UNPUBLISH_USER,
};
} | function socketSubscriberUnpublishUser() {
return {
type: SOCKET_SUBSCRIBER_UNPUBLISH_USER,
};
} |
JavaScript | function socketSubscriberUnpublishUserFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_UNPUBLISH_USER_FAILURE,
};
} | function socketSubscriberUnpublishUserFailure({ error }) {
return {
payload: { error },
type: SOCKET_SUBSCRIBER_UNPUBLISH_USER_FAILURE,
};
} |
JavaScript | function socketSubscriberUnpublishUserSuccess() {
return {
type: SOCKET_SUBSCRIBER_UNPUBLISH_USER_SUCCESS,
};
} | function socketSubscriberUnpublishUserSuccess() {
return {
type: SOCKET_SUBSCRIBER_UNPUBLISH_USER_SUCCESS,
};
} |
JavaScript | function socketSubscriberUnsubscribeActions() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_ACTIONS,
};
} | function socketSubscriberUnsubscribeActions() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_ACTIONS,
};
} |
JavaScript | function socketSubscriberUnsubscribeActionsFailure() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_ACTIONS_FAILURE,
};
} | function socketSubscriberUnsubscribeActionsFailure() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_ACTIONS_FAILURE,
};
} |
JavaScript | function socketSubscriberUnsubscribeActionsSuccess() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_ACTIONS_SUCCESS,
};
} | function socketSubscriberUnsubscribeActionsSuccess() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_ACTIONS_SUCCESS,
};
} |
JavaScript | function socketSubscriberUnsubscribeUsers() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_USERS,
};
} | function socketSubscriberUnsubscribeUsers() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_USERS,
};
} |
JavaScript | function socketSubscriberUnsubscribeUsersFailure() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_USERS_FAILURE,
};
} | function socketSubscriberUnsubscribeUsersFailure() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_USERS_FAILURE,
};
} |
JavaScript | function socketSubscriberUnsubscribeUsersSuccess() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_USERS_SUCCESS,
};
} | function socketSubscriberUnsubscribeUsersSuccess() {
return {
type: SOCKET_SUBSCRIBER_UNSUBSCRIBE_USERS_SUCCESS,
};
} |
JavaScript | function socketSessionTopicOnChange({ value }) {
return {
payload: { value },
type: SOCKET_SESSION_TOPIC_ONCHANGE,
};
} | function socketSessionTopicOnChange({ value }) {
return {
payload: { value },
type: SOCKET_SESSION_TOPIC_ONCHANGE,
};
} |
JavaScript | function unpublishSession({ sessionId, sessionToken }) {
return new Promise((resolve, reject) => {
let sent = false;
socket.emit('unpublishSession', { sessionId, sessionToken }, response => {
sent = true;
resolve(response);
});
setTimeout(() => {
if (!sent) {
reject();
}
}, 2000);
});
} | function unpublishSession({ sessionId, sessionToken }) {
return new Promise((resolve, reject) => {
let sent = false;
socket.emit('unpublishSession', { sessionId, sessionToken }, response => {
sent = true;
resolve(response);
});
setTimeout(() => {
if (!sent) {
reject();
}
}, 2000);
});
} |
JavaScript | function unpublishUser({ sessionId, userId, userToken }) {
return new Promise((resolve, reject) => {
let sent = false;
socket.emit('unpublishUser', { sessionId, userId, userToken }, response => {
sent = true;
resolve(response);
});
setTimeout(() => {
if (!sent) {
reject();
}
}, 2000);
});
} | function unpublishUser({ sessionId, userId, userToken }) {
return new Promise((resolve, reject) => {
let sent = false;
socket.emit('unpublishUser', { sessionId, userId, userToken }, response => {
sent = true;
resolve(response);
});
setTimeout(() => {
if (!sent) {
reject();
}
}, 2000);
});
} |
JavaScript | function socketPublisherPublishActionFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_PUBLISH_ACTION_FAILURE,
};
} | function socketPublisherPublishActionFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_PUBLISH_ACTION_FAILURE,
};
} |
JavaScript | function socketPublisherPublishActionSuccess({
sessionId,
sessionTimestamp,
sessionToken,
sessionTopic,
sessionUsername,
}) {
return {
payload: {
sessionId,
sessionTimestamp,
sessionToken,
sessionTopic,
sessionUsername,
},
type: SOCKET_PUBLISHER_PUBLISH_ACTION_SUCCESS,
};
} | function socketPublisherPublishActionSuccess({
sessionId,
sessionTimestamp,
sessionToken,
sessionTopic,
sessionUsername,
}) {
return {
payload: {
sessionId,
sessionTimestamp,
sessionToken,
sessionTopic,
sessionUsername,
},
type: SOCKET_PUBLISHER_PUBLISH_ACTION_SUCCESS,
};
} |
JavaScript | function socketPublisherPublishSession() {
return {
type: SOCKET_PUBLISHER_PUBLISH_SESSION,
};
} | function socketPublisherPublishSession() {
return {
type: SOCKET_PUBLISHER_PUBLISH_SESSION,
};
} |
JavaScript | function socketPublisherPublishSessionFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_PUBLISH_SESSION_FAILURE,
};
} | function socketPublisherPublishSessionFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_PUBLISH_SESSION_FAILURE,
};
} |
JavaScript | function socketPublisherPublishSessionSuccess({
sessionId,
sessionTimestamp,
sessionToken,
sessionTopic,
sessionUsername,
}) {
return {
payload: {
sessionId,
sessionTimestamp,
sessionToken,
sessionTopic,
sessionUsername,
},
type: SOCKET_PUBLISHER_PUBLISH_SESSION_SUCCESS,
};
} | function socketPublisherPublishSessionSuccess({
sessionId,
sessionTimestamp,
sessionToken,
sessionTopic,
sessionUsername,
}) {
return {
payload: {
sessionId,
sessionTimestamp,
sessionToken,
sessionTopic,
sessionUsername,
},
type: SOCKET_PUBLISHER_PUBLISH_SESSION_SUCCESS,
};
} |
JavaScript | function socketPublisherPublishUser() {
return {
type: SOCKET_PUBLISHER_PUBLISH_USER,
};
} | function socketPublisherPublishUser() {
return {
type: SOCKET_PUBLISHER_PUBLISH_USER,
};
} |
JavaScript | function socketPublisherPublishUserFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_PUBLISH_USER_FAILURE,
};
} | function socketPublisherPublishUserFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_PUBLISH_USER_FAILURE,
};
} |
JavaScript | function socketPublisherPublishUserSuccess({ userId, userToken }) {
return {
payload: { userId, userToken },
type: SOCKET_PUBLISHER_PUBLISH_USER_SUCCESS,
};
} | function socketPublisherPublishUserSuccess({ userId, userToken }) {
return {
payload: { userId, userToken },
type: SOCKET_PUBLISHER_PUBLISH_USER_SUCCESS,
};
} |
JavaScript | function socketPublisherReceiveAction({ type, payload }) {
return {
payload: { type, payload },
type: SOCKET_PUBLISHER_RECEIVE_ACTION,
};
} | function socketPublisherReceiveAction({ type, payload }) {
return {
payload: { type, payload },
type: SOCKET_PUBLISHER_RECEIVE_ACTION,
};
} |
JavaScript | function socketPublisherReceiveUser({ change, username }) {
return {
payload: { change, username },
type: SOCKET_PUBLISHER_RECEIVE_USER,
};
} | function socketPublisherReceiveUser({ change, username }) {
return {
payload: { change, username },
type: SOCKET_PUBLISHER_RECEIVE_USER,
};
} |
JavaScript | function socketPublisherUnpublishSession() {
return {
type: SOCKET_PUBLISHER_UNPUBLISH_SESSION,
};
} | function socketPublisherUnpublishSession() {
return {
type: SOCKET_PUBLISHER_UNPUBLISH_SESSION,
};
} |
JavaScript | function socketPublisherUnpublishSessionSuccess() {
return {
type: SOCKET_PUBLISHER_UNPUBLISH_SESSION_SUCCESS,
};
} | function socketPublisherUnpublishSessionSuccess() {
return {
type: SOCKET_PUBLISHER_UNPUBLISH_SESSION_SUCCESS,
};
} |
JavaScript | function socketPublisherSubscribeActionsFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_SUBSCRIBE_ACTIONS_FAILURE,
};
} | function socketPublisherSubscribeActionsFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_SUBSCRIBE_ACTIONS_FAILURE,
};
} |
JavaScript | function socketPublisherSubscribeActionsSuccess() {
return {
type: SOCKET_PUBLISHER_SUBSCRIBE_ACTIONS_SUCCESS,
};
} | function socketPublisherSubscribeActionsSuccess() {
return {
type: SOCKET_PUBLISHER_SUBSCRIBE_ACTIONS_SUCCESS,
};
} |
JavaScript | function socketPublisherSubscribeUsersFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_SUBSCRIBE_USERS_FAILURE,
};
} | function socketPublisherSubscribeUsersFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_SUBSCRIBE_USERS_FAILURE,
};
} |
JavaScript | function socketPublisherSubscribeUsersSuccess() {
return {
type: SOCKET_PUBLISHER_SUBSCRIBE_USERS_SUCCESS,
};
} | function socketPublisherSubscribeUsersSuccess() {
return {
type: SOCKET_PUBLISHER_SUBSCRIBE_USERS_SUCCESS,
};
} |
JavaScript | function socketPublisherUnpublishUser() {
return {
type: SOCKET_PUBLISHER_UNPUBLISH_USER,
};
} | function socketPublisherUnpublishUser() {
return {
type: SOCKET_PUBLISHER_UNPUBLISH_USER,
};
} |
JavaScript | function socketPublisherUnpublishUserFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_UNPUBLISH_USER_FAILURE,
};
} | function socketPublisherUnpublishUserFailure({ error }) {
return {
payload: { error },
type: SOCKET_PUBLISHER_UNPUBLISH_USER_FAILURE,
};
} |
JavaScript | function socketPublisherUnpublishUserSuccess() {
return {
type: SOCKET_PUBLISHER_UNPUBLISH_USER_SUCCESS,
};
} | function socketPublisherUnpublishUserSuccess() {
return {
type: SOCKET_PUBLISHER_UNPUBLISH_USER_SUCCESS,
};
} |
JavaScript | function socketPublisherUnsubscribeActions() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_ACTIONS,
};
} | function socketPublisherUnsubscribeActions() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_ACTIONS,
};
} |
JavaScript | function socketPublisherUnsubscribeActionsFailure() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_ACTIONS_FAILURE,
};
} | function socketPublisherUnsubscribeActionsFailure() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_ACTIONS_FAILURE,
};
} |
JavaScript | function socketPublisherUnsubscribeActionsSuccess() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_ACTIONS_SUCCESS,
};
} | function socketPublisherUnsubscribeActionsSuccess() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_ACTIONS_SUCCESS,
};
} |
JavaScript | function socketPublisherUnsubscribeUsers() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_USERS,
};
} | function socketPublisherUnsubscribeUsers() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_USERS,
};
} |
JavaScript | function socketPublisherUnsubscribeUsersFailure() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_USERS_FAILURE,
};
} | function socketPublisherUnsubscribeUsersFailure() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_USERS_FAILURE,
};
} |
JavaScript | function socketPublisherUnsubscribeUsersSuccess() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_USERS_SUCCESS,
};
} | function socketPublisherUnsubscribeUsersSuccess() {
return {
type: SOCKET_PUBLISHER_UNSUBSCRIBE_USERS_SUCCESS,
};
} |
JavaScript | function* subscriberPublishUser() {
const sessionId = yield select(selectSocketSessionId());
const username = yield select(selectSocketUsername());
try {
const { userId, userToken } = yield call(publishUser, {
sessionId,
username,
});
yield put(
socketSubscriberPublishUserSuccess({
userId,
userToken,
}),
);
} catch (error) {
yield put(socketSubscriberPublishUserFailure({ error }));
}
} | function* subscriberPublishUser() {
const sessionId = yield select(selectSocketSessionId());
const username = yield select(selectSocketUsername());
try {
const { userId, userToken } = yield call(publishUser, {
sessionId,
username,
});
yield put(
socketSubscriberPublishUserSuccess({
userId,
userToken,
}),
);
} catch (error) {
yield put(socketSubscriberPublishUserFailure({ error }));
}
} |
JavaScript | function* subscriberUnpublishUser() {
const sessionId = yield select(selectSocketSessionId());
const userId = yield select(selectSocketUserId());
const userToken = yield select(selectSocketUserToken());
try {
yield call(unpublishUser, { sessionId, userToken, userId });
yield put(socketSubscriberUnpublishUserSuccess());
} catch (error) {
yield put(socketSubscriberUnpublishUserFailure({ error }));
}
} | function* subscriberUnpublishUser() {
const sessionId = yield select(selectSocketSessionId());
const userId = yield select(selectSocketUserId());
const userToken = yield select(selectSocketUserToken());
try {
yield call(unpublishUser, { sessionId, userToken, userId });
yield put(socketSubscriberUnpublishUserSuccess());
} catch (error) {
yield put(socketSubscriberUnpublishUserFailure({ error }));
}
} |
JavaScript | function* subscriberSubscribeSession({ payload: { sessionId } }) {
try {
const channel = yield call(subscribeSession, { sessionId });
const {
sessionIsLivestream,
sessionTimestamp,
sessionTopic,
sessionUsername,
} = yield take(channel);
yield put(
socketSubscriberSubscribeSessionSuccess({
sessionId,
sessionIsLivestream,
sessionTimestamp,
sessionTopic,
sessionUsername,
}),
);
while (true) {
// eslint-disable-next-line no-shadow
const { sessionIsLivestream, sessionTopic } = yield take(channel);
yield put(
socketSubscriberReceiveSession({
sessionIsLivestream,
sessionTopic,
}),
);
}
} catch (error) {
yield put(socketSubscriberSubscribeSessionFailure({ error }));
}
} | function* subscriberSubscribeSession({ payload: { sessionId } }) {
try {
const channel = yield call(subscribeSession, { sessionId });
const {
sessionIsLivestream,
sessionTimestamp,
sessionTopic,
sessionUsername,
} = yield take(channel);
yield put(
socketSubscriberSubscribeSessionSuccess({
sessionId,
sessionIsLivestream,
sessionTimestamp,
sessionTopic,
sessionUsername,
}),
);
while (true) {
// eslint-disable-next-line no-shadow
const { sessionIsLivestream, sessionTopic } = yield take(channel);
yield put(
socketSubscriberReceiveSession({
sessionIsLivestream,
sessionTopic,
}),
);
}
} catch (error) {
yield put(socketSubscriberSubscribeSessionFailure({ error }));
}
} |
JavaScript | function* subscriberSubscribeActions() {
const sessionId = yield select(selectSocketSessionId());
try {
const channel = yield call(subscribeActions, { sessionId });
yield put(socketSubscriberSubscribeActionsSuccess());
while (true) {
const { payload, type } = yield take(channel);
yield put({
type: `${type}_FROM_SOCKET`,
payload,
});
}
} catch (error) {
yield put(socketSubscriberSubscribeActionsFailure({ error }));
}
} | function* subscriberSubscribeActions() {
const sessionId = yield select(selectSocketSessionId());
try {
const channel = yield call(subscribeActions, { sessionId });
yield put(socketSubscriberSubscribeActionsSuccess());
while (true) {
const { payload, type } = yield take(channel);
yield put({
type: `${type}_FROM_SOCKET`,
payload,
});
}
} catch (error) {
yield put(socketSubscriberSubscribeActionsFailure({ error }));
}
} |
JavaScript | function* subscriberSubscribeUsers() {
const sessionId = yield select(selectSocketSessionId());
try {
const channel = yield call(subscribeUsers, { sessionId });
yield put(socketSubscriberSubscribeUsersSuccess());
while (true) {
const { change, username } = yield take(channel);
yield put(
socketSubscriberReceiveUser({
change,
username,
}),
);
}
} catch (error) {
yield put(
socketSubscriberSubscribeUsersFailure({
error,
}),
);
}
} | function* subscriberSubscribeUsers() {
const sessionId = yield select(selectSocketSessionId());
try {
const channel = yield call(subscribeUsers, { sessionId });
yield put(socketSubscriberSubscribeUsersSuccess());
while (true) {
const { change, username } = yield take(channel);
yield put(
socketSubscriberReceiveUser({
change,
username,
}),
);
}
} catch (error) {
yield put(
socketSubscriberSubscribeUsersFailure({
error,
}),
);
}
} |
JavaScript | function* subscriberUnsubscribeActions() {
const sessionId = yield select(selectSocketSessionId());
try {
yield call(unsubscribeActions, { sessionId });
yield put(socketSubscriberUnsubscribeActionsSuccess());
} catch (error) {
yield put(socketSubscriberUnsubscribeActionsFailure({ error }));
}
} | function* subscriberUnsubscribeActions() {
const sessionId = yield select(selectSocketSessionId());
try {
yield call(unsubscribeActions, { sessionId });
yield put(socketSubscriberUnsubscribeActionsSuccess());
} catch (error) {
yield put(socketSubscriberUnsubscribeActionsFailure({ error }));
}
} |
JavaScript | function* subscriberUnsubscribeUsers() {
const sessionId = yield select(selectSocketSessionId());
try {
yield call(unsubscribeUsers, { sessionId });
yield put(socketSubscriberUnsubscribeUsersSuccess());
} catch (error) {
yield put(socketSubscriberUnsubscribeUsersFailure({ error }));
}
} | function* subscriberUnsubscribeUsers() {
const sessionId = yield select(selectSocketSessionId());
try {
yield call(unsubscribeUsers, { sessionId });
yield put(socketSubscriberUnsubscribeUsersSuccess());
} catch (error) {
yield put(socketSubscriberUnsubscribeUsersFailure({ error }));
}
} |
Subsets and Splits