repo_name stringlengths 2 55 | dataset stringclasses 1 value | owner stringlengths 3 31 | lang stringclasses 10 values | func_name stringlengths 1 104 | code stringlengths 20 96.7k | docstring stringlengths 1 4.92k | url stringlengths 94 241 | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
gluestack-ui | github_2023 | gluestack | typescript | initializePlayers | const initializePlayers = () => {
new window.YT.Player('player1', {
events: {
onStateChange: (event: any) => {
if (event.data === window.YT.PlayerState.PLAYING) {
const player2Frame = document.getElementById(
'player2'
) as HTMLIFrameElement;
player2Frame?.contentWindow?.postMessage(
'{"event":"command","func":"pauseVideo","args":""}',
'*'
);
}
},
},
});
new window.YT.Player('player2', {
events: {
onStateChange: (event: any) => {
if (event.data === window.YT.PlayerState.PLAYING) {
const player1Frame = document.getElementById(
'player1'
) as HTMLIFrameElement;
player1Frame?.contentWindow?.postMessage(
'{"event":"command","func":"pauseVideo","args":""}',
'*'
);
}
},
},
});
}; | // Initialize players when API is ready | https://github.com/gluestack/gluestack-ui/blob/cb33f5f04453642724cdde392c7bfaca132fc214/example/storybook-nativewind/src/extra-components/nativewind/VadimStream.tsx#L24-L56 | cb33f5f04453642724cdde392c7bfaca132fc214 |
edge-runtime | github_2023 | supabase | typescript | createAssertionError | function createAssertionError(
options: ExtendedAssertionErrorConstructorOptions,
): AssertionError {
const error = new AssertionError(options);
if (options.generatedMessage) {
error.generatedMessage = true;
}
return error;
} | // TODO(uki00a): This function is a workaround for setting the `generatedMessage` property flexibly. | https://github.com/supabase/edge-runtime/blob/89e59b0958cae6beb841038022e3afeee3e0f0bf/ext/node/polyfills/assert.ts#L48-L56 | 89e59b0958cae6beb841038022e3afeee3e0f0bf |
cirql | github_2023 | StarlaneStudios | typescript | RelateQueryWriter.parallel | parallel() {
return new RelateQueryWriter({
...this.#state,
parallel: true
});
} | /**
* Run the query in parallel
*
* @returns The query writer
*/ | https://github.com/StarlaneStudios/cirql/blob/cfecba42254fd2003a7cfb06c03306a041ca2b84/lib/writer/relate.ts#L195-L200 | cfecba42254fd2003a7cfb06c03306a041ca2b84 |
gluestack-style | github_2023 | gluestack | typescript | flatten | function flatten(obj: any, path: any = []) {
// Iterate over the object's keys
if (Array.isArray(obj)) {
flat[`${path.join('.')}`] = obj;
} else {
for (const key of Object.keys(obj)) {
// If the value is an object, recurse
if (key === 'ids' && path.length > 0) {
flat[`${path.join('.')}`] = obj[key];
} else if (key === 'props') {
flat[`${path.join('.')}.${key}`] = obj[key];
} else if (typeof obj[key] === 'object') {
flatten(obj[key], [...path, key]);
} else {
flat[`${path.join('.')}`] = obj[key];
}
}
}
} | // Recursive function to flatten the object | https://github.com/gluestack/gluestack-style/blob/3de2207b03d13894f7da9fa20c2ec4bf66760f2e/packages/react/src/styled.tsx#L62-L81 | 3de2207b03d13894f7da9fa20c2ec4bf66760f2e |
hc-tcg | github_2023 | hc-tcg | typescript | AttackModel.calculateDamage | public calculateDamage() {
return Math.max(
this.damage * this.damageMultiplier - this.damageReduction,
0,
)
} | /** Calculates the damage for this attack */ | https://github.com/hc-tcg/hc-tcg/blob/d19bc390c1f920a95a354b6e1573962e729577e9/common/models/attack-model.ts#L128-L133 | d19bc390c1f920a95a354b6e1573962e729577e9 |
hc-tcg | github_2023 | hc-tcg | typescript | parseUntil | function parseUntil(text: string, until: Array<string>): [string, string] {
// We take characters until we get to something that is probably a parser
let out = ''
let i = 0
let isEscaped = text[0] == '\\'
let nextChar: string | undefined = text[0]
while (true) {
if (!isEscaped) {
out += nextChar
}
i++
if (i >= text.length) {
break
}
nextChar = text.at(i)
if (nextChar == undefined) {
break
}
if (!isEscaped && until.includes(nextChar)) {
break
}
isEscaped = nextChar === '\\'
}
if (text[text.length - 1] == '\\') {
out += '\\'
}
return [out, text.slice(i)]
} | /* Parse the raw text that is part of a text mode or emoji node, handling escape sequences. */ | https://github.com/hc-tcg/hc-tcg/blob/d19bc390c1f920a95a354b6e1573962e729577e9/common/utils/formatting.ts#L404-L438 | d19bc390c1f920a95a354b6e1573962e729577e9 |
reka.js | github_2023 | prevwong | typescript | Reka.getNodeLocation | getNodeLocation(node: t.Type) {
return this.observer.getNodeLocation(node);
} | /**
* Get the nearest parent Node and its relative path of a given AST node in the State.
*/ | https://github.com/prevwong/reka.js/blob/ad337b15e172270f9bee4d7bf8bc99850eae83fd/packages/core/src/reka.ts#L357-L359 | ad337b15e172270f9bee4d7bf8bc99850eae83fd |
Digital-IDE | github_2023 | Digital-EDA | typescript | PrjManage.initOpeParam | public async initOpeParam(context: vscode.ExtensionContext): Promise<RefreshPrjConfig> {
const os = process.platform;
const extensionPath = hdlPath.toSlash(context.extensionPath);
const workspacePath = this.getWorkspacePath();
const propertyJsonPath = hdlPath.join(workspacePath, '.vscode', 'property.json');
const propertySchemaPath = hdlPath.join(extensionPath, 'project', 'property-schema.json');
const propertyInitPath = hdlPath.join(extensionPath, 'project', 'property-init.json');
opeParam.setBasicInfo(os,
extensionPath,
workspacePath,
propertyJsonPath,
propertySchemaPath,
propertyInitPath);
opeParam.prjInfo.initContextPath(extensionPath, workspacePath);
const refreshPrjConfig: RefreshPrjConfig = {mkdir: true};
if (fs.existsSync(propertyJsonPath)) {
const rawPrjInfo = hdlFile.readJSON(propertyJsonPath) as RawPrjInfo;
opeParam.mergePrjInfo(rawPrjInfo);
} else {
refreshPrjConfig.mkdir = false;
}
// 创建用户目录
hdlDir.mkdir(opeParam.dideHome);
// 同步部分文件
const cachePPySchema = hdlPath.join(opeParam.dideHome, 'property-schema.json');
const propertySchema = opeParam.propertySchemaPath;
if (fs.existsSync(cachePPySchema) && checkJson(cachePPySchema)) {
hdlFile.copyFile(cachePPySchema, propertySchema);
}
return refreshPrjConfig;
} | /**
* init opeParam
* @param context
*/ | https://github.com/Digital-EDA/Digital-IDE/blob/2f90a87a1c9df236ee621e586d8e56ac0e7aaa57/src/manager/prj.ts#L82-L116 | 2f90a87a1c9df236ee621e586d8e56ac0e7aaa57 |
Digital-IDE | github_2023 | Digital-EDA | typescript | HdlAction.updateLinter | async updateLinter(path: string) {
} | // 下一个版本丢弃,完全由后端承担这部分功能 | https://github.com/Digital-EDA/Digital-IDE/blob/2f90a87a1c9df236ee621e586d8e56ac0e7aaa57/src/monitor/hdl.ts#L157-L158 | 2f90a87a1c9df236ee621e586d8e56ac0e7aaa57 |
zupass | github_2023 | proofcarryingdata | typescript | IssuanceService.verifyKnownTicket | private async verifyKnownTicket(
client: PoolClient,
serializedPCD: SerializedPCD
): Promise<VerifyTicketResult> {
if (!serializedPCD.type) {
throw new Error("input was not a serialized PCD");
}
if (
serializedPCD.type !== EdDSATicketPCDPackage.name &&
serializedPCD.type !== ZKEdDSAEventTicketPCDPackage.name
) {
throw new Error(
`serialized PCD was wrong type, '${serializedPCD.type}' instead of '${EdDSATicketPCDPackage.name}' or '${ZKEdDSAEventTicketPCDPackage.name}'`
);
}
let eventId: string;
let productId: string;
let publicKey: EdDSAPublicKey;
if (serializedPCD.type === EdDSATicketPCDPackage.name) {
const pcd = await EdDSATicketPCDPackage.deserialize(serializedPCD.pcd);
if (!EdDSATicketPCDPackage.verify(pcd)) {
return {
success: true,
value: { verified: false, message: "Could not verify PCD." }
};
}
eventId = pcd.claim.ticket.eventId;
productId = pcd.claim.ticket.productId;
publicKey = pcd.proof.eddsaPCD.claim.publicKey;
} else {
const pcd = await ZKEdDSAEventTicketPCDPackage.deserialize(
serializedPCD.pcd
);
if (!ZKEdDSAEventTicketPCDPackage.verify(pcd)) {
return {
success: true,
value: { verified: false, message: "Could not verify PCD." }
};
}
if (
!(pcd.claim.partialTicket.eventId && pcd.claim.partialTicket.productId)
) {
return {
success: true,
value: {
verified: false,
message: "PCD does not reveal the correct fields."
}
};
}
// Watermarks can be up to four hours old
if (Date.now() - parseInt(pcd.claim.watermark) > ONE_HOUR_MS * 4) {
return {
success: true,
value: {
verified: false,
message: "PCD watermark has expired."
}
};
}
eventId = pcd.claim.partialTicket.eventId;
productId = pcd.claim.partialTicket.productId;
publicKey = pcd.claim.signer;
}
const knownTicketType = await fetchKnownTicketByEventAndProductId(
client,
eventId,
productId
);
// If we found a known ticket type, compare public keys
if (
knownTicketType &&
isEqualEdDSAPublicKey(JSON.parse(knownTicketType.public_key), publicKey)
) {
// We can say that the submitted ticket can be verified as belonging
// to a known group
return {
success: true,
value: {
verified: true,
publicKeyName: knownTicketType.known_public_key_name,
group: knownTicketType.ticket_group,
eventName: knownTicketType.event_name
}
};
} else {
return {
success: true,
value: {
verified: false,
message: "Not a recognized ticket"
}
};
}
} | /**
* Verifies a ticket based on:
* 1) verification of the PCD (that it is correctly formed, with a proof
* matching the claim)
* 2) whether the ticket matches the ticket types known to us, e.g. Zuzalu
* or Zuconnect tickets
*
*/ | https://github.com/proofcarryingdata/zupass/blob/b4757b45a8c4d09fe3d7cea06545a750fa94aeea/apps/passport-server/src/services/issuanceService.ts#L954-L1059 | b4757b45a8c4d09fe3d7cea06545a750fa94aeea |
zupass | github_2023 | proofcarryingdata | typescript | PipelineAPISubservice.handlePollFeed | public async handlePollFeed(
pipelineId: string,
req: PollFeedRequest
): Promise<PollFeedResponseValue> {
return traced(SERVICE_NAME, "handlePollFeed", async (span) => {
logger(LOG_TAG, `handlePollFeed`, pipelineId, str(req));
span?.setAttribute("feed_id", req.feedId);
const pipelineSlot =
await this.pipelineSubservice.ensurePipelineSlotExists(pipelineId);
tracePipeline(pipelineSlot.definition);
const pipeline =
await this.pipelineSubservice.ensurePipelineStarted(pipelineId);
const feed = ensureFeedIssuanceCapability(pipeline, req.feedId);
const feedResponse = await feed.issue(req);
traceFlattenedObject(span, {
result: {
actionCount: feedResponse.actions.length,
pcdCount: getPcdsFromActions(feedResponse.actions).length
}
});
return feedResponse;
});
} | /**
* Handles incoming requests that hit a Pipeline-specific feed for PCDs
* for every single pipeline that has this capability that this server manages.
*/ | https://github.com/proofcarryingdata/zupass/blob/b4757b45a8c4d09fe3d7cea06545a750fa94aeea/apps/passport-server/src/services/generic-issuance/subservices/PipelineAPISubservice.ts#L77-L99 | b4757b45a8c4d09fe3d7cea06545a750fa94aeea |
zupass | github_2023 | proofcarryingdata | typescript | ProtoPODGPC.findCircuit | public static findCircuit(
familyName: string,
circuitName: string,
circuitFamily: ProtoPODGPCCircuitDesc[] = ProtoPODGPC.CIRCUIT_FAMILY
): ProtoPODGPCCircuitDesc | undefined {
if (familyName && familyName !== PROTO_POD_GPC_FAMILY_NAME) {
return undefined;
}
for (const circuitDesc of circuitFamily) {
if (circuitName && circuitDesc.name === circuitName) {
return circuitDesc;
}
}
return undefined;
} | /**
* Finds the description of a circuit in this family by name.
*
* @param familyName the circuit family name
* @param circuitName the name of the circuit
* @param [circuitFamily=ProtoPODGPC.CIRCUIT_FAMILY] the circuit family to
* search
* @returns the circuit description, or undefined if the name is
* unrecognized.
*/ | https://github.com/proofcarryingdata/zupass/blob/b4757b45a8c4d09fe3d7cea06545a750fa94aeea/packages/lib/gpcircuits/src/proto-pod-gpc.ts#L604-L618 | b4757b45a8c4d09fe3d7cea06545a750fa94aeea |
zupass | github_2023 | proofcarryingdata | typescript | replacer | function replacer(key: unknown, value: unknown): unknown {
if (key === "message" && value instanceof Array) {
return value.map((num: bigint) => num.toString(16));
} else {
return value;
}
} | /**
* The replacer is used by `JSON.stringify` and, in this package, it is used within the
* PCD's `serialize` function. It is called for each property on the JSON object and
* converts the value of the property from a list of big integers to a list of hexadecimal
* strings when the property's key name equals "message".
* @param key The object property key.
* @param value The object property value.
* @returns The original value of the property or the converted one.
*/ | https://github.com/proofcarryingdata/zupass/blob/b4757b45a8c4d09fe3d7cea06545a750fa94aeea/packages/pcd/eddsa-pcd/src/EDDSAPCDPackage.ts#L99-L105 | b4757b45a8c4d09fe3d7cea06545a750fa94aeea |
convex-helpers | github_2023 | get-convex | typescript | DatabaseWriterWithTriggers._tableNameFromId | _tableNameFromId<TableName extends TableNamesInDataModel<DataModel>>(
id: GenericId<TableName>,
): TableName | null {
for (const tableName of Object.keys(this.triggers.registered)) {
if (
this.innerDb.normalizeId(
tableName as TableNamesInDataModel<DataModel>,
id,
)
) {
return tableName as TableName;
}
}
return null;
} | // Helper methods. | https://github.com/get-convex/convex-helpers/blob/efd7053350a0fb6d8db1a0ded7df5c3de188d114/packages/convex-helpers/server/triggers.ts#L224-L238 | efd7053350a0fb6d8db1a0ded7df5c3de188d114 |
hermes | github_2023 | hashicorp-forge | typescript | DashboardDocsAwaitingReviewComponent.firstFourDocs | private get firstFourDocs() {
return this.args.docs.slice(0, 4);
} | /**
* (Up to) the first four docs. The default documents shown.
*/ | https://github.com/hashicorp-forge/hermes/blob/ced8f53c5fb431215abc31f4c09222c2e2981c6f/web/app/components/dashboard/docs-awaiting-review.ts#L26-L28 | ced8f53c5fb431215abc31f4c09222c2e2981c6f |
hermes | github_2023 | hashicorp-forge | typescript | DocumentSidebarComponent.allApprovers | protected get allApprovers() {
return this.approverGroups.concat(this.approvers);
} | /**
* A computed property that returns all approvers and approverGroups.
* Passed to the EditableField component to render the list of approvers and groups.
* Recomputes when the approvers or approverGroups arrays change.
*/ | https://github.com/hashicorp-forge/hermes/blob/ced8f53c5fb431215abc31f4c09222c2e2981c6f/web/app/components/document/sidebar.ts#L463-L465 | ced8f53c5fb431215abc31f4c09222c2e2981c6f |
hermes | github_2023 | hashicorp-forge | typescript | DocumentSidebarRelatedResourcesComponent.titleTooltipText | protected get titleTooltipText(): string {
return `Documents and links that are relevant to this work.`;
} | /**
* The text passed to the TooltipIcon beside the title.
*/ | https://github.com/hashicorp-forge/hermes/blob/ced8f53c5fb431215abc31f4c09222c2e2981c6f/web/app/components/document/sidebar/related-resources.ts#L117-L119 | ced8f53c5fb431215abc31f4c09222c2e2981c6f |
hermes | github_2023 | hashicorp-forge | typescript | ProjectIndexComponent.jiraIsEnabled | protected get jiraIsEnabled() {
return !!this.configSvc.config.jira_url;
} | /**
* Whether Jira is configured for the project.
* Determines whether to show the Jira-related UI.
*/ | https://github.com/hashicorp-forge/hermes/blob/ced8f53c5fb431215abc31f4c09222c2e2981c6f/web/app/components/project/index.ts#L120-L122 | ced8f53c5fb431215abc31f4c09222c2e2981c6f |
hermes | github_2023 | hashicorp-forge | typescript | ProjectTileComponent.projectID | protected get projectID() {
if ("objectID" in this.args.project) {
return this.args.project.objectID;
} else {
return this.args.project.id;
}
} | /**
* The project ID used as our LinkTo model.
* If the project is an Algolia result, it has an `objectID`.
* If the project is retrieved from the back-end, it has an `id`.
*/ | https://github.com/hashicorp-forge/hermes/blob/ced8f53c5fb431215abc31f4c09222c2e2981c6f/web/app/components/project/tile.ts#L57-L63 | ced8f53c5fb431215abc31f4c09222c2e2981c6f |
x-crawl | github_2023 | coder-hxl | typescript | loaderAdvancedConfig | async function loaderAdvancedConfig() {
const testCrawlApp = createCrawl({
log: false,
baseUrl: 'http://localhost:8888'
})
const res = await testCrawlApp.crawlData({
targets: ['/data', '/data'],
proxy: { urls: ['http://localhost:7890'] },
timeout: 10000,
intervalTime: { max: 1000 },
maxRetry: 0
})
return res.reduce((prev, item) => prev && item.isSuccess, true)
} | // 2.2.Loader Advanced Config | https://github.com/coder-hxl/x-crawl/blob/5bea607d69c86da8c8f7b2e6b1dfa2078eb28952/test/automation/written/crawlData.test.ts#L74-L89 | 5bea607d69c86da8c8f7b2e6b1dfa2078eb28952 |
IQEngine | github_2023 | IQEngine | typescript | FFT._singleRealTransform2 | _singleRealTransform2(outOff, off, step) {
const out = this._out;
const data = this._data;
const evenR = data[off];
const oddR = data[off + step];
const leftR = evenR + oddR;
const rightR = evenR - oddR;
out[outOff] = leftR;
out[outOff + 1] = 0;
out[outOff + 2] = rightR;
out[outOff + 3] = 0;
} | // NOTE: Only called for len=4 | https://github.com/IQEngine/IQEngine/blob/dd0fc48dee0cdb69fe8350b7429e59ae198aea25/client/src/utils/fft.ts#L445-L459 | dd0fc48dee0cdb69fe8350b7429e59ae198aea25 |
zotero-citation | github_2023 | MuiseDestiny | typescript | Citation.listener | public async listener(t: number) {
let isExecCommand = false;
this.intervalID = window.setInterval(async () => {
if (!Zotero.ZoteroCitation) {
return this.clear();
}
if (!Zotero.Integration.currentSession || isExecCommand) {
return;
}
const sessions = Zotero.Integration.sessions;
const _sessions = this.sessions;
for (const sessionID in sessions) {
const session = sessions[sessionID];
let _session: SessionData;
if (!(session.agent as string).includes("Word")) {
continue;
}
// 初始化对象的session
if (sessionID in _sessions) {
_session = _sessions[sessionID];
} else {
_sessions[sessionID] = _session = { search: undefined, idData: {}, pending: true } as SessionData;
await this.initSearch(sessionID);
_session.pending = false;
}
// 其它线程search正在创建,则退出本次执行
if (_session.pending == true && !_session.search) {
return;
}
const citationsByItemID = session.citationsByItemID;
// 分析排序
const sortedItemIDs = this.getSortedItemIDs(session.citationsByIndex);
this.updateCitations(sessionID, citationsByItemID, sortedItemIDs, session.styleClass);
}
}, t);
window.addEventListener("close", (event) => {
event.preventDefault();
try {
this.clear();
} catch {
/* empty */
}
window.setTimeout(() => {
window.close();
});
});
const execCommand = Zotero.Integration.execCommand;
const _sessions = this.sessions;
// @ts-ignore ignore
Zotero.Integration.execCommand = async function (agent, command, docId) {
// eslint-disable-next-line prefer-rest-params
console.log(...arguments);
isExecCommand = true;
// eslint-disable-next-line prefer-rest-params
await execCommand(...arguments);
isExecCommand = false;
if (docId.endsWith("__doc__")) {
return;
}
const id = window.setInterval(async () => {
const sessionID = Zotero.Integration?.currentSession?.sessionID;
if (!sessionID) {
console.log("sessionID is null, waiting...");
return;
}
window.clearInterval(id);
console.log("clear interval");
let _session;
while (!((_session ??= _sessions[sessionID]) && _session.search)) {
await Zotero.Promise.delay(10);
}
console.log(_sessions);
// 判断是否为插件修改过的名称,如果是则更新
// 若为用户更改则不进行更新
if ([sessionID, _session.lastName].indexOf(_session.search.name) != -1) {
let targetName = docId
try {
targetName = PathUtils.split(docId).slice(-1)[0];
} catch { }
console.log(`${_session.search.name}->${targetName}`);
// 修复Mac储存
if (targetName && targetName.trim().length > 0) {
_session.search.name = _session.lastName = targetName;
await _session.search.saveTx({ skipSelect: true });
}
}
}, 0);
};
} | /**
* 监听session状态以生成搜索目录
*/ | https://github.com/MuiseDestiny/zotero-citation/blob/10c5330216fb3cb5de04f8a93be21fadad8cbfb3/src/modules/citation.ts#L67-L155 | 10c5330216fb3cb5de04f8a93be21fadad8cbfb3 |
qsharp | github_2023 | microsoft | typescript | _classicalRegister | const _classicalRegister = (
startX: number,
gateY: number,
endX: number,
wireY: number,
): SVGElement => {
const wirePadding = 1;
// Draw vertical lines
const vLine1: SVGElement = line(
startX + wirePadding,
gateY,
startX + wirePadding,
wireY - wirePadding,
"register-classical",
);
const vLine2: SVGElement = line(
startX - wirePadding,
gateY,
startX - wirePadding,
wireY + wirePadding,
"register-classical",
);
// Draw horizontal lines
const hLine1: SVGElement = line(
startX + wirePadding,
wireY - wirePadding,
endX,
wireY - wirePadding,
"register-classical",
);
const hLine2: SVGElement = line(
startX - wirePadding,
wireY + wirePadding,
endX,
wireY + wirePadding,
"register-classical",
);
return group([vLine1, vLine2, hLine1, hLine2]);
}; | /**
* Generates the SVG representation of a classical register.
*
* @param startX Start x coord.
* @param gateY y coord of measurement gate.
* @param endX End x coord.
* @param wireY y coord of wire.
*
* @returns SVG representation of the given classical register.
*/ | https://github.com/microsoft/qsharp/blob/902ec5f5f76c104051ac77bfd37c6784f660c489/npm/qsharp/ux/circuit-vis/formatters/registerFormatter.ts#L50-L90 | 902ec5f5f76c104051ac77bfd37c6784f660c489 |
jelly | github_2023 | cs-au-dk | typescript | FragmentState.maybeWidened | maybeWidened<T extends Token>(t: T): T | PackageObjectToken {
if (options.widening && t instanceof ObjectToken && this.widened.has(t))
return this.a.canonicalizeToken(new PackageObjectToken(t.getPackageInfo(), t.kind));
else
return t;
} | /**
* If the provided token is an object token that has been widened, the corresponding package object token is returned.
* Otherwise the provided token is returned as is.
*/ | https://github.com/cs-au-dk/jelly/blob/1e61ea69662fa1181b7190e0a48a7044265176c8/src/analysis/fragmentstate.ts#L839-L844 | 1e61ea69662fa1181b7190e0a48a7044265176c8 |
rooch | github_2023 | rooch-network | typescript | Ed25519Keypair.getSecretKey | getSecretKey(): string {
return encodeRoochSercetKey(
this.keypair.secretKey.slice(0, PRIVATE_KEY_SIZE),
this.getKeyScheme(),
)
} | /**
* The Bech32 secret key string for this Ed25519 keypair
*/ | https://github.com/rooch-network/rooch/blob/a044edde8edbe0f7ea75c66fe47c74e25d6f6b7d/sdk/typescript/rooch-sdk/src/keypairs/ed25519/keypair.ts#L128-L133 | a044edde8edbe0f7ea75c66fe47c74e25d6f6b7d |
rooch | github_2023 | rooch-network | typescript | Secp256k1PublicKey.flag | flag(): number {
return SIGNATURE_SCHEME_TO_FLAG['Secp256k1']
} | /**
* Return the Rooch address associated with this Secp256k1 public key
*/ | https://github.com/rooch-network/rooch/blob/a044edde8edbe0f7ea75c66fe47c74e25d6f6b7d/sdk/typescript/rooch-sdk/src/keypairs/secp256k1/publickey.ts#L74-L76 | a044edde8edbe0f7ea75c66fe47c74e25d6f6b7d |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | typescript | deserializeValue | function deserializeValue(value: any, options: EJSONOptions = {}) {
if (typeof value === 'number') {
// TODO(NODE-4377): EJSON js number handling diverges from BSON
const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
if (options.relaxed || options.legacy) {
return value;
}
if (Number.isInteger(value) && !Object.is(value, -0)) {
// interpret as being of the smallest BSON integer type that can represent the number exactly
if (in32BitRange) {
return new Int32(value);
}
if (in64BitRange) {
if (options.useBigInt64) {
// eslint-disable-next-line no-restricted-globals -- This is allowed here as useBigInt64=true
return BigInt(value);
}
return Long.fromNumber(value);
}
}
// If the number is a non-integer or out of integer range, should interpret as BSON Double.
return new Double(value);
}
// from here on out we're looking for bson types, so bail if its not an object
if (value == null || typeof value !== 'object') return value;
// upgrade deprecated undefined to null
if (value.$undefined) return null;
const keys = Object.keys(value).filter(
k => k.startsWith('$') && value[k] != null
) as (keyof typeof keysToCodecs)[];
for (let i = 0; i < keys.length; i++) {
const c = keysToCodecs[keys[i]];
if (c) return c.fromExtendedJSON(value, options);
}
if (value.$date != null) {
const d = value.$date;
const date = new Date();
if (options.legacy) {
if (typeof d === 'number') date.setTime(d);
else if (typeof d === 'string') date.setTime(Date.parse(d));
else if (typeof d === 'bigint') date.setTime(Number(d));
else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
} else {
if (typeof d === 'string') date.setTime(Date.parse(d));
else if (Long.isLong(d)) date.setTime(d.toNumber());
else if (typeof d === 'number' && options.relaxed) date.setTime(d);
else if (typeof d === 'bigint') date.setTime(Number(d));
else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
}
return date;
}
if (value.$code != null) {
const copy = Object.assign({}, value);
if (value.$scope) {
copy.$scope = deserializeValue(value.$scope);
}
return Code.fromExtendedJSON(value);
}
if (isDBRefLike(value) || value.$dbPointer) {
const v = value.$ref ? value : value.$dbPointer;
// we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
// because of the order JSON.parse goes through the document
if (v instanceof DBRef) return v;
const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
let valid = true;
dollarKeys.forEach(k => {
if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
});
// only make DBRef if $ keys are all valid
if (valid) return DBRef.fromExtendedJSON(v);
}
return value;
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/PROJECTS/AI-PROJECTS/DALLE-3-IMAGE-GENERATOR/backend/node_modules/bson/src/extended_json.ts#L87-L175 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | typescript | ClientSession.advanceOperationTime | advanceOperationTime(operationTime: Timestamp): void {
if (this.operationTime == null) {
this.operationTime = operationTime;
return;
}
if (operationTime.greaterThan(this.operationTime)) {
this.operationTime = operationTime;
}
} | /**
* Advances the operationTime for a ClientSession.
*
* @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/PROJECTS/AI-PROJECTS/DALLE-3-IMAGE-GENERATOR/backend/node_modules/mongodb/src/sessions.ts#L289-L298 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | typescript | List.last | last(): T | null {
// If the list is empty, value will be the head's null
return this.head.prev.value;
} | /** Returns the last item in the list, does not remove */ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/PROJECTS/AI-PROJECTS/DALLE-3-IMAGE-GENERATOR/backend/node_modules/mongodb/src/utils.ts#L835-L838 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
openobserve | github_2023 | openobserve | typescript | isFieldOnly | function isFieldOnly(node: any): boolean {
return node && node.type === "column_ref";
} | // Helper function to check if a node is a field-only reference (column_ref without literal) | https://github.com/openobserve/openobserve/blob/3bac86c507feca65726e1d301cab886f03194b10/web/src/composables/useLogs.ts#L4494-L4496 | 3bac86c507feca65726e1d301cab886f03194b10 |
openobserve | github_2023 | openobserve | typescript | onDrop | function onDrop(event:any ,offSet:any = {x:0,y:0}) {
if (
pipelineObj.hasInputNode &&
pipelineObj.draggedNode.io_type == "input"
) {
$q.notify({
message: "Only 1 source node is allowed",
color: "negative",
position: "bottom",
timeout: 2000,
});
return;
}
const position = screenToFlowCoordinate({
x: event.clientX + offSet.x,
y: event.clientY + offSet.y,
});
const nodeId = getUUID();
const newNode = {
id: nodeId,
type: pipelineObj.draggedNode.io_type || "default",
io_type: pipelineObj.draggedNode.io_type || "default",
position,
data: { label: nodeId, node_type: pipelineObj.draggedNode.subtype },
};
/**
* Align node position after drop, so it's centered to the mouse
*
* We can hook into events even in a callback, and we can remove the event listener after it's been called.
*/
const { off } = onNodesInitialized(() => {
updateNode(nodeId, (node) => ({
position: {
x: node.position.x - node.dimensions.width / 2,
y: node.position.y - node.dimensions.height / 2,
},
}));
off();
});
pipelineObj.currentSelectedNodeData = newNode;
pipelineObj.dialog.name = newNode.data.node_type;
pipelineObj.dialog.show = true;
pipelineObj.isEditNode = false;
} | /**
* Handles the drop event.
*
* @param {DragEvent} event
*/ | https://github.com/openobserve/openobserve/blob/3bac86c507feca65726e1d301cab886f03194b10/web/src/plugins/pipelines/useDnD.ts#L149-L199 | 3bac86c507feca65726e1d301cab886f03194b10 |
dara | github_2023 | causalens | typescript | parseConstraints | function parseConstraints(constraints?: EdgeConstraint[]): EdgeConstraint[] {
if (!constraints) {
return [];
}
return constraints.map((c) => {
const constraintType = c.type;
const { source, target } = c;
return {
...c,
source,
target,
type: constraintType,
};
});
} | /**
* Parse initially defined constraints.
* Reverses backward directed edges.
*
* @param constraints constraints to parse
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/dara-components/js/graphs/visual-edge-encoder.tsx#L67-L83 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | NavigateTo | const NavigateTo: ActionHandler<NavigateToImpl> = (ctx, actionImpl): void => {
const isValidUrl = isValidHttpUrl(actionImpl.url);
if (!isValidUrl) {
throw new Error(`Invalid URL: ${actionImpl.url}`);
}
if (actionImpl.new_tab) {
window.open(actionImpl.url, actionImpl.new_tab ? '_blank' : undefined);
} else {
ctx.history.push(actionImpl.url);
}
}; | /**
* Front-end handler for NavigateTo action.
* Navigates to a specified URL.
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/dara-core/js/actions/navigate-to.tsx#L29-L41 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | UpdateVariable | const UpdateVariable: ActionHandler<UpdateVariableImpl> = async (ctx, actionImpl) => {
let varAtom;
let eventName: 'PLAIN_VARIABLE_LOADED' | 'URL_VARIABLE_LOADED';
// Make sure the variable is registered
switch (actionImpl.variable.__typename) {
case 'Variable':
varAtom = getOrRegisterPlainVariable(actionImpl.variable, ctx.wsClient, ctx.taskCtx, ctx.extras);
eventName = 'PLAIN_VARIABLE_LOADED';
break;
case 'UrlVariable':
varAtom = getOrRegisterUrlVariable(actionImpl.variable);
eventName = 'URL_VARIABLE_LOADED';
break;
case 'DataVariable':
throw new Error('DataVariable is not supported in UpdateVariable action');
}
let newValue;
if (actionImpl.value === INPUT) {
newValue = ctx.input;
} else if (actionImpl.value === TOGGLE) {
// normally we'd use the updater form here, but we need to know what value we're
// toggling to emit the correct event, and the updater must be pure
const value = await ctx.snapshot.getLoadable(varAtom).toPromise();
newValue = !value;
} else {
newValue = actionImpl.value;
}
ctx.set(varAtom, newValue);
ctx.eventBus.publish(eventName, { variable: actionImpl.variable as any, value: newValue });
}; | /**
* Front-end handler for UpdateVariable action.
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/dara-core/js/actions/update-variable.tsx#L18-L51 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | cleanSessionCache | function cleanSessionCache(sessionToken: string): void {
for (const storage of [sessionStorage, localStorage]) {
const keys = Object.keys(storage);
keys.forEach((key) => {
// Remove keys related to a different Dara session
if (key.startsWith('dara-session') && !key.startsWith(`dara-session-${sessionToken}`)) {
storage.removeItem(key);
}
});
}
} | /**
* Clean up session storage cache.
* Purges sessionStorage persisted values which are related to a different session than the current one.
*
* @param sessionToken current session token
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/dara-core/js/shared/utils/clean-session-cache.tsx#L7-L18 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | Modal | function Modal(props: ModalProps): JSX.Element {
const [mounted, setMounted] = useState(false);
const [renderModal, setRenderModal] = useState(false);
// Internal state is updated using the useEffect to delay it to the next tick. This allows for the components css
// animations to work correctly
useEffect(() => {
setRenderModal(props.render);
}, [props.render]);
useEffect(() => {
if (renderModal) {
const keyHandler = (e: KeyboardEvent): void => {
if (e.key === Key.ESCAPE && props.onAttemptClose) {
props.onAttemptClose();
}
};
document.addEventListener('keydown', keyHandler);
return () => {
document.removeEventListener('keydown', keyHandler);
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [renderModal, props.onAttemptClose]);
if (!props.render && !mounted) {
return null;
}
const onTransitionEnd = (): void => {
setMounted(props.render);
if (!props.render && props.onClosed) {
props.onClosed();
}
};
const stopPropagation = (e: React.MouseEvent<HTMLDivElement>): void => {
e.stopPropagation();
};
return ReactDOM.createPortal(
<Background id={props.id} onClick={props.onAttemptClose} onTransitionEnd={onTransitionEnd} render={renderModal}>
<ModalWrapper
className={`cl-modal-content ${props.className ?? ''}`}
onClick={stopPropagation}
render={renderModal}
style={props.style}
>
{props.children}
</ModalWrapper>
</Background>,
document.body
);
} | /**
* A simple modal component, accepts children and a render property. It handles attaching the modal to the body of the
* document and transitioning it in and out of view as required
*
* @param {ModalProps} props - the component props
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/ui-components/src/modal/modal.tsx#L117-L170 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | EllipsisH | const EllipsisH = (props: IconProps): JSX.Element => {
return <StyledFAIcon icon={faEllipsisH} {...props} />;
}; | /**
* EllipsisH icon from FontAwesome
*
* @param {IconProps} props - the component props
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/ui-icons/src/ellipsis-h.tsx#L26-L28 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | Dizzy | const Dizzy = (props: IconProps): JSX.Element => {
return <StyledFAIcon icon={faDizzy} {...props} />;
}; | /**
* Dizzy icon from FontAwesome
*
* @param {IconProps} props - the component props
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/ui-icons/src/dizzy.tsx#L26-L28 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | HouseMedicalCircleExclamation | const HouseMedicalCircleExclamation = (props: IconProps): JSX.Element => {
return <StyledFAIcon icon={faHouseMedicalCircleExclamation} {...props} />;
}; | /**
* HouseMedicalCircleExclamation icon from FontAwesome
*
* @param {IconProps} props - the component props
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/ui-icons/src/house-medical-circle-exclamation.tsx#L26-L28 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | RoadSpikes | const RoadSpikes = (props: IconProps): JSX.Element => {
return <StyledFAIcon icon={faRoadSpikes} {...props} />;
}; | /**
* RoadSpikes icon from FontAwesome
*
* @param {IconProps} props - the component props
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/ui-icons/src/road-spikes.tsx#L26-L28 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | PersonCircleMinus | const PersonCircleMinus = (props: IconProps): JSX.Element => {
return <StyledFAIcon icon={faPersonCircleMinus} {...props} />;
}; | /**
* PersonCircleMinus icon from FontAwesome
*
* @param {IconProps} props - the component props
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/ui-icons/src/person-circle-minus.tsx#L26-L28 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | PlaneLock | const PlaneLock = (props: IconProps): JSX.Element => {
return <StyledFAIcon icon={faPlaneLock} {...props} />;
}; | /**
* PlaneLock icon from FontAwesome
*
* @param {IconProps} props - the component props
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/ui-icons/src/plane-lock.tsx#L26-L28 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | List | const List = (props: IconProps): JSX.Element => {
return <StyledFAIcon icon={faList} {...props} />;
}; | /**
* List icon from FontAwesome
*
* @param {IconProps} props - the component props
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/ui-icons/src/list.tsx#L26-L28 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
dara | github_2023 | causalens | typescript | UserSecret | const UserSecret = (props: IconProps): JSX.Element => {
return <StyledFAIcon icon={faUserSecret} {...props} />;
}; | /**
* UserSecret icon from FontAwesome
*
* @param {IconProps} props - the component props
*/ | https://github.com/causalens/dara/blob/8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9/packages/ui-icons/src/user-secret.tsx#L26-L28 | 8769b0ad0ff467a75ebaf5bb872a7d6d48a629f9 |
quark-core | github_2023 | hellof2e | typescript | QuarkElement.update | update() {
this.getOrInitRenderWatcher().update()
} | // Reserve, may expand in the future | https://github.com/hellof2e/quark-core/blob/3128425ec427f16344ff236c5f74adcfc24de2c7/packages/core/src/main.ts#L533-L535 | 3128425ec427f16344ff236c5f74adcfc24de2c7 |
glass-easel | github_2023 | wechat-miniprogram | typescript | Element.removeAttribute | removeAttribute(name: string) {
if (this._$nodeAttributes) {
delete this._$nodeAttributes[name]
}
const be = this._$backendElement
if (be) {
if (ENV.DEV) performanceMeasureStart('backend.removeAttribute')
be.removeAttribute(name)
if (ENV.DEV) performanceMeasureEnd()
}
if (this._$mutationObserverTarget) {
MutationObserverTarget.callAttrObservers(this, {
type: 'properties',
target: this,
nameType: 'attribute',
attributeName: name,
})
}
} | /** Remove an attribute */ | https://github.com/wechat-miniprogram/glass-easel/blob/7e6976956d5fff398ad93c09b2074a59c01191b8/glass-easel/src/element.ts#L2499-L2517 | 7e6976956d5fff398ad93c09b2074a59c01191b8 |
kui.nvim | github_2023 | romgrk | typescript | shortenNumber | const shortenNumber = (number: number): string | number => {
if (number > 0 && number < 1) return number.toString().replace("0.", ".");
return number;
}; | // Removes leading zero before floating point if necessary | https://github.com/romgrk/kui.nvim/blob/b3b2f53d6678dce86acc91043b32eab6059ce0cf/src/colord/plugins/minify.ts#L60-L63 | b3b2f53d6678dce86acc91043b32eab6059ce0cf |
kui.nvim | github_2023 | romgrk | typescript | Graphics.clear | public clear(): this
{
this._geometry.clear();
this._lineStyle.reset();
this._fillStyle.reset();
this._boundsID++;
this._matrix = null;
this._holeMode = false;
this.currentPath = null;
return this;
} | /**
* Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
* @returns - This Graphics object. Good for chaining method calls
*/ | https://github.com/romgrk/kui.nvim/blob/b3b2f53d6678dce86acc91043b32eab6059ce0cf/src/graphics/Graphics.ts#L811-L823 | b3b2f53d6678dce86acc91043b32eab6059ce0cf |
kui.nvim | github_2023 | romgrk | typescript | Rectangle.ceil | ceil(resolution = 1, eps = 0.001): this
{
const x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution;
const y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution;
this.x = Math.floor((this.x + eps) * resolution) / resolution;
this.y = Math.floor((this.y + eps) * resolution) / resolution;
this.width = x2 - this.x;
this.height = y2 - this.y;
return this;
} | /**
* Enlarges rectangle that way its corners lie on grid
* @param resolution - resolution
* @param eps - precision
* @returns Returns itself.
*/ | https://github.com/romgrk/kui.nvim/blob/b3b2f53d6678dce86acc91043b32eab6059ce0cf/src/math/shapes/Rectangle.ts#L289-L301 | b3b2f53d6678dce86acc91043b32eab6059ce0cf |
Zukeeper | github_2023 | oslabs-beta | typescript | hierarchyConv | function hierarchyConv(state) {
const parent = {
name: "root",
children: [],
};
function addNodeToTree(key, value, parent) {
if (Array.isArray(value) && value.length > 0) {
const node = { name: key, children: [] };
parent.children.push(node);
value.forEach((item, index) => {
addNodeToTree(`[${index}]`, item, node);
});
} else if (typeof value === "object" && Object.keys(value).length > 0) {
const node = { name: key, children: [] };
parent.children.push(node);
Object.entries(value).forEach(([key, val]) => {
addNodeToTree(key, val, node);
});
} else {
if (typeof value === "object") {
const node = { name: key, attributes: { value: "empty" } };
parent.children.push(node);
} else {
const node = { name: key, attributes: { value } };
parent.children.push(node);
}
}
}
addNodeToTree("state", state, parent);
return parent.children[0];
} | /*
hierarchyConv takes in the state to display in the visualization tree,
and converts it to a format readable by D3.
const example = {
name: 'State',
children: [
{
name: 'member1',
attributes: {
value: 'org1',
},
},
{
name: 'member2',
children: [
name: 'member3',
attributes: {
value: 'org2'
}
]
}
]
}
*/ | https://github.com/oslabs-beta/Zukeeper/blob/b6cca3edfcc65951d40e93878f046b848c2bdbe7/src/client/algorithms/hierarchyConv.ts#L27-L59 | b6cca3edfcc65951d40e93878f046b848c2bdbe7 |
ZyPlayer | github_2023 | Hiram-Wong | typescript | parseQueryString | function parseQueryString(query) {
const params = {};
query.split('&').forEach(function (part) {
// 使用正则表达式匹配键和值,直到遇到第一个等号为止
const regex = /^(.*?)=(.*)/;
const match = part.match(regex);
if (match) {
const key = decodeURIComponent(match[1]);
const value = decodeURIComponent(match[2]);
params[key] = value;
}
});
return params;
} | //字符串To对象 | https://github.com/Hiram-Wong/ZyPlayer/blob/0829adc234aa344d07c518aa8873b75765eb87df/src/main/core/server/routes/v1/site/cms/adapter/drpy/drpy3.ts#L1921-L1934 | 0829adc234aa344d07c518aa8873b75765eb87df |
mono | github_2023 | rocicorp | typescript | Replicache.clientGroupID | get clientGroupID(): Promise<string> {
return this.#impl.clientGroupID;
} | /**
* The client group ID for this instance of Replicache. Instances of
* Replicache will have the same client group ID if and only if they have
* the same name, mutators, indexes, schema version, format version, and
* browser profile.
*/ | https://github.com/rocicorp/mono/blob/c81e8ff6903fe24165cee02cce7c79629cdc70e4/packages/replicache/src/replicache.ts#L281-L283 | c81e8ff6903fe24165cee02cce7c79629cdc70e4 |
if | github_2023 | Green-Software-Foundation | typescript | filterOutput | const filterOutput = (
dataFromCSV: any,
output: string | string[] | string[][]
) => {
if (output === '*') {
return nanifyEmptyValues(dataFromCSV);
}
if (Array.isArray(output)) {
/** Check if it's a multidimensional array. */
if (Array.isArray(output[0])) {
const result: any = {};
output.forEach(outputField => {
/** Check if there is no renaming request, then export as is */
const outputTitle = outputField[1] || outputField[0];
result[outputTitle] = fieldAccessor(outputField[0], dataFromCSV);
});
return result;
}
const outputTitle = output[1] || output[0];
return {
[outputTitle as string]: fieldAccessor(output[0], dataFromCSV),
};
}
return {
[output]: fieldAccessor(output, dataFromCSV),
};
}; | /**
* 1. If output is anything, then removes query data from csv record to escape duplicates.
* 2. Otherwise checks if it's a miltidimensional array, then grabs multiple fields ().
* 3. If not, then returns single field.
* 4. In case if it's string, then
*/ | https://github.com/Green-Software-Foundation/if/blob/a202ce71dc4d970b98e090d7714677734112be5c/src/if-run/builtins/csv-import/index.ts#L61-L93 | a202ce71dc4d970b98e090d7714677734112be5c |
if | github_2023 | Green-Software-Foundation | typescript | computeNode | const computeNode = async (node: Node, params: ComputeParams): Promise<any> => {
const pipeline = node.pipeline || (params.pipeline as PhasedPipeline);
const config = node.config || params.config;
const defaults = node.defaults || params.defaults;
const noFlags = !params.observe && !params.regroup && !params.compute;
debugLogger.setExecutingPluginName();
warnIfConfigProvided(node);
if (node.children) {
return traverse(node.children, {
...params,
pipeline,
defaults,
config,
});
}
let outputStorage = structuredClone(node.inputs) as PluginParams[];
outputStorage = mergeDefaults(outputStorage, defaults);
const pipelineCopy = structuredClone(pipeline) || {};
/** Checks if pipeline is not an array or empty object. */
if (
Array.isArray(pipelineCopy) ||
(typeof pipelineCopy === 'object' &&
pipelineCopy !== null &&
Object.keys(pipelineCopy).length === 0)
) {
logger.warn(EMPTY_PIPELINE);
}
/**
* If iteration is on observe pipeline, then executes observe plugins and sets the inputs value.
*/
if ((noFlags || params.observe) && pipelineCopy.observe) {
while (pipelineCopy.observe.length !== 0) {
const pluginName = pipelineCopy.observe.shift() as string;
console.debug(OBSERVING(pluginName));
debugLogger.setExecutingPluginName(pluginName);
const plugin = params.pluginStorage.get(pluginName);
const nodeConfig = config && config[pluginName];
outputStorage = await plugin.execute(outputStorage, nodeConfig);
node.inputs = outputStorage;
if (params.context.explainer) {
addExplainData({
pluginName,
metadata: plugin.metadata,
});
}
}
}
/**
* If regroup is requested, execute regroup strategy, delete child's inputs, outputs and empty regroup array.
*/
if ((noFlags || params.regroup) && pipelineCopy.regroup) {
const originalOutputs = params.append ? node.outputs || [] : [];
if (!isRegrouped(pipelineCopy.regroup, outputStorage, childNames)) {
node.children = Regroup(
outputStorage,
originalOutputs,
pipelineCopy.regroup
);
delete node.inputs;
delete node.outputs;
debugLogger.setExecutingPluginName();
console.debug(REGROUPING);
return traverse(node.children, {
...params,
pipeline: {
...pipelineCopy,
regroup: undefined,
},
defaults,
config,
});
} else {
console.debug(SKIPPING_REGROUP);
}
}
console.debug('\n');
/**
* If iteration is on compute plugin, then executes compute plugins and sets the outputs value.
*/
if ((noFlags || params.compute) && pipelineCopy.compute) {
const originalOutputs = params.append ? node.outputs || [] : [];
while (pipelineCopy.compute.length !== 0) {
const pluginName = pipelineCopy.compute.shift() as string;
const plugin = params.pluginStorage.get(pluginName);
const nodeConfig = config && config[pluginName];
console.debug(COMPUTING_PIPELINE_FOR_NODE(pluginName));
debugLogger.setExecutingPluginName(pluginName);
outputStorage = await plugin.execute(outputStorage, nodeConfig);
debugLogger.setExecutingPluginName();
node.outputs = outputStorage;
if (params.context.explainer) {
addExplainData({
pluginName,
metadata: plugin.metadata,
});
}
}
if (params.append) {
node.outputs = originalOutputs.concat(node.outputs || []);
}
}
console.debug('\n');
}; | /**
* 1. If the node has it's own pipeline, defaults or config then use that,
* otherwise use whatever has been passed down from further up the tree.
* 2. If it's a grouping node, then first of all computes all it's children.
* This is doing a depth first traversal.
* 3. Otherwise merges the defaults into the inputs.
* 4. Iterates over pipeline phases (observe, regroup, compute).
* 5. Observe plugins are used to insert input values
* (isolated execution can be achived by passing `--observe` flag to CLI command).
* 6. Regroup plugin is used to group existing inputs by criteria
* (isolated execution can be achived by passing `--regroup` flag to CLI command).
* Since it creates new children for node, existing inputs and outputs are dropped and recursive traversal is called
* for newbord child component.
* 7. Compute plugins are used to do desired computations and appending the result to outputs
* (isolated execution can be achived by passing `--compute` flag to CLI command).
*/ | https://github.com/Green-Software-Foundation/if/blob/a202ce71dc4d970b98e090d7714677734112be5c/src/if-run/lib/compute.ts#L88-L213 | a202ce71dc4d970b98e090d7714677734112be5c |
obsidian-callout-manager | github_2023 | eth-p | typescript | BitPositionRegistry.claim | public claim(): BitPosition {
const { recycled } = this;
// Claim the next bit.
const claimed = (recycled.length > 0) ? recycled.pop() : (this.next++);
// Update the field.
this.asField = BitField.or(this.asField, BitField.fromPosition(claimed as BitPosition));
return claimed as BitPosition;
} | /**
* Claims a bit from the registry.
*/ | https://github.com/eth-p/obsidian-callout-manager/blob/d425fd450cd06bb776bd04826e5c97d7ffad5407/src/search/bitfield.ts#L125-L134 | d425fd450cd06bb776bd04826e5c97d7ffad5407 |
LibreChat | github_2023 | danny-avila | typescript | getFileStats | async function getFileStats(filePath: string): Promise<FileInfo> {
const stats = await fs.stat(filePath);
return {
size: stats.size,
created: stats.birthtime,
modified: stats.mtime,
accessed: stats.atime,
isDirectory: stats.isDirectory(),
isFile: stats.isFile(),
permissions: stats.mode.toString(8).slice(-3),
};
} | // Tool implementations | https://github.com/danny-avila/LibreChat/blob/52a6de2aa756564ffe12114ebfce0e7f93ea125c/packages/mcp/src/examples/filesystem.ts#L195-L206 | 52a6de2aa756564ffe12114ebfce0e7f93ea125c |
tevm-monorepo | github_2023 | evmts | typescript | BlockHeader.cliqueEpochTransitionSigners | cliqueEpochTransitionSigners(): EthjsAddress[] {
this._requireClique('cliqueEpochTransitionSigners')
if (!this.cliqueIsEpochTransition()) {
const msg = this._errorMsg('Signers are only included in epoch transition blocks (clique)')
throw new Error(msg)
}
const start = CLIQUE_EXTRA_VANITY
const end = this.extraData.length - CLIQUE_EXTRA_SEAL
const signerBytes = this.extraData.subarray(start, end)
const signerList: Uint8Array[] = []
const signerLength = 20
for (let start = 0; start <= signerBytes.length - signerLength; start += signerLength) {
signerList.push(signerBytes.subarray(start, start + signerLength))
}
return signerList.map((buf) => new EthjsAddress(buf))
} | /**
* Returns a list of signers
* (only clique PoA, throws otherwise)
*
* This function throws if not called on an epoch
* transition block and should therefore be used
* in conjunction with {@link BlockHeader.cliqueIsEpochTransition}
*/ | https://github.com/evmts/tevm-monorepo/blob/5b069dac6d3daa99146ce12f749c407f4519d0e2/packages/block/src/header.ts#L823-L840 | 5b069dac6d3daa99146ce12f749c407f4519d0e2 |
tonkeeper-web | github_2023 | tonkeeper | typescript | EmulationApi.emulateMessageToAccountEvent | async emulateMessageToAccountEvent(requestParameters: EmulateMessageToAccountEventRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<AccountEvent> {
const response = await this.emulateMessageToAccountEventRaw(requestParameters, initOverrides);
return await response.value();
} | /**
* Emulate sending message to blockchain
*/ | https://github.com/tonkeeper/tonkeeper-web/blob/c8b92adbbdf6124fac1d83d30ab0376e9a6aad76/packages/core/src/tonApiV2/apis/EmulationApi.ts#L243-L246 | c8b92adbbdf6124fac1d83d30ab0376e9a6aad76 |
tonkeeper-web | github_2023 | tonkeeper | typescript | EmulationApi.emulateMessageToTrace | async emulateMessageToTrace(requestParameters: EmulateMessageToTraceRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Trace> {
const response = await this.emulateMessageToTraceRaw(requestParameters, initOverrides);
return await response.value();
} | /**
* Emulate sending message to blockchain
*/ | https://github.com/tonkeeper/tonkeeper-web/blob/c8b92adbbdf6124fac1d83d30ab0376e9a6aad76/packages/core/src/tonApiV2/apis/EmulationApi.ts#L327-L330 | c8b92adbbdf6124fac1d83d30ab0376e9a6aad76 |
tonkeeper-web | github_2023 | tonkeeper | typescript | StakingApi.getAccountNominatorsPoolsRaw | async getAccountNominatorsPoolsRaw(requestParameters: GetAccountNominatorsPoolsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<AccountStaking>> {
if (requestParameters['accountId'] == null) {
throw new runtime.RequiredError(
'accountId',
'Required parameter "accountId" was null or undefined when calling getAccountNominatorsPools().'
);
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
const response = await this.request({
path: `/v2/staking/nominator/{account_id}/pools`.replace(`{${"account_id"}}`, encodeURIComponent(String(requestParameters['accountId']))),
method: 'GET',
headers: headerParameters,
query: queryParameters,
}, initOverrides);
return new runtime.JSONApiResponse(response, (jsonValue) => AccountStakingFromJSON(jsonValue));
} | /**
* All pools where account participates
*/ | https://github.com/tonkeeper/tonkeeper-web/blob/c8b92adbbdf6124fac1d83d30ab0376e9a6aad76/packages/core/src/tonApiV2/apis/StakingApi.ts#L129-L149 | c8b92adbbdf6124fac1d83d30ab0376e9a6aad76 |
tonkeeper-web | github_2023 | tonkeeper | typescript | StatsServiceService.sendQueryToStats | public static sendQueryToStats(
chain?: Chain,
requestBody?: {
project_id: number;
name?: string;
query?: string;
gpt_message?: string;
/**
* cyclic execution of requests
*/
repeat_interval?: number;
},
): CancelablePromise<StatsQueryResult> {
return __request(OpenAPI, {
method: 'POST',
url: '/api/v1/services/stats/query',
query: {
'chain': chain,
},
body: requestBody,
mediaType: 'application/json',
errors: {
400: `Something went wrong on client side`,
403: `Access token is missing or invalid`,
404: `The specified resource was not found`,
500: `Something went wrong on server side`,
},
});
} | /**
* Send query to stats service
* @param chain chain
* @param requestBody Data that is expected
* @returns StatsQueryResult Query result
* @throws ApiError
*/ | https://github.com/tonkeeper/tonkeeper-web/blob/c8b92adbbdf6124fac1d83d30ab0376e9a6aad76/packages/core/src/tonConsoleApi/services/StatsServiceService.ts#L81-L109 | c8b92adbbdf6124fac1d83d30ab0376e9a6aad76 |
ngx-layout | github_2023 | ngbracket | typescript | ServerMediaQueryList.destroy | destroy() {
this.deactivate();
this._listeners = [];
} | /**
* Destroy the current list by deactivating the
* listeners and clearing the internal list
*/ | https://github.com/ngbracket/ngx-layout/blob/525147da88c960f36c959044084cae25efe55b2e/projects/libs/flex-layout/server/server-match-media.ts#L45-L48 | 525147da88c960f36c959044084cae25efe55b2e |
obsidian-tasks-calendar-wrapper | github_2023 | Leonezz | typescript | Link.withHeader | public withHeader(header: string) {
return Link.header(this.path, header, this.embed, this.display);
} | /** Convert a file link into a link to a specific header. */ | https://github.com/Leonezz/obsidian-tasks-calendar-wrapper/blob/1242f358c95a7b90da74b325e4651a198d9cb1d8/dataview-util/markdown.ts#L128-L130 | 1242f358c95a7b90da74b325e4651a198d9cb1d8 |
circomkit | github_2023 | erhant | typescript | WitnessTester.expectConstraintCount | async expectConstraintCount(expected: number, exact?: boolean) {
const count = await this.getConstraintCount();
if (count < expected) {
throw new AssertionError({
message: 'Circuit is under-constrained',
expected,
actual: count,
});
}
if (exact && count !== expected) {
throw new AssertionError({
message: 'Circuit is over-constrained',
expected,
actual: count,
});
}
} | /** Asserts that the circuit has enough constraints.
*
* By default, this function checks if there **at least** `expected` many constraints in the circuit.
* If `exact` option is set to `true`, it will also check if the number of constraints is exactly equal to
* the `expected` amount.
*
* If first check fails, it means the circuit is under-constrained. If the second check fails, it means
* the circuit is over-constrained.
*/ | https://github.com/erhant/circomkit/blob/b1a8ba682adf6d866ade2d53e3636f13a1d7403f/src/testers/witnessTester.ts#L65-L82 | b1a8ba682adf6d866ade2d53e3636f13a1d7403f |
deep-chat | github_2023 | OvidijusParsiunas | typescript | TextInputEvents.onKeyDown | private static onKeyDown(characterLimit: number, event: KeyboardEvent) {
const inputElement = event.target as HTMLElement;
const textContent = inputElement.textContent;
if (textContent && textContent.length >= characterLimit
&& !TextInputEvents.PERMITTED_KEYS.has(event.key) && !TextInputEvents.isKeyCombinationPermitted(event)) {
event.preventDefault();
}
} | // prettier-ignore | https://github.com/OvidijusParsiunas/deep-chat/blob/80c7386ddb94ba0dacfbd256a2f865cab1628264/component/src/views/chat/input/textInput/textInputEvents.ts#L28-L35 | 80c7386ddb94ba0dacfbd256a2f865cab1628264 |
aztec-packages | github_2023 | AztecProtocol | typescript | LMDBMultiMap.set | set(key: K, val: V): Promise<void> {
return execInWriteTx(this.store, tx => tx.setIndex(serializeKey(this.prefix, key), this.encoder.pack(val)));
} | /**
* Sets the value at the given key.
* @param key - The key to set the value at
* @param val - The value to set
*/ | https://github.com/AztecProtocol/aztec-packages/blob/f418456a84b9387a9d7bf76026a60b7a0f747149/yarn-project/kv-store/src/lmdb-v2/map.ts#L128-L130 | f418456a84b9387a9d7bf76026a60b7a0f747149 |
aztec-packages | github_2023 | AztecProtocol | typescript | AztecLmdbStore.openMultiMap | openMultiMap<K extends Key, V>(name: string): AztecMultiMap<K, V> & AztecAsyncMultiMap<K, V> {
return new LmdbAztecMap(this.#multiMapData, name);
} | /**
* Creates a new AztecMultiMap in the store. A multi-map stores multiple values for a single key automatically.
* @param name - Name of the map
* @returns A new AztecMultiMap
*/ | https://github.com/AztecProtocol/aztec-packages/blob/f418456a84b9387a9d7bf76026a60b7a0f747149/yarn-project/kv-store/src/lmdb/store.ts#L121-L123 | f418456a84b9387a9d7bf76026a60b7a0f747149 |
aztec-packages | github_2023 | AztecProtocol | typescript | StandardIndexedTree.getLatestLeafPreimageCopy | public getLatestLeafPreimageCopy(index: bigint, includeUncommitted: boolean): IndexedTreeLeafPreimage | undefined {
const preimage = !includeUncommitted
? this.getDbPreimage(index)
: this.getCachedPreimage(index) ?? this.getDbPreimage(index);
return preimage && this.leafPreimageFactory.clone(preimage);
} | /**
* Gets the latest LeafPreimage copy.
* @param index - Index of the leaf of which to obtain the LeafPreimage copy.
* @param includeUncommitted - If true, the uncommitted changes are included in the search.
* @returns A copy of the leaf preimage at the given index or undefined if the leaf was not found.
*/ | https://github.com/AztecProtocol/aztec-packages/blob/f418456a84b9387a9d7bf76026a60b7a0f747149/yarn-project/merkle-tree/src/standard_indexed_tree/standard_indexed_tree.ts#L217-L222 | f418456a84b9387a9d7bf76026a60b7a0f747149 |
aztec-packages | github_2023 | AztecProtocol | typescript | ProvingOrchestrator.getBlock | public getBlock(index: number): L2Block {
const block = this.provingState?.blocks[index]?.block;
if (!block) {
throw new Error(`Block at index ${index} not available`);
}
return block;
} | /** Returns the block as built for a given index. */ | https://github.com/AztecProtocol/aztec-packages/blob/f418456a84b9387a9d7bf76026a60b7a0f747149/yarn-project/prover-client/src/orchestrator/orchestrator.ts#L288-L294 | f418456a84b9387a9d7bf76026a60b7a0f747149 |
aztec-packages | github_2023 | AztecProtocol | typescript | ContractDataOracle.getFunctionArtifactByName | public async getFunctionArtifactByName(
contractAddress: AztecAddress,
functionName: string,
): Promise<FunctionArtifact | undefined> {
const tree = await this.getTreeForAddress(contractAddress);
return tree.getArtifact().functions.find(f => f.name === functionName);
} | /**
* Retrieves the artifact of a specified function within a given contract.
* The function is identified by its name, which is unique within a contract.
* Throws if the contract has not been added to the database.
*
* @param contractAddress - The AztecAddress representing the contract containing the function.
* @param functionName - The name of the function.
* @returns The corresponding function's artifact as an object
*/ | https://github.com/AztecProtocol/aztec-packages/blob/f418456a84b9387a9d7bf76026a60b7a0f747149/yarn-project/pxe/src/contract_data_oracle/index.ts#L72-L78 | f418456a84b9387a9d7bf76026a60b7a0f747149 |
aztec-packages | github_2023 | AztecProtocol | typescript | ClientExecutionContext.loadFromExecutionCache | public override loadFromExecutionCache(hash: Fr): Promise<Fr[]> {
return Promise.resolve(this.executionCache.getPreimage(hash));
} | /**
* Gets values from the execution cache.
* @param hash - Hash of the values.
* @returns The values.
*/ | https://github.com/AztecProtocol/aztec-packages/blob/f418456a84b9387a9d7bf76026a60b7a0f747149/yarn-project/simulator/src/client/client_execution_context.ts#L179-L181 | f418456a84b9387a9d7bf76026a60b7a0f747149 |
obsidian-criticmarkup | github_2023 | Fevol | typescript | CriticMarkupRanges.range_adjacent_to_cursor | range_adjacent_to_cursor(cursor: number, left: boolean, loose = false, include_edge = false) {
const ranges = left ? this.ranges.slice().reverse() : this.ranges;
if (include_edge) {
return ranges.find(range =>
left ? ((loose ? range.from : range.to) < cursor) : (cursor < (loose ? range.to : range.from))
);
} else {
return ranges.find(range =>
left ? ((loose ? range.from : range.to) <= cursor) : (cursor <= (loose ? range.to : range.from))
);
}
} | /**
* Get the range that is (not directly) adjacent to the cursor in given direction
* @param cursor - Cursor position in the document
* @param left - Whether to look left or right of the cursor
* @param loose - Whether to include ranges that are partially adjacent to the cursor
* @param include_edge - Whether to include the edges of the range
*/ | https://github.com/Fevol/obsidian-criticmarkup/blob/407222c6e981d7a2acda110f75fd1fcfd5113626/src/editor/base/ranges/grouped_range.ts#L43-L54 | 407222c6e981d7a2acda110f75fd1fcfd5113626 |
aliyunpan | github_2023 | gaozhangmin | typescript | DownDAL.mSpeedEvent | static mSpeedEvent(list: IAriaDownProgress[]) {
const downingStore = useDowningStore()
const settingStore = useSettingStore()
const DowningList = downingStore.ListDataRaw
if (list == undefined) list = []
const dellist: string[] = []
let hasSpeed = 0
for (let n = 0; n < DowningList.length; n++) {
if (DowningList[n].Down.DownSpeedStr != '') {
const gid = DowningList[n].Info.GID
let isFind = false
for (let m = 0; m < list.length; m++) {
if (list[m].gid != gid) continue
if (list[m].gid == gid && list[m].status == 'active') {
isFind = true
break
}
}
if (!isFind) {
if (DowningList[n].Down.DownState != '已暂停') DowningList[n].Down.DownState = '队列中'
DowningList[n].Down.DownSpeed = 0
DowningList[n].Down.DownSpeedStr = ''
}
}
}
const ariaRemote = !settingStore.AriaIsLocal
const saveList: IStateDownFile[] = []
for (let i = 0; i < list.length; i++) {
try {
const gid = list[i].gid
const isComplete = list[i].status === 'complete'
const isDowning = isComplete || list[i].status === 'active' || list[i].status === 'waiting'
const isStop = list[i].status === 'paused' || list[i].status === 'removed'
const isError = list[i].status === 'error'
for (let j = 0; j < DowningList.length; j++) {
if (DowningList[j].Info.ariaRemote != ariaRemote) continue
if (DowningList[j].Info.GID == gid) {
const downItem = DowningList[j]
const down = downItem.Down
const totalLength = parseInt(list[i].totalLength) || 0
down.DownSize = parseInt(list[i].completedLength) || 0
down.DownSpeed = parseInt(list[i].downloadSpeed) || 0
down.DownSpeedStr = humanSize(down.DownSpeed) + '/s'
down.DownProcess = Math.floor((down.DownSize * 100) / (totalLength + 1)) % 100
down.IsCompleted = isComplete
down.IsDowning = isDowning
down.IsFailed = isError
down.IsStop = isStop
if (list[i].errorCode && list[i].errorCode != '0') {
down.FailedCode = parseInt(list[i].errorCode) || 0
down.FailedMessage = FormatAriaError(list[i].errorCode, list[i].errorMessage)
}
if (isComplete) {
down.DownSize = downItem.Info.size
down.DownSpeed = 0
down.DownSpeedStr = ''
down.DownProcess = 100
down.FailedCode = 0
down.FailedMessage = ''
down.DownState = '校验中'
const check = AriaHashFile(downItem)
if (check.Check) {
if (useSettingStore().downFinishAudio && !sound.playing()) {
sound.play()
}
downingStore.mUpdateDownState({
DownID: check.DownID,
DownState: '已完成',
IsFailed: false,
IsDowning: true,
IsStop: false,
IsCompleted: true,
FailedMessage: ''
})
} else {
downingStore.mUpdateDownState({
DownID: check.DownID,
DownState: '已出错',
IsFailed: true,
IsDowning: false,
IsStop: true,
IsCompleted: false,
FailedMessage: '移动文件失败,请重新下载'
})
}
} else if (isStop) {
down.DownState = '已暂停'
down.DownSpeed = 0
down.DownSpeedStr = ''
down.FailedCode = 0
down.FailedMessage = ''
} else if (isStop || isError) {
down.DownState = '已出错'
down.DownSpeed = 0
down.DownSpeedStr = ''
down.AutoTry = Date.now()
if (down.FailedMessage == '') down.FailedMessage = '下载失败'
} else if (isDowning) {
hasSpeed += down.DownSpeed
let lasttime = ((totalLength - down.DownSize) / (down.DownSpeed + 1)) % 356400
if (lasttime < 1) lasttime = 1
down.DownState =
down.DownProcess.toString() +
'% ' +
(lasttime / 3600).toFixed(0).padStart(2, '0') +
':' +
((lasttime % 3600) / 60).toFixed(0).padStart(2, '0') +
':' +
(lasttime % 60).toFixed(0).padStart(2, '0')
if (SaveTimeWait > 10) saveList.push(downItem)
} else {
//console.log('update', DowningList[j]);
}
if (isStop || isError) {
dellist.push(gid)
}
downingStore.mRefreshListDataShow(true)
break
}
}
} catch {
}
}
if (saveList.length > 0) DBDown.saveDownings(JSON.parse(JSON.stringify(saveList)))
if (dellist.length > 0) AriaDeleteList(dellist).then()
if (SaveTimeWait > 10) SaveTimeWait = 0
else SaveTimeWait++
useFootStore().mSaveDownTotalSpeedInfo(hasSpeed && humanSizeSpeed(hasSpeed) || '')
} | /**
* 速度事件方法
*/ | https://github.com/gaozhangmin/aliyunpan/blob/6fc8b1f9c5fa2bccc84143d4bd68d2b2b4c0c757/src/down/DownDAL.ts#L343-L479 | 6fc8b1f9c5fa2bccc84143d4bd68d2b2b4c0c757 |
usearch | github_2023 | unum-cloud | typescript | Index.size | size(): number {
return this.#compiledIndex.size();
} | /**
* Returns the number of vectors currently indexed.
* @return {number} The number of vectors currently indexed.
*/ | https://github.com/unum-cloud/usearch/blob/306d6646b8f539cee6c3fa11879dd3bc0edfa31f/javascript/usearch.ts#L472-L474 | 306d6646b8f539cee6c3fa11879dd3bc0edfa31f |
morjs | github_2023 | eleme | typescript | DataBinding.parseExp | private parseExp(exp: string) {
const res = { isOK: false, code: undefined }
if (!exp) return res
try {
const ast = parser.parse(`var _=(${exp})`)
res.isOK = true
traverse.default(ast, {
ReferencedIdentifier: (path) => {
// 检索出引用标识符
this._bindingVars.add(path.node.name)
},
SequenceExpression() {
res.isOK = false
}
} as any)
} catch (e) {
res.isOK = false
}
return res
} | // 提取变量 | https://github.com/eleme/morjs/blob/c1fd96bf0e5dc1178d56a1aecb4e524f4a4751a3/packages/plugin-compiler-web/src/compiler/core/axml2/ast/data-binding/index.ts#L116-L135 | c1fd96bf0e5dc1178d56a1aecb4e524f4a4751a3 |
morjs | github_2023 | eleme | typescript | View.watchTouchMove | watchTouchMove() {
// 防止重复监听,导致多次触发事件
if (this.isWatchTouchMove) return
this.isWatchTouchMove = true
const parent: Element = this.getScrollParent()
const callback = (ratio) => {
if (ratio >= 0.5 && this.lastTrigger !== 1) {
this.lastTrigger = 1
if (!this.hasAppeared) {
this.dispatchEvent(new CustomEvent('firstappear'))
this.hasAppeared = true
}
this.dispatchEvent(new CustomEvent('appear'))
}
if (ratio < 0.5 && this.lastTrigger === 1) {
this.lastTrigger = 0
this.dispatchEvent(new CustomEvent('disappear'))
}
}
requestAnimationFrame(() => {
// 为了确保元素渲染出来调用
const ratio = getElementVisibleRatio(this)
callback(ratio)
})
this.listener = throttle(
() => {
const ratio = getElementVisibleRatio(this)
callback(ratio)
},
66,
{ leading: true, trailing: true }
)
parent.addEventListener('scroll', this.listener)
} | //是否已经显示过 | https://github.com/eleme/morjs/blob/c1fd96bf0e5dc1178d56a1aecb4e524f4a4751a3/packages/runtime-web/src/components/src/views/view/index.ts#L77-L114 | c1fd96bf0e5dc1178d56a1aecb4e524f4a4751a3 |
morjs | github_2023 | eleme | typescript | Takin.runExtendedRunner | private async runExtendedRunner(options: RunnerOptions): Promise<Runner> {
const RunnerExtended = this.hooks.extendRunner.call(Runner, options)
const runner = new RunnerExtended(
options.config,
options.userConfig,
options.context
)
this.currentRunners.add(runner)
await runner.run(options.command, options.plugins)
return runner
} | /**
* 执行扩展 Runner 方法
*/ | https://github.com/eleme/morjs/blob/c1fd96bf0e5dc1178d56a1aecb4e524f4a4751a3/packages/takin/src/takin.ts#L224-L234 | c1fd96bf0e5dc1178d56a1aecb4e524f4a4751a3 |
sdk-mx-data-nft | github_2023 | Itheum | typescript | BondContract.viewAddressBondsInfo | async viewAddressBondsInfo(address: IAddress): Promise<{
totalStakedAmount: BigNumber.Value;
userStakedAmount: BigNumber.Value;
livelinessScore: number;
}> {
const interaction = this.contract.methodsExplicit.getAddressBondsInfo([
new AddressValue(address)
]);
const query = interaction.buildQuery();
const queryResponse = await this.networkProvider.queryContract(query);
const endpointDefinition = interaction.getEndpoint();
const { firstValue, returnCode } = new ResultsParser().parseQueryResponse(
queryResponse,
endpointDefinition
);
if (returnCode.isSuccess()) {
const returnValue = firstValue?.valueOf();
return {
totalStakedAmount: returnValue.field0.valueOf(),
userStakedAmount: returnValue.field1.valueOf(),
livelinessScore: new BigNumber(returnValue.field2.valueOf())
.div(100)
.toNumber()
};
} else {
throw new ErrContractQuery('viewAddressBondsInfo', returnCode.toString());
}
} | /**
* Returns the address bonds info
* @param address address to query
*
*/ | https://github.com/Itheum/sdk-mx-data-nft/blob/217bc6343c4cdcb40330894f9362a280b55c4907/src/bond.ts#L137-L164 | 217bc6343c4cdcb40330894f9362a280b55c4907 |
tanssi | github_2023 | moondance-labs | typescript | getTmpZombiePath | function getTmpZombiePath() {
return process.env.MOON_ZOMBIE_DIR;
} | /// Returns the /tmp/zombie-52234... path | https://github.com/moondance-labs/tanssi/blob/67bda97356c372ea9c19b1775b0901b5f8283622/test/suites/zombie_tanssi/test_zombie_tanssi.ts#L499-L501 | 67bda97356c372ea9c19b1775b0901b5f8283622 |
CushyStudio | github_2023 | rvion | typescript | Field_custom.defaultValue | get defaultValue(): T {
return this.config.defaultValue()
} | // #region Changes | https://github.com/rvion/CushyStudio/blob/142941557b471d65a1819014059798ed9f6535b3/src/csuite/fields/custom/FieldCustom.tsx#L113-L115 | 142941557b471d65a1819014059798ed9f6535b3 |
CushyStudio | github_2023 | rvion | typescript | Field_matrix.setOwnSerial | protected setOwnSerial(next: Field_matrix_serial): void {
this.assignNewSerial(next)
const cells = this.serial.selected ?? this.config.default ?? []
const selectedCells = new Set(cells.map(({ row, col }) => this.getCellkey(row, col)))
// make sure every cell has the right value
for (const [x, row] of this.config.rows.entries()) {
for (const [y, col] of this.config.cols.entries()) {
const cellKey = this.getCellkey(row, col)
const value = selectedCells.has(cellKey)
const prev = this.store.get(cellKey)
if (prev == null) this.store.set(cellKey, { x, y, col, row, value })
else prev.value = value
}
}
this.patchSerial((draft) => void (draft.selected = this.activeCells))
} | // #region Serial | https://github.com/rvion/CushyStudio/blob/142941557b471d65a1819014059798ed9f6535b3/src/csuite/fields/matrix/FieldMatrix.ts#L87-L105 | 142941557b471d65a1819014059798ed9f6535b3 |
CushyStudio | github_2023 | rvion | typescript | Field_optional.setOff | setOff(): void {
this.setActive(false)
} | /** set the value to false */ | https://github.com/rvion/CushyStudio/blob/142941557b471d65a1819014059798ed9f6535b3/src/csuite/fields/optional/FieldOptional.tsx#L233-L235 | 142941557b471d65a1819014059798ed9f6535b3 |
CushyStudio | github_2023 | rvion | typescript | ComfySchemaL.pythonModuleByNodeNameInCushy | get pythonModuleByNodeNameInCushy(): Map<NodeNameInCushy, ComfyPythonModule> { return this.parseObjectInfo.pythonModuleByNodeNameInCushy } // prettier-ignore | // forward to underlying parsedObjectInfo | https://github.com/rvion/CushyStudio/blob/142941557b471d65a1819014059798ed9f6535b3/src/models/ComfySchema.ts#L53-L53 | 142941557b471d65a1819014059798ed9f6535b3 |
CushyStudio | github_2023 | rvion | typescript | CushyScriptL.getExecutable_orExtract | getExecutable_orExtract(appID: CushyAppID): Maybe<Executable> {
if (this._EXECUTABLES) return this._EXECUTABLES.find((executable) => appID === executable.appID)
this.evaluateAndUpdateAppsAndViews()
return this._EXECUTABLES!.find((executable) => appID === executable.appID)
} | /** more costly variation of getExecutable_orNull */ | https://github.com/rvion/CushyStudio/blob/142941557b471d65a1819014059798ed9f6535b3/src/models/CushyScript.ts#L143-L147 | 142941557b471d65a1819014059798ed9f6535b3 |
CushyStudio | github_2023 | rvion | typescript | CushyLayoutManager.addCustomV2 | addCustomV2<T extends any>(fn: FC<T>, props: T): void {
const uid = uniqueIDByMemoryRef(fn)
const panel = registerCustomPanel(uid, fn)
this.open('Custom', { uid: panel.uid, props })
} | /**
* @experimental
* @unstable
*/ | https://github.com/rvion/CushyStudio/blob/142941557b471d65a1819014059798ed9f6535b3/src/router/Layout.tsx#L924-L928 | 142941557b471d65a1819014059798ed9f6535b3 |
agency-os | github_2023 | directus-labs | typescript | slugify | function slugify(str: string | undefined): string | undefined {
if (!str) return;
return str
.toString()
.trim()
.toLowerCase()
.replace(/[^\w ]+/g, '')
.replace(/ +/g, '-');
} | // Slugify a string for hyphens and underscores | https://github.com/directus-labs/agency-os/blob/78d36dddf74289719249053165cd879cf9fdbeea/utils/strings.ts#L28-L36 | 78d36dddf74289719249053165cd879cf9fdbeea |
lx-music-sync-server | github_2023 | lyswhut | typescript | ListEvent.list_music_update | async list_music_update(userName: string, musicInfos: LX.List.ListActionMusicUpdate, isRemote: boolean = false) {
const userSpace = getUserSpace(userName)
// const changedIds =
await userSpace.listManage.listDataManage.listMusicUpdateInfo(musicInfos)
// await checkUpdateList(changedIds)
this.emit('list_music_update', userName, musicInfos, isRemote)
listUpdated()
} | /**
* 批量更新歌曲信息
* @param musicInfos 歌曲&列表信息
* @param isRemote 是否属于远程操作
*/ | https://github.com/lyswhut/lx-music-sync-server/blob/f483d5fcebfe883141b56fcf08b63d741bb0954b/src/modules/list/event.ts#L187-L194 | f483d5fcebfe883141b56fcf08b63d741bb0954b |
daimo | github_2023 | daimo-eth | typescript | NameRegistry.resolveName | resolveName(name: string): Address | undefined {
return this.nameToReg.get(name)?.addr;
} | /** Find wallet address for a given Daimo name, or undefined if not found. */ | https://github.com/daimo-eth/daimo/blob/a960ddbbc0cb486f21b8460d22cebefc6376aac9/packages/daimo-api/src/contract/nameRegistry.ts#L205-L207 | a960ddbbc0cb486f21b8460d22cebefc6376aac9 |
waku | github_2023 | dai-shi | typescript | isCommonjs | const isCommonjs = (code: string) =>
/\b(?:require|module|exports)\b/.test(
code.replace(/\/\*(.|[\r\n])*?\*\//gm, '').replace(/\/\/.*/g, ''),
); | // https://github.com/vite-plugin/vite-plugin-commonjs/blob/5e3294e78fabb037e12aab75433908fbee17192a/src/utils.ts#L9-L15 | https://github.com/dai-shi/waku/blob/06577a046cf0cbed13f11a4f3251fe525a1ffa25/packages/waku/src/lib/plugins/vite-plugin-dev-commonjs.ts#L8-L11 | 06577a046cf0cbed13f11a4f3251fe525a1ffa25 |
engine | github_2023 | thirdweb-dev | typescript | ConfigurationService.getCacheConfiguration | public getCacheConfiguration(): CancelablePromise<{
result: {
clearCacheCronSchedule: string;
};
}> {
return this.httpRequest.request({
method: 'GET',
url: '/configuration/cache',
errors: {
400: `Bad Request`,
404: `Not Found`,
500: `Internal Server Error`,
},
});
} | /**
* Get cache configuration
* Get cache configuration
* @returns any Default Response
* @throws ApiError
*/ | https://github.com/thirdweb-dev/engine/blob/07d1d7d3b5c28c5977d2b7457bf6ba33c22692d6/sdk/src/services/ConfigurationService.ts#L554-L568 | 07d1d7d3b5c28c5977d2b7457bf6ba33c22692d6 |
engine | github_2023 | thirdweb-dev | typescript | getCurrentNonceState | async function getCurrentNonceState(
walletAddress: Address,
chainId: number,
): Promise<NonceState> {
const [onchainNonce, largestSentNonce] = await Promise.all([
getLastUsedOnchainNonce(chainId, walletAddress),
inspectNonce(chainId, walletAddress),
]);
return {
onchainNonce: onchainNonce,
largestSentNonce: largestSentNonce,
};
} | // Get current nonce state | https://github.com/thirdweb-dev/engine/blob/07d1d7d3b5c28c5977d2b7457bf6ba33c22692d6/src/worker/tasks/nonce-health-check-worker.ts#L104-L117 | 07d1d7d3b5c28c5977d2b7457bf6ba33c22692d6 |
qr | github_2023 | paulmillr | typescript | readInfoBits | function readInfoBits(b: Bitmap) {
const readBit = (x: number, y: number, out: number) => (out << 1) | (b.data[y][x] ? 1 : 0);
const size = b.height;
// Version information
let version1 = 0;
for (let y = 5; y >= 0; y--)
for (let x = size - 9; x >= size - 11; x--) version1 = readBit(x, y, version1);
let version2 = 0;
for (let x = 5; x >= 0; x--)
for (let y = size - 9; y >= size - 11; y--) version2 = readBit(x, y, version2);
// Format information
let format1 = 0;
for (let x = 0; x < 6; x++) format1 = readBit(x, 8, format1);
format1 = readBit(7, 8, format1);
format1 = readBit(8, 8, format1);
format1 = readBit(8, 7, format1);
for (let y = 5; y >= 0; y--) format1 = readBit(8, y, format1);
let format2 = 0;
for (let y = size - 1; y >= size - 7; y--) format2 = readBit(8, y, format2);
for (let x = size - 8; x < size; x++) format2 = readBit(x, 8, format2);
return { version1, version2, format1, format2 };
} | // Same as in drawTemplate, but reading | https://github.com/paulmillr/qr/blob/0681dd8b2934e1c13d957a5a8b61321f64f37661/src/decode.ts#L664-L685 | 0681dd8b2934e1c13d957a5a8b61321f64f37661 |
qr | github_2023 | paulmillr | typescript | Bitmap.scale | scale(factor: number): Bitmap {
if (!Number.isSafeInteger(factor) || factor > 1024)
throw new Error(`invalid scale factor: ${factor}`);
const { height, width } = this;
const res = new Bitmap({ height: factor * height, width: factor * width });
return res.rect(
{ x: 0, y: 0 },
Infinity,
({ x, y }) => this.data[Math.floor(y / factor)][Math.floor(x / factor)]
);
} | // Each pixel size is multiplied by factor | https://github.com/paulmillr/qr/blob/0681dd8b2934e1c13d957a5a8b61321f64f37661/src/index.ts#L284-L294 | 0681dd8b2934e1c13d957a5a8b61321f64f37661 |
camera | github_2023 | houdunwang | typescript | openNewCamera | const openNewCamera = () => {
window.api.openNewCamera()
} | //打开新摄像头 | https://github.com/houdunwang/camera/blob/543ca73de6ef6bce6df3409b148be3e8b8247340/src/renderer/src/composables/useCamera.ts#L16-L18 | 543ca73de6ef6bce6df3409b148be3e8b8247340 |
ChatGPT-Desktop | github_2023 | Synaptrix | typescript | deleteSessionData | const deleteSessionData = async (payload: SessionData) => {
if (sessionDataList.value.length === 1) {
await deleteSession()
} else {
const { id, session_id } = payload
const sql = `DELETE FROM session_data WHERE id = '${id}' AND session_id = '${session_id}';`
await executeSQL(sql)
}
Message.success(t('message.deleteSuccess'))
getSessionData()
} | // 删除一条对话数据 | https://github.com/Synaptrix/ChatGPT-Desktop/blob/fea046838a6a0b3655f9d4ed6e15f9f8fa15ffd2/src/stores/session.ts#L129-L141 | fea046838a6a0b3655f9d4ed6e15f9f8fa15ffd2 |
ai-pr-reviewer | github_2023 | coderabbitai | typescript | Commenter.addReviewedCommitId | addReviewedCommitId(commentBody: string, commitId: string): string {
const start = commentBody.indexOf(COMMIT_ID_START_TAG)
const end = commentBody.indexOf(COMMIT_ID_END_TAG)
if (start === -1 || end === -1) {
return `${commentBody}\n${COMMIT_ID_START_TAG}\n<!-- ${commitId} -->\n${COMMIT_ID_END_TAG}`
}
const ids = commentBody.substring(start + COMMIT_ID_START_TAG.length, end)
return `${commentBody.substring(
0,
start + COMMIT_ID_START_TAG.length
)}${ids}<!-- ${commitId} -->\n${commentBody.substring(end)}`
} | // if the marker doesn't exist, add it | https://github.com/coderabbitai/ai-pr-reviewer/blob/d5ec3970b3acc4b9d673e6cd601bf4d3cf043b55/src/commenter.ts#L706-L717 | d5ec3970b3acc4b9d673e6cd601bf4d3cf043b55 |
grats | github_2023 | captbaritone | typescript | Group.members | async members(): Promise<User[]> {
return [new User()];
} | /** @gqlField */ | https://github.com/captbaritone/grats/blob/7fe027351ba554ddb3ccd13919fd58c7c6bef67f/examples/yoga/models/Group.ts#L17-L19 | 7fe027351ba554ddb3ccd13919fd58c7c6bef67f |
grats | github_2023 | captbaritone | typescript | MyFunc | function MyFunc() {} | /** @gqlType */ | https://github.com/captbaritone/grats/blob/7fe027351ba554ddb3ccd13919fd58c7c6bef67f/src/tests/fixtures/type_definitions/TagAttachedToWrongNode.ts#L2-L2 | 7fe027351ba554ddb3ccd13919fd58c7c6bef67f |
grats | github_2023 | captbaritone | typescript | User.myField | myField(): string {
return "Hello World";
} | /** @gqlField */ | https://github.com/captbaritone/grats/blob/7fe027351ba554ddb3ccd13919fd58c7c6bef67f/website/docs/04-docblock-tags/snippets/02-property-and-method.grats.ts#L10-L12 | 7fe027351ba554ddb3ccd13919fd58c7c6bef67f |
pepr | github_2023 | defenseunicorns | typescript | debounced | const debounced = (): void => {
// Base64 decode the data
const data: DataStore = store.data || {};
// Loop over each stored capability
for (const name of Object.keys(this.#stores)) {
// Get the prefix offset for the keys
const offset = `${name}-`.length;
// Get any keys that match the capability name prefix
const filtered: DataStore = {};
// Loop over each key in the secret
for (const key of Object.keys(data)) {
// Match on the capability name as a prefix
if (startsWith(name, key)) {
// Strip the prefix and store the value
filtered[key.slice(offset)] = data[key];
}
}
// Send the data to the receiver callback
this.#stores[name].receive(filtered);
}
// Call the onReady callback if this is the first time the secret has been read
if (this.#onReady) {
this.#onReady();
this.#onReady = undefined;
}
}; | // Wrap the update in a debounced function | https://github.com/defenseunicorns/pepr/blob/939e93673dde79ba6ba70c8961c6e1fcc1a70dbd/src/lib/controller/store.ts#L113-L143 | 939e93673dde79ba6ba70c8961c6e1fcc1a70dbd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.