language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | disablePlugins(plugins) {
let toKeep = plugin => plugins.indexOf(plugin) === -1;
this[SELECTED_PLUGINS] = this[SELECTED_PLUGINS].filter(toKeep);
this[SETUP]();
} | disablePlugins(plugins) {
let toKeep = plugin => plugins.indexOf(plugin) === -1;
this[SELECTED_PLUGINS] = this[SELECTED_PLUGINS].filter(toKeep);
this[SETUP]();
} |
JavaScript | function insertBr() {
return chainCommands(exitCode, (state, dispatch) => {
dispatch(
state.tr
.replaceSelectionWith(state.schema.nodes.hardBreak.create())
.scrollIntoView()
);
return true;
});
} | function insertBr() {
return chainCommands(exitCode, (state, dispatch) => {
dispatch(
state.tr
.replaceSelectionWith(state.schema.nodes.hardBreak.create())
.scrollIntoView()
);
return true;
});
} |
JavaScript | function mergeSchemaSpecs(specs) {
return specs.reduce(
(merged, spec) => {
return {
nodes: Object.assign({}, merged.nodes, spec.nodes),
marks: Object.assign({}, merged.marks, spec.marks)
};
},
{ nodes: {}, marks: {} }
);
} | function mergeSchemaSpecs(specs) {
return specs.reduce(
(merged, spec) => {
return {
nodes: Object.assign({}, merged.nodes, spec.nodes),
marks: Object.assign({}, merged.marks, spec.marks)
};
},
{ nodes: {}, marks: {} }
);
} |
JavaScript | function flatten(items) {
return items.reduce((flattened, item) => {
if (Array.isArray(item)) {
return flattened.concat(flatten(item));
}
return [...flattened, item];
}, []);
} | function flatten(items) {
return items.reduce((flattened, item) => {
if (Array.isArray(item)) {
return flattened.concat(flatten(item));
}
return [...flattened, item];
}, []);
} |
JavaScript | function WOQLClient(serverUrl, params) {
// current connection context variables
this.connectionConfig = new ConnectionConfig(serverUrl, params)
this.databaseList = []
this.organizationList =[]
} | function WOQLClient(serverUrl, params) {
// current connection context variables
this.connectionConfig = new ConnectionConfig(serverUrl, params)
this.databaseList = []
this.organizationList =[]
} |
JavaScript | function WOQLQuery(query) {
this.query = query ? query : {}
this.errors = []
this.cursor = this.query
this.chain_ended = false
this.contains_update = false
// operators which preserve global paging
this.paging_transitive_properties = ['select', 'from', 'start', 'when', 'opt', 'limit']
this.update_operators = [
'AddTriple',
'DeleteTriple',
'AddQuad',
'DeleteQuad',
'DeleteObject',
'UpdateObject',
]
this.vocab = this.loadDefaultVocabulary()
//object used to accumulate triples from fragments to support usage like node("x").label("y");
this.tripleBuilder = false
return this
} | function WOQLQuery(query) {
this.query = query ? query : {}
this.errors = []
this.cursor = this.query
this.chain_ended = false
this.contains_update = false
// operators which preserve global paging
this.paging_transitive_properties = ['select', 'from', 'start', 'when', 'opt', 'limit']
this.update_operators = [
'AddTriple',
'DeleteTriple',
'AddQuad',
'DeleteQuad',
'DeleteObject',
'UpdateObject',
]
this.vocab = this.loadDefaultVocabulary()
//object used to accumulate triples from fragments to support usage like node("x").label("y");
this.tripleBuilder = false
return this
} |
JavaScript | function copyJSON(orig, rollup) {
if (Array.isArray(orig)) return orig
if (rollup) {
if (orig['@type'] == 'And') {
if (!orig['and'] || !orig['and'].length) return {}
if (orig['and'].length == 1)
return copyJSON(orig['and'][0], rollup)
} else if (orig['@type'] == 'Or') {
if (!orig['or'] || !orig['or'].length) return {}
if (orig['or'].length == 1)
return copyJSON(orig['or'][0], rollup)
}
if (typeof orig['query'] != 'undefined' && orig['@type'] != 'Comment') {
if (!orig['query']['@type']) return {}
} else if (orig['@type'] == 'Comment' && orig['comment']) {
if (!orig['query'] || !orig['query']['@type'])
return {'@type': 'Comment', 'comment': orig['comment']}
}
if (typeof orig['consequent'] != 'undefined') {
if (!orig['consequent']['@type']) return {}
}
}
let nuj = {}
for (var k in orig) {
let part = orig[k]
if (Array.isArray(part)) {
let nupart = []
for (var j = 0; j < part.length; j++) {
if (typeof part[j] == 'object') {
let sub = copyJSON(part[j], rollup)
if (!sub || !UTILS.empty(sub)) nupart.push(sub)
} else {
nupart.push(part[j])
}
}
nuj[k] = nupart
} else if (typeof part == 'object') {
let q = copyJSON(part, rollup)
if (!q || !UTILS.empty(q)) nuj[k] = q
} else {
nuj[k] = part
}
}
return nuj
} | function copyJSON(orig, rollup) {
if (Array.isArray(orig)) return orig
if (rollup) {
if (orig['@type'] == 'And') {
if (!orig['and'] || !orig['and'].length) return {}
if (orig['and'].length == 1)
return copyJSON(orig['and'][0], rollup)
} else if (orig['@type'] == 'Or') {
if (!orig['or'] || !orig['or'].length) return {}
if (orig['or'].length == 1)
return copyJSON(orig['or'][0], rollup)
}
if (typeof orig['query'] != 'undefined' && orig['@type'] != 'Comment') {
if (!orig['query']['@type']) return {}
} else if (orig['@type'] == 'Comment' && orig['comment']) {
if (!orig['query'] || !orig['query']['@type'])
return {'@type': 'Comment', 'comment': orig['comment']}
}
if (typeof orig['consequent'] != 'undefined') {
if (!orig['consequent']['@type']) return {}
}
}
let nuj = {}
for (var k in orig) {
let part = orig[k]
if (Array.isArray(part)) {
let nupart = []
for (var j = 0; j < part.length; j++) {
if (typeof part[j] == 'object') {
let sub = copyJSON(part[j], rollup)
if (!sub || !UTILS.empty(sub)) nupart.push(sub)
} else {
nupart.push(part[j])
}
}
nuj[k] = nupart
} else if (typeof part == 'object') {
let q = copyJSON(part, rollup)
if (!q || !UTILS.empty(q)) nuj[k] = q
} else {
nuj[k] = part
}
}
return nuj
} |
JavaScript | function toggleValidation($field) {
var propRequired = $field.prop("required");
var ariaRequired = $field.attr("aria-required");
var isRequired = (ariaRequired === "true");
// skip toggle if field is already hidden and validation was already toggled (in case of nested show/hide structures)
if ($field.parents(".wcmio-dialog-showhide-status-hide").length > 0) {
return;
}
if ($field.is("foundation-autocomplete") && propRequired !== "undefined") {
if (propRequired === true) {
$field[0].required = false;
$field.attr("aria-required", false);
}
else if (propRequired === false) {
$field[0].required = true;
$field.removeAttr("aria-required");
}
}
else if (typeof ariaRequired !== "undefined") {
$field.attr("aria-required", String(!isRequired));
}
var api = $field.adaptTo("foundation-validation");
if (api) {
if (isRequired) {
api.checkValidity();
}
api.updateUI();
}
} | function toggleValidation($field) {
var propRequired = $field.prop("required");
var ariaRequired = $field.attr("aria-required");
var isRequired = (ariaRequired === "true");
// skip toggle if field is already hidden and validation was already toggled (in case of nested show/hide structures)
if ($field.parents(".wcmio-dialog-showhide-status-hide").length > 0) {
return;
}
if ($field.is("foundation-autocomplete") && propRequired !== "undefined") {
if (propRequired === true) {
$field[0].required = false;
$field.attr("aria-required", false);
}
else if (propRequired === false) {
$field[0].required = true;
$field.removeAttr("aria-required");
}
}
else if (typeof ariaRequired !== "undefined") {
$field.attr("aria-required", String(!isRequired));
}
var api = $field.adaptTo("foundation-validation");
if (api) {
if (isRequired) {
api.checkValidity();
}
api.updateUI();
}
} |
JavaScript | function reportPath() {
// Navigate up to the app dir. Move up the scripts dir, package dir,
// @appsignal dir and node_modules dir.
const appPath = path.join(__dirname, "../../../../")
const hash = crypto.createHash("sha256")
hash.update(appPath)
const reportPathDigest = hash.digest("hex")
return path.join(`/tmp/appsignal-${reportPathDigest}-install.report`)
} | function reportPath() {
// Navigate up to the app dir. Move up the scripts dir, package dir,
// @appsignal dir and node_modules dir.
const appPath = path.join(__dirname, "../../../../")
const hash = crypto.createHash("sha256")
hash.update(appPath)
const reportPathDigest = hash.digest("hex")
return path.join(`/tmp/appsignal-${reportPathDigest}-install.report`)
} |
JavaScript | function mapStateToProps({ authedUser }) {
return {
authedUser,
loading: authedUser === null
}
} | function mapStateToProps({ authedUser }) {
return {
authedUser,
loading: authedUser === null
}
} |
JavaScript | function extractDepcruiseConfig(
pConfigFileName,
pAlreadyVisited = new Set(),
pBaseDirectory = process.cwd()
) {
const lResolvedFileName = resolve(
pConfigFileName,
pBaseDirectory,
normalizeResolveOptions(
{
extensions: [".js", ".json"],
},
{
externalModuleResolutionStrategy: getRunningProcessResolutionStrategy(),
}
),
"cli"
);
const lBaseDirectory = path.dirname(lResolvedFileName);
if (pAlreadyVisited.has(lResolvedFileName)) {
throw new Error(
`config is circular - ${[...pAlreadyVisited].join(
" -> "
)} -> ${lResolvedFileName}.\n`
);
}
pAlreadyVisited.add(lResolvedFileName);
let lReturnValue = readConfig(lResolvedFileName, pBaseDirectory);
if (_has(lReturnValue, "extends")) {
lReturnValue = processExtends(
lReturnValue,
pAlreadyVisited,
lBaseDirectory
);
}
return lReturnValue;
} | function extractDepcruiseConfig(
pConfigFileName,
pAlreadyVisited = new Set(),
pBaseDirectory = process.cwd()
) {
const lResolvedFileName = resolve(
pConfigFileName,
pBaseDirectory,
normalizeResolveOptions(
{
extensions: [".js", ".json"],
},
{
externalModuleResolutionStrategy: getRunningProcessResolutionStrategy(),
}
),
"cli"
);
const lBaseDirectory = path.dirname(lResolvedFileName);
if (pAlreadyVisited.has(lResolvedFileName)) {
throw new Error(
`config is circular - ${[...pAlreadyVisited].join(
" -> "
)} -> ${lResolvedFileName}.\n`
);
}
pAlreadyVisited.add(lResolvedFileName);
let lReturnValue = readConfig(lResolvedFileName, pBaseDirectory);
if (_has(lReturnValue, "extends")) {
lReturnValue = processExtends(
lReturnValue,
pAlreadyVisited,
lBaseDirectory
);
}
return lReturnValue;
} |
JavaScript | function updateDisplay() {
domSystemTime.innerText = `Local time: ${audioCtx.currentTime.toFixed(2)}`;
domSyncTime.innerText = `Synced time: ${ts.now().toFixed(2)}`;
setTimeout(updateDisplay, 100);
} | function updateDisplay() {
domSystemTime.innerText = `Local time: ${audioCtx.currentTime.toFixed(2)}`;
domSyncTime.innerText = `Synced time: ${ts.now().toFixed(2)}`;
setTimeout(updateDisplay, 100);
} |
JavaScript | function showQuestion(question) {
questionEl.innerText = question.question;
question.answers.forEach(answers => {
let button = document.createElement('button');
button.innerText = answers.text;
button.setAttribute('value', answers.correct);
button.classList.add('btn');
answerBtn.appendChild(button);
button.onclick = theQuiz;
})
} | function showQuestion(question) {
questionEl.innerText = question.question;
question.answers.forEach(answers => {
let button = document.createElement('button');
button.innerText = answers.text;
button.setAttribute('value', answers.correct);
button.classList.add('btn');
answerBtn.appendChild(button);
button.onclick = theQuiz;
})
} |
JavaScript | async function register(app) {
await app.registerPlugin({
label: "opulent Door plugin",
name: "opulent-door-plugin",
version: pkg.version
});
} | async function register(app) {
await app.registerPlugin({
label: "opulent Door plugin",
name: "opulent-door-plugin",
version: pkg.version
});
} |
JavaScript | async cancelParcel(req, res) {
const queryText = 'SELECT * FROM parcel_order WHERE parcel_id = $1 AND active = $2 AND status != $3 AND placed_by = $4';
const patchQuery = 'UPDATE parcel_order SET active = $1 WHERE parcel_id = $2 AND placed_by = $3 returning *';
const values = [
req.params.parcelId,
true,
'delivered',
req.user.userId,
];
try {
const { rows } = await querySendItDb(queryText, values);
if (!rows[0]) {
return res.status(404).json({ message: 'Parcel delivery order not found' });
}
// confirm that the logged in user actually created this parcel delivery order
if (rows[0].placed_by !== req.user.userId) {
return res.status(403).json({ status: res.statusCode, message: 'Operation prohibited!Unauthorised access!' });
}
const response = await querySendItDb(patchQuery, [req.body.active, req.params.parcelId, req.user.userId]);
return res.status(200).json({ status: res.statusCode, data: response.rows[0], message: 'Order canceled' });
} catch (error) {
return res.status(400).json({ status: res.statusCode, error: error.message });
}
} | async cancelParcel(req, res) {
const queryText = 'SELECT * FROM parcel_order WHERE parcel_id = $1 AND active = $2 AND status != $3 AND placed_by = $4';
const patchQuery = 'UPDATE parcel_order SET active = $1 WHERE parcel_id = $2 AND placed_by = $3 returning *';
const values = [
req.params.parcelId,
true,
'delivered',
req.user.userId,
];
try {
const { rows } = await querySendItDb(queryText, values);
if (!rows[0]) {
return res.status(404).json({ message: 'Parcel delivery order not found' });
}
// confirm that the logged in user actually created this parcel delivery order
if (rows[0].placed_by !== req.user.userId) {
return res.status(403).json({ status: res.statusCode, message: 'Operation prohibited!Unauthorised access!' });
}
const response = await querySendItDb(patchQuery, [req.body.active, req.params.parcelId, req.user.userId]);
return res.status(200).json({ status: res.statusCode, data: response.rows[0], message: 'Order canceled' });
} catch (error) {
return res.status(400).json({ status: res.statusCode, error: error.message });
}
} |
JavaScript | async changeParcelDestination(req, res) {
const queryText = 'SELECT * FROM parcel_order WHERE parcel_id = $1 AND active = $2 AND status != $3';
const patchQuery = 'UPDATE parcel_order SET receiver = $1 WHERE parcel_id = $2 returning *';
const values = [
req.params.parcelId,
true,
'delivered',
];
try {
const { rows } = await querySendItDb(queryText, values);
if (!rows[0]) {
return res.status(403).json({ status: res.statusCode, message: 'Change of destination not allowed!Unauthorised access!' });
}
// confirm that the logged in user actually created this parcel delivery order
if (rows[0].placed_by !== req.user.userId) {
return res.status(403).json({ status: res.statusCode, message: 'Operation not allowed. Unauthorised access!' });
}
const response = await querySendItDb(patchQuery, [req.body.receiver, req.params.parcelId]);
return res.status(200).json({
status: res.statusCode,
id: response.rows[0].parcel_id,
to: response.rows[0].receiver,
message: 'Parcel destination updated',
});
} catch (error) {
return res.status(412).json({ status: res.statusCode, error: error.message });
}
} | async changeParcelDestination(req, res) {
const queryText = 'SELECT * FROM parcel_order WHERE parcel_id = $1 AND active = $2 AND status != $3';
const patchQuery = 'UPDATE parcel_order SET receiver = $1 WHERE parcel_id = $2 returning *';
const values = [
req.params.parcelId,
true,
'delivered',
];
try {
const { rows } = await querySendItDb(queryText, values);
if (!rows[0]) {
return res.status(403).json({ status: res.statusCode, message: 'Change of destination not allowed!Unauthorised access!' });
}
// confirm that the logged in user actually created this parcel delivery order
if (rows[0].placed_by !== req.user.userId) {
return res.status(403).json({ status: res.statusCode, message: 'Operation not allowed. Unauthorised access!' });
}
const response = await querySendItDb(patchQuery, [req.body.receiver, req.params.parcelId]);
return res.status(200).json({
status: res.statusCode,
id: response.rows[0].parcel_id,
to: response.rows[0].receiver,
message: 'Parcel destination updated',
});
} catch (error) {
return res.status(412).json({ status: res.statusCode, error: error.message });
}
} |
JavaScript | async changeParcelStatus(req, res) {
if (!req.user.isAdmin) {
return res.status(403).json({ status: res.statusCode, message: 'Operation not allowed. Unauthorised access!' });
}
const queryText = 'SELECT * FROM parcel_order WHERE parcel_id = $1 AND active = $2';
const patchQuery = 'UPDATE parcel_order SET status = $1 WHERE parcel_id = $2 returning *';
const patchStatusAndDate = 'UPDATE parcel_order SET status = $1, delivered_on = $2 WHERE parcel_id = $3 returning *';
const values = [
req.params.parcelId,
true,
];
try {
const { rows } = await querySendItDb(queryText, values);
if (!rows[0]) {
return res.status(404).json({ status: res.statusCode, message: 'Parcel delivery order not dound' });
}
let response;
if (req.body.status === 'delivered') {
response = await querySendItDb(patchStatusAndDate, [req.body.status, moment((new Date())), req.params.parcelId]);
} else {
response = await querySendItDb(patchQuery, [req.body.status, req.params.parcelId]);
}
// Send email notification to parcel owner
const findOwner = 'SELECT * FROM user_account WHERE user_id = $1';
const result = await querySendItDb(findOwner, [rows[0].placed_by]);
const statusNotification = `
<h2>Parcel Status Change</h2>
<p>Your parcel status has changed</p>
<p>Status: <strong>${req.body.status}</p>
`;
const mailOptions = {
from: process.env.EMAIL,
to: result.rows[0].email,
subject: 'Your Parcel Delivery Order Status',
html: statusNotification,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(`Could not send email: ${error}`);
} else {
console.log(`Email sent: ${info.response}`);
}
});
console.log('Sender: ', process.env.EMAIL);
console.log('Recipient: ', result.rows[0].email);
return res.status(200).json({
status: res.statusCode,
id: response.rows[0].parcel_id,
currentStatus: response.rows[0].status,
message: 'Parcel status updated',
});
} catch (error) {
return res.status(412).json({ status: res.statusCode, error: error.message });
}
} | async changeParcelStatus(req, res) {
if (!req.user.isAdmin) {
return res.status(403).json({ status: res.statusCode, message: 'Operation not allowed. Unauthorised access!' });
}
const queryText = 'SELECT * FROM parcel_order WHERE parcel_id = $1 AND active = $2';
const patchQuery = 'UPDATE parcel_order SET status = $1 WHERE parcel_id = $2 returning *';
const patchStatusAndDate = 'UPDATE parcel_order SET status = $1, delivered_on = $2 WHERE parcel_id = $3 returning *';
const values = [
req.params.parcelId,
true,
];
try {
const { rows } = await querySendItDb(queryText, values);
if (!rows[0]) {
return res.status(404).json({ status: res.statusCode, message: 'Parcel delivery order not dound' });
}
let response;
if (req.body.status === 'delivered') {
response = await querySendItDb(patchStatusAndDate, [req.body.status, moment((new Date())), req.params.parcelId]);
} else {
response = await querySendItDb(patchQuery, [req.body.status, req.params.parcelId]);
}
// Send email notification to parcel owner
const findOwner = 'SELECT * FROM user_account WHERE user_id = $1';
const result = await querySendItDb(findOwner, [rows[0].placed_by]);
const statusNotification = `
<h2>Parcel Status Change</h2>
<p>Your parcel status has changed</p>
<p>Status: <strong>${req.body.status}</p>
`;
const mailOptions = {
from: process.env.EMAIL,
to: result.rows[0].email,
subject: 'Your Parcel Delivery Order Status',
html: statusNotification,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(`Could not send email: ${error}`);
} else {
console.log(`Email sent: ${info.response}`);
}
});
console.log('Sender: ', process.env.EMAIL);
console.log('Recipient: ', result.rows[0].email);
return res.status(200).json({
status: res.statusCode,
id: response.rows[0].parcel_id,
currentStatus: response.rows[0].status,
message: 'Parcel status updated',
});
} catch (error) {
return res.status(412).json({ status: res.statusCode, error: error.message });
}
} |
JavaScript | async changeParcelCurrentLocation(req, res) {
if (!req.user.isAdmin) {
return res.status(403).json({ message: 'Operation not allowed. Unauthorised access!' });
}
const queryText = 'SELECT * FROM parcel_order WHERE parcel_id = $1 AND active = $2';
const patchQuery = 'UPDATE parcel_order SET current_location = $1 WHERE parcel_id = $2 returning *';
const values = [
req.params.parcelId,
true,
];
try {
const { rows } = await querySendItDb(queryText, values);
if (!rows[0]) {
return res.status(404).json({ status: res.statusCode, message: 'Parcel delivery order not found' });
}
const response = await querySendItDb(patchQuery, [req.body.currentLocation, req.params.parcelId]);
// send email notification to parcel owner
const findOwner = 'SELECT * FROM user_account WHERE user_id = $1';
const result = await querySendItDb(findOwner, [rows[0].placed_by]);
const locationNotification = `
<h2>Parcel Location Change</h2>
<p>Your parcel location has changed</p>
<p>Current Location: <strong>${req.body.currentLocation}<></p>
`;
const mailOptions = {
from: process.env.EMAIL,
to: result.rows[0].email,
subject: 'Your Parcel Delivery Order Location',
html: locationNotification,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(`Could not send email: ${error}`);
} else {
console.log(`Email sent: ${info.response}`);
}
});
console.log('Sender: ', process.env.EMAIL);
console.log('Recipient: ', result.rows[0].email);
return res.status(200).json({
status: res.statusCode,
id: response.rows[0].parcel_id,
currentLocation: response.rows[0].current_location,
message: 'Parcel location updated',
});
} catch (error) {
return res.status(412).json({ status: res.statusCode, error: error.message });
}
} | async changeParcelCurrentLocation(req, res) {
if (!req.user.isAdmin) {
return res.status(403).json({ message: 'Operation not allowed. Unauthorised access!' });
}
const queryText = 'SELECT * FROM parcel_order WHERE parcel_id = $1 AND active = $2';
const patchQuery = 'UPDATE parcel_order SET current_location = $1 WHERE parcel_id = $2 returning *';
const values = [
req.params.parcelId,
true,
];
try {
const { rows } = await querySendItDb(queryText, values);
if (!rows[0]) {
return res.status(404).json({ status: res.statusCode, message: 'Parcel delivery order not found' });
}
const response = await querySendItDb(patchQuery, [req.body.currentLocation, req.params.parcelId]);
// send email notification to parcel owner
const findOwner = 'SELECT * FROM user_account WHERE user_id = $1';
const result = await querySendItDb(findOwner, [rows[0].placed_by]);
const locationNotification = `
<h2>Parcel Location Change</h2>
<p>Your parcel location has changed</p>
<p>Current Location: <strong>${req.body.currentLocation}<></p>
`;
const mailOptions = {
from: process.env.EMAIL,
to: result.rows[0].email,
subject: 'Your Parcel Delivery Order Location',
html: locationNotification,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(`Could not send email: ${error}`);
} else {
console.log(`Email sent: ${info.response}`);
}
});
console.log('Sender: ', process.env.EMAIL);
console.log('Recipient: ', result.rows[0].email);
return res.status(200).json({
status: res.statusCode,
id: response.rows[0].parcel_id,
currentLocation: response.rows[0].current_location,
message: 'Parcel location updated',
});
} catch (error) {
return res.status(412).json({ status: res.statusCode, error: error.message });
}
} |
JavaScript | function encode(s) {
var c, i = 0, sBocu = '',a = [...s];
pPrev = 0;
for (; i < a.length; i++) {
c = encodeBocu1(a[i].codePointAt(0)) // unfortunately chrome is much slower at codePoint than FF
if (c >>> 24) sBocu += String.fromCharCode(c >>> 24); // improved bitwork?
if (c >>> 16) sBocu += String.fromCharCode((c & 0xFF0000) >>> 16);
if (c >>> 8) sBocu += String.fromCharCode((c & 0xFF00) >>> 8);
sBocu += String.fromCharCode(c >>> 0 & 0xFF);
//sBocu += String.fromCodePoint(c); // this isn't working for some high values that aren't valid unicode ( should just add each byte char)
//sBocu += encodeBocu1(s.codePointAt(i)).toString(16) + ' '; // display byte values
}
return sBocu;
} | function encode(s) {
var c, i = 0, sBocu = '',a = [...s];
pPrev = 0;
for (; i < a.length; i++) {
c = encodeBocu1(a[i].codePointAt(0)) // unfortunately chrome is much slower at codePoint than FF
if (c >>> 24) sBocu += String.fromCharCode(c >>> 24); // improved bitwork?
if (c >>> 16) sBocu += String.fromCharCode((c & 0xFF0000) >>> 16);
if (c >>> 8) sBocu += String.fromCharCode((c & 0xFF00) >>> 8);
sBocu += String.fromCharCode(c >>> 0 & 0xFF);
//sBocu += String.fromCodePoint(c); // this isn't working for some high values that aren't valid unicode ( should just add each byte char)
//sBocu += encodeBocu1(s.codePointAt(i)).toString(16) + ' '; // display byte values
}
return sBocu;
} |
JavaScript | function decode(sBocu) {
var rx = { // state for current character
prev: 0, // character zone
count: 0, // 0-3 for position within up to 4 byte set
diff: 0 // char
};
var c, i = 0, s = '', a = bStrToBuf(sBocu);
while (i < a.length) {
c = decodeBocu1(rx, a[i++]);
if (c < -1) {
//console.log("error: Bocu encoding error at string index " + i + ', character and preceding: ' + sBocu.substr(i - Math.max(0, 10), Math.min(i, 10)));
return;
}
if (c >= 0) {
s += String.fromCodePoint(c);
}
// -1 indicates non-character 'window' adjuster that may take 1-3 bytes? followed by final diff, the state is adjusted to handle the next byte
}
return s;
} | function decode(sBocu) {
var rx = { // state for current character
prev: 0, // character zone
count: 0, // 0-3 for position within up to 4 byte set
diff: 0 // char
};
var c, i = 0, s = '', a = bStrToBuf(sBocu);
while (i < a.length) {
c = decodeBocu1(rx, a[i++]);
if (c < -1) {
//console.log("error: Bocu encoding error at string index " + i + ', character and preceding: ' + sBocu.substr(i - Math.max(0, 10), Math.min(i, 10)));
return;
}
if (c >= 0) {
s += String.fromCodePoint(c);
}
// -1 indicates non-character 'window' adjuster that may take 1-3 bytes? followed by final diff, the state is adjusted to handle the next byte
}
return s;
} |
JavaScript | function bocu1Prev(c) {
/* compute new prev (middle of the codepage-like block) */
if (0x3040 <= c && c <= 0x309f) {
/* Hiragana is not 128-aligned */
return 0x3070;
} else if (0x4e00 <= c && c <= 0x9fa5) { // large scripts need two bytes for diff
/* CJK Unihan */
return 0x4e00 - BOCU1_REACH_NEG_2;
} else if (0xac00 <= c && c <= 0xd7a3) {
/* Korean Hangul */
return 0xc1d1; // Math.trunc((0xd7a3 + 0xac00) / 2);
} else {
/* mostly small scripts */ // 0x40 into the ascii-sized 128 byte block of current char
// this can be neg. Need ((c & ~0x7f) >>> 0) to not be neg
return (c & ~0x7f) + BOCU1_ASCII_PREV; // tilde bit swap is twice as fast as negative, and about same as c & 0xFFFFFF80
}
} | function bocu1Prev(c) {
/* compute new prev (middle of the codepage-like block) */
if (0x3040 <= c && c <= 0x309f) {
/* Hiragana is not 128-aligned */
return 0x3070;
} else if (0x4e00 <= c && c <= 0x9fa5) { // large scripts need two bytes for diff
/* CJK Unihan */
return 0x4e00 - BOCU1_REACH_NEG_2;
} else if (0xac00 <= c && c <= 0xd7a3) {
/* Korean Hangul */
return 0xc1d1; // Math.trunc((0xd7a3 + 0xac00) / 2);
} else {
/* mostly small scripts */ // 0x40 into the ascii-sized 128 byte block of current char
// this can be neg. Need ((c & ~0x7f) >>> 0) to not be neg
return (c & ~0x7f) + BOCU1_ASCII_PREV; // tilde bit swap is twice as fast as negative, and about same as c & 0xFFFFFF80
}
} |
JavaScript | function packDiff(diff) {
var result, lead, count, shift;
if (diff >= BOCU1_REACH_NEG_1) {
/* mostly positive differences, and single-byte negative ones */
if (diff <= BOCU1_REACH_POS_1) {
/* single byte */
// return 0x01000000|(BOCU1_MIDDLE+diff); // not using the number of bytes in lead byte
return BOCU1_MIDDLE + diff; // if in same script as last char, instead of encoding char you encode char shift from the middle of the script block
} else if (diff <= BOCU1_REACH_POS_2) {
/* two bytes */
diff -= BOCU1_REACH_POS_1 + 1;
lead = BOCU1_START_POS_2;
count = 1;
} else if (diff <= BOCU1_REACH_POS_3) {
/* three bytes */
diff -= BOCU1_REACH_POS_2 + 1;
lead = BOCU1_START_POS_3;
count = 2;
} else {
/* four bytes */
diff -= BOCU1_REACH_POS_3 + 1;
lead = BOCU1_START_POS_4;
count = 3;
}
} else {
/* two- and four-byte negative differences */
if (diff >= BOCU1_REACH_NEG_2) {
/* two bytes */
diff -= BOCU1_REACH_NEG_1;
lead = BOCU1_START_NEG_2;
count = 1;
} else if (diff >= BOCU1_REACH_NEG_3) {
/* three bytes */
diff -= BOCU1_REACH_NEG_2;
lead = BOCU1_START_NEG_3;
count = 2;
} else {
/* four bytes */
diff -= BOCU1_REACH_NEG_3;
lead = BOCU1_START_NEG_4;
count = 3;
}
}
/* encode the length of the packed result */
//if(count<3) {
//result=(count+1)<<24;
//} else /* count==3, MSB used for the lead byte */ {
result = 0;
//}
/* calculate trail bytes like digits in itoa() */
shift = 0;
var m = 0;
do {
// NEGDIVMOD()
m = diff % BOCU1_TRAIL_COUNT;
diff = ~~(diff / BOCU1_TRAIL_COUNT); // should I use Math.trunc instead? think ~~ is older, and it's a bit faster
if (m < 0) {
--diff;
m += BOCU1_TRAIL_COUNT;
}
// result |= BOCU1_TRAIL_TO_BYTE(NEGDIVMOD(diff, BOCU1_TRAIL_COUNT))<<shift;
result |= BOCU1_TRAIL_TO_BYTE(m) << shift;
shift += 8;
} while (--count > 0);
/* add lead byte */
result |= (lead + diff) << shift;
return result;
} | function packDiff(diff) {
var result, lead, count, shift;
if (diff >= BOCU1_REACH_NEG_1) {
/* mostly positive differences, and single-byte negative ones */
if (diff <= BOCU1_REACH_POS_1) {
/* single byte */
// return 0x01000000|(BOCU1_MIDDLE+diff); // not using the number of bytes in lead byte
return BOCU1_MIDDLE + diff; // if in same script as last char, instead of encoding char you encode char shift from the middle of the script block
} else if (diff <= BOCU1_REACH_POS_2) {
/* two bytes */
diff -= BOCU1_REACH_POS_1 + 1;
lead = BOCU1_START_POS_2;
count = 1;
} else if (diff <= BOCU1_REACH_POS_3) {
/* three bytes */
diff -= BOCU1_REACH_POS_2 + 1;
lead = BOCU1_START_POS_3;
count = 2;
} else {
/* four bytes */
diff -= BOCU1_REACH_POS_3 + 1;
lead = BOCU1_START_POS_4;
count = 3;
}
} else {
/* two- and four-byte negative differences */
if (diff >= BOCU1_REACH_NEG_2) {
/* two bytes */
diff -= BOCU1_REACH_NEG_1;
lead = BOCU1_START_NEG_2;
count = 1;
} else if (diff >= BOCU1_REACH_NEG_3) {
/* three bytes */
diff -= BOCU1_REACH_NEG_2;
lead = BOCU1_START_NEG_3;
count = 2;
} else {
/* four bytes */
diff -= BOCU1_REACH_NEG_3;
lead = BOCU1_START_NEG_4;
count = 3;
}
}
/* encode the length of the packed result */
//if(count<3) {
//result=(count+1)<<24;
//} else /* count==3, MSB used for the lead byte */ {
result = 0;
//}
/* calculate trail bytes like digits in itoa() */
shift = 0;
var m = 0;
do {
// NEGDIVMOD()
m = diff % BOCU1_TRAIL_COUNT;
diff = ~~(diff / BOCU1_TRAIL_COUNT); // should I use Math.trunc instead? think ~~ is older, and it's a bit faster
if (m < 0) {
--diff;
m += BOCU1_TRAIL_COUNT;
}
// result |= BOCU1_TRAIL_TO_BYTE(NEGDIVMOD(diff, BOCU1_TRAIL_COUNT))<<shift;
result |= BOCU1_TRAIL_TO_BYTE(m) << shift;
shift += 8;
} while (--count > 0);
/* add lead byte */
result |= (lead + diff) << shift;
return result;
} |
JavaScript | function decodeBocu1TrailByte(pRx, b) {
var t, c, count;
if (b <= 0x20) {
// -1s (any of special controls (tab, newline,...space) should not be a trail byte)
/* skip some C0 controls and make the trail byte range contiguous */
t = bocu1ByteToTrail[b];
if (t < 0) {
/* illegal trail byte value */
pRx.prev = BOCU1_ASCII_PREV;
pRx.count = 0;
return -99;
}
// #if BOCU1_MAX_TRAIL<0xff
// } else if (b > BOCU1_MAX_TRAIL) {
// return -99;
// #endif
} else {
t = b - BOCU1_TRAIL_BYTE_OFFSET;
}
/* add trail byte into difference and decrement count */
c = pRx.diff;
count = pRx.count;
if (count === 1) {
/* final trail byte, deliver a code point */
c = pRx.prev + c + t;
if (0 <= c && c <= 0x10ffff) {
/* valid code point result */
pRx.prev = bocu1Prev(c);
pRx.count = 0;
return c;
} else {
/* illegal code point result */
pRx.prev = BOCU1_ASCII_PREV;
pRx.count = 0;
return -99;
}
}
/* intermediate trail byte */
if (count === 2) {
pRx.diff = c + t * BOCU1_TRAIL_COUNT;
} else /* count==3 */ {
pRx.diff = c + t * BOCU1_TRAIL_COUNT_SQRD;
}
pRx.count = count - 1;
return -1;
} | function decodeBocu1TrailByte(pRx, b) {
var t, c, count;
if (b <= 0x20) {
// -1s (any of special controls (tab, newline,...space) should not be a trail byte)
/* skip some C0 controls and make the trail byte range contiguous */
t = bocu1ByteToTrail[b];
if (t < 0) {
/* illegal trail byte value */
pRx.prev = BOCU1_ASCII_PREV;
pRx.count = 0;
return -99;
}
// #if BOCU1_MAX_TRAIL<0xff
// } else if (b > BOCU1_MAX_TRAIL) {
// return -99;
// #endif
} else {
t = b - BOCU1_TRAIL_BYTE_OFFSET;
}
/* add trail byte into difference and decrement count */
c = pRx.diff;
count = pRx.count;
if (count === 1) {
/* final trail byte, deliver a code point */
c = pRx.prev + c + t;
if (0 <= c && c <= 0x10ffff) {
/* valid code point result */
pRx.prev = bocu1Prev(c);
pRx.count = 0;
return c;
} else {
/* illegal code point result */
pRx.prev = BOCU1_ASCII_PREV;
pRx.count = 0;
return -99;
}
}
/* intermediate trail byte */
if (count === 2) {
pRx.diff = c + t * BOCU1_TRAIL_COUNT;
} else /* count==3 */ {
pRx.diff = c + t * BOCU1_TRAIL_COUNT_SQRD;
}
pRx.count = count - 1;
return -1;
} |
JavaScript | function decodeBocu1(pRx, b) {
var prev, c, count;
prev = pRx.prev;
if (prev === 0) {
/* lenient handling of initial 0 values */
prev = pRx.prev = BOCU1_ASCII_PREV;
count = pRx.count = 0;
} else {
count = pRx.count;
}
if (count === 0) {
/* byte in lead position */
if (b <= 0x20) {
/*
* Direct-encoded C0 control code or space.
* Reset prev for C0 control codes but not for space.
*/
if (b !== 0x20) {
pRx.prev = BOCU1_ASCII_PREV;
}
return b;
}
/*
* b is a difference lead byte.
*
* Return a code point directly from a single-byte difference.
*
* For multi-byte difference lead bytes, set the decoder state
* with the partial difference value from the lead byte and
* with the number of trail bytes.
*
* For four-byte differences, the signedness also affects the
* first trail byte, which has special handling farther below.
*/
if (b >= BOCU1_START_NEG_2 && b < BOCU1_START_POS_2) {
/* single-byte difference */
c = prev + (b - BOCU1_MIDDLE);
pRx.prev = bocu1Prev(c);
return c;
} else if (b === BOCU1_RESET) {
/* only reset the state, no code point */
pRx.prev = BOCU1_ASCII_PREV;
return -1;
} else {
return decodeBocu1LeadByte(pRx, b);
}
} else {
/* trail byte in any position */
return decodeBocu1TrailByte(pRx, b);
}
} | function decodeBocu1(pRx, b) {
var prev, c, count;
prev = pRx.prev;
if (prev === 0) {
/* lenient handling of initial 0 values */
prev = pRx.prev = BOCU1_ASCII_PREV;
count = pRx.count = 0;
} else {
count = pRx.count;
}
if (count === 0) {
/* byte in lead position */
if (b <= 0x20) {
/*
* Direct-encoded C0 control code or space.
* Reset prev for C0 control codes but not for space.
*/
if (b !== 0x20) {
pRx.prev = BOCU1_ASCII_PREV;
}
return b;
}
/*
* b is a difference lead byte.
*
* Return a code point directly from a single-byte difference.
*
* For multi-byte difference lead bytes, set the decoder state
* with the partial difference value from the lead byte and
* with the number of trail bytes.
*
* For four-byte differences, the signedness also affects the
* first trail byte, which has special handling farther below.
*/
if (b >= BOCU1_START_NEG_2 && b < BOCU1_START_POS_2) {
/* single-byte difference */
c = prev + (b - BOCU1_MIDDLE);
pRx.prev = bocu1Prev(c);
return c;
} else if (b === BOCU1_RESET) {
/* only reset the state, no code point */
pRx.prev = BOCU1_ASCII_PREV;
return -1;
} else {
return decodeBocu1LeadByte(pRx, b);
}
} else {
/* trail byte in any position */
return decodeBocu1TrailByte(pRx, b);
}
} |
JavaScript | function esPar(numerito) {
if (numerito % 2 === 0) {
return true;
} else {
return false;
}
} | function esPar(numerito) {
if (numerito % 2 === 0) {
return true;
} else {
return false;
}
} |
JavaScript | loadConfig(config) {
Object.keys(config).forEach((key) => {
if (this.CONFIG.hasOwnProperty(key)) {
this.CONFIG[key] = config[key];
console.info(`Set config ${key} to ${config[key]}`);
} else {
console.error("Invalid config key: " + key + ". Ignoring.");
}
});
} | loadConfig(config) {
Object.keys(config).forEach((key) => {
if (this.CONFIG.hasOwnProperty(key)) {
this.CONFIG[key] = config[key];
console.info(`Set config ${key} to ${config[key]}`);
} else {
console.error("Invalid config key: " + key + ". Ignoring.");
}
});
} |
JavaScript | pushState(view) {
history.replaceState(
{ viewName: view },
null, view === this.defaultView ? "" : "#/" + view);
} | pushState(view) {
history.replaceState(
{ viewName: view },
null, view === this.defaultView ? "" : "#/" + view);
} |
JavaScript | appendContent(content, target) {
console.log("appending contnet..");
if (typeof content === "string") {
console.log("Raw");
target.innerHTML = content;
}
else {
// Strip the content from the body tags that get automatically added.
content = content.body.childNodes;
if (content.forEach) {
console.log("NodeList foreach implemented..");
content.forEach((node) => target.appendChild(node));
}
else { // Edge does not support forEach on NodeLists
console.log("Array prototype .call() fallback");
Array.prototype.forEach.call(content, (node) => target.appendChild(node));
}
}
} | appendContent(content, target) {
console.log("appending contnet..");
if (typeof content === "string") {
console.log("Raw");
target.innerHTML = content;
}
else {
// Strip the content from the body tags that get automatically added.
content = content.body.childNodes;
if (content.forEach) {
console.log("NodeList foreach implemented..");
content.forEach((node) => target.appendChild(node));
}
else { // Edge does not support forEach on NodeLists
console.log("Array prototype .call() fallback");
Array.prototype.forEach.call(content, (node) => target.appendChild(node));
}
}
} |
JavaScript | loadHTMLContent(fileName, raw = false) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.onload = (e) => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(xhr.statusText);
}
}
};
xhr.onerror = (e) => {
reject(xhr.statusText);
};
let dir = this.CONFIG.viewsDirectory;
xhr.open("GET", dir + (dir.substr(-1) === "/" ? fileName : "/" + fileName));
if (!raw)
xhr.responseType = "document";
xhr.send();
});
} | loadHTMLContent(fileName, raw = false) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.onload = (e) => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(xhr.statusText);
}
}
};
xhr.onerror = (e) => {
reject(xhr.statusText);
};
let dir = this.CONFIG.viewsDirectory;
xhr.open("GET", dir + (dir.substr(-1) === "/" ? fileName : "/" + fileName));
if (!raw)
xhr.responseType = "document";
xhr.send();
});
} |
JavaScript | replaceContent(view, content) {
this.clearContent(this.targetArea);
this.appendContent(content, this.targetArea);
this.currentView = view;
if (this.CONFIG.changeTitle) {
let title = view;
if (this.CONFIG.customTitles &&
this.CONFIG.customTitles[view])
title = this.CONFIG.customTitles[view];
document.title =
this.CONFIG.titlePattern.replace(this.TITLE_PLACEHOLDER, title);
}
this.pushState(view);
} | replaceContent(view, content) {
this.clearContent(this.targetArea);
this.appendContent(content, this.targetArea);
this.currentView = view;
if (this.CONFIG.changeTitle) {
let title = view;
if (this.CONFIG.customTitles &&
this.CONFIG.customTitles[view])
title = this.CONFIG.customTitles[view];
document.title =
this.CONFIG.titlePattern.replace(this.TITLE_PLACEHOLDER, title);
}
this.pushState(view);
} |
JavaScript | loadView(view) {
if (view === null)
console.error("Tried to load 'null' view. Did you specify a default view?");
if (view !== this.currentView) {
this.loadHTMLContent(view + ".html")
.then((content) => this.replaceContent(view, content))
.catch((err) => this.errorViewNotfound(view, err));
}
} | loadView(view) {
if (view === null)
console.error("Tried to load 'null' view. Did you specify a default view?");
if (view !== this.currentView) {
this.loadHTMLContent(view + ".html")
.then((content) => this.replaceContent(view, content))
.catch((err) => this.errorViewNotfound(view, err));
}
} |
JavaScript | errorViewNotfound(view, err) {
console.error(this.ERROR_MSGS.VIEW_NOT_FOUND + " View name: " + view + ", Views directory: " + this.CONFIG.viewsDirectory, err);
if (this.CONFIG.customNotFound && view !== this.CONFIG.customNotFound) {
this.loadView(this.CONFIG.customNotFound);
} else {
this.replaceContent("404", this.DEFAULT_NOT_FOUND, true);
}
} | errorViewNotfound(view, err) {
console.error(this.ERROR_MSGS.VIEW_NOT_FOUND + " View name: " + view + ", Views directory: " + this.CONFIG.viewsDirectory, err);
if (this.CONFIG.customNotFound && view !== this.CONFIG.customNotFound) {
this.loadView(this.CONFIG.customNotFound);
} else {
this.replaceContent("404", this.DEFAULT_NOT_FOUND, true);
}
} |
JavaScript | function handleMenuClick(event){
if (event.target.id !== menu){
clearWindow()
callbacks[`${event.target.id}`]()
// debugger
}
} | function handleMenuClick(event){
if (event.target.id !== menu){
clearWindow()
callbacks[`${event.target.id}`]()
// debugger
}
} |
JavaScript | function handleFormSubmit(event){
if (event.target.id == "garden-submit"){
let gardenInput = gFormDiv.querySelectorAll('input#garden')
let newGardenObj = {
title: gardenInput[0].value,
gardenType: gardenInput[1].value
}
Api.newGarden(newGardenObj)
location.reload()
}
} | function handleFormSubmit(event){
if (event.target.id == "garden-submit"){
let gardenInput = gFormDiv.querySelectorAll('input#garden')
let newGardenObj = {
title: gardenInput[0].value,
gardenType: gardenInput[1].value
}
Api.newGarden(newGardenObj)
location.reload()
}
} |
JavaScript | function createPlantField(e){
clearDivNewPlantForm()
clearDivPlantField()
let targetGardenId = parseInt(e.target.parentNode.id)
let plantField = document.querySelector(`#plant-field-${targetGardenId}`)
let gardenPlantsArr = Plant.all.filter(plant => plant.garden_id === targetGardenId)
let gardenPlants = ''
for (const plant of gardenPlantsArr){
gardenPlants += createIndividualPlant(plant)
}
plantField.innerHTML += gardenPlants
} | function createPlantField(e){
clearDivNewPlantForm()
clearDivPlantField()
let targetGardenId = parseInt(e.target.parentNode.id)
let plantField = document.querySelector(`#plant-field-${targetGardenId}`)
let gardenPlantsArr = Plant.all.filter(plant => plant.garden_id === targetGardenId)
let gardenPlants = ''
for (const plant of gardenPlantsArr){
gardenPlants += createIndividualPlant(plant)
}
plantField.innerHTML += gardenPlants
} |
JavaScript | function createNewPlantForm(e){
clearDivPlantField()
clearDivNewPlantForm()
let targetGardenId = parseInt(e.target.parentNode.id)
let newPlantField = document.querySelector(`#new-plant-form-${targetGardenId}`)
newPlantField.innerHTML = `
<input hidden id="plant" value="${targetGardenId}" />
Plant Name:
<input id="plant" type="text"/>
<br>
Plant Type:
<input id="plant" type="text"/>
<br>
Plant Family:
<input id="plant" type="text"/>
<br>
<span class="plant-submit" id="${targetGardenId}">Submit</span>
`
let plantSubmit = document.querySelector(`.plant-submit`)
plantSubmit.addEventListener("click", handleNewPlantSubmit)
} | function createNewPlantForm(e){
clearDivPlantField()
clearDivNewPlantForm()
let targetGardenId = parseInt(e.target.parentNode.id)
let newPlantField = document.querySelector(`#new-plant-form-${targetGardenId}`)
newPlantField.innerHTML = `
<input hidden id="plant" value="${targetGardenId}" />
Plant Name:
<input id="plant" type="text"/>
<br>
Plant Type:
<input id="plant" type="text"/>
<br>
Plant Family:
<input id="plant" type="text"/>
<br>
<span class="plant-submit" id="${targetGardenId}">Submit</span>
`
let plantSubmit = document.querySelector(`.plant-submit`)
plantSubmit.addEventListener("click", handleNewPlantSubmit)
} |
JavaScript | function handleNewPlantSubmit(e){
let targetFormId = parseInt(e.target.id)
let newPlantField = document.querySelector(`#new-plant-form-${targetFormId}`)
let plantInput = newPlantField.querySelectorAll("input#plant")
let newPlantObj = {
garden_id: plantInput[0].value,
plantName: plantInput[1].value,
plantType: plantInput[2].value,
plantFamily: plantInput[3].value
}
Api.newPlant(newPlantObj)
location.reload()
} | function handleNewPlantSubmit(e){
let targetFormId = parseInt(e.target.id)
let newPlantField = document.querySelector(`#new-plant-form-${targetFormId}`)
let plantInput = newPlantField.querySelectorAll("input#plant")
let newPlantObj = {
garden_id: plantInput[0].value,
plantName: plantInput[1].value,
plantType: plantInput[2].value,
plantFamily: plantInput[3].value
}
Api.newPlant(newPlantObj)
location.reload()
} |
JavaScript | static loadGardens(gardenObj) {
const plants = gardenObj.relationships.plants.data
const id = gardenObj.id
const { title, gardenType } = gardenObj.attributes
return new Garden({id, title, gardenType, plants})
} | static loadGardens(gardenObj) {
const plants = gardenObj.relationships.plants.data
const id = gardenObj.id
const { title, gardenType } = gardenObj.attributes
return new Garden({id, title, gardenType, plants})
} |
JavaScript | async resolveUserId({ dispatch }, userId) {
const queryOpts = {
limit: 1,
startAt: 1,
where: [['$id', '==', userId]],
}
const [dpnsDoc] = await dispatch('queryDocuments', {
dappName: 'dpns',
typeLocator: 'domain',
queryOpts,
})
return dpnsDoc ? dpnsDoc.toJSON() : null
} | async resolveUserId({ dispatch }, userId) {
const queryOpts = {
limit: 1,
startAt: 1,
where: [['$id', '==', userId]],
}
const [dpnsDoc] = await dispatch('queryDocuments', {
dappName: 'dpns',
typeLocator: 'domain',
queryOpts,
})
return dpnsDoc ? dpnsDoc.toJSON() : null
} |
JavaScript | extend(config, ctx) {
if (ctx.isDev) {
config.devtool = ctx.isClient ? 'source-map' : 'inline-source-map'
}
// if (ctx.isDev && ctx.isClient) {
// config.module.rules.push({
// enforce: 'pre',
// test: /\.(js|vue)$/,
// loader: 'eslint-loader',
// exclude: /(node_modules)/,
// options: { fix: true }
// })
// }
config.module.rules.push({
test: /\.(ogg|mp3|wav|mpe?g)$/i,
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
})
config.node = {
fs: 'empty',
}
} | extend(config, ctx) {
if (ctx.isDev) {
config.devtool = ctx.isClient ? 'source-map' : 'inline-source-map'
}
// if (ctx.isDev && ctx.isClient) {
// config.module.rules.push({
// enforce: 'pre',
// test: /\.(js|vue)$/,
// loader: 'eslint-loader',
// exclude: /(node_modules)/,
// options: { fix: true }
// })
// }
config.module.rules.push({
test: /\.(ogg|mp3|wav|mpe?g)$/i,
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
})
config.node = {
fs: 'empty',
}
} |
JavaScript | async onRegister(context, user) {
return new Promise((resolve, reject) => {
if (user.password == user.confrimPassword) {
firebase
.auth()
.createUserWithEmailAndPassword(
user.email.toString().trim(),
user.password.toString().trim()
)
.then(value => {
console.log("onUser Register:" + value.user.uid);
resolve(value.user.uid);
}).catch(e => {
console.log("on User Register :" + e);
reject(e);
});
}
else {
reject('password invalid')
}
})
} | async onRegister(context, user) {
return new Promise((resolve, reject) => {
if (user.password == user.confrimPassword) {
firebase
.auth()
.createUserWithEmailAndPassword(
user.email.toString().trim(),
user.password.toString().trim()
)
.then(value => {
console.log("onUser Register:" + value.user.uid);
resolve(value.user.uid);
}).catch(e => {
console.log("on User Register :" + e);
reject(e);
});
}
else {
reject('password invalid')
}
})
} |
JavaScript | async onSignOut(context, data) {
return new Promise((resolve, reject) => {
firebase.auth().signOut()
if (data != "") {
resolve("User Log Out Successfully..")
console.log('oon User LogOut Successfully..')
}
else {
console.log('user LogOut Failed')
reject('user LogOut Failed')
}
})
} | async onSignOut(context, data) {
return new Promise((resolve, reject) => {
firebase.auth().signOut()
if (data != "") {
resolve("User Log Out Successfully..")
console.log('oon User LogOut Successfully..')
}
else {
console.log('user LogOut Failed')
reject('user LogOut Failed')
}
})
} |
JavaScript | function checkAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next() //Allows you to proceed
}
res.redirect('/login') //Sends back to login
} | function checkAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next() //Allows you to proceed
}
res.redirect('/login') //Sends back to login
} |
JavaScript | function checkNotAuthenticated(req, res, next){
if(req.isAuthenticated()){
return res.redirect('/dashboard') //Sends you to dashboard
}
next() //Sends to login
} | function checkNotAuthenticated(req, res, next){
if(req.isAuthenticated()){
return res.redirect('/dashboard') //Sends you to dashboard
}
next() //Sends to login
} |
JavaScript | function makeArray( obj ) {
var ary = [];
if ( Array.isArray( obj ) ) {
// use object if already an array
ary = obj;
} else if ( obj && typeof obj.length == 'number' ) {
// convert nodeList to array
for ( var i=0; i < obj.length; i++ ) {
ary.push( obj[i] );
}
} else {
// array of single index
ary.push( obj );
}
return ary;
} | function makeArray( obj ) {
var ary = [];
if ( Array.isArray( obj ) ) {
// use object if already an array
ary = obj;
} else if ( obj && typeof obj.length == 'number' ) {
// convert nodeList to array
for ( var i=0; i < obj.length; i++ ) {
ary.push( obj[i] );
}
} else {
// array of single index
ary.push( obj );
}
return ary;
} |
JavaScript | function ensureConnected(remote, callback) {
if (remote.getServer()) {
callback(null, isConnected(remote));
} else {
callback(null, false);
}
} | function ensureConnected(remote, callback) {
if (remote.getServer()) {
callback(null, isConnected(remote));
} else {
callback(null, false);
}
} |
JavaScript | function isConnected(remote) {
if (isNaN(remote._ledger_current_index)) {
// Remote is missing the index of last ledger closed. Unprepared to submit
// transactions
return false;
}
var server = remote.getServer();
if (!server) return false;
if (remote._stand_alone){
// If rippled is in standalone mode we can assume there will not be a
// ledger close within 30 seconds.
return true;
}
return (Date.now() - server._lastLedgerClose) <= CONNECTION_TIMEOUT;
} | function isConnected(remote) {
if (isNaN(remote._ledger_current_index)) {
// Remote is missing the index of last ledger closed. Unprepared to submit
// transactions
return false;
}
var server = remote.getServer();
if (!server) return false;
if (remote._stand_alone){
// If rippled is in standalone mode we can assume there will not be a
// ledger close within 30 seconds.
return true;
}
return (Date.now() - server._lastLedgerClose) <= CONNECTION_TIMEOUT;
} |
JavaScript | function attachPreviousAndNextTransactionIdentifiers(response, notificationDetails, callback) {
// Get all of the transactions affecting the specified
// account in the given ledger. This is done so that
// we can query for one more than that number on either
// side to ensure that we'll find the next and previous
// transactions, no matter how many transactions the
// given account had in the same ledger
function getAccountTransactionsInBaseTransactionLedger(async_callback) {
var params = {
account: notificationDetails.account,
ledger_index_min: notificationDetails.transaction.ledger_index,
ledger_index_max: notificationDetails.transaction.ledger_index,
exclude_failed: false,
max: 99999999,
limit: 200 // arbitrary, just checking number of transactions in ledger
};
transactions.getAccountTransactions(params, response, async_callback);
}
// All we care about is the count of the transactions
function countAccountTransactionsInBaseTransactionledger(transactions, async_callback) {
async_callback(null, transactions.length);
}
// Query for one more than the numTransactionsInLedger
// going forward and backwards to get a range of transactions
// that will definitely include the next and previous transactions
function getNextAndPreviousTransactions(numTransactionsInLedger, async_callback) {
async.concat([false, true], function(earliestFirst, async_concat_callback){
var params = {
account: notificationDetails.account,
max: numTransactionsInLedger + 1,
min: numTransactionsInLedger + 1,
limit: numTransactionsInLedger + 1,
earliestFirst: earliestFirst
};
// In radrd -1 corresponds to the first or last ledger
// in its database, depending on whether it is the min or max value
if (params.earliestFirst) {
params.ledger_index_max = -1;
params.ledger_index_min = notificationDetails.transaction.ledger_index;
} else {
params.ledger_index_max = notificationDetails.transaction.ledger_index;
params.ledger_index_min = -1;
}
transactions.getAccountTransactions(params, response, async_concat_callback);
}, async_callback);
}
// Sort the transactions returned by ledger_index and remove duplicates
function sortTransactions(allTransactions, async_callback) {
allTransactions.push(notificationDetails.transaction);
var transactions = _.uniq(allTransactions, function(tx) {
return tx.hash;
});
// Sort transactions in ascending order (earliestFirst) by ledger_index
transactions.sort(function(a, b) {
if (a.ledger_index === b.ledger_index) {
return a.date <= b.date ? -1 : 1;
} else {
return a.ledger_index < b.ledger_index ? -1 : 1;
}
});
async_callback(null, transactions);
}
// Find the baseTransaction amongst the results. Because the
// transactions have been sorted, the next and previous transactions
// will be the ones on either side of the base transaction
function findPreviousAndNextTransactions(transactions, async_callback) {
// Find the index in the array of the baseTransaction
var baseTransactionIndex = _.findIndex(transactions, function(possibility) {
if (possibility.hash === notificationDetails.transaction.hash) {
return true;
} else if (possibility.client_resource_id &&
(possibility.client_resource_id === notificationDetails.transaction.client_resource_id ||
possibility.client_resource_id === notificationDetails.identifier)) {
return true;
} else {
return false;
}
});
// The previous transaction is the one with an index in
// the array of baseTransactionIndex - 1
if (baseTransactionIndex > 0) {
var previous_transaction = transactions[baseTransactionIndex - 1];
notificationDetails.previous_transaction_identifier = (previous_transaction.from_local_db ? previous_transaction.client_resource_id : previous_transaction.hash);
notificationDetails.previous_hash = previous_transaction.hash;
}
// The next transaction is the one with an index in
// the array of baseTransactionIndex + 1
if (baseTransactionIndex + 1 < transactions.length) {
var next_transaction = transactions[baseTransactionIndex + 1];
notificationDetails.next_transaction_identifier = (next_transaction.from_local_db ? next_transaction.client_resource_id : next_transaction.hash);
notificationDetails.next_hash = next_transaction.hash;
}
async_callback(null, notificationDetails);
};
var steps = [
getAccountTransactionsInBaseTransactionLedger,
countAccountTransactionsInBaseTransactionledger,
getNextAndPreviousTransactions,
sortTransactions,
findPreviousAndNextTransactions
];
async.waterfall(steps, callback);
} | function attachPreviousAndNextTransactionIdentifiers(response, notificationDetails, callback) {
// Get all of the transactions affecting the specified
// account in the given ledger. This is done so that
// we can query for one more than that number on either
// side to ensure that we'll find the next and previous
// transactions, no matter how many transactions the
// given account had in the same ledger
function getAccountTransactionsInBaseTransactionLedger(async_callback) {
var params = {
account: notificationDetails.account,
ledger_index_min: notificationDetails.transaction.ledger_index,
ledger_index_max: notificationDetails.transaction.ledger_index,
exclude_failed: false,
max: 99999999,
limit: 200 // arbitrary, just checking number of transactions in ledger
};
transactions.getAccountTransactions(params, response, async_callback);
}
// All we care about is the count of the transactions
function countAccountTransactionsInBaseTransactionledger(transactions, async_callback) {
async_callback(null, transactions.length);
}
// Query for one more than the numTransactionsInLedger
// going forward and backwards to get a range of transactions
// that will definitely include the next and previous transactions
function getNextAndPreviousTransactions(numTransactionsInLedger, async_callback) {
async.concat([false, true], function(earliestFirst, async_concat_callback){
var params = {
account: notificationDetails.account,
max: numTransactionsInLedger + 1,
min: numTransactionsInLedger + 1,
limit: numTransactionsInLedger + 1,
earliestFirst: earliestFirst
};
// In radrd -1 corresponds to the first or last ledger
// in its database, depending on whether it is the min or max value
if (params.earliestFirst) {
params.ledger_index_max = -1;
params.ledger_index_min = notificationDetails.transaction.ledger_index;
} else {
params.ledger_index_max = notificationDetails.transaction.ledger_index;
params.ledger_index_min = -1;
}
transactions.getAccountTransactions(params, response, async_concat_callback);
}, async_callback);
}
// Sort the transactions returned by ledger_index and remove duplicates
function sortTransactions(allTransactions, async_callback) {
allTransactions.push(notificationDetails.transaction);
var transactions = _.uniq(allTransactions, function(tx) {
return tx.hash;
});
// Sort transactions in ascending order (earliestFirst) by ledger_index
transactions.sort(function(a, b) {
if (a.ledger_index === b.ledger_index) {
return a.date <= b.date ? -1 : 1;
} else {
return a.ledger_index < b.ledger_index ? -1 : 1;
}
});
async_callback(null, transactions);
}
// Find the baseTransaction amongst the results. Because the
// transactions have been sorted, the next and previous transactions
// will be the ones on either side of the base transaction
function findPreviousAndNextTransactions(transactions, async_callback) {
// Find the index in the array of the baseTransaction
var baseTransactionIndex = _.findIndex(transactions, function(possibility) {
if (possibility.hash === notificationDetails.transaction.hash) {
return true;
} else if (possibility.client_resource_id &&
(possibility.client_resource_id === notificationDetails.transaction.client_resource_id ||
possibility.client_resource_id === notificationDetails.identifier)) {
return true;
} else {
return false;
}
});
// The previous transaction is the one with an index in
// the array of baseTransactionIndex - 1
if (baseTransactionIndex > 0) {
var previous_transaction = transactions[baseTransactionIndex - 1];
notificationDetails.previous_transaction_identifier = (previous_transaction.from_local_db ? previous_transaction.client_resource_id : previous_transaction.hash);
notificationDetails.previous_hash = previous_transaction.hash;
}
// The next transaction is the one with an index in
// the array of baseTransactionIndex + 1
if (baseTransactionIndex + 1 < transactions.length) {
var next_transaction = transactions[baseTransactionIndex + 1];
notificationDetails.next_transaction_identifier = (next_transaction.from_local_db ? next_transaction.client_resource_id : next_transaction.hash);
notificationDetails.next_hash = next_transaction.hash;
}
async_callback(null, notificationDetails);
};
var steps = [
getAccountTransactionsInBaseTransactionLedger,
countAccountTransactionsInBaseTransactionledger,
getNextAndPreviousTransactions,
sortTransactions,
findPreviousAndNextTransactions
];
async.waterfall(steps, callback);
} |
JavaScript | function sortTransactions(allTransactions, async_callback) {
allTransactions.push(notificationDetails.transaction);
var transactions = _.uniq(allTransactions, function(tx) {
return tx.hash;
});
// Sort transactions in ascending order (earliestFirst) by ledger_index
transactions.sort(function(a, b) {
if (a.ledger_index === b.ledger_index) {
return a.date <= b.date ? -1 : 1;
} else {
return a.ledger_index < b.ledger_index ? -1 : 1;
}
});
async_callback(null, transactions);
} | function sortTransactions(allTransactions, async_callback) {
allTransactions.push(notificationDetails.transaction);
var transactions = _.uniq(allTransactions, function(tx) {
return tx.hash;
});
// Sort transactions in ascending order (earliestFirst) by ledger_index
transactions.sort(function(a, b) {
if (a.ledger_index === b.ledger_index) {
return a.date <= b.date ? -1 : 1;
} else {
return a.ledger_index < b.ledger_index ? -1 : 1;
}
});
async_callback(null, transactions);
} |
JavaScript | function findPreviousAndNextTransactions(transactions, async_callback) {
// Find the index in the array of the baseTransaction
var baseTransactionIndex = _.findIndex(transactions, function(possibility) {
if (possibility.hash === notificationDetails.transaction.hash) {
return true;
} else if (possibility.client_resource_id &&
(possibility.client_resource_id === notificationDetails.transaction.client_resource_id ||
possibility.client_resource_id === notificationDetails.identifier)) {
return true;
} else {
return false;
}
});
// The previous transaction is the one with an index in
// the array of baseTransactionIndex - 1
if (baseTransactionIndex > 0) {
var previous_transaction = transactions[baseTransactionIndex - 1];
notificationDetails.previous_transaction_identifier = (previous_transaction.from_local_db ? previous_transaction.client_resource_id : previous_transaction.hash);
notificationDetails.previous_hash = previous_transaction.hash;
}
// The next transaction is the one with an index in
// the array of baseTransactionIndex + 1
if (baseTransactionIndex + 1 < transactions.length) {
var next_transaction = transactions[baseTransactionIndex + 1];
notificationDetails.next_transaction_identifier = (next_transaction.from_local_db ? next_transaction.client_resource_id : next_transaction.hash);
notificationDetails.next_hash = next_transaction.hash;
}
async_callback(null, notificationDetails);
} | function findPreviousAndNextTransactions(transactions, async_callback) {
// Find the index in the array of the baseTransaction
var baseTransactionIndex = _.findIndex(transactions, function(possibility) {
if (possibility.hash === notificationDetails.transaction.hash) {
return true;
} else if (possibility.client_resource_id &&
(possibility.client_resource_id === notificationDetails.transaction.client_resource_id ||
possibility.client_resource_id === notificationDetails.identifier)) {
return true;
} else {
return false;
}
});
// The previous transaction is the one with an index in
// the array of baseTransactionIndex - 1
if (baseTransactionIndex > 0) {
var previous_transaction = transactions[baseTransactionIndex - 1];
notificationDetails.previous_transaction_identifier = (previous_transaction.from_local_db ? previous_transaction.client_resource_id : previous_transaction.hash);
notificationDetails.previous_hash = previous_transaction.hash;
}
// The next transaction is the one with an index in
// the array of baseTransactionIndex + 1
if (baseTransactionIndex + 1 < transactions.length) {
var next_transaction = transactions[baseTransactionIndex + 1];
notificationDetails.next_transaction_identifier = (next_transaction.from_local_db ? next_transaction.client_resource_id : next_transaction.hash);
notificationDetails.next_hash = next_transaction.hash;
}
async_callback(null, notificationDetails);
} |
JavaScript | function renameCounterpartyToIssuer(balanceChanges) {
return _.mapValues(balanceChanges, function(changes) {
return _.map(changes, function(change) {
var converted = _.omit(change, 'counterparty');
converted.issuer = change.counterparty;
return converted;
});
});
} | function renameCounterpartyToIssuer(balanceChanges) {
return _.mapValues(balanceChanges, function(changes) {
return _.map(changes, function(change) {
var converted = _.omit(change, 'counterparty');
converted.issuer = change.counterparty;
return converted;
});
});
} |
JavaScript | function closeLedgers(conn) {
for (var i=0; i<LEDGER_OFFSET + 2; i++) {
conn.send(fixtures.ledgerClose());
}
} | function closeLedgers(conn) {
for (var i=0; i<LEDGER_OFFSET + 2; i++) {
conn.send(fixtures.ledgerClose());
}
} |
JavaScript | function deployProcess() {
filename = 'sysout.bpmn';
filepath = path.join(__dirname, filename);
console.log(filepath);
request(
{
method: "POST", // see https://docs.camunda.org/manual/latest/reference/rest/deployment/post-deployment/
uri: camundaEngineUrl + 'engine/default/deployment/create',
headers: {
"Content-Type": "multipart/form-data"
},
formData : {
'deployment-name': 'sysout',
'enable-duplicate-filtering': 'true',
'deploy-changed-only': 'true',
'scripttest.bpmn': {
'value': fs.createReadStream(filepath),
'options': {'filename': filename}
}
}
}, function (err, res, body) {
if (err) {
console.log(err);
throw err;
}
console.log('[%s] Deployment succeeded: ' + body);
});
} | function deployProcess() {
filename = 'sysout.bpmn';
filepath = path.join(__dirname, filename);
console.log(filepath);
request(
{
method: "POST", // see https://docs.camunda.org/manual/latest/reference/rest/deployment/post-deployment/
uri: camundaEngineUrl + 'engine/default/deployment/create',
headers: {
"Content-Type": "multipart/form-data"
},
formData : {
'deployment-name': 'sysout',
'enable-duplicate-filtering': 'true',
'deploy-changed-only': 'true',
'scripttest.bpmn': {
'value': fs.createReadStream(filepath),
'options': {'filename': filename}
}
}
}, function (err, res, body) {
if (err) {
console.log(err);
throw err;
}
console.log('[%s] Deployment succeeded: ' + body);
});
} |
JavaScript | transformVendorResult(entities) {
if (Array.isArray(entities)) {
const vendors = entities
.map(item => this.transformVendorResultEntity(item))
.filter(vendor => vendor);
return {
vendors,
};
}
const vendor = this.transformVendorResultEntity(entities);
return { vendor };
} | transformVendorResult(entities) {
if (Array.isArray(entities)) {
const vendors = entities
.map(item => this.transformVendorResultEntity(item))
.filter(vendor => vendor);
return {
vendors,
};
}
const vendor = this.transformVendorResultEntity(entities);
return { vendor };
} |
JavaScript | transformAddressRequest(address) {
return {
address: address.address_1,
attention: `${address.first_name} ${address.last_name}`,
city: address.city || '',
country: countryFromCode(address.country),
phone: address.phone || '',
state: address.state || '',
street2: address.address_2 || '',
zip: address.postcode || '',
};
} | transformAddressRequest(address) {
return {
address: address.address_1,
attention: `${address.first_name} ${address.last_name}`,
city: address.city || '',
country: countryFromCode(address.country),
phone: address.phone || '',
state: address.state || '',
street2: address.address_2 || '',
zip: address.postcode || '',
};
} |
JavaScript | sanitizeParams(params) {
Object.keys(params).forEach(
key => params[key] === undefined && delete params[key]
);
} | sanitizeParams(params) {
Object.keys(params).forEach(
key => params[key] === undefined && delete params[key]
);
} |
JavaScript | draw(canvas, scale = 16) {
const drawMap = (canvas, scale = 16) => {
if (this.hasBoundary) {
const offset = this.showBounds ? 1 : 0;
for (let x = 0 - offset; x < this.size.x + offset; x++) {
for (let y = 0 - offset; y < this.size.y + offset; y++) {
const cell = this.getCell(x, y);
if (cell !== CELL_TYPES.EMPTY) {
drawNodePair(canvas, [{ x, y }, cell], this.pos.x, this.pos.y, scale);
}
}
}
} else {
this.mapToNodePairArray(true).forEach(
nodePair => drawNodePair(canvas, nodePair, this.pos.x, this.pos.y, scale)
);
}
}
if (this.internalFrameBuffer === null) {
drawMap(canvas, scale);
} else {
if (this.internalFrameBuffer.isDirty) {
drawMap(this.internalFrameBuffer, scale);
this.internalFrameBuffer.isDirty = false;
} else {
for (let i = 0; i < this.changedCells.length; i += 3) {
drawNodePair(this.internalFrameBuffer, [{ x: this.changedCells[i + 1], y: this.changedCells[i + 2] }, this.changedCells[i]], this.pos.x, this.pos.y, scale);
}
}
canvas.context.drawImage(this.internalFrameBuffer.element, 0, 0);
this.changedCells = [];
}
} | draw(canvas, scale = 16) {
const drawMap = (canvas, scale = 16) => {
if (this.hasBoundary) {
const offset = this.showBounds ? 1 : 0;
for (let x = 0 - offset; x < this.size.x + offset; x++) {
for (let y = 0 - offset; y < this.size.y + offset; y++) {
const cell = this.getCell(x, y);
if (cell !== CELL_TYPES.EMPTY) {
drawNodePair(canvas, [{ x, y }, cell], this.pos.x, this.pos.y, scale);
}
}
}
} else {
this.mapToNodePairArray(true).forEach(
nodePair => drawNodePair(canvas, nodePair, this.pos.x, this.pos.y, scale)
);
}
}
if (this.internalFrameBuffer === null) {
drawMap(canvas, scale);
} else {
if (this.internalFrameBuffer.isDirty) {
drawMap(this.internalFrameBuffer, scale);
this.internalFrameBuffer.isDirty = false;
} else {
for (let i = 0; i < this.changedCells.length; i += 3) {
drawNodePair(this.internalFrameBuffer, [{ x: this.changedCells[i + 1], y: this.changedCells[i + 2] }, this.changedCells[i]], this.pos.x, this.pos.y, scale);
}
}
canvas.context.drawImage(this.internalFrameBuffer.element, 0, 0);
this.changedCells = [];
}
} |
JavaScript | mapToNodePairArray(ignoreEmptyCells = true) {
const mapArray = [];
for (const [x, col] of this.map) {
for (const [y, cell] of col) {
if (!ignoreEmptyCells || cell !== CELL_TYPES.EMPTY) {
mapArray.push([
new UMath.Vec2(x, y), cell
]);
}
}
}
return mapArray;
} | mapToNodePairArray(ignoreEmptyCells = true) {
const mapArray = [];
for (const [x, col] of this.map) {
for (const [y, cell] of col) {
if (!ignoreEmptyCells || cell !== CELL_TYPES.EMPTY) {
mapArray.push([
new UMath.Vec2(x, y), cell
]);
}
}
}
return mapArray;
} |
JavaScript | function generatePath() {
if (isPathGenLocked) { return; }
/*
The message must be an array that contains [
The Width of the World, The Height of the World,
Whether or not the World has Boundaries,
The Delay Between Actions, Maximum Cell Queue Length,
The Index of the Currently Selected Algorithm
]
*/
pathGenerator.postMessage([ WORLD_MAP.size.x, WORLD_MAP.size.y, WORLD_MAP.hasBoundary, actionDelay, MAX_CELL_QUEUE, currentAlgorithm ]);
} | function generatePath() {
if (isPathGenLocked) { return; }
/*
The message must be an array that contains [
The Width of the World, The Height of the World,
Whether or not the World has Boundaries,
The Delay Between Actions, Maximum Cell Queue Length,
The Index of the Currently Selected Algorithm
]
*/
pathGenerator.postMessage([ WORLD_MAP.size.x, WORLD_MAP.size.y, WORLD_MAP.hasBoundary, actionDelay, MAX_CELL_QUEUE, currentAlgorithm ]);
} |
JavaScript | async function generatePath(worldMap, algorithm, actionDelay = 0) {
if (lockPathGen) { return null; }
lockPathGen = true;
self.postMessage([ "lock_gen" ]);
worldMap.clearMap();
const start = worldMap.pickRandomPos();
const goal = worldMap.pickRandomPos();
for (let i = 0; i < worldMap.size.x * worldMap.size.y / 3; i++) {
const pos = worldMap.pickRandomPos();
if (start.x === pos.x && start.y === pos.y || goal.x === pos.x && goal.y === pos.y) {
continue;
}
worldMap.putCell(WorldMap.CELL_TYPES.WALL, pos.x, pos.y);
}
const path = await algorithm.search(
start, goal,
worldMap, actionDelay
);
worldMap.sendCellQueue();
lockPathGen = false;
self.postMessage([ "unlock_gen" ]);
return path;
} | async function generatePath(worldMap, algorithm, actionDelay = 0) {
if (lockPathGen) { return null; }
lockPathGen = true;
self.postMessage([ "lock_gen" ]);
worldMap.clearMap();
const start = worldMap.pickRandomPos();
const goal = worldMap.pickRandomPos();
for (let i = 0; i < worldMap.size.x * worldMap.size.y / 3; i++) {
const pos = worldMap.pickRandomPos();
if (start.x === pos.x && start.y === pos.y || goal.x === pos.x && goal.y === pos.y) {
continue;
}
worldMap.putCell(WorldMap.CELL_TYPES.WALL, pos.x, pos.y);
}
const path = await algorithm.search(
start, goal,
worldMap, actionDelay
);
worldMap.sendCellQueue();
lockPathGen = false;
self.postMessage([ "unlock_gen" ]);
return path;
} |
JavaScript | function svg_to_graph() {
let all_nodes = document.querySelectorAll("g.node");
let node_titles = document.querySelectorAll("g.node title");
let all_edges = document.querySelectorAll("g.edge");
let edge_titles = document.querySelectorAll("g.edge title");
let node_map = {};
for (let node of all_nodes) {
node_map[node.firstElementChild.innerHTML] = node;
}
let graph_structure = {};
for (let title of node_titles) {
graph_structure[title.innerHTML] = { "id": title.innerHTML, "edges": [] };
}
for (let edge_title of edge_titles) {
// skip invisible edges
if (edge_title.parentNode.classList.contains("invisible")) {
continue;
}
let parts = edge_title.innerHTML.split("->");
let fr = parts[0];
let to = parts[1];
graph_structure[fr].edges.push(to);
}
return graph_structure;
} | function svg_to_graph() {
let all_nodes = document.querySelectorAll("g.node");
let node_titles = document.querySelectorAll("g.node title");
let all_edges = document.querySelectorAll("g.edge");
let edge_titles = document.querySelectorAll("g.edge title");
let node_map = {};
for (let node of all_nodes) {
node_map[node.firstElementChild.innerHTML] = node;
}
let graph_structure = {};
for (let title of node_titles) {
graph_structure[title.innerHTML] = { "id": title.innerHTML, "edges": [] };
}
for (let edge_title of edge_titles) {
// skip invisible edges
if (edge_title.parentNode.classList.contains("invisible")) {
continue;
}
let parts = edge_title.innerHTML.split("->");
let fr = parts[0];
let to = parts[1];
graph_structure[fr].edges.push(to);
}
return graph_structure;
} |
JavaScript | function extract_points_and_limits(polygon_node) {
let points = [];
let minx, miny, maxx, maxy;
for (let coords of polygon_node.getAttribute("points").split(" ")) {
let [x, y] = coords.split(",");
x = parseFloat(x);
y = parseFloat(y);
if (isNaN(x) || isNaN(y)) {
continue;
}
points.push([x, y]);
if (minx == undefined || x < minx) {
minx = x;
}
if (miny == undefined || y < miny) {
miny = y;
}
if (maxx == undefined || x > maxx) {
maxx = x;
}
if (maxy == undefined || y > maxy) {
maxy = y;
}
}
return [points, [minx, miny, maxx, maxy]];
} | function extract_points_and_limits(polygon_node) {
let points = [];
let minx, miny, maxx, maxy;
for (let coords of polygon_node.getAttribute("points").split(" ")) {
let [x, y] = coords.split(",");
x = parseFloat(x);
y = parseFloat(y);
if (isNaN(x) || isNaN(y)) {
continue;
}
points.push([x, y]);
if (minx == undefined || x < minx) {
minx = x;
}
if (miny == undefined || y < miny) {
miny = y;
}
if (maxx == undefined || x > maxx) {
maxx = x;
}
if (maxy == undefined || y > maxy) {
maxy = y;
}
}
return [points, [minx, miny, maxx, maxy]];
} |
JavaScript | function subsume_polygon(top_node, bot_node) {
// Re-size desctop node
// We grab the "desctop" and "descbot" nodes, extract the points from
// their polygons, and then resize the desctop node so that it stretches
// over both nodes (they're set up in graphviz to be laid out directly
// above/below each other).
let top_poly = top_node.querySelector("polygon");
let bot_poly = bot_node.querySelector("polygon");
let [top_points, toplimits] = extract_points_and_limits(top_poly);
let [bot_points, botlimits] = extract_points_and_limits(bot_poly);
// Take top points from top polygon + bottom points from bottom polygon:
let tl, tr, bl, br;
for (let [top_x, top_y] of top_points) {
if (top_y == toplimits[1]) {
if (top_x == toplimits[0]) {
tl = [top_x, top_y];
} else {
tr = [top_x, top_y];
}
}
}
for (let [bot_x, bot_y] of bot_points) {
if (bot_y != botlimits[1]) {
if (bot_x == botlimits[0]) {
bl = [bot_x, bot_y];
} else {
br = [bot_x, bot_y];
}
}
}
let new_points = [tl, tr, br, bl];
// Construct a points attribute string for a new polygon
let points_attr = "";
for (let [x, y] of new_points) {
points_attr += " " + x + "," + y;
}
// Remove bottom description node
bot_node.parentNode.removeChild(bot_node);
// Expand top description node with the new points
top_poly.setAttribute("points", points_attr);
} | function subsume_polygon(top_node, bot_node) {
// Re-size desctop node
// We grab the "desctop" and "descbot" nodes, extract the points from
// their polygons, and then resize the desctop node so that it stretches
// over both nodes (they're set up in graphviz to be laid out directly
// above/below each other).
let top_poly = top_node.querySelector("polygon");
let bot_poly = bot_node.querySelector("polygon");
let [top_points, toplimits] = extract_points_and_limits(top_poly);
let [bot_points, botlimits] = extract_points_and_limits(bot_poly);
// Take top points from top polygon + bottom points from bottom polygon:
let tl, tr, bl, br;
for (let [top_x, top_y] of top_points) {
if (top_y == toplimits[1]) {
if (top_x == toplimits[0]) {
tl = [top_x, top_y];
} else {
tr = [top_x, top_y];
}
}
}
for (let [bot_x, bot_y] of bot_points) {
if (bot_y != botlimits[1]) {
if (bot_x == botlimits[0]) {
bl = [bot_x, bot_y];
} else {
br = [bot_x, bot_y];
}
}
}
let new_points = [tl, tr, br, bl];
// Construct a points attribute string for a new polygon
let points_attr = "";
for (let [x, y] of new_points) {
points_attr += " " + x + "," + y;
}
// Remove bottom description node
bot_node.parentNode.removeChild(bot_node);
// Expand top description node with the new points
top_poly.setAttribute("points", points_attr);
} |
JavaScript | function reposition_node(target_node, place_onto) {
// We can't actually nest a DIV or other HTML stuff inside of an SVG
// group... but we can put it on top and give it the exact same
// coordinates! T_T
let desc_bcr = place_onto.getBoundingClientRect();
// Absolute position will be relative to the parent, which we assume
// has relative position
let parent_bcr = target_node.parentNode.getBoundingClientRect();
target_node.style.position = "absolute";
target_node.style.left = (desc_bcr.x - parent_bcr.x) + "px";
target_node.style.top = (desc_bcr.y - parent_bcr.y) + "px";
target_node.style.width = desc_bcr.width + "px";
target_node.style.height = desc_bcr.height + "px";
target_node.style.boxSizing = "border-box";
} | function reposition_node(target_node, place_onto) {
// We can't actually nest a DIV or other HTML stuff inside of an SVG
// group... but we can put it on top and give it the exact same
// coordinates! T_T
let desc_bcr = place_onto.getBoundingClientRect();
// Absolute position will be relative to the parent, which we assume
// has relative position
let parent_bcr = target_node.parentNode.getBoundingClientRect();
target_node.style.position = "absolute";
target_node.style.left = (desc_bcr.x - parent_bcr.x) + "px";
target_node.style.top = (desc_bcr.y - parent_bcr.y) + "px";
target_node.style.width = desc_bcr.width + "px";
target_node.style.height = desc_bcr.height + "px";
target_node.style.boxSizing = "border-box";
} |
JavaScript | function self_and_descendants(node_id) {
let result = [ node_id ];
for (let child of graph_structure[node_id].edges) {
result = result.concat(self_and_descendants(child));
}
return result;
} | function self_and_descendants(node_id) {
let result = [ node_id ];
for (let child of graph_structure[node_id].edges) {
result = result.concat(self_and_descendants(child));
}
return result;
} |
JavaScript | function createRespectPluginReducer(actionName) {
return (state = initialState, action) => {
switch (action.type) {
case actionName.REQUEST:
return {
...state,
loading: true,
};
case actionName.CREATE:
return {
...state,
loading: false,
data: action.data
};
case actionName.SUCCESS:
return {
...state,
loading: false,
data: action.data
};
case actionName.FAILURE:
return {
...state,
loading: false,
error: get(action, "error", null),
};
case actionName.REMOVE:
return {
data: null,
loading: false,
error: null,
};
default:
return state;
}
}
} | function createRespectPluginReducer(actionName) {
return (state = initialState, action) => {
switch (action.type) {
case actionName.REQUEST:
return {
...state,
loading: true,
};
case actionName.CREATE:
return {
...state,
loading: false,
data: action.data
};
case actionName.SUCCESS:
return {
...state,
loading: false,
data: action.data
};
case actionName.FAILURE:
return {
...state,
loading: false,
error: get(action, "error", null),
};
case actionName.REMOVE:
return {
data: null,
loading: false,
error: null,
};
default:
return state;
}
}
} |
JavaScript | function createDreamTeam(members) {
var arr = [];
var i = 0;
if(Array.isArray(members) === true){
members.forEach(element => {
if(typeof element === "string"){
let elem = element.trim().toUpperCase();
arr[i] = elem[0];
i++;
}else{
return false;
}
});
return arr.sort().join('');
}else{return false};
} | function createDreamTeam(members) {
var arr = [];
var i = 0;
if(Array.isArray(members) === true){
members.forEach(element => {
if(typeof element === "string"){
let elem = element.trim().toUpperCase();
arr[i] = elem[0];
i++;
}else{
return false;
}
});
return arr.sort().join('');
}else{return false};
} |
JavaScript | function checkHttpStatus(response) {
const { statusCode, statusText } = response;
if (statusCode >= 200 && statusCode < 300) {
return response;
}
const error = new Error(statusText);
error.response = response;
throw error;
} | function checkHttpStatus(response) {
const { statusCode, statusText } = response;
if (statusCode >= 200 && statusCode < 300) {
return response;
}
const error = new Error(statusText);
error.response = response;
throw error;
} |
JavaScript | function eFapsFileInput(){
var ins = document.getElementsByTagName("input");
for (var i = 0; i < ins.length; ++i) {
if(ins[i].type.toLowerCase() === "file"){
var fileNode = ins[i];
var parent = fileNode.parentNode;
var node = fileNode.nextSibling;
var add = true;
while (node != null) {
if(node.nodeName == "INPUT"){
if(node.type == "hidden" && node.name == fileNode.name){
node.value = fileNode.value;
add = false;
}
}
node = node.nextSibling;
}
if(add){
var newinput = document.createElement("input");
newinput.type = "hidden";
newinput.name = fileNode.name;
newinput.value = fileNode.value;
parent.appendChild(newinput);
}
}
}
return true;
} | function eFapsFileInput(){
var ins = document.getElementsByTagName("input");
for (var i = 0; i < ins.length; ++i) {
if(ins[i].type.toLowerCase() === "file"){
var fileNode = ins[i];
var parent = fileNode.parentNode;
var node = fileNode.nextSibling;
var add = true;
while (node != null) {
if(node.nodeName == "INPUT"){
if(node.type == "hidden" && node.name == fileNode.name){
node.value = fileNode.value;
add = false;
}
}
node = node.nextSibling;
}
if(add){
var newinput = document.createElement("input");
newinput.type = "hidden";
newinput.name = fileNode.name;
newinput.value = fileNode.value;
parent.appendChild(newinput);
}
}
}
return true;
} |
JavaScript | function initTimer(defaultContext, duration) {
return {
...defaultContext,
timer: {
...defaultContext.timer,
duration
}
};
} | function initTimer(defaultContext, duration) {
return {
...defaultContext,
timer: {
...defaultContext.timer,
duration
}
};
} |
JavaScript | function removeFilter() {
var n = $(this).text().toUpperCase();
if (award_arr.indexOf(n) > -1) {
award_arr.splice(award_arr.indexOf(n), 1);
document.getElementById(n).remove();
$(".dropdown-award-content p:icontains('{}')".replace("{}", n)).find("i").toggleClass("fa-square-o fa-check-square-o");
} else if (practice_arr.indexOf(n) > -1) {
practice_arr.splice(practice_arr.indexOf(n), 1);
document.getElementById(n).remove();
$(".dropdown-practice-content p:icontains('{}')".replace("{}", n)).find("i").toggleClass("fa-square-o fa-check-square-o");
}
searchFunction();
} | function removeFilter() {
var n = $(this).text().toUpperCase();
if (award_arr.indexOf(n) > -1) {
award_arr.splice(award_arr.indexOf(n), 1);
document.getElementById(n).remove();
$(".dropdown-award-content p:icontains('{}')".replace("{}", n)).find("i").toggleClass("fa-square-o fa-check-square-o");
} else if (practice_arr.indexOf(n) > -1) {
practice_arr.splice(practice_arr.indexOf(n), 1);
document.getElementById(n).remove();
$(".dropdown-practice-content p:icontains('{}')".replace("{}", n)).find("i").toggleClass("fa-square-o fa-check-square-o");
}
searchFunction();
} |
JavaScript | function award_filter() {
var n = $(this).text().toUpperCase();
if (award_arr.indexOf(n) > -1) {
award_arr.splice(award_arr.indexOf(n), 1);
document.getElementById(n).remove();
$(".dropdown-award-content p:icontains('{}')".replace("{}", n)).find("i").toggleClass("fa-square-o fa-check-square-o");
} else {
award_arr.push(n);
const tag = document.getElementById("filter-bank-content")
const newTag = document.createElement("button");
newTag.setAttribute('id', n);
newTag.setAttribute('class', "filter-bank-single");
if (n != "MVP") {
var words = n.toLowerCase().split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
words = words.join(" ");
} else {
var words = n
}
const content = document.createTextNode(words);
newTag.appendChild(content);
tag.appendChild(newTag);
$(".dropdown-award-content p:icontains('{}')".replace("{}", n)).find("i").toggleClass("fa-square-o fa-check-square-o");
}
searchFunction();
} | function award_filter() {
var n = $(this).text().toUpperCase();
if (award_arr.indexOf(n) > -1) {
award_arr.splice(award_arr.indexOf(n), 1);
document.getElementById(n).remove();
$(".dropdown-award-content p:icontains('{}')".replace("{}", n)).find("i").toggleClass("fa-square-o fa-check-square-o");
} else {
award_arr.push(n);
const tag = document.getElementById("filter-bank-content")
const newTag = document.createElement("button");
newTag.setAttribute('id', n);
newTag.setAttribute('class', "filter-bank-single");
if (n != "MVP") {
var words = n.toLowerCase().split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
words = words.join(" ");
} else {
var words = n
}
const content = document.createTextNode(words);
newTag.appendChild(content);
tag.appendChild(newTag);
$(".dropdown-award-content p:icontains('{}')".replace("{}", n)).find("i").toggleClass("fa-square-o fa-check-square-o");
}
searchFunction();
} |
JavaScript | function el(tagName, attributes, children) {
if (typeof tagName !== 'string') {
throw new Error('tagName must be a string');
}
var element = document.createElement(tagName);
if (attributes && (typeof attributes === 'undefined' ? 'undefined' : _typeof(attributes)) === 'object') {
Object.keys(attributes).forEach(function (i) {
// Set event handlers
if (/on[A-Z][a-z]/.test(i)) {
element[i.toLowerCase()] = attributes[i];
} else {
// Set attributes
element.setAttribute(i, attributes[i]);
}
});
}
if (typeof children === 'string') {
element.innerHTML = children;
} else if (children instanceof Array) {
children.forEach(function (child) {
element.appendChild(child);
});
}
return element;
} | function el(tagName, attributes, children) {
if (typeof tagName !== 'string') {
throw new Error('tagName must be a string');
}
var element = document.createElement(tagName);
if (attributes && (typeof attributes === 'undefined' ? 'undefined' : _typeof(attributes)) === 'object') {
Object.keys(attributes).forEach(function (i) {
// Set event handlers
if (/on[A-Z][a-z]/.test(i)) {
element[i.toLowerCase()] = attributes[i];
} else {
// Set attributes
element.setAttribute(i, attributes[i]);
}
});
}
if (typeof children === 'string') {
element.innerHTML = children;
} else if (children instanceof Array) {
children.forEach(function (child) {
element.appendChild(child);
});
}
return element;
} |
JavaScript | function el(tagName, attributes, children) {
if (typeof tagName !== 'string') {
throw new Error('tagName must be a string');
}
var element = document.createElement(tagName);
if (attributes && typeof attributes === 'object') {
Object.keys(attributes).forEach(function (i) {
// Set event handlers
if (/on[A-Z][a-z]/.test(i)) {
element[i.toLowerCase()] = attributes[i];
} else {
// Set attributes
element.setAttribute(i, attributes[i]);
}
});
}
if (typeof children === 'string') {
element.innerHTML = children;
} else if (children instanceof Array) {
children.forEach(function (child) {
element.appendChild(child);
});
}
return element;
} | function el(tagName, attributes, children) {
if (typeof tagName !== 'string') {
throw new Error('tagName must be a string');
}
var element = document.createElement(tagName);
if (attributes && typeof attributes === 'object') {
Object.keys(attributes).forEach(function (i) {
// Set event handlers
if (/on[A-Z][a-z]/.test(i)) {
element[i.toLowerCase()] = attributes[i];
} else {
// Set attributes
element.setAttribute(i, attributes[i]);
}
});
}
if (typeof children === 'string') {
element.innerHTML = children;
} else if (children instanceof Array) {
children.forEach(function (child) {
element.appendChild(child);
});
}
return element;
} |
JavaScript | function onIncomingSDP(sdp) {
console.log("Incoming SDP is "+ JSON.stringify(sdp));
peer_connection.setRemoteDescription(sdp).then(() => {
setStatus("Remote SDP set");
if (sdp.type != "offer")
return;
setStatus("Got SDP offer, creating answer");
peer_connection.createAnswer().then(onLocalDescription).catch(setStatus);
}).catch(setStatus);
} | function onIncomingSDP(sdp) {
console.log("Incoming SDP is "+ JSON.stringify(sdp));
peer_connection.setRemoteDescription(sdp).then(() => {
setStatus("Remote SDP set");
if (sdp.type != "offer")
return;
setStatus("Got SDP offer, creating answer");
peer_connection.createAnswer().then(onLocalDescription).catch(setStatus);
}).catch(setStatus);
} |
JavaScript | function onLocalDescription(desc) {
console.log("Got local description: " + JSON.stringify(desc));
peer_connection.setLocalDescription(desc).then(function() {
setStatus("Sending SDP answer");
ws_conn.send(JSON.stringify(peer_connection.localDescription));
});
} | function onLocalDescription(desc) {
console.log("Got local description: " + JSON.stringify(desc));
peer_connection.setLocalDescription(desc).then(function() {
setStatus("Sending SDP answer");
ws_conn.send(JSON.stringify(peer_connection.localDescription));
});
} |
JavaScript | function onIncomingICE(ice) {
console.log("Incoming ICE: " + JSON.stringify(ice));
var candidate = new RTCIceCandidate(ice);
peer_connection.addIceCandidate(candidate).catch(setStatus);
} | function onIncomingICE(ice) {
console.log("Incoming ICE: " + JSON.stringify(ice));
var candidate = new RTCIceCandidate(ice);
peer_connection.addIceCandidate(candidate).catch(setStatus);
} |
JavaScript | createNegotiatedProtocol (buffer) {
const h = [
buffer.readUInt8(),
buffer.readUInt8(),
buffer.readUInt8(),
buffer.readUInt8()
]
if (h[0] === 0x48 && h[1] === 0x54 && h[2] === 0x54 && h[3] === 0x50) {
throw newError(
'Server responded HTTP. Make sure you are not trying to connect to the http endpoint ' +
'(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)'
)
}
const negotiatedVersion = Number(h[3] + '.' + h[2])
if (this._log.isDebugEnabled()) {
this._log.debug(
`${this._connection} negotiated protocol version ${negotiatedVersion}`
)
}
return this._createProtocolWithVersion(negotiatedVersion)
} | createNegotiatedProtocol (buffer) {
const h = [
buffer.readUInt8(),
buffer.readUInt8(),
buffer.readUInt8(),
buffer.readUInt8()
]
if (h[0] === 0x48 && h[1] === 0x54 && h[2] === 0x54 && h[3] === 0x50) {
throw newError(
'Server responded HTTP. Make sure you are not trying to connect to the http endpoint ' +
'(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)'
)
}
const negotiatedVersion = Number(h[3] + '.' + h[2])
if (this._log.isDebugEnabled()) {
this._log.debug(
`${this._connection} negotiated protocol version ${negotiatedVersion}`
)
}
return this._createProtocolWithVersion(negotiatedVersion)
} |
JavaScript | function createElement(tag, allProps) {
for (var _len = arguments.length, children = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
// todo - pull ids from className as well?
if (allProps && allProps.css) {
var css = allProps.css,
className = allProps.className,
props = _objectWithoutProperties(allProps, ['css', 'className']);
var rule = Array.isArray(css) ? _index.merge.apply(undefined, _toConsumableArray(css)) : (0, _index.isLikeRule)(css) ? css : (0, _index.style)(css);
className = className ? className + ' ' + rule : rule;
props.className = className;
return _react2.default.createElement.apply(_react2.default, [tag, props].concat(children));
}
return _react2.default.createElement.apply(_react2.default, [tag, allProps].concat(children));
} | function createElement(tag, allProps) {
for (var _len = arguments.length, children = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
// todo - pull ids from className as well?
if (allProps && allProps.css) {
var css = allProps.css,
className = allProps.className,
props = _objectWithoutProperties(allProps, ['css', 'className']);
var rule = Array.isArray(css) ? _index.merge.apply(undefined, _toConsumableArray(css)) : (0, _index.isLikeRule)(css) ? css : (0, _index.style)(css);
className = className ? className + ' ' + rule : rule;
props.className = className;
return _react2.default.createElement.apply(_react2.default, [tag, props].concat(children));
}
return _react2.default.createElement.apply(_react2.default, [tag, allProps].concat(children));
} |
JavaScript | function vars() {
var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return function (Target) {
var _class, _temp;
return _temp = _class = function (_React$Component) {
_inherits(Vars, _React$Component);
function Vars() {
_classCallCheck(this, Vars);
return _possibleConstructorReturn(this, (Vars.__proto__ || Object.getPrototypeOf(Vars)).apply(this, arguments));
}
_createClass(Vars, [{
key: 'getChildContext',
value: function getChildContext() {
return {
glamorCssVars: _extends({}, this.context.glamorCssVars, typeof value === 'function' ? value(this.props) : value)
};
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(Target, _extends({}, this.props, { vars: this.context.glamorCssVars || (typeof value === 'function' ? value(this.props) : value) }), this.props.children);
}
}]);
return Vars;
}(_react2.default.Component), _class.childContextTypes = {
glamorCssVars: _propTypes2.default.object
}, _class.contextTypes = {
glamorCssVars: _propTypes2.default.object
}, _temp;
};
} | function vars() {
var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return function (Target) {
var _class, _temp;
return _temp = _class = function (_React$Component) {
_inherits(Vars, _React$Component);
function Vars() {
_classCallCheck(this, Vars);
return _possibleConstructorReturn(this, (Vars.__proto__ || Object.getPrototypeOf(Vars)).apply(this, arguments));
}
_createClass(Vars, [{
key: 'getChildContext',
value: function getChildContext() {
return {
glamorCssVars: _extends({}, this.context.glamorCssVars, typeof value === 'function' ? value(this.props) : value)
};
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(Target, _extends({}, this.props, { vars: this.context.glamorCssVars || (typeof value === 'function' ? value(this.props) : value) }), this.props.children);
}
}]);
return Vars;
}(_react2.default.Component), _class.childContextTypes = {
glamorCssVars: _propTypes2.default.object
}, _class.contextTypes = {
glamorCssVars: _propTypes2.default.object
}, _temp;
};
} |
JavaScript | function propMerge(mergeStyle, props) {
var glamorStyleKeys = Object.keys(props).filter(function (x) {
return !!/data\-css\-([a-zA-Z0-9\-_]+)/.exec(x);
});
// no glamor styles in obj
if (glamorStyleKeys.length === 0) {
return _extends({}, props, toStyle(mergeStyle));
}
if (glamorStyleKeys.length > 1) {
console.warn('[glamor] detected multiple data attributes on an element. This may lead to unexpected style because of css insertion order.'); // eslint-disable-line no-console
// just append "mergeStyle" to props, because we dunno in which order glamor styles were added to props
return _extends({}, props, toStyle(mergeStyle));
}
var dataCssKey = glamorStyleKeys[0];
var cssData = props[dataCssKey];
var mergedStyles = (0, _index.merge)(mergeStyle, _defineProperty({}, dataCssKey, cssData));
var restProps = (0, _objectAssign2.default)({}, props);
delete restProps[dataCssKey];
return _extends({}, restProps, mergedStyles);
} | function propMerge(mergeStyle, props) {
var glamorStyleKeys = Object.keys(props).filter(function (x) {
return !!/data\-css\-([a-zA-Z0-9\-_]+)/.exec(x);
});
// no glamor styles in obj
if (glamorStyleKeys.length === 0) {
return _extends({}, props, toStyle(mergeStyle));
}
if (glamorStyleKeys.length > 1) {
console.warn('[glamor] detected multiple data attributes on an element. This may lead to unexpected style because of css insertion order.'); // eslint-disable-line no-console
// just append "mergeStyle" to props, because we dunno in which order glamor styles were added to props
return _extends({}, props, toStyle(mergeStyle));
}
var dataCssKey = glamorStyleKeys[0];
var cssData = props[dataCssKey];
var mergedStyles = (0, _index.merge)(mergeStyle, _defineProperty({}, dataCssKey, cssData));
var restProps = (0, _objectAssign2.default)({}, props);
delete restProps[dataCssKey];
return _extends({}, restProps, mergedStyles);
} |
JavaScript | ClassProperty(path) {
const {
node,
scope,
} = path;
if (node.key.name === 'propTypes') {
const pathClassDeclaration = scope.path;
if (isReactClass(pathClassDeclaration.get('superClass'), scope)) {
remove(path, {
visitedKey: VISITED_KEY,
wrapperIfTemplate,
mode,
type: 'class static',
types,
pathClassDeclaration,
});
}
}
} | ClassProperty(path) {
const {
node,
scope,
} = path;
if (node.key.name === 'propTypes') {
const pathClassDeclaration = scope.path;
if (isReactClass(pathClassDeclaration.get('superClass'), scope)) {
remove(path, {
visitedKey: VISITED_KEY,
wrapperIfTemplate,
mode,
type: 'class static',
types,
pathClassDeclaration,
});
}
}
} |
JavaScript | function commandConvert(command) {
var match = envExtract.exec(command);
if (match) {
command = isWin ? '%' + match[1] + '%' : '$' + match[1];
}
return command;
} | function commandConvert(command) {
var match = envExtract.exec(command);
if (match) {
command = isWin ? '%' + match[1] + '%' : '$' + match[1];
}
return command;
} |
JavaScript | _processFile(
hasteMap,
map,
mocks,
filePath,
workerOptions)
{
const setModule = (id, module) => {
if (!map[id]) {
map[id] = Object.create(null);
}
const moduleMap = map[id];
const platform =
getPlatformExtension(module[H.PATH]) || H.GENERIC_PLATFORM;
const existingModule = moduleMap[platform];
if (existingModule && existingModule[H.PATH] !== module[H.PATH]) {
const message =
`jest-haste-map: @providesModule naming collision:\n` +
` Duplicate module name: ${ id }\n` +
` Paths: ${ module[H.PATH] } collides with ` +
`${ existingModule[H.PATH] }\n\nThis ` +
`${ this._options.throwOnModuleCollision ? 'error' : 'warning' } ` +
`is caused by a @providesModule declaration ` +
`with the same name across two different files.`;
if (this._options.throwOnModuleCollision) {
throw new Error(message);
}
this._console.warn(message);
}
moduleMap[platform] = module;
};
// If we retain all files in the virtual HasteFS representation, we avoid
// reading them if they aren't important (node_modules).
if (this._options.retainAllFiles && this._isNodeModulesDir(filePath)) {
return null;
}
if (
this._options.mocksPattern &&
this._options.mocksPattern.test(filePath))
{
const mockPath = getMockName(filePath);
if (mocks[mockPath]) {
this._console.warn(
`jest-haste-map: duplicate manual mock found:\n` +
` Module name: ${ mockPath }\n` +
` Duplicate Mock path: ${ filePath }\nThis warning ` +
`is caused by two manual mock files with the same file name.\n` +
`Jest will use the mock file found in: \n` +
`${ filePath }\n` +
` Please delete one of the following two files: \n ` +
`${ mocks[mockPath] }\n${ filePath }\n\n`);
}
mocks[mockPath] = filePath;
}
const fileMetadata = hasteMap.files[filePath];
const moduleMetadata = hasteMap.map[fileMetadata[H.ID]];
if (fileMetadata[H.VISITED]) {
if (!fileMetadata[H.ID]) {
return null;
} else if (fileMetadata[H.ID] && moduleMetadata) {
map[fileMetadata[H.ID]] = moduleMetadata;
return null;
}
}
return this._getWorker(workerOptions)({ filePath }).then(
metadata => {
// `1` for truthy values instead of `true` to save cache space.
fileMetadata[H.VISITED] = 1;
const metadataId = metadata.id;
const metadataModule = metadata.module;
if (metadataId && metadataModule) {
fileMetadata[H.ID] = metadataId;
setModule(metadataId, metadataModule);
}
fileMetadata[H.DEPENDENCIES] = metadata.dependencies || [];
},
error => {
// If a file cannot be read we remove it from the file list and
// ignore the failure silently.
delete hasteMap.files[filePath];
});
} | _processFile(
hasteMap,
map,
mocks,
filePath,
workerOptions)
{
const setModule = (id, module) => {
if (!map[id]) {
map[id] = Object.create(null);
}
const moduleMap = map[id];
const platform =
getPlatformExtension(module[H.PATH]) || H.GENERIC_PLATFORM;
const existingModule = moduleMap[platform];
if (existingModule && existingModule[H.PATH] !== module[H.PATH]) {
const message =
`jest-haste-map: @providesModule naming collision:\n` +
` Duplicate module name: ${ id }\n` +
` Paths: ${ module[H.PATH] } collides with ` +
`${ existingModule[H.PATH] }\n\nThis ` +
`${ this._options.throwOnModuleCollision ? 'error' : 'warning' } ` +
`is caused by a @providesModule declaration ` +
`with the same name across two different files.`;
if (this._options.throwOnModuleCollision) {
throw new Error(message);
}
this._console.warn(message);
}
moduleMap[platform] = module;
};
// If we retain all files in the virtual HasteFS representation, we avoid
// reading them if they aren't important (node_modules).
if (this._options.retainAllFiles && this._isNodeModulesDir(filePath)) {
return null;
}
if (
this._options.mocksPattern &&
this._options.mocksPattern.test(filePath))
{
const mockPath = getMockName(filePath);
if (mocks[mockPath]) {
this._console.warn(
`jest-haste-map: duplicate manual mock found:\n` +
` Module name: ${ mockPath }\n` +
` Duplicate Mock path: ${ filePath }\nThis warning ` +
`is caused by two manual mock files with the same file name.\n` +
`Jest will use the mock file found in: \n` +
`${ filePath }\n` +
` Please delete one of the following two files: \n ` +
`${ mocks[mockPath] }\n${ filePath }\n\n`);
}
mocks[mockPath] = filePath;
}
const fileMetadata = hasteMap.files[filePath];
const moduleMetadata = hasteMap.map[fileMetadata[H.ID]];
if (fileMetadata[H.VISITED]) {
if (!fileMetadata[H.ID]) {
return null;
} else if (fileMetadata[H.ID] && moduleMetadata) {
map[fileMetadata[H.ID]] = moduleMetadata;
return null;
}
}
return this._getWorker(workerOptions)({ filePath }).then(
metadata => {
// `1` for truthy values instead of `true` to save cache space.
fileMetadata[H.VISITED] = 1;
const metadataId = metadata.id;
const metadataModule = metadata.module;
if (metadataId && metadataModule) {
fileMetadata[H.ID] = metadataId;
setModule(metadataId, metadataModule);
}
fileMetadata[H.DEPENDENCIES] = metadata.dependencies || [];
},
error => {
// If a file cannot be read we remove it from the file list and
// ignore the failure silently.
delete hasteMap.files[filePath];
});
} |
JavaScript | _getWorker(
options)
{
if (!this._workerPromise) {
let workerFn;
if (
options && options.forceInBand ||
this._options.maxWorkers <= 1)
{
workerFn = worker;
} else {
this._workerFarm = workerFarm(
{
maxConcurrentWorkers: this._options.maxWorkers },
require.resolve('./worker'));
workerFn = this._workerFarm;
}
this._workerPromise = message => new Promise(
(resolve, reject) => workerFn(message, (error, metadata) => {
if (error || !metadata) {
reject(error);
} else {
resolve(metadata);
}
}));
}
return this._workerPromise;
} | _getWorker(
options)
{
if (!this._workerPromise) {
let workerFn;
if (
options && options.forceInBand ||
this._options.maxWorkers <= 1)
{
workerFn = worker;
} else {
this._workerFarm = workerFarm(
{
maxConcurrentWorkers: this._options.maxWorkers },
require.resolve('./worker'));
workerFn = this._workerFarm;
}
this._workerPromise = message => new Promise(
(resolve, reject) => workerFn(message, (error, metadata) => {
if (error || !metadata) {
reject(error);
} else {
resolve(metadata);
}
}));
}
return this._workerPromise;
} |
JavaScript | function commandConvert(command) {
const match = envExtract.exec(command);
if (match) {
command = isWin ? `%${match[1]}%` : `$${match[1]}`;
}
return command;
} | function commandConvert(command) {
const match = envExtract.exec(command);
if (match) {
command = isWin ? `%${match[1]}%` : `$${match[1]}`;
}
return command;
} |
JavaScript | function ClassProperty(path) {
var node = path.node,
scope = path.scope;
if (node.key.name === 'propTypes') {
var pathClassDeclaration = scope.path;
if (isReactClass(pathClassDeclaration.get('superClass'), scope)) {
remove(path, {
visitedKey: VISITED_KEY,
wrapperIfTemplate: wrapperIfTemplate,
mode: mode,
type: 'class static',
types: types,
pathClassDeclaration: pathClassDeclaration
});
}
}
} | function ClassProperty(path) {
var node = path.node,
scope = path.scope;
if (node.key.name === 'propTypes') {
var pathClassDeclaration = scope.path;
if (isReactClass(pathClassDeclaration.get('superClass'), scope)) {
remove(path, {
visitedKey: VISITED_KEY,
wrapperIfTemplate: wrapperIfTemplate,
mode: mode,
type: 'class static',
types: types,
pathClassDeclaration: pathClassDeclaration
});
}
}
} |
JavaScript | function diff(a, b, options) {
if (a === b) {
return NO_DIFF_MESSAGE;
}
if (getType(a) !== getType(b)) {
return (
' Comparing two different types of values.' +
` Expected ${ chalk.green(getType(a)) } but ` +
`received ${ chalk.red(getType(b)) }.`);
}
switch (getType(a)) {
case 'string':
const multiline = a.match(/[\r\n]/) !== -1 && b.indexOf('\n') !== -1;
if (multiline) {
return diffStrings(String(a), String(b), options);
}
return null;
case 'number':
case 'boolean':
return null;
case 'map':
return compareObjects(sortMap(a), sortMap(b), options);
case 'set':
return compareObjects(sortSet(a), sortSet(b), options);
default:
return compareObjects(a, b, options);}
} | function diff(a, b, options) {
if (a === b) {
return NO_DIFF_MESSAGE;
}
if (getType(a) !== getType(b)) {
return (
' Comparing two different types of values.' +
` Expected ${ chalk.green(getType(a)) } but ` +
`received ${ chalk.red(getType(b)) }.`);
}
switch (getType(a)) {
case 'string':
const multiline = a.match(/[\r\n]/) !== -1 && b.indexOf('\n') !== -1;
if (multiline) {
return diffStrings(String(a), String(b), options);
}
return null;
case 'number':
case 'boolean':
return null;
case 'map':
return compareObjects(sortMap(a), sortMap(b), options);
case 'set':
return compareObjects(sortSet(a), sortSet(b), options);
default:
return compareObjects(a, b, options);}
} |
JavaScript | function insert(spec) {
if (!inserted[spec.id]) {
inserted[spec.id] = true;
var deconstructed = deconstruct(spec.style);
var rules = deconstructedStyleToCSS(spec.id, deconstructed);
inserted[spec.id] = src_isBrowser ? true : rules;
rules.forEach(function (cssRule) {
return styleSheet.insert(cssRule);
});
}
} | function insert(spec) {
if (!inserted[spec.id]) {
inserted[spec.id] = true;
var deconstructed = deconstruct(spec.style);
var rules = deconstructedStyleToCSS(spec.id, deconstructed);
inserted[spec.id] = src_isBrowser ? true : rules;
rules.forEach(function (cssRule) {
return styleSheet.insert(cssRule);
});
}
} |
JavaScript | function prefixAll(styles) {
Object.keys(styles).forEach(function (property) {
var value = styles[property];
if (value instanceof Object && !Array.isArray(value)) {
// recurse through nested style objects
styles[property] = prefixAll(value);
} else {
Object.keys(_prefixProps2.default).forEach(function (prefix) {
var properties = _prefixProps2.default[prefix];
// add prefixes if needed
if (properties[property]) {
styles[prefix + (0, _capitalizeString2.default)(property)] = value;
}
});
}
});
Object.keys(styles).forEach(function (property) {
[].concat(styles[property]).forEach(function (value, index) {
// resolve every special plugins
plugins.forEach(function (plugin) {
return assignStyles(styles, plugin(property, value));
});
});
});
return styles;
} | function prefixAll(styles) {
Object.keys(styles).forEach(function (property) {
var value = styles[property];
if (value instanceof Object && !Array.isArray(value)) {
// recurse through nested style objects
styles[property] = prefixAll(value);
} else {
Object.keys(_prefixProps2.default).forEach(function (prefix) {
var properties = _prefixProps2.default[prefix];
// add prefixes if needed
if (properties[property]) {
styles[prefix + (0, _capitalizeString2.default)(property)] = value;
}
});
}
});
Object.keys(styles).forEach(function (property) {
[].concat(styles[property]).forEach(function (value, index) {
// resolve every special plugins
plugins.forEach(function (plugin) {
return assignStyles(styles, plugin(property, value));
});
});
});
return styles;
} |
JavaScript | function pathToString(d) {
return d.map((command) => {
switch (command.command) {
case 'moveto':
return `M ${command.x} ${command.y}`;
case 'lineto':
return `L ${command.x} ${command.y}`;
case 'horizontal lineto':
return `H ${command.x}`;
case 'vertical lineto':
return `V ${command.y}`;
case 'curveto':
return `C ${command.x1} ${command.y1} ${command.x2} ${command.y2} ${command.x} ${command.y}`;
case 'smooth curveto':
return `S ${command.x2} ${command.y2} ${command.x} ${command.y}`;
case 'quadratic curveto':
return `Q ${command.x1} ${command.y1} ${command.x} ${command.y}`;
case 'smooth quadratic curveto':
return `T ${command.x} ${command.y}`;
case 'elliptical arc':
return `A ${command.rx} ${command.ry} ${command.xAxisRotation} ${command.largeArc ? 1 : 0} ${command.sweep ? 1 : 0} ${command.x} ${command.y}`;
case 'closepath':
return 'Z';
}
return '';
}).join(' ');
} | function pathToString(d) {
return d.map((command) => {
switch (command.command) {
case 'moveto':
return `M ${command.x} ${command.y}`;
case 'lineto':
return `L ${command.x} ${command.y}`;
case 'horizontal lineto':
return `H ${command.x}`;
case 'vertical lineto':
return `V ${command.y}`;
case 'curveto':
return `C ${command.x1} ${command.y1} ${command.x2} ${command.y2} ${command.x} ${command.y}`;
case 'smooth curveto':
return `S ${command.x2} ${command.y2} ${command.x} ${command.y}`;
case 'quadratic curveto':
return `Q ${command.x1} ${command.y1} ${command.x} ${command.y}`;
case 'smooth quadratic curveto':
return `T ${command.x} ${command.y}`;
case 'elliptical arc':
return `A ${command.rx} ${command.ry} ${command.xAxisRotation} ${command.largeArc ? 1 : 0} ${command.sweep ? 1 : 0} ${command.x} ${command.y}`;
case 'closepath':
return 'Z';
}
return '';
}).join(' ');
} |
JavaScript | function writeOutput(inputDir, input, output, svg) {
const writeFile = (path, data) => new Promise(((resolve, reject) => {
fs.writeFile(path, data, { encoding: 'utf8' }, (error) => {
if (error) {
reject(`Could not write SVG file to ${path}: ${error.code} ${error.message}`);
} else {
resolve(path);
}
});
}));
// If it's not a directory, write the file directly
if (output.endsWith('.svg')) {
return writeFile(output, svg);
}
let inputFileName = path.basename(input);
if (!inputDir.endsWith('/')) {
inputDir += '/';
}
inputDir = path.normalize(inputDir);
if (path.normalize(input).startsWith(inputDir)) {
inputFileName = input.replace(inputDir, '');
}
const outputFile = path.join(output, inputFileName);
const outputDir = path.dirname(outputFile);
if (fs.existsSync(outputDir)) {
if (fs.statSync(outputDir).isDirectory()) {
return writeFile(outputFile, svg);
} else {
return Promise.reject(`Output directory is not a directory: ${outputDir}`);
}
}
// Create directory
return new Promise(async (resolve, reject) => {
fs.mkdir(outputDir, { recursive: true }, (error) => {
if (!error) {
writeFile(outputFile, svg).then(resolve).catch(reject);
} else {
reject(`Could not create directory ${outputDir}: ${error.code} ${error.message}`);
}
});
});
} | function writeOutput(inputDir, input, output, svg) {
const writeFile = (path, data) => new Promise(((resolve, reject) => {
fs.writeFile(path, data, { encoding: 'utf8' }, (error) => {
if (error) {
reject(`Could not write SVG file to ${path}: ${error.code} ${error.message}`);
} else {
resolve(path);
}
});
}));
// If it's not a directory, write the file directly
if (output.endsWith('.svg')) {
return writeFile(output, svg);
}
let inputFileName = path.basename(input);
if (!inputDir.endsWith('/')) {
inputDir += '/';
}
inputDir = path.normalize(inputDir);
if (path.normalize(input).startsWith(inputDir)) {
inputFileName = input.replace(inputDir, '');
}
const outputFile = path.join(output, inputFileName);
const outputDir = path.dirname(outputFile);
if (fs.existsSync(outputDir)) {
if (fs.statSync(outputDir).isDirectory()) {
return writeFile(outputFile, svg);
} else {
return Promise.reject(`Output directory is not a directory: ${outputDir}`);
}
}
// Create directory
return new Promise(async (resolve, reject) => {
fs.mkdir(outputDir, { recursive: true }, (error) => {
if (!error) {
writeFile(outputFile, svg).then(resolve).catch(reject);
} else {
reject(`Could not create directory ${outputDir}: ${error.code} ${error.message}`);
}
});
});
} |
JavaScript | function askUser() {
while (newSize !== '1' || newSize !== '2') {
newSize = prompt('Export: 1) 1024x768, or 2) 200x150?', '');
if (newSize === '1' || newSize === '2') return newSize;
}
} | function askUser() {
while (newSize !== '1' || newSize !== '2') {
newSize = prompt('Export: 1) 1024x768, or 2) 200x150?', '');
if (newSize === '1' || newSize === '2') return newSize;
}
} |
JavaScript | function wrap(value, wrapper) {
return function() {
var args = [value];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
} | function wrap(value, wrapper) {
return function() {
var args = [value];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
} |
JavaScript | function FrameCollector() {
var self = this || {};
this.upper_layer = null;
this.lower_layer = null;
this.buffer_collector = Buffer.alloc(0);
this.started = false;
} | function FrameCollector() {
var self = this || {};
this.upper_layer = null;
this.lower_layer = null;
this.buffer_collector = Buffer.alloc(0);
this.started = false;
} |
JavaScript | panic() {
// show which voices are active (playing)
console.log(this.voices);
// loop through active voices
for (let i = 0; i < this.polyphony; i++) {
// turn off voice
this.noteOff(this.voices_to_midinotes[i]);
}
// turn down delay gain
jQuery("#input_range_feedback_gain").val(0);
this.delay.gain = 0;
const now = this.now()
this.delay.gainL.gain.setValueAtTime(this.delay.gain, now);
this.delay.gainR.gain.setValueAtTime(this.delay.gain, now);
} | panic() {
// show which voices are active (playing)
console.log(this.voices);
// loop through active voices
for (let i = 0; i < this.polyphony; i++) {
// turn off voice
this.noteOff(this.voices_to_midinotes[i]);
}
// turn down delay gain
jQuery("#input_range_feedback_gain").val(0);
this.delay.gain = 0;
const now = this.now()
this.delay.gainL.gain.setValueAtTime(this.delay.gain, now);
this.delay.gainR.gain.setValueAtTime(this.delay.gain, now);
} |
JavaScript | function render_graphic_scale_rule()
{
let canvas = document.getElementById("graphic-scale-rule")
let w = canvas.width
let h = canvas.height
let ctx = canvas.getContext("2d")
// render background
ctx.fillStyle = "#fff"
ctx.fillRect(0,0,w,h)
// render a plain horizontal rule
ctx.beginPath()
ctx.moveTo(0,h*0.5)
ctx.lineTo(w,h*0.5)
ctx.strokeStyle = "#555"
ctx.lineWidth = 3
ctx.stroke()
// if scale data exists then add some notches to the rule
if (tuning_table.note_count > 0)
{
let equave = tuning_table.tuning_data[tuning_table.note_count-1]
for (i=0; i<tuning_table.note_count; i++) {
let pos = 1 + ((w-2) * (Math.log(tuning_table.tuning_data[i]) / Math.log(equave)))
ctx.beginPath()
ctx.moveTo(pos,h*0.4)
ctx.lineTo(pos,h*0.6)
ctx.strokeStyle = "#555"
ctx.lineWidth = 3
ctx.stroke()
}
}
} | function render_graphic_scale_rule()
{
let canvas = document.getElementById("graphic-scale-rule")
let w = canvas.width
let h = canvas.height
let ctx = canvas.getContext("2d")
// render background
ctx.fillStyle = "#fff"
ctx.fillRect(0,0,w,h)
// render a plain horizontal rule
ctx.beginPath()
ctx.moveTo(0,h*0.5)
ctx.lineTo(w,h*0.5)
ctx.strokeStyle = "#555"
ctx.lineWidth = 3
ctx.stroke()
// if scale data exists then add some notches to the rule
if (tuning_table.note_count > 0)
{
let equave = tuning_table.tuning_data[tuning_table.note_count-1]
for (i=0; i<tuning_table.note_count; i++) {
let pos = 1 + ((w-2) * (Math.log(tuning_table.tuning_data[i]) / Math.log(equave)))
ctx.beginPath()
ctx.moveTo(pos,h*0.4)
ctx.lineTo(pos,h*0.6)
ctx.strokeStyle = "#555"
ctx.lineWidth = 3
ctx.stroke()
}
}
} |
JavaScript | static install() {
shaka.log.debug('IndexedDB.install');
let disableIDB = false;
if (shaka.util.Platform.isChromecast()) {
shaka.log.debug('Removing IndexedDB from ChromeCast');
disableIDB = true;
} else {
try {
// This is necessary to avoid Closure compiler over optimize this
// block and remove it if it looks like a noop
if (window.indexedDB) {
disableIDB = false;
}
} catch (e) {
shaka.log.debug(
'Removing IndexedDB due to an exception when accessing it');
disableIDB = true;
}
}
if (disableIDB) {
delete window.indexedDB;
goog.asserts.assert(
!window.indexedDB, 'Failed to override window.indexedDB');
}
} | static install() {
shaka.log.debug('IndexedDB.install');
let disableIDB = false;
if (shaka.util.Platform.isChromecast()) {
shaka.log.debug('Removing IndexedDB from ChromeCast');
disableIDB = true;
} else {
try {
// This is necessary to avoid Closure compiler over optimize this
// block and remove it if it looks like a noop
if (window.indexedDB) {
disableIDB = false;
}
} catch (e) {
shaka.log.debug(
'Removing IndexedDB due to an exception when accessing it');
disableIDB = true;
}
}
if (disableIDB) {
delete window.indexedDB;
goog.asserts.assert(
!window.indexedDB, 'Failed to override window.indexedDB');
}
} |
JavaScript | function pointIsOnLine(a, b, c) {
var offset = 0.5;
var distanceAb = distance(a, b);
var distanceBc = distance(b, c);
var distanceAc = distance(a, c);
return Math.abs(distanceAb - (distanceBc + distanceAc)) < offset;
} | function pointIsOnLine(a, b, c) {
var offset = 0.5;
var distanceAb = distance(a, b);
var distanceBc = distance(b, c);
var distanceAc = distance(a, c);
return Math.abs(distanceAb - (distanceBc + distanceAc)) < offset;
} |
JavaScript | function loadAll() {
console.log("Load all", readDataFunction);
readDataFunction(function (data) {
loadedData = data;
//skítamix þartil ég bæti við id á öðru
data.map(x => { if (!x.id) x.id = x.name });
listLength = loadedData.length;
listedData = null;
filterListAndShow();
addSorters();
addLookupHandlers();
});
return false;
} | function loadAll() {
console.log("Load all", readDataFunction);
readDataFunction(function (data) {
loadedData = data;
//skítamix þartil ég bæti við id á öðru
data.map(x => { if (!x.id) x.id = x.name });
listLength = loadedData.length;
listedData = null;
filterListAndShow();
addSorters();
addLookupHandlers();
});
return false;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.