_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q50000
|
_processData
|
train
|
function _processData(){
if(_.isEmpty($scope.mdtRow)) {
return;
}
//local search/filter
if (angular.isUndefined($scope.mdtRowPaginator)) {
$scope.$watch('mdtRow', function (mdtRow) {
vm.dataStorage.storage = [];
_addRawDataToStorage(mdtRow['data']);
}, true);
}else{
//if it's used for 'Ajax pagination'
}
}
|
javascript
|
{
"resource": ""
}
|
q50001
|
nutritionNameFilterCallback
|
train
|
function nutritionNameFilterCallback(names){
var arr = _.filter(nutritionList, function(item){
return item.fields.item_name.toLowerCase().indexOf(names.toLowerCase()) !== -1;
});
return $q.resolve(arr);
}
|
javascript
|
{
"resource": ""
}
|
q50002
|
serviceUnitsFilterCallback
|
train
|
function serviceUnitsFilterCallback(){
var arr = _.filter(nutritionList, function(item){
return item.fields.nf_serving_size_unit && item.fields.nf_serving_size_unit.toLowerCase();
});
arr = _.uniq(arr, function(item){ return item.fields.nf_serving_size_unit;});
return $q.resolve(arr);
}
|
javascript
|
{
"resource": ""
}
|
q50003
|
fatValuesCallback
|
train
|
function fatValuesCallback(){
return $q.resolve([
{
name: '> 50%',
comparator: function(val){ return val > 50;}
}, {
name: '<= 50%',
comparator: function(val){ return val <= 50;}
}]);
}
|
javascript
|
{
"resource": ""
}
|
q50004
|
paginatorCallback
|
train
|
function paginatorCallback(page, pageSize, options){
console.log(options);
var filtersApplied = options.columnFilter;
var offset = (page-1) * pageSize;
var result = nutritionList;
if(filtersApplied[0].length) {
result = _.filter(nutritionList, function (aNutrition) {
var res = false;
_.each(filtersApplied[0], function(filteredNutrition){
if(res){
return;
}
res = aNutrition.fields.item_name.indexOf(filteredNutrition.fields.item_name) !== -1;
});
return res;
});
}
if(filtersApplied[1].length) {
result = _.filter(result, function (aNutrition) {
var res = false;
_.each(filtersApplied[1], function(filteredNutrition){
if(res){
return;
}
res = aNutrition.fields.nf_serving_size_unit && aNutrition.fields.nf_serving_size_unit.toLowerCase() == filteredNutrition.fields.nf_serving_size_unit && filteredNutrition.fields.nf_serving_size_unit.toLowerCase();
});
return res;
});
}
if(filtersApplied[2].length) {
result = _.filter(result, function (aNutrition) {
var res = false;
_.each(filtersApplied[2], function(fatObject){
if(res){
return;
}
res = fatObject.comparator(aNutrition.fields.nf_total_fat);
});
return res;
});
}
return $q(function(resolve, reject){
setTimeout(function(){
resolve({
results: result.slice(offset, offset + pageSize),
totalResultCount: result.length
});
},1000);
});
}
|
javascript
|
{
"resource": ""
}
|
q50005
|
extendsFromDeprecatedWidgetClassVersion
|
train
|
function extendsFromDeprecatedWidgetClassVersion(widgetClass) {
return Object.getPrototypeOf(widgetClass.prototype).constructor.version !== Widget.version;
}
|
javascript
|
{
"resource": ""
}
|
q50006
|
patchWidgetClass
|
train
|
function patchWidgetClass(widgetClass) {
const superWidgetClassPrototype = Object.getPrototypeOf(widgetClass.prototype);
// Patch subscribe method.
superWidgetClassPrototype.subscribe = Widget.prototype.subscribe;
// Patch publish method.
superWidgetClassPrototype.publish = Widget.prototype.publish;
}
|
javascript
|
{
"resource": ""
}
|
q50007
|
reportNonMatchingComponentName
|
train
|
function reportNonMatchingComponentName(node, rawName, name, filename) {
context.report(
node,
'Component name ' + rawName + ' (' + name + ') does not match filename ' + filename
);
}
|
javascript
|
{
"resource": ""
}
|
q50008
|
client
|
train
|
function client(table) {
table = table || process.env.ProgressTable;
if (!table) throw new Error('ProgressTable environment variable is not set');
var dyno = module.exports.Dyno({
table: table.split(':')[5].split('/')[1],
region: table.split(':')[3],
endpoint: process.env.DynamoDbEndpoint
});
/**
* Watchbot's progress client
*
* @name client
*/
return {
/**
* Sets the total number of parts for a map-reduce job
*
* @memberof client
* @param {string} jobId - the identifier for a map-reduce job
* @param {number} total - the total number of parts
* @param {function} [callback] - a function that will be called when the total
* number of parts for this job has been recorded
* @returns {promise}
*/
setTotal: setTotal.bind(null, dyno),
/**
* Mark one part of a map-reduce job as complete
*
* @memberof client
* @param {string} jobId - the identifier for a map-reduce job
* @param {number} part - the part that has completed (1-based, not 0-based)
* @param {function} [callback] - a function that will be called indicating whether
* or not the entire map-reduce job is complete
* @returns {promise}
*/
completePart: completePart.bind(null, dyno),
/**
* Fetch the status of a pending job
*
* @memberof client
* @param {string} jobId - the identifier for a map-reduce job
* @param {number} [part] - the part number to check on
* @param {function} [callback] - a function that will be called indicating the
* current job status
* @returns {promise}
* @example
* // a pending job that is 25% complete
* { "progress": 0.25 }
* @example
* // a completed job
* { "progress": 1 }
* @example
* // a job that failed after completing 60% of the work
* { "progress": 0.60, "failed": "the reason for the failure" }
* @example
* // a job 75% complete which includes metadata
* { "progress": 0.75, "metadata": { "name": "favorite-map-reduce" } }
* @example
* // a job 75% complete indicating that the requested part has already been completed
* { "progress": 0.75, "partComplete": true }
* @example
* // a job 100% complete indicating that the reduce step has been taken
* { "progress": 0.75, "reduceSent": true }
*/
status: status.bind(null, dyno),
/**
* Flag a job record to indicate that a reduce step has been taken.
*
* @param {string} jobId - the identifier for a map-reduce job
* @param {function} [callback] - a function that will be called when the flag has been set
* @returns {promise}
*/
reduceSent: reduceSent.bind(null, dyno),
/**
* Fail a job
*
* @memberof client
* @param {string} jobId - the identifier for a map-reduce job
* @param {string} reason - a description of why the job failed
* @param {function} [callback] - a function that will be called when the reason
* for the failure has been recorded
* @returns {promise}
*/
failJob: failJob.bind(null, dyno),
/**
* Associate arbitrary metadata with the progress record which can be retrieved
* with a status request.
*
* @param {string} jobId - the identifier for a map-reduce job
* @param {object} metadata - arbitrary metadata to store with the progress record.
* @param {function} [callback] - a function that will be called when the metadata
* has been recorded
* @returns {promise}
*/
setMetadata: setMetadata.bind(null, dyno)
};
}
|
javascript
|
{
"resource": ""
}
|
q50009
|
train
|
function(node) {
if (utils.isExplicitComponent(node)) {
return true;
}
if (!node.superClass) {
return false;
}
return new RegExp('^(' + pragma + '\\.)?(Pure)?Component$').test(sourceCode.getText(node.superClass));
}
|
javascript
|
{
"resource": ""
}
|
|
q50010
|
train
|
function(node) {
var comment = sourceCode.getJSDocComment(node);
if (comment === null) {
return false;
}
var commentAst = doctrine.parse(comment.value, {
unwrap: true,
tags: ['extends', 'augments']
});
var relevantTags = commentAst.tags.filter(function(tag) {
return tag.name === 'React.Component' || tag.name === 'React.PureComponent';
});
return relevantTags.length > 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q50011
|
train
|
function (node) {
if (node.superClass) {
return new RegExp('^(' + pragma + '\\.)?PureComponent$').test(sourceCode.getText(node.superClass));
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q50012
|
train
|
function(node) {
if (!node.value || !node.value.body || !node.value.body.body) {
return false;
}
var i = node.value.body.body.length - 1;
for (; i >= 0; i--) {
if (node.value.body.body[i].type === 'ReturnStatement') {
return node.value.body.body[i];
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q50013
|
getTokenBeforeClosingBracket
|
train
|
function getTokenBeforeClosingBracket(node) {
var attributes = node.attributes;
if (attributes.length === 0) {
return node.name;
}
return attributes[attributes.length - 1];
}
|
javascript
|
{
"resource": ""
}
|
q50014
|
train
|
function (chunks, start, end) {
var soff=0, eoff=0, i=0, j=0;
for (i=0; i<chunks.length; i++) {
if (soff + chunks[i].length > start)
break;
soff += chunks[i].length;
}
var strs = [];
eoff = soff;
for (j=i; j<chunks.length; j++) {
strs.push(chunks[j]);
if (eoff + chunks[j].length > end)
break;
eoff += chunks[j].length;
}
var s = strs.join('');
return s.substring(start-soff, start-soff+(end-start));
}
|
javascript
|
{
"resource": ""
}
|
|
q50015
|
minifyCodeEsprima
|
train
|
function minifyCodeEsprima(code,callback,description) {
if ((typeof esprima == "undefined") ||
(typeof esmangle == "undefined") ||
(typeof escodegen == "undefined")) {
console.warn("esprima/esmangle/escodegen not defined - not minifying")
return callback(code);
}
var code, syntax, option, str, before, after;
var options = {};
options["mangle"] = Espruino.Config.MINIFICATION_Mangle;
options["remove-unreachable-branch"] = Espruino.Config.MINIFICATION_Unreachable;
options["remove-unused-vars"] = Espruino.Config.MINIFICATION_Unused;
options["fold-constant"] = Espruino.Config.MINIFICATION_Literal;
options["eliminate-dead-code"] = Espruino.Config.MINIFICATION_DeadCode;
option = {format: {indent: {style: ''},quotes: 'auto',compact: true}};
str = '';
try {
before = code.length;
syntax = esprima.parse(code, { raw: true, loc: true });
syntax = obfuscate(syntax,options);
code = escodegen.generate(syntax, option);
after = code.length;
if (before > after) {
Espruino.Core.Notifications.info('No errors'+description+'. Minified ' + before + ' bytes to ' + after + ' bytes.');
} else {
Espruino.Core.Notifications.info('Can not minify further'+description+', code is already optimized.');
}
callback(code);
} catch (e) {
Espruino.Core.Notifications.error(e.toString()+description);
console.error(e.stack);
callback(code);
} finally { }
}
|
javascript
|
{
"resource": ""
}
|
q50016
|
minifyCodeGoogle
|
train
|
function minifyCodeGoogle(code, callback, minificationLevel, description){
for (var i in minifyCache) {
var item = minifyCache[i];
if (item.code==code && item.level==minificationLevel) {
console.log("Found code in minification cache - using that"+description);
// move to front of cache
minifyCache.splice(i,1); // remove old
minifyCache.push(item); // add at front
// callback
callback(item.minified);
return;
}
}
closureCompilerGoogle(code, minificationLevel, 'compiled_code', function(minified) {
if (minified.trim()!="") {
Espruino.Core.Notifications.info('No errors'+description+'. Minifying ' + code.length + ' bytes to ' + minified.length + ' bytes');
if (minifyCache.length>100)
minifyCache = minifyCache.slice(-100);
minifyCache.push({ level : minificationLevel, code : code, minified : minified });
callback(minified);
} else {
Espruino.Core.Notifications.warning("Errors while minifying"+description+" - sending unminified code.");
callback(code);
// get errors...
closureCompilerGoogle(code, minificationLevel, 'errors',function(errors) {
errors.split("\n").forEach(function (err) {
if (err.trim()!="")
Espruino.Core.Notifications.error(err.trim()+description);
});
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50017
|
initModule
|
train
|
function initModule(modName, mod) {
console.log("Initialising "+modName);
if (mod.init !== undefined)
mod.init();
}
|
javascript
|
{
"resource": ""
}
|
q50018
|
callProcessor
|
train
|
function callProcessor(eventType, data, callback) {
var p = processors[eventType];
// no processors
if (p===undefined || p.length==0) {
if (callback!==undefined) callback(data);
return;
}
// now go through all processors
var n = 0;
var cbCalled = false;
var cb = function(inData) {
if (cbCalled) throw new Error("Internal error in "+eventType+" processor. Callback is called TWICE.");
cbCalled = true;
if (n < p.length) {
cbCalled = false;
p[n++](inData, cb);
} else {
if (callback!==undefined) callback(inData);
}
};
cb(data);
}
|
javascript
|
{
"resource": ""
}
|
q50019
|
getSections
|
train
|
function getSections() {
var sections = [];
// add sections we know about
for (var name in builtinSections)
sections.push(builtinSections[name]);
// add other sections
for (var i in Espruino.Core.Config.data) {
var c = Espruino.Core.Config.data[i];
var found = false;
for (var s in sections)
if (sections[s].name == c.section)
found = true;
if (!found) {
console.warn("Section named "+c.section+" was not added with Config.addSection");
sections[c.section] = {
name : c.section,
sortOrder : 0
};
}
}
// Now sort by sortOrder
sections.sort(function (a,b) { return a.sortOrder - b.sortOrder; });
return sections;
}
|
javascript
|
{
"resource": ""
}
|
q50020
|
countBrackets
|
train
|
function countBrackets(str) {
var lex = getLexer(str);
var brackets = 0;
var tok = lex.next();
while (tok!==undefined) {
if (tok.str=="(" || tok.str=="{" || tok.str=="[") brackets++;
if (tok.str==")" || tok.str=="}" || tok.str=="]") brackets--;
tok = lex.next();
}
return brackets;
}
|
javascript
|
{
"resource": ""
}
|
q50021
|
getEspruinoPrompt
|
train
|
function getEspruinoPrompt(callback) {
if (Espruino.Core.Terminal!==undefined &&
Espruino.Core.Terminal.getTerminalLine()==">") {
console.log("Found a prompt... great!");
return callback();
}
var receivedData = "";
var prevReader = Espruino.Core.Serial.startListening(function (readData) {
var bufView = new Uint8Array(readData);
for(var i = 0; i < bufView.length; i++) {
receivedData += String.fromCharCode(bufView[i]);
}
if (receivedData[receivedData.length-1] == ">") {
if (receivedData.substr(-6)=="debug>") {
console.log("Got debug> - sending Ctrl-C to break out and we'll be good");
Espruino.Core.Serial.write('\x03');
} else {
if (receivedData == "\r\n=undefined\r\n>")
receivedData=""; // this was just what we expected - so ignore it
console.log("Received a prompt after sending newline... good!");
clearTimeout(timeout);
nextStep();
}
}
});
// timeout in case something goes wrong...
var hadToBreak = false;
var timeout = setTimeout(function() {
console.log("Got "+JSON.stringify(receivedData));
// if we haven't had the prompt displayed for us, Ctrl-C to break out of what we had
console.log("No Prompt found, got "+JSON.stringify(receivedData[receivedData.length-1])+" - issuing Ctrl-C to try and break out");
Espruino.Core.Serial.write('\x03');
hadToBreak = true;
timeout = setTimeout(function() {
console.log("Still no prompt - issuing another Ctrl-C");
Espruino.Core.Serial.write('\x03');
nextStep();
},500);
},500);
// when we're done...
var nextStep = function() {
// send data to console anyway...
if(prevReader) prevReader(receivedData);
receivedData = "";
// start the previous reader listening again
Espruino.Core.Serial.startListening(prevReader);
// call our callback
if (callback) callback(hadToBreak);
};
// send a newline, and we hope we'll see '=undefined\r\n>'
Espruino.Core.Serial.write('\n');
}
|
javascript
|
{
"resource": ""
}
|
q50022
|
executeExpression
|
train
|
function executeExpression(expressionToExecute, callback) {
var receivedData = "";
var hadDataSinceTimeout = false;
function getProcessInfo(expressionToExecute, callback) {
var prevReader = Espruino.Core.Serial.startListening(function (readData) {
var bufView = new Uint8Array(readData);
for(var i = 0; i < bufView.length; i++) {
receivedData += String.fromCharCode(bufView[i]);
}
// check if we got what we wanted
var startProcess = receivedData.indexOf("< <<");
var endProcess = receivedData.indexOf(">> >", startProcess);
if(startProcess >= 0 && endProcess > 0){
// All good - get the data!
var result = receivedData.substring(startProcess + 4,endProcess);
console.log("Got "+JSON.stringify(receivedData));
// strip out the text we found
receivedData = receivedData.substr(0,startProcess) + receivedData.substr(endProcess+4);
// Now stop time timeout
if (timeout) clearInterval(timeout);
timeout = "cancelled";
// Do the next stuff
nextStep(result);
} else if (startProcess >= 0) {
// we got some data - so keep waiting...
hadDataSinceTimeout = true;
}
});
// when we're done...
var nextStep = function(result) {
// start the previous reader listing again
Espruino.Core.Serial.startListening(prevReader);
// forward the original text to the previous reader
if(prevReader) prevReader(receivedData);
// run the callback
callback(result);
};
var timeout = undefined;
// Don't Ctrl-C, as we've already got ourselves a prompt with Espruino.Core.Utils.getEspruinoPrompt
Espruino.Core.Serial.write('\x10print("<","<<",JSON.stringify('+expressionToExecute+'),">>",">")\n',
undefined, function() {
// now it's sent, wait for data
var maxTimeout = 10; // seconds - how long we wait if we're getting data
var minTimeout = 2; // seconds - how long we wait if we're not getting data
var pollInterval = 500; // milliseconds
var timeoutSeconds = 0;
if (timeout != "cancelled")
timeout = setInterval(function onTimeout(){
timeoutSeconds += pollInterval/1000;
// if we're still getting data, keep waiting for up to 10 secs
if (hadDataSinceTimeout && timeoutSeconds<maxTimeout) {
hadDataSinceTimeout = false;
} else if (timeoutSeconds > minTimeout) {
// No data yet...
// OR we keep getting data for > maxTimeout seconds
clearInterval(timeout);
console.warn("No result found for "+JSON.stringify(expressionToExecute)+" - just got "+JSON.stringify(receivedData));
nextStep(undefined);
}
}, pollInterval);
});
}
if(Espruino.Core.Serial.isConnected()){
Espruino.Core.Utils.getEspruinoPrompt(function() {
getProcessInfo(expressionToExecute, callback);
});
} else {
console.error("executeExpression called when not connected!");
callback(undefined);
}
}
|
javascript
|
{
"resource": ""
}
|
q50023
|
isRecognisedBluetoothDevice
|
train
|
function isRecognisedBluetoothDevice(name) {
if (!name) return false;
var devs = recognisedBluetoothDevices();
for (var i=0;i<devs.length;i++)
if (name.substr(0, devs[i].length) == devs[i])
return true;
return false;
}
|
javascript
|
{
"resource": ""
}
|
q50024
|
stringToArrayBuffer
|
train
|
function stringToArrayBuffer(str) {
var buf=new Uint8Array(str.length);
for (var i=0; i<str.length; i++) {
var ch = str.charCodeAt(i);
if (ch>=256) {
console.warn("stringToArrayBuffer got non-8 bit character - code "+ch);
ch = "?".charCodeAt(0);
}
buf[i] = ch;
}
return buf.buffer;
}
|
javascript
|
{
"resource": ""
}
|
q50025
|
stringToBuffer
|
train
|
function stringToBuffer(str) {
var buf = new Buffer(str.length);
for (var i = 0; i < buf.length; i++) {
buf.writeUInt8(str.charCodeAt(i), i);
}
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q50026
|
dataViewToArrayBuffer
|
train
|
function dataViewToArrayBuffer(str) {
var bufView = new Uint8Array(dv.byteLength);
for (var i = 0; i < bufView.length; i++) {
bufView[i] = dv.getUint8(i);
}
return bufView.buffer;
}
|
javascript
|
{
"resource": ""
}
|
q50027
|
moduleLoaded
|
train
|
function moduleLoaded(resolve, requires, modName, data, loadedModuleData, alreadyMinified){
// Check for any modules used from this module that we don't already have
var newRequires = getModulesRequired(data);
console.log(" - "+modName+" requires "+JSON.stringify(newRequires));
// if we need new modules, set them to load and get their promises
var newPromises = [];
for (var i in newRequires) {
if (requires.indexOf(newRequires[i])<0) {
console.log(" Queueing "+newRequires[i]);
requires.push(newRequires[i]);
newPromises.push(loadModule(requires, newRequires[i], loadedModuleData));
} else {
console.log(" Already loading "+newRequires[i]);
}
}
var loadProcessedModule = function (module) {
// add the module to the beginning of our array
if (Espruino.Config.MODULE_AS_FUNCTION)
loadedModuleData.unshift("Modules.addCached(" + JSON.stringify(module.name) + ",function(){" + module.code + "});");
else
loadedModuleData.unshift("Modules.addCached(" + JSON.stringify(module.name) + "," + JSON.stringify(module.code) + ");");
// if we needed to load something, wait until we have all promises complete before resolving our promise!
Promise.all(newPromises).then(function(){ resolve(); });
}
if (alreadyMinified)
loadProcessedModule({code:data,name:modName});
else
Espruino.callProcessor("transformModuleForEspruino", {code:data,name:modName}, loadProcessedModule);
}
|
javascript
|
{
"resource": ""
}
|
q50028
|
loadModules
|
train
|
function loadModules(code, callback){
var loadedModuleData = [];
var requires = getModulesRequired(code);
if (requires.length == 0) {
// no modules needed - just return
callback(code);
} else {
Espruino.Core.Status.setStatus("Loading modules");
// Kick off the module loading (each returns a promise)
var promises = requires.map(function (moduleName) {
return loadModule(requires, moduleName, loadedModuleData);
});
// When all promises are complete
Promise.all(promises).then(function(){
callback(loadedModuleData.join("\n") + "\n" + code);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q50029
|
makeJobFile
|
train
|
function makeJobFile(config) {
var job = {"espruino":{}};
// assign commandline values
for (var key in args) {
switch (key) {
case 'job': // remove job itself, and others set internally from the results
case 'espruinoPrefix':
case 'espruinoPostfix':
break;
default: job[key] = args[key]; // otherwise just output each key: value
}
// write fields of Espruino.Config passed as config
for (var k in config) { if (typeof config[k]!=='function') job.espruino[k] = config[k]; };
}
// name job file same as code file with json ending or default and save.
var jobFile = isNextValidJS(args.file) ? args.file.slice(0,args.file.lastIndexOf('.'))+'.json' : "job.json";
if (!fs.existsSync(jobFile)) {
log("Creating job file "+JSON.stringify(jobFile));
fs.writeFileSync(jobFile,JSON.stringify(job,null,2),{encoding:"utf8"});
} else
log("WARNING: File "+JSON.stringify(jobFile)+" already exists - not overwriting.");
}
|
javascript
|
{
"resource": ""
}
|
q50030
|
getBoardList
|
train
|
function getBoardList(callback) {
var jsonDir = Espruino.Config.BOARD_JSON_URL;
// ensure jsonDir ends with slash
if (jsonDir.indexOf('/', jsonDir.length - 1) === -1) {
jsonDir += '/';
}
Espruino.Core.Utils.getJSONURL(jsonDir + "boards.json", function(boards){
// now load all the individual JSON files
var promises = [];
for (var boardId in boards) {
promises.push((function() {
var id = boardId;
return new Promise(function(resolve, reject) {
Espruino.Core.Utils.getJSONURL(jsonDir + boards[boardId].json, function (data) {
boards[id]["json"] = data;
resolve();
});
});
})());
}
// When all are loaded, load the callback
Promise.all(promises).then(function() {
callback(boards);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q50031
|
handler
|
train
|
function handler(opts) {
Object.assign(values, opts);
const configPath = path.join(os.homedir(), ".moleculer-templates.json");
return (
Promise.resolve()
//check for existing template alias config file
.then(() => {
return new Promise((resolve, reject) => {
fs.exists(configPath, exists => {
if (exists) {
fs.readFile(configPath, (err, config) => {
if (err) {
reject();
}
values.aliasedTemplates = JSON.parse(config);
resolve();
});
} else {
resolve();
}
});
});
})
// check if template name already exists
.then(() => {
const { templateName, aliasedTemplates } = values;
if (aliasedTemplates[templateName]) {
// if exists ask for overwrite
return inquirer.prompt([{
type: "confirm",
name: "continue",
message: chalk.yellow.bold(`The alias '${templateName}' already exists with value '${aliasedTemplates[templateName]}'! Overwrite?`),
default: false
}]).then(answers => {
if (!answers.continue)
process.exit(0);
});
}
})
// write template name and repo url
.then(() => {
const { templateName, templateUrl, aliasedTemplates } = values;
const newAliases = JSON.stringify(Object.assign(aliasedTemplates, { [templateName]: templateUrl }));
fs.writeFileSync(configPath, newAliases);
})
.catch(err => fail(err))
);
}
|
javascript
|
{
"resource": ""
}
|
q50032
|
renderTemplate
|
train
|
function renderTemplate(skipInterpolation) {
skipInterpolation = typeof skipInterpolation === "string" ? [skipInterpolation] : skipInterpolation;
const handlebarsMatcher = /{{([^{}]+)}}/;
return function (files, metalsmith, done) {
const keys = Object.keys(files);
const metadata = metalsmith.metadata();
async.each(keys, (file, next) => {
// skipping files with skipInterpolation option
if (skipInterpolation && multimatch([file], skipInterpolation, { dot: true }).length) {
return next();
}
async.series([
// interpolate the file contents
function (callback) {
const str = files[file].contents.toString();
if (!handlebarsMatcher.test(str)) {
return callback();
}
render(str, metadata, function (err, res) {
if (err) return callback(err);
files[file].contents = Buffer.from(res);
callback();
});
},
// interpolate the file name
function (callback) {
if (!handlebarsMatcher.test(file)) {
return callback();
}
render(file, metadata, function (err, res) {
if (err) return callback(err);
// safety check to prevent file deletion in case filename doesn't change
if (file === res) return callback();
// safety check to prevent overwriting another file
if (files[res]) return callback(`Cannot rename file ${file} to ${res}. A file with that name already exists.`);
// add entry for interpolated file name
files[res] = files[file];
// delete entry for template file name
delete files[file];
callback();
});
}
], function (err) {
if (err) return done(err);
next();
});
}, done);
};
}
|
javascript
|
{
"resource": ""
}
|
q50033
|
train
|
function (callback) {
const str = files[file].contents.toString();
if (!handlebarsMatcher.test(str)) {
return callback();
}
render(str, metadata, function (err, res) {
if (err) return callback(err);
files[file].contents = Buffer.from(res);
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50034
|
train
|
function (callback) {
if (!handlebarsMatcher.test(file)) {
return callback();
}
render(file, metadata, function (err, res) {
if (err) return callback(err);
// safety check to prevent file deletion in case filename doesn't change
if (file === res) return callback();
// safety check to prevent overwriting another file
if (files[res]) return callback(`Cannot rename file ${file} to ${res}. A file with that name already exists.`);
// add entry for interpolated file name
files[res] = files[file];
// delete entry for template file name
delete files[file];
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50035
|
train
|
function(chain_id) {
let i, len, network, network_name, ref;
ref = Object.keys(_this.networks);
for (i = 0, len = ref.length; i < len; i++) {
network_name = ref[i];
network = _this.networks[network_name];
if (network.chain_id === chain_id) {
_this.network_name = network_name;
if (network.address_prefix) {
_this.address_prefix = network.address_prefix;
ecc_config.address_prefix = network.address_prefix;
}
// console.log("INFO Configured for", network_name, ":", network.core_asset, "\n");
return {
network_name: network_name,
network: network
}
}
}
if (!_this.network_name) {
console.log("Unknown chain id (this may be a testnet)", chain_id);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50036
|
train
|
function(msg) {
var event = _getEvent.apply(this, arguments);
var data = {event: event};
// Add agent info if required
if (_pageInfo !== 'never') {
if (!_sentPageInfo || _pageInfo === 'per-entry') {
_sentPageInfo = true;
if (typeof event.screen === "undefined" &&
typeof event.browser === "undefined")
_rawLog(_agentInfo()).level('PAGE').send();
}
}
if (_traceCode) {
data.trace = _traceCode;
}
return {level: function(l) {
// Don't log PAGE events to console
// PAGE events are generated for the agentInfo function
if (_print && typeof console !== "undefined" && l !== 'PAGE') {
var serialized = null;
if (typeof XDomainRequest !== "undefined") {
// We're using IE8/9
serialized = data.trace + ' ' + data.event;
}
try {
console[l.toLowerCase()].call(console, (serialized || data));
} catch (ex) {
// IE compat fix
console.log((serialized || data));
}
}
data.level = l;
return {send: function() {
var cache = [];
var serialized = JSON.stringify(data, function(key, value) {
if (typeof value === "undefined") {
return "undefined";
} else if (typeof value === "object" && value !== null) {
if (_indexOf(cache, value) !== -1) {
// We've seen this object before;
// return a placeholder instead to prevent
// cycles
return "<?>";
}
cache.push(value);
}
return value;
});
if (_active) {
_backlog.push(serialized);
} else {
_apiCall(_token, serialized);
}
}};
}};
}
|
javascript
|
{
"resource": ""
}
|
|
q50037
|
Logger
|
train
|
function Logger(options) {
var logger;
// Default values
var dict = {
ssl: true,
catchall: false,
trace: true,
page_info: 'never',
print: false,
endpoint: null,
token: null
};
if (typeof options === "object")
for (var k in options)
dict[k] = options[k];
else
throw new Error("Invalid parameters for createLogStream()");
if (dict.token === null) {
throw new Error("Token not present.");
} else {
logger = new LogStream(dict);
}
var _log = function(msg) {
if (logger) {
return logger.log.apply(this, arguments);
} else
throw new Error("You must call LE.init(...) first.");
};
// The public interface
return {
log: function() {
_log.apply(this, arguments).level('LOG').send();
},
warn: function() {
_log.apply(this, arguments).level('WARN').send();
},
error: function() {
_log.apply(this, arguments).level('ERROR').send();
},
info: function() {
_log.apply(this, arguments).level('INFO').send();
}
};
}
|
javascript
|
{
"resource": ""
}
|
q50038
|
_copyPackageJson
|
train
|
function _copyPackageJson(from, to) {
return new Promise((resolve, reject) => {
const origin = path.join(from, 'package.json');
const destination = path.join(to, 'package.json');
let data = JSON.parse(fs.readFileSync(origin, 'utf-8'));
delete data.engines;
delete data.scripts;
delete data.devDependencies;
fs.writeFileSync(destination, JSON.stringify(data, null, 2));
resolve();
});
}
|
javascript
|
{
"resource": ""
}
|
q50039
|
getRandomNumber
|
train
|
function getRandomNumber(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
|
javascript
|
{
"resource": ""
}
|
q50040
|
addLabelsToResource
|
train
|
async function addLabelsToResource (config, resourceList) {
return resourceList.map((resource) => {
const baseLabel = {
project: config.projectName,
version: config.projectVersion,
provider: 'nodeshift'
};
resource.metadata.labels = _.merge({}, baseLabel, resource.metadata.labels);
if (resource.kind === 'Deployment' || resource.kind === 'DeploymentConfig') {
resource.metadata.labels.app = config.projectName;
resource.spec.template.metadata.labels = _.merge({}, baseLabel, resource.spec.template.metadata.labels);
resource.spec.template.metadata.labels.app = config.projectName;
}
return resource;
});
}
|
javascript
|
{
"resource": ""
}
|
q50041
|
loadEnrichers
|
train
|
function loadEnrichers () {
// find all the js files in the resource-enrichers directory
const enrichers = fs.readdirSync(`${__dirname}/resource-enrichers`).reduce((loaded, file) => {
const filesSplit = file.split('.');
if (filesSplit[1] === 'js') {
const mod = require(`./resource-enrichers/${file}`);
loaded[mod.name] = mod.enrich;
return loaded;
}
return loaded;
}, {});
return enrichers;
}
|
javascript
|
{
"resource": ""
}
|
q50042
|
defaultService
|
train
|
function defaultService (config) {
const serviceConfig = _.merge({}, baseServiceConfig);
// Apply MetaData
serviceConfig.metadata = objectMetadata({
name: config.projectName,
namespace: config.namespace.name
});
serviceConfig.spec.selector = {
project: config.projectName,
provider: 'nodeshift'
};
serviceConfig.spec.ports = [
{
protocol: 'TCP',
port: config.port,
targetPort: config.port,
name: 'http'
}
];
serviceConfig.spec.type = 'ClusterIP';
return serviceConfig;
}
|
javascript
|
{
"resource": ""
}
|
q50043
|
Client
|
train
|
function Client(options) {
this.options = {
host: options.host || '127.0.0.1',
port: options.port || '8983',
core: options.core || '',
rootPath: options.rootPath || 'solr',
protocol: options.protocol || 'http'
};
// Optional Authentication
if (options.user && options.password) {
this.options.user = options.user;
this.options.password = options.password;
}
// Path Constants List
this.SEARCH_PATH = 'select';
this.TERMS_PATH = 'terms';
this.SPELL_PATH = 'spell';
this.MLT_PATH = 'mlt';
this.UPDATE_PATH = 'update';
this.UPDATE_EXTRACT_PATH = 'update/extract';
this.PING_PATH = 'admin/ping';
this.SUGGEST_PATH = 'suggest';
}
|
javascript
|
{
"resource": ""
}
|
q50044
|
train
|
function() {
// Q* := Q / |Q|
// unrolled Q.scale(1 / Q.norm())
var w = this['w'];
var x = this['x'];
var y = this['y'];
var z = this['z'];
var norm = Math.sqrt(w * w + x * x + y * y + z * z);
if (norm < Quaternion['EPSILON']) {
return Quaternion['ZERO'];
}
norm = 1 / norm;
return new Quaternion(w * norm, x * norm, y * norm, z * norm);
}
|
javascript
|
{
"resource": ""
}
|
|
q50045
|
train
|
function(w, x, y, z) {
parse(P, w, x, y, z);
// Q1 * Q2 = [w1 * w2 - dot(v1, v2), w1 * v2 + w2 * v1 + cross(v1, v2)]
// Not commutative because cross(v1, v2) != cross(v2, v1)!
var w1 = this['w'];
var x1 = this['x'];
var y1 = this['y'];
var z1 = this['z'];
var w2 = P['w'];
var x2 = P['x'];
var y2 = P['y'];
var z2 = P['z'];
return new Quaternion(
w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2,
w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2);
}
|
javascript
|
{
"resource": ""
}
|
|
q50046
|
train
|
function(w, x, y, z) {
parse(P, w, x, y, z);
// dot(Q1, Q2) := w1 * w2 + dot(v1, v2)
return this['w'] * P['w'] + this['x'] * P['x'] + this['y'] * P['y'] + this['z'] * P['z'];
}
|
javascript
|
{
"resource": ""
}
|
|
q50047
|
train
|
function() {
var w = this['w'];
var x = this['x'];
var y = this['y'];
var z = this['z'];
var vNorm = Math.sqrt(x * x + y * y + z * z);
var wExp = Math.exp(w);
var scale = wExp / vNorm * Math.sin(vNorm);
if (vNorm === 0) {
//return new Quaternion(wExp * Math.cos(vNorm), 0, 0, 0);
return new Quaternion(wExp, 0, 0, 0);
}
return new Quaternion(
wExp * Math.cos(vNorm),
x * scale,
y * scale,
z * scale);
}
|
javascript
|
{
"resource": ""
}
|
|
q50048
|
train
|
function() {
var w = this['w'];
var x = this['x'];
var y = this['y'];
var z = this['z'];
if (y === 0 && z === 0) {
return new Quaternion(
logHypot(w, x),
Math.atan2(x, w), 0, 0);
}
var qNorm2 = x * x + y * y + z * z + w * w;
var vNorm = Math.sqrt(x * x + y * y + z * z);
var scale = Math.atan2(vNorm, w) / vNorm;
return new Quaternion(
Math.log(qNorm2) * 0.5,
x * scale,
y * scale,
z * scale);
}
|
javascript
|
{
"resource": ""
}
|
|
q50049
|
train
|
function(w, x, y, z) {
parse(P, w, x, y, z);
if (P['y'] === 0 && P['z'] === 0) {
if (P['w'] === 1 && P['x'] === 0) {
return this;
}
if (P['w'] === 0 && P['x'] === 0) {
return Quaternion['ONE'];
}
// Check if we can operate in C
// Borrowed from complex.js
if (this['y'] === 0 && this['z'] === 0) {
var a = this['w'];
var b = this['x'];
if (a === 0 && b === 0) {
return Quaternion['ZERO'];
}
var arg = Math.atan2(b, a);
var loh = logHypot(a, b);
if (P['x'] === 0) {
if (b === 0 && a >= 0) {
return new Quaternion(Math.pow(a, P['w']), 0, 0, 0);
} else if (a === 0) {
switch (P['w'] % 4) {
case 0:
return new Quaternion(Math.pow(b, P['w']), 0, 0, 0);
case 1:
return new Quaternion(0, Math.pow(b, P['w']), 0, 0);
case 2:
return new Quaternion(-Math.pow(b, P['w']), 0, 0, 0);
case 3:
return new Quaternion(0, -Math.pow(b, P['w']), 0, 0);
}
}
}
a = Math.exp(P['w'] * loh - P['x'] * arg);
b = P['x'] * loh + P['w'] * arg;
return new Quaternion(
a * Math.cos(b),
a * Math.sin(b), 0, 0);
}
}
// Normal quaternion behavior
// q^p = e^ln(q^p) = e^(ln(q)*p)
return this.log().mul(P).exp();
}
|
javascript
|
{
"resource": ""
}
|
|
q50050
|
train
|
function(w, x, y, z) {
parse(P, w, x, y, z);
var eps = Quaternion['EPSILON'];
// maybe check for NaN's here?
return Math.abs(P['w'] - this['w']) < eps
&& Math.abs(P['x'] - this['x']) < eps
&& Math.abs(P['y'] - this['y']) < eps
&& Math.abs(P['z'] - this['z']) < eps;
}
|
javascript
|
{
"resource": ""
}
|
|
q50051
|
train
|
function() {
var w = this['w'];
var x = this['x'];
var y = this['y'];
var z = this['z'];
var ret = '';
if (isNaN(w) || isNaN(x) || isNaN(y) || isNaN(z)) {
return 'NaN';
}
// Alternative design?
// '(%f, [%f %f %f])'
ret = numToStr(w, '', ret);
ret += numToStr(x, 'i', ret);
ret += numToStr(y, 'j', ret);
ret += numToStr(z, 'k', ret);
if ('' === ret)
return '0';
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q50052
|
train
|
function(d2) {
var w = this['w'];
var x = this['x'];
var y = this['y'];
var z = this['z'];
var n = w * w + x * x + y * y + z * z;
var s = n === 0 ? 0 : 2 / n;
var wx = s * w * x, wy = s * w * y, wz = s * w * z;
var xx = s * x * x, xy = s * x * y, xz = s * x * z;
var yy = s * y * y, yz = s * y * z, zz = s * z * z;
if (d2) {
return [
[1 - (yy + zz), xy - wz, xz + wy],
[xy + wz, 1 - (xx + zz), yz - wx],
[xz - wy, yz + wx, 1 - (xx + yy)]];
}
return [
1 - (yy + zz), xy - wz, xz + wy,
xy + wz, 1 - (xx + zz), yz - wx,
xz - wy, yz + wx, 1 - (xx + yy)];
}
|
javascript
|
{
"resource": ""
}
|
|
q50053
|
train
|
function(v) {
// [0, v'] = Q * [0, v] * Q'
// Q
var w1 = this['w'];
var x1 = this['x'];
var y1 = this['y'];
var z1 = this['z'];
// [0, v]
var w2 = 0;
var x2 = v[0];
var y2 = v[1];
var z2 = v[2];
// Q * [0, v]
var w3 = /*w1 * w2*/ -x1 * x2 - y1 * y2 - z1 * z2;
var x3 = w1 * x2 + /*x1 * w2 +*/ y1 * z2 - z1 * y2;
var y3 = w1 * y2 + /*y1 * w2 +*/ z1 * x2 - x1 * z2;
var z3 = w1 * z2 + /*z1 * w2 +*/ x1 * y2 - y1 * x2;
var w4 = w3 * w1 + x3 * x1 + y3 * y1 + z3 * z1;
var x4 = x3 * w1 - w3 * x1 - y3 * z1 + z3 * y1;
var y4 = y3 * w1 - w3 * y1 - z3 * x1 + x3 * z1;
var z4 = z3 * w1 - w3 * z1 - x3 * y1 + y3 * x1;
return [x4, y4, z4];
}
|
javascript
|
{
"resource": ""
}
|
|
q50054
|
createPrototype
|
train
|
function createPrototype (type, options) {
return new DuckType({
name: options && options.name || null,
test: function test (object) {
return (object instanceof type);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50055
|
createCombi
|
train
|
function createCombi (types, options) {
var tests = types.map(function (type) {
return ducktype(type).test;
});
return new DuckType({
name: options && options.name || null,
test: function test (object) {
for (var i = 0, ii = tests.length; i < ii; i++) {
if (tests[i](object)) {
return true;
}
}
return false;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50056
|
createFunction
|
train
|
function createFunction (test, options) {
return new DuckType({
name: options && options.name || null,
test: test
});
}
|
javascript
|
{
"resource": ""
}
|
q50057
|
createRegExp
|
train
|
function createRegExp (regexp, options) {
return new DuckType({
name: options && options.name || null,
test: function (object) {
return ((object instanceof String) || typeof(object) === 'string') && regexp.test(object);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50058
|
isUrl
|
train
|
function isUrl(string){
if (typeof string !== 'string') {
return false;
}
var match = string.match(protocolAndDomainRE);
if (!match) {
return false;
}
var everythingAfterProtocol = match[1];
if (!everythingAfterProtocol) {
return false;
}
return localhostDomainRE.test(everythingAfterProtocol) ||
nonLocalhostDomainRE.test(everythingAfterProtocol);
}
|
javascript
|
{
"resource": ""
}
|
q50059
|
MediaType
|
train
|
function MediaType (type, subtype, suffix) {
this.type = type
this.subtype = subtype
this.suffix = suffix
}
|
javascript
|
{
"resource": ""
}
|
q50060
|
checkAudioCodec
|
train
|
function checkAudioCodec(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('OPUS|PCMU|RAW'))
throw SyntaxError(key+' param is not one of [OPUS|PCMU|RAW] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50061
|
checkRTCStatsIceCandidatePairState
|
train
|
function checkRTCStatsIceCandidatePairState(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('frozen|waiting|inprogress|failed|succeeded|cancelled'))
throw SyntaxError(key+' param is not one of [frozen|waiting|inprogress|failed|succeeded|cancelled] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50062
|
checkGstreamerDotDetails
|
train
|
function checkGstreamerDotDetails(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('SHOW_MEDIA_TYPE|SHOW_CAPS_DETAILS|SHOW_NON_DEFAULT_PARAMS|SHOW_STATES|SHOW_FULL_PARAMS|SHOW_ALL|SHOW_VERBOSE'))
throw SyntaxError(key+' param is not one of [SHOW_MEDIA_TYPE|SHOW_CAPS_DETAILS|SHOW_NON_DEFAULT_PARAMS|SHOW_STATES|SHOW_FULL_PARAMS|SHOW_ALL|SHOW_VERBOSE] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50063
|
checkRTCStatsIceCandidateType
|
train
|
function checkRTCStatsIceCandidateType(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('host|serverreflexive|peerreflexive|relayed'))
throw SyntaxError(key+' param is not one of [host|serverreflexive|peerreflexive|relayed] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50064
|
checkConnectionState
|
train
|
function checkConnectionState(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('DISCONNECTED|CONNECTED'))
throw SyntaxError(key+' param is not one of [DISCONNECTED|CONNECTED] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50065
|
checkRTCDataChannelState
|
train
|
function checkRTCDataChannelState(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('connecting|open|closing|closed'))
throw SyntaxError(key+' param is not one of [connecting|open|closing|closed] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50066
|
checkMediaState
|
train
|
function checkMediaState(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('DISCONNECTED|CONNECTED'))
throw SyntaxError(key+' param is not one of [DISCONNECTED|CONNECTED] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50067
|
checkMediaFlowState
|
train
|
function checkMediaFlowState(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('FLOWING|NOT_FLOWING'))
throw SyntaxError(key+' param is not one of [FLOWING|NOT_FLOWING] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50068
|
AudioCaps
|
train
|
function AudioCaps(audioCapsDict){
if(!(this instanceof AudioCaps))
return new AudioCaps(audioCapsDict)
audioCapsDict = audioCapsDict || {}
// Check audioCapsDict has the required fields
//
// checkType('AudioCodec', 'audioCapsDict.codec', audioCapsDict.codec, {required: true});
//
// checkType('int', 'audioCapsDict.bitrate', audioCapsDict.bitrate, {required: true});
//
// Init parent class
AudioCaps.super_.call(this, audioCapsDict)
// Set object properties
Object.defineProperties(this, {
codec: {
writable: true,
enumerable: true,
value: audioCapsDict.codec
},
bitrate: {
writable: true,
enumerable: true,
value: audioCapsDict.bitrate
}
})
}
|
javascript
|
{
"resource": ""
}
|
q50069
|
RTCPeerConnectionStats
|
train
|
function RTCPeerConnectionStats(rTCPeerConnectionStatsDict){
if(!(this instanceof RTCPeerConnectionStats))
return new RTCPeerConnectionStats(rTCPeerConnectionStatsDict)
rTCPeerConnectionStatsDict = rTCPeerConnectionStatsDict || {}
// Check rTCPeerConnectionStatsDict has the required fields
//
// checkType('int64', 'rTCPeerConnectionStatsDict.dataChannelsOpened', rTCPeerConnectionStatsDict.dataChannelsOpened, {required: true});
//
// checkType('int64', 'rTCPeerConnectionStatsDict.dataChannelsClosed', rTCPeerConnectionStatsDict.dataChannelsClosed, {required: true});
//
// Init parent class
RTCPeerConnectionStats.super_.call(this, rTCPeerConnectionStatsDict)
// Set object properties
Object.defineProperties(this, {
dataChannelsOpened: {
writable: true,
enumerable: true,
value: rTCPeerConnectionStatsDict.dataChannelsOpened
},
dataChannelsClosed: {
writable: true,
enumerable: true,
value: rTCPeerConnectionStatsDict.dataChannelsClosed
}
})
}
|
javascript
|
{
"resource": ""
}
|
q50070
|
VideoCaps
|
train
|
function VideoCaps(videoCapsDict){
if(!(this instanceof VideoCaps))
return new VideoCaps(videoCapsDict)
videoCapsDict = videoCapsDict || {}
// Check videoCapsDict has the required fields
//
// checkType('VideoCodec', 'videoCapsDict.codec', videoCapsDict.codec, {required: true});
//
// checkType('Fraction', 'videoCapsDict.framerate', videoCapsDict.framerate, {required: true});
//
// Init parent class
VideoCaps.super_.call(this, videoCapsDict)
// Set object properties
Object.defineProperties(this, {
codec: {
writable: true,
enumerable: true,
value: videoCapsDict.codec
},
framerate: {
writable: true,
enumerable: true,
value: videoCapsDict.framerate
}
})
}
|
javascript
|
{
"resource": ""
}
|
q50071
|
checkVideoCodec
|
train
|
function checkVideoCodec(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('VP8|H264|RAW'))
throw SyntaxError(key+' param is not one of [VP8|H264|RAW] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50072
|
checkFilterType
|
train
|
function checkFilterType(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('AUDIO|AUTODETECT|VIDEO'))
throw SyntaxError(key+' param is not one of [AUDIO|AUTODETECT|VIDEO] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50073
|
checkMediaType
|
train
|
function checkMediaType(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('AUDIO|DATA|VIDEO'))
throw SyntaxError(key+' param is not one of [AUDIO|DATA|VIDEO] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50074
|
EndpointStats
|
train
|
function EndpointStats(endpointStatsDict){
if(!(this instanceof EndpointStats))
return new EndpointStats(endpointStatsDict)
endpointStatsDict = endpointStatsDict || {}
// Check endpointStatsDict has the required fields
//
// checkType('double', 'endpointStatsDict.audioE2ELatency', endpointStatsDict.audioE2ELatency, {required: true});
//
// checkType('double', 'endpointStatsDict.videoE2ELatency', endpointStatsDict.videoE2ELatency, {required: true});
//
// checkType('MediaLatencyStat', 'endpointStatsDict.E2ELatency', endpointStatsDict.E2ELatency, {isArray: true, required: true});
//
// Init parent class
EndpointStats.super_.call(this, endpointStatsDict)
// Set object properties
Object.defineProperties(this, {
audioE2ELatency: {
writable: true,
enumerable: true,
value: endpointStatsDict.audioE2ELatency
},
videoE2ELatency: {
writable: true,
enumerable: true,
value: endpointStatsDict.videoE2ELatency
},
E2ELatency: {
writable: true,
enumerable: true,
value: endpointStatsDict.E2ELatency
}
})
}
|
javascript
|
{
"resource": ""
}
|
q50075
|
Fraction
|
train
|
function Fraction(fractionDict){
if(!(this instanceof Fraction))
return new Fraction(fractionDict)
fractionDict = fractionDict || {}
// Check fractionDict has the required fields
//
// checkType('int', 'fractionDict.numerator', fractionDict.numerator, {required: true});
//
// checkType('int', 'fractionDict.denominator', fractionDict.denominator, {required: true});
//
// Init parent class
Fraction.super_.call(this, fractionDict)
// Set object properties
Object.defineProperties(this, {
numerator: {
writable: true,
enumerable: true,
value: fractionDict.numerator
},
denominator: {
writable: true,
enumerable: true,
value: fractionDict.denominator
}
})
}
|
javascript
|
{
"resource": ""
}
|
q50076
|
checkMediaTranscodingState
|
train
|
function checkMediaTranscodingState(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('TRANSCODING|NOT_TRANSCODING'))
throw SyntaxError(key+' param is not one of [TRANSCODING|NOT_TRANSCODING] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50077
|
checkServerType
|
train
|
function checkServerType(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('KMS|KCS'))
throw SyntaxError(key+' param is not one of [KMS|KCS] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50078
|
ElementStats
|
train
|
function ElementStats(elementStatsDict){
if(!(this instanceof ElementStats))
return new ElementStats(elementStatsDict)
elementStatsDict = elementStatsDict || {}
// Check elementStatsDict has the required fields
//
// checkType('double', 'elementStatsDict.inputAudioLatency', elementStatsDict.inputAudioLatency, {required: true});
//
// checkType('double', 'elementStatsDict.inputVideoLatency', elementStatsDict.inputVideoLatency, {required: true});
//
// checkType('MediaLatencyStat', 'elementStatsDict.inputLatency', elementStatsDict.inputLatency, {isArray: true, required: true});
//
// Init parent class
ElementStats.super_.call(this, elementStatsDict)
// Set object properties
Object.defineProperties(this, {
inputAudioLatency: {
writable: true,
enumerable: true,
value: elementStatsDict.inputAudioLatency
},
inputVideoLatency: {
writable: true,
enumerable: true,
value: elementStatsDict.inputVideoLatency
},
inputLatency: {
writable: true,
enumerable: true,
value: elementStatsDict.inputLatency
}
})
}
|
javascript
|
{
"resource": ""
}
|
q50079
|
checkUriEndpointState
|
train
|
function checkUriEndpointState(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('STOP|START|PAUSE'))
throw SyntaxError(key+' param is not one of [STOP|START|PAUSE] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q50080
|
RembParams
|
train
|
function RembParams(rembParamsDict){
if(!(this instanceof RembParams))
return new RembParams(rembParamsDict)
rembParamsDict = rembParamsDict || {}
// Check rembParamsDict has the required fields
//
// checkType('int', 'rembParamsDict.packetsRecvIntervalTop', rembParamsDict.packetsRecvIntervalTop);
//
// checkType('float', 'rembParamsDict.exponentialFactor', rembParamsDict.exponentialFactor);
//
// checkType('int', 'rembParamsDict.linealFactorMin', rembParamsDict.linealFactorMin);
//
// checkType('float', 'rembParamsDict.linealFactorGrade', rembParamsDict.linealFactorGrade);
//
// checkType('float', 'rembParamsDict.decrementFactor', rembParamsDict.decrementFactor);
//
// checkType('float', 'rembParamsDict.thresholdFactor', rembParamsDict.thresholdFactor);
//
// checkType('int', 'rembParamsDict.upLosses', rembParamsDict.upLosses);
//
// checkType('int', 'rembParamsDict.rembOnConnect', rembParamsDict.rembOnConnect);
//
// Init parent class
RembParams.super_.call(this, rembParamsDict)
// Set object properties
Object.defineProperties(this, {
packetsRecvIntervalTop: {
writable: true,
enumerable: true,
value: rembParamsDict.packetsRecvIntervalTop
},
exponentialFactor: {
writable: true,
enumerable: true,
value: rembParamsDict.exponentialFactor
},
linealFactorMin: {
writable: true,
enumerable: true,
value: rembParamsDict.linealFactorMin
},
linealFactorGrade: {
writable: true,
enumerable: true,
value: rembParamsDict.linealFactorGrade
},
decrementFactor: {
writable: true,
enumerable: true,
value: rembParamsDict.decrementFactor
},
thresholdFactor: {
writable: true,
enumerable: true,
value: rembParamsDict.thresholdFactor
},
upLosses: {
writable: true,
enumerable: true,
value: rembParamsDict.upLosses
},
rembOnConnect: {
writable: true,
enumerable: true,
value: rembParamsDict.rembOnConnect
}
})
}
|
javascript
|
{
"resource": ""
}
|
q50081
|
train
|
function(page) {
if (this.output.name != 'website' || page.search === false) {
return page;
}
var text;
this.log.debug.ln('index page', page.path);
text = page.content;
// Decode HTML
text = Html.decode(text);
// Strip HTML tags
text = text.replace(/(<([^>]+)>)/ig, '');
text = text.replace(/[\n ]+/g, ' ');
var keywords = [];
if (page.search) {
keywords = page.search.keywords || [];
}
// Add to index
var doc = {
url: this.output.toURL(page.path),
title: page.title,
summary: page.description,
keywords: keywords.join(' '),
body: text
};
documentsStore[doc.url] = doc;
return page;
}
|
javascript
|
{
"resource": ""
}
|
|
q50082
|
train
|
function() {
if (this.output.name != 'website') return;
this.log.debug.ln('write search index');
return this.output.writeFile('search_plus_index.json', JSON.stringify(documentsStore));
}
|
javascript
|
{
"resource": ""
}
|
|
q50083
|
toColor
|
train
|
function toColor(str, opacity) {
var rgb = [0, 0, 0, opacity || 0.75];
try {
for (var i = 0; i < str.length; i++) {
var v = str.charCodeAt(i);
var idx = v % 3;
rgb[idx] = (rgb[i % 3] + (13 * (v % 13))) % 20;
}
} finally {
return 'rgba(' +
rgb.map(function(c, idx) {
return idx === 3 ? c : (4 + c) * 17;
}).join(',') + ')';
}
}
|
javascript
|
{
"resource": ""
}
|
q50084
|
train
|
function(configStrategy) {
if (!configStrategy.hasOwnProperty('cache') || !configStrategy.cache.hasOwnProperty('engine')) {
throw 'CACHING_ENGINE parameter is missing.';
}
if (configStrategy.cache.engine === undefined) {
throw 'CACHING_ENGINE parameter is empty.';
}
// Grab the required details from the configStrategy.
const cacheEngine = configStrategy.cache.engine.toString();
let isConsistentBehaviour = configStrategy.cache.consistentBehavior;
// Sanitize isConsistentBehaviour
isConsistentBehaviour = isConsistentBehaviour === undefined ? true : isConsistentBehaviour != '0';
// Stores the endpoint for key generation of instanceMap.
let endpointDetails = null;
// Generate endpointDetails for key generation of instanceMap.
if (cacheEngine == 'redis') {
const redisMandatoryParams = ['host', 'port', 'password', 'enableTsl'];
// Check if all the mandatory connection parameters for Redis are available or not.
for (let i = 0; i < redisMandatoryParams.length; i++) {
if (!configStrategy.cache.hasOwnProperty(redisMandatoryParams[i])) {
throw 'Redis - mandatory connection parameters missing.';
}
if (configStrategy.cache[redisMandatoryParams[i]] === undefined) {
throw 'Redis - connection parameters are empty.';
}
}
endpointDetails =
configStrategy.cache.host.toLowerCase() +
'-' +
configStrategy.cache.port.toString() +
'-' +
configStrategy.cache.enableTsl.toString();
} else if (cacheEngine == 'memcached') {
if (!configStrategy.cache.hasOwnProperty('servers')) {
throw 'Memcached - mandatory connection parameters missing.';
}
if (configStrategy.cache.servers === undefined) {
throw 'MEMCACHE_SERVERS(configStrategy.cache.servers) parameter is empty. ';
}
endpointDetails = configStrategy.cache.servers.join(',').toLowerCase();
} else {
endpointDetails = configStrategy.cache.namespace || '';
}
return cacheEngine + '-' + isConsistentBehaviour.toString() + '-' + endpointDetails;
}
|
javascript
|
{
"resource": ""
}
|
|
q50085
|
train
|
function(lifetimeInSec) {
lifetimeInSec = Number(lifetimeInSec);
if (isNaN(lifetimeInSec)) {
lifetimeInSec = 0;
}
let lifetime = lifetimeInSec * 1000;
if (lifetime <= 0) {
this.expires = Date.now();
} else {
this.expires = Date.now() + lifetime;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50086
|
createTypedef
|
train
|
function createTypedef(context, typeName, value) {
if (value instanceof Reference) {
value = value.resolve(context);
}
context.results[typeName] = value;
return value;
}
|
javascript
|
{
"resource": ""
}
|
q50087
|
setSpaAlias
|
train
|
function setSpaAlias(alias, moduleName, path) {
let resolvedPath = spaPath(path);
if (!fs.existsSync(resolvedPath)) {
resolvedPath = outPath(path);
}
alias['sky-pages-internal/' + moduleName] = resolvedPath;
}
|
javascript
|
{
"resource": ""
}
|
q50088
|
resolve
|
train
|
function resolve(url, localUrl, chunks, skyPagesConfig) {
let host = skyPagesConfig.skyux.host.url;
let config = {
scripts: getScripts(chunks),
localUrl: localUrl
};
if (skyPagesConfig.skyux.app && skyPagesConfig.skyux.app.externals) {
config.externals = skyPagesConfig.skyux.app.externals;
}
// Trim leading slash since getAppBase adds it
if (url && url.charAt(0) === '/') {
url = url.substring(1);
}
// Trim trailing slash since geAppBase adds it
if (host && host.charAt(host.length - 1) === '/') {
host = host.slice(0, -1);
}
const delimeter = url.indexOf('?') === -1 ? '?' : '&';
const encoded = new Buffer(JSON.stringify(config)).toString('base64');
const base = skyPagesConfigUtil.getAppBase(skyPagesConfig);
const resolved = `${host}${base}${url}${delimeter}local=true&_cfg=${encoded}`;
return resolved;
}
|
javascript
|
{
"resource": ""
}
|
q50089
|
getScripts
|
train
|
function getScripts(chunks) {
let scripts = [];
// Used when skipping the build, short-circuit to return metadata
if (chunks.metadata) {
return chunks.metadata;
}
sorter.dependency(chunks).forEach((chunk) => {
scripts.push({
name: chunk.files[0]
});
});
return scripts;
}
|
javascript
|
{
"resource": ""
}
|
q50090
|
WebpackPluginDone
|
train
|
function WebpackPluginDone() {
let launched = false;
this.plugin('done', (stats) => {
if (!launched) {
launched = true;
browser(argv, skyPagesConfig, stats, this.options.devServer.port);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50091
|
getRoutesForConfig
|
train
|
function getRoutesForConfig(routes) {
return routes.map(route => ({
routePath: route.routePath === '?' ? '' : route.routePath.replace(/\#/g, ''),
routeParams: route.routeParams
}));
}
|
javascript
|
{
"resource": ""
}
|
q50092
|
killServers
|
train
|
function killServers(exitCode) {
logger.info('Cleaning up running servers');
if (seleniumServer) {
logger.info('Closing selenium server');
seleniumServer.kill();
seleniumServer = null;
}
// Catch protractor's "Kitchen Sink" error.
if (exitCode === 199) {
logger.warn('Supressing protractor\'s "kitchen sink" error 199');
exitCode = 0;
}
server.stop();
logger.info(`Execution Time: ${(new Date().getTime() - start) / 1000} seconds`);
logger.info(`Exiting process with ${exitCode}`);
process.exit(exitCode || 0);
}
|
javascript
|
{
"resource": ""
}
|
q50093
|
spawnProtractor
|
train
|
function spawnProtractor(configPath, chunks, port, skyPagesConfig) {
logger.info('Running Protractor');
protractorLauncher.init(configPath, {
params: {
localUrl: `https://localhost:${port}`,
chunks: chunks,
skyPagesConfig: skyPagesConfig
}
});
process.on('exit', killServers);
}
|
javascript
|
{
"resource": ""
}
|
q50094
|
getChromeDriverVersion
|
train
|
function getChromeDriverVersion() {
return new Promise(resolve => {
const defaultVersion = 'latest';
matcher.getChromeDriverVersion()
.then(result => {
if (result.chromeDriverVersion) {
resolve(result.chromeDriverVersion);
} else {
resolve(defaultVersion);
}
})
.catch(() => resolve(defaultVersion));
});
}
|
javascript
|
{
"resource": ""
}
|
q50095
|
spawnSelenium
|
train
|
function spawnSelenium(configPath) {
const config = require(configPath).config;
return new Promise((resolve, reject) => {
logger.info('Spawning selenium...');
// Assumes we're running selenium ourselves, so we should prep it
if (config.seleniumAddress) {
logger.info('Installing Selenium...');
selenium.install({ logger: logger.info }, () => {
logger.info('Selenium installed. Starting...');
selenium.start((err, child) => {
if (err) {
reject(err);
return;
}
seleniumServer = child;
logger.info('Selenium server is ready.');
resolve();
});
});
// Otherwise we need to prep protractor's selenium
} else {
logger.info(`Getting webdriver version.`);
getChromeDriverVersion().then(version => {
logger.info(`Updating webdriver to version ${version}`);
const webdriverManagerPath = path.resolve(
'node_modules',
'.bin',
'webdriver-manager'
);
const results = spawn.sync(
webdriverManagerPath,
[
'update',
'--standalone',
'false',
'--gecko',
'false',
'--versions.chrome',
version
],
spawnOptions
);
if (results.error) {
reject(results.error);
return;
}
logger.info('Selenium server is ready.');
resolve();
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50096
|
spawnBuild
|
train
|
function spawnBuild(argv, skyPagesConfig, webpack) {
if (argv.build === false) {
logger.info('Skipping build step');
const file = 'dist/metadata.json';
if (!fs.existsSync(file)) {
logger.info(`Unable to skip build step. "${file}" not found.`);
} else {
return Promise.resolve({
metadata: fs.readJsonSync(file)
});
}
}
return build(argv, skyPagesConfig, webpack)
.then(stats => stats.toJson().chunks);
}
|
javascript
|
{
"resource": ""
}
|
q50097
|
e2e
|
train
|
function e2e(command, argv, skyPagesConfig, webpack) {
start = new Date().getTime();
process.on('SIGINT', killServers);
const specsPath = path.resolve(process.cwd(), 'e2e/**/*.e2e-spec.ts');
const specsGlob = glob.sync(specsPath);
const configPath = configResolver.resolve(command, argv);
if (specsGlob.length === 0) {
logger.info('No spec files located. Skipping e2e command.');
return killServers(0);
}
server.start()
.then((port) => {
argv.assets = 'https://localhost:' + port;
// The assets URL is built by combining the assets URL above with
// the app's root directory, but in e2e tests the assets files
// are served directly from the root. This will back up a directory
// so that asset URLs are built relative to the root rather than
// the app's root directory.
argv.assetsrel = '../';
return Promise
.all([
spawnBuild(argv, skyPagesConfig, webpack),
port,
spawnSelenium(configPath)
]);
})
.then(([chunks, port]) => {
spawnProtractor(
configPath,
chunks,
port,
skyPagesConfig
);
})
.catch(err => {
logger.error(err);
killServers(1);
});
}
|
javascript
|
{
"resource": ""
}
|
q50098
|
bindServe
|
train
|
function bindServe() {
return new Promise((resolve, reject) => {
// Logging "warnings" but not rejecting test
webpackServer.stderr.on('data', data => log(data));
webpackServer.stdout.on('data', data => {
const dataAsString = log(data);
if (dataAsString.indexOf('webpack: Compiled successfully.') > -1) {
resolve(_port);
}
if (dataAsString.indexOf('webpack: Failed to compile.') > -1) {
reject(dataAsString);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q50099
|
exec
|
train
|
function exec(cmd, args, opts) {
console.log(`Running command: ${cmd} ${args.join(' ')}`);
const cp = childProcessSpawn(cmd, args, opts);
cp.stdout.on('data', data => log(data));
cp.stderr.on('data', data => log(data));
return new Promise((resolve, reject) => {
cp.on('error', err => reject(log(err)));
cp.on('exit', code => resolve(code));
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.