_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q40700
assetQueue
train
function assetQueue(addr, queue, options) { return createChannel(addr).then(data => { let ch = data[1]; return ch.assertQueue(queue, options).then(q => [ch, q]); }); }
javascript
{ "resource": "" }
q40701
createChannel
train
function createChannel(addr) { return amqp.connect(genAddr(addr)).then(conn => { return conn.createChannel().then(ch => { connections.push(conn); return [conn, ch]; }); }, debugError); }
javascript
{ "resource": "" }
q40702
SubClass
train
function SubClass() { var ret; // Call the parent constructor. parent.apply(this, arguments); // Only call initialize in self constructor. if(this.constructor === SubClass && this.initialize) { ret = this.initialize.apply(this, arguments); } return ret ? ret : this; }
javascript
{ "resource": "" }
q40703
train
function (event) { //event = $.event.fix(event); // jQuery event normalization. var element = this;//event.target; // @ TextNode -> nodeType == 3 element = (element.nodeType == 3) ? element.parentNode : element; if (opt['disableInInput']) { // Disable shortcut keys in Input, Textarea fields var target = element;//$(element); if (target.tagName == "INPUT" || target.tagName == "TEXTAREA") { return; } } var code = event.which, type = event.type, character = String.fromCharCode(code).toLowerCase(), special = that.special_keys[code], shift = event.shiftKey, ctrl = event.ctrlKey, alt = event.altKey, propagate = true, // default behaivour mapPoint = null; // in opera + safari, the event.target is unpredictable. // for example: 'keydown' might be associated with HtmlBodyElement // or the element where you last clicked with your mouse. if (opt.checkParent) { // while (!that.all[element] && element.parentNode){ while (!element['hotkeys'] && element.parentNode) { element = element.parentNode; } } // var cbMap = that.all[element].events[type].callbackMap; var cbMap = element['hotkeys'].events[type].callbackMap; if (!shift && !ctrl && !alt) { // No Modifiers mapPoint = cbMap[special] || cbMap[character]; } // deals with combinaitons (alt|ctrl|shift+anything) else { var modif = ''; if (alt) modif += 'alt+'; if (ctrl) modif += 'ctrl+'; if (shift) modif += 'shift+'; // modifiers + special keys or modifiers + characters or modifiers + shift characters mapPoint = cbMap[modif + special] || cbMap[modif + character] || cbMap[modif + that.shift_nums[character]]; } if (mapPoint) { mapPoint.cb(event); if (!mapPoint.propagate) { event.stopPropagation(); event.preventDefault(); return false; } } }
javascript
{ "resource": "" }
q40704
init
train
function init() { return user.initComplete ? Q.when(user) : userService.findMe() .then(function setUserLocal(me) { me = me || {}; // pull out the user _.extend(user, me.user); // return the user and notify init complete user.initComplete = true; eventBus.emit('user.init'); return user; }); }
javascript
{ "resource": "" }
q40705
filteredFiles
train
function filteredFiles(folder, pattern) { var files = []; if (fs.existsSync(folder)){ fs.readdirSync(folder).forEach(function(file) { if (file.match(pattern) != null) files.push(file); }); } return files; }
javascript
{ "resource": "" }
q40706
loadViews
train
function loadViews(timbit) { timbit.views = []; var pattern = new RegExp('\.' + timbits.app.settings['view engine'] + '$') , folder = path.join(config.home, 'views', timbit.viewBase); if (fs.existsSync(folder)) { var files = fs.readdirSync(folder); files.forEach(function(file) { timbit.views.push(file.replace(pattern, '')); }); } // We will attempt the default view anyway and hope the timbit knows what it is doing. if (timbit.views.length === 0) timbit.views.push(timbit.defaultView); }
javascript
{ "resource": "" }
q40707
compileTemplate
train
function compileTemplate(name) { var filename = path.join(__dirname, "templates", name + '.hjs'); var contents = fs.readFileSync(filename); return hogan.compile(contents.toString()); }
javascript
{ "resource": "" }
q40708
allowedMethods
train
function allowedMethods(methods) { // default values var methodsAllowed = { 'GET': true, 'POST': false, 'PUT': false, 'HEAD': false, 'DELETE': false }; // check and override if one of the default methods for (var key in methods) { var newKey = key.toUpperCase(); if ( methodsAllowed[newKey]!=undefined) { methodsAllowed[newKey] = Boolean(methods[key]); } } return methodsAllowed; }
javascript
{ "resource": "" }
q40709
text
train
function text(element) { var type = element.nodeType , value = ''; if (1 === type || 9 === type || 11 === type) { // // Use `textContent` instead of `innerText` as it's inconsistent with new // lines. // if ('string' === typeof element.textContent) return element.textContent; for (element = element.firstChild; element; element = element.nextSibling) { value += text(element); } } return 3 === type || 4 === type ? element.nodeValue : value; }
javascript
{ "resource": "" }
q40710
attribute
train
function attribute(element, name, val) { return supports.attributes || !supports.html ? element.getAttribute(name) : (val = element.getAttributeNode(name)) && val.specified ? val.value : ''; }
javascript
{ "resource": "" }
q40711
get
train
function get(element) { var name = element.nodeName.toLowerCase() , value; if (get.parser[element.type] && hasOwn.call(get.parser, element.type)) { value = get.parser[element.type](element); } else if (get.parser[name] && hasOwn.call(get.parser, name)) { value = get.parser[name](element); } if (value !== undefined) return value; value = element.value; return 'string' === typeof value ? value.replace(/\r/g, '') : value === null ? '' : value; }
javascript
{ "resource": "" }
q40712
execute
train
function execute(req, res) { req.conn.monitor(this); res.send(null, Constants.OK); }
javascript
{ "resource": "" }
q40713
routeMatcher
train
function routeMatcher(keys) { return match => { const parseParams = paramsParser(keys); if(match) { const params = parseParams(match); return { match, keys, params, } } } }
javascript
{ "resource": "" }
q40714
train
function(msg, code, errorStr, cb1) { return function(error, data) { if (error) { error = json_rpc.newSysError(msg, code, errorStr, error); } cb1(error, data); }; }
javascript
{ "resource": "" }
q40715
train
function(project_dir) { var mDoc = xml_helpers.parseElementtreeSync(path.join(project_dir, 'AndroidManifest.xml')); return mDoc._root.attrib['package']; }
javascript
{ "resource": "" }
q40716
tryWrap
train
function tryWrap(fn) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return function (def) { try { return fn.apply(void 0, args); } catch (ex) { if (is_1.isFunction(def)) return def(ex); return to_1.toDefault(def); } }; }
javascript
{ "resource": "" }
q40717
tryRequire
train
function tryRequire(name, def, isRoot) { function _require() { if (!is_1.isNode()) /* istanbul ignore next */ return to_1.toDefault(null, def); if (isRoot) return require.main.require(name); return require(name); } return tryWrap(_require)(def); }
javascript
{ "resource": "" }
q40718
getPascalCase
train
function getPascalCase(val) { var parts = val.split('.'); var newVal = ''; for (var i = 0; i < parts.length; i++) { newVal += parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } return newVal; }
javascript
{ "resource": "" }
q40719
mouseup_callback
train
function mouseup_callback(e) { var press_time = new Date().getTime() - mouse_down_time; if (press_time < duration) { // cancel the timeout clearTimeout(timeout); // call the shortCallback if provided if (typeof shortCallback === "function") { shortCallback.call($(this), e); } else if (typeof shortCallback === "undefined") { ; } else { $.error('Optional callback for short press should be a function.'); } } }
javascript
{ "resource": "" }
q40720
train
function () { var series = this, points = series.points, options, level, dataLabelsGroup = this.dataLabelsGroup, dataLabels; each(points, function (point) { if (point.node.isVisible) { level = series.levelMap[point.level]; if (!point.isLeaf || level) { options = undefined; // If not a leaf, then label should be disabled as default if (!point.isLeaf) { options = {enabled: false}; } if (level) { dataLabels = level.dataLabels; if (dataLabels) { options = merge(options, dataLabels); series._hasPointLabels = true; } } options = merge(options, point.options.dataLabels); point.dlOptions = options; } else { delete point.dlOptions; } } }); this.dataLabelsGroup = this.group; Series.prototype.drawDataLabels.call(this); this.dataLabelsGroup = dataLabelsGroup; }
javascript
{ "resource": "" }
q40721
train
function () { var series = this, points = series.points, seriesOptions = series.options, attr, hover, level; each(points, function (point) { if (point.node.isVisible) { level = series.levelMap[point.level]; attr = { stroke: seriesOptions.borderColor, 'stroke-width': seriesOptions.borderWidth, dashstyle: seriesOptions.borderDashStyle, r: 0, // borderRadius gives wrong size relations and should always be disabled fill: pick(point.color, series.color) }; // Overwrite standard series options with level options if (level) { attr.stroke = level.borderColor || attr.stroke; attr['stroke-width'] = level.borderWidth || attr['stroke-width']; attr.dashstyle = level.borderDashStyle || attr.dashstyle; } // Merge with point attributes attr.stroke = point.borderColor || attr.stroke; attr['stroke-width'] = point.borderWidth || attr['stroke-width']; attr.dashstyle = point.borderDashStyle || attr.dashstyle; attr.zIndex = (1000 - (point.level * 2)); // Make a copy to prevent overwriting individual props point.pointAttr = merge(point.pointAttr); hover = point.pointAttr.hover; hover.zIndex = 1001; hover.fill = Color(attr.fill).brighten(seriesOptions.states.hover.brightness).get(); // If not a leaf, then remove fill if (!point.isLeaf) { if (pick(seriesOptions.interactByLeaf, !seriesOptions.allowDrillToNode)) { attr.fill = 'none'; delete hover.fill; } else { // TODO: let users set the opacity attr.fill = Color(attr.fill).setOpacity(0.15).get(); hover.fill = Color(hover.fill).setOpacity(0.75).get(); } } if (point.node.level <= series.nodeMap[series.rootNode].level) { attr.fill = 'none'; attr.zIndex = 0; delete hover.fill; } point.pointAttr[''] = H.extend(point.pointAttr[''], attr); if (point.dataLabel) { point.dataLabel.attr({ zIndex: (point.pointAttr[''].zIndex + 1) }); } } }); // Call standard drawPoints seriesTypes.column.prototype.drawPoints.call(this); each(points, function (point) { if (point.graphic) { point.graphic.attr(point.pointAttr['']); } }); // Set click events on points if (seriesOptions.allowDrillToNode) { series.drillTo(); } }
javascript
{ "resource": "" }
q40722
train
function () { var series = this, points = series.points; each(points, function (point) { var drillId, drillName; if (point.node.isVisible) { H.removeEvent(point, 'click'); if (point.graphic) { point.graphic.css({ cursor: 'default' }); } // Get the drill to id if (series.options.interactByLeaf) { drillId = series.drillToByLeaf(point); } else { drillId = series.drillToByGroup(point); } // If a drill id is returned, add click event and cursor. if (drillId) { drillName = series.nodeMap[series.rootNode].name || series.rootNode; if (point.graphic) { point.graphic.css({ cursor: 'pointer' }); } H.addEvent(point, 'click', function () { point.setState(''); // Remove hover series.drillToNode(drillId); series.showDrillUpButton(drillName); }); } } }); }
javascript
{ "resource": "" }
q40723
train
function (point) { var series = this, drillId = false; if ((point.node.level - series.nodeMap[series.rootNode].level) === 1 && !point.isLeaf) { drillId = point.id; } return drillId; }
javascript
{ "resource": "" }
q40724
train
function (point) { var series = this, drillId = false, nodeParent; if ((point.node.parent !== series.rootNode) && (point.isLeaf)) { nodeParent = point.node; while (!drillId) { nodeParent = series.nodeMap[nodeParent.parent]; if (nodeParent.parent === series.rootNode) { drillId = nodeParent.id; } } } return drillId; }
javascript
{ "resource": "" }
q40725
simplified
train
function simplified(js) { var is = false; var go = false; var here = 'out.html += '; // hardcoced var gone = ' '; // hardcoded to equal length var fixes = []; var lines = js.split('\n').map(function(line, index) { go = line.trim().startsWith(here); if (is && go) { line = line.replace(here, gone); fixes.push(index - 1); } is = go; return line; }); fixes.forEach(function(index) { if (index > -1) { var line = lines[index]; lines[index] = line.replace(/;$/, ' +'); } }); return lines.join('\n'); }
javascript
{ "resource": "" }
q40726
train
function (params) { // // Close the route once it has been handled. // var closeRoute = function () { that._closeRoute(dir, req, res, params); }; var async = new Async(closeRoute); routeConfig.handler(req, res, params, async); if (!async.started()) { // No async operation was started. // Close the route immediately. closeRoute(); } }
javascript
{ "resource": "" }
q40727
replace
train
function replace(node, {enter, leave}) { let rep = (enter && enter(node)) || node switch (rep.type) { // regular non-leaf nodes case 'Apply': for (let i = 0; i < rep.args.length; i++) { const arg = rep.args[i] rep.args[i] = replace(arg, {enter, leave}) } break // Skip leaf nodes because they're handled by the enter/leave calls at // the start/end of replace. case 'Identifier': case 'Number': case 'Ellipsis': break // irregular non-leaf nodes case 'Parentheses': rep.body = replace(rep.body, {enter, leave}) break case 'List': case 'Sequence': for (let i = 0; i < rep.items.length; i++) { const item = rep.items[i] rep.items[i] = replace(item, {enter, leave}) } break case 'System': for (let i = 0; i < rep.relations.length; i++) { const rel = rep.relations[i] rep.relations[i] = replace(rel, {enter, leave}) } break case 'Placeholder': // TODO(kevinb) handle children of the placeholder // e.g. we there might #a_0 could match x_0, y_0, z_0, etc. break default: throw new Error('unrecognized node') } return (leave && leave(rep)) || rep }
javascript
{ "resource": "" }
q40728
ErrorBadRequest
train
function ErrorBadRequest (message) { Error.call(this); // Add Information this.name = 'ErrorBadRequest'; this.type = 'client'; this.status = 400; if (message) { this.message = message; } }
javascript
{ "resource": "" }
q40729
train
function (source) { packageUrl = source; if (source && source.indexOf(bower.config.rhodecode.repo) != -1) { return true; } return Q.nfcall(registryClient.lookup.bind(registryClient), source) .then(function (entry) { if (entry && entry.url && entry.url.indexOf(bower.config.rhodecode.repo) != -1) { packageUrl = entry.url; return true } return false; }); }
javascript
{ "resource": "" }
q40730
train
function (endpoint) { var deferred = Q.defer(), tmpDir = tmp.dirSync().name, target = endpoint.target == '*' ? 'tip' : endpoint.target, url = endpoint.source + '/archive/' + target + '.zip?auth_token=' + bower.config.rhodecode.token, filePath = tmpDir + '/' + endpoint.name; bower.logger.debug('rhodecode: repo url', url); request.get(url) .pipe(fs.createWriteStream(filePath)) .on('close', function () { try { var buffer = readChunk.sync(filePath, 0, 262), fileType = FileType(buffer), fileExt = (fileType ? fileType.ext : 'txt'), newFilePath = filePath + '.' + fileExt; fs.renameSync(filePath, newFilePath); if (fileExt === 'zip') { var zip = new AdmZip(newFilePath), extractedDir; zip.getEntries().forEach(function (zipEntry) { zip.extractEntryTo(zipEntry.entryName, tmpDir, true, true); if (typeof extractedDir == 'undefined') { extractedDir = tmpDir + path.sep + zipEntry.entryName.replace(/(^[^\\\/]+).*/, '$1') } }); fs.unlink(newFilePath, function () { deferred.resolve({ tempPath: extractedDir, removeIgnores: true }); }); } else { deferred.reject("Invalid file, check on this link", url); } } catch (err) { deferred.reject(err); } }) .on('error', function (err) { deferred.reject(err); }); return deferred.promise; }
javascript
{ "resource": "" }
q40731
listItemsService
train
function listItemsService(app) { apiService.call(this); this.setApp(app); var service = this; /** * Default function used to resolve a result set * * @param {Error} err mongoose error * @param {Array} docs an array of mongoose documents or an array of objects */ this.mongOutcome = function(err, docs) { if (service.handleMongoError(err)) { service.outcome.success = true; service.deferred.resolve(docs); } }; /** * Resolve a mongoose query, paginated or not * This method can be used by the service to resolve a mongoose query * The paginate parameter is optional, if not provided, all documents will be resolved to the service promise. * the function to use for pagination is the 2nd argument of the getResultPromise() method * @see listItemsService.getResultPromise() * * @param {Query} find * @param {function} [paginate] (controller optional function to paginate result) * @param {function} [mongOutcome] optional function to customise resultset before resolving */ this.resolveQuery = function(find, paginate, mongOutcome) { if (!mongOutcome) { mongOutcome = this.mongOutcome; } find.exec(function(err, docs) { if (!err && typeof paginate === 'function') { return paginate(docs.length, find).exec(mongOutcome); } return mongOutcome(err, docs); }); }; /** * Services instances must implement * this method to resolve or reject the service promise * list items services have an additional parameter "paginate", this function will be given as parameter * by the controller * * @see listItemsController.paginate() * * @param {Object} params * @param {function} paginate * * @return {Promise} */ this.getResultPromise = function(params, paginate) { console.log('Not implemented'); return this.deferred.promise; }; }
javascript
{ "resource": "" }
q40732
initRedis
train
function initRedis(config, callback) { var self = this; protos.util.checkLocalPort(config.port, function(err) { if (err) { app.log("RedisTransport [%s:%s] %s", config.host, config.port, err.code); } else { // Set redis client self.client = redis.createClient(config.port, config.host, self.options); // Handle error event self.client.on('error', function(err) { callback.call(self, err); }); // Authenticate if password provided if (typeof config.password == 'string') { self.client.auth(config.password, function(err, res) { if (err) { app.log("RedisTransport: [%s:%s] %s", config.host, config.port, err.code); } else if (typeof config.db == 'number' && config.db !== 0) { self.client.select(config.db, function(err, res) { if (err) callback.call(self, err); else callback.call(self, null); }); } else { callback.call(self, null); } }); } else if (typeof config.db == 'number' && config.db !== 0) { self.client.select(config.db, function(err, res) { callback.call(self, err); }); } else { callback.call(self, null); } } }); }
javascript
{ "resource": "" }
q40733
listInstanceMethods
train
function listInstanceMethods (Model) { var classMethods = Object.keys(Model.schema.methods); for (var method in ModelPrototype) { if (!isPrivateMethod(method) && isFunction(ModelPrototype[method])) { classMethods.push(method); } } return classMethods; }
javascript
{ "resource": "" }
q40734
circulationSearch
train
function circulationSearch(array, current, direction, func) { let start = 0; let end = array.length - 1; if (direction === -1) { start = array.length - 1; end = 0; } for (let i = current; i * direction <= end * direction; i += direction) { if (func(array[i])) { return i; } } for (let i = start; i * direction < current * direction; i += direction) { if (func(array[i])) { return i; } } return -1; }
javascript
{ "resource": "" }
q40735
execute
train
function execute(req, res) { // store returns a number but we need to send // a bulk string reply var reply = req.exec.proxy(req, res); res.send(null, '' + reply); }
javascript
{ "resource": "" }
q40736
find
train
function find (client) { return function find (pushAppId) { const req = { url: pushAppId ? `${client.baseUrl}/rest/applications/${pushAppId}` : `${client.baseUrl}/rest/applications/` }; return request(client, req) .then((response) => { if (response.resp.statusCode !== 200) { return Promise.reject(response.body); } return Promise.resolve(response.body); }); }; }
javascript
{ "resource": "" }
q40737
update
train
function update (client) { return function update (pushApp) { const req = { url: `${client.baseUrl}/rest/applications/${pushApp.pushApplicationID}`, body: pushApp, method: 'PUT' }; return request(client, req) .then((response) => { if (response.resp.statusCode !== 204) { return Promise.reject(response.body); } return Promise.resolve(response.body); }); }; }
javascript
{ "resource": "" }
q40738
bootstrap
train
function bootstrap (client) { return function bootstrap (pushApp) { const req = { url: `${client.baseUrl}/rest/applications/bootstrap`, method: 'POST' }; const data = pushApp; // If they send in a string, then lets assume that is the location of the cert file // Otherwise, we will assume it is a Stream or Buffer and can just pass it along if (data.iosVariantName) { if (typeof data.iosCertificate === 'string') { data.iosCertificate = fs.createReadStream(data.iosCertificate); } data.iosProduction = data.iosProduction ? 'true' : 'false'; } req.formData = data; return request(client, req) .then((response) => { if (response.resp.statusCode !== 201) { return Promise.reject(response.body); } return Promise.resolve(response.body); }); }; }
javascript
{ "resource": "" }
q40739
train
function () { var res = arguments[0]; userOptions.emit('response', req, res); if (callback && userOptions.resCallback) callback.apply(this, arguments); res.on('end', function() { userOptions.emit('afterResponse', req, res); }); }
javascript
{ "resource": "" }
q40740
get_cookies
train
function get_cookies(url) { debug.assert(url).is('object'); debug.assert(url.host).is('string'); if(!is.array(_cookies[url.host])) { //debug.log('No cookies for host ', url.host); return undefined; } var cookies = ARRAY(_cookies[url.host]).map(function(cookie) { var i = cookie.indexOf(';'); return cookie.substr(0, ((i >= 1) ? i : cookie.length)); }).valueOf(); //debug.log('Cookies found (for host ', url.host ,'): ', cookies); return cookies; }
javascript
{ "resource": "" }
q40741
set_cookies
train
function set_cookies(url, cookies) { if(is.string(cookies)) { cookies = [cookies]; } debug.assert(url).is('object'); debug.assert(url.host).is('string'); debug.assert(cookies).is('array'); //debug.log('Saving cookies for host = ', url.host); if(!is.array(_cookies[url.host])) { _cookies[url.host] = cookies; //debug.log('Saved new cookies as: ', _cookies[url.host]); return; } var tmp = {}; function save_cookie(cookie) { var i = cookie.indexOf('='); var name = cookie.substr(0, ((i >= 1) ? i : cookie.length)); tmp[name] = cookie; } ARRAY(_cookies[url.host]).forEach(save_cookie); ARRAY(cookies).forEach(save_cookie); _cookies[url.host] = ARRAY(Object.keys(tmp)).map(function(key) { return tmp[key]; }).valueOf(); //debug.log('Saved new cookies as: ', _cookies[url.host]); }
javascript
{ "resource": "" }
q40742
grunt
train
function grunt(gruntInst, verbose, patch) { var mw = (patch || core.base()); mw.enabled = true; if (verbose) { mw.writeln = function (line) { if (mw.enabled) { gruntInst.verbose.writeln(line); } }; } else { mw.writeln = function (line) { if (mw.enabled) { gruntInst.log.writeln(line); } }; } if (!patch) { mw.toString = function () { return '<miniwrite-grunt>'; }; } return mw; }
javascript
{ "resource": "" }
q40743
stoogeStored
train
function stoogeStored(model, error) { if (typeof error != 'undefined') { callback(error); return; } try { self.stoogeIDsStored.push(model.get('id')); //console.log('Now we have moe ' + self.moe.get('id')); //console.log('model says ' + model.get('id')); if (self.stoogeIDsStored.length == 3) { // Now that first 3 stooges are stored lets retrieve and verify var actors = []; for (var i = 0; i < 3; i++) { actors.push(new self.Stooge()); actors[i].set('id', self.stoogeIDsStored[i]); spec.integrationStore.getModel(actors[i], stoogeRetrieved); } } } catch (err) { callback(err); } }
javascript
{ "resource": "" }
q40744
createLines
train
function createLines() { var moesLine = new self.StoogeLine(); moesLine.set('Scene', 1); moesLine.set('SetID', self.indoorSet.get('id')); moesLine.set('StoogeID', self.moe.get('id')); moesLine.set('Line', 'To be or not to be?'); var larrysLine = new self.StoogeLine(); larrysLine.set('Scene', 2); larrysLine.set('SetID', self.desertSet.get('id')); larrysLine.set('StoogeID', self.larry.get('id')); larrysLine.set('Line', 'That is the question!'); spec.integrationStore.putModel(moesLine, function (model, error) { if (typeof error != 'undefined') { callback(error); } else { spec.integrationStore.putModel(larrysLine, function (model, error) { if (typeof error != 'undefined') { callback(error); } else { createView(); } }); } }); }
javascript
{ "resource": "" }
q40745
toggle
train
function toggle(main, alt) { var mw = core.base(); mw.main = main; mw.alt = (alt || function () { }); mw.active = mw.main; mw.enabled = true; mw.swap = function () { mw.active = (mw.active !== mw.main ? mw.main : mw.alt); }; mw.writeln = function (line) { if (!mw.enabled) { return; } if (mw.enabled) { mw.active.writeln(line); } }; mw.toString = function () { return '<miniwrite-toggle>'; }; return mw; }
javascript
{ "resource": "" }
q40746
multi
train
function multi(list /*, ... */) { var mw = core.base(); mw.targets = (isArray(list) ? list : Array.prototype.slice.call(arguments.length, 0)); mw.enabled = true; mw.writeln = function (line) { if (mw.enabled) { for (var i = 0, ii = mw.targets.length; i < ii; i++) { mw.targets[i].writeln(line); } } }; mw.toString = function () { return '<miniwrite-multi>'; }; return mw; }
javascript
{ "resource": "" }
q40747
peek
train
function peek(target, callback) { var mw = core.base(); mw.enabled = true; mw.target = target; mw.callback = (callback || function (line /*, mw*/) { return line; }); mw.writeln = function (line) { if (mw.enabled && mw.callback) { line = mw.callback(line, mw); if (typeof line === 'string') { mw.target.writeln(line); } } }; mw.toString = function () { return '<miniwrite-peek>'; }; return mw; }
javascript
{ "resource": "" }
q40748
need
train
function need(args) { var argsArray, restArgs; if (!args) { return args; } argsArray = Array.prototype.slice.call(args); restArgs = Array.prototype.slice.call(arguments, 1); if (isArgumentObject(args)) { return argCheck(argsArray, restArgs); } return objectCheck(args, restArgs); }
javascript
{ "resource": "" }
q40749
train
function(config) { var directory = null; if(config.workingDir) { directory = path.join(config.workingDir, 'level'); } else { throw Errors.invalidConfig('Invalid configuration. Working directory not defined.'); } return directory; }
javascript
{ "resource": "" }
q40750
train
function(config) { var filePath = null; if(config.levelControllerConfig && config.levelControllerConfig.fileName) { filePath = path.join(_getLevelDir(config), config.levelControllerConfig.fileName); } else { throw Errors.invalidConfig('Invalid configuration. Level controller file name not defined.'); } return filePath; }
javascript
{ "resource": "" }
q40751
assertType
train
function assertType(value, type, allowUndefined, message) { if (!assert(type !== undefined, 'Paremeter \'type\' must be a string or a class')) return; if (!assert((allowUndefined === undefined) || (typeof allowUndefined === 'boolean'), 'Paremeter \'allowUndefined\', if specified, must be a boolean')) return; if (!assert((message === undefined) || (typeof message === 'string'), 'Parameter \'message\', if specified, must be a string')) return; allowUndefined = (allowUndefined === undefined) ? false : allowUndefined; if (allowUndefined && (value === undefined)) return true; if (type instanceof Array) { let n = type.length; for (let i = 0; i < n; i++) { if (checkType(value, type[i])) return true; } throw new Error(message || 'AssertType failed'); } if (checkType(value, type)) return true; throw new Error(message || 'AssertType failed'); }
javascript
{ "resource": "" }
q40752
listToObject
train
function listToObject(list, key) { var length, result, i, obj, keyValue; if (!list) { list = []; } length = list.length; result = { valids: {}, discarded: [] }; for (i = 0; i < length; i += 1) { obj = list[i]; keyValue = obj[key]; // discard the object without a key if (keyValue) { result.valids[keyValue] = obj; } else { result.discarded.push(obj); } } return result; }
javascript
{ "resource": "" }
q40753
exclude
train
function exclude(obj, keys) { var result, key; result = {}; keys = keys || []; for (key in obj) { if (obj.hasOwnProperty(key)) { if (keys.indexOf(key) === -1) { if (typeof obj[key] !== 'function') { result[key] = obj[key]; } } } } return result; }
javascript
{ "resource": "" }
q40754
keep
train
function keep(orig, dest, options) { var keep, i, t; keep = options.keep || []; if (keep.length === 0) { return dest; } for (i = 0; i < keep.length; i += 1) { t = orig[keep[i]]; if (t !== undefined) { dest[keep[i]] = t; } } return dest; }
javascript
{ "resource": "" }
q40755
train
function(p, cb) { //Get the status of the path return fs.stat(p, function(error, stat) { //Check the error if(error) { //Check the error code if(error.code !== 'ENOENT') { //Do the callback with the error return cb(error, false, stat); } else { //Do the callback without error return cb(null, false, stat); } } //Do the callback with the stat return cb(null, true, stat); }); }
javascript
{ "resource": "" }
q40756
train
function(index) { //Check the index if(index >= files.length) { //Do the callback return cb(null); } //Get the file to remove var file = files[index]; //Remove the file fs.unlink(file, function(error) { //Check the error if(error) { //Check the error code if(error.code !== 'ENOENT') { //Do the callback with the error return cb(error); } } //Continue with the next file return remove_file(index + 1); }); }
javascript
{ "resource": "" }
q40757
filterCards
train
function filterCards(cards) { // Option was passed in to disabled this filter. // User is probably requesting to discard. if (noCardFilter) { return cards } const [head, ...tail] = cards if (head && head.filter) { return [head].concat(head.filter(tail)) } return cards }
javascript
{ "resource": "" }
q40758
createBoxes
train
function createBoxes(count) { var boxes = []; for (var i = 0; i < N; i++) { boxes.push( V( elementFlag, "div", "box-view", V(elementFlag, "div", "box", count % 100, { style: { top: Math.sin(count / 10) * 10 + "px", left: Math.cos(count / 10) * 10 + "px", background: "rgb(0, 0," + count % 255 + ")" } }) ) ); } return boxes; }
javascript
{ "resource": "" }
q40759
enumerateBuiltInCommands
train
function enumerateBuiltInCommands(config) { const builtInCommandParentDirGlob = path_1.join(config.builtInCommandLocation, '/*.js'); return globby.sync(builtInCommandParentDirGlob, { ignore: '**/*.map' }); }
javascript
{ "resource": "" }
q40760
build
train
function build(mode, system, cdef, out, cb) { logger.info('building'); out.stdout('building'); cb(); }
javascript
{ "resource": "" }
q40761
undeploy
train
function undeploy(mode, target, system, containerDef, container, out, cb) { logger.info('undeploying'); out.stdout('undeploying'); cb(); }
javascript
{ "resource": "" }
q40762
link
train
function link(mode, target, system, containerDef, container, out, cb) { logger.info('linking'); out.stdout('linking'); var elb = findParentELB(system, container); if (elb) { logger.info(elb, 'elb found'); linkToELB(mode, system, elb, container, out, cb); } else { logger.info('elb not found'); cb(null, system); } }
javascript
{ "resource": "" }
q40763
unlink
train
function unlink(mode, target, system, containerDef, container, out, cb) { logger.info('unlinking'); out.stdout('unlinking'); var elb = findParentELB(system, container); if (elb) { logger.info(elb, 'elb found'); unlinkFromELB(mode, system, elb, container, out, cb); } else { logger.info('elb not found'); cb(null, target); } }
javascript
{ "resource": "" }
q40764
train
function (options, chart, firstAxis) { var pane = this, backgroundOption, defaultOptions = pane.defaultOptions; pane.chart = chart; // Set options if (chart.angular) { // gauges defaultOptions.background = {}; // gets extended by this.defaultBackgroundOptions } pane.options = options = merge(defaultOptions, options); backgroundOption = options.background; // To avoid having weighty logic to place, update and remove the backgrounds, // push them to the first axis' plot bands and borrow the existing logic there. if (backgroundOption) { each([].concat(splat(backgroundOption)).reverse(), function (config) { var backgroundColor = config.backgroundColor, // if defined, replace the old one (specific for gradients) axisUserOptions = firstAxis.userOptions; config = merge(pane.defaultBackgroundOptions, config); if (backgroundColor) { config.backgroundColor = backgroundColor; } config.color = config.backgroundColor; // due to naming in plotBands firstAxis.options.plotBands.unshift(config); axisUserOptions.plotBands = axisUserOptions.plotBands || []; // #3176 axisUserOptions.plotBands.unshift(config); }); } }
javascript
{ "resource": "" }
q40765
train
function () { // Call the Axis prototype method (the method we're in now is on the instance) axisProto.getOffset.call(this); // Title or label offsets are not counted this.chart.axisOffset[this.side] = 0; // Set the center array this.center = this.pane.center = CenteredSeriesMixin.getCenter.call(this.pane); }
javascript
{ "resource": "" }
q40766
train
function (lineWidth, radius) { var center = this.center; radius = pick(radius, center[2] / 2 - this.offset); return this.chart.renderer.symbols.arc( this.left + center[0], this.top + center[1], radius, radius, { start: this.startAngleRad, end: this.endAngleRad, open: true, innerR: 0 } ); }
javascript
{ "resource": "" }
q40767
train
function () { // Call uber method axisProto.setAxisTranslation.call(this); // Set transA and minPixelPadding if (this.center) { // it's not defined the first time if (this.isCircular) { this.transA = (this.endAngleRad - this.startAngleRad) / ((this.max - this.min) || 1); } else { this.transA = (this.center[2] / 2) / ((this.max - this.min) || 1); } if (this.isXAxis) { this.minPixelPadding = this.transA * this.minPointOffset; } else { // This is a workaround for regression #2593, but categories still don't position correctly. // TODO: Implement true handling of Y axis categories on gauges. this.minPixelPadding = 0; } } }
javascript
{ "resource": "" }
q40768
train
function () { axisProto.setAxisSize.call(this); if (this.isRadial) { // Set the center array this.center = this.pane.center = Highcharts.CenteredSeriesMixin.getCenter.call(this.pane); // The sector is used in Axis.translate to compute the translation of reversed axis points (#2570) if (this.isCircular) { this.sector = this.endAngleRad - this.startAngleRad; } // Axis len is used to lay out the ticks this.len = this.width = this.height = this.center[2] * pick(this.sector, 1) / 2; } }
javascript
{ "resource": "" }
q40769
train
function (value, length) { return this.postTranslate( this.isCircular ? this.translate(value) : 0, // #2848 pick(this.isCircular ? length : this.translate(value), this.center[2] / 2) - this.offset ); }
javascript
{ "resource": "" }
q40770
train
function (from, to, options) { var center = this.center, startAngleRad = this.startAngleRad, fullRadius = center[2] / 2, radii = [ pick(options.outerRadius, '100%'), options.innerRadius, pick(options.thickness, 10) ], percentRegex = /%$/, start, end, open, isCircular = this.isCircular, // X axis in a polar chart ret; // Polygonal plot bands if (this.options.gridLineInterpolation === 'polygon') { ret = this.getPlotLinePath(from).concat(this.getPlotLinePath(to, true)); // Circular grid bands } else { // Keep within bounds from = Math.max(from, this.min); to = Math.min(to, this.max); // Plot bands on Y axis (radial axis) - inner and outer radius depend on to and from if (!isCircular) { radii[0] = this.translate(from); radii[1] = this.translate(to); } // Convert percentages to pixel values radii = map(radii, function (radius) { if (percentRegex.test(radius)) { radius = (pInt(radius, 10) * fullRadius) / 100; } return radius; }); // Handle full circle if (options.shape === 'circle' || !isCircular) { start = -Math.PI / 2; end = Math.PI * 1.5; open = true; } else { start = startAngleRad + this.translate(from); end = startAngleRad + this.translate(to); } ret = this.chart.renderer.symbols.arc( this.left + center[0], this.top + center[1], radii[0], radii[0], { start: Math.min(start, end), // Math is for reversed yAxis (#3606) end: Math.max(start, end), innerR: pick(radii[1], radii[0] - radii[2]), open: open } ); } return ret; }
javascript
{ "resource": "" }
q40771
train
function (value, reverse) { var axis = this, center = axis.center, chart = axis.chart, end = axis.getPosition(value), xAxis, xy, tickPositions, ret; // Spokes if (axis.isCircular) { ret = ['M', center[0] + chart.plotLeft, center[1] + chart.plotTop, 'L', end.x, end.y]; // Concentric circles } else if (axis.options.gridLineInterpolation === 'circle') { value = axis.translate(value); if (value) { // a value of 0 is in the center ret = axis.getLinePath(0, value); } // Concentric polygons } else { // Find the X axis in the same pane each(chart.xAxis, function (a) { if (a.pane === axis.pane) { xAxis = a; } }); ret = []; value = axis.translate(value); tickPositions = xAxis.tickPositions; if (xAxis.autoConnect) { tickPositions = tickPositions.concat([tickPositions[0]]); } // Reverse the positions for concatenation of polygonal plot bands if (reverse) { tickPositions = [].concat(tickPositions).reverse(); } each(tickPositions, function (pos, i) { xy = xAxis.getPosition(pos, value); ret.push(i ? 'L' : 'M', xy.x, xy.y); }); } return ret; }
javascript
{ "resource": "" }
q40772
train
function () { var center = this.center, chart = this.chart, titleOptions = this.options.title; return { x: chart.plotLeft + center[0] + (titleOptions.x || 0), y: chart.plotTop + center[1] - ({ high: 0.5, middle: 0.25, low: 0 }[titleOptions.align] * center[2]) + (titleOptions.y || 0) }; }
javascript
{ "resource": "" }
q40773
train
function (segment) { var lowSegment, highSegment = [], i = segment.length, baseGetSegmentPath = Series.prototype.getSegmentPath, point, linePath, lowerPath, options = this.options, step = options.step, higherPath; // Remove nulls from low segment lowSegment = HighchartsAdapter.grep(segment, function (point) { return point.plotLow !== null; }); // Make a segment with plotX and plotY for the top values while (i--) { point = segment[i]; if (point.plotHigh !== null) { highSegment.push({ plotX: point.plotHighX || point.plotX, // plotHighX is for polar charts plotY: point.plotHigh }); } } // Get the paths lowerPath = baseGetSegmentPath.call(this, lowSegment); if (step) { if (step === true) { step = 'left'; } options.step = { left: 'right', center: 'center', right: 'left' }[step]; // swap for reading in getSegmentPath } higherPath = baseGetSegmentPath.call(this, highSegment); options.step = step; // Create a line on both top and bottom of the range linePath = [].concat(lowerPath, higherPath); // For the area path, we need to change the 'move' statement into 'lineTo' or 'curveTo' if (!this.chart.polar) { higherPath[0] = 'L'; // this probably doesn't work for spline } this.areaPath = this.areaPath.concat(lowerPath, higherPath); return linePath; }
javascript
{ "resource": "" }
q40774
train
function () { var data = this.data, length = data.length, i, originalDataLabels = [], seriesProto = Series.prototype, dataLabelOptions = this.options.dataLabels, align = dataLabelOptions.align, point, inverted = this.chart.inverted; if (dataLabelOptions.enabled || this._hasPointLabels) { // Step 1: set preliminary values for plotY and dataLabel and draw the upper labels i = length; while (i--) { point = data[i]; // Set preliminary values point.y = point.high; point._plotY = point.plotY; point.plotY = point.plotHigh; // Store original data labels and set preliminary label objects to be picked up // in the uber method originalDataLabels[i] = point.dataLabel; point.dataLabel = point.dataLabelUpper; // Set the default offset point.below = false; if (inverted) { if (!align) { dataLabelOptions.align = 'left'; } dataLabelOptions.x = dataLabelOptions.xHigh; } else { dataLabelOptions.y = dataLabelOptions.yHigh; } } if (seriesProto.drawDataLabels) { seriesProto.drawDataLabels.apply(this, arguments); // #1209 } // Step 2: reorganize and handle data labels for the lower values i = length; while (i--) { point = data[i]; // Move the generated labels from step 1, and reassign the original data labels point.dataLabelUpper = point.dataLabel; point.dataLabel = originalDataLabels[i]; // Reset values point.y = point.low; point.plotY = point._plotY; // Set the default offset point.below = true; if (inverted) { if (!align) { dataLabelOptions.align = 'right'; } dataLabelOptions.x = dataLabelOptions.xLow; } else { dataLabelOptions.y = dataLabelOptions.yLow; } } if (seriesProto.drawDataLabels) { seriesProto.drawDataLabels.apply(this, arguments); } } dataLabelOptions.align = align; }
javascript
{ "resource": "" }
q40775
train
function () { var series = this, yAxis = series.yAxis, options = series.options, center = yAxis.center; series.generatePoints(); each(series.points, function (point) { var dialOptions = merge(options.dial, point.dial), radius = (pInt(pick(dialOptions.radius, 80)) * center[2]) / 200, baseLength = (pInt(pick(dialOptions.baseLength, 70)) * radius) / 100, rearLength = (pInt(pick(dialOptions.rearLength, 10)) * radius) / 100, baseWidth = dialOptions.baseWidth || 3, topWidth = dialOptions.topWidth || 1, overshoot = options.overshoot, rotation = yAxis.startAngleRad + yAxis.translate(point.y, null, null, null, true); // Handle the wrap and overshoot options if (overshoot && typeof overshoot === 'number') { overshoot = overshoot / 180 * Math.PI; rotation = Math.max(yAxis.startAngleRad - overshoot, Math.min(yAxis.endAngleRad + overshoot, rotation)); } else if (options.wrap === false) { rotation = Math.max(yAxis.startAngleRad, Math.min(yAxis.endAngleRad, rotation)); } rotation = rotation * 180 / Math.PI; point.shapeType = 'path'; point.shapeArgs = { d: dialOptions.path || [ 'M', -rearLength, -baseWidth / 2, 'L', baseLength, -baseWidth / 2, radius, -topWidth / 2, radius, topWidth / 2, baseLength, baseWidth / 2, -rearLength, baseWidth / 2, 'z' ], translateX: center[0], translateY: center[1], rotation: rotation }; // Positions for data label point.plotX = center[0]; point.plotY = center[1]; }); }
javascript
{ "resource": "" }
q40776
train
function (init) { var series = this; if (!init) { each(series.points, function (point) { var graphic = point.graphic; if (graphic) { // start value graphic.attr({ rotation: series.yAxis.startAngleRad * 180 / Math.PI }); // animate graphic.animate({ rotation: point.shapeArgs.rotation }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }
javascript
{ "resource": "" }
q40777
train
function (point) { // return a plain array for speedy calculation return [point.low, point.q1, point.median, point.q3, point.high]; }
javascript
{ "resource": "" }
q40778
train
function (force) { var series = this, options = series.options, yData = series.yData, points = series.options.data, // #3710 Update point does not propagate to sum point, dataLength = yData.length, threshold = options.threshold || 0, subSum, sum, dataMin, dataMax, y, i; sum = subSum = dataMin = dataMax = threshold; for (i = 0; i < dataLength; i++) { y = yData[i]; point = points && points[i] ? points[i] : {}; if (y === "sum" || point.isSum) { yData[i] = sum; } else if (y === "intermediateSum" || point.isIntermediateSum) { yData[i] = subSum; } else { sum += y; subSum += y; } dataMin = Math.min(sum, dataMin); dataMax = Math.max(sum, dataMax); } Series.prototype.processData.call(this, force); // Record extremes series.dataMin = dataMin; series.dataMax = dataMax; }
javascript
{ "resource": "" }
q40779
train
function (pt) { if (pt.isSum) { return (pt.x === 0 ? null : "sum"); //#3245 Error when first element is Sum or Intermediate Sum } else if (pt.isIntermediateSum) { return (pt.x === 0 ? null : "intermediateSum"); //#3245 } return pt.y; }
javascript
{ "resource": "" }
q40780
train
function () { seriesTypes.column.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upColor = options.upColor || series.color, hoverColor = Highcharts.Color(upColor).brighten(0.1).get(), seriesDownPointAttr = merge(series.pointAttr), upColorProp = series.upColorProp; seriesDownPointAttr[''][upColorProp] = upColor; seriesDownPointAttr.hover[upColorProp] = stateOptions.hover.upColor || hoverColor; seriesDownPointAttr.select[upColorProp] = stateOptions.select.upColor || upColor; each(series.points, function (point) { if (!point.options.color) { // Up color if (point.y > 0) { point.pointAttr = seriesDownPointAttr; point.color = upColor; // Down color (#3710, update to negative) } else { point.pointAttr = series.pointAttr; } } }); }
javascript
{ "resource": "" }
q40781
train
function () { var data = this.data, length = data.length, lineWidth = this.options.lineWidth + this.borderWidth, normalizer = mathRound(lineWidth) % 2 / 2, path = [], M = 'M', L = 'L', prevArgs, pointArgs, i, d; for (i = 1; i < length; i++) { pointArgs = data[i].shapeArgs; prevArgs = data[i - 1].shapeArgs; d = [ M, prevArgs.x + prevArgs.width, prevArgs.y + normalizer, L, pointArgs.x, prevArgs.y + normalizer ]; if (data[i - 1].y < 0) { d[2] += prevArgs.height; d[5] += prevArgs.height; } path = path.concat(d); } return path; }
javascript
{ "resource": "" }
q40782
train
function (fill) { var markerOptions = this.options.marker, fillOpacity = pick(markerOptions.fillOpacity, 0.5); // When called from Legend.colorizeItem, the fill isn't predefined fill = fill || markerOptions.fillColor || this.color; if (fillOpacity !== 1) { fill = Color(fill).setOpacity(fillOpacity).get('rgba'); } return fill; }
javascript
{ "resource": "" }
q40783
train
function () { var obj = Series.prototype.convertAttribs.apply(this, arguments); obj.fill = this.applyOpacity(obj.fill); return obj; }
javascript
{ "resource": "" }
q40784
train
function (zMin, zMax, minSize, maxSize) { var len, i, pos, zData = this.zData, radii = [], sizeByArea = this.options.sizeBy !== 'width', zRange; // Set the shape type and arguments to be picked up in drawPoints for (i = 0, len = zData.length; i < len; i++) { zRange = zMax - zMin; pos = zRange > 0 ? // relative size, a number between 0 and 1 (zData[i] - zMin) / (zMax - zMin) : 0.5; if (sizeByArea && pos >= 0) { pos = Math.sqrt(pos); } radii.push(math.ceil(minSize + pos * (maxSize - minSize)) / 2); } this.radii = radii; }
javascript
{ "resource": "" }
q40785
train
function (init) { var animation = this.options.animation; if (!init) { // run the animation each(this.points, function (point) { var graphic = point.graphic, shapeArgs = point.shapeArgs; if (graphic && shapeArgs) { // start values graphic.attr('r', 1); // animate graphic.animate({ r: shapeArgs.r }, animation); } }); // delete this function to allow it only once this.animate = null; } }
javascript
{ "resource": "" }
q40786
train
function () { var i, data = this.data, point, radius, radii = this.radii; // Run the parent method seriesTypes.scatter.prototype.translate.call(this); // Set the shape type and arguments to be picked up in drawPoints i = data.length; while (i--) { point = data[i]; radius = radii ? radii[i] : 0; // #1737 if (radius >= this.minPxSize / 2) { // Shape arguments point.shapeType = 'circle'; point.shapeArgs = { x: point.plotX, y: point.plotY, r: radius }; // Alignment box for the data label point.dlBox = { x: point.plotX - radius, y: point.plotY - radius, width: 2 * radius, height: 2 * radius }; } else { // below zThreshold point.shapeArgs = point.plotY = point.dlBox = UNDEFINED; // #1691 } } }
javascript
{ "resource": "" }
q40787
initArea
train
function initArea(proceed, chart, options) { proceed.call(this, chart, options); if (this.chart.polar) { /** * Overridden method to close a segment path. While in a cartesian plane the area * goes down to the threshold, in the polar chart it goes to the center. */ this.closeSegment = function (path) { var center = this.xAxis.center; path.push( 'L', center[0], center[1] ); }; // Instead of complicated logic to draw an area around the inner area in a stack, // just draw it behind this.closedStacks = true; } }
javascript
{ "resource": "" }
q40788
train
function () { var mediaPath = path.join(__dirname, '..', 'media'), templateFile = path.join(mediaPath, 'templates', 'index.jade'), monolith = require('monolith').init({ minify: true }); monolith.addCSSFile(path.join(mediaPath, "css", "normalize.css")); monolith.addCSSFile(path.join(mediaPath, "css", "razdraz.css")); outputData.css = monolith.getCSS(); outputData.scripts = monolith.getScript(); outputData.pageTemplate = jade.compile(fs.readFileSync(templateFile, 'utf-8')); }
javascript
{ "resource": "" }
q40789
load
train
function load (routes) { if (!Array.isArray(routes) || routes.length === 0) { throw new Error('argument should be an array not empty.') } if (!Array.isArray(routes[0])) { routes = [routes] } return routes.map(route => _getFiles(route)) .reduce((acc, routes) => acc.concat(routes), []) }
javascript
{ "resource": "" }
q40790
_getFiles
train
function _getFiles (route) { const dir = route[0] const prefix = route.splice(1).join('/') return _browseDir(dir) .map(file => require(file)) .reduce((acc, routes) => acc.concat(routes), []) .map(routes => _normalizeUrl(routes, prefix)) }
javascript
{ "resource": "" }
q40791
_browseDir
train
function _browseDir (dir, fileList) { fileList || (fileList = []) try { fs.readdirSync(dir) .map(item => _buildFullPath(dir, item)) .map(item => _addFileOrContinueBrowsing(item, fileList)) } catch (e) { throw new Error(e.message) } return fileList }
javascript
{ "resource": "" }
q40792
_addFileOrContinueBrowsing
train
function _addFileOrContinueBrowsing (item, fileList) { !fs.statSync(item).isDirectory() ? fileList.push(item) : _browseDir(item, fileList) }
javascript
{ "resource": "" }
q40793
_normalizeUrl
train
function _normalizeUrl (route, prefix) { const _route = Object.assign({}, route) const url = _route.url .replace(/^\//, '') .replace(/\/$/, '') // build prefix prefix = prefix ? `/${prefix}` : '' _route.url = url ? `${prefix}/${url}/` : `${prefix}/` debug(`rewritting url: ${_route.url}`) return _route }
javascript
{ "resource": "" }
q40794
train
function(opts) { xml2js.opts = opts; return opts .option('-i, --inputdir [directory]', 'directory for xml files', __dirname + '/xml/mraa') .option('-c, --custom [file]', 'json for customizations') .option('-t, --typemaps [directory]', 'directory for custom pointer type maps') .option('-g, --imagedir [directory]', 'directory to link to where the images will be kept', '') .option('-s, --strict', 'leave out methods/variables if unknown type') }
javascript
{ "resource": "" }
q40795
createXmlParser
train
function createXmlParser(XML_GRAMMAR_SPEC) { return fs.readFileAsync(XML_GRAMMAR_SPEC, 'utf8').then(function(xmlgrammar) { return peg.buildParser(xmlgrammar); }); }
javascript
{ "resource": "" }
q40796
findUsage
train
function findUsage(type, classOnly) { var filterClasses = function(fn) { return _.without(_.map(xml2js.CLASSES, fn), undefined); }; var usesType = function(classSpec, className) { var methodsOfType = (_.find(classSpec.methods, function(methodSpec, methodName) { return ((!_.isEmpty(methodSpec.return) && methodSpec.return.type == type) || (_.contains(_.pluck(methodSpec.params, 'type'), type))); }) != undefined); var variablesOfType = _.contains(_.pluck(classSpec.variable, 'type'), type); return ((methodsOfType || variablesOfType) ? className : undefined); }; var extendsType = function(classSpec, className) { return ((classSpec.parent == type) ? className : undefined); }; var classes = _.union(filterClasses(usesType), filterClasses(extendsType)); if (classOnly) { return classes; } else { return _.without(_.uniq(_.pluck(_.pick(xml2js.CLASSES, classes), 'group')), undefined); } }
javascript
{ "resource": "" }
q40797
customizeMethods
train
function customizeMethods(custom) { _.each(custom, function(classMethods, className) { _.extend(xml2js.CLASSES[className].methods, _.pick(classMethods, function(methodSpec, methodName) { return isValidMethodSpec(methodSpec, className + '.' + methodName); })); }); }
javascript
{ "resource": "" }
q40798
isValidMethodSpec
train
function isValidMethodSpec(methodSpec, methodName) { var valid = true; var printIgnoredMethodOnce = _.once(function() { console.log(methodName + ' from ' + path.basename(xml2js.opts.custom) + ' is omitted from JS documentation.'); }); function checkRule(rule, errMsg) { if (!rule) { printIgnoredMethodOnce(); console.log(' ' + errMsg); valid = false; } } checkRule(_.has(methodSpec, 'description'), 'no description given'); checkRule(_.has(methodSpec, 'params'), 'no params given (specify "params": {} for no params)'); _.each(methodSpec.params, function(paramSpec, paramName) { checkRule(_.has(paramSpec, 'type'), 'no type given for param ' + paramName); checkRule(_.has(paramSpec, 'description'), 'no description given for param ' + paramName); }); checkRule(_.has(methodSpec, 'return'), 'no return given (specify "return": {} for no return value)'); checkRule(_.has(methodSpec.return, 'type'), 'no type given for return value'); checkRule(_.has(methodSpec.return, 'description'), 'no description given for return value'); return valid; }
javascript
{ "resource": "" }
q40799
getEnums
train
function getEnums(spec_c, bygroup, parent) { var spec_js = {}; var enumGroups = _.find(getChildren(spec_c, 'sectiondef'), function(section) { var kind = getAttr(section, 'kind'); return ((kind == 'enum') || (kind == 'public-type')); }); if (enumGroups) { _.each(enumGroups.children, function(enumGroup) { var enumGroupName = getText(getChild(enumGroup, 'name'), 'name'); var enumGroupDescription = getText(getChild(enumGroup, 'detaileddescription'), 'description'); var enumGroupVals = getChildren(enumGroup, 'enumvalue'); if (bygroup) { spec_js[enumGroupName] = { description: enumGroupDescription, members: [] }; } _.each(enumGroupVals, function(e) { // TODO: get prefix as option var enumName = getText(getChild(e, 'name'), 'name').replace(/^MRAA_/, ''); var enumDescription = getText(getChild(e, 'detaileddescription'), 'description'); if (!bygroup) { spec_js[enumName] = { type: enumGroupName, description: enumDescription }; } else { spec_js[enumGroupName].members.push(enumName); } }); }); } return spec_js; }
javascript
{ "resource": "" }