code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
}
actionItems() {
let composing = new PrivateComposing(this.user);
const items = new ItemList();
if (app.session.user && app.forum.attribute('canStartPrivateDiscussion')) {
items.add('start_private', composing.component());
}
| Class | 2 |
PageantSock.prototype.connect = function() {
this.emit('connect');
}; | Base | 1 |
const addReplyToEvent = (event: any) => {
event.reply = (...args: any[]) => {
event.sender.sendToFrame(event.frameId, ...args);
};
}; | Class | 2 |
): void => {
const name = createElement('h2', CLASS_CATEGORY_NAME);
name.innerHTML =
this.i18n.categories[category] || defaultI18n.categories[category];
this.emojis.appendChild(name);
this.headers.push(name);
this.emojis.appendChild(
new EmojiContainer(
emojis,
true,
this.events,
this.options,
category !== 'recents'
).render()
);
}; | Base | 1 |
constructor({ log, port }: { log: LogEntry; port?: number }) {
this.log = log
this.debugLog = this.log.placeholder({ level: LogLevel.debug, childEntriesInheritLevel: true })
this.garden = undefined
this.port = port
this.authKey = randomString(64)
this.incomingEvents = new EventBus()
this.activePersistentRequests = {}
this.serversUpdatedListener = ({ servers }) => {
// Update status log line with new `garden dashboard` server, if any
for (const { host, command } of servers) {
if (command === "dashboard") {
this.showUrl(host)
return
}
}
// No active explicit dashboard processes, show own URL instead
this.showUrl(this.getUrl())
}
} | Base | 1 |
function generate(target, hierarchies, forceOverride) {
let current = target;
hierarchies.forEach(info => {
const descriptor = normalizeDescriptor(info);
const { value, type, create, override, created, skipped, got } = descriptor;
const name = getNonEmptyPropName(current, descriptor);
if (forceOverride || override || !current[name] || typeof current[name] !== 'object') {
const obj = value ? value :
type ? new type() :
create ? create.call(current, current, name) :
{};
current[name] = obj;
if (created) {
created.call(current, current, name, obj);
}
}
else {
if (skipped) {
skipped.call(current, current, name, current[name]);
}
}
const parent = current;
current = current[name];
if (got) {
got.call(parent, parent, name, current);
}
});
return current;
} | Variant | 0 |
constructor({asset, message, onClick}: Params, element: HTMLElement) {
super(message);
this.asset = asset;
this.message = message;
this.isVisible = ko.observable(false);
this.onClick = (_data, event) => onClick(message, event);
this.dummyImageUrl = `data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 1 1' width='${asset.width}' height='${asset.height}'></svg>`;
this.imageUrl = ko.observable();
this.isIdle = () => this.uploadProgress() === -1 && !this.asset.resource() && !this.message.isObfuscated();
ko.computed(
() => {
if (this.isVisible() && asset.resource()) {
this.assetRepository
.load(asset.resource())
.then(blob => {
this.imageUrl(window.URL.createObjectURL(blob));
})
.catch(error => console.error(error));
}
},
{disposeWhenNodeIsRemoved: element},
);
this.container = element;
viewportObserver.onElementInViewport(this.container, () => this.isVisible(true));
} | Base | 1 |
setEntries(entries) {
if (entries.length === 0) {
this.emptyList();
return;
}
let htmlToInsert = '';
for (let timesheet of entries) {
let label = this.attributes['template']
.replace('%customer%', timesheet.project.customer.name)
.replace('%project%', timesheet.project.name)
.replace('%activity%', timesheet.activity.name);
htmlToInsert +=
`<li>` +
`<a href="${ this.attributes['href'].replace('000', timesheet.id) }" data-event="kimai.timesheetStart kimai.timesheetUpdate" class="api-link" data-method="PATCH" data-msg-error="timesheet.start.error" data-msg-success="timesheet.start.success">` +
`<i class="${ this.attributes['icon'] }"></i> ${ label }` +
`</a>` +
`</li>`;
}
this.itemList.innerHTML = htmlToInsert;
} | Base | 1 |
export function loadEmailAddressesAndLoginMethods(userId: UserId, success: UserAcctRespHandler) {
get(`/-/load-email-addrs-login-methods?userId=${userId}`, response => {
success(response);
});
} | Base | 1 |
const assigner = ( ...args: any[] ) => {
console.log( { args } )
return args.reduce( ( a, b ) => {
if ( untracker.includes( a ) ) throw new TypeError( `can't convert ${a} to object` )
if ( useuntrack && untracker.includes( b ) ) return a
Object.keys( b ).forEach( key => {
if ( untracker.includes( a[key] ) ) a[key] = b[key]
else a[key] = delegate.call( this, a[key], b[key] )
} )
return a
} )
}
return assigner
}
Assigner.count = ( qty: number, delegate: ( arg: any, ...args: any[] ) => any ) => {
const assigner = ( ...receives: any[] ) => {
let group = receives.shift()
if ( untracker.includes( group ) ) throw new TypeError( `can't convert ${group} to object` )
let args = receives.splice( 0, qty - 1 )
while ( args.length ) {
const keys = []
for ( const arg of args )
for ( const key of Object.keys( arg ) )
if ( !keys.includes( key ) ) keys.push( key )
for ( const key of keys )
group[key] = delegate.call( this, group[key], ...args.map( arg => arg[key] ) )
args = receives.splice( 0, qty - 1 )
}
return group
}
return assigner
}
declare namespace Assigner {
export type BasicTypes = string | number | symbol | bigint | object | boolean | Function
export type Types = BasicTypes | Types[]
export type TypesWithExclude = BasicTypes | undefined | null | TypesWithExclude[]
}
export { Assigner } | Base | 1 |
function g_sendError(channel: ServerSecureChannelLayer, message: Message, ResponseClass: any, statusCode: StatusCode): void {
const response = new ResponseClass({
responseHeader: { serviceResult: statusCode }
});
return channel.send_response("MSG", response, message);
} | Class | 2 |
function checkCredentials(req, res, next) {
if (!sqlInit.isDbInitialized()) {
res.status(400).send('Database is not initialized yet.');
return;
}
if (!passwordService.isPasswordSet()) {
res.status(400).send('Password has not been set yet. Please set a password and repeat the action');
return;
}
const header = req.headers['trilium-cred'] || '';
const auth = new Buffer.from(header, 'base64').toString();
const [username, password] = auth.split(/:/);
// username is ignored
if (!passwordEncryptionService.verifyPassword(password)) {
res.status(401).send('Incorrect password');
}
else {
next();
}
} | Base | 1 |
function simulateTransation(request: FindServersRequest, response: FindServersResponse, callback: SimpleCallback) {
serverSChannel.once("message", (message: Message) => {
doDebug && console.log("server receiving message =", response.responseHeader.requestHandle);
response.responseHeader.requestHandle = message.request.requestHeader.requestHandle;
serverSChannel.send_response("MSG", response, message, () => {
/** */
doDebug && console.log("server message sent ", response.responseHeader.requestHandle);
});
});
doDebug && console.log(" now sending a request " + request.constructor.name);
clientChannel.performMessageTransaction(request, (err, response) => {
doDebug && console.log("client received a response ", response?.constructor.name);
doDebug && console.log(response?.toString());
callback(err || undefined);
});
} | Class | 2 |
async function installMonitoredItem(subscription, nodeId) {
debugLog("installMonitoredItem", nodeId.toString());
const monitoredItem = await subscription.monitor(
{ nodeId, attributeId: AttributeIds.Value },
{
samplingInterval: 0, // reports immediately
discardOldest: true,
queueSize: 10
},
TimestampsToReturn.Both,
MonitoringMode.Reporting
);
const recordedValue = [];
monitoredItem.on("changed", function (dataValue) {
recordedValue.push(dataValue.value.value);
debugLog("change =", recordedValue);
});
return await new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error("Never received changedx for id" + nodeId.toString()));
}, 5000);
monitoredItem.once("changed", function (dataValue) {
clearTimeout(timer);
resolve([recordedValue, monitoredItem]);
});
});
} | Class | 2 |
schemaTypeOptions = {...schemaTypeOptions, type: getSchema(propertyMetadata.type)};
}
schemaTypeOptions = cleanProps({...schemaTypeOptions, ...rawMongooseSchema});
if (propertyMetadata.isCollection) {
if (propertyMetadata.isArray) {
schemaTypeOptions = [schemaTypeOptions];
} else {
// Can be a Map or a Set;
// Mongoose implements only Map;
if (propertyMetadata.collectionType !== Map) {
throw new Error(`Invalid collection type. ${propertyMetadata.collectionName} is not supported.`);
}
schemaTypeOptions = {type: Map, of: schemaTypeOptions};
}
}
return schemaTypeOptions;
} | Base | 1 |
__(key) {
self.apos.util.warnDevOnce('old-i18n-req-helper', stripIndent`
The req.__() and res.__() functions are deprecated and do not localize in A3.
Use req.t instead.
`);
return key;
} | Base | 1 |
provisionCallback: (user, renew, cb) => {
cb(null, 'zzz');
}
});
xoauth2.getToken(false, function(err, accessToken) {
expect(err).to.not.exist;
expect(accessToken).to.equal('zzz');
done();
});
}); | Base | 1 |
private _on_receive_message_chunk(messageChunk: Buffer) {
/* istanbul ignore next */
if (doDebug1) {
const _stream = new BinaryStream(messageChunk);
const messageHeader = readMessageHeader(_stream);
debugLog("CLIENT RECEIVED " + chalk.yellow(JSON.stringify(messageHeader) + ""));
debugLog("\n" + hexDump(messageChunk));
debugLog(messageHeaderToString(messageChunk));
}
this.messageBuilder.feed(messageChunk);
}
| Class | 2 |
const {type, store = JsonEntityStore.from(type), ...next} = options;
const propertiesMap = getPropertiesStores(store);
let keys = Object.keys(src);
const additionalProperties = propertiesMap.size ? !!store.schema.get("additionalProperties") || options.additionalProperties : true;
const out: any = new type(src);
propertiesMap.forEach((propStore) => {
const key = propStore.parent.schema.getAliasOf(propStore.propertyName) || propStore.propertyName;
keys = keys.filter((k) => k !== key);
let value = alterValue(propStore.schema, src[key], {...options, self: src});
next.type = propStore.computedType;
if (propStore.schema.hasGenerics) {
next.nestedGenerics = propStore.schema.nestedGenerics;
} else if (propStore.schema.isGeneric && options.nestedGenerics) {
const [genericTypes = [], ...nestedGenerics] = options.nestedGenerics;
const genericLabels = propStore.parent.schema.genericLabels || [];
next.type = genericTypes[genericLabels.indexOf(propStore.schema.genericType)] || Object;
next.nestedGenerics = nestedGenerics;
}
value = deserialize(value, {
...next,
collectionType: propStore.collectionType
});
if (value !== undefined) {
out[propStore.propertyName] = value;
}
});
if (additionalProperties) {
keys.forEach((key) => {
out[key] = src[key];
});
}
return out;
} | Base | 1 |
function onconnect() {
var buf;
if (isSigning) {
/*
byte SSH2_AGENTC_SIGN_REQUEST
string key_blob
string data
uint32 flags
*/
var p = 9;
buf = Buffer.allocUnsafe(4 + 1 + 4 + keylen + 4 + datalen + 4);
writeUInt32BE(buf, buf.length - 4, 0);
buf[4] = SIGN_REQUEST;
writeUInt32BE(buf, keylen, 5);
key.copy(buf, p);
writeUInt32BE(buf, datalen, p += keylen);
data.copy(buf, p += 4);
writeUInt32BE(buf, 0, p += datalen);
sock.write(buf);
} else {
/*
byte SSH2_AGENTC_REQUEST_IDENTITIES
*/
sock.write(Buffer.from([0, 0, 0, 1, REQUEST_IDENTITIES]));
}
} | Base | 1 |
static parseChunkToInt(intBytes: Buffer, minByteLen: number, maxByteLen: number, raise_on_Null = false) {
// # Parse data as unsigned-big-endian encoded integer.
// # For empty data different possibilities may occur:
// # minByteLen <= 0 : return 0
// # raise_on_Null == False and minByteLen > 0: return None
// # raise_on_Null == True and minByteLen > 0: raise SlpInvalidOutputMessage
if(intBytes.length >= minByteLen && intBytes.length <= maxByteLen)
return intBytes.readUIntBE(0, intBytes.length)
if(intBytes.length === 0 && !raise_on_Null)
return null;
throw Error('Field has wrong length');
} | Class | 2 |
get lokadIdHex() { return "534c5000" } | Class | 2 |
function exportBranch(req, res) {
const {branchId, type, format, version, taskId} = req.params;
const branch = becca.getBranch(branchId);
if (!branch) {
const message = `Cannot export branch ${branchId} since it does not exist.`;
log.error(message);
res.status(500).send(message);
return;
}
const taskContext = new TaskContext(taskId, 'export');
try {
if (type === 'subtree' && (format === 'html' || format === 'markdown')) {
zipExportService.exportToZip(taskContext, branch, format, res);
}
else if (type === 'single') {
singleExportService.exportSingleNote(taskContext, branch, format, res);
}
else if (format === 'opml') {
opmlExportService.exportToOpml(taskContext, branch, version, res);
}
else {
return [404, "Unrecognized export format " + format];
}
}
catch (e) {
const message = "Export failed with following error: '" + e.message + "'. More details might be in the logs.";
taskContext.reportError(message);
log.error(message + e.stack);
res.status(500).send(message);
}
} | Base | 1 |
module.exports = function(key) {
key = normalizeKey(key.split('@').pop());
return normalized[key] || false;
}; | Base | 1 |
function _ondata(data) {
bc += data.length;
if (state === 'secret') {
// the secret we sent is echoed back to us by cygwin, not sure of
// the reason for that, but we ignore it nonetheless ...
if (bc === 16) {
bc = 0;
state = 'creds';
sock.write(credsbuf);
}
} else if (state === 'creds') {
// if this is the first attempt, make sure to gather the valid
// uid and gid for our next attempt
if (!isRetrying)
inbuf.push(data);
if (bc === 12) {
sock.removeListener('connect', _onconnect);
sock.removeListener('data', _ondata);
sock.removeListener('close', _onclose);
if (isRetrying) {
addSockListeners();
sock.emit('connect');
} else {
isRetrying = true;
credsbuf = Buffer.concat(inbuf);
writeUInt32LE(credsbuf, process.pid, 0);
sock.destroy();
tryConnect();
}
}
}
} | Base | 1 |
triggerMassAction: function (massActionUrl, type) {
const self = this.relatedListInstance;
let validationResult = self.checkListRecordSelected();
if (validationResult != true) {
let progressIndicatorElement = $.progressIndicator(),
selectedIds = self.readSelectedIds(true),
excludedIds = self.readExcludedIds(true),
cvId = self.getCurrentCvId(),
postData = self.getCompleteParams();
delete postData.mode;
delete postData.view;
postData.viewname = cvId;
postData.selected_ids = selectedIds;
postData.excluded_ids = excludedIds;
let actionParams = {
type: 'POST',
url: massActionUrl,
data: postData
};
if (type === 'sendByForm') {
app.openUrlMethodPost(massActionUrl, postData);
progressIndicatorElement.progressIndicator({ mode: 'hide' });
} else {
AppConnector.request(actionParams)
.done(function (responseData) {
progressIndicatorElement.progressIndicator({ mode: 'hide' });
if (responseData && responseData.result !== null) {
if (responseData.result.notify) {
Vtiger_Helper_Js.showMessage(responseData.result.notify);
}
if (responseData.result.reloadList) {
Vtiger_Detail_Js.reloadRelatedList();
}
if (responseData.result.processStop) {
progressIndicatorElement.progressIndicator({ mode: 'hide' });
return false;
}
}
})
.fail(function (error, err) {
progressIndicatorElement.progressIndicator({ mode: 'hide' });
});
}
} else {
self.noRecordSelectedAlert();
}
}, | Compound | 4 |
updateOidcSettings(configuration) {
checkAdminAuthentication(this)
ServiceConfiguration.configurations.remove({
service: 'oidc',
})
ServiceConfiguration.configurations.insert(configuration)
} | Class | 2 |
export declare function applyCommandArgs(configuration: any, argv: string[]): void;
export declare function setDeepProperty(obj: any, propertyPath: string, value: any): void; | Base | 1 |
error: err => {
reject(err)
this.fetching = this.fetching.remove(this.hash(session))
}, | Base | 1 |
function userBroadcast(msg, source) {
var sourceMsg = '> ' + msg;
var name = '{cyan-fg}{bold}' + source.name + '{/}';
msg = ': ' + msg;
for (var i = 0; i < users.length; ++i) {
var user = users[i];
var output = user.output;
if (source === user)
output.add(sourceMsg);
else
output.add(formatMessage(name, output) + msg);
}
} | Base | 1 |
getScriptOperations(script: Buffer) {
let ops: PushDataOperation[] = [];
try {
let n = 0;
let dlen: number;
while (n < script.length) {
let op: PushDataOperation = { opcode: script[n], data: null }
n += 1;
if(op.opcode <= this.BITBOX.Script.opcodes.OP_PUSHDATA4) {
if(op.opcode < this.BITBOX.Script.opcodes.OP_PUSHDATA1)
dlen = op.opcode;
else if(op.opcode === this.BITBOX.Script.opcodes.OP_PUSHDATA1) {
dlen = script[n];
n += 1;
}
else if(op.opcode === this.BITBOX.Script.opcodes.OP_PUSHDATA2) {
dlen = script.slice(n, n + 2).readUIntLE(0,2);
n += 2;
}
else {
dlen = script.slice(n, n + 4).readUIntLE(0,4);
n += 4;
}
if((n + dlen) > script.length) {
throw Error('IndexError');
}
if(dlen > 0)
op.data = script.slice(n, n + dlen);
n += dlen
}
ops.push(op);
}
} catch(e) {
//console.log(e);
throw Error('truncated script')
}
return ops;
} | Class | 2 |
response.responseHeader.serviceResult.should.eql(StatusCodes.BadDiscoveryUrlMissing);
}
await send_registered_server_request(discoveryServerEndpointUrl, request, check_response);
}); | Class | 2 |
export function setupCleanupOnExit(cssPath: string) {
if (!hasSetupCleanupOnExit){
process.on('SIGINT', () => {
console.log('Exiting, running CSS cleanup');
exec(`rm -r ${cssPath}`, function(error) {
if (error) {
console.error(error);
process.exit(1);
}
console.log('Deleted CSS files');
});
});
hasSetupCleanupOnExit = true;
}
} | Base | 1 |
function simulateOpenSecureChannel(callback: SimpleCallback) {
clientChannel.create("fake://foobar:123", (err?: Error) => {
if (param.shouldFailAtClientConnection) {
if (!err) {
return callback(new Error(" Should have failed here !"));
}
callback();
} else {
if (err) {
return callback(err);
}
setImmediate(() => callback());
}
});
} | Class | 2 |
function applyCommandArgs(configuration, argv) {
if (!argv || !argv.length) {
return;
}
argv = argv.slice(2);
const parsedArgv = yargs(argv);
const argvKeys = Object.keys(parsedArgv);
if (!argvKeys.length) {
return;
}
debug("Appling command arguments:", parsedArgv);
if (parsedArgv.config) {
const configFile = path.resolve(process.cwd(), parsedArgv.config);
applyConfigFile(configuration, configFile);
}
for (const key in parsedArgv) {
if (!parsedArgv.hasOwnProperty(key)) {
continue;
}
const configKey = key
.replace(/_/g, ".");
debug(`Found config value from cmd args '${key}' to '${configKey}'`);
setDeepProperty(configuration, configKey, parsedArgv[key]);
}
} | Base | 1 |
WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
if (typeof channel !== 'string') {
throw new Error('Missing required channel argument');
} else if (typeof frameId !== 'number') {
throw new Error('Missing required frameId argument');
}
return this._sendToFrame(false /* internal */, frameId, channel, args);
}; | Class | 2 |
export function verify_multi_chunk_message(packets: any[]) {
const messageBuilder = new MessageBuilder({});
messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None);
messageBuilder.on("full_message_body", (fullMessageBody: Buffer) => {
console.log("full_message_body received:");
analyseExtensionObject(fullMessageBody, 0, 0);
});
messageBuilder.on("start_chunk", (info) => {
console.log(" starting new chunk ", info.messageHeader);
});
messageBuilder.on("chunk", (messageChunk) => {
console.log(messageHeaderToString(messageChunk));
});
let totalLength = 0;
packets.forEach((packet) => {
if (packet instanceof Array) {
packet = Buffer.from(packet);
}
totalLength += packet.length;
// console.log(sprintf(" adding packet size : %5d l=%d", packet.length, totalLength));
messageBuilder.feed(packet);
});
} | Class | 2 |
function text({ url, host }: Record<"url" | "host", string>) {
return `Sign in to ${host}\n${url}\n\n`
} | Base | 1 |
await manager.update(User, organizationUser.userId, { invitationToken: uuid.v4(), password: uuid.v4() });
}); | Class | 2 |
constructor(options?: { signatureLength?: number }) {
super();
this.id = "";
this._tick0 = 0;
this._tick1 = 0;
this._hasReceivedError = false;
this.blocks = [];
this.messageChunks = [];
this._expectedChannelId = 0;
options = options || {};
this.signatureLength = options.signatureLength || 0;
this.options = options;
this._packetAssembler = new PacketAssembler({
minimumSizeInBytes: 0,
readMessageFunc: readRawMessageHeader
});
this._packetAssembler.on("message", (messageChunk) => this._feed_messageChunk(messageChunk));
this._packetAssembler.on("newMessage", (info, data) => {
if (doPerfMonitoring) {
// record tick 0: when the first data is received
this._tick0 = get_clock_tick();
}
/**
*
* notify the observers that a new message is being built
* @event start_chunk
* @param info
* @param data
*/
this.emit("start_chunk", info, data);
});
this._securityDefeated = false;
this.totalBodySize = 0;
this.totalMessageSize = 0;
this.channelId = 0;
this.offsetBodyStart = 0;
this.sequenceHeader = null;
this._init_new();
} | Class | 2 |
async signup(params: any) {
// Check if the installation allows user signups
if (process.env.DISABLE_SIGNUPS === 'true') {
return {};
}
const { email } = params;
const existingUser = await this.usersService.findByEmail(email);
if (existingUser) {
throw new NotAcceptableException('Email already exists');
}
const organization = await this.organizationsService.create('Untitled organization');
const user = await this.usersService.create({ email }, organization, ['all_users', 'admin']);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const organizationUser = await this.organizationUsersService.create(user, organization);
await this.emailService.sendWelcomeEmail(user.email, user.firstName, user.invitationToken);
return {};
} | Class | 2 |
function escapeShellArg(arg) {
return arg.replace(/'/g, `'\\''`);
} | Base | 1 |
putComment(comment, isMarkdown, commentId, author) {
const { pageId, revisionId } = this.getPageContainer().state;
return this.appContainer.apiPost('/comments.update', {
commentForm: {
comment,
page_id: pageId,
revision_id: revisionId,
is_markdown: isMarkdown,
comment_id: commentId,
author,
},
})
.then((res) => {
if (res.ok) {
return this.retrieveComments();
}
});
} | Base | 1 |
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, | Base | 1 |
onBannerChange (input: HTMLInputElement) {
this.bannerfileInput = new ElementRef(input)
const bannerfile = this.bannerfileInput.nativeElement.files[0]
if (bannerfile.size > this.maxBannerSize) {
this.notifier.error('Error', $localize`This image is too large.`)
return
}
const formData = new FormData()
formData.append('bannerfile', bannerfile)
this.bannerPopover?.close()
this.bannerChange.emit(formData)
if (this.previewImage) {
this.preview = this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(bannerfile))
}
} | Base | 1 |
function set(target, path, val) {
"use strict";
try {
return add(target, path, val);
} catch(ex) {
console.error(ex);
return;
}
} | Base | 1 |
node.addEventListener("mouseenter", () => {
const t = tooltip();
t.innerHTML = getter();
}); | Base | 1 |
requestResetPassword(req) {
const config = req.config;
if (!config) {
this.invalidRequest();
}
if (!config.publicServerURL) {
return this.missingPublicServerURL();
}
const { username, token } = req.query;
if (!username || !token) {
return this.invalidLink(req);
}
return config.userController.checkResetTokenValidity(username, token).then(
() => {
const params = qs.stringify({
token,
id: config.applicationId,
username,
app: config.appName,
});
return Promise.resolve({
status: 302,
location: `${config.choosePasswordURL}?${params}`,
});
},
() => {
return this.invalidLink(req);
}
);
} | Class | 2 |
export function escape<T>(input: T): T extends SafeValue ? T['value'] : T {
return typeof input === 'string'
? string.escapeHTML(input)
: input instanceof SafeValue
? input.value
: input
} | Base | 1 |
const unSet = (obj, path, options = {}, tracking = {}) => {
let internalPath = path;
options = {
"transformRead": returnWhatWasGiven,
"transformKey": returnWhatWasGiven,
"transformWrite": returnWhatWasGiven,
...options
};
// No object data
if (obj === undefined || obj === null) {
return;
}
// No path string
if (!internalPath) {
return;
}
internalPath = clean(internalPath);
// Path is not a string, throw error
if (typeof internalPath !== "string") {
throw new Error("Path argument must be a string");
}
if (typeof obj !== "object") {
return;
}
const newObj = decouple(obj, options);
// Path has no dot-notation, set key/value
if (isNonCompositePath(internalPath)) {
if (newObj.hasOwnProperty(unEscape(internalPath))) {
delete newObj[options.transformKey(unEscape(internalPath))];
return newObj;
}
tracking.returnOriginal = true;
return obj;
}
const pathParts = split(internalPath);
const pathPart = pathParts.shift();
const transformedPathPart = options.transformKey(unEscape(pathPart));
let childPart = newObj[transformedPathPart];
if (!childPart) {
// No child part available, nothing to unset!
tracking.returnOriginal = true;
return obj;
}
newObj[transformedPathPart] = unSet(childPart, pathParts.join('.'), options, tracking);
if (tracking.returnOriginal) {
return obj;
}
return newObj;
}; | Base | 1 |
function PageantSock() {
this.proc = undefined;
this.buffer = null;
} | Base | 1 |
export function parse(data: string, params?: IParseConfig): IIniObject {
const {
delimiter = '=',
comment = ';',
nothrow = false,
autoTyping = true,
dataSections = [],
} = { ...params };
let typeParser: ICustomTyping;
if (typeof autoTyping === 'function') {
typeParser = autoTyping;
} else {
typeParser = autoTyping ? <ICustomTyping> autoType : (val) => val;
}
const lines: string[] = data.split(/\r?\n/g);
let lineNumber = 0;
let currentSection: string = '';
let isDataSection: boolean = false;
const result: IIniObject = {};
for (const rawLine of lines) {
lineNumber += 1;
const line: string = rawLine.trim();
if ((line.length === 0) || (line.startsWith(comment))) {
continue;
} else if (line[0] === '[') {
const match = line.match(sectionNameRegex);
if (match !== null) {
currentSection = match[1].trim();
isDataSection = dataSections.includes(currentSection);
if (!(currentSection in result)) {
result[currentSection] = (isDataSection) ? [] : {};
}
continue;
}
} else if (isDataSection) {
(<IniValue[]>result[currentSection]).push(rawLine);
continue;
} else if (line.includes(delimiter)) {
const posOfDelimiter: number = line.indexOf(delimiter);
const name = line.slice(0, posOfDelimiter).trim();
const rawVal = line.slice(posOfDelimiter + 1).trim();
const val = typeParser(rawVal, currentSection, name);
if (currentSection !== '') {
(<IIniObjectSection>result[currentSection])[name] = val;
} else {
result[name] = val;
}
continue;
}
const error = new ParsingError(line, lineNumber);
if (!nothrow) {
throw error;
} else if ($Errors in result) {
(<ParsingError[]>result[$Errors]).push(error);
} else {
result[$Errors] = [error];
}
}
return result;
} | Variant | 0 |
export function cleanObject(obj: any): any {
return Object.entries(obj).reduce(
(obj, [key, value]) =>
value === undefined
? obj
: {
...obj,
[key]: value
},
{}
);
} | Base | 1 |
constructor(options?: MessageChunkerOptions) {
options = options || {};
this.sequenceNumberGenerator = new SequenceNumberGenerator();
this.maxMessageSize = options.maxMessageSize || 16 *1024*1024;
this.update(options);
} | Class | 2 |
function main() {
try {
let tag = process.env.GITHUB_REF;
if (core.getInput('tag')) {
tag = `refs/tags/${core.getInput('tag')}`;
}
exec(`git for-each-ref --format='%(contents)' ${tag}`, (err, stdout) => {
if (err) {
core.setFailed(err);
} else {
core.setOutput('git-tag-annotation', stdout);
}
});
} catch (error) {
core.setFailed(error.message);
}
} | Base | 1 |
get: (path) => {
useCount++;
expect(path).toEqual('somepath');
},
})
).not.toThrow();
expect(useCount).toBeGreaterThan(0);
}); | Class | 2 |
constructor() {
super();
this.name = this.constructor.name + counter;
counter += 1;
this._timerId = null;
this._timeout = 30000; // 30 seconds timeout
this._socket = null;
this.headerSize = 8;
this.protocolVersion = 0;
this._disconnecting = false;
this._pendingBuffer = undefined;
this.bytesWritten = 0;
this.bytesRead = 0;
this._theCallback = undefined;
this.chunkWrittenCount = 0;
this.chunkReadCount = 0;
this._onSocketClosedHasBeenCalled = false;
this._onSocketEndedHasBeenCalled = false;
TCP_transport.registry.register(this);
} | Class | 2 |
export async function recursiveReadDir(dir: string): Promise<string[]> {
const subdirs = await readdir(dir);
const files = await Promise.all(
subdirs.map(async subdir => {
const res = resolve(dir, subdir);
return (await stat(res)).isDirectory() ? recursiveReadDir(res) : [res];
}),
);
return files.reduce((a, f) => a.concat(f), []);
} | Base | 1 |
func cssGogsMinCss() (*asset, error) {
bytes, err := cssGogsMinCssBytes()
if err != nil {
return nil, err
}
info := bindataFileInfo{name: "css/gogs.min.css", size: 64378, mode: os.FileMode(0644), modTime: time.Unix(1584214336, 0)}
a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xd9, 0x49, 0xa9, 0x99, 0x79, 0x58, 0x26, 0xec, 0xaa, 0x9, 0x5a, 0x24, 0x6, 0x69, 0x2e, 0xe0, 0x3a, 0xb1, 0x53, 0xc4, 0x42, 0x72, 0x4d, 0xe0, 0x67, 0x6d, 0xae, 0x6c, 0x8f, 0xc4, 0x27, 0x27}}
return a, nil
} | Base | 1 |
link: new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
const context = operation.getContext();
const {
response: { headers },
} = context;
expect(headers.get('access-control-allow-origin')).toEqual('*');
checked = true;
return response;
});
}).concat( | Class | 2 |
async handler(ctx) {
ctx.logStream.write(`Writing catalog-info.yaml`);
const { entity } = ctx.input;
await fs.writeFile(
resolvePath(ctx.workspacePath, 'catalog-info.yaml'),
yaml.stringify(entity),
);
}, | Base | 1 |
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
totalHours,
} | Base | 1 |
) => {
if (!info || !info.sessionToken) {
throw new Parse.Error(
Parse.Error.INVALID_SESSION_TOKEN,
'Invalid session token'
);
}
const sessionToken = info.sessionToken;
const selectedFields = getFieldNames(queryInfo)
.filter(field => field.startsWith(keysPrefix))
.map(field => field.replace(keysPrefix, ''));
const keysAndInclude = extractKeysAndInclude(selectedFields);
const { keys } = keysAndInclude;
let { include } = keysAndInclude;
if (validatedToken && !keys && !include) {
return {
sessionToken,
};
} else if (keys && !include) {
include = 'user';
}
const options = {};
if (keys) {
options.keys = keys
.split(',')
.map(key => `user.${key}`)
.join(',');
}
if (include) {
options.include = include
.split(',')
.map(included => `user.${included}`)
.join(',');
}
const response = await rest.find(
config,
Auth.master(config),
'_Session',
{ sessionToken },
options,
info.clientVersion,
info.context,
);
if (
!response.results ||
response.results.length == 0 ||
!response.results[0].user
) {
throw new Parse.Error(
Parse.Error.INVALID_SESSION_TOKEN,
'Invalid session token'
);
} else {
const user = response.results[0].user;
return {
sessionToken,
user,
};
}
}; | Class | 2 |
export function escapeCommentText(value: string): string {
return value.replace(END_COMMENT, END_COMMENT_ESCAPED);
} | Base | 1 |
export default async function email(
identifier: string,
options: InternalOptions<"email">
) {
const { url, adapter, provider, logger, callbackUrl } = options
// Generate token
const token =
(await provider.generateVerificationToken?.()) ?? | Base | 1 |
groupNames: groups.join(", "),
}),
"warning"
);
}
}); | Base | 1 |
export function escape(value: unknown, is_attr = false) {
const str = String(value);
const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;
pattern.lastIndex = 0;
let escaped = '';
let last = 0;
while (pattern.test(str)) {
const i = pattern.lastIndex - 1;
const ch = str[i];
escaped += str.substring(last, i) + (ch === '&' ? '&' : (ch === '"' ? '"' : '<'));
last = i + 1;
}
return escaped + str.substring(last);
} | Base | 1 |
func cssGogsMinCssMap() (*asset, error) {
bytes, err := cssGogsMinCssMapBytes()
if err != nil {
return nil, err
}
info := bindataFileInfo{name: "css/gogs.min.css.map", size: 22926, mode: os.FileMode(0644), modTime: time.Unix(1584214336, 0)}
a := &asset{bytes: bytes, info: info, digest: [32]uint8{0x46, 0x89, 0xb2, 0x95, 0x91, 0xfb, 0x5c, 0xda, 0xff, 0x63, 0x54, 0xc5, 0x91, 0xbf, 0x7a, 0x5a, 0xb5, 0x3d, 0xf, 0xf, 0x84, 0x41, 0x2d, 0xc3, 0x18, 0xf5, 0x74, 0xd7, 0xa9, 0x84, 0x70, 0xce}}
return a, nil
} | Base | 1 |
await getManager().transaction(async (manager) => {
const organizationUser = await manager.findOne(OrganizationUser, { where: { id } });
const user = await manager.findOne(User, { where: { id: organizationUser.userId } });
await this.usersService.throwErrorIfRemovingLastActiveAdmin(user);
await manager.update(User, user.id, { invitationToken: null });
await manager.update(OrganizationUser, id, { status: 'archived' });
}); | Class | 2 |
return { session: new Capnp.Capability(new ExternalWebSession(this.url, options), ApiSession) }; | Base | 1 |
async function validateSPLTokenTransfer(
message: Message,
meta: ConfirmedTransactionMeta,
recipient: Recipient,
splToken: SPLToken
): Promise<[BigNumber, BigNumber]> {
const recipientATA = await getAssociatedTokenAddress(splToken, recipient);
const accountIndex = message.accountKeys.findIndex((pubkey) => pubkey.equals(recipientATA));
if (accountIndex === -1) throw new ValidateTransferError('recipient not found');
const preBalance = meta.preTokenBalances?.find((x) => x.accountIndex === accountIndex);
const postBalance = meta.postTokenBalances?.find((x) => x.accountIndex === accountIndex);
return [
new BigNumber(preBalance?.uiTokenAmount.uiAmountString || 0),
new BigNumber(postBalance?.uiTokenAmount.uiAmountString || 0),
];
} | Class | 2 |
redirect: `${url}/error?${new URLSearchParams({
error: error as string,
})}`,
}
}
try {
const redirect = await emailSignin(email, options)
return { redirect }
} catch (error) {
logger.error("SIGNIN_EMAIL_ERROR", {
error: error as Error,
providerId: provider.id,
})
return { redirect: `${url}/error?error=EmailSignin` }
}
}
return { redirect: `${url}/signin` }
} | Class | 2 |
export function setByKeyPath(obj, keyPath, value) {
if (!obj || keyPath === undefined) return;
if ('isFrozen' in Object && Object.isFrozen(obj)) return;
if (typeof keyPath !== 'string' && 'length' in keyPath) {
assert(typeof value !== 'string' && 'length' in value);
for (var i = 0, l = keyPath.length; i < l; ++i) {
setByKeyPath(obj, keyPath[i], value[i]);
}
} else {
var period = keyPath.indexOf('.');
if (period !== -1) {
var currentKeyPath = keyPath.substr(0, period);
var remainingKeyPath = keyPath.substr(period + 1);
if (remainingKeyPath === "")
if (value === undefined) {
if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) obj.splice(currentKeyPath, 1);
else delete obj[currentKeyPath];
} else obj[currentKeyPath] = value;
else {
var innerObj = obj[currentKeyPath];
if (!innerObj) innerObj = (obj[currentKeyPath] = {});
setByKeyPath(innerObj, remainingKeyPath, value);
}
} else {
if (value === undefined) {
if (isArray(obj) && !isNaN(parseInt(keyPath))) obj.splice(keyPath, 1);
else delete obj[keyPath];
} else obj[keyPath] = value;
}
}
} | Variant | 0 |
function cleaner() {
setTimeout(() => {
if (ids.length < 1) { return; }
ActiveRooms.forEach((element, index) => {
element.Players.forEach((element2, index2) => {
if (!ids.includes(element2.Id)) {
ActiveRooms[index].Players.splice(index2, 1);
ActiveRooms[index].Players.forEach((element3) => {
element3.socket.emit('UserLeave', JSON.stringify({ RoomId: element.Id, UserLeaved: element2.Id }));
});
}
});
});
ActiveRooms.forEach((element, index) => {
if (element.Players.length === 0) {
ActiveRooms.splice(index, 1);
}
});
// ids = [];
}, 5000);
} | Compound | 4 |
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, | Base | 1 |
html: html({ url, host, theme }),
})
const failed = result.rejected.concat(result.pending).filter(Boolean)
if (failed.length) {
throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`)
}
},
options,
}
} | Class | 2 |
text: text({ url, host }),
html: html({ url, host, email }),
})
},
options,
}
} | Base | 1 |
function formatMessage(msg, output) {
var output = output;
output.parseTags = true;
msg = output._parseTags(msg);
output.parseTags = false;
return msg;
} | Base | 1 |
function localMessage(msg, source) {
var output = source.output;
output.add(formatMessage(msg, output));
} | Base | 1 |
async convert(input, options) {
this[_validate]();
options = this[_parseOptions](options);
const output = await this[_convert](input, options);
return output;
} | Base | 1 |
text: () => string
): { destroy: () => void; update: (t: () => string) => void } { | Base | 1 |
async function logPlatform(logger: Logger): Promise<void> {
const os = require('os');
let platform = os.platform();
logger.log(`OS is ${platform}`);
if (platform === 'darwin' || platform === 'win32') {
return;
}
const osInfo = require('linux-os-info');
const result = await osInfo();
const dist = result.id;
logger.log(`dist: ${dist}`);
} | Class | 2 |
function reject(req, res, message) {
log.info(`${req.method} ${req.path} rejected with 401 ${message}`);
res.status(401).send(message);
} | Base | 1 |
([ key, value ]) => ({ [key]: list.bind(null, value) }),
), | Base | 1 |
function setCachedRendererFunction (id: RendererFunctionId, wc: electron.WebContents, frameId: number, value: CallIntoRenderer) {
// eslint-disable-next-line no-undef
const wr = new WeakRef<CallIntoRenderer>(value);
const mapKey = id[0] + '~' + id[1];
rendererFunctionCache.set(mapKey, wr);
finalizationRegistry.register(value, {
id,
webContents: wc,
frameId
} as FinalizerInfo);
return value;
} | Class | 2 |
export declare function setDeepProperty(obj: any, propertyPath: string, value: any): void;
export declare function getDeepProperty(obj: any, propertyPath: string): any; | Base | 1 |
calculateGenesisCost(genesisOpReturnLength: number, inputUtxoSize: number, batonAddress: string|null, bchChangeAddress?: string, feeRate = 1) {
return this.calculateMintOrGenesisCost(genesisOpReturnLength, inputUtxoSize, batonAddress, bchChangeAddress, feeRate);
} | Class | 2 |
module.exports = async function(path) {
if (!path || typeof path !== 'string') {
throw new TypeError(`string was expected, instead got ${path}`);
}
const absolute = resolve(path);
if (!(await exist(absolute))) {
throw new Error(`Could not find file at path "${absolute}"`);
}
const ts = await exec(`git log -1 --format="%at" -- ${path}`);
return new Date(Number(ts) * 1000);
}; | Base | 1 |
template({ labelInfo, labelHead, iconSync, iconAdd, pfx, ppfx }: any) {
return `
<div id="${pfx}up" class="${pfx}header">
<div id="${pfx}label" class="${pfx}header-label">${labelHead}</div>
<div id="${pfx}status-c" class="${pfx}header-status">
<span id="${pfx}input-c" data-states-c>
<div class="${ppfx}field ${ppfx}select">
<span id="${ppfx}input-holder">
<select id="${pfx}states" data-states></select>
</span>
<div class="${ppfx}sel-arrow">
<div class="${ppfx}d-s-arrow"></div>
</div>
</div>
</span>
</div>
</div>
<div id="${pfx}tags-field" class="${ppfx}field">
<div id="${pfx}tags-c" data-selectors></div>
<input id="${pfx}new" data-input/>
<span id="${pfx}add-tag" class="${pfx}tags-btn ${pfx}tags-btn__add" data-add>
${iconAdd}
</span>
<span class="${pfx}tags-btn ${pfx}tags-btn__sync" style="display: none" data-sync-style>
${iconSync}
</span>
</div>
<div class="${pfx}sels-info">
<div class="${pfx}label-sel">${labelInfo}:</div>
<div class="${pfx}sels" data-selected></div>
</div>`;
} | Base | 1 |
function detailedDataTableMapper(entry) {
const project = Projects.findOne({ _id: entry.projectId })
const mapping = [project ? project.name : '',
dayjs.utc(entry.date).format(getGlobalSetting('dateformat')),
entry.task,
projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === entry.userId)?.profile?.name : '']
if (getGlobalSetting('showCustomFieldsInDetails')) {
if (CustomFields.find({ classname: 'time_entry' }).count() > 0) {
for (const customfield of CustomFields.find({ classname: 'time_entry' }).fetch()) {
mapping.push(entry[customfield[customFieldType]])
}
}
if (CustomFields.find({ classname: 'project' }).count() > 0) {
for (const customfield of CustomFields.find({ classname: 'project' }).fetch()) {
mapping.push(project[customfield[customFieldType]])
}
}
}
if (getGlobalSetting('showCustomerInDetails')) {
mapping.push(project ? project.customer : '')
}
if (getGlobalSetting('useState')) {
mapping.push(entry.state)
}
mapping.push(Number(timeInUserUnit(entry.hours)))
mapping.push(entry._id)
return mapping
} | Base | 1 |
constructor (
private sanitizer: DomSanitizer,
private serverService: ServerService,
private notifier: Notifier
) { } | Base | 1 |
[req.locale]: self.getBrowserBundles(req.locale)
};
if (req.locale !== self.defaultLocale) {
i18n[self.defaultLocale] = self.getBrowserBundles(self.defaultLocale);
}
const result = {
i18n,
locale: req.locale,
defaultLocale: self.defaultLocale,
locales: self.locales,
debug: self.debug,
show: self.show,
action: self.action,
crossDomainClipboard: req.session.aposCrossDomainClipboard
};
if (req.session.aposCrossDomainClipboard) {
req.session.aposCrossDomainClipboard = null;
}
return result;
}, | Base | 1 |
function networkStats(ifaces, callback) {
let ifacesArray = [];
// fallback - if only callback is given
if (util.isFunction(ifaces) && !callback) {
callback = ifaces;
ifacesArray = [getDefaultNetworkInterface()];
} else {
ifaces = ifaces || getDefaultNetworkInterface();
ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|');
ifacesArray = ifaces.split('|');
}
return new Promise((resolve) => {
process.nextTick(() => {
const result = [];
const workload = [];
if (ifacesArray.length && ifacesArray[0].trim() === '*') {
ifacesArray = [];
networkInterfaces(false).then(allIFaces => {
for (let iface of allIFaces) {
ifacesArray.push(iface.iface);
}
networkStats(ifacesArray.join(',')).then(result => {
if (callback) { callback(result); }
resolve(result);
});
});
} else {
for (let iface of ifacesArray) {
workload.push(networkStatsSingle(iface.trim()));
}
if (workload.length) {
Promise.all(
workload
).then(data => {
if (callback) { callback(data); }
resolve(data);
});
} else {
if (callback) { callback(result); }
resolve(result);
}
}
});
});
} | Base | 1 |
get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } })
})) | Class | 2 |
onUpdate: function(username, accessToken) {
users[username] = accessToken;
} | Base | 1 |
get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } })
})) | Class | 2 |
parse(cookieStr) {
let cookie = {};
(cookieStr || '')
.toString()
.split(';')
.forEach(cookiePart => {
let valueParts = cookiePart.split('=');
let key = valueParts
.shift()
.trim()
.toLowerCase();
let value = valueParts.join('=').trim();
let domain;
if (!key) {
// skip empty parts
return;
}
switch (key) {
case 'expires':
value = new Date(value);
// ignore date if can not parse it
if (value.toString() !== 'Invalid Date') {
cookie.expires = value;
}
break;
case 'path':
cookie.path = value;
break;
case 'domain':
domain = value.toLowerCase();
if (domain.length && domain.charAt(0) !== '.') {
domain = '.' + domain; // ensure preceeding dot for user set domains
}
cookie.domain = domain;
break;
case 'max-age':
cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000);
break;
case 'secure':
cookie.secure = true;
break;
case 'httponly':
cookie.httponly = true;
break;
default:
if (!cookie.name) {
cookie.name = key;
cookie.value = value;
}
}
});
return cookie;
} | Base | 1 |
Server.loadMyself((anyMe: Me | NU, stuffForMe?: StuffForMe) => {
// @ifdef DEBUG
// Might happen if there was no weakSessionId, and also, no cookie.
dieIf(!anyMe, 'TyE4032SMH57');
// @endif
const newMe = anyMe as Me;
if (isInSomeEmbCommentsIframe()) {
// Tell the embedded comments or embedded editor iframe that we just logged in,
// also include the session id, so Talkyard's script on the embedding page
// can remember it — because cookies and localstorage in an iframe typically
// get disabled by tracker blockers (they block 3rd party cookies).
const mainWin = getMainWin();
const typs: PageSession = mainWin.typs;
const weakSessionId = typs.weakSessionId;
const store: Store = ReactStore.allData();
const settings: SettingsVisibleClientSide = store.settings;
const rememberEmbSess =
settings.rememberEmbSess !== false &&
// If we got logged in automatically, then logout will be automatic too
// — could be surprising if we had to click buttons to log out,
// when we didn't need to do that, to log in.
typs.sessType !== SessionType.AutoTokenSiteCustomSso;
if (mainWin !== window) {
mainWin.theStore.me = _.cloneDeep(newMe);
}
sendToOtherIframes([
'justLoggedIn', { user: newMe, stuffForMe,
weakSessionId, pubSiteId: eds.pubSiteId, // [JLGDIN]
sessionType: null, rememberEmbSess }]);
}
setNewMe(newMe, stuffForMe);
if (afterwardsCallback) {
afterwardsCallback();
}
}); | Base | 1 |
module.exports = (yargs) => {
yargs.command('exec <container name> [commands...]', 'Execute command in docker container', () => {}, async (argv) => {
const containers = docker.getContainers();
const services = Object.keys(containers);
if (services.includes(argv.containername) || services.some((service) => service.includes(argv.containername))) {
const container = containers[argv.containername]
? containers[argv.containername]
: Object.entries(containers).find(([key]) => key.includes(argv.containername))[1];
if (argv.commands.length === 0) {
// if we have default connect command then use it
if (container.connectCommand) {
// eslint-disable-next-line no-param-reassign
argv.commands = container.connectCommand;
} else {
// otherwise fall back to bash (if it exists inside container)
argv.commands.push('bash');
}
}
await executeInContainer({
containerName: container.name,
commands: argv.commands
});
return;
}
logger.error(`No container found "${argv.containername}"`);
});
}; | Class | 2 |
userPassword: bcrypt.hashSync(req.body.userPassword, 10),
isAdmin: isAdmin
};
// check for existing user
db.users.findOne({'userEmail': req.body.userEmail}, (err, user) => {
if(user){
// user already exists with that email address
console.error(colors.red('Failed to insert user, possibly already exists: ' + err));
req.session.message = 'A user with that email address already exists';
req.session.messageType = 'danger';
res.redirect('/admin/user/new');
return;
}
// email is ok to be used.
db.users.insert(doc, (err, doc) => {
// show the view
if(err){
if(doc){
console.error(colors.red('Failed to insert user: ' + err));
req.session.message = 'User exists';
req.session.messageType = 'danger';
res.redirect('/admin/user/edit/' + doc._id);
return;
}
console.error(colors.red('Failed to insert user: ' + err));
req.session.message = 'New user creation failed';
req.session.messageType = 'danger';
res.redirect('/admin/user/new');
return;
}
req.session.message = 'User account inserted';
req.session.messageType = 'success';
// if from setup we add user to session and redirect to login.
// Otherwise we show users screen
if(urlParts.path === '/admin/setup'){
req.session.user = req.body.userEmail;
res.redirect('/admin/login');
return;
}
res.redirect('/admin/users');
});
});
}); | Class | 2 |
Subsets and Splits