repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
homebridge-appletv-enhanced
github_2023
maxileith
typescript
AppleTVEnhancedPlatform.discoverDevices
private async discoverDevices(): Promise<void> { this.log.debug('Starting device discovery ...'); let scanResults: NodePyATVDevice[] = []; // multicast discovery if ( this.config.discover?.multicast === undefined || this.config.discover.multicast === true ) { try { const multicastResults: NodePyATVFindResponseObject = await CustomPyAtvInstance.customFind(); multicastResults.errors.forEach((error) => { if (error.exception !== undefined && typeof error.exception === 'string') { this.log.error(`multicast discovery - ${error.exception}`); this.log.debug(JSON.stringify(error, undefined, 2)); } else { this.log.error(JSON.stringify(error, undefined, 2)); } }); scanResults = multicastResults.devices; this.log.debug('finished multicast device discovery'); } catch (e: unknown) { if (typeof e === 'object' && e instanceof Error) { this.log.error(`${e.name}: ${e.message}`); if (e.stack !== undefined && e.stack !== null) { this.log.debug(e.stack); } } else { throw e; } } } // unicast discovery if ( this.config.discover?.unicast && this.config.discover.unicast.length !== 0 ) { try { const unicastResults: NodePyATVFindResponseObject = await CustomPyAtvInstance.customFind({ hosts: this.config.discover?.unicast }); unicastResults.errors.forEach((error) => { if (error.exception !== undefined && typeof error.exception === 'string') { this.log.error(`unicast discovery - ${error.exception}`); this.log.debug(JSON.stringify(error, undefined, 2)); } else { this.log.error(JSON.stringify(error, undefined, 2)); } }); scanResults = [...scanResults, ...unicastResults.devices]; this.log.debug('finished unicast device discovery'); } catch (e: unknown) { if (typeof e === 'object' && e instanceof Error) { this.log.error(`${e.name}: ${e.message}`); if (e.stack !== undefined && e.stack !== null) { this.log.debug(e.stack); } } else { throw e; } } } const appleTVs: NodePyATVDevice[] = scanResults.filter((d) => ALLOWED_MODELS.includes(d.model ?? '') && d.os === 'TvOS'); // loop over the discovered devices and register each one if it has not already been registered for (const appleTV of appleTVs) { this.log.debug(`Found ${appleTV.name} (${appleTV.mac} / ${appleTV.host}).`); if (appleTV.mac === undefined || appleTV.mac === null) { this.log.debug(`${appleTV.name} (${appleTV.host}) is skipped since the MAC address could not be determined.`); continue; } const mac: string = appleTV.mac.toUpperCase(); if ( this.config.discover?.blacklist && ( this.config.discover.blacklist.map((e) => e.toUpperCase()).includes(mac) || this.config.discover.blacklist.includes(appleTV.host) ) ) { this.log.debug(`${appleTV.name} (${appleTV.mac} / ${appleTV.host}) is on the blacklist. Skipping.`); continue; } // generate a unique id for the accessory this should be generated from // something globally unique, but constant, for example, the device serial // number or MAC address const uuid: string = this.api.hap.uuid.generate(DEV_MODE === true ? `x${mac}` : mac); if (this.publishedUUIDs.includes(uuid)) { this.log.debug(`${appleTV.name} (${appleTV.mac}) with UUID ${uuid} already exists. Skipping.`); continue; } this.publishedUUIDs.push(uuid); // the accessory does not yet exist, so we need to create it this.log.info(`Adding ${appleTV.name} (${appleTV.mac})`); // create a new accessory const accessory: PlatformAccessory = new this.api.platformAccessory(appleTV.name, uuid); // store a copy of the device object in the `accessory.context` // the `context` property can be used to store any data about the accessory you may need accessory.context.mac = mac; // create the accessory handler for the newly create accessory // this is imported from `platformAccessory.ts` void (async (): Promise<void> => { this.log.debug(`Waiting for ${appleTV.name} (${appleTV.mac}) to boot ...`); await new AppleTVEnhancedAccessory(this, accessory).untilBooted(); // link the accessory to your platform this.log.debug(`${appleTV.name} (${appleTV.mac}) finished booting. Publishing the accessory now.`); this.api.publishExternalAccessories(PLUGIN_NAME, [accessory]); })(); } this.log.debug('Finished device discovery.'); }
/** * This is an example method showing how to register discovered accessories. * Accessories must only be registered once, previously created accessories * must not be registered again to prevent "duplicate UUID" errors. */
https://github.com/maxileith/homebridge-appletv-enhanced/blob/94633e9bd19b47d6fb9cdc419d5465e7c6382a0a/src/appleTVEnhancedPlatform.ts#L105-L224
94633e9bd19b47d6fb9cdc419d5465e7c6382a0a
icloud-passwords-firefox
github_2023
au2001
typescript
SRPSession.constructor
private constructor( username: Buffer, clientPrivateKey: bigint, shouldUseBase64 = false, ) { this.clientPrivateKey = clientPrivateKey; this.shouldUseBase64 = shouldUseBase64; this.username = this.serialize(username); }
// x
https://github.com/au2001/icloud-passwords-firefox/blob/d41739a4b3fe89faa395cd9dbc788dfe2c84a514/src/utils/srp.ts#L45-L54
d41739a4b3fe89faa395cd9dbc788dfe2c84a514
icloud-passwords-firefox
github_2023
au2001
typescript
SRPSession.clientPublicKey
get clientPublicKey() { return powermod(GROUP_GENERATOR, this.clientPrivateKey, GROUP_PRIME); }
// A
https://github.com/au2001/icloud-passwords-firefox/blob/d41739a4b3fe89faa395cd9dbc788dfe2c84a514/src/utils/srp.ts#L66-L68
d41739a4b3fe89faa395cd9dbc788dfe2c84a514
LLM-RGB
github_2023
babelcloud
typescript
getAggregatedScores
function getAggregatedScores(scores: TestScore[], tests) { var context_length = 0; var reasoning_depth = 0; var instruction_compliance = 0; for (const score of scores) { const diffculties = findDifficulties(score.test_name, tests); context_length = context_length + score.assertion_score * diffculties["context-length"]; reasoning_depth = reasoning_depth + score.assertion_score * diffculties["reasoning-depth"]; instruction_compliance = instruction_compliance + score.assertion_score * diffculties["instruction-compliance"]; } return { context_length: parseFloat(context_length.toFixed(1)), reasoning_depth: parseFloat(reasoning_depth.toFixed(1)), instruction_compliance: parseFloat(instruction_compliance.toFixed(1)) }; }
/** * Calculate the aggregated scores of a given llm's test scores. */
https://github.com/babelcloud/LLM-RGB/blob/e6befa35de28640f0f5bdb5176a385f2784bfae7/utils/generateEvalScore.ts#L160-L175
e6befa35de28640f0f5bdb5176a385f2784bfae7
LLM-RGB
github_2023
babelcloud
typescript
findDifficulties
function findDifficulties(name: string, tests) { for (const test of tests) { if (test.name == name) { return test.difficulties; } } return null; }
/** * Return the difficulties values of given test */
https://github.com/babelcloud/LLM-RGB/blob/e6befa35de28640f0f5bdb5176a385f2784bfae7/utils/generateEvalScore.ts#L181-L188
e6befa35de28640f0f5bdb5176a385f2784bfae7
LLM-RGB
github_2023
babelcloud
typescript
getLLMScores
function getLLMScores(llm_id: string, results, tests) { var scoreMap = new Map<string, TestScore[]>(); for (const result of results) { if (result.provider.id == llm_id) { const test_difficulties = findDifficulties(result.vars.name, tests); const test_score = result.score.toFixed(1) * (test_difficulties["context-length"] + test_difficulties["reasoning-depth"] + test_difficulties["instruction-compliance"]); var score: TestScore = { test_name: result.vars.name, assertion_score: result.score, test_score: test_score, repeat: 1 } if(!scoreMap.has(score.test_name)){ scoreMap.set(score.test_name, []); } scoreMap.get(score.test_name).push(score); } } // calculate the average score const scores: TestScore[] = Array.from(scoreMap.values()).map(scoreList => { let assertion_score_sum = scoreList.map(s => s.assertion_score).reduce((pre, cur) => pre + cur); let test_score_sum = scoreList.map(s => s.test_score).reduce((pre, cur) => pre + cur); return { test_name: scoreList[0].test_name, assertion_score: parseFloat((assertion_score_sum/scoreList.length).toFixed(1)), test_score: parseFloat((test_score_sum/scoreList.length).toFixed(1)), repeat: scoreList.length }; }); return scores.sort((a, b) => a.test_name.localeCompare(b.test_name)); }
/** * Find all results of provided llm and extract the scores */
https://github.com/babelcloud/LLM-RGB/blob/e6befa35de28640f0f5bdb5176a385f2784bfae7/utils/generateEvalScore.ts#L194-L228
e6befa35de28640f0f5bdb5176a385f2784bfae7
directus-schema-sync
github_2023
bcc-code
typescript
CollectionExporter.sortbyIfLinked
protected async sortbyIfLinked(items: Array<Item>) { const { getPrimary, linkedFields } = await this.settings(); if (!linkedFields.length) return false; const itemsMap = items.reduce((map, o) => { o.__dependents = []; map[getPrimary(o)] = o; return map; }, {} as Record<PrimaryKey, Item>); items.forEach(o => { for (const fieldName of linkedFields) { const value = o[fieldName]; if (value && itemsMap[value]) { itemsMap[value].__dependents.push(o); } } }); items.sort((a, b) => this.countDependents(b) - this.countDependents(a)); items.forEach(o => delete o.__dependents); return true; }
/** * Orders items so that items that are linked are inserted after the items they reference * Only works with items that have a primary key * Assumes items not in given items list are already in the database * @param items * @returns */
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/collectionExporter.ts#L230-L253
f73c15c196f2e897d27c7b8f272e94fc68afbf46
directus-schema-sync
github_2023
bcc-code
typescript
CollectionExporter.countDependents
private countDependents(o: any): number { if (!o.__dependents.length) return 0; return (o.__dependents as Array<Item>).reduce((acc, o) => acc + this.countDependents(o), o.__dependents.length); }
// Recursively count dependents
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/collectionExporter.ts#L255-L258
f73c15c196f2e897d27c7b8f272e94fc68afbf46
directus-schema-sync
github_2023
bcc-code
typescript
CollectionExporter.loadGroupedItems
public async loadGroupedItems(config: PARTIAL_CONFIG, merge = false) { const loadedItems = []; let found = 0; const files = await glob(this.groupedFilesPath('*')); for (const file of files) { const groupJson = await readFile(file, { encoding: 'utf8' }); const items = JSON.parse(groupJson) as Array<Item>; if (!Array.isArray(items)) { this.logger.warn(`Not items found in ${file}`); continue; } found += items.length; loadedItems.push(...items); } if (found !== config.count) { if (found === 0) { throw new Error('No items found in grouped files for ${this.collection}'); } this.logger.warn(`Expected ${config.count} items, but found ${found}`); } this.logger.info(`Stitched ${found} items for ${this.collection} from ${files.length} files`); return this.loadItems(loadedItems, merge); }
/** * Fetches the items from grouped files and then subsequently loads the items * * @param config * @param merge {see loadItems} * @returns */
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/collectionExporter.ts#L267-L295
f73c15c196f2e897d27c7b8f272e94fc68afbf46
directus-schema-sync
github_2023
bcc-code
typescript
CollectionExporter.loadItems
public async loadItems(loadedItems: Array<Item>, merge = false) { if (merge && !loadedItems.length) return null; const itemsSvc = await this._getService(); const { getKey, getPrimary, queryWithPrimary } = await this.settings(); const items = await itemsSvc.readByQuery(queryWithPrimary); const itemsMap = new Map<PrimaryKey, Item>(); const duplicatesToDelete: Array<PrimaryKey> = []; // First pass: identify duplicates and build initial map items.forEach(item => { const itemKey = getKey(item); if (itemsMap.has(itemKey)) { const itemId = getPrimary(itemsMap.get(itemKey)!); this.logger.warn(`Will delete duplicate ${this.collection} item found #${itemId}`); duplicatesToDelete.push(itemId); } itemsMap.set(itemKey, item); }); // Delete duplicates first if (duplicatesToDelete.length > 0) { this.logger.debug(`Deleting ${duplicatesToDelete.length} duplicate ${this.collection} items`); await itemsSvc.deleteMany(duplicatesToDelete); } const toUpdate = new Map<PrimaryKey, ToUpdateItemDiff>(); const toInsert: Record<PrimaryKey, Item> = {}; const toDeleteItems = new Map<PrimaryKey, Item>(itemsMap); // Process imported items for (let lr of loadedItems) { if (this.options.onImport) { lr = (await this.options.onImport(lr, itemsSvc)) as Item; if (!lr) continue; } const lrKey = getKey(lr); const existing = itemsMap.get(lrKey); if (existing) { // We delete the item from the map so that we can later check which items were deleted toDeleteItems.delete(lrKey); const diff = getDiff(lr, existing); if (diff) { toUpdate.set(lrKey, { pkey: getPrimary(existing), diff, }); } } else { toInsert[lrKey] = lr; } } // Insert let toInsertValues = Object.values(toInsert); if (toInsertValues.length > 0) { this.logger.debug(`Inserting ${toInsertValues.length} x ${this.collection} items`); if (await this.sortbyIfLinked(toInsertValues)) { for (const item of toInsertValues) { await itemsSvc.createOne(item); } } else { await itemsSvc.createMany(toInsertValues); } } // Update if (toUpdate.size > 0) { this.logger.debug(`Updating ${toUpdate.size} x ${this.collection} items`); for (const [_key, item] of toUpdate) { await itemsSvc.updateOne(item.pkey, item.diff); } } const finishUp = async () => { if (!merge) { // When not merging, delete items that weren't in the import set const toDelete = Array.from(toDeleteItems.values(), getPrimary); if (toDelete.length > 0) { this.logger.debug(`Deleting ${toDelete.length} x ${this.collection} items`); await itemsSvc.deleteMany(toDelete); } } }; return finishUp; }
/** * Loads the items and updates the database * * @param loadedItems An array of loaded items to sync with the database * @param merge boolean indicating whether to merge the items or replace them, ie. delete all items not in the JSON * @returns */
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/collectionExporter.ts#L304-L397
f73c15c196f2e897d27c7b8f272e94fc68afbf46
directus-schema-sync
github_2023
bcc-code
typescript
ExportManager.addExporter
public addExporter(exporterConfig: IExporterConfig) { this.exporters.push(exporterConfig); }
// FIRST: Add exporters
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/exportManager.ts#L12-L14
f73c15c196f2e897d27c7b8f272e94fc68afbf46
directus-schema-sync
github_2023
bcc-code
typescript
ExportManager.loadAll
public async loadAll(merge = false) { await this._loadNextExporter(0, merge); }
// SECOND: Import if needed
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/exportManager.ts#L27-L29
f73c15c196f2e897d27c7b8f272e94fc68afbf46
directus-schema-sync
github_2023
bcc-code
typescript
ExportManager.attachAllWatchers
public attachAllWatchers(action: (event: string, handler: ActionHandler) => void, updateMeta: () => Promise<void>) { // EXPORT SCHEMAS & COLLECTIONS ON CHANGE // const actions = ['create', 'update', 'delete']; this.exporters.forEach(({ watch, exporter }) => { watch.forEach(col => { actions.forEach(evt => { action(`${col}.${evt}`, async () => { await exporter.export(); await updateMeta(); }); }); }); }); }
// THIRD: Start watching for changes
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/exportManager.ts#L45-L58
f73c15c196f2e897d27c7b8f272e94fc68afbf46
directus-schema-sync
github_2023
bcc-code
typescript
SchemaExporter.constructor
constructor( getSchemaService: () => any, protected logger: ApiExtensionContext['logger'], protected options = { split: true } ) { this._getSchemaService = () => getSchemaService(); this._filePath = `${ExportHelper.dataDir}/schema.json`; }
// Directus SchemaService, database and getSchema
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/schemaExporter.ts#L17-L24
f73c15c196f2e897d27c7b8f272e94fc68afbf46
directus-schema-sync
github_2023
bcc-code
typescript
SchemaExporter.createAndSaveSnapshot
public load = async () => { const svc = this._getSchemaService(); if (await ExportHelper.fileExists(this._filePath)) { const json = await readFile(this._filePath, { encoding: 'utf8' }); if (json) { const schemaParsed = JSON.parse(json); // For older versions, the snapshot was stored under the key `snapshot` const { partial, hash, ...snapshot } = ( (schemaParsed as any).snapshot ? Object.assign((schemaParsed as any).snapshot, { hash: schemaParsed.hash }) : schemaParsed ) as Snapshot & { partial?: boolean; hash: string }; if (partial) { snapshot.collections = []; snapshot.fields = []; snapshot.relations = []; let found = 0; const files = await glob(this.schemaFilesPath('*')); for (const file of files) { const collectionJson = await readFile(file, { encoding: 'utf8' }); const { fields, relations, ...collectionInfo } = JSON.parse(collectionJson) as Collection & { fields: SnapshotField[]; relations: SnapshotRelation[]; }; ++found; // Only add collection if it has a meta definition (actual table or group) if (collectionInfo.meta) { snapshot.collections.push(collectionInfo); } for (const field of fields) { snapshot.fields.push(Object.assign({ collection: collectionInfo.collection }, field)); } for (const relation of relations) { snapshot.relations.push(Object.assign({ collection: collectionInfo.collection }, relation)); } } if (found === 0) { this.logger.error('No schema files found in schema directory'); return; } this.logger.info(`Stitched ${found} partial schema files`); snapshot.collections.sort((a, b) => a.collection.localeCompare(b.collection)); // Sort non-table collections to the start snapshot.collections.sort((a, b) => String(!!a.schema).localeCompare(String(!!b.schema))); // Sort fields and relations by collection snapshot.fields.sort((a, b) => a.collection.localeCompare(b.collection)); snapshot.relations.sort((a, b) => a.collection.localeCompare(b.collection)); } const currentSnapshot = await svc.snapshot(); const currentHash = svc.getHashedSnapshot(currentSnapshot).hash; if (currentHash === hash) { this.logger.debug('Schema is already up-to-date'); return; } const diff = await svc.diff(snapshot, { currentSnapshot, force: true }); if (diff !== null) { await svc.apply({ diff, hash: currentHash }); } } } }
/** * Import the schema from file to the database */
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/schemaExporter.ts
f73c15c196f2e897d27c7b8f272e94fc68afbf46
directus-schema-sync
github_2023
bcc-code
typescript
UpdateManager.lockForUpdates
public async lockForUpdates(newHash: string, isoTS: string) { if (this._locked || this._locking) return false; this._locking = true; // Don't lock if schema sync is not installed yet const isInstalled = await this.db.schema.hasColumn(this.tableName, 'mv_hash'); if (!isInstalled) { this._locking = false; return true; } const succeeded = await this.db.transaction(async trx => { const rows = await trx(this.tableName) .select('*') .where('id', this.rowId) .where('mv_locked', false) // Only need to migrate if hash is different .andWhereNot('mv_hash', newHash) // And only if the previous hash is older than the current one .andWhere('mv_ts', '<', isoTS) .orWhereNull('mv_ts') .forUpdate(); // This locks the row // If row is found, lock it if (rows.length) { await trx(this.tableName).where('id', this.rowId).update({ mv_locked: true, }); this._locked = { hash: newHash, ts: isoTS, }; return true; } return false; }); this._locking = false; return succeeded; }
/** * Acquire the lock to make updates * @param newHash - New hash value of latest changes * @param isoTS - ISO timestamp * @returns */
https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/updateManager.ts#L27-L67
f73c15c196f2e897d27c7b8f272e94fc68afbf46
materialite
github_2023
vlcn-io
typescript
IssueModal
function IssueModal({ isOpen, onDismiss }: Props) { const ref = useRef<HTMLInputElement>(null); const [title, setTitle] = useState(""); const [description, setDescription] = useState<string>(); const [priority, setPriority] = useState<PriorityType>(Priority.NONE); const [status, setStatus] = useState<StatusType>(Status.BACKLOG); const handleSubmit = async () => { if (title === "") { showWarning("Please enter a title before submitting", "Title required"); return; } const date = Date.now(); const id = db.nextId<Issue>(); mutations.putIssueWithDescription( { id, title: title, creator: "testuser", priority: priority, status: status, modified: date, created: date, kanbanorder: "aa", // TODO (mlaw) }, { id, body: description ?? "", } ); if (onDismiss) onDismiss(); reset(); showInfo("You created new issue.", "Issue created"); }; const handleClickCloseBtn = () => { if (onDismiss) onDismiss(); reset(); }; const reset = () => { setTimeout(() => { setTitle(""); setDescription(""); setPriority(Priority.NONE); setStatus(Status.BACKLOG); }, 250); }; useEffect(() => { if (isOpen) { setTimeout(() => { ref.current?.focus(); }, 250); } }, [isOpen]); const body = ( <div className="flex flex-col w-full py-4 overflow-hidden"> {/* header */} <div className="flex items-center justify-between flex-shrink-0 px-4"> <div className="flex items-center"> <span className="inline-flex items-center p-1 px-2 text-gray-400 bg-gray-100 rounded"> <LivestoreIcon className="w-3 h-3 scale-150 mr-1" /> <span>LiveStore</span> </span> <ChevronRight className="ml-1" /> <span className="ml-1 font-normal text-gray-700">New Issue</span> </div> <div className="flex items-center"> <button className="inline-flex rounded items-center justify-center ml-2 text-gray-500 h-7 w-7 hover:bg-gray-100 rouned hover:text-gray-700" onClick={handleClickCloseBtn} > <CloseIcon className="w-4" /> </button> </div> </div> <div className="flex flex-col flex-1 pb-3.5 overflow-y-auto"> {/* Issue title */} <div className="flex items-center w-full mt-1.5 px-4"> <StatusMenu id="status-menu" button={ <button className="flex items-center justify-center w-6 h-6 border-none rounded hover:bg-gray-100"> <StatusIcon status={status} /> </button> } onSelect={(st) => { setStatus(st); }} /> <input className="w-full ml-1.5 text-lg font-semibold placeholder-gray-400 border-none h-7 focus:border-none focus:outline-none focus:ring-0" placeholder="Issue title" value={title} ref={ref} onChange={(e) => setTitle(e.target.value)} /> </div> {/* Issue description editor */} <div className="w-full px-4"> <Editor className="prose w-full max-w-full mt-2 font-normal appearance-none min-h-12 p-1 text-md editor border border-transparent focus:outline-none focus:ring-0" value={description || ""} onChange={(val) => setDescription(val)} placeholder="Add description..." /> </div> </div> {/* Issue labels & priority */} <div className="flex items-center px-4 pb-3 mt-1 border-b border-gray-200"> <PriorityMenu id="priority-menu" button={ <button className="inline-flex items-center h-6 px-2 text-gray-500 bg-gray-200 border-none rounded hover:bg-gray-100 hover:text-gray-700"> <PriorityIcon priority={priority} className="mr-1" /> <span>{PriorityDisplay[priority]}</span> </button> } onSelect={(val) => { console.log(val); setPriority(val); }} /> </div> {/* Footer */} <div className="flex items-center flex-shrink-0 px-4 pt-3"> <button className="px-3 ml-auto text-white bg-indigo-600 rounded hover:bg-indigo-700 h-7" onClick={handleSubmit} > Save Issue </button> </div> </div> ); return ( <Modal isOpen={isOpen} center={false} size="large" onDismiss={onDismiss}> {body} </Modal> ); }
// eslint-disable-next-line react-refresh/only-export-components
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/components/IssueModal.tsx#L26-L173
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
IssueCollection.getSortedSource
getSortedSource( order: Order ): Omit<MutableSetSource<Issue>, "add" | "delete"> { let index = this.#orderedIndices.get(order); if (!index) { index = m.newSortedSet<Issue>(issueComparators[order]); const newIndex = index; m.tx(() => { for (const issue of this.#base.value.values()) { newIndex.add(issue); } }); this.#orderedIndices.set(order, index); } return index; }
// the developer should mutate `issueCollection` which keeps all the indices in sync.
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/domain/db.ts#L74-L89
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
IssueItem
const IssueItem = ({ issue, style, isDragging, provided }: IssueProps) => { const navigate = useNavigate(); const priorityIcon = ( <span className="inline-block m-0.5 rounded-sm border border-gray-100 hover:border-gray-200 p-0.5"> <PriorityIcon priority={issue.priority} /> </span> ); const updatePriority = (priority: PriorityType) => mutations.putIssue({ ...db.issues.get(issue.id)!, priority, }); return ( <div ref={provided.innerRef} className={classNames( "cursor-default flex flex-col w-full px-4 py-3 mb-2 bg-white rounded focus:outline-none", { "shadow-modal": isDragging, } )} {...provided.draggableProps} {...provided.dragHandleProps} style={getStyle(provided, style)} onClick={() => navigate(`/issue/${issue.id}`)} > <div className="flex justify-between w-full cursor-default"> <div className="flex flex-col"> <span className="mt-1 text-sm font-medium text-gray-700 line-clamp-2 overflow-ellipsis"> {issue.title} </span> </div> <div className="flex-shrink-0"> <Avatar name={issue.creator} /> </div> </div> <div className="mt-2.5 flex items-center"> <PriorityMenu button={priorityIcon} id={"priority-menu-" + issue.id} filterKeyword={true} onSelect={(p) => updatePriority(p)} /> </div> </div> ); };
// eslint-disable-next-line react-refresh/only-export-components
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/pages/Board/IssueItem.tsx#L34-L82
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
VirtualTableBase
function VirtualTableBase<T>({ rowRenderer, width, height, rowHeight, rows, totalRows, startIndex, onNextPage, onPrevPage, hasNextPage, hasPrevPage, loading, className, }: { className?: string; width: string | number; height: number; rowHeight: number; rows: readonly T[]; totalRows: number; startIndex: number; onNextPage: () => void; onPrevPage: () => void; loading: boolean; hasPrevPage: boolean; hasNextPage: boolean; rowRenderer: ( row: T, style: { [key: string]: string | number } ) => React.ReactNode; }) { const tableContainerRef = React.useRef<HTMLDivElement>(null); const handleScroll = (e: React.UIEvent<HTMLDivElement>) => { const target = e.target as HTMLElement; if (loading) { // TODO (mlaw): // allow scrolling while loading if we're inside the over-scan window. e.preventDefault(); target.scrollTop = prevScrollTop; return false; } const scrollTop = target.scrollTop; setScrollTop(scrollTop); if (Math.abs(scrollTop - prevScrollTop) > vp) { onJump(); } else { onNearScroll(); } const scrollDirection = scrollTop - prevScrollTop > 0 ? "down" : "up"; // TODO: Need to clamp the scroll to not jump ahead more than the items loaded. const loadedItems = rows.length; const lastThirdIndex = Math.floor(loadedItems * (2 / 3)); const firstThirdIndex = Math.floor(loadedItems * (1 / 3)); const bottomIdx = Math.floor((scrollTop + offset + vp) / rh); const topIdx = Math.floor((scrollTop + offset) / rh); if ( scrollDirection === "down" && hasNextPage && !loading && bottomIdx - startIndex > lastThirdIndex ) { const pos = (lastThirdIndex + startIndex) * rh - offset - vp; target.scrollTop = pos; setPrevScrollTop(pos); onNextPage(); } else if ( scrollDirection === "up" && hasPrevPage && !loading && topIdx - startIndex < firstThirdIndex ) { console.log("LOADING PREV PAGE"); const pos = (firstThirdIndex + startIndex) * rh - offset; target.scrollTop = pos; setPrevScrollTop(pos); onPrevPage(); } }; function onJump() { const viewport = tableContainerRef.current; if (!viewport) { return; } const scrollTop = viewport.scrollTop; const newPage = Math.floor(scrollTop * ((th - vp) / (h - vp)) * (1 / ph)); setPage(newPage); setOffest(Math.round(newPage * cj)); setPrevScrollTop(scrollTop); } function onNearScroll() { const viewport = tableContainerRef.current; if (!viewport) { return; } const scrollTop = viewport.scrollTop; // next scroll bar page if (scrollTop + offset > (page + 1) * ph) { const nextPage = page + 1; const nextOffset = Math.round(nextPage * cj); const newPrevScrollTop = scrollTop - cj; viewport.scrollTop = prevScrollTop; setPage(nextPage); setOffest(nextOffset); setPrevScrollTop(newPrevScrollTop); } else if (scrollTop + offset < page * ph) { // prev scroll bar page const nextPage = page - 1; const nextOffset = Math.round(nextPage * cj); const newPrevScrollTop = scrollTop + cj; viewport.scrollTop = prevScrollTop; setPage(nextPage); setOffest(nextOffset); setPrevScrollTop(newPrevScrollTop); } else { setPrevScrollTop(scrollTop); } } const items = totalRows; const itemSize = rowHeight; const th = items * itemSize; const h = 33554400; const ph = h / 100; const n = Math.ceil(th / ph); const vp = height; const rh = rowHeight; const cj = (th - h) / (n - 1) > 0 ? (th - h) / (n - 1) : 1; // "jumpiness" coefficient const contentHeight = h > th ? th : h; // virtual pages, not real pages. Unrelated to items entirely. const [page, setPage] = useState(0); const [offset, setOffest] = useState(0); const [prevScrollTop, setPrevScrollTop] = useState(0); const [scrollTop, setScrollTop] = useState( tableContainerRef.current?.scrollTop || 0 ); const [lastLoading, setLastLoading] = useState(loading); if (lastLoading !== loading) { setLastLoading(loading); if (!loading) { tableContainerRef.current!.scrollTop = prevScrollTop; } } // useEffect(() => { // const current = tableContainerRef.current; // if (!current) { // return; // } // current.addEventListener("scroll", handleScroll); // return () => { // current.removeEventListener("scroll", handleScroll); // }; // }, [tableContainerRef.current, handleScroll]); const buffer = vp; const y = scrollTop + offset; let top = Math.floor((y - buffer) / rh); let bottom = Math.ceil((y + vp + buffer) / rh); // top index for items in the viewport top = Math.max(startIndex, top); // bottom index for items in the viewport bottom = Math.min(th / rh, bottom); const renderedRows: ReactNode[] = []; for (let i = top; i <= bottom; ++i) { const d = rows[i - startIndex]; if (!d) { break; } renderedRows.push( rowRenderer(d, { height: rh, top: i * rh - offset, position: "absolute", }) ); } return ( <div className={`${css.container} ${className}`}
/** * A virtual table which uses a cursor to paginate the data. * * onNextPage and onPrevPage are called when the user scrolls to the bottom or top of the table. * * Note: `onNextPage` and `onPrevPage` should pass the cursor of the item that starts the page. * The caller was doing this: https://github.com/vlcn-io/linearite/blob/90bafe2e5890bf5c290585e9b6d6d1a1076e769e/src/pages/List/index.tsx * but this was likely wrong and what caused the jumping. * * Problems with cursoring: * - `onNextPage` is easy. We just fetch from the cursor till limit. E.g., * `source.after(cursor).limit(limit)` * - `onPrevPage` is hard, however. We have to support fetching backwards since we * do not know the cursor that _starts_ the page but only the cursor that _ends_ the previous page. * E.g., `source.before(cursor).limit(limit)`. So Materialite needs to implement `before` and backwards iteration over sources. * - `onPrevPage` is pretty annoying to do in SQL for SQLite sources as it requires reversing a bunch of comparisons and re-preparing statements. E.g., https://github.com/vlcn-io/linearite/commit/90bafe2e5890bf5c290585e9b6d6d1a1076e769e#diff-3a43274e7eed34c4e02ca0957ffd5fbd38efe244b546bc9a4b463a55925ab3f7 * * Cursoring, however, is the most efficient way. Offset based pagination is not efficient since it requires * loading all the data up to the offset. */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/pages/List/VirtualTable-Cursored.tsx#L24-L215
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
VirtualTableBase
function VirtualTableBase<T>({ rowRenderer, width, height, rowHeight, rows, totalRows, startIndex, onPage, loading, className, }: { className?: string; width: string | number; height: number; rowHeight: number; rows: PersistentTreap<T>; totalRows: number; startIndex: number; onPage: (offset: number) => void; loading: boolean; rowRenderer: ( row: T, style: { [key: string]: string | number } ) => React.ReactNode; }) { const tableContainerRef = React.useRef<HTMLDivElement>(null); const handleScroll = (e: React.UIEvent<HTMLDivElement>) => { const target = e.target as HTMLElement; const scrollTop = target.scrollTop; const bottomIdx = Math.floor((scrollTop + offset + vp) / rh); const topIdx = Math.floor((scrollTop + offset) / rh); if (loading) { if (topIdx - startIndex < 0 || bottomIdx - startIndex > rows.size) { e.preventDefault(); target.scrollTop = prevScrollTop; return false; } } setScrollTop(scrollTop); if (Math.abs(scrollTop - prevScrollTop) > vp) { onJump(); } else { onNearScroll(); } const scrollDirection = scrollTop - prevScrollTop > 0 ? "down" : "up"; const loadedItems = rows.size; const lastSixthIndex = Math.floor(loadedItems * (5 / 6)); const firstSixthIndex = Math.floor(loadedItems * (1 / 6)); const hasNextPage = totalRows > loadedItems; const hasPrevPage = startIndex > 0; if ( scrollDirection === "down" && hasNextPage && !loading && bottomIdx - startIndex > lastSixthIndex ) { onPage(topIdx); } else if ( scrollDirection === "up" && hasPrevPage && !loading && topIdx - startIndex < firstSixthIndex ) { onPage(topIdx); } }; function onJump() { const viewport = tableContainerRef.current; if (!viewport) { return; } const scrollTop = viewport.scrollTop; const newPage = Math.floor(scrollTop * ((th - vp) / (h - vp)) * (1 / ph)); setPage(newPage); setOffest(Math.round(newPage * cj)); setPrevScrollTop(scrollTop); } function onNearScroll() { const viewport = tableContainerRef.current; if (!viewport) { return; } const scrollTop = viewport.scrollTop; // next scroll bar page if (scrollTop + offset > (page + 1) * ph) { const nextPage = page + 1; const nextOffset = Math.round(nextPage * cj); const newPrevScrollTop = scrollTop - cj; viewport.scrollTop = prevScrollTop; setPage(nextPage); setOffest(nextOffset); setPrevScrollTop(newPrevScrollTop); } else if (scrollTop + offset < page * ph) { // prev scroll bar page const nextPage = page - 1; const nextOffset = Math.round(nextPage * cj); const newPrevScrollTop = scrollTop + cj; viewport.scrollTop = prevScrollTop; setPage(nextPage); setOffest(nextOffset); setPrevScrollTop(newPrevScrollTop); } else { setPrevScrollTop(scrollTop); } } const items = totalRows; const itemSize = rowHeight; const th = items * itemSize; const h = 33554400; const ph = h / 100; const n = Math.ceil(th / ph); const vp = height; const rh = rowHeight; const cj = (th - h) / (n - 1) > 0 ? (th - h) / (n - 1) : 1; // "jumpiness" coefficient const contentHeight = h > th ? th : h; // virtual pages, not real pages. Unrelated to items entirely. const [page, setPage] = useState(0); const [offset, setOffest] = useState(0); const [prevScrollTop, setPrevScrollTop] = useState(0); const [scrollTop, setScrollTop] = useState( tableContainerRef.current?.scrollTop || 0 ); const [lastLoading, setLastLoading] = useState(loading); if (lastLoading !== loading) { setLastLoading(loading); if (!loading) { tableContainerRef.current!.scrollTop = prevScrollTop; } } const buffer = vp; const y = scrollTop + offset; let top = Math.floor((y - buffer) / rh); let bottom = Math.ceil((y + vp + buffer) / rh); // top index for items in the viewport top = Math.max(startIndex, top); // bottom index for items in the viewport bottom = Math.min(th / rh, bottom); const renderedRows = []; for (let i = top; i <= bottom; ++i) { const d = rows.at(i - startIndex); if (!d) { break; } renderedRows.push( rowRenderer(d, { height: rh, top: i * rh - offset, position: "absolute", }) ); } return ( <div className={`${css.container} ${className}`}
/** * Same as `VirtualTable` but uses offset pagination. * * Offset pagination isn't terribly efficient for SQLite but there are ways around this: * 1. Creating a temp table to index the offsets * 2. Using cursor as a hint to find the offset? * See: https://github.com/vlcn-io/js/issues/27#issuecomment-1751333337 * * Offset pagination works fine in Materialite since our treap knows indices. * * Offset pagination is in some ways a requirement. If the user wants to drag and scroll, * well how do we jump to where they dragged? We can't do this with a cursor since we don't know the * cursor at an arbitrary position. We can do it with offset pagination though. * * The ideal world is probably some combination of offset pagination and cursor pagination. * Cursor when we can, offset when we can't. * * We will only re-fetch if we scroll into or beyond our over-scan region. */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/pages/List/VirtualTable-Offset.tsx#L25-L192
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
VirtualTableBase
function VirtualTableBase<T>({ rowRenderer, width, height, rowHeight, rows, totalRows, startIndex, onPage, hasNextPage, hasPrevPage, loading, className, }: { className?: string; width: string | number; height: number; rowHeight: number; rows: readonly T[]; totalRows: number; startIndex: number; onPage: (offset: number) => void; loading: boolean; hasPrevPage: boolean; hasNextPage: boolean; rowRenderer: ( row: T, style: { [key: string]: string | number } ) => React.ReactNode; }) { const tableContainerRef = React.useRef<HTMLDivElement>(null); const handleScroll = (e: React.UIEvent<HTMLDivElement>) => { const target = e.target as HTMLElement; const scrollTop = target.scrollTop; const bottomIdx = Math.floor((scrollTop + offset + vp) / rh); const topIdx = Math.floor((scrollTop + offset) / rh); if (loading) { if (topIdx - startIndex < 0 || bottomIdx - startIndex > rows.length) { e.preventDefault(); target.scrollTop = prevScrollTop; return false; } } setScrollTop(scrollTop); if (Math.abs(scrollTop - prevScrollTop) > vp) { onJump(); } else { onNearScroll(); } const scrollDirection = scrollTop - prevScrollTop > 0 ? "down" : "up"; const loadedItems = rows.length; const lastSixthIndex = Math.floor(loadedItems * (5 / 6)); const firstSixthIndex = Math.floor(loadedItems * (1 / 6)); if ( scrollDirection === "down" && hasNextPage && !loading && bottomIdx - startIndex > lastSixthIndex ) { onPage(topIdx); } else if ( scrollDirection === "up" && hasPrevPage && !loading && topIdx - startIndex < firstSixthIndex ) { onPage(topIdx); } }; function onJump() { const viewport = tableContainerRef.current; if (!viewport) { return; } const scrollTop = viewport.scrollTop; const newPage = Math.floor(scrollTop * ((th - vp) / (h - vp)) * (1 / ph)); setPage(newPage); setOffest(Math.round(newPage * cj)); setPrevScrollTop(scrollTop); } function onNearScroll() { const viewport = tableContainerRef.current; if (!viewport) { return; } const scrollTop = viewport.scrollTop; // next scroll bar page if (scrollTop + offset > (page + 1) * ph) { const nextPage = page + 1; const nextOffset = Math.round(nextPage * cj); const newPrevScrollTop = scrollTop - cj; viewport.scrollTop = prevScrollTop; setPage(nextPage); setOffest(nextOffset); setPrevScrollTop(newPrevScrollTop); } else if (scrollTop + offset < page * ph) { // prev scroll bar page const nextPage = page - 1; const nextOffset = Math.round(nextPage * cj); const newPrevScrollTop = scrollTop + cj; viewport.scrollTop = prevScrollTop; setPage(nextPage); setOffest(nextOffset); setPrevScrollTop(newPrevScrollTop); } else { setPrevScrollTop(scrollTop); } } const items = totalRows; const itemSize = rowHeight; const th = items * itemSize; const h = 33554400; const ph = h / 100; const n = Math.ceil(th / ph); const vp = height; const rh = rowHeight; const cj = (th - h) / (n - 1) > 0 ? (th - h) / (n - 1) : 1; // "jumpiness" coefficient const contentHeight = h > th ? th : h; // virtual pages, not real pages. Unrelated to items entirely. const [page, setPage] = useState(0); const [offset, setOffest] = useState(0); const [prevScrollTop, setPrevScrollTop] = useState(0); const [scrollTop, setScrollTop] = useState( tableContainerRef.current?.scrollTop || 0 ); const [lastLoading, setLastLoading] = useState(loading); if (lastLoading !== loading) { setLastLoading(loading); if (!loading) { tableContainerRef.current!.scrollTop = prevScrollTop; } } const buffer = vp; const y = scrollTop + offset; let top = Math.floor((y - buffer) / rh); let bottom = Math.ceil((y + vp + buffer) / rh); // top index for items in the viewport top = Math.max(startIndex, top); // bottom index for items in the viewport bottom = Math.min(th / rh, bottom); const renderedRows = []; for (let i = top; i <= bottom; ++i) { const d = rows[i - startIndex]; if (!d) { break; } renderedRows.push( rowRenderer(d, { height: rh, top: i * rh - offset, position: "absolute", }) ); } return ( <div className={`${css.container} ${className}`}
/** * Same as `VirtualTable` but uses offset pagination. * * Offset pagination isn't terribly efficient for SQLite but there are ways around this: * 1. Creating a temp table to index the offsets * 2. Using cursor as a hint to find the offset? * * Offset pagination works fine in Materialite since our treap knows indices. * * Offset pagination is in some ways a requirement. If the user wants to drag and scroll, * well how do we jump to where they dragged? We can't do this with a cursor since we don't know the * cursor at an arbitrary position. We can do it with offset pagination though. * * The ideal world is probably some combination of offset pagination and cursor pagination. * Cursor when we can, offset when we can't. * * We will only re-fetch if we scroll into or beyond our over-scan region. */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/react/src/virtualized/OffsetVirtualTable.tsx#L23-L192
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
PersistentTreap.findIndexByPredicate
findIndexByPredicate(pred: (x: T) => boolean): number { let index = 0; for (const value of inOrderTraversal(this.#root)) { if (pred(value)) { return index; } index += 1; } return -1; }
// TODO: we can do better here. We can `findIndex` based on a provided value in O(logn)
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/ds-and-algos/src/trees-v2/persistent-treap.ts#L97-L108
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
PersistentTreap.findIndexByPredicate
findIndexByPredicate(pred: (x: T) => boolean): number { let index = 0; for (const value of inOrderTraversal(this.root)) { if (pred(value)) { return index; } index += 1; } return -1; }
// TODO: we can do better here. We can `findIndex` based on a provided value in O(logn)
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/ds-and-algos/src/trees/PersistentTreap.ts#L121-L132
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
TreeIterator.prev
prev() { if (this.cursor === null) { const root = this.#tree.root; if (root !== null) { this.#maxNode(root); } } else { if (this.cursor.left === null) { let save: INode<V> | null; do { save = this.cursor; if (this.ancestors.length) { this.cursor = this.ancestors.pop()!; } else { this.cursor = null; break; } } while (this.cursor.left === save); } else { this.ancestors.push(this.cursor); this.#maxNode(this.cursor.left); } } return this.cursor !== null ? this.cursor.data : null; }
// otherwise, returns previous node
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/ds-and-algos/src/trees/TreeBase.ts#L214-L238
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
depth
function depth<T>(node: Node<T> | null): number { if (!node) return 0; return 1 + Math.max(depth(node.left), depth(node.right)); }
// Assuming your treap class is imported as:
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/ds-and-algos/src/trees/__tests__/TreapFastCheck.test.ts#L12-L15
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Materialite.newStatelessSet
newStatelessSet<T>() { const ret = new SetSource<T>(this.#internal); return ret; }
/** * A source that does not retain and values and * only sends them down the stream. * @returns */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L44-L47
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Materialite.newImmutableSortedSet
newImmutableSortedSet<T>(comparator: Comparator<T>) { const ret = new ImmutableSetSource<T>(this.#internal, comparator); return ret; }
/** * A source that retains values in a versioned, immutable, and sorted data structure. * * 1. The retaining of values allows for late pipeline additions to receive all data they may have missed. * 2. The versioning allows for late pipeline additions to receive data from a specific point in time. * 3. Being sorted allows cheaper construction of the final materialized view on pipeline modification if the * order of the view matches the order of the source. * * @param comparator * @returns */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L65-L68
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Materialite.newSortedSet
newSortedSet<T>(comparator: Comparator<T>) { const ret = new MutableSetSource<T>(this.#internal, comparator); return ret; }
/** * A source that retains values in a mutable, sorted data structure. * * 1. The retaining of values allows for late pipeline additions to receive all data they may have missed. * 2. Being sorted allows cheaper construction of the final materialized view on pipeline modification if the * order of the view matches the order of the source. */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L77-L80
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Materialite.newUnorderedSet
newUnorderedSet<K, V>(getKey: KeyFn<V, K>) { const ret = new MutableMapSource<K, V>(this.#internal, getKey); return ret; }
/** * A source that retains values in a mutable, unordered data structure. * * 1. The retaining of values allows for late pipeline additions to receive all data they may have missed. * * The fact that the source is unsorted means that we can build it faster than a sorted source. This is * useful where the source and view will not have the same ordering. * * If source and view will have the same order, use a sorted source. * * If many views will be created from the same source but with many different orderings, * use this source. * * @param getKey * @returns */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L98-L101
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Materialite.compute
compute<T extends any[], TRet>( f: (...args: { [K in keyof T]: T[K] }) => TRet, ...s: { [K in keyof T]: ISignal<T[K]> } ): Thunk<T, TRet> { return new Thunk(f, ...s) as any; }
/** * * @param f * @param signals */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L108-L113
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Materialite.tx
tx(fn: () => void) { if (this.#currentTx === null) { this.#currentTx = this.#version + 1; } else { // nested transaction // just run the function as we're already inside the // scope of a transaction that will handle rollback and commit. fn(); return; } try { fn(); this.#commit(); } catch (e) { this.#rollback(); throw e; } finally { this.#dirtySources.clear(); } }
/** * Run the provided lambda in a transaciton. * Will be committed when the lambda exits * and all incremental computations that depend on modified inputs * will be run. * * An exception to this is in the case of nested transactions. * No incremental computation will run until the outermost transaction * completes. * * If the transaction throws, all pending inputs which were queued will be rolled back. * If a nested transaction throws, all transactions in the stack are rolled back. * * In this way, nesting transactions only exists to allow functions to be ignorant * of what transactions other functions that they call may create. It would be problematic * if creating transactions within transactions failed as it would preclude the use of * libraries that use transactions internally. */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L133-L153
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Index.compact
compact(keys: K[] = []) { function consolidateValues(values: Entry<V>[]): [V, number][] { const consolidated = new TuplableMap<V, number>(); for (const [value, multiplicity] of values) { if (multiplicity === 0) { continue; } const existing = consolidated.get(value); if (existing === undefined) { consolidated.set(value, multiplicity); } else { const sum = existing + multiplicity; if (sum === 0) { consolidated.delete(value); } else { consolidated.set(value, sum); } } } return [...consolidated.entries()]; } // spread `keys` b/c if we do not then when we add below the iterator will continue. const iterableKeys = keys.length != 0 ? keys : [...this.index.keys()]; for (const key of iterableKeys) { const entries = this.index.get(key); if (entries === undefined) { continue; } this.index.delete(key); const consolidated = consolidateValues(entries); if (consolidated.length != 0) { this.index.set(key, consolidated); } } }
// each tuple will have a unique identity according to `Map`.
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/index.ts#L66-L102
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Multiset.consolidate
consolidate(): Multiset<T> { return new Multiset([...this.#toNormalizedMap()], this.eventMetadata); }
// aka normalize
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/multiset.ts#L57-L59
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Multiset._extend
_extend(other: Multiset<T>) { if (!Array.isArray(this.#entries)) { this.#entries = [...this.#entries]; } for (const e of other.entries) { (this.#entries as Entry<T>[]).push(e); } }
// TODO: faster way to extend without converting to an array?
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/multiset.ts#L131-L138
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
inner
const inner = (version: Version) => { for (const collection of this.inputAMessages(version)) { const deltaA = new Index<K, V1>(); for (const [value, mult] of collection.entries) { deltaA.add(getKeyA(value), [value, mult]); } this.#inputAPending.push(deltaA); } for (const collection of this.inputBMessages(version)) { const deltaB = new Index<K, V2>(); for (const [value, mult] of collection.entries) { deltaB.add(getKeyB(value), [value, mult]); } this.#inputBPending.push(deltaB); } // TODO: join should still be able to operate even if one of the inputs is empty... // right? while (this.#inputAPending.length > 0 && this.#inputBPending.length > 0) { const result = new Multiset<JoinResultVariadic<[V1, V2]>>([], null); const deltaA = this.#inputAPending.shift()!; const deltaB = this.#inputBPending.shift()!; result._extend(deltaA.join(this.#indexB)); this.#indexA.extend(deltaA); result._extend(this.#indexA.join(deltaB)); this.#indexB.extend(deltaB); this.output.sendData(version, result.consolidate() as any); this.#indexA.compact(); this.#indexB.compact(); } };
// TODO: how to deal with full re-compute messages
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/graph/ops/JoinOperator.ts#L31-L64
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Operator.pull
pull(msg: Hoisted) { for (const input of this.inputs) { input.pull(msg); } }
/** * If an operator is pulled, it sends the pull * up the stream to its inputs. * @param msg * @returns */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/graph/ops/Operator.ts#L57-L61
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
subtractValues
const subtractValues = (first: Entry<O>[], second: Entry<O>[]) => { const result = new TuplableMap<O, number>(); for (const [v1, m1] of first) { const sum = (result.get(v1) || 0) + m1; if (sum === 0) { result.delete(v1); } else { result.set(v1, sum); } } for (const [v2, m2] of second) { const sum = (result.get(v2) || 0) - m2; if (sum === 0) { result.delete(v2); } else { result.set(v2, sum); } } return result.entries(); };
// TODO: deal with full recompute messages
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/graph/ops/ReduceOperator.ts#L20-L40
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
Thunk.off
off( fn: (value: TRet, version: Version) => void, options: { autoCleanup?: boolean } = { autoCleanup: true } ): void { this.listeners.delete(fn); this.#maybeCleanup(options.autoCleanup || false); }
/** * If there are 0 listeners left after removing the given listener, * the signal is destroyed. * * To opt out of this behavior, pass `autoCleanup: false` * @param listener */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/signal/Thunk.ts#L133-L139
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
MutableMapSource.on
on(fn: (value: Map<K, T>, version: number) => void): () => void { return this.onChange(fn as any); }
// TODO: implement these correctly.
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/sources/MutableMapSource.ts#L135-L137
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
SetSource.add
add(value: T): this { this.#pending.push([value, 1]); this.#materialite.addDirtySource(this.#internal); return this; }
// making delete problematic?
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/sources/StatelessSetSource.ts#L80-L84
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
SetSource.delete
delete(value: T): void { this.#pending.push([value, -1]); this.#materialite.addDirtySource(this.#internal); }
// }
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/sources/StatelessSetSource.ts#L92-L95
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
PersistentTreeView.rematerialize
rematerialize(newLimit: number) { const newView = new PersistentTreeView( this.materialite, this.stream, this.comparator, newLimit ); newView.#min = this.#min; newView.#max = this.#max; newView.#data = this.#data; if (this.#max !== undefined) { this.materialite.tx(() => { newView.reader.pull({ expressions: [ { _tag: "after", comparator: this.comparator, cursor: this.#max, }, ], }); }); } else { this.materialite.tx(() => { newView.reader.pull({ expressions: [] }); }); } // I assume this is reasonable behavior. If you're rematerializing a view you don't need the old thing? this.destroy(); return newView; }
/** * Re-materialize the view but with a new limit. * All other params remain the same. * Returns a new view. * The view will ask the upstream for data _after_ the current view's max */
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/views/PersistentTreeView.ts#L53-L86
e08c1fa176883a51296d7c2c3a86c539c0e72eab
materialite
github_2023
vlcn-io
typescript
PersistentTreeView.run
protected run(version: Version) { const collections = this.reader.drain(version); let changed = false; let newData = this.#data; for (const c of collections) { if (c.eventMetadata?.cause === "full_recompute") { newData = new PersistentTreap<T>(this.comparator); changed = true; } [changed, newData] = this.#sink(c, newData) || changed; } this.#data = newData; if (changed) { this.notify(newData, version); } }
// TODO: notify on empty?
https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/views/PersistentTreeView.ts#L93-L109
e08c1fa176883a51296d7c2c3a86c539c0e72eab
azure-openai-rag-workshop
github_2023
Azure-Samples
typescript
MessageBuilder.constructor
constructor(systemContent: string, chatgptModel: string) { this.model = chatgptModel; this.messages = [{ role: 'system', content: systemContent }]; this.tokens = this.getTokenCountFromMessages(this.messages[this.messages.length - 1], this.model); }
/** * A class for building and managing messages in a chat conversation. * @param {string} systemContent The initial system message content. * @param {string} chatgptModel The name of the ChatGPT model. */
https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L15-L19
039f3f8bd106f3766f0dc1408f67289d0c1f8121
azure-openai-rag-workshop
github_2023
Azure-Samples
typescript
MessageBuilder.appendMessage
appendMessage(role: AIChatRole, content: string, index = 1) { this.messages.splice(index, 0, { role, content }); this.tokens += this.getTokenCountFromMessages(this.messages[index], this.model); }
/** * Append a new message to the conversation. * @param {AIChatRole} role The role of the message sender. * @param {string} content The content of the message. * @param {number} index The index at which to insert the message. */
https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L27-L30
039f3f8bd106f3766f0dc1408f67289d0c1f8121
azure-openai-rag-workshop
github_2023
Azure-Samples
typescript
MessageBuilder.popMessage
popMessage(): AIChatMessage | undefined { const message = this.messages.pop(); if (message) { this.tokens -= this.getTokenCountFromMessages(message, this.model); } return message; }
/** * Get and remove the last message from the conversation. * @returns {AIChatMessage} The removed message. */
https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L36-L42
039f3f8bd106f3766f0dc1408f67289d0c1f8121
azure-openai-rag-workshop
github_2023
Azure-Samples
typescript
MessageBuilder.getMessages
getMessages(): BaseMessage[] { return this.messages.map((message) => { if (message.role === 'system') { return new SystemMessage(message.content); } else if (message.role === 'assistant') { return new AIMessage(message.content); } else { return new HumanMessage(message.content); } }); }
/** * Get the messages in the conversation in LangChain format. * @returns {BaseMessage[]} The messages. */
https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L48-L58
039f3f8bd106f3766f0dc1408f67289d0c1f8121
azure-openai-rag-workshop
github_2023
Azure-Samples
typescript
MessageBuilder.getTokenCountFromMessages
private getTokenCountFromMessages(message: AIChatMessage, model: string): number { // GPT3.5 tiktoken model name is slightly different than Azure OpenAI model name const tiktokenModel = model.replace('gpt-35', 'gpt-3.5') as TiktokenModel; const encoder = encoding_for_model(tiktokenModel); let tokens = 2; // For "role" and "content" keys for (const value of Object.values(message)) { tokens += encoder.encode(value).length; } encoder.free(); return tokens; }
/** * Calculate the number of tokens required to encode a message. * @param {AIChatMessage} message The message to encode. * @param {string} model The name of the model to use for encoding. * @returns {number} The total number of tokens required to encode the message. * @example * const message = { role: 'user', content: 'Hello, how are you?' }; * const model = 'gpt-3.5-turbo'; * getTokenCountFromMessages(message, model); * // output: 11 */
https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L71-L81
039f3f8bd106f3766f0dc1408f67289d0c1f8121
awesome-leetcode-resources
github_2023
ashishps1
typescript
FastAndSlowPointers.hasCycleHashSetApproach
hasCycleHashSetApproach(head: ListNode | null): boolean { const visited = new Set<ListNode>(); let current = head; while (current) { if (visited.has(current)) { return true; } visited.add(current); current = current.next; } return false; }
// LeetCode 141 - Linked List Cycle (HashSet Approach)
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L11-L22
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
FastAndSlowPointers.hasCycleFastAndSlowPointersApproach
hasCycleFastAndSlowPointersApproach(head: ListNode | null): boolean { if (!head || !head.next) return false; let slow: ListNode | null = head; let fast: ListNode | null = head; while (fast && fast.next) { slow = slow!.next; fast = fast.next.next; if (slow === fast) return true; } return false; }
// LeetCode 141 - Linked List Cycle (Fast and Slow Pointer Approach)
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L25-L35
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
FastAndSlowPointers.middleNodeCountingApproach
middleNodeCountingApproach(head: ListNode | null): ListNode | null { let count = 0; let current = head; while (current) { count++; current = current.next; } current = head; for (let i = 0; i < Math.floor(count / 2); i++) { current = current!.next; } return current; }
// LeetCode 876 - Middle of the Linked List (Counting Approach)
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L38-L50
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
FastAndSlowPointers.middleNodeFastAndSlowPointerApproach
middleNodeFastAndSlowPointerApproach(head: ListNode | null): ListNode | null { let slow = head, fast = head; while (fast && fast.next) { slow = slow!.next; fast = fast.next.next; } return slow; }
// LeetCode 876 - Middle of the Linked List (Fast and Slow Pointer Approach)
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L53-L60
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
FastAndSlowPointers.getSumOfSquares
getSumOfSquares(n: number): number { return String(n).split('').reduce((sum, digit) => sum + Number(digit) ** 2, 0); }
// LeetCode 202 - Happy Number (HashSet Approach)
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L63-L65
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
FastAndSlowPointers.isHappyFastAndSlowPointersApproach
isHappyFastAndSlowPointersApproach(n: number): boolean { let slow = n; let fast = this.getSumOfSquares(n); while (fast !== 1 && slow !== fast) { slow = this.getSumOfSquares(slow); fast = this.getSumOfSquares(this.getSumOfSquares(fast)); } return fast === 1; }
// LeetCode 202 - Happy Number (Fast and Slow Pointer Approach)
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L77-L85
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
SlidingWindow.findMaxAverageBruteForce
findMaxAverageBruteForce(nums: number[], k: number): number { let maxAvg = -Infinity; for (let i = 0; i <= nums.length - k; i++) { let sum = 0; for (let j = i; j < i + k; j++) { sum += nums[j]; } maxAvg = Math.max(maxAvg, sum / k); } return maxAvg; }
// Brute Force Approach - O(n * k)
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/slidingWindow.ts#L3-L14
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
SlidingWindow.findMaxAverageSlidingWindow
findMaxAverageSlidingWindow(nums: number[], k: number): number { let sum = nums.slice(0, k).reduce((a, b) => a + b, 0); let maxSum = sum; for (let i = k; i < nums.length; i++) { sum += nums[i] - nums[i - k]; maxSum = Math.max(maxSum, sum); } return maxSum / k; }
// Sliding Window Approach - O(n)
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/slidingWindow.ts#L17-L27
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
SlidingWindow.lengthOfLongestSubstringSlidingWindow
lengthOfLongestSubstringSlidingWindow(s: string): number { let seen = new Set<string>(); let maxLength = 0, left = 0; for (let right = 0; right < s.length; right++) { while (seen.has(s[right])) { seen.delete(s[left]); left++; } seen.add(s[right]); maxLength = Math.max(maxLength, right - left + 1); } return maxLength; }
// Sliding Window for Longest Substring Without Repeating Characters
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/slidingWindow.ts#L30-L43
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
SlidingWindow.lengthOfLongestSubstringSlidingWindowFrequencyArray
lengthOfLongestSubstringSlidingWindowFrequencyArray(s: string): number { let freq = new Array(128).fill(0); let maxLength = 0, left = 0; for (let right = 0; right < s.length; right++) { freq[s.charCodeAt(right)]++; while (freq[s.charCodeAt(right)] > 1) { freq[s.charCodeAt(left)]--; left++; } maxLength = Math.max(maxLength, right - left + 1); } return maxLength; }
// Sliding Window using Frequency Array
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/slidingWindow.ts#L46-L61
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
TopKElements.kLargestElementsSortingApproach
kLargestElementsSortingApproach(nums: number[], k: number): number[] { nums.sort((a, b) => b - a); return nums.slice(0, k); }
// K Largest Elements using Sorting
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L4-L7
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
TopKElements.kLargestElementsMaxHeapApproach
kLargestElementsMaxHeapApproach(nums: number[], k: number): number[] { const maxHeap = new MaxPriorityQueue({ priority: (x: number) => x }); for (const num of nums) { maxHeap.enqueue(num); } const result: number[] = []; for (let i = 0; i < k; i++) { result.push(maxHeap.dequeue().element); } return result; }
// K Largest Elements using Max Heap
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L10-L20
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
TopKElements.kLargestElementsMinHeapApproach
kLargestElementsMinHeapApproach(nums: number[], k: number): number[] { const minHeap = new MinPriorityQueue({ priority: (x: number) => x }); for (let i = 0; i < k; i++) { minHeap.enqueue(nums[i]); } for (let i = k; i < nums.length; i++) { minHeap.enqueue(nums[i]); if (minHeap.size() > k) { minHeap.dequeue(); } } const result: number[] = []; for (let i = 0; i < k; i++) { result.push(minHeap.dequeue().element); } return result; }
// K Largest Elements using Min Heap
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L23-L39
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
TopKElements.topKFrequentElementsSortingApproach
topKFrequentElementsSortingApproach(nums: number[], k: number): number[] { const frequencyMap = new Map<number, number>(); nums.forEach(num => frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1)); return Array.from(frequencyMap) .sort((a, b) => b[1] - a[1]) .slice(0, k) .map(entry => entry[0]); }
// Top K Frequent Elements using Sorting
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L42-L49
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
TopKElements.topKFrequentElementsMinHeapApproach
topKFrequentElementsMinHeapApproach(nums: number[], k: number): number[] { const frequencyMap = new Map<number, number>(); nums.forEach(num => frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1)); const minHeap = new MinPriorityQueue({ priority: (x: [number, number]) => x[1] }); frequencyMap.forEach((value, key) => { minHeap.enqueue([key, value]); if (minHeap.size() > k) { minHeap.dequeue(); } }); const result: number[] = []; for (let i = 0; i < k; i++) { result.push(minHeap.dequeue().element[0]); } return result; }
// Top K Frequent Elements using Min Heap
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L52-L67
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
TopKElements.getDistance
getDistance(point: number[]): number { return point[0] ** 2 + point[1] ** 2; }
// K Closest Points to Origin using Max Heap
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L70-L72
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
TwoPointers.moveZeroesTwoPointers
moveZeroesTwoPointers(nums: number[]): void { let left = 0; // Pointer for placing non-zero elements // Iterate with right pointer for (let right = 0; right < nums.length; right++) { if (nums[right] !== 0) { // Swap elements if right pointer finds a non-zero [nums[left], nums[right]] = [nums[right], nums[left]]; left++; // Move left pointer forward } } }
// Move Zeroes using Two Pointers
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/twoPointers.ts#L3-L14
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
TwoPointers.maxAreaBruteForce
maxAreaBruteForce(height: number[]): number { let maxArea = 0; let n = height.length; // Check all pairs (i, j) for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { // Compute the minimum height and width let minHeight = Math.min(height[i], height[j]); let width = j - i; let area = minHeight * width; // Compute water contained maxArea = Math.max(maxArea, area); // Update max water } } return maxArea; }
// Brute Force approach for Container with Most Water
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/twoPointers.ts#L17-L33
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
awesome-leetcode-resources
github_2023
ashishps1
typescript
TwoPointers.maxAreaTwoPointers
maxAreaTwoPointers(height: number[]): number { let left = 0, right = height.length - 1; let maxArea = 0; // Move pointers toward each other while (left < right) { let width = right - left; // Distance between lines let minHeight = Math.min(height[left], height[right]); // Compute height let area = minHeight * width; // Compute water contained maxArea = Math.max(maxArea, area); // Update max water // Move the pointer pointing to the shorter height if (height[left] < height[right]) { left++; // Move left pointer forward } else { right--; // Move right pointer backward } } return maxArea; }
// Two Pointers approach for Container with Most Water
https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/twoPointers.ts#L36-L56
c4a4f662ee6e41ae2be1c1c638e76152d6f3751e
openapi-devtools
github_2023
AndrewWalsh
typescript
pruneRouter
const pruneRouter = ( node: RadixNode<RouteData>, parts: Array<string> ): void => { if (!parts.length || !node.children.size) return; const isLast = parts.length === 1; const part = parts[0]; const matchAny = isParameter(part); if (!matchAny && !node.children.has(part)) return; if (!isLast) { if (matchAny) { for (const child of node.children.values()) { pruneRouter(child, parts.slice(1)); } } else if (node.children.has(part)) { const child = node.children.get(part)!; if (child) { pruneRouter(child, parts.slice(1)); } } } const noChildren = node.children.get(part)?.children.size === 0; const noData = !node.children.get(part)?.data; if (noChildren && noData) { node.children.delete(part); } };
/** * When you remove an item in radix3, it only removes the data * We need to remove the node itself so that lookups won't match with it */
https://github.com/AndrewWalsh/openapi-devtools/blob/e26c20b3a9b8e2fa1f2d6e4d525e04f4d1ed0e27/src/lib/store-helpers/prune-router.ts#L9-L36
e26c20b3a9b8e2fa1f2d6e4d525e04f4d1ed0e27
openapi-devtools
github_2023
AndrewWalsh
typescript
remove
function remove(ctx: RadixRouterContext, path: string) { let success = false; const sections = path.split("/"); let node = ctx.rootNode; for (const section of sections) { // @ts-expect-error tempfile node = node.children.get(section); if (!node) { return success; } } if (node.data) { const lastSection = sections[-1]; node.data = null; if (node.children.size === 0) { const parentNode = node.parent; // @ts-expect-error tempfile parentNode.children.delete(lastSection); // @ts-expect-error tempfile parentNode.wildcardChildNode = null; // @ts-expect-error tempfile parentNode.placeholderChildNode = null; } success = true; } return success; }
// This can be removed when https://github.com/unjs/radix3/pull/73 is fixed
https://github.com/AndrewWalsh/openapi-devtools/blob/e26c20b3a9b8e2fa1f2d6e4d525e04f4d1ed0e27/src/lib/store-helpers/remove.ts#L5-L34
e26c20b3a9b8e2fa1f2d6e4d525e04f4d1ed0e27
LLOneBot
github_2023
LLOneBot
typescript
RequestUtil.HttpsGetCookies
static async HttpsGetCookies(url: string): Promise<{ [key: string]: string }> { const client = url.startsWith('https') ? https : http return new Promise((resolve, reject) => { client.get(url, (res) => { let cookies: { [key: string]: string } = {} const handleRedirect = (res: http.IncomingMessage) => { if (res.statusCode === 301 || res.statusCode === 302) { if (res.headers.location) { const redirectUrl = new URL(res.headers.location, url) RequestUtil.HttpsGetCookies(redirectUrl.href).then((redirectCookies) => { // 合并重定向过程中的cookies //log('redirectCookies', redirectCookies) cookies = { ...cookies, ...redirectCookies } resolve(cookies) }) } else { resolve(cookies) } } else { resolve(cookies) } } res.on('data', () => { }) // Necessary to consume the stream res.on('end', () => { handleRedirect(res) }) if (res.headers['set-cookie']) { //log('set-cookie', url, res.headers['set-cookie']) res.headers['set-cookie'].forEach((cookie) => { const parts = cookie.split(';')[0].split('=') const key = parts[0] const value = parts[1] if (key && value && key.length > 0 && value.length > 0) { cookies[key] = value } }) } }).on('error', (err) => { reject(err) }) }) }
// 适用于获取服务器下发cookies时获取,仅GET
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/common/utils/request.ts#L7-L48
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
RequestUtil.HttpGetJson
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: unknown, headers: Record<string, string> = {}, isJsonRet: boolean = true, isArgJson: boolean = true): Promise<T> { const option = new URL(url) const protocol = url.startsWith('https://') ? https : http const options = { hostname: option.hostname, port: option.port, path: option.href, method: method, headers: headers } return new Promise((resolve, reject) => { const req = protocol.request(options, (res: Dict) => { let responseBody = '' res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString() }) res.on('end', () => { try { if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { if (isJsonRet) { const responseJson = JSON.parse(responseBody) resolve(responseJson as T) } else { resolve(responseBody as T) } } else { reject(new Error(`Unexpected status code: ${res.statusCode}`)) } } catch (parseError) { reject(parseError) } }) }) req.on('error', (error) => { reject(error) }) if (method === 'POST' || method === 'PUT' || method === 'PATCH') { if (isArgJson) { req.write(JSON.stringify(data)) } else { req.write(data) } } req.end() }) }
// 请求和回复都是JSON data传原始内容 自动编码json
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/common/utils/request.ts#L51-L98
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
RequestUtil.HttpGetText
static async HttpGetText(url: string, method: string = 'GET', data?: unknown, headers: Record<string, string> = {}) { return this.HttpGetJson<string>(url, method, data, headers, false, false) }
// 请求返回都是原始内容
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/common/utils/request.ts#L101-L103
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
LimitedHashTable.getHeads
getHeads(size: number): { key: K, value: V }[] | undefined { const keyList = this.getKeyList() if (keyList.length === 0) { return undefined } const result: { key: K; value: V }[] = [] const listSize = Math.min(size, keyList.length) for (let i = 0; i < listSize; i++) { const key = keyList[listSize - i] result.push({ key, value: this.keyToValue.get(key)! }) } return result }
//获取最近刚写入的几个值
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/common/utils/table.ts#L58-L70
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
onLoad
function onLoad() { if (!existsSync(DATA_DIR)) { mkdirSync(DATA_DIR, { recursive: true }) } if (!existsSync(LOG_DIR)) { mkdirSync(LOG_DIR) } if (!existsSync(TEMP_DIR)) { mkdirSync(TEMP_DIR) } const dbDir = path.join(DATA_DIR, 'database') if (!existsSync(dbDir)) { mkdirSync(dbDir) } const ctx = new Context() ctx.plugin(NTQQFileApi) ctx.plugin(NTQQFileCacheApi) ctx.plugin(NTQQFriendApi) ctx.plugin(NTQQGroupApi) ctx.plugin(NTQQMsgApi) ctx.plugin(NTQQUserApi) ctx.plugin(NTQQWebApi) ctx.plugin(NTQQSystemApi) ctx.plugin(Database) let started = false ipcMain.handle(CHANNEL_CHECK_VERSION, async () => { return checkNewVersion() }) ipcMain.handle(CHANNEL_UPDATE, async () => { return upgradeLLOneBot() }) ipcMain.handle(CHANNEL_SELECT_FILE, async () => { const selectPath = new Promise<string>((resolve, reject) => { dialog .showOpenDialog({ title: '请选择ffmpeg', properties: ['openFile'], buttonLabel: '确定', }) .then((result) => { log('选择文件', result) if (!result.canceled) { const _selectPath = path.join(result.filePaths[0]) resolve(_selectPath) } else { resolve('') } }) .catch((err) => { reject(err) }) }) try { return await selectPath } catch (e) { log('选择文件出错', e) return '' } }) ipcMain.handle(CHANNEL_ERROR, async () => { const ffmpegOk = await checkFfmpeg(getConfigUtil().getConfig().ffmpeg) llonebotError.ffmpegError = ffmpegOk ? '' : '没有找到 FFmpeg, 音频只能发送 WAV 和 SILK, 视频尺寸可能异常' const { httpServerError, wsServerError, otherError, ffmpegError } = llonebotError let error = `${otherError}\n${httpServerError}\n${wsServerError}\n${ffmpegError}` error = error.replace('\n\n', '\n') error = error.trim() log('查询 LLOneBot 错误信息', error) return error }) ipcMain.handle(CHANNEL_GET_CONFIG, async () => { const config = getConfigUtil().getConfig() return config }) ipcMain.handle(CHANNEL_SET_CONFIG, (_event, ask: boolean, config: LLOBConfig) => { return new Promise<boolean>(resolve => { if (!ask) { getConfigUtil().setConfig(config) log('配置已更新', config) if (started) { ctx.parallel('llob/config-updated', config) } resolve(true) return } dialog .showMessageBox(mainWindow!, { type: 'question', buttons: ['确认', '取消'], defaultId: 0, // 默认选中的按钮,0 代表第一个按钮,即 "确认" title: '确认保存', message: '是否保存?', detail: 'LLOneBot配置已更改,是否保存?', }) .then((result) => { if (result.response === 0) { getConfigUtil().setConfig(config) log('配置已更新', config) if (started) { ctx.parallel('llob/config-updated', config) } resolve(true) } }) .catch((err) => { log('保存设置询问弹窗错误', err) resolve(false) }) }) }) ipcMain.on(CHANNEL_LOG, (_event, arg) => { log(arg) }) const intervalId = setInterval(async () => { const self = Object.assign(selfInfo, { uin: globalThis.authData?.uin, uid: globalThis.authData?.uid, online: true }) if (self.uin) { clearInterval(intervalId) log('process pid', process.pid) const config = getConfigUtil().getConfig() if (config.enableLLOB && (config.satori.enable || config.ob11.enable)) { startHook() await ctx.sleep(800) } else { llonebotError.otherError = 'LLOneBot 未启动' log('LLOneBot 开关设置为关闭,不启动 LLOneBot') return } ctx.plugin(Log, { enable: config.log!, filename: logFileName }) ctx.plugin(SQLiteDriver, { path: path.join(dbDir, `${selfInfo.uin}.db`) }) ctx.plugin(Store, { msgCacheExpire: config.msgCacheExpire! * 1000 }) ctx.plugin(Core, config) if (config.ob11.enable) { ctx.plugin(OneBot11Adapter, { ...config.ob11, heartInterval: config.heartInterval, token: config.token!, debug: config.debug!, musicSignUrl: config.musicSignUrl, enableLocalFile2Url: config.enableLocalFile2Url!, ffmpeg: config.ffmpeg, }) } if (config.satori.enable) { ctx.plugin(SatoriAdapter, { ...config.satori, ffmpeg: config.ffmpeg, }) } ctx.start() started = true llonebotError.otherError = '' } }, 500) }
// 加载插件时触发
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/main/main.ts#L48-L227
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
onBrowserWindowCreated
function onBrowserWindowCreated(window: BrowserWindow) { if (window.id === 2) { mainWindow = window } }
// 创建窗口时触发
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/main/main.ts#L230-L234
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
secondCallback
const secondCallback = () => { eventId = registerReceiveHook<R>(options.cbCmd!, (payload) => { if (options.cmdCB) { if (!options.cmdCB(payload, result)) { return } } removeReceiveHook(eventId) clearTimeout(timeoutId) resolve(payload) }) }
// 这里的callback比较特殊,QQ后端先返回是否调用成功,再返回一条结果数据
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/ntcall.ts#L169-L180
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
NTQQFileApi.uploadFile
async uploadFile(filePath: string, elementType = ElementType.Pic, elementSubType = 0) { const fileMd5 = await calculateFileMD5(filePath) let fileName = path.basename(filePath) if (!fileName.includes('.')) { const ext = (await this.getFileType(filePath))?.ext fileName += ext ? '.' + ext : '' } const mediaPath = await invoke(NTMethod.MEDIA_FILE_PATH, [{ path_info: { md5HexStr: fileMd5, fileName: fileName, elementType: elementType, elementSubType, thumbSize: 0, needCreate: true, downloadType: 1, file_uuid: '', }, }]) await copyFile(filePath, mediaPath) const fileSize = (await stat(filePath)).size return { md5: fileMd5, fileName, path: mediaPath, fileSize, } }
/** 上传文件到 QQ 的文件夹 */
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/api/file.ts#L67-L94
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
NTQQFriendApi.getFriends
async getFriends() { const res = await invoke<{ data: { categoryId: number categroyName: string categroyMbCount: number buddyList: Friend[] }[] }>('getBuddyList', [], { className: NTClass.NODE_STORE_API, cbCmd: ReceiveCmdS.FRIENDS, afterFirstCmd: false }) return res.data.flatMap(e => e.buddyList) }
/** 大于或等于 26702 应使用 getBuddyV2 */
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/api/friend.ts#L18-L32
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
NTQQFriendApi.getBuddyIdMap
async getBuddyIdMap(refresh = false): Promise<Map<string, string>> { const retMap: Map<string, string> = new Map() const data = await invoke<{ buddyCategory: CategoryFriend[] userSimpleInfos: Record<string, SimpleInfo> }>( 'getBuddyList', [refresh], { className: NTClass.NODE_STORE_API, cbCmd: ReceiveCmdS.FRIENDS, afterFirstCmd: false, } ) for (const item of Object.values(data.userSimpleInfos)) { if (retMap.size > 5000) { break } retMap.set(item.uid!, item.uin!) } return retMap }
/** uid -> uin */
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/api/friend.ts#L62-L83
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
NTQQGroupApi.banMember
async banMember(groupCode: string, memList: Array<{ uid: string, timeStamp: number }>) { return await invoke(NTMethod.MUTE_MEMBER, [{ groupCode, memList }]) }
/** timeStamp为秒数, 0为解除禁言 */
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/api/group.ts#L134-L136
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
SendForwardMsg.handleForwardNode
private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[]): Promise<Response> { const selfPeer = { chatType: ChatType.C2C, peerUid: selfInfo.uid, } const nodeMsgIds: { msgId: string, peer: Peer }[] = [] // 先判断一遍是不是id和自定义混用 for (const messageNode of messageNodes) { // 一个node表示一个人的消息 const nodeId = messageNode.data.id // 有nodeId表示一个子转发消息卡片 if (nodeId) { const nodeMsg = await this.ctx.store.getMsgInfoByShortId(+nodeId) if (!nodeMsg) { this.ctx.logger.warn('转发消息失败,未找到消息', nodeId) continue } nodeMsgIds.push(nodeMsg) } else { // 自定义的消息 // 提取消息段,发给自己生成消息id try { const { sendElements, deleteAfterSentFiles } = await createSendElements( this.ctx, messageNode.data.content as OB11MessageData[], destPeer ) this.ctx.logger.info('开始生成转发节点', sendElements) const sendElementsSplit: SendMessageElement[][] = [] let splitIndex = 0 for (const ele of sendElements) { if (!sendElementsSplit[splitIndex]) { sendElementsSplit[splitIndex] = [] } if (ele.elementType === ElementType.File || ele.elementType === ElementType.Video) { if (sendElementsSplit[splitIndex].length > 0) { splitIndex++ } sendElementsSplit[splitIndex] = [ele] splitIndex++ } else { sendElementsSplit[splitIndex].push(ele) } } this.ctx.logger.info('分割后的转发节点', sendElementsSplit) for (const eles of sendElementsSplit) { const nodeMsg = await this.ctx.app.sendMessage(this.ctx, selfPeer, eles, []) if (!nodeMsg) { this.ctx.logger.warn('转发节点生成失败', eles) continue } nodeMsgIds.push({ msgId: nodeMsg.msgId, peer: selfPeer }) await this.ctx.sleep(300) } deleteAfterSentFiles.map(path => unlink(path)) } catch (e) { this.ctx.logger.error('生成转发消息节点失败', e) } } } // 检查srcPeer是否一致,不一致则需要克隆成自己的消息, 让所有srcPeer都变成自己的,使其保持一致才能够转发 const nodeMsgArray: RawMessage[] = [] let srcPeer: Peer let needSendSelf = false for (const { msgId, peer } of nodeMsgIds) { const nodeMsg = (await this.ctx.ntMsgApi.getMsgsByMsgId(peer, [msgId])).msgList[0] srcPeer ??= { chatType: nodeMsg.chatType, peerUid: nodeMsg.peerUid } if (srcPeer.peerUid !== nodeMsg.peerUid) { needSendSelf = true } nodeMsgArray.push(nodeMsg) } let retMsgIds: string[] = [] if (needSendSelf) { for (const msg of nodeMsgArray) { if (msg.peerUid === selfPeer.peerUid) { retMsgIds.push(msg.msgId) continue } const clonedMsg = await this.cloneMsg(msg) if (clonedMsg) retMsgIds.push(clonedMsg.msgId) } } else { retMsgIds = nodeMsgArray.map(msg => msg.msgId) } if (retMsgIds.length === 0) { throw Error('转发消息失败,节点为空') } const msg = await this.ctx.ntMsgApi.multiForwardMsg(srcPeer!, destPeer, retMsgIds) const resid = JSON.parse(msg.elements[0].arkElement!.bytesData).meta.detail.resid const msgShortId = this.ctx.store.createMsgShortId({ chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId) return { message_id: msgShortId, forward_id: resid } }
// 返回一个合并转发的消息id
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/onebot11/action/go-cqhttp/SendForwardMsg.ts#L157-L256
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
buildHostListItem
const buildHostListItem = (type: HostsType, host: string, index: number, inputAttrs = {}) => { const dom = { container: document.createElement('setting-item'), input: document.createElement('input'), inputContainer: document.createElement('div'), deleteBtn: document.createElement('setting-button'), } dom.container.classList.add('setting-host-list-item') dom.container.dataset.direction = 'row' Object.assign(dom.input, inputAttrs) dom.input.classList.add('q-input__inner') dom.input.type = 'url' dom.input.value = host dom.input.addEventListener('input', () => { ob11Config[type][index] = dom.input.value }) dom.inputContainer.classList.add('q-input') dom.inputContainer.appendChild(dom.input) dom.deleteBtn.innerHTML = '删除' dom.deleteBtn.dataset.type = 'secondary' dom.deleteBtn.addEventListener('click', () => { ob11Config[type].splice(index, 1) initReverseHost(type) }) dom.container.appendChild(dom.inputContainer) dom.container.appendChild(dom.deleteBtn) return dom.container }
// 生成反向地址列表
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/renderer/index.ts#L279-L310
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
LLOneBot
github_2023
LLOneBot
typescript
checkVersionFunc
async function checkVersionFunc(info: CheckVersion) { const titleDom = view.querySelector<HTMLSpanElement>('#llonebot-update-title')! const buttonDom = view.querySelector<HTMLButtonElement>('#llonebot-update-button')! if (info.version === '') { titleDom.innerHTML = `当前版本为 v${version},检查更新失败` buttonDom.innerHTML = '点击重试' buttonDom.addEventListener('click', async () => { window.llonebot.checkVersion().then(checkVersionFunc) }, { once: true }) } else if (!info.result) { titleDom.innerHTML = '当前已是最新版本 v' + version buttonDom.innerHTML = '无需更新' } else { titleDom.innerHTML = `当前版本为 v${version},最新版本为 v${info.version}` buttonDom.innerHTML = '点击更新' buttonDom.dataset.type = 'primary' const update = async () => { buttonDom.innerHTML = '正在更新中...' const result = await window.llonebot.updateLLOneBot() if (result) { buttonDom.innerHTML = '更新完成,请重启' } else { buttonDom.innerHTML = '更新失败,前往仓库下载' } buttonDom.removeEventListener('click', update) } buttonDom.addEventListener('click', update) } }
// 更新逻辑
https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/renderer/index.ts#L435-L467
17e8b69a1df7c569cb245d6dc5ad2881e9db1b16
Sistema-Anti-Fraude-Electoral
github_2023
Las-Fuerzas-Del-Cielo
typescript
validarFiscalGeneral
async function validarFiscalGeneral(fiscalId: string): Promise<boolean> { // Lógica para verificar en la base de datos si el fiscal es general // Ejemplo: // const fiscal = await FiscalModel.findById(fiscalId); // return fiscal && fiscal.tipo === 'general'; return true; // Simulación, reemplazar con la lógica real }
// Aquí irían las implementaciones de las funciones auxiliares
https://github.com/Las-Fuerzas-Del-Cielo/Sistema-Anti-Fraude-Electoral/blob/051da907b8ae468060a754a163cda1b0372f8211/api/src/controllers/voting-tables.ts#L89-L95
051da907b8ae468060a754a163cda1b0372f8211
Sistema-Anti-Fraude-Electoral
github_2023
Las-Fuerzas-Del-Cielo
typescript
listener
const listener: typeof handler = (event) => savedHandler.current(event);
// Create event listener that calls handler function stored in ref
https://github.com/Las-Fuerzas-Del-Cielo/Sistema-Anti-Fraude-Electoral/blob/051da907b8ae468060a754a163cda1b0372f8211/frontend/src/hooks/utils/use-event-listener.tsx#L65-L65
051da907b8ae468060a754a163cda1b0372f8211
DevToolboxWeb
github_2023
YourAverageTechBro
typescript
encodeBase64
const encodeBase64 = (inputString: string) => // Use the btoa function to encode the string to Base64 btoa(inputString);
// Encode a string to Base64
https://github.com/YourAverageTechBro/DevToolboxWeb/blob/d5e14628db174c0dc1a9a4249efe85536be79067/src/app/tools/base64encoder/Base64EncoderClientComponent.tsx#L53-L55
d5e14628db174c0dc1a9a4249efe85536be79067
DevToolboxWeb
github_2023
YourAverageTechBro
typescript
decodeBase64
const decodeBase64 = (base64String: string) => // Use the atob function to decode the Base64 string atob(base64String);
// Decode a Base64 string to its original form
https://github.com/YourAverageTechBro/DevToolboxWeb/blob/d5e14628db174c0dc1a9a4249efe85536be79067/src/app/tools/base64encoder/Base64EncoderClientComponent.tsx#L58-L60
d5e14628db174c0dc1a9a4249efe85536be79067
DevToolboxWeb
github_2023
YourAverageTechBro
typescript
toHex
const toHex = (value: number) => { const hex = value.toString(16); return hex.length === 1 ? `0${hex}` : hex; };
// Convert the RGB values to hexadecimal and pad with zeros if needed
https://github.com/YourAverageTechBro/DevToolboxWeb/blob/d5e14628db174c0dc1a9a4249efe85536be79067/src/app/tools/color-converter/ColorConverterComponent.tsx#L68-L71
d5e14628db174c0dc1a9a4249efe85536be79067
velite
github_2023
zce
typescript
timestamp
const timestamp = () => s .custom<string | undefined>(i => i === undefined || typeof i === 'string') .transform<string>(async (value, { meta, addIssue }) => { if (value != null) { addIssue({ fatal: false, code: 'custom', message: '`s.timestamp()` schema will resolve the value from `git log -1 --format=%cd`' }) } const { stdout } = await execAsync(`git log -1 --format=%cd ${meta.path}`) return new Date(stdout || Date.now()).toISOString() })
// refer to https://velite.js.org/guide/last-modified#based-on-git-timestamp for more details
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/examples/nextjs/velite.config.ts#L26-L35
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
load
const load = async (config: Config, path: string, schema: Schema, changed?: string): Promise<VeliteFile> => { path = normalize(path) if (changed != null && path !== changed) { const exists = VeliteFile.get(path) // skip file if changed file not match if (exists) return exists } const file = await VeliteFile.create({ path, config }) // may be one or more records in one file, such as yaml array or json array const isArr = Array.isArray(file.records) const list = isArr ? file.records : [file.records] const parsed = await Promise.all( list.map(async (data, index) => { // push index in path if file is array const path = isArr ? [index] : [] const ctx: ParseContext = { common: { issues: [], async: true }, path, meta: file as ZodMeta, data, parent: null, parsedType: getParsedType(data), schemaErrorMap: schema._def.errorMap } // parse data with given schema const ret = schema._parse({ data, path, meta: ctx.meta, parent: ctx }) const result = await (ret instanceof Promise ? ret : Promise.resolve(ret)) if (result.status === 'valid') return result.value // report error if parsing failed ctx.common.issues.forEach(issue => { const source = issue.path.map(i => (typeof i === 'number' ? `[${i}]` : i)).join('.') const message = file.message(issue.message, { source }) message.fatal = result.status === 'aborted' || issue.fatal }) // return parsed data unless fatal error return result.status !== 'aborted' && result.value }) ) // logger.log(`loaded '${path}' with ${parsed.length} records`) file.result = isArr ? parsed : parsed[0] return file }
/** * Load file and parse data with given schema * @param config resolved config * @param path file path * @param schema data schema * @param changed changed file path (relative to content root) */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/build.ts#L32-L85
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
resolve
const resolve = async (config: Config, changed?: string): Promise<Record<string, unknown>> => { const { root, output, collections, prepare, complete } = config const begin = performance.now() logger.log(`resolving collections from '${root}'`) const entries = await Promise.all( Object.entries(collections).map(async ([name, { pattern, schema }]): Promise<[string, VeliteFile[]]> => { if (changed != null && !matchPatterns(changed, pattern, root) && resolved.has(name)) { // skip collection if changed file not match logger.log(`skipped resolve '${name}', using previous resolved`) return [name, resolved.get(name)!] } const begin = performance.now() const paths = await glob(pattern, { cwd: root, absolute: true, onlyFiles: true, ignore: ['**/_*'] }) const files = await Promise.all(paths.map(path => load(config, path, schema, changed))) logger.log(`resolve ${paths.length} files matching '${pattern}'`, begin) resolved.set(name, files) return [name, files] }) ) const allFiles = entries.flatMap(([, files]) => files) const report = reporter(allFiles, { quiet: true }) if (report.length > 0) { logger.warn(`issues:\n${report}`) if (config.strict) throw new Error('Schema validation failed.') } const result = Object.fromEntries( entries.map(([name, files]): [string, any | any[]] => { const data = files.flatMap(file => file.result).filter(Boolean) if (collections[name].single) { if (data.length === 0) throw new Error(`no data resolved for '${name}' collection`) if (data.length > 1) logger.warn(`resolved ${data.length} ${name}, but expected single, using first one`) else logger.log(`resolved 1 ${name}`) return [name, data[0]] } logger.log(`resolved ${data.length} ${name}`) return [name, data] }) ) const context = { config } let shouldOutput = true // apply prepare hook if (typeof prepare === 'function') { const begin = performance.now() shouldOutput = (await prepare(result, context)) ?? true logger.log(`executed 'prepare' callback got ${shouldOutput}`, begin) } if (shouldOutput) { // emit result if not prevented await outputData(output.data, result) } else { logger.warn(`prevent output by 'prepare' callback`) } // output all assets await outputAssets(output.assets, assets) // call complete hook if (typeof complete === 'function') { const begin = performance.now() await complete(result, context) logger.log(`executed 'complete' callback`, begin) } logger.log(`resolved ${Object.keys(result).length} collections`, begin) return result }
/** * Resolve collections from content root * @param config resolved config * @param changed changed file path (relative to content root) * @returns resolved result */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/build.ts#L93-L167
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
watch
const watch = async (config: Config) => { const { watch } = await import('chokidar') const { root, collections, configImports } = config logger.info(`watching for changes in '${root}'`) const patterns = Object.values(collections).flatMap(({ pattern }) => pattern) const watcher = watch(['.', ...configImports], { cwd: root, ignoreInitial: true, awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 10 } }).on('all', async (event, filename) => { if (event === 'addDir' || event === 'unlinkDir') return if (filename == null || typeof filename !== 'string') return try { const fullpath = join(root, filename) if (configImports.includes(fullpath)) { logger.info('velite config changed, restarting...') watcher.close() return build({ config: config.configPath, clean: false, watch: true }) } // skip if filename not match any collection pattern if (!matchPatterns(filename, patterns)) return // remove changed file cache for (const [key, value] of config.cache.entries()) { if (value === fullpath) config.cache.delete(key) } const begin = performance.now() logger.info(`changed: '${fullpath}', rebuilding...`) await resolve(config, fullpath) logger.info(`rebuild finished`, begin) } catch (err) { logger.warn(err) } }) }
/** * Watch files and rebuild on changes * @param config resolved config */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/build.ts#L173-L214
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
searchFiles
const searchFiles = async (files: string[], cwd: string = process.cwd(), depth: number = 3): Promise<string | undefined> => { for (const file of files) { try { const path = resolve(cwd, file) await access(path) // check file exists return path } catch { continue } } if (depth > 0 && !(cwd === '/' || cwd.endsWith(':\\'))) { return await searchFiles(files, dirname(cwd), depth - 1) } }
/** * recursive 3-level search files in cwd and its parent directories * @param files filenames (relative or absolute) * @param cwd start directory * @param depth search depth * @returns filename first searched */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/config.ts#L19-L32
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
loadConfig
const loadConfig = async (path: string): Promise<[UserConfig, string[]]> => { // TODO: import js (mjs, cjs) config file directly without esbuild? if (!/\.(js|mjs|cjs|ts|mts|cts)$/.test(path)) { const ext = path.split('.').pop() throw new Error(`not supported config file with '${ext}' extension`) } const outfile = join(path, '../node_modules/.velite.config.compiled.mjs') const result = await build({ entryPoints: [path], outfile, bundle: true, write: true, format: 'esm', target: 'node18', platform: 'node', metafile: true, packages: 'external' }) const deps = Object.keys(result.metafile.inputs).map(file => join(path, '..', file)) const configUrl = pathToFileURL(outfile) configUrl.searchParams.set('t', Date.now().toString()) // prevent import cache const mod = await import(configUrl.href) return [mod.default ?? mod, deps] }
/** * bundle and load user config file * @param path config file path * @returns user config object and dependencies */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/config.ts#L39-L67
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
VeliteFile.records
get records(): unknown { return this.data.data }
/** * Get parsed records from file */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L29-L31
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
VeliteFile.content
get content(): string | undefined { return this.data.content }
/** * Get content of file */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L36-L38
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
VeliteFile.mdast
get mdast(): Root | undefined { if (this._mdast != null) return this._mdast if (this.content == null) return undefined this._mdast = Object.freeze(fromMarkdown(this.content)) return this._mdast }
/** * Get mdast object from cache */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L43-L48
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
VeliteFile.hast
get hast(): Nodes | undefined { if (this._hast != null) return this._hast if (this.mdast == null) return undefined this._hast = Object.freeze(raw(toHast(this.mdast, { allowDangerousHtml: true }))) return this._hast }
/** * Get hast object from cache */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L53-L58
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
VeliteFile.plain
get plain(): string | undefined { if (this._plain != null) return this._plain if (this.hast == null) return undefined this._plain = toString(this.hast) return this._plain }
/** * Get plain text of content from cache */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L63-L68
cfb639a8fa0452168c1be3962a1022cdb947d8d3