_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q59400
|
workflowGuidWorkflowLocale
|
validation
|
function workflowGuidWorkflowLocale() {
return self.apos.docs.db.ensureIndex({ workflowGuid: 1, workflowLocale: 1 }, { sparse: 1, unique: 1 })
// eslint-disable-next-line handle-callback-err
.catch(function(err) {
return resolveDuplicateDocs()
.then(function() {
// now we can try the index again, recursively
return workflowGuidWorkflowLocale();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q59401
|
replaceIdsRecursively
|
validation
|
function replaceIdsRecursively(doc) {
_.each(doc, function(val, key) {
if (key === 'workflowGuidAndLocaleDuplicates') {
// Do not alter ids inside the historical archive of
// the original orphaned docs. -Tom
return;
}
if ((typeof (val) === 'string') && (val.length < 100)) {
if (idsToNew[val]) {
self.apos.utils.warn('Correcting ' + doc[key] + ' to ' + idsToNew[val] + ' in join');
doc[key] = idsToNew[val];
modified = true;
}
} else if (val && (typeof (val) === 'object')) {
replaceIdsRecursively(val);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q59402
|
fallback
|
validation
|
function fallback(callback) {
return async.series([ viaBasis, noBasis ], callback);
function viaBasis(callback) {
return self.apos.migrations.eachDoc({ workflowLocale: basis }, 5, function(doc, callback) {
if (!self.includeType(doc.type)) {
return setImmediate(callback);
}
doc.workflowResolveDeferred = true;
var afterSaveOptions = _.assign({}, options, {
permissions: false,
workflowMissingLocalesLive: self.apos.argv.live ? true : 'liveOnly'
});
return self.docAfterSave(req, doc, afterSaveOptions, callback);
}, callback);
}
function noBasis(callback) {
var localeNames = Object.keys(self.locales);
var orphans;
return async.series([ find, fix ], callback);
function find(callback) {
const query = [
{
$match: {
workflowLocale: { $in: localeNames }
}
},
{
$group: {
_id: "$workflowGuid",
count: { $sum: 1 }
}
},
{
$match: {
count: { $lt: localeNames.length }
}
}
];
return self.apos.docs.db.aggregate(query).toArray(function(err, _orphans) {
if (err) {
return callback(err);
}
orphans = _orphans;
return callback(null);
});
}
function fix(callback) {
var seen = {};
if (!orphans.length) {
return callback(null);
}
// The aggregation query returns the workflowGuids but I haven't been able to
// convince it to give me representative _ids to go with them, so we will just
// ignore the additional locales after we fix each one once. -Tom
return self.apos.migrations.eachDoc({ workflowGuid: { $in: _.pluck(orphans, '_id') } }, 5, function(doc, callback) {
if (seen[doc.workflowGuid]) {
return setImmediate(callback);
}
seen[doc.workflowGuid] = true;
if (!self.includeType(doc.type)) {
return setImmediate(callback);
}
doc.workflowResolveDeferred = true;
var afterSaveOptions = _.assign({}, options, {
permissions: false,
workflowMissingLocalesLive: self.apos.argv.live ? true : 'liveOnly'
});
return self.docAfterSave(req, doc, afterSaveOptions, callback);
}, callback);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q59403
|
getWorkflowGuids
|
validation
|
function getWorkflowGuids(callback) {
return self.apos.docs.db.findWithProjection(
{ _id: { $in: _.pluck(related, '_id') } },
{ _id: 1, workflowGuid: 1, type: 1 }
).toArray(function(err, guidDocs) {
if (err) {
return fail(err);
}
_.each(guidDocs, function(guidDoc) {
var relatedOne = _.find(related, { _id: guidDoc._id });
if (relatedOne) {
relatedOne.workflowGuid = guidDoc.workflowGuid;
idsByGuid[relatedOne.workflowGuid] = relatedOne._id;
relatedOne.type = guidDoc.type;
}
});
// Discard unless the type is known, the type is subject to
// workflow and we have the workflowGuid
related = _.filter(related, function(relatedOne) {
return relatedOne.type && relatedOne.workflowGuid && self.includeType(relatedOne.type);
});
return callback(null);
});
}
|
javascript
|
{
"resource": ""
}
|
q59404
|
toAwsParams
|
validation
|
function toAwsParams(file) {
var params = {};
var headers = file.s3.headers || {};
for (var header in headers) {
if (header === 'x-amz-acl') {
params.ACL = headers[header];
} else if (header === 'Content-MD5') {
params.ContentMD5 = headers[header];
} else {
params[pascalCase(header)] = headers[header];
}
}
params.Key = file.s3.path;
params.Body = file.contents;
return params;
}
|
javascript
|
{
"resource": ""
}
|
q59405
|
Publisher
|
validation
|
function Publisher(AWSConfig, cacheOptions) {
this.config = AWSConfig;
this.client = new AWS.S3(AWSConfig);
var bucket = this.config.params.Bucket;
if (!bucket) {
throw new Error('Missing `params.Bucket` config value.');
}
// init Cache file
this._cacheFile =
cacheOptions && cacheOptions.cacheFileName
? cacheOptions.cacheFileName
: '.awspublish-' + bucket;
// load cache
try {
this._cache = JSON.parse(fs.readFileSync(this.getCacheFilename(), 'utf8'));
} catch (err) {
this._cache = {};
}
}
|
javascript
|
{
"resource": ""
}
|
q59406
|
ZarinPal
|
validation
|
function ZarinPal(MerchantID, sandbox) {
if (typeof MerchantID === 'string' && MerchantID.length === config.merchantIDLength) {
this.merchant = MerchantID;
} else {
console.error('The MerchantID must be ' + config.merchantIDLength + ' Characters.');
return false;
}
this.sandbox = sandbox || false;
this.url = (sandbox === true) ? config.sandbox : config.https;
}
|
javascript
|
{
"resource": ""
}
|
q59407
|
deferred
|
validation
|
function deferred() {
var outResolve = function() {}; // will be overwritten
var outReject = function() {}; // will be overwritten
var promise = new Promise(function (resolve, reject) {
outResolve = resolve;
outReject = reject;
});
return {
promise: promise,
resolve: outResolve,
reject: outReject,
};
}
|
javascript
|
{
"resource": ""
}
|
q59408
|
parseResponse
|
validation
|
async function parseResponse(header, response, active = false, id) {
const rows = [];
_.each(response, (value, key) => {
let row = [];
if (active) {
_.each(response[key].active, (activeValue) => {
row = [];
// filter by id
if (id === undefined || activeValue.job_id === id || activeValue.ex_id === id) {
_.each(header, (item) => {
if (item === 'teraslice_version') {
row.push(response[key].teraslice_version);
} else if (item === 'node_id') {
row.push(response[key].node_id);
} else if (item === 'hostname') {
row.push(response[key].hostname);
} else if (item === 'node_version') {
row.push(response[key].node_version);
} else {
row.push(activeValue[item]);
}
});
rows.push(row);
}
});
} else {
_.each(header, (item) => {
if (item === 'active') {
row.push(response[key][item].length);
} else {
row.push(response[key][item]);
}
});
rows.push(row);
}
});
return rows;
}
|
javascript
|
{
"resource": ""
}
|
q59409
|
display
|
validation
|
async function display(header, items, type, active = false, parse = false, id) {
let rows;
if (type === 'txt') {
await text(header, items);
} else if (type === 'txtHorizontal') {
const opts = {
head: header,
chars: {
top: '',
'top-mid': '',
'top-left': '',
'top-right': '',
bottom: '',
'bottom-mid': '',
'bottom-left': '',
'bottom-right': '',
left: '',
'left-mid': '',
mid: '',
'mid-mid': '',
right: '',
'right-mid': '',
middle: ' '.repeat(2)
},
style: {
'padding-left': 0, 'padding-right': 0, head: ['white'], border: ['white']
}
};
if (parse) {
rows = await parseResponse(header, items, active, id);
await horizontal(rows, opts);
} else {
await horizontal(items, opts);
}
} else if (type === 'prettyHorizontal') {
const opts = {
head: header,
style: { 'padding-left': 0, 'padding-right': 0, head: ['blue'] }
};
if (parse) {
rows = await parseResponse(header, items, active, id);
await horizontal(rows, opts);
} else {
await horizontal(items, opts);
}
} else if (type === 'txtVertical') {
const style = {
chars: {
top: '',
'top-mid': '',
'top-left': '',
'top-right': '',
bottom: '',
'bottom-mid': '',
'bottom-left': '',
'bottom-right': '',
left: '',
'left-mid': '',
mid: '',
'mid-mid': '',
right: '',
'right-mid': '',
middle: ' '.repeat(3)
},
style: {
'padding-left': 0, 'padding-right': 0, head: ['white']
}
};
if (parse) {
rows = await parseResponse(header, items, active, id);
await vertical(header, rows, style);
} else {
await vertical(header, items, style);
}
} else if (type === 'prettyVertical') {
const style = {
style: { 'padding-left': 0, 'padding-right': 0, head: ['blue'] }
};
if (parse) {
rows = await parseResponse(header, items, active, id);
await vertical(header, rows, style);
} else {
await vertical(header, items, style);
}
} else {
await pretty(header, items);
}
}
|
javascript
|
{
"resource": ""
}
|
q59410
|
_getClusterState
|
validation
|
function _getClusterState() {
return k8s.list('app=teraslice', 'pods')
.then(k8sPods => k8sState.gen(k8sPods, clusterState, clusterNameLabel))
.catch((err) => {
// TODO: We might need to do more here. I think it's OK to just
// log though. This only gets used to show slicer info through
// the API. We wouldn't want to disrupt the cluster master
// for rare failures to reach the k8s API.
logger.error(err, 'Error listing teraslice pods in k8s');
});
}
|
javascript
|
{
"resource": ""
}
|
q59411
|
allocateWorkers
|
validation
|
function allocateWorkers(execution) {
const kr = new K8sResource(
'deployments', 'worker', context.sysconfig.teraslice, execution
);
const workerDeployment = kr.resource;
logger.debug(`workerDeployment:\n\n${JSON.stringify(workerDeployment, null, 2)}`);
return k8s.post(workerDeployment, 'deployment')
.then(result => logger.debug(`k8s worker deployment submitted: ${JSON.stringify(result)}`))
.catch((err) => {
const error = new TSError(err, {
reason: 'Error submitting k8s worker deployment'
});
return Promise.reject(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q59412
|
getChunk
|
validation
|
function getChunk(readerClient, slice, opConfig, logger, metadata) {
const delimiter = opConfig.line_delimiter;
async function getMargin(offset, length) {
let margin = '';
return new Promise(async (resolve) => {
while (margin.indexOf(delimiter) === -1) {
// reader clients must return false-y when nothing more to read.
const chunk = await readerClient(offset, length); // eslint-disable-line no-await-in-loop, max-len
if (!chunk) {
resolve(margin.split(delimiter)[0]);
return;
}
margin += chunk;
offset += length; // eslint-disable-line no-param-reassign, max-len
}
// Don't read too far - next slice will get it.
resolve(margin.split(delimiter)[0]);
});
}
let needMargin = false;
if (slice.length) {
// Determines whether or not to grab the extra margin.
if (slice.offset + slice.length !== slice.total) {
needMargin = true;
}
}
return readerClient(slice.offset, slice.length)
.then(async (data) => {
if (data.endsWith(delimiter)) {
// Skip the margin if the raw data ends with the delimiter since
// it will end with a complete record.
needMargin = false;
}
if (needMargin) {
// Want to minimize reads since will typically be over the
// network. Using twice the average record size as a heuristic.
const avgSize = _averageRecordSize(data.split(delimiter));
data += await getMargin(slice.offset + slice.length, 2 * avgSize); // eslint-disable-line no-param-reassign, max-len
}
return data;
})
.then(data => chunkFormatter[opConfig.format](data, logger, opConfig, metadata, slice));
}
|
javascript
|
{
"resource": ""
}
|
q59413
|
finishExecution
|
validation
|
function finishExecution(exId, err) {
if (err) {
const error = new TSError(err, {
reason: `terminal error for execution: ${exId}, shutting down execution`,
context: {
ex_id: exId,
}
});
logger.error(error);
}
return getExecutionContext(exId)
.then((execution) => {
const status = execution._status;
if (['stopping', 'stopped'].includes(status)) {
logger.debug(`execution ${exId} is already stopping which means there is no need to stop the execution`);
return true;
}
logger.debug(`execution ${exId} finished, shutting down execution`);
return clusterService.stopExecution(exId).catch((stopErr) => {
const stopError = new TSError(stopErr, {
reason: 'error finishing the execution',
context: {
ex_id: exId,
}
});
logger.error(stopError);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q59414
|
getActiveExecution
|
validation
|
function getActiveExecution(exId) {
const str = terminalStatusList().map(state => ` _status:${state} `).join('OR');
const query = `ex_id: ${exId} NOT (${str.trim()})`;
return searchExecutionContexts(query, null, 1, '_created:desc')
.then((ex) => {
if (ex.length === 0) {
const error = new Error(`no active execution context was found for ex_id: ${exId}`);
error.code = 404;
return Promise.reject(error);
}
return ex[0];
});
}
|
javascript
|
{
"resource": ""
}
|
q59415
|
gen
|
validation
|
function gen(k8sPods, clusterState, clusterNameLabel) {
// Make sure we clean up the old
const hostIPs = _.uniq(_.map(k8sPods.items, 'status.hostIP'));
const oldHostIps = _.difference(_.keys(clusterState), hostIPs);
_.forEach(oldHostIps, (ip) => {
delete clusterState[ip];
});
// Loop over the nodes in clusterState and set active = [] so we can append
// later
Object.keys(clusterState).forEach((nodeId) => {
clusterState[nodeId].active = [];
});
// add a worker for each pod
k8sPods.items.forEach((pod) => {
// Teraslice workers and execution controllers have the `clusterName`
// label that matches their cluster name attached to their k8s pods.
// If these labels don't match the supplied `clusterNameLabel`
// then it is assumed that the pod is not a member of this cluster
// so it is omitted from clusterState.
// NOTE: The cluster master will not appear in cluster state if they do
// not label it with clusterName=clusterNameLabel
if (pod.metadata.labels.clusterName === clusterNameLabel) {
if (!_.has(clusterState, pod.status.hostIP)) {
// If the node isn't in clusterState, add it
clusterState[pod.status.hostIP] = {
node_id: pod.status.hostIP,
hostname: pod.status.hostIP,
pid: 'N/A',
node_version: 'N/A',
teraslice_version: 'N/A',
total: 'N/A',
state: 'connected',
available: 'N/A',
active: []
};
}
const worker = {
assets: [],
assignment: pod.metadata.labels.nodeType,
ex_id: pod.metadata.labels.exId,
// WARNING: This makes the assumption that the first container
// in the pod is the teraslice container. Currently it is the
// only container, so this assumption is safe for now.
image: pod.spec.containers[0].image,
job_id: pod.metadata.labels.jobId,
pod_name: pod.metadata.name,
pod_ip: pod.status.podIP,
worker_id: pod.metadata.name,
};
// k8s pods can have status.phase = `Pending`, `Running`, `Succeeded`,
// `Failed`, `Unknown`. We will only add `Running` pods to the
// Teraslice cluster state.
if (pod.status.phase === 'Running') {
clusterState[pod.status.hostIP].active.push(worker);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q59416
|
errorHandler
|
validation
|
function errorHandler(err) {
// eslint-disable-next-line no-console
const logErr = logger ? logger.error.bind(logger) : console.log;
if (cluster.isMaster) {
logErr(`Error in master with pid: ${process.pid}`);
} else {
logErr(`Error in worker: ${cluster.worker.id} pid: ${process.pid}`);
}
if (err.message) {
logErr(err.message);
} else {
logErr(err);
}
if (err.stack) {
logErr(err.stack);
}
// log saving to disk is async, using hack to give time to flush
setTimeout(() => {
process.exit(-1);
}, 600);
}
|
javascript
|
{
"resource": ""
}
|
q59417
|
allocateWorkers
|
validation
|
function allocateWorkers(execution, numOfWorkersRequested) {
const exId = execution.ex_id;
const jobId = execution.job_id;
const jobStr = JSON.stringify(execution);
const sortedNodes = _.orderBy(clusterState, 'available', 'desc');
let workersRequested = numOfWorkersRequested;
let availWorkers = _availableWorkers(false, true);
const dispatch = _makeDispatch();
while (workersRequested > 0 && availWorkers > 0) {
for (let i = 0; i < sortedNodes.length; i += 1) {
// each iteration check if it can allocate
if (workersRequested > 0 && availWorkers > 0) {
if (sortedNodes[i].available >= 1) {
dispatch.set(sortedNodes[i].node_id, 1);
availWorkers -= 1;
workersRequested -= 1;
}
} else {
break;
}
}
}
// if left over worker requests, enqueue them, queue works based off of id
// so it redundantly references ex_id
const workerData = {
job: jobStr,
id: exId,
ex_id: exId,
job_id: jobId,
workers: 1,
assignment: 'worker'
};
while (workersRequested > 0) {
logger.trace(`adding worker to pending queue for ex: ${exId}`);
pendingWorkerRequests.enqueue(workerData);
workersRequested -= 1;
}
const results = [];
_.forOwn(dispatch.getDispatch(), (workerCount, nodeId) => {
const requestedWorkersData = {
job: jobStr,
id: exId,
ex_id: exId,
job_id: jobId,
workers: workerCount,
assignment: 'worker'
};
const createRequest = messaging.send({
to: 'node_master',
address: nodeId,
message: 'cluster:workers:create',
payload: requestedWorkersData,
response: true
}).then((msg) => {
const createdWorkers = _.get(msg, 'payload.createdWorkers');
if (!_.isInteger(createdWorkers)) {
logger.error(`malformed response from create workers request to node ${nodeId}`, msg);
return;
}
if (createdWorkers < workerCount) {
logger.warn(`node ${nodeId} was only able to allocate ${createdWorkers} the request worker count of ${workerCount}, enqueing the remainder`);
const newWorkersRequest = _.cloneDeep(requestedWorkersData);
newWorkersRequest.workers = workerCount - createdWorkers;
pendingWorkerRequests.enqueue(newWorkersRequest);
} else {
logger.debug(`node ${nodeId} allocated ${createdWorkers}`);
}
}).catch((err) => {
logger.error(err, `An error has occurred in allocating : ${workerCount} workers to node : ${nodeId}, the worker request has been enqueued`);
pendingWorkerRequests.enqueue(requestedWorkersData);
});
results.push(createRequest);
});
// this will resolve successfully if one worker was actually allocated
return Promise.all(results);
}
|
javascript
|
{
"resource": ""
}
|
q59418
|
getRecord
|
validation
|
function getRecord(recordId, indexArg, fields) {
logger.trace(`getting record id: ${recordId}`);
const query = {
index: indexArg || indexName,
type: recordType,
id: recordId
};
if (fields) {
query._source = fields;
}
return elasticsearch.get(query);
}
|
javascript
|
{
"resource": ""
}
|
q59419
|
verifyStatusUpdate
|
validation
|
function verifyStatusUpdate(exId, desiredStatus) {
if (!desiredStatus || !_isValidStatus(desiredStatus)) {
const error = new Error(`Invalid Job status: "${desiredStatus}"`);
error.statusCode = 422;
return Promise.reject(error);
}
return getStatus(exId)
.then((status) => {
// when setting the same status to shouldn't throw an error
if (desiredStatus === status) {
return Promise.resolve();
}
// when the current status is running it cannot be set to an init status
if (_isRunningStatus(status) && _isInitStatus(desiredStatus)) {
const error = new Error(`Cannot update running job status of "${status}" to init status of "${desiredStatus}"`);
return Promise.reject(error);
}
// when the status is a terminal status, it cannot be set to again
if (_isTerminalStatus(status)) {
const error = new Error(`Cannot update terminal job status of "${status}" to "${desiredStatus}"`);
return Promise.reject(error);
}
// otherwise allow the update
return Promise.resolve(status);
});
}
|
javascript
|
{
"resource": ""
}
|
q59420
|
_attachRoomsSocketIO
|
validation
|
function _attachRoomsSocketIO() {
if (!io) return;
// middleware
io.use((socket, next) => {
const {
node_id: nodeId,
} = socket.handshake.query;
if (nodeId) {
logger.info(`node ${nodeId} joining room on connect`);
socket.join(nodeId);
}
return next();
});
}
|
javascript
|
{
"resource": ""
}
|
q59421
|
_toRecords
|
validation
|
function _toRecords(rawData, delimiter, slice) {
// Since slices with a non-zero chunk offset grab the character
// immediately preceding the main chunk, if one of those chunks has a
// delimiter as the first or second character, it means the chunk starts
// with a complete record. In this case as well as when the chunk begins
// with a partial record, splitting the chunk into an array by its
// delimiter will result in a single garbage record at the beginning of
// the array. If the offset is 0, the array will never start with a
// garbage record
let outputData = rawData;
if (rawData.endsWith(delimiter)) {
// Get rid of last character if it is the delimiter since that will
// just result in an empty record.
outputData = rawData.slice(0, -delimiter.length);
}
if (slice.offset === 0) {
return outputData.split(delimiter);
}
return outputData.split(delimiter).splice(1);
}
|
javascript
|
{
"resource": ""
}
|
q59422
|
raw
|
validation
|
function raw(incomingData, logger, opConfig, metadata, slice) {
const data = _toRecords(incomingData, opConfig.line_delimiter, slice);
return data.map((record) => {
try {
return DataEntity.make(
{ data: record },
metadata
);
} catch (err) {
if (opConfig._dead_letter_action === 'log') {
logger.error(err, 'Bad record:', record);
} else if (opConfig._dead_letter_action === 'throw') {
throw err;
}
return null;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q59423
|
tsv
|
validation
|
function tsv(incomingData, logger, opConfig, metadata, slice) {
return csv(incomingData, logger, opConfig, metadata, slice);
}
|
javascript
|
{
"resource": ""
}
|
q59424
|
TransformStreamCloseReadable
|
validation
|
function TransformStreamCloseReadable(transformStream) {
// console.log('TransformStreamCloseReadable()');
if (transformStream._errored === true) {
throw new TypeError('TransformStream is already errored');
}
if (transformStream._readableClosed === true) {
throw new TypeError('Readable side is already closed');
}
TransformStreamCloseReadableInternal(transformStream);
}
|
javascript
|
{
"resource": ""
}
|
q59425
|
TransformStreamCloseReadableInternal
|
validation
|
function TransformStreamCloseReadableInternal(transformStream) {
assert(transformStream._errored === false);
assert(transformStream._readableClosed === false);
try {
ReadableStreamDefaultControllerClose(transformStream._readableController);
} catch (e) {
assert(false);
}
transformStream._readableClosed = true;
}
|
javascript
|
{
"resource": ""
}
|
q59426
|
pipeLoop
|
validation
|
function pipeLoop() {
currentWrite = Promise.resolve();
if (shuttingDown === true) {
return Promise.resolve();
}
return writer._readyPromise.then(() => {
return ReadableStreamDefaultReaderRead(reader).then(({ value, done }) => {
if (done === true) {
return undefined;
}
currentWrite = WritableStreamDefaultWriterWrite(writer, value);
return currentWrite;
});
})
.then(pipeLoop);
}
|
javascript
|
{
"resource": ""
}
|
q59427
|
ReadableStreamAddReadIntoRequest
|
validation
|
function ReadableStreamAddReadIntoRequest(stream) {
assert(IsReadableStreamBYOBReader(stream._reader) === true);
assert(stream._state === 'readable' || stream._state === 'closed');
const promise = new Promise((resolve, reject) => {
const readIntoRequest = {
_resolve: resolve,
_reject: reject
};
stream._reader._readIntoRequests.push(readIntoRequest);
});
return promise;
}
|
javascript
|
{
"resource": ""
}
|
q59428
|
ReadableStreamReaderGenericCancel
|
validation
|
function ReadableStreamReaderGenericCancel(reader, reason) {
const stream = reader._ownerReadableStream;
assert(stream !== undefined);
return ReadableStreamCancel(stream, reason);
}
|
javascript
|
{
"resource": ""
}
|
q59429
|
ReadableStreamDefaultControllerClose
|
validation
|
function ReadableStreamDefaultControllerClose(controller) {
const stream = controller._controlledReadableStream;
assert(controller._closeRequested === false);
assert(stream._state === 'readable');
controller._closeRequested = true;
if (controller._queue.length === 0) {
ReadableStreamClose(stream);
}
}
|
javascript
|
{
"resource": ""
}
|
q59430
|
ReadableByteStreamControllerClose
|
validation
|
function ReadableByteStreamControllerClose(controller) {
const stream = controller._controlledReadableStream;
assert(controller._closeRequested === false);
assert(stream._state === 'readable');
if (controller._totalQueuedBytes > 0) {
controller._closeRequested = true;
return;
}
if (controller._pendingPullIntos.length > 0) {
const firstPendingPullInto = controller._pendingPullIntos[0];
if (firstPendingPullInto.bytesFilled > 0) {
const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
ReadableByteStreamControllerError(controller, e);
throw e;
}
}
ReadableStreamClose(stream);
}
|
javascript
|
{
"resource": ""
}
|
q59431
|
WritableStreamAddWriteRequest
|
validation
|
function WritableStreamAddWriteRequest(stream) {
assert(IsWritableStreamLocked(stream) === true);
assert(stream._state === 'writable');
const promise = new Promise((resolve, reject) => {
const writeRequest = {
_resolve: resolve,
_reject: reject
};
stream._writeRequests.push(writeRequest);
});
return promise;
}
|
javascript
|
{
"resource": ""
}
|
q59432
|
IsWritableStreamDefaultWriter
|
validation
|
function IsWritableStreamDefaultWriter(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q59433
|
WritableStreamDefaultWriterAbort
|
validation
|
function WritableStreamDefaultWriterAbort(writer, reason) {
const stream = writer._ownerWritableStream;
assert(stream !== undefined);
return WritableStreamAbort(stream, reason);
}
|
javascript
|
{
"resource": ""
}
|
q59434
|
WritableStreamDefaultControllerAbort
|
validation
|
function WritableStreamDefaultControllerAbort(controller, reason) {
controller._queue = [];
const sinkAbortPromise = PromiseInvokeOrFallbackOrNoop(controller._underlyingSink, 'abort', [reason],
'close', [controller]);
return sinkAbortPromise.then(() => undefined);
}
|
javascript
|
{
"resource": ""
}
|
q59435
|
WritableStreamDefaultControllerError
|
validation
|
function WritableStreamDefaultControllerError(controller, e) {
const stream = controller._controlledWritableStream;
assert(stream._state === 'writable' || stream._state === 'closing');
WritableStreamError(stream, e);
controller._queue = [];
}
|
javascript
|
{
"resource": ""
}
|
q59436
|
pipe
|
validation
|
function pipe() {
var _this = this;
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
var _done = false;
var targets = items.map(wrap_async_iterable_iterator_1.wrapAsyncIterableIterator);
var call = function (methodName, value) {
return new Promise(function (resolve, reject) {
var remaining = targets.concat();
var next = function (_a) {
var value = _a.value, done = _a.done;
if (!_done) {
_done = done;
}
// if one piped item finishes, then we need to finish
if (!remaining.length || _done) {
if (methodName === "next") {
while (remaining.length) {
(remaining.shift().return || (function () { }))();
}
}
return resolve({ value: value, done: done });
}
var fn = remaining.shift()[methodName];
return fn ? fn(value).then(next, reject) : next(value);
};
next({ value: value, done: false });
});
};
return _a = {},
_a[Symbol.asyncIterator] = function () { return _this; },
_a.next = call.bind(this, "next"),
_a.return = call.bind(this, "return"),
_a.throw = call.bind(this, "throw"),
_a;
var _a;
}
|
javascript
|
{
"resource": ""
}
|
q59437
|
validation
|
function() {
var uris = [];
var db = this.getAnalyser().getDatabase();
function add(classname) {
var def = db.classInfo[classname];
uris.push(def.libraryName + ":" + classname.replace(/\./g, "/") + ".js");
}
this.__loadDeps.forEach(add);
return uris;
}
|
javascript
|
{
"resource": ""
}
|
|
q59438
|
validation
|
function() {
var result = {};
this.__classes.forEach(name => result[name] = true);
this.__expandClassnames(this.getInclude()).forEach(name => result[name] = true);
this.__expandClassnames(this.getExclude()).forEach(name => delete result[name]);
// We sort the result so that we can get a consistent ordering for loading classes, otherwise the order in
// which the filing system returns the files can cause classes to be loaded in a lightly different sequence;
// that would not cause a problem, except that the build is not 100% repeatable.
return Object.keys(result).sort();
}
|
javascript
|
{
"resource": ""
}
|
|
q59439
|
validation
|
function(value, oldValue) {
var loader = path.join(__dirname, "loader-" + (this.isBrowserApp() ? "browser" : "server") + ".tmpl.js");
this.setLoaderTemplate(loader);
this.setTheme(null);
}
|
javascript
|
{
"resource": ""
}
|
|
q59440
|
mkpath
|
validation
|
function mkpath(dir, cb) {
dir = path.normalize(dir);
var segs = dir.split(path.sep);
var made = "";
async.eachSeries(
segs,
function(seg, cb) {
if (made.length || !seg.length) {
made += "/";
}
made += seg;
fs.exists(made, function(exists) {
if (!exists) {
fs.mkdir(made, function(err) {
if (err && err.code === "EEXIST") {
err = null;
}
cb(err);
});
return;
}
fs.stat(made, function(err, stat) {
if (err) {
cb(err);
} else if (stat.isDirectory()) {
cb(null);
} else {
cb(new Error("Cannot create " + made + " (in " + dir + ") because it exists and is not a directory", "ENOENT"));
}
});
});
},
function(err) {
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q59441
|
validation
|
function() {
var t = this;
var p;
if (!this.__opened) {
this.__opened = true;
var resManager = null;
if (this.isProcessResources()) {
resManager = new qx.tool.compiler.resources.Manager(this);
}
this.__resManager = resManager;
p = Promise.all(
[
util.promisifyThis(t.loadDatabase, t),
new Promise((resolve, reject) => {
if (resManager) {
log.debug("Loading resource database");
return util.promisifyThis(resManager.loadDatabase, resManager)
.then(resolve)
.catch(reject);
}
resolve();
return undefined;
})
]);
} else {
p = Promise.resolve();
}
return p.then(() => {
log.debug("Scanning source code");
return util.promisifyThis(t.initialScan, t);
})
.then(() => {
log.debug("Saving database");
return t.saveDatabase();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q59442
|
validation
|
function(cb) {
var t = this;
if (!this.__db) {
this.__db = {};
}
async.parallel(
[
// Load Resources
function(cb) {
if (!t.__resManager) {
cb(null);
return;
}
t.__resManager.findAllResources(function(err) {
if (err) {
cb(err);
return;
}
log.debug("found all resources");
cb(null);
});
},
// Find all classes
function(cb) {
async.each(t.__libraries,
function(library, cb) {
library.scanForClasses(err => {
log.debug("Finished scanning for " + library.getNamespace());
cb(err);
});
},
err => {
log.debug("Finished scanning for all libraries");
cb(err);
});
}
],
function(err) {
log.debug("processed source and resources");
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q59443
|
validation
|
function(cb) {
async.each(t.__libraries,
function(library, cb) {
library.scanForClasses(err => {
log.debug("Finished scanning for " + library.getNamespace());
cb(err);
});
},
err => {
log.debug("Finished scanning for all libraries");
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q59444
|
validation
|
function(cb) {
var t = this;
async.waterfall(
[
/**
* Reads the db.json, if it exists
*
* @param cb
*/
function readDb(cb) {
fs.exists(t.getDbFilename(), function(exists) {
if (exists) {
fs.readFile(t.getDbFilename(), {encoding: "utf-8"}, cb);
} else {
cb(null, null);
}
});
},
/**
* Parses the db.json into db
*
* @param data
* @param cb
*/
function parseDb(data, cb) {
if (data && data.trim().length) {
log.debug("Parsing database");
t.__db = jsonlint.parse(data);
} else {
log.debug("No database to parse");
t.__db = {};
}
cb(null, t.__db);
}
],
/**
* Done
* @param err
* @param result
*/
function(err, result) {
log.debug("loaded database: err=" + err);
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q59445
|
readDb
|
validation
|
function readDb(cb) {
fs.exists(t.getDbFilename(), function(exists) {
if (exists) {
fs.readFile(t.getDbFilename(), {encoding: "utf-8"}, cb);
} else {
cb(null, null);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q59446
|
parseDb
|
validation
|
function parseDb(data, cb) {
if (data && data.trim().length) {
log.debug("Parsing database");
t.__db = jsonlint.parse(data);
} else {
log.debug("No database to parse");
t.__db = {};
}
cb(null, t.__db);
}
|
javascript
|
{
"resource": ""
}
|
q59447
|
validation
|
function(className) {
let t = this;
// __classes will be null if analyseClasses has not formally been called; this would be if the
// analyser is only called externally for getClass()
if (!t.__classes) {
t.__classes = [];
}
// Add it
if (t.__classes.indexOf(className) == -1) {
t.__classes.push(className);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59448
|
validation
|
async function(locale) {
var t = this;
var cldr = this.__cldrs[locale];
if (cldr) {
return cldr;
}
return qx.tool.compiler.app.Cldr.loadCLDR(locale)
.then(cldr => t.__cldrs[locale] = cldr);
}
|
javascript
|
{
"resource": ""
}
|
|
q59449
|
validation
|
async function(library, locale) {
var t = this;
var id = locale + ":" + library.getNamespace();
var translation = t.__translations[id];
if (!translation) {
translation = t.__translations[id] = new qx.tool.compiler.app.Translation(library, locale);
await translation.checkRead();
}
return translation;
}
|
javascript
|
{
"resource": ""
}
|
|
q59450
|
validation
|
function(library, locales) {
const Promisify = qx.tool.compiler.utils.Promisify;
return Promise.all(locales.map(locale => {
var translation = new qx.tool.compiler.app.Translation(library, locale);
return translation.read()
.then(() => {
let unusedEntries = {};
for (let msgid in translation.getEntries())
unusedEntries[msgid] = true;
return Promise.all(this.__classes.map(async classname => {
if (!classname.startsWith(library.getNamespace())) {
return;
}
let dbClassInfo = await Promisify.call(cb => this.getClassInfo(classname, cb));
if (!dbClassInfo.translations)
return;
dbClassInfo.translations.forEach(function(src) {
var entry = translation.getOrCreateEntry(src.msgid);
delete unusedEntries[src.msgid];
if (src.msgid_plural) {
entry.msgid_plural = src.msgid_plural;
}
if (!entry.comments) {
entry.comments = {};
}
entry.comments.extracted = src.comment;
entry.comments.reference = {};
let ref = entry.comments.reference;
const fileName = classname.replace(/\./g, "/") + ".js";
const fnAddReference = lineNo => {
let arr = ref[fileName];
if (!arr)
arr = ref[fileName] = [];
if (!arr.includes(src.lineNo)) {
arr.push(lineNo);
}
};
if (qx.lang.Type.isArray(src.lineNo)) {
src.lineNo.forEach(fnAddReference);
} else {
fnAddReference(src.lineNo);
}
});
}))
.then(() => {
Object.keys(unusedEntries).forEach(msgid => {
var entry = translation.getEntry(msgid);
if (entry) {
if (!entry.comments) {
entry.comments = {};
}
entry.comments.extracted = "NO LONGER USED";
entry.comments.reference = {};
}
});
});
})
.then(() => translation.write());
}));
}
|
javascript
|
{
"resource": ""
}
|
|
q59451
|
validation
|
function(name) {
var t = this;
for (var j = 0; j < t.__libraries.length; j++) {
var library = t.__libraries[j];
var info = library.getSymbolType(name);
if (info) {
return info;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q59452
|
validation
|
function(className) {
var t = this;
var info = this.__classFiles[className];
if (info) {
return info.library;
}
for (var j = 0; j < t.__libraries.length; j++) {
var library = t.__libraries[j];
info = library.getSymbolType(className);
if (info && (info.symbolType == "class" || info.symbolType == "member")) {
return library;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q59453
|
validation
|
function(className) {
var library = this.getLibraryFromClassname(className);
if (!library) {
return null;
}
var path = library.getRootDir() + "/" + library.getSourcePath() + "/" + className.replace(/\./g, "/") + ".js";
return path;
}
|
javascript
|
{
"resource": ""
}
|
|
q59454
|
validation
|
function(key, value) {
if (typeof key == "object") {
var map = key;
for (key in map) {
this.__environmentChecks[key] = map[key];
}
} else if (value === undefined) {
delete this.__environmentChecks[key];
} else {
this.__environmentChecks[key] = value;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59455
|
validation
|
function() {
if (this.__qooxdooVersion) {
return this.__qooxdooVersion;
}
if (!this.__qooxdooVersion) {
let lib = this.findLibrary("qx");
if (lib) {
this.__qooxdooVersion = lib.getVersion();
}
}
return this.__qooxdooVersion;
}
|
javascript
|
{
"resource": ""
}
|
|
q59456
|
validation
|
function() {
var m = this.__dbFilename.match(/(^.*)\/([^/]+)$/);
var resDb;
if (m && m.length == 3) {
resDb = m[1] + "/resource-db.json";
} else {
resDb = "resource-db.json";
}
return resDb;
}
|
javascript
|
{
"resource": ""
}
|
|
q59457
|
validation
|
function(comment) {
var current = { name: "@description", body: "" };
var cmds = [ current ];
if (typeof comment == "string") {
comment = comment.split("\n");
}
comment.forEach(function(line) {
// Strip optional leading *
line = line.trim();
var m = line.match(/^\*\s?(.*)$/);
if (m) {
line = m[1];
}
line = line.trim();
// Look for command at the begining of the line
m = line.match(/^(\@[a-zA-Z0-9_]+)(.*)$/);
if (!m) {
if (current.body.length) {
current.body += "\n";
}
current.body += line;
return;
}
var name = m[1];
var body = m[2];
// Patch common command names
if (name == "@returns") {
name = "@return";
}
if (name == "@throw") {
name = "@throws";
}
// store it
current = { name: name, body: body };
cmds.push(current);
});
var result = {};
cmds.forEach(function(cmd) {
// If the body is surrounded by parameters, remove them
var m = cmd.body.match(/^\s*\(([\s\S]*)\)\s*$/);
if (m) {
cmd.body = m[1];
}
cmd.body = cmd.body.trim();
if (result[cmd.name]) {
result[cmd.name].push(cmd);
} else {
result[cmd.name] = [ cmd ];
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q59458
|
validation
|
function() {
return path.join(process.cwd(), qx.tool.cli.ConfigSchemas.lockfile.filename);
}
|
javascript
|
{
"resource": ""
}
|
|
q59459
|
validation
|
async function() {
let contrib_json_path = this.getContribFileName();
if (!await fs.existsAsync(contrib_json_path)) {
return {
version: qx.tool.cli.ConfigSchemas.lockfile.version,
libraries: []
};
}
return qx.tool.compiler.utils.Json.loadJsonAsync(contrib_json_path);
}
|
javascript
|
{
"resource": ""
}
|
|
q59460
|
validation
|
async function(repo_name, library_name) {
let library = (await this.getContribData()).libraries.find(lib => lib.repo_name === repo_name && lib.library_name === library_name);
return library ? library.repo_tag : false;
}
|
javascript
|
{
"resource": ""
}
|
|
q59461
|
validation
|
async function(library_name) {
return (await this.getContribData()).libraries.find(lib => lib.library_name === library_name);
}
|
javascript
|
{
"resource": ""
}
|
|
q59462
|
validation
|
function(readFromFile = false) {
if (!readFromFile && this.__cache && typeof this.__cache == "object") {
return this.__cache;
}
try {
this.__cache = jsonlint.parse(fs.readFileSync(this.getCachePath(), "UTF-8"));
} catch (e) {
this.__cache = {
repos : {
list : [],
data : {}
},
compat : {}
};
}
return this.__cache;
}
|
javascript
|
{
"resource": ""
}
|
|
q59463
|
validation
|
async function() {
await qx.tool.cli.Utils.makeParentDir(this.getCachePath());
await fs.writeFileAsync(this.getCachePath(), JSON.stringify(this.__cache, null, 2), "UTF-8");
}
|
javascript
|
{
"resource": ""
}
|
|
q59464
|
validation
|
async function(path) {
return fs.writeFileAsync(path, JSON.stringify(this.__cache, null, 2), "UTF-8")
.catch(e => console.error(`Error exporting cache to ${path}:` + e.message));
}
|
javascript
|
{
"resource": ""
}
|
|
q59465
|
expandMemberExpression
|
validation
|
function expandMemberExpression(str) {
var segs = str.split(".");
var expr = types.memberExpression(types.identifier(segs[0]), types.identifier(segs[1]));
for (var i = 2; i < segs.length; i++) {
expr = types.memberExpression(expr, types.identifier(segs[i]));
}
return expr;
}
|
javascript
|
{
"resource": ""
}
|
q59466
|
validation
|
function(callback) {
var t = this;
var className = this.__className;
t.__fatalCompileError = false;
t.__numClassesDefined = 0;
fs.readFile(this.getSourcePath(), {encoding: "utf-8"}, function(err, src) {
if (err) {
callback(err);
return;
}
try {
let options = t.__analyser.getBabelOptions() || {};
options.modules = false;
var config = {
babelrc: false,
sourceFileName : t.getSourcePath(),
filename: t.getSourcePath(),
sourceMaps: true,
"presets": [
[ require.resolve("@babel/preset-env"), options]
],
plugins: [
t._babelClassPlugin()
],
parserOpts: { sourceType: "script" },
passPerPreset: true
};
var result = babelCore.transform(src, config);
} catch (ex) {
if (ex._babel) {
console.log(ex);
}
t.addMarker("compiler.syntaxError", ex.loc, ex.message, ex.codeFrame);
t.__fatalCompileError = true;
t._compileDbClassInfo();
callback();
return;
}
if (!t.__numClassesDefined) {
t.addMarker("compiler.missingClassDef");
t.__fatalCompileError = true;
t._compileDbClassInfo();
callback();
return;
}
if (!t.__metaDefinitions[className]) {
t.addMarker("compiler.wrongClassName", null, className, Object.keys(t.__metaDefinitions).join(", "));
t._compileDbClassInfo();
}
var pos = className.lastIndexOf(".");
var name = pos > -1 ? className.substring(pos + 1) : className;
var outputPath = t.getOutputPath();
util.mkParentPath(outputPath, function(err) {
if (err) {
callback(err);
return;
}
fs.writeFile(outputPath, result.code + "\n\n//# sourceMappingURL=" + name + ".js.map?dt=" + (new Date().getTime()), {encoding: "utf-8"}, function(err) {
if (err) {
callback(err);
return;
}
fs.writeFile(outputPath + ".map", JSON.stringify(result.map, null, 2), {encoding: "utf-8"}, function(err) {
if (err) {
callback(err);
return;
}
t._waitForTaskQueueDrain(function() {
callback();
});
});
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q59467
|
validation
|
function(className) {
var pos = className.lastIndexOf(".");
var meta = {
className: className,
packageName: pos > -1 ? className.substring(0, pos) : null,
name: pos > -1 ? className.substring(pos + 1) : className,
superClass: null,
interfaces: [],
mixins: [],
functionName: null
};
this.__metaStack.push(meta);
this.__classMeta = meta;
this.__metaDefinitions[className] = meta;
this.__numClassesDefined++;
}
|
javascript
|
{
"resource": ""
}
|
|
q59468
|
validation
|
function(className) {
if (!this.__metaStack.length) {
throw new Error("No __metaStack entries to pop");
}
let meta = this.__metaStack[this.__metaStack.length - 1];
if (className && meta.className != className) {
throw new Error("Wrong __metaStack entries to pop, expected " + className + " found " + meta.className);
}
this.__metaStack.pop();
meta = this.__metaStack[this.__metaStack.length - 1] || null;
this.__classMeta = meta;
}
|
javascript
|
{
"resource": ""
}
|
|
q59469
|
validation
|
function(functionName, node, isClassMember) {
this.__scope = {
functionName: functionName,
parent: this.__scope,
vars: {},
unresolved: {},
isClassMember: !!isClassMember
};
}
|
javascript
|
{
"resource": ""
}
|
|
q59470
|
validation
|
function(node) {
var old = this.__scope;
var scope = this.__scope = this.__scope.parent;
var unresolved = scope.unresolved;
for (var name in old.unresolved) {
var entry = unresolved[name];
if (!entry) {
entry = unresolved[name] = {
name: name,
locations: []
};
}
entry.locations.push.apply(entry.locations, old.unresolved[name].locations);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59471
|
validation
|
function(name, valueName) {
if (this.__scope.vars[name] === undefined) {
this.__scope.vars[name] = valueName || true;
var unresolved = this.__scope.unresolved;
delete unresolved[name];
var re = new RegExp(name + "\\.");
for (var tmp in unresolved) {
if (re.test(tmp)) {
delete unresolved[tmp];
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59472
|
validation
|
function(name) {
var pos = name.indexOf(".");
if (pos > -1) {
name = name.substring(0, pos);
}
for (var tmp = this.__scope; tmp; tmp = tmp.parent) {
if (tmp.vars[name] !== undefined) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q59473
|
validation
|
function(name, loc) {
var str = "";
for (var i = 0; i < name.length; i++) {
if (i) {
str += ".";
}
str += name[i];
if (qx.tool.compiler.ClassFile.GLOBAL_SYMBOLS[str] || this.isIgnored(str)) {
return;
}
}
name = name.join(".");
if (name == this.__className || name.startsWith(this.__className + ".") || name.startsWith("(")) {
return;
}
if (name == "qx.ui.tooltip.ToolTip")
debugger;
var scope = this.__scope;
if (scope.vars[name] !== undefined) {
return;
}
if (!scope.unresolved[name]) {
scope.unresolved[name] = {
name: name,
locations: loc ? [loc] : [],
load: this.isLoadScope(),
defer: this.__inDefer
};
} else if (loc) {
scope.unresolved[name].locations.push(loc);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59474
|
validation
|
function(name) {
delete this.__scope.unresolved[name];
var stub = name + ".";
for (var id in this.__scope.unresolved) {
if (id.startsWith(stub)) {
delete this.__scope.unresolved[id];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59475
|
validation
|
function(name) {
var scope = this.__scope;
if (!scope.ignore) {
scope.ignore = {};
}
var segs = name.split(",");
segs.forEach(name => {
if (name.endsWith(".*")) {
scope.ignore[name] = name.substring(0, name.length - 2);
} else if (name.endsWith("*")) {
scope.ignore[name] = name.substring(0, name.length - 1);
} else {
scope.ignore[name] = true;
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q59476
|
validation
|
function(name) {
for (var tmp = this.__scope; tmp; tmp = tmp.parent) {
if (tmp.ignore) {
if (tmp.ignore[name]) {
return true;
}
for (var key in tmp.ignore) {
if (tmp.ignore[key] !== true) {
if (name.startsWith(tmp.ignore[key])) {
return true;
}
}
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q59477
|
validation
|
function(name, location) {
var t = this;
var requiredOpts = {
load: t.isLoadScope(),
defer: t.__inDefer,
construct: t.__classMeta && t.__classMeta.functionName == "$$constructor",
location: location
};
var dest = t.__environmentChecks.required[name];
if (!dest) {
dest = t.__environmentChecks.required[name] = {};
}
if (requiredOpts.load) {
dest.load = true;
}
if (requiredOpts.defer) {
dest.defer = true;
}
if (requiredOpts.construct) {
dest.construct = true;
}
t._requireClass("qx.core.Environment", { location: location });
if (qx.tool.compiler.ClassFile.ENVIRONMENT_CONSTANTS[name] === undefined) {
var entry = qx.tool.compiler.ClassFile.ENVIRONMENT_CHECKS[name];
if (entry && entry.className) {
t._requireClass(entry.className, { load: requiredOpts.load, location: location });
dest.className = entry.className;
} else if (!entry) {
t._requireClass(name, { load: requiredOpts.load, location: location });
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59478
|
validation
|
function(name, opts) {
if (qx.lang.Type.isArray(name)) {
name.forEach(name => this._requireClass(name));
return null;
}
let t = this;
if (name == this.__className) {
return null;
}
if (!name) {
throw new Error("No classname");
}
if (this.isIgnored(name)) {
return null;
}
let requireOpts = {
load: t.isLoadScope(),
defer: t.__inDefer,
construct: t.__classMeta && t.__classMeta.functionName == "$$constructor"
};
if (opts) {
for (let key in opts) {
requireOpts[key] = opts[key];
}
}
let info = t.__analyser.getSymbolType(name);
let symbolType = info ? info.symbolType : null;
let className = info ? info.className : null;
if (symbolType != "package" && className && className != t.__className) {
// Re-check the class name as ignored if this is a member
if (symbolType == "member" && t.isIgnored(className)) {
return null;
}
let data = t.__requiredClasses[className];
if (!data) {
data = t.__requiredClasses[className] = {};
}
if (requireOpts.where !== undefined) {
if (requireOpts.where == "ignore") {
data.ignore = true;
} else if (requireOpts.where == "require") {
data.require = true;
}
}
if (requireOpts.load) {
data.load = true;
if (requireOpts.usage === "dynamic") {
if (data.usage !== "static") {
data.usage = "dynamic";
}
data.load = true;
} else if (!data.load) {
data.load = true;
data.usage = "static";
}
}
if (requireOpts.defer) {
if (requireOpts.load) {
data.defer = "load";
} else if (data.defer !== "load") {
data.defer = "runtime";
}
if (!name.startsWith(t.__className)) {
if (!qx.tool.compiler.ClassFile.DEFER_SAFE_SYMBOLS.some(function(symbol) {
return name.startsWith(symbol);
})) {
// Temporarily disabled until Qooxdoo framework catches up
// t.addMarker("defer.unsafe", (opts && opts.location)||null, name);
}
}
}
if (requireOpts.construct) {
data.construct = true;
}
t.deleteReference(className);
}
return info;
}
|
javascript
|
{
"resource": ""
}
|
|
q59479
|
validation
|
function(path) {
if (path.indexOf("/") < 0 && path.indexOf(".") > -1) {
path = path.replace(/\./g, "/");
}
if (!qx.lang.Array.contains(this.__requiredAssets, path)) {
this.__requiredAssets.push(path);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59480
|
validation
|
function(library, className) {
return pathModule.join(library.getRootDir(), library.getSourcePath(), className.replace(/\./g, pathModule.sep) + ".js");
}
|
javascript
|
{
"resource": ""
}
|
|
q59481
|
validation
|
function(analyser, className) {
var filename = pathModule.join(analyser.getOutputDir(), "transpiled", className.replace(/\./g, pathModule.sep) + ".js");
return filename;
}
|
javascript
|
{
"resource": ""
}
|
|
q59482
|
validation
|
function(array, searchElement) {
var minIndex = 0;
var maxIndex = array.length - 1;
var currentIndex;
var currentElement;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = array[currentIndex];
if (currentElement < searchElement) {
minIndex = currentIndex + 1;
} else if (currentElement > searchElement) {
maxIndex = currentIndex - 1;
} else {
return currentIndex;
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
|
q59483
|
validation
|
async function() {
let compile = await this.parseCompileConfig();
for (let target of compile.targets) {
await this.__removePath(path.join(process.cwd(), target.outputPath));
}
await this.__removePath(path.join(process.cwd(), "contrib"));
}
|
javascript
|
{
"resource": ""
}
|
|
q59484
|
getPages
|
validation
|
function getPages(files, metalsmith, done) {
var metadata = metalsmith.metadata();
var pages = [];
var order = {};
if (metadata.site.pages)
metadata.site.pages.forEach((url, index) => typeof url == "string" ? order[url] = index : null);
var unorderedPages = [];
function addPage(url, title) {
var page = {
url: url,
title: title
};
var index = order[url];
if (index !== undefined)
pages[index] = page;
else
unorderedPages.push(page);
}
for (var filename in files) {
var file = files[filename];
if (filename == "index.html")
addPage("/", file.title||"Home Page");
else if (file.permalink || file.navigation)
addPage(file.permalink||filename, file.title||"Home Page");
}
unorderedPages.forEach(page => pages.push(page));
metadata.site.pages = pages;
done();
}
|
javascript
|
{
"resource": ""
}
|
q59485
|
loadPartials
|
validation
|
function loadPartials(files, metalsmith, done) {
var metadata = metalsmith.metadata();
fs.readdirAsync("./partials", "utf8")
.then(files => {
var promises = files.map(filename => {
var m = filename.match(/^(.+)\.([^.]+)$/);
if (!m)
return;
var name = m[1];
var ext = m[2];
return fs.readFileAsync("partials/" + filename, "utf8")
.then(data => {
var fn;
try {
fn = dot.template(data);
}catch(err) {
console.log("Failed to load partial " + filename + ": " + err);
return;
}
fn.name = filename;
metadata.partials[filename] = fn;
if (ext == "html")
metadata.partials[name] = fn;
});
});
return Promise.all(promises);
})
.then(() => done())
.catch(err => done(err));
}
|
javascript
|
{
"resource": ""
}
|
q59486
|
generateSite
|
validation
|
function generateSite() {
return new Promise((resolve, reject) => {
Metalsmith(__dirname)
.metadata({
site: {
title: "Qooxdoo Application Server",
description: "Mini website used by \"qx serve\"",
email: "info@qooxdoo.org",
twitter_username: "qooxdoo",
github_username: "qooxdoo",
pages: [ "/", "/about/" ]
},
baseurl: "",
url: "",
lang: "en",
partials: {}
})
.source('./src')
.destination('./build')
.clean(true)
.use(loadPartials)
.use(markdown())
.use(getPages)
.use(layouts({
engine: 'dot'
}))
.build(function(err) {
if (err)
reject(err);
else
resolve();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q59487
|
compileScss
|
validation
|
function compileScss() {
return new Promise((resolve, reject) => {
sass.render({
file: "sass/qooxdoo.scss",
outFile: "build/qooxdoo.css"
}, function(err, result) {
if (err)
reject(err);
else
resolve(result);
});
})
.then(result => fs.writeFileAsync("build/qooxdoo.css", result.css, "utf8"));
}
|
javascript
|
{
"resource": ""
}
|
q59488
|
validation
|
function() {
return {
command: "list [repository]",
describe:
"if no repository name is given, lists all available contribs that are compatible with the project's qooxdoo version (\"--all\" lists incompatible ones as well). Otherwise, list all compatible contrib libraries.",
builder: {
all: {
alias: "a",
describe: "Show all versions, including incompatible ones"
},
verbose: {
alias: "v",
describe: "Verbose logging"
},
quiet: {
alias: "q",
describe: "No output"
},
json: {
alias: "j",
describe: "Output list as JSON literal"
},
installed: {
alias: "i",
describe: "Show only installed libraries"
},
namespace: {
alias: "n",
describe: "Display library namespace"
},
match: {
alias: "m",
describe: "Filter by regular expression (case-insensitive)"
},
"libraries": {
alias: "l",
describe: "List libraries only (no repositories)"
},
"short": {
alias: "s",
describe: "Omit title and description to make list more compact"
},
"noheaders": {
alias: "H",
describe: "Omit header and footer"
}
},
handler: function(argv) {
return new qx.tool.cli.commands.contrib.List(argv)
.process()
.catch(e => {
console.error(e.stack || e.message);
process.exit(1);
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q59489
|
validation
|
async function() {
if (!this.__mtime) {
return this.read();
}
var poFile = this.getPoFilename();
let stat = await qx.tool.compiler.files.Utils.safeStat(poFile);
if (stat && this.__mtime == stat.mtime) {
return undefined;
}
return this.read();
}
|
javascript
|
{
"resource": ""
}
|
|
q59490
|
validation
|
function(filename, cb) {
var t = this;
var lines = [];
function write(key, value) {
if (value === undefined || value === null) {
return;
}
value = value.replace(/\t/g, "\\t").replace(/\r/g, "\\r")
.replace(/\n/g, "\\n")
.replace(/"/g, "\\\"");
lines.push(key + " \"" + value + "\"");
}
for (var msgid in t.__translations) {
var entry = t.__translations[msgid];
if (entry.comments) {
if (entry.comments.translator) {
lines.push("# " + entry.comments.translator);
}
if (entry.comments.extracted) {
lines.push("#. " + entry.comments.extracted);
}
if (entry.comments.reference) {
let refStr = "#:";
const ref = entry.comments.reference;
for (let classname in ref) {
if (ref[classname]) {
for (let lineNo of ref[classname]) {
const addStr = " " + classname + ":" + lineNo;
if (refStr.length + addStr.length > 78) { // 78 is default length in python po library
// line break
lines.push(refStr);
refStr = "#:" + addStr;
} else {
refStr += addStr;
}
}
}
}
if (refStr.length > 3) { // write remaining refStr
lines.push(refStr);
}
}
if (entry.comments.flags) {
lines.push("#, " + entry.comments.flags.join(","));
}
} else {
lines.push("#");
}
if (entry.msgctxt) {
lines.push("msgctxt \"" + entry.msgctxt + "\"");
}
write("msgid", entry.msgid);
write("msgid_plural", entry.msgid_plural);
if (qx.lang.Type.isArray(entry.msgstr)) {
entry.msgstr.forEach(function(value, index) {
write("msgstr[" + index + "]", value);
});
} else if (entry.msgid_plural) {
write("msgstr[0]", "");
write("msgstr[1]", "");
} else {
write("msgstr", entry.msgstr || "");
}
lines.push("");
}
var data = lines.join("\n");
return qx.tool.compiler.utils.Promisify.fs.writeFileAsync(filename, data, { encoding: "utf8" });
}
|
javascript
|
{
"resource": ""
}
|
|
q59491
|
validation
|
function(id) {
var t = this;
var entry = t.__translations[id];
if (!entry) {
entry = t.__translations[id] = {
msgid: id
};
}
return entry;
}
|
javascript
|
{
"resource": ""
}
|
|
q59492
|
validation
|
async function() {
let {libraries} = await this.getProjectData();
if (libraries instanceof Array && libraries.length) {
return path.resolve(process.cwd(), libraries[0].path);
}
throw new qx.tool.cli.Utils.UserError("Cannot find library path - are you in the right directory?");
}
|
javascript
|
{
"resource": ""
}
|
|
q59493
|
validation
|
async function() {
let {applications} = await this.getProjectData();
if (applications instanceof Array && applications.length) {
return path.resolve(process.cwd(), applications[0].path);
}
throw new qx.tool.cli.Utils.UserError("Cannot find application path - are you in the right directory?");
}
|
javascript
|
{
"resource": ""
}
|
|
q59494
|
validation
|
async function(filePath) {
var data = await fs.readFileAsync(filePath, "utf8");
try {
let compileAst = JsonToAst.parseToAst(data, {verbose: true});
let compileJson = JsonToAst.astToObject(compileAst);
return compileJson;
} catch (e) {
throw new qx.tool.cli.Utils.UserError(`Cannot parse ${filePath}:` + e.message);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59495
|
validation
|
async function() {
let compileJsonPath = null;
try {
path.join(await this.getApplicationPath(), "compile.json");
} catch (ex) {
// Nothing - cannot find compile.json
}
if (compileJsonPath && await fs.existsAsync(compileJsonPath)) {
let compileConfig = await this.parseCompileConfig();
let qxpath = false;
let appPath = await this.getApplicationPath();
if (compileConfig.libraries) {
for (let somepath of compileConfig.libraries) {
let manifestPath = somepath;
if (!path.isAbsolute(somepath)) {
manifestPath = path.join(appPath, manifestPath);
}
manifestPath = path.join(manifestPath, "Manifest.json");
let manifest = await this.parseJsonFile(manifestPath);
try {
if (manifest.provides.namespace === "qx") {
qxpath = path.dirname(manifestPath);
return qxpath;
}
} catch (e) {
console.warn(`Invalid manifest file ${manifestPath}.`);
}
}
}
}
return this.getGlobalQxPath();
}
|
javascript
|
{
"resource": ""
}
|
|
q59496
|
validation
|
async function() {
let qxpath = await this.getAppQxPath();
return path.isAbsolute(qxpath) ? qxpath : path.resolve(qxpath);
}
|
javascript
|
{
"resource": ""
}
|
|
q59497
|
validation
|
async function(libPath) {
let manifestPath = path.join(libPath, "Manifest.json");
let manifest = await this.parseJsonFile(manifestPath);
let version;
try {
version = manifest.info.version;
} catch (e) {
throw new qx.tool.cli.Utils.UserError(`No valid version data in manifest.`);
}
if (!semver.valid(version)) {
throw new qx.tool.cli.Utils.UserError(`Manifest at ${manifestPath} contains invalid version number "${version}". Please use a semver compatible version.`);
}
return version;
}
|
javascript
|
{
"resource": ""
}
|
|
q59498
|
validation
|
function(cmd, args) {
let opts = {env: process.env};
return new Promise((resolve, reject) => {
let exe = child_process.spawn(cmd, args, opts);
// suppress all output unless in verbose mode
exe.stdout.on("data", data => {
if (this.argv.verbose) {
console.log(data.toString());
}
});
exe.stderr.on("data", data => {
if (this.argv.verbose) {
console.error(data.toString());
}
});
exe.on("close", code => {
if (code !== 0) {
let message = `Error executing ${cmd.join(" ")}. Use --verbose to see what went wrong.`;
throw new qx.tool.cli.Utils.UserError(message);
} else {
resolve(0);
}
});
exe.on("error", reject);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q59499
|
validation
|
function(cmd) {
return new Promise((resolve, reject) => {
child_process.exec(cmd, (err, stdout, stderr) => {
if (err) {
reject(err);
}
if (stderr) {
reject(new Error(stderr));
}
resolve(stdout);
});
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.