language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function demoInput(event) { const demo = event.currentTarget.parentElement const query = demo.getElementsByClassName("query").item(0) const result = demo.getElementsByClassName("result").item(0) try { const data = JSON.parse(demo.getElementsByClassName("data").item(0).value) result.textContent = JSON.stringify(jmespath.search(data, query.value), null, 2).replaceAll(",\n", ",") } catch (e) { result.textContent = e.message } }
function demoInput(event) { const demo = event.currentTarget.parentElement const query = demo.getElementsByClassName("query").item(0) const result = demo.getElementsByClassName("result").item(0) try { const data = JSON.parse(demo.getElementsByClassName("data").item(0).value) result.textContent = JSON.stringify(jmespath.search(data, query.value), null, 2).replaceAll(",\n", ",") } catch (e) { result.textContent = e.message } }
JavaScript
function clickFoodItem(id) { var _token = $('#__token__').val(); $.ajax({ url: '/get-food-extras', method: 'post', data: { get_food_extras: 'Y', _token: _token, food_id: id, }, success: function (res) { if (res.status === 'success') { console.log(res); showExtras(id, res.extras); } else { customAlert(res.message); } } }) }
function clickFoodItem(id) { var _token = $('#__token__').val(); $.ajax({ url: '/get-food-extras', method: 'post', data: { get_food_extras: 'Y', _token: _token, food_id: id, }, success: function (res) { if (res.status === 'success') { console.log(res); showExtras(id, res.extras); } else { customAlert(res.message); } } }) }
JavaScript
serialize() { return { deserializer: "AtomWhatsappView" } }
serialize() { return { deserializer: "AtomWhatsappView" } }
JavaScript
function asyncAuto (tasks, concurrency, callback) { if (typeof concurrency === 'function') { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = once(callback || noop); var keys$1 = keys(tasks); var numTasks = keys$1.length; if (!numTasks) { return callback(null); } if (!concurrency) { concurrency = numTasks; } var results = {}; var runningTasks = 0; var hasError = false; var listeners = Object.create(null); var readyTasks = []; // for cycle detection: var readyToCheck = []; // tasks that have been identified as reachable // without the possibility of returning to an ancestor task var uncheckedDependencies = {}; baseForOwn(tasks, function (task, key) { if (!isArray(task)) { // no dependencies enqueueTask(key, [task]); readyToCheck.push(key); return; } var dependencies = task.slice(0, task.length - 1); var remainingDependencies = dependencies.length; if (remainingDependencies === 0) { enqueueTask(key, task); readyToCheck.push(key); return; } uncheckedDependencies[key] = remainingDependencies; arrayEach(dependencies, function (dependencyName) { if (!tasks[dependencyName]) { throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); } addListener(dependencyName, function () { remainingDependencies--; if (remainingDependencies === 0) { enqueueTask(key, task); } }); }); }); checkForDeadlocks(); processQueue(); function enqueueTask(key, task) { readyTasks.push(function () { runTask(key, task); }); } function processQueue() { if (readyTasks.length === 0 && runningTasks === 0) { return callback(null, results); } while(readyTasks.length && runningTasks < concurrency) { var run = readyTasks.shift(); run(); } } function addListener(taskName, fn) { var taskListeners = listeners[taskName]; if (!taskListeners) { taskListeners = listeners[taskName] = []; } taskListeners.push(fn); } function taskComplete(taskName) { var taskListeners = listeners[taskName] || []; arrayEach(taskListeners, function (fn) { fn(); }); processQueue(); } function runTask(key, task) { if (hasError) return; var taskCallback = onlyOnce(function(err, result) { runningTasks--; if (arguments.length > 2) { result = slice(arguments, 1); } if (err) { var safeResults = {}; baseForOwn(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[key] = result; hasError = true; listeners = Object.create(null); callback(err, safeResults); } else { results[key] = result; taskComplete(key); } }); runningTasks++; var taskFn = wrapAsync(task[task.length - 1]); if (task.length > 1) { taskFn(results, taskCallback); } else { taskFn(taskCallback); } } function checkForDeadlocks() { // Kahn's algorithm // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html var currentTask; var counter = 0; while (readyToCheck.length) { currentTask = readyToCheck.pop(); counter++; arrayEach(getDependents(currentTask), function (dependent) { if (--uncheckedDependencies[dependent] === 0) { readyToCheck.push(dependent); } }); } if (counter !== numTasks) { throw new Error( 'async.auto cannot execute tasks due to a recursive dependency' ); } } function getDependents(taskName) { var result = []; baseForOwn(tasks, function (task, key) { if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { result.push(key); } }); return result; } }
function asyncAuto (tasks, concurrency, callback) { if (typeof concurrency === 'function') { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = once(callback || noop); var keys$1 = keys(tasks); var numTasks = keys$1.length; if (!numTasks) { return callback(null); } if (!concurrency) { concurrency = numTasks; } var results = {}; var runningTasks = 0; var hasError = false; var listeners = Object.create(null); var readyTasks = []; // for cycle detection: var readyToCheck = []; // tasks that have been identified as reachable // without the possibility of returning to an ancestor task var uncheckedDependencies = {}; baseForOwn(tasks, function (task, key) { if (!isArray(task)) { // no dependencies enqueueTask(key, [task]); readyToCheck.push(key); return; } var dependencies = task.slice(0, task.length - 1); var remainingDependencies = dependencies.length; if (remainingDependencies === 0) { enqueueTask(key, task); readyToCheck.push(key); return; } uncheckedDependencies[key] = remainingDependencies; arrayEach(dependencies, function (dependencyName) { if (!tasks[dependencyName]) { throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); } addListener(dependencyName, function () { remainingDependencies--; if (remainingDependencies === 0) { enqueueTask(key, task); } }); }); }); checkForDeadlocks(); processQueue(); function enqueueTask(key, task) { readyTasks.push(function () { runTask(key, task); }); } function processQueue() { if (readyTasks.length === 0 && runningTasks === 0) { return callback(null, results); } while(readyTasks.length && runningTasks < concurrency) { var run = readyTasks.shift(); run(); } } function addListener(taskName, fn) { var taskListeners = listeners[taskName]; if (!taskListeners) { taskListeners = listeners[taskName] = []; } taskListeners.push(fn); } function taskComplete(taskName) { var taskListeners = listeners[taskName] || []; arrayEach(taskListeners, function (fn) { fn(); }); processQueue(); } function runTask(key, task) { if (hasError) return; var taskCallback = onlyOnce(function(err, result) { runningTasks--; if (arguments.length > 2) { result = slice(arguments, 1); } if (err) { var safeResults = {}; baseForOwn(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[key] = result; hasError = true; listeners = Object.create(null); callback(err, safeResults); } else { results[key] = result; taskComplete(key); } }); runningTasks++; var taskFn = wrapAsync(task[task.length - 1]); if (task.length > 1) { taskFn(results, taskCallback); } else { taskFn(taskCallback); } } function checkForDeadlocks() { // Kahn's algorithm // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html var currentTask; var counter = 0; while (readyToCheck.length) { currentTask = readyToCheck.pop(); counter++; arrayEach(getDependents(currentTask), function (dependent) { if (--uncheckedDependencies[dependent] === 0) { readyToCheck.push(dependent); } }); } if (counter !== numTasks) { throw new Error( 'async.auto cannot execute tasks due to a recursive dependency' ); } } function getDependents(taskName) { var result = []; baseForOwn(tasks, function (task, key) { if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { result.push(key); } }); return result; } }
JavaScript
function handleRequest(request, response) { const currentSpan = api.trace.getSpan(api.context.active()); // display traceid in the terminal console.log(`traceid: ${currentSpan.spanContext().traceId}`); const span = tracer.startSpan('handleRequest', { kind: 1, // server attributes: { hello: 'world' }, }); // Annotate our span to capture metadata about the operation span.addEvent('invoking handleRequest'); const body = []; request.on('error', (err) => console.log(err)); request.on('data', (chunk) => body.push(chunk)); request.on('end', () => { // deliberately sleeping to mock some action. setTimeout(() => { span.end(); response.end('Hello From Service B!'); }, 2000); }); }
function handleRequest(request, response) { const currentSpan = api.trace.getSpan(api.context.active()); // display traceid in the terminal console.log(`traceid: ${currentSpan.spanContext().traceId}`); const span = tracer.startSpan('handleRequest', { kind: 1, // server attributes: { hello: 'world' }, }); // Annotate our span to capture metadata about the operation span.addEvent('invoking handleRequest'); const body = []; request.on('error', (err) => console.log(err)); request.on('data', (chunk) => body.push(chunk)); request.on('end', () => { // deliberately sleeping to mock some action. setTimeout(() => { span.end(); response.end('Hello From Service B!'); }, 2000); }); }
JavaScript
function handleRequest(request, response) { const currentSpan = api.trace.getSpan(api.context.active()); // display traceid in the terminal console.log(`traceid: ${currentSpan.spanContext().traceId}`); const span = tracer.startSpan('handleRequest', { kind: 1, // server attributes: { key: 'value' }, }); // Annotate our span to capture metadata about the operation span.addEvent('invoking handleRequest'); const body = []; request.on('error', (err) => console.log(err)); request.on('data', (chunk) => body.push(chunk)); request.on('end', () => { // send request to service-B http.get({ host: 'localhost', port: 8081, path: '/', }, (res) => { const body = []; res.on('data', (chunk) => body.push(chunk)); res.on('end', () => { console.log(body.toString()); span.end(); response.end('Done!') }); }); }); }
function handleRequest(request, response) { const currentSpan = api.trace.getSpan(api.context.active()); // display traceid in the terminal console.log(`traceid: ${currentSpan.spanContext().traceId}`); const span = tracer.startSpan('handleRequest', { kind: 1, // server attributes: { key: 'value' }, }); // Annotate our span to capture metadata about the operation span.addEvent('invoking handleRequest'); const body = []; request.on('error', (err) => console.log(err)); request.on('data', (chunk) => body.push(chunk)); request.on('end', () => { // send request to service-B http.get({ host: 'localhost', port: 8081, path: '/', }, (res) => { const body = []; res.on('data', (chunk) => body.push(chunk)); res.on('end', () => { console.log(body.toString()); span.end(); response.end('Done!') }); }); }); }
JavaScript
function fadeTo(cmd, opt) { var stat = self.xStat[cmd] var node = cmd.split('/').pop(); var opTicks = parseInt(opt.ticks); var steps = stat.fSteps; var span = parseFloat(opt.duration); var oldVal = stat[node]; var oldIdx = stat.idx; var byVal = opTicks * steps / 100; var newIdx = Math.min(steps - 1, Math.max(0, oldIdx + Math.round(byVal))); var slot = opt.store == 'me' ? cmd : opt.store; var r, byVal, newIdx; switch (subAct) { case '_a': // adjust +/- (pseudo %) byVal = opTicks * steps / 100; newIdx = Math.min(steps - 1, Math.max(0, oldIdx + Math.round(byVal))); r = self.fLevels[steps][newIdx]; break; case '_r': // restore r = slot && self.tempStore[slot] ? self.tempStore[slot] : -1; break; case '_s': // store if (slot) { // sanity check self.tempStore[slot] = stat[node]; } r = -1; // the 'store' actions are internal to this module only // r is left undefined since there is nothing to send break; default: // set new value r = parseFloat(opt.fad); } // set up cross fade? if (span > 0 && r >= 0) { var xSteps = span / (1000 / self.fadeResolution); var xDelta = Math.floor((r - oldVal) / xSteps * 10000) / 10000; if (xDelta == 0) { // already there r = -1; } else { self.crossFades[cmd] = { steps: xSteps, delta: xDelta, startVal: oldVal, finalVal: r, atStep: 1 }; // start the xfade r = oldVal + xDelta; } } self.debug(`---------- ${oldIdx}:${oldVal} by ${byVal}(${opTicks}) fadeTo ${newIdx}:${r} ----------`); return r; }
function fadeTo(cmd, opt) { var stat = self.xStat[cmd] var node = cmd.split('/').pop(); var opTicks = parseInt(opt.ticks); var steps = stat.fSteps; var span = parseFloat(opt.duration); var oldVal = stat[node]; var oldIdx = stat.idx; var byVal = opTicks * steps / 100; var newIdx = Math.min(steps - 1, Math.max(0, oldIdx + Math.round(byVal))); var slot = opt.store == 'me' ? cmd : opt.store; var r, byVal, newIdx; switch (subAct) { case '_a': // adjust +/- (pseudo %) byVal = opTicks * steps / 100; newIdx = Math.min(steps - 1, Math.max(0, oldIdx + Math.round(byVal))); r = self.fLevels[steps][newIdx]; break; case '_r': // restore r = slot && self.tempStore[slot] ? self.tempStore[slot] : -1; break; case '_s': // store if (slot) { // sanity check self.tempStore[slot] = stat[node]; } r = -1; // the 'store' actions are internal to this module only // r is left undefined since there is nothing to send break; default: // set new value r = parseFloat(opt.fad); } // set up cross fade? if (span > 0 && r >= 0) { var xSteps = span / (1000 / self.fadeResolution); var xDelta = Math.floor((r - oldVal) / xSteps * 10000) / 10000; if (xDelta == 0) { // already there r = -1; } else { self.crossFades[cmd] = { steps: xSteps, delta: xDelta, startVal: oldVal, finalVal: r, atStep: 1 }; // start the xfade r = oldVal + xDelta; } } self.debug(`---------- ${oldIdx}:${oldVal} by ${byVal}(${opTicks}) fadeTo ${newIdx}:${r} ----------`); return r; }
JavaScript
async function updateRoomWatching() { const url = `${baseUrl}/api/room?type=1` const payload = { roomID, data } const response = await axios.post(url, payload) }
async function updateRoomWatching() { const url = `${baseUrl}/api/room?type=1` const payload = { roomID, data } const response = await axios.post(url, payload) }
JavaScript
updateStyle(styleDef) { this.set('style', createStyleFunc(styleDef.name, styleDef.options)); for (let i = 0, ii = this.workers.length; i < ii; i++) { this.workers[i].postMessage({ type: 'SET_STYLE', style: styleDef, }); } }
updateStyle(styleDef) { this.set('style', createStyleFunc(styleDef.name, styleDef.options)); for (let i = 0, ii = this.workers.length; i < ii; i++) { this.workers[i].postMessage({ type: 'SET_STYLE', style: styleDef, }); } }
JavaScript
onWorkerMessage(message) { const src = this.getSource(); const tc = src.tileCache; let target = null; try { target = tc.get(message.data.key); } catch (e) { // swallow the not found error. } // ensure the target has a canvas defined. // it is possible to get an offscreen tile with no canvas. if (target && target.canvas) { const ctx = target.canvas.getContext('2d'); const imgData = ctx.createImageData(256, 256); imgData.data.set(message.data.results); ctx.putImageData(imgData, 0, 0); src.changed(); } }
onWorkerMessage(message) { const src = this.getSource(); const tc = src.tileCache; let target = null; try { target = tc.get(message.data.key); } catch (e) { // swallow the not found error. } // ensure the target has a canvas defined. // it is possible to get an offscreen tile with no canvas. if (target && target.canvas) { const ctx = target.canvas.getContext('2d'); const imgData = ctx.createImageData(256, 256); imgData.data.set(message.data.results); ctx.putImageData(imgData, 0, 0); src.changed(); } }
JavaScript
function contrastStretchAverage(ranges) { const min = Math.floor((ranges[0][0] + ranges[1][0] + ranges[2][0]) / 3); const max = Math.floor((ranges[0][1] + ranges[1][1] + ranges[2][1]) / 3); const stretched = new Array(3); for (let i = 0, len = ranges.length; i < len; i++) { stretched[i] = [min, max]; } return stretched; }
function contrastStretchAverage(ranges) { const min = Math.floor((ranges[0][0] + ranges[1][0] + ranges[2][0]) / 3); const max = Math.floor((ranges[0][1] + ranges[1][1] + ranges[2][1]) / 3); const stretched = new Array(3); for (let i = 0, len = ranges.length; i < len; i++) { stretched[i] = [min, max]; } return stretched; }
JavaScript
function applyBrightnessContrastSaturation(brt, con, s) { const mat = prepareBCSMat(brt, con, s); return px => { const r = px[0]; const g = px[1]; const b = px[2]; px[0] = r * mat[0][0] + g * mat[1][0] + b * mat[2][0] + mat[3][0]; px[1] = r * mat[0][1] + g * mat[1][1] + b * mat[2][1] + mat[3][1]; px[2] = r * mat[0][2] + g * mat[1][2] + b * mat[2][2] + mat[3][2]; // note - we're taking advantage of receiver of pix using a clamped uint8 // to handle min/max of 0, 255 return px; }; }
function applyBrightnessContrastSaturation(brt, con, s) { const mat = prepareBCSMat(brt, con, s); return px => { const r = px[0]; const g = px[1]; const b = px[2]; px[0] = r * mat[0][0] + g * mat[1][0] + b * mat[2][0] + mat[3][0]; px[1] = r * mat[0][1] + g * mat[1][1] + b * mat[2][1] + mat[3][1]; px[2] = r * mat[0][2] + g * mat[1][2] + b * mat[2][2] + mat[3][2]; // note - we're taking advantage of receiver of pix using a clamped uint8 // to handle min/max of 0, 255 return px; }; }
JavaScript
function fromArrayBuffer(buf) { if (buf.byteLength === 0) { return {}; } // Check the magic number if (!isNumpyArr(buf)) { throw new Error('Not a NumpyTile'); } const headerLength = readUint16LE(buf.slice(8, 10)), headerStr = asciiDecode(buf.slice(10, 10 + headerLength)), offsetBytes = 10 + headerLength; // this is a rough but working conversion of the // numpy header dict to Javascript object. const info = JSON.parse( headerStr .toLowerCase() .replace(/'/g, '"') .replace(/\(/g, '[') .replace(/\),/g, ']') ); // Intepret the bytes according to the specified dtype let data; if (info.descr === '|u1') { data = new Uint8Array(buf, offsetBytes); } else if (info.descr === '|i1') { data = new Int8Array(buf, offsetBytes); } else if (info.descr === '<u2') { data = new Uint16Array(buf, offsetBytes); } else if (info.descr === '<i2') { data = new Int16Array(buf, offsetBytes); } else if (info.descr === '<u4') { data = new Uint32Array(buf, offsetBytes); } else if (info.descr === '<i4') { data = new Int32Array(buf, offsetBytes); } else if (info.descr === '<f4') { data = new Float32Array(buf, offsetBytes); } else if (info.descr === '<f8') { data = new Float64Array(buf, offsetBytes); } else { throw new Error('unknown numeric dtype'); } return { shape: info.shape, data: data, }; }
function fromArrayBuffer(buf) { if (buf.byteLength === 0) { return {}; } // Check the magic number if (!isNumpyArr(buf)) { throw new Error('Not a NumpyTile'); } const headerLength = readUint16LE(buf.slice(8, 10)), headerStr = asciiDecode(buf.slice(10, 10 + headerLength)), offsetBytes = 10 + headerLength; // this is a rough but working conversion of the // numpy header dict to Javascript object. const info = JSON.parse( headerStr .toLowerCase() .replace(/'/g, '"') .replace(/\(/g, '[') .replace(/\),/g, ']') ); // Intepret the bytes according to the specified dtype let data; if (info.descr === '|u1') { data = new Uint8Array(buf, offsetBytes); } else if (info.descr === '|i1') { data = new Int8Array(buf, offsetBytes); } else if (info.descr === '<u2') { data = new Uint16Array(buf, offsetBytes); } else if (info.descr === '<i2') { data = new Int16Array(buf, offsetBytes); } else if (info.descr === '<u4') { data = new Uint32Array(buf, offsetBytes); } else if (info.descr === '<i4') { data = new Int32Array(buf, offsetBytes); } else if (info.descr === '<f4') { data = new Float32Array(buf, offsetBytes); } else if (info.descr === '<f8') { data = new Float64Array(buf, offsetBytes); } else { throw new Error('unknown numeric dtype'); } return { shape: info.shape, data: data, }; }
JavaScript
calculateHistogram(view) { const zoom = this.tileGrid.getZForResolution( view.getResolution(), this.zDirection ); const pxDepth = this.get('pixelDepth'); // check to see if the layer is ready. let histogram = null; this.forEachTileInExtent(view.calculateExtent(), zoom, tile => { const tileState = tile.getState(); if (tileState === TileState.LOADED) { histogram = getHistogram(tile, pxDepth, this.get('bands'), histogram); } }); return histogram; }
calculateHistogram(view) { const zoom = this.tileGrid.getZForResolution( view.getResolution(), this.zDirection ); const pxDepth = this.get('pixelDepth'); // check to see if the layer is ready. let histogram = null; this.forEachTileInExtent(view.calculateExtent(), zoom, tile => { const tileState = tile.getState(); if (tileState === TileState.LOADED) { histogram = getHistogram(tile, pxDepth, this.get('bands'), histogram); } }); return histogram; }
JavaScript
function hulkSmash(statements) { const monsters = [ 'new ', 'window', 'fetch', 'global', 'document', 'alert', 'confirm', 'Math', ].map(monster => new RegExp(monster, 'ig')); // copy the statements to a fresh string let smashed = '' + statements; // smash each monster. monsters.forEach(monster => { smashed = smashed.replace(monster, ''); }); return smashed; }
function hulkSmash(statements) { const monsters = [ 'new ', 'window', 'fetch', 'global', 'document', 'alert', 'confirm', 'Math', ].map(monster => new RegExp(monster, 'ig')); // copy the statements to a fresh string let smashed = '' + statements; // smash each monster. monsters.forEach(monster => { smashed = smashed.replace(monster, ''); }); return smashed; }
JavaScript
function processData(data, bandsize, bandOffset, bandMap, rgbaFunc) { const nBands = bandOffset.length; const res = new Uint8ClampedArray(4 * bandsize); // 8-band capable. const bandData = new Array(nBands); for (let b = 0; b < bandsize; b++) { for (let i = 0; i < nBands; i++) { bandData[i] = data[b + bandOffset[i]]; } rgbaFunc(bandData, bandMap); const offset = b * 4; res[offset] = bandData[0]; res[offset + 1] = bandData[1]; res[offset + 2] = bandData[2]; res[offset + 3] = bandData[3]; } return res; }
function processData(data, bandsize, bandOffset, bandMap, rgbaFunc) { const nBands = bandOffset.length; const res = new Uint8ClampedArray(4 * bandsize); // 8-band capable. const bandData = new Array(nBands); for (let b = 0; b < bandsize; b++) { for (let i = 0; i < nBands; i++) { bandData[i] = data[b + bandOffset[i]]; } rgbaFunc(bandData, bandMap); const offset = b * 4; res[offset] = bandData[0]; res[offset + 1] = bandData[1]; res[offset + 2] = bandData[2]; res[offset + 3] = bandData[3]; } return res; }
JavaScript
function drawArray(styleFunc, data, bands) { const bandMap = {}; const bandOffset = []; const bandsize = 256 * 256; const inBands = bands.slice(); if (inBands.indexOf('a') < 0) { inBands.push('a'); } for (let i = 0, ii = inBands.length; i < ii; i++) { bandOffset.push(i * bandsize); bandMap[inBands[i]] = i; } return processData(data, bandsize, bandOffset, bandMap, styleFunc); }
function drawArray(styleFunc, data, bands) { const bandMap = {}; const bandOffset = []; const bandsize = 256 * 256; const inBands = bands.slice(); if (inBands.indexOf('a') < 0) { inBands.push('a'); } for (let i = 0, ii = inBands.length; i < ii; i++) { bandOffset.push(i * bandsize); bandMap[inBands[i]] = i; } return processData(data, bandsize, bandOffset, bandMap, styleFunc); }
JavaScript
forPixel(dataFn) { // empty arrays get empty results. if (!this.numpyTile || !this.numpyTile.data) { return []; } return eachPixel( this.numpyTile.data, this.getBandOffsets(this.bands), this.bandSize, dataFn ); }
forPixel(dataFn) { // empty arrays get empty results. if (!this.numpyTile || !this.numpyTile.data) { return []; } return eachPixel( this.numpyTile.data, this.getBandOffsets(this.bands), this.bandSize, dataFn ); }
JavaScript
function d3_rebind(target, source, method) { return function () { var value = method.apply(source, arguments); return value === source ? target : value; }; }
function d3_rebind(target, source, method) { return function () { var value = method.apply(source, arguments); return value === source ? target : value; }; }
JavaScript
function toggleButtons() { const input = document.querySelector('.comment .input'); const aside = document.querySelector('.comment__aside'); const transparent = document.querySelector('.comment .cancel'); input.addEventListener('focus', function () { aside.classList.remove('hide'); }); transparent.addEventListener('click', function () { aside.classList.add('hide'); input.value = ''; }); }
function toggleButtons() { const input = document.querySelector('.comment .input'); const aside = document.querySelector('.comment__aside'); const transparent = document.querySelector('.comment .cancel'); input.addEventListener('focus', function () { aside.classList.remove('hide'); }); transparent.addEventListener('click', function () { aside.classList.add('hide'); input.value = ''; }); }
JavaScript
function loadUser() { fetch('/login?isLoggedIn') .then(res => res.text()) .then(u => { user = u; loadUserData(user); }) .catch(error => console.log(error)); return; }
function loadUser() { fetch('/login?isLoggedIn') .then(res => res.text()) .then(u => { user = u; loadUserData(user); }) .catch(error => console.log(error)); return; }
JavaScript
function loadUserData(user) { if (user) { user = JSON.parse(user); const nav = document.querySelector('.nav__user__div'); const userVar = nav.querySelector('.user'); const profile = nav.querySelector('.dropdown--profile'); const form = nav.querySelector('.dropdown--logout'); const logout = nav.querySelector('.submit'); nav.classList.remove('hide'); userVar.classList.remove('hide'); userVar.innerHTML = user.username; const img = new Image(); const picture = document.createElement('div'); img.src = user.profilePicture.url; picture.className = 'picture order-1'; picture.appendChild(img); nav.appendChild(picture); profile.href = `/user/${user._id}`; logout.addEventListener('click', () => form.submit()); logout.addEventListener('keypress', function (e) { const key = e.keyCode || e.which; if (key === 13) { form.submit(); } }); } else { const nav = document.querySelector('.nav__user__a'); const login = nav.querySelector('.login'); nav.classList.remove('hide'); login.classList.remove('hide'); const img = new Image(); const picture = document.createElement('div'); img.src = 'https://res.cloudinary.com/christianjosuebt/image/upload/coffeeShops/smile_bpkzip.svg'; picture.className = 'picture order-1'; picture.appendChild(img); nav.appendChild(picture); nav.classList.add('border', 'height--80'); nav.href = '/login'; } return; }
function loadUserData(user) { if (user) { user = JSON.parse(user); const nav = document.querySelector('.nav__user__div'); const userVar = nav.querySelector('.user'); const profile = nav.querySelector('.dropdown--profile'); const form = nav.querySelector('.dropdown--logout'); const logout = nav.querySelector('.submit'); nav.classList.remove('hide'); userVar.classList.remove('hide'); userVar.innerHTML = user.username; const img = new Image(); const picture = document.createElement('div'); img.src = user.profilePicture.url; picture.className = 'picture order-1'; picture.appendChild(img); nav.appendChild(picture); profile.href = `/user/${user._id}`; logout.addEventListener('click', () => form.submit()); logout.addEventListener('keypress', function (e) { const key = e.keyCode || e.which; if (key === 13) { form.submit(); } }); } else { const nav = document.querySelector('.nav__user__a'); const login = nav.querySelector('.login'); nav.classList.remove('hide'); login.classList.remove('hide'); const img = new Image(); const picture = document.createElement('div'); img.src = 'https://res.cloudinary.com/christianjosuebt/image/upload/coffeeShops/smile_bpkzip.svg'; picture.className = 'picture order-1'; picture.appendChild(img); nav.appendChild(picture); nav.classList.add('border', 'height--80'); nav.href = '/login'; } return; }
JavaScript
function handleIntersect(entries) { if (entries[0].isIntersecting) { getData(); } }
function handleIntersect(entries) { if (entries[0].isIntersecting) { getData(); } }
JavaScript
function dropDown() { const toggles = document.querySelectorAll('.dropdown__toggle'); for (let toggle of toggles) { toggle.addEventListener('click', function (event) { event.preventDefault(); const dropdown = event.target.parentNode; dropdown.classList.toggle('is-open'); }); } window.onclick = function (event) { if (!event.target.matches('.dropdown__toggle')) { const dropDowns = document.querySelectorAll('.dropdown'); for (i = 0; i < dropDowns.length; i++) { if (dropDowns[i].classList.contains('is-open')) dropDowns[i].classList.remove('is-open'); } } }; return; }
function dropDown() { const toggles = document.querySelectorAll('.dropdown__toggle'); for (let toggle of toggles) { toggle.addEventListener('click', function (event) { event.preventDefault(); const dropdown = event.target.parentNode; dropdown.classList.toggle('is-open'); }); } window.onclick = function (event) { if (!event.target.matches('.dropdown__toggle')) { const dropDowns = document.querySelectorAll('.dropdown'); for (i = 0; i < dropDowns.length; i++) { if (dropDowns[i].classList.contains('is-open')) dropDowns[i].classList.remove('is-open'); } } }; return; }
JavaScript
function masonryLayout() { state = 'masonry'; const shops = document.querySelector('.container--100'); shops.classList.remove('container--layout'); const cards = document.querySelectorAll('.card'); for (let card of cards) { card.classList.remove('card--large'); card.classList.remove('card--small'); card.classList.remove('card--layout'); changeImages(card, colWidth); } setupBlocks(); window.addEventListener('resize', setupBlocks, { signal: controller.signal }); return; }
function masonryLayout() { state = 'masonry'; const shops = document.querySelector('.container--100'); shops.classList.remove('container--layout'); const cards = document.querySelectorAll('.card'); for (let card of cards) { card.classList.remove('card--large'); card.classList.remove('card--small'); card.classList.remove('card--layout'); changeImages(card, colWidth); } setupBlocks(); window.addEventListener('resize', setupBlocks, { signal: controller.signal }); return; }
JavaScript
function loadImages(images) { colWidth = parseInt( window.getComputedStyle(document.body).getPropertyValue('font-size') ) * 16; const pixelRatio = window.devicePixelRatio || 1.0; let str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,w_${Math.round( colWidth * pixelRatio )}/coffeeShops`; for (let i = 0; i < images.length; i++) { images[i].src = `${str}/${images[i].dataset.src}`; } }
function loadImages(images) { colWidth = parseInt( window.getComputedStyle(document.body).getPropertyValue('font-size') ) * 16; const pixelRatio = window.devicePixelRatio || 1.0; let str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,w_${Math.round( colWidth * pixelRatio )}/coffeeShops`; for (let i = 0; i < images.length; i++) { images[i].src = `${str}/${images[i].dataset.src}`; } }
JavaScript
function changeImages(card, colWidth) { const pixelRatio = window.devicePixelRatio || 1.0; let str = ''; const images = card.querySelectorAll('img'); // console.log(images); if (state === 'masonry') { str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,w_${Math.round( colWidth * pixelRatio )}/coffeeShops`; } else if (state === 'large') { str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,w_${Math.round( colWidth * pixelRatio )},ar_2:3,c_fill/coffeeShops`; } else if (state === 'small') { str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,w_${Math.round( colWidth * pixelRatio )},ar_1:1,c_fill/coffeeShops`; } for (let i = 0; i < images.length; i++) { images[i].src = `${str}/${images[i].dataset.src}`; } return; }
function changeImages(card, colWidth) { const pixelRatio = window.devicePixelRatio || 1.0; let str = ''; const images = card.querySelectorAll('img'); // console.log(images); if (state === 'masonry') { str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,w_${Math.round( colWidth * pixelRatio )}/coffeeShops`; } else if (state === 'large') { str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,w_${Math.round( colWidth * pixelRatio )},ar_2:3,c_fill/coffeeShops`; } else if (state === 'small') { str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,w_${Math.round( colWidth * pixelRatio )},ar_1:1,c_fill/coffeeShops`; } for (let i = 0; i < images.length; i++) { images[i].src = `${str}/${images[i].dataset.src}`; } return; }
JavaScript
function createCard(data) { let className = ''; if (state === 'masonry') { className = 'card card--v2'; } else if (state === 'large') { className = 'card card--v2 card--layout card--large'; } else if (state === 'small') { className = 'card card--v2 card--layout card--small'; } let card = document.createElement('div'); let card__image = document.createElement('div'); let card__image__top = document.createElement('div'); let card__image__bottom = document.createElement('div'); let h3 = document.createElement('h3'); let h3__a = document.createElement('a'); let p = document.createElement('p'); let svgLeft = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); let useLeft = document.createElementNS('http://www.w3.org/2000/svg', 'use'); let svgRight = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); let useRight = document.createElementNS('http://www.w3.org/2000/svg', 'use'); useLeft.setAttribute('href', '#svg--left'); useRight.setAttribute('href', '#svg--right'); svgLeft.setAttribute('class', 'button--svg button--left hide'); svgRight.setAttribute('class', 'button--svg button--right hide'); svgLeft.appendChild(useLeft); svgRight.appendChild(useRight); card.className = className; card__image.className = 'card__image carousel'; card__image__top.className = 'card__image__top'; card__image__bottom.className = 'card__image__bottom'; h3__a.innerHTML = data.name.split(/\s+/).slice(0, 4).join(' '); h3__a.setAttribute('href', `/coffeeShops/${data._id}`); p.innerHTML = `${data.description.slice(0, 50)}...`; h3.appendChild(h3__a); card__image__top.appendChild(h3); card__image__bottom.appendChild(p); card__image.appendChild(card__image__top); card__image.appendChild(card__image__bottom); card__image.appendChild(svgLeft); card__image.appendChild(svgRight); card.appendChild(card__image); container100.appendChild(card); setImages(card__image, data.images, colWidth, data._id); if (data.images.length > 1) { display([svgLeft, svgRight]); } return; }
function createCard(data) { let className = ''; if (state === 'masonry') { className = 'card card--v2'; } else if (state === 'large') { className = 'card card--v2 card--layout card--large'; } else if (state === 'small') { className = 'card card--v2 card--layout card--small'; } let card = document.createElement('div'); let card__image = document.createElement('div'); let card__image__top = document.createElement('div'); let card__image__bottom = document.createElement('div'); let h3 = document.createElement('h3'); let h3__a = document.createElement('a'); let p = document.createElement('p'); let svgLeft = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); let useLeft = document.createElementNS('http://www.w3.org/2000/svg', 'use'); let svgRight = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); let useRight = document.createElementNS('http://www.w3.org/2000/svg', 'use'); useLeft.setAttribute('href', '#svg--left'); useRight.setAttribute('href', '#svg--right'); svgLeft.setAttribute('class', 'button--svg button--left hide'); svgRight.setAttribute('class', 'button--svg button--right hide'); svgLeft.appendChild(useLeft); svgRight.appendChild(useRight); card.className = className; card__image.className = 'card__image carousel'; card__image__top.className = 'card__image__top'; card__image__bottom.className = 'card__image__bottom'; h3__a.innerHTML = data.name.split(/\s+/).slice(0, 4).join(' '); h3__a.setAttribute('href', `/coffeeShops/${data._id}`); p.innerHTML = `${data.description.slice(0, 50)}...`; h3.appendChild(h3__a); card__image__top.appendChild(h3); card__image__bottom.appendChild(p); card__image.appendChild(card__image__top); card__image.appendChild(card__image__bottom); card__image.appendChild(svgLeft); card__image.appendChild(svgRight); card.appendChild(card__image); container100.appendChild(card); setImages(card__image, data.images, colWidth, data._id); if (data.images.length > 1) { display([svgLeft, svgRight]); } return; }
JavaScript
function changeIndexLeft(images) { let index = 0; for (let i = 0; i < images.length; i++) { if (active(images[i])) index = i; } for (let i = 0; i < images.length; i++) { if (index === 0 && i === index) { images[i].classList.toggle('active'); images[images.length - 1].classList.toggle('active'); } else if (i === index && index !== 0) { images[i].classList.toggle('active'); images[i - 1].classList.toggle('active'); } } setupBlocks(); }
function changeIndexLeft(images) { let index = 0; for (let i = 0; i < images.length; i++) { if (active(images[i])) index = i; } for (let i = 0; i < images.length; i++) { if (index === 0 && i === index) { images[i].classList.toggle('active'); images[images.length - 1].classList.toggle('active'); } else if (i === index && index !== 0) { images[i].classList.toggle('active'); images[i - 1].classList.toggle('active'); } } setupBlocks(); }
JavaScript
function changeIndexRight(images) { // coffeeShops.forEach((img, i) => img.style.display = obj.num === i ? 'block' : 'none'); let index = 0; for (let i = 0; i < images.length; i++) { if (active(images[i])) index = i; } for (let i = 0; i < images.length; i++) { if (index === images.length - 1 && i === index) { images[i].classList.toggle('active'); images[0].classList.toggle('active'); } else if (i === index && index !== images.length - 1) { images[i].classList.toggle('active'); images[i + 1].classList.toggle('active'); } } setupBlocks(); }
function changeIndexRight(images) { // coffeeShops.forEach((img, i) => img.style.display = obj.num === i ? 'block' : 'none'); let index = 0; for (let i = 0; i < images.length; i++) { if (active(images[i])) index = i; } for (let i = 0; i < images.length; i++) { if (index === images.length - 1 && i === index) { images[i].classList.toggle('active'); images[0].classList.toggle('active'); } else if (i === index && index !== images.length - 1) { images[i].classList.toggle('active'); images[i + 1].classList.toggle('active'); } } setupBlocks(); }
JavaScript
function display(nodelist) { for (let i = 0; i < nodelist.length; i++) { nodelist[i].classList.remove('hide'); } }
function display(nodelist) { for (let i = 0; i < nodelist.length; i++) { nodelist[i].classList.remove('hide'); } }
JavaScript
function carousel() { const carousels = document.querySelectorAll('.carousel'); for (let i = 0; i < carousels.length; i++) { const images = carousels[i].querySelectorAll('.carousel__image'); if (images.length > 1) { changePicture(carousels[i], images); const svgs = carousels[i].querySelectorAll('.button--svg'); display(svgs); } } return; }
function carousel() { const carousels = document.querySelectorAll('.carousel'); for (let i = 0; i < carousels.length; i++) { const images = carousels[i].querySelectorAll('.carousel__image'); if (images.length > 1) { changePicture(carousels[i], images); const svgs = carousels[i].querySelectorAll('.button--svg'); display(svgs); } } return; }
JavaScript
function loadImages(images) { const colWidth = document.querySelector('.reviews').offsetWidth; const colHeight = document.querySelector('.reviews').offsetHeight; const pixelRatio = window.devicePixelRatio || 1.0; let str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,c_fill,w_${Math.round( colWidth * pixelRatio )},h_${Math.round(colHeight * pixelRatio)}/coffeeShops`; for (let i = 0; i < images.length; i++) { images[i].src = `${str}/${images[i].dataset.src}`; } }
function loadImages(images) { const colWidth = document.querySelector('.reviews').offsetWidth; const colHeight = document.querySelector('.reviews').offsetHeight; const pixelRatio = window.devicePixelRatio || 1.0; let str = `https://res.cloudinary.com/christianjosuebt/image/upload/q_auto,f_auto,fl_lossy,c_fill,w_${Math.round( colWidth * pixelRatio )},h_${Math.round(colHeight * pixelRatio)}/coffeeShops`; for (let i = 0; i < images.length; i++) { images[i].src = `${str}/${images[i].dataset.src}`; } }
JavaScript
function changeIndexLeft(images, texts, top, bottom, stars) { let index = 0; let items = []; if (images.length !== 0) items.push(images); if (texts.length !== 0) items.push(texts); if (top.length !== 0) items.push(top); if (bottom.length !== 0) items.push(bottom); if (stars.length !== 0) items.push(stars); for (let i = 0; i < items[0].length; i++) { if (active(items[0][i])) { index = i; break; } } for (let i = 0; i < items[0].length; i++) { if (index === 0 && i === index) { for (let j = 0; j < items.length; j++) { items[j][i].classList.toggle('active'); items[j][items[0].length - 1].classList.toggle('active'); } } else if (i === index && index !== 0) { for (let j = 0; j < items.length; j++) { items[j][i].classList.toggle('active'); items[j][i - 1].classList.toggle('active'); } } } }
function changeIndexLeft(images, texts, top, bottom, stars) { let index = 0; let items = []; if (images.length !== 0) items.push(images); if (texts.length !== 0) items.push(texts); if (top.length !== 0) items.push(top); if (bottom.length !== 0) items.push(bottom); if (stars.length !== 0) items.push(stars); for (let i = 0; i < items[0].length; i++) { if (active(items[0][i])) { index = i; break; } } for (let i = 0; i < items[0].length; i++) { if (index === 0 && i === index) { for (let j = 0; j < items.length; j++) { items[j][i].classList.toggle('active'); items[j][items[0].length - 1].classList.toggle('active'); } } else if (i === index && index !== 0) { for (let j = 0; j < items.length; j++) { items[j][i].classList.toggle('active'); items[j][i - 1].classList.toggle('active'); } } } }
JavaScript
function changeIndexRight(images, texts, top, bottom, stars) { // coffeeShops.forEach((img, i) => img.style.display = obj.num === i ? 'block' : 'none'); let index = 0; let items = []; if (images.length !== 0) items.push(images); if (texts.length !== 0) items.push(texts); if (top.length !== 0) items.push(top); if (bottom.length !== 0) items.push(bottom); if (stars.length !== 0) items.push(stars); for (let i = 0; i < items[0].length; i++) { if (active(items[0][i])) { index = i; break; } } for (let i = 0; i < items[0].length; i++) { if (index === items[0].length - 1 && i === index) { for (let j = 0; j < items.length; j++) { items[j][i].classList.toggle('active'); items[j][0].classList.toggle('active'); } } else if (i === index && index !== items[0].length - 1) { for (let j = 0; j < items.length; j++) { items[j][i].classList.toggle('active'); items[j][i + 1].classList.toggle('active'); } } } }
function changeIndexRight(images, texts, top, bottom, stars) { // coffeeShops.forEach((img, i) => img.style.display = obj.num === i ? 'block' : 'none'); let index = 0; let items = []; if (images.length !== 0) items.push(images); if (texts.length !== 0) items.push(texts); if (top.length !== 0) items.push(top); if (bottom.length !== 0) items.push(bottom); if (stars.length !== 0) items.push(stars); for (let i = 0; i < items[0].length; i++) { if (active(items[0][i])) { index = i; break; } } for (let i = 0; i < items[0].length; i++) { if (index === items[0].length - 1 && i === index) { for (let j = 0; j < items.length; j++) { items[j][i].classList.toggle('active'); items[j][0].classList.toggle('active'); } } else if (i === index && index !== items[0].length - 1) { for (let j = 0; j < items.length; j++) { items[j][i].classList.toggle('active'); items[j][i + 1].classList.toggle('active'); } } } }
JavaScript
function carousel() { const carousels = document.querySelectorAll('.carousel'); for (let i = 0; i < carousels.length; i++) { const images = carousels[i].querySelectorAll('.carousel__image'); const texts = carousels[i].querySelectorAll('.carousel__text'); const top = carousels[i].querySelectorAll('.carousel__top'); const bottom = carousels[i].querySelectorAll('.carousel__bottom'); const stars = carousels[i].querySelectorAll('.stars--parent'); if ( images.length > 1 || texts.length > 1 || top.length > 1 || bottom.length > 1 || images.length > 1 ) { changePicture(carousels[i], images, texts, top, bottom, stars); const svgs = carousels[i].querySelectorAll('.button--svg'); if (svgs.length !== 0) display(svgs); } } const linked = document.querySelectorAll('.carousel--linked'); let images = []; let texts = []; let top = []; let bottom = []; let stars = []; if (linked.length > 1) { for (let i = 0; i < linked.length; i++) { images.push.apply( images, Array.from(linked[i].querySelectorAll('.carousel__image')) ); texts.push.apply( texts, Array.from(linked[i].querySelectorAll('.carousel__text')) ); top.push.apply( top, Array.from(linked[i].querySelectorAll('.carousel__top')) ); bottom.push.apply( bottom, Array.from(linked[i].querySelectorAll('.carousel__bottom')) ); stars.push.apply( stars, Array.from(linked[i].querySelectorAll('.stars--parent')) ); } } if ( images.length > 1 || texts.length > 1 || top.length > 1 || bottom.length > 1 || images.length > 1 ) { changePictures(linked, images, texts, top, bottom, stars); for (let i = 0; i < linked.length; i++) { const svgs = linked[i].querySelectorAll('.button--svg'); if (svgs.length !== 0) display(svgs); } } return; }
function carousel() { const carousels = document.querySelectorAll('.carousel'); for (let i = 0; i < carousels.length; i++) { const images = carousels[i].querySelectorAll('.carousel__image'); const texts = carousels[i].querySelectorAll('.carousel__text'); const top = carousels[i].querySelectorAll('.carousel__top'); const bottom = carousels[i].querySelectorAll('.carousel__bottom'); const stars = carousels[i].querySelectorAll('.stars--parent'); if ( images.length > 1 || texts.length > 1 || top.length > 1 || bottom.length > 1 || images.length > 1 ) { changePicture(carousels[i], images, texts, top, bottom, stars); const svgs = carousels[i].querySelectorAll('.button--svg'); if (svgs.length !== 0) display(svgs); } } const linked = document.querySelectorAll('.carousel--linked'); let images = []; let texts = []; let top = []; let bottom = []; let stars = []; if (linked.length > 1) { for (let i = 0; i < linked.length; i++) { images.push.apply( images, Array.from(linked[i].querySelectorAll('.carousel__image')) ); texts.push.apply( texts, Array.from(linked[i].querySelectorAll('.carousel__text')) ); top.push.apply( top, Array.from(linked[i].querySelectorAll('.carousel__top')) ); bottom.push.apply( bottom, Array.from(linked[i].querySelectorAll('.carousel__bottom')) ); stars.push.apply( stars, Array.from(linked[i].querySelectorAll('.stars--parent')) ); } } if ( images.length > 1 || texts.length > 1 || top.length > 1 || bottom.length > 1 || images.length > 1 ) { changePictures(linked, images, texts, top, bottom, stars); for (let i = 0; i < linked.length; i++) { const svgs = linked[i].querySelectorAll('.button--svg'); if (svgs.length !== 0) display(svgs); } } return; }
JavaScript
toggleOne(song, cb = null) { http.post('interaction/like', { id: song.id }, data => { song.liked = data.liked; if (data.liked) { this.add(song); } else { this.remove(song); } if (cb) { cb(); } }); }
toggleOne(song, cb = null) { http.post('interaction/like', { id: song.id }, data => { song.liked = data.liked; if (data.liked) { this.add(song); } else { this.remove(song); } if (cb) { cb(); } }); }
JavaScript
like(songs, cb = null) { this.state.songs = _.union(this.state.songs, songs); http.post('interaction/batch/like', { ids: _.pluck(songs, 'id') }, data => { _.each(songs, song => song.liked = true); if (cb) { cb(); } }); }
like(songs, cb = null) { this.state.songs = _.union(this.state.songs, songs); http.post('interaction/batch/like', { ids: _.pluck(songs, 'id') }, data => { _.each(songs, song => song.liked = true); if (cb) { cb(); } }); }
JavaScript
unlike(songs, cb = null) { this.state.songs = _.difference(this.state.songs, songs); http.post('interaction/batch/unlike', { ids: _.pluck(songs, 'id') }, data => { _.each(songs, song => song.liked = false); if (cb) { cb(); } }); }
unlike(songs, cb = null) { this.state.songs = _.difference(this.state.songs, songs); http.post('interaction/batch/unlike', { ids: _.pluck(songs, 'id') }, data => { _.each(songs, song => song.liked = false); if (cb) { cb(); } }); }
JavaScript
init(data = null) { if (!data) { data = sharedStore.state; } this.state.users = data.users; this.state.current = data.currentUser; // Set the avatar for each of the users… _.each(this.state.users, this.setAvatar); // …and the current user as well. this.setAvatar(); }
init(data = null) { if (!data) { data = sharedStore.state; } this.state.users = data.users; this.state.current = data.currentUser; // Set the avatar for each of the users… _.each(this.state.users, this.setAvatar); // …and the current user as well. this.setAvatar(); }
JavaScript
current(user = null) { if (user) { this.state.current = user; } return this.state.current; }
current(user = null) { if (user) { this.state.current = user; } return this.state.current; }
JavaScript
updateProfile(password = null, cb = null) { http.put('me', { password, name: this.current().name, email: this.current().email }, data => { this.setAvatar(); if (cb) { cb(); } } ); }
updateProfile(password = null, cb = null) { http.put('me', { password, name: this.current().name, email: this.current().email }, data => { this.setAvatar(); if (cb) { cb(); } } ); }
JavaScript
store(name, email, password, cb = null) { http.post('user', { name, email, password }, user => { this.setAvatar(user); this.state.users.push(user); if (cb) { cb(); } }); }
store(name, email, password, cb = null) { http.post('user', { name, email, password }, user => { this.setAvatar(user); this.state.users.push(user); if (cb) { cb(); } }); }
JavaScript
secondsToHis(d) { d = parseInt(d); var s = d%60; if (s < 10) { s = '0' + s; } var i = Math.floor((d/60)%60); if (i < 10) { i = '0' + i; } var h = Math.floor(d/3600); if (h < 10) { h = '0' + h; } return (h === '00' ? '' : h + ':') + i + ':' + s; }
secondsToHis(d) { d = parseInt(d); var s = d%60; if (s < 10) { s = '0' + s; } var i = Math.floor((d/60)%60); if (i < 10) { i = '0' + i; } var h = Math.floor(d/3600); if (h < 10) { h = '0' + h; } return (h === '00' ? '' : h + ':') + i + ':' + s; }
JavaScript
queue(songs, replace = false, toTop = false) { if (!Array.isArray(songs)) { songs = [songs]; } if (replace) { this.state.songs = songs; } else { if (toTop) { this.state.songs = _.union(songs, this.state.songs); } else { this.state.songs = _.union(this.state.songs, songs); } } }
queue(songs, replace = false, toTop = false) { if (!Array.isArray(songs)) { songs = [songs]; } if (replace) { this.state.songs = songs; } else { if (toTop) { this.state.songs = _.union(songs, this.state.songs); } else { this.state.songs = _.union(this.state.songs, songs); } } }
JavaScript
current(song = null) { if (song) { this.state.current = song; } return this.state.current; }
current(song = null) { if (song) { this.state.current = song; } return this.state.current; }
JavaScript
init(artists) { this.artists = artists; // Traverse through the artists array and add their albums into our master album list. this.state.albums = _.reduce(artists, (albums, artist) => { // While we're doing so, for each album, we get its length // and keep a back reference to the artist too. _.each(artist.albums, album => { album.artist = artist; this.getLength(album); }); return albums.concat(artist.albums); }, []); // Then we init the song store. songStore.init(this.state.albums); }
init(artists) { this.artists = artists; // Traverse through the artists array and add their albums into our master album list. this.state.albums = _.reduce(artists, (albums, artist) => { // While we're doing so, for each album, we get its length // and keep a back reference to the artist too. _.each(artist.albums, album => { album.artist = artist; this.getLength(album); }); return albums.concat(artist.albums); }, []); // Then we init the song store. songStore.init(this.state.albums); }
JavaScript
init(artists = null) { this.state.artists = artists ? artists: sharedStore.state.artists; // Init the album store. This must be called prior to the next logic, // because we're using some data from the album store later. albumStore.init(this.state.artists); // Traverse through artists array to get the cover and number of songs for each. _.each(this.state.artists, artist => { this.getCover(artist); artist.songCount = _.reduce(artist.albums, (count, album) => count + album.songs.length, 0); }); }
init(artists = null) { this.state.artists = artists ? artists: sharedStore.state.artists; // Init the album store. This must be called prior to the next logic, // because we're using some data from the album store later. albumStore.init(this.state.artists); // Traverse through artists array to get the cover and number of songs for each. _.each(this.state.artists, artist => { this.getCover(artist); artist.songCount = _.reduce(artist.albums, (count, album) => count + album.songs.length, 0); }); }
JavaScript
init(user = null) { if (!user) { user = userStore.current(); } this.storeKey = `preferences_${user.id}`; _.extend(this.state, ls.get(this.storeKey, this.state)); }
init(user = null) { if (!user) { user = userStore.current(); } this.storeKey = `preferences_${user.id}`; _.extend(this.state, ls.get(this.storeKey, this.state)); }
JavaScript
init(app) { this.app = app; plyr.setup({ controls: [], }); this.player = $('.player')[0].plyr; this.$volumeInput = $('#volumeRange'); /** * Listen to 'error' event on the audio player and play the next song if any. * We don't care about network error capturing here, since every play() call * comes with a POST to api/interaction/play. If the user is not logged in anymore, * this call will result in a 401, following by a redirection to our login page. */ this.player.media.addEventListener('error', e => { this.playNext(); }); /** * Listen to 'input' event on the volume range control. * When user drags the volume control, this event will be triggered, and we * update the volume on the plyr object. */ this.$volumeInput.on('input', e => { this.setVolume($(e.target).val()); }); // Listen to 'ended' event on the audio player and play the next song in the queue. this.player.media.addEventListener('ended', e => { if (preferenceStore.get('repeatMode') === 'REPEAT_ONE') { this.player.restart(); this.player.play(); return; } this.playNext(); }); // On init, set the volume to the value found in the local storage. this.setVolume(preferenceStore.get('volume')); }
init(app) { this.app = app; plyr.setup({ controls: [], }); this.player = $('.player')[0].plyr; this.$volumeInput = $('#volumeRange'); /** * Listen to 'error' event on the audio player and play the next song if any. * We don't care about network error capturing here, since every play() call * comes with a POST to api/interaction/play. If the user is not logged in anymore, * this call will result in a 401, following by a redirection to our login page. */ this.player.media.addEventListener('error', e => { this.playNext(); }); /** * Listen to 'input' event on the volume range control. * When user drags the volume control, this event will be triggered, and we * update the volume on the plyr object. */ this.$volumeInput.on('input', e => { this.setVolume($(e.target).val()); }); // Listen to 'ended' event on the audio player and play the next song in the queue. this.player.media.addEventListener('ended', e => { if (preferenceStore.get('repeatMode') === 'REPEAT_ONE') { this.player.restart(); this.player.play(); return; } this.playNext(); }); // On init, set the volume to the value found in the local storage. this.setVolume(preferenceStore.get('volume')); }
JavaScript
play(song) { if (!song) { return; } // Set the song as the current song queueStore.current(song); this.app.$broadcast('song:play', song); $('title').text(`${song.title} ♫ Koel`); this.player.source(`/api/${song.id}/play`); this.player.play(); // Register the play count to the server songStore.registerPlay(song); // Show the notification if we're allowed to if (!window.Notification || !preferenceStore.get('notify')) { return; } var notification = new Notification(`♫ ${song.title}`, { icon: song.album.cover, body: `${song.album.name} – ${song.album.artist.name}` }); window.setTimeout(() => { notification.close(); }, 5000); }
play(song) { if (!song) { return; } // Set the song as the current song queueStore.current(song); this.app.$broadcast('song:play', song); $('title').text(`${song.title} ♫ Koel`); this.player.source(`/api/${song.id}/play`); this.player.play(); // Register the play count to the server songStore.registerPlay(song); // Show the notification if we're allowed to if (!window.Notification || !preferenceStore.get('notify')) { return; } var notification = new Notification(`♫ ${song.title}`, { icon: song.album.cover, body: `${song.album.name} – ${song.album.artist.name}` }); window.setTimeout(() => { notification.close(); }, 5000); }
JavaScript
nextSong() { var next = queueStore.getNextSong(); if (next) { return next; } if (preferenceStore.get('repeatMode') === 'REPEAT_ALL') { return queueStore.first(); } }
nextSong() { var next = queueStore.getNextSong(); if (next) { return next; } if (preferenceStore.get('repeatMode') === 'REPEAT_ALL') { return queueStore.first(); } }
JavaScript
prevSong() { var prev = queueStore.getPrevSong(); if (prev) { return prev; } if (preferenceStore.get('repeatMode') === 'REPEAT_ALL') { return queueStore.last(); } }
prevSong() { var prev = queueStore.getPrevSong(); if (prev) { return prev; } if (preferenceStore.get('repeatMode') === 'REPEAT_ALL') { return queueStore.last(); } }
JavaScript
changeRepeatMode() { var i = this.repeatModes.indexOf(preferenceStore.get('repeatMode')) + 1; if (i >= this.repeatModes.length) { i = 0; } preferenceStore.set('repeatMode', this.repeatModes[i]); }
changeRepeatMode() { var i = this.repeatModes.indexOf(preferenceStore.get('repeatMode')) + 1; if (i >= this.repeatModes.length) { i = 0; } preferenceStore.set('repeatMode', this.repeatModes[i]); }
JavaScript
playPrev() { // If the song's duration is greater than 5 seconds and we've passed 5 seconds into it // restart playing instead. if (this.player.media.currentTime > 5 && this.player.media.duration > 5) { this.player.seek(0); return; } var prev = this.prevSong(); if (!prev && preferenceStore.get('repeatMode') === 'NO_REPEAT') { this.stop(); return; } this.play(prev); }
playPrev() { // If the song's duration is greater than 5 seconds and we've passed 5 seconds into it // restart playing instead. if (this.player.media.currentTime > 5 && this.player.media.duration > 5) { this.player.seek(0); return; } var prev = this.prevSong(); if (!prev && preferenceStore.get('repeatMode') === 'NO_REPEAT') { this.stop(); return; } this.play(prev); }
JavaScript
playNext() { var next = this.nextSong(); if (!next && preferenceStore.get('repeatMode') === 'NO_REPEAT') { // Nothing lasts forever, even cold November rain. this.stop(); return; } this.play(next); }
playNext() { var next = this.nextSong(); if (!next && preferenceStore.get('repeatMode') === 'NO_REPEAT') { // Nothing lasts forever, even cold November rain. this.stop(); return; } this.play(next); }
JavaScript
queueAndPlay(songs = null, shuffle = false) { if (!songs) { songs = songStore.all(); } if (!songs.length) { return; } if (shuffle) { songs = _.shuffle(songs); } queueStore.clear(); queueStore.queue(songs, true); this.app.loadMainView('queue'); // Wrap this inside a nextTick() to wait for the DOM to complete updating // and then play the first song in the queue. Vue.nextTick(() => this.play(queueStore.first())); }
queueAndPlay(songs = null, shuffle = false) { if (!songs) { songs = songStore.all(); } if (!songs.length) { return; } if (shuffle) { songs = _.shuffle(songs); } queueStore.clear(); queueStore.queue(songs, true); this.app.loadMainView('queue'); // Wrap this inside a nextTick() to wait for the DOM to complete updating // and then play the first song in the queue. Vue.nextTick(() => this.play(queueStore.first())); }
JavaScript
playFirstInQueue() { if (!queueStore.all().length) { this.queueAndPlay(); return; } this.play(queueStore.first()); }
playFirstInQueue() { if (!queueStore.all().length) { this.queueAndPlay(); return; } this.play(queueStore.first()); }
JavaScript
init(albums, interactions = null) { this.albums = albums; this.state.interactions = interactions ? interactions : sharedStore.state.interactions; // Iterate through the albums. With each, add its songs into our master song list. this.state.songs = _.reduce(albums, (songs, album) => { // While doing so, we populate some other information into the songs as well. _.each(album.songs, song => { song.fmtLength = utils.secondsToHis(song.length); // Keep a back reference to the album song.album = album; this.setInteractionStats(song); if (song.liked) { favoriteStore.add(song); } }); return songs.concat(album.songs); }, []); }
init(albums, interactions = null) { this.albums = albums; this.state.interactions = interactions ? interactions : sharedStore.state.interactions; // Iterate through the albums. With each, add its songs into our master song list. this.state.songs = _.reduce(albums, (songs, album) => { // While doing so, we populate some other information into the songs as well. _.each(album.songs, song => { song.fmtLength = utils.secondsToHis(song.length); // Keep a back reference to the album song.album = album; this.setInteractionStats(song); if (song.liked) { favoriteStore.add(song); } }); return songs.concat(album.songs); }, []); }
JavaScript
function breakcmd(cmd) { cmd = cmd.trimLeft(); var m = /\s/.exec(cmd); if (m === null) return [cmd, '']; return [cmd.slice(0, m.index), cmd.slice(m.index).trimLeft()]; }
function breakcmd(cmd) { cmd = cmd.trimLeft(); var m = /\s/.exec(cmd); if (m === null) return [cmd, '']; return [cmd.slice(0, m.index), cmd.slice(m.index).trimLeft()]; }
JavaScript
function rescueEMFILE(callback) { // Output a warning, but only at most every 5 seconds. var now = new Date(); if (now - lastEMFILEWarning > 5000) { console.error('(node) Hit max file limit. Increase "ulimit -n"'); lastEMFILEWarning = now; } if (dummyFD) { close(dummyFD); dummyFD = null; callback(); getDummyFD(); } }
function rescueEMFILE(callback) { // Output a warning, but only at most every 5 seconds. var now = new Date(); if (now - lastEMFILEWarning > 5000) { console.error('(node) Hit max file limit. Increase "ulimit -n"'); lastEMFILEWarning = now; } if (dummyFD) { close(dummyFD); dummyFD = null; callback(); getDummyFD(); } }
JavaScript
function f(s) { eval(s); return function(a) { with({}) {}; // repel JägerMonkey eval(a); return b; }; }
function f(s) { eval(s); return function(a) { with({}) {}; // repel JägerMonkey eval(a); return b; }; }
JavaScript
function stringToFlags(flag) { // Only mess with strings if (typeof flag !== 'string') { return flag; } switch (flag) { case 'r': return constants.O_RDONLY; case 'r+': return constants.O_RDWR; case 'w': return constants.O_CREAT | constants.O_TRUNC | constants.O_WRONLY; case 'w+': return constants.O_CREAT | constants.O_TRUNC | constants.O_RDWR; case 'a': return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY; case 'a+': return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR; default: throw new Error('Unknown file open flag: ' + flag); } }
function stringToFlags(flag) { // Only mess with strings if (typeof flag !== 'string') { return flag; } switch (flag) { case 'r': return constants.O_RDONLY; case 'r+': return constants.O_RDWR; case 'w': return constants.O_CREAT | constants.O_TRUNC | constants.O_WRONLY; case 'w+': return constants.O_CREAT | constants.O_TRUNC | constants.O_RDWR; case 'a': return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY; case 'a+': return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR; default: throw new Error('Unknown file open flag: ' + flag); } }
JavaScript
function toUnixTimestamp(time) { if (typeof time == 'number') { return time; } if (time instanceof Date) { // convert to 123.456 UNIX timestamp return time.getTime() / 1000; } throw new Error("Cannot parse time: " + time); }
function toUnixTimestamp(time) { if (typeof time == 'number') { return time; } if (time instanceof Date) { // convert to 123.456 UNIX timestamp return time.getTime() / 1000; } throw new Error("Cannot parse time: " + time); }
JavaScript
function testWeird(str, printedAs, arg, result) { var fun = new Function('x', str); // this is lame and doesn't normalize whitespace so if an assert fails // here, see if its just whitespace and fix the caller assertEq(fun.toSource(), '(function anonymous(x) {' + printedAs + '})'); test(printedAs, arg, result); }
function testWeird(str, printedAs, arg, result) { var fun = new Function('x', str); // this is lame and doesn't normalize whitespace so if an assert fails // here, see if its just whitespace and fix the caller assertEq(fun.toSource(), '(function anonymous(x) {' + printedAs + '})'); test(printedAs, arg, result); }
JavaScript
function doTest(name, val1, val2, comparator) { if (!comparator) comparator = standardComparator; var a = val1; var b = {value: val2}; var rv = o[name].call(o, a, b); do_check_true(comparator(rv, val2)); do_check_true(comparator(val1, b.value)); }
function doTest(name, val1, val2, comparator) { if (!comparator) comparator = standardComparator; var a = val1; var b = {value: val2}; var rv = o[name].call(o, a, b); do_check_true(comparator(rv, val2)); do_check_true(comparator(val1, b.value)); }
JavaScript
function doIs2Test(name, val1, val1Size, val1IID, val2, val2Size, val2IID) { var a = val1; var aSize = val1Size; var aIID = val1IID; var b = {value: val2}; var bSize = {value: val2Size}; var bIID = {value: val2IID}; var rvSize = {}; var rvIID = {}; var rv = o[name].call(o, aSize, aIID, a, bSize, bIID, b, rvSize, rvIID); do_check_true(arrayComparator(interfaceComparator)(rv, val2)); do_check_true(standardComparator(rvSize.value, val2Size)); do_check_true(dotEqualsComparator(rvIID.value, val2IID)); do_check_true(arrayComparator(interfaceComparator)(val1, b.value)); do_check_true(standardComparator(val1Size, bSize.value)); do_check_true(dotEqualsComparator(val1IID, bIID.value)); }
function doIs2Test(name, val1, val1Size, val1IID, val2, val2Size, val2IID) { var a = val1; var aSize = val1Size; var aIID = val1IID; var b = {value: val2}; var bSize = {value: val2Size}; var bIID = {value: val2IID}; var rvSize = {}; var rvIID = {}; var rv = o[name].call(o, aSize, aIID, a, bSize, bIID, b, rvSize, rvIID); do_check_true(arrayComparator(interfaceComparator)(rv, val2)); do_check_true(standardComparator(rvSize.value, val2Size)); do_check_true(dotEqualsComparator(rvIID.value, val2IID)); do_check_true(arrayComparator(interfaceComparator)(val1, b.value)); do_check_true(standardComparator(val1Size, bSize.value)); do_check_true(dotEqualsComparator(val1IID, bIID.value)); }
JavaScript
function doTypedArrayMismatchTest(name, val1, val1Size, val2, val2Size) { var comparator = arrayComparator(standardComparator); var error = false; try { doIsTest(name, val1, val1Size, val2, val2Size, comparator); // An exception was not thrown as would have been expected. do_check_true(false); } catch (e) { // An exception was thrown as expected. do_check_true(true); } }
function doTypedArrayMismatchTest(name, val1, val1Size, val2, val2Size) { var comparator = arrayComparator(standardComparator); var error = false; try { doIsTest(name, val1, val1Size, val2, val2Size, comparator); // An exception was not thrown as would have been expected. do_check_true(false); } catch (e) { // An exception was thrown as expected. do_check_true(true); } }
JavaScript
function doTestWorkaround(name, val1) { var a = val1; var b = {value: ""}; o[name].call(o, a, b); do_check_eq(val1, b.value); }
function doTestWorkaround(name, val1) { var a = val1; var b = {value: ""}; o[name].call(o, a, b); do_check_eq(val1, b.value); }
JavaScript
async function subscription(register, publicKey) { let isSubscribed = false; let swRegistration = null; swRegistration = register; try { const subscription = await swRegistration.pushManager.getSubscription(); isSubscribed = !(subscription === null); if (isSubscribed) { console.log('User is subscribed'); } else { console.log('User subscribe'); try { const subscriptionData = await register.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: publicKey, }); console.log('User is subscribed'); await fetch(SUBSCRIBE_API, { method: 'POST', body: JSON.stringify(subscriptionData), headers: { 'Content-Type': 'application/json', }, }); isSubscribed = true; // Thanks for subscribing console.log('Thanks for subscribing!'); // notificationComponent(NOTIFICATION_MESSAGE_SUBSCRIBING); } catch (err) { console.log(err); } } } catch (err) { console.log(err); } }
async function subscription(register, publicKey) { let isSubscribed = false; let swRegistration = null; swRegistration = register; try { const subscription = await swRegistration.pushManager.getSubscription(); isSubscribed = !(subscription === null); if (isSubscribed) { console.log('User is subscribed'); } else { console.log('User subscribe'); try { const subscriptionData = await register.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: publicKey, }); console.log('User is subscribed'); await fetch(SUBSCRIBE_API, { method: 'POST', body: JSON.stringify(subscriptionData), headers: { 'Content-Type': 'application/json', }, }); isSubscribed = true; // Thanks for subscribing console.log('Thanks for subscribing!'); // notificationComponent(NOTIFICATION_MESSAGE_SUBSCRIBING); } catch (err) { console.log(err); } } } catch (err) { console.log(err); } }
JavaScript
function urlBase64ToUint8Array(base64String) { const padding = '='.repeat((4 - (base64String.length % 4)) % 4); const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; }
function urlBase64ToUint8Array(base64String) { const padding = '='.repeat((4 - (base64String.length % 4)) % 4); const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; }
JavaScript
function parseJSON(response) { if (response.status === 204 || response.status === 205) { return null; } if (response.postsTotal) { return response.json().then(json => { const data = { posts: json, postsTotal: Number(response.postsTotal), }; return data; }); } return response.json(); }
function parseJSON(response) { if (response.status === 204 || response.status === 205) { return null; } if (response.postsTotal) { return response.json().then(json => { const data = { posts: json, postsTotal: Number(response.postsTotal), }; return data; }); } return response.json(); }
JavaScript
function buildGetService(connectDbPromise, mongooseModel, options) { return function(id) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { let args = [id]; if(options && _.isString(options.select)) { args.push(options.select) } args.push((err, object) => { if (err) { reject(err); } else if(object === null) { resolve(null); } else { resolve(object._doc); } }); mongooseModel.findById.apply(mongooseModel,args); }); }); } }
function buildGetService(connectDbPromise, mongooseModel, options) { return function(id) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { let args = [id]; if(options && _.isString(options.select)) { args.push(options.select) } args.push((err, object) => { if (err) { reject(err); } else if(object === null) { resolve(null); } else { resolve(object._doc); } }); mongooseModel.findById.apply(mongooseModel,args); }); }); } }
JavaScript
function buildSearchService(connectDbPromise, mongooseModel, options) { return function(query, limit, offset, sort) { query = query || ""; limit = Number.parseInt(limit); offset = Number.parseInt(offset); sort = sort || ""; return new Promise((resolve, reject) => { connectDbPromise().then(() => { let searchable = options.searchable; let select = options.select || ''; let meta = { // the meta properties are added to the response limit: limit, offset: offset, query: query, sort: sort }; // create meta properties for this request let regex = new RegExp(query, 'ig'); let q = null; if(_.isString(query)) { if(_.isArray(searchable)) { q = query && query.trim().length ? // create a regex query to match the ff props {$or: searchable.map((cur) => { return {[cur]: regex}; })} : {}; } else { q = {}; } } let promisedQuery = mongooseModel.find(q) .select(select) // select fields .limit(meta.limit)// set pagination limit .skip(meta.offset); //set how many items to skip if (sort.length > 0) { promisedQuery.sort(sort); } promisedQuery.exec(); let promisedCount = mongooseModel.countDocuments(q).exec(); Promise.all([promisedCount, promisedQuery])// execute both asynchronously .then(([total, objects]) => { // when both responses are available meta.total = total; // set the total count into meta resolve({ meta: meta, objects: objects.map((o) => o._doc) }); }, (error) => { reject(error); }); }); }); } }
function buildSearchService(connectDbPromise, mongooseModel, options) { return function(query, limit, offset, sort) { query = query || ""; limit = Number.parseInt(limit); offset = Number.parseInt(offset); sort = sort || ""; return new Promise((resolve, reject) => { connectDbPromise().then(() => { let searchable = options.searchable; let select = options.select || ''; let meta = { // the meta properties are added to the response limit: limit, offset: offset, query: query, sort: sort }; // create meta properties for this request let regex = new RegExp(query, 'ig'); let q = null; if(_.isString(query)) { if(_.isArray(searchable)) { q = query && query.trim().length ? // create a regex query to match the ff props {$or: searchable.map((cur) => { return {[cur]: regex}; })} : {}; } else { q = {}; } } let promisedQuery = mongooseModel.find(q) .select(select) // select fields .limit(meta.limit)// set pagination limit .skip(meta.offset); //set how many items to skip if (sort.length > 0) { promisedQuery.sort(sort); } promisedQuery.exec(); let promisedCount = mongooseModel.countDocuments(q).exec(); Promise.all([promisedCount, promisedQuery])// execute both asynchronously .then(([total, objects]) => { // when both responses are available meta.total = total; // set the total count into meta resolve({ meta: meta, objects: objects.map((o) => o._doc) }); }, (error) => { reject(error); }); }); }); } }
JavaScript
function buildCreateService(connectDbPromise, mongooseModel) { return function(object) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { mongooseModel.create(object, (err, object) => { if (err) { reject(err); } else if(object === null) { resolve(null); } else { resolve(object._doc); } } ); }); }); } }
function buildCreateService(connectDbPromise, mongooseModel) { return function(object) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { mongooseModel.create(object, (err, object) => { if (err) { reject(err); } else if(object === null) { resolve(null); } else { resolve(object._doc); } } ); }); }); } }
JavaScript
function buildCreateManyService(connectDbPromise, mongooseModel) { return function(objects) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { mongooseModel.insertMany(objects, (err, objs) => { if (err) { reject(err); } else if(objs === null) { resolve(null); } else { resolve(objs.map((item) => { return item._doc; })); } } ); }); }); } }
function buildCreateManyService(connectDbPromise, mongooseModel) { return function(objects) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { mongooseModel.insertMany(objects, (err, objs) => { if (err) { reject(err); } else if(objs === null) { resolve(null); } else { resolve(objs.map((item) => { return item._doc; })); } } ); }); }); } }
JavaScript
function buildUpdateService(connectDbPromise, mongooseModel, options) { return function(id,object) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { let opts = { new: true }; if(options && _.isString(options.select)) { opts.select = options.select; } mongooseModel.findByIdAndUpdate(id, object, opts, (err, object) => { if (err) { reject(err); } else if(object === null) { resolve(null); } else { resolve(object._doc); } } ); }); }); } }
function buildUpdateService(connectDbPromise, mongooseModel, options) { return function(id,object) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { let opts = { new: true }; if(options && _.isString(options.select)) { opts.select = options.select; } mongooseModel.findByIdAndUpdate(id, object, opts, (err, object) => { if (err) { reject(err); } else if(object === null) { resolve(null); } else { resolve(object._doc); } } ); }); }); } }
JavaScript
function buildDeleteService(connectDbPromise, mongooseModel) { return function(id) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { mongooseModel.findByIdAndRemove(id, (err, object) => { if (err) { reject(err); } else if(object === null) { resolve(null); } else { resolve(object._doc); } } ); }); }); } }
function buildDeleteService(connectDbPromise, mongooseModel) { return function(id) { return new Promise((resolve, reject) => { connectDbPromise().then(() => { mongooseModel.findByIdAndRemove(id, (err, object) => { if (err) { reject(err); } else if(object === null) { resolve(null); } else { resolve(object._doc); } } ); }); }); } }
JavaScript
function cookie_gone_try_query(q) { console.log(q); var htmlNode = document.querySelector(q); if (htmlNode) { htmlNode.click(); return true; } }
function cookie_gone_try_query(q) { console.log(q); var htmlNode = document.querySelector(q); if (htmlNode) { htmlNode.click(); return true; } }
JavaScript
function cookie_gone_try_id(id) { console.log(id); var htmlnode = document.getElementById(id); if (htmlnode) { console.log('Found ID: ' + id); htmlnode.click(); return true; } }
function cookie_gone_try_id(id) { console.log(id); var htmlnode = document.getElementById(id); if (htmlnode) { console.log('Found ID: ' + id); htmlnode.click(); return true; } }
JavaScript
function cookie_gone_try_class(cls) { console.log(cls); var htmlnode = document.getElementsByClassName(cls); if (htmlnode.length) { console.log('Found Class: ' + cls); htmlnode[0].click(); return true; } }
function cookie_gone_try_class(cls) { console.log(cls); var htmlnode = document.getElementsByClassName(cls); if (htmlnode.length) { console.log('Found Class: ' + cls); htmlnode[0].click(); return true; } }
JavaScript
function remove_all_cookie_bars() { //Check all IDS and click them. console.log('Trying cookie ids'); for (var idIndex in cookie_btn_ids) { if (cookie_gone_try_id(cookie_btn_ids[idIndex])) return true; } //Check all the classes and click them. console.log('Trying cookie classes'); for (var clsIndex in cookie_btn_classes) { if (cookie_gone_try_class(cookie_btn_classes[clsIndex])) return true; } //Check all the queries (most expensive) console.log('Trying cookie queries'); //log(cookie_btn_queries); for (var queryIndex in cookie_btn_queries) { if (cookie_gone_try_query(cookie_btn_queries[queryIndex])) return true; } // Retry 4 times, make the delay longer on every call. if (cookie_attempt < 5) { setTimeout(remove_all_cookie_bars, cookie_timeout * cookie_attempt); } cookie_attempt++; return false; }
function remove_all_cookie_bars() { //Check all IDS and click them. console.log('Trying cookie ids'); for (var idIndex in cookie_btn_ids) { if (cookie_gone_try_id(cookie_btn_ids[idIndex])) return true; } //Check all the classes and click them. console.log('Trying cookie classes'); for (var clsIndex in cookie_btn_classes) { if (cookie_gone_try_class(cookie_btn_classes[clsIndex])) return true; } //Check all the queries (most expensive) console.log('Trying cookie queries'); //log(cookie_btn_queries); for (var queryIndex in cookie_btn_queries) { if (cookie_gone_try_query(cookie_btn_queries[queryIndex])) return true; } // Retry 4 times, make the delay longer on every call. if (cookie_attempt < 5) { setTimeout(remove_all_cookie_bars, cookie_timeout * cookie_attempt); } cookie_attempt++; return false; }
JavaScript
function collectSubNodes(parentNode) { // console.log(`There are ${parentNode.subNodes.length} sub-nodes of ${parentNode.label}`) parentNode.subNodes.forEach( childNode => { if (childNode.opened) { childNode.opened = false; hulls2Remove.push(childNode.id); collectSubNodes(childNode); } }); subNodes2Remove.push(parentNode.subNodes); // console.log(`${parentNode.label} has ${parentNode.subNodes} nodes to be removed`); }
function collectSubNodes(parentNode) { // console.log(`There are ${parentNode.subNodes.length} sub-nodes of ${parentNode.label}`) parentNode.subNodes.forEach( childNode => { if (childNode.opened) { childNode.opened = false; hulls2Remove.push(childNode.id); collectSubNodes(childNode); } }); subNodes2Remove.push(parentNode.subNodes); // console.log(`${parentNode.label} has ${parentNode.subNodes} nodes to be removed`); }
JavaScript
function samples(path, precision) { const n = path.getTotalLength(); const t = [0]; let i = 0; const dt = precision; while((i += dt) < n) t.push(i); t.push(n); return t.map(function(tt) { //console.log("getting p..."); //console.log("path", path); const p = path.getPointAtLength(tt); //console.log("p", p); //console.log("tt", tt); const a = [p.x, p.y]; a.t = tt / n; return a; }); }
function samples(path, precision) { const n = path.getTotalLength(); const t = [0]; let i = 0; const dt = precision; while((i += dt) < n) t.push(i); t.push(n); return t.map(function(tt) { //console.log("getting p..."); //console.log("path", path); const p = path.getPointAtLength(tt); //console.log("p", p); //console.log("tt", tt); const a = [p.x, p.y]; a.t = tt / n; return a; }); }
JavaScript
function lineJoin(p0, p1, p2, p3, width) { const u12 = perp(p1, p2); const r = width / 2; let a = [p1[0] + u12[0] * r, p1[1] + u12[1] * r]; let b = [p2[0] + u12[0] * r, p2[1] + u12[1] * r]; let c = [p2[0] - u12[0] * r, p2[1] - u12[1] * r]; let d = [p1[0] - u12[0] * r, p1[1] - u12[1] * r]; if(p0) { // clip ad and dc using average of u01 and u12 const u01 = perp(p0, p1); const e = [ p1[0] + u01[0] + u12[0], p1[1] + u01[1] + u12[1] ]; a = lineIntersect(p1, e, a, b); d = lineIntersect(p1, e, d, c); } if(p3) { // clip ab and dc using average of u12 and u23 const u23 = perp(p2, p3); const e = [ p2[0] + u23[0] + u12[0], p2[1] + u23[1] + u12[1] ]; b = lineIntersect(p2, e, a, b); c = lineIntersect(p2, e, d, c); } return "M" + a + "L" + b + " " + c + " " + d + "Z"; }
function lineJoin(p0, p1, p2, p3, width) { const u12 = perp(p1, p2); const r = width / 2; let a = [p1[0] + u12[0] * r, p1[1] + u12[1] * r]; let b = [p2[0] + u12[0] * r, p2[1] + u12[1] * r]; let c = [p2[0] - u12[0] * r, p2[1] - u12[1] * r]; let d = [p1[0] - u12[0] * r, p1[1] - u12[1] * r]; if(p0) { // clip ad and dc using average of u01 and u12 const u01 = perp(p0, p1); const e = [ p1[0] + u01[0] + u12[0], p1[1] + u01[1] + u12[1] ]; a = lineIntersect(p1, e, a, b); d = lineIntersect(p1, e, d, c); } if(p3) { // clip ab and dc using average of u12 and u23 const u23 = perp(p2, p3); const e = [ p2[0] + u23[0] + u12[0], p2[1] + u23[1] + u12[1] ]; b = lineIntersect(p2, e, a, b); c = lineIntersect(p2, e, d, c); } return "M" + a + "L" + b + " " + c + " " + d + "Z"; }
JavaScript
function lineIntersect(a, b, c, d) { const x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3; const y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3; const ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); return [x1 + ua * x21, y1 + ua * y21]; }
function lineIntersect(a, b, c, d) { const x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3; const y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3; const ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); return [x1 + ua * x21, y1 + ua * y21]; }
JavaScript
function perp(p0, p1) { const u01x = p0[1] - p1[1]; const u01y = p1[0] - p0[0]; const u01d = Math.sqrt(u01x * u01x + u01y * u01y); return [u01x / u01d, u01y / u01d]; }
function perp(p0, p1) { const u01x = p0[1] - p1[1]; const u01y = p1[0] - p0[0]; const u01d = Math.sqrt(u01x * u01x + u01y * u01y); return [u01x / u01d, u01y / u01d]; }
JavaScript
function borderOrientationIsCounterclockwise(points) { const namedCoordPoints = points.map(vectorPoint_to_namedCoordPoint); const barycenter = pointsBarycenter(namedCoordPoints); const angles = namedCoordPoints.map(point => normalizeAngle(angle(barycenter, point))); const minAngle = Math.min(...angles); const indexOfMin = angles.indexOf(minAngle); // let angles2 = angles.rotate(-indexOfMin); angles.unshift(angles.splice(-indexOfMin, this.length)); return angles[2] > angles[1]; }
function borderOrientationIsCounterclockwise(points) { const namedCoordPoints = points.map(vectorPoint_to_namedCoordPoint); const barycenter = pointsBarycenter(namedCoordPoints); const angles = namedCoordPoints.map(point => normalizeAngle(angle(barycenter, point))); const minAngle = Math.min(...angles); const indexOfMin = angles.indexOf(minAngle); // let angles2 = angles.rotate(-indexOfMin); angles.unshift(angles.splice(-indexOfMin, this.length)); return angles[2] > angles[1]; }
JavaScript
function handlePOST(request, response, command) { if (command === '/temps') { request.on('data', () => {}); request.on('end', () => { response.writeHead(200, {'Content-Type': 'application/json'}); getTemps((data) => { response.end(JSON.stringify(data)); }); }); } else { response.writeHead(404, {'Content-Type': 'text/html'}); response.end('Unknown POST request'); } }
function handlePOST(request, response, command) { if (command === '/temps') { request.on('data', () => {}); request.on('end', () => { response.writeHead(200, {'Content-Type': 'application/json'}); getTemps((data) => { response.end(JSON.stringify(data)); }); }); } else { response.writeHead(404, {'Content-Type': 'text/html'}); response.end('Unknown POST request'); } }
JavaScript
function send404(response) { fs.readFile('./content/404.html', 'utf8', function(err, contents) { if (err) { response.writeHead(500, {'Content-Type': 'text/html'}); response.end("Something weird happened. I blame you. It's all your fault."); } else { response.writeHead(404, {'Content-Type': 'text/html'}); response.end(contents); } }); }
function send404(response) { fs.readFile('./content/404.html', 'utf8', function(err, contents) { if (err) { response.writeHead(500, {'Content-Type': 'text/html'}); response.end("Something weird happened. I blame you. It's all your fault."); } else { response.writeHead(404, {'Content-Type': 'text/html'}); response.end(contents); } }); }
JavaScript
gateOn(source) { console.log('gateOn', this.ctx.currentTime, this.attackTime, this.releaseTime, this.sustainRatio); clearTimeout(this.disconnectTimeout); this.input.connect(this); this.connect(this.output); startADSR(this.gain, this.attackTime, this.decayTime, this.sustainRatio, this.ctx.currentTime); this.on = true; }
gateOn(source) { console.log('gateOn', this.ctx.currentTime, this.attackTime, this.releaseTime, this.sustainRatio); clearTimeout(this.disconnectTimeout); this.input.connect(this); this.connect(this.output); startADSR(this.gain, this.attackTime, this.decayTime, this.sustainRatio, this.ctx.currentTime); this.on = true; }
JavaScript
function createPWMWave(ctx, duty, terms) { const coeffs = createPWMCoefficients(duty, terms); const customWave = ctx.createPeriodicWave(coeffs.sin, coeffs.cos, { disableNormalization: true }); return customWave; }
function createPWMWave(ctx, duty, terms) { const coeffs = createPWMCoefficients(duty, terms); const customWave = ctx.createPeriodicWave(coeffs.sin, coeffs.cos, { disableNormalization: true }); return customWave; }
JavaScript
goTo( path, internal = false ) { this.path = path const request = { paths: this.matchPath( this.path ), internal } if ( !request.paths ) { request[ '404' ] = true request.paths = { go: this.paths[ '*' ] } } if ( this.singleProject ) { this.singleProject.stopRendering() delete this.singleProject } request.paths.go( request ) }
goTo( path, internal = false ) { this.path = path const request = { paths: this.matchPath( this.path ), internal } if ( !request.paths ) { request[ '404' ] = true request.paths = { go: this.paths[ '*' ] } } if ( this.singleProject ) { this.singleProject.stopRendering() delete this.singleProject } request.paths.go( request ) }
JavaScript
matchPath() { if ( this.paths[ this.path ] ) { return { go: this.paths[ this.path ] } } const URLMatches = this.matchURL, variableNames = [] // Resource: // http://krasimirtsonev.com/blog/article/deep-dive-into-client-side-routing-navigo-pushstate-hash if ( !URLMatches || !URLMatches.includes( ':' ) ) return null const route = URLMatches.replace( /([:*])(\w+)/g, ( full, dots, name ) => { variableNames.push( name ) /* eslint-disable no-useless-escape */ return '([^\/]+)' } ) + '(?:\/|$)', /* eslint-enable no-useless-escape */ match = this.path.match( new RegExp( route ) ) if ( match ) { const params = match.slice( 1, match.length ) .reduce( ( param, value, i ) => { // if ( param === null ) param = {} param[ variableNames[ i ] ] = value return param }, {} ) return { go: this.paths[ URLMatches ], params } } }
matchPath() { if ( this.paths[ this.path ] ) { return { go: this.paths[ this.path ] } } const URLMatches = this.matchURL, variableNames = [] // Resource: // http://krasimirtsonev.com/blog/article/deep-dive-into-client-side-routing-navigo-pushstate-hash if ( !URLMatches || !URLMatches.includes( ':' ) ) return null const route = URLMatches.replace( /([:*])(\w+)/g, ( full, dots, name ) => { variableNames.push( name ) /* eslint-disable no-useless-escape */ return '([^\/]+)' } ) + '(?:\/|$)', /* eslint-enable no-useless-escape */ match = this.path.match( new RegExp( route ) ) if ( match ) { const params = match.slice( 1, match.length ) .reduce( ( param, value, i ) => { // if ( param === null ) param = {} param[ variableNames[ i ] ] = value return param }, {} ) return { go: this.paths[ URLMatches ], params } } }
JavaScript
function restoreSettings() { for (let index = 0; index < settingsStorage.length; index++) { let key = settingsStorage.key(index); let data = { key: key, newValue: settingsStorage.getItem(key), dataType: true }; if(key === "restURL") { console.log('restURL') console.log(JSON.parse(settingsStorage.getItem(key)).name) url = JSON.parse(settingsStorage.getItem(key)).name; }else if(key === "dataType") { console.log('dataType') console.log(JSON.parse(settingsStorage.getItem(key))) BgDataType = JSON.parse(settingsStorage.getItem(key)) } } }
function restoreSettings() { for (let index = 0; index < settingsStorage.length; index++) { let key = settingsStorage.key(index); let data = { key: key, newValue: settingsStorage.getItem(key), dataType: true }; if(key === "restURL") { console.log('restURL') console.log(JSON.parse(settingsStorage.getItem(key)).name) url = JSON.parse(settingsStorage.getItem(key)).name; }else if(key === "dataType") { console.log('dataType') console.log(JSON.parse(settingsStorage.getItem(key))) BgDataType = JSON.parse(settingsStorage.getItem(key)) } } }
JavaScript
function sendVal(data) { console.log('in sendVal') console.log(data) // send BG Data type first if (messaging.peerSocket.readyState === messaging.peerSocket.OPEN) { // messaging.peerSocket.send( '{"type":'+BgDataType+'}'); console.log('in IF of sendval ') console.log(JSON.parse(data).length) if(renderAllPoints) { for(let index = JSON.parse(data).length-1; index >= 0; index--) { console.log( JSON.stringify(JSON.parse(data)[index])) console.log('Sending Values') messaging.peerSocket.send(JSON.parse(data)[index]); } renderAllPoints = false; } else { console.log('only send one data point') messaging.peerSocket.send(JSON.parse(data)[0]); } } }
function sendVal(data) { console.log('in sendVal') console.log(data) // send BG Data type first if (messaging.peerSocket.readyState === messaging.peerSocket.OPEN) { // messaging.peerSocket.send( '{"type":'+BgDataType+'}'); console.log('in IF of sendval ') console.log(JSON.parse(data).length) if(renderAllPoints) { for(let index = JSON.parse(data).length-1; index >= 0; index--) { console.log( JSON.stringify(JSON.parse(data)[index])) console.log('Sending Values') messaging.peerSocket.send(JSON.parse(data)[index]); } renderAllPoints = false; } else { console.log('only send one data point') messaging.peerSocket.send(JSON.parse(data)[0]); } } }
JavaScript
_isNumerical(obj) { // eslint-disable-next-line obj -= 0 // eslint-disable-next-line return obj === obj }
_isNumerical(obj) { // eslint-disable-next-line obj -= 0 // eslint-disable-next-line return obj === obj }
JavaScript
function vowelCount(str) { let splitArr = str.split(""); let obj = {}; const vowels = "aeiou"; splitArr.forEach(function(letter) { let lowerCasedLetter = letter.toLowerCase() if (vowels.indexOf(lowerCasedLetter) !== -1) { if (obj[lowerCasedLetter]) { obj[lowerCasedLetter]++; } else { obj[lowerCasedLetter] = 1; } } }); return obj; }
function vowelCount(str) { let splitArr = str.split(""); let obj = {}; const vowels = "aeiou"; splitArr.forEach(function(letter) { let lowerCasedLetter = letter.toLowerCase() if (vowels.indexOf(lowerCasedLetter) !== -1) { if (obj[lowerCasedLetter]) { obj[lowerCasedLetter]++; } else { obj[lowerCasedLetter] = 1; } } }); return obj; }
JavaScript
function average(x) { var result = 0; for (var i = 0; i < x.length; i++) { result = result + x[i].age; } var last= result / x.length; return last; }
function average(x) { var result = 0; for (var i = 0; i < x.length; i++) { result = result + x[i].age; } var last= result / x.length; return last; }
JavaScript
function olderPerson(x) { var maxAge = x[0].age; var index = 0; for (var i = 1; i < x.length; i++) { if (maxAge < x[i].age) { maxAge = x[i].age; index = i; } } return x[index].name.first + " " + x[index].name.last; }
function olderPerson(x) { var maxAge = x[0].age; var index = 0; for (var i = 1; i < x.length; i++) { if (maxAge < x[i].age) { maxAge = x[i].age; index = i; } } return x[index].name.first + " " + x[index].name.last; }