code
stringlengths
31
2.05k
label_name
stringclasses
5 values
label
int64
0
4
public handleUpgrade( req: IncomingMessage, socket: Duplex, upgradeHead: Buffer ) { this.prepare(req); const res = new WebSocketResponse(req, socket); const callback = (errorCode, errorContext) => { if (errorCode) { this.emit("connection_error", { req, code...
Base
1
const callback = (errorCode, errorContext) => { if (errorCode) { this.emit("connection_error", { req, code: errorCode, message: Server.errorMessages[errorCode], context: errorContext, }); abortUpgrade(socket, errorCode, errorContext); ret...
Base
1
const callback = async (errorCode, errorContext) => { if (errorCode) { this.emit("connection_error", { req, code: errorCode, message: Server.errorMessages[errorCode], context: errorContext, }); this.abortRequest(res, errorCode, errorContext); ...
Base
1
`export const devPagesDir = ${ctx.nuxt.options.dev ? JSON.stringify(ctx.nuxt.options.dir.pages) : 'null'}` ].join('\n\n') }
Base
1
return function viteServeStaticMiddleware(req, res, next) { // only serve the file if it's not an html request or ends with `/` // so that html requests can fallthrough to our html middleware for // special processing // also skip internal requests `/@fs/ /@vite-client` etc... const cleanedUrl = c...
Class
2
return function viteServeRawFsMiddleware(req, res, next) { const url = new URL(req.url!, 'http://example.com') // In some cases (e.g. linked monorepos) files outside of root will // reference assets that are also out of served root. In such cases // the paths are rewritten to `/@fs/` prefixed paths an...
Class
2
export function serveRawFsMiddleware( server: ViteDevServer, ): Connect.NextHandleFunction { const serveFromRoot = sirv( '/', sirvOptions({ headers: server.config.server.headers }), ) // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return function vite...
Class
2
getModel() { return { privateAttributes: [], attributes: { title: { type: 'text', private: false, }, }, primaryKey: 'id', options: {}, }; },
Class
2
getModel: jest.fn(() => { return { kind: 'singleType', privateAttributes: [] }; }), };
Class
2
getModel: jest.fn(() => { return { kind: 'singleType', privateAttributes: [] }; }),
Class
2
global.strapi = { config: createConfig() }; Object.assign(model, { privateAttributes: getPrivateAttributes(model) }); expect(isPrivateAttribute(model, 'foo')).toBeTruthy(); expect(isPrivateAttribute(model, 'bar')).toBeFalsy(); expect(isPrivateAttribute(model, 'foobar')).toBeTruthy(); ...
Class
2
Object.assign(model, { privateAttributes: getPrivateAttributes(model) }); expect(isPrivateAttribute(model, 'foo')).toBeTruthy(); expect(isPrivateAttribute(model, 'bar')).toBeFalsy(); expect(isPrivateAttribute(model, 'foobar')).toBeFalsy(); expect(strapi.config.get).toHaveBeenCalledWith('a...
Class
2
export const submitFloatingLink = <V extends Value>(editor: PlateEditor<V>) => { if (!editor.selection) return; const { isUrl, forceSubmit } = getPluginOptions<LinkPlugin, V>( editor, ELEMENT_LINK ); const url = floatingLinkSelectors.url(); const isValid = isUrl?.(url) || forceSubmit;
Base
1
isUrl?: (url: string) => boolean;
Base
1
match: { type: getPluginType(editor, ELEMENT_LINK) }, }); // anchor and focus in link -> insert text if (insertTextInLink && linkAbove) { // we don't want to insert marks in links editor.insertText(url); return true; } if (!isUrl?.(url)) return;
Base
1
export function escape(arg, options = {}) { const helpers = getPlatformHelpers(); const { flagProtection, interpolation, shellName } = parseOptions( { options, process }, helpers, ); const argAsString = checkedToString(arg); const escape = helpers.getEscapeFunction(shellName, { interpolation }); con...
Variant
0
export function quote(arg, options = {}) { const helpers = getPlatformHelpers(); const { flagProtection, shellName } = parseOptions( { options, process }, helpers, ); const argAsString = checkedToString(arg); const [escape, quote] = helpers.getQuoteFunction(shellName); const escapedArg = escape(argA...
Variant
0
export function resolveExecutable({ executable }, { exists, readlink, which }) { try { executable = which(executable); } catch (_) { // For backwards compatibility return the executable even if its location // cannot be obtained return executable; } if (!exists(executable)) { // For backwar...
Variant
0
export function parseOptions( { options: { flagProtection, interpolation, shell }, process: { env } }, { getDefaultShell, getShellName }, ) { flagProtection = flagProtection ? true : false; interpolation = interpolation ? true : false; shell = isString(shell) ? shell : getDefaultShell({ env }); const shell...
Variant
0
export function getShellName({ shell }, { resolveExecutable }) { shell = resolveExecutable( { executable: shell }, { exists: fs.existsSync, readlink: fs.readlinkSync, which: which.sync }, ); const shellName = path.basename(shell); if (getEscapeFunction(shellName, {}) === undefined) { return binBash...
Variant
0
function getPlatformFixtures() { if (common.isWindows) { return fixturesWindows; } else { return fixturesUnix; } }
Variant
0
export function* platformShells() { if (common.isWindows) { yield* common.shellsWindows; } else { yield* common.shellsUnix; } }
Variant
0
quote: Object.values(fixtures.quote[shell]).flat(), }; }
Variant
0
handler: function (grid, rowIndex) { let data = grid.getStore().getAt(rowIndex); pimcore.helpers.deleteConfirm(t('translation'), Ext.util.Format.htmlEncode(data.data.key), function () { grid.getStore().removeAt(rowIndex); ...
Base
1
const htmlPath = `${basePath}/${filename(mdFilePath)}.html`; // if (mdFilename !== 'sanitize_9.md') continue; const mdToHtmlOptions: any = { bodyOnly: true, }; if (mdFilename === 'checkbox_alternative.md') { mdToHtmlOptions.plugins = { checkbox: { checkboxRenderingType: 2, }, ...
Base
1
async updatePlanId(userId: number, planId: number) { const user = await User.findByPk(userId) if (!user) throw Errors.USER_NOT_FOUND if (userId === 6 && planId === 6) { throw Errors.HANDLED_BY_PAYMENT_PROVIDER } await User.update( { planId }, { where: { ...
Class
2
decryptTopicPage(data) { if (!data.currentRouteName?.startsWith("topic.")) { return; } if ( !this.container || this.container.isDestroyed || this.container.isDestroying ) { return; } const topicController = this.container.lookup("controller:topic"); const to...
Base
1
function inbox(ctx: Router.RouterContext) { let signature; try { signature = httpSignature.parseRequest(ctx.req, { 'headers': [] }); } catch (e) { ctx.status = 401; return; } processInbox(ctx.request.body, signature); ctx.status = 202; }
Class
2
function isActivityPubReq(ctx: Router.RouterContext) { ctx.response.vary('Accept'); const accepted = ctx.accepts('html', ACTIVITY_JSON, LD_JSON); return typeof accepted === 'string' && !accepted.match(/html/); }
Class
2
visibility: In(['public' as const, 'home' as const]), localOnly: false, }); if (note == null) { ctx.status = 404; return; } // リモートだったらリダイレクト if (note.userHost != null) { if (note.uri == null || isSelfHost(note.userHost)) { ctx.status = 500; return; } ctx.redirect(note.uri); return; } ct...
Class
2
host: IsNull(), }); if (user == null) { ctx.status = 404; return; } const keypair = await getUserKeypair(user.id); if (Users.isLocalUser(user)) { ctx.body = renderActivity(renderKey(user, keypair)); ctx.set('Cache-Control', 'public, max-age=180'); setResponseType(ctx); } else { ctx.status = 400; ...
Class
2
async function userInfo(ctx: Router.RouterContext, user: User | null) { if (user == null) { ctx.status = 404; return; } ctx.body = renderActivity(await renderPerson(user as ILocalUser)); ctx.set('Cache-Control', 'public, max-age=180'); setResponseType(ctx); }
Class
2
export function serializeObject(o: any): string { return Buffer.from(Cryo.stringify(o)).toString("base64") }
Base
1
export function serializeObject(o: any): string { return Buffer.from(Cryo.stringify(o)).toString("base64") }
Base
1
export function deserializeObject(s: string) { return Cryo.parse(Buffer.from(s, "base64")) }
Base
1
export function deserializeObject(s: string) { return Cryo.parse(Buffer.from(s, "base64")) }
Base
1
cert: fs.readFileSync(sslCert), passphrase: sslKeyPassphrase, }, this.app); } else { log.info("server", "Server Type: HTTP"); this.httpServer = http.createServer(this.app); } try { this.indexHTML = fs.readFileSync("...
Class
2
static getInstance(args) { if (UptimeKumaServer.instance == null) { UptimeKumaServer.instance = new UptimeKumaServer(args); } return UptimeKumaServer.instance; }
Compound
4
constructor(cfg) { super(); /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: ...
Class
2
export async function trackedFetch(url: RequestInfo, init?: RequestInit): Promise<Response> { const request = new Request(url, init) return await runInSpan( { op: 'fetch', description: `${request.method} ${request.url}`, }, async () => await fetch(url, init) )...
Base
1
export async function safeTrackedFetch(url: RequestInfo, init?: RequestInit): Promise<Response> { const request = new Request(url, init) return await runInSpan( { op: 'fetch', description: `${request.method} ${request.url}`, }, async () => { await rais...
Base
1
...(isTestEnv() ? { 'test-utils/write-to-file': writeToFile, } : {}), '@google-cloud/bigquery': bigquery, '@google-cloud/pubsub': pubsub, '@google-cloud/storage': gcs, '@posthog/plugin-contrib': contrib, '@posthog/pl...
Base
1
person_created_at: DateTime.fromISO(now).toUTC(), } as any) expect(fetch).toHaveBeenCalledWith('https://example.com/', { body: JSON.stringify( { hook: { id: 'id', e...
Base
1
person_created_at: DateTime.fromISO(now).toUTC(), } as any) expect(fetch).toHaveBeenCalledWith('https://example.com/', { body: JSON.stringify( { hook: { id: 'id', e...
Base
1
const protectRoute = (query, info) => { const savePopulate = protectPopulate(query, info); query.populate = savePopulate.populate; query.fields = savePopulate.fields; query.filters = protectFilters(query.filters, info); return query; };
Class
2
'Content-Length': Buffer.byteLength(body) } }, (resp) => { let data = ''; resp.on('data', (chunk) => { data += chunk; }); resp.on('end', () => { resolve(normaliseResponse(data)) }); }).on('error', (err) => { reject(err) }) req.write(bo...
Base
1
markClaimed: async function (inviteId = null, user) { const invite = await this.get(`id = ${inviteId}`); if (!invite) return { success: false, error: "Invite does not exist." }; if (invite.status !== "pending") return { success: false, error: "Invite is not in pending status." }; const db = awa...
Base
1
deactivate: async function (inviteId = null) { const invite = await this.get(`id = ${inviteId}`); if (!invite) return { success: false, error: "Invite does not exist." }; if (invite.status !== "pending") return { success: false, error: "Invite is not in pending status." }; const db = await this...
Base
1
update: async function (userId, updates = {}) { const user = await this.get(`id = ${userId}`); if (!user) return { success: false, error: "User does not exist." }; const { username, password, role, suspended = 0 } = updates; const toUpdate = { suspended }; if (user.username !== username && userna...
Base
1
new: async function (name = null, creatorId = null) { if (!name) return { result: null, message: "name cannot be null" }; var slug = slugify(name, { lower: true }); const existingBySlug = await this.get(`slug = '${slug}'`); if (existingBySlug !== null) { const slugSeed = Math.floor(10000000 + M...
Base
1
async function validApiKey(request, response, next) { const multiUserMode = await SystemSettings.isMultiUserMode(); response.locals.multiUserMode = multiUserMode; const auth = request.header("Authorization"); const bearerKey = auth ? auth.split(" ")[1] : null; if (!bearerKey) { response.status(403).json(...
Base
1
constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) { this.children = children || {} this.methods = [] this.name = '' if (method && handler) { const m: Record<string, HandlerSet<T>> = {} m[method] = { handler, params: {}, possibleKeys: [], score: 0, name: this.nam...
Base
1
constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) { this.children = children || {} this.methods = [] this.name = '' if (method && handler) { const m: Record<string, HandlerSet<T>> = {} m[method] = { handler, params: {}, possibleKeys: [], score: 0, name: this.nam...
Base
1
export const canCreateToken = (userScopes: string[], tokenScopes: string[]) => { return tokenScopes.every((scope) => userScopes.includes(scope)) }
Base
1
exports.handler = async ({ arguments: args }) => { if (!args) return respondWithError("Internal error while trying to execute lease task.", "Event arguments missing."); if (!args.action) return respondWithError("Internal error while trying to execute lease task.", "Parameter 'action' missing.");...
Pillar
3
exports.handler = async ({ arguments: args }) => { if (!args) return respondWithError("Internal error while trying to execute lease task.", "Event arguments missing."); if (!args.action) return respondWithError("Internal error while trying to execute lease task.", "Parameter 'action' missing.");...
Class
2
const AuthContainer = ({ children }) => { const dispatch = useDispatch(); const config = useSelector((state) => state.config) const { user, authStatus } = useAuthenticator((context) => [context.user, context.authStatus]); useEffect(() => { applyMode(Mode[config.DISPLAY_THEME]) applyDens...
Pillar
3
const AuthContainer = ({ children }) => { const dispatch = useDispatch(); const config = useSelector((state) => state.config) const { user, authStatus } = useAuthenticator((context) => [context.user, context.authStatus]); useEffect(() => { applyMode(Mode[config.DISPLAY_THEME]) applyDens...
Class
2
const clearEvent = () => { dispatch({ type: "event/dismiss" }); dispatch({ type: "notification/dismiss" }); setInputError({}); setValueChangedOnce(true); };
Pillar
3
const clearEvent = () => { dispatch({ type: "event/dismiss" }); dispatch({ type: "notification/dismiss" }); setInputError({}); setValueChangedOnce(true); };
Class
2
const submit = () => { dispatch({ type: "notification/dismiss" }); if (!validateInputs(value)) { return; } dispatch(fetchEndUserEvent(value)); };
Pillar
3
const submit = () => { dispatch({ type: "notification/dismiss" }); if (!validateInputs(value)) { return; } dispatch(fetchEndUserEvent(value)); };
Class
2
user: User.email, expiresOn: moment .unix(Event.item.eventOn) .add(Event.item.eventDays, "days") .add(Event....
Pillar
3
user: User.email, expiresOn: moment .unix(Event.item.eventOn) .add(Event.item.eventDays, "days") .add(Event....
Class
2
const updateFormValue = (update) => { setValue((prev) => { let newValue = { ...prev, ...update }; validateInputs(newValue, true); let user = newValue.user.replace(/[^a-zA-Z0-9]/g, Config.EVENT_EMAIL_SUBST); if (newValue.eventId !== "") newValu...
Pillar
3
const updateFormValue = (update) => { setValue((prev) => { let newValue = { ...prev, ...update }; validateInputs(newValue, true); let user = newValue.user.replace(/[^a-zA-Z0-9]/g, Config.EVENT_EMAIL_SUBST); if (newValue.eventId !== "") newValu...
Class
2
paramJson: JSON.stringify({ budgetAmount: parseInt(budgetAmount), expiresOn, principalId, budgetNotificationEmails, user, budgetCurrency: config.BUDGET_CURR...
Pillar
3
paramJson: JSON.stringify({ budgetAmount: parseInt(budgetAmount), expiresOn, principalId, budgetNotificationEmails, user, budgetCurrency: config.BUDGET_CURR...
Class
2
eventId: item.principalId.includes(action.config.EVENT_PRINCIPAL_SEPARATOR) ? item.principalId.substring(0, action.config.EVENT_ID_LENGTH) : "" });
Pillar
3
eventId: item.principalId.includes(action.config.EVENT_PRINCIPAL_SEPARATOR) ? item.principalId.substring(0, action.config.EVENT_ID_LENGTH) : "" });
Class
2
value: inputs.json ? value : value.join(inputs.separator), writeOutputFiles: inputs.writeOutputFiles, outputDir: inputs.outputDir, json: inputs.json, shouldEscape: inputs.escapeJson }) }
Class
2
}): Promise<void> => { let cleanedValue if (json) { cleanedValue = jsonOutput({value, shouldEscape}) } else { cleanedValue = value.toString().trim() } // if safeOutput is true, escape special characters for bash shell if (safeOutput) { cleanedValue = cleanedValue.replace(/[$()`|&;]/g, '\\$&') ...
Class
2
}): Promise<void> => { let cleanedValue if (json) { cleanedValue = jsonOutput({value, shouldEscape}) } else { cleanedValue = value.toString().trim() } // if safeOutput is true, escape special characters for bash shell if (safeOutput) { cleanedValue = cleanedValue.replace( /[^\x20-\x7E]|[:...
Class
2
origin(origin, callback) { if (!origin || origin === "null") { callback(null, true); return; } const { hostname } = new URL(origin); const appHostname = new URL(fastify.config.PUBLIC_APP_URL).hostname; if ( hostname === "localhost" || hostname.endsWit...
Class
2
origin(origin, callback) { if (!origin || origin === "null") { callback(null, true); return; } const { hostname } = new URL(origin); const appHostname = new URL(fastify.config.PUBLIC_APP_URL).hostname; if ( hostname === "localhost" || hostname.endsWit...
Base
1
origin(origin, callback) { if (!origin || origin === "null") { callback(null, true); return; } const { hostname } = new URL(origin); const appHostname = new URL(fastify.config.PUBLIC_APP_URL).hostname; if ( hostname === "localhost" || hostname.endsWit...
Base
1
const renderPage = async (reply: FastifyReply): Promise<void> => { return reply.view("index.html", { PUBLIC_APP_URL: fastify.config.PUBLIC_APP_URL, PUBLIC_API_URL: fastify.config.PUBLIC_API_URL, PUBLIC_COLLAB_URL: fastify.config.PUBLIC_COLLAB_URL, PUBLIC_ASSETS_URL: fastify.config.PUBLIC_A...
Class
2
const renderPage = async (reply: FastifyReply): Promise<void> => { return reply.view("index.html", { PUBLIC_APP_URL: fastify.config.PUBLIC_APP_URL, PUBLIC_API_URL: fastify.config.PUBLIC_API_URL, PUBLIC_COLLAB_URL: fastify.config.PUBLIC_COLLAB_URL, PUBLIC_ASSETS_URL: fastify.config.PUBLIC_A...
Base
1
const renderPage = async (reply: FastifyReply): Promise<void> => { return reply.view("index.html", { PUBLIC_APP_URL: fastify.config.PUBLIC_APP_URL, PUBLIC_API_URL: fastify.config.PUBLIC_API_URL, PUBLIC_COLLAB_URL: fastify.config.PUBLIC_COLLAB_URL, PUBLIC_ASSETS_URL: fastify.config.PUBLIC_A...
Base
1
private publishGitDataEvent = createEventPublisher<GitDataEvent>((workspaceId) => { return `gitData:${workspaceId}`; });
Class
2
private publishGitDataEvent = createEventPublisher<GitDataEvent>((workspaceId) => { return `gitData:${workspaceId}`; });
Base
1
private publishGitDataEvent = createEventPublisher<GitDataEvent>((workspaceId) => { return `gitData:${workspaceId}`; });
Base
1
async onAuthenticate(data) { const cookies = fastify.parseCookie(data.requestHeaders.cookie || ""); if (!cookies.accessToken) { throw unauthorized(); } const token = fastify.unsignCookie(cookies.accessToken || "")?.value || ""; if (!token) { throw unauthorized(); ...
Class
2
async onAuthenticate(data) { const cookies = fastify.parseCookie(data.requestHeaders.cookie || ""); if (!cookies.accessToken) { throw unauthorized(); } const token = fastify.unsignCookie(cookies.accessToken || "")?.value || ""; if (!token) { throw unauthorized(); ...
Base
1
async onAuthenticate(data) { const cookies = fastify.parseCookie(data.requestHeaders.cookie || ""); if (!cookies.accessToken) { throw unauthorized(); } const token = fastify.unsignCookie(cookies.accessToken || "")?.value || ""; if (!token) { throw unauthorized(); ...
Base
1
createContext({ req, res }: { req: FastifyRequest; res: FastifyReply }) { return createContext({ req, res }, fastify); }
Class
2
createContext({ req, res }: { req: FastifyRequest; res: FastifyReply }) { return createContext({ req, res }, fastify); }
Base
1
createContext({ req, res }: { req: FastifyRequest; res: FastifyReply }) { return createContext({ req, res }, fastify); }
Base
1
const loadParserPlugins = async (language: string): Promise<Plugin[] | null> => { switch (language as SupportedLanguages) { case "javascript": case "typescript": return [ await import("prettier/plugins/babel"), (await import("prettier/plugins/estree")) as Plugin ]; case "graphq...
Class
2
const loadParserPlugins = async (language: string): Promise<Plugin[] | null> => { switch (language as SupportedLanguages) { case "javascript": case "typescript": return [ await import("prettier/plugins/babel"), (await import("prettier/plugins/estree")) as Plugin ]; case "graphq...
Base
1
const loadParserPlugins = async (language: string): Promise<Plugin[] | null> => { switch (language as SupportedLanguages) { case "javascript": case "typescript": return [ await import("prettier/plugins/babel"), (await import("prettier/plugins/estree")) as Plugin ]; case "graphq...
Base
1
...(language === "json" && { trailingComma: "none", singleQuote: false }) }); } return code; };
Class
2
...(language === "json" && { trailingComma: "none", singleQuote: false }) }); } return code; };
Base
1
...(language === "json" && { trailingComma: "none", singleQuote: false }) }); } return code; };
Base
1
): ((query: string) => string[]) => { const languageIds = getLanguageIds(languages); const engine = searchEngine() || new MiniSearch({ fields: ["id"], searchOptions: { prefix: true } }); if (!searchEngine()) { engine.addAll(languageIds); setSearchEngine(engine); } ...
Class
2
): ((query: string) => string[]) => { const languageIds = getLanguageIds(languages); const engine = searchEngine() || new MiniSearch({ fields: ["id"], searchOptions: { prefix: true } }); if (!searchEngine()) { engine.addAll(languageIds); setSearchEngine(engine); } ...
Base
1
): ((query: string) => string[]) => { const languageIds = getLanguageIds(languages); const engine = searchEngine() || new MiniSearch({ fields: ["id"], searchOptions: { prefix: true } }); if (!searchEngine()) { engine.addAll(languageIds); setSearchEngine(engine); } ...
Base
1
command({ editor, range }) { return editor.chain().focus().deleteRange(range).setWrapper().run(); }
Class
2
command({ editor, range }) { return editor.chain().focus().deleteRange(range).setWrapper().run(); }
Base
1
command({ editor, range }) { return editor.chain().focus().deleteRange(range).setWrapper().run(); }
Base
1