language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | async function createService(service) {
const newService = new Service(service);
const savedService = await newService.save();
return savedService;
} | async function createService(service) {
const newService = new Service(service);
const savedService = await newService.save();
return savedService;
} |
JavaScript | async function createProduct(product) {
const newProduct = new Product(product);
const savedProduct = await newProduct.save();
return savedProduct;
} | async function createProduct(product) {
const newProduct = new Product(product);
const savedProduct = await newProduct.save();
return savedProduct;
} |
JavaScript | async function createOffer(offer) {
const newOffer = new Offer(offer);
const savedOffer = await newOffer.save();
return savedOffer;
} | async function createOffer(offer) {
const newOffer = new Offer(offer);
const savedOffer = await newOffer.save();
return savedOffer;
} |
JavaScript | function element_fade(element)
{
// check if a "delay" exists.
var obj_delay = default_delay;
if($(element).attr("data-delay")) obj_delay = $(element).attr("data-delay");
// check if a "speed" exists.
var obj_speed = default_speed;
if($(element).attr("data-speed")) obj_speed = $(element).attr("data-speed");
// animate the fading in of object.
$(element).delay(obj_delay).animate({'opacity':'1'}, obj_speed);
} | function element_fade(element)
{
// check if a "delay" exists.
var obj_delay = default_delay;
if($(element).attr("data-delay")) obj_delay = $(element).attr("data-delay");
// check if a "speed" exists.
var obj_speed = default_speed;
if($(element).attr("data-speed")) obj_speed = $(element).attr("data-speed");
// animate the fading in of object.
$(element).delay(obj_delay).animate({'opacity':'1'}, obj_speed);
} |
JavaScript | function element_fade_scroll(element)
{
// calculate the halfway to the bottom of the object.
var object_bottom = $(element).offset().top + ($(element).outerHeight()/2);
// calculate the bottom of the window.
var window_bottom = $(window).scrollTop() + $(window).height();
// check if the bottom of the window is now higher than the bottom
// of the object to fade in.
if(window_bottom > object_bottom)
{
// animate the fadein.
element_fade(element);
}
} | function element_fade_scroll(element)
{
// calculate the halfway to the bottom of the object.
var object_bottom = $(element).offset().top + ($(element).outerHeight()/2);
// calculate the bottom of the window.
var window_bottom = $(window).scrollTop() + $(window).height();
// check if the bottom of the window is now higher than the bottom
// of the object to fade in.
if(window_bottom > object_bottom)
{
// animate the fadein.
element_fade(element);
}
} |
JavaScript | function addWaitingFor(moduleName, waitingForName) {
log('module "' + moduleName + '" waiting for module "' + waitingForName + '"');
var pendingEntry = moduleQueue[waitingForName] || []; //['a','b'] or []
if (!(pendingEntry.indexOf(moduleName) > -1)) {
pendingEntry.push(moduleName);
moduleQueue[waitingForName] = pendingEntry;
}
} | function addWaitingFor(moduleName, waitingForName) {
log('module "' + moduleName + '" waiting for module "' + waitingForName + '"');
var pendingEntry = moduleQueue[waitingForName] || []; //['a','b'] or []
if (!(pendingEntry.indexOf(moduleName) > -1)) {
pendingEntry.push(moduleName);
moduleQueue[waitingForName] = pendingEntry;
}
} |
JavaScript | function splitText(txt,split) {
var splits = txt.split('<br>');
var arr = [];
splits.forEach(function(item,id) {
if (id>0) arr.push('<br>');
arr = arr.concat(item.split(split));
});
return arr;
} | function splitText(txt,split) {
var splits = txt.split('<br>');
var arr = [];
splits.forEach(function(item,id) {
if (id>0) arr.push('<br>');
arr = arr.concat(item.split(split));
});
return arr;
} |
JavaScript | function parseLine(line) {
if (line==='' || line===' ') {
return line;
} else {
return (line==='<br>') ? '<br>' : '<span>'+line+'</span>'+((line.length>1)?' ':'');
}
} | function parseLine(line) {
if (line==='' || line===' ') {
return line;
} else {
return (line==='<br>') ? '<br>' : '<span>'+line+'</span>'+((line.length>1)?' ':'');
}
} |
JavaScript | function mqttClientMessageHandler(topic, payload) {
var message = 'message: ' + topic + ':' + payload.toString();
console.log(message);
var payloadObj = JSON.parse(payload);
var date = new Date(payloadObj["timeStampIso"]).toLocaleString();
// If new camera image, display it
if (topic == "sensor/camera/image") {
// Calculate delay and display it
var sender = payloadObj["sender"];
if (sender == getGoogleToken()) {
var delay = Date.now() - cameraPublishTime;
var cameraDelay = document.getElementById("cameraDelay");
cameraDelay.innerHTML = delay + " ms";
}
// Set the image and corresponding text
setImage(payloadObj);
}
// If sensor status changes, add to graph, and update current status
if (topic == "sensor/led/payload") {
// Update led status
ledStatus = payloadObj["status"];
// Calculate delay and display it
var sender = payloadObj["sender"];
if (sender == getGoogleToken()) {
var delay = Date.now() - ledPublishTime;
var ledDelay = document.getElementById("ledDelay");
ledDelay.innerHTML = delay + " ms";
}
// Graph the new data point
var dataLength = ledChart.chart.data.datasets[0].data.length;
ledChart.chart.data.datasets[0].data[dataLength] = payloadObj["status"];
ledChart.chart.data.labels[dataLength] = date;
ledChart.chart.update();
// Update text
setLedButtonStatus(payloadObj["status"]);
var ledText = document.getElementById("ledStatus");
var ledUpdated = document.getElementById("ledUpdatedTime");
ledText.innerHTML = payloadObj["status"] == 1 ? "LED On" : "LED Off";
ledUpdated.innerHTML = date;
}
if (topic == "sensor/motion/payload") {
var dataLength = motionChart.chart.data.datasets[0].data.length;
motionChart.chart.data.datasets[0].data[dataLength] = payloadObj["status"];
motionChart.chart.data.labels[dataLength] = date;
motionChart.chart.update();
var motionText = document.getElementById("motionStatus");
var motionUpdated = document.getElementById("motionUpdatedTime");
motionText.innerHTML = payloadObj["status"] == 1 ? "Motion Detected" : "No Motion Detected";
motionUpdated.innerHTML = date;
}
// Temperature and humidity data are emitted together
if (topic == "sensor/temp/payload") {
var dataLength = tempChart.chart.data.datasets[0].data.length;
tempChart.chart.data.datasets[0].data[dataLength] = payloadObj["temp"];
humChart.chart.data.datasets[0].data[dataLength] = payloadObj["humidity"];
tempChart.chart.data.labels[dataLength] = date;
humChart.chart.data.labels[dataLength] = date;
tempChart.chart.update();
humChart.chart.update();
var tempText = document.getElementById("tempStatus");
var tempUpdated = document.getElementById("tempUpdatedTime");
var humidityText = document.getElementById("humidityStatus");
var humidityUpdated = document.getElementById("humidityUpdatedTime");
tempText.innerHTML = payloadObj["temp"] + " \xB0C";
tempUpdated.innerHTML = date;
humidityText.innerHTML = payloadObj["humidity"] + "%";
humidityUpdated.innerHTML = date;
}
} | function mqttClientMessageHandler(topic, payload) {
var message = 'message: ' + topic + ':' + payload.toString();
console.log(message);
var payloadObj = JSON.parse(payload);
var date = new Date(payloadObj["timeStampIso"]).toLocaleString();
// If new camera image, display it
if (topic == "sensor/camera/image") {
// Calculate delay and display it
var sender = payloadObj["sender"];
if (sender == getGoogleToken()) {
var delay = Date.now() - cameraPublishTime;
var cameraDelay = document.getElementById("cameraDelay");
cameraDelay.innerHTML = delay + " ms";
}
// Set the image and corresponding text
setImage(payloadObj);
}
// If sensor status changes, add to graph, and update current status
if (topic == "sensor/led/payload") {
// Update led status
ledStatus = payloadObj["status"];
// Calculate delay and display it
var sender = payloadObj["sender"];
if (sender == getGoogleToken()) {
var delay = Date.now() - ledPublishTime;
var ledDelay = document.getElementById("ledDelay");
ledDelay.innerHTML = delay + " ms";
}
// Graph the new data point
var dataLength = ledChart.chart.data.datasets[0].data.length;
ledChart.chart.data.datasets[0].data[dataLength] = payloadObj["status"];
ledChart.chart.data.labels[dataLength] = date;
ledChart.chart.update();
// Update text
setLedButtonStatus(payloadObj["status"]);
var ledText = document.getElementById("ledStatus");
var ledUpdated = document.getElementById("ledUpdatedTime");
ledText.innerHTML = payloadObj["status"] == 1 ? "LED On" : "LED Off";
ledUpdated.innerHTML = date;
}
if (topic == "sensor/motion/payload") {
var dataLength = motionChart.chart.data.datasets[0].data.length;
motionChart.chart.data.datasets[0].data[dataLength] = payloadObj["status"];
motionChart.chart.data.labels[dataLength] = date;
motionChart.chart.update();
var motionText = document.getElementById("motionStatus");
var motionUpdated = document.getElementById("motionUpdatedTime");
motionText.innerHTML = payloadObj["status"] == 1 ? "Motion Detected" : "No Motion Detected";
motionUpdated.innerHTML = date;
}
// Temperature and humidity data are emitted together
if (topic == "sensor/temp/payload") {
var dataLength = tempChart.chart.data.datasets[0].data.length;
tempChart.chart.data.datasets[0].data[dataLength] = payloadObj["temp"];
humChart.chart.data.datasets[0].data[dataLength] = payloadObj["humidity"];
tempChart.chart.data.labels[dataLength] = date;
humChart.chart.data.labels[dataLength] = date;
tempChart.chart.update();
humChart.chart.update();
var tempText = document.getElementById("tempStatus");
var tempUpdated = document.getElementById("tempUpdatedTime");
var humidityText = document.getElementById("humidityStatus");
var humidityUpdated = document.getElementById("humidityUpdatedTime");
tempText.innerHTML = payloadObj["temp"] + " \xB0C";
tempUpdated.innerHTML = date;
humidityText.innerHTML = payloadObj["humidity"] + "%";
humidityUpdated.innerHTML = date;
}
} |
JavaScript | makeAutomationScriptsRegistrator (serverScriptHandler) {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
return ({ set }) => {
if (!set || !Array.isArray(set) || set.length === 0) {
return
}
/**
* Register only server-side scripts (!bundle) and only triggers with onManual eventType
*
* 1. client-scripts (bundled) are registered in the bundle's boot loader
* 2. onManual only -- other kinds (implicit, deferred) are handled directly in/by the Corteza API backend
*/
set
.filter(({ name }) => name.substring(0, serverScriptPrefix.length) === serverScriptPrefix)
.forEach(s => {
s.triggers
.filter(({ eventTypes = [] }) => eventTypes.includes('onManual'))
.forEach(t => {
// We are (ab)using eventbus for dispatching onManual scripts as well
// and since it does not know about script structs (only triggers), we need
// to modify trigger we're passing to it by adding script name
t.scriptName = s.name
try {
this.$EventBus.Register(ev => serverScriptHandler(ev, s.name), t)
} catch (e) {
console.error(e)
}
})
})
/**
* Register all
*/
this.$UIHooks.Register(...set)
}
} | makeAutomationScriptsRegistrator (serverScriptHandler) {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
return ({ set }) => {
if (!set || !Array.isArray(set) || set.length === 0) {
return
}
/**
* Register only server-side scripts (!bundle) and only triggers with onManual eventType
*
* 1. client-scripts (bundled) are registered in the bundle's boot loader
* 2. onManual only -- other kinds (implicit, deferred) are handled directly in/by the Corteza API backend
*/
set
.filter(({ name }) => name.substring(0, serverScriptPrefix.length) === serverScriptPrefix)
.forEach(s => {
s.triggers
.filter(({ eventTypes = [] }) => eventTypes.includes('onManual'))
.forEach(t => {
// We are (ab)using eventbus for dispatching onManual scripts as well
// and since it does not know about script structs (only triggers), we need
// to modify trigger we're passing to it by adding script name
t.scriptName = s.name
try {
this.$EventBus.Register(ev => serverScriptHandler(ev, s.name), t)
} catch (e) {
console.error(e)
}
})
})
/**
* Register all
*/
this.$UIHooks.Register(...set)
}
} |
JavaScript | async prefetch () {
return this.api.reminderList({
limit: 0,
resource: this.resource,
toTime: moment().add(this.fetchOffset, 'min').toISOString(),
...this.filter,
}).then(({ set }) => {
return (set || []).map(r => new system.Reminder(r))
})
} | async prefetch () {
return this.api.reminderList({
limit: 0,
resource: this.resource,
toTime: moment().add(this.fetchOffset, 'min').toISOString(),
...this.filter,
}).then(({ set }) => {
return (set || []).map(r => new system.Reminder(r))
})
} |
JavaScript | enqueue (...set) {
set.forEach(r => {
// New or replace
const i = this.set.findIndex(({ reminderID }) => reminderID === r.reminderID)
if (i > -1) {
this.set.splice(i, 1, r)
} else {
this.set.push(r)
}
})
// Should watcher restart
const { changed, time } = this.findNextProcessTime(this.set, this.nextRemindAt)
if (changed) {
this.nextRemindAt = time
this.scheduleReminderProcess(this.nextRemindAt)
}
} | enqueue (...set) {
set.forEach(r => {
// New or replace
const i = this.set.findIndex(({ reminderID }) => reminderID === r.reminderID)
if (i > -1) {
this.set.splice(i, 1, r)
} else {
this.set.push(r)
}
})
// Should watcher restart
const { changed, time } = this.findNextProcessTime(this.set, this.nextRemindAt)
if (changed) {
this.nextRemindAt = time
this.scheduleReminderProcess(this.nextRemindAt)
}
} |
JavaScript | dequeue (IDs = []) {
this.set = this.set.filter(({ reminderID }) => !IDs.includes(reminderID))
// don't reuse time, since it could have been removed
const { changed, time } = this.findNextProcessTime(this.set, null)
if (changed) {
this.nextRemindAt = time
this.scheduleReminderProcess(this.nextRemindAt)
}
} | dequeue (IDs = []) {
this.set = this.set.filter(({ reminderID }) => !IDs.includes(reminderID))
// don't reuse time, since it could have been removed
const { changed, time } = this.findNextProcessTime(this.set, null)
if (changed) {
this.nextRemindAt = time
this.scheduleReminderProcess(this.nextRemindAt)
}
} |
JavaScript | findNextProcessTime (set = [], time = null) {
let changed = false
set.forEach(r => {
if (!time || r.remindAt < time) {
time = r.remindAt
changed = true
}
})
return { changed, time }
} | findNextProcessTime (set = [], time = null) {
let changed = false
set.forEach(r => {
if (!time || r.remindAt < time) {
time = r.remindAt
changed = true
}
})
return { changed, time }
} |
JavaScript | scheduleReminderProcess (at, now = new Date()) {
// Determine ms until next reminder should be processed
const t = intervalToMS(now, at)
if (this.tHandle != null) {
window.clearTimeout(this.tHandle)
}
this.tHandle = window.setTimeout(this.processQueue.bind(this), t)
} | scheduleReminderProcess (at, now = new Date()) {
// Determine ms until next reminder should be processed
const t = intervalToMS(now, at)
if (this.tHandle != null) {
window.clearTimeout(this.tHandle)
}
this.tHandle = window.setTimeout(this.processQueue.bind(this), t)
} |
JavaScript | processQueue (now = new Date()) {
let nextRemindAt = null
this.set.forEach(r => {
if (now >= r.remindAt) {
if (this.emitter) {
this.emitter.$emit('reminder.show', r)
} else {
throw new Error('pool.noEmitter')
}
r.processed = true
} else if (now < r.remindAt && (!nextRemindAt || r.remindAt < nextRemindAt)) {
nextRemindAt = r.remindAt
}
})
this.nextRemindAt = nextRemindAt
this.set = this.set.filter(({ processed }) => !processed)
if (this.nextRemindAt === null) {
this.tHandle = null
} else {
this.scheduleReminderProcess(this.nextRemindAt)
}
} | processQueue (now = new Date()) {
let nextRemindAt = null
this.set.forEach(r => {
if (now >= r.remindAt) {
if (this.emitter) {
this.emitter.$emit('reminder.show', r)
} else {
throw new Error('pool.noEmitter')
}
r.processed = true
} else if (now < r.remindAt && (!nextRemindAt || r.remindAt < nextRemindAt)) {
nextRemindAt = r.remindAt
}
})
this.nextRemindAt = nextRemindAt
this.set = this.set.filter(({ processed }) => !processed)
if (this.nextRemindAt === null) {
this.tHandle = null
} else {
this.scheduleReminderProcess(this.nextRemindAt)
}
} |
JavaScript | function toAttrs (node) {
if (node.attrs.alignment) {
return { style: `text-align: ${node.attrs.alignment}` }
}
return {}
} | function toAttrs (node) {
if (node.attrs.alignment) {
return { style: `text-align: ${node.attrs.alignment}` }
}
return {}
} |
JavaScript | function alignmentParser (node) {
// Covers current structure
let alignment = node.style.textAlign
if (alignment) {
return { alignment }
}
// Covers legacy structure
node.classList.forEach((c) => {
alignment = alignment || qAlignments[c]
})
return { alignment: alignment || undefined }
} | function alignmentParser (node) {
// Covers current structure
let alignment = node.style.textAlign
if (alignment) {
return { alignment }
}
// Covers legacy structure
node.classList.forEach((c) => {
alignment = alignment || qAlignments[c]
})
return { alignment: alignment || undefined }
} |
JavaScript | async function process(word, isSyllabary=true) {
// process
var wholeWord = newWholeWord(word, isSyllabary);
// lookup
// look up in database
let values = await lookupWordInCED(word);
// if exists
// setup wholeWord and return
if (values.length > 0) {
console.log("first value thing found");
wholeWord = await valueFound(values, wholeWord);
}
// else
// deconstruct
// strip final suffixes
// lookup
// if exists
// setup wholeWord and return
// else
// remove affixes
wholeWord = await deconstruct(wholeWord, word);
// put together a simple word that might match the database
if (wholeWord.definition === "" || wholeWord.definition === undefined) {
// right here put together a generic verb entry and then look it up
if (wholeWord.pronounPrefixes && wholeWord.pronounPrefixes.length > 0) {
var pronPrefix = getPronPrefix();
if (wholeWord.tmpParse.endsWith("h")) {
wholeWord.root_ending = "h"
} else if (wholeWord.tmpParse.endsWith("s")) {
wholeWord.root_ending = "s"
}
if (wholeWord.root_ending) {
wholeWord.tmpParse = wholeWord.tmpParse.substring(0, wholeWord.tmpParse.length - 1);
}
wholeWord.root_phonetic = wholeWord.tmpParse;
wholeWord.root_syllabary = tsalagiToSyllabary(wholeWord.root_phonetic);
console.log(wholeWord);
//once parsed then try another lookup in the database
var tmpWord = pronPrefix + wholeWord.tmpParse + VerbTenseLookup.get("PRESENT");
wholeWord.lookupOptions.push(tmpWord);
// console.log("tmpWord " + tmpWord);
tmpWord = tsalagiToSyllabary(tmpWord);
if (wholeWord.definitions.length === 0) {
// lookup
values = await lookupWordInCED(tmpWord);
// if exists
// setup wholeWord and return
if (values.length > 0) {
// TODO: also take broken down word and put that data into a display object
wholeWord = await valueFound(values, wholeWord);
} else {
// else
// we didn't find a match so no definition
// return wholeWord
// TODO: if there's no result then DO SOMETHING ELSE
console.log("still could not find a result");
}
}
}
}
return wholeWord;
} | async function process(word, isSyllabary=true) {
// process
var wholeWord = newWholeWord(word, isSyllabary);
// lookup
// look up in database
let values = await lookupWordInCED(word);
// if exists
// setup wholeWord and return
if (values.length > 0) {
console.log("first value thing found");
wholeWord = await valueFound(values, wholeWord);
}
// else
// deconstruct
// strip final suffixes
// lookup
// if exists
// setup wholeWord and return
// else
// remove affixes
wholeWord = await deconstruct(wholeWord, word);
// put together a simple word that might match the database
if (wholeWord.definition === "" || wholeWord.definition === undefined) {
// right here put together a generic verb entry and then look it up
if (wholeWord.pronounPrefixes && wholeWord.pronounPrefixes.length > 0) {
var pronPrefix = getPronPrefix();
if (wholeWord.tmpParse.endsWith("h")) {
wholeWord.root_ending = "h"
} else if (wholeWord.tmpParse.endsWith("s")) {
wholeWord.root_ending = "s"
}
if (wholeWord.root_ending) {
wholeWord.tmpParse = wholeWord.tmpParse.substring(0, wholeWord.tmpParse.length - 1);
}
wholeWord.root_phonetic = wholeWord.tmpParse;
wholeWord.root_syllabary = tsalagiToSyllabary(wholeWord.root_phonetic);
console.log(wholeWord);
//once parsed then try another lookup in the database
var tmpWord = pronPrefix + wholeWord.tmpParse + VerbTenseLookup.get("PRESENT");
wholeWord.lookupOptions.push(tmpWord);
// console.log("tmpWord " + tmpWord);
tmpWord = tsalagiToSyllabary(tmpWord);
if (wholeWord.definitions.length === 0) {
// lookup
values = await lookupWordInCED(tmpWord);
// if exists
// setup wholeWord and return
if (values.length > 0) {
// TODO: also take broken down word and put that data into a display object
wholeWord = await valueFound(values, wholeWord);
} else {
// else
// we didn't find a match so no definition
// return wholeWord
// TODO: if there's no result then DO SOMETHING ELSE
console.log("still could not find a result");
}
}
}
}
return wholeWord;
} |
JavaScript | function parseHyphen(value) {
var returnValue = "";
//split string by '-'s
var values = value.split("-");
for (var i = 0; i < values.length; i++) {
returnValue += syllabaryMap2[values[i]];
}
return returnValue;
} | function parseHyphen(value) {
var returnValue = "";
//split string by '-'s
var values = value.split("-");
for (var i = 0; i < values.length; i++) {
returnValue += syllabaryMap2[values[i]];
}
return returnValue;
} |
JavaScript | async function writeHtmlToDisk (config, currentDir) {
progress.start('📀 Writing files to disk...')
await writeHtmlFiles(htmlContent, config)
progress.done()
} | async function writeHtmlToDisk (config, currentDir) {
progress.start('📀 Writing files to disk...')
await writeHtmlFiles(htmlContent, config)
progress.done()
} |
JavaScript | async function build (config, currentDir) {
progress.init(6)
const startTime = Date.now()
const folderPaths = getFolderPaths(config, currentDir)
try {
// Copy asset files after required processing
await processAssetFiles(config, currentDir)
// Generate html from markdown
await generatePosts(config, folderPaths)
// Process all html files
await processHtmlFiles(config, currentDir)
// Write html files to disk
await writeHtmlToDisk(config, currentDir)
} catch (error) {
log.error(error)
}
const processTime = (Date.now() - startTime) / 1000
log.success(`Build complete in ${processTime}s`)
} | async function build (config, currentDir) {
progress.init(6)
const startTime = Date.now()
const folderPaths = getFolderPaths(config, currentDir)
try {
// Copy asset files after required processing
await processAssetFiles(config, currentDir)
// Generate html from markdown
await generatePosts(config, folderPaths)
// Process all html files
await processHtmlFiles(config, currentDir)
// Write html files to disk
await writeHtmlToDisk(config, currentDir)
} catch (error) {
log.error(error)
}
const processTime = (Date.now() - startTime) / 1000
log.success(`Build complete in ${processTime}s`)
} |
JavaScript | function parse (files) {
let content = {}
Object.entries(files).forEach(([file, data]) => {
let parsedData = fm(data)
parsedData['content'] = new handlebars.SafeString(md.render(parsedData['content']))
content[file] = parsedData
})
return content
} | function parse (files) {
let content = {}
Object.entries(files).forEach(([file, data]) => {
let parsedData = fm(data)
parsedData['content'] = new handlebars.SafeString(md.render(parsedData['content']))
content[file] = parsedData
})
return content
} |
JavaScript | function loadTemplates (hbs, templates) {
const list = Object.keys(templates)
return list.reduce((results, template) => {
results[template] = hbs.compile(templates[template])
return results
}, {})
} | function loadTemplates (hbs, templates) {
const list = Object.keys(templates)
return list.reduce((results, template) => {
results[template] = hbs.compile(templates[template])
return results
}, {})
} |
JavaScript | function loadHelpers (hbs, helpers) {
return Object.entries(helpers).forEach(([name, helper]) => {
hbs.registerHelper(name, helper)
})
} | function loadHelpers (hbs, helpers) {
return Object.entries(helpers).forEach(([name, helper]) => {
hbs.registerHelper(name, helper)
})
} |
JavaScript | function loadPartials (hbs, partials) {
return Object.entries(partials).forEach(([name, partial]) => {
hbs.registerPartial(name, partial)
})
} | function loadPartials (hbs, partials) {
return Object.entries(partials).forEach(([name, partial]) => {
hbs.registerPartial(name, partial)
})
} |
JavaScript | async function prepareLayouts (paths, handlebars) {
let templateList, partialList, helperList
try {
templateList = await getDataFromFiles(`${paths.templates}/**/*.html`)
partialList = await getDataFromFiles(`${paths.partials}/**/*.html`)
helperList = await getDataFromFiles(`${paths.helpers}/**/*.js`)
loadPartials(handlebars, partialList)
loadHelpers(handlebars, helperList)
return loadTemplates(handlebars, templateList)
} catch (error) {
log(error)
}
} | async function prepareLayouts (paths, handlebars) {
let templateList, partialList, helperList
try {
templateList = await getDataFromFiles(`${paths.templates}/**/*.html`)
partialList = await getDataFromFiles(`${paths.partials}/**/*.html`)
helperList = await getDataFromFiles(`${paths.helpers}/**/*.js`)
loadPartials(handlebars, partialList)
loadHelpers(handlebars, helperList)
return loadTemplates(handlebars, templateList)
} catch (error) {
log(error)
}
} |
JavaScript | function resolvePaths (folders, paths, dirPrefix) {
const resolvedPaths = Object.assign({}, paths)
folders.forEach((dir) => {
resolvedPaths[dir] = path.join(dirPrefix, resolvedPaths[dir])
})
return resolvedPaths
} | function resolvePaths (folders, paths, dirPrefix) {
const resolvedPaths = Object.assign({}, paths)
folders.forEach((dir) => {
resolvedPaths[dir] = path.join(dirPrefix, resolvedPaths[dir])
})
return resolvedPaths
} |
JavaScript | function generate (templateFunctions, contentFiles, globalData) {
const mergedParams = (parsedData) => {
let { data, content } = parsedData
data = deepmerge(globalData, data)
data['content'] = content
return data
}
return Object
.keys(contentFiles)
.reduce((results, path) => {
let params = mergedParams(contentFiles[path])
let tempFn = findTemplateFn(templateFunctions, params['layout'])
results[path] = tempFn(params)
return results
}, {})
} | function generate (templateFunctions, contentFiles, globalData) {
const mergedParams = (parsedData) => {
let { data, content } = parsedData
data = deepmerge(globalData, data)
data['content'] = content
return data
}
return Object
.keys(contentFiles)
.reduce((results, path) => {
let params = mergedParams(contentFiles[path])
let tempFn = findTemplateFn(templateFunctions, params['layout'])
results[path] = tempFn(params)
return results
}, {})
} |
JavaScript | function makeTransaction(tx) {
var result = {};
['data', 'from', 'smokePrice', 'to', 'value'].forEach(function(key) {
if (tx[key] == null) { return; }
result[key] = tx[key];
});
if (tx.smoke != null) { result.smokeLimit = tx.smoke; }
return result;
} | function makeTransaction(tx) {
var result = {};
['data', 'from', 'smokePrice', 'to', 'value'].forEach(function(key) {
if (tx[key] == null) { return; }
result[key] = tx[key];
});
if (tx.smoke != null) { result.smokeLimit = tx.smoke; }
return result;
} |
JavaScript | function formatBlock(block) {
var result = {};
fillCompact(block, result, ['difficulty', 'smokeLimit', 'smokeUsed', 'number', 'timestamp']);
fillCopy(block, result, ['extraData', 'miner', 'parentHash']);
fillCompact(block, result, ['number'], true);
fillCopy(block, result, ['hash', 'nonce'], true);
return result;
} | function formatBlock(block) {
var result = {};
fillCompact(block, result, ['difficulty', 'smokeLimit', 'smokeUsed', 'number', 'timestamp']);
fillCopy(block, result, ['extraData', 'miner', 'parentHash']);
fillCompact(block, result, ['number'], true);
fillCopy(block, result, ['hash', 'nonce'], true);
return result;
} |
JavaScript | function formatTransaction(tx) {
var result = {};
if (tx.smokeLimit) { result.smoke = smallHexlify(tx.smokeLimit); }
result.input = (tx.data || '0x');
fillCompact(tx, result, ['blockNumber', 'smokePrice', 'nonce', 'transactionIndex', 'value'], true);
fillCopy(tx, result, ['blockHash', 'from', 'hash', 'to'], true);
return result;
} | function formatTransaction(tx) {
var result = {};
if (tx.smokeLimit) { result.smoke = smallHexlify(tx.smokeLimit); }
result.input = (tx.data || '0x');
fillCompact(tx, result, ['blockNumber', 'smokePrice', 'nonce', 'transactionIndex', 'value'], true);
fillCopy(tx, result, ['blockHash', 'from', 'hash', 'to'], true);
return result;
} |
JavaScript | function formatReceipt(receipt) {
var result = { logs: [] };
fillCompact(receipt, result, ['blockNumber', 'cumulativeSmokeUsed', 'smokePrice', 'smokeUsed', 'transactionIndex'], true);
fillCopy(receipt, result, ['blockHash', 'contractAddress', 'from', 'logsBloom', 'transactionHash', 'root', 'to'], true);
(receipt.logs || []).forEach(function(log) {
var log = { };
result.logs.push(log);
if (receipt.removed != null) { log.removed = receipt.removed; }
if (receipt.topics != null) { log.topics = receipt.topics; }
fillCompact(receipt, log, ['blockNumber', 'logIndex', 'transactionIndex'], true);
fillCopy(receipt, log, ['address', 'blockHash', 'data', 'transactionHash'], true);
});
return result;
} | function formatReceipt(receipt) {
var result = { logs: [] };
fillCompact(receipt, result, ['blockNumber', 'cumulativeSmokeUsed', 'smokePrice', 'smokeUsed', 'transactionIndex'], true);
fillCopy(receipt, result, ['blockHash', 'contractAddress', 'from', 'logsBloom', 'transactionHash', 'root', 'to'], true);
(receipt.logs || []).forEach(function(log) {
var log = { };
result.logs.push(log);
if (receipt.removed != null) { log.removed = receipt.removed; }
if (receipt.topics != null) { log.topics = receipt.topics; }
fillCompact(receipt, log, ['blockNumber', 'logIndex', 'transactionIndex'], true);
fillCopy(receipt, log, ['address', 'blockHash', 'data', 'transactionHash'], true);
});
return result;
} |
JavaScript | write(targetID, eventName, payload) {
if(this.socket.destroyed) return;
let data = { name: eventName, targetID: targetID };
if (typeof payload !== "undefined") Object.assign(data, payload);
this.socket.write(JSON.stringify(data) + "\n");
} | write(targetID, eventName, payload) {
if(this.socket.destroyed) return;
let data = { name: eventName, targetID: targetID };
if (typeof payload !== "undefined") Object.assign(data, payload);
this.socket.write(JSON.stringify(data) + "\n");
} |
JavaScript | function _conferenceFailed(store, next, action) {
const result = next(action);
// XXX Certain CONFERENCE_FAILED errors are recoverable i.e. they have
// prevented the user from joining a specific conference but the app may be
// able to eventually join the conference.
if (!action.error.recoverable) {
const { callUUID } = action.conference;
if (callUUID) {
CallIntegration.reportCallFailed(callUUID);
}
}
return result;
} | function _conferenceFailed(store, next, action) {
const result = next(action);
// XXX Certain CONFERENCE_FAILED errors are recoverable i.e. they have
// prevented the user from joining a specific conference but the app may be
// able to eventually join the conference.
if (!action.error.recoverable) {
const { callUUID } = action.conference;
if (callUUID) {
CallIntegration.reportCallFailed(callUUID);
}
}
return result;
} |
JavaScript | function _conferenceJoined(store, next, action) {
const result = next(action);
const { callUUID } = action.conference;
if (callUUID) {
CallIntegration.reportConnectedOutgoingCall(callUUID);
}
return result;
} | function _conferenceJoined(store, next, action) {
const result = next(action);
const { callUUID } = action.conference;
if (callUUID) {
CallIntegration.reportConnectedOutgoingCall(callUUID);
}
return result;
} |
JavaScript | function _conferenceLeft(store, next, action) {
const result = next(action);
const { callUUID } = action.conference;
if (callUUID) {
CallIntegration.endCall(callUUID);
}
return result;
} | function _conferenceLeft(store, next, action) {
const result = next(action);
const { callUUID } = action.conference;
if (callUUID) {
CallIntegration.endCall(callUUID);
}
return result;
} |
JavaScript | function _conferenceWillJoin({ dispatch, getState }, next, action) {
const result = next(action);
const { conference } = action;
const state = getState();
const { callHandle, callUUID } = state['features/base/config'];
const url = getInviteURL(state);
const handle = callHandle || url.toString();
const hasVideo = !isVideoMutedByAudioOnly(state);
// When assigning the call UUID, do so in upper case, since iOS will return
// it upper cased.
conference.callUUID = (callUUID || uuid.v4()).toUpperCase();
CallIntegration.startCall(conference.callUUID, handle, hasVideo)
.then(() => {
const displayName = getConferenceName(state);
const muted
= isLocalTrackMuted(
state['features/base/tracks'],
MEDIA_TYPE.AUDIO);
CallIntegration.updateCall(
conference.callUUID,
{
displayName,
hasVideo
});
CallIntegration.setMuted(conference.callUUID, muted);
})
.catch(error => {
// Currently this error code is emitted only by Android.
if (error.code === 'CREATE_OUTGOING_CALL_FAILED') {
// We're not tracking the call anymore - it doesn't exist on
// the native side.
delete conference.callUUID;
dispatch(appNavigate(undefined));
Alert.alert(
'Call aborted',
'There\'s already another call in progress.'
+ ' Please end it first and try again.',
[
{ text: 'OK' }
],
{ cancelable: false });
}
});
return result;
} | function _conferenceWillJoin({ dispatch, getState }, next, action) {
const result = next(action);
const { conference } = action;
const state = getState();
const { callHandle, callUUID } = state['features/base/config'];
const url = getInviteURL(state);
const handle = callHandle || url.toString();
const hasVideo = !isVideoMutedByAudioOnly(state);
// When assigning the call UUID, do so in upper case, since iOS will return
// it upper cased.
conference.callUUID = (callUUID || uuid.v4()).toUpperCase();
CallIntegration.startCall(conference.callUUID, handle, hasVideo)
.then(() => {
const displayName = getConferenceName(state);
const muted
= isLocalTrackMuted(
state['features/base/tracks'],
MEDIA_TYPE.AUDIO);
CallIntegration.updateCall(
conference.callUUID,
{
displayName,
hasVideo
});
CallIntegration.setMuted(conference.callUUID, muted);
})
.catch(error => {
// Currently this error code is emitted only by Android.
if (error.code === 'CREATE_OUTGOING_CALL_FAILED') {
// We're not tracking the call anymore - it doesn't exist on
// the native side.
delete conference.callUUID;
dispatch(appNavigate(undefined));
Alert.alert(
'Call aborted',
'There\'s already another call in progress.'
+ ' Please end it first and try again.',
[
{ text: 'OK' }
],
{ cancelable: false });
}
});
return result;
} |
JavaScript | function _syncTrackState({ getState }, next, action) {
const result = next(action);
const { jitsiTrack } = action.track;
const state = getState();
const conference = getCurrentConference(state);
if (jitsiTrack.isLocal() && conference && conference.callUUID) {
switch (jitsiTrack.getType()) {
case 'audio': {
const tracks = state['features/base/tracks'];
const muted = isLocalTrackMuted(tracks, MEDIA_TYPE.AUDIO);
CallIntegration.setMuted(conference.callUUID, muted);
break;
}
case 'video': {
CallIntegration.updateCall(
conference.callUUID,
{ hasVideo: !isVideoMutedByAudioOnly(state) });
break;
}
}
}
return result;
} | function _syncTrackState({ getState }, next, action) {
const result = next(action);
const { jitsiTrack } = action.track;
const state = getState();
const conference = getCurrentConference(state);
if (jitsiTrack.isLocal() && conference && conference.callUUID) {
switch (jitsiTrack.getType()) {
case 'audio': {
const tracks = state['features/base/tracks'];
const muted = isLocalTrackMuted(tracks, MEDIA_TYPE.AUDIO);
CallIntegration.setMuted(conference.callUUID, muted);
break;
}
case 'video': {
CallIntegration.updateCall(
conference.callUUID,
{ hasVideo: !isVideoMutedByAudioOnly(state) });
break;
}
}
}
return result;
} |
JavaScript | function saveRecord(record){
const transaction = db.transaction("waiting","readwrite");
const save = transaction.objectStore("waiting");
// console.log("hi",transaction.ObjectStore);
save.add(record);
} | function saveRecord(record){
const transaction = db.transaction("waiting","readwrite");
const save = transaction.objectStore("waiting");
// console.log("hi",transaction.ObjectStore);
save.add(record);
} |
JavaScript | function checkDataBase(){
const transaction = db.transaction("waiting","readwrite");
const save = transaction.objectStore("waiting");
// console.log("hello",transaction.ObjectStore);
const getAll = save.getAll();
getAll.onsuccess = function(){
if(getAll.result.lenght > 0){
fetch('/api/transaction/bulk',{
method:'POST',
body:JSON.stringify(getAll.result),
headers:{
accquire: 'application/json, text/plain, */*',
'content-type':'application/json',
},
})
.then((response)=>response.json())
.then(()=>{
const transaction = db.transaction("waiting","readwrite");
const save = transaction.ObjectStore("waiting");
save.clear();
});
}
};
} | function checkDataBase(){
const transaction = db.transaction("waiting","readwrite");
const save = transaction.objectStore("waiting");
// console.log("hello",transaction.ObjectStore);
const getAll = save.getAll();
getAll.onsuccess = function(){
if(getAll.result.lenght > 0){
fetch('/api/transaction/bulk',{
method:'POST',
body:JSON.stringify(getAll.result),
headers:{
accquire: 'application/json, text/plain, */*',
'content-type':'application/json',
},
})
.then((response)=>response.json())
.then(()=>{
const transaction = db.transaction("waiting","readwrite");
const save = transaction.ObjectStore("waiting");
save.clear();
});
}
};
} |
JavaScript | flock(boids) {
const separation = this.separate(boids).multiply(3)
const alignment = this.align(boids)
const cohesion = this.cohesion(boids)
this.acceleration = this.acceleration.add(separation, alignment, cohesion)
// 为什么acceleration会是一个点?
} | flock(boids) {
const separation = this.separate(boids).multiply(3)
const alignment = this.align(boids)
const cohesion = this.cohesion(boids)
this.acceleration = this.acceleration.add(separation, alignment, cohesion)
// 为什么acceleration会是一个点?
} |
JavaScript | align(boids) {
const neighborDist = 25
let steer = new paper.Point()
let count = 0
for (let i = 0, l = boids.length; i < l; i++) {
var other = boids[i]
var distance = this.position.getDistance(other.position)
if (distance > 0 && distance < neighborDist) {
steer = steer.add(other.vector)
count++
}
}
if (count > 0) { steer = steer.divide(count) }
if (!steer.isZero()) {
// Implement Reynolds: Steering = Desired - Velocity
steer.length = this.maxSpeed
steer = steer.subtract(this.vector)
steer.length = Math.min(steer.length, this.maxForce)
}
return steer
} | align(boids) {
const neighborDist = 25
let steer = new paper.Point()
let count = 0
for (let i = 0, l = boids.length; i < l; i++) {
var other = boids[i]
var distance = this.position.getDistance(other.position)
if (distance > 0 && distance < neighborDist) {
steer = steer.add(other.vector)
count++
}
}
if (count > 0) { steer = steer.divide(count) }
if (!steer.isZero()) {
// Implement Reynolds: Steering = Desired - Velocity
steer.length = this.maxSpeed
steer = steer.subtract(this.vector)
steer.length = Math.min(steer.length, this.maxForce)
}
return steer
} |
JavaScript | cohesion(boids) {
const neighborDist = 100
let sum = new paper.Point()
let count = 0
for (let i = 0, l = boids.length; i < l; i++) {
const other = boids[i]
const distance = this.position.getDistance(other.position)
if (distance > 0 && distance < neighborDist) {
sum = sum.add(other.position) // Add location
count++
}
}
if (count > 0) {
sum = sum.divide(count)
// Steer towards the location
return this.steer(sum, false)
}
return sum
} | cohesion(boids) {
const neighborDist = 100
let sum = new paper.Point()
let count = 0
for (let i = 0, l = boids.length; i < l; i++) {
const other = boids[i]
const distance = this.position.getDistance(other.position)
if (distance > 0 && distance < neighborDist) {
sum = sum.add(other.position) // Add location
count++
}
}
if (count > 0) {
sum = sum.divide(count)
// Steer towards the location
return this.steer(sum, false)
}
return sum
} |
JavaScript | onMouseOver({ currentTarget }) {
// cria a tooltipbox e coloca em uma propriedade
this.criarTooltipBox(currentTarget);
currentTarget.addEventListener('mousemove', this.onMouseMove);
currentTarget.addEventListener('mouseleave', this.onMouseLeave);
} | onMouseOver({ currentTarget }) {
// cria a tooltipbox e coloca em uma propriedade
this.criarTooltipBox(currentTarget);
currentTarget.addEventListener('mousemove', this.onMouseMove);
currentTarget.addEventListener('mouseleave', this.onMouseLeave);
} |
JavaScript | addTooltipsEvent() {
this.tooltips.forEach((item) => {
item.addEventListener('mouseover', this.onMouseOver);
});
} | addTooltipsEvent() {
this.tooltips.forEach((item) => {
item.addEventListener('mouseover', this.onMouseOver);
});
} |
JavaScript | hideOnClick() {
for (const link of this.links) {
link.addEventListener('click', this.handleEventHide);
}
} | hideOnClick() {
for (const link of this.links) {
link.addEventListener('click', this.handleEventHide);
}
} |
JavaScript | function headerNavNoDropdown() {
var link= $('.sfn-header-nav__inner > ul > li:not(".dropdown")');
link.on({
mouseenter: function () {
$('body').removeClass('open-subnav');
},
mouseleave: function () {
$('body').addClass('open-subnav');
}
});
} | function headerNavNoDropdown() {
var link= $('.sfn-header-nav__inner > ul > li:not(".dropdown")');
link.on({
mouseenter: function () {
$('body').removeClass('open-subnav');
},
mouseleave: function () {
$('body').addClass('open-subnav');
}
});
} |
JavaScript | function toggleSubnavOnScroll() {
if($(window).scrollTop() == 0 ) {
$('body').addClass('open-subnav');
} else {
$('body').removeClass('open-subnav');
}
} | function toggleSubnavOnScroll() {
if($(window).scrollTop() == 0 ) {
$('body').addClass('open-subnav');
} else {
$('body').removeClass('open-subnav');
}
} |
JavaScript | function fromBeaufort(value, calc) {
if (typeof value==='string')
value = Number(value)
if (calc===undefined || (calc!=='min' && calc!=='max')) {
return 0.8360 * Math.pow(value, 3/2)
} else if (value>=0 && value <=12) {
return calc=='min' ? BEAUFORT_SCALE[value].min : calc=='max' ? BEAUFORT_SCALE[value].max : null;
} else
return null;
} | function fromBeaufort(value, calc) {
if (typeof value==='string')
value = Number(value)
if (calc===undefined || (calc!=='min' && calc!=='max')) {
return 0.8360 * Math.pow(value, 3/2)
} else if (value>=0 && value <=12) {
return calc=='min' ? BEAUFORT_SCALE[value].min : calc=='max' ? BEAUFORT_SCALE[value].max : null;
} else
return null;
} |
JavaScript | function loadData() {
const xhr = new XMLHttpRequest();
//02 open kardan xhr
xhr.open('Get', 'employees.json', true);
//03 onload() kon hala xhr ro ba sharti baraie dorosti yek function
xhr.onload = function() {
//agar status===200 va ya readyState=== 4 bood doroste. (yekish kafie)
if (this.status === 200) {
//chizi ke baiad namiesh dade shavad dar #outpu inja tarif mishavad
// ghesmatie ke dar inja json mored estefade gharar migirad ta dar output namayesh dade shavad
// document.querySelector("#output").innerHTML = `khanevadeye man: ${this.responseText}`;
// besoratbala minevisim besorate string barmigardanad ma bayad string ra be arraye
//va bad peymayesh arrayebta tak tak object beresim
const response = JSON.parse(this.responseText)
// console.log(response);
// bad az tabdil be arraye hala foreach mikonim
//ta har araye ma yek object joda bedahad
//dar output berize
let output=''
response.forEach(khanevade => {
output +=`
<ul>
<li>id:${khanevade.id}</li>
<li>Name:${khanevade.Name}</li>
<li>job:${khanevade.job}</li>
<li>nesbat:${khanevade.nesbat}</li>
<li>farzandan:${khanevade.farzandan}</li>
</ul>`
});
document.querySelector("#output").innerHTML=output
}
};
xhr.send();
} | function loadData() {
const xhr = new XMLHttpRequest();
//02 open kardan xhr
xhr.open('Get', 'employees.json', true);
//03 onload() kon hala xhr ro ba sharti baraie dorosti yek function
xhr.onload = function() {
//agar status===200 va ya readyState=== 4 bood doroste. (yekish kafie)
if (this.status === 200) {
//chizi ke baiad namiesh dade shavad dar #outpu inja tarif mishavad
// ghesmatie ke dar inja json mored estefade gharar migirad ta dar output namayesh dade shavad
// document.querySelector("#output").innerHTML = `khanevadeye man: ${this.responseText}`;
// besoratbala minevisim besorate string barmigardanad ma bayad string ra be arraye
//va bad peymayesh arrayebta tak tak object beresim
const response = JSON.parse(this.responseText)
// console.log(response);
// bad az tabdil be arraye hala foreach mikonim
//ta har araye ma yek object joda bedahad
//dar output berize
let output=''
response.forEach(khanevade => {
output +=`
<ul>
<li>id:${khanevade.id}</li>
<li>Name:${khanevade.Name}</li>
<li>job:${khanevade.job}</li>
<li>nesbat:${khanevade.nesbat}</li>
<li>farzandan:${khanevade.farzandan}</li>
</ul>`
});
document.querySelector("#output").innerHTML=output
}
};
xhr.send();
} |
JavaScript | function load_section(name, json_parent, section_arr, ctx, extras) {
let section_obj = new section(name);
if (Object.entries(json_parent).length > 0) {
Object.entries(json_parent).forEach(entry => {
const [id, quantity] = entry;
// Perform context lookup, if available
let name = String(id);
if (ctx[id]) {
name = ctx[id].name;
}
// Create the item in the section
section_obj.add_item(new value_item(json_parent, id, name));
});
if (extras) {
section_obj.add_extras(extras);
}
section_arr.push(section_obj);
}
} | function load_section(name, json_parent, section_arr, ctx, extras) {
let section_obj = new section(name);
if (Object.entries(json_parent).length > 0) {
Object.entries(json_parent).forEach(entry => {
const [id, quantity] = entry;
// Perform context lookup, if available
let name = String(id);
if (ctx[id]) {
name = ctx[id].name;
}
// Create the item in the section
section_obj.add_item(new value_item(json_parent, id, name));
});
if (extras) {
section_obj.add_extras(extras);
}
section_arr.push(section_obj);
}
} |
JavaScript | function load_array_section(name, json_parent, section_arr, ctx) {
let section_obj = new section(name);
if (json_parent.length > 0) {
json_parent.forEach((value, idx) => {
if (value) {
// Perform context lookup, if available
let name = String(idx);
if (ctx[idx]) {
name = ctx[idx];
}
// Create the item in the section
section_obj.add_item(new value_item(json_parent, idx, name));
}
});
section_arr.push(section_obj);
}
} | function load_array_section(name, json_parent, section_arr, ctx) {
let section_obj = new section(name);
if (json_parent.length > 0) {
json_parent.forEach((value, idx) => {
if (value) {
// Perform context lookup, if available
let name = String(idx);
if (ctx[idx]) {
name = ctx[idx];
}
// Create the item in the section
section_obj.add_item(new value_item(json_parent, idx, name));
}
});
section_arr.push(section_obj);
}
} |
JavaScript | function load_extra_items(item_obj, item_ctx) {
let extra_items = [];
item_ctx.forEach((item) => {
if (item &&
item['name'] &&
item['name'].length > 0 &&
item['name'][0] != '-' &&
!item_obj[item.id]) {
extra_items.push({
'name': item['name'],
'id': item['id'],
'obj': item_obj
});
}
});
return extra_items;
} | function load_extra_items(item_obj, item_ctx) {
let extra_items = [];
item_ctx.forEach((item) => {
if (item &&
item['name'] &&
item['name'].length > 0 &&
item['name'][0] != '-' &&
!item_obj[item.id]) {
extra_items.push({
'name': item['name'],
'id': item['id'],
'obj': item_obj
});
}
});
return extra_items;
} |
JavaScript | function build_sections(json, context) {
let sections = [];
if ('party' in json) {
// Common section
let common = new section('Common');
common.add_item(new value_item(json['party'], '_gold', 'Gold'));
common.add_item(new value_item(json['party'], '_steps', 'Steps'));
sections.push(common);
// Character section
// Note: attributes seem to be fixed in the RPGMaker code itself rather
// than defined in the game data. I don't know if the game can
// change the definition of these fields, but they are hard-coded
// at https://dev.azure.com/je-can-code/RPG%20Maker/_git/rmmz?path=/test-bed/js/rmmz_objects.js&version=GC865a2d06c3b3459496ec380577156ea8ddfb511e&line=2402&lineEnd=2403&lineStartColumn=1&lineEndColumn=1&lineStyle=plain&_a=contents
let party = new section('Characters');
// Build the character sections for every character in the party
let party_actors = get_rm_arr(json['party'], '_actors');
party_actors.forEach((actor_idx) => {
let party_ctx = build_attribute_context(); // Performs the mapping described above
let actor_arr = get_rm_arr(json['actors'], '_data');
party.add_item(new character_item(actor_arr[actor_idx], party_ctx));
});
sections.push(party);
// Inventory
inventory_section('Items', json['party']['_items'], context['items'], sections);
inventory_section('Weapons', json['party']['_weapons'], context['weapons'], sections);
inventory_section('Armor', json['party']['_armors'], context['armors'], sections);
}
// Variables section
if ('variables' in json) {
let var_ctx = {};
if (context['variables']) {
let var_json = JSON.parse(context['variables']);
var_ctx = var_json.variables;
}
load_array_section('Variables', get_rm_arr(json['variables'], '_data'), sections, var_ctx);
}
return sections;
} | function build_sections(json, context) {
let sections = [];
if ('party' in json) {
// Common section
let common = new section('Common');
common.add_item(new value_item(json['party'], '_gold', 'Gold'));
common.add_item(new value_item(json['party'], '_steps', 'Steps'));
sections.push(common);
// Character section
// Note: attributes seem to be fixed in the RPGMaker code itself rather
// than defined in the game data. I don't know if the game can
// change the definition of these fields, but they are hard-coded
// at https://dev.azure.com/je-can-code/RPG%20Maker/_git/rmmz?path=/test-bed/js/rmmz_objects.js&version=GC865a2d06c3b3459496ec380577156ea8ddfb511e&line=2402&lineEnd=2403&lineStartColumn=1&lineEndColumn=1&lineStyle=plain&_a=contents
let party = new section('Characters');
// Build the character sections for every character in the party
let party_actors = get_rm_arr(json['party'], '_actors');
party_actors.forEach((actor_idx) => {
let party_ctx = build_attribute_context(); // Performs the mapping described above
let actor_arr = get_rm_arr(json['actors'], '_data');
party.add_item(new character_item(actor_arr[actor_idx], party_ctx));
});
sections.push(party);
// Inventory
inventory_section('Items', json['party']['_items'], context['items'], sections);
inventory_section('Weapons', json['party']['_weapons'], context['weapons'], sections);
inventory_section('Armor', json['party']['_armors'], context['armors'], sections);
}
// Variables section
if ('variables' in json) {
let var_ctx = {};
if (context['variables']) {
let var_json = JSON.parse(context['variables']);
var_ctx = var_json.variables;
}
load_array_section('Variables', get_rm_arr(json['variables'], '_data'), sections, var_ctx);
}
return sections;
} |
JavaScript | function build_palette(sections, fdata) {
let palette = document.getElementById('palette');
let savebtn = document.createElement('button');
savebtn.textContent = 'Overwrite ' + fdata['filename'];
savebtn.classList.add('palette-button');
savebtn.onclick = (event) => {
handle_save(fdata['savefile'], fdata['object'], fdata['rm_root'], sections);
}
let saveasbtn = document.createElement('button');
saveasbtn.textContent = 'Save as...';
saveasbtn.classList.add('palette-button');
saveasbtn.onclick = (event) => {
handle_save('', fdata['object'], fdata['rm_root'], sections);
}
let jdumpbtn = document.createElement('button');
jdumpbtn.textContent = 'Dump raw JSON';
jdumpbtn.classList.add('palette-button');
jdumpbtn.onclick = (event) => {
dump_json(JSON.stringify(fdata['object']), fdata['rm_root']);
}
let resetbtn = document.createElement('button');
resetbtn.textContent = 'Revert all changes';
resetbtn.classList.add('palette-button');
resetbtn.onclick = (event) => {
sections.forEach((section) => {
section.reset_values();
});
}
palette.appendChild(savebtn);
palette.appendChild(saveasbtn);
palette.appendChild(jdumpbtn);
palette.appendChild(resetbtn);
} | function build_palette(sections, fdata) {
let palette = document.getElementById('palette');
let savebtn = document.createElement('button');
savebtn.textContent = 'Overwrite ' + fdata['filename'];
savebtn.classList.add('palette-button');
savebtn.onclick = (event) => {
handle_save(fdata['savefile'], fdata['object'], fdata['rm_root'], sections);
}
let saveasbtn = document.createElement('button');
saveasbtn.textContent = 'Save as...';
saveasbtn.classList.add('palette-button');
saveasbtn.onclick = (event) => {
handle_save('', fdata['object'], fdata['rm_root'], sections);
}
let jdumpbtn = document.createElement('button');
jdumpbtn.textContent = 'Dump raw JSON';
jdumpbtn.classList.add('palette-button');
jdumpbtn.onclick = (event) => {
dump_json(JSON.stringify(fdata['object']), fdata['rm_root']);
}
let resetbtn = document.createElement('button');
resetbtn.textContent = 'Revert all changes';
resetbtn.classList.add('palette-button');
resetbtn.onclick = (event) => {
sections.forEach((section) => {
section.reset_values();
});
}
palette.appendChild(savebtn);
palette.appendChild(saveasbtn);
palette.appendChild(jdumpbtn);
palette.appendChild(resetbtn);
} |
JavaScript | function handle_file_load(filename, context_obj) {
set_text('status', 'Handling file load for ' + filename);
if (!context_obj) {
console.error('File load failed for ' + filename);
return;
}
let fdata = {};
let json_txt = context_obj['json_txt'];
fdata['filename'] = filename;
fdata['savefile'] = context_obj['savefile'];
fdata['rm_root'] = context_obj['rm_root'];
fdata['object'] = JSON.parse(json_txt);
let sections = build_sections(fdata['object'], context_obj);
const content_div = document.getElementById('content');
sections.forEach((section) => {
content_div.appendChild(section.create_DOM());
});
build_palette(sections, fdata);
hide_dropzone();
} | function handle_file_load(filename, context_obj) {
set_text('status', 'Handling file load for ' + filename);
if (!context_obj) {
console.error('File load failed for ' + filename);
return;
}
let fdata = {};
let json_txt = context_obj['json_txt'];
fdata['filename'] = filename;
fdata['savefile'] = context_obj['savefile'];
fdata['rm_root'] = context_obj['rm_root'];
fdata['object'] = JSON.parse(json_txt);
let sections = build_sections(fdata['object'], context_obj);
const content_div = document.getElementById('content');
sections.forEach((section) => {
content_div.appendChild(section.create_DOM());
});
build_palette(sections, fdata);
hide_dropzone();
} |
JavaScript | function drop_handler(ev) {
ev.preventDefault();
for (var i = 0; i < ev.dataTransfer.items.length; ++i) {
if (ev.dataTransfer.items[i].kind === 'file') {
let file = ev.dataTransfer.items[i].getAsFile();
set_text('status', 'Loading file ' + file.path);
window.ipc_bridge.load_file(file.path, handle_file_load);
}
}
} | function drop_handler(ev) {
ev.preventDefault();
for (var i = 0; i < ev.dataTransfer.items.length; ++i) {
if (ev.dataTransfer.items[i].kind === 'file') {
let file = ev.dataTransfer.items[i].getAsFile();
set_text('status', 'Loading file ' + file.path);
window.ipc_bridge.load_file(file.path, handle_file_load);
}
}
} |
JavaScript | function createCompatibilityTransformMiddleware(cfg) {
/** @type {import('koa').Middleware} */
async function compatibilityMiddleware(ctx, next) {
const baseURL = ctx.url.split('?')[0].split('#')[0];
if (isPolyfill(ctx.url) || !cfg.fileExtensions.some(ext => baseURL.endsWith(ext))) {
return next();
}
if (ctx.headers.accept.includes('text/html')) {
return next();
}
await next();
// should be a 2xx response
if (ctx.status < 200 || ctx.status >= 300) {
return undefined;
}
const transformModule = shoudlTransformToModule(ctx.url);
const filePath = getRequestFilePath(ctx, cfg.rootDir);
// if there is no file path, this file was not served statically
if (!filePath) {
return undefined;
}
// Ensure we respond with js content type
ctx.response.set('content-type', 'text/javascript');
try {
const code = await getBodyAsString(ctx);
const uaCompat = getUserAgentCompat(ctx);
const transformedCode = await cfg.transformJs({
uaCompat,
filePath,
code,
transformModule,
});
ctx.body = transformedCode;
ctx.status = 200;
return undefined;
} catch (error) {
if (error instanceof RequestCancelledError) {
return undefined;
}
// ResolveSyntaxError is thrown when resolveModuleImports runs into a syntax error from
// the lexer, but babel didn't see any errors. this means either a bug in the lexer, or
// some experimental syntax. log a message and return the module untransformed to the
// browser
if (error instanceof ResolveSyntaxError) {
logError(
`Could not resolve module imports in ${ctx.url}: Unable to parse the module, this can be due to experimental syntax or a bug in the parser.`,
);
return undefined;
}
logDebug(error);
let errorMessage = error.message;
// replace babel error messages file path with the request url for readability
if (errorMessage.startsWith(filePath)) {
errorMessage = errorMessage.replace(filePath, ctx.url);
}
errorMessage = `Error compiling: ${errorMessage}`;
// send compile error to browser for logging
ctx.body = errorMessage;
ctx.status = 500;
logError(errorMessage);
}
return undefined;
}
return compatibilityMiddleware;
} | function createCompatibilityTransformMiddleware(cfg) {
/** @type {import('koa').Middleware} */
async function compatibilityMiddleware(ctx, next) {
const baseURL = ctx.url.split('?')[0].split('#')[0];
if (isPolyfill(ctx.url) || !cfg.fileExtensions.some(ext => baseURL.endsWith(ext))) {
return next();
}
if (ctx.headers.accept.includes('text/html')) {
return next();
}
await next();
// should be a 2xx response
if (ctx.status < 200 || ctx.status >= 300) {
return undefined;
}
const transformModule = shoudlTransformToModule(ctx.url);
const filePath = getRequestFilePath(ctx, cfg.rootDir);
// if there is no file path, this file was not served statically
if (!filePath) {
return undefined;
}
// Ensure we respond with js content type
ctx.response.set('content-type', 'text/javascript');
try {
const code = await getBodyAsString(ctx);
const uaCompat = getUserAgentCompat(ctx);
const transformedCode = await cfg.transformJs({
uaCompat,
filePath,
code,
transformModule,
});
ctx.body = transformedCode;
ctx.status = 200;
return undefined;
} catch (error) {
if (error instanceof RequestCancelledError) {
return undefined;
}
// ResolveSyntaxError is thrown when resolveModuleImports runs into a syntax error from
// the lexer, but babel didn't see any errors. this means either a bug in the lexer, or
// some experimental syntax. log a message and return the module untransformed to the
// browser
if (error instanceof ResolveSyntaxError) {
logError(
`Could not resolve module imports in ${ctx.url}: Unable to parse the module, this can be due to experimental syntax or a bug in the parser.`,
);
return undefined;
}
logDebug(error);
let errorMessage = error.message;
// replace babel error messages file path with the request url for readability
if (errorMessage.startsWith(filePath)) {
errorMessage = errorMessage.replace(filePath, ctx.url);
}
errorMessage = `Error compiling: ${errorMessage}`;
// send compile error to browser for logging
ctx.body = errorMessage;
ctx.status = 500;
logError(errorMessage);
}
return undefined;
}
return compatibilityMiddleware;
} |
JavaScript | function createConfig(config) {
const {
babel = false,
babelConfig,
babelExclude = [],
babelModernExclude = [],
babelModuleExclude = [],
basePath,
compress = true,
fileExtensions: fileExtensionsArg,
hostname,
http2 = false,
logStartup,
open = false,
port,
sslCert,
sslKey,
watch = false,
logErrorsToBrowser = false,
polyfillsLoader,
responseTransformers,
debug = false,
nodeResolve: nodeResolveArg = false,
dedupeModules,
moduleDirs = ['node_modules', 'web_modules'],
preserveSymlinks = false,
} = config;
if (debug) {
setDebug(true);
}
let { compatibility = compatibilityModes.AUTO } = config;
if (compatibility === 'modern' || compatibility === 'all') {
/* eslint-disable-next-line no-console */
console.warn(
'[es-dev-server] Compatibility mode "modern" and "all" are deprecated, and combined into "auto".' +
'"auto" mode is turned on by default.',
);
compatibility = compatibilityModes.AUTO;
}
if (!Object.values(compatibilityModes).includes(compatibility)) {
throw new Error(`Unknown compatibility mode: ${compatibility}`);
}
// middlewares used to be called customMiddlewares
// @ts-ignore
const middlewares = config.middlewares || config.customMiddlewares;
let { appIndex, rootDir = process.cwd() } = config;
let appIndexDir;
// ensure rootDir is a fully resolved path, for example if you set ../../
// in the config or cli, it's resolved relative to the current working directory
rootDir = path.resolve(rootDir);
// resolve appIndex relative to rootDir and transform it to a browser path
if (appIndex) {
if (path.isAbsolute(appIndex)) {
appIndex = `/${toBrowserPath(path.relative(rootDir, appIndex))}`;
} else if (!appIndex.startsWith('/')) {
appIndex = `/${toBrowserPath(appIndex)}`;
} else {
appIndex = toBrowserPath(appIndex);
}
appIndexDir = `${appIndex.substring(0, appIndex.lastIndexOf('/'))}`;
}
// parse `open` option, based on whether it's a boolean or a string
let openPath;
if (typeof open === 'string' && open !== '') {
// user-provided open path
openPath = open;
} else if (appIndex) {
// if an appIndex was provided, use it's directory as open path
openPath = `${basePath || ''}${appIndexDir}/`;
} else {
openPath = basePath ? `${basePath}/` : '/';
}
const fileExtensions = [...(fileExtensionsArg || []), ...defaultFileExtensions];
/** @type {boolean | NodeResolveOptions} */
let nodeResolve = nodeResolveArg;
// some node resolve options can be set separately for convenience, primarily
// for the command line args. we merge them into a node resolve options object
if (
nodeResolveArg != null &&
nodeResolveArg !== false &&
(moduleDirs != null || preserveSymlinks != null || dedupeModules != null)
) {
nodeResolve = {
// user provided options, if any
...(typeof nodeResolveArg === 'object' ? nodeResolveArg : {}),
customResolveOptions: {
moduleDirectory: moduleDirs,
preserveSymlinks,
},
};
if (dedupeModules) {
nodeResolve.dedupe =
dedupeModules === true ? importee => !['.', '/'].includes(importee[0]) : dedupeModules;
}
}
return {
appIndex,
appIndexDir,
babelExclude,
babelModernExclude,
babelModuleExclude,
basePath,
compatibilityMode: compatibility,
polyfillsLoaderConfig: polyfillsLoader,
compress,
customBabelConfig: babelConfig,
customMiddlewares: middlewares,
responseTransformers,
fileExtensions,
hostname,
http2,
logStartup,
nodeResolve,
openBrowser: open === true || typeof open === 'string',
openPath,
port,
readUserBabelConfig: babel,
rootDir,
sslCert,
sslKey,
watch,
logErrorsToBrowser,
watchDebounce: 100,
};
} | function createConfig(config) {
const {
babel = false,
babelConfig,
babelExclude = [],
babelModernExclude = [],
babelModuleExclude = [],
basePath,
compress = true,
fileExtensions: fileExtensionsArg,
hostname,
http2 = false,
logStartup,
open = false,
port,
sslCert,
sslKey,
watch = false,
logErrorsToBrowser = false,
polyfillsLoader,
responseTransformers,
debug = false,
nodeResolve: nodeResolveArg = false,
dedupeModules,
moduleDirs = ['node_modules', 'web_modules'],
preserveSymlinks = false,
} = config;
if (debug) {
setDebug(true);
}
let { compatibility = compatibilityModes.AUTO } = config;
if (compatibility === 'modern' || compatibility === 'all') {
/* eslint-disable-next-line no-console */
console.warn(
'[es-dev-server] Compatibility mode "modern" and "all" are deprecated, and combined into "auto".' +
'"auto" mode is turned on by default.',
);
compatibility = compatibilityModes.AUTO;
}
if (!Object.values(compatibilityModes).includes(compatibility)) {
throw new Error(`Unknown compatibility mode: ${compatibility}`);
}
// middlewares used to be called customMiddlewares
// @ts-ignore
const middlewares = config.middlewares || config.customMiddlewares;
let { appIndex, rootDir = process.cwd() } = config;
let appIndexDir;
// ensure rootDir is a fully resolved path, for example if you set ../../
// in the config or cli, it's resolved relative to the current working directory
rootDir = path.resolve(rootDir);
// resolve appIndex relative to rootDir and transform it to a browser path
if (appIndex) {
if (path.isAbsolute(appIndex)) {
appIndex = `/${toBrowserPath(path.relative(rootDir, appIndex))}`;
} else if (!appIndex.startsWith('/')) {
appIndex = `/${toBrowserPath(appIndex)}`;
} else {
appIndex = toBrowserPath(appIndex);
}
appIndexDir = `${appIndex.substring(0, appIndex.lastIndexOf('/'))}`;
}
// parse `open` option, based on whether it's a boolean or a string
let openPath;
if (typeof open === 'string' && open !== '') {
// user-provided open path
openPath = open;
} else if (appIndex) {
// if an appIndex was provided, use it's directory as open path
openPath = `${basePath || ''}${appIndexDir}/`;
} else {
openPath = basePath ? `${basePath}/` : '/';
}
const fileExtensions = [...(fileExtensionsArg || []), ...defaultFileExtensions];
/** @type {boolean | NodeResolveOptions} */
let nodeResolve = nodeResolveArg;
// some node resolve options can be set separately for convenience, primarily
// for the command line args. we merge them into a node resolve options object
if (
nodeResolveArg != null &&
nodeResolveArg !== false &&
(moduleDirs != null || preserveSymlinks != null || dedupeModules != null)
) {
nodeResolve = {
// user provided options, if any
...(typeof nodeResolveArg === 'object' ? nodeResolveArg : {}),
customResolveOptions: {
moduleDirectory: moduleDirs,
preserveSymlinks,
},
};
if (dedupeModules) {
nodeResolve.dedupe =
dedupeModules === true ? importee => !['.', '/'].includes(importee[0]) : dedupeModules;
}
}
return {
appIndex,
appIndexDir,
babelExclude,
babelModernExclude,
babelModuleExclude,
basePath,
compatibilityMode: compatibility,
polyfillsLoaderConfig: polyfillsLoader,
compress,
customBabelConfig: babelConfig,
customMiddlewares: middlewares,
responseTransformers,
fileExtensions,
hostname,
http2,
logStartup,
nodeResolve,
openBrowser: open === true || typeof open === 'string',
openPath,
port,
readUserBabelConfig: babel,
rootDir,
sslCert,
sslKey,
watch,
logErrorsToBrowser,
watchDebounce: 100,
};
} |
JavaScript | function assertFile(expectedPath, actualPath) {
expect(actualPath)
.to.be.a.file()
.and.equal(expectedPath);
} | function assertFile(expectedPath, actualPath) {
expect(actualPath)
.to.be.a.file()
.and.equal(expectedPath);
} |
JavaScript | function checkSnapshotContents(expectedPath, actualPath) {
readdirSync(actualPath).forEach(filename => {
const actualFilePath = join(actualPath, filename);
const expectedFilePath = join(expectedPath, filename);
return lstatSync(actualFilePath).isDirectory()
? checkSnapshotContents(expectedFilePath, actualFilePath)
: assertFile(expectedFilePath, actualFilePath);
});
} | function checkSnapshotContents(expectedPath, actualPath) {
readdirSync(actualPath).forEach(filename => {
const actualFilePath = join(actualPath, filename);
const expectedFilePath = join(expectedPath, filename);
return lstatSync(actualFilePath).isDirectory()
? checkSnapshotContents(expectedFilePath, actualFilePath)
: assertFile(expectedFilePath, actualFilePath);
});
} |
JavaScript | function createPolyfillsLoaderMiddleware(cfg) {
// polyfills, keyed by url
/** @type {Map<string, string>} */
const polyfills = new Map();
// index html data, keyed by url
/** @type {Map<string, IndexHTMLData>} */
const indexHTMLData = new Map();
/** @type {import('koa').Middleware} */
async function polyfillsLoaderMiddleware(ctx, next) {
// serve polyfill from memory if url matches
const polyfill = polyfills.get(ctx.url);
if (polyfill) {
ctx.body = polyfill;
// aggresively cache polyfills, they are hashed so content changes bust the cache
ctx.response.set('cache-control', 'public, max-age=31536000');
ctx.response.set('content-type', 'text/javascript');
return undefined;
}
const uaCompat = getUserAgentCompat(ctx);
/**
* serve extracted inline module if url matches. an inline module requests has this
* structure:
* `/inline-script-<index>?source=<index-html-path>`
* for example:
* `/inline-script-2?source=/src/index-html`
* source query parameter is the index.html the inline module came from, index is the index
* of the inline module in that index.html. We use these to look up the correct code to
* serve
*/
if (isInlineScript(ctx.url)) {
const [url, queryString] = ctx.url.split('?');
const params = new URLSearchParams(queryString);
const data = indexHTMLData.get(
uaCompat.browserTarget + decodeURIComponent(params.get('source')),
);
if (!data) {
return undefined;
}
const name = path.basename(url);
const inlineScript = data.inlineScripts.find(f => f.path.split('?')[0] === name);
if (!inlineScript) {
throw new Error(`Could not find inline module for ${ctx.url}`);
}
ctx.body = inlineScript.content;
ctx.response.set('content-type', 'text/javascript');
ctx.response.set('cache-control', 'no-cache');
ctx.response.set('last-modified', data.lastModified);
return undefined;
}
await next();
// check if we are serving an index.html
if (!(await isIndexHTMLResponse(ctx, cfg.appIndex))) {
return undefined;
}
const lastModified = ctx.response.headers['last-modified'];
// return cached index.html if it did not change
const data = indexHTMLData.get(uaCompat.browserTarget + ctx.url);
// if there is no lastModified cached, the HTML file is not served from the
// file system
if (data && data.lastModified && lastModified && data.lastModified === lastModified) {
ctx.body = data.indexHTML;
return undefined;
}
const indexFilePath = path.join(cfg.rootDir, toFilePath(ctx.url));
try {
// transforms index.html to make the code load correctly with the right polyfills and shims
const htmlString = await getBodyAsString(ctx);
const result = await injectPolyfillsLoader({
htmlString,
indexUrl: ctx.url,
indexFilePath,
transformJs: cfg.transformJs,
compatibilityMode: cfg.compatibilityMode,
polyfillsLoaderConfig: cfg.polyfillsLoaderConfig,
uaCompat,
});
// set new index.html
ctx.body = result.indexHTML;
const polyfillsMap = new Map();
result.polyfills.forEach(file => {
polyfillsMap.set(file.path, file);
});
// cache index for later use
indexHTMLData.set(uaCompat.browserTarget + ctx.url, {
...result,
inlineScripts: result.inlineScripts,
lastModified,
});
// cache polyfills for serving
result.polyfills.forEach(p => {
let root = ctx.url.endsWith('/') ? ctx.url : path.posix.dirname(ctx.url);
if (!root.endsWith('/')) {
root = `${root}/`;
}
polyfills.set(`${root}${toBrowserPath(p.path)}`, p.content);
});
} catch (error) {
if (error instanceof RequestCancelledError) {
return undefined;
}
throw error;
}
return undefined;
}
return polyfillsLoaderMiddleware;
} | function createPolyfillsLoaderMiddleware(cfg) {
// polyfills, keyed by url
/** @type {Map<string, string>} */
const polyfills = new Map();
// index html data, keyed by url
/** @type {Map<string, IndexHTMLData>} */
const indexHTMLData = new Map();
/** @type {import('koa').Middleware} */
async function polyfillsLoaderMiddleware(ctx, next) {
// serve polyfill from memory if url matches
const polyfill = polyfills.get(ctx.url);
if (polyfill) {
ctx.body = polyfill;
// aggresively cache polyfills, they are hashed so content changes bust the cache
ctx.response.set('cache-control', 'public, max-age=31536000');
ctx.response.set('content-type', 'text/javascript');
return undefined;
}
const uaCompat = getUserAgentCompat(ctx);
/**
* serve extracted inline module if url matches. an inline module requests has this
* structure:
* `/inline-script-<index>?source=<index-html-path>`
* for example:
* `/inline-script-2?source=/src/index-html`
* source query parameter is the index.html the inline module came from, index is the index
* of the inline module in that index.html. We use these to look up the correct code to
* serve
*/
if (isInlineScript(ctx.url)) {
const [url, queryString] = ctx.url.split('?');
const params = new URLSearchParams(queryString);
const data = indexHTMLData.get(
uaCompat.browserTarget + decodeURIComponent(params.get('source')),
);
if (!data) {
return undefined;
}
const name = path.basename(url);
const inlineScript = data.inlineScripts.find(f => f.path.split('?')[0] === name);
if (!inlineScript) {
throw new Error(`Could not find inline module for ${ctx.url}`);
}
ctx.body = inlineScript.content;
ctx.response.set('content-type', 'text/javascript');
ctx.response.set('cache-control', 'no-cache');
ctx.response.set('last-modified', data.lastModified);
return undefined;
}
await next();
// check if we are serving an index.html
if (!(await isIndexHTMLResponse(ctx, cfg.appIndex))) {
return undefined;
}
const lastModified = ctx.response.headers['last-modified'];
// return cached index.html if it did not change
const data = indexHTMLData.get(uaCompat.browserTarget + ctx.url);
// if there is no lastModified cached, the HTML file is not served from the
// file system
if (data && data.lastModified && lastModified && data.lastModified === lastModified) {
ctx.body = data.indexHTML;
return undefined;
}
const indexFilePath = path.join(cfg.rootDir, toFilePath(ctx.url));
try {
// transforms index.html to make the code load correctly with the right polyfills and shims
const htmlString = await getBodyAsString(ctx);
const result = await injectPolyfillsLoader({
htmlString,
indexUrl: ctx.url,
indexFilePath,
transformJs: cfg.transformJs,
compatibilityMode: cfg.compatibilityMode,
polyfillsLoaderConfig: cfg.polyfillsLoaderConfig,
uaCompat,
});
// set new index.html
ctx.body = result.indexHTML;
const polyfillsMap = new Map();
result.polyfills.forEach(file => {
polyfillsMap.set(file.path, file);
});
// cache index for later use
indexHTMLData.set(uaCompat.browserTarget + ctx.url, {
...result,
inlineScripts: result.inlineScripts,
lastModified,
});
// cache polyfills for serving
result.polyfills.forEach(p => {
let root = ctx.url.endsWith('/') ? ctx.url : path.posix.dirname(ctx.url);
if (!root.endsWith('/')) {
root = `${root}/`;
}
polyfills.set(`${root}${toBrowserPath(p.path)}`, p.content);
});
} catch (error) {
if (error instanceof RequestCancelledError) {
return undefined;
}
throw error;
}
return undefined;
}
return polyfillsLoaderMiddleware;
} |
JavaScript | function createLoadFile(file) {
const resourePath = cleanImportPath(file.path);
switch (file.type) {
case fileTypes.SCRIPT:
return `loadScript('${resourePath}')`;
case fileTypes.MODULE:
return `loadScript('${resourePath}', 'module')`;
case fileTypes.ES_MODULE_SHIMS:
return `loadScript('${resourePath}', 'module-shim')`;
case fileTypes.SYSTEMJS:
return `System.import('${resourePath}')`;
default:
throw new Error(`Unknown resource type: ${file.type}`);
}
} | function createLoadFile(file) {
const resourePath = cleanImportPath(file.path);
switch (file.type) {
case fileTypes.SCRIPT:
return `loadScript('${resourePath}')`;
case fileTypes.MODULE:
return `loadScript('${resourePath}', 'module')`;
case fileTypes.ES_MODULE_SHIMS:
return `loadScript('${resourePath}', 'module-shim')`;
case fileTypes.SYSTEMJS:
return `System.import('${resourePath}')`;
default:
throw new Error(`Unknown resource type: ${file.type}`);
}
} |
JavaScript | function createLoadFiles(files) {
if (files.length === 1) {
return createLoadFile(files[0]);
}
return `[
${files.map(r => `function() { return ${createLoadFile(r)} }`)}
].reduce(function (a, c) {
return a.then(c);
}, Promise.resolve())`;
} | function createLoadFiles(files) {
if (files.length === 1) {
return createLoadFile(files[0]);
}
return `[
${files.map(r => `function() { return ${createLoadFile(r)} }`)}
].reduce(function (a, c) {
return a.then(c);
}, Promise.resolve())`;
} |
JavaScript | function createLoadFilesFunction(cfg) {
const loadResources = createLoadFiles(cfg.modern.files);
if (!cfg.legacy || cfg.legacy.length === 0) {
return loadResources;
}
/**
* @param {string} all
* @param {LegacyEntrypoint} current
* @param {number} i
*/
function reduceFn(all, current, i) {
return `${all}${i !== 0 ? ' else ' : ''}if (${current.test}) {
${createLoadFiles(current.files)}
}`;
}
const loadLegacyResources = cfg.legacy.reduce(reduceFn, '');
return `${loadLegacyResources} else {
${loadResources}
}`;
} | function createLoadFilesFunction(cfg) {
const loadResources = createLoadFiles(cfg.modern.files);
if (!cfg.legacy || cfg.legacy.length === 0) {
return loadResources;
}
/**
* @param {string} all
* @param {LegacyEntrypoint} current
* @param {number} i
*/
function reduceFn(all, current, i) {
return `${all}${i !== 0 ? ' else ' : ''}if (${current.test}) {
${createLoadFiles(current.files)}
}`;
}
const loadLegacyResources = cfg.legacy.reduce(reduceFn, '');
return `${loadLegacyResources} else {
${loadResources}
}`;
} |
JavaScript | function createLoadFilesCode(cfg, polyfills) {
const loadFilesFunction = createLoadFilesFunction(cfg);
// create a separate loadFiles to be run after polyfills
if (polyfills && polyfills.length > 0) {
return `
function loadFiles() {
${loadFilesFunction}
}
if (polyfills.length) {
Promise.all(polyfills).then(loadFiles);
} else {
loadFiles();
}`;
}
// there are no polyfills, load entries straight away
return `${loadFilesFunction}`;
} | function createLoadFilesCode(cfg, polyfills) {
const loadFilesFunction = createLoadFilesFunction(cfg);
// create a separate loadFiles to be run after polyfills
if (polyfills && polyfills.length > 0) {
return `
function loadFiles() {
${loadFilesFunction}
}
if (polyfills.length) {
Promise.all(polyfills).then(loadFiles);
} else {
loadFiles();
}`;
}
// there are no polyfills, load entries straight away
return `${loadFilesFunction}`;
} |
JavaScript | function createPolyfillsLoader(cfg) {
const { coreJs, polyfillFiles } = createPolyfillsData(cfg);
const { loadPolyfillsCode, generatedFiles } = createPolyfillsLoaderCode(cfg, polyfillFiles);
let code = `
${createLoadScriptCode(cfg, polyfillFiles)}
${loadPolyfillsCode}
${createLoadFilesCode(cfg, polyfillFiles)}
`;
if (coreJs) {
generatedFiles.push({
type: fileTypes.SCRIPT,
path: coreJs.path,
content: coreJs.content,
});
// if core-js should be polyfilled, load it first and then the rest because most
// polyfills rely on things like Promise to be already loaded
code = `(function () {
function polyfillsLoader() {
${code}
}
if (${coreJs.test}) {
var s = document.createElement('script');
function onLoaded() {
document.head.removeChild(s);
polyfillsLoader();
}
s.src = "${coreJs.path}";
s.onload = onLoaded;
s.onerror = function () {
console.error('[polyfills-loader] failed to load: ' + s.src + ' check the network tab for HTTP status.');
onLoaded();
}
document.head.appendChild(s);
} else {
polyfillsLoader();
}
})();`;
} else {
code = `(function () { ${code} })();`;
}
if (cfg.minify) {
const output = Terser.minify(code);
if (!output || !output.code) {
throw new Error('Could not minify loader.');
}
({ code } = output);
} else {
const output = transform(code, { babelrc: false, configFile: false });
if (!output || !output.code) {
throw new Error('Could not prettify loader.');
}
({ code } = output);
}
return { code, polyfillFiles: generatedFiles };
} | function createPolyfillsLoader(cfg) {
const { coreJs, polyfillFiles } = createPolyfillsData(cfg);
const { loadPolyfillsCode, generatedFiles } = createPolyfillsLoaderCode(cfg, polyfillFiles);
let code = `
${createLoadScriptCode(cfg, polyfillFiles)}
${loadPolyfillsCode}
${createLoadFilesCode(cfg, polyfillFiles)}
`;
if (coreJs) {
generatedFiles.push({
type: fileTypes.SCRIPT,
path: coreJs.path,
content: coreJs.content,
});
// if core-js should be polyfilled, load it first and then the rest because most
// polyfills rely on things like Promise to be already loaded
code = `(function () {
function polyfillsLoader() {
${code}
}
if (${coreJs.test}) {
var s = document.createElement('script');
function onLoaded() {
document.head.removeChild(s);
polyfillsLoader();
}
s.src = "${coreJs.path}";
s.onload = onLoaded;
s.onerror = function () {
console.error('[polyfills-loader] failed to load: ' + s.src + ' check the network tab for HTTP status.');
onLoaded();
}
document.head.appendChild(s);
} else {
polyfillsLoader();
}
})();`;
} else {
code = `(function () { ${code} })();`;
}
if (cfg.minify) {
const output = Terser.minify(code);
if (!output || !output.code) {
throw new Error('Could not minify loader.');
}
({ code } = output);
} else {
const output = transform(code, { babelrc: false, configFile: false });
if (!output || !output.code) {
throw new Error('Could not prettify loader.');
}
({ code } = output);
}
return { code, polyfillFiles: generatedFiles };
} |
JavaScript | function shouldTransformBabel(file) {
const customUserTransform = cfg.customBabelConfig || cfg.readUserBabelConfig;
// no compatibility and no custom user transform
if (cfg.compatibilityMode === compatibilityModes.NONE && !customUserTransform) {
return false;
}
// auto transform can be skipped for modern browsers if there is no user-defined config
if (!customUserTransform && isAutoModernTransform(file)) {
return false;
}
const excludeFromModern = cfg.babelModernExclude.some(pattern =>
minimatch(file.filePath, pattern),
);
const onlyModernTransform =
file.uaCompat.modern && cfg.compatibilityMode !== compatibilityModes.MAX;
// if this is only a modern transform, we can skip it if this file is excluded
if (onlyModernTransform && excludeFromModern) {
return false;
}
// we need to run babel if compatibility mode is not none, or the user has defined a custom config
return cfg.compatibilityMode !== compatibilityModes.NONE || customUserTransform;
} | function shouldTransformBabel(file) {
const customUserTransform = cfg.customBabelConfig || cfg.readUserBabelConfig;
// no compatibility and no custom user transform
if (cfg.compatibilityMode === compatibilityModes.NONE && !customUserTransform) {
return false;
}
// auto transform can be skipped for modern browsers if there is no user-defined config
if (!customUserTransform && isAutoModernTransform(file)) {
return false;
}
const excludeFromModern = cfg.babelModernExclude.some(pattern =>
minimatch(file.filePath, pattern),
);
const onlyModernTransform =
file.uaCompat.modern && cfg.compatibilityMode !== compatibilityModes.MAX;
// if this is only a modern transform, we can skip it if this file is excluded
if (onlyModernTransform && excludeFromModern) {
return false;
}
// we need to run babel if compatibility mode is not none, or the user has defined a custom config
return cfg.compatibilityMode !== compatibilityModes.NONE || customUserTransform;
} |
JavaScript | function shouldTransformModules(file) {
if (cfg.babelModuleExclude.some(pattern => minimatch(file.filePath, pattern))) {
return false;
}
return file.transformModule;
} | function shouldTransformModules(file) {
if (cfg.babelModuleExclude.some(pattern => minimatch(file.filePath, pattern))) {
return false;
}
return file.transformModule;
} |
JavaScript | async function fetchKarmaHTML(karmaHost, name, importMap) {
// fetch the original html source from karma, so that it injects test files
// @ts-ignore
const response = await fetch(`${karmaHost}/${name}.html?bypass-es-dev-server`);
let body = await response.text();
if (importMap) {
body = body.replace(
'</head>',
`<script type="importmap">
${importMap}
</script>
</head>`,
);
}
// extract all test file sources
const matches = body.match(regexpScriptSrcGlobal);
if (matches) {
const srcPaths = matches
.map(match => match.match(regexpScriptSrc)[1])
.filter(path => typeof path === 'string');
// disable default karma loaded call
body = body.replace(
regexpKarmaLoaded,
'// disabled by karma-esm\n // window.__karma__.loaded();',
);
// inject module which imports all test files, and then calls karma loaded.
// this ensures that when running in compatibility mode all tests are properly
// imported before starting karma
body = body.replace(
'</body>',
`<script type="module">
// generated by karma-esm to ensure all tests are loaded before running karma
// in compatibility mode
Promise.all([${srcPaths
.map(
path => `import('${path}')
.catch((e) => {
console.log('Error loading test file: ${path.split('?')[0].replace('/base', '')}');
throw e;
})`,
)
.join(',')}])
.then(() => window.__karma__.loaded())
.catch(() => window.__karma__.error())
</script>
</body>`,
);
}
return { body };
} | async function fetchKarmaHTML(karmaHost, name, importMap) {
// fetch the original html source from karma, so that it injects test files
// @ts-ignore
const response = await fetch(`${karmaHost}/${name}.html?bypass-es-dev-server`);
let body = await response.text();
if (importMap) {
body = body.replace(
'</head>',
`<script type="importmap">
${importMap}
</script>
</head>`,
);
}
// extract all test file sources
const matches = body.match(regexpScriptSrcGlobal);
if (matches) {
const srcPaths = matches
.map(match => match.match(regexpScriptSrc)[1])
.filter(path => typeof path === 'string');
// disable default karma loaded call
body = body.replace(
regexpKarmaLoaded,
'// disabled by karma-esm\n // window.__karma__.loaded();',
);
// inject module which imports all test files, and then calls karma loaded.
// this ensures that when running in compatibility mode all tests are properly
// imported before starting karma
body = body.replace(
'</body>',
`<script type="module">
// generated by karma-esm to ensure all tests are loaded before running karma
// in compatibility mode
Promise.all([${srcPaths
.map(
path => `import('${path}')
.catch((e) => {
console.log('Error loading test file: ${path.split('?')[0].replace('/base', '')}');
throw e;
})`,
)
.join(',')}])
.then(() => window.__karma__.loaded())
.catch(() => window.__karma__.error())
</script>
</body>`,
);
}
return { body };
} |
JavaScript | function createServeKarmaHtml(karmaHost, importMap) {
return async function serveKarmaHtml({ url }) {
if (url.startsWith('/context.html')) {
return fetchKarmaHTML(karmaHost, 'context', importMap);
}
if (url.startsWith('/debug.html')) {
return fetchKarmaHTML(karmaHost, 'debug', importMap);
}
return null;
};
} | function createServeKarmaHtml(karmaHost, importMap) {
return async function serveKarmaHtml({ url }) {
if (url.startsWith('/context.html')) {
return fetchKarmaHTML(karmaHost, 'context', importMap);
}
if (url.startsWith('/debug.html')) {
return fetchKarmaHTML(karmaHost, 'debug', importMap);
}
return null;
};
} |
JavaScript | function createServer(cfg, fileWatcher = chokidar.watch([])) {
const middlewares = createMiddlewares(cfg, fileWatcher);
const app = new Koa();
middlewares.forEach(middleware => {
app.use(middleware);
});
let server;
if (cfg.http2) {
const dir = path.join(__dirname, '..');
const options = {
key: fs.readFileSync(
cfg.sslKey ? cfg.sslKey : path.join(dir, '.self-signed-dev-server-ssl.key'),
),
cert: fs.readFileSync(
cfg.sslCert ? cfg.sslCert : path.join(dir, '.self-signed-dev-server-ssl.cert'),
),
allowHTTP1: true,
};
server = http2Server.createSecureServer(options, app.callback());
} else {
server = httpServer.createServer(app.callback());
}
return {
server,
app,
};
} | function createServer(cfg, fileWatcher = chokidar.watch([])) {
const middlewares = createMiddlewares(cfg, fileWatcher);
const app = new Koa();
middlewares.forEach(middleware => {
app.use(middleware);
});
let server;
if (cfg.http2) {
const dir = path.join(__dirname, '..');
const options = {
key: fs.readFileSync(
cfg.sslKey ? cfg.sslKey : path.join(dir, '.self-signed-dev-server-ssl.key'),
),
cert: fs.readFileSync(
cfg.sslCert ? cfg.sslCert : path.join(dir, '.self-signed-dev-server-ssl.cert'),
),
allowHTTP1: true,
};
server = http2Server.createSecureServer(options, app.callback());
} else {
server = httpServer.createServer(app.callback());
}
return {
server,
app,
};
} |
JavaScript | function createHistoryAPIFallbackMiddleware(cfg) {
/** @type {import('koa').Middleware} */
function historyAPIFallback(ctx, next) {
// . character hints at a file request (could possibly check with regex for file ext)
const cleanUrl = ctx.url.split('?')[0].split('#')[0];
if (ctx.method !== 'GET' || cleanUrl.includes('.')) {
return next();
}
if (!ctx.headers || typeof ctx.headers.accept !== 'string') {
return next();
}
if (ctx.headers.accept.includes('application/json')) {
return next();
}
if (!(ctx.headers.accept.includes('text/html') || ctx.headers.accept.includes('*/*'))) {
return next();
}
if (!ctx.url.startsWith(cfg.appIndexDir)) {
return next();
}
// rewrite url and let static serve take it further
ctx.url = cfg.appIndex;
return next();
}
return historyAPIFallback;
} | function createHistoryAPIFallbackMiddleware(cfg) {
/** @type {import('koa').Middleware} */
function historyAPIFallback(ctx, next) {
// . character hints at a file request (could possibly check with regex for file ext)
const cleanUrl = ctx.url.split('?')[0].split('#')[0];
if (ctx.method !== 'GET' || cleanUrl.includes('.')) {
return next();
}
if (!ctx.headers || typeof ctx.headers.accept !== 'string') {
return next();
}
if (ctx.headers.accept.includes('application/json')) {
return next();
}
if (!(ctx.headers.accept.includes('text/html') || ctx.headers.accept.includes('*/*'))) {
return next();
}
if (!ctx.url.startsWith(cfg.appIndexDir)) {
return next();
}
// rewrite url and let static serve take it further
ctx.url = cfg.appIndex;
return next();
}
return historyAPIFallback;
} |
JavaScript | async function injectPolyfillsLoader(cfg) {
const polyfillModules =
([compatibilityModes.AUTO, compatibilityModes.ALWAYS].includes(cfg.compatibilityMode) &&
!cfg.uaCompat.supportsEsm) ||
cfg.compatibilityMode === compatibilityModes.MAX;
const documentAst = parse(cfg.htmlString);
const { files, inlineScripts, scriptNodes, inlineScriptNodes } = findScripts(cfg, documentAst);
const polyfillsConfig = getPolyfillsConfig(cfg);
const polyfillsLoaderConfig = deepmerge(
{
modern: {
files: files.map(f => ({
...f,
type: f.type === fileTypes.MODULE && polyfillModules ? fileTypes.SYSTEMJS : f.type,
})),
},
polyfills: polyfillsConfig,
preload: false,
},
cfg.polyfillsLoaderConfig || {},
);
if (!hasPolyfills(polyfillsLoaderConfig.polyfills) && !polyfillModules) {
// no polyfils module polyfills, so we don't need to inject a loader
if (inlineScripts && inlineScripts.length > 0) {
// there are inline scripts, we need to transform them
// transformInlineScripts mutates documentAst
await transformInlineScripts(cfg, inlineScriptNodes);
return { indexHTML: serialize(documentAst), inlineScripts, polyfills: [] };
}
return { indexHTML: cfg.htmlString, inlineScripts: [], polyfills: [] };
}
// we will inject a loader, so we need to remove the inline script nodes as the loader
// will include them as virtual modules
for (const scriptNode of scriptNodes) {
// remove script from document
remove(scriptNode);
}
logDebug('[polyfills-loader] config', polyfillsLoaderConfig);
const result = originalInjectPolyfillsLoader(serialize(documentAst), polyfillsLoaderConfig);
logDebug(
'[polyfills-loader] generated polyfills: ',
result.polyfillFiles.map(p => ({ ...p, content: '[stripped]' })),
);
logDebug(
'Inline scripts generated by polyfills-loader',
inlineScripts.map(p => ({ ...p, content: '[stripped]' })),
);
return {
indexHTML: result.htmlString,
inlineScripts,
polyfills: result.polyfillFiles,
};
} | async function injectPolyfillsLoader(cfg) {
const polyfillModules =
([compatibilityModes.AUTO, compatibilityModes.ALWAYS].includes(cfg.compatibilityMode) &&
!cfg.uaCompat.supportsEsm) ||
cfg.compatibilityMode === compatibilityModes.MAX;
const documentAst = parse(cfg.htmlString);
const { files, inlineScripts, scriptNodes, inlineScriptNodes } = findScripts(cfg, documentAst);
const polyfillsConfig = getPolyfillsConfig(cfg);
const polyfillsLoaderConfig = deepmerge(
{
modern: {
files: files.map(f => ({
...f,
type: f.type === fileTypes.MODULE && polyfillModules ? fileTypes.SYSTEMJS : f.type,
})),
},
polyfills: polyfillsConfig,
preload: false,
},
cfg.polyfillsLoaderConfig || {},
);
if (!hasPolyfills(polyfillsLoaderConfig.polyfills) && !polyfillModules) {
// no polyfils module polyfills, so we don't need to inject a loader
if (inlineScripts && inlineScripts.length > 0) {
// there are inline scripts, we need to transform them
// transformInlineScripts mutates documentAst
await transformInlineScripts(cfg, inlineScriptNodes);
return { indexHTML: serialize(documentAst), inlineScripts, polyfills: [] };
}
return { indexHTML: cfg.htmlString, inlineScripts: [], polyfills: [] };
}
// we will inject a loader, so we need to remove the inline script nodes as the loader
// will include them as virtual modules
for (const scriptNode of scriptNodes) {
// remove script from document
remove(scriptNode);
}
logDebug('[polyfills-loader] config', polyfillsLoaderConfig);
const result = originalInjectPolyfillsLoader(serialize(documentAst), polyfillsLoaderConfig);
logDebug(
'[polyfills-loader] generated polyfills: ',
result.polyfillFiles.map(p => ({ ...p, content: '[stripped]' })),
);
logDebug(
'Inline scripts generated by polyfills-loader',
inlineScripts.map(p => ({ ...p, content: '[stripped]' })),
);
return {
indexHTML: result.htmlString,
inlineScripts,
polyfills: result.polyfillFiles,
};
} |
JavaScript | function readCommandLineArgs(argv = process.argv, config = {}) {
const { defaultConfigDir = '.', defaultConfigName = 'es-dev-server.config.js' } = config;
const dashesArgs = commandLineArgs(commandLineOptions, { argv, partial: true });
const openInCommandLineArgs = 'open' in dashesArgs;
// convert kebab-case to camelCase
/** @type {object} */
const args = Object.keys(dashesArgs).reduce((acc, key) => {
acc[camelcase(key)] = dashesArgs[key];
return acc;
}, {});
if (args.debug) {
setDebug(true);
}
if ('help' in args) {
/* eslint-disable-next-line no-console */
console.log(
commandLineUsage([
{
header: 'es-dev-server',
content: `
A dev server for modern web development workflows.
Usage: \`es-dev-server [options...]\`
`.trim(),
},
{
header: 'Global Options',
optionList: commandLineOptions,
},
]),
);
process.exit();
}
let options;
if (args.config) {
// read config from user provided path
const configPath = path.join(process.cwd(), args.config);
if (!fs.existsSync(configPath) || !fs.statSync(configPath).isFile()) {
throw new Error(`Did not find any config file at ${configPath}`);
}
const fileConfig = require(configPath);
options = deepmerge(fileConfig, args);
logDebug(`Found a config file at ${configPath}`);
} else {
// read default config if present
const defaultConfigPath = path.join(process.cwd(), defaultConfigDir, defaultConfigName);
if (fs.existsSync(defaultConfigPath) && fs.statSync(defaultConfigPath).isFile()) {
const fileConfig = require(defaultConfigPath);
options = deepmerge(fileConfig, args);
logDebug(`Found a default config file at ${defaultConfigPath}`);
} else {
// no file config, just command line args
options = args;
logDebug(`Did not find a default config file at ${defaultConfigPath}`);
}
}
let { open } = options;
if (options.dedupe) {
options.dedupeModules = options.dedupe;
delete options.dedupe;
}
// open can be a boolean nor a string. if it's a boolean from command line args,
// it's passed as null. so if it's not a string or boolean type, we check for the
// existence of open in the args object, and treat that as true
if (typeof open !== 'string' && typeof open !== 'boolean' && openInCommandLineArgs) {
open = true;
}
return {
...options,
open,
logStartup: true,
// when used from the command line we log compile errors to the browser,
// not to the terminal for a better UX
logCompileErrors: false,
};
} | function readCommandLineArgs(argv = process.argv, config = {}) {
const { defaultConfigDir = '.', defaultConfigName = 'es-dev-server.config.js' } = config;
const dashesArgs = commandLineArgs(commandLineOptions, { argv, partial: true });
const openInCommandLineArgs = 'open' in dashesArgs;
// convert kebab-case to camelCase
/** @type {object} */
const args = Object.keys(dashesArgs).reduce((acc, key) => {
acc[camelcase(key)] = dashesArgs[key];
return acc;
}, {});
if (args.debug) {
setDebug(true);
}
if ('help' in args) {
/* eslint-disable-next-line no-console */
console.log(
commandLineUsage([
{
header: 'es-dev-server',
content: `
A dev server for modern web development workflows.
Usage: \`es-dev-server [options...]\`
`.trim(),
},
{
header: 'Global Options',
optionList: commandLineOptions,
},
]),
);
process.exit();
}
let options;
if (args.config) {
// read config from user provided path
const configPath = path.join(process.cwd(), args.config);
if (!fs.existsSync(configPath) || !fs.statSync(configPath).isFile()) {
throw new Error(`Did not find any config file at ${configPath}`);
}
const fileConfig = require(configPath);
options = deepmerge(fileConfig, args);
logDebug(`Found a config file at ${configPath}`);
} else {
// read default config if present
const defaultConfigPath = path.join(process.cwd(), defaultConfigDir, defaultConfigName);
if (fs.existsSync(defaultConfigPath) && fs.statSync(defaultConfigPath).isFile()) {
const fileConfig = require(defaultConfigPath);
options = deepmerge(fileConfig, args);
logDebug(`Found a default config file at ${defaultConfigPath}`);
} else {
// no file config, just command line args
options = args;
logDebug(`Did not find a default config file at ${defaultConfigPath}`);
}
}
let { open } = options;
if (options.dedupe) {
options.dedupeModules = options.dedupe;
delete options.dedupe;
}
// open can be a boolean nor a string. if it's a boolean from command line args,
// it's passed as null. so if it's not a string or boolean type, we check for the
// existence of open in the args object, and treat that as true
if (typeof open !== 'string' && typeof open !== 'boolean' && openInCommandLineArgs) {
open = true;
}
return {
...options,
open,
logStartup: true,
// when used from the command line we log compile errors to the browser,
// not to the terminal for a better UX
logCompileErrors: false,
};
} |
JavaScript | function publish(symbolSet) {
publish.conf = { // trailing slash expected for dirs
ext: ".rst",
outDir: JSDOC.opt.d || SYS.pwd+"../out/jsdoc/",
templatesDir: JSDOC.opt.t || SYS.pwd+"../templates/jsdoc/",
symbolsDir: "symbols/",
srcDir: "symbols/src/"
};
// If source output is suppressed, just display the links to the source file
if (JSDOC.opt.s && defined(Link) && Link.prototype._makeSrcLink) {
Link.prototype._makeSrcLink = function(srcFilePath) {
return "<"+srcFilePath+">";
}
}
// create the folders and subfolders to hold the output
IO.mkPath((publish.conf.outDir+"symbols/src").split("/"));
// used to allow Link to check the details of things being linked to
Link.symbolSet = symbolSet;
// create the required templates
try {
var classTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"class.tmpl");
var classesTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allclasses.tmpl");
}
catch(e) {
print("Couldn't create the required templates: "+e);
quit();
}
// Some utility filters
function hasNoParent($) {return ($.memberOf == "")}
function isaFile($) {return ($.is("FILE"))}
function isaClass($) {return ($.is("CONSTRUCTOR") || $.isNamespace )}
//function isaNamespace($) {return ($.isNamespace)}
// get an array version of the symbolset, useful for filtering
var symbols = symbolSet.toArray();
// create the hi-lighted source code files
// TODO: restore the src file generation
var files = JSDOC.opt.srcFiles;
/*
for (var i = 0, l = files.length; i < l; i++) {
var file = files[i];
var srcDir = publish.conf.outDir + "symbols/src/";
makeSrcFile(file, srcDir);
}
*/
// get a list of all the classes in the symbolset
var classes = symbols.filter(isaClass).sort(makeSortby("alias"));
// test
//var classes = symbols.filter(isaNamespace).sort(makeSortby("alias"));
// create a filemap in which outfiles must be to be named uniquely, ignoring case
if (JSDOC.opt.u) {
var filemapCounts = {};
Link.filemap = {};
for (var i = 0, l = classes.length; i < l; i++) {
var lcAlias = classes[i].alias.toLowerCase();
if (!filemapCounts[lcAlias]) filemapCounts[lcAlias] = 1;
else filemapCounts[lcAlias]++;
Link.filemap[classes[i].alias] =
(filemapCounts[lcAlias] > 1)?
lcAlias+"_"+filemapCounts[lcAlias] : lcAlias;
}
}
// create a class index, displayed in the left-hand column of every class page
Link.base = "../";
publish.classesIndex = classesTemplate.process(classes); // kept in memory
// create each of the class pages
for (var i = 0, l = classes.length; i < l; i++) {
var symbol = classes[i];
symbol.events = symbol.getEvents(); // 1 order matters
symbol.methods = symbol.getMethods(); // 2
var output = "";
output = classTemplate.process(symbol);
IO.saveFile(publish.conf.outDir+"symbols/", ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias) + publish.conf.ext, output);
}
// regenerate the index with different relative links, used in the index pages
Link.base = "";
publish.classesIndex = classesTemplate.process(classes);
// create the class index page
try {
var classesindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"index.tmpl");
}
catch(e) { print(e.message); quit(); }
var classesIndex = classesindexTemplate.process(classes);
IO.saveFile(publish.conf.outDir, "index"+publish.conf.ext, classesIndex);
classesindexTemplate = classesIndex = classes = null;
// create the file index page
try {
var fileindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allfiles.tmpl");
}
catch(e) { print(e.message); quit(); }
var documentedFiles = symbols.filter(isaFile); // files that have file-level docs
var allFiles = []; // not all files have file-level docs, but we need to list every one
for (var i = 0; i < files.length; i++) {
allFiles.push(new JSDOC.Symbol(files[i], [], "FILE", new JSDOC.DocComment("/** */")));
}
for (var i = 0; i < documentedFiles.length; i++) {
var offset = files.indexOf(documentedFiles[i].alias);
allFiles[offset] = documentedFiles[i];
}
allFiles = allFiles.sort(makeSortby("name"));
// output the file index page
var filesIndex = fileindexTemplate.process(allFiles);
IO.saveFile(publish.conf.outDir, "files"+publish.conf.ext, filesIndex);
fileindexTemplate = filesIndex = files = null;
} | function publish(symbolSet) {
publish.conf = { // trailing slash expected for dirs
ext: ".rst",
outDir: JSDOC.opt.d || SYS.pwd+"../out/jsdoc/",
templatesDir: JSDOC.opt.t || SYS.pwd+"../templates/jsdoc/",
symbolsDir: "symbols/",
srcDir: "symbols/src/"
};
// If source output is suppressed, just display the links to the source file
if (JSDOC.opt.s && defined(Link) && Link.prototype._makeSrcLink) {
Link.prototype._makeSrcLink = function(srcFilePath) {
return "<"+srcFilePath+">";
}
}
// create the folders and subfolders to hold the output
IO.mkPath((publish.conf.outDir+"symbols/src").split("/"));
// used to allow Link to check the details of things being linked to
Link.symbolSet = symbolSet;
// create the required templates
try {
var classTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"class.tmpl");
var classesTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allclasses.tmpl");
}
catch(e) {
print("Couldn't create the required templates: "+e);
quit();
}
// Some utility filters
function hasNoParent($) {return ($.memberOf == "")}
function isaFile($) {return ($.is("FILE"))}
function isaClass($) {return ($.is("CONSTRUCTOR") || $.isNamespace )}
//function isaNamespace($) {return ($.isNamespace)}
// get an array version of the symbolset, useful for filtering
var symbols = symbolSet.toArray();
// create the hi-lighted source code files
// TODO: restore the src file generation
var files = JSDOC.opt.srcFiles;
/*
for (var i = 0, l = files.length; i < l; i++) {
var file = files[i];
var srcDir = publish.conf.outDir + "symbols/src/";
makeSrcFile(file, srcDir);
}
*/
// get a list of all the classes in the symbolset
var classes = symbols.filter(isaClass).sort(makeSortby("alias"));
// test
//var classes = symbols.filter(isaNamespace).sort(makeSortby("alias"));
// create a filemap in which outfiles must be to be named uniquely, ignoring case
if (JSDOC.opt.u) {
var filemapCounts = {};
Link.filemap = {};
for (var i = 0, l = classes.length; i < l; i++) {
var lcAlias = classes[i].alias.toLowerCase();
if (!filemapCounts[lcAlias]) filemapCounts[lcAlias] = 1;
else filemapCounts[lcAlias]++;
Link.filemap[classes[i].alias] =
(filemapCounts[lcAlias] > 1)?
lcAlias+"_"+filemapCounts[lcAlias] : lcAlias;
}
}
// create a class index, displayed in the left-hand column of every class page
Link.base = "../";
publish.classesIndex = classesTemplate.process(classes); // kept in memory
// create each of the class pages
for (var i = 0, l = classes.length; i < l; i++) {
var symbol = classes[i];
symbol.events = symbol.getEvents(); // 1 order matters
symbol.methods = symbol.getMethods(); // 2
var output = "";
output = classTemplate.process(symbol);
IO.saveFile(publish.conf.outDir+"symbols/", ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias) + publish.conf.ext, output);
}
// regenerate the index with different relative links, used in the index pages
Link.base = "";
publish.classesIndex = classesTemplate.process(classes);
// create the class index page
try {
var classesindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"index.tmpl");
}
catch(e) { print(e.message); quit(); }
var classesIndex = classesindexTemplate.process(classes);
IO.saveFile(publish.conf.outDir, "index"+publish.conf.ext, classesIndex);
classesindexTemplate = classesIndex = classes = null;
// create the file index page
try {
var fileindexTemplate = new JSDOC.JsPlate(publish.conf.templatesDir+"allfiles.tmpl");
}
catch(e) { print(e.message); quit(); }
var documentedFiles = symbols.filter(isaFile); // files that have file-level docs
var allFiles = []; // not all files have file-level docs, but we need to list every one
for (var i = 0; i < files.length; i++) {
allFiles.push(new JSDOC.Symbol(files[i], [], "FILE", new JSDOC.DocComment("/** */")));
}
for (var i = 0; i < documentedFiles.length; i++) {
var offset = files.indexOf(documentedFiles[i].alias);
allFiles[offset] = documentedFiles[i];
}
allFiles = allFiles.sort(makeSortby("name"));
// output the file index page
var filesIndex = fileindexTemplate.process(allFiles);
IO.saveFile(publish.conf.outDir, "files"+publish.conf.ext, filesIndex);
fileindexTemplate = filesIndex = files = null;
} |
JavaScript | function summarize(desc) {
if (typeof desc != "undefined")
return desc.match(/([\w\W]+?\.)[^a-z0-9_$]/i)? RegExp.$1 : desc;
return desc;
} | function summarize(desc) {
if (typeof desc != "undefined")
return desc.match(/([\w\W]+?\.)[^a-z0-9_$]/i)? RegExp.$1 : desc;
return desc;
} |
JavaScript | function includeTemplate(path, data) {
data = data || {};
//LOG.inform("Including template from "+path+" with params "+data);
try {
var template = new JSDOC.JsPlate(publish.conf.templatesDir + path);
return template.multiProcess(data);
}
catch(e) { print(e.message); quit(); }
return '';
} | function includeTemplate(path, data) {
data = data || {};
//LOG.inform("Including template from "+path+" with params "+data);
try {
var template = new JSDOC.JsPlate(publish.conf.templatesDir + path);
return template.multiProcess(data);
}
catch(e) { print(e.message); quit(); }
return '';
} |
JavaScript | function resolveLinks(str, from) {
str = str.replace(/\{@link ([^} ]+) ?\}/gi,
function(match, symbolName) {
return ':js:class:`' + symbolName + '<'+symbolName+'>`';
}
);
return str;
} | function resolveLinks(str, from) {
str = str.replace(/\{@link ([^} ]+) ?\}/gi,
function(match, symbolName) {
return ':js:class:`' + symbolName + '<'+symbolName+'>`';
}
);
return str;
} |
JavaScript | function reIndent(text, depth, indentFirst) {
depth = typeof depth != "undefined" ? depth : 4;
indentFirst = typeof indentFirst != "undefined" ? indentFirst : true;
var lines = text.toString().split("\n");
// Iterate lines
for (var l = 0; l < lines.length; l++) {
var indentedText = '';
var line = lines[l];
// Pad space in beginning of each line
for (var i = 0; i < depth; i++) {
indentedText += " ";
}
// Put padding and text into array and reset indent
if (!indentFirst && l == 0) {
lines[l] = line;
} else {
lines[l] = indentedText + line;
}
}
return lines.join("\n");
} | function reIndent(text, depth, indentFirst) {
depth = typeof depth != "undefined" ? depth : 4;
indentFirst = typeof indentFirst != "undefined" ? indentFirst : true;
var lines = text.toString().split("\n");
// Iterate lines
for (var l = 0; l < lines.length; l++) {
var indentedText = '';
var line = lines[l];
// Pad space in beginning of each line
for (var i = 0; i < depth; i++) {
indentedText += " ";
}
// Put padding and text into array and reset indent
if (!indentFirst && l == 0) {
lines[l] = line;
} else {
lines[l] = indentedText + line;
}
}
return lines.join("\n");
} |
JavaScript | function toRst(rawstr) {
var rstLines = new Array();
var lines = rawstr.toString().split("\n");
for(var l =0; l < lines.length ; l++) {
var line = lines[l];
// Remove attribute
line = line.replace(/\<(\/?\w*)([^\>]*)\>/g, '<$1>');
// Italic
line = line.replace(/\<i\>/g, "*");
line = line.replace(/\<\/i\>/g, "*");
// Bold
line = line.replace(/\<.?b\>/g, "**");
line = line.replace(/\<.?strong\>/g, "**");
// Code
line = line.replace(/\<.?code\>/g, "``");
line = line.replace(/\<.?pre\>/g, "``");
// Unicode
line = line.replace('@', '@');
// Blank row/break
line = line.replace(/\<br(\s|\/)*\>/g, '\n\n');
// List
line = line.replace(/\s*\<.?ul\>/g, '\n\n').trim();
line = line.replace(/\s*\<li\>/g, '\n* ').trim();
line = line.replace(/\s*\<\/li\>/g, '\n').trim();
// eat divs
// TODO: consider using containers?
line = line.replace(/\<.?div\>/g, "\n");
rstLines.push(line);
}
return rstLines.join('\n').ltrim();
} | function toRst(rawstr) {
var rstLines = new Array();
var lines = rawstr.toString().split("\n");
for(var l =0; l < lines.length ; l++) {
var line = lines[l];
// Remove attribute
line = line.replace(/\<(\/?\w*)([^\>]*)\>/g, '<$1>');
// Italic
line = line.replace(/\<i\>/g, "*");
line = line.replace(/\<\/i\>/g, "*");
// Bold
line = line.replace(/\<.?b\>/g, "**");
line = line.replace(/\<.?strong\>/g, "**");
// Code
line = line.replace(/\<.?code\>/g, "``");
line = line.replace(/\<.?pre\>/g, "``");
// Unicode
line = line.replace('@', '@');
// Blank row/break
line = line.replace(/\<br(\s|\/)*\>/g, '\n\n');
// List
line = line.replace(/\s*\<.?ul\>/g, '\n\n').trim();
line = line.replace(/\s*\<li\>/g, '\n* ').trim();
line = line.replace(/\s*\<\/li\>/g, '\n').trim();
// eat divs
// TODO: consider using containers?
line = line.replace(/\<.?div\>/g, "\n");
rstLines.push(line);
}
return rstLines.join('\n').ltrim();
} |
JavaScript | function reJoin(text) {
var joinedText = "";
// TODO: room for improvement?
text = text.replace(/\n\s*\n/, "<<--NEWLINE-->>");
var lines = text.toString().split("\n");
return lines.join(" ").replace("<<--NEWLINE-->>", "\n\n");
} | function reJoin(text) {
var joinedText = "";
// TODO: room for improvement?
text = text.replace(/\n\s*\n/, "<<--NEWLINE-->>");
var lines = text.toString().split("\n");
return lines.join(" ").replace("<<--NEWLINE-->>", "\n\n");
} |
JavaScript | function underline(title, uchar, withTitle) {
uchar = uchar || "-";
withTitle = withTitle || true;
var line = "";
for(var l = 0; l<title.length; l++) {
line += uchar;
}
if (withTitle) {
return title + "\n" + line;
}
return line;
} | function underline(title, uchar, withTitle) {
uchar = uchar || "-";
withTitle = withTitle || true;
var line = "";
for(var l = 0; l<title.length; l++) {
line += uchar;
}
if (withTitle) {
return title + "\n" + line;
}
return line;
} |
JavaScript | scrollForwardTo(normX) {
let newPosition = (1-normX) * this.containerElement.offsetWidth.toString() + "px";
for(let i in this.series) {
this.series[i].canvasElement.style.left = newPosition;
}
} | scrollForwardTo(normX) {
let newPosition = (1-normX) * this.containerElement.offsetWidth.toString() + "px";
for(let i in this.series) {
this.series[i].canvasElement.style.left = newPosition;
}
} |
JavaScript | function toggleDiv(statement, divName) {
var element = document.getElementById(divName);
if(statement != 0) {
element.classList.remove("invisible");
} else {
element.classList.add("invisible");
}
} | function toggleDiv(statement, divName) {
var element = document.getElementById(divName);
if(statement != 0) {
element.classList.remove("invisible");
} else {
element.classList.add("invisible");
}
} |
JavaScript | function sha256_transform() {
var a, b, c, d, e, f, g, h, T1, T2;
var W = new Array(16);
/* Initialize registers with the previous intermediate value */
a = ihash[0];
b = ihash[1];
c = ihash[2];
d = ihash[3];
e = ihash[4];
f = ihash[5];
g = ihash[6];
h = ihash[7];
/* make 32-bit words */
for(var i=0; i<16; i++)
W[i] = ((buffer[(i<<2)+3]) | (buffer[(i<<2)+2] << 8) | (buffer[(i<<2)+1]
<< 16) | (buffer[i<<2] << 24));
for(var j=0; j<64; j++) {
T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];
if(j < 16) T1 += W[j];
else T1 += sha256_expand(W, j);
T2 = sha256_Sigma0(a) + majority(a, b, c);
h = g;
g = f;
f = e;
e = safe_add(d, T1);
d = c;
c = b;
b = a;
a = safe_add(T1, T2);
}
/* Compute the current intermediate hash value */
ihash[0] += a;
ihash[1] += b;
ihash[2] += c;
ihash[3] += d;
ihash[4] += e;
ihash[5] += f;
ihash[6] += g;
ihash[7] += h;
} | function sha256_transform() {
var a, b, c, d, e, f, g, h, T1, T2;
var W = new Array(16);
/* Initialize registers with the previous intermediate value */
a = ihash[0];
b = ihash[1];
c = ihash[2];
d = ihash[3];
e = ihash[4];
f = ihash[5];
g = ihash[6];
h = ihash[7];
/* make 32-bit words */
for(var i=0; i<16; i++)
W[i] = ((buffer[(i<<2)+3]) | (buffer[(i<<2)+2] << 8) | (buffer[(i<<2)+1]
<< 16) | (buffer[i<<2] << 24));
for(var j=0; j<64; j++) {
T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];
if(j < 16) T1 += W[j];
else T1 += sha256_expand(W, j);
T2 = sha256_Sigma0(a) + majority(a, b, c);
h = g;
g = f;
f = e;
e = safe_add(d, T1);
d = c;
c = b;
b = a;
a = safe_add(T1, T2);
}
/* Compute the current intermediate hash value */
ihash[0] += a;
ihash[1] += b;
ihash[2] += c;
ihash[3] += d;
ihash[4] += e;
ihash[5] += f;
ihash[6] += g;
ihash[7] += h;
} |
JavaScript | function sha256(data) {
sha256_init();
sha256_update(data, data.length);
sha256_final();
return sha256_encode_hex();
} | function sha256(data) {
sha256_init();
sha256_update(data, data.length);
sha256_final();
return sha256_encode_hex();
} |
JavaScript | updateMedia(uid, options) {
Utils.log(`update media ${uid} ${JSON.stringify(options)}`);
let media = this.data.media || [];
let changed = false;
for (let i = 0; i < media.length; i++) {
let item = media[i];
if (`${item.uid}` === `${uid}`) {
media[i] = Object.assign(item, options);
changed = true;
Utils.log(`after update media ${uid} ${JSON.stringify(item)}`)
break;
}
}
if (changed) {
return this.refreshMedia(media);
} else {
Utils.log(`media not changed: ${JSON.stringify(media)}`)
return Promise.resolve();
}
} | updateMedia(uid, options) {
Utils.log(`update media ${uid} ${JSON.stringify(options)}`);
let media = this.data.media || [];
let changed = false;
for (let i = 0; i < media.length; i++) {
let item = media[i];
if (`${item.uid}` === `${uid}`) {
media[i] = Object.assign(item, options);
changed = true;
Utils.log(`after update media ${uid} ${JSON.stringify(item)}`)
break;
}
}
if (changed) {
return this.refreshMedia(media);
} else {
Utils.log(`media not changed: ${JSON.stringify(media)}`)
return Promise.resolve();
}
} |
JavaScript | refreshMedia(media) {
return new Promise((resolve) => {
for (let i = 0; i < media.length; i++) {
if (i < max_user) {
//show
media[i].holding = false;
} else {
//hide 超过十人隐藏
media[i].holding = true;
}
}
if (media.length > max_user) {
wx.showToast({
title: '由于房内人数超过10人,部分视频未被加载显示',
icon: 'none'
});
}
Utils.log(`updating media: ${JSON.stringify(media)}`);
this.setData({
media: media
}, () => {
resolve();
});
});
} | refreshMedia(media) {
return new Promise((resolve) => {
for (let i = 0; i < media.length; i++) {
if (i < max_user) {
//show
media[i].holding = false;
} else {
//hide 超过十人隐藏
media[i].holding = true;
}
}
if (media.length > max_user) {
wx.showToast({
title: '由于房内人数超过10人,部分视频未被加载显示',
icon: 'none'
});
}
Utils.log(`updating media: ${JSON.stringify(media)}`);
this.setData({
media: media
}, () => {
resolve();
});
});
} |
JavaScript | function responsiveVideo() {
if ($.fn.fitVids) {
$(".video").fitVids()
}
} | function responsiveVideo() {
if ($.fn.fitVids) {
$(".video").fitVids()
}
} |
JavaScript | function googleMap() {
var ourAddress = $("#ourLocation").data("location") || "earth";
function getLatLong(address) {
var geo = new google.maps.Geocoder;
geo.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$("#map").gmap3({
map: {
options: {
maxZoom: 14,
streetViewControl: true,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.LEFT_CENTER
},
mapTypeControl: true,
scrollwheel: false,
disableDoubleClickZoom: true
}
},
streetviewpanorama: {
options: {
container: $("#streetView"),
opts: {
position: {"lat":35.8210411,"lng":10.5944035},
pov: {
heading: 231,
pitch: 10,
zoom: 0
}
}
}
}
}, "autofit");
} else {
alert("Geocode was not successful for the following reason: " + status);
}
})
}
if ($.fn.gmap3) {
getLatLong(ourAddress)
}
} | function googleMap() {
var ourAddress = $("#ourLocation").data("location") || "earth";
function getLatLong(address) {
var geo = new google.maps.Geocoder;
geo.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$("#map").gmap3({
map: {
options: {
maxZoom: 14,
streetViewControl: true,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.LEFT_CENTER
},
mapTypeControl: true,
scrollwheel: false,
disableDoubleClickZoom: true
}
},
streetviewpanorama: {
options: {
container: $("#streetView"),
opts: {
position: {"lat":35.8210411,"lng":10.5944035},
pov: {
heading: 231,
pitch: 10,
zoom: 0
}
}
}
}
}, "autofit");
} else {
alert("Geocode was not successful for the following reason: " + status);
}
})
}
if ($.fn.gmap3) {
getLatLong(ourAddress)
}
} |
JavaScript | function selectpicker() {
if ($.fn.selectpicker) {
$(".selectpicker").selectpicker()
}
} | function selectpicker() {
if ($.fn.selectpicker) {
$(".selectpicker").selectpicker()
}
} |
JavaScript | function navigation() {
if ($.fn.onePageNav && $("#nav").length) {
$('#nav').onePageNav({
currentClass: 'active',
scrollSpeed: 600,
scrollOffset: 60,
scrollThreshold: 0.2,
easing: 'swing'
})
}
} | function navigation() {
if ($.fn.onePageNav && $("#nav").length) {
$('#nav').onePageNav({
currentClass: 'active',
scrollSpeed: 600,
scrollOffset: 60,
scrollThreshold: 0.2,
easing: 'swing'
})
}
} |
JavaScript | function handleErrors( response ) {
if ( !response.ok ) {
throw Error( response.statusText )
}
return response
} | function handleErrors( response ) {
if ( !response.ok ) {
throw Error( response.statusText )
}
return response
} |
JavaScript | function _type_out(message, id) {
return new Promise((resolve) => {
let delay = 200;
(function loop(i) {
if (i < message.length) {
$(id).text($(id).text() + message[i]);
window.setTimeout(function () { loop(++i); }, delay);
}
else {
resolve();
return;
}
})(0);
})
} | function _type_out(message, id) {
return new Promise((resolve) => {
let delay = 200;
(function loop(i) {
if (i < message.length) {
$(id).text($(id).text() + message[i]);
window.setTimeout(function () { loop(++i); }, delay);
}
else {
resolve();
return;
}
})(0);
})
} |
JavaScript | function handleUrl(url) {
var targetUrl,
index = url ? url.indexOf("://") : "",
isAbsolutePath = index !== -1;
if (isAbsolutePath) {
targetUrl = url;
} else {
if (url) {
targetUrl = _domain + url;
} else {
targetUrl = _domain;
}
}
return targetUrl;
} | function handleUrl(url) {
var targetUrl,
index = url ? url.indexOf("://") : "",
isAbsolutePath = index !== -1;
if (isAbsolutePath) {
targetUrl = url;
} else {
if (url) {
targetUrl = _domain + url;
} else {
targetUrl = _domain;
}
}
return targetUrl;
} |
JavaScript | function findReasonString(headerString) {
var obj = _generalHelper.parseHeaders(headerString);
for (var item in obj["X-Ms-diagnostics"]) {
return obj["X-Ms-diagnostics"][item].reason;
}
return null;
} | function findReasonString(headerString) {
var obj = _generalHelper.parseHeaders(headerString);
for (var item in obj["X-Ms-diagnostics"]) {
return obj["X-Ms-diagnostics"][item].reason;
}
return null;
} |
JavaScript | function testForDomainChanges(request, callback) {
if (request._links && request._links.xframe) {
if (_xframe !== request._links.xframe.href) {
_xframe = request._links.xframe.href;
_scope.injectFrame(_xframe, _container, callback);
return true;
}
}
return false;
} | function testForDomainChanges(request, callback) {
if (request._links && request._links.xframe) {
if (_xframe !== request._links.xframe.href) {
_xframe = request._links.xframe.href;
_scope.injectFrame(_xframe, _container, callback);
return true;
}
}
return false;
} |
JavaScript | function loadContent(id) {
$.ajax({
url: "samples/html/" + id + ".html",
type: "get",
dataType: "text",
success: function(result) {
$(".content").html(result);
var counter = 0;
$(".task").each(function() {
$(this)[0].id = counter++;
$("#tasks").append($("#task-template").tmpl({
text: $(this).text(),
id: $(this)[0].id
}));
});
}
});
} | function loadContent(id) {
$.ajax({
url: "samples/html/" + id + ".html",
type: "get",
dataType: "text",
success: function(result) {
$(".content").html(result);
var counter = 0;
$(".task").each(function() {
$(this)[0].id = counter++;
$("#tasks").append($("#task-template").tmpl({
text: $(this).text(),
id: $(this)[0].id
}));
});
}
});
} |
Subsets and Splits