Datasets:

blob_id
large_stringlengths
40
40
language
large_stringclasses
1 value
repo_name
large_stringlengths
5
119
path
large_stringlengths
4
271
score
float64
2.52
4.84
int_score
int64
3
5
text
stringlengths
26
4.09M
5366e27730172437af7ff2c208161a76030aff6f
TypeScript
PetrovIlyuha/uber-eats
/uber-eats-frontend/src/utils/messaging/toasts.ts
2.625
3
import cogoToast from "cogo-toast"; const defaultOptions = {hideAfter: 3, position: 'top-left'} class ToastFactory { private message: string; private options: Object; constructor(message: string, options: Object = defaultOptions) { this.message = message; this.options = options } showError() { return cogoToast.error(this.message, this.options) } showSuccess() { return cogoToast.success(this.message, this.options) } } export const passwordError = new ToastFactory('Password must contain !@#, lowercase and uppercase letters and at least one number'); export const shortPasswordError = new ToastFactory("Password must be longer than 8 characters!") export const accountCreationFailed = new ToastFactory("Failed to crate an account! Try again later!") export const accountCreated = new ToastFactory('Your account was created!') export const profileUpdated = new ToastFactory("Your profile was updated!") export default ToastFactory
2abb616fd2495a1d5c2b8434518c1bc62c71c4d7
TypeScript
sgobotta/dapp-unq-grupo-f-2017
/backend/src/services/rating-service.ts
2.515625
3
import { inject, injectable } from "inversify"; import * as _ from "lodash"; import { MongoDBClient } from "../config/mongodb/client"; import TYPES from "./../constants/types"; import { User, UserBuilder } from "../models/user"; import { Wove } from "aspect.js"; @Wove() @injectable() export class RatingService { private mongoClient: MongoDBClient; private collection: string; constructor( @inject(TYPES.MongoDBClient) mongoClient: MongoDBClient, ) { this.mongoClient = mongoClient; this.collection = "ratings"; } public updateRatingByEmail(email: string, rate: Rate): Promise<RatingResponse> { return new Promise<RatingResponse>((resolve, reject) => { let operation; if (rate.status === "negative") operation = -1 if (rate.status === "positive") operation = 1 this.mongoClient.updateNotSetByProperty(this.collection, { email: email }, { $inc: { rate: operation }}, (error, data: any) => { if (error) { reject({ success: false, msg: "Error while rating" }); } else if (data) { this.getRatingByEmail(email) .then((response) => { resolve(response); }) .catch((error) => { reject(error); }) } }); }); } public getRatingByEmail(email: string): Promise<RatingResponse> { return new Promise<RatingResponse>((resolve, reject) => { this.mongoClient.findOneByProperty(this.collection, { email: email }, (error, rate: any) => { if (error) { reject({ success: false, msg: "Error while getting ratings" }); } else if (rate) { resolve({ success: true, data: rate }); } }); }); } } export interface RatingResponse { success: boolean; data: any; } interface Rate { status: string; }
6c82a0cc2f01215aed25e24af2a0ed7c4a5e2814
TypeScript
marcospmail/rocketseat-gobarber-13
/backend/src/shared/container/providers/StorageProvider/implementations/DiskStorageProvider.ts
2.71875
3
import fs from 'fs' import path from 'path' import uploadConfig from '@config/upload' import IStorageProvider from '@shared/container/providers/StorageProvider/models/IStorageProvider' class DiskStorageProvider implements IStorageProvider { public async save(filename: string): Promise<string> { await fs.promises.rename( path.resolve(uploadConfig.tmp, filename), path.resolve(uploadConfig.directory, filename) ) return filename } public async delete(filename: string): Promise<void> { try { await fs.promises.stat(filename) } catch { return } await fs.promises.unlink(filename) } } export default DiskStorageProvider
64ef4272e8e9439faf7400de54e36648791f8454
TypeScript
woxiaoyao81/CRender
/es/utils/graph.d.ts
2.734375
3
import { Point } from '../types/core/graph'; /** * @description Get the coordinates of the rotated point */ export declare function getRotatePointPos(rotate: number | undefined, point: Point, origin?: Point): Point; /** * @description Get the coordinates of the scaled point */ export declare function getScalePointPos(scale: [number, number] | undefined, point: Point, origin?: Point): Point; /** * @description Get the coordinates of the scaled point */ export declare function getTranslatePointPos(translate: [number, number], point: Point): Point; /** * @description Check if the point is inside the rect */ export declare function checkPointIsInRect([px, py]: Point, x: number, y: number, width: number, height: number): boolean; /** * @description Return a timed release Promise */ export declare function delay(time: number): Promise<void>;
624209a4c895947d6057e9b1c493410c1c0a838a
TypeScript
fatum/ts-api-sample
/api/db.ts
2.546875
3
import { State, step, ok, fail } from "../operation"; const db = require("./../models").sequelize; type Model = { create(params: {}, options: {}): {}; create(params: {}, options: {}): {}; findOne(args: {}): {}; }; const load = (model: Model) => step("model.load", async (state: State) => { const params = state.params as { id: number | undefined }; if (!params.id) { return fail("error"); } const record = (await model.findOne({ where: { id: params.id } })) as { interest: number }; if (record) { state.model = record; return ok(state); } else { return fail("error"); } }); const persist = (model: Model) => step("contract.persist", async (state: State) => { console.log("--- Persisting operation"); if (state.model) { await state.model.update(state.params, { transaction: state.transaction }); } else { state.model = await model.create(state.params, { transaction: state.transaction }); } console.log("--- End persisting operation"); return ok(state); }); const transaction = async (state: State, cb: Function) => { const t = await db.transaction(); try { state.transaction = t; await cb(); await t.commit(); return true; } catch { await t.rollback(); return false; } }; export { db, transaction, persist, load };
14cd0bb9adcfaacdddd23cf40147060b7e419d2c
TypeScript
wpflying/05_utils
/src/utils/array/splitToGroups.ts
3.734375
4
/** * 以${groupSize}为一组,进行分割 * @param items 原数组 * @param groupSize 分割的块的容量 * @example * const splited = splitToGroups(['aa', 'bb', 'cc'], 2) // [['aa','bb'], ['cc']] */ export function splitToGroups<T>(items: Readonly<T[]>, groupSize: number) { const result: T[][] = [] let group: T[] = [] for (let i = 0; i < items.length; i++) { const item = items[i] group.push(item) if (group.length === groupSize || i === items.length - 1) { result.push(group) group = [] } } return result }
ddcd57ab0542e0e685bd4fff30b0c1ce2da16d5c
TypeScript
pnp/sp-dev-fx-extensions
/samples/react-menu-footer-classic-modern/Classic/client/common/model/IHeaderFooterData.ts
2.546875
3
import ILink from './ILink'; // All header-footer data, in the format we expect the JSON to be in export default interface IHeaderFooterData { headerLinks: ILink[]; footerLinks: ILink[]; }
198d15cc44c13f64963ebf0429ae1e01068e1979
TypeScript
dirigeants/utils
/test/isFunction.ts
3.03125
3
import ava from 'ava'; import { isFunction } from '../src'; ava('isFunction(string)', (test): void => { const value = 'Hello World'; test.false(isFunction(value)); }); ava('isFunction(number)', (test): void => { const value = 420; test.false(isFunction(value)); }); ava('isFunction(bigint)', (test): void => { // eslint-disable-next-line no-undef const value = BigInt(420); test.false(isFunction(value)); }); ava('isFunction(boolean)', (test): void => { const value = true; test.false(isFunction(value)); }); ava('isFunction(undefined)', (test): void => { const value = undefined; test.false(isFunction(value)); }); ava('isFunction(object)', (test): void => { const value = { class: '' }; test.false(isFunction(value)); }); ava('isFunction(object-null)', (test): void => { const value = null; test.false(isFunction(value)); }); ava('isFunction(function)', (test): void => { // eslint-disable-next-line func-style const value = function myClass(): void { /* noop */ }; test.true(isFunction(value)); }); ava('isFunction(arrow)', (test): void => { const value = (): void => { /* noop */ }; test.true(isFunction(value)); }); ava('isFunction(class)', (test): void => { const value = class A { }; test.true(isFunction(value)); });
61b93c0f922752aca275086aa7a8045f2df5c5ca
TypeScript
KochankovID/hacatone_miac
/frontend/src/store/PacientDashboard/actions.ts
2.609375
3
import axios from 'axios'; import { baseUrl } from 'helpers'; export enum PatientActions { getMeasurments = 'GET_MEASURMENTS', getPeriodMeasurments = 'GET_PERIOD_MEASURMENTS', getPatientInfo = 'GET_PATIENT_INFO', } export const getMeasurmentsAction = (id: number) => { return async (dispatch: any) => { try { const { data } = await axios.get(`${baseUrl}/measurements/${id}/`); dispatch({ type: PatientActions.getMeasurments, payload: data }); } catch (e) { console.log(e); } }; }; export const getPeriodMeasurmentsAction = (value: {id: number, start: string, end: string}) => { return async (dispatch: any) => { try { const { data } = await axios.get(`${baseUrl}/measurements/${value.id}/`, { params: { created_at__gte: value.start, created_at__lte: value.end, }}); dispatch({ type: PatientActions.getMeasurments, payload: data }); } catch (e) { console.log(e); } }; }; export const getPatientInfoAction = (id: number) => { return async (dispatch: any) => { try { const { data } = await axios.get(`${baseUrl}/measurements/${id}`); dispatch({ type: PatientActions.getPatientInfo, payload: data }); } catch (e) { console.log(e); } }; };
2f24760e19fff38d003d82800ce04c214ad6388c
TypeScript
Gust4voSales/AppointmentSystemServer
/src/services/ServiceService.ts
2.609375
3
import { getRepository, } from "typeorm" import { Service } from "../models/Service" class ServiceService { async createService(name: string, duration: number) { const repository = getRepository(Service) const newService = repository.create({ name, duration }) return await repository.save(newService) } async getServices() { const repository = getRepository(Service) return await repository.find() } } export default new ServiceService()
f694907dae6bc95be0d2db2a4a17f820ecd21b53
TypeScript
ilyajav/MyUnitTests
/src/08_AssociateArray/08_01.test.ts
2.546875
3
import {UsersType} from "./08_01"; let users: UsersType beforeEach(() =>{ users = { '101': {id: 101, name: 'Ilya'}, '3232312': {id: 3232312, name: 'Natasha'}, '1212': {id: 1212, name: 'Valera'}, '1': {id: 1, name: 'Katya'}, } }) test.skip('Should delete select corresponding user', () => { users['1'].name = 'Ekaterina' expect(users['1']).toEqual({id: 1, name: 'Ekaterina'}); })
d8193dcd8991cc5819eb2a28dd2765cdd12f1648
TypeScript
mp-elearning/project-front-end-sample
/src/app/blogs/blogs.component.ts
2.515625
3
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AppRoutingModule } from '../app-routing.module' import { dataCallBlogsService } from 'src/app/services/data-call-blogs.service'; import { blogData } from 'src/app/classes/blog-data'; @Component({ selector: 'app-blogs', templateUrl: './blogs.component.html', styleUrls: ['./blogs.component.css', '../../assets/css-styles/main_styles.css', '../../assets/css-styles/elements_responsive.css', '../../assets/css-styles/elements_styles.css', '../../assets/css-styles/responsive.css' ] }) export class BlogsComponent implements OnInit { bData:blogData; constructor( private router : Router , blogData : blogData, blogService : dataCallBlogsService ) { console.log('reached') blogService.getdata().subscribe( data=>{ this.bData = data console.log(this.bData) },(e)=>{ console.log(e) } ) } ngOnInit() { } blogData :any = [{ title : "Introduction to Blockchain technology", author : "Achiv Chauhan", contentSummary : "Blockchain technology has been garnering great hype recently. It gained popularity after the introduction of Bitcoin in 2009 by the person or group of people by the pseudonym Satoshi Nakamoto. Many people confuse and believe blockchain to be bitcoin. But, bitcoin is one application of the blockchain technology. There are many other applications and use cases that can be solved using blockchain other than just payment systems.", tags : [ "blockchain"] }, { title : "How Does the Blockchain Work?", author : "Anubhav Ujjawal", contentSummary : "Blockchain provides immutability (it’s theoretically possible to mutate the contents but its practically impossible most of the times because of the computational power required, unless there is a bug, which happened to ethereum once and it resulted in a hard fork, thus creating two versions of it, and thus two currencies, ethereum and ethereum classic).Blockchain provides Transparency and trust. Blockchain is shared, and hence it allows the system to be transparent and everybody can verify the data present in it.", tags : [ "blockchain"] }, { title : "Important Tips on How To Prepare for the GRE", author : "Ria Raval", contentSummary : "Graduate Record Examinations (GRE) is the prestigious competitive exam taken for admission in graduate schools across the United States. Preparing for GRE is therefore important. Following are the tips, which must be kept in mind while preparing for GRE-Choose the study material wisely: It is important to carefully choose what you read. Good study material helps in strengthening the concepts. It is advised to follow any one GRE preparation book by some known publication house.", tags : [ "GRE" ] }, { title : "Blockchain vs Bitcoin", author : "Shruti Babu", contentSummary : "Bitcoin: Bitcoin is a crypto-currency (a kind of digital currency), mainly created to simplify a transaction without having third-party intermediaries. It all started when this mysterious man under the name of Satoshi Nakamoto (whose actual identity is still unknown) published a white-paper named Bitcoin: A Peer-to-Peer Electronic Cash System in 2009. A Satoshi is the smallest unit of Bitcoin. Blockchain : Blockchain is a data structure or ledger that stores information about any transactions that occurs(not just bitcoin). Anything that is stored once can’t be changed or modified. This feature of Blockchain makes it the most secure. It is decentralized and establishes a peer to peer network thus eliminating any middle-men.", tags : [ "blockchain","bitcoin"] }, ] onSubmit(i){ console.log(i) if(i=='GRE'){ this.router.navigateByUrl('gre') }else if(i=='blockchain'){ this.router.navigateByUrl('blockchain') }else{ this.router.navigateByUrl('bitcoin') } } viewBlogs(d:any){ console.log(d) this.router.navigate(['eachblog',{data:d}]) } }
1e883336fb7b3a750407ca2be502ca0043281e80
TypeScript
lcsouzamenezes/dragonjs
/src/tools/extensionLang.ts
3.171875
3
interface extensionLangProps { language?: string; extension?: string; } function extensionLang({ language, extension }: extensionLangProps) { let lang = '' if (language === 'javascript') lang = 'js' if (extension === 'js') lang = 'javascript' if (language === 'typescript') lang = 'ts' if (extension === 'ts') lang = 'typescript' return lang } export default extensionLang
ffa69ec298be35b0ffcf9d51f8faee1ddc737c4d
TypeScript
sijeong/codegen-test
/src/swagger/modules/Managers.ts
2.8125
3
import ApiCommon = require("../api-common") // @ts-ignore import Types = require("../api-types") export type postApiV1Managers_Type = { body?: Types.CreateManagerCommand } export type postApiV1Managers_Response = string /** * POST /api/v1/managers * * Sample request: * * POST /api/v1/managers * { * "userName": "manager", * "email": "manger@icloudhospital.com", * "hospitalId": 1, * "firstName": "cloud", * "lastName": "manager", * "photo": "string", * "photoThumbnail": "string", * "gender": "NotSpecified", * "dateOfBirth": "2020-02-22T15:28:09.897Z", * "locations": [ * { * "locationType": "LivesIn", * "latitude": 0, * "longitude": 0, * "country": "string", * "state": "string", * "county": "string", * "city": "string", * "zipCode": "string", * "address": "string" * } * ] * } **/ export const postApiV1Managers = ApiCommon.requestMaker< postApiV1Managers_Type, postApiV1Managers_Response >({ id: "postApiV1Managers", path: "/api/v1/managers", verb: "POST", parameters: [{ name: "body", in: "body" }] }) export type getApiV1Managers_Type = { Created?: string Current?: boolean DateOfBirth?: string Email?: string Fullname?: string Gender?: any hospitalId?: string Id?: string lastRetrieved?: string limit?: number page?: number } export type getApiV1Managers_Response = Types.ManagersViewModel /** * GET /api/v1/managers * * Sample request: * * GET /api/v1/managers * { * "pageQueryFilter": { * "page": 1, * "limit": 20, * "lastRetrived": "2020-02-05T08:40" * }, * "searchString": "manager" * } **/ export const getApiV1Managers = ApiCommon.requestMaker< getApiV1Managers_Type, getApiV1Managers_Response >({ id: "getApiV1Managers", path: "/api/v1/managers", verb: "GET", parameters: [ { name: "Created", in: "query" }, { name: "Current", in: "query" }, { name: "DateOfBirth", in: "query" }, { name: "Email", in: "query" }, { name: "Fullname", in: "query" }, { name: "Gender", in: "query" }, { name: "hospitalId", in: "query" }, { name: "Id", in: "query" }, { name: "lastRetrieved", in: "query" }, { name: "limit", in: "query" }, { name: "page", in: "query" } ] }) export type getApiV1Manager_Type = { managerId: string } export type getApiV1Manager_Response = Types.ManagerViewModel /** * GET /api/v1/managers/{managerId} * * Sample request: * * GET /api/v1/managers/1 **/ export const getApiV1Manager = ApiCommon.requestMaker< getApiV1Manager_Type, getApiV1Manager_Response >({ id: "getApiV1Manager", path: "/api/v1/managers/{managerId}", verb: "GET", parameters: [{ name: "managerId", required: true, in: "path" }] }) export type putApiV1Manager_Type = { body?: Types.UpdateManagerCommand managerId: string } export type putApiV1Manager_Response = boolean /** * PUT /api/v1/managers/{managerId} * * Sample request: * * PUT /api/v1/managers/1 * { * "firstName": "string", * "lastName": "string", * "photo": "string", * "locations": [ * { * "locationType": "LivesIn", * "latitude": 0, * "longitude": 0, * "country": "string", * "state": "string", * "county": "string", * "city": "string", * "zipCode": "string", * "address": "string" * } * ] * } **/ export const putApiV1Manager = ApiCommon.requestMaker< putApiV1Manager_Type, putApiV1Manager_Response >({ id: "putApiV1Manager", path: "/api/v1/managers/{managerId}", verb: "PUT", parameters: [ { name: "body", in: "body" }, { name: "managerId", required: true, in: "path" } ] }) export type deleteApiV1Manager_Type = { managerId: string } export type deleteApiV1Manager_Response = boolean /** * DELETE /api/v1/managers/{managerId} * * Sample request: * * DELETE /api/v1/managers/1 **/ export const deleteApiV1Manager = ApiCommon.requestMaker< deleteApiV1Manager_Type, deleteApiV1Manager_Response >({ id: "deleteApiV1Manager", path: "/api/v1/managers/{managerId}", verb: "DELETE", parameters: [{ name: "managerId", required: true, in: "path" }] })
c943db53cff669442a042fd54c902c31ec2790e3
TypeScript
MikeMnD/ArtemisTS
/src/core/managers/TeamManager.ts
2.953125
3
import MManager = module("core/Manager"); import MEntity = module("core/Entity"); import MBag = module("core/utils/Bag"); import MHashmap = module("core/utils/Hashmap"); /** * * Use this class together with PlayerManager. * * You may sometimes want to create teams in your game, so that * some players are team mates. * * A player can only belong to a single team. * */ export class PlayerManager extends MManager.Manager { private _playersByTeam: MHashmap.Hashmap; //string, Bag of strings private _teamByPlayer: MHashmap.Hashmap; //string, string constructor() { super(); this._playersByTeam = new MHashmap.Hashmap(); this._teamByPlayer = new MHashmap.Hashmap(); } public getTeam(player: string): string { return this._teamByPlayer.getValue(player); } public setTeam(player: string, team: string): void { this.removeFromTeam(player); this._teamByPlayer.add(player, team); var players: MBag.Bag = this._playersByTeam.getValue(team); if (players == null) { players = new MBag.Bag(); this._playersByTeam.add(team, players); } players.add(player); } public getPlayers(team: string): MBag.Bag { return this._playersByTeam.getValue(team); } public removeFromTeam(player: string): void { var team: string = this._teamByPlayer.remove(player); if (team != null) { var players: MBag.Bag = this._playersByTeam.getValue(team); if (players != null) { players.remove(player); } } } //@Override initialize(): void { } }
b044693abcd3b5de9314cee3b2f353e3eee1840e
TypeScript
future4code/dumont-labenu-system10
/template-express-knex/src/endpoints/insertStudentInMission.ts
2.5625
3
import { Request, Response } from "express"; import { updateStudent } from "../data/updateStudent"; export const studentInMission = async (req: Request, res: Response) => { try { const {missionId, studentId} = req.body if(!req.body.missionId){throw new Error("Favor indicar o id da turma")} if(!req.body.studentId){throw new Error("Favor indicar o id do aluno")} await updateStudent(missionId, studentId) res.status(200).send("Estudante adicionado a turma com sucesso") } catch (error) { res.send(error.message) } }
e6c786f91d5879ba3ea56c049bc11c7dca1e18c7
TypeScript
vixriihi/Ilmari
/src/app/form/form.actions.ts
2.53125
3
import { Injectable } from '@angular/core'; import { Action } from '@ngrx/store'; import { FormLocation, FormName } from './form.reducer'; @Injectable() export class FormActions { static UPDATE_NAME = '[Form] update name'; static UPDATE_DATE = '[Form] update date'; static UPDATE_LOCATION = '[Form] update location'; static UPDATE_EXTRA = '[Form] update extra'; static UPDATE_STATE = '[Form] update whole form state'; static LOCATION_TO_HERE = '[Form] location to here'; static NO_GEO_LOCATE = '[Form] no geo locate'; static RESET = '[Form] reset'; constructor() {} updateName(value: FormName): Action { return { type: FormActions.UPDATE_NAME, payload: value }; } updateDate(value: string): Action { return { type: FormActions.UPDATE_DATE, payload: value }; } updateLocation(value: FormLocation): Action { return { type: FormActions.UPDATE_LOCATION, payload: value }; } updateExtra(value: any): Action { return { type: FormActions.UPDATE_EXTRA, payload: value }; } updateState(value: any): Action { return { type: FormActions.UPDATE_STATE, payload: value }; } dateToNow(): Action { return { type: FormActions.UPDATE_DATE, payload: getCurrentTime() }; } noLocationApi(): Action { return { type: FormActions.NO_GEO_LOCATE }; } locationToHere() { return { type: FormActions.LOCATION_TO_HERE }; } reset(): Action { return { type: FormActions.RESET }; } } function getCurrentTime() { const now = new Date(); function pad(number) { if (number < 10) { return '0' + number; } return number; } return now.getFullYear() + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate()) + 'T' + pad(now.getHours()) + ':' + pad(now.getMinutes()); }
c463772c11dcb6242be8ad061aa01eec50170970
TypeScript
Paul12pp/opensourceweb
/ClientApp/src/app/core/tokens/route-param.token.ts
2.5625
3
import { InjectionToken } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; export const ROUTE_PARAM_TOKEN = new InjectionToken<Observable<string>>( 'Stream of route param from activated route' ); // if you want to get :id from route, declare this token export const PARAM_KEY_ID = new InjectionToken<string>( 'static string for :id param key', // this is the second argument of InjectionToken constructor // to produce the value, like when you use useFactory { factory: () => { return 'id'; } } ); // if you want to get :someId from the route, the token should look like this export const PARAM_KEY_SOME_ID = new InjectionToken<string>( 'static string for :someId param key', { factory: () => { return 'someId'; } } ); export function routeParamFactory( route: ActivatedRoute, paramKey: string ): Observable<string> { // should use paramMap because route.params will be deprecated soon return route.paramMap.pipe(map((param) => param.get(paramKey))); }
30e21000fee390aba09e20006bc537dc6ebca35e
TypeScript
mombachm/holdermind-stock-service
/src/routingControllers/StockController.ts
2.734375
3
import * as express from "express"; import { RoutingController } from "./abstractRoutingController/RoutingController"; import { StockService } from "../services/StockService"; export enum StockControllerRoute { GetStockMainInfo = "/getStockMainInfo", GetStocksInfo = "/getStocksInfo", SearchStocks = "/searchStocks" } export enum StockControllerParameter { StockCode = "stockCode", StocksCode = "stocksCode", SearchText = "searchText" } export class StockController extends RoutingController { protected assembleRoutes(): void { this.router.get(StockControllerRoute.GetStocksInfo, this.getStocksInfo.bind(this)); this.router.get(StockControllerRoute.GetStockMainInfo, this.getStockMainInfo.bind(this)); this.router.get(StockControllerRoute.SearchStocks, this.searchStocks.bind(this)); } public async getStocksInfo(req: express.Request, res: express.Response): Promise<void> { const stocksCode = req.query.stocksCode.toString().split(","); const stockInfo = await StockService.getStocksInfo(stocksCode); res.json(stockInfo); } public async getStockMainInfo(req: express.Request, res: express.Response): Promise<void> { const stocksCode = req.query.stockCode.toString(); const stockInfo = await StockService.getStockMainInfo(stocksCode); res.json(stockInfo); } public async searchStocks(req: express.Request, res: express.Response): Promise<void> { const searchText = this.extractValidParameter(req, res, StockControllerParameter.SearchText); const searchResult = await StockService.searchStocks(searchText); res.json(searchResult); } }
ab22200e45ab588c2f9c2bd64c0916510f6bf1ee
TypeScript
siyoola/astrograph
/src/service/dex/offers_graph.ts
2.875
3
import { BigNumber } from "bignumber.js"; import { AssetID } from "../../model"; import { Offer } from "../../orm/entities"; import logger from "../../util/logger"; interface IEdgeData { capacity: BigNumber; orderBook: AssetOrders; } interface IEdge { vertex: AssetID; data: IEdgeData; } class AssetOrder { public readonly amount: BigNumber; public readonly price: BigNumber; // we use it just for sorting public readonly priceN: number; public readonly priceD: number; constructor(offer: Offer) { this.amount = offer.amount; this.price = offer.price; this.priceD = offer.priceD; this.priceN = offer.priceN; } public get sellingBound() { if (this.priceN > this.priceD) { return this.amount; } return this.amount .times(this.priceN) .div(this.priceD) .integerValue(BigNumber.ROUND_FLOOR) .times(this.priceD) .div(this.priceN) .integerValue(BigNumber.ROUND_CEIL); } } class AssetOrders { constructor(private readonly orders: AssetOrder[] = []) {} public getOrders() { // return copy of the orders return this.orders.map(o => o); } public addOrder(order: AssetOrder): void { this.orders.push(order); } public sort() { this.orders.sort((a, b) => a.price.comparedTo(b.price)); } public buy(amountToBuy: BigNumber): BigNumber { let amountToSell = new BigNumber(0); for (const order of this.orders) { const amount = order.sellingBound; const { priceN, priceD } = order; if (amountToBuy.gt(amount)) { amountToSell = amountToSell.plus(amount.times(priceN).div(priceD)); amountToBuy = amountToBuy.minus(amount); } else { amountToSell = amountToSell.plus(amountToBuy.times(priceN).div(priceD)); break; } } return amountToSell; } } export class OffersGraph { public static build(offers: Offer[]) { const graph = new OffersGraph(); graph.build(offers); return graph; } private readonly edges: Map<AssetID, IEdge[]>; constructor() { this.edges = new Map<AssetID, IEdge[]>(); } public build(offers: Offer[]) { for (const offer of offers) { const [assetToBuy, assetToSell] = [offer.buying, offer.selling]; const edge = this.getEdgeData(assetToSell, assetToBuy); const order = new AssetOrder(offer); if (!edge) { this.addEdge(assetToSell, assetToBuy, { capacity: offer.amount, orderBook: new AssetOrders([order]) }); } else { edge.orderBook.addOrder(order); this.updateEdge(assetToSell, assetToBuy, { capacity: edge.capacity.plus(offer.amount), orderBook: edge.orderBook }); } } this.sortOrderBooks(); } public update(selling: AssetID, buying: AssetID, offers: Offer[]): void { if (offers.length === 0) { this.dropEdge(selling, buying); return; } let capacity = new BigNumber(0); const orderBook = new AssetOrders(); for (const offer of offers) { orderBook.addOrder(new AssetOrder(offer)); capacity = capacity.plus(offer.amount); } this.updateEdge(selling, buying, { capacity, orderBook }); this.sortOrderBooks(); } public getEdges(from: AssetID) { return this.edges.get(from); } public addEdge(from: AssetID, to: AssetID, data: IEdgeData): void { const edge = this.getEdge(from, to); if (edge) { throw new Error(`Edge between ${from} and ${to} already exists. Use \`updateEdge\` to overwrite`); } const edges = this.edges.get(from); if (!edges) { this.edges.set(from, [{ vertex: to, data }]); } else { edges.push({ vertex: to, data }); } } public updateEdge(from: AssetID, to: AssetID, data: IEdgeData): void { const edge = this.getEdge(from, to); if (!edge) { return; } edge.data = data; } public getEdgeData(from: AssetID, to: AssetID): IEdgeData | undefined { const edge = this.getEdge(from, to); return edge ? edge.data : undefined; } public dropEdge(from: AssetID, to: AssetID): void { const edges = this.edges.get(from); if (!edges) { return; } const indexToDrop = edges.findIndex(e => e.vertex === to); if (indexToDrop === -1) { logger.warn("Graph seems to be inconsistent"); return; } edges.splice(indexToDrop, 1); this.edges.set(from, edges); } private sortOrderBooks() { this.edges.forEach(edges => { edges.forEach(edge => edge.data.orderBook.sort()); }); } private getEdge(from: AssetID, to: AssetID) { const edges = this.edges.get(from); if (!edges) { return; } return edges.find(e => e.vertex === to); } }
62ce5cc22c26aac79cfcd92b332bf8a248e185ce
TypeScript
pikou-xr/vcf-generator
/src/utils/vcf.ts
3
3
import { DataHeaders, FieldName, PhoneNumber } from '../types' import vCardsJS from 'vcards-js' const GUESS_PHONE_FIELD_NAME = [ 'téléphone', 'telephone', 'phone', 'phone number', 'numéro de téléphone', ] const GUESS_NAME_FIELD_NAME = ['pseudo'] export const VCF_FIELD_NAMES: Array<VcfFieldName> = [ 'firstName', 'workPhone', 'email', 'note', ] export const VCF_FIELD_NAMES_REQUIRED: Array<VcfFieldName> = [ 'firstName', 'workPhone', ] // TODO : i18n export const VCF_FIELD_NAMES_DISPLAY = { workPhone: 'téléphone', firstName: 'nom', } export interface VcfContact { firstName: string workPhone: PhoneNumber email: string note: string } export type VcfFieldName = keyof VcfContact export interface VcfFieldMapping { firstName: FieldName | null workPhone: FieldName | null email: FieldName | null note: FieldName | null } // Helper function, guesses the right field name from `headers` by picking from options in `guessList`. const guessFieldName = ( headers: DataHeaders, guessList: Array<string>, defaultFieldName: string | null ) => { const headersNormalized = headers.map((possibleName) => possibleName.toLowerCase() ) let guessedFieldName: string | null = null for (let possibleName of guessList) { const headerIndex = headersNormalized.indexOf(possibleName) if (headerIndex !== -1) { guessedFieldName = headers[headerIndex] break } } return guessedFieldName || defaultFieldName } export const getEmptyVcfFieldMapping = () => ({ firstName: null, workPhone: null, email: null, note: null, }) export const getDefaultVcfFieldMapping = ( headers: DataHeaders ): VcfFieldMapping => { return { firstName: guessFieldName( headers, GUESS_NAME_FIELD_NAME, headers[0] || null ), workPhone: guessFieldName( headers, GUESS_PHONE_FIELD_NAME, headers[1] || null ), email: null, note: null, } } export const contactsToVcard = (contacts: Array<VcfContact>) => { const vCardStrings = [] for (const contact of contacts) { const vCard = vCardsJS() Object.entries(contact).forEach( ([name, value]) => (vCard[name as VcfFieldName] = value) ) vCardStrings.push(vCard.getFormattedString()) } return vCardStrings.join('\n') }
bee227c3e6d4860514118ba0eef2620c240056be
TypeScript
Alorel/rxutils
/projects/rxutils/creators/asyncMap.spec.ts
2.796875
3
import {expect} from 'chai'; import {noop} from 'lodash'; import type {Observable} from 'rxjs'; import {lastValueFrom, of, timer} from 'rxjs'; import {map, skip, take, tap} from 'rxjs/operators'; import {finaliseObserver} from '../util/finaliseObserver'; import type {asyncFilter} from './asyncFilter'; import {asyncMap} from './asyncMap'; /* eslint-disable @typescript-eslint/no-magic-numbers */ type Def = [string, any]; type Meth = typeof asyncMap | typeof asyncFilter; const _tAsyncMapFilterCommon = { inpNotArray(meth: Meth): Def { return <Def>Object.freeze(['Should throw if input is not an array', (cb: any) => { let errored = false; let emitted = false; (meth as any)(1, noop) .pipe( tap({ error: () => { errored = true; }, next: () => { emitted = true; } }) ) .subscribe(finaliseObserver(() => { if (emitted) { cb(new Error('Emitted')); } else if (errored) { cb(); } else { cb(new Error('Did not error')); } })); }]); }, sameArray(meth: Meth): Def { return <Def>Object.freeze(['Should emit the same array if it\'s empty', async () => { const arr: any[] = []; const v = await lastValueFrom((meth as any)(arr, noop)); expect(v).to.eq(arr); }]); } }; Object.freeze(_tAsyncMapFilterCommon); export {_tAsyncMapFilterCommon}; describe('creators/asyncMap', function () { it.apply(it, <any>_tAsyncMapFilterCommon.inpNotArray(asyncMap)); it.apply(it, <any>_tAsyncMapFilterCommon.sameArray(asyncMap)); describe('emitIntermediate', () => { function mapper(inp: number, idx: number): Observable<number> { return timer(0, 25).pipe( skip(1), take(3), map(v => inp * v * (idx + 1)) ); } const valueSpecs: Array<[boolean | undefined, number[], number | string]> = [ [undefined, [3, 12, 27], 1], [true, [3, 12, 27], '3'] ]; valueSpecs.unshift([false, valueSpecs[0][1].slice(), 1]); for (const [emit, expArray, expEmissions] of valueSpecs) { const expEmissionsString = typeof expEmissions === 'string' ? `${expEmissions}+` : expEmissions.toString(); describe(`When emitIntermediate is ${String(emit)}`, () => { let emissions: number; let out: number[]; before('Run', cb => { emissions = 0; out = []; asyncMap([1, 2, 3], mapper, emit) .subscribe({ complete() { cb(); }, error: cb, next: v => { emissions++; out = v.slice(0); } }); }); it(`Should emit ${expEmissionsString} time(s)`, () => { const xp = expect(emissions).to; if (typeof expEmissions === 'number') { xp.eq(expEmissions); } else { xp.be.gte(parseFloat(expEmissions)); } }); it(`Should output [${expArray.join(', ')}]`, () => { expect(out).to.deep.eq(expArray); }); }); } }); describe('thisArg', () => { class Mapper { public readonly num = 2; public map(v: number): Observable<number> { return of(v * this.num); } } let inst: Mapper; beforeEach(() => { inst = new Mapper(); }); it('Should apply thisArg', async () => { const o$ = asyncMap([1, 2, 3], inst.map, false, inst); expect(await lastValueFrom(o$)).to.deep.eq([2, 4, 6]); }); }); it('Should accept a promise input', async () => { const v$ = asyncMap([1, 2, 3], v => Promise.resolve(v * 2)); expect(await lastValueFrom(v$)).to.deep.eq([2, 4, 6]); }); it('Should observify filter method errors', () => { const msg = Math.random().toString(); function mapper() { throw new Error(msg); } asyncMap<any, any>([1], <any>mapper); }); });
2789ab3bffae8582900fae29a39f9098da547fb3
TypeScript
thienth32/PT15211-WEB-angular
/src/app/components/hero-form/hero-form.component.ts
2.59375
3
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Hero } from 'src/app/models/hero'; import { Skill } from 'src/app/models/skill'; @Component({ selector: 'hero-form', templateUrl: './hero-form.component.html', styleUrls: ['./hero-form.component.css'] }) export class HeroFormComponent implements OnInit { @Input() formObject: Hero; @Output() submitForm = new EventEmitter<Hero>(); lstSkills: Array<Skill> = [ { id: 1, name: "PHP" }, { id: 2, name: "javascript" }, { id: 3, name: "HTML" }, { id: 4, name: "CSS" } ]; constructor() { } ngOnInit(): void { } submitHeroForm(event){ event.preventDefault(); this.submitForm.emit(this.formObject); } addSkill2FormObject(item: Skill, event){ if(event.target.checked == true){ let index = this.formObject.skills.findIndex(e => e.id == item.id); if(index == -1){ this.formObject.skills.push(item); } }else{ this.formObject.skills = this.formObject.skills.filter(e => e.id != item.id); } } setCheckedCheckbox(item: Skill){ if(this.formObject.skills == undefined){ this.formObject.skills = []; } let index = this.formObject.skills.findIndex(el => el.id == item.id ); return index != -1; } resetForm(): Hero{ return { id: 0, name: "", image: "", skills: [] }; } }
e6c14f8c8bcbec8d79d15b6895487ae5bf97387f
TypeScript
thiagoleta/coletrasnFrontEnd
/src/app/models/coluna-generica.model.ts
2.6875
3
export class ColunaGenerica { constructor(titulo: string, data: any, ordernar: boolean, largura?: string, dataTitle?: string, style?: object, dataLimited?: boolean) { this.titulo = titulo; this.data = data; this.ordernar = ordernar; this.largura = largura; if (!this.largura || this.largura.length === 0) this.largura = 'auto'; this.dataTitle = dataTitle; this.style = style; this.dataLimited = dataLimited; } titulo: string; data: any; ordernar: boolean; largura: string; dataTitle: string; style: object; dataLimited: boolean; }
44a0eeb0948291c70df27b33bb9be1016967c753
TypeScript
eguneys/csgo-faceit
/modules/pool/poolmember.ts
2.625
3
import { UserId } from '../user/user'; import { SocketSri } from '../socket/socket'; import { Joiner } from './poolapi'; import { PoolConfig } from './poolconfig'; export type RatingRange = 'TODO implement me'; export class PoolMember { static make = (userId: UserId, sri: SocketSri, rating: number, ratingRange: Maybe<RatingRange>) => new PoolMember(userId, sri, rating, ratingRange) static makeWithJoin = (joiner: Joiner, config: PoolConfig) => new PoolMember(joiner.userId, joiner.sri, joiner.rating, undefined) constructor( readonly userId: UserId, readonly sri: SocketSri, readonly rating: number, readonly ratingRange: Maybe<RatingRange>, readonly misses: number = 0) { } get incMisses() { return new PoolMember(this.userId, this.sri, this.rating, this.ratingRange, this.misses + 1) } ratingDiff(other: PoolMember) { return Math.abs(this.rating - other.rating) } }
81e3f336d3bfef7cbe00efe022ca58a34330d1fc
TypeScript
HitoriSensei/omdb
/vendor/store/guard-reducer.ts
3.0625
3
import { HydrateAction } from './initial-state' /** * Type-checks reducer to implement every action of giver Actions set * @param initial * @param f */ export function guardReducer< Actions extends { [action: string]: ActionPayload<any> | null }, Store >(initial: Store, f: (store: Store, action: ActionOf<Actions> | HydrateAction) => Store) { return (store: any = initial, action: ActionOf<Actions> | HydrateAction) => f(store, action) ?? store }
8f40d71ebe6ce90bc46702797cefcaacf950ae32
TypeScript
pcn-cad-bupt/api-gateway
/src/auth/jwt.ts
2.859375
3
import * as jwt from 'jsonwebtoken' const secret = 'universe-auth' export interface TokenInfo { username: string, passwd : string, iat : number, // 创建时间 exp : number // 过期时间 } export class Token { // 时间单位为天 public static async sign(username: string, passwd: string, expires?: number): Promise<string> { let expiresIn: number | string = '100y' if (expires) { expires = expires * 24 * 60 * 60 expiresIn = expires } return jwt.sign({username: username, passwd: passwd}, secret, {expiresIn: expiresIn}) } public static async verify(token: string): Promise<TokenInfo> { return new Promise((resolve, reject) => { jwt.verify(token, secret, (err, data) => { if (err) { reject(err) } else { resolve(data as TokenInfo) } }) }) } }
ecf9d684b5747a62deddc810b8ca6e51e3ffc55c
TypeScript
su37josephxia/kaikeba-code
/node/09/ts-server/src/routes/user.ts
2.6875
3
import * as Koa from 'koa' import { get, post, middlewares, querystring } from '../utils/decors' const users = [{ name: 'tom', age: 20 }] const api = { findByName(name) { return new Promise((resolve, reject) => { setTimeout(() => { if (name === 'xia') { reject('用户已存在') } else { resolve() } }, 500) }) } } import model from '../model/user' // @middlewares([ // async function guard(ctx: Koa.Context, next: () => Promise<any>) { // console.log('guard', ctx.header); // if (ctx.header.token) { // await next(); // } else { // throw "请登录"; // } // } // ]) export default class User { @get('/users') @querystring({ age: { type: 'int', required: false, max: 200, convertType: 'int' }, }) public async list(ctx: Koa.Context) { // ctx.body = { ok: 1, data: users } const users = await model.findAll() ctx.body = { ok: 1, data: users }; } @post('/users', { middlewares: [ async function validation(ctx: Koa.Context, next: () => Promise<any>) { // 用户名必填 const name = ctx.request.body.name if (!name) { throw "请输入用户名"; } // 用户名不能重复 try { await api.findByName(name); // 校验通过 await next(); } catch (error) { throw error; } } ] }) public add(ctx: Koa.Context) { users.push(ctx.request.body); ctx.body = { ok: 1 } } }
a35fe127585573c1d3c28100694d5403b4b079fd
TypeScript
forforf/justgraphit
/src/StorageModel/Storage.ts
3.125
3
import IsEmpty from 'lodash.isempty'; import { GraphName, JustGraphitEntry, JustGraphitStore, } from '../JustGraphitTypes'; // ToDo Needs testing: // It's just an thin abstraction layer above a persistent store (local storage in this case) // and should not have any JustGraphit dependencies class LocalStorageWrapper { mainKey: string; constructor(mainKey = '__justgraphit__') { this.mainKey = mainKey; } load = () => { return JSON.parse(localStorage.getItem(this.mainKey) ?? '{}'); }; // We are saving an entire JSON object using mainKey // The saved JSON object should have keys of it's own to be // meaningful in this context. save = (value: unknown) => { localStorage.setItem(this.mainKey, JSON.stringify(value)); }; } class Storage { persistentStore: LocalStorageWrapper; store: JustGraphitStore; constructor(initialObj: JustGraphitStore) { const initialObject: JustGraphitStore = IsEmpty(initialObj) ? {} : initialObj; this.persistentStore = new LocalStorageWrapper(); this.store = this.persistentStore.load(); if (this.isEmpty()) { this.persistentStore.save(initialObject); this.store = this.persistentStore.load(); } } deleteObject = (key: string): boolean => { const deleteRetVal = delete this.store[key] ?? ''; if (deleteRetVal) { this.updatePersistence(); } return deleteRetVal; }; getAll = (): JustGraphitStore => this.store; getAllKeys = (): GraphName[] => Object.keys(this.getAll()); getInitialKey = (): GraphName => Object.keys(this.store)[0]; getInitialObject = (): Record<GraphName, JustGraphitEntry[]> => { return { [this.getInitialKey()]: this.store[this.getInitialKey()] }; }; isEmpty = (): boolean => IsEmpty(this.store); load = (key: string): JustGraphitEntry[] => this.store[key]; save = (key: GraphName, val: JustGraphitEntry[]): GraphName => { this.store[key] = val; this.updatePersistence(); return key; }; updatePersistence = (): void => { this.persistentStore.save(this.store); }; } export default Storage;
565ef1968d1cf3cf038b7b5409d214cfbeffeee5
TypeScript
ysfaran/react-fluent-form
/test/DefaultValidator.test.ts
3.09375
3
import * as yup from "yup"; import { DefaultValidator } from "../src/validation/DefaultValidator"; import { TestModel } from "./types"; describe("DefaultValidator", () => { let testModel: TestModel; beforeEach(() => { testModel = { aString: "some-string", aDate: new Date(1970, 1, 1), }; }); it("is able to execute validations for all fields (validateAllFields)", () => { const validator = new DefaultValidator<TestModel>({ aString: yup.mixed(), aDate: yup.mixed(), }); validator.validateField = jest.fn(() => 1) as any; const result = validator.validateAllFields(testModel, { context: "context", }); expect(result).toMatchObject({ aString: 1, aDate: 1, }); expect(validator.validateField).toHaveBeenCalledWith("aString", testModel, { context: "context", }); expect(validator.validateField).toHaveBeenCalledWith("aDate", testModel, { context: "context", }); }); describe("validateField", () => { it("logs a warning when yup throws an error other than ValidationError", () => { const validator = new DefaultValidator<TestModel>({ aString: yup.string().when("aString", { is: () => 1 / 0, then: "error should be thrown before" as any, }), }); console.warn = jest.fn(); validator.validateField("aString", testModel); expect(console.warn).toHaveBeenCalledWith( expect.any(String), expect.any(Error) ); }); it("doesn't validate if neither a function or yup schema was provided and logs warning", () => { const validator = new DefaultValidator<TestModel>({ aString: 1 as any, }); console.warn = jest.fn(); const result = validator.validateField("aString", testModel); expect(result).not.toBeDefined(); expect(console.warn).toHaveBeenCalledWith(expect.any(String), 1); }); it("returns undefined when no validation was passed ", () => { const validator = new DefaultValidator<TestModel>({}); const result = validator.validateField("aString", testModel); expect(result).not.toBeDefined(); }); it("returns result of yup validation properly", () => { const validator = new DefaultValidator<TestModel>({ aString: yup.string().min(20), }); const result = validator.validateField("aString", testModel); expect(result).toEqual(expect.any(Array)); }); it("returns result of custom validation function", () => { const validator = new DefaultValidator<TestModel>({ aString: () => { return 1; }, }); const result = validator.validateField("aString", testModel); expect(result).toBe(1); }); it("allows to return yup validation conditionally", () => { const validator = new DefaultValidator<TestModel>({ aString: (_value, values) => { if (values.aDate) { return yup.string().min(15, "conditional yup.min(15) error"); } else { return yup.string().min(20, "conditional yup.min(20) error"); } }, }); let result = validator.validateField("aString", testModel); expect(result).toEqual(["conditional yup.min(15) error"]); testModel.aDate = null; result = validator.validateField("aString", testModel); expect(result).toEqual(["conditional yup.min(20) error"]); }); it("considers context when validating with validation function", () => { const validator = new DefaultValidator<TestModel>({ aString: (_value, _values, context) => { if (context.contextValue === 1) { return yup.string().min(20); } }, }); let result = validator.validateField("aString", testModel, { contextValue: 1, }); expect(result).toMatchObject(expect.any(Array)); result = validator.validateField("aString", testModel, { contextValue: 2, }); expect(result).not.toBeDefined(); }); it("considers context when validating with yup schema", () => { const validator = new DefaultValidator<TestModel>({ aDate: yup.date().when("$contextValue", { is: 1, then: yup.date().min(new Date(2000, 1, 2)), }), }); let result = validator.validateField("aDate", testModel, { contextValue: 1, }); expect(result).toEqual(expect.any(Array)); result = validator.validateField("aDate", testModel, { contextValue: 2 }); expect(result).not.toBeDefined(); }); it("allows using other fields as yup context for validation", () => { const validator = new DefaultValidator<TestModel>({ aDate: yup.date().when("$aString", { is: "condition", then: yup.date().min(new Date(2000, 1, 1)), }), }); let result = validator.validateField("aDate", testModel); expect(result).not.toBeDefined(); testModel.aString = "condition"; result = validator.validateField("aDate", testModel); expect(result).toEqual(expect.any(Array)); }); }); });
52a13b943120943422593d20c33bd9378cb0015a
TypeScript
qstiegler/angular-1-typescript-setup
/src/app/modules/pwned/search.controller.ts
2.625
3
module HaveIBeenPwned { "use strict"; interface ISearchController { //submit(address: string): void } interface ISearchControllerScope extends ng.IScope { vm: ISearchController } class SearchController implements ISearchController { static $inject = ["$scope", "PwnedService"]; constructor($scope: ISearchControllerScope, private pwnedService: IPwnedService) { $scope.vm = this; console.log('in controller'); } private breachedAccounts: BreachedAccount[]; submit(address: string) { this.pwnedService.check(address) .then((result: ng.IHttpPromiseCallbackArg<BreachedAccount[]>) => { this.breachedAccounts = result.data; }) .catch((reason: any) => { alert(reason.Message || reason.message); }); } } angular .module("app.pwned") .controller("SearchController", SearchController); }
e67ec0aacb2b9fb00cbdf76f4e3bba8618d3baac
TypeScript
dngwoo/TIL
/Language/Typescript/docs/c- function/5-0.overloads.ts
3.6875
4
let suits = ["hearts", "spades", "clubs", "diamonds"]; function pickCard2(x):any { if(typeof x === "object") { let pickedCard = Math.floor(Math.random() * x.length); return pickedCard } else if(typeof x === "number"){ let pickedSuit = Math.floor(x/13); return { suit: suits[pickedSuit], card: x % 13}; } } let myDeck = [{ suit: "diamonds", card: 2 },{ suit: "spades", card: 10 },{ suit: "hearts", card: 4 }] let pickedCard1 = myDeck[pickCard2(myDeck)]; // pickCard2(myDeck) 애는 0 ,1, 2 셋중 하나 출력, any로 잡혀있음. alert("card: " + pickedCard1.card + " of " + pickedCard1.suit); let pickedCard2 = pickCard2(15); // 애는 로직 보면 바로 이해 됨, 얘도 any로 잡혀있음. alert("card: " + pickedCard2.card + " of " + pickedCard2.suit); // 5-1.overloads.ts에서 typescript로 이 로직을 어떻게 구현할 것인지 정리
91fac65ff339e52fac483432ed2164086448e745
TypeScript
studyTsNote/typescript-learning
/ts-basic/src/example/basic-type.ts
4.15625
4
// 布尔 const bool: boolean = true; // 简单类型 ts 可自动推断,所以实际不用声明 // eslint 也会帮忙自动优化写法,但由于练习代码,故配置里关了该条建议 // 数值 let num: number = 123; num = 0b1111011; num = 0o173; num = 0x7b; // 字符串 const str: string = 'abc'; // 数组 const arr1: number[] = [1, 2, 3]; const arr2: Array<number> = [1, 2, 3]; const arr3: Array<string | number> = [1, 2, 'a']; // 元组:数值类型一一对应 const tuple: [string, number ,boolean] = ['a', 1, false]; // 枚举 enum Roles { SUPER_ADMIN, ADMIN, USER = 'user' } console.log(Roles); // any let val: any; let vals: Array<any>; // void: 可赋值 undefined const printMsg = (msg: string): void => { console.log(msg); } printMsg('Hello TS!'); const u: undefined = undefined; const n: null = null; // 无返回值:抛异常或死循环 const errorFn = (): never => { throw new Error('error'); } // 对象 function printObj(obj: Record<string, unknown>): void { console.log(JSON.stringify(obj)); } // 类型断言 const getLen = (target: string | number): number => { if ((<string>target).length || (target as string).length) { return (target as string).length; } else { return target.toString().length; } } console.log(getLen('abc')); console.log(getLen(123));
f38a1017b9f84beca7765d4439cda86ea645d5dd
TypeScript
flavioespinoza/vsce-wordcounter
/src/wordCounter.ts
2.5625
3
import { ConfigurationChangeEvent, Disposable, EndOfLine, Selection, StatusBarAlignment, StatusBarItem, TextDocument, TextDocumentChangeEvent, TextEditorSelectionChangeEvent, window, workspace, } from 'vscode'; interface TextConfig { word: string; words: string; char: string; chars: string; line: string; lines: string; paragraph: string; paragraphs: string; word_delimiter: string; delimiter: string; readingtime: string; } interface WordCounterConfiguration { count_words: boolean; count_chars: boolean; count_lines: boolean; count_paragraphs: boolean; readtime: boolean; simple_wordcount: boolean; include_eol_chars: boolean; wpm: number; side_left: Counter[]; side_right: Counter[]; } interface DisplayData { words: number; chars: number; lines: number; paragraphs: number; } type Counter = "word" | "char" | "line" | "paragraph" | "readingtime" export class WordCounter { wordRegEx: RegExp = /[\S]+/g; wordRegExSub: RegExp = /[\w\u0370-\uffef]+/; crlfRE = { split: /\r\n[\r\n]+/, replace: /\r\n/g }; lfRE = { split: /\n\n+/, replace: /\n/g }; statusBarItemLeft: StatusBarItem; statusBarItemRight: StatusBarItem; text: TextConfig = {} as TextConfig; config: WordCounterConfiguration = {} as WordCounterConfiguration; constructor() { this.statusBarItemLeft = window.createStatusBarItem(StatusBarAlignment.Left); this.statusBarItemRight = window.createStatusBarItem(StatusBarAlignment.Right); } updateConfiguration(configuration: WordCounterConfiguration, text: TextConfig) { this.config = configuration; this.text = text; } update(fromSelection: boolean = true) { if (!this.statusBarItemLeft) { this.statusBarItemLeft = window.createStatusBarItem(StatusBarAlignment.Left); } if (!this.statusBarItemRight) { this.statusBarItemRight = window.createStatusBarItem(StatusBarAlignment.Right); } const editor = window.activeTextEditor; if (!editor) { this.statusBarItemLeft.hide(); this.statusBarItemRight.hide(); return; } const bSelectionSimple = fromSelection && editor.selections.length === 1 && !editor.selection.isEmpty; const bSelectionMultiple = fromSelection && editor.selections.length > 1; if (bSelectionSimple) { this.statusBarItemLeft.text = this.countSelectedSimple(editor.document, editor.selection, StatusBarAlignment.Left); this.statusBarItemRight.text = this.countSelectedSimple(editor.document, editor.selection, StatusBarAlignment.Right); } else if (bSelectionMultiple) { this.statusBarItemLeft.text = this.countSelectedMultiple(editor.document, editor.selections, StatusBarAlignment.Left); this.statusBarItemRight.text = this.countSelectedMultiple(editor.document, editor.selections, StatusBarAlignment.Right); } else { this.statusBarItemLeft.text = this.countAll(editor.document, StatusBarAlignment.Left); this.statusBarItemRight.text = this.countAll(editor.document, StatusBarAlignment.Right); } this.statusBarItemLeft.show(); this.statusBarItemRight.show(); } hide() { this.statusBarItemLeft.hide(); this.statusBarItemRight.hide(); } dispose() { this.statusBarItemLeft.dispose(); this.statusBarItemRight.dispose(); } toDisplay(oIn: DisplayData, alignment: StatusBarAlignment) { const order = alignment === StatusBarAlignment.Left ? this.config.side_left : this.config.side_right; const map = {} as Record<Counter, string> if (this.config.count_words && order.includes("word")) { const val = oIn.words; const text = val === 1 ? this.text.word : this.text.words; map["word"] = `${val}${this.text.word_delimiter}${text}`; } if (this.config.count_chars && order.includes("char")) { const val = oIn.chars; const text = val === 1 ? this.text.char : this.text.chars; map["char"] = `${val}${this.text.word_delimiter}${text}`; } if (this.config.count_lines && order.includes("line")) { const val = oIn.lines; const text = val === 1 ? this.text.line : this.text.lines; map["line"] = `${val}${this.text.word_delimiter}${text}`; } if (this.config.count_paragraphs && order.includes("paragraph")) { const val = oIn.paragraphs; const text = val === 1 ? this.text.paragraph : this.text.paragraphs; map["paragraph"] = `${val}${this.text.word_delimiter}${text}`; } if (this.config.readtime && order.includes("readingtime")) { const div = oIn.words / this.config.wpm; const m = Math.floor(div); const s = Math.round(60 * (div - m)); map["readingtime"] = `~${m}m${s}s ${this.text.readingtime}`; } return order.map(key => map[key]); } computeResult(doc: TextDocument, content: string, hasSelectedText: boolean, alignment: StatusBarAlignment) { const aDisplay = this.toDisplay({ words: this.wordCount(content), chars: this.charCount(content, doc.eol), lines: this.lineCount(content, hasSelectedText, doc), paragraphs: this.paragraphCount(content, doc.eol) } as DisplayData, alignment); return aDisplay.join(this.text.delimiter); } countSelectedSimple(doc: TextDocument, selection: Selection, alignment: StatusBarAlignment) { var content = doc.getText(selection.with()); return this.computeResult(doc, content, true, alignment); } charCount(content: string, linefeed: EndOfLine) { if (this.config.include_eol_chars) { return content.length; } const re = linefeed === EndOfLine.CRLF ? this.crlfRE.replace : this.lfRE.replace; return content.replace(re, '').length; } lineCount(content: string, hasSelectedText: boolean, doc: TextDocument) { if (this.config.count_lines) { if (hasSelectedText) { return content.split('\n').length; } return doc.lineCount; } return 1; } wordCount(content: string) { if (content && (this.config.count_words || this.config.readtime)) { const matches = content.match(this.wordRegEx); if (matches) { if (!this.config.simple_wordcount) { return matches.filter(s => { const submatches = s.match(this.wordRegExSub); return submatches ? submatches.length > 0 : false; }).length; } return matches.length; } } return 0; } paragraphCount(content: string, linefeed: EndOfLine) { if (content && this.config.count_paragraphs) { const re = linefeed === EndOfLine.CRLF ? this.crlfRE : this.lfRE; return content .split(re.split) .map(p => p.replace(re.replace, '')) .filter(p => p.length > 0) .length; } return 0; } countSelectedMultiple(doc: TextDocument, selections: Selection[], alignment: StatusBarAlignment) { let words = 0; let chars = 0; let paragraphs = 0; let lines = 0; selections.forEach(selection => { const content = doc.getText(selection.with()); if (this.config.count_words) { words += this.wordCount(content); } if (this.config.count_paragraphs) { paragraphs += this.paragraphCount(content, doc.eol); } if (this.config.count_chars) { chars += content.length; } if (this.config.count_lines) { if (selection.isSingleLine) { lines++; } else { lines += selection.end.line - selection.start.line + 1; } } }); const aDisplay = this.toDisplay({ words: words, chars: chars, lines: lines, paragraphs: paragraphs } as DisplayData, alignment); return aDisplay.join(this.text.delimiter); } countAll(doc: TextDocument, alignment: StatusBarAlignment) { return this.computeResult(doc, doc.getText(), false, alignment); } } export class WordCounterController { wordCounter: WordCounter; disposable: Disposable; currentEol?: EndOfLine = EndOfLine.LF; enabled: boolean = false; languages: string[] = []; throttleWait: boolean = false; throttleLimit: number = 100; constructor(wordCounter: WordCounter) { this.wordCounter = wordCounter; this.reloadConfig(); const subscriptions: Disposable[] = []; window.onDidChangeTextEditorSelection(this._onEventTextEditorSelection, this, subscriptions); window.onDidChangeActiveTextEditor(this._onDidChangeActiveTextEditor, this, subscriptions); workspace.onDidChangeConfiguration(this._onEventWhenConfChanged, this, subscriptions); workspace.onDidChangeTextDocument(this._onDidChangeTextDocument, this, subscriptions); if (window.activeTextEditor && this._couldUpdate()) { this._doUpdateComplete(); } this.disposable = Disposable.from.apply(Disposable, subscriptions); } dispose() { this.disposable.dispose(); } _couldUpdate() { return this.enabled && window && window.activeTextEditor && (this.languages === null || this.languages.includes(window.activeTextEditor.document.languageId)); } _doUpdateComplete() { if (!this.throttleWait) { this._storeCurrentEOL(); this.wordCounter.update(false); this.throttleWait = true; setTimeout(() => { this.throttleWait = false; }, this.throttleLimit); } } _doUpdatePartial() { if (!this.throttleWait) { this._storeCurrentEOL(); this.wordCounter.update(true); this.throttleWait = true; setTimeout(() => { this.throttleWait = false; }, this.throttleLimit); } } _storeCurrentEOL() { this.currentEol = window.activeTextEditor?.document.eol; } _onDidChangeActiveTextEditor(event: any) { if (this._couldUpdate()) { this._doUpdateComplete(); } else { this.wordCounter.hide(); } } _onDidChangeTextDocument(event: TextDocumentChangeEvent) { if (this._couldUpdate()) { this._doUpdateComplete(); } } _onEventTextEditorSelection(event: TextEditorSelectionChangeEvent) { if (this._couldUpdate()) { if (event.selections.filter(s => !s.isEmpty).length > 0) { this._doUpdatePartial(); } else { this._doUpdateComplete(); } } else { this.wordCounter.hide(); } } _onEventWhenConfChanged(event: ConfigurationChangeEvent) { this.reloadConfig(); if (this._couldUpdate()) { this._doUpdateComplete(); } else { this.wordCounter.hide(); } } reloadConfig() { const configuration = workspace.getConfiguration('wordcounter'); this.languages = configuration.get('languages', []); const side_left = configuration.get('side.left', ["word", "char", "line", "paragraph", "readingtime"]) as Counter[] const side_right = configuration.get('side.right', []) as Counter[] const enabling = new Set<Counter>(Array.from(side_left).concat(side_right)) let config: WordCounterConfiguration = { count_words: enabling.has("word"), count_chars: enabling.has("char"), count_lines: enabling.has("line"), count_paragraphs: enabling.has("paragraph"), readtime: enabling.has("readingtime"), simple_wordcount: configuration.get('simple_wordcount', true), include_eol_chars: configuration.get('include_eol_chars', true), wpm: configuration.get('wpm', 200), side_left, side_right, } as WordCounterConfiguration; const text: TextConfig = { word: configuration.get('text.word'), words: configuration.get('text.words'), char: configuration.get('text.char'), chars: configuration.get('text.chars'), line: configuration.get('text.line'), lines: configuration.get('text.lines'), paragraph: configuration.get('text.paragraph'), paragraphs: configuration.get('text.paragraphs'), word_delimiter: configuration.get('text.word_delimiter'), delimiter: configuration.get('text.delimiter'), readingtime: configuration.get('text.readingtime') } as TextConfig; if (config.wpm < 1) { config.wpm = 200; } this.enabled = configuration.get('enabled', false) && (config.count_chars || config.count_lines || config.count_paragraphs || config.count_words); this.throttleLimit = configuration.get('throttle_limit', 100); this.wordCounter.updateConfiguration(config, text); } }
de03b6659951b3d0367282eaea049943ae641477
TypeScript
cucumber/cucumber-js
/src/plugin/plugin_manager.ts
2.671875
3
import { Plugin, PluginCleanup, PluginEvents } from './types' import { IRunEnvironment, IRunOptions } from '../api' import { ILogger } from '../logger' type HandlerRegistry = { [K in keyof PluginEvents]: Array<(value: PluginEvents[K]) => void> } export class PluginManager { private handlers: HandlerRegistry = { message: [] } private cleanupFns: PluginCleanup[] = [] constructor(private pluginFns: Plugin[]) {} private async register<K extends keyof PluginEvents>( event: K, handler: (value: PluginEvents[K]) => void ) { this.handlers[event].push(handler) } async init( logger: ILogger, configuration: IRunOptions, environment: IRunEnvironment ) { for (const pluginFn of this.pluginFns) { const cleanupFn = await pluginFn({ on: this.register.bind(this), logger, configuration, environment, }) if (cleanupFn) { this.cleanupFns.push(cleanupFn) } } } emit<K extends keyof PluginEvents>(event: K, value: PluginEvents[K]): void { this.handlers[event].forEach((handler) => handler(value)) } async cleanup(): Promise<void> { for (const cleanupFn of this.cleanupFns) { await cleanupFn() } } }
f17389cb6551a61ae6d5f63bae939dcfee5020be
TypeScript
kjwdamme/SPA-groep-angular
/src/app/models/energyvalue.model.ts
2.65625
3
import {Info} from './info.model'; export class EnergyValue { private _id: string; private _converterId: string; private _timestamp: Date; private _info: Info[]; constructor(values: Object = {}) { Object.assign(this, values); } get id(): string { return this._id; } set id(value: string) { this._id = value; } get converterId(): string { return this._converterId; } set converterId(value: string) { this._converterId = value; } get timestamp(): Date { return this._timestamp; } set timestamp(value: Date) { this._timestamp = value; } get info(): Info[] { return this._info; } set info(value: Info[]) { this._info = value; } }
7d1aa4910d4e686f7ee54a057a213fc567f596e5
TypeScript
hongdeyuan/javascript_fullstack
/WoNiu/TypeScript/ts-study/src/class.ts
4.0625
4
// 抽象类 abstract class Animal { abstract makeSound (): void ; move(): void{ console.log('roaming the earth...') } } // 继承抽象类 && 重写 move class Cat extends Animal{ makeSound () { console.log('miao miao') } move(): void{ super.move() console.log('Cat Move') } } // const cat = new Cat() // cat.makeSound() // 访问限定符 // class Cat { // public run () { // console.log('run ...') // } // // 私有属性 -> 在本身的类中使用 // private eat() { // console.log('吃起来了。。。') // } // // 保护属性 -> 在本身的类中使用 或者 子类中使用 // protected sleep () { // console.log('睡觉吧。。。') // } // } // class CTR extends Cat { // init() { // this.run() // this.sleep() // } // } // const cat = new Cat() // cat.run()// run ... // const ctr = new CTR() // ctr.init() // class 可以作为接口 // public static defaultProps = new Props() // props: props
d53d73d53dc5c97617e8562536e96555097aae6b
TypeScript
robertschurig/photography-portfolio-website
/src/app/shared/image-list.interface.ts
2.59375
3
export interface IImages extends Array<IImage> { [index: number]: IImage; } export interface IImage { title?: string; date?: string; thumb: string; source: string; } export interface ISeries extends Array<ISerie> { [index: number]: ISerie; } export interface ISerie { url: string; } export interface IProjects extends Array<IProject> { [index: number]: IProject; } export interface IProject { title: string; images: IImages; }
7fee99ae1dfaa2a851f4238c2032a8359accbea4
TypeScript
Zeindelf/vtex-api
/src/updateDocument.ts
2.875
3
import partialUpdate from './services/partialUpdate'; /** * Insert/update a document * * @param {string} id The ID of the item that will be inserted/updated * @param {object} data The data that will be inserted * @param {string} entity The entity of the document to insert * * @module masterdata * * @example * const response = await updateDocument({ * id: 'aa65fd51-0dab-11ea-82ee-9e3712d56bb3', * data: { * firstName: 'Edited', * lastName: 'Edited', * ... * }, * entity: 'CL', * }); * * @return {promise} */ const updateDocument = ({ id, data, entity, auth, accountName, }: IPartialUpdateArgs): Promise<IResponse> => ( partialUpdate({ id, data, entity, auth, accountName, }) ); export default updateDocument;
20df43f1d977e9ddd07de5949011590afccbd462
TypeScript
tyankatsu0105/react-perfomance
/packages/client/src/app/application/types/scalars.ts
3.109375
3
import format from 'date-fns/format'; import parseISO from 'date-fns/parseISO'; import { locale } from '~client/app/application/shared/modules/date-fns'; export type TypeScalarID = string; export type TypeScalarFloat = number; export type TypeScalarDateTime = string; export type TypeScalarDate = string; export class ScalarID { constructor(public id: TypeScalarID) {} } export class ScalarFloat { constructor(public float: TypeScalarFloat) {} } /** * ISO 8601準拠 YYYY-MM-DDTHH:mm:ss.sssZ * ex: 2011-10-05T14:48:00.000Z */ export class ScalarDateTime { constructor(public dateTime: TypeScalarDateTime) {} public getFormattedValue(formatString: string): string { const parsedISO = parseISO(this.dateTime); return format(parsedISO, formatString, { locale }); } } /** * YYYY-MM-DD * ex: 2020-01-01 */ export class ScalarDate { constructor(public date: TypeScalarDate) {} /** * @param formatString https://date-fns.org/v2.19.0/docs/format */ public getFormattedValue(formatString: string): string { return format(new Date(this.date), formatString, { locale }); } }
1c715371d2fe2024a652b98f2934ed1ad9c0d63c
TypeScript
macniel/derpyBot
/src/Derpy.ts
2.765625
3
import { Client } from 'discord.io'; import { LetterBag } from './LetterBag'; export class Derpy { private discordClient: Client; private letterBag: LetterBag; private broadcastChannelName: string; constructor(authToken: string) { this.broadcastChannelName = 'general'; this.discordClient = new Client( { autorun: true, token: authToken }); this.getReady(); this.letterBag = new LetterBag(); } private getReady() { this.discordClient.on('ready', () => { this.discordClient.connect(); console.log('derpy is up and ready to take and deliver letters'); }); this.discordClient.on('message', (user, userID, channelID, message, rawEvent) => { if (user === this.discordClient.username) { return; } if (message.startsWith("!derpy")) { message = message.substring(6).trim(); this.parseCommand(user, channelID, message); } }); this.discordClient.on('voiceStateUpdate', (payload: { d: { user_id: string, suppress: boolean, session_id: string, channel_id: string | null } }) => { if (payload.d != null && payload.d.channel_id != null) { const userName = this.getMemberById(payload.d.user_id); const voiceChannel = this.getChannelNamebyId(payload.d.channel_id); this.discordClient.sendMessage( { to: this.getChannelIdByName(this.broadcastChannelName), message: '@everyone ' + userName + ' has joined the Voicechat-channel "' + voiceChannel + '"' }); } }); } private getMemberById(id) { for (const userId in this.discordClient.users) { if (userId === id) { return this.discordClient.users[userId].username; } } throw new Error('User with given Id was not found.'); } private getChannelNamebyId(id) { for (const channelId in this.discordClient.channels) { if (channelId === id) { return this.discordClient.channels[channelId].name; } } throw new Error('Channel with given Id was not found.'); } private getChannelIdByName(name) { for (const channelId in this.discordClient.channels) { if (this.discordClient.channels[channelId].name === name) { return channelId; } } throw new Error('Channel with the name "' + name + '" not found.'); } private parseCommand(userName: string, channelID: string, message: string) { if (message.startsWith('help') || message.trim() == '') { this.greet(channelID, userName); } else if (message.startsWith('say')) { this.say(channelID, message.substring('say'.length)); } else if (message.startsWith('take a letter')) { this.letterBag.addLetterFrom(userName, message.substring('take a letter'.length).trim()); this.say(channelID, `got your letter ${userName}`); } else if (message.startsWith('ps')) { let letter = this.letterBag.getLetterFrom(userName); if (letter == null) { this.say(channelID, `I haven't found a Letter from you, ${userName}.`); } else { this.letterBag.modifyLetterFrom(userName, message.substring('ps'.length).trim()); this.say(channelID, `Got it, ${userName}`); } } else if (message.startsWith('get me my letter')) { let letter = this.letterBag.getLetterFrom(userName); if (letter == null) { this.say(channelID, `I have no Letter for you this time, ${userName}`); } else { this.say(channelID, 'I have found your letter\n```' + letter + '```'); this.letterBag.removeLetterFrom(userName); } }; } private say(channelID: string, what: string) { this.discordClient.sendMessage({ to: channelID, message: what }); } private greet(channelID: string, userName: string) { this.say(channelID, 'Hello ' + userName + '\n' + 'I am your friendly mail mare!' + '\n' + 'You can let me **say** <something>' + '\n' + 'or let me **take a letter** <your letter>,' + '\n' + 'but if you want to add something to it just use **ps** <something>,' + '\n' + 'and just to be sure to get your letter afterwards. ' + '\n' + '**get me my letter** (I will no longer have it then.)'); } }
afb3bcadc2deef4663903b1f07617e40cbf2f54e
TypeScript
FlorentinMonteil/nanogl-pbr
/src/ChunksSlots.ts
3.25
3
import { Hash, mergeHash, hashString } from "./Hash"; class HashedChunkCode { code: string; hash: Hash; constructor( code : string ){ this.code = code; this.hash = hashString( code ); } } class ChunkSlot { readonly key: string; private _hash: number = 0; private hashset: Set<Hash> = new Set(); private codes: HashedChunkCode[] = []; private _code : string = ''; constructor( key : string ){ this.key = key; } add( code : HashedChunkCode ){ if( !this.hashset.has(code.hash ) ){ this.hashset.add( code.hash ) this.codes.push( code ); this._code += code.code + '\n'; this._hash = mergeHash( this._hash, code.hash ); } } merge( other : ChunkSlot ){ for (const hcc of other.codes) { this.add( hcc ); } } get code() : string { return this._code; } get hash() : Hash { return this._hash; } } export default class ChunksSlots { slots : ChunkSlot[]; slotsMap: Record<string, ChunkSlot>; hash: Hash = 0; constructor() { this.slots = []; this.slotsMap = {}; } getHash() : Hash { let hash = 0; for (const slot of this.slots) { hash = mergeHash( hash, slot.hash ); } return hash; } getSlot(id: string) { var s: ChunkSlot = this.slotsMap[id]; if (s === undefined) { s = new ChunkSlot( id ); this.slotsMap[id] = s; this.slots.push(s); } return s; } /** * Called by Chunks to add code to shader slots * @param slotId the slot where code will be insterted * @param code the glsl code to inject */ add(slotId: string, code: string) { this.getSlot(slotId).add( new HashedChunkCode( code )); } /** * merge all Hashed code from another ChunkSlots into this one * */ merge( other : ChunksSlots ){ for( var slot of other.slots ){ this.getSlot(slot.key).merge( slot ); } } };
59f72917e52f2b1bd918a31656aaf36f2a097a32
TypeScript
joaquimnet/imager
/src/util/hasValidAttachments.ts
2.609375
3
import { Message } from "discord.js"; import { isValidSharpInput } from "./isValidSharpInput"; export function hasValidAttachments(msg: Message): boolean { if (msg.attachments.size < 1) { return false; } for (const attachment of msg.attachments.values()) { if (isValidSharpInput(attachment.filename)) { return true; } } return false; }
c4905e08657db5ebd7a5b5578750761d316e6fb1
TypeScript
kng83/compound
/src/functional_programming/added_in_12_2019/either.ts
3.53125
4
import {inspect} from 'util'; namespace Either_1 { class Either<T> { protected $value:T; static of<T>(x:T) { return new Right<T>(x); } constructor(x:T) { this.$value = x; } } class Left<T> extends Either<T> { map(fn: () => T) { return this; } inspection() { return `Left(${inspect(this.$value)})`; } } class Right<T> extends Either<T> { map(fn: (value: T) => T) { return Either.of(fn(this.$value)); } inspection() { return `Right(${inspect(this.$value)})`; } } const left = (x:any) => new Left(x); let some = Either.of('rain').map(str => `b${str}`); console.log(some); }
d316fe5e872c272b51579df3f8fdd7f81ef4d03d
TypeScript
iconify/iconify
/packages/utils/tests/emoji-cleanup-test.ts
3.125
3
import { convertEmojiSequenceToUTF32 } from '../lib/emoji/convert'; import { getEmojiSequenceFromString, joinEmojiSequences, getUnqualifiedEmojiSequence, splitEmojiSequences, } from '../lib/emoji/cleanup'; describe('Testing formatting emoji cleanup', () => { it('UTF-32 sequence', () => { // Convert from string const sequence = getEmojiSequenceFromString( '1F441 FE0F 200D 1F5E8 FE0F ' ); expect(sequence).toEqual([0x1f441, 0xfe0f, 0x200d, 0x1f5e8, 0xfe0f]); // Various representations of the same sequence expect( getEmojiSequenceFromString('1f441-fe0f-200d-1f5e8-fe0f') ).toEqual(sequence); expect( convertEmojiSequenceToUTF32( getEmojiSequenceFromString( '\\uD83D\\uDC41\\uFE0F\\u200D\\uD83D\\uDDE8\\uFE0F' ) ) ).toEqual(sequence); // Split const split = splitEmojiSequences(sequence); expect(split).toEqual([ [0x1f441, 0xfe0f], [0x1f5e8, 0xfe0f], ]); // Join again expect(joinEmojiSequences(split)).toEqual(sequence); // Remove variations expect(getUnqualifiedEmojiSequence(sequence)).toEqual([ 0x1f441, 0x200d, 0x1f5e8, ]); }); it('UTF-32 sequence with tones', () => { // Convert from string const sequence = getEmojiSequenceFromString( '1f9d1-1f3ff-200d-1f91d-200d-1f9d1-1f3ff' ); expect(sequence).toEqual([ 0x1f9d1, 0x1f3ff, 0x200d, 0x1f91d, 0x200d, 0x1f9d1, 0x1f3ff, ]); // Split const split = splitEmojiSequences(sequence); expect(split).toEqual([ [0x1f9d1, 0x1f3ff], [0x1f91d], [0x1f9d1, 0x1f3ff], ]); // Join again expect(joinEmojiSequences(split)).toEqual(sequence); // Remove variations (does nothing for this sequence) expect(getUnqualifiedEmojiSequence(sequence)).toEqual(sequence); }); });
fb62e3aa7c26a21222b43e2326552ea21da737b0
TypeScript
arolson101/ofx4js
/src/domain/data/seclist/CallType.ts
3.015625
3
/** * Call type for debt. * @see "Section 13.8.5.2, OFX Spec" */ export enum CallType { CALL, PUT, PREFUND, MATURITY } export function CallType_fromOfx(ofxVal: string): CallType { if ("CALL" === ofxVal) { return CallType.CALL; } else if ("PUT" === ofxVal) { return CallType.PUT; } else if ("PREFUND" === ofxVal) { return CallType.PREFUND; } else if ("MATURITY" === ofxVal) { return CallType.MATURITY; } else { return null; } }
62d2119ec9c634d26f603d48cf1222b215a946ff
TypeScript
nikita41196/AngularProjectASDM
/src/app/item.service.ts
2.6875
3
import { Injectable } from '@angular/core'; import { Item } from './Item.model'; @Injectable() export class ItemService{ arr=[ new Item("pizza",2,230,"large size"), new Item("burger",1,70,"with cheese"), new Item("sandwich",3,150,"without cheese"), new Item("lays",2,40,"salted"), new Item("coke",4,50,"lemon flavour"), ]; getAllItems():Item[] { return this.arr; } addItem(p:Item) { this.arr.push(p); console.log(this.arr); } }
b856a440bda0bb11c568b03284959d8a99797d80
TypeScript
MbugwaSami/react-data-transform
/src/utils/index.ts
2.828125
3
import { useState, useEffect } from "react"; //Generate table data from source data export const GetDataViewProps = <T>( rawData: Array<ViewDataProps<T>>, defaultTableName: string ) => { const [viewTabs, setViewTabs] = useState<Array<Tabs>>([]); const [tableList, setTableList] = useState<Array<TableViewProps<T>>>([]); useEffect(() => { let availableTabs = [] as Tabs[]; let tableList = [] as TableViewProps<T>[]; if (rawData?.length) { rawData.forEach((view, index) => { const tableName = view.name ? view.name : `${defaultTableName}${index + 1}`; const tableColumns = Object.keys(view?.data[0]).map( (key, keyIndex): TableViewColumn => ({ title: view?.columnLabels?.[keyIndex] ? view.columnLabels?.[keyIndex] : `Column${keyIndex + 1}`, dataKey: key, }) ); tableList.push({ tableName, tableData: view.data, colums: tableColumns, }); availableTabs.push({ title: tableName, }); }); } setViewTabs(availableTabs); setTableList(tableList); }, [rawData?.length, defaultTableName]); return { viewTabs, tableList }; };
ce36356134e551a1c2600e4b1cba6fa7c5ba7f7f
TypeScript
Carbulator/carbulator-client
/src/app/pipes/moment.pipe.ts
2.953125
3
import {Pipe, PipeTransform} from '@angular/core'; import * as moment from 'moment'; /** * Formats a moment with the given formatting string. */ @Pipe({ name: 'moment' }) export class MomentPipe implements PipeTransform { /** * Transforms the input value by formatting the moment DateTime with the given formatting string. * @param value Date to format. * @param formattingString Formatting string. * @return Formatted moment. */ transform(value: moment.Moment, formattingString: string): string { if (value) { return value.format(formattingString); } else { return ''; } } }
048a92f771fc9fe2f1cc8f8053ecaab2d4356649
TypeScript
valmassoi/bitpay-card
/src/_services/auth/user.service.ts
2.59375
3
//https://medium.com/@blacksonic86/angular-2-authentication-revisited-611bf7373bf9#.hpdlvsu4i //https://stackoverflow.com/questions/34376854/delegation-eventemitter-or-observable-in-angular2/35568924#35568924 import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; // import localStorage from 'localStorage'; @Injectable() export class UserService { private loggedIn = false; constructor(private _http: Http) { // this.loggedIn = !!localStorage.getItem('auth_token'); //doesnt work here } login(email, password) { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let localUrl = `http://192.168.1.109:8081` //TODO empty for production let url = localUrl + '/auth/login' return this._http .post( url, JSON.stringify({ email, password }), { headers } ) .map(res => res.json()) .map((res) => { if (res.success) { localStorage.setItem('auth_token', 'sometoken')//TODO res.auth_token); this.loggedIn = true this.setLoginStatus(true) } return res.success; }); } logout() { console.log("logout") localStorage.removeItem('auth_token') this.loggedIn = false this.setLoginStatus(false) } isLoggedIn() { //remove infav of emitter below? if (localStorage.getItem('auth_token')!==null)//TODO, bad - user can set themselves AND doesnt work in private mode this.loggedIn=true return this.loggedIn; } private _isUserLoggedIn = new BehaviorSubject<boolean>(this.isLoggedIn()); setStatus$ = this._isUserLoggedIn.asObservable(); setLoginStatus(isLoggedIn){ this._isUserLoggedIn.next(isLoggedIn); } }
102d775fa20b1f6f14a851a53e1688286ef16aa2
TypeScript
nklincoln/persona-maps
/src/app/common/persona.ts
2.859375
3
import { PersonaAspect } from './persona-aspect'; import { Aspect } from './aspect'; export class Persona { private name: string; private personaAspects: Array<PersonaAspect> = []; // Color map[6]: grey, red, dark-orange, light-orange, yellow, light-green, green static colorMap = ['#A6ACAF', '#FF0000', '#FF9912', '#FFD700', '#FFFF00', '#ADFF2F', '#7CFC00']; constructor(name: string) { this.name = name; } setName(name: string) { this.name = name; } getName(): string { return this.name; } addPersonaAspect(comp: PersonaAspect) { this.personaAspects.push(comp); } addPersonaAspects(components: Array<PersonaAspect>) { components.forEach((component) => { this.addPersonaAspect(component); }) } getPersonaAspects(): PersonaAspect[] { return this.personaAspects; } getPersonaAspect(aspect: Aspect): PersonaAspect { let index = this.personaAspects.findIndex((personaAspect) => personaAspect.getAspect().getName().valueOf() === aspect.getName()); if (index !== -1) { return this.personaAspects[index]; } else { throw new Error('No PersonaAspect containing Aspect with name [' + aspect.getName() + '].'); } } hasPersonaAspect(aspect: Aspect): boolean { return ( this.personaAspects.findIndex((personaAspect) => personaAspect.getAspect().getName().valueOf() === aspect.getName()) !== -1); } removePersonaAspect(aspect: Aspect) { let index = this.personaAspects.findIndex((personaAspect) => personaAspect.getAspect().getName().valueOf() === aspect.getName()); if (index !== -1) { this.personaAspects.splice(index,1); } else { throw new Error('No PersonaAspect containing Aspect with name [' + aspect.getName() + '].'); } } updatePersonaAspectWeighting(aspect: Aspect, weighting){ let index = this.personaAspects.findIndex((personaAspect) => personaAspect.getAspect().getName().valueOf() === aspect.getName() ); if (index !== -1) { this.personaAspects[index].setWeighting(weighting); } else { throw new Error('No PersonaAspect containing Aspect with name [' + aspect.getName() + '].'); } } getScheme() { let domainEntries: any =[]; this.personaAspects.forEach((personaComp) => { domainEntries.push(Persona.colorMap[personaComp.getAspect().getConfidence() + 1]); }) return { domain: domainEntries }; } getData() { let data: any =[]; this.personaAspects.forEach((personaComp) => { data.push({name: personaComp.getAspect().getName(), value: personaComp.getWeighting()}); }) return data; } }
fcd105baf8a55a916a35f813df77367e78522855
TypeScript
naporin0624/firebase-next-test
/src/store/index.ts
2.5625
3
import { useMemo } from "react"; import { configureStore, combineReducers } from "@reduxjs/toolkit"; import { FilteredKeys } from "~/utils/types"; import { isClient } from "~/utils/isClient"; import { currentUserReducer } from "./currentUser"; import { entitiesReducer } from "./entities"; const reducer = combineReducers({ entities: entitiesReducer, currentUser: currentUserReducer, }); const createStore = (preloadedState = {}) => configureStore({ reducer, devTools: process.env.NODE_ENV !== "production", preloadedState, }); type Store = ReturnType<typeof createStore>; let store: Store | undefined; export const initializeStore = (preloadedState?: AppState): Store => { let _store = store ?? createStore(preloadedState); // After navigating to a page with an initial Redux state, merge that state // with the current state in the store, and create a new store if (preloadedState && store) { _store = createStore({ ...store.getState(), ...preloadedState, }); // Reset the current store store = undefined; } // For SSG and SSR always create a new store if (!isClient) return _store; // Create the store once in the client if (!store) store = _store; return _store; }; export const useStore = (initialState: AppState): Store => { const _store = useMemo(() => initializeStore(initialState), [initialState]); return _store; }; export type AppState = ReturnType<Store["getState"]>; export type Dispatch = Store["dispatch"]; type E = ReturnType<typeof entitiesReducer>; export type Keys = Exclude<FilteredKeys<E, undefined>, undefined>; export type Entities = { [K in Keys]?: E[K] }; declare module "react-redux" { // eslint-disable-next-line @typescript-eslint/no-empty-interface interface DefaultRootState extends AppState {} }
6f851ecc4fa2bba081d6d5ea48b36bf2d6383dce
TypeScript
baozihuihui/Algorithm
/leetCode/239_sliding-window-maximum.ts
3.515625
4
function maxSlidingWindow(nums: number[], k: number): number[] { let result = []; const length = nums.length; let qenue = []; let left = 0, right = 0; if (length < 2) return nums; const peek = (arr: number[]) => arr.length; let qenueLength = null; for (let i = 0; i < length; i++) { qenueLength = peek(qenue); // 排序双向列表 while (qenueLength !== -1 && nums[i] > nums[qenue[qenueLength - 1]]) { qenue.pop(); qenueLength -= 1; } qenue.push(i); // 成为窗口时 if (right - left + 1 === k) { result.push(nums[qenue[0]]); if (left === qenue[0]) { qenue.shift(); } left += 1; } right += 1; } return result; } let arr = [1, 3, -1, -3, 5, 3, 6, 7]; let width = 3; const result = maxSlidingWindow(arr, width); console.log(result);
b870465bc3d8eb40afbd15c3ab11eea0ba95fb46
TypeScript
SauceCode84/rlds-account-backend
/statement/request-mapping.decorators.ts
2.96875
3
import { METHOD_METADATA, PATH_METADATA } from "./constants"; interface RequestMappingMetadata { [key: string]: string; path?: string; method?: string; } const defaultRequestMappingMetadata: RequestMappingMetadata = { [PATH_METADATA]: "/", [METHOD_METADATA]: "GET" } const RequestMapping = (metadata: RequestMappingMetadata = defaultRequestMappingMetadata): MethodDecorator => { const path = metadata[PATH_METADATA] || "/"; const requestMethod = metadata[METHOD_METADATA] || "GET"; return (target, key, descriptor: PropertyDescriptor) => { Reflect.defineMetadata(PATH_METADATA, path, descriptor.value); Reflect.defineMetadata(METHOD_METADATA, requestMethod, descriptor.value); return descriptor; }; }; const createMappingDecorator = (method: string) => (path?: string): MethodDecorator => { return RequestMapping({ [PATH_METADATA]: path, [METHOD_METADATA]: method }); }; export const Get = createMappingDecorator("GET"); export const Post = createMappingDecorator("POST"); export const Put = createMappingDecorator("PUT");
92dda05ade116ead63ee2250eb18ea02f155bd66
TypeScript
PythSomeone/charades_frontend
/charades-frontend/src/app/_models/player.ts
2.765625
3
export class Player { game_id: string; id: string; name: string; points: number; constructor(name: string, points: number) { this.name = name; this.points = points; } }
25a47d11aca633d8756389de34cf48c43339f675
TypeScript
shilpa10kumar9/medtimeline
/medtimeline/src/app/fhir-data-classes/observation-set.ts
2.875
3
// Copyright 2018 Verily Life Sciences Inc. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import {FhirResourceSet} from '../fhir-resource-set'; import {fixUnitAbbreviations} from '../unit_utils'; import {AnnotatedObservation} from './annotated-observation'; /** * A set of observations that belong together as part of the same series. */ export class ObservationSet extends FhirResourceSet<AnnotatedObservation> { /** * The normal range for this set of observations. Left unset if the normal * range is different across the observations. */ readonly normalRange: [number, number]; /** * The units for this set of observations. Left unset if the normal * range is different across the observations. */ readonly unit: string; /** * Whether or not all Observations belonging to this ObservationSet contain * all qualitative results rather than numerical values. */ readonly allQualitative: boolean = false; /** * Constructor for ObservationSet. * @param observationList The list of observations belonging together. * @throws Error if the observations have different labels, as this indicates * that they are data points from different series, or if there is not * a label. */ constructor(observationList: AnnotatedObservation[]) { super(observationList); let firstNormalRange; let firstUnit; if (observationList.length > 0) { firstNormalRange = observationList[0].observation.normalRange; firstUnit = observationList[0].observation.unit; } // Ensure that the labels of the data are all the same. Also ensure that // we only set a normal range if all the observations have a matching // normal range. let differentNormalRanges = false; let differentUnits = false; for (const obs of observationList) { // Some observations may not have a normal range. if (obs.observation.normalRange && (obs.observation.normalRange[0] !== firstNormalRange[0] || obs.observation.normalRange[1] !== firstNormalRange[1])) { differentNormalRanges = true; } // Some observations may not have a normal range. if (obs.observation.unit && obs.observation.unit !== firstUnit) { differentUnits = true; } } if (!differentNormalRanges) { this.normalRange = firstNormalRange; } if (!differentUnits && firstUnit) { this.unit = fixUnitAbbreviations(firstUnit); } this.allQualitative = observationList.every( obs => (obs.observation.result !== null && !obs.observation.value)); } }
a8535ce217b3be72eb7886e98fac1289a07c158f
TypeScript
danieljameschadwick/ecommerce
/src/util/state/BasketTransform.ts
2.640625
3
import { createTransform } from "redux-persist"; import { Basket } from "./Basket"; import { LocalBasket } from "./LocalBasket"; interface BasketState { basket: Basket; } const BasketTransform = createTransform( // transform state on its way to being serialized and persisted. (inboundState: BasketState, key) => { const basket = inboundState?.basket; if (basket === undefined) { return { ...inboundState }; } const serializedProduct = []; for (const keyMap in basket.products) { const productMap = basket.products[keyMap] for (const key in productMap) { const product = productMap[key]; serializedProduct.push(product); } } return new LocalBasket(serializedProduct, basket.delivery); }, // transform state being rehydrated (outboundState, key) => { return { ...outboundState }; }, ); export default BasketTransform;
59b6ad8026cbf35bf63b5f0e92822683a5da6d74
TypeScript
animenotifier/notify.moe
/scripts/NotificationManager.ts
2.796875
3
import Diff from "./Diff" export default class NotificationManager { unseen: number icon: HTMLElement counter: HTMLElement constructor(icon: HTMLElement, counter: HTMLElement) { this.icon = icon this.counter = counter } async update() { const response = await fetch("/api/count/notifications/unseen", { credentials: "same-origin" }) const body = await response.text() this.setCounter(parseInt(body, 10)) } setCounter(unseen: number) { this.unseen = unseen if(isNaN(this.unseen)) { this.unseen = 0 } if(this.unseen > 99) { this.unseen = 99 } this.render() } render() { Diff.mutations.queue(() => { this.counter.textContent = this.unseen.toString() if(this.unseen === 0) { this.counter.classList.add("hidden") this.icon.classList.remove("hidden") } else { this.icon.classList.add("hidden") this.counter.classList.remove("hidden") } }) } }
7e8bd82a4ca8dd497b35ef0472409504ddc1c74f
TypeScript
thanhcongptit/typescript
/lesson9.ts
2.8125
3
var employee = { id:1, greet : function() { setTimeout(()=> console.log(this.id), 1000); } } console.log(employee.greet());
8bc974e9d66420b51d9974f84a3ed67e7b88688b
TypeScript
chdh/virtual-grid-layout
/src/GridResize.ts
2.8125
3
// Row/column resize logic for grids. import {LayoutController} from "./GridLayout"; interface Point {x: number; y: number; } interface Boundary { // represents a row or column boundary that can be dragged ndx: number; // absolute row or column boundary index orientation: boolean; } // false=horizontal, true=vertical export interface ControllerParms { layoutController: LayoutController; // the layout controller of the grid rowSizingEnabled: boolean; // true to enable row sizing colSizingEnabled: boolean; // true to enable column sizing rowSizingTopWidth: number; // horizontal resize handle width above row boundary rowSizingBottomWidth: number; // horizontal resize handle width below row boundary colSizingLeftWidth: number; // vertical resize handle width left of column boundary colSizingRightWidth: number; // vertical resize handle width right of column boundary rowSizingMaxCols?: number; // maximum active columns for row sizing colSizingMaxRows?: number; } // maximum active rows for column sizing export class ResizeController extends EventTarget { private controllerParms: ControllerParms; private layoutController: LayoutController; private viewportElement: HTMLElement; private isDisposed: boolean = false; private dragging: boolean = false; // true while dragging private dragPointerId?: number; // ID of captured pointer, `undefined` = no capture private dragNdx: number; // row or column index private dragOrientation: boolean; // false=horizontal, true=vertical private dragStartSize: number; // row height or column width at start private dragStartPos: number; private resizeHandleElement?: HTMLElement; private resizeHandleBoundary?: Boundary; // undefined = resize handle element is not visible private resizeHandlePositionValid: boolean = false; constructor (cp: ControllerParms) { super(); this.controllerParms = cp; this.layoutController = cp.layoutController; this.viewportElement = cp.layoutController.viewportElement; this.viewportElement.addEventListener("pointermove", this.viewport_pointerMoveEventListener); this.viewportElement.addEventListener("pointerup", this.viewport_pointerUpEventListener); this.layoutController.addEventListener("render", this.layoutController_renderEventListener); } public dispose() { if (this.isDisposed) { return; } this.isDisposed = true; this.viewportElement.removeEventListener("pointermove", this.viewport_pointerMoveEventListener); this.viewportElement.removeEventListener("pointerup", this.viewport_pointerUpEventListener); this.layoutController.removeEventListener("render", this.layoutController_renderEventListener); if (this.resizeHandleElement) { this.resizeHandleElement.removeEventListener("pointerdown", this.resizeHandle_pointerDownEventListener); this.resizeHandleElement.removeEventListener("pointermove", this.resizeHandle_pointerMoveEventListener); if (this.dragPointerId != undefined) { this.resizeHandleElement.releasePointerCapture(this.dragPointerId); } this.viewportElement.removeChild(this.resizeHandleElement); this.resizeHandleElement = undefined; }} private layoutController_renderEventListener = () => { if (this.dragging && this.resizeHandleBoundary) { this.resizeHandlePositionValid = false; this.adjustResizeHandleElement(this.resizeHandleBoundary); }}; private viewport_pointerMoveEventListener = (event: PointerEvent) => { if (this.isDisposed || !this.layoutController.renderedState) { return; } if (!event.isPrimary || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.buttons) { return; } if (this.dragging) { return; } const point = this.getRelativeCoordinates(event); const boundary = this.findBoundary2D(point); this.adjustResizeHandleElement(boundary); if (boundary) { event.preventDefault(); }}; private resizeHandle_pointerMoveEventListener = (event: PointerEvent) => { if (this.isDisposed || !this.layoutController.renderedState) { return; } if (!event.isPrimary || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { return; } if (!this.dragging) { return; } this.performDragging(event); event.preventDefault(); }; private resizeHandle_pointerDownEventListener = (event: PointerEvent) => { if (this.isDisposed || !this.layoutController.renderedState) { return; } if (!event.isPrimary || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.button != 0) { return; } if (!this.resizeHandleBoundary || !this.resizeHandleElement || this.dragging) { return; } this.startDragging(event); event.preventDefault(); }; private viewport_pointerUpEventListener = (event: PointerEvent) => { if (this.isDisposed) { return; } if (this.dragging) { this.stopDragging(); event.preventDefault(); }}; private startDragging (event: PointerEvent) { const rs = this.layoutController.renderedState!; this.dragPointerId = event.pointerId; this.resizeHandleElement!.setPointerCapture(this.dragPointerId); this.dragNdx = this.resizeHandleBoundary!.ndx - 1; this.dragOrientation = this.resizeHandleBoundary!.orientation; const vPos = rs.viewportPosition; const relNdx = this.dragNdx - (this.dragOrientation ? vPos.rowNdx : vPos.colNdx); const visibleElements = this.dragOrientation ? rs.visibleRows : rs.visibleCols; if (relNdx < 0 || relNdx >= visibleElements) { console.log("`relNdx` out of range when starting to drag. This should not happen."); return; } this.dragStartSize = this.dragOrientation ? rs.visibleRowHeights[relNdx] : rs.visibleColWidths[relNdx]; this.dragStartPos = this.dragOrientation ? event.screenY : event.screenX; this.dragging = true; } private stopDragging() { this.resizeHandleElement!.releasePointerCapture(this.dragPointerId!); this.dragPointerId = undefined; this.dragging = false; } private performDragging (event: PointerEvent) { const pos = this.dragOrientation ? event.screenY : event.screenX; const delta = pos - this.dragStartPos; const size = Math.max(0, this.dragStartSize + delta); const resizeEventDetail = {orientation: this.dragOrientation, ndx: this.dragNdx, size}; this.dispatchEvent(new CustomEvent("element-resize", {detail: resizeEventDetail})); } private getRelativeCoordinates (event: PointerEvent) : Point { const element = this.viewportElement; const rect = element.getBoundingClientRect(); const x = event.clientX - rect.left - element.clientLeft; const y = event.clientY - rect.top - element.clientTop; return {x, y}; } // Find row/column boundary associated with a coordinate point. private findBoundary2D (point: Point) : Boundary | undefined { const cp = this.controllerParms; const rs = this.layoutController.renderedState!; if (cp.colSizingEnabled) { const ndx = this.findBoundary1D(point.x, rs.colXPositions, rs.viewportPosition.colNdx, cp.colSizingLeftWidth, cp.colSizingRightWidth); if (ndx != undefined && this.isVerticalPositionActiveForHorizontalSizing(point.y)) { return {ndx, orientation: false}; }} if (cp.rowSizingEnabled) { const ndx = this.findBoundary1D(point.y, rs.rowYPositions, rs.viewportPosition.rowNdx, cp.rowSizingTopWidth, cp.rowSizingBottomWidth); if (ndx != undefined && this.isHorizontalPositionActiveForVerticalSizing(point.x)) { return {ndx, orientation: true}; }} return undefined; } private findBoundary1D (position: number, positions: Int16Array, startNdx: number, width1: number, width2: number) : (number | undefined) { const relNdx = scanPos(positions, position); if (relNdx == undefined) { return; } const absNdx = startNdx + relNdx; const offset2 = position - positions[relNdx]; // offset right or below of boundary if (offset2 < width2 && relNdx > 0 && absNdx > 0) { return absNdx; } if (relNdx < positions.length - 1) { const offset1 = positions[relNdx + 1] - position; // offset left or above boundary if (offset1 < width1) { return absNdx + 1; }} return undefined; } private isVerticalPositionActiveForHorizontalSizing (y: number) : boolean { const cp = this.controllerParms; const rs = this.layoutController.renderedState!; const maxRowNdx = (cp.colSizingMaxRows != undefined) ? Math.min(cp.colSizingMaxRows, rs.visibleRows) : rs.visibleRows; const maxY = rs.rowYPositions[maxRowNdx]; return y < maxY && !this.inMacroCell(y); } private isHorizontalPositionActiveForVerticalSizing (x: number) : boolean { const cp = this.controllerParms; const rs = this.layoutController.renderedState!; const maxColNdx = (cp.rowSizingMaxCols != undefined) ? Math.min(cp.rowSizingMaxCols, rs.visibleCols) : rs.visibleCols; const maxX = rs.colXPositions[maxColNdx]; return x < maxX; } // Returns true if the specified y coordinate lies within a macro cell. private inMacroCell (y: number) : boolean { const rs = this.layoutController.renderedState!; if (!rs.visibleMacroCellHeights) { return false; } const relRowNdx = scanPos(rs.rowYPositions, y); if (relRowNdx == undefined || relRowNdx >= rs.visibleRows) { return false; } const offset = y - rs.rowYPositions[relRowNdx]; const macroCellOffset = rs.visibleRowHeights[relRowNdx] - rs.visibleMacroCellHeights[relRowNdx]; return offset >= macroCellOffset; } // When `boundary` is `undefined`, the resize handle element is hidden. private adjustResizeHandleElement (boundary: Boundary | undefined) { const cp = this.controllerParms; const rs = this.layoutController.renderedState!; if (!boundary) { // hide the resize handle element if (!this.resizeHandleBoundary) { return; } if (this.resizeHandleElement) { this.resizeHandleElement.style.display = "none"; } this.resizeHandleBoundary = undefined; return; } if (this.resizeHandlePositionValid && this.resizeHandleBoundary && this.resizeHandleBoundary.ndx == boundary.ndx && this.resizeHandleBoundary.orientation == boundary.orientation) { return; } if (!this.resizeHandleElement) { this.resizeHandleElement = document.createElement("div"); this.resizeHandleElement.className = "virtual-grid-layout-gridResizeHandle"; // (only for debugging) this.resizeHandleElement.style.position = "absolute"; this.resizeHandleElement.style.zIndex = "99"; this.resizeHandleElement.addEventListener("pointerdown", this.resizeHandle_pointerDownEventListener); this.resizeHandleElement.addEventListener("pointermove", this.resizeHandle_pointerMoveEventListener); this.viewportElement.appendChild(this.resizeHandleElement); } const style = this.resizeHandleElement.style; style.display = ""; if (boundary.orientation) { const y = rs.rowYPositions[boundary.ndx - rs.viewportPosition.rowNdx]; style.top = (y - cp.rowSizingTopWidth) + "px"; style.height = (cp.rowSizingTopWidth + cp.rowSizingBottomWidth) + "px"; style.left = "0"; style.width = rs.viewportWidth + "px"; style.cursor = "row-resize"; } else { const x = rs.colXPositions[boundary.ndx - rs.viewportPosition.colNdx]; style.left = (x - cp.colSizingLeftWidth) + "px"; style.width = (cp.colSizingLeftWidth + cp.colSizingRightWidth) + "px"; style.top = "0"; style.height = rs.viewportHeight + "px"; style.cursor = "col-resize"; } this.resizeHandleBoundary = boundary; this.resizeHandlePositionValid = true; } } function scanPos (positions: Int16Array, pos: number) : number | undefined { const n = positions.length; for (let i = 0; i < n; i++) { if (pos >= positions[i] && (i + 1 >= n || pos < positions[i + 1])) { return i; }} return undefined; }
401f61986e944dfecd9c461f540df8b44eff67d2
TypeScript
cancerberoSgx/suitecommerce-types
/jasmine-puppeteer-results/src/wait.ts
2.765625
3
// import { Page, EvaluateFn } from 'puppeteer'; // // TODO: move to misc-utils-of-mine-generic // export async function waitForBrowser(predicate: () => boolean, ms = 300, timeout = 2000): Promise<boolean> { // return new Promise(resolve => { // const t = setInterval(() => { // if (predicate()) { // clearInterval(t) // resolve(true) // } // }, ms) // setTimeout(() => { // clearInterval(t) // resolve(false) // }, timeout); // }) // } // export async function waitForElementBrowser(selector: string, ms = 300, timeout = 2000): Promise<boolean> { // return waitForBrowser(() => !!document.querySelector(selector), ms, timeout) // } // export async function waitForGlobalBrowser(g: string, ms = 300, timeout = 2000): Promise<boolean> { // return waitForBrowser(() => typeof window[g] !== 'undefined', ms, timeout) // } // export async function waitFor(page: Page, predicate: () => boolean, ms = 300, timeout = 2000): Promise<boolean> { // return await page.evaluate(waitForBrowser, predicate, ms, timeout) // } // export async function waitForGlobal(page: Page, globalName = 'jQuery', ms = 300, timeout = 2000): Promise<boolean> { // function predicate (g) { // return typeof window[g] !== 'undefined' // } // const s = ` // (function(){ // ${waitForBrowser.toString()}; // ${predicate.toString()}; // return waitForBrowser.apply(this, arguments) // }) // ` // console.log(s); // page.waitFor // const f = eval(s) as EvaluateFn // // return Promise.resolve(true) // return await page.evaluate(f, globalName, ms, timeout) // }
e094a49f696caf98ef7feca63ffa1ffafeb99a3c
TypeScript
wadackel/toy-tree
/src/types.ts
2.75
3
/** * Utilities */ export type TODO_any = any; /** * Node */ interface BaseNode<T> { type: T; name: string; } export interface FileNode extends BaseNode<'file'> {} export interface DirectoryNode extends BaseNode<'directory'> { children: TreeNode[]; } export interface SymlinkNode extends BaseNode<'symlink'> { link: string; } export type TreeNode = FileNode | DirectoryNode | SymlinkNode; /** * Options */ export interface Options { level: number; }
28b668dd9481215be44928e569e9e66fd9a33d47
TypeScript
J-HOVELAQUE/rando-server
/src/place/repository/buildPlaceRepository.ts
3.109375
3
import PlaceModel from "../model/PlaceModel"; import HikeModel from "../../hike/model/HikeModel"; import Place from "../../interfaces/place"; import { OutcomeSuccess, OutcomeFailure } from "../../interfaces/outcomes"; type PlaceRepositoryError = | "DATABASE_ERROR" | "UNIQUE_CONSTRAIN_ERROR" | "ID_NOT_FOUND" | "CAST_ERROR" | "RELATIONAL_ERROR"; interface PlaceRepositoryOutcomeFailure extends OutcomeFailure { errorCode: PlaceRepositoryError; } type ResultRepoMethod<data> = | OutcomeSuccess<data> | PlaceRepositoryOutcomeFailure; interface PlaceDataToUpdate { name?: string; mountainLocation?: string; altitudeInMeters?: number; city?: string; picture?: string; } interface PlaceDataToCreate { name: string; mountainLocation: string; altitudeInMeters: number; picture?: string; city?: string; } interface Coordinates { lat: number; long: number; } interface PlaceRepository { create: ( placeToCreate: PlaceDataToCreate ) => Promise<ResultRepoMethod<Place>>; findAll: () => Promise<ResultRepoMethod<Place[]>>; findOne: (id: string) => Promise<ResultRepoMethod<Place>>; update: ( placeId: string, placeData: PlaceDataToUpdate ) => Promise<ResultRepoMethod<any>>; delete: (placeId: string) => Promise<ResultRepoMethod<any>>; setLocation: ( placeId: string, coordinates: Coordinates ) => Promise<ResultRepoMethod<any>>; } export default function buildPlaceRepository(): PlaceRepository { return { create: async (placeToCreate: PlaceDataToCreate) => { try { const newPlace = new PlaceModel(placeToCreate); const dbAnswer = await newPlace.save(); return { outcome: "SUCCESS", data: dbAnswer, }; } catch (error: any) { if (error.code && error.code === 11000) { return { outcome: "FAILURE", errorCode: "UNIQUE_CONSTRAIN_ERROR", detail: error, }; } return { outcome: "FAILURE", errorCode: "DATABASE_ERROR", detail: error, }; } }, findAll: async () => { try { const placesInDatabase = await PlaceModel.find(); return { outcome: "SUCCESS", data: placesInDatabase, }; } catch (error: any) { return { outcome: "FAILURE", errorCode: "DATABASE_ERROR", detail: error, }; } }, findOne: async (id: string) => { try { const searchedPlace = await PlaceModel.findById(id); if (searchedPlace === null) { return { outcome: "FAILURE", errorCode: "ID_NOT_FOUND", }; } return { outcome: "SUCCESS", data: searchedPlace, }; } catch (error: any) { return { outcome: "FAILURE", errorCode: "DATABASE_ERROR", detail: error, }; } }, update: async (placeId: string, placeData: PlaceDataToUpdate) => { try { const result = await PlaceModel.updateOne({ _id: placeId }, placeData); return { outcome: "SUCCESS", data: result, }; } catch (error: any) { if (error.name === "CastError") { return { outcome: "FAILURE", errorCode: "CAST_ERROR", detail: error, }; } return { outcome: "FAILURE", errorCode: "DATABASE_ERROR", detail: error, }; } }, delete: async (placeId: string) => { const hikeWithThisPlace = await HikeModel.find({ place: placeId }); if (hikeWithThisPlace.length >= 1) { return { outcome: "FAILURE", errorCode: "RELATIONAL_ERROR", detail: "There is one or more hike in this place", }; } try { const deletionResult = await PlaceModel.deleteOne({ _id: placeId }); return { outcome: "SUCCESS", data: deletionResult, }; } catch (error: any) { return { outcome: "FAILURE", errorCode: "DATABASE_ERROR", detail: error, }; } }, setLocation: async (placeId: string, coordinates: Coordinates) => { try { const result = await PlaceModel.updateOne( { _id: placeId }, { location: { type: "Point", coordinates: [coordinates.lat, coordinates.long], }, } ); return { outcome: "SUCCESS", data: result, }; } catch (error: any) { if (error.name === "CastError") { return { outcome: "FAILURE", errorCode: "CAST_ERROR", detail: error, }; } return { outcome: "FAILURE", errorCode: "DATABASE_ERROR", detail: error, }; } }, }; }
ff096f1d1822545bb59ec6e58441909d74886940
TypeScript
calumleask/phaser-framework
/src/core/EventEmitter.ts
3.25
3
type Data = { [key: string]: unknown; }; type EventCallback = ( event: Data & { type: string; target: unknown; }, ) => void; type EventsObject = { [type: string]: EventCallback[] }; export class EventEmitter { private _events: EventsObject; constructor() { this._events = {}; } on(type: string, callback: EventCallback): void { let listeners: EventCallback[] = this._events[type]; if (!listeners) { listeners = []; this._events[type] = listeners; } for (let i = 0; i < listeners.length; ++i) { if (listeners[i] === callback) return; } listeners.push(callback); } off(type: string, callback: EventCallback): void { const listeners: EventCallback[] = this._events[type]; if (!listeners) return; for (let i: number = listeners.length - 1; i >= 0; --i) { if (listeners[i] === callback) { listeners.splice(i, 1); return; } } } fire(type: string, data: Data): void { const listeners: EventCallback[] = this._events[type]; if (!listeners) return; listeners.forEach(callback => { callback({ ...data, type: type, target: this, }); }); } }
a2e6472d0114122b23f197071a23fe423e8b40a0
TypeScript
cosmos-ignite2018-demo/demo
/web_app/static/vendors/bower_components/jqTree/src/save_state_handler.ts
2.734375
3
import { isInt } from "./util"; import { ITreeWidget } from "./itree_widget"; import { Node, NodeId } from "./node"; export default class SaveStateHandler { private tree_widget: ITreeWidget; private _supportsLocalStorage: boolean | null; constructor(tree_widget: ITreeWidget) { this.tree_widget = tree_widget; } public saveState() { const state = JSON.stringify(this.getState()); if (this.tree_widget.options.onSetStateFromStorage) { this.tree_widget.options.onSetStateFromStorage(state); } else if (this.supportsLocalStorage()) { localStorage.setItem(this.getKeyName(), state); } } public getStateFromStorage() { const json_data = this._loadFromStorage(); if (json_data) { return this._parseState(json_data); } else { return null; } } public getState(): any { const getOpenNodeIds = () => { const open_nodes: NodeId[] = []; this.tree_widget.tree.iterate((node: Node) => { if (node.is_open && node.id && node.hasChildren()) { open_nodes.push(node.id); } return true; }); return open_nodes; }; const getSelectedNodeIds = () => this.tree_widget.getSelectedNodes().map((n: Node) => n.id); return { open_nodes: getOpenNodeIds(), selected_node: getSelectedNodeIds() }; } /* Set initial state Don't handle nodes that are loaded on demand result: must load on demand */ public setInitialState(state: any): boolean { if (!state) { return false; } else { let must_load_on_demand = false; if (state.open_nodes) { must_load_on_demand = this._openInitialNodes(state.open_nodes); } if (state.selected_node) { this._resetSelection(); this._selectInitialNodes(state.selected_node); } return must_load_on_demand; } } public setInitialStateOnDemand(state: any, cb_finished: () => void) { if (state) { this._setInitialStateOnDemand( state.open_nodes, state.selected_node, cb_finished ); } else { cb_finished(); } } public getNodeIdToBeSelected() { const state = this.getStateFromStorage(); if (state && state.selected_node) { return state.selected_node[0]; } else { return null; } } private _parseState(json_data: any) { const state = jQuery.parseJSON(json_data); // Check if selected_node is an int (instead of an array) if (state && state.selected_node && isInt(state.selected_node)) { // Convert to array state.selected_node = [state.selected_node]; } return state; } private _loadFromStorage() { if (this.tree_widget.options.onGetStateFromStorage) { return this.tree_widget.options.onGetStateFromStorage(); } else if (this.supportsLocalStorage()) { return localStorage.getItem(this.getKeyName()); } } private _openInitialNodes(node_ids: any[]): boolean { let must_load_on_demand = false; for (const node_id of node_ids) { const node = this.tree_widget.getNodeById(node_id); if (node) { if (!node.load_on_demand) { node.is_open = true; } else { must_load_on_demand = true; } } } return must_load_on_demand; } private _selectInitialNodes(node_ids: NodeId[]): boolean { let select_count = 0; for (const node_id of node_ids) { const node = this.tree_widget.getNodeById(node_id); if (node) { select_count += 1; if (this.tree_widget.select_node_handler) { this.tree_widget.select_node_handler.addToSelection(node); } } } return select_count !== 0; } private _resetSelection() { const select_node_handler = this.tree_widget.select_node_handler; if (select_node_handler) { const selected_nodes = select_node_handler.getSelectedNodes(); selected_nodes.forEach(node => { select_node_handler.removeFromSelection(node); }); } } private _setInitialStateOnDemand( node_ids_param: NodeId[], selected_nodes: NodeId[], cb_finished: () => void ) { let loading_count = 0; let node_ids = node_ids_param; const openNodes = () => { const new_nodes_ids = []; for (const node_id of node_ids) { const node = this.tree_widget.getNodeById(node_id); if (!node) { new_nodes_ids.push(node_id); } else { if (!node.is_loading) { if (node.load_on_demand) { loadAndOpenNode(node); } else { this.tree_widget._openNode(node, false, null); } } } } node_ids = new_nodes_ids; if (this._selectInitialNodes(selected_nodes)) { this.tree_widget._refreshElements(null); } if (loading_count === 0) { cb_finished(); } }; const loadAndOpenNode = (node: Node) => { loading_count += 1; this.tree_widget._openNode(node, false, () => { loading_count -= 1; openNodes(); }); }; openNodes(); } private getKeyName(): string { if (typeof this.tree_widget.options.saveState === "string") { return this.tree_widget.options.saveState; } else { return "tree"; } } private supportsLocalStorage(): boolean { const testSupport = () => { // Is local storage supported? if (localStorage == null) { return false; } else { // Check if it's possible to store an item. Safari does not allow this in private browsing mode. try { const key = "_storage_test"; sessionStorage.setItem(key, "value"); sessionStorage.removeItem(key); } catch (error) { return false; } return true; } }; if (this._supportsLocalStorage == null) { this._supportsLocalStorage = testSupport(); } return this._supportsLocalStorage; } }
d8f7bc15a9d9265e95e6d7587dfd68e2aa31fe30
TypeScript
carlocorradini/happypuppy-server
/src/util/OTPUtil.ts
3.21875
3
export default class OTPUtil { public static readonly DIGITS = '0123456789'; public static readonly ALPHABET: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; public static digits(length: number): Promise<string> { let otp = ''; for (let i = 0; i < length; i += 1) { otp += this.DIGITS.charAt(Math.floor(Math.random() * this.DIGITS.length)); } return Promise.resolve(otp); } public static alphanumerical(length: number): Promise<string> { let otp = ''; for (let i = 0; i < length; i += 1) { otp += this.ALPHABET.charAt(Math.floor(Math.random() * this.ALPHABET.length)); } return Promise.resolve(otp); } }
43ccf4b4ab5d5234e1c47285880253c1751bf4eb
TypeScript
WilliamJenner/BournemouthBindicator
/ClientApp/src/ts/actions/http.ts
2.875
3
// https://stackoverflow.com/a/49471725 export const api = <T>(url: string): Promise<T> => { return fetch(url) .then((response) => { if (!response.ok) { throw new Error(response.statusText); } return response.json(); }) .catch((error: Error) => { throw error; /* <-- rethrow the error so consumer can still catch it */ }); };
098a84030e4717601b5e70378c533d4fc3464a71
TypeScript
das-praktische-schreinerlein/mytourbook
/src/frontend/app/shared-tdoc/services/form.utils.ts
2.78125
3
// TODO move to commons export class FormUtils { public static getNumberFormValue(values: {}, formKey: string): number { if (!values[formKey]) { return undefined; } if (Array.isArray(values[formKey])) { return Number(values[formKey][0]); } else { return Number(values[formKey]); } } public static getStringFormValue(values: {}, formKey: string): string { if (!values[formKey]) { return undefined; } if (Array.isArray(values[formKey])) { return values[formKey][0] + ''; } else { return values[formKey] + ''; } } public static getStringArrayFormValue(values: {}, formKey: string): string[] { if (!values[formKey]) { return undefined; } if (Array.isArray(values[formKey])) { return values[formKey]; } else { return [values[formKey]]; } } }
f28abf4606fd343ea917692fc30ba3f72ccda313
TypeScript
Open-Attestation/token-registry
/test/helpers/impersonate-account.ts
2.828125
3
import { ethers, network } from "hardhat"; import { Signer } from "ethers"; /** * Impersonate an account as signer. * @param address Address of account to be impersonated * @param balance Balance in ethers */ export const impersonateAccount = async ({ address, balance = 100, }: { address: string; balance?: number; }): Promise<Signer> => { await network.provider.request({ method: "hardhat_impersonateAccount", params: [address], }); const hexBalance = ethers.utils.parseEther(String(balance)).toHexString(); await network.provider.send("hardhat_setBalance", [address, ethers.utils.hexStripZeros(hexBalance)]); return ethers.provider.getSigner(address); }; export const stopImpersonatingAccount = async ({ address }: { address: string }) => { await network.provider.request({ method: "hardhat_stopImpersonatingAccount", params: [address], }); };
9bbec4b4059f57b2a1c5240e584ddd52a41e1139
TypeScript
JayJayDee/GBS-Worker
/src/lib/queues/types.ts
2.640625
3
type ConsumerFunction = (payload: any) => Promise<void>; export type Subscribe = ({ topicId, consumer }: { topicId: string, consumer: ConsumerFunction }) => Promise<void>; export type Publish = ({ topicId, payload }: { topicId: string, payload: {[key: string]: any} }) => Promise<void>;
41aa01f7dcb4c995296a0a6e461cabe527661b79
TypeScript
sapir054/mockingbird
/packages/generator/test/e2e/mock-factory.test.ts
2.75
3
import { MockFactory } from '../../src'; import { TestClassesE2E } from './test-classes'; import Dog = TestClassesE2E.Dog; describe('MockFactory e2e Test', () => { when("calling 'many' method with a given class", () => { let result: Dog[]; beforeAll(() => { result = MockFactory<Dog>(Dog).many(3); }); then('return an array with the exact same length', () => { expect(result).toBeInstanceOf(Array); expect(result).toHaveLength(3); }); then('return 3 instances of the given class', () => { expect(result).toMatchSnapshot(); }); }); });
b0b2419bfd1beea7829627428172b7e042a86f15
TypeScript
andreasmwenzel/ts-cards
/src/decks/pinochle.ts
3.3125
3
import { Deck } from '../deck'; import { Card } from '../card'; import { nine, ten, jack, queen, king, ace } from '../ranks'; import { spades, diamonds, clubs, hearts } from '../suits'; import { Suit } from '../suit'; import { Rank } from '../rank'; /** * @class PinochelDeck * @extends Deck */ export class PinochleDeck extends Deck { constructor() { super(generateDeck()); } } const suits = [spades, diamonds, clubs, hearts]; const ranks = [nine, jack, queen, king, ten, ace]; const generateDeck = () => { const cards: Card[] = []; for (const suit of suits) { for (const rank of ranks) { cards.push(new Card(suit, rank, this)); cards.push(new Card(suit, rank, this)); } } return cards; }; export const pinochleRankValues = new Map<Rank, number>(); pinochleRankValues.set(nine, 9); pinochleRankValues.set(jack, 10); pinochleRankValues.set(queen, 11); pinochleRankValues.set(king, 12); pinochleRankValues.set(ten, 13); pinochleRankValues.set(ace, 14); export const pinochleCardCompare = (a: Card, b: Card, leadSuit: Suit | undefined, trump: Suit | undefined): number => { const bRank: number | undefined = pinochleRankValues.get(b.rank); const aRank: number | undefined = pinochleRankValues.get(a.rank); if (a.suit === b.suit) { return (bRank ? bRank : 0) - (aRank ? aRank : 0); } else { if (b.suit === trump) { return 1; } else if (a.suit === trump) { return -1; } else if (b.suit === leadSuit) { return 1; } else { return -1; } } };
8ceb68bcf4a749812f867ac2fc0b6e6df0346dc3
TypeScript
hamada-infocube/romi-dashboard
/src/components/schedule-visualizer/colors.ts
3.15625
3
/** * This can be slow so it should be memoed. * @param name * @param model */ export async function computeRobotColor(name: string, model: string): Promise<string> { const modelHash = new Uint16Array(await _hash(model)); const hue = modelHash[0] % 360; const nameHash = new Uint16Array(await _hash(name)); const satlum = nameHash[0] % 2500; const saturation = 50 + (satlum % 50); const luminance = 25 + satlum / 50; return `hsl(${hue}, ${saturation}%, ${luminance}%)`; } async function _hash(s: string): Promise<ArrayBuffer> { const encoder = new TextEncoder(); const data = encoder.encode(s); return crypto.subtle.digest('SHA-256', data); } export default class ColorManager { async robotColor(name: string, model: string): Promise<string> { const key = this._robotKey(name, model); let color = this._robotColorCache[key]; if (!color) { const modelHash = new Uint16Array(await _hash(model)); const hue = modelHash[0] % 360; const nameHash = new Uint16Array(await _hash(name)); const satlum = nameHash[0] % 2500; const saturation = 50 + (satlum % 50); const luminance = 25 + satlum / 50; color = `hsl(${hue}, ${saturation}%, ${luminance}%)`; this._robotColorCache[key] = color; } return color; } robotColorFromCache(name: string, model: string): string | null { const color = this._robotColorCache[this._robotKey(name, model)]; return color ? color : null; } private _robotColorCache: Record<string, string> = {}; private _robotKey(name: string, model: string) { return `${name}__${model}`; } }
2f2ba92cc13dc1afd11890cf5540be89f2594594
TypeScript
openinsight-project/grafinsight
/packages/grafinsight-data/src/types/geometry.ts
2.984375
3
/** * A coordinate on a two dimensional plane. */ export interface CartesianCoords2D { x: number; y: number; } /** * 2d object dimensions. */ export interface Dimensions2D { width: number; height: number; }
84ebf74eada69de35b128be47e013586bc9f5acc
TypeScript
Marcel2703/ClientWebservice
/src/app/shared/service/sort-date-formatter.service.ts
2.8125
3
import { Injectable } from '@angular/core'; @Injectable() export class SortDateFormatterService { getDateTime(day: string, hour?: string): any { let output; if (day) { output = new Date( +day.split('-')[0], +day.split('-')[1] - 1, +day.split('-')[2] ); if (hour) { output = new Date( +day.split('-')[0], +day.split('-')[1] - 1, +day.split('-')[2], +hour.split(':')[0], +hour.split(':')[1] ); } return output; } else { return ''; } } getTime(date: Date): any { return date.getTime(); } formatDateFR(date: Date): any { const options = { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric' }; if (date.toLocaleTimeString('fr-FR', options) && date.toLocaleTimeString('fr-FR', options).split(' ')[5]) { return date.toLocaleTimeString('fr-FR', options).split(' ').slice(1, 4).join(' ') + ' ' + date.toLocaleTimeString('fr-FR', options).split(' ')[5].split(':').slice(0, 2).join('H'); } else { return date.toLocaleTimeString('fr-FR', options).split(' ').slice(1, 4).join(' ') + ' ' + date.toLocaleTimeString('fr-FR', options).split(' ')[4].split(':').slice(0, 2).join('H'); } } }
280dec878db8ffc6bc96f3bb343637084eea7302
TypeScript
brunogamacatao/nodebackend
/src/rotas/secreto.ts
2.5625
3
import { Router } from "express"; import { AuthUtil } from "../util/auth"; export class Secreto { public rotas(): Router { let router = Router(); router.all('*', AuthUtil.estaAutenticado); router.get('/', (req, res) => { res.send('Retorna todos os registros'); }); router.get('/:id', (req, res) => { res.send(`Retorna o registro com id ${req.params.id}`); }); router.post('/', (req, res) => { res.send('Registro adicionado'); }); router.put('/:id', (req, res) => { res.send(`Altera o registro com id ${req.params.id}`); }); router.delete('/:id', (req, res) => { res.send(`Remove o registro com id ${req.params.id}`); }); return router; } }
e4b42d9e23fe79935cdaf2f1cbc92b8038eb35fc
TypeScript
KYLFYK/miac_backend
/src/patient/interfaces/IPatient.ts
2.578125
3
import { IBaseEntity } from '../../common/interfaces/IBaseEntity'; import {IActivity} from "../../activity/interfaces/IActivity"; export enum sexType { FEMALE = 'female', MALE = 'male' } export enum currentStatusType { NORMAL = 'Нормальное', GOOD = 'Хорошее', SATISFACTORY = 'Удовлитворительное', BAD = 'Плохое', } export interface IPatient extends IBaseEntity { id: number; firstName: string; lastName: string; email: string; phone?: string; weight: number; height: number; snils: string; age: number; sex: sexType; currentStatus: currentStatusType; isVerify: boolean; }
c81affbc988f2ca8e9e3494725587e0bedfccdc9
TypeScript
rope-hmg/lazy_global
/src/test.ts
2.78125
3
import { runTests, assert, assertEq } from "absolute_unit_test"; import { lazy, lazyPromise } from "./index"; runTests( class { "lazy should only evaluate once"() { let evalCount = 0; const lazyString = lazy(() => ((evalCount += 1), "some complicated and expensive thing")); lazyString.value(); lazyString.value(); lazyString.value(); assertEq(evalCount, 1); } "lazy should always evaluate to the same value"() { const lazyString = lazy(() => "some complicated and expensive thing"); assertEq(lazyString.value(), "some complicated and expensive thing"); assertEq(lazyString.value(), "some complicated and expensive thing"); assertEq(lazyString.value(), "some complicated and expensive thing"); } async "lazyPromise should only reevaluate if it failed"() { let evalCount = 0; const lazyString = lazyPromise(async () => { if (evalCount < 2) { evalCount += 1; return Promise.reject("failure"); } return "success"; }); try { await lazyString.value(); } catch {} try { await lazyString.value(); } catch {} try { await lazyString.value(); } catch {} assertEq(evalCount, 2); } async "lazyPromise should evaluate to the correct return value"() { let evalCount = 0; const lazyString = lazyPromise(async () => { if (evalCount < 2) { evalCount += 1; return Promise.reject("failure"); } return "success"; }); try { await lazyString.value(); assert(false, "This code should never be executed"); } catch (error) { assertEq(error, "failure"); } try { await lazyString.value(); assert(false, "This code should never be executed"); } catch (error) { assertEq(error, "failure"); } try { assertEq(await lazyString.value(), "success"); } catch { assert(false, "This code should never be executed"); } } }, );
7c14542a9be912be99653f63b927476bd27daa74
TypeScript
Khoding/obsidian-dataview
/src/data/parse/csv.ts
2.671875
3
import { canonicalizeVarName } from "util/normalize"; import { DataObject } from "../value"; import * as Papa from "papaparse"; import { parseFrontmatter } from "data/parse/markdown"; /** Parse a CSV file into a collection of data rows. */ export function parseCsv(content: string): DataObject[] { let parsed = Papa.parse(content, { header: true, skipEmptyLines: true, comments: "#", dynamicTyping: true, }); let rows = []; for (let parsedRow of parsed.data) { let fields = parseFrontmatter(parsedRow) as DataObject; let result: DataObject = {}; for (let [key, value] of Object.entries(fields)) { result[key] = value; result[canonicalizeVarName(key)] = value; } rows.push(result); } return rows; }
0d93e0934dbc464fe08b4af3931facc5b5b3c501
TypeScript
TatianaFischer/Labephoto-Backend
/src/model/Image.ts
2.90625
3
export interface ImageInputDTO { subtitle: string; file: string; collection: string; } export interface TagsInputDTO { id: string; name: ImageTagsName[]; } export enum ImageTagsName { OLEO = "#ÓLEO", AQUARELA = "#AQUARELA", PASTEL = "#PASTEL", ACRILICA = "#ACRÍLICA", AREIA = "#AREIA", DIGITAL = "#DIGITAL", OCIDENTAL = "#OCIDENTAL", ORIENTAL = "#ORIENTAL", } export class Image { constructor( private id: string, private subtitle: string, private author: string, private file: string, private collection: string ) {} // public getId() { return this.id; } public getSubtitle() { return this.subtitle; } public getAuthor() { return this.author; } public getfile() { return this.file; } public getCollection() { return this.collection; } public static toImageModel(image: any): Image { return new Image( image.id, image.subtitle, image.author, image.file, image.collection ); } }
0a9ab2039adae57c46f3c7197cd4997eae3edd8e
TypeScript
pubkey/event-reduce
/javascript/src/truth-table-generator/data-generator.ts
2.703125
3
import Faker from 'faker'; import { datatype as fakerDatatype } from 'faker'; import type { Human, Procedure } from './types'; import type { ChangeEvent } from '../../src/types'; import { getMinimongoCollection, minimongoFind, applyChangeEvent } from './minimongo-helper'; import { UNKNOWN_VALUE } from './config'; import { randomOfArray } from '../util'; /** * Set a seed to ensure we create deterministic and testable * test data. */ Faker.seed(2345); export function randomHuman(partial?: Partial<Human>): Human { const ret: Human = { _id: Faker.random.alphaNumeric(10), name: Faker.name.firstName().toLowerCase(), gender: fakerDatatype.boolean() ? 'f' : 'm', age: fakerDatatype.number({ min: 1, max: 100 }) }; if (partial) { Object.entries(partial).forEach(([k, v]) => { ret[k] = v; }); } return ret; } export const STATIC_RANDOM_HUMAN: Human = randomHuman(); STATIC_RANDOM_HUMAN._id = 'static_random_human'; export function randomHumans(amount = 0, partial?: Partial<Human>): Human[] { return new Array(amount).fill(0).map(() => randomHuman(partial)); } const keyToChangeFn = { 1: (i: Human) => i.name = Faker.name.firstName().toLowerCase(), 2: (i: Human) => i.gender = fakerDatatype.boolean() ? 'f' : 'm', 3: (i: Human) => i.age = fakerDatatype.number({ min: 1, max: 100 }) }; export function randomChangeHuman(input: Human): Human { const cloned: Human = Object.assign({}, input); const field = fakerDatatype.number({ min: 1, max: 3 }); keyToChangeFn[field](cloned); return cloned; } export function randomChangeEvent( allDocs: Human[], favor: 'INSERT' | 'DELETE' ): ChangeEvent<Human> { const ops = [ 'INSERT', // do many update events 'UPDATE', 'UPDATE', 'UPDATE', 'UPDATE', 'UPDATE', 'DELETE', favor ]; const randomOp = randomOfArray(ops); const operation = allDocs.length === 0 ? 'INSERT' : randomOp; let ret; switch (operation) { case 'INSERT': const newDoc = randomHuman(); ret = { operation, id: newDoc._id, doc: newDoc, previous: null }; break; case 'UPDATE': const oldDoc = Faker.random.arrayElement(allDocs); const changedDoc = randomChangeHuman(oldDoc); ret = { operation, id: oldDoc._id, doc: changedDoc, previous: oldDoc }; break; case 'DELETE': const docToDelete: Human = Faker.random.arrayElement(allDocs); ret = { operation, id: docToDelete._id, doc: null, previous: docToDelete }; break; } // randomly set previous to UNKNOWN if (ret.previous && fakerDatatype.boolean()) { ret.previous = UNKNOWN_VALUE; } return ret; } // ensure that the change-events get generated // before we even need them export const randomEventsPrematureCalculation: { [amount: number]: Procedure; } = {}; export async function getRandomChangeEvents( amount: number = 100 ): Promise<Procedure> { if (randomEventsPrematureCalculation[amount]) { fillRandomEvents(amount); const ret = randomEventsPrematureCalculation[amount]; delete randomEventsPrematureCalculation[amount]; return ret; } else { fillRandomEvents(amount); return _getRandomChangeEvents(amount); } } export function fillRandomEvents(amount: number) { setTimeout(async () => { const newEvents = await _getRandomChangeEvents(amount); randomEventsPrematureCalculation[amount] = newEvents; }, 20); } export async function _getRandomChangeEvents( amount: number = 100 ): Promise<Procedure> { const ret: ChangeEvent<Human>[] = []; const half = Math.ceil(amount / 2); const collection = getMinimongoCollection(); let allDocs: Human[] = []; // in the first half, we do more inserts while (ret.length < half) { const changeEvent = randomChangeEvent(allDocs, 'INSERT'); ret.push(changeEvent); await applyChangeEvent( collection, changeEvent ); allDocs = await minimongoFind(collection, { selector: {}, sort: ['_id'] }); } // in the second half, we do more deletes while (ret.length < amount) { const changeEvent = randomChangeEvent(allDocs, 'DELETE'); ret.push(changeEvent); await applyChangeEvent( collection, changeEvent ); allDocs = await minimongoFind(collection, { selector: {}, sort: ['_id'] }); } return ret; }
cbcc32e6a61ee9cc64698de70f05b7ea0dbc2b20
TypeScript
dsmiller95/StandupTelegramBot
/states/waiting.ts
2.65625
3
import { BotState } from './botState'; import { SetupStandup } from './setupStandup'; export class Waiting extends BotState{ constructor(userID: (number | BotState), bot = null){ super(userID, bot); } public receiveMessage(msg): BotState{ var message = ""; var text = msg.text; var match; if((match = /\/initStandup/.exec(text)) != null){ this.sendResponse("Initializing the standup"); return new SetupStandup(this); } return null; } }
77c8da6ac0c91db0801d2e90cea587accb84d488
TypeScript
StefanSinapov/TelerikAcademy
/09. JavaScript ООП/04. TypeScript Overview/0. Demo/TypeScriptTesting/scripts/interfaces/driver.ts
2.8125
3
 interface Driver extends Person { yearsExperience: number; vehicles: Vehicle[]; addVehicle(vehicle: Vehicle): void; removeVehicle(vehicle: Vehicle): Vehicle; }
c0b4359abe2cc7a3340816f136838d7ce1805e52
TypeScript
gmahechas/tutorial-rxjs
/src/fernando-herrera/08-transformation-operators/switchMap.ts
2.65625
3
/* source: a, b, c subs1: 0, 1 | subs2: a, b, c | subs3: z output: 0, 1, a, b, c, z - switchMap subscribe to the values emitted for source and starts to emit values when the before subs ends */ import { fromEvent, Observable } from 'rxjs'; import { debounceTime, map, pluck, mergeAll, mergeMap, switchMap, tap } from 'rxjs/operators'; import { ajax } from 'rxjs/ajax'; import { GithubResponse } from '../interfaces/github-response.interface'; import { GithubUser } from '../interfaces/github-user.interface'; const body = document.querySelector('body'); const textInput = document.createElement('input'); body.append(textInput); // streams const input$ = fromEvent<KeyboardEvent>(textInput, 'keyup'); // GitHub /* input$.pipe( debounceTime<KeyboardEvent>(1000), pluck<KeyboardEvent, string>('target', 'value'), switchMap<string, Observable<GithubResponse>>(value => ajax.getJSON(`https://api.github.com/search/users?q=${value}`)), pluck<GithubResponse, GithubUser[]>('items') ).subscribe(console.log); */ const url = 'https://httpbin.org/delay/1?arg='; input$.pipe( pluck('target', 'value'), switchMap(text => ajax.getJSON(url+text)) ).subscribe(console.log);
0771716a5525bb5010f2e31736405471c5728a2c
TypeScript
jorge3186/jnetui
/src/services/menu.service.ts
2.953125
3
/** * @name MenuService * @author Jordan Alphonso * @created 05/01/2017 * * @description * This service will make an {@link Http} call from */ import { Injectable } from "@angular/core"; import { Http } from "@angular/http"; import { Observable } from "rxjs/Rx"; import "rxjs/add/operator/map"; import "rxjs/add/operator/catch"; /** * @public * @name MenuItem * @type {Class} * * @description * Template class that holds information retrieved from menu.json file * and all permission attributes for this menu item. */ export class MenuItem { constructor( public title: string, public url: string, public permissions: string, public submenus: MenuItem[]) {} /** * @public * @type {Function} * * @description * Splits the Menu Permissions into {@code String[]} and * returns the Array */ public getPermissions(): string[] { return this.permissions.split(','); } } @Injectable() export class MenuService { /** * @private * @type {string} * * @description * The constant path to where the menu.json file resides */ private menuUrl: string = 'app/files/menu/menu.json'; /** * @private * @type {Observable} * * @description * The asynchronous menu that will be fetched using * the {@link Http#get} method. Since this menu.service is a singleton * class, this menu item will be stored in effort to not make http calls * everytime the menu needs to be accessed. */ private menu: Observable<MenuItem[]>; private submenus: any[]; constructor(private http: Http) {} /** * @public * @type {Function} * @return {Observable} the async menu from menu.json file * * @description * This method will perform the {@link Http#get} call to our menu.json * file and return the {@link Observable} that is parsed. */ public getMenu(): Observable<MenuItem[]> { if (this.menu !== undefined) { return this.menu; } this.menu = this.http.get(this.menuUrl) .map((res) => this.updateSubMenus(<MenuItem[]>res.json())) .catch((err:any) => Observable.throw(err || 'Error retrieving menu.json file')); return this.menu; } /** * @private * @type {Function} * @param {MenuItem[]} menu - the full menu * @return {MenuItem[]} the submenus * * @description * This function will run through each menu item and update the url paths * for all the sub items based on the root path. */ private updateSubMenus(menu: MenuItem[]): MenuItem[] { let entry: string = undefined; this.submenus = new Array<any>(); for (let m of menu) { if (m.submenus !== undefined) { let updated = false; entry = m.url; for (let sub of m.submenus) { if (!updated) { m.url = m.url+sub.url; updated = true; } sub.url = entry+sub.url; } this.submenus.push({url: m.url, subs: m.submenus}); } } return menu; } /** * @public * @type {Function} * @param {string} active - the current router view * * @description * Return the submenu based on the active url * that is passed as a parameter. */ public getSubmenu(active: string): MenuItem[] { if (typeof this.submenus !== 'undefined') { for (let sub of this.submenus) { if (sub.url === active) { return sub.subs; } } } return []; } /** * @public * @type {Function} * @return {MenuItem[]} the refreshed menu * * @description * At certain points in the application, then menu needs to be refreshed. For example, * once a user logs in they may have access to additional menu items. In order for the user * to see these items we need to make another {@link Http#get} call to our menu.json file. */ public refreshMenu(): Observable<MenuItem[]> { this.menu === undefined; return this.getMenu(); } }
e1a2c088a7844eda0bc0b666dcca4133b585cc04
TypeScript
luo-677/webcode
/Stage-three/teacher/code05/typescript/code/2-学习ts/src/6-数组.ts
4.375
4
/* * 原生js * const arr = [1,2,3,4] * const arr = new Array(1,2,3,4) */ //? 1. 定义了一个元素只能为number类型的数组 const arr:number[] = [1,2,3,4] // arr.push('a') arr.push(5) //? 2. 定义了一个元素只能为string类型的数组 const arr2:string[] = ['a','b','c','d'] arr2.push('5') //? 3. number&string --- 联合类型 "|" 我们叫管道符 const arr3:(number|string|boolean)[] = [1,2,3,4,'a','b','c','d',true] //? 4. Array const arr4:Array<number> = new Array(1,2,3,4) const arr5:Array<string> = new Array('a','b','c','d') // const arr6:Array<string|number> = new Array(1,2,3,'a','b','c','d') 报错 联合类型不能这么用 //? 5. json 类型数组 const arr7:Object[] = [{id: 1,name: '手机',price: 100}] // 不推荐 const arr8:Arr8Type[] = [{id: 1,name: '手机',price: 100}] // 不推荐 // type Arr8Type = { // readonly id: number, // name: string, // price: number // } interface Arr8Type { readonly id: number, name: string, price: number }
17ece1139a7adfe89624e9f9224affd1ee4c592d
TypeScript
davorpa/curso-academiawebca-git-terminal-ts
/2-variables/variables.ts
2.90625
3
// Declarar let nombre_de_mi_variable; // Inicializar nombre_de_mi_variable = true; // Declara e Inicializa let equipo = "Real Madrid"; // Constantes const PI = 3.14; //PI = 3.16; // ERROR: Las constantes no se pueden sobrescribir
26370490b63e858b327656a2b444773ce4ab4c6c
TypeScript
gcanti/io-ts-types
/test/fromNewtype.ts
2.953125
3
import * as assert from 'assert' import * as t from 'io-ts' import { fromNewtype } from '../src' import { assertFailure, assertSuccess } from './helpers' import { Newtype, iso } from 'newtype-ts' it('fromNewtype', () => { interface Token extends Newtype<{ readonly Token: unique symbol }, string> {} const T = fromNewtype<Token>(t.string) const token = iso<Token>().wrap('sometoken') assertSuccess(T.decode('sometoken'), token) assertFailure(T, 42, ['Invalid value 42 supplied to : fromNewtype(string)']) assert.ok(T.is('sometoken')) assert.deepStrictEqual(T.encode(token), 'sometoken') const T2 = fromNewtype<Token>(t.string, 'T2') assert.strictEqual(T2.name, 'T2') interface Id extends Newtype<{ readonly Id: unique symbol }, t.Int> {} const T3 = fromNewtype<Id>(t.Int) const id = iso<Id>().wrap(123 as any) assertSuccess(T3.decode(123), id) assertFailure(T3, 'test', ['Invalid value "test" supplied to : fromNewtype(Int)']) assert.ok(T3.is(123)) assert.deepStrictEqual(T3.encode(id), 123) })
be62eb930b6fb8c692f66f5eb1fbc5076024f4a9
TypeScript
jsflow/jsflow
/src/Engine/Tracing/ForStatement.ts
2.53125
3
import { MonitorBase } from "../../MonitorBase"; import { WorkList, ValueStack } from "../../Context"; import { Task } from "../Task"; import { Label, lub } from "../../Label"; import { GetValue } from "../../GetValue"; import { ToBoolean } from "../../Conversion/ToBoolean"; import * as estree from 'estree'; import { StackMarker } from "../../Stack"; declare var monitor: MonitorBase; let emptyLabel = 'default'; // default is a reserved word so no actual label can be named default interface LabeledForStatement extends estree.ForStatement { labelset?: Set<string>; } class ResetValueStack extends Task { targetSize : number constructor(targetSize: number) { super(); } Execute(wl: WorkList, vs: ValueStack): void { while(vs.size() > this.targetSize) { vs.pop(); } } } let MySet = Set; // ------------------------------------------------------------ export function forStatement( node: LabeledForStatement, wl: WorkList, vs: ValueStack ): void { let c = monitor.context; let ip = wl.top(); let lmap = c.labels.labelmap; if (node.init) { ip.then(node.init); ip.then(new ResetValueStack(vs.size())); } if (!node.labelset) { node.labelset = new MySet([]); } node.labelset.add(emptyLabel); let outerEmptyLabelData = lmap[emptyLabel]; lmap[emptyLabel] = { label: c.effectivePC, pcmarker: c.pcStack.marker() }; let contextLabel = lmap[emptyLabel].label; c.pushPC(contextLabel); ip.then(new ForStatementMain(node)); ip.then(new ForStatementEnd(outerEmptyLabelData)); } // --- class ForStatementMain extends Task { node: LabeledForStatement; choose: ForStatementChoose; execute: ForStatementExecute; update: ForStatementUpdate; constructor(node: LabeledForStatement) { super(Task.runfor_continue_break); this.node = node; this.execute = new ForStatementExecute(node, this); this.choose = new ForStatementChoose(node, this); this.update = new ForStatementUpdate(node); } Execute(wl: WorkList, vs: ValueStack): void { let c = monitor.context; let ip = wl.top(); let result = c.result; if (result.type === 'break' && this.node.labelset!.has(result.target)) { result.type = 'normal'; result.target = null; return; } if (result.type !== 'continue' || !this.node.labelset!.has(result.target)) { if (result.type !== 'normal') { return; } } result.type = 'normal'; result.target = null; if (this.node.test) { ip.then(this.node.test); ip.then(this.choose); } else { ip.then(this.execute); } } } // --- class ForStatementChoose extends Task { node: LabeledForStatement; main: ForStatementMain; constructor(node: LabeledForStatement, main: ForStatementMain) { super(Task.runfor_continue); this.node = node; this.main = main; } Execute(wl: WorkList, vs: ValueStack): void { let ip = wl.top(); let c = monitor.context; let result = c.result; //@ts-ignore STACK let cond = GetValue(vs.pop()); let condb = ToBoolean(cond); c.labels.pc = lub(c.labels.pc, condb.label); if (!condb.value) { result.type = 'normal'; result.target = null; return; } ip.then(this.main.execute); } } class ForStatementExecute extends Task { node: LabeledForStatement; main: ForStatementMain; constructor(node: LabeledForStatement, main: ForStatementMain) { super(); this.node = node; this.main = main; } Execute(wl: WorkList, vs: ValueStack): void { let ip = wl.top(); ip.then(this.node.body); ip.then(this.main.update); ip.then(this.main); } } class ForStatementUpdate extends Task { node: LabeledForStatement; constructor(node: LabeledForStatement) { super(Task.runfor_continue); this.node = node; } Execute(wl: WorkList, vs: ValueStack): void { let ip = wl.top(); let c = monitor.context; let result = c.result; if (result.type !== 'continue' || !this.node.labelset!.has(result.target)) { if (result.type !== 'normal') { return; } } result.type = 'normal'; result.target = null; if (this.node.update) { ip.then(this.node.update); ip.then(new ResetValueStack(vs.size())); } } } // forStatementeEnd class ForStatementEnd extends Task { outerEmptyLabelData: { label: Label, pcmarker: StackMarker }; constructor(outerEmptyLabelData: { label: Label, pcmarker: StackMarker }) { super(); this.outerEmptyLabelData = outerEmptyLabelData; } Execute(wl: WorkList, vs: ValueStack): void { let c = monitor.context; c.labels.labelmap[emptyLabel] = this.outerEmptyLabelData; c.popPC(); } }
6b9f76c3ea8dfbc24ccc7f56127a0f45053a86fa
TypeScript
Sayuri/parking
/api/src/entities/car.entity.ts
2.515625
3
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm'; import { User } from './user.entity'; @Entity() export class Car { @PrimaryGeneratedColumn() id: number; @Column() number: string; @Column() brand: string; @Column() model: string; @ManyToOne(type => User, user => user.bookings) owner: User; }
48f6c33a43f5447538dd543be15b51e37ec0818f
TypeScript
hal0x2328/neo-one
/packages/neo-one-smart-contract-codegen/src/types/genConstantFunction.ts
2.53125
3
import { ABIFunction } from '@neo-one/client-common'; import { toTypeScriptType } from '../utils'; import { genFunctionParameters } from './genFunctionParameters'; export const genConstantFunction = (abi: ABIFunction): string => { const paramss = genFunctionParameters(abi); if (paramss.length === 1) { return `(${paramss[0]}) => Promise<${toTypeScriptType(abi.returnType, { isParameter: false })}>;`; } return `{ ${paramss .map((params) => `(${params}): Promise<${toTypeScriptType(abi.returnType, { isParameter: false })}>;`) .join(' \n')} }`; };
6d0f5a7af93ce47a7194c4364e9def75dd58e20d
TypeScript
hrenx/vscode-easymotion
/src/command.ts
2.875
3
import * as vscode from 'vscode'; class Position { line = 0; offset = 0; combo = ''; } function isCharWhitespace(c: number) { // Space, carriage return, line feed, tab return c === 32 || c === 13 || c === 10 || c === 9; } function isCharNumber(c: number) { return c >= 48 && c <= 57; } function isCharUpperAlpha(c: number) { return c >= 65 && c <= 90; } function isCharLowerAlpha(c: number) { return c >= 97 && c <= 122; } function isCharAlpha(c: number) { return isCharUpperAlpha(c) || isCharLowerAlpha(c); } function isCharUnderscore(c: number) { return c === 95; } function isValidIdentifierCharacter(c: number) { return isCharAlpha(c) || isCharNumber(c) || isCharUnderscore(c); } function findCandidatePositions(editor: vscode.TextEditor, context: ActiveCommandContext, config: Configuration) { const positions : Position[] = []; for(const range of editor.visibleRanges) { for(let lineIndex = range.start.line; lineIndex <= range.end.line; lineIndex++) { const line = editor.document.lineAt(lineIndex); let didFindAnyWords = false; let currentIdentifierStart : number | null = null; for(let i = line.firstNonWhitespaceCharacterIndex; i < line.text.length; ++i) { const c = line.text.charCodeAt(i); if (currentIdentifierStart === null) { if (isCharWhitespace(c)) continue; if (isValidIdentifierCharacter(c)) { didFindAnyWords = true; currentIdentifierStart = i; } // TODO: Should we have a separate, symbols-only mode? /* else { const pos = new Position(); pos.line = lineIndex; pos.offset = i; positions.push(pos); }*/ } else if (!isValidIdentifierCharacter(c)) { const pos = new Position(); pos.line = lineIndex; pos.offset = context.usingEndOfWord ? i : currentIdentifierStart; // Don't bother pushing the position if it's the same as the cursor if (!(pos.line === editor.selection.start.line && pos.offset === editor.selection.start.character)) { positions.push(pos); } currentIdentifierStart = null; } } if (currentIdentifierStart) { const pos = new Position(); pos.line = lineIndex; pos.offset = currentIdentifierStart; // Don't bother pushing the position if it's the same as the cursor if (!(pos.line === editor.selection.start.line && pos.offset === editor.selection.start.character)) { positions.push(pos); } currentIdentifierStart = null; } // If there were no words in the line and the line is non-empty, then add it as a jump position if (!didFindAnyWords && config.AllowJumpingToWordlessLine) { const pos = new Position(); pos.line = lineIndex; pos.offset = line.text.length; // Don't bother pushing the position if it's the same as the cursor if (!(pos.line === editor.selection.start.line && pos.offset === editor.selection.start.character)) { positions.push(pos); } } } } // Tuned these keys by hands based on an American English keyboard. // This is a good candidate for configuration so that we can better // support other keyboard layouts. const singleCharacterSet = 'fjrudkeislwoaqghtyp'; const doubleCharacterSet = 'vncmxzb,;\'[*+-'; const selection = editor.selection; const sorted = positions.sort((a, b)=> { if (a.line === b.line) { const aDist = Math.abs(a.offset - selection.start.character); const bDist = Math.abs(b.offset - selection.start.character); if (aDist < bDist) return -1; if (bDist < aDist) return 1; return 0; } const aDist = Math.abs(a.line - selection.start.line); const bDist = Math.abs(b.line - selection.start.line); if (aDist < bDist) return -1; if (bDist < aDist) return 1; return 0; }); let singleCharIndex = 0; let doubleCharIndex = -1; for(let i = 0; (i < positions.length) && (doubleCharIndex < doubleCharacterSet.length); ++i) { let combo = ''; if (doubleCharIndex >= 0) { combo += doubleCharacterSet.charAt(doubleCharIndex); } combo += singleCharacterSet.charAt(singleCharIndex); ++singleCharIndex; if (singleCharIndex >= singleCharacterSet.length) { singleCharIndex = 0; ++doubleCharIndex; } positions[i].combo = combo; } return positions; } function clearDecorations(config: Configuration, editor: vscode.TextEditor) { editor.setDecorations(config.UnfocusedDecoration, []); editor.setDecorations(config.Decoration, []); } function decoratePositions(config: Configuration, context: ActiveCommandContext, editor: vscode.TextEditor, positions: Position[]) { const backgroundDecorations: vscode.DecorationOptions[] = []; backgroundDecorations.push ( { range: new vscode.Range(0, 0, editor.document.lineCount - 1, editor.document.lineAt(editor.document.lineCount - 1).text.length) } ); const decorationsArray: vscode.DecorationOptions[] = []; const colors = ['#ff5555', 'yellow', 'lime', 'magenta']; for(let i = 0; i < positions.length; i++) { const pos = positions[i]; const valueToSub = 1 + (context.keyMelody.length); // TODO: Maybe toggle this with some configuration option? const textToDraw = pos.combo.substr(context.keyMelody.length, pos.combo.length - context.keyMelody.length); // const textToDraw = pos.combo; const tgColor = colors[(pos.combo.length - valueToSub) % colors.length]; const styling = { border: '0 0 0 2px', borderColor: '#cccccc', fontWeight: 'bold', contentText: textToDraw, color: tgColor, width: '0px' }; decorationsArray.push({ range: new vscode.Range(pos.line, pos.offset, pos.line, pos.offset + textToDraw.length), renderOptions: { dark: { before: styling }, light: { before: styling } } }); } editor.setDecorations(config.UnfocusedDecoration, backgroundDecorations); editor.setDecorations(config.Decoration, decorationsArray); } export class Configuration { constructor(unfocused: vscode.TextEditorDecorationType, decoration: vscode.TextEditorDecorationType, allowJumpToWordlessLine: boolean) { this.UnfocusedDecoration = unfocused; this.Decoration = decoration; this.AllowJumpingToWordlessLine = allowJumpToWordlessLine; } UnfocusedDecoration: vscode.TextEditorDecorationType; Decoration: vscode.TextEditorDecorationType; AllowJumpingToWordlessLine: boolean; } export class ActiveCommandContext { cancel() { if (this.keyPromiseResolver) { this.keyPromiseResolver(null); } } usingEndOfWord = false; keyPromiseResolver: ((pressed: string | number | null)=>void) | null = null; keyMelody = ''; } export default async function processCommand(editor: vscode.TextEditor, config: Configuration, context: ActiveCommandContext) { if (editor) { const start = new Date(); const positions = findCandidatePositions(editor, context, config); console.log(`${(new Date().getTime() - start.getTime()) / 1000} seconds to generate candidate positions, ${positions.length} found`); let filteredPositions = positions; do { // Decorate clearDecorations(config, editor); decoratePositions(config, context, editor, filteredPositions); // Get a key const key = await new Promise<string | number | null>((resolve, reject)=> { context.keyPromiseResolver = resolve; }); if (key === null) { filteredPositions = []; break; } let found = false; // If backspace... if (key === -1) { if (context.keyMelody.length > 0) { found = true; context.keyMelody = context.keyMelody.substring(0, context.keyMelody.length - 1); } } else { // Add key to melody context.keyMelody += key; for(const pos of filteredPositions) { if (pos.combo.startsWith(context.keyMelody.toLowerCase())) { found = true; } } } if (found) { if (context.keyMelody.length > 0) { filteredPositions = positions.filter((v)=>v.combo.startsWith(context.keyMelody.toLowerCase())); } else { filteredPositions = positions; } } else { context.keyMelody = context.keyMelody.substring(0, context.keyMelody.length - 1); } } while(filteredPositions.length > 1); clearDecorations(config, editor); if (filteredPositions.length === 1) { const found = filteredPositions[0]; let selection; if (isCharUpperAlpha(context.keyMelody.charCodeAt(context.keyMelody.length - 1))) { // TODO: Do we want fancier logic here? const startLine = editor.selection.start.line; const startChar = editor.selection.start.character; const endLine = found.line; const endChar = found.offset; selection = new vscode.Selection(startLine, startChar, endLine, endChar); } else { selection = new vscode.Selection(found.line, found.offset, found.line, found.offset); } editor.selection = selection; } } else { // TODO: Warn that a text editor needs to be active } }
632affa2b065b99a435df51607a59a0de7ba6af2
TypeScript
keyur2714/E_4_Angular_8
/DirectiveDemo/src/app/app.component.ts
2.515625
3
import { Component, ViewChild, OnInit, ElementRef } from '@angular/core'; import { MyStyleDirective } from './my-style.directive'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit{ title = 'DirectiveDemo'; @ViewChild(MyStyleDirective,{static : true}) myStyleDirective : MyStyleDirective; @ViewChild("p1",{static : true}) p1 : ElementRef; @ViewChild("h1",{static : true}) h1 : ElementRef; age : number = 18; ngOnInit(){ this.myStyleDirective.border = '5px solid green'; } changeStyle(color : string) : void{ this.myStyleDirective.changeStyle(color,'45px',this.h1); } }
2b83a5b017d01f6cc0148efc031e475aa64b0d7c
TypeScript
freenowtech/react-polygon-editor
/src/PolygonDraw/reducer.ts
2.671875
3
import undoable, { excludeAction } from 'redux-undo'; import { Actions, SELECT_POINTS, ADD_POINT_TO_SELECTION, REMOVE_POINT_FROM_SELECTION, DESELECT_ALL_POINTS, SELECT_ALL_POINTS, MOVE_SELECTED_POINTS, DELETE_POLYGON_POINTS, ADD_POINT, ADD_POINT_TO_EDGE, CHANGE_POLYGON, SET_POLYGON, } from './actions'; import { Coordinate } from 'types'; import { movePolygonCoordinates, removeSelectedPoints } from '../helpers'; export interface PolygonEditState { activeIndex: number; polygons: Coordinate[][]; selection: Set<number>; } export const polygonEditReducer = (state: PolygonEditState, action: Actions): PolygonEditState => { switch (action.type) { /////////////////////////////////////////////////////////////////////////////////// /// CHANGE POLYGON CASES /// /////////////////////////////////////////////////////////////////////////////////// case CHANGE_POLYGON: { return { ...state, polygons: [...action.payload], }; } case SET_POLYGON: { return { ...state, polygons: [ ...state.polygons.slice(0, state.activeIndex), action.payload, ...state.polygons.slice(state.activeIndex + 1), ], selection: new Set(), }; } /////////////////////////////////////////////////////////////////////////////////// /// MOVE COORDINATES CASES /// /////////////////////////////////////////////////////////////////////////////////// case MOVE_SELECTED_POINTS: { return { ...state, polygons: [ ...state.polygons.slice(0, state.activeIndex), movePolygonCoordinates(state.polygons[state.activeIndex], state.selection, action.payload), ...state.polygons.slice(state.activeIndex + 1), ], }; } /////////////////////////////////////////////////////////////////////////////////// /// SELECTION CASES /// /////////////////////////////////////////////////////////////////////////////////// case SELECT_POINTS: { return { ...state, selection: new Set(action.payload), }; } case ADD_POINT_TO_SELECTION: { return { ...state, selection: new Set([...state.selection.values(), ...action.payload]), }; } case REMOVE_POINT_FROM_SELECTION: { const selection = new Set(state.selection); selection.delete(action.payload); return { ...state, selection, }; } case SELECT_ALL_POINTS: { return { ...state, selection: new Set(state.polygons[state.activeIndex].map((_, i) => i)), }; } case DESELECT_ALL_POINTS: { return { ...state, selection: new Set(), }; } /////////////////////////////////////////////////////////////////////////////////// /// DELETE POINTS CASE /// /////////////////////////////////////////////////////////////////////////////////// case DELETE_POLYGON_POINTS: { return { ...state, polygons: [ ...state.polygons.slice(0, state.activeIndex), removeSelectedPoints(state.polygons[state.activeIndex], state.selection), ...state.polygons.slice(state.activeIndex + 1), ], selection: new Set(), }; } /////////////////////////////////////////////////////////////////////////////////// /// ADD POINT CASE /// /////////////////////////////////////////////////////////////////////////////////// case ADD_POINT: { return { ...state, polygons: [ ...state.polygons.slice(0, state.activeIndex), [...state.polygons[state.activeIndex], action.payload], ...state.polygons.slice(state.activeIndex + 1), ], selection: new Set([state.polygons.length]), }; } case ADD_POINT_TO_EDGE: { return { ...state, polygons: [ ...state.polygons.slice(0, state.activeIndex), [ ...state.polygons[state.activeIndex].slice(0, action.payload.index + 1), action.payload.coordinate, ...state.polygons[state.activeIndex].slice(action.payload.index + 1), ], ...state.polygons.slice(state.activeIndex + 1), ], selection: new Set([action.payload.index]), }; } default: { return state; } } }; export const EDIT_HISTORY_LIMIT = 20; export const undoablePolygonEditReducer = undoable(polygonEditReducer, { groupBy: (action, state, history) => { if (action.type === MOVE_SELECTED_POINTS) { return `${action.type}-${[...state.selection].sort().join('-')}`; } return null; }, filter: excludeAction([ SELECT_POINTS, ADD_POINT_TO_SELECTION, REMOVE_POINT_FROM_SELECTION, SELECT_ALL_POINTS, DESELECT_ALL_POINTS, CHANGE_POLYGON, ]), // see https://github.com/omnidan/redux-undo/issues/6#issuecomment-142089793 limit: EDIT_HISTORY_LIMIT + 1, debug: false, syncFilter: true, });
777bc2918914bc7ec81fb906581bf696b9d3783a
TypeScript
taskie/matome
/src/commons/ts-promisify.ts
3.0625
3
export type AsyncFunction0<O1, O2, O3, O4, O5, O6>= { (callback?: (o1: O1, o2: O2, o3: O3, o4: O4, o5: O5, o6: O6)=>void): void; }; export type AsyncFunction1<I, O1, O2, O3, O4, O5, O6>= { (i: I, callback?: (o1: O1, o2: O2, o3: O3, o4: O4, o5: O5, o6: O6)=>void): void; }; export type AsyncFunction2<I1, I2, O1, O2, O3, O4, O5, O6>= { (i1: I1, i2: I2, callback?: (o1: O1, o2: O2, o3: O3, o4: O4, o5: O5, o6: O6)=>void): void; }; export type AsyncFunction3<I1, I2, I3, O1, O2, O3, O4, O5, O6> = { (i1: I1, i2: I2, i3: I3, callback?: (o1: O1, o2: O2, o3: O3, o4: O4, o5: O5, o6: O6) => void): void; }; export type AsyncFunction4<I1, I2, I3, I4, O1, O2, O3, O4, O5, O6> = { (i1: I1, i2: I2, i3: I3, i4: I4, callback?: (o1: O1, o2: O2, o3: O3, o4: O4, o5: O5, o6: O6) => void): void; }; export function typed<O1,O2,O3,O4,O5,O6>(af:AsyncFunction0<O1,O2,O3,O4,O5,O6>):()=>Promise<[O1,O2,O3,O4,O5,O6]>; export function typed<O1,O2,O3,O4,O5,O6>(c:Object,af:AsyncFunction0<O1,O2,O3,O4,O5,O6>):()=>Promise<[O1,O2,O3,O4,O5,O6]>; export function typed<I,O1,O2,O3,O4,O5,O6>(af:AsyncFunction1<I,O1,O2,O3,O4,O5,O6>):(i:I)=>Promise<[O1,O2,O3,O4,O5,O6]>; export function typed<I,O1,O2,O3,O4,O5,O6>(c:Object,af:AsyncFunction1<I,O1,O2,O3,O4,O5,O6>):(i:I)=>Promise<[O1,O2,O3,O4,O5,O6]>; export function typed<I1,I2,O1,O2,O3,O4,O5,O6>(af:AsyncFunction2<I1,I2,O1,O2,O3,O4,O5,O6>):(i1:I1,i2:I2)=>Promise<[O1,O2,O3,O3,O4,O5,O6]>; export function typed<I1,I2,O1,O2,O3,O4,O5,O6>(c:Object,af:AsyncFunction2<I1,I2,O1,O2,O3,O4,O5,O6>):(i1:I1,i2:I2)=>Promise<[O1,O2,O3,O4,O5,O6]>; export function typed<I1,I2,I3,O1,O2,O3,O4,O5,O6>(af:AsyncFunction3<I1,I2,I3,O1,O2,O3,O4,O5,O6>):(i1:I1,i2:I2,i3:I3)=>Promise<[O1,O2,O3,O4,O5,O6]>; export function typed<I1,I2,I3,O1,O2,O3,O4,O5,O6>(c:Object,af:AsyncFunction3<I1,I2,I3,O1,O2,O3,O4,O5,O6>):(i1:I1,i2:I2,i3:I3)=>Promise<[O1,O2,O3,O4,O5,O6]>; export function typed<I1,I2,I3,I4,O1,O2,O3,O4,O5,O6>(af:AsyncFunction4<I1,I2,I3,I4,O1,O2,O3,O4,O5,O6>):(i1:I1,i2:I2,i3:I3,i4:I4)=>Promise<[O1,O2,O3,O4,O5,O6]>; export function typed<I1,I2,I3,I4,O1,O2,O3,O4,O5,O6>(c:Object,af:AsyncFunction4<I1,I2,I3,I4,O1,O2,O3,O4,O5,O6>):(i1:I1,i2:I2,i3:I3,i4:I4)=>Promise<[O1,O2,O3,O4,O5,O6]>; export function typed(...inputs: any[]): any { return __generic__(inputs); } export function generic(context: Object, asyncFunction: Function): (...inputs: any[]) => Promise<any[]>; export function generic(asyncFunction: Function): (...inputs: any[]) => Promise<any[]>; export function generic(...inputs: any[]): Function { return __generic__(inputs); } function __generic__(inputs: any[]): Function{ let context: Object; let asyncFunction: Function; if( inputs.length == 2 ){ context= inputs[0]; asyncFunction= inputs[1]; }else{ context= {}; asyncFunction= inputs[0]; } return (...inputs: any[]) => { return new Promise<any[]>(resolve => { asyncFunction.apply(context, inputs.concat([(...outputs: any[]) => resolve(outputs) ])); }); }; }
d92b97d305cfb9030e8a435914e09d16b5ed987f
TypeScript
ChrisNotDefined/ClasePokemons
/src/excercises/05-Destructuring.ts
3.46875
3
// Destructuring interface Details { author: string; releaseYear: number; } interface MusicPlayer { volume: number; second: number; track: string; details: Details; } const player: MusicPlayer = { volume: 50, second: 36, track: "Driver", details: { author: "Pendulum", releaseYear: 2020, }, }; const author = "Knife Party"; const { track, volume, second, details } = player; const { author: detailedAuthor, releaseYear } = details; console.log("Current volume: ", volume); console.log("Current second: ", second); console.log("Current track: ", track); console.log("Track author: ", detailedAuthor); console.log("Track realease year: ", releaseYear); // Destructuring arrays const pokemon: string[] = ["Pikachu", "Charizard", "Charmander"]; const [first, secon, third, ...rest] = pokemon; console.log(first); console.log(secon); console.log(rest);
04e0638ccaaa1710ed0c6bebc44725f99a8dae3a
TypeScript
didierdemoniere/pokeboule
/src/state-management/modules/game.ts
3.015625
3
// actions types const START_GAME = "START_GAME" as "START_GAME"; // action creators export const actionCreators = { startGame: () => ({ type: START_GAME }) }; // reducer export const reducer = function(state = false, action: { type: "START_GAME" }) { switch (action.type) { case START_GAME: return true; default: return state; } };
e3604ca75d9fa68ec2389f58844d9359047b8f3c
TypeScript
jaaamesey/hscenglishbot
/scripts/imagemaker.ts
2.71875
3
const misc = require('../misclib') const fs = require('fs') const memeAmount = 105 var loadedImageData; //var loadedImage = new Image(); drawRandomImage() var textthing = "Compose a piece of writing which persuasively explores the notion of belonging. | | Use the item below as the central element for your writing." var widththing = 600 var Canvas = require('canvas-prebuilt') , ImageThing = Canvas.Image , canvas = new Canvas(800, 800) , ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.rect(0, 0, 1501, 1001); ctx.fillStyle = "white"; ctx.fill(); ctx.font = '12px Times New Roman'; //LOAD IMAGE(S) var img = new Canvas.Image; function randimgpath() { return ( './images/' + 'meme (' + (1 + Math.floor(Math.random() * memeAmount)).toString() + ').PNG' ); } const datatype = "data:image/png;base64,"; var imgbase64; var imagesrcoutput; function drawRandomImage() { fs.readFile(( './images/' + 'meme (' + (1 + Math.floor(Math.random() * memeAmount)).toString() + ').PNG' ), //after loading function(err, data) { if (err) { throw err; } else { console.log('Successfully loaded image.') } //write loadedImageData = data; // loadedImage.src = "data:image/png;base64"; // Create a new Image // img.src = data; console.log(data); function base64_encode(file) { // read binary data var bitmap = fs.readFileSync(file); // convert binary data to base64 encoded string return new Buffer(bitmap).toString('base64'); } imgbase64 = base64_encode(randimgpath()); console.log(imgbase64) imagesrcoutput = datatype + imgbase64; img.src = imagesrcoutput; var aspectRatio = img.width / img.height; console.log(aspectRatio) //actually draw image //ctx.drawImage(img, 72, 222); ctx.drawImage(img, 72, 222, canvas.width - 250, (canvas.height - 222) / aspectRatio ); // destination rectangle console.log(img.src) drawText() }); } function drawText() { function wrap() { const drawx = 72; const drawy = 72; var text = textthing, fontSize = 20, width = widththing, lines = [], line = '', lineTest = '', words = text.split(' '), currentY = 0; ctx.font = fontSize + 'px Times New Roman'; for (var i = 0, len = words.length; i < len; i++) { if (words[i] != "|") { lineTest = line + words[i] + ' '; } // Check total width of line or last word if (ctx.measureText(lineTest).width > width || words[i] == "|") { // Calculate the new height currentY = lines.length * fontSize + fontSize; // Record and reset the current line lines.push({ text: line, height: currentY }); line = words[i] + ' '; } else { line = lineTest; } } // Catch last line in-case something is left over if (line.length > 0) { currentY = lines.length * fontSize + fontSize; lines.push({ text: line.trim(), height: currentY }); } // Visually output text ctx.fillStyle = "black"; for (var i = 0, len = lines.length; i < len; i++) { ctx.fillText(lines[i].text.replace('|', '').trim(), drawx + 0, drawy + lines[i].height); } //drawRandomImage(); } wrap(); misc.notif("Canvas established"); // ctx.drawImage(img, 2, 2); fs.writeFile('bepis.png', canvas.toBuffer()); } //// // // //// // // //// // // //Wrapping // //
5482b2fd4d09295861e97a669eec524c40d48f56
TypeScript
flickswipe/app
/predict/src/modules/track-user-settings/events/listeners/user-updated-setting.ts
2.59375
3
import { Subjects, Listener, UserUpdatedSettingEvent, } from "@flickswipe/common"; import { Message } from "node-nats-streaming"; import { createSuggestions } from "../../../generate-suggestions/generate-suggestions"; import { Setting } from "../../models/setting"; const { QUEUE_GROUP_NAME } = process.env; /** * Listen to `UserUpdatedSetting` events */ export class UserUpdatedSettingListener extends Listener<UserUpdatedSettingEvent> { // set listener subject subject: Subjects.UserUpdatedSetting = Subjects.UserUpdatedSetting; // set queue group name queueGroupName = QUEUE_GROUP_NAME; /** * @param data message data * @param msg message handler */ async onMessage( data: UserUpdatedSettingEvent["data"], msg: Message ): Promise<void> { // update database await updateUserSettings(data); // create suggestions const userId = data.user; await createSuggestions(userId, true); msg.ack(); } } /** * @param data data to update with * @returns {boolean} true if message should be acked */ async function updateUserSettings( data: UserUpdatedSettingEvent["data"] ): Promise<void> { const { settingType, user, value, updatedAt } = data; const existingDoc = await Setting.findOne({ settingType, user }); if (existingDoc) { if (existingDoc.updatedAt > updatedAt) { return; } // update existingDoc.value = value; await existingDoc.save(); } else { // create await Setting.build({ settingType, user, value }).save(); } console.log(`Updated ${settingType} setting for user #${user}`, value); }
10e917d9c202cc312ff8d1b6eed6355314e1137b
TypeScript
ScienceOfComputerProgramming/SCICO-D-20-00066
/src/main/frontend/src/app/models/varListData.ts
3.140625
3
/** * The information about the highlightable variable. */ export interface VarInfo { dataid: string; className: string; methodName: string; var: string; linenum: string; inst: String; count: number; valueList: ValueInfo[]; } /** * The information about the values of variable . */ export interface ValueInfo { data: string; timestamp: string; thread: string; } /** * The all variable information in the project. */ export interface VarListJsonData { recentdata: VarInfo[]; } /** * The model of project variable information */ export class VarListDataModel { private _data: VarListJsonData; constructor(data: VarListJsonData) { this._data = data; } /** * Return the variable information of the specified classname */ getDataOfFile(file: string): VarInfo[] { return this._data.recentdata.filter((x) => x.className === file); } }