language stringclasses 6
values | original_string stringlengths 25 887k | text stringlengths 25 887k |
|---|---|---|
JavaScript | function carFactory(input) {
const cars = {};
const children = {};
const printQueue = [];
const factory = {
create: (name) => {
cars[name] = {};
},
set: (name, key, value) => {
cars[name][key] = value;
},
print: (name) => {
con... | function carFactory(input) {
const cars = {};
const children = {};
const printQueue = [];
const factory = {
create: (name) => {
cars[name] = {};
},
set: (name, key, value) => {
cars[name][key] = value;
},
print: (name) => {
con... |
JavaScript | function maybeBind ( model, value, shouldBind ) {
if ( shouldBind && isFunction( value ) && model.parent && model.parent.isRoot ) {
if ( !model.boundValue ) {
model.boundValue = bind$1( value._r_unbound || value, model.parent.ractive );
}
return model.boundValue;
}
return value;
} | function maybeBind ( model, value, shouldBind ) {
if ( shouldBind && isFunction( value ) && model.parent && model.parent.isRoot ) {
if ( !model.boundValue ) {
model.boundValue = bind$1( value._r_unbound || value, model.parent.ractive );
}
return model.boundValue;
}
return value;
} |
JavaScript | function rebindMatch ( template, next, previous, fragment ) {
var keypath = template.r || template;
// no valid keypath, go with next
if ( !keypath || !isString( keypath ) ) { return next; }
// completely contextual ref, go with next
if ( keypath === '.' || keypath[0] === '@' || ( next || previous ).isKey || ( n... | function rebindMatch ( template, next, previous, fragment ) {
var keypath = template.r || template;
// no valid keypath, go with next
if ( !keypath || !isString( keypath ) ) { return next; }
// completely contextual ref, go with next
if ( keypath === '.' || keypath[0] === '@' || ( next || previous ).isKey || ( n... |
JavaScript | function readKey ( parser ) {
var token;
if ( token = readStringLiteral( parser ) ) {
return identifier.test( token.v ) ? token.v : '"' + token.v.replace( /"/g, '\\"' ) + '"';
}
if ( token = readNumberLiteral( parser ) ) {
return token.v;
}
if ( token = parser.matchPattern( name ) ) {
return token;
}
... | function readKey ( parser ) {
var token;
if ( token = readStringLiteral( parser ) ) {
return identifier.test( token.v ) ? token.v : '"' + token.v.replace( /"/g, '\\"' ) + '"';
}
if ( token = readNumberLiteral( parser ) ) {
return token.v;
}
if ( token = parser.matchPattern( name ) ) {
return token;
}
... |
JavaScript | function isUsCounty(wofData) {
return 'US' === wofData.properties['iso:country'] &&
'county' === wofData.properties['wof:placetype'] &&
!_.isUndefined(wofData.properties['qs:a2_alt']);
} | function isUsCounty(wofData) {
return 'US' === wofData.properties['iso:country'] &&
'county' === wofData.properties['wof:placetype'] &&
!_.isUndefined(wofData.properties['qs:a2_alt']);
} |
JavaScript | function LocalPipService(datapath, layers) {
const self = this;
createPipService(datapath, _.defaultTo(layers, []), false, (err, service) => {
if (err) {
throw err;
}
self.pipService = service;
});
} | function LocalPipService(datapath, layers) {
const self = this;
createPipService(datapath, _.defaultTo(layers, []), false, (err, service) => {
if (err) {
throw err;
}
self.pipService = service;
});
} |
JavaScript | function readData(datapath, layer, localizedAdminNames, callback) {
const features = [];
readSqliteRecords(datapath,layer)
.pipe(whosonfirst.recordHasIdAndProperties())
.pipe(whosonfirst.isActiveRecord())
.pipe(filterOutPointRecords.create())
.pipe(filterOutHierarchylessNeighbourhoods.create())
... | function readData(datapath, layer, localizedAdminNames, callback) {
const features = [];
readSqliteRecords(datapath,layer)
.pipe(whosonfirst.recordHasIdAndProperties())
.pipe(whosonfirst.isActiveRecord())
.pipe(filterOutPointRecords.create())
.pipe(filterOutHierarchylessNeighbourhoods.create())
... |
JavaScript | function calculateLayers(inputLayers) {
const allowedLayers = [ 'neighbourhood', 'borough', 'locality', 'localadmin', 'county',
'macrocounty', 'region', 'macroregion', 'dependency', 'country' ];
// if no input layers are specified, return all of the allowed layers
if (!inputLayers) {
inputLayers = allowe... | function calculateLayers(inputLayers) {
const allowedLayers = [ 'neighbourhood', 'borough', 'locality', 'localadmin', 'county',
'macrocounty', 'region', 'macroregion', 'dependency', 'country' ];
// if no input layers are specified, return all of the allowed layers
if (!inputLayers) {
inputLayers = allowe... |
JavaScript | function q1(){
var favorite_passtime;
var favorite_passtime_correct_answer = 'y';
favorite_passtime = prompt('Do you think that rob obsessivly plays video games? Y or N');
console.log(favorite_passtime + ' y or n');
if(favorite_passtime === favorite_passtime_correct_answer){
alert('How could he not come o... | function q1(){
var favorite_passtime;
var favorite_passtime_correct_answer = 'y';
favorite_passtime = prompt('Do you think that rob obsessivly plays video games? Y or N');
console.log(favorite_passtime + ' y or n');
if(favorite_passtime === favorite_passtime_correct_answer){
alert('How could he not come o... |
JavaScript | _onNobleStateChange(state) {
Logger.debug(`Noble state changed to ${state}`);
if (state === 'poweredOn') {
Logger.info('Searching for drones...');
this.noble.startScanning();
}
} | _onNobleStateChange(state) {
Logger.debug(`Noble state changed to ${state}`);
if (state === 'poweredOn') {
Logger.info('Searching for drones...');
this.noble.startScanning();
}
} |
JavaScript | _onPeripheralDiscovery(peripheral) {
if (!this._validatePeripheral(peripheral)) {
return;
}
Logger.info(`Peripheral found ${peripheral.advertisement.localName}`);
this.noble.stopScanning();
peripheral.connect(error => {
if (error) {
throw error;
}
this._peripheral ... | _onPeripheralDiscovery(peripheral) {
if (!this._validatePeripheral(peripheral)) {
return;
}
Logger.info(`Peripheral found ${peripheral.advertisement.localName}`);
this.noble.stopScanning();
peripheral.connect(error => {
if (error) {
throw error;
}
this._peripheral ... |
JavaScript | _validatePeripheral(peripheral) {
if (!peripheral) {
return false;
}
const localName = peripheral.advertisement.localName;
const manufacturer = peripheral.advertisement.manufacturerData;
const matchesFilter = !this.droneFilter || localName === this.droneFilter;
const localNameMatch =
... | _validatePeripheral(peripheral) {
if (!peripheral) {
return false;
}
const localName = peripheral.advertisement.localName;
const manufacturer = peripheral.advertisement.manufacturerData;
const matchesFilter = !this.droneFilter || localName === this.droneFilter;
const localNameMatch =
... |
JavaScript | _setupPeripheral() {
this.peripheral.discoverAllServicesAndCharacteristics(
(err, services, characteristics) => {
if (err) {
throw err;
}
// @todo
// Parse characteristics and only store the ones needed
// also validate that they're also present
this.... | _setupPeripheral() {
this.peripheral.discoverAllServicesAndCharacteristics(
(err, services, characteristics) => {
if (err) {
throw err;
}
// @todo
// Parse characteristics and only store the ones needed
// also validate that they're also present
this.... |
JavaScript | runCommand(command) {
Logger.debug('SEND: ', command.toString());
const buffer = command.toBuffer();
const messageId = this._getStep(command.bufferType);
buffer.writeIntLE(messageId, 1);
// console.log(command.bufferType, 'type');
this.getCharacteristic(command.sendCharacteristicUuid).write(buf... | runCommand(command) {
Logger.debug('SEND: ', command.toString());
const buffer = command.toBuffer();
const messageId = this._getStep(command.bufferType);
buffer.writeIntLE(messageId, 1);
// console.log(command.bufferType, 'type');
this.getCharacteristic(command.sendCharacteristicUuid).write(buf... |
JavaScript | get sendCharacteristicUuid() {
const t = bufferCharTranslationMap[this.bufferType] || 'SEND_WITH_ACK';
return `fa${characteristicSendUuids[t]}`;
} | get sendCharacteristicUuid() {
const t = bufferCharTranslationMap[this.bufferType] || 'SEND_WITH_ACK';
return `fa${characteristicSendUuids[t]}`;
} |
JavaScript | toBuffer() {
const bufferLength =
6 + this.arguments.reduce((acc, val) => val.getValueSize() + acc, 0);
const buffer = new Buffer(bufferLength);
buffer.fill(0);
buffer.writeUInt16LE(this.bufferFlag, 0);
// Skip command counter (offset 1) because it's set in DroneConnection::runCommand
... | toBuffer() {
const bufferLength =
6 + this.arguments.reduce((acc, val) => val.getValueSize() + acc, 0);
const buffer = new Buffer(bufferLength);
buffer.fill(0);
buffer.writeUInt16LE(this.bufferFlag, 0);
// Skip command counter (offset 1) because it's set in DroneConnection::runCommand
... |
JavaScript | static async load(config, modulePath) {
let filePath;
let isESM;
try {
({ isESM, filePath } = ModuleLoader.resolvePath(config, modulePath));
// It is important to await on _importDynamic to catch the error code.
return isESM ? await _importDynamic(url.pathToFi... | static async load(config, modulePath) {
let filePath;
let isESM;
try {
({ isESM, filePath } = ModuleLoader.resolvePath(config, modulePath));
// It is important to await on _importDynamic to catch the error code.
return isESM ? await _importDynamic(url.pathToFi... |
JavaScript | static async loadWithData(config, modulePath) {
let filePath;
let isESM;
try {
({ isESM, filePath } = ModuleLoader.resolvePath(config, modulePath));
const module = isESM ? await _importDynamic(url.pathToFileURL(filePath)) : require(filePath);
return { isESM, m... | static async loadWithData(config, modulePath) {
let filePath;
let isESM;
try {
({ isESM, filePath } = ModuleLoader.resolvePath(config, modulePath));
const module = isESM ? await _importDynamic(url.pathToFileURL(filePath)) : require(filePath);
return { isESM, m... |
JavaScript | static resolvePath(config, modulePath) {
let isESM;
let filePath;
try {
filePath = require.resolve(modulePath);
isESM = ModuleLoader.isPathModule(filePath);
}
catch (error) {
filePath = ts_node_1.tsPath(config.root, modulePath);
// ... | static resolvePath(config, modulePath) {
let isESM;
let filePath;
try {
filePath = require.resolve(modulePath);
isESM = ModuleLoader.isPathModule(filePath);
}
catch (error) {
filePath = ts_node_1.tsPath(config.root, modulePath);
// ... |
JavaScript | function compose(...fns) {
return (...args) => {
return fns.reduceRight((leftFn, rightFn) => {
return leftFn instanceof Promise
? Promise.resolve(leftFn).then(rightFn)
: rightFn(leftFn);
}, args[0]);
};
} | function compose(...fns) {
return (...args) => {
return fns.reduceRight((leftFn, rightFn) => {
return leftFn instanceof Promise
? Promise.resolve(leftFn).then(rightFn)
: rightFn(leftFn);
}, args[0]);
};
} |
JavaScript | function deferNetworkRequestsUntil(predicatePromise) {
// Defer any `XMLHttpRequest` requests until the Service Worker is ready.
const originalXhrSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function (...args) {
// Keep this function synchronous to comply with ... | function deferNetworkRequestsUntil(predicatePromise) {
// Defer any `XMLHttpRequest` requests until the Service Worker is ready.
const originalXhrSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function (...args) {
// Keep this function synchronous to comply with ... |
JavaScript | function start(options) {
const resolvedOptions = mergeRight(DEFAULT_START_OPTIONS, options || {});
const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
if (!('serviceWorker' in navigator)) {
console.error(`[MSW] Failed to register a Service Worker... | function start(options) {
const resolvedOptions = mergeRight(DEFAULT_START_OPTIONS, options || {});
const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
if (!('serviceWorker' in navigator)) {
console.error(`[MSW] Failed to register a Service Worker... |
JavaScript | function stop() {
var _a;
(_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_DEACTIVATE');
context.events.removeAllListeners();
window.clearInterval(context.keepAliveInterval);
} | function stop() {
var _a;
(_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_DEACTIVATE');
context.events.removeAllListeners();
window.clearInterval(context.keepAliveInterval);
} |
JavaScript | function isNodeProcess() {
// Check browser environment.
if (typeof global !== 'object') {
return false;
}
// Check nodejs or React Native environment.
if (Object.prototype.toString.call(global.process) === '[object process]' ||
navigator.product === 'ReactNative') {
return t... | function isNodeProcess() {
// Check browser environment.
if (typeof global !== 'object') {
return false;
}
// Check nodejs or React Native environment.
if (Object.prototype.toString.call(global.process) === '[object process]' ||
navigator.product === 'ReactNative') {
return t... |
JavaScript | function parseBody(body, headers) {
var _a;
if (body) {
// If the intercepted request's body has a JSON Content-Type
// parse it into an object, otherwise leave as-is.
const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) === null || ... | function parseBody(body, headers) {
var _a;
if (body) {
// If the intercepted request's body has a JSON Content-Type
// parse it into an object, otherwise leave as-is.
const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) === null || ... |
JavaScript | function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util$1.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(ob... | function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util$1.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(ob... |
JavaScript | function createSetupServer(...interceptors) {
return function setupServer(...requestHandlers) {
requestHandlers.forEach((handler) => {
if (Array.isArray(handler))
throw new Error(`[MSW] Failed to call "setupServer" given an Array of request handlers (setupServer([a, b])), expecte... | function createSetupServer(...interceptors) {
return function setupServer(...requestHandlers) {
requestHandlers.forEach((handler) => {
if (Array.isArray(handler))
throw new Error(`[MSW] Failed to call "setupServer" given an Array of request handlers (setupServer([a, b])), expecte... |
JavaScript | printHandlers() {
currentHandlers.forEach((handler) => {
const meta = handler.getMetaInfo();
console.log(`\
${source.bold(meta.header)}
Declaration: ${meta.callFrame}
`);
});
} | printHandlers() {
currentHandlers.forEach((handler) => {
const meta = handler.getMetaInfo();
console.log(`\
${source.bold(meta.header)}
Declaration: ${meta.callFrame}
`);
});
} |
JavaScript | function prepareResponse(res) {
const responseHeaders = lib.listToHeaders(res.headers);
return Object.assign(Object.assign({}, res), {
// Parse a response JSON body for preview in the logs
body: parseBody(res.body, responseHeaders) });
} | function prepareResponse(res) {
const responseHeaders = lib.listToHeaders(res.headers);
return Object.assign(Object.assign({}, res), {
// Parse a response JSON body for preview in the logs
body: parseBody(res.body, responseHeaders) });
} |
JavaScript | function matchRequestUrl(url, mask) {
const resolvedMask = getUrlByMask(mask);
const cleanMask = getCleanMask(resolvedMask);
const cleanRequestUrl = getCleanUrl_1.getCleanUrl(url);
return match(cleanMask, cleanRequestUrl);
} | function matchRequestUrl(url, mask) {
const resolvedMask = getUrlByMask(mask);
const cleanMask = getCleanMask(resolvedMask);
const cleanRequestUrl = getCleanUrl_1.getCleanUrl(url);
return match(cleanMask, cleanRequestUrl);
} |
JavaScript | function stringToHeaders(str) {
var lines = str.trim().split(/[\r\n]+/);
return lines.reduce(function (headers, line) {
var parts = line.split(': ');
var name = parts.shift();
var value = parts.join(': ');
headers.append(name, value);
return headers;
}... | function stringToHeaders(str) {
var lines = str.trim().split(/[\r\n]+/);
return lines.reduce(function (headers, line) {
var parts = line.split(': ');
var name = parts.shift();
var value = parts.join(': ');
headers.append(name, value);
return headers;
}... |
JavaScript | function objectToHeaders(obj) {
return reduceHeadersObject_1.reduceHeadersObject(obj, function (headers, name, value) {
var values = [].concat(value);
values.forEach(function (value) {
headers.append(name, value);
});
return headers;
}, new Headers());
... | function objectToHeaders(obj) {
return reduceHeadersObject_1.reduceHeadersObject(obj, function (headers, name, value) {
var values = [].concat(value);
values.forEach(function (value) {
headers.append(name, value);
});
return headers;
}, new Headers());
... |
JavaScript | function parseBody(body, headers) {
var _a;
if (body) {
// If the intercepted request's body has a JSON Content-Type
// parse it into an object, otherwise leave as-is.
const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) ==... | function parseBody(body, headers) {
var _a;
if (body) {
// If the intercepted request's body has a JSON Content-Type
// parse it into an object, otherwise leave as-is.
const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) ==... |
JavaScript | function deferNetworkRequestsUntil(predicatePromise) {
// Defer any `XMLHttpRequest` requests until the Service Worker is ready.
const originalXhrSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function (...args) {
// Keep this function synchronous to comp... | function deferNetworkRequestsUntil(predicatePromise) {
// Defer any `XMLHttpRequest` requests until the Service Worker is ready.
const originalXhrSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function (...args) {
// Keep this function synchronous to comp... |
JavaScript | function start(options) {
const resolvedOptions = mergeRight(DEFAULT_START_OPTIONS, options || {});
const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
if (!('serviceWorker' in navigator)) {
console.error(`[MSW] Failed to register a Servic... | function start(options) {
const resolvedOptions = mergeRight(DEFAULT_START_OPTIONS, options || {});
const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
if (!('serviceWorker' in navigator)) {
console.error(`[MSW] Failed to register a Servic... |
JavaScript | function stop() {
var _a;
(_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_DEACTIVATE');
context.events.removeAllListeners();
window.clearInterval(context.keepAliveInterval);
} | function stop() {
var _a;
(_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_DEACTIVATE');
context.events.removeAllListeners();
window.clearInterval(context.keepAliveInterval);
} |
JavaScript | function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {
var _locations2, _source2, _positions2, _extensions2;
var _this;
_classCallCheck(this, GraphQLError);
_this = _super.call(this, message); // Compute list of blame nodes.
var _nodes = Array.isArr... | function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {
var _locations2, _source2, _positions2, _extensions2;
var _this;
_classCallCheck(this, GraphQLError);
_this = _super.call(this, message); // Compute list of blame nodes.
var _nodes = Array.isArr... |
JavaScript | function createGraphQLLink(uri) {
return {
operation: createGraphQLOperationHandler(uri),
query: createGraphQLScopedHandler('query', uri),
mutation: createGraphQLScopedHandler('mutation', uri),
};
} | function createGraphQLLink(uri) {
return {
operation: createGraphQLOperationHandler(uri),
query: createGraphQLScopedHandler('query', uri),
mutation: createGraphQLScopedHandler('mutation', uri),
};
} |
JavaScript | function handleClick(index) {
let currentColorHex
Object.keys(colors).map((value, key) => {
if (key === index) {
currentColorHex = colors[value];
return
}
});
setCurrentColor(currentColorHex);
router.push({pathname: "/colors/" + currentColorHex.name.substring(1)}, undefined, {scroll: f... | function handleClick(index) {
let currentColorHex
Object.keys(colors).map((value, key) => {
if (key === index) {
currentColorHex = colors[value];
return
}
});
setCurrentColor(currentColorHex);
router.push({pathname: "/colors/" + currentColorHex.name.substring(1)}, undefined, {scroll: f... |
JavaScript | function findXCodeproject(context, callback) {
fs.readdir(iosFolder(context), function(err, data) {
var projectFolder;
var projectName;
// Find the project folder by looking for *.xcodeproj
if (data && data.length) {
data.forEach(function(folder) {
if (fol... | function findXCodeproject(context, callback) {
fs.readdir(iosFolder(context), function(err, data) {
var projectFolder;
var projectName;
// Find the project folder by looking for *.xcodeproj
if (data && data.length) {
data.forEach(function(folder) {
if (fol... |
JavaScript | function iosFolder(context) {
return context.opts.cordova.project
? context.opts.cordova.project.root
: path.join(context.opts.projectRoot, 'platforms/ios/');
} | function iosFolder(context) {
return context.opts.cordova.project
? context.opts.cordova.project.root
: path.join(context.opts.projectRoot, 'platforms/ios/');
} |
JavaScript | function draw() {
if (bg.ready) {
ctx.drawImage(bg.image, 0, 0);
}
if (hero.ready) {
ctx.drawImage(hero.image, hero.x, hero.y);
}
monsters.forEach((monster) => {
if (monster.ready) {
ctx.drawImage(monster.image, monster.x, monster.y);
}
});
let remainningTime = SECONDS_PER_ROUND - elapsedTime;
timer.... | function draw() {
if (bg.ready) {
ctx.drawImage(bg.image, 0, 0);
}
if (hero.ready) {
ctx.drawImage(hero.image, hero.x, hero.y);
}
monsters.forEach((monster) => {
if (monster.ready) {
ctx.drawImage(monster.image, monster.x, monster.y);
}
});
let remainningTime = SECONDS_PER_ROUND - elapsedTime;
timer.... |
JavaScript | function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, true);
http.send();
return (http.status != 403);
} | function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, true);
http.send();
return (http.status != 403);
} |
JavaScript | function absoluteURI(uri, base) {
if (uri.substr(0, 2) == './')
uri = uri.substr(2);
// absolute urls are left in tact
if (uri.match(absUrlRegEx) || uri.match(protocolRegEx))
return uri;
var baseParts = base.split('/');
var uriParts = uri.split('/');
... | function absoluteURI(uri, base) {
if (uri.substr(0, 2) == './')
uri = uri.substr(2);
// absolute urls are left in tact
if (uri.match(absUrlRegEx) || uri.match(protocolRegEx))
return uri;
var baseParts = base.split('/');
var uriParts = uri.split('/');
... |
JavaScript | function relativeURI(uri, base) {
// reduce base and uri strings to just their difference string
var baseParts = base.split('/');
baseParts.pop();
base = baseParts.join('/') + '/';
i = 0;
while (base.substr(i, 1) == uri.substr(i, 1))
i++;
while (base.... | function relativeURI(uri, base) {
// reduce base and uri strings to just their difference string
var baseParts = base.split('/');
baseParts.pop();
base = baseParts.join('/') + '/';
i = 0;
while (base.substr(i, 1) == uri.substr(i, 1))
i++;
while (base.... |
JavaScript | function angularGridGlobalFunction(element, gridOptions) {
// see if element is a query selector, or a real element
var eGridDiv;
if (typeof element === 'string') {
eGridDiv = document.querySelector(element);
if (!eGridDiv) {
console.log('WARNING - was not... | function angularGridGlobalFunction(element, gridOptions) {
// see if element is a query selector, or a real element
var eGridDiv;
if (typeof element === 'string') {
eGridDiv = document.querySelector(element);
if (!eGridDiv) {
console.log('WARNING - was not... |
JavaScript | function httpConfig(action, data, additionalConfig) {
var config = {
method: methods[action].toLowerCase(),
url: paths[action]
};
if (data) {
if (resourceName) {
config.data = {};
config.data[resourceName] = data;
}... | function httpConfig(action, data, additionalConfig) {
var config = {
method: methods[action].toLowerCase(),
url: paths[action]
};
if (data) {
if (resourceName) {
config.data = {};
config.data[resourceName] = data;
}... |
JavaScript | function configure(obj, suffix) {
angular.forEach(obj, function(v, action) {
this[action + suffix] = function(param) {
if (param === undefined) {
return obj[action];
}
obj[action] = param;
return this;
};... | function configure(obj, suffix) {
angular.forEach(obj, function(v, action) {
this[action + suffix] = function(param) {
if (param === undefined) {
return obj[action];
}
obj[action] = param;
return this;
};... |
JavaScript | moveTo(x, y) {
//Collect Variables
this.planning.start = new Vector(this.x, this.y);
let endPoint = this.scene.tilemap.getPosition(x, y);
this.planning.end = new Vector(endPoint.x, endPoint.y);
let pathVector = this.planning.end.subtract(this.planning.start);
this.planning.distance = pathVector.ge... | moveTo(x, y) {
//Collect Variables
this.planning.start = new Vector(this.x, this.y);
let endPoint = this.scene.tilemap.getPosition(x, y);
this.planning.end = new Vector(endPoint.x, endPoint.y);
let pathVector = this.planning.end.subtract(this.planning.start);
this.planning.distance = pathVector.ge... |
JavaScript | function installSyncSaveDev(packages) {
if (Array.isArray(packages)) {
packages = packages.join(" ");
}
shell.execSync("npm i --save-dev " + packages, {stdio: "inherit"});
} | function installSyncSaveDev(packages) {
if (Array.isArray(packages)) {
packages = packages.join(" ");
}
shell.execSync("npm i --save-dev " + packages, {stdio: "inherit"});
} |
JavaScript | function check(packages, opt) {
var deps = [];
var pkgJson = findPackageJson();
if (!pkgJson) {
throw new Error("Could not find a package.json file");
}
var fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
if (opt.devDependencies) {
deps = deps.concat(Object.keys(fileJson... | function check(packages, opt) {
var deps = [];
var pkgJson = findPackageJson();
if (!pkgJson) {
throw new Error("Could not find a package.json file");
}
var fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
if (opt.devDependencies) {
deps = deps.concat(Object.keys(fileJson... |
JavaScript | function writeTempConfigFile(config, filename, existingTmpDir) {
var tmpFileDir = existingTmpDir || tmp.dirSync({prefix: "eslint-tests-"}).name,
tmpFilePath = path.join(tmpFileDir, filename),
tmpFileContents = JSON.stringify(config);
fs.writeFileSync(tmpFilePath, tmpFileContents);
return tmp... | function writeTempConfigFile(config, filename, existingTmpDir) {
var tmpFileDir = existingTmpDir || tmp.dirSync({prefix: "eslint-tests-"}).name,
tmpFilePath = path.join(tmpFileDir, filename),
tmpFileContents = JSON.stringify(config);
fs.writeFileSync(tmpFilePath, tmpFileContents);
return tmp... |
JavaScript | function checkForBreakAfter(node, msg) {
var paren = context.getTokenAfter(node);
while (paren.value === ")") {
paren = context.getTokenAfter(paren);
}
if (paren.loc.start.line !== node.loc.end.line) {
context.report(node, paren.loc.start, msg, { char: paren.valu... | function checkForBreakAfter(node, msg) {
var paren = context.getTokenAfter(node);
while (paren.value === ")") {
paren = context.getTokenAfter(paren);
}
if (paren.loc.start.line !== node.loc.end.line) {
context.report(node, paren.loc.start, msg, { char: paren.valu... |
JavaScript | function processText(text, configHelper, filename, fix, allowInlineConfig) {
// clear all existing settings for a new file
eslint.reset();
var filePath,
config,
messages,
stats,
fileExtension = path.extname(filename),
processor,
loadedPlugins,
fixedR... | function processText(text, configHelper, filename, fix, allowInlineConfig) {
// clear all existing settings for a new file
eslint.reset();
var filePath,
config,
messages,
stats,
fileExtension = path.extname(filename),
processor,
loadedPlugins,
fixedR... |
JavaScript | function processFile(filename, configHelper, options) {
var text = fs.readFileSync(path.resolve(filename), "utf8"),
result = processText(text, configHelper, filename, options.fix, options.allowInlineConfig);
return result;
} | function processFile(filename, configHelper, options) {
var text = fs.readFileSync(path.resolve(filename), "utf8"),
result = processText(text, configHelper, filename, options.fix, options.allowInlineConfig);
return result;
} |
JavaScript | function CLIEngine(options) {
options = assign(Object.create(null), defaultOptions, options);
/**
* Stored options for this instance
* @type {Object}
*/
this.options = options;
var cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd);
/*... | function CLIEngine(options) {
options = assign(Object.create(null), defaultOptions, options);
/**
* Stored options for this instance
* @type {Object}
*/
this.options = options;
var cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd);
/*... |
JavaScript | function hashOfConfigFor(filename) {
var config = configHelper.getConfig(filename);
if (!prevConfig) {
prevConfig = {};
}
// reuse the previously hashed config if the config hasn't changed
if (prevConfig.config !== config) {
/... | function hashOfConfigFor(filename) {
var config = configHelper.getConfig(filename);
if (!prevConfig) {
prevConfig = {};
}
// reuse the previously hashed config if the config hasn't changed
if (prevConfig.config !== config) {
/... |
JavaScript | function executeOnFile(filename, warnIgnored) {
var hashOfConfig;
if (options.ignore !== false) {
if (ignoredPaths.contains(filename, "custom")) {
if (warnIgnored) {
results.push(createIgnoreResult(filename));
}
... | function executeOnFile(filename, warnIgnored) {
var hashOfConfig;
if (options.ignore !== false) {
if (ignoredPaths.contains(filename, "custom")) {
if (warnIgnored) {
results.push(createIgnoreResult(filename));
}
... |
JavaScript | function generateFormatterExamples(formatterInfo, prereleaseVersion) {
var output = ejs.render(cat("./templates/formatter-examples.md.ejs"), formatterInfo),
filename = "../eslint.github.io/docs/user-guide/formatters/index.md",
htmlFilename = "../eslint.github.io/docs/user-guide/formatters/html-forma... | function generateFormatterExamples(formatterInfo, prereleaseVersion) {
var output = ejs.render(cat("./templates/formatter-examples.md.ejs"), formatterInfo),
filename = "../eslint.github.io/docs/user-guide/formatters/index.md",
htmlFilename = "../eslint.github.io/docs/user-guide/formatters/html-forma... |
JavaScript | function calculateReleaseInfo() {
// get most recent tag
var tags = getVersionTags(),
lastTag = tags[tags.length - 1],
commitFlagPattern = /([a-z]+):/i,
releaseInfo = {};
// get log statements
var logs = execSilent("git log --no-merges --pretty=format:\"* %h %s (%an)\" " + last... | function calculateReleaseInfo() {
// get most recent tag
var tags = getVersionTags(),
lastTag = tags[tags.length - 1],
commitFlagPattern = /([a-z]+):/i,
releaseInfo = {};
// get log statements
var logs = execSilent("git log --no-merges --pretty=format:\"* %h %s (%an)\" " + last... |
JavaScript | function release() {
echo("Updating dependencies");
exec("npm install && npm prune");
echo("Running tests");
target.test();
echo("Calculating changes for release");
var releaseInfo = calculateReleaseInfo();
echo("Release is " + releaseInfo.version);
echo("Generating changelog");
... | function release() {
echo("Updating dependencies");
exec("npm install && npm prune");
echo("Running tests");
target.test();
echo("Calculating changes for release");
var releaseInfo = calculateReleaseInfo();
echo("Release is " + releaseInfo.version);
echo("Generating changelog");
... |
JavaScript | function prerelease(version) {
if (!version) {
echo("Missing prerelease version.");
exit(1);
}
echo("Updating dependencies");
exec("npm install && npm prune");
echo("Running tests");
target.test();
echo("Calculating changes for release");
var releaseInfo = calculateRe... | function prerelease(version) {
if (!version) {
echo("Missing prerelease version.");
exit(1);
}
echo("Updating dependencies");
exec("npm install && npm prune");
echo("Running tests");
target.test();
echo("Calculating changes for release");
var releaseInfo = calculateRe... |
JavaScript | function createConfigForPerformanceTest() {
var content = [
"root: true",
"env:",
" node: true",
" es6: true",
"rules:"
];
content.push.apply(
content,
ls("lib/rules").map(function(fileName) {
return " " + path.basename(fileName, "... | function createConfigForPerformanceTest() {
var content = [
"root: true",
"env:",
" node: true",
" es6: true",
"rules:"
];
content.push.apply(
content,
ls("lib/rules").map(function(fileName) {
return " " + path.basename(fileName, "... |
JavaScript | function sortTable(n, numeric=false) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("tournament_participants");
switching = true;
// Set the sorting direction to ascending:
dir = "asc";
/* Make a loop that will continue until
no switching has bee... | function sortTable(n, numeric=false) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("tournament_participants");
switching = true;
// Set the sorting direction to ascending:
dir = "asc";
/* Make a loop that will continue until
no switching has bee... |
JavaScript | function extendArray(daddyArray, childArray) {
for (var i = 0; i < childArray.length; i++) {
daddyArray.push(childArray[i]);
}
} | function extendArray(daddyArray, childArray) {
for (var i = 0; i < childArray.length; i++) {
daddyArray.push(childArray[i]);
}
} |
JavaScript | initNProgress() {
$(document).ready(function () {
if (this.isPjax) {
$(document).on('pjax:send', function () {
NProgress.start();
});
$(document).on('pjax:end', function () {
NProgress.done();
})... | initNProgress() {
$(document).ready(function () {
if (this.isPjax) {
$(document).on('pjax:send', function () {
NProgress.start();
});
$(document).on('pjax:end', function () {
NProgress.done();
})... |
JavaScript | schema() {
return {
desc: this.desc
};
} | schema() {
return {
desc: this.desc
};
} |
JavaScript | async applyDefaults() {
const requiredOptions = {
long: {},
short: {}
};
const len = this.contexts.length;
log(`Processing default options and environment variables for ${highlight(len)} ${pluralize('context', len)}`);
this.env = {};
// loop through every context
for (let i = len; i; i--) {
con... | async applyDefaults() {
const requiredOptions = {
long: {},
short: {}
};
const len = this.contexts.length;
log(`Processing default options and environment variables for ${highlight(len)} ${pluralize('context', len)}`);
this.env = {};
// loop through every context
for (let i = len; i; i--) {
con... |
JavaScript | async parseWithContext(ctx) {
// print the context's info
log(`Context: ${highlight(ctx.name)}`);
if (!ctx.lookup.empty) {
log(ctx.lookup.toString());
}
await this.parseArg(ctx, 0);
} | async parseWithContext(ctx) {
// print the context's info
log(`Context: ${highlight(ctx.name)}`);
if (!ctx.lookup.empty) {
log(ctx.lookup.toString());
}
await this.parseArg(ctx, 0);
} |
JavaScript | generateHelp() {
const entries = [];
for (const ctxName of Array.from(this.keys())) {
const { aliases, clikitHelp, desc, hidden, name } = this.get(ctxName).exports[ctxName];
if (!hidden && !clikitHelp) {
const labels = new Set([ name ]);
for (const [ alias, display ] of Object.entries(aliases)) {
... | generateHelp() {
const entries = [];
for (const ctxName of Array.from(this.keys())) {
const { aliases, clikitHelp, desc, hidden, name } = this.get(ctxName).exports[ctxName];
if (!hidden && !clikitHelp) {
const labels = new Set([ name ]);
for (const [ alias, display ] of Object.entries(aliases)) {
... |
JavaScript | add(format, params) {
if (!format) {
throw E.INVALID_ARGUMENT('Invalid option format or option', { name: 'format', scope: 'OptionMap.add', value: format });
}
const results = [];
let lastGroup = '';
let options = [];
if (Array.isArray(format)) {
options = format;
} else if (typeof format === 'obje... | add(format, params) {
if (!format) {
throw E.INVALID_ARGUMENT('Invalid option format or option', { name: 'format', scope: 'OptionMap.add', value: format });
}
const results = [];
let lastGroup = '';
let options = [];
if (Array.isArray(format)) {
options = format;
} else if (typeof format === 'obje... |
JavaScript | generateHelp() {
let count = 0;
const groups = {};
const sortFn = (a, b) => {
return a.order < b.order ? -1 : a.order > b.order ? 1 : a.long.localeCompare(b.long);
};
for (const [ groupName, options ] of this.entries()) {
const group = groups[groupName] = [];
for (const opt of options.sort(sortFn)) ... | generateHelp() {
let count = 0;
const groups = {};
const sortFn = (a, b) => {
return a.order < b.order ? -1 : a.order > b.order ? 1 : a.long.localeCompare(b.long);
};
for (const [ groupName, options ] of this.entries()) {
const group = groups[groupName] = [];
for (const opt of options.sort(sortFn)) ... |
JavaScript | function split(str) {
if (typeof str !== 'string') {
return str;
}
const results = [];
const re = /\x07|\x1b(?:[a-z\d]|\[\?25[hl]|\[[A-Za-z]|\[\d+[A-Za-z]|\[\d+;\d+H|\]\d+[^\x07]+\x07)/;
let m;
while (m = re.exec(str)) {
results.push(m.index ? str.substring(0, m.index) : '');
results.push(str.substr(m.ind... | function split(str) {
if (typeof str !== 'string') {
return str;
}
const results = [];
const re = /\x07|\x1b(?:[a-z\d]|\[\?25[hl]|\[[A-Za-z]|\[\d+[A-Za-z]|\[\d+;\d+H|\]\d+[^\x07]+\x07)/;
let m;
while (m = re.exec(str)) {
results.push(m.index ? str.substring(0, m.index) : '');
results.push(str.substr(m.ind... |
JavaScript | function escapeTildes(str) {
let state = [ 0 ];
let s = '';
for (let i = 0, l = str.length; i < l; i++) {
switch (state[0]) {
case 0: // not in an expression
if ((i === 0 || str[i - 1] !== '\\') && str[i] === '$' && str[i + 1] === '{') {
s += str[i++]; // $
s += str[i]; // {
state.unshift(1... | function escapeTildes(str) {
let state = [ 0 ];
let s = '';
for (let i = 0, l = str.length; i < l; i++) {
switch (state[0]) {
case 0: // not in an expression
if ((i === 0 || str[i - 1] !== '\\') && str[i] === '$' && str[i + 1] === '{') {
s += str[i++]; // $
s += str[i]; // {
state.unshift(1... |
JavaScript | onOutput(cb) {
if (this.outputCallbacks) {
this.outputCallbacks.push(cb);
} else {
cb(this.outputResolution);
}
return this;
} | onOutput(cb) {
if (this.outputCallbacks) {
this.outputCallbacks.push(cb);
} else {
cb(this.outputResolution);
}
return this;
} |
JavaScript | registerExtension(name, meta, params) {
log(`Registering extension command: ${highlight(`${this.name}:${name}`)}`);
const cmd = new Command(name, {
parent: this,
...params
});
this.exports[name] = Object.assign(cmd, meta);
cmd.isExtension = true;
if (meta?.pkg?.clikit) {
cmd.isCLIKitExtension = tr... | registerExtension(name, meta, params) {
log(`Registering extension command: ${highlight(`${this.name}:${name}`)}`);
const cmd = new Command(name, {
parent: this,
...params
});
this.exports[name] = Object.assign(cmd, meta);
cmd.isExtension = true;
if (meta?.pkg?.clikit) {
cmd.isCLIKitExtension = tr... |
JavaScript | schema() {
return {
...super.schema,
path: this.path
};
} | schema() {
return {
...super.schema,
path: this.path
};
} |
JavaScript | argument(arg) {
this.args.add(arg);
this.rev++;
return this;
} | argument(arg) {
this.args.add(arg);
this.rev++;
return this;
} |
JavaScript | command(cmd, params, clone) {
const cmds = this.commands.add(cmd, params, clone);
for (const cmd of cmds) {
log(`Adding command: ${highlight(cmd.name)} ${note(`(${this.name})`)}`);
this.register(cmd);
}
this.rev++;
return this;
} | command(cmd, params, clone) {
const cmds = this.commands.add(cmd, params, clone);
for (const cmd of cmds) {
log(`Adding command: ${highlight(cmd.name)} ${note(`(${this.name})`)}`);
this.register(cmd);
}
this.rev++;
return this;
} |
JavaScript | extension(ext, name, clone) {
const exts = this.extensions.add(ext, name, clone);
for (const ext of exts) {
log(`Adding extension: ${highlight(ext.name)} ${note(`(${this.name})`)}`);
this.register(ext);
}
this.rev++;
return this;
} | extension(ext, name, clone) {
const exts = this.extensions.add(ext, name, clone);
for (const ext of exts) {
log(`Adding extension: ${highlight(ext.name)} ${note(`(${this.name})`)}`);
this.register(ext);
}
this.rev++;
return this;
} |
JavaScript | init(params, clone) {
if (!params || typeof params !== 'object' || (params.clikit instanceof Set && !params.clikit.has('Context'))) {
throw E.INVALID_ARGUMENT('Expected parameters to be an object or Context', { name: 'params', scope: 'Context.init', value: params });
}
if (params.clikit instanceof Set && !par... | init(params, clone) {
if (!params || typeof params !== 'object' || (params.clikit instanceof Set && !params.clikit.has('Context'))) {
throw E.INVALID_ARGUMENT('Expected parameters to be an object or Context', { name: 'params', scope: 'Context.init', value: params });
}
if (params.clikit instanceof Set && !par... |
JavaScript | register(it) {
let cmds;
let dest;
if (it.clikit.has('Extension')) {
cmds = Object.values(it.exports);
dest = 'extensions';
} else if (it.clikit.has('Command')) {
cmds = [ it ];
dest = 'commands';
}
if (!cmds) {
return;
}
it.parent = this;
for (const cmd of cmds) {
this.lookup[des... | register(it) {
let cmds;
let dest;
if (it.clikit.has('Extension')) {
cmds = Object.values(it.exports);
dest = 'extensions';
} else if (it.clikit.has('Command')) {
cmds = [ it ];
dest = 'commands';
}
if (!cmds) {
return;
}
it.parent = this;
for (const cmd of cmds) {
this.lookup[des... |
JavaScript | generateHelp() {
const entries = [];
for (const { desc, hidden, hint, multiple, name, required } of this) {
if (!hidden) {
entries.push({
desc,
hint,
multiple,
name,
required
});
}
}
return {
count: entries.length,
entries
};
} | generateHelp() {
const entries = [];
for (const { desc, hidden, hint, multiple, name, required } of this) {
if (!hidden) {
entries.push({
desc,
hint,
multiple,
name,
required
});
}
}
return {
count: entries.length,
entries
};
} |
JavaScript | add(cmd, params, clone) {
if (!cmd) {
throw E.INVALID_ARGUMENT('Invalid command', { name: 'cmd', scope: 'CommandMap.add', value: cmd });
}
if (!Command) {
Command = require('./command').default;
}
if (params !== undefined && params !== null) {
if (typeof cmd !== 'string') {
throw E.INVALID_ARGU... | add(cmd, params, clone) {
if (!cmd) {
throw E.INVALID_ARGUMENT('Invalid command', { name: 'cmd', scope: 'CommandMap.add', value: cmd });
}
if (!Command) {
Command = require('./command').default;
}
if (params !== undefined && params !== null) {
if (typeof cmd !== 'string') {
throw E.INVALID_ARGU... |
JavaScript | generateHelp() {
const entries = [];
for (const cmd of Array.from(this.keys())) {
const { aliases, clikitHelp, desc, hidden, name } = this.get(cmd);
if (!hidden && !clikitHelp) {
const labels = new Set([ name ]);
for (const [ alias, display ] of Object.entries(aliases)) {
if (display === 'visib... | generateHelp() {
const entries = [];
for (const cmd of Array.from(this.keys())) {
const { aliases, clikitHelp, desc, hidden, name } = this.get(cmd);
if (!hidden && !clikitHelp) {
const labels = new Set([ name ]);
for (const [ alias, display ] of Object.entries(aliases)) {
if (display === 'visib... |
JavaScript | async function namedEntityRecognition(data) {
const result = await makeModelRequest(data, "dslim/bert-large-NER");
if (result && result.length > 0) {
if (result[0].entity_group === 'PER') {
return 'Alive Object';
} else {
return 'Location';
}
}
else {
... | async function namedEntityRecognition(data) {
const result = await makeModelRequest(data, "dslim/bert-large-NER");
if (result && result.length > 0) {
if (result[0].entity_group === 'PER') {
return 'Alive Object';
} else {
return 'Location';
}
}
else {
... |
JavaScript | async function evaluateTerminalCommands(message, speaker, agent, res, client, channel) {
if (message === "/reset") { // If the user types /reset into the console...
// If there is a response (i.e. this came from a web client, not local terminal)
if (res) {
... | async function evaluateTerminalCommands(message, speaker, agent, res, client, channel) {
if (message === "/reset") { // If the user types /reset into the console...
// If there is a response (i.e. this came from a web client, not local terminal)
if (res) {
... |
JavaScript | async function archiveConversation(speaker, agent, _conversation, client, channel) {
// Get configuration settings for agent
const { conversationWindowSize } = await getConfigurationSettingsForAgent(agent);
const conversation = (await database.instance.getConversation(agent, speaker, client... | async function archiveConversation(speaker, agent, _conversation, client, channel) {
// Get configuration settings for agent
const { conversationWindowSize } = await getConfigurationSettingsForAgent(agent);
const conversation = (await database.instance.getConversation(agent, speaker, client... |
JavaScript | async function generateContext(speaker, agent, conversation, message) {
let keywords = []
if (!isInFastMode) {
keywords = keywordExtractor(message, agent);
}
const pr = await Promise.all([keywords,
database.instance.getSpeakersFacts(agent, speaker... | async function generateContext(speaker, agent, conversation, message) {
let keywords = []
if (!isInFastMode) {
keywords = keywordExtractor(message, agent);
}
const pr = await Promise.all([keywords,
database.instance.getSpeakersFacts(agent, speaker... |
JavaScript | async function handleInput(message, speaker, agent, res, clientName, channelId) {
let start = Date.now()
log("Handling input: " + message);
agent = agent ?? defaultAgent
//if the input is a command, it handles the command and doesn't respond according to the agent
if (awai... | async function handleInput(message, speaker, agent, res, clientName, channelId) {
let start = Date.now()
log("Handling input: " + message);
agent = agent ?? defaultAgent
//if the input is a command, it handles the command and doesn't respond according to the agent
if (awai... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 14