code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
clip: Object.assign({ x: 0, y: 0 }, dimensions)
}, provider.getScreenshotOptions(options)));
return output;
} | Base | 1 |
PageantSock.prototype.write = function(buf) {
if (this.buffer === null)
this.buffer = buf;
else {
this.buffer = Buffer.concat([this.buffer, buf],
this.buffer.length + buf.length);
}
// Wait for at least all length bytes
if (this.buffer.length < 4)
return;
var len = readUInt32BE(this.buffer, 0);
// Make sure we have a full message before querying pageant
if ((this.buffer.length - 4) < len)
return;
buf = this.buffer.slice(0, 4 + len);
if (this.buffer.length > (4 + len))
this.buffer = this.buffer.slice(4 + len);
else
this.buffer = null;
var self = this;
var proc;
var hadError = false;
proc = this.proc = cp.spawn(EXEPATH, [ buf.length ]);
proc.stdout.on('data', function(data) {
self.emit('data', data);
});
proc.once('error', function(err) {
if (!hadError) {
hadError = true;
self.emit('error', err);
}
});
proc.once('close', function(code) {
self.proc = undefined;
if (ERROR[code] && !hadError) {
hadError = true;
self.emit('error', ERROR[code]);
}
self.emit('close', hadError);
});
proc.stdin.end(buf);
}; | Base | 1 |
export function exportVariable(name: string, val: any): void {
const convertedVal = toCommandValue(val)
process.env[name] = convertedVal
const filePath = process.env['GITHUB_ENV'] || ''
if (filePath) {
const delimiter = '_GitHubActionsFileCommandDelimeter_'
const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`
issueFileCommand('ENV', commandValue)
} else {
issueCommand('set-env', {name}, convertedVal)
}
} | Class | 2 |
...(options.role === 'anon' ? {} : {
user: {
title: 'System Task',
role: options.role
}
}),
res: {},
t(key, options = {}) {
return self.apos.i18n.i18next.t(key, {
...options,
lng: req.locale
});
},
data: {},
protocol: 'http',
get: function (propName) {
return { Host: 'you-need-to-set-baseUrl-in-app-js.com' }[propName];
},
query: {},
url: '/',
locale: self.apos.argv.locale || self.apos.modules['@apostrophecms/i18n'].defaultLocale,
mode: 'published',
aposNeverLoad: {},
aposStack: [],
__(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;
}
};
addCloneMethod(req);
req.res.__ = req.__;
const { role, ..._properties } = options || {};
Object.assign(req, _properties);
self.apos.i18n.setPrefixUrls(req);
return req;
function addCloneMethod(req) {
req.clone = (properties = {}) => {
const _req = {
...req,
...properties
};
self.apos.i18n.setPrefixUrls(_req);
addCloneMethod(_req);
return _req;
};
}
}, | Base | 1 |
async function waitSessionCountChange(currentSessionCountMonitoredItem) {
return await new Promise((resolve,reject) => {
const timer = setTimeout(() => {
reject(new Error("Never received ", currentSessionCountMonitoredItem.toString()));
}, 5000);
currentSessionCountMonitoredItem.once("changed", function (dataValue) {
clearTimeout(timer);
const new_currentSessionCount = dataValue.value.value;
debugLog("new currentSessionCount=", dataValue.toString());
resolve(new_currentSessionCount);
});
});
} | Class | 2 |
create = (profile) => {
const rockUpdateFields = this.mapApollosFieldsToRock(profile);
return this.post('/People', {
Gender: 0, // required by Rock. Listed first so it can be overridden.
...rockUpdateFields,
IsSystem: false, // required by rock
});
}; | Class | 2 |
calculateMintCost(mintOpReturnLength: number, inputUtxoSize: number, batonAddress: string|null, bchChangeAddress?: string, feeRate = 1) {
return this.calculateMintOrGenesisCost(mintOpReturnLength, inputUtxoSize, batonAddress, bchChangeAddress, feeRate);
} | Class | 2 |
export default function isSafeRedirect(url: string): boolean {
if (typeof url !== 'string') {
throw new TypeError(`Invalid url: ${url}`);
}
// Prevent open redirects using the //foo.com format (double forward slash).
if (/\/\//.test(url)) {
return false;
}
return !/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url);
} | Base | 1 |
constructor(url, options, db, saveTemplate) {
super(db, saveTemplate);
if (!saveTemplate) {
// enable backwards-compatibilty tweaks.
this.fromHackSession = true;
}
const parsedUrl = Url.parse(url);
this.host = parsedUrl.hostname;
if (this.fromHackSession) {
// HackSessionContext.getExternalUiView() apparently ignored any path on the URL. Whoops.
} else {
if (parsedUrl.path === "/") {
// The URL parser says path = "/" for both "http://foo" and "http://foo/". We want to be
// strict, though.
this.path = url.endsWith("/") ? "/" : "";
} else {
this.path = parsedUrl.path;
}
}
this.port = parsedUrl.port;
this.protocol = parsedUrl.protocol;
this.options = options || {};
} | Base | 1 |
stitchSchemas({ subschemas: [autoSchema] }),
});
parseGraphQLServer.applyGraphQL(expressApp);
await new Promise((resolve) =>
httpServer.listen({ port: 13377 }, resolve)
);
const httpLink = createUploadLink({
uri: 'http://localhost:13377/graphql',
fetch,
headers,
});
apolloClient = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: 'no-cache',
},
},
});
});
afterAll(async () => {
await httpServer.close();
});
it('can resolve a query', async () => {
const result = await apolloClient.query({
query: gql`
query Health {
health
}
`,
});
expect(result.data.health).toEqual(true);
});
}); | Class | 2 |
export function getCurSid12Maybe3(): St | N { // [ts_authn_modl]
const store: Store = debiki2.ReactStore.allData();
const cookieName =
debiki2.store_isFeatFlagOn(store, 'ffUseNewSid') ? 'TyCoSid123' : 'dwCoSid';
let sid = getSetCookie(cookieName);
if (!sid) {
// Cannot use store.me.mySidPart1 — we might not yet have loaded
// the current user from the server; store.me might be stale.
const typs: PageSession = getMainWin().typs;
// This might not include part 3 (won't, if we're in an embedded comments
// iframe, and didn't login or resume via a popup win directly against the
// server so we could access cookie TyCoSid123, which includes part 3).
sid = typs.weakSessionId;
}
return sid || null;
} | Base | 1 |
function showTooltip(target: HTMLElement): () => void {
const tooltip = document.createElement("div");
const isHidden = target.classList.contains("hidden");
if (isHidden) {
target.classList.remove("hidden");
}
tooltip.className = "keyboard-tooltip";
tooltip.innerHTML = target.getAttribute("data-key") || "";
document.body.appendChild(tooltip);
const parentCoords = target.getBoundingClientRect();
// Padded 10px to the left if there is space or centered otherwise
const left =
parentCoords.left +
Math.min((target.offsetWidth - tooltip.offsetWidth) / 2, 10);
const top =
parentCoords.top + (target.offsetHeight - tooltip.offsetHeight) / 2;
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top + window.pageYOffset}px`;
return (): void => {
tooltip.remove();
if (isHidden) {
target.classList.add("hidden");
}
};
} | Base | 1 |
constructor(bitbox: BITBOX) {
if(!bitbox)
throw Error("Must provide BITBOX instance to class constructor.")
this.BITBOX = bitbox;
} | Class | 2 |
@action gotoUrl = (_url) => {
transaction(() => {
let url = (_url || this.nextUrl).trim().replace(/\/+$/, '');
if (!hasProtocol.test(url)) {
url = `https://${url}`;
}
this.setNextUrl(url);
this.setCurrentUrl(this.nextUrl);
});
} | Class | 2 |
other_senders_count: Math.max(0, all_senders.length - MAX_AVATAR),
other_sender_names,
muted,
topic_muted,
participated: topic_data.participated,
full_last_msg_date_time: full_datetime,
};
} | Base | 1 |
constructor(options: PacketAssemblerOptions) {
super();
this._stack = [];
this.expectedLength = 0;
this.currentLength = 0;
this.readMessageFunc = options.readMessageFunc;
this.minimumSizeInBytes = options.minimumSizeInBytes || 8;
assert(typeof this.readMessageFunc === "function", "packet assembler requires a readMessageFunc");
} | Class | 2 |
html: html({ url, host, email }),
})
}, | Base | 1 |
export function suspendUser(userId: UserId, numDays: number, reason: string, success: () => void) { | Base | 1 |
formatMessage() {
if (this.isATweet) {
const withUserName = this.message.replace(
TWITTER_USERNAME_REGEX,
TWITTER_USERNAME_REPLACEMENT
);
const withHash = withUserName.replace(
TWITTER_HASH_REGEX,
TWITTER_HASH_REPLACEMENT
);
const markedDownOutput = marked(withHash);
return markedDownOutput;
}
return marked(this.message, { breaks: true, gfm: true });
} | Base | 1 |
function setDeepProperty(obj, propertyPath, value) {
const a = splitPath(propertyPath);
const n = a.length;
for (let i = 0; i < n - 1; i++) {
const k = a[i];
if (!(k in obj)) {
obj[k] = {};
}
obj = obj[k];
}
obj[a[n - 1]] = value;
return;
} | 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(
createHttpLink({
uri: 'http://localhost:13377/graphql',
fetch,
headers: {
...headers,
Origin: 'http://someorigin.com',
},
})
),
cache: new InMemoryCache(),
}); | Class | 2 |
_resolvePath(path = '.') {
const clientPath = (() => {
path = nodePath.normalize(path);
if (nodePath.isAbsolute(path)) {
return nodePath.join(path);
} else {
return nodePath.join(this.cwd, path);
}
})();
const fsPath = (() => {
const resolvedPath = nodePath.join(this.root, clientPath);
return nodePath.resolve(nodePath.normalize(nodePath.join(resolvedPath)));
})();
return {
clientPath,
fsPath
};
} | Base | 1 |
Object.keys(data).forEach((key) => {
obj.add(ctx.next(data[key]));
}); | Base | 1 |
export function addEmailAddresses(userId: UserId, emailAddress: string, success: UserAcctRespHandler) {
postJsonSuccess('/-/add-email-address', success, { userId, emailAddress });
} | Base | 1 |
tooltipText: (c: FormatterContext, d: LineChartDatum) => string; | Base | 1 |
next: schemaData => {
if (
schemaData &&
((schemaData.errors && schemaData.errors.length > 0) ||
!schemaData.data)
) {
throw new Error(JSON.stringify(schemaData, null, 2))
}
if (!schemaData) {
throw new NoSchemaError(endpoint)
}
const schema = this.getSchema(schemaData.data as any)
const tracingSupported =
(schemaData.extensions && Boolean(schemaData.extensions.tracing)) ||
false
const result: TracingSchemaTuple = {
schema,
tracingSupported,
}
this.sessionCache.set(this.hash(session), result)
resolve(result)
this.fetching = this.fetching.remove(hash)
const subscription = this.subscriptions.get(hash)
if (subscription) {
subscription(result.schema)
}
}, | Base | 1 |
async start() {
if (this.server) {
return
}
this.app = await this.createApp()
if (this.port) {
this.server = this.app.listen(this.port)
} else {
do {
try {
this.port = await getPort({ port: defaultWatchServerPort })
this.server = this.app.listen(this.port)
} catch {}
} while (!this.server)
}
this.log.info("")
this.statusLog = this.log.placeholder()
} | Base | 1 |
[_sanitize](svg) {
return svg.removeAttr('onload');
} | Base | 1 |
export async function execRequest(routes: Routers, ctx: AppContext) {
const match = findMatchingRoute(ctx.path, routes);
if (!match) throw new ErrorNotFound();
const endPoint = match.route.findEndPoint(ctx.request.method as HttpMethod, match.subPath.schema);
if (ctx.URL && !isValidOrigin(ctx.URL.origin, baseUrl(endPoint.type), endPoint.type)) throw new ErrorNotFound(`Invalid origin: ${ctx.URL.origin}`, 'invalidOrigin');
// This is a generic catch-all for all private end points - if we
// couldn't get a valid session, we exit now. Individual end points
// might have additional permission checks depending on the action.
if (!match.route.isPublic(match.subPath.schema) && !ctx.joplin.owner) throw new ErrorForbidden();
return endPoint.handler(match.subPath, ctx);
} | Compound | 4 |
return code.includes(hash);
});
if (containsMentions) {
// disable code highlighting if there is a mention in there
// highlighting will be wrong anyway because this is not valid code
return code;
}
return hljs.highlightAuto(code).value;
},
}); | Base | 1 |
Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null
]) | Class | 2 |
}validateOrReject(Object.assign(new Validators.${checker.typeToString(v.type)}(), req.${
v.name
}), validatorOptions)${v.hasQuestion ? ' : null' : ''}`
: ''
)
.join(',\n')}\n ])` | Class | 2 |
.catch(error => {
// There was an error with the session token
const result = {};
if (error && error.code === Parse.Error.INVALID_SESSION_TOKEN) {
// Store a resolved promise with the error for 10 minutes
result.error = error;
this.authCache.set(
sessionToken,
Promise.resolve(result),
60 * 10 * 1000
);
} else { | Class | 2 |
export function getProfileFromDeeplink(args): string | undefined {
// check if we are passed a profile in the SSO callback url
const deeplinkUrl = args.find(arg => arg.startsWith('element://'));
if (deeplinkUrl && deeplinkUrl.includes(SEARCH_PARAM)) {
const parsedUrl = new URL(deeplinkUrl);
if (parsedUrl.protocol === 'element:') {
const ssoID = parsedUrl.searchParams.get(SEARCH_PARAM);
const store = readStore();
console.log("Forwarding to profile: ", store[ssoID]);
return store[ssoID];
}
}
} | Variant | 0 |
commentSchema.statics.updateCommentsByPageId = function(comment, isMarkdown, commentId) {
const Comment = this;
return Comment.findOneAndUpdate(
{ _id: commentId },
{ $set: { comment, isMarkdown } },
);
}; | Base | 1 |
const escapedHost = `${host.replace(/\./g, "​.")}`
// Some simple styling options
const backgroundColor = "#f9f9f9"
const textColor = "#444444"
const mainBackgroundColor = "#ffffff"
const buttonBackgroundColor = "#346df1"
const buttonBorderColor = "#346df1"
const buttonTextColor = "#ffffff"
return `
<body style="background: ${backgroundColor};">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" style="padding: 10px 0px 20px 0px; font-size: 22px; font-family: Helvetica, Arial, sans-serif; color: ${textColor};">
<strong>${escapedHost}</strong>
</td>
</tr>
</table>
<table width="100%" border="0" cellspacing="20" cellpadding="0" style="background: ${mainBackgroundColor}; max-width: 600px; margin: auto; border-radius: 10px;">
<tr>
<td align="center" style="padding: 10px 0px 0px 0px; font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: ${textColor};">
Sign in as <strong>${escapedEmail}</strong>
</td>
</tr>
<tr>
<td align="center" style="padding: 20px 0;">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" style="border-radius: 5px;" bgcolor="${buttonBackgroundColor}"><a href="${url}" target="_blank" style="font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: ${buttonTextColor}; text-decoration: none; border-radius: 5px; padding: 10px 20px; border: 1px solid ${buttonBorderColor}; display: inline-block; font-weight: bold;">Sign in</a></td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" style="padding: 0px 0px 10px 0px; font-size: 16px; line-height: 22px; font-family: Helvetica, Arial, sans-serif; color: ${textColor};">
If you did not request this email you can safely ignore it.
</td>
</tr>
</table>
</body>
`
} | Base | 1 |
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
totalHours,
} | Base | 1 |
export function applyCommandArgs(configuration: any, argv: string[]) {
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 |
function process_request_callback(requestData: RequestData, err?: Error | null, response?: Response) {
assert(typeof requestData.callback === "function");
const request = requestData.request;
if (!response && !err && requestData.msgType !== "CLO") {
// this case happens when CLO is called and when some pending transactions
// remains in the queue...
err = new Error(" Connection has been closed by client , but this transaction cannot be honored");
}
if (response && response instanceof ServiceFault) {
response.responseHeader.stringTable = [...(response.responseHeader.stringTable || [])];
err = new Error(" serviceResult = " + response.responseHeader.serviceResult.toString());
// " returned by server \n response:" + response.toString() + "\n request: " + request.toString());
(err as any).response = response;
((err as any).request = request), (response = undefined);
}
const theCallbackFunction = requestData.callback;
/* istanbul ignore next */
if (!theCallbackFunction) {
throw new Error("Internal error");
}
assert(requestData.msgType === "CLO" || (err && !response) || (!err && response));
// let set callback to undefined to prevent callback to be called again
requestData.callback = undefined;
theCallbackFunction(err || null, !err && response !== null ? response : undefined);
}
| Class | 2 |
api.update = async function(req, res) {
const { commentForm } = req.body;
const pageId = commentForm.page_id;
const comment = commentForm.comment;
const isMarkdown = commentForm.is_markdown;
const commentId = commentForm.comment_id;
const author = commentForm.author;
if (comment === '') {
return res.json(ApiResponse.error('Comment text is required'));
}
if (commentId == null) {
return res.json(ApiResponse.error('\'comment_id\' is undefined'));
}
if (author !== req.user.username) {
return res.json(ApiResponse.error('Only the author can edit'));
}
// check whether accessible
const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
if (!isAccessible) {
return res.json(ApiResponse.error('Current user is not accessible to this page.'));
}
let updatedComment;
try {
updatedComment = await Comment.updateCommentsByPageId(comment, isMarkdown, commentId);
}
catch (err) {
logger.error(err);
return res.json(ApiResponse.error(err));
}
res.json(ApiResponse.success({ comment: updatedComment }));
// process notification if needed
}; | Base | 1 |
return txt.replace(/[&<>]/gm, (str) => {
if (str === "&") return "&";
if (str === "<") return "<";
if (str === ">") return ">";
}); | Base | 1 |
static buildGenesisOpReturn(config: configBuildGenesisOpReturn, type = 0x01) {
let hash;
try {
hash = config.hash!.toString('hex')
} catch (_) { hash = null }
return SlpTokenType1.buildGenesisOpReturn(
config.ticker,
config.name,
config.documentUri,
hash,
config.decimals,
config.batonVout,
config.initialQuantity,
type
)
} | Class | 2 |
parseOpReturnToChunks(script: Buffer, allow_op_0=false, allow_op_number=false) {
// """Extract pushed bytes after opreturn. Returns list of bytes() objects,
// one per push.
let ops: PushDataOperation[];
// Strict refusal of non-push opcodes; bad scripts throw OpreturnError."""
try {
ops = this.getScriptOperations(script);
} catch(e) {
//console.log(e);
throw Error('Script error');
}
if(ops[0].opcode !== this.BITBOX.Script.opcodes.OP_RETURN)
throw Error('No OP_RETURN');
let chunks: (Buffer|null)[] = [];
ops.slice(1).forEach(opitem => {
if(opitem.opcode > this.BITBOX.Script.opcodes.OP_16)
throw Error("Non-push opcode");
if(opitem.opcode > this.BITBOX.Script.opcodes.OP_PUSHDATA4) {
if(opitem.opcode === 80)
throw Error('Non-push opcode');
if(!allow_op_number)
throw Error('OP_1NEGATE to OP_16 not allowed');
if(opitem.opcode === this.BITBOX.Script.opcodes.OP_1NEGATE)
opitem.data = Buffer.from([0x81]);
else // OP_1 - OP_16
opitem.data = Buffer.from([opitem.opcode - 80]);
}
if(opitem.opcode === this.BITBOX.Script.opcodes.OP_0 && !allow_op_0){
throw Error('OP_0 not allowed');
}
chunks.push(opitem.data)
});
//console.log(chunks);
return chunks
} | Class | 2 |
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, | Base | 1 |
function RegisterUserName(socket, Data) {
var userName = Data.UserName.split('>').join(' ').split('<').join(' ').split('/').join(' ');
if (userName.length > 16) userName = userName.slice(0, 16);
if (userName.toLowerCase().includes('você')) userName = '~' + userName;
ActiveRooms.forEach((element, index) => {
if (element.Id === Data.RoomId) {
ActiveRooms[index].Players.forEach((element2, index2) => {
if (element2.Name.toLowerCase() === userName.toLowerCase()) {
console.log('UserName already exists');
return socket.emit('UserNameAlreadyExists');
} else if (element2.Id === Data.UserId) {
ActiveRooms[index].Players[index2].Name = userName;
}
socket.emit('UserNameInformation', JSON.stringify({ RoomId: element.Id, UserId: element2.Id, NickName: element2.Name }));
});
}
});
} | Compound | 4 |
export function setDeepProperty(obj: any, propertyPath: string, value: any): void {
const a = splitPath(propertyPath);
const n = a.length;
for (let i = 0; i < n - 1; i++) {
const k = a[i];
if (!(k in obj)) {
obj[k] = {};
}
obj = obj[k];
}
obj[a[n - 1]] = value;
return;
} | Base | 1 |
static buildSendOpReturn(config: configBuildSendOpReturn, type = 0x01) {
return SlpTokenType1.buildSendOpReturn(
config.tokenIdHex,
config.outputQtyArray,
type
)
} | Class | 2 |
ctx.prompt(prompt, function retryPrompt(answers) {
if (answers.length === 0)
return ctx.reject(['keyboard-interactive']);
nick = answers[0];
if (nick.length > MAX_NAME_LEN) {
return ctx.prompt('That nickname is too long.\n' + PROMPT_NAME,
retryPrompt);
} else if (nick.length === 0) {
return ctx.prompt('A nickname is required.\n' + PROMPT_NAME,
retryPrompt);
}
lowered = nick.toLowerCase();
for (var i = 0; i < users.length; ++i) {
if (users[i].name.toLowerCase() === lowered) {
return ctx.prompt('That nickname is already in use.\n' + PROMPT_NAME,
retryPrompt);
}
}
name = nick;
ctx.accept();
}); | Base | 1 |
Object.keys(data).forEach((key) => {
obj.set(key, deserializer(data[key], baseType) as T);
}); | Base | 1 |
.on("message", (request, msgType, requestId, channelId) => {
this._on_common_message(request, msgType, requestId, channelId);
}) | Class | 2 |
function indexer(set) {
return function(obj, i) {
"use strict";
try {
if (obj && i && obj.hasOwnProperty(i)) {
return obj[i];
} else if (obj && i && set) {
obj[i] = {};
return obj[i];
}
return;
} catch(ex) {
console.error(ex);
return;
}
};
} | Base | 1 |
get(`/-/load-email-addrs-login-methods?userId=${userId}`, response => {
success(response);
}); | Base | 1 |
Object.keys(obj).forEach((propertyName: string) => {
const propertyMetadata = ConverterService.getPropertyMetadata(properties, propertyName);
return this.convertProperty(obj, instance, propertyName, propertyMetadata, options);
}); | Base | 1 |
export function protocolInit(): void {
// get all args except `hidden` as it'd mean the app would not get focused
// XXX: passing args to protocol handlers only works on Windows, so unpackaged deep-linking
// --profile/--profile-dir are passed via the SEARCH_PARAM var in the callback url
const args = process.argv.slice(1).filter(arg => arg !== "--hidden" && arg !== "-hidden");
if (app.isPackaged) {
app.setAsDefaultProtocolClient('element', process.execPath, args);
} else if (process.platform === 'win32') { // on Mac/Linux this would just cause the electron binary to open
// special handler for running without being packaged, e.g `electron .` by passing our app path to electron
app.setAsDefaultProtocolClient('element', process.execPath, [app.getAppPath(), ...args]);
}
if (process.platform === 'darwin') {
// Protocol handler for macos
app.on('open-url', function(ev, url) {
ev.preventDefault();
processUrl(url);
});
} else {
// Protocol handler for win32/Linux
app.on('second-instance', (ev, commandLine) => {
const url = commandLine[commandLine.length - 1];
if (!url.startsWith(PROTOCOL)) return;
processUrl(url);
});
}
} | Variant | 0 |
([ key, value ]) => ({ [key]: exec.bind(null, `git show -s --format=%${value}`) }),
), | Base | 1 |
export default function addStickyControl() {
extend(DiscussionListState.prototype, 'requestParams', function(params) {
if (app.current.matches(IndexPage) || app.current.matches(DiscussionPage)) {
params.include.push('firstPost');
}
});
extend(DiscussionListItem.prototype, 'infoItems', function(items) {
const discussion = this.attrs.discussion;
if (discussion.isSticky() && !this.attrs.params.q && !discussion.lastReadPostNumber()) {
const firstPost = discussion.firstPost();
if (firstPost) {
const excerpt = truncate(firstPost.contentPlain(), 175);
items.add('excerpt', m.trust(excerpt), -100);
}
}
});
} | Base | 1 |
const errorHandler = (err: Error) => {
this._cancel_wait_for_open_secure_channel_request_timeout();
this.messageBuilder.removeListener("message", messageHandler);
this.close(() => {
callback(new Error("/Expecting OpenSecureChannelRequest to be valid " + err.message));
});
}; | Class | 2 |
private _renew_security_token() {
doDebug && debugLog("ClientSecureChannelLayer#_renew_security_token");
// istanbul ignore next
if (!this.isValid()) {
// this may happen if the communication has been closed by the client or the sever
warningLog("Invalid socket => Communication has been lost, cannot renew token");
return;
}
const isInitial = false;
this._open_secure_channel_request(isInitial, (err?: Error | null) => {
/* istanbul ignore else */
if (!err) {
doDebug && debugLog(" token renewed");
/**
* notify the observers that the security has been renewed
* @event security_token_renewed
*/
this.emit("security_token_renewed");
} else {
if (doDebug) {
debugLog("ClientSecureChannelLayer: Warning: securityToken hasn't been renewed -> err ", err);
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX CHECK ME !!!
this.closeWithError(new Error("Restarting because Request has timed out during OpenSecureChannel"), () => {
/* */
});
}
});
}
| Class | 2 |
Languages.get = async function (language, namespace) {
const data = await fs.promises.readFile(path.join(languagesPath, language, `${namespace}.json`), 'utf8');
const parsed = JSON.parse(data) || {};
const result = await plugins.hooks.fire('filter:languages.get', {
language,
namespace,
data: parsed,
});
return result.data;
}; | 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 |
export function fetchRemoteBranch(remote: string, remoteBranch: string, cwd: string) {
const results = git(["fetch", remote, remoteBranch], { cwd });
if (!results.success) {
throw gitError(`Cannot fetch remote: ${remote} ${remoteBranch}`);
}
} | Class | 2 |
message: new MockBuilder(
{
from: '[email protected]',
to: '[email protected]'
},
'message\r\nline 2'
)
},
function(err, data) {
expect(err).to.not.exist;
expect(data.messageId).to.equal('<test>');
expect(output).to.equal('message\nline 2');
client._spawn.restore();
done();
}
);
}); | Base | 1 |
async showExportDialogEvent({notePath, defaultType}) {
// each opening of the dialog resets the taskId, so we don't associate it with previous exports anymore
this.taskId = '';
this.$exportButton.removeAttr("disabled");
if (defaultType === 'subtree') {
this.$subtreeType.prop("checked", true).trigger('change');
// to show/hide OPML versions
this.$widget.find("input[name=export-subtree-format]:checked").trigger('change');
}
else if (defaultType === 'single') {
this.$singleType.prop("checked", true).trigger('change');
}
else {
throw new Error("Unrecognized type " + defaultType);
}
this.$widget.find(".opml-v2").prop("checked", true); // setting default
utils.openDialog(this.$widget);
const {noteId, parentNoteId} = treeService.getNoteIdAndParentIdFromNotePath(notePath);
this.branchId = await froca.getBranchId(parentNoteId, noteId);
const noteTitle = await treeService.getNoteTitle(noteId);
this.$noteTitle.html(noteTitle);
} | Base | 1 |
return `1 ${base} = ${c.amount(d.value, quote)}<em>${day(d.date)}</em>`;
},
});
} | Base | 1 |
servers: servers.map((p) => ({ command: p.command!, host: p.serverHost! })),
}) | Base | 1 |
function reduce(obj, str) {
"use strict";
try {
if ( typeof str !== "string") {
return;
}
if ( typeof obj !== "object") {
return;
}
return str.split('.').reduce(indexFalse, obj);
} catch(ex) {
console.error(ex);
return;
}
} | Base | 1 |
Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null
]) | Class | 2 |
'X-Parse-Session-Token': user5.getSessionToken(),
})
).data.find.edges.map((object) => object.node.someField)
).toEqual(['someValue3']);
}); | Class | 2 |
parseGraphQLServer._getGraphQLOptions = async (req) => {
expect(req.info).toBeDefined();
expect(req.config).toBeDefined();
expect(req.auth).toBeDefined();
checked = true;
return await originalGetGraphQLOptions.bind(parseGraphQLServer)(req);
}; | Class | 2 |
use: (path) => {
useCount++;
expect(path).toEqual('somepath');
},
})
).not.toThrow();
expect(useCount).toBeGreaterThan(0);
}); | Class | 2 |
export async function getApi(constructor = Gists) {
const token = await getToken();
const apiurl = config.get("apiUrl");
if (!apiurl) {
const message = "No API URL is set.";
throw new Error(message);
}
return new constructor({ apiurl, token });
} | Class | 2 |
export function logoutClientSideOnly(ps: { goTo?: St, skipSend?: Bo } = {}) {
Server.deleteTempSessId();
ReactDispatcher.handleViewAction({
actionType: actionTypes.Logout
});
if (eds.isInEmbeddedCommentsIframe && !ps.skipSend) {
// Tell the editor iframe that we've logged out.
// And maybe we'll redirect the embedd*ing* window. [sso_redir_par_win]
sendToOtherIframes(['logoutClientSideOnly', ps]);
// Probaby not needed, since reload() below, but anyway:
patchTheStore({ setEditorOpen: false });
const sessWin: MainWin = getMainWin();
delete sessWin.typs.weakSessionId;
sessWin.theStore.me = 'TyMLOGDOUT' as any;
}
// Disconnect WebSocket so we won't receive data, for this user, after we've
// logged out: (we reload() below — but the service-worker might stay connected)
pubsub.disconnectWebSocket();
if (ps.goTo) {
if (eds.isInIframe) {
// Then we'll redirect the parent window instead. [sso_redir_par_win]
}
else {
location.assign(ps.goTo);
}
// If that for some reason won't do anything, then make sure we really forget
// all logged in state anyway:
setTimeout(function() {
logW(`location.assign(${ps.goTo}) had no effect? Reloading anyway...`);
location.reload();
}, 2000);
}
else {
// Quick fix that reloads the admin page (if one views it) so login dialog appears.
// But don't do in the goTo if branch — apparently location.reload()
// cancels location.assign(..) — even if done on the lines after (!).
location.reload();
}
} | Base | 1 |
tooltipText: (c: FormatterContext, d: BarChartDatum, e: string) => string; | Base | 1 |
get: (path) => {
useCount++;
expect(path).toEqual('somepath');
}, | Class | 2 |
return { kind: 'redirect', to: `/signin?from=${encodeURIComponent(req!.url!)}` };
}
}; | Base | 1 |
getDownloadUrl(id, accessToken) {
return this.importExport.getDownloadUrl(id, accessToken);
}, | Base | 1 |
signBufferFunc: (chunk: Buffer) => makeMessageChunkSignatureWithDerivedKeys(chunk, derivedKeys),
signatureLength: derivedKeys.signatureLength,
sequenceHeaderSize: 0,
};
const securityHeader = new SymmetricAlgorithmSecurityHeader({
tokenId: 10
});
const msgChunkManager = new SecureMessageChunkManager("MSG", options, securityHeader, sequenceNumberGenerator);
msgChunkManager.on("chunk", (chunk, final) => callback(null, chunk));
msgChunkManager.write(buffer, buffer.length);
msgChunkManager.end();
} | Class | 2 |
function process_request_callback(requestData: RequestData, err?: Error | null, response?: Response) {
assert(typeof requestData.callback === "function");
const request = requestData.request;
if (!response && !err && requestData.msgType !== "CLO") {
// this case happens when CLO is called and when some pending transactions
// remains in the queue...
err = new Error(" Connection has been closed by client , but this transaction cannot be honored");
}
if (response && response instanceof ServiceFault) {
response.responseHeader.stringTable = [...(response.responseHeader.stringTable || [])];
err = new Error(" serviceResult = " + response.responseHeader.serviceResult.toString());
// " returned by server \n response:" + response.toString() + "\n request: " + request.toString());
(err as any).response = response;
((err as any).request = request), (response = undefined);
}
const theCallbackFunction = requestData.callback;
/* istanbul ignore next */
if (!theCallbackFunction) {
throw new Error("Internal error");
}
assert(requestData.msgType === "CLO" || (err && !response) || (!err && response));
// let set callback to undefined to prevent callback to be called again
requestData.callback = undefined;
theCallbackFunction(err || null, !err && response !== null ? response : undefined);
}
| Base | 1 |
export function get(key: "apiUrl"): string;
export function get(key: "images.markdownPasteFormat"): "markdown" | "html"; | Class | 2 |
export function html(m, keyPath, ...args) {
const html = str(m, keyPath, ...args);
return html ? React.createElement('span', { dangerouslySetInnerHTML: { __html: html } }) : null;
} | Base | 1 |
on(eventName: "message", eventHandler: (message: Buffer) => void): this; | Class | 2 |
WebContents.prototype._sendToFrameInternal = 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(true /* internal */, frameId, channel, args);
}; | Class | 2 |
export function esc<T=unknown>(value: T): T|string;
export function transform(input: string, options?: Options & { format?: 'esm' | 'cjs' }): string; | Base | 1 |
function applyInlineFootnotes(elem) {
const footnoteRefs = elem.querySelectorAll("sup.footnote-ref");
footnoteRefs.forEach((footnoteRef) => {
const expandableFootnote = document.createElement("a");
expandableFootnote.classList.add("expand-footnote");
expandableFootnote.innerHTML = iconHTML("ellipsis-h");
expandableFootnote.href = "";
expandableFootnote.role = "button";
expandableFootnote.dataset.footnoteId = footnoteRef
.querySelector("a")
.id.replace("footnote-ref-", "");
footnoteRef.after(expandableFootnote);
});
if (footnoteRefs.length) {
elem.classList.add("inline-footnotes");
}
} | Class | 2 |
export function createCatalogWriteAction() {
return createTemplateAction<{ name?: string; entity: Entity }>({
id: 'catalog:write',
description: 'Writes the catalog-info.yaml for your template',
schema: {
input: {
type: 'object',
properties: {
entity: {
title: 'Entity info to write catalog-info.yaml',
description:
'You can provide the same values used in the Entity schema.',
type: 'object',
},
},
},
},
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 |
event.reply = (...args: any[]) => {
event.sender.sendToFrame(event.frameId, ...args);
}; | Class | 2 |
return `[${renderType(type.ofType)}]`;
}
return `<a class="typeName">${type.name}</a>`;
} | Base | 1 |
private _readPacketInfo(data: Buffer) {
return this.readMessageFunc(data);
} | Class | 2 |
session: session.fromPartition('about-window'),
spellcheck: false,
webviewTag: false,
},
width: WINDOW_SIZE.WIDTH,
});
aboutWindow.setMenuBarVisibility(false);
// Prevent any kind of navigation
// will-navigate is broken with sandboxed env, intercepting requests instead
// see https://github.com/electron/electron/issues/8841
aboutWindow.webContents.session.webRequest.onBeforeRequest(async ({url}, callback) => {
// Only allow those URLs to be opened within the window
if (ABOUT_WINDOW_ALLOWLIST.includes(url)) {
return callback({cancel: false});
}
// Open HTTPS links in browser instead
if (url.startsWith('https://')) {
await shell.openExternal(url);
} else {
logger.info(`Attempt to open URL "${url}" in window prevented.`);
callback({redirectURL: ABOUT_HTML});
}
});
// Locales
ipcMain.on(EVENT_TYPE.ABOUT.LOCALE_VALUES, (event, labels: locale.i18nLanguageIdentifier[]) => {
if (aboutWindow) {
const isExpected = event.sender.id === aboutWindow.webContents.id;
if (isExpected) {
const resultLabels: Record<string, string> = {};
labels.forEach(label => (resultLabels[label] = locale.getText(label)));
event.sender.send(EVENT_TYPE.ABOUT.LOCALE_RENDER, resultLabels);
}
}
});
// Close window via escape
aboutWindow.webContents.on('before-input-event', (_event, input) => {
if (input.type === 'keyDown' && input.key === 'Escape') {
if (aboutWindow) {
aboutWindow.close();
}
}
});
aboutWindow.on('closed', () => (aboutWindow = undefined));
await aboutWindow.loadURL(ABOUT_HTML);
if (aboutWindow) {
aboutWindow.webContents.send(EVENT_TYPE.ABOUT.LOADED, {
copyright: config.copyright,
electronVersion: config.version,
productName: config.name,
webappVersion,
});
}
}
aboutWindow.show();
}; | Class | 2 |
async resolve(_source, _args, context, queryInfo) {
try {
const { config, info } = context;
return await getUserFromSessionToken(
config,
info,
queryInfo,
'user.',
false
);
} catch (e) {
parseGraphQLSchema.handleError(e);
}
}, | Class | 2 |
constructor()
{
// All construction occurs here
this.setup_palettes();
this._use_classes = false;
this._escape_for_html = true;
this.bold = false;
this.fg = this.bg = null;
this._buffer = '';
this._url_whitelist = { 'http':1, 'https':1 };
} | Base | 1 |
export function fetchRemote(remote: string, cwd: string) {
const results = git(["fetch", remote], { cwd });
if (!results.success) {
throw gitError(`Cannot fetch remote: ${remote}`);
}
} | Class | 2 |
private _buildData(data: Buffer) {
if (data && this._stack.length === 0) {
return data;
}
if (!data && this._stack.length === 1) {
data = this._stack[0];
this._stack.length = 0; // empty stack array
return data;
}
this._stack.push(data);
data = Buffer.concat(this._stack);
this._stack.length = 0;
return data;
} | Class | 2 |
Subsets and Splits