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) ...
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}${...
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.loca...
Base
1
async function waitSessionCountChange(currentSessionCountMonitoredItem) { return await new Promise((resolve,reject) => { const timer = setTimeout(() => { reject(new Error("Never received ", currentSessionCountMonitoredItem.toString())); }, 5000); currentSessionCountMonitoredIte...
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(...
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) { // HackSessionCo...
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', ...
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 — w...
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") ||...
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.readMessage...
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 = ma...
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')...
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.j...
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 NoSche...
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...
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(en...
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( s...
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); ...
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, "&#8203;.")}` // Some simple styling options const backgroundColor = "#f9f9f9" const textColor = "#444444" const mainBackgroundColor = "#ffffff" const buttonBackgroundColor = "#346df1" const buttonBorderColor = "#346df1" const buttonTextColor = "#ffffff" re...
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...
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 an...
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 === '') ...
Base
1
return txt.replace(/[&<>]/gm, (str) => { if (str === "&") return "&amp;"; if (str === "<") return "&lt;"; if (str === ">") return "&gt;"; });
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, ...
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.""" ...
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) => { ...
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); ...
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; } ...
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 = pr...
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(item...
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.m...
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...
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, }); retu...
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 === e...
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: 'test@valid.sender', to: 'test@valid.recipient' }, 'message\r\nline 2' ) }, function(err, data) { expect(e...
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....
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 r...
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...
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 an...
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 /*...
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"...
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: 'E...
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 inst...
Class
2
async resolve(_source, _args, context, queryInfo) { try { const { config, info } = context; return await getUserFromSessionToken( config, info, queryInfo, 'user.', false ); } catch (e) { parseGraphQ...
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.pu...
Class
2