type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
ArrowFunction
res => { this.noticias = res.data; }
adrielparedes/openscore
openscore-ui/src/app/views/noticias/noticias.component.ts
TypeScript
ClassDeclaration
@Component({ selector: 'app-noticias', templateUrl: './noticias.component.html', styleUrls: ['./noticias.component.scss'] }) export class NoticiasComponent implements OnInit { noticias: Noticia[] = []; constructor(private noticiasService: NoticiasService) { } ngOnInit() { this.refresh(); } refresh() { this.noticiasService.getAll(0, 0, [{ key: 'status', value: 'PUBLICADO' }]).subscribe(res => { this.noticias = res.data; }) } }
adrielparedes/openscore
openscore-ui/src/app/views/noticias/noticias.component.ts
TypeScript
MethodDeclaration
ngOnInit() { this.refresh(); }
adrielparedes/openscore
openscore-ui/src/app/views/noticias/noticias.component.ts
TypeScript
MethodDeclaration
refresh() { this.noticiasService.getAll(0, 0, [{ key: 'status', value: 'PUBLICADO' }]).subscribe(res => { this.noticias = res.data; }) }
adrielparedes/openscore
openscore-ui/src/app/views/noticias/noticias.component.ts
TypeScript
ArrowFunction
(item) => item.id === id
Bielma/nestjs-store
src/users/services/users.service.ts
TypeScript
ClassDeclaration
@Injectable() export class UsersService { constructor( private productsService: ProductsService, private configService: ConfigService, ) {} private counterId = 1; private users: User[] = [ { id: 1, email: 'correo@mail.com', password: '12345', role: 'admin', }, ]; findAll() { const apiKey = this.configService.get('API_KEY'); const dbName = this.configService.get('DATABASE_NAME'); console.log(apiKey, dbName); return this.users; } findOne(id: number) { const user = this.users.find((item) => item.id === id); if (!user) { throw new NotFoundException(`User #${id} not found`); } return user; } create(data: CreateUserDto) { this.counterId = this.counterId + 1; const newUser = { id: this.counterId, ...data, }; this.users.push(newUser); return newUser; } update(id: number, changes: UpdateUserDto) { const user = this.findOne(id); const index = this.users.findIndex((item) => item.id === id); this.users[index] = { ...user, ...changes, }; return this.users[index]; } remove(id: number) { const index = this.users.findIndex((item) => item.id === id); if (index === -1) { throw new NotFoundException(`User #${id} not found`); } this.users.splice(index, 1); return true; } getOrderByUser(id: number): Order { const user = this.findOne(id); return { date: new Date(), user, products: this.productsService.findAll(), }; } }
Bielma/nestjs-store
src/users/services/users.service.ts
TypeScript
MethodDeclaration
findAll() { const apiKey = this.configService.get('API_KEY'); const dbName = this.configService.get('DATABASE_NAME'); console.log(apiKey, dbName); return this.users; }
Bielma/nestjs-store
src/users/services/users.service.ts
TypeScript
MethodDeclaration
findOne(id: number) { const user = this.users.find((item) => item.id === id); if (!user) { throw new NotFoundException(`User #${id} not found`); } return user; }
Bielma/nestjs-store
src/users/services/users.service.ts
TypeScript
MethodDeclaration
create(data: CreateUserDto) { this.counterId = this.counterId + 1; const newUser = { id: this.counterId, ...data, }; this.users.push(newUser); return newUser; }
Bielma/nestjs-store
src/users/services/users.service.ts
TypeScript
MethodDeclaration
update(id: number, changes: UpdateUserDto) { const user = this.findOne(id); const index = this.users.findIndex((item) => item.id === id); this.users[index] = { ...user, ...changes, }; return this.users[index]; }
Bielma/nestjs-store
src/users/services/users.service.ts
TypeScript
MethodDeclaration
remove(id: number) { const index = this.users.findIndex((item) => item.id === id); if (index === -1) { throw new NotFoundException(`User #${id} not found`); } this.users.splice(index, 1); return true; }
Bielma/nestjs-store
src/users/services/users.service.ts
TypeScript
MethodDeclaration
getOrderByUser(id: number): Order { const user = this.findOne(id); return { date: new Date(), user, products: this.productsService.findAll(), }; }
Bielma/nestjs-store
src/users/services/users.service.ts
TypeScript
InterfaceDeclaration
export interface Country { _id?: String; name: String; states?: State[]; }
APMIS-HMS/cepmanagement
src/app/models/country.ts
TypeScript
ClassDeclaration
export declare class ResponseOrganization extends Response<Organization> { data: Organization }
h1542462994/teamwork-software-engineering
server/src/main/resources/static/js/model/response_organization.d.ts
TypeScript
ArrowFunction
(_, { search }, context, rootValue) => { return process.env.npm_package_version }
Aeysha0056/vue-storefront-api
packages/default-catalog/graphql/elasticsearch/root.resolver.ts
TypeScript
MethodDeclaration
__resolveType () { return null; }
Aeysha0056/vue-storefront-api
packages/default-catalog/graphql/elasticsearch/root.resolver.ts
TypeScript
ArrowFunction
( globalConfigState: GlobalConfigState, ): GlobalConfigState => { if (!isMigrateModel(globalConfigState, MODEL_VERSION, 'GlobalConfig')) { return globalConfigState; } // NOTE: needs to run before default stuff globalConfigState = _migrateMiscToSeparateKeys(globalConfigState); // NOTE: needs to run before default stuff globalConfigState = _migrateUndefinedShortcutsToNull(globalConfigState); globalConfigState = _migrateSyncCfg(globalConfigState); globalConfigState = _fixDefaultProjectId(globalConfigState); // NOTE: absolutely needs to come last as otherwise the previous defaults won't work // NOTE2: mutates globalConfigState = _extendConfigDefaults(globalConfigState); return { ...globalConfigState, // Update model version after all migrations ran successfully [MODEL_VERSION_KEY]: MODEL_VERSION, }; }
isupovs/super-productivity
src/app/features/config/migrate-global-config.util.ts
TypeScript
ArrowFunction
(config: GlobalConfigState): GlobalConfigState => { const idle: IdleConfig = !!config.idle ? config.idle : { ...DEFAULT_GLOBAL_CONFIG.idle, // eslint-disable-next-line isOnlyOpenIdleWhenCurrentTask: (config.misc as any).isOnlyOpenIdleWhenCurrentTask, // eslint-disable-next-line isEnableIdleTimeTracking: (config.misc as any)['isEnableIdleTimeTracking'], // eslint-disable-next-line minIdleTime: (config.misc as any)['minIdleTime'], // eslint-disable-next-line isUnTrackedIdleResetsBreakTimer: (config.misc as any) .isUnTrackedIdleResetsBreakTimer, }; const takeABreak: TakeABreakConfig = !!config.takeABreak ? config.takeABreak : { ...DEFAULT_GLOBAL_CONFIG.takeABreak, // eslint-disable-next-line isTakeABreakEnabled: (config.misc as any)['isTakeABreakEnabled'], // eslint-disable-next-line takeABreakMessage: (config.misc as any)['takeABreakMessage'], // eslint-disable-next-line takeABreakMinWorkingTime: (config.misc as any)['takeABreakMinWorkingTime'], }; // we delete the old keys. worst case is, that the default settings are used for outdated versions of the app const obsoleteMiscKeys: (keyof TakeABreakConfig | keyof IdleConfig)[] = [ 'isTakeABreakEnabled', 'takeABreakMessage', 'takeABreakMinWorkingTime', 'isOnlyOpenIdleWhenCurrentTask', 'isEnableIdleTimeTracking', 'minIdleTime', 'isUnTrackedIdleResetsBreakTimer', ]; obsoleteMiscKeys.forEach((key) => { if ((config as any)[key]) { delete (config as any)[key]; } }); return { ...config, idle, takeABreak, }; }
isupovs/super-productivity
src/app/features/config/migrate-global-config.util.ts
TypeScript
ArrowFunction
(key) => { if ((config as any)[key]) { delete (config as any)[key]; } }
isupovs/super-productivity
src/app/features/config/migrate-global-config.util.ts
TypeScript
ArrowFunction
(config: GlobalConfigState): GlobalConfigState => { const newCfg: Partial<GlobalConfigState> = { ...config }; for (const key in DEFAULT_GLOBAL_CONFIG) { if (!newCfg.hasOwnProperty(key)) { // @ts-ignore newCfg[key] = { ...DEFAULT_GLOBAL_CONFIG[key] }; } else if ( // @ts-ignore typeof DEFAULT_GLOBAL_CONFIG[key] === 'object' && // @ts-ignore DEFAULT_GLOBAL_CONFIG[key] !== null ) { // @ts-ignore for (const entryKey in DEFAULT_GLOBAL_CONFIG[key]) { // @ts-ignore if (!newCfg[key].hasOwnProperty(entryKey)) { // @ts-ignore const defaultVal = DEFAULT_GLOBAL_CONFIG[key][entryKey]; console.log('EXTEND globalConfig', key, entryKey, defaultVal); // @ts-ignore newCfg[key] = { ...newCfg[key], [entryKey]: defaultVal }; } } } } return newCfg as GlobalConfigState; }
isupovs/super-productivity
src/app/features/config/migrate-global-config.util.ts
TypeScript
ArrowFunction
( config: GlobalConfigState, ): GlobalConfigState => { const keyboardCopy: any = { // also add new keys ...DEFAULT_GLOBAL_CONFIG.keyboard, ...config.keyboard, }; Object.keys(keyboardCopy).forEach((key: string) => { if (keyboardCopy[key] === false || keyboardCopy[key] === undefined) { keyboardCopy[key] = null; } }); return { ...config, keyboard: keyboardCopy, }; }
isupovs/super-productivity
src/app/features/config/migrate-global-config.util.ts
TypeScript
ArrowFunction
(key: string) => { if (keyboardCopy[key] === false || keyboardCopy[key] === undefined) { keyboardCopy[key] = null; } }
isupovs/super-productivity
src/app/features/config/migrate-global-config.util.ts
TypeScript
ArrowFunction
(config: GlobalConfigState): GlobalConfigState => { if (config.sync) { return config; } let prevProvider: SyncProvider | null = null; let syncInterval: number = 0; if ((config as any).dropboxSync?.isEnabled) { prevProvider = SyncProvider.Dropbox; syncInterval = (config as any).dropboxSync.syncInterval; } if ((config as any).googleDriveSync?.isEnabled) { prevProvider = SyncProvider.GoogleDrive; syncInterval = (config as any).googleDriveSync.syncInterval; } return { ...config, sync: !!prevProvider ? ({ isEnabled: true, syncInterval, syncProvider: prevProvider, dropboxSync: { ...DEFAULT_GLOBAL_CONFIG.sync.dropboxSync, accessToken: (config as any).dropboxSync?.accessToken, authCode: (config as any).dropboxSync?.authCode, // copy existing values if any ...(config.sync as any)?.dropboxSync, }, googleDriveSync: { ...DEFAULT_GLOBAL_CONFIG.sync.googleDriveSync, ...(config as any)?.googleDriveSync, // copy existing values if any ...(config.sync as any)?.googleDriveSync, }, webDav: { password: null, syncFilePath: null, userName: null, baseUrl: null, // copy existing values if any ...(config.sync as any)?.webDav, }, localFileSync: { syncFilePath: null, // copy existing values if any ...(config.sync as any)?.localFileSync, }, } as SyncConfig) : DEFAULT_GLOBAL_CONFIG.sync, }; }
isupovs/super-productivity
src/app/features/config/migrate-global-config.util.ts
TypeScript
ArrowFunction
(config: GlobalConfigState): GlobalConfigState => { if (config.misc.defaultProjectId === 'G.NONE' || config.misc.defaultProjectId === '') { return { ...config, misc: { ...config.misc, defaultProjectId: null, }, }; } return { ...config, }; }
isupovs/super-productivity
src/app/features/config/migrate-global-config.util.ts
TypeScript
ClassDeclaration
/** * @en The forward render stage * @zh 前向渲染阶段。 */ @ccclass('ForwardStage') export class ForwardStage extends RenderStage { public static initInfo: IRenderStageInfo = { name: 'ForwardStage', priority: ForwardStagePriority.FORWARD, tag: 0, renderQueues: [ { isTransparent: false, sortMode: RenderQueueSortMode.FRONT_TO_BACK, stages: ['default'], }, { isTransparent: true, sortMode: RenderQueueSortMode.BACK_TO_FRONT, stages: ['default', 'planarShadow'], }, ] }; @type([RenderQueueDesc]) @serializable @displayOrder(2) protected renderQueues: RenderQueueDesc[] = []; protected _renderQueues: RenderQueue[] = []; private _renderArea: GFXRect = { x: 0, y: 0, width: 0, height: 0 }; private _batchedQueue: RenderBatchedQueue; private _instancedQueue: RenderInstancedQueue; private _phaseID = getPhaseID('default'); private declare _additiveLightQueue: RenderAdditiveLightQueue; private declare _planarQueue: PlanarShadowQueue; constructor () { super(); this._batchedQueue = new RenderBatchedQueue(); this._instancedQueue = new RenderInstancedQueue(); } public initialize (info: IRenderStageInfo): boolean { super.initialize(info); if (info.renderQueues) { this.renderQueues = info.renderQueues; } return true; } public activate (pipeline: ForwardPipeline, flow: ForwardFlow) { super.activate(pipeline, flow); for (let i = 0; i < this.renderQueues.length; i++) { let phase = 0; for (let j = 0; j < this.renderQueues[i].stages.length; j++) { phase |= getPhaseID(this.renderQueues[i].stages[j]); } let sortFunc: (a: IRenderPass, b: IRenderPass) => number = opaqueCompareFn; switch (this.renderQueues[i].sortMode) { case RenderQueueSortMode.BACK_TO_FRONT: sortFunc = transparentCompareFn; break; case RenderQueueSortMode.FRONT_TO_BACK: sortFunc = opaqueCompareFn; break; } this._renderQueues[i] = new RenderQueue({ isTransparent: this.renderQueues[i].isTransparent, phases: phase, sortFunc, }); } this._additiveLightQueue = new RenderAdditiveLightQueue(this._pipeline as ForwardPipeline); this._planarQueue = new PlanarShadowQueue(this._pipeline as ForwardPipeline); } public destroy () { } public render (view: RenderView) { this._instancedQueue.clear(); this._batchedQueue.clear(); const pipeline = this._pipeline as ForwardPipeline; const device = pipeline.device; this._renderQueues.forEach(this.renderQueueClearFunc); const renderObjects = pipeline.renderObjects; let m = 0; let p = 0; let k = 0; for (let i = 0; i < renderObjects.length; ++i) { const ro = renderObjects[i]; const subModels = ro.model.subModels; for (m = 0; m < subModels.length; ++m) { const subModel = subModels[m]; const passes = subModel.passes; for (p = 0; p < passes.length; ++p) { const pass = passes[p]; if (pass.phase !== this._phaseID) continue; const batchingScheme = pass.batchingScheme; if (batchingScheme === BatchingSchemes.INSTANCING) { const instancedBuffer = InstancedBuffer.get(pass); instancedBuffer.merge(subModel, ro.model.instancedAttributes, p); this._instancedQueue.queue.add(instancedBuffer); } else if (batchingScheme === BatchingSchemes.VB_MERGING) { const batchedBuffer = BatchedBuffer.get(pass); batchedBuffer.merge(subModel, p, ro); this._batchedQueue.queue.add(batchedBuffer); } else { for (k = 0; k < this._renderQueues.length; k++) { this._renderQueues[k].insertRenderPass(ro, m, p); } } } } } this._renderQueues.forEach(this.renderQueueSortFunc); this._additiveLightQueue.gatherLightPasses(view); this._planarQueue.updateShadowList(view); const camera = view.camera; const cmdBuff = pipeline.commandBuffers[0]; const vp = camera.viewport; this._renderArea!.x = vp.x * camera.width; this._renderArea!.y = vp.y * camera.height; this._renderArea!.width = vp.width * camera.width * pipeline.shadingScale; this._renderArea!.height = vp.height * camera.height * pipeline.shadingScale; if (camera.clearFlag & GFXClearFlag.COLOR) { if (pipeline.isHDR) { SRGBToLinear(colors[0], camera.clearColor); const scale = pipeline.fpScale / camera.exposure; colors[0].x *= scale; colors[0].y *= scale; colors[0].z *= scale; } else { colors[0].x = camera.clearColor.x; colors[0].y = camera.clearColor.y; colors[0].z = camera.clearColor.z; } } colors[0].w = camera.clearColor.w; const framebuffer = view.window.framebuffer; const renderPass = framebuffer.colorTextures[0] ? framebuffer.renderPass : pipeline.getRenderPass(camera.clearFlag); cmdBuff.begin(); cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea!, colors, camera.clearDepth, camera.clearStencil); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); this._renderQueues[0].recordCommandBuffer(device, renderPass, cmdBuff); this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._additiveLightQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._renderQueues[1].recordCommandBuffer(device, renderPass, cmdBuff); cmdBuff.endRenderPass(); cmdBuff.end(); device.queue.submit(pipeline.commandBuffers); } /** * @en Clear the given render queue * @zh 清空指定的渲染队列 * @param rq The render queue */ protected renderQueueClearFunc (rq: RenderQueue) { rq.clear(); } /** * @en Sort the given render queue * @zh 对指定的渲染队列执行排序 * @param rq The render queue */ protected renderQueueSortFunc (rq: RenderQueue) { rq.sort(); } }
CatXia/CatXiaEngine
library/engine-3d/cocos/core/pipeline/forward/forward-stage.ts
TypeScript
MethodDeclaration
public initialize (info: IRenderStageInfo): boolean { super.initialize(info); if (info.renderQueues) { this.renderQueues = info.renderQueues; } return true; }
CatXia/CatXiaEngine
library/engine-3d/cocos/core/pipeline/forward/forward-stage.ts
TypeScript
MethodDeclaration
public activate (pipeline: ForwardPipeline, flow: ForwardFlow) { super.activate(pipeline, flow); for (let i = 0; i < this.renderQueues.length; i++) { let phase = 0; for (let j = 0; j < this.renderQueues[i].stages.length; j++) { phase |= getPhaseID(this.renderQueues[i].stages[j]); } let sortFunc: (a: IRenderPass, b: IRenderPass) => number = opaqueCompareFn; switch (this.renderQueues[i].sortMode) { case RenderQueueSortMode.BACK_TO_FRONT: sortFunc = transparentCompareFn; break; case RenderQueueSortMode.FRONT_TO_BACK: sortFunc = opaqueCompareFn; break; } this._renderQueues[i] = new RenderQueue({ isTransparent: this.renderQueues[i].isTransparent, phases: phase, sortFunc, }); } this._additiveLightQueue = new RenderAdditiveLightQueue(this._pipeline as ForwardPipeline); this._planarQueue = new PlanarShadowQueue(this._pipeline as ForwardPipeline); }
CatXia/CatXiaEngine
library/engine-3d/cocos/core/pipeline/forward/forward-stage.ts
TypeScript
MethodDeclaration
public destroy () { }
CatXia/CatXiaEngine
library/engine-3d/cocos/core/pipeline/forward/forward-stage.ts
TypeScript
MethodDeclaration
public render (view: RenderView) { this._instancedQueue.clear(); this._batchedQueue.clear(); const pipeline = this._pipeline as ForwardPipeline; const device = pipeline.device; this._renderQueues.forEach(this.renderQueueClearFunc); const renderObjects = pipeline.renderObjects; let m = 0; let p = 0; let k = 0; for (let i = 0; i < renderObjects.length; ++i) { const ro = renderObjects[i]; const subModels = ro.model.subModels; for (m = 0; m < subModels.length; ++m) { const subModel = subModels[m]; const passes = subModel.passes; for (p = 0; p < passes.length; ++p) { const pass = passes[p]; if (pass.phase !== this._phaseID) continue; const batchingScheme = pass.batchingScheme; if (batchingScheme === BatchingSchemes.INSTANCING) { const instancedBuffer = InstancedBuffer.get(pass); instancedBuffer.merge(subModel, ro.model.instancedAttributes, p); this._instancedQueue.queue.add(instancedBuffer); } else if (batchingScheme === BatchingSchemes.VB_MERGING) { const batchedBuffer = BatchedBuffer.get(pass); batchedBuffer.merge(subModel, p, ro); this._batchedQueue.queue.add(batchedBuffer); } else { for (k = 0; k < this._renderQueues.length; k++) { this._renderQueues[k].insertRenderPass(ro, m, p); } } } } } this._renderQueues.forEach(this.renderQueueSortFunc); this._additiveLightQueue.gatherLightPasses(view); this._planarQueue.updateShadowList(view); const camera = view.camera; const cmdBuff = pipeline.commandBuffers[0]; const vp = camera.viewport; this._renderArea!.x = vp.x * camera.width; this._renderArea!.y = vp.y * camera.height; this._renderArea!.width = vp.width * camera.width * pipeline.shadingScale; this._renderArea!.height = vp.height * camera.height * pipeline.shadingScale; if (camera.clearFlag & GFXClearFlag.COLOR) { if (pipeline.isHDR) { SRGBToLinear(colors[0], camera.clearColor); const scale = pipeline.fpScale / camera.exposure; colors[0].x *= scale; colors[0].y *= scale; colors[0].z *= scale; } else { colors[0].x = camera.clearColor.x; colors[0].y = camera.clearColor.y; colors[0].z = camera.clearColor.z; } } colors[0].w = camera.clearColor.w; const framebuffer = view.window.framebuffer; const renderPass = framebuffer.colorTextures[0] ? framebuffer.renderPass : pipeline.getRenderPass(camera.clearFlag); cmdBuff.begin(); cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea!, colors, camera.clearDepth, camera.clearStencil); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); this._renderQueues[0].recordCommandBuffer(device, renderPass, cmdBuff); this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._additiveLightQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._renderQueues[1].recordCommandBuffer(device, renderPass, cmdBuff); cmdBuff.endRenderPass(); cmdBuff.end(); device.queue.submit(pipeline.commandBuffers); }
CatXia/CatXiaEngine
library/engine-3d/cocos/core/pipeline/forward/forward-stage.ts
TypeScript
MethodDeclaration
/** * @en Clear the given render queue * @zh 清空指定的渲染队列 * @param rq The render queue */ protected renderQueueClearFunc (rq: RenderQueue) { rq.clear(); }
CatXia/CatXiaEngine
library/engine-3d/cocos/core/pipeline/forward/forward-stage.ts
TypeScript
MethodDeclaration
/** * @en Sort the given render queue * @zh 对指定的渲染队列执行排序 * @param rq The render queue */ protected renderQueueSortFunc (rq: RenderQueue) { rq.sort(); }
CatXia/CatXiaEngine
library/engine-3d/cocos/core/pipeline/forward/forward-stage.ts
TypeScript
ClassDeclaration
export class User { @ApiProperty({ required: false, example: 1, description: 'User ID', }) id?: number; @ApiProperty({ example: 'Juan', description: 'The fist name of the User', }) firstName: string; @ApiProperty({ example: 'Perez', description: 'The lastname of the User', }) lastName: string; @ApiProperty({ example: 'jperez@email.com', description: 'The email of the user', }) email: string; }
rudemex/iol
src/users/entities/user.entity.ts
TypeScript
ArrowFunction
() => { const s: SoftwareDeliveryMachine = { configuration: { sdm: { k8s: { options: {}, }, }, }, } as any; const t = isSyncRepoCommit(s); assert(t === undefined); }
atomist/sdm-pack-k8
test/sync/goals.test.ts
TypeScript
ArrowFunction
async () => { const s: SoftwareDeliveryMachine = { configuration: { name: "@atomist/k8s-sdm_i-started-something", sdm: { k8s: { options: { sync: { credentials: { token: "j04nnym@44", }, repo: { branch: "a-rush-and-a-push", owner: "TheSmiths", providerType: ScmProviderType.github_com, repo: "strangeways", setUserConfig: async () => { }, url: "https://github.com/TheSmiths/strangeways", }, }, }, }, }, workspaceIds: ["AM0441SS3Y"], }, } as any; const p: PushListenerInvocation = { id: { branch: "a-rush-and-a-push", owner: "TheSmiths", providerType: ScmProviderType.github_com, repo: "strangeways", sha: "bb94dbf2a40b3754f2e62797c80923b938f60fb3", }, push: { commits: [ { message: "Stop me if you think you've heard this one before" }, ], }, } as any; const t = isSyncRepoCommit(s); assert(t, "no push test was returned"); const r = await t.mapping(p); assert(r === true, "push test result was false"); }
atomist/sdm-pack-k8
test/sync/goals.test.ts
TypeScript
ArrowFunction
async () => { }
atomist/sdm-pack-k8
test/sync/goals.test.ts
TypeScript
ArrowFunction
async () => { const s: SoftwareDeliveryMachine = { configuration: { name: "@atomist/k8s-sdm_i-started-something", sdm: { k8s: { options: { sync: { credentials: { token: "j04nnym@44", }, repo: { branch: "a-rush-and-a-push", owner: "TheSmiths", repo: "strangeways", }, }, }, }, }, workspaceIds: ["AM0441SS3Y"], }, } as any; const p: PushListenerInvocation = { id: { branch: "a-rush-and-a-push", owner: "TheSmiths", providerType: ScmProviderType.github_com, repo: "strangeways", sha: "bb94dbf2a40b3754f2e62797c80923b938f60fb3", }, push: { commits: [ { message: "Stop me if you think you've heard this one before" }, ], }, } as any; const t = isSyncRepoCommit(s); assert(t, "no push test was returned"); s.configuration.sdm.k8s.options.sync.repo = { branch: "a-rush-and-a-push", owner: "TheSmiths", providerType: ScmProviderType.github_com, repo: "strangeways", setUserConfig: async () => { }, url: "https://github.com/TheSmiths/strangeways", }; const r = await t.mapping(p); assert(r === true, "push test result was false"); }
atomist/sdm-pack-k8
test/sync/goals.test.ts
TypeScript
ArrowFunction
async () => { const s: SoftwareDeliveryMachine = { configuration: { name: "@atomist/k8s-sdm_i-started-something", sdm: { k8s: { options: { sync: { credentials: { token: "j04nnym@44", }, repo: { branch: "a-rush-and-a-push", owner: "TheSmiths", providerType: ScmProviderType.github_com, repo: "strangeways", setUserConfig: async () => { }, url: "https://github.com/TheSmiths/strangeways", }, }, }, }, }, workspaceIds: ["AM0441SS3Y"], }, } as any; const p: PushListenerInvocation = { id: { branch: "a-rush-and-a-push", owner: "TheSmiths", providerType: ScmProviderType.github_com, repo: "strangeways", sha: "bb94dbf2a40b3754f2e62797c80923b938f60fb3", }, push: { commits: [ { message: "Stop me\n\n[atomist:sync-commit=@atomist/k8s-sdm_i-started-something]" }, { message: "If you've\n\n[atomist:sync-commit=@atomist/k8s-sdm_i-started-something]" }, { message: "Heard this\n\n[atomist:sync-commit=@atomist/k8s-sdm_i-started-something]" }, { message: "One before\n\n[atomist:sync-commit=@atomist/k8s-sdm_i-started-something]" }, ], }, } as any; const t = isSyncRepoCommit(s); assert(t, "no push test was returned"); const r = await t.mapping(p); assert(r === false, "push test result was true"); }
atomist/sdm-pack-k8
test/sync/goals.test.ts
TypeScript
ArrowFunction
async () => { const s: SoftwareDeliveryMachine = { configuration: { name: "@atomist/k8s-sdm_i-started-something", sdm: { k8s: { options: { sync: { credentials: { token: "j04nnym@44", }, repo: { branch: "a-rush-and-a-push", owner: "TheSmiths", providerType: ScmProviderType.github_com, repo: "strangeways", setUserConfig: async () => { }, url: "https://github.com/TheSmiths/strangeways", }, }, }, }, }, workspaceIds: ["AM0441SS3Y"], }, } as any; const o: PushListenerInvocation = { id: { branch: "girlfriend-in-a-coma", owner: "TheSmiths", providerType: ScmProviderType.github_com, repo: "strangeways", sha: "bb94dbf2a40b3754f2e62797c80923b938f60fb3", }, push: { commits: [ { message: "Stop me\n\nIf you think" }, { message: "You've heard\n\nThis one before." }, ], }, } as any; const t = isSyncRepoCommit(s); assert(t, "no push test was returned"); const fs = [ { branch: "girlfriend-in-a-coma" }, { owner: "Electronic" }, { providerType: "bitbucket" }, { repo: "the-queen-is-dead" }, ]; for (const f of fs) { const p = _.merge({}, o, f); const r = await t.mapping(p); assert(r === false, `push test result was true when ${Object.keys(f)} differed`); } }
atomist/sdm-pack-k8
test/sync/goals.test.ts
TypeScript
ArrowFunction
async () => { const s: SoftwareDeliveryMachine = { configuration: { name: "@atomist/k8s-sdm_i-started-something", sdm: { k8s: { options: { sync: { credentials: { token: "j04nnym@44", }, repo: { branch: "a-rush-and-a-push", owner: "TheSmiths", repo: "strangeways", }, }, }, }, }, workspaceIds: ["AM0441SS3Y"], }, } as any; const p: PushListenerInvocation = { id: { branch: "girlfriend-in-a-coma", owner: "TheSmiths", providerType: ScmProviderType.github_com, repo: "strangeways", sha: "bb94dbf2a40b3754f2e62797c80923b938f60fb3", }, push: { commits: [ { message: "Stop me\n\nIf you think" }, { message: "You've heard\n\nThis one before." }, ], }, } as any; const t = isSyncRepoCommit(s); assert(t, "no push test was returned"); let thrown = false; try { await t.mapping(p); assert.fail("should have thrown an error"); } catch (e) { thrown = true; assert(e.message.startsWith("SyncRepoRef did not get converted to proper RemoteRepoRef at startup")); } assert(thrown, "should have thrown an error"); }
atomist/sdm-pack-k8
test/sync/goals.test.ts
TypeScript
ArrowFunction
state => state ? this._filterStates(state) : this.statesList.slice()
martinavagyan/us-infographic
client/src/app/components/search/search.component.ts
TypeScript
ArrowFunction
state => state.name.toLowerCase().indexOf(filterValue) === 0
martinavagyan/us-infographic
client/src/app/components/search/search.component.ts
TypeScript
ClassDeclaration
@Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css'] }) export class SearchComponent implements OnInit { @Input('statesList') public statesList: State[] = []; @Output('selectedRegionEvent') public selectedRegionEvent = new EventEmitter<string>(); public stateCtrl = new FormControl(); public filteredStates: Observable<State[]>; ngOnInit() { this.filteredStates = this.stateCtrl.valueChanges .pipe( startWith(''), map(state => state ? this._filterStates(state) : this.statesList.slice()) ); } public stateClicked(selectedState: State): void { this.selectedRegionEvent.emit(selectedState.id); } constructor() { } private _filterStates(value: string): State[] { const filterValue = value.toLowerCase(); return this.statesList.filter(state => state.name.toLowerCase().indexOf(filterValue) === 0); } }
martinavagyan/us-infographic
client/src/app/components/search/search.component.ts
TypeScript
MethodDeclaration
ngOnInit() { this.filteredStates = this.stateCtrl.valueChanges .pipe( startWith(''), map(state => state ? this._filterStates(state) : this.statesList.slice()) ); }
martinavagyan/us-infographic
client/src/app/components/search/search.component.ts
TypeScript
MethodDeclaration
public stateClicked(selectedState: State): void { this.selectedRegionEvent.emit(selectedState.id); }
martinavagyan/us-infographic
client/src/app/components/search/search.component.ts
TypeScript
MethodDeclaration
private _filterStates(value: string): State[] { const filterValue = value.toLowerCase(); return this.statesList.filter(state => state.name.toLowerCase().indexOf(filterValue) === 0); }
martinavagyan/us-infographic
client/src/app/components/search/search.component.ts
TypeScript
ClassDeclaration
@NgModule({ declarations: [ AppComponent ], imports: [ HttpModule, HttpClientModule, FormsModule, BrowserModule, AppRoutingModule, SharedModule ], providers: [ AuthService, LoaderService, ModalTempService, ModalConfirmService, CardService ], bootstrap: [AppComponent] }) export class AppModule { }
MarinTerentiev/mag
src/app/app.module.ts
TypeScript
FunctionDeclaration
export default async function createPlugin({ logger, config, }: PluginEnvironment) { return await createRouter({ logger, config }); }
AdnCodez/backstage
packages/backend/src/plugins/kubernetes.ts
TypeScript
ArrowFunction
({ name, value, className, ...props }: Props & InputProps) => ( <Field name={name}> {({ field, form }: FieldProps)
07test9992/panel
resources/scripts/components/elements/Checkbox.tsx
TypeScript
InterfaceDeclaration
interface Props { name: string; value: string; className?: string; }
07test9992/panel
resources/scripts/components/elements/Checkbox.tsx
TypeScript
TypeAliasDeclaration
type OmitFields = 'ref' | 'name' | 'value' | 'type' | 'checked' | 'onClick' | 'onChange';
07test9992/panel
resources/scripts/components/elements/Checkbox.tsx
TypeScript
TypeAliasDeclaration
type InputProps = Omit<JSX.IntrinsicElements['input'], OmitFields>;
07test9992/panel
resources/scripts/components/elements/Checkbox.tsx
TypeScript
ArrowFunction
(): void => this.terminate()
BenediktMagnus/Wichtelbot
scripts/main.ts
TypeScript
ClassDeclaration
class Main { private wichtelbot: Wichtelbot|null = null; private applicationIsRunning = false; constructor () { const terminateFunction = (): void => this.terminate(); process.on('exit', terminateFunction); process.on('SIGINT', terminateFunction); // Ctrl + C process.on('SIGHUP', terminateFunction); // Terminal closed process.on('SIGTERM', terminateFunction); // "kill pid" / "killall" process.on('SIGUSR1', terminateFunction); // "kill -SIGUSR1 pid" / "killall -SIGUSR1" process.on('SIGUSR2', terminateFunction); // "kill -SIGUSR2 pid" / "killall -SIGUSR2" } /** * Terminate all running connections and report about the closing programme. */ public terminate (): void { if (this.applicationIsRunning) { this.applicationIsRunning = false; if (this.wichtelbot) { this.wichtelbot.terminate(); } console.log("\nWichtelbot closed."); } } public async run (): Promise<void> { console.log('Wichtelbot is starting...'); this.applicationIsRunning = true; this.wichtelbot = new Wichtelbot(); await this.wichtelbot.run(); console.log(`Wichtelbot started.`); } }
BenediktMagnus/Wichtelbot
scripts/main.ts
TypeScript
MethodDeclaration
/** * Terminate all running connections and report about the closing programme. */ public terminate (): void { if (this.applicationIsRunning) { this.applicationIsRunning = false; if (this.wichtelbot) { this.wichtelbot.terminate(); } console.log("\nWichtelbot closed."); } }
BenediktMagnus/Wichtelbot
scripts/main.ts
TypeScript
MethodDeclaration
public async run (): Promise<void> { console.log('Wichtelbot is starting...'); this.applicationIsRunning = true; this.wichtelbot = new Wichtelbot(); await this.wichtelbot.run(); console.log(`Wichtelbot started.`); }
BenediktMagnus/Wichtelbot
scripts/main.ts
TypeScript
ArrowFunction
() => { afterEach(() => { jest.resetAllMocks(); }); it('creates snapshot', () => { const { asFragment } = render(<InputTypeahead {...defaultProps} />); expect(asFragment).toMatchSnapshot(); }); it('renders proper content with selectedValues', () => { const { getByTestId, getAllByTestId, getByText } = render(<InputTypeahead {...defaultProps} />); expect(getByTestId('typeaheadBtn')).toBeInTheDocument(); expect(getAllByTestId('typeaheadSelectedItem')).toHaveLength(2); expect(getByText(defaultProps.label)).toBeInTheDocument(); }); it('renders proper content without selectedValues', () => { const { getByTestId, getByText } = render(<InputTypeahead {...defaultProps} selected={{}} />); expect(getByTestId('typeaheadBtn')).toBeInTheDocument(); expect(getByText(defaultProps.label)).toBeInTheDocument(); expect(getByText('No test selected')).toBeInTheDocument(); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { jest.resetAllMocks(); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { asFragment } = render(<InputTypeahead {...defaultProps} />); expect(asFragment).toMatchSnapshot(); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByTestId, getAllByTestId, getByText } = render(<InputTypeahead {...defaultProps} />); expect(getByTestId('typeaheadBtn')).toBeInTheDocument(); expect(getAllByTestId('typeaheadSelectedItem')).toHaveLength(2); expect(getByText(defaultProps.label)).toBeInTheDocument(); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByTestId, getByText } = render(<InputTypeahead {...defaultProps} selected={{}}
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByTestId, getAllByTestId, getByText, getByPlaceholderText } = render( <InputTypeahead {...defaultProps} /> ); const btn = getByTestId('typeaheadBtn'); fireEvent.click(btn); expect(getByTestId('typeaheadDropdown')).toBeInTheDocument(); expect(getByTestId('typeaheadInput')).toBeInTheDocument(); expect(getByPlaceholderText('Search test')).toBeInTheDocument(); expect(getAllByTestId('typeaheadDropdownBtn')).toHaveLength(4); expect(getByText('Clear all')).toBeInTheDocument(); expect(getByTestId('typeaheadClearBtn')).toBeInTheDocument(); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByText, getByTestId } = render(<InputTypeahead {...defaultProps} />); const item = getByText('Option key 1'); fireEvent.click(item); expect(getByTestId('typeaheadDropdown')).toBeInTheDocument(); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByTestId, getAllByTestId } = render(<InputTypeahead {...defaultProps} />); const btn = getByTestId('typeaheadBtn'); fireEvent.click(btn); const opts = getAllByTestId('typeaheadDropdownBtn'); expect(opts[0]).toHaveTextContent('Option key 2(12)'); expect(opts[1]).toHaveTextContent('Option key 1(7)'); expect(opts[2]).toHaveTextContent('Option 1(19)'); expect(opts[3]).toHaveTextContent('Option 2(17)'); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getAllByTestId } = render(<InputTypeahead {...defaultProps} />); const opts = getAllByTestId('typeaheadSelectedItem'); expect(opts[0]).toHaveTextContent('Option key 2(12)'); expect(opts[1]).toHaveTextContent('Option key 1(7)'); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByTestId, getAllByTestId } = render(<InputTypeahead {...defaultProps} />); const btn = getByTestId('typeaheadBtn'); fireEvent.click(btn); const opts = getAllByTestId('typeaheadDropdownBtn'); fireEvent.click(opts[0]); expect(onChangeMock).toHaveBeenCalledTimes(1); expect(onChangeMock).toHaveBeenCalledWith('key1', 'opt2', false); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByTestId, getAllByTestId } = render(<InputTypeahead {...defaultProps} />); const btn = getByTestId('typeaheadBtn'); fireEvent.click(btn); const opts = getAllByTestId('typeaheadDropdownBtn'); fireEvent.click(opts[2]); expect(onChangeMock).toHaveBeenCalledTimes(1); expect(onChangeMock).toHaveBeenCalledWith('key2', 'opt11', true); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByTestId } = render(<InputTypeahead {...defaultProps} />); const btn = getByTestId('typeaheadBtn'); fireEvent.click(btn); const clearBtn = getByTestId('typeaheadClearBtn'); fireEvent.click(clearBtn); expect(onResetSomeFiltersMock).toHaveBeenCalledTimes(1); expect(onResetSomeFiltersMock).toHaveBeenCalledWith(['key1']); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByTestId, getAllByTestId, getAllByText } = render(<InputTypeahead {...defaultProps} />); const btn = getByTestId('typeaheadBtn'); fireEvent.click(btn); expect(getAllByTestId('typeaheadDropdownBtn')).toHaveLength(4); const input = getByTestId('typeaheadInput'); fireEvent.change(input, { target: { value: 'ke' } }); expect(getAllByTestId('typeaheadDropdownBtn')).toHaveLength(2); expect(getAllByText('ke')).toHaveLength(2); expect(getAllByText('ke')[0]).toHaveClass('hightlighted'); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
() => { const { getByTestId, getAllByTestId, queryAllByTestId, getByText } = render(<InputTypeahead {...defaultProps} />); const btn = getByTestId('typeaheadBtn'); fireEvent.click(btn); expect(getAllByTestId('typeaheadDropdownBtn')).toHaveLength(4); const input = getByTestId('typeaheadInput'); fireEvent.change(input, { target: { value: 'test' } }); expect(queryAllByTestId('typeaheadDropdownBtn')).toHaveLength(0); expect(getByText('Sorry, no matches found')).toBeInTheDocument(); }
DirtyCajunRice/hub
web/src/layout/common/InputTypeahead.test.tsx
TypeScript
ArrowFunction
({ navigation }) => { const { aggregation } = useArtworkFiltersAggregation({ paramName: PARAM_NAME }) const options: FilterData[] = (aggregation?.counts ?? []).map(({ value: paramValue, name }) => { return { displayText: toTitleCase(name), paramName: PARAM_NAME, paramValue } }) const { handleSelect, isSelected, handleClear, isActive } = useMultiSelect({ options, paramName: PARAM_NAME, }) const filterOptions = options.map((option) => ({ ...option, paramValue: isSelected(option) })) return ( <MultiSelectOptionScreen onSelect={handleSelect} filterHeaderText={FilterDisplayName.artistNationalities} filterOptions={filterOptions} navigation={navigation} searchable {...(isActive ? { rightButtonText: "Clear", onRightButtonPress: handleClear } : {})} />
artsy/eigen
src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tsx
TypeScript
ArrowFunction
({ value: paramValue, name }) => { return { displayText: toTitleCase(name), paramName: PARAM_NAME, paramValue } }
artsy/eigen
src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tsx
TypeScript
ArrowFunction
(option) => ({ ...option, paramValue: isSelected(option) })
artsy/eigen
src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tsx
TypeScript
InterfaceDeclaration
interface ArtistNationalitiesOptionsScreenProps extends StackScreenProps<ArtworkFilterNavigationStack, "ArtistNationalitiesOptionsScreen"> {}
artsy/eigen
src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tsx
TypeScript
ClassDeclaration
@Schema() class Card extends Document { @Prop({ type: String }) weight: string; @Prop({ type: String }) type: string; }
Michalus88/black-jack-nest-react-mongo
src/schemas/user.schema.ts
TypeScript
ClassDeclaration
@Schema() export class User extends Document { @Prop({ type: String, unique: true, required: true }) email: string; @Prop({ required: true }) pwd: string; @Prop({ type: Number, default: 1500 }) means: number; @Prop({ type: [CardSchema] }) deck: CardInterface[]; @Prop({ type: [CardSchema] }) playerCards: CardInterface[]; @Prop({ type: Number, default: 0 }) playerPoints: number; @Prop({ type: Number, default: 0 }) playerBet: number; @Prop({ type: [CardSchema] }) dealerCards: CardInterface[]; @Prop({ type: Number, default: 0 }) dealerPoints: number; @Prop({ type: Boolean, default: false }) isDeal: boolean; @Prop({ type: Boolean, default: false }) isBet: boolean; @Prop({ type: Number, default: 0 }) gameResult: number; }
Michalus88/black-jack-nest-react-mongo
src/schemas/user.schema.ts
TypeScript
InterfaceDeclaration
export interface CardInterface { weight: string; type: string; }
Michalus88/black-jack-nest-react-mongo
src/schemas/user.schema.ts
TypeScript
ArrowFunction
( command: commander.Command, version: string, name: string, description: string, usage?: string ): void => { // Set command version command.version(version); // Set command name command.name(name); // Set command description command.description(description); // Set command usage command.usage(usage ? usage : '[options]'); }
joshuatvernon/scriptdir
src/utils/command/set-description/index.ts
TypeScript
FunctionDeclaration
export function executableName(name: string): string { return `${name}${os.platform() === "win32" ? ".exe" : ""}`; }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function changeExt(path: string, newExt: string): string { return path.replace(/\.[^/.]+$/, newExt); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export async function loadBinaryVersions(name: string): Promise<string[]> { const info = await httpsGetJson(`https://binaries.tonlabs.io/${name}.json`); const versions = info[name].sort(compareVersions).reverse(); return versions.length < 10 ? versions : [...versions.slice(0, 10), "..."]; }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function formatTokens(nanoTokens: string | number | bigint): string { const token = BigInt(1000000000); const bigNano = BigInt(nanoTokens); const tokens = Number(bigNano / token) + Number(bigNano % token) / Number(token); const tokensString = tokens < 1 ? tokens.toString() : `≈ ${Math.round(tokens)}`; return `${tokensString} tokens (${bigNano} nano)`; }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function writeTextFile(p: string, s: string) { const folderPath = path.dirname(p); if (!fs.existsSync(folderPath)) { fs.mkdirSync(folderPath, { recursive: true }); } fs.writeFileSync(p, s); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function writeJsonFile(p: string, v: unknown) { writeTextFile(p, JSON.stringify(v, undefined, " ")); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
async function installGlobally(dstPath: string, version: string, terminal: Terminal): Promise<void> { const binDir = path.dirname(dstPath); const [name, ext] = path.basename(dstPath).split("."); try { writeJsonFile(`${binDir}/package.json`, { name: name, // ex: tonos-cli version, bin: `./${name}${ext ? "." + ext : ""}`, }); await run("npm", ["install", "-g"], { cwd: binDir }, terminal); } catch (err) { terminal.writeError(err); throw Error(`An error occurred while trying to install ${name} globally. Make sure you can execute 'npm i <package> -g' without using sudo and try again`, ); } }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
function downloadAndUnzip(dst: string, url: string, terminal: Terminal): Promise<void> { return new Promise((resolve, reject) => { request(url) .on("data", _ => { terminal.write("."); }) .on("error", reject) // http protocol errors .pipe( unzip .Extract({ path: dst }) .on("error", reject) // unzip errors .on("close", resolve), ); }); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export async function downloadFromGithub(terminal: Terminal, srcUrl: string, dstPath: string) { terminal.write(`Downloading from ${srcUrl}`); if (!fs.existsSync(dstPath)) { fs.mkdirSync(dstPath, { recursive: true }); } await downloadAndUnzip(dstPath, srcUrl, terminal); terminal.write("\n"); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
function downloadAndGunzip(dest: string, url: string, terminal: Terminal): Promise<void> { return new Promise((resolve, reject) => { const request = https.get(url, response => { if (response.statusCode !== 200) { reject( new Error( `Download from ${url} failed with ${response.statusCode}: ${response.statusMessage}`, ), ); return; } let file: fs.WriteStream | null = fs.createWriteStream(dest, { flags: "w" }); let opened = false; const failed = (err: Error) => { if (file) { file.close(); file = null; fs.unlink(dest, () => { }); reject(err); } }; const unzip = zlib.createGunzip(); unzip.pipe(file); response.pipe(unzip); response.on("data", _ => { terminal.write("."); }); request.on("error", err => { failed(err); }); file.on("finish", () => { if (opened && file) { resolve(); } }); file.on("open", () => { opened = true; }); file.on("error", err => { if ((err as any).code === "EEXIST" && file) { file.close(); reject("File already exists"); } else { failed(err); } }); }); }); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export async function downloadFromBinaries( terminal: Terminal, dstPath: string, src: string, options?: { executable?: boolean, adjustedPath?: string, globally?: boolean, version?: string, }, ) { src = src.replace("{p}", os.platform()); const srcExt = path.extname(src).toLowerCase(); const srcUrl = `https://binaries.tonlabs.io/${src}`; terminal.write(`Downloading from ${srcUrl}`); const dstDir = path.dirname(dstPath); if (!fs.existsSync(dstDir)) { fs.mkdirSync(dstDir, { recursive: true }); } if (srcExt === ".zip") { await downloadAndUnzip(dstDir, srcUrl, terminal); } else if (srcExt === ".gz") { await downloadAndGunzip(dstPath, srcUrl, terminal); if (path.extname(dstPath) === ".tar") { await run("tar", ["xvf", dstPath], { cwd: path.dirname(dstPath) }, terminal); fs.unlink(dstPath, () => { }); } } else { throw Error(`Unexpected binary file extension: ${srcExt}`); } if (options?.executable && os.platform() !== "win32") { if (options?.adjustedPath) { const dir = path.dirname(options.adjustedPath); fs.readdirSync(dir) .map(filename => path.resolve(dir, filename)) .filter(filename => !fs.lstatSync(filename).isDirectory()) .forEach(filename => fs.chmodSync(filename, 0o755)); } else { fs.chmodSync(dstPath, 0o755); } // Without pause on Fedora 32 Linux always leads to an error: spawn ETXTBSY await new Promise(resolve => setTimeout(resolve, 100)); } if (options?.globally) { if (!options.version) { throw Error("Version required to install package"); } await installGlobally(dstPath, options.version, terminal).catch(err => { fs.unlink(dstPath, () => { }); throw err; }); } terminal.write("\n"); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function run( name: string, args: string[], options: SpawnOptionsWithoutStdio, terminal: Terminal, ): Promise<string> { return new Promise((resolve, reject) => { try { const { cwd } = options; if (cwd && !fs.existsSync(cwd)) { throw Error(`Directory not exists: ${cwd}`); } const isWindows = os.platform() === "win32"; const spawned = isWindows ? spawn("cmd.exe", ["/c", name].concat(args), { env: process.env, ...options, }) : spawn(name, args, { env: process.env, ...options, }); const output: string[] = []; spawned.stdout.on("data", function (data) { const text = data.toString(); output.push(text); terminal.log(text); }); spawned.stderr.on("data", data => { const text = data.toString(); terminal.writeError(text); }); spawned.on("error", err => { reject(err); }); spawned.on("close", code => { if (code === 0) { resolve(output.join("")); } else { reject(`${name} failed`); } }); } catch (error) { reject(error); } }); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function uniqueFilePath(folderPath: string, namePattern: string): string { let index = 0; while (true) { const filePath = path.resolve( folderPath, namePattern.replace("{}", index === 0 ? "" : index.toString()), ); if (!fs.existsSync(filePath)) { return filePath; } index += 1; } }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function versionToNumber(s: string): number { if (s.toLowerCase() === "latest") { return 1_000_000_000; } const parts = `${s || ""}` .split(".") .map(x => Number.parseInt(x)) .slice(0, 3); while (parts.length < 3) { parts.push(0); } return parts[0] * 1000000 + parts[1] * 1000 + parts[2]; }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function compareVersions(a: string, b: string): number { const an = versionToNumber(a); const bn = versionToNumber(b); return an < bn ? -1 : (an === bn ? 0 : 1); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function compareVersionsDescending(a: string, b: string): number { const an = versionToNumber(a); const bn = versionToNumber(b); return an > bn ? -1 : (an === bn ? 0 : 1); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function progressLine(terminal: Terminal, line: string) { terminal.write(`\r${line}`); const extra = _progressLine.length - line.length; if (extra > 0) { terminal.write(" ".repeat(extra) + "\b".repeat(extra)); } _progressLine = line; }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function progress(terminal: Terminal, info: string) { progressLine(terminal, `${info}...`); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function progressDone(terminal: Terminal) { terminal.log(" ✓"); _progressLine = ""; }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function httpsGetJson(url: string): Promise<any> { return new Promise((resolve, reject) => { const tryUrl = (url: string) => { https .get(url, function (res) { let body = ""; res.on("data", function (chunk) { body += chunk; }); res.on("end", function () { if (res.statusCode === 301) { const redirectUrl = res.headers["location"]; if (redirectUrl) { tryUrl(redirectUrl); } else { reject(new Error("Redirect response has no `location` header.")); } return; } const response = JSON.parse(body); resolve(response); }); }) .on("error", error => { reject(error); }); }; tryUrl(url); }); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
function toIdentifier(s: string): string { let identifier = ""; for (let i = 0; i < s.length; i += 1) { const c = s[i]; const isLetter = c.toLowerCase() !== c.toUpperCase(); const isDigit = !isLetter && "0123456789".includes(c); if (isLetter || isDigit) { identifier += c; } } return identifier; }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
export function userIdentifier(): string { return toIdentifier(os.userInfo().username).toLowerCase(); }
INTONNATION/tondev
src/core/utils.ts
TypeScript
FunctionDeclaration
function toString(value: any): string { return value === null || value === undefined ? "" : value.toString(); }
INTONNATION/tondev
src/core/utils.ts
TypeScript