_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q1100
concatUnique
train
function concatUnique(aItems, bItems, algebra) { var idTree = {}; var aSet; // IE 9 and 10 don't have Set. if(typeof Set !== "undefined") { aSet = new Set(); // jshint ignore:line } aItems.forEach(function(item) { var keyNode = idTree; if(aSet) { aSet.add(item); } each(algebra.clauses.id, function(prop) { var propVal = getProp(item, prop); if(keyNode && typeof propVal !== "undefined") { keyNode = keyNode[propVal] = keyNode[propVal] || {}; } else { keyNode = undefined;
javascript
{ "resource": "" }
q1101
train
function(){ var clauses = this.clauses = { where: {}, order: {}, paginate: {}, id: {} }; this.translators = { where: new Translate("where", { fromSet: function(set, setRemainder){ return setRemainder; }, toSet: function(set, wheres){ return assign(set, wheres); } }) }; var self = this; each(arguments, function(arg) {
javascript
{ "resource": "" }
q1102
train
function(aClauses, bClauses) { var self = this; var differentTypes = []; each(clause.TYPES, function(type) { if( !self.evaluateOperator(compare.equal,
javascript
{ "resource": "" }
q1103
train
function(set, clause, result, useSet) { if(result && typeof result === "object" && useSet !== false) { if( this.translators[clause] ) { set = this.translators.where.toSet(set, result); } else { set = assign(set, result);
javascript
{ "resource": "" }
q1104
train
function(operator, a, b, aOptions, bOptions, evaluateOptions) { aOptions = aOptions || {}; bOptions = bOptions || {}; evaluateOptions = assign({ evaluateWhere: operator, evaluatePaginate: operator, evaluateOrder: operator, shouldEvaluatePaginate: function(aClauseProps, bClauseProps) { return aClauseProps.enabled.paginate || bClauseProps.enabled.paginate; }, shouldEvaluateOrder: function(aClauseProps, bClauseProps) { return aClauseProps.enabled.order && compare.equal(aClauseProps.order, bClauseProps.order, undefined, undefined, undefined,{},{}); } /* aClauseProps.enabled.order || bClauseProps.enabled.order */ }, evaluateOptions||{}); var aClauseProps = this.getClauseProperties(a, aOptions), bClauseProps = this.getClauseProperties(b, bOptions), set = {}, useSet; var result = evaluateOptions.evaluateWhere(aClauseProps.where, bClauseProps.where, undefined, undefined, undefined, this.clauses.where, {}); useSet = this.updateSet(set, "where", result, useSet); // if success, and either has paginate props if(result && evaluateOptions.shouldEvaluatePaginate(aClauseProps,bClauseProps) ) { // if they have an order, it has to be true for paginate to be valid // this isn't true if a < b, a is paginated, and b is not.
javascript
{ "resource": "" }
q1105
train
function(setA, setB, property1, property2){ // p for param // v for value var numProps = numericProperties(setA, setB, property1, property2); var sAv1 = numProps.sAv1, sAv2 = numProps.sAv2, sBv1 = numProps.sBv1, sBv2 = numProps.sBv2, count = sAv2 - sAv1 + 1; var after = { difference: [sBv2+1, sAv2], intersection: [sAv1,sBv2], union: [sBv1, sAv2], count: count, meta: "after" }; var before = { difference: [sAv1, sBv1-1], intersection: [sBv1,sAv2], union: [sAv1, sBv2], count: count, meta: "before" }; // if the sets are equal if(sAv1 === sBv1 && sAv2 === sBv2) { return { intersection: [sAv1,sAv2], union: [sAv1,sAv2], count: count, meta: "equal" }; } // A starts at B but A ends later else if( sAv1 === sBv1 && sBv2 < sAv2 ) { return after; } // A end at B but A starts earlier else if( sAv2 === sBv2 && sBv1 > sAv1 ) { return before; } // B contains A else if( within(sAv1, [sBv1, sBv2]) && within(sAv2, [sBv1, sBv2]) ) { return { intersection: [sAv1,sAv2], union: [sBv1, sBv2], count: count, meta: "subset" }; } // A contains B else if( within(sBv1, [sAv1, sAv2]) && within(sBv2, [sAv1, sAv2]) ) { return { intersection: [sBv1,sBv2], // there is a difference in what A has difference: [null, null], union: [sAv1, sAv2], count: count, meta: "superset" }; } // setA starts earlier
javascript
{ "resource": "" }
q1106
getThreshold
train
function getThreshold(fromStep, toStep, now) { let threshold // Allows custom thresholds when moving // from a specific step to a specific step. if (fromStep && (fromStep.id || fromStep.unit)) { threshold = toStep[`threshold_for_${fromStep.id || fromStep.unit}`] } // If no custom threshold is set for this transition // then use the usual threshold for the next step. if (threshold === undefined) { threshold = toStep.threshold } // Convert threshold to a number. if (typeof threshold === 'function') { threshold = threshold(now) } // Throw if
javascript
{ "resource": "" }
q1107
getAllowedSteps
train
function getAllowedSteps(gradation, units) { return gradation.filter(({ unit }) => { // If this step has a `unit` defined // then this `unit` must be in the list of `units` allowed. if (unit) { return units.indexOf(unit) >= 0
javascript
{ "resource": "" }
q1108
getTimeIntervalMeasurementUnits
train
function getTimeIntervalMeasurementUnits(localeData, restrictedSetOfUnits) { // All available time interval measurement units. let units = Object.keys(localeData) // If only a specific set of available // time measurement units can be used. if (restrictedSetOfUnits) { // Reduce available time interval measurement units // based on user's preferences. units = restrictedSetOfUnits.filter(_ => units.indexOf(_) >= 0) } // Stock `Intl.RelativeTimeFormat` locale data doesn't have "now" units. // So either "now" is
javascript
{ "resource": "" }
q1109
toggle
train
function toggle(element, animation, callbackFn) { var nowVisible = element.style.display != 'none' || element.offsetLeft > 0; // create clone for reference var clone = element.cloneNode(true); var cleanup = function() { element.removeAttribute('data-animated'); element.setAttribute('style', clone.getAttribute('style')); element.style.display = nowVisible ? 'none' : ''; if( callbackFn ) { callbackFn(); } }; // store attribute so everyone knows we're animating this element element.setAttribute('data-animated', "true"); // toggle element visiblity right away if we're making something visible if( ! nowVisible ) { element.style.display = ''; } var hiddenStyles, visibleStyles; // animate properties if( animation === 'slide' ) { hiddenStyles = initObjectProperties(["height", "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"], 0); visibleStyles = {}; if( ! nowVisible ) { var computedStyles = window.getComputedStyle(element); visibleStyles = copyObjectProperties(["height", "borderTopWidth",
javascript
{ "resource": "" }
q1110
nest
train
function nest (str, refs, escape) { var res = [], match var a = 0 while (match = re.exec(str)) { if (a++ > 10e3) throw Error('Circular references in parenthesis') res.push(str.slice(0, match.index))
javascript
{ "resource": "" }
q1111
loadData
train
function loadData() { var data = fs.readFileSync(__dirname + '/zip_codes.csv', 'utf8'); var lines = data.split('\r\n'); var trie = {}; lines.forEach(function(line) { var parts = line.split(','); var zip = parts[0], city = parts[1], state = parts[2]; var node = trie; for (var i = 0; i < zip.length; i++) {
javascript
{ "resource": "" }
q1112
setupStyleguide
train
function setupStyleguide(options) { let cwd = !!options && !!options.cwd ? options.cwd : process.cwd() success('Styleguide.new:', 'initialize styleguide ...') return new Styleguide() .initialize(cwd) .then(function
javascript
{ "resource": "" }
q1113
resolveStyleguide
train
function resolveStyleguide(options) { return setupStyleguide(options) .then(function (styleguide) { success('Styleguide.read:', 'start reading ...') return styleguide.read() }) .then(function (styleguide) {
javascript
{ "resource": "" }
q1114
build
train
function build(options) { options = Object.assign({}, options) return resolveStyleguide(options) .then(function (styleguide) { success('Styleguide.write:', 'start writing ...') return styleguide.write() }) .then(function (styleguide) {
javascript
{ "resource": "" }
q1115
createExport
train
function createExport(options) { options = Object.assign({}, options, { prepare: false }) /** we need no styleguide preparation, like asset copying etc. */ return resolveStyleguide(options) .then(function (styleguide) { return styleguide.exportStyleguide() }) .catch(function (e)
javascript
{ "resource": "" }
q1116
train
function (config, mockSrc, defaultScenario, filenames, scenarioName) { // read mock data files for this scenario var scenario = filenames.map(function (filename) { var filepath = fs.realpathSync(path.join(mockSrc, filename));
javascript
{ "resource": "" }
q1117
train
function (config, mockSrc) { var mockManifestPath = path.join(process.cwd(), mockSrc, mockManifestFilename), // read manifest JSON by require'ing it mockManifest = require(mockManifestPath), // read files for default scenario first, so we can merge it into other // scenarios later defaultScenario = readScenario(config, mockSrc, [],
javascript
{ "resource": "" }
q1118
train
function (data, pluginNames) { logger('runPlugins input', data); var plugins = pluginNames.map(function (pn) { return pluginRegistry[pn]; }), applyPlugin = function (oldData, plugin) { return plugin(oldData); }; // Use reduce to apply all
javascript
{ "resource": "" }
q1119
train
function (dataWithContext) { return _.mapValues(dataWithContext, function (scenario) { return
javascript
{ "resource": "" }
q1120
train
function (config, mockSrc) { var dataWithContext = readMockManifest(config, mockSrc); // log('readScenarioData config',
javascript
{ "resource": "" }
q1121
train
function (templatePath, path, data, name) { var templateString = fs.readFileSync(templatePath); // generate scenarioData.js contents by inserting data into template var templateData = {scenarioData: data}; templateData.scenarioDataName = name ||
javascript
{ "resource": "" }
q1122
train
function () { config.multipleFiles = config.multipleFiles || false; var defaultTemplate = singleFileDefaultTemplate; if (config.multipleFiles) { defaultTemplate = multipleFilesDefaultTemplate; } config.template = config.template || defaultTemplate; var mockSrc = _.isArray(config.src) ? _.first(config.src) : config.src; logger('mock source', mockSrc); logger('dest', config.dest); logger('template', config.template); logger('multipleFiles', config.multipleFiles); logger('plugins', config.plugins); // read all scenario data from manifest/JSON files var scenarioData = readScenarioData(config, mockSrc); logger('scenarioData', scenarioData); var scenarioModuleFilename = config.dest, scenarioString; if (!config.multipleFiles) { // stringify all scenario files into a single Angular module scenarioString = JSON.stringify(scenarioData); writeScenarioModule(config.template, scenarioModuleFilename,
javascript
{ "resource": "" }
q1123
accessor
train
function accessor(k) { Popup.prototype[k] = function(v) { if
javascript
{ "resource": "" }
q1124
compile
train
function compile(pos) { var values = [] if (!pos) { return null } values = [[pos.line || 1, pos.column || 1].join(':')] if
javascript
{ "resource": "" }
q1125
stringify
train
function stringify(start, end) { var values = [] var positions = [] var offsets = [] add(start) add(end) if (positions.length !== 0) { values.push(positions.join('-')) } if (offsets.length !== 0)
javascript
{ "resource": "" }
q1126
add
train
function add(position) { var tuple = compile(position) if (tuple) {
javascript
{ "resource": "" }
q1127
formatNode
train
function formatNode(node) { var log = node.type var location = node.position || {} var position = stringify(location.start, location.end) var key var values = [] var value if (node.children) { log += dim('[') + yellow(node.children.length) + dim(']') } else if (typeof node.value === 'string') { log += dim(': ') + green(JSON.stringify(node.value)) } if (position) { log += ' (' + position + ')' } for (key in node) { value = node[key] if ( ignore.indexOf(key) !== -1 || value === null ||
javascript
{ "resource": "" }
q1128
execList
train
function execList(options) { const deferred = Q.defer(); const json = options.json !== false; const offline = options.offline !== false; const cwd = options.cwd || process.cwd();
javascript
{ "resource": "" }
q1129
errMessageFormat
train
function errMessageFormat (showDiff, pos, title, msg, stack) { if (showDiff) { return format.red(' ' + pos + ') ' + title + ':\n' + msg) + format.gray('\n' + stack + '\n') } return format.red('
javascript
{ "resource": "" }
q1130
unifiedDiff
train
function unifiedDiff (err) { let indent = ' ' function cleanUp (line) { if (line[0] === '+') { return indent + format.colorLines('green', line) } if (line[0] === '-') { return indent + format.colorLines('red', line) } if (line.match(/@@/)) { return null } if (line.match(/\\ No newline/)) { return null } if (line.trim().length) { line = format.colorLines('white', line) } return indent + line } function notBlank (line) {
javascript
{ "resource": "" }
q1131
unwrapReturns
train
function unwrapReturns(ast, src, result) { const charArray = src.split(''); const state = { hasReturn: false, source(node) { return src.slice(node.start, node.end); }, replace(node, str) { charArray.fill('', node.start, node.end); charArray[node.start] = str; } }; walk(ast, unwrapReturnsVisitors, state);
javascript
{ "resource": "" }
q1132
checkPageViewsCriteria
train
function checkPageViewsCriteria() { // don't bother if another box is currently open if( isAnyBoxVisible() ) { return; } boxes.forEach(function(box) { if( ! box.mayAutoShow() ) { return; }
javascript
{ "resource": "" }
q1133
checkTimeCriteria
train
function checkTimeCriteria() { // don't bother if another box is currently open if( isAnyBoxVisible() ) { return; } boxes.forEach(function(box) { if( ! box.mayAutoShow() ) { return; } // check "time on site" trigger if (box.config.trigger.method === 'time_on_site' && siteTimer.time >= box.config.trigger.value) { box.trigger();
javascript
{ "resource": "" }
q1134
checkHeightCriteria
train
function checkHeightCriteria() { var scrollY = scrollElement.hasOwnProperty('pageYOffset') ? scrollElement.pageYOffset : scrollElement.scrollTop; scrollY = scrollY + window.innerHeight * 0.9; boxes.forEach(function(box) { if( ! box.mayAutoShow() || box.triggerHeight <= 0 ) { return; } if( scrollY > box.triggerHeight ) { // don't bother if another box is currently open if( isAnyBoxVisible() ) { return;
javascript
{ "resource": "" }
q1135
Refs
train
function Refs(a, b) { if (!(this instanceof Refs)) { return new Refs(a, b); } // link a.inverse = b; b.inverse = a;
javascript
{ "resource": "" }
q1136
train
function(element, event, callback, capturePhase) { if (!element.id) element.id = $.uuid() if (!ChuiEventCache.elements[element.id]) { ChuiEventCache.elements[element.id] = [] } ChuiEventCache.elements[element.id].push({
javascript
{ "resource": "" }
q1137
train
function(element, event, callback) { const eventStack = ChuiEventCache.elements[element.id] if (!eventStack) return let deleteOrder = [] if (!event) { deleteOrder = [] eventStack.forEach(function(evt, idx) { element.removeEventListener(evt.event, evt.callback, evt.capturePhase) deleteOrder.push(idx) }) deleteFromEventStack(deleteOrder, eventStack) } else if (!!event && !callback) { deleteOrder = [] eventStack.forEach(function(evt, idx) { if (evt.event === event) { element.removeEventListener(evt.event, evt.callback, evt.capturePhase) deleteOrder.push(idx) }
javascript
{ "resource": "" }
q1138
train
function(element, selector, event, callback, capturePhase) { const delegateElement = $(element).array[0] $(element).forEach(function(ctx) { $(ctx).on(event, function(e) { let target = e.target if (e.target.nodeType === 3) { target = e.target.parentNode } $(ctx).find(selector).forEach(function(delegateElement) { if (delegateElement === target) { callback.call(delegateElement, e) } else { try {
javascript
{ "resource": "" }
q1139
getName
train
function getName () { const pathname = url.parse(parts[parts.length
javascript
{ "resource": "" }
q1140
getOptionsObject
train
function getOptionsObject () { if (parts.length > 1) { // Options should be appended to the last hosts querystring
javascript
{ "resource": "" }
q1141
getAuthenticationObject
train
function getAuthenticationObject () { const authString = url.parse(parts[0]).auth; if (authString) { return { source: getName(),
javascript
{ "resource": "" }
q1142
train
function (metadata) { var key; if (metadata) { this.name = metadata.name; this.size = metadata.size || 0; this.mime = metadata.mime || ''; this.isPublic = metadata.isPublic || false; this.tags = metadata.tags || []; this.content = metadata.content; this.contentType = metadata.contentType || BlobMetadata.CONTENT_TYPES.OBJECT; if (this.contentType === BlobMetadata.CONTENT_TYPES.COMPLEX) { for (key in this.content) { if (this.content.hasOwnProperty(key)) {
javascript
{ "resource": "" }
q1143
train
function (parameters) { parameters = parameters || {}; if (parameters.logger) { this.logger = parameters.logger; } else { /*eslint-disable no-console*/ var doLog = function () { console.log.apply(console, arguments); }; this.logger = { debug: doLog, log: doLog, info: doLog, warn: doLog, error: doLog }; console.warn('Since v1.3.0 ExecutorClient requires a logger, falling back on console.log.'); /*eslint-enable no-console*/ } this.logger.debug('ctor', {metadata: parameters}); this.isNodeJS = (typeof window === 'undefined') && (typeof process === 'object'); this.isNodeWebkit = (typeof window === 'object') && (typeof process === 'object'); //console.log(isNode); if (this.isNodeJS) { this.logger.debug('Running under node'); this.server = '127.0.0.1'; this.httpsecure = false; } this.server = parameters.server || this.server; this.serverPort = parameters.serverPort || this.serverPort; this.httpsecure = (parameters.httpsecure !== undefined) ? parameters.httpsecure : this.httpsecure; if (this.isNodeJS) { this.http = this.httpsecure ? require('https') : require('http'); } this.origin = ''; if (this.httpsecure !== undefined
javascript
{ "resource": "" }
q1144
expandKeys
train
function expandKeys(object) { var hasFlattenedKeys = _.some(object, function(val, key) { return key.split('.').length > 1; }); if (!hasFlattenedKeys) return object; return _.reduce(object, function(payload, value, key) { var path = key.split('.');
javascript
{ "resource": "" }
q1145
deepExtend
train
function deepExtend(target, source) { _.each(source, function(value, key) { if (_.has(target, key) && isObject(target[key]) && isObject(source[key])) {
javascript
{ "resource": "" }
q1146
query
train
function query(value, field, expression) { if (!expression) { return value; } var expressionQuery = {};
javascript
{ "resource": "" }
q1147
train
function() { var distDir = this.readConfig('distDir'); var packedDirName = this.readConfig('packedDirName'); var archivePath = this.readConfig('archivePath'); if (packedDirName) {
javascript
{ "resource": "" }
q1148
checkChain
train
function checkChain(value, chain, baton, callback) { var funs = chain.validators.map(function(i) { return i.func; }); function _reduce(memo, validator, callback) { validator(memo, baton, function(err, result) {
javascript
{ "resource": "" }
q1149
chainHelp
train
function chainHelp(chain) { return chain.validators.map(function(e) { return e.help; })
javascript
{ "resource": "" }
q1150
train
function() { if (! (this instanceof Chain)) { return new Chain(); } this.validators = []; this.target = null; this.isOptional = false;
javascript
{ "resource": "" }
q1151
train
function(schema, /* optional */ baton) { if (! (this instanceof Valve)) { return new Valve(schema,
javascript
{ "resource": "" }
q1152
createDitcherInstance
train
function createDitcherInstance(mongoUrl, callback) { // Default config used by ditcher if no connection string // is provided var config = { database: { host: process.env.MONGODB_HOST || '127.0.0.1', port: process.env.FH_LOCAL_DB_PORT || 27017, name: 'FH_LOCAL' } }; if (mongoUrl) { try {
javascript
{ "resource": "" }
q1153
train
function(next) { logger.log("DeregisterImage:", images); if (shell.isArg("-dry-run", options)) return next();
javascript
{ "resource": "" }
q1154
makeRequest
train
function makeRequest(capturedError) { req(app) .get('/bundle.js') .expect(500) .end(function(err, res) { if (err) { done(err); }
javascript
{ "resource": "" }
q1155
train
function(userIds) { return new Promise((resolve, reject) => { this._start() .uri('/api/user/bulk') .urlParameter('userId', userIds)
javascript
{ "resource": "" }
q1156
train
function(userId, applicationId, callerIPAddress) { return new Promise((resolve, reject) => { this._start() .uri('/api/login')
javascript
{ "resource": "" }
q1157
train
function(global, refreshToken) { return new Promise((resolve, reject) => { this._start() .uri('/api/logout') .urlParameter('global', global)
javascript
{ "resource": "" }
q1158
train
function(applicationId, start, end) { return new Promise((resolve, reject) => { this._start() .uri('/api/report/daily-active-user')
javascript
{ "resource": "" }
q1159
train
function(userId) { return new Promise((resolve, reject) => { this._start() .uri('/api/user') .urlSegment(userId)
javascript
{ "resource": "" }
q1160
train
function(userId, offset, limit) { return new Promise((resolve, reject) => { this._start() .uri('/api/report/user-login')
javascript
{ "resource": "" }
q1161
train
function(token, userId, applicationId) { return new Promise((resolve, reject) => { this._start() .uri('/api/jwt/refresh') .urlParameter('token', token) .urlParameter('userId',
javascript
{ "resource": "" }
q1162
train
function(request) { return new Promise((resolve, reject) => { this._start() .uri('/api/system/audit-log/search') .setJSONBody(request)
javascript
{ "resource": "" }
q1163
train
function(verificationId) { return new Promise((resolve, reject) => { this._start() .uri('/api/user/verify-email') .urlSegment(verificationId)
javascript
{ "resource": "" }
q1164
train
function(version) { var command = 'node_modules/.bin/bower uninstall ember && node_modules/.bin/bower install ember#' + version; grunt.log.writeln('Running bower install', command); try {
javascript
{ "resource": "" }
q1165
train
function(nodeUnitTaskName) { grunt.registerTask(nodeUnitTaskName, 'Nodeunit sync runner', function() { try { var result = execSync('node_modules/.bin/nodeunit --reporter="minimal"', { encoding: 'utf8' });
javascript
{ "resource": "" }
q1166
matchObj
train
function matchObj(obj, line) { for (const p in obj) if (obj[p]
javascript
{ "resource": "" }
q1167
processRow
train
function processRow(row) { if (!row) row = {}; for (var i = 0; i < hooks.length; i++)
javascript
{ "resource": "" }
q1168
updateTaxis
train
function updateTaxis() { var ids = [ "11", "22", "33" ]; var statuses = [ "avail", "busy", "scheduled" ]; var bbox = bkutils.geoBoundingBox(center[0], center[1], 2); // within 2 km from the center var latitude = lib.randomNum(bbox[0], bbox[2], 5); var longitude = lib.randomNum(bbox[1], bbox[3], 5);
javascript
{ "resource": "" }
q1169
mergeSubResource
train
function mergeSubResource(attrNode, subResourceConfig, context) { // Merge options from sub-resource to parent (order is irrelevant here): Object.keys(subResourceConfig).forEach(optionName => { if (optionName === 'attributes') { if (!attrNode.attributes) attrNode.attributes = {}; } else if (optionName === 'dataSources') { const newDataSources = Object.assign({}, subResourceConfig.dataSources); if (attrNode.dataSources) { Object.keys(attrNode.dataSources).forEach(dataSourceName => { if (newDataSources[dataSourceName]) { if (attrNode.dataSources[dataSourceName].inherit) { if (attrNode.dataSources[dataSourceName].inherit === 'inherit') { newDataSources[dataSourceName] = Object.assign( {}, newDataSources[dataSourceName], attrNode.dataSources[dataSourceName] ); } else if (attrNode.dataSources[dataSourceName].inherit === 'replace') { newDataSources[dataSourceName] = attrNode.dataSources[dataSourceName]; } } else { throw new ImplementationError(
javascript
{ "resource": "" }
q1170
getAttribute
train
function getAttribute(path, attrNode, context) { path.forEach((attributeName, i) => { if (!(attrNode.attributes && attrNode.attributes[attributeName])) { if (attrNode._origNodes) { let subAttrNode = null; attrNode._origNodes.forEach((origNode, inheritDepth) => { if (!origNode || !origNode.attributes || !origNode.attributes[attributeName]) return; let origSubAttrNode = origNode.attributes[attributeName]; if (subAttrNode) { if (subAttrNode.inherit === 'inherit') { // just add/merge options from sub-resource below } else if (subAttrNode.inherit === 'replace') { return; // just ignore options from sub-resource } else { let attrPath = context.attrPath.join('.'); throw new ImplementationError( `Cannot overwrite attribute "${attributeName}" in "${attrPath}" (maybe use "inherit"?)` ); } } else { subAttrNode = {}; } Object.keys(origSubAttrNode).forEach(optionName => { if (subAttrNode.hasOwnProperty(optionName)) return; // for inherit if (optionName === 'attributes') { subAttrNode[optionName] = {}; } else if (optionName === 'dataSources') { // DataSources are handled/cloned later in resolveResourceTree(): subAttrNode[optionName] = origSubAttrNode[optionName]; } else if (typeof origSubAttrNode[optionName] === 'object') {
javascript
{ "resource": "" }
q1171
resolveDataSourceAttributes
train
function resolveDataSourceAttributes(resourceTree, dataSources, primaryName) { Object.keys(dataSources).forEach(dataSourceName => { const dataSource = dataSources[dataSourceName]; dataSource.attributes = []; dataSource.attributeOptions = {}; }); resourceTree.attributes.forEach(function resolveAttribute(attrInfo) { let selectedDataSources; if (attrInfo.fromDataSource === '#same-group') { return attrInfo.attributes.forEach(resolveAttribute); // handle key-groups as flat } if (attrInfo.fromDataSource === '#all-selected') { attrInfo.attrNode.selectedDataSource = primaryName; selectedDataSources = []; Object.keys(dataSources).forEach(dataSourceName => { if (dataSources[dataSourceName].joinParentKey) return; selectedDataSources.push(dataSourceName); }); } else if (attrInfo.fromDataSource === '#current-primary') { attrInfo.attrNode.selectedDataSource = primaryName; selectedDataSources = [attrInfo.attrNode.selectedDataSource]; } else if (attrInfo.fromDataSource) { attrInfo.attrNode.selectedDataSource = attrInfo.fromDataSource; selectedDataSources = [attrInfo.attrNode.selectedDataSource]; } else { attrInfo.attrNode.selectedDataSource = Object.keys(attrInfo.dataSourceMap).find( dataSourceName => dataSources[dataSourceName] ); if (!attrInfo.attrNode.selectedDataSource) {
javascript
{ "resource": "" }
q1172
train
function () { var _this = this; console.info('INFO: creating tunnel to %s', this.proxyHost); this._tunnel = childProcess.spawn('ssh', this._buildSSHArgs()); var cleanup = function () { _this._tunnel.stderr.removeAllListeners('data'); }; this._tunnel.stderr.on('data', function (data) { if (/success/.test(data)) { cleanup(); return _this._resolveTunnel();
javascript
{ "resource": "" }
q1173
train
function () { if (!this._tunnel) { return q(); } var _this = this; this._tunnel.kill('SIGTERM'); return this._closeDeferred.promise.timeout(3000).fail(function () {
javascript
{ "resource": "" }
q1174
train
function(next) { core.allowPackages.forEach(function(pkg) { try { var mod = path.dirname(require.resolve(pkg)).replace(/\/lib$/, ""); core.packages[pkg] = { path: mod }; if (lib.statSync(mod + "/etc").isDirectory()) { core.packages[pkg].etc = 1; var cfg = lib.readFileSync(mod + "/etc/config"); if (cfg) { config = cfg + "\n" + config; core.packages[pkg].config = 1; core.parseConfig(cfg, 1); } } ["modules","locales","views","web"].forEach(function(x) {
javascript
{ "resource": "" }
q1175
train
function(next) { if (options.noModules) return next(); var opts = { denyModules: options.denyModules || core.denyModules[core.role] || core.denyModules[""], allowModules: options.allowModules || core.allowModules[core.role] || core.allowModules[""],
javascript
{ "resource": "" }
q1176
train
function(next) { var files = []; if (core.appPackage && core.packages[core.appPackage]) files.push(core.packages[core.appPackage].path); files.push(core.home, core.path.etc + "/..", __dirname + "/.."); for (var i in files) { var pkg = lib.readFileSync(files[i] + "/package.json", { json: 1, logger: "error", missingok: 1 }); logger.debug("init:", files[i] + "/package.json", pkg.name, pkg.version); if (!core.appName && pkg.name) core.appName = pkg.name; if (!core.appVersion && pkg.version) core.appVersion = pkg.version; if (!core.appDescr && pkg.description) core.appDescr = pkg.description;
javascript
{ "resource": "" }
q1177
train
function(next) { if (options.noDns || core.noDns) return next();
javascript
{ "resource": "" }
q1178
train
function(next) { try { process.umask(core.umask); } catch(e) { logger.error("umask:", core.umask, e) } // Create all subfolders with permissions, run it before initializing db which may create files in the spool folder if (!cluster.isWorker && !core.worker) { Object.keys(core.path).forEach(function(p) { var paths = Array.isArray(core.path[p]) ? core.path[p] : [core.path[p]]; paths.forEach(function(x) {
javascript
{ "resource": "" }
q1179
train
function(next) { if (options.noDb || core.noDb) return next();
javascript
{ "resource": "" }
q1180
train
function(next) { if (options.noDb || core.noDb) return next();
javascript
{ "resource": "" }
q1181
train
function(next) { if (!cluster.isWorker && !core.worker && process.getuid() == 0) {
javascript
{ "resource": "" }
q1182
train
function(next) { if (options.noConfigure || core.noConfigure) return next();
javascript
{ "resource": "" }
q1183
updateVersion2gitTag
train
function updateVersion2gitTag(pkg) { let tag = child_process.execSync('git
javascript
{ "resource": "" }
q1184
train
function(t, utc, lang, tz) { return zeropad(utc ?
javascript
{ "resource": "" }
q1185
_parse
train
function _parse(type, obj, options) { if (!obj) return _checkResult(type, lib.newError("empty " + type), obj, options); try { obj = _parseResult(type,
javascript
{ "resource": "" }
q1186
_checkResult
train
function _checkResult(type, err, obj, options) { if (options) { if (options.logger) logger.logger(options.logger, 'parse:', type, options, lib.traceError(err), obj); if (options.datatype == "object" || options.datatype == "obj") return
javascript
{ "resource": "" }
q1187
getConfig
train
function getConfig(fpath, defaults) { var path = require('path'); var dpath = path.dirname(path.resolve(fpath)); function parentpath(fromdir, pattern) { var pp = require('parentpath'), cwd = process.cwd(); try { process.chdir(fromdir); return pp.sync(pattern); } catch (e) { return null; } finally { process.chdir(cwd); } } function fromNpm() { var config; var dir = parentpath(dpath, 'package.json'); if (dir) { try { config = require(dir + '/package.json')[MJS_NPM]; config.__origin__ = dir + '/package.json'; } catch (e) { } } return config; } function fromResourceFile() { var candidates = [ parentpath(path, MJS_RC), process.env.HOME, process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOMEDRIVE + process.env.HOMEPATH ]; var config; for (var i = 0; i < candidates.length; i++)
javascript
{ "resource": "" }
q1188
walk
train
function walk(configDirectory, resourceName, resources) { resourceName = resourceName || ''; resources = resources || {}; fs.readdirSync(path.join(configDirectory, resourceName)).forEach(fileName => { const subResourceName = (resourceName !== '' ? resourceName + '/' : '') + fileName; const absoluteFilePath = path.join(configDirectory, subResourceName); const stat = fs.statSync(absoluteFilePath); if (stat && stat.isDirectory()) { walk(configDirectory, subResourceName, resources); } else if (resourceName !== '') { if (fileName.startsWith('config.')) {
javascript
{ "resource": "" }
q1189
Client
train
function Client(options) { this.accessID = options.accessID; this.accessKey = options.accessKey; this.signatureMethod = options.signatureMethod || 'HmacSHA1'; this.signatureVersion = options.signatureVersion || '1'; this.APIVersion = options.APIVersion || '2013-05-10'; this.APIHost = options.APIHost || 'http://ots.aliyuncs.com'; // protocol: 'http:' // hostname: 'service.ots.aliyun.com' // port:
javascript
{ "resource": "" }
q1190
getDataSource
train
function getDataSource(node) { const config = Object.assign({}, copyXmlAttributes(node)); if (node.childNodes.length) { // parse datasource options for (let i = 0; i < node.childNodes.length; ++i) { const childNode = node.childNodes.item(i); if (childNode.nodeType === TEXT_NODE && childNode.textContent.trim().length > 0) { throw new ImplementationError(`dataSource contains useless text: "${childNode.textContent.trim()}"`); } if ( childNode.nodeType === ELEMENT_NODE &&
javascript
{ "resource": "" }
q1191
parse
train
function parse(node) { const cfg = Object.assign({}, copyXmlAttributes(node)); for (let i = 0, l = node.childNodes.length; i < l; ++i) { const el = node.childNodes.item(i); if (el.nodeType === ELEMENT_NODE) { if (!el.namespaceURI) { // attribute elements if (!cfg.attributes) cfg.attributes = {}; cfg.attributes[el.localName] = el.childNodes.length ? parse(el) : copyXmlAttributes(el); } else if (el.namespaceURI === 'urn:flora:options') { // flora specific elements if (el.localName === 'dataSource') { const dataSource = getDataSource(el); if (!cfg.dataSources) cfg.dataSources = {}; if (cfg.dataSources[dataSource.name]) { throw new Error(`Data source "${dataSource.name}" already defined`); }
javascript
{ "resource": "" }
q1192
getAttribute
train
function getAttribute(path, attrNode) { path.forEach(attrName => { if (!(attrNode.attributes && attrNode.attributes[attrName])) { throw new ImplementationError(`Result-Builder: Unknown attribute
javascript
{ "resource": "" }
q1193
preprocessRawResults
train
function preprocessRawResults(rawResults, resolvedConfig) { rawResults.forEach((rawResult, resultId) => { if (!rawResult.attributePath) return; // e.g. sub-filter results don't need indexing // link resultIds into attribute tree (per DataSource): const attrNode = getAttribute(rawResult.attributePath, resolvedConfig); attrNode.dataSources[rawResult.dataSourceName].resultId = resultId; // index rows by childKey if available // (top-level result has no childKey and does not need to be indexed): if (rawResult.childKey) { const keyAttr = rawResult.childKey.length === 1 ? rawResult.childKey[0] : null; rawResult.indexedData = {}; rawResult.data.forEach((row, i) => { function dereferenceKeyAttr(keyAttrib) { const keyVal = row[keyAttrib]; if (keyVal === undefined) { const attrPath = rawResult.attributePath.length > 0 ? rawResult.attributePath.join('.') : '{root}'; throw new DataError( `Result-row ${i} of "${attrPath}" (DataSource "${ rawResult.dataSourceName }") misses child key attribute "${keyAttr}"` ); } return keyVal; } const key = keyAttr ? '' + dereferenceKeyAttr(keyAttr) // speed up non-composite keys
javascript
{ "resource": "" }
q1194
parseNode
train
function parseNode(attrNode, parsers, context) { const attrNames = Object.keys(attrNode); const errorContext = context.errorContext; Object.keys(parsers).forEach(attrName => { const parser = parsers[attrName]; context.errorContext = ` (option "${attrName}"${errorContext})`; removeValue(attrNames, attrName); if (attrName in attrNode && parser !== null) {
javascript
{ "resource": "" }
q1195
checkIdentifier
train
function checkIdentifier(str, context) { if (!/^[a-zA-Z_][a-zA-Z_0-9]*$/.test(str)) {
javascript
{ "resource": "" }
q1196
parseAttributePath
train
function parseAttributePath(attrPath, context) { const parsed =
javascript
{ "resource": "" }
q1197
parsePrimaryKey
train
function parsePrimaryKey(attrPathList, context) { return
javascript
{ "resource": "" }
q1198
checkWhitelist
train
function checkWhitelist(str, whitelist, context) { if (whitelist.indexOf(str) === -1) { throw new ImplementationError( 'Invalid "' + str
javascript
{ "resource": "" }
q1199
parseList
train
function parseList(list, whitelist, context) { const parsed = list.split(',');
javascript
{ "resource": "" }